svelte-rtf-editor 1.11.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.
@@ -64,6 +64,10 @@
64
64
  * focus() — Focuses the editor.
65
65
  * exportFile(format) — Downloads as 'html', 'md', or 'rtf'.
66
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.
67
71
  */
68
72
 
69
73
  import { onMount } from 'svelte';
@@ -71,7 +75,7 @@
71
75
  import Modal from './Modal.svelte';
72
76
  import ImageOverlay from './ImageOverlay.svelte';
73
77
  import { htmlToMarkdown, downloadFile } from '../utils.js';
74
- import { keptMarks, pasteNotes, removeWordHidden, sanitizedNodes, sanitizeTree, type PasteNotes } from '../sanitize.js';
78
+ import { keptMarks, pasteHasWords, pasteNotes, removeWordHidden, sanitizedNodes, sanitizeTree, type PasteNotes } from '../sanitize.js';
75
79
  import { readRtfFile, DEFAULT_MAX_RTF_BYTES } from '../rtf-parser.js';
76
80
  import {
77
81
  htmlToRtf,
@@ -145,6 +149,9 @@
145
149
  */
146
150
  const EMPTY_DOCUMENT = '<p><br></p>';
147
151
 
152
+ /** The kinds of block the toolbar's list offers. */
153
+ const BLOCK_CHOICES = new Set(['p', 'h1', 'h2', 'h3', 'blockquote', 'pre']);
154
+
148
155
  /** The sizes, in points, the toolbar's size list offers unless `fontSizes` says otherwise. */
149
156
  const DEFAULT_FONT_SIZES = [8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 36];
150
157
  const NO_KEPT_ATTRIBUTES: string[] = [];
@@ -235,8 +242,14 @@
235
242
  if (editorEl) {
236
243
  selectedImage = null;
237
244
  documentReplaced();
238
- showDocument(html);
245
+ const shown = showDocument(html);
239
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
+ }
240
253
  if (autosave) scheduleAutoSave();
241
254
  }
242
255
  }
@@ -245,21 +258,169 @@
245
258
  * Put HTML from outside in the editor: made safe first, and with a line in every empty
246
259
  * paragraph, so it shows as the blank line the RTF writes for it. The nodes that were checked
247
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.)
248
267
  */
249
- function showDocument(html: string): void {
250
- if (!editorEl) return;
268
+ function showDocument(html: string): boolean {
269
+ if (!editorEl) return false;
251
270
  // An id the page already uses outside an editor is not the document's to take: see
252
271
  // sanitize.ts. (Another editor on the page may hold a document with the same ids.)
253
272
  const idTaken = (id: string) => {
254
273
  const owner = document.getElementById(id);
255
274
  return owner !== null && owner.closest('.ink-content') === null;
256
275
  };
257
- editorEl.replaceChildren(...sanitizedNodes(html, document, idTaken, keptNames));
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);
258
284
  for (const p of Array.from(editorEl.querySelectorAll('p'))) {
259
285
  if (p.childNodes.length === 0) p.appendChild(document.createElement('br'));
260
286
  }
287
+ return nodes !== null;
261
288
  }
262
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
+ }
398
+ }
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
+
263
424
  export function getMarkdown(): string {
264
425
  if (!editorEl) return '';
265
426
  return htmlToMarkdown(editorEl);
@@ -287,10 +448,8 @@
287
448
  selectedImage = null;
288
449
  documentReplaced();
289
450
  editorEl.innerHTML = EMPTY_DOCUMENT;
290
- clearTimeout(saveTimer);
291
- try { localStorage.removeItem(storageKey); } catch (e) {}
451
+ dropDraft();
292
452
  updateCounts();
293
- lastSaved = '';
294
453
  fireChange();
295
454
  }
296
455
  }
@@ -334,6 +493,14 @@
334
493
  indentUndo = [];
335
494
  pastedOver = null;
336
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;
337
504
  stopCopyFormat();
338
505
  }
339
506
 
