@fabrika/ui 0.9.0-dev.37 → 0.9.0-dev.38
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/package.json +1 -1
- package/src/Field.tsx +26 -5
- package/src/FormDialog.tsx +107 -0
- package/src/index.ts +12 -1
- package/src/use-form.ts +145 -0
- package/types/src/Field.d.ts +14 -4
- package/types/src/FormDialog.d.ts +30 -0
- package/types/src/index.d.ts +3 -1
- package/types/src/use-form.d.ts +63 -0
package/package.json
CHANGED
package/src/Field.tsx
CHANGED
|
@@ -1,7 +1,13 @@
|
|
|
1
|
-
import { createContext, isValidElement, type ReactNode, useContext, useId } from 'react'
|
|
1
|
+
import { type ChangeEventHandler, createContext, isValidElement, type ReactNode, useContext, useId } from 'react'
|
|
2
2
|
import { classNames } from './class-names'
|
|
3
3
|
import { useFormFieldError } from './Form'
|
|
4
4
|
|
|
5
|
+
/** A text value the control inside a `Field` shows and changes, such as one `useForm` holds. */
|
|
6
|
+
export interface FieldBinding {
|
|
7
|
+
readonly value: string
|
|
8
|
+
readonly onChange: (value: string) => void
|
|
9
|
+
}
|
|
10
|
+
|
|
5
11
|
/** What a `Field` hands the one control inside it. */
|
|
6
12
|
export interface FieldControl {
|
|
7
13
|
readonly id: string
|
|
@@ -9,6 +15,7 @@ export interface FieldControl {
|
|
|
9
15
|
readonly describedBy: string | undefined
|
|
10
16
|
readonly invalid: boolean
|
|
11
17
|
readonly required: boolean
|
|
18
|
+
readonly bind: FieldBinding | undefined
|
|
12
19
|
}
|
|
13
20
|
|
|
14
21
|
const FieldContext = createContext<FieldControl | undefined>(undefined)
|
|
@@ -23,6 +30,8 @@ export interface FieldProps {
|
|
|
23
30
|
readonly hint?: ReactNode
|
|
24
31
|
readonly error?: string
|
|
25
32
|
readonly required?: boolean
|
|
33
|
+
/** Binds the control's value: it shows `bind.value` and reports each change to `bind.onChange`. */
|
|
34
|
+
readonly bind?: FieldBinding
|
|
26
35
|
readonly children: ReactNode
|
|
27
36
|
readonly className?: string
|
|
28
37
|
}
|
|
@@ -34,7 +43,7 @@ function explicitId(children: ReactNode): string | undefined {
|
|
|
34
43
|
return typeof id === 'string' && id !== '' ? id : undefined
|
|
35
44
|
}
|
|
36
45
|
|
|
37
|
-
export function Field({ label, name, hint, error, required = false, children, className }: FieldProps) {
|
|
46
|
+
export function Field({ label, name, hint, error, required = false, bind, children, className }: FieldProps) {
|
|
38
47
|
const generated = useId()
|
|
39
48
|
const id = explicitId(children) ?? generated
|
|
40
49
|
const formError = useFormFieldError(name)
|
|
@@ -42,7 +51,7 @@ export function Field({ label, name, hint, error, required = false, children, cl
|
|
|
42
51
|
const hintId = hint === undefined ? undefined : `${id}-hint`
|
|
43
52
|
const errorId = message === undefined ? undefined : `${id}-error`
|
|
44
53
|
const describedBy = [hintId, errorId].filter((value) => value !== undefined).join(' ') || undefined
|
|
45
|
-
const control: FieldControl = { id, name, describedBy, invalid: message !== undefined, required }
|
|
54
|
+
const control: FieldControl = { id, name, describedBy, invalid: message !== undefined, required, bind }
|
|
46
55
|
return (
|
|
47
56
|
<div className={classNames('fui-field', message !== undefined && 'fui-field--invalid', className)}>
|
|
48
57
|
<label className="fui-field__label" htmlFor={id}>
|
|
@@ -68,24 +77,36 @@ export function Field({ label, name, hint, error, required = false, children, cl
|
|
|
68
77
|
)
|
|
69
78
|
}
|
|
70
79
|
|
|
71
|
-
interface ControlAttributes {
|
|
80
|
+
interface ControlAttributes<E extends HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement> {
|
|
72
81
|
readonly id?: string
|
|
73
82
|
readonly name?: string
|
|
74
83
|
readonly required?: boolean
|
|
84
|
+
readonly value?: string | number | readonly string[]
|
|
85
|
+
readonly onChange?: ChangeEventHandler<E>
|
|
75
86
|
readonly 'aria-describedby'?: string
|
|
76
87
|
readonly 'aria-invalid'?: boolean | 'true' | 'false' | 'grammar' | 'spelling'
|
|
77
88
|
}
|
|
78
89
|
|
|
79
90
|
/** The attributes a control takes from its `Field`; what the author passed explicitly wins. */
|
|
80
|
-
export function useFieldAttributes
|
|
91
|
+
export function useFieldAttributes<E extends HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>(
|
|
92
|
+
own: ControlAttributes<E>,
|
|
93
|
+
): ControlAttributes<E> {
|
|
81
94
|
const field = useFieldControl()
|
|
82
95
|
if (field === undefined) return own
|
|
83
96
|
const describedBy = [own['aria-describedby'], field.describedBy].filter((value) => value !== undefined).join(' ') || undefined
|
|
97
|
+
const bind = own.value === undefined ? field.bind : undefined
|
|
84
98
|
return {
|
|
85
99
|
id: own.id ?? field.id,
|
|
86
100
|
name: own.name ?? field.name,
|
|
87
101
|
required: own.required ?? (field.required || undefined),
|
|
88
102
|
'aria-describedby': describedBy,
|
|
89
103
|
'aria-invalid': own['aria-invalid'] ?? (field.invalid || undefined),
|
|
104
|
+
...(bind === undefined ? {} : {
|
|
105
|
+
value: bind.value,
|
|
106
|
+
onChange: (event) => {
|
|
107
|
+
bind.onChange(event.currentTarget.value)
|
|
108
|
+
own.onChange?.(event)
|
|
109
|
+
},
|
|
110
|
+
}),
|
|
90
111
|
}
|
|
91
112
|
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { type ReactNode, useEffect, useLayoutEffect, useRef, useState } from 'react'
|
|
2
|
+
import { Button } from './Button'
|
|
3
|
+
import { Dialog } from './Dialog'
|
|
4
|
+
import { Form, FormActions, type FormErrorLike } from './Form'
|
|
5
|
+
import type { FormState } from './use-form'
|
|
6
|
+
|
|
7
|
+
export interface FormDialogProps<Input, Output> {
|
|
8
|
+
readonly open: boolean
|
|
9
|
+
readonly title: ReactNode
|
|
10
|
+
readonly description?: ReactNode
|
|
11
|
+
readonly form: FormState<Input, Output>
|
|
12
|
+
/**
|
|
13
|
+
* Runs with the schema's output once the values pass it; the dialog is pending until it settles, so return the
|
|
14
|
+
* mutation's promise: a refused field takes the focus only if `error` holds it by then. It answers a refusal through
|
|
15
|
+
* `error` and does not throw: a rejection is the page's unhandled error.
|
|
16
|
+
*/
|
|
17
|
+
readonly onSubmit: (value: Output) => Promise<unknown> | void
|
|
18
|
+
readonly onClose: () => void
|
|
19
|
+
/** The server's refusal: its message in the summary, its `fields` under the fields of those names. */
|
|
20
|
+
readonly error?: FormErrorLike | null
|
|
21
|
+
readonly submitLabel?: string
|
|
22
|
+
readonly cancelLabel?: string
|
|
23
|
+
readonly closeLabel?: string
|
|
24
|
+
readonly fieldsSummary?: string
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The schema's refusal as the summary shows it: an issue of no field in its words, field issues as the summary line. */
|
|
28
|
+
function schemaError(errors: Readonly<Record<string, string>>): FormErrorLike | null {
|
|
29
|
+
const own = errors['']
|
|
30
|
+
if (own !== undefined) return { message: own }
|
|
31
|
+
return Object.keys(errors).length === 0 ? null : { message: '', fields: errors }
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* A dialog around one form: the fields, then Cancel and the submit button. Submitting checks the values with the
|
|
36
|
+
* form's schema and runs `onSubmit` only when they pass; a refused field, the schema's or the server's, takes the
|
|
37
|
+
* focus. The dialog cannot be dismissed while `onSubmit` runs, and the values start over each time it opens.
|
|
38
|
+
*/
|
|
39
|
+
export function FormDialog<Input, Output>({
|
|
40
|
+
open,
|
|
41
|
+
title,
|
|
42
|
+
description,
|
|
43
|
+
form,
|
|
44
|
+
onSubmit,
|
|
45
|
+
onClose,
|
|
46
|
+
error = null,
|
|
47
|
+
submitLabel = 'Save',
|
|
48
|
+
cancelLabel = 'Cancel',
|
|
49
|
+
closeLabel,
|
|
50
|
+
fieldsSummary,
|
|
51
|
+
children,
|
|
52
|
+
}: FormDialogProps<Input, Output> & { readonly children: ReactNode }) {
|
|
53
|
+
const [pending, setPending] = useState(false)
|
|
54
|
+
// Grows once per submit that ended: the first refused field takes the focus then, never on a later render.
|
|
55
|
+
const [submits, setSubmits] = useState(0)
|
|
56
|
+
const element = useRef<HTMLFormElement | null>(null)
|
|
57
|
+
const { reset } = form
|
|
58
|
+
|
|
59
|
+
// Before paint, so a reopened dialog never shows the values it was closed with.
|
|
60
|
+
useLayoutEffect(() => {
|
|
61
|
+
if (open) reset()
|
|
62
|
+
}, [open, reset])
|
|
63
|
+
|
|
64
|
+
useEffect(() => {
|
|
65
|
+
if (submits === 0) return
|
|
66
|
+
const invalid = element.current?.querySelector('[aria-invalid="true"]')
|
|
67
|
+
if (invalid instanceof HTMLElement) invalid.focus()
|
|
68
|
+
}, [submits])
|
|
69
|
+
|
|
70
|
+
const close = () => {
|
|
71
|
+
if (!pending) onClose()
|
|
72
|
+
}
|
|
73
|
+
const submit = async (formElement: HTMLFormElement) => {
|
|
74
|
+
if (pending) return
|
|
75
|
+
element.current = formElement
|
|
76
|
+
setPending(true)
|
|
77
|
+
try {
|
|
78
|
+
const checked = await form.check()
|
|
79
|
+
if (checked.ok) await onSubmit(checked.value)
|
|
80
|
+
} finally {
|
|
81
|
+
setPending(false)
|
|
82
|
+
setSubmits((count) => count + 1)
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
const formError = error ?? schemaError(form.errors)
|
|
86
|
+
|
|
87
|
+
return (
|
|
88
|
+
<Dialog open={open} title={title} description={description} onClose={close} closeLabel={closeLabel}>
|
|
89
|
+
<Form
|
|
90
|
+
onSubmit={(_, formElement) => void submit(formElement)}
|
|
91
|
+
error={formError}
|
|
92
|
+
fieldsSummary={fieldsSummary}
|
|
93
|
+
aria-label={typeof title === 'string' ? title : undefined}
|
|
94
|
+
>
|
|
95
|
+
{children}
|
|
96
|
+
<FormActions>
|
|
97
|
+
<Button variant="ghost" onClick={close} disabled={pending}>
|
|
98
|
+
{cancelLabel}
|
|
99
|
+
</Button>
|
|
100
|
+
<Button type="submit" variant="primary" loading={pending}>
|
|
101
|
+
{submitLabel}
|
|
102
|
+
</Button>
|
|
103
|
+
</FormActions>
|
|
104
|
+
</Form>
|
|
105
|
+
</Dialog>
|
|
106
|
+
)
|
|
107
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -14,10 +14,11 @@ export {
|
|
|
14
14
|
useSelection,
|
|
15
15
|
} from './DataTable'
|
|
16
16
|
export { ConfirmDialog, type ConfirmDialogProps, Dialog, type DialogProps } from './Dialog'
|
|
17
|
-
export { Field, type FieldControl, type FieldProps, useFieldControl } from './Field'
|
|
17
|
+
export { Field, type FieldBinding, type FieldControl, type FieldProps, useFieldControl } from './Field'
|
|
18
18
|
export { FieldList, type FieldListItem, type FieldListProps } from './FieldList'
|
|
19
19
|
export { FilterBar, type FilterBarProps } from './FilterBar'
|
|
20
20
|
export { Form, FormActions, type FormActionsProps, type FormErrorLike, type FormProps } from './Form'
|
|
21
|
+
export { FormDialog, type FormDialogProps } from './FormDialog'
|
|
21
22
|
export {
|
|
22
23
|
Checkbox,
|
|
23
24
|
type CheckboxProps,
|
|
@@ -67,3 +68,13 @@ export { type TabItem, Tabs, type TabsProps } from './Tabs'
|
|
|
67
68
|
export { Timeline, type TimelineItem, type TimelineProps } from './Timeline'
|
|
68
69
|
export { type ToastApi, type ToastOptions, ToastProvider, type ToastProviderProps, type ToastTone, useToast } from './Toast'
|
|
69
70
|
export type { Tone } from './tone'
|
|
71
|
+
export {
|
|
72
|
+
type FormCheck,
|
|
73
|
+
type FormFieldProps,
|
|
74
|
+
type FormState,
|
|
75
|
+
type StandardIssue,
|
|
76
|
+
type StandardResult,
|
|
77
|
+
type StandardSchema,
|
|
78
|
+
type TextField,
|
|
79
|
+
useForm,
|
|
80
|
+
} from './use-form'
|
package/src/use-form.ts
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { useCallback, useRef, useState } from 'react'
|
|
2
|
+
import type { FieldBinding } from './Field'
|
|
3
|
+
|
|
4
|
+
/** One problem a schema found, as Standard Schema (standardschema.dev) reports it. */
|
|
5
|
+
export interface StandardIssue {
|
|
6
|
+
readonly message: string
|
|
7
|
+
readonly path?: readonly (PropertyKey | { readonly key: PropertyKey })[] | undefined
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export type StandardResult<Output> = { readonly value: Output; readonly issues?: undefined } | { readonly issues: readonly StandardIssue[] }
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The part of a Standard Schema the form reads. A zod schema is one, so the kit validates with it without depending on
|
|
14
|
+
* zod.
|
|
15
|
+
*/
|
|
16
|
+
export interface StandardSchema<Input, Output> {
|
|
17
|
+
readonly '~standard': {
|
|
18
|
+
readonly validate: (value: unknown) => StandardResult<Output> | Promise<StandardResult<Output>>
|
|
19
|
+
readonly types?: { readonly input: Input; readonly output: Output } | undefined
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** The fields of `V` that hold text, which a `Field` binds to an input, a select or a textarea. */
|
|
24
|
+
export type TextField<V> = { [K in keyof V]-?: V[K] extends string ? K : never }[keyof V] & string
|
|
25
|
+
|
|
26
|
+
/** What `form.field(name)` spreads onto a `Field`: its name, its error and the binding of its control. */
|
|
27
|
+
export interface FormFieldProps {
|
|
28
|
+
readonly name: string
|
|
29
|
+
readonly error: string | undefined
|
|
30
|
+
readonly bind: FieldBinding
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export type FormCheck<Output> = { readonly ok: true; readonly value: Output } | { readonly ok: false }
|
|
34
|
+
|
|
35
|
+
export interface FormState<Input, Output> {
|
|
36
|
+
/** The values the fields show, of the schema's input type. */
|
|
37
|
+
readonly values: Input
|
|
38
|
+
/** The first message for each refused path (`title`, `lines.0.amount`); `''` holds what concerns no field. */
|
|
39
|
+
readonly errors: Readonly<Record<string, string>>
|
|
40
|
+
set<K extends keyof Input>(name: K, value: Input[K]): void
|
|
41
|
+
field(name: TextField<Input>): FormFieldProps
|
|
42
|
+
/** Validates the values with the schema: the output, or `{ ok: false }` with `errors` shown. */
|
|
43
|
+
check(): Promise<FormCheck<Output>>
|
|
44
|
+
/** Back to the latest initial values, with no errors. */
|
|
45
|
+
reset(): void
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The first message per dotted path; an issue without a path is the form's own, under `''`. */
|
|
49
|
+
function errorsOf(issues: readonly StandardIssue[]): Readonly<Record<string, string>> {
|
|
50
|
+
const errors: Record<string, string> = {}
|
|
51
|
+
for (const issue of issues) {
|
|
52
|
+
const path = (issue.path ?? []).map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')
|
|
53
|
+
errors[path] ??= issue.message
|
|
54
|
+
}
|
|
55
|
+
return errors
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const NO_ERRORS: Readonly<Record<string, string>> = Object.freeze({})
|
|
59
|
+
|
|
60
|
+
function isPlainObject(value: unknown): value is object {
|
|
61
|
+
if (typeof value !== 'object' || value === null) return false
|
|
62
|
+
const prototype: unknown = Object.getPrototypeOf(value)
|
|
63
|
+
return prototype === Object.prototype || prototype === null
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Whether two values hold the same data: an array, a plain object and a `Date` by content, anything else by identity. */
|
|
67
|
+
function sameValue(left: unknown, right: unknown): boolean {
|
|
68
|
+
if (Object.is(left, right)) return true
|
|
69
|
+
if (left instanceof Date && right instanceof Date) return Object.is(left.getTime(), right.getTime())
|
|
70
|
+
if (Array.isArray(left) && Array.isArray(right)) {
|
|
71
|
+
return left.length === right.length && left.every((item, index) => sameValue(item, right[index]))
|
|
72
|
+
}
|
|
73
|
+
if (!isPlainObject(left) || !isPlainObject(right)) return false
|
|
74
|
+
const keys = Object.keys(left)
|
|
75
|
+
return keys.length === Object.keys(right).length
|
|
76
|
+
&& keys.every((key) => Object.hasOwn(right, key) && sameValue(Reflect.get(left, key), Reflect.get(right, key)))
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The state of a form over a schema: the values its fields show, starting at `initial`, and the schema's messages by
|
|
81
|
+
* field. A field binds through `<Field label="Title" {...form.field('title')}>`. Errors appear after the first check
|
|
82
|
+
* and then follow every change, so a fixed field clears at once. When `initial` holds other values (the record was
|
|
83
|
+
* saved or changed meanwhile), the form starts over from them. Arrays, plain objects and `Date`s compare by content; any
|
|
84
|
+
* other value in `initial` (a `Map`, a function) must keep its identity across renders, or every render starts over.
|
|
85
|
+
*/
|
|
86
|
+
export function useForm<Input extends object, Output>(schema: StandardSchema<Input, Output>, initial: NoInfer<Input>): FormState<Input, Output> {
|
|
87
|
+
const [values, setValues] = useState(initial)
|
|
88
|
+
const [errors, setErrors] = useState(NO_ERRORS)
|
|
89
|
+
const [seed, setSeed] = useState(initial)
|
|
90
|
+
const latest = useRef(values)
|
|
91
|
+
const latestInitial = useRef(initial)
|
|
92
|
+
latestInitial.current = initial
|
|
93
|
+
const checked = useRef(false)
|
|
94
|
+
// Only the newest validation sets the errors: an older asynchronous one may settle after it.
|
|
95
|
+
const sequence = useRef(0)
|
|
96
|
+
|
|
97
|
+
const validate = useCallback(async (next: Input): Promise<StandardResult<Output>> => {
|
|
98
|
+
const call = ++sequence.current
|
|
99
|
+
const result = await schema['~standard'].validate(next)
|
|
100
|
+
if (call === sequence.current) setErrors(result.issues === undefined ? NO_ERRORS : errorsOf(result.issues))
|
|
101
|
+
return result
|
|
102
|
+
}, [schema])
|
|
103
|
+
|
|
104
|
+
const startOver = useCallback((from: Input) => {
|
|
105
|
+
sequence.current++
|
|
106
|
+
checked.current = false
|
|
107
|
+
latest.current = from
|
|
108
|
+
setValues(from)
|
|
109
|
+
setErrors(NO_ERRORS)
|
|
110
|
+
}, [])
|
|
111
|
+
|
|
112
|
+
// `initial` is usually built on every render: only other data, not a new object, starts the form over.
|
|
113
|
+
if (!sameValue(seed, initial)) {
|
|
114
|
+
setSeed(initial)
|
|
115
|
+
startOver(initial)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// A bound control writes text; the schema judges it, so a literal union field is checked there, not here.
|
|
119
|
+
const write = useCallback((name: PropertyKey, value: unknown) => {
|
|
120
|
+
const next: Input = { ...latest.current, [name]: value }
|
|
121
|
+
latest.current = next
|
|
122
|
+
setValues(next)
|
|
123
|
+
if (checked.current) void validate(next)
|
|
124
|
+
}, [validate])
|
|
125
|
+
const set = useCallback(<K extends keyof Input>(name: K, value: Input[K]) => write(name, value), [write])
|
|
126
|
+
|
|
127
|
+
const check = useCallback(async (): Promise<FormCheck<Output>> => {
|
|
128
|
+
checked.current = true
|
|
129
|
+
const result = await validate(latest.current)
|
|
130
|
+
return result.issues === undefined ? { ok: true, value: result.value } : { ok: false }
|
|
131
|
+
}, [validate])
|
|
132
|
+
|
|
133
|
+
const reset = useCallback(() => startOver(latestInitial.current), [startOver])
|
|
134
|
+
|
|
135
|
+
const field = (name: TextField<Input>): FormFieldProps => {
|
|
136
|
+
const value = values[name]
|
|
137
|
+
return {
|
|
138
|
+
name,
|
|
139
|
+
error: Object.hasOwn(errors, name) ? errors[name] : undefined,
|
|
140
|
+
bind: { value: typeof value === 'string' ? value : '', onChange: (next) => write(name, next) },
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return { values, errors, set, field, check, reset }
|
|
145
|
+
}
|
package/types/src/Field.d.ts
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
|
-
import { type ReactNode } from 'react';
|
|
1
|
+
import { type ChangeEventHandler, type ReactNode } from 'react';
|
|
2
|
+
/** A text value the control inside a `Field` shows and changes, such as one `useForm` holds. */
|
|
3
|
+
export interface FieldBinding {
|
|
4
|
+
readonly value: string;
|
|
5
|
+
readonly onChange: (value: string) => void;
|
|
6
|
+
}
|
|
2
7
|
/** What a `Field` hands the one control inside it. */
|
|
3
8
|
export interface FieldControl {
|
|
4
9
|
readonly id: string;
|
|
@@ -6,6 +11,7 @@ export interface FieldControl {
|
|
|
6
11
|
readonly describedBy: string | undefined;
|
|
7
12
|
readonly invalid: boolean;
|
|
8
13
|
readonly required: boolean;
|
|
14
|
+
readonly bind: FieldBinding | undefined;
|
|
9
15
|
}
|
|
10
16
|
export declare function useFieldControl(): FieldControl | undefined;
|
|
11
17
|
export interface FieldProps {
|
|
@@ -14,17 +20,21 @@ export interface FieldProps {
|
|
|
14
20
|
readonly hint?: ReactNode;
|
|
15
21
|
readonly error?: string;
|
|
16
22
|
readonly required?: boolean;
|
|
23
|
+
/** Binds the control's value: it shows `bind.value` and reports each change to `bind.onChange`. */
|
|
24
|
+
readonly bind?: FieldBinding;
|
|
17
25
|
readonly children: ReactNode;
|
|
18
26
|
readonly className?: string;
|
|
19
27
|
}
|
|
20
|
-
export declare function Field({ label, name, hint, error, required, children, className }: FieldProps): import("react").JSX.Element;
|
|
21
|
-
interface ControlAttributes {
|
|
28
|
+
export declare function Field({ label, name, hint, error, required, bind, children, className }: FieldProps): import("react").JSX.Element;
|
|
29
|
+
interface ControlAttributes<E extends HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement> {
|
|
22
30
|
readonly id?: string;
|
|
23
31
|
readonly name?: string;
|
|
24
32
|
readonly required?: boolean;
|
|
33
|
+
readonly value?: string | number | readonly string[];
|
|
34
|
+
readonly onChange?: ChangeEventHandler<E>;
|
|
25
35
|
readonly 'aria-describedby'?: string;
|
|
26
36
|
readonly 'aria-invalid'?: boolean | 'true' | 'false' | 'grammar' | 'spelling';
|
|
27
37
|
}
|
|
28
38
|
/** The attributes a control takes from its `Field`; what the author passed explicitly wins. */
|
|
29
|
-
export declare function useFieldAttributes(own: ControlAttributes): ControlAttributes
|
|
39
|
+
export declare function useFieldAttributes<E extends HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>(own: ControlAttributes<E>): ControlAttributes<E>;
|
|
30
40
|
export {};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { type ReactNode } from 'react';
|
|
2
|
+
import { type FormErrorLike } from './Form';
|
|
3
|
+
import type { FormState } from './use-form';
|
|
4
|
+
export interface FormDialogProps<Input, Output> {
|
|
5
|
+
readonly open: boolean;
|
|
6
|
+
readonly title: ReactNode;
|
|
7
|
+
readonly description?: ReactNode;
|
|
8
|
+
readonly form: FormState<Input, Output>;
|
|
9
|
+
/**
|
|
10
|
+
* Runs with the schema's output once the values pass it; the dialog is pending until it settles, so return the
|
|
11
|
+
* mutation's promise: a refused field takes the focus only if `error` holds it by then. It answers a refusal through
|
|
12
|
+
* `error` and does not throw: a rejection is the page's unhandled error.
|
|
13
|
+
*/
|
|
14
|
+
readonly onSubmit: (value: Output) => Promise<unknown> | void;
|
|
15
|
+
readonly onClose: () => void;
|
|
16
|
+
/** The server's refusal: its message in the summary, its `fields` under the fields of those names. */
|
|
17
|
+
readonly error?: FormErrorLike | null;
|
|
18
|
+
readonly submitLabel?: string;
|
|
19
|
+
readonly cancelLabel?: string;
|
|
20
|
+
readonly closeLabel?: string;
|
|
21
|
+
readonly fieldsSummary?: string;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* A dialog around one form: the fields, then Cancel and the submit button. Submitting checks the values with the
|
|
25
|
+
* form's schema and runs `onSubmit` only when they pass; a refused field, the schema's or the server's, takes the
|
|
26
|
+
* focus. The dialog cannot be dismissed while `onSubmit` runs, and the values start over each time it opens.
|
|
27
|
+
*/
|
|
28
|
+
export declare function FormDialog<Input, Output>({ open, title, description, form, onSubmit, onClose, error, submitLabel, cancelLabel, closeLabel, fieldsSummary, children, }: FormDialogProps<Input, Output> & {
|
|
29
|
+
readonly children: ReactNode;
|
|
30
|
+
}): import("react").JSX.Element;
|
package/types/src/index.d.ts
CHANGED
|
@@ -4,10 +4,11 @@ export { Card, type CardProps, Section, type SectionProps } from './Card';
|
|
|
4
4
|
export { Columns, type ColumnsProps, SidePanel, type SidePanelProps } from './Columns';
|
|
5
5
|
export { type Column, type ColumnWidth, DataTable, type DataTableProps, type LoadMore, type Selection, type TableSelection, type TableStatus, useSelection, } from './DataTable';
|
|
6
6
|
export { ConfirmDialog, type ConfirmDialogProps, Dialog, type DialogProps } from './Dialog';
|
|
7
|
-
export { Field, type FieldControl, type FieldProps, useFieldControl } from './Field';
|
|
7
|
+
export { Field, type FieldBinding, type FieldControl, type FieldProps, useFieldControl } from './Field';
|
|
8
8
|
export { FieldList, type FieldListItem, type FieldListProps } from './FieldList';
|
|
9
9
|
export { FilterBar, type FilterBarProps } from './FilterBar';
|
|
10
10
|
export { Form, FormActions, type FormActionsProps, type FormErrorLike, type FormProps } from './Form';
|
|
11
|
+
export { FormDialog, type FormDialogProps } from './FormDialog';
|
|
11
12
|
export { Checkbox, type CheckboxProps, DateInput, type DateInputProps, DateRange, type DateRangeProps, type DateRangeValue, Input, type InputProps, RadioGroup, type RadioGroupProps, Select, type SelectOption, type SelectProps, Textarea, type TextareaProps, } from './inputs';
|
|
12
13
|
export { type Gap, Inline, type InlineProps, Stack, type StackProps } from './layout';
|
|
13
14
|
export { PageHeader, type PageHeaderProps } from './PageHeader';
|
|
@@ -18,3 +19,4 @@ export { type TabItem, Tabs, type TabsProps } from './Tabs';
|
|
|
18
19
|
export { Timeline, type TimelineItem, type TimelineProps } from './Timeline';
|
|
19
20
|
export { type ToastApi, type ToastOptions, ToastProvider, type ToastProviderProps, type ToastTone, useToast } from './Toast';
|
|
20
21
|
export type { Tone } from './tone';
|
|
22
|
+
export { type FormCheck, type FormFieldProps, type FormState, type StandardIssue, type StandardResult, type StandardSchema, type TextField, useForm, } from './use-form';
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { FieldBinding } from './Field';
|
|
2
|
+
/** One problem a schema found, as Standard Schema (standardschema.dev) reports it. */
|
|
3
|
+
export interface StandardIssue {
|
|
4
|
+
readonly message: string;
|
|
5
|
+
readonly path?: readonly (PropertyKey | {
|
|
6
|
+
readonly key: PropertyKey;
|
|
7
|
+
})[] | undefined;
|
|
8
|
+
}
|
|
9
|
+
export type StandardResult<Output> = {
|
|
10
|
+
readonly value: Output;
|
|
11
|
+
readonly issues?: undefined;
|
|
12
|
+
} | {
|
|
13
|
+
readonly issues: readonly StandardIssue[];
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* The part of a Standard Schema the form reads. A zod schema is one, so the kit validates with it without depending on
|
|
17
|
+
* zod.
|
|
18
|
+
*/
|
|
19
|
+
export interface StandardSchema<Input, Output> {
|
|
20
|
+
readonly '~standard': {
|
|
21
|
+
readonly validate: (value: unknown) => StandardResult<Output> | Promise<StandardResult<Output>>;
|
|
22
|
+
readonly types?: {
|
|
23
|
+
readonly input: Input;
|
|
24
|
+
readonly output: Output;
|
|
25
|
+
} | undefined;
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
/** The fields of `V` that hold text, which a `Field` binds to an input, a select or a textarea. */
|
|
29
|
+
export type TextField<V> = {
|
|
30
|
+
[K in keyof V]-?: V[K] extends string ? K : never;
|
|
31
|
+
}[keyof V] & string;
|
|
32
|
+
/** What `form.field(name)` spreads onto a `Field`: its name, its error and the binding of its control. */
|
|
33
|
+
export interface FormFieldProps {
|
|
34
|
+
readonly name: string;
|
|
35
|
+
readonly error: string | undefined;
|
|
36
|
+
readonly bind: FieldBinding;
|
|
37
|
+
}
|
|
38
|
+
export type FormCheck<Output> = {
|
|
39
|
+
readonly ok: true;
|
|
40
|
+
readonly value: Output;
|
|
41
|
+
} | {
|
|
42
|
+
readonly ok: false;
|
|
43
|
+
};
|
|
44
|
+
export interface FormState<Input, Output> {
|
|
45
|
+
/** The values the fields show, of the schema's input type. */
|
|
46
|
+
readonly values: Input;
|
|
47
|
+
/** The first message for each refused path (`title`, `lines.0.amount`); `''` holds what concerns no field. */
|
|
48
|
+
readonly errors: Readonly<Record<string, string>>;
|
|
49
|
+
set<K extends keyof Input>(name: K, value: Input[K]): void;
|
|
50
|
+
field(name: TextField<Input>): FormFieldProps;
|
|
51
|
+
/** Validates the values with the schema: the output, or `{ ok: false }` with `errors` shown. */
|
|
52
|
+
check(): Promise<FormCheck<Output>>;
|
|
53
|
+
/** Back to the latest initial values, with no errors. */
|
|
54
|
+
reset(): void;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* The state of a form over a schema: the values its fields show, starting at `initial`, and the schema's messages by
|
|
58
|
+
* field. A field binds through `<Field label="Title" {...form.field('title')}>`. Errors appear after the first check
|
|
59
|
+
* and then follow every change, so a fixed field clears at once. When `initial` holds other values (the record was
|
|
60
|
+
* saved or changed meanwhile), the form starts over from them. Arrays, plain objects and `Date`s compare by content; any
|
|
61
|
+
* other value in `initial` (a `Map`, a function) must keep its identity across renders, or every render starts over.
|
|
62
|
+
*/
|
|
63
|
+
export declare function useForm<Input extends object, Output>(schema: StandardSchema<Input, Output>, initial: NoInfer<Input>): FormState<Input, Output>;
|