@tristan2828/ui-foundation 4.125.0 → 4.127.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 (94) hide show
  1. package/README.md +1 -1
  2. package/conventions/docs/add-an-entity.md +140 -35
  3. package/conventions/docs/cell-patterns.md +144 -56
  4. package/conventions/docs/design-language.md +45 -13
  5. package/dist/api/contracts.d.ts +8 -1
  6. package/dist/api/gateway/errors.js +4 -0
  7. package/dist/api/schema.d.ts +9 -0
  8. package/dist/api/transport/index.js +10 -1
  9. package/dist/components/app/data-table-tools.d.ts +12 -0
  10. package/dist/components/app/data-table-tools.js +2 -2
  11. package/dist/components/app/data-table.d.ts +2 -1
  12. package/dist/components/app/data-table.js +1 -1
  13. package/dist/components/app/edit-caret.d.ts +25 -0
  14. package/dist/components/app/edit-caret.js +118 -0
  15. package/dist/components/app/edit-in-place-presets.d.ts +51 -1
  16. package/dist/components/app/edit-in-place-presets.js +30 -0
  17. package/dist/components/app/edit-in-place-store.d.ts +70 -4
  18. package/dist/components/app/edit-in-place-store.js +219 -21
  19. package/dist/components/app/edit-in-place.d.ts +11 -0
  20. package/dist/components/app/editable-value.js +202 -25
  21. package/dist/components/app/entity-form.js +4 -0
  22. package/dist/components/app/entity-view.js +5 -1
  23. package/dist/components/app/equal-items.d.ts +32 -6
  24. package/dist/components/app/equal-items.js +59 -8
  25. package/dist/components/app/error-state.js +1 -0
  26. package/dist/components/app/form-leave-guard.js +7 -1
  27. package/dist/components/app/milkdown-editor.d.ts +1 -0
  28. package/dist/components/app/milkdown-editor.js +226 -64
  29. package/dist/components/app/pill-filter.d.ts +16 -0
  30. package/dist/components/app/pill-filter.js +22 -1
  31. package/dist/components/app/prose-look.d.ts +1 -1
  32. package/dist/components/app/prose-look.js +3 -1
  33. package/dist/components/app/rating-input.d.ts +22 -0
  34. package/dist/components/app/rating-input.js +65 -0
  35. package/dist/components/app/rating-score.d.ts +2 -1
  36. package/dist/components/app/rating-score.js +2 -6
  37. package/dist/components/app/rich-text-autolink.d.ts +6 -0
  38. package/dist/components/app/rich-text-autolink.js +79 -0
  39. package/dist/components/app/rich-text-edges.d.ts +8 -0
  40. package/dist/components/app/rich-text-edges.js +144 -0
  41. package/dist/components/app/rich-text-editor.d.ts +19 -4
  42. package/dist/components/app/rich-text-editor.js +19 -6
  43. package/dist/components/app/rich-text-empty-paragraph.d.ts +14 -6
  44. package/dist/components/app/rich-text-empty-paragraph.js +19 -8
  45. package/dist/components/app/rich-text-formats.js +88 -15
  46. package/dist/components/app/rich-text-full-screen.d.ts +2 -0
  47. package/dist/components/app/rich-text-full-screen.js +78 -0
  48. package/dist/components/app/rich-text-highlight-menu.d.ts +3 -1
  49. package/dist/components/app/rich-text-highlight-menu.js +3 -2
  50. package/dist/components/app/rich-text-input-rules.d.ts +7 -0
  51. package/dist/components/app/rich-text-input-rules.js +83 -0
  52. package/dist/components/app/rich-text-keyboard-bar.d.ts +24 -0
  53. package/dist/components/app/rich-text-keyboard-bar.js +215 -0
  54. package/dist/components/app/rich-text-node-views.js +2 -1
  55. package/dist/components/app/rich-text-paste.d.ts +43 -0
  56. package/dist/components/app/rich-text-paste.js +355 -0
  57. package/dist/components/app/rich-text-shortcuts.d.ts +5 -1
  58. package/dist/components/app/rich-text-shortcuts.js +132 -2
  59. package/dist/components/app/rich-text-slash-menu.js +47 -9
  60. package/dist/components/app/rich-text-slash.d.ts +7 -0
  61. package/dist/components/app/rich-text-slash.js +27 -14
  62. package/dist/components/app/rich-text-table-grips.d.ts +8 -6
  63. package/dist/components/app/rich-text-table-grips.js +11 -12
  64. package/dist/components/app/rich-text-tasks.d.ts +8 -0
  65. package/dist/components/app/rich-text-tasks.js +20 -0
  66. package/dist/components/app/rich-text-toolbar.d.ts +5 -1
  67. package/dist/components/app/rich-text-toolbar.js +14 -6
  68. package/dist/components/app/rich-text-tools-bar.d.ts +3 -1
  69. package/dist/components/app/rich-text-tools-bar.js +2 -2
  70. package/dist/components/app/rich-text-touch.d.ts +2 -0
  71. package/dist/components/app/rich-text-touch.js +18 -0
  72. package/dist/components/app/rich-text-widgets.js +1 -1
  73. package/dist/hooks/table-url-changes.d.ts +4 -0
  74. package/dist/hooks/table-url-changes.js +13 -0
  75. package/dist/hooks/use-record-update.d.ts +13 -1
  76. package/dist/hooks/use-record-update.js +17 -3
  77. package/dist/hooks/use-table-url-state.js +14 -8
  78. package/dist/index.d.ts +5 -2
  79. package/dist/index.js +8 -0
  80. package/dist/lib/markdown-merge.d.ts +38 -0
  81. package/dist/lib/markdown-merge.js +202 -17
  82. package/dist/lib/page-leaving.d.ts +8 -0
  83. package/dist/lib/page-leaving.js +30 -0
  84. package/dist/lib/pending-edits.d.ts +14 -0
  85. package/dist/lib/pending-edits.js +51 -0
  86. package/dist/lib/rating-glyphs.d.ts +3 -0
  87. package/dist/lib/rating-glyphs.js +7 -0
  88. package/dist/mocks/e2e-hooks.js +10 -0
  89. package/dist/mocks/override.d.ts +8 -0
  90. package/dist/testing/index.d.ts +40 -2
  91. package/dist/testing/index.js +101 -7
  92. package/openapi/foundation.yaml +12 -0
  93. package/package.json +1 -1
  94. package/styles/index.css +7 -0
