@splendidlabz/svelte 4.15.3 → 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.
@@ -2,11 +2,24 @@
2
2
  import { autocompleteInput } from './autocomplete.svelte.js'
3
3
  import ComboboxInput from './ComboboxInput.svelte'
4
4
 
5
+ /**
6
+ * @import { ComponentProps } from 'svelte'
7
+ */
8
+
9
+ /**
10
+ * @typedef {object} AutocompleteInputOwnProps
11
+ * @property {(query: string) => Promise<any[]>} [search] Replaces local filtering
12
+ * @property {number} [debounceMs] Wait before searching
13
+ * @property {(item: any) => void} [onselect] Receives the item, or the option element
14
+ */
15
+
16
+ /** @type {ComponentProps<typeof ComboboxInput> & AutocompleteInputOwnProps} */
5
17
  let {
6
18
  value = $bindable(''),
7
19
  ref = $bindable(null),
8
20
  search,
9
21
  debounceMs,
22
+ loop = true,
10
23
  onselect,
11
24
  ...rest
12
25
  } = $props()
@@ -21,6 +34,7 @@
21
34
  },
22
35
  ]}
23
36
  aria-autocomplete="list"
37
+ {loop}
24
38
  bind:value
25
39
  bind:ref
26
40
  />
@@ -12,6 +12,7 @@
12
12
  option,
13
13
  loading,
14
14
  empty,
15
+ failed,
15
16
  children,
16
17
  ...rest
17
18
  } = $props()
@@ -20,6 +21,12 @@
20
21
  const shownItems = $derived(combobox?.state.results ?? items)
21
22
  const searchState = $derived(combobox?.state.searchState ?? 'idle')
22
23
 
24
+ /**
25
+ * getText
26
+ * Gets the text an item is filtered by.
27
+ *
28
+ * @param {any} item
29
+ */
23
30
  function getText(item) {
24
31
  return filterBy ? getNestedValue(item, filterBy) : item
25
32
  }
