svelte-rtf-editor 1.11.0 → 1.13.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.
@@ -11,6 +11,10 @@
11
11
  * `content`. Default: false. Give each document its own storageKey.
12
12
  * storageKey — localStorage key for auto-save. Default: 'ink-editor-content'.
13
13
  * showToolbar — Show the formatting toolbar. Default: true.
14
+ * stickyToolbar — Keep the toolbar in sight while a long document is scrolled: it
15
+ * stays at the top of the window, or of the scrolling element the
16
+ * editor is in. Default: true. Under a header of your own that stays
17
+ * too, set the CSS variable --ink-toolbar-top to its height.
14
18
  * showStatusBar — Show the word/char count status bar. Default: true.
15
19
  * minHeight — CSS min-height of the editing area. Default: '40vh'.
16
20
  * readonly — If true, editor is not editable. Default: false.
@@ -30,13 +34,22 @@
30
34
  * maxRtfBytes — The largest RTF file Import reads. Default: 52428800 (50 MB);
31
35
  * 0 reads any size.
32
36
  * fontFamily — Font for the document, both on screen and in the RTF.
33
- * Default: DEFAULT_FONT_FAMILY (rtf-writer.ts).
37
+ * Given a CSS list ('Segoe UI, Selawik, sans-serif'), the first
38
+ * family is the font, and the rest is what a screen without it
39
+ * shows. Default: DEFAULT_FONT_FAMILY (rtf-writer.ts).
34
40
  * fontSize — Body text size in points, both on screen and in the RTF.
35
41
  * Headings scale from it. Default: 12.
36
42
  * fontSizes — The sizes, in points, the toolbar's size list offers for the
37
43
  * selected text. The body size is always among them. An empty
38
44
  * list takes the size list off the toolbar.
39
45
  * Default: 8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 36.
46
+ * fonts — The fonts the toolbar's font list offers for the selected text,
47
+ * beside the document's own: names ('Calibri'), or CSS lists whose
48
+ * first family is the name ('Calibri, Carlito, sans-serif'). Text
49
+ * in one of them is written in it to the RTF and read back in it;
50
+ * any other font is taken off HTML as it comes in, set or pasted.
51
+ * Default: none: there is no font list, and no font but the
52
+ * document's is let in.
40
53
  * keepAttributes — `data-` attributes the application's documents carry, which
41
54
  * the editor leaves on their elements: a mark on a paragraph that
42
55
  * the application reads back (`data-section="2"`). Every other
@@ -64,6 +77,12 @@
64
77
  * focus() — Focuses the editor.
65
78
  * exportFile(format) — Downloads as 'html', 'md', or 'rtf'.
66
79
  * importRtf() — Opens the file picker to import an RTF file.
80
+ * setFontSize(points) — Sets the size of the selected text, or of what is typed next.
81
+ * setFont(name) — Sets the font of the selected text, or of what is typed next, to
82
+ * one of `fonts`; '' or the document font's name sets it back.
83
+ * clearFormatting() — Takes bold, italic, underline, strike, color, size and font off
84
+ * the selected text. Headings, lists, links, alignment, indents and
85
+ * the application's own marks stay.
67
86
  */
68
87
 
69
88
  import { onMount } from 'svelte';
@@ -71,13 +90,17 @@
71
90
  import Modal from './Modal.svelte';
72
91
  import ImageOverlay from './ImageOverlay.svelte';
73
92
  import { htmlToMarkdown, downloadFile } from '../utils.js';
74
- import { keptMarks, pasteNotes, removeWordHidden, sanitizedNodes, sanitizeTree, type PasteNotes } from '../sanitize.js';
93
+ import { keptMarks, pasteHasWords, pasteNotes, pasteWithoutFrames, removeWordHidden, sanitizedNodes, sanitizeTree, type PasteNotes } from '../sanitize.js';
94
+ import { givePastedPictures, pastePictures, type PastePictures } from '../paste-pictures.js';
75
95
  import { readRtfFile, DEFAULT_MAX_RTF_BYTES } from '../rtf-parser.js';
76
96
  import {
77
97
  htmlToRtf,
78
98
  estimateRtfBytes,
79
99
  isSafeLinkUrl,
100
+ linkTarget,
80
101
  cssFontFamily,
102
+ fontChoices,
103
+ fontKey,
81
104
  normalizeFontSize,
82
105
  DEFAULT_FONT_FAMILY,
83
106
  DEFAULT_FONT_SIZE
@@ -117,6 +140,7 @@
117
140
  autosave?: boolean;
118
141
  storageKey?: string;
119
142
  showToolbar?: boolean;
143
+ stickyToolbar?: boolean;
120
144
  showStatusBar?: boolean;
121
145
  minHeight?: string;
122
146
  readonly?: boolean;
@@ -129,6 +153,8 @@
129
153
  fontFamily?: string;
130
154
  fontSize?: number;
131
155
  fontSizes?: number[];
156
+ /** The fonts offered for text, beside the document's own; none unless given. */
157
+ fonts?: string[];
132
158
  /** `data-` attributes of the application's own, kept on HTML that is set or pasted. */
133
159
  keepAttributes?: string[];
134
160
  /** Class names of the application's own, kept the same way. */
@@ -145,6 +171,9 @@
145
171
  */
146
172
  const EMPTY_DOCUMENT = '<p><br></p>';
147
173
 
174
+ /** The kinds of block the toolbar's list offers. */
175
+ const BLOCK_CHOICES = new Set(['p', 'h1', 'h2', 'h3', 'blockquote', 'pre']);
176
+
148
177
  /** The sizes, in points, the toolbar's size list offers unless `fontSizes` says otherwise. */
149
178
  const DEFAULT_FONT_SIZES = [8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 36];
150
179
  const NO_KEPT_ATTRIBUTES: string[] = [];
@@ -156,6 +185,7 @@
156
185
  autosave = false,
157
186
  storageKey = 'ink-editor-content',
158
187
  showToolbar = true,
188
+ stickyToolbar = true,
159
189
  showStatusBar = true,
160
190
  minHeight = '40vh',
161
191
  readonly = false,
@@ -167,6 +197,7 @@
167
197
  fontFamily = DEFAULT_FONT_FAMILY,
168
198
  fontSize = DEFAULT_FONT_SIZE,
169
199
  fontSizes = DEFAULT_FONT_SIZES,
200
+ fonts = NO_KEPT_ATTRIBUTES,
170
201
  keepAttributes = NO_KEPT_ATTRIBUTES,
171
202
  keepClasses = NO_KEPT_ATTRIBUTES,
172
203
  onchange,
@@ -174,12 +205,15 @@
174
205
  onimport
175
206
  }: Props = $props();
176
207
 
177
- const keptNames = $derived(keptMarks({ keepAttributes, keepClasses }));
208
+ const keptNames = $derived(keptMarks({ keepAttributes, keepClasses, fonts, fontFamily }));
178
209
 
179
210
  // The same font and size go to the screen and to the RTF, so the editor
180
211
  // shows what the receiving system will show.
181
- const rtfOptions = $derived({ fontFamily, fontSize });
212
+ const rtfOptions = $derived({ fontFamily, fontSize, fonts });
182
213
  const screenFontFamily = $derived(cssFontFamily(fontFamily));
214
+ /** The name the document font is looked up by, and the fonts offered beside it. */
215
+ const documentFontKey = $derived(fontKey(screenFontFamily));
216
+ const fontList = $derived(fontChoices(fonts).filter((choice) => choice.key !== documentFontKey));
183
217
  const screenFontSize = $derived(normalizeFontSize(fontSize));
184
218
 
185
219
  // ── Internal state ──
@@ -191,6 +225,8 @@
191
225
  let currentBlock: string = $state('p');
192
226
  /** The size of the text at the caret, in points, for the toolbar. */
193
227
  let currentFontSize: number | null = $state(null);
228
+ /** The font at the selection, by its key: '' for the document font, null where it has more than one. */
229
+ let currentFont: string | null = $state('');
194
230
 