@@ -352,19 +519,76 @@
352
519
  });
353
520
 
354
521
  // ── Selection helpers ──
355
- function saveSelection(): void {
522
+ /** Whether what is selected now, or the caret, is in the document. */
523
+ function selectionInEditor(): boolean {
356
524
  const sel = window.getSelection();
357
- if (sel && sel.rangeCount > 0) {
358
- savedSelection = sel.getRangeAt(0).cloneRange();
359
- }
525
+ return !!editorEl && !!sel && sel.rangeCount > 0 && editorEl.contains(sel.anchorNode) && editorEl.contains(sel.focusNode);
526
+ }
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();
360
537
  }
361
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
+ */
362
546
  function restoreSelection(): void {
363
- if (savedSelection) {
364
- const sel = window.getSelection();
365
- sel?.removeAllRanges();
366
- 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;
367
589
  }
590
+ savedSelection.setStart(range.startContainer, range.startOffset);
591
+ savedSelection.setEnd(range.endContainer, range.endOffset);
368
592
  }
369
593
 
370
594
  // ── Font size ──
@@ -542,6 +766,10 @@
542
766
 
543
767
  // ── Exec command ──
544
768
  function exec(cmd: string, value: string | null = null): void {
769
+ if (cmd === 'removeFormat') {
770
+ clearFormatting();
771
+ return;
772
+ }
545
773
  restoreSelection();
546
774
  editorEl?.focus();
547
775
  // Color commands require an actual text selection — a collapsed cursor
@@ -559,12 +787,296 @@
559
787
  hangAtCaret();
560
788
  return;
561
789
  }
562
- if (cmd === 'undo' && undoIndent()) return;
790
+ if (cmd === 'undo' && (undoIndent() || undoClear())) return;
791
+ if (cmd === 'redo' && redoClear()) return;
563
792
  document.execCommand(cmd, false, value ?? undefined);
564
793
  if (cmd === 'undo' || cmd === 'redo') afterHistory();
565
794
  updateToolbarState();
566
795
  }
567
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
+
568
1080
  // ── Indent ──
569
1081
  // Indent and Outdent move the paragraphs the selection touches by half an inch (48px, written
570
1082
  // to RTF as \li720) per press, as margin-left on each paragraph. The browser's own commands are
@@ -1151,8 +1663,7 @@
1151
1663
 
1152
1664
  const block = document.queryCommandValue('formatBlock');
1153
1665
  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';
1666
+ currentBlock = BLOCK_CHOICES.has(normalized) ? normalized : 'p';
1156
1667
 
1157
1668
  updateCounts();
1158
1669
  }
@@ -1209,8 +1720,9 @@
1209
1720
  // ── Auto-save ──
1210
1721
  let saveTimer: ReturnType<typeof setTimeout> | undefined;
1211
1722
 
