@tristan2828/ui-foundation 4.127.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 (43) hide show
  1. package/conventions/docs/add-an-entity.md +52 -16
  2. package/conventions/docs/design-language.md +25 -8
  3. package/dist/components/app/edit-in-place-store.d.ts +2 -3
  4. package/dist/components/app/edit-in-place-store.js +53 -9
  5. package/dist/components/app/entity-form.d.ts +9 -1
  6. package/dist/components/app/entity-form.js +9 -2
  7. package/dist/components/app/equal-items.d.ts +2 -1
  8. package/dist/components/app/equal-items.js +9 -25
  9. package/dist/components/app/form-conflict-notice.d.ts +8 -0
  10. package/dist/components/app/form-conflict-notice.js +15 -0
  11. package/dist/components/app/form-dialog.d.ts +8 -1
  12. package/dist/components/app/form-dialog.js +9 -2
  13. package/dist/components/app/milkdown-editor.js +21 -329
  14. package/dist/components/app/notify.d.ts +18 -1
  15. package/dist/components/app/notify.js +26 -3
  16. package/dist/components/app/page-restore.js +1 -1
  17. package/dist/components/app/rich-text-box-anchor.d.ts +6 -0
  18. package/dist/components/app/rich-text-box-anchor.js +8 -0
  19. package/dist/components/app/rich-text-heading-view.d.ts +4 -0
  20. package/dist/components/app/rich-text-heading-view.js +91 -0
  21. package/dist/components/app/rich-text-link-box.d.ts +9 -0
  22. package/dist/components/app/rich-text-link-box.js +40 -0
  23. package/dist/components/app/rich-text-links.d.ts +14 -0
  24. package/dist/components/app/rich-text-links.js +92 -0
  25. package/dist/components/app/rich-text-page-box.d.ts +10 -0
  26. package/dist/components/app/rich-text-page-box.js +45 -0
  27. package/dist/components/app/rich-text-task-item-view.d.ts +4 -0
  28. package/dist/components/app/rich-text-task-item-view.js +59 -0
  29. package/dist/components/app/rich-text-toggle-heading.js +1 -1
  30. package/dist/components/app/step-row.d.ts +15 -0
  31. package/dist/components/app/step-row.js +27 -0
  32. package/dist/components/app/step-track.d.ts +82 -0
  33. package/dist/components/app/step-track.js +98 -0
  34. package/dist/components/ui/sonner.js +1 -1
  35. package/dist/hooks/use-form-version.d.ts +101 -0
  36. package/dist/hooks/use-form-version.js +187 -0
  37. package/dist/hooks/use-record-update.d.ts +2 -7
  38. package/dist/hooks/use-record-update.js +2 -11
  39. package/dist/index.d.ts +3 -1
  40. package/dist/index.js +2 -0
  41. package/dist/lib/refusal.d.ts +9 -0
  42. package/dist/lib/refusal.js +19 -0
  43. package/package.json +1 -1
@@ -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
@@ -63,12 +64,7 @@ type Entry<TRecord, TUpdate> = {
63
64
  change: RecordChange<TRecord, TUpdate>;
64
65
  optimistic: boolean;
65
66
  };
