@tristan2828/ui-foundation 4.83.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.
Files changed (43) hide show
  1. package/README.md +1 -1
  2. package/conventions/docs/add-an-entity.md +68 -23
  3. package/conventions/docs/design-language.md +82 -30
  4. package/dist/components/app/entity-form.d.ts +27 -3
  5. package/dist/components/app/entity-form.js +124 -3
  6. package/dist/components/app/form-dialog.js +16 -4
  7. package/dist/components/app/form-leave-guard.d.ts +4 -0
  8. package/dist/components/app/form-leave-guard.js +42 -0
  9. package/dist/components/app/form-section.d.ts +9 -0
  10. package/dist/components/app/form-section.js +15 -0
  11. package/dist/components/app/freshness.d.ts +14 -0
  12. package/dist/components/app/freshness.js +25 -0
  13. package/dist/components/app/list-header.d.ts +44 -0
  14. package/dist/components/app/list-header.js +27 -0
  15. package/dist/components/app/needs-you.d.ts +19 -0
  16. package/dist/components/app/needs-you.js +30 -0
  17. package/dist/components/app/option-select.d.ts +30 -0
  18. package/dist/components/app/option-select.js +21 -0
  19. package/dist/components/app/part-empty.d.ts +20 -0
  20. package/dist/components/app/part-empty.js +17 -0
  21. package/dist/components/app/timeline.d.ts +25 -0
  22. package/dist/components/app/timeline.js +31 -0
  23. package/dist/components/app/value-list.d.ts +14 -0
  24. package/dist/components/app/value-list.js +13 -0
  25. package/dist/components/app/widget-card.d.ts +9 -1
  26. package/dist/components/app/widget-card.js +3 -2
  27. package/dist/components/ui/button.js +1 -1
  28. package/dist/components/ui/combobox.js +1 -1
  29. package/dist/components/ui/field.d.ts +28 -3
  30. package/dist/components/ui/field.js +116 -8
  31. package/dist/components/ui/input-group.js +1 -1
  32. package/dist/components/ui/input.js +1 -1
  33. package/dist/components/ui/select.js +1 -1
  34. package/dist/index.d.ts +11 -0
  35. package/dist/index.js +11 -0
  36. package/dist/lib/field-rows.d.ts +18 -0
  37. package/dist/lib/field-rows.js +53 -0
  38. package/dist/lib/form-errors.d.ts +6 -0
  39. package/dist/lib/form-errors.js +19 -0
  40. package/dist/lib/freshness.d.ts +6 -0
  41. package/dist/lib/freshness.js +37 -0
  42. package/package.json +1 -1
  43. package/styles/index.css +60 -0
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 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):
@@ -3,36 +3,37 @@
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
- - [Palettes](#palettes) · lines 45–112
7
- - [Glow](#glow) · lines 114–132
8
- - [Semantic tones](#semantic-tones) · lines 134–162
9
- - [The three badge styles](#the-three-badge-styles) · lines 164–181
10
- - [Mapping an enum to tones](#mapping-an-enum-to-tones) · lines 183–212
11
- - [Glyphs and icons: 3:1](#glyphs-and-icons-31) · lines 214–227
12
- - [Logos and brand marks](#logos-and-brand-marks) · lines 229–273
13
- - [Categorical colour](#categorical-colour) · lines 275–345
14
- - [Heat scale](#heat-scale) · lines 347–408
15
- - [Depth ramps](#depth-ramps) · lines 410–488
16
- - [A stored colour](#a-stored-colour) · lines 490–538
17
- - [Shapes and sizes](#shapes-and-sizes) · lines 540–561
18
- - [Typography](#typography) · lines 563–683
19
- - [Written text (notes)](#written-text-notes) · lines 597–683
20
- - [Density](#density) · lines 685–771
21
- - [Rows on this device](#rows-on-this-device) · lines 744–771
22
- - [Widget cards (hub pages)](#widget-cards-hub-pages) · lines 773–887
23
- - [Module cards (a hub's places)](#module-cards-a-hubs-places) · lines 889–966
24
- - [Notices](#notices) · lines 968–996
25
- - [A value over time](#a-value-over-time) · lines 998–1084
26
- - [Several values over time](#several-values-over-time) · lines 1047–1084
27
- - [A list as a board](#a-list-as-a-board) · lines 1086–1137
28
- - [A list as cards](#a-list-as-cards) · lines 1139–1185
29
- - [Key numbers on a record](#key-numbers-on-a-record) · lines 1187–1216
30
- - [A record's header and empty values](#a-records-header-and-empty-values) · lines 1218–1256
31
- - [A record's tabs, mark and rail](#a-records-tabs-mark-and-rail) · lines 1258–1303
32
- - [Picking at random](#picking-at-random) · lines 1305–1336
33
- - [Filling in what's missing](#filling-in-whats-missing) · lines 1338–1405
34
- - [Values edited in place: the presets' looks](#values-edited-in-place-the-presets-looks) · lines 1407–1432
35
- - [The sidebar and the phone's bar](#the-sidebar-and-the-phones-bar) · lines 1434–1480
6
+ - [Palettes](#palettes) · lines 46–113
7
+ - [Glow](#glow) · lines 115–133
8
+ - [Semantic tones](#semantic-tones) · lines 135–163
9
+ - [The three badge styles](#the-three-badge-styles) · lines 165–182
10
+ - [Mapping an enum to tones](#mapping-an-enum-to-tones) · lines 184–213
11
+ - [Glyphs and icons: 3:1](#glyphs-and-icons-31) · lines 215–228
12
+ - [Logos and brand marks](#logos-and-brand-marks) · lines 230–274
13
+ - [Categorical colour](#categorical-colour) · lines 276–346
14
+ - [Heat scale](#heat-scale) · lines 348–409
15
+ - [Depth ramps](#depth-ramps) · lines 411–489
16
+ - [A stored colour](#a-stored-colour) · lines 491–539
17
+ - [Shapes and sizes](#shapes-and-sizes) · lines 541–562
18
+ - [Typography](#typography) · lines 564–684
19
+ - [Written text (notes)](#written-text-notes) · lines 598–684
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
36
37
 
37
38
  <!-- /index -->
38
39
 
@@ -703,6 +704,13 @@ set, not a `DataTable` prop:
703
704
 
704
705
  - `compact` and `comfortable` change padding only. Text keeps
705
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.
706
714
  - On a hub, `compact` takes a `WidgetCard`'s padding from 16px to 12px,
707
715
  a `WidgetList` row from 36px to 32px (6px around its line) and a
708
716
  `ModuleCard`'s band and body by 4px each. On a phone a compact row is
@@ -1215,6 +1223,50 @@ row under the header, across the page at every width.
1215
1223
  - **`subtitle`** is the line under the title: what the record is for,
1216
1224
  in muted body type, editable in place like any value.
1217
1225
 
1226
+ ## Parts of the page standards
1227
+
1228
+ Six small parts the list, record and overview standards share. Each is
1229
+ generic and standalone: an app (or a later foundation release) wires it
1230
+ into a table, a record or an overview.
1231
+
1232
+ - **`ValueList`: several values in a cell.** `<ValueList items={[{ label }]} max={2} />`
1233
+ shows two values on one line and the rest as `+N`, every folded value in
1234
+ its tooltip (the `+N` is a button, so a keyboard and a tap reach it). A
1235
+ value is a chip by default, or the app's own `node` (an icon, a
1236
+ `ColorSwatch`) with its `label` as the plain text. An empty cell is a
1237
+ muted dash that reads "None".
1238
+ - **`ListHeader`: a list's header.** The title (the page's h1) with its
1239
+ `count`, `newAction` alone beside it, and one ⋯ menu for the rest. One
1240
+ related link in `links` stays a button; two or more fold into ⋯ with
1241
+ `more` (the page's own actions). `deleted={{ shown, onShownChange }}` adds
1242
+ "Show deleted" as the menu's last item and, while it's on, an info
1243
+ `Notice` with "Back to the list" in a `role="status"` region that is
1244
+ always there. It holds no state: the app keeps `shown`.
1245
+ - **`Timeline`: a record's dated history.** `items` newest first
1246
+ (`{ id, date, dateTime?, kind?, body, edit? }`): dates in a tabular
1247
+ column on the left, a dot and a thin line, the entry on the right with
1248
+ its `kind` as a muted line under it and `edit` (the entry's own
1249
+ control) at its end. The first `initial` (5) show, then "Show all N";
1250
+ under 24rem of its own width the date moves above its entry. Empty
1251
+ reads `emptyText` ("Nothing yet").
1252
+ - **`NeedsYou`: what waits on the user.** `items={[{ text, to, tone? }]}`:
1253
+ one region at the top of an overview, a warning wash with the `*-text`
1254
+ icon, each line a link; `tone: 'destructive'` for an overdue one.
1255
+ Nothing renders for an empty list.
1256
+ - **`Freshness`: how old a number is.** `<Freshness label="Balances entered"
1257
+ at="2026-08-02" staleAfter="2026-11-02" />` reads "Balances entered Aug
1258
+ 2" in caption type and the muted tone, and once `staleAfter` has passed
1259
+ the warning tone with a warning icon and ", out of date" for a screen
1260
+ reader. The app owns the rule (entered plus 90 days); this only compares.
1261
+ A plain `'YYYY-MM-DD'` day is never shifted by the time zone.
1262
+ - **`PartEmpty` and `WidgetCard`'s `empty`: a part with nothing yet.**
1263
+ `empty={{ text?, action }}` draws "Nothing here yet" and one outline
1264
+ button (a link `to`, or `onClick`) in place of the card's plain
1265
+ `emptyMessage` line, the foundation's `Empty` at card size.
1266
+
1267
+ Every one is measured with axe and the glyph check in both themes
1268
+ (fixtures `app/ValueList`, `ListHeader`, `Timeline`, `NeedsYou`,
1269
+ `Freshness`, `PartEmpty`).
1218
1270
  ## A record's header and empty values
1219
1271
 
1220
1272
  The record page standard (4.81): the same header on every record, the
@@ -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,14 @@
1
+ export type FreshnessProps = {
2
+ /** When it was entered or checked; null or '' when it never was. */
3
+ at: Date | string | null | undefined;
4
+ /** The moment it goes stale. Left out, the line is never in the warning tone. */
5
+ staleAfter?: Date | string;
6
+ /** What happened, before the date: "Balances entered", "Prices checked". */
7
+ label: string;
8
+ /** What the line says when `at` is empty. Defaults to "<label>: never". */
9
+ neverText?: string;
10
+ /** The clock, for stories and tests. Defaults to now. */
11
+ now?: Date;
12
+ className?: string;
13
+ };
14
+ export declare function Freshness({ at, staleAfter, label, neverText, now, className }: FreshnessProps): import("react").JSX.Element;
@@ -0,0 +1,25 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // How fresh a number is (overview standard O3): one quiet line under it,
3
+ // "Balances entered Aug 2", in the caption type and the muted tone. Once
4
+ // `staleAfter` has passed it turns to the warning tone and gains a
5
+ // warning icon, so an out-of-date balance never looks current; the line
6
+ // still says when, and a screen reader hears ", out of date".
7
+ //
8
+ // Used in a part's tile and detail and in a WidgetCard's body. The date is
9
+ // a plain day ('YYYY-MM-DD', as the wire writes it, shown without the
10
+ // time zone shifting it) or an instant (a Date, or an ISO timestamp).
11
+ // `staleAfter` is the moment it goes stale, so the app owns the rule
12
+ // (entered + 90 days): this only says whether it has passed. `now` is for
13
+ // stories and tests.
14
+ import { TriangleAlertIcon } from 'lucide-react';
15
+ import { cn } from 'cn';
16
+ import { isStale, showDate } from '../../lib/freshness.js';
17
+ export function Freshness({ at, staleAfter, label, neverText, now = new Date(), className }) {
18
+ const entered = at ? showDate(at, now) : '';
19
+ if (!entered) {
20
+ return (_jsx("span", { "data-slot": "freshness", "data-state": "never", className: cn('type-caption text-muted-foreground', className), children: neverText ?? `${label}: never` }));
21
+ }
22
+ const stale = isStale(staleAfter, now);
23
+ const iso = at instanceof Date ? at.toISOString() : String(at);
24
+ return (_jsxs("span", { "data-slot": "freshness", "data-state": stale ? 'stale' : 'fresh', className: cn('inline-flex items-center gap-1 type-caption', stale ? 'text-warning-text' : 'text-muted-foreground', className), children: [stale && _jsx(TriangleAlertIcon, { "aria-hidden": "true", className: "size-3 shrink-0" }), _jsxs("span", { children: [label, " ", _jsx("time", { dateTime: iso, children: entered }), stale && _jsx("span", { className: "sr-only", children: ", out of date" })] })] }));
25
+ }