forked from Dogfalo/materialize
-
-
Notifications
You must be signed in to change notification settings - Fork 106
/
Copy pathtimepicker.ts
805 lines (734 loc) · 24.7 KB
/
timepicker.ts
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
import { Utils } from './utils';
import { Component, BaseOptions, InitElements, MElement, I18nOptions } from './component';
export type Views = 'hours' | 'minutes';
export interface TimepickerOptions extends BaseOptions {
/**
* Dial radius.
* @default 135
*/
dialRadius: number;
/**
* Outer radius.
* @default 105
*/
outerRadius: number;
/**
* Inner radius.
* @default 70
*/
innerRadius: number;
/**
* Tick radius.
* @default 20
*/
tickRadius: number;
/**
* Duration of the transition from/to the hours/minutes view.
* @default 350
*/
duration: number;
/**
* Specify a DOM element OR selector for a DOM element to render
* the time picker in, by default it will be placed before the input.
* @default null
*/
container: HTMLElement | string | null;
/**
* Show the clear button in the Timepicker.
* @default false
*/
showClearBtn: boolean;
/**
* Default time to set on the timepicker 'now' or '13:14'.
* @default 'now';
*/
defaultTime: string;
/**
* Millisecond offset from the defaultTime.
* @default 0
*/
fromNow: number;
/**
* Internationalization options.
*/
i18n: Partial<I18nOptions>;
/**
* Use 12 hour AM/PM clock instead of 24 hour clock.
* @default true
*/
twelveHour: boolean;
/**
* Vibrate device when dragging clock hand.
* @default true
*/
vibrate: boolean;
/**
* Callback function when a time is selected.
* @default null
*/
onSelect: (hour: number, minute: number) => void;
}
const _defaults: TimepickerOptions = {
dialRadius: 135,
outerRadius: 105,
innerRadius: 70,
tickRadius: 20,
duration: 350,
container: null,
defaultTime: 'now', // default time, 'now' or '13:14' e.g.
fromNow: 0, // Millisecond offset from the defaultTime
showClearBtn: false,
// internationalization
i18n: {
cancel: 'Cancel',
clear: 'Clear',
done: 'Ok'
},
twelveHour: true, // change to 12 hour AM/PM clock from 24 hour
vibrate: true, // vibrate the device when dragging clock hand
// Callbacks
onSelect: null
};
type Point = {
x: number;
y: number;
};
export class Timepicker extends Component<TimepickerOptions> {
declare el: HTMLInputElement;
id: string;
modalEl: HTMLElement;
plate: HTMLElement;
digitalClock: HTMLElement;
inputHours: HTMLInputElement;
inputMinutes: HTMLInputElement;
x0: number;
y0: number;
moved: boolean;
dx: number;
dy: number;
/**
* Current view on the timepicker.
* @default 'hours'
*/
currentView: Views;
hand: SVGElement;
minutesView: HTMLElement;
hours: number;
minutes: number;
/** The selected time. */
time: string;
/**
* If the time is AM or PM on twelve-hour clock.
* @default 'PM'
*/
amOrPm: 'AM' | 'PM';
static _template;
/** Vibrate device when dragging clock hand. */
vibrate: 'vibrate' | 'webkitVibrate' | null;
_canvas: HTMLElement;
hoursView: HTMLElement;
spanAmPm: HTMLSpanElement;
footer: HTMLElement;
private _amBtn: HTMLElement;
private _pmBtn: HTMLElement;
bg: Element;
bearing: Element;
g: Element;
toggleViewTimer: string | number | NodeJS.Timeout;
vibrateTimer: NodeJS.Timeout | number;
constructor(el: HTMLInputElement, options: Partial<TimepickerOptions>) {
super(el, options, Timepicker);
this.el['M_Timepicker'] = this;
this.options = {
...Timepicker.defaults,
...options
};
this.id = Utils.guid();
this._insertHTMLIntoDOM();
this._setupVariables();
this._setupEventHandlers();
this._clockSetup();
this._pickerSetup();
}
static get defaults(): TimepickerOptions {
return _defaults;
}
/**
* Initializes instance of Timepicker.
* @param el HTML element.
* @param options Component options.
*/
static init(el: HTMLInputElement, options?: Partial<TimepickerOptions>): Timepicker;
/**
* Initializes instances of Timepicker.
* @param els HTML elements.
* @param options Component options.
*/
static init(
els: InitElements<HTMLInputElement | MElement>,
options?: Partial<TimepickerOptions>
): Timepicker[];
/**
* Initializes instances of Timepicker.
* @param els HTML elements.
* @param options Component options.
*/
static init(
els: HTMLInputElement | InitElements<HTMLInputElement | MElement>,
options: Partial<TimepickerOptions> = {}
): Timepicker | Timepicker[] {
return super.init(els, options, Timepicker);
}
static _addLeadingZero(num: number) {
return (num < 10 ? '0' : '') + num;
}
static _createSVGEl(name: string) {
const svgNS = 'http://www.w3.org/2000/svg';
return document.createElementNS(svgNS, name);
}
static _Pos(e: TouchEvent | MouseEvent): Point {
if (e.type.startsWith('touch') && (e as TouchEvent).targetTouches.length >= 1) {
return {
x: (e as TouchEvent).targetTouches[0].clientX,
y: (e as TouchEvent).targetTouches[0].clientY
};
}
// mouse event
return { x: (e as MouseEvent).clientX, y: (e as MouseEvent).clientY };
}
static getInstance(el: HTMLElement): Timepicker {
return el['M_Timepicker'];
}
destroy() {
this._removeEventHandlers();
this.modalEl.remove();
this.el['M_Timepicker'] = undefined;
}
_setupEventHandlers() {
this.el.addEventListener('click', this._handleInputClick);
this.el.addEventListener('keydown', this._handleInputKeydown);
this.plate.addEventListener('mousedown', this._handleClockClickStart);
this.plate.addEventListener('touchstart', this._handleClockClickStart);
this.digitalClock.addEventListener('keyup', this._inputFromTextField);
this.inputHours.addEventListener('focus', () => this.showView('hours'));
this.inputHours.addEventListener('focusout', () => this.formatHours());
this.inputMinutes.addEventListener('focus', () => this.showView('minutes'));
this.inputMinutes.addEventListener('focusout', () => this.formatMinutes());
}
_removeEventHandlers() {
this.el.removeEventListener('click', this._handleInputClick);
this.el.removeEventListener('keydown', this._handleInputKeydown);
}
_handleInputClick = () => {
this.open();
};
_handleInputKeydown = (e: KeyboardEvent) => {
if (Utils.keys.ENTER.includes(e.key)) {
e.preventDefault();
this.open();
}
};
_handleTimeInputEnterKey = (e: KeyboardEvent) => {
if (Utils.keys.ENTER.includes(e.key)) {
e.preventDefault();
this._inputFromTextField();
}
};
_handleClockClickStart = (e) => {
e.preventDefault();
const clockPlateBR = this.plate.getBoundingClientRect();
const offset = { x: clockPlateBR.left, y: clockPlateBR.top };
this.x0 = offset.x + this.options.dialRadius;
this.y0 = offset.y + this.options.dialRadius;
this.moved = false;
const clickPos = Timepicker._Pos(e);
this.dx = clickPos.x - this.x0;
this.dy = clickPos.y - this.y0;
// Set clock hands
this.setHand(this.dx, this.dy, false);
// Mousemove on document
document.addEventListener('mousemove', this._handleDocumentClickMove);
document.addEventListener('touchmove', this._handleDocumentClickMove);
// Mouseup on document
document.addEventListener('mouseup', this._handleDocumentClickEnd);
document.addEventListener('touchend', this._handleDocumentClickEnd);
};
_handleDocumentClickMove = (e) => {
e.preventDefault();
const clickPos = Timepicker._Pos(e);
const x = clickPos.x - this.x0;
const y = clickPos.y - this.y0;
this.moved = true;
this.setHand(x, y, false);
};
_handleDocumentClickEnd = (e) => {
e.preventDefault();
document.removeEventListener('mouseup', this._handleDocumentClickEnd);
document.removeEventListener('touchend', this._handleDocumentClickEnd);
const clickPos = Timepicker._Pos(e);
const x = clickPos.x - this.x0;
const y = clickPos.y - this.y0;
if (this.moved && x === this.dx && y === this.dy) {
this.setHand(x, y);
}
if (this.currentView === 'hours') {
this.showView('minutes', this.options.duration / 2);
} else {
this.minutesView.classList.add('timepicker-dial-out');
setTimeout(() => {
this.done();
}, this.options.duration / 2);
}
if (typeof this.options.onSelect === 'function') {
this.options.onSelect.call(this, this.hours, this.minutes);
}
// Unbind mousemove event
document.removeEventListener('mousemove', this._handleDocumentClickMove);
document.removeEventListener('touchmove', this._handleDocumentClickMove);
};
_insertHTMLIntoDOM() {
const template = document.createElement('template');
template.innerHTML = Timepicker._template.trim();
this.modalEl = <HTMLElement>template.content.firstChild;
this.modalEl.id = 'modal-' + this.id;
// Append popover to input by default
const optEl = this.options.container;
const containerEl = optEl instanceof HTMLElement ? optEl : document.querySelector(optEl);
if (this.options.container && !!containerEl) {
containerEl.append(this.modalEl);
} else {
this.el.parentElement.appendChild(this.modalEl);
}
}
_setupVariables() {
this.currentView = 'hours';
this.vibrate = navigator.vibrate
? 'vibrate'
: navigator['webkitVibrate']
? 'webkitVibrate'
: null;
this._canvas = this.modalEl.querySelector('.timepicker-canvas');
this.plate = this.modalEl.querySelector('.timepicker-plate');
this.digitalClock = this.modalEl.querySelector('.timepicker-display-column');
this.hoursView = this.modalEl.querySelector('.timepicker-hours');
this.minutesView = this.modalEl.querySelector('.timepicker-minutes');
this.inputHours = this.modalEl.querySelector('.timepicker-input-hours');
this.inputMinutes = this.modalEl.querySelector('.timepicker-input-minutes');
this.spanAmPm = this.modalEl.querySelector('.timepicker-span-am-pm');
this.footer = this.modalEl.querySelector('.timepicker-footer');
this.amOrPm = 'PM';
}
private _createButton(text: string, visibility: string): HTMLButtonElement {
const button = document.createElement('button');
button.classList.add('btn', 'btn-flat', 'waves-effect', 'text');
button.style.visibility = visibility;
button.type = 'button';
button.tabIndex = -1;
button.innerText = text;
return button;
}
_pickerSetup() {
const clearButton = this._createButton(
this.options.i18n.clear,
this.options.showClearBtn ? '' : 'hidden'
);
clearButton.classList.add('timepicker-clear');
clearButton.addEventListener('click', this.clear);
this.footer.appendChild(clearButton);
const confirmationBtnsContainer = document.createElement('div');
confirmationBtnsContainer.classList.add('confirmation-btns');
this.footer.append(confirmationBtnsContainer);
const cancelButton = this._createButton(this.options.i18n.cancel, '');
cancelButton.classList.add('timepicker-close');
cancelButton.addEventListener('click', this.close);
confirmationBtnsContainer.appendChild(cancelButton);
const doneButton = this._createButton(this.options.i18n.done, '');
doneButton.classList.add('timepicker-close');
//doneButton.addEventListener('click', this._finishSelection);
confirmationBtnsContainer.appendChild(doneButton);
}
_clockSetup() {
if (this.options.twelveHour) {
// AM Button
this._amBtn = document.createElement('div');
this._amBtn.classList.add('am-btn', 'btn');
this._amBtn.innerText = 'AM';
this._amBtn.addEventListener('click', this._handleAmPmClick);
this.spanAmPm.appendChild(this._amBtn);
// PM Button
this._pmBtn = document.createElement('div');
this._pmBtn.classList.add('pm-btn', 'btn');
this._pmBtn.innerText = 'PM';
this._pmBtn.addEventListener('click', this._handleAmPmClick);
this.spanAmPm.appendChild(this._pmBtn);
}
this._buildHoursView();
this._buildMinutesView();
this._buildSVGClock();
}
_buildSVGClock() {
// Draw clock hands and others
const dialRadius = this.options.dialRadius;
const tickRadius = this.options.tickRadius;
const diameter = dialRadius * 2;
const svg = Timepicker._createSVGEl('svg');
svg.setAttribute('class', 'timepicker-svg');
svg.setAttribute('width', diameter.toString());
svg.setAttribute('height', diameter.toString());
const g = Timepicker._createSVGEl('g');
g.setAttribute('transform', 'translate(' + dialRadius + ',' + dialRadius + ')');
const bearing = Timepicker._createSVGEl('circle');
bearing.setAttribute('class', 'timepicker-canvas-bearing');
bearing.setAttribute('cx', '0');
bearing.setAttribute('cy', '0');
bearing.setAttribute('r', '4');
const hand = Timepicker._createSVGEl('line');
hand.setAttribute('x1', '0');
hand.setAttribute('y1', '0');
const bg = Timepicker._createSVGEl('circle');
bg.setAttribute('class', 'timepicker-canvas-bg');
bg.setAttribute('r', tickRadius.toString());
g.appendChild(hand);
g.appendChild(bg);
g.appendChild(bearing);
svg.appendChild(g);
this._canvas.appendChild(svg);
this.hand = hand;
this.bg = bg;
this.bearing = bearing;
this.g = g;
}
_buildHoursView() {
// const $tick = document.createElement('div');
// $tick.classList.add('timepicker-tick');
// Hours view
if (this.options.twelveHour) {
for (let i = 1; i < 13; i += 1) {
// const tick = <HTMLElement>$tick.cloneNode(true);
const radian = (i / 6) * Math.PI;
const radius = this.options.outerRadius;
this._buildHoursTick(i, radian, radius);
}
} else {
for (let i = 0; i < 24; i += 1) {
// const tick = <HTMLElement>$tick.cloneNode(true);
const radian = (i / 6) * Math.PI;
const inner = i > 0 && i < 13;
const radius = inner ? this.options.innerRadius : this.options.outerRadius;
this._buildHoursTick(i, radian, radius);
}
}
}
_buildHoursTick(i: number, radian: number, radius: number) {
const tick = document.createElement('div');
tick.classList.add('timepicker-tick');
tick.style.left =
this.options.dialRadius + Math.sin(radian) * radius - this.options.tickRadius + 'px';
tick.style.top =
this.options.dialRadius - Math.cos(radian) * radius - this.options.tickRadius + 'px';
tick.innerHTML = i === 0 ? '00' : i.toString();
this.hoursView.appendChild(tick);
}
_buildMinutesView() {
const _tick = document.createElement('div');
_tick.classList.add('timepicker-tick');
// Minutes view
for (let i = 0; i < 60; i += 5) {
const tick = <HTMLElement>_tick.cloneNode(true);
const radian = (i / 30) * Math.PI;
tick.style.left =
this.options.dialRadius +
Math.sin(radian) * this.options.outerRadius -
this.options.tickRadius +
'px';
tick.style.top =
this.options.dialRadius -
Math.cos(radian) * this.options.outerRadius -
this.options.tickRadius +
'px';
tick.innerHTML = Timepicker._addLeadingZero(i);
this.minutesView.appendChild(tick);
}
}
_handleAmPmClick = (e) => {
const btnClicked = <HTMLElement>e.target;
this.amOrPm = btnClicked.classList.contains('am-btn') ? 'AM' : 'PM';
this._updateAmPmView();
};
_updateAmPmView() {
if (this.options.twelveHour) {
if (this.amOrPm === 'PM') {
this._amBtn.classList.remove('filled');
this._pmBtn.classList.add('filled');
} else if (this.amOrPm === 'AM') {
this._amBtn.classList.add('filled');
this._pmBtn.classList.remove('filled');
}
}
}
_updateTimeFromInput() {
// Get the time
let value = ((this.el.value || this.options.defaultTime || '') + '').split(':');
if (this.options.twelveHour && !(typeof value[1] === 'undefined')) {
if (value[1].toUpperCase().indexOf('AM') > 0) {
this.amOrPm = 'AM';
} else {
this.amOrPm = 'PM';
}
value[1] = value[1].replace('AM', '').replace('PM', '');
}
if (value[0] === 'now') {
const now = new Date(+new Date() + this.options.fromNow);
value = [now.getHours().toString(), now.getMinutes().toString()];
if (this.options.twelveHour) {
this.amOrPm = parseInt(value[0]) >= 12 && parseInt(value[0]) < 24 ? 'PM' : 'AM';
}
}
this.hours = +value[0] || 0;
this.minutes = +value[1] || 0;
this.inputHours.value = Timepicker._addLeadingZero(this.hours);
this.inputMinutes.value = Timepicker._addLeadingZero(this.minutes);
this._updateAmPmView();
}
/**
* Show hours or minutes view on timepicker.
* @param view The name of the view you want to switch to, 'hours' or 'minutes'.
* @param delay
*/
showView = (view: Views, delay: number = null) => {
if (view === 'minutes' && getComputedStyle(this.hoursView).visibility === 'visible') {
// raiseCallback(this.options.beforeHourSelect);
}
const isHours = view === 'hours',
nextView = isHours ? this.hoursView : this.minutesView,
hideView = isHours ? this.minutesView : this.hoursView;
this.currentView = view;
if (isHours) {
this.inputHours.classList.add('text-primary');
this.inputMinutes.classList.remove('text-primary');
} else {
this.inputHours.classList.remove('text-primary');
this.inputMinutes.classList.add('text-primary');
}
// Transition view
hideView.classList.add('timepicker-dial-out');
nextView.style.visibility = 'visible';
nextView.classList.remove('timepicker-dial-out');
// Reset clock hand
this.resetClock(delay);
// After transitions ended
clearTimeout(this.toggleViewTimer);
this.toggleViewTimer = setTimeout(() => {
hideView.style.visibility = 'hidden';
}, this.options.duration);
};
resetClock(delay) {
const view = this.currentView,
value = this[view],
isHours = view === 'hours',
unit = Math.PI / (isHours ? 6 : 30),
radian = value * unit,
radius =
isHours && value > 0 && value < 13 ? this.options.innerRadius : this.options.outerRadius,
x = Math.sin(radian) * radius,
y = -Math.cos(radian) * radius;
if (delay) {
this._canvas?.classList.add('timepicker-canvas-out');
setTimeout(() => {
this._canvas?.classList.remove('timepicker-canvas-out');
this.setHand(x, y);
}, delay);
} else {
this.setHand(x, y);
}
}
_inputFromTextField = () => {
const isHours = this.currentView === 'hours';
if (isHours && this.inputHours.value !== '') {
const value = parseInt(this.inputHours.value);
if (value > 0 && value < (this.options.twelveHour ? 13 : 24)) {
this.hours = value;
} else {
this.setHoursDefault();
}
this.drawClockFromTimeInput(this.hours, isHours);
} else if (!isHours && this.inputMinutes.value !== '') {
const value = parseInt(this.inputMinutes.value);
if (value >= 0 && value < 60) {
this.minutes = value;
} else {
this.minutes = new Date().getMinutes();
this.inputMinutes.value = this.minutes.toString();
}
this.drawClockFromTimeInput(this.minutes, isHours);
}
};
drawClockFromTimeInput(value, isHours) {
const unit = Math.PI / (isHours ? 6 : 30);
const radian = value * unit;
let radius;
if (this.options.twelveHour) {
radius = this.options.outerRadius;
} else {
radius =
isHours && value > 0 && value < 13 ? this.options.innerRadius : this.options.outerRadius;
}
this.setClockAttributes(radian, radius);
}
setHand(x, y, roundBy5: boolean = false) {
const isHours = this.currentView === 'hours',
unit = Math.PI / (isHours || roundBy5 ? 6 : 30),
z = Math.sqrt(x * x + y * y),
inner = isHours && z < (this.options.outerRadius + this.options.innerRadius) / 2;
let radian = Math.atan2(x, -y),
radius = inner ? this.options.innerRadius : this.options.outerRadius;
if (this.options.twelveHour) {
radius = this.options.outerRadius;
}
// Radian should in range [0, 2PI]
if (radian < 0) {
radian = Math.PI * 2 + radian;
}
// Get the round value
let value = Math.round(radian / unit);
// Get the round radian
radian = value * unit;
// Correct the hours or minutes
if (this.options.twelveHour) {
if (isHours) {
if (value === 0) value = 12;
} else {
if (roundBy5) value *= 5;
if (value === 60) value = 0;
}
} else {
if (isHours) {
if (value === 12) {
value = 0;
}
value = inner ? (value === 0 ? 12 : value) : value === 0 ? 0 : value + 12;
} else {
if (roundBy5) {
value *= 5;
}
if (value === 60) {
value = 0;
}
}
}
// Once hours or minutes changed, vibrate the device
if (this[this.currentView] !== value) {
if (this.vibrate && this.options.vibrate) {
// Do not vibrate too frequently
if (!this.vibrateTimer) {
navigator[this.vibrate](10);
this.vibrateTimer = setTimeout(() => {
this.vibrateTimer = null;
}, 100);
}
}
}
this[this.currentView] = value;
if (isHours) {
this.inputHours.value = Timepicker._addLeadingZero(value);
} else {
this.inputMinutes.value = Timepicker._addLeadingZero(value);
}
// Set clock hand and others' position
this.setClockAttributes(radian, radius);
}
setClockAttributes(radian: number, radius: number) {
const cx1 = Math.sin(radian) * (radius - this.options.tickRadius),
cy1 = -Math.cos(radian) * (radius - this.options.tickRadius),
cx2 = Math.sin(radian) * radius,
cy2 = -Math.cos(radian) * radius;
this.hand.setAttribute('x2', cx1.toString());
this.hand.setAttribute('y2', cy1.toString());
this.bg.setAttribute('cx', cx2.toString());
this.bg.setAttribute('cy', cy2.toString());
}
formatHours() {
if (this.inputHours.value == '') this.setHoursDefault();
this.inputHours.value = Timepicker._addLeadingZero(Number(this.inputHours.value));
}
formatMinutes() {
if (this.inputMinutes.value == '') this.minutes = new Date().getMinutes();
this.inputMinutes.value = Timepicker._addLeadingZero(Number(this.inputMinutes.value));
}
setHoursDefault() {
this.hours = new Date().getHours();
this.inputHours.value = (this.hours % (this.options.twelveHour ? 12 : 24)).toString();
}
// todo: remove e
done = (e = null, clearValue = null) => {
// Set input value
const last = this.el.value;
let value = clearValue
? ''
: Timepicker._addLeadingZero(this.hours) + ':' + Timepicker._addLeadingZero(this.minutes);
this.time = value;
if (!clearValue && this.options.twelveHour) {
value = `${value} ${this.amOrPm}`;
}
this.el.value = value;
// Trigger change event
if (value !== last) {
this.el.dispatchEvent(
new Event('change', { bubbles: true, cancelable: true, composed: true })
);
}
//this.el.focus();
return e; // just for passing linter, can be removed
};
clear = () => {
this.done(null, true);
};
// deprecated
open() {
// this._updateTimeFromInput();
// this.showView('hours');
console.warn(
'Timepicker.close() is deprecated. Remove this method and wrap in modal yourself.'
);
return this;
}
close() {
console.warn(
'Timepicker.close() is deprecated. Remove this method and wrap in modal yourself.'
);
return this;
}
static {
Timepicker._template = `
<div class="modal timepicker-modal">
<div class="modal-content timepicker-container">
<div class="timepicker-digital-display">
<div class="timepicker-text-container">
<div class="timepicker-display-column">
<div class="timepicker-input-hours-wrapper">
<input type="text" maxlength="2" autofocus class="timepicker-input-hours text-primary" />
</div>
<div class="timepicker-input-divider-wrapper">
<span class="timepicker-input-divider">:</span>
</div>
<div class="timepicker-input-minutes-wrapper">
<input type="text" maxlength="2" class="timepicker-input-minutes" />
</div>
</div>
<div class="timepicker-display-column timepicker-display-am-pm">
<div class="timepicker-span-am-pm"></div>
</div>
</div>
</div>
<div class="timepicker-analog-display">
<div class="timepicker-plate">
<div class="timepicker-canvas"></div>
<div class="timepicker-dial timepicker-hours"></div>
<div class="timepicker-dial timepicker-minutes timepicker-dial-out"></div>
</div>
<div class="timepicker-footer"></div>
</div>
</div>
</div>`;
}
}