@splendidlabz/svelte 4.15.2 → 4.15.3

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,26 @@
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
+ let {
6
+ value = $bindable(''),
7
+ ref = $bindable(null),
8
+ search,
9
+ debounceMs,
10
+ onselect,
11
+ ...rest
12
+ } = $props()
41
13
  </script>
42
14
 
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}
15
+ <ComboboxInput
16
+ {...rest}
52
17
  actions={[
53
- [disclosureTrigger, { options: disclosureOpts }],
54
- [
55
- autocompleteInput,
56
- {
57
- state: { haystack },
58
- options: autocompleteInputOpts,
59
- },
60
- ],
18
+ {
19
+ fn: autocompleteInput,
20
+ props: { options: { search, debounceMs, onselect } },
21
+ },
61
22
  ]}
62
- {...$$restProps}
63
- /> -->
23
+ aria-autocomplete="list"
24
+ bind:value
25
+ bind:ref
26
+ />
@@ -1,74 +1,59 @@
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'
10
-
11
- let klass = ''
12
- export { klass as class }
13
- export let id
14
- export let options = {}
15
-
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 = ''
29
-
30
- $: Box = $comboboxes.find(c => c.id === listboxId)
31
- $: if (Box) {
32
- matches = Box.state.matches
33
- searchState = Box.state.searchState
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'
6
+
7
+ let {
8
+ ref = $bindable(null),
9
+ id,
10
+ items,
11
+ filterBy,
12
+ option,
13
+ loading,
14
+ empty,
15
+ children,
16
+ ...rest
17
+ } = $props()
18
+
19
+ const combobox = $derived(getCombobox(id))
20
+ const shownItems = $derived(combobox?.state.results ?? items)
21
+ const searchState = $derived(combobox?.state.searchState ?? 'idle')
22
+
23
+ function getText(item) {
24
+ return filterBy ? getNestedValue(item, filterBy) : item
34
25
  }
35
- </script> -->
26
+ </script>
36
27
 
37
- <!-- <PopoverContent
28
+ <ComboboxOptions
29
+ {...rest}
38
30
  {id}
39
- class="AutocompleteOptions ListboxPopover {klass}"
40
- options={opts}
31
+ actions={[{ fn: autocompleteOptions, props: { items: shownItems } }]}
32
+ bind:ref
41
33
  >
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>
34
+ {#if shownItems}
35
+ {#each shownItems as item, index (index)}
36
+ {@const text = getText(item)}
37
+ <li
38
+ id="{id}-option-{index}"
39
+ data-index={index}
40
+ data-text={text}
41
+ role="option"
42
+ >
43
+ {#if option}{@render option(item)}{:else}{text}{/if}
44
+ </li>
45
+ {/each}
46
+ {:else}
47
+ {@render children?.()}
62
48
  {/if}
63
49
 
64
- {#if searchState === 'searching'}
65
- <div class="Card AutocompleteLoader">
66
- <slot name="loading">Loading...</slot>
67
- </div>
68
- {/if}
50
+ {#snippet status()}
51
+ {#if searchState === 'searching' && loading}
52
+ <div class="combobox-status">{@render loading()}</div>
53
+ {/if}
69
54
 
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> -->
55
+ {#if searchState === 'done' && !shownItems?.length && empty}
56
+ <div class="combobox-status">{@render empty()}</div>
57
+ {/if}
58
+ {/snippet}
59
+ </ComboboxOptions>
@@ -0,0 +1,37 @@
1
+ <script>
2
+ import { init } from '../../../utils'
3
+ import TextInput from '../TextInput.svelte'
4
+ import { comboboxInput } from './combobox.svelte.js'
5
+
6
+ let {
7
+ value = $bindable(''),
8
+ ref = $bindable(null),
9
+ target,
10
+ loop,
11
+ onselect,
12
+ actions = [],
13
+ ...rest
14
+ } = $props()
15
+
16
+ init(() => {
17
+ if (!target) throw new Error('ComboboxInput requires a target')
18
+ })
19
+ </script>
20
+
21
+ <TextInput
22
+ {...rest}
23
+ actions={[
24
+ {
25
+ fn: comboboxInput,
26
+ props: { options: { loop, onselect } },
27
+ },
28
+ ...actions,
29
+ ]}
30
+ aria-controls="{target}-listbox"
31
+ aria-expanded="false"
32
+ autocomplete="off"
33
+ role="combobox"
34
+ {target}
35
+ bind:value
36
+ bind:ref
37
+ />
@@ -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,69 @@
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
+ * autosuggest-highlight strips diacritics before matching, so "cafe" matches "Café".
5
+ */
6
+ import aMatch from 'autosuggest-highlight/match/index.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: getRanges({ 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
+ function getMatchingIndexes({ texts, query, insideWords }) {
53
+ return texts.flatMap((text, index) => {
54
+ const ranges = getRanges({ text, query, insideWords })
55
+ return ranges.length ? [index] : []
75
56
  })
76
57
  }
77
58
 
78
- // Returns list of matches
79
- function _getMatch(string, query, options = {}) {
80
- const opts = mix({}, defaultSuggestOptions, options)
81
- return aMatch(string, query, opts)
59
+ function getRanges({ text, query, insideWords }) {
60
+ return aMatch(text, query, { insideWords, requireMatchAll: true })
82
61
  }
83
62
 
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
- }
63
+ function isPerfectMatch({ text, query }) {
64
+ if (text.length !== query.length) return false
103
65
 
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('')
66
+ const ranges = getRanges({ text, query, insideWords: true })
67
+ if (!ranges.length) return false
68
+ return ranges[0][0] === 0 && ranges.at(-1)[1] === text.length
114
69
  }