@@ -30,14 +30,14 @@
30
30
  - [A list as cards](#a-list-as-cards) · lines 1308–1354
31
31
  - [Key numbers on a record](#key-numbers-on-a-record) · lines 1356–1392
32
32
  - [Parts of the page standards](#parts-of-the-page-standards) · lines 1394–1464
33
- - [A few equal things](#a-few-equal-things) · lines 1466–1550
34
- - [An overview page](#an-overview-page) · lines 1552–1623
35
- - [A record's header and empty values](#a-records-header-and-empty-values) · lines 1624–1690
36
- - [A record's tabs, mark and facts](#a-records-tabs-mark-and-facts) · lines 1692–1816
37
- - [Picking at random](#picking-at-random) · lines 1818–1849
38
- - [Filling in what's missing](#filling-in-whats-missing) · lines 1851–1918
39
- - [Values edited in place: the presets' looks](#values-edited-in-place-the-presets-looks) · lines 1920–1945
40
- - [The sidebar and the phone's bar](#the-sidebar-and-the-phones-bar) · lines 1947–2043
33
+ - [A few equal things](#a-few-equal-things) · lines 1466–1569
34
+ - [An overview page](#an-overview-page) · lines 1571–1642
35
+ - [A record's header and empty values](#a-records-header-and-empty-values) · lines 1643–1709
36
+ - [A record's tabs, mark and facts](#a-records-tabs-mark-and-facts) · lines 1711–1848
37
+ - [Picking at random](#picking-at-random) · lines 1850–1881
38
+ - [Filling in what's missing](#filling-in-whats-missing) · lines 1883–1950
39
+ - [Values edited in place: the presets' looks](#values-edited-in-place-the-presets-looks) · lines 1952–1977
40
+ - [The sidebar and the phone's bar](#the-sidebar-and-the-phones-bar) · lines 1979–2075
41
41
 
42
42
  <!-- /index -->
43
43
 
@@ -1467,8 +1467,8 @@ Every one is measured with axe and the glyph check in both themes
1467
1467
 
1468
1468
  `EqualItems` (4.93, record standard R10): a small set of equal, related
1469
1469
  things inside a record (a plan's phases, the stores a price is compared
1470
- at, a handful of options), one data shape in four looks. A record picks
1471
- one look per set; a fifth is asked for first.
1470
+ at, a handful of options), one data shape in five looks. A record picks
1471
+ one look per set; a sixth is asked for first.
1472
1472
 
1473
1473
  ```tsx
1474
1474
  <EqualItems
@@ -1490,6 +1490,7 @@ one look per set; a fifth is asked for first.
1490
1490
  | `table` | one compact row per item, the title as its row header, a column per field label (first-seen order), a dash where an item has none; scrolls sideways in its own box on a phone | things compared on the same values (a price at each store) |
1491
1491
  | `featured` | the item `featuredId` names in full, in a card with the accent border, then the rest as toggles that open in place | one is current or best (a program's phases) |
1492
1492
  | `panels` | a panel per item side by side, its title and state in a muted band, every detail labelled above its value; stacked on a phone | each has several details and must read as separate |
1493
+ | `stepper` (4.127) | a row of numbered steps joined by a line, each done, current or upcoming, picking the one item whose panel shows under it; opens on the current step; the row scrolls sideways in its own box on a phone | a sequence with one running and the others looked at in turn (a program's phases), where `featured`'s toggles would stack every phase's long content |
1493
1494
 
1494
1495
  - **A state is a badge**, the outline style in its tone (`state: 'Planned'`
1495
1496
  is the neutral one; `{ label, tone }` with `info`, `success`, `warning`
@@ -1501,6 +1502,24 @@ one look per set; a fifth is asked for first.
1501
1502
  Enter or Space opens one, Tab moves to the next, several can be open,
1502
1503
  `aria-expanded` says which. Never a link; `defaultOpenIds` opens some at
1503
1504
  first.
1505
+ - **The stepper** (4.127): each item's `step` is `done` (filled with
1506
+ the primary, a check), `current` (ringed, "Current" under its name, its
1507
+ panel's border the accent) or `upcoming` (outlined, the default); the
1508
+ line into a step is the primary up to the current one. It opens on
1509
+ `featuredId`, else the `current` step, else the first; the shown step
1510
+ has a ring round its mark and its name semibold. The steps are a
1511
+ tablist named `label`: arrow keys, Home and End move and pick, Tab goes
1512
+ on into the panel, and the current step is `aria-current="step"`. A
1513
+ step's name is what it shows plus hidden words ("Step 2: Phase 2:
1514
+ Build, done"), never an `aria-label`. An app that keeps the shown step
1515
+ (in the URL as `?phase=`) passes `selectedId` and `onSelectedChange`.
1516
+ `attention` ("needs an answer") puts a small warning dot on a step and
1517
+ those words in its name, for something in a panel not shown (an
1518
+ unsaved change waiting on an answer). **On a phone** the row stays a
1519
+ row: each step at least 4.5rem wide and 44px tall, scrolling sideways
1520
+ in its own box (never the page) as the record's tab bar does, the
1521
+ shown step kept in view; it never folds into a select, which would
1522
+ hide the done and current marks the stepper is for.
1504
1523
  - **Empty**: no items reads `emptyText` ("Nothing yet"), an item with no
1505
1524
  fields `noFieldsText` ("No details"). `label` names the set for a screen
1506
1525
  reader (the list's name, the table's caption); titles are `h3` under a
@@ -1546,7 +1565,7 @@ items={stores.map((store) => ({
1546
1565
 
1547
1566
  Measured with axe, the token check and the glyph check in both themes and
1548
1567
  every palette (fixtures `app/EqualItems`, "Content and actions" among
1549
- them), and from the keyboard and at a phone's width in
1568
+ them, and "Stepper"), and from the keyboard and at a phone's width in
1550
1569
  `e2e/equal-items.spec.ts`.
1551
1570
 
1552
1571
  ## An overview page
@@ -1776,8 +1795,21 @@ its short facts the last tab, Details. A mark goes left of the title.
1776
1795
  that's what a screen reader hears, one image named in words. The
1777
1796
  glyphs are a fixed size, so the value never moves on hover, and it's
1778
1797
  drawn the same in Details on a phone. An empty one reads its
1779
- `emptyLabel` ("Not rated"), not a row of empty stars. Edited in place
1780
- like any fact (`edit`), usually `inPlace.select` over the scores.
1798
+ `emptyLabel` ("Not rated"), not a row of empty stars. A score the
1799
+ person sets is edited with `inPlace.rating` (4.127): the stars become
1800
+ `RatingInput`, set by a click where they're drawn (no select to open),
1801
+ and an empty one is then five empty stars to click. "Saving…" and
1802
+ "Saved" are an icon beside the stars, words for a screen reader, so the
1803
+ row never grows. On a touch screen each star is a 44px target and the
1804
+ row puts its label above them, which a narrow value column can't hold.
1805
+ - **`RatingInput`** (4.127): RatingScore's glyphs and tokens as a radio
1806
+ group named by the field's label, each star a radio ("2 of 5"). The
1807
+ arrow keys move and set it, a click or Space sets the star it's on,
1808
+ pressing the set star again clears it. A mouse's hover previews the
1809
+ score in the same ink (the filled count is the preview; leaving puts it
1810
+ back); a finger gets no preview. 24px targets on a laptop, 44px on a
1811
+ touch screen, fixed-size either way. Disabled, it's the score at half
1812
+ opacity and ignores the pointer.
1781
1813
  - **A yes/no** (`kind: 'switch'`, 4.120) is a switch on the value's
1782
1814
  line, never a two-choice select: `checked`, `onCheckedChange` (return
1783
1815
  the save's promise and the switch shows the new state, busy, until it
@@ -11,8 +11,15 @@ export type AppError = {
11
11
  * lapsed, not from the app: a page or a redirect where JSON was
12
12
  * expected. Only a full page load signs in again. Not the app's own
13
13
  * session, which is `auth`.
14
+ *
15
+ * `conflict` (a 409): the save was refused because the record changed
16
+ * since the version it was built on (another tab, a phone, an AI chat
17
+ * saved in between). Nothing was written: fetch the record again and
18
+ * let the person choose. `useRecordUpdate` refetches it, and editing in
19
+ * place asks "This changed elsewhere" (docs/foundation/add-an-entity.md
20
+ * "Saves that don't overwrite").
14
21
  */
15
- kind: "validation" | "notfound" | "auth" | "rate_limited" | "server" | "network" | "proxy_auth";
22
+ kind: "validation" | "notfound" | "auth" | "rate_limited" | "conflict" | "server" | "network" | "proxy_auth";
16
23
  message: string;
17
24
  fieldErrors?: Record<string, string[]>;
18
25
  /**
@@ -89,6 +89,10 @@ function translate(status, body, headers) {
89
89
  return { kind: "notfound", message };
90
90
  if (status === 401)
91
91
  return { kind: "auth", message };
92
+ // The record changed since the version the save was built on: nothing
93
+ // was written (ConflictError in openapi/foundation.yaml).
94
+ if (status === 409)
95
+ return { kind: "conflict", message };
92
96
  if (status === 429) {
93
97
  const retryAfterSeconds = parseRetryAfter(headers?.get("retry-after") ?? null);
94
98
  return retryAfterSeconds === undefined
@@ -330,6 +330,15 @@ export interface components {
330
330
  "application/json": components["schemas"]["HTTPErrorBody"];
331
331
  };
332
332
  };
333
+ /** @description The record changed since the version the request was built on (another tab, device or AI chat saved in between). Nothing was written. The client fetches the record again and lets the person choose; the gateway's toAppError makes it AppError kind "conflict". */
334
+ ConflictError: {
335
+ headers: {
336
+ [name: string]: unknown;
337
+ };
338
+ content: {
339
+ "application/json": components["schemas"]["HTTPErrorBody"];
340
+ };
341
+ };
333
342
  /** @description The pending sign-in is missing, expired or out of tries. Start again with POST /auth/login. */
334
343
  SignInExpiredError: {
335
344
  headers: {
@@ -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
  }
@@ -11,11 +11,23 @@ export type DataTableView = {
11
11
  label?: string;
12
12
  /** The columns this view shows; while it's on they win over the Columns menu. */
13
13
  columns?: readonly string[];
14
+ /**
15
+ * How many records the view holds, after its label: "Needs a Look · 3"
16
+ * (4.127). The app counts them with its own query; the table doesn't.
17
+ * null, undefined and 0 show no count, as the sidebar's counts and
18
+ * EntityView's tab counts don't, and past 99 it reads "99+". It's part
19
+ * of the pill's name ("Needs a Look, 3"). A view that has the key at all,
20
+ * even undefined while the count loads, keeps room for a two-digit count
21
+ * from the first render, so the pills don't move when it arrives.
22
+ */
23
+ count?: number | null;
14
24
  };
15
25
  export declare function ViewPills({ views, value, onValueChange, label, }: {
16
26
  views: readonly {
17
27
  id: string;
18
28
  label: string;
29
+ count?: number | null;
30
+ counted?: boolean;
19
31
  }[];
20
32
  value: string | null;
21
33
  onValueChange: (id: string) => void;
@@ -5,12 +5,12 @@ import { Button } from '../ui/button.js';
5
5
  import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger, } from '../ui/dropdown-menu.js';
6
6
  import { Skeleton } from '../ui/skeleton.js';
7
7
  import { IconAction } from './icon-action.js';
8
- import { PillFilter } from './pill-filter.js';
8
+ import { PillGroup } from './pill-filter.js';
9
9
  import { togglePick } from './table-columns.js';
10
10
  // The pills on one line that scrolls sideways under 48rem, wrapping wider.
11
11
  // The padding keeps the focus ring inside the scroll box.
12
12
  export function ViewPills({ views, value, onValueChange, label, }) {
13
- return (_jsx("div", { "data-slot": "data-table-views", className: "max-md:-mx-1 max-md:overflow-x-auto max-md:p-1", children: _jsx(PillFilter, { label: label, allLabel: null, options: views.map((view) => ({ value: view.id, label: view.label })),
13
+ return (_jsx("div", { "data-slot": "data-table-views", className: "max-md:-mx-1 max-md:overflow-x-auto max-md:p-1", children: _jsx(PillGroup, { label: label, allLabel: null, options: views.map((view) => ({ value: view.id, label: view.label, count: view.count, counted: view.counted })),
14
14
  // No view's id matches '' (filters set by hand), so none is pressed.
15
15
  value: value ?? '', onValueChange: onValueChange, className: "max-md:w-max max-md:flex-nowrap" }) }));
16
16
  }
@@ -269,7 +269,8 @@ export type DataTableProps<TData extends Record<string, unknown>, TView extends
269
269
  * their order. One is pressed while it's `activeView`; none once the
270
270
  * filters move off every view. Under 48rem they stay on one line that
271
271
  * scrolls sideways. A view with `columns` shows those while it's on, over
272
- * the Columns menu's pick.
272
+ * the Columns menu's pick. A view with `count` shows it after its label
273
+ * ("Needs a Look · 3", 4.127).
273
274
  */
274
275
  views?: Readonly<Record<string, TView>>;
275
276
  /** The view on: useTableUrlState's `activeView`, or null. */
@@ -761,7 +761,7 @@ export function DataTable({ columns, data, total, page, pageSize, onPageChange,
761
761
  const showColumnsMenu = Boolean(columnsMenu) && !showPhoneRows;
762
762
  // The pieces, placed as `look` says: plain, or a framed card.
763
763
  const framed = look === 'framed';
764
- const viewPills = (_jsx(_Fragment, { children: viewEntries.length > 0 ? (_jsx(ViewPills, { label: viewsLabel, views: viewEntries.map(([id, view]) => ({ id, label: view.label ?? id })), value: activeView, onValueChange: (id) => {
764
+ const viewPills = (_jsx(_Fragment, { children: viewEntries.length > 0 ? (_jsx(ViewPills, { label: viewsLabel, views: viewEntries.map(([id, view]) => ({ id, label: view.label ?? id, count: view.count, counted: 'count' in view })), value: activeView, onValueChange: (id) => {
765
765
  const view = views?.[id];
766
766
  if (view)
767
767
  onViewChange?.(view, id);
@@ -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
+ }
@@ -3,7 +3,8 @@ import { type MonthDay } from '../../lib/month-day.js';
3
3
  import { type PlainDate } from '../../lib/plain-date.js';
4
4
  import { type Recurrence, type WeekdayCode } from '../../lib/recurrence.js';
5
5
  import { type ChoiceButtonsOption } from './choice-buttons.js';
6
- import type { EditInPlace } from './edit-in-place.js';
6
+ import { type RatingScoreGlyph } from './rating-score.js';
7
+ import type { EditControlProps, EditInPlace } from './edit-in-place.js';
7
8
  /** What the value saves as: with `required: true` never `null` (a blank is refused). */
8
9
  export type InPlaceSaved<TValue, TRequired extends boolean> = TRequired extends true ? TValue : TValue | null;
9
10
  type Common<TValue, TSaved> = {
@@ -125,6 +126,21 @@ export type InPlaceSelectConfig<T extends string | number, TRequired extends boo
125
126
  emptyLabel?: string;
126
127
  placeholder?: string;
127
128
  };
129
+ /**
130
+ * A score out of a few, set by clicking a star (RatingInput, 4.127). The
131
+ * stars are the value: shown at rest, with no click to open, a click on a
132
+ * star saving it at once. Pressing the set star again saves `null` (none)
133
+ * unless `required`; the arrow keys move and set it, saved a pause after
134
+ * the last one (or on leaving it).
135
+ */
136
+ export type InPlaceRatingConfig<TRequired extends boolean = boolean> = {
137
+ /** Pressing the set star again doesn't clear it: never `null`. */
138
+ required?: TRequired;
139
+ /** How many stars. Defaults to 5. */
140
+ max?: number;
141
+ /** Stars (the default) or hearts. */
142
+ glyph?: RatingScoreGlyph;
143
+ };
128
144
  /** A record found by search, as `search` returns it. */
129
145
  export type InPlaceRecord<Id> = {
130
146
  id: Id;
@@ -248,6 +264,40 @@ export declare const inPlace: {
248
264
  * saves. `inPlace.select` with `look: 'buttons'`.
249
265
  */
250
266
  choice<T extends string | number, R extends boolean = false>(options: Common<T | null | undefined, InPlaceSaved<T, R>> & Omit<InPlaceSelectConfig<T, R>, "look">): EditInPlace;
267
+ /**
268
+ * A score out of a few as stars (or hearts) set by a click (RatingInput):
269
+ * the stars are the value, always there with no click to open, and a
270
+ * click on one saves it. Pressing the set one again saves `null` unless
271
+ * `required`. Reads at rest (printed) as RatingScore.
272
+ */
273
+ rating<R extends boolean = false>(options: Common<number | null | undefined, InPlaceSaved<number, R>> & InPlaceRatingConfig<R>): {
274
+ alwaysEditable: boolean;
275
+ kind: import("./edit-in-place.js").EditKind;
276
+ value: unknown;
277
+ control: (props: EditControlProps<unknown>) => ReactNode;
278
+ schema?: {
279
+ safeParse: (value: unknown) => {
280
+ success: false;
281
+ error: {
282
+ issues: readonly {
283
+ message: string;
284
+ path?: readonly PropertyKey[];
285
+ }[];
286
+ };
287
+ } | {
288
+ success: true;
289
+ data: unknown;
290
+ };
291
+ };
292
+ save: (value: unknown) => Promise<unknown>;
293
+ isEqual?: (a: unknown, b: unknown) => boolean;
294
+ autosave?: boolean;
295
+ inline?: boolean;
296
+ shown?: ReactNode;
297
+ fieldErrors?: (cause: unknown) => Record<string, string> | null;
298
+ errorsOnFields?: boolean;
299
+ rebase?: ((base: unknown, mine: unknown, theirs: unknown) => unknown) | false;
300
+ };
251
301
  /**
252
302
  * Another record, searched as you type through the app's `search`; a
253
303
  * pick saves its id. With `onCreate`, Create "<typed>" makes one.
@@ -10,6 +10,8 @@ import { ChoiceButtons } from './choice-buttons.js';
10
10
  import { DateField } from './date-field.js';
11
11
  import { MonthDayField } from './month-day-field.js';
12
12
  import { OptionSelect } from './option-select.js';
13
+ import { RatingInput } from './rating-input.js';
14
+ import { RatingScore } from './rating-score.js';
13
15
  import { RecurrenceField } from './recurrence-field.js';
14
16
  import { Parts, ReferencePicker } from './edit-in-place-controls.js';
15
17
  import { LinkOut } from './row-edit-cells.js';
@@ -216,6 +218,25 @@ function selectKind(config) {
216
218
  },
217
219
  };
218
220
  }
221
+ function ratingKind(config) {
222
+ const max = config.max ?? 5;
223
+ return {
224
+ editKind: 'choice',
225
+ toDraft: (value) => (value == null ? null : Math.min(Math.max(0, Math.round(value)), max) || null),
226
+ check: (draft) => (draft == null && config.required ? { ok: false, message: REQUIRED } : { ok: true, value: draft }),
227
+ show: (value) => (value == null ? null : _jsx(RatingScore, { value: value, max: max, glyph: config.glyph })),
228
+ control: (props) => (_jsx(RatingInput, { id: props.id, value: props.value, max: max, glyph: config.glyph, label: props.label,
229
+ // A pick saves now; an arrow's value waits for the last one.
230
+ onChange: (next, source) => {
231
+ if (next === null && config.required)
232
+ return;
233
+ if (source === 'pointer')
234
+ props.commit(next);
235
+ else
236
+ props.onChange(next);
237
+ }, disabled: props.disabled, invalid: props.invalid, "aria-describedby": props.describedBy })),
238
+ };
239
+ }
219
240
  function referenceKind(config) {
220
241
  return {
221
242
  editKind: 'choice',
@@ -461,6 +482,15 @@ export const inPlace = {
461
482
  choice(options) {
462
483
  return single(selectKind({ ...options, look: 'buttons' }), { ...options, value: options.value ?? null });
463
484
  },
485
+ /**
486
+ * A score out of a few as stars (or hearts) set by a click (RatingInput):
487
+ * the stars are the value, always there with no click to open, and a
488
+ * click on one saves it. Pressing the set one again saves `null` unless
489
+ * `required`. Reads at rest (printed) as RatingScore.
490
+ */
491
+ rating(options) {
492
+ return { ...single(ratingKind(options), { ...options, value: options.value ?? null }), alwaysEditable: true };
493
+ },
464
494
  /**
465
495
  * Another record, searched as you type through the app's `search`; a
466
496
  * pick saves its id. With `onCreate`, Create "<typed>" makes one.
@@ -32,6 +32,13 @@ export type EditFieldConfig = {
32
32
  * value (`text`, `effort`). `null` or `{}` when it names none.
33
33
  */
34
34
  fieldErrors?: (cause: unknown) => Record<string, string> | null;
35
+ /**
36
+ * "Keep mine" after a conflict: `mine` (what's typed, started from
37
+ * `base`) laid onto `theirs` (the value saved elsewhere since), or null
38
+ * when both changed the same part. Without it, "keep mine" saves what's
39
+ * typed over theirs. Long text's default is `rebaseMarkdown`.
40
+ */
41
+ rebase?: ((base: unknown, mine: unknown, theirs: unknown) => unknown) | false;
35
42
  };
36
43
  export type EditFieldState = {
37
44
  status: 'closed';
@@ -55,6 +62,18 @@ export type OpenFieldState = {
55
62
  autosave?: 'saving' | 'saved';
56
63
  /** Counts the times an always-editable field started over from a value saved elsewhere (`refresh`). */
57
64
  revision?: number;
65
+ /**
66
+ * The saved value changed elsewhere while this held unsaved typing:
67
+ * nothing saves until `keepMine` (save over it) or `takeSaved` (show it).
68
+ * A save the server refused with a 409 (AppError kind `conflict`) sets
69
+ * it too.
70
+ */
71
+ conflict?: boolean;
72
+ /**
73
+ * "Keep mine" couldn't lay what's typed onto the value saved elsewhere:
74
+ * both changed the same part. Another "keep mine" replaces theirs.
75
+ */
76
+ overlap?: boolean;
58
77
  };
59
78
  /** How long typing has to stop before an autosaving field saves. */
60
79
  export declare const AUTOSAVE_DELAY_MS = 1000;
@@ -62,6 +81,14 @@ export type EditInPlaceStoreOptions = {
62
81
  /** The pause before an autosave, in ms. Defaults to AUTOSAVE_DELAY_MS. */
63
82
  autosaveDelay?: number;
64
83
  };
84
+ /** What a field shows when the saved value changed under unsaved typing. */
85
+ export declare const CONFLICT_MESSAGE = "This changed elsewhere (another tab, device or chat) since you started typing. Saving now replaces that.";
86
+ /** The conflict's message for a field that can keep both (a `rebase`): Keep Mine adds what's typed to it. */
87
+ export declare const CONFLICT_REBASE_MESSAGE = "This changed elsewhere (another tab, device or chat) since you started typing. Keep Mine adds your changes to it.";
88
+ /** "Keep mine" found both sides changed the same part. */
89
+ export declare const OVERLAP_MESSAGE = "Your changes and the ones saved elsewhere are in the same place, so both can't be kept. Keep Mine again replaces theirs; Show Saved drops yours.";
90
+ /** Whether a save's rejection is the server's "changed since" (a 409, AppError kind `conflict`). */
91
+ export declare function isConflict(error: unknown): boolean;
65
92
  /** Why a save failed, in words to show beside what was being saved. */
66
93
  export declare function messageOf(error: unknown): string;
67
94
  export declare class EditInPlaceStore {
@@ -76,12 +103,17 @@ export declare class EditInPlaceStore {
76
103
  private queued;
77
104
  private always;
78
105
  private holds;
106
+ private seen;
107
+ private sent;
108
+ private detached;
109
+ private hurried;
79
110
  constructor(options?: EditInPlaceStoreOptions);
80
111
  subscribe: (listener: () => void) => () => void;
81
112
  private emit;
82
113
  private set;
83
114
  /** A field joins the view. `config` is read fresh each time it's needed. */
84
115
  register(key: string, config: () => EditFieldConfig): () => void;
116
+ private sendDetached;
85
117
  state(key: string): EditFieldState;
86
118
  /** The field that's open, if any. An always-editable one never counts. */
87
119
  get open(): string | null;
@@ -98,7 +130,10 @@ export declare class EditInPlaceStore {
98
130
  hold(): () => void;
99
131
  /** Whether leaving the page now would lose something: a draft that isn't saved. */
100
132
  get dirty(): boolean;
101
- /** Whether everything unsaved saves on its own, so leaving can save it first rather than ask. */
133
+ /**
134
+ * Whether everything unsaved saves on its own, so leaving can save it
135
+ * first rather than ask. A problem or a conflict can't: leaving asks at once.
136
+ */
102
137
  get savesOnLeave(): boolean;
103
138
  private unsaved;
104
139
  private isEqual;
@@ -128,6 +163,13 @@ export declare class EditInPlaceStore {
128
163
  commit(key: string, draft?: unknown): Promise<boolean>;
129
164
  private commitAutosaved;
130
165
  private schedule;
166
+ /**
167
+ * The page is hidden (another tab, a phone's home screen, F13): while it
168
+ * is, an autosave goes without the pause, and one waiting goes now.
169
+ */
170
+ hurry(hidden: boolean): void;
171
+ private remember;
172
+ private isEcho;
131
173
  private clearTimer;
132
174
  /**
133
175
  * Saves an autosaving field's latest draft now. With a save in flight,
@@ -142,11 +184,35 @@ export declare class EditInPlaceStore {
142
184
  */
143
185
  saveAll(): Promise<boolean>;
144
186
  /**
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.
187
+ * The field's saved value (its config's `value`) may have changed
188
+ * elsewhere: another tab, a phone, an AI chat, the form. Call it whenever
189
+ * the value changes. An open autosaving field with nothing of its own unsaved or
190
+ * saving shows it, starting its control over (`revision`): true when it
191
+ * did, so the caret can be put back (F4). One with unsaved typing gets a
192
+ * conflict (`conflict`, its message), and nothing saves until the person
193
+ * picks. The field's own save coming back, as sent or as the server
194
+ * normalised it (trimmed), is no change: the control keeps its text and
195
+ * its undo (F25).
148
196
  */
149
197
  refresh(key: string): boolean;
198
+ /**
199
+ * The saved value changed under this field's unsaved typing, as a
200
+ * server's conflict answer says. A save refused with a 409 (AppError
201
+ * kind `conflict`) does this itself. Nothing saves until the person picks.
202
+ */
203
+ markConflict(key: string): void;
204
+ /**
205
+ * A conflict, answered "keep mine". With a `rebase`, what's typed is laid
206
+ * onto the value saved elsewhere and the control starts over showing
207
+ * both (`revision`) as it saves; if both changed the same part it stays
208
+ * a conflict (`overlap`), and keeping mine again saves what's typed over
209
+ * theirs. Without a `rebase`, what's typed saves over it. The save
210
+ * carries the record's latest version, so a writer that saved again
211
+ * meanwhile is another conflict, not an overwrite.
212
+ */
213
+ keepMine(key: string): Promise<boolean>;
214
+ /** A conflict, answered "show the saved one": what's typed goes, and the control starts over from the saved value. */
215
+ takeSaved(key: string): void;
150
216
  /**
151
217
  * Esc: closes and shows the saved value again. Not while a save is in
152
218
  * flight, and never for an always-editable field.