@splendidlabz/svelte 4.15.0 → 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.
package/LICENSE.md ADDED
@@ -0,0 +1,95 @@
1
+ Copyright (c) 2024-present Splendid Labz Pte. Ltd.
2
+
3
+ Elastic License 2.0
4
+
5
+ URL: https://www.elastic.co/licensing/elastic-license
6
+
7
+ ## Acceptance
8
+
9
+ By using the software, you agree to all of the terms and conditions below.
10
+
11
+ ## Copyright License
12
+
13
+ The licensor grants you a non-exclusive, royalty-free, worldwide,
14
+ non-sublicensable, non-transferable license to use, copy, distribute, make
15
+ available, and prepare derivative works of the software, in each case subject to
16
+ the limitations and conditions below.
17
+
18
+ ## Limitations
19
+
20
+ You may not provide the software to third parties as a hosted or managed
21
+ service, where the service provides users with access to any substantial set of
22
+ the features or functionality of the software.
23
+
24
+ You may not move, change, disable, or circumvent the license key functionality
25
+ in the software, and you may not remove or obscure any functionality in the
26
+ software that is protected by the license key.
27
+
28
+ You may not alter, remove, or obscure any licensing, copyright, or other notices
29
+ of the licensor in the software. Any use of the licensor’s trademarks is subject
30
+ to applicable law.
31
+
32
+ ## Patents
33
+
34
+ The licensor grants you a license, under any patent claims the licensor can
35
+ license, or becomes able to license, to make, have made, use, sell, offer for
36
+ sale, import and have imported the software, in each case subject to the
37
+ limitations and conditions in this license. This license does not cover any
38
+ patent claims that you cause to be infringed by modifications or additions to
39
+ the software. If you or your company make any written claim that the software
40
+ infringes or contributes to infringement of any patent, your patent license for
41
+ the software granted under these terms ends immediately. If your company makes
42
+ such a claim, your patent license ends immediately for work on behalf of your
43
+ company.
44
+
45
+ ## Notices
46
+
47
+ You must ensure that anyone who gets a copy of any part of the software from you
48
+ also gets a copy of these terms.
49
+
50
+ If you modify the software, you must include in any modified copies of the
51
+ software prominent notices stating that you have modified the software.
52
+
53
+ ## No Other Rights
54
+
55
+ These terms do not imply any licenses other than those expressly granted in
56
+ these terms.
57
+
58
+ ## Termination
59
+
60
+ If you use the software in violation of these terms, such use is not licensed,
61
+ and your licenses will automatically terminate. If the licensor provides you
62
+ with a notice of your violation, and you cease all violation of this license no
63
+ later than 30 days after you receive that notice, your licenses will be
64
+ reinstated retroactively. However, if you violate these terms after such
65
+ reinstatement, any additional violation of these terms will cause your licenses
66
+ to terminate automatically and permanently.
67
+
68
+ ## No Liability
69
+
70
+ _As far as the law allows, the software comes as is, without any warranty or
71
+ condition, and the licensor will not be liable to you for any damages arising
72
+ out of these terms or the use or nature of the software, under any kind of
73
+ legal claim._
74
+
75
+ ## Definitions
76
+
77
+ The **licensor** is the entity offering these terms, and the **software** is the
78
+ software the licensor makes available under these terms, including any portion
79
+ of it.
80
+
81
+ **you** refers to the individual or entity agreeing to these terms.
82
+
83
+ **your company** is any legal entity, sole proprietorship, or other kind of
84
+ organization that you work for, plus all organizations that have control over,
85
+ are under the control of, or are under common control with that
86
+ organization. **control** means ownership of substantially all the assets of an
87
+ entity, or the power to direct its management and policies by vote, contract, or
88
+ otherwise. Control can be direct or indirect.
89
+
90
+ **your licenses** are all the licenses granted to you for the software under
91
+ these terms.
92
+
93
+ **use** means anything you do with the software requiring one of your licenses.
94
+
95
+ **trademark** means trademarks, service marks, and similar rights.
@@ -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
  }