@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.
package/README.md ADDED
@@ -0,0 +1,44 @@
1
+ # @splendidlabz/svelte
2
+
3
+ Svelte 5 components for Astro and Svelte projects: forms, disclosures, tabs, content helpers and media.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @splendidlabz/svelte @splendidlabz/styles
9
+ ```
10
+
11
+ ## Styles
12
+
13
+ The components use class names from `@splendidlabz/styles`. Point Tailwind at this package so it scans them:
14
+
15
+ ```css
16
+ @source "../node_modules/@splendidlabz/svelte";
17
+
18
+ @import 'tailwindcss';
19
+ @import '@splendidlabz/styles/base';
20
+ @import '@splendidlabz/styles/components/svelte';
21
+ ```
22
+
23
+ ## Use
24
+
25
+ ```svelte
26
+ <script>
27
+ import { Select, SelectOptions } from '@splendidlabz/svelte'
28
+ </script>
29
+
30
+ <Select name="country" label="Country" target="countries" />
31
+ <SelectOptions
32
+ id="countries"
33
+ aria-label="Countries"
34
+ items={['Malaysia', 'Singapore']}
35
+ />
36
+ ```
37
+
38
+ In Astro, hydrate interactive components with `client:load`. Props that take a function or a snippet need a Svelte file.
39
+
40
+ Actions and utilities have their own entry points: `@splendidlabz/svelte/actions` and `@splendidlabz/svelte/utils`.
41
+
42
+ ## Docs
43
+
44
+ https://splendidlabz.com/docs/svelte
@@ -0,0 +1,208 @@
1
+ <script>
2
+ import { randomString } from '@splendidlabz/utils/dom'
3
+ import { useActions } from '../../../actions/use-actions'
4
+ import { init } from '../../../utils'
5
+ import FieldMeta from '../FieldMeta.svelte'
6
+ import { autocompleteInput } from './autocomplete.svelte.js'
7
+ import Chips from './Chips.svelte'
8
+ import { comboboxInput, getCombobox } from './combobox.svelte.js'
9
+ import { toSelectedOptions } from './select.svelte.js'
10
+
11
+ /**
12
+ * @import { Snippet } from 'svelte'
13
+ * @import { SelectedOption, SelectEntry } from './select.svelte.js'
14
+ */
15
+
16
+ /**
17
+ * @typedef {object} AutocompleteProps
18
+ * @property {string} name Name the selection submits under
19
+ * @property {string} target Id of the options
20
+ * @property {SelectEntry | SelectEntry[] | null} [selected] One entry, or an array with `multiple`. Bindable.
21
+ * @property {string} [value] Typed text, bindable
22
+ * @property {HTMLInputElement | null} [ref]
23
+ * @property {boolean} [multiple] Let more than one option be selected
24
+ * @property {number} [max] Most options a multi select takes
25
+ * @property {boolean} [creatable] Accept text that matches no option
26
+ * @property {(text: string) => string} [onCreateValue] Value for created text
27
+ * @property {boolean} [caseSensitive] Match case while filtering and creating
28
+ * @property {string | string[]} [matchBy] Keys typing matches against
29
+ * @property {(query: string) => Promise<any[]>} [search] Fetches options as someone types
30
+ * @property {number} [debounceMs] Wait before searching
31
+ * @property {(item: any) => void} [onselect] Receives the item, or the option element
32
+ * @property {boolean} [openOnFocus] Open the options on focus
33
+ * @property {boolean} [loop] Wrap past either end
34
+ * @property {string} [id]
35
+ * @property {string} [label]
36
+ * @property {boolean} [labelVisible]
37
+ * @property {string | null} [hint]
38
+ * @property {string | null} [error]
39
+ * @property {boolean | null} [disabled]
40
+ * @property {boolean | null} [readonly]
41
+ * @property {string} [class]
42
+ * @property {string} [style]
43
+ * @property {string} [labelClass]
44
+ * @property {string} [hintClass]
45
+ * @property {string} [errorClass]
46
+ * @property {string} [inputGroupClass]
47
+ * @property {string} [fieldClass]
48
+ * @property {string} [chipsClass]
49
+ * @property {Snippet<[SelectedOption]>} [chip] Replaces a chip's label
50
+ * @property {{ fn: Function, props?: any }[]} [actions] Actions run on the input
51
+ */
52
+
53
+ /** @type {AutocompleteProps & Record<string, any>} */
54
+ let {
55
+ value = $bindable(''),
56
+ selected = $bindable(),
57
+ ref = $bindable(null),
58
+ // Classes
59
+ class: klass,
60
+ style,
61
+ labelClass,
62
+ hintClass,
63
+ errorClass,
64
+ inputGroupClass,
65
+ fieldClass,
66
+ chipsClass,
67
+ // Slots
68
+ chip,
69
+ // Options and props
70
+ id = randomString(8),
71
+ name,
72
+ target,
73
+ label = '',
74
+ labelVisible = true,
75
+ hint = null,
76
+ error = null,
77
+ disabled = null,
78
+ readonly = null,
79
+ multiple = false,
80
+ max,
81
+ creatable = false,
82
+ caseSensitive = false,
83
+ matchBy,
84
+ onCreateValue,
85
+ openOnFocus = true,
86
+ search,
87
+ debounceMs,
88
+ onselect,
89
+ loop = true,
90
+ actions = [],
91
+ ...rest
92
+ } = $props()
93
+
94
+ init(() => {
95
+ if (!name) throw new Error('Autocomplete requires a name')
96
+ if (!target) throw new Error('Autocomplete requires a target')
97
+
98
+ // A single select shows its selection as the input's text
99
+ if (!multiple) value = toSelectedOptions(selected)[0]?.label ?? ''
100
+ })
101
+
102
+ const combobox = $derived(getCombobox(target))
103
+ const selectedOptions = $derived(
104
+ combobox?.state.selected ?? toSelectedOptions(selected),
105
+ )
106
+
107
+ // A single selection is the input's text, so only a multi select shows chips
108
+ const chips = $derived(multiple ? selectedOptions : [])
109
+
110
+ // A multi select submits an array, the way NativeSelect does
111
+ const hiddenName = $derived(multiple ? `${name}[]` : name)
112
+
113
+ // Only a selection passed in can go over the cap, since the field refuses the option past it
114
+ const maxError = $derived(
115
+ max && selectedOptions.length > max
116
+ ? `Choose no more than ${max} option${max === 1 ? '' : 's'}.`
117
+ : null,
118
+ )
119
+ const fieldError = $derived(error ?? maxError)
120
+
121
+ // IDs for aria-describedby
122
+ const hintId = $derived(hint ? id + '-hint' : '')
123
+ const errorId = $derived(id + '-error')
124
+ const describedBy = $derived(`${hintId} ${errorId}`.trim() || null)
125
+ </script>
126
+
127
+ <div
128
+ {style}
129
+ class="input-container combobox autocomplete {klass}"
130
+ class:disabled
131
+ class:readonly
132
+ >
133
+ <FieldMeta
134
+ {id}
135
+ error={fieldError}
136
+ {errorClass}
137
+ {hint}
138
+ {hintClass}
139
+ {label}
140
+ {labelClass}
141
+ {labelVisible}
142
+ />
143
+
144
+ <div class="input-group {inputGroupClass}">
145
+ <Chips
146
+ class={chipsClass}
147
+ {chip}
148
+ disabled={disabled || readonly}
149
+ selected={chips}
150
+ {target}
151
+ />
152
+
153
+ <input
154
+ {...rest}
155
+ bind:this={ref}
156
+ {id}
157
+ class="input {fieldClass}"
158
+ aria-autocomplete="list"
159
+ aria-controls="{target}-listbox"
160
+ aria-describedby={describedBy}
161
+ aria-expanded="false"
162
+ aria-invalid={fieldError ? 'true' : null}
163
+ aria-label={!labelVisible && label ? label : null}
164
+ autocomplete="off"
165
+ disabled={disabled || readonly}
166
+ role="combobox"
167
+ {target}
168
+ type="text"
169
+ bind:value
170
+ use:useActions={[
171
+ {
172
+ fn: comboboxInput,
173
+ props: {
174
+ options: {
175
+ loop,
176
+ onselectedchange:
177
+ /** @param {SelectedOption | SelectedOption[] | null} next */ next =>
178
+ (selected = next),
179
+ },
180
+ },
181
+ },
182
+ {
183
+ fn: autocompleteInput,
184
+ props: {
185
+ options: {
186
+ search,
187
+ debounceMs,
188
+ onselect,
189
+ multiple,
190
+ max,
191
+ creatable,
192
+ caseSensitive,
193
+ matchBy,
194
+ onCreateValue,
195
+ openOnFocus,
196
+ selected,
197
+ },
198
+ },
199
+ },
200
+ ...actions,
201
+ ]}
202
+ />
203
+ </div>
204
+
205
+ {#each selectedOptions as option (option.value)}
206
+ <input name={hiddenName} {disabled} type="hidden" value={option.value} />
207
+ {/each}
208
+ </div>
@@ -1,60 +1,131 @@
1
1
  <script>
2
- import { getNestedValue } from '@splendidlabz/utils'
3
- import { autocompleteOptions } from './autocomplete.svelte.js'
2
+ import {
3
+ getMatchData,
4
+ mergeItems,
5
+ orderItems,
6
+ } from './autocomplete.svelte.js'
4
7
  import { getCombobox } from './combobox.svelte.js'
5
8
  import ComboboxOptions from './ComboboxOptions.svelte'
9
+ import { getValueAndLabel, selectOptions } from './select.svelte.js'
6
10
 
11
+ /**
12
+ * @import { Snippet } from 'svelte'
13
+ * @import { OrderBy } from './autocomplete.svelte.js'
14
+ * @import { SelectEntry } from './select.svelte.js'
15
+ */
16
+
17
+ /**
18
+ * @typedef {object} AutocompleteOptionsProps
19
+ * @property {string} id Matches the Autocomplete's `target`
20
+ * @property {SelectEntry[]} [items] Options to render. With `search`, what shows before results arrive. A string is both value and label.
21
+ * @property {OrderBy} [orderBy] Key or comparator sorting `items` and results
22
+ * @property {HTMLDivElement | null} [ref]
23
+ * @property {string} [class]
24
+ * @property {boolean} [inline] Render in the flow instead of a popover
25
+ * @property {number} [size] How many options to show before scrolling
26
+ * @property {string} [aria-label]
27
+ * @property {string} [aria-labelledby]
28
+ * @property {Snippet<[any]>} [option] Replaces an option's contents
29
+ * @property {Snippet} [check] Replaces the check a selected option shows
30
+ * @property {Snippet} [loading] Shows while `search` runs
31
+ * @property {Snippet} [empty] Shows when `search` finds nothing
32
+ * @property {Snippet} [failed] Shows when `search` throws
33
+ * @property {Snippet<[string]>} [create] Replaces the create option's wording
34
+ * @property {Snippet} [children] Options written as `<li>` elements
35
+ */
36
+
37
+ /** @type {AutocompleteOptionsProps & Record<string, any>} */
7
38
  let {
8
39
  ref = $bindable(null),
9
40
  id,
10
41
  items,
11
- filterBy,
42
+ orderBy,
12
43
  option,
13
44
  loading,
14
45
  empty,
15
46
  failed,
47
+ create,
16
48
  children,
17
49
  ...rest
18
50
  } = $props()
19
51
 
20
52
  const combobox = $derived(getCombobox(id))
21
- const shownItems = $derived(combobox?.state.results ?? items)
53
+ const results = $derived(combobox?.state.results)
54
+ const shownItems = $derived(
55
+ items || results
56
+ ? orderItems({ items: mergeItems({ items, results }), orderBy })
57
+ : undefined,
58
+ )
22
59
  const searchState = $derived(combobox?.state.searchState ?? 'idle')
60
+ const matchCount = $derived(combobox?.state.matchCount ?? 0)
61
+ const created = $derived(combobox?.state.created ?? [])
62
+ const query = $derived(combobox?.state.query ?? '')
23
63
 
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
32
- }
64
+ // The input part registers these, and it can hydrate after this one
65
+ const multiple = $derived(combobox?.options.multiple ?? false)
66
+ const creatable = $derived(combobox?.options.creatable ?? false)
67
+ const matchBy = $derived(combobox?.options.matchBy)
68
+
69
+ // Text an option already says needs no create option under it
70
+ const canCreate = $derived(
71
+ creatable && Boolean(query) && !combobox?.state.hasExactMatch,
72
+ )
33
73
  </script>
34
74
 
35
75
  <ComboboxOptions
36
76
  {...rest}
37
77
  {id}
38
- actions={[{ fn: autocompleteOptions, props: { items: shownItems } }]}
78
+ actions={[{ fn: selectOptions, props: { items: shownItems } }]}
79
+ {multiple}
39
80
  bind:ref
40
81
  >
41
82
  {#if shownItems}
42
83
  {#each shownItems as item, index (index)}
43
- {@const text = getText(item)}
44
- <!-- svelte-ignore a11y_role_has_required_aria_props -->
84
+ {@const { value, label } = getValueAndLabel(item)}
45
85
  <li
86
+ {...getMatchData({ item, matchBy })}
46
87
  id="{id}-option-{index}"
47
88
  data-index={index}
48
- data-text={text}
89
+ data-label={label}
90
+ data-position={index}
91
+ data-value={value}
49
92
  role="option"
50
93
  >
51
- {#if option}{@render option(item)}{:else}{text}{/if}
94
+ {#if option}{@render option(item)}{:else}{label}{/if}
52
95
  </li>
53
96
  {/each}
54
97
  {:else}
55
98
  {@render children?.()}
56
99
  {/if}
57
100
 
101
+ <!-- A created value is an option like any other, from the moment it is made. `data-appended` says it renders from its own block below the list, so filtering leaves it where it is. -->
102
+ {#each created as createdOption (createdOption.value)}
103
+ <li
104
+ id="{id}-created-{createdOption.value}"
105
+ aria-selected="true"
106
+ data-appended=""
107
+ data-label={createdOption.label}
108
+ data-value={createdOption.value}
109
+ role="option"
110
+ >
111
+ {createdOption.label}
112
+ </li>
113
+ {/each}
114
+
115
+ {#if canCreate}
116
+ <!-- svelte-ignore a11y_role_has_required_aria_props -->
117
+ <li
118
+ id="{id}-create"
119
+ class="select-create"
120
+ data-appended=""
121
+ data-create=""
122
+ data-label={query}
123
+ role="option"
124
+ >
125
+ {#if create}{@render create(query)}{:else}Create "{query}"{/if}
126
+ </li>
127
+ {/if}
128
+
58
129
  {#snippet status()}
59
130
  {#if searchState === 'searching' && loading}
60
131
  <div class="combobox-status" data-state="searching">
@@ -62,7 +133,7 @@
62
133
  </div>
63
134
  {/if}
64
135
 
65
- {#if searchState === 'done' && !shownItems?.length && empty}
136
+ {#if searchState === 'done' && !matchCount && empty}
66
137
  <div class="combobox-status" data-state="empty">{@render empty()}</div>
67
138
  {/if}
68
139
 
@@ -0,0 +1,58 @@
1
+ <script>
2
+ import { getCombobox } from './combobox.svelte.js'
3
+
4
+ /**
5
+ * @import { Snippet } from 'svelte'
6
+ * @import { SelectedOption } from './select.svelte.js'
7
+ */
8
+
9
+ /**
10
+ * @typedef {object} ChipsProps
11
+ * @property {string} target Id of the options
12
+ * @property {SelectedOption[]} selected Options shown as chips
13
+ * @property {Snippet<[SelectedOption]>} [chip] Replaces a chip's label
14
+ * @property {boolean | null} [disabled] Stops chips being removed
15
+ * @property {string} [class]
16
+ */
17
+
18
+ /** @type {ChipsProps} */
19
+ let { target, selected, chip, disabled = null, class: klass = '' } = $props()
20
+
21
+ /**
22
+ * removeChip
23
+ * Tells the field a chip was removed.
24
+ *
25
+ * @param {string} value
26
+ */
27
+ function removeChip(value) {
28
+ getCombobox(target)?.nodes.input.dispatchEvent(
29
+ new CustomEvent('chipremove', { detail: { value } }),
30
+ )
31
+ }
32
+ </script>
33
+
34
+ {#if selected.length}
35
+ <ul class="chips {klass}">
36
+ {#each selected as option (option.value)}
37
+ <li class="chip">
38
+ {#if chip}{@render chip(option)}{:else}{option.label}{/if}
39
+ <button
40
+ class="chip-remove-button"
41
+ aria-label="Remove {option.label}"
42
+ {disabled}
43
+ onclick={() => removeChip(option.value)}
44
+ type="button"
45
+ >
46
+ <svg aria-hidden="true" fill="none" viewBox="0 0 24 24">
47
+ <path
48
+ d="M6 6L18 18M18 6L6 18"
49
+ stroke="currentcolor"
50
+ stroke-linecap="round"
51
+ stroke-width="2"
52
+ />
53
+ </svg>
54
+ </button>
55
+ </li>
56
+ {/each}
57
+ </ul>
58
+ {/if}
@@ -4,15 +4,39 @@
4
4
  import { init } from '../../../utils'
5
5
  import { comboboxOptions } from './combobox.svelte.js'
6
6
 
7
+ /**
8
+ * @import { Snippet } from 'svelte'
9
+ */
10
+
11
+ /**
12
+ * @typedef {object} ComboboxOptionsProps
13
+ * @property {string} id Matches the input's `target`
14
+ * @property {HTMLDivElement | null} [ref]
15
+ * @property {string} [class]
16
+ * @property {boolean} [inline] Render in the flow instead of a popover
17
+ * @property {boolean} [multiple] Let more than one option be selected
18
+ * @property {number} [size] How many options to show before scrolling
19
+ * @property {string} [aria-label]
20
+ * @property {string} [aria-labelledby]
21
+ * @property {{ fn: Function, props?: any }[]} [actions] Actions run on the wrapper
22
+ * @property {Snippet} [status] Renders after the listbox
23
+ * @property {Snippet} [check] Replaces the check a selected option shows
24
+ * @property {Snippet} [children] The options
25
+ */
26
+
27
+ /** @type {ComboboxOptionsProps & Record<string, any>} */
7
28
  let {
8
29
  ref = $bindable(null),
9
30
  class: klass = '',
10
31
  id,
11
32
  inline = false,
33
+ multiple = false,
34
+ size = 8,
12
35
  'aria-label': ariaLabel,
13
36
  'aria-labelledby': ariaLabelledBy,
14
37
  actions = [],
15
38
  status,
39
+ check,
16
40
  children,
17
41
  ...rest
18
42
  } = $props()
@@ -33,7 +57,7 @@
33
57
  {id}
34
58
  class="combobox-options {klass}"
35
59
  popover={inline ? null : 'manual'}
36
- use:comboboxOptions
60
+ use:comboboxOptions={{ multiple, size }}
37
61
  use:useActions={actions}
38
62
  >
39
63
  <ul
@@ -41,9 +65,29 @@
41
65
  aria-label={ariaLabel}
42
66
  aria-labelledby={ariaLabelledBy}
43
67
  role="listbox"
68
+ tabindex="-1"
44
69
  >
45
70
  {@render children?.()}
46
71
  </ul>
47
72
 
48
73
  {@render status?.()}
74
+
75
+ <!-- prepareOptions copies this into every option, since Svelte can't render into slot options -->
76
+ <div class="option-check-source" hidden>
77
+ <span class="option-check" aria-hidden="true">
78
+ {#if check}
79
+ {@render check()}
80
+ {:else}
81
+ <svg fill="none" height="24" viewBox="0 0 24 24" width="24">
82
+ <path
83
+ d="M5 12L10 17L20 7"
84
+ stroke="currentcolor"
85
+ stroke-linecap="round"
86
+ stroke-linejoin="round"
87
+ stroke-width="2"
88
+ />
89
+ </svg>
90
+ {/if}
91
+ </span>
92
+ </div>
49
93
  </div>