@tristan2828/ui-foundation 4.147.0 → 4.149.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` | The composites and what goes with them: `AppShell`, `DataTable`, `EntityView` (with editing in place: `EditableValue`, `editInPlace`, `inPlace`), `EntityForm`, `FormDialog`, `RecordDialogRoute`, `Markdown`, `RichTextEditor`, `ErrorState`, `FoundationProviders`, `LoginRoute`, `RegisterRoute`; the hooks `useAuth`, `useTableUrlState`, `useRecordUpdate`; `createQueryClient`, `cn`; types `Page`, `AppError`, `QuerySpec`. The full list is the package's type declarations (`dist/index.d.ts`); what each part is for is in the app's `docs/foundation/` |
21
+ | `@tristan2828/ui-foundation` | The composites and what goes with them: `AppShell`, `DataTable`, `EntityView` (with editing in place: `EditableValue`, `editInPlace`, `inPlace`; `EditInPlaceScope` runs it on a page of the app's own), `EntityForm`, `FormDialog`, `RecordDialogRoute`, `Markdown`, `RichTextEditor` (and `preloadRichTextEditor`), `ErrorState`, `FoundationProviders`, `LoginRoute`, `RegisterRoute`; the hooks `useAuth`, `useTableUrlState`, `useRecordUpdate`; `createQueryClient`, `cn`; types `Page`, `AppError`, `QuerySpec`. The full list is the package's type declarations (`dist/index.d.ts`); what each part is for is in the app's `docs/foundation/` |
22
22
  | `@tristan2828/ui-foundation/ui/<name>` | shadcn primitives: alert, badge, breadcrumb, button, calendar, card, checkbox, collapsible, combobox, dialog, dropdown-menu, empty, field, input, input-group, label, popover, progress, radio-group, select, separator, sheet, sidebar, skeleton, slider, sonner, spinner, switch, table, tabs, textarea, toggle, toggle-group, tooltip |
23
23
  | `@tristan2828/ui-foundation/gateway` | `safeFetch`, `toAppError`, `networkError`, `proxyAuthError` — for an app's `src/api/gateway/` only |
24
24
  | `@tristan2828/ui-foundation/mocks` | MSW: `authHandlers`, `environmentHandlers`, `clientErrorHandlers`, `pushHandlers`, `resetMockAuth`, `getMockCurrentUser`, `MOCK_USER`, `startMockWorker` (mock mode's boot), `exposeMswForE2E`, among others (`dist/mocks/index.d.ts`) |
@@ -16,7 +16,7 @@
16
16
  - Step 8: Add Playwright specs for all three screens · lines 255–335
17
17
  - Step 9: Register the nav entry and route names · lines 336–349
18
18
  - Step 10: `npm run verify`. · lines 350–351
19
- - [Step 6 in detail](#step-6-in-detail) · lines 353–935
19
+ - [Step 6 in detail](#step-6-in-detail) · lines 353–959
20
20
  - [A `reference`](#a-reference) · lines 358–360
21
21
  - [A `single choice`](#a-single-choice) · lines 362–368
22
22
  - [A `date-time`](#a-date-time) · lines 370–373
@@ -28,29 +28,29 @@
28
28
  - [A `date`](#a-date) · lines 436–459
29
29
  - [A `month-day`](#a-month-day) · lines 461–481
30
30
  - [A `recurrence`](#a-recurrence) · lines 483–504
31
- - [An image on a record](#an-image-on-a-record) · lines 506–534
32
- - [A `reference` inside a sub-record item](#a-reference-inside-a-sub-record-item) · lines 536–595
33
- - [A `yes/no` marked `toggle`](#a-yesno-marked-toggle) · lines 597–612
34
- - [Keep column definitions stable](#keep-column-definitions-stable) · lines 614–622
35
- - [The view](#the-view) · lines 624–742
36
- - [The view: long text and notes](#the-view-long-text-and-notes) · lines 744–798
37
- - [The view: quick actions and editing in place](#the-view-quick-actions-and-editing-in-place) · lines 800–858
38
- - [The table opens the view, and the form returns to it](#the-table-opens-the-view-and-the-form-returns-to-it) · lines 860–871
39
- - [`<SelectValue>` shows the value, not the label](#selectvalue-shows-the-value-not-the-label) · lines 873–919
40
- - [Choosing how each column looks](#choosing-how-each-column-looks) · lines 921–935
41
- - [How a list opens a record](#how-a-list-opens-a-record) · lines 937–1448
42
- - [The record view](#the-record-view) · lines 1080–1267
43
- - [Forms](#forms) · lines 1269–1352
44
- - [Dialogs](#dialogs) · lines 1354–1387
45
- - [Toasts and feedback](#toasts-and-feedback) · lines 1389–1448
46
- - [What not to copy](#what-not-to-copy) · lines 1450–1477
47
- - [After a commit, in the backend](#after-a-commit-in-the-backend) · lines 1479–1496
48
- - [Saves that don't overwrite](#saves-that-dont-overwrite) · lines 1498–1558
49
- - [Deleting](#deleting) · lines 1560–1590
50
- - [Fields only a script writes](#fields-only-a-script-writes) · lines 1592–1611
51
- - [Searching one part of the app](#searching-one-part-of-the-app) · lines 1613–1622
52
- - [What a chat is told about an entity](#what-a-chat-is-told-about-an-entity) · lines 1625–1667
53
- - [Behind a sign-in proxy](#behind-a-sign-in-proxy) · lines 1669–1702
31
+ - [An image on a record](#an-image-on-a-record) · lines 506–558
32
+ - [A `reference` inside a sub-record item](#a-reference-inside-a-sub-record-item) · lines 560–619
33
+ - [A `yes/no` marked `toggle`](#a-yesno-marked-toggle) · lines 621–636
34
+ - [Keep column definitions stable](#keep-column-definitions-stable) · lines 638–646
35
+ - [The view](#the-view) · lines 648–766
36
+ - [The view: long text and notes](#the-view-long-text-and-notes) · lines 768–822
37
+ - [The view: quick actions and editing in place](#the-view-quick-actions-and-editing-in-place) · lines 824–882
38
+ - [The table opens the view, and the form returns to it](#the-table-opens-the-view-and-the-form-returns-to-it) · lines 884–895
39
+ - [`<SelectValue>` shows the value, not the label](#selectvalue-shows-the-value-not-the-label) · lines 897–943
40
+ - [Choosing how each column looks](#choosing-how-each-column-looks) · lines 945–959
41
+ - [How a list opens a record](#how-a-list-opens-a-record) · lines 961–1472
42
+ - [The record view](#the-record-view) · lines 1104–1291
43
+ - [Forms](#forms) · lines 1293–1376
44
+ - [Dialogs](#dialogs) · lines 1378–1411
45
+ - [Toasts and feedback](#toasts-and-feedback) · lines 1413–1472
46
+ - [What not to copy](#what-not-to-copy) · lines 1474–1501
47
+ - [After a commit, in the backend](#after-a-commit-in-the-backend) · lines 1503–1520
48
+ - [Saves that don't overwrite](#saves-that-dont-overwrite) · lines 1522–1582
49
+ - [Deleting](#deleting) · lines 1584–1614
50
+ - [Fields only a script writes](#fields-only-a-script-writes) · lines 1616–1635
51
+ - [Searching one part of the app](#searching-one-part-of-the-app) · lines 1637–1646
52
+ - [What a chat is told about an entity](#what-a-chat-is-told-about-an-entity) · lines 1649–1691
53
+ - [Behind a sign-in proxy](#behind-a-sign-in-proxy) · lines 1693–1726
54
54
 
55
55
  <!-- /index -->
56
56
 
@@ -505,33 +505,57 @@ rule it refuses); `next_after` and `occurrences` say when it falls
505
505
 
506
506
  ### An image on a record
507
507
 
508
- **An image on a record** (a photo of it) is the stored file's id on the
509
- wire (`string`, nullable), and on the form the foundation's
510
- `ImageField` in a `Controller` (`z.string().nullable()`): `value` and
511
- `onChange` are the id, `thumbUrl` the record's saved photo,
512
- `onBusyChange` holds the submit while a file uploads. Its `upload` is the app's own, one function in the
513
- gateway that sends the file to the app's endpoint and resolves to
514
- `{ id, thumbUrl, url }` (the `ImageUploadResult`), rejecting with the
515
- `AppError`; the same function goes to a notes field's
516
- `RichTextEditor`, so pictures in its text use the same storage:
517
-
518
- ```ts
519
- // src/api/gateway/files.ts
520
- export async function uploadImage(file: File): Promise<ImageUploadResult> {
521
- const body = new FormData()
522
- body.append('file', file)
523
- const response = await safeFetch('/files', { method: 'POST', body })
524
- if (response.status !== 201) throw toAppError(response.status, response.body, response.headers)
525
- const { id } = response.body as components['schemas']['File']
526
- return { id, thumbUrl: `/api/files/${id}/content?size=thumb`, url: `/api/files/${id}/content` }
527
- }
528
- ```
508
+ **Pictures are stored once, for the whole app**, by the template's
509
+ reference: copy it whole the first time an entity needs one.
510
+ - *Contract:* `openapi.yaml`'s `/files` (`uploadFile`: the request body
511
+ is the picture itself, no multipart form; 201 a `File`, 413 over
512
+ 10 MB, 422 on `file` for anything not a JPEG, PNG or WebP), `/files/{id}`
513
+ (`getFile`) and `/files/{id}/content` (`getFileContent`, the bytes, with
514
+ a `size` it takes and ignores). Another user's file is a 404.
515
+ - *Gateway:* `src/api/gateway/files.ts`. `uploadImage(file)` is the
516
+ foundation's `ImageUpload`: it calls `shrinkImage(file)` first (redrawn
517
+ upright, at most 2560 px on its long edge, as WebP, with no EXIF and so
518
+ no location; the original file where the browser can't), sends it with
519
+ `uploadFile`, and resolves to `{ id, thumbUrl, url }` (the
520
+ `ImageUploadResult`), the 422's reason as its `message`.
521
+ `fileContentUrl(id)` is the address, `/api/files/{id}/content`; text
522
+ holds it as `![](/api/files/{id}/content)`. Its tests are
523
+ `tests/gateway/files.test.ts`.
524
+ - *Mocks:* `src/mocks/files.ts`, reset by `resetMockData()`; read the type
525
+ from the bytes as the backend does.
526
+ - *Backend:* `app/routers/files.py`, `StoredFile` and `StoredFileContent`
527
+ in `app/models.py`, migration `0018` (a `files` row, the bytes in
528
+ `file_contents` so reading the row never loads them). The type sniff,
529
+ the read with a limit and the serving headers are the backend
530
+ package's `foundation_backend.uploads` (`image_type`, `read_upload`,
531
+ `image_response`), never the app's own code: served with `nosniff`, an
532
+ inline `Content-Disposition` named from the id, `default-src 'none';
533
+ sandbox`, `same-origin` and a private, immutable cache. Nothing deletes a
534
+ file: a soft-deleted record can come back with its pictures.
535
+
536
+ **Pictures in long text** (a notes field): the description editor's
537
+ `upload` is that function, through a mutation
538
+ (`src/routes/widgets/use-upload-image.ts`, `upload={useUploadImage()}` on
539
+ `WidgetDescriptionEditor`); a picture pasted, dropped or picked with the
540
+ Image tool goes in as its address. `e2e/widget-description-images.spec.ts`
541
+ is its spec.
542
+
543
+ **An image on a record** (a photo of it) is its file's id on the wire
544
+ (`photoFileId`, `integer`, nullable), and on
545
+ the form the foundation's `ImageField` in a `Controller`
546
+ (`z.string().nullable()`, converted with the form's other fields:
547
+ `String(id)` in, `Number(value)` out): `value` and `onChange` are the
548
+ id, `thumbUrl` the record's saved photo (`fileContentUrl(id, 'thumb')`),
549
+ `onBusyChange` holds the submit while a file uploads, and `upload` the
550
+ same `useUploadImage()`. The backend column is a foreign key to
551
+ `files.id`, checked as the record's other references are (another
552
+ user's file is a 422 on the field).
529
553
 
530
554
  The types it takes default to JPEG, PNG and WebP; never add SVG or
531
- HTML, which run script when served from the app's own domain. The
532
- endpoint, the storage and serving the files are the app's (the
533
- template has none); `<Markdown>` shows an image only from a web
534
- address or a path on the site, so `url` is one of those.
555
+ HTML, which run script when served from the app's own domain. Don't set
556
+ `maxSize` to the server's limit: the size checked is the picked file's,
557
+ before `shrinkImage` makes it smaller. `<Markdown>` shows an image only
558
+ from a web address or a path on the site, so `url` is one of those.
535
559
 
536
560
  ### A `reference` inside a sub-record item
537
561
 
@@ -3,48 +3,49 @@
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 rules that apply to every cell](#the-rules-that-apply-to-every-cell) · lines 63–86
7
- - [1. Plain text](#1-plain-text) · lines 88–137
8
- - [2. Icon + label](#2-icon--label) · lines 139–162
9
- - [3. Icon in a badge](#3-icon-in-a-badge) · lines 164–177
10
- - [4. Icon only, label in a tooltip](#4-icon-only-label-in-a-tooltip) · lines 179–255
11
- - [Several values: the icons side by side, every name in one tooltip](#several-values-the-icons-side-by-side-every-name-in-one-tooltip) · lines 204–255
12
- - [5. Enum → tone-mapped badge](#5-enum--tone-mapped-badge) · lines 257–277
13
- - [6. Multi-value enum, clustered](#6-multi-value-enum-clustered) · lines 279–291
14
- - [7. Link as an outline button](#7-link-as-an-outline-button) · lines 293–314
15
- - [8. Date, relative](#8-date-relative) · lines 316–353
16
- - [9. Ordinal scale (bounded integer)](#9-ordinal-scale-bounded-integer) · lines 355–431
17
- - [Three variants the package draws: a step bar, a star and a score](#three-variants-the-package-draws-a-step-bar-a-star-and-a-score) · lines 373–431
18
- - [10. Summary in the cell, detail in a popover](#10-summary-in-the-cell-detail-in-a-popover) · lines 433–482
19
- - [A second example: what a row depends on](#a-second-example-what-a-row-depends-on) · lines 451–482
20
- - [11. Number or currency — Unproven](#11-number-or-currency--unproven) · lines 484–524
21
- - [12. Boolean](#12-boolean) · lines 526–554
22
- - [13. Progress bar — Unproven](#13-progress-bar--unproven) · lines 556–590
23
- - [The compact form: `ProgressRing`](#the-compact-form-progressring) · lines 575–590
24
- - [14. Avatar and name — Unproven](#14-avatar-and-name--unproven) · lines 592–610
25
- - [15. Yes/no you flip in the row](#15-yesno-you-flip-in-the-row) · lines 612–714
26
- - [A variant: a pressed icon inside another value's cell](#a-variant-a-pressed-icon-inside-another-values-cell) · lines 635–714
27
- - [16. Title linking to the record's view](#16-title-linking-to-the-records-view) · lines 716–757
28
- - [17. Quick action on the view](#17-quick-action-on-the-view) · lines 759–831
29
- - [18. Editable value](#18-editable-value) · lines 833–1571
30
- - [Presets: one line per field](#presets-one-line-per-field) · lines 1217–1289
31
- - [Several fields edited as one](#several-fields-edited-as-one) · lines 1291–1327
32
- - [A link and its label](#a-link-and-its-label) · lines 1329–1353
33
- - [A list of sub-items](#a-list-of-sub-items) · lines 1355–1488
34
- - [In a table's rows](#in-a-tables-rows) · lines 1490–1564
35
- - [A table of a few short columns: `width="content"`](#a-table-of-a-few-short-columns-widthcontent) · lines 1566–1571
36
- - [19. Stage circle for an ordered status](#19-stage-circle-for-an-ordered-status) · lines 1573–1639
37
- - [20. Count linking to the related records](#20-count-linking-to-the-related-records) · lines 1641–1695
38
- - [21. Rows grouped under headings, and a pill filter](#21-rows-grouped-under-headings-and-a-pill-filter) · lines 1697–1779
39
- - [22. A highlighted row, and rows that are done](#22-a-highlighted-row-and-rows-that-are-done) · lines 1781–1806
40
- - [28. A list's rows: hover, lines, rows per page](#28-a-lists-rows-hover-lines-rows-per-page) · lines 1808–1841
41
- - [23. A Group menu, and a record read beside the list](#23-a-group-menu-and-a-record-read-beside-the-list) · lines 1843–1894
42
- - [24. A stored colour beside its name](#24-a-stored-colour-beside-its-name) · lines 1896–1970
43
- - [Picking one on a form: `ColorField`](#picking-one-on-a-form-colorfield) · lines 1916–1970
44
- - [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 1972–2184
45
- - [The framed look, and sibling lists beside the title](#the-framed-look-and-sibling-lists-beside-the-title) · lines 2133–2184
46
- - [26. A record's related list, capped](#26-a-records-related-list-capped) · lines 2186–2220
47
- - [27. A repeat and its next time](#27-a-repeat-and-its-next-time) · lines 2222–2269
6
+ - [The rules that apply to every cell](#the-rules-that-apply-to-every-cell) · lines 64–87
7
+ - [1. Plain text](#1-plain-text) · lines 89–138
8
+ - [2. Icon + label](#2-icon--label) · lines 140–163
9
+ - [3. Icon in a badge](#3-icon-in-a-badge) · lines 165–178
10
+ - [4. Icon only, label in a tooltip](#4-icon-only-label-in-a-tooltip) · lines 180–256
11
+ - [Several values: the icons side by side, every name in one tooltip](#several-values-the-icons-side-by-side-every-name-in-one-tooltip) · lines 205–256
12
+ - [5. Enum → tone-mapped badge](#5-enum--tone-mapped-badge) · lines 258–278
13
+ - [6. Multi-value enum, clustered](#6-multi-value-enum-clustered) · lines 280–292
14
+ - [7. Link as an outline button](#7-link-as-an-outline-button) · lines 294–315
15
+ - [8. Date, relative](#8-date-relative) · lines 317–354
16
+ - [9. Ordinal scale (bounded integer)](#9-ordinal-scale-bounded-integer) · lines 356–432
17
+ - [Three variants the package draws: a step bar, a star and a score](#three-variants-the-package-draws-a-step-bar-a-star-and-a-score) · lines 374–432
18
+ - [10. Summary in the cell, detail in a popover](#10-summary-in-the-cell-detail-in-a-popover) · lines 434–483
19
+ - [A second example: what a row depends on](#a-second-example-what-a-row-depends-on) · lines 452–483
20
+ - [11. Number or currency — Unproven](#11-number-or-currency--unproven) · lines 485–525
21
+ - [12. Boolean](#12-boolean) · lines 527–555
22
+ - [13. Progress bar — Unproven](#13-progress-bar--unproven) · lines 557–591
23
+ - [The compact form: `ProgressRing`](#the-compact-form-progressring) · lines 576–591
24
+ - [14. Avatar and name — Unproven](#14-avatar-and-name--unproven) · lines 593–611
25
+ - [15. Yes/no you flip in the row](#15-yesno-you-flip-in-the-row) · lines 613–715
26
+ - [A variant: a pressed icon inside another value's cell](#a-variant-a-pressed-icon-inside-another-values-cell) · lines 636–715
27
+ - [16. Title linking to the record's view](#16-title-linking-to-the-records-view) · lines 717–758
28
+ - [17. Quick action on the view](#17-quick-action-on-the-view) · lines 760–832
29
+ - [18. Editable value](#18-editable-value) · lines 834–1627
30
+ - [Presets: one line per field](#presets-one-line-per-field) · lines 1227–1299
31
+ - [Several fields edited as one](#several-fields-edited-as-one) · lines 1301–1337
32
+ - [A link and its label](#a-link-and-its-label) · lines 1339–1363
33
+ - [A list of sub-items](#a-list-of-sub-items) · lines 1365–1498
34
+ - [On a page of the app's own: `EditInPlaceScope`](#on-a-page-of-the-apps-own-editinplacescope) · lines 1500–1544
35
+ - [In a table's rows](#in-a-tables-rows) · lines 1546–1620
36
+ - [A table of a few short columns: `width="content"`](#a-table-of-a-few-short-columns-widthcontent) · lines 1622–1627
37
+ - [19. Stage circle for an ordered status](#19-stage-circle-for-an-ordered-status) · lines 1629–1695
38
+ - [20. Count linking to the related records](#20-count-linking-to-the-related-records) · lines 1697–1751
39
+ - [21. Rows grouped under headings, and a pill filter](#21-rows-grouped-under-headings-and-a-pill-filter) · lines 1753–1835
40
+ - [22. A highlighted row, and rows that are done](#22-a-highlighted-row-and-rows-that-are-done) · lines 1837–1862
41
+ - [28. A list's rows: hover, lines, rows per page](#28-a-lists-rows-hover-lines-rows-per-page) · lines 1864–1897
42
+ - [23. A Group menu, and a record read beside the list](#23-a-group-menu-and-a-record-read-beside-the-list) · lines 1899–1950
43
+ - [24. A stored colour beside its name](#24-a-stored-colour-beside-its-name) · lines 1952–2026
44
+ - [Picking one on a form: `ColorField`](#picking-one-on-a-form-colorfield) · lines 1972–2026
45
+ - [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 2028–2240
46
+ - [The framed look, and sibling lists beside the title](#the-framed-look-and-sibling-lists-beside-the-title) · lines 2189–2240
47
+ - [26. A record's related list, capped](#26-a-records-related-list-capped) · lines 2242–2276
48
+ - [27. A repeat and its next time](#27-a-repeat-and-its-next-time) · lines 2278–2325
48
49
 
49
50
  <!-- /index -->
50
51
 
@@ -840,6 +841,13 @@ header `StatusMark`), Price, Description (rich text edited where it's read,
840
841
  `inline`) and Extra Categories, with the controls in `widget-fields.tsx`,
841
842
  the same ones the form uses.
842
843
 
844
+ Something has to run the editing: one value open at a time, autosave,
845
+ the leave-page prompt. A record's view (`EntityView`) runs it for what's
846
+ on it, a table (`DataTable`) for its rows, and a page of the app's own
847
+ that is neither (a notes screen that is nothing but its text) wraps what
848
+ it edits in `EditInPlaceScope` ("On a page of the app's own" below).
849
+ `<EditableValue>` outside all three throws, naming them.
850
+
843
851
  The rule behind every part of it: **nothing typed is ever lost.**
844
852
 
845
853
  **No toast, but one.** An edit in place says what happened where it
@@ -1069,7 +1077,9 @@ to open, and it never closes. Ctrl/Cmd+Enter or Esc saves now and leaves
1069
1077
  the caret where it is. It sits beside the one open value rather than
1070
1078
  being it: opening another value leaves it alone. Don't give its control
1071
1079
  `autoFocus`. The cost: at rest the page shows the editor, not the read
1072
- view, and the editor loads on every visit. A click on a link in the
1080
+ view, and the editor loads on every visit (an app whose first screen is
1081
+ an editor starts that load as it starts: `preloadRichTextEditor()`, "On a
1082
+ page of the app's own" below). A click on a link in the
1073
1083
  notes still opens it in a new tab; its words are edited from the
1074
1084
  keyboard or by dragging over them, and Ctrl/Cmd+K edits its address. Use it where the notes are what the page is
1075
1085
  for; elsewhere `autosave` alone keeps the read view at rest.
@@ -1487,6 +1497,52 @@ const files = editInPlace<Attachment>({
1487
1497
  })
1488
1498
  ```
