-
Notifications
You must be signed in to change notification settings - Fork 0
/
spindle.js
301 lines (255 loc) · 7.96 KB
/
spindle.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import React, { PropTypes } from 'react';
import { Union } from 'results';
import is from './lib/is';
const I_PROMISE_I_WILL_ONLY_CALL_THESE_PROPTYPES_CHECKERS_IN_DEV_MODE =
'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
const validUpdateKeys = {
model: true,
cmds: true,
cb: true,
};
export function Update(stuff) {
if (!(this instanceof Update)) {
return new Update(stuff);
}
if (typeof stuff === 'undefined') {
return this;
}
Object.keys(stuff).forEach(k => {
if (typeof validUpdateKeys[k] === 'undefined') {
throw new TypeError(`Unrecognized key \`${k}\` supplied to Update(). ` +
`Valid keys: ${Object.keys(validUpdateKeys).join(', ')}`);
}
});
Object.assign(this, stuff);
};
const assertType = process.env.NODE_ENV === 'production'
? () => null
: (who, checker, value, name, source) => {
const result = checker({ [who]: value }, who, `${name} => ${source}`, 'prop', who,
I_PROMISE_I_WILL_ONLY_CALL_THESE_PROPTYPES_CHECKERS_IN_DEV_MODE);
if (result instanceof Error) {
console.error(result.message || result);
}
};
const propsEq = (a, b) => {
for (const k in a) {
if (a[k] !== b[k]) return false;
}
return Object.keys(a).length === Object.keys(b).length;
};
export const Cmd = options => {
if (process.env.NODE_ENV !== 'production') {
assertType('options', PropTypes.shape({
run: PropTypes.func.isRequired,
abort: PropTypes.func.isRequired,
}), options, 'Cmd', 'setup');
}
return options;
};
export const Sub = (ns, options) => {
// assertType('ns', symbolType, ns, 'Sub', 'setup');
if (process.env.NODE_ENV !== 'production') {
assertType('options', PropTypes.shape({
key: PropTypes.string.isRequired,
start: PropTypes.func.isRequired,
stop: PropTypes.func.isRequired,
}), options, 'Sub', 'setup');
}
return { ns, ...options };
};
export const TypedUnion = process.env.NODE_ENV === 'production'
? Union
: options => {
const U = Union(options);
Object.keys(options).forEach(o => {
const C = U[o];
U[o] = x => {
assertType('payload', options[o], x, `TypedUnion{${Object.keys(options).join(',')}}`, o);
return C(x);
};
});
return U;
};
const createSpindle = () => {
const components = new Map();
const subscriptions = new Map(); // ns => Map(key => sub)
return {
register: component =>
components.set(component, { subs: [], cmds: [] }),
unregister: component => {
components.get(component).cmds.forEach(cmd =>
cmd.abort(cmd.state));
components.delete(component);
},
pushCmds: (component, cmds) => {
cmds.forEach(([{ run, abort }, Tag ]) => {
const ccmds = components.get(component).cmds;
const cmd = { state: null, abort };
ccmds.push(cmd);
const finish = () =>
ccmds.splice(ccmds.indexOf(cmd), 1);
const msg = payload =>
component._dispatch(Tag(payload));
cmd.state = run(msg, finish);
});
},
updateSubs: (component, subs) => {
// ensure all subs are set up and started
subs.forEach(([{ ns, key, start, stop }, Tag]) => {
if (!subscriptions.has(ns)) {
subscriptions.set(ns, new Map());
}
const nsSubs = subscriptions.get(ns);
if (!nsSubs.has(key)) {
const sub = { stop, state: null };
sub.state = start((next, payload) => {
sub.state = next;
components.forEach(({ subs: subs_ }, c) =>
subs_
.filter(([n, k]) =>
n === ns && k === key)
.forEach(([_, __, T]) =>
c._dispatch(T(payload))));
});
nsSubs.set(key, sub);
}
});
// update the component's subscriptions
components.get(component).subs = subs
.map(([{ ns, key }, Tag]) =>
[ns, key, Tag]);
// super-wastefully turn off all unused subs
subscriptions.forEach((nsSubs, ns) =>
nsSubs.forEach((sub, key) => {
for (const [c, { subs }] of components) {
if (subs.some(([n, k]) =>
n === ns && k === key)) {
return;
}
}
sub.stop(sub.state);
nsSubs.delete(key);
}));
},
};
};
const bindActions = (dispatch, Action) =>
Object.keys(Action.options).forEach(k =>
dispatch[k] = payload => dispatch(Action[k](payload)));
export default function Spindle(name, {
Action = Union({}),
init = () => Update(),
propsUpdate = () => Update(),
update = () => Update(),
view = () => null,
subscriptions = () => [],
modelType = PropTypes.any,
cbTypes = {},
propTypes: componentPropTypes = {},
}) {
class Component extends React.Component {
constructor(props, context) {
super(props, context);
if (typeof context.spindle === 'undefined') {
this._isSpindleRoot = true;
this._spindle = createSpindle();
} else {
this._isSpindleRoot = false;
this._spindle = undefined; // only for the root
}
this.getSpindle().register(this);
this._dispatch = action =>
this.queue(update(action, this._model), 'update', action);
bindActions(this._dispatch, Action);
this._model = null;
}
componentWillMount() {
this.queue(init(this.props), 'init');
}
getChildContext() {
return { spindle: this.context.spindle || this._spindle };
}
componentWillReceiveProps(nextProps) {
if (!propsEq(this.props, nextProps)) {
this.queue(propsUpdate(nextProps, this._model), 'propsUpdate');
}
}
shouldComponentUpdate(nextProps, nextState) {
return !propsEq(nextProps, this.props) ||
!is(nextState.model, this.state.model);
}
componentWillUnmount() {
this.getSpindle().unregister(this);
}
getSpindle() {
return this.context.spindle || this._spindle;
}
queue(update, source, action) {
if (!(update instanceof Update)) {
if (action && action.name && action.payload) {
source = `${source} => ${action.name}(${action.payload || ''})`
}
throw new TypeError(`${name}'s \`${source}\` function returned \`${typeof update}\`. ` +
`Did you forget to wrap a new model in \`Update({ model: ... })\`?`);
}
const { model, cmds, cb } = update;
if (typeof model !== 'undefined') {
if (process.env.NODE_ENV !== 'production') {
assertType('model', modelType, model, name, source);
}
this._model = model;
}
if (typeof cmds !== 'undefined') {
this.getSpindle().pushCmds(this, cmds);
}
const subs = subscriptions(this._model);
this.getSpindle().updateSubs(this, subs);
if (typeof cb !== 'undefined') {
Object.keys(cb)
.filter(prop =>
this.props[prop])
.forEach(prop => {
if (process.env.NODE_ENV !== 'production' &&
prop in cbTypes) {
assertType(`cb: { ${prop} }`, cbTypes[prop], cb[prop], name, source);
}
this.props[prop](cb[prop]);
});
}
if (source === 'init') {
this.state = { model: this._model };
} else {
this.setState({ model: this._model });
}
}
render() {
return view(this._model, this._dispatch, this.props);
}
}
Object.assign(Component, {
displayName: name,
contextTypes: {
spindle: PropTypes.object,
},
childContextTypes: {
spindle: PropTypes.object,
},
propTypes: componentPropTypes,
spindle: {
Action,
init,
propsUpdate,
update,
view,
subscriptions,
modelType,
cbTypes,
propTypes: componentPropTypes,
}
});
return Component;
};
// be friendly to cjs modules
Object.assign(exports['default'], exports); // attach all the exports to Spindle
module.exports = exports['default']; // export it like a cjs module