@tristan2828/ui-foundation 4.84.0 → 4.85.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -18,7 +18,7 @@ than installing this by hand:
18
18
 
19
19
  | Import | What |
20
20
  |---|---|
21
- | `@tristan2828/ui-foundation` | `AppShell`, `DataTable`, `EntityView` (with `EditableValue`, `editInPlace`, printing its notes and `usePrinting`, `KeyStats`, `IconAction`), `EntityForm`, `Markdown` (with `countTasks`, `toggleTaskAt`), `RichTextEditor`, `ErrorState`, `MultiChoice`, `MultiReference`, `ListEditor`, `PasswordInput`, `RouteErrorBoundary`, `FoundationProviders`, `DataEnvironmentBanner`, `LoginRoute`, `RegisterRoute`, `useAuth`, `useTableUrlState`, `useRecordUpdate`, `useDebouncedValue`, `createQueryClient`, `cn`; types `Page`, `AppError`, `QuerySpec`. For timed screens (`docs/foundation/timed-screens.md`): `SessionView`, `useSessionClock`, `useWakeLock`, `useMuted`, `usePrefersReducedMotion`, and the audio cues `unlockAudio`, `chime`, `sequence`, `cancelCues`, `onCuesRecovered`, `cuesInSync`, `keepAudioAlive`, `say`, `hush`, `vibrate`, `canVibrate`. For the page standards (`docs/foundation/design-language.md` "Parts of the page standards"): `ValueList`, `ListHeader`, `Timeline`, `NeedsYou`, `Freshness`, `PartEmpty`. For reminders (`docs/foundation/reminders.md`): `AllowReminders`, `usePushPermission`. For a record opened in a dialog over its list (`docs/foundation/add-an-entity.md`): `RecordDialogRoute`, `RecordLink`, `useOpenRecord`, `useRecordDialog`, `recordDialogState`, and for a new record over it `useNewRecordDialog`. A small form in a dialog: `FormDialog`. From `/ui/dialog`, `DialogContent` takes `size` and `dirty`, and `DiscardChangesDialog` is the "Discard your changes?" prompt |
21
+ | `@tristan2828/ui-foundation` | `AppShell`, `DataTable`, `EntityView` (with `EditableValue`, `editInPlace`, printing its notes and `usePrinting`, `KeyStats`, `IconAction`), `EntityForm`, `Markdown` (with `countTasks`, `toggleTaskAt`), `RichTextEditor`, `ErrorState`, `MultiChoice`, `MultiReference`, `ListEditor`, `PasswordInput`, `RouteErrorBoundary`, `FoundationProviders`, `DataEnvironmentBanner`, `LoginRoute`, `RegisterRoute`, `useAuth`, `useTableUrlState`, `useRecordUpdate`, `useDebouncedValue`, `createQueryClient`, `cn`; types `Page`, `AppError`, `QuerySpec`. For timed screens (`docs/foundation/timed-screens.md`): `SessionView`, `useSessionClock`, `useWakeLock`, `useMuted`, `usePrefersReducedMotion`, and the audio cues `unlockAudio`, `chime`, `sequence`, `cancelCues`, `onCuesRecovered`, `cuesInSync`, `keepAudioAlive`, `say`, `hush`, `vibrate`, `canVibrate`. For the page standards (`docs/foundation/design-language.md` "Parts of the page standards"): `ValueList`, `ListHeader`, `Timeline`, `NeedsYou`, `Freshness`, `PartEmpty`. For reminders (`docs/foundation/reminders.md`): `AllowReminders`, `usePushPermission`. For a record opened in a dialog over its list (`docs/foundation/add-an-entity.md`): `RecordDialogRoute`, `RecordLink`, `useOpenRecord`, `useRecordDialog`, `recordDialogState`, and for a new record over it `useNewRecordDialog`. A small form in a dialog: `FormDialog`. For the form standard (`docs/foundation/add-an-entity.md` "Forms"): `FormSection`, `OptionSelect`, `countFormErrors`, `fieldRows`; from `/ui/field`, `Field` takes `size`, `solo` and `kind`, and `FieldLabel` takes `required`. From `/ui/dialog`, `DialogContent` takes `size` and `dirty`, and `DiscardChangesDialog` is the "Discard your changes?" prompt |
22
22
  | `@tristan2828/ui-foundation/ui/<name>` | shadcn primitives: badge, button, calendar, card, checkbox, combobox, dialog, empty, field, input, input-group, label, popover, select, separator, sheet, sidebar, skeleton, sonner, spinner, switch, table, textarea, tooltip |
23
23
  | `@tristan2828/ui-foundation/gateway` | `safeFetch`, `toAppError`, `networkError` — for an app's `src/api/gateway/` only |
24
24
  | `@tristan2828/ui-foundation/mocks` | MSW: `authHandlers`, `environmentHandlers`, `resetMockAuth`, `getMockCurrentUser`, `MOCK_USER`, `exposeMswForE2E` |
@@ -3,27 +3,28 @@
3
3
  <!-- index: written by `npm run docs:index` in the package from the headings below; never edit it by hand -->
4
4
  ## Index
5
5
 
