@stacksjs/components 0.2.369 → 0.2.371

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.
Files changed (62) hide show
  1. package/dist/{Checkbox-e7gn3w06.stx → Checkbox-tt8bze29.stx} +19 -3
  2. package/dist/Combobox-9xh1jgjr.stx +266 -0
  3. package/dist/{ComboboxButton-g76stp1e.stx → ComboboxButton-4r6a45s1.stx} +8 -1
  4. package/dist/{ComboboxInput-a5g0vn3e.stx → ComboboxInput-1gyfpnca.stx} +3 -0
  5. package/dist/{ComboboxOption-vnb67p8d.stx → ComboboxOption-wkw70js7.stx} +27 -1
  6. package/dist/{CommandPalette-y6t67rjj.stx → CommandPalette-vvaqtqat.stx} +2 -2
  7. package/dist/CommandPaletteItem-7290ce1z.stx +40 -0
  8. package/dist/Dropdown-25160tc6.stx +204 -0
  9. package/dist/{DropdownButton-6by2ybde.stx → DropdownButton-wxc25hsy.stx} +2 -0
  10. package/dist/{DropdownItem-wht1vcm5.stx → DropdownItem-af0vzc8a.stx} +15 -1
  11. package/dist/Listbox-32gzxace.stx +273 -0
  12. package/dist/{ListboxButton-3yc7tm8w.stx → ListboxButton-gan8e3nw.stx} +2 -0
  13. package/dist/{ListboxOption-9c9jpz1n.stx → ListboxOption-gpaqvk3s.stx} +14 -1
  14. package/dist/{Login-3dsk93vm.stx → Login-4666t7j4.stx} +18 -7
  15. package/dist/{NumberInput-awn66hfs.stx → NumberInput-g3jfy120.stx} +21 -4
  16. package/dist/{PasswordInput-hradj0xd.stx → PasswordInput-p2rt5926.stx} +21 -4
  17. package/dist/Popover-9m42pym0.stx +101 -0
  18. package/dist/{PopoverButton-htfypg00.stx → PopoverButton-3w6550hv.stx} +1 -0
  19. package/dist/{Radio-nr8rbb6g.stx → Radio-625byys2.stx} +19 -3
  20. package/dist/{RadioGroup-neej7522.stx → RadioGroup-smqcqgds.stx} +14 -1
  21. package/dist/{RadioGroupOption-c6xd0at9.stx → RadioGroupOption-twcw1b2a.stx} +13 -1
  22. package/dist/{Select-danh680d.stx → Select-1p9mcbsb.stx} +19 -3
  23. package/dist/{Signup-dh96kskd.stx → Signup-pm2r0f2m.stx} +21 -10
  24. package/dist/{SubscriptionCheckout-75x9mfv2.stx → SubscriptionCheckout-f1ev0ry8.stx} +27 -11
  25. package/dist/{TextInput-48ghmccm.stx → TextInput-t0a4ch49.stx} +19 -3
  26. package/dist/{Textarea-dndmk6ah.stx → Textarea-k1gf21kw.stx} +21 -4
  27. package/dist/{TwoFactorChallenge-ete7yk9y.stx → TwoFactorChallenge-st48qkzw.stx} +25 -5
  28. package/dist/index.js +7 -7
  29. package/package.json +3 -3
  30. package/src/components/Footer.stx +2 -2
  31. package/src/ui/auth/Login.stx +18 -7
  32. package/src/ui/auth/Signup.stx +21 -10
  33. package/src/ui/auth/TwoFactorChallenge.stx +25 -5
  34. package/src/ui/checkbox/Checkbox.stx +19 -3
  35. package/src/ui/combobox/Combobox.stx +174 -4
  36. package/src/ui/combobox/ComboboxButton.stx +8 -1
  37. package/src/ui/combobox/ComboboxInput.stx +3 -0
  38. package/src/ui/combobox/ComboboxOption.stx +27 -1
  39. package/src/ui/command-palette/CommandPalette.stx +2 -2
  40. package/src/ui/command-palette/CommandPaletteItem.stx +14 -1
  41. package/src/ui/dropdown/Dropdown.stx +122 -0
  42. package/src/ui/dropdown/DropdownButton.stx +2 -0
  43. package/src/ui/dropdown/DropdownItem.stx +15 -1
  44. package/src/ui/input/NumberInput.stx +21 -4
  45. package/src/ui/input/PasswordInput.stx +21 -4
  46. package/src/ui/input/TextInput.stx +19 -3
  47. package/src/ui/listbox/Listbox.stx +175 -3
  48. package/src/ui/listbox/ListboxButton.stx +2 -0
  49. package/src/ui/listbox/ListboxOption.stx +14 -1
  50. package/src/ui/payment/SubscriptionCheckout.stx +27 -11
  51. package/src/ui/popover/Popover.stx +43 -2
  52. package/src/ui/popover/PopoverButton.stx +1 -0
  53. package/src/ui/radio/Radio.stx +19 -3
  54. package/src/ui/radio-group/RadioGroup.stx +14 -1
  55. package/src/ui/radio-group/RadioGroupOption.stx +13 -1
  56. package/src/ui/select/Select.stx +19 -3
  57. package/src/ui/textarea/Textarea.stx +21 -4
  58. package/dist/Combobox-06x0nywb.stx +0 -96
  59. package/dist/CommandPaletteItem-6rp133ta.stx +0 -27
  60. package/dist/Dropdown-cmwge7vx.stx +0 -82
  61. package/dist/Listbox-e5jreb0a.stx +0 -101
  62. package/dist/Popover-3g8rgxt1.stx +0 -60
