@zooui/nuxt 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/nuxt.config.ts ADDED
@@ -0,0 +1,93 @@
1
+ // Zoo UI — the BASE layer, `@zooui/nuxt`. Nuxt UI as it ships, Zoo UI's own components (ZKicker, ZIdentifier, ZStatus,
2
+ // ZQuotaMeter, ZCodeBlock, ZTokenReveal, ZEcosystemMark, ZThemeToggle) and its colored-edge wrappers (ZCard, ZModal,
3
+ // ZSlideover, ZDrawer), written on Nuxt UI's semantic tokens so they take whatever colors the product gives Nuxt UI.
4
+ // No colors, typefaces, ground or component restyling: that is a THEME, a layer of its own that extends this one
5
+ // (`@zooui/theme-forest`, Forest). A Forest product extends the theme; a product with its own look extends
6
+ // this base and keeps it.
7
+ // Compare against apps/kitchen-sink (the same specimens with no layer) to see exactly what the theme changes.
8
+ //
9
+ // The STYLESHEET is not registered here on purpose. The app owns its one Tailwind entry and starts it with
10
+ // @import "@zooui/theme-forest/assets/css/forest.css"; (Forest products: base + theme)
11
+ // @import "@zooui/nuxt/assets/css/base.css"; (products with their own look)
12
+ // so it can also add `@source` for component directories outside its own root, and its own tokens after it.
13
+ // Two entries would mean two Tailwind compiles.
14
+ import { fileURLToPath } from 'node:url'
15
+ import { isThemeLayer, stylesheetMismatch } from './stylesheet-guard.js'
16
+
17
+ /** Absolute path inside THIS layer (a relative path would resolve against the app). */
18
+ const resolve = (p: string) => fileURLToPath(new URL(p, import.meta.url))
19
+
20
+ /** The slice of Nuxt the modules below touch, typed here so the layer needs no @nuxt/schema of its own. */
21
+ interface LayerNuxt {
22
+ options: {
23
+ rootDir: string
24
+ css: unknown[]
25
+ alias: Record<string, string>
26
+ _layers: readonly { cwd: string }[]
27
+ optimization: { treeShake: { composables: { client: Record<string, string[]> } } }
28
+ }
29
+ hook(name: 'modules:done', fn: () => void): void
30
+ hook(name: 'icon:clientBundleIcons', fn: (icons: Set<string>) => void): void
31
+ }
32
+
33
+ /** Icons the Z* components render, for the client bundle below. scripts/check-icons.test.mjs keeps it in step with
34
+ * components/. */
35
+ const Z_ICONS = ['lucide:sun', 'lucide:moon', 'lucide:monitor', 'lucide:triangle-alert', 'lucide:check',
36
+ 'lucide:circle-check', 'lucide:pencil', 'lucide:x', 'lucide:trash-2', 'lucide:plus', 'lucide:chevron-up', 'lucide:chevron-down', 'lucide:calendar']
37
+
38
+ export default defineNuxtConfig({
39
+ modules: [
40
+ '@nuxt/ui',
41
+ // Keep `onServerPrefetch` in the CLIENT bundle. A production build strips it there by default, but Vue counts
42
+ // every component that registers one (each UIcon in svg mode) as an async boundary when it hands out useId()
43
+ // ids. Stripped on the client only, the browser counts fewer boundaries than the server, and everything after
44
+ // them gets a different id: hydration re-sets a UInput's id while its UFormField label keeps the server's
45
+ // `for`, so the field loses its name. The hook never runs in the browser; keeping the call keeps the count
46
+ // equal, as it already is under `nuxi dev`. Filtered, not replaced: Nuxt's other tree-shaken composables stay.
47
+ (_options: unknown, nuxt: LayerNuxt) => {
48
+ const client = nuxt.options.optimization.treeShake.composables.client
49
+ if (client.vue) client.vue = client.vue.filter((name) => name !== 'onServerPrefetch')
50
+ },
51
+ // Z* icons in the client bundle, through the hook Nuxt UI uses for its own — so they render without a request
52
+ // to the icon endpoint whatever the product's `icon` options are, and a product's own list is left alone.
53
+ (_options: unknown, nuxt: LayerNuxt) => {
54
+ nuxt.hook('icon:clientBundleIcons', (icons) => { for (const icon of Z_ICONS) icons.add(icon) })
55
+ },
56
+ // The stylesheet and the layers must agree. forest.css is the Forest theme's look, and its app.config half lives in
57
+ // the theme layer; a product that imports forest.css but extends only this base would build in Forest's ramps and
58
+ // typefaces with Nuxt UI's default colors. The reverse — the theme layer over base.css — is half a theme too.
59
+ // Either fails the build, naming the fix. What the CSS brings in is read by following its imports, and the theme
60
+ // layer is recognized by its package name (stylesheet-guard.js).
61
+ (_options: unknown, nuxt: LayerNuxt) => {
62
+ nuxt.hook('modules:done', () => {
63
+ const themed = nuxt.options._layers.some((layer) => isThemeLayer(layer.cwd))
64
+ const mismatch = stylesheetMismatch({ entries: nuxt.options.css, alias: nuxt.options.alias, rootDir: nuxt.options.rootDir, themed })
65
+ if (mismatch) throw new Error(mismatch)
66
+ })
67
+ },
68
+ ],
69
+
70
+ // Z* components, prefixed: <ZCard>, <ZStatus> … — .vue only: edge.ts and recipes.ts are their shared helpers.
71
+ components: [{ path: resolve('./components'), prefix: 'Z', extensions: ['.vue'] }],
72
+
73
+ /**
74
+ * Exactly ONE @tailwindcss/vite, and it is Nuxt UI's (its module registers it). If anything else also registers
75
+ * Tailwind — @nuxtjs/tailwindcss, a hand-added `vite.plugins` entry — the stylesheet is compiled twice. Fail the
76
+ * build loudly: the fix is to remove the second registration. `vite:extendConfig` is where every registration
77
+ * is visible (it runs after all `vite:extend` hooks, where Nuxt UI registers).
78
+ */
79
+ hooks: {
80
+ 'vite:extendConfig'(config) {
81
+ const name = (p: unknown) => (p && typeof p === 'object' ? String((p as { name?: unknown }).name ?? '') : '')
82
+ const counts = new Map<string, number>()
83
+ for (const p of ((config.plugins ?? []) as unknown[]).flat(Infinity)) {
84
+ const n = name(p)
85
+ if (n.startsWith('@tailwindcss/vite')) counts.set(n, (counts.get(n) ?? 0) + 1)
86
+ }
87
+ const dupes = [...counts].filter(([, c]) => c > 1).map(([n, c]) => `${n} ×${c}`)
88
+ if (dupes.length) {
89
+ throw new Error(`[zooui] Tailwind is registered more than once (${dupes.join(', ')}). Nuxt UI registers it; remove the other registration.`)
90
+ }
91
+ },
92
+ },
93
+ })
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
2
  "name": "@zooui/nuxt",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Zoo UI for Nuxt: a theme-free Nuxt layer with Nuxt UI as it ships, Zoo UI's Z* components and colored-edge surfaces, and the mechanisms every product needs, all on Nuxt UI's tokens so they take the product's own colors. Add a theme layer such as @zooui/theme-forest for a ready-made look.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/zooui-dev/zooui.git",
