@tristan2828/ui-foundation 4.124.2 → 4.126.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +1 -1
  2. package/conventions/docs/add-an-entity.md +42 -21
  3. package/conventions/docs/cell-patterns.md +80 -39
  4. package/dist/api/transport/index.js +10 -1
  5. package/dist/components/app/edit-caret.d.ts +25 -0
  6. package/dist/components/app/edit-caret.js +118 -0
  7. package/dist/components/app/edit-in-place-store.d.ts +43 -4
  8. package/dist/components/app/edit-in-place-store.js +169 -19
  9. package/dist/components/app/editable-value.js +164 -22
  10. package/dist/components/app/entity-form.js +4 -0
  11. package/dist/components/app/entity-view.js +1 -1
  12. package/dist/components/app/form-leave-guard.js +7 -1
  13. package/dist/components/app/milkdown-editor.d.ts +1 -0
  14. package/dist/components/app/milkdown-editor.js +224 -63
  15. package/dist/components/app/prose-look.d.ts +1 -1
  16. package/dist/components/app/prose-look.js +3 -1
  17. package/dist/components/app/rich-text-autolink.d.ts +6 -0
  18. package/dist/components/app/rich-text-autolink.js +79 -0
  19. package/dist/components/app/rich-text-edges.d.ts +8 -0
  20. package/dist/components/app/rich-text-edges.js +144 -0
  21. package/dist/components/app/rich-text-editor.d.ts +15 -2
  22. package/dist/components/app/rich-text-editor.js +16 -4
  23. package/dist/components/app/rich-text-empty-paragraph.d.ts +14 -6
  24. package/dist/components/app/rich-text-empty-paragraph.js +19 -8
  25. package/dist/components/app/rich-text-formats.js +88 -15
  26. package/dist/components/app/rich-text-full-screen.d.ts +2 -0
  27. package/dist/components/app/rich-text-full-screen.js +78 -0
  28. package/dist/components/app/rich-text-highlight-menu.d.ts +3 -1
  29. package/dist/components/app/rich-text-highlight-menu.js +3 -2
  30. package/dist/components/app/rich-text-input-rules.d.ts +7 -0
  31. package/dist/components/app/rich-text-input-rules.js +83 -0
  32. package/dist/components/app/rich-text-keyboard-bar.d.ts +24 -0
  33. package/dist/components/app/rich-text-keyboard-bar.js +214 -0
  34. package/dist/components/app/rich-text-node-views.js +2 -1
  35. package/dist/components/app/rich-text-paste.d.ts +43 -0
  36. package/dist/components/app/rich-text-paste.js +355 -0
  37. package/dist/components/app/rich-text-shortcuts.d.ts +5 -1
  38. package/dist/components/app/rich-text-shortcuts.js +132 -2
  39. package/dist/components/app/rich-text-slash-menu.js +47 -9
  40. package/dist/components/app/rich-text-slash.d.ts +7 -0
  41. package/dist/components/app/rich-text-slash.js +27 -14
  42. package/dist/components/app/rich-text-table-grips.d.ts +8 -6
  43. package/dist/components/app/rich-text-table-grips.js +11 -12
  44. package/dist/components/app/rich-text-tasks.d.ts +8 -0
  45. package/dist/components/app/rich-text-tasks.js +20 -0
  46. package/dist/components/app/rich-text-toolbar.d.ts +5 -1
  47. package/dist/components/app/rich-text-toolbar.js +13 -5
  48. package/dist/components/app/rich-text-touch.d.ts +2 -0
  49. package/dist/components/app/rich-text-touch.js +18 -0
  50. package/dist/components/app/rich-text-widgets.js +1 -1
  51. package/dist/hooks/table-url-changes.d.ts +4 -0
  52. package/dist/hooks/table-url-changes.js +13 -0
  53. package/dist/hooks/use-table-url-state.js +14 -8
  54. package/dist/index.d.ts +1 -0
  55. package/dist/index.js +3 -0
  56. package/dist/lib/markdown-merge.d.ts +26 -0
  57. package/dist/lib/markdown-merge.js +112 -17
  58. package/dist/lib/page-leaving.d.ts +8 -0
  59. package/dist/lib/page-leaving.js +30 -0
  60. package/dist/lib/pending-edits.d.ts +14 -0
  61. package/dist/lib/pending-edits.js +51 -0
  62. package/dist/mocks/e2e-hooks.js +10 -0
  63. package/dist/mocks/override.d.ts +8 -0
  64. package/dist/mocks/start-worker.d.ts +24 -0
  65. package/dist/mocks/start-worker.js +120 -3
  66. package/dist/testing/index.d.ts +84 -5
  67. package/dist/testing/index.js +177 -10
  68. package/package.json +1 -1
  69. package/styles/index.css +7 -0
@@ -1,7 +1,22 @@
1
1
  import { refusalReason } from '../../hooks/use-record-update.js';