195
231
  let formatState = $state({
196
232
  bold: false,
@@ -235,8 +271,14 @@
235
271
  if (editorEl) {
236
272
  selectedImage = null;
237
273
  documentReplaced();
238
- showDocument(html);
274
+ const shown = showDocument(html);
239
275
  updateCounts();
276
+ if (!shown) {
277
+ // The caller is told, and the editor is empty: see showDocument.
278
+ dropDraft();
279
+ showError(NOT_SHOWN);
280
+ throw new Error(`InkEditor.setHTML: ${NOT_SHOWN.toLowerCase()}`);
281
+ }
240
282
  if (autosave) scheduleAutoSave();
241
283
  }
242
284
  }
@@ -245,21 +287,169 @@
245
287
  * Put HTML from outside in the editor: made safe first, and with a line in every empty
246
288
  * paragraph, so it shows as the blank line the RTF writes for it. The nodes that were checked
247
289
  * are the nodes shown (see sanitizedNodes): the HTML is read once.
290
+ *
291
+ * Returns whether the document is shown. If it could not be made safe it is not shown, and
292
+ * neither is the one before it: the editor is left empty. (A failure here used to go up to
293
+ * whoever called. Given as `content`, there was then no editor at all; given to setHTML, the
294
+ * document before stayed on the screen, where it read as the one just asked for: one
295
+ * patient's report under another's name.)
248
296
  */
249
- function showDocument(html: string): void {
250
- if (!editorEl) return;
297
+ function showDocument(html: string): boolean {
298
+ if (!editorEl) return false;
251
299
  // An id the page already uses outside an editor is not the document's to take: see
252
300
  // sanitize.ts. (Another editor on the page may hold a document with the same ids.)
253
301
  const idTaken = (id: string) => {
254
302
  const owner = document.getElementById(id);
255
303
  return owner !== null && owner.closest('.ink-content') === null;
256
304
  };
257
- editorEl.replaceChildren(...sanitizedNodes(html, document, idTaken, keptNames));
305
+ let nodes: Node[] | null = null;
306
+ try {
307
+ nodes = sanitizedNodes(html, document, idTaken, keptNames, partLeftOut);
308
+ } catch {
309
+ // Not shown: see above.
310
+ }
311
+ if (nodes === null) editorEl.innerHTML = EMPTY_DOCUMENT;
312
+ else editorEl.replaceChildren(...nodes);
258
313
  for (const p of Array.from(editorEl.querySelectorAll('p'))) {
259
314
  if (p.childNodes.length === 0) p.appendChild(document.createElement('br'));
260
315
  }
316
+ return nodes !== null;
261
317
  }
262
318
 
319
+ /** Said when a document could not be made safe, and so is not shown. */
320
+ const NOT_SHOWN = 'This document could not be shown';
321
+
322
+ /**
323
+ * Said when one element could not be checked and was taken out, with what was in it, while
324
+ * the rest was. (It went without a word: a part of a report gone, and nobody told.)
325
+ */
326
+ const PART_LEFT_OUT = 'A part of this could not be checked, so that part was left out';
327
+ const partLeftOut = () => showError(PART_LEFT_OUT);
328
+
329
+ // ── What the browser brings in, and puts back ──
330
+ // Markup reaches the document in more ways than setHTML and a paste: it is dragged in, and
331
+ // Undo and Redo put back what the browser remembers of a paste, not what the editor made of
332
+ // it. Redo brings back the frame or the form that was taken out, as an element the editor has
333
+ // not seen. It also writes the style it first gave an element back on that element, which
334
+ // the editor has seen and made safe: "position: fixed" was on it again, over the page. So
335
+ // there is no element that, checked once, need not be looked at again: after Undo or Redo
336
+ // the whole document is checked, as it is when it is first shown.
337
+
338
+ /**
339
+ * Make safe the elements `only` accepts. If that cannot be done at all, they are taken out:
340
+ * what could not be checked does not stay. Returns whether it could be done.
341
+ */
342
+ function makeSafe(only: (el: Element) => boolean): boolean {
343
+ if (!editorEl) return true;
344
+ try {
345
+ sanitizeTree(editorEl, only, undefined, keptNames, wordsLeftFor, partLeftOut);
346
+ return true;
347
+ } catch {
348
+ for (const el of Array.from(editorEl.querySelectorAll('*'))) {
349
+ if (el.isConnected && only(el)) el.remove();
350
+ }
351
+ return false;
352
+ }
353
+ }
354
+
355
+ /**
356
+ * Make the whole document safe again: after Undo or Redo, and after a paste or a drop the
357
+ * editor was not told of. What a paste was tidied of, Redo also puts back, and it is taken
358
+ * off again. A document that cannot be checked is not shown, as in showDocument, and the
359
+ * draft is left as it was last kept: that one was checked, and it is the writer's work.
360
+ * Returns whether the document is shown.
361
+ */
362
+ function checkDocument(): boolean {
363
+ if (!editorEl) return true;
364
+ try {
365
+ sanitizeTree(editorEl, undefined, undefined, keptNames, wordsLeftFor, partLeftOut);
366
+ } catch {
367
+ editorEl.innerHTML = EMPTY_DOCUMENT;
368
+ documentReplaced();
369
+ clearTimeout(saveTimer);
370
+ showError(NOT_SHOWN);
371
+ return false;
372
+ }
373
+ // (Only where the style is not the one it was left with: each of these is measured.)
374
+ tidySpacing(
375
+ (el) => broughtIn.has(el) && broughtIn.get(el)!.style !== el.getAttribute('style'),
376
+ (el) => broughtIn.get(el)?.own ?? false
377
+ );
378
+ return true;
379
+ }
380
+
381
+ /**
382
+ * The words left in the document where an element was taken out of it: a button's, a text
383
+ * box's. The browser's history knows nothing of them. Undo takes the paste out and leaves
384
+ * them, and Redo puts the button back beside them, to be taken out again: its words were
385
+ * then in the document twice, and three times after the next Redo. So where an element comes
386
+ * back whose words are still there as they were left, those go, and the ones just left in
387
+ * its place stay.
388
+ *
389
+ * (The elements are held here, not looked up in a WeakMap. An element that is out of the
390
+ * document, with nothing but the browser's history holding it, is given a new object by
391
+ * WebKit when it comes back: a WeakMap had forgotten it, and Safari had the words twice.
392
+ * The history holds the elements as long anyway; these go when the document is replaced.)
393
+ */
394
+ const wordsLeft = new Map<Element, { node: Text; text: string }>();
395
+
396
+ function wordsLeftFor(el: Element, node: Text): void {
397
+ const earlier = wordsLeft.get(el);
398
+ // (Words that have been typed in since are the writer's own, and stay.)
399
+ if (earlier && earlier.node !== node && earlier.node.isConnected && earlier.node.data === earlier.text) earlier.node.remove();
400
+ wordsLeft.set(el, { node, text: node.data });
401
+ leftNow?.push(el);
402
+ }
403
+
404
+ /**
405
+ * Each paste or drop that left such words, with the elements it brought that stayed. Undo of
406
+ * the paste takes those elements out and knows nothing of the words: they stayed in the
407
+ * report, words of a paste the writer had taken back. So where an Undo has just taken out
408
+ * every element a paste brought, the words it left go too, if they are still as they were
409
+ * left. (A paste that brought words and no element that stayed has nothing to be known by,
410
+ * and its words do stay.)
411
+ */
412
+ const pastesWithWords: { stayed: Element[]; left: Element[]; there: boolean }[] = [];
413
+ /** The elements the paste being made safe has left words for. */
414
+ let leftNow: Element[] | null = null;
415
+
416
+ function followPastes(undone: boolean): void {
417
+ for (const paste of pastesWithWords) {
418
+ const there = paste.stayed.some((el) => el.isConnected);
419
+ if (undone && paste.there && !there) {
420
+ for (const el of paste.left) {
421
+ const words = wordsLeft.get(el);
422
+ if (words?.node.isConnected && words.node.data === words.text) words.node.remove();
423
+ }
424
+ }
425
+ paste.there = there;
426
+ }
427
+ }
428
+
429
+ /**
430
+ * Each paste Word's hidden text was taken out of, with the elements that were left empty
431
+ * and went with it. Redo puts the paste back much as the browser first made it: some of the
432
+ * hidden words shown again, and those elements empty. Where the text there is once more that
433
+ * paste, the words are taken out again (see removeWordHidden), and the elements with them.
434
+ */
435
+ const hiddenTaken: { notes: PasteNotes; from: number; came: Set<Element>; emptied: Element[] }[] = [];
436
+
437
+ function hideAgain(): void {
438
+ for (const paste of hiddenTaken) {
439
+ takeHidden(paste.from, null, paste.notes, (el) => paste.came.has(el));
440
+ const sel = window.getSelection();
441
+ for (const el of paste.emptied) {
442
+ if (!el.isConnected || el.childNodes.length > 0) continue;
443
+ // (Not the one the caret is in: see takeHidden.)
444
+ if (sel?.anchorNode && el.contains(sel.anchorNode)) el.appendChild(document.createElement('br'));
445
+ else el.remove();
446
+ }
447
+ }
448
+ }
449
+
450
+ /** Said when what came in could not be made safe, and so was taken out again. */
451
+ const LEFT_OUT = 'What was put in could not be checked, so it was left out';
452
+
263
453
  export function getMarkdown(): string {
264
454
  if (!editorEl) return '';
265
455
  return htmlToMarkdown(editorEl);
@@ -287,10 +477,8 @@
287
477
  selectedImage = null;
288
478
  documentReplaced();
289
479
  editorEl.innerHTML = EMPTY_DOCUMENT;
290
- clearTimeout(saveTimer);
291
- try { localStorage.removeItem(storageKey); } catch (e) {}
480
+ dropDraft();
292
481
  updateCounts();
293
- lastSaved = '';
294
482
  fireChange();
295
483
  }
296
484
  }
@@ -334,6 +522,16 @@
334
522
  indentUndo = [];
335
523
  pastedOver = null;
336
524
  pastedLoss = null;
525
+ pastedPictures = null;
526
+ commentsBefore = null;
527
+ // (A selection kept from the document before points at nothing in the new one.)
528
+ savedSelection = null;
529
+ dialogSelection = null;
530
+ wordsLeft.clear();
531
+ broughtIn.clear();
532
+ pastesWithWords.length = 0;
533
+ hiddenTaken.length = 0;
534
+ clearUndo = clearRedo = clearPast = null;
337
535
  stopCopyFormat();
338
536
  }
339
537
 
@@ -352,19 +550,76 @@
352
550
  });
353
551
 
354
552
  // ── Selection helpers ──
355
- function saveSelection(): void {
553
+ /** Whether what is selected now, or the caret, is in the document. */
554
+ function selectionInEditor(): boolean {
356
555
  const sel = window.getSelection();
357
- if (sel && sel.rangeCount > 0) {
358
- savedSelection = sel.getRangeAt(0).cloneRange();
359
- }
556
+ return !!editorEl && !!sel && sel.rangeCount > 0 && editorEl.contains(sel.anchorNode) && editorEl.contains(sel.focusNode);
557
+ }
558
+
559
+ /**
560
+ * Keep the selection, to put back when a dialog closes. Only one in the document is kept:
561
+ * with something on the page around the editor selected, the one kept is still the last one
562
+ * that was in the document. (That one was kept in its place, and could not be put back: the
563
+ * link made from the toolbar then went to the top of the document, as its own address.)
564
+ */
565
+ function saveSelection(): void {
566
+ if (!selectionInEditor()) return;
567
+ savedSelection = window.getSelection()!.getRangeAt(0).cloneRange();
360
568
  }
361
569
 
570
+ /**
571
+ * Put the selection back in the document, where it has left it: a dialog or a list of the
572
+ * toolbar took the keyboard. Where the selection is in the document, that is the one to act
573
+ * on, and it is left alone. (The kept one was put back every time, and it was kept only when a
574
+ * dialog opened or a picture went in: after one link, Bold and every other button changed
575
+ * the words of that link, whatever was selected by then.)
576
+ */
362
577
  function restoreSelection(): void {
363
- if (savedSelection) {
364
- const sel = window.getSelection();
365
- sel?.removeAllRanges();
366
- sel?.addRange(savedSelection);
578
+ if (selectionInEditor()) return;
579
+ select(savedSelection);
580
+ }
581
+
582
+ /** Select a range kept earlier, if it is still in the document. Returns whether it was. */
583
+ function select(kept: Range | null): boolean {
584
+ if (!kept || !editorEl?.contains(kept.startContainer) || !editorEl.contains(kept.endContainer)) return false;
585
+ const sel = window.getSelection();
586
+ sel?.removeAllRanges();
587
+ sel?.addRange(kept);
588
+ return true;
589
+ }
590
+
591
+ /**
592
+ * The selection a dialog was opened on, kept apart from the one that follows the document's.
593
+ * (That one moves when the dialog closes: the browser gives the document the keyboard back
594
+ * with a caret of its own at the top, and a picture that was still being read went in there,
595
+ * not where the writer had been.)
596
+ */
597
+ let dialogSelection: Range | null = null;
598
+
599
+ function keepForDialog(): void {
600
+ saveSelection();
601
+ dialogSelection = savedSelection?.cloneRange() ?? null;
602
+ }
603
+
604
+ /** Put back the selection a dialog was opened on, or failing that the last one in the document. */
605
+ function restoreFor(dialog: Range | null): void {
606
+ if (!select(dialog)) restoreSelection();
607
+ }
608
+
609
+ /**
610
+ * Keep the selection whenever it changes in the document, so the one put back is the last one
611
+ * there. (Kept in the one Range, moved along: a new Range for every key pressed would be a
612
+ * thousand of them for the browser to keep up to date with the text.)
613
+ */
614
+ function trackSelection(): void {
615
+ if (!selectionInEditor()) return;
616
+ const range = window.getSelection()!.getRangeAt(0);
617
+ if (!savedSelection) {
618
+ savedSelection = range.cloneRange();
619
+ return;
367
620
  }
621
+ savedSelection.setStart(range.startContainer, range.startOffset);
622
+ savedSelection.setEnd(range.endContainer, range.endOffset);
368
623
  }
369
624
 
370
625
  // ── Font size ──
@@ -512,7 +767,7 @@
512
767
  if (autosave) scheduleAutoSave();
513
768
  }
514
769
 
515
- /** The size of the text at the selection, for the toolbar: null where it starts and ends in different sizes. */
770
+ /** The size of the text at the selection, for the toolbar: null where the text selected is in more than one. */
516
771
  function sizeAtSelection(): number | null {
517
772
  if (pendingSize !== null) return pendingSize;
518
773
  const selection = window.getSelection();
@@ -530,7 +785,137 @@
530
785
  const first = start ? shownSize(start) : null;
531
786
  if (range.collapsed) return first;
532
787
  const end = holder(range.endContainer, range.endOffset, true);
533
- return end && shownSize(end) === first ? first : null;
788
+ if (!end || shownSize(end) !== first) return null;
789
+ // The same at both ends, and another in between: the list shows none, as for two.
790
+ return throughout(range, (el) => shownSize(el) ?? 0) === null ? null : first;
791
+ }
792
+
793
+ // ── Font ──
794
+ // The browser's own command does all of it: it writes <font face="…"> around the selected
795
+ // text, cuts a font that is there already in two rather than putting one inside another,
796
+ // and keeps the font for what is typed next at a caret. So a change of font is undone and
797
+ // redone with everything else. Which fonts there may be is the application's to say
798
+ // (`fonts`): the sanitizer takes any other off what comes in.
799
+
800
+ /** The font chosen at a caret and not yet typed in: the document has no element to show it by. */
801
+ let pendingFont: string | null = null;
802
+
803
+ /**
804
+ * Set the font of the selected text; with nothing selected, of what is typed next. The name
805
+ * is one of `fonts`; '' or the document font's own name sets the text back to the document
806
+ * font. A font that is not offered is not set. Also what the toolbar's font list calls.
807
+ */
808
+ export function setFont(name: string | null): void {
809
+ if (readonly || !editorEl) return;
810
+ const key = fontKey(name);
811
+ const choice = fontList.find((font) => font.key === key);
812
+ if (key !== '' && key !== documentFontKey && !choice) return;
813
+ restoreSelection();
814
+ editorEl.focus();
815
+ const selection = window.getSelection();
816
+ if (!selection || selection.rangeCount === 0 || !selectionInEditor()) return;
817
+ const wanted = choice?.key ?? '';
818
+ // Nothing to change: no step is made that would undo to the same thing.
819
+ if (fontAtSelection() === wanted) {
820
+ updateToolbarState();
821
+ return;
822
+ }
823
+ // (Given the document font as the screen has it, Chromium and Safari take the font off
824
+ // the text; Firefox writes it, which the writer and the font list read as no font.)
825
+ document.execCommand('fontName', false, choice ? choice.css : screenFontFamily);
826
+ // With text selected the font is on it now. At a caret it waits for the typing.
827
+ pendingFont = selection.isCollapsed ? wanted : null;
828
+ updateToolbarState();
829
+ }
830
+
831
+ /** The font an element's text is in, by its key: '' for the document font, or a font that is not offered. */
832
+ function fontOfElement(el: Element | null): string {
833
+ for (let at = el; at && at !== editorEl; at = at.parentElement) {
834
+ const key = fontKey((at as HTMLElement).style?.fontFamily || (at.tagName === 'FONT' ? at.getAttribute('face') : ''));
835
+ if (key) return fontList.some((font) => font.key === key) ? key : '';
836
+ }
837
+ return '';
838
+ }
839
+
840
+ /** The font of the text at the selection, for the toolbar: null where the text selected is in more than one. */
841
+ function fontAtSelection(): string | null {
842
+ if (pendingFont !== null) return pendingFont;
843
+ const selection = window.getSelection();
844
+ if (!editorEl || !selection || selection.rangeCount === 0) return '';
845
+ const range = selection.getRangeAt(0);
846
+ if (!editorEl.contains(range.startContainer)) return '';
847
+ if (range.collapsed) {
848
+ const at = range.startContainer;
849
+ return fontOfElement(at.nodeType === Node.ELEMENT_NODE ? (at as Element) : at.parentElement);
850
+ }
851
+ const font = throughout(range, fontOfElement);
852
+ return font === undefined ? '' : font;
853
+ }
854
+
855
+ /** Lists, tables and the document itself: white space between their parts is not text one sees. */
856
+ const HOLDS_BLOCKS = new Set(['UL', 'OL', 'TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TR']);
857
+
858
+ /**
859
+ * What all the text selected has in common, as `of` reads it from the element a text is in:
860
+ * its font, its size. null where two texts differ, so that the toolbar's list shows none
861
+ * rather than the one the selection happens to start in. undefined where no text is selected.
862
+ *
863
+ * From the first text selected to the last: a selection often starts at the end of the text
864
+ * before it (Safari leaves it there after the command), which is in another font.
865
+ */
866
+ function throughout<T>(range: Range, of: (el: Element) => T): T | null | undefined {
867
+ const first = textAtEdge(range, false);
868
+ const last = textAtEdge(range, true);
869
+ if (!editorEl || !first || !last) return undefined;
870
+ if (first !== last && !(first.compareDocumentPosition(last) & Node.DOCUMENT_POSITION_FOLLOWING)) return undefined;
871
+ const walker = document.createTreeWalker(editorEl, NodeFilter.SHOW_TEXT);
872
+ walker.currentNode = first;
873
+ let seen: Element | null = null;
874
+ let value: T | undefined;
875
+ for (let text: Text | null = first; text; text = walker.nextNode() as Text | null) {
876
+ const parent = text.parentElement;
877
+ const unseen = (parent === editorEl || HOLDS_BLOCKS.has(parent?.tagName ?? '')) && text.data.trim() === '';
878
+ if (parent && parent !== seen && text.data !== '' && !unseen) {
879
+ const here = of(parent);
880
+ if (seen && here !== value) return null;
881
+ value = here;
882
+ seen = parent;
883
+ }
884
+ if (text === last) break;
885
+ }
886
+ return value;
887
+ }
888
+
889
+ /** The first text a range has a character of, or the last. */
890
+ function textAtEdge(range: Range, last: boolean): Text | null {
891
+ if (!editorEl) return null;
892
+ const walker = document.createTreeWalker(editorEl, NodeFilter.SHOW_TEXT);
893
+ const node = last ? range.endContainer : range.startContainer;
894
+ const offset = last ? range.endOffset : range.startOffset;
895
+ const step = () => (last ? walker.previousNode() : walker.nextNode()) as Text | null;
896
+ let text: Text | null;
897
+ if (node.nodeType === Node.TEXT_NODE) {
898
+ walker.currentNode = node;
899
+ const inside = last ? offset > 0 : offset < (node as Text).data.length;
900
+ text = inside ? (node as Text) : step();
901
+ } else {
902
+ // From the point between two children: into the child on the range's side of it, or
903
+ // on from the element where it has none there.
904
+ const child = node.childNodes[last ? offset - 1 : offset];
905
+ if (child) {
906
+ let edge: Node = child;
907
+ if (last) while (edge.lastChild) edge = edge.lastChild;
908
+ walker.currentNode = edge;
909
+ text = edge.nodeType === Node.TEXT_NODE ? (edge as Text) : step();
910
+ } else {
911
+ let edge: Node = node;
912
+ if (!last) while (edge.lastChild) edge = edge.lastChild;
913
+ walker.currentNode = edge;
914
+ text = step();
915
+ }
916
+ }
917
+ while (text && text.data === '') text = step();
918
+ return text && range.intersectsNode(text) ? text : null;
534
919
  }
535
920
 
536
921
  /** The sizes the list offers: those asked for, and always the body size. */
@@ -542,6 +927,10 @@
542
927
 
543
928
  // ── Exec command ──
544
929
  function exec(cmd: string, value: string | null = null): void {
930
+ if (cmd === 'removeFormat') {
931
+ clearFormatting();
932
+ return;
933
+ }
545
934
  restoreSelection();
546
935
  editorEl?.focus();
547
936
  // Color commands require an actual text selection — a collapsed cursor
@@ -559,12 +948,297 @@
559
948
  hangAtCaret();
560
949
  return;
561
950
  }
562
- if (cmd === 'undo' && undoIndent()) return;
951
+ if (cmd === 'undo' && (undoIndent() || undoClear())) return;
952
+ if (cmd === 'redo' && redoClear()) return;
563
953
  document.execCommand(cmd, false, value ?? undefined);
564
954
  if (cmd === 'undo' || cmd === 'redo') afterHistory();
565
955
  updateToolbarState();
566
956
  }
