-
Notifications
You must be signed in to change notification settings - Fork 0
/
timeline.js
7038 lines (6145 loc) · 227 KB
/
timeline.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
/* eslint-disable */
/**
* @file timeline.js
*
* @brief
* The Timeline is an interactive visualization chart to visualize events in
* time, having a start and end date.
* You can freely move and zoom in the timeline by dragging
* and scrolling in the Timeline. Items are optionally dragable. The time
* scale on the axis is adjusted automatically, and supports scales ranging
* from milliseconds to years.
*
* Timeline is part of the CHAP Links library.
*
* Timeline is tested on Firefox 3.6, Safari 5.0, Chrome 6.0, Opera 10.6, and
* Internet Explorer 6+.
*
* @license
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
* Copyright (c) 2011-2015 Almende B.V.
*
* @author Jos de Jong, <[email protected]>
* @date 2015-03-04
* @version 2.9.1
*/
/*
* i18n mods by github user iktuz (https://gist.github.com/iktuz/3749287/)
* added to v2.4.1 with da_DK language by @bjarkebech
*/
/*
* TODO
*
* Add zooming with pinching on Android
*
* Bug: when an item contains a javascript onclick or a link, this does not work
* when the item is not selected (when the item is being selected,
* it is redrawn, which cancels any onclick or link action)
* Bug: when an item contains an image without size, or a css max-width, it is not sized correctly
* Bug: neglect items when they have no valid start/end, instead of throwing an error
* Bug: Pinching on ipad does not work very well, sometimes the page will zoom when pinching vertically
* Bug: cannot set max width for an item, like div.timeline-event-content {white-space: normal; max-width: 100px;}
* Bug on IE in Quirks mode. When you have groups, and delete an item, the groups become invisible
*/
/**
* Declare a unique namespace for CHAP's Common Hybrid Visualisation Library,
* "links"
*/
if (typeof links === 'undefined') {
var links = {};
// important: do not use var, as "var links = {};" will overwrite
// the existing links variable value with undefined in IE8, IE7.
}
/**
* Ensure the variable google exists
*/
if (typeof google === 'undefined') {
var google = undefined;
// important: do not use var, as "var google = undefined;" will overwrite
// the existing google variable value with undefined in IE8, IE7.
}
// Internet Explorer 8 and older does not support Array.indexOf,
// so we define it here in that case
// http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/
if(!Array.prototype.indexOf) {
Array.prototype.indexOf = function(obj){
for(var i = 0; i < this.length; i++){
if(this[i] == obj){
return i;
}
}
return -1;
}
}
// Internet Explorer 8 and older does not support Array.forEach,
// so we define it here in that case
// https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(fn, scope) {
for(var i = 0, len = this.length; i < len; ++i) {
fn.call(scope || this, this[i], i, this);
}
}
}
/**
* @constructor links.Timeline
* The timeline is a visualization chart to visualize events in time.
*
* The timeline is developed in javascript as a Google Visualization Chart.
*
* @param {Element} container The DOM element in which the Timeline will
* be created. Normally a div element.
* @param {Object} options A name/value map containing settings for the
* timeline. Optional.
*/
links.Timeline = function(container, options) {
if (!container) {
// this call was probably only for inheritance, no constructor-code is required
return;
}
// create variables and set default values
this.dom = {};
this.conversion = {};
this.eventParams = {}; // stores parameters for mouse events
this.groups = [];
this.groupIndexes = {};
this.items = [];
this.renderQueue = {
show: [], // Items made visible but not yet added to DOM
hide: [], // Items currently visible but not yet removed from DOM
update: [] // Items with changed data but not yet adjusted DOM
};
this.renderedItems = []; // Items currently rendered in the DOM
this.clusterGenerator = new links.Timeline.ClusterGenerator(this);
this.currentClusters = [];
this.selection = undefined; // stores index and item which is currently selected
this.listeners = {}; // event listener callbacks
// Initialize sizes.
// Needed for IE (which gives an error when you try to set an undefined
// value in a style)
this.size = {
'actualHeight': 0,
'axis': {
'characterMajorHeight': 0,
'characterMajorWidth': 0,
'characterMinorHeight': 0,
'characterMinorWidth': 0,
'height': 0,
'labelMajorTop': 0,
'labelMinorTop': 0,
'line': 0,
'lineMajorWidth': 0,
'lineMinorHeight': 0,
'lineMinorTop': 0,
'lineMinorWidth': 0,
'top': 0
},
'contentHeight': 0,
'contentLeft': 0,
'contentWidth': 0,
'frameHeight': 0,
'frameWidth': 0,
'groupsLeft': 0,
'groupsWidth': 0,
'items': {
'top': 0
}
};
this.dom.container = container;
//
// Let's set the default options first
//
this.options = {
'width': "100%",
'height': "auto",
'minHeight': 0, // minimal height in pixels
'groupMinHeight': 0,
'autoHeight': true,
'eventMargin': 10, // minimal margin between events
'eventMarginAxis': 20, // minimal margin between events and the axis
'dragAreaWidth': 10, // pixels
'min': undefined,
'max': undefined,
'zoomMin': 10, // milliseconds
'zoomMax': 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
'moveable': true,
'zoomable': true,
'zoomableWithCtrl': false,
'selectable': true,
'unselectable': true,
'editable': false,
'snapEvents': true,
'groupsChangeable': true,
'timeChangeable': true,
'showCurrentTime': true, // show a red bar displaying the current time
'showCustomTime': false, // show a blue, draggable bar displaying a custom time
'showMajorLabels': true,
'showMinorLabels': true,
'showNavigation': false,
'showButtonNew': false,
'groupsOnRight': false,
'groupsOrder' : true,
'axisOnTop': false,
'stackEvents': true,
'animate': true,
'animateZoom': true,
'cluster': false,
'clusterMaxItems': 5,
'style': 'box',
'customStackOrder': false, //a function(a,b) for determining stackorder amongst a group of items. Essentially a comparator, -ve value for "a before b" and vice versa
// i18n: Timeline only has built-in English text per default. Include timeline-locales.js to support more localized text.
'locale': 'en',
'MONTHS': ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
'MONTHS_SHORT': ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
'DAYS': ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
'DAYS_SHORT': ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
'ZOOM_IN': "Zoom in",
'ZOOM_OUT': "Zoom out",
'MOVE_LEFT': "Move left",
'MOVE_RIGHT': "Move right",
'NEW': "New",
'CREATE_NEW_EVENT': "Create new event"
};
//
// Now we can set the givenproperties
//
this.setOptions(options);
this.clientTimeOffset = 0; // difference between client time and the time
// set via Timeline.setCurrentTime()
var dom = this.dom;
// remove all elements from the container element.
while (dom.container.hasChildNodes()) {
dom.container.removeChild(dom.container.firstChild);
}
// create a step for drawing the axis
this.step = new links.Timeline.StepDate();
// add standard item types
this.itemTypes = {
box: links.Timeline.ItemBox,
range: links.Timeline.ItemRange,
floatingRange: links.Timeline.ItemFloatingRange,
dot: links.Timeline.ItemDot
};
// initialize data
this.data = [];
this.firstDraw = true;
// date interval must be initialized
this.setVisibleChartRange(undefined, undefined, false);
// render for the first time
this.render();
// fire the ready event
var me = this;
setTimeout(function () {
me.trigger('ready');
}, 0);
};
/**
* Main drawing logic. This is the function that needs to be called
* in the html page, to draw the timeline.
*
* A data table with the events must be provided, and an options table.
*
* @param {google.visualization.DataTable} data
* The data containing the events for the timeline.
* Object DataTable is defined in
* google.visualization.DataTable
* @param {Object} options A name/value map containing settings for the
* timeline. Optional. The use of options here
* is deprecated. Pass timeline options in the
* constructor or use setOptions()
*/
links.Timeline.prototype.draw = function(data, options) {
if (options) {
console.log("WARNING: Passing options in draw() is deprecated. Pass options to the constructur or use setOptions() instead!");
this.setOptions(options);
}
if (this.options.selectable) {
links.Timeline.addClassName(this.dom.frame, "timeline-selectable");
}
// read the data
this.setData(data);
if (this.firstDraw) {
this.setVisibleChartRangeAuto();
}
this.firstDraw = false;
};
/**
* Set options for the timeline.
* Timeline must be redrawn afterwards
* @param {Object} options A name/value map containing settings for the
* timeline. Optional.
*/
links.Timeline.prototype.setOptions = function(options) {
if (options) {
// retrieve parameter values
for (var i in options) {
if (options.hasOwnProperty(i)) {
this.options[i] = options[i];
}
}
// prepare i18n dependent on set locale
if (typeof links.locales !== 'undefined' && this.options.locale !== 'en') {
var localeOpts = links.locales[this.options.locale];
if(localeOpts) {
for (var l in localeOpts) {
if (localeOpts.hasOwnProperty(l)) {
this.options[l] = localeOpts[l];
}
}
}
}
// New Lateral margin option
if (options.eventMarginLateral == undefined) {
this.options.eventMarginLateral = this.options.eventMargin;
}
// check for deprecated options
if (options.showButtonAdd != undefined) {
this.options.showButtonNew = options.showButtonAdd;
console.log('WARNING: Option showButtonAdd is deprecated. Use showButtonNew instead');
}
if (options.intervalMin != undefined) {
this.options.zoomMin = options.intervalMin;
console.log('WARNING: Option intervalMin is deprecated. Use zoomMin instead');
}
if (options.intervalMax != undefined) {
this.options.zoomMax = options.intervalMax;
console.log('WARNING: Option intervalMax is deprecated. Use zoomMax instead');
}
if (options.scale && options.step) {
this.step.setScale(options.scale, options.step);
}
}
// validate options
this.options.autoHeight = (this.options.height === "auto");
};
/**
* Get options for the timeline.
*
* @return the options object
*/
links.Timeline.prototype.getOptions = function() {
return this.options;
};
/**
* Add new type of items
* @param {String} typeName Name of new type
* @param {links.Timeline.Item} typeFactory Constructor of items
*/
links.Timeline.prototype.addItemType = function (typeName, typeFactory) {
this.itemTypes[typeName] = typeFactory;
};
/**
* Retrieve a map with the column indexes of the columns by column name.
* For example, the method returns the map
* {
* start: 0,
* end: 1,
* content: 2,
* group: undefined,
* className: undefined
* editable: undefined
* type: undefined
* }
* @param {google.visualization.DataTable} dataTable
* @type {Object} map
*/
links.Timeline.mapColumnIds = function (dataTable) {
var cols = {},
colCount = dataTable.getNumberOfColumns(),
allUndefined = true;
// loop over the columns, and map the column id's to the column indexes
for (var col = 0; col < colCount; col++) {
var id = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
cols[id] = col;
if (id == 'start' || id == 'end' || id == 'content' || id == 'group' ||
id == 'className' || id == 'editable' || id == 'type') {
allUndefined = false;
}
}
// if no labels or ids are defined, use the default mapping
// for start, end, content, group, className, editable, type
if (allUndefined) {
cols.start = 0;
cols.end = 1;
cols.content = 2;
if (colCount > 3) {cols.group = 3}
if (colCount > 4) {cols.className = 4}
if (colCount > 5) {cols.editable = 5}
if (colCount > 6) {cols.type = 6}
}
return cols;
};
/**
* Set data for the timeline
* @param {google.visualization.DataTable | Array} data
*/
links.Timeline.prototype.setData = function(data) {
// unselect any previously selected item
this.unselectItem();
if (!data) {
data = [];
}
// clear all data
this.stackCancelAnimation();
this.clearItems();
this.data = data;
var items = this.items;
this.deleteGroups();
if (google && google.visualization &&
data instanceof google.visualization.DataTable) {
// map the datatable columns
var cols = links.Timeline.mapColumnIds(data);
// read DataTable
for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
items.push(this.createItem({
'start': ((cols.start != undefined) ? data.getValue(row, cols.start) : undefined),
'end': ((cols.end != undefined) ? data.getValue(row, cols.end) : undefined),
'content': ((cols.content != undefined) ? data.getValue(row, cols.content) : undefined),
'group': ((cols.group != undefined) ? data.getValue(row, cols.group) : undefined),
'className': ((cols.className != undefined) ? data.getValue(row, cols.className) : undefined),
'editable': ((cols.editable != undefined) ? data.getValue(row, cols.editable) : undefined),
'type': ((cols.type != undefined) ? data.getValue(row, cols.type) : undefined),
'id': ((cols.id != undefined) ? data.getValue(row, cols.id) : undefined),
'style': ((cols.style != undefined) ? data.getValue(row, cols.style) : undefined),
}));
}
}
else if (links.Timeline.isArray(data)) {
// read JSON array
for (var row = 0, rows = data.length; row < rows; row++) {
var itemData = data[row];
var item = this.createItem(itemData);
items.push(item);
}
}
else {
throw "Unknown data type. DataTable or Array expected.";
}
// prepare data for clustering, by filtering and sorting by type
if (this.options.cluster) {
this.clusterGenerator.setData(this.items);
}
this.render({
animate: false
});
};
/**
* Return the original data table.
* @return {google.visualization.DataTable | Array} data
*/
links.Timeline.prototype.getData = function () {
return this.data;
};
/**
* Update the original data with changed start, end or group.
*
* @param {Number} index
* @param {Object} values An object containing some of the following parameters:
* {Date} start,
* {Date} end,
* {String} content,
* {String} group
*/
links.Timeline.prototype.updateData = function (index, values) {
var data = this.data,
prop;
if (google && google.visualization &&
data instanceof google.visualization.DataTable) {
// update the original google DataTable
var missingRows = (index + 1) - data.getNumberOfRows();
if (missingRows > 0) {
data.addRows(missingRows);
}
// map the column id's by name
var cols = links.Timeline.mapColumnIds(data);
// merge all fields from the provided data into the current data
for (prop in values) {
if (values.hasOwnProperty(prop)) {
var col = cols[prop];
if (col == undefined) {
// create new column
var value = values[prop];
var valueType = 'string';
if (typeof(value) == 'number') {valueType = 'number';}
else if (typeof(value) == 'boolean') {valueType = 'boolean';}
else if (value instanceof Date) {valueType = 'datetime';}
col = data.addColumn(valueType, prop);
}
data.setValue(index, col, values[prop]);
// TODO: correctly serialize the start and end Date to the desired type (Date, String, or Number)
}
}
}
else if (links.Timeline.isArray(data)) {
// update the original JSON table
var row = data[index];
if (row == undefined) {
row = {};
data[index] = row;
}
// merge all fields from the provided data into the current data
for (prop in values) {
if (values.hasOwnProperty(prop)) {
row[prop] = values[prop];
// TODO: correctly serialize the start and end Date to the desired type (Date, String, or Number)
}
}
}
else {
throw "Cannot update data, unknown type of data";
}
};
/**
* Find the item index from a given HTML element
* If no item index is found, undefined is returned
* @param {Element} element
* @return {Number | undefined} index
*/
links.Timeline.prototype.getItemIndex = function(element) {
var e = element,
dom = this.dom,
frame = dom.items.frame,
items = this.items,
index = undefined;
// try to find the frame where the items are located in
while (e.parentNode && e.parentNode !== frame) {
e = e.parentNode;
}
if (e.parentNode === frame) {
// yes! we have found the parent element of all items
// retrieve its id from the array with items
for (var i = 0, iMax = items.length; i < iMax; i++) {
if (items[i].dom === e) {
index = i;
break;
}
}
}
return index;
};
/**
* Find the cluster index from a given HTML element
* If no cluster index is found, undefined is returned
* @param {Element} element
* @return {Number | undefined} index
*/
links.Timeline.prototype.getClusterIndex = function(element) {
var e = element,
dom = this.dom,
frame = dom.items.frame,
clusters = this.clusters,
index = undefined;
if (this.clusters) {
// try to find the frame where the clusters are located in
while (e.parentNode && e.parentNode !== frame) {
e = e.parentNode;
}
if (e.parentNode === frame) {
// yes! we have found the parent element of all clusters
// retrieve its id from the array with clusters
for (var i = 0, iMax = clusters.length; i < iMax; i++) {
if (clusters[i].dom === e) {
index = i;
break;
}
}
}
}
return index;
};
/**
* Find all elements within the start and end range
* If no element is found, returns an empty array
* @param start time
* @param end time
* @return Array itemsInRange
*/
links.Timeline.prototype.getVisibleItems = function (start, end) {
var items = this.items;
var itemsInRange = [];
if (items) {
for (var i = 0, iMax = items.length; i < iMax; i++) {
var item = items[i];
if (item.end) {
// Time range object // NH use getLeft and getRight here
if (start <= item.start && item.end <= end) {
itemsInRange.push({"row": i});
}
} else {
// Point object
if (start <= item.start && item.start <= end) {
itemsInRange.push({"row": i});
}
}
}
}
// var sel = [];
// if (this.selection) {
// sel.push({"row": this.selection.index});
// }
// return sel;
return itemsInRange;
};
/**
* Set a new size for the timeline
* @param {string} width Width in pixels or percentage (for example "800px"
* or "50%")
* @param {string} height Height in pixels or percentage (for example "400px"
* or "30%")
*/
links.Timeline.prototype.setSize = function(width, height) {
if (width) {
this.options.width = width;
this.dom.frame.style.width = width;
}
if (height) {
this.options.height = height;
this.options.autoHeight = (this.options.height === "auto");
if (height !== "auto" ) {
this.dom.frame.style.height = height;
}
}
this.render({
animate: false
});
};
/**
* Set a new value for the visible range int the timeline.
* Set start undefined to include everything from the earliest date to end.
* Set end undefined to include everything from start to the last date.
* Example usage:
* myTimeline.setVisibleChartRange(new Date("2010-08-22"),
* new Date("2010-09-13"));
* @param {Date} start The start date for the timeline. optional
* @param {Date} end The end date for the timeline. optional
* @param {boolean} redraw Optional. If true (default) the Timeline is
* directly redrawn
*/
links.Timeline.prototype.setVisibleChartRange = function(start, end, redraw) {
var range = {};
if (!start || !end) {
// retrieve the date range of the items
range = this.getDataRange(true);
}
if (!start) {
if (end) {
if (range.min && range.min.valueOf() < end.valueOf()) {
// start of the data
start = range.min;
}
else {
// 7 days before the end
start = new Date(end.valueOf());
start.setDate(start.getDate() - 7);
}
}
else {
// default of 3 days ago
start = new Date();
start.setDate(start.getDate() - 3);
}
}
if (!end) {
if (range.max) {
// end of the data
end = range.max;
}
else {
// 7 days after start
end = new Date(start.valueOf());
end.setDate(end.getDate() + 7);
}
}
// prevent start Date <= end Date
if (end <= start) {
end = new Date(start.valueOf());
end.setDate(end.getDate() + 7);
}
// limit to the allowed range (don't let this do by applyRange,
// because that method will try to maintain the interval (end-start)
var min = this.options.min ? this.options.min : undefined; // date
if (min != undefined && start.valueOf() < min.valueOf()) {
start = new Date(min.valueOf()); // date
}
var max = this.options.max ? this.options.max : undefined; // date
if (max != undefined && end.valueOf() > max.valueOf()) {
end = new Date(max.valueOf()); // date
}
this.applyRange(start, end);
if (redraw == undefined || redraw == true) {
this.render({
animate: false
}); // TODO: optimize, no reflow needed
}
else {
this.recalcConversion();
}
};
/**
* Change the visible chart range such that all items become visible
*/
links.Timeline.prototype.setVisibleChartRangeAuto = function() {
var range = this.getDataRange(true);
this.setVisibleChartRange(range.min, range.max);
};
/**
* Adjust the visible range such that the current time is located in the center
* of the timeline
*/
links.Timeline.prototype.setVisibleChartRangeNow = function() {
var now = new Date();
var diff = (this.end.valueOf() - this.start.valueOf());
var startNew = new Date(now.valueOf() - diff/2);
var endNew = new Date(startNew.valueOf() + diff);
this.setVisibleChartRange(startNew, endNew);
};
/**
* Retrieve the current visible range in the timeline.
* @return {Object} An object with start and end properties
*/
links.Timeline.prototype.getVisibleChartRange = function() {
return {
'start': new Date(this.start.valueOf()),
'end': new Date(this.end.valueOf())
};
};
/**
* Get the date range of the items.
* @param {boolean} [withMargin] If true, 5% of whitespace is added to the
* left and right of the range. Default is false.
* @return {Object} range An object with parameters min and max.
* - {Date} min is the lowest start date of the items
* - {Date} max is the highest start or end date of the items
* If no data is available, the values of min and max
* will be undefined
*/
links.Timeline.prototype.getDataRange = function (withMargin) {
var items = this.items,
min = undefined, // number
max = undefined; // number
if (items) {
for (var i = 0, iMax = items.length; i < iMax; i++) {
var item = items[i],
start = item.start != undefined ? item.start.valueOf() : undefined,
end = item.end != undefined ? item.end.valueOf() : start;
if (start != undefined) {
min = (min != undefined) ? Math.min(min.valueOf(), start.valueOf()) : start;
}
if (end != undefined) {
max = (max != undefined) ? Math.max(max.valueOf(), end.valueOf()) : end;
}
}
}
if (min && max && withMargin) {
// zoom out 5% such that you have a little white space on the left and right
var diff = (max - min);
min = min - diff * 0.05;
max = max + diff * 0.05;
}
return {
'min': min != undefined ? new Date(min) : undefined,
'max': max != undefined ? new Date(max) : undefined
};
};
/**
* Re-render (reflow and repaint) all components of the Timeline: frame, axis,
* items, ...
* @param {Object} [options] Available options:
* {boolean} renderTimesLeft Number of times the
* render may be repeated
* 5 times by default.
* {boolean} animate takes options.animate
* as default value
*/
links.Timeline.prototype.render = function(options) {
var frameResized = this.reflowFrame();
var axisResized = this.reflowAxis();
var groupsResized = this.reflowGroups();
var itemsResized = this.reflowItems();
var resized = (frameResized || axisResized || groupsResized || itemsResized);
// TODO: only stackEvents/filterItems when resized or changed. (gives a bootstrap issue).
// if (resized) {
var animate = this.options.animate;
if (options && options.animate != undefined) {
animate = options.animate;
}
this.recalcConversion();
this.clusterItems();
this.filterItems();
this.stackItems(animate);
this.recalcItems();
// TODO: only repaint when resized or when filterItems or stackItems gave a change?
var needsReflow = this.repaint();
// re-render once when needed (prevent endless re-render loop)
if (needsReflow) {
var renderTimesLeft = options ? options.renderTimesLeft : undefined;
if (renderTimesLeft == undefined) {
renderTimesLeft = 5;
}
if (renderTimesLeft > 0) {
this.render({
'animate': options ? options.animate: undefined,
'renderTimesLeft': (renderTimesLeft - 1)
});
}
}
};
/**
* Repaint all components of the Timeline
* @return {boolean} needsReflow Returns true if the DOM is changed such that
* a reflow is needed.
*/
links.Timeline.prototype.repaint = function() {
var frameNeedsReflow = this.repaintFrame();
var axisNeedsReflow = this.repaintAxis();
var groupsNeedsReflow = this.repaintGroups();
var itemsNeedsReflow = this.repaintItems();
this.repaintCurrentTime();
this.repaintCustomTime();
return (frameNeedsReflow || axisNeedsReflow || groupsNeedsReflow || itemsNeedsReflow);
};
/**
* Reflow the timeline frame
* @return {boolean} resized Returns true if any of the frame elements
* have been resized.
*/
links.Timeline.prototype.reflowFrame = function() {
var dom = this.dom,
options = this.options,
size = this.size,
resized = false;
// Note: IE7 has issues with giving frame.clientWidth, therefore I use offsetWidth instead
var frameWidth = dom.frame ? dom.frame.offsetWidth : 0,
frameHeight = dom.frame ? dom.frame.clientHeight : 0;
resized = resized || (size.frameWidth !== frameWidth);
resized = resized || (size.frameHeight !== frameHeight);
size.frameWidth = frameWidth;
size.frameHeight = frameHeight;
return resized;
};
/**
* repaint the Timeline frame
* @return {boolean} needsReflow Returns true if the DOM is changed such that
* a reflow is needed.
*/
links.Timeline.prototype.repaintFrame = function() {
var needsReflow = false,
dom = this.dom,
options = this.options,
size = this.size;
// main frame
if (!dom.frame) {
dom.frame = document.createElement("DIV");
dom.frame.className = "timeline-frame ui-widget ui-widget-content ui-corner-all";
dom.container.appendChild(dom.frame);
needsReflow = true;
}
var height = options.autoHeight ?
(size.actualHeight + "px") :
(options.height || "100%");
var width = options.width || "100%";
needsReflow = needsReflow || (dom.frame.style.height != height);
needsReflow = needsReflow || (dom.frame.style.width != width);
dom.frame.style.height = height;
dom.frame.style.width = width;
// contents
if (!dom.content) {
// create content box where the axis and items will be created
dom.content = document.createElement("DIV");
dom.content.className = "timeline-content";
dom.frame.appendChild(dom.content);
var timelines = document.createElement("DIV");
timelines.style.position = "absolute";
timelines.style.left = "0px";
timelines.style.top = "0px";
timelines.style.height = "100%";
timelines.style.width = "0px";
dom.content.appendChild(timelines);
dom.contentTimelines = timelines;
var params = this.eventParams,
me = this;
if (!params.onMouseDown) {
params.onMouseDown = function (event) {me.onMouseDown(event);};
links.Timeline.addEventListener(dom.content, "mousedown", params.onMouseDown);
}
if (!params.onTouchStart) {
params.onTouchStart = function (event) {me.onTouchStart(event);};
links.Timeline.addEventListener(dom.content, "touchstart", params.onTouchStart);
}
if (!params.onMouseWheel) {
params.onMouseWheel = function (event) {me.onMouseWheel(event);};