@tristan2828/ui-foundation 4.125.0 → 4.126.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 (66) hide show
  1. package/README.md +1 -1
  2. package/conventions/docs/add-an-entity.md +42 -21
  3. package/conventions/docs/cell-patterns.md +80 -39
  4. package/dist/api/transport/index.js +10 -1
  5. package/dist/components/app/edit-caret.d.ts +25 -0
  6. package/dist/components/app/edit-caret.js +118 -0
  7. package/dist/components/app/edit-in-place-store.d.ts +43 -4
  8. package/dist/components/app/edit-in-place-store.js +169 -19
  9. package/dist/components/app/editable-value.js +164 -22
  10. package/dist/components/app/entity-form.js +4 -0
  11. package/dist/components/app/form-leave-guard.js +7 -1
  12. package/dist/components/app/milkdown-editor.d.ts +1 -0
  13. package/dist/components/app/milkdown-editor.js +224 -63
  14. package/dist/components/app/prose-look.d.ts +1 -1
  15. package/dist/components/app/prose-look.js +3 -1
  16. package/dist/components/app/rich-text-autolink.d.ts +6 -0
  17. package/dist/components/app/rich-text-autolink.js +79 -0
  18. package/dist/components/app/rich-text-edges.d.ts +8 -0
  19. package/dist/components/app/rich-text-edges.js +144 -0
  20. package/dist/components/app/rich-text-editor.d.ts +15 -2
  21. package/dist/components/app/rich-text-editor.js +16 -4
  22. package/dist/components/app/rich-text-empty-paragraph.d.ts +14 -6
  23. package/dist/components/app/rich-text-empty-paragraph.js +19 -8
  24. package/dist/components/app/rich-text-formats.js +88 -15
  25. package/dist/components/app/rich-text-full-screen.d.ts +2 -0
  26. package/dist/components/app/rich-text-full-screen.js +78 -0
  27. package/dist/components/app/rich-text-highlight-menu.d.ts +3 -1
  28. package/dist/components/app/rich-text-highlight-menu.js +3 -2
  29. package/dist/components/app/rich-text-input-rules.d.ts +7 -0
  30. package/dist/components/app/rich-text-input-rules.js +83 -0
  31. package/dist/components/app/rich-text-keyboard-bar.d.ts +24 -0
  32. package/dist/components/app/rich-text-keyboard-bar.js +214 -0
  33. package/dist/components/app/rich-text-node-views.js +2 -1
  34. package/dist/components/app/rich-text-paste.d.ts +43 -0
  35. package/dist/components/app/rich-text-paste.js +355 -0
  36. package/dist/components/app/rich-text-shortcuts.d.ts +5 -1
  37. package/dist/components/app/rich-text-shortcuts.js +132 -2
  38. package/dist/components/app/rich-text-slash-menu.js +47 -9
  39. package/dist/components/app/rich-text-slash.d.ts +7 -0
  40. package/dist/components/app/rich-text-slash.js +27 -14
  41. package/dist/components/app/rich-text-table-grips.d.ts +8 -6
  42. package/dist/components/app/rich-text-table-grips.js +11 -12
  43. package/dist/components/app/rich-text-tasks.d.ts +8 -0
  44. package/dist/components/app/rich-text-tasks.js +20 -0
  45. package/dist/components/app/rich-text-toolbar.d.ts +5 -1
  46. package/dist/components/app/rich-text-toolbar.js +13 -5
  47. package/dist/components/app/rich-text-touch.d.ts +2 -0
  48. package/dist/components/app/rich-text-touch.js +18 -0
  49. package/dist/components/app/rich-text-widgets.js +1 -1
  50. package/dist/hooks/table-url-changes.d.ts +4 -0
  51. package/dist/hooks/table-url-changes.js +13 -0
  52. package/dist/hooks/use-table-url-state.js +14 -8
  53. package/dist/index.d.ts +1 -0
  54. package/dist/index.js +3 -0
  55. package/dist/lib/markdown-merge.d.ts +26 -0
  56. package/dist/lib/markdown-merge.js +112 -17
  57. package/dist/lib/page-leaving.d.ts +8 -0
  58. package/dist/lib/page-leaving.js +30 -0
  59. package/dist/lib/pending-edits.d.ts +14 -0
  60. package/dist/lib/pending-edits.js +51 -0
  61. package/dist/mocks/e2e-hooks.js +10 -0
  62. package/dist/mocks/override.d.ts +8 -0
  63. package/dist/testing/index.d.ts +40 -2
  64. package/dist/testing/index.js +101 -7
  65. package/package.json +1 -1
  66. package/styles/index.css +7 -0