66
- /**
67
- * Why a save was refused, in the server's words: for a 422, the message
68
- * on a field the save sent (the first field error otherwise), else the
69
- * `AppError`'s message.
70
- */
71
- export declare function refusalReason(error: AppError, sent?: object): string;
67
+ export { refusalReason };
72
68
  /**
73
69
  * The mutation options behind `useRecordUpdate`, for a given QueryClient.
74
70
  * Exported for tests and for code outside React; screens use the hook.
@@ -92,4 +88,3 @@ export declare function useRecordUpdate<TRecord extends {
92
88
  }, TUpdate extends Partial<TRecord>>(options: RecordUpdateOptions<TRecord, TUpdate>): import("@tanstack/react-query").UseMutationResult<TRecord, AppError, RecordChange<TRecord, TUpdate>, {
93
89
  entry: Entry<TRecord, TUpdate>;
94
90
  }>;
95
- export {};
@@ -47,6 +47,7 @@
47
47
  // mutation, after the package's own cache work, either way (#250).
48
48
  import { hashKey, useMutation, useQueryClient, } from '@tanstack/react-query';
49
49
  import { toast } from 'sonner';
50
+ import { refusalReason } from '../lib/refusal.js';
50
51
  const states = new WeakMap();
51
52
  function recordStates(queryClient) {
52
53
  let map = states.get(queryClient);
@@ -62,17 +63,7 @@ const notLoaded = {
62
63
  function resolve(change, record) {
63
64
  return typeof change === 'function' ? change(record) : change;
64
65
  }
65
- /**
66
- * Why a save was refused, in the server's words: for a 422, the message
67
- * on a field the save sent (the first field error otherwise), else the
68
- * `AppError`'s message.
69
- */
70
- export function refusalReason(error, sent) {
71
- const fieldErrors = Object.entries(error.fieldErrors ?? {});
72
- const fields = Object.keys(sent ?? {});
73
- const onSentField = fieldErrors.find(([key]) => fields.some((field) => key === field || key.startsWith(`${field}.`)));
74
- return (onSentField ?? fieldErrors[0])?.[1][0] ?? error.message;
75
- }
66
+ export { refusalReason };
76
67
  /**
77
68
  * The mutation options behind `useRecordUpdate`, for a given QueryClient.
78
69
  * Exported for tests and for code outside React; screens use the hook.
package/dist/index.d.ts CHANGED
@@ -38,7 +38,7 @@ export { RecordDialogRoute, RecordLink, type RecordDialogRouteProps, type Record
38
38
  export { recordDialogState, useNewRecordDialog, useOpenRecord, useRecordDialog, type NewRecordDialogContextValue, type RecordDialogBackground, type RecordDialogContextValue, type RecordDialogState, } from './components/app/record-dialog-context.js';
39
39
  export { FormDialog, type FormDialogProps } from './components/app/form-dialog.js';
40
40
  export { DeleteAction, type DeleteActionProps, type DeleteKind, type DeleteReason } from './components/app/delete-action.js';
41
- export { notify, doneMessage, pastTense, type NotifyDoneOptions } from './components/app/notify.js';
41
+ export { notify, doneMessage, pastTense, type NotifyDoneOptions, type NotifyOpen } from './components/app/notify.js';
42
42
  export { useAction, type ActionOutcome, type ActionState, type UseActionOptions } from './hooks/use-action.js';
43
43
  export { ActionError, type ActionErrorProps } from './components/app/action-error.js';
44
44
  export { JobStatus, type JobProgress, type JobStatusProps } from './components/app/job-status.js';
@@ -86,6 +86,7 @@ export { ValueList, type ValueListItem, type ValueListProps } from './components
86
86
  export { ListHeader, type ListHeaderAction, type ListHeaderLink, type ListHeaderProps, type ListHeaderSecondaryAction, type ListHeaderSibling, } from './components/app/list-header.js';
87
87
  export { Timeline, type TimelineItem, type TimelineProps } from './components/app/timeline.js';
88
88
  export { EqualItems, type EqualItem, type EqualItemField, type EqualItemState, type EqualItemStep, type EqualItemTone, type EqualItemsLook, type EqualItemsProps, } from './components/app/equal-items.js';
89
+ export { StepTrack, type StepTrackProps, type StepTrackState, type StepTrackStep, } from './components/app/step-track.js';
89
90
  export { NeedsYou, type NeedsYouItem, type NeedsYouProps, type NeedsYouTone } from './components/app/needs-you.js';
90
91
  export { Freshness, type FreshnessProps } from './components/app/freshness.js';
91
92
  export { isStale } from './lib/freshness.js';
@@ -130,6 +131,7 @@ export type { TableView, UrlChanges } from './hooks/table-url-changes.js';
130
131
  export { useDebouncedValue } from './hooks/use-debounced-value.js';
131
132
  export { useDocumentTitle } from './hooks/use-document-title.js';
132
133
  export { useRecordUpdate, type RecordChange, type RecordUpdateOptions, } from './hooks/use-record-update.js';
134
+ export { useFormVersion, type FormConflict, type FormVersion, type FormVersionOptions, } from './hooks/use-form-version.js';
133
135
  export { useIsMobile } from './hooks/use-mobile.js';
134
136
  export { useWakeLock } from './hooks/use-wake-lock.js';
135
137
  export { useSessionClock, type SessionClock, type SessionClockOptions, type SessionClockState, type SessionStatus, } from './hooks/use-session-clock.js';
package/dist/index.js CHANGED
@@ -97,6 +97,7 @@ export { ValueList } from './components/app/value-list.js';
97
97
  export { ListHeader, } from './components/app/list-header.js';
98
98
  export { Timeline } from './components/app/timeline.js';
99
99
  export { EqualItems, } from './components/app/equal-items.js';
100
+ export { StepTrack, } from './components/app/step-track.js';
100
101
  export { NeedsYou } from './components/app/needs-you.js';
101
102
  export { Freshness } from './components/app/freshness.js';
102
103
  export { isStale } from './lib/freshness.js';
@@ -140,6 +141,7 @@ export { useWidgetLayout, createWidgetLayoutStore, mergeWidgetLayout, } from './
140
141
  export { useDebouncedValue } from './hooks/use-debounced-value.js';
141
142
  export { useDocumentTitle } from './hooks/use-document-title.js';
142
143
  export { useRecordUpdate, } from './hooks/use-record-update.js';
144
+ export { useFormVersion, } from './hooks/use-form-version.js';
143
145
  export { useIsMobile } from './hooks/use-mobile.js';
144
146
  // Timed screens (docs/foundation/timed-screens.md)
145
147
  export { useWakeLock } from './hooks/use-wake-lock.js';
@@ -0,0 +1,9 @@
1
+ import type { AppError } from '../api/contracts.js';
2
+ /**
3
+ * Why a save was refused, in the server's words: for a 422, the message
4
+ * on a field the save sent (the first field error otherwise), else the
5
+ * `AppError`'s message.
6
+ */
7
+ export declare function refusalReason(error: AppError, sent?: object): string;
8
+ /** Why a save failed, in words to show beside what was being saved. */
9
+ export declare function messageOf(error: unknown): string;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Why a save was refused, in the server's words: for a 422, the message
3
+ * on a field the save sent (the first field error otherwise), else the
4
+ * `AppError`'s message.
5
+ */
6
+ export function refusalReason(error, sent) {
7
+ const fieldErrors = Object.entries(error.fieldErrors ?? {});
8
+ const fields = Object.keys(sent ?? {});
9
+ const onSentField = fieldErrors.find(([key]) => fields.some((field) => key === field || key.startsWith(`${field}.`)));
10
+ return (onSentField ?? fieldErrors[0])?.[1][0] ?? error.message;
11
+ }
12
+ /** Why a save failed, in words to show beside what was being saved. */
13
+ export function messageOf(error) {
14
+ if (error && typeof error === 'object' && 'kind' in error)
15
+ return refusalReason(error);
16
+ if (error instanceof Error)
17
+ return error.message;
18
+ return 'The save failed. Try again.';
19
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tristan2828/ui-foundation",
3
- "version": "4.127.0",
3
+ "version": "4.128.0",
4
4
  "description": "Shared UI foundation for contract-first, database-backed React apps: shadcn primitives, DataTable/EntityForm composites, auth, the gateway error seam, design tokens, lint rules and the AI playbook.",
5
5
  "license": "MIT",
6
6
  "repository": {