-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
history.js
656 lines (518 loc) · 21.1 KB
/
history.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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
import _cloneDeep from 'lodash-es/cloneDeep';
import _cloneDeepWith from 'lodash-es/cloneDeepWith';
import _difference from 'lodash-es/difference';
import _flatten from 'lodash-es/flatten';
import _groupBy from 'lodash-es/groupBy';
import _isFunction from 'lodash-es/isFunction';
import _isEmpty from 'lodash-es/isEmpty';
import _forEach from 'lodash-es/forEach';
import _map from 'lodash-es/map';
import _omit from 'lodash-es/omit';
import _uniq from 'lodash-es/uniq';
import { dispatch as d3_dispatch } from 'd3-dispatch';
import { easeLinear as d3_easeLinear } from 'd3-ease';
import { select as d3_select } from 'd3-selection';
import { coreDifference } from './difference';
import { coreGraph } from './graph';
import { coreTree } from './tree';
import { osmEntity } from '../osm/entity';
import { uiLoading } from '../ui';
import { utilRebind, utilSessionMutex } from '../util';
export function coreHistory(context) {
var dispatch = d3_dispatch('change', 'annotatedChange', 'merge', 'restore', 'undone', 'redone');
var lock = utilSessionMutex('lock');
var duration = 150;
var _imageryUsed = [];
var _checkpoints = {};
var _pausedGraph;
var _stack;
var _index;
var _tree;
// internal _act, accepts list of actions and eased time
function _act(actions, t) {
actions = Array.prototype.slice.call(actions);
var annotation;
if (!_isFunction(actions[actions.length - 1])) {
annotation = actions.pop();
}
var graph = _stack[_index].graph;
for (var i = 0; i < actions.length; i++) {
graph = actions[i](graph, t);
}
return {
graph: graph,
annotation: annotation,
imageryUsed: _imageryUsed,
transform: context.projection.transform(),
selectedIDs: context.selectedIDs()
};
}
// internal _perform with eased time
function _perform(args, t) {
var previous = _stack[_index].graph;
_stack = _stack.slice(0, _index + 1);
var actionResult = _act(args, t);
_stack.push(actionResult);
_index++;
return change(previous, actionResult.annotation);
}
// internal _replace with eased time
function _replace(args, t) {
var previous = _stack[_index].graph;
// assert(_index == _stack.length - 1)
var actionResult = _act(args, t);
_stack[_index] = actionResult;
return change(previous, actionResult.annotation);
}
// internal _overwrite with eased time
function _overwrite(args, t) {
var previous = _stack[_index].graph;
if (_index > 0) {
_index--;
_stack.pop();
}
_stack = _stack.slice(0, _index + 1);
var actionResult = _act(args, t);
_stack.push(actionResult);
_index++;
return change(previous, actionResult.annotation);
}
// determine difference and dispatch a change event
function change(previous, isAnnotated) {
var difference = coreDifference(previous, history.graph());
if (!_pausedGraph) {
dispatch.call('change', this, difference);
if (isAnnotated) {
// actions like dragging a node can fire lots of changes,
// so use 'annotatedChange' to listen for grouped undo/redo changes
dispatch.call('annotatedChange', this, difference);
}
}
return difference;
}
// iD uses namespaced keys so multiple installations do not conflict
function getKey(n) {
return 'iD_' + window.location.origin + '_' + n;
}
var history = {
graph: function() {
return _stack[_index].graph;
},
tree: function() {
return _tree;
},
base: function() {
return _stack[0].graph;
},
merge: function(entities, extent) {
_stack[0].graph.rebase(entities, _map(_stack, 'graph'), false);
_tree.rebase(entities, false);
dispatch.call('change', this, undefined, extent);
dispatch.call('merge', this, entities);
},
perform: function() {
// complete any transition already in progress
d3_select(document).interrupt('history.perform');
var transitionable = false;
var action0 = arguments[0];
if (arguments.length === 1 ||
arguments.length === 2 && !_isFunction(arguments[1])) {
transitionable = !!action0.transitionable;
}
if (transitionable) {
var origArguments = arguments;
d3_select(document)
.transition('history.perform')
.duration(duration)
.ease(d3_easeLinear)
.tween('history.tween', function() {
return function(t) {
if (t < 1) _overwrite([action0], t);
};
})
.on('start', function() {
_perform([action0], 0);
})
.on('end interrupt', function() {
_overwrite(origArguments, 1);
});
} else {
return _perform(arguments);
}
},
replace: function() {
d3_select(document).interrupt('history.perform');
return _replace(arguments, 1);
},
// Same as calling pop and then perform
overwrite: function() {
d3_select(document).interrupt('history.perform');
return _overwrite(arguments, 1);
},
pop: function(n) {
d3_select(document).interrupt('history.perform');
var previous = _stack[_index].graph;
if (isNaN(+n) || +n < 0) {
n = 1;
}
while (n-- > 0 && _index > 0) {
_index--;
_stack.pop();
}
return change(previous);
},
// Back to the previous annotated state or _index = 0.
undo: function() {
d3_select(document).interrupt('history.perform');
var previous = _stack[_index].graph;
while (_index > 0) {
_index--;
if (_stack[_index].annotation) break;
}
dispatch.call('undone', this, _stack[_index]);
return change(previous, true);
},
// Forward to the next annotated state.
redo: function() {
d3_select(document).interrupt('history.perform');
var previous = _stack[_index].graph;
var tryIndex = _index;
while (tryIndex < _stack.length - 1) {
tryIndex++;
if (_stack[tryIndex].annotation) {
_index = tryIndex;
dispatch.call('redone', this, _stack[_index]);
break;
}
}
return change(previous, true);
},
pauseChangeDispatch: function() {
if (!_pausedGraph) {
_pausedGraph = _stack[_index].graph;
}
},
resumeChangeDispatch: function() {
if (_pausedGraph) {
var previous = _pausedGraph;
_pausedGraph = null;
return change(previous, true);
}
},
undoAnnotation: function() {
var i = _index;
while (i >= 0) {
if (_stack[i].annotation) return _stack[i].annotation;
i--;
}
},
redoAnnotation: function() {
var i = _index + 1;
while (i <= _stack.length - 1) {
if (_stack[i].annotation) return _stack[i].annotation;
i++;
}
},
intersects: function(extent) {
return _tree.intersects(extent, _stack[_index].graph);
},
difference: function() {
var base = _stack[0].graph;
var head = _stack[_index].graph;
return coreDifference(base, head);
},
changes: function(action) {
var base = _stack[0].graph;
var head = _stack[_index].graph;
if (action) {
head = action(head);
}
var difference = coreDifference(base, head);
return {
modified: difference.modified(),
created: difference.created(),
deleted: difference.deleted()
};
},
hasChanges: function() {
return this.difference().length() > 0;
},
imageryUsed: function(sources) {
if (sources) {
_imageryUsed = sources;
return history;
} else {
var s = new Set();
_stack.slice(1, _index + 1).forEach(function(state) {
state.imageryUsed.forEach(function(source) {
if (source !== 'Custom') {
s.add(source);
}
});
});
if (window.mocha) {
var arr = [];
s.forEach(function(v) { arr.push(v); });
return arr;
} else {
return Array.from(s);
}
// var arr = _map(_stack.slice(1, _index + 1), 'imageryUsed');
// return _without(_uniq(_flatten(arr)), 'Custom');
}
},
// save the current history state
checkpoint: function(key) {
_checkpoints[key] = {
stack: _cloneDeep(_stack),
index: _index
};
return history;
},
// restore history state to a given checkpoint or reset completely
reset: function(key) {
if (key !== undefined && _checkpoints.hasOwnProperty(key)) {
_stack = _cloneDeep(_checkpoints[key].stack);
_index = _checkpoints[key].index;
} else {
_stack = [{graph: coreGraph()}];
_index = 0;
_tree = coreTree(_stack[0].graph);
_checkpoints = {};
}
dispatch.call('change');
return history;
},
toIntroGraph: function() {
var nextId = { n: 0, r: 0, w: 0 };
var permIds = {};
var graph = this.graph();
var baseEntities = {};
// clone base entities..
_forEach(graph.base().entities, function(entity) {
var copy = _cloneDeepWith(entity, customizer);
baseEntities[copy.id] = copy;
});
// replace base entities with head entities..
_forEach(graph.entities, function(entity, id) {
if (entity) {
var copy = _cloneDeepWith(entity, customizer);
baseEntities[copy.id] = copy;
} else {
delete baseEntities[id];
}
});
// swap temporary for permanent ids..
_forEach(baseEntities, function(entity) {
if (Array.isArray(entity.nodes)) {
entity.nodes = entity.nodes.map(function(node) {
return permIds[node] || node;
});
}
if (Array.isArray(entity.members)) {
entity.members = entity.members.map(function(member) {
member.id = permIds[member.id] || member.id;
return member;
});
}
});
return JSON.stringify({ dataIntroGraph: baseEntities });
function customizer(src) {
var copy = _omit(_cloneDeep(src), ['type', 'user', 'v', 'version', 'visible']);
if (_isEmpty(copy.tags)) {
delete copy.tags;
}
if (Array.isArray(copy.loc)) {
copy.loc[0] = +copy.loc[0].toFixed(6);
copy.loc[1] = +copy.loc[1].toFixed(6);
}
var match = src.id.match(/([nrw])-\d*/); // temporary id
if (match !== null) {
var nrw = match[1], permId;
do { permId = nrw + (++nextId[nrw]); }
while (baseEntities.hasOwnProperty(permId));
copy.id = permIds[src.id] = permId;
}
return copy;
}
},
toJSON: function() {
if (!this.hasChanges()) return;
var allEntities = {};
var baseEntities = {};
var base = _stack[0];
var s = _stack.map(function(i) {
var modified = [];
var deleted = [];
_forEach(i.graph.entities, function(entity, id) {
if (entity) {
var key = osmEntity.key(entity);
allEntities[key] = entity;
modified.push(key);
} else {
deleted.push(id);
}
// make sure that the originals of changed or deleted entities get merged
// into the base of the _stack after restoring the data from JSON.
if (id in base.graph.entities) {
baseEntities[id] = base.graph.entities[id];
}
if (entity && entity.nodes) {
// get originals of pre-existing child nodes
_forEach(entity.nodes, function(nodeId) {
if (nodeId in base.graph.entities) {
baseEntities[nodeId] = base.graph.entities[nodeId];
}
});
}
// get originals of parent entities too
_forEach(base.graph._parentWays[id], function(parentId) {
if (parentId in base.graph.entities) {
baseEntities[parentId] = base.graph.entities[parentId];
}
});
});
var x = {};
if (modified.length) x.modified = modified;
if (deleted.length) x.deleted = deleted;
if (i.imageryUsed) x.imageryUsed = i.imageryUsed;
if (i.annotation) x.annotation = i.annotation;
if (i.transform) x.transform = i.transform;
if (i.selectedIDs) x.selectedIDs = i.selectedIDs;
return x;
});
return JSON.stringify({
version: 3,
entities: Object.values(allEntities),
baseEntities: Object.values(baseEntities),
stack: s,
nextIDs: osmEntity.id.next,
index: _index
});
},
fromJSON: function(json, loadChildNodes) {
var h = JSON.parse(json);
var loadComplete = true;
osmEntity.id.next = h.nextIDs;
_index = h.index;
if (h.version === 2 || h.version === 3) {
var allEntities = {};
h.entities.forEach(function(entity) {
allEntities[osmEntity.key(entity)] = osmEntity(entity);
});
if (h.version === 3) {
// This merges originals for changed entities into the base of
// the _stack even if the current _stack doesn't have them (for
// example when iD has been restarted in a different region)
var baseEntities = h.baseEntities.map(function(d) { return osmEntity(d); });
_stack[0].graph.rebase(baseEntities, _map(_stack, 'graph'), true);
_tree.rebase(baseEntities, true);
// When we restore a modified way, we also need to fetch any missing
// childnodes that would normally have been downloaded with it.. #2142
if (loadChildNodes) {
var osm = context.connection();
var baseWays = baseEntities.filter(function(e) { return e.type === 'way'; });
var nodes = _flatten(_uniq(_map(baseWays, 'nodes')));
var missing = nodes.filter(function(n) { return !_stack[0].graph.hasEntity(n); });
if (!_isEmpty(missing) && osm) {
loadComplete = false;
context.redrawEnable(false);
var loading = uiLoading(context).blocking(true);
context.container().call(loading);
var childNodesLoaded = function(err, result) {
if (!err) {
var visible = _groupBy(result.data, 'visible');
if (!_isEmpty(visible.true)) {
missing = _difference(missing, _map(visible.true, 'id'));
_stack[0].graph.rebase(visible.true, _map(_stack, 'graph'), true);
_tree.rebase(visible.true, true);
}
// fetch older versions of nodes that were deleted..
_forEach(visible.false, function(entity) {
osm.loadEntityVersion(entity.id, +entity.version - 1, childNodesLoaded);
});
}
if (err || _isEmpty(missing)) {
loading.close();
context.redrawEnable(true);
dispatch.call('change');
dispatch.call('restore', this);
}
};
osm.loadMultiple(missing, childNodesLoaded);
}
}
}
_stack = h.stack.map(function(d) {
var entities = {}, entity;
if (d.modified) {
d.modified.forEach(function(key) {
entity = allEntities[key];
entities[entity.id] = entity;
});
}
if (d.deleted) {
d.deleted.forEach(function(id) {
entities[id] = undefined;
});
}
return {
graph: coreGraph(_stack[0].graph).load(entities),
annotation: d.annotation,
imageryUsed: d.imageryUsed,
transform: d.transform,
selectedIDs: d.selectedIDs
};
});
} else { // original version
_stack = h.stack.map(function(d) {
var entities = {};
for (var i in d.entities) {
var entity = d.entities[i];
entities[i] = entity === 'undefined' ? undefined : osmEntity(entity);
}
d.graph = coreGraph(_stack[0].graph).load(entities);
return d;
});
}
var transform = _stack[_index].transform;
if (transform) {
context.map().transformEase(transform, 0); // 0 = immediate, no easing
}
if (loadComplete) {
dispatch.call('change');
dispatch.call('restore', this);
}
return history;
},
save: function() {
if (lock.locked()) context.storage(getKey('saved_history'), history.toJSON() || null);
return history;
},
clearSaved: function() {
context.debouncedSave.cancel();
if (lock.locked()) context.storage(getKey('saved_history'), null);
return history;
},
lock: function() {
return lock.lock();
},
unlock: function() {
lock.unlock();
},
// is iD not open in another window and it detects that
// there's a history stored in localStorage that's recoverable?
restorableChanges: function() {
return lock.locked() && !!context.storage(getKey('saved_history'));
},
// load history from a version stored in localStorage
restore: function() {
if (!lock.locked()) return;
var json = context.storage(getKey('saved_history'));
if (json) history.fromJSON(json, true);
},
_getKey: getKey
};
history.reset();
return utilRebind(history, dispatch, 'on');
}