tam_select 1.2.4 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2328 @@
1
+ // src/tam-select.js
2
+ var THEME_CLASSES = {
3
+ select2: {
4
+ wrapper: "tam-select relative w-full text-sm text-gray-700",
5
+ control: "relative flex min-h-11 w-full touch-manipulation cursor-text flex-wrap items-center gap-1.5 overflow-hidden rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm font-normal text-gray-800 transition duration-150 hover:border-gray-400 focus-within:border-blue-500 focus-within:outline-2 focus-within:outline-blue-500/20 focus-within:outline-offset-2",
6
+ controlMultiple: "h-auto min-h-11 py-2",
7
+ controlOpen: "border-blue-500 outline-2 outline-blue-500/20 outline-offset-2",
8
+ controlInvalid: "border-red-500 outline-2 outline-red-500/20 outline-offset-2",
9
+ controlDisabled: "cursor-not-allowed bg-gray-50 opacity-60",
10
+ input: "min-w-20 flex-1 shrink basis-0 border-0 bg-transparent p-0 text-start text-base font-normal text-gray-800 outline-none placeholder:font-normal placeholder:text-gray-400 focus:ring-0 sm:text-sm",
11
+ inputClosed: "absolute inset-0 z-[1] h-full w-full cursor-pointer opacity-0",
12
+ trigger: "absolute inset-0 z-0 h-full w-full touch-manipulation cursor-pointer rounded-md border-0 bg-transparent p-0 focus:outline-none disabled:cursor-not-allowed",
13
+ searchIcon: "size-3.5 shrink-0 text-gray-400",
14
+ placeholder: "pointer-events-none min-w-0 flex-1 truncate font-normal text-gray-400",
15
+ tag: "relative z-10 inline-flex max-w-full shrink-0 items-center gap-1 rounded bg-gray-100 border border-gray-300 px-1.5 py-0.5 text-xs font-medium text-gray-700",
16
+ tagRemove: "me-0.5 shrink-0 rounded p-0.5 hover:bg-gray-200 focus:outline-none focus:ring-1 focus:ring-blue-500",
17
+ clear: "relative z-20 inline-flex size-5 shrink-0 touch-manipulation items-center justify-center rounded text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600 focus:outline-none focus:ring-1 focus:ring-blue-500",
18
+ chevron: "pointer-events-none relative z-10 size-3.5 shrink-0 text-gray-400 transition-transform",
19
+ chevronOpen: "rotate-180",
20
+ dropdown: "absolute z-50 mt-1 flex w-full min-w-0 max-w-full flex-col overflow-hidden rounded-md border border-gray-300 bg-white shadow-lg",
21
+ dropdownSearch: "mb-0.5 flex w-full min-w-0 max-w-full shrink-0 items-center gap-1.5 rounded bg-gray-50 px-2 py-1.5",
22
+ results: "max-h-56 w-full min-w-0 max-w-full overflow-y-auto overscroll-contain scroll-py-0.5",
23
+ dropdownAnimation: "origin-top",
24
+ dropdownClosed: "mt-1 max-h-64 w-full scale-y-[0.97] opacity-0 pointer-events-none",
25
+ dropdownOpen: "scale-y-100 opacity-100 pointer-events-auto",
26
+ groupHeader: "px-2.5 pt-2.5 pb-0.5 text-[11px] font-semibold uppercase tracking-wider text-gray-400 select-none",
27
+ option: "flex min-h-8 touch-manipulation cursor-pointer select-none items-center justify-between gap-2 rounded px-2.5 py-1.5 text-sm leading-5 text-gray-700 outline-none transition-colors duration-75 hover:bg-blue-500 hover:text-white",
28
+ optionContent: "flex min-w-0 flex-1 items-center gap-2",
29
+ optionText: "flex min-w-0 flex-1 flex-col",
30
+ optionLabel: "font-normal",
31
+ optionDetail: "text-xs font-normal text-gray-400",
32
+ selectionContent: "flex min-w-0 flex-1 items-center overflow-hidden",
33
+ selectionLabel: "truncate text-sm font-normal",
34
+ optionImage: "size-8 shrink-0 rounded bg-gray-100 object-cover",
35
+ optionMeta: "shrink-0 rounded bg-gray-200 px-1.5 py-0.5 text-[11px] font-medium text-gray-600",
36
+ optionActive: "bg-blue-500 text-white [&_*]:text-white",
37
+ optionSelected: "bg-gray-100 font-normal text-gray-800",
38
+ optionCheck: "shrink-0",
39
+ optionDisabled: "pointer-events-none cursor-not-allowed opacity-50",
40
+ highlight: "rounded-sm bg-amber-200/80 px-0.5 text-inherit",
41
+ status: "sr-only",
42
+ message: "px-2.5 py-5 text-center text-sm text-gray-400",
43
+ loadMore: "block w-full cursor-pointer rounded px-2.5 py-2 text-center text-sm text-blue-600 hover:bg-gray-100",
44
+ spinner: "size-3.5 animate-spin rounded-full border-2 border-gray-200 border-t-blue-600",
45
+ error: "px-2.5 py-2.5 text-sm text-red-600",
46
+ tagDragging: "opacity-50 ring-1 ring-blue-400",
47
+ tagDragOver: "border-l-2 border-l-blue-500"
48
+ }
49
+ };
50
+ var DEFAULT_CLASSES = {
51
+ wrapper: "tam-select relative block w-full min-w-0 max-w-full self-stretch text-zinc-900 [color-scheme:light] dark:text-zinc-100 dark:[color-scheme:dark]",
52
+ control: "relative flex min-h-11 w-full touch-manipulation cursor-text flex-wrap items-center gap-1.5 overflow-hidden rounded-lg border border-zinc-200 bg-white px-3 py-2 text-sm font-normal text-zinc-800 shadow-sm transition duration-150 hover:border-zinc-300 focus-within:border-blue-500 focus-within:outline-2 focus-within:outline-blue-500/20 focus-within:outline-offset-2 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-100 dark:shadow-black/20 dark:hover:border-zinc-600 dark:focus-within:border-blue-400 dark:focus-within:outline-blue-400/20",
53
+ controlMultiple: "h-auto min-h-11 py-2",
54
+ controlOpen: "border-blue-500 outline-2 outline-blue-500/20 outline-offset-2 dark:border-blue-400 dark:outline-blue-400/20",
55
+ controlInvalid: "border-red-500 outline-2 outline-red-500/20 outline-offset-2 dark:border-red-400 dark:outline-red-400/20",
56
+ controlDisabled: "cursor-not-allowed bg-zinc-50 opacity-60 dark:bg-zinc-800 dark:text-zinc-400",
57
+ input: "min-w-12 flex-1 shrink basis-0 border-0 bg-transparent p-0 text-start text-base font-normal text-zinc-800 outline-none placeholder:font-normal placeholder:text-zinc-400 focus:ring-0 sm:text-sm dark:text-zinc-100 dark:placeholder:text-zinc-500",
58
+ inputClosed: "absolute inset-0 z-[1] h-full w-full cursor-pointer opacity-0",
59
+ trigger: "absolute inset-0 z-0 h-full w-full touch-manipulation cursor-pointer rounded-md border-0 bg-transparent p-0 focus:outline-none disabled:cursor-not-allowed",
60
+ searchIcon: "size-3.5 shrink-0 text-zinc-400 dark:text-zinc-500",
61
+ placeholder: "pointer-events-none min-w-0 flex-1 truncate font-normal text-zinc-400 dark:text-zinc-500",
62
+ tag: "relative z-10 inline-flex max-w-full shrink-0 items-center gap-1 rounded bg-blue-50 px-1.5 py-0.5 text-xs font-medium text-blue-700 transition-colors dark:bg-blue-950/50 dark:text-blue-300",
63
+ tagRemove: "me-0.5 shrink-0 rounded p-0.5 hover:bg-blue-100 focus:outline-none focus:ring-1 focus:ring-blue-500 dark:hover:bg-blue-900",
64
+ clear: "relative z-20 inline-flex size-5 shrink-0 touch-manipulation items-center justify-center rounded text-zinc-400 transition-colors hover:bg-zinc-100 hover:text-zinc-600 focus:outline-none focus:ring-1 focus:ring-blue-500 dark:text-zinc-500 dark:hover:bg-zinc-800 dark:hover:text-zinc-200 dark:focus:ring-blue-400",
65
+ chevron: "pointer-events-none relative z-10 size-3.5 shrink-0 text-zinc-400 transition-transform",
66
+ chevronOpen: "rotate-180",
67
+ dropdown: "absolute z-50 mt-1 flex w-full min-w-0 max-w-full flex-col overflow-hidden rounded-lg border border-zinc-200 bg-white shadow-lg dark:border-zinc-700 dark:bg-zinc-900 dark:shadow-black/50",
68
+ dropdownSearch: "mb-0.5 flex w-full min-w-0 max-w-full shrink-0 items-center gap-1.5 rounded bg-zinc-50 px-2 py-1.5 transition dark:bg-zinc-800/70",
69
+ results: "max-h-56 w-full min-w-0 max-w-full overflow-y-auto overscroll-contain scroll-py-1 p-1",
70
+ dropdownAnimation: "origin-top",
71
+ dropdownClosed: "mt-1 max-h-64 w-full scale-y-[0.97] opacity-0 pointer-events-none",
72
+ dropdownOpen: "scale-y-100 opacity-100 pointer-events-auto",
73
+ groupHeader: "px-2.5 pt-2.5 pb-0.5 text-[11px] font-semibold uppercase tracking-wider text-zinc-500 select-none dark:text-zinc-400",
74
+ option: "flex min-h-8 touch-manipulation cursor-pointer select-none items-center justify-between gap-2 rounded px-2.5 py-1.5 text-sm leading-5 text-zinc-700 outline-none transition-colors duration-75 hover:bg-zinc-100 dark:text-zinc-200 dark:hover:bg-zinc-800",
75
+ optionContent: "flex min-w-0 flex-1 items-center gap-2",
76
+ optionText: "flex min-w-0 flex-1 flex-col",
77
+ optionLabel: "font-normal",
78
+ optionLabelWrap: "whitespace-normal break-words [overflow-wrap:anywhere]",
79
+ optionDetail: "text-xs font-normal text-zinc-500 dark:text-zinc-400",
80
+ optionDetailWrap: "whitespace-normal break-words [overflow-wrap:anywhere]",
81
+ selectionContent: "flex min-w-0 flex-1 items-center overflow-hidden",
82
+ selectionLabel: "truncate text-sm font-normal",
83
+ optionImage: "size-8 shrink-0 rounded-full bg-zinc-100 object-cover dark:bg-zinc-800",
84
+ optionMeta: "shrink-0 rounded bg-zinc-100 px-1.5 py-0.5 text-[11px] font-medium text-zinc-500 dark:bg-zinc-800 dark:text-zinc-400",
85
+ optionActive: "bg-zinc-100 text-zinc-900 dark:bg-zinc-800 dark:text-white",
86
+ optionSelected: "bg-blue-50 font-normal text-blue-700 dark:bg-blue-950/60 dark:text-blue-300",
87
+ optionCheck: "shrink-0 text-blue-600 dark:text-blue-400",
88
+ optionDisabled: "pointer-events-none cursor-not-allowed opacity-50",
89
+ highlight: "rounded-sm bg-amber-200/80 px-0.5 text-inherit dark:bg-amber-400/30",
90
+ status: "sr-only",
91
+ selectionToolbar: "flex shrink-0 flex-wrap items-center gap-1.5 border-b border-zinc-200 bg-zinc-50/80 px-2 py-1.5 text-sm dark:border-zinc-700 dark:bg-zinc-800/60",
92
+ selectionAction: "inline-flex min-h-9 touch-manipulation items-center gap-1.5 rounded-md px-2.5 text-xs font-semibold transition-colors focus-visible:outline-2 focus-visible:outline-blue-500 disabled:cursor-not-allowed disabled:opacity-40",
93
+ selectionActionSelect: "bg-blue-600 text-white shadow-sm hover:bg-blue-700 dark:bg-blue-500 dark:text-zinc-950 dark:hover:bg-blue-400",
94
+ selectionActionClear: "border border-zinc-200 bg-white text-zinc-600 hover:bg-zinc-100 hover:text-zinc-900 dark:border-zinc-600 dark:bg-zinc-800 dark:text-zinc-300 dark:hover:bg-zinc-700 dark:hover:text-white",
95
+ selectionActionIcon: "size-3.5 shrink-0",
96
+ selectionShortcut: "hidden rounded border border-zinc-200 bg-white px-1.5 py-0.5 font-mono text-[10px] text-zinc-400 shadow-sm sm:inline-flex dark:border-zinc-600 dark:bg-zinc-900 dark:text-zinc-500",
97
+ selectionCount: "ms-auto rounded-full bg-zinc-200/70 px-2 py-1 text-[11px] font-semibold text-zinc-600 dark:bg-zinc-700 dark:text-zinc-300",
98
+ message: "px-2.5 py-5 text-center text-sm text-zinc-500 dark:text-zinc-400",
99
+ loadMore: "block w-full touch-manipulation cursor-pointer rounded px-2.5 py-2 text-center text-sm font-medium text-blue-600 hover:bg-zinc-100 focus:outline-none focus-visible:outline-2 focus-visible:outline-blue-500 dark:text-blue-400 dark:hover:bg-zinc-800",
100
+ spinner: "size-3.5 animate-spin rounded-full border-2 border-zinc-200 border-t-blue-500 dark:border-zinc-700 dark:border-t-blue-400",
101
+ error: "px-2.5 py-2.5 text-sm text-red-600 dark:text-red-400",
102
+ tagDragging: "opacity-50 ring-1 ring-blue-400",
103
+ tagDragOver: "border-l-2 border-l-blue-500"
104
+ };
105
+ var ICONS = {
106
+ search: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path stroke-linecap="round" d="m14.5 14.5 3 3m-1.25-8.25a7 7 0 1 1-14 0 7 7 0 0 1 14 0Z"/></svg>',
107
+ chevron: '<svg viewBox="0 0 20 20" fill="currentColor" aria-hidden="true"><path fill-rule="evenodd" d="M5.22 7.22a.75.75 0 011.06 0L10 10.94l3.72-3.72a.75.75 0 111.06 1.06l-4.25 4.25a.75.75 0 01-1.06 0L5.22 8.28a.75.75 0 010-1.06z" clip-rule="evenodd"/></svg>',
108
+ close: '<svg viewBox="0 0 20 20" fill="currentColor" class="size-3" aria-hidden="true"><path d="M6.28 5.22a.75.75 0 00-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 101.06 1.06L10 11.06l3.72 3.72a.75.75 0 101.06-1.06L11.06 10l3.72-3.72a.75.75 0 00-1.06-1.06L10 8.94 6.28 5.22z"/></svg>',
109
+ check: '<svg viewBox="0 0 20 20" fill="currentColor" class="size-4" aria-hidden="true"><path fill-rule="evenodd" d="M16.7 5.3a1 1 0 010 1.4l-8 8a1 1 0 01-1.4 0l-4-4a1 1 0 011.4-1.4L8 12.6l7.3-7.3a1 1 0 011.4 0z" clip-rule="evenodd"/></svg>'
110
+ };
111
+ var ANIMATION_PRESETS = {
112
+ default: { duration: 150, easing: "ease-out" },
113
+ material: { duration: 250, easing: "cubic-bezier(0.4, 0, 0.2, 1)" },
114
+ spring: { duration: 400, easing: "cubic-bezier(0.34, 1.56, 0.64, 1)" },
115
+ snappy: { duration: 100, easing: "ease-in" },
116
+ smooth: { duration: 300, easing: "cubic-bezier(0.25, 0.1, 0.25, 1)" },
117
+ bounce: { duration: 500, easing: "cubic-bezier(0.68, -0.55, 0.27, 1.55)" },
118
+ elastic: { duration: 600, easing: "cubic-bezier(0.68, -0.6, 0.32, 1.6)" },
119
+ fade: { duration: 200, easing: "linear" },
120
+ pop: { duration: 200, easing: "cubic-bezier(0.175, 0.885, 0.32, 1.275)" },
121
+ slide: { duration: 250, easing: "cubic-bezier(0.25, 0.46, 0.45, 0.94)" },
122
+ none: { duration: 0, easing: "ease" }
123
+ };
124
+ var uid = () => `tam-select-${Math.random().toString(36).slice(2, 10)}`;
125
+ var fold = (value) => String(value ?? "").normalize("NFKD").replace(/\p{Mark}/gu, "").toLocaleLowerCase();
126
+ var normalize = (value) => fold(value).trim();
127
+ var wordTokens = (value) => normalize(value).split(/[^\p{Letter}\p{Number}]+/u).filter(Boolean);
128
+ var boundedDistance = (left, right, maximum) => {
129
+ if (Math.abs(left.length - right.length) > maximum) return maximum + 1;
130
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
131
+ for (let leftIndex = 1; leftIndex <= left.length; leftIndex += 1) {
132
+ const current = [leftIndex];
133
+ let rowMinimum = current[0];
134
+ for (let rightIndex = 1; rightIndex <= right.length; rightIndex += 1) {
135
+ const substitution = previous[rightIndex - 1] + (left[leftIndex - 1] === right[rightIndex - 1] ? 0 : 1);
136
+ const distance = Math.min(previous[rightIndex] + 1, current[rightIndex - 1] + 1, substitution);
137
+ current.push(distance);
138
+ rowMinimum = Math.min(rowMinimum, distance);
139
+ }
140
+ if (rowMinimum > maximum) return maximum + 1;
141
+ previous = current;
142
+ }
143
+ return previous[right.length];
144
+ };
145
+ var setHidden = (element, hidden) => {
146
+ element.classList.toggle("hidden", hidden);
147
+ element.style.display = hidden ? "none" : "";
148
+ };
149
+ var toggleClasses = (element, classNames, force) => {
150
+ String(classNames).split(/\s+/).filter(Boolean).forEach((className) => element.classList.toggle(className, force));
151
+ };
152
+ var hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
153
+ var TamSelect = class _TamSelect {
154
+ static instances = /* @__PURE__ */ new WeakMap();
155
+ /**
156
+ * Undo markup left by an instance that no longer exists, e.g. a select
157
+ * restored from a page snapshot taken while it was enhanced.
158
+ */
159
+ static recoverStaleMarkup(select) {
160
+ const saved = select.dataset.tamSelectState;
161
+ if (!saved || _TamSelect.instances.has(select)) return;
162
+ let state;
163
+ try {
164
+ state = JSON.parse(saved);
165
+ } catch {
166
+ state = null;
167
+ }
168
+ const stale = select.nextElementSibling;
169
+ if (stale?.hasAttribute("data-tam-select-root")) stale.remove();
170
+ const staleDropdown = select.id ? select.ownerDocument.getElementById(`${select.id}-dropdown`) : null;
171
+ if (staleDropdown?.hasAttribute("data-tam-select-dropdown")) staleDropdown.remove();
172
+ if (state) {
173
+ if (!state.srOnly) select.classList.remove("sr-only");
174
+ if (state.tabindex === null) select.removeAttribute("tabindex");
175
+ else select.setAttribute("tabindex", state.tabindex);
176
+ if (state.ariaHidden === null) select.removeAttribute("aria-hidden");
177
+ else select.setAttribute("aria-hidden", state.ariaHidden);
178
+ if (state.id === null) select.removeAttribute("id");
179
+ }
180
+ delete select.dataset.tamSelectState;
181
+ }
182
+ static getInstance(element) {
183
+ return this.instances.get(element) || null;
184
+ }
185
+ constructor(select, options = {}) {
186
+ if (!(select instanceof HTMLSelectElement)) throw new TypeError("TamSelect requires a <select> element");
187
+ if (_TamSelect.instances.has(select)) return _TamSelect.instances.get(select);
188
+ this.select = select;
189
+ this.options = {
190
+ searchable: true,
191
+ creatable: false,
192
+ clearable: true,
193
+ closeAfterSelect: !select.multiple,
194
+ placeholder: select.dataset.placeholder || select.querySelector('option[value=""]')?.textContent || "Select\u2026",
195
+ searchPlaceholder: "Search\u2026",
196
+ noResultsText: "No results found",
197
+ createText: (query) => `Create "${query}"`,
198
+ loadingText: "Loading\u2026",
199
+ loadMoreText: "Load more",
200
+ inputTooShortText: (remaining) => `Enter ${remaining} more character${remaining === 1 ? "" : "s"}`,
201
+ remoteUrl: null,
202
+ queryParam: "q",
203
+ pageParam: "page",
204
+ debounce: 250,
205
+ minQueryLength: 0,
206
+ fuzzySearch: true,
207
+ highlightMatches: true,
208
+ sortByRelevance: true,
209
+ searchFields: ["label", "detail", "meta"],
210
+ resultsText: (count) => `${count} result${count === 1 ? "" : "s"} available`,
211
+ clearLabel: "Clear selection",
212
+ removeLabel: (item) => `Remove ${item.label}`,
213
+ selectionLimitText: (limit) => `You can select up to ${limit} item${limit === 1 ? "" : "s"}`,
214
+ language: {},
215
+ valueField: "value",
216
+ labelField: "label",
217
+ imageField: "image",
218
+ itemsPath: "items",
219
+ paginationPath: "pagination",
220
+ matcher: null,
221
+ theme: "auto",
222
+ classes: {},
223
+ headers: {},
224
+ animations: true,
225
+ animationPreset: null,
226
+ animationDuration: 150,
227
+ animationEasing: "ease-out",
228
+ emptyState: null,
229
+ noResultsState: null,
230
+ loadingState: null,
231
+ lazyLoadImages: false,
232
+ virtualScroll: false,
233
+ virtualScrollThreshold: 100,
234
+ virtualScrollBuffer: 5,
235
+ virtualItemHeight: 32,
236
+ wrapOptionText: null,
237
+ optionTooltip: true,
238
+ draggable: false,
239
+ maximumSelectionLength: 0,
240
+ bulkActions: false,
241
+ showSelectionCount: false,
242
+ hideSelected: false,
243
+ selectAllText: (count) => `Select all${count > 0 ? ` ${count}` : ""}`,
244
+ deselectAllText: (count) => `Clear${count > 0 ? ` ${count}` : ""}`,
245
+ selectionCountText: (count, limit) => limit > 0 ? `${count} / ${limit} selected` : `${count} selected`,
246
+ maximumInputLength: 0,
247
+ minimumResultsForSearch: 0,
248
+ selectOnClose: false,
249
+ tokenSeparators: [],
250
+ sorter: null,
251
+ templateResult: null,
252
+ templateSelection: null,
253
+ transport: null,
254
+ processResults: null,
255
+ remoteParams: {},
256
+ cacheRemote: false,
257
+ dropdownParent: null,
258
+ dropdownWidth: "auto",
259
+ maxDropdownWidth: 480,
260
+ maxDropdownHeight: 360,
261
+ viewportPadding: 8,
262
+ width: "resolve",
263
+ dir: "auto",
264
+ ...options
265
+ };
266
+ const languageOptions = {
267
+ placeholder: "placeholder",
268
+ searchPlaceholder: "searchPlaceholder",
269
+ noResults: "noResultsText",
270
+ create: "createText",
271
+ loading: "loadingText",
272
+ loadMore: "loadMoreText",
273
+ inputTooShort: "inputTooShortText",
274
+ results: "resultsText",
275
+ clear: "clearLabel",
276
+ remove: "removeLabel",
277
+ selectionLimit: "selectionLimitText",
278
+ selectAll: "selectAllText",
279
+ deselectAll: "deselectAllText",
280
+ selectionCount: "selectionCountText"
281
+ };
282
+ Object.entries(languageOptions).forEach(([languageKey, optionKey]) => {
283
+ if (hasOwn(this.options.language, languageKey) && !hasOwn(options, optionKey)) {
284
+ this.options[optionKey] = this.options.language[languageKey];
285
+ }
286
+ });
287
+ this.dir = this.options.dir === "auto" ? this.detectDirection() : this.options.dir;
288
+ this.theme = this.options.theme === "auto" ? "default" : this.options.theme;
289
+ const themeClasses = THEME_CLASSES[this.theme] || {};
290
+ this.classes = { ...DEFAULT_CLASSES, ...themeClasses, ...this.options.classes };
291
+ this.multiple = select.multiple;
292
+ this.searchable = Boolean(this.options.searchable || this.options.creatable);
293
+ this.items = [];
294
+ this.remoteResults = [];
295
+ this.visibleItems = [];
296
+ this.activeIndex = -1;
297
+ this.opened = false;
298
+ this.loading = false;
299
+ this.loadingPage = null;
300
+ this.error = null;
301
+ this.query = "";
302
+ this.page = 0;
303
+ this.nextPage = null;
304
+ this.hasMore = false;
305
+ this.requestSequence = 0;
306
+ this.activeRequest = null;
307
+ this.optionIds = /* @__PURE__ */ new WeakMap();
308
+ this.optionIdSequence = 0;
309
+ this.invalidFromEvent = false;
310
+ _TamSelect.recoverStaleMarkup(select);
311
+ this.originalTabIndex = select.getAttribute("tabindex");
312
+ this.originalAriaHidden = select.getAttribute("aria-hidden");
313
+ this.originalId = select.getAttribute("id");
314
+ this.hadSrOnlyClass = select.classList.contains("sr-only");
315
+ select.dataset.tamSelectState = JSON.stringify({
316
+ tabindex: this.originalTabIndex,
317
+ ariaHidden: this.originalAriaHidden,
318
+ id: this.originalId,
319
+ srOnly: this.hadSrOnlyClass
320
+ });
321
+ this.typeaheadBuffer = "";
322
+ this.typeaheadTimer = null;
323
+ this.groupTree = [];
324
+ this.closeTimer = null;
325
+ this.closeTransitionHandler = null;
326
+ this.lazyObserver = null;
327
+ this.selectionLimitReached = false;
328
+ this.searchVisible = this.options.minimumResultsForSearch <= 0;
329
+ this.isVirtualScroll = false;
330
+ this.virtualStartIndex = 0;
331
+ this.onVirtualScroll = null;
332
+ this.remoteCache = /* @__PURE__ */ new Map();
333
+ this.destroyed = false;
334
+ this.refreshQueued = false;
335
+ this.composing = false;
336
+ this.animationsEnabled = this.options.animations && !(typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches);
337
+ this.build();
338
+ this.bind();
339
+ this.readNativeOptions();
340
+ this.renderSelection();
341
+ this.applyFitWidth();
342
+ document.fonts?.ready?.then(() => {
343
+ if (this.destroyed) return;
344
+ this.textWidthCache?.clear();
345
+ this.itemWidthCache = /* @__PURE__ */ new WeakMap();
346
+ this.applyFitWidth();
347
+ });
348
+ _TamSelect.instances.set(select, this);
349
+ }
350
+ build() {
351
+ this.id = this.select.id || uid();
352
+ if (!this.select.id) this.select.id = this.id;
353
+ this.listboxId = `${this.id}-listbox`;
354
+ this.valuesId = `${this.id}-value`;
355
+ this.select.classList.add("sr-only");
356
+ this.select.tabIndex = -1;
357
+ this.select.setAttribute("aria-hidden", "true");
358
+ this.wrapper = document.createElement("div");
359
+ this.wrapper.className = this.classes.wrapper;
360
+ this.wrapper.dataset.tamSelectRoot = "";
361
+ this.wrapper.setAttribute("dir", this.dir);
362
+ const requestedWidth = this.options.width === "resolve" ? this.select.style.width || "100%" : this.options.width;
363
+ this.fitWidth = ["auto", "fit"].includes(String(requestedWidth).trim());
364
+ this.wrapper.style.width = this.fitWidth ? "auto" : requestedWidth;
365
+ this.wrapper.style.maxWidth = "100%";
366
+ this.wrapper.style.minWidth = "0";
367
+ this.wrapper.style.position = "relative";
368
+ if (this.fitWidth) {
369
+ this.wrapper.style.display = "inline-block";
370
+ this.wrapper.style.verticalAlign = "middle";
371
+ }
372
+ this.control = document.createElement("div");
373
+ this.control.className = [
374
+ this.classes.control,
375
+ this.multiple && this.classes.controlMultiple
376
+ ].filter(Boolean).join(" ");
377
+ this.values = document.createElement("div");
378
+ this.values.id = this.valuesId;
379
+ this.values.className = "contents";
380
+ this.values.style.display = "contents";
381
+ this.searchIcon = document.createElement("span");
382
+ this.searchIcon.className = this.classes.searchIcon;
383
+ this.searchIcon.innerHTML = ICONS.search;
384
+ if (this.searchable) {
385
+ this.input = document.createElement("input");
386
+ this.input.id = `${this.id}-search`;
387
+ this.input.type = "text";
388
+ this.input.className = this.classes.input;
389
+ this.input.autocomplete = "off";
390
+ this.input.spellcheck = false;
391
+ this.input.autocapitalize = "none";
392
+ this.input.setAttribute("autocorrect", "off");
393
+ this.input.setAttribute("enterkeyhint", "search");
394
+ if (this.options.maximumInputLength > 0) this.input.maxLength = this.options.maximumInputLength;
395
+ this.input.setAttribute("aria-controls", this.listboxId);
396
+ if (this.multiple) {
397
+ this.input.setAttribute("role", "combobox");
398
+ this.input.setAttribute("aria-haspopup", "listbox");
399
+ this.input.setAttribute("aria-expanded", "false");
400
+ this.input.setAttribute("aria-autocomplete", "list");
401
+ this.focusTarget = this.input;
402
+ } else {
403
+ this.input.type = "search";
404
+ this.input.setAttribute("role", "searchbox");
405
+ this.input.setAttribute("aria-label", this.options.searchPlaceholder);
406
+ }
407
+ }
408
+ if (!this.multiple || !this.searchable) {
409
+ this.trigger = document.createElement("button");
410
+ this.trigger.type = "button";
411
+ this.trigger.className = this.classes.trigger;
412
+ this.trigger.setAttribute("role", "combobox");
413
+ this.trigger.setAttribute("aria-haspopup", "listbox");
414
+ this.trigger.setAttribute("aria-expanded", "false");
415
+ this.trigger.setAttribute("aria-controls", this.listboxId);
416
+ this.focusTarget = this.trigger;
417
+ }
418
+ this.clearButton = document.createElement("button");
419
+ this.clearButton.type = "button";
420
+ this.clearButton.className = this.classes.clear;
421
+ this.clearButton.setAttribute("aria-label", this.options.clearLabel);
422
+ this.clearButton.innerHTML = ICONS.close;
423
+ this.chevron = document.createElement("span");
424
+ this.chevron.className = this.classes.chevron;
425
+ this.chevron.innerHTML = ICONS.chevron;
426
+ this.dropdown = document.createElement("div");
427
+ this.dropdown.id = `${this.id}-dropdown`;
428
+ this.dropdown.dataset.tamSelectDropdown = "";
429
+ this.dropdown.className = this.classes.dropdown;
430
+ setHidden(this.dropdown, true);
431
+ this.dropdown.style.width = "100%";
432
+ this.dropdown.style.minWidth = "0";
433
+ this.dropdown.style.maxWidth = "100%";
434
+ this.dropdown.style.boxSizing = "border-box";
435
+ if (this.animationsEnabled) {
436
+ const preset = this.options.animationPreset ? ANIMATION_PRESETS[this.options.animationPreset] : null;
437
+ const duration = preset ? preset.duration : this.options.animationDuration;
438
+ const easing = preset ? preset.easing : this.options.animationEasing;
439
+ this.options.animationDuration = duration;
440
+ this.options.animationEasing = easing;
441
+ toggleClasses(this.dropdown, this.classes.dropdownAnimation, true);
442
+ this.dropdown.style.setProperty("--tam-duration", `${duration}ms`);
443
+ this.dropdown.style.setProperty("--tam-easing", easing);
444
+ this.dropdown.style.transition = [
445
+ `opacity var(--tam-duration) var(--tam-easing)`,
446
+ `transform var(--tam-duration) var(--tam-easing)`
447
+ ].join(", ");
448
+ }
449
+ this.results = document.createElement("div");
450
+ this.results.id = this.listboxId;
451
+ this.results.className = this.classes.results;
452
+ this.results.style.width = "100%";
453
+ this.results.style.minWidth = "0";
454
+ this.results.style.maxWidth = "100%";
455
+ this.results.style.boxSizing = "border-box";
456
+ this.results.setAttribute("role", "listbox");
457
+ if (this.multiple) this.results.setAttribute("aria-multiselectable", "true");
458
+ if (this.searchable && !this.multiple) {
459
+ this.searchPanel = document.createElement("div");
460
+ this.searchPanel.className = this.classes.dropdownSearch;
461
+ this.searchPanel.style.width = "100%";
462
+ this.searchPanel.style.minWidth = "0";
463
+ this.searchPanel.style.maxWidth = "100%";
464
+ this.searchPanel.style.boxSizing = "border-box";
465
+ this.input.style.width = "100%";
466
+ this.input.style.minWidth = "0";
467
+ this.input.style.maxWidth = "100%";
468
+ this.input.style.boxSizing = "border-box";
469
+ this.searchPanel.append(this.searchIcon, this.input);
470
+ this.dropdown.append(this.searchPanel, this.results);
471
+ } else {
472
+ this.dropdown.append(this.results);
473
+ }
474
+ this.buildSelectionToolbar();
475
+ this.status = document.createElement("div");
476
+ this.status.className = this.classes.status;
477
+ this.status.setAttribute("role", "status");
478
+ this.status.setAttribute("aria-live", "polite");
479
+ this.status.setAttribute("aria-atomic", "true");
480
+ const focusControl = this.multiple && this.searchable ? [this.searchIcon, this.input] : [this.trigger];
481
+ this.control.append(this.values, ...focusControl, this.chevron, this.clearButton);
482
+ this.wrapper.append(this.control, this.status);
483
+ this.select.after(this.wrapper);
484
+ this.dropdownParent = this.resolveDropdownParent();
485
+ this.portalDropdown = Boolean(this.dropdownParent);
486
+ if (this.portalDropdown) {
487
+ this.dropdownParent.append(this.dropdown);
488
+ this.dropdown.style.position = "fixed";
489
+ this.dropdown.style.marginTop = "0";
490
+ this.dropdown.style.visibility = "hidden";
491
+ } else {
492
+ this.wrapper.append(this.dropdown);
493
+ }
494
+ this.labelElements = this.findLabelElements();
495
+ this.applyDisabled();
496
+ this.syncAria();
497
+ this.initLazyObserver();
498
+ }
499
+ buildSelectionToolbar() {
500
+ if (!this.multiple || !(this.options.bulkActions || this.options.showSelectionCount)) return;
501
+ this.selectionToolbar = document.createElement("div");
502
+ this.selectionToolbar.className = this.classes.selectionToolbar;
503
+ this.selectionToolbar.dataset.tamSelectToolbar = "";
504
+ if (this.options.bulkActions) {
505
+ const makeAction = (action, icon, variantClass) => {
506
+ const button = document.createElement("button");
507
+ button.type = "button";
508
+ button.className = `${this.classes.selectionAction} ${variantClass}`;
509
+ button.setAttribute("aria-controls", this.listboxId);
510
+ const iconElement = document.createElement("span");
511
+ iconElement.className = this.classes.selectionActionIcon;
512
+ iconElement.setAttribute("aria-hidden", "true");
513
+ iconElement.innerHTML = icon;
514
+ const labelElement = document.createElement("span");
515
+ button.append(iconElement, labelElement);
516
+ button.addEventListener("click", (event) => {
517
+ event.stopPropagation();
518
+ if (!button.disabled) action();
519
+ });
520
+ return { button, labelElement };
521
+ };
522
+ const selectAction = makeAction(() => this.selectAll(), ICONS.check, this.classes.selectionActionSelect);
523
+ const clearAction = makeAction(() => this.deselectAll(), ICONS.close, this.classes.selectionActionClear);
524
+ this.selectAllButton = selectAction.button;
525
+ this.selectAllLabel = selectAction.labelElement;
526
+ this.deselectAllButton = clearAction.button;
527
+ this.deselectAllLabel = clearAction.labelElement;
528
+ this.selectionShortcut = document.createElement("kbd");
529
+ this.selectionShortcut.className = this.classes.selectionShortcut;
530
+ this.selectionShortcut.textContent = /Mac|iPhone|iPad/.test(navigator.platform || "") ? "\u2318 A" : "Ctrl A";
531
+ this.selectionShortcut.title = "Toggle all matching options";
532
+ this.selectionToolbar.append(this.selectAllButton, this.deselectAllButton, this.selectionShortcut);
533
+ this.selectionToolbar.addEventListener("keydown", (event) => {
534
+ if (event.key === "Escape") {
535
+ event.preventDefault();
536
+ this.close(false);
537
+ this.focusTarget.focus();
538
+ } else if (event.key === "Tab") {
539
+ const enabledActions = [this.selectAllButton, this.deselectAllButton].filter((button) => !button.disabled);
540
+ if (event.shiftKey && event.target === enabledActions[0]) {
541
+ event.preventDefault();
542
+ this.focusTarget.focus();
543
+ } else if (!event.shiftKey && event.target === enabledActions.at(-1)) {
544
+ this.focusTarget.focus();
545
+ this.close(false);
546
+ }
547
+ }
548
+ });
549
+ }
550
+ if (this.options.showSelectionCount) {
551
+ this.selectionCount = document.createElement("span");
552
+ this.selectionCount.className = this.classes.selectionCount;
553
+ this.selectionCount.setAttribute("role", "status");
554
+ this.selectionCount.setAttribute("aria-live", "polite");
555
+ this.selectionCount.setAttribute("aria-atomic", "true");
556
+ this.selectionToolbar.append(this.selectionCount);
557
+ }
558
+ this.dropdown.insertBefore(this.selectionToolbar, this.results);
559
+ }
560
+ updateSelectionToolbar() {
561
+ if (!this.selectionToolbar) return;
562
+ const count = this.selectedItems().length;
563
+ const limit = this.options.maximumSelectionLength;
564
+ if (this.selectionCount) {
565
+ const text = typeof this.options.selectionCountText === "function" ? this.options.selectionCountText(count, limit) : this.options.selectionCountText;
566
+ if (this.selectionCount.textContent !== String(text)) this.selectionCount.textContent = text;
567
+ }
568
+ if (this.selectAllButton) {
569
+ const matches = this.bulkCandidates();
570
+ const selectedMatches = matches.filter((item) => item.selected).length;
571
+ const selectableMatches = matches.length - selectedMatches;
572
+ const selectText = typeof this.options.selectAllText === "function" ? this.options.selectAllText(matches.length) : this.options.selectAllText;
573
+ const deselectText = typeof this.options.deselectAllText === "function" ? this.options.deselectAllText(selectedMatches) : this.options.deselectAllText;
574
+ this.selectAllLabel.textContent = selectText;
575
+ this.deselectAllLabel.textContent = deselectText;
576
+ this.selectAllButton.setAttribute("aria-label", selectText);
577
+ this.deselectAllButton.setAttribute("aria-label", deselectText);
578
+ this.selectAllButton.disabled = this.select.disabled || limit > 0 && count >= limit || selectableMatches === 0;
579
+ this.deselectAllButton.disabled = this.select.disabled || selectedMatches === 0;
580
+ this.selectAllButton.setAttribute("aria-disabled", String(this.selectAllButton.disabled));
581
+ this.deselectAllButton.setAttribute("aria-disabled", String(this.deselectAllButton.disabled));
582
+ }
583
+ }
584
+ bind() {
585
+ this.onControlClick = (event) => {
586
+ if (!this.searchable || this.select.disabled || event.target.closest("button")) return;
587
+ this.open();
588
+ this.input.focus();
589
+ };
590
+ this.onInput = (event) => {
591
+ if (this.destroyed || this.composing || event?.isComposing) return;
592
+ this.query = this.input.value;
593
+ if (this.multiple && this.options.tokenSeparators.length && this.options.creatable) {
594
+ this.tokenizeInput();
595
+ }
596
+ this.open(false);
597
+ if (this.options.remoteUrl) this.scheduleRemote();
598
+ else this.filterLocal();
599
+ };
600
+ this.onCompositionStart = () => {
601
+ this.composing = true;
602
+ };
603
+ this.onCompositionEnd = () => {
604
+ this.composing = false;
605
+ queueMicrotask(() => {
606
+ if (!this.destroyed && this.query !== this.input.value) this.onInput();
607
+ });
608
+ };
609
+ this.onKeydown = (event) => this.handleKeydown(event);
610
+ this.onClear = (event) => {
611
+ event.stopPropagation();
612
+ this.clear();
613
+ };
614
+ this.onTrigger = (event) => {
615
+ event.preventDefault();
616
+ this.open();
617
+ };
618
+ this.onOutside = (event) => {
619
+ if (!this.wrapper.contains(event.target) && !this.dropdown.contains(event.target)) this.close();
620
+ };
621
+ this.onNativeChange = () => {
622
+ if (this.select.checkValidity()) this.invalidFromEvent = false;
623
+ this.readNativeOptions();
624
+ this.renderSelection();
625
+ this.syncAria();
626
+ this.renderDropdown();
627
+ };
628
+ this.onNativeInvalid = (event) => {
629
+ event.preventDefault();
630
+ this.invalidFromEvent = true;
631
+ this.syncAria();
632
+ this.focusTarget.focus();
633
+ };
634
+ this.onScroll = () => {
635
+ if (!this.error && this.results.scrollTop + this.results.clientHeight >= this.results.scrollHeight - 32) this.loadNextPage();
636
+ if (this.isVirtualScroll) {
637
+ this.rerenderVirtualItems();
638
+ }
639
+ };
640
+ this.onLabelClick = (event) => {
641
+ if (event.target.closest("a, button, input, select, textarea")) return;
642
+ event.preventDefault();
643
+ this.focusTarget.focus();
644
+ };
645
+ this.onFormReset = () => queueMicrotask(() => this.refresh());
646
+ this.onViewportChange = (event) => {
647
+ if (!this.opened) return;
648
+ if (event?.type === "scroll" && event.target === this.results) return;
649
+ if (this.portalDropdown) this.updateDropdownPosition();
650
+ else if (event?.type !== "scroll") this.updateInlineDropdownWidth();
651
+ };
652
+ this.control.addEventListener("click", this.onControlClick);
653
+ this.focusTarget.addEventListener("keydown", this.onKeydown);
654
+ if (this.input && this.input !== this.focusTarget) this.input.addEventListener("keydown", this.onKeydown);
655
+ if (this.input) {
656
+ this.input.addEventListener("input", this.onInput);
657
+ this.input.addEventListener("compositionstart", this.onCompositionStart);
658
+ this.input.addEventListener("compositionend", this.onCompositionEnd);
659
+ }
660
+ if (this.trigger) this.trigger.addEventListener("click", this.onTrigger);
661
+ this.clearButton.addEventListener("click", this.onClear);
662
+ this.results.addEventListener("scroll", this.onScroll);
663
+ this.select.addEventListener("change", this.onNativeChange);
664
+ this.select.addEventListener("invalid", this.onNativeInvalid);
665
+ this.labelElements.forEach((label) => label.addEventListener("click", this.onLabelClick));
666
+ document.addEventListener("pointerdown", this.onOutside);
667
+ this.select.form?.addEventListener("reset", this.onFormReset);
668
+ window.addEventListener("resize", this.onViewportChange);
669
+ window.addEventListener("scroll", this.onViewportChange, true);
670
+ window.visualViewport?.addEventListener("resize", this.onViewportChange);
671
+ window.visualViewport?.addEventListener("scroll", this.onViewportChange);
672
+ this.mutationObserver = new MutationObserver(() => this.queueRefresh());
673
+ this.mutationObserver.observe(this.select, {
674
+ childList: true,
675
+ subtree: true,
676
+ attributes: true,
677
+ attributeFilter: ["disabled", "label", "value", "selected", "required", "aria-invalid", "aria-describedby", "data-detail", "data-meta", "data-image"]
678
+ });
679
+ }
680
+ resolveDropdownParent() {
681
+ if (!this.options.dropdownParent) return null;
682
+ if (typeof this.options.dropdownParent === "string") return document.querySelector(this.options.dropdownParent);
683
+ const ElementClass = this.select.ownerDocument.defaultView.Element;
684
+ return this.options.dropdownParent instanceof ElementClass ? this.options.dropdownParent : null;
685
+ }
686
+ queueRefresh() {
687
+ if (this.refreshQueued || this.destroyed) return;
688
+ this.refreshQueued = true;
689
+ queueMicrotask(() => {
690
+ this.refreshQueued = false;
691
+ if (!this.destroyed && this.select.isConnected) this.refresh();
692
+ });
693
+ }
694
+ viewportBox() {
695
+ const padding = Math.max(0, Number(this.options.viewportPadding) || 0);
696
+ const visualViewport = window.visualViewport;
697
+ const left = visualViewport?.offsetLeft || 0;
698
+ const top = visualViewport?.offsetTop || 0;
699
+ const width = visualViewport?.width || document.documentElement.clientWidth || window.innerWidth;
700
+ const height = visualViewport?.height || document.documentElement.clientHeight || window.innerHeight;
701
+ return { left, top, width, height, right: left + width, bottom: top + height, padding };
702
+ }
703
+ // Like a native select, the menu is never narrower than its control and
704
+ // grows to fit its widest option, within maxDropdownWidth and the viewport.
705
+ resolveDropdownWidth(triggerWidth, availableWidth) {
706
+ const viewportLimit = availableWidth || triggerWidth;
707
+ if (!["auto", "content"].includes(this.options.dropdownWidth)) return Math.min(triggerWidth, viewportLimit);
708
+ if (this.dropdownContentWidth == null || this.dropdownWidthStale) {
709
+ this.dropdownContentWidth = Math.max(this.dropdownContentWidth || 0, this.measureDropdownContentWidth());
710
+ this.dropdownWidthStale = false;
711
+ }
712
+ const configuredMaximum = Number(this.options.maxDropdownWidth);
713
+ const maximum = configuredMaximum > 0 ? Math.max(triggerWidth, configuredMaximum) : Infinity;
714
+ return Math.min(Math.max(triggerWidth, this.dropdownContentWidth), maximum, viewportLimit);
715
+ }
716
+ // Align the menu with the control's start edge, then keep it on screen.
717
+ resolveDropdownLeft(rect, width, viewport) {
718
+ const start = this.dir === "rtl" ? rect.right - width : rect.left;
719
+ const minimum = viewport.left + viewport.padding;
720
+ const maximum = Math.max(minimum, viewport.right - viewport.padding - width);
721
+ return Math.min(Math.max(start, minimum), maximum);
722
+ }
723
+ // The horizontal space an inline menu may use: the viewport, narrowed by
724
+ // every ancestor that clips overflow (cards, modals, scrolling tables), so
725
+ // a wider menu is never cut off. Use dropdownParent to escape them.
726
+ inlineDropdownBounds() {
727
+ const viewport = this.viewportBox();
728
+ let left = viewport.left + viewport.padding;
729
+ let right = viewport.right - viewport.padding;
730
+ const view = this.select.ownerDocument.defaultView;
731
+ const root = this.select.ownerDocument.documentElement;
732
+ for (let element = this.wrapper.parentElement; element && element !== root && element !== this.select.ownerDocument.body; element = element.parentElement) {
733
+ const style = view.getComputedStyle(element);
734
+ const overflowX = [style.overflowX, String(style.overflow || "").split(/\s+/)[0]].find((value) => value && value !== "visible");
735
+ if (!overflowX) continue;
736
+ const box = element.getBoundingClientRect();
737
+ if (!box.width) continue;
738
+ const innerLeft = box.left + (element.clientLeft || 0);
739
+ left = Math.max(left, innerLeft);
740
+ right = Math.min(right, innerLeft + (element.clientWidth || box.width));
741
+ }
742
+ return { left, right: Math.max(left, right) };
743
+ }
744
+ updateInlineDropdownWidth() {
745
+ if (this.portalDropdown || !this.opened) return;
746
+ const rect = this.control.getBoundingClientRect();
747
+ if (!rect.width) return;
748
+ const bounds = this.inlineDropdownBounds();
749
+ const width = this.resolveDropdownWidth(rect.width, Math.max(0, bounds.right - bounds.left));
750
+ if (width <= rect.width + 0.5) {
751
+ this.dropdown.style.width = "100%";
752
+ this.dropdown.style.maxWidth = "100%";
753
+ this.dropdown.style.left = "";
754
+ this.dropdown.style.right = "";
755
+ return;
756
+ }
757
+ const offsetParentLeft = this.wrapper.getBoundingClientRect().left + (this.wrapper.clientLeft || 0);
758
+ this.dropdown.style.width = `${width}px`;
759
+ this.dropdown.style.maxWidth = "none";
760
+ this.dropdown.style.left = `${this.resolveDropdownLeft(rect, width, { ...bounds, padding: 0 }) - offsetParentLeft}px`;
761
+ this.dropdown.style.right = "auto";
762
+ }
763
+ updateDropdownPosition() {
764
+ if (!this.portalDropdown) return;
765
+ const rect = this.control.getBoundingClientRect();
766
+ const gap = 6;
767
+ const viewport = this.viewportBox();
768
+ const { padding, top: viewportTop, bottom: viewportBottom } = viewport;
769
+ const maximumHeight = Math.max(96, Number(this.options.maxDropdownHeight) || 360);
770
+ const searchHeight = this.searchPanel && !this.searchPanel.classList.contains("hidden") ? this.searchPanel.getBoundingClientRect().height || 44 : 0;
771
+ const toolbarHeight = this.selectionToolbar?.getBoundingClientRect().height || (this.selectionToolbar ? 52 : 0);
772
+ const dropdownChrome = Math.max(0, this.dropdown.offsetHeight - this.dropdown.clientHeight);
773
+ const naturalHeight = this.results.scrollHeight > 0 ? this.results.scrollHeight + searchHeight + toolbarHeight + dropdownChrome : this.dropdown.scrollHeight || 288;
774
+ const desiredHeight = Math.min(naturalHeight, maximumHeight);
775
+ const availableBelow = Math.max(0, viewportBottom - rect.bottom - gap - padding);
776
+ const availableAbove = Math.max(0, rect.top - viewportTop - gap - padding);
777
+ const placeAbove = availableBelow < Math.min(desiredHeight, 192) && availableAbove > availableBelow;
778
+ const availableHeight = placeAbove ? availableAbove : availableBelow;
779
+ const dropdownHeight = Math.max(96, Math.min(desiredHeight, availableHeight || desiredHeight));
780
+ const availableWidth = Math.max(0, viewport.width - padding * 2);
781
+ const dropdownWidth = this.resolveDropdownWidth(rect.width, availableWidth);
782
+ const left = this.resolveDropdownLeft(rect, dropdownWidth, viewport);
783
+ this.dropdown.style.left = `${left}px`;
784
+ this.dropdown.style.width = `${dropdownWidth}px`;
785
+ this.dropdown.style.maxWidth = `${availableWidth || dropdownWidth}px`;
786
+ this.dropdown.style.maxHeight = `${dropdownHeight}px`;
787
+ this.results.style.maxHeight = `${Math.max(48, dropdownHeight - searchHeight - toolbarHeight - dropdownChrome)}px`;
788
+ this.dropdown.style.top = `${placeAbove ? Math.max(viewportTop + padding, rect.top - dropdownHeight - gap) : rect.bottom + gap}px`;
789
+ this.dropdown.dataset.placement = placeAbove ? "top" : "bottom";
790
+ }
791
+ // Returns a function measuring text in `element`'s font. Canvas is exact;
792
+ // environments without it (jsdom) fall back to an average glyph width.
793
+ textMeasurer(element, fallbackFontSize = 16) {
794
+ const view = this.select.ownerDocument.defaultView;
795
+ const style = element ? view.getComputedStyle(element) : null;
796
+ const fontSize = Number.parseFloat(style?.fontSize) || fallbackFontSize;
797
+ const averageCharacterWidth = fontSize * 0.58;
798
+ if (this.measureContext === void 0) {
799
+ this.measureContext = null;
800
+ if (!/jsdom/i.test(view.navigator.userAgent)) {
801
+ try {
802
+ this.measureContext = this.select.ownerDocument.createElement("canvas").getContext("2d");
803
+ } catch {
804
+ this.measureContext = null;
805
+ }
806
+ }
807
+ }
808
+ const context = this.measureContext;
809
+ const font = style?.font || `${style?.fontWeight || 400} ${fontSize}px ${style?.fontFamily || "sans-serif"}`;
810
+ this.textWidthCache ||= /* @__PURE__ */ new Map();
811
+ if (this.textWidthCache.size > 5e3) this.textWidthCache.clear();
812
+ return (value) => {
813
+ const text = String(value ?? "");
814
+ if (!text) return 0;
815
+ if (!context) return Array.from(text).length * averageCharacterWidth;
816
+ const key = `${font}\0${text}`;
817
+ let width = this.textWidthCache.get(key);
818
+ if (width === void 0) {
819
+ context.font = font;
820
+ width = context.measureText(text).width;
821
+ this.textWidthCache.set(key, width);
822
+ }
823
+ return width;
824
+ };
825
+ }
826
+ // The natural width of the open menu: its widest row plus option padding,
827
+ // icons, and the scrollbar. Callers clamp it to the control and viewport.
828
+ // Item widths are cached, so repeat renders (each keystroke) only measure
829
+ // rows they have not seen, and only new rows trigger DOM layout reads.
830
+ measureDropdownContentWidth() {
831
+ this.itemWidthCache ||= /* @__PURE__ */ new WeakMap();
832
+ const renderedEntries = this.results.querySelectorAll("[data-tam-select-entry]");
833
+ let textWidth = null;
834
+ const measureText = (value) => {
835
+ textWidth ||= this.textMeasurer(renderedEntries[0] || this.results);
836
+ return textWidth(value);
837
+ };
838
+ let measuredWidth = 0;
839
+ let sawNewItem = this.dropdownContentWidth == null;
840
+ this.visibleItems.forEach((entry) => {
841
+ const item = entry.item;
842
+ let width = item ? this.itemWidthCache.get(item) : void 0;
843
+ if (width === void 0) {
844
+ const primaryWidth = item ? Math.max(measureText(item.label), measureText(item.detail)) : measureText(entry.label);
845
+ width = primaryWidth + 56 + (item?.image ? 40 : 0) + (item?.meta ? measureText(item.meta) + 20 : 0);
846
+ if (item) {
847
+ this.itemWidthCache.set(item, width);
848
+ sawNewItem = true;
849
+ }
850
+ }
851
+ measuredWidth = Math.max(measuredWidth, width);
852
+ });
853
+ if (sawNewItem) {
854
+ renderedEntries.forEach((entry) => {
855
+ let widestContent = 0;
856
+ entry.querySelectorAll("*").forEach((element) => {
857
+ if (element.childElementCount === 0) {
858
+ const visibleWidth = element.clientWidth || element.getBoundingClientRect().width || 0;
859
+ if (element.scrollWidth > visibleWidth + 1) {
860
+ widestContent = Math.max(widestContent, element.scrollWidth);
861
+ }
862
+ }
863
+ });
864
+ if (widestContent) measuredWidth = Math.max(measuredWidth, widestContent + 72);
865
+ });
866
+ }
867
+ const scrollbarWidth = Math.max(0, (this.results.offsetWidth || 0) - (this.results.clientWidth || 0));
868
+ return Math.ceil(measuredWidth + scrollbarWidth);
869
+ }
870
+ // width: "auto" sizes the closed control to its widest option, so picking
871
+ // a different option never resizes it, exactly like a native select.
872
+ applyFitWidth() {
873
+ if (!this.fitWidth) return;
874
+ const view = this.select.ownerDocument.defaultView;
875
+ const style = view.getComputedStyle(this.control);
876
+ const length = (value, fallback) => {
877
+ const number = Number.parseFloat(value);
878
+ return Number.isFinite(number) ? number : fallback;
879
+ };
880
+ const textWidth = this.textMeasurer(this.control, 14);
881
+ let widest = textWidth(this.options.placeholder);
882
+ let hasImage = false;
883
+ this.items.forEach((item) => {
884
+ widest = Math.max(widest, textWidth(item.label));
885
+ if (item.image) hasImage = true;
886
+ });
887
+ const gap = length(style.columnGap, 6);
888
+ const chrome = length(style.paddingLeft, 12) + length(style.paddingRight, 12) + length(style.borderLeftWidth, 1) + length(style.borderRightWidth, 1);
889
+ const chevron = this.chevron.getBoundingClientRect().width || 14;
890
+ const clear = this.options.clearable && this.canClear() ? (this.clearButton.getBoundingClientRect().width || 20) + gap : 0;
891
+ const tag = this.multiple ? 32 : 0;
892
+ const image = hasImage && !this.multiple ? 40 : 0;
893
+ const width = Math.ceil(widest + tag + image + chrome + gap + chevron + clear + 2);
894
+ this.wrapper.style.width = `${width}px`;
895
+ }
896
+ detectDirection() {
897
+ const selectDir = this.select.closest('[dir="rtl" i], [dir="ltr" i]')?.getAttribute("dir");
898
+ if (selectDir) return selectDir.toLowerCase();
899
+ const docDir = document.documentElement.getAttribute("dir") || document.body?.getAttribute("dir");
900
+ if (docDir) return docDir;
901
+ return "ltr";
902
+ }
903
+ findLabelElements() {
904
+ const labels = Array.from(document.querySelectorAll("label")).filter((label) => label.htmlFor === this.id || label.contains(this.select));
905
+ return [...new Set(labels)];
906
+ }
907
+ labelledBy() {
908
+ const nativeLabelledBy = this.select.getAttribute("aria-labelledby");
909
+ if (nativeLabelledBy) return nativeLabelledBy;
910
+ if (!this.labelElements.length) return null;
911
+ return this.labelElements.map((label) => {
912
+ if (!label.id) label.id = uid();
913
+ return label.id;
914
+ }).join(" ");
915
+ }
916
+ readNativeOptions() {
917
+ this.previousItemsByOption = new Map(this.items.map((item) => [item.option, item]));
918
+ const parsed = this.parseGroups();
919
+ this.previousItemsByOption = null;
920
+ this.groupTree = parsed.tree;
921
+ this.items = parsed.flat;
922
+ if (this.options.remoteUrl) {
923
+ const currentItems = new Map(this.items.map((item) => [item.option, item]));
924
+ this.remoteResults = this.remoteResults.map((item) => currentItems.get(item.option)).filter(Boolean);
925
+ this.updateVisibleItems(this.remoteResults);
926
+ } else {
927
+ this.filterLocal(false);
928
+ }
929
+ }
930
+ parseGroups() {
931
+ const tree = [];
932
+ const flat = [];
933
+ const children = Array.from(this.select.children);
934
+ for (const child of children) {
935
+ if (child.tagName === "OPTGROUP") {
936
+ const group = { label: child.label, items: [], entries: [] };
937
+ for (const option of child.querySelectorAll("option")) {
938
+ if (option.value === "") continue;
939
+ const item = this.buildItem(option);
940
+ item.group = group.label;
941
+ flat.push(item);
942
+ group.items.push(item);
943
+ group.entries.push({ type: "item", id: item.id, item, disabled: Boolean(item.disabled) });
944
+ }
945
+ if (group.items.length > 0) tree.push(group);
946
+ } else if (child.tagName === "OPTION" && child.value !== "") {
947
+ const item = this.buildItem(child);
948
+ flat.push(item);
949
+ tree.push({ type: "ungrouped", items: [item], entries: [{ type: "item", id: item.id, item, disabled: Boolean(item.disabled) }] });
950
+ }
951
+ }
952
+ return { tree, flat };
953
+ }
954
+ buildItem(option) {
955
+ const attributes = {
956
+ id: this.optionId(option),
957
+ value: option.value,
958
+ label: option.textContent.trim(),
959
+ detail: option.dataset.detail || null,
960
+ meta: option.dataset.meta || null,
961
+ image: option.dataset.image || null,
962
+ disabled: option.disabled || Boolean(option.closest("optgroup")?.disabled),
963
+ selected: option.selected,
964
+ option,
965
+ group: null
966
+ };
967
+ const existing = this.previousItemsByOption?.get(option);
968
+ return existing ? Object.assign(existing, attributes) : attributes;
969
+ }
970
+ selectedItems() {
971
+ return this.items.filter((item) => item.option ? item.option.selected : item.selected);
972
+ }
973
+ matchesLocalItem(item) {
974
+ if (typeof this.options.matcher === "function") return Boolean(this.options.matcher(item, this.query));
975
+ return Number.isFinite(this.searchScore(item));
976
+ }
977
+ filterLocal(render = true) {
978
+ let matches;
979
+ if (typeof this.options.matcher === "function") {
980
+ matches = this.items.filter((item) => this.matchesLocalItem(item));
981
+ } else {
982
+ matches = this.items.map((item, index) => ({ item, index, score: this.searchScore(item) })).filter((match) => Number.isFinite(match.score));
983
+ if (this.options.sortByRelevance && normalize(this.query)) {
984
+ matches.sort((left, right) => left.score - right.score || left.index - right.index);
985
+ }
986
+ matches = matches.map((match) => match.item);
987
+ }
988
+ matches = this.sortResults(matches);
989
+ this.updateVisibleItems(matches);
990
+ if (render) this.renderDropdown();
991
+ }
992
+ searchScore(item) {
993
+ const terms = normalize(this.query).split(/\s+/).filter(Boolean);
994
+ if (!terms.length) return 0;
995
+ const configuredFields = Array.isArray(this.options.searchFields) ? this.options.searchFields : ["label", "detail", "meta"];
996
+ const fields = configuredFields.map((name, index) => ({ text: normalize(item[name]), weight: index * 0.25 })).filter((field) => field.text);
997
+ let total = 0;
998
+ for (const term of terms) {
999
+ let best = Infinity;
1000
+ fields.forEach((field) => {
1001
+ const tokens = wordTokens(field.text);
1002
+ let score = Infinity;
1003
+ if (field.text === term) score = 0;
1004
+ else if (field.text.startsWith(term)) score = 0.5;
1005
+ else if (tokens.includes(term)) score = 1;
1006
+ else if (tokens.some((token) => token.startsWith(term))) score = 1.5;
1007
+ else {
1008
+ const position = field.text.indexOf(term);
1009
+ if (position >= 0) score = 2 + position / Math.max(field.text.length, 1);
1010
+ }
1011
+ if (!Number.isFinite(score) && this.options.fuzzySearch && term.length >= 3) {
1012
+ const maximum = term.length >= 6 ? 2 : 1;
1013
+ const distance = tokens.reduce((closest, token) => Math.min(closest, boundedDistance(term, token, maximum)), maximum + 1);
1014
+ if (distance <= maximum) score = 4 + distance;
1015
+ }
1016
+ best = Math.min(best, score + field.weight);
1017
+ });
1018
+ if (!Number.isFinite(best)) return Infinity;
1019
+ total += best;
1020
+ }
1021
+ return total;
1022
+ }
1023
+ updateVisibleItems(candidateItems, preserveActive = true) {
1024
+ this.matchedItems = candidateItems;
1025
+ candidateItems = candidateItems.filter((item) => !(this.options.hideSelected && item.selected));
1026
+ const previousId = preserveActive ? this.visibleItems[this.activeIndex]?.id : null;
1027
+ const hasGroups = this.groupTree.some((group) => group.type !== "ungrouped");
1028
+ let entries;
1029
+ if (!hasGroups) {
1030
+ entries = candidateItems.map((item) => ({ type: "item", id: item.id, item, disabled: Boolean(item.disabled) }));
1031
+ } else {
1032
+ const rank = new Map(candidateItems.map((item, index) => [item.id, index]));
1033
+ const byRank = (left, right) => rank.get(left.item.id) - rank.get(right.item.id);
1034
+ entries = [];
1035
+ for (const group of this.groupTree) {
1036
+ if (group.type === "ungrouped") {
1037
+ for (const entry of group.entries) {
1038
+ if (rank.has(entry.item.id)) {
1039
+ entries.push(entry);
1040
+ }
1041
+ }
1042
+ } else {
1043
+ const groupEntries = group.entries.filter((entry) => rank.has(entry.item.id)).sort(byRank);
1044
+ if (groupEntries.length > 0) {
1045
+ entries.push({ type: "group-header", id: `group-${group.label}`, group: group.label });
1046
+ entries.push(...groupEntries);
1047
+ }
1048
+ }
1049
+ }
1050
+ }
1051
+ const createEntry = this.createEntry();
1052
+ if (createEntry) entries.push(createEntry);
1053
+ this.visibleItems = entries;
1054
+ const preservedIndex = previousId ? entries.findIndex((entry) => entry.id === previousId && !entry.disabled) : -1;
1055
+ const selectedIndex = !this.multiple && !this.query.trim() ? entries.findIndex((entry) => entry.type === "item" && entry.item.selected && !entry.disabled) : -1;
1056
+ const firstIndex = entries.findIndex((entry) => !entry.disabled && entry.type !== "group-header");
1057
+ this.activeIndex = [preservedIndex, selectedIndex, firstIndex].find((index) => index >= 0) ?? -1;
1058
+ }
1059
+ createEntry() {
1060
+ const label = this.query.trim();
1061
+ if (!this.options.creatable || !label) return null;
1062
+ if (this.multiple && this.options.maximumSelectionLength > 0 && this.selectedItems().length >= this.options.maximumSelectionLength) return null;
1063
+ const value = typeof this.options.createValue === "function" ? this.options.createValue(label) : label;
1064
+ const normalizedValue = normalize(value);
1065
+ const normalizedLabel = normalize(label);
1066
+ const duplicate = this.items.some((item) => normalize(item.value) === normalizedValue || normalize(item.label) === normalizedLabel);
1067
+ if (!normalizedValue || duplicate) return null;
1068
+ return { type: "create", id: `${this.listboxId}-create`, label, value: String(value), disabled: false };
1069
+ }
1070
+ typeahead(char) {
1071
+ if (!this.opened) return;
1072
+ clearTimeout(this.typeaheadTimer);
1073
+ this.typeaheadBuffer += char;
1074
+ this.typeaheadTimer = setTimeout(() => {
1075
+ this.typeaheadBuffer = "";
1076
+ }, 500);
1077
+ const query = normalize(this.typeaheadBuffer);
1078
+ const offset = this.typeaheadBuffer.length > 1 ? 0 : 1;
1079
+ const startIndex = this.activeIndex >= 0 ? this.activeIndex + offset : 0;
1080
+ const candidates = [...this.visibleItems.slice(startIndex), ...this.visibleItems.slice(0, startIndex)];
1081
+ const match = candidates.find(
1082
+ (entry) => entry.type !== "group-header" && !entry.disabled && normalize(entry.item?.label ?? entry.label).startsWith(query)
1083
+ );
1084
+ if (match) {
1085
+ const index = this.visibleItems.indexOf(match);
1086
+ this.activeIndex = index;
1087
+ this.updateActiveOption();
1088
+ }
1089
+ }
1090
+ renderSelection() {
1091
+ const selected = this.selectedItems();
1092
+ this.values.replaceChildren();
1093
+ if (this.multiple) {
1094
+ selected.forEach((item) => this.values.append(this.makeTag(item)));
1095
+ } else if (selected.length) {
1096
+ this.values.append(this.makeItemContent(selected[0], true));
1097
+ } else {
1098
+ const placeholder = document.createElement("span");
1099
+ placeholder.className = this.classes.placeholder;
1100
+ placeholder.textContent = this.options.placeholder;
1101
+ this.values.append(placeholder);
1102
+ }
1103
+ const hasValue = selected.length > 0;
1104
+ const atLimit = this.multiple && this.options.maximumSelectionLength > 0 && selected.length >= this.options.maximumSelectionLength;
1105
+ this.selectionLimitReached = atLimit;
1106
+ this.values.classList.remove("hidden");
1107
+ setHidden(this.searchIcon, !this.searchable || !this.searchVisible);
1108
+ if (this.searchPanel) setHidden(this.searchPanel, !this.searchVisible);
1109
+ if (this.input) {
1110
+ toggleClasses(this.input, this.classes.inputClosed, false);
1111
+ this.input.placeholder = this.multiple && !hasValue ? this.options.placeholder : this.options.searchPlaceholder;
1112
+ this.input.disabled = this.select.disabled;
1113
+ }
1114
+ setHidden(this.clearButton, !this.options.clearable || !hasValue || !this.canClear() || this.select.disabled);
1115
+ this.updateSelectionToolbar();
1116
+ this.syncAria();
1117
+ }
1118
+ makeTag(item) {
1119
+ const tag = document.createElement("span");
1120
+ tag.className = this.classes.tag;
1121
+ tag.style.maxWidth = "100%";
1122
+ tag.style.minWidth = "0";
1123
+ tag.dataset.tagValue = item.value;
1124
+ const label = document.createElement("span");
1125
+ label.className = "max-w-48 truncate";
1126
+ label.style.minWidth = "0";
1127
+ label.style.overflow = "hidden";
1128
+ label.style.textOverflow = "ellipsis";
1129
+ label.style.whiteSpace = "nowrap";
1130
+ const template = this.renderTemplate(this.options.templateSelection, item, "selection");
1131
+ if (template) label.append(template);
1132
+ else label.textContent = item.label;
1133
+ const remove = document.createElement("button");
1134
+ remove.type = "button";
1135
+ remove.className = this.classes.tagRemove;
1136
+ remove.disabled = this.select.disabled;
1137
+ const removeLabel = typeof this.options.removeLabel === "function" ? this.options.removeLabel(item) : this.options.removeLabel;
1138
+ remove.setAttribute("aria-label", removeLabel);
1139
+ remove.innerHTML = ICONS.close;
1140
+ remove.addEventListener("click", (event) => {
1141
+ event.stopPropagation();
1142
+ this.deselect(item);
1143
+ });
1144
+ tag.append(label, remove);
1145
+ if (this.options.draggable && this.multiple && !this.select.disabled) {
1146
+ tag.setAttribute("draggable", "true");
1147
+ tag.style.cursor = "grab";
1148
+ tag.addEventListener("dragstart", (event) => this.onTagDragStart(event, item));
1149
+ tag.addEventListener("dragend", () => this.onTagDragEnd());
1150
+ tag.addEventListener("dragover", (event) => this.onTagDragOver(event));
1151
+ tag.addEventListener("dragenter", (event) => this.onTagDragEnter(event));
1152
+ tag.addEventListener("dragleave", (event) => this.onTagDragLeave(event));
1153
+ tag.addEventListener("drop", (event) => this.onTagDrop(event, item));
1154
+ }
1155
+ return tag;
1156
+ }
1157
+ onTagDragStart(event, item) {
1158
+ event.dataTransfer.effectAllowed = "move";
1159
+ event.dataTransfer.setData("text/plain", item.value);
1160
+ this.draggedItem = item;
1161
+ const scheduleFrame = window.requestAnimationFrame || ((callback) => window.setTimeout(callback, 0));
1162
+ scheduleFrame(() => {
1163
+ toggleClasses(event.target, this.classes.tagDragging, true);
1164
+ });
1165
+ }
1166
+ onTagDragEnd() {
1167
+ this.draggedItem = null;
1168
+ this.values.querySelectorAll("[data-tag-value]").forEach((el) => {
1169
+ toggleClasses(el, this.classes.tagDragging, false);
1170
+ toggleClasses(el, this.classes.tagDragOver, false);
1171
+ });
1172
+ }
1173
+ onTagDragOver(event) {
1174
+ event.preventDefault();
1175
+ event.dataTransfer.dropEffect = "move";
1176
+ }
1177
+ onTagDragEnter(event) {
1178
+ event.preventDefault();
1179
+ const tag = event.target.closest("[data-tag-value]");
1180
+ if (tag && tag.dataset.tagValue !== this.draggedItem?.value) {
1181
+ toggleClasses(tag, this.classes.tagDragOver, true);
1182
+ }
1183
+ }
1184
+ onTagDragLeave(event) {
1185
+ const tag = event.target.closest("[data-tag-value]");
1186
+ if (tag) toggleClasses(tag, this.classes.tagDragOver, false);
1187
+ }
1188
+ onTagDrop(event, targetItem) {
1189
+ event.preventDefault();
1190
+ const sourceItem = this.draggedItem;
1191
+ if (!sourceItem || sourceItem === targetItem) return;
1192
+ const sourceIndex = this.selectedItems().indexOf(sourceItem);
1193
+ const targetIndex = this.selectedItems().indexOf(targetItem);
1194
+ if (sourceIndex < 0 || targetIndex < 0) return;
1195
+ const option = sourceItem.option;
1196
+ const targetOption = targetItem.option;
1197
+ if (option && targetOption && option.parentElement === targetOption.parentElement) {
1198
+ if (sourceIndex < targetIndex) {
1199
+ targetOption.after(option);
1200
+ } else {
1201
+ targetOption.before(option);
1202
+ }
1203
+ }
1204
+ this.readNativeOptions();
1205
+ this.renderSelection();
1206
+ this.emit("tam-select:reorder", { value: this.value, items: this.selectedItems() });
1207
+ }
1208
+ renderDropdown() {
1209
+ if (!this.opened) return;
1210
+ this.updateSelectionToolbar();
1211
+ this.results.replaceChildren();
1212
+ this.results.setAttribute("aria-busy", String(this.loading));
1213
+ const remaining = Math.max(0, this.options.minQueryLength - this.query.trim().length);
1214
+ if (this.options.remoteUrl && remaining > 0) {
1215
+ const text = typeof this.options.inputTooShortText === "function" ? this.options.inputTooShortText(remaining) : this.options.inputTooShortText;
1216
+ this.renderMessage(text);
1217
+ this.updateStatus(text);
1218
+ return this.finishDropdownRender();
1219
+ }
1220
+ if (this.error && !this.errorAfterResults) {
1221
+ const error = document.createElement("div");
1222
+ error.className = this.classes.error;
1223
+ error.setAttribute("role", "alert");
1224
+ error.textContent = this.error;
1225
+ this.results.append(error);
1226
+ this.updateStatus(this.error);
1227
+ return this.finishDropdownRender();
1228
+ }
1229
+ if (this.loading && this.loadingPage === 1) {
1230
+ this.renderMessage(this.options.loadingText, true);
1231
+ this.updateStatus(this.options.loadingText);
1232
+ return this.finishDropdownRender();
1233
+ }
1234
+ const searching = Boolean(this.query.trim()) && Boolean(this.options.noResultsState);
1235
+ if (this.options.emptyState && !this.visibleItems.length && !this.loading && !searching) {
1236
+ const empty = document.createElement("div");
1237
+ empty.className = this.classes.message;
1238
+ if (typeof this.options.emptyState === "function") this.options.emptyState(empty);
1239
+ else empty.textContent = this.options.emptyState;
1240
+ this.results.append(empty);
1241
+ this.updateStatus("");
1242
+ return this.finishDropdownRender();
1243
+ }
1244
+ const largeList = this.options.virtualScroll || this.visibleItems.length > this.options.virtualScrollThreshold;
1245
+ this.wrapOptionText = this.options.wrapOptionText ?? !largeList;
1246
+ const shouldVirtual = !this.wrapOptionText && largeList;
1247
+ this.isVirtualScroll = shouldVirtual;
1248
+ if (shouldVirtual && this.visibleItems.length > 0) {
1249
+ this.renderVirtualDropdown();
1250
+ } else {
1251
+ this.renderStandardDropdown();
1252
+ }
1253
+ if (!this.visibleItems.length) {
1254
+ if (this.options.noResultsState) {
1255
+ const noResults = document.createElement("div");
1256
+ noResults.className = this.classes.message;
1257
+ if (typeof this.options.noResultsState === "function") this.options.noResultsState(noResults);
1258
+ else noResults.textContent = this.options.noResultsState;
1259
+ this.results.append(noResults);
1260
+ } else {
1261
+ this.renderMessage(this.options.noResultsText);
1262
+ }
1263
+ }
1264
+ if (this.error && this.errorAfterResults) {
1265
+ const error = document.createElement("div");
1266
+ error.className = this.classes.error;
1267
+ error.setAttribute("role", "alert");
1268
+ error.textContent = this.error;
1269
+ this.results.append(error);
1270
+ }
1271
+ if (this.loading && this.loadingPage > 1) this.renderMessage(this.options.loadingText, true);
1272
+ else if (this.hasMore) this.renderLoadMore();
1273
+ const resultCount = this.visibleItems.filter((entry) => entry.type === "item").length;
1274
+ const statusText = resultCount || this.visibleItems.length ? typeof this.options.resultsText === "function" ? this.options.resultsText(resultCount) : this.options.resultsText : this.options.noResultsText;
1275
+ this.updateStatus(statusText);
1276
+ this.finishDropdownRender();
1277
+ }
1278
+ finishDropdownRender() {
1279
+ this.syncActiveDescendant();
1280
+ this.dropdownWidthStale = true;
1281
+ if (this.portalDropdown) this.updateDropdownPosition();
1282
+ else this.updateInlineDropdownWidth();
1283
+ if (this.options.remoteUrl && this.hasMore && !this.loading && !this.error && this.results.clientHeight > 0 && this.results.scrollHeight <= this.results.clientHeight + 32) {
1284
+ const scheduleFrame = window.requestAnimationFrame || ((callback) => window.setTimeout(callback, 0));
1285
+ scheduleFrame(() => {
1286
+ if (this.opened && !this.destroyed) this.onScroll();
1287
+ });
1288
+ }
1289
+ }
1290
+ loadNextPage() {
1291
+ if (this.options.remoteUrl && this.hasMore && !this.loading) this.loadRemote(this.nextPage || this.page + 1, true);
1292
+ }
1293
+ renderLoadMore() {
1294
+ const button = document.createElement("button");
1295
+ button.type = "button";
1296
+ button.className = this.classes.loadMore;
1297
+ button.textContent = this.options.loadMoreText;
1298
+ button.dataset.tamSelectLoadMore = "";
1299
+ button.addEventListener("pointerdown", (event) => event.preventDefault());
1300
+ button.addEventListener("click", (event) => {
1301
+ event.stopPropagation();
1302
+ this.loadNextPage();
1303
+ });
1304
+ this.results.append(button);
1305
+ }
1306
+ renderStandardDropdown() {
1307
+ for (const entry of this.visibleItems) {
1308
+ if (entry.type === "group-header") {
1309
+ this.results.append(this.makeGroupHeader(entry));
1310
+ } else {
1311
+ const index = this.visibleItems.indexOf(entry);
1312
+ this.results.append(this.makeOption(entry, index));
1313
+ }
1314
+ }
1315
+ }
1316
+ renderVirtualDropdown(preservedScrollTop = null, container = this.results) {
1317
+ this.isVirtualScroll = true;
1318
+ const itemHeight = this.options.virtualItemHeight;
1319
+ const buffer = this.options.virtualScrollBuffer;
1320
+ const total = this.visibleItems.length;
1321
+ const totalHeight = total * itemHeight;
1322
+ const scrollTop = preservedScrollTop ?? this.results.scrollTop ?? 0;
1323
+ const viewportHeight = this.results.clientHeight || 288;
1324
+ const start = Math.max(0, Math.floor(scrollTop / itemHeight) - buffer);
1325
+ const end = Math.min(total, Math.ceil((scrollTop + viewportHeight) / itemHeight) + buffer);
1326
+ if (start > 0) {
1327
+ const topSpacer = document.createElement("div");
1328
+ topSpacer.style.height = `${start * itemHeight}px`;
1329
+ topSpacer.dataset.virtualSpacer = "top";
1330
+ container.append(topSpacer);
1331
+ }
1332
+ for (let i = start; i < end; i++) {
1333
+ const entry = this.visibleItems[i];
1334
+ if (entry.type === "group-header") {
1335
+ container.append(this.makeGroupHeader(entry));
1336
+ } else {
1337
+ container.append(this.makeOption(entry, i));
1338
+ }
1339
+ }
1340
+ if (end < total) {
1341
+ const bottomSpacer = document.createElement("div");
1342
+ bottomSpacer.style.height = `${(total - end) * itemHeight}px`;
1343
+ bottomSpacer.dataset.virtualSpacer = "bottom";
1344
+ container.append(bottomSpacer);
1345
+ }
1346
+ }
1347
+ rerenderVirtualItems(targetScrollTop = null) {
1348
+ if (!this.isVirtualScroll || !this.opened) return;
1349
+ const scrollTop = targetScrollTop ?? (this.results.scrollTop || 0);
1350
+ const fragment = document.createDocumentFragment();
1351
+ this.renderVirtualDropdown(scrollTop, fragment);
1352
+ this.results.replaceChildren(fragment);
1353
+ this.results.scrollTop = scrollTop;
1354
+ this.syncActiveDescendant();
1355
+ }
1356
+ makeGroupHeader(entry) {
1357
+ const header = document.createElement("div");
1358
+ header.className = this.classes.groupHeader;
1359
+ header.setAttribute("role", "presentation");
1360
+ header.textContent = entry.group;
1361
+ header.style.pointerEvents = "none";
1362
+ header.dataset.tamSelectGroup = entry.group;
1363
+ return header;
1364
+ }
1365
+ makeOption(entry, index) {
1366
+ const option = document.createElement("div");
1367
+ option.id = entry.id;
1368
+ option.dataset.tamSelectEntry = String(index);
1369
+ option.className = [
1370
+ this.classes.option,
1371
+ index === this.activeIndex && this.classes.optionActive,
1372
+ index !== this.activeIndex && entry.type === "item" && entry.item.selected && this.classes.optionSelected,
1373
+ entry.disabled && this.classes.optionDisabled
1374
+ ].filter(Boolean).join(" ");
1375
+ option.setAttribute("role", "option");
1376
+ option.setAttribute("aria-selected", String(Boolean(entry.type === "item" && entry.item.selected)));
1377
+ option.setAttribute("aria-disabled", String(Boolean(entry.disabled)));
1378
+ if (entry.type === "create") {
1379
+ option.textContent = typeof this.options.createText === "function" ? this.options.createText(entry.label) : this.options.createText;
1380
+ } else {
1381
+ const item = entry.item;
1382
+ option.dataset.value = item.value;
1383
+ option.append(this.makeItemContent(item));
1384
+ if (item.meta) {
1385
+ const meta = document.createElement("span");
1386
+ meta.className = this.classes.optionMeta;
1387
+ this.renderHighlightedText(meta, item.meta);
1388
+ option.append(meta);
1389
+ }
1390
+ if (item.selected) {
1391
+ const check = document.createElement("span");
1392
+ check.className = this.classes.optionCheck;
1393
+ check.innerHTML = ICONS.check;
1394
+ option.append(check);
1395
+ }
1396
+ }
1397
+ option.addEventListener("pointerenter", () => {
1398
+ if (entry.disabled || this.activeIndex === index) return;
1399
+ this.activeIndex = index;
1400
+ this.updateActiveOption(false);
1401
+ });
1402
+ option.addEventListener("click", () => this.activateEntry(entry));
1403
+ return option;
1404
+ }
1405
+ makeItemContent(item, selected = false) {
1406
+ const content = document.createElement("span");
1407
+ content.className = selected ? this.classes.selectionContent : this.classes.optionContent;
1408
+ content.style.minWidth = "0";
1409
+ content.style.maxWidth = "100%";
1410
+ const template = this.renderTemplate(selected ? this.options.templateSelection : this.options.templateResult, item, selected ? "selection" : "result");
1411
+ if (template) {
1412
+ content.append(template);
1413
+ return content;
1414
+ }
1415
+ if (selected) {
1416
+ const label2 = document.createElement("span");
1417
+ label2.className = this.classes.selectionLabel;
1418
+ label2.style.minWidth = "0";
1419
+ label2.style.overflow = "hidden";
1420
+ label2.style.textOverflow = "ellipsis";
1421
+ label2.style.whiteSpace = "nowrap";
1422
+ label2.textContent = item.label;
1423
+ if (this.options.optionTooltip) label2.title = item.label;
1424
+ content.append(label2);
1425
+ return content;
1426
+ }
1427
+ if (item.image) {
1428
+ const image = this.options.lazyLoadImages ? this.makeLazyImage(item) : document.createElement("img");
1429
+ if (!this.options.lazyLoadImages) {
1430
+ image.className = this.classes.optionImage;
1431
+ image.src = item.image;
1432
+ image.alt = "";
1433
+ image.loading = "lazy";
1434
+ }
1435
+ content.append(image);
1436
+ }
1437
+ const text = document.createElement("span");
1438
+ text.className = this.classes.optionText;
1439
+ text.style.minWidth = "0";
1440
+ text.style.overflow = "hidden";
1441
+ const label = document.createElement("span");
1442
+ label.className = [
1443
+ this.classes.optionLabel,
1444
+ this.wrapOptionText ? this.classes.optionLabelWrap : "truncate"
1445
+ ].filter(Boolean).join(" ");
1446
+ if (!this.wrapOptionText) {
1447
+ label.style.overflow = "hidden";
1448
+ label.style.textOverflow = "ellipsis";
1449
+ label.style.whiteSpace = "nowrap";
1450
+ }
1451
+ if (this.options.optionTooltip) label.title = item.label;
1452
+ this.renderHighlightedText(label, item.label);
1453
+ text.append(label);
1454
+ if (item.detail) {
1455
+ const detail = document.createElement("span");
1456
+ detail.className = [
1457
+ this.classes.optionDetail,
1458
+ this.wrapOptionText ? this.classes.optionDetailWrap : "truncate"
1459
+ ].filter(Boolean).join(" ");
1460
+ if (!this.wrapOptionText) {
1461
+ detail.style.overflow = "hidden";
1462
+ detail.style.textOverflow = "ellipsis";
1463
+ detail.style.whiteSpace = "nowrap";
1464
+ }
1465
+ if (this.options.optionTooltip) detail.title = item.detail;
1466
+ this.renderHighlightedText(detail, item.detail);
1467
+ text.append(detail);
1468
+ }
1469
+ content.append(text);
1470
+ return content;
1471
+ }
1472
+ renderTemplate(template, item, context) {
1473
+ if (typeof template !== "function") return null;
1474
+ const rendered = template(item, { tamSelect: this, context });
1475
+ if (rendered == null || rendered === false) return null;
1476
+ if (rendered instanceof Node) return rendered;
1477
+ const text = document.createElement("span");
1478
+ text.textContent = String(rendered);
1479
+ return text;
1480
+ }
1481
+ makeLazyImage(item) {
1482
+ const image = document.createElement("img");
1483
+ image.className = this.classes.optionImage;
1484
+ image.alt = "";
1485
+ image.dataset.lazySrc = item.image;
1486
+ if (this.lazyObserver) this.lazyObserver.observe(image);
1487
+ else image.src = item.image;
1488
+ return image;
1489
+ }
1490
+ initLazyObserver() {
1491
+ if (!this.options.lazyLoadImages) return;
1492
+ this.lazyObserver = new IntersectionObserver((entries) => {
1493
+ for (const entry of entries) {
1494
+ if (entry.isIntersecting) {
1495
+ const img = entry.target;
1496
+ if (img.dataset.lazySrc) {
1497
+ img.src = img.dataset.lazySrc;
1498
+ delete img.dataset.lazySrc;
1499
+ }
1500
+ this.lazyObserver.unobserve(img);
1501
+ }
1502
+ }
1503
+ }, { root: this.dropdown, rootMargin: "50px" });
1504
+ }
1505
+ renderHighlightedText(element, value) {
1506
+ const text = String(value ?? "");
1507
+ const terms = normalize(this.query).split(/\s+/).filter(Boolean);
1508
+ if (!this.options.highlightMatches || !terms.length) {
1509
+ element.textContent = text;
1510
+ return;
1511
+ }
1512
+ const positions = [];
1513
+ let offset = 0;
1514
+ let normalizedText = "";
1515
+ for (const character of text) {
1516
+ const start = offset;
1517
+ offset += character.length;
1518
+ const normalizedCharacter = fold(character);
1519
+ normalizedText += normalizedCharacter;
1520
+ for (let index = 0; index < normalizedCharacter.length; index += 1) positions.push({ start, end: offset });
1521
+ }
1522
+ const ranges = [];
1523
+ terms.forEach((term) => {
1524
+ let from = 0;
1525
+ while (from < normalizedText.length) {
1526
+ const index = normalizedText.indexOf(term, from);
1527
+ if (index < 0) break;
1528
+ const first = positions[index];
1529
+ const last = positions[index + term.length - 1];
1530
+ if (first && last) ranges.push([first.start, last.end]);
1531
+ from = index + Math.max(term.length, 1);
1532
+ }
1533
+ });
1534
+ if (!ranges.length) {
1535
+ element.textContent = text;
1536
+ return;
1537
+ }
1538
+ ranges.sort((left, right) => left[0] - right[0] || left[1] - right[1]);
1539
+ const merged = [];
1540
+ ranges.forEach((range) => {
1541
+ const previous = merged.at(-1);
1542
+ if (previous && range[0] <= previous[1]) previous[1] = Math.max(previous[1], range[1]);
1543
+ else merged.push([...range]);
1544
+ });
1545
+ let cursor = 0;
1546
+ merged.forEach(([start, end]) => {
1547
+ if (start > cursor) element.append(document.createTextNode(text.slice(cursor, start)));
1548
+ const mark = document.createElement("mark");
1549
+ mark.className = this.classes.highlight;
1550
+ mark.textContent = text.slice(start, end);
1551
+ element.append(mark);
1552
+ cursor = end;
1553
+ });
1554
+ if (cursor < text.length) element.append(document.createTextNode(text.slice(cursor)));
1555
+ }
1556
+ updateStatus(text) {
1557
+ this.status.textContent = String(text ?? "");
1558
+ }
1559
+ renderMessage(text, spinner = false) {
1560
+ if (this.options.loadingState && spinner) {
1561
+ const state = document.createElement("div");
1562
+ state.className = this.classes.message;
1563
+ state.setAttribute("role", "status");
1564
+ if (typeof this.options.loadingState === "function") this.options.loadingState(state);
1565
+ else state.textContent = this.options.loadingState;
1566
+ this.results.append(state);
1567
+ return;
1568
+ }
1569
+ const message = document.createElement("div");
1570
+ message.className = this.classes.message;
1571
+ message.setAttribute("role", "status");
1572
+ if (spinner) {
1573
+ const row = document.createElement("span");
1574
+ row.className = "inline-flex items-center gap-2";
1575
+ const icon = document.createElement("span");
1576
+ icon.className = this.classes.spinner;
1577
+ row.append(icon, document.createTextNode(text));
1578
+ message.append(row);
1579
+ } else {
1580
+ message.textContent = text;
1581
+ }
1582
+ this.results.append(message);
1583
+ }
1584
+ handleKeydown(event) {
1585
+ if (this.composing || event.isComposing || event.keyCode === 229) return;
1586
+ if (this.select.disabled || event.target.closest("button") && event.target !== this.trigger) return;
1587
+ if (["ArrowDown", "ArrowUp"].includes(event.key)) {
1588
+ event.preventDefault();
1589
+ const wasOpen = this.opened;
1590
+ this.open();
1591
+ if (wasOpen || event.key === "ArrowUp") this.moveActive(event.key === "ArrowDown" ? 1 : -1);
1592
+ else this.updateActiveOption();
1593
+ } else if (event.key === "Enter") {
1594
+ event.preventDefault();
1595
+ if (!this.opened) return this.open();
1596
+ this.activateEntry(this.visibleItems[this.activeIndex]);
1597
+ } else if (event.key === " " && event.target === this.trigger) {
1598
+ event.preventDefault();
1599
+ this.open();
1600
+ } else if (event.key === "Escape" && this.opened) {
1601
+ event.preventDefault();
1602
+ this.close();
1603
+ this.focusTarget.focus();
1604
+ } else if (event.key === "Backspace" && this.multiple && this.input && !this.input.value) {
1605
+ const last = this.selectedItems().at(-1);
1606
+ if (last) this.deselect(last);
1607
+ } else if (event.key === "Tab") {
1608
+ const action = this.selectionToolbar?.querySelector("button:not(:disabled)");
1609
+ if (this.opened && !event.shiftKey && action) {
1610
+ event.preventDefault();
1611
+ action.focus();
1612
+ return;
1613
+ }
1614
+ this.close(false);
1615
+ } else if (event.key === "Home" && this.opened) {
1616
+ event.preventDefault();
1617
+ this.moveActiveToFirst();
1618
+ } else if (event.key === "End" && this.opened) {
1619
+ event.preventDefault();
1620
+ this.moveActiveToLast();
1621
+ } else if (event.key === "a" && (event.ctrlKey || event.metaKey) && this.multiple && this.opened) {
1622
+ event.preventDefault();
1623
+ this.toggleAll();
1624
+ } else if (event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {
1625
+ if (this.opened) {
1626
+ if (event.target !== this.input) this.typeahead(event.key);
1627
+ } else if (this.input) {
1628
+ this.open(false);
1629
+ }
1630
+ }
1631
+ }
1632
+ moveActive(direction) {
1633
+ if (!this.visibleItems.length) return;
1634
+ let next = this.activeIndex;
1635
+ for (let count = 0; count < this.visibleItems.length; count += 1) {
1636
+ next = (next + direction + this.visibleItems.length) % this.visibleItems.length;
1637
+ const entry = this.visibleItems[next];
1638
+ if (entry.type !== "group-header" && !entry.disabled) {
1639
+ this.activeIndex = next;
1640
+ return this.updateActiveOption();
1641
+ }
1642
+ }
1643
+ }
1644
+ moveActiveToFirst() {
1645
+ if (!this.visibleItems.length) return;
1646
+ const first = this.visibleItems.findIndex((entry) => entry.type !== "group-header" && !entry.disabled);
1647
+ if (first >= 0) {
1648
+ this.activeIndex = first;
1649
+ this.updateActiveOption();
1650
+ }
1651
+ }
1652
+ moveActiveToLast() {
1653
+ if (!this.visibleItems.length) return;
1654
+ const last = this.visibleItems.findLastIndex((entry) => entry.type !== "group-header" && !entry.disabled);
1655
+ if (last >= 0) {
1656
+ this.activeIndex = last;
1657
+ this.updateActiveOption();
1658
+ }
1659
+ }
1660
+ toggleAll() {
1661
+ const matches = this.bulkCandidates();
1662
+ const atLimit = this.options.maximumSelectionLength > 0 && this.selectedItems().length >= this.options.maximumSelectionLength;
1663
+ if (matches.length && (matches.every((item) => item.selected) || atLimit && matches.some((item) => item.selected))) this.deselectAll();
1664
+ else this.selectAll();
1665
+ }
1666
+ bulkCandidates() {
1667
+ if (this.options.remoteUrl && (this.loading || this.error || this.query.trim().length < this.options.minQueryLength)) return [];
1668
+ return (this.matchedItems || []).filter((item) => !item.disabled);
1669
+ }
1670
+ /** Select loaded options matching the current search, up to the selection limit. */
1671
+ selectAll() {
1672
+ this.changeMatchingSelection(true);
1673
+ }
1674
+ /** Deselect loaded matches, including matches hidden by hideSelected. */
1675
+ deselectAll() {
1676
+ this.changeMatchingSelection(false);
1677
+ }
1678
+ changeMatchingSelection(selected) {
1679
+ if (!this.multiple || this.select.disabled || this.destroyed) return;
1680
+ const changed = [];
1681
+ let count = this.selectedItems().length;
1682
+ for (const item of this.bulkCandidates()) {
1683
+ if (item.selected === selected) continue;
1684
+ if (selected && this.options.maximumSelectionLength > 0 && count >= this.options.maximumSelectionLength) break;
1685
+ if (!this.emit(selected ? "tam-select:selecting" : "tam-select:unselecting", { item }, true)) continue;
1686
+ item.selected = selected;
1687
+ item.option.selected = selected;
1688
+ count += selected ? 1 : -1;
1689
+ changed.push(item);
1690
+ }
1691
+ if (!changed.length) return;
1692
+ this.commit();
1693
+ changed.forEach((item) => this.emit(selected ? "tam-select:select" : "tam-select:unselect", { item }));
1694
+ this.emit("tam-select:bulk-change", { action: selected ? "select" : "deselect", items: changed, value: this.value });
1695
+ this.updateDropdownPosition();
1696
+ }
1697
+ updateActiveOption(scroll = true) {
1698
+ this.results.querySelectorAll("[data-tam-select-entry]").forEach((option) => {
1699
+ const index = Number(option.dataset.tamSelectEntry);
1700
+ const entry = this.visibleItems[index];
1701
+ if (entry && entry.type !== "group-header") {
1702
+ const active = index === this.activeIndex;
1703
+ const selected = !active && entry.type === "item" && entry.item.selected;
1704
+ toggleClasses(option, this.classes.optionActive, false);
1705
+ toggleClasses(option, this.classes.optionSelected, false);
1706
+ if (active) toggleClasses(option, this.classes.optionActive, true);
1707
+ if (selected) toggleClasses(option, this.classes.optionSelected, true);
1708
+ }
1709
+ });
1710
+ this.syncActiveDescendant(scroll);
1711
+ }
1712
+ /** Whether the single-select search input inside the dropdown is in use. */
1713
+ searchPanelActive() {
1714
+ return Boolean(this.searchable && !this.multiple && this.input && this.searchVisible);
1715
+ }
1716
+ syncActiveDescendant(scroll = false) {
1717
+ const entry = this.visibleItems[this.activeIndex];
1718
+ let active = entry && this.results.querySelector(`[data-tam-select-entry="${this.activeIndex}"]`);
1719
+ if (scroll && entry && !active && this.isVirtualScroll && this.opened && !this.syncingVirtualWindow) {
1720
+ const itemHeight = this.options.virtualItemHeight;
1721
+ const viewportHeight = this.results.clientHeight || 288;
1722
+ const maxScrollTop = Math.max(0, this.visibleItems.length * itemHeight - viewportHeight);
1723
+ this.results.scrollTop = Math.min(maxScrollTop, Math.max(0, this.activeIndex * itemHeight - viewportHeight / 2));
1724
+ this.syncingVirtualWindow = true;
1725
+ try {
1726
+ this.rerenderVirtualItems(this.results.scrollTop);
1727
+ } finally {
1728
+ this.syncingVirtualWindow = false;
1729
+ }
1730
+ active = this.results.querySelector(`[data-tam-select-entry="${this.activeIndex}"]`);
1731
+ }
1732
+ const activeTarget = this.opened && this.searchPanelActive() ? this.input : this.focusTarget;
1733
+ this.focusTarget.removeAttribute("aria-activedescendant");
1734
+ if (this.input && this.input !== this.focusTarget) this.input.removeAttribute("aria-activedescendant");
1735
+ if (this.opened && active && !entry.disabled && entry.type !== "group-header") {
1736
+ activeTarget.setAttribute("aria-activedescendant", entry.id);
1737
+ if (scroll) active.scrollIntoView({ block: "nearest" });
1738
+ }
1739
+ }
1740
+ activateEntry(entry) {
1741
+ if (!entry || entry.disabled) return;
1742
+ if (entry.type === "create") this.createItem(entry.label, entry.value);
1743
+ else this.toggleItem(entry.item);
1744
+ }
1745
+ toggleItem(item) {
1746
+ if (item.disabled) return;
1747
+ if (this.multiple && item.selected) {
1748
+ this.deselect(item);
1749
+ } else if (this.multiple && this.options.maximumSelectionLength > 0) {
1750
+ const selectedCount = this.selectedItems().length;
1751
+ if (selectedCount >= this.options.maximumSelectionLength) {
1752
+ const text = typeof this.options.selectionLimitText === "function" ? this.options.selectionLimitText(this.options.maximumSelectionLength) : this.options.selectionLimitText;
1753
+ this.updateStatus(text);
1754
+ return;
1755
+ }
1756
+ this.selectValue(item);
1757
+ } else {
1758
+ this.selectValue(item);
1759
+ }
1760
+ }
1761
+ /** Select an item, or the first item with a value (creating it if needed). */
1762
+ selectValue(value) {
1763
+ if (this.select.disabled) return;
1764
+ const item = this.resolveItem(value);
1765
+ if (!item || item.disabled) return;
1766
+ const alreadySelected = item.option?.selected && (this.multiple || this.selectedItems().length === 1);
1767
+ if (alreadySelected) {
1768
+ if (this.options.closeAfterSelect) this.close();
1769
+ else this.resetQueryAfterSelection();
1770
+ return;
1771
+ }
1772
+ if (!this.emit("tam-select:selecting", { item }, true)) return;
1773
+ if (this.multiple && this.options.maximumSelectionLength > 0) {
1774
+ if (this.selectedItems().length >= this.options.maximumSelectionLength) {
1775
+ const text = typeof this.options.selectionLimitText === "function" ? this.options.selectionLimitText(this.options.maximumSelectionLength) : this.options.selectionLimitText;
1776
+ this.updateStatus(text);
1777
+ return;
1778
+ }
1779
+ }
1780
+ if (!this.multiple) Array.from(this.select.options).forEach((option) => {
1781
+ option.selected = false;
1782
+ });
1783
+ item.option.selected = true;
1784
+ item.selected = true;
1785
+ this.commit();
1786
+ this.emit("tam-select:select", { item });
1787
+ if (this.options.closeAfterSelect) this.close();
1788
+ else this.resetQueryAfterSelection();
1789
+ }
1790
+ resetQueryAfterSelection() {
1791
+ const hadQuery = Boolean(this.query);
1792
+ if (this.input) this.input.value = "";
1793
+ this.query = "";
1794
+ if (!this.options.remoteUrl) this.filterLocal();
1795
+ else if (hadQuery) this.scheduleRemote();
1796
+ else this.renderDropdown();
1797
+ }
1798
+ /** Deselect an item, or the first item with a value. */
1799
+ deselect(value) {
1800
+ if (this.select.disabled) return;
1801
+ const item = this.items.includes(value) ? value : this.items.find((entry) => String(entry.value) === String(value));
1802
+ if (!item) return;
1803
+ if (!this.emit("tam-select:unselecting", { item }, true)) return;
1804
+ item.selected = false;
1805
+ if (item.option) item.option.selected = false;
1806
+ this.commit();
1807
+ this.emit("tam-select:unselect", { item });
1808
+ }
1809
+ /** The empty option a single select falls back to when cleared. */
1810
+ emptyOption() {
1811
+ return Array.from(this.select.options).find((option) => option.value === "") || null;
1812
+ }
1813
+ canClear() {
1814
+ return this.multiple || Boolean(this.emptyOption());
1815
+ }
1816
+ clear() {
1817
+ if (this.select.disabled) return;
1818
+ const items = this.selectedItems();
1819
+ if (!items.length || !this.canClear() || !this.emit("tam-select:clearing", { items }, true)) return;
1820
+ Array.from(this.select.options).forEach((option) => {
1821
+ option.selected = false;
1822
+ });
1823
+ this.items.forEach((item) => {
1824
+ item.selected = false;
1825
+ });
1826
+ if (!this.multiple) this.emptyOption().selected = true;
1827
+ this.commit();
1828
+ this.emit("tam-select:clear", { items });
1829
+ }
1830
+ createItem(label, candidateValue = void 0) {
1831
+ if (this.select.disabled) return null;
1832
+ const value = candidateValue ?? (typeof this.options.createValue === "function" ? this.options.createValue(label) : label);
1833
+ const existing = this.items.find((item2) => normalize(item2.value) === normalize(value) || normalize(item2.label) === normalize(label));
1834
+ if (existing) {
1835
+ this.selectValue(existing.value);
1836
+ return existing;
1837
+ }
1838
+ if (this.multiple && this.options.maximumSelectionLength > 0 && this.selectedItems().length >= this.options.maximumSelectionLength) {
1839
+ const text = typeof this.options.selectionLimitText === "function" ? this.options.selectionLimitText(this.options.maximumSelectionLength) : this.options.selectionLimitText;
1840
+ this.updateStatus(text);
1841
+ return null;
1842
+ }
1843
+ if (!this.emit("tam-select:creating", { label, value: String(value) }, true)) return null;
1844
+ const item = this.addItem({ value, label, selected: false, created: true });
1845
+ this.selectValue(item.value);
1846
+ this.emit("tam-select:create", { item });
1847
+ return item;
1848
+ }
1849
+ addItem(raw) {
1850
+ const rawValue = raw.value ?? raw[this.options.valueField];
1851
+ const value = String(rawValue ?? "");
1852
+ const existing = this.items.find((item2) => String(item2.value) === value);
1853
+ const label = String(raw.label ?? raw[this.options.labelField] ?? value);
1854
+ const image = raw.image ?? raw[this.options.imageField];
1855
+ if (existing) {
1856
+ existing.value = value;
1857
+ existing.label = label;
1858
+ existing.detail = hasOwn(raw, "detail") ? raw.detail : existing.detail;
1859
+ existing.meta = hasOwn(raw, "meta") ? raw.meta : existing.meta;
1860
+ existing.image = image ?? existing.image;
1861
+ if (hasOwn(raw, "disabled")) existing.disabled = Boolean(raw.disabled);
1862
+ this.syncNativeOption(existing);
1863
+ return existing;
1864
+ }
1865
+ const option = new Option(label, value, Boolean(raw.selected), Boolean(raw.selected));
1866
+ option.dataset.tamSelectGenerated = "";
1867
+ this.select.add(option);
1868
+ const item = {
1869
+ ...raw,
1870
+ id: this.optionId(option),
1871
+ value,
1872
+ label,
1873
+ detail: raw.detail ?? null,
1874
+ meta: raw.meta ?? null,
1875
+ image: image == null ? null : String(image),
1876
+ option,
1877
+ selected: option.selected,
1878
+ disabled: Boolean(raw.disabled)
1879
+ };
1880
+ this.syncNativeOption(item);
1881
+ this.items.push(item);
1882
+ return item;
1883
+ }
1884
+ upsertRemoteItem(raw) {
1885
+ const value = String(raw?.[this.options.valueField] ?? raw?.value ?? "");
1886
+ const label = String(raw?.[this.options.labelField] ?? raw?.label ?? value);
1887
+ const image = raw?.[this.options.imageField] ?? raw?.image ?? null;
1888
+ const item = this.addItem({
1889
+ value,
1890
+ label,
1891
+ detail: raw?.detail ?? null,
1892
+ meta: raw?.meta ?? null,
1893
+ image,
1894
+ disabled: Boolean(raw?.disabled)
1895
+ });
1896
+ item.detail = raw?.detail ?? null;
1897
+ item.meta = raw?.meta ?? null;
1898
+ item.image = image == null ? null : String(image);
1899
+ item.disabled = Boolean(raw?.disabled);
1900
+ this.syncNativeOption(item);
1901
+ return item;
1902
+ }
1903
+ syncNativeOption(item) {
1904
+ if (!item.option) return;
1905
+ item.option.value = item.value;
1906
+ item.option.textContent = item.label;
1907
+ item.option.disabled = Boolean(item.disabled);
1908
+ this.setDataAttribute(item.option, "detail", item.detail);
1909
+ this.setDataAttribute(item.option, "meta", item.meta);
1910
+ this.setDataAttribute(item.option, "image", item.image);
1911
+ }
1912
+ setDataAttribute(option, name, value) {
1913
+ if (value == null || value === "") delete option.dataset[name];
1914
+ else option.dataset[name] = String(value);
1915
+ }
1916
+ optionId(option) {
1917
+ if (!this.optionIds.has(option)) {
1918
+ this.optionIdSequence += 1;
1919
+ this.optionIds.set(option, `${this.listboxId}-option-${this.optionIdSequence}`);
1920
+ }
1921
+ return this.optionIds.get(option);
1922
+ }
1923
+ // Accepts an item from this instance, a copy or stale item (matched by its
1924
+ // value), or a plain value.
1925
+ resolveItem(value) {
1926
+ if (this.items.includes(value)) return value;
1927
+ if (value && typeof value === "object") {
1928
+ if (value.value == null) return null;
1929
+ return this.items.find((item) => String(item.value) === String(value.value)) || this.addItem({ value: value.value, label: value.label ?? value.value });
1930
+ }
1931
+ return this.ensureNativeOption(value);
1932
+ }
1933
+ ensureNativeOption(value) {
1934
+ return this.items.find((item) => String(item.value) === String(value)) || this.addItem({ value, label: value });
1935
+ }
1936
+ commit() {
1937
+ if (this.select.checkValidity()) this.invalidFromEvent = false;
1938
+ this.readNativeOptions();
1939
+ this.renderSelection();
1940
+ this.renderDropdown();
1941
+ this.syncAria();
1942
+ this.select.dispatchEvent(new Event("change", { bubbles: true }));
1943
+ this.emit("tam-select:change", { value: this.value, items: this.selectedItems() });
1944
+ }
1945
+ get value() {
1946
+ return this.multiple ? this.selectedItems().map((item) => item.value) : this.selectedItems()[0]?.value ?? "";
1947
+ }
1948
+ setValue(value) {
1949
+ const rawValues = value == null ? [] : Array.isArray(value) ? value : [value];
1950
+ const values = new Set(rawValues.map(String));
1951
+ this.items.forEach((item) => {
1952
+ item.selected = values.has(String(item.value));
1953
+ if (item.option) item.option.selected = item.selected;
1954
+ });
1955
+ this.commit();
1956
+ }
1957
+ open(loadRemote = true) {
1958
+ if (this.opened || this.select.disabled) return;
1959
+ if (!this.emit("tam-select:opening", {}, true)) return;
1960
+ clearTimeout(this.closeTimer);
1961
+ if (this.closeTransitionHandler) {
1962
+ this.dropdown.removeEventListener("transitionend", this.closeTransitionHandler);
1963
+ this.closeTransitionHandler = null;
1964
+ }
1965
+ this.opened = true;
1966
+ this.dropdownContentWidth = null;
1967
+ if (this.options.minimumResultsForSearch > 0) {
1968
+ const totalOptions = this.options.remoteUrl ? Infinity : this.items.length;
1969
+ this.searchVisible = totalOptions >= this.options.minimumResultsForSearch;
1970
+ this.renderSelection();
1971
+ }
1972
+ if (this.portalDropdown) this.dropdown.style.visibility = "hidden";
1973
+ setHidden(this.dropdown, false);
1974
+ if (this.animationsEnabled) {
1975
+ toggleClasses(this.dropdown, this.classes.dropdownClosed, false);
1976
+ toggleClasses(this.dropdown, this.classes.dropdownOpen, true);
1977
+ }
1978
+ this.focusTarget.setAttribute("aria-expanded", "true");
1979
+ toggleClasses(this.control, this.classes.controlOpen, true);
1980
+ toggleClasses(this.chevron, this.classes.chevronOpen, true);
1981
+ this.renderSelection();
1982
+ if (this.options.remoteUrl && loadRemote) this.startRemoteSearch(false);
1983
+ else this.renderDropdown();
1984
+ if (this.portalDropdown) {
1985
+ this.updateDropdownPosition();
1986
+ this.dropdown.style.visibility = "";
1987
+ const scheduleFrame = window.requestAnimationFrame || ((callback) => window.setTimeout(callback, 0));
1988
+ scheduleFrame(() => {
1989
+ if (this.opened) this.updateDropdownPosition();
1990
+ });
1991
+ }
1992
+ if (this.isVirtualScroll) this.syncActiveDescendant(true);
1993
+ const openTarget = this.searchPanelActive() ? this.input : this.focusTarget;
1994
+ openTarget.focus({ preventScroll: true });
1995
+ this.emit("tam-select:open");
1996
+ }
1997
+ close(restoreFocus = true) {
1998
+ if (!this.opened) return;
1999
+ if (!this.emit("tam-select:closing", {}, true)) return;
2000
+ this.opened = false;
2001
+ if (this.options.selectOnClose && this.activeIndex >= 0) {
2002
+ const entry = this.visibleItems[this.activeIndex];
2003
+ const alreadySelected = entry?.type === "item" && entry.item.option?.selected;
2004
+ if (entry && entry.type !== "group-header" && !entry.disabled && !alreadySelected) this.activateEntry(entry);
2005
+ }
2006
+ this.cancelRemoteWork();
2007
+ this.focusTarget.setAttribute("aria-expanded", "false");
2008
+ toggleClasses(this.control, this.classes.controlOpen, false);
2009
+ this.focusTarget.removeAttribute("aria-activedescendant");
2010
+ if (this.input && this.input !== this.focusTarget) this.input.removeAttribute("aria-activedescendant");
2011
+ toggleClasses(this.chevron, this.classes.chevronOpen, false);
2012
+ if (this.input) this.input.value = "";
2013
+ this.query = "";
2014
+ this.loading = false;
2015
+ this.loadingPage = null;
2016
+ this.error = null;
2017
+ this.hasMore = false;
2018
+ this.nextPage = null;
2019
+ this.isVirtualScroll = false;
2020
+ this.updateStatus("");
2021
+ if (this.options.remoteUrl) {
2022
+ this.remoteResults = [];
2023
+ this.updateVisibleItems([]);
2024
+ } else {
2025
+ this.filterLocal(false);
2026
+ if (!this.multiple) this.updateVisibleItems(this.matchedItems, false);
2027
+ }
2028
+ this.renderSelection();
2029
+ if (restoreFocus && !this.multiple && this.input && document.activeElement === this.input) {
2030
+ this.focusTarget.focus({ preventScroll: true });
2031
+ }
2032
+ if (this.animationsEnabled) {
2033
+ toggleClasses(this.dropdown, this.classes.dropdownOpen, false);
2034
+ toggleClasses(this.dropdown, this.classes.dropdownClosed, true);
2035
+ const hide = () => {
2036
+ if (this.opened) return;
2037
+ setHidden(this.dropdown, true);
2038
+ this.dropdown.removeEventListener("transitionend", hide);
2039
+ if (this.closeTransitionHandler === hide) this.closeTransitionHandler = null;
2040
+ };
2041
+ this.closeTransitionHandler = hide;
2042
+ this.dropdown.addEventListener("transitionend", hide, { once: true });
2043
+ this.closeTimer = setTimeout(hide, this.options.animationDuration + 50);
2044
+ } else {
2045
+ setHidden(this.dropdown, true);
2046
+ }
2047
+ this.emit("tam-select:close");
2048
+ }
2049
+ focus() {
2050
+ if (!this.select.disabled) this.focusTarget.focus();
2051
+ }
2052
+ blur() {
2053
+ this.focusTarget.blur();
2054
+ }
2055
+ scheduleRemote() {
2056
+ this.startRemoteSearch(true);
2057
+ }
2058
+ startRemoteSearch(debounced) {
2059
+ clearTimeout(this.remoteTimer);
2060
+ this.cancelActiveRequest();
2061
+ this.loading = false;
2062
+ this.loadingPage = null;
2063
+ this.error = null;
2064
+ this.page = 0;
2065
+ this.nextPage = null;
2066
+ this.hasMore = false;
2067
+ this.remoteResults = [];
2068
+ this.updateVisibleItems([]);
2069
+ if (this.query.trim().length < this.options.minQueryLength) return this.renderDropdown();
2070
+ if (!debounced || this.options.debounce <= 0) return this.loadRemote(1, false);
2071
+ this.loading = true;
2072
+ this.loadingPage = 1;
2073
+ this.renderDropdown();
2074
+ this.remoteTimer = setTimeout(() => {
2075
+ this.remoteTimer = null;
2076
+ this.loadRemote(1, false);
2077
+ }, this.options.debounce);
2078
+ }
2079
+ cancelActiveRequest() {
2080
+ if (!this.activeRequest) return;
2081
+ this.activeRequest.controller.abort();
2082
+ this.activeRequest = null;
2083
+ }
2084
+ cancelRemoteWork() {
2085
+ clearTimeout(this.remoteTimer);
2086
+ this.remoteTimer = null;
2087
+ this.cancelActiveRequest();
2088
+ }
2089
+ async loadRemote(page = 1, append = false) {
2090
+ if (append && (this.loading || !this.hasMore || page <= this.page)) return;
2091
+ if (this.query.trim().length < this.options.minQueryLength) return;
2092
+ clearTimeout(this.remoteTimer);
2093
+ this.remoteTimer = null;
2094
+ if (!append) {
2095
+ this.cancelActiveRequest();
2096
+ this.remoteResults = [];
2097
+ this.updateVisibleItems([]);
2098
+ }
2099
+ const requestId = ++this.requestSequence;
2100
+ const controller = new AbortController();
2101
+ const request = { id: requestId, controller, page, query: this.query };
2102
+ this.activeRequest = request;
2103
+ this.loading = true;
2104
+ this.loadingPage = page;
2105
+ this.error = null;
2106
+ this.errorAfterResults = false;
2107
+ this.renderDropdown();
2108
+ try {
2109
+ const url = new URL(this.options.remoteUrl, window.location.origin);
2110
+ url.searchParams.set(this.options.queryParam, request.query);
2111
+ url.searchParams.set(this.options.pageParam, page);
2112
+ const extraParams = typeof this.options.remoteParams === "function" ? this.options.remoteParams({ query: request.query, page, tamSelect: this }) : this.options.remoteParams;
2113
+ Object.entries(extraParams || {}).forEach(([key, value]) => {
2114
+ if (value != null) url.searchParams.set(key, String(value));
2115
+ });
2116
+ const cacheKey = url.toString();
2117
+ let data = this.options.cacheRemote ? this.remoteCache.get(cacheKey) : null;
2118
+ if (!data) {
2119
+ const transportOptions = {
2120
+ url,
2121
+ query: request.query,
2122
+ page,
2123
+ headers: { Accept: "application/json", ...this.options.headers },
2124
+ signal: controller.signal,
2125
+ tamSelect: this
2126
+ };
2127
+ const result = typeof this.options.transport === "function" ? await this.options.transport(transportOptions) : await fetch(url, { headers: transportOptions.headers, signal: controller.signal });
2128
+ if (result && typeof result.json === "function") {
2129
+ if (!result.ok) throw new Error(`Request failed (${result.status})`);
2130
+ data = await result.json();
2131
+ } else {
2132
+ data = result;
2133
+ }
2134
+ if (this.options.cacheRemote) this.remoteCache.set(cacheKey, data);
2135
+ }
2136
+ if (typeof this.options.processResults === "function") {
2137
+ data = await this.options.processResults(data, { query: request.query, page, tamSelect: this });
2138
+ }
2139
+ if (this.activeRequest?.id !== requestId) return;
2140
+ const rawItems = this.getPath(data, this.options.itemsPath);
2141
+ const responseItems = (Array.isArray(rawItems) ? rawItems : []).map((raw) => this.upsertRemoteItem(raw));
2142
+ const combinedItems = append ? [...this.remoteResults, ...responseItems] : responseItems;
2143
+ this.remoteResults = this.deduplicateByValue(combinedItems);
2144
+ this.page = page;
2145
+ const pagination = this.getPath(data, this.options.paginationPath) || {};
2146
+ this.nextPage = pagination.next_page ?? null;
2147
+ this.hasMore = Boolean(this.nextPage || pagination.has_more || pagination.page && pagination.total_pages && pagination.page < pagination.total_pages);
2148
+ this.updateVisibleItems(this.remoteResults);
2149
+ this.emit("tam-select:load", { items: this.deduplicateByValue(responseItems), pagination });
2150
+ } catch (error) {
2151
+ if (this.activeRequest?.id !== requestId) return;
2152
+ if (error.name !== "AbortError") {
2153
+ this.error = error.message || "Unable to load options";
2154
+ this.errorAfterResults = append && this.remoteResults.length > 0;
2155
+ this.emit("tam-select:error", { error });
2156
+ }
2157
+ } finally {
2158
+ if (this.activeRequest?.id === requestId) {
2159
+ this.activeRequest = null;
2160
+ this.loading = false;
2161
+ this.loadingPage = null;
2162
+ this.renderDropdown();
2163
+ }
2164
+ }
2165
+ }
2166
+ deduplicateByValue(items) {
2167
+ const seen = /* @__PURE__ */ new Set();
2168
+ return items.filter((item) => {
2169
+ const value = String(item.value);
2170
+ if (seen.has(value)) return false;
2171
+ seen.add(value);
2172
+ return true;
2173
+ });
2174
+ }
2175
+ getPath(object, path) {
2176
+ return String(path).split(".").reduce((value, key) => value?.[key], object);
2177
+ }
2178
+ syncAria() {
2179
+ const labelledBy = this.labelledBy();
2180
+ if (labelledBy) {
2181
+ const valueReference = this.trigger ? ` ${this.valuesId}` : "";
2182
+ this.focusTarget.setAttribute("aria-labelledby", `${labelledBy}${valueReference}`);
2183
+ this.focusTarget.removeAttribute("aria-label");
2184
+ } else {
2185
+ const ariaLabel = this.select.getAttribute("aria-label") || this.options.placeholder;
2186
+ this.focusTarget.setAttribute("aria-label", ariaLabel);
2187
+ if (this.trigger) this.focusTarget.setAttribute("aria-labelledby", this.valuesId);
2188
+ else this.focusTarget.removeAttribute("aria-labelledby");
2189
+ }
2190
+ const describedBy = this.select.getAttribute("aria-describedby");
2191
+ if (describedBy) this.focusTarget.setAttribute("aria-describedby", describedBy);
2192
+ else this.focusTarget.removeAttribute("aria-describedby");
2193
+ this.focusTarget.setAttribute("aria-required", String(Boolean(this.select.required)));
2194
+ this.focusTarget.setAttribute("aria-disabled", String(Boolean(this.select.disabled)));
2195
+ const nativeInvalid = this.select.getAttribute("aria-invalid");
2196
+ const invalid = this.invalidFromEvent || nativeInvalid === "true";
2197
+ if (this.invalidFromEvent) this.focusTarget.setAttribute("aria-invalid", "true");
2198
+ else if (nativeInvalid != null) this.focusTarget.setAttribute("aria-invalid", nativeInvalid);
2199
+ else this.focusTarget.removeAttribute("aria-invalid");
2200
+ toggleClasses(this.control, this.classes.controlInvalid, invalid);
2201
+ }
2202
+ applyDisabled() {
2203
+ if (this.select.disabled && this.opened) this.close(false);
2204
+ toggleClasses(this.control, this.classes.controlDisabled, this.select.disabled);
2205
+ this.focusTarget.disabled = this.select.disabled;
2206
+ this.clearButton.disabled = this.select.disabled;
2207
+ this.syncAria();
2208
+ }
2209
+ refresh() {
2210
+ this.readNativeOptions();
2211
+ this.applyDisabled();
2212
+ this.renderSelection();
2213
+ this.applyFitWidth();
2214
+ this.renderDropdown();
2215
+ }
2216
+ emit(name, detail = {}, cancelable = false) {
2217
+ return this.select.dispatchEvent(new CustomEvent(name, {
2218
+ bubbles: true,
2219
+ cancelable,
2220
+ detail: { tamSelect: this, ...detail }
2221
+ }));
2222
+ }
2223
+ clearRemoteCache() {
2224
+ this.remoteCache.clear();
2225
+ }
2226
+ tokenizeInput() {
2227
+ if (!this.input) return;
2228
+ const value = this.input.value;
2229
+ const separators = this.options.tokenSeparators;
2230
+ let hasToken = false;
2231
+ for (const sep of separators) {
2232
+ if (value.includes(sep)) {
2233
+ hasToken = true;
2234
+ break;
2235
+ }
2236
+ }
2237
+ if (!hasToken) return;
2238
+ const tokens = value.split(new RegExp(separators.map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|"))).filter(Boolean);
2239
+ tokens.forEach((token) => {
2240
+ const trimmed = token.trim();
2241
+ if (trimmed) this.createItem(trimmed);
2242
+ });
2243
+ this.input.value = "";
2244
+ this.query = "";
2245
+ this.filterLocal();
2246
+ }
2247
+ sortResults(items) {
2248
+ if (typeof this.options.sorter === "function") {
2249
+ return this.options.sorter(items);
2250
+ }
2251
+ return items;
2252
+ }
2253
+ addData(raw) {
2254
+ const items = Array.isArray(raw) ? raw : [raw];
2255
+ items.forEach((data) => this.addItem(data));
2256
+ this.readNativeOptions();
2257
+ this.renderSelection();
2258
+ if (this.opened) this.renderDropdown();
2259
+ this.emit("tam-select:data:add", { items: items.map((d) => this.items.find((i) => String(i.value) === String(d.value ?? d[this.options.valueField]))) });
2260
+ }
2261
+ removeData(values) {
2262
+ const rawValues = Array.isArray(values) ? values : [values];
2263
+ const removed = [];
2264
+ rawValues.forEach((value) => {
2265
+ const item = this.items.find((i) => String(i.value) === String(value));
2266
+ if (item) {
2267
+ if (item.option) item.option.remove();
2268
+ this.items = this.items.filter((i) => i !== item);
2269
+ removed.push(item);
2270
+ }
2271
+ });
2272
+ if (removed.length) {
2273
+ this.readNativeOptions();
2274
+ this.renderSelection();
2275
+ if (this.opened) this.renderDropdown();
2276
+ this.emit("tam-select:data:remove", { items: removed });
2277
+ }
2278
+ }
2279
+ destroy() {
2280
+ if (this.destroyed) return;
2281
+ this.destroyed = true;
2282
+ this.cancelRemoteWork();
2283
+ clearTimeout(this.closeTimer);
2284
+ if (this.closeTransitionHandler) {
2285
+ this.dropdown.removeEventListener("transitionend", this.closeTransitionHandler);
2286
+ this.closeTransitionHandler = null;
2287
+ }
2288
+ clearTimeout(this.typeaheadTimer);
2289
+ if (this.lazyObserver) {
2290
+ this.lazyObserver.disconnect();
2291
+ this.lazyObserver = null;
2292
+ }
2293
+ document.removeEventListener("pointerdown", this.onOutside);
2294
+ window.removeEventListener("resize", this.onViewportChange);
2295
+ window.removeEventListener("scroll", this.onViewportChange, true);
2296
+ window.visualViewport?.removeEventListener("resize", this.onViewportChange);
2297
+ window.visualViewport?.removeEventListener("scroll", this.onViewportChange);
2298
+ this.select.form?.removeEventListener("reset", this.onFormReset);
2299
+ this.mutationObserver?.disconnect();
2300
+ this.select.removeEventListener("change", this.onNativeChange);
2301
+ this.select.removeEventListener("invalid", this.onNativeInvalid);
2302
+ this.focusTarget.removeEventListener("keydown", this.onKeydown);
2303
+ if (this.input && this.input !== this.focusTarget) this.input.removeEventListener("keydown", this.onKeydown);
2304
+ if (this.input) {
2305
+ this.input.removeEventListener("input", this.onInput);
2306
+ this.input.removeEventListener("compositionstart", this.onCompositionStart);
2307
+ this.input.removeEventListener("compositionend", this.onCompositionEnd);
2308
+ }
2309
+ this.results.removeEventListener("scroll", this.onScroll);
2310
+ this.labelElements.forEach((label) => label.removeEventListener("click", this.onLabelClick));
2311
+ this.wrapper.remove();
2312
+ if (this.portalDropdown) this.dropdown.remove();
2313
+ if (!this.hadSrOnlyClass) this.select.classList.remove("sr-only");
2314
+ if (this.originalTabIndex === null) this.select.removeAttribute("tabindex");
2315
+ else this.select.setAttribute("tabindex", this.originalTabIndex);
2316
+ if (this.originalAriaHidden === null) this.select.removeAttribute("aria-hidden");
2317
+ else this.select.setAttribute("aria-hidden", this.originalAriaHidden);
2318
+ if (this.originalId === null) this.select.removeAttribute("id");
2319
+ delete this.select.dataset.tamSelectState;
2320
+ if (_TamSelect.instances.get(this.select) === this) _TamSelect.instances.delete(this.select);
2321
+ }
2322
+ };
2323
+ var tam_select_default = TamSelect;
2324
+ export {
2325
+ ANIMATION_PRESETS,
2326
+ TamSelect,
2327
+ tam_select_default as default
2328
+ };