@tristan2828/ui-foundation 4.126.0 → 4.128.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 (74) hide show
  1. package/conventions/docs/add-an-entity.md +154 -34
  2. package/conventions/docs/cell-patterns.md +88 -41
  3. package/conventions/docs/design-language.md +62 -13
  4. package/dist/api/contracts.d.ts +8 -1
  5. package/dist/api/gateway/errors.js +4 -0
  6. package/dist/api/schema.d.ts +9 -0
  7. package/dist/components/app/data-table-tools.d.ts +12 -0
  8. package/dist/components/app/data-table-tools.js +2 -2
  9. package/dist/components/app/data-table.d.ts +2 -1
  10. package/dist/components/app/data-table.js +1 -1
  11. package/dist/components/app/edit-in-place-presets.d.ts +51 -1
  12. package/dist/components/app/edit-in-place-presets.js +30 -0
  13. package/dist/components/app/edit-in-place-store.d.ts +33 -7
  14. package/dist/components/app/edit-in-place-store.js +112 -20
  15. package/dist/components/app/edit-in-place.d.ts +11 -0
  16. package/dist/components/app/editable-value.js +43 -8
  17. package/dist/components/app/entity-form.d.ts +9 -1
  18. package/dist/components/app/entity-form.js +9 -2
  19. package/dist/components/app/entity-view.js +5 -1
  20. package/dist/components/app/equal-items.d.ts +33 -6
  21. package/dist/components/app/equal-items.js +42 -7
  22. package/dist/components/app/error-state.js +1 -0
  23. package/dist/components/app/form-conflict-notice.d.ts +8 -0
  24. package/dist/components/app/form-conflict-notice.js +15 -0
  25. package/dist/components/app/form-dialog.d.ts +8 -1
  26. package/dist/components/app/form-dialog.js +9 -2
  27. package/dist/components/app/milkdown-editor.js +24 -331
  28. package/dist/components/app/notify.d.ts +18 -1
  29. package/dist/components/app/notify.js +26 -3
  30. package/dist/components/app/page-restore.js +1 -1
  31. package/dist/components/app/pill-filter.d.ts +16 -0
  32. package/dist/components/app/pill-filter.js +22 -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-box-anchor.d.ts +6 -0
  38. package/dist/components/app/rich-text-box-anchor.js +8 -0
  39. package/dist/components/app/rich-text-editor.d.ts +4 -2
  40. package/dist/components/app/rich-text-editor.js +3 -2
  41. package/dist/components/app/rich-text-heading-view.d.ts +4 -0
  42. package/dist/components/app/rich-text-heading-view.js +91 -0
  43. package/dist/components/app/rich-text-keyboard-bar.js +3 -2
  44. package/dist/components/app/rich-text-link-box.d.ts +9 -0
  45. package/dist/components/app/rich-text-link-box.js +40 -0
  46. package/dist/components/app/rich-text-links.d.ts +14 -0
  47. package/dist/components/app/rich-text-links.js +92 -0
  48. package/dist/components/app/rich-text-page-box.d.ts +10 -0
  49. package/dist/components/app/rich-text-page-box.js +45 -0
  50. package/dist/components/app/rich-text-task-item-view.d.ts +4 -0
  51. package/dist/components/app/rich-text-task-item-view.js +59 -0
  52. package/dist/components/app/rich-text-toggle-heading.js +1 -1
  53. package/dist/components/app/rich-text-toolbar.js +1 -1
  54. package/dist/components/app/rich-text-tools-bar.d.ts +3 -1
  55. package/dist/components/app/rich-text-tools-bar.js +2 -2
  56. package/dist/components/app/step-row.d.ts +15 -0
  57. package/dist/components/app/step-row.js +27 -0
  58. package/dist/components/app/step-track.d.ts +82 -0
  59. package/dist/components/app/step-track.js +98 -0
  60. package/dist/components/ui/sonner.js +1 -1
  61. package/dist/hooks/use-form-version.d.ts +101 -0
  62. package/dist/hooks/use-form-version.js +187 -0
  63. package/dist/hooks/use-record-update.d.ts +15 -8
  64. package/dist/hooks/use-record-update.js +19 -14
  65. package/dist/index.d.ts +7 -3
  66. package/dist/index.js +7 -0
  67. package/dist/lib/markdown-merge.d.ts +12 -0
  68. package/dist/lib/markdown-merge.js +90 -0
  69. package/dist/lib/rating-glyphs.d.ts +3 -0
  70. package/dist/lib/rating-glyphs.js +7 -0
  71. package/dist/lib/refusal.d.ts +9 -0
  72. package/dist/lib/refusal.js +19 -0
  73. package/openapi/foundation.yaml +12 -0
  74. package/package.json +1 -1