1489
1499
 
1500
+ ### On a page of the app's own: `EditInPlaceScope`
1501
+
1502
+ A page that is neither a record's view nor a table, such as a notes app
1503
+ whose screen is nothing but the note, wraps what it edits in
1504
+ `<EditInPlaceScope>` and puts `<EditableValue>`s inside: the same rules
1505
+ as a view, the same "Saving…" and "Saved", refusals, Keep Mine or Show
1506
+ Saved, and leaving the page saves first. The page needs a data router
1507
+ (`createBrowserRouter`), as a view does: the leave-page prompt uses its
1508
+ blocker.
1509
+
1510
+ ```tsx
1511
+ const body = editInPlace<string>({
1512
+ kind: 'long-text',
1513
+ inline: true,
1514
+ value: note.body,
1515
+ save: (body) => editField.mutateAsync({ body }),
1516
+ // The form's own control, spreading what it gets onto RichTextEditor
1517
+ // with inline={props.inline} toolbar="floating"
1518
+ control: (props) => <NoteBodyEditor … />,
1519
+ })
1520
+
1521
+ <EditInPlaceScope>
1522
+ <EditableValue label="Note" edit={body} />
1523
+ </EditInPlaceScope>
1524
+ ```
1525
+
1526
+ - **One scope per page, around everything it edits**, not one per
1527
+ value. Each scope renders a leave guard, which takes the router's
1528
+ blocker, and a router holds one at a time. A page with an `EntityView`
1529
+ or a `DataTable` doesn't need one: they run their own.
1530
+ - **Several always-editable values in one scope** is what a notes app's
1531
+ tabs are: one pane per open note, all mounted, only the one in front
1532
+ shown (the others `hidden`), so each keeps its caret and undo. A
1533
+ hidden value still saves, and the one leave guard covers them all.
1534
+ - **A value that leaves the page mid-typing is still saved** (a tab
1535
+ closed, a pane unmounted): what was typed goes at once rather than
1536
+ after the pause.
1537
+ - **An app that opens on an editor** calls `preloadRichTextEditor()`
1538
+ as it starts (in `main.tsx`), so the editor's code is loading while
1539
+ the note is fetched, not after. It returns nothing, never throws, and
1540
+ is safe to call more than once; a failed load is the editor's to meet
1541
+ when one mounts.
1542
+
1543
+ The stories are `app/EditInPlaceScope` (one note, and two in one scope);
1544
+ `e2e/edit-in-place-scope.spec.ts` is the browser behaviour.
1545
+
1490
1546
  ### In a table's rows
