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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +164 -0
- data/README.md +325 -340
- data/app/assets/tailwind/tam_select/engine.css +4 -0
- data/config/importmap.rb +4 -0
- data/examples/playground.html +740 -0
- data/examples/tam-select.bundle.js +2328 -0
- data/lib/generators/tam_select/install_generator.rb +105 -37
- data/lib/generators/tam_select/legacy_copies.json +48 -0
- data/lib/generators/tam_select/templates/tam_select.rb +8 -0
- data/lib/generators/tam_select/templates/tam_select_controller.js +3 -26
- data/lib/generators/tam_select/update_generator.rb +13 -0
- data/lib/tam_select/default_select.rb +108 -0
- data/lib/tam_select/engine.rb +50 -0
- data/lib/tam_select/version.rb +1 -1
- data/lib/tam_select.rb +1 -0
- data/package.json +21 -5
- data/rails/app/controllers/concerns/tam_select_paginatable.rb +9 -3
- data/rails/app/helpers/tam_select_helper.rb +13 -2
- data/rails/app/inputs/tam_select_input.rb +19 -4
- data/rails/app/javascript/controllers/tam_select_controller.d.ts +21 -0
- data/rails/app/javascript/controllers/tam_select_controller.js +55 -2
- data/src/tam-select.d.ts +347 -0
- data/src/tam-select.js +1785 -146
- metadata +18 -7
- data/lib/generators/tam_select/templates/tam_select_helper.rb +0 -17
- data/lib/generators/tam_select/templates/tam_select_input.rb +0 -30
- data/lib/generators/tam_select/templates/tam_select_paginatable.rb +0 -32
- /data/{lib/generators/tam_select/templates → rails/app/controllers/concerns}/tam_select_remote.rb +0 -0
data/src/tam-select.js
CHANGED
|
@@ -1,33 +1,106 @@
|
|
|
1
|
+
const THEME_CLASSES = {
|
|
2
|
+
select2: {
|
|
3
|
+
wrapper: "tam-select relative w-full text-sm text-gray-700",
|
|
4
|
+
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",
|
|
5
|
+
controlMultiple: "h-auto min-h-11 py-2",
|
|
6
|
+
controlOpen: "border-blue-500 outline-2 outline-blue-500/20 outline-offset-2",
|
|
7
|
+
controlInvalid: "border-red-500 outline-2 outline-red-500/20 outline-offset-2",
|
|
8
|
+
controlDisabled: "cursor-not-allowed bg-gray-50 opacity-60",
|
|
9
|
+
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",
|
|
10
|
+
inputClosed: "absolute inset-0 z-[1] h-full w-full cursor-pointer opacity-0",
|
|
11
|
+
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",
|
|
12
|
+
searchIcon: "size-3.5 shrink-0 text-gray-400",
|
|
13
|
+
placeholder: "pointer-events-none min-w-0 flex-1 truncate font-normal text-gray-400",
|
|
14
|
+
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",
|
|
15
|
+
tagRemove: "me-0.5 shrink-0 rounded p-0.5 hover:bg-gray-200 focus:outline-none focus:ring-1 focus:ring-blue-500",
|
|
16
|
+
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",
|
|
17
|
+
chevron: "pointer-events-none relative z-10 size-3.5 shrink-0 text-gray-400 transition-transform",
|
|
18
|
+
chevronOpen: "rotate-180",
|
|
19
|
+
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",
|
|
20
|
+
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",
|
|
21
|
+
results: "max-h-56 w-full min-w-0 max-w-full overflow-y-auto overscroll-contain scroll-py-0.5",
|
|
22
|
+
dropdownAnimation: "origin-top",
|
|
23
|
+
dropdownClosed: "mt-1 max-h-64 w-full scale-y-[0.97] opacity-0 pointer-events-none",
|
|
24
|
+
dropdownOpen: "scale-y-100 opacity-100 pointer-events-auto",
|
|
25
|
+
groupHeader: "px-2.5 pt-2.5 pb-0.5 text-[11px] font-semibold uppercase tracking-wider text-gray-400 select-none",
|
|
26
|
+
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",
|
|
27
|
+
optionContent: "flex min-w-0 flex-1 items-center gap-2",
|
|
28
|
+
optionText: "flex min-w-0 flex-1 flex-col",
|
|
29
|
+
optionLabel: "font-normal",
|
|
30
|
+
optionDetail: "text-xs font-normal text-gray-400",
|
|
31
|
+
selectionContent: "flex min-w-0 flex-1 items-center overflow-hidden",
|
|
32
|
+
selectionLabel: "truncate text-sm font-normal",
|
|
33
|
+
optionImage: "size-8 shrink-0 rounded bg-gray-100 object-cover",
|
|
34
|
+
optionMeta: "shrink-0 rounded bg-gray-200 px-1.5 py-0.5 text-[11px] font-medium text-gray-600",
|
|
35
|
+
optionActive: "bg-blue-500 text-white [&_*]:text-white",
|
|
36
|
+
optionSelected: "bg-gray-100 font-normal text-gray-800",
|
|
37
|
+
optionCheck: "shrink-0",
|
|
38
|
+
optionDisabled: "pointer-events-none cursor-not-allowed opacity-50",
|
|
39
|
+
highlight: "rounded-sm bg-amber-200/80 px-0.5 text-inherit",
|
|
40
|
+
status: "sr-only",
|
|
41
|
+
message: "px-2.5 py-5 text-center text-sm text-gray-400",
|
|
42
|
+
loadMore: "block w-full cursor-pointer rounded px-2.5 py-2 text-center text-sm text-blue-600 hover:bg-gray-100",
|
|
43
|
+
spinner: "size-3.5 animate-spin rounded-full border-2 border-gray-200 border-t-blue-600",
|
|
44
|
+
error: "px-2.5 py-2.5 text-sm text-red-600",
|
|
45
|
+
tagDragging: "opacity-50 ring-1 ring-blue-400",
|
|
46
|
+
tagDragOver: "border-l-2 border-l-blue-500"
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
1
50
|
const DEFAULT_CLASSES = {
|
|
2
|
-
wrapper: "tam-select relative w-full text-zinc-900 [color-scheme:light] dark:text-zinc-100 dark:[color-scheme:dark]",
|
|
3
|
-
control: "relative flex min-h-11 w-full cursor-text flex-wrap items-center gap-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
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",
|
|
16
66
|
chevronOpen: "rotate-180",
|
|
17
|
-
dropdown: "absolute z-50 mt-1
|
|
18
|
-
|
|
19
|
-
|
|
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",
|
|
20
76
|
optionText: "flex min-w-0 flex-1 flex-col",
|
|
21
77
|
optionLabel: "font-normal",
|
|
78
|
+
optionLabelWrap: "whitespace-normal break-words [overflow-wrap:anywhere]",
|
|
22
79
|
optionDetail: "text-xs font-normal text-zinc-500 dark:text-zinc-400",
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
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"
|
|
31
104
|
}
|
|
32
105
|
|
|
33
106
|
const ICONS = {
|
|
@@ -37,8 +110,49 @@ const ICONS = {
|
|
|
37
110
|
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>'
|
|
38
111
|
}
|
|
39
112
|
|
|
113
|
+
const ANIMATION_PRESETS = {
|
|
114
|
+
default: { duration: 150, easing: "ease-out" },
|
|
115
|
+
material: { duration: 250, easing: "cubic-bezier(0.4, 0, 0.2, 1)" },
|
|
116
|
+
spring: { duration: 400, easing: "cubic-bezier(0.34, 1.56, 0.64, 1)" },
|
|
117
|
+
snappy: { duration: 100, easing: "ease-in" },
|
|
118
|
+
smooth: { duration: 300, easing: "cubic-bezier(0.25, 0.1, 0.25, 1)" },
|
|
119
|
+
bounce: { duration: 500, easing: "cubic-bezier(0.68, -0.55, 0.27, 1.55)" },
|
|
120
|
+
elastic: { duration: 600, easing: "cubic-bezier(0.68, -0.6, 0.32, 1.6)" },
|
|
121
|
+
fade: { duration: 200, easing: "linear" },
|
|
122
|
+
pop: { duration: 200, easing: "cubic-bezier(0.175, 0.885, 0.32, 1.275)" },
|
|
123
|
+
slide: { duration: 250, easing: "cubic-bezier(0.25, 0.46, 0.45, 0.94)" },
|
|
124
|
+
none: { duration: 0, easing: "ease" }
|
|
125
|
+
}
|
|
126
|
+
|
|
40
127
|
const uid = () => `tam-select-${Math.random().toString(36).slice(2, 10)}`
|
|
41
|
-
const
|
|
128
|
+
const fold = value => String(value ?? "").normalize("NFKD").replace(/\p{Mark}/gu, "").toLocaleLowerCase()
|
|
129
|
+
const normalize = value => fold(value).trim()
|
|
130
|
+
const wordTokens = value => normalize(value).split(/[^\p{Letter}\p{Number}]+/u).filter(Boolean)
|
|
131
|
+
const boundedDistance = (left, right, maximum) => {
|
|
132
|
+
if (Math.abs(left.length - right.length) > maximum) return maximum + 1
|
|
133
|
+
let previous = Array.from({ length: right.length + 1 }, (_, index) => index)
|
|
134
|
+
for (let leftIndex = 1; leftIndex <= left.length; leftIndex += 1) {
|
|
135
|
+
const current = [leftIndex]
|
|
136
|
+
let rowMinimum = current[0]
|
|
137
|
+
for (let rightIndex = 1; rightIndex <= right.length; rightIndex += 1) {
|
|
138
|
+
const substitution = previous[rightIndex - 1] + (left[leftIndex - 1] === right[rightIndex - 1] ? 0 : 1)
|
|
139
|
+
const distance = Math.min(previous[rightIndex] + 1, current[rightIndex - 1] + 1, substitution)
|
|
140
|
+
current.push(distance)
|
|
141
|
+
rowMinimum = Math.min(rowMinimum, distance)
|
|
142
|
+
}
|
|
143
|
+
if (rowMinimum > maximum) return maximum + 1
|
|
144
|
+
previous = current
|
|
145
|
+
}
|
|
146
|
+
return previous[right.length]
|
|
147
|
+
}
|
|
148
|
+
// Hide with the `hidden` class and an inline display. In Tailwind v4 a
|
|
149
|
+
// display utility on the same element (such as `inline-flex`) can be emitted
|
|
150
|
+
// after `hidden` and win, so the class alone is not enough.
|
|
151
|
+
const setHidden = (element, hidden) => {
|
|
152
|
+
element.classList.toggle("hidden", hidden)
|
|
153
|
+
element.style.display = hidden ? "none" : ""
|
|
154
|
+
}
|
|
155
|
+
|
|
42
156
|
const toggleClasses = (element, classNames, force) => {
|
|
43
157
|
String(classNames).split(/\s+/).filter(Boolean).forEach(className => element.classList.toggle(className, force))
|
|
44
158
|
}
|
|
@@ -47,6 +161,32 @@ const hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key
|
|
|
47
161
|
export class TamSelect {
|
|
48
162
|
static instances = new WeakMap()
|
|
49
163
|
|
|
164
|
+
/**
|
|
165
|
+
* Undo markup left by an instance that no longer exists, e.g. a select
|
|
166
|
+
* restored from a page snapshot taken while it was enhanced.
|
|
167
|
+
*/
|
|
168
|
+
static recoverStaleMarkup(select) {
|
|
169
|
+
const saved = select.dataset.tamSelectState
|
|
170
|
+
if (!saved || TamSelect.instances.has(select)) return
|
|
171
|
+
let state
|
|
172
|
+
try { state = JSON.parse(saved) } catch { state = null }
|
|
173
|
+
const stale = select.nextElementSibling
|
|
174
|
+
if (stale?.hasAttribute("data-tam-select-root")) stale.remove()
|
|
175
|
+
// A portaled menu lives outside the wrapper. Remove it too, or its ids
|
|
176
|
+
// collide with the new instance's and ARIA references resolve to it.
|
|
177
|
+
const staleDropdown = select.id ? select.ownerDocument.getElementById(`${select.id}-dropdown`) : null
|
|
178
|
+
if (staleDropdown?.hasAttribute("data-tam-select-dropdown")) staleDropdown.remove()
|
|
179
|
+
if (state) {
|
|
180
|
+
if (!state.srOnly) select.classList.remove("sr-only")
|
|
181
|
+
if (state.tabindex === null) select.removeAttribute("tabindex")
|
|
182
|
+
else select.setAttribute("tabindex", state.tabindex)
|
|
183
|
+
if (state.ariaHidden === null) select.removeAttribute("aria-hidden")
|
|
184
|
+
else select.setAttribute("aria-hidden", state.ariaHidden)
|
|
185
|
+
if (state.id === null) select.removeAttribute("id")
|
|
186
|
+
}
|
|
187
|
+
delete select.dataset.tamSelectState
|
|
188
|
+
}
|
|
189
|
+
|
|
50
190
|
static getInstance(element) {
|
|
51
191
|
return this.instances.get(element) || null
|
|
52
192
|
}
|
|
@@ -64,7 +204,7 @@ export class TamSelect {
|
|
|
64
204
|
placeholder: select.dataset.placeholder || select.querySelector('option[value=""]')?.textContent || "Select…",
|
|
65
205
|
searchPlaceholder: "Search…",
|
|
66
206
|
noResultsText: "No results found",
|
|
67
|
-
createText: query => `Create
|
|
207
|
+
createText: query => `Create "${query}"`,
|
|
68
208
|
loadingText: "Loading…",
|
|
69
209
|
loadMoreText: "Load more",
|
|
70
210
|
inputTooShortText: remaining => `Enter ${remaining} more character${remaining === 1 ? "" : "s"}`,
|
|
@@ -73,17 +213,91 @@ export class TamSelect {
|
|
|
73
213
|
pageParam: "page",
|
|
74
214
|
debounce: 250,
|
|
75
215
|
minQueryLength: 0,
|
|
216
|
+
fuzzySearch: true,
|
|
217
|
+
highlightMatches: true,
|
|
218
|
+
sortByRelevance: true,
|
|
219
|
+
searchFields: ["label", "detail", "meta"],
|
|
220
|
+
resultsText: count => `${count} result${count === 1 ? "" : "s"} available`,
|
|
221
|
+
clearLabel: "Clear selection",
|
|
222
|
+
removeLabel: item => `Remove ${item.label}`,
|
|
223
|
+
selectionLimitText: limit => `You can select up to ${limit} item${limit === 1 ? "" : "s"}`,
|
|
224
|
+
language: {},
|
|
76
225
|
valueField: "value",
|
|
77
226
|
labelField: "label",
|
|
78
227
|
imageField: "image",
|
|
79
228
|
itemsPath: "items",
|
|
80
229
|
paginationPath: "pagination",
|
|
81
230
|
matcher: null,
|
|
231
|
+
theme: "auto",
|
|
82
232
|
classes: {},
|
|
83
233
|
headers: {},
|
|
234
|
+
animations: true,
|
|
235
|
+
animationPreset: null,
|
|
236
|
+
animationDuration: 150,
|
|
237
|
+
animationEasing: "ease-out",
|
|
238
|
+
emptyState: null,
|
|
239
|
+
noResultsState: null,
|
|
240
|
+
loadingState: null,
|
|
241
|
+
lazyLoadImages: false,
|
|
242
|
+
virtualScroll: false,
|
|
243
|
+
virtualScrollThreshold: 100,
|
|
244
|
+
virtualScrollBuffer: 5,
|
|
245
|
+
virtualItemHeight: 32,
|
|
246
|
+
wrapOptionText: null,
|
|
247
|
+
optionTooltip: true,
|
|
248
|
+
draggable: false,
|
|
249
|
+
maximumSelectionLength: 0,
|
|
250
|
+
bulkActions: false,
|
|
251
|
+
showSelectionCount: false,
|
|
252
|
+
hideSelected: false,
|
|
253
|
+
selectAllText: count => `Select all${count > 0 ? ` ${count}` : ""}`,
|
|
254
|
+
deselectAllText: count => `Clear${count > 0 ? ` ${count}` : ""}`,
|
|
255
|
+
selectionCountText: (count, limit) => limit > 0 ? `${count} / ${limit} selected` : `${count} selected`,
|
|
256
|
+
maximumInputLength: 0,
|
|
257
|
+
minimumResultsForSearch: 0,
|
|
258
|
+
selectOnClose: false,
|
|
259
|
+
tokenSeparators: [],
|
|
260
|
+
sorter: null,
|
|
261
|
+
templateResult: null,
|
|
262
|
+
templateSelection: null,
|
|
263
|
+
transport: null,
|
|
264
|
+
processResults: null,
|
|
265
|
+
remoteParams: {},
|
|
266
|
+
cacheRemote: false,
|
|
267
|
+
dropdownParent: null,
|
|
268
|
+
dropdownWidth: "auto",
|
|
269
|
+
maxDropdownWidth: 480,
|
|
270
|
+
maxDropdownHeight: 360,
|
|
271
|
+
viewportPadding: 8,
|
|
272
|
+
width: "resolve",
|
|
273
|
+
dir: "auto",
|
|
84
274
|
...options
|
|
85
275
|
}
|
|
86
|
-
|
|
276
|
+
const languageOptions = {
|
|
277
|
+
placeholder: "placeholder",
|
|
278
|
+
searchPlaceholder: "searchPlaceholder",
|
|
279
|
+
noResults: "noResultsText",
|
|
280
|
+
create: "createText",
|
|
281
|
+
loading: "loadingText",
|
|
282
|
+
loadMore: "loadMoreText",
|
|
283
|
+
inputTooShort: "inputTooShortText",
|
|
284
|
+
results: "resultsText",
|
|
285
|
+
clear: "clearLabel",
|
|
286
|
+
remove: "removeLabel",
|
|
287
|
+
selectionLimit: "selectionLimitText",
|
|
288
|
+
selectAll: "selectAllText",
|
|
289
|
+
deselectAll: "deselectAllText",
|
|
290
|
+
selectionCount: "selectionCountText"
|
|
291
|
+
}
|
|
292
|
+
Object.entries(languageOptions).forEach(([languageKey, optionKey]) => {
|
|
293
|
+
if (hasOwn(this.options.language, languageKey) && !hasOwn(options, optionKey)) {
|
|
294
|
+
this.options[optionKey] = this.options.language[languageKey]
|
|
295
|
+
}
|
|
296
|
+
})
|
|
297
|
+
this.dir = this.options.dir === "auto" ? this.detectDirection() : this.options.dir
|
|
298
|
+
this.theme = this.options.theme === "auto" ? "default" : this.options.theme
|
|
299
|
+
const themeClasses = THEME_CLASSES[this.theme] || {}
|
|
300
|
+
this.classes = { ...DEFAULT_CLASSES, ...themeClasses, ...this.options.classes }
|
|
87
301
|
this.multiple = select.multiple
|
|
88
302
|
this.searchable = Boolean(this.options.searchable || this.options.creatable)
|
|
89
303
|
this.items = []
|
|
@@ -103,14 +317,47 @@ export class TamSelect {
|
|
|
103
317
|
this.optionIds = new WeakMap()
|
|
104
318
|
this.optionIdSequence = 0
|
|
105
319
|
this.invalidFromEvent = false
|
|
320
|
+
TamSelect.recoverStaleMarkup(select)
|
|
106
321
|
this.originalTabIndex = select.getAttribute("tabindex")
|
|
107
322
|
this.originalAriaHidden = select.getAttribute("aria-hidden")
|
|
108
323
|
this.originalId = select.getAttribute("id")
|
|
109
324
|
this.hadSrOnlyClass = select.classList.contains("sr-only")
|
|
325
|
+
// Recorded on the element so a page snapshot (such as Turbo's cache)
|
|
326
|
+
// still knows the native state after the live instance is gone.
|
|
327
|
+
select.dataset.tamSelectState = JSON.stringify({
|
|
328
|
+
tabindex: this.originalTabIndex,
|
|
329
|
+
ariaHidden: this.originalAriaHidden,
|
|
330
|
+
id: this.originalId,
|
|
331
|
+
srOnly: this.hadSrOnlyClass
|
|
332
|
+
})
|
|
333
|
+
this.typeaheadBuffer = ""
|
|
334
|
+
this.typeaheadTimer = null
|
|
335
|
+
this.groupTree = []
|
|
336
|
+
this.closeTimer = null
|
|
337
|
+
this.closeTransitionHandler = null
|
|
338
|
+
this.lazyObserver = null
|
|
339
|
+
this.selectionLimitReached = false
|
|
340
|
+
this.searchVisible = this.options.minimumResultsForSearch <= 0
|
|
341
|
+
this.isVirtualScroll = false
|
|
342
|
+
this.virtualStartIndex = 0
|
|
343
|
+
this.onVirtualScroll = null
|
|
344
|
+
this.remoteCache = new Map()
|
|
345
|
+
this.destroyed = false
|
|
346
|
+
this.refreshQueued = false
|
|
347
|
+
this.composing = false
|
|
348
|
+
this.animationsEnabled = this.options.animations && !(typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches)
|
|
110
349
|
this.build()
|
|
111
350
|
this.bind()
|
|
112
351
|
this.readNativeOptions()
|
|
113
352
|
this.renderSelection()
|
|
353
|
+
this.applyFitWidth()
|
|
354
|
+
// Canvas measurements use fallback fonts until web fonts finish loading.
|
|
355
|
+
document.fonts?.ready?.then(() => {
|
|
356
|
+
if (this.destroyed) return
|
|
357
|
+
this.textWidthCache?.clear()
|
|
358
|
+
this.itemWidthCache = new WeakMap()
|
|
359
|
+
this.applyFitWidth()
|
|
360
|
+
})
|
|
114
361
|
TamSelect.instances.set(select, this)
|
|
115
362
|
}
|
|
116
363
|
|
|
@@ -126,13 +373,33 @@ export class TamSelect {
|
|
|
126
373
|
this.wrapper = document.createElement("div")
|
|
127
374
|
this.wrapper.className = this.classes.wrapper
|
|
128
375
|
this.wrapper.dataset.tamSelectRoot = ""
|
|
376
|
+
this.wrapper.setAttribute("dir", this.dir)
|
|
377
|
+
// "resolve" follows an inline width on the native select, like Select2,
|
|
378
|
+
// and otherwise fills the container. "auto"/"fit" size the control to its
|
|
379
|
+
// widest option the way a native select sizes itself.
|
|
380
|
+
const requestedWidth = this.options.width === "resolve" ? (this.select.style.width || "100%") : this.options.width
|
|
381
|
+
this.fitWidth = ["auto", "fit"].includes(String(requestedWidth).trim())
|
|
382
|
+
this.wrapper.style.width = this.fitWidth ? "auto" : requestedWidth
|
|
383
|
+
this.wrapper.style.maxWidth = "100%"
|
|
384
|
+
this.wrapper.style.minWidth = "0"
|
|
385
|
+
// Inline menus are positioned against the wrapper, even when a custom
|
|
386
|
+
// `classes.wrapper` leaves out `relative`.
|
|
387
|
+
this.wrapper.style.position = "relative"
|
|
388
|
+
if (this.fitWidth) {
|
|
389
|
+
this.wrapper.style.display = "inline-block"
|
|
390
|
+
this.wrapper.style.verticalAlign = "middle"
|
|
391
|
+
}
|
|
129
392
|
|
|
130
393
|
this.control = document.createElement("div")
|
|
131
|
-
this.control.className =
|
|
394
|
+
this.control.className = [
|
|
395
|
+
this.classes.control,
|
|
396
|
+
this.multiple && this.classes.controlMultiple
|
|
397
|
+
].filter(Boolean).join(" ")
|
|
132
398
|
|
|
133
399
|
this.values = document.createElement("div")
|
|
134
400
|
this.values.id = this.valuesId
|
|
135
401
|
this.values.className = "contents"
|
|
402
|
+
this.values.style.display = "contents"
|
|
136
403
|
|
|
137
404
|
this.searchIcon = document.createElement("span")
|
|
138
405
|
this.searchIcon.className = this.classes.searchIcon
|
|
@@ -145,13 +412,25 @@ export class TamSelect {
|
|
|
145
412
|
this.input.className = this.classes.input
|
|
146
413
|
this.input.autocomplete = "off"
|
|
147
414
|
this.input.spellcheck = false
|
|
148
|
-
this.input.
|
|
149
|
-
this.input.setAttribute("
|
|
150
|
-
this.input.setAttribute("
|
|
415
|
+
this.input.autocapitalize = "none"
|
|
416
|
+
this.input.setAttribute("autocorrect", "off")
|
|
417
|
+
this.input.setAttribute("enterkeyhint", "search")
|
|
418
|
+
if (this.options.maximumInputLength > 0) this.input.maxLength = this.options.maximumInputLength
|
|
151
419
|
this.input.setAttribute("aria-controls", this.listboxId)
|
|
152
|
-
this.
|
|
153
|
-
|
|
154
|
-
|
|
420
|
+
if (this.multiple) {
|
|
421
|
+
this.input.setAttribute("role", "combobox")
|
|
422
|
+
this.input.setAttribute("aria-haspopup", "listbox")
|
|
423
|
+
this.input.setAttribute("aria-expanded", "false")
|
|
424
|
+
this.input.setAttribute("aria-autocomplete", "list")
|
|
425
|
+
this.focusTarget = this.input
|
|
426
|
+
} else {
|
|
427
|
+
this.input.type = "search"
|
|
428
|
+
this.input.setAttribute("role", "searchbox")
|
|
429
|
+
this.input.setAttribute("aria-label", this.options.searchPlaceholder)
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
if (!this.multiple || !this.searchable) {
|
|
155
434
|
this.trigger = document.createElement("button")
|
|
156
435
|
this.trigger.type = "button"
|
|
157
436
|
this.trigger.className = this.classes.trigger
|
|
@@ -165,7 +444,7 @@ export class TamSelect {
|
|
|
165
444
|
this.clearButton = document.createElement("button")
|
|
166
445
|
this.clearButton.type = "button"
|
|
167
446
|
this.clearButton.className = this.classes.clear
|
|
168
|
-
this.clearButton.setAttribute("aria-label",
|
|
447
|
+
this.clearButton.setAttribute("aria-label", this.options.clearLabel)
|
|
169
448
|
this.clearButton.innerHTML = ICONS.close
|
|
170
449
|
|
|
171
450
|
this.chevron = document.createElement("span")
|
|
@@ -173,18 +452,179 @@ export class TamSelect {
|
|
|
173
452
|
this.chevron.innerHTML = ICONS.chevron
|
|
174
453
|
|
|
175
454
|
this.dropdown = document.createElement("div")
|
|
176
|
-
this.dropdown.id = this.
|
|
177
|
-
this.dropdown.
|
|
178
|
-
this.dropdown.
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
this.
|
|
183
|
-
this.
|
|
455
|
+
this.dropdown.id = `${this.id}-dropdown`
|
|
456
|
+
this.dropdown.dataset.tamSelectDropdown = ""
|
|
457
|
+
this.dropdown.className = this.classes.dropdown
|
|
458
|
+
setHidden(this.dropdown, true)
|
|
459
|
+
this.dropdown.style.width = "100%"
|
|
460
|
+
this.dropdown.style.minWidth = "0"
|
|
461
|
+
this.dropdown.style.maxWidth = "100%"
|
|
462
|
+
this.dropdown.style.boxSizing = "border-box"
|
|
463
|
+
if (this.animationsEnabled) {
|
|
464
|
+
const preset = this.options.animationPreset ? ANIMATION_PRESETS[this.options.animationPreset] : null
|
|
465
|
+
const duration = preset ? preset.duration : this.options.animationDuration
|
|
466
|
+
const easing = preset ? preset.easing : this.options.animationEasing
|
|
467
|
+
this.options.animationDuration = duration
|
|
468
|
+
this.options.animationEasing = easing
|
|
469
|
+
toggleClasses(this.dropdown, this.classes.dropdownAnimation, true)
|
|
470
|
+
this.dropdown.style.setProperty("--tam-duration", `${duration}ms`)
|
|
471
|
+
this.dropdown.style.setProperty("--tam-easing", easing)
|
|
472
|
+
// Geometry is calculated at runtime for portaled menus. Animating `all`
|
|
473
|
+
// also animated width/max-height, causing a large-to-small flash.
|
|
474
|
+
this.dropdown.style.transition = [
|
|
475
|
+
`opacity var(--tam-duration) var(--tam-easing)`,
|
|
476
|
+
`transform var(--tam-duration) var(--tam-easing)`
|
|
477
|
+
].join(", ")
|
|
478
|
+
}
|
|
479
|
+
this.results = document.createElement("div")
|
|
480
|
+
this.results.id = this.listboxId
|
|
481
|
+
this.results.className = this.classes.results
|
|
482
|
+
this.results.style.width = "100%"
|
|
483
|
+
this.results.style.minWidth = "0"
|
|
484
|
+
this.results.style.maxWidth = "100%"
|
|
485
|
+
this.results.style.boxSizing = "border-box"
|
|
486
|
+
this.results.setAttribute("role", "listbox")
|
|
487
|
+
if (this.multiple) this.results.setAttribute("aria-multiselectable", "true")
|
|
488
|
+
|
|
489
|
+
if (this.searchable && !this.multiple) {
|
|
490
|
+
this.searchPanel = document.createElement("div")
|
|
491
|
+
this.searchPanel.className = this.classes.dropdownSearch
|
|
492
|
+
this.searchPanel.style.width = "100%"
|
|
493
|
+
this.searchPanel.style.minWidth = "0"
|
|
494
|
+
this.searchPanel.style.maxWidth = "100%"
|
|
495
|
+
this.searchPanel.style.boxSizing = "border-box"
|
|
496
|
+
this.input.style.width = "100%"
|
|
497
|
+
this.input.style.minWidth = "0"
|
|
498
|
+
this.input.style.maxWidth = "100%"
|
|
499
|
+
this.input.style.boxSizing = "border-box"
|
|
500
|
+
this.searchPanel.append(this.searchIcon, this.input)
|
|
501
|
+
this.dropdown.append(this.searchPanel, this.results)
|
|
502
|
+
} else {
|
|
503
|
+
this.dropdown.append(this.results)
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
this.buildSelectionToolbar()
|
|
507
|
+
|
|
508
|
+
this.status = document.createElement("div")
|
|
509
|
+
this.status.className = this.classes.status
|
|
510
|
+
this.status.setAttribute("role", "status")
|
|
511
|
+
this.status.setAttribute("aria-live", "polite")
|
|
512
|
+
this.status.setAttribute("aria-atomic", "true")
|
|
513
|
+
|
|
514
|
+
const focusControl = this.multiple && this.searchable ? [this.searchIcon, this.input] : [this.trigger]
|
|
515
|
+
this.control.append(this.values, ...focusControl, this.chevron, this.clearButton)
|
|
516
|
+
this.wrapper.append(this.control, this.status)
|
|
184
517
|
this.select.after(this.wrapper)
|
|
518
|
+
this.dropdownParent = this.resolveDropdownParent()
|
|
519
|
+
this.portalDropdown = Boolean(this.dropdownParent)
|
|
520
|
+
if (this.portalDropdown) {
|
|
521
|
+
this.dropdownParent.append(this.dropdown)
|
|
522
|
+
this.dropdown.style.position = "fixed"
|
|
523
|
+
this.dropdown.style.marginTop = "0"
|
|
524
|
+
// Keep the unpositioned portal out of the first paint. It is revealed
|
|
525
|
+
// synchronously after open() has measured and constrained it.
|
|
526
|
+
this.dropdown.style.visibility = "hidden"
|
|
527
|
+
} else {
|
|
528
|
+
this.wrapper.append(this.dropdown)
|
|
529
|
+
}
|
|
185
530
|
this.labelElements = this.findLabelElements()
|
|
186
531
|
this.applyDisabled()
|
|
187
532
|
this.syncAria()
|
|
533
|
+
this.initLazyObserver()
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
buildSelectionToolbar() {
|
|
537
|
+
if (!this.multiple || !(this.options.bulkActions || this.options.showSelectionCount)) return
|
|
538
|
+
this.selectionToolbar = document.createElement("div")
|
|
539
|
+
this.selectionToolbar.className = this.classes.selectionToolbar
|
|
540
|
+
this.selectionToolbar.dataset.tamSelectToolbar = ""
|
|
541
|
+
if (this.options.bulkActions) {
|
|
542
|
+
const makeAction = (action, icon, variantClass) => {
|
|
543
|
+
const button = document.createElement("button")
|
|
544
|
+
button.type = "button"
|
|
545
|
+
button.className = `${this.classes.selectionAction} ${variantClass}`
|
|
546
|
+
button.setAttribute("aria-controls", this.listboxId)
|
|
547
|
+
const iconElement = document.createElement("span")
|
|
548
|
+
iconElement.className = this.classes.selectionActionIcon
|
|
549
|
+
iconElement.setAttribute("aria-hidden", "true")
|
|
550
|
+
iconElement.innerHTML = icon
|
|
551
|
+
const labelElement = document.createElement("span")
|
|
552
|
+
button.append(iconElement, labelElement)
|
|
553
|
+
button.addEventListener("click", event => {
|
|
554
|
+
event.stopPropagation()
|
|
555
|
+
if (!button.disabled) action()
|
|
556
|
+
})
|
|
557
|
+
return { button, labelElement }
|
|
558
|
+
}
|
|
559
|
+
const selectAction = makeAction(() => this.selectAll(), ICONS.check, this.classes.selectionActionSelect)
|
|
560
|
+
const clearAction = makeAction(() => this.deselectAll(), ICONS.close, this.classes.selectionActionClear)
|
|
561
|
+
this.selectAllButton = selectAction.button
|
|
562
|
+
this.selectAllLabel = selectAction.labelElement
|
|
563
|
+
this.deselectAllButton = clearAction.button
|
|
564
|
+
this.deselectAllLabel = clearAction.labelElement
|
|
565
|
+
this.selectionShortcut = document.createElement("kbd")
|
|
566
|
+
this.selectionShortcut.className = this.classes.selectionShortcut
|
|
567
|
+
this.selectionShortcut.textContent = /Mac|iPhone|iPad/.test(navigator.platform || "") ? "⌘ A" : "Ctrl A"
|
|
568
|
+
this.selectionShortcut.title = "Toggle all matching options"
|
|
569
|
+
this.selectionToolbar.append(this.selectAllButton, this.deselectAllButton, this.selectionShortcut)
|
|
570
|
+
this.selectionToolbar.addEventListener("keydown", event => {
|
|
571
|
+
if (event.key === "Escape") {
|
|
572
|
+
event.preventDefault()
|
|
573
|
+
this.close(false)
|
|
574
|
+
this.focusTarget.focus()
|
|
575
|
+
} else if (event.key === "Tab") {
|
|
576
|
+
const enabledActions = [this.selectAllButton, this.deselectAllButton].filter(button => !button.disabled)
|
|
577
|
+
if (event.shiftKey && event.target === enabledActions[0]) {
|
|
578
|
+
event.preventDefault()
|
|
579
|
+
this.focusTarget.focus()
|
|
580
|
+
} else if (!event.shiftKey && event.target === enabledActions.at(-1)) {
|
|
581
|
+
// Restore the control's place in document tab order for body portals.
|
|
582
|
+
this.focusTarget.focus()
|
|
583
|
+
this.close(false)
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
})
|
|
587
|
+
}
|
|
588
|
+
if (this.options.showSelectionCount) {
|
|
589
|
+
this.selectionCount = document.createElement("span")
|
|
590
|
+
this.selectionCount.className = this.classes.selectionCount
|
|
591
|
+
this.selectionCount.setAttribute("role", "status")
|
|
592
|
+
this.selectionCount.setAttribute("aria-live", "polite")
|
|
593
|
+
this.selectionCount.setAttribute("aria-atomic", "true")
|
|
594
|
+
this.selectionToolbar.append(this.selectionCount)
|
|
595
|
+
}
|
|
596
|
+
this.dropdown.insertBefore(this.selectionToolbar, this.results)
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
updateSelectionToolbar() {
|
|
600
|
+
if (!this.selectionToolbar) return
|
|
601
|
+
const count = this.selectedItems().length
|
|
602
|
+
const limit = this.options.maximumSelectionLength
|
|
603
|
+
if (this.selectionCount) {
|
|
604
|
+
const text = typeof this.options.selectionCountText === "function"
|
|
605
|
+
? this.options.selectionCountText(count, limit)
|
|
606
|
+
: this.options.selectionCountText
|
|
607
|
+
if (this.selectionCount.textContent !== String(text)) this.selectionCount.textContent = text
|
|
608
|
+
}
|
|
609
|
+
if (this.selectAllButton) {
|
|
610
|
+
const matches = this.bulkCandidates()
|
|
611
|
+
const selectedMatches = matches.filter(item => item.selected).length
|
|
612
|
+
const selectableMatches = matches.length - selectedMatches
|
|
613
|
+
const selectText = typeof this.options.selectAllText === "function"
|
|
614
|
+
? this.options.selectAllText(matches.length)
|
|
615
|
+
: this.options.selectAllText
|
|
616
|
+
const deselectText = typeof this.options.deselectAllText === "function"
|
|
617
|
+
? this.options.deselectAllText(selectedMatches)
|
|
618
|
+
: this.options.deselectAllText
|
|
619
|
+
this.selectAllLabel.textContent = selectText
|
|
620
|
+
this.deselectAllLabel.textContent = deselectText
|
|
621
|
+
this.selectAllButton.setAttribute("aria-label", selectText)
|
|
622
|
+
this.deselectAllButton.setAttribute("aria-label", deselectText)
|
|
623
|
+
this.selectAllButton.disabled = this.select.disabled || (limit > 0 && count >= limit) || selectableMatches === 0
|
|
624
|
+
this.deselectAllButton.disabled = this.select.disabled || selectedMatches === 0
|
|
625
|
+
this.selectAllButton.setAttribute("aria-disabled", String(this.selectAllButton.disabled))
|
|
626
|
+
this.deselectAllButton.setAttribute("aria-disabled", String(this.deselectAllButton.disabled))
|
|
627
|
+
}
|
|
188
628
|
}
|
|
189
629
|
|
|
190
630
|
bind() {
|
|
@@ -193,16 +633,29 @@ export class TamSelect {
|
|
|
193
633
|
this.open()
|
|
194
634
|
this.input.focus()
|
|
195
635
|
}
|
|
196
|
-
this.onInput =
|
|
636
|
+
this.onInput = event => {
|
|
637
|
+
if (this.destroyed || this.composing || event?.isComposing) return
|
|
197
638
|
this.query = this.input.value
|
|
639
|
+
if (this.multiple && this.options.tokenSeparators.length && this.options.creatable) {
|
|
640
|
+
this.tokenizeInput()
|
|
641
|
+
}
|
|
198
642
|
this.open(false)
|
|
199
643
|
if (this.options.remoteUrl) this.scheduleRemote()
|
|
200
644
|
else this.filterLocal()
|
|
201
645
|
}
|
|
646
|
+
this.onCompositionStart = () => { this.composing = true }
|
|
647
|
+
this.onCompositionEnd = () => {
|
|
648
|
+
this.composing = false
|
|
649
|
+
queueMicrotask(() => {
|
|
650
|
+
if (!this.destroyed && this.query !== this.input.value) this.onInput()
|
|
651
|
+
})
|
|
652
|
+
}
|
|
202
653
|
this.onKeydown = event => this.handleKeydown(event)
|
|
203
654
|
this.onClear = event => { event.stopPropagation(); this.clear() }
|
|
204
|
-
this.onTrigger = event => { event.preventDefault(); this.open()
|
|
205
|
-
this.onOutside = event => {
|
|
655
|
+
this.onTrigger = event => { event.preventDefault(); this.open() }
|
|
656
|
+
this.onOutside = event => {
|
|
657
|
+
if (!this.wrapper.contains(event.target) && !this.dropdown.contains(event.target)) this.close()
|
|
658
|
+
}
|
|
206
659
|
this.onNativeChange = () => {
|
|
207
660
|
if (this.select.checkValidity()) this.invalidFromEvent = false
|
|
208
661
|
this.readNativeOptions()
|
|
@@ -217,9 +670,11 @@ export class TamSelect {
|
|
|
217
670
|
this.focusTarget.focus()
|
|
218
671
|
}
|
|
219
672
|
this.onScroll = () => {
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
673
|
+
// After a failed page, wait for an explicit retry via Load more instead
|
|
674
|
+
// of re-requesting it on every scroll.
|
|
675
|
+
if (!this.error && this.results.scrollTop + this.results.clientHeight >= this.results.scrollHeight - 32) this.loadNextPage()
|
|
676
|
+
if (this.isVirtualScroll) {
|
|
677
|
+
this.rerenderVirtualItems()
|
|
223
678
|
}
|
|
224
679
|
}
|
|
225
680
|
this.onLabelClick = event => {
|
|
@@ -227,17 +682,309 @@ export class TamSelect {
|
|
|
227
682
|
event.preventDefault()
|
|
228
683
|
this.focusTarget.focus()
|
|
229
684
|
}
|
|
685
|
+
this.onFormReset = () => queueMicrotask(() => this.refresh())
|
|
686
|
+
this.onViewportChange = event => {
|
|
687
|
+
if (!this.opened) return
|
|
688
|
+
// The window scroll listener uses capture so it can follow scrolling
|
|
689
|
+
// containers. It also sees the results panel's own scroll events, which
|
|
690
|
+
// do not change the control's viewport position and must not resize it.
|
|
691
|
+
if (event?.type === "scroll" && event.target === this.results) return
|
|
692
|
+
if (this.portalDropdown) this.updateDropdownPosition()
|
|
693
|
+
// An inline menu scrolls with its control, so only a resize can push
|
|
694
|
+
// it past the viewport edge.
|
|
695
|
+
else if (event?.type !== "scroll") this.updateInlineDropdownWidth()
|
|
696
|
+
}
|
|
230
697
|
|
|
231
698
|
this.control.addEventListener("click", this.onControlClick)
|
|
232
699
|
this.focusTarget.addEventListener("keydown", this.onKeydown)
|
|
233
|
-
if (this.input) this.input.addEventListener("
|
|
700
|
+
if (this.input && this.input !== this.focusTarget) this.input.addEventListener("keydown", this.onKeydown)
|
|
701
|
+
if (this.input) {
|
|
702
|
+
this.input.addEventListener("input", this.onInput)
|
|
703
|
+
this.input.addEventListener("compositionstart", this.onCompositionStart)
|
|
704
|
+
this.input.addEventListener("compositionend", this.onCompositionEnd)
|
|
705
|
+
}
|
|
234
706
|
if (this.trigger) this.trigger.addEventListener("click", this.onTrigger)
|
|
235
707
|
this.clearButton.addEventListener("click", this.onClear)
|
|
236
|
-
this.
|
|
708
|
+
this.results.addEventListener("scroll", this.onScroll)
|
|
237
709
|
this.select.addEventListener("change", this.onNativeChange)
|
|
238
710
|
this.select.addEventListener("invalid", this.onNativeInvalid)
|
|
239
711
|
this.labelElements.forEach(label => label.addEventListener("click", this.onLabelClick))
|
|
240
712
|
document.addEventListener("pointerdown", this.onOutside)
|
|
713
|
+
this.select.form?.addEventListener("reset", this.onFormReset)
|
|
714
|
+
window.addEventListener("resize", this.onViewportChange)
|
|
715
|
+
window.addEventListener("scroll", this.onViewportChange, true)
|
|
716
|
+
window.visualViewport?.addEventListener("resize", this.onViewportChange)
|
|
717
|
+
window.visualViewport?.addEventListener("scroll", this.onViewportChange)
|
|
718
|
+
this.mutationObserver = new MutationObserver(() => this.queueRefresh())
|
|
719
|
+
this.mutationObserver.observe(this.select, {
|
|
720
|
+
childList: true,
|
|
721
|
+
subtree: true,
|
|
722
|
+
attributes: true,
|
|
723
|
+
attributeFilter: ["disabled", "label", "value", "selected", "required", "aria-invalid", "aria-describedby", "data-detail", "data-meta", "data-image"]
|
|
724
|
+
})
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
resolveDropdownParent() {
|
|
728
|
+
if (!this.options.dropdownParent) return null
|
|
729
|
+
if (typeof this.options.dropdownParent === "string") return document.querySelector(this.options.dropdownParent)
|
|
730
|
+
const ElementClass = this.select.ownerDocument.defaultView.Element
|
|
731
|
+
return this.options.dropdownParent instanceof ElementClass ? this.options.dropdownParent : null
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
queueRefresh() {
|
|
735
|
+
if (this.refreshQueued || this.destroyed) return
|
|
736
|
+
this.refreshQueued = true
|
|
737
|
+
queueMicrotask(() => {
|
|
738
|
+
this.refreshQueued = false
|
|
739
|
+
if (!this.destroyed && this.select.isConnected) this.refresh()
|
|
740
|
+
})
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
viewportBox() {
|
|
744
|
+
const padding = Math.max(0, Number(this.options.viewportPadding) || 0)
|
|
745
|
+
const visualViewport = window.visualViewport
|
|
746
|
+
const left = visualViewport?.offsetLeft || 0
|
|
747
|
+
const top = visualViewport?.offsetTop || 0
|
|
748
|
+
const width = visualViewport?.width || document.documentElement.clientWidth || window.innerWidth
|
|
749
|
+
const height = visualViewport?.height || document.documentElement.clientHeight || window.innerHeight
|
|
750
|
+
return { left, top, width, height, right: left + width, bottom: top + height, padding }
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
// Like a native select, the menu is never narrower than its control and
|
|
754
|
+
// grows to fit its widest option, within maxDropdownWidth and the viewport.
|
|
755
|
+
resolveDropdownWidth(triggerWidth, availableWidth) {
|
|
756
|
+
const viewportLimit = availableWidth || triggerWidth
|
|
757
|
+
if (!["auto", "content"].includes(this.options.dropdownWidth)) return Math.min(triggerWidth, viewportLimit)
|
|
758
|
+
if (this.dropdownContentWidth == null || this.dropdownWidthStale) {
|
|
759
|
+
// Keep the widest width seen while open, so filtering never shrinks or
|
|
760
|
+
// shifts the menu under the pointer. open() resets it.
|
|
761
|
+
this.dropdownContentWidth = Math.max(this.dropdownContentWidth || 0, this.measureDropdownContentWidth())
|
|
762
|
+
this.dropdownWidthStale = false
|
|
763
|
+
}
|
|
764
|
+
const configuredMaximum = Number(this.options.maxDropdownWidth)
|
|
765
|
+
const maximum = configuredMaximum > 0 ? Math.max(triggerWidth, configuredMaximum) : Infinity
|
|
766
|
+
return Math.min(Math.max(triggerWidth, this.dropdownContentWidth), maximum, viewportLimit)
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
// Align the menu with the control's start edge, then keep it on screen.
|
|
770
|
+
resolveDropdownLeft(rect, width, viewport) {
|
|
771
|
+
const start = this.dir === "rtl" ? rect.right - width : rect.left
|
|
772
|
+
const minimum = viewport.left + viewport.padding
|
|
773
|
+
const maximum = Math.max(minimum, viewport.right - viewport.padding - width)
|
|
774
|
+
return Math.min(Math.max(start, minimum), maximum)
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
// The horizontal space an inline menu may use: the viewport, narrowed by
|
|
778
|
+
// every ancestor that clips overflow (cards, modals, scrolling tables), so
|
|
779
|
+
// a wider menu is never cut off. Use dropdownParent to escape them.
|
|
780
|
+
inlineDropdownBounds() {
|
|
781
|
+
const viewport = this.viewportBox()
|
|
782
|
+
let left = viewport.left + viewport.padding
|
|
783
|
+
let right = viewport.right - viewport.padding
|
|
784
|
+
const view = this.select.ownerDocument.defaultView
|
|
785
|
+
const root = this.select.ownerDocument.documentElement
|
|
786
|
+
for (let element = this.wrapper.parentElement; element && element !== root && element !== this.select.ownerDocument.body; element = element.parentElement) {
|
|
787
|
+
const style = view.getComputedStyle(element)
|
|
788
|
+
// Read the shorthand's x value too; some engines leave overflowX unset.
|
|
789
|
+
const overflowX = [style.overflowX, String(style.overflow || "").split(/\s+/)[0]]
|
|
790
|
+
.find(value => value && value !== "visible")
|
|
791
|
+
if (!overflowX) continue
|
|
792
|
+
const box = element.getBoundingClientRect()
|
|
793
|
+
if (!box.width) continue
|
|
794
|
+
const innerLeft = box.left + (element.clientLeft || 0)
|
|
795
|
+
left = Math.max(left, innerLeft)
|
|
796
|
+
right = Math.min(right, innerLeft + (element.clientWidth || box.width))
|
|
797
|
+
}
|
|
798
|
+
return { left, right: Math.max(left, right) }
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
updateInlineDropdownWidth() {
|
|
802
|
+
if (this.portalDropdown || !this.opened) return
|
|
803
|
+
const rect = this.control.getBoundingClientRect()
|
|
804
|
+
if (!rect.width) return
|
|
805
|
+
const bounds = this.inlineDropdownBounds()
|
|
806
|
+
const width = this.resolveDropdownWidth(rect.width, Math.max(0, bounds.right - bounds.left))
|
|
807
|
+
if (width <= rect.width + 0.5) {
|
|
808
|
+
this.dropdown.style.width = "100%"
|
|
809
|
+
this.dropdown.style.maxWidth = "100%"
|
|
810
|
+
this.dropdown.style.left = ""
|
|
811
|
+
this.dropdown.style.right = ""
|
|
812
|
+
return
|
|
813
|
+
}
|
|
814
|
+
const offsetParentLeft = this.wrapper.getBoundingClientRect().left + (this.wrapper.clientLeft || 0)
|
|
815
|
+
this.dropdown.style.width = `${width}px`
|
|
816
|
+
this.dropdown.style.maxWidth = "none"
|
|
817
|
+
this.dropdown.style.left = `${this.resolveDropdownLeft(rect, width, { ...bounds, padding: 0 }) - offsetParentLeft}px`
|
|
818
|
+
this.dropdown.style.right = "auto"
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
updateDropdownPosition() {
|
|
822
|
+
if (!this.portalDropdown) return
|
|
823
|
+
const rect = this.control.getBoundingClientRect()
|
|
824
|
+
const gap = 6
|
|
825
|
+
const viewport = this.viewportBox()
|
|
826
|
+
const { padding, top: viewportTop, bottom: viewportBottom } = viewport
|
|
827
|
+
const maximumHeight = Math.max(96, Number(this.options.maxDropdownHeight) || 360)
|
|
828
|
+
const searchHeight = this.searchPanel && !this.searchPanel.classList.contains("hidden")
|
|
829
|
+
? (this.searchPanel.getBoundingClientRect().height || 44)
|
|
830
|
+
: 0
|
|
831
|
+
const toolbarHeight = this.selectionToolbar?.getBoundingClientRect().height || (this.selectionToolbar ? 52 : 0)
|
|
832
|
+
const dropdownChrome = Math.max(0, this.dropdown.offsetHeight - this.dropdown.clientHeight)
|
|
833
|
+
// `dropdown.scrollHeight` reflects a previously applied max-height because
|
|
834
|
+
// results is its own scrolling region. Measure the results' full content
|
|
835
|
+
// instead so the menu can grow again when viewport space becomes available.
|
|
836
|
+
const naturalHeight = this.results.scrollHeight > 0
|
|
837
|
+
? this.results.scrollHeight + searchHeight + toolbarHeight + dropdownChrome
|
|
838
|
+
: (this.dropdown.scrollHeight || 288)
|
|
839
|
+
const desiredHeight = Math.min(naturalHeight, maximumHeight)
|
|
840
|
+
const availableBelow = Math.max(0, viewportBottom - rect.bottom - gap - padding)
|
|
841
|
+
const availableAbove = Math.max(0, rect.top - viewportTop - gap - padding)
|
|
842
|
+
const placeAbove = availableBelow < Math.min(desiredHeight, 192) && availableAbove > availableBelow
|
|
843
|
+
const availableHeight = placeAbove ? availableAbove : availableBelow
|
|
844
|
+
const dropdownHeight = Math.max(96, Math.min(desiredHeight, availableHeight || desiredHeight))
|
|
845
|
+
const availableWidth = Math.max(0, viewport.width - (padding * 2))
|
|
846
|
+
const dropdownWidth = this.resolveDropdownWidth(rect.width, availableWidth)
|
|
847
|
+
const left = this.resolveDropdownLeft(rect, dropdownWidth, viewport)
|
|
848
|
+
|
|
849
|
+
this.dropdown.style.left = `${left}px`
|
|
850
|
+
this.dropdown.style.width = `${dropdownWidth}px`
|
|
851
|
+
this.dropdown.style.maxWidth = `${availableWidth || dropdownWidth}px`
|
|
852
|
+
this.dropdown.style.maxHeight = `${dropdownHeight}px`
|
|
853
|
+
this.results.style.maxHeight = `${Math.max(48, dropdownHeight - searchHeight - toolbarHeight - dropdownChrome)}px`
|
|
854
|
+
this.dropdown.style.top = `${placeAbove ? Math.max(viewportTop + padding, rect.top - dropdownHeight - gap) : rect.bottom + gap}px`
|
|
855
|
+
this.dropdown.dataset.placement = placeAbove ? "top" : "bottom"
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
// Returns a function measuring text in `element`'s font. Canvas is exact;
|
|
859
|
+
// environments without it (jsdom) fall back to an average glyph width.
|
|
860
|
+
textMeasurer(element, fallbackFontSize = 16) {
|
|
861
|
+
const view = this.select.ownerDocument.defaultView
|
|
862
|
+
const style = element ? view.getComputedStyle(element) : null
|
|
863
|
+
const fontSize = Number.parseFloat(style?.fontSize) || fallbackFontSize
|
|
864
|
+
const averageCharacterWidth = fontSize * 0.58
|
|
865
|
+
if (this.measureContext === undefined) {
|
|
866
|
+
this.measureContext = null
|
|
867
|
+
if (!/jsdom/i.test(view.navigator.userAgent)) {
|
|
868
|
+
try {
|
|
869
|
+
this.measureContext = this.select.ownerDocument.createElement("canvas").getContext("2d")
|
|
870
|
+
} catch {
|
|
871
|
+
this.measureContext = null
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
const context = this.measureContext
|
|
876
|
+
const font = style?.font || `${style?.fontWeight || 400} ${fontSize}px ${style?.fontFamily || "sans-serif"}`
|
|
877
|
+
// Menus re-measure on every keystroke, so cache widths per font. The cache
|
|
878
|
+
// is bounded so long-lived remote selects cannot grow it without limit.
|
|
879
|
+
this.textWidthCache ||= new Map()
|
|
880
|
+
if (this.textWidthCache.size > 5000) this.textWidthCache.clear()
|
|
881
|
+
return value => {
|
|
882
|
+
const text = String(value ?? "")
|
|
883
|
+
if (!text) return 0
|
|
884
|
+
if (!context) return Array.from(text).length * averageCharacterWidth
|
|
885
|
+
const key = `${font}\u0000${text}`
|
|
886
|
+
let width = this.textWidthCache.get(key)
|
|
887
|
+
if (width === undefined) {
|
|
888
|
+
context.font = font
|
|
889
|
+
width = context.measureText(text).width
|
|
890
|
+
this.textWidthCache.set(key, width)
|
|
891
|
+
}
|
|
892
|
+
return width
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
// The natural width of the open menu: its widest row plus option padding,
|
|
897
|
+
// icons, and the scrollbar. Callers clamp it to the control and viewport.
|
|
898
|
+
// Item widths are cached, so repeat renders (each keystroke) only measure
|
|
899
|
+
// rows they have not seen, and only new rows trigger DOM layout reads.
|
|
900
|
+
measureDropdownContentWidth() {
|
|
901
|
+
this.itemWidthCache ||= new WeakMap()
|
|
902
|
+
const renderedEntries = this.results.querySelectorAll("[data-tam-select-entry]")
|
|
903
|
+
let textWidth = null
|
|
904
|
+
const measureText = value => {
|
|
905
|
+
textWidth ||= this.textMeasurer(renderedEntries[0] || this.results)
|
|
906
|
+
return textWidth(value)
|
|
907
|
+
}
|
|
908
|
+
let measuredWidth = 0
|
|
909
|
+
let sawNewItem = this.dropdownContentWidth == null
|
|
910
|
+
this.visibleItems.forEach(entry => {
|
|
911
|
+
const item = entry.item
|
|
912
|
+
let width = item ? this.itemWidthCache.get(item) : undefined
|
|
913
|
+
if (width === undefined) {
|
|
914
|
+
const primaryWidth = item
|
|
915
|
+
? Math.max(measureText(item.label), measureText(item.detail))
|
|
916
|
+
: measureText(entry.label)
|
|
917
|
+
// Option and list padding, the dropdown border, and the selected check.
|
|
918
|
+
width = primaryWidth + 56 + (item?.image ? 40 : 0) + (item?.meta ? measureText(item.meta) + 20 : 0)
|
|
919
|
+
if (item) {
|
|
920
|
+
this.itemWidthCache.set(item, width)
|
|
921
|
+
sawNewItem = true
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
measuredWidth = Math.max(measuredWidth, width)
|
|
925
|
+
})
|
|
926
|
+
|
|
927
|
+
// Custom templates and truncated rows can be wider than their text
|
|
928
|
+
// estimate. Measure what actually overflows, but only for new content.
|
|
929
|
+
if (sawNewItem) {
|
|
930
|
+
renderedEntries.forEach(entry => {
|
|
931
|
+
let widestContent = 0
|
|
932
|
+
entry.querySelectorAll("*").forEach(element => {
|
|
933
|
+
if (element.childElementCount === 0) {
|
|
934
|
+
const visibleWidth = element.clientWidth || element.getBoundingClientRect().width || 0
|
|
935
|
+
// Flex children often stretch to the popup's current width. Only
|
|
936
|
+
// use DOM width when content genuinely overflows that box.
|
|
937
|
+
if (element.scrollWidth > visibleWidth + 1) {
|
|
938
|
+
widestContent = Math.max(widestContent, element.scrollWidth)
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
})
|
|
942
|
+
if (widestContent) measuredWidth = Math.max(measuredWidth, widestContent + 72)
|
|
943
|
+
})
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
const scrollbarWidth = Math.max(0, (this.results.offsetWidth || 0) - (this.results.clientWidth || 0))
|
|
947
|
+
return Math.ceil(measuredWidth + scrollbarWidth)
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
// width: "auto" sizes the closed control to its widest option, so picking
|
|
951
|
+
// a different option never resizes it, exactly like a native select.
|
|
952
|
+
applyFitWidth() {
|
|
953
|
+
if (!this.fitWidth) return
|
|
954
|
+
const view = this.select.ownerDocument.defaultView
|
|
955
|
+
const style = view.getComputedStyle(this.control)
|
|
956
|
+
const length = (value, fallback) => {
|
|
957
|
+
const number = Number.parseFloat(value)
|
|
958
|
+
return Number.isFinite(number) ? number : fallback
|
|
959
|
+
}
|
|
960
|
+
const textWidth = this.textMeasurer(this.control, 14)
|
|
961
|
+
let widest = textWidth(this.options.placeholder)
|
|
962
|
+
let hasImage = false
|
|
963
|
+
this.items.forEach(item => {
|
|
964
|
+
widest = Math.max(widest, textWidth(item.label))
|
|
965
|
+
if (item.image) hasImage = true
|
|
966
|
+
})
|
|
967
|
+
const gap = length(style.columnGap, 6)
|
|
968
|
+
const chrome = length(style.paddingLeft, 12) + length(style.paddingRight, 12) +
|
|
969
|
+
length(style.borderLeftWidth, 1) + length(style.borderRightWidth, 1)
|
|
970
|
+
const chevron = this.chevron.getBoundingClientRect().width || 14
|
|
971
|
+
// Reserve the clear button even while it is hidden so the width is stable.
|
|
972
|
+
const clear = this.options.clearable && this.canClear() ? (this.clearButton.getBoundingClientRect().width || 20) + gap : 0
|
|
973
|
+
// Tags add their own padding and a remove button around the label.
|
|
974
|
+
const tag = this.multiple ? 32 : 0
|
|
975
|
+
const image = hasImage && !this.multiple ? 40 : 0
|
|
976
|
+
const width = Math.ceil(widest + tag + image + chrome + gap + chevron + clear + 2)
|
|
977
|
+
this.wrapper.style.width = `${width}px`
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
detectDirection() {
|
|
981
|
+
// dir="auto" resolves from text content, not inheritance, so look past it
|
|
982
|
+
// to the nearest explicit direction.
|
|
983
|
+
const selectDir = this.select.closest('[dir="rtl" i], [dir="ltr" i]')?.getAttribute("dir")
|
|
984
|
+
if (selectDir) return selectDir.toLowerCase()
|
|
985
|
+
const docDir = document.documentElement.getAttribute("dir") || document.body?.getAttribute("dir")
|
|
986
|
+
if (docDir) return docDir
|
|
987
|
+
return "ltr"
|
|
241
988
|
}
|
|
242
989
|
|
|
243
990
|
findLabelElements() {
|
|
@@ -256,67 +1003,178 @@ export class TamSelect {
|
|
|
256
1003
|
}
|
|
257
1004
|
|
|
258
1005
|
readNativeOptions() {
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
Object.assign(item, {
|
|
265
|
-
value: option.value,
|
|
266
|
-
label: option.textContent.trim(),
|
|
267
|
-
detail: option.dataset.detail || null,
|
|
268
|
-
meta: option.dataset.meta || null,
|
|
269
|
-
image: option.dataset.image || null,
|
|
270
|
-
disabled: option.disabled,
|
|
271
|
-
selected: option.selected,
|
|
272
|
-
option
|
|
273
|
-
})
|
|
274
|
-
return item
|
|
275
|
-
})
|
|
1006
|
+
this.previousItemsByOption = new Map(this.items.map(item => [item.option, item]))
|
|
1007
|
+
const parsed = this.parseGroups()
|
|
1008
|
+
this.previousItemsByOption = null
|
|
1009
|
+
this.groupTree = parsed.tree
|
|
1010
|
+
this.items = parsed.flat
|
|
276
1011
|
|
|
277
1012
|
if (this.options.remoteUrl) {
|
|
278
|
-
const
|
|
279
|
-
this.remoteResults = this.remoteResults.
|
|
1013
|
+
const currentItems = new Map(this.items.map(item => [item.option, item]))
|
|
1014
|
+
this.remoteResults = this.remoteResults.map(item => currentItems.get(item.option)).filter(Boolean)
|
|
280
1015
|
this.updateVisibleItems(this.remoteResults)
|
|
281
1016
|
} else {
|
|
282
1017
|
this.filterLocal(false)
|
|
283
1018
|
}
|
|
284
1019
|
}
|
|
285
1020
|
|
|
1021
|
+
parseGroups() {
|
|
1022
|
+
const tree = []
|
|
1023
|
+
const flat = []
|
|
1024
|
+
const children = Array.from(this.select.children)
|
|
1025
|
+
|
|
1026
|
+
for (const child of children) {
|
|
1027
|
+
if (child.tagName === "OPTGROUP") {
|
|
1028
|
+
const group = { label: child.label, items: [], entries: [] }
|
|
1029
|
+
for (const option of child.querySelectorAll("option")) {
|
|
1030
|
+
if (option.value === "") continue
|
|
1031
|
+
const item = this.buildItem(option)
|
|
1032
|
+
item.group = group.label
|
|
1033
|
+
flat.push(item)
|
|
1034
|
+
group.items.push(item)
|
|
1035
|
+
group.entries.push({ type: "item", id: item.id, item, disabled: Boolean(item.disabled) })
|
|
1036
|
+
}
|
|
1037
|
+
if (group.items.length > 0) tree.push(group)
|
|
1038
|
+
} else if (child.tagName === "OPTION" && child.value !== "") {
|
|
1039
|
+
const item = this.buildItem(child)
|
|
1040
|
+
flat.push(item)
|
|
1041
|
+
tree.push({ type: "ungrouped", items: [item], entries: [{ type: "item", id: item.id, item, disabled: Boolean(item.disabled) }] })
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
return { tree, flat }
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
buildItem(option) {
|
|
1048
|
+
const attributes = {
|
|
1049
|
+
id: this.optionId(option),
|
|
1050
|
+
value: option.value,
|
|
1051
|
+
label: option.textContent.trim(),
|
|
1052
|
+
detail: option.dataset.detail || null,
|
|
1053
|
+
meta: option.dataset.meta || null,
|
|
1054
|
+
image: option.dataset.image || null,
|
|
1055
|
+
disabled: option.disabled || Boolean(option.closest("optgroup")?.disabled),
|
|
1056
|
+
selected: option.selected,
|
|
1057
|
+
option,
|
|
1058
|
+
group: null
|
|
1059
|
+
}
|
|
1060
|
+
const existing = this.previousItemsByOption?.get(option)
|
|
1061
|
+
return existing ? Object.assign(existing, attributes) : attributes
|
|
1062
|
+
}
|
|
1063
|
+
|
|
286
1064
|
selectedItems() {
|
|
287
|
-
return this.items.filter(item => item.option
|
|
1065
|
+
return this.items.filter(item => (item.option ? item.option.selected : item.selected))
|
|
288
1066
|
}
|
|
289
1067
|
|
|
290
1068
|
matchesLocalItem(item) {
|
|
291
1069
|
if (typeof this.options.matcher === "function") return Boolean(this.options.matcher(item, this.query))
|
|
292
|
-
|
|
293
|
-
if (!terms.length) return true
|
|
294
|
-
const searchableText = normalize([item.label, item.detail, item.meta].filter(Boolean).join(" "))
|
|
295
|
-
return terms.every(term => searchableText.includes(term))
|
|
1070
|
+
return Number.isFinite(this.searchScore(item))
|
|
296
1071
|
}
|
|
297
1072
|
|
|
298
1073
|
filterLocal(render = true) {
|
|
299
|
-
|
|
1074
|
+
let matches
|
|
1075
|
+
if (typeof this.options.matcher === "function") {
|
|
1076
|
+
matches = this.items.filter(item => this.matchesLocalItem(item))
|
|
1077
|
+
} else {
|
|
1078
|
+
matches = this.items
|
|
1079
|
+
.map((item, index) => ({ item, index, score: this.searchScore(item) }))
|
|
1080
|
+
.filter(match => Number.isFinite(match.score))
|
|
1081
|
+
if (this.options.sortByRelevance && normalize(this.query)) {
|
|
1082
|
+
matches.sort((left, right) => left.score - right.score || left.index - right.index)
|
|
1083
|
+
}
|
|
1084
|
+
matches = matches.map(match => match.item)
|
|
1085
|
+
}
|
|
1086
|
+
matches = this.sortResults(matches)
|
|
1087
|
+
this.updateVisibleItems(matches)
|
|
300
1088
|
if (render) this.renderDropdown()
|
|
301
1089
|
}
|
|
302
1090
|
|
|
1091
|
+
searchScore(item) {
|
|
1092
|
+
const terms = normalize(this.query).split(/\s+/).filter(Boolean)
|
|
1093
|
+
if (!terms.length) return 0
|
|
1094
|
+
const configuredFields = Array.isArray(this.options.searchFields) ? this.options.searchFields : ["label", "detail", "meta"]
|
|
1095
|
+
const fields = configuredFields
|
|
1096
|
+
.map((name, index) => ({ text: normalize(item[name]), weight: index * 0.25 }))
|
|
1097
|
+
.filter(field => field.text)
|
|
1098
|
+
|
|
1099
|
+
let total = 0
|
|
1100
|
+
for (const term of terms) {
|
|
1101
|
+
let best = Infinity
|
|
1102
|
+
fields.forEach(field => {
|
|
1103
|
+
const tokens = wordTokens(field.text)
|
|
1104
|
+
let score = Infinity
|
|
1105
|
+
if (field.text === term) score = 0
|
|
1106
|
+
else if (field.text.startsWith(term)) score = 0.5
|
|
1107
|
+
else if (tokens.includes(term)) score = 1
|
|
1108
|
+
else if (tokens.some(token => token.startsWith(term))) score = 1.5
|
|
1109
|
+
else {
|
|
1110
|
+
const position = field.text.indexOf(term)
|
|
1111
|
+
if (position >= 0) score = 2 + position / Math.max(field.text.length, 1)
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
if (!Number.isFinite(score) && this.options.fuzzySearch && term.length >= 3) {
|
|
1115
|
+
const maximum = term.length >= 6 ? 2 : 1
|
|
1116
|
+
const distance = tokens.reduce((closest, token) => Math.min(closest, boundedDistance(term, token, maximum)), maximum + 1)
|
|
1117
|
+
if (distance <= maximum) score = 4 + distance
|
|
1118
|
+
}
|
|
1119
|
+
best = Math.min(best, score + field.weight)
|
|
1120
|
+
})
|
|
1121
|
+
if (!Number.isFinite(best)) return Infinity
|
|
1122
|
+
total += best
|
|
1123
|
+
}
|
|
1124
|
+
return total
|
|
1125
|
+
}
|
|
1126
|
+
|
|
303
1127
|
updateVisibleItems(candidateItems, preserveActive = true) {
|
|
1128
|
+
this.matchedItems = candidateItems
|
|
1129
|
+
candidateItems = candidateItems.filter(item => !(this.options.hideSelected && item.selected))
|
|
304
1130
|
const previousId = preserveActive ? this.visibleItems[this.activeIndex]?.id : null
|
|
305
|
-
const
|
|
306
|
-
|
|
307
|
-
|
|
1131
|
+
const hasGroups = this.groupTree.some(group => group.type !== "ungrouped")
|
|
1132
|
+
|
|
1133
|
+
let entries
|
|
1134
|
+
if (!hasGroups) {
|
|
1135
|
+
entries = candidateItems
|
|
1136
|
+
.map(item => ({ type: "item", id: item.id, item, disabled: Boolean(item.disabled) }))
|
|
1137
|
+
} else {
|
|
1138
|
+
// Key on item ids (values may repeat) and keep each group's entries in
|
|
1139
|
+
// candidate order so relevance sorting and custom sorters still apply.
|
|
1140
|
+
const rank = new Map(candidateItems.map((item, index) => [item.id, index]))
|
|
1141
|
+
const byRank = (left, right) => rank.get(left.item.id) - rank.get(right.item.id)
|
|
1142
|
+
entries = []
|
|
1143
|
+
for (const group of this.groupTree) {
|
|
1144
|
+
if (group.type === "ungrouped") {
|
|
1145
|
+
for (const entry of group.entries) {
|
|
1146
|
+
if (rank.has(entry.item.id)) {
|
|
1147
|
+
entries.push(entry)
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
} else {
|
|
1151
|
+
const groupEntries = group.entries.filter(entry => rank.has(entry.item.id)).sort(byRank)
|
|
1152
|
+
if (groupEntries.length > 0) {
|
|
1153
|
+
entries.push({ type: "group-header", id: `group-${group.label}`, group: group.label })
|
|
1154
|
+
entries.push(...groupEntries)
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
308
1159
|
|
|
309
1160
|
const createEntry = this.createEntry()
|
|
310
1161
|
if (createEntry) entries.push(createEntry)
|
|
311
1162
|
|
|
312
1163
|
this.visibleItems = entries
|
|
313
1164
|
const preservedIndex = previousId ? entries.findIndex(entry => entry.id === previousId && !entry.disabled) : -1
|
|
314
|
-
|
|
1165
|
+
// Like a native select, a single selection opens on its current choice
|
|
1166
|
+
// until a search query asks for the best match instead.
|
|
1167
|
+
const selectedIndex = !this.multiple && !this.query.trim()
|
|
1168
|
+
? entries.findIndex(entry => entry.type === "item" && entry.item.selected && !entry.disabled)
|
|
1169
|
+
: -1
|
|
1170
|
+
const firstIndex = entries.findIndex(entry => !entry.disabled && entry.type !== "group-header")
|
|
1171
|
+
this.activeIndex = [preservedIndex, selectedIndex, firstIndex].find(index => index >= 0) ?? -1
|
|
315
1172
|
}
|
|
316
1173
|
|
|
317
1174
|
createEntry() {
|
|
318
1175
|
const label = this.query.trim()
|
|
319
1176
|
if (!this.options.creatable || !label) return null
|
|
1177
|
+
if (this.multiple && this.options.maximumSelectionLength > 0 && this.selectedItems().length >= this.options.maximumSelectionLength) return null
|
|
320
1178
|
const value = typeof this.options.createValue === "function" ? this.options.createValue(label) : label
|
|
321
1179
|
const normalizedValue = normalize(value)
|
|
322
1180
|
const normalizedLabel = normalize(label)
|
|
@@ -325,6 +1183,28 @@ export class TamSelect {
|
|
|
325
1183
|
return { type: "create", id: `${this.listboxId}-create`, label, value: String(value), disabled: false }
|
|
326
1184
|
}
|
|
327
1185
|
|
|
1186
|
+
typeahead(char) {
|
|
1187
|
+
if (!this.opened) return
|
|
1188
|
+
clearTimeout(this.typeaheadTimer)
|
|
1189
|
+
this.typeaheadBuffer += char
|
|
1190
|
+
this.typeaheadTimer = setTimeout(() => { this.typeaheadBuffer = "" }, 500)
|
|
1191
|
+
|
|
1192
|
+
const query = normalize(this.typeaheadBuffer)
|
|
1193
|
+
// A new first character cycles past the current option; further
|
|
1194
|
+
// characters refine the current match, so it is still a candidate.
|
|
1195
|
+
const offset = this.typeaheadBuffer.length > 1 ? 0 : 1
|
|
1196
|
+
const startIndex = this.activeIndex >= 0 ? this.activeIndex + offset : 0
|
|
1197
|
+
const candidates = [...this.visibleItems.slice(startIndex), ...this.visibleItems.slice(0, startIndex)]
|
|
1198
|
+
const match = candidates.find(entry =>
|
|
1199
|
+
entry.type !== "group-header" && !entry.disabled && normalize(entry.item?.label ?? entry.label).startsWith(query)
|
|
1200
|
+
)
|
|
1201
|
+
if (match) {
|
|
1202
|
+
const index = this.visibleItems.indexOf(match)
|
|
1203
|
+
this.activeIndex = index
|
|
1204
|
+
this.updateActiveOption()
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
|
|
328
1208
|
renderSelection() {
|
|
329
1209
|
const selected = this.selectedItems()
|
|
330
1210
|
this.values.replaceChildren()
|
|
@@ -340,64 +1220,302 @@ export class TamSelect {
|
|
|
340
1220
|
}
|
|
341
1221
|
|
|
342
1222
|
const hasValue = selected.length > 0
|
|
343
|
-
this.
|
|
344
|
-
this.
|
|
1223
|
+
const atLimit = this.multiple && this.options.maximumSelectionLength > 0 && selected.length >= this.options.maximumSelectionLength
|
|
1224
|
+
this.selectionLimitReached = atLimit
|
|
1225
|
+
this.values.classList.remove("hidden")
|
|
1226
|
+
setHidden(this.searchIcon, !this.searchable || !this.searchVisible)
|
|
1227
|
+
if (this.searchPanel) setHidden(this.searchPanel, !this.searchVisible)
|
|
345
1228
|
if (this.input) {
|
|
346
|
-
toggleClasses(this.input, this.classes.inputClosed,
|
|
1229
|
+
toggleClasses(this.input, this.classes.inputClosed, false)
|
|
347
1230
|
this.input.placeholder = this.multiple && !hasValue ? this.options.placeholder : this.options.searchPlaceholder
|
|
1231
|
+
this.input.disabled = this.select.disabled
|
|
348
1232
|
}
|
|
349
|
-
this.clearButton
|
|
1233
|
+
setHidden(this.clearButton, !this.options.clearable || !hasValue || !this.canClear() || this.select.disabled)
|
|
1234
|
+
this.updateSelectionToolbar()
|
|
350
1235
|
this.syncAria()
|
|
351
1236
|
}
|
|
352
1237
|
|
|
353
1238
|
makeTag(item) {
|
|
354
1239
|
const tag = document.createElement("span")
|
|
355
1240
|
tag.className = this.classes.tag
|
|
1241
|
+
tag.style.maxWidth = "100%"
|
|
1242
|
+
tag.style.minWidth = "0"
|
|
1243
|
+
tag.dataset.tagValue = item.value
|
|
356
1244
|
const label = document.createElement("span")
|
|
357
1245
|
label.className = "max-w-48 truncate"
|
|
358
|
-
label.
|
|
1246
|
+
label.style.minWidth = "0"
|
|
1247
|
+
label.style.overflow = "hidden"
|
|
1248
|
+
label.style.textOverflow = "ellipsis"
|
|
1249
|
+
label.style.whiteSpace = "nowrap"
|
|
1250
|
+
const template = this.renderTemplate(this.options.templateSelection, item, "selection")
|
|
1251
|
+
if (template) label.append(template)
|
|
1252
|
+
else label.textContent = item.label
|
|
359
1253
|
const remove = document.createElement("button")
|
|
360
1254
|
remove.type = "button"
|
|
361
1255
|
remove.className = this.classes.tagRemove
|
|
362
1256
|
remove.disabled = this.select.disabled
|
|
363
|
-
|
|
1257
|
+
const removeLabel = typeof this.options.removeLabel === "function" ? this.options.removeLabel(item) : this.options.removeLabel
|
|
1258
|
+
remove.setAttribute("aria-label", removeLabel)
|
|
364
1259
|
remove.innerHTML = ICONS.close
|
|
365
|
-
remove.addEventListener("click", event => { event.stopPropagation(); this.deselect(item
|
|
1260
|
+
remove.addEventListener("click", event => { event.stopPropagation(); this.deselect(item) })
|
|
366
1261
|
tag.append(label, remove)
|
|
1262
|
+
if (this.options.draggable && this.multiple && !this.select.disabled) {
|
|
1263
|
+
tag.setAttribute("draggable", "true")
|
|
1264
|
+
tag.style.cursor = "grab"
|
|
1265
|
+
tag.addEventListener("dragstart", event => this.onTagDragStart(event, item))
|
|
1266
|
+
tag.addEventListener("dragend", () => this.onTagDragEnd())
|
|
1267
|
+
tag.addEventListener("dragover", event => this.onTagDragOver(event))
|
|
1268
|
+
tag.addEventListener("dragenter", event => this.onTagDragEnter(event))
|
|
1269
|
+
tag.addEventListener("dragleave", event => this.onTagDragLeave(event))
|
|
1270
|
+
tag.addEventListener("drop", event => this.onTagDrop(event, item))
|
|
1271
|
+
}
|
|
367
1272
|
return tag
|
|
368
1273
|
}
|
|
369
1274
|
|
|
1275
|
+
onTagDragStart(event, item) {
|
|
1276
|
+
event.dataTransfer.effectAllowed = "move"
|
|
1277
|
+
event.dataTransfer.setData("text/plain", item.value)
|
|
1278
|
+
this.draggedItem = item
|
|
1279
|
+
const scheduleFrame = window.requestAnimationFrame || (callback => window.setTimeout(callback, 0))
|
|
1280
|
+
scheduleFrame(() => {
|
|
1281
|
+
toggleClasses(event.target, this.classes.tagDragging, true)
|
|
1282
|
+
})
|
|
1283
|
+
}
|
|
1284
|
+
|
|
1285
|
+
onTagDragEnd() {
|
|
1286
|
+
this.draggedItem = null
|
|
1287
|
+
this.values.querySelectorAll("[data-tag-value]").forEach(el => {
|
|
1288
|
+
toggleClasses(el, this.classes.tagDragging, false)
|
|
1289
|
+
toggleClasses(el, this.classes.tagDragOver, false)
|
|
1290
|
+
})
|
|
1291
|
+
}
|
|
1292
|
+
|
|
1293
|
+
onTagDragOver(event) {
|
|
1294
|
+
event.preventDefault()
|
|
1295
|
+
event.dataTransfer.dropEffect = "move"
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
onTagDragEnter(event) {
|
|
1299
|
+
event.preventDefault()
|
|
1300
|
+
const tag = event.target.closest("[data-tag-value]")
|
|
1301
|
+
if (tag && tag.dataset.tagValue !== this.draggedItem?.value) {
|
|
1302
|
+
toggleClasses(tag, this.classes.tagDragOver, true)
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
|
|
1306
|
+
onTagDragLeave(event) {
|
|
1307
|
+
const tag = event.target.closest("[data-tag-value]")
|
|
1308
|
+
if (tag) toggleClasses(tag, this.classes.tagDragOver, false)
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
onTagDrop(event, targetItem) {
|
|
1312
|
+
event.preventDefault()
|
|
1313
|
+
const sourceItem = this.draggedItem
|
|
1314
|
+
if (!sourceItem || sourceItem === targetItem) return
|
|
1315
|
+
|
|
1316
|
+
const sourceIndex = this.selectedItems().indexOf(sourceItem)
|
|
1317
|
+
const targetIndex = this.selectedItems().indexOf(targetItem)
|
|
1318
|
+
if (sourceIndex < 0 || targetIndex < 0) return
|
|
1319
|
+
|
|
1320
|
+
const option = sourceItem.option
|
|
1321
|
+
const targetOption = targetItem.option
|
|
1322
|
+
// Moving an option next to one in another optgroup would change its group.
|
|
1323
|
+
if (option && targetOption && option.parentElement === targetOption.parentElement) {
|
|
1324
|
+
if (sourceIndex < targetIndex) {
|
|
1325
|
+
targetOption.after(option)
|
|
1326
|
+
} else {
|
|
1327
|
+
targetOption.before(option)
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
this.readNativeOptions()
|
|
1332
|
+
this.renderSelection()
|
|
1333
|
+
this.emit("tam-select:reorder", { value: this.value, items: this.selectedItems() })
|
|
1334
|
+
}
|
|
1335
|
+
|
|
370
1336
|
renderDropdown() {
|
|
371
1337
|
if (!this.opened) return
|
|
372
|
-
this.
|
|
373
|
-
this.
|
|
1338
|
+
this.updateSelectionToolbar()
|
|
1339
|
+
this.results.replaceChildren()
|
|
1340
|
+
this.results.setAttribute("aria-busy", String(this.loading))
|
|
374
1341
|
|
|
375
1342
|
const remaining = Math.max(0, this.options.minQueryLength - this.query.trim().length)
|
|
376
1343
|
if (this.options.remoteUrl && remaining > 0) {
|
|
377
1344
|
const text = typeof this.options.inputTooShortText === "function" ? this.options.inputTooShortText(remaining) : this.options.inputTooShortText
|
|
378
1345
|
this.renderMessage(text)
|
|
379
|
-
|
|
1346
|
+
this.updateStatus(text)
|
|
1347
|
+
return this.finishDropdownRender()
|
|
380
1348
|
}
|
|
381
|
-
if (this.error) {
|
|
1349
|
+
if (this.error && !this.errorAfterResults) {
|
|
382
1350
|
const error = document.createElement("div")
|
|
383
1351
|
error.className = this.classes.error
|
|
384
1352
|
error.setAttribute("role", "alert")
|
|
385
1353
|
error.textContent = this.error
|
|
386
|
-
this.
|
|
387
|
-
|
|
1354
|
+
this.results.append(error)
|
|
1355
|
+
this.updateStatus(this.error)
|
|
1356
|
+
return this.finishDropdownRender()
|
|
388
1357
|
}
|
|
389
1358
|
if (this.loading && this.loadingPage === 1) {
|
|
390
1359
|
this.renderMessage(this.options.loadingText, true)
|
|
391
|
-
|
|
1360
|
+
this.updateStatus(this.options.loadingText)
|
|
1361
|
+
return this.finishDropdownRender()
|
|
392
1362
|
}
|
|
393
1363
|
|
|
394
|
-
|
|
395
|
-
|
|
1364
|
+
// emptyState covers an empty list; a search with no matches uses
|
|
1365
|
+
// noResultsState when one is set.
|
|
1366
|
+
const searching = Boolean(this.query.trim()) && Boolean(this.options.noResultsState)
|
|
1367
|
+
if (this.options.emptyState && !this.visibleItems.length && !this.loading && !searching) {
|
|
1368
|
+
const empty = document.createElement("div")
|
|
1369
|
+
empty.className = this.classes.message
|
|
1370
|
+
if (typeof this.options.emptyState === "function") this.options.emptyState(empty)
|
|
1371
|
+
else empty.textContent = this.options.emptyState
|
|
1372
|
+
this.results.append(empty)
|
|
1373
|
+
this.updateStatus("")
|
|
1374
|
+
return this.finishDropdownRender()
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
// Wrapped rows have variable heights, while this virtualizer deliberately
|
|
1378
|
+
// uses a fixed row height. Render the full list so multiline rows never
|
|
1379
|
+
// overlap, disappear, or produce incorrect scroll spacers.
|
|
1380
|
+
const largeList = this.options.virtualScroll || this.visibleItems.length > this.options.virtualScrollThreshold
|
|
1381
|
+
this.wrapOptionText = this.options.wrapOptionText ?? !largeList
|
|
1382
|
+
const shouldVirtual = !this.wrapOptionText && largeList
|
|
1383
|
+
this.isVirtualScroll = shouldVirtual
|
|
1384
|
+
if (shouldVirtual && this.visibleItems.length > 0) {
|
|
1385
|
+
this.renderVirtualDropdown()
|
|
1386
|
+
} else {
|
|
1387
|
+
this.renderStandardDropdown()
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
if (!this.visibleItems.length) {
|
|
1391
|
+
if (this.options.noResultsState) {
|
|
1392
|
+
const noResults = document.createElement("div")
|
|
1393
|
+
noResults.className = this.classes.message
|
|
1394
|
+
if (typeof this.options.noResultsState === "function") this.options.noResultsState(noResults)
|
|
1395
|
+
else noResults.textContent = this.options.noResultsState
|
|
1396
|
+
this.results.append(noResults)
|
|
1397
|
+
} else {
|
|
1398
|
+
this.renderMessage(this.options.noResultsText)
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
1401
|
+
if (this.error && this.errorAfterResults) {
|
|
1402
|
+
const error = document.createElement("div")
|
|
1403
|
+
error.className = this.classes.error
|
|
1404
|
+
error.setAttribute("role", "alert")
|
|
1405
|
+
error.textContent = this.error
|
|
1406
|
+
this.results.append(error)
|
|
1407
|
+
}
|
|
396
1408
|
if (this.loading && this.loadingPage > 1) this.renderMessage(this.options.loadingText, true)
|
|
397
|
-
else if (this.hasMore) this.
|
|
1409
|
+
else if (this.hasMore) this.renderLoadMore()
|
|
1410
|
+
const resultCount = this.visibleItems.filter(entry => entry.type === "item").length
|
|
1411
|
+
const statusText = resultCount || this.visibleItems.length
|
|
1412
|
+
? (typeof this.options.resultsText === "function" ? this.options.resultsText(resultCount) : this.options.resultsText)
|
|
1413
|
+
: this.options.noResultsText
|
|
1414
|
+
this.updateStatus(statusText)
|
|
1415
|
+
this.finishDropdownRender()
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1418
|
+
finishDropdownRender() {
|
|
1419
|
+
this.syncActiveDescendant()
|
|
1420
|
+
this.dropdownWidthStale = true
|
|
1421
|
+
if (this.portalDropdown) this.updateDropdownPosition()
|
|
1422
|
+
else this.updateInlineDropdownWidth()
|
|
1423
|
+
// A short first page never scrolls, so the scroll listener would never
|
|
1424
|
+
// ask for the next one. Load it as soon as the panel has room.
|
|
1425
|
+
if (this.options.remoteUrl && this.hasMore && !this.loading && !this.error && this.results.clientHeight > 0 &&
|
|
1426
|
+
this.results.scrollHeight <= this.results.clientHeight + 32) {
|
|
1427
|
+
const scheduleFrame = window.requestAnimationFrame || (callback => window.setTimeout(callback, 0))
|
|
1428
|
+
scheduleFrame(() => { if (this.opened && !this.destroyed) this.onScroll() })
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
loadNextPage() {
|
|
1433
|
+
if (this.options.remoteUrl && this.hasMore && !this.loading) this.loadRemote(this.nextPage || this.page + 1, true)
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
renderLoadMore() {
|
|
1437
|
+
const button = document.createElement("button")
|
|
1438
|
+
button.type = "button"
|
|
1439
|
+
button.className = this.classes.loadMore
|
|
1440
|
+
button.textContent = this.options.loadMoreText
|
|
1441
|
+
button.dataset.tamSelectLoadMore = ""
|
|
1442
|
+
// Keep focus in the search input while the pointer presses the button.
|
|
1443
|
+
button.addEventListener("pointerdown", event => event.preventDefault())
|
|
1444
|
+
button.addEventListener("click", event => {
|
|
1445
|
+
event.stopPropagation()
|
|
1446
|
+
this.loadNextPage()
|
|
1447
|
+
})
|
|
1448
|
+
this.results.append(button)
|
|
1449
|
+
}
|
|
1450
|
+
|
|
1451
|
+
renderStandardDropdown() {
|
|
1452
|
+
for (const entry of this.visibleItems) {
|
|
1453
|
+
if (entry.type === "group-header") {
|
|
1454
|
+
this.results.append(this.makeGroupHeader(entry))
|
|
1455
|
+
} else {
|
|
1456
|
+
const index = this.visibleItems.indexOf(entry)
|
|
1457
|
+
this.results.append(this.makeOption(entry, index))
|
|
1458
|
+
}
|
|
1459
|
+
}
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1462
|
+
renderVirtualDropdown(preservedScrollTop = null, container = this.results) {
|
|
1463
|
+
this.isVirtualScroll = true
|
|
1464
|
+
const itemHeight = this.options.virtualItemHeight
|
|
1465
|
+
const buffer = this.options.virtualScrollBuffer
|
|
1466
|
+
const total = this.visibleItems.length
|
|
1467
|
+
const totalHeight = total * itemHeight
|
|
1468
|
+
const scrollTop = preservedScrollTop ?? this.results.scrollTop ?? 0
|
|
1469
|
+
const viewportHeight = this.results.clientHeight || 288
|
|
1470
|
+
const start = Math.max(0, Math.floor(scrollTop / itemHeight) - buffer)
|
|
1471
|
+
const end = Math.min(total, Math.ceil((scrollTop + viewportHeight) / itemHeight) + buffer)
|
|
1472
|
+
|
|
1473
|
+
if (start > 0) {
|
|
1474
|
+
const topSpacer = document.createElement("div")
|
|
1475
|
+
topSpacer.style.height = `${start * itemHeight}px`
|
|
1476
|
+
topSpacer.dataset.virtualSpacer = "top"
|
|
1477
|
+
container.append(topSpacer)
|
|
1478
|
+
}
|
|
1479
|
+
|
|
1480
|
+
for (let i = start; i < end; i++) {
|
|
1481
|
+
const entry = this.visibleItems[i]
|
|
1482
|
+
if (entry.type === "group-header") {
|
|
1483
|
+
container.append(this.makeGroupHeader(entry))
|
|
1484
|
+
} else {
|
|
1485
|
+
container.append(this.makeOption(entry, i))
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
if (end < total) {
|
|
1490
|
+
const bottomSpacer = document.createElement("div")
|
|
1491
|
+
bottomSpacer.style.height = `${(total - end) * itemHeight}px`
|
|
1492
|
+
bottomSpacer.dataset.virtualSpacer = "bottom"
|
|
1493
|
+
container.append(bottomSpacer)
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
rerenderVirtualItems(targetScrollTop = null) {
|
|
1498
|
+
if (!this.isVirtualScroll || !this.opened) return
|
|
1499
|
+
// Replacing virtual rows can make browsers clamp scrollTop to zero. Build
|
|
1500
|
+
// the next window off-DOM, swap it atomically, then restore the position.
|
|
1501
|
+
const scrollTop = targetScrollTop ?? (this.results.scrollTop || 0)
|
|
1502
|
+
const fragment = document.createDocumentFragment()
|
|
1503
|
+
this.renderVirtualDropdown(scrollTop, fragment)
|
|
1504
|
+
this.results.replaceChildren(fragment)
|
|
1505
|
+
this.results.scrollTop = scrollTop
|
|
398
1506
|
this.syncActiveDescendant()
|
|
399
1507
|
}
|
|
400
1508
|
|
|
1509
|
+
makeGroupHeader(entry) {
|
|
1510
|
+
const header = document.createElement("div")
|
|
1511
|
+
header.className = this.classes.groupHeader
|
|
1512
|
+
header.setAttribute("role", "presentation")
|
|
1513
|
+
header.textContent = entry.group
|
|
1514
|
+
header.style.pointerEvents = "none"
|
|
1515
|
+
header.dataset.tamSelectGroup = entry.group
|
|
1516
|
+
return header
|
|
1517
|
+
}
|
|
1518
|
+
|
|
401
1519
|
makeOption(entry, index) {
|
|
402
1520
|
const option = document.createElement("div")
|
|
403
1521
|
option.id = entry.id
|
|
@@ -421,50 +1539,200 @@ export class TamSelect {
|
|
|
421
1539
|
if (item.meta) {
|
|
422
1540
|
const meta = document.createElement("span")
|
|
423
1541
|
meta.className = this.classes.optionMeta
|
|
424
|
-
meta
|
|
1542
|
+
this.renderHighlightedText(meta, item.meta)
|
|
425
1543
|
option.append(meta)
|
|
426
1544
|
}
|
|
427
1545
|
if (item.selected) {
|
|
428
1546
|
const check = document.createElement("span")
|
|
1547
|
+
check.className = this.classes.optionCheck
|
|
429
1548
|
check.innerHTML = ICONS.check
|
|
430
1549
|
option.append(check)
|
|
431
1550
|
}
|
|
432
1551
|
}
|
|
433
1552
|
|
|
434
|
-
option.addEventListener("
|
|
1553
|
+
option.addEventListener("pointerenter", () => {
|
|
1554
|
+
if (entry.disabled || this.activeIndex === index) return
|
|
1555
|
+
this.activeIndex = index
|
|
1556
|
+
this.updateActiveOption(false)
|
|
1557
|
+
})
|
|
435
1558
|
option.addEventListener("click", () => this.activateEntry(entry))
|
|
436
1559
|
return option
|
|
437
1560
|
}
|
|
438
1561
|
|
|
439
1562
|
makeItemContent(item, selected = false) {
|
|
440
1563
|
const content = document.createElement("span")
|
|
441
|
-
content.className = this.classes.optionContent
|
|
442
|
-
|
|
1564
|
+
content.className = selected ? this.classes.selectionContent : this.classes.optionContent
|
|
1565
|
+
content.style.minWidth = "0"
|
|
1566
|
+
content.style.maxWidth = "100%"
|
|
1567
|
+
const template = this.renderTemplate(selected ? this.options.templateSelection : this.options.templateResult, item, selected ? "selection" : "result")
|
|
1568
|
+
if (template) {
|
|
1569
|
+
content.append(template)
|
|
1570
|
+
return content
|
|
1571
|
+
}
|
|
1572
|
+
if (selected) {
|
|
1573
|
+
const label = document.createElement("span")
|
|
1574
|
+
label.className = this.classes.selectionLabel
|
|
1575
|
+
label.style.minWidth = "0"
|
|
1576
|
+
label.style.overflow = "hidden"
|
|
1577
|
+
label.style.textOverflow = "ellipsis"
|
|
1578
|
+
label.style.whiteSpace = "nowrap"
|
|
1579
|
+
label.textContent = item.label
|
|
1580
|
+
if (this.options.optionTooltip) label.title = item.label
|
|
1581
|
+
content.append(label)
|
|
1582
|
+
return content
|
|
1583
|
+
}
|
|
443
1584
|
if (item.image) {
|
|
444
|
-
const image = document.createElement("img")
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
1585
|
+
const image = this.options.lazyLoadImages ? this.makeLazyImage(item) : document.createElement("img")
|
|
1586
|
+
if (!this.options.lazyLoadImages) {
|
|
1587
|
+
image.className = this.classes.optionImage
|
|
1588
|
+
image.src = item.image
|
|
1589
|
+
image.alt = ""
|
|
1590
|
+
image.loading = "lazy"
|
|
1591
|
+
}
|
|
449
1592
|
content.append(image)
|
|
450
1593
|
}
|
|
451
1594
|
const text = document.createElement("span")
|
|
452
1595
|
text.className = this.classes.optionText
|
|
1596
|
+
text.style.minWidth = "0"
|
|
1597
|
+
text.style.overflow = "hidden"
|
|
453
1598
|
const label = document.createElement("span")
|
|
454
|
-
label.className =
|
|
455
|
-
|
|
1599
|
+
label.className = [
|
|
1600
|
+
this.classes.optionLabel,
|
|
1601
|
+
this.wrapOptionText ? this.classes.optionLabelWrap : "truncate"
|
|
1602
|
+
].filter(Boolean).join(" ")
|
|
1603
|
+
if (!this.wrapOptionText) {
|
|
1604
|
+
label.style.overflow = "hidden"
|
|
1605
|
+
label.style.textOverflow = "ellipsis"
|
|
1606
|
+
label.style.whiteSpace = "nowrap"
|
|
1607
|
+
}
|
|
1608
|
+
if (this.options.optionTooltip) label.title = item.label
|
|
1609
|
+
this.renderHighlightedText(label, item.label)
|
|
456
1610
|
text.append(label)
|
|
457
1611
|
if (item.detail) {
|
|
458
1612
|
const detail = document.createElement("span")
|
|
459
|
-
detail.className =
|
|
460
|
-
|
|
1613
|
+
detail.className = [
|
|
1614
|
+
this.classes.optionDetail,
|
|
1615
|
+
this.wrapOptionText ? this.classes.optionDetailWrap : "truncate"
|
|
1616
|
+
].filter(Boolean).join(" ")
|
|
1617
|
+
if (!this.wrapOptionText) {
|
|
1618
|
+
detail.style.overflow = "hidden"
|
|
1619
|
+
detail.style.textOverflow = "ellipsis"
|
|
1620
|
+
detail.style.whiteSpace = "nowrap"
|
|
1621
|
+
}
|
|
1622
|
+
if (this.options.optionTooltip) detail.title = item.detail
|
|
1623
|
+
this.renderHighlightedText(detail, item.detail)
|
|
461
1624
|
text.append(detail)
|
|
462
1625
|
}
|
|
463
1626
|
content.append(text)
|
|
464
1627
|
return content
|
|
465
1628
|
}
|
|
466
1629
|
|
|
1630
|
+
renderTemplate(template, item, context) {
|
|
1631
|
+
if (typeof template !== "function") return null
|
|
1632
|
+
const rendered = template(item, { tamSelect: this, context })
|
|
1633
|
+
if (rendered == null || rendered === false) return null
|
|
1634
|
+
if (rendered instanceof Node) return rendered
|
|
1635
|
+
const text = document.createElement("span")
|
|
1636
|
+
text.textContent = String(rendered)
|
|
1637
|
+
return text
|
|
1638
|
+
}
|
|
1639
|
+
|
|
1640
|
+
makeLazyImage(item) {
|
|
1641
|
+
const image = document.createElement("img")
|
|
1642
|
+
image.className = this.classes.optionImage
|
|
1643
|
+
image.alt = ""
|
|
1644
|
+
image.dataset.lazySrc = item.image
|
|
1645
|
+
if (this.lazyObserver) this.lazyObserver.observe(image)
|
|
1646
|
+
else image.src = item.image
|
|
1647
|
+
return image
|
|
1648
|
+
}
|
|
1649
|
+
|
|
1650
|
+
initLazyObserver() {
|
|
1651
|
+
if (!this.options.lazyLoadImages) return
|
|
1652
|
+
this.lazyObserver = new IntersectionObserver((entries) => {
|
|
1653
|
+
for (const entry of entries) {
|
|
1654
|
+
if (entry.isIntersecting) {
|
|
1655
|
+
const img = entry.target
|
|
1656
|
+
if (img.dataset.lazySrc) {
|
|
1657
|
+
img.src = img.dataset.lazySrc
|
|
1658
|
+
delete img.dataset.lazySrc
|
|
1659
|
+
}
|
|
1660
|
+
this.lazyObserver.unobserve(img)
|
|
1661
|
+
}
|
|
1662
|
+
}
|
|
1663
|
+
}, { root: this.dropdown, rootMargin: "50px" })
|
|
1664
|
+
}
|
|
1665
|
+
|
|
1666
|
+
renderHighlightedText(element, value) {
|
|
1667
|
+
const text = String(value ?? "")
|
|
1668
|
+
const terms = normalize(this.query).split(/\s+/).filter(Boolean)
|
|
1669
|
+
if (!this.options.highlightMatches || !terms.length) {
|
|
1670
|
+
element.textContent = text
|
|
1671
|
+
return
|
|
1672
|
+
}
|
|
1673
|
+
|
|
1674
|
+
const positions = []
|
|
1675
|
+
let offset = 0
|
|
1676
|
+
let normalizedText = ""
|
|
1677
|
+
for (const character of text) {
|
|
1678
|
+
const start = offset
|
|
1679
|
+
offset += character.length
|
|
1680
|
+
const normalizedCharacter = fold(character)
|
|
1681
|
+
normalizedText += normalizedCharacter
|
|
1682
|
+
for (let index = 0; index < normalizedCharacter.length; index += 1) positions.push({ start, end: offset })
|
|
1683
|
+
}
|
|
1684
|
+
|
|
1685
|
+
const ranges = []
|
|
1686
|
+
terms.forEach(term => {
|
|
1687
|
+
let from = 0
|
|
1688
|
+
while (from < normalizedText.length) {
|
|
1689
|
+
const index = normalizedText.indexOf(term, from)
|
|
1690
|
+
if (index < 0) break
|
|
1691
|
+
const first = positions[index]
|
|
1692
|
+
const last = positions[index + term.length - 1]
|
|
1693
|
+
if (first && last) ranges.push([first.start, last.end])
|
|
1694
|
+
from = index + Math.max(term.length, 1)
|
|
1695
|
+
}
|
|
1696
|
+
})
|
|
1697
|
+
if (!ranges.length) {
|
|
1698
|
+
element.textContent = text
|
|
1699
|
+
return
|
|
1700
|
+
}
|
|
1701
|
+
|
|
1702
|
+
ranges.sort((left, right) => left[0] - right[0] || left[1] - right[1])
|
|
1703
|
+
const merged = []
|
|
1704
|
+
ranges.forEach(range => {
|
|
1705
|
+
const previous = merged.at(-1)
|
|
1706
|
+
if (previous && range[0] <= previous[1]) previous[1] = Math.max(previous[1], range[1])
|
|
1707
|
+
else merged.push([...range])
|
|
1708
|
+
})
|
|
1709
|
+
|
|
1710
|
+
let cursor = 0
|
|
1711
|
+
merged.forEach(([start, end]) => {
|
|
1712
|
+
if (start > cursor) element.append(document.createTextNode(text.slice(cursor, start)))
|
|
1713
|
+
const mark = document.createElement("mark")
|
|
1714
|
+
mark.className = this.classes.highlight
|
|
1715
|
+
mark.textContent = text.slice(start, end)
|
|
1716
|
+
element.append(mark)
|
|
1717
|
+
cursor = end
|
|
1718
|
+
})
|
|
1719
|
+
if (cursor < text.length) element.append(document.createTextNode(text.slice(cursor)))
|
|
1720
|
+
}
|
|
1721
|
+
|
|
1722
|
+
updateStatus(text) {
|
|
1723
|
+
this.status.textContent = String(text ?? "")
|
|
1724
|
+
}
|
|
1725
|
+
|
|
467
1726
|
renderMessage(text, spinner = false) {
|
|
1727
|
+
if (this.options.loadingState && spinner) {
|
|
1728
|
+
const state = document.createElement("div")
|
|
1729
|
+
state.className = this.classes.message
|
|
1730
|
+
state.setAttribute("role", "status")
|
|
1731
|
+
if (typeof this.options.loadingState === "function") this.options.loadingState(state)
|
|
1732
|
+
else state.textContent = this.options.loadingState
|
|
1733
|
+
this.results.append(state)
|
|
1734
|
+
return
|
|
1735
|
+
}
|
|
468
1736
|
const message = document.createElement("div")
|
|
469
1737
|
message.className = this.classes.message
|
|
470
1738
|
message.setAttribute("role", "status")
|
|
@@ -478,10 +1746,11 @@ export class TamSelect {
|
|
|
478
1746
|
} else {
|
|
479
1747
|
message.textContent = text
|
|
480
1748
|
}
|
|
481
|
-
this.
|
|
1749
|
+
this.results.append(message)
|
|
482
1750
|
}
|
|
483
1751
|
|
|
484
1752
|
handleKeydown(event) {
|
|
1753
|
+
if (this.composing || event.isComposing || event.keyCode === 229) return
|
|
485
1754
|
if (this.select.disabled || event.target.closest("button") && event.target !== this.trigger) return
|
|
486
1755
|
|
|
487
1756
|
if (["ArrowDown", "ArrowUp"].includes(event.key)) {
|
|
@@ -494,7 +1763,7 @@ export class TamSelect {
|
|
|
494
1763
|
event.preventDefault()
|
|
495
1764
|
if (!this.opened) return this.open()
|
|
496
1765
|
this.activateEntry(this.visibleItems[this.activeIndex])
|
|
497
|
-
} else if (event.key === " " && this.trigger) {
|
|
1766
|
+
} else if (event.key === " " && event.target === this.trigger) {
|
|
498
1767
|
event.preventDefault()
|
|
499
1768
|
this.open()
|
|
500
1769
|
} else if (event.key === "Escape" && this.opened) {
|
|
@@ -503,11 +1772,33 @@ export class TamSelect {
|
|
|
503
1772
|
this.focusTarget.focus()
|
|
504
1773
|
} else if (event.key === "Backspace" && this.multiple && this.input && !this.input.value) {
|
|
505
1774
|
const last = this.selectedItems().at(-1)
|
|
506
|
-
if (last) this.deselect(last
|
|
1775
|
+
if (last) this.deselect(last)
|
|
507
1776
|
} else if (event.key === "Tab") {
|
|
508
|
-
this.
|
|
509
|
-
|
|
510
|
-
|
|
1777
|
+
const action = this.selectionToolbar?.querySelector("button:not(:disabled)")
|
|
1778
|
+
if (this.opened && !event.shiftKey && action) {
|
|
1779
|
+
event.preventDefault()
|
|
1780
|
+
action.focus()
|
|
1781
|
+
return
|
|
1782
|
+
}
|
|
1783
|
+
this.close(false)
|
|
1784
|
+
} else if (event.key === "Home" && this.opened) {
|
|
1785
|
+
event.preventDefault()
|
|
1786
|
+
this.moveActiveToFirst()
|
|
1787
|
+
} else if (event.key === "End" && this.opened) {
|
|
1788
|
+
event.preventDefault()
|
|
1789
|
+
this.moveActiveToLast()
|
|
1790
|
+
} else if (event.key === "a" && (event.ctrlKey || event.metaKey) && this.multiple && this.opened) {
|
|
1791
|
+
event.preventDefault()
|
|
1792
|
+
this.toggleAll()
|
|
1793
|
+
} else if (event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {
|
|
1794
|
+
if (this.opened) {
|
|
1795
|
+
// Keys typed into the search input are query text that the input
|
|
1796
|
+
// event filters on; typeahead there would move the active option
|
|
1797
|
+
// ahead of the filter. Typeahead is for a focused trigger only.
|
|
1798
|
+
if (event.target !== this.input) this.typeahead(event.key)
|
|
1799
|
+
} else if (this.input) {
|
|
1800
|
+
this.open(false)
|
|
1801
|
+
}
|
|
511
1802
|
}
|
|
512
1803
|
}
|
|
513
1804
|
|
|
@@ -516,29 +1807,115 @@ export class TamSelect {
|
|
|
516
1807
|
let next = this.activeIndex
|
|
517
1808
|
for (let count = 0; count < this.visibleItems.length; count += 1) {
|
|
518
1809
|
next = (next + direction + this.visibleItems.length) % this.visibleItems.length
|
|
519
|
-
|
|
1810
|
+
const entry = this.visibleItems[next]
|
|
1811
|
+
if (entry.type !== "group-header" && !entry.disabled) {
|
|
520
1812
|
this.activeIndex = next
|
|
521
1813
|
return this.updateActiveOption()
|
|
522
1814
|
}
|
|
523
1815
|
}
|
|
524
1816
|
}
|
|
525
1817
|
|
|
526
|
-
|
|
527
|
-
this.
|
|
1818
|
+
moveActiveToFirst() {
|
|
1819
|
+
if (!this.visibleItems.length) return
|
|
1820
|
+
const first = this.visibleItems.findIndex(entry => entry.type !== "group-header" && !entry.disabled)
|
|
1821
|
+
if (first >= 0) { this.activeIndex = first; this.updateActiveOption() }
|
|
1822
|
+
}
|
|
1823
|
+
|
|
1824
|
+
moveActiveToLast() {
|
|
1825
|
+
if (!this.visibleItems.length) return
|
|
1826
|
+
const last = this.visibleItems.findLastIndex(entry => entry.type !== "group-header" && !entry.disabled)
|
|
1827
|
+
if (last >= 0) { this.activeIndex = last; this.updateActiveOption() }
|
|
1828
|
+
}
|
|
1829
|
+
|
|
1830
|
+
toggleAll() {
|
|
1831
|
+
const matches = this.bulkCandidates()
|
|
1832
|
+
const atLimit = this.options.maximumSelectionLength > 0 && this.selectedItems().length >= this.options.maximumSelectionLength
|
|
1833
|
+
if (matches.length && (matches.every(item => item.selected) || (atLimit && matches.some(item => item.selected)))) this.deselectAll()
|
|
1834
|
+
else this.selectAll()
|
|
1835
|
+
}
|
|
1836
|
+
|
|
1837
|
+
bulkCandidates() {
|
|
1838
|
+
if (this.options.remoteUrl && (this.loading || this.error || this.query.trim().length < this.options.minQueryLength)) return []
|
|
1839
|
+
return (this.matchedItems || []).filter(item => !item.disabled)
|
|
1840
|
+
}
|
|
1841
|
+
|
|
1842
|
+
/** Select loaded options matching the current search, up to the selection limit. */
|
|
1843
|
+
selectAll() {
|
|
1844
|
+
this.changeMatchingSelection(true)
|
|
1845
|
+
}
|
|
1846
|
+
|
|
1847
|
+
/** Deselect loaded matches, including matches hidden by hideSelected. */
|
|
1848
|
+
deselectAll() {
|
|
1849
|
+
this.changeMatchingSelection(false)
|
|
1850
|
+
}
|
|
1851
|
+
|
|
1852
|
+
changeMatchingSelection(selected) {
|
|
1853
|
+
if (!this.multiple || this.select.disabled || this.destroyed) return
|
|
1854
|
+
const changed = []
|
|
1855
|
+
let count = this.selectedItems().length
|
|
1856
|
+
for (const item of this.bulkCandidates()) {
|
|
1857
|
+
if (item.selected === selected) continue
|
|
1858
|
+
if (selected && this.options.maximumSelectionLength > 0 && count >= this.options.maximumSelectionLength) break
|
|
1859
|
+
if (!this.emit(selected ? "tam-select:selecting" : "tam-select:unselecting", { item }, true)) continue
|
|
1860
|
+
item.selected = selected
|
|
1861
|
+
item.option.selected = selected
|
|
1862
|
+
count += selected ? 1 : -1
|
|
1863
|
+
changed.push(item)
|
|
1864
|
+
}
|
|
1865
|
+
if (!changed.length) return
|
|
1866
|
+
this.commit()
|
|
1867
|
+
changed.forEach(item => this.emit(selected ? "tam-select:select" : "tam-select:unselect", { item }))
|
|
1868
|
+
this.emit("tam-select:bulk-change", { action: selected ? "select" : "deselect", items: changed, value: this.value })
|
|
1869
|
+
this.updateDropdownPosition()
|
|
1870
|
+
}
|
|
1871
|
+
|
|
1872
|
+
updateActiveOption(scroll = true) {
|
|
1873
|
+
this.results.querySelectorAll("[data-tam-select-entry]").forEach(option => {
|
|
528
1874
|
const index = Number(option.dataset.tamSelectEntry)
|
|
529
|
-
|
|
1875
|
+
const entry = this.visibleItems[index]
|
|
1876
|
+
if (entry && entry.type !== "group-header") {
|
|
1877
|
+
const active = index === this.activeIndex
|
|
1878
|
+
const selected = !active && entry.type === "item" && entry.item.selected
|
|
1879
|
+
// Remove both state classes before adding one, since custom themes
|
|
1880
|
+
// may share utilities between them.
|
|
1881
|
+
toggleClasses(option, this.classes.optionActive, false)
|
|
1882
|
+
toggleClasses(option, this.classes.optionSelected, false)
|
|
1883
|
+
if (active) toggleClasses(option, this.classes.optionActive, true)
|
|
1884
|
+
if (selected) toggleClasses(option, this.classes.optionSelected, true)
|
|
1885
|
+
}
|
|
530
1886
|
})
|
|
531
|
-
this.syncActiveDescendant(
|
|
1887
|
+
this.syncActiveDescendant(scroll)
|
|
1888
|
+
}
|
|
1889
|
+
|
|
1890
|
+
/** Whether the single-select search input inside the dropdown is in use. */
|
|
1891
|
+
searchPanelActive() {
|
|
1892
|
+
return Boolean(this.searchable && !this.multiple && this.input && this.searchVisible)
|
|
532
1893
|
}
|
|
533
1894
|
|
|
534
1895
|
syncActiveDescendant(scroll = false) {
|
|
535
1896
|
const entry = this.visibleItems[this.activeIndex]
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
1897
|
+
let active = entry && this.results.querySelector(`[data-tam-select-entry="${this.activeIndex}"]`)
|
|
1898
|
+
// Only explicit navigation moves the virtual window; a user scroll must
|
|
1899
|
+
// not snap back to the active row.
|
|
1900
|
+
if (scroll && entry && !active && this.isVirtualScroll && this.opened && !this.syncingVirtualWindow) {
|
|
1901
|
+
const itemHeight = this.options.virtualItemHeight
|
|
1902
|
+
const viewportHeight = this.results.clientHeight || 288
|
|
1903
|
+
const maxScrollTop = Math.max(0, this.visibleItems.length * itemHeight - viewportHeight)
|
|
1904
|
+
this.results.scrollTop = Math.min(maxScrollTop, Math.max(0, this.activeIndex * itemHeight - viewportHeight / 2))
|
|
1905
|
+
this.syncingVirtualWindow = true
|
|
1906
|
+
try {
|
|
1907
|
+
this.rerenderVirtualItems(this.results.scrollTop)
|
|
1908
|
+
} finally {
|
|
1909
|
+
this.syncingVirtualWindow = false
|
|
1910
|
+
}
|
|
1911
|
+
active = this.results.querySelector(`[data-tam-select-entry="${this.activeIndex}"]`)
|
|
1912
|
+
}
|
|
1913
|
+
const activeTarget = this.opened && this.searchPanelActive() ? this.input : this.focusTarget
|
|
1914
|
+
this.focusTarget.removeAttribute("aria-activedescendant")
|
|
1915
|
+
if (this.input && this.input !== this.focusTarget) this.input.removeAttribute("aria-activedescendant")
|
|
1916
|
+
if (this.opened && active && !entry.disabled && entry.type !== "group-header") {
|
|
1917
|
+
activeTarget.setAttribute("aria-activedescendant", entry.id)
|
|
539
1918
|
if (scroll) active.scrollIntoView({ block: "nearest" })
|
|
540
|
-
} else {
|
|
541
|
-
this.focusTarget.removeAttribute("aria-activedescendant")
|
|
542
1919
|
}
|
|
543
1920
|
}
|
|
544
1921
|
|
|
@@ -550,49 +1927,114 @@ export class TamSelect {
|
|
|
550
1927
|
|
|
551
1928
|
toggleItem(item) {
|
|
552
1929
|
if (item.disabled) return
|
|
553
|
-
if (this.multiple && item.selected)
|
|
554
|
-
|
|
1930
|
+
if (this.multiple && item.selected) {
|
|
1931
|
+
this.deselect(item)
|
|
1932
|
+
} else if (this.multiple && this.options.maximumSelectionLength > 0) {
|
|
1933
|
+
const selectedCount = this.selectedItems().length
|
|
1934
|
+
if (selectedCount >= this.options.maximumSelectionLength) {
|
|
1935
|
+
const text = typeof this.options.selectionLimitText === "function"
|
|
1936
|
+
? this.options.selectionLimitText(this.options.maximumSelectionLength)
|
|
1937
|
+
: this.options.selectionLimitText
|
|
1938
|
+
this.updateStatus(text)
|
|
1939
|
+
return
|
|
1940
|
+
}
|
|
1941
|
+
this.selectValue(item)
|
|
1942
|
+
} else {
|
|
1943
|
+
this.selectValue(item)
|
|
1944
|
+
}
|
|
555
1945
|
}
|
|
556
1946
|
|
|
1947
|
+
/** Select an item, or the first item with a value (creating it if needed). */
|
|
557
1948
|
selectValue(value) {
|
|
558
|
-
|
|
559
|
-
|
|
1949
|
+
if (this.select.disabled) return
|
|
1950
|
+
const item = this.resolveItem(value)
|
|
1951
|
+
if (!item || item.disabled) return
|
|
1952
|
+
// Re-picking the current choice changes nothing, so like a native select
|
|
1953
|
+
// it emits no select or change events.
|
|
1954
|
+
const alreadySelected = item.option?.selected && (this.multiple || this.selectedItems().length === 1)
|
|
1955
|
+
if (alreadySelected) {
|
|
1956
|
+
if (this.options.closeAfterSelect) this.close()
|
|
1957
|
+
else this.resetQueryAfterSelection()
|
|
1958
|
+
return
|
|
1959
|
+
}
|
|
1960
|
+
if (!this.emit("tam-select:selecting", { item }, true)) return
|
|
1961
|
+
if (this.multiple && this.options.maximumSelectionLength > 0) {
|
|
1962
|
+
if (this.selectedItems().length >= this.options.maximumSelectionLength) {
|
|
1963
|
+
const text = typeof this.options.selectionLimitText === "function"
|
|
1964
|
+
? this.options.selectionLimitText(this.options.maximumSelectionLength)
|
|
1965
|
+
: this.options.selectionLimitText
|
|
1966
|
+
this.updateStatus(text)
|
|
1967
|
+
return
|
|
1968
|
+
}
|
|
1969
|
+
}
|
|
560
1970
|
if (!this.multiple) Array.from(this.select.options).forEach(option => { option.selected = false })
|
|
561
1971
|
item.option.selected = true
|
|
562
1972
|
item.selected = true
|
|
563
1973
|
this.commit()
|
|
1974
|
+
this.emit("tam-select:select", { item })
|
|
564
1975
|
if (this.options.closeAfterSelect) this.close()
|
|
565
1976
|
else this.resetQueryAfterSelection()
|
|
566
1977
|
}
|
|
567
1978
|
|
|
568
1979
|
resetQueryAfterSelection() {
|
|
1980
|
+
const hadQuery = Boolean(this.query)
|
|
569
1981
|
if (this.input) this.input.value = ""
|
|
570
1982
|
this.query = ""
|
|
571
|
-
if (this.options.remoteUrl) this.
|
|
572
|
-
else this.
|
|
1983
|
+
if (!this.options.remoteUrl) this.filterLocal()
|
|
1984
|
+
else if (hadQuery) this.scheduleRemote()
|
|
1985
|
+
else this.renderDropdown()
|
|
573
1986
|
}
|
|
574
1987
|
|
|
1988
|
+
/** Deselect an item, or the first item with a value. */
|
|
575
1989
|
deselect(value) {
|
|
576
|
-
|
|
1990
|
+
if (this.select.disabled) return
|
|
1991
|
+
const item = this.items.includes(value) ? value : this.items.find(entry => String(entry.value) === String(value))
|
|
577
1992
|
if (!item) return
|
|
1993
|
+
if (!this.emit("tam-select:unselecting", { item }, true)) return
|
|
578
1994
|
item.selected = false
|
|
579
1995
|
if (item.option) item.option.selected = false
|
|
580
1996
|
this.commit()
|
|
1997
|
+
this.emit("tam-select:unselect", { item })
|
|
1998
|
+
}
|
|
1999
|
+
|
|
2000
|
+
/** The empty option a single select falls back to when cleared. */
|
|
2001
|
+
emptyOption() {
|
|
2002
|
+
return Array.from(this.select.options).find(option => option.value === "") || null
|
|
2003
|
+
}
|
|
2004
|
+
|
|
2005
|
+
canClear() {
|
|
2006
|
+
return this.multiple || Boolean(this.emptyOption())
|
|
581
2007
|
}
|
|
582
2008
|
|
|
583
2009
|
clear() {
|
|
2010
|
+
if (this.select.disabled) return
|
|
2011
|
+
const items = this.selectedItems()
|
|
2012
|
+
// Without an empty option the browser re-selects the first option, so a
|
|
2013
|
+
// single select has no empty state to clear to.
|
|
2014
|
+
if (!items.length || !this.canClear() || !this.emit("tam-select:clearing", { items }, true)) return
|
|
584
2015
|
Array.from(this.select.options).forEach(option => { option.selected = false })
|
|
585
2016
|
this.items.forEach(item => { item.selected = false })
|
|
2017
|
+
if (!this.multiple) this.emptyOption().selected = true
|
|
586
2018
|
this.commit()
|
|
2019
|
+
this.emit("tam-select:clear", { items })
|
|
587
2020
|
}
|
|
588
2021
|
|
|
589
2022
|
createItem(label, candidateValue = undefined) {
|
|
2023
|
+
if (this.select.disabled) return null
|
|
590
2024
|
const value = candidateValue ?? (typeof this.options.createValue === "function" ? this.options.createValue(label) : label)
|
|
591
2025
|
const existing = this.items.find(item => normalize(item.value) === normalize(value) || normalize(item.label) === normalize(label))
|
|
592
2026
|
if (existing) {
|
|
593
2027
|
this.selectValue(existing.value)
|
|
594
2028
|
return existing
|
|
595
2029
|
}
|
|
2030
|
+
if (this.multiple && this.options.maximumSelectionLength > 0 && this.selectedItems().length >= this.options.maximumSelectionLength) {
|
|
2031
|
+
const text = typeof this.options.selectionLimitText === "function"
|
|
2032
|
+
? this.options.selectionLimitText(this.options.maximumSelectionLength)
|
|
2033
|
+
: this.options.selectionLimitText
|
|
2034
|
+
this.updateStatus(text)
|
|
2035
|
+
return null
|
|
2036
|
+
}
|
|
2037
|
+
if (!this.emit("tam-select:creating", { label, value: String(value) }, true)) return null
|
|
596
2038
|
const item = this.addItem({ value, label, selected: false, created: true })
|
|
597
2039
|
this.selectValue(item.value)
|
|
598
2040
|
this.emit("tam-select:create", { item })
|
|
@@ -679,6 +2121,18 @@ export class TamSelect {
|
|
|
679
2121
|
return this.optionIds.get(option)
|
|
680
2122
|
}
|
|
681
2123
|
|
|
2124
|
+
// Accepts an item from this instance, a copy or stale item (matched by its
|
|
2125
|
+
// value), or a plain value.
|
|
2126
|
+
resolveItem(value) {
|
|
2127
|
+
if (this.items.includes(value)) return value
|
|
2128
|
+
if (value && typeof value === "object") {
|
|
2129
|
+
if (value.value == null) return null
|
|
2130
|
+
return this.items.find(item => String(item.value) === String(value.value)) ||
|
|
2131
|
+
this.addItem({ value: value.value, label: value.label ?? value.value })
|
|
2132
|
+
}
|
|
2133
|
+
return this.ensureNativeOption(value)
|
|
2134
|
+
}
|
|
2135
|
+
|
|
682
2136
|
ensureNativeOption(value) {
|
|
683
2137
|
return this.items.find(item => String(item.value) === String(value)) || this.addItem({ value, label: value })
|
|
684
2138
|
}
|
|
@@ -709,26 +2163,59 @@ export class TamSelect {
|
|
|
709
2163
|
|
|
710
2164
|
open(loadRemote = true) {
|
|
711
2165
|
if (this.opened || this.select.disabled) return
|
|
2166
|
+
if (!this.emit("tam-select:opening", {}, true)) return
|
|
2167
|
+
clearTimeout(this.closeTimer)
|
|
2168
|
+
if (this.closeTransitionHandler) {
|
|
2169
|
+
this.dropdown.removeEventListener("transitionend", this.closeTransitionHandler)
|
|
2170
|
+
this.closeTransitionHandler = null
|
|
2171
|
+
}
|
|
712
2172
|
this.opened = true
|
|
713
|
-
this.
|
|
2173
|
+
this.dropdownContentWidth = null
|
|
2174
|
+
if (this.options.minimumResultsForSearch > 0) {
|
|
2175
|
+
const totalOptions = this.options.remoteUrl ? Infinity : this.items.length
|
|
2176
|
+
this.searchVisible = totalOptions >= this.options.minimumResultsForSearch
|
|
2177
|
+
this.renderSelection()
|
|
2178
|
+
}
|
|
2179
|
+
if (this.portalDropdown) this.dropdown.style.visibility = "hidden"
|
|
2180
|
+
setHidden(this.dropdown, false)
|
|
2181
|
+
if (this.animationsEnabled) {
|
|
2182
|
+
toggleClasses(this.dropdown, this.classes.dropdownClosed, false)
|
|
2183
|
+
toggleClasses(this.dropdown, this.classes.dropdownOpen, true)
|
|
2184
|
+
}
|
|
714
2185
|
this.focusTarget.setAttribute("aria-expanded", "true")
|
|
715
2186
|
toggleClasses(this.control, this.classes.controlOpen, true)
|
|
716
2187
|
toggleClasses(this.chevron, this.classes.chevronOpen, true)
|
|
717
2188
|
this.renderSelection()
|
|
718
2189
|
if (this.options.remoteUrl && loadRemote) this.startRemoteSearch(false)
|
|
719
2190
|
else this.renderDropdown()
|
|
720
|
-
this.
|
|
2191
|
+
if (this.portalDropdown) {
|
|
2192
|
+
// Position before returning control to the browser so an unconstrained,
|
|
2193
|
+
// full-width portal can never flash for a frame.
|
|
2194
|
+
this.updateDropdownPosition()
|
|
2195
|
+
this.dropdown.style.visibility = ""
|
|
2196
|
+
const scheduleFrame = window.requestAnimationFrame || (callback => window.setTimeout(callback, 0))
|
|
2197
|
+
scheduleFrame(() => { if (this.opened) this.updateDropdownPosition() })
|
|
2198
|
+
}
|
|
2199
|
+
if (this.isVirtualScroll) this.syncActiveDescendant(true)
|
|
2200
|
+
const openTarget = this.searchPanelActive() ? this.input : this.focusTarget
|
|
2201
|
+
openTarget.focus({ preventScroll: true })
|
|
721
2202
|
this.emit("tam-select:open")
|
|
722
2203
|
}
|
|
723
2204
|
|
|
724
|
-
close() {
|
|
2205
|
+
close(restoreFocus = true) {
|
|
725
2206
|
if (!this.opened) return
|
|
2207
|
+
if (!this.emit("tam-select:closing", {}, true)) return
|
|
726
2208
|
this.opened = false
|
|
2209
|
+
if (this.options.selectOnClose && this.activeIndex >= 0) {
|
|
2210
|
+
const entry = this.visibleItems[this.activeIndex]
|
|
2211
|
+
const alreadySelected = entry?.type === "item" && entry.item.option?.selected
|
|
2212
|
+
if (entry && entry.type !== "group-header" && !entry.disabled && !alreadySelected) this.activateEntry(entry)
|
|
2213
|
+
}
|
|
727
2214
|
this.cancelRemoteWork()
|
|
728
|
-
this.dropdown.classList.add("hidden")
|
|
729
2215
|
this.focusTarget.setAttribute("aria-expanded", "false")
|
|
730
2216
|
toggleClasses(this.control, this.classes.controlOpen, false)
|
|
731
2217
|
this.focusTarget.removeAttribute("aria-activedescendant")
|
|
2218
|
+
if (this.input && this.input !== this.focusTarget) this.input.removeAttribute("aria-activedescendant")
|
|
732
2219
|
toggleClasses(this.chevron, this.classes.chevronOpen, false)
|
|
733
2220
|
if (this.input) this.input.value = ""
|
|
734
2221
|
this.query = ""
|
|
@@ -737,16 +2224,46 @@ export class TamSelect {
|
|
|
737
2224
|
this.error = null
|
|
738
2225
|
this.hasMore = false
|
|
739
2226
|
this.nextPage = null
|
|
2227
|
+
this.isVirtualScroll = false
|
|
2228
|
+
this.updateStatus("")
|
|
740
2229
|
if (this.options.remoteUrl) {
|
|
741
2230
|
this.remoteResults = []
|
|
742
2231
|
this.updateVisibleItems([])
|
|
743
2232
|
} else {
|
|
744
2233
|
this.filterLocal(false)
|
|
2234
|
+
if (!this.multiple) this.updateVisibleItems(this.matchedItems, false)
|
|
745
2235
|
}
|
|
746
2236
|
this.renderSelection()
|
|
2237
|
+
if (restoreFocus && !this.multiple && this.input && document.activeElement === this.input) {
|
|
2238
|
+
this.focusTarget.focus({ preventScroll: true })
|
|
2239
|
+
}
|
|
2240
|
+
|
|
2241
|
+
if (this.animationsEnabled) {
|
|
2242
|
+
toggleClasses(this.dropdown, this.classes.dropdownOpen, false)
|
|
2243
|
+
toggleClasses(this.dropdown, this.classes.dropdownClosed, true)
|
|
2244
|
+
const hide = () => {
|
|
2245
|
+
if (this.opened) return
|
|
2246
|
+
setHidden(this.dropdown, true)
|
|
2247
|
+
this.dropdown.removeEventListener("transitionend", hide)
|
|
2248
|
+
if (this.closeTransitionHandler === hide) this.closeTransitionHandler = null
|
|
2249
|
+
}
|
|
2250
|
+
this.closeTransitionHandler = hide
|
|
2251
|
+
this.dropdown.addEventListener("transitionend", hide, { once: true })
|
|
2252
|
+
this.closeTimer = setTimeout(hide, this.options.animationDuration + 50)
|
|
2253
|
+
} else {
|
|
2254
|
+
setHidden(this.dropdown, true)
|
|
2255
|
+
}
|
|
747
2256
|
this.emit("tam-select:close")
|
|
748
2257
|
}
|
|
749
2258
|
|
|
2259
|
+
focus() {
|
|
2260
|
+
if (!this.select.disabled) this.focusTarget.focus()
|
|
2261
|
+
}
|
|
2262
|
+
|
|
2263
|
+
blur() {
|
|
2264
|
+
this.focusTarget.blur()
|
|
2265
|
+
}
|
|
2266
|
+
|
|
750
2267
|
scheduleRemote() {
|
|
751
2268
|
this.startRemoteSearch(true)
|
|
752
2269
|
}
|
|
@@ -806,18 +2323,44 @@ export class TamSelect {
|
|
|
806
2323
|
this.loading = true
|
|
807
2324
|
this.loadingPage = page
|
|
808
2325
|
this.error = null
|
|
2326
|
+
this.errorAfterResults = false
|
|
809
2327
|
this.renderDropdown()
|
|
810
2328
|
|
|
811
2329
|
try {
|
|
812
2330
|
const url = new URL(this.options.remoteUrl, window.location.origin)
|
|
813
2331
|
url.searchParams.set(this.options.queryParam, request.query)
|
|
814
2332
|
url.searchParams.set(this.options.pageParam, page)
|
|
815
|
-
const
|
|
816
|
-
|
|
817
|
-
|
|
2333
|
+
const extraParams = typeof this.options.remoteParams === "function"
|
|
2334
|
+
? this.options.remoteParams({ query: request.query, page, tamSelect: this })
|
|
2335
|
+
: this.options.remoteParams
|
|
2336
|
+
Object.entries(extraParams || {}).forEach(([key, value]) => {
|
|
2337
|
+
if (value != null) url.searchParams.set(key, String(value))
|
|
818
2338
|
})
|
|
819
|
-
|
|
820
|
-
|
|
2339
|
+
const cacheKey = url.toString()
|
|
2340
|
+
let data = this.options.cacheRemote ? this.remoteCache.get(cacheKey) : null
|
|
2341
|
+
if (!data) {
|
|
2342
|
+
const transportOptions = {
|
|
2343
|
+
url,
|
|
2344
|
+
query: request.query,
|
|
2345
|
+
page,
|
|
2346
|
+
headers: { Accept: "application/json", ...this.options.headers },
|
|
2347
|
+
signal: controller.signal,
|
|
2348
|
+
tamSelect: this
|
|
2349
|
+
}
|
|
2350
|
+
const result = typeof this.options.transport === "function"
|
|
2351
|
+
? await this.options.transport(transportOptions)
|
|
2352
|
+
: await fetch(url, { headers: transportOptions.headers, signal: controller.signal })
|
|
2353
|
+
if (result && typeof result.json === "function") {
|
|
2354
|
+
if (!result.ok) throw new Error(`Request failed (${result.status})`)
|
|
2355
|
+
data = await result.json()
|
|
2356
|
+
} else {
|
|
2357
|
+
data = result
|
|
2358
|
+
}
|
|
2359
|
+
if (this.options.cacheRemote) this.remoteCache.set(cacheKey, data)
|
|
2360
|
+
}
|
|
2361
|
+
if (typeof this.options.processResults === "function") {
|
|
2362
|
+
data = await this.options.processResults(data, { query: request.query, page, tamSelect: this })
|
|
2363
|
+
}
|
|
821
2364
|
if (this.activeRequest?.id !== requestId) return
|
|
822
2365
|
|
|
823
2366
|
const rawItems = this.getPath(data, this.options.itemsPath)
|
|
@@ -834,6 +2377,9 @@ export class TamSelect {
|
|
|
834
2377
|
if (this.activeRequest?.id !== requestId) return
|
|
835
2378
|
if (error.name !== "AbortError") {
|
|
836
2379
|
this.error = error.message || "Unable to load options"
|
|
2380
|
+
// A later page failed: keep the loaded options and offer Load more as
|
|
2381
|
+
// the retry, rather than replacing the list with the error.
|
|
2382
|
+
this.errorAfterResults = append && this.remoteResults.length > 0
|
|
837
2383
|
this.emit("tam-select:error", { error })
|
|
838
2384
|
}
|
|
839
2385
|
} finally {
|
|
@@ -888,6 +2434,7 @@ export class TamSelect {
|
|
|
888
2434
|
}
|
|
889
2435
|
|
|
890
2436
|
applyDisabled() {
|
|
2437
|
+
if (this.select.disabled && this.opened) this.close(false)
|
|
891
2438
|
toggleClasses(this.control, this.classes.controlDisabled, this.select.disabled)
|
|
892
2439
|
this.focusTarget.disabled = this.select.disabled
|
|
893
2440
|
this.clearButton.disabled = this.select.disabled
|
|
@@ -898,28 +2445,120 @@ export class TamSelect {
|
|
|
898
2445
|
this.readNativeOptions()
|
|
899
2446
|
this.applyDisabled()
|
|
900
2447
|
this.renderSelection()
|
|
2448
|
+
this.applyFitWidth()
|
|
901
2449
|
this.renderDropdown()
|
|
902
2450
|
}
|
|
903
2451
|
|
|
904
|
-
emit(name, detail = {}) {
|
|
905
|
-
this.select.dispatchEvent(new CustomEvent(name, {
|
|
2452
|
+
emit(name, detail = {}, cancelable = false) {
|
|
2453
|
+
return this.select.dispatchEvent(new CustomEvent(name, {
|
|
2454
|
+
bubbles: true,
|
|
2455
|
+
cancelable,
|
|
2456
|
+
detail: { tamSelect: this, ...detail }
|
|
2457
|
+
}))
|
|
2458
|
+
}
|
|
2459
|
+
|
|
2460
|
+
clearRemoteCache() {
|
|
2461
|
+
this.remoteCache.clear()
|
|
2462
|
+
}
|
|
2463
|
+
|
|
2464
|
+
tokenizeInput() {
|
|
2465
|
+
if (!this.input) return
|
|
2466
|
+
const value = this.input.value
|
|
2467
|
+
const separators = this.options.tokenSeparators
|
|
2468
|
+
let hasToken = false
|
|
2469
|
+
for (const sep of separators) {
|
|
2470
|
+
if (value.includes(sep)) {
|
|
2471
|
+
hasToken = true
|
|
2472
|
+
break
|
|
2473
|
+
}
|
|
2474
|
+
}
|
|
2475
|
+
if (!hasToken) return
|
|
2476
|
+
const tokens = value.split(new RegExp(separators.map(s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|'))).filter(Boolean)
|
|
2477
|
+
tokens.forEach(token => {
|
|
2478
|
+
const trimmed = token.trim()
|
|
2479
|
+
if (trimmed) this.createItem(trimmed)
|
|
2480
|
+
})
|
|
2481
|
+
this.input.value = ""
|
|
2482
|
+
this.query = ""
|
|
2483
|
+
this.filterLocal()
|
|
2484
|
+
}
|
|
2485
|
+
|
|
2486
|
+
sortResults(items) {
|
|
2487
|
+
if (typeof this.options.sorter === "function") {
|
|
2488
|
+
return this.options.sorter(items)
|
|
2489
|
+
}
|
|
2490
|
+
return items
|
|
2491
|
+
}
|
|
2492
|
+
|
|
2493
|
+
addData(raw) {
|
|
2494
|
+
const items = Array.isArray(raw) ? raw : [raw]
|
|
2495
|
+
items.forEach(data => this.addItem(data))
|
|
2496
|
+
this.readNativeOptions()
|
|
2497
|
+
this.renderSelection()
|
|
2498
|
+
if (this.opened) this.renderDropdown()
|
|
2499
|
+
this.emit("tam-select:data:add", { items: items.map(d => this.items.find(i => String(i.value) === String(d.value ?? d[this.options.valueField]))) })
|
|
2500
|
+
}
|
|
2501
|
+
|
|
2502
|
+
removeData(values) {
|
|
2503
|
+
const rawValues = Array.isArray(values) ? values : [values]
|
|
2504
|
+
const removed = []
|
|
2505
|
+
rawValues.forEach(value => {
|
|
2506
|
+
const item = this.items.find(i => String(i.value) === String(value))
|
|
2507
|
+
if (item) {
|
|
2508
|
+
if (item.option) item.option.remove()
|
|
2509
|
+
this.items = this.items.filter(i => i !== item)
|
|
2510
|
+
removed.push(item)
|
|
2511
|
+
}
|
|
2512
|
+
})
|
|
2513
|
+
if (removed.length) {
|
|
2514
|
+
this.readNativeOptions()
|
|
2515
|
+
this.renderSelection()
|
|
2516
|
+
if (this.opened) this.renderDropdown()
|
|
2517
|
+
this.emit("tam-select:data:remove", { items: removed })
|
|
2518
|
+
}
|
|
906
2519
|
}
|
|
907
2520
|
|
|
908
2521
|
destroy() {
|
|
2522
|
+
if (this.destroyed) return
|
|
2523
|
+
this.destroyed = true
|
|
909
2524
|
this.cancelRemoteWork()
|
|
2525
|
+
clearTimeout(this.closeTimer)
|
|
2526
|
+
if (this.closeTransitionHandler) {
|
|
2527
|
+
this.dropdown.removeEventListener("transitionend", this.closeTransitionHandler)
|
|
2528
|
+
this.closeTransitionHandler = null
|
|
2529
|
+
}
|
|
2530
|
+
clearTimeout(this.typeaheadTimer)
|
|
2531
|
+
if (this.lazyObserver) { this.lazyObserver.disconnect(); this.lazyObserver = null }
|
|
910
2532
|
document.removeEventListener("pointerdown", this.onOutside)
|
|
2533
|
+
window.removeEventListener("resize", this.onViewportChange)
|
|
2534
|
+
window.removeEventListener("scroll", this.onViewportChange, true)
|
|
2535
|
+
window.visualViewport?.removeEventListener("resize", this.onViewportChange)
|
|
2536
|
+
window.visualViewport?.removeEventListener("scroll", this.onViewportChange)
|
|
2537
|
+
this.select.form?.removeEventListener("reset", this.onFormReset)
|
|
2538
|
+
this.mutationObserver?.disconnect()
|
|
911
2539
|
this.select.removeEventListener("change", this.onNativeChange)
|
|
912
2540
|
this.select.removeEventListener("invalid", this.onNativeInvalid)
|
|
2541
|
+
this.focusTarget.removeEventListener("keydown", this.onKeydown)
|
|
2542
|
+
if (this.input && this.input !== this.focusTarget) this.input.removeEventListener("keydown", this.onKeydown)
|
|
2543
|
+
if (this.input) {
|
|
2544
|
+
this.input.removeEventListener("input", this.onInput)
|
|
2545
|
+
this.input.removeEventListener("compositionstart", this.onCompositionStart)
|
|
2546
|
+
this.input.removeEventListener("compositionend", this.onCompositionEnd)
|
|
2547
|
+
}
|
|
2548
|
+
this.results.removeEventListener("scroll", this.onScroll)
|
|
913
2549
|
this.labelElements.forEach(label => label.removeEventListener("click", this.onLabelClick))
|
|
914
2550
|
this.wrapper.remove()
|
|
2551
|
+
if (this.portalDropdown) this.dropdown.remove()
|
|
915
2552
|
if (!this.hadSrOnlyClass) this.select.classList.remove("sr-only")
|
|
916
2553
|
if (this.originalTabIndex === null) this.select.removeAttribute("tabindex")
|
|
917
2554
|
else this.select.setAttribute("tabindex", this.originalTabIndex)
|
|
918
2555
|
if (this.originalAriaHidden === null) this.select.removeAttribute("aria-hidden")
|
|
919
2556
|
else this.select.setAttribute("aria-hidden", this.originalAriaHidden)
|
|
920
2557
|
if (this.originalId === null) this.select.removeAttribute("id")
|
|
921
|
-
|
|
2558
|
+
delete this.select.dataset.tamSelectState
|
|
2559
|
+
if (TamSelect.instances.get(this.select) === this) TamSelect.instances.delete(this.select)
|
|
922
2560
|
}
|
|
923
2561
|
}
|
|
924
2562
|
|
|
2563
|
+
export { ANIMATION_PRESETS }
|
|
925
2564
|
export default TamSelect
|