svelte-rtf-editor 1.10.0 → 1.12.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.
@@ -37,6 +37,15 @@
37
37
  * selected text. The body size is always among them. An empty
38
38
  * list takes the size list off the toolbar.
39
39
  * Default: 8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 36.
40
+ * keepAttributes — `data-` attributes the application's documents carry, which
41
+ * the editor leaves on their elements: a mark on a paragraph that
42
+ * the application reads back (`data-section="2"`). Every other
43
+ * attribute the editor does not know is taken off HTML as it comes
44
+ * in, set or pasted. Names that do not start with `data-` are not
45
+ * kept. Default: none.
46
+ * keepClasses — Class names of the application's own that stay in an element's
47
+ * class list the same way (`<pre class="summary">`). Every other
48
+ * class is taken off. Default: none.
40
49
  *
41
50
  * Events (callback props):
42
51
  * onchange — Fires on content change with
@@ -55,6 +64,10 @@
55
64
  * focus() — Focuses the editor.
56
65
  * exportFile(format) — Downloads as 'html', 'md', or 'rtf'.
57
66
  * importRtf() — Opens the file picker to import an RTF file.
67
+ * setFontSize(points) — Sets the size of the selected text, or of what is typed next.
68
+ * clearFormatting() — Takes bold, italic, underline, strike, color, size and font off
69
+ * the selected text. Headings, lists, links, alignment, indents and
70
+ * the application's own marks stay.
58
71
  */
59
72
 
60
73
  import { onMount } from 'svelte';
@@ -62,7 +75,7 @@
62
75
  import Modal from './Modal.svelte';
63
76
  import ImageOverlay from './ImageOverlay.svelte';
64
77
  import { htmlToMarkdown, downloadFile } from '../utils.js';
65
- import { pasteNotes, removeWordHidden, sanitizedNodes, sanitizeTree, type PasteNotes } from '../sanitize.js';
78
+ import { keptMarks, pasteHasWords, pasteNotes, removeWordHidden, sanitizedNodes, sanitizeTree, type PasteNotes } from '../sanitize.js';
66
79
  import { readRtfFile, DEFAULT_MAX_RTF_BYTES } from '../rtf-parser.js';
67
80
  import {
68
81
  htmlToRtf,
@@ -120,6 +133,10 @@
120
133
  fontFamily?: string;
121
134
  fontSize?: number;
122
135
  fontSizes?: number[];
136
+ /** `data-` attributes of the application's own, kept on HTML that is set or pasted. */
137
+ keepAttributes?: string[];
138
+ /** Class names of the application's own, kept the same way. */
139
+ keepClasses?: string[];
123
140
  onchange?: (payload: ChangePayload) => void;
124
141
  onsave?: (payload: { html: string }) => void;
125
142
  onimport?: (payload: { html: string }) => void;
@@ -132,8 +149,12 @@
132
149
  */
133
150
  const EMPTY_DOCUMENT = '<p><br></p>';
134
151
 
152
+ /** The kinds of block the toolbar's list offers. */
153
+ const BLOCK_CHOICES = new Set(['p', 'h1', 'h2', 'h3', 'blockquote', 'pre']);
154
+
135
155
  /** The sizes, in points, the toolbar's size list offers unless `fontSizes` says otherwise. */
136
156
  const DEFAULT_FONT_SIZES = [8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 36];
157
+ const NO_KEPT_ATTRIBUTES: string[] = [];
137
158
 
138
159
  // ── Props ──
139
160
  let {
@@ -153,11 +174,15 @@
153
174
  fontFamily = DEFAULT_FONT_FAMILY,
154
175
  fontSize = DEFAULT_FONT_SIZE,
155
176
  fontSizes = DEFAULT_FONT_SIZES,
177
+ keepAttributes = NO_KEPT_ATTRIBUTES,
178
+ keepClasses = NO_KEPT_ATTRIBUTES,
156
179
  onchange,
157
180
  onsave,
158
181
  onimport
159
182
  }: Props = $props();
160
183
 
184
+ const keptNames = $derived(keptMarks({ keepAttributes, keepClasses }));
185
+
161
186
  // The same font and size go to the screen and to the RTF, so the editor
162
187
  // shows what the receiving system will show.
163
188
  const rtfOptions = $derived({ fontFamily, fontSize });
@@ -217,8 +242,14 @@
217
242
  if (editorEl) {
218
243
  selectedImage = null;
219
244
  documentReplaced();
220
- showDocument(html);
245
+ const shown = showDocument(html);
221
246
  updateCounts();
247
+ if (!shown) {
248
+ // The caller is told, and the editor is empty: see showDocument.
249
+ dropDraft();
250
+ showError(NOT_SHOWN);
251
+ throw new Error(`InkEditor.setHTML: ${NOT_SHOWN.toLowerCase()}`);
252
+ }
222
253
  if (autosave) scheduleAutoSave();
223
254
  }
224
255
  }
@@ -227,21 +258,169 @@
227
258
  * Put HTML from outside in the editor: made safe first, and with a line in every empty
228
259
  * paragraph, so it shows as the blank line the RTF writes for it. The nodes that were checked
229
260
  * are the nodes shown (see sanitizedNodes): the HTML is read once.
261
+ *
262
+ * Returns whether the document is shown. If it could not be made safe it is not shown, and
263
+ * neither is the one before it: the editor is left empty. (A failure here used to go up to
264
+ * whoever called. Given as `content`, there was then no editor at all; given to setHTML, the
265
+ * document before stayed on the screen, where it read as the one just asked for: one
266
+ * patient's report under another's name.)
230
267
  */