1491
1547
 
1492
1548
  For a **small entity edited in its table** (a name and a few fields,
@@ -0,0 +1,5 @@
1
+ import { type ReactNode } from 'react';
2
+ export type EditInPlaceScopeProps = {
3
+ children: ReactNode;
4
+ };
5
+ export declare function EditInPlaceScope({ children }: EditInPlaceScopeProps): import("react").JSX.Element;
@@ -0,0 +1,30 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // Editing in place on a page of the app's own: one that isn't a record's
3
+ // view or a table. EntityView and DataTable each run it for what's inside
4
+ // them (one field open at a time, autosave, the leave-page prompt); a page
5
+ // built from other parts, such as a notes screen that is nothing but its
6
+ // text, wraps those parts in this and uses <EditableValue> inside, with
7
+ // the same rules (cell-patterns.md "Editable value").
8
+ //
9
+ // Everything inside one scope is one page's worth of editing: opening a
10
+ // value saves the open one first, and leaving the page (a link, Back,
11
+ // closing the tab, hiding it on a phone) saves what autosaves and asks
12
+ // about the rest.
13
+ //
14
+ // One scope per page, around everything editable on it, not one per
15
+ // value, and not on a page that has an EntityView or a DataTable (each
16
+ // runs its own). Every one of them renders a leave guard, which takes
17
+ // React Router's blocker, and the router holds one blocker at a time. A
18
+ // scope holds any number of always-editable values, such as a notes
19
+ // app's open tabs kept mounted with only the one in front shown.
20
+ import { useState, useSyncExternalStore } from 'react';
21
+ import { EditInPlaceContext } from './edit-in-place.js';
22
+ import { EditInPlaceStore } from './edit-in-place-store.js';
23
+ import { LeaveGuard } from './editable-value.js';
24
+ export function EditInPlaceScope({ children }) {
25
+ const [store] = useState(() => new EditInPlaceStore());
26
+ // The leave-page prompt only while a value is open (or one is always
27
+ // editable), so a page nobody's editing never blocks anything.
28
+ const editing = useSyncExternalStore(store.subscribe, () => store.editing, () => store.editing);
29
+ return (_jsxs(EditInPlaceContext.Provider, { value: store, children: [editing && _jsx(LeaveGuard, { store: store }), children] }));
30
+ }
@@ -42,8 +42,9 @@ export declare function EditableField({ label, edit, children, layout, look, cla
42
42
  /**
43
43
  * While a field holds something unsaved, leaving asks first: an in-app
44
44
  * link or Back (React Router's blocker, so the app needs a data router),
45
- * or closing the tab (`beforeunload`). Rendered by EntityView only while
46
- * a field is being edited, so a view nobody's editing never blocks anything.
45
+ * or closing the tab (`beforeunload`). Rendered by EntityView, DataTable
46
+ * and EditInPlaceScope only while a field is being edited, so a view
47
+ * nobody's editing never blocks anything.
47
48
  *
48
49
  * When everything unsaved autosaves, an in-app move saves it first and
49
50
  * goes on once saved, asking only if that save fails. Closing the tab
@@ -2,7 +2,8 @@ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-run
2
2
  // A value on a record's view that turns into its form control where it's
3
3
  // shown, and saves when you leave it (cell-patterns.md "Editable value").
4
4
  // EntityView wraps every field, section and title marked `edit`; a header
5
- // badge uses <EditableValue> itself. The rules are edit-in-place-store.ts.
5
+ // badge uses <EditableValue> itself, and so does a page of the app's own
6
+ // inside an <EditInPlaceScope>. The rules are edit-in-place-store.ts.
6
7
  //
7
8
  // - Start: click the value (a link inside it still navigates), or tab to
8
9
  // its edit button and press Enter. Hover and focus show it's editable.
@@ -156,7 +157,7 @@ function usePinnedStatus(field, enabled) {
156
157
  function useStore() {
157
158
  const store = useContext(EditInPlaceContext);
158
159
  if (!store)
159
- throw new Error('<EditableValue> works inside an <EntityView>, which runs editing in place.');
160
+ throw new Error('<EditableValue> works inside an <EntityView> or an <EditInPlaceScope>, which run editing in place.');
160
161
  return store;
161
162
  }
162
163
  // Long text's "Keep Mine": both sides kept block by block (rebaseMarkdown).
@@ -458,8 +459,9 @@ const sameAsJson = (a, b) => JSON.stringify(a) === JSON.stringify(b);
458
459
  /**
459
460
  * While a field holds something unsaved, leaving asks first: an in-app
460
461
  * link or Back (React Router's blocker, so the app needs a data router),
461
- * or closing the tab (`beforeunload`). Rendered by EntityView only while
462
- * a field is being edited, so a view nobody's editing never blocks anything.
462
+ * or closing the tab (`beforeunload`). Rendered by EntityView, DataTable
463
+ * and EditInPlaceScope only while a field is being edited, so a view
464
+ * nobody's editing never blocks anything.
463
465
  *
464
466
  * When everything unsaved autosaves, an in-app move saves it first and
465
467
  * goes on once saved, asking only if that save fails. Closing the tab
@@ -44,12 +44,14 @@ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-run
44
44
  // The editor (Milkdown) is loaded on first use, so a page that only reads
45
45
  // Markdown never downloads it. Until it arrives the text shows as
46
46
  // <Markdown> draws it, the field's size, so nothing moves when the editor
47
- // takes its place; an empty one shows skeleton lines.
47
+ // takes its place; an empty one shows skeleton lines. An app that opens on
48
+ // an editor loads it ahead with `preloadRichTextEditor()`.
48
49
  import { lazy, Suspense, useLayoutEffect, useRef, useState } from 'react';
49
50
  import { cn } from 'cn';
50
51
  import { Skeleton } from '../ui/skeleton.js';
51
52
  import { Markdown } from './markdown.js';
52
- const MilkdownEditor = lazy(() => import('./milkdown-editor.js'));
53
+ import { loadRichTextEditor } from './rich-text-load.js';
54
+ const MilkdownEditor = lazy(loadRichTextEditor);
53
55
  // When the editor opens again: each time `defaultValue` changes to
54
56
  // Markdown it didn't report. Adjusted while rendering (React's "storing
55
57
  // information from previous renders"), so the new text never shows a
@@ -0,0 +1,11 @@
1
+ /** The editor's module, fetched once: later calls get the same one. */
2
+ export declare const loadRichTextEditor: () => Promise<typeof import("./milkdown-editor.js")>;
3
+ /**
4
+ * Starts loading the editor now, before one is on screen: an app whose
5
+ * first screen is an editor (a notes app that opens on a note) calls it as
6
+ * the app starts, so the editor is there when the note is, not a moment
7
+ * after it. Safe to call more than once, and anywhere: it never throws,
8
+ * and a failed load is swallowed here, so the page goes on; the editor
9
+ * meets the same failure when one mounts, as it would with no preload.
10
+ */
11
+ export declare function preloadRichTextEditor(): void;
@@ -0,0 +1,16 @@
1
+ // The editor's own code (Milkdown), loaded apart from the page that shows
2
+ // it: RichTextEditor asks for it when it first mounts, and an app that
3
+ // opens on an editor asks ahead with `preloadRichTextEditor()`.
4
+ /** The editor's module, fetched once: later calls get the same one. */
5
+ export const loadRichTextEditor = () => import('./milkdown-editor.js');
6
+ /**
7
+ * Starts loading the editor now, before one is on screen: an app whose
8
+ * first screen is an editor (a notes app that opens on a note) calls it as
9
+ * the app starts, so the editor is there when the note is, not a moment
10
+ * after it. Safe to call more than once, and anywhere: it never throws,
11
+ * and a failed load is swallowed here, so the page goes on; the editor
12
+ * meets the same failure when one mounts, as it would with no preload.
13
+ */
14
+ export function preloadRichTextEditor() {
15
+ void loadRichTextEditor().catch(() => { });
16
+ }
package/dist/index.d.ts CHANGED
@@ -52,6 +52,7 @@ export { linkHost, linkHref, linkRule } from './lib/link-href.js';
52
52
  export { TITLE_CASE_SMALL_WORDS, titleCase } from './lib/title-case.js';
53
53
  export { DataEnvironmentBanner } from './components/app/data-environment-banner.js';
54
54
  export { EditableValue, type EditableValueProps } from './components/app/editable-value.js';
55
+ export { EditInPlaceScope, type EditInPlaceScopeProps } from './components/app/edit-in-place-scope.js';
55
56
  export { editRowClass, onEditRowClick, SAVED_FOR_MS } from './components/app/edit-row.js';
56
57
  export { ErrorState } from './components/app/error-state.js';
57
58
  export { InlineCreate, type InlineCreateProps } from './components/app/inline-create.js';
@@ -71,6 +72,7 @@ export { MultiReference } from './components/app/multi-reference.js';
71
72
  export { ListEditor } from './components/app/list-editor.js';
72
73
  export { PasswordInput } from './components/app/password-input.js';
73
74
  export { RichTextEditor, type RichTextEditorProps } from './components/app/rich-text-editor.js';
75
+ export { preloadRichTextEditor } from './components/app/rich-text-load.js';
74
76
  export { flushPendingEdits, hasPendingEdits } from './lib/pending-edits.js';
75
77
  export { RouteErrorBoundary } from './components/app/route-error-boundary.js';
76
78
  export { PillFilter, type PillFilterOption, type PillFilterProps } from './components/app/pill-filter.js';
@@ -115,7 +117,7 @@ export { IconField, type IconFieldOption, type IconFieldProps } from './componen
115
117
  export { MonthDayField, type MonthDayFieldProps } from './components/app/month-day-field.js';
116
118
  export { ImageField, type ImageFieldProps } from './components/app/image-field.js';
117
119
  export { ImageViewer, type ImageViewerImage, type ImageViewerProps } from './components/app/image-viewer.js';
118
- export { DEFAULT_IMAGE_TYPES, type ImageUpload, type ImageUploadResult } from './lib/image-file.js';
120
+ export { DEFAULT_IMAGE_TYPES, shrinkImage, type ImageUpload, type ImageUploadResult, type ShrinkImageOptions } from './lib/image-file.js';
119
121
  export { formatPlainDate, parsePlainDate, plainDateExamples, unreadableDateMessage, type ParsePlainDateOptions, type PlainDate, } from './lib/plain-date.js';
120
122
  export { formatMonthDay, isMonthDay, monthDayProblem, type MonthDay } from './lib/month-day.js';
121
123
  export { RecurrenceField, type RecurrenceFieldProps } from './components/app/recurrence-field.js';
package/dist/index.js CHANGED
@@ -63,6 +63,7 @@ export { linkHost, linkHref, linkRule } from './lib/link-href.js';
63
63
  export { TITLE_CASE_SMALL_WORDS, titleCase } from './lib/title-case.js';
64
64
  export { DataEnvironmentBanner } from './components/app/data-environment-banner.js';
65
65
  export { EditableValue } from './components/app/editable-value.js';
66
+ export { EditInPlaceScope } from './components/app/edit-in-place-scope.js';
66
67
  export { editRowClass, onEditRowClick, SAVED_FOR_MS } from './components/app/edit-row.js';
67
68
  export { ErrorState } from './components/app/error-state.js';
68
69
  export { InlineCreate } from './components/app/inline-create.js';
@@ -80,6 +81,7 @@ export { MultiReference } from './components/app/multi-reference.js';
80
81
  export { ListEditor } from './components/app/list-editor.js';
81
82
  export { PasswordInput } from './components/app/password-input.js';
82
83
  export { RichTextEditor } from './components/app/rich-text-editor.js';
84
+ export { preloadRichTextEditor } from './components/app/rich-text-load.js';
83
85
  // Typing a RichTextEditor holds back until a pause, reported now: call it
84
86
  // before reading a rich-text field's value to save it in your own form.
85
87
  export { flushPendingEdits, hasPendingEdits } from './lib/pending-edits.js';
@@ -125,7 +127,7 @@ export { IconField } from './components/app/icon-field.js';
125
127
  export { MonthDayField } from './components/app/month-day-field.js';
126
128
  export { ImageField } from './components/app/image-field.js';
127
129
  export { ImageViewer } from './components/app/image-viewer.js';
128
- export { DEFAULT_IMAGE_TYPES } from './lib/image-file.js';
130
+ export { DEFAULT_IMAGE_TYPES, shrinkImage } from './lib/image-file.js';
129
131
  export { formatPlainDate, parsePlainDate, plainDateExamples, unreadableDateMessage, } from './lib/plain-date.js';
130
132
  export { formatMonthDay, isMonthDay, monthDayProblem } from './lib/month-day.js';
131
133
  export { RecurrenceField } from './components/app/recurrence-field.js';
@@ -36,5 +36,24 @@ export declare function acceptAttribute(accept?: readonly string[]): string;
36
36
  export declare function imageRefusal(file: Pick<File, 'type' | 'size'> & {
37
37
  name?: string;
38
38
  }, rules?: ImageFileRules): string | null;
39
+ export type ShrinkImageOptions = {
40
+ /** The longest edge, in pixels, the picture is drawn at most. Defaults to 2560. A smaller picture is never enlarged. */
41
+ maxEdge?: number;
42
+ /** The type it's written as. Defaults to `image/webp`. */
43
+ type?: string;
44
+ /** Quality for a lossy type, 0 to 1. Defaults to 0.85. */
45
+ quality?: number;
46
+ };
47
+ /**
48
+ * A picture redrawn before it's uploaded: turned upright from its EXIF
49
+ * orientation, no longer than `maxEdge` on its long edge, and written as
50
+ * `type` (WebP unless asked otherwise). A phone photo of several
51
+ * megabytes becomes a few hundred kilobytes, and a redraw carries no
52
+ * EXIF, so no location. Resolves to the original file, untouched, when
53
+ * the browser can't: it can't read the file as a picture, or can't write
54
+ * the type. A courtesy, not a defence: the server checks what it's sent
55
+ * either way. An app's `ImageUpload` calls it before it sends the file.
56
+ */
57
+ export declare function shrinkImage(file: File, options?: ShrinkImageOptions): Promise<File>;
39
58
  /** What a failed upload says: the rejection's own `message` (an `AppError`'s), else a generic sentence. */
40
59
  export declare function uploadFailure(error: unknown, noun?: string): string;
@@ -1,7 +1,8 @@
1
1
  // Images a person picks, pastes or drops, before they're uploaded: which
2
2
  // files are accepted, and why one isn't, in words. Shared by ImageField
3
3
  // and the rich-text editor's upload. The upload itself is the app's (an
4
- // `ImageUpload`): the package knows no endpoint and no storage.
4
+ // `ImageUpload`): the package knows no endpoint and no storage. Before it
5
+ // sends a picture, `shrinkImage` redraws it smaller and without its EXIF.
5
6
  /** The image types accepted unless a field says otherwise. */
6
7
  export const DEFAULT_IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/webp'];
7
8
  // How a type is named to a person: "JPEG", not "image/jpeg".
@@ -86,6 +87,56 @@ function article(name) {
86
87
  const spelled = /^[A-Z][A-Z0-9]+$/.test(name);
87
88
  return (spelled ? /^[AEFHILMNORSX]/ : /^[aeiou]/i).test(name) ? 'an' : 'a';
88
89
  }
90
+ /**
91
+ * A picture redrawn before it's uploaded: turned upright from its EXIF
92
+ * orientation, no longer than `maxEdge` on its long edge, and written as
93
+ * `type` (WebP unless asked otherwise). A phone photo of several
94
+ * megabytes becomes a few hundred kilobytes, and a redraw carries no
95
+ * EXIF, so no location. Resolves to the original file, untouched, when
96
+ * the browser can't: it can't read the file as a picture, or can't write
97
+ * the type. A courtesy, not a defence: the server checks what it's sent
98
+ * either way. An app's `ImageUpload` calls it before it sends the file.
99
+ */
100
+ export async function shrinkImage(file, options = {}) {
101
+ const { maxEdge = 2560, type = 'image/webp', quality = 0.85 } = options;
102
+ if (typeof createImageBitmap !== 'function' || typeof document === 'undefined')
103
+ return file;
104
+ let bitmap;
105
+ try {
106
+ bitmap = await createImageBitmap(file, { imageOrientation: 'from-image' });
107
+ }
108
+ catch {
109
+ return file;
110
+ }
111
+ try {
112
+ const scale = Math.min(1, maxEdge / Math.max(bitmap.width, bitmap.height));
113
+ const width = Math.max(1, Math.round(bitmap.width * scale));
114
+ const height = Math.max(1, Math.round(bitmap.height * scale));
115
+ const canvas = document.createElement('canvas');
116
+ canvas.width = width;
117
+ canvas.height = height;
118
+ const context = canvas.getContext('2d');
119
+ if (!context)
120
+ return file;
121
+ context.imageSmoothingQuality = 'high';
122
+ context.drawImage(bitmap, 0, 0, width, height);
123
+ const blob = await new Promise((resolve) => canvas.toBlob(resolve, type, quality));
124
+ // A browser that can't write the type hands back a PNG instead.
125
+ if (!blob || blob.type !== type)
126
+ return file;
127
+ return new File([blob], renamed(file.name, type), { type, lastModified: file.lastModified });
128
+ }
129
+ finally {
130
+ bitmap.close();
131
+ }
132
+ }
133
+ const EXTENSIONS = { 'image/webp': 'webp', 'image/jpeg': 'jpg', 'image/png': 'png' };
134
+ // "IMG_0042.HEIC" written as WebP is "IMG_0042.webp".
135
+ function renamed(name, type) {
136
+ const extension = EXTENSIONS[type] ?? type.split('/')[1] ?? 'img';
137
+ const stem = name.includes('.') ? name.slice(0, name.lastIndexOf('.')) : name;
138
+ return `${stem || 'image'}.${extension}`;
139
+ }
89
140
  /** What a failed upload says: the rejection's own `message` (an `AppError`'s), else a generic sentence. */
90
141
  export function uploadFailure(error, noun = 'image') {
91
142
  if (error && typeof error === 'object' && 'message' in error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tristan2828/ui-foundation",
3
- "version": "4.147.0",
3
+ "version": "4.149.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": {