@open-document/core 0.6.0 → 0.7.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 (34) hide show
  1. package/dist/{build-BvIHtePO.js → build-CFL7nhz0.js} +1 -1
  2. package/dist/{check-BqEdVH7G.js → check-pEQh4jJE.js} +3 -3
  3. package/dist/cli/bin.js +6 -6
  4. package/dist/{config-B7vFf9qZ.js → config-4nz5NnxW.js} +593 -137
  5. package/dist/{context-BaUE_aqU.js → context-BH8C-dSW.js} +1 -1
  6. package/dist/{dev-DXG-Dg-y.js → dev-BCSUczXW.js} +1 -1
  7. package/dist/{export-CT1Axnjv.js → export-BQ-GvMsb.js} +3 -3
  8. package/dist/{import-C8ZC4R6T.js → import-Daat3L2J.js} +2 -2
  9. package/dist/index.d.ts +21 -3
  10. package/dist/index.js +40 -9
  11. package/dist/ops/index.d.ts +47 -3
  12. package/dist/ops/index.js +3 -3
  13. package/dist/{ops-ByclxTfk.js → ops-DQfckiyp.js} +2 -45
  14. package/dist/{preview-CdmWbaHy.js → preview-CwCrw-i3.js} +1 -1
  15. package/dist/vite/index.js +1 -1
  16. package/package.json +1 -1
  17. package/src/app/components/data-table.tsx +17 -2
  18. package/src/app/components/design-panel/design-panel.tsx +149 -274
  19. package/src/app/components/design-panel/design-provider.tsx +35 -15
  20. package/src/app/components/footnote.tsx +27 -10
  21. package/src/app/components/history-provider.tsx +125 -0
  22. package/src/app/components/inspector/inspector.tsx +1145 -208
  23. package/src/app/components/numbering.tsx +13 -1
  24. package/src/app/components/panel/edit-save-card.tsx +112 -0
  25. package/src/app/components/panel/fields.tsx +247 -0
  26. package/src/app/components/panel/panel-shell.tsx +71 -0
  27. package/src/app/components/panel/save-card.tsx +146 -0
  28. package/src/app/lib/footnotes.ts +6 -3
  29. package/src/app/lib/href.ts +14 -0
  30. package/src/app/lib/inspector/inline-edit.test.ts +244 -0
  31. package/src/app/lib/inspector/inline-edit.ts +770 -0
  32. package/src/app/lib/source-loc.ts +15 -0
  33. package/src/app/routes/doc.tsx +109 -39
  34. package/src/app/styles.css +41 -0
