svelte-rtf-editor 1.13.0 → 1.15.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.
@@ -88,11 +88,15 @@
88
88
  import { onMount } from 'svelte';
89
89
  import Toolbar from './Toolbar.svelte';
90
90
  import Modal from './Modal.svelte';
91
- import ImageOverlay from './ImageOverlay.svelte';
91
+ import ImageOverlay, { type PicturePlace } from './ImageOverlay.svelte';
92
92
  import { htmlToMarkdown, downloadFile } from '../utils.js';
93
93
  import { keptMarks, pasteHasWords, pasteNotes, pasteWithoutFrames, removeWordHidden, sanitizedNodes, sanitizeTree, type PasteNotes } from '../sanitize.js';
94
94
  import { givePastedPictures, pastePictures, type PastePictures } from '../paste-pictures.js';
95
95
  import { readRtfFile, DEFAULT_MAX_RTF_BYTES } from '../rtf-parser.js';
96
+ import { createHistory, type DocumentHistory } from '../history.js';
97
+ import { GAPPED_ROW_STYLE, MOST_GAP_PT, isGapCell, isPlainCell, lengthTwips, pointsOf } from '../picture-rows.js';
98
+ import { toggleList, nestItems, unnestItems, leaveList, inEmptyItem, atItemStart, listKindAt, type ListKind } from '../lists.js';
99
+ import { LEAST_MARKER_GAP, MOST_MARKER_GAP, markerGapTwips, markItems, withoutMarkers, MARKER_ATTRIBUTE } from '../list-markers.js';
96
100
  import {
97
101
  htmlToRtf,
98
102
  estimateRtfBytes,
@@ -103,7 +107,8 @@
103
107
  fontKey,
104
108
  normalizeFontSize,
105
109
  DEFAULT_FONT_FAMILY,
106
- DEFAULT_FONT_SIZE
110
+ DEFAULT_FONT_SIZE,
111
+ LEAST_LINES
107
112
  } from '../rtf-writer.js';
108
113
  import {
109
114
  fileToImageSrc,
@@ -225,6 +230,8 @@
225
230
  let currentBlock: string = $state('p');
226
231
  /** The size of the text at the caret, in points, for the toolbar. */
227
232
  let currentFontSize: number | null = $state(null);
233
+ /** The spacing of the paragraph at the caret, as its own style sets it: see spacingOf. */
234
+ let currentSpacing: ParagraphSpacing = $state({ line: null, before: 0, after: 0 });
228
235
  /** The font at the selection, by its key: '' for the document font, null where it has more than one. */
229
236
  let currentFont: string | null = $state('');
230
237
 
@@ -232,12 +239,19 @@
232
239
  bold: false,
233
240
  italic: false,
234
241
  underline: false,
235
- strikeThrough: false
242
+ strikeThrough: false,
243
+ bulletList: false,
244
+ numberedList: false
236
245
  });
237
246
 
238
247
  // Modal state
239
248
  let linkModalOpen: boolean = $state(false);
240
249
  let imageModalOpen: boolean = $state(false);
250
+ let tableModalOpen: boolean = $state(false);
251
+ let tableRows: number | null = $state(3);
252
+ let tableColumns: number | null = $state(3);
253
+ let tableBorders: boolean = $state(true);
254
+ let tableHeader: boolean = $state(false);
241
255
  let linkUrl: string = $state('');
242
256
  let linkError: string = $state('');
243
257
  let linkText: string = $state('');
@@ -260,7 +274,85 @@
260
274
 
261
275
  // ── Public API (exposed via bind:this) ──
262
276
  export function getHTML(): string {
263
- return editorEl?.innerHTML || '';
277
+ return documentHtml();
278
+ }
279
+
280
+ /** What a paragraph cannot hold in HTML: a parser that meets one ends the paragraph there. */
281
+ const BLOCKS = 'ul, ol, div, p, table, blockquote, pre, h1, h2, h3, h4, h5, h6, hr, figure';
282
+
283
+ /**
284
+ * Put what no paragraph can hold beside the paragraph it is in, in the document itself.
285
+ *
286
+ * A browser leaves a block inside a paragraph in more than one way: Firefox leaves the
287
+ * paragraphs of a paste inside the paragraph they were pasted in, and Chromium's and
288
+ * Safari's list commands left the list inside the paragraph it was made from. No HTML can
289
+ * say that. Read again, by an application that keeps what getHTML() or onsave gave it, or
290
+ * by the editor's own Undo, it is an empty paragraph, the block, and another empty
291
+ * paragraph, and the RTF of that has an empty line before and after. So each such block is
292
+ * put where a parser would put it, with no empty paragraph around it; what the paragraph
293
+ * held before a block and after it are paragraphs of their own.
294
+ *
295
+ * `live` says it is the document being edited: the caret stays in the words it was in, and
296
+ * an empty line it is in stays to be typed in.
297
+ */
298
+ function liftBlocks(root: HTMLElement, live: boolean): void {
299
+ if (!root.querySelector(`p > :is(${BLOCKS})`)) return;
300
+ const sel = live ? window.getSelection() : null;
301
+ const holds = (el: Element) => (el.textContent ?? '').trim() !== '' || !!el.querySelector(':not(br)');
302
+ const caretIn = (el: Element) => !!sel && sel.rangeCount > 0 && (el.contains(sel.anchorNode) || el.contains(sel.focusNode));
303
+ for (const paragraph of Array.from(root.querySelectorAll('p'))) {
304
+ if (!root.contains(paragraph) || !Array.from(paragraph.children).some((child) => child.matches(BLOCKS))) continue;
305
+ // A caret that is said by the paragraph itself (before its third child) is at that child.
306
+ const caretAt = sel && sel.isCollapsed && sel.anchorNode === paragraph ? { child: paragraph.childNodes[sel.anchorOffset] ?? null } : null;
307
+ const parts: Element[] = [];
308
+ const lines = new Set<Element>();
309
+ let line: Element | null = null;
310
+ for (const child of Array.from(paragraph.childNodes)) {
311
+ if (child instanceof Element && child.matches(BLOCKS)) {
312
+ line = null;
313
+ parts.push(child);
314
+ } else {
315
+ if (!line) {
316
+ line = paragraph.cloneNode(false) as Element;
317
+ lines.add(line);
318
+ parts.push(line);
319
+ }
320
+ line.appendChild(child);
321
+ }
322
+ }
323
+ // (A line with nothing in it is the paragraph the block was put in: the empty line
324
+ // the browser left before it or after it. It is no paragraph; a comment in it,
325
+ // which is an application's own mark, stays where it was.)
326
+ const kept = parts.flatMap((part): Node[] =>
327
+ !lines.has(part) || holds(part) || caretIn(part) ? [part] : Array.from(part.childNodes).filter((node) => node.nodeType === Node.COMMENT_NODE)
328
+ );
329
+ paragraph.replaceWith(...kept);
330
+ if (!caretAt || !sel) continue;
331
+ const at = caretAt.child?.isConnected ? caretAt.child : kept[kept.length - 1];
332
+ if (!at) continue;
333
+ const caret = document.createRange();
334
+ if (at instanceof Text) caret.setStart(at, caretAt.child === at ? 0 : at.length);
335
+ else caret.selectNodeContents(at);
336
+ caret.collapse(caretAt.child === at);
337
+ sel.removeAllRanges();
338
+ sel.addRange(caret);
339
+ }
340
+ }
341
+
342
+ /**
343
+ * The document as HTML that says what the document is: see liftBlocks. (The document is
344
+ * kept that way as it is edited. This is for one that is not, at the moment it is asked
345
+ * for: it is never handed out as HTML that reads back as another document.)
346
+ */
347
+ function documentHtml(): string {
348
+ if (!editorEl) return '';
349
+ const marked = editorEl.querySelector(`[${MARKER_ATTRIBUTE}]`) !== null;
350
+ if (!marked && !editorEl.querySelector(`p > :is(${BLOCKS})`)) return editorEl.innerHTML;
351
+ const copy = editorEl.cloneNode(true) as HTMLElement;
352
+ liftBlocks(copy, false);
353
+ // (The markers the editor draws a list with a gap by are the screen's, not the document's.)
354
+ if (marked) withoutMarkers(copy);
355
+ return copy.innerHTML;
264
356
  }
265
357
 
