@open-document/core 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/{build-BvIHtePO.js → build-CFL7nhz0.js} +1 -1
  2. package/dist/{check-BqEdVH7G.js → check-pEQh4jJE.js} +3 -3
  3. package/dist/cli/bin.js +6 -6
  4. package/dist/{config-B7vFf9qZ.js → config-4nz5NnxW.js} +593 -137
  5. package/dist/{context-BaUE_aqU.js → context-BH8C-dSW.js} +1 -1
  6. package/dist/{dev-DXG-Dg-y.js → dev-BCSUczXW.js} +1 -1
  7. package/dist/{export-CT1Axnjv.js → export-BQ-GvMsb.js} +3 -3
  8. package/dist/{import-C8ZC4R6T.js → import-Daat3L2J.js} +2 -2
  9. package/dist/index.d.ts +21 -3
  10. package/dist/index.js +40 -9
  11. package/dist/ops/index.d.ts +47 -3
  12. package/dist/ops/index.js +3 -3
  13. package/dist/{ops-ByclxTfk.js → ops-DQfckiyp.js} +2 -45
  14. package/dist/{preview-CdmWbaHy.js → preview-CwCrw-i3.js} +1 -1
  15. package/dist/vite/index.js +1 -1
  16. package/package.json +1 -1
  17. package/src/app/components/data-table.tsx +17 -2
  18. package/src/app/components/design-panel/design-panel.tsx +149 -274
  19. package/src/app/components/design-panel/design-provider.tsx +35 -15
  20. package/src/app/components/footnote.tsx +27 -10
  21. package/src/app/components/history-provider.tsx +125 -0
  22. package/src/app/components/inspector/inspector.tsx +1145 -208
  23. package/src/app/components/numbering.tsx +13 -1
  24. package/src/app/components/panel/edit-save-card.tsx +112 -0
  25. package/src/app/components/panel/fields.tsx +247 -0
  26. package/src/app/components/panel/panel-shell.tsx +71 -0
  27. package/src/app/components/panel/save-card.tsx +146 -0
  28. package/src/app/lib/footnotes.ts +6 -3
  29. package/src/app/lib/href.ts +14 -0
  30. package/src/app/lib/inspector/inline-edit.test.ts +244 -0
  31. package/src/app/lib/inspector/inline-edit.ts +770 -0
  32. package/src/app/lib/source-loc.ts +15 -0
  33. package/src/app/routes/doc.tsx +109 -39
  34. package/src/app/styles.css +41 -0