2
+ import { flushPendingEdits } from '../../lib/pending-edits.js';
2
3
  /** How long typing has to stop before an autosaving field saves. */
3
4
  export const AUTOSAVE_DELAY_MS = 1000;
4
5
  const CLOSED = { status: 'closed' };
6
+ /** What a field shows when the saved value changed under unsaved typing. */
7
+ export const CONFLICT_MESSAGE = 'This changed elsewhere (another tab, device or chat) since you started typing. Saving now replaces that.';
8
+ // Line endings, trailing spaces on a line and blank lines at either end:
9
+ // what a backend commonly normalises in text it's sent.
10
+ function normalisedText(value) {
11
+ return value
12
+ .replace(/\r\n?/g, '\n')
13
+ .split('\n')
14
+ .map((line) => line.trimEnd())
15
+ .join('\n')
16
+ .trim();
17
+ }
18
+ // How many of a field's last sent values still count as its own echo.
19
+ const ECHOES = 4;
5
20
  const sameAsJson = (a, b) => JSON.stringify(a) === JSON.stringify(b);
6
21
  /** Why a save failed, in words to show beside what was being saved. */
7
22
  export function messageOf(error) {
@@ -31,6 +46,14 @@ export class EditInPlaceStore {
31
46
  always = new Set();
32
47
  // Leaving the page, waiting for its saves: the leave prompt stays.
33
48
  holds = 0;
49
+ // The saved value each field last saw (`refresh` tells a change from it),
50
+ // and the values it last sent (their echo isn't a change elsewhere).
51
+ seen = new Map();
52
+ sent = new Map();
53
+ // Saves of fields that left the view mid-save, still to send or land.
54
+ detached = new Set();
55
+ // The page is hidden: an autosave doesn't wait for the pause.
56
+ hurried = false;
34
57
  constructor(options = {}) {
35
58
  this.autosaveDelay = options.autosaveDelay ?? AUTOSAVE_DELAY_MS;
36
59
  }
@@ -54,23 +77,59 @@ export class EditInPlaceStore {
54
77
  register(key, config) {
55
78
  this.configs.set(key, config);
56
79
  const { alwaysEditable, value } = config();
80
+ this.seen.set(key, value);
57
81
  if (alwaysEditable) {
58
82
  this.always.add(key);
59
83
  this.set(key, { status: 'open', draft: value, initial: value, error: null, problem: null });
60
84
  }
61
85
  return () => {
86
+ // A rich-text editor reports its typing a pause after it stops
87
+ // (src/lib/pending-edits.ts, F6): asked for now, before this reads it.
88
+ flushPendingEdits();
89
+ const inFlight = this.autosaving.get(key);
90
+ const state = this.state(key);
91
+ const last = this.configs.get(key)?.();
92
+ // With a save in flight, what was typed since goes once it lands,
93
+ // from this draft and config: the field is gone by then (F3).
94
+ if (inFlight) {
95
+ this.clearTimer(key);
96
+ if (state.status === 'open' && last)
97
+ this.sendDetached(inFlight, state, last);
98
+ }
62
99
  // A save still waiting for the pause goes now: the field is leaving,
63
100
  // not giving up what was typed.
64
- if (this.timers.has(key))
101
+ else if (this.timers.has(key))
65
102
  void this.flush(key);
66
103
  this.configs.delete(key);
67
104
  this.states.delete(key);
105
+ this.seen.delete(key);
106
+ this.sent.delete(key);
68
107
  if (this.openKey === key)
69
108
  this.openKey = null;
70
109
  if (this.always.delete(key))
71
110
  this.emit();
72
111
  };
73
112
  }
113
+ // A field that left mid-save: once its save in flight settles, its last
114
+ // draft is sent if it's newer than what that save held.
115
+ sendDetached(inFlight, state, config) {
116
+ const isEqual = config.isEqual ?? sameAsJson;
117
+ const run = inFlight.promise
118
+ .then((saved) => {
119
+ if (state.problem || state.conflict || isEqual(state.draft, inFlight.draft))
120
+ return saved;
121
+ const parsed = config.schema ? config.schema.safeParse(state.draft) : { success: true, data: state.draft };
122
+ if (!parsed.success)
123
+ return false;
124
+ return config.save(parsed.data).then(() => true, () => false);
125
+ })
126
+ .finally(() => {
127
+ this.detached.delete(run);
128
+ this.emit();
129
+ });
130
+ this.detached.add(run);
131
+ this.emit();
132
+ }
74
133
  state(key) {
75
134
  return this.states.get(key) ?? CLOSED;
76
135
  }
@@ -83,7 +142,7 @@ export class EditInPlaceStore {
83
142
  * a move off the page waiting for its saves (`hold`).
84
143
  */
85
144
  get editing() {
86
- return this.openKey !== null || this.always.size > 0 || this.holds > 0;
145
+ return this.openKey !== null || this.always.size > 0 || this.holds > 0 || this.detached.size > 0;
87
146
  }
88
147
  /**
89
148
  * Keeps `editing` true until released: the leave prompt, saving on the
@@ -103,11 +162,17 @@ export class EditInPlaceStore {
103
162
  }
104
163
  /** Whether leaving the page now would lose something: a draft that isn't saved. */
105
164
  get dirty() {
106
- return this.unsaved().length > 0;
165
+ return this.unsaved().length > 0 || this.detached.size > 0;
107
166
  }
108
- /** Whether everything unsaved saves on its own, so leaving can save it first rather than ask. */
167
+ /**
168
+ * Whether everything unsaved saves on its own, so leaving can save it
169
+ * first rather than ask. A problem or a conflict can't: leaving asks at once.
170
+ */
109
171
  get savesOnLeave() {
110
- return this.unsaved().every((key) => this.autosaves(key));
172
+ return this.unsaved().every((key) => {
173
+ const state = this.state(key);
174
+ return this.autosaves(key) && !(state.status !== 'closed' && (state.problem || state.conflict));
175
+ });
111
176
  }
112
177
  unsaved() {
113
178
  const keys = new Set(this.always);
@@ -119,6 +184,9 @@ export class EditInPlaceStore {
119
184
  return false;
120
185
  if (state.status === 'saving' || this.autosaving.has(key) || state.error !== null)
121
186
  return true;
187
+ // A reported problem is unsaved at once, not only after the pause (F5).
188
+ if (state.problem !== null || state.conflict)
189
+ return true;
122
190
  return !this.isEqual(key)(state.draft, state.initial);
123
191
  });
124
192
  }
@@ -149,6 +217,7 @@ export class EditInPlaceStore {
149
217
  if (!config)
150
218
  return false;
151
219
  this.openKey = key;
220
+ this.seen.set(key, config.value);
152
221
  this.set(key, { status: 'open', draft: config.value, initial: config.value, error: null, problem: null });
153
222
  return true;
154
223
  }
@@ -188,6 +257,7 @@ export class EditInPlaceStore {
188
257
  * and resolves true once what's on screen is saved.
189
258
  */
190
259
  commit(key, draft) {
260
+ flushPendingEdits();
191
261
  if (this.autosaves(key))
192
262
  return this.commitAutosaved(key, draft);
193
263
  const inFlight = this.saving.get(key);
@@ -204,8 +274,8 @@ export class EditInPlaceStore {
204
274
  const config = this.configs.get(key)?.();
205
275
  if (!config)
206
276
  return Promise.resolve(false);
207
- if (open.problem) {
208
- this.set(key, { ...open, error: open.problem });
277
+ if (open.problem || open.conflict) {
278
+ this.set(key, { ...open, error: open.problem ?? CONFLICT_MESSAGE });
209
279
  return Promise.resolve(false);
210
280
  }
211
281
  const isEqual = config.isEqual ?? sameAsJson;
@@ -220,6 +290,9 @@ export class EditInPlaceStore {
220
290
  return Promise.resolve(false);
221
291
  }
222
292
  this.set(key, { ...open, status: 'saving', error: null, fieldErrors: undefined });
293
+ this.remember(key, open.draft);
294
+ if (parsed.data !== open.draft)
295
+ this.remember(key, parsed.data);
223
296
  const save = config
224
297
  .save(parsed.data)
225
298
  .then(() => {
@@ -254,7 +327,25 @@ export class EditInPlaceStore {
254
327
  this.timers.set(key, setTimeout(() => {
255
328
  this.timers.delete(key);
256
329
  void this.flush(key);
257
- }, this.autosaveDelay));
330
+ }, this.hurried ? 0 : this.autosaveDelay));
331
+ }
332
+ /**
333
+ * The page is hidden (another tab, a phone's home screen, F13): while it
334
+ * is, an autosave goes without the pause, and one waiting goes now.
335
+ */
336
+ hurry(hidden) {
337
+ this.hurried = hidden;
338
+ if (hidden)
339
+ for (const key of [...this.timers.keys()])
340
+ void this.flush(key);
341
+ }
342
+ // A value this field sent: its echo from the server isn't a change elsewhere.
343
+ remember(key, value) {
344
+ this.sent.set(key, [...(this.sent.get(key) ?? []), value].slice(-ECHOES));
345
+ }
346
+ isEcho(key, value, isEqual) {
347
+ return (this.sent.get(key) ?? []).some((sent) => isEqual(value, sent) ||
348
+ (typeof value === 'string' && typeof sent === 'string' && normalisedText(value) === normalisedText(sent)));
258
349
  }
259
350
  clearTimer(key) {
260
351
  clearTimeout(this.timers.get(key));
@@ -267,6 +358,8 @@ export class EditInPlaceStore {
267
358
  * sent is saved (or there was nothing to send).
268
359
  */
269
360
  flush(key) {
361
+ // Typing an editor holds back is reported first (F6).
362
+ flushPendingEdits();
270
363
  this.clearTimer(key);
271
364
  const inFlight = this.autosaving.get(key);
272
365
  if (inFlight) {
@@ -290,8 +383,8 @@ export class EditInPlaceStore {
290
383
  const config = this.configs.get(key)?.();
291
384
  if (!config)
292
385
  return Promise.resolve(false);
293
- if (state.problem) {
294
- this.set(key, { ...state, error: state.problem });
386
+ if (state.problem || state.conflict) {
387
+ this.set(key, { ...state, error: state.problem ?? CONFLICT_MESSAGE });
295
388
  return Promise.resolve(false);
296
389
  }
297
390
  const isEqual = config.isEqual ?? sameAsJson;
@@ -307,6 +400,9 @@ export class EditInPlaceStore {
307
400
  return Promise.resolve(false);
308
401
  }
309
402
  const sent = state.draft;
403
+ this.remember(key, sent);
404
+ if (parsed.data !== sent)
405
+ this.remember(key, parsed.data);
310
406
  this.set(key, { ...state, error: null, fieldErrors: undefined, autosave: 'saving' });
311
407
  const promise = config
312
408
  .save(parsed.data)
@@ -332,34 +428,86 @@ export class EditInPlaceStore {
332
428
  * (leaving the page). Resolves true once nothing unsaved is left.
333
429
  */
334
430
  async saveAll() {
431
+ flushPendingEdits();
335
432
  const keys = this.unsaved().filter((key) => this.autosaves(key));
336
- const results = await Promise.all(keys.map((key) => this.flush(key)));
433
+ const results = await Promise.all([...keys.map((key) => this.flush(key)), ...this.detached]);
337
434
  return results.every(Boolean) && !this.dirty;
338
435
  }
339
436
  /**
340
- * An always-editable field shows the saved value again when it changed
341
- * elsewhere (another tab, the form), but only while nothing of its own
342
- * is unsaved or saving. True when it did: the control starts over.
437
+ * The field's saved value (its config's `value`) may have changed
438
+ * elsewhere: another tab, a phone, an AI chat, the form. Call it whenever
439
+ * the value changes. An open autosaving field with nothing of its own unsaved or
440
+ * saving shows it, starting its control over (`revision`): true when it
441
+ * did, so the caret can be put back (F4). One with unsaved typing gets a
442
+ * conflict (`conflict`, its message), and nothing saves until the person
443
+ * picks. The field's own save coming back, as sent or as the server
444
+ * normalised it (trimmed), is no change: the control keeps its text and
445
+ * its undo (F25).
343
446
  */
344
447
  refresh(key) {
448
+ // Typing an editor holds back counts as unsaved (a conflict, not a reload).
449
+ flushPendingEdits();
345
450
  const state = this.state(key);
346
451
  const config = this.configs.get(key)?.();
347
- if (!this.always.has(key) || state.status !== 'open' || !config)
348
- return false;
349
- if (this.timers.has(key) || this.autosaving.has(key) || state.error !== null)
452
+ // Only a field that saves itself (notes): a field opened by a click
453
+ // holds its draft until it's saved, and a control that saves each
454
+ // pick itself (MultiPick) changes the value it shows while open.
455
+ if (state.status === 'closed' || !config || !this.autosaves(key))
350
456
  return false;
351
457
  const isEqual = config.isEqual ?? sameAsJson;
352
- if (!isEqual(state.draft, state.initial) || isEqual(config.value, state.initial))
458
+ const seen = this.seen.has(key) ? this.seen.get(key) : state.initial;
459
+ if (isEqual(config.value, seen))
353
460
  return false;
461
+ this.seen.set(key, config.value);
462
+ if (this.isEcho(key, config.value, isEqual) || isEqual(config.value, state.initial))
463
+ return false;
464
+ const busy = this.timers.has(key) || this.autosaving.has(key) || this.queued.has(key) || state.status === 'saving';
465
+ const clean = !busy && state.error === null && state.problem === null && isEqual(state.draft, state.initial);
466
+ if (!clean) {
467
+ this.set(key, { ...state, conflict: true, error: CONFLICT_MESSAGE });
468
+ return false;
469
+ }
354
470
  const revision = (state.revision ?? 0) + 1;
355
471
  this.set(key, { status: 'open', draft: config.value, initial: config.value, error: null, problem: null, revision });
356
472
  return true;
357
473
  }
474
+ /**
475
+ * 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.
478
+ */
479
+ markConflict(key) {
480
+ const state = this.state(key);
481
+ if (state.status === 'closed')
482
+ return;
483
+ this.clearTimer(key);
484
+ this.set(key, { ...state, status: 'open', conflict: true, error: CONFLICT_MESSAGE, autosave: undefined });
485
+ }
486
+ /** A conflict, answered "keep mine": what's typed saves over the value saved elsewhere. */
487
+ keepMine(key) {
488
+ const state = this.state(key);
489
+ const config = this.configs.get(key)?.();
490
+ if (state.status !== 'open' || !state.conflict || !config)
491
+ return Promise.resolve(false);
492
+ this.set(key, { ...state, conflict: false, error: null, initial: config.value });
493
+ return this.autosaves(key) ? this.flush(key) : this.commit(key);
494
+ }
495
+ /** A conflict, answered "show the saved one": what's typed goes, and the control starts over from the saved value. */
496
+ takeSaved(key) {
497
+ const state = this.state(key);
498
+ const config = this.configs.get(key)?.();
499
+ if (state.status !== 'open' || !state.conflict || !config)
500
+ return;
501
+ this.clearTimer(key);
502
+ const revision = (state.revision ?? 0) + 1;
503
+ this.set(key, { status: 'open', draft: config.value, initial: config.value, error: null, problem: null, revision });
504
+ }
358
505
  /**
359
506
  * Esc: closes and shows the saved value again. Not while a save is in
360
507
  * flight, and never for an always-editable field.
361
508
  */
362
509
  cancel(key) {
510
+ flushPendingEdits();
363
511
  const state = this.state(key);
364
512
  if (state.status !== 'open' || this.always.has(key) || this.autosaving.has(key))
365
513
  return;
@@ -368,6 +516,8 @@ export class EditInPlaceStore {
368
516
  }
369
517
  /** Leaving the page anyway: whatever is open is dropped, and nothing waiting to autosave is sent. */
370
518
  discard() {
519
+ // Reported now, so nothing held back lands after it's dropped.
520
+ flushPendingEdits();
371
521
  for (const key of [...this.timers.keys()])
372
522
  this.clearTimer(key);
373
523
  if (this.openKey !== null) {
@@ -379,7 +529,7 @@ export class EditInPlaceStore {
379
529
  for (const key of this.always) {
380
530
  const state = this.state(key);
381
531
  if (state.status === 'open')
382
- this.set(key, { ...state, draft: state.initial, error: null, autosave: undefined });
532
+ this.set(key, { ...state, draft: state.initial, error: null, problem: null, conflict: false, autosave: undefined });
383
533
  }
384
534
  }
385
535
  }
@@ -13,7 +13,17 @@ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-run
13
13
  // the server agrees. Failed: it stays, with the draft and the reason.
14
14
  // - `autosave`: it saves itself a pause after typing stops and stays
15
15
  // editable while it does ("Saving…", then "Saved" under it). Leaving,
16
- // Ctrl/Cmd+Enter and Esc save what's left now and close it.
16
+ // Ctrl/Cmd+Enter and Esc save what's left now and close it. On a note
17
+ // longer than the screen the line under it is pinned to the screen's
18
+ // bottom edge, so a refusal or a failed save is never off screen, and
19
+ // the first one also toasts (F5).
20
+ // - `long-text` without `autosave`: Esc on a changed draft asks
21
+ // ("Discard your changes?") rather than dropping it (F7).
22
+ // - Opening by a click puts the caret where the click was, not at the
23
+ // top, and the page doesn't move (F8).
24
+ // - The saved value changing elsewhere shows at once when nothing here is
25
+ // unsaved, the caret keeping its block; under unsaved typing the line
26
+ // says so, with "Keep Mine" and "Show Saved" (F4).
17
27
  // - `alwaysEditable`: the control is shown at rest, with no pencil and no
18
28
  // click to open, and never closes. Ctrl/Cmd+Enter and Esc save now.
19
29
  // - `inline`: always editable, and the control is told to look like the
@@ -31,11 +41,15 @@ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-run
31
41
  import { CheckIcon, ChevronRightIcon, PencilIcon } from 'lucide-react';
32
42
  import { useCallback, useContext, useEffect, useId, useLayoutEffect, useRef, useState, useSyncExternalStore } from 'react';
33
43
  import { useBlocker } from 'react-router';
44
+ import { toast } from 'sonner';
34
45
  import { cn } from 'cn';
35
46
  import { Button } from '../ui/button.js';
36
47
  import { DiscardChangesDialog } from '../ui/dialog.js';
37
48
  import { FieldError } from '../ui/field.js';
38
49
  import { Spinner } from '../ui/spinner.js';
50
+ import { clearPageLeaving, markPageLeaving } from '../../lib/page-leaving.js';
51
+ import { flushPendingEdits, hasPendingEdits, subscribePendingEdits } from '../../lib/pending-edits.js';
52
+ import { caretSpot, placeCaretWhenReady, spotAtPoint } from './edit-caret.js';
39
53
  import { EditInPlaceContext } from './edit-in-place.js';
40
54
  import { SAVED_FOR_MS } from './edit-row.js';
41
55
  import { escapePassedThrough } from './escape-passthrough.js';
@@ -68,6 +82,47 @@ function InlinePencilRoom({ inline, children }) {
68
82
  function Control({ render, ...props }) {
69
83
  return render(props);
70
84
  }
85
+ // While a field runs past the bottom of the screen, its status line (the
86
+ // save's state, a refusal) is pinned to the screen's bottom edge, under the
87
+ // field's left edge, so it's never off screen (F5). Not CSS sticky: a
88
+ // section's card clips its content (`overflow-hidden`), which stops sticky
89
+ // at the card. Returns where to pin it, or null while it shows in place.
90
+ function usePinnedStatus(field, enabled) {
91
+ const [pin, setPin] = useState(null);
92
+ useLayoutEffect(() => {
93
+ if (!enabled)
94
+ return;
95
+ let frame = 0;
96
+ const measure = () => {
97
+ frame = 0;
98
+ const box = field.current?.getBoundingClientRect();
99
+ const runsPast = box !== undefined && box.top < window.innerHeight - 48 && box.bottom > window.innerHeight;
100
+ setPin((current) => {
101
+ if (!runsPast)
102
+ return null;
103
+ const next = { left: Math.round(box.left), width: Math.round(box.width) };
104
+ return current && current.left === next.left && current.width === next.width ? current : next;
105
+ });
106
+ };
107
+ const schedule = () => {
108
+ if (!frame)
109
+ frame = requestAnimationFrame(measure);
110
+ };
111
+ measure();
112
+ window.addEventListener('scroll', schedule, { capture: true, passive: true });
113
+ window.addEventListener('resize', schedule);
114
+ const observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(schedule);
115
+ if (field.current)
116
+ observer?.observe(field.current);
117
+ return () => {
118
+ cancelAnimationFrame(frame);
119
+ window.removeEventListener('scroll', schedule, { capture: true });
120
+ window.removeEventListener('resize', schedule);
121
+ observer?.disconnect();
122
+ };
123
+ }, [field, enabled]);
124
+ return enabled ? pin : null;
125
+ }
71
126
  function useStore() {
72
127
  const store = useContext(EditInPlaceContext);
73
128
  if (!store)
@@ -117,29 +172,46 @@ export function EditableField({ label, edit, children, layout = 'block', look =
117
172
  // Set by a keyboard save or Esc: the caret goes back to the edit button.
118
173
  const refocus = useRef(false);
119
174
  const blurTimer = useRef(undefined);
120
- // An always-editable control starts over (it's uncontrolled: a rich-text
121
- // editor reads its value once) when the value changed elsewhere while
122
- // nothing of its own was unsaved and the caret wasn't in it.
175
+ // Where the caret goes once the control shows or starts over: the spot
176
+ // clicked in the read view (F8), or the caret's own block (F4).
177
+ const caretTarget = useRef(null);
178
+ const stopPlacing = useRef(() => { });
179
+ useEffect(() => () => stopPlacing.current(), []);
180
+ const placeCaretSoon = useCallback((spot) => {
181
+ stopPlacing.current();
182
+ stopPlacing.current = placeCaretWhenReady(() => container.current, spot);
183
+ }, []);
184
+ // The value changed elsewhere (another tab, a phone, an AI chat): the
185
+ // control starts over (it's uncontrolled: a rich-text editor reads its
186
+ // value once) when nothing of its own is unsaved, the caret keeping its
187
+ // block if it was in it; under unsaved typing the store marks a conflict.
123
188
  const refresh = useCallback(() => {
124
- if (!container.current?.contains(document.activeElement))
125
- store.refresh(key);
126
- }, [store, key]);
189
+ const focused = Boolean(container.current?.contains(document.activeElement));
190
+ const spot = focused && container.current ? caretSpot(container.current) : null;
191
+ if (store.refresh(key) && spot)
192
+ placeCaretSoon(spot);
193
+ }, [store, key, placeCaretSoon]);
127
194
  useEffect(() => {
128
- if (always)
129
- refresh();
130
- }, [always, refresh, edit.value]);
195
+ refresh();
196
+ }, [refresh, edit.value]);
131
197
  const isOpen = state.status !== 'closed';
198
+ const pinned = usePinnedStatus(container, autosave && (isOpen || always));
132
199
  const wasOpen = useRef(false);
133
200
  useEffect(() => {
134
201
  // Always open: the caret stays wherever the person put it.
135
202
  if (isOpen && !wasOpen.current && !always) {
203
+ const spot = caretTarget.current;
204
+ caretTarget.current = null;
136
205
  for (const selector of FOCUS_ORDER) {
137
206
  const target = container.current?.querySelector(selector);
138
207
  if (target) {
139
- target.focus();
208
+ // Opened by a click on the text: the page stays where it is.
209
+ target.focus(spot ? { preventScroll: true } : undefined);
140
210
  break;
141
211
  }
142
212
  }
213
+ if (spot)
214
+ placeCaretSoon(spot);
143
215
  }
144
216
  // Closed: the caret goes back to the value's edit button after a
145
217
  // keyboard save or Esc, or whenever closing left it nowhere (a pick
@@ -149,7 +221,30 @@ export function EditableField({ label, edit, children, layout = 'block', look =
149
221
  (editButton.current ?? triggerBox.current?.querySelector('button'))?.focus();
150
222
  }
151
223
  wasOpen.current = isOpen;
152
- }, [isOpen, always]);
224
+ }, [isOpen, always, placeCaretSoon]);
225
+ // Esc on a changed long text that doesn't autosave: asks first (F7).
226
+ const [askingDiscard, setAskingDiscard] = useState(false);
227
+ const asking = useRef(false);
228
+ useLayoutEffect(() => {
229
+ asking.current = askingDiscard;
230
+ });
231
+ // The first refusal or failed save of an autosaving field toasts too:
232
+ // its line may be far from where the person is looking (F5). Once per
233
+ // run of failures; a save that lands starts the count again.
234
+ const failure = state.status !== 'closed' ? state.error : null;
235
+ const toasted = useRef(false);
236
+ useEffect(() => {
237
+ if (!autosave)
238
+ return;
239
+ if (failure === null) {
240
+ toasted.current = false;
241
+ return;
242
+ }
243
+ if (toasted.current)
244
+ return;
245
+ toasted.current = true;
246
+ toast.error(`Couldn't save ${label}`, { description: failure });
247
+ }, [autosave, failure, label]);
153
248
  useEffect(() => () => window.clearTimeout(blurTimer.current), []);
154
249
  // Whether an Esc is closing a list inside the control. Read on the way
155
250
  // down (window, capture): a picker closes its list from a document
@@ -188,6 +283,9 @@ export function EditableField({ label, edit, children, layout = 'block', look =
188
283
  const onShownClick = (event) => {
189
284
  if (event.target.closest(INTERACTIVE))
190
285
  return;
286
+ // Long text opens with the caret where it was clicked (F8).
287
+ if (edit.kind === 'long-text')
288
+ caretTarget.current = spotAtPoint(event.currentTarget, event.clientX, event.clientY);
191
289
  start();
192
290
  };
193
291
  // Always editable: Ctrl/Cmd+Enter or Esc saves now, the caret staying put.
@@ -208,6 +306,13 @@ export function EditableField({ label, edit, children, layout = 'block', look =
208
306
  saveNow();
209
307
  else if (autosave)
210
308
  commitFromKeyboard();
309
+ else if (edit.kind === 'long-text' && !(edit.isEqual ?? sameAsJson)(state.draft, state.initial)) {
310
+ window.clearTimeout(blurTimer.current);
311
+ // This Esc opens the question; it mustn't also close it (or a
312
+ // record dialog around the field) on its way up to the document.
313
+ event.stopPropagation();
314
+ setAskingDiscard(true);
315
+ }
211
316
  else {
212
317
  refocus.current = true;
213
318
  cancel();
@@ -236,7 +341,7 @@ export function EditableField({ label, edit, children, layout = 'block', look =
236
341
  blurTimer.current = window.setTimeout(() => {
237
342
  if (store.state(key).status !== 'open')
238
343
  return;
239
- if (container.current?.querySelector(HOLD))
344
+ if (container.current?.querySelector(HOLD) || asking.current)
240
345
  return;
241
346
  void store.commit(key).then(() => {
242
347
  if (always)
@@ -270,9 +375,22 @@ export function EditableField({ label, edit, children, layout = 'block', look =
270
375
  // A refusal about one of the value's own fields shows on that field when
271
376
  // the control says it shows them; anything else shows under the control.
272
377
  const lineError = edit.errorsOnFields && fieldErrors ? null : open.error;
273
- return (_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, className: "type-body", children: autosave ? (_jsxs(_Fragment, { children: [lineError && _jsx(FieldError, { className: "type-caption", children: lineError }), _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' &&
274
- !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"] })) : (lineError && _jsx(FieldError, { className: "type-caption", children: lineError })) })] }));
378
+ // Something to say: a save in flight, saved, or why it can't save.
379
+ const hasStatus = autosaving || open.autosave === 'saved' || lineError !== null;
380
+ const pin = hasStatus ? pinned : null;
381
+ // The saved value changed elsewhere under unsaved typing: the person picks (F4).
382
+ 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,
384
+ // Pinned to the screen's bottom edge while the field runs past
385
+ // 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: () => {
388
+ setAskingDiscard(false);
389
+ refocus.current = true;
390
+ cancel();
391
+ } })] }));
275
392
  }
393
+ const sameAsJson = (a, b) => JSON.stringify(a) === JSON.stringify(b);
276
394
  /**
277
395
  * While a field holds something unsaved, leaving asks first: an in-app
278
396
  * link or Back (React Router's blocker, so the app needs a data router),
@@ -287,7 +405,13 @@ export function EditableField({ label, edit, children, layout = 'block', look =
287
405
  export function LeaveGuard({ store }) {
288
406
  const dirty = useSyncExternalStore(store.subscribe, () => store.dirty, () => store.dirty);
289
407
  const savesOnLeave = useSyncExternalStore(store.subscribe, () => store.savesOnLeave, () => store.savesOnLeave);
290
- const blocker = useBlocker(({ currentLocation, nextLocation }) => store.dirty && currentLocation.pathname !== nextLocation.pathname);
408
+ // Typing a rich-text field holds back (F6) counts: the tab's prompt is
409
+ // set up from the first key, and a move reports it before it's judged.
410
+ const holding = useSyncExternalStore(subscribePendingEdits, hasPendingEdits, hasPendingEdits);
411
+ const blocker = useBlocker(({ currentLocation, nextLocation }) => {
412
+ flushPendingEdits();
413
+ return store.dirty && currentLocation.pathname !== nextLocation.pathname;
414
+ });
291
415
  const [saveFailed, setSaveFailed] = useState(false);
292
416
  const latestBlocker = useRef(blocker);
293
417
  useLayoutEffect(() => {
@@ -315,23 +439,41 @@ export function LeaveGuard({ store }) {
315
439
  };
316
440
  }, [blocker.state, store]);
317
441
  useEffect(() => {
318
- if (!dirty)
442
+ if (!dirty && !holding)
319
443
  return;
320
- const onBeforeUnload = (event) => {
444
+ // Saves started as the page goes ask the browser to finish them
445
+ // (`keepalive`, lib/page-leaving.ts), F13.
446
+ const saveAsLeaving = () => {
447
+ markPageLeaving();
321
448
  void store.saveAll();
322
- event.preventDefault();
323
449
  };
450
+ const onBeforeUnload = (event) => {
451
+ saveAsLeaving();
452
+ // Held-back typing that turned out unchanged leaves nothing to ask about.
453
+ if (store.dirty)
454
+ event.preventDefault();
455
+ };
456
+ // Hidden (another tab, a phone's home screen, often the last thing a
457
+ // phone tells a page): save now, and while hidden don't wait for the
458
+ // pause. iOS gives no leave prompt, only these.
324
459
  const onVisibilityChange = () => {
325
- if (document.visibilityState === 'hidden')
326
- void store.saveAll();
460
+ const hidden = document.visibilityState === 'hidden';
461
+ store.hurry(hidden);
462
+ if (hidden)
463
+ saveAsLeaving();
464
+ else
465
+ clearPageLeaving();
327
466
  };
328
467
  window.addEventListener('beforeunload', onBeforeUnload);
468
+ window.addEventListener('pagehide', saveAsLeaving);
329
469
  document.addEventListener('visibilitychange', onVisibilityChange);
330
470
  return () => {
331
471
  window.removeEventListener('beforeunload', onBeforeUnload);
472
+ window.removeEventListener('pagehide', saveAsLeaving);
332
473
  document.removeEventListener('visibilitychange', onVisibilityChange);
474
+ store.hurry(false);
333
475
  };
334
- }, [dirty, store]);
476
+ }, [dirty, holding, store]);
335
477
  return (_jsx(DiscardChangesDialog, { open: blocker.state === 'blocked' && (!savesOnLeave || saveFailed), description: "A field you're editing hasn't been saved. Leaving now loses what you typed.", "data-leave-guard": "", onKeepEditing: () => {
336
478
  setSaveFailed(false);
337
479
  if (blocker.state === 'blocked')
@@ -29,6 +29,7 @@ import { DiscardChangesDialog } from '../ui/dialog.js';
29
29
  import { FieldGroup } from '../ui/field.js';
30
30
  import { Spinner } from '../ui/spinner.js';
31
31
  import { countFormErrors } from '../../lib/form-errors.js';
32
+ import { flushPendingEdits } from '../../lib/pending-edits.js';
32
33
  import { FormLeaveGuard } from './form-leave-guard.js';
33
34
  import { Notice } from './notice.js';
34
35
  const FOCUSABLE = 'input:not([type=hidden]), select, textarea, button, [contenteditable=true], [tabindex]:not([tabindex="-1"])';
@@ -98,6 +99,9 @@ export function EntityForm({ title, onSubmit, isSubmitting, submitError, onRetry
98
99
  // the render that draws react-hook-form's marks, and looks for them.
99
100
  const [attempt, setAttempt] = useState(0);
100
101
  const submit = (event) => {
102
+ // A rich-text field reports its typing a pause after it stops: asked
103
+ // for now, so the submit reads the last of it (F6).
104
+ flushPendingEdits();
101
105
  const done = onSubmit(event);
102
106
  void Promise.resolve(done).then(() => setAttempt((count) => count + 1));
103
107
  };