@splendidlabz/svelte 4.16.0 → 4.17.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.
@@ -1,39 +1,84 @@
1
1
  /**
2
- * @file Filters a combobox's options as someone types.
2
+ * @file Filters an autocomplete's options as someone types.
3
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.
4
+ * Filtering reads the `data-*` attribute of every key `matchBy` names — `data-label` by default. The match highlight is computed separately from the option's rendered `textContent`, because an `option` snippet can render text that differs from the label, and the highlight has to sit on what's on screen.
5
+ *
6
+ * With `search`, the `items` are seeds. Typing filters them at once, and each search's results merge in below them. Results pass through the same filter, so the list only ever shows what the query matches.
5
7
  */
6
- import { debounce, omitEmpty } from '@splendidlabz/utils'
8
+ import {
9
+ debounce,
10
+ omitEmpty,
11
+ toCamel,
12
+ toKebab,
13
+ toSlug,
14
+ } from '@splendidlabz/utils'
7
15
  import { addListeners, removeListeners } from '@splendidlabz/utils/dom'
16
+ import { tick } from 'svelte'
8
17
  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'
18
+ import { getMatchedIndexes, hasPerfectMatch } from './matching.js'
19
+ import { match, removeAccents } from './match.js'
20
+ import {
21
+ closeCombobox,
22
+ isComboboxOpen,
23
+ openCombobox,
24
+ } from './combobox.svelte.js'
25
+ import {
26
+ addSelected,
27
+ getOptionData,
28
+ getValueAndLabel,
29
+ initSelection,
30
+ isSelected,
31
+ sendItem,
32
+ toggleSelected,
33
+ } from './select.svelte.js'
34
+ import {
35
+ clearHighlight,
36
+ getAllOptions,
37
+ getVisibleOptions,
38
+ selectOption,
39
+ sortOptions,
40
+ } from './listbox.js'
41
+
42
+ /**
43
+ * @import { Combobox } from './combobox.svelte.js'
44
+ * @import { SelectEntry } from './select.svelte.js'
45
+ */
12
46
 
13
47
  /**
14
48
  * autocompleteInput
15
- * Narrows the options a combobox shows to the ones its text matches.
49
+ * Narrows the options an autocomplete shows to the ones its text matches, and records what gets selected.
16
50
  *
17
51
  * @param {HTMLInputElement} node
18
52
  * @param {object} [props]
19
53
  * @param {object} [props.options]
20
- * @param {(query: string) => Promise<any[]>} [props.options.search] Replaces local filtering
54
+ * @param {(query: string) => Promise<any[]>} [props.options.search] Fetches options as someone types
21
55
  * @param {number} [props.options.debounceMs] Wait before searching
22
56
  * @param {(item: any) => void} [props.options.onselect] Receives the item, or the option element
57
+ * @param {boolean} [props.options.multiple] Let more than one option be selected
58
+ * @param {number} [props.options.max] Most options a multi select takes
59
+ * @param {boolean} [props.options.creatable] Accept text that matches no option
60
+ * @param {(text: string) => string} [props.options.onCreateValue] Value for created text
61
+ * @param {boolean} [props.options.caseSensitive] Match case while filtering and creating
62
+ * @param {string | string[]} [props.options.matchBy] Keys typing matches against
63
+ * @param {boolean} [props.options.openOnFocus] Open the options on focus
64
+ * @param {SelectEntry | SelectEntry[] | null} [props.options.selected] Selection to start with
23
65
  */