@@ -0,0 +1,27 @@
1
+ // The step row's classes and its keep-in-view hook, shared by StepTrack
2
+ // (step-track.tsx) and the stepper look (equal-items.tsx), so the two rows
3
+ // never drift apart. Internal: never exported from the package's index.
4
+ import { useLayoutEffect } from 'react';
5
+ import { cn } from 'cn';
6
+ /** A step's box: at least 4.5rem wide and 44px tall, sharing the row. */
7
+ export const STEP_CELL = 'group/step relative flex min-h-11 min-w-18 flex-1 basis-0 flex-col items-center gap-1 rounded-md px-1 pt-1 pb-1.5 text-center text-xs text-muted-foreground';
8
+ /** The line from the step before, under the marks: the primary up to the current one. */
9
+ export const stepLine = (step) => cn('before:absolute before:top-4 before:right-1/2 before:h-0.5 before:w-full first:before:hidden', step === 'upcoming' ? 'before:bg-border' : 'before:bg-primary');
10
+ /** The row's scroll box: sideways in its own box, never the page. */
11
+ export const STEP_ROW = 'relative flex max-w-full overflow-x-auto overflow-y-hidden [scrollbar-width:thin]';
12
+ /**
13
+ * Keeps the step `selector` finds in the row's view when the row scrolls
14
+ * sideways: the row only, never the page. Runs again when `key` changes.
15
+ */
16
+ export function useKeepStepInView(rowRef, selector, key) {
17
+ useLayoutEffect(() => {
18
+ const row = rowRef.current;
19
+ const step = row?.querySelector(selector);
20
+ if (!row || !step || row.scrollWidth <= row.clientWidth)
21
+ return;
22
+ const left = step.offsetLeft - row.offsetLeft;
23
+ if (left < row.scrollLeft || left + step.offsetWidth > row.scrollLeft + row.clientWidth) {
24
+ row.scrollLeft = left - (row.clientWidth - step.offsetWidth) / 2;
25
+ }
26
+ }, [rowRef, selector, key]);
27
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Where a step is in a sequence: `done` (a filled step with a check),
3
+ * `current` (ringed, "Current" or a caption under its name) or `upcoming`
4
+ * (outlined, the default).
5
+ */
6
+ export type StepTrackState = 'done' | 'current' | 'upcoming';
7
+ /**
8
+ * One step. An `EqualItem` is one too (its `id`, `title`, `step` and
9
+ * `attention`), so a record's stepper items can be passed as they are.
10
+ */
11
+ export type StepTrackStep = {
12
+ /** Unique in the track. */
13
+ id: string;
14
+ /** Its name ("Phase 2: Build"). Plain text. */
15
+ title: string;
16
+ /** Done, current or upcoming (the default). */
17
+ step?: StepTrackState;
18
+ /**
19
+ * A step that needs a look: a small warning dot on its mark, and these
20
+ * words at the end of its name ("needs an answer").
21
+ */
22
+ attention?: string;
23
+ };
24
+ export type StepTrackProps = {
25
+ steps: readonly StepTrackStep[];
26
+ /** The list's name for screen readers ("Phases"). */
27
+ label: string;
28
+ /**
29
+ * A few words under the current step in place of "Current" ("Day 12").
30
+ * The step's name still says it's the current one.
31
+ */
32
+ caption?: string;
33
+ /** What no steps says. Defaults to "Nothing yet". */
34
+ emptyText?: string;
35
+ className?: string;
36
+ };
37
+ /**
38
+ * A step's numbered mark. `ring` is `active` for the stepper (a ring when
39
+ * its tab is the one shown) or `on` (the track's current step).
40
+ */
41
+ export declare function StepMark({ step, number, attention, ring, slot, }: {
42
+ step: StepTrackState;
43
+ number: number;
44
+ attention: string | undefined;
45
+ ring: 'active' | 'on' | 'off';
46
+ slot: string;
47
+ }): import("react").JSX.Element;
48
+ /**
49
+ * A step's name: what it shows plus hidden words ("Step 2: Phase 2: Build,
50
+ * done"), never an aria-label, so the visible text stays in the name. The
51
+ * hidden words sit inside the clamped line, with no gap a block would add.
52
+ */
53
+ export declare function StepName({ step, number, title, attention, current, }: {
54
+ step: StepTrackState;
55
+ number: number;
56
+ title: string;
57
+ attention: string | undefined;
58
+ /** Hidden ", current", where no visible "Current" says so. */
59
+ current?: boolean;
60
+ }): import("react").JSX.Element;
61
+ /**
62
+ * A read-only row of numbered steps (4.128): the stepper look's marks
63
+ * without its panels, for showing where a sequence is (a list card's
64
+ * phases), with a `caption` under the current step.
65
+ *
66
+ * ```tsx
67
+ * <StepTrack
68
+ * label="Phases"
69
+ * caption="Day 12"
70
+ * steps={[
71
+ * { id: 'p1', title: 'Phase 1', step: 'done' },
72
+ * { id: 'p2', title: 'Phase 2', step: 'current' },
73
+ * { id: 'p3', title: 'Phase 3' },
74
+ * ]}
75
+ * />
76
+ * ```
77
+ *
78
+ * A named list, not a tablist: nothing is picked. To look at each step's
79
+ * details in turn, use `EqualItems look="stepper"` (design-language.md "A
80
+ * few equal things").
81
+ */
82
+ export declare function StepTrack({ steps, label, caption, emptyText, className }: StepTrackProps): import("react").JSX.Element;
@@ -0,0 +1,98 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // A row of numbered steps joined by a line, each done, current or upcoming:
3
+ // the marks of `EqualItems look="stepper"` (4.127), on their own and read
4
+ // only (4.128). For a display of where a sequence is (a list card showing a
5
+ // program's phases, a caption such as "Day 12" under the current one),
6
+ // where nothing is picked and no panel shows.
7
+ //
8
+ // The stepper draws its steps from the same parts (StepMark and StepName
9
+ // below, the cell and line classes and the keep-in-view hook in
10
+ // step-row.ts), so the two never
11
+ // drift apart: change a mark here and both change.
12
+ //
13
+ // It is not interactive, so it's a named list (`<ol>`), never a tablist:
14
+ // each step is a list item whose text is what it shows plus hidden words
15
+ // ("Step 2: Phase 2: Build, done"). Wider than its column (a phone, many
16
+ // steps), the row scrolls sideways in its own box, never the page, with the
17
+ // current step in view; only while it overflows is the box a tab stop
18
+ // (axe's scrollable-region-focusable), so the arrow keys can scroll it.
19
+ import { useEffect, useRef, useState } from 'react';
20
+ import { CheckIcon } from 'lucide-react';
21
+ import { cn } from 'cn';
22
+ import { STEP_CELL, STEP_ROW, stepLine, useKeepStepInView } from './step-row.js';
23
+ // The stepper's and the track's shared marks (step-row.ts has the row's
24
+ // classes and its keep-in-view hook). Internal: exported for
25
+ // equal-items.tsx only, never from the package's index.
26
+ /**
27
+ * A step's numbered mark. `ring` is `active` for the stepper (a ring when
28
+ * its tab is the one shown) or `on` (the track's current step).
29
+ */
30
+ export function StepMark({ step, number, attention, ring, slot, }) {
31
+ return (_jsxs("span", { "aria-hidden": "true", "data-slot": `${slot}-mark`, className: cn('relative z-10 grid size-6.5 shrink-0 place-items-center rounded-full border-2 text-xs font-bold tabular-nums', step === 'done'
32
+ ? 'border-primary bg-primary text-primary-foreground'
33
+ : step === 'current'
34
+ ? 'border-primary bg-card text-foreground'
35
+ : 'border-border bg-card text-muted-foreground', ring === 'active' &&
36
+ 'group-data-active/step:ring-2 group-data-active/step:ring-ring group-data-active/step:ring-offset-2 group-data-active/step:ring-offset-card', ring === 'on' && 'ring-2 ring-ring ring-offset-2 ring-offset-card'), children: [step === 'done' ? _jsx(CheckIcon, { className: "size-3.5" }) : number, attention && (_jsx("span", { "data-slot": `${slot}-attention`, className: "absolute -top-0.5 -right-0.5 size-2.5 rounded-full border border-card bg-warning-text" }))] }));
37
+ }
38
+ /**
39
+ * A step's name: what it shows plus hidden words ("Step 2: Phase 2: Build,
40
+ * done"), never an aria-label, so the visible text stays in the name. The
41
+ * hidden words sit inside the clamped line, with no gap a block would add.
42
+ */
43
+ export function StepName({ step, number, title, attention, current, }) {
44
+ return (_jsxs("span", { className: "line-clamp-3 max-w-full min-w-0 break-words", children: [_jsx("span", { className: "sr-only", children: `Step ${number}: ` }), title, step === 'done' && _jsx("span", { className: "sr-only", children: ", done" }), current && _jsx("span", { className: "sr-only", children: ", current" }), attention && _jsx("span", { className: "sr-only", children: `, ${attention}` })] }));
45
+ }
46
+ // Whether the row is wider than its box, followed as either changes size.
47
+ function useOverflows(rowRef) {
48
+ const [overflows, setOverflows] = useState(false);
49
+ useEffect(() => {
50
+ const row = rowRef.current;
51
+ if (!row)
52
+ return;
53
+ const check = () => setOverflows(row.scrollWidth > row.clientWidth + 1);
54
+ check();
55
+ if (typeof ResizeObserver === 'undefined')
56
+ return;
57
+ const observer = new ResizeObserver(check);
58
+ observer.observe(row);
59
+ return () => observer.disconnect();
60
+ }, [rowRef]);
61
+ return overflows;
62
+ }
63
+ /**
64
+ * A read-only row of numbered steps (4.128): the stepper look's marks
65
+ * without its panels, for showing where a sequence is (a list card's
66
+ * phases), with a `caption` under the current step.
67
+ *
68
+ * ```tsx
69
+ * <StepTrack
70
+ * label="Phases"
71
+ * caption="Day 12"
72
+ * steps={[
73
+ * { id: 'p1', title: 'Phase 1', step: 'done' },
74
+ * { id: 'p2', title: 'Phase 2', step: 'current' },
75
+ * { id: 'p3', title: 'Phase 3' },
76
+ * ]}
77
+ * />
78
+ * ```
79
+ *
80
+ * A named list, not a tablist: nothing is picked. To look at each step's
81
+ * details in turn, use `EqualItems look="stepper"` (design-language.md "A
82
+ * few equal things").
83
+ */
84
+ export function StepTrack({ steps, label, caption, emptyText = 'Nothing yet', className }) {
85
+ const rowRef = useRef(null);
86
+ const currentId = steps.find((step) => step.step === 'current')?.id;
87
+ useKeepStepInView(rowRef, '[data-slot="step-track-step"][aria-current]', currentId);
88
+ const overflows = useOverflows(rowRef);
89
+ if (steps.length === 0) {
90
+ return (_jsx("p", { "data-slot": "step-track", "data-state": "empty", className: cn('type-body text-muted-foreground', className), children: emptyText }));
91
+ }
92
+ return (_jsx("ol", { ref: rowRef, "data-slot": "step-track", "aria-label": label, tabIndex: overflows ? 0 : undefined, className: cn(STEP_ROW, 'm-0 list-none p-0 outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50', className), children: steps.map((item, index) => {
93
+ const step = item.step ?? 'upcoming';
94
+ const current = step === 'current';
95
+ const showCaption = current && caption !== undefined && caption !== '';
96
+ return (_jsxs("li", { "data-slot": "step-track-step", "data-step": step, "aria-current": current ? 'step' : undefined, className: cn(STEP_CELL, stepLine(step), current && 'font-semibold text-foreground'), children: [_jsx(StepMark, { step: step, number: index + 1, attention: item.attention, ring: current ? 'on' : 'off', slot: "step-track-step" }), _jsx(StepName, { step: step, number: index + 1, title: item.title, attention: item.attention, current: showCaption }), current && (_jsx("span", { "data-slot": "step-track-caption", className: "font-normal text-muted-foreground", children: showCaption ? caption : 'Current' }))] }, item.id));
97
+ }) }));
98
+ }
@@ -15,7 +15,7 @@ import { jsx as _jsx } from "react/jsx-runtime";
15
15
  // - Toasts last 4 seconds, Undo too. An error from `notify.failed` stays
16
16
  // until it's closed.
17
17
  //
18
- // What a toast says and when one shows: `notify` (components/app/notify.ts).
18
+ // What a toast says and when one shows: `notify` (components/app/notify.tsx).
19
19
  import { useTheme } from "next-themes";
20
20
  import { Toaster as Sonner } from "sonner";
21
21
  import { CircleCheckIcon, InfoIcon, TriangleAlertIcon, OctagonXIcon, Loader2Icon } from "lucide-react";
@@ -0,0 +1,101 @@
1
+ import type { AppError } from '../api/contracts.js';
2
+ type RecordId = string | number;
3
+ /** What EntityForm's and FormDialog's `conflict` take: a save refused because the record changed elsewhere. */
4
+ export type FormConflict = {
5
+ /** Save what's typed over the newer version (the form submits again). */
6
+ onKeepMine: () => void;
7
+ /** Drop what's typed and show the newer version. */
8
+ onShowSaved: () => void;
9
+ /** The newer version is still being fetched: both wait for it. */
10
+ loading?: boolean;
11
+ };
12
+ export type FormVersionOptions<TRecord extends {
13
+ id: RecordId;
14
+ }, TUpdate> = {
15
+ /** The record as the form's query has it now (its `data`); undefined on a create form or while loading. */
16
+ record: TRecord | undefined;
17
+ /**
18
+ * Adds the version to what's sent: `(update, widget) => ({ ...update,
19
+ * baseUpdatedAt: widget.updatedAt })`, the same function the entity's
20
+ * `useRecordUpdate` takes.
21
+ */
22
+ withVersion: (update: TUpdate, record: TRecord) => TUpdate;
23
+ /** Fetches the record again (the query's `refetch`), after a 409, so Keep Mine and Show Saved have the newer version. */
24
+ refetch: () => Promise<unknown> | unknown;
25
+ };
26
+ type Phase = 'none' | 'loading' | 'ready';
27
+ type Snapshot<TRecord> = {
28
+ /** The record the form shows: what it opened with, or what Show Saved took. */
29
+ opened: TRecord | undefined;
30
+ phase: Phase;
31
+ };
32
+ /**
33
+ * The state behind `useFormVersion`, outside React (exported for tests).
34
+ * `latest` is the query's record, kept current by the hook; `opened` the
35
+ * one the form's values came from; `base` the one the next save is built
36
+ * on (Keep Mine moves it to the newer version without touching `opened`).
37
+ */
38
+ export declare class FormVersionStore<TRecord extends {
39
+ id: RecordId;
40
+ }, TUpdate> {
41
+ private latest;
42
+ private base;
43
+ private snapshot;
44
+ private listeners;
45
+ private turn;
46
+ private withVersion;
47
+ private refetch;
48
+ constructor(withVersion: (update: TUpdate, record: TRecord) => TUpdate, refetch: () => Promise<unknown> | unknown);
49
+ subscribe: (listener: () => void) => () => boolean;
50
+ getSnapshot: () => Snapshot<TRecord>;
51
+ private set;
52
+ setOptions(withVersion: FormVersionStore<TRecord, TUpdate>['withVersion'], refetch: () => Promise<unknown> | unknown): void;
53
+ /**
54
+ * The query's record now. The first one (or one with another id: the
55
+ * form moved to another record) is the one the form opens with; later
56
+ * ones are only remembered, for Keep Mine and Show Saved.
57
+ */
58
+ sync(record: TRecord | undefined): void;
59
+ /** The record the form shows, given the query's record this render (before `sync` has run). */
60
+ shown(record: TRecord | undefined): TRecord | undefined;
61
+ /** `update` with the version the form's values were built on. No record yet (a create): unchanged. */
62
+ send(update: TUpdate): TUpdate;
63
+ /** A save was refused: true when it's a conflict, which this now shows. */
64
+ refused(error: AppError | unknown): boolean;
65
+ /** Keep Mine: the next save is built on the newer version; what's typed stays. */
66
+ keepMine(): void;
67
+ /** Show Saved: the form takes the newer record (its values reset to it). */
68
+ showSaved(): void;
69
+ /** A save went through: the next one builds on what it wrote. What the form shows is unchanged. */
70
+ saved(record: TRecord): void;
71
+ /** EntityForm's / FormDialog's `conflict` while one stands. */
72
+ conflict(): FormConflict | undefined;
73
+ }
74
+ export type FormVersion<TRecord, TUpdate> = {
75
+ /** The record the form was opened with (or Show Saved took): the form's `values` come from it. */
76
+ record: TRecord | undefined;
77
+ /** What to send: `update` with that record's version. */
78
+ send: (update: TUpdate) => TUpdate;
79
+ /** First in the save's `onError`: true when the save was refused as a conflict, which `conflict` now shows. */
80
+ refused: (error: AppError) => boolean;
81
+ /** In the save's `onSuccess` when the form stays open: the next save builds on this one. */
82
+ saved: (record: TRecord) => void;
83
+ /** EntityForm's or FormDialog's `conflict`. */
84
+ conflict: FormConflict | undefined;
85
+ };
86
+ /**
87
+ * An edit form's version check (see the top of this file):
88
+ *
89
+ * ```tsx
90
+ * const version = useFormVersion({ record: widgetQuery.data, withVersion, refetch: widgetQuery.refetch })
91
+ * useForm({ values: version.record && widgetToFormValues(version.record) })
92
+ * updateWidget.mutate(version.send(formValuesToWidgetUpdate(values)), {
93
+ * onError: (error) => { if (!version.refused(error)) setSubmitError(error) },
94
+ * })
95
+ * <EntityForm conflict={version.conflict} … />
96
+ * ```
97
+ */
98
+ export declare function useFormVersion<TRecord extends {
99
+ id: RecordId;
100
+ }, TUpdate>({ record, withVersion, refetch, }: FormVersionOptions<TRecord, TUpdate>): FormVersion<TRecord, TUpdate>;
101
+ export {};
@@ -0,0 +1,187 @@
1
+ // A form's save that doesn't overwrite (add-an-entity.md "Saves that don't
2
+ // overwrite", forms): the edit form sends the version of the record it was
3
+ // opened with, as editing in place does, so a form left open on a record
4
+ // another tab, phone or chat has saved since is refused (a 409, AppError
5
+ // kind `conflict`) instead of replacing their save.
6
+ //
7
+ // - **The form keeps the record it opened with.** `record` is that one,
8
+ // not the query's latest: feed the form's `values` from it, and a
9
+ // refetch in the background (a window focus, another save's
10
+ // invalidation) never resets what's typed. Only Show Saved does, on a
11
+ // click.
12
+ // - **`send(update)`** adds the version the form was built on (the app's
13
+ // `withVersion`, the one its `useRecordUpdate` takes).
14
+ // - **`refused(error)`**, first in the save's `onError`: true for a
15
+ // conflict, which this hook now shows (the record is fetched again, and
16
+ // `conflict` is set for EntityForm or FormDialog), so the app doesn't
17
+ // also show it as a failed save. Anything else is false and the app
18
+ // handles it as before.
19
+ // - **`conflict`** goes to EntityForm's or FormDialog's `conflict`: a
20
+ // warning Notice in the bar, "This changed elsewhere", with Keep Mine
21
+ // (save what's typed over it, now built on the newer version) and Show
22
+ // Saved (the form takes the newer record; what was typed goes, as the
23
+ // Notice says). What's typed stays until one is picked.
24
+ // - **`saved(record)`**, in the save's `onSuccess`, when the form stays
25
+ // open after a save (a dialog that doesn't close): the next save builds
26
+ // on the version this one wrote. A form that leaves can skip it.
27
+ //
28
+ // No `withVersion`, no hook: a form that doesn't use it sends no version
29
+ // and behaves as it always has.
30
+ import { useLayoutEffect, useMemo, useState, useSyncExternalStore } from 'react';
31
+ /**
32
+ * The state behind `useFormVersion`, outside React (exported for tests).
33
+ * `latest` is the query's record, kept current by the hook; `opened` the
34
+ * one the form's values came from; `base` the one the next save is built
35
+ * on (Keep Mine moves it to the newer version without touching `opened`).
36
+ */
37
+ export class FormVersionStore {
38
+ latest;
39
+ base;
40
+ snapshot = { opened: undefined, phase: 'none' };
41
+ listeners = new Set();
42
+ // Bumped by every conflict: a refetch that lands after a newer conflict
43
+ // (or after a pick) doesn't mark it ready.
44
+ turn = 0;
45
+ withVersion;
46
+ refetch;
47
+ constructor(withVersion, refetch) {
48
+ this.withVersion = withVersion;
49
+ this.refetch = refetch;
50
+ }
51
+ subscribe = (listener) => {
52
+ this.listeners.add(listener);
53
+ return () => this.listeners.delete(listener);
54
+ };
55
+ getSnapshot = () => this.snapshot;
56
+ set(next) {
57
+ this.snapshot = { ...this.snapshot, ...next };
58
+ for (const listener of this.listeners)
59
+ listener();
60
+ }
61
+ setOptions(withVersion, refetch) {
62
+ this.withVersion = withVersion;
63
+ this.refetch = refetch;
64
+ }
65
+ /**
66
+ * The query's record now. The first one (or one with another id: the
67
+ * form moved to another record) is the one the form opens with; later
68
+ * ones are only remembered, for Keep Mine and Show Saved.
69
+ */
70
+ sync(record) {
71
+ this.latest = record;
72
+ if (!record)
73
+ return;
74
+ const opened = this.snapshot.opened;
75
+ if (!opened || opened.id !== record.id) {
76
+ this.base = record;
77
+ this.turn++;
78
+ this.set({ opened: record, phase: 'none' });
79
+ }
80
+ }
81
+ /** The record the form shows, given the query's record this render (before `sync` has run). */
82
+ shown(record) {
83
+ const opened = this.snapshot.opened;
84
+ if (!record)
85
+ return opened;
86
+ return opened && opened.id === record.id ? opened : record;
87
+ }
88
+ /** `update` with the version the form's values were built on. No record yet (a create): unchanged. */
89
+ send(update) {
90
+ const base = this.base ?? this.latest;
91
+ return base ? this.withVersion(update, base) : update;
92
+ }
93
+ /** A save was refused: true when it's a conflict, which this now shows. */
94
+ refused(error) {
95
+ if (!error || typeof error !== 'object' || error.kind !== 'conflict')
96
+ return false;
97
+ const turn = ++this.turn;
98
+ this.set({ phase: 'loading' });
99
+ let fetched;
100
+ try {
101
+ fetched = Promise.resolve(this.refetch());
102
+ }
103
+ catch (failed) {
104
+ fetched = Promise.reject(failed);
105
+ }
106
+ void fetched
107
+ .catch(() => undefined)
108
+ .then((result) => {
109
+ // A TanStack refetch answers with the query's result: its record
110
+ // is the newer version, before the next render syncs it.
111
+ const data = result?.data;
112
+ const opened = this.snapshot.opened;
113
+ if (data && typeof data === 'object' && (!opened || data.id === opened.id))
114
+ this.latest = data;
115
+ // Ready either way: a refetch that failed leaves the older
116
+ // version, and Keep Mine is refused again rather than overwriting.
117
+ if (this.turn === turn)
118
+ this.set({ phase: 'ready' });
119
+ });
120
+ return true;
121
+ }
122
+ /** Keep Mine: the next save is built on the newer version; what's typed stays. */
123
+ keepMine() {
124
+ if (this.snapshot.phase !== 'ready')
125
+ return;
126
+ if (this.latest)
127
+ this.base = this.latest;
128
+ this.turn++;
129
+ this.set({ phase: 'none' });
130
+ }
131
+ /** Show Saved: the form takes the newer record (its values reset to it). */
132
+ showSaved() {
133
+ if (this.snapshot.phase !== 'ready')
134
+ return;
135
+ this.base = this.latest ?? this.base;
136
+ this.turn++;
137
+ this.set({ opened: this.latest ?? this.snapshot.opened, phase: 'none' });
138
+ }
139
+ /** A save went through: the next one builds on what it wrote. What the form shows is unchanged. */
140
+ saved(record) {
141
+ this.latest = record;
142
+ this.base = record;
143
+ this.turn++;
144
+ if (this.snapshot.phase !== 'none')
145
+ this.set({ phase: 'none' });
146
+ }
147
+ /** EntityForm's / FormDialog's `conflict` while one stands. */
148
+ conflict() {
149
+ const { phase } = this.snapshot;
150
+ if (phase === 'none')
151
+ return undefined;
152
+ return { loading: phase === 'loading', onKeepMine: () => this.keepMine(), onShowSaved: () => this.showSaved() };
153
+ }
154
+ }
155
+ /**
156
+ * An edit form's version check (see the top of this file):
157
+ *
158
+ * ```tsx
159
+ * const version = useFormVersion({ record: widgetQuery.data, withVersion, refetch: widgetQuery.refetch })
160
+ * useForm({ values: version.record && widgetToFormValues(version.record) })
161
+ * updateWidget.mutate(version.send(formValuesToWidgetUpdate(values)), {
162
+ * onError: (error) => { if (!version.refused(error)) setSubmitError(error) },
163
+ * })
164
+ * <EntityForm conflict={version.conflict} … />
165
+ * ```
166
+ */
167
+ export function useFormVersion({ record, withVersion, refetch, }) {
168
+ const [store] = useState(() => new FormVersionStore(withVersion, refetch));
169
+ const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
170
+ useLayoutEffect(() => {
171
+ store.setOptions(withVersion, refetch);
172
+ store.sync(record);
173
+ });
174
+ // Before the effect has synced a new record: the one the form opened
175
+ // with when it's the same record, else the new one.
176
+ const { opened, phase } = snapshot;
177
+ const shown = !record ? opened : opened && opened.id === record.id ? opened : record;
178
+ return useMemo(() => ({
179
+ record: shown,
180
+ send: (update) => store.send(update),
181
+ refused: (error) => store.refused(error),
182
+ saved: (saved) => store.saved(saved),
183
+ conflict: phase === 'none'
184
+ ? undefined
185
+ : { loading: phase === 'loading', onKeepMine: () => store.keepMine(), onShowSaved: () => store.showSaved() },
186
+ }), [store, shown, phase]);
187
+ }
@@ -1,5 +1,6 @@
1
1
  import { type MutationOptions, type QueryClient, type QueryKey } from '@tanstack/react-query';
2
2
  import type { AppError } from '../api/contracts.js';
3
+ import { refusalReason } from '../lib/refusal.js';
3
4
  type RecordId = string | number;
4
5
  /**
5
6
  * What one save changes: the fields to send (`{ status: 'done' }`), or a
@@ -21,6 +22,18 @@ export type RecordUpdateOptions<TRecord extends {
21
22
  listsKey: QueryKey;
22
23
  /** The gateway's PATCH: sends `update`, resolves with the saved record, rejects with an `AppError`. */
23
24
  update: (id: TRecord['id'], update: TUpdate) => Promise<TRecord>;
25
+ /**
26
+ * Adds the version the change was built on to what's sent, when the
27
+ * record has one: `(update, widget) => ({ ...update, baseUpdatedAt:
28
+ * widget.updatedAt })`. `record` is the server's latest record this tab
29
+ * knows (in a burst of saves, the one the previous save returned), so a
30
+ * save never conflicts with this tab's own. The server answers 409 when
31
+ * the record's version is no longer that one (AppError kind `conflict`):
32
+ * the record is refetched, and nothing was written. Leave it out and no
33
+ * version is sent (docs/foundation/add-an-entity.md "Saves that don't
34
+ * overwrite").
35
+ */
36
+ withVersion?: (update: TUpdate, record: TRecord) => TUpdate;
24
37
  /** What a refusal's toast calls the record: "Couldn't update <name>: <reason>". */
25
38
  name: (record: TRecord) => string;
26
39
  /**
@@ -51,19 +64,14 @@ type Entry<TRecord, TUpdate> = {
51
64
  change: RecordChange<TRecord, TUpdate>;
52
65
  optimistic: boolean;
53
66
  };
54
- /**
55
- * Why a save was refused, in the server's words: for a 422, the message
56
- * on a field the save sent (the first field error otherwise), else the
57
- * `AppError`'s message.
58
- */
59
- export declare function refusalReason(error: AppError, sent?: object): string;
67
+ export { refusalReason };
60
68
  /**
61
69
  * The mutation options behind `useRecordUpdate`, for a given QueryClient.
62
70
  * Exported for tests and for code outside React; screens use the hook.
63
71
  */
64
72
  export declare function recordUpdateMutationOptions<TRecord extends {
65
73
  id: RecordId;
66
- }, TUpdate extends Partial<TRecord>>(queryClient: QueryClient, { id, detailKey, listsKey, update, name, optimistic, toastOnError, onSuccess, onError, onSettled, }: RecordUpdateOptions<TRecord, TUpdate>): MutationOptions<TRecord, AppError, RecordChange<TRecord, TUpdate>, {
74
+ }, TUpdate extends Partial<TRecord>>(queryClient: QueryClient, { id, detailKey, listsKey, update, name, withVersion, optimistic, toastOnError, onSuccess, onError, onSettled, }: RecordUpdateOptions<TRecord, TUpdate>): MutationOptions<TRecord, AppError, RecordChange<TRecord, TUpdate>, {
67
75
  entry: Entry<TRecord, TUpdate>;
68
76
  }>;
69
77
  /**
@@ -80,4 +88,3 @@ export declare function useRecordUpdate<TRecord extends {
80
88
  }, TUpdate extends Partial<TRecord>>(options: RecordUpdateOptions<TRecord, TUpdate>): import("@tanstack/react-query").UseMutationResult<TRecord, AppError, RecordChange<TRecord, TUpdate>, {
81
89
  entry: Entry<TRecord, TUpdate>;
82
90
  }>;
83
- export {};
@@ -26,6 +26,14 @@
26
26
  // function change has nothing to build on and is refused like any other
27
27
  // refusal. Both warn in the console, naming the keys searched.
28
28
  //
29
+ // - **A version check, when the record has one** (`withVersion`). Each
30
+ // request carries the version of the record it was built on (its
31
+ // `updatedAt`), and the server answers 409 when another writer saved
32
+ // since: nothing is written, the save rejects with an AppError of kind
33
+ // `conflict`, and the record is fetched again so the screen shows what
34
+ // the other writer saved. Without `withVersion` nothing is sent and
35
+ // nothing is checked, as before.
36
+ //
29
37
  // Editing in place uses the same save with `optimistic: false` and
30
38
  // `toastOnError: false`: nothing changes on screen until the server
31
39
  // agrees, and a refusal comes back to the field (`mutateAsync` rejects)
@@ -39,6 +47,7 @@
39
47
  // mutation, after the package's own cache work, either way (#250).
40
48
  import { hashKey, useMutation, useQueryClient, } from '@tanstack/react-query';
41
49
  import { toast } from 'sonner';
50
+ import { refusalReason } from '../lib/refusal.js';
42
51
  const states = new WeakMap();
43
52
  function recordStates(queryClient) {
44
53
  let map = states.get(queryClient);
@@ -54,22 +63,12 @@ const notLoaded = {
54
63
  function resolve(change, record) {
55
64
  return typeof change === 'function' ? change(record) : change;
56
65
  }
57
- /**
58
- * Why a save was refused, in the server's words: for a 422, the message
59
- * on a field the save sent (the first field error otherwise), else the
60
- * `AppError`'s message.
61
- */
62
- export function refusalReason(error, sent) {
63
- const fieldErrors = Object.entries(error.fieldErrors ?? {});
64
- const fields = Object.keys(sent ?? {});
65
- const onSentField = fieldErrors.find(([key]) => fields.some((field) => key === field || key.startsWith(`${field}.`)));
66
- return (onSentField ?? fieldErrors[0])?.[1][0] ?? error.message;
67
- }
66
+ export { refusalReason };
68
67
  /**
69
68
  * The mutation options behind `useRecordUpdate`, for a given QueryClient.
70
69
  * Exported for tests and for code outside React; screens use the hook.
71
70
  */
72
- export function recordUpdateMutationOptions(queryClient, { id, detailKey, listsKey, update, name, optimistic = true, toastOnError = true, onSuccess, onError, onSettled, }) {
71
+ export function recordUpdateMutationOptions(queryClient, { id, detailKey, listsKey, update, name, withVersion, optimistic = true, toastOnError = true, onSuccess, onError, onSettled, }) {
73
72
  const key = hashKey(detailKey);
74
73
  const lists = { queryKey: listsKey };
75
74
  const map = recordStates(queryClient);
@@ -110,8 +109,10 @@ export function recordUpdateMutationOptions(queryClient, { id, detailKey, listsK
110
109
  scope: { id: `record-update:${key}` },
111
110
  mutationFn: (change) => {
112
111
  const confirmed = map.get(key)?.confirmed ?? cached();
113
- if (confirmed)
114
- return update(id, resolve(change, confirmed));
112
+ if (confirmed) {
113
+ const built = resolve(change, confirmed);
114
+ return update(id, withVersion ? withVersion(built, confirmed) : built);
115
+ }
115
116
  // The screen holds the record somewhere these keys don't reach (a
116
117
  // query gathering a related list's records, say). An object change
117
118
  // needs no current record, so it's still sent; a function change
@@ -147,6 +148,10 @@ export function recordUpdateMutationOptions(queryClient, { id, detailKey, listsK
147
148
  const record = state.confirmed;
148
149
  const sent = record ? resolve(change, record) : typeof change === 'function' ? undefined : change;
149
150
  settle(state, context.entry);
151
+ // Another writer saved since: show what they saved (the detail;
152
+ // the lists refetch once the last save settles, in settle).
153
+ if (error.kind === 'conflict')
154
+ void queryClient.invalidateQueries({ queryKey: detailKey });
150
155
  if (toastOnError)
151
156
  toast.error(`Couldn't update ${record ? name(record) : 'this record'}: ${refusalReason(error, sent)}`);
152
157
  }