@splendidlabz/svelte 4.16.0 → 4.17.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.
@@ -14,7 +14,9 @@ import {
14
14
  highlightOption,
15
15
  prepareOptions,
16
16
  selectOption,
17
+ showOptionCount,
17
18
  } from './listbox.js'
19
+ import { canSelectOption, deselect } from './select.svelte.js'
18
20
 
19
21
  // ========================================
20
22
  // Shared state
@@ -30,10 +32,12 @@ const comboboxes = $state([])
30
32
  *
31
33
  * @typedef {object} Combobox
32
34
  * @property {string} id Id of the options wrapper
33
- * @property {Record<string, any>} state
35
+ * @property {Record<string, any>} state Holds `phase`: closed, open or closing
34
36
  * @property {Record<string, any>} nodes Each part registers its own nodes
35
37
  * @property {Record<string, any>} options
36
38
  * @property {ReturnType<typeof initFloating>} [floating]
39
+ * @property {ResizeObserver} [resizeObserver] Keeps open options as wide as the box
40
+ * @property {() => void} [stopClosing] Ends the fade, leaving the options shown
37
41
  *
38
42
  * @param {string} id
39
43
  * @returns {Combobox | undefined}
@@ -77,13 +81,14 @@ export function initCombobox({ id, state = {}, nodes = {}, options = {} }) {
77
81
  // ========================================
78
82
  /**
79
83
  * comboboxInput
80
- * Lets an input open, move through and select the options it targets.
84
+ * Lets an input or a button open, move through and select the options it targets.
81
85
  *
82
- * @param {HTMLInputElement} node
86
+ * @param {HTMLInputElement | HTMLButtonElement} node
83
87
  * @param {object} [props]
84
88
  * @param {object} [props.options]
85
89
  * @param {boolean} [props.options.loop] Wrap past either end
86
90
  * @param {(option: HTMLElement) => void} [props.options.onselect] Receives the selected option
91
+ * @param {(selected: any) => void} [props.options.onselectedchange] Receives the selection after each change
87
92
  */
88
93
  export function comboboxInput(node, props = {}) {
89
94
  const id = /** @type {string} */ (node.getAttribute('target'))
@@ -93,11 +98,12 @@ export function comboboxInput(node, props = {}) {
93
98
  options: { loop: false, ...omitEmpty(props.options) },
94
99
  })
95
100
 
96
- setInitialExpanded(combobox)
101
+ setInitialPhase(combobox)
97
102
 
98
103
  const listeners = [
99
104
  { event: 'keydown', node, handler: onKeydown },
100
105
  { event: 'focusout', node, handler: onFocusout },
106
+ { event: 'chipremove', node, handler: onChipremove },
101
107
  ]
102
108
 
103
109
  addListeners(listeners)
@@ -127,6 +133,7 @@ export function comboboxInput(node, props = {}) {
127
133
  function onKeydown(event) {
128
134
  const { listbox } = combobox.nodes
129
135
  if (!listbox) return
136
+ if (!canChangeSelection(combobox)) return
130
137
 
131
138
  const { key } = event
132
139
  const isOpen = isComboboxOpen(combobox)
@@ -134,6 +141,9 @@ export function comboboxInput(node, props = {}) {
134
141
  if (key === 'ArrowDown' || key === 'ArrowUp') {
135
142
  event.preventDefault()
136
143
 
144
+ // An arrow means the options are wanted, so it also ends a close still fading
145
+ stopClosingCombobox(combobox)
146
+
137
147
  if (!isOpen) {
138
148
  if (getVisibleOptions(listbox).length) openCombobox(combobox)
139
149
  return
@@ -144,7 +154,7 @@ export function comboboxInput(node, props = {}) {
144
154
  direction: key === 'ArrowDown' ? 'next' : 'prev',
145
155
  loop: combobox.options.loop,
146
156
  })
147
- if (option) highlight(combobox, option)
157
+ if (option) highlight(combobox, option, { behaviour: 'instant' })
148
158
  return
149
159
  }
150
160
 
@@ -154,20 +164,68 @@ export function comboboxInput(node, props = {}) {
154
164
  return
155
165
  }
156
166
 
167
+ // Backspace on empty text takes the last chip off
168
+ if (key === 'Backspace' && combobox.options.multiple && !node.value) {
169
+ const lastSelected = combobox.state.selected.at(-1)
170
+ if (lastSelected) deselect({ combobox, value: lastSelected.value })
171
+ return
172
+ }
173
+
157
174
  const highlightedOption = getHighlightedOption(listbox)
158
- if (!isOpen || !highlightedOption) return
159
175
 
176
+ // An exact match closes a single select, and Enter still picks it
160
177
  if (key === 'Enter') {
161
- event.preventDefault()
162
- commitSelection(combobox, highlightedOption)
178
+ // Create sorts last, so it heads the list only when nothing matched — and that is the only time Enter takes it
179
+ const [firstOption] = getVisibleOptions(listbox)
180
+ const createOption =
181
+ firstOption?.dataset.create === undefined ? null : firstOption
182
+
183
+ const option =
184
+ highlightedOption ?? combobox.options.getTypedOption?.() ?? createOption
185
+ // Enter submits only from a closed list that picks nothing
186
+ if (isOpen || option) event.preventDefault()
187
+
188
+ if (option) commitSelection(combobox, option)
189
+ // An option already says this text, so the field is cleared for the next one
190
+ else if (combobox.options.multiple && combobox.state.hasExactMatch)
191
+ writeInputText(combobox, '')
192
+
193
+ return
163
194
  }
164
195
 
165
- if (isTab(event)) commitSelection(combobox, highlightedOption)
196
+ if (!isOpen) return
197
+
198
+ if (isTab(event) && highlightedOption) {
199
+ commitSelection(combobox, highlightedOption)
200
+ }
166
201
  }
167
202
 
203
+ /**
204
+ * onFocusout
205
+ * Puts the selected label back and closes the options.
206
+ *
207
+ * Text matching no option never stands as the answer.
208
+ */
168
209
  function onFocusout() {
210
+ if (node instanceof HTMLInputElement) {
211
+ const text = combobox.options.multiple
212
+ ? ''
213
+ : (combobox.state.selected[0]?.label ?? '')
214
+ writeInputText(combobox, text)
215
+ }
169
216
  if (combobox.nodes.listbox) closeCombobox(combobox)
170
217
  }
218
+
219
+ /**
220
+ * onChipremove
221
+ * Takes the removed chip off the selection, and puts focus back here.
222
+ *
223
+ * @param {CustomEvent<{ value: string }>} event
224
+ */
225
+ function onChipremove(event) {
226
+ deselect({ combobox, value: event.detail.value })
227
+ node.focus()
228
+ }
171
229
  }
172
230
 
173
231
  /**
@@ -177,31 +235,63 @@ export function comboboxInput(node, props = {}) {
177
235
  * @param {HTMLElement} node Wrapper holding the listbox
178
236
  * @param {object} [props]
179
237
  * @param {boolean} [props.multiple] Let more than one option be selected
238
+ * @param {number} [props.size] How many options to show before scrolling
180
239
  */
181
240
  export function comboboxOptions(node, props = {}) {
182
241
  const listbox = /** @type {HTMLElement} */ (
183
242
  node.querySelector('[role="listbox"]')
184
243
  )
185
- prepareOptions({ listbox, multiple: props.multiple })
244
+ /** @type {HTMLElement | null} */
245
+ const check = node.querySelector('.option-check-source > .option-check')
246
+ let multiple = props.multiple
247
+ let size = props.size
248
+ prepareOptions({ listbox, multiple, check })
249
+ showOptionCount({ listbox, size })
250
+
251
+ // Search results and created values are added after this runs, so they're prepared as they arrive
252
+ const optionsObserver = new MutationObserver(() => {
253
+ prepareOptions({ listbox, multiple, check })
254
+ showOptionCount({ listbox, size })
255
+ })
256
+ optionsObserver.observe(listbox, { childList: true })
186
257
 
187
258
  const combobox = initCombobox({
188
259
  id: node.id,
189
260
  nodes: { listbox, popover: node.hasAttribute('popover') ? node : null },
261
+ options: { size },
190
262
  })
191
263
 
192
- setInitialExpanded(combobox)
264
+ setInitialPhase(combobox)
265
+
266
+ /** @type {number | null} */
267
+ let lastPointerX = null
268
+ /** @type {number | null} */
269
+ let lastPointerY = null
193
270
 
194
271
  const listeners = [
195
272
  { event: 'pointerdown', node, handler: keepInputFocus },
196
- { event: 'pointerover', node: listbox, handler: highlightHoveredOption },
197
- { event: 'click', node: listbox, handler: selectClickedOption },
273
+ { event: 'pointermove', node: listbox, handler: highlightHoveredOption },
274
+ { event: 'pointerup', node: listbox, handler: selectReleasedOption },
198
275
  ]
199
276
 
200
277
  addListeners(listeners)
201
278
 
202
279
  return {
280
+ /**
281
+ * update
282
+ * Prepares options Svelte added, and takes `multiple` once the input registers it.
283
+ *
284
+ * @param {typeof props} [nextProps]
285
+ */
286
+ update(nextProps = {}) {
287
+ multiple = nextProps.multiple
288
+ size = nextProps.size
289
+ prepareOptions({ listbox, multiple, check })
290
+ showOptionCount({ listbox, size })
291
+ },
203
292
  destroy() {
204
293
  removeListeners(listeners)
294
+ optionsObserver.disconnect()
205
295
  removeComboboxNodes({ combobox, names: ['listbox', 'popover'] })
206
296
  },
207
297
  }
@@ -223,17 +313,31 @@ export function comboboxOptions(node, props = {}) {
223
313
  * @param {PointerEvent} event
224
314
  */
225
315
  function highlightHoveredOption(event) {
316
+ if (!canChangeSelection(combobox)) return
317
+
318
+ // Scrolling fires pointermove at the resting coordinates, so an option arriving under a still pointer doesn't take the keyboard's place
319
+ const hasMoved =
320
+ event.clientX !== lastPointerX || event.clientY !== lastPointerY
321
+ lastPointerX = event.clientX
322
+ lastPointerY = event.clientY
323
+ if (!hasMoved) return
324
+
226
325
  const option = getEventOption(event)
227
326
  if (option) highlight(combobox, option, { shouldScroll: false })
228
327
  }
229
328
 
230
329
  /**
231
- * selectClickedOption
232
- * Selects the clicked option.
330
+ * selectReleasedOption
331
+ * Selects the option the pointer lifts over, so a press on the trigger can drag into the list and release on a choice.
233
332
  *
234
- * @param {MouseEvent} event
333
+ * @param {PointerEvent} event
235
334
  */
236
- function selectClickedOption(event) {
335
+ function selectReleasedOption(event) {
336
+ if (!canChangeSelection(combobox)) return
337
+
338
+ // A list still fading is on its way out, so a release that lands on it picks nothing
339
+ if (combobox.state.phase === 'closing') return
340
+
237
341
  const option = getEventOption(event)
238
342
  if (option) commitSelection(combobox, option)
239
343
  }
@@ -244,35 +348,58 @@ export function comboboxOptions(node, props = {}) {
244
348
  // ========================================
245
349
  /**
246
350
  * openCombobox
247
- * Shows the options under the input.
351
+ * Shows the options under the input's box, as wide as the box.
248
352
  *
249
- * Inline options are always shown, so this only changes popover options.
353
+ * Inline options are always shown, so this only changes popover options. Chips share the box with the input, so the box can change size while the options are open.
250
354
  *
251
355
  * @param {Combobox} combobox
252
356
  * @returns {void}
253
357
  */
254
358
  export function openCombobox(combobox) {
255
- if (isComboboxOpen(combobox)) return
256
-
257
359
  const { input, popover } = combobox.nodes
360
+
361
+ stopClosingCombobox(combobox)
362
+ if (combobox.state.phase === 'open') return
363
+
364
+ combobox.state.phase = 'open'
258
365
  input.setAttribute('aria-expanded', 'true')
259
366
 
260
- popover.style.width = `${input.getBoundingClientRect().width}px`
367
+ const box = input.closest('.input-group') ?? input
368
+ function matchBoxWidth() {
369
+ popover.style.width = `${box.getBoundingClientRect().width}px`
370
+ }
371
+
372
+ // Hidden until the first position lands, because floating-ui computes it a tick after the popover is shown
373
+ matchBoxWidth()
374
+ popover.style.visibility = 'hidden'
261
375
  popover.showPopover()
262
376
 
377
+ combobox.resizeObserver = new ResizeObserver(matchBoxWidth)
378
+ combobox.resizeObserver.observe(box)
379
+
263
380
  combobox.floating ??= initFloating({
264
- referenceNode: input,
381
+ referenceNode: box,
265
382
  floatingNode: popover,
266
383
  placement: 'bottom-start',
267
384
  offset: 0,
268
385
  })
269
386
  combobox.floating.update()
387
+
388
+ // Options measure 0 while the popover is closed, so the cap is set here, once they have a height
389
+ showOptionCount({
390
+ listbox: combobox.nodes.listbox,
391
+ size: combobox.options.size,
392
+ })
393
+
394
+ requestAnimationFrame(() => popover.style.removeProperty('visibility'))
270
395
  }
271
396
 
272
397
  /**
273
398
  * closeCombobox
274
399
  * Hides popover options and clears the highlight.
275
400
  *
401
+ * The options stay on screen while they fade, so the combobox still reads as open until the fade ends. A click on the input during the fade closes rather than reopens, and a reopen picks the options up where they are.
402
+ *
276
403
  * @param {Combobox} combobox
277
404
  * @returns {void}
278
405
  */
@@ -282,52 +409,89 @@ export function closeCombobox(combobox) {
282
409
  clearHighlight(listbox)
283
410
  input.removeAttribute('aria-activedescendant')
284
411
 
285
- if (!popover || !isComboboxOpen(combobox)) return
412
+ // Nothing to close, or a close already running that's left to finish
413
+ if (!popover || combobox.state.phase !== 'open') return
286
414
 
287
- input.setAttribute('aria-expanded', 'false')
288
- popover.hidePopover()
289
- combobox.floating?.cleanup()
415
+ function onFadeEnd(/** @type {TransitionEvent} */ event) {
416
+ if (event.target !== popover) return
417
+ if (event.propertyName !== 'opacity') return
418
+ hideOptions()
419
+ }
420
+
421
+ // Takes the options off screen once they have faded
422
+ function hideOptions() {
423
+ combobox.stopClosing?.()
424
+ combobox.state.phase = 'closed'
425
+ input.setAttribute('aria-expanded', 'false')
426
+ popover.hidePopover()
427
+ combobox.floating?.cleanup()
428
+ combobox.resizeObserver?.disconnect()
429
+ }
430
+
431
+ // Nothing to fade — reduced motion, a zero duration, or a test environment
432
+ const duration = fadeDuration(popover)
433
+ if (!duration) return hideOptions()
434
+
435
+ // Fades the options out here rather than leaving it to the browser. Safari runs no transition when it tears a popover down, so the list would vanish instead of fading.
436
+ combobox.state.phase = 'closing'
437
+ popover.style.opacity = '0'
438
+ popover.addEventListener('transitionend', onFadeEnd)
439
+
440
+ // Covers a fade the engine skips
441
+ const timer = setTimeout(hideOptions, duration + 50)
442
+
443
+ combobox.stopClosing = function stopClosing() {
444
+ combobox.stopClosing = undefined
445
+ combobox.state.phase = 'open'
446
+ popover.removeEventListener('transitionend', onFadeEnd)
447
+ clearTimeout(timer)
448
+ popover.style.removeProperty('opacity')
449
+ }
290
450
  }
291
451
 
292
452
  /**
293
- * isComboboxOpen
294
- * Reads whether the input says its options are shown.
453
+ * stopClosingCombobox
454
+ * Ends a close still fading, so the options stay on screen at full strength.
295
455
  *
296
456
  * @param {Combobox} combobox
457
+ * @returns {void}
297
458
  */
298
- function isComboboxOpen(combobox) {
299
- return combobox.nodes.input.getAttribute('aria-expanded') === 'true'
459
+ export function stopClosingCombobox(combobox) {
460
+ combobox.stopClosing?.()
300
461
  }
301
462
 
302
463
  /**
303
- * setInitialExpanded
304
- * Starts the input expanded when its options are inline, since those are always shown.
464
+ * fadeDuration
465
+ * Reads how long the options take to fade, in milliseconds.
305
466
  *
306
- * @param {Combobox} combobox
467
+ * @param {HTMLElement} popover
468
+ * @returns {number}
307
469
  */
308
- function setInitialExpanded(combobox) {
309
- const { input, listbox, popover } = combobox.nodes
310
- if (!input || !listbox) return
311
- input.setAttribute('aria-expanded', String(!popover))
470
+ function fadeDuration(popover) {
471
+ const { transitionDuration, transitionProperty } = getComputedStyle(popover)
472
+ const properties = (transitionProperty ?? '')
473
+ .split(',')
474
+ .map(one => one.trim())
475
+ const durations = (transitionDuration ?? '').split(',').map(one => one.trim())
476
+ const index = properties.indexOf('opacity')
477
+ const duration = durations[index] || durations[0] || '0s'
478
+
479
+ const milliseconds = duration.endsWith('ms')
480
+ ? parseFloat(duration)
481
+ : parseFloat(duration) * 1000
482
+
483
+ // A test environment reports no transition at all, and NaN would make the timer fire on the next tick
484
+ return Number.isFinite(milliseconds) ? milliseconds : 0
312
485
  }
313
486
 
314
487
  /**
315
- * removeComboboxNodes
316
- * Drops a destroyed part's nodes, and the entry once no part is left.
488
+ * isComboboxOpen
489
+ * Reads whether the options are on screen, counting a close still fading.
317
490
  *
318
- * @param {object} opts
319
- * @param {Combobox} opts.combobox
320
- * @param {string[]} opts.names Node names the part registered
491
+ * @param {Combobox} combobox
321
492
  */
322
- function removeComboboxNodes({ combobox, names }) {
323
- // Positioning points at the old nodes, so the next open rebuilds it
324
- combobox.floating?.cleanup()
325
- delete combobox.floating
326
-
327
- for (const name of names) delete combobox.nodes[name]
328
- if (combobox.nodes.input || combobox.nodes.listbox) return
329
-
330
- comboboxes.splice(comboboxes.indexOf(combobox), 1)
493
+ export function isComboboxOpen(combobox) {
494
+ return combobox.state.phase !== 'closed'
331
495
  }
332
496
 
333
497
  /**
@@ -338,9 +502,19 @@ function removeComboboxNodes({ combobox, names }) {
338
502
  * @param {HTMLElement} option
339
503
  * @param {object} [opts]
340
504
  * @param {boolean} [opts.shouldScroll] Scroll option into view
505
+ * @param {ScrollBehavior} [opts.behaviour] How the scroll runs. Falls back to the CSS `scroll-behavior`.
341
506
  */
342
- function highlight(combobox, option, { shouldScroll = true } = {}) {
343
- highlightOption({ listbox: combobox.nodes.listbox, option, shouldScroll })
507
+ export function highlight(
508
+ combobox,
509
+ option,
510
+ { shouldScroll = true, behaviour } = {},
511
+ ) {
512
+ highlightOption({
513
+ listbox: combobox.nodes.listbox,
514
+ option,
515
+ shouldScroll,
516
+ behaviour,
517
+ })
344
518
  combobox.nodes.input.setAttribute('aria-activedescendant', option.id)
345
519
  }
346
520
 
@@ -351,18 +525,89 @@ function highlight(combobox, option, { shouldScroll = true } = {}) {
351
525
  * @param {Combobox} combobox
352
526
  * @param {HTMLElement} option
353
527
  */
354
- function commitSelection(combobox, option) {
528
+ export function commitSelection(combobox, option) {
355
529
  const { input, listbox } = combobox.nodes
356
- const { text } = option.dataset
530
+
531
+ if (!canSelectOption(combobox, option)) return
357
532
 
358
533
  selectOption({ listbox, option })
534
+
535
+ // A layer above owns the items, so it gets the element and maps it back.
536
+ combobox.options.onselect?.(option)
537
+
538
+ // A button shows its selection through Svelte, not through a value
539
+ if (input instanceof HTMLInputElement) {
540
+ // Selecting one of many leaves the text behind: the selection shows as a chip, and the next one is typed right after it.
541
+ const nextText = combobox.options.multiple
542
+ ? ''
543
+ : /** @type {string} */ (option.dataset.label)
544
+ writeInputText(combobox, nextText)
545
+ }
546
+
547
+ if (!combobox.options.multiple) closeCombobox(combobox)
548
+ }
549
+
550
+ /**
551
+ * canChangeSelection
552
+ * Reads whether the input is neither disabled nor readonly.
553
+ *
554
+ * Inline options stay clickable while the input can't change, so the options check this too.
555
+ *
556
+ * @param {Combobox} combobox
557
+ */
558
+ function canChangeSelection(combobox) {
559
+ const { input } = combobox.nodes
560
+ if (!input) return true
561
+ return !input.disabled && !input.hasAttribute('readonly')
562
+ }
563
+
564
+ /**
565
+ * writeInputText
566
+ * Writes the input's text, then dispatches `input` so `bind:value` and filtering see it.
567
+ *
568
+ * @param {Combobox} combobox
569
+ * @param {string} text
570
+ */
571
+ function writeInputText(combobox, text) {
572
+ const { input } = combobox.nodes
573
+ // Searching skips the text a selection wrote
359
574
  combobox.state.selectedText = text
360
575
  input.value = text
361
576
  input.dispatchEvent(new Event('input', { bubbles: true }))
362
- closeCombobox(combobox)
577
+ }
363
578
 
364
- // A layer above owns the items, so it gets the element and maps it back.
365
- combobox.options.onselect?.(option)
579
+ /**
580
+ * setInitialPhase
581
+ * Starts the combobox open when its options are inline, since those are always shown.
582
+ *
583
+ * @param {Combobox} combobox
584
+ */
585
+ function setInitialPhase(combobox) {
586
+ const { input, listbox, popover } = combobox.nodes
587
+ if (!input || !listbox) return
588
+
589
+ combobox.state.phase = popover ? 'closed' : 'open'
590
+ input.setAttribute('aria-expanded', String(!popover))
591
+ }
592
+
593
+ /**
594
+ * removeComboboxNodes
595
+ * Drops a destroyed part's nodes, and the entry once no part is left.
596
+ *
597
+ * @param {object} opts
598
+ * @param {Combobox} opts.combobox
599
+ * @param {string[]} opts.names Node names the part registered
600
+ */
601
+ function removeComboboxNodes({ combobox, names }) {
602
+ // Positioning points at the old nodes, so the next open rebuilds it
603
+ combobox.floating?.cleanup()
604
+ delete combobox.floating
605
+ combobox.resizeObserver?.disconnect()
606
+
607
+ for (const name of names) delete combobox.nodes[name]
608
+ if (combobox.nodes.input || combobox.nodes.listbox) return
609
+
610
+ comboboxes.splice(comboboxes.indexOf(combobox), 1)
366
611
  }
367
612
 
368
613
  /**
@@ -1,11 +1,15 @@
1
- import AutocompleteInput from './AutocompleteInput.svelte'
1
+ import Autocomplete from './Autocomplete.svelte'
2
2
  import AutocompleteOptions from './AutocompleteOptions.svelte'
3
+ import Select from './Select.svelte'
4
+ import SelectOptions from './SelectOptions.svelte'
3
5
  import TimepickerInput from './TimepickerInput.svelte'
4
6
  import TimepickerOptions from './TimepickerOptions.svelte'
5
7
 
6
8
  export {
7
- AutocompleteInput,
9
+ Autocomplete,
8
10
  AutocompleteOptions,
11
+ Select,
12
+ SelectOptions,
9
13
  TimepickerInput,
10
14
  TimepickerOptions,
11
15
  }