forked from PeWu/osm-history
-
Notifications
You must be signed in to change notification settings - Fork 0
/
history-ctrl.js
595 lines (529 loc) · 16.5 KB
/
history-ctrl.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
/**
* For the given point, returns square bounds around it.
*/
extendBounds = function(latLng) {
var DELTA = 0.001;
var deltaLng =
(Math.asin(
Math.sin((DELTA * Math.PI) / 180) / Math.cos((latLng.lat * Math.PI) / 180)
) *
180) /
Math.PI;
return L.latLngBounds(
[latLng.lat - DELTA, latLng.lng - deltaLng],
[latLng.lat + DELTA, latLng.lng + deltaLng]
);
};
/**
* Returns a list of tags with previous and next values that are changed.
* A previous or next value is undefined if it doesn't exist.
*/
tagsDiff = function(prev, next) {
var allTags = new Map();
if (prev?.tag) {
prev.tag.forEach(tag => {
var entry = next?.tag ? next.tag.find(element => element._k === tag._k) : null;
if (!entry) {
allTags.set(tag._k, {prev: tag._v});
}
})
}
if (next.tag) {
next.tag.forEach(tag => {
var entry = prev?.tag ? prev.tag.find(element => element._k === tag._k) : null;
if (entry) {
if (entry._v != tag._v) {
allTags.set(tag._k, { prev: entry._v, next: tag._v });
}
} else {
allTags.set(tag._k, {next: tag._v});
}
})
}
return [...allTags].sort().map(entry => {
var prev = entry[1].prev;
var next = entry[1].next;
return {
key: entry[0],
prev: prev,
next: next,
};
});
};
/**
* Returns an object containing differences between the previous and next
* versions of an object.
*/
objDiff = function(prev, next) {
var allTagsList = tagsDiff(prev, next);
var coordinates = {
prev: latLngFromNode(prev),
next: latLngFromNode(next),
};
const prevNodesSet = new Set();
const nextNodesSet = new Set();
prev?.nd?.forEach(prevNd => prevNodesSet.add(prevNd._ref));
next?.nd?.forEach(nextNd => nextNodesSet.add(nextNd._ref));
const nodesList = [];
prev?.nd?.forEach(prevNd => {
if (!nextNodesSet.has(prevNd._ref)) {
nodesList.push({ key: 'nd', prev: prevNd._ref, additional: '' });
}
});
next?.nd?.forEach(nextNd => {
if (!prevNodesSet.has(nextNd._ref)) {
nodesList.push({ key: 'nd', next: nextNd._ref, additional: '' });
}
});
const prevMembersMap = new Map();
const nextMembersMap = new Map();
const createKey = (member) => `${member._type}:${member._ref}`;
const parseKey = (key) => {
const [type, ref] = key.split(':');
return {
_type: type,
_ref: ref
};
};
prev?.member?.forEach(prevMember => {
const key = createKey(prevMember);
if (!prevMembersMap.has(key)) {
prevMembersMap.set(key, new Set());
}
const rolesSet = prevMembersMap.get(key);
rolesSet.add(prevMember._role);
});
next?.member?.forEach(nextMember => {
const key = createKey(nextMember);
if (!nextMembersMap.has(key)) {
nextMembersMap.set(key, new Set());
}
const rolesSet = nextMembersMap.get(key);
rolesSet.add(nextMember._role);
});
const membersList = [];
prev?.member?.forEach(prevMember => {
const key = createKey(prevMember);
if (!nextMembersMap.has(key)) {
membersList.push({ key: prevMember._type, prev: prevMember._role, additional: prevMember._ref });
prevMembersMap.delete(key);
}
});
next?.member?.forEach(nextMember => {
const key = createKey(nextMember);
if (!prevMembersMap.has(key)) {
membersList.push({ key: nextMember._type, next: nextMember._role, additional: nextMember._ref });
nextMembersMap.delete(key);
}
});
prevMembersMap.forEach((prevRoles, key) => {
const parsedKey = parseKey(key);
var nextRoles = nextMembersMap.get(key);
const itemsToDelete = [...prevRoles].filter(prevRole => nextRoles.has(prevRole));
itemsToDelete.forEach(itemToDelete => {
prevRoles.delete(itemToDelete);
nextRoles.delete(itemToDelete);
});
var difference = Math.abs(prevRoles.size - nextRoles.size);
if (prevRoles.size < nextRoles.size) {
for (let i = 0; i < difference; i++) {
const nextIterator = nextRoles.values();
const nextElement = nextIterator.next().value;
nextRoles.delete(nextElement);
membersList.push({ key: parsedKey._type, next: nextElement, additional: parsedKey._ref });
}
} else if (nextRoles.size < prevRoles.size) {
for (let i = 0; i < difference; i++) {
const prevIterator = prevRoles.values();
const prevElement = prevIterator.next().value;
prevRoles.delete(prevElement);
membersList.push({ key: parsedKey._type, prev: prevElement, additional: parsedKey._ref });
}
}
const prevIterator = prevRoles.values();
const nextIterator = nextRoles.values();
for (let i = 0; i < nextRoles.size; i++) {
const prevElement = prevIterator.next().value;
const nextElement = nextIterator.next().value;
membersList.push({ key: parsedKey._type, prev: prevElement, next: nextElement, additional: parsedKey._ref });
}
});
return {
tags: allTagsList,
coordinates: coordinates,
nodesList: nodesList,
membersList: membersList,
};
};
/** Filters out history entries that do not modify any tag. */
filterTagHistory = function(history) {
return history.filter(entry =>
entry.diff.tags.some(tag => tag.prev != tag.next)
);
};
/**
* Controller for the history pages (way, node, relation).
*/
HistoryCtrl = function(
$rootScope,
$q,
$routeParams,
$timeout,
leafletBoundsHelpers,
osmService
) {
if (!$routeParams.id || !$routeParams.type) {
return;
}
this.id = $routeParams.id;
this.type = $routeParams.type;
this.ngQ = $q;
this.ngTimeout = $timeout;
this.leafletBoundsHelpers = leafletBoundsHelpers;
this.osmService = osmService;
this.numberOfDisplayedChanges = 50;
/** Full and partial history lists. */
this.fullHistory = [];
this.history = [];
/** History of tag changes. */
this.tagHistory = [];
/** Hide versions without tag changes. */
this.hideTagless = false;
$rootScope.title = `OSM history: ${this.type} ${this.id}`;
this.mapTiles = {
url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
options: {
maxZoom: 19,
attribution:
'© <a href="http://openstreetmap.org">OpenStreetMap</a> contributors',
},
};
this.mapControls = {
fullscreen: {
position: 'topleft',
},
};
var path = `${this.type}/${this.id}/history`;
this.osmService
.fetchOsm(path, this.type)
.then(history => {
this.fullHistory = history;
this.updateHistory();
})
.catch(error => {
this.error = error;
});
// Fetch full view of a relation and calculate its bounds to display a link
// to JOSM.
if (this.type == 'relation') {
var path = `relation/${this.id}/full`;
this.osmService.fetchOsm(path, 'node').then(memberNodes => {
if (memberNodes && memberNodes.length) {
var bounds = getBounds(memberNodes);
this.extendedBounds = L.latLngBounds(
extendBounds(bounds.getSouthWest()).getSouthWest(),
extendBounds(bounds.getNorthEast()).getNorthEast()
);
}
});
}
};
/** Updates internal buffers with selected window of history */
HistoryCtrl.prototype.updateHistory = function() {
var clippedHistory = this.fullHistory.slice(-this.numberOfDisplayedChanges);
var prev = null;
if (this.numberOfDisplayedChanges < this.fullHistory.length) {
prev = this.fullHistory[this.fullHistory.length - this.numberOfDisplayedChanges - 1];
}
this.history = clippedHistory.map(obj => {
var diff = objDiff(prev, obj);
prev = obj;
return {
obj: obj,
diff: diff,
};
});
this.history.reverse();
var currentObj = this.history[0].obj;
this.deleted = currentObj._visible == 'false';
if (this.type == 'node' && !this.deleted) {
var latLng = latLngFromNode(currentObj);
this.extendedBounds = extendBounds(latLng);
}
this.tagHistory = filterTagHistory(this.history);
this.populateChangesets();
this.populateWayHistory().then(() => {
this.populateWayMapData();
// Calculate bounds for JOSM link.
if (this.type == 'way' && this.history[0].nodes) {
var bounds = getBounds(this.history[0].nodes);
this.extendedBounds = L.latLngBounds(
extendBounds(bounds.getSouthWest()).getSouthWest(),
extendBounds(bounds.getNorthEast()).getNorthEast()
);
}
});
this.populateMapData();
}
/** Returns the history list to be displayed. */
HistoryCtrl.prototype.getHistory = function() {
return this.hideTagless ? this.tagHistory : this.history;
};
/** Loads more changes */
HistoryCtrl.prototype.loadMore = function() {
this.numberOfDisplayedChanges += 50;
if (this.numberOfDisplayedChanges > this.fullHistory.length) {
this.numberOfDisplayedChanges = this.fullHistory.length;
}
this.updateHistory();
};
/** Loads all remaining changes */
HistoryCtrl.prototype.loadAll = function() {
this.numberOfDisplayedChanges = this.fullHistory.length;
this.updateHistory();
};
/**
* Fetches changeset data for all changes.
* This is used to display changeset messages.
*/
HistoryCtrl.prototype.populateChangesets = function() {
var changesets = this.history.map(entry => entry.obj._changeset);
var path = `changesets?changesets=${changesets.join(',')}`;
this.osmService.fetchOsm(path, 'changeset').then(changesets => {
var changesetMap = new Map();
changesets.forEach(cs => changesetMap.set(cs._id, cs));
this.history.forEach(entry => {
entry.changeset = changesetMap.get(entry.obj._changeset);
});
});
};
/**
* Returns the link to open the JOSM editor with extendedBounds around
* the currently viewed object.
*/
HistoryCtrl.prototype.getJosmLink = function() {
if (!this.extendedBounds) {
return '';
}
return (
'http://localhost:8111/load_and_zoom' +
`?left=${this.extendedBounds.getWest()}` +
`&right=${this.extendedBounds.getEast()}` +
`&top=${this.extendedBounds.getNorth()}` +
`&bottom=${this.extendedBounds.getSouth()}` +
`&select=${this.type[0]}${this.id}`
);
};
/**
* Given the full history of nodes, returns the view of the given node
* at the given changeset.
*/
getHistoricalNode = function(nodeHistory, nodeId, changeset) {
return nodeHistory[nodeId].find(
node => parseInt(node._changeset) <= parseInt(changeset)
);
};
/**
* Returns lists of changed way segments based on the state of the way
* before and after the change.
* @param prev list of nodes before the change.
* @param next list of nodes after the change.
* @return 3 lists of segments (from node, to node): added, removed
* and unchanged.
*/
nodeListDiff = function(prev, next) {
var prevIds = prev && prev.map(node => node._id);
var nextIds = next && next.map(node => node._id);
var prevIdsSet = new Set(prevIds);
var nextIdsSet = new Set(nextIds);
var removedIds = new Set([...prevIdsSet].filter(x => !nextIdsSet.has(x)));
var addedIds = new Set([...nextIdsSet].filter(x => !prevIdsSet.has(x)));
if ((!prev || prev.length < 2) && (!next || next.length < 2)) {
return null;
}
if (!prev || prev.length < 2) {
return {
added: getSegments(next),
};
}
if (!next || next.length < 2) {
return {
removed: getSegments(prev),
};
}
var added = [];
var removed = [];
var unchanged = [];
var prevIt = 0;
var nextIt = 0;
// Iterate over both previous and next lists of nodes and mark added,
// removed and unchanged segments.
while (prevIt < prev.length || nextIt < next.length) {
var startPrev = prev[prevIt - 1];
var startNext = next[nextIt - 1];
var endPrev = prev[prevIt];
var endNext = next[nextIt];
var startSameId = startPrev && startNext && startPrev._id == startNext._id;
var endSameId = endPrev && endNext && endPrev._id == endNext._id;
var startEqual =
startSameId &&
startPrev._lat == startNext._lat &&
startPrev._lon == startNext._lon;
var endEqual =
endSameId && endPrev._lat == endNext._lat && endPrev._lon == endNext._lon;
if (startEqual && endEqual) {
unchanged.push({ from: startPrev, to: endPrev });
prevIt++;
nextIt++;
} else {
if (endSameId || (endPrev && removedIds.has(endPrev._id)) || !endNext) {
if (startPrev) {
removed.push({ from: startPrev, to: endPrev });
}
prevIt++;
}
if (endSameId || (endNext && addedIds.has(endNext._id)) || !endPrev) {
if (startNext) {
added.push({ from: startNext, to: endNext });
}
nextIt++;
}
// Changed order of nodes.
if (
endPrev &&
endNext &&
!endSameId &&
!removedIds.has(endPrev._id) &&
!addedIds.has(endNext._id)
) {
if (startPrev) {
removed.push({ from: startPrev, to: endPrev });
}
if (startNext) {
added.push({ from: startNext, to: endNext });
}
prevIt++;
nextIt++;
}
}
}
return {
added: added,
removed: removed,
unchanged: unchanged,
};
};
/**
* Fetches node history for all historical nodes of a way and populates the
* nodeListDiff for all changes. The nodeListDiff field contains lists of
* added, removed and unchanged segments of the way.
* Returns a promise that is resolved when all data has been populated.
*/
HistoryCtrl.prototype.populateWayHistory = function() {
var nodes = new Set();
this.history.forEach(change => {
if (change.obj.nd) {
change.obj.nd.forEach(node => nodes.add(node._ref));
}
});
var nodeHistory = {};
var nodePromises = [...nodes].map(nodeId => {
var path = `node/${nodeId}/history`;
return this.osmService.fetchOsm(path, 'node').then(history => {
history.reverse();
nodeHistory[nodeId] = history;
});
});
return this.ngQ.all(nodePromises).then(() => {
this.history.forEach(change => {
if (change.obj.nd) {
change.nodes = change.obj.nd.map(node =>
getHistoricalNode(nodeHistory, node._ref, change.obj._changeset)
);
// There are cases where a way from changeset X contains a node N
// and the history of node N starts from a changeset later than X.
// In this case, we ignore such nodes for rendering.
// E.g. way/3323922
change.nodes = change.nodes.filter(n => !!n);
}
});
var reverseHistory = this.history.slice(0).reverse();
var prev = null;
reverseHistory.forEach(change => {
change.nodeListDiff = nodeListDiff(prev && prev.nodes, change.nodes);
prev = change;
});
});
};
/** Creates a line to be drawn on a map. */
createLine = function(segment, color) {
return {
type: 'polyline',
weight: 5,
color: color,
opacity: 0.7,
latlngs: [latLngFromNode(segment.from), latLngFromNode(segment.to)],
};
};
/** Adds way data to be rendered on a map for each change. */
HistoryCtrl.prototype.populateWayMapData = function() {
this.history.forEach(change => {
if (!change.nodeListDiff) return;
var added = change.nodeListDiff.added || [];
var removed = change.nodeListDiff.removed || [];
var unchanged = change.nodeListDiff.unchanged || [];
var allSegments = added.concat(removed).concat(unchanged);
if (!added.length && !removed.length) return;
var allNodes = allSegments
.map(s => s.from)
.concat(allSegments.map(s => s.to));
var bounds = getBounds(allNodes);
var paths = []
.concat(unchanged.map(segment => createLine(segment, '#444')))
.concat(removed.map(segment => createLine(segment, '#a00')))
.concat(added.map(segment => createLine(segment, '#0a0')));
change.mapData = {
bounds: this.leafletBoundsHelpers.createBoundsFromLeaflet(bounds),
paths: paths,
};
});
};
/** Adds node data to be rendered on a map for each change. */
HistoryCtrl.prototype.populateMapData = function() {
this.history.forEach(change => {
var prev = change.diff.coordinates.prev;
var next = change.diff.coordinates.next;
if ((!prev && !next) || (prev && prev.equals(next))) return;
var bounds = L.latLngBounds();
bounds.extend(prev);
bounds.extend(next);
change.mapData = {
bounds: this.leafletBoundsHelpers.createBoundsFromLeaflet(bounds),
paths: {},
};
if (prev) {
change.mapData.paths.prev = {
type: 'circleMarker',
radius: 5,
weight: 3,
color: '#a00',
latlngs: prev,
};
}
if (next) {
change.mapData.paths.next = {
type: 'circleMarker',
radius: 5,
weight: 3,
color: '#0a0',
latlngs: next,
};
}
});
};
/**
* Formats the coordinates as string.
*/
HistoryCtrl.prototype.formatCoords = function(coords) {
return coords && `${coords.lat}, ${coords.lng}`;
};