@zooui/nuxt 0.3.1 → 0.4.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.
@@ -0,0 +1,283 @@
1
+ // What a person types into a month field, turned into a month of a year — and the one-key shortcuts that move it. The
2
+ // parsing behind <ZMonthField>, on ZDateField's rules (date-entry.ts): no JavaScript `Date`, "today" handed in by the
3
+ // caller, a two-digit year read as ZDateField reads one (entryYear), and the field order and separator a parameter.
4
+ //
5
+ // A month is a Temporal.PlainYearMonth. A field may also hold an @internationalized/date CalendarDate (the type Nuxt
6
+ // UI's UCalendar uses for a month too), read as the month it falls in and handed back as the first of it.
7
+ //
8
+ // Framework-free: Nuxt auto-imports it in a product, and `@zooui/nuxt/month-entry` imports it anywhere else.
9
+ import { CalendarDate } from '@internationalized/date'
10
+ import { Temporal } from 'temporal-polyfill/implementation'
11
+ import { dateEntryFormatFor, dateModelTypeOf, entryYear, toPlainDate, type CalendarDateLike } from './date-entry.ts'
12
+
13
+ type PlainDate = Temporal.PlainDate
14
+ type PlainYearMonth = Temporal.PlainYearMonth
15
+
16
+ /** The order a format writes a month's fields in: month then year, or year then month (ISO). */
17
+ export type MonthEntryOrder = 'MY' | 'YM'
18
+
19
+ /** How a field writes a month and reads one back. Make one with monthEntryFormat('MM/YYYY'); every function here also
20
+ * takes the pattern string itself. */
21
+ export interface MonthEntryFormat {
22
+ /** The pattern it was made from, `MM/YYYY` — what the field shows as its placeholder. */
23
+ readonly pattern: string
24
+ readonly order: MonthEntryOrder
25
+ /** The one character between the fields. */
26
+ readonly separator: string
27
+ }
28
+
29
+ const MONTH_PATTERN = /^(MM|YYYY)(.)(MM|YYYY)$/u
30
+ const monthFormats = new Map<string, MonthEntryFormat>()
31
+
32
+ /**
33
+ * A format from its pattern: `MM` and `YYYY` in either order with one separator between them that isn't a letter, a
34
+ * digit or a space — `MM/YYYY`, `MM.YYYY`, `YYYY-MM`. Throws a RangeError for anything else.
35
+ */
36
+ export function monthEntryFormat(pattern: string): MonthEntryFormat {
37
+ const cached = monthFormats.get(pattern)
38
+ if (cached) return cached
39
+ const match = MONTH_PATTERN.exec(pattern)
40
+ const separator = match?.[2] ?? ''
41
+ if (!match || match[1] === match[3] || /[\p{L}\p{N}\s]/u.test(separator)) {
42
+ throw new RangeError(`Not a month entry format: "${pattern}". Use MM and YYYY in either order with one separator between them, such as "MM/YYYY", "MM.YYYY" or "YYYY-MM".`)
43
+ }
44
+ const format = Object.freeze({ pattern, order: (match[1] === 'MM' ? 'MY' : 'YM') as MonthEntryOrder, separator })
45
+ monthFormats.set(pattern, format)
46
+ return format
47
+ }
48
+
49
+ /** The US format, and the default wherever a format is optional: MM/YYYY. */
50
+ export const US_MONTH_ENTRY = monthEntryFormat('MM/YYYY')
51
+
52
+ const formatOf = (f: MonthEntryFormat | string) => (typeof f === 'string' ? monthEntryFormat(f) : f)
53
+
54
+ /**
55
+ * The format a locale writes a month in: its numeric date format (dateEntryFormatFor) without the day, so a month
56
+ * field reads the same way as a date field beside it. `en` MM/YYYY, `en-GB` and `fr` MM/YYYY, `de` MM.YYYY, `sv` and
57
+ * `en-CA` YYYY-MM, `ja` YYYY/MM.
58
+ */
59
+ export function monthEntryFormatFor(locale: string): MonthEntryFormat {
60
+ const { order, separator } = dateEntryFormatFor(locale)
61
+ return monthEntryFormat(order === 'YMD' ? `YYYY${separator}MM` : `MM${separator}YYYY`)
62
+ }
63
+
64
+ // A month from parts, or null when there is no such month.
65
+ function monthOf(year: number | null, month: number): PlainYearMonth | null {
66
+ if (year === null || !Number.isInteger(year) || year < 1000 || year > 9999) return null
67
+ if (!Number.isInteger(month) || month < 1 || month > 12) return null
68
+ return Temporal.PlainYearMonth.from({ year, month })
69
+ }
70
+
71
+ const MONTH_DIGITS = /^\d{1,2}$/
72
+
73
+ // Two parts, a month and a year. A part of four digits can only be the year, so it is wherever it is written; two
74
+ // short parts are read in the format's order.
75
+ function monthFromParts(order: MonthEntryOrder, a: string, b: string, today: PlainDate): PlainYearMonth | null {
76
+ if (!/^\d+$/.test(a) || !/^\d+$/.test(b)) return null
77
+ const yearFirst = a.length > 2 || (b.length <= 2 && order === 'YM')
78
+ const [year, month] = yearFirst ? [a, b] : [b, a]
79
+ if (!MONTH_DIGITS.test(month)) return null
80
+ return monthOf(entryYear(year, today), Number(month))
81
+ }
82
+
83
+ /**
84
+ * Parse what was typed into a month field. Digits and the format's separator only (and ISO's `-` between a four-digit
85
+ * year and a month); anything else is not a month. In MM/YYYY (the default):
86
+ *
87
+ * - `5/26`, `05/26`, `5/2026`, `05/2026` — May 2026 (a two-digit year as ZDateField reads one)
88
+ * - `2026/5` and `2026-05` — May 2026 too: a four-digit part is the year, wherever it is written
89
+ * - `052026` — May 2026
90
+ * - `5`, `12` — that month this year
91
+ * - `2026` — a year alone is December of that year, the year's last month
92
+ *
93
+ * In YYYY-MM, two short parts read year first (`26-5` is May 2026) and six digits are YYYYMM; the rest reads the same.
94
+ * Returns null for anything that doesn't name a real month: blank text, month 0 or 13, three digits, a year before 1000
95
+ * or of all zeros.
96
+ */
97
+ export function parseMonthEntry(text: string, today: PlainDate, format: MonthEntryFormat | string = US_MONTH_ENTRY): PlainYearMonth | null {
98
+ const { order, separator } = formatOf(format)
99
+ const value = text.trim()
100
+ if (!value) return null
101
+ const iso = /^(\d{4})-(\d{1,2})$/.exec(value)
102
+ if (iso) return monthFromParts('YM', iso[1]!, iso[2]!, today)
103
+ if ([...value].some((c) => c !== separator && !/\d/.test(c))) return null
104
+
105
+ if (value.includes(separator)) {
106
+ const parts = value.split(separator)
107
+ return parts.length === 2 ? monthFromParts(order, parts[0]!, parts[1]!, today) : null
108
+ }
109
+ if (value.length <= 2) return monthOf(today.year, Number(value))
110
+ if (value.length === 4) return monthOf(entryYear(value, today), 12)
111
+ if (value.length === 6) {
112
+ return order === 'MY' ? monthFromParts('MY', value.slice(0, 2), value.slice(2), today) : monthFromParts('YM', value.slice(0, 4), value.slice(4), today)
113
+ }
114
+ return null
115
+ }
116
+
117
+ /** The month in the format (MM/YYYY by default), zero-padded — the form parseMonthEntry reads back. Empty for none. */
118
+ export function formatMonthEntry(m: PlainYearMonth | null | undefined, format: MonthEntryFormat | string = US_MONTH_ENTRY): string {
119
+ if (!m) return ''
120
+ const { order, separator } = formatOf(format)
121
+ const month = String(m.month).padStart(2, '0')
122
+ const year = String(m.year).padStart(4, '0')
123
+ return order === 'MY' ? `${month}${separator}${year}` : `${year}${separator}${month}`
124
+ }
125
+
126
+ /**
127
+ * The month a field holds once its text is committed: `current` while the text is still what formatMonthEntry drew
128
+ * for it, else what parseMonthEntry reads (null for blank or not a month).
129
+ */
130
+ export function commitMonthEntry(text: string, current: PlainYearMonth | null, today: PlainDate, format: MonthEntryFormat | string = US_MONTH_ENTRY): PlainYearMonth | null {
131
+ const typed = text.trim()
132
+ if (typed === formatMonthEntry(current, format)) return current
133
+ return typed ? parseMonthEntry(typed, today, format) : null
134
+ }
135
+
136
+ // The months a field can show and read back: a four-digit year, from 1000.
137
+ export const FIRST_ENTRY_MONTH = Temporal.PlainYearMonth.from({ year: 1000, month: 1 })
138
+ export const LAST_ENTRY_MONTH = Temporal.PlainYearMonth.from({ year: 9999, month: 12 })
139
+
140
+ // Months each key moves by; `t` is this month.
141
+ const MONTH_STEP: Record<string, number> = { 't': 0, 'y': -12, 'r': 12, 'm': -1, '-': -1, '_': -1, 'h': 1, '+': 1, '=': 1 }
142
+
143
+ /** Whether `key` is one of applyMonthShortcut's keys in this format (its separator never is), so a field can take the
144
+ * key even when the shortcut has nowhere to go. */
145
+ export function isMonthShortcut(key: string, format: MonthEntryFormat | string = US_MONTH_ENTRY): boolean {
146
+ return key !== formatOf(format).separator && Object.hasOwn(MONTH_STEP, key.toLowerCase())
147
+ }
148
+
149
+ /**
150
+ * The month a one-key shortcut moves to, or null when `key` isn't a shortcut (so the key types as usual). `current`
151
+ * is the field's month, or null when it is empty — then the shortcut works from this month.
152
+ *
153
+ * - `t` this month
154
+ * - `y` the same month a year before, `r` a year after
155
+ * - `m`, `-` or `_` the month before; `h`, `+` or `=` the month after
156
+ *
157
+ * The format's separator is never a shortcut, so it can be typed: in YYYY-MM, `-` writes a dash and `_` is the month
158
+ * before. It stops at FIRST_ENTRY_MONTH and LAST_ENTRY_MONTH, and at the limits' `minValue` and `maxValue` (`t`
159
+ * included: this month, or the nearest limit to it). Null when the limits leave no month at all.
160
+ */
161
+ export function applyMonthShortcut(
162
+ key: string,
163
+ current: PlainYearMonth | null,
164
+ today: PlainDate,
165
+ format: MonthEntryFormat | string = US_MONTH_ENTRY,
166
+ limits?: MonthLimits,
167
+ ): PlainYearMonth | null {
168
+ if (!isMonthShortcut(key, format)) return null
169
+ const k = key.toLowerCase()
170
+ const lo = laterMonth(toPlainYearMonth(limits?.minValue) ?? FIRST_ENTRY_MONTH, FIRST_ENTRY_MONTH)
171
+ const hi = earlierMonth(toPlainYearMonth(limits?.maxValue) ?? LAST_ENTRY_MONTH, LAST_ENTRY_MONTH)
172
+ if (Temporal.PlainYearMonth.compare(lo, hi) > 0) return null
173
+ const now = today.toPlainYearMonth()
174
+ const base = k === 't' ? now : (current ?? now)
175
+ // Stepped by month count, so it never throws past year 9999 or before year 1: the clamp below pulls it in.
176
+ const index = base.year * 12 + (base.month - 1) + MONTH_STEP[k]!
177
+ const target = Temporal.PlainYearMonth.from({ year: Math.floor(index / 12), month: (index % 12) + 1 })
178
+ return laterMonth(lo, earlierMonth(target, hi))
179
+ }
180
+
181
+ const earlierMonth = (a: PlainYearMonth, b: PlainYearMonth) => (Temporal.PlainYearMonth.compare(a, b) <= 0 ? a : b)
182
+ const laterMonth = (a: PlainYearMonth, b: PlainYearMonth) => (Temporal.PlainYearMonth.compare(a, b) >= 0 ? a : b)
183
+
184
+ // ── The two month types ─────────────────────────────────────────────────────────────────────────────────────────
185
+
186
+ /** What a month field holds and hands back: a Temporal.PlainYearMonth, or an @internationalized/date CalendarDate
187
+ * (the first of the month). */
188
+ export type MonthModelType = 'plain-year-month' | 'calendar-date'
189
+
190
+ /** A month in either type. */
191
+ export type EntryMonth = PlainYearMonth | CalendarDateLike
192
+
193
+ /** Which of the two types `value` is, or null for anything else (null included). */
194
+ export function monthModelTypeOf(value: unknown): MonthModelType | null {
195
+ if (value instanceof Temporal.PlainYearMonth) return 'plain-year-month'
196
+ return dateModelTypeOf(value) === 'calendar-date' ? 'calendar-date' : null
197
+ }
198
+
199
+ /**
200
+ * The month as a PlainYearMonth: a PlainYearMonth as it is, a Gregorian CalendarDate as the month it falls in (its
201
+ * day is ignored), null for null. A CalendarDate in another calendar system throws a RangeError, as toPlainDate does.
202
+ */
203
+ export function toPlainYearMonth(value: EntryMonth | null | undefined): PlainYearMonth | null {
204
+ if (value == null) return null
205
+ if (value instanceof Temporal.PlainYearMonth) return value
206
+ if (monthModelTypeOf(value) !== 'calendar-date') throw new TypeError(`Not a month: expected a Temporal.PlainYearMonth or an @internationalized/date CalendarDate, got ${String(value)}.`)
207
+ return toPlainDate(value)!.toPlainYearMonth()
208
+ }
209
+
210
+ type CalendarDateClass = new (year: number, month: number, day: number) => CalendarDateLike
211
+
212
+ /**
213
+ * The month in the type asked for: the PlainYearMonth itself, or a CalendarDate on the first of the month. `like`, a
214
+ * CalendarDate the caller already holds, names the class to build with, as for fromPlainDate.
215
+ */
216
+ export function fromPlainYearMonth(m: PlainYearMonth, type: 'plain-year-month', like?: CalendarDateLike | null): PlainYearMonth
217
+ export function fromPlainYearMonth(m: PlainYearMonth, type: 'calendar-date', like?: CalendarDateLike | null): CalendarDate
218
+ export function fromPlainYearMonth(m: PlainYearMonth, type: MonthModelType, like?: CalendarDateLike | null): EntryMonth
219
+ export function fromPlainYearMonth(m: PlainYearMonth | null, type: MonthModelType, like?: CalendarDateLike | null): EntryMonth | null
220
+ export function fromPlainYearMonth(m: PlainYearMonth | null, type: MonthModelType, like?: CalendarDateLike | null): EntryMonth | null {
221
+ if (!m || type === 'plain-year-month') return m
222
+ const Class = (like?.constructor ?? CalendarDate) as CalendarDateClass
223
+ return new Class(m.year, m.month, 1)
224
+ }
225
+
226
+ // ── Limits ──────────────────────────────────────────────────────────────────────────────────────────────────────
227
+
228
+ /** The months a field takes, as Nuxt UI's UCalendar names them: the first and the last, either type of month. */
229
+ export interface MonthLimits {
230
+ minValue?: EntryMonth | null
231
+ maxValue?: EntryMonth | null
232
+ }
233
+
234
+ /** Why the limits refuse a month. */
235
+ export type MonthLimitReason = 'before-min' | 'after-max'
236
+
237
+ /** A month the limits refuse: why, the month, and the limit it crossed. A PlainYearMonth here; ZMonthField's
238
+ * `invalid` hands it back in the model's own type. */
239
+ export interface MonthLimitProblem<M = PlainYearMonth> {
240
+ readonly reason: MonthLimitReason
241
+ readonly date: M
242
+ readonly limit: M
243
+ }
244
+
245
+ /** Why the limits refuse `month`, or null when they take it. */
246
+ export function checkMonthLimits(month: PlainYearMonth, limits?: MonthLimits): MonthLimitProblem | null {
247
+ const min = toPlainYearMonth(limits?.minValue)
248
+ if (min && Temporal.PlainYearMonth.compare(month, min) < 0) return { reason: 'before-min', date: month, limit: min }
249
+ const max = toPlainYearMonth(limits?.maxValue)
250
+ if (max && Temporal.PlainYearMonth.compare(month, max) > 0) return { reason: 'after-max', date: month, limit: max }
251
+ return null
252
+ }
253
+
254
+ /** An English sentence for a refused month, in the field's format: "Choose a month on or after 03/2026.", "Choose a
255
+ * month on or before 08/2026." A product in another language builds its own from `reason` and `limit`. */
256
+ export function monthLimitMessage(problem: MonthLimitProblem, format: MonthEntryFormat | string = US_MONTH_ENTRY): string {
257
+ return `Choose a month on or ${problem.reason === 'before-min' ? 'after' : 'before'} ${formatMonthEntry(problem.limit, format)}.`
258
+ }
259
+
260
+ // ── A month of the year, with no year ───────────────────────────────────────────────────────────────────────────
261
+
262
+ /** One month of the year for a USelect: `value` 1 (January) to 12, `label` its name in the locale. */
263
+ export interface MonthOfYearItem {
264
+ label: string
265
+ value: number
266
+ }
267
+
268
+ /**
269
+ * The twelve months as USelect items, named by Intl in `locale` (`en` by default): "January" … "December". `month`
270
+ * picks the name's length (`'long'`, `'short'`); `numbered` puts the month's number first, "1 - January", so a
271
+ * person can type it.
272
+ *
273
+ * <USelect v-model="month" :items="monthOfYearItems('en', { numbered: true })" />
274
+ */
275
+ export function monthOfYearItems(locale = 'en', options: { month?: 'long' | 'short', numbered?: boolean } = {}): MonthOfYearItem[] {
276
+ // Intl names a month of an instant, so it is handed a number of milliseconds in UTC (the 15th of each month of 2001),
277
+ // never a Date: only the month's name is read.
278
+ const name = new Intl.DateTimeFormat(locale, { month: options.month ?? 'long', timeZone: 'UTC' })
279
+ return Array.from({ length: 12 }, (_, i) => {
280
+ const label = name.format(Date.UTC(2001, i, 15))
281
+ return { label: options.numbered ? `${i + 1} - ${label}` : label, value: i + 1 }
282
+ })
283
+ }
@@ -0,0 +1,97 @@
1
+ // ZStatus's status map: a key → { label, icon, color }, so a product names its own statuses once (app.config
2
+ // `zooui.status.states`, or a component's `states` prop) and every ZStatus, select and filter reads the same entry.
3
+ //
4
+ // Layers merge field by field, later over earlier: the built-ins, then app.config, then the prop. A key keeps the
5
+ // place it first appeared in, so a product overriding a built-in leaves it where it was and new keys follow in the
6
+ // order they were written — that order is the one a select lists them in. An unknown key resolves to the fallback.
7
+ //
8
+ // Framework-free: Nuxt auto-imports it in a product.
9
+
10
+ /** Nuxt UI's semantic colors: a status is tinted with the product's palette, never a hard-coded one. */
11
+ export type StatusColor = 'primary' | 'secondary' | 'success' | 'info' | 'warning' | 'error' | 'neutral'
12
+
13
+ /** The five states ZStatus draws by shape. */
14
+ export type BuiltInStatus = 'healthy' | 'warn' | 'suspended' | 'unreachable' | 'quiet'
15
+
16
+ /** One status as a product writes it. Every field is optional on an override; a new key's label defaults to the key. */
17
+ export interface StatusStateInput {
18
+ label?: string
19
+ /** An Iconify name (`i-lucide-pencil-line`). Without one, a product status is a dot in its color. */
20
+ icon?: string
21
+ color?: StatusColor
22
+ }
23
+
24
+ /** One status, resolved. `shape` names the built-in drawing it keeps (a built-in whose icon and color are untouched). */
25
+ export interface StatusState {
26
+ label: string
27
+ icon?: string
28
+ color: StatusColor
29
+ shape?: BuiltInStatus
30
+ }
31
+
32
+ export type StatusStateMap = Record<string, StatusStateInput>
33
+
34
+ /** What a product sets once, in its app.config under `zooui.status`. */
35
+ export interface StatusConfig {
36
+ states?: StatusStateMap
37
+ /** What an unknown key shows: `Unknown` with a help icon, in neutral, unless the product says otherwise. */
38
+ fallback?: StatusStateInput
39
+ }
40
+
41
+ export const BUILT_IN_STATUS_STATES: Readonly<Record<BuiltInStatus, StatusState>> = {
42
+ healthy: { label: 'Healthy', color: 'success', shape: 'healthy' },
43
+ warn: { label: 'Near limit', color: 'warning', shape: 'warn' },
44
+ suspended: { label: 'Suspended', color: 'neutral', shape: 'suspended' },
45
+ unreachable: { label: 'Unreachable', color: 'error', shape: 'unreachable' },
46
+ quiet: { label: 'Quiet', color: 'neutral', shape: 'quiet' },
47
+ }
48
+
49
+ export const STATUS_FALLBACK: Readonly<StatusState> = { label: 'Unknown', icon: 'i-lucide-circle-help', color: 'neutral' }
50
+
51
+ /** Merge status maps, later over earlier, field by field; the first map is usually BUILT_IN_STATUS_STATES. */
52
+ export function mergeStatusStates(...maps: (StatusStateMap | undefined)[]): Record<string, StatusState> {
53
+ const out: Record<string, StatusState> = {}
54
+ for (const map of maps) {
55
+ for (const [key, input] of Object.entries(map ?? {})) {
56
+ const prev = out[key]
57
+ const next: StatusState = {
58
+ label: input.label ?? prev?.label ?? key,
59
+ color: input.color ?? prev?.color ?? 'neutral',
60
+ }
61
+ const icon = input.icon ?? prev?.icon
62
+ if (icon) next.icon = icon
63
+ // A built-in keeps its shape only while it still looks like itself: a new icon or color is the product's drawing.
64
+ const shape = (input as StatusState).shape ?? prev?.shape
65
+ if (shape && !icon && next.color === BUILT_IN_STATUS_STATES[shape].color) next.shape = shape
66
+ out[key] = next
67
+ }
68
+ }
69
+ return out
70
+ }
71
+
72
+ /** The entry for `key`, or the fallback (merged over STATUS_FALLBACK) when the map has none. */
73
+ export function statusInfo(states: Record<string, StatusState>, key: string | null | undefined, fallback?: StatusStateInput): StatusState & { known: boolean } {
74
+ const hit = key != null && Object.hasOwn(states, key) ? states[key] : undefined
75
+ if (hit) return { ...hit, known: true }
76
+ return { ...mergeStatusStates({ fallback: STATUS_FALLBACK }, fallback && { fallback }).fallback!, known: false }
77
+ }
78
+
79
+ export interface StatusOption {
80
+ label: string
81
+ value: string
82
+ icon?: string
83
+ color: StatusColor
84
+ /** For an entry without an icon, a USelectMenu chip in its color. */
85
+ chip?: { color: StatusColor }
86
+ }
87
+
88
+ /** The map as items for a select or filter, in map order — or in the order of `keys`, when given. */
89
+ export function statusOptions(states: Record<string, StatusState>, keys?: readonly string[]): StatusOption[] {
90
+ return (keys ?? Object.keys(states)).map((value) => {
91
+ const info = statusInfo(states, value)
92
+ const option: StatusOption = { label: info.label, value, color: info.color }
93
+ if (info.icon) option.icon = info.icon
94
+ else option.chip = { color: info.color }
95
+ return option
96
+ })
97
+ }
@@ -0,0 +1,71 @@
1
+ // A website address, as a person types one into a form: "example.com", "www.example.com/about", "http://example.com".
2
+ // ZUrlInput runs commitWebAddress on blur; a product can run the same checks in its own form rules.
3
+ //
4
+ // NORMALIZING. The text is trimmed; an `http://` or `https://` in front (in any case) is replaced by `https://`, and
5
+ // anything without one gets `https://` added. Only http and https are read as schemes: "ftp://example.com" becomes
6
+ // "https://ftp://example.com", which then fails the check rather than passing as something it isn't. The rest of
7
+ // the text is kept as typed (its case, path, query and fragment): the value is the person's address, not the URL
8
+ // parser's rewrite of it.
9
+ //
10
+ // `www.` IS OPT-IN. With `addWww`, a host of exactly two labels ("example.com", not "app.example.com") gets `www.` in
11
+ // front. That is wrong for many real sites — "example.app" or a bare-domain shop may have no `www` host at all, and
12
+ // the address would then point nowhere — so it is off unless a product knows its addresses want it.
13
+ //
14
+ // CHECKING. A web address is https, with no user name or password (an email address typed in the wrong box,
15
+ // "sam@example.com", parses as a URL with a user), and a host of at least two labels after any leading `www.`:
16
+ // letters, digits, hyphens and underscores, no empty label, and a top-level domain of two or more letters (or an
17
+ // internationalized one, `xn--…`). So "localhost", "example", "example.", "192.168.1.10" and "www.com" are refused.
18
+ // Hosts are read as the URL parser reads them, so "bücher.de" is checked as "xn--bcher-kva.de" and passes.
19
+ //
20
+ // Framework-free: Nuxt auto-imports it in a product.
21
+
22
+ export interface WebAddressOptions {
23
+ /** Add `www.` in front of a two-label host ("example.com" → "www.example.com"). Off by default. */
24
+ addWww?: boolean
25
+ }
26
+
27
+ export interface WebAddressCommit {
28
+ /** What the field should hold: the normalized address, the trimmed text when it isn't one, or null when empty. */
29
+ value: string | null
30
+ /** False when there was text and it isn't a web address. */
31
+ valid: boolean
32
+ }
33
+
34
+ const SCHEME = /^https?:\/\//i
35
+ const LABEL = /^[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?$/
36
+ const TLD = /^(?:[a-z]{2,63}|xn--[a-z0-9-]{1,59})$/
37
+
38
+ /** The text as an https address: trimmed, `https://` in front, `www.` added when asked. Empty text stays empty. */
39
+ export function normalizeWebAddress(text: string, options: WebAddressOptions = {}): string {
40
+ let rest = text.trim()
41
+ if (!rest) return ''
42
+ rest = rest.replace(SCHEME, '')
43
+ if (options.addWww) {
44
+ // The host is what comes before the path, query or fragment, without a port.
45
+ const host = (rest.split(/[/?#]/, 1)[0] ?? '').replace(/:\d*$/, '')
46
+ if (!/^www\./i.test(host) && host.split('.').length === 2) rest = `www.${rest}`
47
+ }
48
+ return `https://${rest}`
49
+ }
50
+
51
+ /** Whether an address (as normalizeWebAddress writes one) is https to a real host with a top-level domain. */
52
+ export function isWebAddress(address: string): boolean {
53
+ let url: URL
54
+ try {
55
+ url = new URL(address)
56
+ } catch {
57
+ return false
58
+ }
59
+ if (url.protocol !== 'https:' || url.username || url.password) return false
60
+ const labels = url.hostname.replace(/^www\./, '').split('.')
61
+ if (labels.length < 2 || !labels.every((label) => LABEL.test(label))) return false
62
+ return TLD.test(labels[labels.length - 1]!)
63
+ }
64
+
65
+ /** What a field holds once its text is committed (on blur): see WebAddressCommit. */
66
+ export function commitWebAddress(text: string, options: WebAddressOptions = {}): WebAddressCommit {
67
+ const trimmed = text.trim()
68
+ if (!trimmed) return { value: null, valid: true }
69
+ const address = normalizeWebAddress(trimmed, options)
70
+ return isWebAddress(address) ? { value: address, valid: true } : { value: trimmed, valid: false }
71
+ }
@@ -0,0 +1,96 @@
1
+ // What a person types into a year field, turned into a year — and the one-key shortcuts that move it. The parsing
2
+ // behind <ZYearField>, on the same rules as ZDateField's (date-entry.ts): a year is a plain number, "today" is handed
3
+ // in by the caller, and a two-digit year reads as ZDateField reads one (entryYear).
4
+ //
5
+ // Framework-free: Nuxt auto-imports it in a product, and `@zooui/nuxt/year-entry` imports it anywhere else.
6
+ import type { Temporal } from 'temporal-polyfill/implementation'
7
+ import { entryYear } from './date-entry.ts'
8
+
9
+ type PlainDate = Temporal.PlainDate
10
+
11
+ /** The years a field can show and read back: four digits, from 1000 (a typed "0026" is far likelier a slip). */
12
+ export const FIRST_ENTRY_YEAR = 1000
13
+ export const LAST_ENTRY_YEAR = 9999
14
+
15
+ /**
16
+ * Parse what was typed into a year field: `2026`, or `26` and `6` (within the 100 years ending 20 years from now, as
17
+ * ZDateField reads a two-digit year: in 2026, `46` is 2046 and `47` is 1947). Digits only; anything else, blank text,
18
+ * three digits, a year before 1000 and a year of all zeros are null.
19
+ */
20
+ export function parseYearEntry(text: string, today: PlainDate): number | null {
21
+ return entryYear(text.trim(), today)
22
+ }
23
+
24
+ /** The year as the field writes it, four digits. Empty for no year. */
25
+ export function formatYearEntry(year: number | null | undefined): string {
26
+ return year == null ? '' : String(year).padStart(4, '0')
27
+ }
28
+
29
+ /**
30
+ * The year a field holds once its text is committed: `current` while the text is still what formatYearEntry drew for
31
+ * it, else what parseYearEntry reads (null for blank or not a year).
32
+ */
33
+ export function commitYearEntry(text: string, current: number | null, today: PlainDate): number | null {
34
+ const typed = text.trim()
35
+ if (typed === formatYearEntry(current)) return current
36
+ return typed ? parseYearEntry(typed, today) : null
37
+ }
38
+
39
+ /** The years a field takes: the first and the last. */
40
+ export interface YearLimits {
41
+ minValue?: number | null
42
+ maxValue?: number | null
43
+ }
44
+
45
+ const STEP: Record<string, 1 | -1 | 0> = { 't': 0, 'r': 1, '+': 1, '=': 1, 'y': -1, '-': -1, '_': -1 }
46
+
47
+ /** Whether `key` is one of applyYearShortcut's keys, so a field can take the key even when it has nowhere to go. */
48
+ export function isYearShortcut(key: string): boolean {
49
+ return Object.hasOwn(STEP, key.toLowerCase())
50
+ }
51
+
52
+ /**
53
+ * The year a one-key shortcut moves to, or null when `key` isn't a shortcut. `current` is the field's year, or null
54
+ * when it is empty — then the shortcut works from this year.
55
+ *
56
+ * - `t` this year
57
+ * - `y`, `-` or `_` the year before
58
+ * - `r`, `+` or `=` the year after
59
+ *
60
+ * It stops at FIRST_ENTRY_YEAR and LAST_ENTRY_YEAR, and at the limits' `minValue` and `maxValue` (`t` included: this
61
+ * year, or the nearest limit to it). Null when the limits leave no year at all.
62
+ */
63
+ export function applyYearShortcut(key: string, current: number | null, today: PlainDate, limits?: YearLimits): number | null {
64
+ const k = key.toLowerCase()
65
+ if (!Object.hasOwn(STEP, k)) return null
66
+ const lo = Math.max(limits?.minValue ?? FIRST_ENTRY_YEAR, FIRST_ENTRY_YEAR)
67
+ const hi = Math.min(limits?.maxValue ?? LAST_ENTRY_YEAR, LAST_ENTRY_YEAR)
68
+ if (lo > hi) return null
69
+ const target = k === 't' ? today.year : (current ?? today.year) + STEP[k]!
70
+ return Math.min(Math.max(target, lo), hi)
71
+ }
72
+
73
+ /** Why the limits refuse a year. */
74
+ export type YearLimitReason = 'before-min' | 'after-max'
75
+
76
+ /** A year the limits refuse: why, the year, and the limit it crossed. */
77
+ export interface YearLimitProblem {
78
+ readonly reason: YearLimitReason
79
+ readonly date: number
80
+ readonly limit: number
81
+ }
82
+
83
+ /** Why the limits refuse `year`, or null when they take it. */
84
+ export function checkYearLimits(year: number, limits?: YearLimits): YearLimitProblem | null {
85
+ const min = limits?.minValue
86
+ if (min != null && year < min) return { reason: 'before-min', date: year, limit: min }
87
+ const max = limits?.maxValue
88
+ if (max != null && year > max) return { reason: 'after-max', date: year, limit: max }
89
+ return null
90
+ }
91
+
92
+ /** An English sentence for a refused year, as ZDateField words one: "Choose a year on or after 2020.", "Choose a year
93
+ * on or before 2030." A product in another language builds its own from the problem's `reason` and `limit`. */
94
+ export function yearLimitMessage(problem: YearLimitProblem): string {
95
+ return `Choose a year on or ${problem.reason === 'before-min' ? 'after' : 'before'} ${formatYearEntry(problem.limit)}.`
96
+ }