231
- function showDocument(html: string): void {
232
- if (!editorEl) return;
268
+ function showDocument(html: string): boolean {
269
+ if (!editorEl) return false;
233
270
  // An id the page already uses outside an editor is not the document's to take: see
234
271
  // sanitize.ts. (Another editor on the page may hold a document with the same ids.)
235
272
  const idTaken = (id: string) => {
236
273
  const owner = document.getElementById(id);
237
274
  return owner !== null && owner.closest('.ink-content') === null;
238
275
  };
239
- editorEl.replaceChildren(...sanitizedNodes(html, document, idTaken));
276
+ let nodes: Node[] | null = null;
277
+ try {
278
+ nodes = sanitizedNodes(html, document, idTaken, keptNames, partLeftOut);
279
+ } catch {
280
+ // Not shown: see above.
281
+ }
282
+ if (nodes === null) editorEl.innerHTML = EMPTY_DOCUMENT;
283
+ else editorEl.replaceChildren(...nodes);
240
284
  for (const p of Array.from(editorEl.querySelectorAll('p'))) {
241
285
  if (p.childNodes.length === 0) p.appendChild(document.createElement('br'));
242
286
  }
287
+ return nodes !== null;
288
+ }
289
+
290
+ /** Said when a document could not be made safe, and so is not shown. */
291
+ const NOT_SHOWN = 'This document could not be shown';
292
+
293
+ /**
294
+ * Said when one element could not be checked and was taken out, with what was in it, while
295
+ * the rest was. (It went without a word: a part of a report gone, and nobody told.)
296
+ */
297
+ const PART_LEFT_OUT = 'A part of this could not be checked, so that part was left out';
298
+ const partLeftOut = () => showError(PART_LEFT_OUT);
299
+
300
+ // ── What the browser brings in, and puts back ──
301
+ // Markup reaches the document in more ways than setHTML and a paste: it is dragged in, and
302
+ // Undo and Redo put back what the browser remembers of a paste, not what the editor made of
303
+ // it. Redo brings back the frame or the form that was taken out, as an element the editor has
304
+ // not seen. It also writes the style it first gave an element back on that element, which
305
+ // the editor has seen and made safe: "position: fixed" was on it again, over the page. So
306
+ // there is no element that, checked once, need not be looked at again: after Undo or Redo
307
+ // the whole document is checked, as it is when it is first shown.
308
+
309
+ /**
310
+ * Make safe the elements `only` accepts. If that cannot be done at all, they are taken out:
311
+ * what could not be checked does not stay. Returns whether it could be done.
312
+ */
313
+ function makeSafe(only: (el: Element) => boolean): boolean {
314
+ if (!editorEl) return true;
315
+ try {
316
+ sanitizeTree(editorEl, only, undefined, keptNames, wordsLeftFor, partLeftOut);
317
+ return true;
318
+ } catch {
319
+ for (const el of Array.from(editorEl.querySelectorAll('*'))) {
320
+ if (el.isConnected && only(el)) el.remove();
321
+ }
322
+ return false;
323
+ }
324
+ }
325
+
326
+ /**
327
+ * Make the whole document safe again: after Undo or Redo, and after a paste or a drop the
328
+ * editor was not told of. What a paste was tidied of, Redo also puts back, and it is taken
329
+ * off again. A document that cannot be checked is not shown, as in showDocument, and the
330
+ * draft is left as it was last kept: that one was checked, and it is the writer's work.
331
+ * Returns whether the document is shown.
332
+ */
333
+ function checkDocument(): boolean {
334
+ if (!editorEl) return true;
335
+ try {
336
+ sanitizeTree(editorEl, undefined, undefined, keptNames, wordsLeftFor, partLeftOut);
337
+ } catch {
338
+ editorEl.innerHTML = EMPTY_DOCUMENT;
339
+ documentReplaced();
340
+ clearTimeout(saveTimer);
341
+ showError(NOT_SHOWN);
342
+ return false;
343
+ }
344
+ // (Only where the style is not the one it was left with: each of these is measured.)
345
+ tidySpacing(
346
+ (el) => broughtIn.has(el) && broughtIn.get(el)!.style !== el.getAttribute('style'),
347
+ (el) => broughtIn.get(el)?.own ?? false
348
+ );
349
+ return true;
350
+ }
351
+
352
+ /**
353
+ * The words left in the document where an element was taken out of it: a button's, a text
354
+ * box's. The browser's history knows nothing of them. Undo takes the paste out and leaves
355
+ * them, and Redo puts the button back beside them, to be taken out again: its words were
356
+ * then in the document twice, and three times after the next Redo. So where an element comes
357
+ * back whose words are still there as they were left, those go, and the ones just left in
358
+ * its place stay.
359
+ *
360
+ * (The elements are held here, not looked up in a WeakMap. An element that is out of the
361
+ * document, with nothing but the browser's history holding it, is given a new object by
362
+ * WebKit when it comes back: a WeakMap had forgotten it, and Safari had the words twice.
363
+ * The history holds the elements as long anyway; these go when the document is replaced.)
364
+ */
365
+ const wordsLeft = new Map<Element, { node: Text; text: string }>();
366
+
367
+ function wordsLeftFor(el: Element, node: Text): void {
368
+ const earlier = wordsLeft.get(el);
369
+ // (Words that have been typed in since are the writer's own, and stay.)
370
+ if (earlier && earlier.node !== node && earlier.node.isConnected && earlier.node.data === earlier.text) earlier.node.remove();
371
+ wordsLeft.set(el, { node, text: node.data });
372
+ leftNow?.push(el);
373
+ }
374
+
375
+ /**
376
+ * Each paste or drop that left such words, with the elements it brought that stayed. Undo of
377
+ * the paste takes those elements out and knows nothing of the words: they stayed in the
378
+ * report, words of a paste the writer had taken back. So where an Undo has just taken out
379
+ * every element a paste brought, the words it left go too, if they are still as they were
380
+ * left. (A paste that brought words and no element that stayed has nothing to be known by,
381
+ * and its words do stay.)
382
+ */
383
+ const pastesWithWords: { stayed: Element[]; left: Element[]; there: boolean }[] = [];
384
+ /** The elements the paste being made safe has left words for. */
385
+ let leftNow: Element[] | null = null;
386
+
387
+ function followPastes(undone: boolean): void {
388
+ for (const paste of pastesWithWords) {
389
+ const there = paste.stayed.some((el) => el.isConnected);
390
+ if (undone && paste.there && !there) {
391
+ for (const el of paste.left) {
392
+ const words = wordsLeft.get(el);
393
+ if (words?.node.isConnected && words.node.data === words.text) words.node.remove();
394
+ }
395
+ }
396
+ paste.there = there;
397
+ }
243
398
  }
244
399
 
400
+ /**
401
+ * Each paste Word's hidden text was taken out of, with the elements that were left empty
402
+ * and went with it. Redo puts the paste back much as the browser first made it: some of the
403
+ * hidden words shown again, and those elements empty. Where the text there is once more that
404
+ * paste, the words are taken out again (see removeWordHidden), and the elements with them.
405
+ */
406
+ const hiddenTaken: { notes: PasteNotes; from: number; came: Set<Element>; emptied: Element[] }[] = [];
407
+
408
+ function hideAgain(): void {
409
+ for (const paste of hiddenTaken) {
410
+ takeHidden(paste.from, null, paste.notes, (el) => paste.came.has(el));
411
+ const sel = window.getSelection();
412
+ for (const el of paste.emptied) {
413
+ if (!el.isConnected || el.childNodes.length > 0) continue;
414
+ // (Not the one the caret is in: see takeHidden.)
415
+ if (sel?.anchorNode && el.contains(sel.anchorNode)) el.appendChild(document.createElement('br'));
416
+ else el.remove();
417
+ }
418
+ }
419
+ }
420
+
421
+ /** Said when what came in could not be made safe, and so was taken out again. */
422
+ const LEFT_OUT = 'What was put in could not be checked, so it was left out';
423
+
245
424
  export function getMarkdown(): string {
246
425
  if (!editorEl) return '';
247
426
  return htmlToMarkdown(editorEl);
@@ -269,10 +448,8 @@
269
448
  selectedImage = null;
270
449
  documentReplaced();
271
450
  editorEl.innerHTML = EMPTY_DOCUMENT;
272
- clearTimeout(saveTimer);
273
- try { localStorage.removeItem(storageKey); } catch (e) {}
451
+ dropDraft();
274
452
  updateCounts();
275
- lastSaved = '';
276
453
  fireChange();
277
454
  }
278
455
  }
@@ -316,6 +493,14 @@
316
493
  indentUndo = [];
317
494
  pastedOver = null;
318
495
  pastedLoss = null;
496
+ // (A selection kept from the document before points at nothing in the new one.)
497
+ savedSelection = null;
498
+ dialogSelection = null;
499
+ wordsLeft.clear();
500
+ broughtIn.clear();
501
+ pastesWithWords.length = 0;
502
+ hiddenTaken.length = 0;
503
+ clearUndo = clearRedo = clearPast = null;
319
504
  stopCopyFormat();
320
505
  }
321
506
 
@@ -334,19 +519,76 @@
334
519
  });
335
520
 
336
521
  // ── Selection helpers ──
