-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimepicker.js
More file actions
1948 lines (1833 loc) · 66.6 KB
/
Copy pathtimepicker.js
File metadata and controls
1948 lines (1833 loc) · 66.6 KB
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
// ==================== TimePicker plugin ====================
// Encoding: UTF-8 without BOM (auto-detect: °°°°°) for built-in message texts
const inputWrapperClass = "ff-input-wrapper";
const svgNS = "http://www.w3.org/2000/svg";
// Chromium sources: https://github.com/chromium/chromium/tree/master/third_party/blink/public/strings/translations
// "en" is the fallback and must be complete.
const dictionary = {
cs: { y: "rrrr", month: "Měsíc", week1: null, week2: ". týden, ", w: "tt", today: "Dnes", now: "Teď", back: "Zpátky", keyboard: "Klávesnice", clear: "Smazat" },
da: { y: "åååå", month: "Måned", week1: "Uge ", w: "uu", today: "I dag", now: "Nu", back: "Tilbage", keyboard: "Tastatur", clear: "Slette" },
de: { y: "jjjj", month: "Monat", week1: "Woche ", w: "ww", d: "tt", today: "Heute", now: "Jetzt", back: "Zurück", keyboard: "Tastatur", clear: "Löschen" },
en: { y: "yyyy", month: "Month", mo: "mm", week1: "Week ", week2: ", ", w: "ww", d: "dd", today: "Today", now: "Now", back: "Back", keyboard: "Keyboard", clear: "Clear" },
es: { y: "aaaa", month: "Mes", week1: "Semana ", w: "ss", today: "Hoy", now: "Ahora", back: "Atrás", keyboard: "Teclado", clear: "Borrar" },
fi: { y: "vvvv", month: "Kuukausi", mo: "kk", week1: "Viikko ", w: "vv", d: "pp", today: "Tänään", now: "Nyt", back: "Takaisin", keyboard: "Näppäimistö", clear: "Poistaa" },
fr: { y: "aaaa", month: "Mois", week1: "Semaine ", w: "ss", d: "jj", today: "Aujourd’hui", now: "Maintenant", back: "Retour", keyboard: "Clavier", clear: "Supprimer" },
hu: { y: "éééé", month: "Hónap", mo: "hh", week1: null, week2: ". hét, ", w: "hh", d: "nn", today: "Ma", now: "Most", back: "Vissza", keyboard: "Billentyűzet", clear: "Töröl" },
is: { y: "áááá", month: "Mánuður", week1: "Vika ", w: "vv", today: "Í dag", now: "Núna", back: "Aftur", keyboard: "Lyklaborð", clear: "Eyðing" },
it: { y: "aaaa", month: "Mese", week1: "Settimana ", w: "ss", d: "gg", today: "Oggi", now: "Ora", back: "Indietro", keyboard: "Tastiera", clear: "Cancellare" },
nl: { y: "jjjj", month: "Maand", week1: "Week ", w: "ww", today: "Vandaag", now: "Nu", back: "Terug", keyboard: "Toetsenbord", clear: "Wissen" },
no: { y: "åååå", month: "Måned", week1: "Uke ", w: "uu", today: "I dag", now: "Nå", back: "Tilbake", keyboard: "Tastatur", clear: "Slette" },
pt: { y: "aaaa", month: "Mês", week1: "Semana ", week2: ", de ", w: "ss", today: "Hoje", now: "Agora", back: "De volta", keyboard: "Teclado", clear: "Cancelar" },
ro: { y: "aaaa", month: "Lună", mo: "ll", week1: "Săptămâna ", w: "ss", d: "zz", today: "Astăzi", now: "Acum", back: "Înapoi", keyboard: "Tastatură", clear: "Șterge" },
sk: { y: "rrrr", month: "Mesiac", week1: null, week2: ". týždeň, ", w: "tt", today: "Dnes", now: "Teraz", back: "Späť", keyboard: "Klávesnica", clear: "Vymazať" },
sl: { y: "llll", month: "Mesec", week1: null, week2: ". teden, ", w: "tt", today: "Danes", now: "Zdaj", back: "Nazaj", keyboard: "Tipkovnica", clear: "Izbrisati" },
sv: { y: "åååå", month: "Månad", week1: "Vecka ", week2: " ", w: "vv", today: "Idag", now: "Nu", back: "Tillbaka", keyboard: "Tangentbord", clear: "Radera" }
};
// Defines default options for the timePicker plugin.
let timePickerDefaults = {
// The locale used for formats and text translations. Default: Auto.
localeCode: undefined,
// A function that changes the format of a month item.
monthFormatter: undefined,
// A function that changes the format of a day item.
dayFormatter: undefined,
// Indicates whether the ISO 8601 date and time format is used instead of the local format.
isoFormat: false,
// The separator between date and time for ISO 8601 format. Can be set to "T".
isoFormatSeparator: ", "
};
// Converts each selected date/time input element into a masked text field with time picker button.
function timePicker(options) {
return this.forEach(input => {
if (input.parentElement.classList.contains(inputWrapperClass)) return; // Already done
let opt = F.initOptions("timePicker", input, {}, options);
let originalType = input.getAttribute("type").trim().toLowerCase();
let dateSelection = originalType === "date" || originalType === "datetime-local" || originalType === "month" || originalType === "week";
let weekSelection = originalType === "week";
let daySelection = originalType === "date" || originalType === "datetime-local";
let timeSelection = originalType === "datetime-local" || originalType === "time";
let step = +input.step || (timeSelection ? 60 : 1);
let minuteSelection = timeSelection && step < 3600;
let secondSelection = timeSelection && step < 60;
let required = input.required;
input.required = false; // We have no way to show a browser-generated message on the original hidden and new readonly field
// Put a wrapper between the input and its parent
let wrapper = F.c("div");
wrapper.classList.add(inputWrapperClass);
if (input.getAttribute("style"))
wrapper.setAttribute("style", input.getAttribute("style"));
if (!input.F.visible) {
wrapper.F.visible = false;
}
input.F.wrap(wrapper);
// Hide original input and add a new one, synchronise (and convert) values
input.F.hide();
input.autocomplete = "off";
let inputChanging = false;
let isKeyboardMode = false;
let newInput = F.c("input");
newInput.type = "text";
newInput.classList.add("ff-timepicker-input");
newInput.readonly = true;
newInput.inputMode = "none";
newInput.enterKeyHint = "done"; // Enter key is handled separately to close dropdown/keyboard but prevent submit
newInput.setAttribute("autocapitalize", "off");
newInput.setAttribute("autocomplete", "off");
newInput.setAttribute("autocorrect", "off");
newInput.setAttribute("spellcheck", "false");
input.after(newInput);
// Show or hide the new element wrapper instead whenever the <input> element should be shown or hidden
F.internalData.set(input, "visible.replacement", wrapper);
// Enable or disable the new element when the <input> element is enabled or disabled
disabledObservers = input.F.observeDisabled(disabled => {
newInput.F.disabled = disabled;
if (disabled) {
dropdown.F.dropdown.close();
}
});
if (input.F.disabled) {
newInput.F.disabled = true;
}
// Overwrite the focus method to focus the new visible element
//let origFocusFunction = input.focus; // TODO: Use for deinit
input.focus = () => newInput.focus();
// Copy some CSS classes to the replacement element
["input-validation-error", "dark", "not-dark"].forEach(clsName => {
if (input.classList.contains(clsName))
newInput.classList.add(clsName);
});
newInput.F.on("change", () => {
inputChanging = true;
input.F.value(getValue());
inputChanging = false;
validate();
updateViews();
});
input.F.on("change", () => {
if (!inputChanging) {
setValue(input.value);
newInput.F.trigger("input", { bubbles: true });
newInput.F.trigger("change", { bubbles: true });
}
});
newInput.F.on("copy", event => {
if (event.clipboardData) {
event.clipboardData.setData("text/plain", newInput.value);
event.preventDefault();
}
});
newInput.F.on("paste", event => {
event.preventDefault();
if (event.clipboardData) {
let text = event.clipboardData.getData("text");
let pattern = "";
let matchParts = [];
for (let i = 0; i < parts.length; i++) {
if (parts[i].name) {
if (parts[i].options) {
pattern += "(" + parts[i].options.map(F.regExpEscape).join("|") + ")";
}
else {
pattern += "([0-9]{1," + parts[i].length + "})";
}
matchParts.push(parts[i]);
}
else {
pattern += F.regExpEscape(parts[i].text);
}
}
let re = new RegExp("^" + pattern + "$");
let match = re.exec(text);
let newPartData = {};
if (match) {
for (let i = 0; i < matchParts.length; i++) {
let value = +match[i + 1];
if (isNaN(value)) {
value = matchParts[i].options.indexOf(match[i + 1]) + matchParts[i].min;
}
if (value < matchParts[i].min || value > matchParts[i].max) return; // Invalid value
newPartData[matchParts[i].name] = value;
}
partData = newPartData;
input.value = getValue(); // Update native field for validation/fixing
fixValue(true);
updateText();
newInput.F.trigger("input", { bubbles: true });
newInput.F.trigger("change", { bubbles: true });
}
}
});
newInput.F.forwardUIEvents(input, "blur");
function fixValue(noChangeEvent) {
let isComplete = true;
for (let i = 0; i < parts.length; i++) {
if (parts[i].name && !F.isSet(partData[parts[i].name])) {
isComplete = false;
break;
}
}
if (isComplete && !input.F.value()) {
// All values set but no valid value available
if (weekSelection) {
let part = findPart("w");
if (part) partData.w = getPartMax(part);
}
else {
let part = findPart("d");
if (part) partData.d = getPartMax(part);
}
if (!noChangeEvent) {
updateText();
newInput.F.trigger("input", { bubbles: true });
newInput.F.trigger("change", { bubbles: true });
}
}
}
function validate() {
if (required) {
if (input.F.value())
newInput.removeAttribute("pattern");
else
newInput.setAttribute("pattern", "^invalid$");
}
}
validate();
// Create picker dropdown
let dropdown = F.c("div");
dropdown.classList.add("dropdown", "bordered");
// Set up masked edit
let formatOptions = {
calendar: "gregory",
numberingSystem: "latn"
};
if (dateSelection && !weekSelection) {
if (daySelection) {
formatOptions.day = "numeric";
formatOptions.month = "numeric";
}
else {
formatOptions.month = "long";
}
formatOptions.year = "numeric";
}
if (timeSelection) {
formatOptions.hour = "numeric";
formatOptions.hour12 = false; // TODO: Add 12h clock support; detect from format part "dayPeriod"
if (minuteSelection) {
formatOptions.minute = "numeric";
if (secondSelection) {
formatOptions.second = "numeric";
}
}
}
let format = new Intl.DateTimeFormat(opt.localeCode, formatOptions);
let formatResolvedOptions = format.resolvedOptions();
//console.log(formatResolvedOptions);
let language = formatResolvedOptions.locale.split("-")[0];
let translate = F.getTranslator(dictionary, language);
// All data and text parts of the masked input
var parts = [];
if (!weekSelection) {
if (opt.isoFormat) {
if (dateSelection) {
parts.push({ name: "y", min: 1, max: 9999, length: 4, placeholder: translate("y") });
parts.push({ text: "-" });
parts.push({ name: "mo", min: 1, max: 12, length: 2, placeholder: translate("mo") });
if (daySelection) {
parts.push({ text: "-" });
parts.push({ name: "d", min: 1, max: 31, length: 2, placeholder: translate("d") });
}
}
if (timeSelection) {
if (dateSelection)
parts.push({ text: opt.isoFormatSeparator });
parts.push({ name: "h", min: 0, max: 23, length: 2 });
if (minuteSelection) {
parts.push({ text: ":" });
parts.push({ name: "min", min: 0, max: 59, length: 2 });
if (secondSelection) {
parts.push({ text: ":" });
parts.push({ name: "s", min: 0, max: 59, length: 2 });
}
}
}
}
else {
let formatParts = format.formatToParts(new Date());
for (let f of formatParts) {
switch (f.type) {
case "literal": parts.push({ text: f.value }); break;
case "year": parts.push({ name: "y", min: 1, max: 9999, length: 4, placeholder: translate("y") }); break;
case "month":
if (formatOptions.month === "numeric") {
parts.push({ name: "mo", min: 1, max: 12, length: 2, placeholder: translate("mo") });
}
else {
// Collect all localised month names
let monthFormat = new Intl.DateTimeFormat(opt.localeCode, { month: "long" });
let monthNames = [];
for (let m = 0; m < 12; m++)
monthNames.push(monthFormat.format(new Date(2000, m, 1)));
parts.push({ name: "mo", min: 1, max: 12, length: 4, options: monthNames, placeholder: translate("month") });
}
break;
case "day": parts.push({ name: "d", min: 1, max: 31, length: 2, placeholder: translate("d") }); break;
case "hour": parts.push({ name: "h", min: 0, max: 23, length: 2 }); break;
case "minute": parts.push({ name: "min", min: 0, max: 59, length: 2 }); break;
case "second": parts.push({ name: "s", min: 0, max: 59, length: 2 }); break;
}
}
}
}
else {
if (translate("week1"))
parts.push({ text: translate("week1") });
parts.push({ name: "w", min: 1, max: 53, length: 2, placeholder: translate("w") });
if (translate("week2"))
parts.push({ text: translate("week2") });
parts.push({ name: "y", min: 1, max: 9999, length: 4, placeholder: translate("y") });
}
/*
if (dateSelection && !weekSelection) {
if (daySelection) {
parts.push({ name: "d", min: 1, max: 31, length: 2, placeholder: "tt" });
parts.push({ text: "." });
parts.push({ name: "mo", min: 1, max: 12, length: 2, placeholder: "mm" });
parts.push({ text: "." });
}
else {
parts.push({ name: "mo", min: 1, max: 12, options: ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"], length: 4, placeholder: "mmmm" });
parts.push({ text: " " });
}
parts.push({ name: "y", min: 1, max: 9999, length: 4, placeholder: "jjjj" });
if (timeSelection) {
parts.push({ text: ", " });
}
}
if (weekSelection) {
parts.push({ text: "Woche " });
parts.push({ name: "w", min: 1, max: 53, length: 2, placeholder: "ww" });
parts.push({ text: ", " });
parts.push({ name: "y", min: 1, max: 9999, length: 4, placeholder: "jjjj" });
}
if (timeSelection) {
parts.push({ name: "h", min: 0, max: 23, length: 2 });
if (minuteSelection) {
parts.push({ text: ":" });
parts.push({ name: "min", min: 0, max: 59, length: 2 });
if (secondSelection) {
parts.push({ text: ":" });
parts.push({ name: "s", min: 0, max: 59, length: 2 });
}
}
}
*/
// The index of the selected data part (text part indices are invalid)
var selectedPart = -1;
for (let i = 0; i < parts.length; i++) {
if (parts[i].name) {
selectedPart = i;
break;
}
}
// Indicates whether further input is appended to the current part
// (Set to false when the part is entered, to overwrite the current value with new input;
// set to true on the first input event in a part)
let appendInput = false;
// The number of typed digits in the selected data part
let inputLength = 0;
// The values for each data part
let partData = {};
// Collecting characters for an options lookup input in the current field
let optionSearch;
// An active timeout to restart the options search
let optionSearchTimeout;
function findPart(name) {
for (let i = 0; i < parts.length; i++) {
if (parts[i].name === name)
return parts[i];
}
return null;
}
function findGreaterPartName(name) {
switch (name) {
case "mo": return "y";
case "w": return "y";
case "d": return "mo";
case "h": return "d";
case "min": return "h";
case "s": return "min";
default: return null;
}
}
function selectPart(name) {
for (let i = 0; i < parts.length; i++) {
if (parts[i].name === name) {
selectedPart = i;
appendInput = false;
inputLength = 0;
break;
}
}
}
function updateText() {
let text = "";
let anyValueSet = false;
for (let i = 0; i < parts.length; i++) {
let part = parts[i];
if (F.isSet(part.text)) {
text += part.text;
}
else if (part.name) {
part.start = text.length;
let value = partData[part.name];
if (F.isSet(value)) {
// Display value
anyValueSet = true;
if (part.options) {
text += part.options[value - part.min];
}
else {
text += (value + "").padStart(part.length, "0");
}
}
else {
// Display placeholder or empty space
if (part.placeholder)
text += part.placeholder;
else
text += "-".repeat(part.length);
//text += "\u2007".repeat(part.length); // FIGURE SPACE
}
part.end = text.length;
}
}
newInput.value = text;
newInput.classList.toggle("empty", !anyValueSet);
if (parts[selectedPart] && parts[selectedPart].end) {
newInput.setSelectionRange(parts[selectedPart].start, parts[selectedPart][isFocused ? "end" : "start"]);
// Setting a non-empty selection always shows the selection background, even if not
// focused. To avoid this, when unfocused, only the selection start is set to
// maintain the selected part.
}
}
updateText();
function getValue() {
let value = "";
if (dateSelection) {
if (!F.isSet(partData.y)) return "";
value += (partData.y + "").padStart(4, "0") + "-";
if (weekSelection) {
if (!F.isSet(partData.w)) return "";
value += "W" + (partData.w + "").padStart(2, "0");
}
else {
if (!F.isSet(partData.mo)) return "";
value += (partData.mo + "").padStart(2, "0");
if (daySelection) {
if (!F.isSet(partData.d)) return "";
value += "-" + (partData.d + "").padStart(2, "0");
}
}
}
if (timeSelection) {
if (dateSelection)
value += "T";
if (!F.isSet(partData.h)) return "";
if (!F.isSet(partData.min)) return "";
value += (partData.h + "").padStart(2, "0") + ":" +
(partData.min + "").padStart(2, "0");
if (secondSelection) {
if (!F.isSet(partData.s)) return "";
value += ":" + (partData.s + "").padStart(2, "0");
}
}
return value;
}
function setValue(value) {
let match;
partData = {};
if (match = value.match(/^([0-9]+)-([0-9]+)(?:-([0-9]+)(?:T([0-9]+):([0-9]+)(?::([0-9]+)(?:.[0-9]+)?)?)?)?$/)) {
partData.y = +match[1];
partData.mo = +match[2];
if (match[3])
partData.d = +match[3];
if (match[4])
partData.h = +match[4];
if (match[5])
partData.min = +match[5];
if (match[6])
partData.s = +match[6];
else if (match[5]) // Assume 0 seconds if minutes are also given because HTML input drops 0 seconds from the string value
partData.s = 0;
// Ignore (but accept) optional milliseconds
}
else if (match = value.match(/^([0-9]+):([0-9]+)(?::([0-9]+))?$/)) {
partData.h = +match[1];
partData.min = +match[2];
if (match[3])
partData.s = +match[3];
}
else if (match = value.match(/^([0-9]+)-W([0-9]+)$/)) {
partData.y = +match[1];
partData.w = +match[2];
}
updateText();
validate();
cancelSearchTimeout();
}
// Add control buttons
//let buttons = [];
//let decButton = F("<button type='button'/>").addClass("button").appendTo(wrapper).attr("tabindex", "-1").text("\u2212").first; // −
//buttons.push(decButton);
//decButton.F.on("repeatclick", () => {
// changeValue(-1, 1);
//});
//decButton.F.repeatButton();
//let incButton = F("<button type='button'/>").addClass("button").appendTo(wrapper).attr("tabindex", "-1").text("+").first;
//buttons.push(incButton);
//incButton.F.on("repeatclick", () => {
// changeValue(1, 1);
//});
//incButton.F.repeatButton();
//bindInputButtonsDisabled(newInput, buttons);
function changeValue(direction, count, partName) {
let part = partName ? findPart(partName) : parts[selectedPart];
if (part) {
let value = partData[part.name];
// TODO: Consider valid values as defined by step and min
if (F.isSet(value)) {
let backupPartData = Object.assign({}, partData);
while (count-- > 0) {
let isOverflow;
let myPart = part;
do
{
partData[myPart.name] += direction;
isOverflow = false;
if (direction > 0 && partData[myPart.name] > getPartMax(myPart)) {
isOverflow = true;
partData[myPart.name] = getPartMin(myPart, direction); // min of next overflow state
}
else if (direction < 0 && partData[myPart.name] < getPartMin(myPart)) {
isOverflow = true;
partData[myPart.name] = getPartMax(myPart, direction); // max of next overflow state
}
if (isOverflow) {
myPart = findPart(findGreaterPartName(myPart.name));
if (myPart && !F.isSet(partData[myPart.name]))
isOverflow = false; // Incomplete data, don't overflow to next field
}
}
while (myPart && isOverflow);
if (isOverflow && dateSelection) {
// No more space for the overflow, cancel entire change
partData = backupPartData;
}
}
}
else {
partData[part.name] = part[direction > 0 ? "min" : "max"];
}
updateText();
cancelSearchTimeout();
newInput.F.trigger("input", { bubbles: true });
newInput.F.trigger("change", { bubbles: true });
newInput.focus();
appendInput = false;
inputLength = 0;
}
}
// Gets the minimum value of a part.
// If nextLevelOffset is 1, the next-higher part is incremented by 1 to consider the
// correct min value of the requested part.
// nextLevelOffset can only be 0 or 1. Undefined is interpreted as 0.
function getPartMin(part, nextLevelOffset) {
// TODO: Consider valid values as defined by min and max
return part.min;
}
// Gets the maximum value of a part.
// If nextLevelOffset is -1, the next-higher part is decremented by 1 to consider the
// correct max value of the requested part.
// nextLevelOffset can only be -1 or 0. Undefined is interpreted as 0.
function getPartMax(part, nextLevelOffset) {
// TODO: Consider valid values as defined by min and max
if (part.name === "w") {
let year = partData.y;
if (year) {
year += (nextLevelOffset || 0);
// A year has 53 weeks if it begins or ends on a Thursday
// Source: https://de.wikipedia.org/wiki/Woche#Z%C3%A4hlweise_nach_ISO_8601
// Algorithm to determine the weekday of the 1st January in a year (0 = Sun ... 6 = Sat)
// Source: https://de.wikipedia.org/wiki/Gau%C3%9Fsche_Wochentagsformel
// Simplification:
// * A year that begins on a Thursday (= 4) has 53 weeks
// * A year that ends on a Thursday (the next year begins on a Friday = 5) has 53 weeks
// * Other years have 52 weeks
let firstWeekday = year => (1 + 5 * ((year - 1) % 4) + 4 * ((year - 1) % 100) + 6 * ((year - 1) % 400)) % 7;
if (firstWeekday(year) !== 4 && firstWeekday(year + 1) !== 5)
return 52;
}
return part.max;
}
if (part.name === "d") {
let month = partData.mo;
if (month) {
month += (nextLevelOffset || 0);
if (month === 0) month = 12;
let year = partData.y;
return getDaysInMonth(month, year);
}
return part.max;
}
return part.max;
}
// Focus and selection events
var isFocused = false;
let blurCloseTimeout;
newInput.F.on("focus", () => {
//console.log("newInput.focus:", newInput);
isFocused = true;
setTimeout(fixSelection, 0);
if (blurCloseTimeout) {
// Clicked on an item, focused back; don't close the dropdown
clearTimeout(blurCloseTimeout);
blurCloseTimeout = undefined;
}
});
newInput.F.on("blur", event => {
//console.log("newInput.blur:", newInput);
isFocused = false;
cancelSearchTimeout();
newInput.readonly = true;
newInput.inputmode = "none";
isKeyboardMode = false;
if (!newInput.classList.contains("open"))
fixValue();
// Close the dropdown when leaving the field with the Tab key
// (but not when clicking an item in the dropdown)
// DEBUG: disable following code to allow inspecting the dropdown contents
if (newInput.classList.contains("open") && !blurCloseTimeout) {
blurCloseTimeout = setTimeout(() => {
dropdown.F.dropdown.close();
blurCloseTimeout = undefined;
// Forward this event explicitly to the original input
input.F.trigger("blur", event, FocusEvent);
}, 20);
}
else {
// Forward this event explicitly to the original input
input.F.trigger("blur", event, FocusEvent);
}
});
newInput.F.on("mousedown mouseup", event => {
//console.log("newInput." + event.type);
cancelSearchTimeout();
setTimeout(fixSelection, 0);
});
newInput.F.on("click", () => {
//console.log("newInput.click");
if (newInput.F.disabled) return;
if (!isKeyboardMode && !newInput.classList.contains("open")) {
// Select useful part if no data is set
if (daySelection && !partData.d) {
selectPart("d");
updateText();
}
else if (weekSelection && !partData.w) {
selectPart("w");
updateText();
}
else if (timeSelection && !F.isSet(partData.h)) {
selectPart("h");
updateText();
}
openDropdown();
}
});
let separatorChars = [".", ":", "-", "/", ","];
newInput.F.on("keydown", event => {
//console.log("keydown: keyCode:", event.keyCode, event);
//alert("keyCode: " + event.keyCode + ", key: " + event.key);
switch (event.key) {
case "Enter":
event.preventDefault();
dropdown.F.dropdown.close();
newInput.prop("readonly", true)
.attr("inputmode", "none");
isKeyboardMode = false;
break;
case "Escape":
event.preventDefault();
dropdown.F.dropdown.close();
break;
case " ":
event.preventDefault();
if (!newInput.classList.contains("open"))
openDropdown();
else
dropdown.F.dropdown.close();
break;
case "ArrowLeft":
event.preventDefault();
prevPart();
updateText();
cancelSearchTimeout();
break;
case "ArrowRight":
event.preventDefault();
nextPart();
updateText();
cancelSearchTimeout();
break;
case "ArrowUp":
event.preventDefault();
changeValue(1, 1);
break;
case "ArrowDown":
event.preventDefault();
changeValue(-1, 1);
break;
case "PageUp":
event.preventDefault();
changeValue(1, getPartLargeStep());
break;
case "PageDown":
event.preventDefault();
changeValue(-1, getPartLargeStep());
break;
case "Backspace":
case "Delete":
event.preventDefault();
if (!required) {
delete partData[parts[selectedPart].name];
updateText();
newInput.F.trigger("input", { bubbles: true });
newInput.F.trigger("change", { bubbles: true });
}
cancelSearchTimeout();
break;
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
event.preventDefault();
let digit = +event.key;
let part = parts[selectedPart];
let value = partData[part.name];
if (F.isSet(value) && appendInput) {
value = value * 10 + digit;
if (value > getPartMax(part))
value = digit;
}
else {
value = digit;
}
appendInput = true;
inputLength++;
partData[part.name] = value;
// Skip to next part if the value is complete
if (inputLength >= part.length && value >= part.min ||
value * 10 > getPartMax(part)) {
nextPart();
}
updateText();
cancelSearchTimeout();
newInput.F.trigger("input", { bubbles: true });
newInput.F.trigger("change", { bubbles: true });
break;
default:
if (event.key.length === 1 && separatorChars.indexOf(event.key) !== -1) { // Separator
event.preventDefault();
if (appendInput) {
nextPart();
updateText();
}
cancelSearchTimeout();
}
else if (event.key.length === 1 && !event.altKey && !event.ctrlKey) { // Other char
event.preventDefault();
if (!appendInput)
optionSearch = "";
optionSearch += event.key.toLowerCase();
appendInput = true;
inputLength++;
//console.log("optionSearch:", optionSearch);
let part = parts[selectedPart];
if (part.options) {
for (let i = 0; i < part.options.length; i++) {
if (part.options[i].toLowerCase().startsWith(optionSearch)) {
partData[part.name] = i + part.min;
updateText();
break;
}
}
}
startSearchTimeout();
}
else {
// Whatever it was, reset the text
updateText();
newInput.F.trigger("input", { bubbles: true });
newInput.F.trigger("change", { bubbles: true });
}
break;
}
});
let newInputInInputEvent = false;
newInput.F.on("input", event => {
if (newInputInInputEvent) return; // Recursion
newInputInInputEvent = true;
if (event.data) {
// Something was typed in, reset the text
// (Generated input events have no set data property)
if (separatorChars.indexOf(event.data) !== -1) { // Separator (for Chrome/Android: https://crbug.com/118639)
if (appendInput) {
nextPart();
}
cancelSearchTimeout();
}
updateText();
newInput.F.trigger("input", { bubbles: true });
newInput.F.trigger("change", { bubbles: true });
}
newInputInInputEvent = false;
});
function startSearchTimeout() {
if (!optionSearchTimeout) {
optionSearchTimeout = setTimeout(() => {
appendInput = false;
inputLength = 0;
optionSearchTimeout = null;
optionSearch = "";
}, 2000);
}
}
function cancelSearchTimeout() {
if (optionSearchTimeout) {
clearTimeout(optionSearchTimeout);
optionSearchTimeout = null;
optionSearch = "";
}
}
function getPartLargeStep() {
switch (parts[selectedPart].name) {
case "y": return 10;
case "mo": return 3;
case "d": return 7;
case "h": return 12;
case "min": return 15;
case "s": return 15;
default: return 1;
}
}
function prevPart() {
//console.log("selectedPart:", selectedPart);
for (let i = selectedPart - 1; i >= 0; i--) {
if (parts[i].name) {
selectedPart = i;
//console.log("new selectedPart:", selectedPart);
appendInput = false;
inputLength = 0;
updateViewVisibilities();
break;
}
}
}
function nextPart() {
//console.log("selectedPart:", selectedPart);
for (let i = selectedPart + 1; i < parts.length; i++) {
if (parts[i].name) {
selectedPart = i;
//console.log("new selectedPart:", selectedPart);
appendInput = false;
inputLength = 0;
updateViewVisibilities();
break;
}
}
}
function fixSelection() {
let selStart = newInput.selectionStart;
//console.log("selectionStart:", selStart);
for (let i = 0; i < parts.length; i++) {
let part = parts[i];
if (part.name && selStart <= part.end) {
selectedPart = i;
//console.log("New selected part:", i);
appendInput = false;
inputLength = 0;
updateViewVisibilities();
if (isFocused)
newInput.setSelectionRange(part.start, part.end);
break;
}
}
}
// Load initial value
setValue(input.value);
// Create dropdown contents
let dropdownInner = F.c("div");
dropdownInner.classList.add("ff-timepicker");
dropdown.append(dropdownInner);
let dropdownButtons = F.c("div");
dropdownButtons.classList.add("ff-timepicker-buttons");
dropdownInner.append(dropdownButtons);
let boxSize = { width: 280, height: 240 };
if (!dateSelection)
boxSize.width = boxSize.height; // No need for space for longer month names
let dropdownContent = F.c("div");
dropdownContent.classList.add("ff-timepicker-content");
dropdownContent.style.width = boxSize.width + "px";
dropdownContent.style.height = boxSize.height + "px";
dropdownInner.append(dropdownContent);
let updateHandler = () => {
updateText();
newInput.F.trigger("input", { bubbles: true });
newInput.F.trigger("change", { bubbles: true });
};
// These will be accessed from functions implemented below but called above
var yearView;
var monthView;
var clockHourView;
var clockMinuteView;
var clockSecondView;
if (dateSelection) {
yearView = new YearView(dropdownContent, boxSize, opt, translate, weekSelection, () => partData, changeValue, updateHandler, () => {
if (daySelection) {
selectPart("d");
updateText();
yearView.hide();
monthView.show();
}
else if (weekSelection) {
// Convert month selection to week selection
// (Keep selected week if the month matches)
if (partData.w < getWeekData(new Date(partData.y, partData.mo - 1, 1)).w ||
partData.w > getWeekData(new Date(partData.y, partData.mo, 0)).w) {
let weekData = getWeekData(new Date(partData.y, partData.mo - 1, 4)); // Thursday
delete partData.mo;
partData.y = weekData.y;
partData.w = weekData.w;
}
selectPart("w");
updateText();
monthView.update();
yearView.hide();
monthView.show();
}
else {
dropdown.F.dropdown.close();
}
});
monthView = new MonthView(dropdownContent, boxSize, opt, translate, weekSelection ? "w" : "d", () => partData, changeValue, updateHandler, () => {
if (timeSelection) {
selectPart("h");
updateText();
monthView.hide();
clockHourView.show();
}
else {
dropdown.F.dropdown.close();
}
});
opt._updateMonthView = () => monthView.update(true);
}
if (timeSelection) {
clockHourView = new ClockView(dropdownContent, boxSize, translate, "h", () => partData, changeValue, updateHandler, () => {
if (minuteSelection) {
selectPart("min");
updateText();
clockHourView.hide();
clockMinuteView.show();
}
else {
dropdown.F.dropdown.close();
}
});
if (minuteSelection)
clockMinuteView = new ClockView(dropdownContent, boxSize, translate, "min", () => partData, changeValue, updateHandler, () => {