@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,357 @@
1
+ /**
2
+ * ZNumberInput's text: what the field shows and how typing changes it, apart from the component so it reads (and is
3
+ * tested, scripts/number-format.test.mjs) in one place. The live editing is the behavior of PrimeVue's
4
+ * InputNumber, at the size of its rules rather than its 1,100 lines:
5
+ *
6
+ * - every change is rebuilt by `reformat`: the locale's grouping, one decimal mark, a minus only at the front, no
7
+ * leading zeros, at most the maximum decimal places (typing into a full fraction overwrites the next digit), and
8
+ * the caret kept on the same digit as separators come and go;
9
+ * - `edit` is one keystroke or paste on top of that: Backspace or Delete over a group separator takes the digit
10
+ * beyond it, a fixed decimal mark is stepped over rather than deleted, a second decimal mark is ignored.
11
+ *
12
+ * Figures are plain strings ("-1234.5") between here and decimal.js, and every value is a Decimal of this file's own
13
+ * precision, so nothing passes through a float. `toModel` hands the caller back its own kind: a string, a number, or
14
+ * a Decimal built with the caller's own class.
15
+ */
16
+ import Decimal from 'decimal.js'
17
+
18
+ /** decimal.js with room for a Postgres `numeric` (the default 20 significant digits would round a sum of two), and
19
+ * half-away-from-zero rounding, as Intl rounds for display. */
20
+ export const D = Decimal.clone({ precision: 40, rounding: Decimal.ROUND_HALF_UP, toExpNeg: -40, toExpPos: 40 })
21
+ export type Dec = InstanceType<typeof D>
22
+
23
+ /** The locale's marks: its group and decimal characters and how it groups (en-IN: 12,34,567). Latin digits only. */
24
+ export interface Symbols {
25
+ group: string
26
+ decimal: string
27
+ /** Digits in the last group, and in each group before it. */
28
+ primary: number
29
+ secondary: number
30
+ /** Group only from primary + minGroup digits (es: 1234 but 12.345). */
31
+ minGroup: number
32
+ }
33
+
34
+ const cache = new Map<string, Symbols>()
35
+
36
+ export function symbols(locale: string): Symbols {
37
+ let s = cache.get(locale)
38
+ if (s) return s
39
+ const nf = new Intl.NumberFormat(locale, { numberingSystem: 'latn' })
40
+ const parts = nf.formatToParts(123456789.5)
41
+ const ints = parts.filter((p) => p.type === 'integer').map((p) => p.value.length)
42
+ s = {
43
+ group: parts.find((p) => p.type === 'group')?.value ?? ',',
44
+ decimal: parts.find((p) => p.type === 'decimal')?.value ?? '.',
45
+ primary: ints.at(-1) ?? 3,
46
+ secondary: ints.length > 2 ? ints.at(-2)! : ints.at(-1) ?? 3,
47
+ minGroup: nf.formatToParts(1234).some((p) => p.type === 'group') ? 1 : 2,
48
+ }
49
+ cache.set(locale, s)
50
+ return s
51
+ }
52
+
53
+ /** Decimal places: at least `min` once committed, at most `max` (none: as many as typed). */
54
+ export interface Places { min: number, max?: number }
55
+
56
+ /** How a field reads and writes its text. */
57
+ export interface Format {
58
+ symbols: Symbols
59
+ places: Places
60
+ /** Whether a minus may be typed (min unset or below zero). */
61
+ negative: boolean
62
+ }
63
+
64
+ const isDigit = (c: string) => c >= '0' && c <= '9'
65
+ export const isMinus = (c: string) => c === '-' || c === '−'
66
+ /** The locale's group character; any space where it groups with one (fr's narrow no-break space), an apostrophe
67
+ * where it uses ’ (de-CH). */
68
+ export function isGroup(c: string, s: Symbols): boolean {
69
+ if (c === s.group) return true
70
+ if (/\s/.test(s.group)) return /\s/.test(c)
71
+ return s.group === '’' && c === '\''
72
+ }
73
+ /** The locale's decimal mark, or a full stop where the full stop isn't its group (a numeric keypad's key). */
74
+ export const isDecimal = (c: string, s: Symbols) => c === s.decimal || (c === '.' && s.group !== '.')
75
+
76
+ /** The integer digits grouped for the locale, with the text index after `at` digits (the caret's). */
77
+ export function grouped(int: string, s: Symbols, at = -1): { text: string, caret: number } {
78
+ let text = '', caret = at === 0 ? 0 : -1
79
+ const groupIt = int.length >= s.primary + s.minGroup
80
+ for (let i = 0; i < int.length; i++) {
81
+ const left = int.length - i
82
+ if (groupIt && i > 0 && left >= s.primary && (left === s.primary || (left - s.primary) % s.secondary === 0)) text += s.group
83
+ text += int[i]
84
+ if (i + 1 === at) caret = text.length
85
+ }
86
+ return { text, caret }
87
+ }
88
+
89
+ /** A typed or shown text and where its caret is. */
90
+ export interface Field { text: string, caret: number }
91
+
92
+ /**
93
+ * The text as the field shows it while typing, with the caret on the same digit. Anything that isn't a digit, the
94
+ * decimal mark or a leading minus is dropped (a pasted "$1,234.50" arrives as 1,234.50). Not padded: the minimum
95
+ * places are written on commit, so "1.0" survives on the way to "1.05".
96
+ */
97
+ export function reformat(raw: string, caret: number, f: Format): Field {
98
+ const s = f.symbols
99
+ let neg = false, int = '', frac = '', dec = false
100
+ let part: 'int' | 'frac' = 'int', at = 0
101
+ for (let k = 0; k <= raw.length; k++) {
102
+ if (k === caret) [part, at] = dec ? ['frac', frac.length] : ['int', int.length]
103
+ if (k === raw.length) break
104
+ const c = raw[k]!
105
+ if (isDigit(c)) {
106
+ if (dec) frac += c
107
+ else int += c
108
+ } else if (isDecimal(c, s) && !dec) dec = true
109
+ else if (isMinus(c) && f.negative && !int && !dec) neg = true
110
+ }
111
+ // no leading zeros, but a zero before the decimal mark
112
+ const significant = int.replace(/^0+/, '')
113
+ const zeros = int.length - significant.length - (int && !significant ? 1 : 0)
114
+ if (zeros > 0) {
115
+ int = int.slice(zeros)
116
+ // all zeros, one is left: a caret past any of them goes after it
117
+ if (part === 'int') at = significant ? Math.max(0, at - zeros) : Math.min(at, 1)
118
+ }
119
+ if (dec && !int) {
120
+ int = '0'
121
+ if (part === 'int') at = 1
122
+ }
123
+ // at most `max` places: overwrite after the caret, then drop from the end
124
+ const max = f.places.max
125
+ if (max !== undefined && frac.length > max) {
126
+ let excess = frac.length - max
127
+ if (part === 'frac') {
128
+ const cut = Math.min(excess, frac.length - at)
129
+ frac = frac.slice(0, at) + frac.slice(at + cut)
130
+ excess -= cut
131
+ }
132
+ frac = frac.slice(0, frac.length - excess)
133
+ if (part === 'frac') at = Math.min(at, frac.length)
134
+ }
135
+ const sign = neg ? '-' : ''
136
+ const g = grouped(int, s, part === 'int' ? at : -1)
137
+ if (!dec || max === 0) return { text: sign + g.text, caret: sign.length + (part === 'int' ? g.caret : g.text.length) }
138
+ const text = sign + g.text + s.decimal + frac
139
+ return { text, caret: sign.length + (part === 'int' ? g.caret : g.text.length + 1 + at) }
140
+ }
141
+
142
+ /** One change to the field: text typed or pasted over the selection, or a Backspace or Delete. */
143
+ export type Edit = { insert: string } | { delete: 'backward' | 'forward' }
144
+ export interface Selection { text: string, start: number, end: number }
145
+
146
+ /**
147
+ * Where a deletion lands: the selection, or one character beside the caret, where a group separator means the digit
148
+ * beyond it (Backspace over "1,|234" deletes the 1). `null`: nothing to delete there.
149
+ */
150
+ export function deletion(sel: Selection, direction: 'backward' | 'forward', s: Symbols): [number, number] | null {
151
+ const { text, start, end } = sel
152
+ if (start !== end) return [start, end]
153
+ if (direction === 'backward') {
154
+ if (start === 0) return null
155
+ return isGroup(text[start - 1]!, s) ? (start > 1 ? [start - 2, start - 1] : null) : [start - 1, start]
156
+ }
157
+ if (start >= text.length) return null
158
+ return isGroup(text[start]!, s) ? (start + 1 < text.length ? [start + 1, start + 2] : null) : [start, start + 1]
159
+ }
160
+
161
+ export const splice = (text: string, from: number, to: number, put = '') => text.slice(0, from) + put + text.slice(to)
162
+
163
+ /** The field after one edit, reformatted; `null` when the edit is refused and nothing changes, the selection
164
+ * included (a letter typed over "1,234.50" leaves it there, selected). */
165
+ export function edit(sel: Selection, e: Edit, f: Format): Field | null {
166
+ const s = f.symbols
167
+ const { text, start, end } = sel
168
+ if ('delete' in e) {
169
+ const range = deletion(sel, e.delete, s)
170
+ if (!range) return { text, caret: start }
171
+ // a fixed decimal mark with places after it is stepped over, not deleted (it would run the fraction into the
172
+ // whole part)
173
+ if (range[1] - range[0] === 1 && isDecimal(text[range[0]]!, s) && f.places.min > 0 && /\d/.test(text.slice(range[1]))) {
174
+ return { text, caret: e.delete === 'backward' ? range[0] : range[1] }
175
+ }
176
+ return reformat(splice(text, range[0], range[1]), range[0], f)
177
+ }
178
+ let put = e.insert
179
+ let [from, to] = [start, end]
180
+ const outside = [...text].some((c, i) => (i < start || i >= end) && isDecimal(c, s))
181
+ if (outside && [...put].some((c) => isDecimal(c, s))) {
182
+ // a decimal mark typed just before the one there steps over it; any other second mark is ignored
183
+ if (put.length === 1 && start === end && isDecimal(text[start] ?? '', s)) return { text, caret: start + 1 }
184
+ put = [...put].filter((c) => !isDecimal(c, s)).join('')
185
+ }
186
+ // typed before the minus, a digit goes after it: the sign stays
187
+ if (to === 0 && isMinus(text[0] ?? '') && ![...put].some(isMinus)) from = to = 1
188
+ // nothing in it may go here (a letter, a decimal mark with no places, a minus past the start or where none may go):
189
+ // refused before it clears a selection. Anything that may, replaces the selection, even if it reads the same ("0"
190
+ // over "12" in "120" is 0)
191
+ const allowed = (c: string) => isDigit(c) || (isDecimal(c, s) && f.places.max !== 0) || (isMinus(c) && f.negative && from === 0)
192
+ if (![...put].some(allowed)) return null
193
+ const after = reformat(splice(text, from, to, put), from + put.length, f)
194
+ // at a caret, an insertion that changes neither the text nor the caret (a digit past a full fraction) is refused
195
+ // too; a digit typed over the same digit in a full fraction leaves the text as it was but moves the caret on
196
+ if (from === to) {
197
+ const base = reformat(text, from, f)
198
+ if (after.text === base.text && after.caret === base.caret) return null
199
+ }
200
+ return after
201
+ }
202
+
203
+ /** A field's text, written in another locale's marks: group separators dropped, the decimal mark swapped (and the
204
+ * caret kept on its character), ready for `reformat` in the new locale. */
205
+ export function relocalize(field: Field, from: Symbols, to: Symbols): Field {
206
+ let text = '', caret = 0
207
+ ;[...field.text].forEach((c, i) => {
208
+ if (i === field.caret) caret = text.length
209
+ if (isGroup(c, from)) return
210
+ text += isDecimal(c, from) ? to.decimal : c
211
+ })
212
+ return { text, caret: field.caret >= field.text.length ? text.length : caret }
213
+ }
214
+
215
+ /** The figure in a field's text ("-1,234.5" → "-1234.5"); `null` when there is none yet ("", "-"). */
216
+ export function figureOf(text: string, s: Symbols): string | null {
217
+ let out = ''
218
+ for (const c of text) {
219
+ if (isDigit(c)) out += c
220
+ else if (isDecimal(c, s) && !out.includes('.')) out += '.'
221
+ else if (isMinus(c) && !out) out = '-'
222
+ }
223
+ out = out.replace(/\.$/, '')
224
+ if (out.startsWith('.')) out = `0${out}`
225
+ if (out.startsWith('-.')) out = `-0${out.slice(1)}`
226
+ return /\d/.test(out) ? out : null
227
+ }
228
+
229
+ /** A plain figure as Decimal, or `null` for none. */
230
+ export const toDec = (figure: string | null) => (figure === null ? null : new D(figure))
231
+
232
+ /** A value as the field shows it at rest: rounded to the maximum places, padded to the minimum, grouped. */
233
+ export function display(value: Dec | null, s: Symbols, places: Places): string {
234
+ if (value === null) return ''
235
+ const rounded = places.max === undefined ? value : value.toDecimalPlaces(places.max)
236
+ const fixed = rounded.toFixed(Math.max(places.min, rounded.decimalPlaces()))
237
+ const [whole, frac] = fixed.replace('-', '').split('.')
238
+ const sign = rounded.isNeg() && !rounded.isZero() ? '-' : ''
239
+ return sign + grouped(whole!, s).text + (frac ? s.decimal + frac : '')
240
+ }
241
+
242
+ const bounded = (b: number | string | undefined): b is number | string => b !== undefined && b !== ''
243
+
244
+ /** A committed value as the field shows it: `committed` has rounded it already, or kept a bound the places can't
245
+ * write, so it is not rounded again (min 0.004, max 0.006, two places shows 0.006, as the model holds). */
246
+ export const shownCommitted = (value: Dec | null, s: Symbols, places: Places) => display(value, s, { min: places.min })
247
+
248
+ /** Kept within min/max. */
249
+ export function clamp(value: Dec, min?: number | string, max?: number | string): Dec {
250
+ if (bounded(min) && value.lt(min)) return new D(min)
251
+ if (bounded(max) && value.gt(max)) return new D(max)
252
+ return value
253
+ }
254
+
255
+ /** Out of min/max: -1 below, 1 above, 0 within. */
256
+ export function outside(value: Dec | null, min?: number | string, max?: number | string): -1 | 0 | 1 {
257
+ if (value === null) return 0
258
+ if (bounded(min) && value.lt(min)) return -1
259
+ if (bounded(max) && value.gt(max)) return 1
260
+ return 0
261
+ }
262
+
263
+ /**
264
+ * What a commit (blur, Enter, Tab, or a nudge) makes of a value: rounded to the maximum places, half away from zero,
265
+ * then kept within min/max at those places. A rounded value past a bound becomes the nearest value inside it that the
266
+ * places can write (max 1.235 at two places: 1.23; min 0.004: 0.01), so a commit never leaves the range. If no such
267
+ * value exists (min 0.004, max 0.006, two places), the bound itself is kept, unrounded.
268
+ */
269
+ export function committed(value: Dec | null, o: { min?: number | string, max?: number | string, places: Places }): Dec | null {
270
+ if (value === null) return null
271
+ const dp = o.places.max
272
+ if (dp === undefined) return clamp(value, o.min, o.max)
273
+ const rounded = value.toDecimalPlaces(dp)
274
+ const off = outside(rounded, o.min, o.max)
275
+ if (off === 0) return rounded
276
+ const bound = new D(off > 0 ? o.max! : o.min!)
277
+ const inside = bound.toDecimalPlaces(dp, off > 0 ? D.ROUND_FLOOR : D.ROUND_CEIL)
278
+ return outside(inside, o.min, o.max) === 0 ? inside : bound
279
+ }
280
+
281
+ /** The committed figure, padded to the minimum places: what a string model holds ("1234.50"). */
282
+ export function fixedFigure(value: Dec, places: Places): string {
283
+ return value.toFixed(Math.max(places.min, value.decimalPlaces()))
284
+ }
285
+
286
+ /** The kind of value the caller holds, and so hands back. */
287
+ export type ModelKind = 'string' | 'number' | 'decimal'
288
+ /** Any decimal.js Decimal, from this copy or another. */
289
+ export type DecimalLike = { toString(): string, constructor: unknown }
290
+ export type ModelValue = string | number | DecimalLike | null | undefined
291
+
292
+ /** The kind of a model value; `undefined` for null or undefined, which hold no kind. A Decimal is recognized by
293
+ * decimal.js's own check, which also knows another copy's instances. */
294
+ export function kindOf(v: ModelValue): ModelKind | undefined {
295
+ if (v === null || v === undefined) return undefined
296
+ if (Decimal.isDecimal(v)) return 'decimal'
297
+ return typeof v === 'number' ? 'number' : 'string'
298
+ }
299
+
300
+ /** A model value as this file's Decimal: `null` for empty, or for a string that isn't a plain figure. */
301
+ export function readModel(v: ModelValue): Dec | null {
302
+ const kind = kindOf(v)
303
+ if (!kind) return null
304
+ if (kind === 'number') return Number.isFinite(v) ? new D(v as number) : null
305
+ const text = String(v).trim()
306
+ if (kind === 'string' && !/^-?(\d+\.?\d*|\.\d+)$/.test(text)) return null
307
+ try {
308
+ const d = new D(text)
309
+ return d.isFinite() ? d : null
310
+ } catch {
311
+ return null
312
+ }
313
+ }
314
+
315
+ /**
316
+ * The value a model holds, for its range check: `readModel`, and for a string that isn't a plain figure ("1,500") the
317
+ * figure the field would read from it as text, so a grouped string model is judged by its value, not skipped.
318
+ */
319
+ export function readHeld(v: ModelValue, s: Symbols): Dec | null {
320
+ return readModel(v) ?? (kindOf(v) === 'string' ? toDec(figureOf(String(v), s)) : null)
321
+ }
322
+
323
+ /** A Decimal class: the caller's own, so its `instanceof` holds whichever copy of decimal.js it uses. */
324
+ export type DecimalClass = new (value: string) => DecimalLike
325
+
326
+ /**
327
+ * The class a Decimal was built with, to build its successors with. decimal.js writes the constructor that built an
328
+ * instance onto it, which is the right class for the base and for a `Decimal.clone()` (whose precision it carries):
329
+ * they share one prototype. A subclass (`class Money extends Decimal`) has a prototype of its own, while decimal.js
330
+ * still writes the class it extends onto the instance; there, the prototype's constructor is the caller's class.
331
+ */
332
+ export function decimalClass(v: DecimalLike): DecimalClass {
333
+ const own = v.constructor as { prototype?: unknown }
334
+ const proto = Object.getPrototypeOf(v) as { constructor?: unknown } | null
335
+ if (typeof own === 'function' && own.prototype === proto) return own as DecimalClass
336
+ return (typeof proto?.constructor === 'function' ? proto.constructor : own) as DecimalClass
337
+ }
338
+
339
+ /**
340
+ * A figure handed back as the caller's kind: a string as is, a number, or a Decimal built from the figure's text by
341
+ * the caller's class (`cls`; this file's when the model started empty). Empty is `''` for a string model and `null`
342
+ * otherwise.
343
+ */
344
+ export function toModel(figure: string | null, kind: ModelKind, cls: DecimalClass = Decimal): string | number | DecimalLike | null {
345
+ if (figure === null) return kind === 'string' ? '' : null
346
+ if (kind === 'number') return Number(figure)
347
+ return kind === 'decimal' ? new cls(figure) : figure
348
+ }
349
+
350
+ /** Whether the model already holds this figure, so typing doesn't hand back what is there (a string compares as
351
+ * text, so "1.0" is news to a model holding "1"). */
352
+ export function holds(v: ModelValue, figure: string | null): boolean {
353
+ if (figure === null) return v === null || v === undefined || v === ''
354
+ if (kindOf(v) === 'string') return v === figure
355
+ const d = readModel(v)
356
+ return d !== null && d.eq(figure)
357
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * ZNumberInput's arithmetic and labels, apart from the component so the rules read in one place. The product's choices are options: the
3
+ * default step per unit and the currency and locale come from the product's app.config (`zooui.numberInput`) or the
4
+ * component's props, falling back to the neutral defaults below.
5
+ *
6
+ * The arithmetic is decimal.js, so a nudge never shows binary float noise (0.1 + 0.2 stays 0.3). The text itself (live
7
+ * formatting, the caret, commits, the caller's kind of value) is number-format.ts; calc is number-calc.ts.
8
+ */
9
+ import { clamp, D, type Dec, type Places, type Symbols } from './number-format.ts'
10
+
11
+ export type NumberUnit = 'money' | 'percent' | 'count' | 'hours'
12
+
13
+ /** What a product sets once, in its app.config under `zooui.numberInput`; a prop on the component wins over it. */
14
+ export interface NumberInputConfig {
15
+ /** The step for each unit, when the component is given none. */
16
+ steps?: Partial<Record<NumberUnit, number>>
17
+ /** ISO 4217 code for `unit="money"`: its symbol is the leading mark. */
18
+ currency?: string
19
+ /** BCP 47 locale for the currency symbol, the grouping and decimal marks, and the chevrons' labels. Fixed by
20
+ * default, so the server and the browser render the same text (a browser-default locale would mismatch on
21
+ * hydration). */
22
+ locale?: string
23
+ /** Decimal places for each unit: `min` written on commit, `max` rounded to (none: as typed). */
24
+ fractionDigits?: Partial<Record<NumberUnit, Partial<Places>>>
25
+ }
26
+
27
+ /** Neutral defaults: a product's own (say, money by 5,000) go in its app.config. */
28
+ export const DEFAULTS = {
29
+ steps: { money: 1, percent: 1, count: 1, hours: 0.5 } satisfies Record<NumberUnit, number>,
30
+ /** Money in cents; every other unit as typed. */
31
+ places: { money: { min: 2, max: 2 }, percent: { min: 0 }, count: { min: 0 }, hours: { min: 0 } } as Record<NumberUnit, Places>,
32
+ currency: 'USD',
33
+ locale: 'en-US',
34
+ }
35
+
36
+ /** The mark after the value. Kept the same width when empty (money, count), so values line up in a column. */
37
+ export const SUFFIX: Record<NumberUnit, string> = { money: '', percent: '%', count: '', hours: 'hrs' }
38
+
39
+ /** The currency's own short symbol ($, €, £, CHF), or the code itself if Intl doesn't know it. */
40
+ export function currencySymbol(locale: string, currency: string): string {
41
+ try {
42
+ const parts = new Intl.NumberFormat(locale, { style: 'currency', currency, currencyDisplay: 'narrowSymbol' }).formatToParts(0)
43
+ return parts.find((p) => p.type === 'currency')?.value ?? currency
44
+ } catch {
45
+ return currency
46
+ }
47
+ }
48
+
49
+ /** The step as the chevrons name it: "Add $5,000", "Subtract 0.5 hours". */
50
+ export function stepLabel(unit: NumberUnit, step: number, locale: string, currency: string): string {
51
+ const plain = new Intl.NumberFormat(locale, { maximumFractionDigits: 20 }).format(step)
52
+ if (unit === 'money') {
53
+ try {
54
+ return new Intl.NumberFormat(locale, { style: 'currency', currency, currencyDisplay: 'narrowSymbol', minimumFractionDigits: 0, maximumFractionDigits: 20 }).format(step)
55
+ } catch {
56
+ return `${currency} ${plain}`
57
+ }
58
+ }
59
+ if (unit === 'percent') return `${plain}%`
60
+ return unit === 'hours' ? `${plain} hours` : plain
61
+ }
62
+
63
+ export const PLAIN_NUMBER = /^-?(\d+\.?\d*|\.\d+)$/
64
+
65
+ const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
66
+
67
+ /**
68
+ * What someone typed, made into a plain number where it plainly is one: "$120,000" → "120000", "24 %" → "24",
69
+ * "40." → "40". Group separators go only when they group thousands: in en-US "1,5" (a decimal comma) or "12 34" is
70
+ * left as typed, so the field's own validation says it isn't a number rather than it saving quietly as 15 or 1234.
71
+ * In a locale with a decimal comma (`symbols`, from the field's locale) "1,5" is 1.5 and "1.234,5" 1234.5. `symbol`
72
+ * is the currency mark to strip from the front (`$`, say), after any `prefix`; `suffix` comes off the end.
73
+ */
74
+ export function readFigure(
75
+ raw: string | number | null | undefined,
76
+ o: { symbol?: string, symbols?: Pick<Symbols, 'group' | 'decimal'>, prefix?: string, suffix?: string } = {},
77
+ ): string {
78
+ const s = String(raw ?? '').trim()
79
+ if (s === '') return ''
80
+ let bare = s
81
+ for (const lead of [o.prefix, o.symbol ?? '$']) if (lead?.trim()) bare = bare.replace(new RegExp(`^${escapeRegExp(lead.trim())}\\s*`), '')
82
+ if (o.suffix?.trim()) bare = bare.replace(new RegExp(`\\s*${escapeRegExp(o.suffix.trim())}$`), '')
83
+ bare = bare.replace(/\s*%$/, '')
84
+ const { group, decimal } = o.symbols ?? { group: ',', decimal: '.' }
85
+ const g = /\s/.test(group) ? '\\s' : escapeRegExp(group)
86
+ let plain = new RegExp(`^-?\\d{1,3}(${g}\\d{3})+(${escapeRegExp(decimal)}\\d*)?$`).test(bare) ? bare.replace(new RegExp(g, 'g'), '') : bare
87
+ if (decimal !== '.') plain = plain.replace(decimal, '.')
88
+ return PLAIN_NUMBER.test(plain) ? plain.replace(/\.$/, '') : s
89
+ }
90
+
91
+ /** A figure written for freeform text in the field's locale: its decimal mark, no grouping, so `readFigure` reads it
92
+ * back as the same value (de: "1,234", never "1.234", which de reads as 1234). */
93
+ export const writeFigure = (figure: string, symbols: Pick<Symbols, 'decimal'>) => figure.replace('.', symbols.decimal)
94
+
95
+ /**
96
+ * The value after one nudge of `step` in `direction`, from whatever is there (38,500 → 43,500: never snapped to a
97
+ * multiple of the step), clamped to min/max. Empty starts from zero.
98
+ */
99
+ export function nudged(current: Dec | null, direction: 1 | -1, o: { step: number, min?: number | string, max?: number | string }): Dec {
100
+ return clamp((current ?? new D(0)).plus(new D(o.step).times(direction)), o.min, o.max)
101
+ }
102
+
103
+ /** The decimal places for a unit: the props' (`minFractionDigits`, `maxFractionDigits`), then the app.config's, then
104
+ * the defaults. A minimum above an explicit maximum comes down to it; otherwise the maximum goes up to the minimum. */
105
+ export function resolvePlaces(own: { min?: number, max?: number }, fallback: Places): Places {
106
+ const min = own.min ?? fallback.min
107
+ const max = own.max ?? fallback.max
108
+ if (max === undefined || min <= max) return { min, max }
109
+ return own.max !== undefined ? { min: max, max } : { min, max: min }
110
+ }
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Class strings for Zoo UI's own components — the few things Nuxt UI has no equivalent of: Kicker, Identifier,
3
+ * Status, QuotaMeter, CodeBlock, TokenReveal and EcosystemMark (Slots is Nuxt UI badges, and needs none). Everything
4
+ * else is Nuxt UI's own component, colored by the layer.
5
+ *
6
+ * They are written on Nuxt UI's semantic tokens (text-muted, bg-elevated, border-default …) and its palettes
7
+ * (`--ui-color-<color>-<shade>`), never on raw ramps, so a scheme or a dark-mode switch carries through them as it
8
+ * does through Nuxt UI's components. Where Zoo UI needs more contrast than Nuxt UI's 500/400 text shades give — the
9
+ * status and accent inks, which must clear 4.5:1 — they use 700 in light mode and 300 in dark, as v1 did.
10
+ *
11
+ * One rule keeps them order-independent: never put two utilities for the same property on one element. Tailwind
12
+ * resolves that by its GENERATED order, never by the order the classes are written, so a base string holds only
13
+ * what no variant changes and what varies lives in exactly one map entry. apps/forest runs
14
+ * testing/find-conflicts on every rendered element to hold it.
15
+ */
16
+
17
+ /** Keyboard focus, as Nuxt UI draws it on its own controls. */
18
+ const focus = 'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary'
19
+
20
+ /** Accent ink that clears 4.5:1 on Nuxt UI's surfaces in both themes. */
21
+ const accentText = 'text-(--ui-color-primary-700) dark:text-(--ui-color-primary-300)'
22
+
23
+ export const kicker = {
24
+ base: 'font-mono font-medium text-xs leading-[1.2] tracking-[0.08em] uppercase',
25
+ variant: {
26
+ /** Zoo UI's own: a muted label in primary brackets */
27
+ bracket: "text-muted before:content-['[_'] before:text-primary after:content-['_]'] after:text-primary",
28
+ /** The eyebrow: the label itself in the accent ink, no brackets (they would be a second accent mark) */
29
+ eyebrow: accentText,
30
+ },
31
+ } as const
32
+
33
+ export const ident = {
34
+ /* `kind` owns weight, color, background and padding: plain has no chip */
35
+ base: 'font-mono text-sm leading-[1.3] rounded-sm py-px whitespace-nowrap',
36
+ kind: {
37
+ package: 'font-medium text-highlighted bg-elevated px-1.5',
38
+ version: `font-medium ${accentText} bg-elevated px-1.5`,
39
+ /** never tinted: a hash is read character by character */
40
+ hash: 'font-normal text-highlighted tracking-[0.01em] bg-elevated px-1.5',
41
+ plain: 'font-medium text-highlighted',
42
+ },
43
+ } as const
44
+
45
+ export const status = {
46
+ /* no text-* here: `state` owns the color, `pill` owns the size */
47
+ base: 'inline-flex items-center gap-1.5 font-normal leading-normal whitespace-nowrap',
48
+ size: { plain: 'text-sm', pill: 'text-xs' },
49
+ state: {
50
+ healthy: 'text-default',
51
+ warn: 'text-default',
52
+ suspended: 'text-muted',
53
+ quiet: 'text-muted',
54
+ unreachable: 'text-(--ui-color-error-700) dark:text-(--ui-color-error-300)',
55
+ },
56
+ pill: 'h-[22px] pl-[7px] pr-2 rounded-full bg-elevated ring ring-inset ring-default',
57
+ /** shape carries the state; color only reinforces it, so it survives grayscale */
58
+ glyph: 'flex-none inline-block relative',
59
+ shape: {
60
+ healthy: 'w-2.5 h-2.5 rounded-full bg-success',
61
+ warn: 'w-0 h-0 border-l-[5.5px] border-l-transparent border-r-[5.5px] border-r-transparent border-b-[10px] border-b-warning',
62
+ suspended: 'w-2.5 h-2.5 rounded-[1px] bg-(--ui-color-neutral-500)',
63
+ unreachable: 'w-2.5 h-2.5 rounded-full border-[1.5px] border-dashed border-error box-border',
64
+ quiet: 'w-2.5 h-2.5 rounded-full border-[1.5px] border-(--ui-text-dimmed) box-border',
65
+ },
66
+ /** `glow`: a soft light around the healthy dot, in its own color. Only healthy lights up — a glow
67
+ * says "live", and the other states are the ones that are not. */
68
+ glow: 'shadow-[0_0_12px_var(--ui-success)]',
69
+ } as const
70
+
71
+ export const meter = {
72
+ /* no text-* / no height here: `size` owns both */
73
+ base: 'inline-flex items-center gap-2 font-mono font-normal leading-[1.6] text-muted min-w-0 whitespace-nowrap',
74
+ size: { md: 'text-xs', lg: 'text-sm' },
75
+ track: 'block flex-1 min-w-[60px] rounded-[2px] bg-accented overflow-hidden relative',
76
+ trackSize: { md: 'h-1.5', lg: 'h-2.5' },
77
+ /* the hatch stripes paint in currentColor, so the fill sets a text color for them */
78
+ fill: 'block h-full rounded-[2px] transition-[width] text-white/55 dark:text-black/45',
79
+ level: {
80
+ ok: 'bg-(--ui-color-neutral-700) dark:bg-(--ui-color-neutral-200)',
81
+ warn: 'bg-warning',
82
+ over: 'bg-error hatch',
83
+ },
84
+ mark: 'absolute -top-0.5 -bottom-0.5 w-px bg-(--ui-text-dimmed)',
85
+ value: 'whitespace-nowrap tabular-nums',
86
+ valueLevel: {
87
+ ok: '',
88
+ warn: 'text-(--ui-color-warning-700) dark:text-(--ui-color-warning-300)',
89
+ over: 'text-(--ui-color-error-700) dark:text-(--ui-color-error-300)',
90
+ },
91
+ } as const
92
+
93
+ /** Zoo UI's code surface: near-black in BOTH themes — the one surface that does not follow the page. */
94
+ export const code = {
95
+ wrap: 'relative flex items-start gap-3 py-3 pr-3 pl-4 bg-(--ui-color-neutral-900) dark:bg-(--ui-color-neutral-950) text-(--ui-color-neutral-100) border border-(--ui-color-neutral-700) rounded-md font-mono font-normal text-sm leading-[1.6] [container-type:inline-size]',
96
+ prompt: 'text-(--ui-color-primary-300) select-none flex-none',
97
+ pre: 'm-0 flex-1 min-w-0 overflow-x-auto [font:inherit]',
98
+ lang: 'flex-none order-2 self-center font-mono font-medium text-xs leading-[1.2] tracking-[0.08em] uppercase text-(--ui-color-neutral-400)',
99
+ copy: `appearance-none flex-none order-3 h-6 px-2 inline-flex items-center gap-1.5 bg-transparent border border-(--ui-color-neutral-700) rounded-sm text-(--ui-color-neutral-400) font-sans font-medium text-xs leading-[1.2] cursor-pointer hover:text-(--ui-color-neutral-100) hover:border-(--ui-color-neutral-400) data-[done=true]:text-(--ui-color-primary-300) data-[done=true]:border-(--ui-color-primary-300) ${focus}`,
100
+ /** the secret: one click selects all of it, the fallback when the clipboard refuses */
101
+ tok: 'text-(--ui-color-primary-300) select-all',
102
+ } as const
103
+
104
+ /** The shown-once secret: Zoo UI's code surface for the token, a banner for the warning, Nuxt UI's buttons. */
105
+ export const tokenReveal = {
106
+ root: 'flex flex-col gap-3 min-w-0',
107
+ /* `hidden` owns the filter: after acknowledgment the secret blurs and stops being selectable */
108
+ secret: 'transition-[filter] duration-200',
109
+ hidden: 'blur-sm select-none',
110
+ actions: 'flex flex-wrap items-center gap-2',
111
+ } as const
112
+
113
+ /** Ecosystem monogram tiles: shape (corner geometry) tells them apart, never color. */
114
+ export const eco = {
115
+ /* no text-* color, border color or style here: `state` owns them; `size` owns box, font size and tracking */
116
+ base: 'inline-flex flex-none items-center justify-center box-border border-[1.5px] bg-default font-mono font-semibold leading-none',
117
+ size: {
118
+ sm: 'size-5 text-[9px] tracking-[-0.02em]',
119
+ md: 'size-7 text-[11.5px] tracking-normal',
120
+ lg: 'size-10 text-[15px] tracking-normal',
121
+ },
122
+ state: {
123
+ enabled: 'text-highlighted border-inverted border-solid',
124
+ /** dashed means disabled: not available yet */
125
+ disabled: 'text-muted border-accented border-dashed',
126
+ },
127
+ /** every corner written out: a single `rounded-full` corner would scale its neighbors to zero */
128
+ shape: {
129
+ square: 'rounded-none',
130
+ circle: 'rounded-[50%]',
131
+ leaf: 'rounded-tl-xs rounded-tr-xs rounded-br-[50%] rounded-bl-xs',
132
+ arch: 'rounded-tl-[50%] rounded-tr-[50%] rounded-br-xs rounded-bl-xs',
133
+ lens: 'rounded-tl-[50%] rounded-tr-xs rounded-br-[50%] rounded-bl-xs',
134
+ drop: 'rounded-tl-xs rounded-tr-[50%] rounded-br-[50%] rounded-bl-[50%]',
135
+ rounded: 'rounded-xs',
136
+ },
137
+ wrap: 'inline-flex items-center gap-2 text-sm whitespace-nowrap',
138
+ label: { enabled: 'text-default', disabled: 'text-muted' },
139
+ } as const
140
+
141
+ export const cx = (...parts: (string | false | null | undefined)[]) => parts.filter(Boolean).join(' ')
@@ -0,0 +1,19 @@
1
+ import { Temporal } from 'temporal-polyfill/implementation'
2
+
3
+ /**
4
+ * The USER's today: the calendar day where the person at the keyboard is sitting, from the browser's own time zone.
5
+ * It is what ZDateField means by "today" — the `t` shortcut, a bare "12" typed for the 12th of this month, the month
6
+ * the calendar opens on.
7
+ *
8
+ * Client-only, on purpose. During SSR the only zone available is the server's, which for an evening user in
9
+ * California is already tomorrow; a field that rendered with that would show the wrong day until hydration fixed it,
10
+ * or not at all. ZDateField only asks for today from event handlers and from a popover that opens on a click, both
11
+ * of which run in the browser.
12
+ *
13
+ * Server code that needs "today" for the business — what's overdue, which week a forecast starts — wants the
14
+ * COMPANY's today instead: `Temporal.Now.plainDateISO(companyTimeZone)`, not this.
15
+ */
16
+ export function useToday(): Temporal.PlainDate {
17
+ if (import.meta.server) throw new Error('useToday() reads the browser\'s day; call it from client code only')
18
+ return Temporal.Now.plainDateISO()
19
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Light, dark or system — a view over @nuxtjs/color-mode (Nuxt UI installs it, and it owns the `dark` class and the
3
+ * pre-paint script), kept so callers and ZThemeToggle have one small API.
4
+ *
5
+ * There is no corner dial: geometry is Nuxt UI's, so a product that wants squarer corners sets Nuxt UI's own
6
+ * `--ui-radius`.
7
+ */
8
+ export type ZooTheme = 'light' | 'dark' | 'system'
9
+
10
+ export const ZOO_THEMES = ['light', 'dark', 'system'] as const satisfies readonly ZooTheme[]
11
+
12
+ export function useZooTheme() {
13
+ const colorMode = useColorMode()
14
+
15
+ const theme = computed<ZooTheme>({
16
+ get: () => colorMode.preference as ZooTheme,
17
+ set: (v) => { colorMode.preference = v },
18
+ })
19
+
20
+ function setTheme(v: ZooTheme) {
21
+ theme.value = v
22
+ }
23
+
24
+ return { theme, setTheme }
25
+ }