567
957
 
958
+ // ── Clear formatting ──
959
+ // The browser's own command does this, and each browser does it differently. Chromium and
960
+ // Safari take a paragraph's alignment and first-line indent with its color; Firefox leaves
961
+ // the color on the paragraph, and takes out the element an application's mark is on; Safari
962
+ // leaves a size where it is. So the command is used for what only it can do, which is to
963
+ // take the <b>, <i> and <font> elements out with an entry in the browser's own history
964
+ // (taken out by the editor instead, the next Undo in Safari empties the document). What is
965
+ // written on the elements is the editor's to change: before the command, the looks of the
966
+ // text are taken off every element whose text is all selected, and after it, whatever the
967
+ // command took off that is not a look of the text is written back.
968
+
969
+ /** What is written on an element for the looks of its text. */
970
+ const CHARACTER_STYLES = [
971
+ 'color', 'background', 'background-color', 'font', 'font-family', 'font-size', 'font-weight', 'font-style',
972
+ 'font-variant', 'font-stretch', 'text-decoration', 'text-decoration-line', 'text-decoration-color',
973
+ 'text-decoration-style', 'text-decoration-thickness', 'letter-spacing', 'text-transform', 'text-shadow',
974
+ 'vertical-align', '-webkit-text-stroke-width', '-webkit-text-fill-color'
975
+ ];
976
+ const isLook = (prop: string) =>
977
+ CHARACTER_STYLES.includes(prop) || /^(font|text-decoration|background|-webkit-text)-/.test(prop);
978
+ /** In a table these are the table's design, not the looks of its text. */
979
+ const TABLE_PARTS = 'table, thead, tbody, tfoot, tr, td, th, col, colgroup';
980
+ const TABLE_DESIGN = new Set(['background', 'background-color', 'vertical-align']);
981
+ /** The attributes that carry looks: `style`, and on a <font> its own. */
982
+ const LOOKS = ['style', 'color', 'size', 'face'] as const;
983
+ type Looks = Record<(typeof LOOKS)[number], string | null>;
984
+
985
+ /** One Clear formatting: what was written on each element before and after, to put back. */
986
+ interface ClearStep {
987
+ before: Map<Element, Looks>;
988
+ after: Map<Element, Looks>;
989
+ /** The browser's command changed something, and has an entry in its history. */
990
+ native: boolean;
991
+ /** The document as the editor handed it to the command: where the browser's Undo of the command leads back to. */
992
+ pre: string;
993
+ /** The document as the step left it. */
994
+ cleared: string;
995
+ /** The document as it is now, the step done or undone: it is undone, or redone, only from there. */
996
+ html: string;
997
+ }
998
+ let clearUndo: ClearStep | null = null;
999
+ let clearRedo: ClearStep | null = null;
1000
+ /** The last one made, also after more was typed: the browser's Undo may yet lead back to it. */
1001
+ let clearPast: ClearStep | null = null;
1002
+ /** The input events of the editor's own commands, while it clears: what they leave is not yet the document. */
1003
+ let clearing = false;
1004
+
1005
+ /**
1006
+ * After the browser's own Undo. A Clear formatting is the editor's to undo only while nothing
1007
+ * else has been done. After that the browser undoes its command with everything else, and
1008
+ * knows nothing of what the editor took off the elements: bold was back, and the color was
1009
+ * not. Where its Undo has led back to the document as the command was given it, the rest is
1010
+ * put back here. A step the command left nothing of (a paragraph's color and no more) has no
1011
+ * such place to be led back to: it is the editor's to undo again once the document is as
1012
+ * that step left it, which is when what was typed after it has been undone.
1013
+ */
1014
+ function afterUndoOfClear(): void {
1015
+ const step = clearPast;
1016
+ if (!step || !editorEl || clearing) return;
1017
+ const now = editorEl.innerHTML;
1018
+ if (step.native && step.pre !== step.cleared) {
1019
+ if (now !== step.pre) return;
1020
+ writeLooks(step.before);
1021
+ clearUndo = null;
1022
+ clearRedo = { ...step, html: editorEl.innerHTML };
1023
+ } else if (now === step.cleared) {
1024
+ clearUndo = { ...step, html: now };
1025
+ }
1026
+ }
1027
+
1028
+ const looksOf = (el: Element): Looks => ({
1029
+ style: el.getAttribute('style'),
1030
+ color: el.getAttribute('color'),
1031
+ size: el.getAttribute('size'),
1032
+ face: el.getAttribute('face')
1033
+ });
1034
+
1035
+ function writeLooks(looks: Map<Element, Looks>): void {
1036
+ for (const [el, wanted] of looks) {
1037
+ if (!el.isConnected) continue;
1038
+ for (const name of LOOKS) {
1039
+ if (el.getAttribute(name) === wanted[name]) continue;
1040
+ if (wanted[name] === null) el.removeAttribute(name);
1041
+ else el.setAttribute(name, wanted[name]);
1042
+ }
1043
+ }
1044
+ }
1045
+
1046
+ /** Whether all the text of an element is selected. (One with no text is, if it is in the selection.) */
1047
+ function allSelected(range: Range, el: Element): boolean {
1048
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
1049
+ for (let text = walker.nextNode() as Text | null; text; text = walker.nextNode() as Text | null) {
1050
+ if (text.data === '') continue;
1051
+ if (range.comparePoint(text, 0) !== 0 || range.comparePoint(text, text.data.length) !== 0) return false;
1052
+ }
1053
+ return true;
1054
+ }
1055
+
1056
+ /**
1057
+ * A <span> that is there for the looks of its text and nothing else. The command takes such
1058
+ * a one out whole, in every browser, and its Undo puts it back as it was: it is left to it.
1059
+ */
1060
+ function onlyLooks(el: HTMLElement): boolean {
1061
+ return el.tagName === 'SPAN' && el.attributes.length === 1 && el.style.length > 0 && Array.from(el.style).every(isLook);
1062
+ }
1063
+
1064
+ /** An element that says something of its text other than how it looks: a mark of the application's, a tab. */
1065
+ function isMark(el: HTMLElement): boolean {
1066
+ return (
1067
+ Array.from(el.attributes).some((attr) => !(LOOKS as readonly string[]).includes(attr.name)) ||
1068
+ Array.from(el.style).some((prop) => !isLook(prop))
1069
+ );
1070
+ }
1071
+
1072
+ /** Take the looks of its text off one element: the element stays, and so does its layout. */
1073
+ function plain(el: HTMLElement): void {
1074
+ const tablePart = el.matches(TABLE_PARTS);
1075
+ for (const prop of [...CHARACTER_STYLES, ...Array.from(el.style).filter(isLook)]) {
1076
+ if (tablePart && TABLE_DESIGN.has(prop)) continue;
1077
+ el.style.removeProperty(prop);
1078
+ }
1079
+ if (!el.getAttribute('style')) el.removeAttribute('style');
1080
+ if (el.tagName === 'FONT') for (const name of ['color', 'size', 'face']) el.removeAttribute(name);
1081
+ }
1082
+
1083
+ /**
1084
+ * Take the formatting off the selected text: bold, italic, underline, strike, color, size and
1085
+ * font, wherever it is written. What the text is stays: a heading is still a heading, a list
1086
+ * a list, a link a link, and a paragraph keeps its alignment and its indents. So do the
1087
+ * marks the application named (keepAttributes, keepClasses). Undo puts it back.
1088
+ */
1089
+ export function clearFormatting(): void {
1090
+ if (readonly || !editorEl) return;
1091
+ restoreSelection();
1092
+ editorEl.focus();
1093
+ const sel = window.getSelection();
1094
+ if (!sel || sel.rangeCount === 0 || !selectionInEditor()) return;
1095
+ if (sel.isCollapsed) {
1096
+ // At a caret there is nothing to clear but what was chosen for the words typed next.
1097
+ pendingSize = null;
1098
+ pendingFont = null;
1099
+ document.execCommand('removeFormat');
1100
+ updateToolbarState();
1101
+ return;
1102
+ }
1103
+ // The document changes outside an input event: earlier indent steps no longer undo.
1104
+ indentUndo = [];
1105
+ const range = sel.getRangeAt(0);
1106
+ const touched = Array.from(editorEl.querySelectorAll<HTMLElement>('*')).filter((el) => range.intersectsNode(el));
1107
+ const before = new Map(touched.map((el) => [el, looksOf(el)]));
1108
+ const whole = touched.filter((el) => allSelected(range, el));
1109
+ for (const el of whole) if (!onlyLooks(el)) plain(el);
1110
+ const wanted = new Map(touched.map((el) => [el, el.getAttribute('style')]));
1111
+ const html = editorEl.innerHTML;
1112
+ // An element that says something of its text other than how it looks is not there for the
1113
+ // command to take out: it is the application's mark, or the space a tab takes. Safari
1114
+ // takes out a <span> that has nothing but a style, and Firefox every <span> there is; and
1115
+ // where only some words of a mark are selected, Firefox cuts the mark in two around them.
1116
+ // So each such element is marked for the command as one to keep, which is enough for
1117
+ // Safari; and where one is taken out or cut all the same, the command is taken back and
1118
+ // done again with those elements closed to it. (What is bold inside one of them then
1119
+ // stays bold.)
1120
+ const marks = new Map(touched.filter(isMark).map((el) => [el, el.textContent]));
1121
+ const kept = Array.from(marks.keys());
1122
+ const selected = range.cloneRange();
1123
+ clearing = true;
1124
+ try {
1125
+ let closed = spansAreTakenOut ? kept.filter((el) => el.tagName === 'SPAN') : [];
1126
+ removeFormat(selected, kept, closed);
1127
+ const lost = kept.filter((el) => !el.isConnected || el.textContent !== marks.get(el));
1128
+ if (lost.length > 0) {
1129
+ document.execCommand('undo');
1130
+ if (lost.some((el) => el.tagName === 'SPAN')) spansAreTakenOut = true;
1131
+ closed = Array.from(new Set([...closed, ...lost])).filter((el) => el.isConnected);
1132
+ removeFormat(selected, kept.filter((el) => el.isConnected), closed);
1133
+ }
1134
+ } finally {
1135
+ clearing = false;
1136
+ }
1137
+ const native = editorEl.innerHTML !== html;
1138
+ // What the command took off that is not a look of the text goes back on.
1139
+ const probe = document.createElement('span');
1140
+ for (const el of touched) {
1141
+ if (!el.isConnected) continue;
1142
+ probe.setAttribute('style', wanted.get(el) ?? '');
1143
+ for (const prop of Array.from(probe.style)) {
1144
+ if (isLook(prop) && !(el.matches(TABLE_PARTS) && TABLE_DESIGN.has(prop))) continue;
1145
+ const value = probe.style.getPropertyValue(prop);
1146
+ if (el.style.getPropertyValue(prop) !== value) el.style.setProperty(prop, value, probe.style.getPropertyPriority(prop));
1147
+ }
1148
+ if (!el.getAttribute('style')) el.removeAttribute('style');
1149
+ }
1150
+ // (And a <span> left to the command that it did not take out after all.)
1151
+ for (const el of whole) if (el.isConnected) plain(el);
1152
+ const after = new Map(touched.map((el) => [el, looksOf(el)]));
1153
+ const changed = native || touched.some((el) => LOOKS.some((name) => before.get(el)![name] !== after.get(el)![name]));
1154
+ const cleared = editorEl.innerHTML;
1155
+ clearUndo = clearPast = changed ? { before, after, native, pre: html, cleared, html: cleared } : null;
1156
+ clearRedo = null;
1157
+ updateToolbarState();
1158
+ if (!changed) return;
1159
+ fireChange();
1160
+ if (autosave) scheduleAutoSave();
1161
+ }
1162
+
1163
+ /** Whether this browser's command has been seen to take out a <span> that was to stay. */
1164
+ let spansAreTakenOut = false;
1165
+ /** Written on an element while the command runs, so that it is not one with only a style. */
1166
+ const KEEP_MARK = 'data-ink-keep';
1167
+
1168
+ /**
1169
+ * The browser's command on what was selected, with the elements in `kept` marked to stay and
1170
+ * those in `closed` out of its reach. Where the selection begins or ends inside a closed
1171
+ * element, the command would do nothing at all: it is given the part outside it.
1172
+ */
1173
+ function removeFormat(selected: Range, kept: HTMLElement[], closed: HTMLElement[]): void {
1174
+ const selection = window.getSelection();
1175
+ if (!selection) return;
1176
+ if (closed.length > 0 && selected.startContainer.isConnected && selected.endContainer.isConnected) {
1177
+ const outside = selected.cloneRange();
1178
+ for (const el of closed) {
1179
+ if (el.contains(outside.startContainer)) outside.setStartAfter(el);
1180
+ if (el.contains(outside.endContainer)) outside.setEndBefore(el);
1181
+ }
1182
+ if (outside.collapsed) return;
1183
+ selection.removeAllRanges();
1184
+ selection.addRange(outside);
1185
+ }
1186
+ const was = closed.map((el) => el.getAttribute('contenteditable'));
1187
+ for (const el of kept) el.setAttribute(KEEP_MARK, '');
1188
+ for (const el of closed) el.setAttribute('contenteditable', 'false');
1189
+ document.execCommand('removeFormat');
1190
+ // (Also off the copy the command makes of an element it cuts in two.)
1191
+ for (const el of [...kept, ...Array.from(editorEl?.querySelectorAll(`[${KEEP_MARK}]`) ?? [])]) el.removeAttribute(KEEP_MARK);
1192
+ closed.forEach((el, i) => {
1193
+ if (was[i] === null) el.removeAttribute('contenteditable');
1194
+ else el.setAttribute('contenteditable', was[i]!);
1195
+ });
1196
+ }
1197
+
1198
+ /** Undo the last Clear formatting, if nothing has changed since. */
1199
+ function undoClear(): boolean {
1200
+ const step = clearUndo;
1201
+ clearUndo = null;
1202
+ if (!step || !editorEl || editorEl.innerHTML !== step.html) return false;
1203
+ clearing = true;
1204
+ try {
1205
+ if (step.native) document.execCommand('undo');
1206
+ } finally {
1207
+ clearing = false;
1208
+ }
1209
+ writeLooks(step.before);
1210
+ // (Safari may take the step before back with it, and that may be a change of size.)
1211
+ afterHistory();
1212
+ clearRedo = { ...step, html: editorEl.innerHTML };
1213
+ clearChanged();
1214
+ return true;
1215
+ }
1216
+
1217
+ /** Do it again, if nothing has changed since it was undone. */
1218
+ function redoClear(): boolean {
1219
+ const step = clearRedo;
1220
+ clearRedo = null;
1221
+ if (!step || !editorEl || editorEl.innerHTML !== step.html) return false;
1222
+ // (In the order it was done: the command read the elements as the editor had left them.)
1223
+ writeLooks(step.after);
1224
+ clearing = true;
1225
+ try {
1226
+ if (step.native) document.execCommand('redo');
1227
+ } finally {
1228
+ clearing = false;
1229
+ }
1230
+ writeLooks(step.after);
1231
+ clearUndo = { ...step, html: editorEl.innerHTML };
1232
+ clearChanged();
1233
+ return true;
1234
+ }
1235
+
1236
+ function clearChanged(): void {
1237
+ updateToolbarState();
1238
+ fireChange();
1239
+ if (autosave) scheduleAutoSave();
1240
+ }
1241
+
568
1242
  // ── Indent ──
