@open-document/core 0.6.0 → 0.8.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.
- package/dist/{build-BvIHtePO.js → build-CFL7nhz0.js} +1 -1
- package/dist/{check-BqEdVH7G.js → check-pEQh4jJE.js} +3 -3
- package/dist/cli/bin.js +6 -6
- package/dist/{config-B7vFf9qZ.js → config-4nz5NnxW.js} +593 -137
- package/dist/{context-BaUE_aqU.js → context-BH8C-dSW.js} +1 -1
- package/dist/{dev-DXG-Dg-y.js → dev-BCSUczXW.js} +1 -1
- package/dist/{export-CT1Axnjv.js → export-BQ-GvMsb.js} +3 -3
- package/dist/{import-C8ZC4R6T.js → import-Daat3L2J.js} +2 -2
- package/dist/index.d.ts +21 -3
- package/dist/index.js +40 -9
- package/dist/ops/index.d.ts +47 -3
- package/dist/ops/index.js +3 -3
- package/dist/{ops-ByclxTfk.js → ops-DQfckiyp.js} +2 -45
- package/dist/{preview-CdmWbaHy.js → preview-CwCrw-i3.js} +1 -1
- package/dist/vite/index.js +1 -1
- package/package.json +1 -1
- package/src/app/components/data-table.tsx +17 -2
- package/src/app/components/design-panel/design-panel.tsx +149 -274
- package/src/app/components/design-panel/design-provider.tsx +35 -15
- package/src/app/components/footnote.tsx +27 -10
- package/src/app/components/history-provider.tsx +125 -0
- package/src/app/components/inspector/inspector.tsx +1149 -208
- package/src/app/components/numbering.tsx +13 -1
- package/src/app/components/panel/edit-save-card.tsx +112 -0
- package/src/app/components/panel/fields.tsx +247 -0
- package/src/app/components/panel/panel-shell.tsx +71 -0
- package/src/app/components/panel/save-card.tsx +146 -0
- package/src/app/lib/footnotes.ts +6 -3
- package/src/app/lib/href.ts +14 -0
- package/src/app/lib/inspector/inline-edit.test.ts +244 -0
- package/src/app/lib/inspector/inline-edit.ts +770 -0
- package/src/app/lib/source-loc.ts +15 -0
- package/src/app/lib/view-mode.test.ts +46 -0
- package/src/app/lib/view-mode.ts +76 -0
- package/src/app/routes/doc.tsx +206 -48
- package/src/app/styles.css +41 -0
|
@@ -1,7 +1,18 @@
|
|
|
1
|
-
import {
|
|
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
|
-
|
|
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 =
|
|
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
|
-
|
|
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
|
-
|
|
42
|
-
|
|
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
|
-
|
|
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,1009 @@ 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({
|
|
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<
|
|
549
|
+
const [hover, setHover] = useState<HTMLElement | null>(null);
|
|
139
550
|
const [selected, setSelected] = useState<InspectorTarget | null>(null);
|
|
140
|
-
const [
|
|
141
|
-
|
|
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
|
|
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
|
|
151
|
-
(node: EventTarget | null) =>
|
|
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 (
|
|
160
|
-
|
|
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 (
|
|
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
|
+
// On the window, not the pane: the first click opens the element panel,
|
|
1047
|
+
// and in two-up or grid a sheet near the right edge can have the panel
|
|
1048
|
+
// open right under the pointer — the second click then lands on it, and a
|
|
1049
|
+
// listener on the pane would never hear the double-click at all.
|
|
1050
|
+
const onDblClick = (e: MouseEvent) => {
|
|
1051
|
+
const first = firstClickRef.current;
|
|
1052
|
+
firstClickRef.current = null;
|
|
1053
|
+
if (first && Date.now() - first.time < DOUBLE_CLICK_MS) {
|
|
1054
|
+
e.preventDefault();
|
|
1055
|
+
setWantEdit({ anchor: first.anchor, at: first.at, selectWord: true });
|
|
1056
|
+
return;
|
|
1057
|
+
}
|
|
1058
|
+
if (!container.contains(e.target as Node) || insideChrome(e.target)) return;
|
|
1059
|
+
if (entryAt(e.target)) return;
|
|
1060
|
+
const target = targetFrom(e.target as Element);
|
|
1061
|
+
if (!target?.anchor.contains(e.target as Node)) return;
|
|
1062
|
+
e.preventDefault();
|
|
1063
|
+
setSelected((prev) => (prev?.anchor === target.anchor ? prev : target));
|
|
1064
|
+
setWantEdit({
|
|
1065
|
+
anchor: target.anchor,
|
|
1066
|
+
at: atIn(target.anchor, e.clientX, e.clientY),
|
|
1067
|
+
selectWord: true,
|
|
1068
|
+
});
|
|
1069
|
+
};
|
|
1070
|
+
const onPointerDown = (e: PointerEvent) => {
|
|
1071
|
+
if (!active || active.editor.clone.contains(e.target as Node)) return;
|
|
1072
|
+
if (toolbarRef.current?.contains(e.target as Node)) return;
|
|
1073
|
+
finish(active, false);
|
|
1074
|
+
};
|
|
178
1075
|
const onKey = (e: KeyboardEvent) => {
|
|
179
|
-
if (e.
|
|
180
|
-
|
|
181
|
-
|
|
1076
|
+
if (e.isComposing || e.keyCode === 229) return;
|
|
1077
|
+
// The link field handles its own Enter and Escape.
|
|
1078
|
+
if (toolbarRef.current?.contains(e.target as Node)) return;
|
|
1079
|
+
if (e.key === 'Escape') {
|
|
1080
|
+
if (active) {
|
|
1081
|
+
e.preventDefault();
|
|
1082
|
+
e.stopPropagation();
|
|
1083
|
+
finish(active, true);
|
|
1084
|
+
return;
|
|
1085
|
+
}
|
|
1086
|
+
if (selected) {
|
|
1087
|
+
setSelected(null);
|
|
1088
|
+
return;
|
|
1089
|
+
}
|
|
1090
|
+
void leave();
|
|
182
1091
|
return;
|
|
183
1092
|
}
|
|
184
|
-
|
|
1093
|
+
if (e.key === 'Enter' && !active && selected && !e.metaKey && !e.ctrlKey && !e.altKey) {
|
|
1094
|
+
const typing = (e.target as HTMLElement | null)?.closest?.(
|
|
1095
|
+
'input, textarea, select, button, a, [contenteditable]',
|
|
1096
|
+
);
|
|
1097
|
+
if (typing) return;
|
|
1098
|
+
e.preventDefault();
|
|
1099
|
+
if (entriesRef.current.has(selected.anchor)) begin(selected.anchor, null, false);
|
|
1100
|
+
else setWantEdit({ anchor: selected.anchor, at: null, selectWord: false });
|
|
1101
|
+
}
|
|
185
1102
|
};
|
|
186
1103
|
|
|
187
1104
|
container.addEventListener('pointermove', onMove, true);
|
|
188
1105
|
container.addEventListener('click', onClick, true);
|
|
1106
|
+
window.addEventListener('dblclick', onDblClick, true);
|
|
1107
|
+
window.addEventListener('pointerdown', onPointerDown, true);
|
|
189
1108
|
window.addEventListener('keydown', onKey, true);
|
|
190
1109
|
return () => {
|
|
191
1110
|
container.removeEventListener('pointermove', onMove, true);
|
|
192
1111
|
container.removeEventListener('click', onClick, true);
|
|
1112
|
+
window.removeEventListener('dblclick', onDblClick, true);
|
|
1113
|
+
window.removeEventListener('pointerdown', onPointerDown, true);
|
|
193
1114
|
window.removeEventListener('keydown', onKey, true);
|
|
194
1115
|
};
|
|
195
|
-
}, [container,
|
|
1116
|
+
}, [container, insideChrome, entryAt, active, selected, begin, finish, leave]);
|
|
1117
|
+
|
|
1118
|
+
// Typing is applied by hand to the run under the caret — see inline-edit.ts
|
|
1119
|
+
// for why the browser is not allowed to. IME composition is the exception:
|
|
1120
|
+
// it cannot be cancelled, so it runs natively and is checked afterwards.
|
|
1121
|
+
useEffect(() => {
|
|
1122
|
+
if (!active) return;
|
|
1123
|
+
const { clone, runs } = active.editor;
|
|
1124
|
+
let beforeComposition: { html: Node; snapshot: Segment[][] } | null = null;
|
|
1125
|
+
|
|
1126
|
+
const record = (before: Segment[][], coalesce: boolean) => {
|
|
1127
|
+
const now = Date.now();
|
|
1128
|
+
if (!(coalesce && now - active.lastInsert < 1000)) active.undo.push(before);
|
|
1129
|
+
active.lastInsert = coalesce ? now : 0;
|
|
1130
|
+
active.redo = [];
|
|
1131
|
+
};
|
|
1132
|
+
const step = (forward: boolean) => {
|
|
1133
|
+
const from = forward ? active.redo : active.undo;
|
|
1134
|
+
const to = forward ? active.undo : active.redo;
|
|
1135
|
+
const texts = from.pop();
|
|
1136
|
+
if (!texts) return;
|
|
1137
|
+
to.push(snapshotRuns(runs));
|
|
1138
|
+
restoreRuns(runs, texts);
|
|
1139
|
+
active.lastInsert = 0;
|
|
1140
|
+
const last = runs[runs.length - 1];
|
|
1141
|
+
if (last) placeCaret(last.el, runLength(last.el));
|
|
1142
|
+
refresh();
|
|
1143
|
+
};
|
|
1144
|
+
|
|
1145
|
+
const onBeforeInput = (e: InputEvent) => {
|
|
1146
|
+
const type = e.inputType;
|
|
1147
|
+
if (e.isComposing || type === 'insertCompositionText') return;
|
|
1148
|
+
e.preventDefault();
|
|
1149
|
+
if (type === 'historyUndo' || type === 'historyRedo') {
|
|
1150
|
+
step(type === 'historyRedo');
|
|
1151
|
+
return;
|
|
1152
|
+
}
|
|
1153
|
+
let text: string;
|
|
1154
|
+
if (type === 'insertParagraph' || type === 'insertLineBreak') {
|
|
1155
|
+
// Enter keeps the change. Shift+Enter breaks the line — a `<br />` in
|
|
1156
|
+
// source, so only in text written between tags; a string passed in as
|
|
1157
|
+
// a prop has nowhere to put one. A code block keeps real newlines.
|
|
1158
|
+
if (!active.pre && type === 'insertParagraph') {
|
|
1159
|
+
finish(active, false);
|
|
1160
|
+
return;
|
|
1161
|
+
}
|
|
1162
|
+
if (!active.pre && !selectionIn(active)?.run.formattable) return;
|
|
1163
|
+
text = '\n';
|
|
1164
|
+
} else if (type.startsWith('insert')) {
|
|
1165
|
+
text = e.data ?? e.dataTransfer?.getData('text/plain') ?? '';
|
|
1166
|
+
if (!active.pre) text = text.replace(/\s*\n\s*/g, ' ');
|
|
1167
|
+
} else if (type.startsWith('delete')) {
|
|
1168
|
+
text = '';
|
|
1169
|
+
} else {
|
|
1170
|
+
return;
|
|
1171
|
+
}
|
|
1172
|
+
const range = e.getTargetRanges()[0] ?? fallbackRange(type);
|
|
1173
|
+
if (!range) return;
|
|
1174
|
+
const before = snapshotRuns(runs);
|
|
1175
|
+
if (replaceInRun(clone, range, text)) {
|
|
1176
|
+
record(before, type === 'insertText' && text.trim() !== '');
|
|
1177
|
+
refresh();
|
|
1178
|
+
}
|
|
1179
|
+
};
|
|
1180
|
+
const onKeyDown = (e: KeyboardEvent) => {
|
|
1181
|
+
if (e.isComposing || !(e.metaKey || e.ctrlKey) || e.altKey) return;
|
|
1182
|
+
const key = e.key.toLowerCase();
|
|
1183
|
+
if (key === 'z' || (key === 'y' && e.ctrlKey)) {
|
|
1184
|
+
e.preventDefault();
|
|
1185
|
+
step(e.shiftKey || key === 'y');
|
|
1186
|
+
} else if (key === 'b' || key === 'i' || key === 'e') {
|
|
1187
|
+
e.preventDefault();
|
|
1188
|
+
format(key === 'b' ? 'bold' : key === 'i' ? 'italic' : 'code');
|
|
1189
|
+
} else if (key === 'k') {
|
|
1190
|
+
e.preventDefault();
|
|
1191
|
+
openLink();
|
|
1192
|
+
} else if (key === '\\') {
|
|
1193
|
+
e.preventDefault();
|
|
1194
|
+
clear();
|
|
1195
|
+
} else if (key === 'u') {
|
|
1196
|
+
e.preventDefault();
|
|
1197
|
+
}
|
|
1198
|
+
};
|
|
1199
|
+
const onCompositionStart = () => {
|
|
1200
|
+
beforeComposition = { html: clone.cloneNode(true), snapshot: snapshotRuns(runs) };
|
|
1201
|
+
};
|
|
1202
|
+
const onCompositionEnd = () => {
|
|
1203
|
+
const snapshot = beforeComposition;
|
|
1204
|
+
beforeComposition = null;
|
|
1205
|
+
if (runs.every((run) => clone.contains(run.el))) {
|
|
1206
|
+
if (snapshot) record(snapshot.snapshot, false);
|
|
1207
|
+
refresh();
|
|
1208
|
+
return;
|
|
1209
|
+
}
|
|
1210
|
+
// The composition replaced a selection that ran past the edge of a run
|
|
1211
|
+
// and took the run's span with it. Put the structure back.
|
|
1212
|
+
if (!snapshot) return;
|
|
1213
|
+
clone.replaceChildren(...Array.from(snapshot.html.childNodes));
|
|
1214
|
+
for (const run of runs) {
|
|
1215
|
+
const el = clone.querySelector<HTMLElement>(`[data-od-run="${run.index}"]`);
|
|
1216
|
+
if (el) run.el = el;
|
|
1217
|
+
}
|
|
1218
|
+
setStatus('Type inside one run of text — the markup between runs stays as written.');
|
|
1219
|
+
refresh();
|
|
1220
|
+
};
|
|
1221
|
+
|
|
1222
|
+
clone.addEventListener('beforeinput', onBeforeInput);
|
|
1223
|
+
clone.addEventListener('keydown', onKeyDown);
|
|
1224
|
+
clone.addEventListener('compositionstart', onCompositionStart);
|
|
1225
|
+
clone.addEventListener('compositionend', onCompositionEnd);
|
|
1226
|
+
return () => {
|
|
1227
|
+
clone.removeEventListener('beforeinput', onBeforeInput);
|
|
1228
|
+
clone.removeEventListener('keydown', onKeyDown);
|
|
1229
|
+
clone.removeEventListener('compositionstart', onCompositionStart);
|
|
1230
|
+
clone.removeEventListener('compositionend', onCompositionEnd);
|
|
1231
|
+
};
|
|
1232
|
+
}, [active, finish, refresh, format, openLink, clear]);
|
|
196
1233
|
|
|
197
1234
|
// Report the pick to the dev server so `current.json` can answer "this
|
|
198
1235
|
// element" for an agent. Clearing the selection clears it there too.
|
|
@@ -204,49 +1241,47 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
|
|
|
204
1241
|
line: selected.line,
|
|
205
1242
|
column: selected.column,
|
|
206
1243
|
tagName: selected.anchor.tagName.toLowerCase(),
|
|
207
|
-
text:
|
|
1244
|
+
text: shownText(selected.anchor).slice(0, 120),
|
|
208
1245
|
}
|
|
209
1246
|
: null,
|
|
210
1247
|
});
|
|
211
1248
|
}, [selected]);
|
|
212
1249
|
|
|
213
1250
|
// Read the element's text from source, not from the DOM: only source can say
|
|
214
|
-
//
|
|
1251
|
+
// which runs are editable and which are markup we must not touch.
|
|
215
1252
|
useEffect(() => {
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
setDrafts({});
|
|
219
|
-
return;
|
|
220
|
-
}
|
|
1253
|
+
setResolution(null);
|
|
1254
|
+
if (!selected) return;
|
|
221
1255
|
let cancelled = false;
|
|
222
1256
|
const params = new URLSearchParams({
|
|
223
1257
|
docId,
|
|
224
1258
|
locs: formatLocs(candidateLocs(selected.anchor)),
|
|
225
|
-
shown:
|
|
1259
|
+
shown: shownText(selected.anchor).slice(0, 400),
|
|
1260
|
+
...(selected.prop ? { prop: selected.prop } : {}),
|
|
226
1261
|
});
|
|
227
1262
|
fetch(`/__edit/text?${params}`)
|
|
228
1263
|
.then((res) => res.json())
|
|
229
1264
|
.then((body: ResolvedTarget & { error?: string }) => {
|
|
230
1265
|
if (cancelled) return;
|
|
231
1266
|
if (body.error) {
|
|
232
|
-
setTarget(null);
|
|
233
1267
|
setStatus(body.error);
|
|
234
1268
|
return;
|
|
235
1269
|
}
|
|
236
1270
|
// Last line of defence: every run the source offers has to be visible
|
|
237
1271
|
// in the element the user clicked. A drifted resolution would
|
|
238
1272
|
// otherwise let a save rewrite someone else's words.
|
|
239
|
-
const
|
|
1273
|
+
const visible = shownText(selected.anchor);
|
|
240
1274
|
const runs = (body.parts ?? []).filter((part) => part.kind === 'text');
|
|
241
1275
|
const belongs =
|
|
242
1276
|
runs.length > 0 &&
|
|
243
|
-
runs.every((part) => part.kind === 'text' &&
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
1277
|
+
runs.every((part) => part.kind === 'text' && visible.includes(normalize(part.value)));
|
|
1278
|
+
setResolution({
|
|
1279
|
+
anchor: selected.anchor,
|
|
1280
|
+
value:
|
|
1281
|
+
body.editable && !belongs
|
|
1282
|
+
? { ...body, editable: false, reason: 'source text does not match this element' }
|
|
1283
|
+
: body,
|
|
1284
|
+
});
|
|
250
1285
|
})
|
|
251
1286
|
.catch(() => {
|
|
252
1287
|
if (!cancelled) setStatus('could not read source');
|
|
@@ -256,45 +1291,15 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
|
|
|
256
1291
|
};
|
|
257
1292
|
}, [selected, docId]);
|
|
258
1293
|
|
|
259
|
-
|
|
260
|
-
(
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
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);
|
|
1294
|
+
useEffect(() => {
|
|
1295
|
+
if (!wantEdit || !target || selected?.anchor !== wantEdit.anchor) return;
|
|
1296
|
+
setWantEdit(null);
|
|
1297
|
+
if (!target.editable) {
|
|
1298
|
+
setStatus(target.reason ?? 'This text cannot be edited here.');
|
|
1299
|
+
return;
|
|
296
1300
|
}
|
|
297
|
-
|
|
1301
|
+
begin(wantEdit.anchor, wantEdit.at, wantEdit.selectWord, target);
|
|
1302
|
+
}, [wantEdit, target, selected, begin]);
|
|
298
1303
|
|
|
299
1304
|
const saveComment = async () => {
|
|
300
1305
|
if (!selected || note.trim() === '' || busy) return;
|
|
@@ -323,20 +1328,58 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
|
|
|
323
1328
|
}
|
|
324
1329
|
};
|
|
325
1330
|
|
|
1331
|
+
const visible = (anchor: HTMLElement | null | undefined) =>
|
|
1332
|
+
anchor ? (entriesRef.current.get(anchor)?.editor.clone ?? anchor) : null;
|
|
1333
|
+
const selectedEl = visible(selected?.anchor);
|
|
1334
|
+
const hint = active
|
|
1335
|
+
? 'Enter to keep · Shift+Enter for a new line · Esc to revert'
|
|
1336
|
+
: selected
|
|
1337
|
+
? 'Double-click or Enter to edit text · Esc to deselect'
|
|
1338
|
+
: 'Click to select · double-click to edit · Esc to leave';
|
|
1339
|
+
|
|
326
1340
|
const overlay = container
|
|
327
1341
|
? createPortal(
|
|
328
1342
|
<>
|
|
329
1343
|
<div className="pointer-events-none absolute inset-0 z-30">
|
|
1344
|
+
{pending.map((entry) =>
|
|
1345
|
+
entry.editor.clone === selectedEl ? null : (
|
|
1346
|
+
<Frame
|
|
1347
|
+
key={`${entry.line}:${entry.column}:${entry.shown}`}
|
|
1348
|
+
anchor={entry.editor.clone}
|
|
1349
|
+
container={container}
|
|
1350
|
+
variant="pending"
|
|
1351
|
+
/>
|
|
1352
|
+
),
|
|
1353
|
+
)}
|
|
330
1354
|
<Frame
|
|
331
|
-
anchor={hover
|
|
1355
|
+
anchor={hover === selectedEl ? null : hover}
|
|
332
1356
|
container={container}
|
|
333
1357
|
variant="hover"
|
|
334
1358
|
/>
|
|
335
|
-
<Frame anchor={
|
|
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'}
|
|
1359
|
+
<Frame anchor={selectedEl} container={container} variant="selected" />
|
|
339
1360
|
</div>
|
|
1361
|
+
{/* Only while there is something to act on: a row of disabled
|
|
1362
|
+
buttons over every caret covers the line above for nothing. */}
|
|
1363
|
+
{active && emphasis && (emphasis.actionable || linkDraft) && (
|
|
1364
|
+
<TextToolbar
|
|
1365
|
+
anchor={active.editor.clone}
|
|
1366
|
+
container={container}
|
|
1367
|
+
emphasis={emphasis}
|
|
1368
|
+
link={linkDraft}
|
|
1369
|
+
onFormat={format}
|
|
1370
|
+
onOpenLink={openLink}
|
|
1371
|
+
onClear={clear}
|
|
1372
|
+
onLinkChange={(value) => setLinkDraft((prev) => (prev ? { ...prev, value } : prev))}
|
|
1373
|
+
onLinkApply={applyLink}
|
|
1374
|
+
onLinkCancel={cancelLink}
|
|
1375
|
+
toolbarRef={toolbarRef}
|
|
1376
|
+
/>
|
|
1377
|
+
)}
|
|
1378
|
+
{!quiet && (
|
|
1379
|
+
<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">
|
|
1380
|
+
{status ?? hint}
|
|
1381
|
+
</div>
|
|
1382
|
+
)}
|
|
340
1383
|
</>,
|
|
341
1384
|
container,
|
|
342
1385
|
)
|
|
@@ -345,26 +1388,22 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
|
|
|
345
1388
|
return (
|
|
346
1389
|
<>
|
|
347
1390
|
{overlay}
|
|
348
|
-
{selected && (
|
|
349
|
-
<
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
<span className="font-mono text-[11px] text-muted-foreground">
|
|
1391
|
+
{selected && !panelHidden && (
|
|
1392
|
+
<PanelShell
|
|
1393
|
+
label="Element"
|
|
1394
|
+
panelRef={panelRef}
|
|
1395
|
+
header={
|
|
1396
|
+
<span className="truncate font-mono text-[11px] text-muted-foreground">
|
|
355
1397
|
<{selected.tag}> · {target?.line ?? selected.line}:
|
|
356
1398
|
{target?.column ?? selected.column}
|
|
357
1399
|
</span>
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
onClick={() => setSelected(null)}
|
|
362
|
-
className="flex size-5 items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground"
|
|
363
|
-
>
|
|
1400
|
+
}
|
|
1401
|
+
actions={
|
|
1402
|
+
<PanelIconButton label="Close" onClick={() => setSelected(null)}>
|
|
364
1403
|
<X className="size-3.5" />
|
|
365
|
-
</
|
|
366
|
-
|
|
367
|
-
|
|
1404
|
+
</PanelIconButton>
|
|
1405
|
+
}
|
|
1406
|
+
>
|
|
368
1407
|
<div className="min-h-0 flex-1 overflow-y-auto p-3">
|
|
369
1408
|
<span className="block text-[10px] text-muted-foreground uppercase tracking-wider">
|
|
370
1409
|
Text
|
|
@@ -374,111 +1413,13 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
|
|
|
374
1413
|
<Loader2 className="size-3.5 animate-spin text-muted-foreground" />
|
|
375
1414
|
</div>
|
|
376
1415
|
) : target.editable ? (
|
|
377
|
-
|
|
378
|
-
{
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
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
|
-
</>
|
|
1416
|
+
<p className="mt-1 text-[11px] text-muted-foreground leading-relaxed">
|
|
1417
|
+
{active?.anchor === selected.anchor
|
|
1418
|
+
? 'Editing on the page. Enter keeps the change, Shift+Enter starts a new line, Esc reverts it.'
|
|
1419
|
+
: 'Double-click the text on the page, or press Enter, to edit it where it is printed.'}
|
|
1420
|
+
{target.parts.some((part) => part.kind === 'markup') &&
|
|
1421
|
+
' Inline markup stays as written.'}
|
|
1422
|
+
</p>
|
|
482
1423
|
) : (
|
|
483
1424
|
<p className="mt-1 rounded border border-border bg-muted px-2 py-1.5 text-[11px] text-muted-foreground">
|
|
484
1425
|
{target.reason ?? 'Not editable here.'}
|
|
@@ -510,7 +1451,7 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
|
|
|
510
1451
|
|
|
511
1452
|
{status && <p className="mt-2 text-[11px] text-muted-foreground">{status}</p>}
|
|
512
1453
|
</div>
|
|
513
|
-
</
|
|
1454
|
+
</PanelShell>
|
|
514
1455
|
)}
|
|
515
1456
|
</>
|
|
516
1457
|
);
|