266
358
  export function getText(): string {
@@ -272,6 +364,7 @@
272
364
  selectedImage = null;
273
365
  documentReplaced();
274
366
  const shown = showDocument(html);
367
+ newDocument();
275
368
  updateCounts();
276
369
  if (!shown) {
277
370
  // The caller is told, and the editor is empty: see showDocument.
@@ -366,6 +459,7 @@
366
459
  } catch {
367
460
  editorEl.innerHTML = EMPTY_DOCUMENT;
368
461
  documentReplaced();
462
+ newDocument();
369
463
  clearTimeout(saveTimer);
370
464
  showError(NOT_SHOWN);
371
465
  return false;
@@ -477,6 +571,7 @@
477
571
  selectedImage = null;
478
572
  documentReplaced();
479
573
  editorEl.innerHTML = EMPTY_DOCUMENT;
574
+ newDocument();
480
575
  dropDraft();
481
576
  updateCounts();
482
577
  fireChange();
@@ -491,7 +586,7 @@
491
586
  if (!editorEl) return;
492
587
  switch (format) {
493
588
  case 'html': {
494
- const html = `<!DOCTYPE html>\n<html lang="en">\n<head><meta charset="UTF-8"><title>Document</title></head>\n<body>\n${editorEl.innerHTML}\n</body>\n</html>`;
589
+ const html = `<!DOCTYPE html>\n<html lang="en">\n<head><meta charset="UTF-8"><title>Document</title></head>\n<body>\n${documentHtml()}\n</body>\n</html>`;
495
590
  downloadFile('document.html', html, 'text/html');
496
591
  break;
497
592
  }
@@ -515,11 +610,11 @@
515
610
 
516
611
  /**
517
612
  * The whole document is about to be replaced (setHTML, clear, an RTF import): nothing that
518
- * points into the old one may act on the new one. Indent steps no longer undo, the Copy format
519
- * brush is put down, and a paste that inserted nothing is forgotten.
613
+ * points into the old one may act on the new one. The Copy format brush is put down, and a
614
+ * paste that inserted nothing is forgotten. (And once the new one is shown, the history is
615
+ * forgotten: see newDocument.)
520
616
  */
521
617
  function documentReplaced(): void {
522
- indentUndo = [];
523
618
  pastedOver = null;
524
619
  pastedLoss = null;
525
620
  pastedPictures = null;
@@ -531,10 +626,17 @@
531
626
  broughtIn.clear();
532
627
  pastesWithWords.length = 0;
533
628
  hiddenTaken.length = 0;
534
- clearUndo = clearRedo = clearPast = null;
535
629
  stopCopyFormat();
536
630
  }
537
631
 
632
+ /**
633
+ * Another document is shown: Undo does not lead back into the one before it. (It is one
634
+ * patient's report, and this another's.)
635
+ */
636
+ function newDocument(): void {
637
+ history?.reset();
638
+ }
639
+
538
640
  // The frame around the paragraph copied from follows it when the text reflows: typing is caught
539
641
  // by the input handler, and a picture finishing loading or the editor changing width by this.
540
642
  $effect(() => {
@@ -631,26 +733,14 @@
631
733
  // (<font style="font-size:14pt">), which is what the RTF writer reads. Only attributes are
632
734
  // changed, never the elements, so the browser's undo still finds what it made.
633
735
  //
634
- // Undo puts back what the browser itself recorded, which is right: the element goes, or gets
635
- // back the size it had. Redo is not: the browser does its own step again, the mark for size 7
636
- // and nothing after it, and the text came back at 36 pt. So each change of size is remembered
637
- // here with the size every element was given, and after a redo the elements that are marked
638
- // again are given theirs again.
639
- //
640
- // And undo is only right where the browser recorded something to put back. It records the
641
- // size it takes off an element, not the one given here afterwards. So a <font> element is
642
- // never left without a size of its own: where the text is to have the size of the text around
643
- // it, the size stated is 1em, which is that size. The writer reads 1em as no size.
736
+ // A <font> element is never left without a size of its own: where the text is to have the
737
+ // size of the text around it, the size stated is 1em, which is that size. The writer reads
738
+ // 1em as no size. (The browser's Undo put back only a size its command had taken off an
739
+ // element, which is why one was always there; Undo is the editor's own now, see history.ts,
740
+ // and the HTML of a document is left as it has been.)
644
741
  const SIZE_MARK = '7';
645
742
  /** The size that is the size of the text around: what "no size of its own" is written as. */
646
743
  const SIZE_AROUND = '1em';
647
- /** One change of size: the elements it sized, each with the font-size it was given. */
648
- type SizeStep = Map<HTMLElement, string>;
649
- /** The changes of size made, in order; those from `sizeStepsApplied` on were undone and can be redone. */
650
- let sizeSteps: SizeStep[] = [];
651
- let sizeStepsApplied = 0;
652
- /** Every element this editor has given a size: a mark on one of these is the browser redoing a step. */
653
- const sizedHere = new WeakSet<Element>();
654
744
  /** The size chosen and not yet given to an element: a caret has no text to carry it until something is typed. */
655
745
  let pendingSize: number | null = null;
656
746
  /** Elements that were marked size 7 before the command (pasted that way): not ours to change. */
@@ -671,10 +761,9 @@
671
761
  const markedElements = (): HTMLElement[] =>
672
762
  editorEl ? Array.from(editorEl.querySelectorAll<HTMLElement>(`font[size="${SIZE_MARK}"]`)) : [];
673
763
 
674
- /** Give the elements the command marked the size that was chosen, and remember the step. */
764
+ /** Give the elements the command marked the size that was chosen. */
675
765
  function applyPendingSize(): void {
676
766
  if (!editorEl || pendingSize === null) return;
677
- const step: SizeStep = new Map();
678
767
  for (const font of markedElements()) {
679
768
  if (markedBefore.has(font)) continue;
680
769
  sizeElement(font, SIZE_AROUND);
@@ -682,39 +771,6 @@
682
771
  // size, a heading to the heading's), it stays at the size around it: the text then
683
772
  // follows the document's size, as text that was never sized does.
684
773
  if (shownSize(font) !== pendingSize) sizeElement(font, `${pendingSize}pt`);
685
- step.set(font, font.style.fontSize);
686
- sizedHere.add(font);
687
- }
688
- if (step.size === 0) return;
689
- // A new change: what was undone before it can no longer be redone.
690
- sizeSteps = [...sizeSteps.slice(0, sizeStepsApplied), step];
691
- sizeStepsApplied = sizeSteps.length;
692
- }
693
-
694
- /** Whether a change of size is in the document as it was made: every element there, with its size. */
695
- function stepStands(step: SizeStep | undefined): boolean {
696
- if (!step) return false;
697
- for (const [font, fontSize] of step) {
698
- if (!font.isConnected || font.getAttribute('size') === SIZE_MARK || font.style.fontSize !== fontSize) return false;
699
- }
700
- return true;
701
- }
702
-
703
- /** After an undo or a redo: follow which changes of size are in the document, and finish a redone one. */
704
- function afterHistory(): void {
705
- const next = sizeSteps[sizeStepsApplied];
706
- const marked = markedElements().filter((font) => sizedHere.has(font));
707
- if (marked.length > 0) {
708
- // The browser redid its part of a change of size. (A mark with no step to go with it
709
- // should not happen; it is then taken off, and the text has the size around it,
710
- // which is better than 36 pt.)
711
- for (const font of marked) sizeElement(font, next?.get(font) ?? SIZE_AROUND);
712
- if (next) sizeStepsApplied++;
713
- } else if (stepStands(next)) {
714
- // Redone, and nothing was marked: the step only made elements, which came back as they were.
715
- sizeStepsApplied++;
716
- } else if (sizeStepsApplied > 0 && !stepStands(sizeSteps[sizeStepsApplied - 1])) {
717
- sizeStepsApplied--;
718
774
  }
719
775
  }
720
776
 
@@ -742,8 +798,7 @@
742
798
  if (typeof points !== 'number' || !Number.isFinite(points) || points <= 0) return;
743
799
  restoreSelection();
744
800
  editorEl.focus();
745
- // The document changes outside an input event: earlier indent steps no longer undo.
746
- indentUndo = [];
801
+ history?.step();
747
802
  const size = normalizeFontSize(points);
748
803
  // Nothing to change: no step is made that would undo to the same thing.
749
804
  if (selectionHasSize(size)) {
@@ -757,7 +812,7 @@
757
812
  if (!font.style.fontSize && !markedBefore.has(font)) font.style.fontSize = SIZE_AROUND;
758
813
  }
759
814
  pendingSize = size;
760
- document.execCommand('fontSize', false, SIZE_MARK);
815
+ browserCommand('fontSize', false, SIZE_MARK);
761
816
  applyPendingSize();
762
817
  // With text selected the size is on it now. At a caret it waits for the typing.
763
818
  const selection = window.getSelection();
@@ -822,7 +877,7 @@
822
877
  }
823
878
  // (Given the document font as the screen has it, Chromium and Safari take the font off
824
879
  // the text; Firefox writes it, which the writer and the font list read as no font.)
825
- document.execCommand('fontName', false, choice ? choice.css : screenFontFamily);
880
+ browserCommand('fontName', false, choice ? choice.css : screenFontFamily);
826
881
  // With text selected the font is on it now. At a caret it waits for the typing.
827
882
  pendingFont = selection.isCollapsed ? wanted : null;
828
883
  updateToolbarState();
@@ -931,8 +986,15 @@
931
986
  clearFormatting();
932
987
  return;
933
988
  }
989
+ if (cmd === 'undo' || cmd === 'redo') {
990
+ stepBack(cmd === 'undo');
991
+ return;
992
+ }
934
993
  restoreSelection();
935
994
  editorEl?.focus();
995
+ // Each command is a step of its own in the history: what was typed before it is the
996
+ // step before.
997
+ history?.step();
936
998
  // Color commands require an actual text selection — a collapsed cursor
937
999
  // would silently apply the color to nothing (or to subsequently typed
938
1000
  // text), which causes accidental color spans to appear in the RTF output.
@@ -948,11 +1010,149 @@
948
1010
  hangAtCaret();
949
1011
  return;
950
1012
  }
951
- if (cmd === 'undo' && (undoIndent() || undoClear())) return;
952
- if (cmd === 'redo' && redoClear()) return;
953
- document.execCommand(cmd, false, value ?? undefined);
954
- if (cmd === 'undo' || cmd === 'redo') afterHistory();
1013
+ if (cmd === 'markerGap') {
1014
+ const n = value === null || value === '' ? null : Number(value);
1015
+ if (n !== null && !Number.isFinite(n)) return;
1016
+ setListMarkerGap(n);
1017
+ return;
1018
+ }
1019
+ if (cmd === 'lineSpacing' || cmd === 'spaceBefore' || cmd === 'spaceAfter') {
1020
+ const n = value === null || value === '' ? null : Number(value);
1021
+ if (n !== null && !Number.isFinite(n)) return;
1022
+ if (cmd === 'lineSpacing') applySpacing({ line: n });
1023
+ else applySpacing(cmd === 'spaceBefore' ? { before: n } : { after: n });
1024
+ return;
1025
+ }
1026
+ if (cmd === 'insertUnorderedList' || cmd === 'insertOrderedList') {
1027
+ listCommand(cmd === 'insertOrderedList' ? 'ol' : 'ul');
1028
+ return;
1029
+ }
1030
+ browserCommand(cmd, false, value ?? undefined);
1031
+ updateToolbarState();
1032
+ }
1033
+
1034
+ // ── Undo and Redo ──
1035
+ // The editor's own (see history.ts): the browser's history knows nothing of a picture or a
1036
+ // table put in, a picture moved or an indent, and its Undo went past them to the typing
1037
+ // before. Every way to it leads here: the toolbar, the keys, and the browser's own menu.
1038
+ let history: DocumentHistory | null = null;
1039
+
1040
+ /** Undo the last step, or redo the one last undone. Returns whether there was one. */
1041
+ function stepBack(undo: boolean): boolean {
1042
+ if (readonly || !editorEl || !history) return false;
1043
+ let shown = true;
1044
+ const done = (undo ? history.undo : history.redo)(() => {
1045
+ // Nothing that points into the document as it was may act on it as it is now.
1046
+ selectedImage = null;
1047
+ pendingSize = null;
1048
+ pendingFont = null;
1049
+ pastedOver = null;
1050
+ pastedLoss = null;
1051
+ pastedPictures = null;
1052
+ commentsBefore = null;
1053
+ savedSelection = null;
1054
+ dialogSelection = null;
1055
+ if (copySource && !copySource.isConnected) stopCopyFormat();
1056
+ // What is put back was checked when it was first in the document; it is HTML that
1057
+ // was kept as text all the same, and is checked as any other is.
1058
+ shown = checkDocument();
1059
+ });
1060
+ if (!done) return false;
1061
+ // (A document that could not be checked is not shown, and has no history.)
1062
+ if (!shown) history.reset();
1063
+ if (document.activeElement !== editorEl && selectionInEditor()) editorEl.focus({ preventScroll: true });
1064
+ placeCopySourceBox();
1065
+ overlayRef?.reposition();
955
1066
  updateToolbarState();
1067
+ keepCaretInSight();
1068
+ fireChange();
1069
+ if (autosave && shown) scheduleAutoSave();
1070
+ return true;
1071
+ }
1072
+
1073
+ /** Undo the last step: what was typed, a command, a picture or a table put in, a picture moved. */
1074
+ export function undo(): boolean {
1075
+ return stepBack(true);
1076
+ }
1077
+
1078
+ /** Redo the step last undone. */
1079
+ export function redo(): boolean {
1080
+ return stepBack(false);
1081
+ }
1082
+
1083
+ /**
1084
+ * A command of the browser's, run by the editor. Safari says what such a command is about
1085
+ * to do as it says a key: heard as one, it ended the step the editor's command was in the
1086
+ * middle of, and a Clear formatting was two steps to undo, the first of them half done. So
1087
+ * what is said while one runs is not input to the history.
1088
+ */
1089
+ let inCommand = 0;
1090
+ function browserCommand(cmd: string, ui = false, value?: string): boolean {
1091
+ inCommand++;
1092
+ try {
1093
+ return document.execCommand(cmd, ui, value);
1094
+ } finally {
1095
+ inCommand--;
1096
+ }
1097
+ }
1098
+
1099
+ /**
1100
+ * Take back the browser's own last command, inside a command of the editor's that tried
1101
+ * it and found it wanting. (The browser's history is used for nothing else.)
1102
+ */
1103
+ function browserUndo(): void {
1104
+ browserCommand('undo');
1105
+ }
1106
+
1107
+ /** What the browser is about to do to the document: the history is told, and Undo and Redo are the editor's. */
1108
+ function handleBeforeInput(e: InputEvent): void {
1109
+ const kind = e.inputType;
1110
+ if (inCommand > 0) return;
1111
+ if (kind === 'historyUndo' || kind === 'historyRedo') {
1112
+ e.preventDefault();
1113
+ stepBack(kind === 'historyUndo');
1114
+ return;
1115
+ }
1116
+ if (readonly) return;
1117
+ // Words dragged from one place in the document to another are two inputs, the words
1118
+ // taken out and the words dropped: one move, and one step. (As two, the first Undo took
1119
+ // the dropped words out, and they were nowhere until the second.)
1120
+ const dropAfterTaking = kind === 'insertFromDrop' && dragTaken;
1121
+ dragTaken = kind === 'deleteByDrag';
1122
+ if (dropAfterTaking) return;
1123
+ // (Text an input method composes, and what Safari makes of it at the end, is typing.)
1124
+ const typed = /^insert(Text|CompositionText|ReplacementText|FromComposition)$/.test(kind) || kind === 'deleteCompositionText';
1125
+ const deleted = /^delete(Content|Word|SoftLine|HardLine)/.test(kind);
1126
+ history?.typing(typed ? 'insert' : deleted ? 'delete' : null);
1127
+ }
1128
+
1129
+ /** The last input was words dragged in the document taken out where they were: the drop that follows is the same step. */
1130
+ let dragTaken = false;
1131
+
1132
+ // ── Lists ──
1133
+ // The editor's own (see lists.ts): each browser's list command made something else of the
1134
+ // same click, and none of them puts an item under the one before it.
1135
+
1136
+ /** The toolbar's list buttons: make the lines selected a list of this kind, or paragraphs again. */
1137
+ function listCommand(kind: ListKind): void {
1138
+ if (readonly || !editorEl) return;
1139
+ if (toggleList(editorEl, window.getSelection(), kind)) indentChanged();
1140
+ else updateToolbarState();
1141
+ }
1142
+
1143
+ /**
1144
+ * Enter in an item with nothing in it, and Backspace at the start of an item, take the item
1145
+ * one step out of its list: out of a list within a list, and then a paragraph. Returns
1146
+ * whether the key was that.
1147
+ */
1148
+ function leaveListAt(e: KeyboardEvent): boolean {
1149
+ if (readonly || !editorEl || e.isComposing || e.ctrlKey || e.metaKey || e.altKey || e.shiftKey) return false;
1150
+ const sel = window.getSelection();
1151
+ if (e.key === 'Enter' ? !inEmptyItem(editorEl, sel) : e.key !== 'Backspace' || !atItemStart(editorEl, sel)) return false;
1152
+ e.preventDefault();
1153
+ history?.step();
1154
+ if (leaveList(editorEl, sel)) indentChanged();
1155
+ return true;
956
1156
  }
957
1157
 
958
1158
  // ── Clear formatting ──
@@ -960,8 +1160,7 @@
960
1160
  // Safari take a paragraph's alignment and first-line indent with its color; Firefox leaves
961
1161
  // the color on the paragraph, and takes out the element an application's mark is on; Safari
962
1162
  // leaves a size where it is. So the command is used for what only it can do, which is to
963
- // take the <b>, <i> and <font> elements out with an entry in the browser's own history
964
- // (taken out by the editor instead, the next Undo in Safari empties the document). What is
1163
+ // take the <b>, <i> and <font> elements out, cutting them where the selection ends. What is
965
1164
  // written on the elements is the editor's to change: before the command, the looks of the
966
1165
  // text are taken off every element whose text is all selected, and after it, whatever the
967
1166
  // command took off that is not a look of the text is written back.
@@ -982,49 +1181,9 @@
982
1181
  const LOOKS = ['style', 'color', 'size', 'face'] as const;
983
1182
  type Looks = Record<(typeof LOOKS)[number], string | null>;
984
1183
 
985
- /** One Clear formatting: what was written on each element before and after, to put back. */
986
- interface ClearStep {
987
- before: Map<Element, Looks>;
988
- after: Map<Element, Looks>;
989
- /** The browser's command changed something, and has an entry in its history. */
990
- native: boolean;
991
- /** The document as the editor handed it to the command: where the browser's Undo of the command leads back to. */
992
- pre: string;
993
- /** The document as the step left it. */
994
- cleared: string;
995
- /** The document as it is now, the step done or undone: it is undone, or redone, only from there. */
996
- html: string;
997
- }
998
- let clearUndo: ClearStep | null = null;
999
- let clearRedo: ClearStep | null = null;
1000
- /** The last one made, also after more was typed: the browser's Undo may yet lead back to it. */
1001
- let clearPast: ClearStep | null = null;
1002
1184
  /** The input events of the editor's own commands, while it clears: what they leave is not yet the document. */
1003
1185
  let clearing = false;
1004
1186
 
1005
- /**
1006
- * After the browser's own Undo. A Clear formatting is the editor's to undo only while nothing
1007
- * else has been done. After that the browser undoes its command with everything else, and
1008
- * knows nothing of what the editor took off the elements: bold was back, and the color was
1009
- * not. Where its Undo has led back to the document as the command was given it, the rest is
1010
- * put back here. A step the command left nothing of (a paragraph's color and no more) has no
1011
- * such place to be led back to: it is the editor's to undo again once the document is as
1012
- * that step left it, which is when what was typed after it has been undone.
1013
- */
1014
- function afterUndoOfClear(): void {
1015
- const step = clearPast;
1016
- if (!step || !editorEl || clearing) return;
1017
- const now = editorEl.innerHTML;
1018
- if (step.native && step.pre !== step.cleared) {
1019
- if (now !== step.pre) return;
1020
- writeLooks(step.before);
1021
- clearUndo = null;
1022
- clearRedo = { ...step, html: editorEl.innerHTML };
1023
- } else if (now === step.cleared) {
1024
- clearUndo = { ...step, html: now };
1025
- }
1026
- }
1027
-
1028
1187
  const looksOf = (el: Element): Looks => ({
1029
1188
  style: el.getAttribute('style'),
1030
1189
  color: el.getAttribute('color'),
@@ -1032,17 +1191,6 @@
1032
1191
  face: el.getAttribute('face')
1033
1192
  });
1034
1193
 
1035
- function writeLooks(looks: Map<Element, Looks>): void {
1036
- for (const [el, wanted] of looks) {
1037
- if (!el.isConnected) continue;
1038
- for (const name of LOOKS) {
1039
- if (el.getAttribute(name) === wanted[name]) continue;
1040
- if (wanted[name] === null) el.removeAttribute(name);
1041
- else el.setAttribute(name, wanted[name]);
1042
- }
1043
- }
1044
- }
1045
-
1046
1194
  /** Whether all the text of an element is selected. (One with no text is, if it is in the selection.) */
1047
1195
  function allSelected(range: Range, el: Element): boolean {
1048
1196
  const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
@@ -1096,12 +1244,12 @@
1096
1244
  // At a caret there is nothing to clear but what was chosen for the words typed next.
1097
1245
  pendingSize = null;
1098
1246
  pendingFont = null;
1099
- document.execCommand('removeFormat');
1247
+ history?.step();
1248
+ browserCommand('removeFormat');
1100
1249
  updateToolbarState();
1101
1250
  return;
1102
1251
  }
1103
- // The document changes outside an input event: earlier indent steps no longer undo.
1104
- indentUndo = [];
1252
+ history?.step();
1105
1253
  const range = sel.getRangeAt(0);
1106
1254
  const touched = Array.from(editorEl.querySelectorAll<HTMLElement>('*')).filter((el) => range.intersectsNode(el));
1107
1255
  const before = new Map(touched.map((el) => [el, looksOf(el)]));
@@ -1126,7 +1274,7 @@
1126
1274
  removeFormat(selected, kept, closed);
1127
1275
  const lost = kept.filter((el) => !el.isConnected || el.textContent !== marks.get(el));
1128
1276
  if (lost.length > 0) {
1129
- document.execCommand('undo');
1277
+ browserUndo();
1130
1278
  if (lost.some((el) => el.tagName === 'SPAN')) spansAreTakenOut = true;
1131
1279
  closed = Array.from(new Set([...closed, ...lost])).filter((el) => el.isConnected);
1132
1280
  removeFormat(selected, kept.filter((el) => el.isConnected), closed);
@@ -1151,9 +1299,6 @@
1151
1299
  for (const el of whole) if (el.isConnected) plain(el);
1152
1300
  const after = new Map(touched.map((el) => [el, looksOf(el)]));
1153
1301
  const changed = native || touched.some((el) => LOOKS.some((name) => before.get(el)![name] !== after.get(el)![name]));
1154
- const cleared = editorEl.innerHTML;
1155
- clearUndo = clearPast = changed ? { before, after, native, pre: html, cleared, html: cleared } : null;
1156
- clearRedo = null;
1157
1302
  updateToolbarState();
1158
1303
  if (!changed) return;
1159
1304
  fireChange();
@@ -1186,7 +1331,7 @@
1186
1331
  const was = closed.map((el) => el.getAttribute('contenteditable'));
1187
1332
  for (const el of kept) el.setAttribute(KEEP_MARK, '');
1188
1333
  for (const el of closed) el.setAttribute('contenteditable', 'false');
1189
- document.execCommand('removeFormat');
1334
+ browserCommand('removeFormat');
1190
1335
  // (Also off the copy the command makes of an element it cuts in two.)
1191
1336
  for (const el of [...kept, ...Array.from(editorEl?.querySelectorAll(`[${KEEP_MARK}]`) ?? [])]) el.removeAttribute(KEEP_MARK);
1192
1337
  closed.forEach((el, i) => {
@@ -1195,57 +1340,12 @@
1195
1340
  });
1196
1341
  }
1197
1342
 
1198
- /** Undo the last Clear formatting, if nothing has changed since. */
1199
- function undoClear(): boolean {
1200
- const step = clearUndo;
1201
- clearUndo = null;
1202
- if (!step || !editorEl || editorEl.innerHTML !== step.html) return false;
1203
- clearing = true;
1204
- try {
1205
- if (step.native) document.execCommand('undo');
1206
- } finally {
1207
- clearing = false;
1208
- }
1209
- writeLooks(step.before);
1210
- // (Safari may take the step before back with it, and that may be a change of size.)
1211
- afterHistory();
1212
- clearRedo = { ...step, html: editorEl.innerHTML };
1213
- clearChanged();
1214
- return true;
1215
- }
1216
-
1217
- /** Do it again, if nothing has changed since it was undone. */
1218
- function redoClear(): boolean {
1219
- const step = clearRedo;
1220
- clearRedo = null;
1221
- if (!step || !editorEl || editorEl.innerHTML !== step.html) return false;
1222
- // (In the order it was done: the command read the elements as the editor had left them.)
1223
- writeLooks(step.after);
1224
- clearing = true;
1225
- try {
1226
- if (step.native) document.execCommand('redo');
1227
- } finally {
1228
- clearing = false;
1229
- }
1230
- writeLooks(step.after);
1231
- clearUndo = { ...step, html: editorEl.innerHTML };
1232
- clearChanged();
1233
- return true;
1234
- }
1235
-
1236
- function clearChanged(): void {
1237
- updateToolbarState();
1238
- fireChange();
1239
- if (autosave) scheduleAutoSave();
1240
- }
1241
-
1242
1343
  // ── Indent ──
1243
1344
  // Indent and Outdent move the paragraphs the selection touches by half an inch (48px, written
1244
1345
  // to RTF as \li720) per press, as margin-left on each paragraph. The browser's own commands are
1245
1346
  // not used: Chromium's Outdent strips the first paragraph to loose text ("one<br>"), and the
1246
1347
  // browsers disagree on the markup. Only a style changes (and a line of loose text gets a
1247
- // paragraph of its own), so earlier typing stays undoable; the editor keeps its own undo for
1248
- // these steps until the next edit.
1348
+ // paragraph of its own). Each press is a step of the editor's history.
1249
1349
  //
1250
1350
  // The right indent and the hanging indent move by the same step, on a paragraph (a <p>, or a
1251
1351
  // <div> that holds text) outside a table cell, which is where the RTF writer sends them:
@@ -1272,23 +1372,20 @@
1272
1372
  /** CSS lengths a margin is written in, in px. */
1273
1373
  const PX_PER_UNIT: Record<string, number> = { px: 1, pt: 96 / 72, in: 96, cm: 96 / 2.54, mm: 96 / 25.4 };
1274
1374
 
1275
- /** One block an Indent or Outdent changed, and how to put it back. */
1276
- interface IndentChange {
1277
- el: HTMLElement;
1278
- before: string | null;
1279
- after: string | null;
1280
- /** The block is a paragraph this step made around loose text, and the <br> that ended it. */
1281
- wrapped: { br: HTMLBRElement | null } | null;
1282
- /** The paragraph's data-rtf-tab-stops before a step that changed it. */
1283
- stops?: { before: string | null; after: string | null };
1284
- }
1285
- let indentUndo: IndentChange[][] = [];
1286
-
1287
1375
  function indentBlocks(cmd: IndentCommand): void {
1288
1376
  if (readonly || !editorEl) return;
1289
1377
  editorEl.focus();
1290
1378
  const sel = window.getSelection();
1291
1379
  if (!sel || sel.rangeCount === 0 || !sel.anchorNode || !editorEl.contains(sel.anchorNode)) return;
1380
+ history?.step();
1381
+ // In a list, an indent puts the items under the item before them, and an outdent
1382
+ // takes them out from under it, as a word processor's do. (The first item of a list
1383
+ // has none before it, and an item of a list in no other list is under none: there
1384
+ // the list itself is moved, as a paragraph is.)
1385
+ if ((cmd === 'indent' && nestItems(editorEl, sel)) || (cmd === 'outdent' && unnestItems(editorEl, sel))) {
1386
+ indentChanged();
1387
+ return;
1388
+ }
1292
1389
  const { anchorNode, anchorOffset, focusNode, focusOffset } = sel;
1293
1390
  const wrapped = new Map<HTMLElement, HTMLBRElement | null>();
1294
1391
  const targets = indentTargets(sel.getRangeAt(0), cmd, wrapped);
@@ -1297,9 +1394,8 @@
1297
1394
  if (wrapped.size > 0 && anchorNode instanceof Text && focusNode instanceof Text && anchorNode.isConnected && focusNode.isConnected) {
1298
1395
  sel.setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset);
1299
1396
  }
1300
- const step: IndentChange[] = [];
1397
+ let moved = wrapped.size > 0;
1301
1398
  for (const el of targets) {
1302
- const before = el.getAttribute('style');
1303
1399
  const left = marginLeftPx(el);
1304
1400
  const first = textIndentPx(el);
1305
1401
  const setPx = (prop: 'marginLeft' | 'marginRight' | 'textIndent', px: number) => {
@@ -1329,11 +1425,189 @@
1329
1425
  setPx('textIndent', first + back);
1330
1426
  }
1331
1427
  if (!el.getAttribute('style')) el.removeAttribute('style');
1332
- const br = wrapped.get(el);
1333
- step.push({ el, before, after: el.getAttribute('style'), wrapped: br === undefined ? null : { br } });
1428
+ moved = true;
1334
1429
  }
1335
- if (step.length === 0) return;
1336
- indentUndo.push(step);
1430
+ if (!moved) return;
1431
+ indentChanged();
1432
+ }
1433
+
1434
+ // ── Spacing ──
1435
+ // The space before and after a paragraph, and between its lines, as a style on each
1436
+ // paragraph the selection touches: a paragraph, a heading, and a picture (which has the
1437
+ // space around it, and no lines). It is what the RTF writer sends:
1438
+ //
1439
+ // | Set | Style on the paragraph | RTF |
1440
+ // |----------------------|------------------------|-------------------|
1441
+ // | 6 pt before | margin-top: 6pt | \sb120 |
1442
+ // | 6 pt after | margin-bottom: 6pt | \sa120 |
1443
+ // | lines 1.5 apart | line-height: 1.5 | \sl360\slmult1 |
1444
+ //
1445
+ // A list item is spaced as one paragraph: the style is on the <li>, as Word's list
1446
+ // paragraphs carry it. In a table cell, the paragraph the caret is in: a line typed straight
1447
+ // into the cell is made a paragraph first. Each change is one step of the editor's history,
1448
+ // as an indent is.
1449
+
1450
+ /** A paragraph's spacing as its own style sets it: lines apart (null: the editor's own), and points before and after. */
1451
+ interface ParagraphSpacing {
1452
+ line: number | null;
1453
+ before: number;
1454
+ after: number;
1455
+ /** In a list: the gap after its markers, in points (null: it sets none). Left out elsewhere. */
1456
+ gap?: number | null;
1457
+ }
1458
+ /** The most that is set: ten lines, and a space of two inches. */
1459
+ const MOST_LINES = 10;
1460
+ const MOST_SPACE_PT = 144;
1461
+
1462
+ /** A margin a style sets, in points; 0 where it sets none, or one that cannot be read. */
1463
+ function spacePt(value: string): number {
1464
+ const m = value.trim().toLowerCase().match(/^(\d+(?:\.\d+)?|\.\d+)(px|pt|in|cm|mm)$/);
1465
+ return m ? Math.round(((parseFloat(m[1]) * PX_PER_UNIT[m[2]]) / PX_PER_UNIT.pt) * 100) / 100 : 0;
1466
+ }
1467
+
1468
+ function spacingOf(el: HTMLElement): ParagraphSpacing {
1469
+ const line = el.style.lineHeight.trim();
1470
+ const lines = /^(\d+(\.\d+)?|\.\d+)%?$/.test(line) ? parseFloat(line) / (line.endsWith('%') ? 100 : 1) : null;
1471
+ return { line: lines !== null && lines > 0 ? Math.round(lines * 100) / 100 : null, before: spacePt(el.style.marginTop), after: spacePt(el.style.marginBottom) };
1472
+ }
1473
+
1474
+ /** The paragraph, heading, list item or picture the caret is in, where spacing can be set on it. */
1475
+ function spacedBlockAtCaret(): HTMLElement | null {
1476
+ if (!editorEl) return null;
1477
+ const node = selectedImage ?? window.getSelection()?.anchorNode ?? null;
1478
+ if (!node || !editorEl.contains(node)) return null;
1479
+ // (A picture in a table cell is the cell's: no paragraph is spaced there.)
1480
+ if (selectedImage?.closest('td, th')) return null;
1481
+ return spacedBlockFor(node);
1482
+ }
1483
+
1484
+ /**
1485
+ * The block that is spaced where a node is: the list item it is in (the innermost), or the
1486
+ * paragraph, heading or picture it is in, in a table cell too. Null where there is none,
1487
+ * as for a line typed straight into the document or a cell, which is made one to be spaced.
1488
+ */
1489
+ function spacedBlockFor(node: Node): HTMLElement | null {
1490
+ if (!editorEl || node === editorEl || !editorEl.contains(node)) return null;
1491
+ const el = node instanceof Element ? node : node.parentElement;
1492
+ if (!el) return null;
1493
+ const cell = el.closest('td, th');
1494
+ const inScope = (b: Element | null): b is HTMLElement =>
1495
+ b instanceof HTMLElement && b !== editorEl && editorEl!.contains(b) && (!cell || cell.contains(b));
1496
+ const item = el.closest('li');
1497
+ if (inScope(item)) return item;
1498
+ const block = el.closest<HTMLElement>(INDENT_TARGETS);
1499
+ if (!inScope(block)) return null;
1500
+ return isPlainParagraph(block) || /^(H[1-6]|FIGURE)$/.test(block.tagName) ? block : null;
1501
+ }
1502
+
1503
+ function applySpacing(change: { line?: number | null; before?: number | null; after?: number | null }): void {
1504
+ if (readonly || !editorEl) return;
1505
+ const valid = (n: number | null | undefined, most: number) => n == null || (typeof n === 'number' && Number.isFinite(n) && n >= 0 && n <= most);
1506
+ // (Lines closer than LEAST_LINES are printed over each other: no spacing to set.)
1507
+ if (!valid(change.line, MOST_LINES) || (change.line != null && change.line < LEAST_LINES) || !valid(change.before, MOST_SPACE_PT) || !valid(change.after, MOST_SPACE_PT)) return;
1508
+ // A picture that is selected is spaced as the paragraph it is.
1509
+ const figure = selectedImage?.closest<HTMLElement>('figure') ?? null;
1510
+ // (Not one in a table cell, where no paragraph is spaced: nor is the paragraph the
1511
+ // caret was last in, which is not what is selected.)
1512
+ if (selectedImage?.closest('td, th')) return;
1513
+ const wrapped = new Map<HTMLElement, HTMLBRElement | null>();
1514
+ let targets: HTMLElement[];
1515
+ history?.step();
1516
+ if (figure && editorEl.contains(figure)) {
1517
+ targets = [figure];
1518
+ } else {
1519
+ restoreSelection();
1520
+ editorEl.focus();
1521
+ const sel = window.getSelection();
1522
+ if (!sel || sel.rangeCount === 0 || !sel.anchorNode || !editorEl.contains(sel.anchorNode)) return;
1523
+ const { anchorNode, anchorOffset, focusNode, focusOffset } = sel;
1524
+ targets = indentTargets(sel.getRangeAt(0), 'spacing', wrapped);
1525
+ if (wrapped.size > 0 && anchorNode instanceof Text && focusNode instanceof Text && anchorNode.isConnected && focusNode.isConnected) {
1526
+ sel.setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset);
1527
+ }
1528
+ }
1529
+ const points = (n: number) => `${Math.round(n * 100) / 100}pt`;
1530
+ let spaced = false;
1531
+ for (const el of targets) {
1532
+ const before = el.getAttribute('style');
1533
+ // (A picture has no lines to space.)
1534
+ if (change.line !== undefined && el.tagName !== 'FIGURE') el.style.lineHeight = change.line === null ? '' : String(Math.round(change.line * 100) / 100);
1535
+ if (change.before !== undefined) el.style.marginTop = change.before ? points(change.before) : '';
1536
+ if (change.after !== undefined) el.style.marginBottom = change.after ? points(change.after) : '';
1537
+ if (!el.getAttribute('style')) el.removeAttribute('style');
1538
+ if (el.getAttribute('style') !== before || wrapped.has(el)) spaced = true;
1539
+ }
1540
+ if (!spaced) return;
1541
+ indentChanged();
1542
+ overlayRef?.reposition();
1543
+ }
1544
+
1545
+ /**
1546
+ * Set how far apart the lines are in the paragraphs the selection touches, in lines: 1, 1.15,
1547
+ * 1.5, 2. `null` takes the setting off, and the lines are as far apart as the editor's own
1548
+ * style has them. Also what the toolbar's spacing list calls.
1549
+ */
1550
+ export function setLineSpacing(lines: number | null): void {
1551
+ applySpacing({ line: lines });
1552
+ }
1553
+
1554
+ /**
1555
+ * Set the space before and after the paragraphs the selection touches, in points; a picture
1556
+ * that is selected is spaced the same way. `0` or `null` takes a space off, and a side that
1557
+ * is left out stays as it is: `setParagraphSpacing({ after: 6 })`.
1558
+ */
1559
+ export function setParagraphSpacing(space: { before?: number | null; after?: number | null }): void {
1560
+ if (!space || typeof space !== 'object') return;
1561
+ applySpacing({ before: space.before, after: space.after });
1562
+ }
1563
+
1564
+ // ── The gap after a list's markers ──
1565
+ // How far an item's text starts from its bullet or number: the list's text indent, as Word
1566
+ // has it, written as the list's padding-left (see markerGapTwips). The marker stays where
1567
+ // it is; the text moves. The editor draws the markers of such a list itself (markItems).
1568
+
1569
+ /** The list the caret is in: the innermost, for an item of a list within a list. */
1570
+ function listAtCaret(): HTMLElement | null {
1571
+ const node = window.getSelection()?.anchorNode ?? null;
1572
+ if (!editorEl || !node || !editorEl.contains(node)) return null;
1573
+ const item = (node instanceof Element ? node : node.parentElement)?.closest('li');
1574
+ const list = item?.parentElement;
1575
+ return list && editorEl.contains(list) && /^(UL|OL)$/.test(list.tagName) ? list : null;
1576
+ }
1577
+
1578
+ /**
1579
+ * Set how far the text of the items of the lists the selection touches starts from their
1580
+ * bullet or number, in points: 6 to 144. `null` takes the setting off, and the list has the
1581
+ * quarter inch (18 pt) it always had. Also what the toolbar's spacing list calls.
1582
+ */
1583
+ export function setListMarkerGap(points: number | null): void {
1584
+ if (readonly || !editorEl) return;
1585
+ if (points !== null && (typeof points !== 'number' || !Number.isFinite(points) || points * 20 < LEAST_MARKER_GAP || points * 20 > MOST_MARKER_GAP)) return;
1586
+ restoreSelection();
1587
+ editorEl.focus();
1588
+ const sel = window.getSelection();
1589
+ if (!sel || sel.rangeCount === 0 || !sel.anchorNode || !editorEl.contains(sel.anchorNode)) return;
1590
+ const range = sel.getRangeAt(0);
1591
+ const lists: HTMLElement[] = [];
1592
+ const add = (node: Node) => {
1593
+ const item = (node instanceof Element ? node : node.parentElement)?.closest('li');
1594
+ const list = item?.parentElement;
1595
+ if (list && editorEl!.contains(list) && /^(UL|OL)$/.test(list.tagName) && !lists.includes(list)) lists.push(list);
1596
+ };
1597
+ add(range.startContainer);
1598
+ const walker = document.createTreeWalker(editorEl, NodeFilter.SHOW_TEXT);
1599
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) if (range.intersectsNode(n) && (n.textContent ?? '').trim()) add(n);
1600
+ if (lists.length === 0) return;
1601
+ history?.step();
1602
+ let changed = false;
1603
+ for (const list of lists) {
1604
+ const before = list.getAttribute('style');
1605
+ list.style.paddingLeft = points === null ? '' : `${Math.round(points * 100) / 100}pt`;
1606
+ if (!list.getAttribute('style')) list.removeAttribute('style');
1607
+ if (list.getAttribute('style') !== before) changed = true;
1608
+ }
1609
+ if (!changed) return;
1610
+ markItems(editorEl);
1337
1611
  indentChanged();