package/README.md CHANGED
@@ -22,7 +22,7 @@ than installing this by hand:
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`, `startMockWorker` (mock mode's boot), `exposeMswForE2E` |
25
- | `@tristan2828/ui-foundation/testing` | Playwright: `test` and `expect` (a page whose `goto()`/`reload()` wait for the app's boot; `withBootWait` for a page of your own), `defineA11ySuite`, `defineMockModeBannerSuite`, `defineDataEnvironmentBannerSuite`, `forceMswOverride`, `forceLoggedOut`, `waitForMswReady`, `expectDataViewsLoaded` |
25
+ | `@tristan2828/ui-foundation/testing` | Playwright: `test` and `expect` (a page whose `goto()`/`reload()` let its `/api/` requests settle, then wait for the app's boot; `withBootWait` for a page of your own), `defineA11ySuite`, `defineMockModeBannerSuite`, `defineDataEnvironmentBannerSuite`, `forceMswOverride` (`{ hold: true }` for a loading state, then `release()`), `releaseMswOverride`, `forceLoggedOut`, `waitForMswReady`, `expectDataViewsLoaded` |
26
26
  | `@tristan2828/ui-foundation/eslint` | the lint rules, as a flat config: `export default [...uiFoundation()]` |
27
27
  | `@tristan2828/ui-foundation/styles.css` | tokens and base styles, after `@import "tailwindcss";` |
28
28
  | `@tristan2828/ui-foundation/openapi.yaml` | the part of an app's API contract the package calls: `/auth/*`, `/environment` (optional) and the error bodies |
@@ -4,29 +4,29 @@
4
4
  ## Index
5
5
 
6
6
  - [The reference files](#the-reference-files) · lines 45–67
7
- - [Before anything: the entity plan](#before-anything-the-entity-plan) · lines 69–859
7
+ - [Before anything: the entity plan](#before-anything-the-entity-plan) · lines 69–880
8
8
  - Step 1: Add `<Entity>` to `openapi.yaml` · lines 111–118
9
9
  - Step 2: `npm run gen:api` · lines 119–120
10
10
  - Step 3: Add gateway tests in `tests/gateway/<entity>.test.ts`, derived from the spec · lines 121–132
11
11
  - Step 4: Add MSW handlers in `src/mocks/<entity>.ts` · lines 133–142
12
12
  - Step 5: Add a gateway module in `src/api/gateway/<entity>.ts` · lines 143–149
13
- - Step 6: Copy the reference files, one for one, not just the two screens · lines 150–747
14
- - Step 7: Register routes · lines 748–763
15
- - Step 8: Add Playwright specs for all three screens · lines 764–841
16
- - Step 9: Register the nav entry and route names · lines 842–856
17
- - Step 10: `npm run verify`. · lines 857–859
18
- - [How a list opens a record](#how-a-list-opens-a-record) · lines 861–1330
19
- - [The record view](#the-record-view) · lines 1014–1171
20
- - [Forms](#forms) · lines 1173–1244
21
- - [Dialogs](#dialogs) · lines 1246–1277
22
- - [Toasts and feedback](#toasts-and-feedback) · lines 1279–1330
23
- - [What not to copy](#what-not-to-copy) · lines 1332–1365
24
- - [After a commit, in the backend](#after-a-commit-in-the-backend) · lines 1367–1384
25
- - [Deleting](#deleting) · lines 1386–1417
26
- - [Fields only a script writes](#fields-only-a-script-writes) · lines 1419–1440
27
- - [Searching one part of the app](#searching-one-part-of-the-app) · lines 1442–1451
28
- - [What a chat is told about an entity](#what-a-chat-is-told-about-an-entity) · lines 1454–1496
29
- - [Behind a sign-in proxy](#behind-a-sign-in-proxy) · lines 1498–1534
13
+ - Step 6: Copy the reference files, one for one, not just the two screens · lines 150–758
14
+ - Step 7: Register routes · lines 759–774
15
+ - Step 8: Add Playwright specs for all three screens · lines 775–862
16
+ - Step 9: Register the nav entry and route names · lines 863–877
17
+ - Step 10: `npm run verify`. · lines 878–880
18
+ - [How a list opens a record](#how-a-list-opens-a-record) · lines 882–1351
19
+ - [The record view](#the-record-view) · lines 1035–1192
20
+ - [Forms](#forms) · lines 1194–1265
21
+ - [Dialogs](#dialogs) · lines 1267–1298
22
+ - [Toasts and feedback](#toasts-and-feedback) · lines 1300–1351
23
+ - [What not to copy](#what-not-to-copy) · lines 1353–1386
24
+ - [After a commit, in the backend](#after-a-commit-in-the-backend) · lines 1388–1405
25
+ - [Deleting](#deleting) · lines 1407–1438
26
+ - [Fields only a script writes](#fields-only-a-script-writes) · lines 1440–1461
27
+ - [Searching one part of the app](#searching-one-part-of-the-app) · lines 1463–1472
28
+ - [What a chat is told about an entity](#what-a-chat-is-told-about-an-entity) · lines 1475–1517
29
+ - [Behind a sign-in proxy](#behind-a-sign-in-proxy) · lines 1519–1555
30
30
 
31
31
  <!-- /index -->
32
32
 
@@ -425,7 +425,14 @@ is a filled-in example while the Widgets demo is still here).
425
425
  the Markdown long text's `RichTextEditor` (on the form whether or
426
426
  not it edits in place), given a `placeholder` and `maxLength` (the
427
427
  schema's limit, one constant both read, like Widget's
428
- `DESCRIPTION_MAX_LENGTH`). Every other field's control stays inline in
428
+ `DESCRIPTION_MAX_LENGTH`) and an `onProblem` prop it passes on. **On
429
+ the form, bind `onProblem`** as `widget-form.tsx`'s
430
+ `onDescriptionProblem` does: the message becomes the field's error
431
+ (`setError`, type `refused`) and submit is refused while it stands.
432
+ An edit the editor can't save without rewriting text nobody touched
433
+ never reaches `onChange`, so a form without it would send the last
434
+ text that could be saved and say it worked. (An editor given no
435
+ `onProblem` says it inside the field itself.) Every other field's control stays inline in
429
436
  the form, as `widget-form.tsx`'s Category, Tags and Available From
430
437
  do. No `Edit in place` line and no Markdown long text: no fields
431
438
  file.
@@ -641,7 +648,11 @@ is a filled-in example while the Widgets demo is still here).
641
648
  `useEditWidgetField`: the single-field save with `optimistic: false,
642
649
  toastOnError: false`). `kind` follows the control: `text` (one line;
643
650
  a number or integer too), `long-text` (Markdown, `RichTextEditor`
644
- with `autoFocus` and `onProblem={props.onProblem}`), `choice` (a
651
+ with `onProblem={props.onProblem}`; notes are `inline: true` by
652
+ default, the control passing `inline={props.inline}` and
653
+ `toolbar={props.inline ? 'floating' : true}` with no `autoFocus`,
654
+ as Widget's Description does; a short one opened by a click is
655
+ `autosave: true` with `autoFocus`), `choice` (a
645
656
  select or a single reference: its list opens with the field,
646
657
  `defaultOpen`, non-modal, `onChange={(v) => props.commit(v)}`,
647
658
  `onOpenChange={(open) => !open && props.cancel()}`; a yes/no switch
@@ -768,7 +779,10 @@ is a filled-in example while the Widgets demo is still here).
768
779
  `e2e/widgets-table.spec.ts`/`e2e/widget-form.spec.ts`/
769
780
  `e2e/widget-view.spec.ts` for the pattern. Import `test` and
770
781
  `expect` from there too, not from `@playwright/test`: its page's
771
- `goto()` and `reload()` return once the app has rendered (after MSW's
782
+ `goto()` and `reload()` first wait for the page's `/api/` requests to
783
+ settle (150 ms with none in flight, at most 3 s, never a failure), so a
784
+ save's follow-up refresh isn't sent past the mocks by the page as it
785
+ unloads; then they return once the app has rendered (after MSW's
772
786
  start), and load once more if the server refused one of its files,
773
787
  so a spec's first expect never meets an empty page. The view's states are
774
788
  loading, not found (a 404: "Not found", the way back, no retry), error
@@ -806,6 +820,13 @@ is a filled-in example while the Widgets demo is still here).
806
820
  section placed `details`, that test checks its labels sit beside
807
821
  their values, and another on a wide screen that there's no rail (copy
808
822
  `wide screens: …` in `e2e/widget-view.spec.ts`).
823
+ **A loading test holds the answer, never delays it:**
824
+ `forceMswOverride(page, override, { hold: true })` returns a
825
+ `release()`; assert the skeleton, `await release()`, then assert the
826
+ data, so the test waits on nothing but its own steps. A `delayMs` can
827
+ run out before the page first renders under load, and the skeleton is
828
+ never seen. Copy `loading: …` in `e2e/widgets-table.spec.ts`; keep
829
+ `delayMs` for a test about time itself.
809
830
  States forced via a first-load init script (loading, load-time error)
810
831
  need `page.addInitScript` before navigation; states forced after the
811
832
  page is already up (a mutation's error response) can use a
@@ -26,25 +26,25 @@
26
26
  - [A variant: a pressed icon inside another value's cell](#a-variant-a-pressed-icon-inside-another-values-cell) · lines 645–728
27
27
  - [16. Title linking to the record's view](#16-title-linking-to-the-records-view) · lines 730–776
28
28
  - [17. Quick action on the view](#17-quick-action-on-the-view) · lines 778–851
29
- - [18. Editable value](#18-editable-value) · lines 853–1556
30
- - [Presets: one line per field](#presets-one-line-per-field) · lines 1188–1256
31
- - [Several fields edited as one](#several-fields-edited-as-one) · lines 1258–1294
32
- - [A link and its label](#a-link-and-its-label) · lines 1296–1320
33
- - [A list of sub-items](#a-list-of-sub-items) · lines 1322–1455
34
- - [In a table's rows](#in-a-tables-rows) · lines 1457–1542
35
- - [A table of a few short columns: `width="content"`](#a-table-of-a-few-short-columns-widthcontent) · lines 1544–1556
36
- - [19. Stage circle for an ordered status](#19-stage-circle-for-an-ordered-status) · lines 1558–1624
37
- - [20. Count linking to the related records](#20-count-linking-to-the-related-records) · lines 1626–1690
38
- - [21. Rows grouped under headings, and a pill filter](#21-rows-grouped-under-headings-and-a-pill-filter) · lines 1692–1790
39
- - [22. A highlighted row, and rows that are done](#22-a-highlighted-row-and-rows-that-are-done) · lines 1792–1821
40
- - [24. A list's rows: hover, lines, rows per page](#24-a-lists-rows-hover-lines-rows-per-page) · lines 1823–1861
41
- - [23. A Group menu, and a record read beside the list](#23-a-group-menu-and-a-record-read-beside-the-list) · lines 1863–1939
42
- - [24. A stored colour beside its name](#24-a-stored-colour-beside-its-name) · lines 1941–2027
43
- - [Picking one on a form: `ColorField`](#picking-one-on-a-form-colorfield) · lines 1966–2027
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 2029–2254
45
- - [The framed look, and sibling lists beside the title](#the-framed-look-and-sibling-lists-beside-the-title) · lines 2183–2254
46
- - [26. A record's related list, capped](#26-a-records-related-list-capped) · lines 2256–2292
47
- - [27. A repeat and its next time](#27-a-repeat-and-its-next-time) · lines 2294–2343
29
+ - [18. Editable value](#18-editable-value) · lines 853–1597
30
+ - [Presets: one line per field](#presets-one-line-per-field) · lines 1229–1297
31
+ - [Several fields edited as one](#several-fields-edited-as-one) · lines 1299–1335
32
+ - [A link and its label](#a-link-and-its-label) · lines 1337–1361
33
+ - [A list of sub-items](#a-list-of-sub-items) · lines 1363–1496
34
+ - [In a table's rows](#in-a-tables-rows) · lines 1498–1583
35
+ - [A table of a few short columns: `width="content"`](#a-table-of-a-few-short-columns-widthcontent) · lines 1585–1597
36
+ - [19. Stage circle for an ordered status](#19-stage-circle-for-an-ordered-status) · lines 1599–1665
37
+ - [20. Count linking to the related records](#20-count-linking-to-the-related-records) · lines 1667–1731
38
+ - [21. Rows grouped under headings, and a pill filter](#21-rows-grouped-under-headings-and-a-pill-filter) · lines 1733–1831
39
+ - [22. A highlighted row, and rows that are done](#22-a-highlighted-row-and-rows-that-are-done) · lines 1833–1862
40
+ - [24. A list's rows: hover, lines, rows per page](#24-a-lists-rows-hover-lines-rows-per-page) · lines 1864–1902
41
+ - [23. A Group menu, and a record read beside the list](#23-a-group-menu-and-a-record-read-beside-the-list) · lines 1904–1980
42
+ - [24. A stored colour beside its name](#24-a-stored-colour-beside-its-name) · lines 1982–2068
43
+ - [Picking one on a form: `ColorField`](#picking-one-on-a-form-colorfield) · lines 2007–2068
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 2070–2295
45
+ - [The framed look, and sibling lists beside the title](#the-framed-look-and-sibling-lists-beside-the-title) · lines 2224–2295
46
+ - [26. A record's related list, capped](#26-a-records-related-list-capped) · lines 2297–2333
47
+ - [27. A repeat and its next time](#27-a-repeat-and-its-next-time) · lines 2335–2384
48
48
 
49
49
  <!-- /index -->
50
50
 
@@ -856,17 +856,21 @@ A value on the record's view that turns into **the form's own control**
856
856
  where it's shown, and saves when you leave it: a title, a status, a
857
857
  price, notes, a list of linked records. Widget's view is the reference
858
858
  (`src/routes/widgets/widget-view.tsx`): Name (the title), Status (its
859
- header badge), Price, Description (rich text that autosaves) and Extra
860
- Categories, with the controls in `widget-fields.tsx`, the same ones the
861
- form uses.
859
+ header badge), Price, Description (rich text edited where it's read,
860
+ `inline`) and Extra Categories, with the controls in `widget-fields.tsx`,
861
+ the same ones the form uses.
862
862
 
863
863
  The rule behind every part of it: **nothing typed is ever lost.**
864
864
 
865
- **No toast, ever.** An edit in place says what happened where it
865
+ **No toast, but one.** An edit in place says what happened where it
866
866
  happened: "Saving…" and "Saved" beside the value, a refusal's reason
867
867
  under it. A toast after one would repeat what the person just watched
868
868
  (add-an-entity.md "Toasts and feedback": a toast is for what happened
869
- out of sight).
869
+ out of sight). The one exception is notes that save themselves
870
+ (`autosave`, `alwaysEditable`, `inline`): the first refusal or failed
871
+ save of a run also toasts ("Couldn't save Description", the reason
872
+ under it), since the person is typing, not watching the line, and on a
873
+ long note the line can be a screen away.
870
874
 
871
875
  **Which values.** Only those the plan's "View screen" names under `Edit
872
876
  in place`; read-only is the default, and a value not named renders
@@ -920,7 +924,7 @@ Save button, no Undo:
920
924
  | Kind (`editInPlace({ kind })`) | Saves on | Esc |
921
925
  |---|---|---|
922
926
  | `text`: one line | Enter, or leaving it | puts the saved value back |
923
- | `long-text`: notes, rich text for Markdown | Ctrl/Cmd+Enter, or leaving it (Enter is a new line); with `autosave`, also a pause in typing | the same; with `autosave`, saves what's left and closes |
927
+ | `long-text`: notes, rich text for Markdown | Ctrl/Cmd+Enter, or leaving it (Enter is a new line); with `autosave`, also a pause in typing | a changed draft asks "Discard your changes?" first (unchanged closes); with `autosave`, saves what's left and closes |
924
928
  | `choice`: a select, a switch, a single reference | the pick (its list opens with the field, non-modal) | closes the list with nothing picked: gives up |
925
929
  | `multi`: a multi reference | leaving it, or Ctrl/Cmd+Enter (Enter picks) | closes the list first; Esc again gives up |
926
930
  | `multi` over a small set (`MultiPick`) | each click, on its own | closes it: every pick is already saved |
@@ -1035,19 +1039,44 @@ nobody has to click away to save notes. Opt in per field:
1035
1039
  is by then, so saves never cross and the latest always wins.
1036
1040
  - Under the text, a quiet line in the muted caption tone
1037
1041
  (`role="status"`): "Saving…" with a spinner while a save is in flight,
1038
- "Saved" with a check once nothing typed is waiting. No toast.
1042
+ "Saved" with a check once nothing typed is waiting. **On a note longer
1043
+ than the screen the line is pinned to the screen's bottom edge** while
1044
+ the note runs past it, so the save's state and a refusal are never off
1045
+ screen.
1039
1046
  - **Refused:** exactly what was typed stays, with the reason under it, as
1040
- above. Typing again retries after the pause; a refused draft is never
1041
- re-sent on its own.
1047
+ above, and the first refusal of a run toasts. Typing again retries
1048
+ after the pause; a refused draft is never re-sent on its own.
1049
+ - **Saved elsewhere** (another tab, a phone, an AI chat; the record's
1050
+ query refetches): with nothing typed waiting, the note shows the new
1051
+ text at once, even with the caret in it, which keeps its paragraph.
1052
+ Under unsaved typing nothing saves over it: the line says it "changed
1053
+ elsewhere", with **Keep Mine** (save what's typed over it) and **Show
1054
+ Saved** (drop what's typed). The server sending back what it was sent,
1055
+ even trimmed, is not a change: the editor keeps its undo.
1056
+ - **Leaving mid-save:** a field that leaves the view while a save is in
1057
+ flight (a session ending, a parent that stops showing it) still sends
1058
+ what was typed after that save started.
1042
1059
  - **Esc saves what's left and closes.** Nothing reverts: what was saved a
1043
1060
  second ago stays saved, so "give up" would only drop the last second.
1044
1061
  - Rich text that can't save without rewriting what the person didn't edit
1045
- (`RichTextEditor`'s `onProblem`) saves nothing; its message shows after
1046
- the pause, and the next good edit saves.
1062
+ (`RichTextEditor`'s `onProblem`) saves nothing; it counts as unsaved at
1063
+ once (leaving asks straight away), its message shows after the pause,
1064
+ and the next good edit saves.
1047
1065
  - **Leaving the page** with a save still to come saves it first and goes
1048
1066
  on; "Discard your changes?" shows only if that save is refused. Closing
1049
1067
  the tab can't wait: it starts the save and the browser asks. Hiding the
1050
- page (another tab, a phone's home screen) saves too.
1068
+ page (another tab, a phone's home screen) saves at once, with no pause.
1069
+ A save started as the page goes is sent with `keepalive` when its body
1070
+ fits (about 30 KB of JSON), so the browser finishes it after the page
1071
+ is gone; a longer note's save goes as an ordinary request.
1072
+
1073
+ **Notes are edited where they're read by default (`inline: true`)** (the
1074
+ developer, 2026-11-17): a record's notes, a description, any long text
1075
+ the page is for. `alwaysEditable` (the boxed editor at rest) and
1076
+ `autosave` alone (the read view at rest, a click opens the editor) are
1077
+ for where that doesn't fit, such as a short summary beside other values.
1078
+ Opening one by a click puts the caret where the click was, and the page
1079
+ doesn't move.
1051
1080
 
1052
1081
  **Always editable (`alwaysEditable: true`, implies `autosave`)**: the
1053
1082
  notes are the editor itself, shown at rest, with no pencil and no click
@@ -1087,13 +1116,13 @@ notes: editInPlace({
1087
1116
  ```
1088
1117
 
1089
1118
  ```tsx
1090
- description: editInPlace({
1119
+ summary: editInPlace({
1091
1120
  kind: 'long-text',
1092
- autosave: true, // or alwaysEditable: true, with no autoFocus on the control
1093
- value: widget.description,
1094
- schema: widgetFormSchema.shape.description,
1095
- save: (description) => editField.mutateAsync({ description }),
1096
- control: (props) => <WidgetDescriptionEditor {...} />,
1121
+ autosave: true, // not notes: a click opens it (autoFocus on the control)
1122
+ value: widget.summary,
1123
+ schema: widgetFormSchema.shape.summary,
1124
+ save: (summary) => editField.mutateAsync({ summary }),
1125
+ control: (props) => <WidgetSummaryEditor {...} />,
1097
1126
  }),
1098
1127
  ```
1099
1128
 
@@ -1132,7 +1161,14 @@ const price = editInPlace({
1132
1161
  (a count shows from 80% of it, in the destructive text tone once over).
1133
1162
  Its keys: Ctrl/Cmd+K adds or edits a link (web and email addresses
1134
1163
  only), Ctrl/Cmd+Shift+Enter ticks the task item the caret is in, and
1135
- Markdown pasted as plain text arrives formatted. Notion's block keys
1164
+ Markdown pasted as plain text arrives formatted. A web or email address
1165
+ typed (on a space or Enter) or pasted becomes a link, and one pasted
1166
+ over selected words links them; pasted lines stay lines, Word's and
1167
+ Notion's lists and to-dos arrive as lists and task items. An edit it
1168
+ can't save without rewriting text nobody touched is never saved: on a
1169
+ form, bind its `onProblem` to the field's error and refuse submit while
1170
+ it stands (add-an-entity.md, `widget-form.tsx`); with no `onProblem` it
1171
+ says so inside the field. Notion's block keys
1136
1172
  work: Ctrl+Shift+1 to 3 for headings, +4 tasks, +5 bullets, +6 numbers,
1137
1173
  +8 a code block, +0 back to text (Cmd+Option on a Mac), and
1138
1174
  Ctrl/Cmd+Shift+S strikes through. Ctrl/Cmd+Enter stays the save, in a
@@ -1163,7 +1199,12 @@ const price = editInPlace({
1163
1199
  saved by it), and on a touch screen or under 768px it carries Indent
1164
1200
  and Outdent for list items, where there is no Tab. A field with only the
1165
1201
  floating toolbar (`inline` notes) gets the same two in a small "Editor
1166
- tools" strip over its corner while it has focus. A new checklist item
1202
+ tools" strip over its corner while it has focus. On a touch screen the
1203
+ toolbar is instead one row pinned to the top of the keyboard while the
1204
+ field has focus (Aa for every format, in the keyboard's place; the list
1205
+ buttons, Insert and Undo; with words selected, their formats first, and
1206
+ no floating bar under the system's Copy bar), and the checkbox, the
1207
+ table grips, the fold button and the callout icon take a 40px tap. A new checklist item
1167
1208
  shows a "To-do" placeholder and the caret until you type. `[] ` (or
1168
1209
  `[x] `) at a line's start makes it a checklist item, a bulleted item
1169
1210
  too; Enter in one makes the next, its box unticked, and Enter in an
@@ -3,6 +3,7 @@
3
3
  // no-restricted-imports / no-restricted-syntax rules in eslint.config.js.
4
4
  // Owns the base URL and the raw HTTP call; knows nothing about widgets,
5
5
  // pagination, or error shapes — that translation is the gateway's job.
6
+ import { keepaliveFor } from "../../lib/page-leaving.js";
6
7
  const BASE_URL = "/api";
7
8
  // Sent unless the caller set them: they tell a proxy in front of the app
8
9
  // that this is a script asking for JSON, not a page, so a proxy that can
@@ -22,7 +23,15 @@ export async function apiFetch(path, init) {
22
23
  // error that can't be told from being offline; not followed, it comes
23
24
  // back as an opaque redirect the gateway can name. A caller can still
24
25
  // pass `redirect: "follow"`.
25
- const response = await fetch(`${BASE_URL}${path}`, { ...init, headers, redirect: init?.redirect ?? "manual" });
26
+ // Started as the page goes (an autosave on closing the tab): the browser
27
+ // finishes it after the page is gone, when the body fits (lib/page-leaving.ts).
28
+ const keepalive = init?.keepalive ?? (keepaliveFor(init?.body) || undefined);
29
+ const response = await fetch(`${BASE_URL}${path}`, {
30
+ ...init,
31
+ headers,
32
+ redirect: init?.redirect ?? "manual",
33
+ ...(keepalive ? { keepalive } : {}),
34
+ });
26
35
  if (response.type === "opaqueredirect") {
27
36
  return { status: response.status, body: undefined, headers: response.headers, foreign: "opaque-redirect" };
28
37
  }
@@ -0,0 +1,25 @@
1
+ export type CaretSpot = {
2
+ /** The block's text. */
3
+ text: string;
4
+ /** Which of the blocks with that text it is (0 for the first). */
5
+ nth: number;
6
+ /** Its place among all the blocks: the fallback when no block has its text. */
7
+ index: number;
8
+ /** The caret's offset in the block's text. */
9
+ offset: number;
10
+ };
11
+ /** The caret's spot in `root`, or null when it isn't in a block there. */
12
+ export declare function caretSpot(root: Element): CaretSpot | null;
13
+ /** The spot a click at (x, y) points at in `root` (the read view). */
14
+ export declare function spotAtPoint(root: Element, x: number, y: number): CaretSpot | null;
15
+ /**
16
+ * Puts the caret at `spot` in an editable `root` and brings its block into
17
+ * view if it isn't (no jump when it is). False when `root` has no blocks yet.
18
+ */
19
+ export declare function placeCaret(root: HTMLElement, spot: CaretSpot): boolean;
20
+ /**
21
+ * Puts the caret at `spot` once the editor in `container` has drawn its
22
+ * text (a rich-text editor builds itself a moment after it mounts), then
23
+ * once more in the frame after, past the editor's own first focus.
24
+ */
25
+ export declare function placeCaretWhenReady(container: () => Element | null, spot: CaretSpot, frames?: number): () => void;
@@ -0,0 +1,118 @@
1
+ // Where the caret is in a block of text, kept across the control starting
2
+ // over (editable-value.tsx): a value saved elsewhere reloading under the
3
+ // caret (F4), and a click-to-open note opening where it was clicked (F8),
4
+ // the read view's text becoming the editor's.
5
+ //
6
+ // A spot is the innermost block holding the caret (a paragraph, a list
7
+ // item's text, a heading, a cell), told apart by its text and which of
8
+ // the blocks with that text it is, and the caret's offset in its text.
9
+ // Matching by text, not position, survives the read view and the editor
10
+ // nesting blocks differently (a tight list's item is a paragraph in the
11
+ // editor); the block's place among all blocks is the fallback when its
12
+ // text changed (the reload changed that block).
13
+ const BLOCKS = 'p, li, h1, h2, h3, h4, h5, h6, pre, blockquote, td, th, dt, dd, summary';
14
+ // The blocks that hold no other block: the ones text is typed into.
15
+ function leafBlocks(root) {
16
+ return [...root.querySelectorAll(BLOCKS)].filter((block) => !block.querySelector(BLOCKS));
17
+ }
18
+ function spotIn(root, node, offset) {
19
+ const element = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
20
+ const blocks = leafBlocks(root);
21
+ const block = blocks.find((candidate) => candidate.contains(element));
22
+ if (!block)
23
+ return null;
24
+ const text = block.textContent ?? '';
25
+ const range = document.createRange();
26
+ range.setStart(block, 0);
27
+ range.setEnd(node, offset);
28
+ return {
29
+ text,
30
+ nth: blocks.filter((candidate) => (candidate.textContent ?? '') === text).indexOf(block),
31
+ index: blocks.indexOf(block),
32
+ offset: range.toString().length,
33
+ };
34
+ }
35
+ /** The caret's spot in `root`, or null when it isn't in a block there. */
36
+ export function caretSpot(root) {
37
+ const selection = document.getSelection();
38
+ if (!selection?.anchorNode || !root.contains(selection.anchorNode))
39
+ return null;
40
+ return spotIn(root, selection.anchorNode, selection.anchorOffset);
41
+ }
42
+ /** The spot a click at (x, y) points at in `root` (the read view). */
43
+ export function spotAtPoint(root, x, y) {
44
+ const doc = document;
45
+ const position = doc.caretPositionFromPoint?.(x, y);
46
+ if (position)
47
+ return root.contains(position.offsetNode) ? spotIn(root, position.offsetNode, position.offset) : null;
48
+ const range = doc.caretRangeFromPoint?.(x, y);
49
+ if (range)
50
+ return root.contains(range.startContainer) ? spotIn(root, range.startContainer, range.startOffset) : null;
51
+ return null;
52
+ }
53
+ /**
54
+ * Puts the caret at `spot` in an editable `root` and brings its block into
55
+ * view if it isn't (no jump when it is). False when `root` has no blocks yet.
56
+ */
57
+ export function placeCaret(root, spot) {
58
+ const blocks = leafBlocks(root);
59
+ if (blocks.length === 0)
60
+ return false;
61
+ const same = blocks.filter((block) => (block.textContent ?? '') === spot.text);
62
+ const block = same[Math.min(spot.nth, same.length - 1)] ?? blocks[Math.min(spot.index, blocks.length - 1)];
63
+ const walker = document.createTreeWalker(block, NodeFilter.SHOW_TEXT);
64
+ let left = Math.min(spot.offset, (block.textContent ?? '').length);
65
+ let node = walker.nextNode();
66
+ let target = { node: block, offset: 0 };
67
+ while (node) {
68
+ const length = node.textContent?.length ?? 0;
69
+ if (left <= length) {
70
+ target = { node, offset: left };
71
+ break;
72
+ }
73
+ left -= length;
74
+ const next = walker.nextNode();
75
+ if (!next)
76
+ target = { node, offset: length };
77
+ node = next;
78
+ }
79
+ if (document.activeElement !== root)
80
+ root.focus({ preventScroll: true });
81
+ document.getSelection()?.collapse(target.node, target.offset);
82
+ const box = block.getBoundingClientRect();
83
+ if (box.bottom < 0 || box.top > window.innerHeight)
84
+ block.scrollIntoView({ block: 'center' });
85
+ return true;
86
+ }
87
+ /**
88
+ * Puts the caret at `spot` once the editor in `container` has drawn its
89
+ * text (a rich-text editor builds itself a moment after it mounts), then
90
+ * once more in the frame after, past the editor's own first focus.
91
+ */
92
+ export function placeCaretWhenReady(container, spot, frames = 60) {
93
+ let left = frames;
94
+ let placed = false;
95
+ let handle = 0;
96
+ // Once the person acts (a key, a click), the caret is theirs.
97
+ const stop = () => {
98
+ cancelAnimationFrame(handle);
99
+ document.removeEventListener('keydown', stop, true);
100
+ document.removeEventListener('pointerdown', stop, true);
101
+ };
102
+ const step = () => {
103
+ const editable = container()?.querySelector('[contenteditable="true"]');
104
+ if (editable && placeCaret(editable, spot)) {
105
+ if (placed)
106
+ return stop();
107
+ placed = true;
108
+ }
109
+ if (--left > 0)
110
+ handle = requestAnimationFrame(step);
111
+ else
112
+ stop();
113
+ };
114
+ document.addEventListener('keydown', stop, true);
115
+ document.addEventListener('pointerdown', stop, true);
116
+ handle = requestAnimationFrame(step);
117
+ return stop;
118
+ }
@@ -55,6 +55,12 @@ export type OpenFieldState = {
55
55
  autosave?: 'saving' | 'saved';
56
56
  /** Counts the times an always-editable field started over from a value saved elsewhere (`refresh`). */
57
57
  revision?: number;
58
+ /**
59
+ * The saved value changed elsewhere while this held unsaved typing:
60
+ * nothing saves until `keepMine` (save over it) or `takeSaved` (show it).
61
+ * `markConflict` sets it too: the seam for a server's 409 (Roadmap 405).
62
+ */
63
+ conflict?: boolean;
58
64
  };