@@ -14,21 +14,41 @@ const isOpen = state(false)
14
14
  let rootEl = null
15
15
  let outsideHandler = null
16
16
 
17
+ /*
18
+ * The trigger carries the open state for assistive tech. `isOpen` already
19
+ * drove `data-state` on the root, which styles the panel but says nothing to a
20
+ * screen reader: the button announced itself as a plain button, with no
21
+ * indication that it opens anything or whether it is open right now.
22
+ */
23
+ function syncExpanded() {
24
+ if (!rootEl) return
25
+ const trigger = rootEl.querySelector('[data-stx-dropdown-button]')
26
+ if (!trigger) return
27
+ trigger.setAttribute('aria-expanded', isOpen() ? 'true' : 'false')
28
+ const panel = rootEl.querySelector('[data-stx-dropdown-items]')
29
+ if (!panel) return
30
+ if (!panel.id) panel.id = 'stx-dropdown-panel-' + dropdownInstanceId
31
+ trigger.setAttribute('aria-controls', panel.id)
32
+ }
33
+
17
34
  function toggle() {
18
35
  isOpen.set(!isOpen())
19
36
  emit('change', isOpen())
37
+ syncExpanded()
20
38
  }
21
39
 
22
40
  function open() {
23
41
  if (isOpen()) return
24
42
  isOpen.set(true)
25
43
  emit('change', true)
44
+ syncExpanded()
26
45
  }
27
46
 
28
47
  function close() {
29
48
  if (!isOpen()) return
30
49
  isOpen.set(false)
31
50
  emit('change', false)
51
+ syncExpanded()
32
52
  }
33
53
 