1338
1612
  }
1339
1613
 
@@ -1403,6 +1677,7 @@
1403
1677
  const offset = caret.startOffset;
1404
1678
  const el = node instanceof Element ? node : node.parentElement;
1405
1679
  if (!el || el.closest('td, th, li, pre, figure, h1, h2, h3, h4, h5, h6')) return;
1680
+ history?.step();
1406
1681
  const x = caretLeft(caret);
1407
1682
  if (x === null) return;
1408
1683
 
@@ -1466,7 +1741,6 @@
1466
1741
  const after = block.getAttribute('style');
1467
1742
  const stopsAfter = block.getAttribute(TAB_STOPS);
1468
1743
  if (!wrapped && after === before && stopsAfter === stopsBefore) return;
1469
- indentUndo.push([{ el: block, before, after, wrapped, stops: { before: stopsBefore, after: stopsAfter } }]);
1470
1744
  indentChanged();
1471
1745
  }
1472
1746
 
@@ -1536,8 +1810,12 @@
1536
1810
  /** The tab stop that goes with a hanging indent: tab-size on screen, \tx in the RTF. */
1537
1811
  tabSize: string;
1538
1812
  tabStops: string;
1813
+ /** The space before and after it, and between its lines. */
1814
+ marginTop: string;
1815
+ marginBottom: string;
1816
+ lineHeight: string;
1539
1817
  }
