@zooui/nuxt 0.0.0-stage → 0.1.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,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>
@@ -0,0 +1,22 @@
1
+ <script setup lang="ts">
2
+ /**
3
+ * USlideover with Zoo UI's colored edge: side drawer — a top edge, as for every overlay. Only `color` is added
4
+ * — every other prop, `v-model`, event and slot passes straight through to Nuxt UI's USlideover, so its
5
+ * behavior and polish are untouched. No `color`, no edge: a plain USlideover.
6
+ */
7
+ import { edge, useSectionAccent, withEdge, withSectionAccent, type EdgeColor } from './edge'
8
+
9
+ defineOptions({ inheritAttrs: false })
10
+ const props = defineProps<{ color?: EdgeColor; ui?: Record<string, any> }>()
11
+ const ui = computed(() => withEdge(props.ui, 'content', edge('top', props.color)))
12
+ // `accent`: the overlay portals to <body>, so it takes the name of the section it was opened from
13
+ const section = useSectionAccent()
14
+ </script>
15
+
16
+ <template>
17
+ <USlideover v-bind="$attrs" :ui="ui" :content="withSectionAccent($attrs.content, color, section)">
18
+ <template v-for="(_, name) in $slots" #[name]="scope">
19
+ <slot :name="name" v-bind="scope ?? {}" />
20
+ </template>
21
+ </USlideover>
22
+ </template>
@@ -0,0 +1,27 @@
1
+ <script setup lang="ts">
2
+ /**
3
+ * One chip per slot of capacity, each NAMED: "slot 1 · free", "slot 2 · build 4812". An open slot is a solid
4
+ * primary badge (the accent, with ground-colored text in dark); a held one is an outline neutral badge saying what
5
+ * holds it. Blank colored bars read as empty tags, so a chip always carries its text. Nuxt UI's UBadge as it ships
6
+ * (the Forest theme sets badges in its mono face); the list is labeled for assistive tech by `label`.
7
+ */
8
+ defineProps<{
9
+ /** In display order. `label` is the chip's text; `available` marks an open slot; `title` is an optional tooltip. */
10
+ slots: { label: string; available: boolean; title?: string }[]
11
+ /** What the group is, for assistive tech: "Linux VMs: 1 of 4 free". */
12
+ label?: string
13
+ size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl'
14
+ }>()
15
+ </script>
16
+
17
+ <template>
18
+ <ul class="flex flex-wrap gap-1.5 m-0 p-0 list-none" :aria-label="label">
19
+ <li v-for="(slot, i) in slots" :key="i" class="flex">
20
+ <UBadge
21
+ :label="slot.label" :title="slot.title" :size="size"
22
+ :color="slot.available ? 'primary' : 'neutral'" :variant="slot.available ? 'solid' : 'outline'"
23
+ :data-available="slot.available ? 'true' : 'false'"
24
+ />
25
+ </li>
26
+ </ul>
27
+ </template>
@@ -0,0 +1,24 @@
1
+ <script setup lang="ts">
2
+ import { status, cx } from "./recipes";
3
+
4
+ const LABELS = {
5
+ healthy: "Healthy", warn: "Near limit", suspended: "Suspended",
6
+ unreachable: "Unreachable", quiet: "Quiet",
7
+ } as const;
8
+
9
+ const props = withDefaults(defineProps<{
10
+ state?: keyof typeof LABELS;
11
+ pill?: boolean;
12
+ /** A soft glow around the healthy dot. Other states stay unlit. */
13
+ glow?: boolean;
14
+ }>(), { state: "healthy", pill: false, glow: false });
15
+ </script>
16
+
17
+ <template>
18
+ <!-- Shape carries the state; color only reinforces it, so this survives
19
+ 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>
23
+ </span>
24
+ </template>
@@ -0,0 +1,30 @@
1
+ <script setup lang="ts">
2
+ /**
3
+ * Light / dark / system as one segmented control: Nuxt UI buttons in a field group, the chosen one pressed
4
+ * (aria-pressed) and solid. The preference is only known on the client, so the control renders there and a
5
+ * disabled copy stands in on the server rather than a guess.
6
+ */
7
+ import { ZOO_THEMES } from '../composables/useZooTheme'
8
+
9
+ const { theme, setTheme } = useZooTheme()
10
+
11
+ const ICONS = { light: 'i-lucide-sun', dark: 'i-lucide-moon', system: 'i-lucide-monitor' } as const
12
+ </script>
13
+
14
+ <template>
15
+ <ClientOnly>
16
+ <UFieldGroup role="group" aria-label="Theme">
17
+ <UButton
18
+ v-for="t in ZOO_THEMES" :key="t"
19
+ :icon="ICONS[t]" :label="t" size="xs" color="neutral"
20
+ :variant="theme === t ? 'solid' : 'outline'" :aria-pressed="theme === t"
21
+ @click="setTheme(t)"
22
+ />
23
+ </UFieldGroup>
24
+ <template #fallback>
25
+ <UFieldGroup role="group" aria-label="Theme">
26
+ <UButton v-for="t in ZOO_THEMES" :key="t" :icon="ICONS[t]" :label="t" size="xs" color="neutral" variant="outline" disabled />
27
+ </UFieldGroup>
28
+ </template>
29
+ </ClientOnly>
30
+ </template>
@@ -0,0 +1,62 @@
1
+ <script setup lang="ts">
2
+ /**
3
+ * The shown-once moment: a secret (an API token, say) displayed once after it is created. Zoo UI's code surface holds
4
+ * the token — its copy button, the token marked and selectable in one click — under a `[ token · name · shown once ]`
5
+ * kicker, with Zoo UI's banner (UAlert outline, warning) saying it will not be shown again. With `require-ack`, a
6
+ * button acknowledges it has been saved: the secret then blurs and goes inert, out of reach of focus and readers.
7
+ */
8
+ import { tokenReveal, cx } from "./recipes";
9
+
10
+ withDefaults(defineProps<{
11
+ /** the secret, shown in full */
12
+ token: string;
13
+ /** the token's name, in the kicker */
14
+ name?: string;
15
+ /** show the acknowledgment button; the parent usually moves on when it emits `ack` */
16
+ requireAck?: boolean;
17
+ ackLabel?: string;
18
+ /** the banner's title; the default slot replaces its description */
19
+ title?: string;
20
+ }>(), { name: "default", requireAck: false, ackLabel: "I have saved it", title: "You won't see this token again" });
21
+
22
+ defineSlots<{
23
+ /** the warning's description: what the token grants and what to do if it is lost */
24
+ default?: () => unknown;
25
+ /** more actions beside the acknowledgment, e.g. a "Done" link */
26
+ actions?: () => unknown;
27
+ }>();
28
+
29
+ const emit = defineEmits<{
30
+ /** the token reached the clipboard (never on a failed copy) */
31
+ copy: [token: string];
32
+ /** the acknowledgment button was pressed; emitted once */
33
+ ack: [];
34
+ }>();
35
+
36
+ const labelId = useId();
37
+ const acknowledged = ref(false);
38
+
39
+ function ack() {
40
+ if (acknowledged.value) return;
41
+ acknowledged.value = true;
42
+ emit("ack");
43
+ }
44
+ </script>
45
+
46
+ <template>
47
+ <section :class="tokenReveal.root" :aria-labelledby="labelId">
48
+ <ZKicker :id="labelId">token · {{ name }} · shown once</ZKicker>
49
+ <div :class="cx(tokenReveal.secret, acknowledged && tokenReveal.hidden)" :inert="acknowledged" data-slot="secret">
50
+ <ZCodeBlock variant="block" :code="token" :token="token" @copy="emit('copy', $event)" />
51
+ </div>
52
+ <UAlert color="warning" variant="outline" icon="i-lucide-triangle-alert" :title="title">
53
+ <template #description>
54
+ <slot>Copy it now and keep it somewhere safe. It is not stored in a recoverable form: if you lose it, revoke it and create another.</slot>
55
+ </template>
56
+ </UAlert>
57
+ <div v-if="requireAck || $slots.actions" :class="tokenReveal.actions">
58
+ <UButton v-if="requireAck" color="primary" :label="ackLabel" :icon="acknowledged ? 'i-lucide-check' : undefined" @click="ack" />
59
+ <slot name="actions" />
60
+ </div>
61
+ </section>
62
+ </template>
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The ecosystems ZEcosystemMark knows by name — package managers as two-letter monogram tiles. Each has its own
3
+ * corner SHAPE so they read apart at 20px without brand color. A product with ecosystems beyond these passes
4
+ * `label`, `monogram` and `shape` to the component (any of them also overrides an entry here); an unknown ecosystem
5
+ * with none of them is still drawn, from its own name, on the plain `rounded` tile.
6
+ */
7
+ export const ECOSYSTEM_SHAPES = ['square', 'circle', 'leaf', 'arch', 'lens', 'drop', 'rounded'] as const
8
+ export type EcosystemShape = (typeof ECOSYSTEM_SHAPES)[number]
9
+
10
+ export interface Ecosystem {
11
+ /** what the tile reads as — the accessible name, and the visible label with `with-label` */
12
+ label: string
13
+ /** two letters, set in the mono face */
14
+ monogram: string
15
+ shape: EcosystemShape
16
+ }
17
+
18
+ export const ECOSYSTEMS = {
19
+ npm: { label: 'npm', monogram: 'npm', shape: 'square' },
20
+ nuget: { label: 'NuGet', monogram: 'nu', shape: 'circle' },
21
+ winget: { label: 'winget', monogram: 'wg', shape: 'leaf' },
22
+ chocolatey: { label: 'Chocolatey', monogram: 'ch', shape: 'arch' },
23
+ scoop: { label: 'Scoop', monogram: 'sc', shape: 'lens' },
24
+ homebrew: { label: 'Homebrew', monogram: 'br', shape: 'drop' },
25
+ } as const satisfies Record<string, Ecosystem>
26
+
27
+ export type KnownEcosystem = keyof typeof ECOSYSTEMS
28
+
29
+ /** The entry for `id`, with any overrides applied; an unknown id falls back to its own name. */
30
+ export function ecosystem(id: string, overrides: Partial<Ecosystem> = {}): Ecosystem {
31
+ const known: Ecosystem | undefined = (ECOSYSTEMS as Record<string, Ecosystem>)[id]
32
+ const base = known ?? { label: id, monogram: id.slice(0, 2), shape: 'rounded' }
33
+ return {
34
+ label: overrides.label ?? base.label,
35
+ monogram: overrides.monogram ?? base.monogram,
36
+ shape: overrides.shape ?? base.shape,
37
+ }
38
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Zoo UI's colored edge — the one piece of Zoo UI styling the base adds to Nuxt UI's surfaces. A 3px stripe in the
3
+ * surface's color: on the TOP for overlays (dialog, slideover, drawer — Zoo UI's danger dialog), on the LEFT for
4
+ * inline surfaces (card, toast — Zoo UI's toast and callout). Everything else about the surface is Nuxt UI's.
5
+ *
6
+ * The class strings are written out in full so Tailwind's scan finds them. `border-<color>` sets every side's
7
+ * color, but only the edge side has width, so only the edge shows; Nuxt UI's semantic colors switch to their
8
+ * 400 shade in dark mode on their own.
9
+ *
10
+ * `accent` is the section's accent (`data-accent`, base.css): the `--accent` role, which carries its own dark value.
11
+ * Outside any `data-accent` container it falls back to the primary. Overlays portal to <body>, outside the section,
12
+ * so their wrappers carry the section's name onto the overlay's content (useSectionAccent).
13
+ */
14
+ import { getCurrentInstance, onMounted, onUpdated, ref } from 'vue'
15
+
16
+ export const EDGE_COLORS = ['primary', 'secondary', 'success', 'info', 'warning', 'error', 'neutral', 'accent'] as const
17
+ export type EdgeColor = (typeof EDGE_COLORS)[number]
18
+
19
+ const edgeColor: Record<EdgeColor, string> = {
20
+ primary: 'border-primary',
21
+ secondary: 'border-secondary',
22
+ success: 'border-success',
23
+ info: 'border-info',
24
+ warning: 'border-warning',
25
+ error: 'border-error',
26
+ neutral: 'border-inverted',
27
+ accent: 'border-[color:var(--accent,var(--ui-primary))]',
28
+ }
29
+
30
+ /** The edge classes for a surface, or '' for no color (a plain Nuxt UI surface). */
31
+ export const edge = (side: 'top' | 'left', color?: EdgeColor) =>
32
+ color ? `${side === 'top' ? 'border-t-3' : 'border-l-3'} ${edgeColor[color]}` : ''
33
+
34
+ /** Prepend the edge to one slot of a Nuxt UI `ui` object, keeping whatever the caller passed for it. */
35
+ export function withEdge<T extends Record<string, unknown>>(ui: T | undefined, slot: string, classes: string): T {
36
+ if (!classes) return (ui ?? {}) as T
37
+ const existing = ui?.[slot]
38
+ return { ...(ui ?? {}), [slot]: existing ? `${classes} ${existing}` : classes } as T
39
+ }
40
+
41
+ /**
42
+ * The `data-accent` name of the section a component sits in, read from the DOM where it renders — for an overlay
43
+ * wrapper to put on its content, which Nuxt UI portals to <body> and so out of the section's reach. Read after mount
44
+ * and after every update (the wrapper re-renders when its `open` or other attributes change), so it is current
45
+ * whenever the overlay opens; undefined on the server and outside any section.
46
+ */
47
+ export function useSectionAccent() {
48
+ const instance = getCurrentInstance()
49
+ const name = ref<string>()
50
+ const read = () => {
51
+ const el = instance?.proxy?.$el as Node | null | undefined
52
+ name.value = (el?.parentElement?.closest('[data-accent]') as HTMLElement | null)?.dataset.accent
53
+ }
54
+ onMounted(read)
55
+ onUpdated(read)
56
+ return name
57
+ }
58
+
59
+ /** An overlay's `content` props with the section's accent added, for `color="accent"`; the caller's kept otherwise. */
60
+ export function withSectionAccent(content: unknown, color: EdgeColor | undefined, accent: string | undefined) {
61
+ const props = content as Record<string, any> | undefined
62
+ return color === 'accent' && accent ? { ...(props ?? {}), 'data-accent': accent } : props
63
+ }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * ZNumberInput's `calc` mode: a currency field with a calculator in it, apart from the component (tests:
3
+ * scripts/number-calc.test.mjs). `+ - * /` with the usual precedence, read by a small recursive-descent parser (never
4
+ * `eval`) and worked in decimal.js, so 0.1 + 0.2 is 0.3. Each number in the expression is grouped as it is typed, for
5
+ * the field's locale, with the caret kept on the same character.
6
+ */
7
+ import { D, deletion, grouped, isDecimal, isGroup, isMinus, splice, type Dec, type Edit, type Field, type Places, type Selection, type Symbols } from './number-format.ts'
8
+
9
+ const OPERATOR = /([+\-*/−])/
10
+ const isOperator = (c: string) => c.length === 1 && OPERATOR.test(c)
11
+
12
+ /**
13
+ * The value of an expression, or `null` when it is incomplete ("678+"), not one ("abc"), or divides by zero. Spaces
14
+ * and the locale's group separators are ignored ("1,000+500" is 1500 in en-US, "1.000+500" in de); a minus straight
15
+ * before a number makes it negative ("-100+200", "5*-2").
16
+ */
17
+ export function evaluate(input: string, s: Symbols): Dec | null {
18
+ let expr = ''
19
+ for (const c of input) {
20
+ if (/\s/.test(c) || isGroup(c, s)) continue
21
+ expr += isDecimal(c, s) ? '.' : isMinus(c) ? '-' : c
22
+ }
23
+ let pos = 0
24
+
25
+ // number → -? [digits and one decimal point]
26
+ const number = (): Dec | null => {
27
+ let text = ''
28
+ if (expr[pos] === '-') text += expr[pos++]
29
+ while (pos < expr.length && /[\d.]/.test(expr[pos]!)) text += expr[pos++]
30
+ if (!/\d/.test(text)) return null
31
+ try {
32
+ return new D(text)
33
+ } catch {
34
+ return null
35
+ }
36
+ }
37
+ // term → number ((* or /) number)*
38
+ const term = (): Dec | null => {
39
+ let result = number()
40
+ while (result !== null && (expr[pos] === '*' || expr[pos] === '/')) {
41
+ const op = expr[pos++]
42
+ const right = number()
43
+ if (right === null || (op === '/' && right.isZero())) return null
44
+ result = op === '*' ? result.times(right) : result.div(right)
45
+ }
46
+ return result
47
+ }
48
+ // expression → term ((+ or -) term)*
49
+ const expression = (): Dec | null => {
50
+ let result = term()
51
+ while (result !== null && (expr[pos] === '+' || expr[pos] === '-')) {
52
+ const op = expr[pos++]
53
+ const right = term()
54
+ if (right === null) return null
55
+ result = op === '+' ? result.plus(right) : result.minus(right)
56
+ }
57
+ return result
58
+ }
59
+
60
+ if (!expr) return null
61
+ const result = expression()
62
+ return pos === expr.length && result !== null && result.isFinite() ? result : null
63
+ }
64
+
65
+ /** Ten places, for a calc field with no maximum of its own: 1/3*3 is 1 rather than forty nines. */
66
+ export const CALC_PLACES = 10
67
+
68
+ /** The places a calc field's result is rounded to, once, on commit: the field's maximum, else ten. */
69
+ export const calcPlaces = (places: Places): Places => (places.max === undefined ? { min: places.min, max: CALC_PLACES } : places)
70
+
71
+ /** Whether there is an operator past the first character (a leading minus is a sign, not a sum). */
72
+ export const containsOperator = (text: string) => text.length > 1 && OPERATOR.test(text.slice(1))
73
+
74
+ /** One number of an expression grouped: "12345.6" → "12,345.6", spaces around it kept. Anything it can't read is
75
+ * left as typed. */
76
+ function segment(part: string, s: Symbols): string {
77
+ const bare = [...part].filter((c) => !isGroup(c, s)).join('')
78
+ const [, before, core, after] = /^(\s*)(.*?)(\s*)$/s.exec(bare)!
79
+ if (!/\d/.test(core!)) return part
80
+ const at = [...core!].findIndex((c) => isDecimal(c, s))
81
+ const int = at < 0 ? core! : core!.slice(0, at)
82
+ return before + (/^\d+$/.test(int) ? grouped(int, s).text : int) + (at < 0 ? '' : core!.slice(at)) + after
83
+ }
84
+
85
+ /** The same caret in a regrouped text: after as many characters other than group separators. */
86
+ function keepCaret(before: string, after: string, caret: number, s: Symbols): number {
87
+ let count = 0
88
+ for (let i = 0; i < Math.min(caret, before.length); i++) if (!isGroup(before[i]!, s)) count++
89
+ let pos = 0
90
+ for (let seen = 0; pos < after.length && seen < count; pos++) if (!isGroup(after[pos]!, s)) seen++
91
+ return pos
92
+ }
93
+
94
+ /** An expression as the field shows it while typing: each number grouped, the caret on the same character. */
95
+ export function reformatExpression(raw: string, caret: number, s: Symbols): Field {
96
+ const text = raw.split(OPERATOR).map((part, i) => (i % 2 ? part : segment(part, s))).join('')
97
+ return { text, caret: keepCaret(raw, text, caret, s) }
98
+ }
99
+
100
+ /**
101
+ * The expression after one edit. The rule: an operator typed over a selection is added at the end rather than
102
+ * replacing it (so "1,200" selected on focus, then "+50", is 1,250), except a minus over the whole text, which starts
103
+ * a negative number. `null`: the edit is refused and nothing changes, the selection included.
104
+ */
105
+ export function editExpression(sel: Selection, e: Edit, s: Symbols): Field | null {
106
+ const { text, start, end } = sel
107
+ if ('delete' in e) {
108
+ const range = deletion(sel, e.delete, s)
109
+ return range ? reformatExpression(splice(text, range[0], range[1]), range[0], s) : { text, caret: start }
110
+ }
111
+ // what an expression can hold: a pasted "$1,200" arrives as 1,200, and a line break as a space
112
+ const put = [...e.insert.replace(/\s/g, ' ')].filter((c) => /[\d ]/.test(c) || isOperator(c) || isDecimal(c, s) || isGroup(c, s)).join('')
113
+ if (!put) return null
114
+ if (start !== end && isOperator(put) && !(isMinus(put) && start === 0 && end === text.length)) {
115
+ return reformatExpression(text + put, text.length + 1, s)
116
+ }
117
+ return reformatExpression(splice(text, start, end, put), start + put.length, s)
118
+ }