@tristan2828/ui-foundation 4.87.0 → 4.88.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 (31) hide show
  1. package/README.md +1 -1
  2. package/conventions/docs/add-an-entity.md +38 -23
  3. package/conventions/docs/cell-patterns.md +49 -24
  4. package/dist/components/app/choice-buttons.d.ts +25 -0
  5. package/dist/components/app/choice-buttons.js +17 -0
  6. package/dist/components/app/date-field.d.ts +28 -9
  7. package/dist/components/app/date-field.js +103 -10
  8. package/dist/components/app/edit-in-place-controls.d.ts +1 -3
  9. package/dist/components/app/edit-in-place-controls.js +4 -58
  10. package/dist/components/app/edit-in-place-presets.d.ts +38 -4
  11. package/dist/components/app/edit-in-place-presets.js +48 -27
  12. package/dist/components/app/edit-row.d.ts +7 -0
  13. package/dist/components/app/edit-row.js +23 -0
  14. package/dist/components/app/editable-value.d.ts +8 -1
  15. package/dist/components/app/editable-value.js +36 -4
  16. package/dist/components/app/entity-view.js +5 -1
  17. package/dist/components/app/multi-pick.d.ts +8 -1
  18. package/dist/components/app/multi-pick.js +19 -5
  19. package/dist/components/app/multi-reference.d.ts +8 -1
  20. package/dist/components/app/multi-reference.js +44 -6
  21. package/dist/components/app/reference-combobox.d.ts +37 -0
  22. package/dist/components/app/reference-combobox.js +96 -0
  23. package/dist/components/ui/field.d.ts +2 -2
  24. package/dist/components/ui/field.js +2 -1
  25. package/dist/index.d.ts +4 -1
  26. package/dist/index.js +4 -1
  27. package/dist/lib/names-record.d.ts +4 -0
  28. package/dist/lib/names-record.js +7 -0
  29. package/dist/lib/plain-date.d.ts +20 -0
  30. package/dist/lib/plain-date.js +72 -0
  31. package/package.json +1 -1
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 a list's tools (`docs/foundation/cell-patterns.md` 25 and 26): `FilterBar`, `FilterSelect`, `RelatedTable`, and DataTable's `views`, `columnsMenu`, `rowActions`, `phoneRow`, `limit` and `viewAll`. 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 trail and search in `AppShell`'s bar (`docs/foundation/design-language.md` "The sidebar and the phone's bar"): `usePageTrail`, `useRecentRecord`, `PageTrail`; types `AppShellSearch`, `SearchRecord`, `RecentRecord`. 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 |
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 a list's tools (`docs/foundation/cell-patterns.md` 25 and 26): `FilterBar`, `FilterSelect`, `RelatedTable`, and DataTable's `views`, `columnsMenu`, `rowActions`, `phoneRow`, `limit` and `viewAll`. 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 trail and search in `AppShell`'s bar (`docs/foundation/design-language.md` "The sidebar and the phone's bar"): `usePageTrail`, `useRecentRecord`, `PageTrail`; types `AppShellSearch`, `SearchRecord`, `RecentRecord`. For the form standard (`docs/foundation/add-an-entity.md` "Forms"): `FormSection`, `OptionSelect`, `ChoiceButtons`, `ReferenceCombobox`, `countFormErrors`, `fieldRows`, `parsePlainDate`, and for a record's rows edited in place `editRowClass`, `onEditRowClick` and `inPlace.choice`; 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` |
@@ -4,27 +4,27 @@
4
4
  ## Index
5
5
 