1540
- const NO_FORMAT: ParagraphFormat = { textAlign: '', marginLeft: '', marginRight: '', textIndent: '', tabSize: '', tabStops: '' };
1818
+ const NO_FORMAT: ParagraphFormat = { textAlign: '', marginLeft: '', marginRight: '', textIndent: '', tabSize: '', tabStops: '', marginTop: '', marginBottom: '', lineHeight: '' };
1541
1819
  const PAINT_BLOCKS = 'p, div, h1, h2, h3, h4, h5, h6';
1542
1820
 
1543
1821
  /** 'pick': waiting for the paragraph to copy from. 'apply': each click applies the format. */
@@ -1584,7 +1862,10 @@
1584
1862
  marginRight: el.style.marginRight,
1585
1863
  textIndent: el.style.textIndent,
1586
1864
  tabSize: el.style.tabSize,
1587
- tabStops: el.getAttribute(TAB_STOPS) ?? ''
1865
+ tabStops: el.getAttribute(TAB_STOPS) ?? '',
1866
+ marginTop: el.style.marginTop,
1867
+ marginBottom: el.style.marginBottom,
1868
+ lineHeight: el.style.lineHeight
1588
1869
  };
1589
1870
  }
1590
1871
 
@@ -1635,6 +1916,7 @@
1635
1916
  return;
1636
1917
  }
1637
1918
  if (block && block === copySource) return;
1919
+ history?.step();
1638
1920
  let target = block;
1639
1921
  let wrapped: { br: HTMLBRElement | null } | null = null;
