-
Notifications
You must be signed in to change notification settings - Fork 319
/
Core.js
1403 lines (1229 loc) · 54.3 KB
/
Core.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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Emitter from 'component-emitter';
import Hammer from '../module/hammer';
import * as hammerUtil from '../hammerUtil';
import util from '../util';
import TimeAxis from './component/TimeAxis';
import Activator from '../shared/Activator';
import * as DateUtil from './DateUtil';
import CustomTime from './component/CustomTime';
import './component/css/animation.css';
import './component/css/currenttime.css';
import './component/css/panel.css';
import './component/css/pathStyles.css';
import './component/css/timeline.css';
import '../shared/bootstrap.css';
/**
* Create a timeline visualization
* @constructor Core
*/
class Core {
/**
* Create the main DOM for the Core: a root panel containing left, right,
* top, bottom, content, and background panel.
* @param {Element} container The container element where the Core will
* be attached.
* @protected
*/
_create(container) {
this.dom = {};
this.dom.container = container;
this.dom.container.style.position = 'relative';
this.dom.root = document.createElement('div');
this.dom.background = document.createElement('div');
this.dom.backgroundVertical = document.createElement('div');
this.dom.backgroundHorizontal = document.createElement('div');
this.dom.centerContainer = document.createElement('div');
this.dom.leftContainer = document.createElement('div');
this.dom.rightContainer = document.createElement('div');
this.dom.center = document.createElement('div');
this.dom.left = document.createElement('div');
this.dom.right = document.createElement('div');
this.dom.top = document.createElement('div');
this.dom.bottom = document.createElement('div');
this.dom.shadowTop = document.createElement('div');
this.dom.shadowBottom = document.createElement('div');
this.dom.shadowTopLeft = document.createElement('div');
this.dom.shadowBottomLeft = document.createElement('div');
this.dom.shadowTopRight = document.createElement('div');
this.dom.shadowBottomRight = document.createElement('div');
this.dom.rollingModeBtn = document.createElement('div');
this.dom.loadingScreen = document.createElement('div');
this.dom.root.className = 'vis-timeline';
this.dom.background.className = 'vis-panel vis-background';
this.dom.backgroundVertical.className = 'vis-panel vis-background vis-vertical';
this.dom.backgroundHorizontal.className = 'vis-panel vis-background vis-horizontal';
this.dom.centerContainer.className = 'vis-panel vis-center';
this.dom.leftContainer.className = 'vis-panel vis-left';
this.dom.rightContainer.className = 'vis-panel vis-right';
this.dom.top.className = 'vis-panel vis-top';
this.dom.bottom.className = 'vis-panel vis-bottom';
this.dom.left.className = 'vis-content';
this.dom.center.className = 'vis-content';
this.dom.right.className = 'vis-content';
this.dom.shadowTop.className = 'vis-shadow vis-top';
this.dom.shadowBottom.className = 'vis-shadow vis-bottom';
this.dom.shadowTopLeft.className = 'vis-shadow vis-top';
this.dom.shadowBottomLeft.className = 'vis-shadow vis-bottom';
this.dom.shadowTopRight.className = 'vis-shadow vis-top';
this.dom.shadowBottomRight.className = 'vis-shadow vis-bottom';
this.dom.rollingModeBtn.className = 'vis-rolling-mode-btn';
this.dom.loadingScreen.className = 'vis-loading-screen';
this.dom.root.appendChild(this.dom.background);
this.dom.root.appendChild(this.dom.backgroundVertical);
this.dom.root.appendChild(this.dom.backgroundHorizontal);
this.dom.root.appendChild(this.dom.centerContainer);
this.dom.root.appendChild(this.dom.leftContainer);
this.dom.root.appendChild(this.dom.rightContainer);
this.dom.root.appendChild(this.dom.top);
this.dom.root.appendChild(this.dom.bottom);
this.dom.root.appendChild(this.dom.rollingModeBtn);
this.dom.centerContainer.appendChild(this.dom.center);
this.dom.leftContainer.appendChild(this.dom.left);
this.dom.rightContainer.appendChild(this.dom.right);
this.dom.centerContainer.appendChild(this.dom.shadowTop);
this.dom.centerContainer.appendChild(this.dom.shadowBottom);
this.dom.leftContainer.appendChild(this.dom.shadowTopLeft);
this.dom.leftContainer.appendChild(this.dom.shadowBottomLeft);
this.dom.rightContainer.appendChild(this.dom.shadowTopRight);
this.dom.rightContainer.appendChild(this.dom.shadowBottomRight);
// size properties of each of the panels
this.props = {
root: {},
background: {},
centerContainer: {},
leftContainer: {},
rightContainer: {},
center: {},
left: {},
right: {},
top: {},
bottom: {},
border: {},
scrollTop: 0,
scrollTopMin: 0
};
this.on('rangechange', () => {
if (this.initialDrawDone === true) {
this._redraw();
}
});
this.on('rangechanged', () => {
if (!this.initialRangeChangeDone) {
this.initialRangeChangeDone = true;
}
});
this.on('touch', this._onTouch.bind(this));
this.on('panmove', this._onDrag.bind(this));
const me = this;
this._origRedraw = this._redraw.bind(this);
this._redraw = util.throttle(this._origRedraw);
this.on('_change', properties => {
if (me.itemSet && me.itemSet.initialItemSetDrawn && properties && properties.queue == true) {
me._redraw()
} else {
me._origRedraw();
}
});
// create event listeners for all interesting events, these events will be
// emitted via emitter
this.hammer = new Hammer(this.dom.root);
const pinchRecognizer = this.hammer.get('pinch').set({enable: true});
pinchRecognizer && hammerUtil.disablePreventDefaultVertically(pinchRecognizer);
this.hammer.get('pan').set({threshold: 5, direction: Hammer.DIRECTION_ALL});
this.timelineListeners = {};
const events = [
'tap', 'doubletap', 'press',
'pinch',
'pan', 'panstart', 'panmove', 'panend'
// TODO: cleanup
//'touch', 'pinch',
//'tap', 'doubletap', 'hold',
//'dragstart', 'drag', 'dragend',
//'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is needed for Firefox
];
events.forEach(type => {
const listener = event => {
if (me.isActive()) {
me.emit(type, event);
}
};
me.hammer.on(type, listener);
me.timelineListeners[type] = listener;
});
// emulate a touch event (emitted before the start of a pan, pinch, tap, or press)
hammerUtil.onTouch(this.hammer, event => {
me.emit('touch', event);
});
// emulate a release event (emitted after a pan, pinch, tap, or press)
hammerUtil.onRelease(this.hammer, event => {
me.emit('release', event);
});
/**
*
* @param {WheelEvent} event
*/
function onMouseWheel(event) {
// Reasonable default wheel deltas
const LINE_HEIGHT = 40;
const PAGE_HEIGHT = 800;
if (this.isActive()) {
this.emit('mousewheel', event);
}
// deltaX and deltaY normalization from jquery.mousewheel.js
let deltaX = 0;
let deltaY = 0;
// Old school scrollwheel delta
if ('detail' in event) {
deltaY = event.detail * -1;
}
if ('wheelDelta' in event) {
deltaY = event.wheelDelta;
}
if ('wheelDeltaY' in event) {
deltaY = event.wheelDeltaY;
}
if ('wheelDeltaX' in event) {
deltaX = event.wheelDeltaX * -1;
}
// Firefox < 17 horizontal scrolling related to DOMMouseScroll event
if ('axis' in event && event.axis === event.HORIZONTAL_AXIS) {
deltaX = deltaY * -1;
deltaY = 0;
}
// New school wheel delta (wheel event)
if ('deltaY' in event) {
deltaY = event.deltaY * -1;
}
if ('deltaX' in event) {
deltaX = event.deltaX;
}
// Normalize deltas
if (event.deltaMode) {
if (event.deltaMode === 1) { // delta in LINE units
deltaX *= LINE_HEIGHT;
deltaY *= LINE_HEIGHT;
} else { // delta in PAGE units
deltaX *= LINE_HEIGHT;
deltaY *= PAGE_HEIGHT;
}
}
// Prevent scrolling when zooming (no zoom key, or pressing zoom key)
if (this.options.preferZoom) {
if (!this.options.zoomKey || event[this.options.zoomKey]) return;
} else {
if (this.options.zoomKey && event[this.options.zoomKey]) return
}
// Don't preventDefault if you can't scroll
if (!this.options.verticalScroll && !this.options.horizontalScroll) return;
if (this.options.verticalScroll && Math.abs(deltaY) >= Math.abs(deltaX)) {
const current = this.props.scrollTop;
const adjusted = current + deltaY;
if (this.isActive()) {
const newScrollTop = this._setScrollTop(adjusted);
if (newScrollTop !== current) {
this._redraw();
this.emit('scroll', event);
// Prevent default actions caused by mouse wheel
// (else the page and timeline both scroll)
event.preventDefault();
}
}
} else if (this.options.horizontalScroll) {
const delta = Math.abs(deltaX) >= Math.abs(deltaY) ? deltaX : deltaY;
// calculate a single scroll jump relative to the range scale
const diff = (delta / 120) * (this.range.end - this.range.start) / 20;
// calculate new start and end
const newStart = this.range.start + diff;
const newEnd = this.range.end + diff;
const options = {
animation: false,
byUser: true,
event
};
this.range.setRange(newStart, newEnd, options);
event.preventDefault();
}
}
// Add modern wheel event listener
const wheelType = "onwheel" in document.createElement("div") ? "wheel" : // Modern browsers support "wheel"
document.onmousewheel !== undefined ? "mousewheel" : // Webkit and IE support at least "mousewheel"
// DOMMouseScroll - Older Firefox versions use "DOMMouseScroll"
// onmousewheel - All the use "onmousewheel"
this.dom.centerContainer.addEventListener ? "DOMMouseScroll" : "onmousewheel"
this.dom.top.addEventListener ? "DOMMouseScroll" : "onmousewheel"
this.dom.bottom.addEventListener ? "DOMMouseScroll" : "onmousewheel"
this.dom.centerContainer.addEventListener(wheelType, onMouseWheel.bind(this), false);
this.dom.top.addEventListener(wheelType, onMouseWheel.bind(this), false);
this.dom.bottom.addEventListener(wheelType, onMouseWheel.bind(this), false);
/**
*
* @param {scroll} event
*/
function onMouseScrollSide(event) {
if (!me.options.verticalScroll) return;
event.preventDefault();
if (me.isActive()) {
const adjusted = -event.target.scrollTop;
me._setScrollTop(adjusted);
me._redraw();
me.emit('scrollSide', event);
}
}
this.dom.left.parentNode.addEventListener('scroll', onMouseScrollSide.bind(this));
this.dom.right.parentNode.addEventListener('scroll', onMouseScrollSide.bind(this));
let itemAddedToTimeline = false;
/**
*
* @param {dragover} event
* @returns {boolean}
*/
function handleDragOver(event) {
if (event.preventDefault) {
me.emit('dragover', me.getEventProperties(event));
event.preventDefault(); // Necessary. Allows us to drop.
}
// make sure your target is a timeline element
if (!(event.target.className.indexOf("timeline") > -1)) return;
// make sure only one item is added every time you're over the timeline
if (itemAddedToTimeline) return;
event.dataTransfer.dropEffect = 'move';
itemAddedToTimeline = true;
return false;
}
/**
*
* @param {drop} event
* @returns {boolean}
*/
function handleDrop(event) {
// prevent redirect to blank page - Firefox
if (event.preventDefault) {
event.preventDefault();
}
if (event.stopPropagation) {
event.stopPropagation();
}
// return when dropping non-timeline items
try {
var itemData = JSON.parse(event.dataTransfer.getData("text"))
if (!itemData || !itemData.content) return
} catch (err) {
return false;
}
itemAddedToTimeline = false;
event.center = {
x: event.clientX,
y: event.clientY
};
if (itemData.target !== 'item') {
me.itemSet._onAddItem(event);
} else {
me.itemSet._onDropObjectOnItem(event);
}
me.emit('drop', me.getEventProperties(event))
return false;
}
this.dom.center.addEventListener('dragover', handleDragOver.bind(this), false);
this.dom.center.addEventListener('drop', handleDrop.bind(this), false);
this.customTimes = [];
// store state information needed for touch events
this.touch = {};
this.redrawCount = 0;
this.initialDrawDone = false;
this.initialRangeChangeDone = false;
// attach the root panel to the provided container
if (!container) throw new Error('No container provided');
container.appendChild(this.dom.root);
container.appendChild(this.dom.loadingScreen);
}
/**
* Set options. Options will be passed to all components loaded in the Timeline.
* @param {Object} [options]
* {String} orientation
* Vertical orientation for the Timeline,
* can be 'bottom' (default) or 'top'.
* {string | number} width
* Width for the timeline, a number in pixels or
* a css string like '1000px' or '75%'. '100%' by default.
* {string | number} height
* Fixed height for the Timeline, a number in pixels or
* a css string like '400px' or '75%'. If undefined,
* The Timeline will automatically size such that
* its contents fit.
* {string | number} minHeight
* Minimum height for the Timeline, a number in pixels or
* a css string like '400px' or '75%'.
* {string | number} maxHeight
* Maximum height for the Timeline, a number in pixels or
* a css string like '400px' or '75%'.
* {number | Date | string} start
* Start date for the visible window
* {number | Date | string} end
* End date for the visible window
*/
setOptions(options) {
if (options) {
// copy the known options
const fields = [
'width', 'height', 'minHeight', 'maxHeight', 'autoResize',
'start', 'end', 'clickToUse', 'dataAttributes', 'hiddenDates',
'locale', 'locales', 'moment', 'preferZoom', 'rtl', 'zoomKey',
'horizontalScroll', 'verticalScroll', 'longSelectPressTime', 'snap'
];
util.selectiveExtend(fields, this.options, options);
this.dom.rollingModeBtn.style.visibility = 'hidden';
if (this.options.rtl) {
this.dom.container.style.direction = "rtl";
this.dom.backgroundVertical.className = 'vis-panel vis-background vis-vertical-rtl';
}
if (this.options.verticalScroll) {
if (this.options.rtl) {
this.dom.rightContainer.className = 'vis-panel vis-right vis-vertical-scroll';
} else {
this.dom.leftContainer.className = 'vis-panel vis-left vis-vertical-scroll';
}
}
if (typeof this.options.orientation !== 'object') {
this.options.orientation = {item: undefined, axis: undefined};
}
if ('orientation' in options) {
if (typeof options.orientation === 'string') {
this.options.orientation = {
item: options.orientation,
axis: options.orientation
};
} else if (typeof options.orientation === 'object') {
if ('item' in options.orientation) {
this.options.orientation.item = options.orientation.item;
}
if ('axis' in options.orientation) {
this.options.orientation.axis = options.orientation.axis;
}
}
}
if (this.options.orientation.axis === 'both') {
if (!this.timeAxis2) {
const timeAxis2 = this.timeAxis2 = new TimeAxis(this.body, this.options);
timeAxis2.setOptions = options => {
const _options = options ? util.extend({}, options) : {};
_options.orientation = 'top'; // override the orientation option, always top
TimeAxis.prototype.setOptions.call(timeAxis2, _options);
};
this.components.push(timeAxis2);
}
} else {
if (this.timeAxis2) {
const index = this.components.indexOf(this.timeAxis2);
if (index !== -1) {
this.components.splice(index, 1);
}
this.timeAxis2.destroy();
this.timeAxis2 = null;
}
}
// if the graph2d's drawPoints is a function delegate the callback to the onRender property
if (typeof options.drawPoints == 'function') {
options.drawPoints = {
onRender: options.drawPoints
};
}
if ('hiddenDates' in this.options) {
DateUtil.convertHiddenOptions(this.options.moment, this.body, this.options.hiddenDates);
}
if ('clickToUse' in options) {
if (options.clickToUse) {
if (!this.activator) {
this.activator = new Activator(this.dom.root);
}
} else {
if (this.activator) {
this.activator.destroy();
delete this.activator;
}
}
}
// enable/disable autoResize
this._initAutoResize();
}
// propagate options to all components
this.components.forEach(component => component.setOptions(options));
// enable/disable configure
if ('configure' in options) {
if (!this.configurator) {
this.configurator = this._createConfigurator();
}
this.configurator.setOptions(options.configure);
// collect the settings of all components, and pass them to the configuration system
const appliedOptions = util.deepExtend({}, this.options);
this.components.forEach(component => {
util.deepExtend(appliedOptions, component.options);
});
this.configurator.setModuleOptions({global: appliedOptions});
}
this._redraw();
}
/**
* Returns true when the Timeline is active.
* @returns {boolean}
*/
isActive() {
return !this.activator || this.activator.active;
}
/**
* Destroy the Core, clean up all DOM elements and event listeners.
*/
destroy() {
// unbind datasets
this.setItems(null);
this.setGroups(null);
// remove all event listeners
this.off();
// stop checking for changed size
this._stopAutoResize();
// remove from DOM
if (this.dom.root.parentNode) {
this.dom.root.parentNode.removeChild(this.dom.root);
}
this.dom = null;
// remove Activator
if (this.activator) {
this.activator.destroy();
delete this.activator;
}
// cleanup hammer touch events
for (const event in this.timelineListeners) {
if (this.timelineListeners.hasOwnProperty(event)) {
delete this.timelineListeners[event];
}
}
this.timelineListeners = null;
this.hammer && this.hammer.destroy();
this.hammer = null;
// give all components the opportunity to cleanup
this.components.forEach(component => component.destroy());
this.body = null;
}
/**
* Set a custom time bar
* @param {Date} time
* @param {number} [id=undefined] Optional id of the custom time bar to be adjusted.
*/
setCustomTime(time, id) {
const customTimes = this.customTimes.filter(component => id === component.options.id);
if (customTimes.length === 0) {
throw new Error(`No custom time bar found with id ${JSON.stringify(id)}`)
}
if (customTimes.length > 0) {
customTimes[0].setCustomTime(time);
}
}
/**
* Retrieve the current custom time.
* @param {number} [id=undefined] Id of the custom time bar.
* @return {Date | undefined} customTime
*/
getCustomTime(id) {
const customTimes = this.customTimes.filter(component => component.options.id === id);
if (customTimes.length === 0) {
throw new Error(`No custom time bar found with id ${JSON.stringify(id)}`)
}
return customTimes[0].getCustomTime();
}
/**
* Set a custom marker for the custom time bar.
* @param {string} [title] Title of the custom marker.
* @param {number} [id=undefined] Id of the custom marker.
* @param {boolean} [editable=false] Make the custom marker editable.
*/
setCustomTimeMarker(title, id, editable) {
const customTimes = this.customTimes.filter(component => component.options.id === id);
if (customTimes.length === 0) {
throw new Error(`No custom time bar found with id ${JSON.stringify(id)}`)
}
if (customTimes.length > 0) {
customTimes[0].setCustomMarker(title, editable);
}
}
/**
* Set a custom title for the custom time bar.
* @param {string} [title] Custom title
* @param {number} [id=undefined] Id of the custom time bar.
* @returns {*}
*/
setCustomTimeTitle(title, id) {
const customTimes = this.customTimes.filter(component => component.options.id === id);
if (customTimes.length === 0) {
throw new Error(`No custom time bar found with id ${JSON.stringify(id)}`)
}
if (customTimes.length > 0) {
return customTimes[0].setCustomTitle(title);
}
}
/**
* Retrieve meta information from an event.
* Should be overridden by classes extending Core
* @param {Event} event
* @return {Object} An object with related information.
*/
getEventProperties(event) {
return {event};
}
/**
* Add custom vertical bar
* @param {Date | string | number} [time] A Date, unix timestamp, or
* ISO date string. Time point where
* the new bar should be placed.
* If not provided, `new Date()` will
* be used.
* @param {number | string} [id=undefined] Id of the new bar. Optional
* @return {number | string} Returns the id of the new bar
*/
addCustomTime(time, id) {
const timestamp = time !== undefined
? util.convert(time, 'Date')
: new Date();
const exists = this.customTimes.some(customTime => customTime.options.id === id);
if (exists) {
throw new Error(`A custom time with id ${JSON.stringify(id)} already exists`);
}
const customTime = new CustomTime(this.body, util.extend({}, this.options, {
time: timestamp,
id,
snap: this.itemSet ? this.itemSet.options.snap : this.options.snap
}));
this.customTimes.push(customTime);
this.components.push(customTime);
this._redraw();
return id;
}
/**
* Remove previously added custom bar
* @param {int} id ID of the custom bar to be removed
* [at]returns {boolean} True if the bar exists and is removed, false otherwise
*/
removeCustomTime(id) {
const customTimes = this.customTimes.filter(bar => bar.options.id === id);
if (customTimes.length === 0) {
throw new Error(`No custom time bar found with id ${JSON.stringify(id)}`)
}
customTimes.forEach(customTime => {
this.customTimes.splice(this.customTimes.indexOf(customTime), 1);
this.components.splice(this.components.indexOf(customTime), 1);
customTime.destroy();
})
}
/**
* Get the id's of the currently visible items.
* @returns {Array} The ids of the visible items
*/
getVisibleItems() {
return this.itemSet && this.itemSet.getVisibleItems() || [];
}
/**
* Get the id's of the items at specific time, where a click takes place on the timeline.
* @returns {Array} The ids of all items in existence at the time of event.
*/
getItemsAtCurrentTime(timeOfEvent) {
this.time = timeOfEvent;
return this.itemSet && this.itemSet.getItemsAtCurrentTime(this.time) || [];
}
/**
* Get the id's of the currently visible groups.
* @returns {Array} The ids of the visible groups
*/
getVisibleGroups() {
return this.itemSet && this.itemSet.getVisibleGroups() || [];
}
/**
* Set Core window such that it fits all items
* @param {Object} [options] Available options:
* `animation: boolean | {duration: number, easingFunction: string}`
* If true (default), the range is animated
* smoothly to the new window. An object can be
* provided to specify duration and easing function.
* Default duration is 500 ms, and default easing
* function is 'easeInOutQuad'.
* @param {function} [callback] a callback funtion to be executed at the end of this function
*/
fit(options, callback) {
const range = this.getDataRange();
// skip range set if there is no min and max date
if (range.min === null && range.max === null) {
return;
}
// apply a margin of 1% left and right of the data
const interval = range.max - range.min;
const min = new Date(range.min.valueOf() - interval * 0.01);
const max = new Date(range.max.valueOf() + interval * 0.01);
const animation = (options && options.animation !== undefined) ? options.animation : true;
this.range.setRange(min, max, {animation}, callback);
}
/**
* Calculate the data range of the items start and end dates
* [at]returns {{min: [Date], max: [Date]}}
* @protected
*/
getDataRange() {
// must be implemented by Timeline and Graph2d
throw new Error('Cannot invoke abstract method getDataRange');
}
/**
* Set the visible window. Both parameters are optional, you can change only
* start or only end. Syntax:
*
* TimeLine.setWindow(start, end)
* TimeLine.setWindow(start, end, options)
* TimeLine.setWindow(range)
*
* Where start and end can be a Date, number, or string, and range is an
* object with properties start and end.
*
* @param {Date | number | string | Object} [start] Start date of visible window
* @param {Date | number | string} [end] End date of visible window
* @param {Object} [options] Available options:
* `animation: boolean | {duration: number, easingFunction: string}`
* If true (default), the range is animated
* smoothly to the new window. An object can be
* provided to specify duration and easing function.
* Default duration is 500 ms, and default easing
* function is 'easeInOutQuad'.
* @param {function} [callback] a callback funtion to be executed at the end of this function
*/
setWindow(start, end, options, callback) {
if (typeof arguments[2] == "function") {
callback = arguments[2];
options = {};
}
let animation;
let range;
if (arguments.length == 1) {
range = arguments[0];
animation = (range.animation !== undefined) ? range.animation : true;
this.range.setRange(range.start, range.end, {animation});
} else if (arguments.length == 2 && typeof arguments[1] == "function") {
range = arguments[0];
callback = arguments[1];
animation = (range.animation !== undefined) ? range.animation : true;
this.range.setRange(range.start, range.end, {animation}, callback);
} else {
animation = (options && options.animation !== undefined) ? options.animation : true;
this.range.setRange(start, end, {animation}, callback);
}
}
/**
* Move the window such that given time is centered on screen.
* @param {Date | number | string} time
* @param {Object} [options] Available options:
* `animation: boolean | {duration: number, easingFunction: string}`
* If true (default), the range is animated
* smoothly to the new window. An object can be
* provided to specify duration and easing function.
* Default duration is 500 ms, and default easing
* function is 'easeInOutQuad'.
* @param {function} [callback] a callback funtion to be executed at the end of this function
*/
moveTo(time, options, callback) {
if (typeof arguments[1] == "function") {
callback = arguments[1];
options = {};
}
const interval = this.range.end - this.range.start;
const t = util.convert(time, 'Date').valueOf();
const start = t - interval / 2;
const end = t + interval / 2;
const animation = (options && options.animation !== undefined) ? options.animation : true;
this.range.setRange(start, end, {animation}, callback);
}
/**
* Get the visible window
* @return {{start: Date, end: Date}} Visible range
*/
getWindow() {
const range = this.range.getRange();
return {
start: new Date(range.start),
end: new Date(range.end)
};
}
/**
* Zoom in the window such that given time is centered on screen.
* @param {number} percentage - must be between [0..1]
* @param {Object} [options] Available options:
* `animation: boolean | {duration: number, easingFunction: string}`
* If true (default), the range is animated
* smoothly to the new window. An object can be
* provided to specify duration and easing function.
* Default duration is 500 ms, and default easing
* function is 'easeInOutQuad'.
* @param {function} [callback] a callback funtion to be executed at the end of this function
*/
zoomIn(percentage, options, callback) {
if (!percentage || percentage < 0 || percentage > 1) return;
if (typeof arguments[1] == "function") {
callback = arguments[1];
options = {};
}
const range = this.getWindow();
const start = range.start.valueOf();
const end = range.end.valueOf();
const interval = end - start;
const newInterval = interval / (1 + percentage);
const distance = (interval - newInterval) / 2;
const newStart = start + distance;
const newEnd = end - distance;
this.setWindow(newStart, newEnd, options, callback);
}
/**
* Zoom out the window such that given time is centered on screen.
* @param {number} percentage - must be between [0..1]
* @param {Object} [options] Available options:
* `animation: boolean | {duration: number, easingFunction: string}`
* If true (default), the range is animated
* smoothly to the new window. An object can be
* provided to specify duration and easing function.
* Default duration is 500 ms, and default easing
* function is 'easeInOutQuad'.
* @param {function} [callback] a callback funtion to be executed at the end of this function
*/
zoomOut(percentage, options, callback) {
if (!percentage || percentage < 0 || percentage > 1) return
if (typeof arguments[1] == "function") {
callback = arguments[1];
options = {};
}
const range = this.getWindow();
const start = range.start.valueOf();
const end = range.end.valueOf();
const interval = end - start;
const newStart = start - interval * percentage / 2;
const newEnd = end + interval * percentage / 2;
this.setWindow(newStart, newEnd, options, callback);
}
/**
* Force a redraw. Can be overridden by implementations of Core
*
* Note: this function will be overridden on construction with a trottled version
*/
redraw() {
this._redraw();
}
/**
* Redraw for internal use. Redraws all components. See also the public
* method redraw.
* @protected
*/
_redraw() {
this.redrawCount++;
const dom = this.dom;
if (!dom || !dom.container || dom.root.offsetWidth == 0) return; // when destroyed, or invisible
let resized = false;
const options = this.options;
const props = this.props;
DateUtil.updateHiddenDates(this.options.moment, this.body, this.options.hiddenDates);
// update class names
if (options.orientation == 'top') {
util.addClassName(dom.root, 'vis-top');
util.removeClassName(dom.root, 'vis-bottom');
} else {
util.removeClassName(dom.root, 'vis-top');
util.addClassName(dom.root, 'vis-bottom');
}
if (options.rtl) {
util.addClassName(dom.root, 'vis-rtl');
util.removeClassName(dom.root, 'vis-ltr');
} else {
util.addClassName(dom.root, 'vis-ltr');
util.removeClassName(dom.root, 'vis-rtl');
}
// update root width and height options
dom.root.style.maxHeight = util.option.asSize(options.maxHeight, '');
dom.root.style.minHeight = util.option.asSize(options.minHeight, '');
dom.root.style.width = util.option.asSize(options.width, '');
const rootOffsetWidth = dom.root.offsetWidth;
// calculate border widths
props.border.left = 1
props.border.right = 1
props.border.top = 1
props.border.bottom = 1
// calculate the heights. If any of the side panels is empty, we set the height to
// minus the border width, such that the border will be invisible
props.center.height = dom.center.offsetHeight;
props.left.height = dom.left.offsetHeight;
props.right.height = dom.right.offsetHeight;
props.top.height = dom.top.clientHeight || -props.border.top;
props.bottom.height = Math.round(dom.bottom.getBoundingClientRect().height) || dom.bottom.clientHeight || -props.border.bottom;
// TODO: compensate borders when any of the panels is empty.
// apply auto height
// TODO: only calculate autoHeight when needed (else we cause an extra reflow/repaint of the DOM)
const contentHeight = Math.max(props.left.height, props.center.height, props.right.height);
const autoHeight = props.top.height + contentHeight + props.bottom.height + props.border.top + props.border.bottom;
dom.root.style.height = util.option.asSize(options.height, `${autoHeight}px`);
// calculate heights of the content panels
props.root.height = dom.root.offsetHeight;
props.background.height = props.root.height;
const containerHeight = props.root.height - props.top.height - props.bottom.height;
props.centerContainer.height = containerHeight;
props.leftContainer.height = containerHeight;
props.rightContainer.height = props.leftContainer.height;
// calculate the widths of the panels
props.root.width = rootOffsetWidth;
props.background.width = props.root.width;
if (!this.initialDrawDone) {
props.scrollbarWidth = util.getScrollBarWidth();
}
const leftContainerClientWidth = dom.leftContainer.clientWidth;
const rightContainerClientWidth = dom.rightContainer.clientWidth;
if (options.verticalScroll) {
if (options.rtl) {