569
1243
  // Indent and Outdent move the paragraphs the selection touches by half an inch (48px, written
570
1244
  // to RTF as \li720) per press, as margin-left on each paragraph. The browser's own commands are
@@ -1141,6 +1815,7 @@
1141
1815
  // temporarily moved to a toolbar element (e.g. colour picker, select).
1142
1816
  saveSelection();
1143
1817
  currentFontSize = sizeAtSelection();
1818
+ currentFont = fontList.length > 0 ? fontAtSelection() : '';
1144
1819
 
1145
1820
  formatState = {
1146
1821
  bold: document.queryCommandState('bold'),
@@ -1151,8 +1826,7 @@
1151
1826
 
1152
1827
  const block = document.queryCommandValue('formatBlock');
1153
1828
  const normalized = block.replace(/[<>]/g, '').toLowerCase();
1154
- const map: Record<string, string> = { h1: 'h1', h2: 'h2', h3: 'h3', blockquote: 'blockquote', pre: 'pre', p: 'p' };
1155
- currentBlock = map[normalized] || 'p';
1829
+ currentBlock = BLOCK_CHOICES.has(normalized) ? normalized : 'p';
1156
1830
 
1157
1831
  updateCounts();
1158
1832
  }
@@ -1163,11 +1837,48 @@
1163
1837
  */
1164
1838
  function caretMoved(): void {
1165
1839
  pendingSize = null;
1840
+ pendingFont = null;
1166
1841
  updateToolbarState();
1842
+ keepCaretInSight();
1843
+ }
1844
+
1845
+ let headEl: HTMLDivElement | undefined = $state();
1846
+
1847
+ /**
1848
+ * The browser scrolls a caret into the window, and knows nothing of the toolbar that stays
1849
+ * at the top of it: a caret moved up with the keys ends under the toolbar. The page is
1850
+ * scrolled by what the toolbar covers of the caret's line.
1851
+ */
1852
+ function keepCaretInSight(): void {
1853
+ if (!stickyToolbar || !headEl || !editorEl) return;
1854
+ const selection = window.getSelection();
1855
+ if (!selection || selection.rangeCount === 0 || !selectionInEditor()) return;
1856
+ const focus = document.createRange();
1857
+ try {
1858
+ focus.setStart(selection.focusNode!, selection.focusOffset);
1859
+ } catch {
1860
+ return;
1861
+ }
1862
+ const caret = focus.getClientRects()[0];
1863
+ if (!caret) return;
1864
+ const head = headEl.getBoundingClientRect();
1865
+ // Only where the toolbar is over the document, which it is not until the page is scrolled.
1866
+ if (head.bottom <= editorEl.getBoundingClientRect().top) return;
1867
+ const covered = head.bottom + 8 - caret.top;
1868
+ if (covered <= 0 || caret.bottom < head.top) return;
1869
+ for (let at: HTMLElement | null = editorEl.parentElement; at; at = at.parentElement) {
1870
+ const overflow = getComputedStyle(at).overflowY;
1871
+ if ((overflow === 'auto' || overflow === 'scroll') && at.scrollHeight > at.clientHeight) {
1872
+ at.scrollTop -= covered;
1873
+ return;
1874
+ }
1875
+ }
1876
+ window.scrollBy(0, -covered);
1167
1877
  }
1168
1878
 
1169
1879
  /** The editing area was scrolled sideways (a wide table): what is drawn over it moves with it. */
1170
1880
  function contentScrolled(): void {
1881
+ hideLinkHint();
1171
1882
  overlayRef?.reposition();
1172
1883
  placeCopySourceBox();
1173
1884
  }
@@ -1189,7 +1900,7 @@
1189
1900
  // every keystroke: with a few pictures in the document it took a tenth of a second. Each is
1190
1901
  // worked out when the handler asks for it, once, and not at all if it never does.
1191
1902
  const el = editorEl;
