@fabrika/ui 0.9.0-dev.5 → 0.9.0-dev.51

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 CHANGED
@@ -21,5 +21,8 @@ const { Router, useRoute, href } = createRouter({
21
21
  - `styles.css` — the theme tokens plus every component rule; the one file to import.
22
22
  - `theme.css` — the tokens alone (`--fui-*`), light on `:root`, dark on `:root[data-theme='dark']`.
23
23
  - Every plain `<a href>` inside `<Router>` navigates in-app; add `data-router="native"` to opt a link out.
24
+ - A list keeps its filters in the URL: `href`, `navigate` and `<Link>` take `query` (`{ stage: 'won', owner: ['a', 'b'] }`),
25
+ and `useSearchParams()` reads it. A navigation that changes only the query keeps the scroll position and the focus
26
+ (a page link that should start at the top changes the path, or scrolls itself).
24
27
  - `@fabrika/ui/challenge`: `<Challenge url={challengeUrl(api.visitors.register)} onToken={…} />`, the ALTCHA widget of
25
28
  a public procedure's challenge. It needs the optional peer `altcha`, and fills the form's `challengeToken` field.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/ui",
3
- "version": "0.9.0-dev.5",
3
+ "version": "0.9.0-dev.51",
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/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
+ }
@@ -827,6 +827,13 @@
827
827
  .fui-table__cell--wrap {
828
828
  white-space: normal;
829
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);
830
837
  }
831
838
 
832
839
  .fui-table__cell--width-xs {
@@ -849,6 +856,27 @@
849
856
  width: var(--fui-column-width-xl);
850
857
  }