337
- function saveSelection(): void {
522
+ /** Whether what is selected now, or the caret, is in the document. */
523
+ function selectionInEditor(): boolean {
338
524
  const sel = window.getSelection();
339
- if (sel && sel.rangeCount > 0) {
340
- savedSelection = sel.getRangeAt(0).cloneRange();
341
- }
525
+ return !!editorEl && !!sel && sel.rangeCount > 0 && editorEl.contains(sel.anchorNode) && editorEl.contains(sel.focusNode);
342
526
  }
343
527
 
528
+ /**
529
+ * Keep the selection, to put back when a dialog closes. Only one in the document is kept:
530
+ * with something on the page around the editor selected, the one kept is still the last one
531
+ * that was in the document. (That one was kept in its place, and could not be put back: the
532
+ * link made from the toolbar then went to the top of the document, as its own address.)
533
+ */
534
+ function saveSelection(): void {
535
+ if (!selectionInEditor()) return;
536
+ savedSelection = window.getSelection()!.getRangeAt(0).cloneRange();
537
+ }
538
+
539
+ /**
540
+ * Put the selection back in the document, where it has left it: a dialog or a list of the
541
+ * toolbar took the keyboard. Where the selection is in the document, that is the one to act
542
+ * on, and it is left alone. (The kept one was put back every time, and it was kept only when a
543
+ * dialog opened or a picture went in: after one link, Bold and every other button changed
544
+ * the words of that link, whatever was selected by then.)
545
+ */
344
546
  function restoreSelection(): void {
345
- if (savedSelection) {
346
- const sel = window.getSelection();
347
- sel?.removeAllRanges();
348
- sel?.addRange(savedSelection);
547
+ if (selectionInEditor()) return;
548
+ select(savedSelection);
549
+ }
550
+
551
+ /** Select a range kept earlier, if it is still in the document. Returns whether it was. */
552
+ function select(kept: Range | null): boolean {
553
+ if (!kept || !editorEl?.contains(kept.startContainer) || !editorEl.contains(kept.endContainer)) return false;
554
+ const sel = window.getSelection();
555
+ sel?.removeAllRanges();
556
+ sel?.addRange(kept);
557
+ return true;
558
+ }
559
+
560
+ /**
561
+ * The selection a dialog was opened on, kept apart from the one that follows the document's.
562
+ * (That one moves when the dialog closes: the browser gives the document the keyboard back
563
+ * with a caret of its own at the top, and a picture that was still being read went in there,
564
+ * not where the writer had been.)
565
+ */
566
+ let dialogSelection: Range | null = null;
567
+
568
+ function keepForDialog(): void {
569
+ saveSelection();
570
+ dialogSelection = savedSelection?.cloneRange() ?? null;
571
+ }
572
+
573
+ /** Put back the selection a dialog was opened on, or failing that the last one in the document. */
574
+ function restoreFor(dialog: Range | null): void {
575
+ if (!select(dialog)) restoreSelection();
576
+ }
577
+
578
+ /**
579
+ * Keep the selection whenever it changes in the document, so the one put back is the last one
580
+ * there. (Kept in the one Range, moved along: a new Range for every key pressed would be a
581
+ * thousand of them for the browser to keep up to date with the text.)
582
+ */
583
+ function trackSelection(): void {
584
+ if (!selectionInEditor()) return;
585
+ const range = window.getSelection()!.getRangeAt(0);
586
+ if (!savedSelection) {
587
+ savedSelection = range.cloneRange();
588
+ return;
349
589
  }
590
+ savedSelection.setStart(range.startContainer, range.startOffset);
591
+ savedSelection.setEnd(range.endContainer, range.endOffset);
350
592
  }
351
593
 
352
594
  // ── Font size ──
@@ -524,6 +766,10 @@
524
766
 
525
767
  // ── Exec command ──
526
768
  function exec(cmd: string, value: string | null = null): void {
769
+ if (cmd === 'removeFormat') {
770
+ clearFormatting();
771
+ return;
772
+ }
527
773
  restoreSelection();
528
774
  editorEl?.focus();
529
775
  // Color commands require an actual text selection — a collapsed cursor
@@ -541,12 +787,296 @@
541
787
  hangAtCaret();
542
788
  return;
543
789
  }
544
- if (cmd === 'undo' && undoIndent()) return;
790
+ if (cmd === 'undo' && (undoIndent() || undoClear())) return;
791
+ if (cmd === 'redo' && redoClear()) return;
545
792
  document.execCommand(cmd, false, value ?? undefined);
546
793
  if (cmd === 'undo' || cmd === 'redo') afterHistory();
547
794
  updateToolbarState();
548
795
  }
549
796
 
797
+ // ── Clear formatting ──
798
+ // The browser's own command does this, and each browser does it differently. Chromium and
799
+ // Safari take a paragraph's alignment and first-line indent with its color; Firefox leaves
800
+ // the color on the paragraph, and takes out the element an application's mark is on; Safari
801
+ // leaves a size where it is. So the command is used for what only it can do, which is to
802
+ // take the <b>, <i> and <font> elements out with an entry in the browser's own history
803
+ // (taken out by the editor instead, the next Undo in Safari empties the document). What is
804
+ // written on the elements is the editor's to change: before the command, the looks of the
805
+ // text are taken off every element whose text is all selected, and after it, whatever the
806
+ // command took off that is not a look of the text is written back.
807
+
808
+ /** What is written on an element for the looks of its text. */
809
+ const CHARACTER_STYLES = [
810
+ 'color', 'background', 'background-color', 'font', 'font-family', 'font-size', 'font-weight', 'font-style',
811
+ 'font-variant', 'font-stretch', 'text-decoration', 'text-decoration-line', 'text-decoration-color',
812
+ 'text-decoration-style', 'text-decoration-thickness', 'letter-spacing', 'text-transform', 'text-shadow',
813
+ 'vertical-align', '-webkit-text-stroke-width', '-webkit-text-fill-color'
814
+ ];
815
+ const isLook = (prop: string) =>
816
+ CHARACTER_STYLES.includes(prop) || /^(font|text-decoration|background|-webkit-text)-/.test(prop);
817
+ /** In a table these are the table's design, not the looks of its text. */
818
+ const TABLE_PARTS = 'table, thead, tbody, tfoot, tr, td, th, col, colgroup';
819
+ const TABLE_DESIGN = new Set(['background', 'background-color', 'vertical-align']);
820
+ /** The attributes that carry looks: `style`, and on a <font> its own. */
821
+ const LOOKS = ['style', 'color', 'size', 'face'] as const;
822
+ type Looks = Record<(typeof LOOKS)[number], string | null>;
823
+
824
+ /** One Clear formatting: what was written on each element before and after, to put back. */
825
+ interface ClearStep {
826
+ before: Map<Element, Looks>;
827
+ after: Map<Element, Looks>;
828
+ /** The browser's command changed something, and has an entry in its history. */
829
+ native: boolean;
830
+ /** The document as the editor handed it to the command: where the browser's Undo of the command leads back to. */
831
+ pre: string;
832
+ /** The document as the step left it. */
833
+ cleared: string;
834
+ /** The document as it is now, the step done or undone: it is undone, or redone, only from there. */
835
+ html: string;
836
+ }
837
+ let clearUndo: ClearStep | null = null;
838
+ let clearRedo: ClearStep | null = null;
839
+ /** The last one made, also after more was typed: the browser's Undo may yet lead back to it. */
840
+ let clearPast: ClearStep | null = null;
841
+ /** The input events of the editor's own commands, while it clears: what they leave is not yet the document. */
842
+ let clearing = false;
843
+
844
+ /**
845
+ * After the browser's own Undo. A Clear formatting is the editor's to undo only while nothing
846
+ * else has been done. After that the browser undoes its command with everything else, and
847
+ * knows nothing of what the editor took off the elements: bold was back, and the color was
848
+ * not. Where its Undo has led back to the document as the command was given it, the rest is
849
+ * put back here. A step the command left nothing of (a paragraph's color and no more) has no
850
+ * such place to be led back to: it is the editor's to undo again once the document is as
851
+ * that step left it, which is when what was typed after it has been undone.
852
+ */
853
+ function afterUndoOfClear(): void {
854
+ const step = clearPast;
855
+ if (!step || !editorEl || clearing) return;
856
+ const now = editorEl.innerHTML;
857
+ if (step.native && step.pre !== step.cleared) {
858
+ if (now !== step.pre) return;
859
+ writeLooks(step.before);
860
+ clearUndo = null;
861
+ clearRedo = { ...step, html: editorEl.innerHTML };
862
+ } else if (now === step.cleared) {
863
+ clearUndo = { ...step, html: now };
864
+ }
865
+ }
866
+
867
+ const looksOf = (el: Element): Looks => ({
868
+ style: el.getAttribute('style'),
869
+ color: el.getAttribute('color'),
870
+ size: el.getAttribute('size'),
871
+ face: el.getAttribute('face')
872
+ });
873
+
874
+ function writeLooks(looks: Map<Element, Looks>): void {
875
+ for (const [el, wanted] of looks) {
876
+ if (!el.isConnected) continue;
877
+ for (const name of LOOKS) {
878
+ if (el.getAttribute(name) === wanted[name]) continue;
879
+ if (wanted[name] === null) el.removeAttribute(name);
880
+ else el.setAttribute(name, wanted[name]);
881
+ }
882
+ }
883
+ }
884
+
885
+ /** Whether all the text of an element is selected. (One with no text is, if it is in the selection.) */
886
+ function allSelected(range: Range, el: Element): boolean {
887
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
888
+ for (let text = walker.nextNode() as Text | null; text; text = walker.nextNode() as Text | null) {
889
+ if (text.data === '') continue;
890
+ if (range.comparePoint(text, 0) !== 0 || range.comparePoint(text, text.data.length) !== 0) return false;
891
+ }
892
+ return true;
893
+ }
894
+
895
+ /**
896
+ * A <span> that is there for the looks of its text and nothing else. The command takes such
897
+ * a one out whole, in every browser, and its Undo puts it back as it was: it is left to it.
898
+ */
899
+ function onlyLooks(el: HTMLElement): boolean {
900
+ return el.tagName === 'SPAN' && el.attributes.length === 1 && el.style.length > 0 && Array.from(el.style).every(isLook);
901
+ }
902
+
903
+ /** An element that says something of its text other than how it looks: a mark of the application's, a tab. */
904
+ function isMark(el: HTMLElement): boolean {
905
+ return (
906
+ Array.from(el.attributes).some((attr) => !(LOOKS as readonly string[]).includes(attr.name)) ||
907
+ Array.from(el.style).some((prop) => !isLook(prop))
908
+ );
909
+ }
910
+
911
+ /** Take the looks of its text off one element: the element stays, and so does its layout. */
912
+ function plain(el: HTMLElement): void {
913
+ const tablePart = el.matches(TABLE_PARTS);
914
+ for (const prop of [...CHARACTER_STYLES, ...Array.from(el.style).filter(isLook)]) {
915
+ if (tablePart && TABLE_DESIGN.has(prop)) continue;
916
+ el.style.removeProperty(prop);
917
+ }
918
+ if (!el.getAttribute('style')) el.removeAttribute('style');
919
+ if (el.tagName === 'FONT') for (const name of ['color', 'size', 'face']) el.removeAttribute(name);
920
+ }
921
+
922
+ /**
923
+ * Take the formatting off the selected text: bold, italic, underline, strike, color, size and
924
+ * font, wherever it is written. What the text is stays: a heading is still a heading, a list
925
+ * a list, a link a link, and a paragraph keeps its alignment and its indents. So do the
926
+ * marks the application named (keepAttributes, keepClasses). Undo puts it back.
927
+ */
928
+ export function clearFormatting(): void {
929
+ if (readonly || !editorEl) return;
930
+ restoreSelection();
931
+ editorEl.focus();
932
+ const sel = window.getSelection();
933
+ if (!sel || sel.rangeCount === 0 || !selectionInEditor()) return;
934
+ if (sel.isCollapsed) {
935
+ // At a caret there is nothing to clear but what was chosen for the words typed next.
936
+ pendingSize = null;
937
+ document.execCommand('removeFormat');
938
+ updateToolbarState();
939
+ return;
940
+ }
941
+ // The document changes outside an input event: earlier indent steps no longer undo.
942
+ indentUndo = [];
943
+ const range = sel.getRangeAt(0);
944
+ const touched = Array.from(editorEl.querySelectorAll<HTMLElement>('*')).filter((el) => range.intersectsNode(el));
945
+ const before = new Map(touched.map((el) => [el, looksOf(el)]));
946
+ const whole = touched.filter((el) => allSelected(range, el));
947
+ for (const el of whole) if (!onlyLooks(el)) plain(el);
948
+ const wanted = new Map(touched.map((el) => [el, el.getAttribute('style')]));
949
+ const html = editorEl.innerHTML;
950
+ // An element that says something of its text other than how it looks is not there for the
951
+ // command to take out: it is the application's mark, or the space a tab takes. Safari
952
+ // takes out a <span> that has nothing but a style, and Firefox every <span> there is; and
953
+ // where only some words of a mark are selected, Firefox cuts the mark in two around them.
954
+ // So each such element is marked for the command as one to keep, which is enough for
955
+ // Safari; and where one is taken out or cut all the same, the command is taken back and
956
+ // done again with those elements closed to it. (What is bold inside one of them then
957
+ // stays bold.)
958
+ const marks = new Map(touched.filter(isMark).map((el) => [el, el.textContent]));
959
+ const kept = Array.from(marks.keys());
960
+ const selected = range.cloneRange();
961
+ clearing = true;
962
+ try {
963
+ let closed = spansAreTakenOut ? kept.filter((el) => el.tagName === 'SPAN') : [];
964
+ removeFormat(selected, kept, closed);
965
+ const lost = kept.filter((el) => !el.isConnected || el.textContent !== marks.get(el));
966
+ if (lost.length > 0) {
967
+ document.execCommand('undo');
968
+ if (lost.some((el) => el.tagName === 'SPAN')) spansAreTakenOut = true;
969
+ closed = Array.from(new Set([...closed, ...lost])).filter((el) => el.isConnected);
970
+ removeFormat(selected, kept.filter((el) => el.isConnected), closed);
971
+ }
972
+ } finally {
973
+ clearing = false;
974
+ }
975
+ const native = editorEl.innerHTML !== html;
976
+ // What the command took off that is not a look of the text goes back on.
977
+ const probe = document.createElement('span');
978
+ for (const el of touched) {
979
+ if (!el.isConnected) continue;
980
+ probe.setAttribute('style', wanted.get(el) ?? '');
981
+ for (const prop of Array.from(probe.style)) {
982
+ if (isLook(prop) && !(el.matches(TABLE_PARTS) && TABLE_DESIGN.has(prop))) continue;
983
+ const value = probe.style.getPropertyValue(prop);
984
+ if (el.style.getPropertyValue(prop) !== value) el.style.setProperty(prop, value, probe.style.getPropertyPriority(prop));
985
+ }
986
+ if (!el.getAttribute('style')) el.removeAttribute('style');
987
+ }
988
+ // (And a <span> left to the command that it did not take out after all.)
989
+ for (const el of whole) if (el.isConnected) plain(el);
990
+ const after = new Map(touched.map((el) => [el, looksOf(el)]));
991
+ const changed = native || touched.some((el) => LOOKS.some((name) => before.get(el)![name] !== after.get(el)![name]));
992
+ const cleared = editorEl.innerHTML;
993
+ clearUndo = clearPast = changed ? { before, after, native, pre: html, cleared, html: cleared } : null;
994
+ clearRedo = null;
995
+ updateToolbarState();
996
+ if (!changed) return;
997
+ fireChange();
998
+ if (autosave) scheduleAutoSave();
999
+ }
1000
+
1001
+ /** Whether this browser's command has been seen to take out a <span> that was to stay. */
1002
+ let spansAreTakenOut = false;
1003
+ /** Written on an element while the command runs, so that it is not one with only a style. */
1004
+ const KEEP_MARK = 'data-ink-keep';
1005
+
1006
+ /**
1007
+ * The browser's command on what was selected, with the elements in `kept` marked to stay and
1008
+ * those in `closed` out of its reach. Where the selection begins or ends inside a closed
1009
+ * element, the command would do nothing at all: it is given the part outside it.
1010
+ */
1011
+ function removeFormat(selected: Range, kept: HTMLElement[], closed: HTMLElement[]): void {
1012
+ const selection = window.getSelection();
1013
+ if (!selection) return;
1014
+ if (closed.length > 0 && selected.startContainer.isConnected && selected.endContainer.isConnected) {
1015
+ const outside = selected.cloneRange();
1016
+ for (const el of closed) {
1017
+ if (el.contains(outside.startContainer)) outside.setStartAfter(el);
1018
+ if (el.contains(outside.endContainer)) outside.setEndBefore(el);
1019
+ }
1020
+ if (outside.collapsed) return;
1021
+ selection.removeAllRanges();
1022
+ selection.addRange(outside);
1023
+ }
1024
+ const was = closed.map((el) => el.getAttribute('contenteditable'));
1025
+ for (const el of kept) el.setAttribute(KEEP_MARK, '');
1026
+ for (const el of closed) el.setAttribute('contenteditable', 'false');
1027
+ document.execCommand('removeFormat');
1028
+ // (Also off the copy the command makes of an element it cuts in two.)
1029
+ for (const el of [...kept, ...Array.from(editorEl?.querySelectorAll(`[${KEEP_MARK}]`) ?? [])]) el.removeAttribute(KEEP_MARK);
1030
+ closed.forEach((el, i) => {
1031
+ if (was[i] === null) el.removeAttribute('contenteditable');
1032
+ else el.setAttribute('contenteditable', was[i]!);
1033
+ });
1034
+ }
1035
+
1036
+ /** Undo the last Clear formatting, if nothing has changed since. */
1037
+ function undoClear(): boolean {
1038
+ const step = clearUndo;
1039
+ clearUndo = null;
1040
+ if (!step || !editorEl || editorEl.innerHTML !== step.html) return false;
1041
+ clearing = true;
1042
+ try {
1043
+ if (step.native) document.execCommand('undo');
1044
+ } finally {
1045
+ clearing = false;
1046
+ }
1047
+ writeLooks(step.before);
1048
+ // (Safari may take the step before back with it, and that may be a change of size.)
1049
+ afterHistory();
1050
+ clearRedo = { ...step, html: editorEl.innerHTML };
1051
+ clearChanged();
1052
+ return true;
1053
+ }
1054
+
1055
+ /** Do it again, if nothing has changed since it was undone. */
1056
+ function redoClear(): boolean {
1057
+ const step = clearRedo;
1058
+ clearRedo = null;
1059
+ if (!step || !editorEl || editorEl.innerHTML !== step.html) return false;
1060
+ // (In the order it was done: the command read the elements as the editor had left them.)
1061
+ writeLooks(step.after);
1062
+ clearing = true;
1063
+ try {
1064
+ if (step.native) document.execCommand('redo');
1065
+ } finally {
1066
+ clearing = false;
1067
+ }
1068
+ writeLooks(step.after);
1069
+ clearUndo = { ...step, html: editorEl.innerHTML };
1070
+ clearChanged();
1071
+ return true;
1072
+ }
1073
+
1074
+ function clearChanged(): void {
1075
+ updateToolbarState();
1076
+ fireChange();
1077
+ if (autosave) scheduleAutoSave();
1078
+ }
1079
+
550
1080
  // ── Indent ──
551
1081
  // Indent and Outdent move the paragraphs the selection touches by half an inch (48px, written
552
1082
  // to RTF as \li720) per press, as margin-left on each paragraph. The browser's own commands are
@@ -1133,8 +1663,7 @@
1133
1663
 
1134
1664
  const block = document.queryCommandValue('formatBlock');
1135
1665
  const normalized = block.replace(/[<>]/g, '').toLowerCase();
1136
- const map: Record<string, string> = { h1: 'h1', h2: 'h2', h3: 'h3', blockquote: 'blockquote', pre: 'pre', p: 'p' };
1137
- currentBlock = map[normalized] || 'p';
1666
+ currentBlock = BLOCK_CHOICES.has(normalized) ? normalized : 'p';
1138
1667
 
1139
1668
  updateCounts();
1140
1669
  }