@@ -34,6 +41,7 @@
34
41
  {#if shownItems}
35
42
  {#each shownItems as item, index (index)}
36
43
  {@const text = getText(item)}
44
+ <!-- svelte-ignore a11y_role_has_required_aria_props -->
37
45
  <li
38
46
  id="{id}-option-{index}"
39
47
  data-index={index}
@@ -49,11 +57,17 @@
49
57
 
50
58
  {#snippet status()}
51
59
  {#if searchState === 'searching' && loading}
52
- <div class="combobox-status">{@render loading()}</div>
60
+ <div class="combobox-status" data-state="searching">
61
+ {@render loading()}
62
+ </div>
53
63
  {/if}
54
64
 
55
65
  {#if searchState === 'done' && !shownItems?.length && empty}
56
- <div class="combobox-status">{@render empty()}</div>
66
+ <div class="combobox-status" data-state="empty">{@render empty()}</div>
67
+ {/if}
68
+
69
+ {#if searchState === 'failed' && failed}
70
+ <div class="combobox-status" data-state="failed">{@render failed()}</div>
57
71
  {/if}
58
72
  {/snippet}
59
73
  </ComboboxOptions>
@@ -3,6 +3,19 @@
3
3
  import TextInput from '../TextInput.svelte'
4
4
  import { comboboxInput } from './combobox.svelte.js'
5
5
 
6
+ /**
7
+ * @import { ComponentProps } from 'svelte'
8
+ */
9
+
10
+ /**
11
+ * @typedef {object} ComboboxInputOwnProps
12
+ * @property {string} target Id of the options
13
+ * @property {boolean} [loop] Wrap past either end
14
+ * @property {(option: HTMLElement) => void} [onselect] Receives the selected option
15
+ *
16
+ */
17
+
18
+ /** @type {ComponentProps<typeof TextInput> & ComboboxInputOwnProps} */
6
19
  let {
7
20
  value = $bindable(''),
8
21
  ref = $bindable(null),
@@ -1,9 +1,9 @@
1
1
  /**
2
2
  * @file Matches option texts against a typed query.
3
3
  *
4
- * autosuggest-highlight strips diacritics before matching, so "cafe" matches "Café".
4
+ * match strips diacritics before matching, so "cafe" matches "Café".
5
5
  */
6
- import aMatch from 'autosuggest-highlight/match/index.js'
6
+ import { match } from './match.js'
7
7
 
8
8
  /**
9
9
  * getMatches
@@ -32,7 +32,7 @@ export function getMatches({ texts, query }) {
32
32
 
33
33
  return Array.from(indexes, index => ({
34
34
  index,
35
- ranges: getRanges({ text: texts[index], query, insideWords: true }),
35
+ ranges: match({ text: texts[index], query, insideWords: true }),
36
36
  }))
37
37
  }
38
38
 
@@ -49,21 +49,35 @@ export function hasPerfectMatch({ texts, query }) {
49
49
  return texts.some(text => isPerfectMatch({ text, query }))
50
50
  }
51
51
 
52
+ /**
53
+ * getMatchingIndexes
54
+ * Gets the indexes of the texts a query matches.
55
+ *
56
+ * @param {object} opts
57
+ * @param {string[]} opts.texts Texts to search
58
+ * @param {string} opts.query Typed query
59
+ * @param {boolean} opts.insideWords Match inside words too
60
+ * @returns {number[]}
61
+ */
52
62
  function getMatchingIndexes({ texts, query, insideWords }) {
53
63
  return texts.flatMap((text, index) => {
54
- const ranges = getRanges({ text, query, insideWords })
64
+ const ranges = match({ text, query, insideWords })
55
65
  return ranges.length ? [index] : []
56
66
  })
57
67
  }
58
68
 
59
- function getRanges({ text, query, insideWords }) {
60
- return aMatch(text, query, { insideWords, requireMatchAll: true })
61
- }
62
-
69
+ /**
70
+ * isPerfectMatch
71
+ * Checks whether the query covers the whole text.
72
+ *
73
+ * @param {object} opts
74
+ * @param {string} opts.text Text to compare
75
+ * @param {string} opts.query Typed query
76
+ */
63
77
  function isPerfectMatch({ text, query }) {
64
78
  if (text.length !== query.length) return false
65
79
 
66
- const ranges = getRanges({ text, query, insideWords: true })
80
+ const ranges = match({ text, query, insideWords: true })
67
81
  if (!ranges.length) return false
68
- return ranges[0][0] === 0 && ranges.at(-1)[1] === text.length
82
+ return ranges[0][0] === 0 && ranges[ranges.length - 1][1] === text.length
69
83
  }
@@ -19,10 +19,10 @@ import { clearHighlight, getAllOptions } from './listbox.js'
19
19
  * @param {object} [props.options]
20
20
  * @param {(query: string) => Promise<any[]>} [props.options.search] Replaces local filtering
21
21
  * @param {number} [props.options.debounceMs] Wait before searching
22
- * @param {(item: any) => void} [props.options.onselect] Receives the selected item
22
+ * @param {(item: any) => void} [props.options.onselect] Receives the item, or the option element
23
23
  */
24
24
  export function autocompleteInput(node, props = {}) {
25
- const id = node.getAttribute('target')
25
+ const id = /** @type {string} */ (node.getAttribute('target'))
26
26
  let onselect = props.options?.onselect
27
27
 
28
28
  const combobox = initCombobox({
@@ -38,8 +38,16 @@ export function autocompleteInput(node, props = {}) {
38
38
  const searchCache = new SvelteMap()
39
39
 
40
40
  const fetchResults = debounce(
41
+ /** @param {string} query */
41
42
  async query => {
42
- const results = await combobox.options.search(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
+ }
43
51
  searchCache.set(query, results)
44
52
 
45
53
  // Someone kept typing while this was in flight
@@ -54,6 +62,12 @@ export function autocompleteInput(node, props = {}) {
54
62
  addListeners(listeners)
55
63
 
56
64
  return {
65
+ /**
66
+ * update
67
+ * Takes the input's new options.
68
+ *
69
+ * @param {typeof props} [nextProps]
70
+ */
57
71
  update(nextProps = {}) {
58
72
  onselect = nextProps.options?.onselect
59
73
  Object.assign(combobox.options, omitEmpty(nextProps.options), {
@@ -66,7 +80,12 @@ export function autocompleteInput(node, props = {}) {
66
80
  },
67
81
  }
68
82
 
69
- // The combobox layer hands back the option element. Items live here, so this maps it back.
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
+ */
70
89
  function selectItem(option) {
71
90
  if (!onselect) return
72
91
 
@@ -75,6 +94,10 @@ export function autocompleteInput(node, props = {}) {
75
94
  onselect($state.snapshot(combobox.state.items[Number(index)]))
76
95
  }
77
96
 
97
+ /**
98
+ * onInput
99
+ * Searches or filters for what was typed.
100
+ */
78
101
  function onInput() {
79
102
  // The options can hydrate as their own island, after the input
80
103
  if (!combobox.nodes.listbox) return
@@ -84,6 +107,12 @@ export function autocompleteInput(node, props = {}) {
84
107
  else showMatchingOptions({ combobox, query })
85
108
  }
86
109
 
110
+ /**
111
+ * searchOptions
112
+ * Shows cached results for a query, or searches for it.
113
+ *
114
+ * @param {string} query
115
+ */
87
116
  function searchOptions(query) {
88
117
  if (!query) {
89
118
  combobox.state.results = null
@@ -105,6 +134,12 @@ export function autocompleteInput(node, props = {}) {
105
134
  fetchResults(query)
106
135
  }
107
136
 
137
+ /**
138
+ * showResults
139
+ * Shows what a search returned.
140
+ *
141
+ * @param {any[]} results
142
+ */
108
143
  function showResults(results) {
109
144
  combobox.state.results = results
110
145
  combobox.state.searchState = 'done'
@@ -127,13 +162,28 @@ export function autocompleteOptions(node, props = {}) {
127
162
  })
128
163
 
129
164
  return {
165
+ /**
166
+ * update
167
+ * Takes the new items.
168
+ *
169
+ * @param {typeof props} [nextProps]
170
+ */
130
171
  update(nextProps = {}) {
131
172
  combobox.state.items = nextProps.items
132
173
  },
133
174
  }
134
175
  }
135
176
 
136
- // Hides what the query misses, ranks what's left, and paints the letters that matched
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
+ */
137
187
  function showMatchingOptions({ combobox, query }) {
138
188
  const { input, listbox } = combobox.nodes
139
189
  const options = getAllOptions(listbox)
@@ -149,7 +199,10 @@ function showMatchingOptions({ combobox, query }) {
149
199
  return
150
200
  }
151
201
 
152
- const texts = options.map(option => option.dataset.text)
202
+ // prepareOptions or the Svelte markup gives every option its text
203
+ const texts = options.map(
204
+ option => /** @type {string} */ (option.dataset.text),
205
+ )
153
206
  const matches = getMatches({ texts, query })
154
207
  const matchedOptions = matches.map(match => options[match.index])
155
208
 
@@ -164,7 +217,12 @@ function showMatchingOptions({ combobox, query }) {
164
217
  else openCombobox(combobox)
165
218
  }
166
219
 
167
- // Puts every option back to unfiltered
220
+ /**
221
+ * showAllOptions
222
+ * Puts every option back to unfiltered.
223
+ *
224
+ * @param {HTMLElement[]} options
225
+ */
168
226
  function showAllOptions(options) {
169
227
  for (const option of options) {
170
228
  option.hidden = false
@@ -174,17 +232,27 @@ function showAllOptions(options) {
174
232
  }
175
233
  }
176
234
 
177
- // Shows the best matches first through `order`, which leaves every node where Svelte put it
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
+ */
178
241
  function rankOptions(options) {
179
242
  options.forEach((option, rank) => {
180
243
  option.hidden = false
181
- option.style.order = rank
182
- option.setAttribute('aria-posinset', rank + 1)
183
- option.setAttribute('aria-setsize', options.length)
244
+ option.style.order = String(rank)
245
+ option.setAttribute('aria-posinset', String(rank + 1))
246
+ option.setAttribute('aria-setsize', String(options.length))
184
247
  })
185
248
  }
186
249
 
187
- // Paints the matched letters. A browser without the Highlight API filters without painting.
250
+ /**
251
+ * paintMatches
252
+ * Paints the matched letters. A browser without the Highlight API filters without painting.
253
+ *
254
+ * @param {Range[]} ranges
255
+ */
188
256
  function paintMatches(ranges) {
189
257
  if (!CSS.highlights) return
190
258
 
@@ -196,24 +264,44 @@ function paintMatches(ranges) {
196
264
  CSS.highlights.set('autocomplete-match', new Highlight(...ranges))
197
265
  }
198
266
 
199
- // Turns matched character positions into DOM ranges the Highlight API can paint
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
+ */
200
278
  function getTextRanges({ option, query }) {
201
279
  const positions = getMatches({ texts: [option.textContent], query })[0]
202
280
  ?.ranges
203
281
  if (!positions) return []
204
282
 
205
283
  const walker = document.createTreeWalker(option, NodeFilter.SHOW_TEXT)
284
+ /** @type {TextChunk[]} */
206
285
  const chunks = []
207
286
  let offset = 0
208
287
 
209
- for (let node = walker.nextNode(); node; node = walker.nextNode()) {
288
+ for (
289
+ let node = /** @type {Text | null} */ (walker.nextNode());
290
+ node;
291
+ node = /** @type {Text | null} */ (walker.nextNode())
292
+ ) {
210
293
  chunks.push({ node, start: offset, end: offset + node.length })
211
294
  offset += node.length
212
295
  }
213
296
 
214
297
  return positions.map(([start, end]) => {
215
- const startChunk = chunks.find(chunk => start < chunk.end)
216
- const endChunk = chunks.find(chunk => end <= chunk.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
+ )
217
305
  const range = new Range()
218
306
  range.setStart(startChunk.node, start - startChunk.start)
219
307
  range.setEnd(endChunk.node, end - endChunk.start)
@@ -19,13 +19,24 @@ import {
19
19
  // ========================================
20
20
  // Shared state
21
21
  // ========================================
22
+ /**
23
+ * @type {Combobox[]}
24
+ */
22
25
  const comboboxes = $state([])
23
26
 
24
27
  /**
25
28
  * getCombobox
26
29
  * Gets the combobox registered under an id.
27
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
+ *
28
38
  * @param {string} id
39
+ * @returns {Combobox | undefined}
29
40
  */
30
41
  export function getCombobox(id) {
31
42
  return comboboxes.find(combobox => combobox.id === id)
@@ -40,6 +51,7 @@ export function getCombobox(id) {
40
51
  * @param {object} [opts.state]
41
52
  * @param {object} [opts.nodes]
42
53
  * @param {object} [opts.options]
54
+ * @returns {Combobox}
43
55
  */
44
56
  export function initCombobox({ id, state = {}, nodes = {}, options = {} }) {
45
57
  const combobox = getCombobox(id)
@@ -50,7 +62,8 @@ export function initCombobox({ id, state = {}, nodes = {}, options = {} }) {
50
62
  nodes: omitEmpty(nodes, { shallow: true }),
51
63
  options,
52
64
  })
53
- return getCombobox(id)
65
+ // The store wraps what was pushed in a proxy, so the entry is read back
66
+ return /** @type {Combobox} */ (getCombobox(id))
54
67
  }
55
68
 
56
69
  combobox.state = { ...combobox.state, ...omitEmpty(state) }
@@ -70,14 +83,14 @@ export function initCombobox({ id, state = {}, nodes = {}, options = {} }) {
70
83
  * @param {object} [props]
71
84
  * @param {object} [props.options]
72
85
  * @param {boolean} [props.options.loop] Wrap past either end
73
- * @param {(item: any) => void} [props.options.onselect] Receives the selected item
86
+ * @param {(option: HTMLElement) => void} [props.options.onselect] Receives the selected option
74
87
  */
75
88
  export function comboboxInput(node, props = {}) {
76
- const id = node.getAttribute('target')
89
+ const id = /** @type {string} */ (node.getAttribute('target'))
77
90
  const combobox = initCombobox({
78
91
  id,
79
92
  nodes: { input: node },
80
- options: { loop: true, ...omitEmpty(props.options) },
93
+ options: { loop: false, ...omitEmpty(props.options) },
81
94
  })
82
95
 
83
96
  setInitialExpanded(combobox)
@@ -90,14 +103,27 @@ export function comboboxInput(node, props = {}) {
90
103
  addListeners(listeners)
91
104
 
92
105
  return {
106
+ /**
107
+ * update
108
+ * Takes the input's new options.
109
+ *
110
+ * @param {typeof props} [nextProps]
111
+ */
93
112
  update(nextProps = {}) {
94
113
  Object.assign(combobox.options, omitEmpty(nextProps.options))
95
114
  },
96
115
  destroy() {
97
116
  removeListeners(listeners)
117
+ removeComboboxNodes({ combobox, names: ['input'] })
98
118
  },
99
119
  }
100
120
 
121
+ /**
122
+ * onKeydown
123
+ * Opens, moves through, selects and closes the options.
124
+ *
125
+ * @param {KeyboardEvent} event
126
+ */
101
127
  function onKeydown(event) {
102
128
  const { listbox } = combobox.nodes
103
129
  if (!listbox) return
@@ -153,7 +179,9 @@ export function comboboxInput(node, props = {}) {
153
179
  * @param {boolean} [props.multiple] Let more than one option be selected
154
180
  */
155
181
  export function comboboxOptions(node, props = {}) {
156
- const listbox = node.querySelector('[role="listbox"]')
182
+ const listbox = /** @type {HTMLElement} */ (
183
+ node.querySelector('[role="listbox"]')
184
+ )
157
185
  prepareOptions({ listbox, multiple: props.multiple })
158
186
 
159
187
  const combobox = initCombobox({
@@ -174,22 +202,39 @@ export function comboboxOptions(node, props = {}) {
174
202
  return {
175
203
  destroy() {
176
204
  removeListeners(listeners)
177
- combobox.floating?.cleanup()
205
+ removeComboboxNodes({ combobox, names: ['listbox', 'popover'] })
178
206
  },
179
207
  }
180
208
 
181
- // Stops a press inside the list from blurring the input
209
+ /**
210
+ * keepInputFocus
211
+ * Stops a press inside the list from blurring the input.
212
+ *
213
+ * @param {PointerEvent} event
214
+ */
182
215
  function keepInputFocus(event) {
183
216
  event.preventDefault()
184
217
  }
185
218
 
219
+ /**
220
+ * highlightHoveredOption
221
+ * Highlights the option under the pointer.
222
+ *
223
+ * @param {PointerEvent} event
224
+ */
186
225
  function highlightHoveredOption(event) {
187
- const option = event.target.closest('[role="option"]')
226
+ const option = getEventOption(event)
188
227
  if (option) highlight(combobox, option, { shouldScroll: false })
189
228
  }
190
229
 
230
+ /**
231
+ * selectClickedOption
232
+ * Selects the clicked option.
233
+ *
234
+ * @param {MouseEvent} event
235
+ */
191
236
  function selectClickedOption(event) {
192
- const option = event.target.closest('[role="option"]')
237
+ const option = getEventOption(event)
193
238
  if (option) commitSelection(combobox, option)
194
239
  }
195
240
  }
@@ -203,7 +248,7 @@ export function comboboxOptions(node, props = {}) {
203
248
  *
204
249
  * Inline options are always shown, so this only changes popover options.
205
250
  *
206
- * @param {object} combobox
251
+ * @param {Combobox} combobox
207
252
  * @returns {void}
208
253
  */
209
254
  export function openCombobox(combobox) {
@@ -228,7 +273,7 @@ export function openCombobox(combobox) {
228
273
  * closeCombobox
229
274
  * Hides popover options and clears the highlight.
230
275
  *
231
- * @param {object} combobox
276
+ * @param {Combobox} combobox
232
277
  * @returns {void}
233
278
  */
234
279
  export function closeCombobox(combobox) {
@@ -241,26 +286,71 @@ export function closeCombobox(combobox) {
241
286
 
242
287
  input.setAttribute('aria-expanded', 'false')
243
288
  popover.hidePopover()
244
- combobox.floating.cleanup()
289
+ combobox.floating?.cleanup()
245
290
  }
246
291
 
292
+ /**
293
+ * isComboboxOpen
294
+ * Reads whether the input says its options are shown.
295
+ *
296
+ * @param {Combobox} combobox
297
+ */
247
298
  function isComboboxOpen(combobox) {
248
299
  return combobox.nodes.input.getAttribute('aria-expanded') === 'true'
249
300
  }
250
301
 
251
- // Inline options are always shown, so the input starts expanded
302
+ /**
303
+ * setInitialExpanded
304
+ * Starts the input expanded when its options are inline, since those are always shown.
305
+ *
306
+ * @param {Combobox} combobox
307
+ */
252
308
  function setInitialExpanded(combobox) {
253
309
  const { input, listbox, popover } = combobox.nodes
254
310
  if (!input || !listbox) return
255
311
  input.setAttribute('aria-expanded', String(!popover))
256
312
  }
257
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
+ */
258
342
  function highlight(combobox, option, { shouldScroll = true } = {}) {
259
343
  highlightOption({ listbox: combobox.nodes.listbox, option, shouldScroll })
260
344
  combobox.nodes.input.setAttribute('aria-activedescendant', option.id)
261
345
  }
262
346
 
263
- // Marks the option chosen, then dispatches `input` so `bind:value` and filtering see the new text
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
+ */
264
354
  function commitSelection(combobox, option) {
265
355
  const { input, listbox } = combobox.nodes
266
356
  const { text } = option.dataset
@@ -274,3 +364,14 @@ function commitSelection(combobox, option) {
274
364
  // A layer above owns the items, so it gets the element and maps it back.
275
365
  combobox.options.onselect?.(option)
276
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
+ }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * @file DOM helpers for the options inside a listbox.
3
3
  *
4
- * Two states sit on an option and they are not the same thing. `data-highlighted` is the cursor — where the keyboard or pointer is, one option at a time. `aria-selected` is the selection — what the person chose, which can be more than one.
4
+ * Two states sit on an option and they are not the same thing. `data-highlighted` is the highlighted option — where the keyboard or pointer is, one option at a time. `aria-selected` is the selection — what the person chose, which can be more than one.
5
5
  */
6
6
  import { randomString } from '@splendidlabz/utils/dom'
7
7
 
@@ -19,7 +19,9 @@ import { randomString } from '@splendidlabz/utils/dom'
19
19
  export function prepareOptions({ listbox, multiple = false }) {
20
20
  if (multiple) listbox.setAttribute('aria-multiselectable', 'true')
21
21
 
22
- for (const option of listbox.querySelectorAll('li:not([role])')) {
22
+ /** @type {NodeListOf<HTMLLIElement>} */
23
+ const plainOptions = listbox.querySelectorAll('li:not([role])')
24
+ for (const option of plainOptions) {
23
25
  option.setAttribute('role', 'option')
24
26
  option.id ||= randomString(8)
25
27
  option.dataset.text = option.textContent.trim()
@@ -55,15 +57,14 @@ export function getAllOptions(listbox) {
55
57
  * @returns {HTMLElement[]}
56
58
  */
57
59
  export function getVisibleOptions(listbox) {
58
- const options = Array.from(
59
- listbox.querySelectorAll('[role="option"]:not([hidden])'),
60
- )
61
- return options.sort((a, b) => getOrder(a) - getOrder(b))
60
+ return getAllOptions(listbox)
61
+ .filter(option => !option.hidden)
62
+ .sort((a, b) => getOrder(a) - getOrder(b))
62
63
  }
63
64
 
64
65
  /**
65
66
  * getHighlightedOption
66
- * Gets the option the cursor is on.
67
+ * Gets the highlighted option.
67
68
  *
68
69
  * @param {HTMLElement} listbox
69
70
  * @returns {HTMLElement | null}
@@ -74,7 +75,7 @@ export function getHighlightedOption(listbox) {
74
75
 
75
76
  /**
76
77
  * highlightOption
77
- * Moves the cursor onto one option.
78
+ * Highlights one option.
78
79
  *
79
80
  * @param {object} opts
80
81
  * @param {HTMLElement} opts.listbox
@@ -90,7 +91,7 @@ export function highlightOption({ listbox, option, shouldScroll = true }) {
90
91
 
91
92
  /**
92
93
  * clearHighlight
93
- * Takes the cursor off every option.
94
+ * Removes the highlight from every option.
94
95
  *
95
96
  * @param {HTMLElement} listbox
96
97
  * @returns {void}
@@ -155,7 +156,10 @@ export function getAdjacentOption({ listbox, direction, loop }) {
155
156
  const options = getVisibleOptions(listbox)
156
157
  if (!options.length) return null
157
158
 
158
- const currentIndex = options.indexOf(getHighlightedOption(listbox))
159
+ const highlightedOption = getHighlightedOption(listbox)
160
+ const currentIndex = highlightedOption
161
+ ? options.indexOf(highlightedOption)
162
+ : -1
159
163
  const lastIndex = options.length - 1
160
164
 
161
165
  if (currentIndex === -1)
@@ -167,7 +171,12 @@ export function getAdjacentOption({ listbox, direction, loop }) {
167
171
  return options[index]
168
172
  }
169
173
 
170
- // Reads the rank filtering wrote. An unranked option sits at 0, the CSS default.
174
+ /**
175
+ * getOrder
176
+ * Reads the rank filtering wrote. An unranked option sits at 0, the CSS default.
177
+ *
178
+ * @param {HTMLElement} option
179
+ */
171
180
  function getOrder(option) {
172
181
  return Number(option.style.order) || 0
173
182
  }
@@ -0,0 +1,392 @@
1
+ /**
2
+ * @file Matches query words inside text, ignoring accents.
3
+ *
4
+ * Copied from autosuggest-highlight 3.3.4 (match) and its bundled remove-accents, both MIT. autosuggest-highlight ships CommonJS only, so importing it from this package broke hydration in `astro dev`.
5
+ */
6
+
7
+ /**
8
+ * match
9
+ * Finds where every word of a query matches inside a text.
10
+ *
11
+ * @param {object} opts
12
+ * @param {string} opts.text Text to search
13
+ * @param {string} opts.query Typed query
14
+ * @param {boolean} opts.insideWords Match inside words too
15
+ * @returns {[number, number][]} Sorted ranges, or empty when any word misses.
16
+ */
17
+ export function match({ text, query, insideWords }) {
18
+ const removeAccents = AccentRemover()
19
+ const characters = Array.from(text).map(removeAccents)
20
+ let remainingText = characters.join('')
21
+ const words = removeAccents(query)
22
+ .trim()
23
+ .split(/\s+/)
24
+ .filter(word => word.length > 0)
25
+
26
+ /** @type {[number, number][]} */
27
+ const ranges = []
28
+ for (const word of words) {
29
+ const boundary = !insideWords && /[a-z0-9_]/i.test(word[0]) ? '\\b' : ''
30
+ const escapedWord = word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
31
+ const occurrence = new RegExp(boundary + escapedWord, 'i').exec(
32
+ remainingText,
33
+ )
34
+ if (!occurrence) return []
35
+
36
+ // Maps the index back to the original text, where "Æ" became "AE"
37
+ const { index } = occurrence
38
+ const startOffset = index - characters.slice(0, index).join('').length
39
+ const endOffset =
40
+ word.length - characters.slice(index, index + word.length).join('').length
41
+ const start = index + startOffset
42
+ const end = index + word.length + startOffset + endOffset
43
+ if (start !== end) ranges.push([start, end])
44
+
45
+ // Blanks the matched part so later words skip it
46
+ remainingText =
47
+ remainingText.slice(0, index) +
48
+ ' '.repeat(word.length) +
49
+ remainingText.slice(index + word.length)
50
+ }
51
+
52
+ return ranges.sort((a, b) => a[0] - b[0])
53
+ }
54
+
55
+ /**
56
+ * AccentRemover
57
+ * Replaces accented characters with their plain letters.
58
+ *
59
+ * @returns {(string: string) => string}
60
+ */
61
+ function AccentRemover() {
62
+ /** @type {Record<string, string>} */
63
+ const accentMap = {
64
+ À: 'A',
65
+ Á: 'A',
66
+ Â: 'A',
67
+ Ã: 'A',
68
+ Ä: 'A',
69
+ Å: 'A',
70
+ Ấ: 'A',
71
+ Ắ: 'A',
72
+ Ẳ: 'A',
73
+ Ẵ: 'A',
74
+ Ặ: 'A',
75
+ Æ: 'AE',
76
+ Ầ: 'A',
77
+ Ằ: 'A',
78
+ Ȃ: 'A',
79
+ Ç: 'C',
80
+ Ḉ: 'C',
81
+ È: 'E',
82
+ É: 'E',
83
+ Ê: 'E',
84
+ Ë: 'E',
85
+ Ế: 'E',
86
+ Ḗ: 'E',
87
+ Ề: 'E',
88
+ Ḕ: 'E',
89
+ Ḝ: 'E',
90
+ Ȇ: 'E',
91
+ Ì: 'I',
92
+ Í: 'I',
93
+ Î: 'I',
94
+ Ï: 'I',
95
+ Ḯ: 'I',
96
+ Ȋ: 'I',
97
+ Ð: 'D',
98
+ Ñ: 'N',
99
+ Ò: 'O',
100
+ Ó: 'O',
101
+ Ô: 'O',
102
+ Õ: 'O',
103
+ Ö: 'O',
104
+ Ø: 'O',
105
+ Ố: 'O',
106
+ Ṍ: 'O',
107
+ Ṓ: 'O',
108
+ Ȏ: 'O',
109
+ Ù: 'U',
110
+ Ú: 'U',
111
+ Û: 'U',
112
+ Ü: 'U',
113
+ Ý: 'Y',
114
+ à: 'a',
115
+ á: 'a',
116
+ â: 'a',
117
+ ã: 'a',
118
+ ä: 'a',
119
+ å: 'a',
120
+ ấ: 'a',
121
+ ắ: 'a',
122
+ ẳ: 'a',
123
+ ẵ: 'a',
124
+ ặ: 'a',
125
+ æ: 'ae',
126
+ ầ: 'a',
127
+ ằ: 'a',
128
+ ȃ: 'a',
129
+ ç: 'c',
130
+ ḉ: 'c',
131
+ è: 'e',
132
+ é: 'e',
133
+ ê: 'e',
134
+ ë: 'e',
135
+ ế: 'e',
136
+ ḗ: 'e',
137
+ ề: 'e',
138
+ ḕ: 'e',
139
+ ḝ: 'e',
140
+ ȇ: 'e',
141
+ ì: 'i',
142
+ í: 'i',
143
+ î: 'i',
144
+ ï: 'i',
145
+ ḯ: 'i',
146
+ ȋ: 'i',
147
+ ð: 'd',
148
+ ñ: 'n',
149
+ ò: 'o',
150
+ ó: 'o',
151
+ ô: 'o',
152
+ õ: 'o',
153
+ ö: 'o',
154
+ ø: 'o',
155
+ ố: 'o',
156
+ ṍ: 'o',
157
+ ṓ: 'o',
158
+ ȏ: 'o',
159
+ ù: 'u',
160
+ ú: 'u',
161
+ û: 'u',
162
+ ü: 'u',
163
+ ý: 'y',
164
+ ÿ: 'y',
165
+ Ā: 'A',
166
+ ā: 'a',
167
+ Ă: 'A',
168
+ ă: 'a',
169
+ Ą: 'A',
170
+ ą: 'a',
171
+ Ć: 'C',
172
+ ć: 'c',
173
+ Ĉ: 'C',
174
+ ĉ: 'c',
175
+ Ċ: 'C',
176
+ ċ: 'c',
177
+ Č: 'C',
178
+ č: 'c',
179
+ Ď: 'D',
180
+ ď: 'd',
181
+ Đ: 'D',
182
+ đ: 'd',
183
+ Ē: 'E',
184
+ ē: 'e',
185
+ Ĕ: 'E',
186
+ ĕ: 'e',
187
+ Ė: 'E',
188
+ ė: 'e',
189
+ Ę: 'E',
190
+ ę: 'e',
191
+ Ě: 'E',
192
+ ě: 'e',
193
+ Ĝ: 'G',
194
+ Ǵ: 'G',
195
+ ĝ: 'g',
196
+ ǵ: 'g',
197
+ Ğ: 'G',
198
+ ğ: 'g',
199
+ Ġ: 'G',
200
+ ġ: 'g',
201
+ Ģ: 'G',
202
+ ģ: 'g',
203
+ Ĥ: 'H',
204
+ ĥ: 'h',
205
+ Ħ: 'H',
206
+ ħ: 'h',
207
+ Ḫ: 'H',
208
+ ḫ: 'h',
209
+ Ĩ: 'I',
210
+ ĩ: 'i',
211
+ Ī: 'I',
212
+ ī: 'i',
213
+ Ĭ: 'I',
214
+ ĭ: 'i',
215
+ Į: 'I',
216
+ į: 'i',
217
+ İ: 'I',
218
+ ı: 'i',
219
+ IJ: 'IJ',
220
+ ij: 'ij',
221
+ Ĵ: 'J',
222
+ ĵ: 'j',
223
+ Ķ: 'K',
224
+ ķ: 'k',
225
+ Ḱ: 'K',
226
+ ḱ: 'k',
227
+ Ĺ: 'L',
228
+ ĺ: 'l',
229
+ Ļ: 'L',
230
+ ļ: 'l',
231
+ Ľ: 'L',
232
+ ľ: 'l',
233
+ Ŀ: 'L',
234
+ ŀ: 'l',
235
+ Ł: 'l',
236
+ ł: 'l',
237
+ Ḿ: 'M',
238
+ ḿ: 'm',
239
+ Ń: 'N',
240
+ ń: 'n',
241
+ Ņ: 'N',
242
+ ņ: 'n',
243
+ Ň: 'N',
244
+ ň: 'n',
245
+ ʼn: 'n',
246
+ Ō: 'O',
247
+ ō: 'o',
248
+ Ŏ: 'O',
249
+ ŏ: 'o',
250
+ Ő: 'O',
251
+ ő: 'o',
252
+ Œ: 'OE',
253
+ œ: 'oe',
254
+ Ŕ: 'R',
255
+ ŕ: 'r',
256
+ Ŗ: 'R',
257
+ ŗ: 'r',
258
+ Ř: 'R',
259
+ ř: 'r',
260
+ Ȓ: 'R',
261
+ ȓ: 'r',
262
+ Ś: 'S',
263
+ ś: 's',
264
+ Ŝ: 'S',
265
+ ŝ: 's',
266
+ Ş: 'S',
267
+ Ș: 'S',
268
+ ș: 's',
269
+ ş: 's',
270
+ Š: 'S',
271
+ š: 's',
272
+ Ţ: 'T',
273
+ ţ: 't',
274
+ ț: 't',
275
+ Ț: 'T',
276
+ Ť: 'T',
277
+ ť: 't',
278
+ Ŧ: 'T',
279
+ ŧ: 't',
280
+ Ũ: 'U',
281
+ ũ: 'u',
282
+ Ū: 'U',
283
+ ū: 'u',
284
+ Ŭ: 'U',
285
+ ŭ: 'u',
286
+ Ů: 'U',
287
+ ů: 'u',
288
+ Ű: 'U',
289
+ ű: 'u',
290
+ Ų: 'U',
291
+ ų: 'u',
292
+ Ȗ: 'U',
293
+ ȗ: 'u',
294
+ Ŵ: 'W',
295
+ ŵ: 'w',
296
+ Ẃ: 'W',
297
+ ẃ: 'w',
298
+ Ŷ: 'Y',
299
+ ŷ: 'y',
300
+ Ÿ: 'Y',
301
+ Ź: 'Z',
302
+ ź: 'z',
303
+ Ż: 'Z',
304
+ ż: 'z',
305
+ Ž: 'Z',
306
+ ž: 'z',
307
+ ſ: 's',
308
+ ƒ: 'f',
309
+ Ơ: 'O',
310
+ ơ: 'o',
311
+ Ư: 'U',
312
+ ư: 'u',
313
+ Ǎ: 'A',
314
+ ǎ: 'a',
315
+ Ǐ: 'I',
316
+ ǐ: 'i',
317
+ Ǒ: 'O',
318
+ ǒ: 'o',
319
+ Ǔ: 'U',
320
+ ǔ: 'u',
321
+ Ǖ: 'U',
322
+ ǖ: 'u',
323
+ Ǘ: 'U',
324
+ ǘ: 'u',
325
+ Ǚ: 'U',
326
+ ǚ: 'u',
327
+ Ǜ: 'U',
328
+ ǜ: 'u',
329
+ Ứ: 'U',
330
+ ứ: 'u',
331
+ Ṹ: 'U',
332
+ ṹ: 'u',
333
+ Ǻ: 'A',
334
+ ǻ: 'a',
335
+ Ǽ: 'AE',
336
+ ǽ: 'ae',
337
+ Ǿ: 'O',
338
+ ǿ: 'o',
339
+ Þ: 'TH',
340
+ þ: 'th',
341
+ Ṕ: 'P',
342
+ ṕ: 'p',
343
+ Ṥ: 'S',
344
+ ṥ: 's',
345
+ Ѓ: 'Г',
346
+ ѓ: 'г',
347
+ Ќ: 'К',
348
+ ќ: 'к',
349
+ Ǹ: 'N',
350
+ ǹ: 'n',
351
+ Ồ: 'O',
352
+ ồ: 'o',
353
+ Ṑ: 'O',
354
+ ṑ: 'o',
355
+ Ừ: 'U',
356
+ ừ: 'u',
357
+ Ẁ: 'W',
358
+ ẁ: 'w',
359
+ Ỳ: 'Y',
360
+ ỳ: 'y',
361
+ Ȁ: 'A',
362
+ ȁ: 'a',
363
+ Ȅ: 'E',
364
+ ȅ: 'e',
365
+ Ȉ: 'I',
366
+ ȉ: 'i',
367
+ Ȍ: 'O',
368
+ ȍ: 'o',
369
+ Ȑ: 'R',
370
+ ȑ: 'r',
371
+ Ȕ: 'U',
372
+ ȕ: 'u',
373
+ Ǧ: 'G',
374
+ ǧ: 'g',
375
+ Ȟ: 'H',
376
+ ȟ: 'h',
377
+ ǰ: 'j',
378
+ Ǩ: 'K',
379
+ ǩ: 'k',
380
+ Ṧ: 'S',
381
+ ṧ: 's',
382
+ Ḑ: 'D',
383
+ ḑ: 'd',
384
+ Ȩ: 'E',
385
+ ȩ: 'e',
386
+ Ḩ: 'H',
387
+ ḩ: 'h',
388
+ }
389
+
390
+ return string =>
391
+ Array.from(string, character => accentMap[character] ?? character).join('')
392
+ }
@@ -9,11 +9,13 @@
9
9
  } = $props()
10
10
  </script>
11
11
 
12
- <!-- `autocomplete="off"` keeps the browser from filling a field named after a real one, which would reject a real person as a bot. -->
12
+ <!-- `autocomplete="off"` keeps the browser from filling a field named after a real one, which would reject a real person as a bot. `tabindex` and `aria-hidden` keep keyboard and screen reader users out of the field. -->
13
13
  <TextInput
14
14
  {...rest}
15
15
  {name}
16
16
  class="form-field-helper {klass}"
17
17
  autocomplete="off"
18
+ tabindex="-1"
19
+ aria-hidden="true"
18
20
  bind:value
19
21
  />
@@ -1,5 +1,11 @@
1
1
  <script>
2
2
  import TextInput from './TextInput.svelte'
3
+
4
+ /**
5
+ * @import { ComponentProps } from 'svelte'
6
+ */
7
+
8
+ /** @type {ComponentProps<typeof TextInput>} */
3
9
  const { ...rest } = $props()
4
10
  </script>
5
11
 
@@ -4,6 +4,37 @@
4
4
  import { init } from '../../utils'
5
5
  import Markdown from '../Markdown/Markdown.svelte'
6
6
 
7
+ /**
8
+ * @import { Snippet } from 'svelte'
9
+ */
10
+
11
+ /**
12
+ * @typedef {object} TextInputProps
13
+ * @property {string} name
14
+ * @property {string} [value]
15
+ * @property {HTMLInputElement | null} [ref]
16
+ * @property {string} [class]
17
+ * @property {string} [style]
18
+ * @property {string} [labelClass]
19
+ * @property {string} [hintClass]
20
+ * @property {string} [errorClass]
21
+ * @property {string} [inputGroupClass]
22
+ * @property {string} [fieldClass]
23
+ * @property {Snippet} [before] Content before the input
24
+ * @property {Snippet} [after] Content after the input
25
+ * @property {Snippet} [children]
26
+ * @property {string} [id]
27
+ * @property {'text' | 'email' | 'password' | 'search' | 'url' | 'tel'} [type]
28
+ * @property {string} [label]
29
+ * @property {boolean} [labelVisible]
30
+ * @property {string | null} [hint]
31
+ * @property {string | null} [error]
32
+ * @property {boolean | null} [disabled]
33
+ * @property {boolean | null} [readonly]
34
+ * @property {{ fn: Function, props?: any }[]} [actions] Actions run on the input
35
+ */
36
+
37
+ /** @type {TextInputProps & Record<string, any>} */
7
38
  let {
8
39
  value = $bindable(''),
9
40
  ref = $bindable(null),
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@splendidlabz/svelte",
3
3
  "type": "module",
4
- "version": "4.15.3",
4
+ "version": "4.16.0",
5
5
  "license": "Elastic-2.0",
6
6
  "sideEffects": false,
7
7
  "homepage": "https://splendidlabz.com/docs/svelte",
@@ -34,8 +34,7 @@
34
34
  "dependencies": {
35
35
  "@floating-ui/dom": "^1.7.6",
36
36
  "@iconify/svelte": "^5.2.1",
37
- "@splendidlabz/utils": "*",
38
- "autosuggest-highlight": "^3.3.4"
37
+ "@splendidlabz/utils": "*"
39
38
  },
40
39
  "devDependencies": {
41
40
  "@splendidlabz/eslint-config": "2.2.0",