1212
- function autoSaveNow(): void {
1213
- if (!editorEl || !autosave) return;
1723
+ /** Keep the draft in the browser's storage. */
1724
+ function keepDraft(): void {
1725
+ if (!editorEl) return;
1214
1726
  try {
1215
1727
  localStorage.setItem(storageKey, editorEl.innerHTML);
1216
1728
  lastSaved = `Saved ${new Date().toLocaleTimeString()}`;
@@ -1220,6 +1732,35 @@
1220
1732
  // fires so the host app can persist the content itself.
1221
1733
  lastSaved = 'Too large to auto-save in this browser';
1222
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();
1223
1764
  onsave?.({ html: editorEl.innerHTML });
1224
1765
  }
1225
1766
 
@@ -1228,18 +1769,38 @@
1228
1769
  saveTimer = setTimeout(autoSaveNow, 1000);
1229
1770
  }
1230
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
+
1231
1775
  // ── Input handler ──
1232
1776
  function handleInput(e?: Event): void {
1233
1777
  placeCopySourceBox();
1234
- 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') {
1235
1784
  tidyPasted(pastedOver);
1236
1785
  pastedOver = null;
1237
- }
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');
1238
1795
  indentUndo = [];
1239
- const kind = (e as InputEvent | undefined)?.inputType ?? '';
1240
- if (kind === 'historyUndo' || kind === 'historyRedo') {
1241
- 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();
1242
1801
  } else {
1802
+ // (And a Clear formatting before this edit is the browser's to undo from here on.)
1803
+ clearUndo = clearRedo = null;
1243
1804
  // An edit: what was undone can no longer be redone.
1244
1805
  sizeSteps = sizeSteps.slice(0, sizeStepsApplied);
1245
1806
  // What was typed at a caret after a size was chosen came in marked: give it the size.
@@ -1251,13 +1812,15 @@
1251
1812
  // selection here keeps Backspace editing that text instead of deleting a
1252
1813
  // still-selected image somewhere else in the document.
1253
1814
  selectedImage = null;
1815
+ // (Clear formatting says so itself, when the document is as it leaves it.)
1816
+ if (clearing) return;
1254
1817
  fireChange();
1255
- if (autosave) scheduleAutoSave();
1818
+ if (autosave && shown) scheduleAutoSave();
1256
1819
  }
1257
1820
 
1258
1821
  // ── Link modal ──
1259
1822
  function openLinkModal(): void {
1260
- saveSelection();
1823
+ keepForDialog();
1261
1824
  linkUrl = '';
1262
1825
  linkText = '';
1263
1826
  linkError = '';
@@ -1276,7 +1839,7 @@
1276
1839
  linkError = '';
1277
1840
  // Inserting changes the document outside an input event: earlier indent steps no longer undo.
1278
1841
  indentUndo = [];
1279
- restoreSelection();
1842
+ restoreFor(dialogSelection);
1280
1843
  editorEl?.focus();
1281
1844
 
1282
1845
  if (linkText) {
@@ -1315,7 +1878,7 @@
1315
1878
 
1316
1879
  // ── Images ──
1317
1880
  function openImageModal(): void {
1318
- saveSelection();
1881
+ keepForDialog();
1319
1882
  imageUrl = '';
1320
1883
  imageAlt = '';
1321
1884
  imageCaption = '';
@@ -1338,12 +1901,13 @@
1338
1901
  const url = imageUrl.trim();
1339
1902
  const caption = imageCaption.trim();
1340
1903
  const alt = imageAlt.trim();
1904
+ const at = dialogSelection;
1341
1905
 
1342
1906
  imageModalOpen = false;
1343
1907
  pendingImageFiles = [];
1344
1908
 
1345
1909
  if (files.length > 0) {
1346
- await insertImageFiles(files, caption, alt);
1910
+ await insertImageFiles(files, caption, alt, at);
1347
1911
  return;
1348
1912
  }
1349
1913
  if (!url) return;
@@ -1366,7 +1930,7 @@
1366
1930
  showError(UNREADABLE_MESSAGE);
1367
1931
  return;
1368
1932
  }
1369
- restoreSelection();
1933
+ restoreFor(at);
1370
1934
  editorEl?.focus();
1371
1935
  finishInsert(insertFigure(src, alt || caption, caption));
1372
1936
  // It displays either way, but only embedded bytes reach the RTF.
@@ -1503,8 +2067,11 @@
1503
2067
  if (autosave) scheduleAutoSave();
1504
2068
  }
1505
2069
 
1506
- /** Insert one figure per file, in the order they were given. */
1507
- 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> {
1508
2075
  if (files.length === 0) return;
1509
2076
  insertingImages = true;
1510
2077
  let inserted: { img: HTMLImageElement; after: HTMLElement } | null = null;
@@ -1513,7 +2080,9 @@
1513
2080
  for (const file of files) {
1514
2081
  try {
1515
2082
  const src = await fileToImageSrc(file, imageLimits());
1516
- restoreSelection();
2083
+ // (The next one goes after this one: the caret is put there.)
2084
+ restoreFor(at);
2085
+ at = null;
1517
2086
  editorEl?.focus();
1518
2087
  // A single image takes the description typed in the dialog; a batch
1519
2088
  // gets empty captions the user fills in under each picture.
@@ -1602,15 +2171,27 @@
1602
2171
  function handleDrop(e: DragEvent): void {
1603
2172
  if (readonly) return;
1604
2173
  const files = Array.from(e.dataTransfer?.files || []).filter((f) => f.type.startsWith('image/'));
1605
- 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
+ }
1606
2187
  e.preventDefault();
1607
2188
  editorEl?.focus();
1608
2189
  placeCaretAtPoint(e.clientX, e.clientY);
1609
2190
  void insertImageFiles(files);
1610
2191
  }
1611
2192
 
1612
- /** Move the caret under the pointer so a dropped image lands where it was dropped. */
1613
- 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 {
1614
2195
  const doc = document as Document & {
1615
2196
  caretPositionFromPoint?: (x: number, y: number) => { offsetNode: Node; offset: number } | null;
1616
2197
  caretRangeFromPoint?: (x: number, y: number) => Range | null;
@@ -1627,7 +2208,12 @@
1627
2208
  } else if (typeof doc.caretRangeFromPoint === 'function') {
1628
2209
  range = doc.caretRangeFromPoint(x, y);
1629
2210
  }
2211
+ return range;
2212
+ }
1630
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);
1631
2217
  if (!range || !editorEl?.contains(range.startContainer)) return;
1632
2218
  const sel = window.getSelection();
1633
2219
  sel?.removeAllRanges();
@@ -1651,9 +2237,14 @@
1651
2237
  documentReplaced();
1652
2238
  // (What the reader writes is safe as it stands; it goes the same way as any other
1653
2239
  // HTML so there is one way in.)
1654
- showDocument(html);
2240
+ const shown = showDocument(html);
1655
2241
  updateCounts();
2242
+ // (Shown or not, the document before it is gone, and the application is told so.)
1656
2243
  fireChange();
2244
+ if (!shown) {
2245
+ dropDraft();
2246
+ throw new Error(NOT_SHOWN);
2247
+ }
1657
2248
  if (autosave) scheduleAutoSave();
1658
2249
  onimport?.({ html });
1659
2250
  }
@@ -1678,8 +2269,11 @@
1678
2269
  if (mod && e.key === 'i') { e.preventDefault(); exec('italic'); }
1679
2270
  if (mod && e.key === 'u') { e.preventDefault(); exec('underline'); }
1680
2271
  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; }
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; }
1683
2277
  if (mod && e.key === ']') { e.preventDefault(); indentBlocks('indent'); return; }