6
6
  - [The reference files](#the-reference-files) · lines 43–65
7
- - [Before anything: the entity plan](#before-anything-the-entity-plan) · lines 67–826
7
+ - [Before anything: the entity plan](#before-anything-the-entity-plan) · lines 67–830
8
8
  - Step 1: Add `<Entity>` to `openapi.yaml` · lines 109–116
9
9
  - Step 2: `npm run gen:api` · lines 117–118
10
10
  - Step 3: Add gateway tests in `tests/gateway/<entity>.test.ts`, derived from the spec · lines 119–130
11
11
  - Step 4: Add MSW handlers in `src/mocks/<entity>.ts` · lines 131–140
12
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–713
14
- - Step 7: Register routes · lines 714–729
15
- - Step 8: Add Playwright specs for all three screens · lines 730–808
16
- - Step 9: Register the nav entry and route names · lines 809–823
17
- - Step 10: `npm run verify`. · lines 824–826
18
- - [How a list opens a record](#how-a-list-opens-a-record) · lines 828–1086
19
- - [The record view](#the-record-view) · lines 977–1016
20
- - [Forms](#forms) · lines 1018–1059
21
- - [Dialogs](#dialogs) · lines 1061–1086
22
- - [What not to copy](#what-not-to-copy) · lines 1088–1114
23
- - [After a commit, in the backend](#after-a-commit-in-the-backend) · lines 1116–1133
24
- - [Deleting](#deleting) · lines 1135–1164
25
- - [Fields only a script writes](#fields-only-a-script-writes) · lines 1166–1187
26
- - [Searching one part of the app](#searching-one-part-of-the-app) · lines 1189–1198
27
- - [What a chat is told about an entity](#what-a-chat-is-told-about-an-entity) · lines 1201–1240
13
+ - Step 6: Copy the reference files, one for one, not just the two screens · lines 146–717
14
+ - Step 7: Register routes · lines 718–733
15
+ - Step 8: Add Playwright specs for all three screens · lines 734–812
16
+ - Step 9: Register the nav entry and route names · lines 813–827
17
+ - Step 10: `npm run verify`. · lines 828–830
18
+ - [How a list opens a record](#how-a-list-opens-a-record) · lines 832–1101
19
+ - [The record view](#the-record-view) · lines 981–1020
20
+ - [Forms](#forms) · lines 1022–1074
21
+ - [Dialogs](#dialogs) · lines 1076–1101
22
+ - [What not to copy](#what-not-to-copy) · lines 1103–1129
23
+ - [After a commit, in the backend](#after-a-commit-in-the-backend) · lines 1131–1148
24
+ - [Deleting](#deleting) · lines 1150–1179
25
+ - [Fields only a script writes](#fields-only-a-script-writes) · lines 1181–1202
26
+ - [Searching one part of the app](#searching-one-part-of-the-app) · lines 1204–1213
27
+ - [What a chat is told about an entity](#what-a-chat-is-told-about-an-entity) · lines 1216–1255
28
28
 
29
29
  <!-- /index -->
30
30
 
@@ -220,11 +220,15 @@ is a filled-in example while the Widgets demo is still here).
220
220
  it's the foundation's `DateField` in a `Controller` (`clearable` when
221
221
  optional); the schema is the string (`z.string().min(1, …)` when
222
222
  required). The table and the view show `formatPlainDate(value)`
223
- ("Sep 2, 2026"), the not-set label when empty. Editing in place is
224
- `editInPlace({ kind: 'choice', ... })` with `DateField` as the
225
- control, `defaultOpen`, `modal={false}`, `onChange={(day) =>
226
- props.commit(day)}` and `onOpenChange` cancelling on close, as a
227
- Select is (the fixtures' `app/DateField` EditInPlace). The backend column
223
+ ("Sep 2, 2026"), the not-set label when empty. `DateField` is typed
224
+ (4.88): a box that reads "3/14", "Mar 14", "2026-03-14" or "today",
225
+ with the calendar on its button, and something unreadable says "Try a
226
+ date like 3/14 or Mar 14" and gives `''`. Editing in place is
227
+ `inPlace.date({ value, save })`: Enter or leaving saves the day typed,
228
+ a day picked in the calendar saves at once. (`typing={false}` is the
229
+ button alone; in place then `editInPlace({ kind: 'choice', ... })` with
230
+ `defaultOpen`, `modal={false}` and `onChange={(day) => props.commit(day)}`,
231
+ the fixtures' `app/DateField` EditInPlace.) The backend column
228
232
  is a SQL `date` (`datetime.date` in the model).
229
233
 
230
234
  **A `month-day`** (a day that comes round every year, with no year:
@@ -1029,8 +1033,8 @@ shape (4.85):
1029
1033
  fields share a row, up to three, as wide as their sizes; a long one
1030
1034
  takes one short partner (Series and Number). `<Field solo>` keeps a
1031
1035
  short one alone where a pairing would read wrong. Under 48rem every
1032
- field takes its own row but two dates or two numbers (a date picker of
1033
- your own says so with `kind="date"`). Never a hand-made
1036
+ field takes its own row but two dates or two numbers (`DateField` says
1037
+ so itself; a date picker of your own with `kind="date"`). Never a hand-made
1034
1038
  `sm:grid-cols-2` row.
1035
1039
  - **Order:** required first, the status next, long text last.
1036
1040
  - **Required:** `<FieldLabel required>` (an asterisk, and `aria-required`
@@ -1044,6 +1048,17 @@ shape (4.85):
1044
1048
  "Enter a full address, starting https://", never "Title is required".
1045
1049
  - **A status** is an `OptionSelect` with the same `render` (its badge) as
1046
1050
  its cell and the record: `inPlace.select`'s `{ value, label }` options.
1051
+ - **The controls** (4.88): a choice of two to four short options is
1052
+ `ChoiceButtons` (`inPlace.choice` in place), five or more an
1053
+ `OptionSelect`. A date is `DateField`, typed ("3/14", "Mar 14",
1054
+ "today") with the calendar on its button. A single reference is
1055
+ `ReferenceCombobox` (`inPlace.reference` in place), several are
1056
+ `MultiReference`, and a set the app loads whole (tags, a few dozen
1057
+ records from its list query) is `MultiPick`, whose chips wrap and which
1058
+ shows 30 before "Show all". Where a missing record stops the form, give
1059
+ the reference `onCreate(name)`: open the other entity's `FormDialog`
1060
+ with the name filled in, and resolve with the record it saves (or
1061
+ `null` on Cancel).
1047
1062
  - **Cards** (`<FormSection title>`) only on a form of eight fields or
1048
1063
  more, never in a dialog; a short form is one run of fields. Sub-record
1049
1064
  editors (`ListEditor`) sit in a card of their own.
@@ -26,22 +26,22 @@
26
26
  - [A variant: a pressed icon inside another value's cell](#a-variant-a-pressed-icon-inside-another-values-cell) · lines 618–701
27
27
  - [16. Title linking to the record's view](#16-title-linking-to-the-records-view) · lines 703–738
28
28
  - [17. Quick action on the view](#17-quick-action-on-the-view) · lines 740–813
29
- - [18. Editable value](#18-editable-value) · lines 815–1458
30
- - [Presets: one line per field](#presets-one-line-per-field) · lines 1100–1158
31
- - [Several fields edited as one](#several-fields-edited-as-one) · lines 1160–1196
32
- - [A link and its label](#a-link-and-its-label) · lines 1198–1222
33
- - [A list of sub-items](#a-list-of-sub-items) · lines 1224–1357
34
- - [In a table's rows](#in-a-tables-rows) · lines 1359–1444
35
- - [A table of a few short columns: `width="content"`](#a-table-of-a-few-short-columns-widthcontent) · lines 1446–1458
36
- - [19. Stage circle for an ordered status](#19-stage-circle-for-an-ordered-status) · lines 1460–1526
37
- - [20. Count linking to the related records](#20-count-linking-to-the-related-records) · lines 1528–1592
38
- - [21. Rows grouped under headings, and a pill filter](#21-rows-grouped-under-headings-and-a-pill-filter) · lines 1594–1692
39
- - [22. A highlighted row, and rows that are done](#22-a-highlighted-row-and-rows-that-are-done) · lines 1694–1723
40
- - [24. A list's rows: hover, lines, rows per page](#24-a-lists-rows-hover-lines-rows-per-page) · lines 1725–1763
41
- - [23. A Group menu, and a record read beside the list](#23-a-group-menu-and-a-record-read-beside-the-list) · lines 1765–1841
42
- - [24. A stored colour beside its name](#24-a-stored-colour-beside-its-name) · lines 1843–1866
43
- - [25. A list's tools: views, filters, columns, row actions, a phone's rows](#25-a-lists-tools-views-filters-columns-row-actions-a-phones-rows) · lines 1868–1954
44
- - [26. A record's related list, capped](#26-a-records-related-list-capped) · lines 1956–1992
29
+ - [18. Editable value](#18-editable-value) · lines 815–1483
30
+ - [Presets: one line per field](#presets-one-line-per-field) · lines 1115–1183
31
+ - [Several fields edited as one](#several-fields-edited-as-one) · lines 1185–1221
32
+ - [A link and its label](#a-link-and-its-label) · lines 1223–1247
33
+ - [A list of sub-items](#a-list-of-sub-items) · lines 1249–1382
34
+ - [In a table's rows](#in-a-tables-rows) · lines 1384–1469
35
+ - [A table of a few short columns: `width="content"`](#a-table-of-a-few-short-columns-widthcontent) · lines 1471–1483
36
+ - [19. Stage circle for an ordered status](#19-stage-circle-for-an-ordered-status) · lines 1485–1551
37
+ - [20. Count linking to the related records](#20-count-linking-to-the-related-records) · lines 1553–1617
38
+ - [21. Rows grouped under headings, and a pill filter](#21-rows-grouped-under-headings-and-a-pill-filter) · lines 1619–1717
39
+ - [22. A highlighted row, and rows that are done](#22-a-highlighted-row-and-rows-that-are-done) · lines 1719–1748
40
+ - [24. A list's rows: hover, lines, rows per page](#24-a-lists-rows-hover-lines-rows-per-page) · lines 1750–1788
41
+ - [23. A Group menu, and a record read beside the list](#23-a-group-menu-and-a-record-read-beside-the-list) · lines 1790–1866
42
+ - [24. A stored colour beside its name](#24-a-stored-colour-beside-its-name) · lines 1868–1891
43
+ - [25. A list's tools: views, filters, columns, row actions, a phone's rows](#25-a-lists-tools-views-filters-columns-row-actions-a-phones-rows) · lines 1893–1979
44
+ - [26. A record's related list, capped](#26-a-records-related-list-capped) · lines 1981–2017
45
45
 
46
46
  <!-- /index -->
47
47
 
@@ -845,6 +845,16 @@ touch screen the pencil always shows. A click anywhere on the value opens it, ex
845
845
  link inside it (a reference to a record with a view, a link in the
846
846
  notes), which still navigates.
847
847
 
848
+ **In a field list, the row is the target** (4.88, `look="row"`, which
849
+ EntityView's field rows use). The row wears the list's row hover, the
850
+ `--table-hover` tint and the 3px `--primary` bar at its start, as a
851
+ DataTable row does, with its label readable on it and the pencil at its
852
+ end; a click anywhere on the row (its label too) opens the value. Under
853
+ 48rem or on a touch screen there's no pencil but a chevron, and the row
854
+ is 44px tall at least; the control still opens in the row. The header's
855
+ strip and the title keep the value-sized tint above. A field list of the
856
+ app's own gets the same with `editRowClass` and `onEditRowClick` on its row.
857
+
848
858
  **Open: the form's control, nothing else.** The same labels, choices and
849
859
  pickers as `EntityForm`; the field's label is its accessible name. No
850
860
  Save button, no Undo:
@@ -868,9 +878,13 @@ multi field whose options are few (up to about 25) and all loaded (a
868
878
  dozen labels, a short tag list) uses `MultiPick` instead, on the form
869
879
  and in place: every option a toggle chip with its icon or colour where
870
880
  the app draws one (`icon`), the picked ones pressed with a check, and a
871
- filter box above them, not in front of them. Larger sets, or ones that
872
- grow with the data, keep `MultiReference` (typing searches the server)
873
- or `MultiChoice`.
881
+ filter box above them, not in front of them. The chips wrap at every
882
+ width (4.88); past 30 options (`limit`) it shows the picked ones and the
883
+ first 30, then "Show all N", and a filter searches them all. The options
884
+ can be the app's list of records (its query's rows as `{ id, label }`,
885
+ `loading` meanwhile), so links to a few dozen other records use it too.
886
+ Larger sets, or ones that grow with the data, keep `MultiReference`
887
+ (typing searches the server) or `MultiChoice`.
874
888
 
875
889
  - **The plan says which**, by marking the field `small`; the control
876
890
  isn't switched by option count. The two save differently in place
@@ -924,7 +938,8 @@ open.
924
938
 
925
939
  **Saving: still open, read-only, and says so.** Under the control,
926
940
  "Saving…" with a spinner (`role="status"`) until the server agrees, then
927
- it closes on the saved value. **Not optimistic**: the value only shows as
941
+ it closes on the saved value, with "✓ Saved" beside it for two seconds
942
+ (4.88, `role="status"`). **Not optimistic**: the value only shows as
928
943
  saved once it is, and the view shows the record the server returned (a
929
944
  side effect included). The rest of the page stays usable.
930
945
 
@@ -1115,11 +1130,13 @@ fields: [
1115
1130
  { label: 'Budget', edit: inPlace.money({ value: project.budget, save: (budget) => save({ budget }) }) },
1116
1131
  { label: 'Due', edit: inPlace.date({ value: project.due, required: true, save: (due) => save({ due }) }) },
1117
1132
  { label: 'Renews on', edit: inPlace.monthDay({ value: project.renewsOn, save: (renewsOn) => save({ renewsOn }) }) },
1133
+ { label: 'Format', edit: inPlace.choice({ value: project.format, options: FORMAT_OPTIONS, save: (format) => save({ format }) }) },
1118
1134
  { label: 'Priority', edit: inPlace.select({ value: project.priority, options: PRIORITY_OPTIONS,
1119
1135
  render: (priority, label) => <Badge variant={PRIORITY_BADGE[priority]}>{label}</Badge>,
1120
1136
  save: (priority) => save({ priority }) }) },
1121
1137
  { label: 'Category', edit: inPlace.reference({ value: project.categoryId, label: categoryName,
1122
- search: (text) => searchCategories(text), save: (categoryId) => save({ categoryId }) }) },
1138
+ search: (text) => searchCategories(text), onCreate: (name) => openNewCategory(name),
1139
+ save: (categoryId) => save({ categoryId }) }) },
1123
1140
  ]
1124
1141
  // The title: <EntityView titleEdit={{ label: 'Name', ...inPlace.text({ value: project.name, required: true, save: … }) }} />
1125
1142
  // A badge: <EditableValue label="Priority" edit={priority} layout="inline" /> (its children default to the preset's look)
@@ -1136,20 +1153,28 @@ fields: [
1136
1153
  | `text` | the text | it trimmed; blank is `null` | blank when `required`, past `maxLength` |
1137
1154
  | `number` | `1,234 h` (`unit`) | a number; blank is `null` | not a number, under `min`, over `max`, a fraction with `integer` |
1138
1155
  | `money` | `$1,234.56` (`currency`, `locale`) | the API's decimal string, two places (`"1234.50"`), built from the digits, never a float; `$` and commas typed are fine | a third decimal, words, under `min` (0 by default), over `max` |
1139
- | `date` | `Sep 2, 2026` | `'YYYY-MM-DD'`; Clear is `null` | Clear when `required` |
1156
+ | `date` | `Sep 2, 2026` | `'YYYY-MM-DD'`, typed ("3/14", "Mar 14", "today") or picked; an empty box or Clear is `null` | empty when `required`; what it can't read ("Try a date like 3/14 or Mar 14", nothing sent) |
1140
1157
  | `monthDay` | `Mar 14` (`format`, `locale`); a stored value that isn't a day, as written | `'MM-DD'`, no year; February 29 is a day; Clear is `null` | Clear when `required`, a day the month can't have ("February has 29 days") |
1141
1158
  | `select` | the option's label, or its `render` (a badge) | the option's value; "Not set" is `null` | "Not set" isn't offered when `required` |
1159
+ | `choice` | as `select` | as `select`, drawn as ChoiceButtons (two to four short options); pressing the picked one again is `null` | as `select` |
1142
1160
  | `reference` | the record's `label` (the view's lookup by id) | the picked record's id | "Not set" isn't offered when `required` |
1143
1161
 
1144
1162
  - **They save the way their kind does** (the table above): `text`,
1145
- `number` and `money` on Enter or leaving them, `date`, `monthDay`,
1146
- `select` and `reference` on the pick (the list opens with the field).
1163
+ `number`, `money` and a typed `date` on Enter or leaving them, a day
1164
+ picked in the date's calendar, `monthDay`, `select`, `choice` and
1165
+ `reference` on the pick (a list opens with the field).
1147
1166
  `required: true` types the save without `null`.
1148
1167
  - **`reference` searches through the app.** The package knows no
1149
1168
  endpoint: `search(text)` is the app's (its gateway's search by name,
1150
1169
  `''` when the list opens), called a pause after typing stops; a
1151
1170
  rejection reads as nothing found. Names come from the searches and from
1152
1171
  `label`, so the saved record's name shows before any search answers.
1172
+ With `onCreate(name)`, Create "name" ends the list when what's typed
1173
+ names no record: the app opens the other entity's `FormDialog` with the
1174
+ name filled in and resolves with the record it saves (`null` on
1175
+ Cancel); the field stays open meanwhile and saves the new record's id.
1176
+ The form's control is the same `ReferenceCombobox`; `MultiReference`
1177
+ takes the same `onCreate`.
1153
1178
  - **Keep the app's own control when it has one.** A field whose control
1154
1179
  is the form's own (a rich-text editor, a multi picker, an icon select,
1155
1180
  anything in `<entity>-fields.tsx` beyond a plain box) stays
@@ -0,0 +1,25 @@
1
+ import type { ReactNode } from 'react';
2
+ export type ChoiceButtonsOption<T> = {
3
+ value: T;
4
+ label: string;
5
+ };
6
+ export type ChoiceButtonsProps<T extends string | number> = {
7
+ /** The group's id. Name it with `aria-labelledby` (the FieldLabel's id) or `aria-label`. */
8
+ id?: string;
9
+ /** Two to four short options, in the order they read. */
10
+ options: readonly ChoiceButtonsOption<T>[];
11
+ /** The picked one, or `null` for none. */
12
+ value: T | null;
13
+ onValueChange: (value: T | null) => void;
14
+ /** How an option reads on its button. Defaults to its label. */
15
+ render?: (value: T, label: string) => ReactNode;
16
+ /** Pressing the picked one again unpicks it (`null`): an optional field. */
17
+ clearable?: boolean;
18
+ invalid?: boolean;
19
+ disabled?: boolean;
20
+ className?: string;
21
+ 'aria-label'?: string;
22
+ 'aria-labelledby'?: string;
23
+ 'aria-describedby'?: string;
24
+ };
25
+ export declare function ChoiceButtons<T extends string | number>({ id, options, value, onValueChange, render, clearable, invalid, disabled, className, ...aria }: ChoiceButtonsProps<T>): import("react").JSX.Element;
@@ -0,0 +1,17 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { cn } from 'cn';
3
+ import { ToggleGroup, ToggleGroupItem } from '../ui/toggle-group.js';
4
+ export function ChoiceButtons({ id, options, value, onValueChange, render, clearable = false, invalid = false, disabled = false, className, ...aria }) {
5
+ const at = value == null ? -1 : options.findIndex((option) => option.value === value);
6
+ return (_jsx(ToggleGroup, { id: id, "data-slot": "choice-buttons", variant: "outline", spacing: 0, value: at === -1 ? [] : [String(at)], onValueChange: (next) => {
7
+ const key = next[0];
8
+ if (key === undefined) {
9
+ if (clearable)
10
+ onValueChange(null);
11
+ return;
12
+ }
13
+ const option = options[Number(key)];
14
+ if (option && option.value !== value)
15
+ onValueChange(option.value);
16
+ }, disabled: disabled, "aria-invalid": invalid || undefined, className: cn('max-w-full flex-wrap rounded-md aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40', className), ...aria, children: options.map((option, index) => (_jsx(ToggleGroupItem, { value: String(index), className: cn('h-(--control-height,--spacing(8)) px-3 font-normal text-muted-foreground aria-pressed:font-medium aria-pressed:text-foreground', invalid && 'border-destructive'), children: render ? render(option.value, option.label) : option.label }, String(option.value)))) }));
17
+ }
@@ -1,26 +1,45 @@
1
1
  import { type PlainDate } from '../../lib/plain-date.js';
2
2
  export type DateFieldProps = {
3
- /** The trigger button's id, for the field's `<FieldLabel htmlFor>`. */
3
+ /** The box's id (the button's with `typing={false}`), for the field's `<FieldLabel htmlFor>`. */
4
4
  id?: string;
5
5
  /** `'YYYY-MM-DD'`, or `''` for not set. */
6
6
  value: PlainDate;
7
- /** Called with the picked day as `'YYYY-MM-DD'`, or `''` when cleared. */
7
+ /**
8
+ * Called with the day as `'YYYY-MM-DD'`, or `''` when cleared or when
9
+ * what's typed can't be read.
10
+ */
8
11
  onChange: (value: PlainDate) => void;
9
- /** What the button says with no day set. Defaults to "Pick a date". */
12
+ /**
13
+ * A box to type the day in, with the calendar on its button (the
14
+ * default). `false`: the button alone, opening the calendar.
15
+ */
16
+ typing?: boolean;
17
+ /**
18
+ * A day picked in the calendar, when that should do more than a typed
19
+ * one does (editing in place saves it at once). Defaults to `onChange`.
20
+ */
21
+ onPick?: (value: PlainDate) => void;
22
+ /**
23
+ * Told when what's typed can't be read (with its message), and `null`
24
+ * once it can: editing in place gives it to `onProblem`, so the field
25
+ * won't save a day nobody meant.
26
+ */
27
+ onProblem?: (message: string | null) => void;
28
+ /** The empty box's words. Defaults to "3/14 or Mar 14" typed (the locale's order), "Pick a date" on the button. */
10
29
  placeholder?: string;
11
30
  /** Offer Clear in the calendar, for an optional field. */
12
31
  clearable?: boolean;
13
- /** The value was refused: `aria-invalid` on the button. */
32
+ /** The value was refused: `aria-invalid` on the box (or button). */
14
33
  invalid?: boolean;
15
- /** Saving: the button shows the day but won't open. */
34
+ /** Saving: the day shows but can't change. */
16
35
  readOnly?: boolean;
17
- /** Open on mount: editing in place, where the calendar opens with the field. */
36
+ /** Open the calendar on mount (the button's way of editing in place). */
18
37
  defaultOpen?: boolean;
19
38
  /** Passed to the Popover; `false` when editing in place, as for a Select. */
20
39
  modal?: boolean;
21
- /** Told when the calendar opens or closes; editing in place gives up on a close with nothing picked. */
40
+ /** Told when the calendar opens or closes. */
22
41
  onOpenChange?: (open: boolean) => void;
23
- /** How the day is shown on the button. Defaults to `{ dateStyle: 'medium' }`. */
42
+ /** How the day is shown. Defaults to `{ dateStyle: 'medium' }`. */
24
43
  format?: Intl.DateTimeFormatOptions;
25
44
  locale?: string;
26
45
  className?: string;
@@ -28,4 +47,4 @@ export type DateFieldProps = {
28
47
  'aria-labelledby'?: string;
29
48
  'aria-describedby'?: string;
30
49
  };
31
- export declare function DateField({ id, value, onChange, placeholder, clearable, invalid, readOnly, defaultOpen, modal, onOpenChange, format, locale, className, ...aria }: DateFieldProps): import("react").JSX.Element;
50
+ export declare function DateField({ typing, onProblem, ...props }: DateFieldProps): import("react").JSX.Element;
@@ -4,19 +4,111 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
4
4
  // not set, and it's read as a calendar day, never an instant: nothing here
5
5
  // goes through the browser's time zone, so Sep 2 is Sep 2 everywhere.
6
6
  //
7
- // A button showing the day, opening the package's Calendar in a Popover.
8
- // One control for the form (a react-hook-form `Controller`) and for
9
- // editing in place (`editInPlace({ kind: 'choice' })`: picking a day saves,
10
- // and the calendar opens with the field). `clearable` adds Clear for an
11
- // optional field.
12
- import { useRef, useState } from 'react';
7
+ // Typed (the default, 4.88's F12): a box that reads "3/14", "Mar 14",
8
+ // "2026-03-14" or "today" (`parsePlainDate`), with the package's Calendar
9
+ // on its button. Something it can't read says "Try a date like 3/14 or
10
+ // Mar 14" under the box once it's left, and gives `''`, so a form never
11
+ // keeps the day it had before. `typing={false}` is the button alone,
12
+ // opening the calendar in a Popover. One control for the form (a
13
+ // react-hook-form `Controller`) and for editing in place (`inPlace.date`).
14
+ // `clearable` adds Clear to the calendar for an optional field. Either way
15
+ // the control carries `data-kind="date"`, so two dates keep sharing a row
16
+ // on a phone without their Field saying `kind="date"`.
17
+ import { useId, useRef, useState } from 'react';
13
18
  import { CalendarIcon } from 'lucide-react';
14
19
  import { cn } from 'cn';
15
20
  import { Button } from '../ui/button.js';
16
21
  import { Calendar } from '../ui/calendar.js';
22
+ import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from '../ui/input-group.js';
17
23
  import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover.js';
18
- import { formatPlainDate, localToPlainDate, plainDateToLocal } from '../../lib/plain-date.js';
19
- export function DateField({ id, value, onChange, placeholder = 'Pick a date', clearable = false, invalid = false, readOnly = false, defaultOpen = false, modal, onOpenChange, format, locale, className, ...aria }) {
24
+ import { formatPlainDate, localToPlainDate, parsePlainDate, plainDateExamples, plainDateToLocal, unreadableDateMessage, } from '../../lib/plain-date.js';
25
+ export function DateField({ typing = true, onProblem, ...props }) {
26
+ return typing ? _jsx(TypedDate, { ...props, onProblem: onProblem }) : _jsx(DateButton, { ...props });
27
+ }
28
+ function TypedDate({ id, value, onChange, onPick, onProblem, placeholder, clearable = false, invalid = false, readOnly = false, defaultOpen = false, modal, onOpenChange, format, locale, className, 'aria-describedby': describedBy, ...aria }) {
29
+ const messageId = useId();
30
+ const [open, setOpen] = useState(defaultOpen && !readOnly);
31
+ const box = useRef(null);
32
+ const group = useRef(null);
33
+ const popup = useRef(null);
34
+ const shown = (day) => formatPlainDate(day, format, locale);
35
+ const [text, setText] = useState(() => shown(value));
36
+ // What's typed can't be read: its message, shown once the box is left (or on Enter).
37
+ const [problem, setProblem] = useState(null);
38
+ const [told, setTold] = useState(false);
39
+ // The value this box last gave. Any other came from outside (the record
40
+ // saved elsewhere, a reset form) and replaces what's typed.
41
+ const [given, setGiven] = useState(value);
42
+ if (value !== given) {
43
+ setGiven(value);
44
+ setText(shown(value));
45
+ setProblem(null);
46
+ setTold(false);
47
+ }
48
+ const report = (next) => {
49
+ if (next !== problem)
50
+ onProblem?.(next);
51
+ setProblem(next);
52
+ };
53
+ const give = (day) => {
54
+ setGiven(day);
55
+ if (day !== value)
56
+ onChange(day);
57
+ };
58
+ const type = (typed) => {
59
+ setText(typed);
60
+ setTold(false);
61
+ const day = parsePlainDate(typed, { locale });
62
+ if (day === null) {
63
+ report(unreadableDateMessage(locale));
64
+ give('');
65
+ }
66
+ else {
67
+ report(null);
68
+ give(day);
69
+ }
70
+ };
71
+ // Leaving the box (or Enter): a day it read reads back the way it's shown.
72
+ const settle = () => {
73
+ if (problem)
74
+ setTold(true);
75
+ else
76
+ setText(shown(given));
77
+ };
78
+ const changeOpen = (next) => {
79
+ if (next && readOnly)
80
+ return;
81
+ setOpen(next);
82
+ onOpenChange?.(next);
83
+ };
84
+ const pick = (day) => {
85
+ setGiven(day);
86
+ setText(shown(day));
87
+ report(null);
88
+ setTold(false);
89
+ changeOpen(false);
90
+ (onPick ?? onChange)(day);
91
+ };
92
+ const onKeyDown = (event) => {
93
+ if (event.key === 'Enter')
94
+ settle();
95
+ // Alt+Down opens the calendar, as it opens a select's list.
96
+ if (event.key === 'ArrowDown' && event.altKey) {
97
+ event.preventDefault();
98
+ changeOpen(true);
99
+ }
100
+ };
101
+ const selected = plainDateToLocal(given);
102
+ const showProblem = told && problem !== null;
103
+ return (_jsxs("div", { "data-slot": "date-field", "data-kind": "date", className: cn('flex w-full min-w-0 flex-col gap-1.5', className), children: [_jsxs(InputGroup, { ref: group, children: [_jsx(InputGroupInput, { ref: box, id: id, value: text, onChange: (event) => type(event.target.value), onBlur: settle, onKeyDown: onKeyDown, placeholder: placeholder ?? plainDateExamples(locale), readOnly: readOnly, autoComplete: "off", "aria-invalid": invalid || showProblem || undefined, "aria-describedby": [showProblem ? messageId : null, describedBy].filter(Boolean).join(' ') || undefined, ...aria }), _jsx(InputGroupAddon, { align: "inline-end", children: _jsxs(Popover, { open: open, onOpenChange: changeOpen, modal: modal, children: [_jsx(PopoverTrigger, { render: _jsx(InputGroupButton, { type: "button", size: "icon-xs", variant: "ghost", disabled: readOnly, "aria-label": "Open calendar" }), children: _jsx(CalendarIcon, { "aria-hidden": "true" }) }), _jsxs(PopoverContent, { ref: popup, anchor: group, align: "start", className: "w-auto p-0", "data-slot": "date-field-calendar",
104
+ // The day the keyboard starts from (the chosen one, else today).
105
+ initialFocus: () => popup.current?.querySelector('button[data-day][tabindex="0"]') ?? true,
106
+ // Back to the box, where typing goes on.
107
+ finalFocus: box, children: [_jsx(Calendar, { mode: "single",
108
+ // Picking the chosen day again keeps it (and closes), never unsets it: Clear does that.
109
+ required: true, selected: selected, defaultMonth: selected, onSelect: (date) => pick(localToPlainDate(date)) }), clearable && given && (_jsx("div", { className: "border-t border-border p-2", children: _jsx(Button, { type: "button", variant: "ghost", size: "sm", className: "w-full", onClick: () => pick(''), children: "Clear" }) }))] })] }) })] }), showProblem && (_jsx("p", { id: messageId, "data-slot": "date-field-problem", className: "type-caption text-destructive-text", children: problem }))] }));
110
+ }
111
+ function DateButton({ id, value, onChange, onPick, placeholder = 'Pick a date', clearable = false, invalid = false, readOnly = false, defaultOpen = false, modal, onOpenChange, format, locale, className, ...aria }) {
20
112
  const [open, setOpen] = useState(defaultOpen && !readOnly);
21
113
  const popup = useRef(null);
22
114
  const selected = plainDateToLocal(value);
@@ -28,10 +120,11 @@ export function DateField({ id, value, onChange, placeholder = 'Pick a date', cl
28
120
  onOpenChange?.(next);
29
121
  };
30
122
  const pick = (next) => {
31
- onChange(next);
123
+ ;
124
+ (onPick ?? onChange)(next);
32
125
  changeOpen(false);
33
126
  };
34
- return (_jsxs(Popover, { open: open, onOpenChange: changeOpen, modal: modal, children: [_jsxs(PopoverTrigger, { render: _jsx(Button, { id: id, type: "button", variant: "outline", "aria-invalid": invalid || undefined, "aria-readonly": readOnly || undefined, className: cn('w-full justify-start font-normal', !shown && 'text-muted-foreground', className), ...aria }), children: [_jsx(CalendarIcon, { "aria-hidden": "true", className: "size-4" }), shown || placeholder] }), _jsxs(PopoverContent, { ref: popup, className: "w-auto p-0", "data-slot": "date-field-calendar",
127
+ return (_jsxs(Popover, { open: open, onOpenChange: changeOpen, modal: modal, children: [_jsxs(PopoverTrigger, { render: _jsx(Button, { id: id, type: "button", variant: "outline", "data-kind": "date", "aria-invalid": invalid || undefined, "aria-readonly": readOnly || undefined, className: cn('w-full justify-start font-normal', !shown && 'text-muted-foreground', className), ...aria }), children: [_jsx(CalendarIcon, { "aria-hidden": "true", className: "size-4" }), shown || placeholder] }), _jsxs(PopoverContent, { ref: popup, className: "w-auto p-0", "data-slot": "date-field-calendar",
35
128
  // The day the keyboard starts from (the chosen one, else today):
36
129
  // the one day react-day-picker makes tabbable. The popup would
37
130
  // otherwise take focus itself, past the Calendar's autoFocus.
@@ -1,4 +1,4 @@
1
- import { type ReactNode } from 'react';
1
+ import type { ReactNode } from 'react';
2
2
  import type { EditControlProps, EditKind } from './edit-in-place.js';
3
3
  import type { InPlacePart, InPlaceReferenceConfig } from './edit-in-place-presets.js';
4
4
  export type Checked<TValue> = {
@@ -16,8 +16,6 @@ export type Kind<TValue, TDraft> = {
16
16
  control: (props: EditControlProps<TDraft>, alone: boolean) => ReactNode;
17
17
  };
18
18
  export type AnyKind = Kind<any, any>;
19
- /** A select's and a combobox's items are strings: the option's position, or this for "Not set". */
20
- export declare const NONE = "none";
21
19
  type ReferencePickerProps<Id extends string | number> = {
22
20
  props: EditControlProps<Id | null>;
23
21
  alone: boolean;
@@ -1,12 +1,6 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- // The controls behind the `inPlace` presets that hold state or lay out
3
- // several parts (edit-in-place-presets.tsx), kept in a file of their own
4
- // so the presets' file exports no components.
5
- import { useEffect, useRef, useState } from 'react';
6
- import { Combobox, ComboboxContent, ComboboxEmpty, ComboboxInput, ComboboxItem, ComboboxList } from '../ui/combobox.js';
7
2
  import { FieldError } from '../ui/field.js';
8
- /** A select's and a combobox's items are strings: the option's position, or this for "Not set". */
9
- export const NONE = 'none';
3
+ import { ReferenceCombobox } from './reference-combobox.js';
10
4
  function controlAria(props) {
11
5
  return {
12
6
  'aria-label': props.label,
@@ -14,58 +8,10 @@ function controlAria(props) {
14
8
  'aria-invalid': props.invalid || undefined,
15
9
  };
16
10
  }
17
- // How long typing pauses before the search runs.
18
- const SEARCH_DELAY_MS = 200;
19
- // The reference's combobox: what's typed searches (through the app's
20
- // `search`), a pick is the record's id. Names come from the searches and
21
- // from the saved record's `label`, so a pick the current search no longer
22
- // returns still shows its name.
11
+ // The reference's combobox (ReferenceCombobox, the form's): alone, its
12
+ // list opens with the field and a pick (or a record created from it) saves.
23
13
  export function ReferencePicker({ props, alone, config }) {
24
- const [text, setText] = useState('');
25
- const [found, setFound] = useState([]);
26
- const [names] = useState(() => new Map());
27
- if (props.value != null && config.label !== undefined && !names.has(String(props.value)))
28
- names.set(String(props.value), { id: props.value, label: config.label });
29
- for (const record of found)
30
- names.set(String(record.id), record);
31
- // The search is the app's, often a new function each render: the
32
- // latest is called, and only what's typed starts a search.
33
- const search = useRef(config.search);
34
- useEffect(() => {
35
- search.current = config.search;
36
- });
37
- useEffect(() => {
38
- let live = true;
39
- const timer = setTimeout(() => {
40
- search.current(text).then((records) => {
41
- if (live)
42
- setFound(records);
43
- }, () => {
44
- if (live)
45
- setFound([]);
46
- });
47
- }, text === '' ? 0 : SEARCH_DELAY_MS);
48
- return () => {
49
- live = false;
50
- clearTimeout(timer);
51
- };
52
- }, [text]);
53
- const picked = props.value == null ? null : String(props.value);
54
- const items = [...(config.required ? [] : [NONE]), ...found.map((record) => String(record.id))];
55
- const emptyLabel = config.emptyLabel ?? 'Not set';
56
- const nameOf = (key) => (key === NONE ? '' : (names.get(key)?.label ?? ''));
57
- return (_jsxs(Combobox, { items: items, value: picked, onValueChange: (key) => {
58
- if (key == null)
59
- return;
60
- const id = key === NONE ? null : (names.get(key)?.id ?? null);
61
- if (alone)
62
- props.commit(id);
63
- else
64
- props.onChange(id);
65
- },
66
- // The box showing the pick's own name is no search: the list then
67
- // offers everything, not only the one already picked.
68
- onInputValueChange: (typed) => setText(picked !== null && typed === nameOf(picked) ? '' : typed), itemToStringLabel: nameOf, filter: null, readOnly: props.disabled, defaultOpen: alone, children: [_jsx(ComboboxInput, { id: props.id, placeholder: config.placeholder ?? 'Search', ...controlAria(props) }), _jsxs(ComboboxContent, { children: [_jsx(ComboboxEmpty, { children: config.emptyText ?? 'No matches.' }), _jsx(ComboboxList, { children: items.map((key) => (_jsx(ComboboxItem, { value: key, children: key === NONE ? emptyLabel : nameOf(key) }, key))) })] })] }));
14
+ return (_jsx(ReferenceCombobox, { id: props.id, value: props.value, onValueChange: (id) => (alone ? props.commit(id) : props.onChange(id)), search: config.search, label: config.label, required: config.required, emptyLabel: config.emptyLabel, placeholder: config.placeholder, emptyText: config.emptyText, onCreate: config.onCreate, readOnly: props.disabled, defaultOpen: alone, ...controlAria(props) }));
69
15
  }
70
16
  // The parts side by side (stacked when the field is narrow), each with its
71
17
  // own label over its control and its own refusal under it. A refusal