@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
@@ -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: {
@@ -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);
@@ -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.
@@ -1,3 +1,4 @@
1
+ import { messageOf } from '../../lib/refusal.js';
1
2
  type SafeParse = (value: unknown) => {
2
3
  success: true;
3
4
  data: unknown;
@@ -32,6 +33,13 @@ export type EditFieldConfig = {
32
33
  * value (`text`, `effort`). `null` or `{}` when it names none.
33
34
  */
34
35
  fieldErrors?: (cause: unknown) => Record<string, string> | null;
36
+ /**
37
+ * "Keep mine" after a conflict: `mine` (what's typed, started from
38
+ * `base`) laid onto `theirs` (the value saved elsewhere since), or null
39
+ * when both changed the same part. Without it, "keep mine" saves what's
40
+ * typed over theirs. Long text's default is `rebaseMarkdown`.
41
+ */
42
+ rebase?: ((base: unknown, mine: unknown, theirs: unknown) => unknown) | false;
35
43
  };
36
44
  export type EditFieldState = {
37
45
  status: 'closed';
@@ -58,9 +66,15 @@ export type OpenFieldState = {
58
66
  /**
59
67
  * The saved value changed elsewhere while this held unsaved typing:
60
68
  * nothing saves until `keepMine` (save over it) or `takeSaved` (show it).
61
- * `markConflict` sets it too: the seam for a server's 409 (Roadmap 405).
69
+ * A save the server refused with a 409 (AppError kind `conflict`) sets
70
+ * it too.
62
71
  */
63
72
  conflict?: boolean;
73
+ /**
74
+ * "Keep mine" couldn't lay what's typed onto the value saved elsewhere:
75
+ * both changed the same part. Another "keep mine" replaces theirs.
76
+ */
77
+ overlap?: boolean;
64
78
  };
65
79
  /** How long typing has to stop before an autosaving field saves. */
66
80
  export declare const AUTOSAVE_DELAY_MS = 1000;
@@ -70,8 +84,13 @@ export type EditInPlaceStoreOptions = {
70
84
  };
71
85
  /** What a field shows when the saved value changed under unsaved typing. */
72
86
  export declare const CONFLICT_MESSAGE = "This changed elsewhere (another tab, device or chat) since you started typing. Saving now replaces that.";
73
- /** Why a save failed, in words to show beside what was being saved. */
74
- export declare function messageOf(error: unknown): string;
87
+ /** The conflict's message for a field that can keep both (a `rebase`): Keep Mine adds what's typed to it. */
88
+ 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.";
89
+ /** "Keep mine" found both sides changed the same part. */
90
+ 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.";
91
+ /** Whether a save's rejection is the server's "changed since" (a 409, AppError kind `conflict`). */
92
+ export declare function isConflict(error: unknown): boolean;
93
+ export { messageOf };
75
94
  export declare class EditInPlaceStore {
76
95
  private configs;
77
96
  private states;
@@ -178,11 +197,19 @@ export declare class EditInPlaceStore {
178
197
  refresh(key: string): boolean;
179
198
  /**
180
199
  * The saved value changed under this field's unsaved typing, as a
181
- * server's conflict answer says: the seam for a version check's 409
182
- * (Roadmap 405). Nothing saves until the person picks.
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.
183
202
  */
184
203
  markConflict(key: string): void;
185
- /** A conflict, answered "keep mine": what's typed saves over the value saved elsewhere. */
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
+ */
186
213
  keepMine(key: string): Promise<boolean>;
187
214
  /** A conflict, answered "show the saved one": what's typed goes, and the control starts over from the saved value. */
188
215
  takeSaved(key: string): void;
@@ -194,4 +221,3 @@ export declare class EditInPlaceStore {
194
221
  /** Leaving the page anyway: whatever is open is dropped, and nothing waiting to autosave is sent. */
195
222
  discard(): void;
196
223
  }
197
- export {};
@@ -1,10 +1,71 @@
1
- import { refusalReason } from '../../hooks/use-record-update.js';
1
+ // The rules of editing in place on a record's view, without React (so
2
+ // they're tested on their own, tests/edit-in-place-store.test.ts). One
3
+ // store per EntityView; each editable value is a field in it, and
4
+ // EditableValue is the React side.
5
+ //
6
+ // The rule behind every one: nothing typed is ever lost.
7
+ // - One field open at a time. Opening another saves the open one first;
8
+ // if that save fails, it stays open and the other doesn't open.
9
+ // - Saving: an unchanged draft closes with no request. A draft the form's
10
+ // schema rejects stays open with the schema's message, unsent. Otherwise
11
+ // it's sent; the field stays open (read-only, "Saving…") until the
12
+ // server agrees, then closes. Not optimistic.
13
+ // - A failed save keeps the field open with exactly the draft, and the
14
+ // reason under it. Nothing reverts on its own; saving again retries.
15
+ // - Cancel (Esc) closes and puts the saved value back. Not while saving.
16
+ //
17
+ // A field marked `autosave` (long text, Notion-style) saves on its own:
18
+ // - About a second after typing stops (debounced), and at once on leaving
19
+ // it. It stays open and editable while a save is in flight ("Saving…",
20
+ // then "Saved"); the next save waits behind that one and always sends
21
+ // the latest draft, so quick edits never cross or lose each other.
22
+ // - A failed save keeps the draft and the reason, as above; typing again
23
+ // retries after the pause.
24
+ // - What's been saved stays saved: closing it (leaving, Esc) saves what's
25
+ // left first. Nothing reverts.
26
+ // - A problem the control reports (rich text that can't round-trip) means
27
+ // nothing is saved; it counts as unsaved at once (leaving asks), and its
28
+ // message shows after the pause.
29
+ // - A field leaving the view mid-save (unmounted) still sends what was
30
+ // typed after that save started: the last draft and its config go with
31
+ // the save waiting behind it (`register`'s cleanup).
32
+ // - The saved value changing elsewhere (another tab, a phone, an AI chat)
33
+ // shows at once in a field with nothing of its own unsaved, even with the
34
+ // caret in it (`refresh`). Under unsaved typing it's a conflict: nothing
35
+ // saves until the person picks theirs or the saved one (`keepMine`,
36
+ // `takeSaved`). The server echoing a save back, even normalised
37
+ // (trimmed), is not a change.
38
+ // - The server refusing a save because the record changed since the
39
+ // version it was built on (a 409, AppError kind `conflict`: a writer this
40
+ // tab hadn't heard from yet) is the same conflict: nothing was written,
41
+ // and the record's query refetches (useRecordUpdate) so the latest value
42
+ // arrives. Never a plain failure that saving again would push through.
43
+ // - "Keep mine" keeps both where it can: with a `rebase` (long text's is
44
+ // block by block, rebaseMarkdown), what was typed is laid onto the latest
45
+ // saved value, and the control shows the result as it saves. When both
46
+ // changed the same part, it says so, and only a second "keep mine"
47
+ // replaces the other one.
48
+ // A field marked `alwaysEditable` is also open from the moment it joins:
49
+ // it's the value itself, never "the open field", so it never closes and
50
+ // opening another field leaves it alone.
51
+ import { messageOf } from '../../lib/refusal.js';
2
52
  import { flushPendingEdits } from '../../lib/pending-edits.js';
3
53
  /** How long typing has to stop before an autosaving field saves. */
4
54
  export const AUTOSAVE_DELAY_MS = 1000;
5
55
  const CLOSED = { status: 'closed' };
6
56
  /** What a field shows when the saved value changed under unsaved typing. */
7
57
  export const CONFLICT_MESSAGE = 'This changed elsewhere (another tab, device or chat) since you started typing. Saving now replaces that.';
58
+ /** The conflict's message for a field that can keep both (a `rebase`): Keep Mine adds what's typed to it. */
59
+ export const CONFLICT_REBASE_MESSAGE = 'This changed elsewhere (another tab, device or chat) since you started typing. Keep Mine adds your changes to it.';
60
+ /** "Keep mine" found both sides changed the same part. */
61
+ export 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.";
62
+ function conflictMessage(config) {
63
+ return config?.rebase ? CONFLICT_REBASE_MESSAGE : CONFLICT_MESSAGE;
64
+ }
65
+ /** Whether a save's rejection is the server's "changed since" (a 409, AppError kind `conflict`). */
66
+ export function isConflict(error) {
67
+ return Boolean(error && typeof error === 'object' && error.kind === 'conflict');
68
+ }
8
69
  // Line endings, trailing spaces on a line and blank lines at either end:
9
70
  // what a backend commonly normalises in text it's sent.
10
71
  function normalisedText(value) {
@@ -18,19 +79,13 @@ function normalisedText(value) {
18
79
  // How many of a field's last sent values still count as its own echo.
19
80
  const ECHOES = 4;
20
81
  const sameAsJson = (a, b) => JSON.stringify(a) === JSON.stringify(b);
21
- /** Why a save failed, in words to show beside what was being saved. */
22
- export function messageOf(error) {
23
- if (error && typeof error === 'object' && 'kind' in error)
24
- return refusalReason(error);
25
- if (error instanceof Error)
26
- return error.message;
27
- return 'The save failed. Try again.';
28
- }
29
82
  // The refusal's messages for the value's own fields, or null for none.
30
83
  function fieldErrorsOf(config, cause) {
31
84
  const found = config?.fieldErrors?.(cause);
32
85
  return found && Object.keys(found).length > 0 ? found : undefined;
33
86
  }
87
+ // Re-exported for the components that word a refusal beside the store's.
88
+ export { messageOf };
34
89
  export class EditInPlaceStore {
35
90
  configs = new Map();
36
91
  states = new Map();
@@ -275,7 +330,7 @@ export class EditInPlaceStore {
275
330
  if (!config)
276
331
  return Promise.resolve(false);
277
332
  if (open.problem || open.conflict) {
278
- this.set(key, { ...open, error: open.problem ?? CONFLICT_MESSAGE });
333
+ this.set(key, { ...open, error: open.problem ?? open.error ?? conflictMessage(config) });
279
334
  return Promise.resolve(false);
280
335
  }
281
336
  const isEqual = config.isEqual ?? sameAsJson;
@@ -299,7 +354,12 @@ export class EditInPlaceStore {
299
354
  this.set(key, CLOSED);
300
355
  return true;
301
356
  }, (error) => {
302
- this.set(key, { ...open, status: 'open', error: messageOf(error), fieldErrors: fieldErrorsOf(config, error) });
357
+ // Another writer saved since (a 409): nothing was written, and
358
+ // nothing saves until the person picks.
359
+ if (isConflict(error))
360
+ this.set(key, { ...open, status: 'open', conflict: true, error: conflictMessage(config) });
361
+ else
362
+ this.set(key, { ...open, status: 'open', error: messageOf(error), fieldErrors: fieldErrorsOf(config, error) });
303
363
  return false;
304
364
  })
305
365
  .finally(() => this.saving.delete(key));
@@ -384,7 +444,7 @@ export class EditInPlaceStore {
384
444
  if (!config)
385
445
  return Promise.resolve(false);
386
446
  if (state.problem || state.conflict) {
387
- this.set(key, { ...state, error: state.problem ?? CONFLICT_MESSAGE });
447
+ this.set(key, { ...state, error: state.problem ?? state.error ?? conflictMessage(config) });
388
448
  return Promise.resolve(false);
389
449
  }
390
450
  const isEqual = config.isEqual ?? sameAsJson;
@@ -415,7 +475,15 @@ export class EditInPlaceStore {
415
475
  return true;
416
476
  }, (error) => {
417
477
  const now = this.state(key);
418
- if (now.status === 'open')
478
+ if (now.status !== 'open')
479
+ return false;
480
+ // Another writer saved since (a 409): nothing was written, and
481
+ // nothing saves until the person picks.
482
+ if (isConflict(error)) {
483
+ this.clearTimer(key);
484
+ this.set(key, { ...now, conflict: true, overlap: false, error: conflictMessage(config), fieldErrors: undefined, autosave: undefined });
485
+ }
486
+ else
419
487
  this.set(key, { ...now, error: messageOf(error), fieldErrors: fieldErrorsOf(config, error), autosave: undefined });
420
488
  return false;
421
489
  })
@@ -464,7 +532,9 @@ export class EditInPlaceStore {
464
532
  const busy = this.timers.has(key) || this.autosaving.has(key) || this.queued.has(key) || state.status === 'saving';
465
533
  const clean = !busy && state.error === null && state.problem === null && isEqual(state.draft, state.initial);
466
534
  if (!clean) {
467
- this.set(key, { ...state, conflict: true, error: CONFLICT_MESSAGE });
535
+ // Already a conflict ("keep mine" found an overlap): the new value is
536
+ // what it's now against, and the person picks again.
537
+ this.set(key, { ...state, conflict: true, overlap: false, error: conflictMessage(config) });
468
538
  return false;
469
539
  }
470
540
  const revision = (state.revision ?? 0) + 1;
@@ -473,23 +543,45 @@ export class EditInPlaceStore {
473
543
  }
474
544
  /**
475
545
  * The saved value changed under this field's unsaved typing, as a
476
- * server's conflict answer says: the seam for a version check's 409
477
- * (Roadmap 405). Nothing saves until the person picks.
546
+ * server's conflict answer says. A save refused with a 409 (AppError
547
+ * kind `conflict`) does this itself. Nothing saves until the person picks.
478
548
  */
479
549
  markConflict(key) {
480
550
  const state = this.state(key);
481
551
  if (state.status === 'closed')
482
552
  return;
483
553
  this.clearTimer(key);
484
- this.set(key, { ...state, status: 'open', conflict: true, error: CONFLICT_MESSAGE, autosave: undefined });
554
+ this.set(key, { ...state, status: 'open', conflict: true, error: conflictMessage(this.configs.get(key)?.()), autosave: undefined });
485
555
  }
486
- /** A conflict, answered "keep mine": what's typed saves over the value saved elsewhere. */
556
+ /**
557
+ * A conflict, answered "keep mine". With a `rebase`, what's typed is laid
558
+ * onto the value saved elsewhere and the control starts over showing
559
+ * both (`revision`) as it saves; if both changed the same part it stays
560
+ * a conflict (`overlap`), and keeping mine again saves what's typed over
561
+ * theirs. Without a `rebase`, what's typed saves over it. The save
562
+ * carries the record's latest version, so a writer that saved again
563
+ * meanwhile is another conflict, not an overwrite.
564
+ */
487
565
  keepMine(key) {
488
566
  const state = this.state(key);
489
567
  const config = this.configs.get(key)?.();
490
568
  if (state.status !== 'open' || !state.conflict || !config)
491
569
  return Promise.resolve(false);
492
- this.set(key, { ...state, conflict: false, error: null, initial: config.value });
570
+ let draft = state.draft;
571
+ let revision = state.revision;
572
+ if (config.rebase && !state.overlap) {
573
+ const merged = config.rebase(state.initial, state.draft, config.value);
574
+ if (merged === null || merged === undefined) {
575
+ this.set(key, { ...state, overlap: true, error: OVERLAP_MESSAGE });
576
+ return Promise.resolve(false);
577
+ }
578
+ if (!(config.isEqual ?? sameAsJson)(merged, state.draft)) {
579
+ draft = merged;
580
+ revision = (state.revision ?? 0) + 1;
581
+ }
582
+ }
583
+ this.seen.set(key, config.value);
584
+ this.set(key, { ...state, draft, revision, conflict: false, overlap: false, error: null, initial: config.value });
493
585
  return this.autosaves(key) ? this.flush(key) : this.commit(key);
494
586
  }
495
587
  /** A conflict, answered "show the saved one": what's typed goes, and the control starts over from the saved value. */
@@ -529,7 +621,7 @@ export class EditInPlaceStore {
529
621
  for (const key of this.always) {
530
622
  const state = this.state(key);
531
623
  if (state.status === 'open')
532
- this.set(key, { ...state, draft: state.initial, error: null, problem: null, conflict: false, autosave: undefined });
624
+ this.set(key, { ...state, draft: state.initial, error: null, problem: null, conflict: false, overlap: false, autosave: undefined });
533
625
  }
534
626
  }
535
627
  }
@@ -76,6 +76,7 @@ export type EditInPlace = {
76
76
  shown?: ReactNode;
77
77
  fieldErrors?: (cause: unknown) => Record<string, string> | null;
78
78
  errorsOnFields?: boolean;
79
+ rebase?: ((base: unknown, mine: unknown, theirs: unknown) => unknown) | false;
79
80
  };
80
81
  export type EditInPlaceOptions<TDraft, TValue> = {
81
82
  kind: EditKind;
@@ -138,6 +139,16 @@ export type EditInPlaceOptions<TDraft, TValue> = {
138
139
  * its path inside the value. The control gets them as `errors`.
139
140
  */
140
141
  fieldErrors?: (cause: unknown) => Record<string, string> | null;
142
+ /**
143
+ * "Keep Mine" after the value changed elsewhere (another tab, a phone,
144
+ * an AI chat): what's typed (`mine`, started from `base`) laid onto the
145
+ * value saved since (`theirs`), or null when both changed the same part
146
+ * (the person is told, and a second Keep Mine replaces theirs). Long
147
+ * text (`kind: 'long-text'`, a string) defaults to `rebaseMarkdown`,
148
+ * block by block; `false` turns that off, so Keep Mine saves what's
149
+ * typed over theirs, as every other kind does.
150
+ */
151
+ rebase?: ((base: TDraft, mine: TDraft, theirs: TDraft) => TDraft | null) | false;
141
152
  /**
142
153
  * The control shows `errors` on its own fields, so a refusal about one
143
154
  * of them isn't repeated under the control; one about none still shows there.
@@ -28,6 +28,9 @@ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-run
28
28
  // click to open, and never closes. Ctrl/Cmd+Enter and Esc save now.
29
29
  // - `inline`: always editable, and the control is told to look like the
30
30
  // value it edits (`inline` among its props).
31
+ // - Always editable and a `choice` (4.127, `inPlace.rating`'s stars): a
32
+ // value on one line, so "Saving…" and "Saved" sit beside it, not on a
33
+ // line under it, and "Saved" goes after two seconds, as at rest.
31
34
  // - Saved (4.88, F16): once a save lands, "✓ Saved" shows beside the value
32
35
  // for two seconds (`role="status"`).
33
36
  // - `layout="inline"` (4.102): the pencil takes no room until hover or
@@ -50,6 +53,7 @@ import { Spinner } from '../ui/spinner.js';
50
53
  import { clearPageLeaving, markPageLeaving } from '../../lib/page-leaving.js';
51
54
  import { flushPendingEdits, hasPendingEdits, subscribePendingEdits } from '../../lib/pending-edits.js';
52
55
  import { caretSpot, placeCaretWhenReady, spotAtPoint } from './edit-caret.js';
56
+ import { rebaseMarkdown } from '../../lib/markdown-merge.js';
53
57
  import { EditInPlaceContext } from './edit-in-place.js';
54
58
  import { SAVED_FOR_MS } from './edit-row.js';
55
59
  import { escapePassedThrough } from './escape-passthrough.js';
@@ -129,6 +133,12 @@ function useStore() {
129
133
  throw new Error('<EditableValue> works inside an <EntityView>, which runs editing in place.');
130
134
  return store;
131
135
  }
136
+ // Long text's "Keep Mine": both sides kept block by block (rebaseMarkdown).
137
+ function rebaseText(base, mine, theirs) {
138
+ if (typeof base !== 'string' || typeof mine !== 'string' || typeof theirs !== 'string')
139
+ return null;
140
+ return rebaseMarkdown(base, mine, theirs);
141
+ }
132
142
  export function EditableValue(props) {
133
143
  return _jsx(EditableField, { ...props });
134
144
  }
@@ -142,10 +152,12 @@ export function EditableField({ label, edit, children, layout = 'block', look =
142
152
  const always = Boolean(edit.alwaysEditable || edit.inline);
143
153
  const autosave = always || Boolean(edit.autosave);
144
154
  // The latest config, read by the store whenever it needs it (`inline`
145
- // is always editable to it).
146
- const config = useRef(edit);
155
+ // is always editable to it; long text keeps both sides of a conflict
156
+ // block by block unless it says otherwise).
157
+ const config = useRef({ ...edit, rebase: undefined });
147
158
  useLayoutEffect(() => {
148
- config.current = always && !edit.alwaysEditable ? { ...edit, alwaysEditable: true } : edit;
159
+ const rebase = edit.rebase === false ? undefined : (edit.rebase ?? (edit.kind === 'long-text' ? rebaseText : undefined));
160
+ config.current = { ...edit, alwaysEditable: always || edit.alwaysEditable, rebase };
149
161
  });
150
162
  useEffect(() => store.register(key, () => config.current), [store, key]);
151
163
  const state = useSyncExternalStore(store.subscribe, () => store.state(key), () => store.state(key));
@@ -194,6 +206,21 @@ export function EditableField({ label, edit, children, layout = 'block', look =
194
206
  useEffect(() => {
195
207
  refresh();
196
208
  }, [refresh, edit.value]);
209
+ // Always editable and one pick (stars): its line is beside it (4.127).
210
+ const beside = always && edit.kind === 'choice';
211
+ const autosaved = state.status !== 'closed' && state.autosave === 'saved';
212
+ const [savedGone, setSavedGone] = useState(false);
213
+ const [seenSaved, setSeenSaved] = useState(autosaved);
214
+ if (seenSaved !== autosaved) {
215
+ setSeenSaved(autosaved);
216
+ setSavedGone(false);
217
+ }
218
+ useEffect(() => {
219
+ if (!beside || !autosaved)
220
+ return;
221
+ const timer = window.setTimeout(() => setSavedGone(true), SAVED_FOR_MS);
222
+ return () => window.clearTimeout(timer);
223
+ }, [beside, autosaved]);
197
224
  const isOpen = state.status !== 'closed';
198
225
  const pinned = usePinnedStatus(container, autosave && (isOpen || always));
199
226
  const wasOpen = useRef(false);
@@ -231,7 +258,9 @@ export function EditableField({ label, edit, children, layout = 'block', look =
231
258
  // The first refusal or failed save of an autosaving field toasts too:
232
259
  // its line may be far from where the person is looking (F5). Once per
233
260
  // run of failures; a save that lands starts the count again.
261
+ // A conflict (saved elsewhere) isn't a failed save: its toast says so.
234
262
  const failure = state.status !== 'closed' ? state.error : null;
263
+ const conflicted = state.status !== 'closed' && Boolean(state.conflict);
235
264
  const toasted = useRef(false);
236
265
  useEffect(() => {
237
266
  if (!autosave)
@@ -243,8 +272,11 @@ export function EditableField({ label, edit, children, layout = 'block', look =
243
272
  if (toasted.current)
244
273
  return;
245
274
  toasted.current = true;
246
- toast.error(`Couldn't save ${label}`, { description: failure });
247
- }, [autosave, failure, label]);
275
+ if (conflicted)
276
+ toast.warning(`${label} changed elsewhere`, { description: 'Keep Mine or Show Saved, under it.' });
277
+ else
278
+ toast.error(`Couldn't save ${label}`, { description: failure });
279
+ }, [autosave, failure, conflicted, label]);
248
280
  useEffect(() => () => window.clearTimeout(blurTimer.current), []);
249
281
  // Whether an Esc is closing a list inside the control. Read on the way
250
282
  // down (window, capture): a picker closes its list from a document
@@ -380,11 +412,14 @@ export function EditableField({ label, edit, children, layout = 'block', look =
380
412
  const pin = hasStatus ? pinned : null;
381
413
  // The saved value changed elsewhere under unsaved typing: the person picks (F4).
382
414
  const conflictActions = 'conflict' in open && open.conflict && (_jsxs("span", { className: "mt-1 flex flex-wrap gap-2", children: [_jsx(Button, { type: "button", size: "xs", variant: "outline", onClick: () => void store.keepMine(key), children: "Keep Mine" }), _jsx(Button, { type: "button", size: "xs", variant: "ghost", onClick: () => store.takeSaved(key), children: "Show Saved" })] }));
383
- return (_jsxs(_Fragment, { children: [_jsxs("span", { ref: container, "data-slot": "editable-value", "data-state": saving || autosaving ? 'saving' : open.error ? 'failed' : 'editing', onKeyDown: onKeyDown, onBlur: onBlur, onFocus: onFocus, className: cn('flex min-w-0 flex-col gap-1.5', layout === 'block' ? 'w-full' : 'w-fit max-w-full', className), children: [_jsx(Control, { render: edit.control, id: controlId, value: open.draft, onChange: (value) => store.change(key, value), commit: commit, cancel: cancel, disabled: saving, invalid: !saving && open.error !== null, label: label, describedBy: describedBy, onProblem: (problem) => store.report(key, problem), inline: Boolean(edit.inline), errors: saving ? undefined : fieldErrors }, open.revision ?? 0), _jsx("span", { id: describedBy, "data-slot": "editable-value-status", "data-pinned": pin ? '' : undefined,
415
+ return (_jsxs(_Fragment, { children: [_jsxs("span", { ref: container, "data-slot": "editable-value", "data-state": saving || autosaving ? 'saving' : open.error ? 'failed' : 'editing', onKeyDown: onKeyDown, onBlur: onBlur, onFocus: onFocus, className: cn('flex min-w-0', beside ? 'flex-row flex-wrap items-center gap-x-2 gap-y-1' : 'flex-col gap-1.5', layout === 'block' ? 'w-full' : 'w-fit max-w-full', className), children: [_jsx(Control, { render: edit.control, id: controlId, value: open.draft, onChange: (value) => store.change(key, value), commit: commit, cancel: cancel, disabled: saving, invalid: !saving && open.error !== null, label: label, describedBy: describedBy, onProblem: (problem) => store.report(key, problem), inline: Boolean(edit.inline), errors: saving ? undefined : fieldErrors }, open.revision ?? 0), _jsx("span", { id: describedBy, "data-slot": "editable-value-status", "data-pinned": pin ? '' : undefined,
384
416
  // Pinned to the screen's bottom edge while the field runs past
385
417
  // it, so the save's state and a refusal stay in view (F5).
386
- style: pin ? { left: pin.left, maxWidth: pin.width } : undefined, className: cn('type-body', pin && 'fixed bottom-3 z-30 w-fit rounded-md border border-border bg-popover px-2 py-1 text-popover-foreground shadow-md'), children: autosave ? (_jsxs(_Fragment, { children: [lineError && _jsx(FieldError, { className: "type-caption", children: lineError }), conflictActions, _jsx("span", { role: "status", className: "inline-flex items-center gap-1.5 type-caption text-muted-foreground", children: autosaving ? (_jsxs(_Fragment, { children: [_jsx(Spinner, { "aria-hidden": "true", className: "size-3.5" }), "Saving\u2026"] })) : (open.autosave === 'saved' &&
387
- !open.error && (_jsxs(_Fragment, { children: [_jsx(CheckIcon, { "aria-hidden": "true", className: "size-3.5" }), "Saved"] }))) })] })) : saving ? (_jsxs("span", { role: "status", className: "inline-flex items-center gap-1.5 type-caption text-muted-foreground", children: [_jsx(Spinner, { "aria-hidden": "true", className: "size-3.5" }), "Saving\u2026"] })) : (_jsxs(_Fragment, { children: [lineError && _jsx(FieldError, { className: "type-caption", children: lineError }), conflictActions] })) })] }), _jsx(DiscardChangesDialog, { open: askingDiscard, "data-leave-guard": "", onKeepEditing: () => setAskingDiscard(false), onDiscard: () => {
418
+ style: pin ? { left: pin.left, maxWidth: pin.width } : undefined, className: cn('type-body',
419
+ // Beside the value, a refusal takes the line under it.
420
+ beside && (lineError ? 'basis-full' : 'flex items-center'), pin && 'fixed bottom-3 z-30 w-fit rounded-md border border-border bg-popover px-2 py-1 text-popover-foreground shadow-md'), children: autosave ? (_jsxs(_Fragment, { children: [lineError && _jsx(FieldError, { className: "type-caption", children: lineError }), conflictActions, _jsx("span", { role: "status", className: "inline-flex items-center gap-1.5 type-caption text-muted-foreground", children: autosaving ? (_jsxs(_Fragment, { children: [_jsx(Spinner, { "aria-hidden": "true", className: "size-3.5" }), _jsx("span", { className: cn(beside && 'sr-only'), children: "Saving\u2026" })] })) : (open.autosave === 'saved' &&
421
+ !open.error &&
422
+ !(beside && savedGone) && (_jsxs(_Fragment, { children: [_jsx(CheckIcon, { "aria-hidden": "true", className: cn('size-3.5', beside && 'text-success-text') }), _jsx("span", { className: cn(beside && 'sr-only'), children: "Saved" })] }))) })] })) : saving ? (_jsxs("span", { role: "status", className: "inline-flex items-center gap-1.5 type-caption text-muted-foreground", children: [_jsx(Spinner, { "aria-hidden": "true", className: "size-3.5" }), "Saving\u2026"] })) : (_jsxs(_Fragment, { children: [lineError && _jsx(FieldError, { className: "type-caption", children: lineError }), conflictActions] })) })] }), _jsx(DiscardChangesDialog, { open: askingDiscard, "data-leave-guard": "", onKeepEditing: () => setAskingDiscard(false), onDiscard: () => {
388
423
  setAskingDiscard(false);
389
424
  refocus.current = true;
390
425
  cancel();