@@ -1191,8 +1720,9 @@
1191
1720
  // ── Auto-save ──
1192
1721
  let saveTimer: ReturnType<typeof setTimeout> | undefined;
1193
1722
 
1194
- function autoSaveNow(): void {
1195
- if (!editorEl || !autosave) return;
1723
+ /** Keep the draft in the browser's storage. */
1724
+ function keepDraft(): void {
1725
+ if (!editorEl) return;
1196
1726
  try {
1197
1727
  localStorage.setItem(storageKey, editorEl.innerHTML);
1198
1728
  lastSaved = `Saved ${new Date().toLocaleTimeString()}`;
@@ -1202,6 +1732,35 @@
1202
1732
  // fires so the host app can persist the content itself.
1203
1733
  lastSaved = 'Too large to auto-save in this browser';
1204
1734
  }
1735
+ }
1736
+
1737
+ /**
1738
+ * Forget the draft, and the save that was waiting. (A document that could not be shown left
1739
+ * the draft of the one before it: opened again, the editor showed that one, the report of
1740
+ * the patient before.)
1741
+ */
1742
+ function dropDraft(): void {
1743
+ clearTimeout(saveTimer);
1744
+ try { localStorage.removeItem(storageKey); } catch (e) {}
1745
+ lastSaved = '';
1746
+ }
1747
+
1748
+ function autoSaveNow(): void {
1749
+ if (!editorEl || !autosave) return;
1750
+ keepDraft();
1751
+ onsave?.({ html: editorEl.innerHTML });
1752
+ }
1753
+
1754
+ /**
1755
+ * Ctrl+S: onsave, whether or not drafts are kept. (It went through the auto-save, which does
1756
+ * nothing where `autosave` is off. Since that is the default, the key was taken from the
1757
+ * browser and nothing was saved anywhere: an application that saves from onsave saved nothing.)
1758
+ */
1759
+ function saveNow(): void {
1760
+ if (!editorEl) return;
1761
+ // The save that was waiting is this one.
1762
+ clearTimeout(saveTimer);
1763
+ if (autosave) keepDraft();
1205
1764
  onsave?.({ html: editorEl.innerHTML });
1206
1765
  }
1207
1766
 
@@ -1210,18 +1769,38 @@
1210
1769
  saveTimer = setTimeout(autoSaveNow, 1000);
1211
1770
  }
