@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.
@@ -12,16 +12,15 @@
12
12
  * @param {string} [listClass] - CSS classes for the list element
13
13
  * @param {string} [liClass] - CSS classes for list item elements
14
14
  * @param {string} [aClass] - CSS classes for anchor elements
15
- * @param {Object} [options] - Configuration options for heading selection
16
- * @param {string[]} [options.includes=['h2','h3','h4','h5','h6']] - Heading tags to include
17
- * @param {string[]} [options.excludes=[]] - CSS selectors to exclude from the list
15
+ * @param {string[]} [includes=['h2','h3','h4','h5','h6']] - Heading tags to include, replacing the default
16
+ * @param {string[]} [excludes=[]] - CSS selectors to exclude from the list
18
17
  * @param {...*} [rest] - Additional props passed to the wrapper div
19
18
  *
20
19
  * @example
21
20
  * <ContentList
22
21
  * label="On this page"
23
22
  * selector=".content"
24
- * options={{ includes: ['h2', 'h3'] }}
23
+ * includes={['h2', 'h3']}
25
24
  * />
26
25
  */
27
26
  import {
@@ -59,19 +58,40 @@
59
58
 
60
59
  onMount(() => {
61
60
  if (typeof window === 'undefined') return
62
- const includes = rawIncludes.concat(defaultOptions.includes)
61
+ const includes = rawIncludes.length ? rawIncludes : defaultOptions.includes
63
62
  const excludes = rawExcludes.concat(defaultOptions.excludes)
63
+ const headingSelector = includes.join(',')
64
64
  const targetElement = selector ? document.querySelector(selector) : document
65
65
 
66
- elements = Array.from(
67
- targetElement.querySelectorAll(includes.join(',')),
68
- ).filter(el => {
69
- if (el.matches('.contentlist-exclude')) return false
70
- if (excludes.some(selector => el.matches(selector))) return false
71
- return true
66
+ collectHeadings()
67
+
68
+ // Collects headings again when content with headings arrives late
69
+ const observer = new MutationObserver(mutations => {
70
+ const hasNewHeading = mutations.some(mutation =>
71
+ Array.from(mutation.addedNodes).some(
72
+ node =>
73
+ node.nodeType === Node.ELEMENT_NODE &&
74
+ (node.matches(headingSelector) ||
75
+ node.querySelector(headingSelector)),
76
+ ),
77
+ )
78
+ if (hasNewHeading) collectHeadings()
72
79
  })
80
+ observer.observe(targetElement, { childList: true, subtree: true })
81
+
82
+ return () => observer.disconnect()
83
+
84
+ function collectHeadings() {
85
+ elements = Array.from(
86
+ targetElement.querySelectorAll(headingSelector),
87
+ ).filter(el => {
88
+ if (el.matches('.contentlist-exclude')) return false
89
+ if (excludes.some(selector => el.matches(selector))) return false
90
+ return true
91
+ })
73
92
 
74
- structure = buildStructure(elements, liClass, aClass)
93
+ structure = buildStructure(elements, liClass, aClass)
94
+ }
75
95
  })
76
96
 
77
97
  $effect(_ => {
@@ -105,6 +125,6 @@
105
125
  {:else}
106
126
  {@render label?.()}
107
127
  {/if}
108
- <NestedList items={structure} class={listClass} />
128
+ <NestedList class={listClass} items={structure} />
109
129
  </div>
110
130
  {/if}
@@ -1,63 +1,40 @@
1
- <!-- <script>
2
- import { splitObject } from '@splendidlabz/utils'
3
- import { disclosureTrigger } from '../../Disclosure/Disclosure/Old/disclosure.jsd/disclosure.js'
4
- import TextInput from '../TextInput.svelte'
5
- import {
6
- AUTOCOMPLETE_INPUT_OPT_KEYS,
7
- autocompleteInput,
8
- DEFAULT_AUTOCOMPLETE_INPUT_OPTS,
9
- } from './autocomplete.js'
10
- import { comboboxes, updateCombobox } from './combobox-store.js'
11
-
12
- let klass = ''
13
- export { klass as class }
14
- export let target
15
- export let haystack = []
16
- export let options = {}
17
-
18
- if (!target) throw new Error('AutocompleteInput requires a target prop')
19
-
20
- const opts = {
21
- ...DEFAULT_AUTOCOMPLETE_INPUT_OPTS.disclosure,
22
- ...DEFAULT_AUTOCOMPLETE_INPUT_OPTS.input,
23
- ...options,
24
- }
25
-
26
- const { picked: autocompleteInputOpts, omitted: disclosureOpts } =
27
- splitObject(opts, AUTOCOMPLETE_INPUT_OPT_KEYS)
28
-
29
- const listboxId = target + '-autocomplete'
30
- let inputRef
31
- let Box
32
-
33
- $: {
34
- Box = $comboboxes.find(c => c.id === listboxId)
35
- if (!Box) break $
36
-
37
- // Updates haystack if user fetches it later
38
- Box.state.haystack = haystack
39
- updateCombobox(Box)
40
- }
1
+ <script>
2
+ import { autocompleteInput } from './autocomplete.svelte.js'
3
+ import ComboboxInput from './ComboboxInput.svelte'
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} */
17
+ let {
18
+ value = $bindable(''),
19
+ ref = $bindable(null),
20
+ search,
21
+ debounceMs,
22
+ loop = true,
23
+ onselect,
24
+ ...rest
25
+ } = $props()
41
26
  </script>
42
27
 
43
- <TextInput
44
- class="AutocompleteInput {klass}"
45
- {target}
46
- bind:ref={inputRef}
47
- role="combobox"
48
- aria-autocomplete="list"
49
- aria-controls={listboxId}
50
- aria-owns={listboxId}
51
- aria-activedescendant={Box?.state.activeDescendantId || null}
28
+ <ComboboxInput
29
+ {...rest}
52
30
  actions={[
53
- [disclosureTrigger, { options: disclosureOpts }],
54
- [
55
- autocompleteInput,
56
- {
57
- state: { haystack },
58
- options: autocompleteInputOpts,
59
- },
60
- ],
31
+ {
32
+ fn: autocompleteInput,
33
+ props: { options: { search, debounceMs, onselect } },
34
+ },
61
35
  ]}
62
- {...$$restProps}
63
- /> -->
36
+ aria-autocomplete="list"
37
+ {loop}
38
+ bind:value
39
+ bind:ref
40
+ />
@@ -1,74 +1,73 @@
1
- <!-- <script>
2
- import { splitObject } from '@splendidlabz/utils'
3
- import PopoverContent from '../../Disclosure/Popover/PopoverContent.svelte'
4
- import {
5
- AUTOCOMPLETE_CONTENT_KEYS,
6
- autocompleteOptions,
7
- DEFAULT_AUTOCOMPLETE_CONTENT_OPTS,
8
- } from './autocomplete.js'
9
- import { comboboxes } from './combobox-store.js'
1
+ <script>
2
+ import { getNestedValue } from '@splendidlabz/utils'
3
+ import { autocompleteOptions } from './autocomplete.svelte.js'
4
+ import { getCombobox } from './combobox.svelte.js'
5
+ import ComboboxOptions from './ComboboxOptions.svelte'
10
6
 
11
- let klass = ''
12
- export { klass as class }
13
- export let id
14
- export let options = {}
7
+ let {
8
+ ref = $bindable(null),
9
+ id,
10
+ items,
11
+ filterBy,
12
+ option,
13
+ loading,
14
+ empty,
15
+ failed,
16
+ children,
17
+ ...rest
18
+ } = $props()
15
19
 
16
- const opts = {
17
- ...DEFAULT_AUTOCOMPLETE_CONTENT_OPTS.disclosure,
18
- ...DEFAULT_AUTOCOMPLETE_CONTENT_OPTS.floating,
19
- ...DEFAULT_AUTOCOMPLETE_CONTENT_OPTS.options,
20
- ...options,
21
- }
22
-
23
- const { picked: comboboxOpts } = splitObject(opts, AUTOCOMPLETE_CONTENT_KEYS)
24
-
25
- const listboxId = id + '-autocomplete'
26
- let Box
27
- let matches = []
28
- let searchState = ''
20
+ const combobox = $derived(getCombobox(id))
21
+ const shownItems = $derived(combobox?.state.results ?? items)
22
+ const searchState = $derived(combobox?.state.searchState ?? 'idle')
29
23
 
30
- $: Box = $comboboxes.find(c => c.id === listboxId)
31
- $: if (Box) {
32
- matches = Box.state.matches
33
- searchState = Box.state.searchState
24
+ /**
25
+ * getText
26
+ * Gets the text an item is filtered by.
27
+ *
28
+ * @param {any} item
29
+ */
30
+ function getText(item) {
31
+ return filterBy ? getNestedValue(item, filterBy) : item
34
32
  }
35
- </script> -->
33
+ </script>
36
34
 
37
- <!-- <PopoverContent
35
+ <ComboboxOptions
36
+ {...rest}
38
37
  {id}
39
- class="AutocompleteOptions ListboxPopover {klass}"
40
- options={opts}
38
+ actions={[{ fn: autocompleteOptions, props: { items: shownItems } }]}
39
+ bind:ref
41
40
  >
42
- {#if matches.length && searchState !== 'searching'}
43
- <ul
44
- id={listboxId}
45
- tabindex="0"
46
- class="Listbox Card-list {klass}"
47
- role="listbox"
48
- use:autocompleteOptions={{ options: comboboxOpts }}
49
- >
50
- <slot>
51
- {#each matches as match}
52
- <li role="option" aria-selected="false">
53
- {#if Box.options.filterByProp}
54
- {@html match.string}
55
- {:else}
56
- {@html match}
57
- {/if}
58
- </li>
59
- {/each}
60
- </slot>
61
- </ul>
41
+ {#if shownItems}
42
+ {#each shownItems as item, index (index)}
43
+ {@const text = getText(item)}
44
+ <!-- svelte-ignore a11y_role_has_required_aria_props -->
45
+ <li
46
+ id="{id}-option-{index}"
47
+ data-index={index}
48
+ data-text={text}
49
+ role="option"
50
+ >
51
+ {#if option}{@render option(item)}{:else}{text}{/if}
52
+ </li>
53
+ {/each}
54
+ {:else}
55
+ {@render children?.()}
62
56
  {/if}
63
57
 
64
- {#if searchState === 'searching'}
65
- <div class="Card AutocompleteLoader">
66
- <slot name="loading">Loading...</slot>
67
- </div>
68
- {/if}
58
+ {#snippet status()}
59
+ {#if searchState === 'searching' && loading}
60
+ <div class="combobox-status" data-state="searching">
61
+ {@render loading()}
62
+ </div>
63
+ {/if}
69
64
 
70
- No results found. Optional
71
- {#if searchState === 'complete' && matches.length === 0}
72
- <div class="Card AutocompleteEmpty"><slot name="no-results"></slot></div>
73
- {/if}
74
- </PopoverContent> -->
65
+ {#if searchState === 'done' && !shownItems?.length && empty}
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>
71
+ {/if}
72
+ {/snippet}
73
+ </ComboboxOptions>
@@ -0,0 +1,50 @@
1
+ <script>
2
+ import { init } from '../../../utils'
3
+ import TextInput from '../TextInput.svelte'
4
+ import { comboboxInput } from './combobox.svelte.js'
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} */
19
+ let {
20
+ value = $bindable(''),
21
+ ref = $bindable(null),
22
+ target,
23
+ loop,
24
+ onselect,
25
+ actions = [],
26
+ ...rest
27
+ } = $props()
28
+
29
+ init(() => {
30
+ if (!target) throw new Error('ComboboxInput requires a target')
31
+ })
32
+ </script>
33
+
34
+ <TextInput
35
+ {...rest}
36
+ actions={[
37
+ {
38
+ fn: comboboxInput,
39
+ props: { options: { loop, onselect } },
40
+ },
41
+ ...actions,
42
+ ]}
43
+ aria-controls="{target}-listbox"
44
+ aria-expanded="false"
45
+ autocomplete="off"
46
+ role="combobox"
47
+ {target}
48
+ bind:value
49
+ bind:ref
50
+ />
@@ -0,0 +1,49 @@
1
+ <script>
2
+ import { checkForAccessibleName } from '@splendidlabz/utils/dom'
3
+ import { useActions } from '../../../actions/use-actions'
4
+ import { init } from '../../../utils'
5
+ import { comboboxOptions } from './combobox.svelte.js'
6
+
7
+ let {
8
+ ref = $bindable(null),
9
+ class: klass = '',
10
+ id,
11
+ inline = false,
12
+ 'aria-label': ariaLabel,
13
+ 'aria-labelledby': ariaLabelledBy,
14
+ actions = [],
15
+ status,
16
+ children,
17
+ ...rest
18
+ } = $props()
19
+
20
+ init(() => {
21
+ if (!id) throw new Error('ComboboxOptions requires an id')
22
+ checkForAccessibleName({
23
+ name: `ComboboxOptions (id: ${id})`,
24
+ ariaLabel,
25
+ ariaLabelledBy,
26
+ })
27
+ })
28
+ </script>
29
+
30
+ <div
31
+ {...rest}
32
+ bind:this={ref}
33
+ {id}
34
+ class="combobox-options {klass}"
35
+ popover={inline ? null : 'manual'}
36
+ use:comboboxOptions
37
+ use:useActions={actions}
38
+ >
39
+ <ul
40
+ id="{id}-listbox"
41
+ aria-label={ariaLabel}
42
+ aria-labelledby={ariaLabelledBy}
43
+ role="listbox"
44
+ >
45
+ {@render children?.()}
46
+ </ul>
47
+
48
+ {@render status?.()}
49
+ </div>
@@ -1,114 +1,83 @@
1
- import { getNestedProperty2, mix } from '@splendidlabz/utils'
2
-
3
- import aMatch from 'autosuggest-highlight/match'
4
- import aParse from 'autosuggest-highlight/parse'
5
-
6
- // Autosuggest highlight options can be found here:
7
- // https://github.com/moroshko/autosuggest-highlight
8
- const defaultSuggestOptions = {
9
- insideWords: true,
10
- requireMatchAll: true,
11
- }
12
-
13
- export function getMatches(strings, query, options = {}) {
14
- // Two rounds of filtering for best results
15
- const set = new Set([
16
- ...strings.filter(str =>
17
- isMatch(str, query, { ...options, insideWords: false }),
18
- ),
19
-
20
- // Filter through the matches
21
- ...strings.filter(str =>
22
- isMatch(str, query, { ...options, insideWords: true }),
23
- ),
24
- ])
25
-
26
- const uniques = Array.from(set)
27
-
28
- return uniques.map(str => {
29
- const m = _getMatch(str, query, options)
30
- return _getHighlight(str, m)
1
+ /**
2
+ * @file Matches option texts against a typed query.
3
+ *
4
+ * match strips diacritics before matching, so "cafe" matches "Café".
5
+ */
6
+ import { match } from './match.js'
7
+
8
+ /**
9
+ * getMatches
10
+ * Finds the texts a query matches, and where each match sits.
11
+ *
12
+ * @typedef {[number, number]} Range Start and end index of a matched part.
13
+ * @typedef {{ index: number, ranges: Range[] }} Match `index` points into the texts passed in.
14
+ *
15
+ * @param {object} opts
16
+ * @param {string[]} opts.texts Texts to search
17
+ * @param {string} opts.query Typed query
18
+ * @returns {Match[]} Word-start matches first, then inside-word matches.
19
+ */
20
+ export function getMatches({ texts, query }) {
21
+ const wordStartIndexes = getMatchingIndexes({
22
+ texts,
23
+ query,
24
+ insideWords: false,
31
25
  })
32
- }
33
-
34
- export function getPropertyMatches({ items, prop, query, options = {} }) {
35
- // Map objects for easier filtering
36
- const objs = items.map(obj => {
37
- const _str = getNestedProperty2(obj, prop)
38
- if (!_str) throw new Error(`Property "${prop}" not found in object`)
39
- return {
40
- ...obj,
41
- _str: getNestedProperty2(obj, prop),
42
- }
26
+ const insideWordIndexes = getMatchingIndexes({
27
+ texts,
28
+ query,
29
+ insideWords: true,
43
30
  })
31
+ const indexes = new Set([...wordStartIndexes, ...insideWordIndexes])
44
32
 
45
- // Two rounds of filtering for best results
46
- const set = new Set([
47
- ...objs.filter(obj => {
48
- return isMatch(obj._str, query, { ...options, insideWords: false })
49
- }),
50
- ...objs.filter(obj => {
51
- return isMatch(obj._str, query, { ...options, insideWords: true })
52
- }),
53
- ])
54
-
55
- const uniques = Array.from(set)
56
-
57
- return uniques.map(obj => {
58
- const { _str, ...rest } = obj
59
- const m = _getMatch(_str, query, options, { insideWords: true })
60
- return {
61
- ...rest,
62
- string: _getHighlight(_str, m),
63
- }
64
- })
33
+ return Array.from(indexes, index => ({
34
+ index,
35
+ ranges: match({ text: texts[index], query, insideWords: true }),
36
+ }))
65
37
  }
66
38
 
67
- export function hasPerfectMatch(strings, query) {
68
- return strings.some(str => isPerfectMatch(str, query))
39
+ /**
40
+ * hasPerfectMatch
41
+ * Checks whether the query equals one of the texts, ignoring case and diacritics.
42
+ *
43
+ * @param {object} opts
44
+ * @param {string[]} opts.texts Texts to search
45
+ * @param {string} opts.query Typed query
46
+ * @returns {boolean}
47
+ */
48
+ export function hasPerfectMatch({ texts, query }) {
49
+ return texts.some(text => isPerfectMatch({ text, query }))
69
50
  }
70
51
 
71
- export function hasPerfectPropertyMatch({ items, prop, query }) {
72
- return items.some(obj => {
73
- const str = getNestedProperty2(obj, prop)
74
- return isPerfectMatch(str, query)
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
+ */
62
+ function getMatchingIndexes({ texts, query, insideWords }) {
63
+ return texts.flatMap((text, index) => {
64
+ const ranges = match({ text, query, insideWords })
65
+ return ranges.length ? [index] : []
75
66
  })
76
67
  }
77
68
 
78
- // Returns list of matches
79
- function _getMatch(string, query, options = {}) {
80
- const opts = mix({}, defaultSuggestOptions, options)
81
- return aMatch(string, query, opts)
82
- }
83
-
84
- function isMatch(string, query, options) {
85
- return _getMatch(string, query, options).length > 0
86
- }
87
-
88
- // Either query or string my have diatrics
89
- // So we need to pass them through _getMatch to ensure diatrics are handled in the matching.
90
- function isPerfectMatch(string, query) {
91
- const matches = _getMatch(string, query)
92
- if (matches.length <= 0) return false // No match automatically means no perfect match
93
-
94
- // Naïve checking for perfect match with a couple of assumptions
95
- const firstIndex = matches[0][0]
96
- const lastIndex = matches[matches.length - 1][1]
97
- return (
98
- firstIndex === 0 &&
99
- lastIndex === string.length &&
100
- string.length === query.length
101
- )
102
- }
103
-
104
- // Parses and highlights the matched string
105
- function _getHighlight(string, matches) {
106
- const parts = aParse(string, matches)
107
- return parts
108
- .map(part => {
109
- if (part.highlight)
110
- return `<span class="ComboboxMatchedString">${part.text}</span>`
111
- return part.text
112
- })
113
- .join('')
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
+ */
77
+ function isPerfectMatch({ text, query }) {
78
+ if (text.length !== query.length) return false
79
+
80
+ const ranges = match({ text, query, insideWords: true })
81
+ if (!ranges.length) return false
82
+ return ranges[0][0] === 0 && ranges[ranges.length - 1][1] === text.length
114
83
  }