6
- - [The reference files](#the-reference-files) · lines 42–64
7
- - [Before anything: the entity plan](#before-anything-the-entity-plan) · lines 66–807
8
- - Step 1: Add `<Entity>` to `openapi.yaml` · lines 108–115
9
- - Step 2: `npm run gen:api` · lines 116–117
10
- - Step 3: Add gateway tests in `tests/gateway/<entity>.test.ts`, derived from the spec · lines 118–129
11
- - Step 4: Add MSW handlers in `src/mocks/<entity>.ts` · lines 130–139
12
- - Step 5: Add a gateway module in `src/api/gateway/<entity>.ts` · lines 140–144
13
- - Step 6: Copy the reference files, one for one, not just the two screens · lines 145–694
14
- - Step 7: Register routes · lines 695–710
15
- - Step 8: Add Playwright specs for all three screens · lines 711–789
16
- - Step 9: Register the nav entry and route names · lines 790–804
17
- - Step 10: `npm run verify`. · lines 805–807
18
- - [How a list opens a record](#how-a-list-opens-a-record) · lines 809–1024
19
- - [The record view](#the-record-view) · lines 958–997
20
- - [Dialogs](#dialogs) · lines 999–1024
21
- - [What not to copy](#what-not-to-copy) · lines 1026–1052
22
- - [After a commit, in the backend](#after-a-commit-in-the-backend) · lines 1054–1071
23
- - [Deleting](#deleting) · lines 1073–1102
24
- - [Fields only a script writes](#fields-only-a-script-writes) · lines 1104–1125
25
- - [Searching one part of the app](#searching-one-part-of-the-app) · lines 1127–1136
26
- - [What a chat is told about an entity](#what-a-chat-is-told-about-an-entity) · lines 1139–1178
6
+ - [The reference files](#the-reference-files) · lines 43–65
7
+ - [Before anything: the entity plan](#before-anything-the-entity-plan) · lines 67–809
8
+ - Step 1: Add `<Entity>` to `openapi.yaml` · lines 109–116
9
+ - Step 2: `npm run gen:api` · lines 117–118
10
+ - Step 3: Add gateway tests in `tests/gateway/<entity>.test.ts`, derived from the spec · lines 119–130
11
+ - Step 4: Add MSW handlers in `src/mocks/<entity>.ts` · lines 131–140
12
+ - Step 5: Add a gateway module in `src/api/gateway/<entity>.ts` · lines 141–145
13
+ - Step 6: Copy the reference files, one for one, not just the two screens · lines 146–696
14
+ - Step 7: Register routes · lines 697–712
15
+ - Step 8: Add Playwright specs for all three screens · lines 713–791
16
+ - Step 9: Register the nav entry and route names · lines 792–806
17
+ - Step 10: `npm run verify`. · lines 807–809
18
+ - [How a list opens a record](#how-a-list-opens-a-record) · lines 811–1069
19
+ - [The record view](#the-record-view) · lines 960–999
20
+ - [Forms](#forms) · lines 1001–1042
21
+ - [Dialogs](#dialogs) · lines 1044–1069
22
+ - [What not to copy](#what-not-to-copy) · lines 1071–1097
23
+ - [After a commit, in the backend](#after-a-commit-in-the-backend) · lines 1099–1116
24
+ - [Deleting](#deleting) · lines 1118–1147
25
+ - [Fields only a script writes](#fields-only-a-script-writes) · lines 1149–1170
26
+ - [Searching one part of the app](#searching-one-part-of-the-app) · lines 1172–1181
27
+ - [What a chat is told about an entity](#what-a-chat-is-told-about-an-entity) · lines 1184–1223
27
28
 
28
29
  <!-- /index -->
29
30
 
@@ -403,8 +404,9 @@ is a filled-in example while the Widgets demo is still here).
403
404
  - `src/routes/widgets/widget-form.tsx` →
404
405
  `src/routes/<entity>/<entity>-form.tsx` — thin consumer of the
405
406
  foundation's `<EntityForm>` (its `danger` slot takes an edit-only
406
- delete). Swap the zod schema and fields. Every way out lands on a
407
- view (below).
407
+ delete). Swap the zod schema and fields, each `Field` with its
408
+ `size` and the required ones' `<FieldLabel required>` ("Forms"
409
+ below). Every way out lands on a view (below).
408
410
 
409
411
  **The view** is the read-only page for one record, at `/<entity>/:id`
410
412
  (apart from the plan's quick actions and fields edited in place, if it
@@ -996,6 +998,49 @@ view reaches them all. A record uses the parts it has, in this order:
996
998
  Edit and its form page stay only for a field the view can't edit in
997
999
  place yet; the plan says which, and the gap is raised for the package.
998
1000
 
1001
+ ### Forms
1002
+
1003
+ Every create and edit form is an `EntityForm` (a page) or a `FormDialog`
1004
+ (up to about eight fields, over its list), and every one has the same
1005
+ shape (4.85):
1006
+
1007
+ - **One column, short fields sharing a row.** Give each `Field` its
1008
+ `size` and the form lays the rows out itself, from the order: `s` a
1009
+ number or a short code, `m` a date, a status, a choice of two to four
1010
+ or a rating, `l` a name or a pick of a record, and no `size` (`full`)
1011
+ for long text, a list or anything that needs the row. Consecutive short
1012
+ fields share a row, up to three, as wide as their sizes; a long one
1013
+ takes one short partner (Series and Number). `<Field solo>` keeps a
1014
+ short one alone where a pairing would read wrong. Under 48rem every
1015
+ field takes its own row but two dates or two numbers (a date picker of
1016
+ your own says so with `kind="date"`). Never a hand-made
1017
+ `sm:grid-cols-2` row.
1018
+ - **Order:** required first, the status next, long text last.
1019
+ - **Required:** `<FieldLabel required>` (an asterisk, and `aria-required`
1020
+ on the control it names). Nothing on an optional field: never
1021
+ "(optional)".
1022
+ - **Labels** above the box, sentence case ("My rating"). Help text
1023
+ (`FieldDescription`) only where the label can't say it, one short line.
1024
+ A placeholder only for a format the box needs (`https://`), never an
1025
+ example that looks like a value.
1026
+ - **Messages say what to do**, in the app's voice: "Give it a title",
1027
+ "Enter a full address, starting https://", never "Title is required".
1028
+ - **A status** is an `OptionSelect` with the same `render` (its badge) as
1029
+ its cell and the record: `inPlace.select`'s `{ value, label }` options.
1030
+ - **Cards** (`<FormSection title>`) only on a form of eight fields or
1031
+ more, never in a dialog; a short form is one run of fields. Sub-record
1032
+ editors (`ListEditor`) sit in a card of their own.
1033
+ - **Pass `dirty={formState.isDirty}` and `errors={formState.errors}`.**
1034
+ With `dirty`, leaving (a link, Back, the sidebar, Cancel) asks "Discard
1035
+ your changes?" first and a reload asks the browser; navigating while
1036
+ `isSubmitting` (the save's own move to the record) doesn't. With
1037
+ `errors`, a refused Add moves to the first problem and the bar says
1038
+ "2 to fix". Both come free; the form draws a failed save as a `Notice`
1039
+ with Try again in its bar, which sticks to the window's bottom on a long
1040
+ form.
1041
+ - **The words:** "New book", "Add book" (the word Add on every create
1042
+ form), and the toast after it "Added The Long Walk".
1043
+
999
1044
  ### Dialogs
1000
1045
 
1001
1046
  Every dialog is one of three widths, `DialogContent`'s `size` (4.82):
@@ -17,23 +17,23 @@
17
17
  - [Shapes and sizes](#shapes-and-sizes) · lines 541–562
18
18
  - [Typography](#typography) · lines 564–684
19
19
  - [Written text (notes)](#written-text-notes) · lines 598–684
20
- - [Density](#density) · lines 686–772
21
- - [Rows on this device](#rows-on-this-device) · lines 745–772
22
- - [Widget cards (hub pages)](#widget-cards-hub-pages) · lines 774–888
23
- - [Module cards (a hub's places)](#module-cards-a-hubs-places) · lines 890–967
24
- - [Notices](#notices) · lines 969–997
25
- - [A value over time](#a-value-over-time) · lines 999–1085
26
- - [Several values over time](#several-values-over-time) · lines 1048–1085
27
- - [A list as a board](#a-list-as-a-board) · lines 1087–1138
28
- - [A list as cards](#a-list-as-cards) · lines 1140–1186
29
- - [Key numbers on a record](#key-numbers-on-a-record) · lines 1188–1217
30
- - [Parts of the page standards](#parts-of-the-page-standards) · lines 1219–1262
31
- - [A record's header and empty values](#a-records-header-and-empty-values) · lines 1263–1301
32
- - [A record's tabs, mark and rail](#a-records-tabs-mark-and-rail) · lines 1303–1348
33
- - [Picking at random](#picking-at-random) · lines 1350–1381
34
- - [Filling in what's missing](#filling-in-whats-missing) · lines 1383–1450
35
- - [Values edited in place: the presets' looks](#values-edited-in-place-the-presets-looks) · lines 1452–1477
36
- - [The sidebar and the phone's bar](#the-sidebar-and-the-phones-bar) · lines 1479–1525
20
+ - [Density](#density) · lines 686–779
21
+ - [Rows on this device](#rows-on-this-device) · lines 752–779
22
+ - [Widget cards (hub pages)](#widget-cards-hub-pages) · lines 781–895
23
+ - [Module cards (a hub's places)](#module-cards-a-hubs-places) · lines 897–974
24
+ - [Notices](#notices) · lines 976–1004
25
+ - [A value over time](#a-value-over-time) · lines 1006–1092
26
+ - [Several values over time](#several-values-over-time) · lines 1055–1092
27
+ - [A list as a board](#a-list-as-a-board) · lines 1094–1145
28
+ - [A list as cards](#a-list-as-cards) · lines 1147–1193
29
+ - [Key numbers on a record](#key-numbers-on-a-record) · lines 1195–1224
30
+ - [Parts of the page standards](#parts-of-the-page-standards) · lines 1226–1269
31
+ - [A record's header and empty values](#a-records-header-and-empty-values) · lines 1270–1308
32
+ - [A record's tabs, mark and rail](#a-records-tabs-mark-and-rail) · lines 1310–1355
33
+ - [Picking at random](#picking-at-random) · lines 1357–1388
34
+ - [Filling in what's missing](#filling-in-whats-missing) · lines 1390–1457
35
+ - [Values edited in place: the presets' looks](#values-edited-in-place-the-presets-looks) · lines 1459–1484
36
+ - [The sidebar and the phone's bar](#the-sidebar-and-the-phones-bar) · lines 1486–1532
37
37
 
38
38
  <!-- /index -->
39
39
 
@@ -704,6 +704,13 @@ set, not a `DataTable` prop:
704
704
 
705
705
  - `compact` and `comfortable` change padding only. Text keeps
706
706
  `type-body`, so compact never drops below a readable size.
707
+ - **Forms are compact at every density but `large`** (4.85): inside a
708
+ `FieldGroup` (every `EntityForm`, `FormDialog` and `FormSection`) the
709
+ inputs, selects, combobox boxes and default buttons are 32px, the
710
+ compact table's row, with 14px between fields; under 48rem or on a
711
+ touch screen 40px, for the finger. They read `--control-height`, which
712
+ `FieldGroup` and the forms' bars set from `--spacing`, so `large` grows
713
+ them as it grows everything. Outside a form a control keeps its 36px.
707
714
  - On a hub, `compact` takes a `WidgetCard`'s padding from 16px to 12px,
708
715
  a `WidgetList` row from 36px to 32px (6px around its line) and a
709
716
  `ModuleCard`'s band and body by 4px each. On a phone a compact row is
@@ -1,14 +1,38 @@
1
- import type { FormEvent, ReactNode } from 'react';
1
+ import { type FormEvent, type ReactNode } from 'react';
2
2
  import type { AppError } from '../../api/contracts.js';
3
3
  export type EntityFormProps = {
4
+ /** "New book", "Edit book". */
4
5
  title: string;
5
- onSubmit: (event: FormEvent<HTMLFormElement>) => void;
6
+ /** The form's submit: react-hook-form's `handleSubmit(...)`, or any handler. */
7
+ onSubmit: (event: FormEvent<HTMLFormElement>) => void | Promise<void>;
6
8
  isSubmitting: boolean;
9
+ /** A save that failed: a Notice above the buttons, with Try again. */
7
10
  submitError?: AppError | null;
11
+ /** Try again's action. Defaults to submitting the form again. */
12
+ onRetry?: () => void;
13
+ /** "Add book": the word Add on every create form. */
8
14
  submitLabel: string;
9
15
  onCancel: () => void;
10
16
  /** An edit-only destructive action (e.g. delete), shown opposite Cancel/Submit. */
11
17
  danger?: ReactNode;
18
+ /**
19
+ * Something was typed (react-hook-form's `formState.isDirty`): leaving
20
+ * asks "Discard your changes?" first. Leave it out and nothing is
21
+ * guarded. Needs a data router (createBrowserRouter).
22
+ */
23
+ dirty?: boolean;
24
+ /**
25
+ * The form's errors (react-hook-form's `formState.errors`), counted for
26
+ * the bar's "N to fix". Without it, the fields marked `data-invalid`
27
+ * are counted.
28
+ */
29
+ errors?: object;
30
+ /**
31
+ * The field to move to after a refused submit. Defaults to the first
32
+ * control marked `aria-invalid`, or failing that the first Field marked
33
+ * `data-invalid`.
34
+ */
35
+ firstInvalid?: (form: HTMLFormElement) => HTMLElement | null;
12
36
  children: ReactNode;
13
37
  };
14
- export declare function EntityForm({ title, onSubmit, isSubmitting, submitError, submitLabel, onCancel, danger, children, }: EntityFormProps): import("react").JSX.Element;
38
+ export declare function EntityForm({ title, onSubmit, isSubmitting, submitError, onRetry, submitLabel, onCancel, danger, dirty, errors, firstInvalid, children, }: EntityFormProps): import("react").JSX.Element;
@@ -1,8 +1,129 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { ErrorState } from './error-state.js';
2
+ // Generic create/edit form chrome: title, field layout, a failed save, and
3
+ // the cancel/submit bar. Deliberately thin: each entity screen still owns
4
+ // its own zod schema, its own <Field> markup, and its own react-hook-form
5
+ // wiring; this component does not attempt to generate fields from a
6
+ // schema.
7
+ //
8
+ // The form standard (4.85) is drawn here and in Field:
9
+ //
10
+ // - Fields are a FieldGroup, so short ones share a row (`Field size`),
11
+ // compact (32px controls, 14px between). `FormSection` groups them in
12
+ // cards on a long form.
13
+ // - Add finds the problem: a submit that's refused moves to the first
14
+ // field marked invalid (opening a fold around it) and the bar says how
15
+ // many are left ("2 to fix"), from `errors` or the fields marked
16
+ // `data-invalid`.
17
+ // - A failed save is a destructive Notice in the bar, above the buttons,
18
+ // with Try again; what was typed stays.
19
+ // - The bar sticks to the bottom of the window while the form is taller
20
+ // than it; on a phone, two wide buttons. It sets
21
+ // `--toast-bottom-offset` on <html> to the room it takes, for anything
22
+ // pinned to the bottom of the window to sit above it.
23
+ // - `dirty`: leaving (a link, Back, the sidebar, Cancel) asks "Discard
24
+ // your changes?" first, and the browser asks before a reload. Nothing
25
+ // typed, nothing asked.
26
+ import { useEffect, useLayoutEffect, useRef, useState } from 'react';
3
27
  import { Button } from '../ui/button.js';
28
+ import { DiscardChangesDialog } from '../ui/dialog.js';
4
29
  import { FieldGroup } from '../ui/field.js';
5
30
  import { Spinner } from '../ui/spinner.js';
6
- export function EntityForm({ title, onSubmit, isSubmitting, submitError, submitLabel, onCancel, danger, children, }) {
7
- return (_jsxs("form", { onSubmit: onSubmit, noValidate: true, className: "flex max-w-xl flex-col gap-6", children: [_jsx("h1", { className: "type-page-title text-foreground", children: title }), _jsx(FieldGroup, { children: children }), submitError && (_jsx(ErrorState, { error: submitError, className: "border border-dashed border-destructive/30" })), _jsxs("div", { className: `flex items-center gap-2 ${danger ? 'justify-between' : 'justify-end'}`, children: [danger, _jsxs("div", { className: "flex justify-end gap-2", children: [_jsx(Button, { type: "button", variant: "outline", onClick: onCancel, disabled: isSubmitting, children: "Cancel" }), _jsxs(Button, { type: "submit", disabled: isSubmitting, children: [isSubmitting && _jsx(Spinner, { className: "size-4" }), submitLabel] })] })] })] }));
31
+ import { countFormErrors } from '../../lib/form-errors.js';
32
+ import { FormLeaveGuard } from './form-leave-guard.js';
33
+ import { Notice } from './notice.js';
34
+ const FOCUSABLE = 'input:not([type=hidden]), select, textarea, button, [contenteditable=true], [tabindex]:not([tabindex="-1"])';
35
+ function problemIn(form) {
36
+ return (form.querySelector('[aria-invalid=true]') ??
37
+ form.querySelector('[data-slot=field][data-invalid=true]'));
38
+ }
39
+ /** Opens what hides it (a fold), then moves to it. */
40
+ function moveTo(target, form) {
41
+ for (let at = target.parentElement; at && at !== form; at = at.parentElement) {
42
+ if (at instanceof HTMLDetailsElement && !at.open)
43
+ at.open = true;
44
+ }
45
+ const control = target.matches(FOCUSABLE) ? target : (target.querySelector(FOCUSABLE) ?? target);
46
+ const smooth = !window.matchMedia('(prefers-reduced-motion: reduce)').matches;
47
+ control.scrollIntoView({ block: 'center', behavior: smooth ? 'smooth' : 'auto' });
48
+ // react-hook-form may have focused it already.
49
+ if (!target.contains(document.activeElement))
50
+ control.focus({ preventScroll: true });
51
+ }
52
+ export function EntityForm({ title, onSubmit, isSubmitting, submitError, onRetry, submitLabel, onCancel, danger, dirty, errors, firstInvalid, children, }) {
53
+ const form = useRef(null);
54
+ const bar = useRef(null);
55
+ // A submit was refused: the bar counts what's left until it's none.
56
+ const [refused, setRefused] = useState(false);
57
+ const [marked, setMarked] = useState(0);
58
+ const [askingCancel, setAskingCancel] = useState(false);
59
+ // Moves the guard lets through: while saving, and once Cancel has asked.
60
+ const leaving = useRef(false);
61
+ const submitting = useRef(isSubmitting);
62
+ useLayoutEffect(() => {
63
+ submitting.current = isSubmitting;
64
+ });
65
+ // Without `errors`, count the fields marked invalid, as they change,
66
+ // while there's a count to show.
67
+ const counted = errors !== undefined;
68
+ useEffect(() => {
69
+ const element = form.current;
70
+ if (!refused || counted || !element)
71
+ return;
72
+ const count = () => setMarked(element.querySelectorAll('[data-slot=field][data-invalid=true]').length);
73
+ count();
74
+ const observer = new MutationObserver(count);
75
+ observer.observe(element, { subtree: true, attributes: true, attributeFilter: ['data-invalid'], childList: true });
76
+ return () => observer.disconnect();
77
+ }, [refused, counted]);
78
+ const toFix = refused ? (errors ? countFormErrors(errors) : marked) : 0;
79
+ // The room the stuck bar takes, for the toaster.
80
+ useEffect(() => {
81
+ const element = bar.current;
82
+ if (!element)
83
+ return;
84
+ const root = document.documentElement;
85
+ const measure = () => {
86
+ const bottom = Number.parseFloat(getComputedStyle(element).bottom) || 0;
87
+ root.style.setProperty('--toast-bottom-offset', `${Math.round(element.offsetHeight + bottom)}px`);
88
+ };
89
+ measure();
90
+ const observer = new ResizeObserver(measure);
91
+ observer.observe(element);
92
+ return () => {
93
+ observer.disconnect();
94
+ root.style.removeProperty('--toast-bottom-offset');
95
+ };
96
+ }, []);
97
+ // Each submit, once its validation is done: the effect below runs after
98
+ // the render that draws react-hook-form's marks, and looks for them.
99
+ const [attempt, setAttempt] = useState(0);
100
+ const submit = (event) => {
101
+ const done = onSubmit(event);
102
+ void Promise.resolve(done).then(() => setAttempt((count) => count + 1));
103
+ };
104
+ const findInvalid = useRef(firstInvalid);
105
+ useLayoutEffect(() => {
106
+ findInvalid.current = firstInvalid;
107
+ });
108
+ useEffect(() => {
109
+ const element = form.current;
110
+ if (attempt === 0 || !element)
111
+ return;
112
+ const target = findInvalid.current ? findInvalid.current(element) : problemIn(element);
113
+ setRefused(target !== null);
114
+ if (target)
115
+ moveTo(target, element);
116
+ }, [attempt]);
117
+ const cancel = () => {
118
+ if (dirty) {
119
+ setAskingCancel(true);
120
+ return;
121
+ }
122
+ onCancel();
123
+ };
124
+ return (_jsxs("form", { ref: form, onSubmit: submit, noValidate: true, "data-slot": "entity-form", className: "flex max-w-xl flex-col gap-6", children: [_jsx("h1", { className: "type-page-title text-foreground", children: title }), _jsx(FieldGroup, { children: children }), _jsxs("div", { ref: bar, "data-slot": "entity-form-bar", className: "sticky z-10 -mt-3 flex flex-col gap-3 border-t border-border bg-background pt-3", children: [_jsx("div", { role: "status", className: "empty:hidden", children: submitError && (_jsx(Notice, { tone: "destructive", action: _jsx(Button, { type: "button", size: "sm", variant: "outline", disabled: isSubmitting, onClick: () => (onRetry ? onRetry() : form.current?.requestSubmit()), children: "Try again" }), children: submitError.message })) }), _jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [danger, _jsx("p", { role: "status", "data-slot": "entity-form-to-fix", className: "mr-auto type-label text-destructive-text empty:hidden", children: toFix > 0 ? `${toFix} to fix` : '' }), _jsxs("div", { className: "ml-auto flex gap-2 max-md:w-full max-md:[&>*]:flex-1", children: [_jsx(Button, { type: "button", variant: "outline", onClick: cancel, disabled: isSubmitting, children: "Cancel" }), _jsxs(Button, { type: "submit", disabled: isSubmitting, children: [isSubmitting && _jsx(Spinner, { className: "size-4" }), submitLabel] })] })] })] }), dirty !== undefined && _jsx(FormLeaveGuard, { dirty: dirty, letThrough: () => leaving.current || submitting.current }), _jsx(DiscardChangesDialog, { open: askingCancel, onKeepEditing: () => setAskingCancel(false), onDiscard: () => {
125
+ setAskingCancel(false);
126
+ leaving.current = true;
127
+ onCancel();
128
+ } })] }));
8
129
  }
@@ -15,17 +15,20 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
15
15
  //
16
16
  // `dirty` (react-hook-form's `formState.isDirty`) makes Esc, the close
17
17
  // button, a click outside and Cancel ask "Discard your changes?" first.
18
+ // As a list's `new` route, `dirty` also guards leaving by a link, Back or
19
+ // the sidebar (FormLeaveGuard, 4.85), as EntityForm's does.
18
20
  // A failed save is a Notice above the buttons with Try again, which
19
21
  // submits again unless `onRetry` says otherwise; what was typed stays.
20
22
  //
21
23
  // The form is the app's: its fields, its schema and its react-hook-form
22
24
  // wiring, as with EntityForm. This draws the chrome around them.
23
- import { useId, useRef } from 'react';
25
+ import { useId, useLayoutEffect, useRef } from 'react';
24
26
  import { cn } from 'cn';
25
27
  import { Button } from '../ui/button.js';
26
28
  import { Dialog, DialogClose, DialogContent, DialogDescription, DialogTitle } from '../ui/dialog.js';
27
29
  import { FieldGroup } from '../ui/field.js';
28
30
  import { Spinner } from '../ui/spinner.js';
31
+ import { FormLeaveGuard } from './form-leave-guard.js';
29
32
  import { Notice } from './notice.js';
30
33
  import { useNewRecordDialog } from './record-dialog-context.js';
31
34
  export function FormDialog({ title, description, open, onOpenChange, onSubmit, isSubmitting, submitLabel, submitError, onRetry, dirty = false, children, className, }) {
@@ -33,10 +36,19 @@ export function FormDialog({ title, description, open, onOpenChange, onSubmit, i
33
36
  const form = useRef(null);
34
37
  const formId = useId();
35
38
  const isOpen = open ?? route !== null;
36
- return (_jsx(Dialog, { open: isOpen, onOpenChange: (next) => {
39
+ // The route guard lets through the dialog's own close (it has asked
40
+ // already) and the save's move to the new record.
41
+ const leaving = useRef(false);
42
+ const submitting = useRef(isSubmitting);
43
+ useLayoutEffect(() => {
44
+ submitting.current = isSubmitting;
45
+ });
46
+ return (_jsxs(Dialog, { open: isOpen, onOpenChange: (next) => {
37
47
  if (onOpenChange)
38
48
  onOpenChange(next);
39
- else if (!next)
49
+ else if (!next) {
50
+ leaving.current = true;
40
51
  route?.close();
41
- }, children: _jsxs(DialogContent, { size: "form", dirty: dirty, "data-slot": "form-dialog", className: cn('gap-0 p-0', className), children: [_jsxs("div", { "data-slot": "form-dialog-header", className: "flex flex-col gap-1 px-4 pt-4 pb-2 pr-12 md:px-6 md:pt-5 md:pr-14", children: [_jsx(DialogTitle, { className: "type-section-title", children: title }), description && _jsx(DialogDescription, { children: description })] }), _jsxs("form", { ref: form, id: formId, onSubmit: onSubmit, noValidate: true, className: "flex min-h-0 flex-1 flex-col", children: [_jsx("div", { "data-slot": "form-dialog-body", className: "min-h-0 flex-1 overflow-y-auto px-4 py-4 md:px-6", children: _jsx(FieldGroup, { children: children }) }), _jsxs("div", { "data-slot": "form-dialog-bar", className: "flex flex-col gap-3 border-t px-4 py-3 pb-[calc(0.75rem+env(safe-area-inset-bottom))] md:px-6 md:pb-3", children: [_jsx("div", { role: "status", className: "empty:hidden", children: submitError && (_jsx(Notice, { tone: "destructive", action: _jsx(Button, { type: "button", size: "sm", variant: "outline", disabled: isSubmitting, onClick: () => (onRetry ? onRetry() : form.current?.requestSubmit()), children: "Try again" }), children: submitError.message })) }), _jsxs("div", { className: "flex justify-end gap-2 max-md:[&>*]:h-10 max-md:[&>*]:flex-1", children: [_jsx(DialogClose, { render: _jsx(Button, { type: "button", variant: "outline", disabled: isSubmitting }), children: "Cancel" }), _jsxs(Button, { type: "submit", disabled: isSubmitting, children: [isSubmitting && _jsx(Spinner, { className: "size-4" }), submitLabel] })] })] })] })] }) }));
52
+ }
53
+ }, children: [_jsxs(DialogContent, { size: "form", dirty: dirty, "data-slot": "form-dialog", className: cn('gap-0 p-0', className), children: [_jsxs("div", { "data-slot": "form-dialog-header", className: "flex flex-col gap-1 px-4 pt-4 pb-2 pr-12 md:px-6 md:pt-5 md:pr-14", children: [_jsx(DialogTitle, { className: "type-section-title", children: title }), description && _jsx(DialogDescription, { children: description })] }), _jsxs("form", { ref: form, id: formId, onSubmit: onSubmit, noValidate: true, className: "flex min-h-0 flex-1 flex-col", children: [_jsx("div", { "data-slot": "form-dialog-body", className: "min-h-0 flex-1 overflow-y-auto px-4 py-4 md:px-6", children: _jsx(FieldGroup, { children: children }) }), _jsxs("div", { "data-slot": "form-dialog-bar", className: "flex flex-col gap-3 border-t px-4 py-3 pb-[calc(0.75rem+env(safe-area-inset-bottom))] md:px-6 md:pb-3", children: [_jsx("div", { role: "status", className: "empty:hidden", children: submitError && (_jsx(Notice, { tone: "destructive", action: _jsx(Button, { type: "button", size: "sm", variant: "outline", disabled: isSubmitting, onClick: () => (onRetry ? onRetry() : form.current?.requestSubmit()), children: "Try again" }), children: submitError.message })) }), _jsxs("div", { className: "flex justify-end gap-2 max-md:[&>*]:h-10 max-md:[&>*]:flex-1", children: [_jsx(DialogClose, { render: _jsx(Button, { type: "button", variant: "outline", disabled: isSubmitting }), children: "Cancel" }), _jsxs(Button, { type: "submit", disabled: isSubmitting, children: [isSubmitting && _jsx(Spinner, { className: "size-4" }), submitLabel] })] })] })] })] }), route && open === undefined && (_jsx(FormLeaveGuard, { dirty: dirty, letThrough: () => leaving.current || submitting.current }))] }));
42
54
  }
@@ -0,0 +1,4 @@
1
+ export declare function FormLeaveGuard({ dirty, letThrough }: {
2
+ dirty: boolean;
3
+ letThrough: () => boolean;
4
+ }): import("react").JSX.Element;
@@ -0,0 +1,42 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ // Leaving a form with something typed (4.85, the form standard's F8):
3
+ // "Discard your changes?" (Keep editing, Discard), the prompt a dialog
4
+ // and a value edited in place ask with, before a link, Back or the
5
+ // sidebar moves to another page; the browser's own prompt before a reload
6
+ // or closing the tab. Nothing typed, nothing asked.
7
+ //
8
+ // EntityForm renders it when it's given `dirty`, and FormDialog when it
9
+ // is a list's `new` route. React Router's useBlocker, so it needs a data
10
+ // router (createBrowserRouter), as EditableValue's guard does.
11
+ //
12
+ // `letThrough` is read when a move starts: true while the form is saving
13
+ // (the save's own navigate to the new record must not ask), and once the
14
+ // form has already asked (its Cancel) or the move is its own close.
15
+ import { useEffect, useLayoutEffect, useRef } from 'react';
16
+ import { useBlocker } from 'react-router';
17
+ import { DiscardChangesDialog } from '../ui/dialog.js';
18
+ export function FormLeaveGuard({ dirty, letThrough }) {
19
+ const latest = useRef({ dirty, letThrough });
20
+ useLayoutEffect(() => {
21
+ latest.current = { dirty, letThrough };
22
+ });
23
+ const blocker = useBlocker(({ currentLocation, nextLocation }) => latest.current.dirty && !latest.current.letThrough() && currentLocation.pathname !== nextLocation.pathname);
24
+ useEffect(() => {
25
+ if (!dirty)
26
+ return;
27
+ const onBeforeUnload = (event) => {
28
+ if (latest.current.letThrough())
29
+ return;
30
+ event.preventDefault();
31
+ };
32
+ window.addEventListener('beforeunload', onBeforeUnload);
33
+ return () => window.removeEventListener('beforeunload', onBeforeUnload);
34
+ }, [dirty]);
35
+ return (_jsx(DiscardChangesDialog, { open: blocker.state === 'blocked', "data-form-leave-guard": "", onKeepEditing: () => {
36
+ if (blocker.state === 'blocked')
37
+ blocker.reset();
38
+ }, onDiscard: () => {
39
+ if (blocker.state === 'blocked')
40
+ blocker.proceed();
41
+ } }));
42
+ }
@@ -0,0 +1,9 @@
1
+ import { type ReactNode } from 'react';
2
+ export type FormSectionProps = {
3
+ /** What the group is ("Reading", "Details"): sentence case, a word or two. */
4
+ title: string;
5
+ /** The group's fields. */
6
+ children: ReactNode;
7
+ className?: string;
8
+ };
9
+ export declare function FormSection({ title, children, className }: FormSectionProps): import("react").JSX.Element;
@@ -0,0 +1,15 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // A group of a form's fields in a card (4.85, the form standard's F2),
3
+ // drawn as a record's section is (EntityView): the card surface, its title
4
+ // on the heading band. Only on a form of eight fields or more, and never
5
+ // in a dialog; a short form is one run of fields. Its fields are a
6
+ // FieldGroup of their own, so short ones share rows inside it as they do
7
+ // on the form.
8
+ import { useId } from 'react';
9
+ import { cn } from 'cn';
10
+ import { Card, CardContent, CardHeader } from '../ui/card.js';
11
+ import { FieldGroup } from '../ui/field.js';
12
+ export function FormSection({ title, children, className }) {
13
+ const headingId = useId();
14
+ return (_jsx("section", { "aria-labelledby": headingId, "data-slot": "form-section", className: cn('w-full', className), children: _jsxs(Card, { children: [_jsx(CardHeader, { children: _jsx("h2", { id: headingId, className: "type-section-title text-foreground", children: title }) }), _jsx(CardContent, { children: _jsx(FieldGroup, { children: children }) })] }) }));
15
+ }
@@ -0,0 +1,30 @@
1
+ import type { ReactNode } from 'react';
2
+ export type OptionSelectOption<T> = {
3
+ value: T;
4
+ label: string;
5
+ };
6
+ export type OptionSelectProps<T extends string | number> = {
7
+ id?: string;
8
+ /** Every option, in the order the list shows them. */
9
+ options: readonly OptionSelectOption<T>[];
10
+ value: T | null;
11
+ onValueChange: (value: T | null) => void;
12
+ /** How an option reads on the trigger and in the list (a badge). Defaults to its label. */
13
+ render?: (value: T, label: string) => ReactNode;
14
+ /** No "Not set" option: one of the list must be picked. */
15
+ required?: boolean;
16
+ /** The "Not set" option's words. */
17
+ emptyLabel?: string;
18
+ /** The trigger's words while nothing is picked (a required one). */
19
+ placeholder?: string;
20
+ invalid?: boolean;
21
+ disabled?: boolean;
22
+ defaultOpen?: boolean;
23
+ onOpenChange?: (open: boolean) => void;
24
+ modal?: boolean;
25
+ className?: string;
26
+ 'aria-label'?: string;
27
+ 'aria-labelledby'?: string;
28
+ 'aria-describedby'?: string;
29
+ };
30
+ export declare function OptionSelect<T extends string | number>({ id, options, value, onValueChange, render, required, emptyLabel, placeholder, invalid, disabled, defaultOpen, onOpenChange, modal, className, ...aria }: OptionSelectProps<T>): import("react").JSX.Element;
@@ -0,0 +1,21 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { cn } from 'cn';
3
+ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select.js';
4
+ const NONE = '__none__';
5
+ export function OptionSelect({ id, options, value, onValueChange, render, required = false, emptyLabel = 'Not set', placeholder = 'Pick one', invalid = false, disabled, defaultOpen, onOpenChange, modal, className, ...aria }) {
6
+ const shown = (option) => (render ? render(option.value, option.label) : option.label);
7
+ const at = value == null ? -1 : options.findIndex((option) => option.value === value);
8
+ const key = at === -1 ? (required ? null : NONE) : String(at);
9
+ return (_jsxs(Select, { value: key, onValueChange: (next) => {
10
+ if (next === null)
11
+ return;
12
+ onValueChange(next === NONE ? null : (options[Number(next)]?.value ?? null));
13
+ }, disabled: disabled, defaultOpen: defaultOpen, onOpenChange: onOpenChange, modal: modal, children: [_jsx(SelectTrigger, { id: id, "aria-invalid": invalid || undefined, className: cn('w-full', className), ...aria, children: _jsx(SelectValue, { placeholder: placeholder, children: (picked) => {
14
+ if (picked === null)
15
+ return placeholder;
16
+ if (picked === NONE)
17
+ return _jsx("span", { className: "text-muted-foreground", children: emptyLabel });
18
+ const option = options[Number(picked)];
19
+ return option ? shown(option) : placeholder;
20
+ } }) }), _jsxs(SelectContent, { children: [!required && _jsx(SelectItem, { value: NONE, children: emptyLabel }), options.map((option, index) => (_jsx(SelectItem, { value: String(index), children: shown(option) }, String(option.value))))] })] }));
21
+ }
@@ -13,7 +13,7 @@ const buttonVariants = cva("group/button inline-flex shrink-0 items-center justi
13
13
  link: "text-link underline-offset-4 hover:underline",
14
14
  },
15
15
  size: {
16
- default: "h-9 gap-1.5 px-4 has-data-[icon=inline-end]:pr-3 has-data-[icon=inline-start]:pl-3",
16
+ default: "h-[var(--control-height,--spacing(9))] gap-1.5 px-4 has-data-[icon=inline-end]:pr-3 has-data-[icon=inline-start]:pl-3",
17
17
  xs: "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",
18
18
  sm: "h-8 gap-1 rounded-[min(var(--radius-md),12px)] px-3 text-(length:--control-text-sm) in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
19
19
  lg: "h-10 gap-1.5 px-5 has-data-[icon=inline-end]:pr-4 has-data-[icon=inline-start]:pl-4",
@@ -44,7 +44,7 @@ function ComboboxSeparator({ className, ...props }) {
44
44
  return (_jsx(ComboboxPrimitive.Separator, { "data-slot": "combobox-separator", className: cn("-mx-1 my-1 h-px bg-border", className), ...props }));
45
45
  }
46
46
  function ComboboxChips({ className, ...props }) {
47
- return (_jsx(ComboboxPrimitive.Chips, { "data-slot": "combobox-chips", className: cn("flex min-h-9 flex-wrap items-center gap-1 rounded-md border border-input bg-transparent bg-clip-padding px-2.5 py-1 text-sm transition-colors focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50 has-aria-invalid:border-destructive has-aria-invalid:ring-3 has-aria-invalid:ring-destructive/20 has-data-[slot=combobox-chip]:px-1 dark:bg-input/30 dark:has-aria-invalid:border-destructive/50 dark:has-aria-invalid:ring-destructive/40", className), ...props }));
47
+ return (_jsx(ComboboxPrimitive.Chips, { "data-slot": "combobox-chips", className: cn("flex min-h-[var(--control-height,--spacing(9))] flex-wrap items-center gap-1 rounded-md border border-input bg-transparent bg-clip-padding px-2.5 py-1 text-sm transition-colors focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50 has-aria-invalid:border-destructive has-aria-invalid:ring-3 has-aria-invalid:ring-destructive/20 has-data-[slot=combobox-chip]:px-1 dark:bg-input/30 dark:has-aria-invalid:border-destructive/50 dark:has-aria-invalid:ring-destructive/40", className), ...props }));
48
48
  }
49
49
  function ComboboxChip({ className, children, showRemove = true, ...props }) {
50
50
  return (_jsxs(ComboboxPrimitive.Chip, { "data-slot": "combobox-chip", className: cn("flex h-[calc(--spacing(5.25))] w-fit items-center justify-center gap-1 rounded-sm bg-muted px-1.5 text-xs font-medium whitespace-nowrap text-foreground has-disabled:pointer-events-none has-disabled:cursor-not-allowed has-disabled:opacity-50 has-data-[slot=combobox-chip-remove]:pr-0", className), ...props, children: [children, showRemove && (_jsx(ComboboxPrimitive.ChipRemove
@@ -1,16 +1,41 @@
1
1
  import { type VariantProps } from "class-variance-authority";
2
2
  import { Label } from "./label.js";
3
+ import { type FieldKind, type FieldSize } from "../../lib/field-rows.js";
3
4
  declare function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">): import("react").JSX.Element;
4
5
  declare function FieldLegend({ className, variant, ...props }: React.ComponentProps<"legend"> & {
5
6
  variant?: "legend" | "label";
6
7
  }): import("react").JSX.Element;
7
- declare function FieldGroup({ className, ...props }: React.ComponentProps<"div">): import("react").JSX.Element;
8
+ declare function FieldGroup({ className, ref, ...props }: React.ComponentProps<"div">): import("react").JSX.Element;
8
9
  declare const fieldVariants: (props?: ({
9
10
  orientation?: "horizontal" | "vertical" | "responsive" | null | undefined;
10
11
  } & import("class-variance-authority/types").ClassProp) | undefined) => string;
11
- declare function Field({ className, orientation, ...props }: React.ComponentProps<"div"> & VariantProps<typeof fieldVariants>): import("react").JSX.Element;
12
+ declare function Field({ className, orientation, size, solo, kind, ...props }: React.ComponentProps<"div"> & VariantProps<typeof fieldVariants> & {
13
+ /**
14
+ * How much it holds, so FieldGroup can put short fields side by side:
15
+ * `s` a number or a short code, `m` a date, a status, a choice of two
16
+ * to four or a rating, `l` a name or a pick of a record, `full` (the
17
+ * default) long text, a list or anything that needs the row.
18
+ */
19
+ size?: FieldSize;
20
+ /** Keep this short field on a row of its own, where a pairing would read wrong. */
21
+ solo?: boolean;
22
+ /**
23
+ * A date or a number: two of a kind stay side by side on a phone.
24
+ * Found by itself for a date or number `<input>`; say it for a
25
+ * control of your own (DateField's button).
26
+ */
27
+ kind?: FieldKind;
28
+ }): import("react").JSX.Element;
12
29
  declare function FieldContent({ className, ...props }: React.ComponentProps<"div">): import("react").JSX.Element;
13
- declare function FieldLabel({ className, ...props }: React.ComponentProps<typeof Label>): import("react").JSX.Element;
30
+ declare function FieldLabel({ className, required, children, ...props }: React.ComponentProps<typeof Label> & {
31
+ /**
32
+ * A field that must be filled: an asterisk after the words, and
33
+ * `aria-required` on the control `htmlFor` names where its role takes
34
+ * it (a box, a select, a combobox; not a date picker's button). Nothing
35
+ * marks an optional one (no "(optional)").
36
+ */
37
+ required?: boolean;
38
+ }): import("react").JSX.Element;
14
39
  declare function FieldTitle({ className, ...props }: React.ComponentProps<"div">): import("react").JSX.Element;
15
40
  declare function FieldDescription({ className, ...props }: React.ComponentProps<"p">): import("react").JSX.Element;
16
41
  declare function FieldSeparator({ children, className, ...props }: React.ComponentProps<"div"> & {
@@ -1,22 +1,106 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { useMemo } from "react";
2
+ import { useLayoutEffect, useMemo, useRef } from "react";
3
3
  import { cva } from "class-variance-authority";
4
4
  import { cn } from "cn";
5
5
  import { Label } from "./label.js";
6
6
  import { Separator } from "./separator.js";
7
+ import { fieldRows } from "../../lib/field-rows.js";
8
+ // The foundation's additions to shadcn's Field (4.85, the form standard):
9
+ //
10
+ // - FieldGroup lays its fields out itself: consecutive short fields
11
+ // (`<Field size="s" | "m" | "l">`) share a row, up to three, each as
12
+ // wide as its size; `<Field solo>` keeps a short one alone
13
+ // (lib/field-rows.ts has the rule). Below 48rem each takes its own row
14
+ // but two dates or two numbers. The rows are worked out from the DOM, so
15
+ // a Field inside the app's own component still counts.
16
+ // - Compact: 14px between fields and 32px controls (40px under 48rem or
17
+ // on a touch screen), from `--control-height`, which FieldGroup sets
18
+ // and the inputs, selects and buttons read (styles/index.css).
19
+ // - `<FieldLabel required>`: an asterisk in the destructive text tone,
20
+ // hidden from screen readers, and `aria-required` on the control it
21
+ // names, which says it instead.
7
22
  function FieldSet({ className, ...props }) {
8
23
  return (_jsx("fieldset", { "data-slot": "field-set", className: cn("flex flex-col gap-4 has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3", className), ...props }));
9
24
  }
10
25
  function FieldLegend({ className, variant = "legend", ...props }) {
11
26
  return (_jsx("legend", { "data-slot": "field-legend", "data-variant": variant, className: cn("mb-1.5 font-medium data-[variant=label]:text-sm data-[variant=legend]:text-base", className), ...props }));
12
27
  }
13
- function FieldGroup({ className, ...props }) {
14
- return (_jsx("div", { "data-slot": "field-group", className: cn("group/field-group @container/field-group flex w-full flex-col gap-5 data-[slot=checkbox-group]:gap-3 *:data-[slot=field-group]:gap-4", className), ...props }));
28
+ // What a Field holds, when it doesn't say (`kind`): a date or a number
29
+ // box keeps its partner on a phone.
30
+ const DATE_CONTROL = "input[type=date]";
31
+ const NUMBER_CONTROL = "input[type=number], input[inputmode=numeric], input[inputmode=decimal]";
32
+ function kindOf(field) {
33
+ const said = field.dataset.kind;
34
+ if (said === "date" || said === "number")
35
+ return said;
36
+ if (field.querySelector(DATE_CONTROL))
37
+ return "date";
38
+ if (field.querySelector(NUMBER_CONTROL))
39
+ return "number";
40
+ return null;
41
+ }
42
+ const SIZES = new Set(["s", "m", "l", "full"]);
43
+ /** Puts each of the group's own fields in its row (lib/field-rows.ts). */
44
+ function layOut(group) {
45
+ const children = Array.from(group.children);
46
+ const items = children.map((child) => {
47
+ const isField = child.dataset.slot === "field";
48
+ const size = isField ? child.dataset.size : undefined;
49
+ return {
50
+ size: (size && SIZES.has(size) ? size : "full"),
51
+ solo: child.dataset.solo !== undefined,
52
+ kind: isField ? kindOf(child) : null,
53
+ };
54
+ });
55
+ fieldRows(items).forEach((place, at) => {
56
+ const child = children[at];
57
+ if (place.share === null) {
58
+ child.style.removeProperty("--field-share");
59
+ child.style.removeProperty("--field-gaps");
60
+ delete child.dataset.fieldRow;
61
+ delete child.dataset.phonePair;
62
+ return;
63
+ }
64
+ child.style.setProperty("--field-share", String(place.share));
65
+ child.style.setProperty("--field-gaps", String(place.gaps));
66
+ child.dataset.fieldRow = "";
67
+ if (place.phonePair)
68
+ child.dataset.phonePair = "";
69
+ else
70
+ delete child.dataset.phonePair;
71
+ });
72
+ }
73
+ function FieldGroup({ className, ref, ...props }) {
74
+ const own = useRef(null);
75
+ useLayoutEffect(() => {
76
+ const group = own.current;
77
+ if (!group)
78
+ return;
79
+ layOut(group);
80
+ // Fields come and go (a conditional field, an error line), and a
81
+ // field's size can change: lay it out again. Only what layOut reads
82
+ // is watched, so its own writes don't wake it.
83
+ const observer = new MutationObserver(() => layOut(group));
84
+ observer.observe(group, {
85
+ childList: true,
86
+ subtree: true,
87
+ attributes: true,
88
+ attributeFilter: ["data-size", "data-solo", "data-kind", "type", "inputmode"],
89
+ });
90
+ return () => observer.disconnect();
91
+ }, []);
92
+ return (_jsx("div", { ref: (node) => {
93
+ own.current = node;
94
+ if (typeof ref === "function")
95
+ return ref(node);
96
+ if (ref)
97
+ ref.current = node;
98
+ }, "data-slot": "field-group", className: cn("group/field-group @container/field-group flex w-full flex-wrap gap-x-3 gap-y-3.5 data-[slot=checkbox-group]:gap-3 *:data-[slot=field-group]:gap-y-3.5 has-[>[data-slot=form-section]]:gap-y-6", className), ...props }));
15
99
  }
16
100
  const fieldVariants = cva("group/field flex w-full gap-2 data-[invalid=true]:text-destructive-text", {
17
101
  variants: {
18
102
  orientation: {
19
- vertical: "flex-col *:w-full [&>.sr-only]:w-auto",
103
+ vertical: "flex-col gap-1.5 *:w-full [&>.sr-only]:w-auto",
20
104
  horizontal: "flex-row items-center has-[>[data-slot=field-content]]:items-start *:data-[slot=field-label]:flex-auto has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
21
105
  responsive: "flex-col *:w-full @md/field-group:flex-row @md/field-group:items-center @md/field-group:*:w-auto @md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:*:data-[slot=field-label]:flex-auto [&>.sr-only]:w-auto @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
22
106
  },
@@ -25,14 +109,38 @@ const fieldVariants = cva("group/field flex w-full gap-2 data-[invalid=true]:tex
25
109
  orientation: "vertical",
26
110
  },
27
111
  });
28
- function Field({ className, orientation = "vertical", ...props }) {
29
- return (_jsx("div", { role: "group", "data-slot": "field", "data-orientation": orientation, className: cn(fieldVariants({ orientation }), className), ...props }));
112
+ function Field({ className, orientation = "vertical", size, solo = false, kind, ...props }) {
113
+ return (_jsx("div", { role: "group", "data-slot": "field", "data-orientation": orientation, "data-size": size, "data-solo": solo ? "" : undefined, "data-kind": kind, className: cn(fieldVariants({ orientation }), className), ...props }));
30
114
  }
31
115
  function FieldContent({ className, ...props }) {
32
116
  return (_jsx("div", { "data-slot": "field-content", className: cn("group/field-content flex flex-1 flex-col gap-0.5 leading-snug", className), ...props }));
33
117
  }
34
- function FieldLabel({ className, ...props }) {
35
- return (_jsx(Label, { "data-slot": "field-label", className: cn("group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50 has-data-checked:border-primary/30 has-data-checked:bg-primary/5 has-[>[data-slot=field]]:rounded-lg has-[>[data-slot=field]]:border has-[>[data-slot=field]]:not-has-[:disabled,[data-disabled]]:hover:bg-muted/50 has-[>[data-slot=field]]:has-[:focus-visible]:border-ring has-[>[data-slot=field]]:has-[:focus-visible]:ring-3 has-[>[data-slot=field]]:has-[:focus-visible]:ring-ring/50 *:data-[slot=field]:p-2.5 dark:has-data-checked:border-primary/20 dark:has-data-checked:bg-primary/10", "has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col", className), ...props }));
118
+ const REQUIRABLE_ROLES = new Set(["combobox", "textbox", "listbox", "radiogroup", "spinbutton", "searchbox", "gridcell", "tree", "treegrid", "checkbox", "switch"]);
119
+ /** Whether `aria-required` is allowed on it: a form control, or a role that takes it. */
120
+ function takesRequired(control) {
121
+ const role = control.getAttribute("role");
122
+ if (role)
123
+ return REQUIRABLE_ROLES.has(role);
124
+ if (control instanceof HTMLTextAreaElement || control instanceof HTMLSelectElement)
125
+ return true;
126
+ if (control instanceof HTMLInputElement)
127
+ return !["button", "submit", "reset", "image", "hidden"].includes(control.type);
128
+ return false;
129
+ }
130
+ function FieldLabel({ className, required = false, children, ...props }) {
131
+ const { htmlFor } = props;
132
+ useLayoutEffect(() => {
133
+ if (!required || !htmlFor)
134
+ return;
135
+ const control = document.getElementById(htmlFor);
136
+ // Only where the control's role takes it (ARIA): a box, a list or a
137
+ // group of choices, not a button (a date picker's trigger).
138
+ if (!control || !takesRequired(control))
139
+ return;
140
+ control.setAttribute("aria-required", "true");
141
+ return () => control.removeAttribute("aria-required");
142
+ }, [required, htmlFor]);
143
+ return (_jsxs(Label, { "data-slot": "field-label", "data-required": required ? "" : undefined, className: cn("group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50 has-data-checked:border-primary/30 has-data-checked:bg-primary/5 has-[>[data-slot=field]]:rounded-lg has-[>[data-slot=field]]:border has-[>[data-slot=field]]:not-has-[:disabled,[data-disabled]]:hover:bg-muted/50 has-[>[data-slot=field]]:has-[:focus-visible]:border-ring has-[>[data-slot=field]]:has-[:focus-visible]:ring-3 has-[>[data-slot=field]]:has-[:focus-visible]:ring-ring/50 *:data-[slot=field]:p-2.5 dark:has-data-checked:border-primary/20 dark:has-data-checked:bg-primary/10", "has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col", className), ...props, children: [children, required && (_jsx("span", { "aria-hidden": "true", "data-slot": "field-required", className: "-ml-1.5 text-destructive-text", children: "*" }))] }));
36
144
  }
37
145
  function FieldTitle({ className, ...props }) {
38
146
  return (_jsx("div", { "data-slot": "field-label", className: cn("flex w-fit items-center gap-2 text-sm font-medium group-data-[disabled=true]/field:opacity-50", className), ...props }));
@@ -6,7 +6,7 @@ import { Button } from "./button.js";
6
6
  import { Input } from "./input.js";
7
7
  import { Textarea } from "./textarea.js";
8
8
  function InputGroup({ className, ...props }) {
9
- return (_jsx("div", { "data-slot": "input-group", role: "group", className: cn("group/input-group relative flex h-9 w-full min-w-0 items-center rounded-md border border-input transition-colors outline-none in-data-[slot=combobox-content]:focus-within:border-inherit in-data-[slot=combobox-content]:focus-within:ring-0 has-disabled:bg-input/50 has-disabled:opacity-50 has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-3 has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot][aria-invalid=true]]:border-destructive has-[[data-slot][aria-invalid=true]]:ring-3 has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>textarea]:h-auto dark:bg-input/30 dark:has-disabled:bg-input/80 dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40 has-[>[data-align=block-end]]:[&>input]:pt-3 has-[>[data-align=block-start]]:[&>input]:pb-3 has-[>[data-align=inline-end]]:[&>input]:pr-1.5 has-[>[data-align=inline-start]]:[&>input]:pl-1.5", className), ...props }));
9
+ return (_jsx("div", { "data-slot": "input-group", role: "group", className: cn("group/input-group relative flex h-[var(--control-height,--spacing(9))] w-full min-w-0 items-center rounded-md border border-input transition-colors outline-none in-data-[slot=combobox-content]:focus-within:border-inherit in-data-[slot=combobox-content]:focus-within:ring-0 has-disabled:bg-input/50 has-disabled:opacity-50 has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-3 has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot][aria-invalid=true]]:border-destructive has-[[data-slot][aria-invalid=true]]:ring-3 has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>textarea]:h-auto dark:bg-input/30 dark:has-disabled:bg-input/80 dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40 has-[>[data-align=block-end]]:[&>input]:pt-3 has-[>[data-align=block-start]]:[&>input]:pb-3 has-[>[data-align=inline-end]]:[&>input]:pr-1.5 has-[>[data-align=inline-start]]:[&>input]:pl-1.5", className), ...props }));
10
10
  }
11
11
  const inputGroupAddonVariants = cva("flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm font-medium text-muted-foreground select-none group-data-[disabled=true]/input-group:opacity-50 [&>kbd]:rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-4", {
12
12
  variants: {
@@ -3,6 +3,6 @@ import * as React from "react";
3
3
  import { Input as InputPrimitive } from "@base-ui/react/input";
4
4
  import { cn } from "cn";
5
5
  function Input({ className, type, ...props }) {
6
- return (_jsx(InputPrimitive, { type: type, "data-slot": "input", className: cn("h-9 w-full min-w-0 rounded-md border border-input bg-transparent palette:text-foreground px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40", className), ...props }));
6
+ return (_jsx(InputPrimitive, { type: type, "data-slot": "input", className: cn("h-[var(--control-height,--spacing(9))] w-full min-w-0 rounded-md border border-input bg-transparent palette:text-foreground px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40", className), ...props }));
7
7
  }
8
8
  export { Input };
@@ -12,7 +12,7 @@ function SelectValue({ className, ...props }) {
12
12
  return (_jsx(SelectPrimitive.Value, { "data-slot": "select-value", className: cn("flex flex-1 text-left", className), ...props }));
13
13
  }
14
14
  function SelectTrigger({ className, size = "default", children, ...props }) {
15
- return (_jsxs(SelectPrimitive.Trigger, { "data-slot": "select-trigger", "data-size": size, className: cn("flex w-fit items-center justify-between gap-1.5 rounded-md border border-input bg-transparent palette:text-foreground py-2 pr-2 pl-2.5 text-sm whitespace-nowrap transition-colors outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 data-[size=sm]:rounded-[min(var(--radius-md),10px)] *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", className), ...props, children: [children, _jsx(SelectPrimitive.Icon, { render: _jsx(ChevronDownIcon, { className: "pointer-events-none size-4 text-muted-foreground" }) })] }));
15
+ return (_jsxs(SelectPrimitive.Trigger, { "data-slot": "select-trigger", "data-size": size, className: cn("flex w-fit items-center justify-between gap-1.5 rounded-md border border-input bg-transparent palette:text-foreground py-2 pr-2 pl-2.5 text-sm whitespace-nowrap transition-colors outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-[var(--control-height,--spacing(9))] data-[size=sm]:h-8 data-[size=sm]:rounded-[min(var(--radius-md),10px)] *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", className), ...props, children: [children, _jsx(SelectPrimitive.Icon, { render: _jsx(ChevronDownIcon, { className: "pointer-events-none size-4 text-muted-foreground" }) })] }));
16
16
  }
17
17
  function SelectContent({ className, children, side = "bottom", sideOffset = 4, align = "center", alignOffset = 0, alignItemWithTrigger = true, ...props }) {
18
18
  return (_jsx(SelectPrimitive.Portal, { children: _jsx(SelectPrimitive.Positioner, { side: side, sideOffset: sideOffset, align: align, alignOffset: alignOffset, alignItemWithTrigger: alignItemWithTrigger, className: "isolate z-50", children: _jsxs(SelectPrimitive.Popup, { "data-slot": "select-content", "data-align-trigger": alignItemWithTrigger, className: cn("relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className), ...props, children: [_jsx(SelectScrollUpButton, {}), _jsx(SelectPrimitive.List, { children: children }), _jsx(SelectScrollDownButton, {})] }) }) }));
package/dist/index.d.ts CHANGED
@@ -13,6 +13,10 @@ export { DataTable, type DataTableCardLayout, type DataTableOpens, type DataTabl
13
13
  export { type RowGroup } from './components/app/table-groups.js';
14
14
  export { byDay, type ByDayOptions } from './lib/group-by-day.js';
15
15
  export { EntityForm, type EntityFormProps } from './components/app/entity-form.js';
16
+ export { countFormErrors } from './lib/form-errors.js';
17
+ export { FormSection, type FormSectionProps } from './components/app/form-section.js';
18
+ export { OptionSelect, type OptionSelectOption, type OptionSelectProps } from './components/app/option-select.js';
19
+ export { fieldRows, type FieldKind, type FieldRowItem, type FieldRowPlace, type FieldSize } from './lib/field-rows.js';
16
20
  export { KeyStats, type KeyStat, type KeyStatsProps } from './components/app/key-stats.js';
17
21
  export { IconAction, type IconActionProps } from './components/app/icon-action.js';
18
22
  export { EntityView, type EntityViewEmptyFields, type EntityViewField, type EntityViewLayout, type EntityViewMobileOrder, type EntityViewPlacement, type EntityViewProps, type EntityViewRailFields, type EntityViewSection, } from './components/app/entity-view.js';
package/dist/index.js CHANGED
@@ -17,6 +17,10 @@ export { DataTable, } from './components/app/data-table.js';
17
17
  export {} from './components/app/table-groups.js';
18
18
  export { byDay } from './lib/group-by-day.js';
19
19
  export { EntityForm } from './components/app/entity-form.js';
20
+ export { countFormErrors } from './lib/form-errors.js';
21
+ export { FormSection } from './components/app/form-section.js';
22
+ export { OptionSelect } from './components/app/option-select.js';
23
+ export { fieldRows } from './lib/field-rows.js';
20
24
  export { KeyStats } from './components/app/key-stats.js';
21
25
  export { IconAction } from './components/app/icon-action.js';
22
26
  export { EntityView, } from './components/app/entity-view.js';
@@ -0,0 +1,18 @@
1
+ export type FieldSize = 's' | 'm' | 'l' | 'full';
2
+ export type FieldKind = 'date' | 'number';
3
+ export type FieldRowItem = {
4
+ size: FieldSize;
5
+ solo?: boolean;
6
+ kind?: FieldKind | null;
7
+ };
8
+ export type FieldRowPlace = {
9
+ /** Its share of the row's width (after the gaps), or null for a row of its own. */
10
+ share: number | null;
11
+ /** How many gaps its row has (fields in it, less one). */
12
+ gaps: number;
13
+ /** Stays beside its partner on a phone: two dates or two numbers. */
14
+ phonePair: boolean;
15
+ };
16
+ /** The most fields one row holds. */
17
+ export declare const FIELDS_PER_ROW = 3;
18
+ export declare function fieldRows(items: readonly FieldRowItem[]): FieldRowPlace[];
@@ -0,0 +1,53 @@
1
+ // Which fields of a form share a row (4.85, the form standard's F1),
2
+ // worked out from their order, never listed by hand. A field says how
3
+ // much it holds (`Field size`); consecutive short ones share a row, up to
4
+ // three, each as wide as its size: s 1, m 1.4, l 2.6 parts of the row.
5
+ // A long box (`l`) takes one short partner at most (a series and its
6
+ // number), never another long one, so the row ends with the pair and the
7
+ // next short fields start their own (Started, Finished, Rating). `full`
8
+ // (a field with no size), a `solo` field and anything that isn't a Field
9
+ // take a row of their own.
10
+ //
11
+ // Below 48rem every field takes its own row, except two dates or two
12
+ // numbers next to each other in a row, which stay side by side
13
+ // (`phonePair`).
14
+ const PARTS = { s: 1, m: 1.4, l: 2.6 };
15
+ /** The most fields one row holds. */
16
+ export const FIELDS_PER_ROW = 3;
17
+ export function fieldRows(items) {
18
+ const places = items.map(() => ({ share: null, gaps: 0, phonePair: false }));
19
+ let row = [];
20
+ const close = () => {
21
+ if (row.length > 1) {
22
+ const parts = row.map((at) => PARTS[items[at].size]);
23
+ const total = parts.reduce((sum, part) => sum + part, 0);
24
+ row.forEach((at, index) => {
25
+ places[at] = { share: parts[index] / total, gaps: row.length - 1, phonePair: false };
26
+ });
27
+ for (let index = 0; index + 1 < row.length; index++) {
28
+ const a = items[row[index]].kind;
29
+ const b = items[row[index + 1]].kind;
30
+ if (a && a === b && !places[row[index]].phonePair) {
31
+ places[row[index]].phonePair = true;
32
+ places[row[index + 1]].phonePair = true;
33
+ index++;
34
+ }
35
+ }
36
+ }
37
+ row = [];
38
+ };
39
+ items.forEach((item, at) => {
40
+ const shares = item.size !== 'full' && !item.solo;
41
+ if (!shares) {
42
+ close();
43
+ return;
44
+ }
45
+ const hasLong = row.some((index) => items[index].size === 'l');
46
+ const full = row.length >= (hasLong || item.size === 'l' ? 2 : FIELDS_PER_ROW);
47
+ if (full || (item.size === 'l' && hasLong))
48
+ close();
49
+ row.push(at);
50
+ });
51
+ close();
52
+ return places;
53
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * How many problems react-hook-form's `formState.errors` hold: one per
3
+ * field, one per list's own (`root`), however deep (4.85, EntityForm's
4
+ * "N to fix").
5
+ */
6
+ export declare function countFormErrors(errors: unknown): number;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * How many problems react-hook-form's `formState.errors` hold: one per
3
+ * field, one per list's own (`root`), however deep (4.85, EntityForm's
4
+ * "N to fix").
5
+ */
6
+ export function countFormErrors(errors) {
7
+ if (!errors || typeof errors !== 'object')
8
+ return 0;
9
+ const entry = errors;
10
+ if (typeof entry.type === 'string' || typeof entry.message === 'string')
11
+ return 1;
12
+ let count = 0;
13
+ for (const [key, value] of Object.entries(entry)) {
14
+ if (key === 'ref')
15
+ continue;
16
+ count += countFormErrors(value);
17
+ }
18
+ return count;
19
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tristan2828/ui-foundation",
3
- "version": "4.84.0",
3
+ "version": "4.85.0",
4
4
  "description": "Shared UI foundation for contract-first, database-backed React apps: shadcn primitives, DataTable/EntityForm composites, auth, the gateway error seam, design tokens, lint rules and the AI playbook.",
5
5
  "license": "MIT",
6
6
  "repository": {
package/styles/index.css CHANGED
@@ -615,3 +615,63 @@
615
615
  .page-removed .page-removed-note {
616
616
  margin-inline: 0;
617
617
  }
618
+
619
+ /* Forms (4.85, the form standard; field.tsx and entity-form.tsx).
620
+ Compact: controls inside a FieldGroup and on a form's bar read
621
+ --control-height (Input, SelectTrigger, InputGroup, the combobox's chips
622
+ box and a default Button), 32px, or 40px under 48rem or on a touch
623
+ screen, for the finger. Anywhere else they keep their 36px. Each is a
624
+ calc of --spacing, resolved here, so the large density grows it. */
625
+ [data-slot="field-group"],
626
+ [data-slot="entity-form-bar"],
627
+ [data-slot="form-dialog-bar"] {
628
+ --control-height: calc(var(--spacing) * 8);
629
+ }
630
+ @media (width < 48rem), (pointer: coarse) {
631
+ [data-slot="field-group"],
632
+ [data-slot="entity-form-bar"],
633
+ [data-slot="form-dialog-bar"] {
634
+ --control-height: calc(var(--spacing) * 10);
635
+ }
636
+ }
637
+
638
+ /* Short fields side by side (FieldGroup's layOut sets --field-share and
639
+ --field-gaps on each field of a shared row; lib/field-rows.ts): its
640
+ share of what the row's gaps leave. A hair under, so rounding never
641
+ pushes the last one onto the next line. Under 48rem every field takes
642
+ the row but two dates or two numbers. */
643
+ /* Everything else in a group takes the row, as it did when the group was
644
+ a column (a button, a fieldset, a line of text). In the base layer, so
645
+ a width utility on the child still wins. */
646
+ @layer base {
647
+ [data-slot="field-group"] > * {
648
+ width: 100%;
649
+ min-width: 0;
650
+ }
651
+ }
652
+ [data-slot="field-group"] > [data-field-row] {
653
+ flex: 0 0 auto;
654
+ width: calc((100% - var(--field-gaps) * var(--spacing) * 3) * var(--field-share) - 0.05px);
655
+ }
656
+ @media (width < 48rem) {
657
+ [data-slot="field-group"] > [data-field-row] {
658
+ width: 100%;
659
+ }
660
+ [data-slot="field-group"] > [data-field-row][data-phone-pair] {
661
+ width: calc((100% - var(--spacing) * 3) / 2 - 0.05px);
662
+ }
663
+ }
664
+
665
+ /* EntityForm's bar, stuck to the bottom of the window while the form is
666
+ taller than it. Above the shell's bottom bar on a phone, which then
667
+ has the safe area under it already. */
668
+ [data-slot="entity-form-bar"] {
669
+ bottom: var(--form-bar-bottom, 0px);
670
+ padding-bottom: calc(var(--spacing) * 3 + var(--form-bar-safe-area, env(safe-area-inset-bottom)));
671
+ }
672
+ @media (width < 48rem) {
673
+ :root:has([data-slot="app-shell-bottom-bar"]) {
674
+ --form-bar-bottom: calc(var(--spacing) * 16 + 1px + env(safe-area-inset-bottom));
675
+ --form-bar-safe-area: 0px;
676
+ }
677
+ }