@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.
- package/README.md +14 -2
- package/components/DateField.vue +62 -265
- package/components/FileDropOverlay.vue +2 -1
- package/components/FilterSelect.vue +3 -6
- package/components/Highlight.vue +37 -0
- package/components/MaskedInput.vue +199 -0
- package/components/MonthField.vue +183 -0
- package/components/OptionalDate.vue +1 -1
- package/components/OrderList.vue +2 -2
- package/components/RepeatingList.vue +1 -1
- package/components/SearchInput.vue +135 -0
- package/components/Status.vue +22 -9
- package/components/UrlInput.vue +110 -0
- package/components/YearField.vue +143 -0
- package/components/confirm.ts +1 -3
- package/components/internal/EntryField.vue +317 -0
- package/components/internal/entry-field.ts +41 -0
- package/components/recipes.ts +13 -0
- package/composables/useNotify.ts +90 -0
- package/composables/useStatusStates.ts +45 -0
- package/nuxt.config.ts +7 -5
- package/package.json +14 -1
- package/plugins/error-message.ts +11 -0
- package/utils/date-entry.ts +9 -5
- package/utils/error-message.ts +96 -0
- package/utils/masked-input.ts +306 -0
- package/utils/month-entry.ts +283 -0
- package/utils/status-states.ts +97 -0
- package/utils/url-input.ts +71 -0
- package/utils/year-entry.ts +96 -0
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Toasts in one line, each tone with its own color, icon and duration, on Nuxt UI's `useToast`.
|
|
3
|
+
*
|
|
4
|
+
* const notify = useNotify()
|
|
5
|
+
* notify.success('Project saved')
|
|
6
|
+
* notify.warning('Two tasks have no owner', 'Assign them before the sprint starts.')
|
|
7
|
+
* try { await save() } catch (err) { notify.error('Couldn’t save the project', err) }
|
|
8
|
+
*
|
|
9
|
+
* The description may be the caught error itself: anything that isn't a string goes through `errorMessage()`, so the
|
|
10
|
+
* toast shows the server's message rather than trying to render the object. A third argument takes any of Nuxt UI's
|
|
11
|
+
* toast options (`duration`, `actions`, `icon`, `close`, `id`, `onClick` …) and wins over the tone's own.
|
|
12
|
+
*
|
|
13
|
+
* Defaults in app.config:
|
|
14
|
+
*
|
|
15
|
+
* zooui: { notify: { duration: 4000, tones: { error: { duration: 8000 }, success: { icon: 'i-lucide-circle-check' } } } }
|
|
16
|
+
*
|
|
17
|
+
* Toasts render in <UApp>'s toaster, so the app must be wrapped in one.
|
|
18
|
+
*/
|
|
19
|
+
import type { Toast } from '@nuxt/ui/composables'
|
|
20
|
+
import { errorMessage } from '../utils/error-message'
|
|
21
|
+
|
|
22
|
+
export type NotifyTone = 'primary' | 'success' | 'info' | 'warning' | 'error'
|
|
23
|
+
|
|
24
|
+
/** Any of Nuxt UI's toast fields; the title and description are the call's first two arguments. */
|
|
25
|
+
export type NotifyOptions = Omit<Partial<Toast>, 'title' | 'description'>
|
|
26
|
+
|
|
27
|
+
export interface NotifyToneConfig {
|
|
28
|
+
icon?: string
|
|
29
|
+
duration?: number
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** app.config `zooui.notify`. */
|
|
33
|
+
export interface NotifyConfig {
|
|
34
|
+
/** Every tone's duration in ms, unless the tone sets its own. Default 3000. */
|
|
35
|
+
duration?: number
|
|
36
|
+
tones?: Partial<Record<NotifyTone, NotifyToneConfig>>
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export const NOTIFY_DURATION = 3000
|
|
40
|
+
|
|
41
|
+
export const NOTIFY_ICONS: Record<NotifyTone, string> = {
|
|
42
|
+
primary: 'i-lucide-check',
|
|
43
|
+
success: 'i-lucide-check',
|
|
44
|
+
info: 'i-lucide-info',
|
|
45
|
+
warning: 'i-lucide-triangle-alert',
|
|
46
|
+
error: 'i-lucide-octagon-alert',
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A description, or a caught error as text; `undefined` when there is none. */
|
|
50
|
+
function describe(description: unknown): string | undefined {
|
|
51
|
+
if (description === null || description === undefined || description === '') return undefined
|
|
52
|
+
return typeof description === 'string' ? description : errorMessage(description)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function useNotify() {
|
|
56
|
+
const toast = useToast()
|
|
57
|
+
const config = useAppConfig() as { zooui?: { notify?: NotifyConfig } }
|
|
58
|
+
|
|
59
|
+
function show(tone: NotifyTone, title?: string | null, description?: unknown, options?: NotifyOptions): Toast {
|
|
60
|
+
const own = config.zooui?.notify
|
|
61
|
+
return toast.add({
|
|
62
|
+
color: tone,
|
|
63
|
+
icon: own?.tones?.[tone]?.icon ?? NOTIFY_ICONS[tone],
|
|
64
|
+
duration: own?.tones?.[tone]?.duration ?? own?.duration ?? NOTIFY_DURATION,
|
|
65
|
+
close: true,
|
|
66
|
+
...options,
|
|
67
|
+
title: title ?? undefined,
|
|
68
|
+
description: describe(description),
|
|
69
|
+
})
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
type Shortcut = (title?: string | null, description?: unknown, options?: NotifyOptions) => Toast
|
|
73
|
+
const tone = (t: NotifyTone): Shortcut => (title, description, options) => show(t, title, description, options)
|
|
74
|
+
|
|
75
|
+
const error = tone('error')
|
|
76
|
+
return {
|
|
77
|
+
primary: tone('primary'),
|
|
78
|
+
success: tone('success'),
|
|
79
|
+
info: tone('info'),
|
|
80
|
+
warning: tone('warning'),
|
|
81
|
+
error,
|
|
82
|
+
/** `error` under the name some codebases use for it. */
|
|
83
|
+
danger: error,
|
|
84
|
+
/** Nuxt UI's own, for a toast the shortcuts don't cover. */
|
|
85
|
+
add: toast.add,
|
|
86
|
+
update: toast.update,
|
|
87
|
+
remove: toast.remove,
|
|
88
|
+
clear: toast.clear,
|
|
89
|
+
}
|
|
90
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { AppConfig } from 'nuxt/schema'
|
|
2
|
+
import type { MaybeRefOrGetter } from 'vue'
|
|
3
|
+
import { status } from '../components/recipes'
|
|
4
|
+
import {
|
|
5
|
+
BUILT_IN_STATUS_STATES, mergeStatusStates, statusInfo, statusOptions,
|
|
6
|
+
type BuiltInStatus, type StatusColor, type StatusConfig, type StatusOption, type StatusState, type StatusStateMap,
|
|
7
|
+
} from '../utils/status-states'
|
|
8
|
+
|
|
9
|
+
/** The keys a product put under `zooui.status.states` in its app.config, read from Nuxt's generated types. */
|
|
10
|
+
type ConfiguredStatus = AppConfig extends { zooui: { status: { states: infer S } } } ? Extract<keyof S, string> : never
|
|
11
|
+
|
|
12
|
+
/** Every status a product has: the built-ins and its own, for autocomplete. Any other string still works and falls back. */
|
|
13
|
+
export type StatusKey = BuiltInStatus | ConfiguredStatus
|
|
14
|
+
|
|
15
|
+
export interface StatusOptionWithClass extends StatusOption {
|
|
16
|
+
/** The icon's color class, for ZFilterSelect's `icon-class-key` or a `#leading` slot. */
|
|
17
|
+
iconClass: string
|
|
18
|
+
/** The same class where USelectMenu and USelect read it, so their items' icons take the status's color. */
|
|
19
|
+
ui: { itemLeadingIcon: string }
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The product's status map: the five built-ins, then app.config `zooui.status.states`, then `states` (a prop, a ref or
|
|
24
|
+
* a getter), each over the last. `info(key)` is one entry, with the fallback for a key the map lacks; `options()` the
|
|
25
|
+
* map as select or filter items, in its order (or the order of the keys given); `keys` the map's keys in that order.
|
|
26
|
+
*/
|
|
27
|
+
export function useStatusStates(states?: MaybeRefOrGetter<StatusStateMap | undefined>) {
|
|
28
|
+
const config = useAppConfig() as { zooui?: { status?: StatusConfig } }
|
|
29
|
+
const own = computed(() => config.zooui?.status ?? {})
|
|
30
|
+
const map = computed<Record<string, StatusState>>(() => mergeStatusStates(BUILT_IN_STATUS_STATES, own.value.states, toValue(states)))
|
|
31
|
+
|
|
32
|
+
return {
|
|
33
|
+
states: map,
|
|
34
|
+
keys: computed(() => Object.keys(map.value) as (StatusKey | (string & {}))[]),
|
|
35
|
+
info: (key: StatusKey | (string & {}) | null | undefined) => statusInfo(map.value, key, own.value.fallback),
|
|
36
|
+
options: (keys?: readonly (StatusKey | (string & {}))[]): StatusOptionWithClass[] =>
|
|
37
|
+
statusOptions(map.value, keys).map((o) => {
|
|
38
|
+
const iconClass = statusIconClass(o.color)
|
|
39
|
+
return { ...o, iconClass, ui: { itemLeadingIcon: iconClass } }
|
|
40
|
+
}),
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The icon ink for a status color (recipes.ts holds the classes, where Tailwind sees them). */
|
|
45
|
+
export const statusIconClass = (color: StatusColor) => status.ink[color]
|
package/nuxt.config.ts
CHANGED
|
@@ -30,14 +30,15 @@ interface LayerNuxt {
|
|
|
30
30
|
hook(name: 'icon:clientBundleIcons', fn: (icons: Set<string>) => void): void
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
-
/** Icons the Z* components render, for the client bundle below. scripts/check-icons.test.mjs keeps it
|
|
34
|
-
* components/. */
|
|
33
|
+
/** Icons the Z* components and composables render, for the client bundle below. scripts/check-icons.test.mjs keeps it
|
|
34
|
+
* in step with components/ and composables/. */
|
|
35
35
|
const Z_ICONS = ['lucide:sun', 'lucide:moon', 'lucide:monitor', 'lucide:triangle-alert', 'lucide:check',
|
|
36
36
|
'lucide:circle-check', 'lucide:pencil', 'lucide:x', 'lucide:trash-2', 'lucide:plus', 'lucide:chevron-up', 'lucide:chevron-down', 'lucide:calendar',
|
|
37
37
|
'lucide:file', 'lucide:file-image', 'lucide:file-video', 'lucide:file-audio', 'lucide:file-spreadsheet',
|
|
38
38
|
'lucide:file-archive', 'lucide:file-text',
|
|
39
39
|
'lucide:list-filter', 'lucide:search', 'lucide:check-check', 'lucide:arrow-up-to-line', 'lucide:arrow-down-to-line',
|
|
40
|
-
'lucide:circle-alert'
|
|
40
|
+
'lucide:circle-alert', 'lucide:info', 'lucide:octagon-alert',
|
|
41
|
+
'lucide:circle-help']
|
|
41
42
|
|
|
42
43
|
export default defineNuxtConfig({
|
|
43
44
|
modules: [
|
|
@@ -71,8 +72,9 @@ export default defineNuxtConfig({
|
|
|
71
72
|
},
|
|
72
73
|
],
|
|
73
74
|
|
|
74
|
-
// Z* components, prefixed: <ZCard>, <ZStatus> … — .vue only: edge.ts and recipes.ts are their shared helpers.
|
|
75
|
-
components
|
|
75
|
+
// Z* components, prefixed: <ZCard>, <ZStatus> … — .vue only: edge.ts and recipes.ts are their shared helpers. Not
|
|
76
|
+
// internal/: the pieces Z* components are built from (the field under ZDateField, ZMonthField and ZYearField).
|
|
77
|
+
components: [{ path: resolve('./components'), prefix: 'Z', extensions: ['.vue'], ignore: ['internal/**'] }],
|
|
76
78
|
|
|
77
79
|
/**
|
|
78
80
|
* Exactly ONE @tailwindcss/vite, and it is Nuxt UI's (its module registers it). If anything else also registers
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zooui/nuxt",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.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": {
|
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
"components",
|
|
23
23
|
"composables",
|
|
24
24
|
"utils",
|
|
25
|
+
"plugins",
|
|
25
26
|
"testing"
|
|
26
27
|
],
|
|
27
28
|
"exports": {
|
|
@@ -31,6 +32,18 @@
|
|
|
31
32
|
"types": "./utils/date-entry.ts",
|
|
32
33
|
"default": "./utils/date-entry.ts"
|
|
33
34
|
},
|
|
35
|
+
"./masked-input": {
|
|
36
|
+
"types": "./utils/masked-input.ts",
|
|
37
|
+
"default": "./utils/masked-input.ts"
|
|
38
|
+
},
|
|
39
|
+
"./month-entry": {
|
|
40
|
+
"types": "./utils/month-entry.ts",
|
|
41
|
+
"default": "./utils/month-entry.ts"
|
|
42
|
+
},
|
|
43
|
+
"./year-entry": {
|
|
44
|
+
"types": "./utils/year-entry.ts",
|
|
45
|
+
"default": "./utils/year-entry.ts"
|
|
46
|
+
},
|
|
34
47
|
"./testing/find-conflicts": {
|
|
35
48
|
"types": "./testing/find-conflicts.d.ts",
|
|
36
49
|
"default": "./testing/find-conflicts.js"
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// errorMessage() reads the product's app.config `zooui.errorMessage` ({ extract, fallback }) whenever a call gives no
|
|
2
|
+
// options, wherever it is called from: a catch block in an event handler has no Nuxt context to look it up in.
|
|
3
|
+
import { configureErrorMessage, type ErrorMessageOptions } from '../utils/error-message'
|
|
4
|
+
|
|
5
|
+
export default defineNuxtPlugin({
|
|
6
|
+
name: 'zooui:error-message',
|
|
7
|
+
setup() {
|
|
8
|
+
const config = useAppConfig() as { zooui?: { errorMessage?: ErrorMessageOptions } }
|
|
9
|
+
configureErrorMessage(() => config.zooui?.errorMessage)
|
|
10
|
+
},
|
|
11
|
+
})
|
package/utils/date-entry.ts
CHANGED
|
@@ -93,10 +93,14 @@ function dayOf(year: number, month: number, day: number): PlainDate | null {
|
|
|
93
93
|
return first.with({ day })
|
|
94
94
|
}
|
|
95
95
|
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
96
|
+
/**
|
|
97
|
+
* A typed year's digits as a full year, or null. A one- or two-digit year lands within the 100 years ending 20 years
|
|
98
|
+
* from now: in 2026, "46" is 2046 and "47" is 1947. Far enough ahead for a loan's maturity date, near enough back
|
|
99
|
+
* for a building's year. Four digits are that year from 1000 on; three digits are no year. A year of all zeros
|
|
100
|
+
* ("0", "00", "0000") is no year at all: never 2000. ZDateField, ZMonthField and ZYearField all read a year this way.
|
|
101
|
+
*/
|
|
102
|
+
export function entryYear(digits: string, today: PlainDate): number | null {
|
|
103
|
+
if (!/^\d+$/.test(digits)) return null
|
|
100
104
|
if (/^0+$/.test(digits)) return null
|
|
101
105
|
if (digits.length === 4) return Number(digits) >= 1000 ? Number(digits) : null
|
|
102
106
|
if (digits.length > 2) return null
|
|
@@ -120,7 +124,7 @@ function dayFromParts(order: DateEntryOrder, parts: string[], today: PlainDate):
|
|
|
120
124
|
if (!DIGITS.test(month) || !DIGITS.test(day)) return null
|
|
121
125
|
if (parts.length === 2) return dayOf(today.year, Number(month), Number(day))
|
|
122
126
|
if (!/^\d+$/.test(part('Y'))) return null
|
|
123
|
-
const year =
|
|
127
|
+
const year = entryYear(part('Y'), today)
|
|
124
128
|
return year === null ? null : dayOf(year, Number(month), Number(day))
|
|
125
129
|
}
|
|
126
130
|
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `errorMessage(err)`: readable text for whatever a `catch` caught, so it can go straight into a toast's description
|
|
3
|
+
* (an object there would be rendered as a component) or onto the page.
|
|
4
|
+
*
|
|
5
|
+
* try { await $fetch('/api/projects', { method: 'POST', body }) }
|
|
6
|
+
* catch (err) { notify.error('Couldn’t save the project', errorMessage(err)) }
|
|
7
|
+
*
|
|
8
|
+
* A thrown `$fetch` error carries the response body in `data`; the body is read first, then the error itself. In order:
|
|
9
|
+
*
|
|
10
|
+
* 1. a string is its own message; `null` or `undefined` is the fallback
|
|
11
|
+
* 2. the product's own extractor (`app.config` `zooui.errorMessage.extract`), when it returns text
|
|
12
|
+
* 3. a list of errors, `validationErrors` or `errors`: an array, or a record of field → message(s); each entry a
|
|
13
|
+
* string, or an object with `detail`, `message` or `title`. Joined with ", ".
|
|
14
|
+
* 4. `detail` (RFC 9457 problem details)
|
|
15
|
+
* 5. `error`: a string, or an object read the same way
|
|
16
|
+
* 6. `message`
|
|
17
|
+
* 7. `title` — last of the body's, as a problem's title is the generic summary ("Validation failed")
|
|
18
|
+
* 8. the error's own `message`, then `title`, when the body had neither
|
|
19
|
+
* 9. `String(err)`, unless that is "[object Object]": then the fallback ("An error occurred")
|
|
20
|
+
*
|
|
21
|
+
* Framework-free (scripts/error-message.test.mjs); plugins/error-message.ts points it at app.config.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/** A product's own reader for its backend's error shape. Return the text, or nothing to fall through to the rest. */
|
|
25
|
+
export type ErrorMessageExtractor = (error: unknown) => string | null | undefined
|
|
26
|
+
|
|
27
|
+
export interface ErrorMessageOptions {
|
|
28
|
+
/** Read first, before any of the shapes Zoo UI knows. */
|
|
29
|
+
extract?: ErrorMessageExtractor
|
|
30
|
+
/** The text when nothing readable is found. Default: "An error occurred". */
|
|
31
|
+
fallback?: string
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export const ERROR_MESSAGE_FALLBACK = 'An error occurred'
|
|
35
|
+
|
|
36
|
+
type Bag = Record<string, unknown>
|
|
37
|
+
|
|
38
|
+
const isBag = (v: unknown): v is Bag => typeof v === 'object' && v !== null
|
|
39
|
+
const text = (v: unknown): string | undefined => (typeof v === 'string' && v !== '' ? v : undefined)
|
|
40
|
+
|
|
41
|
+
/** One entry of an `errors` list: a string, a number, a nested list, or an object with detail/message/title. */
|
|
42
|
+
function entries(value: unknown): string[] {
|
|
43
|
+
if (typeof value === 'string') return value ? [value] : []
|
|
44
|
+
if (typeof value === 'number') return [String(value)]
|
|
45
|
+
if (Array.isArray(value)) return value.flatMap(entries)
|
|
46
|
+
if (isBag(value)) {
|
|
47
|
+
const own = text(value.detail) ?? text(value.message) ?? text(value.title)
|
|
48
|
+
return own ? [own] : []
|
|
49
|
+
}
|
|
50
|
+
return []
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** `errors: ['a', 'b']`, `errors: [{ detail, pointer }]` or `errors: { name: ['Required'], email: 'Taken' }`. */
|
|
54
|
+
function list(value: unknown): string | undefined {
|
|
55
|
+
if (!isBag(value)) return undefined
|
|
56
|
+
const found = Array.isArray(value) ? entries(value) : Object.values(value).flatMap(entries)
|
|
57
|
+
return found.length ? found.join(', ') : undefined
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The shapes of a body, steps 3 to 7. `depth` stops an `error` that nests forever. */
|
|
61
|
+
function fromBody(body: Bag, depth: number): string | undefined {
|
|
62
|
+
const nested = depth < 3 && isBag(body.error) ? fromBody(body.error, depth + 1) : undefined
|
|
63
|
+
return list(body.validationErrors) ??
|
|
64
|
+
list(body.errors) ??
|
|
65
|
+
text(body.detail) ??
|
|
66
|
+
text(body.error) ??
|
|
67
|
+
nested ??
|
|
68
|
+
text(body.message) ??
|
|
69
|
+
text(body.title)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
let configured: () => ErrorMessageOptions | undefined = () => undefined
|
|
73
|
+
|
|
74
|
+
/** Where `errorMessage` finds its options when a call gives none: the app's `zooui.errorMessage` (set by the layer's
|
|
75
|
+
* plugin). A getter, so a later `updateAppConfig` is seen. */
|
|
76
|
+
export function configureErrorMessage(options: () => ErrorMessageOptions | undefined) {
|
|
77
|
+
configured = options
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Readable text for a caught error: the response body's message, the error's own, or the fallback. */
|
|
81
|
+
export function errorMessage(error: unknown, options: ErrorMessageOptions = configured() ?? {}): string {
|
|
82
|
+
const fallback = options.fallback ?? ERROR_MESSAGE_FALLBACK
|
|
83
|
+
if (typeof error === 'string') return error
|
|
84
|
+
if (error === null || error === undefined) return fallback
|
|
85
|
+
|
|
86
|
+
const own = text(options.extract?.(error))
|
|
87
|
+
if (own) return own
|
|
88
|
+
|
|
89
|
+
if (isBag(error)) {
|
|
90
|
+
const body = isBag(error.data) ? error.data : error
|
|
91
|
+
const found = fromBody(body, 0) ?? text(error.message) ?? text(error.title)
|
|
92
|
+
if (found) return found
|
|
93
|
+
}
|
|
94
|
+
const plain = String(error)
|
|
95
|
+
return plain === '[object Object]' ? fallback : plain
|
|
96
|
+
}
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
// What a masked field shows and how typing changes it, apart from <ZMaskedInput> so the rules read (and are tested,
|
|
2
|
+
// scripts/masked-input.test.mjs) in one place.
|
|
3
|
+
//
|
|
4
|
+
// A MASK is a pattern of tokens and literals: `#` a digit, `A` a letter, `*` a letter or digit, anything else a
|
|
5
|
+
// literal written for the person ("(###) ###-####"); a backslash makes a token character literal ("\#"). A field may
|
|
6
|
+
// have several masks, and which one formats the text is chosen afresh on every change:
|
|
7
|
+
//
|
|
8
|
+
// - by the separator typed: a literal typed where the mask in use has none, but another mask has it right there,
|
|
9
|
+
// chooses that mask ("12-" in a US tax-ID field chooses the EIN's ##-####### over the SSN's ###-##-####). The choice
|
|
10
|
+
// holds until the field is empty, or its whole text is replaced;
|
|
11
|
+
// - otherwise, the first mask that holds every character typed, or, if none does, the first that holds the most.
|
|
12
|
+
//
|
|
13
|
+
// A mask's literals are written once a character follows them, so "123" doesn't end in a dash, except in a mask a
|
|
14
|
+
// separator chose: there they are written as soon as the characters before them are in ("12-").
|
|
15
|
+
//
|
|
16
|
+
// Every change is rebuilt by `reformat`, with the caret kept on the same character as literals come and go, the way
|
|
17
|
+
// ZNumberInput keeps it on its digit (components/number-format.ts): the caret is counted in characters typed, not
|
|
18
|
+
// in text, and put back after the same count. `editMasked` is one keystroke or paste on top of that: Backspace or
|
|
19
|
+
// Delete over a literal takes the character beyond it (but Backspace at the end over the separator that chose the
|
|
20
|
+
// mask takes the separator, and the choice), a key that adds nothing is refused.
|
|
21
|
+
//
|
|
22
|
+
// Framework-free: Nuxt auto-imports it in a product, and `@zooui/nuxt/masked-input` imports it anywhere else (a
|
|
23
|
+
// server route validating the same value).
|
|
24
|
+
|
|
25
|
+
/** What one mask character accepts, and how it is written (`transform`: say, to upper case). */
|
|
26
|
+
export interface MaskToken {
|
|
27
|
+
readonly pattern: RegExp
|
|
28
|
+
readonly transform?: (c: string) => string
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The tokens every mask knows: `#` a digit, `A` a letter, `*` either. A field's `tokens` add to these, and one for
|
|
32
|
+
* the same character replaces it. */
|
|
33
|
+
export const MASK_TOKENS: Readonly<Record<string, MaskToken>> = {
|
|
34
|
+
'#': { pattern: /\d/ },
|
|
35
|
+
'A': { pattern: /[A-Za-z]/ },
|
|
36
|
+
'*': { pattern: /[A-Za-z\d]/ },
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
type Slot = { readonly token: MaskToken } | { readonly literal: string }
|
|
40
|
+
|
|
41
|
+
/** A pattern, read into its slots. Make one with `parseMask`; every function here also takes the pattern itself. */
|
|
42
|
+
export interface Mask {
|
|
43
|
+
readonly pattern: string
|
|
44
|
+
readonly slots: readonly Slot[]
|
|
45
|
+
/** How many characters it holds: its tokens. */
|
|
46
|
+
readonly capacity: number
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** One pattern or a list of them, as a field's `mask` prop takes them. */
|
|
50
|
+
export type MaskSource = string | Mask | readonly (string | Mask)[]
|
|
51
|
+
|
|
52
|
+
export function parseMask(pattern: string, tokens: Readonly<Record<string, MaskToken>> = MASK_TOKENS): Mask {
|
|
53
|
+
const slots: Slot[] = []
|
|
54
|
+
for (let i = 0; i < pattern.length; i++) {
|
|
55
|
+
const c = pattern[i]!
|
|
56
|
+
if (c === '\\' && i + 1 < pattern.length) slots.push({ literal: pattern[++i]! })
|
|
57
|
+
else if (tokens[c]) slots.push({ token: tokens[c] })
|
|
58
|
+
else slots.push({ literal: c })
|
|
59
|
+
}
|
|
60
|
+
return { pattern, slots, capacity: slots.filter((s) => 'token' in s).length }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** A field's masks, read. */
|
|
64
|
+
export function masksOf(source: MaskSource, tokens?: Readonly<Record<string, MaskToken>>): Mask[] {
|
|
65
|
+
const list = typeof source === 'string' || !Array.isArray(source) ? [source as string | Mask] : source as readonly (string | Mask)[]
|
|
66
|
+
return list.map((m) => (typeof m === 'string' ? parseMask(m, tokens) : m))
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const tokensOf = (mask: Mask) => mask.slots.flatMap((s) => ('token' in s ? [s.token] : []))
|
|
70
|
+
|
|
71
|
+
/** The literals a mask writes after `n` characters, before the next one: `(###) ###` after 3 is ") ". */
|
|
72
|
+
export function literalsAfter(mask: Mask, n: number): string {
|
|
73
|
+
let passed = 0, out = ''
|
|
74
|
+
for (const s of mask.slots) {
|
|
75
|
+
if ('token' in s) {
|
|
76
|
+
if (passed === n) return out
|
|
77
|
+
passed++
|
|
78
|
+
} else if (passed === n) out += s.literal
|
|
79
|
+
}
|
|
80
|
+
return out
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The field's text after a change, with the caret, and what it holds. */
|
|
84
|
+
export interface Masked {
|
|
85
|
+
readonly text: string
|
|
86
|
+
readonly caret: number
|
|
87
|
+
/** The characters typed, without the literals: "123456789" for "123-45-6789". */
|
|
88
|
+
readonly raw: string
|
|
89
|
+
/** Which of the masks formats it. */
|
|
90
|
+
readonly mask: number
|
|
91
|
+
/** The mask a separator chose, held until the field is empty; `null` when the first fit chooses. */
|
|
92
|
+
readonly chosen: number | null
|
|
93
|
+
/** Every character the mask holds is in. */
|
|
94
|
+
readonly complete: boolean
|
|
95
|
+
/** Characters typed that didn't fit (past the end, or of the wrong kind for their place). */
|
|
96
|
+
readonly overflow: number
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** What the field's masks take: a character some token accepts. Anything else is a separator, kept or not. */
|
|
100
|
+
const accepts = (masks: readonly Mask[], c: string) => masks.some((m) => tokensOf(m).some((t) => t.pattern.test(c)))
|
|
101
|
+
|
|
102
|
+
/** The characters a mask takes from the ones typed, in order, each in the next slot that accepts it. */
|
|
103
|
+
function fill(mask: Mask, typed: readonly string[]): { taken: string[], from: number[] } {
|
|
104
|
+
const tokens = tokensOf(mask)
|
|
105
|
+
const taken: string[] = [], from: number[] = []
|
|
106
|
+
typed.forEach((c, k) => {
|
|
107
|
+
const t = tokens[taken.length]
|
|
108
|
+
if (!t || !t.pattern.test(c)) return
|
|
109
|
+
taken.push(t.transform ? t.transform(c) : c)
|
|
110
|
+
from.push(k)
|
|
111
|
+
})
|
|
112
|
+
return { taken, from }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** The first mask that holds every character, else the first that holds the most. */
|
|
116
|
+
function firstFit(masks: readonly Mask[], typed: readonly string[]): number {
|
|
117
|
+
let best = 0, most = -1
|
|
118
|
+
for (let m = 0; m < masks.length; m++) {
|
|
119
|
+
const n = fill(masks[m]!, typed).taken.length
|
|
120
|
+
if (n === typed.length) return m
|
|
121
|
+
if (n > most) [best, most] = [m, n]
|
|
122
|
+
}
|
|
123
|
+
return best
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* The text as the field shows it, formatted by the mask that fits (see the top of this file), with the caret on the
|
|
128
|
+
* same character it was on. `chosen` is the mask a separator chose on an earlier change, if any. `typed` is the part
|
|
129
|
+
* of the input just typed or pasted: only a separator there may choose a mask, so one left behind by a deletion
|
|
130
|
+
* ("12-45" after Backspace in "123-|45") never does. Without it, the whole input counts, as for a value read in.
|
|
131
|
+
*/
|
|
132
|
+
export function reformat(input: string, caret: number, source: MaskSource, chosen: number | null = null, typed?: readonly [number, number]): Masked {
|
|
133
|
+
const masks = masksOf(source)
|
|
134
|
+
const chars: string[] = []
|
|
135
|
+
const separators: { c: string, n: number, k: number }[] = []
|
|
136
|
+
// the caret, as a count of the characters typed before it, and whether a separator was right before it
|
|
137
|
+
let at = 0, afterSeparator = false
|
|
138
|
+
for (let k = 0; k <= input.length; k++) {
|
|
139
|
+
if (k === caret) [at, afterSeparator] = [chars.length, k > 0 && !accepts(masks, input[k - 1]!)]
|
|
140
|
+
if (k === input.length) break
|
|
141
|
+
const c = input[k]!
|
|
142
|
+
if (accepts(masks, c)) chars.push(c)
|
|
143
|
+
else separators.push({ c, n: chars.length, k })
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// a separator where the fitting mask has none, and another mask has it right there, chooses that mask
|
|
147
|
+
let picked = chosen !== null && chosen < masks.length ? chosen : null
|
|
148
|
+
if (picked === null) {
|
|
149
|
+
const fit = masks[firstFit(masks, chars)]!
|
|
150
|
+
for (const { c, n, k } of separators) {
|
|
151
|
+
if (typed && (k < typed[0] || k >= typed[1])) continue
|
|
152
|
+
if (literalsAfter(fit, n).includes(c)) continue
|
|
153
|
+
const m = masks.findIndex((mask) => literalsAfter(mask, n).includes(c))
|
|
154
|
+
if (m >= 0) {
|
|
155
|
+
picked = m
|
|
156
|
+
break
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
const index = picked ?? firstFit(masks, chars)
|
|
161
|
+
const mask = masks[index]!
|
|
162
|
+
const { taken, from } = fill(mask, chars)
|
|
163
|
+
const eager = picked !== null
|
|
164
|
+
|
|
165
|
+
// written slot by slot: literals once a character follows them (or, eager, once the ones before them are in)
|
|
166
|
+
let text = '', i = 0, pending = ''
|
|
167
|
+
const ends: number[] = [] // the text's length after each character
|
|
168
|
+
const literal: boolean[] = []
|
|
169
|
+
const write = (s: string, isLiteral: boolean) => {
|
|
170
|
+
text += s
|
|
171
|
+
for (let j = 0; j < s.length; j++) literal.push(isLiteral)
|
|
172
|
+
}
|
|
173
|
+
for (const s of mask.slots) {
|
|
174
|
+
if ('literal' in s) {
|
|
175
|
+
pending += s.literal
|
|
176
|
+
continue
|
|
177
|
+
}
|
|
178
|
+
if (i >= taken.length) break
|
|
179
|
+
write(pending, true)
|
|
180
|
+
pending = ''
|
|
181
|
+
write(taken[i]!, false)
|
|
182
|
+
ends.push(text.length)
|
|
183
|
+
i++
|
|
184
|
+
}
|
|
185
|
+
if (pending && (eager || i === mask.capacity)) write(pending, true)
|
|
186
|
+
|
|
187
|
+
const before = from.filter((k) => k < at).length
|
|
188
|
+
let pos = before === 0 ? 0 : ends[before - 1]!
|
|
189
|
+
// typed just after a separator, the caret stays after the literals there ("12-|", not "12|-"); after the last
|
|
190
|
+
// character, it goes past any literals written after it ("(12)|")
|
|
191
|
+
if (afterSeparator || (before > 0 && before === taken.length)) while (pos < text.length && literal[pos]) pos++
|
|
192
|
+
|
|
193
|
+
return {
|
|
194
|
+
text,
|
|
195
|
+
caret: pos,
|
|
196
|
+
raw: taken.join(''),
|
|
197
|
+
mask: index,
|
|
198
|
+
chosen: text === '' ? null : picked,
|
|
199
|
+
complete: taken.length === mask.capacity,
|
|
200
|
+
overflow: chars.length - taken.length,
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** One change to the field: text typed or pasted over the selection, or a Backspace or Delete. */
|
|
205
|
+
export type MaskEdit = { insert: string } | { delete: 'backward' | 'forward' }
|
|
206
|
+
export interface MaskSelection { text: string, start: number, end: number }
|
|
207
|
+
|
|
208
|
+
const splice = (text: string, from: number, to: number, put = '') => text.slice(0, from) + put + text.slice(to)
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Where a deletion lands: the selection, or one character beside the caret, where a literal means the character
|
|
212
|
+
* beyond it (Backspace over "123-|45" deletes the 3, over "(555) |123" the last 5). With nothing beyond it, the
|
|
213
|
+
* literal itself. `null`: nothing to delete there.
|
|
214
|
+
*/
|
|
215
|
+
export function maskDeletion(sel: MaskSelection, direction: 'backward' | 'forward', source: MaskSource): [number, number] | null {
|
|
216
|
+
const masks = masksOf(source)
|
|
217
|
+
const { text, start, end } = sel
|
|
218
|
+
if (start !== end) return [start, end]
|
|
219
|
+
if (direction === 'backward') {
|
|
220
|
+
if (start === 0) return null
|
|
221
|
+
for (let k = start - 1; k >= 0; k--) if (accepts(masks, text[k]!)) return [k, k + 1]
|
|
222
|
+
return [start - 1, start]
|
|
223
|
+
}
|
|
224
|
+
if (start >= text.length) return null
|
|
225
|
+
for (let k = start; k < text.length; k++) if (accepts(masks, text[k]!)) return [k, k + 1]
|
|
226
|
+
return [start, start + 1]
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* The field after one edit, reformatted; `null` when the edit is refused and nothing changes, the selection included
|
|
231
|
+
* (a letter typed over a digit-only field's text leaves it there, selected). `chosen` is the mask a separator chose;
|
|
232
|
+
* an edit that replaces the whole text starts the choice afresh.
|
|
233
|
+
*/
|
|
234
|
+
export function editMasked(sel: MaskSelection, e: MaskEdit, source: MaskSource, chosen: number | null = null): Masked | null {
|
|
235
|
+
const masks = masksOf(source)
|
|
236
|
+
const { text, start, end } = sel
|
|
237
|
+
const keep = start === 0 && end === text.length && text !== '' ? null : chosen
|
|
238
|
+
if ('delete' in e) {
|
|
239
|
+
// Backspace over the separator that chose the mask, at the end ("12-|"), takes it and the choice back: "12".
|
|
240
|
+
// Unless the text would read the same without it ("(555) |", where the "(" chooses again): then as usual
|
|
241
|
+
if (e.delete === 'backward' && keep !== null && start === end && start === text.length && start > 0 && !accepts(masks, text[start - 1]!)) {
|
|
242
|
+
let k = start
|
|
243
|
+
while (k > 0 && !accepts(masks, text[k - 1]!)) k--
|
|
244
|
+
const r = reformat(text.slice(0, k), k, masks, null)
|
|
245
|
+
if (r.text !== text) return r
|
|
246
|
+
}
|
|
247
|
+
const range = maskDeletion(sel, e.delete, masks)
|
|
248
|
+
if (!range) return null
|
|
249
|
+
// Backspace leaves the caret where the character was; Delete leaves it where it is
|
|
250
|
+
return reformat(splice(text, range[0], range[1]), e.delete === 'backward' ? range[0] : start, masks, keep, [0, 0])
|
|
251
|
+
}
|
|
252
|
+
const put = e.insert
|
|
253
|
+
// nothing in it the field takes, or writes: refused before it clears a selection
|
|
254
|
+
const literals = new Set(masks.flatMap((m) => m.slots.flatMap((s) => ('literal' in s ? [s.literal] : []))))
|
|
255
|
+
if (![...put].some((c) => accepts(masks, c) || literals.has(c))) return null
|
|
256
|
+
const after = reformat(splice(text, start, end, put), start + put.length, masks, keep, [start, start + put.length])
|
|
257
|
+
if (start === end) {
|
|
258
|
+
// at a caret, an insertion that changes nothing (a separator the mask writes anyway), or pushes a character
|
|
259
|
+
// out of a full field, is refused
|
|
260
|
+
const base = reformat(text, start, masks, chosen, [0, 0])
|
|
261
|
+
if (after.text === base.text && after.caret === base.caret) return null
|
|
262
|
+
if (base.complete && after.overflow > base.overflow) return null
|
|
263
|
+
}
|
|
264
|
+
return after
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* The text a field formatted on commit (blur) shows: formatted by its mask when it holds a whole value and nothing
|
|
269
|
+
* else ("5551234567" or "555.123.4567" → "(555) 123-4567"), and as typed otherwise ("+44 20 7946 0958" stays).
|
|
270
|
+
*/
|
|
271
|
+
export function commitMasked(text: string, source: MaskSource): string {
|
|
272
|
+
const r = reformat(text, text.length, source)
|
|
273
|
+
return r.complete && r.overflow === 0 ? r.text : text
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Whether a text is a whole value written in one of the masks: "(555) 123-4567" is, "5551234567" and "(555) 12" are
|
|
277
|
+
* not. For a form's own rules, on the server as in the field. */
|
|
278
|
+
export function isMaskComplete(text: string | null | undefined, source: MaskSource): boolean {
|
|
279
|
+
if (!text) return false
|
|
280
|
+
const r = reformat(text, text.length, source)
|
|
281
|
+
return r.complete && r.overflow === 0 && r.text === text
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** The characters a text holds that its masks take, without the literals, as the field's `raw` model has them:
|
|
285
|
+
* "5551234567" for "(555) 123-4567", and every digit of a number typed in another form ("+44 20 7946 0958"). */
|
|
286
|
+
export function unmaskedValue(text: string | null | undefined, source: MaskSource): string {
|
|
287
|
+
const masks = masksOf(source)
|
|
288
|
+
return [...text ?? ''].filter((c) => accepts(masks, c)).join('')
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** What a preset sets: its masks, when it formats, and the input's attributes. Every one can be overridden. */
|
|
292
|
+
export interface MaskPreset {
|
|
293
|
+
readonly mask: readonly string[]
|
|
294
|
+
readonly formatOn: 'input' | 'blur'
|
|
295
|
+
readonly attrs: Readonly<Record<string, string>>
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* `phone`: a US number, (555) 123-4567, formatted on blur when the field holds ten digits and nothing else, and left
|
|
300
|
+
* as typed otherwise, so a number from elsewhere ("+44 20 7946 0958") goes in as it is. `tax-id`: a US SSN
|
|
301
|
+
* (123-45-6789) or EIN (12-3456789), formatted as typed; a dash after two digits chooses the EIN.
|
|
302
|
+
*/
|
|
303
|
+
export const MASK_PRESETS: Readonly<Record<'phone' | 'tax-id', MaskPreset>> = {
|
|
304
|
+
'phone': { mask: ['(###) ###-####'], formatOn: 'blur', attrs: { type: 'tel', inputmode: 'tel', autocomplete: 'tel' } },
|
|
305
|
+
'tax-id': { mask: ['###-##-####', '##-#######'], formatOn: 'input', attrs: { inputmode: 'numeric', placeholder: 'SSN or EIN' } },
|
|
306
|
+
}
|