WIP Readme.

This commit is contained in:
mike-thompson-day8 2014-12-12 22:50:39 +11:00
parent 84b25cab64
commit 55044abc31
1 changed files with 100 additions and 68 deletions

168
README.md
View File

@ -13,10 +13,10 @@ it is instead a functional RACES framework - Reactive-Atom Component Event Subsc
Nothing about re-frame is the slightest bit original or clever.
You'll find no ingenious use of functional zippers, transducers or core.async.
I claim is a good thing (although, for the record, one day I'd love to develop
This is a good thing (although, for the record, one day I'd love to develop
something original and clever).
Using re-frame, you WILL be able to break your application code into distinct pieces.
Using re-frame, you will be able to break your application code into distinct pieces.
Each of these pieces can be easily described, understood and tested independently.
These pieces will (mostly) be pure functions.
@ -24,14 +24,14 @@ At small scale, any framework seems like pesky overhead. The
explanatory examples in here are small scale, so you'll need to
squint a little to see the benefit.
## Shaping Beliefs
## Core Beliefs
First, above all we believe in the one true [Dan Holmsand] (creator of reagent),
and his divine instrument the `ratom`. We genuflect towards Sweden once a day.
Second, because paradigm is worth 80 points of IQ, you'll only
Second, we believe that [FRP] is a honking great idea. You'll only
really "get" Reagent once you view it as an [FRP] library, and not simply a
ReactJS wrapper. To put that another way, we think that Reagent is closer in
ReactJS wrapper. To put that another way, we think that Reagent at its best is closer in
nature to [Hoplon] or [Elm] than it is [OM]. This wasn't obvious to us initially - we
knew we liked reagent, but it took a while for the penny to drop as to why.
@ -39,16 +39,20 @@ Finally, we believe in one way data flow. We don't like read/write `cursors` wh
allow for the two way flow of data. re-frame does implement two data way flow, but it
ues two, one-way flows to do it.
## FRP
If you aren't familiar with FRP, or even if you think you are, I'd recomend reading [this FRP backgrounder](https://gist.github.com/staltz/868e7e9bc2a7b8c1f754).
## The Parts
To explain re-frame, we'll now incrementally
develop a diagram. We'll explain each part as it is added in.
##### The Big Ratom
develop a diagram. We'll explain each part as it is added.
<blockquote class="twitter-tweet" lang="en"><p>Well-formed Data at rest is as close to perfection in programming as it gets. All the crap that had to happen to put it there however...</p>&mdash; Fogus (@fogus) <a href="https://twitter.com/fogus/status/454582953067438080">April 11, 2014</a></blockquote>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
##### The Big Ratom
Our re-frame diagram starts with the "well formed data at rest" bit:
```
app-db
@ -58,61 +62,64 @@ So, re-frame says that you should put your data into one place (probably one dir
big atom) which we'll call `app-db`. Structure the data in that place, of course.
Now, this advice is not the slightest bit controversial for 'real' databases, right?
You'd happily put all your well formed data into Postgres or mysql. But within an app (in memory),
it is different. If you have
You'd happily put all your well formed data into Postgres or mysql. But within a running application (in memory), it is different. If you have
background in OO, this data-in-one-place is a hard one to swallow. You've
spent your life breaking systems into pieces, organised around behaviour and trying
to hide the data. I still wake up in a sweat some nights thinking about all
that clojure data lying around exposed and passive.
But, as @Fogus says, data is the easy bit.
But, as @Fogus said above, data is the easy bit.
From here on, we'll assume `app-db` looks like this:
```
(def app-db (reagent/atom {})) ;; a reagent atom, containing a map
```
Although it is an atom, I'd encourage you to actively think about it as an (in-memory) database.
Although it is a reagent atom (ratom), I'd encourage you to actively think about
it as an (in-memory) database.
It will contain structured data (perhaps with a formal [Prismatic Schema] spec).
You will need to query that data. You will perform CRUD
and other transformations on it. You'll often want to transact on this
database atomically, etc. So "in-memory database"
seems a more useful paradigm than plain old atom.
Finally, a clarification: `app-db` doesn't actually have to be a ratom containing
Finally, a clarification: `app-db` doesn't actually have to be a reagent/atom containing
a map. In theory, re-frame
imposes no requirement here. It could be a [datascript] database. But as you'll see it
imposes no requirement here. It could be a [datascript] database. But, as you'll see, it
would have to be a "reactive datastore" of some description (an
"observable" datastore -- one that can tell you when it has changed).
##### Magic Ratoms
Reagent provides a `ratom` and a `reaction`. These are the two key building blocks.
Reagent provides a `ratom` (reagent atom) and a `reaction`. These are the two key building blocks.
`ratoms` are like normal ClojureScript atoms. You can swap! and reset! them, watch them, etc.
`ratoms` are like normal ClojureScript atoms. You can `swap!` and `reset!` them, `watch` them, etc.
`reactions` act a bit like functions. Its a macro which wraps some "computation" (forms?) and returns
a ratom containing the result of that computation.
`reactions` act a bit like functions. Its a macro which wraps some `computation` (some forms?) and returns a `ratom` containing the result of that` computation`.
The magic bit is that `reaction` will automatically rerun the computation whenever the "inputs" change, and it will reset! the ratom to the new value.
The magic bit is that `reaction` will automatically rerun the `computation` whenever the computation's "inputs" change, and it will `reset!` the originally returned `ratom` to the newly conputed value.
Okay, enough words ...
```clojure
(ns example1
(:require-macros [reagent.ratom :refer [reaction]])
(:require
[reagent.core :as r]))
(:require [reagent.core :as r]))
(def db-app (r/atom {:a 1})) ;; our base ratom -- think of it like our app-db
(def db-app (r/atom {:a 1})) ;; our base ratom
(def ratom2 (reaction {:b (:a @db-app)})) ;; notice use of "reaction" which wraps some computation
(def ratom3 (reaction (cond = (:a @db-app) ;; notice use of "reaction" which wraps some computation
(def ratom2 (reaction {:b (:a @db-app)})) ;; reaction wraps a computation
(def ratom3 (reaction (cond = (:a @db-app) ;; reaction wraps another computation
0 "World"
1 "Hello")))
1 "Hello")))
(println @ratom2) ;; ==> {:b 1} ;; contains a computed result. Based on values in 'db-app'
(println @ratom3) ;; ==> "Hello" ;; contains a computed result. Based on values in 'db-app'
;; notice that both the computations above involve dereferencing db-app
(reset! db-app {:a 0}) ;; this change "flows" (triggers) reactive computations for ratom2 and ratom3
(println @ratom2) ;; ==> {:b 1} ;; a computed result. Based on values in 'db-app'
(println @ratom3) ;; ==> "Hello" ;; a computed result. Based on values in 'db-app'
(reset! db-app {:a 0}) ;; this change "flows" (triggers) reactive computations
;; both ratom2 and ratom3 will change.
(println @ratom2) ;; ==> {:b 0} ;; ratom2 is {:b (:a @ratom)}
(println @ratom3) ;; ==> "World" ;; ratom3 is automatically updated too.
@ -122,16 +129,22 @@ The magic bit is that `reaction` will automatically rerun the computation whenev
(dispose ratom3)
```
So `reaction` wraps a computation (acts like a function), and it returns a `ratom` which will then be `reset!` whenever its "inputs" change.
So, `reaction` wraps a computation, and returns a `ratom`. Whenever the "inputs" to the computation change, the computation is rerun and the returned ratom is `reset!` with the new value. The "inputs" to the computation are any ratoms which are dereferenced duration execution of the computation.
The "inputs" are any ratoms which are dereferenced within the computation. So, it "watches" (observes) an ratom which is dereferenced in the body of the computation, and if any of those ratoms change, it reruns the computation.
While the mechanics are different, this is similar in intent to `lift' in [Elm].
Using the combination of these two building blocks you can create reactive functions
So, in FRP terms, a `reaction` will produce a "stream" of values, accessible via the ratom it returns.
I'm going to repeat that, because it is important. A `reaction` wraps a computaion and returns a `ratom`. Any `ratom` can produce a stream of changes (they are observable). The is effectively a "stream"
So, ratom and reaction are the building blocks which can be combined to create reactive functions
similar to `lift` in [Elm] or `defc=` in [hoplon]. This enables [FRP].
The way that reagent harnesses these two building blocks is delightfully easy.
### The Components
Extending the diagram a bit, we introduce the beginnings of one way data flow:
Extending the diagram a bit, we introduce the beginnings of one way (reactive) data flow:
```
db-app --> components --> hiccup
```
@ -145,23 +158,29 @@ Here's a trivial component:
[]
[:div "Hello ratoms and recactions"])
(greet n) ;; returns [:div "Hello ratoms and recactions"]
(greet n)
;; ==> [:div "Hello ratoms and recactions"]
```
You'll notice that its a normal clojure function, nothing special. It takes no inputs (no `db-app` involved) but it does produce `hiccup` (a vector data strcutre in this case).
You'll notice that our component is a regular clojure function, nothing special. In this case, it takes no inputs and it does produce `hiccup` (a vector of stuff in this case).
Here is a slightly interesting one:
Here is a slightly more interesting component:
```
(defn greet
[name] ;; name is a ratom
[:div "Hello " @name]) ;; dereference name here, to get out the value it contains
[name] ;; 'name' is a ratom, contains a string
[:div "Hello " @name]) ;; dereference name here to get out the value it contains
(def n (reagent/atom "re-frame")) ;; create a ratom, containing a string
;; create a ratom, containing a string
(def n (reagent/atom "re-frame"))
(greet n) ;; ==> [:div "Hello " "re-frame"]
;; call our component
(greet n)
;; ==> [:div "Hello " "re-frame"]
```
So far, so good? Let's add a `reaction`.
Okay, so have we got it that components are: data in, hiccup out ?
Good, let's introduce a `reaction`:
```
(defn greet
[name] ;; name is a ratom
@ -169,46 +188,59 @@ So far, so good? Let's add a `reaction`.
(def n (reagent/atom "re-frame"))
(def hiccup-ratom (reaction (greet n))) ;; reactive computation, result stored in hiccup-ratom
;; The computation '(greet n)' produces hiccup which is stored into 'hiccup-ratom'
(def hiccup-ratom (reaction (greet n)))
(println @hiccup-ratom) ;; [:div "Hello " "re-frame"]
;; what is the result of the initial computation ?
(println @hiccup-ratom)
;; ==> [:div "Hello " "re-frame"]
;; now change the ratom which is dereferenced in the computation
(reset! n "blah") ;; change n to a new value
(println @hiccup-ratom) ;; [:div "Hello " "blah"]
;; the computaton will have been rerun, and 'hiccup-ratom' now has an updated value
(println @hiccup-ratom)
;; ==> [:div "Hello " "blah"]
```
The computation `(greet n)` produces hiccup which is stored into `hiccup-ratom`.
This computation involves dereferencing a ratom (passed as `n`to greet). Whenever that ratom changes, the computation will be rerun and hiccup-ratom will be reset to this new value.
Still with us? Good. If you understand the **concept** of re-computation, then we're there.
These components are a bit like the templates you'd find in frameworks
Truth injection time. I haven't been completely straight with you, so we could just focus on the **concepts**. Here's the inconvienient reality -- reagent runs `reactions` (re-computations) via requestAnnimationFrame, which is, say, 16ms in the future, or after the current thread of processing finishes, which ever is the greater. So if you were to actually run the lines of code above one after the other, you might not see the re-computation done after `n` gets reset!, unless the animation frame has run. Not that this bit of annoying truth really matters much. All you need is the concept.
On with my lies and distortions ...
A `component` like `greet` is a bit like the templates you'd find in frameworks
like Django or Rails or Mustache, except for two massive differences:
- you have available the full power of ClojureScript.
The downside tradeoff is that these are not "designer friendly" HTML templates.
- these components are reactive. When their inputs change, they
- you have available the full power of ClojureScript (you are just generating a clojure datastructure). The downside tradeoff is that these are not "designer friendly" HTML templates.
- these components are reactive. When their "inputs" change, they
are automatically rerun, producing new hiccup. reagent adroitly shields you from
the details, but `components` (functions you write) are wrapped by
`reaction` in such a way that they re-run when the ratoms they
dereference change. This is FRP. This is why reagent feels slightly magic.
the details, but `components` are wrapped by a
`reaction`.
So `components` are pure, **reactive** functions. Change the inputs
and automatically, new hiccup is produced.
Summary: when the stream of data flowing into a `component` changes, the `component` is re-computed, producing a "stream" of output hiccup. Below, we'll see that this hiccup is turned into DOM and stitched into the GUI.
This is not a tutorial on how to write reagent components, but let's
talk briefly about the "data in" bit. Turns out there are two ways
data flows into components:
### Subscriptions
1. the data is supplied as component parameters, typically from a parent
component. There tends to be a
hierarchy of components and data often flows from parent to child
via function parameters.
So let's get back to our diagram.
```
app-db --> components --> hiccup
```
Subscriptions enable the reactive flow of data from `app-db` to the components.
2. a component can 'subscribe' to some aspect of the data. As a result, it becomes an
observer of that state, and it gets an stream of data updates as that part
of the ratom changes.
(subscribe [:pods]
Either way, when the "data in" changes, the component function is rerun,
and it produces new hiccup, which is then stitched into the DOM.
Data "flows" from the db-app into our components, and they produce hiccup.
Subscriptions are a significant part of re-frame ... more on them soon.
The compoents are reactive functions. But now we need to understand
components tend to be organised into a heirarchy and most of the time data is flowing from parents to child compoentns.
But at certain points, for example at the root compoentns, something has to 'subscribe' to
XXX ask for a
(def-component
subscriptions: [blah (subscribe :pods)
such (subscript XXX)]
[
### ReactJS