@fabrika/ui 0.9.0-dev.4 → 0.9.0-dev.40

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/ui",
3
- "version": "0.9.0-dev.4",
3
+ "version": "0.9.0-dev.40",
4
4
  "type": "module",
5
5
  "description": "React component kit for the paved road: accessible admin components styled through CSS custom properties.",
6
6
  "license": "MIT",
@@ -32,7 +32,7 @@
32
32
  "./theme.css": "./src/theme.css"
33
33
  },
34
34
  "scripts": {
35
- "typecheck": "tsc --noEmit",
35
+ "typecheck": "tsrs --build tsconfig.test.json",
36
36
  "test": "bun test --isolate"
37
37
  },
38
38
  "peerDependencies": {
package/src/Challenge.tsx CHANGED
@@ -2,6 +2,10 @@
2
2
  // challenge the application issued, solves its proof of work in workers, and the page sends the payload as the
3
3
  // procedure's `challengeToken`. Nothing is loaded from a third party: the widget is bundled with the page.
4
4
  //
5
+ // To the visitor it is a part of the page, not a third party's badge: the widget's logo and attribution footer are
6
+ // hidden (the library's MIT license asks for neither), and `.fui-challenge` sets its theme variables from the kit's
7
+ // tokens.
8
+ //
5
9
  // The one module of the kit with a runtime dependency, the optional peer `altcha`, which registers `<altcha-widget>`
6
10
  // when this module loads; the kit's root never imports it.
7
11
 
@@ -13,7 +17,7 @@ import { classNames } from './class-names'
13
17
 
14
18
  /**
15
19
  * The texts the widget renders as text, each with the widget's English default. Its footer is not among them: the
16
- * widget renders that one as HTML, so the kit keeps the widget's own.
20
+ * widget renders that one as HTML, and the kit hides it.
17
21
  */
18
22
  export interface ChallengeStrings {
19
23
  readonly label: string
@@ -24,7 +28,8 @@ export interface ChallengeStrings {
24
28
  readonly error: string
25
29
  readonly reload: string
26
30
  readonly waitAlert: string
27
- readonly ariaLinkLabel: string
31
+ /** @deprecated The label of the widget's logo link, which the kit hides; it reaches nothing, so it is not sent. */
32
+ readonly ariaLinkLabel?: string
28
33
  }
29
34
 
30
35
  export interface ChallengeProps {
@@ -46,11 +51,14 @@ export interface ChallengeProps {
46
51
  /** The input a procedure with a challenge reads its token from; `@fabrika/app`'s `CHALLENGE_FIELD`. */
47
52
  const CHALLENGE_FIELD = 'challengeToken'
48
53
 
54
+ /** The widget's configuration: no logo and no footer, both of which name and link the library. */
55
+ const CONFIGURATION = JSON.stringify({ hideLogo: true, hideFooter: true })
56
+
49
57
  /** Each set of strings is registered once with the widget, under a language code of its own. */
50
58
  const registered = new Map<string, string>()
51
59
 
52
- /** The fields of `ChallengeStrings`: only these reach the widget, whatever else an object passed as one carries. */
53
- const TEXT_FIELDS: readonly (keyof ChallengeStrings)[] = [
60
+ /** The fields of `ChallengeStrings` that reach the widget, whatever else an object passed as one carries. */
61
+ const TEXT_FIELDS: readonly Exclude<keyof ChallengeStrings, 'ariaLinkLabel'>[] = [
54
62
  'label',
55
63
  'verifying',
56
64
  'verified',
@@ -59,7 +67,6 @@ const TEXT_FIELDS: readonly (keyof ChallengeStrings)[] = [
59
67
  'error',
60
68
  'reload',
61
69
  'waitAlert',
62
- 'ariaLinkLabel',
63
70
  ]
64
71
 
65
72
  function languageOf(given: Partial<ChallengeStrings> | undefined): string | undefined {
@@ -97,7 +104,7 @@ function tokenOf(event: Event): string | null | undefined {
97
104
  }
98
105
 
99
106
  /**
100
- * The ALTCHA widget for one procedure's challenge. A challenge passes once: after a refused submission, give the
107
+ * The proof-of-work widget for one procedure's challenge. A challenge passes once: after a refused submission, give the
101
108
  * component a new `key` so the visitor solves a fresh one.
102
109
  */
103
110
  export function Challenge({ url, onToken, name = CHALLENGE_FIELD, auto = 'off', strings, className }: ChallengeProps) {
@@ -121,6 +128,7 @@ export function Challenge({ url, onToken, name = CHALLENGE_FIELD, auto = 'off',
121
128
  ref={host}
122
129
  className={classNames('fui-challenge', className)}
123
130
  challenge={url}
131
+ configuration={CONFIGURATION}
124
132
  name={name}
125
133
  auto={auto}
126
134
  language={languageOf(strings)}
package/src/DataTable.tsx CHANGED
@@ -12,7 +12,7 @@ export interface Column<Row> {
12
12
  readonly grow?: boolean
13
13
  /** A width of the column scale (`--fui-column-width-<size>`), on its head and its cells. */
14
14
  readonly width?: ColumnWidth
15
- /** Its cells wrap their text instead of keeping it on one line. */
15
+ /** Its cells wrap their text, a long token anywhere; the column keeps at least its `width`, else `md` (`lg` with `grow`). */
16
16
  readonly wrap?: boolean
17
17
  }
18
18
 
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(own: ControlAttributes): ControlAttributes {
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
+ }
@@ -520,6 +520,35 @@
520
520
  gap: var(--fui-space-4);
521
521
  }
522
522
 
523
+ /* Challenge: the widget's own theme variables, set from the kit's tokens on its element, which its parts inherit. */
524
+
525
+ .fui-challenge {
526
+ display: block;
527
+ font-family: var(--fui-font-family);
528
+ font-size: var(--fui-text-md);
529
+ --altcha-color-base: var(--fui-surface);
530
+ --altcha-color-base-content: var(--fui-text);
531
+ --altcha-color-neutral: var(--fui-border-strong);
532
+ --altcha-color-neutral-content: var(--fui-text-muted);
533
+ --altcha-color-primary: var(--fui-accent);
534
+ --altcha-color-primary-content: var(--fui-accent-contrast);
535
+ --altcha-color-success: var(--fui-success);
536
+ --altcha-color-success-content: var(--fui-accent-contrast);
537
+ --altcha-color-error: var(--fui-danger);
538
+ --altcha-color-error-content: var(--fui-accent-contrast);
539
+ --altcha-border-color: var(--fui-border);
540
+ --altcha-border-width: var(--fui-border-width);
541
+ --altcha-border-radius: var(--fui-radius-md);
542
+ --altcha-padding: var(--fui-space-3);
543
+ --altcha-checkbox-size: var(--fui-check-size);
544
+ --altcha-checkbox-border-color: var(--fui-border-strong);
545
+ --altcha-checkbox-border-radius: var(--fui-radius-sm);
546
+ --altcha-checkbox-outline: var(--fui-focus-width) solid var(--fui-focus);
547
+ --altcha-input-background-color: var(--fui-surface);
548
+ --altcha-input-border-radius: var(--fui-radius-sm);
549
+ --altcha-spinner-color: var(--fui-text-muted);
550
+ }
551
+
523
552
  /* Button */
524
553
 
525
554
  .fui-button {
@@ -798,6 +827,13 @@
798
827
  .fui-table__cell--wrap {
799
828
  white-space: normal;
800
829
  overflow-wrap: anywhere;
830
+ /* `anywhere` lowers the min-content width to one letter: without a floor, columns that keep their text on one line squeeze it. */
831
+ min-width: var(--fui-column-width-md);
832
+ }
833
+
834
+ /* The growing column carries the table's main text. */
835
+ .fui-table__cell--wrap.fui-table__cell--grow {
836
+ min-width: var(--fui-column-width-lg);
801
837
  }
802
838
 
803
839
  .fui-table__cell--width-xs {
@@ -820,6 +856,27 @@
820
856
  width: var(--fui-column-width-xl);
821
857
  }
822
858
 
859
+ /* A wrapped column's own width replaces its floor. */
860
+ .fui-table__cell--wrap.fui-table__cell--width-xs {
861
+ min-width: var(--fui-column-width-xs);
862
+ }
863
+
864
+ .fui-table__cell--wrap.fui-table__cell--width-sm {
865
+ min-width: var(--fui-column-width-sm);
866
+ }
867
+
868
+ .fui-table__cell--wrap.fui-table__cell--width-md {
869
+ min-width: var(--fui-column-width-md);
870
+ }
871
+
872
+ .fui-table__cell--wrap.fui-table__cell--width-lg {
873
+ min-width: var(--fui-column-width-lg);
874
+ }
875
+
876
+ .fui-table__cell--wrap.fui-table__cell--width-xl {
877
+ min-width: var(--fui-column-width-xl);
878
+ }
879
+
823
880
  .fui-table__select {
824
881
  width: 1px;
825
882
  padding-right: 0;
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'
@@ -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
+ }
@@ -1,7 +1,7 @@
1
1
  import 'altcha';
2
2
  /**
3
3
  * The texts the widget renders as text, each with the widget's English default. Its footer is not among them: the
4
- * widget renders that one as HTML, so the kit keeps the widget's own.
4
+ * widget renders that one as HTML, and the kit hides it.
5
5
  */
6
6
  export interface ChallengeStrings {
7
7
  readonly label: string;
@@ -12,7 +12,8 @@ export interface ChallengeStrings {
12
12
  readonly error: string;
13
13
  readonly reload: string;
14
14
  readonly waitAlert: string;
15
- readonly ariaLinkLabel: string;
15
+ /** @deprecated The label of the widget's logo link, which the kit hides; it reaches nothing, so it is not sent. */
16
+ readonly ariaLinkLabel?: string;
16
17
  }
17
18
  export interface ChallengeProps {
18
19
  /** Where the widget fetches its challenge: `challengeUrl(api.<procedure>)` of `@fabrika/app/client`. */
@@ -30,7 +31,7 @@ export interface ChallengeProps {
30
31
  readonly className?: string;
31
32
  }
32
33
  /**
33
- * The ALTCHA widget for one procedure's challenge. A challenge passes once: after a refused submission, give the
34
+ * The proof-of-work widget for one procedure's challenge. A challenge passes once: after a refused submission, give the
34
35
  * component a new `key` so the visitor solves a fresh one.
35
36
  */
36
37
  export declare function Challenge({ url, onToken, name, auto, strings, className }: ChallengeProps): import("react").JSX.Element;
@@ -8,7 +8,7 @@ export interface Column<Row> {
8
8
  readonly grow?: boolean;
9
9
  /** A width of the column scale (`--fui-column-width-<size>`), on its head and its cells. */
10
10
  readonly width?: ColumnWidth;
11
- /** Its cells wrap their text instead of keeping it on one line. */
11
+ /** Its cells wrap their text, a long token anywhere; the column keeps at least its `width`, else `md` (`lg` with `grow`). */
12
12
  readonly wrap?: boolean;
13
13
  }
14
14
  export type ColumnWidth = 'xs' | 'sm' | 'md' | 'lg' | 'xl';
@@ -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;
@@ -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>;