@zooui/nuxt 0.2.0 → 0.3.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.
@@ -3,7 +3,7 @@
3
3
  // rows' fields are the caller's, in the #row slot, so it holds any input; this owns adding, removing, folding,
4
4
  // per-row errors, focus and announcing the count. Written on Nuxt UI's tokens.
5
5
  //
6
- // <ZRepeatingList v-model="rows" item-label="referral source" :new-row="() => ({ name: '' })" :row-key="(r) => r.id">
6
+ // <ZRepeatingList v-model="rows" item-label="contact" :new-row="() => ({ name: '' })" :row-key="(r) => r.id">
7
7
  // <template #row="{ row, index, error, errorId }"> …inputs bound to row… </template>
8
8
  // <template #summary="{ row }">{{ row.name }}</template> <!-- optional: fold rows to one line -->
9
9
  // </ZRepeatingList>
@@ -12,9 +12,14 @@
12
12
  // line with an Edit button (new rows, and any row with an error, are open); without one every row is open.
13
13
  // `rowKey` keeps a row's identity while it is renamed (rows that carry history); rows it has no key for are told
14
14
  // apart by object identity, hence `T extends object`.
15
+ //
16
+ // With #summary, an open row has Done (fold it, keeping the edits) and Cancel (put back what it held when it opened,
17
+ // then fold it; Escape does the same); Cancel on a row added here and never Done removes it.
18
+ import { restore, snapshot } from './row-snapshot'
19
+
15
20
  const props = withDefaults(
16
21
  defineProps<{
17
- /** One row, singular and lower case: "referral source". */
22
+ /** One row, singular and lower case: "contact". */
18
23
  itemLabel: string
19
24
  /** A new row's starting values. */
20
25
  newRow: () => T
@@ -28,7 +33,7 @@ const props = withDefaults(
28
33
  errors?: Record<string, string>
29
34
  /** Whether a row may be removed (default: every row, down to `min`). */
30
35
  removable?: (row: T) => boolean
31
- /** The row's heading, and the name its buttons carry; "Referral source 2" unless given. Hidden in `compact`. */
36
+ /** The row's heading, and the name its buttons carry; "Contact 2" unless given. Hidden in `compact`. */
32
37
  rowTitle?: (row: T, index: number) => string
33
38
  /** One line per row, no heading or card: for rows of a single short field. */
34
39
  compact?: boolean
@@ -38,6 +43,10 @@ const props = withDefaults(
38
43
  removeLabel?: string
39
44
  /** The folded row's Edit button's word; named the same way. */
40
45
  editLabel?: string
46
+ /** With #summary, the open row's Done button's word (fold it, keeping the edits); named the same way. */
47
+ doneLabel?: string
48
+ /** With #summary, the open row's Cancel button's word (undo the edits and fold it); named the same way. */
49
+ cancelLabel?: string
41
50
  /** Shown beside the disabled Add button at `max`; "That's the most you can add here (12)." unless given. */
42
51
  maxLabel?: string
43
52
  /** What a screen reader hears when a row is added or removed; "Part 3 added. 3 in the list." unless given. */
@@ -56,6 +65,8 @@ const props = withDefaults(
56
65
  addLabel: undefined,
57
66
  removeLabel: 'Remove',
58
67
  editLabel: 'Edit',
68
+ doneLabel: 'Done',
69
+ cancelLabel: 'Cancel',
59
70
  maxLabel: undefined,
60
71
  announce: undefined,
61
72
  focusSelector: 'input, select, textarea, button[role="radio"]',
@@ -74,8 +85,11 @@ let counter = 0
74
85
  function keyOf(row: T): string {
75
86
  const k = props.rowKey?.(row)
76
87
  if (k) return k
77
- let id = ids.get(row)
78
- if (!id) ids.set(row, (id = `${uid}:new-${++counter}`))
88
+ // By the object a reactive proxy wraps: a new row is seen both as the object newRow() made and as the parent ref's
89
+ // proxy of it.
90
+ const raw = toRaw(row)
91
+ let id = ids.get(raw)
92
+ if (!id) ids.set(raw, (id = `${uid}:new-${++counter}`))
79
93
  return id
80
94
  }
81
95
 
@@ -104,7 +118,12 @@ watch(
104
118
  if (!errs) return
105
119
  const next = new Set(folded.value)
106
120
  let changed = false
107
- for (const k of Object.keys(errs)) if (errs[k] && next.delete(k)) changed = true
121
+ for (const k of Object.keys(errs)) {
122
+ if (!errs[k] || !next.delete(k)) continue
123
+ changed = true
124
+ const row = rows.value.find((r) => keyOf(r) === k)
125
+ if (row) opened(row)
126
+ }
108
127
  if (changed) folded.value = next
109
128
  },
110
129
  { deep: true },
@@ -130,32 +149,33 @@ function say(type: 'added' | 'removed', title: string, count: number) {
130
149
  }
131
150
  onBeforeUnmount(() => clearTimeout(announceTimer))
132
151
 
133
- // The row to put focus in once it is drawn. With v-model the new row only arrives back through the parent, so this
134
- // waits for a render that has it rather than a fixed tick.
135
- const focusAt = ref<number | null>(null)
136
- const firstInput = (i: number) => {
137
- const row = root.value?.querySelector<HTMLElement>(`:scope > [data-row="${i}"]`)
138
- return row?.querySelector<HTMLElement>(props.focusSelector) ?? null
139
- }
152
+ // The row to put focus in once it is drawn: the first match for `selector` in it (a folded row's Edit), else its first
153
+ // field. With v-model the new row only arrives back through the parent, so this waits for a render that has it rather
154
+ // than a fixed tick.
155
+ const focusAt = shallowRef<{ index: number; selector?: string } | null>(null)
156
+ const rowEl = (i: number) => root.value?.querySelector<HTMLElement>(`:scope > [data-row="${i}"]`) ?? null
140
157
  watch(
141
158
  [focusAt, () => rows.value.length, folded],
142
159
  () => {
143
- if (focusAt.value === null) return
144
- const el = firstInput(focusAt.value)
160
+ const at = focusAt.value
161
+ if (at === null) return
162
+ const row = rowEl(at.index)
163
+ const el = (at.selector && row?.querySelector<HTMLElement>(at.selector)) || row?.querySelector<HTMLElement>(props.focusSelector)
145
164
  if (!el) return
146
165
  el.focus()
147
166
  focusAt.value = null
148
167
  },
149
168
  { flush: 'post' },
150
169
  )
151
- function focusRow(i: number) {
152
- focusAt.value = i
170
+ function focusRow(i: number, selector?: string) {
171
+ focusAt.value = { index: i, selector }
153
172
  }
154
173
 
155
174
  function add() {
156
175
  if (atMax.value) return
157
176
  const i = rows.value.length
158
177
  const row = props.newRow()
178
+ fresh.add(keyOf(row))
159
179
  rows.value = [...rows.value, row]
160
180
  focusRow(i)
161
181
  say('added', titleOf(row, i), i + 1)
@@ -163,6 +183,9 @@ function add() {
163
183
 
164
184
  function remove(i: number) {
165
185
  const title = titleOf(rows.value[i]!, i)
186
+ const k = keyOf(rows.value[i]!)
187
+ snapshots.delete(k)
188
+ fresh.delete(k)
166
189
  const next = rows.value.filter((_, j) => j !== i)
167
190
  rows.value = next
168
191
  // Counted from `next`: with v-model, rows.value is the old array until the parent hands the new one back.
@@ -175,19 +198,76 @@ function edit(row: T, i: number) {
175
198
  const next = new Set(folded.value)
176
199
  next.delete(keyOf(row))
177
200
  folded.value = next
201
+ opened(row)
178
202
  focusRow(i)
179
203
  }
180
204
 
205
+ // Done and Cancel, on an open row of a list with #summary. A row is copied when it opens (Edit, or an error opening
206
+ // it), and Cancel puts the copy back into the same object, so it keeps its identity and key. A row added here and not
207
+ // yet Done has nothing to go back to: Cancel removes it, where Remove could (not at `min`). Done or Cancel on a row with
208
+ // an error leaves it open (Cancel having put its values back), the error showing, with focus in its first field.
209
+ const snapshots = shallowReactive(new Map<string, T>())
210
+ const fresh = shallowReactive(new Set<string>())
211
+ const closable = computed(() => !!slots.summary)
212
+ const canCancel = (row: T) => {
213
+ const k = keyOf(row)
214
+ return snapshots.has(k) || (fresh.has(k) && canRemove(row))
215
+ }
216
+ function opened(row: T) {
217
+ const k = keyOf(row)
218
+ if (!fresh.has(k)) snapshots.set(k, snapshot(row))
219
+ }
220
+ function fold(row: T, i: number) {
221
+ const next = new Set(folded.value)
222
+ next.add(keyOf(row))
223
+ folded.value = next
224
+ focusRow(i, '[data-edit]')
225
+ }
226
+ function done(row: T, i: number) {
227
+ if (errorOf(row)) return focusRow(i)
228
+ const k = keyOf(row)
229
+ snapshots.delete(k)
230
+ fresh.delete(k)
231
+ fold(row, i)
232
+ }
233
+ function cancel(row: T, i: number) {
234
+ const k = keyOf(row)
235
+ const snap = snapshots.get(k)
236
+ if (snap) {
237
+ restore(row, snap)
238
+ // Still in error: open, as Done leaves it, so it cannot fold under the user once the error clears.
239
+ if (errorOf(row)) return focusRow(i)
240
+ snapshots.delete(k)
241
+ fold(row, i)
242
+ } else if (fresh.has(k) && canRemove(row)) {
243
+ remove(i)
244
+ }
245
+ }
246
+
247
+ // Escape anywhere in an open row is Cancel. A field with its own popup open keeps it, and a field that handled it (a
248
+ // menu closing) or a row of a list nested in this one has already taken it (defaultPrevented).
249
+ function onRowKeydown(e: KeyboardEvent, row: T, i: number) {
250
+ if (e.key !== 'Escape' || e.defaultPrevented) return
251
+ if (!closable.value || isFolded(row) || !canCancel(row) || (e.target as HTMLElement).closest('[aria-expanded="true"]')) return
252
+ e.preventDefault()
253
+ cancel(row, i)
254
+ }
255
+
181
256
  /** Back up to `min` rows, whenever there are fewer (on mount, the list was emptied from outside, or `min` rose). */
182
257
  function fillToMin() {
183
258
  if (rows.value.length < props.min) {
184
- rows.value = [...rows.value, ...Array.from({ length: props.min - rows.value.length }, () => props.newRow())]
259
+ const added = Array.from({ length: props.min - rows.value.length }, () => props.newRow())
260
+ for (const row of added) fresh.add(keyOf(row))
261
+ rows.value = [...rows.value, ...added]
185
262
  }
186
263
  }
187
264
  watch([() => rows.value.length, () => props.min], fillToMin)
188
265
 
189
266
  onMounted(() => {
190
- if (slots.summary) folded.value = new Set(rows.value.filter((row) => !errorOf(row)).map(keyOf))
267
+ if (slots.summary) {
268
+ folded.value = new Set(rows.value.filter((row) => !errorOf(row)).map(keyOf))
269
+ for (const row of rows.value) if (errorOf(row)) opened(row)
270
+ }
191
271
  fillToMin()
192
272
  })
193
273
  </script>
@@ -204,7 +284,7 @@ onMounted(() => {
204
284
  >
205
285
  <UIcon name="i-lucide-circle-check" class="size-4 shrink-0 text-success" aria-hidden="true" />
206
286
  <span class="min-w-0 flex-1 truncate text-sm text-toned"><slot name="summary" :row="row" :index="i" /></span>
207
- <UButton type="button" size="xs" variant="ghost" color="neutral" icon="i-lucide-pencil" :aria-label="`${editLabel} ${titleOf(row, i)}`" @click="edit(row, i)">
287
+ <UButton type="button" size="xs" variant="ghost" color="neutral" icon="i-lucide-pencil" :aria-label="`${editLabel} ${titleOf(row, i)}`" data-edit @click="edit(row, i)">
208
288
  {{ editLabel }}
209
289
  </UButton>
210
290
  <UButton
@@ -223,14 +303,19 @@ onMounted(() => {
223
303
  v-else
224
304
  :data-row="i"
225
305
  :class="compact ? 'flex items-start gap-2' : 'rounded-md border border-default p-3 sm:p-4'"
306
+ @keydown="onRowKeydown($event, row, i)"
226
307
  >
227
308
  <legend :class="compact ? 'sr-only' : 'px-1 text-sm font-semibold text-highlighted'">{{ titleOf(row, i) }}</legend>
228
309
  <div :class="compact ? 'min-w-0 flex-1' : 'space-y-4'">
229
310
  <slot name="row" :row="row" :index="i" :key="keyOf(row)" :error="errorOf(row)" :errorId="errorIdOf(row)" />
230
311
  <p v-if="errorOf(row)" :id="errorIdOf(row)" role="alert" class="mt-1 text-sm text-(--ui-color-error-700) dark:text-(--ui-color-error-300)">{{ errorOf(row) }}</p>
231
312
  </div>
232
- <div v-if="canRemove(row)" :class="compact ? 'pt-1' : 'mt-3 flex justify-end'">
313
+ <div
314
+ v-if="canRemove(row) || closable"
315
+ :class="[compact ? 'pt-1' : 'mt-3 flex justify-end', closable && (compact ? 'flex gap-1' : 'gap-3')]"
316
+ >
233
317
  <UButton
318
+ v-if="canRemove(row)"
234
319
  type="button"
235
320
  size="xs"
236
321
  variant="ghost"
@@ -241,6 +326,33 @@ onMounted(() => {
241
326
  >
242
327
  <span v-if="!compact">{{ removeLabel }}</span>
243
328
  </UButton>
329
+ <template v-if="closable">
330
+ <UButton
331
+ v-if="canCancel(row)"
332
+ type="button"
333
+ size="xs"
334
+ variant="ghost"
335
+ color="neutral"
336
+ :icon="compact ? 'i-lucide-x' : undefined"
337
+ :aria-label="`${cancelLabel} ${titleOf(row, i)}`"
338
+ data-cancel
339
+ @click="cancel(row, i)"
340
+ >
341
+ <span v-if="!compact">{{ cancelLabel }}</span>
342
+ </UButton>
343
+ <UButton
344
+ type="button"
345
+ size="xs"
346
+ variant="outline"
347
+ color="neutral"
348
+ :icon="compact ? 'i-lucide-check' : undefined"
349
+ :aria-label="`${doneLabel} ${titleOf(row, i)}`"
350
+ data-done
351
+ @click="done(row, i)"
352
+ >
353
+ <span v-if="!compact">{{ doneLabel }}</span>
354
+ </UButton>
355
+ </template>
244
356
  </div>
245
357
  </fieldset>
246
358
  </template>
@@ -0,0 +1,325 @@
1
+ <script setup lang="ts" generic="T extends SelectMenuItem, V = unknown">
2
+ // Nuxt UI's USelectMenu with the keyboard a data-entry form wants. Every USelectMenu prop, slot, event and v-model
3
+ // passes through unchanged; this adds four switches, each driving USelectMenu (and reka-ui under it) only through its
4
+ // public surface: its props, the trigger, the menu's DOM and the keys reka-ui already handles.
5
+ //
6
+ // <ZSelectMenu v-model="fruit" :items="fruits" /> <!-- type "ch" on the closed menu: Cherry -->
7
+ // <ZSelectMenu v-model="state" :items="states" value-key="code" open-on-focus />
8
+ //
9
+ // - highlightSelectedOnOpen: reka-ui already highlights the checked item when the menu opens (the first checked one
10
+ // with `multiple`), so arrow keys go on from it; that is kept. Off, the menu opens on the first item instead.
11
+ // - typeahead: printable keys on the closed trigger pick the first item from the top of the list whose label starts
12
+ // with what was typed (one letter pressed again and again cycles through the items that start with it), tell a
13
+ // surrounding UForm, and announce it in a polite live region beside the trigger (whose accessible name is its
14
+ // label, not its value). With `multiple` it never replaces the selection: it opens the menu on the match instead.
15
+ // - openOnFocus: keyboard focus opens the menu (not a click, which opens it anyway, and not focus coming back from it).
16
+ // - closeOnTab: Tab and Shift+Tab close the open menu and move on to the next or previous field. reka-ui otherwise
17
+ // keeps focus looping inside the menu. A single-select menu commits the highlighted item first, as Enter would, once
18
+ // the person has moved the highlight in this opening (arrow keys, typing in the search or the list, a hover): type
19
+ // or arrow to an item, Tab to take it. An untouched menu leaves the value as it was, and so does `multiple` (Tab
20
+ // there would add or remove an item just by leaving the field; Enter and a click toggle it).
21
+ //
22
+ // The trigger shows its focus ring on any focus, a click's included (stock shows it on keyboard focus only): while it
23
+ // has focus, and while the menu is open, the menu is drawn with stock's keyboard-focus look, the ring and halo a focused
24
+ // UInput shows.
25
+ import type { SelectMenuItem, SelectMenuProps } from '@nuxt/ui'
26
+ import { formFieldInjectionKey, useFormField } from '@nuxt/ui/composables'
27
+ import { itemLabel, itemValue, selectableItems, typeaheadMatch, type TypeaheadKeys } from './select-typeahead.ts'
28
+
29
+ defineOptions({ inheritAttrs: false })
30
+
31
+ const props = withDefaults(
32
+ defineProps<{
33
+ /** USelectMenu's items: a list, or a list of groups. */
34
+ items?: T[] | T[][]
35
+ /** USelectMenu's `labelKey`, read here for typeahead. */
36
+ labelKey?: string
37
+ /** USelectMenu's `valueKey`, read here for typeahead. */
38
+ valueKey?: string
39
+ /** USelectMenu's `multiple`. */
40
+ multiple?: boolean
41
+ /** USelectMenu's `searchInput` (on unless `false`). */
42
+ searchInput?: boolean | Record<string, unknown>
43
+ /** Open on the selected item, so arrow keys go on from it; off, on the first item. */
44
+ highlightSelectedOnOpen?: boolean
45
+ /** Typing on the closed menu picks the first item that starts with what was typed. */
46
+ typeahead?: boolean
47
+ /** Keyboard focus opens the menu: for data entry, where every field is filled in turn. */
48
+ openOnFocus?: boolean
49
+ /** Tab closes the open menu and moves on, taking the highlighted item in a single-select menu once the highlight has moved. */
50
+ closeOnTab?: boolean
51
+ }>(),
52
+ {
53
+ items: undefined,
54
+ labelKey: undefined,
55
+ valueKey: undefined,
56
+ multiple: undefined,
57
+ searchInput: undefined,
58
+ highlightSelectedOnOpen: true,
59
+ typeahead: true,
60
+ openOnFocus: false,
61
+ closeOnTab: true,
62
+ },
63
+ )
64
+ // The caller's model type. USelectMenu works its own out from items, value-key and multiple, which this wrapper's
65
+ // generics don't reproduce, so the model crosses to it untyped (`as never` in the template) and comes back as V.
66
+ const [model, modelModifiers] = defineModel<V>()
67
+ const emit = defineEmits<{ change: [event: Event] }>()
68
+ const attrs = useAttrs()
69
+ const slots = useSlots()
70
+
71
+ // useFormField() clears the form field it hands its own component, for the input inside it; here that input is the
72
+ // wrapped USelectMenu, which needs the field (its id, name, aria and error color), so it is handed on again.
73
+ const formField = inject(formFieldInjectionKey, undefined)
74
+ const { emitFormChange, emitFormInput } = useFormField()
75
+ provide(formFieldInjectionKey, formField)
76
+
77
+ const menu = useTemplateRef<{ triggerRef: HTMLElement | null; viewportRef: HTMLElement | null }>('menu')
78
+ const trigger = () => menu.value?.triggerRef ?? null
79
+ const content = () => menu.value?.viewportRef?.closest<HTMLElement>('[data-slot="content"]') ?? null
80
+
81
+ const keys = computed<TypeaheadKeys>(() => ({
82
+ labelKey: props.labelKey,
83
+ valueKey: props.valueKey,
84
+ by: attrs.by as TypeaheadKeys['by'],
85
+ }))
86
+ const hasSearch = computed(() => props.searchInput !== false)
87
+
88
+ const isOpen = ref(false)
89
+ let closedAt = 0
90
+ /** A letter typed on the closed `multiple` menu, handed to the menu once it is open. */
91
+ let pendingKey = ''
92
+ /** Whether the person has moved the highlight since the menu opened (arrow keys, typing, a hover): only then does
93
+ * Tab take the highlighted item. Untouched, the highlight is only where the menu opened (the selected item, or the first
94
+ * one when nothing is selected), and Tabbing past the field must not fill it in. */
95
+ let touched = false
96
+
97
+ function onOpen(value: boolean) {
98
+ if (value === isOpen.value) return
99
+ isOpen.value = value
100
+ if (value) {
101
+ touched = false
102
+ document.addEventListener('keydown', onDocumentKeydown, true)
103
+ document.addEventListener('input', onDocumentInput, true)
104
+ document.addEventListener('pointermove', onDocumentPointermove, true)
105
+ void afterOpen()
106
+ } else {
107
+ closedAt = performance.now()
108
+ pendingKey = ''
109
+ removeDocumentListeners()
110
+ }
111
+ }
112
+ function removeDocumentListeners() {
113
+ document.removeEventListener('keydown', onDocumentKeydown, true)
114
+ document.removeEventListener('input', onDocumentInput, true)
115
+ document.removeEventListener('pointermove', onDocumentPointermove, true)
116
+ }
117
+ onBeforeUnmount(removeDocumentListeners)
118
+ // A menu opened (or closed) from code through v-model:open emits no update:open; `open` passes through $attrs, and
119
+ // a change to it re-renders this wrapper, so it is caught here.
120
+ function followOpenAttr() {
121
+ const open = attrs.open
122
+ if (typeof open === 'boolean' && open !== isOpen.value) onOpen(open)
123
+ }
124
+ onMounted(followOpenAttr)
125
+ onBeforeUpdate(followOpenAttr)
126
+
127
+ const NAVIGATION = new Set(['ArrowDown', 'ArrowUp', 'Home', 'End', 'PageDown', 'PageUp'])
128
+ const inMenu = (e: Event) => e.isTrusted && e.target instanceof Node && !!content()?.contains(e.target)
129
+ function onDocumentInput(e: Event) {
130
+ if (inMenu(e)) touched = true
131
+ }
132
+ // A hover moves the highlight: reka-ui highlights the item a pointer moves over, so a move over one it hasn't
133
+ // highlighted yet is the person moving it.
134
+ function onDocumentPointermove(e: PointerEvent) {
135
+ if (!inMenu(e)) return
136
+ const option = (e.target as Element).closest?.('[role="option"]')
137
+ if (option && !option.hasAttribute('data-highlighted')) touched = true
138
+ }
139
+
140
+ /** Resolves to what `find` returns once it returns something, or null after about ten frames. */
141
+ function waitFor<R>(find: () => R | null | undefined, frames = 10): Promise<R | null> {
142
+ return new Promise((done) => {
143
+ const step = (left: number) => {
144
+ const found = find()
145
+ if (found) done(found)
146
+ else if (left <= 0) done(null)
147
+ else requestAnimationFrame(() => step(left - 1))
148
+ }
149
+ step(frames)
150
+ })
151
+ }
152
+
153
+ /** A key, sent where reka-ui listens for it: the search input, or the item that has focus. */
154
+ function press(key: string) {
155
+ const target = document.activeElement
156
+ if (!target || !content()?.contains(target)) return
157
+ target.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }))
158
+ }
159
+
160
+ async function afterOpen() {
161
+ // reka-ui highlights the checked item a couple of ticks after opening; act once it has.
162
+ const viewport = await waitFor(() => (isOpen.value ? menu.value?.viewportRef : null))
163
+ if (!viewport || !(await waitFor(() => viewport.querySelector('[data-highlighted]')))) return
164
+ if (!props.highlightSelectedOnOpen) press('Home')
165
+ const key = pendingKey
166
+ pendingKey = ''
167
+ if (!key) return
168
+ const input = hasSearch.value ? document.activeElement : null
169
+ if (input instanceof HTMLInputElement && content()?.contains(input)) {
170
+ // Into the search, as if typed there: it filters and highlights the first match, and typing carries on in it.
171
+ input.value = key
172
+ input.dispatchEvent(new Event('input', { bubbles: true }))
173
+ } else {
174
+ press(key) // reka-ui's own typeahead, in the open list
175
+ }
176
+ }
177
+
178
+ function openMenu() {
179
+ if (!isOpen.value) trigger()?.click()
180
+ }
181
+
182
+ // ── Typeahead, on the closed trigger ───────────────────────────────────────────────────────────────────────────
183
+ let search = ''
184
+ let searchTimer: ReturnType<typeof setTimeout> | undefined
185
+ const announced = ref('')
186
+ onBeforeUnmount(() => clearTimeout(searchTimer))
187
+
188
+ function onTriggerKeydown(e: KeyboardEvent) {
189
+ if (!props.typeahead || isOpen.value || e.defaultPrevented || e.isComposing) return
190
+ if (e.key.length !== 1 || e.ctrlKey || e.metaKey || e.altKey) return
191
+ // Space opens the menu, unless it is part of a search under way ("new y").
192
+ if (e.key === ' ' && !search) return
193
+ e.preventDefault()
194
+ clearTimeout(searchTimer)
195
+ searchTimer = setTimeout(() => (search = ''), 1000)
196
+ search += e.key
197
+
198
+ if (props.multiple) {
199
+ pendingKey = e.key
200
+ openMenu()
201
+ return
202
+ }
203
+ const match = typeaheadMatch(selectableItems(props.items), search, model.value, keys.value)
204
+ if (match === undefined) return
205
+ model.value = withModifiers(itemValue(match, keys.value)) as V
206
+ emit('change', new Event('change'))
207
+ emitFormChange()
208
+ emitFormInput()
209
+ // The trigger's accessible name is its label, not its value, so a pick made with the menu closed is announced.
210
+ announced.value = itemLabel(match, keys.value)
211
+ }
212
+
213
+ /** A value as USelectMenu's own update applies `v-model`'s modifiers to it. */
214
+ function withModifiers(value: unknown): unknown {
215
+ const m = (modelModifiers ?? {}) as Record<string, boolean | undefined>
216
+ if (m.trim && (typeof value === 'string' || value == null)) value = (value as string | null | undefined)?.trim() ?? null
217
+ if (m.number) {
218
+ const n = Number.parseFloat(value as string)
219
+ if (!Number.isNaN(n)) value = n
220
+ }
221
+ if (m.nullable) value ??= null
222
+ if (m.optional && !m.nullable && value !== null) value ??= undefined
223
+ return value
224
+ }
225
+
226
+ // ── Focus ring on any focus ────────────────────────────────────────────────────────────────────────────────────
227
+ const focused = ref(false)
228
+ const appConfig = useAppConfig() as { ui?: { selectMenu?: { defaultVariants?: { variant?: string } } } }
229
+ // While the trigger has focus, or the menu is open (focus is then in the menu, but the field is still the one being
230
+ // filled in), stock's keyboard-focus look, as a focused UInput draws it: `highlight` is the 1px ring in the menu's
231
+ // color, and `outline-3` the width stock's `focus-visible:outline-3` gives the `outline-<color>/25` halo the theme
232
+ // already sets. The `none` variant has no halo in the theme, so it gets the ring alone.
233
+ const focusRing = computed(() => {
234
+ if (!focused.value && !isOpen.value) return {}
235
+ const variant = (attrs.variant as string | undefined) ?? appConfig.ui?.selectMenu?.defaultVariants?.variant ?? 'outline'
236
+ if (variant === 'none') return { highlight: true }
237
+ const ui = (attrs.ui ?? {}) as NonNullable<SelectMenuProps['ui']>
238
+ const base = ui.base
239
+ // A `ui.base` may be classes to merge or a function that replaces the defaults; the outline goes on after either.
240
+ const halo: typeof base = typeof base === 'function' ? (defaults: string) => [base(defaults), 'outline-3'] : [base, 'outline-3']
241
+ return { highlight: true, ui: { ...ui, base: halo } }
242
+ })
243
+
244
+ function onTriggerFocusout(e: FocusEvent) {
245
+ if (!(e.currentTarget as Node).contains(e.relatedTarget as Node | null)) focused.value = false
246
+ }
247
+
248
+ // ── Open on focus ──────────────────────────────────────────────────────────────────────────────────────────────
249
+ let movingFocus = false
250
+
251
+ function onTriggerFocusin(e: FocusEvent) {
252
+ focused.value = true
253
+ // Every way back into the menu starts here, so a menu left inert by Tab is usable again (it may be reopened while
254
+ // it is still animating closed, as the same element).
255
+ if (left) left.inert = false
256
+ left = null
257
+ if (!props.openOnFocus || isOpen.value || movingFocus) return
258
+ const el = e.currentTarget as HTMLElement
259
+ // A click focuses the trigger and opens the menu itself; opening here too would close it again.
260
+ if (!el.matches(':focus-visible')) return
261
+ // Focus coming back from the menu as it closes (Escape, a pick) is not arriving at the field.
262
+ const from = e.relatedTarget as Node | null
263
+ if (from ? content()?.contains(from) : performance.now() - closedAt < 400) return
264
+ openMenu()
265
+ }
266
+
267
+ // ── Close on Tab ───────────────────────────────────────────────────────────────────────────────────────────────
268
+ /** The menu Tab closed, inert while it animates closed. */
269
+ let left: HTMLElement | null = null
270
+
271
+ function onDocumentKeydown(e: KeyboardEvent) {
272
+ // Arrow keys, and a letter in a list without a search input (reka-ui's own typeahead moves the highlight).
273
+ if ((NAVIGATION.has(e.key) || (e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey)) && inMenu(e)) touched = true
274
+ if (e.key !== 'Tab' || !props.closeOnTab || !isOpen.value || e.ctrlKey || e.metaKey || e.altKey) return
275
+ const el = trigger()
276
+ const menuEl = content()
277
+ const target = e.target as Node | null
278
+ if (!el || !menuEl || !target || !menuEl.contains(target)) return
279
+ // reka-ui's focus scope loops Tab inside the menu only while focus is on its last (or first) item; by the time the
280
+ // key reaches it, focus is on the trigger below, so it lets the key be.
281
+ if (touched && !props.multiple) press('Enter') // the highlighted item, as Enter takes it
282
+ // Focus leaving the menu for its trigger closes it (the spec checks it, on the page's last field too). Not a click
283
+ // on the trigger: `isOpen` hears of a close a tick late, so a click after Enter's close could open it again.
284
+ movingFocus = true
285
+ el.focus()
286
+ movingFocus = false
287
+ // The search input's UInput `autofocus` focuses it on a timer after it mounts; a Tab that comes inside that window
288
+ // would have focus pulled back into the closing menu. Inert, nothing in it can take focus, Tab's included.
289
+ menuEl.inert = true
290
+ left = menuEl
291
+ // No preventDefault: the browser's own Tab now moves on from the trigger, to the next field or (Shift) the last.
292
+ }
293
+
294
+ defineExpose({
295
+ /** The trigger button. */
296
+ triggerRef: computed(() => menu.value?.triggerRef ?? null),
297
+ /** The open menu's list of items. */
298
+ viewportRef: computed(() => menu.value?.viewportRef ?? null),
299
+ })
300
+ </script>
301
+
302
+ <template>
303
+ <USelectMenu
304
+ ref="menu"
305
+ v-bind="{ ...$attrs, ...focusRing }"
306
+ :model-value="model as never"
307
+ :model-modifiers="modelModifiers"
308
+ :items="props.items"
309
+ :label-key="props.labelKey"
310
+ :value-key="props.valueKey"
311
+ :multiple="props.multiple"
312
+ :search-input="props.searchInput"
313
+ @update:model-value="(v: unknown) => (model = v as V)"
314
+ @change="(e: Event) => emit('change', e)"
315
+ @update:open="onOpen"
316
+ @keydown="onTriggerKeydown"
317
+ @focusin="onTriggerFocusin"
318
+ @focusout="onTriggerFocusout"
319
+ >
320
+ <template v-for="(_, name) in slots" :key="name" #[name]="slotProps">
321
+ <slot :name="name" v-bind="slotProps ?? {}" />
322
+ </template>
323
+ </USelectMenu>
324
+ <span class="sr-only" aria-live="polite" data-select-menu-announce>{{ announced }}</span>
325
+ </template>