1640
1922
  if (!target && loose) {
@@ -1659,6 +1941,10 @@
1659
1941
  if (indents) {
1660
1942
  target.style.marginRight = copiedFormat.marginRight;
1661
1943
  target.style.textIndent = copiedFormat.textIndent;
1944
+ // (Spacing goes where the writer sends it: the same blocks.)
1945
+ target.style.marginTop = copiedFormat.marginTop;
1946
+ target.style.marginBottom = copiedFormat.marginBottom;
1947
+ target.style.lineHeight = copiedFormat.lineHeight;
1662
1948
  }
1663
1949
  if (whole) {
1664
1950
  target.style.tabSize = copiedFormat.tabSize;
@@ -1669,33 +1955,10 @@
1669
1955
  const after = target.getAttribute('style');
1670
1956
  const stopsAfter = target.getAttribute(TAB_STOPS);
1671
1957
  if (!wrapped && after === before && stopsAfter === stopsBefore) return;
1672
- indentUndo.push([{ el: target, before, after, wrapped, stops: { before: stopsBefore, after: stopsAfter } }]);
1673
1958
  indentChanged();
1674
1959
  placeCopySourceBox();
1675
1960
  }
1676
1961
 
1677
- /** Undo the last Indent or Outdent, if nothing has changed since. */
1678
- function undoIndent(): boolean {
1679
- const step = indentUndo.pop();
1680
- if (!step) return false;
1681
- // Content replaced or edited since (setHTML, an import, a link): the step no longer applies.
1682
- if (step.some(({ el, after }) => !el.isConnected || el.getAttribute('style') !== after)) {
1683
- indentUndo = [];
1684
- return false;
1685
- }
1686
- for (const { el, before, wrapped, stops } of step) {
1687
- if (before === null) el.removeAttribute('style');
1688
- else el.setAttribute('style', before);
1689
- if (stops) {
1690
- if (stops.before === null) el.removeAttribute(TAB_STOPS);
1691
- else el.setAttribute(TAB_STOPS, stops.before);
1692
- }
1693
- if (wrapped) undoWrap(el, wrapped);
1694
- }
1695
- indentChanged();
1696
- return true;
1697
- }
1698
-
1699
1962
  function indentChanged(): void {
1700
1963
  placeCopySourceBox();
1701
1964
  updateToolbarState();
@@ -1712,7 +1975,7 @@
1712
1975
  */
1713
1976
  function indentTargets(
1714
1977
  range: Range,
1715
- cmd: IndentCommand,
1978
+ cmd: IndentCommand | 'spacing',
1716
1979
  wrapped: Map<HTMLElement, HTMLBRElement | null>
1717
1980
  ): HTMLElement[] {
1718
1981
  if (!editorEl) return [];
@@ -1731,6 +1994,15 @@
1731
1994
  const item = el.closest('li');
1732
1995
  const closest = el.closest(INDENT_TARGETS);
1733
1996
  const block = inScope(item) ? item.parentElement : inScope(closest) ? closest : null;
1997
+ if (cmd === 'spacing') {
1998
+ const spaced = spacedBlockFor(node);
1999
+ if (spaced) return spaced;
2000
+ // (Nor is a block that holds others, a list or a quotation, spaced as one.)
2001
+ if (inScope(closest) || inScope(item)) return null;
2002
+ const made = wrapLooseLine(node);
2003
+ if (made) wrapped.set(made.p, made.br);
2004
+ return made?.p ?? null;
2005
+ }
1734
2006
  if (cmd !== 'indent' && cmd !== 'outdent') {
1735
2007
  if (cell) return null;
1736
2008
  if (inScope(block)) return isPlainParagraph(block) ? block : null;
@@ -1805,7 +2077,8 @@
1805
2077
  function setBlock(tag: string): void {
1806
2078
  restoreSelection();
1807
2079
  editorEl?.focus();
1808
- document.execCommand('formatBlock', false, tag);
2080
+ history?.step();
2081
+ browserCommand('formatBlock', false, tag);
1809
2082
  updateToolbarState();
1810
2083
  }
1811
2084
 
@@ -1816,12 +2089,23 @@
1816
2089
  saveSelection();
1817
2090
  currentFontSize = sizeAtSelection();
1818
2091
  currentFont = fontList.length > 0 ? fontAtSelection() : '';
2092
+ const spaced = spacedBlockAtCaret();
2093
+ currentSpacing = spaced ? spacingOf(spaced) : { line: null, before: 0, after: 0 };
2094
+ const gapped = listAtCaret();
2095
+ if (gapped) {
2096
+ const twips = markerGapTwips(gapped);
2097
+ currentSpacing.gap = twips === null ? null : twips / 20;
2098
+ }
1819
2099
 
2100
+ // The list the caret's item is in: the innermost, for an item of a list within a list.
2101
+ const listKind = editorEl ? listKindAt(editorEl, window.getSelection()) : null;
1820
2102
  formatState = {
1821
2103
  bold: document.queryCommandState('bold'),
1822
2104
  italic: document.queryCommandState('italic'),
1823
2105
  underline: document.queryCommandState('underline'),
1824
- strikeThrough: document.queryCommandState('strikeThrough')
2106
+ strikeThrough: document.queryCommandState('strikeThrough'),
2107
+ bulletList: listKind === 'ul',
2108
+ numberedList: listKind === 'ol'
1825
2109
  };
1826
2110
 
1827
2111
  const block = document.queryCommandValue('formatBlock');
@@ -1905,7 +2189,7 @@
1905
2189
  let value: { v: T } | null = null;
1906
2190
  return () => (value ??= { v: read() }).v;
1907
2191
  };
1908
- const html = once(() => el?.innerHTML || '');
2192
+ const html = once(() => (el ? documentHtml() : ''));
1909
2193
  const text = once(() => el?.innerText || '');
1910
2194
  const estimate = once(() => (el ? estimateRtfBytes(el, options) : 0));
1911
2195
  onchange({
@@ -1924,7 +2208,7 @@
1924
2208
  function keepDraft(): void {
1925
2209
  if (!editorEl) return;
1926
2210
  try {
1927
- localStorage.setItem(storageKey, editorEl.innerHTML);
2211
+ localStorage.setItem(storageKey, documentHtml());
1928
2212
  lastSaved = `Saved ${new Date().toLocaleTimeString()}`;
1929
2213
  } catch (e) {
1930
2214
  // Embedded images can push a document past the localStorage quota. Say
@@ -1948,7 +2232,7 @@
1948
2232
  function autoSaveNow(): void {
1949
2233
  if (!editorEl || !autosave) return;
1950
2234
  keepDraft();
1951
- onsave?.({ html: editorEl.innerHTML });
2235
+ onsave?.({ html: documentHtml() });
1952
2236
  }
1953
2237
 
1954
2238
  /**
@@ -1961,7 +2245,7 @@
1961
2245
  // The save that was waiting is this one.
1962
2246
  clearTimeout(saveTimer);
1963
2247
  if (autosave) keepDraft();
1964
- onsave?.({ html: editorEl.innerHTML });
2248
+ onsave?.({ html: documentHtml() });
1965
2249
  }
1966
2250
 
1967
2251
  function scheduleAutoSave(): void {
@@ -1976,14 +2260,16 @@
1976
2260
  function handleInput(e?: Event): void {
1977
2261
  placeCopySourceBox();
1978
2262
  const kind = (e as InputEvent | undefined)?.inputType ?? '';
1979
- const history = kind === 'historyUndo' || kind === 'historyRedo';
2263
+ // (The editor's own Undo and Redo do not come this way. These are the browser's, where
2264
+ // one could not be stopped: what it puts back is checked as it always was.)
2265
+ const browserHistory = kind === 'historyUndo' || kind === 'historyRedo';
1980
2266
  // (Words dragged from one place in the document to another are first taken out where
1981
2267
  // they were, which is an input event of its own: what was dropped has not come in yet.)
1982
2268
  let shown = true;
1983
2269
  if (pastedOver && kind !== 'deleteByDrag') {
1984
2270
  tidyPasted(pastedOver);
1985
2271
  pastedOver = null;
1986
- } else if (history || MARKUP_FROM_OUTSIDE.has(kind)) {
2272
+ } else if (browserHistory || MARKUP_FROM_OUTSIDE.has(kind)) {
1987
2273
  // Undo and Redo put back what the browser remembers, not what the editor made of it:
1988
2274
  // Redo after a paste brings back the frame that was taken out of the paste, the
1989
2275
  // style that was taken off what stayed, and Word's hidden text as words. And a drop
@@ -1992,20 +2278,12 @@
1992
2278
  shown = checkDocument();
1993
2279
  }
1994
2280
  followPastes(kind === 'historyUndo');
1995
- indentUndo = [];
1996
- if (history) {
1997
- // (Not in the middle of a Clear formatting or of its Undo: the sizes are then not
1998
- // yet back on the elements. And what the editor puts back first, for the same reason.)
1999
- if (kind === 'historyUndo') afterUndoOfClear();
2000
- if (!clearing) afterHistory();
2001
- } else {
2002
- // (And a Clear formatting before this edit is the browser's to undo from here on.)
2003
- clearUndo = clearRedo = null;
2004
- // An edit: what was undone can no longer be redone.
2005
- sizeSteps = sizeSteps.slice(0, sizeStepsApplied);
2006
- // What was typed at a caret after a size was chosen came in marked: give it the size.
2007
- applyPendingSize();
2008
- }
2281
+ // What was typed at a caret after a size was chosen came in marked: give it the size.
2282
+ if (!browserHistory) applyPendingSize();
2283
+ // (Not between the commands of a Clear formatting, which is not yet the document.)
2284
+ if (editorEl && !clearing) liftBlocks(editorEl, true);
2285
+ // (What the editor made of the input is part of the same step as the input.)
2286
+ history?.typed();
2009
2287
  pendingSize = null;
2010
2288
  pendingFont = null;
2011
2289
  updateToolbarState();
@@ -2038,8 +2316,7 @@
2038
2316
  return;
2039
2317
  }
2040
2318
  linkError = '';
2041
- // Inserting changes the document outside an input event: earlier indent steps no longer undo.
2042
- indentUndo = [];
2319
+ history?.step();
2043
2320
  restoreFor(dialogSelection);
2044
2321
  editorEl?.focus();
2045
2322
 
@@ -2057,7 +2334,7 @@
2057
2334
  sel.addRange(range);
2058
2335
  }
2059
2336
  } else {
2060
- document.execCommand('createLink', false, linkUrl.trim());
2337
+ browserCommand('createLink', false, linkUrl.trim());
2061
2338
  }
2062
2339
  linkModalOpen = false;
2063
2340
  updateCounts();
@@ -2077,6 +2354,93 @@
2077
2354
  act();
2078
2355
  }
2079
2356
 
2357
+ // ── Tables ──
2358
+ // A table is put in from a dialog: its rows and columns, whether its cells have borders,
2359
+ // and whether its first row is a header. It is written the way rtfToHtml reads a table
2360
+ // back, so that a document is the same after it is saved and opened again: the cells
2361
+ // share the width of the table, and a border is a style on each cell, which is what the
2362
+ // RTF writer sends (\clbrdrt\brdrs\brdrw15 and so on). A table with no borders has none
2363
+ // in the RTF either; the editor draws a faint line around its cells while it is edited.
2364
+ const MOST_TABLE_ROWS = 50;
2365
+ const MOST_TABLE_COLUMNS = 12;
2366
+ const TABLE_STYLE = 'border-collapse:collapse;width:100%;margin:4px 0';
2367
+ const CELL_BORDER = 'border:1px solid;';
2368
+
2369
+ /**
2370
+ * A column's share of the width of a table of `count` equal columns, as the reader gives
2371
+ * it: the edges, each rounded to a hundredth of a percent, and a cell the difference of two.
2372
+ */
2373
+ function columnShare(column: number, count: number): string {
2374
+ const edge = (k: number) => Math.round((k / count) * 10000) / 100;
2375
+ return (edge(column + 1) - edge(column)).toFixed(2).replace(/0$/, '');
2376
+ }
2377
+
2378
+ function openTableModal(): void {
2379
+ keepForDialog();
2380
+ tableModalOpen = true;
2381
+ }
2382
+
2383
+ function applyTable(): void {
2384
+ const at = dialogSelection;
2385
+ tableModalOpen = false;
2386
+ restoreFor(at);
2387
+ insertTable(tableRows ?? 0, tableColumns ?? 0, { borders: tableBorders, header: tableHeader });
2388
+ }
2389
+
2390
+ /**
2391
+ * Put a table of empty cells in after the paragraph the caret is in (in its place where
2392
+ * that is empty), and the caret in its first cell. `borders` (default true) gives every
2393
+ * cell a border, which is written to the RTF; `header` makes the first row header cells.
2394
+ * At most 50 rows and 12 columns. Also what the toolbar's Insert table dialog calls.
2395
+ */
2396
+ export function insertTable(rows: number, columns: number, options: { borders?: boolean; header?: boolean } = {}): void {
2397
+ if (readonly || !editorEl) return;
2398
+ const whole = (n: unknown, most: number) => (typeof n === 'number' && Number.isFinite(n) ? Math.max(1, Math.min(most, Math.floor(n))) : 0);
2399
+ const rowCount = whole(rows, MOST_TABLE_ROWS);
2400
+ const columnCount = whole(columns, MOST_TABLE_COLUMNS);
2401
+ if (rowCount < 1 || columnCount < 1 || rows < 1 || columns < 1) return;
2402
+ const borders = options?.borders !== false;
2403
+ const header = options?.header === true;
2404
+ editorEl.focus();
2405
+ history?.step();
2406
+
2407
+ const table = document.createElement('table');
2408
+ table.setAttribute('style', TABLE_STYLE);
2409
+ const body = document.createElement('tbody');
2410
+ for (let r = 0; r < rowCount; r++) {
2411
+ const row = document.createElement('tr');
2412
+ for (let c = 0; c < columnCount; c++) {
2413
+ const head = header && r === 0;
2414
+ const cell = document.createElement(head ? 'th' : 'td');
2415
+ const width = `width:${columnShare(c, columnCount)}%`;
2416
+ // (A header cell says how it is aligned: a browser centers one that does not.
2417
+ // With no borders it has the line under it that marks a header cell in the RTF.)
2418
+ cell.setAttribute('style', head ? `${borders ? CELL_BORDER : 'border-bottom:1px solid;'}padding:2px 6px;text-align:left;${width}` : `${borders ? CELL_BORDER : ''}padding:2px 6px;${width}`);
2419
+ cell.appendChild(document.createElement('br'));
2420
+ row.appendChild(cell);
2421
+ }
2422
+ body.appendChild(row);
2423
+ }
2424
+ table.appendChild(body);
2425
+
2426
+ const block = caretBlock();
2427
+ if (block && isEmptyBlock(block)) block.replaceWith(table);
2428
+ else if (block) block.after(table);
2429
+ else editorEl.appendChild(table);
2430
+ // Somewhere to go on typing after the table.
2431
+ const next = table.nextElementSibling;
2432
+ if (!next || next.tagName === 'TABLE' || next.tagName === 'FIGURE') {
2433
+ const p = document.createElement('p');
2434
+ p.appendChild(document.createElement('br'));
2435
+ table.after(p);
2436
+ }
2437
+ selectedImage = null;
2438
+ placeCaret(table.querySelector('td, th') as HTMLElement);
2439
+ updateToolbarState();
2440
+ fireChange();
2441
+ if (autosave) scheduleAutoSave();
2442
+ }
2443
+
2080
2444
  // ── Images ──
2081
2445
  function openImageModal(): void {
2082
2446
  keepForDialog();
@@ -2199,7 +2563,7 @@
2199
2563
  caption: string
2200
2564
  ): { img: HTMLImageElement; after: HTMLElement } | null {
2201
2565
  if (!editorEl) return null;
2202
- indentUndo = [];
2566
+ history?.step();
2203
2567
 
2204
2568
  const figure = document.createElement('figure');
2205
2569
  const img = document.createElement('img');
@@ -2247,10 +2611,13 @@
2247
2611
  fitImage(img);
2248
2612
  return;
2249
2613
  }
2614
+ // (Not if the picture has been taken out again by then.)
2250
2615
  img.addEventListener(
2251
2616
  'load',
2252
2617
  () => {
2253
- fitImage(img);
2618
+ // (Part of putting the picture in, not a step of its own to undo.)
2619
+ if (history) history.quietly(() => fitImage(img));
2620
+ else fitImage(img);
2254
2621
  updateCounts();
2255
2622
  fireChange();
2256
2623
  if (autosave) scheduleAutoSave();
@@ -2422,8 +2789,468 @@
2422
2789
  return !!el?.closest('figcaption');
2423
2790
  }
2424
2791
 
2792
+ // ── Pictures: where they are ──
2793
+ // A picture is moved up and down the document as the block it is: its figure, with its
2794
+ // caption. Two pictures side by side are a table of one row with no borders, a picture
2795
+ // and its own caption in each cell: that is what an RTF can say (a row of cells, read by
2796
+ // Word and by every other reader), and what rtfToHtml gives back. The frame around a
2797
+ // selected picture has the buttons: Move up, Move down, Place beside the picture above,
2798
+ // and, for a picture that is beside another, Place on its own line.
2799
+ const MOST_PICTURES_IN_ROW = 4;
2800
+ const PICTURE_CELL_STYLE = 'padding:2px 6px;';
2801
+ /** The padding of such a cell, left and right together, in px. */
2802
+ const PICTURE_CELL_PADDING = 12;
2803
+
2804
+ /** The picture a cell holds and nothing else: its figure, or the picture itself. */
2805
+ function pictureInCell(cell: Element): HTMLElement | null {
2806
+ const held = Array.from(cell.children).filter((child) => child.tagName !== 'BR');
2807
+ if (held.length !== 1) return null;
2808
+ const unit = held[0] as HTMLElement;
2809
+ const pictures = unit.tagName === 'IMG' ? 1 : unit.tagName === 'FIGURE' ? unit.querySelectorAll('img').length : 0;
2810
+ if (pictures !== 1) return null;
2811
+ // (Words typed beside the picture make the cell an ordinary one.)
2812
+ return (cell.textContent ?? '').trim() === (unit.textContent ?? '').trim() ? unit : null;
2813
+ }
2814
+
2815
+ /**
2816
+ * The row of pictures a picture is in: a table of one row, a picture in each of its cells.
2817
+ * `cells` are the pictures' cells; `gap` is the space set between two of them, in points,
2818
+ * or null for a row that shares the page equally (see picture-rows.ts).
2819
+ */
2820
+ function pictureRowOf(node: Element | null): { table: HTMLTableElement; cells: HTMLTableCellElement[]; gap: number | null } | null {
2821
+ const table = node?.closest('table');
2822
+ if (!table || !editorEl || table.parentElement !== editorEl || table.querySelector('table')) return null;
2823
+ if (table.rows.length !== 1 || table.querySelector('caption')) return null;
2824
+ const all = Array.from(table.rows[0].cells);
2825
+ // (Only a row with no width of its own has gaps: an empty cell in a row across the page is no gap.)
2826
+ const fixed = !table.style.width && !table.getAttribute('width');
2827
+ const gaps = fixed ? all.filter(isGapCell) : [];
2828
+ const cells = all.filter((cell) => !gaps.includes(cell));
2829
+ if (cells.length === 0 || !cells.every((cell) => pictureInCell(cell))) return null;
2830
+ // (A row with gaps is laid out by the editor, which writes each cell's style: one with
2831
+ // a border or a background of its own is a table of its own, and is left as it is.)
2832
+ if (gaps.length > 0 && !all.every(isPlainCell)) return null;
2833
+ const twips = gaps.length > 0 ? lengthTwips(gaps[0]) : null;
2834
+ return { table, cells, gap: twips === null ? null : twips / 20 };
2835
+ }
2836
+
2837
+ /** A block of the document that is one picture: its figure, or a paragraph that holds it alone. */
2838
+ function isPictureBlock(block: Element | null): block is HTMLElement {
2839
+ if (!(block instanceof HTMLElement) || block.parentElement !== editorEl) return false;
2840
+ if (block.tagName === 'IMG') return true;
2841
+ if (!/^(FIGURE|P|DIV)$/.test(block.tagName) || block.querySelectorAll('img').length !== 1) return false;
2842
+ const caption = block.tagName === 'FIGURE' ? block.querySelector('figcaption') : null;
2843
+ return (block.textContent ?? '').trim() === (caption?.textContent ?? '').trim();
2844
+ }
2845
+
2846
+ /** What is moved when a picture is: its own block, or the row of pictures it is in. Null for a picture in a line of text. */
2847
+ function movedWith(img: HTMLImageElement | null): HTMLElement | null {
2848
+ if (!img || !editorEl?.contains(img)) return null;
2849
+ const row = pictureRowOf(img);
2850
+ if (row) return row.table;
2851
+ let block: HTMLElement = img.closest<HTMLElement>('figure') ?? img;
2852
+ while (block.parentElement && block.parentElement !== editorEl) block = block.parentElement;
2853
+ return isPictureBlock(block) ? block : null;
2854
+ }
2855
+
2856
+ /** An empty line at the end of the document: where typing goes on, and nothing to move a picture past. */
2857
+ function isLastEmptyLine(el: Element | null): boolean {
2858
+ return !!el && el === editorEl?.lastElementChild && /^(P|DIV)$/.test(el.tagName) && isEmptyBlock(el as HTMLElement);
2859
+ }
2860
+
2861
+ function picturePlace(): PicturePlace {
2862
+ const none: PicturePlace = { up: false, down: false, beside: null, gap: null };
2863
+ const block = readonly ? null : movedWith(selectedImage);
2864
+ if (!block) return none;
2865
+ const above = block.previousElementSibling;
2866
+ const below = block.nextElementSibling;
2867
+ const inRow = block.tagName === 'TABLE';
2868
+ const joins = !inRow && !!above && (isPictureBlock(above) || (pictureRowOf(above)?.cells.length ?? MOST_PICTURES_IN_ROW) < MOST_PICTURES_IN_ROW);
2869
+ const gap = inRow ? (pictureRowOf(block)?.gap ?? null) : null;
2870
+ return { up: !!above, down: !!below && !isLastEmptyLine(below), beside: inRow ? 'leave' : joins ? 'join' : null, gap };
2871
+ }
2872
+
2873
+ function pictureMoved(): void {
2874
+ const last = editorEl?.lastElementChild;
2875
+ // Somewhere to go on typing after a picture that is now the last thing in the document.
2876
+ if (editorEl && last && (last.tagName === 'FIGURE' || last.tagName === 'TABLE')) {
2877
+ const p = document.createElement('p');
2878
+ p.appendChild(document.createElement('br'));
2879
+ editorEl.appendChild(p);
2880
+ }
2881
+ selectedImage?.scrollIntoView?.({ block: 'nearest' });
2882
+ overlayRef?.reposition();
2883
+ handleImageEdited();
2884
+ }
2885
+
2886
+ /** Move the selected picture (with its caption, or the row of pictures it is in) over the block above it or below it. */
2887
+ function moveSelectedImage(direction: -1 | 1): void {
2888
+ const place = picturePlace();
2889
+ const block = movedWith(selectedImage);
2890
+ if (!block || !(direction < 0 ? place.up : place.down)) return;
2891
+ history?.step();
2892
+ if (direction < 0) block.previousElementSibling!.before(block);
2893
+ else block.nextElementSibling!.after(block);
2894
+ pictureMoved();
2895
+ }
2896
+
2897
+ /** A picture block as the figure it is put in a cell as. */
2898
+ function figureOf(block: HTMLElement): { figure: HTMLElement; align: string } {
2899
+ const align = block.style.textAlign;
2900
+ if (block.tagName === 'FIGURE') {
2901
+ // (In a cell it is the cell that is aligned, and nothing is indented or spaced.)
2902
+ block.removeAttribute('style');
2903
+ return { figure: block, align };
2904
+ }
2905
+ const figure = document.createElement('figure');
2906
+ const img = block.tagName === 'IMG' ? block : block.querySelector('img')!;
2907
+ figure.append(img, document.createElement('figcaption'));
2908
+ if (block !== img) block.remove();
2909
+ return { figure, align };
2910
+ }
2911
+
2912
+ function pictureCell(block: HTMLElement): HTMLTableCellElement {
2913
+ const cell = document.createElement('td');
2914
+ const { figure, align } = figureOf(block);
2915
+ cell.appendChild(figure);
2916
+ cell.setAttribute('style', PICTURE_CELL_STYLE);
2917
+ if (align && align !== 'left') cell.style.textAlign = align;
2918
+ return cell;
2919
+ }
2920
+
2921
+ /** How wide a picture is shown, in px. */
2922
+ function pictureWidth(img: HTMLImageElement): number {
2923
+ return parseFloat(img.style.width) || img.getBoundingClientRect().width || img.naturalWidth || 0;
2924
+ }
2925
+
2926
+ /** A picture shown this wide, in px: its style says so, and the RTF writes it so. */
2927
+ function sizePicture(img: HTMLImageElement, px: number): void {
2928
+ img.removeAttribute('width');
2929
+ img.removeAttribute('height');
2930
+ img.style.width = `${px}px`;
2931
+ img.style.height = 'auto';
2932
+ }
2933
+
2934
+ /**
2935
+ * Lay out a row of pictures: across the page in equal shares (`gap` null), or with `gap`
2936
+ * points between each two, each picture in a cell as wide as it is. Pictures too wide for
2937
+ * the page together, with the gaps between them, are made smaller alike until they fit.
2938
+ */
2939
+ function layoutPictureRow(table: HTMLTableElement, cells: HTMLTableCellElement[], gap: number | null): void {
2940
+ for (const cell of Array.from(table.rows[0]?.cells ?? [])) if (isGapCell(cell)) cell.remove();
2941
+ if (gap === null) {
2942
+ table.setAttribute('style', TABLE_STYLE);
2943
+ fitPictureRow(cells);
2944
+ return;
2945
+ }
2946
+ table.setAttribute('style', GAPPED_ROW_STYLE);
2947
+ const page = contentWidth();
2948
+ // (No wider a gap than leaves each picture its least width on the page.)
2949
+ gap = Math.min(gap, fittingGap(page, cells.length) ?? gap);
2950
+ const imgs = cells.map((cell) => cell.querySelector('img')!);
2951
+ // (A picture not yet loaded has no width to go by: it is laid out once it has one.)
2952
+ const widths = imgs.map((img) => Math.round(pictureWidth(img)));
2953
+ const room = page - (gap * 4) / 3 * (cells.length - 1);
2954
+ const total = widths.reduce((a, b) => a + b, 0);
2955
+ const scale = room > 0 && total > room ? room / total : 1;
2956
+ cells.forEach((cell, i) => {
2957
+ if (widths[i] > 0) {
2958
+ const width = Math.max(MIN_PICTURE_IN_ROW, Math.floor(widths[i] * scale));
2959
+ sizePicture(imgs[i], width);
2960
+ cell.setAttribute('style', `padding:0;width:${pointsOf(width * 15)}`);
2961
+ } else {
2962
+ cell.setAttribute('style', 'padding:0');
2963
+ imgs[i].addEventListener(
2964
+ 'load',
2965
+ () => {
2966
+ if (!table.isConnected) return;
2967
+ if (history) history.quietly(() => relayoutPictureRow(table));
2968
+ else relayoutPictureRow(table);
2969
+ overlayRef?.reposition();
2970
+ },
2971
+ { once: true }
2972
+ );
2973
+ }
2974
+ if (i === 0) return;
2975
+ const between = document.createElement('td');
2976
+ between.setAttribute('style', `padding:0;width:${pointsOf(gap * 20)}`);
2977
+ cell.before(between);
2978
+ });
2979
+ }
2980
+
2981
+ /**
2982
+ * The widest gap, in points, that leaves `count` pictures their least width each on a page
2983
+ * this wide (px); null where the page has no width to go by (not laid out).
2984
+ */
2985
+ function fittingGap(page: number, count: number): number | null {
2986
+ if (page <= 0 || count < 2) return null;
2987
+ const px = (page - MIN_PICTURE_IN_ROW * count) / (count - 1);
2988
+ return Math.max(0, Math.floor(px * 0.75 * 20) / 20);
2989
+ }
2990
+
2991
+ /** Lay a row of pictures out again, as it was laid out: with the gap it has. */
2992
+ function relayoutPictureRow(table: HTMLTableElement): void {
2993
+ const row = pictureRowOf(table.rows[0]?.cells[0] ?? null);
2994
+ if (row) layoutPictureRow(table, row.cells, row.gap);
2995
+ }
2996
+
2997
+ /** The narrowest a picture in a row with a set gap is made, in px. */
2998
+ const MIN_PICTURE_IN_ROW = 40;
2999
+
3000
+ /** Set the space between the pictures of the selected picture's row, in points; null: they share the page equally. */
3001
+ function setPictureGap(gap: number | null): void {
3002
+ const row = !readonly && selectedImage ? pictureRowOf(selectedImage) : null;
3003
+ if (!row) return;
3004
+ let pt = gap === null || !Number.isFinite(gap) ? null : Math.min(MOST_GAP_PT, Math.max(1, Math.round(gap * 20) / 20));
3005
+ // (On a page too narrow for the gap asked for, the widest that fits; and none where not even 1 pt does.)
3006
+ const fits = fittingGap(contentWidth(), row.cells.length);
3007
+ if (pt !== null && fits !== null) {
3008
+ if (fits < 1) return;
3009
+ pt = Math.min(pt, fits);
3010
+ }
3011
+ if (pt === row.gap) return;
3012
+ history?.step();
3013
+ layoutPictureRow(row.table, row.cells, pt);
3014
+ pictureMoved();
3015
+ }
3016
+
3017
+ /** While a picture in a row with a set gap is resized, its cell follows it: the gap stays the gap. */
3018
+ function pictureResizing(): void {
3019
+ const row = selectedImage ? pictureRowOf(selectedImage) : null;
3020
+ if (!row || row.gap === null || !selectedImage) return;
3021
+ const cell = selectedImage.closest('td, th') as HTMLElement;
3022
+ cell.style.width = pointsOf(Math.round(pictureWidth(selectedImage)) * 15);
3023
+ }
3024
+
3025
+ /** The cells of a row of pictures share its width, and no picture is wider than its cell. */
3026
+ function fitPictureRow(cells: HTMLTableCellElement[]): void {
3027
+ const whole = contentWidth();
3028
+ cells.forEach((cell, i) => {
3029
+ const align = cell.style.textAlign;
3030
+ cell.setAttribute('style', `${PICTURE_CELL_STYLE}width:${columnShare(i, cells.length)}%`);
3031
+ if (align && align !== 'left') cell.style.textAlign = align;
3032
+ const img = cell.querySelector('img');
3033
+ const room = Math.floor(whole / cells.length) - PICTURE_CELL_PADDING;
3034
+ if (!img || room < 40) return;
3035
+ const width = parseFloat(img.style.width) || img.getBoundingClientRect().width || img.naturalWidth;
3036
+ if (width > room || !img.style.width) {
3037
+ img.removeAttribute('width');
3038
+ img.removeAttribute('height');
3039
+ img.style.width = `${Math.min(width || room, room)}px`;
3040
+ img.style.height = 'auto';
3041
+ }
3042
+ });
3043
+ }
3044
+
3045
+ /** The picture of a cell back on a line of its own, where `at` is. */
3046
+ function pictureOutOfCell(cell: HTMLTableCellElement, at: Element, where: 'before' | 'after'): void {
3047
+ const unit = pictureInCell(cell);
3048
+ if (!unit) return;
3049
+ const { figure } = figureOf(unit);
3050
+ const align = cell.style.textAlign;
3051
+ if (align && align !== 'left') figure.style.textAlign = align;
3052
+ at[where](figure);
3053
+ cell.remove();
3054
+ }
3055
+
3056
+ /** What is left of a row of pictures after one has gone: a narrower row, or the one picture on its own line. */
3057
+ function closeUpPictureRow(table: HTMLTableElement): void {
3058
+ const all = Array.from(table.rows[0]?.cells ?? []);
3059
+ const fixed = !table.style.width && !table.getAttribute('width');
3060
+ const gapCell = fixed ? all.find(isGapCell) : undefined;
3061
+ const twips = gapCell ? lengthTwips(gapCell) : null;
3062
+ const cells = all.filter((cell) => !(fixed && isGapCell(cell)));
3063
+ if (cells.length > 1) {
3064
+ layoutPictureRow(table, cells, twips === null ? null : twips / 20);
3065
+ return;
3066
+ }
3067
+ for (const cell of all) if (!cells.includes(cell)) cell.remove();
3068
+ if (cells.length === 1) pictureOutOfCell(cells[0], table, 'before');
3069
+ table.remove();
3070
+ }
3071
+
3072
+ /**
3073
+ * Put the selected picture beside the picture above it; or, where it is beside another,
3074
+ * back on a line of its own, under the row it was in.
3075
+ */
3076
+ function toggleBeside(): void {
3077
+ const place = picturePlace();
3078
+ const img = selectedImage;
3079
+ const block = movedWith(img);
3080
+ if (!img || !block || !place.beside) return;
3081
+ history?.step();
3082
+ if (place.beside === 'leave') {
3083
+ const cell = img.closest('td, th') as HTMLTableCellElement;
3084
+ pictureOutOfCell(cell, block, 'after');
3085
+ closeUpPictureRow(block as HTMLTableElement);
3086
+ } else {
3087
+ const above = block.previousElementSibling as HTMLElement;
3088
+ const joined = pictureRowOf(above);
3089
+ let row = joined?.table.rows[0];
3090
+ if (!row) {
3091
+ const table = document.createElement('table');
3092
+ table.setAttribute('style', TABLE_STYLE);
3093
+ const body = document.createElement('tbody');
3094
+ row = document.createElement('tr');
3095
+ body.appendChild(row);
3096
+ table.appendChild(body);
3097
+ above.before(table);
3098
+ row.appendChild(pictureCell(above));
3099
+ }
3100
+ row.appendChild(pictureCell(block));
3101
+ // (With the gap the row has: one more picture, the same distance from the one before.)
3102
+ relayoutPictureRow(row.closest('table')!);
3103
+ }
3104
+ pictureMoved();
3105
+ }
3106
+
3107
+ // ── Pictures: dragged by the mouse ──
3108
+ // A picture dropped on the left or right half of another picture is put beside it, as
3109
+ // Place beside does: the two are a row, each with its caption under it. Dropped on a
3110
+ // picture of a row, it joins the row there (or changes places in its own row). Dropped
3111
+ // anywhere else, it is moved there whole, with its caption, before or after the block it
3112
+ // is dropped on.
3113
+
3114
+ /** A picture of the document being dragged by the mouse. */
3115
+ let draggedPicture: HTMLImageElement | null = null;
3116
+
3117
+ function pictureDragStarted(e: DragEvent): void {
3118
+ const img = e.target instanceof HTMLImageElement ? e.target : null;
3119
+ draggedPicture = !readonly && img && movedWith(img) ? img : null;
3120
+ if (draggedPicture && e.dataTransfer) e.dataTransfer.effectAllowed = 'move';
3121
+ }
3122
+
3123
+ /** The block of the document (a child of the editor) at a point; between blocks, the nearest one. */
3124
+ function blockAtPoint(x: number, y: number): HTMLElement | null {
3125
+ if (!editorEl) return null;
3126
+ for (const el of document.elementsFromPoint(x, y)) {
3127
+ if (el === editorEl || !editorEl.contains(el)) continue;
3128
+ let top: Element = el;
3129
+ while (top.parentElement && top.parentElement !== editorEl) top = top.parentElement;
3130
+ return top as HTMLElement;
3131
+ }
3132
+ let nearest: HTMLElement | null = null;
3133
+ let distance = Infinity;
3134
+ for (const child of Array.from(editorEl.children) as HTMLElement[]) {
3135
+ const box = child.getBoundingClientRect();
3136
+ const d = y < box.top ? box.top - y : y > box.bottom ? y - box.bottom : 0;
3137
+ if (d < distance) {
3138
+ distance = d;
3139
+ nearest = child;
3140
+ }
3141
+ }
3142
+ return nearest;
3143
+ }
3144
+
3145
+ /** Take a picture out of where it is, as a block of its own (not yet put anywhere): out of its row, which closes up. */
3146
+ function takePictureOut(img: HTMLImageElement): HTMLElement | null {
3147
+ const row = pictureRowOf(img);
3148
+ if (!row) {
3149
+ const block = movedWith(img);
3150
+ block?.remove();
3151
+ return block;
3152
+ }
3153
+ const cell = img.closest('td, th') as HTMLTableCellElement;
3154
+ const unit = pictureInCell(cell);
3155
+ if (!unit) return null;
3156
+ const { figure } = figureOf(unit);
3157
+ const align = cell.style.textAlign;
3158
+ if (align && align !== 'left') figure.style.textAlign = align;
3159
+ cell.remove();
3160
+ closeUpPictureRow(row.table);
3161
+ return figure;
3162
+ }
3163
+
3164
+ /** Move a picture dragged to a point: beside the picture there, or before or after the block there. Returns whether it moved. */
3165
+ function dropPicture(img: HTMLImageElement, x: number, y: number): boolean {
3166
+ const source = movedWith(img);
3167
+ const target = blockAtPoint(x, y);
3168
+ if (!source || !target) return false;
3169
+ const sourceRow = pictureRowOf(img);
3170
+ const targetRow = pictureRowOf(target);
3171
+ const halfOf = (box: DOMRect, along: 'x' | 'y') => ((along === 'x' ? x < box.left + box.width / 2 : y < box.top + box.height / 2) ? 'before' : 'after');
3172
+
3173
+ if (targetRow || isPictureBlock(target)) {
3174
+ // The picture of the row it is dropped on: the one under the pointer, or the nearest.
3175
+ const cell = targetRow
3176
+ ? targetRow.cells.reduce((best, c) => {
3177
+ const box = c.getBoundingClientRect();
3178
+ const d = x < box.left ? box.left - x : x > box.right ? x - box.right : 0;
3179
+ const bestBox = best.getBoundingClientRect();
3180
+ const bestD = x < bestBox.left ? bestBox.left - x : x > bestBox.right ? x - bestBox.right : 0;
3181
+ return d < bestD ? c : best;
3182
+ })
3183
+ : null;
3184
+ const onto = cell ?? target;
3185
+ const side = halfOf((cell?.querySelector('img') ?? target.querySelector('img') ?? target).getBoundingClientRect(), 'x');
3186
+ if (onto === source || onto === img.closest('td, th')) return false;
3187
+ if (sourceRow && targetRow && sourceRow.table === targetRow.table) {
3188
+ // (Its own row: it changes places.)
3189
+ cell![side](img.closest('td, th')!);
3190
+ relayoutPictureRow(targetRow.table);
3191
+ return true;
3192
+ }
3193
+ if (!targetRow || targetRow.cells.length < MOST_PICTURES_IN_ROW) {
3194
+ const unit = takePictureOut(img);
3195
+ if (!unit) return false;
3196
+ if (targetRow) {
3197
+ cell![side](pictureCell(unit));
3198
+ relayoutPictureRow(targetRow.table);
3199
+ } else {
3200
+ const table = document.createElement('table');
3201
+ table.setAttribute('style', TABLE_STYLE);
3202
+ const body = document.createElement('tbody');
3203
+ const row = document.createElement('tr');
3204
+ body.appendChild(row);
3205
+ table.appendChild(body);
3206
+ target.before(table);
3207
+ // (The cells in the order they are seen: the one dropped on its left is first.)
3208
+ const first = pictureCell(side === 'before' ? unit : target);
3209
+ const second = pictureCell(side === 'before' ? target : unit);
3210
+ row.append(first, second);
3211
+ fitPictureRow([first, second]);
3212
+ }
3213
+ return true;
3214
+ }
3215
+ // (A row that is full: the picture goes under it, or over it.)
3216
+ }
3217
+ if (target === source) return false;
3218
+ const side = halfOf(target.getBoundingClientRect(), 'y');
3219
+ const unit = takePictureOut(img);
3220
+ if (!unit || !target.isConnected) return false;
3221
+ target[side](unit);
3222
+ return true;
3223
+ }
3224
+
3225
+ /** Width in px a picture has room for: its cell where it is one of a row of pictures, else the page. */
3226
+ function pictureRoom(): number {
3227
+ const whole = contentWidth();
3228
+ const row = selectedImage ? pictureRowOf(selectedImage) : null;
3229
+ if (!row) return whole;
3230
+ if (row.gap === null) return Math.max(0, Math.floor(whole / row.cells.length) - PICTURE_CELL_PADDING);
3231
+ // (With a set gap: the page, less the gaps and the other pictures.)
3232
+ const others = row.cells.reduce((sum, cell) => (cell.contains(selectedImage) ? sum : sum + pictureWidth(cell.querySelector('img')!)), 0);
3233
+ // (At least a little over the least width a picture is given here: the frame takes 40 px
3234
+ // and less as no limit at all.)
3235
+ return Math.max(MIN_PICTURE_IN_ROW + 1, Math.floor(whole - (row.gap * 4) / 3 * (row.cells.length - 1) - others));
3236
+ }
3237
+
2425
3238
  function removeSelectedImage(): void {
2426
3239
  if (!selectedImage) return;
3240
+ history?.step();
3241
+ const row = pictureRowOf(selectedImage);
3242
+ if (row) {
3243
+ // One of a row of pictures: the others close up, and a last one is on its own line again.
3244
+ selectedImage.closest('td, th')!.remove();
3245
+ selectedImage = null;
3246
+ const next = row.table.nextElementSibling as HTMLElement | null;
3247
+ closeUpPictureRow(row.table);
3248
+ if (next && !/^(TABLE|FIGURE)$/.test(next.tagName)) placeCaret(next);
3249
+ updateCounts();
3250
+ fireChange();
3251
+ if (autosave) scheduleAutoSave();
3252
+ return;
3253
+ }
2427
3254
  const figure = selectedImage.closest('figure');
2428
3255
  const next = (figure ?? selectedImage).nextElementSibling as HTMLElement | null;
2429
3256
  (figure ?? selectedImage).remove();
@@ -2436,7 +3263,16 @@
2436
3263
 
2437
3264
  /** Put the caret in the image's description line, creating it if needed. */
2438
3265
  function focusCaption(img: HTMLImageElement): void {
2439
- const figure = img.closest('figure');
3266
+ history?.step();
3267
+ let figure = img.closest('figure');
3268
+ // One of a row of pictures that had no caption is read back as the picture alone in
3269
+ // its cell: it is a figure again when it is given one.
3270
+ const cell = img.parentElement;
3271
+ if (!figure && cell && /^(TD|TH)$/.test(cell.tagName) && pictureInCell(cell) === img) {
3272
+ figure = document.createElement('figure');
3273
+ img.before(figure);
3274
+ figure.appendChild(img);
3275
+ }
2440
3276
  if (!figure) return;
2441
3277
  let caption = figure.querySelector('figcaption');
2442
3278
  if (!caption) {
@@ -2456,10 +3292,33 @@
2456
3292
  function handleDragOver(e: DragEvent): void {
2457
3293
  if (readonly) return;
2458
3294
  if (Array.from(e.dataTransfer?.types || []).includes('Files')) e.preventDefault();
3295
+ // (A picture of the document is the editor's to drop: said so, or WebKit drops it nowhere.)
3296
+ if (draggedPicture) {
3297
+ e.preventDefault();
3298
+ if (e.dataTransfer) e.dataTransfer.dropEffect = 'move';
3299
+ }
2459
3300
  }
2460
3301
 
2461
3302
  function handleDrop(e: DragEvent): void {
2462
3303
  if (readonly) return;
3304
+ // A picture of the document dragged by the mouse is moved by the editor, as its buttons
3305
+ // move it: the browser put it in the line it was dropped in, inside another picture's
3306
+ // figure, with its caption left behind as an empty line of its own.
3307
+ if (draggedPicture) {
3308
+ const img = draggedPicture;
3309
+ draggedPicture = null;
3310
+ e.preventDefault();
3311
+ if (!img.isConnected) return;
3312
+ history?.step();
3313
+ if (dropPicture(img, e.clientX, e.clientY)) {
3314
+ selectedImage = img;
3315
+ pictureMoved();
3316
+ }
3317
+ return;
3318
+ }
3319
+ // (A drop is a step of its own; where the words were already taken out from further up
3320
+ // the document, it is the step that began with that.)
3321
+ if (!dragTaken) history?.step();
2463
3322
  const files = Array.from(e.dataTransfer?.files || []).filter((f) => f.type.startsWith('image/'));
2464
3323
  if (files.length === 0) {
2465
3324
  // Text or markup dragged in, from another page or from further up this one. The
@@ -2480,7 +3339,7 @@
2480
3339
  e.preventDefault();
2481
3340
  editorEl?.focus();
2482
3341
  placeCaretAtPoint(e.clientX, e.clientY);
2483
- document.execCommand('insertHTML', false, unframed);
3342
+ browserCommand('insertHTML', false, unframed);
2484
3343
  }
2485
3344
  return;
2486
3345
  }
@@ -2538,6 +3397,7 @@
2538
3397
  // (What the reader writes is safe as it stands; it goes the same way as any other
2539
3398
  // HTML so there is one way in.)
2540
3399
  const shown = showDocument(html);
3400
+ newDocument();
2541
3401
  updateCounts();
2542
3402
  // (Shown or not, the document before it is gone, and the application is told so.)
2543
3403
  fireChange();
@@ -2570,10 +3430,13 @@
2570
3430
  if (mod && e.key === 'u') { e.preventDefault(); exec('underline'); }
2571
3431
  if (mod && e.key === 'k') { e.preventDefault(); openLinkModal(); }
2572
3432
  if (mod && e.key === 's') { e.preventDefault(); saveNow(); }
2573
- if (mod && !e.shiftKey && e.key.toLowerCase() === 'z' && (undoIndent() || undoClear())) { e.preventDefault(); return; }
3433
+ // Undo and Redo are the editor's own: the browser's is never asked. (While an input
3434
+ // method composes, the keys are the method's: what it does with them is its own.)
3435
+ const composingKey = e.isComposing || e.keyCode === 229;
3436
+ if (mod && !composingKey && !e.shiftKey && !e.altKey && e.key.toLowerCase() === 'z') { e.preventDefault(); stepBack(true); return; }
2574
3437
  // (Redo is Ctrl+Y as well, but not Cmd+Y.)
2575
3438
  const redoKey = (e.shiftKey && e.key.toLowerCase() === 'z') || (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'y');
2576
- if (mod && redoKey && redoClear()) { e.preventDefault(); return; }
3439
+ if (mod && !composingKey && redoKey && !e.altKey) { e.preventDefault(); stepBack(false); return; }
2577
3440
  if (mod && e.key === ']') { e.preventDefault(); indentBlocks('indent'); return; }
2578
3441
  if (mod && e.key === '[') { e.preventDefault(); indentBlocks('outdent'); return; }
2579
3442
 
@@ -2593,6 +3456,8 @@
2593
3456
  return;
2594
3457
  }
2595
3458
 
3459
+ if ((e.key === 'Enter' || e.key === 'Backspace') && leaveListAt(e)) return;
3460
+
2596
3461
  if (e.key === 'Tab') handleTab(e);
2597
3462
  else tabLeavesEditor = e.key === 'Escape';
2598
3463
  }
@@ -2614,7 +3479,10 @@
2614
3479
  e.preventDefault();
2615
3480
 
2616
3481
  if (sel.anchorNode.parentElement?.closest?.('pre')) {
2617
- if (!e.shiftKey) document.execCommand('insertText', false, ' ');
3482
+ if (!e.shiftKey) {
3483
+ history?.typing('insert');
3484
+ browserCommand('insertText', false, ' ');
3485
+ }
2618
3486
  return;
2619
3487
  }
2620
3488
  // Several lines selected: Tab and Shift+Tab indent and outdent them all, as a word
@@ -2624,12 +3492,28 @@
2624
3492
  return;
2625
3493
  }
2626
3494
  if (!e.shiftKey) {
3495
+ // At the start of an item, Tab puts the item under the one before it. (Anywhere
3496
+ // else in it, and in the first item, it types a tab.)
3497
+ if (atItemStart(editorEl, sel)) {
3498
+ history?.step();
3499
+ if (nestItems(editorEl, sel)) {
3500
+ indentChanged();
3501
+ return;
3502
+ }
3503
+ }
3504
+ // (A tab is typed, with the words around it.)
3505
+ history?.typing('insert');
2627
3506
  insertTab(sel);
2628
3507
  return;
2629
3508
  }
2630
3509
  // Shift+Tab takes one tab off the start of the line the caret is on, wherever the caret is
2631
- // on it, as a word processor outdents.
2632
- if (sel.isCollapsed) removeLeadingTab(sel);
3510
+ // on it, as a word processor outdents; and an item that begins with none out from under
3511
+ // the item it is under.
3512
+ if (sel.isCollapsed) {
3513
+ history?.step();
3514
+ if (leadingTab(sel)) removeLeadingTab(sel);
3515
+ else if (unnestItems(editorEl, sel)) indentChanged();
3516
+ }
2633
3517
  }
2634
3518
 
2635
3519
  /**
@@ -2639,10 +3523,10 @@
2639
3523
  * is not typed inside it.
2640
3524
  */
2641
3525
  function insertTab(sel: Selection): void {
2642
- document.execCommand('insertText', false, '\t');
3526
+ browserCommand('insertText', false, '\t');
2643
3527
  if (textBeforeCaret(sel).endsWith('\t')) return;
2644
- document.execCommand('undo');
2645
- document.execCommand('insertHTML', false, '<span style="white-space:pre">\t</span>');
3528
+ browserUndo();
3529
+ browserCommand('insertHTML', false, '<span style="white-space:pre">\t</span>');
2646
3530
  const node = sel.anchorNode;
2647
3531
  const span = (node instanceof Element ? node : node?.parentElement)?.closest('span');
2648
3532
  if (span && span.textContent === '\t' && editorEl?.contains(span)) {
@@ -2722,7 +3606,7 @@
2722
3606
  // Delete through execCommand so Ctrl+Z puts the tab back, then return the caret.
2723
3607
  sel.removeAllRanges();
2724
3608
  sel.addRange(range);
2725
- document.execCommand('delete');
3609
+ browserCommand('delete');
2726
3610
  if (caret.startContainer.isConnected) {
2727
3611
  sel.removeAllRanges();
2728
3612
  sel.addRange(caret);
@@ -2730,6 +3614,8 @@
2730
3614
  }
2731
3615
 
2732
3616
  function handlePaste(e: ClipboardEvent): void {
3617
+ // (A paste is a step of its own, with what the editor makes of it.)
3618
+ if (!readonly) history?.step();
2733
3619
  // clipboardData is only valid during the event — pull the files out first.
2734
3620
  const files = Array.from(e.clipboardData?.items || [])
2735
3621
  .filter((item) => item.kind === 'file' && item.type.startsWith('image/'))
@@ -2751,7 +3637,7 @@
2751
3637
  if (sel?.anchorNode?.parentElement?.closest?.('pre')) {
2752
3638
  e.preventDefault();
2753
3639
  const text = e.clipboardData?.getData('text/plain') || '';
2754
- document.execCommand('insertText', false, text);
3640
+ browserCommand('insertText', false, text);
2755
3641
  return;
2756
3642
  }
2757
3643
  // The browser pastes next; the input event that follows tidies what came in.
@@ -2770,7 +3656,7 @@
2770
3656
  const unframed = pasteWithoutFrames(html, keptNames);
2771
3657
  if (unframed !== null) {
2772
3658
  e.preventDefault();
2773
- document.execCommand('insertHTML', false, unframed);
3659
+ browserCommand('insertHTML', false, unframed);
2774
3660
  }
2775
3661
  }
2776
3662
  }
@@ -3303,7 +4189,11 @@
3303
4189
  onMount(() => {
3304
4190
  if (!editorEl) return;
3305
4191
  document.addEventListener('selectionchange', trackSelection);
3306
- const stopTracking = () => document.removeEventListener('selectionchange', trackSelection);
4192
+ const stopTracking = () => {
4193
+ document.removeEventListener('selectionchange', trackSelection);
4194
+ history?.destroy();
4195
+ history = null;
4196
+ };
3307
4197
  if (autosave) {
3308
4198
  let saved: string | null = null;
3309
4199
  try {
@@ -3314,6 +4204,7 @@
3314
4204
  // origin's storage can write it.
3315
4205
  if (showDocument(saved)) {
3316
4206
  updateCounts();
4207
+ history = createHistory(editorEl);
3317
4208
  return stopTracking;
3318
4209
  }
3319
4210
  // (A draft that cannot be shown was dropped without a word; it is said now, and
@@ -3328,9 +4219,33 @@
3328
4219
  // used to go up through the component as it was made, and there was no editor.)
3329
4220
  if (!showDocument(content || EMPTY_DOCUMENT)) showError(NOT_SHOWN);
3330
4221
  updateCounts();
4222
+ // (From the document as it is first shown: there is nothing before it to undo to.)
4223
+ history = createHistory(editorEl);
3331
4224
  return stopTracking;
3332
4225
  });
3333
4226
 
4227
+ // The markers of a list with a gap, drawn by the editor (see markItems), follow every change
4228
+ // to the document: an item put in or taken out, a list renumbered, its gap set. They are no
4229
+ // step of the history of their own: they go with the change they follow.
4230
+ $effect(() => {
4231
+ if (!editorEl || typeof MutationObserver === 'undefined') return;
4232
+ const root = editorEl;
4233
+ let queued = false;
4234
+ const mark = () => {
4235
+ queued = false;
4236
+ if (history) history.quietly(() => markItems(root));
4237
+ else markItems(root);
4238
+ };
4239
+ const observer = new MutationObserver(() => {
4240
+ if (queued) return;
4241
+ queued = true;
4242
+ queueMicrotask(mark);
4243
+ });
4244
+ observer.observe(root, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'start', 'type', 'value'] });
4245
+ mark();
4246
+ return () => observer.disconnect();
4247
+ });
4248
+
3334
4249
  // Suppress unused warning for importing state (used in template)
3335
4250
  $effect(() => { void importing; });
3336
4251
  </script>
@@ -3372,8 +4287,14 @@
3372
4287
  }}
3373
4288
  />
3374
4289
 
4290
+ <!-- (Whatever a click or a press on the editor goes on to do is a step of its own in the
4291
+ history: what was typed before it ends there. Heard on the way down, before the button
4292
+ or the picture's handle that does it.) -->
4293
+ <!-- svelte-ignore a11y_no_static_element_interactions, a11y_click_events_have_key_events -->
3375
4294
  <div
3376
4295
  class="ink-editor"
4296
+ onpointerdowncapture={() => history?.step()}
4297
+ onclickcapture={() => history?.step()}
3377
4298
  style:--ink-min-height={minHeight}
3378
4299
  style:--ink-font-family={screenFontFamily}
3379
4300
  style:--ink-font-size="{screenFontSize}pt"
@@ -3388,6 +4309,7 @@
3388
4309
  onblock={setBlock}
3389
4310
  oninsertlink={openLinkModal}
3390
4311
  oninsertimage={openImageModal}
4312
+ oninserttable={openTableModal}
3391
4313
  fontSize={currentFontSize}
3392
4314
  fontSizes={sizeChoices}
3393
4315
  onfontsize={setFontSize}
@@ -3395,6 +4317,7 @@
3395
4317
  fonts={fontList}
3396
4318
  documentFont={fontChoices([fontFamily])[0]?.name ?? DEFAULT_FONT_FAMILY}
3397
4319
  onfont={setFont}
4320
+ spacing={currentSpacing}
3398
4321
  copyingFormat={copyFormat !== 'off'}
3399
4322
  oncopyformat={toggleCopyFormat}
3400
4323
  />
@@ -3434,7 +4357,10 @@
3434
4357
  aria-readonly={readonly ? 'true' : undefined}
3435
4358
  spellcheck="true"
3436
4359
  bind:this={editorEl}
4360
+ onbeforeinput={handleBeforeInput}
3437
4361
  oninput={handleInput}
4362
+ oncompositionstart={() => history?.composing(true)}
4363
+ oncompositionend={() => history?.composing(false)}
3438
4364
  onmouseup={caretMoved}
3439
4365
  onkeyup={caretMoved}
3440
4366
  onscroll={contentScrolled}
@@ -3448,8 +4374,14 @@
3448
4374
  onblur={() => (tabLeavesEditor = false)}
3449
4375
  onpaste={handlePaste}
3450
4376
  onclick={handleContentClick}
3451
- ondragstart={() => (draggedFromHere = true)}
3452
- ondragend={() => (draggedFromHere = false)}
4377
+ ondragstart={(e) => {
4378
+ draggedFromHere = true;
4379
+ pictureDragStarted(e);
4380
+ }}
4381
+ ondragend={() => {
4382
+ draggedFromHere = false;
4383
+ draggedPicture = null;
4384
+ }}
3453
4385
  ondragover={handleDragOver}
3454
4386
  ondrop={handleDrop}
3455
4387
  data-placeholder={placeholder}
@@ -3484,10 +4416,15 @@
3484
4416
  target={selectedImage}
3485
4417
  bounds={contentWrapEl}
3486
4418
  within={editorEl}
3487
- maxWidth={contentWidth}
4419
+ maxWidth={pictureRoom}
3488
4420
  onchange={handleImageEdited}
3489
4421
  onremove={removeSelectedImage}
3490
4422
  oncaption={focusCaption}
4423
+ place={picturePlace}
4424
+ onmove={moveSelectedImage}
4425
+ onbeside={toggleBeside}
4426
+ ongap={setPictureGap}
4427
+ onresizing={pictureResizing}
3491
4428
  />
3492
4429
  {/if}
3493
4430
  </div>
@@ -3530,6 +4467,26 @@
3530
4467
  {/snippet}
3531
4468
  </Modal>
3532
4469
 
4470
+ <!-- Table Modal -->
4471
+ <Modal title="Insert Table" open={tableModalOpen} onclose={() => (tableModalOpen = false)}>
4472
+ <div class="ink-table-size">
4473
+ <label>
4474
+ <span>Rows</span>
4475
+ <input type="number" min="1" max={MOST_TABLE_ROWS} step="1" data-autofocus bind:value={tableRows} onkeydown={(e) => onEnter(e, applyTable)} />
4476
+ </label>
4477
+ <label>
4478
+ <span>Columns</span>
4479
+ <input type="number" min="1" max={MOST_TABLE_COLUMNS} step="1" bind:value={tableColumns} onkeydown={(e) => onEnter(e, applyTable)} />
4480
+ </label>
4481
+ </div>
4482
+ <label class="ink-check"><input type="checkbox" bind:checked={tableBorders} /> <span>Borders</span></label>
4483
+ <label class="ink-check"><input type="checkbox" bind:checked={tableHeader} /> <span>First row is a header</span></label>
4484
+ {#snippet actions()}
4485
+ <button class="ink-btn-ghost" onclick={() => (tableModalOpen = false)}>Cancel</button>
4486
+ <button class="ink-btn-primary" onclick={applyTable}>Insert</button>
4487
+ {/snippet}
4488
+ </Modal>
4489
+
3533
4490
  <!-- Image Modal -->
3534
4491
  <Modal title="Insert Image" open={imageModalOpen} onclose={() => (imageModalOpen = false)}>
3535
4492
  <button class="ink-file-pick" onclick={chooseImageFiles}>
@@ -3866,10 +4823,54 @@
3866
4823
  margin-bottom: 12px;
3867
4824
  }
3868
4825
 
4826
+ /* The bullets and the numbers are said here, and not left to the browser's own style
4827
+ sheet: the page an editor is put in often takes them off every list it has
4828
+ (`ol, ul { list-style: none }`, as Tailwind's base styles and most CSS resets do), and
4829
+ a list in the editor was then indented lines with nothing in front of them. A list
4830
+ that says its own marker (type="A", or a list-style-type of its own) keeps it. */
4831
+ .ink-content :global(ul:not([type])) {
4832
+ list-style-type: disc;
4833
+ }
4834
+
4835
+ .ink-content :global(:is(ul, ol) ul:not([type])) {
4836
+ list-style-type: circle;
4837
+ }
4838
+
4839
+ .ink-content :global(:is(ul, ol) :is(ul, ol) ul:not([type])) {
4840
+ list-style-type: square;
4841
+ }
4842
+
4843
+ .ink-content :global(ol:not([type])) {
4844
+ list-style-type: decimal;
4845
+ }
4846
+
4847
+ .ink-content :global(li) {
4848
+ display: list-item;
4849
+ }
4850
+
3869
4851
  .ink-content :global(li) {
3870
4852
  margin-bottom: 4px;
3871
4853
  }
3872
4854
 
4855
+ /* A list with a gap after its markers (its own padding-left: see markerGapTwips) has its
4856
+ markers drawn by the editor, at the list's edge, where Word has its number: the text is
4857
+ the gap further in. The browser's own marker is drawn against the text, by how wide it
4858
+ is, and could not be put there. */
4859
+ .ink-content :global(:is(ul, ol):has(> li[data-ink-marker])) {
4860
+ position: relative;
4861
+ }
4862
+
4863
+ .ink-content :global(li[data-ink-marker]) {
4864
+ list-style: none;
4865
+ }
4866
+
4867
+ .ink-content :global(li[data-ink-marker]::before) {
4868
+ content: attr(data-ink-marker);
4869
+ position: absolute;
4870
+ left: 0;
4871
+ white-space: nowrap;
4872
+ }
4873
+
3873
4874
  .ink-content :global(a) {
3874
4875
  color: var(--accent, #d4622b);
3875
4876
  text-decoration: underline;
@@ -3884,8 +4885,31 @@
3884
4885
  }
3885
4886
 
3886
4887
  /* ── Figures (image + description) ── */
4888
+ /* A picture has the space of a paragraph, which is what the RTF gives it: none of its own.
4889
+ The space before and after it is set from the Spacing list, and shows as it is set.
4890
+ (It had 20px here that no reader of the RTF showed, and a space that was set was lost
4891
+ in it.) */
3887
4892
  .ink-content :global(figure) {
3888
- margin: 20px 0;
4893
+ margin: 0 0 0.2em;
4894
+ }
4895
+
4896
+ /* A cell with no border has none in the RTF. While the document is edited it is drawn with
4897
+ a faint line, or a table of empty cells could not be seen at all. (Not a cell that holds
4898
+ a picture: pictures side by side are a row of such cells, and show where they are.) */
4899
+ /* (Nor the empty cell between two pictures with a set gap: it is the gap.) */
4900
+ .ink-content[contenteditable='true'] :global(:is(td, th):not([style*='border']):not(:has(> figure, > img)):not(table:not([style*='width']) tr:has(> td > :is(figure, img)) > td:empty)) {
4901
+ outline: 1px dashed var(--border, #e5e2dc);
4902
+ outline-offset: -1px;
4903
+ }
4904
+
4905
+ /* A picture in a cell starts at the top of it, where the RTF has it. */
4906
+ .ink-content :global(:is(td, th):has(> figure, > img)) {
4907
+ vertical-align: top;
4908
+ }
4909
+
4910
+ .ink-content :global(:is(td, th) > img:only-child) {
4911
+ margin: 0;
4912
+ vertical-align: bottom;
3889
4913
  }
3890
4914
 
3891
4915
  .ink-content :global(figure img) {
@@ -3999,6 +5023,45 @@
3999
5023
  color: var(--text-muted, #8a7e72);
4000
5024
  }
4001
5025
 
5026
+ .ink-table-size {
5027
+ display: flex;
5028
+ gap: 16px;
5029
+ margin-bottom: 14px;
5030
+ }
5031
+
5032
+ .ink-table-size label {
5033
+ display: flex;
5034
+ flex-direction: column;
5035
+ gap: 4px;
5036
+ flex: 1;
5037
+ font-size: 13px;
5038
+ color: var(--text-muted, #8a7e72);
5039
+ }
5040
+
5041
+ .ink-table-size input {
5042
+ padding: 9px 12px;
5043
+ border: 1px solid var(--border, #e5e2dc);
5044
+ border-radius: var(--radius-sm, 5px);
5045
+ font: inherit;
5046
+ font-size: 14px;
5047
+ color: var(--text, #2c2520);
5048
+ outline: none;
5049
+ }
5050
+
5051
+ .ink-table-size input:focus {
5052
+ border-color: var(--accent, #d4622b);
5053
+ }
5054
+
5055
+ .ink-check {
5056
+ display: flex;
5057
+ align-items: center;
5058
+ gap: 8px;
5059
+ margin-bottom: 8px;
5060
+ font-size: 14px;
5061
+ color: var(--text, #2c2520);
5062
+ cursor: pointer;
5063
+ }
5064
+
4002
5065
  .ink-modal-error {
4003
5066
  margin: 0 0 12px;
4004
5067
  font-size: 12px;