1192
- const options = { fontFamily, fontSize };
1903
+ const options = { fontFamily, fontSize, fonts };
1193
1904
  const once = <T,>(read: () => T): (() => T) => {
1194
1905
  let value: { v: T } | null = null;
1195
1906
  return () => (value ??= { v: read() }).v;
@@ -1209,8 +1920,9 @@
1209
1920
  // ── Auto-save ──
1210
1921
  let saveTimer: ReturnType<typeof setTimeout> | undefined;
1211
1922
 
1212
- function autoSaveNow(): void {
1213
- if (!editorEl || !autosave) return;
1923
+ /** Keep the draft in the browser's storage. */
1924
+ function keepDraft(): void {
1925
+ if (!editorEl) return;
1214
1926
  try {
1215
1927
  localStorage.setItem(storageKey, editorEl.innerHTML);
1216
1928
  lastSaved = `Saved ${new Date().toLocaleTimeString()}`;
@@ -1220,6 +1932,35 @@
1220
1932
  // fires so the host app can persist the content itself.
1221
1933
  lastSaved = 'Too large to auto-save in this browser';
1222
1934
  }
1935
+ }
1936
+
1937
+ /**
1938
+ * Forget the draft, and the save that was waiting. (A document that could not be shown left
1939
+ * the draft of the one before it: opened again, the editor showed that one, the report of
1940
+ * the patient before.)
1941
+ */
1942
+ function dropDraft(): void {
1943
+ clearTimeout(saveTimer);
1944
+ try { localStorage.removeItem(storageKey); } catch (e) {}
1945
+ lastSaved = '';
1946
+ }
1947
+
1948
+ function autoSaveNow(): void {
1949
+ if (!editorEl || !autosave) return;
1950
+ keepDraft();
1951
+ onsave?.({ html: editorEl.innerHTML });
1952
+ }
1953
+
1954
+ /**
1955
+ * Ctrl+S: onsave, whether or not drafts are kept. (It went through the auto-save, which does
1956
+ * nothing where `autosave` is off. Since that is the default, the key was taken from the
1957
+ * browser and nothing was saved anywhere: an application that saves from onsave saved nothing.)
1958
+ */
1959
+ function saveNow(): void {
1960
+ if (!editorEl) return;
1961
+ // The save that was waiting is this one.
1962
+ clearTimeout(saveTimer);
1963
+ if (autosave) keepDraft();
1223
1964
  onsave?.({ html: editorEl.innerHTML });
1224
1965
  }
1225
1966
 
@@ -1228,36 +1969,59 @@
1228
1969
  saveTimer = setTimeout(autoSaveNow, 1000);
1229
1970
  }
1230
1971
 
1972
+ /** The kinds of input event that put markup from somewhere else into the document. */
1973
+ const MARKUP_FROM_OUTSIDE = new Set(['insertFromPaste', 'insertFromPasteAsQuotation', 'insertFromDrop', 'insertFromYank']);
1974
+
1231
1975
  // ── Input handler ──
1232
1976
  function handleInput(e?: Event): void {
1233
1977
  placeCopySourceBox();
1234
- if (pastedOver) {
1978
+ const kind = (e as InputEvent | undefined)?.inputType ?? '';
1979
+ const history = kind === 'historyUndo' || kind === 'historyRedo';
1980
+ // (Words dragged from one place in the document to another are first taken out where
1981
+ // they were, which is an input event of its own: what was dropped has not come in yet.)
1982
+ let shown = true;
1983
+ if (pastedOver && kind !== 'deleteByDrag') {
1235
1984
  tidyPasted(pastedOver);
1236
1985
  pastedOver = null;
1237
- }
1986
+ } else if (history || MARKUP_FROM_OUTSIDE.has(kind)) {
1987
+ // Undo and Redo put back what the browser remembers, not what the editor made of it:
1988
+ // Redo after a paste brings back the frame that was taken out of the paste, the
1989
+ // style that was taken off what stayed, and Word's hidden text as words. And a drop
1990
+ // or a paste the editor was not told of is still a drop or a paste.
1991
+ if (kind === 'historyRedo') hideAgain();
1992
+ shown = checkDocument();
1993
+ }
1994
+ followPastes(kind === 'historyUndo');
1238
1995
  indentUndo = [];
1239
- const kind = (e as InputEvent | undefined)?.inputType ?? '';
1240
- if (kind === 'historyUndo' || kind === 'historyRedo') {
1241
- afterHistory();
1996
+ if (history) {
1997
+ // (Not in the middle of a Clear formatting or of its Undo: the sizes are then not
1998
+ // yet back on the elements. And what the editor puts back first, for the same reason.)
1999
+ if (kind === 'historyUndo') afterUndoOfClear();
2000
+ if (!clearing) afterHistory();
1242
2001
  } else {
2002
+ // (And a Clear formatting before this edit is the browser's to undo from here on.)
2003
+ clearUndo = clearRedo = null;
1243
2004
  // An edit: what was undone can no longer be redone.
1244
2005
  sizeSteps = sizeSteps.slice(0, sizeStepsApplied);
1245
2006
  // What was typed at a caret after a size was chosen came in marked: give it the size.
1246
2007
  applyPendingSize();
1247
2008
  }
1248
2009
  pendingSize = null;
2010
+ pendingFont = null;
1249
2011
  updateToolbarState();
1250
2012
  // Typing means the user is editing text, not the picture. Dropping the
1251
2013
  // selection here keeps Backspace editing that text instead of deleting a
1252
2014
  // still-selected image somewhere else in the document.
1253
2015
  selectedImage = null;
2016
+ // (Clear formatting says so itself, when the document is as it leaves it.)
2017
+ if (clearing) return;
1254
2018
  fireChange();
1255
- if (autosave) scheduleAutoSave();
2019
+ if (autosave && shown) scheduleAutoSave();
1256
2020
  }
1257
2021
 
1258
2022
  // ── Link modal ──
1259
2023
  function openLinkModal(): void {
1260
- saveSelection();
2024
+ keepForDialog();
1261
2025
  linkUrl = '';
1262
2026
  linkText = '';
1263
2027
  linkError = '';
@@ -1276,7 +2040,7 @@
1276
2040
  linkError = '';
1277
2041
  // Inserting changes the document outside an input event: earlier indent steps no longer undo.
1278
2042
  indentUndo = [];
1279
- restoreSelection();
2043
+ restoreFor(dialogSelection);
1280
2044
  editorEl?.focus();
1281
2045
 
1282
2046
  if (linkText) {
@@ -1315,7 +2079,7 @@
1315
2079
 
1316
2080
  // ── Images ──
1317
2081
  function openImageModal(): void {
1318
- saveSelection();
2082
+ keepForDialog();
1319
2083
  imageUrl = '';
1320
2084
  imageAlt = '';
1321
2085
  imageCaption = '';
@@ -1338,12 +2102,13 @@
1338
2102
  const url = imageUrl.trim();
1339
2103
  const caption = imageCaption.trim();
1340
2104
  const alt = imageAlt.trim();
2105
+ const at = dialogSelection;
1341
2106
 
1342
2107
  imageModalOpen = false;
1343
2108
  pendingImageFiles = [];
1344
2109
 
1345
2110
  if (files.length > 0) {
1346
- await insertImageFiles(files, caption, alt);
2111
+ await insertImageFiles(files, caption, alt, at);
1347
2112
  return;
1348
2113
  }
1349
2114
  if (!url) return;
@@ -1366,7 +2131,7 @@
1366
2131
  showError(UNREADABLE_MESSAGE);
1367
2132
  return;
1368
2133
  }
1369
- restoreSelection();
2134
+ restoreFor(at);
1370
2135
  editorEl?.focus();
1371
2136
  finishInsert(insertFigure(src, alt || caption, caption));
1372
2137
  // It displays either way, but only embedded bytes reach the RTF.
@@ -1503,8 +2268,11 @@
1503
2268
  if (autosave) scheduleAutoSave();
1504
2269
  }
1505
2270
 
1506
- /** Insert one figure per file, in the order they were given. */
1507
- async function insertImageFiles(files: File[], caption = '', alt = ''): Promise<void> {
2271
+ /**
2272
+ * Insert one figure per file, in the order they were given: at `at`, the selection the dialog
2273
+ * they were chosen in was opened on, or where the selection is.
2274
+ */
2275
+ async function insertImageFiles(files: File[], caption = '', alt = '', at: Range | null = null): Promise<void> {
1508
2276
  if (files.length === 0) return;
1509
2277
  insertingImages = true;
1510
2278
  let inserted: { img: HTMLImageElement; after: HTMLElement } | null = null;
@@ -1513,7 +2281,9 @@
1513
2281
  for (const file of files) {
1514
2282
  try {
1515
2283
  const src = await fileToImageSrc(file, imageLimits());
1516
- restoreSelection();
2284
+ // (The next one goes after this one: the caret is put there.)
2285
+ restoreFor(at);
2286
+ at = null;
1517
2287
  editorEl?.focus();
1518
2288
  // A single image takes the description typed in the dialog; a batch
1519
2289
  // gets empty captions the user fills in under each picture.
@@ -1546,12 +2316,101 @@
1546
2316
  }
1547
2317
 
1548
2318
  // ── Image selection / editing ──
2319
+ // ── Opening a link ──
2320
+ // A click in text one can edit puts the caret there, in a link as anywhere else, so that the
2321
+ // link's words can be changed: the browser follows no link in it. As in Word, a click with
2322
+ // Ctrl (Cmd on a Mac) opens the link, in a new tab, and a note at the link under the pointer
2323
+ // says so. The note is the editor's own and no part of the document.
2324
+
2325
+ const ON_MAC = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent);
2326
+ const OPEN_HINT = ON_MAC ? '\u2318 Command-click to open link' : 'Ctrl+click to open link';
2327
+ /** Room kept for the note beside the link, so that it is not cut off at the right. */
2328
+ const HINT_WIDTH = 320;
2329
+
2330
+ let linkHint: { top: number; left: number; above: boolean; href: string } | null = $state(null);
2331
+ /**
2332
+ * Ctrl or Cmd is down: the link under the pointer shows the hand it will be opened with.
2333
+ * (Only with the pointer at a link: the keys are down for every shortcut, and the document's
2334
+ * element is not to change its class with each.)
2335
+ */
2336
+ let linkArmed = $state(false);
2337
+ let hintedLink: Element | null = null;
2338
+
2339
+ /** The link an event is at, where it has an address a link may have. */
2340
+ function linkAt(e: Event): Element | null {
2341
+ const link = e.target instanceof Element ? e.target.closest('a[href]') : null;
2342
+ return link && editorEl?.contains(link) && linkTarget(link.getAttribute('href') ?? '') !== null ? link : null;
2343
+ }
2344
+
2345
+ function hideLinkHint(): void {
2346
+ hintedLink = null;
2347
+ linkHint = null;
2348
+ }
2349
+
2350
+ function linkHovered(e: MouseEvent): void {
2351
+ linkArmed = !readonly && (e.metaKey || e.ctrlKey);
2352
+ // (Not with a button down: the pointer is selecting text, and the note would be in its way.)
2353
+ if (readonly || copyFormat !== 'off' || e.buttons !== 0 || !contentWrapEl) return;
2354
+ const link = linkAt(e);
2355
+ if (!link || link === hintedLink) return;
2356
+ hintedLink = link;
2357
+ const wrap = contentWrapEl.getBoundingClientRect();
2358
+ // The line of the link the pointer is on: a link may run over two.
2359
+ const line = Array.from(link.getClientRects()).find((r) => e.clientY >= r.top && e.clientY <= r.bottom) ?? link.getBoundingClientRect();
2360
+ // Below the line, or above it where there is no room left in the window.
2361
+ const above = line.bottom + 64 > window.innerHeight;
2362
+ linkHint = {
2363
+ top: (above ? line.top - 6 : line.bottom + 6) - wrap.top,
2364
+ left: Math.max(0, Math.min(line.left - wrap.left, wrap.width - HINT_WIDTH)),
2365
+ above,
2366
+ href: link.getAttribute('href') ?? ''
2367
+ };
2368
+ }
2369
+
2370
+ function linkLeft(e: MouseEvent): void {
2371
+ if (!hintedLink) return;
2372
+ const to = e.relatedTarget;
2373
+ if (!(to instanceof Node) || !hintedLink.contains(to)) hideLinkHint();
2374
+ }
2375
+
2376
+ /** Open a link in a tab of its own, which is not handed this page. */
2377
+ function openLink(address: string): void {
2378
+ const target = linkTarget(address);
2379
+ if (target === null) return;
2380
+ const link = document.createElement('a');
2381
+ link.href = target;
2382
+ link.target = '_blank';
2383
+ link.rel = 'noopener noreferrer';
2384
+ link.click();
2385
+ }
2386
+
2387
+ /**
2388
+ * A click on a link: with Ctrl or Cmd it is opened. Where the document cannot be edited a
2389
+ * plain click opens it, as in the viewer, and in a new tab too: the browser would open it
2390
+ * in this one, in place of the application. True where the click was the link's.
2391
+ */
2392
+ function followLink(e: MouseEvent): boolean {
2393
+ const modified = e.metaKey || e.ctrlKey;
2394
+ // (Read only, a click with a key down is the browser's own: a new tab, a new window.)
2395
+ if (readonly ? modified || e.shiftKey || e.altKey : !modified) return false;
2396
+ const link = e.target instanceof Element ? e.target.closest('a[href]') : null;
2397
+ if (!link || !editorEl?.contains(link)) return false;
2398
+ e.preventDefault();
2399
+ hideLinkHint();
2400
+ openLink(link.getAttribute('href') ?? '');
2401
+ return true;
2402
+ }
2403
+
1549
2404
  function handleContentClick(e: MouseEvent): void {
1550
- if (readonly) return;
2405
+ if (readonly) {
2406
+ followLink(e);
2407
+ return;
2408
+ }
1551
2409
  if (copyFormat !== 'off') {
1552
2410
  handleCopyFormatClick(e);
1553
2411
  return;
1554
2412
  }
2413
+ if (followLink(e)) return;
1555
2414
  const target = e.target as HTMLElement | null;
1556
2415
  selectedImage = target?.tagName === 'IMG' ? (target as HTMLImageElement) : null;
1557
2416
  }
@@ -1602,15 +2461,37 @@
1602
2461
  function handleDrop(e: DragEvent): void {
1603
2462
  if (readonly) return;
1604
2463
  const files = Array.from(e.dataTransfer?.files || []).filter((f) => f.type.startsWith('image/'));
1605
- if (files.length === 0) return;
2464
+ if (files.length === 0) {
2465
+ // Text or markup dragged in, from another page or from further up this one. The
2466
+ // browser puts it in the document itself, as it does a paste, and the input event
2467
+ // that follows makes it safe the same way. (Only a paste was: what was dragged in
2468
+ // stayed as the browser left it, with a block drawn over the whole page, a form
2469
+ // that sends what is typed in it somewhere else, a frame showing another site.)
2470
+ expectInsertion(draggedFromHere);
2471
+ // What the browser may lose of it, as of a paste: it begins where it is dropped.
2472
+ const dropped = e.dataTransfer?.getData?.('text/html') ?? '';
2473
+ pastedPictures = pastePictures(dropped, e.dataTransfer?.getData?.('text/rtf') ?? '');
2474
+ const notes = pasteNotes(dropped);
2475
+ const at = notes ? rangeAtPoint(e.clientX, e.clientY) : null;
2476
+ pastedLoss = notes && at && editorEl?.contains(at.startContainer) ? { notes, from: shownCharsBefore(at.startContainer, at.startOffset), dropped: true } : null;
2477
+ // What holds a frame is put in here, made safe and without it (see pasteWithoutFrames).
2478
+ const unframed = pasteWithoutFrames(dropped, keptNames);
2479
+ if (unframed !== null) {
2480
+ e.preventDefault();
2481
+ editorEl?.focus();
2482
+ placeCaretAtPoint(e.clientX, e.clientY);
2483
+ document.execCommand('insertHTML', false, unframed);
2484
+ }
2485
+ return;
2486
+ }
1606
2487
  e.preventDefault();
1607
2488
  editorEl?.focus();
1608
2489
  placeCaretAtPoint(e.clientX, e.clientY);
1609
2490
  void insertImageFiles(files);
1610
2491
  }
1611
2492
 
1612
- /** Move the caret under the pointer so a dropped image lands where it was dropped. */
1613
- function placeCaretAtPoint(x: number, y: number): void {
2493
+ /** The place in the text under the pointer. */
2494
+ function rangeAtPoint(x: number, y: number): Range | null {
1614
2495
  const doc = document as Document & {
1615
2496
  caretPositionFromPoint?: (x: number, y: number) => { offsetNode: Node; offset: number } | null;
1616
2497
  caretRangeFromPoint?: (x: number, y: number) => Range | null;
@@ -1627,7 +2508,12 @@
1627
2508
  } else if (typeof doc.caretRangeFromPoint === 'function') {
1628
2509
  range = doc.caretRangeFromPoint(x, y);
1629
2510
  }
2511
+ return range;
2512
+ }
1630
2513
 
2514
+ /** Move the caret under the pointer so a dropped image lands where it was dropped. */
2515
+ function placeCaretAtPoint(x: number, y: number): void {
2516
+ const range = rangeAtPoint(x, y);
1631
2517
  if (!range || !editorEl?.contains(range.startContainer)) return;
1632
2518
  const sel = window.getSelection();
1633
2519
  sel?.removeAllRanges();
@@ -1645,15 +2531,20 @@
1645
2531
  importing = true;
1646
2532
 
1647
2533
  try {
1648
- const html = await readRtfFile(file, { fontSize, maxBytes: maxRtfBytes });
2534
+ const html = await readRtfFile(file, { fontSize, fontFamily, fonts, maxBytes: maxRtfBytes });
1649
2535
  if (editorEl) {
1650
2536
  selectedImage = null;
1651
2537
  documentReplaced();
1652
2538
  // (What the reader writes is safe as it stands; it goes the same way as any other
1653
2539
  // HTML so there is one way in.)
1654
- showDocument(html);
2540
+ const shown = showDocument(html);
1655
2541
  updateCounts();
2542
+ // (Shown or not, the document before it is gone, and the application is told so.)
1656
2543
  fireChange();
2544
+ if (!shown) {
2545
+ dropDraft();
2546
+ throw new Error(NOT_SHOWN);
2547
+ }
1657
2548
  if (autosave) scheduleAutoSave();
1658
2549
  onimport?.({ html });
1659
2550
  }
@@ -1678,8 +2569,11 @@
1678
2569
  if (mod && e.key === 'i') { e.preventDefault(); exec('italic'); }
1679
2570
  if (mod && e.key === 'u') { e.preventDefault(); exec('underline'); }
1680
2571
  if (mod && e.key === 'k') { e.preventDefault(); openLinkModal(); }
1681
- if (mod && e.key === 's') { e.preventDefault(); autoSaveNow(); }
1682
- if (mod && !e.shiftKey && e.key.toLowerCase() === 'z' && undoIndent()) { e.preventDefault(); return; }
2572
+ if (mod && e.key === 's') { e.preventDefault(); saveNow(); }
2573
+ if (mod && !e.shiftKey && e.key.toLowerCase() === 'z' && (undoIndent() || undoClear())) { e.preventDefault(); return; }
2574
+ // (Redo is Ctrl+Y as well, but not Cmd+Y.)
2575
+ const redoKey = (e.shiftKey && e.key.toLowerCase() === 'z') || (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'y');
2576
+ if (mod && redoKey && redoClear()) { e.preventDefault(); return; }
1683
2577
  if (mod && e.key === ']') { e.preventDefault(); indentBlocks('indent'); return; }
1684
2578
  if (mod && e.key === '[') { e.preventDefault(); indentBlocks('outdent'); return; }
1685
2579
 
@@ -1842,7 +2736,12 @@
1842
2736
  .map((item) => item.getAsFile())
1843
2737
  .filter((file): file is File => file !== null);
1844
2738
 
1845
- if (files.length > 0 && !readonly) {
2739
+ // A picture that comes with words is a picture of those words: Word copies its text
2740
+ // that way, and Chromium hands over both. The words are what is pasted. (The picture was:
2741
+ // text copied in Word went in as a picture of it, which cannot be edited, and Word's
2742
+ // hidden text with it, unseen. Safari hands over no picture, and pasted the words.)
2743
+ const html = e.clipboardData?.getData('text/html') ?? '';
2744
+ if (files.length > 0 && !readonly && !pasteHasWords(html)) {
1846
2745
  e.preventDefault();
1847
2746
  void insertImageFiles(files);
1848
2747
  return;
@@ -1857,27 +2756,51 @@
1857
2756
  }
1858
2757
  // The browser pastes next; the input event that follows tidies what came in.
1859
2758
  if (!readonly && editorEl) {
1860
- const snapshot = new Set(editorEl.querySelectorAll('*'));
1861
- pastedOver = snapshot;
2759
+ expectInsertion();
1862
2760
  // What the browser's paste may lose (see pasteNotes), and where the paste begins.
1863
- const notes = pasteNotes(e.clipboardData?.getData('text/html') ?? '');
2761
+ const notes = pasteNotes(html);
1864
2762
  const start = sel && sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
1865
2763
  pastedLoss =
1866
2764
  notes && start && editorEl.contains(start.startContainer)
1867
2765
  ? { notes, from: shownCharsBefore(start.startContainer, start.startOffset) }
1868
2766
  : null;
1869
- // A paste that inserts nothing (an empty clipboard, a host that cancels it) raises no
1870
- // input event. Left set, the snapshot would make the next keystroke treat the whole
1871
- // document as pasted.
1872
- setTimeout(() => {
1873
- if (pastedOver === snapshot) {
1874
- pastedOver = null;
1875
- pastedLoss = null;
1876
- }
1877
- }, 0);
2767
+ // The pictures Word's HTML only names, from its RTF (see pastePictures).
2768
+ pastedPictures = pastePictures(html, e.clipboardData?.getData('text/rtf') ?? '');
2769
+ // What holds a frame is put in here, made safe and without it (see pasteWithoutFrames).
2770
+ const unframed = pasteWithoutFrames(html, keptNames);
2771
+ if (unframed !== null) {
2772
+ e.preventDefault();
2773
+ document.execCommand('insertHTML', false, unframed);
2774
+ }
1878
2775
  }
1879
2776
  }
1880
2777
 
2778
+ /**
2779
+ * The browser is about to put something in the document itself, a paste or a drop: remember
2780
+ * which elements are there now, so that the input event that follows knows what came in.
2781
+ * `own` says it was picked up in this document.
2782
+ */
2783
+ function expectInsertion(own = false): void {
2784
+ if (readonly || !editorEl) return;
2785
+ const snapshot = new Set(editorEl.querySelectorAll('*'));
2786
+ pastedOver = snapshot;
2787
+ pastedOwn = own;
2788
+ pastedLoss = null;
2789
+ pastedPictures = null;
2790
+ commentsBefore = new Set(commentsIn(editorEl));
2791
+ // A paste that inserts nothing (an empty clipboard, a host that cancels it) raises no
2792
+ // input event. Left set, the snapshot would make the next keystroke treat the whole
2793
+ // document as pasted.
2794
+ setTimeout(() => {
2795
+ if (pastedOver === snapshot) {
2796
+ pastedOver = null;
2797
+ pastedLoss = null;
2798
+ pastedPictures = null;
2799
+ commentsBefore = null;
2800
+ }
2801
+ }, 0);
2802
+ }
2803
+
1881
2804
  /** How many characters that are not white space the document has before a place in it. */
1882
2805
  function shownCharsBefore(node: Node, offset: number): number {
1883
2806
  if (!editorEl) return 0;
@@ -1891,7 +2814,7 @@
1891
2814
  * Set right what the browser's paste changed before it could be looked at: Word's hidden
1892
2815
  * text shown as text, and a text box left empty.
1893
2816
  */
1894
- function restorePasteLoss(before: Set<Element>, loss: { notes: PasteNotes; from: number }): void {
2817
+ function restorePasteLoss(before: Set<Element>, loss: { notes: PasteNotes; from: number; dropped?: boolean }): void {
1895
2818
  if (!editorEl) return;
1896
2819
  const areas = Array.from(editorEl.querySelectorAll('textarea')).filter((area) => !before.has(area));
1897
2820
  if (areas.length === loss.notes.textareas.length) {
@@ -1899,17 +2822,76 @@
1899
2822
  if (area.value === '') area.textContent = loss.notes.textareas[i];
1900
2823
  });
1901
2824
  }
1902
- // After a paste the caret is at its end.
2825
+ // After a paste the caret is at its end. After a drop what was dropped may be selected
2826
+ // instead, and then it is known exactly where it begins as well.
1903
2827
  const sel = window.getSelection();
1904
- if (!sel || sel.rangeCount === 0 || !sel.isCollapsed || !editorEl.contains(sel.anchorNode)) return;
1905
- const caret = sel.getRangeAt(0);
1906
- const to = shownCharsBefore(caret.startContainer, caret.startOffset);
2828
+ if (!sel || sel.rangeCount === 0 || !editorEl.contains(sel.anchorNode) || !editorEl.contains(sel.focusNode)) return;
2829
+ if (!sel.isCollapsed && !loss.dropped) return;
2830
+ const range = sel.getRangeAt(0);
2831
+ let from = sel.isCollapsed ? loss.from : shownCharsBefore(range.startContainer, range.startOffset);
2832
+ let to = shownCharsBefore(range.endContainer, range.endOffset);
2833
+ const came = new Set(Array.from(editorEl.querySelectorAll('*')).filter((el) => !before.has(el)));
2834
+ // Firefox leaves the caret before a whole page it has pasted (a copy made in Word, with
2835
+ // its <head>), not after it. The paste is then the elements that came in, from the
2836
+ // first to the end of the last. (Text that is not the paste's own, to the character,
2837
+ // is left alone as ever: see removeWordHidden.)
2838
+ if (sel.isCollapsed && to <= from && came.size > 0) {
2839
+ const outer = Array.from(came).filter((el) => el.parentElement && !came.has(el.parentElement));
2840
+ const index = (el: Element) => Array.prototype.indexOf.call(el.parentNode!.childNodes, el);
2841
+ from = Math.min(...outer.map((el) => shownCharsBefore(el.parentNode!, index(el))));
2842
+ to = Math.max(...outer.map((el) => shownCharsBefore(el.parentNode!, index(el) + 1)));
2843
+ }
2844
+ if (takeHidden(from, to, loss.notes, (el) => came.has(el))) {
2845
+ hiddenTaken.push({ notes: loss.notes, from, came, emptied: Array.from(came).filter((el) => !el.isConnected) });
2846
+ }
2847
+ }
2848
+
2849
+ /**
2850
+ * Take Word's hidden text out of the paste that is the text from the `from`th to the `to`th
2851
+ * character shown, or with null for `to`, the paste Redo has put back from the `from`th on
2852
+ * (see removeWordHidden). Returns whether anything was taken out.
2853
+ */
2854
+ /** Word's mark on text it hides, as a paste carries it in a style. */
2855
+ const WORD_HIDES = /mso-hide\s*:\s*all/i;
2856
+
2857
+ function takeHidden(from: number, to: number | null, notes: PasteNotes, came: (el: Element) => boolean): boolean {
2858
+ if (!editorEl) return false;
1907
2859
  // A pasted element left with nothing in it goes, but not the one the caret is in: that
1908
2860
  // one becomes an empty line, to type in. (Taken out as well, a paste of hidden text
1909
2861
  // alone left the caret in no line at all, and the next words typed were in none.)
1910
- const held = sel.anchorNode instanceof Element ? sel.anchorNode : (sel.anchorNode?.parentElement ?? null);
1911
- if (!removeWordHidden(editorEl, loss.from, to, loss.notes, (el) => !before.has(el) && !(held !== null && el.contains(held)))) return;
2862
+ const sel = window.getSelection();
2863
+ const at = sel && sel.rangeCount > 0 && editorEl.contains(sel.anchorNode) ? sel.anchorNode : null;
2864
+ let held = at instanceof Element ? at : (at?.parentElement ?? null);
2865
+ // Firefox pastes Word's hidden text as an element that is not displayed, and leaves the
2866
+ // caret inside it: what was typed next was typed where it is not seen, and what is not
2867
+ // seen is not written. The caret is put before a hidden piece of a line, which then
2868
+ // goes with its text; a hidden paragraph the caret is in becomes the empty line, shown.
2869
+ let unseen: HTMLElement | null = null;
2870
+ for (let el = held; el && el !== editorEl; el = el.parentElement) {
2871
+ // (Word's own mark is still on it as the style it came with: the browser knows no
2872
+ // such property, and what came in has not been made safe yet.)
2873
+ const hidden = el instanceof HTMLElement && (WORD_HIDES.test(el.getAttribute('style') ?? '') || el.style.display === 'none' || el.style.visibility === 'hidden' || el.hasAttribute('hidden'));
2874
+ if (hidden && came(el)) unseen = el as HTMLElement;
2875
+ }
2876
+ if (unseen && sel) {
2877
+ if (/^(P|DIV|LI|H[1-6]|BLOCKQUOTE|PRE|TD|TH)$/.test(unseen.tagName)) {
2878
+ unseen.setAttribute('style', (unseen.getAttribute('style') ?? '').replace(new RegExp(`${WORD_HIDES.source}\\s*;?`, 'gi'), ''));
2879
+ unseen.style.removeProperty('display');
2880
+ unseen.style.removeProperty('visibility');
2881
+ unseen.removeAttribute('hidden');
2882
+ if (!unseen.getAttribute('style')?.trim()) unseen.removeAttribute('style');
2883
+ } else {
2884
+ const before = document.createRange();
2885
+ before.setStartBefore(unseen);
2886
+ before.collapse(true);
2887
+ sel.removeAllRanges();
2888
+ sel.addRange(before);
2889
+ held = unseen.parentElement;
2890
+ }
2891
+ }
2892
+ if (!removeWordHidden(editorEl, from, to, notes, (el) => came(el) && !(held !== null && el.contains(held)))) return false;
1912
2893
  if (held && held !== editorEl && held.isConnected && held.childNodes.length === 0) held.appendChild(document.createElement('br'));
2894
+ return true;
1913
2895
  }
1914
2896
 
1915
2897
  // ── Pasted formatting ──
@@ -1922,30 +2904,124 @@
1922
2904
  const PASTED_SPACING = ['margin-top', 'margin-right', 'margin-bottom', 'margin-left', 'text-indent'];
1923
2905
  /** The elements in the editor just before a paste; what is not in it came from the paste. */
1924
2906
  let pastedOver: Set<Element> | null = null;
1925
- /** What the paste under way may lose, and how much text the document had before it. */
1926
- let pastedLoss: { notes: PasteNotes; from: number } | null = null;
2907
+ /** Whether what is coming in was picked up in this document, and dragged to another place in it. */
2908
+ let pastedOwn = false;
2909
+ /** Whether what is being dragged now was picked up in this document. */
2910
+ let draggedFromHere = false;
2911
+ /**
2912
+ * Every element a paste or a drop has brought in, with the style it was left with when it
2913
+ * was tidied, and whether it was the document's own (see pastedOwn). Redo writes back on
2914
+ * these the style the browser first gave them, with the margins that were taken off: an
2915
+ * element whose style is another by then is tidied again.
2916
+ * (Held, not looked up in a WeakMap, for the reason given at wordsLeft.)
2917
+ */
2918
+ const broughtIn = new Map<Element, { style: string | null; own: boolean }>();
2919
+ /** What the paste or the drop under way may lose, and how much text the document had before it. */
2920
+ let pastedLoss: { notes: PasteNotes; from: number; dropped?: boolean } | null = null;
2921
+ /** The pictures of the paste that is coming in, where its HTML only names them (see pastePictures). */
2922
+ let pastedPictures: PastePictures | null = null;
2923
+
2924
+ // ── Comments that come in ──
2925
+ // HTML copied in another program may hold comments. What is in one is not shown and not
2926
+ // written to the RTF, but it is kept in the HTML that is saved, and Word writes in one the
2927
+ // address of each copied picture: a file on the writer's own disk, with the name of the
2928
+ // writer's account in it. A browser leaves comments out of a paste; Firefox keeps those of
2929
+ // markup that is dropped. So a comment that comes in is emptied. It is not taken out: Firefox
2930
+ // cannot undo a drop from which a node is gone, and an empty comment says nothing. Those the
2931
+ // application's own HTML has are not the editor's to judge, and stay as they are.
2932
+ /** The comments in the document just before a paste or a drop; what is not among them came with it. */
2933
+ let commentsBefore: Set<Comment> | null = null;
2934
+
2935
+ function commentsIn(root: Node): Comment[] {
2936
+ const found: Comment[] = [];
2937
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_COMMENT);
2938
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) found.push(node as Comment);
2939
+ return found;
2940
+ }
2941
+
2942
+ /**
2943
+ * Take off the elements `came` accepts, the ones a paste or a drop brought in, their id and
2944
+ * the margins and first-line indents that change nothing (see above). One `own` accepts was
2945
+ * moved from another place in this document, and keeps its id unless another element has it
2946
+ * too. (Moved words lost theirs like pasted ones, though the id was in the document once,
2947
+ * as before: an application that marks elements with ids lost its marks to a drag.)
2948
+ */
2949
+ function tidySpacing(came: (el: Element) => boolean, own: (el: Element) => boolean = () => false): void {
2950
+ if (!editorEl) return;
2951
+ const all = Array.from(editorEl.querySelectorAll<HTMLElement>('*'));
2952
+ const timesUsed = new Map<string, number>();
2953
+ for (const el of all) if (el.id) timesUsed.set(el.id, (timesUsed.get(el.id) ?? 0) + 1);
2954
+ for (const el of all) {
2955
+ if (!came(el)) continue;
2956
+ const isOwn = own(el);
2957
+ if (el.hasAttribute('id') && !(isOwn && timesUsed.get(el.id) === 1)) {
2958
+ timesUsed.set(el.id, (timesUsed.get(el.id) ?? 1) - 1);
2959
+ el.removeAttribute('id');
2960
+ }
2961
+ tidyStyle(el);
2962
+ broughtIn.set(el, { style: el.getAttribute('style'), own: isOwn });
2963
+ }
2964
+ }
2965
+
2966
+ /** Take off one element the margins and the first-line indent that change nothing. */
2967
+ function tidyStyle(el: HTMLElement): void {
2968
+ if (!el.getAttribute('style')) return;
2969
+ const inline = !el.matches(`${INDENT_TARGETS}, li, table, thead, tbody, tfoot, tr, td, th, figcaption, hr`);
2970
+ for (const prop of PASTED_SPACING) {
2971
+ const value = el.style.getPropertyValue(prop);
2972
+ if (!value) continue;
2973
+ const shown = getComputedStyle(el).getPropertyValue(prop);
2974
+ el.style.removeProperty(prop);
2975
+ if (!inline && getComputedStyle(el).getPropertyValue(prop) !== shown) el.style.setProperty(prop, value);
2976
+ }
2977
+ if (!el.getAttribute('style')) el.removeAttribute('style');
2978
+ }
1927
2979
 
1928
2980
  function tidyPasted(before: Set<Element>): void {
1929
2981
  if (!editorEl) return;
2982
+ // Firefox pastes the <style> of a copied page into the document with its words. It is
2983
+ // taken out below with all that is not safe; here first, because its rules count as text
2984
+ // of the paste, and Word's hidden words are found by the paste's text, to the character:
2985
+ // with a style sheet among them they were not found, and stayed in the document, unseen.
2986
+ for (const el of Array.from(editorEl.querySelectorAll('style, script, template, title'))) {
2987
+ if (!before.has(el)) el.remove();
2988
+ }
2989
+ if (commentsBefore) {
2990
+ for (const comment of commentsIn(editorEl)) {
2991
+ if (!commentsBefore.has(comment) && comment.data !== '') comment.data = '';
2992
+ }
2993
+ }
2994
+ commentsBefore = null;
1930
2995
  if (pastedLoss) restorePasteLoss(before, pastedLoss);
1931
2996
  pastedLoss = null;
2997
+ // Before what came in is made safe: an image that names a file on a disk loses that
2998
+ // address there, and is then an image of nothing.
2999
+ if (pastedPictures) {
3000
+ givePastedPictures(
3001
+ Array.from(editorEl.querySelectorAll('img')).filter((img) => !before.has(img)),
3002
+ pastedPictures
3003
+ );
3004
+ }
3005
+ pastedPictures = null;
1932
3006
  // What the paste brought is made safe as HTML from anywhere else is: a browser takes the
1933
3007
  // scripts out of a paste itself, but leaves a form, an <iframe>, or a block with
1934
3008
  // position: fixed that covers the page.
1935
- sanitizeTree(editorEl, (el) => !before.has(el), undefined, keptNames);
1936
- for (const el of Array.from(editorEl.querySelectorAll<HTMLElement>('*'))) {
1937
- if (before.has(el)) continue;
1938
- el.removeAttribute('id');
1939
- if (!el.getAttribute('style')) continue;
1940
- const inline = !el.matches(`${INDENT_TARGETS}, li, table, thead, tbody, tfoot, tr, td, th, figcaption, hr`);
1941
- for (const prop of PASTED_SPACING) {
1942
- const value = el.style.getPropertyValue(prop);
1943
- if (!value) continue;
1944
- const shown = getComputedStyle(el).getPropertyValue(prop);
1945
- el.style.removeProperty(prop);
1946
- if (!inline && getComputedStyle(el).getPropertyValue(prop) !== shown) el.style.setProperty(prop, value);
1947
- }
1948
- if (!el.getAttribute('style')) el.removeAttribute('style');
3009
+ // (And if it cannot be made safe, none of it stays.)
3010
+ const came = (el: Element) => !before.has(el);
3011
+ const own = pastedOwn;
3012
+ pastedOwn = false;
3013
+ leftNow = [];
3014
+ const safe = makeSafe(came);
3015
+ const left = leftNow;
3016
+ leftNow = null;
3017
+ if (!safe) {
3018
+ showError(LEFT_OUT);
3019
+ return;
3020
+ }
3021
+ tidySpacing(came, () => own);
3022
+ if (left.length > 0) {
3023
+ const stayed = Array.from(editorEl.querySelectorAll('*')).filter(came);
3024
+ if (stayed.length > 0) pastesWithWords.push({ stayed, left, there: true });
1949
3025
  }
1950
3026
  // A picture copied with its text comes in by address (<img src="https://…">), or as data in
1951
3027
  // a format the RTF cannot carry (GIF, WebP, SVG) or larger than maxImageBytes. Only PNG or
@@ -2226,23 +3302,33 @@
2226
3302
  // ── Lifecycle ──
2227
3303
  onMount(() => {
2228
3304
  if (!editorEl) return;
3305
+ document.addEventListener('selectionchange', trackSelection);
3306
+ const stopTracking = () => document.removeEventListener('selectionchange', trackSelection);
2229
3307
  if (autosave) {
3308
+ let saved: string | null = null;
2230
3309
  try {
2231
- const saved = localStorage.getItem(storageKey);
2232
- if (saved) {
2233
- // A draft is HTML from outside like any other: anything that can write to this
2234
- // origin's storage can write it.
2235
- showDocument(saved);
3310
+ saved = localStorage.getItem(storageKey);
3311
+ } catch (e) {}
3312
+ if (saved) {
3313
+ // A draft is HTML from outside like any other: anything that can write to this
3314
+ // origin's storage can write it.
3315
+ if (showDocument(saved)) {
2236
3316
  updateCounts();
2237
- return;
3317
+ return stopTracking;
2238
3318
  }
2239
- } catch (e) {}
3319
+ // (A draft that cannot be shown was dropped without a word; it is said now, and
3320
+ // the content given is shown in its place.)
3321
+ showError('The draft kept in this browser could not be shown');
3322
+ }
2240
3323
  }
2241
3324
  // Always write the initial content prop so the div isn't empty.
2242
3325
  // {#html content} must NOT be used inside the contenteditable div —
2243
3326
  // Svelte would re-inject it on every reactive update, duplicating text.
2244
- showDocument(content || EMPTY_DOCUMENT);
3327
+ // (A document that cannot be shown leaves the editor empty and says so: the failure
3328
+ // used to go up through the component as it was made, and there was no editor.)
3329
+ if (!showDocument(content || EMPTY_DOCUMENT)) showError(NOT_SHOWN);
2245
3330
  updateCounts();
3331
+ return stopTracking;
2246
3332
  });
2247
3333
 
2248
3334
  // Suppress unused warning for importing state (used in template)
@@ -2271,8 +3357,19 @@
2271
3357
  <svelte:window
2272
3358
  onkeydown={(e) => {
2273
3359
  if (copyFormat !== 'off' && e.key === 'Escape') stopCopyFormat();
3360
+ linkArmed = !readonly && (e.metaKey || e.ctrlKey);
3361
+ // Typing: the note at a link is in the way of the words.
3362
+ if (linkHint && e.key !== 'Meta' && e.key !== 'Control') hideLinkHint();
3363
+ }}
3364
+ onkeyup={(e) => (linkArmed = !readonly && (e.metaKey || e.ctrlKey))}
3365
+ onblur={() => {
3366
+ linkArmed = false;
3367
+ hideLinkHint();
3368
+ }}
3369
+ onresize={() => {
3370
+ placeCopySourceBox();
3371
+ hideLinkHint();
2274
3372
  }}
2275
- onresize={placeCopySourceBox}
2276
3373
  />
2277
3374
 
2278
3375
  <div
@@ -2281,43 +3378,54 @@
2281
3378
  style:--ink-font-family={screenFontFamily}
2282
3379
  style:--ink-font-size="{screenFontSize}pt"
2283
3380
  >
2284
- {#if showToolbar && !readonly}
2285
- <Toolbar
2286
- {formatState}
2287
- blockType={currentBlock}
2288
- onexec={exec}
2289
- onblock={setBlock}
2290
- oninsertlink={openLinkModal}
2291
- oninsertimage={openImageModal}
2292
- fontSize={currentFontSize}
2293
- fontSizes={sizeChoices}
2294
- onfontsize={setFontSize}
2295
- copyingFormat={copyFormat !== 'off'}
2296
- oncopyformat={toggleCopyFormat}
2297
- />
2298
- {/if}
3381
+ {#if !readonly && (showToolbar || copyFormat !== 'off')}
3382
+ <div class="ink-head" class:sticky={stickyToolbar} bind:this={headEl}>
3383
+ {#if showToolbar}
3384
+ <Toolbar
3385
+ {formatState}
3386
+ blockType={currentBlock}
3387
+ onexec={exec}
3388
+ onblock={setBlock}
3389
+ oninsertlink={openLinkModal}
3390
+ oninsertimage={openImageModal}
3391
+ fontSize={currentFontSize}
3392
+ fontSizes={sizeChoices}
3393
+ onfontsize={setFontSize}
3394
+ font={currentFont}
3395
+ fonts={fontList}
3396
+ documentFont={fontChoices([fontFamily])[0]?.name ?? DEFAULT_FONT_FAMILY}
3397
+ onfont={setFont}
3398
+ copyingFormat={copyFormat !== 'off'}
3399
+ oncopyformat={toggleCopyFormat}
3400
+ />
3401
+ {/if}
2299
3402
 
2300
- {#if copyFormat !== 'off' && !readonly}
2301
- <div class="ink-copy-format" role="status">
2302
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="14" height="6" rx="1.5"/><path d="M17 6h3v5h-9v3"/><rect x="9.5" y="14" width="3" height="7" rx="1"/></svg>
2303
- <span>
2304
- {copyFormat === 'pick'
2305
- ? 'Copy format: click the paragraph to copy from.'
2306
- : 'Format copied. Click each paragraph that should get it.'}
2307
- </span>
2308
- <button type="button" class="ink-copy-format-done" onmousedown={(e) => e.preventDefault()} onclick={stopCopyFormat}>
2309
- {copyFormat === 'pick' ? 'Cancel' : 'Done'}
2310
- </button>
2311
- <span class="ink-copy-format-key">or press Esc</span>
3403
+ {#if copyFormat !== 'off'}
3404
+ <div class="ink-copy-format" role="status">
3405
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="14" height="6" rx="1.5"/><path d="M17 6h3v5h-9v3"/><rect x="9.5" y="14" width="3" height="7" rx="1"/></svg>
3406
+ <span>
3407
+ {copyFormat === 'pick'
3408
+ ? 'Copy format: click the paragraph to copy from.'
3409
+ : 'Format copied. Click each paragraph that should get it.'}
3410
+ </span>
3411
+ <button type="button" class="ink-copy-format-done" onmousedown={(e) => e.preventDefault()} onclick={stopCopyFormat}>
3412
+ {copyFormat === 'pick' ? 'Cancel' : 'Done'}
3413
+ </button>
3414
+ <span class="ink-copy-format-key">or press Esc</span>
3415
+ </div>
3416
+ {/if}
2312
3417
  </div>
2313
3418
  {/if}
2314
3419
 
2315
3420
  <div class="ink-content-wrap" bind:this={contentWrapEl}>
2316
- <!-- svelte-ignore a11y_no_static_element_interactions -->
3421
+ <!-- (The pointer over a link shows a note of how the pointer opens it: there is nothing
3422
+ in it for the keyboard, which opens a link from the browser's own menu.) -->
3423
+ <!-- svelte-ignore a11y_no_static_element_interactions, a11y_mouse_events_have_key_events -->
2317
3424
  <div
2318
3425
  class="ink-content"
2319
3426
  class:copy-format-pick={copyFormat === 'pick'}
2320
3427
  class:copy-format-apply={copyFormat === 'apply'}
3428
+ class:links-open={linkArmed && linkHint !== null}
2321
3429
  contenteditable={!readonly}
2322
3430
  role="textbox"
2323
3431
  tabindex="0"
@@ -2331,10 +3439,17 @@
2331
3439
  onkeyup={caretMoved}
2332
3440
  onscroll={contentScrolled}
2333
3441
  onkeydown={handleKeydown}
2334
- onmousedown={() => (tabLeavesEditor = false)}
3442
+ onmousedown={() => {
3443
+ tabLeavesEditor = false;
3444
+ hideLinkHint();
3445
+ }}
3446
+ onmouseover={linkHovered}
3447
+ onmouseout={linkLeft}
2335
3448
  onblur={() => (tabLeavesEditor = false)}
2336
3449
  onpaste={handlePaste}
2337
3450
  onclick={handleContentClick}
3451
+ ondragstart={() => (draggedFromHere = true)}
3452
+ ondragend={() => (draggedFromHere = false)}
2338
3453
  ondragover={handleDragOver}
2339
3454
  ondrop={handleDrop}
2340
3455
  data-placeholder={placeholder}
@@ -2350,6 +3465,19 @@
2350
3465
  ></div>
2351
3466
  {/if}
2352
3467
 
3468
+ {#if linkHint && !readonly}
3469
+ <div
3470
+ class="ink-link-hint"
3471
+ class:above={linkHint.above}
3472
+ role="tooltip"
3473
+ style:top="{linkHint.top}px"
3474
+ style:left="{linkHint.left}px"
3475
+ >
3476
+ <span class="ink-link-hint-address">{linkHint.href}</span>
3477
+ <span class="ink-link-hint-how">{OPEN_HINT}</span>
3478
+ </div>
3479
+ {/if}
3480
+
2353
3481
  {#if !readonly}
2354
3482
  <ImageOverlay
2355
3483
  bind:this={overlayRef}
@@ -2462,6 +3590,22 @@
2462
3590
  width: 100%;
2463
3591
  }
2464
3592
 
3593
+ /* The toolbar, and under it the note of a format being copied. It stays in sight while a
3594
+ long document is scrolled, at the top of the window or of the scrolling element the
3595
+ editor is in: under a header of the page's own, --ink-toolbar-top is that header's
3596
+ height. Its ground is the toolbar's, so that no words show between its parts. */
3597
+ .ink-head {
3598
+ margin: 24px 0 16px;
3599
+ border-radius: var(--radius, 8px);
3600
+ background: var(--bg-toolbar, #fff);
3601
+ }
3602
+
3603
+ .ink-head.sticky {
3604
+ position: sticky;
3605
+ top: var(--ink-toolbar-top, 0px);
3606
+ z-index: 30;
3607
+ }
3608
+
2465
3609
  /* Anchors the image selection frame, which lives outside the
2466
3610
  contenteditable area so it never lands in the exported HTML. */
2467
3611
  .ink-content-wrap {
@@ -2520,7 +3664,7 @@
2520
3664
  display: flex;
2521
3665
  align-items: center;
2522
3666
  gap: 10px;
2523
- margin: -8px 0 12px;
3667
+ margin: 8px 0 0;
2524
3668
  padding: 8px 12px;
2525
3669
  border: 1px solid var(--accent, #6e56cf);
2526
3670
  border-radius: var(--radius-sm, 5px);
@@ -2565,6 +3709,64 @@
2565
3709
  pointer-events: none;
2566
3710
  }
2567
3711
 
3712
+ /* The note at a link under the pointer: where it goes, and how to open it. */
3713
+ .ink-link-hint {
3714
+ position: absolute;
3715
+ z-index: 5;
3716
+ box-sizing: border-box;
3717
+ max-width: min(320px, 100%);
3718
+ display: flex;
3719
+ flex-direction: column;
3720
+ gap: 2px;
3721
+ padding: 6px 10px;
3722
+ border-radius: 8px;
3723
+ background: var(--ink, #1a1714);
3724
+ color: #fff;
3725
+ font-family: 'DM Sans', system-ui, sans-serif;
3726
+ font-size: 12px;
3727
+ line-height: 1.35;
3728
+ box-shadow: 0 4px 14px rgba(0, 0, 0, 0.18);
3729
+ pointer-events: none;
3730
+ /* Not at once: the pointer crosses links on its way elsewhere. */
3731
+ animation: ink-link-hint-in 120ms ease 350ms both;
3732
+ }
3733
+
3734
+ .ink-link-hint.above {
3735
+ transform: translateY(-100%);
3736
+ }
3737
+
3738
+ .ink-link-hint-address {
3739
+ overflow: hidden;
3740
+ white-space: nowrap;
3741
+ text-overflow: ellipsis;
3742
+ opacity: 0.75;
3743
+ }
3744
+
3745
+ .ink-link-hint-how {
3746
+ font-weight: 600;
3747
+ white-space: nowrap;
3748
+ }
3749
+
3750
+ @keyframes ink-link-hint-in {
3751
+ from {
3752
+ opacity: 0;
3753
+ }
3754
+ to {
3755
+ opacity: 1;
3756
+ }
3757
+ }
3758
+
3759
+ @media (prefers-reduced-motion: reduce) {
3760
+ .ink-link-hint {
3761
+ animation-duration: 1ms;
3762
+ }
3763
+ }
3764
+
3765
+ /* Ctrl or Cmd is down: a click will open the link. */
3766
+ .ink-content.links-open :global(a[href]) {
3767
+ cursor: pointer;
3768
+ }
3769
+
2568
3770
  /* Placeholder */
2569
3771
  .ink-content:empty::before {
2570
3772
  content: attr(data-placeholder);