24
66
  export function autocompleteInput(node, props = {}) {
25
67
  const id = /** @type {string} */ (node.getAttribute('target'))
26
68
  let onselect = props.options?.onselect
27
69
 
28
- const combobox = initCombobox({
70
+ const combobox = initSelection({
29
71
  id,
30
72
  state: { searchState: 'idle' },
31
- options: {
32
- debounceMs: 250,
33
- ...omitEmpty(props.options),
34
- onselect: selectItem,
35
- },
73
+ options: props.options,
74
+ defaults: { debounceMs: 250, matchBy: 'label', openOnFocus: true },
75
+ onselect: selectItem,
36
76
  })
77
+ combobox.options.getTypedOption = getTypedOption
78
+
79
+ // An empty array and an empty string don't survive the merge into a registered part, so they're written here
80
+ combobox.state.query ??= ''
81
+ combobox.state.created ??= []
37
82
 
38
83
  const searchCache = new SvelteMap()
39
84
 
@@ -52,12 +97,18 @@ export function autocompleteInput(node, props = {}) {
52
97
 
53
98
  // Someone kept typing while this was in flight
54
99
  if (node.value.trim() !== query) return
55
- showResults(results)
100
+ combobox.state.results = results
101
+ combobox.state.searchState = 'done'
102
+ await showSearchedOptions(query)
56
103
  },
57
104
  () => combobox.options.debounceMs,
58
105
  )
59
106
 
60
- const listeners = [{ event: 'input', node, handler: onInput }]
107
+ const listeners = [
108
+ { event: 'input', node, handler: onInput },
109
+ { event: 'focusin', node, handler: openList },
110
+ { event: 'click', node, handler: reopenList },
111
+ ]
61
112
 
62
113
  addListeners(listeners)
63
114
 
@@ -82,16 +133,73 @@ export function autocompleteInput(node, props = {}) {
82
133
 
83
134
  /**
84
135
  * selectItem
85
- * Maps the option element the combobox layer hands back to the item it was rendered from.
136
+ * Records the selection, then hands the item back to whoever owns it.
86
137
  *
87
138
  * @param {HTMLElement} option
88
139
  */
89
140
  function selectItem(option) {
90
- if (!onselect) return
141
+ if (option.dataset.create === undefined)
142
+ toggleSelected(combobox, getOptionData(option))
143
+ else selectCreated()
144
+
145
+ sendItem({ combobox, option, onselect })
146
+ }
147
+
148
+ /**
149
+ * getTypedOption
150
+ * Gets the option Enter selects when nothing is highlighted: the exact match, or the first match.
151
+ *
152
+ * The exact match is looked for separately because it doesn't always rank first — "Mali" sits below "Café Mali" when both match at a word start.
153
+ *
154
+ * Selected options are left out, so Enter on a single select showing its selection submits the form.
155
+ *
156
+ * @returns {HTMLElement | undefined}
157
+ */
158
+ function getTypedOption() {
159
+ const { query } = combobox.state
160
+ if (!query) return
161
+
162
+ const { caseSensitive, matchBy } = combobox.options
163
+ const options = getVisibleOptions(combobox.nodes.listbox).filter(
164
+ option =>
165
+ option.dataset.create === undefined &&
166
+ option.getAttribute('aria-selected') !== 'true',
167
+ )
168
+ const exactOption = options.find(option =>
169
+ hasPerfectMatch({
170
+ texts: getOptionTexts({ option, matchBy }),
171
+ query,
172
+ caseSensitive,
173
+ }),
174
+ )
91
175
 
92
- const { index } = option.dataset
93
- if (index === undefined) return onselect(option)
94
- onselect($state.snapshot(combobox.state.items[Number(index)]))
176
+ return exactOption ?? options[0]
177
+ }
178
+
179
+ /**
180
+ * selectCreated
181
+ * Turns the typed text into a value, or selects the option already holding that value.
182
+ */
183
+ function selectCreated() {
184
+ const text = combobox.state.query.trim()
185
+ const value = combobox.options.onCreateValue?.(text) ?? toSlug(text)
186
+ const twin = getAllOptions(combobox.nodes.listbox).find(
187
+ option =>
188
+ option.dataset.create === undefined &&
189
+ isSameName({ combobox, one: option.dataset.value, other: value }),
190
+ )
191
+
192
+ if (!twin) {
193
+ combobox.state.created.push({ value, label: text })
194
+ addSelected(combobox, { value, label: text })
195
+ return
196
+ }
197
+
198
+ // The twin can already be selected, and selecting it again would take it off
199
+ const twinData = getOptionData(twin)
200
+ if (isSelected({ combobox, value: twinData.value })) return
201
+ selectOption({ listbox: combobox.nodes.listbox, option: twin })
202
+ addSelected(combobox, twinData)
95
203
  }
96
204
 
97
205
  /**
@@ -99,152 +207,372 @@ export function autocompleteInput(node, props = {}) {
99
207
  * Searches or filters for what was typed.
100
208
  */
101
209
  function onInput() {
210
+ const query = node.value.trim()
211
+
212
+ // The create option reads the query, and it renders from the options island
213
+ combobox.state.query = query
214
+
102
215
  // The options can hydrate as their own island, after the input
103
216
  if (!combobox.nodes.listbox) return
104
217
 
105
- const query = node.value.trim()
106
218
  if (combobox.options.search) searchOptions(query)
107
219
  else showMatchingOptions({ combobox, query })
108
220
  }
109
221
 
222
+ /**
223
+ * openList
224
+ * Opens the options on the list the field's own text gives. An empty field shows every option.
225
+ *
226
+ * A search field with no seed items has nothing to show, so it stays shut.
227
+ */
228
+ function openList() {
229
+ if (!combobox.options.openOnFocus) return
230
+ if (node.disabled || node.readOnly) return
231
+
232
+ const { listbox } = combobox.nodes
233
+ if (!listbox) return
234
+
235
+ // Filters the way typing this text would, then opens on what's left — an exact match closes it otherwise
236
+ const query = node.value.trim()
237
+ combobox.state.query = query
238
+ showMatchingOptions({ combobox, query })
239
+
240
+ if (!getVisibleOptions(listbox).length) return
241
+ openCombobox(combobox)
242
+ }
243
+
244
+ /**
245
+ * reopenList
246
+ * Opens the options when a field that already has focus is clicked.
247
+ *
248
+ * Selecting and Escape close the list without moving focus, so no focus event comes to reopen it.
249
+ */
250
+ function reopenList() {
251
+ if (isComboboxOpen(combobox)) return
252
+ openList()
253
+ }
254
+
110
255
  /**
111
256
  * searchOptions
112
- * Shows cached results for a query, or searches for it.
257
+ * Filters what's already listed, then shows cached results for the query or searches for it.
113
258
  *
114
259
  * @param {string} query
115
260
  */
116
- function searchOptions(query) {
261
+ async function searchOptions(query) {
262
+ // Selecting dispatches `input`, which shouldn't search for what was just chosen
263
+ if (query && query === combobox.state.selectedText) return
264
+
265
+ const cachedResults = searchCache.get(query)
266
+
117
267
  if (!query) {
118
268
  combobox.state.results = null
119
269
  combobox.state.searchState = 'idle'
120
- closeCombobox(combobox)
121
- return
270
+ } else if (cachedResults) {
271
+ combobox.state.results = cachedResults
272
+ combobox.state.searchState = 'done'
273
+ } else {
274
+ combobox.state.searchState = 'searching'
275
+ fetchResults(query)
122
276
  }
123
277
 
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)
278
+ await showSearchedOptions(query)
135
279
  }
136
280
 
137
281
  /**
138
- * showResults
139
- * Shows what a search returned.
282
+ * showSearchedOptions
283
+ * Filters the seeds and results once Svelte has rendered them, and keeps the list open while there's a query.
140
284
  *
141
- * @param {any[]} results
285
+ * @param {string} query
142
286
  */
143
- function showResults(results) {
144
- combobox.state.results = results
145
- combobox.state.searchState = 'done'
146
- openCombobox(combobox)
287
+ async function showSearchedOptions(query) {
288
+ await tick()
289
+
290
+ // The options can be destroyed while Svelte renders or a search is in flight
291
+ if (!combobox.nodes.listbox) return
292
+ filterOptions({ combobox, query })
293
+
294
+ // The status under the list reports the search, so the list stays up while there's a query
295
+ if (query) openCombobox(combobox)
296
+ else if (!combobox.options.multiple) closeCombobox(combobox)
147
297
  }
148
298
  }
149
299
 
150
300
  /**
151
- * autocompleteOptions
152
- * Registers the items the options were rendered from, so selecting one can return the original.
301
+ * mergeItems
302
+ * Adds search results below the seed items, leaving out a result whose value a seed already holds.
153
303
  *
154
- * @param {HTMLElement} node Wrapper holding the listbox
155
- * @param {object} [props]
156
- * @param {any[]} [props.items]
304
+ * @param {object} opts
305
+ * @param {SelectEntry[]} [opts.items] Seed items
306
+ * @param {SelectEntry[] | null} [opts.results] What the search returned
307
+ * @returns {SelectEntry[]}
157
308
  */
158
- export function autocompleteOptions(node, props = {}) {
159
- const combobox = initCombobox({
160
- id: node.id,
161
- state: { items: props.items },
162
- })
309
+ export function mergeItems({ items = [], results }) {
310
+ if (!results) return items
163
311
 
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
- }
312
+ const seedValues = items.map(item => getValueAndLabel(item).value)
313
+ const newResults = results.filter(
314
+ result => !seedValues.includes(getValueAndLabel(result).value),
315
+ )
316
+ return [...items, ...newResults]
175
317
  }
176
318
 
177
319
  /**
178
- * showMatchingOptions
179
- * Hides what the query misses, ranks what's left, and paints the letters that matched.
320
+ * orderItems
321
+ * Sorts items by a key, or by a comparator. A key starting with `-` sorts descending.
180
322
  *
181
- * @import { Combobox } from './combobox.svelte.js'
323
+ * @typedef {string | ((one: any, other: any) => number) | null} OrderBy
324
+ *
325
+ * @param {object} opts
326
+ * @param {SelectEntry[]} opts.items
327
+ * @param {OrderBy} [opts.orderBy]
328
+ * @returns {SelectEntry[]}
329
+ */
330
+ export function orderItems({ items, orderBy }) {
331
+ if (!orderBy) return items
332
+ if (typeof orderBy === 'function') return items.toSorted(orderBy)
333
+
334
+ const isDescending = orderBy.startsWith('-')
335
+ const key = isDescending ? orderBy.slice(1) : orderBy
336
+ const direction = isDescending ? -1 : 1
337
+
338
+ return items.toSorted(
339
+ (one, other) =>
340
+ direction *
341
+ compareValues(
342
+ readItemKey({ item: one, key }),
343
+ readItemKey({ item: other, key }),
344
+ ),
345
+ )
346
+ }
347
+
348
+ /**
349
+ * getMatchData
350
+ * Gets the `data-*` attributes an item's option needs for the keys `matchBy` names beyond its label and value.
351
+ *
352
+ * @param {object} opts
353
+ * @param {SelectEntry} opts.item
354
+ * @param {string | string[]} [opts.matchBy]
355
+ * @returns {Record<string, string>}
356
+ */
357
+ export function getMatchData({ item, matchBy = 'label' }) {
358
+ const keys = [matchBy]
359
+ .flat()
360
+ .filter(key => key !== 'label' && key !== 'value')
361
+
362
+ return Object.fromEntries(
363
+ keys.map(key => [
364
+ `data-${toKebab(key)}`,
365
+ String(readItemKey({ item, key }) ?? ''),
366
+ ]),
367
+ )
368
+ }
369
+
370
+ /**
371
+ * readItemKey
372
+ * Reads a key off an item. A bare string is its own label and value.
373
+ *
374
+ * @param {object} opts
375
+ * @param {SelectEntry} opts.item
376
+ * @param {string} opts.key
377
+ * @returns {any}
378
+ */
379
+ function readItemKey({ item, key }) {
380
+ const itemData = typeof item === 'string' ? {} : item
381
+ return { ...itemData, ...getValueAndLabel(item) }[key]
382
+ }
383
+
384
+ /**
385
+ * compareValues
386
+ * Compares two values for sorting. Strings sort the way people read them, so "Item 2" comes before "Item 10".
387
+ *
388
+ * @param {any} one
389
+ * @param {any} other
390
+ * @returns {number}
391
+ */
392
+ function compareValues(one, other) {
393
+ if (typeof one === 'string' && typeof other === 'string')
394
+ return one.localeCompare(other, undefined, {
395
+ numeric: true,
396
+ sensitivity: 'base',
397
+ })
398
+ if (one < other) return -1
399
+ if (one > other) return 1
400
+ return 0
401
+ }
402
+
403
+ /**
404
+ * isSameName
405
+ * Compares what two values name, so "Lead-generation" and "Lead generation" are one option rather than two.
406
+ *
407
+ * @param {object} opts
408
+ * @param {Combobox} opts.combobox
409
+ * @param {string} [opts.one]
410
+ * @param {string} [opts.other]
411
+ * @returns {boolean}
412
+ */
413
+ function isSameName({ combobox, one, other }) {
414
+ if (one === undefined || other === undefined) return false
415
+ if (combobox.options.caseSensitive) return one.trim() === other.trim()
416
+ return toName(one) === toName(other)
417
+ }
418
+
419
+ /**
420
+ * toName
421
+ * Strips what filtering already ignores — case, accents and the spaces and dashes between words.
422
+ *
423
+ * @param {string} value
424
+ * @returns {string}
425
+ */
426
+ function toName(value) {
427
+ return toSlug(removeAccents(value.trim()))
428
+ }
429
+
430
+ /**
431
+ * showMatchingOptions
432
+ * Filters the options, then opens the list on what's left or closes it when nothing is left to choose.
182
433
  *
183
434
  * @param {object} opts
184
435
  * @param {Combobox} opts.combobox
185
436
  * @param {string} opts.query Typed query
186
437
  */
187
438
  function showMatchingOptions({ combobox, query }) {
439
+ filterOptions({ combobox, query })
440
+
441
+ const { creatable, multiple } = combobox.options
442
+ const { matchCount } = combobox.state
443
+
444
+ // Selecting one of many clears the input, and the list has to stay up for the next one
445
+ const canClose = !multiple
446
+
447
+ if (!query) {
448
+ if (canClose) closeCombobox(combobox)
449
+ return
450
+ }
451
+
452
+ // With creation on, text that matches nothing still has the create option under it
453
+ const isEmpty = !matchCount && !creatable
454
+
455
+ // Text that reads as an option's label closes a single select, since there is nothing left to choose. An exact match on another key keeps the list up, so the option shows. Multi select keeps it up, because the match is still waiting to be selected.
456
+ const isExact =
457
+ !creatable &&
458
+ hasPerfectMatch({
459
+ texts: getVisibleOptions(combobox.nodes.listbox).map(
460
+ option => option.dataset.label ?? '',
461
+ ),
462
+ query,
463
+ caseSensitive: combobox.options.caseSensitive,
464
+ })
465
+
466
+ if (isEmpty || (isExact && canClose)) closeCombobox(combobox)
467
+ else openCombobox(combobox)
468
+ }
469
+
470
+ /**
471
+ * filterOptions
472
+ * Hides what the query misses, ranks what's left, and paints the letters that matched.
473
+ *
474
+ * @param {object} opts
475
+ * @param {Combobox} opts.combobox
476
+ * @param {string} opts.query Typed query
477
+ */
478
+ function filterOptions({ combobox, query }) {
188
479
  const { input, listbox } = combobox.nodes
189
- const options = getAllOptions(listbox)
480
+
481
+ // The create option carries the query as its label, so filtering it would rank it against itself
482
+ const options = getAllOptions(listbox).filter(
483
+ option => option.dataset.create === undefined,
484
+ )
485
+
486
+ const { caseSensitive, matchBy } = combobox.options
487
+ const texts = options.map(option => getOptionTexts({ option, matchBy }))
190
488
 
191
489
  // The list is about to change, so the current highlight points nowhere
192
490
  clearHighlight(listbox)
193
491
  input.removeAttribute('aria-activedescendant')
194
492
 
493
+ // The create option renders from the options island, which asks whether an option already says this
494
+ combobox.state.hasExactMatch = hasPerfectMatch({
495
+ texts: texts.flat(),
496
+ query,
497
+ caseSensitive,
498
+ })
499
+
500
+ // A created value and the create option are rendered below the list from their own blocks, so they keep their place
501
+ const sortableOptions = options.filter(
502
+ option => option.dataset.appended === undefined,
503
+ )
504
+
195
505
  if (!query) {
196
- showAllOptions(options)
506
+ for (const option of options) option.hidden = false
507
+ sortOptions({ listbox, options: sortableOptions.toSorted(byPosition) })
197
508
  paintMatches([])
198
- closeCombobox(combobox)
509
+ combobox.state.matchCount = options.length
199
510
  return
200
511
  }
201
512
 
202
- // prepareOptions or the Svelte markup gives every option its text
203
- const texts = options.map(
204
- option => /** @type {string} */ (option.dataset.text),
513
+ const matchedOptions = getMatchedIndexes({ texts, query, caseSensitive }).map(
514
+ index => options[index],
205
515
  )
206
- const matches = getMatches({ texts, query })
207
- const matchedOptions = matches.map(match => options[match.index])
208
516
 
209
517
  for (const option of options) option.hidden = true
210
- rankOptions(matchedOptions)
518
+ for (const option of matchedOptions) option.hidden = false
519
+ sortOptions({
520
+ listbox,
521
+ options: rankOptions({ sortableOptions, matchedOptions }),
522
+ })
211
523
  paintMatches(
212
- matchedOptions.flatMap(option => getTextRanges({ option, query })),
524
+ matchedOptions.flatMap(option =>
525
+ getTextRanges({ option, query, caseSensitive }),
526
+ ),
213
527
  )
214
528
 
215
- const isSettled = !matches.length || hasPerfectMatch({ texts, query })
216
- if (isSettled) closeCombobox(combobox)
217
- else openCombobox(combobox)
529
+ // The empty status reads this, since it can't see which options are hidden
530
+ combobox.state.matchCount = matchedOptions.length
218
531
  }
219
532
 
220
533
  /**
221
- * showAllOptions
222
- * Puts every option back to unfiltered.
534
+ * getOptionTexts
535
+ * Reads the texts an option matches by, one per key `matchBy` names.
223
536
  *
224
- * @param {HTMLElement[]} options
537
+ * @param {object} opts
538
+ * @param {HTMLElement} opts.option
539
+ * @param {string | string[]} opts.matchBy
540
+ * @returns {string[]}
225
541
  */
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
- }
542
+ function getOptionTexts({ option, matchBy }) {
543
+ return [matchBy].flat().map(key => option.dataset[toCamel(key)] ?? '')
233
544
  }
234
545
 
235
546
  /**
236
547
  * rankOptions
237
- * Shows the best matches first through `order`, which leaves every node where Svelte put it.
548
+ * Puts the matches in front, best first, and the rest back in the order the markup wrote them.
238
549
  *
239
- * @param {HTMLElement[]} options Matched options, best first
550
+ * @param {object} opts
551
+ * @param {HTMLElement[]} opts.sortableOptions Options that can be reordered
552
+ * @param {HTMLElement[]} opts.matchedOptions Matched options, best first
553
+ * @returns {HTMLElement[]}
240
554
  */
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
- })
555
+ function rankOptions({ sortableOptions, matchedOptions }) {
556
+ const matched = matchedOptions.filter(option =>
557
+ sortableOptions.includes(option),
558
+ )
559
+ const rest = sortableOptions.filter(
560
+ option => !matchedOptions.includes(option),
561
+ )
562
+
563
+ return [...matched, ...rest.toSorted(byPosition)]
564
+ }
565
+
566
+ /**
567
+ * byPosition
568
+ * Sorts options into the order the markup wrote them.
569
+ *
570
+ * @param {HTMLElement} one
571
+ * @param {HTMLElement} other
572
+ * @returns {number}
573
+ */
574
+ function byPosition(one, other) {
575
+ return Number(one.dataset.position) - Number(other.dataset.position)
248
576
  }
249
577
 
250
578
  /**
@@ -257,11 +585,11 @@ function paintMatches(ranges) {
257
585
  if (!CSS.highlights) return
258
586
 
259
587
  if (!ranges.length) {
260
- CSS.highlights.delete('autocomplete-match')
588
+ CSS.highlights.delete('match')
261
589
  return
262
590
  }
263
591
 
264
- CSS.highlights.set('autocomplete-match', new Highlight(...ranges))
592
+ CSS.highlights.set('match', new Highlight(...ranges))
265
593
  }
266
594
 
267
595
  /**
@@ -273,12 +601,17 @@ function paintMatches(ranges) {
273
601
  * @param {object} opts
274
602
  * @param {HTMLElement} opts.option
275
603
  * @param {string} opts.query Typed query
604
+ * @param {boolean} [opts.caseSensitive] Take case into account
276
605
  * @returns {Range[]}
277
606
  */
278
- function getTextRanges({ option, query }) {
279
- const positions = getMatches({ texts: [option.textContent], query })[0]
280
- ?.ranges
281
- if (!positions) return []
607
+ function getTextRanges({ option, query, caseSensitive }) {
608
+ const positions = match({
609
+ text: option.textContent,
610
+ query,
611
+ insideWords: true,
612
+ caseSensitive,
613
+ })
614
+ if (!positions.length) return []
282
615
 
283
616
  const walker = document.createTreeWalker(option, NodeFilter.SHOW_TEXT)
284
617
  /** @type {TextChunk[]} */