@zooui/nuxt 0.2.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -1
- package/components/ConfirmButton.vue +124 -0
- package/components/ConfirmDialog.vue +201 -0
- package/components/DateField.vue +16 -8
- package/components/FileDropOverlay.vue +275 -0
- package/components/FileList.vue +155 -0
- package/components/FilterSelect.vue +340 -0
- package/components/OptionalDate.vue +180 -0
- package/components/OrderList.vue +495 -0
- package/components/RepeatingList.vue +133 -21
- package/components/SelectMenu.vue +325 -0
- package/components/confirm.ts +163 -0
- package/components/row-snapshot.ts +48 -0
- package/components/select-typeahead.ts +79 -0
- package/composables/useConfirm.ts +68 -0
- package/nuxt.config.ts +5 -1
- package/package.json +2 -1
- package/utils/confirm-queue.ts +85 -0
- package/utils/date-entry.ts +9 -2
- package/utils/file-drop.ts +151 -0
- package/utils/filter-match.ts +62 -0
- package/utils/order-list.ts +42 -0
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
<script setup lang="ts" generic="T extends object, VK extends (keyof T & string) | undefined = undefined">
|
|
2
|
+
// A faceted filter for a list or table toolbar: a button naming the filter, with a chip per chosen value (up to
|
|
3
|
+
// `maxShown`, then one chip saying how many), that opens a searchable list of options to check, each with an
|
|
4
|
+
// optional count of the records it matches and an optional icon, and All and Clear under them.
|
|
5
|
+
//
|
|
6
|
+
// <ZFilterSelect v-model="statuses" label="Status" :options="statusOptions" value-key="value" />
|
|
7
|
+
// <ZFilterSelect v-model="owners" label="Owner" :options="people" value-key="id" label-key="name" count-key="open" />
|
|
8
|
+
//
|
|
9
|
+
// The list is Nuxt UI's UListbox (reka-ui's Listbox: role="listbox", aria-multiselectable, an aria-activedescendant
|
|
10
|
+
// search box) in a UPopover. v-model is an array of values: each option's `valueKey` field, or the option itself
|
|
11
|
+
// without one (then compared by identity). Values the options no longer hold are kept, not dropped.
|
|
12
|
+
//
|
|
13
|
+
// SEARCH is literal and case-insensitive (utils/filter-match.ts): what is typed is text, never a pattern, so `(` or
|
|
14
|
+
// `.` match themselves. The options keep their order, and each label is drawn as segments with the matches in <mark>,
|
|
15
|
+
// never through v-html. Checking or unchecking an option clears the search, so the next pick
|
|
16
|
+
// starts from the whole list. All checks every option on screen (the matches, while searching) and leaves the search
|
|
17
|
+
// as it is; Clear empties the filter.
|
|
18
|
+
//
|
|
19
|
+
// KEYBOARD. Focus opens in the search box. The arrow keys, Home and End move through the options; Enter checks one.
|
|
20
|
+
// Space checks one too, from the search box, while the box is empty or once the arrows have moved since the last
|
|
21
|
+
// character typed; otherwise it is a space in the search. Escape closes the panel, and focus goes back to the
|
|
22
|
+
// button. Without `searchable`, focus opens in the list itself and Space is reka-ui's own. Each change is
|
|
23
|
+
// announced politely ("Status: 2 selected."), and the button's name carries the chips ("Status, Open, Blocked" or
|
|
24
|
+
// "Status, 3 selected").
|
|
25
|
+
//
|
|
26
|
+
// `ui` takes classes for the parts, as Nuxt UI's components do, merged over the defaults with tailwind-merge (the
|
|
27
|
+
// same merge Nuxt UI's own `ui` goes through), so an override replaces the default it conflicts with rather than
|
|
28
|
+
// sitting beside it. A root `class` lands on the wrapper.
|
|
29
|
+
import type { ListboxItem } from '@nuxt/ui'
|
|
30
|
+
import { useLocale } from '@nuxt/ui/composables'
|
|
31
|
+
import { twMerge } from 'tailwind-merge'
|
|
32
|
+
import { filterSelectMatches, filterSelectSegments } from '../utils/filter-match'
|
|
33
|
+
|
|
34
|
+
type Value = VK extends keyof T ? T[VK] : T
|
|
35
|
+
type Part = 'trigger' | 'badge' | 'content' | 'search' | 'list' | 'item' | 'itemIcon' | 'itemLabel' | 'itemCount' | 'footer'
|
|
36
|
+
|
|
37
|
+
defineOptions({ inheritAttrs: false })
|
|
38
|
+
|
|
39
|
+
const props = withDefaults(
|
|
40
|
+
defineProps<{
|
|
41
|
+
/** The filter's name: the button's text, and the list's accessible name. "Status". */
|
|
42
|
+
label: string
|
|
43
|
+
/** The options, in the order they are listed. */
|
|
44
|
+
options: T[]
|
|
45
|
+
/** The option field that is its value in v-model. Unset: the option itself. */
|
|
46
|
+
valueKey?: VK
|
|
47
|
+
/** The option field shown as its label. Unset: `label`. */
|
|
48
|
+
labelKey?: keyof T & string
|
|
49
|
+
/** The option field holding how many records it matches, shown beside it. Unset: `count`. */
|
|
50
|
+
countKey?: keyof T & string
|
|
51
|
+
/** The option field holding its icon. Unset: `icon`. A product's own icons are the product's to bundle. */
|
|
52
|
+
iconKey?: keyof T & string
|
|
53
|
+
/** The option field holding classes for its icon ("text-success"). Unset: `iconClass`. Without any, `text-dimmed`. */
|
|
54
|
+
iconClassKey?: keyof T & string
|
|
55
|
+
/** How many chosen values the button names, a chip each, before it shows one "N selected" chip. 0: always a count. */
|
|
56
|
+
maxShown?: number
|
|
57
|
+
/** Whether the panel has an All button. Without it, the footer shows only while something is chosen. */
|
|
58
|
+
showSelectAll?: boolean
|
|
59
|
+
/** Classes for the parts, merged over the defaults. */
|
|
60
|
+
ui?: Partial<Record<Part, string>>
|
|
61
|
+
/** The button's leading icon; '' for none. */
|
|
62
|
+
icon?: string
|
|
63
|
+
/** Whether the panel has a search box. */
|
|
64
|
+
searchable?: boolean
|
|
65
|
+
/** Unset: "Search". The search box is named "Search <label>" for assistive tech. */
|
|
66
|
+
searchPlaceholder?: string
|
|
67
|
+
/** The button's size, as UButton's. */
|
|
68
|
+
size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl'
|
|
69
|
+
disabled?: boolean
|
|
70
|
+
/** UPopover's `portal`. */
|
|
71
|
+
portal?: boolean | string
|
|
72
|
+
allLabel?: string
|
|
73
|
+
clearLabel?: string
|
|
74
|
+
/** Shown when nothing matches the search. Unset: "No matches". */
|
|
75
|
+
emptyLabel?: string
|
|
76
|
+
/** The count chip's words, also read in the button's name; "3 selected" unless given. */
|
|
77
|
+
selectedLabel?: (count: number) => string
|
|
78
|
+
/** What a screen reader hears when the selection changes; "Status: 2 selected." unless given. */
|
|
79
|
+
announce?: (change: { label: string; count: number }) => string
|
|
80
|
+
}>(),
|
|
81
|
+
{
|
|
82
|
+
valueKey: undefined,
|
|
83
|
+
labelKey: undefined,
|
|
84
|
+
countKey: undefined,
|
|
85
|
+
iconKey: undefined,
|
|
86
|
+
iconClassKey: undefined,
|
|
87
|
+
maxShown: 2,
|
|
88
|
+
showSelectAll: true,
|
|
89
|
+
ui: undefined,
|
|
90
|
+
icon: 'i-lucide-list-filter',
|
|
91
|
+
searchable: true,
|
|
92
|
+
searchPlaceholder: 'Search',
|
|
93
|
+
size: 'sm',
|
|
94
|
+
disabled: false,
|
|
95
|
+
portal: true,
|
|
96
|
+
allLabel: 'All',
|
|
97
|
+
clearLabel: 'Clear',
|
|
98
|
+
emptyLabel: 'No matches',
|
|
99
|
+
selectedLabel: undefined,
|
|
100
|
+
announce: undefined,
|
|
101
|
+
},
|
|
102
|
+
)
|
|
103
|
+
const model = defineModel<Value[]>({ default: () => [] })
|
|
104
|
+
defineSlots<{
|
|
105
|
+
/** The option's label, in place of its highlighted text. */
|
|
106
|
+
'option-label'?(props: { option: T; segments: ReturnType<typeof filterSelectSegments>; selected: boolean }): unknown
|
|
107
|
+
}>()
|
|
108
|
+
|
|
109
|
+
const uid = useId()
|
|
110
|
+
const { code: localeCode } = useLocale()
|
|
111
|
+
const open = ref(false)
|
|
112
|
+
const query = ref('')
|
|
113
|
+
const panel = ref<HTMLElement | null>(null)
|
|
114
|
+
|
|
115
|
+
const field = (option: T, key: string) => (option as Record<string, unknown>)[key]
|
|
116
|
+
const valueOf = (option: T) => (props.valueKey ? field(option, props.valueKey) : option) as Value
|
|
117
|
+
const labelOf = (option: T) => String(field(option, props.labelKey ?? 'label') ?? '')
|
|
118
|
+
const countOf = (option: T) => {
|
|
119
|
+
const n = field(option, props.countKey ?? 'count')
|
|
120
|
+
return typeof n === 'number' ? n : undefined
|
|
121
|
+
}
|
|
122
|
+
const iconOf = (option: T) => {
|
|
123
|
+
const name = field(option, props.iconKey ?? 'icon')
|
|
124
|
+
return typeof name === 'string' && name ? name : undefined
|
|
125
|
+
}
|
|
126
|
+
const iconClassOf = (option: T) => {
|
|
127
|
+
const value = field(option, props.iconClassKey ?? 'iconClass')
|
|
128
|
+
return typeof value === 'string' && value ? value : undefined
|
|
129
|
+
}
|
|
130
|
+
const isDisabled = (option: T) => field(option, 'disabled') === true
|
|
131
|
+
/** A part's classes: the defaults, then the caller's `ui` for it, conflicts going to the caller. */
|
|
132
|
+
const cls = (part: Part, ...defaults: (string | undefined)[]) => twMerge(...defaults, props.ui?.[part])
|
|
133
|
+
/** An option's icon: the default color only when the option brings none; the option's own over `ui.itemIcon`. */
|
|
134
|
+
const iconClasses = (option: T) => {
|
|
135
|
+
const own = iconClassOf(option)
|
|
136
|
+
return twMerge('size-4 shrink-0', own ? undefined : 'text-dimmed', props.ui?.itemIcon, own)
|
|
137
|
+
}
|
|
138
|
+
// Values are compared the same way here and in reka-ui (given as UListbox's `by`): a field's value by ===, an option
|
|
139
|
+
// by identity — of the raw object, since a model held in ref() hands back reactive proxies of the options.
|
|
140
|
+
const same = (a: unknown, b: unknown) => Object.is(toRaw(a), toRaw(b))
|
|
141
|
+
const has = (value: Value) => model.value.some((v) => same(v, value))
|
|
142
|
+
const isSelected = (option: T) => has(valueOf(option))
|
|
143
|
+
|
|
144
|
+
const shown = computed(() => props.options.filter((o) => filterSelectMatches(labelOf(o), query.value)))
|
|
145
|
+
const checkable = computed(() => shown.value.filter((o) => !isDisabled(o)))
|
|
146
|
+
const allSelected = computed(() => checkable.value.every(isSelected))
|
|
147
|
+
|
|
148
|
+
const countFormat = computed(() => new Intl.NumberFormat(localeCode.value))
|
|
149
|
+
const formatCount = (n: number) => countFormat.value.format(n)
|
|
150
|
+
|
|
151
|
+
/** The chosen values' labels in the options' order; values no option holds follow, as written. */
|
|
152
|
+
const chosenLabels = computed(() => [
|
|
153
|
+
...props.options.filter(isSelected).map(labelOf),
|
|
154
|
+
...model.value.filter((v) => !props.options.some((o) => same(valueOf(o), v))).map((v) => String(v)),
|
|
155
|
+
])
|
|
156
|
+
/** The button's chips: one per value up to `maxShown`, otherwise one saying how many. */
|
|
157
|
+
const chips = computed(() => {
|
|
158
|
+
const n = model.value.length
|
|
159
|
+
if (!n) return []
|
|
160
|
+
return n <= props.maxShown ? chosenLabels.value : [props.selectedLabel?.(n) ?? `${n} selected`]
|
|
161
|
+
})
|
|
162
|
+
// The button's name, the chips said in words: "Status, Open, Blocked" or "Status, 3 selected". It starts with the
|
|
163
|
+
// visible label, so speech input still finds the button by what it shows.
|
|
164
|
+
const buttonName = computed(() => (chips.value.length ? `${props.label}, ${chips.value.join(', ')}` : undefined))
|
|
165
|
+
|
|
166
|
+
// A chip cut short by the cap carries its whole text as a title. Measured once drawn, and again as the pointer or
|
|
167
|
+
// focus reaches the button, since a web font arriving late can change what fits.
|
|
168
|
+
const chipBox = ref<HTMLElement | null>(null)
|
|
169
|
+
const cutShort = ref<boolean[]>([])
|
|
170
|
+
function measureChips() {
|
|
171
|
+
cutShort.value = [...(chipBox.value?.children ?? [])].map((el) => el.scrollWidth > el.clientWidth)
|
|
172
|
+
}
|
|
173
|
+
watch([chips, chipBox], measureChips, { flush: 'post' })
|
|
174
|
+
|
|
175
|
+
function selectAll() {
|
|
176
|
+
model.value = [...model.value, ...checkable.value.map(valueOf).filter((v) => !has(v))]
|
|
177
|
+
refocus()
|
|
178
|
+
}
|
|
179
|
+
function clear() {
|
|
180
|
+
model.value = []
|
|
181
|
+
refocus()
|
|
182
|
+
}
|
|
183
|
+
/** After All or Clear, focus goes back into the list's search box (or the list), not to a button that may go disabled. */
|
|
184
|
+
function refocus() {
|
|
185
|
+
panel.value?.querySelector<HTMLElement>('input, [role="listbox"]')?.focus()
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Space checks the highlighted option from the search box while the box is empty, or once the arrow keys have moved
|
|
189
|
+
// since the last character typed; otherwise it is part of the search.
|
|
190
|
+
let navigated = false
|
|
191
|
+
const NAVIGATION = new Set(['ArrowDown', 'ArrowUp', 'Home', 'End', 'PageUp', 'PageDown'])
|
|
192
|
+
function onKeydown(e: KeyboardEvent) {
|
|
193
|
+
if (NAVIGATION.has(e.key)) {
|
|
194
|
+
navigated = true
|
|
195
|
+
return
|
|
196
|
+
}
|
|
197
|
+
if (e.key !== ' ' || !(e.target instanceof HTMLInputElement)) return
|
|
198
|
+
if (query.value && !navigated) return
|
|
199
|
+
const option = panel.value?.querySelector<HTMLElement>('[role="option"][data-highlighted]')
|
|
200
|
+
if (!option) return
|
|
201
|
+
e.preventDefault()
|
|
202
|
+
option.click()
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// The list is named for the filter, and the search box says which list it drives. UListbox puts neither attribute on
|
|
206
|
+
// the elements that need them, so they are set once the panel is drawn.
|
|
207
|
+
watch(
|
|
208
|
+
[panel, () => props.label],
|
|
209
|
+
([el]) => {
|
|
210
|
+
const list = el?.querySelector<HTMLElement>('[role="listbox"]')
|
|
211
|
+
if (!list) return
|
|
212
|
+
list.setAttribute('aria-label', props.label)
|
|
213
|
+
list.id = `${uid}-list`
|
|
214
|
+
el?.querySelector('input')?.setAttribute('aria-controls', list.id)
|
|
215
|
+
},
|
|
216
|
+
{ flush: 'post' },
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
/** A check from the list (click, Enter or Space): the new selection, and the search cleared for the next pick. */
|
|
220
|
+
function onPick(values: Value[]) {
|
|
221
|
+
model.value = values
|
|
222
|
+
query.value = ''
|
|
223
|
+
navigated = false
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// A closed panel forgets its search.
|
|
227
|
+
watch(open, (isOpen) => {
|
|
228
|
+
if (!isOpen) query.value = ''
|
|
229
|
+
navigated = false
|
|
230
|
+
})
|
|
231
|
+
|
|
232
|
+
// The polite announcement of the selection. Cleared first and set again in a later task, so the same words twice are
|
|
233
|
+
// heard twice; a newer announcement replaces one still pending.
|
|
234
|
+
const announcement = ref('')
|
|
235
|
+
let announceTimer: ReturnType<typeof setTimeout> | undefined
|
|
236
|
+
watch(model, (values) => {
|
|
237
|
+
const count = values.length
|
|
238
|
+
const text = props.announce?.({ label: props.label, count }) ?? `${props.label}: ${count ? count : 'none'} selected.`
|
|
239
|
+
announcement.value = ''
|
|
240
|
+
clearTimeout(announceTimer)
|
|
241
|
+
announceTimer = setTimeout(() => { announcement.value = text }, 100)
|
|
242
|
+
})
|
|
243
|
+
onBeforeUnmount(() => clearTimeout(announceTimer))
|
|
244
|
+
|
|
245
|
+
const searchInput = computed(() => props.searchable
|
|
246
|
+
? { placeholder: props.searchPlaceholder, icon: 'i-lucide-search', autocomplete: 'off', 'aria-label': `Search ${props.label}`, 'data-search': '', class: props.ui?.search }
|
|
247
|
+
: false)
|
|
248
|
+
</script>
|
|
249
|
+
|
|
250
|
+
<template>
|
|
251
|
+
<div class="inline-flex" data-filter-select v-bind="$attrs">
|
|
252
|
+
<UPopover v-model:open="open" :portal="portal" :content="{ side: 'bottom', align: 'start', sideOffset: 6 }" :ui="{ content: cls('content', 'w-64') }">
|
|
253
|
+
<UButton
|
|
254
|
+
type="button"
|
|
255
|
+
variant="outline"
|
|
256
|
+
color="neutral"
|
|
257
|
+
:size="size"
|
|
258
|
+
:icon="icon || undefined"
|
|
259
|
+
:disabled="disabled"
|
|
260
|
+
:aria-label="buttonName"
|
|
261
|
+
:class="ui?.trigger"
|
|
262
|
+
data-trigger
|
|
263
|
+
@pointerenter="measureChips"
|
|
264
|
+
@focus="measureChips"
|
|
265
|
+
>
|
|
266
|
+
<span>{{ label }}</span>
|
|
267
|
+
<!-- Not UBadges: their block padding and line height would make a button with chips taller than one without,
|
|
268
|
+
and a theme may restyle badges (Forest sets them in the mono face). These take the button's own line
|
|
269
|
+
height and font, so the button is the same height whatever it holds and the values read as words. The
|
|
270
|
+
row is capped, and a grid rather than a flex row: its tracks grow each chip toward its whole width and give
|
|
271
|
+
what is left to the longer ones, so a short chip ("Low") stays whole and only a long one truncates. -->
|
|
272
|
+
<span v-if="chips.length" ref="chipBox" class="grid min-w-0 max-w-40 auto-cols-[minmax(0,max-content)] grid-flow-col gap-1" data-badges>
|
|
273
|
+
<span
|
|
274
|
+
v-for="(chip, i) in chips"
|
|
275
|
+
:key="i"
|
|
276
|
+
:class="cls('badge', 'min-w-0 truncate rounded-sm bg-elevated px-1.5 text-[0.875em] text-default tabular-nums')"
|
|
277
|
+
:title="cutShort[i] ? chip : undefined"
|
|
278
|
+
data-badge
|
|
279
|
+
>{{ chip }}</span>
|
|
280
|
+
</span>
|
|
281
|
+
</UButton>
|
|
282
|
+
|
|
283
|
+
<template #content>
|
|
284
|
+
<div ref="panel" data-filter-panel @keydown="onKeydown" @input="navigated = false">
|
|
285
|
+
<UListbox
|
|
286
|
+
:model-value="(model as never)"
|
|
287
|
+
:search-term="query"
|
|
288
|
+
:items="(shown as ListboxItem[])"
|
|
289
|
+
multiple
|
|
290
|
+
:value-key="valueKey"
|
|
291
|
+
:by="same"
|
|
292
|
+
:filter="searchInput"
|
|
293
|
+
ignore-filter
|
|
294
|
+
:autofocus="searchable"
|
|
295
|
+
:ui="{ root: 'rounded-none ring-0', content: cls('list', 'max-h-72'), item: ui?.item }"
|
|
296
|
+
@update:model-value="onPick($event as Value[])"
|
|
297
|
+
@update:search-term="query = $event"
|
|
298
|
+
>
|
|
299
|
+
<template #item="{ item }">
|
|
300
|
+
<span
|
|
301
|
+
aria-hidden="true"
|
|
302
|
+
:class="[
|
|
303
|
+
'grid size-4 shrink-0 place-items-center rounded-sm border',
|
|
304
|
+
isSelected(item as T) ? 'border-primary bg-primary text-inverted' : 'border-accented bg-default',
|
|
305
|
+
]"
|
|
306
|
+
data-check
|
|
307
|
+
>
|
|
308
|
+
<UIcon v-if="isSelected(item as T)" name="i-lucide-check" class="size-3" />
|
|
309
|
+
</span>
|
|
310
|
+
<UIcon v-if="iconOf(item as T)" :name="iconOf(item as T)!" :class="iconClasses(item as T)" aria-hidden="true" data-icon />
|
|
311
|
+
<span :class="cls('itemLabel', 'min-w-0 flex-1 truncate')" data-label>
|
|
312
|
+
<slot name="option-label" :option="(item as T)" :segments="filterSelectSegments(labelOf(item as T), query)" :selected="isSelected(item as T)">
|
|
313
|
+
<template v-for="(segment, i) in filterSelectSegments(labelOf(item as T), query)" :key="i">
|
|
314
|
+
<mark v-if="segment.match" class="rounded-xs bg-primary/15 font-semibold text-highlighted">{{ segment.text }}</mark>
|
|
315
|
+
<template v-else>{{ segment.text }}</template>
|
|
316
|
+
</template>
|
|
317
|
+
</slot>
|
|
318
|
+
</span>
|
|
319
|
+
<span v-if="countOf(item as T) !== undefined" :class="cls('itemCount', 'ms-auto shrink-0 text-xs tabular-nums text-muted')" data-count>
|
|
320
|
+
{{ formatCount(countOf(item as T)!) }}
|
|
321
|
+
</span>
|
|
322
|
+
</template>
|
|
323
|
+
<template #empty>{{ emptyLabel }}</template>
|
|
324
|
+
</UListbox>
|
|
325
|
+
|
|
326
|
+
<!-- Without All, the footer is there only while Clear has something to clear. -->
|
|
327
|
+
<div v-if="showSelectAll || model.length" :class="cls('footer', 'flex gap-1 border-t border-default p-1')" data-footer>
|
|
328
|
+
<UButton v-if="showSelectAll" type="button" size="xs" variant="ghost" color="neutral" icon="i-lucide-check-check" class="flex-1 justify-center" :disabled="!checkable.length || allSelected" data-all @click="selectAll">
|
|
329
|
+
{{ allLabel }}
|
|
330
|
+
</UButton>
|
|
331
|
+
<UButton type="button" size="xs" variant="ghost" color="neutral" icon="i-lucide-x" class="flex-1 justify-center" :disabled="!model.length" data-clear @click="clear">
|
|
332
|
+
{{ clearLabel }}
|
|
333
|
+
</UButton>
|
|
334
|
+
</div>
|
|
335
|
+
</div>
|
|
336
|
+
</template>
|
|
337
|
+
</UPopover>
|
|
338
|
+
<p class="sr-only" role="status" aria-live="polite" data-announce>{{ announcement }}</p>
|
|
339
|
+
</div>
|
|
340
|
+
</template>
|
|
@@ -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>
|