-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselectable.js
More file actions
1153 lines (1086 loc) · 39.3 KB
/
Copy pathselectable.js
File metadata and controls
1153 lines (1086 loc) · 39.3 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
// ==================== Selectable plugin ====================
const selectableClass = "ff-selectable";
const selectableSearchMatchClass = "selectable-search-match";
const selectableSearchNoMatchClass = "selectable-search-no-match";
const selectableEventClass = ".ff-selectable";
// Defines default options for the selectable plugin.
let selectableDefaults = {
// Indicates whether multiple items can be selected.
multiple: false,
// Indicates whether a single click toggles the selection of an item. This implies multiple selection.
toggle: false,
// Indicates whether a selection is required, i.e. cannot be cleared.
required: false,
// The separator for multi-select dropdown lists.
separator: ", ",
// The placeholder text for the empty selection in the dropdown button.
placeholder: "",
// Indicates whether the entered search text is shown in the matching item.
showSearchMatch: true
};
// Makes the child elements in each selected element selectable.
function selectable(options) {
return this.forEach(elem => {
if (elem.classList.contains(selectableClass)) return; // Already done
elem.classList.add(selectableClass);
let opt = F.initOptions("selectable", elem, {}, options);
opt._selectAll = selectAll;
opt._selectNone = selectNone;
opt._selectItem = selectItem;
opt._deinit = deinit;
let originalElem = elem;
let replaceHtmlSelect = elem.F.nodeNameLower === "select";
let htmlSize = +elem.getAttribute("size");
let useDropdown = replaceHtmlSelect && htmlSize === 0; // Includes missing size attribute
let htmlSelect, button;
let disabledObservers, forwardedEvents, originalHtmlSelectFocus;
let htmlSelectChanging;
let blurTimeout;
let lastClickedItem, focusedItem, focusedIndex = -1;
let searchText = "", searchUnderlineItem, searchUnderlineLength;
let clearSearchTimeout, clearSearchTimeoutMs = 3000;
if (replaceHtmlSelect) {
htmlSelect = elem;
let origStyle = elem.getAttribute("style");
let origTitle = elem.getAttribute("title");
htmlSelect.F.visible = false;
opt.multiple |= htmlSelect.multiple;
opt.required |= htmlSelect.required;
let newSelect = F.c("div");
newSelect.classList.add(selectableClass);
newSelect.F.insertAfter(htmlSelect);
if (htmlSize > 1) {
if (htmlSelect.style.height) {
// Copy the HTML select's explicit height style
newSelect.style.height = htmlSelect.style.height;
}
else {
// Use size attribute to determine the visible rows
let frameHeight = newSelect.F.height;
// Create dummy element for height measurement
let dummyOption = F.c("div");
dummyOption.textContent = "x";
newSelect.append(dummyOption);
let itemHeight = dummyOption.F.height;
dummyOption.remove();
let marginFromSecond = 1; // See CSS
newSelect.F.height = frameHeight + htmlSize * itemHeight + (htmlSize - 1) * marginFromSecond;
}
}
elem = newSelect;
updateChildrenFromOptions();
if (useDropdown) {
button = F.c("div");
button.classList.add("ff-selectable-button");
let contentPart = F.c("div");
button.append(contentPart);
let iconPart = F.c("div");
button.append(iconPart);
button.F.insertAfter(htmlSelect);
if (!htmlSelect.disabled)
button.setAttribute("tabindex", 0);
if (originalElem.classList.contains("narrow"))
button.classList.add("narrow");
if (origStyle)
button.setAttribute("style", origStyle);
if (origTitle)
button.setAttribute("title", origTitle);
newSelect.classList.add("dropdown");
newSelect.style.height = "100%"; // Scroll the selectable, not the dropdown container
if (!htmlSelect.querySelector(":scope > option"))
elem.style.minHeight = "4em";
updateButtonContent();
updateButtonIcon();
let openDropdown = () => {
if (button.F.disabled) return;
clearSearchText();
button.classList.add("open");
updateButtonIcon();
let fixed = button.F.closest(p => p.F.computedStyle.position === "fixed").length > 0;
let cssClass = "";
if (button.F.dark)
cssClass = "dark"; // Set dropdown container to dark
newSelect.F.dropdown({
target: button,
offsetTop: 1,
offsetBottom: -1,
fixed: fixed,
cssClass: cssClass,
minWidth: button.F.borderWidth
});
let firstSelectedItem = elem.querySelector(":scope > .selected");
if (firstSelectedItem) {
scrollItemIntoView(firstSelectedItem, true);
}
};
opt._openDropdown = openDropdown;
opt._closeDropdown = () => newSelect.F.dropdown.close();
opt._isDropdownOpen = () => newSelect.F.dropdown.isOpen;
let justClosed = false;
let touchDown = false;
let touchDownClosedDropdown = false;
button.F.on("pointerdown", event => {
if (event.pointerType === "mouse" && event.button !== 0) {
// Ignore other-than-left mouse button
return;
}
touchDown = false;
touchDownClosedDropdown = false;
if (event.pointerType === "touch") {
// Don't open the dropdown when touching, it might be a scroll gesture.
// For touch input, only open the dropdown on pointerup.
touchDown = true;
touchDownClosedDropdown = newSelect.F.dropdown.isOpen;
return;
}
if (!justClosed)
openDropdown();
// Stop other event handlers up the document tree, like a modal that would try
// to find the event source in its modal element and close the modal if it
// wasn't in there. We're opening or closing the dropdown here, which includes
// updating the button icon. If the icon was clicked on, the originally clicked
// icon is no longer in the tree when the event bubbles up to the modal, so it
// would close - even with the selectable dropdown still open!
// (The dropdown closing happens in the capture phase, managed by the dropdown
// plugin itself, not here.)
event.stopPropagation();
});
button.F.on("pointerup", event => {
if (event.pointerType === "touch" && touchDown) {
touchDown = false;
if (!touchDownClosedDropdown)
openDropdown();
touchDownClosedDropdown = false;
}
});
newSelect.F.on("close", () => {
button.classList.remove("open");
updateButtonIcon();
clearSearchText();
justClosed = true;
setTimeout(() => justClosed = false, 0);
});
button.F.on("keydown", event => {
//console.log(event);
if (button.F.disabled) return;
if (event.key !== "Control" && event.key !== "Shift" && event.key !== "Alt")
button.classList.add("ff-focus-visible");
switch (event.key) {
case "Enter":
case " ":
event.preventDefault();
if (button.classList.contains("open")) {
newSelect.F.dropdown.close();
}
else {
openDropdown();
}
break;
case "Escape":
event.preventDefault();
clearSearchText();
newSelect.F.dropdown.close();
break;
default:
handleKeyDown(event);
break;
}
});
// Close the dropdown when leaving the field with the Tab key
// (but not when clicking into the dropdown)
button.F.on("blur", () => {
if (!blurTimeout) {
blurTimeout = setTimeout(() => {
if (button.classList.contains("open")) {
newSelect.F.dropdown.close();
}
button.classList.remove("ff-focus-visible");
blurTimeout = undefined;
}, 50);
}
});
button.F.on("focus", () => {
if (blurTimeout) {
// Clicked on an item, focused back; don't close the dropdown
clearTimeout(blurTimeout);
blurTimeout = undefined;
}
});
}
let replacement = useDropdown ? button : newSelect;
// Show or hide the new element instead whenever the <select> element should be shown or hidden
F.internalData.set(htmlSelect, "visible.replacement", replacement);
// Enable or disable the new element when the <select> element is enabled or disabled
disabledObservers = htmlSelect.F.observeDisabled(disabled => {
replacement.F.disabled = disabled;
if (button) {
// Make the button unfocusable while it is disabled
if (disabled) {
newSelect.F.dropdown.close();
button.removeAttribute("tabindex");
}
else {
button.setAttribute("tabindex", 0);
}
}
});
// Apply disabled property where appropriate
if (htmlSelect.F.disabled) {
if (useDropdown)
button.F.disabled = true;
else
newSelect.F.disabled = true;
}
// Copy some CSS classes to the replacement element (new list or button)
["wrap", "input-validation-error", "dark", "not-dark"].forEach(clsName => {
if (htmlSelect.classList.contains(clsName))
replacement.classList.add(clsName);
});
forwardedEvents = replacement.F.forwardUIEvents(htmlSelect, "pointerdown");
// Overwrite the focus method to focus the new visible element
originalHtmlSelectFocus = htmlSelect.focus;
htmlSelect.focus = () => replacement.focus();
htmlSelect.F.on("change" + selectableEventClass, () => {
if (!htmlSelectChanging) {
updateSelectionFromHtml();
lastClickedItem = elem.F.querySelector(":scope > .selected");
if (!lastClickedItem)
lastClickedItem = elem.F.querySelector(":scope > :not([disabled])");
if (lastClickedItem)
setFocusedItem(lastClickedItem);
}
if (useDropdown) {
updateButtonContent();
}
});
}
elem.setAttribute("tabindex", 0);
elem.F.children.forEach(prepareChild);
// Selects a non-disabled item if none is selected but a selection is required.
// Returns true if an item was selected; otherwise, false.
let trySelectOne = () => {
if (opt.required && !elem.querySelector(":scope > .selected")) {
elem.querySelector(":scope > :not([disabled])")?.classList.add("selected");
return true;
}
return false;
};
// Automatically prepare newly added children and notify if a selected child was removed
let removedSelectedItems = [];
let observer = new MutationObserver((mutationsList, observer) => {
mutationsList.forEach(mutation => {
if (mutation.type === "childList") {
//console.log("addedNodes:", mutation.addedNodes);
//console.log("removedNodes:", mutation.removedNodes);
mutation.addedNodes.forEach(child => {
if (replaceHtmlSelect) {
// Create UI element
let i = removedSelectedItems.indexOf(child);
if (i !== -1) {
// This added child was removed as selected, now it's back again
removedSelectedItems.splice(i, 1);
}
let newChild = createChildForOption(child);
let optionIndex = child.F.index;
if (optionIndex === htmlSelect.children.length - 1) {
// Last option, append child
elem.append(newChild);
}
else {
// Insert child at correct index
elem.insertBefore(newChild, elem.children[optionIndex]);
}
prepareChild(newChild);
}
else {
prepareChild(child);
}
if (trySelectOne()) {
let changeEventData = { reason: "added" };
if (replaceHtmlSelect)
updateHtmlSelect(changeEventData);
else
originalElem.F.trigger("change", { bubbles: true }, changeEventData);
}
if (useDropdown) {
updateButtonContent();
elem.style.minHeight = "";
}
});
mutation.removedNodes.forEach(child => {
if (child.nodeType !== 1 /*ELEMENT_NODE*/) return; // Ignore text nodes
let uiChild = child;
if (replaceHtmlSelect) {
// Remove UI element
uiChild = elem.F.children.find(c => c._optionElement === child);
if (uiChild)
uiChild.remove();
}
else if (child === searchUnderlineItem) {
revertSearchUnderline();
}
if (uiChild?.classList.contains("selected")) {
removedSelectedItems.push(child);
if (removedSelectedItems.length === 1)
queueMicrotask(() => {
if (removedSelectedItems.length > 0) {
// Some removed selected items have not been added back
trySelectOne();
let changeEventData = { reason: "removed" };
if (replaceHtmlSelect)
updateHtmlSelect(changeEventData);
else
originalElem.F.trigger("change", { bubbles: true }, changeEventData);
removedSelectedItems.length = 0;
}
});
}
if (uiChild === focusedItem) {
// The focused item was removed: focus a nearby item
let uiChildren = elem.F.children;
if (focusedIndex < uiChildren.length) {
// Focus the remaining element at the same index (the following item)
setFocusedItem(uiChildren.get(focusedIndex));
}
else if (uiChildren.length > 0) {
// No following item: focus the last item
setFocusedItem(uiChildren.get(-1));
}
else {
// No items left
setFocusedItem();
}
}
});
if (useDropdown) {
updateButtonContent();
if (!htmlSelect.querySelector(":scope > option"))
elem.style.minHeight = "4em";
}
updateFocusedIndex();
}
});
});
observer.observe(originalElem, { childList: true });
lastClickedItem = elem.querySelector(":scope > .selected");
if (!lastClickedItem)
lastClickedItem = elem.querySelector(":scope > :not([disabled])");
if (lastClickedItem)
setFocusedItem(lastClickedItem);
elem.F.on("blur" + selectableEventClass, () => elem.classList.remove("ff-focus-visible"));
elem.F.on("keydown" + selectableEventClass, event => {
//console.log(event);
if (elem.F.disabled) return;
if (event.key !== "Control" && event.key !== "Shift" && event.key !== "Alt")
elem.classList.add("ff-focus-visible");
handleKeyDown(event);
});
// Also don't close the dropdown if clicked on a disabled item or empty space (if there are no items)
if (useDropdown) {
let isPointerDown = false;
elem.F.on("pointerdown", event => {
if (event.button === 0) {
isPointerDown = true;
setTimeout(() => button.focus(), 0);
}
else {
isPointerDown = false;
}
});
elem.F.on("pointerup", () => {
if (!isPointerDown) return;
isPointerDown = false;
button.focus();
});
}
function handleKeyDown(event) {
// Extend from base to current
let extend = !!event.shiftKey && (opt.multiple || opt.toggle);
// Extend to current
let extendAll = !!event.shiftKey && !!event.ctrlKey;
// Only focus, don't select
let focus = !!event.ctrlKey && !event.shiftKey && (opt.multiple || opt.toggle);
switch (event.key) {
case " ":
if (!event.ctrlKey) {
event.preventDefault();
// Allow space in search if a search was already started
if (searchText.length > 0) {
searchText += event.key;
restartSearchTimeout();
selectFirstSearchMatch();
}
else if (opt.multiple || opt.toggle) {
clearSearchText();
if (focusedItem) {
// Don't allow deselecting the last required selected item
if (!focusedItem.classList.contains("selected") ||
!opt.required ||
elem.querySelectorAll(":scope > .selected").length > 1) {
if (focusedItem.classList.toggle("selected")) {
lastClickedItem = focusedItem;
}
let changeEventData = { reason: "keyboard", key: event.key };
if (replaceHtmlSelect)
updateHtmlSelect(changeEventData);
else
elem.F.trigger("change", { bubbles: true }, changeEventData);
}
}
}
}
break;
case "End":
event.preventDefault();
clearSearchText();
changeSelectedIndex(3, extend, extendAll, focus, { reason: "keyboard", key: event.key });
break;
case "Home":
event.preventDefault();
clearSearchText();
changeSelectedIndex(-3, extend, extendAll, focus, { reason: "keyboard", key: event.key });
break;
case "ArrowUp":
event.preventDefault();
clearSearchText();
changeSelectedIndex(-1, extend, extendAll, focus, { reason: "keyboard", key: event.key });
break;
case "ArrowDown":
event.preventDefault();
clearSearchText();
changeSelectedIndex(1, extend, extendAll, focus, { reason: "keyboard", key: event.key });
break;
case "PageUp":
event.preventDefault();
clearSearchText();
changeSelectedIndex(-2, extend, extendAll, focus, { reason: "keyboard", key: event.key });
break;
case "PageDown":
event.preventDefault();
clearSearchText();
changeSelectedIndex(2, extend, extendAll, focus, { reason: "keyboard", key: event.key });
break;
case "Escape":
event.preventDefault();
clearSearchText();
break;
case "Backspace":
event.preventDefault();
if (searchText.length > 0) {
searchText = searchText.substring(0, searchText.length - 1);
restartSearchTimeout();
selectFirstSearchMatch();
}
break;
default:
if (event.key === "a" && event.ctrlKey && !event.shiftKey) {
event.preventDefault();
clearSearchText();
selectAll({ reason: "keyboard", key: "Control+a" });
}
else if (event.key === "d" && event.ctrlKey && !event.shiftKey) {
event.preventDefault();
clearSearchText();
selectNone({ reason: "keyboard", key: "Control+d" });
}
else if (event.key.length === 1 && !event.ctrlKey) {
// Printable character, perform text search
event.preventDefault();
searchText += event.key;
restartSearchTimeout();
selectFirstSearchMatch();
}
break;
}
}
function selectFirstSearchMatch() {
let prevSearchUnderlineItem = searchUnderlineItem;
let prevSearchUnderlineLength = searchUnderlineLength;
// First undo any existing underline so that we match the list items against their
// correct text content
revertSearchUnderline();
let match = originalElem.F.children
.where(":not([disabled])")
.where(child => child.textContent.toLowerCase().startsWith(searchText.toLowerCase()))
.first;
if (match) {
selectItem(match, { reason: "search" });
scrollItemIntoView(match);
setSearchUnterline(match);
}
else if (searchText.length > 0 && opt.showSearchMatch && prevSearchUnderlineItem) {
// There was a matching item, but with the new search text no item matches anymore.
// Keep the previous item's underline but change its style to indicate that this was
// the best match but there currently isn't an exact match.
let prevItem = prevSearchUnderlineItem;
if (replaceHtmlSelect)
prevItem = prevItem._optionElement;
setSearchUnterline(prevItem, prevSearchUnderlineLength);
}
}
// Underlines matching text in an element.
function setSearchUnterline(element, limitLength) {
if (searchText.length > 0 && opt.showSearchMatch) {
if (replaceHtmlSelect) {
// Recreate the UI element content from the <option> element's plain-text content
let uiChild = elem.F.children.find(c => c._optionElement === element);
let text = element.textContent;
appendSearchUnderline(uiChild, text, limitLength);
searchUnderlineItem = uiChild;
if (useDropdown && !button.classList.contains("open")) {
// Update button again to show the underline text
updateButtonContent();
}
}
else {
// Stash the original child nodes of the item and create underlining parts from
// the previous plain-text content
let stash = F.c("div");
stash.style.display = "none";
stash.classList.add("stash");
let text = element.textContent;
stash.append(...Array.from(element.childNodes));
appendSearchUnderline(element, text, limitLength);
element.append(stash);
searchUnderlineItem = element;
}
// Remember the underline length if it was a match
if (!limitLength)
searchUnderlineLength = searchText.length;
}
}
// Replaces the element's content with the search match underlined text.
function appendSearchUnderline(element, fullText, limitLength) {
let underlineLength = searchText.length;
if (limitLength)
underlineLength = limitLength;
let underlineText = fullText.substring(0, underlineLength);
let remainderText = fullText.substring(underlineLength);
let underline = F.c("span");
if (limitLength)
underline.classList.add(selectableSearchNoMatchClass);
else
underline.classList.add(selectableSearchMatchClass);
underline.textContent = underlineText;
let remainder = F.c("span");
remainder.textContent = remainderText;
element.replaceChildren(underline, remainder);
}
// Restarts the timeout to clear the search text after more text has been entered.
function restartSearchTimeout() {
if (clearSearchTimeout)
clearTimeout(clearSearchTimeout);
clearSearchTimeout = setTimeout(clearSearchText, clearSearchTimeoutMs);
}
// Forgets the entered search text and restores search underline changes.
function clearSearchText() {
if (clearSearchTimeout)
clearTimeout(clearSearchTimeout);
searchText = "";
revertSearchUnderline();
}
// Undoes any changes made for the search text underlining and restores the original content.
function revertSearchUnderline() {
if (!searchUnderlineItem) return;
if (replaceHtmlSelect) {
// Recreate the UI element content from the <option> element
setChildContentFromOption(searchUnderlineItem);
// Also update the button if the underline was shown there
if (useDropdown && !button.classList.contains("open"))
updateButtonContent();
}
else {
// Restore the original child nodes of the item
let stash = searchUnderlineItem.querySelector(".stash");
if (stash)
searchUnderlineItem.replaceChildren(...Array.from(stash.childNodes));
}
searchUnderlineItem = undefined;
}
// Sets up event handlers on a selection child.
function prepareChild(child) {
let isPointerDown = false;
child.F.on("pointerdown" + selectableEventClass, event => {
if (elem.F.disabled || child.F.disabled) return;
if (event.button === 0) {
event.stopPropagation(); // No need to handle events on elem itself
isPointerDown = true;
setTimeout(() => {
if (useDropdown)
button.focus();
else
elem.focus();
}, 0);
}
else {
isPointerDown = false;
}
});
child.F.on("pointerup" + selectableEventClass, event => {
if (!isPointerDown) return;
event.stopPropagation(); // No need to handle events on elem itself
isPointerDown = false;
if (useDropdown)
button.focus();
else
elem.focus();
let ctrlKey = !!event.ctrlKey;
let shiftKey = !!event.shiftKey;
if (!opt.multiple) ctrlKey = shiftKey = false;
if (opt.toggle) ctrlKey = true;
let changed = false, closeDropdown = false;
if (ctrlKey) {
child.classList.toggle("selected");
if (opt.required && !elem.querySelector(":scope > .selected")) {
// Empty selection not allowed
child.classList.add("selected");
}
else {
changed = true;
}
lastClickedItem = child;
}
else if (shiftKey) {
let lastIndex = lastClickedItem.F.index;
let currentIndex = child.F.index;
// Bring indices in a defined order
let i1 = Math.min(lastIndex, currentIndex);
let i2 = Math.max(lastIndex, currentIndex);
// Replace selection with all items between these indices (inclusive)
elem.F.children.classList.remove("selected");
for (let i = i1; i <= i2; i++) {
let c = elem.children[i];
if (!c.F.disabled)
c.classList.add("selected");
}
changed = true;
}
else {
changed = !child.classList.contains("selected") || elem.querySelectorAll(":scope > .selected").length > 1;
elem.F.children.classList.remove("selected");
child.classList.add("selected");
lastClickedItem = child;
closeDropdown = true;
}
setFocusedItem(child);
clearSearchText();
if (changed || closeDropdown) {
let changeEventData = { reason: "pointer", pointerType: event.pointerType, ctrlKey: event.ctrlKey, shiftKey: event.shiftKey };
// Defer the new event until the current pointerup event handler is finished,
// or the pointerup event would be immediately also be triggered on whatever
// element the triggered change event handler shows. No idea how that can happen.
setTimeout(() => {
if (replaceHtmlSelect) {
updateHtmlSelect(changeEventData);
if (useDropdown) {
updateButtonContent();
if (!(opt.multiple || opt.toggle)) {
elem.F.dropdown.close();
}
}
}
else if (changed) {
elem.F.trigger("change", { bubbles: true }, changeEventData);
}
}, 1);
}
});
if (useDropdown && opt.multiple && !opt.toggle) {
child.F.on("dblclick", event => {
if (elem.F.disabled || child.F.disabled) return;
let ctrlKey = !!event.ctrlKey;
let shiftKey = !!event.shiftKey;
if (!ctrlKey && !shiftKey) {
elem.F.dropdown.close();
}
});
}
}
// Updates the HTML select element's selection from the UI elements (selected CSS class).
function updateHtmlSelect(changeEventData) {
let selectedOptions = elem.F.querySelectorAll(":scope > .selected").select(child => child._optionElement);
htmlSelectChanging = true;
htmlSelect.F.querySelectorAll(":scope > option").forEach(option => {
option.selected = selectedOptions.contains(option);
});
htmlSelect.F.trigger("change", { bubbles: true }, changeEventData);
htmlSelectChanging = false;
}
// Updates the selection state of all children from the HTML <select> element.
function updateSelectionFromHtml() {
elem.F.children.forEach(child => {
child.classList.toggle("selected", !!child._optionElement?.selected);
});
}
// Appends the missing UI child elements for HTML <option> elements and removes old children.
// This function cannot insert added children at the correct index.
function updateChildrenFromOptions() {
let options = htmlSelect.F.querySelectorAll(":scope > option");
elem.F.children.forEach(child => {
if (!child._optionElement || !options.contains(child._optionElement)) {
// Original option element is missing, remove this child
child.remove();
}
});
let children = elem.F.children;
options.forEach(option => {
if (!children.any(child => child._optionElement === option)) {
// No child found for this option, add a new child
let newOption = createChildForOption(option);
elem.append(newOption);
}
});
// Keep the dropdown height visible if it's empty
if (useDropdown) {
if (options.length === 0)
elem.style.height = "4em";
else
elem.style.height = "";
}
}
// Creates a visual child element for an HTML <option> element.
function createChildForOption(option) {
let child = F.c("div");
child._optionElement = option;
child.dataset.value = option.value;
setChildContentFromOption(child);
if (option.dataset.summary)
child.dataset.summary = option.dataset.summary;
if (option.dataset.summaryHtml)
child.dataset.summaryHtml = option.dataset.summaryHtml;
if (option.selected)
child.classList.add("selected");
if (option.disabled)
child.F.disabled = true;
child.F.visible = option.F.visible;
F.internalData.set(option, "visible.replacement", child);
let observer = new MutationObserver((mutationsList, observer) => {
mutationsList.forEach(mutation => {
if (mutation.type === "attributes" && mutation.attributeName === "value") {
child.dataset.value = option.value;
}
else if (mutation.type === "childList" || mutation.type === "characterData") {
setChildContentFromOption(child);
if (useDropdown) {
updateButtonContent();
}
}
});
});
observer.observe(option, {
// (see https://stackoverflow.com/a/40195712)
// for textContent changes:
childList: true,
// for innerHTML changes:
characterData: true, subtree: true,
// for value attribute changes:
attributes: true, attributeFilter: ["value"]
});
return child;
}
// Sets the visible content of a UI child from its original <option> element.
function setChildContentFromOption(child) {
let option = child._optionElement;
if (option.dataset.html)
child.innerHTML = option.dataset.html;
else
child.textContent = option.textContent;
if (child.innerHTML === "")
child.innerHTML = " ";
}
// Updates the dropdown list button's text from the current selection.
function updateButtonContent() {
let html = "";
elem.F.querySelectorAll(":scope > .selected").forEach(child => {
if (html) html += opt.separator;
let summaryText = child.dataset.summary;
let summaryHtml = child.dataset.summaryHtml;
if (summaryHtml)
html += summaryHtml;
else if (summaryText)
html += F.encodeHTML(summaryText);
else
html += child.innerHTML;
});
if (html) {
button.firstElementChild.innerHTML = "<span>" + html + "</span>";
}
else if (opt.placeholder) {
button.firstElementChild.replaceChildren(F("<div>").addClass("placeholder").text(opt.placeholder).first);
}
else {
button.firstElementChild.innerHTML = " ";
}
}
// Updates the dropdown list button's icon.
function updateButtonIcon() {
if (button.classList.contains("open")) {
button.lastElementChild.innerHTML = `<svg style="width: 10px; height: 7px;"><polyline fill="none" points="1,5 5,1 9,5"/></svg>`;
}
else {
button.lastElementChild.innerHTML = `<svg style="width: 10px; height: 7px;"><polyline fill="none" points="1,1 5,5 9,1"/></svg>`;
}
}
// Moves (and optionally extends) the selected index up or down.
// offset: The offset to move. Negative moves up, positive moves down. Supported values:
// -1/1: Move by one up or down
// -2/2: Move by page up or down
// -3/3: Move to first or last
// extend: Indicates whether all items from the base (last clicked) to the new index are selected.
// extendAll: Indicates whether the new index will be added to the selection but nothing else deselected.
// focus: Indicates whether only the focused item is moved and the selection is unchanged.
// changeEventData: Additional properties to set in the change event.
function changeSelectedIndex(offset, extend, extendAll, focus, changeEventData) {
let children = elem.children;
let count = children.length;
if (count === 0 || offset === 0)
return; // Nothing to do
// Find item
let myFocusedItem = focusedItem ?? elem.children[0];
let index = myFocusedItem.F.index;
if (offset === -1 || offset === 1) {
if (!focus && !myFocusedItem.classList.contains("selected")) {
// Select the last item itself first, not one below/above it
}
else {
// Move selection until an enabled item was found
do {
index += offset;
if (index < 0 || index >= count)
return; // Nothing found
}
while (children[index].F.disabled || !children[index].F.visible);
}
}
else if (offset === -2) {
// Move selection to an item that is no more than the view height away
let top = myFocusedItem.F.getRelativeTop(elem);
let newTop = top - elem.clientHeight + myFocusedItem.offsetHeight;
do {
index--;
}
while (index >= 0 && (children[index].F.getRelativeTop(elem) > newTop || children[index].F.disabled || !children[index].F.visible));
while (index < 0 || children[index].F.disabled || !children[index].F.visible)
index++;
}
else if (offset === 2) {
// Move selection down an item that is no more than the view height away
let top = myFocusedItem.F.getRelativeTop(elem);
let newTop = top + elem.clientHeight - myFocusedItem.offsetHeight;
do {
index++;
}
while (index < count && (children[index].F.getRelativeTop(elem) < newTop || children[index].F.disabled || !children[index].F.visible));
while (index >= count || children[index].F.disabled || !children[index].F.visible)
index--;
}
else if (offset < 0) {
// Move selection to the first enabled item
index = elem.F.children.where(":not([disabled])").where(c => c.F.visible).first.F.index;
}
else if (offset > 0) {
// Move selection to the last enabled item
index = elem.F.children.where(":not([disabled])").where(c => c.F.visible).last.F.index;
}
if (index === -1)
return; // Nothing found
// Apply selection
if (!extendAll && !focus)
children.F.classList.remove("selected");
if (focus) {
// No selection change
}
else if (extend || extendAll) {
let lastIndex = lastClickedItem.F.index;
// Bring indices in a defined order
let i1 = Math.min(lastIndex, index);
let i2 = Math.max(lastIndex, index);
// Replace selection with all items between these indices (inclusive)
for (let i = i1; i <= i2; i++) {
let c = children[i];
if (!c.F.disabled && children[index].F.visible)
c.classList.add("selected");
}
}
else {
lastClickedItem = children[index];
lastClickedItem.classList.add("selected");
}
setFocusedItem(children[index]);
scrollItemIntoView(children[index]);
if (replaceHtmlSelect)
updateHtmlSelect(changeEventData);
else
elem.F.trigger("change", { bubbles: true }, changeEventData);
}
// Scrolls the specified item into view. Accepts both originalElement children (HTML options)
// and UI children.
function scrollItemIntoView(child, toMiddle) {
// Only try to scroll the item into view if the selectable itself is scrollable, to not
// scroll the page to the item.
if (elem.F.isScrollable()) {
let uiChild = child;
if (replaceHtmlSelect && child.parentElement !== elem)
uiChild = elem.F.children.find(c => c._optionElement === child);
if (uiChild) {
let elemStyle = elem.F.computedStyle;
let paddingTop = parseFloat(elemStyle.paddingTop);
let paddingBottom = parseFloat(elemStyle.paddingBottom);
if (toMiddle)
paddingTop = paddingBottom = elem.clientHeight / 2 - uiChild.offsetHeight;
uiChild.F.scrollIntoView([paddingTop, paddingBottom]);
}
}
}
// Updates the new focused item and clears the previous focused item.
function setFocusedItem(item) {
focusedItem && focusedItem.classList.remove("focused");
focusedItem = item;
focusedItem && focusedItem.classList.add("focused");
updateFocusedIndex();
}
function updateFocusedIndex() {
if (focusedItem)
focusedIndex = focusedItem.F.index;
else
focusedIndex = -1;