9
+ "directory": "packages/nuxt"
10
+ },
11
+ "homepage": "https://zooui.dev",
12
+ "bugs": {
13
+ "url": "https://github.com/zooui-dev/zooui/issues"
14
+ },
15
+ "type": "module",
16
+ "main": "./nuxt.config.ts",
17
+ "files": [
18
+ "nuxt.config.ts",
19
+ "stylesheet-guard.js",
20
+ "stylesheet-guard.d.ts",
21
+ "assets",
22
+ "components",
23
+ "composables",
24
+ "utils",
25
+ "testing"
26
+ ],
27
+ "exports": {
28
+ ".": "./nuxt.config.ts",
29
+ "./assets/css/*": "./assets/css/*",
30
+ "./date-entry": {
31
+ "types": "./utils/date-entry.ts",
32
+ "default": "./utils/date-entry.ts"
33
+ },
34
+ "./testing/find-conflicts": {
35
+ "types": "./testing/find-conflicts.d.ts",
36
+ "default": "./testing/find-conflicts.js"
37
+ }
38
+ },
39
+ "dependencies": {
40
+ "@iconify-json/lucide": "^1.2.133",
41
+ "@internationalized/date": "^3.12.4",
42
+ "@nuxt/ui": "~4.11.1",
43
+ "decimal.js": "^10.6.0",
44
+ "tailwindcss": "^4.0.0",
45
+ "temporal-polyfill": "^1.0.5"
46
+ },
47
+ "peerDependencies": {
48
+ "nuxt": "^4.1.0",
49
+ "vue": "^3.5.0"
50
+ },
51
+ "devDependencies": {
52
+ "vue": "^3.5.42"
53
+ },
54
+ "engines": {
55
+ "node": ">=22"
56
+ },
57
+ "publishConfig": {
58
+ "access": "public"
59
+ }
6
60
  }