@@ -1,7 +1,18 @@
1
- import { Check, Loader2, MessageSquarePlus, X } from 'lucide-react';
1
+ import {
2
+ Bold,
3
+ Check,
4
+ Code,
5
+ Italic,
6
+ Link2,
7
+ Loader2,
8
+ MessageSquarePlus,
9
+ RemoveFormatting,
10
+ Unlink,
11
+ X,
12
+ } from 'lucide-react';
2
13
  import {
3
14
  type CSSProperties,
4
- Fragment,
15
+ type MutableRefObject,
5
16
  useCallback,
6
17
  useEffect,
7
18
  useLayoutEffect,
@@ -9,9 +20,45 @@ import {
9
20
  useState,
10
21
  } from 'react';
11
22
  import { createPortal } from 'react-dom';
23
+ import { isSafeHref } from '../../lib/href';
12
24
  import { candidateLocs, formatLocs } from '../../lib/inspector/fiber';
25
+ import {
26
+ cleanRun,
27
+ cleanSegments,
28
+ clearFormatting,
29
+ focusAt,
30
+ hasMark,
31
+ hrefOf,
32
+ isFormatted,
33
+ isRunChanged,
34
+ linkAt,
35
+ locate,
36
+ type Mark,
37
+ type MountedEditor,
38
+ mountEditor,
39
+ normalize,
40
+ placeCaret,
41
+ type Run,
42
+ readSegments,
43
+ replaceInRun,
44
+ restoreRuns,
45
+ runLength,
46
+ runText,
47
+ type Segment,
48
+ selectInRun,
49
+ setHref,
50
+ shownText,
51
+ snapshotRuns,
52
+ toggleMark,
53
+ writeSegments,
54
+ } from '../../lib/inspector/inline-edit';
55
+ import { PROP_ATTR } from '../../lib/source-loc';
56
+ import { useHistory } from '../history-provider';
57
+ import { PanelIconButton, PanelShell } from '../panel/panel-shell';
13
58
 
14
- type TextPart = { kind: 'text'; index: number; value: string } | { kind: 'markup'; label: string };
59
+ type TextPart =
60
+ | { kind: 'text'; index: number; value: string; formattable?: true; segments?: Segment[] }
61
+ | { kind: 'markup'; label: string };
15
62
 
16
63
  type ResolvedTarget = {
17
64
  line: number;
@@ -29,18 +76,71 @@ export type InspectorTarget = {
29
76
  column: number;
30
77
  anchor: HTMLElement;
31
78
  tag: string;
79
+ /** Set when the words are an attribute of a component's call site. */
80
+ prop?: string;
81
+ };
82
+
83
+ /**
84
+ * Text being edited on the page. `line:column` is where the server resolved the
85
+ * words to — not necessarily the clicked element's own tag, when the words are
86
+ * a prop written at a call site.
87
+ */
88
+ type Entry = {
89
+ /** Stable across a reload that moves the editor to a new element, so undo can find it. */
90
+ id: number;
91
+ anchor: HTMLElement;
92
+ editor: MountedEditor;
93
+ line: number;
94
+ column: number;
95
+ prop?: string;
96
+ shown: string;
97
+ pre: boolean;
98
+ undo: Segment[][][];
99
+ redo: Segment[][][];
100
+ lastInsert: number;
101
+ /** Where the caret was, so a transplanted editor can put it back. */
102
+ caret: { run: number; from: number; to: number } | null;
32
103
  };
33
104
 
105
+ type Outcome = { ok: true } | { ok: false; status: number; error: string };
106
+
107
+ /**
108
+ * Where in an element the reader clicked, as a fraction of its box. Selecting
109
+ * opens the side panel, which narrows the pane and re-zooms the page between
110
+ * the two clicks of a double-click — an absolute point would land on whatever
111
+ * slid under it.
112
+ */
113
+ type At = { rx: number; ry: number };
114
+
115
+ function atIn(el: HTMLElement, x: number, y: number): At {
116
+ const r = el.getBoundingClientRect();
117
+ return {
118
+ rx: r.width ? (x - r.left) / r.width : 0,
119
+ ry: r.height ? (y - r.top) / r.height : 0,
120
+ };
121
+ }
122
+
123
+ function pointIn(el: HTMLElement, at: At | null): { x: number; y: number } | null {
124
+ if (!at) return null;
125
+ const r = el.getBoundingClientRect();
126
+ return { x: r.left + at.rx * r.width, y: r.top + at.ry * r.height };
127
+ }
128
+
129
+ // Longer than any double-click interval a system allows by default.
130
+ const DOUBLE_CLICK_MS = 600;
131
+
34
132
  // Same visual language as open-slide's inspector: dashed on hover, solid on
35
- // selection, both in the same blue.
36
- const FRAME_STYLE: Record<'hover' | 'selected', CSSProperties> = {
133
+ // selection, both in the same blue. Unsaved text keeps a dashed frame after the
134
+ // cursor leaves it, so a change that exists only on screen never looks saved.
135
+ const FRAME_STYLE: Record<'hover' | 'selected' | 'pending', CSSProperties> = {
37
136
  hover: { outline: '1.5px dashed #3b82f6', background: 'rgba(59,130,246,0.05)' },
38
137
  selected: { outline: '2px solid #3b82f6', background: 'rgba(59,130,246,0.1)' },
138
+ pending: { outline: '1.5px dashed #3b82f6', outlineOffset: 2 },
39
139
  };
40
140
 
41
- function normalize(value: string): string {
42
- return value.replace(/\s+/g, ' ').trim();
43
- }
141
+ // Past this, a reload that should have replaced a saved element is not coming
142
+ // (the write changed nothing the page renders), and the clone must not linger.
143
+ const RELOAD_TIMEOUT_MS = 4000;
44
144
 
45
145
  function targetFrom(el: Element | null): InspectorTarget | null {
46
146
  // A contents row is generated from a heading and written nowhere; the words
@@ -54,7 +154,8 @@ function targetFrom(el: Element | null): InspectorTarget | null {
54
154
  if (!host || !raw) return null;
55
155
  const [line, column] = raw.split(':').map(Number);
56
156
  if (!Number.isFinite(line) || !Number.isFinite(column)) return null;
57
- return { line, column, anchor: host, tag: host.tagName.toLowerCase() };
157
+ const prop = host.getAttribute(PROP_ATTR) ?? undefined;
158
+ return { line, column, anchor: host, tag: host.tagName.toLowerCase(), ...(prop ? { prop } : {}) };
58
159
  }
59
160
 
60
161
  type Rect = { left: number; top: number; width: number; height: number };
@@ -76,7 +177,7 @@ function Frame({
76
177
  }: {
77
178
  anchor: HTMLElement | null;
78
179
  container: HTMLElement;
79
- variant: 'hover' | 'selected';
180
+ variant: 'hover' | 'selected' | 'pending';
80
181
  }) {
81
182
  const [rect, setRect] = useState<Rect | null>(null);
82
183
 
@@ -126,73 +227,1005 @@ function Frame({
126
227
  );
127
228
  }
128
229
 
230
+ const TOOLBAR_GAP = 6;
231
+
232
+ type LinkDraft = { run: Run; from: number; to: number; value: string; existing: boolean };
233
+
234
+ // Icons read at 75% of the foreground and fall to 30% when disabled: dimming a
235
+ // muted colour instead left disabled icons all but invisible on the dark theme.
236
+ const TOOL_CLASS =
237
+ 'flex size-8 items-center justify-center rounded text-foreground/75 transition-colors hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-foreground/60 disabled:text-foreground/30 disabled:hover:bg-transparent aria-pressed:bg-accent aria-pressed:text-foreground';
238
+
239
+ /**
240
+ * Inline formatting, floating over the text being edited: emphasis, code,
241
+ * links, and a way to take them off. Size, colour and alignment are not here
242
+ * on purpose — they belong to the document's design system, and a one-off
243
+ * inline style would quietly fork it.
244
+ */
245
+ function TextToolbar({
246
+ anchor,
247
+ container,
248
+ emphasis,
249
+ link,
250
+ onFormat,
251
+ onOpenLink,
252
+ onClear,
253
+ onLinkChange,
254
+ onLinkApply,
255
+ onLinkCancel,
256
+ toolbarRef,
257
+ }: {
258
+ anchor: HTMLElement;
259
+ container: HTMLElement;
260
+ emphasis: Emphasis;
261
+ link: LinkDraft | null;
262
+ onFormat: (mark: Mark) => void;
263
+ onOpenLink: () => void;
264
+ onClear: () => void;
265
+ onLinkChange: (value: string) => void;
266
+ onLinkApply: () => void;
267
+ onLinkCancel: () => void;
268
+ toolbarRef: React.RefObject<HTMLDivElement>;
269
+ }) {
270
+ const [position, setPosition] = useState<{ left: number; top: number } | null>(null);
271
+
272
+ // Same measuring contract as Frame: after every render, compared by value.
273
+ useLayoutEffect(() => {
274
+ const measure = () => {
275
+ const a = anchor.getBoundingClientRect();
276
+ const c = container.getBoundingClientRect();
277
+ const height = toolbarRef.current?.offsetHeight ?? 36;
278
+ const above = a.top - c.top - height - TOOLBAR_GAP;
279
+ const next = {
280
+ left: a.left - c.left + container.scrollLeft,
281
+ top: (above >= 0 ? above : a.bottom - c.top + TOOLBAR_GAP) + container.scrollTop,
282
+ };
283
+ setPosition((prev) =>
284
+ prev && prev.left === next.left && prev.top === next.top ? prev : next,
285
+ );
286
+ };
287
+ measure();
288
+ container.addEventListener('scroll', measure, { passive: true });
289
+ return () => container.removeEventListener('scroll', measure);
290
+ });
291
+
292
+ const title = (label: string, keys: string) =>
293
+ emphasis.canFormat ? `${label} (${keys})` : (emphasis.reason ?? label);
294
+ const invalid = link !== null && link.value.trim() !== '' && !isSafeHref(link.value.trim());
295
+
296
+ return (
297
+ <div
298
+ ref={toolbarRef}
299
+ role="toolbar"
300
+ aria-label="Text formatting"
301
+ className="pointer-events-auto absolute z-40 flex items-center gap-0.5 rounded-md border border-border bg-background p-0.5 shadow-md"
302
+ style={position ?? { visibility: 'hidden' }}
303
+ // Keep focus, and the selection, in the text being edited — except for
304
+ // the link field, which has to take focus to be typed into.
305
+ onPointerDown={(e) => {
306
+ if (!(e.target instanceof HTMLInputElement)) e.preventDefault();
307
+ }}
308
+ >
309
+ {link ? (
310
+ <>
311
+ <input
312
+ // biome-ignore lint/a11y/noAutofocus: the field opens on an explicit request and is the only thing to do next
313
+ autoFocus
314
+ type="url"
315
+ aria-label="Link address"
316
+ aria-invalid={invalid}
317
+ placeholder="https://… or #section"
318
+ value={link.value}
319
+ onChange={(e) => onLinkChange(e.target.value)}
320
+ onKeyDown={(e) => {
321
+ if (e.key === 'Enter') {
322
+ e.preventDefault();
323
+ if (!invalid) onLinkApply();
324
+ } else if (e.key === 'Escape') {
325
+ e.preventDefault();
326
+ onLinkCancel();
327
+ }
328
+ }}
329
+ title={invalid ? 'Only web, mail, phone, or in-document addresses' : undefined}
330
+ className="h-8 w-64 rounded border border-border bg-transparent px-2 text-xs outline-none focus:border-foreground/40 aria-invalid:border-destructive"
331
+ />
332
+ <button
333
+ type="button"
334
+ aria-label="Apply link"
335
+ title="Apply (Enter)"
336
+ disabled={invalid}
337
+ onClick={onLinkApply}
338
+ className={TOOL_CLASS}
339
+ >
340
+ <Check className="size-3.5" />
341
+ </button>
342
+ {link.existing && (
343
+ <button
344
+ type="button"
345
+ aria-label="Remove link"
346
+ title="Remove link"
347
+ onClick={() => {
348
+ onLinkChange('');
349
+ onLinkApply();
350
+ }}
351
+ className={TOOL_CLASS}
352
+ >
353
+ <Unlink className="size-3.5" />
354
+ </button>
355
+ )}
356
+ </>
357
+ ) : (
358
+ <>
359
+ {(
360
+ [
361
+ ['bold', 'Bold', '⌘B', Bold],
362
+ ['italic', 'Italic', '⌘I', Italic],
363
+ ['code', 'Code', '⌘E', Code],
364
+ ] as const
365
+ ).map(([mark, label, keys, Icon]) => {
366
+ const styled = mark === 'bold' && emphasis.boldFromStyle;
367
+ return (
368
+ <button
369
+ key={mark}
370
+ type="button"
371
+ aria-label={label}
372
+ aria-pressed={emphasis[mark]}
373
+ title={
374
+ styled ? 'Already bold — this element’s own style sets it' : title(label, keys)
375
+ }
376
+ disabled={!emphasis.canFormat || styled}
377
+ onClick={() => onFormat(mark)}
378
+ className={TOOL_CLASS}
379
+ >
380
+ <Icon className="size-3.5" />
381
+ </button>
382
+ );
383
+ })}
384
+ <span aria-hidden className="mx-0.5 h-4 w-px bg-border" />
385
+ <button
386
+ type="button"
387
+ aria-label="Link"
388
+ aria-pressed={emphasis.href !== null}
389
+ title={emphasis.linkable ? 'Link (⌘K)' : (emphasis.reason ?? 'Link')}
390
+ disabled={!emphasis.linkable}
391
+ onClick={onOpenLink}
392
+ className={TOOL_CLASS}
393
+ >
394
+ <Link2 className="size-3.5" />
395
+ </button>
396
+ <button
397
+ type="button"
398
+ aria-label="Clear formatting"
399
+ title={title('Clear formatting', '⌘\\')}
400
+ disabled={!emphasis.canFormat}
401
+ onClick={onClear}
402
+ className={TOOL_CLASS}
403
+ >
404
+ <RemoveFormatting className="size-3.5" />
405
+ </button>
406
+ </>
407
+ )}
408
+ </div>
409
+ );
410
+ }
411
+
412
+ function dirtyRuns(entry: Entry): number {
413
+ return entry.editor.runs.filter(isRunChanged).length;
414
+ }
415
+
416
+ /** The DOM range an input will act on, when the browser does not say. */
417
+ function fallbackRange(inputType: string): StaticRange | null {
418
+ const selection = window.getSelection();
419
+ if (!selection || selection.rangeCount === 0) return null;
420
+ const modifiable = selection as Selection & {
421
+ modify?: (alter: string, direction: string, granularity: string) => void;
422
+ };
423
+ if (selection.isCollapsed && inputType.startsWith('delete') && modifiable.modify) {
424
+ const backward = inputType.includes('Backward');
425
+ const word = inputType.includes('Word');
426
+ modifiable.modify('extend', backward ? 'backward' : 'forward', word ? 'word' : 'character');
427
+ }
428
+ const range = selection.getRangeAt(0);
429
+ return new StaticRange({
430
+ startContainer: range.startContainer,
431
+ startOffset: range.startOffset,
432
+ endContainer: range.endContainer,
433
+ endOffset: range.endOffset,
434
+ });
435
+ }
436
+
437
+ function selectionIn(entry: Entry): { run: Run; from: number; to: number } | null {
438
+ const selection = window.getSelection();
439
+ if (!selection || selection.rangeCount === 0) return null;
440
+ const at = locate(entry.editor.clone, selection.getRangeAt(0));
441
+ const run = at && entry.editor.runs.find((candidate) => candidate.el === at.run);
442
+ return at && run ? { run, from: at.from, to: at.to } : null;
443
+ }
444
+
445
+ type Emphasis = {
446
+ /** Words are selected, or the caret sits in a link — something the toolbar can act on. */
447
+ actionable: boolean;
448
+ canFormat: boolean;
449
+ /** A link can be edited from a bare caret inside it, not only from a selection. */
450
+ linkable: boolean;
451
+ reason?: string;
452
+ bold: boolean;
453
+ italic: boolean;
454
+ code: boolean;
455
+ /** Bold because the element is styled bold, not because the words are marked. */
456
+ boldFromStyle: boolean;
457
+ href: string | null;
458
+ };
459
+
460
+ const PLAIN: Omit<Emphasis, 'actionable' | 'canFormat' | 'linkable' | 'reason'> = {
461
+ bold: false,
462
+ italic: false,
463
+ code: false,
464
+ boldFromStyle: false,
465
+ href: null,
466
+ };
467
+
468
+ function emphasisAt(entry: Entry): Emphasis {
469
+ const at = selectionIn(entry);
470
+ if (!at) {
471
+ return {
472
+ ...PLAIN,
473
+ actionable: false,
474
+ canFormat: false,
475
+ linkable: false,
476
+ reason: 'Select words to format',
477
+ };
478
+ }
479
+ if (!at.run.formattable) {
480
+ return {
481
+ ...PLAIN,
482
+ actionable: at.from !== at.to,
483
+ canFormat: false,
484
+ linkable: false,
485
+ reason: 'This text is passed in as a string — formatting needs text written in the document',
486
+ };
487
+ }
488
+ const segments = readSegments(at.run.el);
489
+ if (at.from === at.to) {
490
+ const link = linkAt(segments, at.from);
491
+ return {
492
+ ...PLAIN,
493
+ actionable: link !== null,
494
+ canFormat: false,
495
+ linkable: link !== null,
496
+ reason: 'Select words to format',
497
+ href: link?.href ?? null,
498
+ };
499
+ }
500
+ const bold = hasMark(segments, at.from, at.to, 'bold');
501
+ return {
502
+ actionable: true,
503
+ canFormat: true,
504
+ linkable: true,
505
+ bold,
506
+ italic: hasMark(segments, at.from, at.to, 'italic'),
507
+ code: hasMark(segments, at.from, at.to, 'code'),
508
+ boldFromStyle: !bold && Number.parseInt(getComputedStyle(at.run.el).fontWeight, 10) >= 600,
509
+ href: hrefOf(segments, at.from, at.to),
510
+ };
511
+ }
512
+
513
+ /** What the document view's save card drives: page edits are saved and discarded from there. */
514
+ export type SaveOutcome = { ok: boolean; error?: string };
515
+
516
+ export type InspectorControls = {
517
+ save: () => Promise<SaveOutcome>;
518
+ discard: () => void;
519
+ };
520
+
129
521
  type Props = {
130
522
  docId: string;
131
523
  /** The scroll container the pages live in. */
132
524
  containerRef: React.RefObject<HTMLDivElement | null>;
525
+ /** The design panel shares the right dock and wins it while open. */
526
+ panelHidden: boolean;
527
+ /** The save card is showing, so the hint underneath it steps aside. */
528
+ quiet: boolean;
133
529
  onExit: () => void;
530
+ /** Set to a function that saves any unsaved text, then leaves edit mode. */
531
+ exitRef: MutableRefObject<(() => void) | null>;
532
+ controlsRef: MutableRefObject<InspectorControls | null>;
533
+ onPendingChange: (count: number) => void;
134
534
  };
135
535
 
136
- export function Inspector({ docId, containerRef, onExit }: Props) {
536
+ export function Inspector({
537
+ docId,
538
+ containerRef,
539
+ panelHidden,
540
+ quiet,
541
+ onExit,
542
+ exitRef,
543
+ controlsRef,
544
+ onPendingChange,
545
+ }: Props) {
546
+ const history = useHistory();
547
+ const nextIdRef = useRef(1);
137
548
  const [container, setContainer] = useState<HTMLElement | null>(null);
138
- const [hover, setHover] = useState<InspectorTarget | null>(null);
549
+ const [hover, setHover] = useState<HTMLElement | null>(null);
139
550
  const [selected, setSelected] = useState<InspectorTarget | null>(null);
140
- const [target, setTarget] = useState<ResolvedTarget | null>(null);
141
- const [drafts, setDrafts] = useState<Record<number, string>>({});
551
+ const [resolution, setResolution] = useState<{
552
+ anchor: HTMLElement;
553
+ value: ResolvedTarget;
554
+ } | null>(null);
555
+ // Derived against the selection, never stored alone: a click that selects
556
+ // and a double-click that asks to edit can land in one render, before the
557
+ // new lookup has even started, and the previous element's runs would be
558
+ // laid over this one's text.
559
+ const target = resolution && resolution.anchor === selected?.anchor ? resolution.value : null;
560
+ const [active, setActive] = useState<Entry | null>(null);
561
+ const activeRef = useRef<Entry | null>(null);
562
+ activeRef.current = active;
563
+ const [wantEdit, setWantEdit] = useState<{
564
+ anchor: HTMLElement;
565
+ at: At | null;
566
+ selectWord: boolean;
567
+ } | null>(null);
568
+ const [pending, setPending] = useState<Entry[]>([]);
142
569
  const [note, setNote] = useState('');
143
570
  const [busy, setBusy] = useState(false);
144
571
  const [status, setStatus] = useState<string | null>(null);
145
572
  const panelRef = useRef<HTMLElement>(null);
146
- const editorRef = useRef<HTMLDivElement>(null);
573
+ const toolbarRef = useRef<HTMLDivElement>(null);
574
+ const entriesRef = useRef(new Map<HTMLElement, Entry>());
575
+ const sessionStartRef = useRef<Segment[][]>([]);
576
+ const firstClickRef = useRef<{ anchor: HTMLElement; at: At; time: number } | null>(null);
147
577
 
148
578
  useLayoutEffect(() => setContainer(containerRef.current), [containerRef]);
149
579
 
150
- const insidePanel = useCallback(
151
- (node: EventTarget | null) => panelRef.current?.contains(node as Node) ?? false,
580
+ const insideChrome = useCallback(
581
+ (node: EventTarget | null) =>
582
+ (panelRef.current?.contains(node as Node) ?? false) ||
583
+ (toolbarRef.current?.contains(node as Node) ?? false),
584
+ [],
585
+ );
586
+
587
+ const entryAt = useCallback((node: EventTarget | null): Entry | null => {
588
+ for (const entry of entriesRef.current.values()) {
589
+ if (entry.editor.clone.contains(node as Node)) return entry;
590
+ }
591
+ return null;
592
+ }, []);
593
+
594
+ const refresh = useCallback(() => {
595
+ setPending([...entriesRef.current.values()].filter((entry) => dirtyRuns(entry) > 0));
596
+ }, []);
597
+
598
+ const drop = useCallback((entry: Entry) => {
599
+ entry.editor.restore();
600
+ entriesRef.current.delete(entry.anchor);
601
+ }, []);
602
+
603
+ const begin = useCallback(
604
+ (anchor: HTMLElement, at: At | null, selectWord: boolean, resolved?: ResolvedTarget) => {
605
+ let entry = entriesRef.current.get(anchor);
606
+ if (!entry) {
607
+ if (!resolved) return;
608
+ const runs = resolved.parts.filter(
609
+ (part): part is Extract<TextPart, { kind: 'text' }> => part.kind === 'text',
610
+ );
611
+ const shown = shownText(anchor);
612
+ const editor = mountEditor(anchor, runs);
613
+ if (!editor) {
614
+ setStatus(
615
+ 'The text on the page does not line up with its source, so it cannot be edited here.',
616
+ );
617
+ return;
618
+ }
619
+ entry = {
620
+ id: nextIdRef.current++,
621
+ anchor,
622
+ editor,
623
+ line: resolved.line,
624
+ ...(anchor.hasAttribute(PROP_ATTR)
625
+ ? { prop: anchor.getAttribute(PROP_ATTR) as string }
626
+ : {}),
627
+ column: resolved.column,
628
+ shown,
629
+ pre: getComputedStyle(anchor).whiteSpace.startsWith('pre'),
630
+ undo: [],
631
+ redo: [],
632
+ lastInsert: 0,
633
+ caret: null,
634
+ };
635
+ entriesRef.current.set(anchor, entry);
636
+ }
637
+ sessionStartRef.current = snapshotRuns(entry.editor.runs);
638
+ setStatus(null);
639
+ setActive(entry);
640
+ focusAt(entry.editor.clone, pointIn(entry.editor.clone, at), selectWord);
641
+ },
152
642
  [],
153
643
  );
154
644
 
645
+ /** Puts an editor's runs back to a snapshot, wherever a reload has since moved it. */
646
+ const applySnapshot = useCallback(
647
+ (id: number, snapshot: Segment[][]) => {
648
+ for (const entry of entriesRef.current.values()) {
649
+ if (entry.id !== id) continue;
650
+ restoreRuns(entry.editor.runs, snapshot);
651
+ refresh();
652
+ return;
653
+ }
654
+ },
655
+ [refresh],
656
+ );
657
+
658
+ /**
659
+ * Ends the typing session. The change stays on the page, unsaved, unless
660
+ * reverted — and becomes one step in the view's history, beside design
661
+ * changes. Inside the field, ⌘Z still steps through the typing itself.
662
+ */
663
+ const finish = useCallback(
664
+ (entry: Entry, revert: boolean) => {
665
+ const start = sessionStartRef.current;
666
+ if (revert) restoreRuns(entry.editor.runs, start);
667
+ const end = snapshotRuns(entry.editor.runs);
668
+ const changed = !revert && JSON.stringify(end) !== JSON.stringify(start);
669
+ if (changed) {
670
+ const { id } = entry;
671
+ history.record({
672
+ undo: () => applySnapshot(id, start),
673
+ redo: () => applySnapshot(id, end),
674
+ });
675
+ }
676
+ // An editor a history step points at stays, even when it now reads as
677
+ // the source does: undo and redo need it to put the words back.
678
+ if (dirtyRuns(entry) === 0 && !changed) drop(entry);
679
+ else entry.editor.clone.blur();
680
+ setActive((current) => (current === entry ? null : current));
681
+ refresh();
682
+ },
683
+ [drop, refresh, history, applySnapshot],
684
+ );
685
+
686
+ const discard = useCallback(() => {
687
+ for (const entry of [...entriesRef.current.values()]) drop(entry);
688
+ setActive(null);
689
+ refresh();
690
+ setStatus('Discarded unsaved edits');
691
+ }, [drop, refresh]);
692
+
693
+ /**
694
+ * Leaves the clone in place until hot reload has replaced what it covers —
695
+ * removing it at once would flash the old words for the length of a reload.
696
+ */
697
+ const settle = useCallback(
698
+ (entry: Entry) => {
699
+ entriesRef.current.delete(entry.anchor);
700
+ const root = container ?? document.body;
701
+ const before = entry.anchor.textContent;
702
+ let timer = 0;
703
+ const done = () => {
704
+ observer.disconnect();
705
+ window.clearTimeout(timer);
706
+ entry.editor.restore();
707
+ };
708
+ const observer = new MutationObserver(() => {
709
+ if (!entry.anchor.isConnected || entry.anchor.textContent !== before) done();
710
+ });
711
+ observer.observe(root, { childList: true, subtree: true, characterData: true });
712
+ timer = window.setTimeout(done, RELOAD_TIMEOUT_MS);
713
+ },
714
+ [container],
715
+ );
716
+
717
+ /**
718
+ * Bold or italic on the selected words. Only text written between tags can
719
+ * carry it — a prop or an array entry is a string in source, and a string
720
+ * has nowhere to put a `<strong>`.
721
+ */
722
+ const reformat = useCallback(
723
+ (run: Run, from: number, to: number, change: (segments: Segment[]) => Segment[]) => {
724
+ if (!active) return;
725
+ active.undo.push(snapshotRuns(active.editor.runs));
726
+ active.redo = [];
727
+ active.lastInsert = 0;
728
+ writeSegments(run.el, change(readSegments(run.el)));
729
+ active.editor.clone.focus({ preventScroll: true });
730
+ selectInRun(run.el, from, to);
731
+ refresh();
732
+ },
733
+ [active, refresh],
734
+ );
735
+
736
+ const format = useCallback(
737
+ (mark: Mark) => {
738
+ if (!active) return;
739
+ const at = selectionIn(active);
740
+ if (!at || at.from === at.to || !at.run.formattable) return;
741
+ if (mark === 'bold' && emphasisAt(active).boldFromStyle) return;
742
+ reformat(at.run, at.from, at.to, (segments) => toggleMark(segments, at.from, at.to, mark));
743
+ },
744
+ [active, reformat],
745
+ );
746
+
747
+ const clear = useCallback(() => {
748
+ if (!active) return;
749
+ const at = selectionIn(active);
750
+ if (!at || at.from === at.to || !at.run.formattable) return;
751
+ reformat(at.run, at.from, at.to, (segments) => clearFormatting(segments, at.from, at.to));
752
+ }, [active, reformat]);
753
+
754
+ const [linkDraft, setLinkDraft] = useState<LinkDraft | null>(null);
755
+ useEffect(() => {
756
+ void active;
757
+ setLinkDraft(null);
758
+ }, [active]);
759
+
760
+ /** Opens the link field over the selection, or over the whole link the caret is in. */
761
+ const openLink = useCallback(() => {
762
+ if (!active) return;
763
+ const at = selectionIn(active);
764
+ if (!at?.run.formattable) return;
765
+ const segments = readSegments(at.run.el);
766
+ let { from, to } = at;
767
+ if (from === to) {
768
+ const link = linkAt(segments, from);
769
+ if (!link) return;
770
+ ({ from, to } = link);
771
+ }
772
+ const href = hrefOf(segments, from, to);
773
+ setLinkDraft({ run: at.run, from, to, value: href ?? '', existing: href !== null });
774
+ }, [active]);
775
+
776
+ const applyLink = useCallback(() => {
777
+ if (!linkDraft) return;
778
+ const href = linkDraft.value.trim();
779
+ if (href !== '' && !isSafeHref(href)) return;
780
+ const { run, from, to } = linkDraft;
781
+ setLinkDraft(null);
782
+ reformat(run, from, to, (segments) => setHref(segments, from, to, href || null));
783
+ }, [linkDraft, reformat]);
784
+
785
+ const cancelLink = useCallback(() => {
786
+ if (!active || !linkDraft) return;
787
+ const { run, from, to } = linkDraft;
788
+ setLinkDraft(null);
789
+ active.editor.clone.focus({ preventScroll: true });
790
+ selectInRun(run.el, from, to);
791
+ }, [active, linkDraft]);
792
+
793
+ const [emphasis, setEmphasis] = useState<Emphasis | null>(null);
794
+ useEffect(() => {
795
+ if (!active) {
796
+ setEmphasis(null);
797
+ return;
798
+ }
799
+ const update = () => {
800
+ const at = selectionIn(active);
801
+ if (at) active.caret = { run: active.editor.runs.indexOf(at.run), from: at.from, to: at.to };
802
+ setEmphasis(emphasisAt(active));
803
+ };
804
+ update();
805
+ document.addEventListener('selectionchange', update);
806
+ return () => document.removeEventListener('selectionchange', update);
807
+ }, [active]);
808
+
809
+ const save = useCallback(async (): Promise<SaveOutcome> => {
810
+ if (active) finish(active, false);
811
+ // Editors undo brought back to the source's words have nothing to write.
812
+ for (const entry of [...entriesRef.current.values()]) {
813
+ if (dirtyRuns(entry) === 0) drop(entry);
814
+ }
815
+ const entries = [...entriesRef.current.values()];
816
+ const edits: Array<Record<string, unknown>> = [];
817
+ const owners: Entry[] = [];
818
+ for (const entry of entries) {
819
+ for (const run of entry.editor.runs) {
820
+ if (!isRunChanged(run)) continue;
821
+ const segments = cleanSegments(readSegments(run.el), run.expected);
822
+ edits.push({
823
+ line: entry.line,
824
+ column: entry.column,
825
+ index: run.index,
826
+ expected: run.expected,
827
+ shown: entry.shown,
828
+ ...(entry.prop ? { prop: entry.prop } : {}),
829
+ text: cleanRun(runText(run.el), run.expected),
830
+ ...(run.formattable ? { segments } : {}),
831
+ });
832
+ owners.push(entry);
833
+ }
834
+ }
835
+ if (edits.length === 0) return { ok: true };
836
+
837
+ setBusy(true);
838
+ try {
839
+ const res = await fetch('/__edit/texts', {
840
+ method: 'PUT',
841
+ headers: { 'content-type': 'application/json' },
842
+ body: JSON.stringify({ docId, edits }),
843
+ });
844
+ const body = (await res.json()) as { results?: Outcome[]; error?: string };
845
+ if (!res.ok || !body.results) {
846
+ const error = body.error ?? 'Save failed';
847
+ setStatus(error);
848
+ return { ok: false, error };
849
+ }
850
+ const results = body.results;
851
+ const failures = results.filter(
852
+ (result): result is Extract<Outcome, { ok: false }> => !result.ok,
853
+ );
854
+ for (const entry of new Set(owners)) {
855
+ const wrote = results.some((result, at) => result.ok && owners[at] === entry);
856
+ if (wrote) settle(entry);
857
+ else drop(entry);
858
+ }
859
+ refresh();
860
+ setSelected(null);
861
+ if (failures.length === 0) {
862
+ setStatus('Saved to source');
863
+ return { ok: true };
864
+ }
865
+ const error = `${failures.length} of ${edits.length} not saved — ${failures[0]?.error ?? 'refused'}`;
866
+ setStatus(error);
867
+ return { ok: false, error };
868
+ } catch {
869
+ setStatus('Save failed');
870
+ return { ok: false, error: 'Save failed' };
871
+ } finally {
872
+ setBusy(false);
873
+ }
874
+ }, [active, docId, drop, finish, refresh, settle]);
875
+
876
+ const leave = useCallback(async () => {
877
+ if ((await save()).ok) onExit();
878
+ }, [save, onExit]);
879
+
880
+ useEffect(() => {
881
+ exitRef.current = () => void leave();
882
+ controlsRef.current = { save, discard };
883
+ return () => {
884
+ exitRef.current = null;
885
+ controlsRef.current = null;
886
+ };
887
+ }, [exitRef, leave, controlsRef, save, discard]);
888
+
889
+ useEffect(() => {
890
+ onPendingChange(pending.length);
891
+ }, [pending.length, onPendingChange]);
892
+ useEffect(() => () => onPendingChange(0), [onPendingChange]);
893
+
894
+ // Leaving edit mode any other way — a route change, closing the tab — drops
895
+ // unsaved text rather than leaving a clone on the page with nothing to own it.
896
+ useEffect(() => {
897
+ const entries = entriesRef.current;
898
+ return () => {
899
+ for (const entry of entries.values()) entry.editor.restore();
900
+ entries.clear();
901
+ };
902
+ }, []);
903
+
904
+ useEffect(() => {
905
+ if (pending.length === 0) return;
906
+ const onBeforeUnload = (e: BeforeUnloadEvent) => e.preventDefault();
907
+ window.addEventListener('beforeunload', onBeforeUnload);
908
+ return () => window.removeEventListener('beforeunload', onBeforeUnload);
909
+ }, [pending.length]);
910
+
911
+ // An external write — an agent, the design panel, another save — reloads the
912
+ // document and replaces elements, clones and all. When the element at the
913
+ // same source location still reads what it did when editing began, the
914
+ // reload did not touch these words: the editor moves onto it with its unsaved
915
+ // text, its undo history and its caret. Only when the words themselves
916
+ // changed is the edit given up, and said so.
917
+ useEffect(() => {
918
+ if (!container) return;
919
+ const observer = new MutationObserver(() => {
920
+ const successor = (anchor: HTMLElement): HTMLElement | null => {
921
+ if (anchor.isConnected) return anchor;
922
+ const loc = anchor.getAttribute(LOC_ATTR);
923
+ if (!loc) return null;
924
+ // A component's root and the caption it prints share one call site;
925
+ // the prop is what tells them apart.
926
+ const prop = anchor.getAttribute(PROP_ATTR);
927
+ const which = prop ? `[${PROP_ATTR}="${CSS.escape(prop)}"]` : `:not([${PROP_ATTR}])`;
928
+ return container.querySelector<HTMLElement>(`[${LOC_ATTR}="${CSS.escape(loc)}"]${which}`);
929
+ };
930
+
931
+ let lost = 0;
932
+ let replaced = false;
933
+ for (const entry of [...entriesRef.current.values()]) {
934
+ if (entry.anchor.isConnected) continue;
935
+ replaced = true;
936
+ const wasActive = activeRef.current === entry;
937
+ const changed = dirtyRuns(entry) > 0;
938
+ const snapshot = snapshotRuns(entry.editor.runs);
939
+ entriesRef.current.delete(entry.anchor);
940
+ entry.editor.restore();
941
+
942
+ const next = successor(entry.anchor);
943
+ const editor =
944
+ next && shownText(next) === entry.shown
945
+ ? mountEditor(
946
+ next,
947
+ entry.editor.runs.map((run) => ({
948
+ index: run.index,
949
+ value: run.expected,
950
+ formattable: run.formattable,
951
+ ...(isFormatted(run.expectedSegments) ? { segments: run.expectedSegments } : {}),
952
+ })),
953
+ )
954
+ : null;
955
+ if (!next || !editor) {
956
+ if (changed) lost++;
957
+ if (wasActive) setActive(null);
958
+ continue;
959
+ }
960
+ restoreRuns(editor.runs, snapshot);
961
+ const moved: Entry = { ...entry, anchor: next, editor };
962
+ entriesRef.current.set(next, moved);
963
+ if (wasActive) {
964
+ setActive(moved);
965
+ moved.editor.clone.focus({ preventScroll: true });
966
+ const caret = entry.caret;
967
+ const run = caret ? moved.editor.runs[caret.run] : undefined;
968
+ if (caret && run) selectInRun(run.el, caret.from, caret.to);
969
+ }
970
+ }
971
+ if (replaced) refresh();
972
+ if (lost > 0) {
973
+ setStatus(
974
+ `The document reloaded with new text here — ${lost} unsaved edit${lost > 1 ? 's were' : ' was'} lost`,
975
+ );
976
+ }
977
+
978
+ // A selection carries over the same way — otherwise a reload between
979
+ // the two clicks of a double-click leaves the edit waiting on a node
980
+ // that is gone.
981
+ setSelected((prev) => {
982
+ if (!prev || prev.anchor.isConnected) return prev;
983
+ const anchor = successor(prev.anchor);
984
+ return anchor ? { ...prev, anchor } : null;
985
+ });
986
+ setWantEdit((prev) => {
987
+ if (!prev || prev.anchor.isConnected) return prev;
988
+ const anchor = successor(prev.anchor);
989
+ return anchor ? { ...prev, anchor } : null;
990
+ });
991
+ const first = firstClickRef.current;
992
+ if (first && !first.anchor.isConnected) {
993
+ const anchor = successor(first.anchor);
994
+ firstClickRef.current = anchor ? { ...first, anchor } : null;
995
+ }
996
+ });
997
+ observer.observe(container, { childList: true, subtree: true });
998
+ return () => observer.disconnect();
999
+ }, [container, refresh]);
1000
+
155
1001
  useEffect(() => {
156
1002
  if (!container) return;
157
1003
 
158
1004
  const onMove = (e: PointerEvent) => {
159
- if (insidePanel(e.target)) return;
160
- setHover(targetFrom(e.target as Element));
1005
+ if (insideChrome(e.target)) return;
1006
+ const entry = entryAt(e.target);
1007
+ setHover(entry ? entry.editor.clone : (targetFrom(e.target as Element)?.anchor ?? null));
161
1008
  };
162
1009
  const onClick = (e: MouseEvent) => {
163
- if (insidePanel(e.target)) return;
1010
+ if (insideChrome(e.target)) return;
1011
+ // Text already open on the page is a field: a click places the caret.
1012
+ const entry = entryAt(e.target);
1013
+ if (entry) {
1014
+ const owner = targetFrom(entry.anchor);
1015
+ if (owner) setSelected((prev) => (prev?.anchor === owner.anchor ? prev : owner));
1016
+ if (active !== entry) {
1017
+ begin(entry.anchor, atIn(entry.editor.clone, e.clientX, e.clientY), false);
1018
+ }
1019
+ return;
1020
+ }
1021
+ const first = firstClickRef.current;
1022
+ if (e.detail > 1 && first && Date.now() - first.time < DOUBLE_CLICK_MS) {
1023
+ // The second click of a double-click: the page may have moved under
1024
+ // the pointer since the first, so it must not change the selection.
1025
+ e.preventDefault();
1026
+ e.stopPropagation();
1027
+ return;
1028
+ }
164
1029
  const target = targetFrom(e.target as Element);
165
1030
  if (!target) return;
166
1031
  e.preventDefault();
167
1032
  e.stopPropagation();
1033
+ firstClickRef.current = target.anchor.contains(e.target as Node)
1034
+ ? { anchor: target.anchor, at: atIn(target.anchor, e.clientX, e.clientY), time: Date.now() }
1035
+ : null;
168
1036
  // A contents row sends the selection to a heading pages away. Without
169
1037
  // this the panel fills in and the document sits where it was, which
170
1038
  // reads as nothing having happened.
171
1039
  if (!target.anchor.contains(e.target as Node)) {
172
1040
  target.anchor.scrollIntoView({ block: 'center', behavior: 'smooth' });
173
1041
  }
174
- setSelected(target);
1042
+ setSelected((prev) => (prev?.anchor === target.anchor ? prev : target));
175
1043
  setStatus(null);
176
1044
  setNote('');
177
1045
  };
1046
+ const onDblClick = (e: MouseEvent) => {
1047
+ if (insideChrome(e.target)) return;
1048
+ const first = firstClickRef.current;
1049
+ firstClickRef.current = null;
1050
+ if (first && Date.now() - first.time < DOUBLE_CLICK_MS) {
1051
+ e.preventDefault();
1052
+ setWantEdit({ anchor: first.anchor, at: first.at, selectWord: true });
1053
+ return;
1054
+ }
1055
+ if (entryAt(e.target)) return;
1056
+ const target = targetFrom(e.target as Element);
1057
+ if (!target?.anchor.contains(e.target as Node)) return;
1058
+ e.preventDefault();
1059
+ setSelected((prev) => (prev?.anchor === target.anchor ? prev : target));
1060
+ setWantEdit({
1061
+ anchor: target.anchor,
1062
+ at: atIn(target.anchor, e.clientX, e.clientY),
1063
+ selectWord: true,
1064
+ });
1065
+ };
1066
+ const onPointerDown = (e: PointerEvent) => {
1067
+ if (!active || active.editor.clone.contains(e.target as Node)) return;
1068
+ if (toolbarRef.current?.contains(e.target as Node)) return;
1069
+ finish(active, false);
1070
+ };
178
1071
  const onKey = (e: KeyboardEvent) => {
179
- if (e.key !== 'Escape') return;
180
- if (selected) {
181
- setSelected(null);
1072
+ if (e.isComposing || e.keyCode === 229) return;
1073
+ // The link field handles its own Enter and Escape.
1074
+ if (toolbarRef.current?.contains(e.target as Node)) return;
1075
+ if (e.key === 'Escape') {
1076
+ if (active) {
1077
+ e.preventDefault();
1078
+ e.stopPropagation();
1079
+ finish(active, true);
1080
+ return;
1081
+ }
1082
+ if (selected) {
1083
+ setSelected(null);
1084
+ return;
1085
+ }
1086
+ void leave();
182
1087
  return;
183
1088
  }
184
- onExit();
1089
+ if (e.key === 'Enter' && !active && selected && !e.metaKey && !e.ctrlKey && !e.altKey) {
1090
+ const typing = (e.target as HTMLElement | null)?.closest?.(
1091
+ 'input, textarea, select, button, a, [contenteditable]',
1092
+ );
1093
+ if (typing) return;
1094
+ e.preventDefault();
1095
+ if (entriesRef.current.has(selected.anchor)) begin(selected.anchor, null, false);
1096
+ else setWantEdit({ anchor: selected.anchor, at: null, selectWord: false });
1097
+ }
185
1098
  };
186
1099
 
187
1100
  container.addEventListener('pointermove', onMove, true);
188
1101
  container.addEventListener('click', onClick, true);
1102
+ container.addEventListener('dblclick', onDblClick, true);
1103
+ window.addEventListener('pointerdown', onPointerDown, true);
189
1104
  window.addEventListener('keydown', onKey, true);
190
1105
  return () => {
191
1106
  container.removeEventListener('pointermove', onMove, true);
192
1107
  container.removeEventListener('click', onClick, true);
1108
+ container.removeEventListener('dblclick', onDblClick, true);
1109
+ window.removeEventListener('pointerdown', onPointerDown, true);
193
1110
  window.removeEventListener('keydown', onKey, true);
194
1111
  };
195
- }, [container, insidePanel, onExit, selected]);
1112
+ }, [container, insideChrome, entryAt, active, selected, begin, finish, leave]);
1113
+
1114
+ // Typing is applied by hand to the run under the caret — see inline-edit.ts
1115
+ // for why the browser is not allowed to. IME composition is the exception:
1116
+ // it cannot be cancelled, so it runs natively and is checked afterwards.
1117
+ useEffect(() => {
1118
+ if (!active) return;
1119
+ const { clone, runs } = active.editor;
1120
+ let beforeComposition: { html: Node; snapshot: Segment[][] } | null = null;
1121
+
1122
+ const record = (before: Segment[][], coalesce: boolean) => {
1123
+ const now = Date.now();
1124
+ if (!(coalesce && now - active.lastInsert < 1000)) active.undo.push(before);
1125
+ active.lastInsert = coalesce ? now : 0;
1126
+ active.redo = [];
1127
+ };
1128
+ const step = (forward: boolean) => {
1129
+ const from = forward ? active.redo : active.undo;
1130
+ const to = forward ? active.undo : active.redo;
1131
+ const texts = from.pop();
1132
+ if (!texts) return;
1133
+ to.push(snapshotRuns(runs));
1134
+ restoreRuns(runs, texts);
1135
+ active.lastInsert = 0;
1136
+ const last = runs[runs.length - 1];
1137
+ if (last) placeCaret(last.el, runLength(last.el));
1138
+ refresh();
1139
+ };
1140
+
1141
+ const onBeforeInput = (e: InputEvent) => {
1142
+ const type = e.inputType;
1143
+ if (e.isComposing || type === 'insertCompositionText') return;
1144
+ e.preventDefault();
1145
+ if (type === 'historyUndo' || type === 'historyRedo') {
1146
+ step(type === 'historyRedo');
1147
+ return;
1148
+ }
1149
+ let text: string;
1150
+ if (type === 'insertParagraph' || type === 'insertLineBreak') {
1151
+ // Enter keeps the change. Shift+Enter breaks the line — a `<br />` in
1152
+ // source, so only in text written between tags; a string passed in as
1153
+ // a prop has nowhere to put one. A code block keeps real newlines.
1154
+ if (!active.pre && type === 'insertParagraph') {
1155
+ finish(active, false);
1156
+ return;
1157
+ }
1158
+ if (!active.pre && !selectionIn(active)?.run.formattable) return;
1159
+ text = '\n';
1160
+ } else if (type.startsWith('insert')) {
1161
+ text = e.data ?? e.dataTransfer?.getData('text/plain') ?? '';
1162
+ if (!active.pre) text = text.replace(/\s*\n\s*/g, ' ');
1163
+ } else if (type.startsWith('delete')) {
1164
+ text = '';
1165
+ } else {
1166
+ return;
1167
+ }
1168
+ const range = e.getTargetRanges()[0] ?? fallbackRange(type);
1169
+ if (!range) return;
1170
+ const before = snapshotRuns(runs);
1171
+ if (replaceInRun(clone, range, text)) {
1172
+ record(before, type === 'insertText' && text.trim() !== '');
1173
+ refresh();
1174
+ }
1175
+ };
1176
+ const onKeyDown = (e: KeyboardEvent) => {
1177
+ if (e.isComposing || !(e.metaKey || e.ctrlKey) || e.altKey) return;
1178
+ const key = e.key.toLowerCase();
1179
+ if (key === 'z' || (key === 'y' && e.ctrlKey)) {
1180
+ e.preventDefault();
1181
+ step(e.shiftKey || key === 'y');
1182
+ } else if (key === 'b' || key === 'i' || key === 'e') {
1183
+ e.preventDefault();
1184
+ format(key === 'b' ? 'bold' : key === 'i' ? 'italic' : 'code');
1185
+ } else if (key === 'k') {
1186
+ e.preventDefault();
1187
+ openLink();
1188
+ } else if (key === '\\') {
1189
+ e.preventDefault();
1190
+ clear();
1191
+ } else if (key === 'u') {
1192
+ e.preventDefault();
1193
+ }
1194
+ };
1195
+ const onCompositionStart = () => {
1196
+ beforeComposition = { html: clone.cloneNode(true), snapshot: snapshotRuns(runs) };
1197
+ };
1198
+ const onCompositionEnd = () => {
1199
+ const snapshot = beforeComposition;
1200
+ beforeComposition = null;
1201
+ if (runs.every((run) => clone.contains(run.el))) {
1202
+ if (snapshot) record(snapshot.snapshot, false);
1203
+ refresh();
1204
+ return;
1205
+ }
1206
+ // The composition replaced a selection that ran past the edge of a run
1207
+ // and took the run's span with it. Put the structure back.
1208
+ if (!snapshot) return;
1209
+ clone.replaceChildren(...Array.from(snapshot.html.childNodes));
1210
+ for (const run of runs) {
1211
+ const el = clone.querySelector<HTMLElement>(`[data-od-run="${run.index}"]`);
1212
+ if (el) run.el = el;
1213
+ }
1214
+ setStatus('Type inside one run of text — the markup between runs stays as written.');
1215
+ refresh();
1216
+ };
1217
+
1218
+ clone.addEventListener('beforeinput', onBeforeInput);
1219
+ clone.addEventListener('keydown', onKeyDown);
1220
+ clone.addEventListener('compositionstart', onCompositionStart);
1221
+ clone.addEventListener('compositionend', onCompositionEnd);
1222
+ return () => {
1223
+ clone.removeEventListener('beforeinput', onBeforeInput);
1224
+ clone.removeEventListener('keydown', onKeyDown);
1225
+ clone.removeEventListener('compositionstart', onCompositionStart);
1226
+ clone.removeEventListener('compositionend', onCompositionEnd);
1227
+ };
1228
+ }, [active, finish, refresh, format, openLink, clear]);
196
1229
 
197
1230
  // Report the pick to the dev server so `current.json` can answer "this
198
1231
  // element" for an agent. Clearing the selection clears it there too.
@@ -204,49 +1237,47 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
204
1237
  line: selected.line,
205
1238
  column: selected.column,
206
1239
  tagName: selected.anchor.tagName.toLowerCase(),
207
- text: normalize(selected.anchor.textContent ?? '').slice(0, 120),
1240
+ text: shownText(selected.anchor).slice(0, 120),
208
1241
  }
209
1242
  : null,
210
1243
  });
211
1244
  }, [selected]);
212
1245
 
213
1246
  // Read the element's text from source, not from the DOM: only source can say
214
- // whether it is a single editable text child or markup we must not touch.
1247
+ // which runs are editable and which are markup we must not touch.
215
1248
  useEffect(() => {
216
- if (!selected) {
217
- setTarget(null);
218
- setDrafts({});
219
- return;
220
- }
1249
+ setResolution(null);
1250
+ if (!selected) return;
221
1251
  let cancelled = false;
222
1252
  const params = new URLSearchParams({
223
1253
  docId,
224
1254
  locs: formatLocs(candidateLocs(selected.anchor)),
225
- shown: normalize(selected.anchor.textContent ?? '').slice(0, 400),
1255
+ shown: shownText(selected.anchor).slice(0, 400),
1256
+ ...(selected.prop ? { prop: selected.prop } : {}),
226
1257
  });
227
1258
  fetch(`/__edit/text?${params}`)
228
1259
  .then((res) => res.json())
229
1260
  .then((body: ResolvedTarget & { error?: string }) => {
230
1261
  if (cancelled) return;
231
1262
  if (body.error) {
232
- setTarget(null);
233
1263
  setStatus(body.error);
234
1264
  return;
235
1265
  }
236
1266
  // Last line of defence: every run the source offers has to be visible
237
1267
  // in the element the user clicked. A drifted resolution would
238
1268
  // otherwise let a save rewrite someone else's words.
239
- const shownText = normalize(selected.anchor.textContent ?? '');
1269
+ const visible = shownText(selected.anchor);
240
1270
  const runs = (body.parts ?? []).filter((part) => part.kind === 'text');
241
1271
  const belongs =
242
1272
  runs.length > 0 &&
243
- runs.every((part) => part.kind === 'text' && shownText.includes(normalize(part.value)));
244
- setTarget(
245
- body.editable && !belongs
246
- ? { ...body, editable: false, reason: 'source text does not match this element' }
247
- : body,
248
- );
249
- setDrafts({});
1273
+ runs.every((part) => part.kind === 'text' && visible.includes(normalize(part.value)));
1274
+ setResolution({
1275
+ anchor: selected.anchor,
1276
+ value:
1277
+ body.editable && !belongs
1278
+ ? { ...body, editable: false, reason: 'source text does not match this element' }
1279
+ : body,
1280
+ });
250
1281
  })
251
1282
  .catch(() => {
252
1283
  if (!cancelled) setStatus('could not read source');
@@ -256,45 +1287,15 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
256
1287
  };
257
1288
  }, [selected, docId]);
258
1289
 
259
- const textParts = (target?.parts ?? []).filter(
260
- (part): part is Extract<TextPart, { kind: 'text' }> => part.kind === 'text',
261
- );
262
- const dirty = textParts.filter(
263
- (part) => drafts[part.index] !== undefined && drafts[part.index] !== part.value,
264
- );
265
-
266
- const saveText = async () => {
267
- if (!target || !selected || dirty.length === 0 || busy) return;
268
- setBusy(true);
269
- try {
270
- for (const part of dirty) {
271
- const res = await fetch('/__edit/text', {
272
- method: 'PUT',
273
- headers: { 'content-type': 'application/json' },
274
- body: JSON.stringify({
275
- docId,
276
- line: target.line,
277
- column: target.column,
278
- index: part.index,
279
- expected: part.value,
280
- shown: normalize(selected.anchor.textContent ?? ''),
281
- text: drafts[part.index],
282
- }),
283
- });
284
- const body = (await res.json()) as { ok?: boolean; error?: string };
285
- if (!res.ok || !body.ok) {
286
- setStatus(body.error ?? 'Save failed');
287
- return;
288
- }
289
- }
290
- setStatus('Saved to source');
291
- // Editing shifts what follows, so the captured location is good for one
292
- // write. Reselect to edit again.
293
- setSelected(null);
294
- } finally {
295
- setBusy(false);
1290
+ useEffect(() => {
1291
+ if (!wantEdit || !target || selected?.anchor !== wantEdit.anchor) return;
1292
+ setWantEdit(null);
1293
+ if (!target.editable) {
1294
+ setStatus(target.reason ?? 'This text cannot be edited here.');
1295
+ return;
296
1296
  }
297
- };
1297
+ begin(wantEdit.anchor, wantEdit.at, wantEdit.selectWord, target);
1298
+ }, [wantEdit, target, selected, begin]);
298
1299
 
299
1300
  const saveComment = async () => {
300
1301
  if (!selected || note.trim() === '' || busy) return;
@@ -323,20 +1324,58 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
323
1324
  }
324
1325
  };
325
1326
 
1327
+ const visible = (anchor: HTMLElement | null | undefined) =>
1328
+ anchor ? (entriesRef.current.get(anchor)?.editor.clone ?? anchor) : null;
1329
+ const selectedEl = visible(selected?.anchor);
1330
+ const hint = active
1331
+ ? 'Enter to keep · Shift+Enter for a new line · Esc to revert'
1332
+ : selected
1333
+ ? 'Double-click or Enter to edit text · Esc to deselect'
1334
+ : 'Click to select · double-click to edit · Esc to leave';
1335
+
326
1336
  const overlay = container
327
1337
  ? createPortal(
328
1338
  <>
329
1339
  <div className="pointer-events-none absolute inset-0 z-30">
1340
+ {pending.map((entry) =>
1341
+ entry.editor.clone === selectedEl ? null : (
1342
+ <Frame
1343
+ key={`${entry.line}:${entry.column}:${entry.shown}`}
1344
+ anchor={entry.editor.clone}
1345
+ container={container}
1346
+ variant="pending"
1347
+ />
1348
+ ),
1349
+ )}
330
1350
  <Frame
331
- anchor={hover?.anchor === selected?.anchor ? null : (hover?.anchor ?? null)}
1351
+ anchor={hover === selectedEl ? null : hover}
332
1352
  container={container}
333
1353
  variant="hover"
334
1354
  />
335
- <Frame anchor={selected?.anchor ?? null} container={container} variant="selected" />
336
- </div>
337
- <div className="pointer-events-none sticky bottom-3 z-40 mx-auto w-fit rounded-full bg-foreground/90 px-3 py-1.5 text-[11px] text-background">
338
- {selected ? 'Esc to deselect' : 'Click an element · Esc to exit'}
1355
+ <Frame anchor={selectedEl} container={container} variant="selected" />
339
1356
  </div>
1357
+ {/* Only while there is something to act on: a row of disabled
1358
+ buttons over every caret covers the line above for nothing. */}
1359
+ {active && emphasis && (emphasis.actionable || linkDraft) && (
1360
+ <TextToolbar
1361
+ anchor={active.editor.clone}
1362
+ container={container}
1363
+ emphasis={emphasis}
1364
+ link={linkDraft}
1365
+ onFormat={format}
1366
+ onOpenLink={openLink}
1367
+ onClear={clear}
1368
+ onLinkChange={(value) => setLinkDraft((prev) => (prev ? { ...prev, value } : prev))}
1369
+ onLinkApply={applyLink}
1370
+ onLinkCancel={cancelLink}
1371
+ toolbarRef={toolbarRef}
1372
+ />
1373
+ )}
1374
+ {!quiet && (
1375
+ <div className="pointer-events-none sticky bottom-3 z-40 mx-auto w-fit rounded-full bg-foreground/90 px-3 py-1.5 text-[11px] text-background">
1376
+ {status ?? hint}
1377
+ </div>
1378
+ )}
340
1379
  </>,
341
1380
  container,
342
1381
  )
@@ -345,26 +1384,22 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
345
1384
  return (
346
1385
  <>
347
1386
  {overlay}
348
- {selected && (
349
- <aside
350
- ref={panelRef}
351
- className="flex w-72 flex-none flex-col border-border border-l bg-background"
352
- >
353
- <header className="flex h-10 flex-none items-center justify-between border-border border-b px-3">
354
- <span className="font-mono text-[11px] text-muted-foreground">
1387
+ {selected && !panelHidden && (
1388
+ <PanelShell
1389
+ label="Element"
1390
+ panelRef={panelRef}
1391
+ header={
1392
+ <span className="truncate font-mono text-[11px] text-muted-foreground">
355
1393
  &lt;{selected.tag}&gt; · {target?.line ?? selected.line}:
356
1394
  {target?.column ?? selected.column}
357
1395
  </span>
358
- <button
359
- type="button"
360
- aria-label="Close"
361
- onClick={() => setSelected(null)}
362
- className="flex size-5 items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground"
363
- >
1396
+ }
1397
+ actions={
1398
+ <PanelIconButton label="Close" onClick={() => setSelected(null)}>
364
1399
  <X className="size-3.5" />
365
- </button>
366
- </header>
367
-
1400
+ </PanelIconButton>
1401
+ }
1402
+ >
368
1403
  <div className="min-h-0 flex-1 overflow-y-auto p-3">
369
1404
  <span className="block text-[10px] text-muted-foreground uppercase tracking-wider">
370
1405
  Text
@@ -374,111 +1409,13 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
374
1409
  <Loader2 className="size-3.5 animate-spin text-muted-foreground" />
375
1410
  </div>
376
1411
  ) : target.editable ? (
377
- <>
378
- {/*
379
- * One field, not one per run. A sentence interrupted by five
380
- * <code> spans is still one sentence, and bordering each
381
- * fragment turned a paragraph into eleven stacked boxes.
382
- *
383
- * The runs are laid out as the sentence reads, with the markup
384
- * between them as inert chips. Nothing re-renders while typing:
385
- * the children never change, so React leaves the DOM — and the
386
- * caret — alone, and the text is read back out of it.
387
- */}
388
- {target.parts.length > 1 ? (
389
- // biome-ignore lint/a11y/useSemanticElements: a textarea cannot hold the inert markup chips
390
- <div
391
- key={`${target.line}:${target.column}`}
392
- ref={editorRef}
393
- contentEditable
394
- suppressContentEditableWarning
395
- role="textbox"
396
- tabIndex={0}
397
- aria-label="Text"
398
- onInput={() => {
399
- const host = editorRef.current;
400
- if (!host) return;
401
- const next: Record<number, string> = {};
402
- for (const run of host.querySelectorAll<HTMLElement>('[data-run]')) {
403
- next[Number(run.dataset.run)] = run.textContent ?? '';
404
- }
405
- setDrafts(next);
406
- }}
407
- onKeyDown={(e) => {
408
- // A newline would be a <br> the runs cannot carry.
409
- if (e.key === 'Enter') {
410
- e.preventDefault();
411
- void saveText();
412
- }
413
- }}
414
- className="mt-1 rounded border border-border px-2 py-1.5 text-xs leading-relaxed outline-none focus-within:border-foreground/40"
415
- >
416
- {target.parts.map((part, index) =>
417
- part.kind === 'markup' ? (
418
- // A chip carries no whitespace, so `real<code>/<code>`
419
- // is one unbreakable word without these.
420
- // biome-ignore lint/suspicious/noArrayIndexKey: parts are positional
421
- <Fragment key={`m${index}`}>
422
- <wbr />
423
- <span
424
- contentEditable={false}
425
- title="Markup is kept as written"
426
- className="mx-0.5 select-none rounded bg-muted px-1 py-px font-mono text-[10px] text-muted-foreground"
427
- >
428
- {part.label}
429
- </span>
430
- <wbr />
431
- </Fragment>
432
- ) : (
433
- <span key={`t${part.index}`} data-run={part.index}>
434
- {part.value}
435
- </span>
436
- ),
437
- )}
438
- </div>
439
- ) : (
440
- target.parts.map((part) =>
441
- part.kind === 'markup' ? null : (
442
- <textarea
443
- key={`t${part.index}`}
444
- value={drafts[part.index] ?? part.value}
445
- onChange={(e) =>
446
- setDrafts((prev) => ({ ...prev, [part.index]: e.target.value }))
447
- }
448
- onKeyDown={(e) => {
449
- if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) void saveText();
450
- }}
451
- rows={Math.min(
452
- 14,
453
- Math.max(
454
- 2,
455
- (drafts[part.index] ?? part.value).split('\n').length,
456
- Math.ceil((drafts[part.index] ?? part.value).length / 40),
457
- ),
458
- )}
459
- className={`mt-1 w-full resize-y rounded border border-border bg-transparent px-2 py-1.5 outline-none focus:border-foreground/40 ${
460
- selected?.tag === 'pre'
461
- ? 'whitespace-pre font-mono text-[11px]'
462
- : 'text-xs'
463
- }`}
464
- />
465
- ),
466
- )
467
- )}
468
- <button
469
- type="button"
470
- onClick={saveText}
471
- disabled={busy || dirty.length === 0}
472
- className="mt-1.5 flex w-full items-center justify-center gap-1.5 rounded bg-primary px-2 py-1.5 text-primary-foreground text-xs disabled:opacity-50"
473
- >
474
- {busy ? (
475
- <Loader2 className="size-3 animate-spin" />
476
- ) : (
477
- <Check className="size-3" />
478
- )}
479
- {dirty.length > 1 ? `Save ${dirty.length} edits` : 'Save text'}
480
- </button>
481
- </>
1412
+ <p className="mt-1 text-[11px] text-muted-foreground leading-relaxed">
1413
+ {active?.anchor === selected.anchor
1414
+ ? 'Editing on the page. Enter keeps the change, Shift+Enter starts a new line, Esc reverts it.'
1415
+ : 'Double-click the text on the page, or press Enter, to edit it where it is printed.'}
1416
+ {target.parts.some((part) => part.kind === 'markup') &&
1417
+ ' Inline markup stays as written.'}
1418
+ </p>
482
1419
  ) : (
483
1420
  <p className="mt-1 rounded border border-border bg-muted px-2 py-1.5 text-[11px] text-muted-foreground">
484
1421
  {target.reason ?? 'Not editable here.'}
@@ -510,7 +1447,7 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
510
1447
 
511
1448
  {status && <p className="mt-2 text-[11px] text-muted-foreground">{status}</p>}
512
1449
  </div>
513
- </aside>
1450
+ </PanelShell>
514
1451
  )}
515
1452
  </>
516
1453
  );