@zooui/nuxt 0.1.0 → 0.2.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/README.md +50 -439
- package/components/DateField.vue +163 -37
- package/package.json +1 -1
- package/utils/date-entry.ts +180 -6
package/README.md
CHANGED
|
@@ -4,473 +4,84 @@ Zoo UI's theme-free Nuxt layer: **Nuxt UI exactly as it ships**, Zoo UI's `Z*` c
|
|
|
4
4
|
equivalent of, colored-edge surfaces, and the mechanisms every product needs. It has no look of its own: everything
|
|
5
5
|
is written on Nuxt UI's semantic tokens, so it takes the product's colors, typefaces and color-mode key.
|
|
6
6
|
|
|
7
|
-
For a ready-made look, extend a theme layer instead
|
|
8
|
-
extends this layer with its colors, ground, typefaces and schemes.
|
|
9
|
-
component geometry stay Nuxt UI's in both: anything beyond that is added one deliberate decision at a time, judged
|
|
10
|
-
against the untouched baseline in `../../apps/kitchen-sink`.
|
|
11
|
-
|
|
12
|
-
```bash
|
|
13
|
-
pnpm base:dev # → http://localhost:3004 — this layer alone, in a product's own look
|
|
14
|
-
pnpm base:build && pnpm base:test
|
|
15
|
-
pnpm ks:dev # → http://localhost:3003 — the baseline: Nuxt UI as it ships
|
|
16
|
-
```
|
|
7
|
+
For a ready-made look, extend a theme layer instead: Forest, [`@zooui/theme-forest`](https://github.com/zooui-dev/zooui/blob/main/packages/theme-forest/README.md),
|
|
8
|
+
extends this layer with its colors, ground, typefaces and schemes.
|
|
17
9
|
|
|
18
10
|
## Using it
|
|
19
11
|
|
|
20
|
-
|
|
21
|
-
|
|
12
|
+
```bash
|
|
13
|
+
pnpm add @zooui/nuxt
|
|
14
|
+
```
|
|
22
15
|
|
|
23
16
|
```ts
|
|
24
|
-
// nuxt.config.ts
|
|
17
|
+
// nuxt.config.ts
|
|
25
18
|
export default defineNuxtConfig({
|
|
26
19
|
extends: ['@zooui/nuxt'],
|
|
27
20
|
css: ['~/assets/css/main.css'],
|
|
28
21
|
colorMode: { preference: 'light', fallback: 'light', storageKey: 'product-color-mode' },
|
|
29
|
-
icon: { mode: 'svg', clientBundle: { scan: true, icons: [/* the app's own */] } },
|
|
30
22
|
})
|
|
31
23
|
```
|
|
32
24
|
|
|
33
25
|
```css
|
|
34
26
|
/* app/assets/css/main.css — the app's one Tailwind entry */
|
|
35
27
|
@import "@zooui/nuxt/assets/css/base.css";
|
|
36
|
-
@theme
|
|
37
|
-
@utility section-label { /* … */ }
|
|
38
|
-
@layer base { [data-accent='teal'] { --a-600: var(--color-teal-600); /* … */ } }
|
|
28
|
+
/* the product's own @theme tokens, @utility and @layer base rules go after it */
|
|
39
29
|
```
|
|
40
30
|
|
|
41
31
|
The palette goes in the product's `app.config.ts` (`ui.colors: { primary: 'sky', neutral: 'slate', … }`), as with
|
|
42
|
-
plain Nuxt UI.
|
|
43
|
-
compile, and the product's `@theme` overrides Tailwind's own tokens there.
|
|
44
|
-
|
|
45
|
-
The layer registers Nuxt UI but **not** the stylesheet: the app owns its single Tailwind entry so it can add
|
|
46
|
-
`@source` for components outside its root (and, on a theme, pick a scheme). Two entries would mean two Tailwind
|
|
47
|
-
compiles. `apps/forest` shows why it matters: its specimens come from `../../apps/kitchen-sink`, and until it
|
|
48
|
-
declared `@source` for them the page had the right colors and no spacing at all.
|
|
49
|
-
|
|
50
|
-
Do **not** add `@nuxt/ui`, `tailwindcss` or `@tailwindcss/vite` to a product: the layer owns them, and a second
|
|
51
|
-
Tailwind registration fails the build. Wrap the app in `<UApp>`: Nuxt UI mounts toasts, tooltips and overlays
|
|
52
|
-
through it. `../../apps/base` is this layer in a product with its own look; `../../apps/starter` is the smallest product
|
|
53
|
-
on Forest.
|
|
54
|
-
|
|
55
|
-
## The base and a theme
|
|
56
|
-
|
|
57
|
-
| | Base — `@zooui/nuxt`, `base.css` | Theme — `@zooui/theme-forest`, `theme.css` |
|
|
58
|
-
| --- | --- | --- |
|
|
59
|
-
| Nuxt UI | registered (the one Tailwind registration, and the guard against a second) | — |
|
|
60
|
-
| Components | every `Z*` component, on Nuxt UI's semantic tokens | — |
|
|
61
|
-
| Colors | none: Nuxt UI's defaults until the product's `ui.colors` | `ui.colors` → Forest's palettes; ramps, schemes, per-scheme success/info |
|
|
62
|
-
| Typefaces | none: `@nuxt/fonts` on, as Nuxt UI ships | `ui.fonts: false`; Inter and JetBrains Mono (fontsource), behind the six `--zoo-font-*` / `--zoo-features-*` hooks |
|
|
63
|
-
| Ground | Nuxt UI's (`--ui-bg`) | Forest's paper under light pages |
|
|
64
|
-
| Nuxt UI restyling | none | mono badges, kbd and table headers; striped alerts; toast edges, no progress bar; nu-grid |
|
|
65
|
-
| Color mode | untouched: the product's key and default | `storageKey: 'zooui-color-mode'` |
|
|
66
|
-
| Also | `color-scheme` on the root, `data-accent` roles, `hatch`, the SSR label fix, Z\* icons bundled, `testing/find-conflicts` | — |
|
|
67
|
-
|
|
68
|
-
**Why two layers, not an option.** Nuxt merges every layer's `app.config` into the product's, and a product's
|
|
69
|
-
app.config can override a key but never remove one: a base that carried Forest's `ui.colors` or its alert restyling
|
|
70
|
-
would carry them into every product, and a product could only paint over them one key at a time. A module option
|
|
71
|
-
could not help either — the theme is mostly app.config and CSS, which are merged, not executed. So the theme is a
|
|
72
|
-
layer of its own that extends the base, and adding it (or not) is the whole choice. The CSS splits the same way:
|
|
73
|
-
`forest.css` is `base.css` then `theme.css`.
|
|
74
|
-
|
|
75
|
-
**The layer and the stylesheet must agree**, and the base fails the build if they don't: an app whose CSS imports
|
|
76
|
-
`forest.css` but extends only the base
|
|
77
|
-
would get Forest's typefaces and ramps with Nuxt UI's default colors, and the theme layer over `base.css` is half a
|
|
78
|
-
theme too. The error names the fix. The guard follows each `css` entry's active `@import` rules (comments aside) to
|
|
79
|
-
the files they resolve to, package specifiers included, so it judges what the CSS reaches, not how it is spelled:
|
|
80
|
-
`base.css` then `theme.css` counts as `forest.css` (`stylesheet-guard.js`, tested by
|
|
81
|
-
`scripts/check-stylesheet-guard.test.mjs`).
|
|
82
|
-
|
|
83
|
-
**Z\* components in a product's colors.** They are written on Nuxt UI's semantic tokens and palettes (`text-muted`,
|
|
84
|
-
`bg-elevated`, `--ui-color-primary-700` …), never on a theme's ramps, so on the base they take the product's primary,
|
|
85
|
-
neutral and status colors, in both modes. Where they set a value in mono (`ZKicker`, `ZIdentifier`, `ZCodeBlock`,
|
|
86
|
-
`ZQuotaMeter`, `ZEcosystemMark`) they use `font-mono`, which on the base is Tailwind's system mono stack
|
|
87
|
-
(`ui-monospace, …`) — the product's, if it sets `--font-mono`. `ZTokenReveal`'s warning is Nuxt UI's outline alert,
|
|
88
|
-
unstriped. `../../apps/base` is the base in a product with its own look, and its tests hold all of this.
|
|
89
|
-
|
|
90
|
-
## Per-section accent (`data-accent`)
|
|
91
|
-
|
|
92
|
-
A product can paint each section in its own hue: `data-accent="teal"` on a container, and everything inside reads
|
|
93
|
-
six **roles** instead of a fixed color. The base defines the roles; the **product supplies the hues**.
|
|
94
|
-
|
|
95
|
-
| Role | For | Light | Dark |
|
|
96
|
-
| --- | --- | --- | --- |
|
|
97
|
-
| `--accent` | the solid: an icon tile, a band's rule, a colored edge | `--a-600` | `--a-400` |
|
|
98
|
-
| `--accent-on` | text or an icon on the solid | white | `--a-950` |
|
|
99
|
-
| `--accent-strong` | titles and labels in the accent | `--a-800` | `--a-200` |
|
|
100
|
-
| `--accent-soft` | a band or panel tint | `--a-50` | `--a-500` at 12% |
|
|
101
|
-
| `--accent-muted` | chips | `--a-100` | `--a-500` at 24% |
|
|
102
|
-
| `--accent-line` | a rule or border | `--a-200` | `--a-500` at 40% |
|
|
103
|
-
|
|
104
|
-
A hue is eight stops, `--a-50 … --a-950`, set under `[data-accent='<name>']` in the product's CSS (in `@layer base`
|
|
105
|
-
or unlayered: either wins over the base's rule). They are inputs to the roles, not a palette, so a hue may point one
|
|
106
|
-
elsewhere or set a role outright — a cyan hue can use cyan-500 for its solid and set `--accent-on` to cyan-950.
|
|
107
|
-
Each role carries both modes in one `light-dark()` declaration, so the product writes no `.dark` rules. A name with no
|
|
108
|
-
hue map reads as the product's primary. Components read the roles with arbitrary values (`bg-(--accent)
|
|
109
|
-
text-(--accent-on)`, `border-(--accent-line)`), and the colored-edge wrappers take `color="accent"`: `<ZCard
|
|
110
|
-
color="accent">` inside a section gets that section's edge (the primary outside any section). Overlays portal to
|
|
111
|
-
`<body>`, out of the section, so `ZModal`, `ZSlideover` and `ZDrawer` read the section they are rendered in and put
|
|
112
|
-
its `data-accent` on the overlay's content: a dialog opened from a teal section has a teal edge.
|
|
113
|
-
|
|
114
|
-
## Mechanisms the base carries
|
|
115
|
-
|
|
116
|
-
**`color-scheme` on the root, for `light-dark()`.** Tailwind 4's production build (Lightning CSS) compiles
|
|
117
|
-
`light-dark()` into variables it defines only where `color-scheme` is declared. color-mode only toggles the `dark`
|
|
118
|
-
class, and Nuxt UI declares `color-scheme` on `<body>` — but `@theme` tokens live on `:root`, so a token like
|
|
119
|
-
`--color-x: light-dark(#fff, #000)` came out empty in production while dev looked right. The base declares
|
|
120
|
-
`:root { color-scheme: light } .dark { color-scheme: dark }`. On a Forest product it changes nothing on the page (the
|
|
121
|
-
Forest app and the starter were compared pixel for pixel, light and dark, before and after); the browser's own page
|
|
122
|
-
scrollbar now follows dark mode.
|
|
32
|
+
plain Nuxt UI. Three rules:
|
|
123
33
|
|
|
124
|
-
**
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
tree-shakes still is.
|
|
130
|
-
|
|
131
|
-
**Z\* icons in the client bundle.** The icons the `Z*` components render (`ZThemeToggle`'s, `ZTokenReveal`'s) are
|
|
132
|
-
added to the consumer's client icon bundle through `@nuxt/icon`'s `icon:clientBundleIcons` hook, as Nuxt UI adds its
|
|
133
|
-
own — whatever the product's `icon` options, and without touching its list. A product need not list them.
|
|
134
|
-
`scripts/check-icons.test.mjs` holds the layer's list to what `components/` uses. Most of them (sun, moon, monitor,
|
|
135
|
-
triangle-alert, check, circle-check, x, plus, chevron-up, chevron-down) are also Nuxt UI's own default icons,
|
|
136
|
-
which Nuxt UI bundles anyway; `ZRepeatingList`'s pencil and trash-2 and `ZDateField`'s calendar are not, so only the
|
|
137
|
-
layer's registration puts them in the bundle. The base app's tests hold the outcome
|
|
138
|
-
(Z\* icons render with no request for icon data), and a `ZDateField` that mounts in the browser on a page of its own
|
|
139
|
-
(`apps/base/app/pages/date-field-later.vue`) fails that test when `lucide:calendar` is taken out of the list.
|
|
140
|
-
|
|
141
|
-
**Shipping as source.** The package is TypeScript and `.vue`, not built output, and needs nothing from a product:
|
|
142
|
-
Nuxt adds every layer root under `node_modules` to `build.transpile` and transpiles component directories there
|
|
143
|
-
itself, and neither layer has a `server/` directory or module of its own for Nitro to parse, so no `nitro.esbuild`
|
|
144
|
-
setting is needed either. The workspace apps consume it as
|
|
145
|
-
`workspace:*`, which resolves outside `node_modules`; an npm install is the `node_modules` case above.
|
|
34
|
+
- **One Tailwind entry.** The layer registers Nuxt UI but not the stylesheet, so the app owns its single entry and
|
|
35
|
+
can add `@source` for components outside its root.
|
|
36
|
+
- **No `@nuxt/ui`, `tailwindcss` or `@tailwindcss/vite` in the product.** The layer owns them, and a second
|
|
37
|
+
Tailwind registration fails the build.
|
|
38
|
+
- **Wrap the app in `<UApp>`.** Nuxt UI mounts toasts, tooltips and overlays through it.
|
|
146
39
|
|
|
147
40
|
## Versions
|
|
148
41
|
|
|
149
|
-
| | Minimum |
|
|
42
|
+
| | Minimum | |
|
|
150
43
|
| --- | --- | --- |
|
|
151
|
-
| Nuxt | 4.1 |
|
|
152
|
-
| Nuxt UI | 4.11 (`~4.11.1`) | The layer's dependency
|
|
153
|
-
| Tailwind CSS | 4.3.3 |
|
|
154
|
-
| Node | 22 |
|
|
155
|
-
|
|
156
|
-
A product on an older Nuxt UI moves to the layer's when it adopts Zoo UI: it removes its own `@nuxt/ui` (and
|
|
157
|
-
`tailwindcss`) and gets 4.11 through the layer. A product on 4.10 moves to 4.11 that way. See [Upgrading Nuxt
|
|
158
|
-
UI](#upgrading-nuxt-ui).
|
|
159
|
-
|
|
160
|
-
## Colored edges
|
|
161
|
-
|
|
162
|
-
A **3px edge in the surface's color**: on the **left** for inline surfaces (cards) and on the **top** for overlays
|
|
163
|
-
(dialogs, slideovers, drawers). Everything else about the surface — padding, radius, shadow, motion, focus — is
|
|
164
|
-
Nuxt UI's. No color, no edge.
|
|
165
|
-
|
|
166
|
-
| Surface | How | Edge |
|
|
167
|
-
| --- | --- | --- |
|
|
168
|
-
| Card | `<ZCard color="…">` | left |
|
|
169
|
-
| Dialog | `<ZModal color="…">` | top |
|
|
170
|
-
| Side drawer | `<ZSlideover color="…">` | top |
|
|
171
|
-
| Bottom drawer | `<ZDrawer color="…">` | top |
|
|
172
|
-
|
|
173
|
-
Only `UToast` has a `color` of its own, so these four get a thin `Z*` wrapper (`components/`) that adds
|
|
174
|
-
`color` and passes every other prop, `v-model`, event and slot straight through to the Nuxt UI component —
|
|
175
|
-
tests hold each overlay to its Nuxt UI behavior (focus, Escape, focus return). Colors are the semantic ones
|
|
176
|
-
(`primary` … `neutral`), so edges follow the product's palette and switch shade in dark mode on their own — plus
|
|
177
|
-
`accent`, the section's [`data-accent`](#per-section-accent-data-accent) color. Forest adds the same edge to toasts
|
|
178
|
-
and striped alert banners: [Forest's colored edges](https://github.com/zooui-dev/zooui/blob/main/packages/theme-forest/README.md#colored-edges).
|
|
44
|
+
| Nuxt | 4.1 | The layer's peer range (`^4.1.0`); tested on 4.5 |
|
|
45
|
+
| Nuxt UI | 4.11 (`~4.11.1`) | The layer's dependency; products don't add their own |
|
|
46
|
+
| Tailwind CSS | 4.3.3 | Comes with Nuxt UI |
|
|
47
|
+
| Node | 22 | Nuxt UI 4.11 needs ≥ 22.12 on the 22 line |
|
|
179
48
|
|
|
180
49
|
## Components
|
|
181
50
|
|
|
182
|
-
For what Nuxt UI has no equivalent of — built on Nuxt UI's tokens, so a product's palette, a theme's schemes and
|
|
183
|
-
dark mode carry through them as they do through Nuxt UI's own components. Inks that carry text use the 700 shade in
|
|
184
|
-
light mode and 300 in dark, so they clear 4.5:1 on every Forest scheme (Nuxt UI's 500 does not, on Teal or Slate · Cobalt).
|
|
185
|
-
|
|
186
51
|
| Component | What it is |
|
|
187
52
|
| --- | --- |
|
|
188
|
-
|
|
|
189
|
-
|
|
|
190
|
-
|
|
|
191
|
-
|
|
|
192
|
-
|
|
|
193
|
-
|
|
|
194
|
-
|
|
|
195
|
-
|
|
|
196
|
-
|
|
|
197
|
-
|
|
|
198
|
-
|
|
|
199
|
-
|
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
over a primary underline (`highlight-color` must be named: unset, Nuxt UI takes it from `color`, and the bar goes
|
|
216
|
-
neutral).
|
|
217
|
-
|
|
218
|
-
### ZRepeatingList
|
|
219
|
-
|
|
220
|
-
```vue
|
|
221
|
-
<ZRepeatingList v-model="sources" item-label="referral source" :new-row="() => ({ name: '' })" :row-key="(s) => s.id" :errors="errors">
|
|
222
|
-
<template #row="{ row, errorId }"><UFormField label="Name"><UInput v-model="row.name" :aria-describedby="errorId" /></UFormField></template>
|
|
223
|
-
<template #summary="{ row }">{{ row.name }}</template>
|
|
224
|
-
</ZRepeatingList>
|
|
225
|
-
```
|
|
226
|
-
|
|
227
|
-
Generic over the row type (`T extends object`), so `row` in `#row` and `#summary` is the list's own type. Rows are
|
|
228
|
-
told apart by `rowKey`, or by object identity for rows without one. `min` rows are always on screen (Remove hides at
|
|
229
|
-
it); at `max` Add is disabled and `max-label` says so. `errors` is keyed by row key; a row's message is a
|
|
230
|
-
`role="alert"` under it, and its id reaches the slot as `errorId`. With `#summary`, rows present at mount fold to one
|
|
231
|
-
line with Edit; new rows and rows with an error are open. `compact` is one line per row with an icon-only Remove.
|
|
232
|
-
Focus goes to the first `focus-selector` match in an added or opened row, and to Add after a remove; a polite live
|
|
233
|
-
region announces each add and remove. The words are props: `add-label`, `remove-label`, `edit-label`, `max-label`,
|
|
234
|
-
`row-title`, `announce`. The list carries `data-testid="repeating-list"` and each row `data-row`, for e2e selectors.
|
|
235
|
-
|
|
236
|
-
### ZDateField
|
|
237
|
-
|
|
238
|
-
The date field (`components/DateField.vue`), with its parser (`utils/date-entry.ts`) and `useToday()`. The model is
|
|
239
|
-
a `Temporal.PlainDate` or `null`, the same type a `date` column comes back as, and **no JavaScript `Date` is made
|
|
240
|
-
anywhere**: a `Date` is an instant, and every conversion to a day goes through a time zone. The calendar's `CalendarDate`
|
|
241
|
-
is converted by its fields alone.
|
|
242
|
-
|
|
243
|
-
```vue
|
|
244
|
-
<UFormField label="Ends"><ZDateField v-model="form.endDate" clearable class="w-full" /></UFormField>
|
|
245
|
-
<ZDateField v-model="due" locale="de" /> <!-- DD.MM.YYYY, a German calendar -->
|
|
246
|
-
<ZDateField v-model="due" format="YYYY-MM-DD" />
|
|
247
|
-
```
|
|
248
|
-
|
|
249
|
-
- **Typing**, in MM/DD/YYYY: `5` or `12` is that day this month, `0512` May 12, `051226`, `5/12/26` and `5/12/2026`
|
|
250
|
-
carry the year (a two-digit year lands within 20 years ahead and 79 behind; a four-digit one must be 1000 or later).
|
|
251
|
-
A year of all zeros is not a date: `5/12/0`, `5/12/00` and `051200` clear the field rather
|
|
252
|
-
than land on 2000. Other formats read the same shapes in their own order. Enter, Tab or leaving commits; text that
|
|
253
|
-
isn't a date clears the field; untouched text keeps its date, even one it couldn't read back (a stored year before
|
|
254
|
-
1000).
|
|
255
|
-
- **Shortcut keys**: `t` today; `m`/`h` first and last of the month, `y`/`r` of the year (again to keep walking); `+`
|
|
256
|
-
or `=` the next day, `-` or `_` the day before. The format's separator is never a shortcut, so in `YYYY-MM-DD`, `-`
|
|
257
|
-
types a dash and `_` is the day before. Alt+↓ opens the calendar. Shortcuts stop at 1000-01-01 and 9999-12-31.
|
|
258
|
-
- **Format and locale.** `format` is a pattern of `MM`, `DD` and `YYYY` in month-day-year, day-month-year or
|
|
259
|
-
year-month-day order with one separator: `MM/DD/YYYY`, `DD/MM/YYYY`, `DD.MM.YYYY`, `YYYY-MM-DD` …
|
|
260
|
-
`locale` is the calendar's language. **By default** the locale is Nuxt UI's (`<UApp :locale>`,
|
|
261
|
-
`en` unless set) and the format is that locale's own numeric order (`dateEntryFormatFor`: `en` → `MM/DD/YYYY`,
|
|
262
|
-
`en-GB` → `DD/MM/YYYY`, `de` → `DD.MM.YYYY`, `sv` → `YYYY-MM-DD`), so a product on `en` gets `MM/DD/YYYY` with
|
|
263
|
-
no props. The placeholder is the pattern. The two buttons are named by `clear-label` and `choose-label` (English
|
|
264
|
-
by default) for a product in another language.
|
|
265
|
-
- **`@date-update`** fires once per settle (picked, cleared, a shortcut, Enter, or focus leaving for somewhere other
|
|
266
|
-
than its own calendar) and always carries the date just settled, even before a parent-owned v-model has caught up:
|
|
267
|
-
the moment an inline editor should save.
|
|
268
|
-
- **Icons.** `icon` puts a leading icon in the field, and a click on it emits
|
|
269
|
-
**`@icon-click`** with the `MouseEvent` (the field's own handling is untouched: the click still blurs the input, so
|
|
270
|
-
a typed date settles first). `calendar-icon` replaces the calendar button's icon (`i-lucide-calendar` by default).
|
|
271
|
-
The layer bundles only its default; an icon a product passes is the product's to bundle (its `icon.clientBundle`) or
|
|
272
|
-
to serve from its icon endpoint.
|
|
273
|
-
- **The calendar** heads its columns with the locale's narrow weekdays (`S M T W T F S` in `en`, `M D M D F S S` in
|
|
274
|
-
`de`).
|
|
275
|
-
- **Today** is `useToday()`: the browser's day, in the browser's time zone, client-only (it throws on the server,
|
|
276
|
-
where the zone is the server's). Server code that needs the business's today wants
|
|
277
|
-
`Temporal.Now.plainDateISO(companyZone)` instead.
|
|
278
|
-
- **Look.** Nuxt UI's `UInput` and `UCalendar` in the product's colors; while the calendar is open the field takes
|
|
279
|
-
Nuxt UI's `highlight` ring. The placeholder keeps the input's own ink: a product that wants it darker (its own
|
|
280
|
-
placeholder color token) passes `:ui="{ base: 'placeholder:…' }"` or sets it on `ui.input` in `app.config`.
|
|
53
|
+
| `ZCard`, `ZModal`, `ZSlideover`, `ZDrawer` | Nuxt UI's surfaces with a `color` that draws a 3px colored edge |
|
|
54
|
+
| `ZKicker` | The mono label over a section: `[ DEPLOYMENTS ]` |
|
|
55
|
+
| `ZIdentifier` | A package, version or hash in the mono face |
|
|
56
|
+
| `ZStatus` | Status by shape, so it survives grayscale |
|
|
57
|
+
| `ZSlots` | One named chip per slot of capacity |
|
|
58
|
+
| `ZQuotaMeter` | Usage against a limit |
|
|
59
|
+
| `ZCodeBlock` | The near-black code surface, with copy |
|
|
60
|
+
| `ZTokenReveal` | A shown-once secret, with a warning and an optional acknowledgement |
|
|
61
|
+
| `ZEcosystemMark` | A package manager as a two-letter tile |
|
|
62
|
+
| `ZThemeToggle` | Light / dark / system |
|
|
63
|
+
| `ZRepeatingList` | A generic list editor |
|
|
64
|
+
| `ZNumberInput` | One number input for money, percent, count and hours, with a calc mode |
|
|
65
|
+
| `ZDateField` | A calendar-day field on `Temporal.PlainDate` or `CalendarDate`, with Nuxt UI's limit props |
|
|
66
|
+
|
|
67
|
+
## Docs
|
|
68
|
+
|
|
69
|
+
- [Components](https://github.com/zooui-dev/zooui/blob/main/packages/nuxt/docs/components.md): every prop, the select-none helpers and the nav marker
|
|
70
|
+
- [ZRepeatingList](https://github.com/zooui-dev/zooui/blob/main/packages/nuxt/docs/repeating-list.md),
|
|
71
|
+
[ZNumberInput](https://github.com/zooui-dev/zooui/blob/main/packages/nuxt/docs/number-input.md),
|
|
72
|
+
[ZDateField](https://github.com/zooui-dev/zooui/blob/main/packages/nuxt/docs/date-field.md)
|
|
73
|
+
- [The base and a theme](https://github.com/zooui-dev/zooui/blob/main/packages/nuxt/docs/base-and-theme.md): what each layer carries, and why they're two layers
|
|
74
|
+
- [Accents and colored edges](https://github.com/zooui-dev/zooui/blob/main/packages/nuxt/docs/accents-and-edges.md): `data-accent` sections and the `color` edge
|
|
75
|
+
- [Mechanisms](https://github.com/zooui-dev/zooui/blob/main/packages/nuxt/docs/mechanisms.md): `light-dark()`, the hydration label fix, icon bundling, shipping as source
|
|
76
|
+
- [Guards and tests](https://github.com/zooui-dev/zooui/blob/main/packages/nuxt/docs/testing.md)
|
|
77
|
+
- [Releasing](https://github.com/zooui-dev/zooui/blob/main/docs/releasing.md) and [upgrading Nuxt UI](https://github.com/zooui-dev/zooui/blob/main/docs/upgrading-nuxt-ui.md)
|
|
78
|
+
|
|
79
|
+
## Developing
|
|
281
80
|
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
relies on the default reads the same. Its tests are `scripts/date-entry.test.mjs` (`node:test`, every format).
|
|
287
|
-
|
|
288
|
-
**Temporal** is `temporal-polyfill`'s `/implementation` entry (^1.0.5), never the bare entry, which becomes the
|
|
289
|
-
engine's own `Temporal` where one exists. A product builds its `PlainDate`s from the same subpath, so there is one
|
|
290
|
-
class; a product that already installs `temporal-polyfill` imports from that subpath too, and one that doesn't adds
|
|
291
|
-
it.
|
|
292
|
-
|
|
293
|
-
### ZNumberInput
|
|
294
|
-
|
|
295
|
-
One number input, so every figure looks and moves the same, formatting as it is typed. It is Nuxt UI's `UInput` (`type="text"`, `inputmode="decimal"`): every other attribute, `size`,
|
|
296
|
-
`color`, `highlight`, `disabled`, `readonly`, `ui`, `aria-*`, falls through to it, the marks and chevrons sit in its
|
|
297
|
-
`leading` and `trailing` slots, and calc's preview in its default slot. It is on Nuxt UI's tokens: marks and chevrons
|
|
298
|
-
in `text-dimmed`, hover `text-default`, the preview `bg-inverted`/`text-inverted`.
|
|
299
|
-
|
|
300
|
-
| Prop | | |
|
|
301
|
-
| --- | --- | --- |
|
|
302
|
-
| `modelValue` | `string \| number \| Decimal \| null` | Every change hands back the caller's kind: a string stays a string (as typed: `"1.0"` on the way to `"1.05"`; written to the places on commit, `"1234.50"`), a number a number, a decimal.js `Decimal` a `Decimal` of the caller's own class. Cleared: `''` for a string, `null` otherwise. Strings and Decimals never pass through a float |
|
|
303
|
-
| `modelType` | `'string' \| 'number' \| 'decimal'` | The kind to hand back when the model starts empty (it has no value to take a kind from). A `Decimal` v-model that can start null needs `model-type="decimal"`; without it, empty starts as a string |
|
|
304
|
-
| `unit` | `money \| percent \| count \| hours` | `count` by default. Money puts the currency symbol on the left; percent `%` and hours `hrs` on the right, in a slot kept the same width when empty, so values end on one edge |
|
|
305
|
-
| `locale`, `currency` | BCP 47, ISO 4217 | The grouping and decimal marks typed and shown (`de`: `1.234,56`), the money symbol, and the chevrons' labels ("Add $5,000", "Subtract 0.5 hours") |
|
|
306
|
-
| `minFractionDigits`, `maxFractionDigits` | `number` | Decimal places: the minimum written on commit, the maximum rounded to on commit and the most that can be typed. Money is `2`/`2`; every other unit `0`/none (as typed). A minimum above an explicit maximum comes down to it |
|
|
307
|
-
| `min`, `max` | `number \| string` | Clamp a nudge and a commit. Out of range otherwise (between keystrokes, or a model that arrives so) the field is `:invalid` (`setCustomValidity`), following the model as a parent changes it; a minus can't be typed where `min` is 0 or more |
|
|
308
|
-
| `step` | `number` | What the chevrons and ArrowUp/ArrowDown add, from the current value, never snapped to a multiple |
|
|
309
|
-
| `spin` | `boolean` | `true` by default. `false`: no chevrons, ArrowUp/ArrowDown do nothing, and the field is a plain text box rather than a `spinbutton` |
|
|
310
|
-
| `prefix`, `suffix` | `string` | Free text beside the marks: `prefix="~"` shows `~$`, `suffix="/mo"` shows `/mo` after the value. Kept out of the text, in the mark slots, which grow to fit |
|
|
311
|
-
| `highlightOnFocus` | `boolean` | Select the whole value on focus, by click or key (on by default in `calc`) |
|
|
312
|
-
| `calc` | `boolean` | Take `+ - * /` expressions ([below](#calc)) |
|
|
313
|
-
| `commitOnBlur` | `boolean` | `true` by default. `false` for a grid editor that commits itself with `evaluate()` |
|
|
314
|
-
| `freeform` | `boolean` | A text box that takes "$125,000" or "24 %" as typed and hands the text back as it is, for a product that tidies it itself; the arrows read the figure out of it (in the field's locale) and leave anything else ("forty") untouched. No live formatting, clamping or rounding |
|
|
315
|
-
|
|
316
|
-
Emits `update:modelValue`; no slots. Exposes `evaluate()`, which commits what is typed and returns the model's value,
|
|
317
|
-
and `inputRef`. Keeps `data-number-input` on the `<input>` (and adds `data-unit`), `data-number-mark` on the
|
|
318
|
-
marks, and the chevrons' labels.
|
|
319
|
-
|
|
320
|
-
**Typing.** Each keystroke, paste and deletion is worked out before the browser applies it (`beforeinput`): the
|
|
321
|
-
locale's grouping comes and goes (`12,345`), the caret stays on its digit, one decimal mark, a minus only at the
|
|
322
|
-
front, no leading zeros. Backspace or Delete over a separator takes the digit beyond it; a fixed decimal mark is
|
|
323
|
-
stepped over rather than deleted; typed into a full fraction, a digit overwrites the next; typed before a minus, a
|
|
324
|
-
digit goes after it. A key that would add nothing (a letter, a second decimal mark, a minus where none may go) is
|
|
325
|
-
refused, and leaves a selection selected. A paste keeps the figure's digits (`$1,234.50` arrives as `1,234.50`).
|
|
326
|
-
Anything else (an IME, undo, autofill) is tidied after it lands, and keys an IME is composing with are left to it.
|
|
327
|
-
The model follows the typing; a **commit** (blur, Enter, Tab, or a nudge, by key or chevron alike: a chevron doesn't
|
|
328
|
-
take the focus) rounds to the places (half away from zero, in decimal.js), keeps the result within `min`/`max`, and
|
|
329
|
-
shows the value in full (`38,500.00`). A rounded value past a bound becomes the nearest value inside it that the
|
|
330
|
-
places can write (`max="1.235"` at two places commits `1.23`, never `1.24`); if the places can write none (`min` 0.004,
|
|
331
|
-
`max` 0.006, two places), the bound itself is kept.
|
|
332
|
-
|
|
333
|
-
**Marks.** The currency symbol and `prefix` stay to the left of the text and `%`, `hrs` and `suffix` to the right,
|
|
334
|
-
in the input's own padding, so a column of values still ends on one edge and typing only ever meets digits. A
|
|
335
|
-
locale that writes its symbol after the number (`de`: `1.234,56 €`) still shows `€` on the left, with the money.
|
|
336
|
-
|
|
337
|
-
**Accessibility.** While it spins the input is a `spinbutton` with `aria-valuemin`, `aria-valuemax`, `aria-valuenow`
|
|
338
|
-
and an `aria-valuetext` with its marks ("$38,500.00"); the chevrons are named buttons, out of the tab order (the
|
|
339
|
-
arrow keys do the same). With `:spin="false"` it is a plain text box.
|
|
340
|
-
|
|
341
|
-
#### Calc
|
|
342
|
-
|
|
343
|
-
`calc` makes the field a small calculator: `+ - * /` with the usual precedence, read by a small
|
|
344
|
-
recursive-descent parser (never `eval`) and worked in decimal.js, so `0.1+0.2` is `0.3`.
|
|
345
|
-
Each number is grouped as it is typed, for the locale, keeping the caret. While focused, the result shows under the
|
|
346
|
-
field (`= $1,250.00`, with the unit's marks), absolutely placed in `UInput`'s slot so nothing moves, and announced
|
|
347
|
-
politely. Enter, Tab or blur (unless `:commit-on-blur="false"`) puts it in, rounded and kept in range like any commit.
|
|
348
|
-
The result is rounded once, at the field's places (ten where the field has no maximum), so a sum is never
|
|
349
|
-
rounded twice: whole dollars only is `calc :max-fraction-digits="0"`. A line break in a paste is a space. Incomplete or invalid input (`678+`, `abc`) or a division
|
|
350
|
-
by zero gives no value. An operator typed over a selection is added at the end (the value is
|
|
351
|
-
selected on focus, so `+50` adds to it), except a minus over everything, which starts a negative number. A grid
|
|
352
|
-
cell editor:
|
|
353
|
-
|
|
354
|
-
```vue
|
|
355
|
-
<ZNumberInput ref="cell" v-model="value" unit="money" calc :spin="false" :commit-on-blur="false" />
|
|
356
|
-
<!-- on Enter, Tab or an arrow: cell.value.evaluate(), then move -->
|
|
357
|
-
```
|
|
358
|
-
|
|
359
|
-
**Defaults, and a product's own.** Without props: money moves by 1, percent and count by 1, hours by 0.5, in US
|
|
360
|
-
dollars, `en-US` (fixed, so the server and the browser render the same text), money to 2 places. A product sets its
|
|
361
|
-
own once in its `app.config.ts`; a prop still wins. A product's own $5,000 step:
|
|
362
|
-
|
|
363
|
-
```ts
|
|
364
|
-
export default defineAppConfig({ zooui: { numberInput: { steps: { money: 5000 } } } })
|
|
365
|
-
// also: currency, locale, fractionDigits: { money: { min: 0, max: 0 } }
|
|
366
|
-
```
|
|
367
|
-
|
|
368
|
-
**Decimal.** A database client may return Postgres `numeric` as decimal.js `Decimal`s, and a schema may check
|
|
369
|
-
`instanceof Decimal`. ZNumberInput recognizes a `Decimal` with `Decimal.isDecimal` (which knows another copy's
|
|
370
|
-
instances too), reads it from its string, and builds every value it hands back with the caller's own class, so
|
|
371
|
-
`instanceof` holds even with two copies installed. A `Decimal.clone()` comes back the clone, with its precision, and
|
|
372
|
-
a subclass (`class Money extends Decimal`) comes back a subclass: decimal.js writes the class it extends onto each
|
|
373
|
-
instance, so for a subclass the class is read from the instance's prototype instead. The layer depends on decimal.js
|
|
374
|
-
`^10.6.0`, so a product that also installs decimal.js itself gets one copy: keep the product's own range compatible
|
|
375
|
-
with it.
|
|
376
|
-
|
|
377
|
-
**Where it lives.** The component is thin; the rules are pure TypeScript beside it: `number-format.ts` (the locale's
|
|
378
|
-
marks, live formatting and the caret, commits, the caller's kind of value), `number-calc.ts` (the evaluator and
|
|
379
|
-
expression editing) and `number-input.ts` (config, labels, nudges, freeform reading). Their tests are
|
|
380
|
-
`scripts/number-input.test.mjs` and `scripts/number-calc.test.mjs`.
|
|
381
|
-
|
|
382
|
-
## The guards every product runs
|
|
383
|
-
|
|
384
|
-
One check ships with the base layer, for any page's Playwright test (it runs inside the page):
|
|
385
|
-
|
|
386
|
-
```ts
|
|
387
|
-
import { findConflicts } from '@zooui/nuxt/testing/find-conflicts'
|
|
388
|
-
|
|
389
|
-
expect(await page.evaluate(findConflicts)).toEqual([]) // no element with two same-property utilities
|
|
81
|
+
```bash
|
|
82
|
+
pnpm base:dev # → http://localhost:3004 — this layer alone, in a product's own look
|
|
83
|
+
pnpm base:build && pnpm base:test
|
|
84
|
+
pnpm ks:dev # → http://localhost:3003 — the baseline: Nuxt UI as it ships
|
|
390
85
|
```
|
|
391
86
|
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
`../../apps/base/tests/base.spec.ts` holds the base alone, in a product with its own look (its own palette, typefaces,
|
|
395
|
-
color-mode key, CSS and accent map), against its production build: none of Forest's colors, ramps, typefaces,
|
|
396
|
-
ground or restyling arrive; the color-mode key and default stay the product's and no `data-theme` is written;
|
|
397
|
-
every Z\* component paints in the product's colors in both modes, and `font-mono` falls back to the system mono
|
|
398
|
-
stack; the product's `@theme` tokens, `@utility` and `@layer base` rules work after `base.css`; `light-dark()`
|
|
399
|
-
tokens resolve in both modes in the compiled CSS; a `data-accent` hue map paints the roles and `ZCard
|
|
400
|
-
color="accent"` in both modes; `UFormField` labels still name their inputs after hydration; and Z\* icons render
|
|
401
|
-
with no request for icon data.
|
|
402
|
-
|
|
403
|
-
Forest's own tests, which also run every `Z*` component on every scheme, are in
|
|
404
|
-
[its README](https://github.com/zooui-dev/zooui/blob/main/packages/theme-forest/README.md#the-tests-prove-color-only).
|
|
405
|
-
|
|
406
|
-
## Open — decide one at a time
|
|
407
|
-
|
|
408
|
-
**Corners.** Nuxt UI's `--ui-radius` (4px base) is close to the design source's `tight` corners; its
|
|
409
|
-
`soft`/`tight`/`flat` dial is not carried into Nuxt. A product that wants squarer corners sets `--ui-radius` itself.
|
|
410
|
-
|
|
411
|
-
## Releasing
|
|
412
|
-
|
|
413
|
-
Both layers, `@zooui/nuxt` and `@zooui/theme-forest`, release to the public npm registry
|
|
414
|
-
(`publishConfig.access: public`) through **shiprig**. Neither has been published yet. The theme
|
|
415
|
-
ships no font files of its own.
|
|
416
|
-
|
|
417
|
-
1. **In each PR with a user-facing change**, record it: `changerig add -t fix -p @zooui/nuxt -m "…"` (or `-p @zooui/theme-forest`)
|
|
418
|
-
(`feat` for features). The entry is written for the changelog's reader, and links its commit and PR.
|
|
419
|
-
2. **To release: merge the release PR, approve the publish run, done.** shiprig's action
|
|
420
|
-
(`.github/workflows/release.yml`, `rigsmith/shiprig-action`, settings in `.github/shiprig-action.jsonc`) works the
|
|
421
|
-
way release-please does, on every push to `main` of zooui-dev/zooui (anywhere else it does nothing):
|
|
422
|
-
- With changesets pending, it keeps a standing **release PR** (`chore: release …`) up to date: `shiprig version`
|
|
423
|
-
bumps the versions and writes each package's `CHANGELOG.md`. This needs no approval and no secret.
|
|
424
|
-
- Merge that PR, and the run for the merge has something to publish: its **Publish** job waits for approval in
|
|
425
|
-
the protected `release` environment. Approve it (the run's page → Review deployments). It checks every package
|
|
426
|
-
it would publish has a `## <version>` entry in its `CHANGELOG.md` (the GitHub release is made from it) and stops
|
|
427
|
-
with nothing published if one doesn't, then `shiprig publish` packs each layer with pnpm (which rewrites the
|
|
428
|
-
theme's `workspace:*` dependency on the base to the exact version) and npm publishes it with provenance. It
|
|
429
|
-
pushes the tags and makes a GitHub release per package from its changelog entry.
|
|
430
|
-
- Any other push does nothing.
|
|
431
|
-
- **Rehearse** any time: Actions → **Release** → Run workflow, with `dry_run` ticked (the default). It shows the
|
|
432
|
-
release PR it would open or what it would publish, with no approval and no secret, and changes nothing. With
|
|
433
|
-
`dry_run` unticked, a manual run does what a push does: the way to retry a publish that failed or was rejected.
|
|
434
|
-
- **Locally**, `shiprig release --dry-run` previews the whole pipeline (`.changeset/release.jsonc`). A real local
|
|
435
|
-
publish is refused: `node.provenance` is `"always"` (`.changeset/config.json`), and npm provenance can only be
|
|
436
|
-
made in GitHub Actions.
|
|
437
|
-
3. **Design source changes** (`packages/theme-forest/design/`) are `@zooui/theme-forest` changes: record them with
|
|
438
|
-
`changerig add -p @zooui/theme-forest`. Like any change to `@zooui/theme-forest`, it is recorded in the theme's changeset and appears in the theme's changelog.
|
|
439
|
-
|
|
440
|
-
Don't edit the version or changelog by hand, and don't `pnpm publish` directly: `changerig` owns both (0.1.0, below, was the one exception).
|
|
441
|
-
|
|
442
|
-
### The first release, 0.1.0
|
|
443
|
-
|
|
444
|
-
Both layers are already at `0.1.0` and have never been published, and the public repository starts with no
|
|
445
|
-
changesets and empty changelogs. `releaseAs` in `.github/shiprig-action.jsonc` names each at `0.1.0`, which makes
|
|
446
|
-
every push open a `chore: release 0.1.0` PR anyway. npm trusted publishing can only be set up for a package that
|
|
447
|
-
already exists, and npm no longer issues tokens a CI publish can use, so 0.1.0 is published by hand and the workflow
|
|
448
|
-
takes over from there. Once, in zooui-dev/zooui:
|
|
449
|
-
|
|
450
|
-
1. **The `release` environment.** Settings → Environments → New environment, named `release`, with **Required
|
|
451
|
-
reviewers** (John). Only the Publish job runs in it, so only a real release waits for that approval.
|
|
452
|
-
2. **Let workflows open PRs.** Settings → Actions → General → Workflow permissions: tick **Allow GitHub Actions to
|
|
453
|
-
create and approve pull requests**, or the action can't open the release PR. (In an organization that forbids
|
|
454
|
-
it, allow it at the organization first.)
|
|
455
|
-
3. **Push `main`.** The push opens `chore: release 0.1.0`, in which
|
|
456
|
-
`shiprig version --release-as @zooui/nuxt=0.1.0 --release-as @zooui/theme-forest=0.1.0` writes each package's
|
|
457
|
-
`## 0.1.0` changelog entry ("Initial release") and changes no version. Don't merge it yet.
|
|
458
|
-
4. **Publish 0.1.0 by hand**, from a clean checkout of that `main`, logged in to npm as an owner of the `@zooui`
|
|
459
|
-
scope: `pnpm publish -r --access public`. pnpm publishes the base before the theme and rewrites the theme's
|
|
460
|
-
`workspace:*` dependency to `0.1.0`. This is the only publish that isn't the workflow's.
|
|
461
|
-
5. **Trusted publishing.** On npmjs.com, each package → Settings → Trusted publishing → GitHub Actions: repository
|
|
462
|
-
`zooui-dev/zooui`, workflow `release.yml`, environment `release`. Do both packages.
|
|
463
|
-
6. **Merge the release PR.** A PR the default token opens doesn't start its own checks: approve them on the PR
|
|
464
|
-
(**Approve workflows to run**) first. The merge's run waits for approval in `release`; approve it. It finds 0.1.0
|
|
465
|
-
already on npm and skips the publish, then pushes the `@zooui/nuxt@0.1.0` and `@zooui/theme-forest@0.1.0` tags
|
|
466
|
-
and makes their GitHub releases. Every later release publishes from the workflow with the run's OIDC token.
|
|
467
|
-
|
|
468
|
-
The `releaseAs` entries can stay: once a package has its `## 0.1.0` entry and tag, the action skips them.
|
|
469
|
-
|
|
470
|
-
### Upgrading Nuxt UI
|
|
471
|
-
|
|
472
|
-
The layer depends on `@nuxt/ui` with a **tilde** range (`~4.11.1`): patches arrive by themselves, minors don't.
|
|
473
|
-
The `apps/forest` tests pin Nuxt UI's measured geometry, so a Nuxt UI minor can change what the layer delivers, and
|
|
474
|
-
a caret range would let products resolve a version the tests never saw. A minor is a deliberate upgrade of the
|
|
475
|
-
layer: bump `@nuxt/ui` here and in `apps/kitchen-sink/package.json` (the baseline, always the same range), run the
|
|
476
|
-
`apps/forest` suite against the kitchen sink, record it with `changerig add`, and release.
|
|
87
|
+
`apps/base` is this layer in a product with its own look; `apps/starter` is the smallest product on Forest.
|
package/components/DateField.vue
CHANGED
|
@@ -1,15 +1,22 @@
|
|
|
1
|
-
<script setup lang="ts">
|
|
2
|
-
// A calendar-day field: type a date, press a shortcut key, or pick from a calendar. The model is a Temporal.PlainDate (
|
|
3
|
-
// column comes back as, so a form round-trips the server's value without ever touching a string or a
|
|
1
|
+
<script setup lang="ts" generic="T extends Temporal.PlainDate | CalendarDateLike | null">
|
|
2
|
+
// A calendar-day field: type a date, press a shortcut key, or pick from a calendar. The model is a Temporal.PlainDate (the
|
|
3
|
+
// same type a `date` column comes back as, so a form round-trips the server's value without ever touching a string or a
|
|
4
|
+
// time zone) or an @internationalized/date CalendarDate (the type Nuxt UI's UCalendar and UInputDate use), or null.
|
|
5
|
+
//
|
|
6
|
+
// THE CALLER'S TYPE. Whatever the model holds is what comes back, in `update:modelValue`, `dateUpdate` and `invalid`
|
|
7
|
+
// alike; a CalendarDate is built with the caller's own class. A model that starts out null hands back `modelType`'s
|
|
8
|
+
// type ('plain-date' by default), and one that held a day and was cleared keeps the type it had. Only a Gregorian
|
|
9
|
+
// CalendarDate is taken: one in another calendar throws (toPlainDate), since converting it by its fields would land
|
|
10
|
+
// on another day. Inside, everything is a PlainDate; the conversion is at the edges.
|
|
4
11
|
//
|
|
5
12
|
// WHY NO `Date`. A JavaScript Date is an instant, not a day. Every conversion between the two goes through a
|
|
6
13
|
// time zone, and every one of those is a chance for the 12th to become the 11th. So nothing here constructs one:
|
|
7
|
-
// the typed text is parsed by parseDateEntry (utils/date-entry.ts, pure Temporal), and
|
|
8
|
-
//
|
|
9
|
-
// "Today" comes from useToday().
|
|
14
|
+
// the typed text is parsed by parseDateEntry (utils/date-entry.ts, pure Temporal), and a CalendarDate is converted
|
|
15
|
+
// by its fields alone (year, month, day), never via toDate()/getLocalTimeZone(). "Today" comes from useToday().
|
|
10
16
|
//
|
|
11
17
|
// <ZDateField v-model="form.endDate" clearable class="w-full" />
|
|
12
18
|
// <ZDateField v-model="due" format="DD.MM.YYYY" locale="de" />
|
|
19
|
+
// <ZDateField v-model="due" :min-value="opened" :max-value="closes" :is-date-unavailable="isHoliday" />
|
|
13
20
|
//
|
|
14
21
|
// FORMAT AND LOCALE. `locale` names the calendar's language and week (Nuxt UI's locale when unset, `en` unless the
|
|
15
22
|
// app's <UApp :locale> says otherwise). `format` is how the box writes and reads a day — a pattern such as
|
|
@@ -22,6 +29,14 @@
|
|
|
22
29
|
// start/end of month, y/r start/end of year, + and - a day either way (_ too, so a format whose separator is "-"
|
|
23
30
|
// keeps a key for the day before).
|
|
24
31
|
//
|
|
32
|
+
// LIMITS. `minValue`, `maxValue` and `isDateUnavailable`, named as Nuxt UI's UCalendar names them, go to the calendar,
|
|
33
|
+
// which disables those days. A typed date they refuse is not committed: the field keeps the date it had and draws it
|
|
34
|
+
// back in the box (as with text that isn't a date, the box never shows a day the form isn't holding), and is marked
|
|
35
|
+
// invalid — aria-invalid, Nuxt UI's error color, a message for screen readers — until the next edit, pick, shortcut or
|
|
36
|
+
// clear. `invalid` carries the problem (why, the date, the limit, an English message) for the product to show, and
|
|
37
|
+
// null once it's gone; a refused Enter doesn't announce `dateUpdate`. The shortcuts stop at the limits and skip
|
|
38
|
+
// unavailable days (applyDateShortcut says how, `t` included).
|
|
39
|
+
//
|
|
25
40
|
// `dateUpdate` fires when a date is settled — picked, cleared, set by a shortcut, committed with Enter, or when
|
|
26
41
|
// focus leaves the field for somewhere other than its own calendar (Tab included, once) — which is the moment
|
|
27
42
|
// an inline editor (a table cell) should save and close. It always carries the date just settled, even when
|
|
@@ -30,15 +45,23 @@
|
|
|
30
45
|
//
|
|
31
46
|
// Also: a leading `icon` whose click emits `iconClick`, a `calendarIcon` in place of the calendar,
|
|
32
47
|
// and one-letter weekday headers (the locale's narrow weekday).
|
|
33
|
-
import type { CalendarDate as CalendarDay } from '@internationalized/date'
|
|
34
48
|
import { CalendarDate } from '@internationalized/date'
|
|
35
|
-
import { useLocale } from '@nuxt/ui/composables'
|
|
36
|
-
import { Temporal } from 'temporal-polyfill/implementation'
|
|
49
|
+
import { formFieldInjectionKey, useLocale } from '@nuxt/ui/composables'
|
|
50
|
+
import type { Temporal } from 'temporal-polyfill/implementation'
|
|
37
51
|
import { useToday } from '../composables/useToday'
|
|
38
|
-
import {
|
|
52
|
+
import {
|
|
53
|
+
applyDateShortcut, checkDateLimits, commitDateEntry, dateEntryFormat, dateEntryFormatFor, dateLimitMessage, dateModelTypeOf, formatDateEntry,
|
|
54
|
+
fromPlainDate, isDateShortcut, parseDateEntry, toPlainDate,
|
|
55
|
+
type CalendarDateLike, type DateLimitProblem, type DateLimits, type DateModelType,
|
|
56
|
+
} from '../utils/date-entry'
|
|
39
57
|
|
|
40
58
|
defineOptions({ inheritAttrs: false })
|
|
41
59
|
|
|
60
|
+
// A CalendarDate is typed by the fields read from it (CalendarDateLike), not its class: Vue's ref() unwraps a class
|
|
61
|
+
// with private fields into a type the class no longer accepts, so a `ref<CalendarDate | null>` would not type-check
|
|
62
|
+
// against the class itself.
|
|
63
|
+
type Day = NonNullable<T>
|
|
64
|
+
|
|
42
65
|
const props = withDefaults(
|
|
43
66
|
defineProps<{
|
|
44
67
|
clearable?: boolean
|
|
@@ -61,37 +84,108 @@ const props = withDefaults(
|
|
|
61
84
|
/** The two buttons' accessible names, for a product in another language. */
|
|
62
85
|
clearLabel?: string
|
|
63
86
|
chooseLabel?: string
|
|
87
|
+
/** The type to hand back while the model is null and has held no day: a CalendarDate v-model that starts out
|
|
88
|
+
* null needs `calendar-date`. */
|
|
89
|
+
modelType?: DateModelType
|
|
90
|
+
/** The first day the field takes, a PlainDate or a CalendarDate. */
|
|
91
|
+
minValue?: Temporal.PlainDate | CalendarDateLike
|
|
92
|
+
/** The last day the field takes, a PlainDate or a CalendarDate. */
|
|
93
|
+
maxValue?: Temporal.PlainDate | CalendarDateLike
|
|
94
|
+
/** Days the field refuses between the two; called with a day of the model's type. */
|
|
95
|
+
isDateUnavailable?: (date: Day) => boolean
|
|
64
96
|
}>(),
|
|
65
|
-
{ portal: true, calendarIcon: 'i-lucide-calendar', clearLabel: 'Clear date', chooseLabel: 'Choose a date' },
|
|
97
|
+
{ portal: true, calendarIcon: 'i-lucide-calendar', clearLabel: 'Clear date', chooseLabel: 'Choose a date', modelType: 'plain-date' },
|
|
66
98
|
)
|
|
67
99
|
const emit = defineEmits<{
|
|
68
|
-
dateUpdate: [value:
|
|
100
|
+
dateUpdate: [value: T | null]
|
|
101
|
+
// A typed day refused by the limits, and null once the field is no longer marked invalid.
|
|
102
|
+
invalid: [problem: (DateLimitProblem<Day> & { message: string }) | null]
|
|
69
103
|
clear: []
|
|
70
104
|
// A click on the leading `icon` (`iconClick`).
|
|
71
105
|
iconClick: [event: MouseEvent]
|
|
72
106
|
}>()
|
|
73
|
-
const model = defineModel<
|
|
107
|
+
const model = defineModel<T | null>({ default: null })
|
|
74
108
|
|
|
75
109
|
const { locale: uiLocale } = useLocale()
|
|
76
110
|
const localeCode = computed(() => props.locale ?? uiLocale.value.code)
|
|
77
111
|
const entryFormat = computed(() => (props.format ? dateEntryFormat(props.format) : dateEntryFormatFor(localeCode.value)))
|
|
78
112
|
const show = (d: Temporal.PlainDate | null) => formatDateEntry(d, entryFormat.value)
|
|
79
113
|
|
|
114
|
+
// The caller's type, kept through an empty spell, and the CalendarDate it last held (whose class builds the next).
|
|
115
|
+
let remembered: DateModelType | undefined
|
|
116
|
+
let like: CalendarDateLike | undefined
|
|
117
|
+
function remember(v: unknown) {
|
|
118
|
+
const type = dateModelTypeOf(v)
|
|
119
|
+
if (type) remembered = type
|
|
120
|
+
if (type === 'calendar-date') like = v as CalendarDateLike
|
|
121
|
+
}
|
|
122
|
+
remember(model.value)
|
|
123
|
+
const kind = () => dateModelTypeOf(model.value) ?? remembered ?? props.modelType
|
|
124
|
+
/** A day as the caller's type. */
|
|
125
|
+
const out = (d: Temporal.PlainDate | null) => fromPlainDate(d, kind(), like) as T | null
|
|
126
|
+
const outDay = (d: Temporal.PlainDate) => fromPlainDate(d, kind(), like) as Day
|
|
127
|
+
|
|
80
128
|
const open = ref(false)
|
|
81
|
-
const text = ref(show(model.value))
|
|
129
|
+
const text = ref(show(toPlainDate(model.value)))
|
|
82
130
|
|
|
83
131
|
const sameDay = (a: Temporal.PlainDate | null, b: Temporal.PlainDate | null) => a === b || (!!a && !!b && a.equals(b))
|
|
84
132
|
|
|
133
|
+
const limits = computed<DateLimits>(() => {
|
|
134
|
+
const unavailable = props.isDateUnavailable
|
|
135
|
+
return {
|
|
136
|
+
minValue: toPlainDate(props.minValue),
|
|
137
|
+
maxValue: toPlainDate(props.maxValue),
|
|
138
|
+
isDateUnavailable: unavailable && ((d: Temporal.PlainDate) => unavailable(outDay(d))),
|
|
139
|
+
}
|
|
140
|
+
})
|
|
141
|
+
|
|
142
|
+
// ── Invalid ───────────────────────────────────────────────────────────────────────────────────────────────────
|
|
143
|
+
const problem = ref<DateLimitProblem | null>(null)
|
|
144
|
+
const problemMessage = computed(() => (problem.value ? dateLimitMessage(problem.value, entryFormat.value) : ''))
|
|
145
|
+
function flag(p: DateLimitProblem | null) {
|
|
146
|
+
if (!p && !problem.value) return
|
|
147
|
+
problem.value = p
|
|
148
|
+
emit('invalid', p && { reason: p.reason, date: outDay(p.date), limit: p.limit && outDay(p.limit), message: problemMessage.value })
|
|
149
|
+
}
|
|
150
|
+
// In a UFormField, Nuxt UI's UInput takes aria-invalid, its error color and aria-describedby from the field, over
|
|
151
|
+
// anything passed to it: so while a day is refused the field the UInput sees carries the message as its error (unless
|
|
152
|
+
// it has one of its own, which the product may have set from `invalid`), and the message below takes the id that
|
|
153
|
+
// aria-describedby names. Outside one, they are passed to the UInput directly.
|
|
154
|
+
const formField = inject(formFieldInjectionKey, undefined)
|
|
155
|
+
if (formField) {
|
|
156
|
+
provide(formFieldInjectionKey, computed(() => {
|
|
157
|
+
const f = formField.value
|
|
158
|
+
return problem.value && f && !f.error ? { ...f, error: problemMessage.value } : f
|
|
159
|
+
}))
|
|
160
|
+
}
|
|
161
|
+
const panelId = useId()
|
|
162
|
+
const messageId = computed(() => {
|
|
163
|
+
if (!problem.value) return undefined
|
|
164
|
+
if (!formField?.value) return `${panelId}-invalid`
|
|
165
|
+
return formField.value.error ? undefined : `${formField.value.ariaId}-error`
|
|
166
|
+
})
|
|
167
|
+
const attrs = useAttrs()
|
|
168
|
+
const invalidAttrs = computed(() => {
|
|
169
|
+
if (!problem.value || formField?.value) return {}
|
|
170
|
+
const describedBy = [attrs['aria-describedby'], messageId.value].filter(Boolean).join(' ')
|
|
171
|
+
return { 'color': 'error', 'aria-invalid': true, 'aria-describedby': describedBy }
|
|
172
|
+
})
|
|
173
|
+
|
|
85
174
|
// The date this field last settled on, which is what `dateUpdate` reports. NEVER re-read `model.value` for
|
|
86
175
|
// that: when the parent owns the v-model, writing it only emits `update:modelValue`, and the prop comes back
|
|
87
176
|
// on the parent's next render — so in the same tick `model.value` is still the OLD date, and a blur that just
|
|
88
177
|
// committed "5/12" would announce null.
|
|
89
|
-
let settled = model.value
|
|
178
|
+
let settled = toPlainDate(model.value)
|
|
90
179
|
// The date `dateUpdate` last carried, boxed so an announced null is told apart from nothing announced yet.
|
|
91
180
|
let announced: { date: Temporal.PlainDate | null } | undefined
|
|
92
|
-
watch(model, (
|
|
181
|
+
watch(model, (v) => {
|
|
182
|
+
remember(v)
|
|
183
|
+
const d = toPlainDate(v)
|
|
93
184
|
// The parent set a different date, so whatever we announced before is no longer what's in the field.
|
|
94
|
-
if (!sameDay(d, settled))
|
|
185
|
+
if (!sameDay(d, settled)) {
|
|
186
|
+
announced = undefined
|
|
187
|
+
flag(null)
|
|
188
|
+
}
|
|
95
189
|
settled = d
|
|
96
190
|
text.value = show(d)
|
|
97
191
|
})
|
|
@@ -99,10 +193,9 @@ watch(model, (d) => {
|
|
|
99
193
|
watch(entryFormat, () => { text.value = show(settled) })
|
|
100
194
|
|
|
101
195
|
const inputCmp = useTemplateRef<{ inputRef: HTMLInputElement | null, $el: HTMLElement }>('inputCmp')
|
|
102
|
-
const panelId = useId()
|
|
103
196
|
|
|
104
197
|
function set(d: Temporal.PlainDate | null) {
|
|
105
|
-
if (!sameDay(d, settled)) model.value = d
|
|
198
|
+
if (!sameDay(d, settled)) model.value = out(d)
|
|
106
199
|
settled = d
|
|
107
200
|
text.value = show(d)
|
|
108
201
|
return d
|
|
@@ -110,9 +203,22 @@ function set(d: Temporal.PlainDate | null) {
|
|
|
110
203
|
|
|
111
204
|
// What's typed becomes the value — or nothing, when it isn't a date. Leaving "5/32" in the box would show one
|
|
112
205
|
// thing while the form saved another. Untouched text keeps the date as it is, so passing through the field
|
|
113
|
-
// can't blank a stored date it wouldn't read back (a year before 1000).
|
|
114
|
-
|
|
115
|
-
|
|
206
|
+
// can't blank a stored date it wouldn't read back (a year before 1000). A day the limits refuse keeps the date
|
|
207
|
+
// there was, drawn back in the box, and marks the field invalid: undefined, for nothing settled.
|
|
208
|
+
function commitText(): { date: Temporal.PlainDate | null } | undefined {
|
|
209
|
+
const next = commitDateEntry(text.value, settled, useToday(), entryFormat.value)
|
|
210
|
+
const refused = next && !sameDay(next, settled) ? checkDateLimits(next, limits.value) : null
|
|
211
|
+
if (refused) {
|
|
212
|
+
text.value = show(settled)
|
|
213
|
+
flag(refused)
|
|
214
|
+
return undefined
|
|
215
|
+
}
|
|
216
|
+
return { date: set(next) }
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function onType(v: string | number | null | undefined) {
|
|
220
|
+
text.value = v == null ? '' : String(v)
|
|
221
|
+
flag(null)
|
|
116
222
|
}
|
|
117
223
|
|
|
118
224
|
function focusInput() {
|
|
@@ -133,7 +239,7 @@ function isOurs(target: EventTarget | null) {
|
|
|
133
239
|
|
|
134
240
|
function announce(d: Temporal.PlainDate | null) {
|
|
135
241
|
announced = { date: d }
|
|
136
|
-
emit('dateUpdate', d)
|
|
242
|
+
emit('dateUpdate', out(d))
|
|
137
243
|
}
|
|
138
244
|
|
|
139
245
|
// Leaving settles the field, but a date already announced (by Enter, say) isn't announced again: an inline
|
|
@@ -160,7 +266,10 @@ function onKeydown(e: KeyboardEvent) {
|
|
|
160
266
|
}
|
|
161
267
|
if (e.key === 'Enter') {
|
|
162
268
|
open.value = false
|
|
163
|
-
|
|
269
|
+
const committed = commitText()
|
|
270
|
+
if (committed) announce(committed.date)
|
|
271
|
+
// Refused: the date it kept is selected, so typing another replaces it.
|
|
272
|
+
else nextTick(() => inputCmp.value?.inputRef?.select())
|
|
164
273
|
return
|
|
165
274
|
}
|
|
166
275
|
// Tab commits here, so the text is settled before focus moves; the blur that follows announces it, once.
|
|
@@ -169,12 +278,14 @@ function onKeydown(e: KeyboardEvent) {
|
|
|
169
278
|
open.value = false
|
|
170
279
|
return
|
|
171
280
|
}
|
|
172
|
-
if (e.key.length !== 1) return
|
|
281
|
+
if (e.key.length !== 1 || !isDateShortcut(e.key, entryFormat.value)) return
|
|
282
|
+
e.preventDefault()
|
|
173
283
|
const today = useToday()
|
|
174
|
-
// Shortcuts step from what's on screen, even if it hasn't been committed yet.
|
|
175
|
-
|
|
284
|
+
// Shortcuts step from what's on screen, even if it hasn't been committed yet. With no allowed day to go to, the
|
|
285
|
+
// key does nothing.
|
|
286
|
+
const next = applyDateShortcut(e.key, parseDateEntry(text.value, today, entryFormat.value) ?? settled, today, entryFormat.value, limits.value)
|
|
176
287
|
if (!next) return
|
|
177
|
-
|
|
288
|
+
flag(null)
|
|
178
289
|
announce(set(next))
|
|
179
290
|
// Selected, so typing a date replaces the shortcut's rather than appending to it.
|
|
180
291
|
nextTick(() => inputCmp.value?.inputRef?.select())
|
|
@@ -182,32 +293,41 @@ function onKeydown(e: KeyboardEvent) {
|
|
|
182
293
|
|
|
183
294
|
function clear() {
|
|
184
295
|
const d = set(null)
|
|
296
|
+
flag(null)
|
|
185
297
|
emit('clear')
|
|
186
298
|
announce(d)
|
|
187
299
|
focusInput()
|
|
188
300
|
}
|
|
189
301
|
|
|
190
302
|
// ── Calendar ──────────────────────────────────────────────────────────────────────────────────────────────
|
|
191
|
-
// CalendarDate
|
|
303
|
+
// UCalendar takes Nuxt UI's CalendarDate, a bare year/month/day, so the conversion is by fields both ways.
|
|
192
304
|
const toCalendar = (d: Temporal.PlainDate) => new CalendarDate(d.year, d.month, d.day)
|
|
193
305
|
|
|
194
306
|
// The selection follows text typed but not yet committed, as the month and the shortcuts do, so the picker and the
|
|
195
307
|
// input never disagree; untouched or unreadable text falls back to the model.
|
|
196
308
|
const calendarValue = computed(() => {
|
|
197
|
-
const day = parseDateEntry(text.value, useToday(), entryFormat.value) ?? model.value
|
|
309
|
+
const day = parseDateEntry(text.value, useToday(), entryFormat.value) ?? toPlainDate(model.value)
|
|
198
310
|
return day ? toCalendar(day) : undefined
|
|
199
311
|
})
|
|
200
312
|
// The month the calendar shows: the date in the box (typed or committed), else this month. Only read while
|
|
201
313
|
// the popover is open, which is only ever in the browser.
|
|
202
314
|
const calendarMonth = computed(() =>
|
|
203
|
-
toCalendar(parseDateEntry(text.value, useToday(), entryFormat.value) ?? model.value ?? useToday()),
|
|
315
|
+
toCalendar(parseDateEntry(text.value, useToday(), entryFormat.value) ?? toPlainDate(model.value) ?? useToday()),
|
|
204
316
|
)
|
|
317
|
+
// The limits, for the calendar to disable those days.
|
|
318
|
+
const calendarMin = computed(() => (limits.value.minValue ? toCalendar(limits.value.minValue as Temporal.PlainDate) : undefined))
|
|
319
|
+
const calendarMax = computed(() => (limits.value.maxValue ? toCalendar(limits.value.maxValue as Temporal.PlainDate) : undefined))
|
|
320
|
+
const calendarUnavailable = computed(() => {
|
|
321
|
+
const unavailable = limits.value.isDateUnavailable
|
|
322
|
+
return unavailable ? (v: CalendarDateLike) => unavailable(toPlainDate(v)!) : undefined
|
|
323
|
+
})
|
|
205
324
|
|
|
206
325
|
function onPick(v: unknown) {
|
|
207
|
-
|
|
208
|
-
|
|
326
|
+
const type = dateModelTypeOf(v)
|
|
327
|
+
if (type !== 'calendar-date') return
|
|
209
328
|
open.value = false
|
|
210
|
-
|
|
329
|
+
flag(null)
|
|
330
|
+
announce(set(toPlainDate(v as CalendarDateLike)))
|
|
211
331
|
focusInput()
|
|
212
332
|
}
|
|
213
333
|
|
|
@@ -248,16 +368,17 @@ defineExpose({ focus: focusInput })
|
|
|
248
368
|
takes Nuxt UI's highlight ring, so it reads as the one being edited. -->
|
|
249
369
|
<UInput
|
|
250
370
|
ref="inputCmp"
|
|
251
|
-
|
|
371
|
+
:model-value="text"
|
|
252
372
|
type="text"
|
|
253
373
|
autocomplete="off"
|
|
254
|
-
v-bind="
|
|
374
|
+
v-bind="{ ...$attrs, ...invalidAttrs }"
|
|
255
375
|
:size="size"
|
|
256
376
|
:icon="icon"
|
|
257
377
|
:disabled="disabled"
|
|
258
378
|
:placeholder="placeholder ?? entryFormat.pattern"
|
|
259
|
-
:highlight="highlight || open"
|
|
379
|
+
:highlight="highlight || open || !!problem"
|
|
260
380
|
:ui="{ ...ui, root: `group ${ui?.root ?? ''}` }"
|
|
381
|
+
@update:model-value="onType"
|
|
261
382
|
@keydown="onKeydown"
|
|
262
383
|
@blur="onBlur"
|
|
263
384
|
>
|
|
@@ -265,6 +386,8 @@ defineExpose({ focus: focusInput })
|
|
|
265
386
|
<UIcon :name="icon" data-slot="leadingIcon" :class="inputUi.leadingIcon({ class: ui?.leadingIcon })" @click="emit('iconClick', $event)" />
|
|
266
387
|
</template>
|
|
267
388
|
<template #trailing="{ ui: inputUi }">
|
|
389
|
+
<!-- Why a typed day was refused, for screen readers: the input's aria-describedby names it. -->
|
|
390
|
+
<span v-if="messageId" :id="messageId" class="sr-only">{{ problemMessage }}</span>
|
|
268
391
|
<!-- Neither button takes focus (mousedown is prevented), so the input never blurs to them. Each icon is
|
|
269
392
|
`text-current`, over Nuxt UI's dimmed trailing icon, so the button's own color reaches it. -->
|
|
270
393
|
<button
|
|
@@ -302,6 +425,9 @@ defineExpose({ focus: focusInput })
|
|
|
302
425
|
:locale="localeCode"
|
|
303
426
|
:size="size"
|
|
304
427
|
:view-control="headingButton"
|
|
428
|
+
:min-value="calendarMin"
|
|
429
|
+
:max-value="calendarMax"
|
|
430
|
+
:is-date-unavailable="calendarUnavailable"
|
|
305
431
|
weekday-format="narrow"
|
|
306
432
|
prevent-deselect
|
|
307
433
|
class="p-2"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zooui/nuxt",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
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
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
package/utils/date-entry.ts
CHANGED
|
@@ -13,6 +13,12 @@
|
|
|
13
13
|
// server route, a domain package). Temporal is the polyfill's own `/implementation`, never the bare entry, which
|
|
14
14
|
// resolves to `globalThis.Temporal` where an engine has one: one class wherever this runs, the same one
|
|
15
15
|
// a database client or serializer in the product hands out.
|
|
16
|
+
//
|
|
17
|
+
// THE TWO DAY TYPES. Everything here works in PlainDate. A field may also hold an @internationalized/date
|
|
18
|
+
// CalendarDate, the type Nuxt UI's UCalendar and UInputDate use: toPlainDate and fromPlainDate convert by the fields
|
|
19
|
+
// alone (year, month, day), and only a Gregorian one is accepted, since another calendar's year and month are not the
|
|
20
|
+
// ISO ones and converting them by their fields would land on a different day.
|
|
21
|
+
import { CalendarDate } from '@internationalized/date'
|
|
16
22
|
import { Temporal } from 'temporal-polyfill/implementation'
|
|
17
23
|
|
|
18
24
|
type PlainDate = Temporal.PlainDate
|
|
@@ -209,14 +215,63 @@ export function commitDateEntry(text: string, current: PlainDate | null, today:
|
|
|
209
215
|
*
|
|
210
216
|
* Pressing m, h, y or r again keeps walking, so "hhh" is the end of the month after next. The walk stops at
|
|
211
217
|
* FIRST_ENTRY_DATE and LAST_ENTRY_DATE, so a shortcut never lands on a day the field can't read back.
|
|
218
|
+
*
|
|
219
|
+
* With `limits`, it also stops at `minValue` and `maxValue`, and skips the days `isDateUnavailable` refuses:
|
|
220
|
+
*
|
|
221
|
+
* - `m` and `y` land on the first available day of the month or year, `h` and `r` on the last; pressed there, they
|
|
222
|
+
* go on to the month or year before (m, y) or after (h, r), as they do from the 1st or the 31st.
|
|
223
|
+
* - `+` and `-` go to the next or previous available day.
|
|
224
|
+
* - `t` is today, or the nearest allowed day to it: `minValue` when today is before it, `maxValue` when today is
|
|
225
|
+
* after it, and the next available day when today is unavailable (the one before, at `maxValue`).
|
|
226
|
+
*
|
|
227
|
+
* Unavailable days are looked through for a year at most. When no allowed day is in reach it returns null, as for a
|
|
228
|
+
* key that isn't a shortcut: isDateShortcut tells the two apart.
|
|
212
229
|
*/
|
|
213
|
-
export function applyDateShortcut(
|
|
230
|
+
export function applyDateShortcut(
|
|
231
|
+
key: string,
|
|
232
|
+
current: PlainDate | null,
|
|
233
|
+
today: PlainDate,
|
|
234
|
+
format: DateEntryFormat | string = US_DATE_ENTRY,
|
|
235
|
+
limits?: DateLimits,
|
|
236
|
+
): PlainDate | null {
|
|
214
237
|
if (key === formatOf(format).separator) return null
|
|
215
|
-
const
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
if (
|
|
219
|
-
|
|
238
|
+
const k = key.toLowerCase()
|
|
239
|
+
const base = current ?? today
|
|
240
|
+
const target = shortcutTarget(k, base, today)
|
|
241
|
+
if (!target) return null
|
|
242
|
+
const { lo, hi } = bounds(limits)
|
|
243
|
+
if (Temporal.PlainDate.compare(lo, hi) > 0) return null
|
|
244
|
+
const unavailable = limits?.isDateUnavailable
|
|
245
|
+
const walk = WALK[k]!
|
|
246
|
+
const inward = INWARD[k]
|
|
247
|
+
const day = nearestAllowed(target, inward ?? walk, lo, hi, unavailable)
|
|
248
|
+
if (!inward || !day || Temporal.PlainDate.compare(day, base) * walk > 0) return day
|
|
249
|
+
// The first available day of the month is where m already is (or after it): the month before's, as from the 1st.
|
|
250
|
+
const again = nearestAllowed(shortcutTarget(k, target.add({ days: walk }), today)!, inward, lo, hi, unavailable)
|
|
251
|
+
return again && Temporal.PlainDate.compare(again, base) * walk > 0 ? again : day
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// Which way each key moves, and for the period keys, which way to look for an available day from the period's edge.
|
|
255
|
+
const WALK: Record<string, 1 | -1> = { 't': 1, 'h': 1, 'r': 1, '+': 1, '=': 1, 'm': -1, 'y': -1, '-': -1, '_': -1 }
|
|
256
|
+
const INWARD: Record<string, 1 | -1> = { m: 1, y: 1, h: -1, r: -1 }
|
|
257
|
+
const UNAVAILABLE_SEARCH_DAYS = 366
|
|
258
|
+
|
|
259
|
+
// `target` pulled inside lo..hi, then the nearest available day from it: `step`'s way, or back into the bounds when
|
|
260
|
+
// it was pulled in. Null when there is none within the bounds and the search's year.
|
|
261
|
+
function nearestAllowed(target: PlainDate, step: 1 | -1, lo: PlainDate, hi: PlainDate, unavailable?: ((date: PlainDate) => boolean) | null) {
|
|
262
|
+
const dir = Temporal.PlainDate.compare(target, hi) > 0 ? -1 : Temporal.PlainDate.compare(target, lo) < 0 ? 1 : step
|
|
263
|
+
let day = clamp(target, lo, hi)
|
|
264
|
+
for (let i = 0; unavailable?.(day); i++) {
|
|
265
|
+
day = day.add({ days: dir })
|
|
266
|
+
if (i >= UNAVAILABLE_SEARCH_DAYS || Temporal.PlainDate.compare(day, lo) < 0 || Temporal.PlainDate.compare(day, hi) > 0) return null
|
|
267
|
+
}
|
|
268
|
+
return day
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** Whether `key` is one of applyDateShortcut's keys in this format (its separator never is), so a field can take the
|
|
272
|
+
* key even when the shortcut has no allowed day to go to. */
|
|
273
|
+
export function isDateShortcut(key: string, format: DateEntryFormat | string = US_DATE_ENTRY): boolean {
|
|
274
|
+
return key !== formatOf(format).separator && Object.hasOwn(WALK, key.toLowerCase())
|
|
220
275
|
}
|
|
221
276
|
|
|
222
277
|
function shortcutTarget(key: string, base: PlainDate, today: PlainDate): PlainDate | null {
|
|
@@ -243,3 +298,122 @@ function shortcutTarget(key: string, base: PlainDate, today: PlainDate): PlainDa
|
|
|
243
298
|
return null
|
|
244
299
|
}
|
|
245
300
|
}
|
|
301
|
+
|
|
302
|
+
// ── The two day types ───────────────────────────────────────────────────────────────────────────────────────────
|
|
303
|
+
|
|
304
|
+
/** What a field holds and hands back: a Temporal.PlainDate, or an @internationalized/date CalendarDate. */
|
|
305
|
+
export type DateModelType = 'plain-date' | 'calendar-date'
|
|
306
|
+
|
|
307
|
+
/** The part of an @internationalized/date CalendarDate read here. Matched by shape, not by class, so a CalendarDate
|
|
308
|
+
* from the product's own copy of the package is read the same as one from Nuxt UI's. */
|
|
309
|
+
export interface CalendarDateLike {
|
|
310
|
+
readonly calendar: { readonly identifier: string }
|
|
311
|
+
readonly era: string
|
|
312
|
+
readonly year: number
|
|
313
|
+
readonly month: number
|
|
314
|
+
readonly day: number
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** A day in either type. */
|
|
318
|
+
export type EntryDate = PlainDate | CalendarDateLike
|
|
319
|
+
|
|
320
|
+
/** Which of the two types `value` is, or null for anything else (null included). */
|
|
321
|
+
export function dateModelTypeOf(value: unknown): DateModelType | null {
|
|
322
|
+
if (value instanceof Temporal.PlainDate) return 'plain-date'
|
|
323
|
+
if (!value || typeof value !== 'object') return null
|
|
324
|
+
const v = value as Partial<CalendarDateLike>
|
|
325
|
+
return typeof v.calendar?.identifier === 'string' && typeof v.year === 'number' && typeof v.month === 'number' && typeof v.day === 'number'
|
|
326
|
+
? 'calendar-date'
|
|
327
|
+
: null
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* The day as a PlainDate: a PlainDate as it is, a Gregorian CalendarDate by its fields, null for null. A CalendarDate
|
|
332
|
+
* in any other calendar system (Japanese, Buddhist, Persian …) throws a RangeError rather than land on another day:
|
|
333
|
+
* convert it first with @internationalized/date's `toCalendar(date, new GregorianCalendar())`.
|
|
334
|
+
*/
|
|
335
|
+
export function toPlainDate(value: EntryDate | null | undefined): PlainDate | null {
|
|
336
|
+
if (value == null) return null
|
|
337
|
+
if (value instanceof Temporal.PlainDate) return value
|
|
338
|
+
if (dateModelTypeOf(value) !== 'calendar-date') throw new TypeError(`Not a day: expected a Temporal.PlainDate or an @internationalized/date CalendarDate, got ${String(value)}.`)
|
|
339
|
+
const { calendar, era, year, month, day } = value
|
|
340
|
+
if (calendar.identifier !== 'gregory') {
|
|
341
|
+
throw new RangeError(`Only a Gregorian CalendarDate can be used as a day here; this one is in the "${calendar.identifier}" calendar. Convert it with toCalendar(date, new GregorianCalendar()) from @internationalized/date.`)
|
|
342
|
+
}
|
|
343
|
+
// A Gregorian year counts within its era: 1 BC is the ISO year 0.
|
|
344
|
+
return Temporal.PlainDate.from({ year: era === 'BC' ? 1 - year : year, month, day }, { overflow: 'reject' })
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
type CalendarDateClass = new (year: number, month: number, day: number) => CalendarDateLike
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* The day in the type asked for: the PlainDate itself, or a Gregorian CalendarDate with its fields. `like`, a
|
|
351
|
+
* CalendarDate the caller already holds, names the class to build with, so the caller's own copy of
|
|
352
|
+
* @internationalized/date gets its own class back; without one it is the layer's.
|
|
353
|
+
*/
|
|
354
|
+
export function fromPlainDate(d: PlainDate, type: 'plain-date', like?: CalendarDateLike | null): PlainDate
|
|
355
|
+
export function fromPlainDate(d: PlainDate, type: 'calendar-date', like?: CalendarDateLike | null): CalendarDate
|
|
356
|
+
export function fromPlainDate(d: PlainDate, type: DateModelType, like?: CalendarDateLike | null): EntryDate
|
|
357
|
+
export function fromPlainDate(d: PlainDate | null, type: DateModelType, like?: CalendarDateLike | null): EntryDate | null
|
|
358
|
+
export function fromPlainDate(d: PlainDate | null, type: DateModelType, like?: CalendarDateLike | null): EntryDate | null {
|
|
359
|
+
if (!d || type === 'plain-date') return d
|
|
360
|
+
const Class = (like?.constructor ?? CalendarDate) as CalendarDateClass
|
|
361
|
+
return new Class(d.year, d.month, d.day)
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// ── Limits ──────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
365
|
+
|
|
366
|
+
/** The days a field takes, as Nuxt UI's UCalendar names them: the first and the last, and the days in between it
|
|
367
|
+
* refuses. `minValue` and `maxValue` may be either day type. */
|
|
368
|
+
export interface DateLimits {
|
|
369
|
+
minValue?: EntryDate | null
|
|
370
|
+
maxValue?: EntryDate | null
|
|
371
|
+
isDateUnavailable?: ((date: PlainDate) => boolean) | null
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** Why the limits refuse a day. */
|
|
375
|
+
export type DateLimitReason = 'before-min' | 'after-max' | 'unavailable'
|
|
376
|
+
|
|
377
|
+
/** A day the limits refuse: why, the day, and the limit it crossed (`minValue` or `maxValue`; null when unavailable).
|
|
378
|
+
* A PlainDate here; ZDateField's `invalid` hands it back in the model's own type. */
|
|
379
|
+
export interface DateLimitProblem<D = PlainDate> {
|
|
380
|
+
readonly reason: DateLimitReason
|
|
381
|
+
readonly date: D
|
|
382
|
+
readonly limit: D | null
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
const earlier = (a: PlainDate, b: PlainDate) => (Temporal.PlainDate.compare(a, b) <= 0 ? a : b)
|
|
386
|
+
const later = (a: PlainDate, b: PlainDate) => (Temporal.PlainDate.compare(a, b) >= 0 ? a : b)
|
|
387
|
+
const clamp = (d: PlainDate, lo: PlainDate, hi: PlainDate) => later(lo, earlier(d, hi))
|
|
388
|
+
|
|
389
|
+
// The first and last days a shortcut may land on: the limits', within the days a field can show and read back.
|
|
390
|
+
function bounds(limits?: DateLimits) {
|
|
391
|
+
const min = toPlainDate(limits?.minValue)
|
|
392
|
+
const max = toPlainDate(limits?.maxValue)
|
|
393
|
+
return { lo: min ? later(min, FIRST_ENTRY_DATE) : FIRST_ENTRY_DATE, hi: max ? earlier(max, LAST_ENTRY_DATE) : LAST_ENTRY_DATE }
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** Why the limits refuse `date`, or null when they take it. Checked in that order: before `minValue`, after
|
|
397
|
+
* `maxValue`, then `isDateUnavailable`. */
|
|
398
|
+
export function checkDateLimits(date: PlainDate, limits?: DateLimits): DateLimitProblem | null {
|
|
399
|
+
const min = toPlainDate(limits?.minValue)
|
|
400
|
+
if (min && Temporal.PlainDate.compare(date, min) < 0) return { reason: 'before-min', date, limit: min }
|
|
401
|
+
const max = toPlainDate(limits?.maxValue)
|
|
402
|
+
if (max && Temporal.PlainDate.compare(date, max) > 0) return { reason: 'after-max', date, limit: max }
|
|
403
|
+
if (limits?.isDateUnavailable?.(date)) return { reason: 'unavailable', date, limit: null }
|
|
404
|
+
return null
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** An English sentence for a refused day, its dates in the field's format: "Choose a date on or after 01/01/2026.",
|
|
408
|
+
* "Choose a date on or before 12/31/2026.", "12/25/2026 isn't available." A product in another language builds its
|
|
409
|
+
* own from the problem's `reason`, `date` and `limit`. */
|
|
410
|
+
export function dateLimitMessage(problem: DateLimitProblem, format: DateEntryFormat | string = US_DATE_ENTRY): string {
|
|
411
|
+
switch (problem.reason) {
|
|
412
|
+
case 'before-min':
|
|
413
|
+
return `Choose a date on or after ${formatDateEntry(problem.limit, format)}.`
|
|
414
|
+
case 'after-max':
|
|
415
|
+
return `Choose a date on or before ${formatDateEntry(problem.limit, format)}.`
|
|
416
|
+
case 'unavailable':
|
|
417
|
+
return `${formatDateEntry(problem.date, format)} isn't available.`
|
|
418
|
+
}
|
|
419
|
+
}
|