34
54
  function onItemSelect(event) {
@@ -41,17 +61,119 @@ function onToggle(event) { event.stopPropagation(); toggle() }
41
61
  function onOpen(event) { event.stopPropagation(); open() }
42
62
  function onClose(event) { event.stopPropagation(); close() }
43
63
 
64
+ /*
65
+ * Escape dismisses it, from anywhere rather than only from inside the panel.
66
+ *
67
+ * Opening one of these does not move focus, so a keydown bound on the panel
68
+ * never sees the first Escape - focus is still on whatever opened it. Drawer
69
+ * reached the same conclusion and binds on the document; this follows it, and
70
+ * only acts while open so one open popup does not swallow Escape for the page.
71
+ *
72
+ * Focus goes back to the trigger, but only if it had moved into the panel:
73
+ * otherwise this would steal it from wherever the user actually is.
74
+ */
75
+ function onDocumentKey(event) {
76
+ if (event.key !== 'Escape' || !isOpen()) return
77
+ close()
78
+ if (!rootEl) return
79
+ const active = rootEl.ownerDocument && rootEl.ownerDocument.activeElement
80
+ if (!active || !rootEl.contains(active)) return
81
+ const trigger = rootEl.querySelector('[data-stx-dropdown-button]')
82
+ if (trigger && trigger.focus) trigger.focus()
83
+ }
84
+
85
+ /*
86
+ * Roving focus over the menu items.
87
+ *
88
+ * `role="menuitem"` on a div is not focusable on its own, so the items carry
89
+ * tabindex="-1" and focus is moved programmatically -- the APG menu-button
90
+ * arrangement. Only the items are in the ring; a disabled one is skipped
91
+ * rather than focused and ignored, because landing on something inert reads as
92
+ * the menu being broken.
93
+ */
94
+ function menuItems() {
95
+ if (!rootEl) return []
96
+ const all = rootEl.querySelectorAll('[data-stx-dropdown-item]')
97
+ return Array.prototype.filter.call(all, item => item.getAttribute('aria-disabled') !== 'true')
98
+ }
99
+
100
+ function focusItemAt(index) {
101
+ const items = menuItems()
102
+ if (!items.length) return
103
+ const target = items[(index + items.length) % items.length]
104
+ if (target && target.focus) target.focus()
105
+ }
106
+
107
+ function focusedItemIndex() {
108
+ const doc = rootEl && rootEl.ownerDocument
109
+ return doc ? menuItems().indexOf(doc.activeElement) : -1
110
+ }
111
+
112
+ /*
113
+ * Keys are handled only while the event comes from inside this dropdown.
114
+ * Bound on the document so Escape works before focus has moved into the panel,
115
+ * which means an unguarded ArrowDown here would hijack scrolling for the whole
116
+ * page.
117
+ */
118
+ function onMenuKey(event) {
119
+ if (!rootEl || !rootEl.contains(event.target)) return
120
+ const key = event.key
121
+
122
+ if (!isOpen()) {
123
+ // ArrowDown opens and lands on the first item; ArrowUp on the last, which
124
+ // is how a menu button reached from below behaves.
125
+ if (key !== 'ArrowDown' && key !== 'ArrowUp') return
126
+ event.preventDefault()
127
+ open()
128
+ focusItemAt(key === 'ArrowDown' ? 0 : menuItems().length - 1)
129
+ return
130
+ }
131
+
132
+ if (key === 'ArrowDown' || key === 'ArrowUp') {
133
+ event.preventDefault()
134
+ const current = focusedItemIndex()
135
+ if (current === -1) focusItemAt(key === 'ArrowDown' ? 0 : menuItems().length - 1)
136
+ else focusItemAt(current + (key === 'ArrowDown' ? 1 : -1))
137
+ return
138
+ }
139
+
140
+ if (key === 'Home' || key === 'End') {
141
+ event.preventDefault()
142
+ focusItemAt(key === 'Home' ? 0 : menuItems().length - 1)
143
+ return
144
+ }
145
+
146
+ if (key === 'Enter' || key === ' ') {
147
+ // The item is a div, so Enter does not activate it the way it would a
148
+ // button. Clicking it runs the handler the item already has.
149
+ const current = focusedItemIndex()
150
+ if (current === -1) return
151
+ event.preventDefault()
152
+ menuItems()[current].click()
153
+ return
154
+ }
155
+
156
+ // Tabbing out of an open menu closes it, rather than leaving it hanging
157
+ // over the content the user has moved to.
158
+ if (key === 'Tab') close()
159
+ }
160
+
44
161
  onMount(() => {
45
162
  rootEl = document.querySelector(`[data-dropdown-id="${dropdownInstanceId}"]`)
163
+ syncExpanded()
46
164
  outsideHandler = (event) => {
47
165
  if (!isOpen()) return
48
166
  if (rootEl && !rootEl.contains(event.target)) close()
49
167
  }
50
168
  document.addEventListener('click', outsideHandler, true)
169
+ document.addEventListener('keydown', onDocumentKey)
170
+ document.addEventListener('keydown', onMenuKey)
51
171
  })
52
172
 
53
173
  onDestroy(() => {
54
174
  if (outsideHandler) document.removeEventListener('click', outsideHandler, true)
175
+ document.removeEventListener('keydown', onDocumentKey)
176
+ document.removeEventListener('keydown', onMenuKey)
55
177
  })
56
178
 
57
179
  const dataState = derived(() => isOpen() ? 'open' : 'closed')
@@ -22,6 +22,8 @@ function onClick(event) {
22
22
  :is="{{ as }}"
23
23
  class="{{ buttonClasses }}"
24
24
  data-stx-dropdown-button
25
+ aria-haspopup="menu"
26
+ aria-expanded="false"
25
27
  @if(disabled)disabled aria-disabled="true"@endif
26
28
  @click="onClick($event)"
27
29
  >
@@ -3,6 +3,7 @@ export const className = $props.className || ''
3
3
  export const as = $props.as || 'div'
4
4
  export const disabled = $bool($props.disabled)
5
5
  export const value = $props.value
6
+ export const valueJson = JSON.stringify(value === undefined ? null : value)
6
7
 
7
8
  const baseClasses = 'group flex w-full items-center px-2 py-2 text-sm transition-colors text-fg hover:bg-accent-solid hover:text-accent-ink'
8
9
  const disabledClasses = disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'
@@ -12,7 +13,19 @@ export const itemClasses = `${baseClasses} ${disabledClasses} ${className}`.trim
12
13
  <script client>
13
14
  const emit = defineEmits()
14
15
  const isDisabled = {{ disabled }}
15
- const itemValue = {{ value === undefined ? 'null' : value }}
16
+ /*
17
+ * JSON built on the server and emitted raw, rather than a 'null' sentinel
18
+ * through an ordinary interpolation.
19
+ *
20
+ * A `value === undefined ? 'null' : value` ternary was meant to put the bare
21
+ * token null into the script. An interpolation QUOTES a string, so what it
22
+ * emitted was the four-character string "null" -- truthy, in the one place a
23
+ * value is meant to be absent. JSON.stringify produces the correct literal for
24
+ * every type, null included, and raw interpolation passes it through unquoted.
25
+ * Calendar and DateRangePicker already avoid this sentinel and say why
26
+ * (stacksjs/stx#1981).
27
+ */
28
+ const itemValue = {!! valueJson !!}
16
29
 
17
30
  function onClick(event) {
18
31
  if (isDisabled) return
@@ -28,6 +41,7 @@ function onClick(event) {
28
41
  class="{{ itemClasses }}"
29
42
  data-stx-dropdown-item
30
43
  role="menuitem"
44
+ tabindex="-1"
31
45
  @if(disabled)aria-disabled="true"@endif
32
46
  @click="onClick($event)"
33
47
  >
@@ -6,6 +6,23 @@ export const readonly = $bool($props.readonly)
6
6
  export const size = $props.size || 'md'
7
7
  export const error = $bool($props.error)
8
8
  export const label = $props.label || ''
9
+ /*
10
+ * Ids unique to this instance.
11
+ *
12
+ * These were derived from the LABEL or hardcoded outright, so two of these on
13
+ * one page -- an ordinary form -- emitted the same id twice. `<label for>`
14
+ * then activated the FIRST field from every label, and `aria-describedby`
15
+ * pointed every field's description at the first one's helper text. A label
16
+ * containing a space also produced an invalid id, `input-First name`, which
17
+ * getElementById and querySelector cannot address at all.
18
+ *
19
+ * `$uid` is unique per instance and stable across renders, which is what an id
20
+ * has to be (utils.ts explains why a render that changes its own bytes is
21
+ * uncacheable). The `id` prop overrides it, for a caller that needs to point
22
+ * its own `for` or `aria-describedby` at this control.
23
+ */
24
+ export const inputId = $props.id || `number-input-${$uid}`
25
+ export const helperId = `${inputId}-helper`
9
26
  export const helperText = $props.helperText || ''
10
27
  export const required = $bool($props.required)
11
28
  export const min = $props.min
@@ -76,7 +93,7 @@ defineExpose({ value: inputValue, increment, decrement })
76
93
 
77
94
  <div class="w-full {{ className }}">
78
95
  @if(label)
79
- <label for="number-input" class="{{ labelClasses }}">
96
+ <label for="{{ inputId }}" class="{{ labelClasses }}">
80
97
  {{ label }}
81
98
  @if(required)
82
99
  <span class="text-danger ml-1">*</span>
@@ -87,7 +104,7 @@ defineExpose({ value: inputValue, increment, decrement })
87
104
  <div class="relative">
88
105
  <input
89
106
  type="number"
90
- id="number-input"
107
+ id="{{ inputId }}"
91
108
  class="{{ inputClasses }}"
92
109
  :value="inputValue()"
93
110
  placeholder="{{ placeholder }}"
@@ -99,7 +116,7 @@ defineExpose({ value: inputValue, increment, decrement })
99
116
  step="{{ step }}"
100
117
  @input="onInput($event)"
101
118
  :aria-invalid="{{ error ? 'true' : 'false' }}"
102
- @if(helperText)aria-describedby="helper-text"@endif
119
+ @if(helperText)aria-describedby="{{ helperId }}"@endif
103
120
  />
104
121
 
105
122
  @if(showControls && !disabled && !readonly)
@@ -129,7 +146,7 @@ defineExpose({ value: inputValue, increment, decrement })
129
146
  </div>
130
147
 
131
148
  @if(helperText)
132
- <p id="helper-text" class="{{ helperClasses }}">
149
+ <p id="{{ helperId }}" class="{{ helperClasses }}">
133
150
  {{ helperText }}
134
151
  </p>
135
152
  @endif
@@ -6,6 +6,23 @@ export const readonly = $bool($props.readonly)
6
6
  export const size = $props.size || 'md'
7
7
  export const error = $bool($props.error)
8
8
  export const label = $props.label || ''
9
+ /*
10
+ * Ids unique to this instance.
11
+ *
12
+ * These were derived from the LABEL or hardcoded outright, so two of these on
13
+ * one page -- an ordinary form -- emitted the same id twice. `<label for>`
14
+ * then activated the FIRST field from every label, and `aria-describedby`
15
+ * pointed every field's description at the first one's helper text. A label
16
+ * containing a space also produced an invalid id, `input-First name`, which
17
+ * getElementById and querySelector cannot address at all.
18
+ *
19
+ * `$uid` is unique per instance and stable across renders, which is what an id
20
+ * has to be (utils.ts explains why a render that changes its own bytes is
21
+ * uncacheable). The `id` prop overrides it, for a caller that needs to point
22
+ * its own `for` or `aria-describedby` at this control.
23
+ */
24
+ export const inputId = $props.id || `password-input-${$uid}`
25
+ export const helperId = `${inputId}-helper`
9
26
  export const helperText = $props.helperText || ''
10
27
  export const required = $bool($props.required)
11
28
  export const showStrength = $bool($props.showStrength)
@@ -88,7 +105,7 @@ defineExpose({ value: inputValue })
88
105
 
89
106
  <div class="w-full {{ className }}">
90
107
  @if(label)
91
- <label for="password-input" class="{{ labelClasses }}">
108
+ <label for="{{ inputId }}" class="{{ labelClasses }}">
92
109
  {{ label }}
93
110
  @if(required)
94
111
  <span class="text-danger ml-1">*</span>
@@ -99,7 +116,7 @@ defineExpose({ value: inputValue })
99
116
  <div class="relative">
100
117
  <input
101
118
  :type="inputType()"
102
- id="password-input"
119
+ id="{{ inputId }}"
103
120
  class="{{ inputClasses }}"
104
121
  :value="inputValue()"
105
122
  placeholder="{{ placeholder }}"
@@ -108,7 +125,7 @@ defineExpose({ value: inputValue })
108
125
  @if(required)required@endif
109
126
  @input="onInput($event)"
110
127
  :aria-invalid="{{ error ? 'true' : 'false' }}"
111
- @if(helperText)aria-describedby="helper-text"@endif
128
+ @if(helperText)aria-describedby="{{ helperId }}"@endif
112
129
  />
113
130
 
114
131
  <div class="absolute inset-y-0 right-0 flex items-center pr-3">
@@ -146,7 +163,7 @@ defineExpose({ value: inputValue })
146
163
  @endif
147
164
 
148
165
  @if(helperText)
149
- <p id="helper-text" class="{{ helperClasses }}">
166
+ <p id="{{ helperId }}" class="{{ helperClasses }}">
150
167
  {{ helperText }}
151
168
  </p>
152
169
  @endif
@@ -44,7 +44,23 @@ export const inputClasses = `${baseClasses} ${sizeClasses[size] || sizeClasses.m
44
44
  export const labelClasses = `block text-sm font-medium leading-6 mb-2 ${error ? 'text-danger' : 'text-fg'}`.trim()
45
45
  export const helperClasses = `mt-2 text-sm ${error ? 'text-danger' : 'text-fg-soft'}`.trim()
46
46
  export const iconClasses = iconSizeClasses[size] || iconSizeClasses.md
47
- export const inputId = `input-${label}`
47
+ /*
48
+ * Ids unique to this instance.
49
+ *
50
+ * These were derived from the LABEL or hardcoded outright, so two of these on
51
+ * one page -- an ordinary form -- emitted the same id twice. `<label for>`
52
+ * then activated the FIRST field from every label, and `aria-describedby`
53
+ * pointed every field's description at the first one's helper text. A label
54
+ * containing a space also produced an invalid id, `input-First name`, which
55
+ * getElementById and querySelector cannot address at all.
56
+ *
57
+ * `$uid` is unique per instance and stable across renders, which is what an id
58
+ * has to be (utils.ts explains why a render that changes its own bytes is
59
+ * uncacheable). The `id` prop overrides it, for a caller that needs to point
60
+ * its own `for` or `aria-describedby` at this control.
61
+ */
62
+ export const inputId = $props.id || `input-${$uid}`
63
+ export const helperId = `${inputId}-helper`
48
64
  </script>
49
65
 
50
66
  <script client>
@@ -104,7 +120,7 @@ defineExpose({ value: inputValue, clear: onClear })
104
120
  @input="onInput($event)"
105
121
  @change="onChange($event)"
106
122
  :aria-invalid="{{ error ? 'true' : 'false' }}"
107
- @if(helperText)aria-describedby="helper-text"@endif
123
+ @if(helperText)aria-describedby="{{ helperId }}"@endif
108
124
  />
109
125
 
110
126
  @if(clearable)
@@ -131,7 +147,7 @@ defineExpose({ value: inputValue, clear: onClear })
131
147
  @if(helperText || (showCount && maxLength))
132
148
  <div class="flex items-center justify-between mt-2">
133
149
  @if(helperText)
134
- <p id="helper-text" class="{{ helperClasses }}">
150
+ <p id="{{ helperId }}" class="{{ helperClasses }}">
135
151
  {{ helperText }}
136
152
  </p>
137
153
  @else
@@ -1,5 +1,6 @@
1
1
  <script server>
2
2
  export const value = $props.value
3
+ export const valueJson = JSON.stringify(value === undefined ? null : value)
3
4
  export const multiple = $bool($props.multiple)
4
5
  export const className = $props.className || ''
5
6
  export const as = $props.as || 'div'
@@ -13,7 +14,19 @@ export const listboxInstanceId = $uid
13
14
  const emit = defineEmits()
14
15
  const listboxInstanceId = {{ listboxInstanceId }}
15
16
  const multiple = {{ multiple }}
16
- const initialValue = {{ value === undefined ? 'null' : value }}
17
+ /*
18
+ * JSON built on the server and emitted raw, rather than a 'null' sentinel
19
+ * through an ordinary interpolation.
20
+ *
21
+ * A `value === undefined ? 'null' : value` ternary was meant to put the bare
22
+ * token null into the script. An interpolation QUOTES a string, so what it
23
+ * emitted was the four-character string "null" -- truthy, in the one place a
24
+ * value is meant to be absent. JSON.stringify produces the correct literal for
25
+ * every type, null included, and raw interpolation passes it through unquoted.
26
+ * Calendar and DateRangePicker already avoid this sentinel and say why
27
+ * (stacksjs/stx#1981).
28
+ */
29
+ const initialValue = {!! valueJson !!}
17
30
 
18
31
  const isOpen = state(false)
19
32
  const selected = state(initialValue)
@@ -36,6 +49,9 @@ function selectValue(v) {
36
49
  isOpen.set(false)
37
50
  }
38
51
  syncOptionStates()
52
+ // The single-select branch above closes the panel without going through
53
+ // close(), so the trigger's state has to be refreshed here too.
54
+ syncExpanded()
39
55
  emit('change', selected())
40
56
  }
41
57
 
@@ -53,8 +69,25 @@ function syncOptionStates() {
53
69
  }
54
70
  }
55
71
 
56
- function open() { if (!isOpen()) { isOpen.set(true); emit('change', selected()) } }
57
- function close() { if (isOpen()) { isOpen.set(false) } }
72
+ /*
73
+ * The trigger carries the open state for assistive tech. `isOpen` already
74
+ * drove `data-state` on the root, which styles the panel but says nothing to a
75
+ * screen reader: the button announced itself as a plain button, with no
76
+ * indication that it opens anything or whether it is open right now.
77
+ */
78
+ function syncExpanded() {
79
+ if (!rootEl) return
80
+ const trigger = rootEl.querySelector('[data-stx-listbox-button]')
81
+ if (!trigger) return
82
+ trigger.setAttribute('aria-expanded', isOpen() ? 'true' : 'false')
83
+ const panel = rootEl.querySelector('[data-stx-listbox-options]')
84
+ if (!panel) return
85
+ if (!panel.id) panel.id = 'stx-listbox-panel-' + listboxInstanceId
86
+ trigger.setAttribute('aria-controls', panel.id)
87
+ }
88
+
89
+ function open() { if (!isOpen()) { isOpen.set(true); emit('change', selected()); syncExpanded() } }
90
+ function close() { if (isOpen()) { isOpen.set(false); syncExpanded() } }
58
91
  function toggle() { isOpen() ? close() : open() }
59
92
 
60
93
  function onToggle(event) { event.stopPropagation(); toggle() }
@@ -63,18 +96,157 @@ function onSelect(event) {
63
96
  selectValue(event.detail)
64
97
  }
65
98
 
99
+ /*
100
+ * Escape dismisses it, from anywhere rather than only from inside the panel.
101
+ *
102
+ * Opening one of these does not move focus, so a keydown bound on the panel
103
+ * never sees the first Escape - focus is still on whatever opened it. Drawer
104
+ * reached the same conclusion and binds on the document; this follows it, and
105
+ * only acts while open so one open popup does not swallow Escape for the page.
106
+ *
107
+ * Focus goes back to the trigger, but only if it had moved into the panel:
108
+ * otherwise this would steal it from wherever the user actually is.
109
+ */
110
+ function onDocumentKey(event) {
111
+ if (event.key !== 'Escape' || !isOpen()) return
112
+ close()
113
+ if (!rootEl) return
114
+ const active = rootEl.ownerDocument && rootEl.ownerDocument.activeElement
115
+ if (!active || !rootEl.contains(active)) return
116
+ const trigger = rootEl.querySelector('[data-stx-listbox-button]')
117
+ if (trigger && trigger.focus) trigger.focus()
118
+ }
119
+
120
+ /*
121
+ * Roving focus over the options.
122
+ *
123
+ * `role="option"` on an li is not focusable on its own, so the options carry
124
+ * tabindex="-1" and focus moves programmatically -- the same arrangement
125
+ * <Dropdown> uses for its menu items. APG allows either this or
126
+ * aria-activedescendant for a listbox; <Combobox> is the case that REQUIRES
127
+ * the latter, because focus has to stay in its input.
128
+ *
129
+ * Arrows move focus and do not change the selection. Selection following focus
130
+ * is a documented variant, and the quieter of the two: arrowing past an option
131
+ * should not commit a value the user was only passing over.
132
+ */
133
+ function optionElements() {
134
+ if (!rootEl) return []
135
+ const all = rootEl.querySelectorAll('[data-stx-listbox-option]')
136
+ return Array.prototype.filter.call(all, option => option.getAttribute('aria-disabled') !== 'true')
137
+ }
138
+
139
+ function focusOptionAt(index) {
140
+ const options = optionElements()
141
+ if (!options.length) return
142
+ const target = options[(index + options.length) % options.length]
143
+ if (target && target.focus) target.focus()
144
+ }
145
+
146
+ function focusedOptionIndex() {
147
+ const doc = rootEl && rootEl.ownerDocument
148
+ return doc ? optionElements().indexOf(doc.activeElement) : -1
149
+ }
150
+
151
+ /** Opening lands on what is already chosen, so the current value is in view. */
152
+ function focusSelectedOrFirst(fallbackToLast) {
153
+ const options = optionElements()
154
+ const chosen = options.findIndex(option => option.getAttribute('aria-selected') === 'true')
155
+ if (chosen !== -1) focusOptionAt(chosen)
156
+ else focusOptionAt(fallbackToLast ? options.length - 1 : 0)
157
+ }
158
+
159
+ /*
160
+ * Type-ahead: a printable character jumps to the next option whose label
161
+ * starts with it, wrapping, so a long list is reachable without arrowing
162
+ * through all of it.
163
+ */
164
+ function focusByTypeAhead(character) {
165
+ const options = optionElements()
166
+ if (!options.length) return false
167
+ const wanted = character.toLowerCase()
168
+ const from = focusedOptionIndex()
169
+ for (let step = 1; step <= options.length; step++) {
170
+ const candidate = options[(from + step + options.length) % options.length]
171
+ const label = (candidate.textContent || '').trim().toLowerCase()
172
+ if (label.startsWith(wanted)) {
173
+ if (candidate.focus) candidate.focus()
174
+ return true
175
+ }
176
+ }
177
+ return false
178
+ }
179
+
180
+ /*
181
+ * Gated on the event coming from inside this listbox. The handler is on the
182
+ * document so Escape works before focus has moved into the panel, which would
183
+ * otherwise make ArrowDown a page-wide scroll hijack.
184
+ */
185
+ function onListboxKey(event) {
186
+ if (!rootEl || !rootEl.contains(event.target)) return
187
+ const key = event.key
188
+
189
+ if (!isOpen()) {
190
+ if (key !== 'ArrowDown' && key !== 'ArrowUp') return
191
+ event.preventDefault()
192
+ open()
193
+ focusSelectedOrFirst(key === 'ArrowUp')
194
+ return
195
+ }
196
+
197
+ if (key === 'ArrowDown' || key === 'ArrowUp') {
198
+ event.preventDefault()
199
+ const current = focusedOptionIndex()
200
+ if (current === -1) focusSelectedOrFirst(key === 'ArrowUp')
201
+ else focusOptionAt(current + (key === 'ArrowDown' ? 1 : -1))
202
+ return
203
+ }
204
+
205
+ if (key === 'Home' || key === 'End') {
206
+ event.preventDefault()
207
+ focusOptionAt(key === 'Home' ? 0 : optionElements().length - 1)
208
+ return
209
+ }
210
+
211
+ if (key === 'Enter' || key === ' ') {
212
+ // An li does not activate on Enter, so the option is clicked and runs the
213
+ // handler it already has.
214
+ const current = focusedOptionIndex()
215
+ if (current === -1) return
216
+ event.preventDefault()
217
+ optionElements()[current].click()
218
+ return
219
+ }
220
+
221
+ if (key === 'Tab') {
222
+ close()
223
+ return
224
+ }
225
+
226
+ // A single printable character, so modifier combinations still reach the
227
+ // browser.
228
+ if (key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {
229
+ if (focusByTypeAhead(key)) event.preventDefault()
230
+ }
231
+ }
232
+
66
233
  onMount(() => {
67
234
  rootEl = document.querySelector(`[data-listbox-id="${listboxInstanceId}"]`)
235
+ syncExpanded()
68
236
  syncOptionStates()
69
237
  outsideHandler = (event) => {
70
238
  if (!isOpen()) return
71
239
  if (rootEl && !rootEl.contains(event.target)) close()
72
240
  }
73
241
  document.addEventListener('click', outsideHandler, true)
242
+ document.addEventListener('keydown', onDocumentKey)
243
+ document.addEventListener('keydown', onListboxKey)
74
244
  })
75
245
 
76
246
  onDestroy(() => {
77
247
  if (outsideHandler) document.removeEventListener('click', outsideHandler, true)
248
+ document.removeEventListener('keydown', onDocumentKey)
249
+ document.removeEventListener('keydown', onListboxKey)
78
250
  })
79
251
 
80
252
  const dataState = derived(() => isOpen() ? 'open' : 'closed')
@@ -21,6 +21,8 @@ function onClick(event) {
21
21
  :is="{{ as }}"
22
22
  class="{{ buttonClasses }}"
23
23
  data-stx-listbox-button
24
+ aria-haspopup="listbox"
25
+ aria-expanded="false"
24
26
  @if(disabled)disabled aria-disabled="true"@endif
25
27
  @click="onClick($event)"
26
28
  >
@@ -12,7 +12,19 @@ export const valueJson = JSON.stringify(value === undefined ? null : value)
12
12
 
13
13
  <script client>
14
14
  const isDisabled = {{ disabled }}
15
- const optionValue = {{ value === undefined ? 'null' : value }}
15
+ /*
16
+ * JSON built on the server and emitted raw, rather than a 'null' sentinel
17
+ * through an ordinary interpolation.
18
+ *
19
+ * A `value === undefined ? 'null' : value` ternary was meant to put the bare
20
+ * token null into the script. An interpolation QUOTES a string, so what it
21
+ * emitted was the four-character string "null" -- truthy, in the one place a
22
+ * value is meant to be absent. JSON.stringify produces the correct literal for
23
+ * every type, null included, and raw interpolation passes it through unquoted.
24
+ * Calendar and DateRangePicker already avoid this sentinel and say why
25
+ * (stacksjs/stx#1981).
26
+ */
27
+ const optionValue = {!! valueJson !!}
16
28
 
17
29
  function onClick(event) {
18
30
  if (isDisabled) return
@@ -28,6 +40,7 @@ function onClick(event) {
28
40
  data-stx-listbox-option
29
41
  data-option-value="{{ valueJson }}"
30
42
  role="option"
43
+ tabindex="-1"
31
44
  aria-selected="false"
32
45
  @if(disabled)aria-disabled="true"@endif
33
46
  @click="onClick($event)"