forked from lekoala/bootstrap5-tags
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tags.js
2245 lines (2016 loc) · 66.8 KB
/
tags.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Bootstrap 5 (and 4!) tags
*
* Turns your select[multiple] into nice tags lists
*
* Required Bootstrap 5 styles:
* - badge
* - background-color utility
* - text-truncate utility
* - forms
* - dropdown
*/
// #region config
/**
* @callback EventCallback
* @param {Event} event
* @param {Tags} inst
* @returns {void}
*/
/**
* @callback ServerCallback
* @param {Response} response
* @param {Tags} inst
* @returns {Promise}
*/
/**
* @callback RenderCallback
* @param {Suggestion} item
* @param {String} label
* @param {Tags} inst
* @returns {String}
*/
/**
* @callback ItemCallback
* @param {Suggestion} item
* @param {Tags} inst
* @returns {void}
*/
/**
* @callback ValueCallback
* @param {String} value
* @param {Tags} inst
* @returns {void}
*/
/**
* @callback AddCallback
* @param {String} value
* @param {Object} data
* @param {Tags} inst
* @returns {void|Boolean}
*/
/**
* @callback CreateCallback
* @param {HTMLOptionElement} option
* @param {Tags} inst
* @returns {void}
*/
/**
* @typedef Config
* @property {Array<Suggestion|SuggestionGroup>} items Source items
* @property {Boolean} allowNew Allows creation of new tags
* @property {Boolean} showAllSuggestions Show all suggestions even if they don't match. Disables validation.
* @property {String} badgeStyle Color of the badge (color can be configured per option as well)
* @property {Boolean} allowClear Show a clear icon
* @property {Boolean} clearEnd Place clear icon at the end
* @property {Array} selected A list of initially selected values
* @property {String} regex Regex for new tags
* @property {Array|String} separator A list (pipe separated) of characters that should act as separator (default is using enter key)
* @property {Number} max Limit to a maximum of tags (0 = no limit)
* @property {String} placeholder Provides a placeholder if none are provided as the first empty option
* @property {String} clearLabel Text as clear tooltip
* @property {String} searchLabel Default placeholder
* @property {Boolean} showDropIcon Show dropdown icon
* @property {Boolean} keepOpen Keep suggestions open after selection, clear on focus out
* @property {Boolean} allowSame Allow same tags used multiple times
* @property {String} baseClass Customize the class applied to badges
* @property {Boolean} addOnBlur Add new tags on blur (only if allowNew is enabled)
* @property {Boolean} showDisabled Show disabled tags
* @property {Boolean} hideNativeValidation Hide native validation tooltips
* @property {Number} suggestionsThreshold Number of chars required to show suggestions
* @property {Number} maximumItems Maximum number of items to display
* @property {Boolean} autoselectFirst Always select the first item
* @property {Boolean} updateOnSelect Update input value on selection (doesn't play nice with autoselectFirst)
* @property {Boolean} highlightTyped Highlight matched part of the suggestion
* @property {Boolean} fullWidth Match the width on the input field
* @property {Boolean} fixed Use fixed positioning (solve overflow issues)
* @property {Boolean} fuzzy Fuzzy search
* @property {Boolean} singleBadge Show badge for single elements
* @property {Array} activeClasses By default: ["bg-primary", "text-white"]
* @property {String} labelField Key for the label
* @property {String} valueField Key for the value
* @property {Array} searchFields Key for the search
* @property {String} queryParam Name of the param passed to endpoint (query by default)
* @property {String} server Endpoint for data provider
* @property {String} serverMethod HTTP request method for data provider, default is GET
* @property {String|Object} serverParams Parameters to pass along to the server. You can specify a "related" key with the id of a related field.
* @property {String} serverDataKey By default: data
* @property {Object} fetchOptions Any other fetch options (https://developer.mozilla.org/en-US/docs/Web/API/fetch#syntax)
* @property {Boolean} liveServer Should the endpoint be called each time on input
* @property {Boolean} noCache Prevent caching by appending a timestamp
* @property {Number} debounceTime Debounce time for live server
* @property {String} notFoundMessage Display a no suggestions found message. Leave empty to disable
* @property {RenderCallback} onRenderItem Callback function that returns the suggestion
* @property {ItemCallback} onSelectItem Callback function to call on selection
* @property {ValueCallback} onClearItem Callback function to call on clear
* @property {CreateCallback} onCreateItem Callback function when an item is created
* @property {EventCallback} onBlur Callback function on blur
* @property {EventCallback} onFocus Callback function on focus
* @property {AddCallback} onCanAdd Callback function to validate item. Return false to show validation message.
* @property {ServerCallback} onServerResponse Callback function to process server response. Must return a Promise
*/
/**
* @typedef Suggestion
* @property {String} value Can be overriden by config valueField
* @property {String} label Can be overriden by config labelField
* @property {Boolean} disabled
* @property {Object} data
* @property {Boolean} [selected]
* @property {Number} [group_id]
*/
/**
* @typedef SuggestionGroup
* @property {String} group
* @property {Array} items
*/
/**
* @type {Config}
*/
const DEFAULTS = {
items: [],
allowNew: false,
showAllSuggestions: false,
badgeStyle: "primary",
allowClear: false,
clearEnd: false,
selected: [],
regex: "",
separator: [],
max: 0,
clearLabel: "Clear",
searchLabel: "Type a value",
showDropIcon: true,
keepOpen: false,
allowSame: false,
baseClass: "",
placeholder: "",
addOnBlur: false,
showDisabled: false,
hideNativeValidation: false,
suggestionsThreshold: -1,
maximumItems: 0,
autoselectFirst: true,
updateOnSelect: false,
highlightTyped: false,
fullWidth: true,
fixed: false,
fuzzy: false,
singleBadge: false,
activeClasses: ["bg-primary", "text-white"],
labelField: "label",
valueField: "value",
searchFields: ["label"],
queryParam: "query",
server: "",
serverMethod: "GET",
serverParams: {},
serverDataKey: "data",
fetchOptions: {},
liveServer: false,
noCache: true,
debounceTime: 300,
notFoundMessage: "",
onRenderItem: (item, label, inst) => {
return label;
},
onSelectItem: (item, inst) => {},
onClearItem: (value, inst) => {},
onCreateItem: (option, inst) => {},
onBlur: (event, inst) => {},
onFocus: (event, inst) => {},
onCanAdd: (text, data, inst) => {},
onServerResponse: (response, inst) => {
return response.json();
},
};
// #endregion
// #region constants
const CLASS_PREFIX = "tags-";
const LOADING_CLASS = "is-loading";
const ACTIVE_CLASS = "is-active";
const INVALID_CLASS = "is-invalid";
const MAX_REACHED_CLASS = "is-max-reached";
const SHOW_CLASS = "show";
const VALUE_ATTRIBUTE = "data-value";
const NEXT = "next";
const PREV = "prev";
const FOCUS_CLASS = "form-control-focus"; // should match form-control:focus
const PLACEHOLDER_CLASS = "form-placeholder-shown"; // should match :placeholder-shown
const DISABLED_CLASS = "form-control-disabled"; // should match form-control:disabled
const INSTANCE_MAP = new WeakMap();
let counter = 0;
let tooltip = window.bootstrap && window.bootstrap.Tooltip;
// #endregion
// #region functions
/**
* @param {Function} func
* @param {number} timeout
* @returns {Function}
*/
function debounce(func, timeout = 300) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => {
//@ts-ignore
func.apply(this, args);
}, timeout);
};
}
/**
* @param {string} text
* @param {string} size
* @returns {Number}
*/
function calcTextWidth(text, size = null) {
const span = ce("span");
document.body.appendChild(span);
span.style.fontSize = size || "inherit";
span.style.height = "auto";
span.style.width = "auto";
span.style.position = "absolute";
span.style.whiteSpace = "no-wrap";
span.innerHTML = text;
const width = Math.ceil(span.clientWidth);
document.body.removeChild(span);
return width;
}
/**
* @param {String} str
* @returns {String}
*/
function removeDiacritics(str) {
return str.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
}
/**
* @param {String|Number} str
* @returns {String}
*/
function normalize(str) {
if (!str) {
return "";
}
return removeDiacritics(str.toString()).toLowerCase();
}
/**
* A simple fuzzy match algorithm that checks if chars are matched
* in order in the target string
*
* @param {String} str
* @param {String} lookup
* @returns {Boolean}
*/
function fuzzyMatch(str, lookup) {
if (str.indexOf(lookup) >= 0) {
return true;
}
let pos = 0;
for (let i = 0; i < lookup.length; i++) {
const c = lookup[i];
if (c == " ") continue;
pos = str.indexOf(c, pos) + 1;
if (pos <= 0) {
return false;
}
}
return true;
}
/**
* @param {HTMLElement} item
*/
function hideItem(item) {
item.style.display = "none";
attrs(item, {
"aria-hidden": "true",
});
}
/**
* @param {HTMLElement} item
*/
function showItem(item) {
item.style.display = "list-item";
attrs(item, {
"aria-hidden": "false",
});
}
/**
* @param {HTMLElement} el
* @param {Object} attrs
*/
function attrs(el, attrs) {
for (const [k, v] of Object.entries(attrs)) {
el.setAttribute(k, v);
}
}
/**
* @param {HTMLElement} el
* @param {string} attr
*/
function rmAttr(el, attr) {
if (el.hasAttribute(attr)) {
el.removeAttribute(attr);
}
}
/**
* Allow 1/0, true/false as strings
* @param {any} value
* @returns {Boolean}
*/
function parseBool(value) {
return ["true", "false", "1", "0", true, false].includes(value) && !!JSON.parse(value);
}
/**
* @template {keyof HTMLElementTagNameMap} K
* @param {K|String} tagName Name of the element
* @returns {*}
*/
function ce(tagName) {
return document.createElement(tagName);
}
/**
* @param {HTMLElement} el
* @param {HTMLElement} newEl
* @returns {HTMLElement}
*/
// function insertAfter(el, newEl) {
// return el.parentNode.insertBefore(newEl, el.nextSibling);
// }
// #endregion
class Tags {
/**
* @param {HTMLSelectElement} el
* @param {Object|Config} config
*/
constructor(el, config = {}) {
if (!(el instanceof HTMLElement)) {
console.error("Invalid element", el);
return;
}
INSTANCE_MAP.set(el, this);
counter++;
this._selectElement = el;
this._configure(config);
// private vars
this._keyboardNavigation = false;
this._searchFunc = debounce(() => {
this._loadFromServer(true);
}, this._config.debounceTime);
this._fireEvents = true;
this._configureParent();
// Create elements
this._holderElement = ce("div"); // this is the one holding the fake input and the dropmenu
this._containerElement = ce("div"); // this is the one for the fake input (labels + input)
this._dropElement = ce("ul"); // this dropdown list
this._searchInput = ce("input"); // the input element
this._holderElement.appendChild(this._containerElement);
// insert before select, this helps having native validation tooltips positioned properly
this._selectElement.parentElement.insertBefore(this._holderElement, this._selectElement);
// insertAfter(this._selectElement, this._holderElement);
// Configure them
this._configureHolderElement();
this._configureContainerElement();
this._configureSelectElement();
this._configureSearchInput();
this._configureDropElement();
this.resetState();
this.handleEvent = (ev) => {
this._handleEvent(ev);
};
if (this._config.fixed) {
document.addEventListener("scroll", this, true); // capture input for all scrollables elements
window.addEventListener("resize", this);
}
// Add listeners (remove then on dispose()). See handleEvent.
this._searchInput.addEventListener("focus", this); // focusin bubbles, focus does not.
this._searchInput.addEventListener("blur", this); // focusout bubbles, blur does not.
this._searchInput.addEventListener("input", this);
this._searchInput.addEventListener("keydown", this);
this._dropElement.addEventListener("mousemove", this);
this.loadData(true);
}
// #region Core
/**
* Attach to all elements matched by the selector
* @param {string} selector
* @param {Object} opts
*/
static init(selector = "select[multiple]", opts = {}) {
/**
* @type {NodeListOf<HTMLSelectElement>}
*/
let list = document.querySelectorAll(selector);
for (let i = 0; i < list.length; i++) {
if (Tags.getInstance(list[i])) {
continue;
}
new Tags(list[i], opts);
}
}
/**
* @param {HTMLSelectElement} el
*/
static getInstance(el) {
if (INSTANCE_MAP.has(el)) {
return INSTANCE_MAP.get(el);
}
}
dispose() {
this._searchInput.removeEventListener("focus", this);
this._searchInput.removeEventListener("blur", this);
this._searchInput.removeEventListener("input", this);
this._searchInput.removeEventListener("keydown", this);
this._dropElement.removeEventListener("mousemove", this);
if (this._config.fixed) {
document.removeEventListener("scroll", this, true);
window.removeEventListener("resize", this);
}
// restore select, remove our custom stuff and unbind parent
this._selectElement.style.display = "block";
this._holderElement.parentElement.removeChild(this._holderElement);
if (this.parentForm) {
this.parentForm.removeEventListener("reset", this);
}
INSTANCE_MAP.delete(this._selectElement);
}
/**
* @link https://gist.github.com/WebReflection/ec9f6687842aa385477c4afca625bbf4#handling-events
* @param {Event} event
*/
_handleEvent(event) {
// debounce scroll and resize
const debounced = ["scroll", "resize"];
if (debounced.includes(event.type)) {
if (this._timer) window.cancelAnimationFrame(this._timer);
this._timer = window.requestAnimationFrame(() => {
this[`on${event.type}`](event);
});
} else {
this[`on${event.type}`](event);
}
}
/**
* @param {Config|Object} config
*/
_configure(config = {}) {
this._config = Object.assign({}, DEFAULTS, {
// Hide icon by default if no value
showDropIcon: this._findOption() ? true : false,
});
const json = this._selectElement.dataset.config ? JSON.parse(this._selectElement.dataset.config) : {};
// Handle options, using arguments first, then json config and then data attr as override
const o = { ...config, ...json, ...this._selectElement.dataset };
// Typecast provided options based on defaults types
for (const [key, defaultValue] of Object.entries(DEFAULTS)) {
// Check for undefined keys
if (key == "config" || o[key] === void 0) {
continue;
}
const value = o[key];
switch (typeof defaultValue) {
case "number":
this._config[key] = parseInt(value);
break;
case "boolean":
this._config[key] = parseBool(value);
break;
case "string":
this._config[key] = value.toString();
break;
case "object":
this._config[key] = value;
if (typeof value === "string") {
if (["{", "["].includes(value[0])) {
// JSON like string
this._config[key] = JSON.parse(value);
} else {
// CSV or pipe separated string
this._config[key] = value.split(value.includes("|") ? "|" : ",");
}
}
break;
case "function":
// Find a global function with this name
this._config[key] = typeof value === "string" ? value.split(".").reduce((r, p) => r[p], window) : value;
if (!this._config[key]) {
console.error("Invalid function", value);
}
break;
default:
this._config[key] = value;
break;
}
}
// Dynamic default values
if (!this._config.placeholder) {
this._config.placeholder = this._getPlaceholder();
}
if (this._config.suggestionsThreshold == -1) {
// if we don't have ajax auto completion, behave like a select by default
this._config.suggestionsThreshold = this._config.liveServer ? 1 : 0;
}
}
/**
* @param {String} k
* @returns {*}
*/
config(k = null) {
return k ? this._config[k] : this._config;
}
/**
* @param {String} k
* @param {*} v
*/
setConfig(k, v) {
this._config[k] = v;
}
// #endregion
// #region Html
/**
* Find overflow parent for positioning
* and bind reset event of the parent form
*/
_configureParent() {
this.overflowParent = null;
this.parentForm = this._selectElement.parentElement;
while (this.parentForm) {
if (this.parentForm.style.overflow === "hidden") {
this.overflowParent = this.parentForm;
}
this.parentForm = this.parentForm.parentElement;
if (this.parentForm && this.parentForm.nodeName == "FORM") {
break;
}
}
if (this.parentForm) {
this.parentForm.addEventListener("reset", this);
}
}
/**
* @returns {string}
*/
_getPlaceholder() {
// Use placeholder and data-placeholder in priority
if (this._selectElement.hasAttribute("placeholder")) {
return this._selectElement.getAttribute("placeholder");
}
if (this._selectElement.dataset.placeholder) {
return this._selectElement.dataset.placeholder;
}
// Fallback to first option if no value
let firstOption = this._selectElement.querySelector("option");
if (!firstOption || !this._config.autoselectFirst) {
return "";
}
rmAttr(firstOption, "selected");
firstOption.selected = false;
return !firstOption.value ? firstOption.textContent : "";
}
_configureSelectElement() {
const selectEl = this._selectElement;
// Hiding the select should keep it focusable, otherwise we get this
// An invalid form control with name='...' is not focusable.
// If it's not focusable, we need to remove the native validation attributes
// If we use display none, we don't get the focus event
// selectEl.style.display = "none";
// If we position it like this, the html5 validation message will not display properly
if (this._config.hideNativeValidation) {
// This position dont break render within input-group and is focusable
selectEl.style.position = "absolute";
selectEl.style.left = "-9999px";
} else {
// Hide but keep it focusable. If 0 height, no native validation message will show
// It is placed below so that native tooltip is displayed properly
// Flex basis is required for input-group otherwise it breaks the layout
selectEl.style.cssText = `height:1px;width:1px;opacity:0;padding:0;margin:0;border:0;float:left;flex-basis:100%;`;
}
// Make sure it's not usable using tab
selectEl.tabIndex = -1;
// No need for custom label click event if select is focusable
// const label = document.querySelector('label[for="' + selectEl.getAttribute("id") + '"]');
// if (label) {
// label.addEventListener("click", this);
// }
// It can be focused by clicking on the label
selectEl.addEventListener("focus", (event) => {
this.onclick(event);
});
// When using regular html5 validation, make sure our fake element get the proper class
selectEl.addEventListener("invalid", (event) => {
this._holderElement.classList.add(INVALID_CLASS);
});
}
/**
* Configure drop element
* Needs to be called after searchInput is created
*/
_configureDropElement() {
const dropEl = this._dropElement;
dropEl.classList.add(...["dropdown-menu", CLASS_PREFIX + "menu"]);
dropEl.id = CLASS_PREFIX + "menu-" + counter;
dropEl.setAttribute("role", "menu");
const dropStyles = dropEl.style;
dropStyles.padding = "0"; // avoid ugly space before option
dropStyles.maxHeight = "280px";
if (!this._config.fullWidth) {
dropStyles.maxWidth = "360px";
}
if (this._config.fixed) {
dropStyles.position = "fixed";
}
dropStyles.overflowY = "auto";
// Prevent scrolling the menu from scrolling the page
// @link https://developer.mozilla.org/en-US/docs/Web/CSS/overscroll-behavior
dropStyles.overscrollBehavior = "contain";
dropStyles.textAlign = "unset"; // otherwise RTL is not good
// If the mouse was outside, entering remove keyboard nav mode
dropEl.addEventListener("mouseenter", (event) => {
this._keyboardNavigation = false;
});
this._holderElement.appendChild(dropEl);
// include aria-controls with the value of the id of the suggested list of values.
this._searchInput.setAttribute("aria-controls", dropEl.id);
}
_configureHolderElement() {
const holder = this._holderElement;
holder.classList.add(...["form-control", "dropdown"]);
// Reflect size (we must use form-select-xx because we may use form-select)
["form-select-lg", "form-select-sm"].forEach((className) => {
if (this._selectElement.classList.contains(className)) {
holder.classList.add(className);
}
});
// It is really more like a dropdown
if (this._config.suggestionsThreshold == 0 && this._config.showDropIcon) {
holder.classList.add("form-select");
}
// If we have an overflow parent, we can simply inherit styles
if (this.overflowParent) {
holder.style.position = "inherit";
}
// Prevent fixed height due to form-control in bs4
holder.style.height = "auto";
// Without this, clicking on a floating label won't always focus properly
holder.addEventListener("click", this);
}
_configureContainerElement() {
this._containerElement.addEventListener("click", (event) => {
if (this.isDisabled()) {
return;
}
if (this._searchInput.style.visibility != "hidden") {
this._searchInput.focus();
}
});
// Add some extra css to help positioning
const containerStyles = this._containerElement.style;
containerStyles.display = "flex";
containerStyles.alignItems = "center";
containerStyles.flexWrap = "wrap";
}
_configureSearchInput() {
const searchInput = this._searchInput;
searchInput.type = "text";
searchInput.autocomplete = "field-" + Date.now(); // off is ignored
searchInput.spellcheck = false;
// note: firefox doesn't support the properties so we use attributes
// @link https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-autocomplete
// @link https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-expanded
// use the aria-expanded state on the element with role combobox to communicate that the list is displayed.
// https://developer.mozilla.org/en-US/docs/Web/API/Element/ariaLabel
attrs(searchInput, {
"aria-auto-complete": "list",
"aria-has-popup": "menu",
"aria-expanded": "false",
"aria-label": this._config.searchLabel,
role: "combobox",
});
searchInput.style.cssText = `background-color:transparent;color:currentColor;border:0;padding:0;outline:0;max-width:100%`;
this.resetSearchInput(true);
this._containerElement.appendChild(searchInput);
this._rtl = window.getComputedStyle(searchInput).direction === "rtl";
}
// #endregion
// #region Events
onfocus(event) {
this._holderElement.classList.add(FOCUS_CLASS);
this.showOrSearch();
this._config.onFocus(event, this);
}
onblur(event) {
// Cancel any pending request
if (this._abortController) {
this._abortController.abort();
}
let clearValidation = true;
if (this._config.addOnBlur && this._searchInput.value) {
clearValidation = this._enterValue();
}
this._holderElement.classList.remove(FOCUS_CLASS);
this.hideSuggestions(clearValidation);
if (this._fireEvents) {
const sel = this.getSelection();
const data = {
selection: sel ? sel.dataset.value : null,
input: this._searchInput.value,
};
this._config.onBlur(event, this);
this._selectElement.dispatchEvent(new CustomEvent("tags.blur", { bubbles: true, detail: data }));
}
}
oninput(ev) {
const data = this._searchInput.value;
// Add item if a separator is used
// On mobile or copy paste, it can pass multiple chars (eg: when pressing space and it formats the string)
if (data) {
const lastChar = data.slice(-1);
if (this._config.separator.length && this._config.separator.includes(lastChar)) {
// Remove separator even if adding is prevented
this._searchInput.value = this._searchInput.value.slice(0, -1);
let value = this._searchInput.value;
let label = value;
let addData = {};
// There is no good reason to use the separator feature without allowNew, but who knows!
if (!this._config.allowNew) {
const sel = this.getSelection();
if (!sel) {
return;
}
value = sel.getAttribute(VALUE_ATTRIBUTE);
label = sel.dataset.label;
} else {
addData.new = 1;
}
this._add(label, value, addData);
return;
}
}
// Adjust input width to current content
setTimeout(() => {
this._adjustWidth();
});
// Check if we should display suggestions
this.showOrSearch();
}
/**
* keypress doesn't send arrow keys, so we use keydown
* @param {KeyboardEvent} event
*/
onkeydown(event) {
// Keycode reference : https://css-tricks.com/snippets/javascript/javascript-keycodes/
let key = event.keyCode || event.key;
/**
* @type {HTMLInputElement}
*/
// @ts-ignore
const target = event.target;
// Android virtual keyboard might always return 229
if (event.keyCode == 229) {
key = target.value.charAt(target.selectionStart - 1).charCodeAt(0);
}
// Keyboard keys
switch (key) {
case 13:
case "Enter":
event.preventDefault();
this._enterValue();
break;
case 38:
case "ArrowUp":
event.preventDefault();
this._keyboardNavigation = true;
this._moveSelection(PREV);
break;
case 40:
case "ArrowDown":
event.preventDefault();
this._keyboardNavigation = true;
if (this.isDropdownVisible()) {
this._moveSelection(NEXT);
} else {
// show menu regardless of input length
this.showOrSearch(false);
}
break;
case 8:
case "Backspace":
// If the current item is empty, remove the last one
if (this._searchInput.value.length == 0) {
this.removeLastItem();
this._adjustWidth();
this.showOrSearch();
}
break;
case 27:
case "Escape":
this._searchInput.focus();
this.hideSuggestions();
break;
}
}
onmousemove(e) {
// Moving the mouse means no longer using keyboard
this._keyboardNavigation = false;
}
onscroll(e) {
this._positionMenu();
}
onresize(e) {
this._positionMenu();
}
onclick(e = null) {
if (e) {
e.preventDefault();
}
if (!this.isSingle() && this.isMaxReached()) {
return;
}
// Focus on input when clicking on element or focusing select
this._searchInput.focus();
}
onreset(e) {
this.reset();
}
// #endregion
/**
* @param {Boolean} init called during init
*/
loadData(init = false) {
if (Object.keys(this._config.items).length > 0) {
this.setData(this._config.items, true);
} else {
this.resetSuggestions(true);
}
if (this._config.server) {
if (this._config.liveServer) {
// No need to load anything since it will happen when typing
// Initial values are loaded from config items or from provided options
} else {
this._loadFromServer(!init);
}
}
}
/**
* Make sure we have valid selected attributes
*/
_setSelectedAttributes() {
// we use selectedOptions because single select can have a selected option without a selected attribute if it's the first value
const selectedOptions = this._selectElement.selectedOptions || [];
for (let j = 0; j < selectedOptions.length; j++) {
// Enforce selected attr for consistency
if (selectedOptions[j].value && !selectedOptions[j].hasAttribute("selected")) {
selectedOptions[j].setAttribute("selected", "selected");
}
}
}
resetState() {
if (this.isDisabled()) {
this._holderElement.setAttribute("readonly", "");
this._searchInput.setAttribute("disabled", "");
this._holderElement.classList.add(DISABLED_CLASS);
} else {
rmAttr(this._holderElement, "readonly");
rmAttr(this._searchInput, "disabled");
this._holderElement.classList.remove(DISABLED_CLASS);
}
}
/**
* Reset suggestions from select element
* Iterates over option children then calls setData
* @param {Boolean} init called during init
*/
resetSuggestions(init = false) {
this._setSelectedAttributes();
let suggestions = Array.from(this._selectElement.children)
.filter(
/**
* @param {HTMLOptionElement|HTMLOptGroupElement} option
*/
(option) => {
return option instanceof HTMLOptGroupElement || !option.disabled || this._config.showDisabled;
}
)
.map(
/**
* @param {HTMLOptionElement|HTMLOptGroupElement} option
*/
(option) => {
if (option instanceof HTMLOptGroupElement) {
return {