1684
2278
  if (mod && e.key === '[') { e.preventDefault(); indentBlocks('outdent'); return; }
1685
2279
 
@@ -1842,7 +2436,12 @@
1842
2436
  .map((item) => item.getAsFile())
1843
2437
  .filter((file): file is File => file !== null);
1844
2438
 
1845
- 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)) {
1846
2445
  e.preventDefault();
1847
2446
  void insertImageFiles(files);
1848
2447
  return;
@@ -1857,27 +2456,39 @@
1857
2456
  }
1858
2457
  // The browser pastes next; the input event that follows tidies what came in.
1859
2458
  if (!readonly && editorEl) {
1860
- const snapshot = new Set(editorEl.querySelectorAll('*'));
1861
- pastedOver = snapshot;
2459
+ expectInsertion();
1862
2460
  // What the browser's paste may lose (see pasteNotes), and where the paste begins.
1863
- const notes = pasteNotes(e.clipboardData?.getData('text/html') ?? '');
2461
+ const notes = pasteNotes(html);
1864
2462
  const start = sel && sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
1865
2463
  pastedLoss =
1866
2464
  notes && start && editorEl.contains(start.startContainer)
1867
2465
  ? { notes, from: shownCharsBefore(start.startContainer, start.startOffset) }
1868
2466
  : 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);
