@zooui/nuxt 0.3.1 → 0.4.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.
@@ -0,0 +1,199 @@
1
+ <script setup lang="ts">
2
+ /**
3
+ * A text input with a mask: "(555) 123-4567", "123-45-6789", "AB-1234", or any pattern of `#` digits, `A` letters,
4
+ * `*` either and literals between them, or a list of patterns chosen as it is typed (by the separator typed, else the
5
+ * first that fits). The rules are utils/masked-input.ts, and every one of them is a prop away:
6
+ *
7
+ * <ZMaskedInput v-model="phone" preset="phone" /> US phone, formatted on blur
8
+ * <ZMaskedInput v-model="taxId" preset="tax-id" /> US SSN or EIN, formatted as typed
9
+ * <ZMaskedInput v-model="code" v-model:raw="digits" mask="####-####" />
10
+ *
11
+ * `format-on="input"` (the default without a preset) formats every keystroke, paste and deletion before the browser
12
+ * applies it (`beforeinput`): only characters the mask takes get in, and the caret stays on its character as the
13
+ * literals come and go. `format-on="blur"` takes the text as typed and formats it when the field is left, if it holds a
14
+ * whole value and nothing else; otherwise it is left as typed, so a number written another way goes in as it is. The
15
+ * commit runs in the capture phase of the field's change and blur events, before UInput's own handlers tell a
16
+ * UFormField to validate, so a form's rules read the formatted value. Either way the model is `null` when empty.
17
+ *
18
+ * Everything else (id, size, color, placeholder, disabled, readonly, aria-*, class) falls through to the UInput.
19
+ */
20
+ import {
21
+ commitMasked, editMasked, isMaskComplete, MASK_PRESETS, MASK_TOKENS, masksOf, reformat, unmaskedValue,
22
+ type Masked, type MaskEdit, type MaskSource, type MaskToken,
23
+ } from '../utils/masked-input'
24
+
25
+ defineOptions({ inheritAttrs: false })
26
+
27
+ const props = defineProps<{
28
+ modelValue?: string | null
29
+ /** The value without its literals ("5551234567"), for `v-model:raw`. Set from outside, it is formatted by the mask. */
30
+ raw?: string | null
31
+ /** A pattern or a list of them; a preset's when unset. */
32
+ mask?: MaskSource
33
+ /** Tokens the patterns use, added to `#`, `A` and `*`; one for the same character replaces it. */
34
+ tokens?: Record<string, MaskToken>
35
+ /** `phone` (US, on blur) or `tax-id` (US SSN or EIN, as typed): a mask, a `format-on` and the input's attributes. */
36
+ preset?: keyof typeof MASK_PRESETS
37
+ /** When the mask is written: as typed, or on blur. A preset's when unset, else `input`. */
38
+ formatOn?: 'input' | 'blur'
39
+ }>()
40
+ const emit = defineEmits<{
41
+ 'update:modelValue': [value: string | null]
42
+ 'update:raw': [value: string | null]
43
+ }>()
44
+ const attrs = useAttrs()
45
+
46
+ const preset = computed(() => (props.preset ? MASK_PRESETS[props.preset] : undefined))
47
+ const masks = computed(() => masksOf(props.mask ?? preset.value?.mask ?? [], props.tokens ? { ...MASK_TOKENS, ...props.tokens } : undefined))
48
+ const formatOn = computed(() => props.formatOn ?? preset.value?.formatOn ?? 'input')
49
+ const live = computed(() => formatOn.value === 'input' && masks.value.length > 0)
50
+ // a mask of digits alone brings up a number pad
51
+ const digitsOnly = computed(() => masks.value.length > 0 && masks.value.every((m) => m.slots.every((s) => !('token' in s) || s.token === MASK_TOKENS['#'])))
52
+ const inputAttrs = computed(() => ({ ...(digitsOnly.value ? { inputmode: 'numeric' } : {}), ...preset.value?.attrs, ...attrs }))
53
+
54
+ const field = useTemplateRef<{ inputRef: HTMLInputElement | null }>('field')
55
+ const input = () => field.value?.inputRef ?? null
56
+
57
+ /** The text for a value from outside: formatted as typed (live), as it is on blur. */
58
+ function shown(v: string | null | undefined): Masked | null {
59
+ if (!v) return null
60
+ return live.value ? reformat(v, v.length, masks.value) : null
61
+ }
62
+ function initial(): string {
63
+ if (props.modelValue) return shown(props.modelValue)?.text ?? props.modelValue
64
+ if (props.raw) return reformat(props.raw, props.raw.length, masks.value).text
65
+ return ''
66
+ }
67
+ const text = ref(initial())
68
+ /** The mask a separator chose ("12-" → the EIN), held until the field is empty. */
69
+ let chosen: number | null = live.value ? reformat(text.value, text.value.length, masks.value).chosen : null
70
+
71
+ const modelOf = (t: string) => t || null
72
+ const rawOf = (t: string) => unmaskedValue(t, masks.value) || null
73
+ const unmasked = computed(() => rawOf(text.value))
74
+ /** The value is whole: every character its mask holds, written in it (on blur: as the commit will write it). */
75
+ const complete = computed(() => isMaskComplete(formatOn.value === 'blur' ? commitMasked(text.value, masks.value) : text.value, masks.value))
76
+
77
+ function hand(t: string) {
78
+ if (modelOf(t) !== (props.modelValue ?? null)) emit('update:modelValue', modelOf(t))
79
+ if (rawOf(t) !== (props.raw ?? null)) emit('update:raw', rawOf(t))
80
+ }
81
+
82
+ /** Show a text, with the caret where it goes (the end, for a whole new value). */
83
+ function put(next: { text: string, caret: number } | string) {
84
+ const f = typeof next === 'string' ? { text: next, caret: next.length } : next
85
+ text.value = f.text
86
+ const el = input()
87
+ if (!el) return
88
+ if (el.value !== f.text) el.value = f.text
89
+ if (el === document.activeElement) el.setSelectionRange(f.caret, f.caret)
90
+ }
91
+
92
+ // A value from outside (not this field's own, coming back) is shown, the mask it is written in held, and the raw
93
+ // value kept in step with it.
94
+ watch(() => props.modelValue, (v) => {
95
+ if ((v ?? null) === modelOf(text.value)) return
96
+ const r = shown(v)
97
+ chosen = r?.chosen ?? null
98
+ put(r?.text ?? v ?? '')
99
+ if (unmasked.value !== (props.raw ?? null)) emit('update:raw', unmasked.value)
100
+ })
101
+ watch(() => props.raw, (v) => {
102
+ if ((v ?? null) === unmasked.value) return
103
+ const r = v ? reformat(v, v.length, masks.value) : null
104
+ chosen = r?.chosen ?? null
105
+ put(r?.text ?? '')
106
+ hand(text.value)
107
+ })
108
+ // New masks reformat the text, but only when they really change: an inline `mask` or `tokens` is a new array or object
109
+ // on every render of the parent, and each keystroke re-renders it. The caret stays where it is.
110
+ const maskKey = computed(() => JSON.stringify(masks.value.map((m) => m.slots.map((s) => ('literal' in s ? s.literal : [s.token.pattern.source, s.token.pattern.flags, String(s.token.transform ?? '')])))))
111
+ watch(maskKey, () => {
112
+ if (!live.value) return
113
+ const el = input()
114
+ const r = reformat(text.value, el && el === document.activeElement ? el.selectionStart ?? text.value.length : text.value.length, masks.value)
115
+ chosen = r.chosen
116
+ if (r.text === text.value) return
117
+ put(r)
118
+ hand(r.text)
119
+ })
120
+
121
+ // Typing. Each keystroke, paste or deletion is worked out in masked-input.ts before the browser applies it; whatever
122
+ // gets past that (an IME, undo, autofill, a cut) is tidied when UInput hands the text on.
123
+ const EDITS: Record<string, 'insert' | 'backward' | 'forward'> = {
124
+ insertText: 'insert', insertFromPaste: 'insert', insertFromDrop: 'insert', insertReplacementText: 'insert',
125
+ deleteContentBackward: 'backward', deleteContentForward: 'forward',
126
+ }
127
+ function onBeforeinput(e: InputEvent) {
128
+ const op = EDITS[e.inputType]
129
+ if (!live.value || e.isComposing || !op) return
130
+ const el = e.target as HTMLInputElement
131
+ const data = op === 'insert' ? e.data ?? e.dataTransfer?.getData('text/plain') : ''
132
+ if (data === undefined || data === null) return
133
+ e.preventDefault()
134
+ const sel = { text: el.value, start: el.selectionStart ?? el.value.length, end: el.selectionEnd ?? el.value.length }
135
+ const change: MaskEdit = op === 'insert' ? { insert: data } : { delete: op }
136
+ const next = editMasked(sel, change, masks.value, chosen)
137
+ if (!next) return // refused: nothing changes, the selection included
138
+ chosen = next.chosen
139
+ if (next.text === el.value) return el.setSelectionRange(next.caret, next.caret)
140
+ el.value = next.text
141
+ el.setSelectionRange(next.caret, next.caret)
142
+ el.dispatchEvent(new Event('input', { bubbles: true }))
143
+ }
144
+
145
+ let composing = false
146
+ // UInput hands the text on from its input event, then tells a UFormField: the model is set in between.
147
+ function onUpdate() {
148
+ const el = input()
149
+ if (!el) return
150
+ if (!live.value || composing) {
151
+ text.value = el.value
152
+ return hand(el.value)
153
+ }
154
+ const r = reformat(el.value, el.selectionStart ?? el.value.length, masks.value, chosen)
155
+ chosen = r.chosen
156
+ put(r)
157
+ hand(r.text)
158
+ }
159
+ function onCompositionend() {
160
+ composing = false
161
+ onUpdate()
162
+ }
163
+
164
+ /** Write the mask now, as leaving the field does: a whole value formatted, anything else left as typed. */
165
+ function commit() {
166
+ const el = input()
167
+ const current = el?.value ?? text.value
168
+ const next = masks.value.length ? commitMasked(current, masks.value) : current
169
+ if (next === current) return
170
+ chosen = live.value ? reformat(next, next.length, masks.value).chosen : null
171
+ put(next)
172
+ hand(next)
173
+ }
174
+ // In the capture phase, on the way down to the input: before UInput's own change and blur handlers ask a UFormField
175
+ // to validate (a changed field's change event comes just before its blur).
176
+ function onLeaveCapture(e: Event) {
177
+ const el = e.target as HTMLInputElement | null
178
+ if (el?.tagName !== 'INPUT' || el !== input() || el.readOnly || el.disabled) return
179
+ commit()
180
+ }
181
+
182
+ defineExpose({ complete, isValid: complete, raw: unmasked, commit, inputRef: computed(input) })
183
+ </script>
184
+
185
+ <template>
186
+ <div class="contents" @change.capture="onLeaveCapture" @blur.capture="onLeaveCapture">
187
+ <UInput
188
+ ref="field"
189
+ :model-value="text"
190
+ v-bind="inputAttrs"
191
+ data-masked-input
192
+ :data-complete="complete ? '' : undefined"
193
+ @update:model-value="onUpdate"
194
+ @beforeinput="onBeforeinput"
195
+ @compositionstart="composing = true"
196
+ @compositionend="onCompositionend"
197
+ />
198
+ </div>
199
+ </template>
@@ -0,0 +1,183 @@
1
+ <script setup lang="ts" generic="T extends Temporal.PlainYearMonth | CalendarDateLike | null">
2
+ // A month-of-a-year field: type a month, press a shortcut key, or pick from a calendar of months. ZDateField for a
3
+ // month — the same box, the same commit on Enter, Tab and blur, the same invalid mark, `dateUpdate` and clear button
4
+ // (the field under both is internal/EntryField.vue) — with month-entry.ts doing the reading and writing.
5
+ //
6
+ // <ZMonthField v-model="form.period" clearable />
7
+ // <ZMonthField v-model="period" format="YYYY-MM" :min-value="opened" :max-value="closes" />
8
+ //
9
+ // THE CALLER'S TYPE, as ZDateField keeps it: a Temporal.PlainYearMonth (the default) or an @internationalized/date
10
+ // CalendarDate (what Nuxt UI's UCalendar holds for a month), read as the month it falls in and handed back as the first
11
+ // of it; `modelType` names the type for a model that starts out null. No JavaScript Date is made.
12
+ //
13
+ // FORMAT AND LOCALE. `format` is "MM/YYYY", "MM.YYYY", "YYYY-MM" …; unset, it is the locale's date order without the
14
+ // day (monthEntryFormatFor: `en` MM/YYYY, `de` MM.YYYY, `sv` YYYY-MM).
15
+ //
16
+ // Typing (in MM/YYYY): "5/26", "05/2026", "052026" and ISO's "2026-05" are May 2026; "5" or "12" is that month this
17
+ // year; "2026" alone is December 2026. Shortcut keys: t this month, y/r the year before or after, m/h the month before
18
+ // or after, - and + (or _ and =) a month either way; the format's separator always types. They step from the committed
19
+ // month (this month when there is none) and stop at `minValue` and `maxValue`. A typed month outside them is refused,
20
+ // as ZDateField refuses a day.
21
+ import { CalendarDate } from '@internationalized/date'
22
+ import { useLocale } from '@nuxt/ui/composables'
23
+ import type { Temporal } from 'temporal-polyfill/implementation'
24
+ import EntryField from './internal/EntryField.vue'
25
+ import type { EntryEngine, EntryProblem, InputSlotUi } from './internal/entry-field'
26
+ import type { CalendarDateLike } from '../utils/date-entry'
27
+ import {
28
+ applyMonthShortcut, checkMonthLimits, commitMonthEntry, formatMonthEntry, fromPlainYearMonth, isMonthShortcut, monthEntryFormat,
29
+ monthEntryFormatFor, monthLimitMessage, monthModelTypeOf, parseMonthEntry, toPlainYearMonth,
30
+ type MonthLimitProblem, type MonthLimits, type MonthModelType,
31
+ } from '../utils/month-entry'
32
+
33
+ defineOptions({ inheritAttrs: false })
34
+
35
+ type Month = NonNullable<T>
36
+
37
+ const props = withDefaults(
38
+ defineProps<{
39
+ clearable?: boolean
40
+ disabled?: boolean
41
+ /** The pattern the box writes and reads: "MM/YYYY", "MM.YYYY", "YYYY-MM" … Unset: the locale's own. */
42
+ format?: string
43
+ /** The calendar's locale (BCP 47), and the format's when `format` is unset. Unset: Nuxt UI's locale. */
44
+ locale?: string
45
+ /** Unset: the format's pattern, "MM/YYYY". */
46
+ placeholder?: string
47
+ size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl'
48
+ /** A leading icon; a click on it emits `iconClick`. */
49
+ icon?: string
50
+ /** The calendar button's icon. */
51
+ calendarIcon?: string
52
+ highlight?: boolean
53
+ ui?: { root?: string, base?: string, trailing?: string, leading?: string, leadingIcon?: string }
54
+ portal?: boolean | string
55
+ /** The two buttons' accessible names, for a product in another language. */
56
+ clearLabel?: string
57
+ chooseLabel?: string
58
+ /** The type to hand back while the model is null and has held no month. */
59
+ modelType?: MonthModelType
60
+ /** The first month the field takes, a PlainYearMonth or a CalendarDate (its month). */
61
+ minValue?: Temporal.PlainYearMonth | CalendarDateLike
62
+ /** The last month the field takes, a PlainYearMonth or a CalendarDate (its month). */
63
+ maxValue?: Temporal.PlainYearMonth | CalendarDateLike
64
+ }>(),
65
+ { portal: true, calendarIcon: 'i-lucide-calendar', clearLabel: 'Clear month', chooseLabel: 'Choose a month', modelType: 'plain-year-month' },
66
+ )
67
+ const emit = defineEmits<{
68
+ dateUpdate: [value: T | null]
69
+ // A typed month refused by the limits, and null once the field is no longer marked invalid.
70
+ invalid: [problem: (MonthLimitProblem<Month> & { message: string }) | null]
71
+ clear: []
72
+ iconClick: [event: MouseEvent]
73
+ }>()
74
+ const model = defineModel<T | null>({ default: null })
75
+ defineSlots<{
76
+ /** UInput's leading slot, in place of the `icon` when given; `ui` is the input's, for its `leadingIcon` class. */
77
+ leading?(props: { ui: InputSlotUi }): unknown
78
+ }>()
79
+
80
+ const { locale: uiLocale } = useLocale()
81
+ const localeCode = computed(() => props.locale ?? uiLocale.value.code)
82
+ const entryFormat = computed(() => (props.format ? monthEntryFormat(props.format) : monthEntryFormatFor(localeCode.value)))
83
+
84
+ // The caller's type, kept through an empty spell, and the CalendarDate it last held (whose class builds the next).
85
+ let remembered: MonthModelType | undefined
86
+ let like: CalendarDateLike | undefined
87
+ function remember(v: unknown) {
88
+ const type = monthModelTypeOf(v)
89
+ if (type) remembered = type
90
+ if (type === 'calendar-date') like = v as CalendarDateLike
91
+ }
92
+ remember(model.value)
93
+ watch(model, remember)
94
+ const kind = () => monthModelTypeOf(model.value) ?? remembered ?? props.modelType
95
+ const out = (m: Temporal.PlainYearMonth | null) => fromPlainYearMonth(m, kind(), like) as T | null
96
+ const outMonth = (m: Temporal.PlainYearMonth) => fromPlainYearMonth(m, kind(), like) as Month
97
+
98
+ const month = computed(() => toPlainYearMonth(model.value))
99
+ const sameMonth = (a: Temporal.PlainYearMonth | null, b: Temporal.PlainYearMonth | null) => a === b || (!!a && !!b && a.equals(b))
100
+
101
+ const limits = computed<MonthLimits>(() => ({ minValue: toPlainYearMonth(props.minValue), maxValue: toPlainYearMonth(props.maxValue) }))
102
+
103
+ const engine = computed<EntryEngine<Temporal.PlainYearMonth>>(() => {
104
+ const format = entryFormat.value
105
+ const within = limits.value
106
+ return {
107
+ pattern: format.pattern,
108
+ show: (m) => formatMonthEntry(m, format),
109
+ parse: (text, today) => parseMonthEntry(text, today, format),
110
+ commit: (text, current, today) => commitMonthEntry(text, current, today, format),
111
+ same: sameMonth,
112
+ check: (m) => checkMonthLimits(m, within),
113
+ message: (p) => monthLimitMessage(p as MonthLimitProblem, format),
114
+ isShortcut: (key) => isMonthShortcut(key, format),
115
+ shortcut: (key, current, today) => applyMonthShortcut(key, current, today, format, within),
116
+ today: (today) => today.toPlainYearMonth(),
117
+ }
118
+ })
119
+
120
+ // The field's problem is the engine's, which is MonthLimitProblem's.
121
+ function onInvalid(problem: (EntryProblem<Temporal.PlainYearMonth> & { message: string }) | null) {
122
+ const p = problem as (MonthLimitProblem & { message: string }) | null
123
+ emit('invalid', p && { reason: p.reason, date: outMonth(p.date), limit: outMonth(p.limit), message: p.message })
124
+ }
125
+
126
+ const fieldCmp = useTemplateRef<{ focus: () => void }>('fieldCmp')
127
+
128
+ // ── Calendar ──────────────────────────────────────────────────────────────────────────────────────────────
129
+ // UCalendar's month grid holds a CalendarDate: the first of the month, both ways. It disables a month whose first day
130
+ // is after `max-value` or whose last day is before `min-value`, so the first of each limit's month is exact.
131
+ const toCalendar = (m: Temporal.PlainYearMonth) => new CalendarDate(m.year, m.month, 1)
132
+ const calendarMin = computed(() => (limits.value.minValue ? toCalendar(limits.value.minValue as Temporal.PlainYearMonth) : undefined))
133
+ const calendarMax = computed(() => (limits.value.maxValue ? toCalendar(limits.value.maxValue as Temporal.PlainYearMonth) : undefined))
134
+
135
+ function onPick(v: unknown, pick: (m: Temporal.PlainYearMonth) => void) {
136
+ if (monthModelTypeOf(v) === 'calendar-date') pick(toPlainYearMonth(v as CalendarDateLike)!)
137
+ }
138
+
139
+ defineExpose({ focus: () => fieldCmp.value?.focus() })
140
+ </script>
141
+
142
+ <template>
143
+ <EntryField
144
+ ref="fieldCmp"
145
+ v-bind="$attrs"
146
+ :model-value="month"
147
+ :engine="engine"
148
+ :clearable="clearable"
149
+ :disabled="disabled"
150
+ :placeholder="placeholder"
151
+ :size="size"
152
+ :icon="icon"
153
+ :calendar-icon="calendarIcon"
154
+ :highlight="highlight"
155
+ :ui="ui"
156
+ :portal="portal"
157
+ :clear-label="clearLabel"
158
+ :choose-label="chooseLabel"
159
+ @update:model-value="(m) => (model = out(m))"
160
+ @date-update="(m) => emit('dateUpdate', out(m))"
161
+ @invalid="onInvalid"
162
+ @clear="emit('clear')"
163
+ @icon-click="emit('iconClick', $event)"
164
+ >
165
+ <template v-if="$slots.leading" #leading="slotProps">
166
+ <slot name="leading" v-bind="slotProps" />
167
+ </template>
168
+ <template #calendar="{ value, view, pick }">
169
+ <UCalendar
170
+ type="month"
171
+ :model-value="value ? toCalendar(value) : undefined"
172
+ :placeholder="toCalendar(view)"
173
+ :locale="localeCode"
174
+ :size="size"
175
+ :min-value="calendarMin"
176
+ :max-value="calendarMax"
177
+ prevent-deselect
178
+ class="p-2"
179
+ @update:model-value="(v) => onPick(v, pick)"
180
+ />
181
+ </template>
182
+ </EntryField>
183
+ </template>
@@ -76,7 +76,7 @@ const ownId = useId()
76
76
  // Inside a UFormField the date input takes the field's id (so its label names it); outside, one of ours.
