-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
timeline.js
5144 lines (4701 loc) · 231 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
import "core-js/stable"
import "regenerator-runtime/runtime"
/*!
* jQuery Timeline
* ------------------------
* Version: 2.1.2
* Author: Ka2 (https://ka2.org/)
* Repository: https://github.com/ka215/jquery.timeline
* Lisenced: MIT
*/
/* ----------------------------------------------------------------------------------------------------------------
* Constants
* ----------------------------------------------------------------------------------------------------------------
*/
const NAME = "Timeline"
const VERSION = "2.1.2"
const DATA_KEY = "jq.timeline"
const EVENT_KEY = `.${DATA_KEY}`
const PREFIX = "jqtl-"
const IS_TOUCH = 'ontouchstart' in window
const MIN_POINTER_SIZE = 12
const JQUERY_NO_CONFLICT = $.fn[NAME]
const Default = {
type : "bar",
scale : "day",
startDatetime : "currently",
endDatetime : "auto",
range : 3,
rows : "auto",
rowHeight : 48,
width : "auto",
height : "auto",
minGridSize : 30,
marginHeight : 2,
headline : {
display : true,
title : "",
range : true,
locale : "en-US",
format : { hour12: false }
},
sidebar : {
sticky : false,
overlay : false,
list : [],
},
ruler : {
truncateLowers : false,
top : {
lines : [],
height : 30,
fontSize : 14,
color : "inherit",// Changed since v2.1.0, an old value is "#777777"
background : "inherit",// Changed since v2.1.0, an old value is "#FFFFFF"
locale : "en-US",
format : { hour12: false }
},
bottom : {// Added since v2.1.0 to fix #61
lines : [],
height : 30,
fontSize : 14,
color : "inherit",
background : "inherit",
locale : "en-US",
format : { hour12: false }
}
},
footer : {
display : true,
content : "",
range : false,
locale : "en-US",
format : { hour12: false }
},
eventMeta : {
display : false,
scale : "day",
locale : "en-US",
format : { hour12: false },
content : ""
},
eventData : [],
effects : {
presentTime : true,
hoverEvent : true,
stripedGridRow : true,
horizontalGridStyle : "dotted",
verticalGridStyle : "solid",
},
//startHour : 0, // Merge PR#37
//endHour : 23, // Merge PR#37
/*
hourPeriod : { // Added new option inspired from PR#37; Available only if the scale is "day"( or "week")
start : 0,
end : 23,
},
*/
colorScheme : { // Added new option since v2.0.0
theme : { // Added new option since v2.1.0
name : "default",
text : "#343A40",
subtext : "#707070",
offtext : "#BBBBBB",
modesttext : "#969696",
line : "#6C757D",
offline : "#DDDDDD",
activeline : "#DC3545",
background : "#FFFFFF",
invertbg : "#121212",
striped1 : "#F7F7F7",
striped2 : "#F0F0F0",
active : "#F73333",
marker : "#2C7CFF",
gridbase : "#333333"
},
event : {
text : "#343A40",
border : "#6C757D",
background : "#E7E7E7"
},
hookEventColors : () => null, // Added instead of merging setColorEvent of PR#37 since v2.0.0
},
// onOpenEvent : () => null, // Merge PR#37; (event) => null
rangeAlign : "latest",
loader : "default",
loadingMessage : "",
hideScrollbar : false,
storage : "session",
reloadCacheKeep : true,
zoom : false,
wrapScale : true,
firstDayOfWeek : 0, // 0: Sunday, 1: Monday, ... 6: Saturday
engine : "canvas",
disableLimitter : false, // Added new option since v2.1.2
debug : false,
// datetimeFormat : {}, // --> Deprecated since v2.0.0
// datetimePrefix : "", // --> Deprecated since v2.0.0
// duration : 150, // --> Deprecated since v2.0.0
// showPointer : true, // --> Deprecated since v2.0.0
// httpLanguage : false, // --> Deprecated since v2.0.0
// i18n : {}, // --> Deprecated since v2.0.0
// langsDir : "./langs/", // --> Deprecated since v2.0.0
// minGridPer : 2, // --> Deprecated since v2.0.0
// minuteInterval : 30, // --> Deprecated since v2.0.0
// naviIcon : {}, // --> Deprecated since v2.0.0
// showHeadline : true, // --> Deprecated since v2.0.0
// zerofillYear : false, // --> Deprecated since v2.0.0
}
const LimitScaleGrids = {
millennium : 100,
century : 100 * 5,
decade : 10 * 50,
lustrum : 5 * 100,
year : 500,
month : 12 * 45,
week : 53 * 10,
day : 366,
hour : 24 * 30,
quarterHour : 24 * 4 * 7.5,
halfHour : 24 * 2 * 15,
minute : 60 * 12,
second : 60 * 15
}
const EventParams = {
uid : "",
eventId : "",
x : 0,
y : Default.marginHeight,
width : Default.minGridSize,
height : Default.rowHeight - Default.marginHeight * 2,
start : "",
end : "",
row : 1,
bgColor : Default.colorScheme.event.background, // Modified since v2.0.0
color : Default.colorScheme.event.text, // Modified since v2.0.0
bdColor : Default.colorScheme.event.border, // Modified since v2.0.0
label : "",
content : "",
category : "", // Added new option since v2.0.0
image : "",
margin : Default.marginHeight,
rangeMeta : "",
size : "normal",
type : "",
extend : {},
remote : false,
relation : {},
callback() {}
}
const Event = {
INITIALIZED : `initialized${EVENT_KEY}`,
HIDE : `hide${EVENT_KEY}`,
SHOW : `show${EVENT_KEY}`,
CLICK_EVENT : `click.open${EVENT_KEY}`,
FOCUSIN_EVENT : `focusin.event${EVENT_KEY}`,
FOCUSOUT_EVENT : `focusout.event${EVENT_KEY}`,
TOUCHSTART_TIMELINE: `mousedown.timeline${EVENT_KEY}`, // Deleted touchstart.timeline${EVENT_KEY} because never work the openEvent on touch device; since v2.0.0
TOUCHMOVE_TIMELINE : `mousemove.timeline${EVENT_KEY}`, // Deleted touchmove.timeline${EVENT_KEY} because never work the openEvent on touch device; since v2.0.0
TOUCHEND_TIMELINE : `mouseup.timeline${EVENT_KEY}`, // Deleted touchend.timeline${EVENT_KEY} because never work the openEvent on touch device; since v2.0.0
MOUSEENTER_POINTER : `mouseenter.pointer${EVENT_KEY}`,
MOUSELEAVE_POINTER : `mouseleave.pointer${EVENT_KEY}`,
ZOOMIN_SCALE : `dblclick.zoom${EVENT_KEY}`
}
const ClassName = {
TIMELINE_CONTAINER : `${PREFIX}container`,
TIMELINE_MAIN : `${PREFIX}main`,
TIMELINE_HEADLINE : `${PREFIX}headline`,
TIMELINE_HEADLINE_WRAPPER : `${PREFIX}headline-wrapper`,
HEADLINE_TITLE : `${PREFIX}timeline-title`,
RANGE_META : `${PREFIX}range-meta`,
RANGE_SPAN : `${PREFIX}range-span`,
TIMELINE_EVENT_CONTAINER : `${PREFIX}event-container`,
TIMELINE_BACKGROUND_GRID : `${PREFIX}bg-grid`,
TIMELINE_RELATION_LINES : `${PREFIX}relation-lines`,
TIMELINE_EVENTS : `${PREFIX}events`,
TIMELINE_EVENT_NODE : `${PREFIX}event-node`,
TIMELINE_EVENT_LABEL : `${PREFIX}event-label`,
TIMELINE_EVENT_THUMBNAIL : `${PREFIX}event-thumbnail`,
TIMELINE_RULER_LINES : `${PREFIX}ruler-line-rows`,
TIMELINE_RULER_ITEM : `${PREFIX}ruler-line-item`,
TIMELINE_SIDEBAR : `${PREFIX}side-index`,
TIMELINE_SIDEBAR_MARGIN : `${PREFIX}side-index-margin`,
TIMELINE_SIDEBAR_ITEM : `${PREFIX}side-index-item`,
TIMELINE_FOOTER : `${PREFIX}footer`,
TIMELINE_FOOTER_CONTENT : `${PREFIX}footer-content`,
VIEWER_EVENT_TITLE : `${PREFIX}event-title`,
VIEWER_EVENT_CONTENT : `${PREFIX}event-content`,
VIEWER_EVENT_META : `${PREFIX}event-meta`,
VIEWER_EVENT_IMAGE_WRAPPER : `${PREFIX}event-image-wrapper`,
VIEWER_EVENT_IMAGE : `${PREFIX}event-image`,
VIEWER_EVENT_TYPE_POINTER : `${PREFIX}event-type-pointer`,
HIDE_SCROLLBAR : `${PREFIX}hide-scrollbar`,
HIDE : `${PREFIX}hide`,
RULER_ITEM_ALIGN_LEFT : `${PREFIX}rli-left`,
STICKY_LEFT : `${PREFIX}sticky-left`,
OVERLAY : `${PREFIX}overlay`,
ALIGN_SELF_RIGHT : `${PREFIX}align-self-right`,
PRESENT_TIME_MARKER : `${PREFIX}present-time`,
LOADER_CONTAINER : `${PREFIX}loader`,
LOADER_ITEM : `${PREFIX}loading`
}
const Selector = {
EVENT_NODE : `.${PREFIX}event-node`,
EVENT_VIEW : `.timeline-event-view, .${PREFIX}event-view`,
RULER_TOP : `.${PREFIX}ruler-top`,
RULER_BOTTOM : `.${PREFIX}ruler-bottom`,
TIMELINE_CONTAINER : `.${ClassName.TIMELINE_CONTAINER}`,
TIMELINE_MAIN : `.${ClassName.TIMELINE_MAIN}`,
HEADLINE_TITLE : `.${ClassName.HEADLINE_TITLE}`,// Added since v2.1.0
RANGE_META : `.${ClassName.RANGE_META}`,// Added since v2.1.0
TIMELINE_RULER_TOP : `.${PREFIX}ruler-top`,
TIMELINE_EVENT_CONTAINER : `.${ClassName.TIMELINE_EVENT_CONTAINER}`,
TIMELINE_RULER_BOTTOM : `.${PREFIX}ruler-bottom`,
TIMELINE_RULER_LINES : `.${ClassName.TIMELINE_RULER_LINES}`,// Added since v2.1.0
TIMELINE_RULER_ITEM : `.${ClassName.TIMELINE_RULER_ITEM}`,
TIMELINE_RELATION_LINES : `.${ClassName.TIMELINE_RELATION_LINES}`,
TIMELINE_EVENTS : `.${ClassName.TIMELINE_EVENTS}`,
TIMELINE_SIDEBAR : `.${ClassName.TIMELINE_SIDEBAR}`,
TIMELINE_SIDEBAR_MARGIN : `.${ClassName.TIMELINE_SIDEBAR_MARGIN}`,// Added since v2.1.0
TIMELINE_SIDEBAR_ITEM : `.${ClassName.TIMELINE_SIDEBAR_ITEM}`,
TIMELINE_EVENT_NODE : `.${ClassName.TIMELINE_EVENT_NODE}`,
VIEWER_EVENT_TITLE : `.${ClassName.VIEWER_EVENT_TITLE}`,// Added since v2.1.0
VIEWER_EVENT_CONTENT : `.${ClassName.VIEWER_EVENT_CONTENT}`,// Added since v2.1.0
VIEWER_EVENT_META : `.${ClassName.VIEWER_EVENT_META}`,// Added since v2.1.0
VIEWER_EVENT_TYPE_POINTER : `.${ClassName.VIEWER_EVENT_TYPE_POINTER}`,
OVERLAY : `.${ClassName.OVERLAY}`,// Added since v2.1.0
PRESENT_TIME_MARKER : `.${ClassName.PRESENT_TIME_MARKER}`,// Added since v2.1.0
LOADER : `.${ClassName.LOADER_CONTAINER}`,
LOADER_ITEM : `.${ClassName.LOADER_ITEM}`,// Added since v2.1.0
DEFAULT_EVENTS : ".timeline-events"
}
const mapData = (() => {
const storeData = {}
let id = 1
return {
set( element, key, data ) {
if ( typeof element.key === 'undefined' ) {
element.key = { key, id }
id++
}
storeData[element.key.id] = data
},
get( element, key ) {
if ( ! element || typeof element.key === 'undefined' ) {
return null
}
const keyProperties = element.key
if ( keyProperties.key === key ) {
return storeData[keyProperties.id]
}
return null
},
delete( element, key ) {
if ( typeof element.key === 'undefined' ) {
return
}
const keyProperties = element.key
if ( keyProperties.key === key ) {
delete storeData[keyProperties.id]
delete element.key
}
}
}
})()
const Data = {
setData( instance, key, data ) {
mapData.set( instance, key, data )
},
getData( instance, key ) {
return mapData.get( instance, key )
},
removeData( instance, key ) {
mapData.delete( instance, key )
}
}
/* ----------------------------------------------------------------------------------------------------------------
* Plugin Core Class
* ----------------------------------------------------------------------------------------------------------------
*/
class Timeline {
constructor( element, config ) {
this._config = this._getConfig( config )
this._element = element
this._selector = null
this._isInitialized = false
this._isCached = false
this._isCompleted = false
this._isShown = false
this._isTouched = false
this._instanceProps = {}
this._observer = null // Added new since v2.0.0
this._beforeOpenEvent = null // Added new since v2.0.0
//this._countEventinCell = {} // since v2.0.0
Data.setData( element, DATA_KEY, this )
}
// Getters
static get VERSION() {
return VERSION
}
static get Default() {
return Default
}
// Private
/*
* @private: Define the default options of this plugin
*/
_getConfig( config ) {
// config = { ...Default, ...config } // Note: this is NG because two objects have not merged deeply
if ( config.startDatetime instanceof Date ) {
config.startDatetime = config.startDatetime.toString()
}
if ( config.endDatetime instanceof Date ) {
config.endDatetime = config.endDatetime.toString()
}
return this.mergeDeep( Default, config )
}
/*
* @private: Filter the given scale key name to allowed for plugin
*/
_filterScaleKeyName( key ) {
let filteredKey = null
switch( true ) {
case /^millenniums?|millennia$/i.test( key ):
filteredKey = 'millennium'
break
case /^century$/i.test( key ):
filteredKey = 'century'
break
case /^dec(ade|ennium)$/i.test( key ):
filteredKey = 'decade'
break
case /^lustrum$/i.test( key ):
filteredKey = 'lustrum'
break
case /^years?$/i.test( key ):
filteredKey = 'year'
break
case /^months?$/i.test( key ):
filteredKey = 'month'
break
case /^weeks?$/i.test( key ):
filteredKey = 'week'
break
case /^weekdays?$/i.test( key ):
filteredKey = 'weekday'
break
case /^da(y|te)s?$/i.test( key ):
filteredKey = 'day'
break
case /^hours?$/i.test( key ):
filteredKey = 'hour'
break
case /^quarter-?(|hour)$/i.test( key ):
filteredKey = 'quarterHour'
break
case /^half-?(|hour)$/i.test( key ):
filteredKey = 'halfHour'
break
case /^minutes?$/i.test( key ):
filteredKey = 'minute'
break
case /^seconds?$/i.test( key ):
filteredKey = 'second'
break
default:
filteredKey = 'millisecond'
}
return filteredKey
}
/*
* @private: Initialize the plugin
*/
async _init() {
this._debug( '_init' )
let _elem = this._element,
_selector = `${_elem.tagName}${( _elem.id ? `#${_elem.id}` : '' )}${( _elem.className ? `.${_elem.className.replace(/\s/g, '.')}` : '' )}`
this._selector = _selector//.toLowerCase()
if ( this._isInitialized || this._isCompleted ) {
return this
}
this._calcVars()
this.showLoader()
if ( ! this._verifyMaxRenderableRange() ) {
throw new RangeError( `Timeline display period exceeds maximum renderable range.` )
}
this._renderView()
if ( ! this._isCached ) {
this._loadEvent()
}
if ( this._isCached ) {
await this._placeEvent()
}
// Assign events for the timeline
$(document).on(
Event.CLICK_EVENT,
`${this._selector} ${Selector.EVENT_NODE}`,
( event ) => this.openEvent( event )
)
$(_elem).on(
Event.FOCUSIN_EVENT,
Selector.TIMELINE_EVENT_NODE,
( event ) => this._activeEvent( event )
)
$(_elem).on(
Event.FOCUSOUT_EVENT,
Selector.TIMELINE_EVENT_NODE,
( event ) => this._activeEvent( event )
)
$(_elem).on(
Event.TOUCHSTART_TIMELINE,
Selector.TIMELINE_MAIN,
( event ) => this._swipeStart( event )
)
$(_elem).on(
Event.TOUCHMOVE_TIMELINE,
Selector.TIMELINE_MAIN,
( event ) => this._swipeMove( event )
)
$(_elem).on(
Event.TOUCHEND_TIMELINE,
Selector.TIMELINE_MAIN,
( event ) => this._swipeEnd( event )
)
if ( /^point(|er)$/i.test( this._config.type ) ) {
$(_elem).on(
Event.MOUSEENTER_POINTER,
Selector.VIEWER_EVENT_TYPE_POINTER,
( event ) => this._hoverPointer( event )
)
$(_elem).on(
Event.MOUSELEAVE_POINTER,
Selector.VIEWER_EVENT_TYPE_POINTER,
( event ) => this._hoverPointer( event )
)
}
if ( this._config.zoom ) {
$(_elem).on(
Event.ZOOMIN_SCALE,
Selector.TIMELINE_RULER_ITEM,
( event ) => this.zoomScale( event )
)
}
$(_elem).find( Selector.TIMELINE_CONTAINER ).on(
'scroll',
( event ) => this._scrollTimeline( event )
)
this._isCompleted = true
await this.hideLoader()
this.alignment()
if ( ! this._isInitialized ) {
const afterInitEvent = $.Event( Event.INITIALIZED, _elem )
$(_elem).trigger( afterInitEvent )
$(_elem).off( Event.INITIALIZED )
}
// Binding bs.popover
if ( $.fn['popover'] ) {
$('[data-toggle="popover"]').popover()
}
}
/*
* @private: Calculate each properties of the timeline instance
*/
_calcVars() {
let _opts = this._config,
_props = {},
_callback = ( _ac, _cv ) => {
if ( this.verifyScale( _cv ) ) {
_cv = this._filterScaleKeyName( _cv )
if ( _ac.indexOf( _cv ) === -1 ) {
_ac.push( _cv )
}
}
return _ac
}
_props.begin = this.supplement( null, this._getPluggableDatetime( _opts.startDatetime, 'first' ) ) // The milliseconds as start datetime (:> 開始日時のミリ秒
_props.end = this.supplement( null, this._getPluggableDatetime( _opts.endDatetime, 'last' ) ) // The milliseconds as end datetime (:> 終了日時のミリ秒
_props.scaleSize = this.supplement( null, _opts.minGridSize, this.validateNumeric ) // The minimum width of one grid on the base scale (:> 基本スケール上の1グリッドの最小幅
_props.rows = this._getPluggableRows() // The number of rows on the timeline container (:> タイムラインコンテナの行数
_props.rowSize = this.supplement( null, _opts.rowHeight, this.validateNumeric ) // The height of one row on the timeline container (:> タイムラインコンテナの1行の高さ
_props.width = this.supplement( null, _opts.width, this.validateNumeric ) // ?
_props.height = this.supplement( null, _opts.height, this.validateNumeric ) // ?
_props.isVLS = true // Whether is the variable length scale, fixed as constraint value of the "true" since v2.0.0b2
// _props.scale // The basic millisecond of one base grid on the setting scale (:> 設定スケールにおける起点グリッド1目盛の基準ミリ秒
// _props.grids // Number of base grids on the setting scale (= number of grids displayed) (:> 設定スケールにおける起点グリッド数(=表示されるグリッド数)
// _props.variableScale // An object that referable as the width of the base grid on the setting scale (:> 設定スケールにおける起点グリッド幅の幅員基準値となるオブジェクト
// _props.gridsMap // An object that mapped the available grids (:> 有効グリッドをマップしたオブジェクト -> これを定義するとメモリを食うのでNG
// _props.rulers // The available scale list on the ruler (:> 有効な目盛のスケールリスト
// _props.fullwidth // The total width of the timeline container (:> タイムラインコンテナの横幅の全長
// _props.fullheight // The total height of the timeline container (:> タイムラインコンテナの縦幅の全長
// _props.visibleWidth // The width of the timeline that will display (:> 表示されるタイムラインの横幅
// _props.visibleHeight // The height of the timeline that will display (:> 表示されるタイムラインの縦幅
_props.absX = 0 // An absolute X position on the page for using in swipe event (:> スワイプイベント用
_props.moveX = 0 // The moving position after doing the touchstart for using in swipe event (:> スワイプイベント用
// get all scales on ruler
let _rulers = _opts.ruler.top.lines.reduce( _callback, [])
if ( Object.hasOwnProperty.call( _opts.ruler, 'bottom' ) && Object.hasOwnProperty.call( _opts.ruler.bottom, 'lines' ) ) {
_rulers = [..._rulers, ..._opts.ruler.bottom.lines].reduce( _callback, [] )
}
if ( this.is_empty( _rulers ) ) {
_opts.ruler.top.lines.push( _opts.scale )
_rulers.push( _opts.scale )
}
_props.rulers = _rulers
this._instanceProps = _props // pre-cache
if ( _props.isVLS ) {
// For scales where the value of quantity per unit is variable length (:> 単位あたりの量の値が可変長であるスケールの場合
let _temp = this.verifyScale( _opts.scale, _props.begin, _props.end, _props.isVLS ),
_values = Object.values( _temp ),
//_averageVar = this.numRound( _values.reduce( ( a, v ) => a + v, 0 ) / _values.length, 4 ), // Average value within the range
//_minVar = Math.min( ..._values ),
_baseVar = /^weeks?$/i.test( _opts.scale ) ? Math.max( ..._values ) : Math.min( ..._values ),
_totalWidth = 0//,
//_baseToMin = true, // Whether use min value of scale as base grid width (:> スケールの最小値をベースグリッド幅として使用するか
//_baseVar = _baseToMin ? _minVar : _averageVar
switch ( true ) {
case /^millenniums?|millennia$/i.test( _opts.scale ):
case /^century$/i.test( _opts.scale ):
// unit: years = 365.25 * 24 * 60 * 60 * 1000
_props.scale = _baseVar * ( 365.25 * 24 * 60 * 60 * 1000 )
break
case /^dec(ade|ennium)$/i.test( _opts.scale ):
case /^lustrum$/i.test( _opts.scale ):
case /^years?$/i.test( _opts.scale ):
case /^months?$/i.test( _opts.scale ):
// unit: days = 24 * 60 * 60 * 1000
_props.scale = _baseVar * ( 24 * 60 * 60 * 1000 )
break
case /^weeks?$/i.test( _opts.scale ):
case /^(|week)days?$/i.test( _opts.scale ):
// unit: hours = 60 * 60 * 1000
_props.scale = _baseVar * ( 60 * 60 * 1000 )
break
case /^hours?$/i.test( _opts.scale ):
// unit: minutes = 60 * 1000
_props.scale = _baseVar * ( 60 * 1000 )
break
case /^minutes?$/i.test( _opts.scale ):
// unit: seconds = 1000
_props.scale = _baseVar * 1000
break
case /^seconds?$/i.test( _opts.scale ):
default:
// unit: milliseconds = 1
_props.scale = _baseVar * 1
break
}
//console.log( '!_calcVars::', _opts.scale, _temp, _values, _props )
_values.forEach( ( val ) => {
//console.log( `!!_calcVars::_totalWidth: ${_totalWidth} + ${this.numRound( ( val * _props.scaleSize ) / _baseVar, 2 )}` )
_totalWidth += this.numRound( ( val * _props.scaleSize ) / _baseVar, 2 )
})
_props.grids = _values.length
_props.variableScale = _temp
_props.fullwidth = _totalWidth
} else {
// Deprecated since v2.0.0 stable; in case of fixed length scale
}
_props.fullheight = _props.rows * _props.rowSize // Provisional value as theoretical value
// Define visible size according to full size of timeline (:> タイムラインのフルサイズに準じた可視サイズを定義
_props.visibleWidth = _props.width > 0 ? `${( _props.width <= _props.fullwidth ? _props.width : _props.fullwidth )}px` : 'max-content'
_props.visibleHeight = _props.height > 0 ? `${( _props.height <= _props.fullheight ? _props.height : _props.fullheight )}px` : 'max-content'
for ( let _prop in _props ) {
if ( /^(width|height|variableScale|absX|moveX)$/.test( _prop ) ) {
continue
}
if ( this.is_empty( _props[_prop] ) ) {
throw new TypeError( `Property "${_prop}" cannot set because undefined or invalid variable.` )
}
}
if ( _props.fullwidth < 2 || _props.fullheight < 2 ) {
throw new TypeError( `The range of the timeline to be rendered is incorrect.` )
}
//console.log( '!_calcVars::return:', _props )
this._instanceProps = _props
}
/*
* @private: Retrieve the pluggable datetime as milliseconds depend on specific preset keyword
*
* @param mixed key (required; preset keywords 'current', 'currently', 'auto' or seed of datetime)
* @param string round_type (optional; defaults to '')
*
* @return int (milliseconds as valid datetime)
*/
_getPluggableDatetime( key, round_type = '' ) {
let _opts = this._config,
_date = null,
getFirstDate = ( dateObj, scale ) => {
let _fullYear = dateObj.getFullYear(),
_remapYear = _fullYear >= 0 && Math.abs( _fullYear ) < 100 ? true : false,
_tmpDate
switch ( true ) {
case /^millenniums?|millennia$/i.test( scale ):
case /^century$/i.test( scale ):
case /^dec(ade|ennium)$/i.test( scale ):
case /^lustrum$/i.test( scale ):
case /^years?$/i.test( scale ):
_tmpDate = new Date( _fullYear, 0, 1 )
break
case /^months?$/i.test( scale ):
_tmpDate = new Date( _fullYear, dateObj.getMonth(), 1 )
break
case /^(week|day)s?$/i.test( scale ):
_tmpDate = new Date( _fullYear, dateObj.getMonth(), dateObj.getDate() )
break
case /^(|half|quarter)-?hours?$/i.test( scale ):
_tmpDate = new Date( _fullYear, dateObj.getMonth(), dateObj.getDate(), dateObj.getHours() )
break
case /^minutes?$/i.test( scale ):
_tmpDate = new Date( _fullYear, dateObj.getMonth(), dateObj.getDate(), dateObj.getHours(), dateObj.getMinutes() )
break
case /^seconds?$/i.test( scale ):
_tmpDate = new Date( _fullYear, dateObj.getMonth(), dateObj.getDate(), dateObj.getHours(), dateObj.getMinutes(), dateObj.getSeconds() )
break
default:
_tmpDate = new Date( _fullYear, dateObj.getMonth(), dateObj.getDate(), dateObj.getHours(), dateObj.getMinutes(), dateObj.getSeconds(), dateObj.getMilliseconds() )
break
}
if ( _remapYear ) {
_tmpDate.setFullYear( _fullYear )
}
return _tmpDate
},
getLastDate = ( dateObj, scale ) => {
let _fullYear = dateObj.getFullYear(),
_remapYear = _fullYear >= 0 && Math.abs( _fullYear ) < 100 ? true : false,
_offset = _fullYear >= 0 ? -1 : 1,
_tmpDate
switch ( true ) {
case /^millenniums?|millennia$/i.test( scale ):
case /^century$/i.test( scale ):
case /^dec(ade|ennium)$/i.test( scale ):
case /^lustrum$/i.test( scale ):
case /^years?$/i.test( scale ):
_tmpDate = new Date( _fullYear + 1, 0, 1 )
_remapYear = ( _fullYear + 1 ) >= 0 && Math.abs( _fullYear + 1 ) < 100 ? true : false
_offset = ( _fullYear + 1 ) >= 0 ? -1 : 1
break
case /^months?$/i.test( scale ):
_tmpDate = new Date( _fullYear, dateObj.getMonth() + 1, 1 )
break
case /^(week|day)s?$/i.test( scale ):
_tmpDate = new Date( _fullYear, dateObj.getMonth(), dateObj.getDate() + 1 )
break
case /^(|half|quarter)-?hours?$/i.test( scale ):
_tmpDate = new Date( _fullYear, dateObj.getMonth(), dateObj.getDate(), dateObj.getHours() + 1 )
break
case /^minutes?$/i.test( scale ):
_tmpDate = new Date( _fullYear, dateObj.getMonth(), dateObj.getDate(), dateObj.getHours(), dateObj.getMinutes() + 1 )
break
case /^seconds?$/i.test( scale ):
_tmpDate = new Date( _fullYear, dateObj.getMonth(), dateObj.getDate(), dateObj.getHours(), dateObj.getMinutes(), dateObj.getSeconds() + 1 )
break
default:
_tmpDate = new Date( _fullYear, dateObj.getMonth(), dateObj.getDate(), dateObj.getHours(), dateObj.getMinutes(), dateObj.getSeconds(), dateObj.getMilliseconds() + 1 )
break
}
if ( _remapYear ) {
_tmpDate.setFullYear( _fullYear )
}
return new Date( _tmpDate.getTime() + _offset )
}
//console.log( '!_getPluggableDatetime::return:', key )
switch ( true ) {
case /^current(|ly)$/i.test( key ):
// now date
_date = new Date()
break
case /^auto$/i.test( key ): {
let _auto_range = _opts.range && _opts.range > 0 ? parseInt( _opts.range, 10 ) : 3,
_higherScale = /^(|week)days?$/i.test( _opts.scale ) ? 'month' : this.getHigherScale( _opts.scale )
if ( /^current(|ly)$/i.test( _opts.startDatetime ) ) {
_date = getFirstDate( new Date(), _opts.scale )
} else {
_date = this.getCorrectDatetime( _opts.startDatetime )
}
_date = this.modifyDate( _date, _auto_range, _higherScale )
break
}
default:
_date = this.getCorrectDatetime( key )
break
}
if ( ! this.is_empty( round_type ) ) {
if ( 'first' === round_type ) {
_date = getFirstDate( _date, _opts.scale )
} else
if ( 'last' === round_type ) {
_date = getLastDate( _date, _opts.scale )
}
}
//console.log( '!!_getPluggableDatetime::return:', _date )
return _date.getTime()
}
/*
* @private: Retrieve the pluggable parameter as an object
*/
_getPluggableParams( str_like_params ) {
let params = {}
if ( typeof str_like_params === 'string' && str_like_params ) {
try {
params = JSON.parse( JSON.stringify( ( new Function( `return ${str_like_params}` ) )() ) )
if ( Object.hasOwnProperty.call( params, 'extend' ) && typeof params.extend === 'string' ) {
params.extend = JSON.parse( JSON.stringify( ( new Function( `return ${params.extend}` ) )() ) )
}
} catch( e ) {
//console.warn( 'Can not parse to object therefor invalid param.' )
this._error( 'Can not parse to object therefor invalid param.', 'warn' )
}
}
return params
}
/*
* @private: Retrieve the pluggable rows of the timeline (:> プラガブルなタイムラインの行数を取得する
*/
_getPluggableRows() {
let _opts = this._config,
fixed_rows = this.supplement( 'auto', _opts.rows, this.validateNumeric )
if ( fixed_rows === 'auto' ) {
fixed_rows = _opts.sidebar.list.length
}
return fixed_rows > 0 ? fixed_rows : 1
}
/*
* @private: Verify the display period of the timeline does not exceed the maximum renderable range (:> タイムラインの表示期間が最大描画可能範囲を超過していないか検証する
*/
_verifyMaxRenderableRange( scale = this._config.scale ) {
if ( this._config.disableLimitter ) {
this._debug( `The scale limiter has been OFF::${scale}: ${this._instanceProps.grids} / ${LimitScaleGrids[this._filterScaleKeyName( scale )]}` )
return true
} else {
this._debug( `Verify max renderable range::${scale}: ${this._instanceProps.grids} / ${LimitScaleGrids[this._filterScaleKeyName( scale )]}` )
return this._instanceProps.grids <= LimitScaleGrids[this._filterScaleKeyName( scale )]
}
}
/*
* @private: Render the view of timeline container
*/
_renderView() {
this._debug( '_renderView' )
let _elem = this._element,
_opts = this._config,
_props = this._instanceProps,
_tl_container = $('<div></div>', { class: ClassName.TIMELINE_CONTAINER }),// .jqtl-container
_tl_main = $('<div></div>', { class: ClassName.TIMELINE_MAIN }),// .jqtl-main
$_el = $(_elem),// Cached an element
$_tl_parent = $_el.parent()
//console.log( '_renderView::', _elem, _opts, _props )
if ( $_el.length == 0 ) {
throw new TypeError( 'Does not exist the element to render a timeline container.' )
}
this._debug( `Timeline:{ fullWidth: ${_props.fullwidth}px, fullHeight: ${_props.fullheight}px, viewWidth: ${_props.visibleWidth}, viewHeight: ${_props.visibleHeight} }` )
$_el.css( 'position', 'relative' ) // initialize; not .empty()
if ( _opts.hideScrollbar ) {
_tl_container.addClass( ClassName.HIDE_SCROLLBAR )// .jqtl-hide-scrollbar
}
// Create the timeline headline (:> タイムラインの見出しを生成
$_el.prepend( this._createHeadline() )
// Create the timeline event container (:> タイムラインのイベントコンテナを生成
_tl_main.append( this._createEventContainer() )
// Create the timeline ruler (:> タイムラインの目盛を生成
if ( Object.hasOwnProperty.call( _opts.ruler, 'top' ) && Object.hasOwnProperty.call( _opts.ruler.top, 'lines' ) && ! this.is_empty( _opts.ruler.top.lines ) ) {
_tl_main.prepend( this._createRuler( 'top' ) )
}
if ( Object.hasOwnProperty.call( _opts.ruler, 'bottom' ) && Object.hasOwnProperty.call( _opts.ruler.bottom, 'lines' ) && ! this.is_empty( _opts.ruler.bottom.lines ) ) {
_tl_main.append( this._createRuler( 'bottom' ) )
}
// Create the timeline side index (:> タイムラインのサイドインデックスを生成
let margin = {
top : parseInt( _tl_main.find( Selector.RULER_TOP ).height(), 10 ) - 1,
bottom : parseInt( _tl_main.find( Selector.RULER_BOTTOM ).height(), 10 ) - 1
}
if ( _opts.sidebar.list.length > 0 ) {
_tl_container.prepend( this._createSideIndex( margin ) )
}
// Append the timeline container in the timeline element (:> タイムライン要素にタイムラインコンテナを追加
_tl_container.append( _tl_main )
$_el.append( _tl_container )
// Create the timeline footer (:> タイムラインのフッタを生成
$_el.append( this._createFooter() )
// Optimize the parent element of the timeline
if ( this.is_empty( $_el.attr( 'data-resized' ) ) ) {
//console.log( '_renderView::', $_tl_parent, Number(_tl_main.get(0).scrollWidth), Number($_el.get(0).scrollWidth), Number($_tl_parent.width() + 2) )
if ( $_el.get(0).scrollWidth > $_tl_parent.width() + 2 ) {
_tl_container.css({ width: $_tl_parent.width() - 2, height: _props.visibleHeight })
$_tl_parent.css({ maxWidth: '100vw', overflowX: 'hidden' })
} else {
_tl_container.css({ width: _props.visibleWidth, height: _props.visibleHeight })
}
$_el.attr( 'data-resized', true )
}
// Apply the theme color scheme
this.applyThemeStyle()
this._isShown = true
}
/*
* @private: Create the headline of the timeline (:> タイムラインの見出しを作成する
*/
_createHeadline() {
let _opts = this._config,
_props = this._instanceProps,
_display = this.supplement( Default.headline.display, _opts.headline.display, this.validateBoolean ),
_title = this.supplement( null, _opts.headline.title ),
_range = this.supplement( Default.headline.range, _opts.headline.range, this.validateBoolean ),
_locale = this.supplement( Default.headline.locale, _opts.headline.locale ),
_format = this.supplement( Default.headline.format, _opts.headline.format ),
_begin = this.supplement( null, _props.begin ),
_end = this.supplement( null, _props.end ),
_scale = _opts.scale,
_tl_headline = $('<div></div>', { class: ClassName.TIMELINE_HEADLINE }),// .jqtl-headline
_wrapper = $('<div></div>', { class: ClassName.TIMELINE_HEADLINE_WRAPPER })// .jqtl-headline-wrapper
if ( _title ) {
_wrapper.append( `<h3 class="${ClassName.HEADLINE_TITLE}">${_opts.headline.title}</h3>` )// .jqtl-timeline-title
}
if ( _range ) {
if ( _begin && _end ) {
let _meta = ''
if ( Object.hasOwnProperty.call( _format, 'custom' ) ) {
_scale = 'custom'
}
if ( [ 'year', 'month', 'day', 'week' ].includes( _scale ) ) {
_meta = `${this.getLocaleString( _opts.startDatetime, _scale, _locale, _format )}<span class="${ClassName.RANGE_SPAN}"></span>${this.getLocaleString( _opts.endDatetime, _scale, _locale, _format )}`
} else {
_meta = `${this.getLocaleString( _begin, _scale, _locale, _format )}<span class="${ClassName.RANGE_SPAN}"></span>${this.getLocaleString( _end, _scale, _locale, _format )}`
}
_wrapper.append( `<div class="${ClassName.RANGE_META}">${_meta}</div>` )// .jqtl-range-meta
}
}
if ( ! _display ) {
_tl_headline.addClass( ClassName.HIDE )// .jqtl-hide
}
return _tl_headline.append( _wrapper )
}
/*
* @private: Create the event container of the timeline (:> タイムラインのイベントコンテナを作成する
*/
_createEventContainer() {
let _opts = this._config,
_props = this._instanceProps,
_actualHeight = _props.fullheight + Math.ceil( _props.rows / 2 ) + 1,
_container = $('<div></div>', { class: ClassName.TIMELINE_EVENT_CONTAINER, style: `height:${_actualHeight}px;` }),
_events_bg = $(`<canvas width="${( _props.fullwidth - 1 )}" height="${_actualHeight}" class="${ClassName.TIMELINE_BACKGROUND_GRID}"></canvas>`),
_events_lines = $(`<canvas width="${( _props.fullwidth - 1 )}" height="${_actualHeight}" class="${ClassName.TIMELINE_RELATION_LINES}"></canvas>`),
_events_body = $('<div></div>', { class: ClassName.TIMELINE_EVENTS }),
_cy = 0,
ctx_grid = _events_bg[0].getContext('2d'),
_grid_style = { horizontal: 'dotted', vertical: 'solid' },
drawRowRect = ( pos_y, color ) => {
color = this.supplement( _opts.colorScheme.theme.background, color )
// console.log( 0, pos_y, _fullwidth, _size_row, color )
ctx_grid.fillStyle = color
ctx_grid.fillRect( 0, pos_y + 0.5, _props.fullwidth, _props.rowSize + 1.5 )
ctx_grid.stroke()
},
drawHorizontalLine = ( pos_y, style ) => {
let _correction = 0.5
switch ( true ) {
case /^solid$/i.test( style ):
style = 'solid'
break
case /^dotted$/i.test( style ):
style = 'dotted'
break
case /^none$/i.test( style ):
default:
return
}
ctx_grid.strokeStyle = this.hexToRgbA( _opts.colorScheme.theme.gridbase, 0.1 )// 'rgba( 51, 51, 51, 0.1 )'
ctx_grid.lineWidth = 1
ctx_grid.filter = 'url(#crisp)'
ctx_grid.beginPath()
if ( style === 'dotted' ) {
ctx_grid.setLineDash([ 1, 2 ])
} else {
ctx_grid.setLineDash([])
}