@zooui/nuxt 0.0.0-stage → 0.1.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,370 @@
1
+ <script setup lang="ts" generic="T extends string | number | DecimalLike | null | undefined">
2
+ /**
3
+ * One number input for money, percent, count and hours, so every figure looks and moves the same,
4
+ * formatting as it is typed. Layout, in every unit: the currency mark (and any
5
+ * `prefix`) on the left, the value right-aligned, then the unit slot (`%`, `hrs` and any `suffix`; kept empty but the
6
+ * same width for money and counts, so values line up in a column), then its own up/down chevrons. The marks stay out
7
+ * of the text, so typing only ever meets digits.
8
+ *
9
+ * Typing is rebuilt keystroke by keystroke in number-format.ts: the locale's grouping (12,345; de 12.345), one decimal
10
+ * mark, the caret kept on its digit as separators come and go. A commit (blur, Enter, Tab) clamps to min/max and rounds
11
+ * to the decimal places (money: 2). The chevrons and ArrowUp/ArrowDown move by `step` from whatever is there, never
12
+ * snapping to multiples; `:spin="false"` takes both away. `calc` takes `+ - * /` expressions (number-calc.ts), shows
13
+ * the result underneath while focused and puts it in on commit or `evaluate()`. `freeform` keeps it a text box, for a
14
+ * field that takes "$125,000" as typed and tidies it itself: it nudges the same.
15
+ *
16
+ * The model keeps the caller's kind: a string, a number, or a decimal.js Decimal built with the caller's own class.
17
+ * The step, decimal places, currency and locale come from the props, then the product's app.config
18
+ * (`zooui.numberInput`), then number-input.ts's neutral defaults. Everything else (id, size, color, highlight,
19
+ * placeholder, inputmode, disabled, readonly, aria-*) falls through to the UInput.
20
+ */
21
+ import { calcPlaces, containsOperator, editExpression, evaluate as evaluateExpression, reformatExpression } from './number-calc'
22
+ import {
23
+ D, committed, decimalClass, display, edit, figureOf, fixedFigure, holds, kindOf, outside, readHeld, readModel, reformat, relocalize, shownCommitted,
24
+ symbols, toDec, toModel,
25
+ type Dec, type DecimalClass, type DecimalLike, type Edit, type Field, type ModelKind,
26
+ } from './number-format'
27
+ import {
28
+ currencySymbol, DEFAULTS, nudged, PLAIN_NUMBER, readFigure, resolvePlaces, stepLabel, SUFFIX, writeFigure, type NumberInputConfig, type NumberUnit,
29
+ } from './number-input'
30
+
31
+ const props = withDefaults(defineProps<{
32
+ modelValue: T
33
+ unit?: NumberUnit
34
+ step?: number
35
+ freeform?: boolean
36
+ min?: number | string
37
+ max?: number | string
38
+ /** ISO 4217 code for `unit="money"` (default: app.config, then USD). */
39
+ currency?: string
40
+ /** BCP 47 locale for the grouping and decimal marks, the currency symbol and the chevrons' labels (default:
41
+ * app.config, then en-US). */
42
+ locale?: string
43
+ /** The chevrons and ArrowUp/ArrowDown; `false` takes both away. */
44
+ spin?: boolean
45
+ /** Decimal places written on commit (default: app.config, then 2 for money, 0 otherwise). */
46
+ minFractionDigits?: number
47
+ /** Decimal places rounded to on commit, and the most that can be typed (default: app.config, then 2 for money,
48
+ * none otherwise). */
49
+ maxFractionDigits?: number
50
+ /** Text before the value, beside the currency mark. */
51
+ prefix?: string
52
+ /** Text after the value, beside the unit mark. */
53
+ suffix?: string
54
+ /** Select the whole value on focus (default: on in calc). */
55
+ highlightOnFocus?: boolean
56
+ /** Take `+ - * /` expressions, worked out on commit. */
57
+ calc?: boolean
58
+ /** Commit (clamp, round, work out an expression) on blur; `false` for a grid editor that calls `evaluate()`. */
59
+ commitOnBlur?: boolean
60
+ /** The kind to hand back when the model starts empty: a `Decimal` v-model that can be null needs `decimal`. */
61
+ modelType?: ModelKind
62
+ ui?: Record<string, string>
63
+ }>(), { spin: true, highlightOnFocus: undefined, commitOnBlur: true })
64
+ // T is the caller's kind, so a `Ref<Decimal | null>` takes what comes back; empty is `null` (a string model gets '').
65
+ const emit = defineEmits<{ 'update:modelValue': [value: T | null] }>()
66
+ const attrs = useAttrs()
67
+ const config = useAppConfig() as { zooui?: { numberInput?: NumberInputConfig } }
68
+
69
+ const unit = computed<NumberUnit>(() => props.unit ?? 'count')
70
+ const own = computed(() => config.zooui?.numberInput ?? {})
71
+ const step = computed(() => props.step ?? own.value.steps?.[unit.value] ?? DEFAULTS.steps[unit.value])
72
+ const currency = computed(() => props.currency ?? own.value.currency ?? DEFAULTS.currency)
73
+ const locale = computed(() => props.locale ?? own.value.locale ?? DEFAULTS.locale)
74
+ const symbol = computed(() => currencySymbol(locale.value, currency.value))
75
+ const label = computed(() => stepLabel(unit.value, step.value, locale.value, currency.value))
76
+ const sym = computed(() => symbols(locale.value))
77
+ const places = computed(() => {
78
+ const set = own.value.fractionDigits?.[unit.value]
79
+ return resolvePlaces({ min: props.minFractionDigits ?? set?.min, max: props.maxFractionDigits ?? set?.max }, DEFAULTS.places[unit.value])
80
+ })
81
+ const format = computed(() => ({
82
+ symbols: sym.value,
83
+ places: places.value,
84
+ negative: props.min === undefined || props.min === '' || new D(props.min).isNeg(),
85
+ }))
86
+ // calc rounds its result once, on commit: to the field's places, or ten where it has no maximum
87
+ const bounds = computed(() => ({ min: props.min, max: props.max, places: props.calc ? calcPlaces(places.value) : places.value }))
88
+ const highlight = computed(() => props.highlightOnFocus ?? props.calc)
89
+
90
+ // A disabled or read-only field can't be nudged or committed, by its chevrons or its keys.
91
+ const disabled = computed(() => [attrs.disabled, attrs.readonly].some((a) => a === '' || !!a))
92
+
93
+ // The caller's kind, kept through an empty spell, and its Decimal class (so its `instanceof` holds).
94
+ let remembered: ModelKind | undefined
95
+ let cls: DecimalClass | undefined
96
+ watch(() => props.modelValue, (v) => {
97
+ remembered = kindOf(v) ?? remembered
98
+ if (remembered === 'decimal' && v) cls = decimalClass(v as DecimalLike)
99
+ }, { immediate: true })
100
+ const kind = () => kindOf(props.modelValue) ?? props.modelType ?? remembered ?? 'string'
101
+ const model = (figure: string | null) => toModel(figure, kind(), cls) as T | null
102
+
103
+ /** The text for a model value at rest. A string this can't read (freeform's "forty") is shown as it is. */
104
+ function shown(v: T): string {
105
+ if (props.freeform) return String(v ?? '')
106
+ const d = readModel(v)
107
+ return d === null ? (kindOf(v) === 'string' ? String(v) : '') : display(d, sym.value, places.value)
108
+ }
109
+
110
+ const text = ref(shown(props.modelValue))
111
+ const focused = ref(false)
112
+ // What this field last handed back, until the model's next change: that change coming back as it is the field's own
113
+ // typing, not news to show. Any change uses it up, so a parent's 3 and then 2 again after the field's 2 both show.
114
+ const NONE = Symbol('none')
115
+ let emitted: unknown = NONE
116
+ watch(() => props.modelValue, (v) => {
117
+ const own = v === emitted
118
+ emitted = NONE
119
+ if (own) return
120
+ text.value = shown(v)
121
+ validity(props.freeform ? null : readHeld(v, sym.value))
122
+ })
123
+ watch([sym, places], ([now], [before]) => {
124
+ if (!focused.value) return void (text.value = shown(props.modelValue))
125
+ // mid-edit, the text is rewritten in the new locale's marks, so it is never read with marks it wasn't typed in
126
+ const el = input()
127
+ if (props.freeform || now === before || !el) return
128
+ const moved = relocalize({ text: text.value, caret: el.selectionStart ?? text.value.length }, before, now)
129
+ put(props.calc ? reformatExpression(moved.text, moved.caret, now) : reformat(moved.text, moved.caret, format.value))
130
+ })
131
+
132
+ function hand(v: T | null) {
133
+ emitted = v
134
+ emit('update:modelValue', v)
135
+ }
136
+
137
+ const field = useTemplateRef<{ inputRef: HTMLInputElement | null }>('field')
138
+ const input = () => field.value?.inputRef ?? null
139
+
140
+ /** Show a text, with the caret where it goes (the end, for a whole new value). */
141
+ function put(next: Field | string) {
142
+ const f = typeof next === 'string' ? { text: next, caret: next.length } : next
143
+ text.value = f.text
144
+ const el = input()
145
+ if (!el) return
146
+ if (el.value !== f.text) el.value = f.text
147
+ if (el === document.activeElement) el.setSelectionRange(f.caret, f.caret)
148
+ }
149
+
150
+ const lead = computed(() => `${props.prefix ?? ''}${unit.value === 'money' ? symbol.value : ''}`)
151
+ const trail = computed(() => `${SUFFIX[unit.value]}${props.suffix ?? ''}`)
152
+ /** A value with its marks, as the preview and a screen reader say it: "$1,200.00", "12.5%", "40 hrs". */
153
+ const marked = (t: string) => `${lead.value}${t}${trail.value && unit.value === 'hours' ? ' ' : ''}${trail.value}`
154
+
155
+ const n = (v: Dec) => display(v, sym.value, { min: 0 })
156
+ /** Out of range, the field is :invalid (a form won't submit it) until a commit brings it back. */
157
+ function validity(value: Dec | null) {
158
+ const off = outside(value, props.min, props.max)
159
+ input()?.setCustomValidity(off > 0 ? `At most ${n(new D(props.max!))}` : off < 0 ? `At least ${n(new D(props.min!))}` : '')
160
+ }
161
+ /** The value the field holds now, for its range mark: what is being typed, else the model. At rest the text is
162
+ * rounded for display (0.005 shows 0.01 at two places), so it is the model that says whether the value is in range. */
163
+ function current(): Dec | null {
164
+ if (props.freeform) return null
165
+ if (props.calc || !focused.value) return readHeld(props.modelValue, sym.value)
166
+ return toDec(figureOf(text.value, sym.value))
167
+ }
168
+ // a model that arrives out of range is marked so too, from the first render, and the mark follows the bounds
169
+ onMounted(() => validity(current()))
170
+ watch(() => [props.min, props.max], () => validity(current()))
171
+
172
+ // Typing. Each keystroke, paste or deletion is worked out in number-format.ts (or number-calc.ts) before the browser
173
+ // applies it; whatever gets past that (an IME, undo, autofill, a cut) is tidied by the input event after it.
174
+ const EDITS: Record<string, 'insert' | 'backward' | 'forward'> = {
175
+ insertText: 'insert', insertFromPaste: 'insert', deleteContentBackward: 'backward', deleteContentForward: 'forward',
176
+ }
177
+ function onBeforeinput(e: InputEvent) {
178
+ const op = EDITS[e.inputType]
179
+ if (props.freeform || e.isComposing || !op) return
180
+ const el = e.target as HTMLInputElement
181
+ const data = op === 'insert' ? e.data ?? e.dataTransfer?.getData('text/plain') : ''
182
+ if (data === undefined || data === null) return
183
+ e.preventDefault()
184
+ const sel = { text: el.value, start: el.selectionStart ?? el.value.length, end: el.selectionEnd ?? el.value.length }
185
+ const change: Edit = op === 'insert' ? { insert: data } : { delete: op }
186
+ const next = props.calc ? editExpression(sel, change, sym.value) : edit(sel, change, format.value)
187
+ if (!next) return // refused: nothing changes, the selection included
188
+ if (next.text === el.value) return el.setSelectionRange(next.caret, next.caret)
189
+ el.value = next.text
190
+ el.setSelectionRange(next.caret, next.caret)
191
+ el.dispatchEvent(new Event('input', { bubbles: true }))
192
+ }
193
+
194
+ // (an IME's text is tidied once it is composed: compositionend comes here too)
195
+ function onInput(e: Event) {
196
+ if ((e as InputEvent).isComposing) return
197
+ const el = e.target as HTMLInputElement
198
+ if (props.freeform) {
199
+ text.value = el.value
200
+ return hand(el.value as unknown as T)
201
+ }
202
+ const caret = el.selectionStart ?? el.value.length
203
+ put(props.calc ? reformatExpression(el.value, caret, sym.value) : reformat(el.value, caret, format.value))
204
+ if (props.calc) return
205
+ // the model follows the typing (rounded and clamped only on commit); out of range meanwhile, the field is :invalid
206
+ const figure = figureOf(text.value, sym.value)
207
+ validity(toDec(figure))
208
+ if (!holds(props.modelValue, figure)) hand(model(figure))
209
+ }
210
+
211
+ /**
212
+ * Commit what is typed: an expression worked out, clamped to min/max, rounded to the decimal places, handed back and
213
+ * shown in full. An expression that isn't one ("678+", "5/0") leaves the field empty. Returns the model's value.
214
+ */
215
+ function evaluate() {
216
+ if (props.freeform || disabled.value) return props.modelValue ?? null
217
+ const value = committed(props.calc ? evaluateExpression(text.value, sym.value) : toDec(figureOf(text.value, sym.value)), bounds.value)
218
+ validity(value)
219
+ put(shownCommitted(value, sym.value, places.value))
220
+ const figure = value === null ? null : fixedFigure(value, places.value)
221
+ if (holds(props.modelValue, figure)) return props.modelValue ?? null
222
+ const next = model(figure)
223
+ hand(next)
224
+ return next
225
+ }
226
+
227
+ function nudge(direction: 1 | -1) {
228
+ if (disabled.value || !props.spin) return
229
+ const o = { step: step.value, min: props.min, max: props.max }
230
+ if (props.freeform) {
231
+ // what is there isn't a figure (freeform: one `readFigure` can't read): it is never overwritten
232
+ const typed = readFigure(text.value, { symbol: symbol.value, symbols: sym.value, prefix: props.prefix, suffix: props.suffix })
233
+ if (typed !== '' && !PLAIN_NUMBER.test(typed)) return
234
+ const figure = nudged(toDec(typed || null), direction, o).toFixed()
235
+ // written in the field's own marks, so the next nudge reads the same value back; a string model gets that text
236
+ const written = writeFigure(figure, sym.value)
237
+ put(written)
238
+ return hand(kind() === 'string' ? written as unknown as T : model(figure))
239
+ }
240
+ const current = props.calc ? evaluateExpression(text.value, sym.value) : toDec(figureOf(text.value, sym.value))
241
+ if (current === null && figureOf(text.value, sym.value) !== null) return
242
+ const next = committed(nudged(current, direction, o), bounds.value)!
243
+ validity(next)
244
+ put(shownCommitted(next, sym.value, places.value))
245
+ const figure = fixedFigure(next, places.value)
246
+ if (!holds(props.modelValue, figure)) hand(model(figure))
247
+ }
248
+
249
+ function onKeydown(e: KeyboardEvent) {
250
+ // an IME's own Enter (and arrows) choose what it is composing: they aren't the field's
251
+ if (e.isComposing || e.keyCode === 229) return
252
+ if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
253
+ e.preventDefault()
254
+ nudge(e.key === 'ArrowUp' ? 1 : -1)
255
+ } else if (e.key === 'Enter' || e.key === 'Tab') evaluate()
256
+ }
257
+
258
+ // Select-all on focus. A click's own caret would undo it, so a click that focuses selects again on mouseup.
259
+ let clicked = false
260
+ function onFocus(e: FocusEvent) {
261
+ focused.value = true
262
+ if (highlight.value && !disabled.value) (e.target as HTMLInputElement).select()
263
+ }
264
+ function onMousedown(e: MouseEvent) {
265
+ clicked = e.target !== document.activeElement
266
+ }
267
+ function onMouseup(e: MouseEvent) {
268
+ if (clicked && highlight.value && !disabled.value) {
269
+ e.preventDefault()
270
+ ;(e.target as HTMLInputElement).select()
271
+ }
272
+ clicked = false
273
+ }
274
+ function onBlur() {
275
+ focused.value = false
276
+ if (props.commitOnBlur) evaluate()
277
+ }
278
+
279
+ /** calc's result while focused, as it will go in. */
280
+ const preview = computed(() => {
281
+ if (!props.calc || props.freeform || !focused.value || !containsOperator(text.value)) return null
282
+ const value = committed(evaluateExpression(text.value, sym.value), bounds.value)
283
+ return value === null ? null : marked(shownCommitted(value, sym.value, places.value))
284
+ })
285
+
286
+ // A spinbutton, with its range and value, while it spins; a plain text box (no aria-value*) when it doesn't.
287
+ const aria = computed(() => {
288
+ if (!props.spin) return {}
289
+ const figure = props.freeform ? readFigure(text.value, { symbol: symbol.value, symbols: sym.value, prefix: props.prefix, suffix: props.suffix }) : null
290
+ const now = props.calc ? readModel(props.modelValue) : props.freeform ? (PLAIN_NUMBER.test(figure!) ? toDec(figure) : null) : toDec(figureOf(text.value, sym.value))
291
+ return {
292
+ 'role': 'spinbutton',
293
+ 'aria-valuemin': props.min === '' ? undefined : props.min,
294
+ 'aria-valuemax': props.max === '' ? undefined : props.max,
295
+ 'aria-valuenow': now?.toFixed(),
296
+ 'aria-valuetext': text.value && !props.freeform ? marked(text.value) : undefined,
297
+ }
298
+ })
299
+
300
+ // Room for the marks, in the input's own padding so the value never runs under them: a mark character is about half
301
+ // a rem (text-xs). Start: the leading marks ("$" is narrow, wider for "kr" or a prefix). End: the unit slot (the
302
+ // percent sign's width when empty, hours' wider) and the chevrons.
303
+ const slot = computed(() => Math.max(unit.value === 'hours' ? 1.5 : 0.75, trail.value.length * 0.5))
304
+ const room = computed(() => ({
305
+ '--zni-start': lead.value ? `${1 + 0.5 * lead.value.length}rem` : undefined,
306
+ '--zni-end': `${slot.value + (props.spin ? 2 : 0.875)}rem`,
307
+ }))
308
+ const inputUi = computed(() => ({
309
+ ...props.ui,
310
+ base: ['text-right tabular-nums pe-(--zni-end)', lead.value ? 'ps-(--zni-start)' : '', props.ui?.base].filter(Boolean).join(' '),
311
+ leading: ['ps-2.5', props.ui?.leading].filter(Boolean).join(' '),
312
+ trailing: ['pe-1.5', props.ui?.trailing].filter(Boolean).join(' '),
313
+ }))
314
+
315
+ defineExpose({ evaluate, inputRef: computed(input) })
316
+ </script>
317
+
318
+ <template>
319
+ <UInput
320
+ ref="field"
321
+ :model-value="text"
322
+ type="text"
323
+ :inputmode="freeform || calc ? undefined : 'decimal'"
324
+ data-number-input
325
+ :data-unit="unit"
326
+ :style="room"
327
+ v-bind="aria"
328
+ :ui="inputUi"
329
+ @beforeinput="onBeforeinput"
330
+ @input="onInput"
331
+ @compositionend="onInput"
332
+ @keydown="onKeydown"
333
+ @focus="onFocus"
334
+ @blur="onBlur"
335
+ @mousedown="onMousedown"
336
+ @mouseup="onMouseup"
337
+ >
338
+ <output
339
+ v-if="calc && !freeform"
340
+ aria-live="polite"
341
+ class="pointer-events-none absolute inset-x-0 top-full z-10 mt-1 flex justify-between rounded-sm bg-inverted px-1.5 py-0.5 text-xs text-inverted tabular-nums shadow-sm"
342
+ :class="preview ? '' : 'invisible'"
343
+ data-number-preview
344
+ >
345
+ <span><span class="sr-only">Result</span><span aria-hidden="true">=</span></span>
346
+ <span>{{ preview }}</span>
347
+ </output>
348
+ <template v-if="lead" #leading><span class="text-xs whitespace-nowrap text-dimmed" data-number-mark="lead">{{ lead }}</span></template>
349
+ <template #trailing>
350
+ <span class="flex items-center gap-0.5">
351
+ <span class="text-xs whitespace-nowrap text-dimmed" :style="{ width: `${slot}rem` }" aria-hidden="true" data-number-mark="unit">{{ trail }}</span>
352
+ <span v-if="spin" class="flex flex-col print:hidden">
353
+ <button
354
+ v-for="d in ([1, -1] as const)"
355
+ :key="d"
356
+ type="button"
357
+ tabindex="-1"
358
+ :disabled="disabled"
359
+ class="grid h-3 w-4 place-items-center text-dimmed hover:text-default disabled:pointer-events-none"
360
+ :aria-label="`${d > 0 ? 'Add' : 'Subtract'} ${label}`"
361
+ @mousedown.prevent
362
+ @click="nudge(d)"
363
+ >
364
+ <UIcon :name="d > 0 ? 'i-lucide-chevron-up' : 'i-lucide-chevron-down'" class="size-3" />
365
+ </button>
366
+ </span>
367
+ </span>
368
+ </template>
369
+ </UInput>
370
+ </template>
@@ -0,0 +1,32 @@
1
+ <script setup lang="ts">
2
+ import { meter, cx } from "./recipes";
3
+
4
+ const props = withDefaults(defineProps<{
5
+ used: number; quota: number; unit?: string;
6
+ size?: "md" | "lg"; showValue?: boolean;
7
+ /** 0–1; amber from here, red + hatched at 100% */
8
+ warnAt?: number;
9
+ format?: (used: number, quota: number) => string;
10
+ }>(), { unit: "GB", size: "md", showValue: true, warnAt: 0.8 });
11
+
12
+ const ratio = computed(() => (props.quota > 0 ? props.used / props.quota : 0));
13
+ const level = computed<"ok" | "warn" | "over">(() =>
14
+ ratio.value >= 1 ? "over" : ratio.value >= props.warnAt ? "warn" : "ok");
15
+ const pct = computed(() => Math.min(100, Math.round(ratio.value * 100)));
16
+ const label = computed(() => props.format
17
+ ? props.format(props.used, props.quota)
18
+ : `${+props.used.toFixed(props.used < 10 ? 1 : 0)} / ${props.quota} ${props.unit}`);
19
+ </script>
20
+
21
+ <template>
22
+ <span
23
+ :class="cx(meter.base, meter.size[size])"
24
+ role="meter" :aria-valuemin="0" :aria-valuemax="quota" :aria-valuenow="used" :aria-label="label"
25
+ >
26
+ <span :class="cx(meter.track, meter.trackSize[size])">
27
+ <span :class="cx(meter.fill, meter.level[level])" :style="{ width: pct + '%' }" />
28
+ <span v-if="warnAt < 1" :class="meter.mark" :style="{ left: warnAt * 100 + '%' }" />
29
+ </span>
30
+ <span v-if="showValue" :class="cx(meter.value, meter.valueLevel[level])">{{ label }}</span>
31
+ </span>
32
+ </template>
@@ -0,0 +1,256 @@
1
+ <script setup lang="ts" generic="T extends object">
2
+ // A repeating-list editor: rows of the same few fields, with "Add another …" under them and Remove on each. The
3
+ // rows' fields are the caller's, in the #row slot, so it holds any input; this owns adding, removing, folding,
4
+ // per-row errors, focus and announcing the count. Written on Nuxt UI's tokens.
5
+ //
6
+ // <ZRepeatingList v-model="rows" item-label="referral source" :new-row="() => ({ name: '' })" :row-key="(r) => r.id">
7
+ // <template #row="{ row, index, error, errorId }"> …inputs bound to row… </template>
8
+ // <template #summary="{ row }">{{ row.name }}</template> <!-- optional: fold rows to one line -->
9
+ // </ZRepeatingList>
10
+ //
11
+ // Rows are edited in place in #row. With a #summary slot, rows already there when it mounts start folded to that
12
+ // line with an Edit button (new rows, and any row with an error, are open); without one every row is open.
13
+ // `rowKey` keeps a row's identity while it is renamed (rows that carry history); rows it has no key for are told
14
+ // apart by object identity, hence `T extends object`.
15
+ const props = withDefaults(
16
+ defineProps<{
17
+ /** One row, singular and lower case: "referral source". */
18
+ itemLabel: string
19
+ /** A new row's starting values. */
20
+ newRow: () => T
21
+ /** A stable key per row (a saved record's id). Undefined for a new row. */
22
+ rowKey?: (row: T) => string | null | undefined
23
+ /** Rows always on screen: rows are added up to it when it mounts, and Remove hides at it. */
24
+ min?: number
25
+ /** Most rows allowed: Add is disabled at it, and says so. */
26
+ max?: number
27
+ /** Errors by row key (rowKey, or the key the #row slot is given), shown under the row. */
28
+ errors?: Record<string, string>
29
+ /** Whether a row may be removed (default: every row, down to `min`). */
30
+ removable?: (row: T) => boolean
31
+ /** The row's heading, and the name its buttons carry; "Referral source 2" unless given. Hidden in `compact`. */
32
+ rowTitle?: (row: T, index: number) => string
33
+ /** One line per row, no heading or card: for rows of a single short field. */
34
+ compact?: boolean
35
+ /** The Add button's words; "Add a(n) <item>", then "Add another <item>", unless given. */
36
+ addLabel?: string
37
+ /** The Remove button's word; its accessible name is this and the row's title: "Remove Part 3". */
38
+ removeLabel?: string
39
+ /** The folded row's Edit button's word; named the same way. */
40
+ editLabel?: string
41
+ /** Shown beside the disabled Add button at `max`; "That's the most you can add here (12)." unless given. */
42
+ maxLabel?: string
43
+ /** What a screen reader hears when a row is added or removed; "Part 3 added. 3 in the list." unless given. */
44
+ announce?: (change: { type: 'added' | 'removed'; title: string; count: number }) => string
45
+ /** Where focus lands in a row that is added or opened: the first match in the row. */
46
+ focusSelector?: string
47
+ }>(),
48
+ {
49
+ rowKey: undefined,
50
+ min: 0,
51
+ max: undefined,
52
+ errors: undefined,
53
+ removable: undefined,
54
+ rowTitle: undefined,
55
+ compact: false,
56
+ addLabel: undefined,
57
+ removeLabel: 'Remove',
58
+ editLabel: 'Edit',
59
+ maxLabel: undefined,
60
+ announce: undefined,
61
+ focusSelector: 'input, select, textarea, button[role="radio"]',
62
+ },
63
+ )
64
+ const rows = defineModel<T[]>({ required: true })
65
+ const slots = defineSlots<{
66
+ row(props: { row: T; index: number; key: string; error?: string; errorId?: string }): unknown
67
+ summary?(props: { row: T; index: number }): unknown
68
+ }>()
69
+
70
+ const uid = useId()
71
+ // Rows without a rowKey get one of their own, behind this instance's useId() so it cannot match a caller's key.
72
+ const ids = new WeakMap<object, string>()
73
+ let counter = 0
74
+ function keyOf(row: T): string {
75
+ const k = props.rowKey?.(row)
76
+ if (k) return k
77
+ let id = ids.get(row)
78
+ if (!id) ids.set(row, (id = `${uid}:new-${++counter}`))
79
+ return id
80
+ }
81
+
82
+ const capital = (s: string) => s.charAt(0).toUpperCase() + s.slice(1)
83
+ const titleOf = (row: T, i: number) => props.rowTitle?.(row, i) ?? `${capital(props.itemLabel)} ${i + 1}`
84
+ const errorOf = (row: T) => props.errors?.[keyOf(row)]
85
+ // The message's DOM id is numbered per key, never the key itself: a key with a space would read as two ids in
86
+ // aria-describedby.
87
+ const domIds = new Map<string, number>()
88
+ const errorIdOf = (row: T) => {
89
+ if (!errorOf(row)) return undefined
90
+ const k = keyOf(row)
91
+ let n = domIds.get(k)
92
+ if (n === undefined) domIds.set(k, (n = domIds.size + 1))
93
+ return `${uid}-error-${n}`
94
+ }
95
+
96
+ // Folded rows, by key. Only with a #summary to fold them to; a row with an error is always open.
97
+ const folded = ref(new Set<string>())
98
+ const isFolded = (row: T) => !!slots.summary && folded.value.has(keyOf(row)) && !errorOf(row)
99
+ // An error unfolds its row for good: when live validation clears it mid-edit, the row must not fold back and take
100
+ // the focused input with it.
101
+ watch(
102
+ () => props.errors,
103
+ (errs) => {
104
+ if (!errs) return
105
+ const next = new Set(folded.value)
106
+ let changed = false
107
+ for (const k of Object.keys(errs)) if (errs[k] && next.delete(k)) changed = true
108
+ if (changed) folded.value = next
109
+ },
110
+ { deep: true },
111
+ )
112
+
113
+ const root = ref<HTMLElement | null>(null)
114
+ const addButton = ref<{ $el: HTMLElement } | null>(null)
115
+ const atMax = computed(() => props.max !== undefined && rows.value.length >= props.max)
116
+ const canRemove = (row: T) => rows.value.length > props.min && (props.removable?.(row) ?? true)
117
+ const addText = computed(() => props.addLabel ?? `Add ${rows.value.length ? 'another' : /^[aeiou]/i.test(props.itemLabel) ? 'an' : 'a'} ${props.itemLabel}`)
118
+ const maxText = computed(() => props.maxLabel ?? `That's the most you can add here (${props.max}).`)
119
+
120
+ // The polite announcement of a row added or removed. Cleared first and set again in a later task, so the same words
121
+ // twice are heard twice (a microtask apart, the browser can coalesce the two); a newer announcement replaces one
122
+ // still pending.
123
+ const announcement = ref('')
124
+ let announceTimer: ReturnType<typeof setTimeout> | undefined
125
+ function say(type: 'added' | 'removed', title: string, count: number) {
126
+ const text = props.announce?.({ type, title, count }) ?? `${title} ${type}. ${count} in the list.`
127
+ announcement.value = ''
128
+ clearTimeout(announceTimer)
129
+ announceTimer = setTimeout(() => { announcement.value = text }, 100)
130
+ }
131
+ onBeforeUnmount(() => clearTimeout(announceTimer))
132
+
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
+ }
140
+ watch(
141
+ [focusAt, () => rows.value.length, folded],
142
+ () => {
143
+ if (focusAt.value === null) return
144
+ const el = firstInput(focusAt.value)
145
+ if (!el) return
146
+ el.focus()
147
+ focusAt.value = null
148
+ },
149
+ { flush: 'post' },
150
+ )
151
+ function focusRow(i: number) {
152
+ focusAt.value = i
153
+ }
154
+
155
+ function add() {
156
+ if (atMax.value) return
157
+ const i = rows.value.length
158
+ const row = props.newRow()
159
+ rows.value = [...rows.value, row]
160
+ focusRow(i)
161
+ say('added', titleOf(row, i), i + 1)
162
+ }
163
+
164
+ function remove(i: number) {
165
+ const title = titleOf(rows.value[i]!, i)
166
+ const next = rows.value.filter((_, j) => j !== i)
167
+ rows.value = next
168
+ // Counted from `next`: with v-model, rows.value is the old array until the parent hands the new one back.
169
+ say('removed', title, next.length)
170
+ // The Remove button is gone with its row: focus goes to Add rather than falling to the page.
171
+ nextTick(() => addButton.value?.$el?.focus())
172
+ }
173
+
174
+ function edit(row: T, i: number) {
175
+ const next = new Set(folded.value)
176
+ next.delete(keyOf(row))
177
+ folded.value = next
178
+ focusRow(i)
179
+ }
180
+
181
+ /** Back up to `min` rows, whenever there are fewer (on mount, the list was emptied from outside, or `min` rose). */
182
+ function fillToMin() {
183
+ if (rows.value.length < props.min) {
184
+ rows.value = [...rows.value, ...Array.from({ length: props.min - rows.value.length }, () => props.newRow())]
185
+ }
186
+ }
187
+ watch([() => rows.value.length, () => props.min], fillToMin)
188
+
189
+ onMounted(() => {
190
+ if (slots.summary) folded.value = new Set(rows.value.filter((row) => !errorOf(row)).map(keyOf))
191
+ fillToMin()
192
+ })
193
+ </script>
194
+
195
+ <template>
196
+ <div ref="root" class="space-y-3" data-testid="repeating-list">
197
+ <template v-for="(row, i) in rows" :key="keyOf(row)">
198
+ <!-- Folded: one line and an Edit button. -->
199
+ <div
200
+ v-if="isFolded(row)"
201
+ :data-row="i"
202
+ data-folded
203
+ class="flex items-center gap-3 rounded-md border border-default bg-muted px-3 py-2"
204
+ >
205
+ <UIcon name="i-lucide-circle-check" class="size-4 shrink-0 text-success" aria-hidden="true" />
206
+ <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)">
208
+ {{ editLabel }}
209
+ </UButton>
210
+ <UButton
211
+ v-if="canRemove(row)"
212
+ type="button"
213
+ size="xs"
214
+ variant="ghost"
215
+ color="neutral"
216
+ icon="i-lucide-x"
217
+ :aria-label="`${removeLabel} ${titleOf(row, i)}`"
218
+ @click="remove(i)"
219
+ />
220
+ </div>
221
+
222
+ <fieldset
223
+ v-else
224
+ :data-row="i"
225
+ :class="compact ? 'flex items-start gap-2' : 'rounded-md border border-default p-3 sm:p-4'"
226
+ >
227
+ <legend :class="compact ? 'sr-only' : 'px-1 text-sm font-semibold text-highlighted'">{{ titleOf(row, i) }}</legend>
228
+ <div :class="compact ? 'min-w-0 flex-1' : 'space-y-4'">
229
+ <slot name="row" :row="row" :index="i" :key="keyOf(row)" :error="errorOf(row)" :errorId="errorIdOf(row)" />
230
+ <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
+ </div>
232
+ <div v-if="canRemove(row)" :class="compact ? 'pt-1' : 'mt-3 flex justify-end'">
233
+ <UButton
234
+ type="button"
235
+ size="xs"
236
+ variant="ghost"
237
+ color="neutral"
238
+ icon="i-lucide-trash-2"
239
+ :aria-label="`${removeLabel} ${titleOf(row, i)}`"
240
+ @click="remove(i)"
241
+ >
242
+ <span v-if="!compact">{{ removeLabel }}</span>
243
+ </UButton>
244
+ </div>
245
+ </fieldset>
246
+ </template>
247
+
248
+ <div class="flex flex-wrap items-center gap-3">
249
+ <UButton ref="addButton" type="button" variant="outline" color="neutral" icon="i-lucide-plus" :disabled="atMax" data-add @click="add()">
250
+ {{ addText }}
251
+ </UButton>
252
+ <span v-if="atMax" class="text-sm text-muted" data-max>{{ maxText }}</span>
253
+ </div>
254
+ <p class="sr-only" role="status" aria-live="polite" data-announce>{{ announcement }}</p>
255
+ </div>
256
+ </template>