@splendidlabz/svelte 4.15.2 → 4.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,310 @@
1
+ /**
2
+ * @file Filters a combobox's options as someone types.
3
+ *
4
+ * Filtering reads each option's `data-text`. The match highlight is computed separately from the option's rendered `textContent`, because an `option` snippet can render text that differs from `data-text`, and the highlight has to sit on what's on screen.
5
+ */
6
+ import { debounce, omitEmpty } from '@splendidlabz/utils'
7
+ import { addListeners, removeListeners } from '@splendidlabz/utils/dom'
8
+ import { SvelteMap } from 'svelte/reactivity'
9
+ import { getMatches, hasPerfectMatch } from './autocomplete-matching.js'
10
+ import { closeCombobox, initCombobox, openCombobox } from './combobox.svelte.js'
11
+ import { clearHighlight, getAllOptions } from './listbox.js'
12
+
13
+ /**
14
+ * autocompleteInput
15
+ * Narrows the options a combobox shows to the ones its text matches.
16
+ *
17
+ * @param {HTMLInputElement} node
18
+ * @param {object} [props]
19
+ * @param {object} [props.options]
20
+ * @param {(query: string) => Promise<any[]>} [props.options.search] Replaces local filtering
21
+ * @param {number} [props.options.debounceMs] Wait before searching
22
+ * @param {(item: any) => void} [props.options.onselect] Receives the item, or the option element
23
+ */
24
+ export function autocompleteInput(node, props = {}) {
25
+ const id = /** @type {string} */ (node.getAttribute('target'))
26
+ let onselect = props.options?.onselect
27
+
28
+ const combobox = initCombobox({
29
+ id,
30
+ state: { searchState: 'idle' },
31
+ options: {
32
+ debounceMs: 250,
33
+ ...omitEmpty(props.options),
34
+ onselect: selectItem,
35
+ },
36
+ })
37
+
38
+ const searchCache = new SvelteMap()
39
+
40
+ const fetchResults = debounce(
41
+ /** @param {string} query */
42
+ async query => {
43
+ let results
44
+ try {
45
+ results = await combobox.options.search(query)
46
+ } catch (error) {
47
+ // A stale query's failure shouldn't replace the current state
48
+ if (node.value.trim() === query) combobox.state.searchState = 'failed'
49
+ throw error
50
+ }
51
+ searchCache.set(query, results)
52
+
53
+ // Someone kept typing while this was in flight
54
+ if (node.value.trim() !== query) return
55
+ showResults(results)
56
+ },
57
+ () => combobox.options.debounceMs,
58
+ )
59
+
60
+ const listeners = [{ event: 'input', node, handler: onInput }]
61
+
62
+ addListeners(listeners)
63
+
64
+ return {
65
+ /**
66
+ * update
67
+ * Takes the input's new options.
68
+ *
69
+ * @param {typeof props} [nextProps]
70
+ */
71
+ update(nextProps = {}) {
72
+ onselect = nextProps.options?.onselect
73
+ Object.assign(combobox.options, omitEmpty(nextProps.options), {
74
+ onselect: selectItem,
75
+ })
76
+ },
77
+ destroy() {
78
+ removeListeners(listeners)
79
+ fetchResults.cancel()
80
+ },
81
+ }
82
+
83
+ /**
84
+ * selectItem
85
+ * Maps the option element the combobox layer hands back to the item it was rendered from.
86
+ *
87
+ * @param {HTMLElement} option
88
+ */
89
+ function selectItem(option) {
90
+ if (!onselect) return
91
+
92
+ const { index } = option.dataset
93
+ if (index === undefined) return onselect(option)
94
+ onselect($state.snapshot(combobox.state.items[Number(index)]))
95
+ }
96
+
97
+ /**
98
+ * onInput
99
+ * Searches or filters for what was typed.
100
+ */
101
+ function onInput() {
102
+ // The options can hydrate as their own island, after the input
103
+ if (!combobox.nodes.listbox) return
104
+
105
+ const query = node.value.trim()
106
+ if (combobox.options.search) searchOptions(query)
107
+ else showMatchingOptions({ combobox, query })
108
+ }
109
+
110
+ /**
111
+ * searchOptions
112
+ * Shows cached results for a query, or searches for it.
113
+ *
114
+ * @param {string} query
115
+ */
116
+ function searchOptions(query) {
117
+ if (!query) {
118
+ combobox.state.results = null
119
+ combobox.state.searchState = 'idle'
120
+ closeCombobox(combobox)
121
+ return
122
+ }
123
+
124
+ // Selecting dispatches `input`, which shouldn't search for what was just chosen
125
+ if (query === combobox.state.selectedText) return
126
+
127
+ if (searchCache.has(query)) {
128
+ showResults(searchCache.get(query))
129
+ return
130
+ }
131
+
132
+ combobox.state.searchState = 'searching'
133
+ openCombobox(combobox)
134
+ fetchResults(query)
135
+ }
136
+
137
+ /**
138
+ * showResults
139
+ * Shows what a search returned.
140
+ *
141
+ * @param {any[]} results
142
+ */
143
+ function showResults(results) {
144
+ combobox.state.results = results
145
+ combobox.state.searchState = 'done'
146
+ openCombobox(combobox)
147
+ }
148
+ }
149
+
150
+ /**
151
+ * autocompleteOptions
152
+ * Registers the items the options were rendered from, so selecting one can return the original.
153
+ *
154
+ * @param {HTMLElement} node Wrapper holding the listbox
155
+ * @param {object} [props]
156
+ * @param {any[]} [props.items]
157
+ */
158
+ export function autocompleteOptions(node, props = {}) {
159
+ const combobox = initCombobox({
160
+ id: node.id,
161
+ state: { items: props.items },
162
+ })
163
+
164
+ return {
165
+ /**
166
+ * update
167
+ * Takes the new items.
168
+ *
169
+ * @param {typeof props} [nextProps]
170
+ */
171
+ update(nextProps = {}) {
172
+ combobox.state.items = nextProps.items
173
+ },
174
+ }
175
+ }
176
+
177
+ /**
178
+ * showMatchingOptions
179
+ * Hides what the query misses, ranks what's left, and paints the letters that matched.
180
+ *
181
+ * @import { Combobox } from './combobox.svelte.js'
182
+ *
183
+ * @param {object} opts
184
+ * @param {Combobox} opts.combobox
185
+ * @param {string} opts.query Typed query
186
+ */
187
+ function showMatchingOptions({ combobox, query }) {
188
+ const { input, listbox } = combobox.nodes
189
+ const options = getAllOptions(listbox)
190
+
191
+ // The list is about to change, so the current highlight points nowhere
192
+ clearHighlight(listbox)
193
+ input.removeAttribute('aria-activedescendant')
194
+
195
+ if (!query) {
196
+ showAllOptions(options)
197
+ paintMatches([])
198
+ closeCombobox(combobox)
199
+ return
200
+ }
201
+
202
+ // prepareOptions or the Svelte markup gives every option its text
203
+ const texts = options.map(
204
+ option => /** @type {string} */ (option.dataset.text),
205
+ )
206
+ const matches = getMatches({ texts, query })
207
+ const matchedOptions = matches.map(match => options[match.index])
208
+
209
+ for (const option of options) option.hidden = true
210
+ rankOptions(matchedOptions)
211
+ paintMatches(
212
+ matchedOptions.flatMap(option => getTextRanges({ option, query })),
213
+ )
214
+
215
+ const isSettled = !matches.length || hasPerfectMatch({ texts, query })
216
+ if (isSettled) closeCombobox(combobox)
217
+ else openCombobox(combobox)
218
+ }
219
+
220
+ /**
221
+ * showAllOptions
222
+ * Puts every option back to unfiltered.
223
+ *
224
+ * @param {HTMLElement[]} options
225
+ */
226
+ function showAllOptions(options) {
227
+ for (const option of options) {
228
+ option.hidden = false
229
+ option.style.order = ''
230
+ option.removeAttribute('aria-posinset')
231
+ option.removeAttribute('aria-setsize')
232
+ }
233
+ }
234
+
235
+ /**
236
+ * rankOptions
237
+ * Shows the best matches first through `order`, which leaves every node where Svelte put it.
238
+ *
239
+ * @param {HTMLElement[]} options Matched options, best first
240
+ */
241
+ function rankOptions(options) {
242
+ options.forEach((option, rank) => {
243
+ option.hidden = false
244
+ option.style.order = String(rank)
245
+ option.setAttribute('aria-posinset', String(rank + 1))
246
+ option.setAttribute('aria-setsize', String(options.length))
247
+ })
248
+ }
249
+
250
+ /**
251
+ * paintMatches
252
+ * Paints the matched letters. A browser without the Highlight API filters without painting.
253
+ *
254
+ * @param {Range[]} ranges
255
+ */
256
+ function paintMatches(ranges) {
257
+ if (!CSS.highlights) return
258
+
259
+ if (!ranges.length) {
260
+ CSS.highlights.delete('autocomplete-match')
261
+ return
262
+ }
263
+
264
+ CSS.highlights.set('autocomplete-match', new Highlight(...ranges))
265
+ }
266
+
267
+ /**
268
+ * getTextRanges
269
+ * Turns matched character positions into DOM ranges the Highlight API can paint.
270
+ *
271
+ * @typedef {{ node: Text, start: number, end: number }} TextChunk Where one text node sits in the option's text.
272
+ *
273
+ * @param {object} opts
274
+ * @param {HTMLElement} opts.option
275
+ * @param {string} opts.query Typed query
276
+ * @returns {Range[]}
277
+ */
278
+ function getTextRanges({ option, query }) {
279
+ const positions = getMatches({ texts: [option.textContent], query })[0]
280
+ ?.ranges
281
+ if (!positions) return []
282
+
283
+ const walker = document.createTreeWalker(option, NodeFilter.SHOW_TEXT)
284
+ /** @type {TextChunk[]} */
285
+ const chunks = []
286
+ let offset = 0
287
+
288
+ for (
289
+ let node = /** @type {Text | null} */ (walker.nextNode());
290
+ node;
291
+ node = /** @type {Text | null} */ (walker.nextNode())
292
+ ) {
293
+ chunks.push({ node, start: offset, end: offset + node.length })
294
+ offset += node.length
295
+ }
296
+
297
+ return positions.map(([start, end]) => {
298
+ // Positions come from the same text, so a chunk always holds them
299
+ const startChunk = /** @type {TextChunk} */ (
300
+ chunks.find(chunk => start < chunk.end)
301
+ )
302
+ const endChunk = /** @type {TextChunk} */ (
303
+ chunks.find(chunk => end <= chunk.end)
304
+ )
305
+ const range = new Range()
306
+ range.setStart(startChunk.node, start - startChunk.start)
307
+ range.setEnd(endChunk.node, end - endChunk.start)
308
+ return range
309
+ })
310
+ }
@@ -0,0 +1,377 @@
1
+ /**
2
+ * @file Links a combobox input to its listbox by id.
3
+ *
4
+ * The input and the options can hydrate as separate Astro islands in either order, so both parts register into one store keyed by id.
5
+ */
6
+ import { omitEmpty } from '@splendidlabz/utils'
7
+ import { addListeners, isTab, removeListeners } from '@splendidlabz/utils/dom'
8
+ import { initFloating } from '../../Disclosure/Popover/floating.js'
9
+ import {
10
+ clearHighlight,
11
+ getAdjacentOption,
12
+ getHighlightedOption,
13
+ getVisibleOptions,
14
+ highlightOption,
15
+ prepareOptions,
16
+ selectOption,
17
+ } from './listbox.js'
18
+
19
+ // ========================================
20
+ // Shared state
21
+ // ========================================
22
+ /**
23
+ * @type {Combobox[]}
24
+ */
25
+ const comboboxes = $state([])
26
+
27
+ /**
28
+ * getCombobox
29
+ * Gets the combobox registered under an id.
30
+ *
31
+ * @typedef {object} Combobox
32
+ * @property {string} id Id of the options wrapper
33
+ * @property {Record<string, any>} state
34
+ * @property {Record<string, any>} nodes Each part registers its own nodes
35
+ * @property {Record<string, any>} options
36
+ * @property {ReturnType<typeof initFloating>} [floating]
37
+ *
38
+ * @param {string} id
39
+ * @returns {Combobox | undefined}
40
+ */
41
+ export function getCombobox(id) {
42
+ return comboboxes.find(combobox => combobox.id === id)
43
+ }
44
+
45
+ /**
46
+ * initCombobox
47
+ * Registers one part of a combobox, merging it with parts already registered.
48
+ *
49
+ * @param {object} opts
50
+ * @param {string} opts.id Id of the options wrapper
51
+ * @param {object} [opts.state]
52
+ * @param {object} [opts.nodes]
53
+ * @param {object} [opts.options]
54
+ * @returns {Combobox}
55
+ */
56
+ export function initCombobox({ id, state = {}, nodes = {}, options = {} }) {
57
+ const combobox = getCombobox(id)
58
+ if (!combobox) {
59
+ comboboxes.push({
60
+ id,
61
+ state,
62
+ nodes: omitEmpty(nodes, { shallow: true }),
63
+ options,
64
+ })
65
+ // The store wraps what was pushed in a proxy, so the entry is read back
66
+ return /** @type {Combobox} */ (getCombobox(id))
67
+ }
68
+
69
+ combobox.state = { ...combobox.state, ...omitEmpty(state) }
70
+ combobox.nodes = { ...combobox.nodes, ...omitEmpty(nodes, { shallow: true }) }
71
+ combobox.options = { ...combobox.options, ...omitEmpty(options) }
72
+ return combobox
73
+ }
74
+
75
+ // ========================================
76
+ // Actions
77
+ // ========================================
78
+ /**
79
+ * comboboxInput
80
+ * Lets an input open, move through and select the options it targets.
81
+ *
82
+ * @param {HTMLInputElement} node
83
+ * @param {object} [props]
84
+ * @param {object} [props.options]
85
+ * @param {boolean} [props.options.loop] Wrap past either end
86
+ * @param {(option: HTMLElement) => void} [props.options.onselect] Receives the selected option
87
+ */
88
+ export function comboboxInput(node, props = {}) {
89
+ const id = /** @type {string} */ (node.getAttribute('target'))
90
+ const combobox = initCombobox({
91
+ id,
92
+ nodes: { input: node },
93
+ options: { loop: false, ...omitEmpty(props.options) },
94
+ })
95
+
96
+ setInitialExpanded(combobox)
97
+
98
+ const listeners = [
99
+ { event: 'keydown', node, handler: onKeydown },
100
+ { event: 'focusout', node, handler: onFocusout },
101
+ ]
102
+
103
+ addListeners(listeners)
104
+
105
+ return {
106
+ /**
107
+ * update
108
+ * Takes the input's new options.
109
+ *
110
+ * @param {typeof props} [nextProps]
111
+ */
112
+ update(nextProps = {}) {
113
+ Object.assign(combobox.options, omitEmpty(nextProps.options))
114
+ },
115
+ destroy() {
116
+ removeListeners(listeners)
117
+ removeComboboxNodes({ combobox, names: ['input'] })
118
+ },
119
+ }
120
+
121
+ /**
122
+ * onKeydown
123
+ * Opens, moves through, selects and closes the options.
124
+ *
125
+ * @param {KeyboardEvent} event
126
+ */
127
+ function onKeydown(event) {
128
+ const { listbox } = combobox.nodes
129
+ if (!listbox) return
130
+
131
+ const { key } = event
132
+ const isOpen = isComboboxOpen(combobox)
133
+
134
+ if (key === 'ArrowDown' || key === 'ArrowUp') {
135
+ event.preventDefault()
136
+
137
+ if (!isOpen) {
138
+ if (getVisibleOptions(listbox).length) openCombobox(combobox)
139
+ return
140
+ }
141
+
142
+ const option = getAdjacentOption({
143
+ listbox,
144
+ direction: key === 'ArrowDown' ? 'next' : 'prev',
145
+ loop: combobox.options.loop,
146
+ })
147
+ if (option) highlight(combobox, option)
148
+ return
149
+ }
150
+
151
+ if (key === 'Escape' && isOpen) {
152
+ event.preventDefault()
153
+ closeCombobox(combobox)
154
+ return
155
+ }
156
+
157
+ const highlightedOption = getHighlightedOption(listbox)
158
+ if (!isOpen || !highlightedOption) return
159
+
160
+ if (key === 'Enter') {
161
+ event.preventDefault()
162
+ commitSelection(combobox, highlightedOption)
163
+ }
164
+
165
+ if (isTab(event)) commitSelection(combobox, highlightedOption)
166
+ }
167
+
168
+ function onFocusout() {
169
+ if (combobox.nodes.listbox) closeCombobox(combobox)
170
+ }
171
+ }
172
+
173
+ /**
174
+ * comboboxOptions
175
+ * Registers the options a combobox input targets.
176
+ *
177
+ * @param {HTMLElement} node Wrapper holding the listbox
178
+ * @param {object} [props]
179
+ * @param {boolean} [props.multiple] Let more than one option be selected
180
+ */
181
+ export function comboboxOptions(node, props = {}) {
182
+ const listbox = /** @type {HTMLElement} */ (
183
+ node.querySelector('[role="listbox"]')
184
+ )
185
+ prepareOptions({ listbox, multiple: props.multiple })
186
+
187
+ const combobox = initCombobox({
188
+ id: node.id,
189
+ nodes: { listbox, popover: node.hasAttribute('popover') ? node : null },
190
+ })
191
+
192
+ setInitialExpanded(combobox)
193
+
194
+ const listeners = [
195
+ { event: 'pointerdown', node, handler: keepInputFocus },
196
+ { event: 'pointerover', node: listbox, handler: highlightHoveredOption },
197
+ { event: 'click', node: listbox, handler: selectClickedOption },
198
+ ]
199
+
200
+ addListeners(listeners)
201
+
202
+ return {
203
+ destroy() {
204
+ removeListeners(listeners)
205
+ removeComboboxNodes({ combobox, names: ['listbox', 'popover'] })
206
+ },
207
+ }
208
+
209
+ /**
210
+ * keepInputFocus
211
+ * Stops a press inside the list from blurring the input.
212
+ *
213
+ * @param {PointerEvent} event
214
+ */
215
+ function keepInputFocus(event) {
216
+ event.preventDefault()
217
+ }
218
+
219
+ /**
220
+ * highlightHoveredOption
221
+ * Highlights the option under the pointer.
222
+ *
223
+ * @param {PointerEvent} event
224
+ */
225
+ function highlightHoveredOption(event) {
226
+ const option = getEventOption(event)
227
+ if (option) highlight(combobox, option, { shouldScroll: false })
228
+ }
229
+
230
+ /**
231
+ * selectClickedOption
232
+ * Selects the clicked option.
233
+ *
234
+ * @param {MouseEvent} event
235
+ */
236
+ function selectClickedOption(event) {
237
+ const option = getEventOption(event)
238
+ if (option) commitSelection(combobox, option)
239
+ }
240
+ }
241
+
242
+ // ========================================
243
+ // Methods
244
+ // ========================================
245
+ /**
246
+ * openCombobox
247
+ * Shows the options under the input.
248
+ *
249
+ * Inline options are always shown, so this only changes popover options.
250
+ *
251
+ * @param {Combobox} combobox
252
+ * @returns {void}
253
+ */
254
+ export function openCombobox(combobox) {
255
+ if (isComboboxOpen(combobox)) return
256
+
257
+ const { input, popover } = combobox.nodes
258
+ input.setAttribute('aria-expanded', 'true')
259
+
260
+ popover.style.width = `${input.getBoundingClientRect().width}px`
261
+ popover.showPopover()
262
+
263
+ combobox.floating ??= initFloating({
264
+ referenceNode: input,
265
+ floatingNode: popover,
266
+ placement: 'bottom-start',
267
+ offset: 0,
268
+ })
269
+ combobox.floating.update()
270
+ }
271
+
272
+ /**
273
+ * closeCombobox
274
+ * Hides popover options and clears the highlight.
275
+ *
276
+ * @param {Combobox} combobox
277
+ * @returns {void}
278
+ */
279
+ export function closeCombobox(combobox) {
280
+ const { input, listbox, popover } = combobox.nodes
281
+
282
+ clearHighlight(listbox)
283
+ input.removeAttribute('aria-activedescendant')
284
+
285
+ if (!popover || !isComboboxOpen(combobox)) return
286
+
287
+ input.setAttribute('aria-expanded', 'false')
288
+ popover.hidePopover()
289
+ combobox.floating?.cleanup()
290
+ }
291
+
292
+ /**
293
+ * isComboboxOpen
294
+ * Reads whether the input says its options are shown.
295
+ *
296
+ * @param {Combobox} combobox
297
+ */
298
+ function isComboboxOpen(combobox) {
299
+ return combobox.nodes.input.getAttribute('aria-expanded') === 'true'
300
+ }
301
+
302
+ /**
303
+ * setInitialExpanded
304
+ * Starts the input expanded when its options are inline, since those are always shown.
305
+ *
306
+ * @param {Combobox} combobox
307
+ */
308
+ function setInitialExpanded(combobox) {
309
+ const { input, listbox, popover } = combobox.nodes
310
+ if (!input || !listbox) return
311
+ input.setAttribute('aria-expanded', String(!popover))
312
+ }
313
+
314
+ /**
315
+ * removeComboboxNodes
316
+ * Drops a destroyed part's nodes, and the entry once no part is left.
317
+ *
318
+ * @param {object} opts
319
+ * @param {Combobox} opts.combobox
320
+ * @param {string[]} opts.names Node names the part registered
321
+ */
322
+ function removeComboboxNodes({ combobox, names }) {
323
+ // Positioning points at the old nodes, so the next open rebuilds it
324
+ combobox.floating?.cleanup()
325
+ delete combobox.floating
326
+
327
+ for (const name of names) delete combobox.nodes[name]
328
+ if (combobox.nodes.input || combobox.nodes.listbox) return
329
+
330
+ comboboxes.splice(comboboxes.indexOf(combobox), 1)
331
+ }
332
+
333
+ /**
334
+ * highlight
335
+ * Highlights an option and points the input at it.
336
+ *
337
+ * @param {Combobox} combobox
338
+ * @param {HTMLElement} option
339
+ * @param {object} [opts]
340
+ * @param {boolean} [opts.shouldScroll] Scroll option into view
341
+ */
342
+ function highlight(combobox, option, { shouldScroll = true } = {}) {
343
+ highlightOption({ listbox: combobox.nodes.listbox, option, shouldScroll })
344
+ combobox.nodes.input.setAttribute('aria-activedescendant', option.id)
345
+ }
346
+
347
+ /**
348
+ * commitSelection
349
+ * Marks the option chosen, then dispatches `input` so `bind:value` and filtering see the new text.
350
+ *
351
+ * @param {Combobox} combobox
352
+ * @param {HTMLElement} option
353
+ */
354
+ function commitSelection(combobox, option) {
355
+ const { input, listbox } = combobox.nodes
356
+ const { text } = option.dataset
357
+
358
+ selectOption({ listbox, option })
359
+ combobox.state.selectedText = text
360
+ input.value = text
361
+ input.dispatchEvent(new Event('input', { bubbles: true }))
362
+ closeCombobox(combobox)
363
+
364
+ // A layer above owns the items, so it gets the element and maps it back.
365
+ combobox.options.onselect?.(option)
366
+ }
367
+
368
+ /**
369
+ * getEventOption
370
+ * Gets the option an event happened on.
371
+ *
372
+ * @param {Event} event
373
+ * @returns {HTMLElement | null}
374
+ */
375
+ function getEventOption(event) {
376
+ return /** @type {HTMLElement} */ (event.target).closest('[role="option"]')
377
+ }
@@ -3,12 +3,9 @@ import AutocompleteOptions from './AutocompleteOptions.svelte'
3
3
  import TimepickerInput from './TimepickerInput.svelte'
4
4
  import TimepickerOptions from './TimepickerOptions.svelte'
5
5
 
6
- // Combobox has been renamed to Autocomplete
7
6
  export {
8
7
  AutocompleteInput,
9
8
  AutocompleteOptions,
10
- AutocompleteInput as ComboboxInput,
11
- AutocompleteOptions as ComboboxOptions,
12
9
  TimepickerInput,
13
10
  TimepickerOptions,
14
11
  }