@@ -0,0 +1,770 @@
1
+ /*
2
+ * Editing text on the page, where it is printed.
3
+ *
4
+ * The element the reader double-clicked belongs to React. Typing into it
5
+ * directly lets the browser split, merge, and delete nodes React still holds
6
+ * references to, and the next commit that touches that subtree throws. So the
7
+ * editor never touches it: it hides the element and puts a clone in its place,
8
+ * with the same classes and inline styles, in the same parent — the clone lays
9
+ * out exactly as the original did. Discarding removes the clone and shows the
10
+ * original again, untouched. Saving writes source and lets hot reload replace
11
+ * the original; the clone is only removed once it has.
12
+ *
13
+ * Inside the clone every run of text the source can take back is wrapped in a
14
+ * `[data-od-run]` span, and every other node is inert. Keystrokes are applied
15
+ * by hand to the run the caret is in, which is what keeps the runs intact:
16
+ * left to itself the browser deletes an emptied span and puts the next
17
+ * character beside it, where no run can claim it.
18
+ *
19
+ * A run is held as segments — stretches of text and the formatting on them —
20
+ * so bold, italic, code and links show as real `<strong>`, `<em>`, `<code>`
21
+ * and `<a>` inside the run and still read back as one run the source can take.
22
+ *
23
+ * A line break is a `'\n'` in a segment and a `<br>` on the page. A `<br>` has
24
+ * no text, so every offset here counts it as one character by hand — reading
25
+ * offsets off `Range.toString()` would put the caret one place short after
26
+ * every break.
27
+ */
28
+
29
+ export const EDITING_ATTR = 'data-od-editing';
30
+ const RUN_ATTR = 'data-od-run';
31
+
32
+ export type Mark = 'bold' | 'italic' | 'code';
33
+ export type Segment = {
34
+ text: string;
35
+ bold?: boolean;
36
+ italic?: boolean;
37
+ code?: boolean;
38
+ href?: string;
39
+ };
40
+
41
+ export type RunPart = {
42
+ index: number;
43
+ value: string;
44
+ formattable?: boolean;
45
+ segments?: Segment[];
46
+ };
47
+
48
+ export type Run = {
49
+ index: number;
50
+ /** The run's text in source, as the server resolved it. */
51
+ expected: string;
52
+ /** The run's formatting in source; plain text when it has none. */
53
+ expectedSegments: Segment[];
54
+ /** Written between tags in source, so it can take formatting. */
55
+ formattable: boolean;
56
+ el: HTMLElement;
57
+ };
58
+
59
+ function sameMarks(a: Segment, b: Segment): boolean {
60
+ return (
61
+ Boolean(a.bold) === Boolean(b.bold) &&
62
+ Boolean(a.italic) === Boolean(b.italic) &&
63
+ Boolean(a.code) === Boolean(b.code) &&
64
+ a.href === b.href
65
+ );
66
+ }
67
+
68
+ function marksOf(segment: Segment | undefined): Omit<Segment, 'text'> {
69
+ return {
70
+ ...(segment?.bold ? { bold: true } : {}),
71
+ ...(segment?.italic ? { italic: true } : {}),
72
+ ...(segment?.code ? { code: true } : {}),
73
+ ...(segment?.href ? { href: segment.href } : {}),
74
+ };
75
+ }
76
+
77
+ /** Drops empty pieces and joins neighbours that carry the same formatting. */
78
+ export function mergeSegments(segments: Segment[]): Segment[] {
79
+ const out: Segment[] = [];
80
+ for (const segment of segments) {
81
+ if (segment.text === '') continue;
82
+ const last = out[out.length - 1];
83
+ if (last && sameMarks(last, segment)) last.text += segment.text;
84
+ else out.push({ text: segment.text, ...marksOf(segment) });
85
+ }
86
+ return out;
87
+ }
88
+
89
+ export function segmentsText(segments: Segment[]): string {
90
+ return segments.map((segment) => segment.text).join('');
91
+ }
92
+
93
+ /**
94
+ * One piece per UTF-16 unit — the unit DOM offsets count in, so a range read
95
+ * off the selection lines up with these indices even past an emoji.
96
+ */
97
+ function explode(segments: Segment[]): Segment[] {
98
+ return segments.flatMap((segment) =>
99
+ segment.text.split('').map((char) => ({ text: char, ...marksOf(segment) })),
100
+ );
101
+ }
102
+
103
+ /**
104
+ * Replaces characters `from`–`to` with `text`. Typing over a selection takes
105
+ * the formatting of what it replaces — retyping a bold word keeps it bold.
106
+ * Typing at a caret takes the formatting of the character before it, so
107
+ * typing at the end of a bold word continues the bold. A link is the
108
+ * exception: typing just past its end does not extend it.
109
+ */
110
+ export function spliceSegments(
111
+ segments: Segment[],
112
+ from: number,
113
+ to: number,
114
+ text: string,
115
+ ): Segment[] {
116
+ const chars = explode(segments);
117
+ const source = to > from ? chars[from] : (chars[from - 1] ?? chars[from]);
118
+ const like = { ...marksOf(source ?? chars[0]) };
119
+ if (like.href && chars[to]?.href !== like.href && from > 0) delete like.href;
120
+ const inserted = text.split('').map((char) => ({ text: char, ...like }));
121
+ return mergeSegments([...chars.slice(0, from), ...inserted, ...chars.slice(to)]);
122
+ }
123
+
124
+ /** Whether every character in `from`–`to` carries the mark. */
125
+ export function hasMark(segments: Segment[], from: number, to: number, mark: Mark): boolean {
126
+ const chars = explode(segments).slice(from, to);
127
+ return chars.length > 0 && chars.every((char) => char[mark]);
128
+ }
129
+
130
+ /** Adds the mark to the range, or takes it off when the whole range already has it. */
131
+ export function toggleMark(segments: Segment[], from: number, to: number, mark: Mark): Segment[] {
132
+ const on = !hasMark(segments, from, to, mark);
133
+ const chars = explode(segments).map((char, at) =>
134
+ at >= from && at < to ? { ...char, [mark]: on } : char,
135
+ );
136
+ return mergeSegments(chars);
137
+ }
138
+
139
+ /** Links the range to `href`, or unlinks it when `href` is null. */
140
+ export function setHref(
141
+ segments: Segment[],
142
+ from: number,
143
+ to: number,
144
+ href: string | null,
145
+ ): Segment[] {
146
+ const chars = explode(segments).map((char, at) => {
147
+ if (at < from || at >= to) return char;
148
+ const { href: _drop, ...rest } = char;
149
+ return href ? { ...rest, href } : rest;
150
+ });
151
+ return mergeSegments(chars);
152
+ }
153
+
154
+ /** Takes every kind of formatting off the range. */
155
+ export function clearFormatting(segments: Segment[], from: number, to: number): Segment[] {
156
+ const chars = explode(segments).map((char, at) =>
157
+ at >= from && at < to ? { text: char.text } : char,
158
+ );
159
+ return mergeSegments(chars);
160
+ }
161
+
162
+ /** The link under `offset`, and how far it reaches either side. */
163
+ export function linkAt(
164
+ segments: Segment[],
165
+ offset: number,
166
+ ): { from: number; to: number; href: string } | null {
167
+ const chars = explode(segments);
168
+ const href = chars[offset]?.href ?? chars[offset - 1]?.href;
169
+ if (!href) return null;
170
+ let from = chars[offset]?.href === href ? offset : offset - 1;
171
+ let to = from + 1;
172
+ while (from > 0 && chars[from - 1]?.href === href) from--;
173
+ while (to < chars.length && chars[to]?.href === href) to++;
174
+ return { from, to, href };
175
+ }
176
+
177
+ /** The href shared by every character in the range, if there is one. */
178
+ export function hrefOf(segments: Segment[], from: number, to: number): string | null {
179
+ const chars = explode(segments).slice(from, to);
180
+ const href = chars[0]?.href;
181
+ return href && chars.every((char) => char.href === href) ? href : null;
182
+ }
183
+
184
+ /** A length-preserving rewrite of the text, applied across piece boundaries. */
185
+ export function mapSegmentText(segments: Segment[], fn: (text: string) => string): Segment[] {
186
+ const next = fn(segmentsText(segments));
187
+ let at = 0;
188
+ return segments.map((segment) => {
189
+ const text = next.slice(at, at + segment.text.length);
190
+ at += segment.text.length;
191
+ return { ...segment, text };
192
+ });
193
+ }
194
+
195
+ /**
196
+ * The formatting of a run, character by character, blind to whitespace — two
197
+ * runs whose words carry the same marks compare equal however their spaces
198
+ * were written.
199
+ */
200
+ function formatSignature(segments: Segment[]): string {
201
+ return explode(segments)
202
+ .filter((char) => char.text === '\n' || char.text.trim() !== '')
203
+ .map(
204
+ (char) =>
205
+ `${char.text}${char.bold ? 'b' : ''}${char.italic ? 'i' : ''}${char.code ? 'c' : ''}${char.href ?? ''}`,
206
+ )
207
+ .join('\n');
208
+ }
209
+
210
+ export type MountedEditor = {
211
+ clone: HTMLElement;
212
+ runs: Run[];
213
+ restore: () => void;
214
+ };
215
+
216
+ export function normalize(value: string): string {
217
+ return value.replace(/\s+/g, ' ').trim();
218
+ }
219
+
220
+ const MARK_ELEMENTS = new Set(['STRONG', 'B', 'EM', 'I', 'CODE']);
221
+
222
+ /**
223
+ * The DOM side of the server's rule: a bare mark, or a link with nothing but
224
+ * an href, holding only text and other marks. `data-*` attributes do not
225
+ * count: the loc tag is ours, and extensions and tooling stamp their own onto
226
+ * whatever they touch. One the author wrote makes the server call the element
227
+ * markup, and the runs it splits into still line up here.
228
+ */
229
+ function isMarkElement(el: Element): boolean {
230
+ const own = Array.from(el.attributes)
231
+ .map((attribute) => attribute.name)
232
+ .filter((name) => !name.startsWith('data-'));
233
+ const bare =
234
+ el.tagName === 'A'
235
+ ? own.length === 1 && own[0] === 'href'
236
+ : MARK_ELEMENTS.has(el.tagName) && own.length === 0;
237
+ return bare && Array.from(el.children).every(isMarkElement);
238
+ }
239
+
240
+ export type Item = { text: string; inline: boolean };
241
+
242
+ /**
243
+ * Pairs each source run with a stretch of the element's children, in order.
244
+ *
245
+ * A run is text and marks side by side, so its match is a contiguous range of
246
+ * inline children — text nodes, bare marks — whose words read as the run's.
247
+ * Markup between runs is stepped over; so is text a run does not claim, such
248
+ * as the output of an expression the source cannot trace. Returns the range
249
+ * per run, or null when any run cannot be placed.
250
+ */
251
+ export function matchRanges(parts: RunPart[], items: Item[]): Array<[number, number]> | null {
252
+ if (parts.length === 0) return null;
253
+ const out: Array<[number, number]> = [];
254
+ let from = 0;
255
+ for (const part of parts) {
256
+ const want = normalize(part.value);
257
+ let found: [number, number] | null = null;
258
+ for (let start = from; start < items.length && !found; start++) {
259
+ const first = items[start];
260
+ if (!first?.inline || normalize(first.text) === '') continue;
261
+ let seen = '';
262
+ for (let end = start; end < items.length; end++) {
263
+ const item = items[end];
264
+ if (!item?.inline) break;
265
+ seen += item.text;
266
+ const have = normalize(seen);
267
+ if (have === want) {
268
+ found = [start, end];
269
+ break;
270
+ }
271
+ if (!want.startsWith(have)) break;
272
+ }
273
+ }
274
+ if (!found) return null;
275
+ out.push(found);
276
+ from = found[1] + 1;
277
+ }
278
+ return out;
279
+ }
280
+
281
+ function itemsOf(anchor: HTMLElement): Item[] {
282
+ return Array.from(anchor.childNodes).map((node) => {
283
+ if (node instanceof Element && node.tagName === 'BR') return { text: '\n', inline: true };
284
+ return {
285
+ text: node.textContent ?? '',
286
+ inline: node.nodeType === Node.TEXT_NODE || (node instanceof Element && isMarkElement(node)),
287
+ };
288
+ });
289
+ }
290
+
291
+ /**
292
+ * A helper may wrap its children one level down, so a plain run that is not
293
+ * among the element's own children is looked for as a single text node
294
+ * anywhere inside it. A formatted run is never searched for this way: its
295
+ * pieces would have to be gathered from wherever they happened to fall.
296
+ */
297
+ function deepTextNodes(anchor: HTMLElement, parts: RunPart[]): Text[] | null {
298
+ if (parts.some((part) => part.segments)) return null;
299
+ const pool: Text[] = [];
300
+ const walker = document.createTreeWalker(anchor, NodeFilter.SHOW_TEXT);
301
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
302
+ if (normalize(node.nodeValue ?? '') !== '') pool.push(node as Text);
303
+ }
304
+ const picked: Text[] = [];
305
+ let from = 0;
306
+ for (const part of parts) {
307
+ const at = pool.findIndex(
308
+ (node, index) => index >= from && normalize(node.nodeValue ?? '') === normalize(part.value),
309
+ );
310
+ const node = pool[at];
311
+ if (at < 0 || !node) return null;
312
+ picked.push(node);
313
+ from = at + 1;
314
+ }
315
+ return picked;
316
+ }
317
+
318
+ function pathOf(node: Node, root: Node): number[] {
319
+ const path: number[] = [];
320
+ let at: Node | null = node;
321
+ while (at && at !== root) {
322
+ const parent: Node | null = at.parentNode;
323
+ if (!parent) return [];
324
+ path.unshift(Array.prototype.indexOf.call(parent.childNodes, at));
325
+ at = parent;
326
+ }
327
+ return path;
328
+ }
329
+
330
+ function follow(root: Node, path: number[]): Node | null {
331
+ let at: Node | null = root;
332
+ for (const step of path) at = at?.childNodes[step] ?? null;
333
+ return at;
334
+ }
335
+
336
+ /**
337
+ * Hides `anchor` and puts an editable clone where it was, or returns null when
338
+ * the rendered text cannot be lined up with the runs the source offers — the
339
+ * caller then says why rather than guessing which words go where.
340
+ */
341
+ export function mountEditor(anchor: HTMLElement, parts: RunPart[]): MountedEditor | null {
342
+ const ranges = matchRanges(parts, itemsOf(anchor));
343
+ const deep = ranges ? null : deepTextNodes(anchor, parts);
344
+ if (!ranges && !deep) return null;
345
+
346
+ const clone = anchor.cloneNode(true) as HTMLElement;
347
+ // Ids and loc tags belong to the original: a duplicate id would capture
348
+ // outline jumps, and a loc tag would let the inspector select the clone as
349
+ // if it were source.
350
+ for (const el of [clone, ...Array.from(clone.querySelectorAll<HTMLElement>('*'))]) {
351
+ el.removeAttribute('id');
352
+ el.removeAttribute('data-od-loc');
353
+ }
354
+
355
+ // Resolve every run's nodes in the clone before moving any of them, so one
356
+ // run's wrapping cannot shift the positions another is found by.
357
+ const groups: Node[][] = ranges
358
+ ? ranges.map(([start, end]) => Array.from(clone.childNodes).slice(start, end + 1))
359
+ : (deep ?? []).map((node) => {
360
+ const twin = follow(clone, pathOf(node, anchor));
361
+ return twin ? [twin] : [];
362
+ });
363
+
364
+ const runs: Run[] = [];
365
+ groups.forEach((nodes, at) => {
366
+ const part = parts[at];
367
+ const first = nodes[0];
368
+ if (!part || !first) return;
369
+ const span = document.createElement('span');
370
+ span.setAttribute(RUN_ATTR, String(part.index));
371
+ first.parentNode?.insertBefore(span, first);
372
+ for (const node of nodes) span.appendChild(node);
373
+ runs.push({
374
+ index: part.index,
375
+ expected: part.value,
376
+ expectedSegments: part.segments ?? [{ text: part.value }],
377
+ formattable: part.formattable ?? false,
378
+ el: span,
379
+ });
380
+ });
381
+ if (runs.length !== parts.length) return null;
382
+
383
+ for (const el of Array.from(clone.querySelectorAll<HTMLElement>('*'))) {
384
+ if (!el.hasAttribute(RUN_ATTR) && !el.closest(`[${RUN_ATTR}]`)) {
385
+ el.setAttribute('contenteditable', 'false');
386
+ }
387
+ }
388
+ clone.setAttribute(EDITING_ATTR, '');
389
+ clone.setAttribute('contenteditable', 'true');
390
+ clone.setAttribute('spellcheck', 'false');
391
+ clone.setAttribute('role', 'textbox');
392
+ clone.setAttribute('aria-label', 'Edit text');
393
+ // The inspector's selection frame is the focus indicator; the browser's own
394
+ // ring would sit inside it, a second outline around the same words.
395
+ clone.style.outline = 'none';
396
+ clone.style.cursor = 'text';
397
+ clone.style.userSelect = 'text';
398
+ // A link inside the text being edited is text to edit, not a way off the page.
399
+ clone.addEventListener('click', (event) => {
400
+ if ((event.target as Element | null)?.closest?.('a')) event.preventDefault();
401
+ });
402
+
403
+ const display = anchor.style.getPropertyValue('display');
404
+ const priority = anchor.style.getPropertyPriority('display');
405
+ anchor.style.setProperty('display', 'none', 'important');
406
+ anchor.after(clone);
407
+
408
+ return {
409
+ clone,
410
+ runs,
411
+ restore: () => {
412
+ clone.remove();
413
+ if (display) anchor.style.setProperty('display', display, priority);
414
+ else anchor.style.removeProperty('display');
415
+ },
416
+ };
417
+ }
418
+
419
+ /**
420
+ * What an element reads as, a line break counting as a space. `textContent`
421
+ * joins the words either side of a `<br>` into one, so text the source holds
422
+ * as two words would never be found in it.
423
+ */
424
+ export function shownText(el: HTMLElement): string {
425
+ let out = '';
426
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);
427
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
428
+ if (node.nodeType === Node.TEXT_NODE) out += (node as Text).data;
429
+ else if ((node as Element).tagName === 'BR') out += ' ';
430
+ }
431
+ return normalize(out);
432
+ }
433
+
434
+ /** A run's text with its line breaks — `textContent` would drop every `<br>`. */
435
+ export function runText(el: HTMLElement): string {
436
+ return segmentsText(readSegments(el));
437
+ }
438
+
439
+ const MARK_TAGS: Record<string, Mark> = {
440
+ STRONG: 'bold',
441
+ B: 'bold',
442
+ EM: 'italic',
443
+ I: 'italic',
444
+ CODE: 'code',
445
+ };
446
+
447
+ const CARET_ATTR = 'data-od-caret';
448
+
449
+ /**
450
+ * A `<br>` that ends a block draws no line of its own, so a break typed at the
451
+ * very end would be invisible and the caret would have nowhere to go. A second
452
+ * one holds the new line open; it is ours, and nothing reads it back.
453
+ */
454
+ function isCaretBreak(node: Node): boolean {
455
+ return node instanceof Element && node.hasAttribute(CARET_ATTR);
456
+ }
457
+
458
+ /** The run's characters in order: its text nodes and its line breaks. */
459
+ function units(run: HTMLElement): Node[] {
460
+ const out: Node[] = [];
461
+ const walker = document.createTreeWalker(run, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT, {
462
+ acceptNode: (node) =>
463
+ node.nodeType === Node.TEXT_NODE ||
464
+ ((node as Element).tagName === 'BR' && !isCaretBreak(node))
465
+ ? NodeFilter.FILTER_ACCEPT
466
+ : NodeFilter.FILTER_SKIP,
467
+ });
468
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) out.push(node);
469
+ return out;
470
+ }
471
+
472
+ function unitLength(node: Node): number {
473
+ return node.nodeType === Node.TEXT_NODE ? (node as Text).data.length : 1;
474
+ }
475
+
476
+ export function runLength(run: HTMLElement): number {
477
+ return units(run).reduce((total, node) => total + unitLength(node), 0);
478
+ }
479
+
480
+ /** The run as it stands on the page, formatting included. */
481
+ export function readSegments(el: HTMLElement): Segment[] {
482
+ const out: Segment[] = [];
483
+ for (const node of units(el)) {
484
+ const segment: Segment = {
485
+ text: node.nodeType === Node.TEXT_NODE ? (node as Text).data : '\n',
486
+ };
487
+ for (let at = node.parentElement; at && at !== el; at = at.parentElement) {
488
+ const mark = MARK_TAGS[at.tagName];
489
+ if (mark) segment[mark] = true;
490
+ if (at.tagName === 'A' && !segment.href) {
491
+ const href = at.getAttribute('href');
492
+ if (href) segment.href = href;
493
+ }
494
+ }
495
+ out.push(segment);
496
+ }
497
+ return mergeSegments(out);
498
+ }
499
+
500
+ function wrap(node: Node, tag: string): Node {
501
+ const el = document.createElement(tag);
502
+ el.appendChild(node);
503
+ return el;
504
+ }
505
+
506
+ /** A piece's text as nodes: in a run that does not keep whitespace, each `'\n'` is a `<br>`. */
507
+ function textNodes(text: string, pre: boolean): Node {
508
+ if (pre || !text.includes('\n')) return document.createTextNode(text);
509
+ const fragment = document.createDocumentFragment();
510
+ text.split('\n').forEach((line, at) => {
511
+ if (at > 0) fragment.appendChild(document.createElement('br'));
512
+ if (line !== '') fragment.appendChild(document.createTextNode(line));
513
+ });
514
+ return fragment;
515
+ }
516
+
517
+ export function writeSegments(el: HTMLElement, segments: Segment[]): void {
518
+ const pre = getComputedStyle(el).whiteSpace.startsWith('pre');
519
+ const merged = mergeSegments(segments);
520
+ el.replaceChildren(
521
+ ...merged.map((segment) => {
522
+ let node: Node = textNodes(segment.text, pre);
523
+ if (segment.code) node = wrap(node, 'code');
524
+ if (segment.italic) node = wrap(node, 'em');
525
+ if (segment.bold) node = wrap(node, 'strong');
526
+ if (segment.href) {
527
+ node = wrap(node, 'a');
528
+ (node as HTMLAnchorElement).setAttribute('href', segment.href);
529
+ }
530
+ return node;
531
+ }),
532
+ );
533
+ if (!pre && segmentsText(merged).endsWith('\n')) {
534
+ const hold = document.createElement('br');
535
+ hold.setAttribute(CARET_ATTR, '');
536
+ el.appendChild(hold);
537
+ }
538
+ }
539
+
540
+ /** Every run's segments — what undo and Escape put back. */
541
+ export function snapshotRuns(runs: Run[]): Segment[][] {
542
+ return runs.map((run) => readSegments(run.el));
543
+ }
544
+
545
+ export function restoreRuns(runs: Run[], snapshot: Segment[][]): void {
546
+ runs.forEach((run, at) => {
547
+ writeSegments(run.el, snapshot[at] ?? []);
548
+ });
549
+ }
550
+
551
+ export function isFormatted(segments: Segment[]): boolean {
552
+ return segments.some((segment) => segment.bold || segment.italic || segment.code || segment.href);
553
+ }
554
+
555
+ /** The segments to send, cleaned the way `cleanRun` cleans the text. */
556
+ export function cleanSegments(segments: Segment[], expected: string): Segment[] {
557
+ const unbreak = !expected.includes(' ');
558
+ const out = segments.map((segment) => ({
559
+ ...segment,
560
+ text: unbreak ? segment.text.replace(/ /g, ' ') : segment.text,
561
+ }));
562
+ if (expected === expected.trim()) {
563
+ // A break at either end of a run draws nothing a reader could see.
564
+ const first = out[0];
565
+ if (first) out[0] = { ...first, text: first.text.trimStart() };
566
+ const last = out[out.length - 1];
567
+ if (last) out[out.length - 1] = { ...last, text: last.text.trimEnd() };
568
+ }
569
+ return mergeSegments(out);
570
+ }
571
+
572
+ export function isRunChanged(run: Run): boolean {
573
+ return (
574
+ isRunDirty(runText(run.el), run.expected) ||
575
+ formatSignature(readSegments(run.el)) !== formatSignature(run.expectedSegments)
576
+ );
577
+ }
578
+
579
+ /**
580
+ * What to send for a run. Non-breaking spaces are the browser's, not the
581
+ * author's — contenteditable inserts them for any space it fears would
582
+ * collapse. Whitespace at the edges is dropped only when the source run had
583
+ * none: a JSX text run is stored trimmed, and its indentation is not part of it.
584
+ */
585
+ export function cleanRun(current: string, expected: string): string {
586
+ const text = expected.includes(' ') ? current : current.replace(/ /g, ' ');
587
+ return expected === expected.trim() ? text.trim() : text;
588
+ }
589
+
590
+ /**
591
+ * A space the layout would collapse — at either end of the run, or after
592
+ * another space — takes no width, so the browser snaps the caret back over it
593
+ * and the next character lands before it. Browsers keep such a space as a
594
+ * non-breaking one while editing; `cleanRun` turns it back on the way out.
595
+ */
596
+ export function holdSpaces(text: string): string {
597
+ let out = '';
598
+ for (let at = 0; at < text.length; at++) {
599
+ const char = text[at] as string;
600
+ const collapsible =
601
+ char === ' ' && (at === 0 || at === text.length - 1 || /\s/.test(out[at - 1] ?? ''));
602
+ out += collapsible ? ' ' : char;
603
+ }
604
+ return out;
605
+ }
606
+
607
+ export function isRunDirty(current: string, expected: string): boolean {
608
+ return normalize(cleanRun(current, expected)) !== normalize(expected);
609
+ }
610
+
611
+ export function runOf(node: Node | null, clone: HTMLElement): HTMLElement | null {
612
+ const el = node instanceof Element ? node : (node?.parentElement ?? null);
613
+ const run = el?.closest<HTMLElement>(`[${RUN_ATTR}]`) ?? null;
614
+ return run && clone.contains(run) ? run : null;
615
+ }
616
+
617
+ /** Character offset of a DOM point within a run, a line break counting as one. */
618
+ function offsetIn(run: HTMLElement, container: Node, offset: number): number {
619
+ const point = document.createRange();
620
+ point.setStart(container, offset);
621
+ point.collapse(true);
622
+ let total = 0;
623
+ for (const node of units(run)) {
624
+ if (node === container) return total + offset;
625
+ const parent = node.parentNode;
626
+ if (!parent) continue;
627
+ const index = Array.prototype.indexOf.call(parent.childNodes, node) as number;
628
+ // Wholly before the point: its end is at or before it.
629
+ if (point.comparePoint(parent, index + 1) > 0) break;
630
+ total += unitLength(node);
631
+ }
632
+ return total;
633
+ }
634
+
635
+ export function placeCaret(run: HTMLElement, offset: number): void {
636
+ const selection = window.getSelection();
637
+ if (!selection) return;
638
+ let remaining = offset;
639
+ for (const node of units(run)) {
640
+ const length = unitLength(node);
641
+ if (node.nodeType === Node.TEXT_NODE && remaining <= length) {
642
+ selection.collapse(node, remaining);
643
+ return;
644
+ }
645
+ if (node.nodeType !== Node.TEXT_NODE && remaining === 0) {
646
+ const parent = node.parentNode as Node;
647
+ selection.collapse(parent, Array.prototype.indexOf.call(parent.childNodes, node));
648
+ return;
649
+ }
650
+ remaining -= length;
651
+ }
652
+ // Past the last character: before the line-holding break, if there is one,
653
+ // so the caret sits on the new empty line.
654
+ const hold = run.querySelector(`[${CARET_ATTR}]`);
655
+ if (hold?.parentNode) {
656
+ selection.collapse(
657
+ hold.parentNode,
658
+ Array.prototype.indexOf.call(hold.parentNode.childNodes, hold),
659
+ );
660
+ return;
661
+ }
662
+ selection.collapse(run, run.childNodes.length);
663
+ }
664
+
665
+ type DomRange = {
666
+ startContainer: Node;
667
+ startOffset: number;
668
+ endContainer: Node;
669
+ endOffset: number;
670
+ };
671
+
672
+ /**
673
+ * The run a range acts on, and its character offsets within that run. A
674
+ * range that spills past one run — select-all, or a selection dragged over a
675
+ * piece of markup — is narrowed to it, leaving the markup alone. A range that
676
+ * touches two runs has no one place in source it could be written back to.
677
+ */
678
+ export function locate(
679
+ clone: HTMLElement,
680
+ range: DomRange,
681
+ ): { run: HTMLElement; from: number; to: number } | null {
682
+ let run = runOf(range.startContainer, clone);
683
+ if (!run || runOf(range.endContainer, clone) !== run) {
684
+ const live = document.createRange();
685
+ live.setStart(range.startContainer, range.startOffset);
686
+ live.setEnd(range.endContainer, range.endOffset);
687
+ const touched = Array.from(clone.querySelectorAll<HTMLElement>(`[${RUN_ATTR}]`)).filter(
688
+ (candidate) => live.intersectsNode(candidate),
689
+ );
690
+ if (touched.length !== 1) return null;
691
+ run = touched[0] as HTMLElement;
692
+ }
693
+ const length = runLength(run);
694
+ const start = run.contains(range.startContainer)
695
+ ? offsetIn(run, range.startContainer, range.startOffset)
696
+ : 0;
697
+ const end = run.contains(range.endContainer)
698
+ ? offsetIn(run, range.endContainer, range.endOffset)
699
+ : length;
700
+ return start <= end ? { run, from: start, to: end } : { run, from: end, to: start };
701
+ }
702
+
703
+ /** Replaces the text a range covers with `text`. Returns false, changing nothing, when it cannot. */
704
+ export function replaceInRun(clone: HTMLElement, range: DomRange, text: string): boolean {
705
+ const at = locate(clone, range);
706
+ if (!at) return false;
707
+ const { run, from, to } = at;
708
+ let next = spliceSegments(readSegments(run), from, to, text);
709
+ if (!getComputedStyle(run).whiteSpace.startsWith('pre')) next = mapSegmentText(next, holdSpaces);
710
+ writeSegments(run, next);
711
+ placeCaret(run, from + text.length);
712
+ return true;
713
+ }
714
+
715
+ export function selectInRun(run: HTMLElement, from: number, to: number): void {
716
+ const selection = window.getSelection();
717
+ if (!selection) return;
718
+ placeCaret(run, from);
719
+ const anchor = { node: selection.anchorNode, offset: selection.anchorOffset };
720
+ placeCaret(run, to);
721
+ const focus = { node: selection.focusNode, offset: selection.focusOffset };
722
+ if (anchor.node && focus.node) {
723
+ selection.setBaseAndExtent(anchor.node, anchor.offset, focus.node, focus.offset);
724
+ }
725
+ }
726
+
727
+ /** Puts the caret where the reader clicked, and selects the word there on a double-click. */
728
+ export function focusAt(
729
+ clone: HTMLElement,
730
+ point: { x: number; y: number } | null,
731
+ selectWord: boolean,
732
+ ): void {
733
+ clone.focus({ preventScroll: true });
734
+ const selection = window.getSelection();
735
+ if (!selection) return;
736
+ if (point) {
737
+ const range = caretRangeAt(point.x, point.y);
738
+ if (range && runOf(range.startContainer, clone)) {
739
+ selection.removeAllRanges();
740
+ selection.addRange(range);
741
+ const modifiable = selection as Selection & {
742
+ modify?: (alter: string, direction: string, granularity: string) => void;
743
+ };
744
+ if (selectWord && typeof modifiable.modify === 'function') {
745
+ modifiable.modify('move', 'backward', 'word');
746
+ modifiable.modify('extend', 'forward', 'word');
747
+ }
748
+ return;
749
+ }
750
+ }
751
+ const runs = clone.querySelectorAll<HTMLElement>(`[${RUN_ATTR}]`);
752
+ const last = runs[runs.length - 1];
753
+ if (last) placeCaret(last, runLength(last));
754
+ }
755
+
756
+ function caretRangeAt(x: number, y: number): Range | null {
757
+ const doc = document as Document & {
758
+ caretRangeFromPoint?: (x: number, y: number) => Range | null;
759
+ caretPositionFromPoint?: (x: number, y: number) => { offsetNode: Node; offset: number } | null;
760
+ };
761
+ if (typeof doc.caretPositionFromPoint === 'function') {
762
+ const position = doc.caretPositionFromPoint(x, y);
763
+ if (!position) return null;
764
+ const range = document.createRange();
765
+ range.setStart(position.offsetNode, position.offset);
766
+ range.collapse(true);
767
+ return range;
768
+ }
769
+ return doc.caretRangeFromPoint?.(x, y) ?? null;
770
+ }