├── .eslintignore
├── .eslintrc
├── .gitignore
├── .npmignore
├── .travis.yml
├── LICENSE
├── README.md
├── examples
├── counter
│ ├── app.js
│ └── flux.js
├── react-hot
│ ├── .eslintrc
│ ├── client
│ │ ├── Application.js
│ │ ├── app.js
│ │ └── dispatcher.js
│ ├── index.html
│ ├── package.json
│ ├── server.js
│ └── webpack.config.js
└── react-iso
│ ├── .eslintrc
│ ├── client
│ ├── app.js
│ ├── components
│ │ ├── Application.js
│ │ ├── Error404.js
│ │ ├── Film.js
│ │ ├── Films.js
│ │ ├── Home.js
│ │ ├── Planet.js
│ │ └── Planets.js
│ ├── data.js
│ ├── dispatcher.js
│ ├── routes.js
│ ├── stores
│ │ ├── films.js
│ │ ├── planets.js
│ │ └── routing.js
│ └── swapi.js
│ ├── index.html
│ ├── package.json
│ ├── server-render.js
│ ├── server.js
│ └── webpack.config.js
├── fluctuations.js
├── package.json
└── test
├── .eslintrc
└── test.js
/.eslintignore:
--------------------------------------------------------------------------------
1 | node_modules/*
2 |
--------------------------------------------------------------------------------
/.eslintrc:
--------------------------------------------------------------------------------
1 | {
2 | "env": {
3 | "node": true
4 | },
5 | "rules": {
6 | "strict": 0,
7 | "quotes": 0,
8 | "indent": [2, 2],
9 | "curly": [2, "multi-line"],
10 | "no-use-before-define": "func",
11 | "no-unused-vars": [2, "all"],
12 | "no-mixed-requires": [1, true],
13 | "max-depth": [1, 5],
14 | "max-len": [1, 80, 4],
15 | "max-params": [1, 6],
16 | "max-statements": [1, 20],
17 | "eqeqeq": 0,
18 | "new-cap": 0,
19 | "no-else-return": 1,
20 | "no-eq-null": 1,
21 | "no-lonely-if": 1,
22 | "no-path-concat": 0,
23 | "comma-dangle": 0,
24 | "complexity": [1, 20],
25 | "no-floating-decimal": 1,
26 | "no-void": 1,
27 | "no-sync": 1,
28 | "consistent-this": [1, "nope-dont-capture-this"],
29 | "max-nested-callbacks": [2, 3],
30 | "no-nested-ternary": 1,
31 | "space-after-keywords": [1, "always"],
32 | "space-before-function-paren": [1, "never"],
33 | "spaced-line-comment": [1, "always"]
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 |
5 | # Runtime data
6 | pids
7 | *.pid
8 | *.seed
9 |
10 | # Directory for instrumented libs generated by jscoverage/JSCover
11 | lib-cov
12 |
13 | # Coverage directory used by tools like istanbul
14 | coverage
15 |
16 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
17 | .grunt
18 |
19 | # node-waf configuration
20 | .lock-wscript
21 |
22 | # Compiled binary addons (http://nodejs.org/api/addons.html)
23 | build/Release
24 |
25 | # Dependency directory
26 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git
27 | node_modules
28 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | coverage
2 | examples
3 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | sudo: false
3 | node_js:
4 | - "0.10"
5 | - "0.12"
6 | - "iojs"
7 | script: "npm run travis"
8 | after_script: "cat ./coverage/lcov.info | ./node_modules/.bin/coveralls"
9 | matrix:
10 | allow_failures:
11 | - node_js: "iojs"
12 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2015 Glen Mailer
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
23 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # fluctuations
2 |
3 | Yet another flux implementation
4 |
5 | Formerly known as `flux-redux`.
6 |
7 | [](https://www.npmjs.com/package/fluctuations) [](https://travis-ci.org/glenjamin/fluctuations) [](https://coveralls.io/r/glenjamin/fluctuations?branch=master) 
8 |
9 | ## Goals
10 |
11 | * Simple Implementation
12 | * Small API
13 | * Flexible
14 | * Functional rather than OO
15 | * Reducer-style stores
16 | * Actions as simple data
17 | * Action interceptors for async stuff
18 | * No singletons
19 | * Easy to use with Immutable.js
20 | * Easy to run isomorphically
21 | * Easy to use with hot reloading
22 |
23 | ## Install
24 |
25 | ```sh
26 | npm install fluctuations
27 | ```
28 |
29 | ## Usage
30 |
31 | ```js
32 | var fluctuations = require('fluctuations');
33 |
34 | var store = fluctuations.createStore(
35 | function() {
36 | return { initial: 'data', number: 0 };
37 | },
38 | {
39 | CHANGE_MESSAGE: function(state, payload) {
40 | state.initial = payload.value;
41 | return state;
42 | },
43 | INC_NUMBER: function(state) {
44 | state.number += 1;
45 | return state;
46 | }
47 | }
48 | );
49 |
50 | var interceptor = fluctuations.createInterceptor({
51 | FETCH_MESSAGE: function(emit, payload) {
52 | emit("FETCH_MESSAGE_BEGIN");
53 | setTimeout(function() {
54 | emit("CHANGE_MESSAGE", { value: "whatever" });
55 | }, 2000);
56 | }
57 | });
58 |
59 | var flux = fluctuations.createDispatcher();
60 | flux.addInterceptor('stuff', interceptor);
61 | flux.addStore('stuff', store);
62 |
63 | flux.listen("logging", function() {
64 | console.log(flux.get());
65 | });
66 |
67 | flux.dispatch("INC_NUMBER");
68 | ```
69 |
70 | ## Concepts
71 |
72 | **Fluctuations** is based around the Flux architecture as laid out by facebook. See the [flux documentation](https://facebook.github.io/flux/docs/overview.html#structure-and-data-flow) for more information. We keep the concepts defined by facebook, but make a few tweaks. Most notably **Action Creators** are removed, and **Action Interceptors** are introduced to perform a similar role.
73 |
74 | ### Action Interceptors
75 |
76 | In early explanations of flux, the role of actions was a bit blurred. They seem to behave like commands and like events. As implementations were further clarified, Action Creators were explained as representing the command portion, while the data representation they sent to the dispatcher is referred to as the action. For many simple actions, this results in boilerplate code which translates a function call into a data payload. More complicated actions can use this layer of indirection to perform multiple actions, do asynchronous lookups etc.
77 |
78 | The goal of action interceptors is to retain this capability, but remove the boilerplate code required in the common case. The **dispatcher** remains the central point for all communication. Stores and interceptors are attached to a dispatcher instance. Subscriptions are managed via the dispatcher, and the UI is expected to be able to call `dispatch()` directly.
79 |
80 | Unlike creators, Interceptors sit behind the dispatcher. The actions which are dispatched into the dispatcher are intended to be treated like commands. If no interceptor exists then the action is treated like an event, and forwarded to all stores. If an interceptor chooses to handle the command, it is then freeto translate it into whatever event-like actions it wants to. Interceptors are also able to re-dispatch new commands and read the state of stores. This allows them full flexibility when deciding what events they must produce.
81 |
82 | To summarise the key points here:
83 |
84 | * **Stores** receive actions which should be treated like *events*
85 | * The **Dispatcher** receives actions which should be treated like *commands*
86 | * **Action Interceptors** capture a *command* and produce *events*
87 | * If no interceptor exists, a *command* becomes an *event*
88 |
89 | ### Hot Reloading
90 |
91 | The practice of hot reloading is making a system which can receive new code at runtime, and incorporate it into itself - ideally behaving the same as if it had been started afresh. The goal being to reduce the feedback cycle between changes.
92 |
93 | The simplest way to make code hot reloadable is to make it pure (stateless), as soon as state is introduced, we have to decide what to do with it when reloading.
94 |
95 | To make hot reloading easier, fluctuations minimises the number of places state is held - everything is kept in the dispatcher. In addition, every time something is attached to the dispatcher it is required to pass a `key` which names it uniquely. This is used to ensure the same item is never duplicated.
96 |
97 | To hot reload fluctuations, you just need to re-use the dispatcher instance every time, like in the following webpack example:
98 |
99 | ```js
100 | var dispatcher = flux.createDispatcher();
101 | if (module.hot) {
102 | if (module.hot.data) {
103 | dispatcher = module.hot.data.dispatcher;
104 | }
105 | module.hot.accept();
106 | module.hot.dispose((data) => data.dispatcher = dispatcher);
107 | }
108 | ```
109 |
110 | # Docs
111 |
112 | In addition to these API docs, there are a few examples you can look at.
113 |
114 | * [Counter](examples/counter/) - Basic data handling
115 | * [React Hot](examples/react-hot/) - React w/ hot module reloading and async data fetching
116 | * [React Isomorphic](examples/react-iso) - React w/ hot module reloading, routing, route-aware async data fetching & server rendering
117 |
118 | ## API
119 |
120 | ### `fluctuations`
121 |
122 | ```js
123 | var fluctuations = require('fluctuations');
124 | ```
125 |
126 | #### `.createDispatcher(options)`
127 |
128 | Create yourself a shiny new dispatcher instance.
129 |
130 | * `options` *{object}* - additional creation options
131 | * `options.state` *{object}* - pass this to reuse state from a previous dispatcher
132 |
133 | Returns [*{Dispatcher}*](#dispatcher)
134 |
135 | #### `.createStore(initial, handlers, merge)`
136 |
137 | Create yourself a shiny new store representation.
138 |
139 | Store representations by themselves don't do anything, they should be attached to your friendly neighbourhood dispatcher instance to make things work.
140 |
141 | * `initial` *{function() => state}* - will be called when attaching a store to a dispatcher. The return value will become the initial state.
142 | * `handlers` *{object}* - mapping of action-name to handler function, where handler functions are *{function(state, payload) => newState}*. See [Store Handlers](#store-handlers) below.
143 | * `merge` (optional) *{function(state, newState) => state}* - will be called when a store is being replaced, and can be used to combine the old and new states. The return value will become the new store state.
144 |
145 | Returns [*{StoreSpec}*](#addstorekey-store)
146 |
147 | ##### Store Handlers
148 |
149 | Store handlers map incoming actions to state changes that should be made. The handler function will receive the current state of the store and any action payload, and should return a new state for the store.
150 |
151 | For example, this set of handlers will increment and decrement the a number in the store as actions are passed in.
152 | ```js
153 | {
154 | INC: function(state, n) {
155 | return { n: state.n + n };
156 | },
157 | DEC: function(state, n) {
158 | return { n: state.n - n };
159 | }
160 | }
161 | ```
162 | In general you are likely to want to use a merge function to ensure you don't replace properties you're not interested in, or look into using something like [Immutable](http://facebook.github.io/immutable-js/) here instead.
163 |
164 | #### `.createInterceptor(handlers)`
165 |
166 | Create yourself a shiny new interceptor representation.
167 |
168 | Interceptor representations by themselves don't do anything, they should be attached to your friendly neighbourhood dispatcher instance to make things work.
169 |
170 | * `handlers` *{object}* - mapping of action-name to handler function, where handler functions are `function(emit, payload)`. See [Interceptor Handlers](#interceptor-handlers) below.
171 |
172 | Returns [*{InterceptorSpec}*](#addinterceptorkey-interceptor)
173 |
174 | #### Interceptor Handlers
175 |
176 | > TODO: flesh this out properly
177 |
178 | Handlers come in two flavours, the first is the simple common case, the second provides more flexibility.
179 |
180 | `function(emit, payload)`
181 | * `emit = function(action, payload)` send action to stores
182 | * `payload` the data for the incoming action
183 |
184 | `function(system, payload)`
185 | * `system.emit = function(action, payload)` send action to stores
186 | * `system.redispatch = function(action, payload)` send action back to dispatcher so it can be re-intercepted
187 | * `system.state` the state of the system when the action was intercepted
188 | * `payload` the data for the incoming action
189 |
190 | ### `Dispatcher`
191 |
192 | The dispatcher is the central point of the application's data flow, everything else plugs into it.
193 |
194 | #### `.addStore(key, store)`
195 |
196 | Attach a *{StoreSpec}* as created by `createStore` into the dispatcher. This will delegate management of the value at `key` to the store's handlers.
197 |
198 | If attaching a store with the same `key` as a previous store, it will be overwritten, using the merge strategy to combine the new initial and the current state. This is very useful when hot reloading.
199 |
200 | * `key` *{string}* - unique name to identify this store
201 | * `store` *{StoreSpec}* - the store details, as produced by createStore
202 |
203 | #### `.addInterceptor(key, interceptor)`
204 |
205 | Attach an *{InterceptorSpec}* as create by `createInterceptor` into the dispatcher. This will cause the interceptor to capture any action matched by it's handlers, and allow it to emit multiple actions over time instead.
206 |
207 | If attaching an interceptor with the same `key` as a previous interceptor, it will be overwritten. This is very useful when hot reloading.
208 |
209 | #### `.dispatch(action, payload)`
210 |
211 | Send an action into the dispatcher.
212 |
213 | * `action` *{string}* - name of the action
214 | * `payload` *{any}* - extra data associated with the action, usually an object
215 |
216 | #### `.listen(key, listener)`
217 |
218 | Attach a listener to the dispatcher which will be called whenever the state of the system changes. It is expected that you'll want to call [get()](#get) within this listener.
219 |
220 | If attaching a listener with the same `key` as a previous listener, it will be overwritten. This can be very useful when hot reloading, as it means you don't need to clean up old listeners.
221 |
222 | * `key` *{string}* - unique name to identify this listener
223 | * `listener` *{function()}* - function to be called when state changes
224 |
225 | #### `.get()`
226 |
227 | Retreive the current state of the whole system. This will be an object with a `key` for each store containing the last known state of that store.
228 |
229 | Returns *{object}*
230 |
231 |
232 | # TODO
233 |
234 | * High level tests
235 | * Low level tests
236 | * Cycle detection?
237 | * Separate dispatcher definition and instances?
238 | * Benchmarking / profiling
239 | * Granular subscriptions
240 | * tidy up docs
241 |
--------------------------------------------------------------------------------
/examples/counter/app.js:
--------------------------------------------------------------------------------
1 | var dispatch = require('./flux');
2 |
3 | dispatch('INC');
4 | dispatch('INC');
5 | dispatch('INC');
6 |
7 | dispatch('SLOW_INC');
8 | dispatch('SLOW_INC', { delay: 5000 });
9 |
--------------------------------------------------------------------------------
/examples/counter/flux.js:
--------------------------------------------------------------------------------
1 | var fluctuations = require('../..');
2 |
3 | function copy(a, b) {
4 | var ret = {};
5 | function add(k) { ret[k] = this[k]; }
6 | Object.keys(a).forEach(add, a);
7 | Object.keys(b).forEach(add, b);
8 | return ret;
9 | }
10 |
11 | var store = fluctuations.createStore(
12 | function() {
13 | return { number: 0, pending: 0 };
14 | },
15 | {
16 | INC_WAIT: function(state) {
17 | return copy(state, { pending: state.pending + 1 });
18 | },
19 | INC_DONE: function(state) {
20 | return copy(state, {
21 | number: state.number + 1,
22 | pending: state.pending - 1
23 | });
24 | },
25 | INC: function(state) {
26 | return copy(state, { number: state.number + 1 });
27 | }
28 | }
29 | );
30 |
31 | var interceptor = fluctuations.createInterceptor({
32 | SLOW_INC: function(emit, payload) {
33 | emit("INC_WAIT");
34 | setTimeout(function() {
35 | emit("INC_DONE");
36 | }, payload.delay || 1000);
37 | }
38 | });
39 |
40 | var flux = fluctuations.createDispatcher();
41 |
42 | flux.addInterceptor('n', interceptor);
43 | flux.addStore('n', store);
44 |
45 | flux.listen("logging", function() {
46 | var stores = flux.get();
47 | console.log("%d%s",
48 | stores.n.number,
49 | stores.n.pending > 0 ? ' (pending)' : '');
50 | });
51 |
52 | module.exports = flux.dispatch;
53 |
--------------------------------------------------------------------------------
/examples/react-hot/.eslintrc:
--------------------------------------------------------------------------------
1 | {
2 | "env": {
3 | "node": true
4 | },
5 | "parser": "babel-eslint",
6 | "ecmaFeatures": {
7 | "jsx": true
8 | },
9 | "plugins": [
10 | "no-class",
11 | "react"
12 | ],
13 | "rules": {
14 | "strict": 0,
15 | "quotes": 0,
16 | "indent": [2, 2],
17 | "curly": [2, "multi-line"],
18 | "no-use-before-define": "func",
19 | "no-unused-vars": [2, "all"],
20 | "no-mixed-requires": [1, true],
21 | "max-depth": [1, 5],
22 | "max-len": [1, 80, 4],
23 | "max-params": [1, 6],
24 | "max-statements": [1, 20],
25 | "eqeqeq": 0,
26 | "new-cap": 0,
27 | "no-else-return": 1,
28 | "no-eq-null": 1,
29 | "no-lonely-if": 1,
30 | "no-path-concat": 0,
31 | "comma-dangle": 0,
32 | "complexity": [1, 20],
33 | "no-floating-decimal": 1,
34 | "no-void": 1,
35 | "no-sync": 1,
36 | "consistent-this": [1, "nope-dont-capture-this"],
37 | "max-nested-callbacks": [2, 3],
38 | "no-nested-ternary": 1,
39 | "space-after-keywords": [1, "always"],
40 | "space-before-function-paren": [1, "never"],
41 | "spaced-line-comment": [1, "always"],
42 | "no-class/no-class": 2,
43 | "react/jsx-boolean-value": 1,
44 | "react/jsx-quotes": 0,
45 | "react/jsx-no-undef": 1,
46 | "react/jsx-sort-props": 0,
47 | "react/jsx-sort-prop-types": 0,
48 | "react/jsx-uses-react": 1,
49 | "react/jsx-uses-vars": 1,
50 | "react/no-did-mount-set-state": 1,
51 | "react/no-did-update-set-state": 1,
52 | "react/no-multi-comp": 0,
53 | "react/no-unknown-property": 1,
54 | "react/prop-types": 1,
55 | "react/react-in-jsx-scope": 1,
56 | "react/self-closing-comp": 0,
57 | "react/wrap-multilines": 1
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/examples/react-hot/client/Application.js:
--------------------------------------------------------------------------------
1 | var React = require('react');
2 |
3 | var Application = React.createClass({
4 | propTypes: {
5 | dispatch: React.PropTypes.func,
6 | stores: React.PropTypes.object
7 | },
8 | render() {
9 | var {swapi} = this.props.stores;
10 | var {films = []} = swapi;
11 | return (
12 |