59
65
  /** How long typing has to stop before an autosaving field saves. */
60
66
  export declare const AUTOSAVE_DELAY_MS = 1000;
@@ -62,6 +68,8 @@ export type EditInPlaceStoreOptions = {
62
68
  /** The pause before an autosave, in ms. Defaults to AUTOSAVE_DELAY_MS. */
63
69
  autosaveDelay?: number;
64
70
  };
71
+ /** What a field shows when the saved value changed under unsaved typing. */
72
+ export declare const CONFLICT_MESSAGE = "This changed elsewhere (another tab, device or chat) since you started typing. Saving now replaces that.";
65
73
  /** Why a save failed, in words to show beside what was being saved. */
66
74
  export declare function messageOf(error: unknown): string;
67
75
  export declare class EditInPlaceStore {
@@ -76,12 +84,17 @@ export declare class EditInPlaceStore {
76
84
  private queued;
77
85
  private always;
78
86
  private holds;
87
+ private seen;
88
+ private sent;
89
+ private detached;
90
+ private hurried;
79
91
  constructor(options?: EditInPlaceStoreOptions);
80
92
  subscribe: (listener: () => void) => () => void;
81
93
  private emit;
82
94
  private set;
83
95
  /** A field joins the view. `config` is read fresh each time it's needed. */
84
96
  register(key: string, config: () => EditFieldConfig): () => void;
97
+ private sendDetached;
85
98
  state(key: string): EditFieldState;
86
99
  /** The field that's open, if any. An always-editable one never counts. */
87
100
  get open(): string | null;
@@ -98,7 +111,10 @@ export declare class EditInPlaceStore {
98
111
  hold(): () => void;
99
112
  /** Whether leaving the page now would lose something: a draft that isn't saved. */
100
113
  get dirty(): boolean;
101
- /** Whether everything unsaved saves on its own, so leaving can save it first rather than ask. */
114
+ /**
115
+ * Whether everything unsaved saves on its own, so leaving can save it
116
+ * first rather than ask. A problem or a conflict can't: leaving asks at once.
117
+ */
102
118
  get savesOnLeave(): boolean;
103
119
  private unsaved;
104
120
  private isEqual;
@@ -128,6 +144,13 @@ export declare class EditInPlaceStore {
128
144
  commit(key: string, draft?: unknown): Promise<boolean>;
129
145
  private commitAutosaved;
130
146
  private schedule;
147
+ /**
148
+ * The page is hidden (another tab, a phone's home screen, F13): while it
149
+ * is, an autosave goes without the pause, and one waiting goes now.
150
+ */
151
+ hurry(hidden: boolean): void;
152
+ private remember;
153
+ private isEcho;
131
154
  private clearTimer;
132
155
  /**
133
156
  * Saves an autosaving field's latest draft now. With a save in flight,
@@ -142,11 +165,27 @@ export declare class EditInPlaceStore {
142
165
  */
143
166
  saveAll(): Promise<boolean>;
144
167
  /**
145
- * An always-editable field shows the saved value again when it changed
146
- * elsewhere (another tab, the form), but only while nothing of its own
147
- * is unsaved or saving. True when it did: the control starts over.
168
+ * The field's saved value (its config's `value`) may have changed
169
+ * elsewhere: another tab, a phone, an AI chat, the form. Call it whenever
170
+ * the value changes. An open autosaving field with nothing of its own unsaved or
171
+ * saving shows it, starting its control over (`revision`): true when it
172
+ * did, so the caret can be put back (F4). One with unsaved typing gets a
173
+ * conflict (`conflict`, its message), and nothing saves until the person
174
+ * picks. The field's own save coming back, as sent or as the server
175
+ * normalised it (trimmed), is no change: the control keeps its text and
176
+ * its undo (F25).
148
177
  */
149
178
  refresh(key: string): boolean;
179
+ /**
180
+ * The saved value changed under this field's unsaved typing, as a
181
+ * server's conflict answer says: the seam for a version check's 409
182
+ * (Roadmap 405). Nothing saves until the person picks.
183
+ */
184
+ markConflict(key: string): void;
185
+ /** A conflict, answered "keep mine": what's typed saves over the value saved elsewhere. */
186
+ keepMine(key: string): Promise<boolean>;
187
+ /** A conflict, answered "show the saved one": what's typed goes, and the control starts over from the saved value. */
188
+ takeSaved(key: string): void;
150
189
  /**
151
190
  * Esc: closes and shows the saved value again. Not while a save is in
152
191
  * flight, and never for an always-editable field.