1212
1771
 
1772
+ /** The kinds of input event that put markup from somewhere else into the document. */
1773
+ const MARKUP_FROM_OUTSIDE = new Set(['insertFromPaste', 'insertFromPasteAsQuotation', 'insertFromDrop', 'insertFromYank']);
1774
+
1213
1775
  // ── Input handler ──
1214
1776
  function handleInput(e?: Event): void {
1215
1777
  placeCopySourceBox();
1216
- if (pastedOver) {
1778
+ const kind = (e as InputEvent | undefined)?.inputType ?? '';
1779
+ const history = kind === 'historyUndo' || kind === 'historyRedo';
1780
+ // (Words dragged from one place in the document to another are first taken out where
1781
+ // they were, which is an input event of its own: what was dropped has not come in yet.)
1782
+ let shown = true;
1783
+ if (pastedOver && kind !== 'deleteByDrag') {
1217
1784
  tidyPasted(pastedOver);
1218
1785
  pastedOver = null;
1219
- }
1786
+ } else if (history || MARKUP_FROM_OUTSIDE.has(kind)) {
1787
+ // Undo and Redo put back what the browser remembers, not what the editor made of it:
1788
+ // Redo after a paste brings back the frame that was taken out of the paste, the
1789
+ // style that was taken off what stayed, and Word's hidden text as words. And a drop
1790
+ // or a paste the editor was not told of is still a drop or a paste.
1791
+ if (kind === 'historyRedo') hideAgain();
1792
+ shown = checkDocument();
1793
+ }
1794
+ followPastes(kind === 'historyUndo');
1220
1795
  indentUndo = [];
1221
- const kind = (e as InputEvent | undefined)?.inputType ?? '';
1222
- if (kind === 'historyUndo' || kind === 'historyRedo') {
1223
- afterHistory();
1796
+ if (history) {
1797
+ // (Not in the middle of a Clear formatting or of its Undo: the sizes are then not
1798
+ // yet back on the elements. And what the editor puts back first, for the same reason.)
1799
+ if (kind === 'historyUndo') afterUndoOfClear();
1800
+ if (!clearing) afterHistory();
1224
1801
  } else {
1802
+ // (And a Clear formatting before this edit is the browser's to undo from here on.)
1803
+ clearUndo = clearRedo = null;
1225
1804
  // An edit: what was undone can no longer be redone.
1226
1805
  sizeSteps = sizeSteps.slice(0, sizeStepsApplied);
1227
1806
  // What was typed at a caret after a size was chosen came in marked: give it the size.
@@ -1233,13 +1812,15 @@
1233
1812
  // selection here keeps Backspace editing that text instead of deleting a
1234
1813
  // still-selected image somewhere else in the document.
1235
1814
  selectedImage = null;
1815
+ // (Clear formatting says so itself, when the document is as it leaves it.)
1816
+ if (clearing) return;
1236
1817
  fireChange();
1237
- if (autosave) scheduleAutoSave();
1818
+ if (autosave && shown) scheduleAutoSave();
1238
1819
  }
1239
1820
 
1240
1821
  // ── Link modal ──
1241
1822
  function openLinkModal(): void {
1242
- saveSelection();
1823
+ keepForDialog();
1243
1824
  linkUrl = '';
1244
1825
  linkText = '';
1245
1826
  linkError = '';
@@ -1258,7 +1839,7 @@
1258
1839
  linkError = '';
1259
1840
  // Inserting changes the document outside an input event: earlier indent steps no longer undo.
1260
1841
  indentUndo = [];
1261
- restoreSelection();
1842
+ restoreFor(dialogSelection);
1262
1843
  editorEl?.focus();
1263
1844
 
1264
1845
  if (linkText) {
@@ -1297,7 +1878,7 @@
1297
1878
 
1298
1879
  // ── Images ──
1299
1880
  function openImageModal(): void {
1300
- saveSelection();
1881
+ keepForDialog();
1301
1882
  imageUrl = '';
1302
1883
  imageAlt = '';
1303
1884
  imageCaption = '';
@@ -1320,12 +1901,13 @@
1320
1901
  const url = imageUrl.trim();
1321
1902
  const caption = imageCaption.trim();
1322
1903
  const alt = imageAlt.trim();
1904
+ const at = dialogSelection;
1323
1905
 
1324
1906
  imageModalOpen = false;
1325
1907
  pendingImageFiles = [];
1326
1908
 
1327
1909
  if (files.length > 0) {
1328
- await insertImageFiles(files, caption, alt);
1910
+ await insertImageFiles(files, caption, alt, at);
1329
1911
  return;
1330
1912
  }
1331
1913
  if (!url) return;
@@ -1348,7 +1930,7 @@
1348
1930
  showError(UNREADABLE_MESSAGE);
1349
1931
  return;
1350
1932
  }
1351
- restoreSelection();
1933
+ restoreFor(at);
1352
1934
  editorEl?.focus();
1353
1935
  finishInsert(insertFigure(src, alt || caption, caption));
1354
1936
  // It displays either way, but only embedded bytes reach the RTF.
@@ -1485,8 +2067,11 @@
1485
2067
  if (autosave) scheduleAutoSave();
1486
2068
  }
1487
2069
 
1488
- /** Insert one figure per file, in the order they were given. */
1489
- async function insertImageFiles(files: File[], caption = '', alt = ''): Promise<void> {
2070
+ /**
2071
+ * Insert one figure per file, in the order they were given: at `at`, the selection the dialog
2072
+ * they were chosen in was opened on, or where the selection is.
2073
+ */
2074
+ async function insertImageFiles(files: File[], caption = '', alt = '', at: Range | null = null): Promise<void> {
1490
2075
  if (files.length === 0) return;
1491
2076
  insertingImages = true;
1492
2077
  let inserted: { img: HTMLImageElement; after: HTMLElement } | null = null;
@@ -1495,7 +2080,9 @@
1495
2080
  for (const file of files) {
1496
2081
  try {
1497
2082
  const src = await fileToImageSrc(file, imageLimits());
1498
- restoreSelection();
2083
+ // (The next one goes after this one: the caret is put there.)
2084
+ restoreFor(at);
2085
+ at = null;
1499
2086
  editorEl?.focus();
1500
2087
  // A single image takes the description typed in the dialog; a batch
1501
2088
  // gets empty captions the user fills in under each picture.
@@ -1584,15 +2171,27 @@
1584
2171
  function handleDrop(e: DragEvent): void {
1585
2172
  if (readonly) return;
1586
2173
  const files = Array.from(e.dataTransfer?.files || []).filter((f) => f.type.startsWith('image/'));
1587
- if (files.length === 0) return;
2174
+ if (files.length === 0) {
2175
+ // Text or markup dragged in, from another page or from further up this one. The
2176
+ // browser puts it in the document itself, as it does a paste, and the input event
2177
+ // that follows makes it safe the same way. (Only a paste was: what was dragged in
2178
+ // stayed as the browser left it, with a block drawn over the whole page, a form
2179
+ // that sends what is typed in it somewhere else, a frame showing another site.)
2180
+ expectInsertion(draggedFromHere);
2181
+ // What the browser may lose of it, as of a paste: it begins where it is dropped.
2182
+ const notes = pasteNotes(e.dataTransfer?.getData?.('text/html') ?? '');
2183
+ const at = notes ? rangeAtPoint(e.clientX, e.clientY) : null;
2184
+ pastedLoss = notes && at && editorEl?.contains(at.startContainer) ? { notes, from: shownCharsBefore(at.startContainer, at.startOffset), dropped: true } : null;
2185
+ return;
2186
+ }
1588
2187
  e.preventDefault();
1589
2188
  editorEl?.focus();
1590
2189
  placeCaretAtPoint(e.clientX, e.clientY);
1591
2190
  void insertImageFiles(files);
1592
2191
  }
1593
2192
 
1594
- /** Move the caret under the pointer so a dropped image lands where it was dropped. */
1595
- function placeCaretAtPoint(x: number, y: number): void {
2193
+ /** The place in the text under the pointer. */
2194
+ function rangeAtPoint(x: number, y: number): Range | null {
1596
2195
  const doc = document as Document & {
1597
2196
  caretPositionFromPoint?: (x: number, y: number) => { offsetNode: Node; offset: number } | null;
1598
2197
  caretRangeFromPoint?: (x: number, y: number) => Range | null;
@@ -1609,7 +2208,12 @@
1609
2208
  } else if (typeof doc.caretRangeFromPoint === 'function') {
1610
2209
  range = doc.caretRangeFromPoint(x, y);
1611
2210
  }
2211
+ return range;
2212
+ }
1612
2213
 
2214
+ /** Move the caret under the pointer so a dropped image lands where it was dropped. */
2215
+ function placeCaretAtPoint(x: number, y: number): void {
2216
+ const range = rangeAtPoint(x, y);
1613
2217
  if (!range || !editorEl?.contains(range.startContainer)) return;
1614
2218
  const sel = window.getSelection();
1615
2219
  sel?.removeAllRanges();
@@ -1633,9 +2237,14 @@
1633
2237
  documentReplaced();
1634
2238
  // (What the reader writes is safe as it stands; it goes the same way as any other
1635
2239
  // HTML so there is one way in.)
1636
- showDocument(html);
2240
+ const shown = showDocument(html);
1637
2241
  updateCounts();
2242
+ // (Shown or not, the document before it is gone, and the application is told so.)
1638
2243
  fireChange();
2244
+ if (!shown) {
2245
+ dropDraft();
2246
+ throw new Error(NOT_SHOWN);
2247
+ }
1639
2248
  if (autosave) scheduleAutoSave();
1640
2249
  onimport?.({ html });
1641
2250
  }
@@ -1660,8 +2269,11 @@
1660
2269
  if (mod && e.key === 'i') { e.preventDefault(); exec('italic'); }
1661
2270
  if (mod && e.key === 'u') { e.preventDefault(); exec('underline'); }
1662
2271
  if (mod && e.key === 'k') { e.preventDefault(); openLinkModal(); }
1663
- if (mod && e.key === 's') { e.preventDefault(); autoSaveNow(); }
1664
- if (mod && !e.shiftKey && e.key.toLowerCase() === 'z' && undoIndent()) { e.preventDefault(); return; }
2272
+ if (mod && e.key === 's') { e.preventDefault(); saveNow(); }
2273
+ if (mod && !e.shiftKey && e.key.toLowerCase() === 'z' && (undoIndent() || undoClear())) { e.preventDefault(); return; }
2274
+ // (Redo is Ctrl+Y as well, but not Cmd+Y.)
2275
+ const redoKey = (e.shiftKey && e.key.toLowerCase() === 'z') || (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'y');
2276
+ if (mod && redoKey && redoClear()) { e.preventDefault(); return; }
1665
2277
  if (mod && e.key === ']') { e.preventDefault(); indentBlocks('indent'); return; }
1666
2278
  if (mod && e.key === '[') { e.preventDefault(); indentBlocks('outdent'); return; }
1667
2279
 
@@ -1824,7 +2436,12 @@
1824
2436
  .map((item) => item.getAsFile())
1825
2437
  .filter((file): file is File => file !== null);
1826
2438
 
1827
- if (files.length > 0 && !readonly) {
2439
+ // A picture that comes with words is a picture of those words: Word copies its text
2440
+ // that way, and Chromium hands over both. The words are what is pasted. (The picture was:
2441
+ // text copied in Word went in as a picture of it, which cannot be edited, and Word's
2442
+ // hidden text with it, unseen. Safari hands over no picture, and pasted the words.)
2443
+ const html = e.clipboardData?.getData('text/html') ?? '';
2444
+ if (files.length > 0 && !readonly && !pasteHasWords(html)) {
1828
2445
  e.preventDefault();
1829
2446
  void insertImageFiles(files);
1830
2447
  return;
@@ -1839,27 +2456,39 @@
1839
2456
  }
1840
2457
  // The browser pastes next; the input event that follows tidies what came in.
1841
2458
  if (!readonly && editorEl) {
1842
- const snapshot = new Set(editorEl.querySelectorAll('*'));
1843
- pastedOver = snapshot;
2459
+ expectInsertion();
1844
2460
  // What the browser's paste may lose (see pasteNotes), and where the paste begins.
1845
- const notes = pasteNotes(e.clipboardData?.getData('text/html') ?? '');
2461
+ const notes = pasteNotes(html);
1846
2462
  const start = sel && sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
1847
2463
  pastedLoss =
1848
2464
  notes && start && editorEl.contains(start.startContainer)
1849
2465
  ? { notes, from: shownCharsBefore(start.startContainer, start.startOffset) }
1850
2466
  : null;
1851
- // A paste that inserts nothing (an empty clipboard, a host that cancels it) raises no
1852
- // input event. Left set, the snapshot would make the next keystroke treat the whole
1853
- // document as pasted.
1854
- setTimeout(() => {
1855
- if (pastedOver === snapshot) {
1856
- pastedOver = null;
1857
- pastedLoss = null;
1858
- }
1859
- }, 0);
1860
2467
  }
1861
2468
  }
1862
2469
 
2470
+ /**
2471
+ * The browser is about to put something in the document itself, a paste or a drop: remember
2472
+ * which elements are there now, so that the input event that follows knows what came in.
2473
+ * `own` says it was picked up in this document.
2474
+ */
2475
+ function expectInsertion(own = false): void {
2476
+ if (readonly || !editorEl) return;
2477
+ const snapshot = new Set(editorEl.querySelectorAll('*'));
2478
+ pastedOver = snapshot;
2479
+ pastedOwn = own;
2480
+ pastedLoss = null;
2481
+ // A paste that inserts nothing (an empty clipboard, a host that cancels it) raises no
2482
+ // input event. Left set, the snapshot would make the next keystroke treat the whole
2483
+ // document as pasted.
2484
+ setTimeout(() => {
2485
+ if (pastedOver === snapshot) {
2486
+ pastedOver = null;
2487
+ pastedLoss = null;
2488
+ }
2489
+ }, 0);
2490
+ }
2491
+
1863
2492
  /** How many characters that are not white space the document has before a place in it. */
1864
2493
  function shownCharsBefore(node: Node, offset: number): number {
1865
2494
  if (!editorEl) return 0;
@@ -1873,7 +2502,7 @@
1873
2502
  * Set right what the browser's paste changed before it could be looked at: Word's hidden
1874
2503
  * text shown as text, and a text box left empty.
1875
2504
  */
1876
- function restorePasteLoss(before: Set<Element>, loss: { notes: PasteNotes; from: number }): void {
2505
+ function restorePasteLoss(before: Set<Element>, loss: { notes: PasteNotes; from: number; dropped?: boolean }): void {
1877
2506
  if (!editorEl) return;
1878
2507
  const areas = Array.from(editorEl.querySelectorAll('textarea')).filter((area) => !before.has(area));
1879
2508
  if (areas.length === loss.notes.textareas.length) {
@@ -1881,17 +2510,36 @@
1881
2510
  if (area.value === '') area.textContent = loss.notes.textareas[i];
1882
2511
  });
1883
2512
  }
1884
- // After a paste the caret is at its end.
2513
+ // After a paste the caret is at its end. After a drop what was dropped may be selected
2514
+ // instead, and then it is known exactly where it begins as well.
1885
2515
  const sel = window.getSelection();
1886
- if (!sel || sel.rangeCount === 0 || !sel.isCollapsed || !editorEl.contains(sel.anchorNode)) return;
1887
- const caret = sel.getRangeAt(0);
1888
- const to = shownCharsBefore(caret.startContainer, caret.startOffset);
2516
+ if (!sel || sel.rangeCount === 0 || !editorEl.contains(sel.anchorNode) || !editorEl.contains(sel.focusNode)) return;
2517
+ if (!sel.isCollapsed && !loss.dropped) return;
2518
+ const range = sel.getRangeAt(0);
2519
+ const from = sel.isCollapsed ? loss.from : shownCharsBefore(range.startContainer, range.startOffset);
2520
+ const to = shownCharsBefore(range.endContainer, range.endOffset);
2521
+ const came = new Set(Array.from(editorEl.querySelectorAll('*')).filter((el) => !before.has(el)));
2522
+ if (takeHidden(from, to, loss.notes, (el) => came.has(el))) {
2523
+ hiddenTaken.push({ notes: loss.notes, from, came, emptied: Array.from(came).filter((el) => !el.isConnected) });
2524
+ }
2525
+ }
2526
+
2527
+ /**
2528
+ * Take Word's hidden text out of the paste that is the text from the `from`th to the `to`th
2529
+ * character shown, or with null for `to`, the paste Redo has put back from the `from`th on
2530
+ * (see removeWordHidden). Returns whether anything was taken out.
2531
+ */
2532
+ function takeHidden(from: number, to: number | null, notes: PasteNotes, came: (el: Element) => boolean): boolean {
2533
+ if (!editorEl) return false;
1889
2534
  // A pasted element left with nothing in it goes, but not the one the caret is in: that
1890
2535
  // one becomes an empty line, to type in. (Taken out as well, a paste of hidden text
1891
2536
  // alone left the caret in no line at all, and the next words typed were in none.)
1892
- const held = sel.anchorNode instanceof Element ? sel.anchorNode : (sel.anchorNode?.parentElement ?? null);
1893
- if (!removeWordHidden(editorEl, loss.from, to, loss.notes, (el) => !before.has(el) && !(held !== null && el.contains(held)))) return;
2537
+ const sel = window.getSelection();
2538
+ const at = sel && sel.rangeCount > 0 && editorEl.contains(sel.anchorNode) ? sel.anchorNode : null;
2539
+ const held = at instanceof Element ? at : (at?.parentElement ?? null);
2540
+ if (!removeWordHidden(editorEl, from, to, notes, (el) => came(el) && !(held !== null && el.contains(held)))) return false;
1894
2541
  if (held && held !== editorEl && held.isConnected && held.childNodes.length === 0) held.appendChild(document.createElement('br'));
2542
+ return true;
1895
2543
  }
1896
2544
 
1897
2545
  // ── Pasted formatting ──
@@ -1904,8 +2552,58 @@
1904
2552
  const PASTED_SPACING = ['margin-top', 'margin-right', 'margin-bottom', 'margin-left', 'text-indent'];
1905
2553
  /** The elements in the editor just before a paste; what is not in it came from the paste. */
1906
2554
  let pastedOver: Set<Element> | null = null;
1907
- /** What the paste under way may lose, and how much text the document had before it. */
1908
- let pastedLoss: { notes: PasteNotes; from: number } | null = null;
2555
+ /** Whether what is coming in was picked up in this document, and dragged to another place in it. */
2556
+ let pastedOwn = false;
2557
+ /** Whether what is being dragged now was picked up in this document. */
2558
+ let draggedFromHere = false;
2559
+ /**
2560
+ * Every element a paste or a drop has brought in, with the style it was left with when it
2561
+ * was tidied, and whether it was the document's own (see pastedOwn). Redo writes back on
2562
+ * these the style the browser first gave them, with the margins that were taken off: an
2563
+ * element whose style is another by then is tidied again.
2564
+ * (Held, not looked up in a WeakMap, for the reason given at wordsLeft.)
2565
+ */
2566
+ const broughtIn = new Map<Element, { style: string | null; own: boolean }>();
2567
+ /** What the paste or the drop under way may lose, and how much text the document had before it. */
2568
+ let pastedLoss: { notes: PasteNotes; from: number; dropped?: boolean } | null = null;
2569
+
2570
+ /**
2571
+ * Take off the elements `came` accepts, the ones a paste or a drop brought in, their id and
2572
+ * the margins and first-line indents that change nothing (see above). One `own` accepts was
2573
+ * moved from another place in this document, and keeps its id unless another element has it
2574
+ * too. (Moved words lost theirs like pasted ones, though the id was in the document once,
2575
+ * as before: an application that marks elements with ids lost its marks to a drag.)
2576
+ */
2577
+ function tidySpacing(came: (el: Element) => boolean, own: (el: Element) => boolean = () => false): void {
2578
+ if (!editorEl) return;
2579
+ const all = Array.from(editorEl.querySelectorAll<HTMLElement>('*'));
2580
+ const timesUsed = new Map<string, number>();
2581
+ for (const el of all) if (el.id) timesUsed.set(el.id, (timesUsed.get(el.id) ?? 0) + 1);
2582
+ for (const el of all) {
2583
+ if (!came(el)) continue;
2584
+ const isOwn = own(el);
2585
+ if (el.hasAttribute('id') && !(isOwn && timesUsed.get(el.id) === 1)) {
2586
+ timesUsed.set(el.id, (timesUsed.get(el.id) ?? 1) - 1);
2587
+ el.removeAttribute('id');
2588
+ }
2589
+ tidyStyle(el);
2590
+ broughtIn.set(el, { style: el.getAttribute('style'), own: isOwn });
2591
+ }
2592
+ }
2593
+
2594
+ /** Take off one element the margins and the first-line indent that change nothing. */
2595
+ function tidyStyle(el: HTMLElement): void {
2596
+ if (!el.getAttribute('style')) return;
2597
+ const inline = !el.matches(`${INDENT_TARGETS}, li, table, thead, tbody, tfoot, tr, td, th, figcaption, hr`);
2598
+ for (const prop of PASTED_SPACING) {
2599
+ const value = el.style.getPropertyValue(prop);
2600
+ if (!value) continue;
2601
+ const shown = getComputedStyle(el).getPropertyValue(prop);
2602
+ el.style.removeProperty(prop);
2603
+ if (!inline && getComputedStyle(el).getPropertyValue(prop) !== shown) el.style.setProperty(prop, value);
2604
+ }
2605
+ if (!el.getAttribute('style')) el.removeAttribute('style');
2606
+ }
1909
2607
 
1910
2608
  function tidyPasted(before: Set<Element>): void {
1911
2609
  if (!editorEl) return;
@@ -1914,20 +2612,22 @@
1914
2612
  // What the paste brought is made safe as HTML from anywhere else is: a browser takes the
1915
2613
  // scripts out of a paste itself, but leaves a form, an <iframe>, or a block with
1916
2614
  // position: fixed that covers the page.
1917
- sanitizeTree(editorEl, (el) => !before.has(el));
1918
- for (const el of Array.from(editorEl.querySelectorAll<HTMLElement>('*'))) {
1919
- if (before.has(el)) continue;
1920
- el.removeAttribute('id');
1921
- if (!el.getAttribute('style')) continue;
1922
- const inline = !el.matches(`${INDENT_TARGETS}, li, table, thead, tbody, tfoot, tr, td, th, figcaption, hr`);
1923
- for (const prop of PASTED_SPACING) {
1924
- const value = el.style.getPropertyValue(prop);
1925
- if (!value) continue;
1926
- const shown = getComputedStyle(el).getPropertyValue(prop);
1927
- el.style.removeProperty(prop);
1928
- if (!inline && getComputedStyle(el).getPropertyValue(prop) !== shown) el.style.setProperty(prop, value);
1929
- }
1930
- if (!el.getAttribute('style')) el.removeAttribute('style');
2615
+ // (And if it cannot be made safe, none of it stays.)
2616
+ const came = (el: Element) => !before.has(el);
2617
+ const own = pastedOwn;
2618
+ pastedOwn = false;
2619
+ leftNow = [];
2620
+ const safe = makeSafe(came);
2621
+ const left = leftNow;
2622
+ leftNow = null;
2623
+ if (!safe) {
2624
+ showError(LEFT_OUT);
2625
+ return;
2626
+ }
2627
+ tidySpacing(came, () => own);
2628
+ if (left.length > 0) {
2629
+ const stayed = Array.from(editorEl.querySelectorAll('*')).filter(came);
2630
+ if (stayed.length > 0) pastesWithWords.push({ stayed, left, there: true });
1931
2631
  }
1932
2632
  // A picture copied with its text comes in by address (<img src="https://…">), or as data in
1933
2633
  // a format the RTF cannot carry (GIF, WebP, SVG) or larger than maxImageBytes. Only PNG or
@@ -2208,23 +2908,33 @@
2208
2908
  // ── Lifecycle ──
2209
2909
  onMount(() => {
2210
2910
  if (!editorEl) return;
2911
+ document.addEventListener('selectionchange', trackSelection);
2912
+ const stopTracking = () => document.removeEventListener('selectionchange', trackSelection);
2211
2913
  if (autosave) {
2914
+ let saved: string | null = null;
2212
2915
  try {
2213
- const saved = localStorage.getItem(storageKey);
2214
- if (saved) {
2215
- // A draft is HTML from outside like any other: anything that can write to this
2216
- // origin's storage can write it.
2217
- showDocument(saved);
2916
+ saved = localStorage.getItem(storageKey);
2917
+ } catch (e) {}
2918
+ if (saved) {
2919
+ // A draft is HTML from outside like any other: anything that can write to this
2920
+ // origin's storage can write it.
2921
+ if (showDocument(saved)) {
2218
2922
  updateCounts();
2219
- return;
2923
+ return stopTracking;
2220
2924
  }
2221
- } catch (e) {}
2925
+ // (A draft that cannot be shown was dropped without a word; it is said now, and
2926
+ // the content given is shown in its place.)
2927
+ showError('The draft kept in this browser could not be shown');
2928
+ }
2222
2929
  }
2223
2930
  // Always write the initial content prop so the div isn't empty.
2224
2931
  // {#html content} must NOT be used inside the contenteditable div —
2225
2932
  // Svelte would re-inject it on every reactive update, duplicating text.
2226
- showDocument(content || EMPTY_DOCUMENT);
2933
+ // (A document that cannot be shown leaves the editor empty and says so: the failure
2934
+ // used to go up through the component as it was made, and there was no editor.)
2935
+ if (!showDocument(content || EMPTY_DOCUMENT)) showError(NOT_SHOWN);
2227
2936
  updateCounts();
2937
+ return stopTracking;
2228
2938
  });
2229
2939
 
2230
2940
  // Suppress unused warning for importing state (used in template)
@@ -2317,6 +3027,8 @@
2317
3027
  onblur={() => (tabLeavesEditor = false)}
2318
3028
  onpaste={handlePaste}
2319
3029
  onclick={handleContentClick}
3030
+ ondragstart={() => (draggedFromHere = true)}
3031
+ ondragend={() => (draggedFromHere = false)}
2320
3032
  ondragover={handleDragOver}
2321
3033
  ondrop={handleDrop}
2322
3034
  data-placeholder={placeholder}