@zooui/nuxt 0.1.1 → 0.3.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.
@@ -0,0 +1,180 @@
1
+ <script setup lang="ts" generic="T extends Temporal.PlainDate | CalendarDateLike | null">
2
+ // An optional date: a checkbox in front of a ZDateField, for a day a record may or may not have — "Has an end date",
3
+ // "Follow-up booked". The date is editable, and counts, only while the box is ticked.
4
+ //
5
+ // <UFormField label="Ends"><ZOptionalDate v-model="form.endDate" label="Has an end date" /></UFormField>
6
+ // <ZOptionalDate v-model="followUp" v-model:enabled="hasFollowUp" label="Follow-up booked" model-type="calendar-date" />
7
+ //
8
+ // THE MODEL. By default, unticking disables the date field and greys it out, and LEAVES the day in v-model,
9
+ // so the form reads `enabled` to know whether it counts. The box and the day are independent: a day the parent sets
10
+ // doesn't tick the box. Ticked and empty is a state of its own ("has an end date, not yet known"), which is why the box
11
+ // is `v-model:enabled` rather than read off the date. Unbound, the box starts ticked when the model holds a day.
12
+ //
13
+ // `clear-when-off` makes v-model null while the box is off, for a form that saves what it holds: unticking REMEMBERS
14
+ // the day (here, not in the model) and ticking again puts it back, so a box unticked by mistake costs nothing; the
15
+ // field shows no day while it is off, and a day the parent sets ticks the box. Unticking a day announces `dateUpdate`
16
+ // with null (an inline editor saves then); a restored day is announced by the field itself when focus leaves it.
17
+ //
18
+ // Nothing is written at mount in either mode, so loading a record never marks the form changed: a box off with a day
19
+ // in hand shows the day greyed out until the user ticks or unticks.
20
+ //
21
+ // `enabled-change` fires with the new state when the USER ticks or unticks, never when the
22
+ // parent sets `enabled` or the day — the moment to fetch a default date. A tick by the user moves focus into the date
23
+ // field.
24
+ //
25
+ // SIZE. An explicit `size` prop wins, then a surrounding UFieldGroup's, then a UFormField's, the order
26
+ // Nuxt UI's own useFieldGroup and useFormField read it in.
27
+ //
28
+ // IN A UFormField the date field is the input: the label names it and the field's error and help describe it, as for
29
+ // a bare ZDateField. The checkbox is named by `label` and kept out of the form field (an input in a UFormField takes
30
+ // its id, which two inputs can't share), and it names the date input in aria-controls.
31
+ //
32
+ // Everything else — format, locale, clearable, placeholder, icon, `@invalid`, `@clear` … — passes through to ZDateField.
33
+ import { fieldGroupInjectionKey, formBusInjectionKey, formFieldInjectionKey, inputIdInjectionKey } from '@nuxt/ui/composables'
34
+ import type { Temporal } from 'temporal-polyfill/implementation'
35
+ import type { CalendarDateLike, DateModelType } from '../utils/date-entry'
36
+
37
+ defineOptions({ inheritAttrs: false })
38
+
39
+ type Day = NonNullable<T>
40
+ type Size = 'xs' | 'sm' | 'md' | 'lg' | 'xl'
41
+
42
+ const props = withDefaults(
43
+ defineProps<{
44
+ /** The checkbox's accessible name: "Has an end date", "Follow-up booked". */
45
+ label?: string
46
+ /** Disables the checkbox and the date field. */
47
+ disabled?: boolean
48
+ size?: Size
49
+ /** As ZDateField's: the type to hand back while the model is null and has held no day. */
50
+ modelType?: DateModelType
51
+ /** Make v-model null while the box is off, keeping the day to put back on a tick. Off: the day stays in v-model. */
52
+ clearWhenOff?: boolean
53
+ /** The first day the field takes, a PlainDate or a CalendarDate. */
54
+ minValue?: Temporal.PlainDate | CalendarDateLike
55
+ /** The last day the field takes, a PlainDate or a CalendarDate. */
56
+ maxValue?: Temporal.PlainDate | CalendarDateLike
57
+ /** Days the field refuses between the two; called with a day of the model's type. */
58
+ isDateUnavailable?: (date: Day) => boolean
59
+ }>(),
60
+ { label: 'Set a date', modelType: 'plain-date' },
61
+ )
62
+ const emit = defineEmits<{
63
+ // As ZDateField's, and null when unticking clears a day (clear-when-off).
64
+ dateUpdate: [value: T | null]
65
+ // The user ticked (true) or unticked (false) the box.
66
+ enabledChange: [enabled: boolean]
67
+ }>()
68
+ const model = defineModel<T | null>({ default: null })
69
+ /** Whether the box is ticked. Unbound, it starts ticked when the model holds a day. */
70
+ const enabled = defineModel<boolean | undefined>('enabled', { default: undefined })
71
+
72
+ const formField = inject(formFieldInjectionKey, undefined)
73
+ const formInputId = inject(inputIdInjectionKey, undefined)
74
+ const formBus = inject(formBusInjectionKey, undefined)
75
+ const ownId = useId()
76
+ // Inside a UFormField the date input takes the field's id (so its label names it); outside, one of ours.
77
+ const inputId = computed(() => (formField?.value ? formInputId?.value : undefined) ?? ownId)
78
+ const fieldGroup = inject(fieldGroupInjectionKey, undefined)
79
+ const size = computed<Size>(() => props.size ?? fieldGroup?.value?.size ?? (formField?.value?.size as Size | undefined) ?? 'md')
80
+
81
+ // The checkbox outside the form field: no shared id, no field error color, no form events on its own.
82
+ const OutsideFormField = defineComponent({
83
+ setup(_, { slots }) {
84
+ provide(formFieldInjectionKey, undefined)
85
+ provide(inputIdInjectionKey, ref<string>())
86
+ return () => slots.default?.()
87
+ },
88
+ })
89
+
90
+ // The box's state, read here rather than off `enabled`: a parent-owned v-model only catches up on its next render.
91
+ const on = ref(enabled.value ?? model.value != null)
92
+ // The day unticking took away, for ticking to put back (clear-when-off).
93
+ let kept: T | null = null
94
+
95
+ // Returns whether the box changed.
96
+ function apply(next: boolean) {
97
+ if (next === on.value) return false
98
+ on.value = next
99
+ enabled.value = next
100
+ if (!props.clearWhenOff) return true
101
+ if (!next) {
102
+ if (model.value == null) return true
103
+ kept = model.value
104
+ model.value = null
105
+ emit('dateUpdate', null)
106
+ } else if (model.value == null && kept != null) {
107
+ model.value = kept
108
+ kept = null
109
+ }
110
+ return true
111
+ }
112
+
113
+ watch(() => enabled.value, (v) => { if (v !== undefined) apply(v) })
114
+ // clear-when-off: a day the parent sets ticks the box, and replaces any kept one.
115
+ watch(model, (v) => {
116
+ if (v == null || !props.clearWhenOff) return
117
+ kept = null
118
+ if (!on.value) {
119
+ on.value = true
120
+ enabled.value = true
121
+ }
122
+ })
123
+
124
+ const fieldCmp = useTemplateRef<{ focus: () => void }>('fieldCmp')
125
+ const checkboxCmp = useTemplateRef<{ $el: HTMLElement }>('checkboxCmp')
126
+
127
+ function onToggle(v: boolean | 'indeterminate') {
128
+ if (apply(v === true)) emit('enabledChange', on.value)
129
+ // The model changed in code, which the date input never reports, and the box is kept out of the form field: so a
130
+ // UForm hears it here, and revalidates the field (an error for a date the box no longer asks for goes away).
131
+ const name = formField?.value?.name
132
+ if (formBus && name) formBus.emit({ type: 'change', name })
133
+ if (on.value) nextTick(() => fieldCmp.value?.focus())
134
+ }
135
+
136
+ const attrs = useAttrs()
137
+ const fieldAttrs = computed(() => {
138
+ const { class: _class, style: _style, ui, ...rest } = attrs as Record<string, unknown> & { ui?: { base?: string, root?: string } }
139
+ return { ...rest, ui: { ...ui, root: `-ms-px min-w-0 flex-1 ${ui?.root ?? ''}`, base: `rounded-s-none ${ui?.base ?? ''}` } }
140
+ })
141
+
142
+ defineExpose({
143
+ /** Focuses the date field while the box is ticked, the checkbox while it isn't. */
144
+ focus: () => {
145
+ if (on.value) fieldCmp.value?.focus()
146
+ else checkboxCmp.value?.$el?.querySelector<HTMLElement>('button')?.focus()
147
+ },
148
+ })
149
+ </script>
150
+
151
+ <template>
152
+ <div class="inline-flex items-stretch" :class="attrs.class" :style="attrs.style as never" data-optional-date :data-enabled="on || undefined">
153
+ <div class="flex items-center rounded-s-md bg-default ps-2.5 pe-2 ring ring-inset ring-accented">
154
+ <OutsideFormField>
155
+ <UCheckbox
156
+ ref="checkboxCmp"
157
+ :model-value="on"
158
+ :size="size"
159
+ :disabled="disabled"
160
+ :aria-label="label"
161
+ :aria-controls="inputId"
162
+ @update:model-value="onToggle"
163
+ />
164
+ </OutsideFormField>
165
+ </div>
166
+ <ZDateField
167
+ :id="formField ? undefined : inputId"
168
+ ref="fieldCmp"
169
+ v-bind="fieldAttrs"
170
+ v-model="model"
171
+ :size="size"
172
+ :disabled="disabled || !on"
173
+ :model-type="modelType"
174
+ :min-value="minValue"
175
+ :max-value="maxValue"
176
+ :is-date-unavailable="isDateUnavailable as never"
177
+ @date-update="(d: T | null) => emit('dateUpdate', d)"
178
+ />
179
+ </div>
180
+ </template>
@@ -0,0 +1,495 @@
1
+ <script setup lang="ts" generic="T">
2
+ // An order list: the left half of a master-detail editor. A compact listbox with ONE selected row, and a toolbar
3
+ // beside it that adds, removes and moves that row; the selected item's form sits next to it, in the caller's markup.
4
+ // Written on Nuxt UI's tokens.
5
+ //
6
+ // <ZOrderList v-model="statuses" v-model:selection="selectedId" :row-key="(s) => s.id" item-label="status" allow-remove @add="add" @remove="remove">
7
+ // <template #item="{ item }">{{ item.name }}</template>
8
+ // </ZOrderList>
9
+ //
10
+ // The list owns the order: a move hands back a new array of the same items through v-model, and `reorder` says what
11
+ // moved. `add` asks the caller for a new item. `remove` hands over the one to go: with a listener bound the caller
12
+ // takes it out (a server call can come first), and with none the list does. Selection is the selected
13
+ // item's key, so it follows the item through a move.
14
+ // Selection follows focus: Up/Down select the next row, so the form beside the list follows the keyboard.
15
+ import { twMerge } from 'tailwind-merge'
16
+ import { moveItem, moveTarget, typeaheadIndex, type OrderMove } from '../utils/order-list'
17
+
18
+ const props = withDefaults(
19
+ defineProps<{
20
+ /** The item's stable key (a saved record's id): what `v-model:selection` holds. */
21
+ rowKey: (item: T) => string | number
22
+ /** The item's name, for the buttons, the announcements and typeahead; the row's text unless given. */
23
+ rowTitle?: (item: T, index: number) => string
24
+ /** One item, singular and lower case: "status". Names the Add button: "Add status". */
25
+ itemLabel?: string
26
+ /** The heading over the list, and the listbox's name. The #header slot replaces it. */
27
+ title?: string
28
+ /** The listbox's accessible name when there is no title. */
29
+ label?: string
30
+ /** The list's most height before it scrolls, as CSS. Ignored with `fill`. */
31
+ maxHeight?: string
32
+ /** Fill the height it is given (a grid cell, a panel) instead of stopping at `max-height`. */
33
+ fill?: boolean
34
+ /** Classes for its parts, merged over the defaults (tailwind-merge): `root`, `header`, `list` (the bordered box),
35
+ * `row`, `controls` (the built-in toolbar). */
36
+ ui?: Partial<Record<'root' | 'header' | 'list' | 'row' | 'controls', string>>
37
+ /** Every other row tinted. */
38
+ striped?: boolean
39
+ /** Show the Add button. */
40
+ allowAdd?: boolean
41
+ /** Show the Remove button. */
42
+ allowRemove?: boolean
43
+ /** Whether the selected item may be removed (default: any). Remove is disabled when it may not. */
44
+ removable?: (item: T) => boolean
45
+ /** Ask before Remove goes ahead, in ZConfirmButton's popover. False: Remove acts at once. */
46
+ confirmRemove?: boolean
47
+ /** The question ZConfirmButton asks; "Remove Open?" unless given. */
48
+ removeQuestion?: string
49
+ /** A line under the question saying what happens: "Tasks in this status keep it." */
50
+ removeDescription?: string
51
+ /** The popover's confirming button; the Remove word unless given. */
52
+ removeConfirmLabel?: string
53
+ /** The popover's declining button. */
54
+ removeCancelLabel?: string
55
+ /** The Add button's name; "Add <item-label>" unless given. */
56
+ addLabel?: string
57
+ /** The Remove button's word; its name is this and the selected item's title: "Remove Open". */
58
+ removeLabel?: string
59
+ /** A move button's name; "Move Open to top", "Move Open up" … unless given. */
60
+ moveLabel?: (move: OrderMove, title: string | undefined) => string
61
+ /** The toolbar's accessible name. */
62
+ controlsLabel?: string
63
+ /** Shown in the box when the list is empty. The #empty slot replaces it. */
64
+ emptyLabel?: string
65
+ /** What a screen reader hears after a move or a remove; "Moved Open to position 3 of 5." unless given. */
66
+ announce?: (change: { type: 'moved' | 'removed'; title: string; position: number; count: number }) => string
67
+ }>(),
68
+ {
69
+ rowTitle: undefined,
70
+ itemLabel: undefined,
71
+ title: undefined,
72
+ label: undefined,
73
+ maxHeight: '15rem',
74
+ fill: false,
75
+ ui: undefined,
76
+ striped: false,
77
+ allowAdd: true,
78
+ allowRemove: false,
79
+ removable: undefined,
80
+ confirmRemove: true,
81
+ removeQuestion: undefined,
82
+ removeDescription: undefined,
83
+ removeConfirmLabel: undefined,
84
+ removeCancelLabel: 'Cancel',
85
+ addLabel: undefined,
86
+ removeLabel: 'Remove',
87
+ moveLabel: undefined,
88
+ controlsLabel: 'List actions',
89
+ emptyLabel: 'Nothing here yet.',
90
+ announce: undefined,
91
+ },
92
+ )
93
+ const items = defineModel<T[]>({ required: true })
94
+ const selection = defineModel<string | number | null>('selection', { default: null })
95
+ const emit = defineEmits<{
96
+ /** Add was pressed: create the item, put it in the list and select it. */
97
+ add: []
98
+ /** Remove was pressed (and confirmed). Bound, the caller takes the item out; unbound, the list does. */
99
+ remove: [item: T, index: number]
100
+ /** A move changed the order; v-model has the new array. */
101
+ reorder: [change: { item: T; from: number; to: number }]
102
+ }>()
103
+
104
+ /** What the #controls slot gets, for a toolbar of the caller's own. */
105
+ interface Controls {
106
+ /** The selected item, or null. */
107
+ selected: T | null
108
+ /** Its index, or -1. */
109
+ index: number
110
+ add: () => void
111
+ remove: () => void
112
+ move: (move: OrderMove) => void
113
+ moveTop: () => void
114
+ moveUp: () => void
115
+ moveDown: () => void
116
+ moveBottom: () => void
117
+ /** Whether the selected row has somewhere to go. */
118
+ canMove: (move: OrderMove) => boolean
119
+ /** Whether the selected row may be removed. */
120
+ canRemove: boolean
121
+ }
122
+ const slots = defineSlots<{
123
+ /** One row. */
124
+ item?(props: { item: T; index: number; selected: boolean }): unknown
125
+ /** The heading over the list, in place of `title`. */
126
+ header?(): unknown
127
+ /** The empty list, in place of `empty-label`. */
128
+ empty?(): unknown
129
+ /** The toolbar, in place of the built-in buttons. */
130
+ controls?(props: Controls): unknown
131
+ }>()
132
+
133
+ const uid = useId()
134
+ const keyOf = (item: T) => props.rowKey(item)
135
+ // A row's DOM id is numbered per key, never the key itself: a key with a space would not be one id.
136
+ const domIds = new Map<string | number, number>()
137
+ function rowId(item: T) {
138
+ const k = keyOf(item)
139
+ let n = domIds.get(k)
140
+ if (n === undefined) domIds.set(k, (n = domIds.size + 1))
141
+ return `${uid}-row-${n}`
142
+ }
143
+
144
+ /** The selected row; -1 when nothing is selected, or the key is not in the list. */
145
+ const selectedIndex = computed(() => (selection.value == null ? -1 : items.value.findIndex((item) => keyOf(item) === selection.value)))
146
+ const selectedItem = computed(() => (selectedIndex.value < 0 ? null : items.value[selectedIndex.value]!))
147
+
148
+ const root = ref<HTMLElement | null>(null)
149
+ const scroller = ref<HTMLElement | null>(null)
150
+ const listbox = () => scroller.value?.querySelector<HTMLElement>('[role="listbox"]') ?? null
151
+ // By the row's own id, never its place: a removed row stays in the DOM one frame, with its old data-row, while it leaves.
152
+ const rowEl = (i: number) => {
153
+ const item = items.value[i]
154
+ return item === undefined ? null : scroller.value?.querySelector<HTMLElement>(`[id="${rowId(item)}"]`) ?? null
155
+ }
156
+
157
+ // Without rowTitle, a row's title is its text as drawn, read after each render (read during one, it would be the
158
+ // text before the edit that caused it).
159
+ const rowTexts = ref(new Map<string, string>())
160
+ function readRowTexts() {
161
+ if (props.rowTitle) return
162
+ const texts = new Map([...(scroller.value?.querySelectorAll<HTMLElement>('[role="option"]') ?? [])].map((el) => [el.id, el.textContent?.trim() ?? '']))
163
+ const now = rowTexts.value
164
+ if (texts.size !== now.size || [...texts].some(([id, t]) => now.get(id) !== t)) rowTexts.value = texts
165
+ }
166
+ onMounted(readRowTexts)
167
+ onUpdated(readRowTexts)
168
+ const titleOf = (i: number) => {
169
+ const item = items.value[i]
170
+ if (item === undefined) return ''
171
+ return props.rowTitle?.(item, i) ?? rowTexts.value.get(rowId(item)) ?? ''
172
+ }
173
+ const selectedTitle = computed(() => (selectedIndex.value < 0 ? undefined : titleOf(selectedIndex.value)))
174
+
175
+ const MOVE_WORDS: Record<OrderMove, string> = { top: 'to top', up: 'up', down: 'down', bottom: 'to bottom' }
176
+ const moveText = (m: OrderMove) => props.moveLabel?.(m, selectedTitle.value) ?? ['Move', selectedTitle.value, MOVE_WORDS[m]].filter(Boolean).join(' ')
177
+ const addText = computed(() => props.addLabel ?? (props.itemLabel ? `Add ${props.itemLabel}` : 'Add'))
178
+ const removeText = computed(() => [props.removeLabel, selectedTitle.value].filter(Boolean).join(' '))
179
+
180
+ const canMove = (m: OrderMove) => moveTarget(selectedIndex.value, items.value.length, m) !== null
181
+ const canRemove = computed(() => !!selectedItem.value && (props.removable?.(selectedItem.value) ?? true))
182
+
183
+ // The polite announcement of a move or a remove. Cleared first and set again in a later task, so the same words twice
184
+ // are heard twice; a newer announcement replaces one still pending.
185
+ const announcement = ref('')
186
+ let announceTimer: ReturnType<typeof setTimeout> | undefined
187
+ function say(type: 'moved' | 'removed', title: string, position: number, count: number) {
188
+ const text = props.announce?.({ type, title, position, count })
189
+ ?? (type === 'moved' ? `Moved ${title} to position ${position} of ${count}.` : `Removed ${title}. ${count} in the list.`)
190
+ announcement.value = ''
191
+ clearTimeout(announceTimer)
192
+ announceTimer = setTimeout(() => { announcement.value = text }, 100)
193
+ }
194
+
195
+ function select(i: number) {
196
+ const item = items.value[i]
197
+ if (item !== undefined) selection.value = keyOf(item)
198
+ }
199
+
200
+ /** The selected row into view in the list's own scroll box, by its layout offset: during a move the row is drawn
201
+ * where it was (the transition's transform), and its bounding box would scroll to the wrong place. */
202
+ function scrollToRow(i: number) {
203
+ const box = scroller.value
204
+ const row = rowEl(i)
205
+ if (!box || !row) return
206
+ const pad = 4
207
+ const top = row.offsetTop
208
+ const bottom = top + row.offsetHeight
209
+ if (top - pad < box.scrollTop) box.scrollTop = top - pad
210
+ else if (bottom + pad > box.scrollTop + box.clientHeight) box.scrollTop = bottom + pad - box.clientHeight
211
+ }
212
+ watch(selectedIndex, (i) => { if (i >= 0) scrollToRow(i) }, { flush: 'post' })
213
+ onMounted(() => { if (selectedIndex.value >= 0) scrollToRow(selectedIndex.value) })
214
+
215
+ /** Focus on the toolbar button that was clicked, or back on the list when it is gone or disabled (Move to top, at the
216
+ * top). The button is named rather than read from document.activeElement: Safari does not focus a button on click.
217
+ * Never scrolls: focusing the list would scroll the page to it, and the row is brought into view by scrollToRow. */
218
+ function keepFocus(control?: HTMLButtonElement | null) {
219
+ nextTick(() => {
220
+ if (control?.isConnected && !control.disabled) return control.focus({ preventScroll: true })
221
+ const active = document.activeElement as HTMLButtonElement | null
222
+ if (!active || active === document.body || !root.value?.contains(active) || active.disabled) listbox()?.focus({ preventScroll: true })
223
+ })
224
+ }
225
+
226
+ function move(m: OrderMove, control?: HTMLButtonElement | null) {
227
+ const from = selectedIndex.value
228
+ const to = moveTarget(from, items.value.length, m)
229
+ if (to === null) return
230
+ const item = items.value[from]!
231
+ const title = titleOf(from)
232
+ const next = moveItem(items.value, from, to)
233
+ items.value = next
234
+ // The moved item stays selected (its key, not its old place).
235
+ selection.value = keyOf(next[to]!)
236
+ emit('reorder', { item, from, to })
237
+ say('moved', title, to + 1, next.length)
238
+ keepFocus(control)
239
+ }
240
+
241
+ function add() {
242
+ emit('add')
243
+ }
244
+
245
+ // A remove the list asked for, until the item has left the list: the caller may call a server first.
246
+ let pendingRemove: { key: string | number; index: number; title: string } | null = null
247
+ const instance = getCurrentInstance()
248
+ /** Whether the caller listens to `remove` (and so takes the item out itself). */
249
+ const removeHandled = () => !!instance?.vnode.props?.onRemove
250
+ function remove() {
251
+ const i = selectedIndex.value
252
+ const item = selectedItem.value
253
+ if (!item || !canRemove.value) return
254
+ pendingRemove = { key: keyOf(item), index: i, title: titleOf(i) }
255
+ emit('remove', item, i)
256
+ if (!removeHandled()) items.value = items.value.filter((_, j) => j !== i)
257
+ }
258
+ // When it has gone, the row that took its place is selected, and focus stays in the list.
259
+ watch(
260
+ () => items.value.map(keyOf),
261
+ (keys) => {
262
+ if (!pendingRemove || keys.includes(pendingRemove.key)) return
263
+ const { index, title } = pendingRemove
264
+ pendingRemove = null
265
+ if (keys.length) select(Math.min(index, keys.length - 1))
266
+ else selection.value = null
267
+ say('removed', title, 0, keys.length)
268
+ keepFocus()
269
+ },
270
+ )
271
+ // A remove the caller decided against (a failed server call) is forgotten at the next selection change, so a later
272
+ // reload doesn't announce it or move the selection. Not when the item went in the same tick (a caller clearing the
273
+ // selection as it removes): the watcher above, which runs first, then selects the row that took its place.
274
+ watch(selection, () => {
275
+ if (pendingRemove && items.value.some((item) => keyOf(item) === pendingRemove!.key)) pendingRemove = null
276
+ })
277
+
278
+ // ZConfirmButton's words. Focus goes back to Remove when it is cancelled (ZConfirmButton's own), and to the list
279
+ // once the confirmed item has gone (keepFocus, above).
280
+ const removeQuestionText = computed(() => props.removeQuestion ?? `${removeText.value}?`)
281
+ const removeConfirmText = computed(() => props.removeConfirmLabel ?? props.removeLabel)
282
+
283
+ // Keyboard focus, for the ring: shown when the list was reached or driven by the keyboard, not after a click.
284
+ const focused = ref(false)
285
+ const keyboard = ref(false)
286
+ let pointing = false
287
+ function onFocus() {
288
+ focused.value = true
289
+ keyboard.value = !pointing
290
+ pointing = false
291
+ }
292
+ function onPointerdown() {
293
+ pointing = true
294
+ keyboard.value = false
295
+ }
296
+ // What the rows draw from: a focus move that leaves the ring as it was (the list blurring as a clicked toolbar button
297
+ // takes focus) must not re-render them, or TransitionGroup cancels the slide it has just started.
298
+ const ring = computed(() => focused.value && keyboard.value)
299
+
300
+ let query = ''
301
+ let queryTimer: ReturnType<typeof setTimeout> | undefined
302
+ function typeahead(key: string) {
303
+ query += key
304
+ clearTimeout(queryTimer)
305
+ queryTimer = setTimeout(() => { query = '' }, 500)
306
+ const i = typeaheadIndex(items.value.map((_, j) => titleOf(j)), query, selectedIndex.value)
307
+ if (i >= 0) select(i)
308
+ }
309
+
310
+ const ALT_MOVES: Record<string, OrderMove> = { ArrowUp: 'up', ArrowDown: 'down', Home: 'top', End: 'bottom' }
311
+ function onKeydown(e: KeyboardEvent) {
312
+ keyboard.value = true
313
+ const n = items.value.length
314
+ if (!n) return
315
+ const i = selectedIndex.value
316
+ if (e.altKey && !e.ctrlKey && !e.metaKey) {
317
+ const m = ALT_MOVES[e.key]
318
+ if (!m) return
319
+ e.preventDefault()
320
+ move(m)
321
+ return
322
+ }
323
+ if (e.ctrlKey || e.metaKey || e.altKey) return
324
+ let to: number
325
+ // With nothing selected, Down and Up both start at the first row, and Enter and Space do nothing (selection
326
+ // follows focus, so on a selected row they keep it).
327
+ switch (e.key) {
328
+ case 'ArrowDown': to = i < 0 ? 0 : Math.min(i + 1, n - 1); break
329
+ case 'ArrowUp': to = i < 0 ? 0 : Math.max(i - 1, 0); break
330
+ case 'Home': to = 0; break
331
+ case 'End': to = n - 1; break
332
+ case 'Enter':
333
+ e.preventDefault()
334
+ return
335
+ case ' ':
336
+ e.preventDefault()
337
+ // Part of a name while one is being typed.
338
+ if (query) typeahead(' ')
339
+ return
340
+ default:
341
+ if (e.key.length === 1) { e.preventDefault(); typeahead(e.key) }
342
+ return
343
+ }
344
+ e.preventDefault()
345
+ select(to)
346
+ }
347
+
348
+ onBeforeUnmount(() => { clearTimeout(announceTimer); clearTimeout(queryTimer) })
349
+
350
+ const controls = computed<Controls>(() => ({
351
+ selected: selectedItem.value,
352
+ index: selectedIndex.value,
353
+ add,
354
+ remove,
355
+ move,
356
+ moveTop: () => move('top'),
357
+ moveUp: () => move('up'),
358
+ moveDown: () => move('down'),
359
+ moveBottom: () => move('bottom'),
360
+ canMove,
361
+ canRemove: canRemove.value,
362
+ }))
363
+
364
+ const MOVES: { move: OrderMove; icon: string }[] = [
365
+ { move: 'top', icon: 'i-lucide-arrow-up-to-line' },
366
+ { move: 'up', icon: 'i-lucide-chevron-up' },
367
+ { move: 'down', icon: 'i-lucide-chevron-down' },
368
+ { move: 'bottom', icon: 'i-lucide-arrow-down-to-line' },
369
+ ]
370
+
371
+ const headerId = `${uid}-header`
372
+ const hasHeader = computed(() => !!props.title || !!slots.header)
373
+
374
+ function rowClass(i: number, selected: boolean) {
375
+ return twMerge(
376
+ 'cursor-pointer select-none rounded px-2.5 py-1.5 text-sm',
377
+ selected ? 'bg-primary/10 text-highlighted hover:bg-primary/15' : ['text-default hover:bg-elevated', props.striped && i % 2 === 1 && 'bg-elevated/50'],
378
+ selected && ring.value && 'ring-2 ring-inset ring-primary',
379
+ props.ui?.row,
380
+ )
381
+ }
382
+
383
+ // With `fill` the root, the list column (a flex column) and the box take the height they are given; the box grows to
384
+ // what the header leaves, rather than h-full, which would overflow by the header's height.
385
+ const rootClass = computed(() => twMerge('flex flex-col gap-3 sm:flex-row', props.fill && 'h-full', props.ui?.root))
386
+ const columnClass = computed(() => twMerge('min-w-0 flex-auto', props.fill && 'flex min-h-0 flex-col'))
387
+ const headerClass = computed(() => twMerge('px-2.5 py-1.5 text-sm font-medium text-muted', props.ui?.header))
388
+ const listClass = computed(() => twMerge(
389
+ 'relative overflow-y-auto rounded-md bg-default p-1 ring ring-default',
390
+ ring.value && selectedIndex.value < 0 && 'ring-2 ring-primary',
391
+ props.fill && 'min-h-0 flex-1',
392
+ props.ui?.list,
393
+ ))
394
+ const controlsClass = computed(() => twMerge('flex flex-row items-start gap-1 sm:flex-col sm:items-stretch', props.ui?.controls))
395
+
396
+ defineExpose({
397
+ /** Focus the list. */
398
+ focus: () => listbox()?.focus(),
399
+ move,
400
+ remove,
401
+ })
402
+ </script>
403
+
404
+ <template>
405
+ <div ref="root" :class="rootClass" data-testid="order-list">
406
+ <div role="group" :aria-label="controlsLabel" data-controls>
407
+ <slot name="controls" v-bind="controls">
408
+ <div :class="controlsClass">
409
+ <UButton v-if="allowAdd" type="button" size="xs" color="primary" variant="soft" square icon="i-lucide-plus" :aria-label="addText" data-add @click="add()" />
410
+ <template v-if="allowRemove">
411
+ <ZConfirmButton
412
+ v-if="confirmRemove"
413
+ :question="removeQuestionText"
414
+ :description="removeDescription"
415
+ :confirm-label="removeConfirmText"
416
+ :cancel-label="removeCancelLabel"
417
+ type="button"
418
+ size="xs"
419
+ color="error"
420
+ variant="soft"
421
+ square
422
+ icon="i-lucide-trash-2"
423
+ :aria-label="removeText"
424
+ :disabled="!canRemove"
425
+ data-remove
426
+ @confirm="remove()"
427
+ />
428
+ <UButton v-else type="button" size="xs" color="error" variant="soft" square icon="i-lucide-trash-2" :aria-label="removeText" :disabled="!canRemove" data-remove @click="remove()" />
429
+ </template>
430
+ <!-- A gap between the actions and the moves. -->
431
+ <div v-if="allowAdd || allowRemove" class="w-2 sm:h-2 sm:w-0" aria-hidden="true" />
432
+ <UButton
433
+ v-for="b in MOVES"
434
+ :key="b.move"
435
+ type="button"
436
+ size="xs"
437
+ color="neutral"
438
+ variant="soft"
439
+ square
440
+ :icon="b.icon"
441
+ :aria-label="moveText(b.move)"
442
+ :disabled="!canMove(b.move)"
443
+ :data-move="b.move"
444
+ @click="(e: MouseEvent) => move(b.move, e.currentTarget as HTMLButtonElement | null)"
445
+ />
446
+ </div>
447
+ </slot>
448
+ </div>
449
+
450
+ <div :class="columnClass">
451
+ <div v-if="hasHeader" :id="headerId" :class="headerClass" data-header>
452
+ <slot name="header">{{ title }}</slot>
453
+ </div>
454
+ <div
455
+ ref="scroller"
456
+ :class="listClass"
457
+ :style="fill ? undefined : { maxHeight }"
458
+ data-scroller
459
+ >
460
+ <TransitionGroup
461
+ tag="ul"
462
+ role="listbox"
463
+ tabindex="0"
464
+ class="outline-none"
465
+ move-class="transition-transform duration-180 ease-out motion-reduce:transition-none"
466
+ :aria-labelledby="hasHeader ? headerId : undefined"
467
+ :aria-label="hasHeader ? undefined : label"
468
+ :aria-activedescendant="selectedItem !== null ? rowId(selectedItem) : undefined"
469
+ @focus="onFocus"
470
+ @blur="focused = false"
471
+ @pointerdown="onPointerdown"
472
+ @keydown="onKeydown"
473
+ >
474
+ <li
475
+ v-for="(item, i) in items"
476
+ :id="rowId(item)"
477
+ :key="keyOf(item)"
478
+ role="option"
479
+ :aria-selected="i === selectedIndex"
480
+ :data-row="i"
481
+ :data-selected="i === selectedIndex ? '' : undefined"
482
+ :class="rowClass(i, i === selectedIndex)"
483
+ @click="select(i)"
484
+ >
485
+ <slot name="item" :item="item" :index="i" :selected="i === selectedIndex">{{ rowTitle?.(item, i) ?? item }}</slot>
486
+ </li>
487
+ </TransitionGroup>
488
+ <p v-if="!items.length" class="px-2.5 py-1.5 text-sm text-muted" data-empty>
489
+ <slot name="empty">{{ emptyLabel }}</slot>
490
+ </p>
491
+ </div>
492
+ </div>
493
+ <p class="sr-only" role="status" aria-live="polite" data-announce>{{ announcement }}</p>
494
+ </div>
495
+ </template>