@open-document/core 0.5.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.
- package/dist/{build-BzhYQKev.js → build-CFL7nhz0.js} +1 -1
- package/dist/{check-CCAaXofH.js → check-pEQh4jJE.js} +3 -3
- package/dist/cli/bin.js +6 -6
- package/dist/{config-CNr8hd5X.js → config-4nz5NnxW.js} +899 -159
- package/dist/{context-CJpdjYfU.js → context-BH8C-dSW.js} +1 -1
- package/dist/{dev-BhXgunme.js → dev-BCSUczXW.js} +1 -1
- package/dist/{export-B69kDkyp.js → export-BQ-GvMsb.js} +3 -3
- package/dist/{import-DBhCpUsl.js → import-Daat3L2J.js} +2 -2
- package/dist/index.d.ts +21 -3
- package/dist/index.js +41 -9
- package/dist/ops/index.d.ts +47 -3
- package/dist/ops/index.js +3 -3
- package/dist/{ops-BCBmRMCS.js → ops-DQfckiyp.js} +2 -45
- package/dist/{preview-Da4Aq9yF.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 +1158 -146
- 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/components/table-of-contents.tsx +4 -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/routes/doc.tsx +109 -39
- package/src/app/styles.css +41 -0
|
@@ -1,6 +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,
|
|
15
|
+
type MutableRefObject,
|
|
4
16
|
useCallback,
|
|
5
17
|
useEffect,
|
|
6
18
|
useLayoutEffect,
|
|
@@ -8,9 +20,45 @@ import {
|
|
|
8
20
|
useState,
|
|
9
21
|
} from 'react';
|
|
10
22
|
import { createPortal } from 'react-dom';
|
|
23
|
+
import { isSafeHref } from '../../lib/href';
|
|
11
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';
|
|
12
58
|
|
|
13
|
-
type TextPart =
|
|
59
|
+
type TextPart =
|
|
60
|
+
| { kind: 'text'; index: number; value: string; formattable?: true; segments?: Segment[] }
|
|
61
|
+
| { kind: 'markup'; label: string };
|
|
14
62
|
|
|
15
63
|
type ResolvedTarget = {
|
|
16
64
|
line: number;
|
|
@@ -28,26 +76,86 @@ export type InspectorTarget = {
|
|
|
28
76
|
column: number;
|
|
29
77
|
anchor: HTMLElement;
|
|
30
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;
|
|
31
103
|
};
|
|
32
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
|
+
|
|
33
132
|
// Same visual language as open-slide's inspector: dashed on hover, solid on
|
|
34
|
-
// selection, both in the same blue.
|
|
35
|
-
|
|
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> = {
|
|
36
136
|
hover: { outline: '1.5px dashed #3b82f6', background: 'rgba(59,130,246,0.05)' },
|
|
37
137
|
selected: { outline: '2px solid #3b82f6', background: 'rgba(59,130,246,0.1)' },
|
|
138
|
+
pending: { outline: '1.5px dashed #3b82f6', outlineOffset: 2 },
|
|
38
139
|
};
|
|
39
140
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
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;
|
|
43
144
|
|
|
44
145
|
function targetFrom(el: Element | null): InspectorTarget | null {
|
|
45
|
-
|
|
146
|
+
// A contents row is generated from a heading and written nowhere; the words
|
|
147
|
+
// to edit are the heading's. Clicking the row selects that instead, so the
|
|
148
|
+
// list stays what it is — a view — and still answers to a click.
|
|
149
|
+
const row = (el as HTMLElement | null)?.closest?.('[data-od-toc-entry]') as HTMLElement | null;
|
|
150
|
+
const heading = row?.dataset.odTocEntry ? document.getElementById(row.dataset.odTocEntry) : null;
|
|
151
|
+
const from = heading ?? el;
|
|
152
|
+
const host = (from as HTMLElement | null)?.closest?.(`[${LOC_ATTR}]`) as HTMLElement | null;
|
|
46
153
|
const raw = host?.getAttribute(LOC_ATTR);
|
|
47
154
|
if (!host || !raw) return null;
|
|
48
155
|
const [line, column] = raw.split(':').map(Number);
|
|
49
156
|
if (!Number.isFinite(line) || !Number.isFinite(column)) return null;
|
|
50
|
-
|
|
157
|
+
const prop = host.getAttribute(PROP_ATTR) ?? undefined;
|
|
158
|
+
return { line, column, anchor: host, tag: host.tagName.toLowerCase(), ...(prop ? { prop } : {}) };
|
|
51
159
|
}
|
|
52
160
|
|
|
53
161
|
type Rect = { left: number; top: number; width: number; height: number };
|
|
@@ -69,7 +177,7 @@ function Frame({
|
|
|
69
177
|
}: {
|
|
70
178
|
anchor: HTMLElement | null;
|
|
71
179
|
container: HTMLElement;
|
|
72
|
-
variant: 'hover' | 'selected';
|
|
180
|
+
variant: 'hover' | 'selected' | 'pending';
|
|
73
181
|
}) {
|
|
74
182
|
const [rect, setRect] = useState<Rect | null>(null);
|
|
75
183
|
|
|
@@ -119,66 +227,1005 @@ function Frame({
|
|
|
119
227
|
);
|
|
120
228
|
}
|
|
121
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
|
+
|
|
122
521
|
type Props = {
|
|
123
522
|
docId: string;
|
|
124
523
|
/** The scroll container the pages live in. */
|
|
125
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;
|
|
126
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;
|
|
127
534
|
};
|
|
128
535
|
|
|
129
|
-
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);
|
|
130
548
|
const [container, setContainer] = useState<HTMLElement | null>(null);
|
|
131
|
-
const [hover, setHover] = useState<
|
|
549
|
+
const [hover, setHover] = useState<HTMLElement | null>(null);
|
|
132
550
|
const [selected, setSelected] = useState<InspectorTarget | null>(null);
|
|
133
|
-
const [
|
|
134
|
-
|
|
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[]>([]);
|
|
135
569
|
const [note, setNote] = useState('');
|
|
136
570
|
const [busy, setBusy] = useState(false);
|
|
137
571
|
const [status, setStatus] = useState<string | null>(null);
|
|
138
572
|
const panelRef = useRef<HTMLElement>(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);
|
|
139
577
|
|
|
140
578
|
useLayoutEffect(() => setContainer(containerRef.current), [containerRef]);
|
|
141
579
|
|
|
142
|
-
const
|
|
143
|
-
(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
|
+
},
|
|
144
642
|
[],
|
|
145
643
|
);
|
|
146
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
|
+
|
|
147
1001
|
useEffect(() => {
|
|
148
1002
|
if (!container) return;
|
|
149
1003
|
|
|
150
1004
|
const onMove = (e: PointerEvent) => {
|
|
151
|
-
if (
|
|
152
|
-
|
|
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));
|
|
153
1008
|
};
|
|
154
1009
|
const onClick = (e: MouseEvent) => {
|
|
155
|
-
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
|
+
}
|
|
156
1029
|
const target = targetFrom(e.target as Element);
|
|
157
1030
|
if (!target) return;
|
|
158
1031
|
e.preventDefault();
|
|
159
1032
|
e.stopPropagation();
|
|
160
|
-
|
|
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;
|
|
1036
|
+
// A contents row sends the selection to a heading pages away. Without
|
|
1037
|
+
// this the panel fills in and the document sits where it was, which
|
|
1038
|
+
// reads as nothing having happened.
|
|
1039
|
+
if (!target.anchor.contains(e.target as Node)) {
|
|
1040
|
+
target.anchor.scrollIntoView({ block: 'center', behavior: 'smooth' });
|
|
1041
|
+
}
|
|
1042
|
+
setSelected((prev) => (prev?.anchor === target.anchor ? prev : target));
|
|
161
1043
|
setStatus(null);
|
|
162
1044
|
setNote('');
|
|
163
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
|
+
};
|
|
164
1071
|
const onKey = (e: KeyboardEvent) => {
|
|
165
|
-
if (e.
|
|
166
|
-
|
|
167
|
-
|
|
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();
|
|
168
1087
|
return;
|
|
169
1088
|
}
|
|
170
|
-
|
|
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
|
+
}
|
|
171
1098
|
};
|
|
172
1099
|
|
|
173
1100
|
container.addEventListener('pointermove', onMove, true);
|
|
174
1101
|
container.addEventListener('click', onClick, true);
|
|
1102
|
+
container.addEventListener('dblclick', onDblClick, true);
|
|
1103
|
+
window.addEventListener('pointerdown', onPointerDown, true);
|
|
175
1104
|
window.addEventListener('keydown', onKey, true);
|
|
176
1105
|
return () => {
|
|
177
1106
|
container.removeEventListener('pointermove', onMove, true);
|
|
178
1107
|
container.removeEventListener('click', onClick, true);
|
|
1108
|
+
container.removeEventListener('dblclick', onDblClick, true);
|
|
1109
|
+
window.removeEventListener('pointerdown', onPointerDown, true);
|
|
179
1110
|
window.removeEventListener('keydown', onKey, true);
|
|
180
1111
|
};
|
|
181
|
-
}, [container,
|
|
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]);
|
|
182
1229
|
|
|
183
1230
|
// Report the pick to the dev server so `current.json` can answer "this
|
|
184
1231
|
// element" for an agent. Clearing the selection clears it there too.
|
|
@@ -190,49 +1237,47 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
|
|
|
190
1237
|
line: selected.line,
|
|
191
1238
|
column: selected.column,
|
|
192
1239
|
tagName: selected.anchor.tagName.toLowerCase(),
|
|
193
|
-
text:
|
|
1240
|
+
text: shownText(selected.anchor).slice(0, 120),
|
|
194
1241
|
}
|
|
195
1242
|
: null,
|
|
196
1243
|
});
|
|
197
1244
|
}, [selected]);
|
|
198
1245
|
|
|
199
1246
|
// Read the element's text from source, not from the DOM: only source can say
|
|
200
|
-
//
|
|
1247
|
+
// which runs are editable and which are markup we must not touch.
|
|
201
1248
|
useEffect(() => {
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
setDrafts({});
|
|
205
|
-
return;
|
|
206
|
-
}
|
|
1249
|
+
setResolution(null);
|
|
1250
|
+
if (!selected) return;
|
|
207
1251
|
let cancelled = false;
|
|
208
1252
|
const params = new URLSearchParams({
|
|
209
1253
|
docId,
|
|
210
1254
|
locs: formatLocs(candidateLocs(selected.anchor)),
|
|
211
|
-
shown:
|
|
1255
|
+
shown: shownText(selected.anchor).slice(0, 400),
|
|
1256
|
+
...(selected.prop ? { prop: selected.prop } : {}),
|
|
212
1257
|
});
|
|
213
1258
|
fetch(`/__edit/text?${params}`)
|
|
214
1259
|
.then((res) => res.json())
|
|
215
1260
|
.then((body: ResolvedTarget & { error?: string }) => {
|
|
216
1261
|
if (cancelled) return;
|
|
217
1262
|
if (body.error) {
|
|
218
|
-
setTarget(null);
|
|
219
1263
|
setStatus(body.error);
|
|
220
1264
|
return;
|
|
221
1265
|
}
|
|
222
1266
|
// Last line of defence: every run the source offers has to be visible
|
|
223
1267
|
// in the element the user clicked. A drifted resolution would
|
|
224
1268
|
// otherwise let a save rewrite someone else's words.
|
|
225
|
-
const
|
|
1269
|
+
const visible = shownText(selected.anchor);
|
|
226
1270
|
const runs = (body.parts ?? []).filter((part) => part.kind === 'text');
|
|
227
1271
|
const belongs =
|
|
228
1272
|
runs.length > 0 &&
|
|
229
|
-
runs.every((part) => part.kind === 'text' &&
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
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
|
+
});
|
|
236
1281
|
})
|
|
237
1282
|
.catch(() => {
|
|
238
1283
|
if (!cancelled) setStatus('could not read source');
|
|
@@ -242,44 +1287,15 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
|
|
|
242
1287
|
};
|
|
243
1288
|
}, [selected, docId]);
|
|
244
1289
|
|
|
245
|
-
|
|
246
|
-
(
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
const saveText = async () => {
|
|
253
|
-
if (!target || dirty.length === 0 || busy) return;
|
|
254
|
-
setBusy(true);
|
|
255
|
-
try {
|
|
256
|
-
for (const part of dirty) {
|
|
257
|
-
const res = await fetch('/__edit/text', {
|
|
258
|
-
method: 'PUT',
|
|
259
|
-
headers: { 'content-type': 'application/json' },
|
|
260
|
-
body: JSON.stringify({
|
|
261
|
-
docId,
|
|
262
|
-
line: target.line,
|
|
263
|
-
column: target.column,
|
|
264
|
-
index: part.index,
|
|
265
|
-
expected: part.value,
|
|
266
|
-
text: drafts[part.index],
|
|
267
|
-
}),
|
|
268
|
-
});
|
|
269
|
-
const body = (await res.json()) as { ok?: boolean; error?: string };
|
|
270
|
-
if (!res.ok || !body.ok) {
|
|
271
|
-
setStatus(body.error ?? 'Save failed');
|
|
272
|
-
return;
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
setStatus('Saved to source');
|
|
276
|
-
// Editing shifts what follows, so the captured location is good for one
|
|
277
|
-
// write. Reselect to edit again.
|
|
278
|
-
setSelected(null);
|
|
279
|
-
} finally {
|
|
280
|
-
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;
|
|
281
1296
|
}
|
|
282
|
-
|
|
1297
|
+
begin(wantEdit.anchor, wantEdit.at, wantEdit.selectWord, target);
|
|
1298
|
+
}, [wantEdit, target, selected, begin]);
|
|
283
1299
|
|
|
284
1300
|
const saveComment = async () => {
|
|
285
1301
|
if (!selected || note.trim() === '' || busy) return;
|
|
@@ -308,20 +1324,58 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
|
|
|
308
1324
|
}
|
|
309
1325
|
};
|
|
310
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
|
+
|
|
311
1336
|
const overlay = container
|
|
312
1337
|
? createPortal(
|
|
313
1338
|
<>
|
|
314
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
|
+
)}
|
|
315
1350
|
<Frame
|
|
316
|
-
anchor={hover
|
|
1351
|
+
anchor={hover === selectedEl ? null : hover}
|
|
317
1352
|
container={container}
|
|
318
1353
|
variant="hover"
|
|
319
1354
|
/>
|
|
320
|
-
<Frame anchor={
|
|
321
|
-
</div>
|
|
322
|
-
<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">
|
|
323
|
-
{selected ? 'Esc to deselect' : 'Click an element · Esc to exit'}
|
|
1355
|
+
<Frame anchor={selectedEl} container={container} variant="selected" />
|
|
324
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
|
+
)}
|
|
325
1379
|
</>,
|
|
326
1380
|
container,
|
|
327
1381
|
)
|
|
@@ -330,26 +1384,22 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
|
|
|
330
1384
|
return (
|
|
331
1385
|
<>
|
|
332
1386
|
{overlay}
|
|
333
|
-
{selected && (
|
|
334
|
-
<
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
<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">
|
|
340
1393
|
<{selected.tag}> · {target?.line ?? selected.line}:
|
|
341
1394
|
{target?.column ?? selected.column}
|
|
342
1395
|
</span>
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
onClick={() => setSelected(null)}
|
|
347
|
-
className="flex size-5 items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground"
|
|
348
|
-
>
|
|
1396
|
+
}
|
|
1397
|
+
actions={
|
|
1398
|
+
<PanelIconButton label="Close" onClick={() => setSelected(null)}>
|
|
349
1399
|
<X className="size-3.5" />
|
|
350
|
-
</
|
|
351
|
-
|
|
352
|
-
|
|
1400
|
+
</PanelIconButton>
|
|
1401
|
+
}
|
|
1402
|
+
>
|
|
353
1403
|
<div className="min-h-0 flex-1 overflow-y-auto p-3">
|
|
354
1404
|
<span className="block text-[10px] text-muted-foreground uppercase tracking-wider">
|
|
355
1405
|
Text
|
|
@@ -359,51 +1409,13 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
|
|
|
359
1409
|
<Loader2 className="size-3.5 animate-spin text-muted-foreground" />
|
|
360
1410
|
</div>
|
|
361
1411
|
) : target.editable ? (
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
className="rounded border border-border border-dashed px-2 py-1 font-mono text-[10px] text-muted-foreground"
|
|
370
|
-
title="Markup is kept as written"
|
|
371
|
-
>
|
|
372
|
-
{part.label}
|
|
373
|
-
</div>
|
|
374
|
-
) : (
|
|
375
|
-
<textarea
|
|
376
|
-
key={`t${part.index}`}
|
|
377
|
-
value={drafts[part.index] ?? part.value}
|
|
378
|
-
onChange={(e) =>
|
|
379
|
-
setDrafts((prev) => ({ ...prev, [part.index]: e.target.value }))
|
|
380
|
-
}
|
|
381
|
-
onKeyDown={(e) => {
|
|
382
|
-
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) void saveText();
|
|
383
|
-
}}
|
|
384
|
-
rows={Math.min(
|
|
385
|
-
6,
|
|
386
|
-
Math.ceil((drafts[part.index] ?? part.value).length / 28) + 1,
|
|
387
|
-
)}
|
|
388
|
-
className="w-full resize-y rounded border border-border bg-transparent px-2 py-1.5 text-xs outline-none focus:border-foreground/40"
|
|
389
|
-
/>
|
|
390
|
-
),
|
|
391
|
-
)}
|
|
392
|
-
</div>
|
|
393
|
-
<button
|
|
394
|
-
type="button"
|
|
395
|
-
onClick={saveText}
|
|
396
|
-
disabled={busy || dirty.length === 0}
|
|
397
|
-
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"
|
|
398
|
-
>
|
|
399
|
-
{busy ? (
|
|
400
|
-
<Loader2 className="size-3 animate-spin" />
|
|
401
|
-
) : (
|
|
402
|
-
<Check className="size-3" />
|
|
403
|
-
)}
|
|
404
|
-
{dirty.length > 1 ? `Save ${dirty.length} edits` : 'Save text'}
|
|
405
|
-
</button>
|
|
406
|
-
</>
|
|
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>
|
|
407
1419
|
) : (
|
|
408
1420
|
<p className="mt-1 rounded border border-border bg-muted px-2 py-1.5 text-[11px] text-muted-foreground">
|
|
409
1421
|
{target.reason ?? 'Not editable here.'}
|
|
@@ -435,7 +1447,7 @@ export function Inspector({ docId, containerRef, onExit }: Props) {
|
|
|
435
1447
|
|
|
436
1448
|
{status && <p className="mt-2 text-[11px] text-muted-foreground">{status}</p>}
|
|
437
1449
|
</div>
|
|
438
|
-
</
|
|
1450
|
+
</PanelShell>
|
|
439
1451
|
)}
|
|
440
1452
|
</>
|
|
441
1453
|
);
|