851
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
+
852
880
  .fui-table__select {
853
881
  width: 1px;
854
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,
@@ -41,10 +42,12 @@ export { PageHeader, type PageHeaderProps } from './PageHeader'
41
42
  export {
42
43
  type CreatedRouter,
43
44
  createRouter,
45
+ type HrefOptions,
44
46
  type LinkProps,
45
47
  type NavigateOptions,
46
48
  type ParamsArgs,
47
49
  type ParamsOf,
50
+ type QueryInit,
48
51
  type RouteMatch,
49
52
  type RouterOptions,
50
53
  type RouterProps,
@@ -67,3 +70,13 @@ export { type TabItem, Tabs, type TabsProps } from './Tabs'
67
70
  export { Timeline, type TimelineItem, type TimelineProps } from './Timeline'
68
71
  export { type ToastApi, type ToastOptions, ToastProvider, type ToastProviderProps, type ToastTone, useToast } from './Toast'
69
72
  export type { Tone } from './tone'
73
+ export {
74
+ type FormCheck,
75
+ type FormFieldProps,
76
+ type FormState,
77
+ type StandardIssue,
78
+ type StandardResult,
79
+ type StandardSchema,
80
+ type TextField,
81
+ useForm,
82
+ } from './use-form'
package/src/router.tsx CHANGED
@@ -1,4 +1,4 @@
1
- import { type ComponentProps, type ReactNode, useEffect, useSyncExternalStore } from 'react'
1
+ import { type ComponentProps, type ReactNode, useEffect, useMemo, useSyncExternalStore } from 'react'
2
2
 
3
3
  type ParamNames<P extends string> = P extends `${string}:${infer Name}/${infer Rest}` ? Name | ParamNames<`/${Rest}`>
4
4
  : P extends `${string}:${infer Name}` ? Name
@@ -24,13 +24,20 @@ export interface RouterOptions {
24
24
  readonly base?: string
25
25
  }
26
26
 
27
- export interface NavigateOptions {
27
+ /** A URL query: an `undefined` value leaves its key out, an array repeats the key once per value. */
28
+ export type QueryInit = Readonly<Record<string, string | readonly string[] | undefined>>
29
+
30
+ export interface HrefOptions {
31
+ readonly query?: QueryInit
32
+ }
33
+
34
+ export interface NavigateOptions extends HrefOptions {
28
35
  readonly replace?: boolean
29
36
  }
30
37
 
31
38
  export type LinkProps<R extends RouteTable, Name extends RouteName<R>> =
32
39
  & Readonly<Omit<ComponentProps<'a'>, 'href'>>
33
- & { readonly to: Name }
40
+ & { readonly to: Name; readonly query?: QueryInit }
34
41
  & ([ParamNames<R[Name]>] extends [never] ? { readonly params?: undefined } : { readonly params: ParamsOf<R[Name]> })
35
42
 
36
43
  export interface RouterProps {
@@ -41,7 +48,9 @@ export interface CreatedRouter<R extends RouteTable> {
41
48
  readonly Router: (props: RouterProps) => ReactNode
42
49
  readonly Link: <Name extends RouteName<R>>(props: LinkProps<R, Name>) => ReactNode
43
50
  readonly useRoute: () => RouteMatch<R> | null
44
- readonly href: <Name extends RouteName<R>>(name: Name, ...params: ParamsArgs<R[Name]>) => string
51
+ /** The current URL's query; a new instance when the query changes. Read it, and change it through `navigate`. */
52
+ readonly useSearchParams: () => URLSearchParams
53
+ readonly href: <Name extends RouteName<R>>(name: Name, ...args: [...ParamsArgs<R[Name]>, options?: HrefOptions]) => string
45
54
  readonly navigate: <Name extends RouteName<R>>(name: Name, ...args: [...ParamsArgs<R[Name]>, options?: NavigateOptions]) => void
46
55
  }
47
56
 
@@ -54,7 +63,11 @@ interface CompiledRoute {
54
63
 
55
64
  interface LocationSnapshot {
56
65
  readonly pathname: string
57
- /** Set by a navigation this router made, so the page scrolls to the top and focus moves to its heading. */
66
+ readonly search: string
67
+ /**
68
+ * Set by a navigation this router made to another path, or to the same URL again, so the page scrolls to the top and
69
+ * focus moves to its heading. A navigation that changes only the query (a filter) keeps both.
70
+ */
58
71
  readonly announce: boolean
59
72
  }
60
73
 
@@ -125,6 +138,16 @@ function isNavigateOptions(value: unknown): value is NavigateOptions {
125
138
  return typeof value === 'object' && value !== null
126
139
  }
127
140
 
141
+ function searchOf(query: QueryInit | undefined): string {
142
+ const search = new URLSearchParams()
143
+ for (const [name, value] of Object.entries(query ?? {})) {
144
+ if (value === undefined) continue
145
+ for (const item of typeof value === 'string' ? [value] : value) search.append(name, item)
146
+ }
147
+ const text = search.toString()
148
+ return text === '' ? '' : `?${text}`
149
+ }
150
+
128
151
  /**
129
152
  * A typed History API router over a route table. Every function it answers is typed from `routes`, and `Router` turns
130
153
  * every plain same-origin `<a href>` under `base` into an in-app navigation.
@@ -162,7 +185,7 @@ export function createRouter<const R extends RouteTable>(routes: R, options: Rou
162
185
  return null
163
186
  }
164
187
 
165
- function buildHref(name: string, params: unknown): string {
188
+ function buildHref(name: string, params: unknown, query?: QueryInit): string {
166
189
  const route = byName.get(name)
167
190
  if (route === undefined) throw new Error(`unknown route ${JSON.stringify(name)}`)
168
191
  const values = isStringRecord(params) ? params : {}
@@ -172,7 +195,7 @@ export function createRouter<const R extends RouteTable>(routes: R, options: Rou
172
195
  if (value === undefined) throw new Error(`route ${name}: missing param ${segment.name}`)
173
196
  return encodeURIComponent(value)
174
197
  })
175
- return `${base}/${path.join('/')}`
198
+ return `${base}/${path.join('/')}${searchOf(query)}`
176
199
  }
177
200
 
178
201
  function hasParams(name: string): boolean {
@@ -180,13 +203,13 @@ export function createRouter<const R extends RouteTable>(routes: R, options: Rou
180
203
  }
181
204
 
182
205
  function getSnapshot(): LocationSnapshot {
183
- const pathname = window.location.pathname
184
- if (snapshot === undefined || snapshot.pathname !== pathname) snapshot = { pathname, announce: false }
206
+ const { pathname, search } = window.location
207
+ if (snapshot === undefined || snapshot.pathname !== pathname || snapshot.search !== search) snapshot = { pathname, search, announce: false }
185
208
  return snapshot
186
209
  }
187
210
 
188
211
  function notify(announce: boolean): void {
189
- snapshot = { pathname: window.location.pathname, announce }
212
+ snapshot = { pathname: window.location.pathname, search: window.location.search, announce }
190
213
  for (const listener of listeners) listener()
191
214
  }
192
215
 
@@ -200,10 +223,16 @@ export function createRouter<const R extends RouteTable>(routes: R, options: Rou
200
223
  }
201
224
  }
202
225
 
203
- function go(url: string, replace: boolean): void {
226
+ /**
227
+ * Moves to `url`. A new path scrolls up and focuses the heading; a new query alone keeps both, so a filter does not
228
+ * jump the page. A click on a link to the page already shown (`reclick`) scrolls up too, as a browser would.
229
+ */
230
+ function go(url: string, replace: boolean, reclick: boolean): void {
231
+ const { pathname, search } = window.location
204
232
  if (replace) window.history.replaceState(null, '', url)
205
233
  else window.history.pushState(null, '', url)
206
- notify(true)
234
+ const samePage = window.location.pathname === pathname && window.location.search === search
235
+ notify(window.location.pathname !== pathname || (reclick && samePage))
207
236
  }
208
237
 
209
238
  function useLocation(): LocationSnapshot {
@@ -234,7 +263,7 @@ export function createRouter<const R extends RouteTable>(routes: R, options: Rou
234
263
  const url = interceptedUrl(event)
235
264
  if (url === undefined) return
236
265
  event.preventDefault()
237
- go(`${url.pathname}${url.search}${url.hash}`, false)
266
+ go(`${url.pathname}${url.search}${url.hash}`, false, true)
238
267
  }
239
268
  document.addEventListener('click', onClick)
240
269
  return () => document.removeEventListener('click', onClick)
@@ -252,28 +281,40 @@ export function createRouter<const R extends RouteTable>(routes: R, options: Rou
252
281
  return match(useLocation().pathname)
253
282
  }
254
283
 
255
- function href<Name extends RouteName<R>>(name: Name, ...params: ParamsArgs<R[Name]>): string {
256
- return buildHref(name, params[0])
284
+ function useSearchParams(): URLSearchParams {
285
+ const { search } = useLocation()
286
+ // One instance per query, so an effect that depends on it reruns only when the query changes.
287
+ return useMemo(() => new URLSearchParams(search), [search])
288
+ }
289
+
290
+ /** Splits the rest arguments of `href` and `navigate`: the params when the route has any, then the options. */
291
+ function splitArgs(name: string, args: readonly unknown[]): { readonly params: unknown; readonly options: NavigateOptions } {
292
+ const params = hasParams(name) ? args[0] : undefined
293
+ const options = args[hasParams(name) ? 1 : 0]
294
+ return { params, options: isNavigateOptions(options) ? options : {} }
295
+ }
296
+
297
+ function href<Name extends RouteName<R>>(name: Name, ...args: [...ParamsArgs<R[Name]>, options?: HrefOptions]): string {
298
+ const { params, options } = splitArgs(name, args)
299
+ return buildHref(name, params, options.query)
257
300
  }
258
301
 
259
302
  function navigate<Name extends RouteName<R>>(name: Name, ...args: [...ParamsArgs<R[Name]>, options?: NavigateOptions]): void {
260
- const list: readonly unknown[] = args
261
- const params = hasParams(name) ? list[0] : undefined
262
- const options = list[hasParams(name) ? 1 : 0]
263
- go(buildHref(name, params), isNavigateOptions(options) && options.replace === true)
303
+ const { params, options } = splitArgs(name, args)
304
+ go(buildHref(name, params, options.query), options.replace === true, false)
264
305
  }
265
306
 
266
307
  function Link<Name extends RouteName<R>>(props: LinkProps<R, Name>): ReactNode {
267
- const { to, params, children, ...rest } = props
308
+ const { to, params, query, children, ...rest } = props
268
309
  const location = useLocation()
269
- const target = buildHref(to, params)
270
- const current = splitPath(location.pathname).join('/') === splitPath(target).join('/')
310
+ // Current by path alone: a navigation item stays current whatever query (filters) the page carries.
311
+ const current = splitPath(location.pathname).join('/') === splitPath(buildHref(to, params)).join('/')
271
312
  return (
272
- <a {...rest} href={target} aria-current={current ? 'page' : rest['aria-current']}>
313
+ <a {...rest} href={buildHref(to, params, query)} aria-current={rest['aria-current'] ?? (current ? 'page' : undefined)}>
273
314
  {children}
274
315
  </a>
275
316
  )
276
317
  }
277
318
 
278
- return { Router, Link, useRoute, href, navigate }
319
+ return { Router, Link, useRoute, useSearchParams, href, navigate }
279
320
  }
@@ -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
+ }
@@ -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,17 +4,19 @@ 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';
14
- export { type CreatedRouter, createRouter, type LinkProps, type NavigateOptions, type ParamsArgs, type ParamsOf, type RouteMatch, type RouterOptions, type RouterProps, type RouteTable, } from './router';
15
+ export { type CreatedRouter, createRouter, type HrefOptions, type LinkProps, type NavigateOptions, type ParamsArgs, type ParamsOf, type QueryInit, type RouteMatch, type RouterOptions, type RouterProps, type RouteTable, } from './router';
15
16
  export { CountBadge, type CountBadgeProps, EmptyState, type EmptyStateProps, ErrorState, type ErrorStateProps, LoadingState, type LoadingStateProps, Spinner, type SpinnerProps, } from './states';
16
17
  export { StatusPill, type StatusPillProps } from './StatusPill';
17
18
  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';
@@ -19,11 +19,17 @@ export interface RouterOptions {
19
19
  /** The path the application is mounted under; it is stripped when matching and added by `href`. */
20
20
  readonly base?: string;
21
21
  }
22
- export interface NavigateOptions {
22
+ /** A URL query: an `undefined` value leaves its key out, an array repeats the key once per value. */
23
+ export type QueryInit = Readonly<Record<string, string | readonly string[] | undefined>>;
24
+ export interface HrefOptions {
25
+ readonly query?: QueryInit;
26
+ }
27
+ export interface NavigateOptions extends HrefOptions {
23
28
  readonly replace?: boolean;
24
29
  }
25
30
  export type LinkProps<R extends RouteTable, Name extends RouteName<R>> = Readonly<Omit<ComponentProps<'a'>, 'href'>> & {
26
31
  readonly to: Name;
32
+ readonly query?: QueryInit;
27
33
  } & ([ParamNames<R[Name]>] extends [never] ? {
28
34
  readonly params?: undefined;
29
35
  } : {
@@ -36,7 +42,9 @@ export interface CreatedRouter<R extends RouteTable> {
36
42
  readonly Router: (props: RouterProps) => ReactNode;
37
43
  readonly Link: <Name extends RouteName<R>>(props: LinkProps<R, Name>) => ReactNode;
38
44
  readonly useRoute: () => RouteMatch<R> | null;
39
- readonly href: <Name extends RouteName<R>>(name: Name, ...params: ParamsArgs<R[Name]>) => string;
45
+ /** The current URL's query; a new instance when the query changes. Read it, and change it through `navigate`. */
46
+ readonly useSearchParams: () => URLSearchParams;
47
+ readonly href: <Name extends RouteName<R>>(name: Name, ...args: [...ParamsArgs<R[Name]>, options?: HrefOptions]) => string;
40
48
  readonly navigate: <Name extends RouteName<R>>(name: Name, ...args: [...ParamsArgs<R[Name]>, options?: NavigateOptions]) => void;
41
49
  }
42
50
  /**
@@ -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>;