This repository was archived by the owner on Jun 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathindex.js
508 lines (451 loc) · 17.6 KB
/
index.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
/* global fetch:true, Promise:true, document:true */
import {
concat,
contains,
has,
intersection,
isEmpty,
keys,
lensPath,
pluck,
reject,
slice,
sort,
type,
union,
view
} from 'ramda';
import {createAction} from 'redux-actions';
import {crawlLayout, hasId} from '../reducers/utils';
import {APP_STATES} from '../reducers/constants';
import {ACTIONS} from './constants';
import cookie from 'cookie';
import {urlBase} from '../utils';
export const updateProps = createAction(ACTIONS('ON_PROP_CHANGE'));
export const setRequestQueue = createAction(ACTIONS('SET_REQUEST_QUEUE'));
export const computeGraphs = createAction(ACTIONS('COMPUTE_GRAPHS'));
export const computePaths = createAction(ACTIONS('COMPUTE_PATHS'));
export const setLayout = createAction(ACTIONS('SET_LAYOUT'));
export const setAppLifecycle = createAction(ACTIONS('SET_APP_LIFECYCLE'));
export const readConfig = createAction(ACTIONS('READ_CONFIG'));
export function hydrateInitialOutputs() {
return function (dispatch, getState) {
triggerDefaultState(dispatch, getState);
dispatch(setAppLifecycle(APP_STATES('HYDRATED')));
}
}
function triggerDefaultState(dispatch, getState) {
const {graphs} = getState();
const {InputGraph} = graphs;
const allNodes = InputGraph.overallOrder();
const inputNodeIds = [];
allNodes.reverse();
allNodes.forEach(nodeId => {
const componentId = nodeId.split('.')[0];
/*
* Filter out the outputs,
* inputs that aren't leaves,
* and the invisible inputs
*/
if (InputGraph.dependenciesOf(nodeId).length > 0 &&
InputGraph.dependantsOf(nodeId).length == 0 &&
has(componentId, getState().paths)
) {
inputNodeIds.push(nodeId);
}
});
reduceInputIds(inputNodeIds, InputGraph).forEach(nodeId => {
const [componentId, componentProp] = nodeId.split('.');
// Get the initial property
const propLens = lensPath(
concat(getState().paths[componentId],
['props', componentProp]
));
const propValue = view(
propLens,
getState().layout
);
dispatch(notifyObservers({
id: componentId,
props: {[componentProp]: propValue}
}));
});
}
export function redo() {
return function (dispatch, getState) {
const history = getState().history;
dispatch(createAction('REDO')());
const next = history.future[0];
// Update props
dispatch(createAction('REDO_PROP_CHANGE')({
itempath: getState().paths[next.id],
props: next.props
}));
// Notify observers
dispatch(notifyObservers({
id: next.id,
props: next.props
}));
}
}
export function undo() {
return function (dispatch, getState) {
const history = getState().history;
dispatch(createAction('UNDO')());
const previous = history.past[history.past.length - 1];
// Update props
dispatch(createAction('UNDO_PROP_CHANGE')({
itempath: getState().paths[previous.id],
props: previous.props
}));
// Notify observers
dispatch(notifyObservers({
id: previous.id,
props: previous.props
}));
}
}
function reduceInputIds(nodeIds, InputGraph) {
/*
* Create input-output(s) pairs,
* sort by number of outputs,
* and remove redudant inputs (inputs that update the same output)
*/
const inputOutputPairs = nodeIds.map(nodeId => ({
input: nodeId,
outputs: InputGraph.dependenciesOf(nodeId)
}));
const sortedInputOutputPairs = sort(
(a, b) => b.outputs.length - a.outputs.length,
inputOutputPairs
);
const uniquePairs = sortedInputOutputPairs.filter((pair, i) => !contains(
pair.outputs,
pluck('outputs', slice(i + 1, Infinity, sortedInputOutputPairs))
));
return pluck('input', uniquePairs);
}
export function notifyObservers(payload) {
return function (dispatch, getState) {
const {
id,
event,
props
} = payload
const {
config,
layout,
graphs,
paths,
requestQueue,
dependenciesRequest
} = getState();
const {EventGraph, InputGraph} = graphs;
/*
* Figure out all of the output id's that depend on this
* event or input.
* This includes id's that are direct children as well as
* grandchildren.
* grandchildren will get filtered out in a later stage.
*/
let outputObservers;
if (event) {
outputObservers = EventGraph.dependenciesOf(`${id}.${event}`);
} else {
const changedProps = keys(props);
outputObservers = [];
changedProps.forEach(propName => {
const node = `${id}.${propName}`
if (!InputGraph.hasNode(node)) {
return;
}
InputGraph.dependenciesOf(node).forEach(outputId => {
outputObservers.push(outputId);
});
});
}
if (isEmpty(outputObservers)) {
return;
}
/*
* There may be several components that depend on this input.
* And some components may depend on other components before
* updating. Get this update order straightened out.
*/
const depOrder = InputGraph.overallOrder();
outputObservers = sort(
(a, b) => depOrder.indexOf(b) - depOrder.indexOf(a),
outputObservers
);
const queuedObservers = [];
outputObservers.forEach(function filterObservers(outputIdAndProp) {
const outputComponentId = outputIdAndProp.split('.')[0];
/*
* before we make the POST to update the output, check
* that the output doesn't depend on any other inputs that
* that depend on the same controller.
* if the output has another input with a shared controller,
* then don't update this output yet.
* when each dependency updates, it'll dispatch its own
* `notifyObservers` action which will allow this
* component to update.
*
* for example, if A updates B and C (A -> [B, C]) and B updates C
* (B -> C), then when A updates, this logic will
* reject C from the queue since it will end up getting updated
* by B.
*
* in this case, B will already be in queuedObservers by the time
* this loop hits C because of the overallOrder sorting logic
*/
/*
* if the output just listens to events, then it won't be in
* the InputGraph
*/
const controllers = (InputGraph.hasNode(outputIdAndProp) ?
InputGraph.dependantsOf(outputIdAndProp) : []);
const controllersInFutureQueue = intersection(
queuedObservers,
controllers
);
/*
* check that the output hasn't been triggered to update already
* by a different input.
*
* for example:
* Grandparent -> [Parent A, Parent B] -> Child
*
* when Grandparent changes, it will trigger Parent A and Parent B
* to each update Child.
* one of the components (Parent A or Parent B) will queue up
* the change for Child. if this update has already been queued up,
* then skip the update for the other component
*/
const controllersInExistingQueue = intersection(
requestQueue, controllers
);
/*
* also check that this observer is actually in the current
* component tree.
* observers don't actually need to be rendered at the moment
* of a controller change.
* for example, perhaps the user has hidden one of the observers
*/
if (
(controllersInFutureQueue.length === 0) &&
(has(outputComponentId, getState().paths)) &&
(controllersInExistingQueue.length === 0)
) {
queuedObservers.push(outputIdAndProp)
}
});
/*
* record the set of output IDs that will eventually need to be
* updated in a queue. not all of these requests will be fired in this
* action
*/
dispatch(setRequestQueue(union(queuedObservers, requestQueue)));
const promises = [];
for (let i = 0; i < queuedObservers.length; i++) {
const outputIdAndProp = queuedObservers[i];
const [outputComponentId, outputProp] = outputIdAndProp.split('.');
/*
* Construct a payload of the input, state, and event.
* For example:
* If the input triggered this update, then:
* {
* inputs: [{'id': 'input1', 'property': 'new value'}],
* state: [{'id': 'state1', 'property': 'existing value'}]
* }
*
* If an event triggered this udpate, then:
* {
* state: [{'id': 'state1', 'property': 'existing value'}],
* event: {'id': 'graph', 'event': 'click'}
* }
*
*/
const payload = {
output: {id: outputComponentId, property: outputProp}
};
if (event) {
payload.event = event;
}
const {inputs, state} = dependenciesRequest.content.find(
dependency => (
dependency.output.id === outputComponentId &&
dependency.output.property === outputProp
)
)
if (inputs.length > 0) {
payload.inputs = inputs.map(inputObject => {
const propLens = lensPath(
concat(paths[inputObject.id],
['props', inputObject.property]
));
return {
id: inputObject.id,
property: inputObject.property,
value: view(propLens, layout)
};
});
}
if (state.length > 0) {
payload.state = state.map(stateObject => {
const propLens = lensPath(
concat(paths[stateObject.id],
['props', stateObject.property]
));
return {
id: stateObject.id,
property: stateObject.property,
value: view(propLens, layout)
};
});
}
promises.push(fetch(`${urlBase(config)}_dash-update-component`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': cookie.parse(document.cookie)._csrf_token
},
credentials: 'same-origin',
body: JSON.stringify(payload)
}).then(function handleResponse(res) {
dispatch({
type: 'lastUpdateComponentRequest',
payload: {status: res.status}
});
// clear this item from the request queue
dispatch(setRequestQueue(
reject(
id => id === outputIdAndProp,
getState().requestQueue
)
));
return res.json().then(function handleJson(data) {
/*
* it's possible that this output item is no longer visible.
* for example, the could still be request running when
* the user switched the chapter
*
* if it's not visible, then ignore the rest of the updates
* to the store
*/
if (!has(outputComponentId, getState().paths)) {
return;
}
// and update the props of the component
const observerUpdatePayload = {
itempath: getState().paths[outputComponentId],
// new prop from the server
props: data.response.props,
source: 'response'
};
dispatch(updateProps(observerUpdatePayload));
dispatch(notifyObservers({
id: outputComponentId,
props: data.response.props
}));
/*
* If the response includes children, then we need to update our
* paths store.
* TODO - Do we need to wait for updateProps to finish?
*/
if (has('children', observerUpdatePayload.props)) {
dispatch(computePaths({
subTree: observerUpdatePayload.props.children,
startingPath: concat(
getState().paths[outputComponentId],
['props', 'children']
)
}));
/*
* if children contains objects with IDs, then we
* need to dispatch a propChange for all of these
* new children components
*/
if (contains(
type(observerUpdatePayload.props.children),
['Array', 'Object']
) && !isEmpty(observerUpdatePayload.props.children)
) {
/*
* TODO: We're just naively crawling
* the _entire_ layout to recompute the
* the dependency graphs.
* We don't need to do this - just need
* to compute the subtree
*/
const newProps = {};
crawlLayout(
observerUpdatePayload.props.children,
function appendIds(child) {
if (hasId(child)) {
keys(child.props).forEach(childProp => {
const inputId = (
`${child.props.id}.${childProp}`
);
if (has(inputId, InputGraph.nodes)) {
newProps[inputId] = ({
id: child.props.id,
props: {
[childProp]: child.props[childProp]
}
});
}
})
}
}
);
/*
* Organize props by shared outputs so that we
* only make one request per output component
* (even if there are multiple inputs).
*/
const reducedNodeIds = reduceInputIds(
keys(newProps), InputGraph);
const depOrder = InputGraph.overallOrder();
const sortedNewProps = sort((a, b) =>
depOrder.indexOf(a) - depOrder.indexOf(b),
reducedNodeIds
);
sortedNewProps.forEach(function(nodeId) {
dispatch(notifyObservers(newProps[nodeId]));
});
}
}
})}));
}
return Promise.all(promises);
}
}
export function serialize(state) {
// Record minimal input state in the url
const {graphs, paths, layout} = state;
const {InputGraph} = graphs;
const allNodes = InputGraph.nodes;
const savedState = {};
keys(allNodes).forEach(nodeId => {
const [componentId, componentProp] = nodeId.split('.');
/*
* Filter out the outputs,
* and the invisible inputs
*/
if (InputGraph.dependenciesOf(nodeId).length > 0 &&
has(componentId, paths)
) {
// Get the property
const propLens = lensPath(
concat(paths[componentId],
['props', componentProp]
));
const propValue = view(
propLens,
layout
);
savedState[nodeId] = propValue;
}
});
return savedState;
}