-
Notifications
You must be signed in to change notification settings - Fork 1
/
TimelineSliderControl.js
549 lines (509 loc) · 15.5 KB
/
TimelineSliderControl.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
/* global L */
/*
* @class
* @extends L.Control
*/
L.TimelineSliderControl = L.Control.extend({
/**
* @constructor
* @param {Number} [options.duration=10000] The amount of time a complete
* playback should take. Not guaranteed; if there's a lot of data or
* complicated rendering, it will likely wind up taking longer.
* @param {Boolean} [options.enableKeyboardControls=false] Allow playback to
* be controlled using the spacebar (play/pause) and right/left arrow keys
* (next/previous).
* @param {Boolean} [options.enablePlayback=true] Show playback controls (i.e.
* prev/play/pause/next).
* @param {Function} [options.formatOutput] A function which takes the current
* time value (usually a Unix timestamp) and outputs a string that is
* displayed beneath the control buttons.
* @param {Boolean} [options.showTicks=true] Show ticks on the timeline (if
* the browser supports it).
* @param {Boolean} [options.waitToUpdateMap=false] Wait until the user is
* finished changing the date to update the map. By default, both the map and
* the date update for every change. With complex data, this can slow things
* down, so set this to true to only update the displayed date.
* @param {Number} [options.start] The start time of the timeline. If unset,
* this will be calculated automatically based on the timelines registered to
* this control.
* @param {Number} [options.end] The end time of the timeline. If unset, this
* will be calculated automatically based on the timelines registered to this
* control.
*/
initialize(options = {}) {
const defaultOptions = {
duration: 10000,
enableKeyboardControls: false,
enablePlayback: true,
formatOutput: output => `${output || ''}`,
showTicks: true,
waitToUpdateMap: false,
position: 'bottomleft',
steps: 1000,
};
this.timelines = [];
L.Util.setOptions(this, defaultOptions);
L.Util.setOptions(this, options);
if (typeof options.start !== 'undefined') {
this.start = options.start;
}
if (typeof options.end !== 'undefined') {
this.end = options.end;
}
},
/* INTERNAL API *************************************************************/
/**
* @private
* @returns {Number[]} A flat, sorted list of all the times of all layers
*/
_getTimes() {
const times = [];
this.timelines.forEach((timeline) => {
const timesInRange = timeline.times
.filter(time => time >= this.start && time <= this.end);
times.push(...timesInRange);
});
if (times.length) {
times.sort((a, b) => a - b);
const dedupedTimes = [times[0]];
times.reduce((a, b) => {
if (a !== b) {
dedupedTimes.push(b);
}
return b;
});
return dedupedTimes;
}
return times;
},
/**
* Adjusts start/end/step size/etc. Should be called if any of those might
* change (e.g. when adding a new layer).
*
* @private
*/
_recalculate() {
const manualStart = typeof this.options.start !== 'undefined';
const manualEnd = typeof this.options.end !== 'undefined';
const duration = this.options.duration;
let min = Infinity;
let max = -Infinity;
this.timelines.forEach((timeline) => {
if (timeline.start < min) {
min = timeline.start;
}
if (timeline.end > max) {
max = timeline.end;
}
});
if (!manualStart) {
this.start = min;
this._timeSlider.min = min === Infinity ? 0 : min;
this._timeSlider.value = this._timeSlider.min;
}
if (!manualEnd) {
this.end = max;
this._timeSlider.max = max === -Infinity ? 0 : max;
}
this._stepSize = Math.max(1, (this.end - this.start) / this.options.steps);
this._stepDuration = Math.max(1, duration / this.options.steps);
},
/**
* If `mode` is 0, finds the event nearest to `findTime`.
*
* If `mode` is 1, finds the event immediately after `findTime`.
*
* If `mode` is -1, finds the event immediately before `findTime`.
*
* @private
* @param {Number} findTime The time to find events around
* @param {Number} mode The operating mode. See main function description.
* @returns {Number} The time of the nearest event.
*/
_nearestEventTime(findTime, mode = 0) {
const times = this._getTimes();
let retNext = false;
let lastTime = times[0];
for (let i = 1; i < times.length; i++) {
const time = times[i];
if (retNext) {
return time;
}
if (time >= findTime) {
if (mode === -1) {
return lastTime;
}
// else if (mode === 1) {
if (time === findTime) {
retNext = true;
} else {
return time;
}
// }
// this isn't actually used anywhere, and it's a private method
// so .. commenting out
// else {
// const prevDiff = Math.abs(findTime - lastTime);
// const nextDiff = Math.abs(findTime - time);
// return prevDiff < nextDiff ? lastTime : time;
// }
}
lastTime = time;
}
return lastTime;
},
/* DOM CREATION & INTERACTION ***********************************************/
/**
* Create all of the DOM for the control.
*
* @private
*/
_createDOM() {
const classes = [
'leaflet-control-layers',
'leaflet-control-layers-expanded',
'leaflet-timeline-control',
];
const container = L.DomUtil.create('div', classes.join(' '));
// Create div for vis-Timeline
const visTimeline = L.DomUtil.create('div', 'vis-t', container)
visTimeline.setAttribute("id", "vis-timeline");
this.container = container;
if (this.options.enablePlayback) {
const sliderCtrlC = L.DomUtil.create(
'div',
'sldr-ctrl-container',
container,
);
const buttonContainer = L.DomUtil.create(
'div',
'button-container',
sliderCtrlC,
);
this._makeButtons(buttonContainer);
if (this.options.enableKeyboardControls) {
this._addKeyListeners();
}
this._makeOutput(sliderCtrlC);
}
this._makeSlider(container);
if (this.options.showTicks) {
this._buildDataList(container);
}
},
/**
* Add keyboard listeners for keyboard control
*
* @private
*/
_addKeyListeners() {
this._listener = (...args) => this._onKeydown(...args);
document.addEventListener('keydown', this._listener);
},
/**
* Remove keyboard listeners
*
* @private
*/
_removeKeyListeners() {
document.removeEventListener('keydown', this._listener);
},
/**
* Constructs a <datalist>, for showing ticks on the range input.
*
* @private
* @param {HTMLElement} container The container to which to add the datalist
*/
_buildDataList(container) {
this._datalist = L.DomUtil.create('datalist', '', container);
const idNum = Math.floor(Math.random() * 1000000);
this._datalist.id = `timeline-datalist-${idNum}`;
this._timeSlider.setAttribute('list', this._datalist.id);
this._rebuildDataList();
},
/**
* Reconstructs the <datalist>. Should be called when new data comes in.
*/
_rebuildDataList() {
//Old Code
const datalist = this._datalist;
while (datalist.firstChild) {
datalist.removeChild(datalist.firstChild);
}
const datalistSelect = L.DomUtil.create('select', '', this._datalist);
this._getTimes().forEach((time) => {
L.DomUtil.create('option', '', datalistSelect).value = time;
});
// Thegsi code. Add table with marks for temporal divisions
// var max = this._timeSlider.max
// var min = this._timeSlider.min
// var width = max - min;
// var times = this._getTimes();
//
// times.forEach((time, i) => {
// var timeClass = 'time-' + time
// L.DomUtil.create('td', timeClass, this.timeVisualise);
// var cell = time - times[i-1] || 0
// var cellPercent = cell / width * 100;
// var cellPercentAdj = cellPercent
//
// d3.select('.' + timeClass)
// // .style('width', function() { return 1 / length * 100 + "%"; })
// .style('width', cellPercentAdj.toFixed(2).toString() + '%')
// .style('height', '100%')
// .style('background-color', 'white')
//
// });
},
/**
* Makes a button with the passed name as a class, which calls the
* corresponding function when clicked. Attaches the button to container.
*
* @private
* @param {HTMLElement} container The container to which to add the button
* @param {String} name The class to give the button and the function to call
*/
_makeButton(container, name) {
const button = L.DomUtil.create('button', name, container);
button.addEventListener('click', () => this[name]());
L.DomEvent.disableClickPropagation(button);
},
/**
* Makes the prev, play, pause, and next buttons
*
* @private
* @param {HTMLElement} container The container to which to add the buttons
*/
_makeButtons(container) {
this._makeButton(container, 'prev');
this._makeButton(container, 'play');
this._makeButton(container, 'pause');
this._makeButton(container, 'next');
},
/**
* DOM event handler to disable dragging on map
*
* @private
*/
_disableMapDragging() {
this.map.dragging.disable();
},
/**
* DOM event handler to enable dragging on map
*
* @private
*/
_enableMapDragging() {
this.map.dragging.enable();
},
/**
* Creates the range input
*
* @private
* @param {HTMLElement} container The container to which to add the input
*/
_makeSlider(container) {
const sliderContainer = L.DomUtil.create('div', 'slider-container', container);
this._makeTimeVisualise(sliderContainer)
const slider = L.DomUtil.create('input', 'time-slider', sliderContainer);
slider.type = 'range';
slider.min = this.start || 0;
slider.max = this.end || 0;
slider.value = this.start || 0;
this._timeSlider = slider;
// register events using leaflet for easy removal
L.DomEvent.on(this._timeSlider, 'change input', this._sliderChanged, this);
L.DomEvent.on(this._timeSlider, 'pointerdown mousedown touchstart', this._disableMapDragging, this);
L.DomEvent.on(document, 'pointerup mouseup touchend', this._enableMapDragging, this);
},
_makeTimeVisualise(sliderContainer) {
const timeVisualise = L.DomUtil.create(
'table',
'chart',
sliderContainer
)
this.timeVisualise = timeVisualise;
},
_makeOutput(container) {
this._output = L.DomUtil.create('output', 'time-text', container);
this._output.innerHTML = this.options.formatOutput(this.start);
},
_onKeydown(e) {
switch (e.keyCode || e.which) {
case 37:
this.prev();
break;
case 39:
this.next();
break;
case 32:
this.toggle();
break;
default:
return;
}
e.preventDefault();
},
_sliderChanged(e) {
const time = parseFloat(+e.target.value, 10);
this.time = time;
if (!this.options.waitToUpdateMap || e.type === 'change') {
this.timelines.forEach(timeline => timeline.setTime(time));
}
if (this._output) {
this._output.innerHTML = this.options.formatOutput(time);
}
},
_resetIfTimelinesChanged(oldTimelineCount) {
if (this.timelines.length !== oldTimelineCount) {
this._recalculate();
if (this.options.showTicks) {
this._rebuildDataList();
}
this.setTime(this.start);
}
},
/* EXTERNAL API *************************************************************/
/**
* Register timeline layers with this control. This could change the start and
* end points of the timeline (unless manually set). It will also reset the
* playback.
*
* @param {...L.Timeline} timelines The `L.Timeline`s to register
*/
addTimelines(timelines) {
if (!timelines.length) timelines = [timelines]
this.pause();
const timelineCount = this.timelines.length;
timelines.forEach((timeline) => {
if (this.timelines.indexOf(timeline) === -1) {
this.timelines.push(timeline);
}
});
this._resetIfTimelinesChanged(timelineCount);
},
/**
* Unregister timeline layers with this control. This could change the start
* and end points of the timeline unless manually set. It will also reset the
* playback.
*
* @param {...L.Timeline} timelines The `L.Timeline`s to unregister
*/
removeTimelines(...timelines) {
this.pause();
const timelineCount = this.timelines.length;
timelines.forEach((timeline) => {
const index = this.timelines.indexOf(timeline);
if (index !== -1) {
this.timelines.splice(index, 1);
}
});
this._resetIfTimelinesChanged(timelineCount);
},
/**
* Toggles play/pause state.
*/
toggle() {
if (this._playing) {
this.pause();
} else {
this.play();
}
},
/**
* Pauses playback and goes to the previous event.
*/
prev() {
this.pause();
const prevTime = this._nearestEventTime(this.time, -1);
this._timeSlider.value = prevTime;
this.setTime(prevTime);
},
/**
* Pauses playback.
*/
pause(fromSynced) {
clearTimeout(this._timer);
this._playing = false;
this.container.classList.remove('playing');
if (this.syncedControl && !fromSynced) {
this.syncedControl.map(function(control) {
control.pause(true);
})
}
},
/**
* Starts playback.
*/
play(fromSynced) {
clearTimeout(this._timer);
if (parseFloat(this._timeSlider.value, 10) === this.end) {
this._timeSlider.value = this.start;
}
this._timeSlider.value = parseFloat(this._timeSlider.value, 10) +
this._stepSize;
this.setTime(this._timeSlider.value);
if (parseFloat(this._timeSlider.value, 10) === this.end) {
this._playing = false;
this.container.classList.remove('playing');
} else {
this._playing = true;
this.container.classList.add('playing');
this._timer = setTimeout(() => this.play(true), this._stepDuration);
}
if (this.syncedControl && !fromSynced) {
this.syncedControl.map(function(control) {
control.play(true);
});
}
},
/**
* Pauses playback and goes to the next event.
*/
next() {
this.pause();
const nextTime = this._nearestEventTime(this.time, 1);
this._timeSlider.value = nextTime;
this.setTime(nextTime);
},
/**
* Set the time displayed.
*
* @param {Number} time The time to set
*/
setTime(time) {
if (this._timeSlider) this._timeSlider.value = +time;
this._sliderChanged({
type: 'change',
target: {
value: time
},
});
},
onAdd(map) {
this.map = map;
this._createDOM();
this.setTime(this.start);
return this.container;
},
onRemove() {
/* istanbul ignore else */
if (this.options.enableKeyboardControls) {
this._removeKeyListeners();
}
// cleanup events registered in _makeSlider
L.DomEvent.off(this._timeSlider, 'change input', this._sliderChanged, this);
L.DomEvent.off(this._timeSlider, 'pointerdown mousedown touchstart', this._disableMapDragging, this);
L.DomEvent.off(document, 'pointerup mouseup touchend', this._enableMapDragging, this);
// make sure that dragging is restored to enabled state
this._enableMapDragging();
},
syncControl(controlToSync) {
if (!this.syncedControl) {
this.syncedControl = [];
}
this.syncedControl.push(syncedControl);
}
});
L.timelineSliderControl = (timeline, start, end, timelist) =>
new L.TimelineSliderControl(timeline, start, end, timelist);