@@ -0,0 +1,12 @@
1
+ export const THEME_PACKAGE: string
2
+ export function packageName(dir: string): string | null
3
+ export function isThemeLayer(dir: string): boolean
4
+ export function cssImports(source: string): string[]
5
+ export function locate(specifier: string, fromDir: string): string | null
6
+ export function reaches(file: string, seen?: Set<string>): { base: boolean; theme: boolean }
7
+ export function stylesheetMismatch(o: {
8
+ entries: readonly unknown[]
9
+ alias: Record<string, string>
10
+ rootDir: string
11
+ themed: boolean
12
+ }): string | null
@@ -0,0 +1,103 @@
1
+ // The check behind the base layer's stylesheet guard (nuxt.config.ts): do the app's CSS entries agree with the layers
2
+ // it extends? The Forest theme comes in two halves, its stylesheet (theme.css, which forest.css imports after the
3
+ // base's base.css) and its layer (`@zooui/theme-forest`, the app.config half), so an app with one and not the other
4
+ // gets half a theme. The CSS side is read by FOLLOWING each entry's active @import rules to the files they resolve to
5
+ // — comments stripped, package specifiers and relative paths resolved as Node would — so what counts is which of the
6
+ // two stylesheets an entry reaches, not how it spells them: `forest.css`, or `base.css` then `theme.css`, are the
7
+ // same thing. The theme is a package of its own that the base does not depend on, so its stylesheet and its layer are
8
+ // recognized by the package they sit in, wherever that is installed. Plain JavaScript, so
9
+ // scripts/check-stylesheet-guard.test.mjs can test it without a build.
10
+ import { existsSync, readFileSync, realpathSync } from 'node:fs'
11
+ import { createRequire } from 'node:module'
12
+ import { dirname, isAbsolute, join, resolve } from 'node:path'
13
+ import { fileURLToPath } from 'node:url'
14
+
15
+ const real = (p) => (existsSync(p) ? realpathSync(p) : p)
16
+ const css = fileURLToPath(new URL('./assets/css/', import.meta.url))
17
+ const BASE = real(join(css, 'base.css'))
18
+
19
+ /** The theme layer the guard knows, and its theme-only stylesheet relative to the package's root. */
20
+ export const THEME_PACKAGE = '@zooui/theme-forest'
21
+ const THEME_STYLESHEET = join('assets', 'css', 'theme.css')
22
+
23
+ /** The `name` in `dir`'s own package.json, or null. */
24
+ export function packageName(dir) {
25
+ const file = join(dir, 'package.json')
26
+ if (!existsSync(file)) return null
27
+ try {
28
+ return JSON.parse(readFileSync(file, 'utf8')).name ?? null
29
+ } catch {
30
+ return null
31
+ }
32
+ }
33
+
34
+ /** Whether a layer's directory is the theme layer's. */
35
+ export const isThemeLayer = (dir) => packageName(dir) === THEME_PACKAGE
36
+
37
+ /** Whether a (real) path is the theme's stylesheet: assets/css/theme.css in the theme package. */
38
+ function isThemeStylesheet(path) {
39
+ const root = resolve(dirname(path), '..', '..')
40
+ return join(root, THEME_STYLESHEET) === path && isThemeLayer(root)
41
+ }
42
+
43
+ /** The targets of a stylesheet's active @import rules: commented-out ones are not imports. */
44
+ export function cssImports(source) {
45
+ return [...source.replace(/\/\*[\s\S]*?\*\//g, '').matchAll(/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)].map((m) => m[1])
46
+ }
47
+
48
+ /** A specifier as Node resolves it from `fromDir` (a relative or absolute path, or a package's export), or null. */
49
+ export function locate(specifier, fromDir) {
50
+ if (specifier.startsWith('.') || isAbsolute(specifier)) return resolve(fromDir, specifier)
51
+ try {
52
+ return createRequire(join(fromDir, 'index.js')).resolve(specifier)
53
+ } catch {
54
+ return null
55
+ }
56
+ }
57
+
58
+ /** Which of the two stylesheets (the base's base.css, the theme's theme.css) a CSS file reaches through its @imports, at any depth. */
59
+ export function reaches(file, seen = new Set()) {
60
+ const out = { base: false, theme: false }
61
+ const path = real(file)
62
+ if (seen.has(path) || !path.endsWith('.css') || !existsSync(path)) return out
63
+ seen.add(path)
64
+ if (path === BASE) out.base = true
65
+ if (isThemeStylesheet(path)) out.theme = true
66
+ for (const specifier of cssImports(readFileSync(path, 'utf8'))) {
67
+ const target = locate(specifier, dirname(path))
68
+ if (!target) continue
69
+ const r = reaches(target, seen)
70
+ out.base ||= r.base
71
+ out.theme ||= r.theme
72
+ }
73
+ return out
74
+ }
75
+
76
+ /**
77
+ * The guard's verdict: an error message, or null when the CSS and the layers agree (or the CSS reaches neither of the
78
+ * two stylesheets, which says nothing either way). `entries` are the app's `css` entries as written; `alias` is
79
+ * Nuxt's alias map (`~`, `@` …), and `themed` whether the app extends the theme layer.
80
+ */
81
+ export function stylesheetMismatch({ entries, alias, rootDir, themed }) {
82
+ const aliases = Object.entries(alias).sort(([a], [b]) => b.length - a.length)
83
+ const file = (entry) => {
84
+ const hit = aliases.find(([a]) => entry === a || entry.startsWith(`${a}/`))
85
+ return hit ? hit[1] + entry.slice(hit[0].length) : locate(entry, rootDir)
86
+ }
87
+ const seen = { base: [], theme: [] }
88
+ for (const entry of entries) {
89
+ if (typeof entry !== 'string') continue
90
+ const path = file(entry)
91
+ if (!path) continue
92
+ const r = reaches(path)
93
+ if (r.base) seen.base.push(entry)
94
+ if (r.theme) seen.theme.push(entry)
95
+ }
96
+ if (!themed && seen.theme.length) {
97
+ return `[zooui] ${seen.theme[0]} brings in the Forest theme's look (theme.css), but the app extends only the base layer. Extend '${THEME_PACKAGE}' instead of '@zooui/nuxt', or import '@zooui/nuxt/assets/css/base.css' for a product with its own look.`
98
+ }
99
+ if (themed && seen.base.length && !seen.theme.length) {
100
+ return `[zooui] The app extends '${THEME_PACKAGE}', but ${seen.base[0]} imports base.css, which has none of the Forest theme's colors or typefaces. Import '${THEME_PACKAGE}/assets/css/forest.css' instead.`
101
+ }
102
+ return null
103
+ }
@@ -0,0 +1,2 @@
1
+ /** Runs in the page (pass it to `page.evaluate`). Returns one line per conflicting class pair. */
2
+ export declare function findConflicts(): string[]
@@ -0,0 +1,103 @@
1
+ // Guard for the bug class behind 1.6.0 and 1.6.1: two utilities on one element setting the same
2
+ // property in the same context. Tailwind resolves that by its GENERATED order (colors sort
3
+ // alphabetically, spacing numerically) — never by the order the classes are written — so
4
+ // `text-fg-muted` silently beat `text-fg` and `border-transparent` beat `border-border-strong`.
5
+ //
6
+ // It reads the real built stylesheet, maps every class to {context → properties}, and flags an
7
+ // element carrying two classes whose property sets are IDENTICAL in the same context (context =
8
+ // the selector with the class removed, plus enclosing @media/@container/@supports). Identical sets
9
+ // is deliberate: Tailwind's designed pairs — `p-0 px-3`, `text-sm leading-code`, `border border-b-2`
10
+ // — set different properties and are ordered on purpose. Also flagged: a `font` shorthand next to
11
+ // any font longhand (a type-* composite stacked with a size/weight/family/leading utility), and
12
+ // any `all` reset.
13
+ //
14
+ // Shared: the layer's test apps and every Zoo UI product run it. In a Playwright test:
15
+ // import { findConflicts } from '@zooui/nuxt/testing/find-conflicts'
16
+ // expect(await page.evaluate(findConflicts)).toEqual([])
17
+ // It runs INSIDE the page (page.evaluate serializes it), so it must stay self-contained — no imports.
18
+ //
19
+ // Plain JavaScript, not TypeScript: a consumer loads it from node_modules, where Node will not strip types
20
+ // ("Stripping types is currently unsupported for files under node_modules"). Types: find-conflicts.d.ts.
21
+ /** Runs in the page. Returns one line per conflicting pair. */
22
+ export function findConflicts() {
23
+ const byClass = new Map();
24
+ const unescape = (s) => s.replace(/\\(.)/g, '$1');
25
+ const walk = (rules, at) => {
26
+ for (const r of rules) {
27
+ if (r instanceof CSSStyleRule) {
28
+ for (const sel of r.selectorText.split(/,(?![^(]*\))/)) {
29
+ const m = sel.trim().match(/^\.((?:\\.|[^\s.:[#>+~,()\\])+)(.*)$/);
30
+ if (!m)
31
+ continue;
32
+ // Tailwind's own --tw-* variables stay IN the signature: shadow-sm and ring-0 both write
33
+ // box-shadow, but through the shared formula, one via --tw-shadow and one via
34
+ // --tw-ring-shadow — they compose, so their signatures must differ. Other custom
35
+ // properties (tokens, --radius-* re-declarations) are not what a conflict is about.
36
+ const props = [...r.style].filter((p) => !p.startsWith('--') || p.startsWith('--tw-'));
37
+ // A `font:` shorthand (a type-* composite) is recognized by what it SETS as well as by "font:"
38
+ // in cssText: with var() values plus a later font-feature-settings, the browser serializes
39
+ // the rule as longhands and the text "font:" disappears (core 1.9.3 gave composites a set).
40
+ const decl = r.style.cssText;
41
+ if (/(^|;\s*)font\s*:/.test(decl) || (props.includes('font-family') && props.includes('font-size') && props.includes('line-height')))
42
+ props.push('font(shorthand)');
43
+ if (!props.length)
44
+ continue;
45
+ // One entry per (class, context), with the UNION of its properties: the minifier merges
46
+ // identical declarations across selectors (`.border-2,.border-[1.5px]{border-style:…}`),
47
+ // splitting one utility over several rules — compared rule by rule, border-[1.5px] looked
48
+ // like a style-only utility and collided with border-dashed.
49
+ const cls = unescape(m[1]);
50
+ const ctx = [...at, m[2] ?? ''].join(' | ');
51
+ const list = byClass.get(cls) ?? [];
52
+ const entry = list.find((e) => e.ctx === ctx);
53
+ if (entry)
54
+ entry.props = [...new Set([...entry.props, ...props])].sort();
55
+ else
56
+ list.push({ ctx, props });
57
+ byClass.set(cls, list);
58
+ }
59
+ if (r.cssRules?.length)
60
+ walk(r.cssRules, [...at, '&' + r.selectorText]);
61
+ }
62
+ else if ('cssRules' in r) {
63
+ const cond = r instanceof CSSLayerBlockRule ? null
64
+ : r.conditionText ?? r.cssText.slice(0, r.cssText.indexOf('{'));
65
+ walk(r.cssRules, cond ? [...at, cond] : at);
66
+ }
67
+ }
68
+ };
69
+ for (const sheet of document.styleSheets) {
70
+ try {
71
+ walk(sheet.cssRules, []);
72
+ }
73
+ catch { /* cross-origin */ }
74
+ }
75
+ const FONT_LONGHANDS = ['font-size', 'font-weight', 'font-family', 'line-height', 'font-style'];
76
+ const out = new Set();
77
+ for (const el of document.querySelectorAll('[class]')) {
78
+ const classes = [...el.classList].filter((c) => byClass.has(c));
79
+ for (const c of classes) {
80
+ for (const e of byClass.get(c))
81
+ if (e.props.includes('all'))
82
+ out.add(`[all] ${c}`);
83
+ }
84
+ for (let i = 0; i < classes.length; i++) {
85
+ for (let j = i + 1; j < classes.length; j++) {
86
+ for (const a of byClass.get(classes[i])) {
87
+ for (const b of byClass.get(classes[j])) {
88
+ if (a.ctx !== b.ctx)
89
+ continue;
90
+ const same = a.props.join() === b.props.join();
91
+ const stacked = (a.props.includes('font(shorthand)') && b.props.some((p) => FONT_LONGHANDS.includes(p)))
92
+ || (b.props.includes('font(shorthand)') && a.props.some((p) => FONT_LONGHANDS.includes(p)));
93
+ if (same || stacked) {
94
+ const where = el.id ? `#${el.id}` : `<${el.tagName.toLowerCase()} class="${el.className}">`.slice(0, 140);
95
+ out.add(`${classes[i]} × ${classes[j]} [${a.props.join(',')}]${a.ctx.trim() ? ` in "${a.ctx.trim()}"` : ''} on ${where}`);
96
+ }
97
+ }
98
+ }
99
+ }
100
+ }
101
+ }
102
+ return [...out];
103
+ }
@@ -0,0 +1,245 @@
1
+ // What a person types into a date field, turned into a calendar day — and the one-key shortcuts that move it. The
2
+ // parsing behind <ZDateField>, with the field order and
3
+ // separator made a parameter: MM/DD/YYYY is one format among several, and the default for every function
4
+ // here.
5
+ //
6
+ // NO JAVASCRIPT `Date` HERE, and no clock. A `Date` is an instant, not a day: turning one into "the 12th" goes
7
+ // through a time zone, and every place that happens is a chance for a due date to land on the 11th. Everything
8
+ // below is Temporal.PlainDate arithmetic, and "today" is always handed in by the caller (the browser's own day,
9
+ // see composables/useToday.ts), so these functions give the same answer on any machine at any hour and are
10
+ // testable with a fixed today.
11
+ //
12
+ // Framework-free: Nuxt auto-imports it in a product, and `@zooui/nuxt/date-entry` imports it anywhere else (a
13
+ // server route, a domain package). Temporal is the polyfill's own `/implementation`, never the bare entry, which
14
+ // resolves to `globalThis.Temporal` where an engine has one: one class wherever this runs, the same one
15
+ // a database client or serializer in the product hands out.
16
+ import { Temporal } from 'temporal-polyfill/implementation'
17
+
18
+ type PlainDate = Temporal.PlainDate
19
+
20
+ /** The order a format writes a day's fields in: month-day-year (US), day-month-year, or year-month-day (ISO). */
21
+ export type DateEntryOrder = 'MDY' | 'DMY' | 'YMD'
22
+
23
+ /** How a field writes a day and reads one back. Make one with dateEntryFormat('DD.MM.YYYY'); every function here
24
+ * also takes the pattern string itself. */
25
+ export interface DateEntryFormat {
26
+ /** The pattern it was made from, `MM/DD/YYYY` — what the field shows as its placeholder. */
27
+ readonly pattern: string
28
+ readonly order: DateEntryOrder
29
+ /** The one character between the fields. */
30
+ readonly separator: string
31
+ }
32
+
33
+ const ORDERS: readonly DateEntryOrder[] = ['MDY', 'DMY', 'YMD']
34
+ const TOKEN = { MM: 'M', DD: 'D', YYYY: 'Y' } as const
35
+ const PATTERN = /^(MM|DD|YYYY)(.)(MM|DD|YYYY)\2(MM|DD|YYYY)$/u
36
+ const formats = new Map<string, DateEntryFormat>()
37
+
38
+ /**
39
+ * A format from its pattern: `MM`, `DD` and `YYYY` in month-day-year, day-month-year or year-month-day order, with
40
+ * one separator between them that isn't a letter, a digit or a space — `MM/DD/YYYY`, `DD/MM/YYYY`, `DD.MM.YYYY`,
41
+ * `YYYY-MM-DD`. Throws a RangeError for anything else.
42
+ */
43
+ export function dateEntryFormat(pattern: string): DateEntryFormat {
44
+ const cached = formats.get(pattern)
45
+ if (cached) return cached
46
+ const match = PATTERN.exec(pattern)
47
+ const order = match && [match[1], match[3], match[4]].map((t) => TOKEN[t as keyof typeof TOKEN]).join('')
48
+ const separator = match?.[2] ?? ''
49
+ if (!match || !ORDERS.includes(order as DateEntryOrder) || /[\p{L}\p{N}\s]/u.test(separator)) {
50
+ throw new RangeError(`Not a date entry format: "${pattern}". Use MM, DD and YYYY in MDY, DMY or YMD order with one separator between them, such as "MM/DD/YYYY", "DD.MM.YYYY" or "YYYY-MM-DD".`)
51
+ }
52
+ const format = Object.freeze({ pattern, order: order as DateEntryOrder, separator })
53
+ formats.set(pattern, format)
54
+ return format
55
+ }
56
+
57
+ /** The US format, and the default wherever a format is optional: MM/DD/YYYY. */
58
+ export const US_DATE_ENTRY = dateEntryFormat('MM/DD/YYYY')
59
+
60
+ const formatOf = (f: DateEntryFormat | string) => (typeof f === 'string' ? dateEntryFormat(f) : f)
61
+
62
+ /**
63
+ * The format a locale writes a numeric date in, from Intl: `en` and `en-US` MM/DD/YYYY, `en-GB` and `fr`
64
+ * DD/MM/YYYY, `de` DD.MM.YYYY, `nl` DD-MM-YYYY, `sv` and `en-CA` YYYY-MM-DD, `ja` YYYY/MM/DD. Only the order of the
65
+ * fields and the first separator are taken (spaces and direction marks dropped: `ko` writes "2026. 11. 13.", which
66
+ * reads as YYYY.MM.DD); a locale whose separator isn't one character gets `/`, and one whose order isn't MDY, DMY
67
+ * or YMD gets MM/DD/YYYY.
68
+ */
69
+ export function dateEntryFormatFor(locale: string): DateEntryFormat {
70
+ // Intl formats an instant, so it is handed the number 0 in UTC rather than a Date: only the parts' order and the
71
+ // text between them are read, never the day they name.
72
+ const parts = new Intl.DateTimeFormat(locale, { year: 'numeric', month: '2-digit', day: '2-digit', timeZone: 'UTC' }).formatToParts(0)
73
+ const order = parts.flatMap((p) => (p.type === 'year' ? 'Y' : p.type === 'month' ? 'M' : p.type === 'day' ? 'D' : [])).join('')
74
+ if (!ORDERS.includes(order as DateEntryOrder)) return US_DATE_ENTRY
75
+ const literal = parts.find((p) => p.type === 'literal')?.value.replace(/[\s‎‏؜]/gu, '') ?? ''
76
+ const separator = [...literal].length === 1 && !/[\p{L}\p{N}]/u.test(literal) ? literal : '/'
77
+ const token = { M: 'MM', D: 'DD', Y: 'YYYY' } as const
78
+ return dateEntryFormat([...order].map((c) => token[c as keyof typeof token]).join(separator))
79
+ }
80
+
81
+ // A calendar day from parts, or null when there is no such day (month 13, Feb 30, Apr 31).
82
+ function dayOf(year: number, month: number, day: number): PlainDate | null {
83
+ if (!Number.isInteger(year) || year < 1 || year > 9999) return null
84
+ if (!Number.isInteger(month) || month < 1 || month > 12) return null
85
+ const first = Temporal.PlainDate.from({ year, month, day: 1 })
86
+ if (!Number.isInteger(day) || day < 1 || day > first.daysInMonth) return null
87
+ return first.with({ day })
88
+ }
89
+
90
+ // A one- or two-digit year lands within the 100 years ending 20 years from now: in 2026, "46" is 2046 and "47"
91
+ // is 1947. Far enough ahead for a loan's maturity date, near enough back for a building's year. A year of all
92
+ // zeros ("0", "00", "0000") is no year at all: never 2000.
93
+ function fullYear(digits: string, today: PlainDate): number | null {
94
+ if (/^0+$/.test(digits)) return null
95
+ if (digits.length === 4) return Number(digits) >= 1000 ? Number(digits) : null
96
+ if (digits.length > 2) return null
97
+ const century = Math.floor(today.year / 100) * 100
98
+ const year = century + Number(digits)
99
+ if (year > today.year + 20) return year - 100
100
+ if (year <= today.year - 80) return year + 100
101
+ return year
102
+ }
103
+
104
+ const DIGITS = /^\d{1,2}$/
105
+
106
+ // The day named by `parts`, written in the format's order: three parts with the year, or two without it (then
107
+ // the year is today's, wherever the format puts it — so in YYYY-MM-DD, "5-12" is May 12).
108
+ function dayFromParts(order: DateEntryOrder, parts: string[], today: PlainDate): PlainDate | null {
109
+ const fields = parts.length === 2 ? order.replace('Y', '') : order
110
+ if (parts.length !== fields.length) return null
111
+ const part = (field: 'M' | 'D' | 'Y') => parts[fields.indexOf(field)] ?? ''
112
+ const month = part('M')
113
+ const day = part('D')
114
+ if (!DIGITS.test(month) || !DIGITS.test(day)) return null
115
+ if (parts.length === 2) return dayOf(today.year, Number(month), Number(day))
116
+ if (!/^\d+$/.test(part('Y'))) return null
117
+ const year = fullYear(part('Y'), today)
118
+ return year === null ? null : dayOf(year, Number(month), Number(day))
119
+ }
120
+
121
+ /**
122
+ * Parse what was typed into a date field. Digits and the format's separator only; anything else is not a date.
123
+ * In MM/DD/YYYY (the default):
124
+ *
125
+ * - `5`, `12` (up to 31) — that day of today's month
126
+ * - `0512` — May 12 this year; `051226` — May 12, 2026
127
+ * - `5/12` — this year; `5/12/26`, `5/12/2026`
128
+ *
129
+ * Other formats read the same shapes in their own order: in DD/MM/YYYY `1205` and `12/5` are May 12, and
130
+ * `120526` is May 12, 2026; in YYYY-MM-DD `0512` and `5-12` are May 12 and `260512` and `2026-5-12` carry the year.
131
+ * A bare day of the month reads the same in all of them. Returns null for anything that doesn't name a real day,
132
+ * including blank text and a year of all zeros (`5/12/0`, `5/12/00`, `051200`).
133
+ */
134
+ export function parseDateEntry(text: string, today: PlainDate, format: DateEntryFormat | string = US_DATE_ENTRY): PlainDate | null {
135
+ const { order, separator } = formatOf(format)
136
+ const value = text.trim()
137
+ if (!value || [...value].some((c) => c !== separator && !/\d/.test(c))) return null
138
+
139
+ if (value.includes(separator)) return dayFromParts(order, value.split(separator), today)
140
+
141
+ if (Number(value) === 0) return null
142
+ if (value.length === 1 || (value.length === 2 && Number(value) <= 31))
143
+ return dayOf(today.year, today.month, Number(value))
144
+ if (value.length === 4) return dayFromParts(order, [value.slice(0, 2), value.slice(2, 4)], today)
145
+ if (value.length === 6) return dayFromParts(order, [value.slice(0, 2), value.slice(2, 4), value.slice(4, 6)], today)
146
+ return null
147
+ }
148
+
149
+ // The days a field can show and read back. formatDateEntry writes a four-digit year and parseDateEntry only reads
150
+ // four-digit years from 1000 (a typed "0026" is far likelier a slip than the year 26), so a date outside these
151
+ // would be shown, then cleared on blur as not a date.
152
+ export const FIRST_ENTRY_DATE = Temporal.PlainDate.from({ year: 1000, month: 1, day: 1 })
153
+ export const LAST_ENTRY_DATE = Temporal.PlainDate.from({ year: 9999, month: 12, day: 31 })
154
+
155
+ /**
156
+ * An ISO day as it may be stored from outside a date field (an import): the day as `YYYY-MM-DD` when a field can show
157
+ * and read it back, else null. Text that names no day (`05/12/2026`, `2026-02-30`) is null too, so one bad cell
158
+ * doesn't abort an import; what Temporal does read (`20260512`, `2026-05-12T10:00`) comes back in the canonical form. A
159
+ * year before 1000 in a file is far likelier a slip than a real date, and stored, it would sit in a field that couldn't
160
+ * be edited back to it.
161
+ */
162
+ export function entryDay(iso: string | null | undefined): string | null {
163
+ if (!iso) return null
164
+ let day: PlainDate
165
+ try {
166
+ day = Temporal.PlainDate.from(iso)
167
+ } catch (e) {
168
+ if (e instanceof RangeError) return null
169
+ throw e
170
+ }
171
+ return Temporal.PlainDate.compare(day, FIRST_ENTRY_DATE) < 0 || Temporal.PlainDate.compare(day, LAST_ENTRY_DATE) > 0
172
+ ? null
173
+ : day.toString()
174
+ }
175
+
176
+ /** The day in the format (MM/DD/YYYY by default), zero-padded — the form parseDateEntry reads back. Empty for no date. */
177
+ export function formatDateEntry(d: PlainDate | null | undefined, format: DateEntryFormat | string = US_DATE_ENTRY): string {
178
+ if (!d) return ''
179
+ const { order, separator } = formatOf(format)
180
+ const pad = (n: number, w: number) => String(n).padStart(w, '0')
181
+ const field = { M: pad(d.month, 2), D: pad(d.day, 2), Y: pad(d.year, 4) }
182
+ return [...order].map((c) => field[c as keyof typeof field]).join(separator)
183
+ }
184
+
185
+ /**
186
+ * The date a field holds once its text is committed: `current` while the text is still what formatDateEntry drew
187
+ * for it, else what parseDateEntry reads (null for blank or not a date). Passing through a field without editing
188
+ * never changes its date, even one parseDateEntry can't read back, such as a stored year before 1000.
189
+ */
190
+ export function commitDateEntry(text: string, current: PlainDate | null, today: PlainDate, format: DateEntryFormat | string = US_DATE_ENTRY): PlainDate | null {
191
+ const typed = text.trim()
192
+ if (typed === formatDateEntry(current, format)) return current
193
+ return typed ? parseDateEntry(typed, today, format) : null
194
+ }
195
+
196
+ /**
197
+ * The date a one-key shortcut moves to, or null when `key` isn't a shortcut (so the key types as usual).
198
+ * `current` is the field's date, or null when it is empty — then the shortcut works from today.
199
+ *
200
+ * - `t` today
201
+ * - `m` first of the month; on the 1st already, the first of the month before
202
+ * - `h` last of the month; on the last already, the last of the month after
203
+ * - `y` January 1; on Jan 1 already, the year before's
204
+ * - `r` December 31; on Dec 31 already, the year after's
205
+ * - `+` or `=` next day, `-` or `_` previous day
206
+ *
207
+ * The format's separator is never a shortcut, so it can be typed: in YYYY-MM-DD, `-` writes a dash and `_` is the
208
+ * previous day.
209
+ *
210
+ * Pressing m, h, y or r again keeps walking, so "hhh" is the end of the month after next. The walk stops at
211
+ * FIRST_ENTRY_DATE and LAST_ENTRY_DATE, so a shortcut never lands on a day the field can't read back.
212
+ */
213
+ export function applyDateShortcut(key: string, current: PlainDate | null, today: PlainDate, format: DateEntryFormat | string = US_DATE_ENTRY): PlainDate | null {
214
+ if (key === formatOf(format).separator) return null
215
+ const next = shortcutTarget(key, current ?? today, today)
216
+ if (!next) return null
217
+ if (Temporal.PlainDate.compare(next, FIRST_ENTRY_DATE) < 0) return FIRST_ENTRY_DATE
218
+ if (Temporal.PlainDate.compare(next, LAST_ENTRY_DATE) > 0) return LAST_ENTRY_DATE
219
+ return next
220
+ }
221
+
222
+ function shortcutTarget(key: string, base: PlainDate, today: PlainDate): PlainDate | null {
223
+ switch (key.toLowerCase()) {
224
+ case 't':
225
+ return today
226
+ case 'm':
227
+ return (base.day === 1 ? base.subtract({ days: 1 }) : base).with({ day: 1 })
228
+ case 'h': {
229
+ const month = base.day === base.daysInMonth ? base.add({ days: 1 }) : base
230
+ return month.with({ day: month.daysInMonth })
231
+ }
232
+ case 'y':
233
+ return (base.month === 1 && base.day === 1 ? base.subtract({ days: 1 }) : base).with({ month: 1, day: 1 })
234
+ case 'r':
235
+ return (base.month === 12 && base.day === 31 ? base.add({ days: 1 }) : base).with({ month: 12, day: 31 })
236
+ case '+':
237
+ case '=':
238
+ return base.add({ days: 1 })
239
+ case '-':
240
+ case '_':
241
+ return base.subtract({ days: 1 })
242
+ default:
243
+ return null
244
+ }
245
+ }
@@ -0,0 +1,23 @@
1
+ // "Nothing selected", as a value a select can actually hold. Named so it
2
+ // can sit in an auto-import list beside every other name a product has: `NONE` and `orNull` are not
3
+ // something to claim globally.
4
+ //
5
+ // reka-ui THROWS if a SelectItem carries `value=""` — it reserves the empty string for "no selection, show
6
+ // the placeholder", so an explicit "No project" option cannot use it. The throw happens during render, which
7
+ // aborts the patch: the practical symptom is not an error anyone sees but a modal that will not close and a
8
+ // field that appears to reset itself. (Nuxt UI's USelect and USelectMenu are built on reka-ui.)
9
+ //
10
+ // So the option travels as this sentinel and is translated back at the edge, where the API wants either a
11
+ // uuid or nothing at all.
12
+ //
13
+ // Framework-free: Nuxt auto-imports it in a product.
14
+ export const SELECT_NONE = '__none__'
15
+
16
+ /** The value to send for a select whose "none" option is chosen. */
17
+ export const selectNoneToUndefined = (v: string | undefined | null) => (!v || v === SELECT_NONE ? undefined : v)
18
+
19
+ /** The same, for update endpoints where clearing a field means an explicit null. */
20
+ export const selectNoneToNull = (v: string | undefined | null) => (!v || v === SELECT_NONE ? null : v)
21
+
22
+ /** What to show in the box for a value that may be absent. */
23
+ export const emptyToSelectNone = (v: string | undefined | null) => v || SELECT_NONE