77
77
  const inputId = computed(() => (formField?.value ? formInputId?.value : undefined) ?? ownId)
78
78
  const fieldGroup = inject(fieldGroupInjectionKey, undefined)
79
- const size = computed<Size>(() => props.size ?? fieldGroup?.value?.size ?? (formField?.value?.size as Size | undefined) ?? 'md')
79
+ const size = computed<Size>(() => props.size ?? (fieldGroup?.value?.size as Size | undefined) ?? (formField?.value?.size as Size | undefined) ?? 'md')
80
80
 
81
81
  // The checkbox outside the form field: no shared id, no field error color, no form events on its own.
82
82
  const OutsideFormField = defineComponent({
@@ -185,8 +185,8 @@ const canRemove = computed(() => !!selectedItem.value && (props.removable?.(sele
185
185
  const announcement = ref('')
186
186
  let announceTimer: ReturnType<typeof setTimeout> | undefined
187
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.`)
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
190
  announcement.value = ''
191
191
  clearTimeout(announceTimer)
192
192
  announceTimer = setTimeout(() => { announcement.value = text }, 100)
@@ -307,7 +307,7 @@ onMounted(() => {
307
307
  >
308
308
  <legend :class="compact ? 'sr-only' : 'px-1 text-sm font-semibold text-highlighted'">{{ titleOf(row, i) }}</legend>
309
309
  <div :class="compact ? 'min-w-0 flex-1' : 'space-y-4'">
310
- <slot name="row" :row="row" :index="i" :key="keyOf(row)" :error="errorOf(row)" :errorId="errorIdOf(row)" />
310
+ <slot :key="keyOf(row)" name="row" :row="row" :index="i" :error="errorOf(row)" :error-id="errorIdOf(row)" />
311
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>
312
312
  </div>
313
313
  <div
@@ -0,0 +1,135 @@
1
+ <script setup lang="ts">
2
+ /**
3
+ * A search (filter) box for a list or a table toolbar: a UInput with a search icon at the start and a clear button at
4
+ * the end while it holds text. What is typed is handed back once typing pauses for `debounce` ms (300 by default), as
5
+ * `update:modelValue` and `filter` together, so a list is filtered once per pause rather than once per key. Clearing,
6
+ * by the button or by Escape, hands back '' at once and keeps focus in the field; an Escape with nothing to clear is
7
+ * left alone, so it still closes the dialog the field sits in.
8
+ *
9
+ * Everything else (id, name, size, color, variant, disabled, readonly, aria-*, class) falls through to the UInput;
10
+ * `ui` is merged over the field's own classes.
11
+ */
12
+ const props = withDefaults(defineProps<{
13
+ modelValue?: string | null
14
+ /** Milliseconds of quiet before what is typed is handed back. */
15
+ debounce?: number
16
+ placeholder?: string
17
+ icon?: string
18
+ clearIcon?: string
19
+ /** The clear button's accessible name. */
20
+ clearLabel?: string
21
+ ui?: Record<string, string>
22
+ }>(), {
23
+ modelValue: undefined,
24
+ debounce: 300,
25
+ placeholder: 'Filter…',
26
+ icon: 'i-lucide-search',
27
+ clearIcon: 'i-lucide-x',
28
+ clearLabel: 'Clear',
29
+ })
30
+ const emit = defineEmits<{
31
+ 'update:modelValue': [value: string]
32
+ 'filter': [value: string]
33
+ }>()
34
+
35
+ /** What the field shows, ahead of the model while a pause is pending. */
36
+ const text = ref(props.modelValue ?? '')
37
+ /** The value last handed back or given by the parent: a pause that ends on it hands nothing back. */
38
+ let settled = text.value
39
+ let timer: ReturnType<typeof setTimeout> | undefined
40
+
41
+ function cancel() {
42
+ clearTimeout(timer)
43
+ timer = undefined
44
+ }
45
+
46
+ function flush() {
47
+ cancel()
48
+ if (text.value === settled) return
49
+ settled = text.value
50
+ emit('update:modelValue', settled)
51
+ emit('filter', settled)
52
+ }
53
+
54
+ function onUpdate(value: string | number | null | undefined) {
55
+ text.value = String(value ?? '')
56
+ cancel()
57
+ timer = setTimeout(flush, props.debounce)
58
+ }
59
+
60
+ // The parent setting the model shows it, and drops a pause still pending: the parent's value wins.
61
+ watch(() => props.modelValue, (v) => {
62
+ const next = v ?? ''
63
+ if (next === settled && next === text.value) return
64
+ cancel()
65
+ text.value = settled = next
66
+ })
67
+
68
+ onBeforeUnmount(cancel)
69
+
70
+ const field = useTemplateRef<{ inputRef: HTMLInputElement | null }>('field')
71
+ const inputRef = computed(() => field.value?.inputRef ?? null)
72
+
73
+ function focus() {
74
+ inputRef.value?.focus()
75
+ }
76
+
77
+ /** Empty the field and hand back '' now, with no pause. */
78
+ function clear() {
79
+ text.value = ''
80
+ flush()
81
+ }
82
+
83
+ function onClearClick() {
84
+ clear()
85
+ focus()
86
+ }
87
+
88
+ function onKeydown(e: KeyboardEvent) {
89
+ if (e.key !== 'Escape' || e.isComposing) return
90
+ if (text.value === '' && settled === '') return
91
+ e.preventDefault()
92
+ e.stopPropagation()
93
+ clear()
94
+ }
95
+
96
+ // The clear button hides while the input is disabled or read-only, however it got so (a UFormField included).
97
+ const inputUi = computed(() => ({
98
+ ...props.ui,
99
+ base: ['peer', props.ui?.base].filter(Boolean).join(' '),
100
+ trailing: ['pe-1.5 peer-disabled:hidden peer-read-only:hidden', props.ui?.trailing].filter(Boolean).join(' '),
101
+ }))
102
+
103
+ defineExpose({ focus, clear, inputRef })
104
+ </script>
105
+
106
+ <template>
107
+ <UInput
108
+ ref="field"
109
+ :model-value="text"
110
+ type="text"
111
+ role="searchbox"
112
+ autocomplete="off"
113
+ :icon="icon"
114
+ :placeholder="placeholder"
115
+ :ui="inputUi"
116
+ data-search-input
117
+ @update:model-value="onUpdate"
118
+ @keydown="onKeydown"
119
+ >
120
+ <template #trailing="{ ui: slotUi }">
121
+ <button
122
+ v-if="text"
123
+ type="button"
124
+ tabindex="-1"
125
+ class="grid place-items-center rounded-sm p-1 text-dimmed hover:text-default"
126
+ :aria-label="clearLabel"
127
+ data-search-clear
128
+ @mousedown.prevent
129
+ @click="onClearClick"
130
+ >
131
+ <UIcon :name="clearIcon" :class="slotUi.trailingIcon({ class: 'text-current' })" />
132
+ </button>
133
+ </template>
134
+ </UInput>
135
+ </template>
@@ -1,24 +1,37 @@
1
1
  <script setup lang="ts">
2
+ /**
3
+ * A status: a mark and a label. The five built-ins (healthy, warn, suspended, unreachable, quiet) are drawn by shape.
4
+ * A product's own statuses come from app.config `zooui.status.states` and the `states` prop (key → label, icon,
5
+ * color), merged over the built-ins field by field (useStatusStates); each draws its icon, or a dot, in its color.
6
+ * A key the map lacks falls back to `zooui.status.fallback`, then "Unknown" with a help icon.
7
+ */
8
+ import type { StatusKey } from '../composables/useStatusStates'
9
+ import type { StatusStateMap } from '../utils/status-states'
2
10
  import { status, cx } from "./recipes";
3
11
 
4
- const LABELS = {
5
- healthy: "Healthy", warn: "Near limit", suspended: "Suspended",
6
- unreachable: "Unreachable", quiet: "Quiet",
7
- } as const;
8
-
9
12
  const props = withDefaults(defineProps<{
10
- state?: keyof typeof LABELS;
13
+ state?: StatusKey | (string & {});
14
+ /** Statuses for this one, over app.config's and the built-ins. */
15
+ states?: StatusStateMap;
11
16
  pill?: boolean;
12
17
  /** A soft glow around the healthy dot. Other states stay unlit. */
13
18
  glow?: boolean;
14
19
  }>(), { state: "healthy", pill: false, glow: false });
20
+
21
+ const { info } = useStatusStates(() => props.states);
22
+ const entry = computed(() => info(props.state));
15
23
  </script>
16
24
 
17
25
  <template>
18
26
  <!-- Shape carries the state; color only reinforces it, so this survives
19
27
  grayscale. Always render the glyph child. -->
20
- <span :class="cx(status.base, status.state[state], pill ? cx(status.pill, status.size.pill) : status.size.plain)">
21
- <span :class="cx(status.glyph, status.shape[state], glow && state === 'healthy' && status.glow)" aria-hidden="true" />
22
- <slot>{{ LABELS[props.state] }}</slot>
28
+ <span
29
+ :class="cx(status.base, entry.shape ? status.state[entry.shape] : status.custom, pill ? cx(status.pill, status.size.pill) : status.size.plain)"
30
+ :data-state-known="entry.known ? undefined : 'false'"
31
+ >
32
+ <span v-if="entry.shape" :class="cx(status.glyph, status.shape[entry.shape], glow && entry.shape === 'healthy' && status.glow)" aria-hidden="true" />
33
+ <UIcon v-else-if="entry.icon" :name="entry.icon" :class="cx(status.icon, status.ink[entry.color])" aria-hidden="true" />
34
+ <span v-else :class="cx(status.glyph, status.dot, status.fill[entry.color])" aria-hidden="true" />
35
+ <slot>{{ entry.label }}</slot>
23
36
  </span>
24
37
  </template>