1878
2467
  }
1879
2468
  }
1880
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
+
1881
2492
  /** How many characters that are not white space the document has before a place in it. */
1882
2493
  function shownCharsBefore(node: Node, offset: number): number {
1883
2494
  if (!editorEl) return 0;
@@ -1891,7 +2502,7 @@
1891
2502
  * Set right what the browser's paste changed before it could be looked at: Word's hidden
1892
2503
  * text shown as text, and a text box left empty.
1893
2504
  */
1894
- 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 {
1895
2506
  if (!editorEl) return;
1896
2507
  const areas = Array.from(editorEl.querySelectorAll('textarea')).filter((area) => !before.has(area));
1897
2508
  if (areas.length === loss.notes.textareas.length) {
@@ -1899,17 +2510,36 @@
1899
2510
  if (area.value === '') area.textContent = loss.notes.textareas[i];
1900
2511
  });
1901
2512
  }
1902
- // 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.
1903
2515
  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);
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;
1907
2534
  // A pasted element left with nothing in it goes, but not the one the caret is in: that
1908
2535
  // one becomes an empty line, to type in. (Taken out as well, a paste of hidden text
1909
2536
  // 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;
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;
1912
2541
  if (held && held !== editorEl && held.isConnected && held.childNodes.length === 0) held.appendChild(document.createElement('br'));
2542
+ return true;
1913
2543
  }
1914
2544
 
1915
2545
  // ── Pasted formatting ──
@@ -1922,8 +2552,58 @@
1922
2552
  const PASTED_SPACING = ['margin-top', 'margin-right', 'margin-bottom', 'margin-left', 'text-indent'];
1923
2553
  /** The elements in the editor just before a paste; what is not in it came from the paste. */
1924
2554
  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;
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
+ }
1927
2607
 
1928
2608
  function tidyPasted(before: Set<Element>): void {
1929
2609
  if (!editorEl) return;
@@ -1932,20 +2612,22 @@
1932
2612
  // What the paste brought is made safe as HTML from anywhere else is: a browser takes the
1933
2613
  // scripts out of a paste itself, but leaves a form, an <iframe>, or a block with
1934
2614
  // 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');
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 });
1949
2631
  }
1950
2632
  // A picture copied with its text comes in by address (<img src="https://…">), or as data in
1951
2633
  // a format the RTF cannot carry (GIF, WebP, SVG) or larger than maxImageBytes. Only PNG or
@@ -2226,23 +2908,33 @@
2226
2908
  // ── Lifecycle ──
2227
2909
  onMount(() => {
2228
2910
  if (!editorEl) return;
2911
+ document.addEventListener('selectionchange', trackSelection);
2912
+ const stopTracking = () => document.removeEventListener('selectionchange', trackSelection);
2229
2913
  if (autosave) {
2914
+ let saved: string | null = null;
2230
2915
  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);
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)) {
2236
2922
  updateCounts();
2237
- return;
2923
+ return stopTracking;
2238
2924
  }
2239
- } 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
+ }
2240
2929
  }
2241
2930
  // Always write the initial content prop so the div isn't empty.
2242
2931
  // {#html content} must NOT be used inside the contenteditable div —
2243
2932
  // Svelte would re-inject it on every reactive update, duplicating text.
2244
- 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);
2245
2936
  updateCounts();
2937
+ return stopTracking;
2246
2938
  });
2247
2939
 
2248
2940
  // Suppress unused warning for importing state (used in template)
@@ -2335,6 +3027,8 @@
2335
3027
  onblur={() => (tabLeavesEditor = false)}
2336
3028
  onpaste={handlePaste}
2337
3029
  onclick={handleContentClick}
3030
+ ondragstart={() => (draggedFromHere = true)}
3031
+ ondragend={() => (draggedFromHere = false)}
2338
3032
  ondragover={handleDragOver}
2339
3033
  ondrop={handleDrop}
2340
3034
  data-placeholder={placeholder}