svelte-rtf-editor 1.12.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.
@@ -11,6 +11,10 @@
11
11
  * `content`. Default: false. Give each document its own storageKey.
12
12
  * storageKey — localStorage key for auto-save. Default: 'ink-editor-content'.
13
13
  * showToolbar — Show the formatting toolbar. Default: true.
14
+ * stickyToolbar — Keep the toolbar in sight while a long document is scrolled: it
15
+ * stays at the top of the window, or of the scrolling element the
16
+ * editor is in. Default: true. Under a header of your own that stays
17
+ * too, set the CSS variable --ink-toolbar-top to its height.
14
18
  * showStatusBar — Show the word/char count status bar. Default: true.
15
19
  * minHeight — CSS min-height of the editing area. Default: '40vh'.
16
20
  * readonly — If true, editor is not editable. Default: false.
@@ -30,13 +34,22 @@
30
34
  * maxRtfBytes — The largest RTF file Import reads. Default: 52428800 (50 MB);
31
35
  * 0 reads any size.
32
36
  * fontFamily — Font for the document, both on screen and in the RTF.
33
- * Default: DEFAULT_FONT_FAMILY (rtf-writer.ts).
37
+ * Given a CSS list ('Segoe UI, Selawik, sans-serif'), the first
38
+ * family is the font, and the rest is what a screen without it
39
+ * shows. Default: DEFAULT_FONT_FAMILY (rtf-writer.ts).
34
40
  * fontSize — Body text size in points, both on screen and in the RTF.
35
41
  * Headings scale from it. Default: 12.
36
42
  * fontSizes — The sizes, in points, the toolbar's size list offers for the
37
43
  * selected text. The body size is always among them. An empty
38
44
  * list takes the size list off the toolbar.
39
45
  * Default: 8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 36.
46
+ * fonts — The fonts the toolbar's font list offers for the selected text,
47
+ * beside the document's own: names ('Calibri'), or CSS lists whose
48
+ * first family is the name ('Calibri, Carlito, sans-serif'). Text
49
+ * in one of them is written in it to the RTF and read back in it;
50
+ * any other font is taken off HTML as it comes in, set or pasted.
51
+ * Default: none: there is no font list, and no font but the
52
+ * document's is let in.
40
53
  * keepAttributes — `data-` attributes the application's documents carry, which
41
54
  * the editor leaves on their elements: a mark on a paragraph that
42
55
  * the application reads back (`data-section="2"`). Every other
@@ -65,6 +78,8 @@
65
78
  * exportFile(format) — Downloads as 'html', 'md', or 'rtf'.
66
79
  * importRtf() — Opens the file picker to import an RTF file.
67
80
  * setFontSize(points) — Sets the size of the selected text, or of what is typed next.
81
+ * setFont(name) — Sets the font of the selected text, or of what is typed next, to
82
+ * one of `fonts`; '' or the document font's name sets it back.
68
83
  * clearFormatting() — Takes bold, italic, underline, strike, color, size and font off
69
84
  * the selected text. Headings, lists, links, alignment, indents and
70
85
  * the application's own marks stay.
@@ -73,18 +88,27 @@
73
88
  import { onMount } from 'svelte';
74
89
  import Toolbar from './Toolbar.svelte';
75
90
  import Modal from './Modal.svelte';
76
- import ImageOverlay from './ImageOverlay.svelte';
91
+ import ImageOverlay, { type PicturePlace } from './ImageOverlay.svelte';
77
92
  import { htmlToMarkdown, downloadFile } from '../utils.js';
78
- import { keptMarks, pasteHasWords, pasteNotes, removeWordHidden, sanitizedNodes, sanitizeTree, type PasteNotes } from '../sanitize.js';
93
+ import { keptMarks, pasteHasWords, pasteNotes, pasteWithoutFrames, removeWordHidden, sanitizedNodes, sanitizeTree, type PasteNotes } from '../sanitize.js';
94
+ import { givePastedPictures, pastePictures, type PastePictures } from '../paste-pictures.js';
79
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';
80
100
  import {
81
101
  htmlToRtf,
82
102
  estimateRtfBytes,
83
103
  isSafeLinkUrl,
104
+ linkTarget,
84
105
  cssFontFamily,
106
+ fontChoices,
107
+ fontKey,
85
108
  normalizeFontSize,
86
109
  DEFAULT_FONT_FAMILY,
87
- DEFAULT_FONT_SIZE
110
+ DEFAULT_FONT_SIZE,
111
+ LEAST_LINES
88
112
  } from '../rtf-writer.js';
89
113
  import {
90
114
  fileToImageSrc,
@@ -121,6 +145,7 @@
121
145
  autosave?: boolean;
122
146
  storageKey?: string;
123
147
  showToolbar?: boolean;
148
+ stickyToolbar?: boolean;
124
149
  showStatusBar?: boolean;
125
150
  minHeight?: string;
126
151
  readonly?: boolean;
@@ -133,6 +158,8 @@
133
158
  fontFamily?: string;
134
159
  fontSize?: number;
135
160
  fontSizes?: number[];
161
+ /** The fonts offered for text, beside the document's own; none unless given. */
162
+ fonts?: string[];
136
163
  /** `data-` attributes of the application's own, kept on HTML that is set or pasted. */
137
164
  keepAttributes?: string[];
138
165
  /** Class names of the application's own, kept the same way. */
@@ -163,6 +190,7 @@
163
190
  autosave = false,
164
191
  storageKey = 'ink-editor-content',
165
192
  showToolbar = true,
193
+ stickyToolbar = true,
166
194
  showStatusBar = true,
167
195
  minHeight = '40vh',
168
196
  readonly = false,
@@ -174,6 +202,7 @@
174
202
  fontFamily = DEFAULT_FONT_FAMILY,
175
203
  fontSize = DEFAULT_FONT_SIZE,
176
204
  fontSizes = DEFAULT_FONT_SIZES,
205
+ fonts = NO_KEPT_ATTRIBUTES,
177
206
  keepAttributes = NO_KEPT_ATTRIBUTES,
178
207
  keepClasses = NO_KEPT_ATTRIBUTES,
179
208
  onchange,
@@ -181,12 +210,15 @@
181
210
  onimport
182
211
  }: Props = $props();
183
212
 
184
- const keptNames = $derived(keptMarks({ keepAttributes, keepClasses }));
213
+ const keptNames = $derived(keptMarks({ keepAttributes, keepClasses, fonts, fontFamily }));
185
214
 
186
215
  // The same font and size go to the screen and to the RTF, so the editor
187
216
  // shows what the receiving system will show.
188
- const rtfOptions = $derived({ fontFamily, fontSize });
217
+ const rtfOptions = $derived({ fontFamily, fontSize, fonts });
189
218
  const screenFontFamily = $derived(cssFontFamily(fontFamily));
219
+ /** The name the document font is looked up by, and the fonts offered beside it. */
220
+ const documentFontKey = $derived(fontKey(screenFontFamily));
221
+ const fontList = $derived(fontChoices(fonts).filter((choice) => choice.key !== documentFontKey));
190
222
  const screenFontSize = $derived(normalizeFontSize(fontSize));
191
223
 
192
224
  // ── Internal state ──
@@ -198,17 +230,28 @@
198
230
  let currentBlock: string = $state('p');
199
231
  /** The size of the text at the caret, in points, for the toolbar. */
200
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 });
235
+ /** The font at the selection, by its key: '' for the document font, null where it has more than one. */
236
+ let currentFont: string | null = $state('');
201
237
 
202
238
  let formatState = $state({
203
239
  bold: false,
204
240
  italic: false,
205
241
  underline: false,
206
- strikeThrough: false
242
+ strikeThrough: false,
243
+ bulletList: false,
244
+ numberedList: false
207
245
  });
208
246
 
209
247
  // Modal state
210
248
  let linkModalOpen: boolean = $state(false);
211
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);
212
255
  let linkUrl: string = $state('');
213
256
  let linkError: string = $state('');
214
257
  let linkText: string = $state('');
@@ -231,7 +274,85 @@
231
274
 
232
275
  // ── Public API (exposed via bind:this) ──
233
276
  export function getHTML(): string {
234
- 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;
235
356
  }
236
357
 
237
358
  export function getText(): string {
@@ -243,6 +364,7 @@
243
364
  selectedImage = null;
244
365
  documentReplaced();
245
366
  const shown = showDocument(html);
367
+ newDocument();
246
368
  updateCounts();
247
369
  if (!shown) {
248
370
  // The caller is told, and the editor is empty: see showDocument.
@@ -337,6 +459,7 @@
337
459
  } catch {
338
460
  editorEl.innerHTML = EMPTY_DOCUMENT;
339
461
  documentReplaced();
462
+ newDocument();
340
463
  clearTimeout(saveTimer);
341
464
  showError(NOT_SHOWN);
342
465
  return false;
@@ -448,6 +571,7 @@
448
571
  selectedImage = null;
449
572
  documentReplaced();
450
573
  editorEl.innerHTML = EMPTY_DOCUMENT;
574
+ newDocument();
451
575
  dropDraft();
452
576
  updateCounts();
453
577
  fireChange();
@@ -462,7 +586,7 @@
462
586
  if (!editorEl) return;
463
587
  switch (format) {
464
588
  case 'html': {
465
- 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>`;
466
590
  downloadFile('document.html', html, 'text/html');
467
591
  break;
468
592
  }
@@ -486,13 +610,15 @@
486
610
 
487
611
  /**
488
612
  * The whole document is about to be replaced (setHTML, clear, an RTF import): nothing that
489
- * points into the old one may act on the new one. Indent steps no longer undo, the Copy format
490
- * 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.)
491
616
  */
492
617
  function documentReplaced(): void {
493
- indentUndo = [];
494
618
  pastedOver = null;
495
619
  pastedLoss = null;
620
+ pastedPictures = null;
621
+ commentsBefore = null;
496
622
  // (A selection kept from the document before points at nothing in the new one.)
497
623
  savedSelection = null;
498
624
  dialogSelection = null;
@@ -500,10 +626,17 @@
500
626
  broughtIn.clear();
501
627
  pastesWithWords.length = 0;
502
628
  hiddenTaken.length = 0;
503
- clearUndo = clearRedo = clearPast = null;
504
629
  stopCopyFormat();
505
630
  }
506
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
+
507
640
  // The frame around the paragraph copied from follows it when the text reflows: typing is caught
508
641
  // by the input handler, and a picture finishing loading or the editor changing width by this.
509
642
  $effect(() => {
@@ -600,26 +733,14 @@
600
733
  // (<font style="font-size:14pt">), which is what the RTF writer reads. Only attributes are
601
734
  // changed, never the elements, so the browser's undo still finds what it made.
602
735
  //
603
- // Undo puts back what the browser itself recorded, which is right: the element goes, or gets
604
- // back the size it had. Redo is not: the browser does its own step again, the mark for size 7
605
- // and nothing after it, and the text came back at 36 pt. So each change of size is remembered
606
- // here with the size every element was given, and after a redo the elements that are marked
607
- // again are given theirs again.
608
- //
609
- // And undo is only right where the browser recorded something to put back. It records the
610
- // size it takes off an element, not the one given here afterwards. So a <font> element is
611
- // never left without a size of its own: where the text is to have the size of the text around
612
- // 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.)
613
741
  const SIZE_MARK = '7';
614
742
  /** The size that is the size of the text around: what "no size of its own" is written as. */
615
743
  const SIZE_AROUND = '1em';
616
- /** One change of size: the elements it sized, each with the font-size it was given. */
617
- type SizeStep = Map<HTMLElement, string>;
618
- /** The changes of size made, in order; those from `sizeStepsApplied` on were undone and can be redone. */
619
- let sizeSteps: SizeStep[] = [];
620
- let sizeStepsApplied = 0;
621
- /** Every element this editor has given a size: a mark on one of these is the browser redoing a step. */
622
- const sizedHere = new WeakSet<Element>();
623
744
  /** The size chosen and not yet given to an element: a caret has no text to carry it until something is typed. */
624
745
  let pendingSize: number | null = null;
625
746
  /** Elements that were marked size 7 before the command (pasted that way): not ours to change. */
@@ -640,10 +761,9 @@
640
761
  const markedElements = (): HTMLElement[] =>
641
762
  editorEl ? Array.from(editorEl.querySelectorAll<HTMLElement>(`font[size="${SIZE_MARK}"]`)) : [];
642
763
 
643
- /** 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. */
644
765
  function applyPendingSize(): void {
645
766
  if (!editorEl || pendingSize === null) return;
646
- const step: SizeStep = new Map();
647
767
  for (const font of markedElements()) {
648
768
  if (markedBefore.has(font)) continue;
649
769
  sizeElement(font, SIZE_AROUND);
@@ -651,39 +771,6 @@
651
771
  // size, a heading to the heading's), it stays at the size around it: the text then
652
772
  // follows the document's size, as text that was never sized does.
653
773
  if (shownSize(font) !== pendingSize) sizeElement(font, `${pendingSize}pt`);
654
- step.set(font, font.style.fontSize);
655
- sizedHere.add(font);
656
- }
657
- if (step.size === 0) return;
658
- // A new change: what was undone before it can no longer be redone.
659
- sizeSteps = [...sizeSteps.slice(0, sizeStepsApplied), step];
660
- sizeStepsApplied = sizeSteps.length;
661
- }
662
-
663
- /** Whether a change of size is in the document as it was made: every element there, with its size. */
664
- function stepStands(step: SizeStep | undefined): boolean {
665
- if (!step) return false;
666
- for (const [font, fontSize] of step) {
667
- if (!font.isConnected || font.getAttribute('size') === SIZE_MARK || font.style.fontSize !== fontSize) return false;
668
- }
669
- return true;
670
- }
671
-
672
- /** After an undo or a redo: follow which changes of size are in the document, and finish a redone one. */
673
- function afterHistory(): void {
674
- const next = sizeSteps[sizeStepsApplied];
675
- const marked = markedElements().filter((font) => sizedHere.has(font));
676
- if (marked.length > 0) {
677
- // The browser redid its part of a change of size. (A mark with no step to go with it
678
- // should not happen; it is then taken off, and the text has the size around it,
679
- // which is better than 36 pt.)
680
- for (const font of marked) sizeElement(font, next?.get(font) ?? SIZE_AROUND);
681
- if (next) sizeStepsApplied++;
682
- } else if (stepStands(next)) {
683
- // Redone, and nothing was marked: the step only made elements, which came back as they were.
684
- sizeStepsApplied++;
685
- } else if (sizeStepsApplied > 0 && !stepStands(sizeSteps[sizeStepsApplied - 1])) {
686
- sizeStepsApplied--;
687
774
  }
688
775
  }
689
776
 
@@ -711,8 +798,7 @@
711
798
  if (typeof points !== 'number' || !Number.isFinite(points) || points <= 0) return;
712
799
  restoreSelection();
713
800
  editorEl.focus();
714
- // The document changes outside an input event: earlier indent steps no longer undo.
715
- indentUndo = [];
801
+ history?.step();
716
802
  const size = normalizeFontSize(points);
717
803
  // Nothing to change: no step is made that would undo to the same thing.
718
804
  if (selectionHasSize(size)) {
@@ -726,7 +812,7 @@
726
812
  if (!font.style.fontSize && !markedBefore.has(font)) font.style.fontSize = SIZE_AROUND;
727
813
  }
728
814
  pendingSize = size;
729
- document.execCommand('fontSize', false, SIZE_MARK);
815
+ browserCommand('fontSize', false, SIZE_MARK);
730
816
  applyPendingSize();
731
817
  // With text selected the size is on it now. At a caret it waits for the typing.
732
818
  const selection = window.getSelection();
@@ -736,7 +822,7 @@
736
822
  if (autosave) scheduleAutoSave();
737
823
  }
738
824
 
739
- /** The size of the text at the selection, for the toolbar: null where it starts and ends in different sizes. */
825
+ /** The size of the text at the selection, for the toolbar: null where the text selected is in more than one. */
740
826
  function sizeAtSelection(): number | null {
741
827
  if (pendingSize !== null) return pendingSize;
742
828
  const selection = window.getSelection();
@@ -754,7 +840,137 @@
754
840
  const first = start ? shownSize(start) : null;
755
841
  if (range.collapsed) return first;
756
842
  const end = holder(range.endContainer, range.endOffset, true);
757
- return end && shownSize(end) === first ? first : null;
843
+ if (!end || shownSize(end) !== first) return null;
844
+ // The same at both ends, and another in between: the list shows none, as for two.
845
+ return throughout(range, (el) => shownSize(el) ?? 0) === null ? null : first;
846
+ }
847
+
848
+ // ── Font ──
849
+ // The browser's own command does all of it: it writes <font face="…"> around the selected
850
+ // text, cuts a font that is there already in two rather than putting one inside another,
851
+ // and keeps the font for what is typed next at a caret. So a change of font is undone and
852
+ // redone with everything else. Which fonts there may be is the application's to say
853
+ // (`fonts`): the sanitizer takes any other off what comes in.
854
+
855
+ /** The font chosen at a caret and not yet typed in: the document has no element to show it by. */
856
+ let pendingFont: string | null = null;
857
+
858
+ /**
859
+ * Set the font of the selected text; with nothing selected, of what is typed next. The name
860
+ * is one of `fonts`; '' or the document font's own name sets the text back to the document
861
+ * font. A font that is not offered is not set. Also what the toolbar's font list calls.
862
+ */
863
+ export function setFont(name: string | null): void {
864
+ if (readonly || !editorEl) return;
865
+ const key = fontKey(name);
866
+ const choice = fontList.find((font) => font.key === key);
867
+ if (key !== '' && key !== documentFontKey && !choice) return;
868
+ restoreSelection();
869
+ editorEl.focus();
870
+ const selection = window.getSelection();
871
+ if (!selection || selection.rangeCount === 0 || !selectionInEditor()) return;
872
+ const wanted = choice?.key ?? '';
873
+ // Nothing to change: no step is made that would undo to the same thing.
874
+ if (fontAtSelection() === wanted) {
875
+ updateToolbarState();
876
+ return;
877
+ }
878
+ // (Given the document font as the screen has it, Chromium and Safari take the font off
879
+ // the text; Firefox writes it, which the writer and the font list read as no font.)
880
+ browserCommand('fontName', false, choice ? choice.css : screenFontFamily);
881
+ // With text selected the font is on it now. At a caret it waits for the typing.
882
+ pendingFont = selection.isCollapsed ? wanted : null;
883
+ updateToolbarState();
884
+ }
885
+
886
+ /** The font an element's text is in, by its key: '' for the document font, or a font that is not offered. */
887
+ function fontOfElement(el: Element | null): string {
888
+ for (let at = el; at && at !== editorEl; at = at.parentElement) {
889
+ const key = fontKey((at as HTMLElement).style?.fontFamily || (at.tagName === 'FONT' ? at.getAttribute('face') : ''));
890
+ if (key) return fontList.some((font) => font.key === key) ? key : '';
891
+ }
892
+ return '';
893
+ }
894
+
895
+ /** The font of the text at the selection, for the toolbar: null where the text selected is in more than one. */
896
+ function fontAtSelection(): string | null {
897
+ if (pendingFont !== null) return pendingFont;
898
+ const selection = window.getSelection();
899
+ if (!editorEl || !selection || selection.rangeCount === 0) return '';
900
+ const range = selection.getRangeAt(0);
901
+ if (!editorEl.contains(range.startContainer)) return '';
902
+ if (range.collapsed) {
903
+ const at = range.startContainer;
904
+ return fontOfElement(at.nodeType === Node.ELEMENT_NODE ? (at as Element) : at.parentElement);
905
+ }
906
+ const font = throughout(range, fontOfElement);
907
+ return font === undefined ? '' : font;
908
+ }
909
+
910
+ /** Lists, tables and the document itself: white space between their parts is not text one sees. */
911
+ const HOLDS_BLOCKS = new Set(['UL', 'OL', 'TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TR']);
912
+
913
+ /**
914
+ * What all the text selected has in common, as `of` reads it from the element a text is in:
915
+ * its font, its size. null where two texts differ, so that the toolbar's list shows none
916
+ * rather than the one the selection happens to start in. undefined where no text is selected.
917
+ *
918
+ * From the first text selected to the last: a selection often starts at the end of the text
919
+ * before it (Safari leaves it there after the command), which is in another font.
920
+ */
921
+ function throughout<T>(range: Range, of: (el: Element) => T): T | null | undefined {
922
+ const first = textAtEdge(range, false);
923
+ const last = textAtEdge(range, true);
924
+ if (!editorEl || !first || !last) return undefined;
925
+ if (first !== last && !(first.compareDocumentPosition(last) & Node.DOCUMENT_POSITION_FOLLOWING)) return undefined;
926
+ const walker = document.createTreeWalker(editorEl, NodeFilter.SHOW_TEXT);
927
+ walker.currentNode = first;
928
+ let seen: Element | null = null;
929
+ let value: T | undefined;
930
+ for (let text: Text | null = first; text; text = walker.nextNode() as Text | null) {
931
+ const parent = text.parentElement;
932
+ const unseen = (parent === editorEl || HOLDS_BLOCKS.has(parent?.tagName ?? '')) && text.data.trim() === '';
933
+ if (parent && parent !== seen && text.data !== '' && !unseen) {
934
+ const here = of(parent);
935
+ if (seen && here !== value) return null;
936
+ value = here;
937
+ seen = parent;
938
+ }
939
+ if (text === last) break;
940
+ }
941
+ return value;
942
+ }
943
+
944
+ /** The first text a range has a character of, or the last. */
945
+ function textAtEdge(range: Range, last: boolean): Text | null {
946
+ if (!editorEl) return null;
947
+ const walker = document.createTreeWalker(editorEl, NodeFilter.SHOW_TEXT);
948
+ const node = last ? range.endContainer : range.startContainer;
949
+ const offset = last ? range.endOffset : range.startOffset;
950
+ const step = () => (last ? walker.previousNode() : walker.nextNode()) as Text | null;
951
+ let text: Text | null;
952
+ if (node.nodeType === Node.TEXT_NODE) {
953
+ walker.currentNode = node;
954
+ const inside = last ? offset > 0 : offset < (node as Text).data.length;
955
+ text = inside ? (node as Text) : step();
956
+ } else {
957
+ // From the point between two children: into the child on the range's side of it, or
958
+ // on from the element where it has none there.
959
+ const child = node.childNodes[last ? offset - 1 : offset];
960
+ if (child) {
961
+ let edge: Node = child;
962
+ if (last) while (edge.lastChild) edge = edge.lastChild;
963
+ walker.currentNode = edge;
964
+ text = edge.nodeType === Node.TEXT_NODE ? (edge as Text) : step();
965
+ } else {
966
+ let edge: Node = node;
967
+ if (!last) while (edge.lastChild) edge = edge.lastChild;
968
+ walker.currentNode = edge;
969
+ text = step();
970
+ }
971
+ }
972
+ while (text && text.data === '') text = step();
973
+ return text && range.intersectsNode(text) ? text : null;
758
974
  }
759
975
 
760
976
  /** The sizes the list offers: those asked for, and always the body size. */
@@ -770,8 +986,15 @@
770
986
  clearFormatting();
771
987
  return;
772
988
  }
989
+ if (cmd === 'undo' || cmd === 'redo') {
990
+ stepBack(cmd === 'undo');
991
+ return;
992
+ }
773
993
  restoreSelection();
774
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();
775
998
  // Color commands require an actual text selection — a collapsed cursor
776
999
  // would silently apply the color to nothing (or to subsequently typed
777
1000
  // text), which causes accidental color spans to appear in the RTF output.
@@ -787,11 +1010,149 @@
787
1010
  hangAtCaret();
788
1011
  return;
789
1012
  }
790
- if (cmd === 'undo' && (undoIndent() || undoClear())) return;
791
- if (cmd === 'redo' && redoClear()) return;
792
- document.execCommand(cmd, false, value ?? undefined);
793
- 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();
794
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;
795
1156
  }
796
1157
 
797
1158
  // ── Clear formatting ──
@@ -799,8 +1160,7 @@
799
1160
  // Safari take a paragraph's alignment and first-line indent with its color; Firefox leaves
800
1161
  // the color on the paragraph, and takes out the element an application's mark is on; Safari
801
1162
  // leaves a size where it is. So the command is used for what only it can do, which is to
802
- // take the <b>, <i> and <font> elements out with an entry in the browser's own history
803
- // (taken out by the editor instead, the next Undo in Safari empties the document). What is
1163
+ // take the <b>, <i> and <font> elements out, cutting them where the selection ends. What is
804
1164
  // written on the elements is the editor's to change: before the command, the looks of the
805
1165
  // text are taken off every element whose text is all selected, and after it, whatever the
806
1166
  // command took off that is not a look of the text is written back.
@@ -821,49 +1181,9 @@
821
1181
  const LOOKS = ['style', 'color', 'size', 'face'] as const;
822
1182
  type Looks = Record<(typeof LOOKS)[number], string | null>;
823
1183
 
824
- /** One Clear formatting: what was written on each element before and after, to put back. */
825
- interface ClearStep {
826
- before: Map<Element, Looks>;
827
- after: Map<Element, Looks>;
828
- /** The browser's command changed something, and has an entry in its history. */
829
- native: boolean;
830
- /** The document as the editor handed it to the command: where the browser's Undo of the command leads back to. */
831
- pre: string;
832
- /** The document as the step left it. */
833
- cleared: string;
834
- /** The document as it is now, the step done or undone: it is undone, or redone, only from there. */
835
- html: string;
836
- }
837
- let clearUndo: ClearStep | null = null;
838
- let clearRedo: ClearStep | null = null;
839
- /** The last one made, also after more was typed: the browser's Undo may yet lead back to it. */
840
- let clearPast: ClearStep | null = null;
841
1184
  /** The input events of the editor's own commands, while it clears: what they leave is not yet the document. */
842
1185
  let clearing = false;
843
1186
 
844
- /**
845
- * After the browser's own Undo. A Clear formatting is the editor's to undo only while nothing
846
- * else has been done. After that the browser undoes its command with everything else, and
847
- * knows nothing of what the editor took off the elements: bold was back, and the color was
848
- * not. Where its Undo has led back to the document as the command was given it, the rest is
849
- * put back here. A step the command left nothing of (a paragraph's color and no more) has no
850
- * such place to be led back to: it is the editor's to undo again once the document is as
851
- * that step left it, which is when what was typed after it has been undone.
852
- */
853
- function afterUndoOfClear(): void {
854
- const step = clearPast;
855
- if (!step || !editorEl || clearing) return;
856
- const now = editorEl.innerHTML;
857
- if (step.native && step.pre !== step.cleared) {
858
- if (now !== step.pre) return;
859
- writeLooks(step.before);
860
- clearUndo = null;
861
- clearRedo = { ...step, html: editorEl.innerHTML };
862
- } else if (now === step.cleared) {
863
- clearUndo = { ...step, html: now };
864
- }
865
- }
866
-
867
1187
  const looksOf = (el: Element): Looks => ({
868
1188
  style: el.getAttribute('style'),
869
1189
  color: el.getAttribute('color'),
@@ -871,17 +1191,6 @@
871
1191
  face: el.getAttribute('face')
872
1192
  });
873
1193
 
874
- function writeLooks(looks: Map<Element, Looks>): void {
875
- for (const [el, wanted] of looks) {
876
- if (!el.isConnected) continue;
877
- for (const name of LOOKS) {
878
- if (el.getAttribute(name) === wanted[name]) continue;
879
- if (wanted[name] === null) el.removeAttribute(name);
880
- else el.setAttribute(name, wanted[name]);
881
- }
882
- }
883
- }
884
-
885
1194
  /** Whether all the text of an element is selected. (One with no text is, if it is in the selection.) */
886
1195
  function allSelected(range: Range, el: Element): boolean {
887
1196
  const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
@@ -934,12 +1243,13 @@
934
1243
  if (sel.isCollapsed) {
935
1244
  // At a caret there is nothing to clear but what was chosen for the words typed next.
936
1245
  pendingSize = null;
937
- document.execCommand('removeFormat');
1246
+ pendingFont = null;
1247
+ history?.step();
1248
+ browserCommand('removeFormat');
938
1249
  updateToolbarState();
939
1250
  return;
940
1251
  }
941
- // The document changes outside an input event: earlier indent steps no longer undo.
942
- indentUndo = [];
1252
+ history?.step();
943
1253
  const range = sel.getRangeAt(0);
944
1254
  const touched = Array.from(editorEl.querySelectorAll<HTMLElement>('*')).filter((el) => range.intersectsNode(el));
945
1255
  const before = new Map(touched.map((el) => [el, looksOf(el)]));
@@ -964,7 +1274,7 @@
964
1274
  removeFormat(selected, kept, closed);
965
1275
  const lost = kept.filter((el) => !el.isConnected || el.textContent !== marks.get(el));
966
1276
  if (lost.length > 0) {
967
- document.execCommand('undo');
1277
+ browserUndo();
968
1278
  if (lost.some((el) => el.tagName === 'SPAN')) spansAreTakenOut = true;
969
1279
  closed = Array.from(new Set([...closed, ...lost])).filter((el) => el.isConnected);
970
1280
  removeFormat(selected, kept.filter((el) => el.isConnected), closed);
@@ -989,9 +1299,6 @@
989
1299
  for (const el of whole) if (el.isConnected) plain(el);
990
1300
  const after = new Map(touched.map((el) => [el, looksOf(el)]));
991
1301
  const changed = native || touched.some((el) => LOOKS.some((name) => before.get(el)![name] !== after.get(el)![name]));
992
- const cleared = editorEl.innerHTML;
993
- clearUndo = clearPast = changed ? { before, after, native, pre: html, cleared, html: cleared } : null;
994
- clearRedo = null;
995
1302
  updateToolbarState();
996
1303
  if (!changed) return;
997
1304
  fireChange();
@@ -1024,7 +1331,7 @@
1024
1331
  const was = closed.map((el) => el.getAttribute('contenteditable'));
1025
1332
  for (const el of kept) el.setAttribute(KEEP_MARK, '');
1026
1333
  for (const el of closed) el.setAttribute('contenteditable', 'false');
1027
- document.execCommand('removeFormat');
1334
+ browserCommand('removeFormat');
1028
1335
  // (Also off the copy the command makes of an element it cuts in two.)
1029
1336
  for (const el of [...kept, ...Array.from(editorEl?.querySelectorAll(`[${KEEP_MARK}]`) ?? [])]) el.removeAttribute(KEEP_MARK);
1030
1337
  closed.forEach((el, i) => {
@@ -1033,57 +1340,12 @@
1033
1340
  });
1034
1341
  }
1035
1342
 
1036
- /** Undo the last Clear formatting, if nothing has changed since. */
1037
- function undoClear(): boolean {
1038
- const step = clearUndo;
1039
- clearUndo = null;
1040
- if (!step || !editorEl || editorEl.innerHTML !== step.html) return false;
1041
- clearing = true;
1042
- try {
1043
- if (step.native) document.execCommand('undo');
1044
- } finally {
1045
- clearing = false;
1046
- }
1047
- writeLooks(step.before);
1048
- // (Safari may take the step before back with it, and that may be a change of size.)
1049
- afterHistory();
1050
- clearRedo = { ...step, html: editorEl.innerHTML };
1051
- clearChanged();
1052
- return true;
1053
- }
1054
-
1055
- /** Do it again, if nothing has changed since it was undone. */
1056
- function redoClear(): boolean {
1057
- const step = clearRedo;
1058
- clearRedo = null;
1059
- if (!step || !editorEl || editorEl.innerHTML !== step.html) return false;
1060
- // (In the order it was done: the command read the elements as the editor had left them.)
1061
- writeLooks(step.after);
1062
- clearing = true;
1063
- try {
1064
- if (step.native) document.execCommand('redo');
1065
- } finally {
1066
- clearing = false;
1067
- }
1068
- writeLooks(step.after);
1069
- clearUndo = { ...step, html: editorEl.innerHTML };
1070
- clearChanged();
1071
- return true;
1072
- }
1073
-
1074
- function clearChanged(): void {
1075
- updateToolbarState();
1076
- fireChange();
1077
- if (autosave) scheduleAutoSave();
1078
- }
1079
-
1080
1343
  // ── Indent ──
1081
1344
  // Indent and Outdent move the paragraphs the selection touches by half an inch (48px, written
1082
1345
  // to RTF as \li720) per press, as margin-left on each paragraph. The browser's own commands are
1083
1346
  // not used: Chromium's Outdent strips the first paragraph to loose text ("one<br>"), and the
1084
1347
  // browsers disagree on the markup. Only a style changes (and a line of loose text gets a
1085
- // paragraph of its own), so earlier typing stays undoable; the editor keeps its own undo for
1086
- // these steps until the next edit.
1348
+ // paragraph of its own). Each press is a step of the editor's history.
1087
1349
  //
1088
1350
  // The right indent and the hanging indent move by the same step, on a paragraph (a <p>, or a
1089
1351
  // <div> that holds text) outside a table cell, which is where the RTF writer sends them:
@@ -1110,23 +1372,20 @@
1110
1372
  /** CSS lengths a margin is written in, in px. */
1111
1373
  const PX_PER_UNIT: Record<string, number> = { px: 1, pt: 96 / 72, in: 96, cm: 96 / 2.54, mm: 96 / 25.4 };
1112
1374
 
1113
- /** One block an Indent or Outdent changed, and how to put it back. */
1114
- interface IndentChange {
1115
- el: HTMLElement;
1116
- before: string | null;
1117
- after: string | null;
1118
- /** The block is a paragraph this step made around loose text, and the <br> that ended it. */
1119
- wrapped: { br: HTMLBRElement | null } | null;
1120
- /** The paragraph's data-rtf-tab-stops before a step that changed it. */
1121
- stops?: { before: string | null; after: string | null };
1122
- }
1123
- let indentUndo: IndentChange[][] = [];
1124
-
1125
1375
  function indentBlocks(cmd: IndentCommand): void {
1126
1376
  if (readonly || !editorEl) return;
1127
1377
  editorEl.focus();
1128
1378
  const sel = window.getSelection();
1129
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
+ }
1130
1389
  const { anchorNode, anchorOffset, focusNode, focusOffset } = sel;
1131
1390
  const wrapped = new Map<HTMLElement, HTMLBRElement | null>();
1132
1391
  const targets = indentTargets(sel.getRangeAt(0), cmd, wrapped);
@@ -1135,9 +1394,8 @@
1135
1394
  if (wrapped.size > 0 && anchorNode instanceof Text && focusNode instanceof Text && anchorNode.isConnected && focusNode.isConnected) {
1136
1395
  sel.setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset);
1137
1396
  }
1138
- const step: IndentChange[] = [];
1397
+ let moved = wrapped.size > 0;
1139
1398
  for (const el of targets) {
1140
- const before = el.getAttribute('style');
1141
1399
  const left = marginLeftPx(el);
1142
1400
  const first = textIndentPx(el);
1143
1401
  const setPx = (prop: 'marginLeft' | 'marginRight' | 'textIndent', px: number) => {
@@ -1167,11 +1425,189 @@
1167
1425
  setPx('textIndent', first + back);
1168
1426
  }
1169
1427
  if (!el.getAttribute('style')) el.removeAttribute('style');
1170
- const br = wrapped.get(el);
1171
- step.push({ el, before, after: el.getAttribute('style'), wrapped: br === undefined ? null : { br } });
1428
+ moved = true;
1429
+ }
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;
1172
1608
  }
1173
- if (step.length === 0) return;
1174
- indentUndo.push(step);
1609
+ if (!changed) return;
1610
+ markItems(editorEl);
1175
1611
  indentChanged();
1176
1612
  }
1177
1613
 
@@ -1241,6 +1677,7 @@
1241
1677
  const offset = caret.startOffset;
1242
1678
  const el = node instanceof Element ? node : node.parentElement;
1243
1679
  if (!el || el.closest('td, th, li, pre, figure, h1, h2, h3, h4, h5, h6')) return;
1680
+ history?.step();
1244
1681
  const x = caretLeft(caret);
1245
1682
  if (x === null) return;
1246
1683
 
@@ -1304,7 +1741,6 @@
1304
1741
  const after = block.getAttribute('style');
1305
1742
  const stopsAfter = block.getAttribute(TAB_STOPS);
1306
1743
  if (!wrapped && after === before && stopsAfter === stopsBefore) return;
1307
- indentUndo.push([{ el: block, before, after, wrapped, stops: { before: stopsBefore, after: stopsAfter } }]);
1308
1744
  indentChanged();
1309
1745
  }
1310
1746
 
@@ -1374,8 +1810,12 @@
1374
1810
  /** The tab stop that goes with a hanging indent: tab-size on screen, \tx in the RTF. */
1375
1811
  tabSize: string;
1376
1812
  tabStops: string;
1813
+ /** The space before and after it, and between its lines. */
1814
+ marginTop: string;
1815
+ marginBottom: string;
1816
+ lineHeight: string;
1377
1817
  }
1378
- const NO_FORMAT: ParagraphFormat = { textAlign: '', marginLeft: '', marginRight: '', textIndent: '', tabSize: '', tabStops: '' };
1818
+ const NO_FORMAT: ParagraphFormat = { textAlign: '', marginLeft: '', marginRight: '', textIndent: '', tabSize: '', tabStops: '', marginTop: '', marginBottom: '', lineHeight: '' };
1379
1819
  const PAINT_BLOCKS = 'p, div, h1, h2, h3, h4, h5, h6';
1380
1820
 
1381
1821
  /** 'pick': waiting for the paragraph to copy from. 'apply': each click applies the format. */
@@ -1422,7 +1862,10 @@
1422
1862
  marginRight: el.style.marginRight,
1423
1863
  textIndent: el.style.textIndent,
1424
1864
  tabSize: el.style.tabSize,
1425
- 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
1426
1869
  };
1427
1870
  }
1428
1871
 
@@ -1473,6 +1916,7 @@
1473
1916
  return;
1474
1917
  }
1475
1918
  if (block && block === copySource) return;
1919
+ history?.step();
1476
1920
  let target = block;
1477
1921
  let wrapped: { br: HTMLBRElement | null } | null = null;
1478
1922
  if (!target && loose) {
@@ -1497,6 +1941,10 @@
1497
1941
  if (indents) {
1498
1942
  target.style.marginRight = copiedFormat.marginRight;
1499
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;
1500
1948
  }
1501
1949
  if (whole) {
1502
1950
  target.style.tabSize = copiedFormat.tabSize;
@@ -1507,33 +1955,10 @@
1507
1955
  const after = target.getAttribute('style');
1508
1956
  const stopsAfter = target.getAttribute(TAB_STOPS);
1509
1957
  if (!wrapped && after === before && stopsAfter === stopsBefore) return;
1510
- indentUndo.push([{ el: target, before, after, wrapped, stops: { before: stopsBefore, after: stopsAfter } }]);
1511
1958
  indentChanged();
1512
1959
  placeCopySourceBox();
1513
1960
  }
1514
1961
 
1515
- /** Undo the last Indent or Outdent, if nothing has changed since. */
1516
- function undoIndent(): boolean {
1517
- const step = indentUndo.pop();
1518
- if (!step) return false;
1519
- // Content replaced or edited since (setHTML, an import, a link): the step no longer applies.
1520
- if (step.some(({ el, after }) => !el.isConnected || el.getAttribute('style') !== after)) {
1521
- indentUndo = [];
1522
- return false;
1523
- }
1524
- for (const { el, before, wrapped, stops } of step) {
1525
- if (before === null) el.removeAttribute('style');
1526
- else el.setAttribute('style', before);
1527
- if (stops) {
1528
- if (stops.before === null) el.removeAttribute(TAB_STOPS);
1529
- else el.setAttribute(TAB_STOPS, stops.before);
1530
- }
1531
- if (wrapped) undoWrap(el, wrapped);
1532
- }
1533
- indentChanged();
1534
- return true;
1535
- }
1536
-
1537
1962
  function indentChanged(): void {
1538
1963
  placeCopySourceBox();
1539
1964
  updateToolbarState();
@@ -1550,7 +1975,7 @@
1550
1975
  */
1551
1976
  function indentTargets(
1552
1977
  range: Range,
1553
- cmd: IndentCommand,
1978
+ cmd: IndentCommand | 'spacing',
1554
1979
  wrapped: Map<HTMLElement, HTMLBRElement | null>
1555
1980
  ): HTMLElement[] {
1556
1981
  if (!editorEl) return [];
@@ -1569,6 +1994,15 @@
1569
1994
  const item = el.closest('li');
1570
1995
  const closest = el.closest(INDENT_TARGETS);
1571
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
+ }
1572
2006
  if (cmd !== 'indent' && cmd !== 'outdent') {
1573
2007
  if (cell) return null;
1574
2008
  if (inScope(block)) return isPlainParagraph(block) ? block : null;
@@ -1643,7 +2077,8 @@
1643
2077
  function setBlock(tag: string): void {
1644
2078
  restoreSelection();
1645
2079
  editorEl?.focus();
1646
- document.execCommand('formatBlock', false, tag);
2080
+ history?.step();
2081
+ browserCommand('formatBlock', false, tag);
1647
2082
  updateToolbarState();
1648
2083
  }
1649
2084
 
@@ -1653,12 +2088,24 @@
1653
2088
  // temporarily moved to a toolbar element (e.g. colour picker, select).
1654
2089
  saveSelection();
1655
2090
  currentFontSize = sizeAtSelection();
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
+ }
1656
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;
1657
2102
  formatState = {
1658
2103
  bold: document.queryCommandState('bold'),
1659
2104
  italic: document.queryCommandState('italic'),
1660
2105
  underline: document.queryCommandState('underline'),
1661
- strikeThrough: document.queryCommandState('strikeThrough')
2106
+ strikeThrough: document.queryCommandState('strikeThrough'),
2107
+ bulletList: listKind === 'ul',
2108
+ numberedList: listKind === 'ol'
1662
2109
  };
1663
2110
 
1664
2111
  const block = document.queryCommandValue('formatBlock');
@@ -1674,11 +2121,48 @@
1674
2121
  */
1675
2122
  function caretMoved(): void {
1676
2123
  pendingSize = null;
2124
+ pendingFont = null;
1677
2125
  updateToolbarState();
2126
+ keepCaretInSight();
2127
+ }
2128
+
2129
+ let headEl: HTMLDivElement | undefined = $state();
2130
+
2131
+ /**
2132
+ * The browser scrolls a caret into the window, and knows nothing of the toolbar that stays
2133
+ * at the top of it: a caret moved up with the keys ends under the toolbar. The page is
2134
+ * scrolled by what the toolbar covers of the caret's line.
2135
+ */
2136
+ function keepCaretInSight(): void {
2137
+ if (!stickyToolbar || !headEl || !editorEl) return;
2138
+ const selection = window.getSelection();
2139
+ if (!selection || selection.rangeCount === 0 || !selectionInEditor()) return;
2140
+ const focus = document.createRange();
2141
+ try {
2142
+ focus.setStart(selection.focusNode!, selection.focusOffset);
2143
+ } catch {
2144
+ return;
2145
+ }
2146
+ const caret = focus.getClientRects()[0];
2147
+ if (!caret) return;
2148
+ const head = headEl.getBoundingClientRect();
2149
+ // Only where the toolbar is over the document, which it is not until the page is scrolled.
2150
+ if (head.bottom <= editorEl.getBoundingClientRect().top) return;
2151
+ const covered = head.bottom + 8 - caret.top;
2152
+ if (covered <= 0 || caret.bottom < head.top) return;
2153
+ for (let at: HTMLElement | null = editorEl.parentElement; at; at = at.parentElement) {
2154
+ const overflow = getComputedStyle(at).overflowY;
2155
+ if ((overflow === 'auto' || overflow === 'scroll') && at.scrollHeight > at.clientHeight) {
2156
+ at.scrollTop -= covered;
2157
+ return;
2158
+ }
2159
+ }
2160
+ window.scrollBy(0, -covered);
1678
2161
  }
1679
2162
 
1680
2163
  /** The editing area was scrolled sideways (a wide table): what is drawn over it moves with it. */
1681
2164
  function contentScrolled(): void {
2165
+ hideLinkHint();
1682
2166
  overlayRef?.reposition();
1683
2167
  placeCopySourceBox();
1684
2168
  }
@@ -1700,12 +2184,12 @@
1700
2184
  // every keystroke: with a few pictures in the document it took a tenth of a second. Each is
1701
2185
  // worked out when the handler asks for it, once, and not at all if it never does.
1702
2186
  const el = editorEl;
1703
- const options = { fontFamily, fontSize };
2187
+ const options = { fontFamily, fontSize, fonts };
1704
2188
  const once = <T,>(read: () => T): (() => T) => {
1705
2189
  let value: { v: T } | null = null;
1706
2190
  return () => (value ??= { v: read() }).v;
1707
2191
  };
1708
- const html = once(() => el?.innerHTML || '');
2192
+ const html = once(() => (el ? documentHtml() : ''));
1709
2193
  const text = once(() => el?.innerText || '');
1710
2194
  const estimate = once(() => (el ? estimateRtfBytes(el, options) : 0));
1711
2195
  onchange({
@@ -1724,7 +2208,7 @@
1724
2208
  function keepDraft(): void {
1725
2209
  if (!editorEl) return;
1726
2210
  try {
1727
- localStorage.setItem(storageKey, editorEl.innerHTML);
2211
+ localStorage.setItem(storageKey, documentHtml());
1728
2212
  lastSaved = `Saved ${new Date().toLocaleTimeString()}`;
1729
2213
  } catch (e) {
1730
2214
  // Embedded images can push a document past the localStorage quota. Say
@@ -1748,7 +2232,7 @@
1748
2232
  function autoSaveNow(): void {
1749
2233
  if (!editorEl || !autosave) return;
1750
2234
  keepDraft();
1751
- onsave?.({ html: editorEl.innerHTML });
2235
+ onsave?.({ html: documentHtml() });
1752
2236
  }
1753
2237
 
1754
2238
  /**
@@ -1761,7 +2245,7 @@
1761
2245
  // The save that was waiting is this one.
1762
2246
  clearTimeout(saveTimer);
1763
2247
  if (autosave) keepDraft();
1764
- onsave?.({ html: editorEl.innerHTML });
2248
+ onsave?.({ html: documentHtml() });
1765
2249
  }
1766
2250
 
1767
2251
  function scheduleAutoSave(): void {
@@ -1776,14 +2260,16 @@
1776
2260
  function handleInput(e?: Event): void {
1777
2261
  placeCopySourceBox();
1778
2262
  const kind = (e as InputEvent | undefined)?.inputType ?? '';
1779
- 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';
1780
2266
  // (Words dragged from one place in the document to another are first taken out where
1781
2267
  // they were, which is an input event of its own: what was dropped has not come in yet.)
1782
2268
  let shown = true;
1783
2269
  if (pastedOver && kind !== 'deleteByDrag') {
1784
2270
  tidyPasted(pastedOver);
1785
2271
  pastedOver = null;
1786
- } else if (history || MARKUP_FROM_OUTSIDE.has(kind)) {
2272
+ } else if (browserHistory || MARKUP_FROM_OUTSIDE.has(kind)) {
1787
2273
  // Undo and Redo put back what the browser remembers, not what the editor made of it:
1788
2274
  // Redo after a paste brings back the frame that was taken out of the paste, the
1789
2275
  // style that was taken off what stayed, and Word's hidden text as words. And a drop
@@ -1792,21 +2278,14 @@
1792
2278
  shown = checkDocument();
1793
2279
  }
1794
2280
  followPastes(kind === 'historyUndo');
1795
- indentUndo = [];
1796
- if (history) {
1797
- // (Not in the middle of a Clear formatting or of its Undo: the sizes are then not
1798
- // yet back on the elements. And what the editor puts back first, for the same reason.)
1799
- if (kind === 'historyUndo') afterUndoOfClear();
1800
- if (!clearing) afterHistory();
1801
- } else {
1802
- // (And a Clear formatting before this edit is the browser's to undo from here on.)
1803
- clearUndo = clearRedo = null;
1804
- // An edit: what was undone can no longer be redone.
1805
- sizeSteps = sizeSteps.slice(0, sizeStepsApplied);
1806
- // What was typed at a caret after a size was chosen came in marked: give it the size.
1807
- applyPendingSize();
1808
- }
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();
1809
2287
  pendingSize = null;
2288
+ pendingFont = null;
1810
2289
  updateToolbarState();
1811
2290
  // Typing means the user is editing text, not the picture. Dropping the
1812
2291
  // selection here keeps Backspace editing that text instead of deleting a
@@ -1837,8 +2316,7 @@
1837
2316
  return;
1838
2317
  }
1839
2318
  linkError = '';
1840
- // Inserting changes the document outside an input event: earlier indent steps no longer undo.
1841
- indentUndo = [];
2319
+ history?.step();
1842
2320
  restoreFor(dialogSelection);
1843
2321
  editorEl?.focus();
1844
2322
 
@@ -1856,7 +2334,7 @@
1856
2334
  sel.addRange(range);
1857
2335
  }
1858
2336
  } else {
1859
- document.execCommand('createLink', false, linkUrl.trim());
2337
+ browserCommand('createLink', false, linkUrl.trim());
1860
2338
  }
1861
2339
  linkModalOpen = false;
1862
2340
  updateCounts();
@@ -1876,6 +2354,93 @@
1876
2354
  act();
1877
2355
  }
1878
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
+
1879
2444
  // ── Images ──
1880
2445
  function openImageModal(): void {
1881
2446
  keepForDialog();
@@ -1998,7 +2563,7 @@
1998
2563
  caption: string
1999
2564
  ): { img: HTMLImageElement; after: HTMLElement } | null {
2000
2565
  if (!editorEl) return null;
2001
- indentUndo = [];
2566
+ history?.step();
2002
2567
 
2003
2568
  const figure = document.createElement('figure');
2004
2569
  const img = document.createElement('img');
@@ -2046,10 +2611,13 @@
2046
2611
  fitImage(img);
2047
2612
  return;
2048
2613
  }
2614
+ // (Not if the picture has been taken out again by then.)
2049
2615
  img.addEventListener(
2050
2616
  'load',
2051
2617
  () => {
2052
- 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);
2053
2621
  updateCounts();
2054
2622
  fireChange();
2055
2623
  if (autosave) scheduleAutoSave();
@@ -2115,12 +2683,101 @@
2115
2683
  }
2116
2684
 
2117
2685
  // ── Image selection / editing ──
2686
+ // ── Opening a link ──
2687
+ // A click in text one can edit puts the caret there, in a link as anywhere else, so that the
2688
+ // link's words can be changed: the browser follows no link in it. As in Word, a click with
2689
+ // Ctrl (Cmd on a Mac) opens the link, in a new tab, and a note at the link under the pointer
2690
+ // says so. The note is the editor's own and no part of the document.
2691
+
2692
+ const ON_MAC = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent);
2693
+ const OPEN_HINT = ON_MAC ? '\u2318 Command-click to open link' : 'Ctrl+click to open link';
2694
+ /** Room kept for the note beside the link, so that it is not cut off at the right. */
2695
+ const HINT_WIDTH = 320;
2696
+
2697
+ let linkHint: { top: number; left: number; above: boolean; href: string } | null = $state(null);
2698
+ /**
2699
+ * Ctrl or Cmd is down: the link under the pointer shows the hand it will be opened with.
2700
+ * (Only with the pointer at a link: the keys are down for every shortcut, and the document's
2701
+ * element is not to change its class with each.)
2702
+ */
2703
+ let linkArmed = $state(false);
2704
+ let hintedLink: Element | null = null;
2705
+
2706
+ /** The link an event is at, where it has an address a link may have. */
2707
+ function linkAt(e: Event): Element | null {
2708
+ const link = e.target instanceof Element ? e.target.closest('a[href]') : null;
2709
+ return link && editorEl?.contains(link) && linkTarget(link.getAttribute('href') ?? '') !== null ? link : null;
2710
+ }
2711
+
2712
+ function hideLinkHint(): void {
2713
+ hintedLink = null;
2714
+ linkHint = null;
2715
+ }
2716
+
2717
+ function linkHovered(e: MouseEvent): void {
2718
+ linkArmed = !readonly && (e.metaKey || e.ctrlKey);
2719
+ // (Not with a button down: the pointer is selecting text, and the note would be in its way.)
2720
+ if (readonly || copyFormat !== 'off' || e.buttons !== 0 || !contentWrapEl) return;
2721
+ const link = linkAt(e);
2722
+ if (!link || link === hintedLink) return;
2723
+ hintedLink = link;
2724
+ const wrap = contentWrapEl.getBoundingClientRect();
2725
+ // The line of the link the pointer is on: a link may run over two.
2726
+ const line = Array.from(link.getClientRects()).find((r) => e.clientY >= r.top && e.clientY <= r.bottom) ?? link.getBoundingClientRect();
2727
+ // Below the line, or above it where there is no room left in the window.
2728
+ const above = line.bottom + 64 > window.innerHeight;
2729
+ linkHint = {
2730
+ top: (above ? line.top - 6 : line.bottom + 6) - wrap.top,
2731
+ left: Math.max(0, Math.min(line.left - wrap.left, wrap.width - HINT_WIDTH)),
2732
+ above,
2733
+ href: link.getAttribute('href') ?? ''
2734
+ };
2735
+ }
2736
+
2737
+ function linkLeft(e: MouseEvent): void {
2738
+ if (!hintedLink) return;
2739
+ const to = e.relatedTarget;
2740
+ if (!(to instanceof Node) || !hintedLink.contains(to)) hideLinkHint();
2741
+ }
2742
+
2743
+ /** Open a link in a tab of its own, which is not handed this page. */
2744
+ function openLink(address: string): void {
2745
+ const target = linkTarget(address);
2746
+ if (target === null) return;
2747
+ const link = document.createElement('a');
2748
+ link.href = target;
2749
+ link.target = '_blank';
2750
+ link.rel = 'noopener noreferrer';
2751
+ link.click();
2752
+ }
2753
+
2754
+ /**
2755
+ * A click on a link: with Ctrl or Cmd it is opened. Where the document cannot be edited a
2756
+ * plain click opens it, as in the viewer, and in a new tab too: the browser would open it
2757
+ * in this one, in place of the application. True where the click was the link's.
2758
+ */
2759
+ function followLink(e: MouseEvent): boolean {
2760
+ const modified = e.metaKey || e.ctrlKey;
2761
+ // (Read only, a click with a key down is the browser's own: a new tab, a new window.)
2762
+ if (readonly ? modified || e.shiftKey || e.altKey : !modified) return false;
2763
+ const link = e.target instanceof Element ? e.target.closest('a[href]') : null;
2764
+ if (!link || !editorEl?.contains(link)) return false;
2765
+ e.preventDefault();
2766
+ hideLinkHint();
2767
+ openLink(link.getAttribute('href') ?? '');
2768
+ return true;
2769
+ }
2770
+
2118
2771
  function handleContentClick(e: MouseEvent): void {
2119
- if (readonly) return;
2772
+ if (readonly) {
2773
+ followLink(e);
2774
+ return;
2775
+ }
2120
2776
  if (copyFormat !== 'off') {
2121
2777
  handleCopyFormatClick(e);
2122
2778
  return;
2123
2779
  }
2780
+ if (followLink(e)) return;
2124
2781
  const target = e.target as HTMLElement | null;
2125
2782
  selectedImage = target?.tagName === 'IMG' ? (target as HTMLImageElement) : null;
2126
2783
  }
@@ -2132,8 +2789,468 @@
2132
2789
  return !!el?.closest('figcaption');
2133
2790
  }
2134
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
+
2135
3238
  function removeSelectedImage(): void {
2136
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
+ }
2137
3254
  const figure = selectedImage.closest('figure');
2138
3255
  const next = (figure ?? selectedImage).nextElementSibling as HTMLElement | null;
2139
3256
  (figure ?? selectedImage).remove();
@@ -2146,7 +3263,16 @@
2146
3263
 
2147
3264
  /** Put the caret in the image's description line, creating it if needed. */
2148
3265
  function focusCaption(img: HTMLImageElement): void {
2149
- 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
+ }
2150
3276
  if (!figure) return;
2151
3277
  let caption = figure.querySelector('figcaption');
2152
3278
  if (!caption) {
@@ -2166,10 +3292,33 @@
2166
3292
  function handleDragOver(e: DragEvent): void {
2167
3293
  if (readonly) return;
2168
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
+ }
2169
3300
  }
2170
3301
 
2171
3302
  function handleDrop(e: DragEvent): void {
2172
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();
2173
3322
  const files = Array.from(e.dataTransfer?.files || []).filter((f) => f.type.startsWith('image/'));
2174
3323
  if (files.length === 0) {
2175
3324
  // Text or markup dragged in, from another page or from further up this one. The
@@ -2179,9 +3328,19 @@
2179
3328
  // that sends what is typed in it somewhere else, a frame showing another site.)
2180
3329
  expectInsertion(draggedFromHere);
2181
3330
  // What the browser may lose of it, as of a paste: it begins where it is dropped.
2182
- const notes = pasteNotes(e.dataTransfer?.getData?.('text/html') ?? '');
3331
+ const dropped = e.dataTransfer?.getData?.('text/html') ?? '';
3332
+ pastedPictures = pastePictures(dropped, e.dataTransfer?.getData?.('text/rtf') ?? '');
3333
+ const notes = pasteNotes(dropped);
2183
3334
  const at = notes ? rangeAtPoint(e.clientX, e.clientY) : null;
2184
3335
  pastedLoss = notes && at && editorEl?.contains(at.startContainer) ? { notes, from: shownCharsBefore(at.startContainer, at.startOffset), dropped: true } : null;
3336
+ // What holds a frame is put in here, made safe and without it (see pasteWithoutFrames).
3337
+ const unframed = pasteWithoutFrames(dropped, keptNames);
3338
+ if (unframed !== null) {
3339
+ e.preventDefault();
3340
+ editorEl?.focus();
3341
+ placeCaretAtPoint(e.clientX, e.clientY);
3342
+ browserCommand('insertHTML', false, unframed);
3343
+ }
2185
3344
  return;
2186
3345
  }
2187
3346
  e.preventDefault();
@@ -2231,13 +3390,14 @@
2231
3390
  importing = true;
2232
3391
 
2233
3392
  try {
2234
- const html = await readRtfFile(file, { fontSize, maxBytes: maxRtfBytes });
3393
+ const html = await readRtfFile(file, { fontSize, fontFamily, fonts, maxBytes: maxRtfBytes });
2235
3394
  if (editorEl) {
2236
3395
  selectedImage = null;
2237
3396
  documentReplaced();
2238
3397
  // (What the reader writes is safe as it stands; it goes the same way as any other
2239
3398
  // HTML so there is one way in.)
2240
3399
  const shown = showDocument(html);
3400
+ newDocument();
2241
3401
  updateCounts();
2242
3402
  // (Shown or not, the document before it is gone, and the application is told so.)
2243
3403
  fireChange();
@@ -2270,10 +3430,13 @@
2270
3430
  if (mod && e.key === 'u') { e.preventDefault(); exec('underline'); }
2271
3431
  if (mod && e.key === 'k') { e.preventDefault(); openLinkModal(); }
2272
3432
  if (mod && e.key === 's') { e.preventDefault(); saveNow(); }
2273
- 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; }
2274
3437
  // (Redo is Ctrl+Y as well, but not Cmd+Y.)
2275
3438
  const redoKey = (e.shiftKey && e.key.toLowerCase() === 'z') || (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'y');
2276
- if (mod && redoKey && redoClear()) { e.preventDefault(); return; }
3439
+ if (mod && !composingKey && redoKey && !e.altKey) { e.preventDefault(); stepBack(false); return; }
2277
3440
  if (mod && e.key === ']') { e.preventDefault(); indentBlocks('indent'); return; }
2278
3441
  if (mod && e.key === '[') { e.preventDefault(); indentBlocks('outdent'); return; }
2279
3442
 
@@ -2293,6 +3456,8 @@
2293
3456
  return;
2294
3457
  }
2295
3458
 
3459
+ if ((e.key === 'Enter' || e.key === 'Backspace') && leaveListAt(e)) return;
3460
+
2296
3461
  if (e.key === 'Tab') handleTab(e);
2297
3462
  else tabLeavesEditor = e.key === 'Escape';
2298
3463
  }
@@ -2314,7 +3479,10 @@
2314
3479
  e.preventDefault();
2315
3480
 
2316
3481
  if (sel.anchorNode.parentElement?.closest?.('pre')) {
2317
- if (!e.shiftKey) document.execCommand('insertText', false, ' ');
3482
+ if (!e.shiftKey) {
3483
+ history?.typing('insert');
3484
+ browserCommand('insertText', false, ' ');
3485
+ }
2318
3486
  return;
2319
3487
  }
2320
3488
  // Several lines selected: Tab and Shift+Tab indent and outdent them all, as a word
@@ -2324,12 +3492,28 @@
2324
3492
  return;
2325
3493
  }
2326
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');
2327
3506
  insertTab(sel);
2328
3507
  return;
2329
3508
  }
2330
3509
  // Shift+Tab takes one tab off the start of the line the caret is on, wherever the caret is
2331
- // on it, as a word processor outdents.
2332
- 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
+ }
2333
3517
  }
2334
3518
 
2335
3519
  /**
@@ -2339,10 +3523,10 @@
2339
3523
  * is not typed inside it.
2340
3524
  */
2341
3525
  function insertTab(sel: Selection): void {
2342
- document.execCommand('insertText', false, '\t');
3526
+ browserCommand('insertText', false, '\t');
2343
3527
  if (textBeforeCaret(sel).endsWith('\t')) return;
2344
- document.execCommand('undo');
2345
- document.execCommand('insertHTML', false, '<span style="white-space:pre">\t</span>');
3528
+ browserUndo();
3529
+ browserCommand('insertHTML', false, '<span style="white-space:pre">\t</span>');
2346
3530
  const node = sel.anchorNode;
2347
3531
  const span = (node instanceof Element ? node : node?.parentElement)?.closest('span');
2348
3532
  if (span && span.textContent === '\t' && editorEl?.contains(span)) {
@@ -2422,7 +3606,7 @@
2422
3606
  // Delete through execCommand so Ctrl+Z puts the tab back, then return the caret.
2423
3607
  sel.removeAllRanges();
2424
3608
  sel.addRange(range);
2425
- document.execCommand('delete');
3609
+ browserCommand('delete');
2426
3610
  if (caret.startContainer.isConnected) {
2427
3611
  sel.removeAllRanges();
2428
3612
  sel.addRange(caret);
@@ -2430,6 +3614,8 @@
2430
3614
  }
2431
3615
 
2432
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();
2433
3619
  // clipboardData is only valid during the event — pull the files out first.
2434
3620
  const files = Array.from(e.clipboardData?.items || [])
2435
3621
  .filter((item) => item.kind === 'file' && item.type.startsWith('image/'))
@@ -2451,7 +3637,7 @@
2451
3637
  if (sel?.anchorNode?.parentElement?.closest?.('pre')) {
2452
3638
  e.preventDefault();
2453
3639
  const text = e.clipboardData?.getData('text/plain') || '';
2454
- document.execCommand('insertText', false, text);
3640
+ browserCommand('insertText', false, text);
2455
3641
  return;
2456
3642
  }
2457
3643
  // The browser pastes next; the input event that follows tidies what came in.
@@ -2464,6 +3650,14 @@
2464
3650
  notes && start && editorEl.contains(start.startContainer)
2465
3651
  ? { notes, from: shownCharsBefore(start.startContainer, start.startOffset) }
2466
3652
  : null;
3653
+ // The pictures Word's HTML only names, from its RTF (see pastePictures).
3654
+ pastedPictures = pastePictures(html, e.clipboardData?.getData('text/rtf') ?? '');
3655
+ // What holds a frame is put in here, made safe and without it (see pasteWithoutFrames).
3656
+ const unframed = pasteWithoutFrames(html, keptNames);
3657
+ if (unframed !== null) {
3658
+ e.preventDefault();
3659
+ browserCommand('insertHTML', false, unframed);
3660
+ }
2467
3661
  }
2468
3662
  }
2469
3663
 
@@ -2478,6 +3672,8 @@
2478
3672
  pastedOver = snapshot;
2479
3673
  pastedOwn = own;
2480
3674
  pastedLoss = null;
3675
+ pastedPictures = null;
3676
+ commentsBefore = new Set(commentsIn(editorEl));
2481
3677
  // A paste that inserts nothing (an empty clipboard, a host that cancels it) raises no
2482
3678
  // input event. Left set, the snapshot would make the next keystroke treat the whole
2483
3679
  // document as pasted.
@@ -2485,6 +3681,8 @@
2485
3681
  if (pastedOver === snapshot) {
2486
3682
  pastedOver = null;
2487
3683
  pastedLoss = null;
3684
+ pastedPictures = null;
3685
+ commentsBefore = null;
2488
3686
  }
2489
3687
  }, 0);
2490
3688
  }
@@ -2516,9 +3714,19 @@
2516
3714
  if (!sel || sel.rangeCount === 0 || !editorEl.contains(sel.anchorNode) || !editorEl.contains(sel.focusNode)) return;
2517
3715
  if (!sel.isCollapsed && !loss.dropped) return;
2518
3716
  const range = sel.getRangeAt(0);
2519
- const from = sel.isCollapsed ? loss.from : shownCharsBefore(range.startContainer, range.startOffset);
2520
- const to = shownCharsBefore(range.endContainer, range.endOffset);
3717
+ let from = sel.isCollapsed ? loss.from : shownCharsBefore(range.startContainer, range.startOffset);
3718
+ let to = shownCharsBefore(range.endContainer, range.endOffset);
2521
3719
  const came = new Set(Array.from(editorEl.querySelectorAll('*')).filter((el) => !before.has(el)));
3720
+ // Firefox leaves the caret before a whole page it has pasted (a copy made in Word, with
3721
+ // its <head>), not after it. The paste is then the elements that came in, from the
3722
+ // first to the end of the last. (Text that is not the paste's own, to the character,
3723
+ // is left alone as ever: see removeWordHidden.)
3724
+ if (sel.isCollapsed && to <= from && came.size > 0) {
3725
+ const outer = Array.from(came).filter((el) => el.parentElement && !came.has(el.parentElement));
3726
+ const index = (el: Element) => Array.prototype.indexOf.call(el.parentNode!.childNodes, el);
3727
+ from = Math.min(...outer.map((el) => shownCharsBefore(el.parentNode!, index(el))));
3728
+ to = Math.max(...outer.map((el) => shownCharsBefore(el.parentNode!, index(el) + 1)));
3729
+ }
2522
3730
  if (takeHidden(from, to, loss.notes, (el) => came.has(el))) {
2523
3731
  hiddenTaken.push({ notes: loss.notes, from, came, emptied: Array.from(came).filter((el) => !el.isConnected) });
2524
3732
  }
@@ -2529,6 +3737,9 @@
2529
3737
  * character shown, or with null for `to`, the paste Redo has put back from the `from`th on
2530
3738
  * (see removeWordHidden). Returns whether anything was taken out.
2531
3739
  */
3740
+ /** Word's mark on text it hides, as a paste carries it in a style. */
3741
+ const WORD_HIDES = /mso-hide\s*:\s*all/i;
3742
+
2532
3743
  function takeHidden(from: number, to: number | null, notes: PasteNotes, came: (el: Element) => boolean): boolean {
2533
3744
  if (!editorEl) return false;
2534
3745
  // A pasted element left with nothing in it goes, but not the one the caret is in: that
@@ -2536,7 +3747,34 @@
2536
3747
  // alone left the caret in no line at all, and the next words typed were in none.)
2537
3748
  const sel = window.getSelection();
2538
3749
  const at = sel && sel.rangeCount > 0 && editorEl.contains(sel.anchorNode) ? sel.anchorNode : null;
2539
- const held = at instanceof Element ? at : (at?.parentElement ?? null);
3750
+ let held = at instanceof Element ? at : (at?.parentElement ?? null);
3751
+ // Firefox pastes Word's hidden text as an element that is not displayed, and leaves the
3752
+ // caret inside it: what was typed next was typed where it is not seen, and what is not
3753
+ // seen is not written. The caret is put before a hidden piece of a line, which then
3754
+ // goes with its text; a hidden paragraph the caret is in becomes the empty line, shown.
3755
+ let unseen: HTMLElement | null = null;
3756
+ for (let el = held; el && el !== editorEl; el = el.parentElement) {
3757
+ // (Word's own mark is still on it as the style it came with: the browser knows no
3758
+ // such property, and what came in has not been made safe yet.)
3759
+ const hidden = el instanceof HTMLElement && (WORD_HIDES.test(el.getAttribute('style') ?? '') || el.style.display === 'none' || el.style.visibility === 'hidden' || el.hasAttribute('hidden'));
3760
+ if (hidden && came(el)) unseen = el as HTMLElement;
3761
+ }
3762
+ if (unseen && sel) {
3763
+ if (/^(P|DIV|LI|H[1-6]|BLOCKQUOTE|PRE|TD|TH)$/.test(unseen.tagName)) {
3764
+ unseen.setAttribute('style', (unseen.getAttribute('style') ?? '').replace(new RegExp(`${WORD_HIDES.source}\\s*;?`, 'gi'), ''));
3765
+ unseen.style.removeProperty('display');
3766
+ unseen.style.removeProperty('visibility');
3767
+ unseen.removeAttribute('hidden');
3768
+ if (!unseen.getAttribute('style')?.trim()) unseen.removeAttribute('style');
3769
+ } else {
3770
+ const before = document.createRange();
3771
+ before.setStartBefore(unseen);
3772
+ before.collapse(true);
3773
+ sel.removeAllRanges();
3774
+ sel.addRange(before);
3775
+ held = unseen.parentElement;
3776
+ }
3777
+ }
2540
3778
  if (!removeWordHidden(editorEl, from, to, notes, (el) => came(el) && !(held !== null && el.contains(held)))) return false;
2541
3779
  if (held && held !== editorEl && held.isConnected && held.childNodes.length === 0) held.appendChild(document.createElement('br'));
2542
3780
  return true;
@@ -2566,6 +3804,26 @@
2566
3804
  const broughtIn = new Map<Element, { style: string | null; own: boolean }>();
2567
3805
  /** What the paste or the drop under way may lose, and how much text the document had before it. */
2568
3806
  let pastedLoss: { notes: PasteNotes; from: number; dropped?: boolean } | null = null;
3807
+ /** The pictures of the paste that is coming in, where its HTML only names them (see pastePictures). */
3808
+ let pastedPictures: PastePictures | null = null;
3809
+
3810
+ // ── Comments that come in ──
3811
+ // HTML copied in another program may hold comments. What is in one is not shown and not
3812
+ // written to the RTF, but it is kept in the HTML that is saved, and Word writes in one the
3813
+ // address of each copied picture: a file on the writer's own disk, with the name of the
3814
+ // writer's account in it. A browser leaves comments out of a paste; Firefox keeps those of
3815
+ // markup that is dropped. So a comment that comes in is emptied. It is not taken out: Firefox
3816
+ // cannot undo a drop from which a node is gone, and an empty comment says nothing. Those the
3817
+ // application's own HTML has are not the editor's to judge, and stay as they are.
3818
+ /** The comments in the document just before a paste or a drop; what is not among them came with it. */
3819
+ let commentsBefore: Set<Comment> | null = null;
3820
+
3821
+ function commentsIn(root: Node): Comment[] {
3822
+ const found: Comment[] = [];
3823
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_COMMENT);
3824
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) found.push(node as Comment);
3825
+ return found;
3826
+ }
2569
3827
 
2570
3828
  /**
2571
3829
  * Take off the elements `came` accepts, the ones a paste or a drop brought in, their id and
@@ -2607,8 +3865,30 @@
2607
3865
 
2608
3866
  function tidyPasted(before: Set<Element>): void {
2609
3867
  if (!editorEl) return;
3868
+ // Firefox pastes the <style> of a copied page into the document with its words. It is
3869
+ // taken out below with all that is not safe; here first, because its rules count as text
3870
+ // of the paste, and Word's hidden words are found by the paste's text, to the character:
3871
+ // with a style sheet among them they were not found, and stayed in the document, unseen.
3872
+ for (const el of Array.from(editorEl.querySelectorAll('style, script, template, title'))) {
3873
+ if (!before.has(el)) el.remove();
3874
+ }
3875
+ if (commentsBefore) {
3876
+ for (const comment of commentsIn(editorEl)) {
3877
+ if (!commentsBefore.has(comment) && comment.data !== '') comment.data = '';
3878
+ }
3879
+ }
3880
+ commentsBefore = null;
2610
3881
  if (pastedLoss) restorePasteLoss(before, pastedLoss);
2611
3882
  pastedLoss = null;
3883
+ // Before what came in is made safe: an image that names a file on a disk loses that
3884
+ // address there, and is then an image of nothing.
3885
+ if (pastedPictures) {
3886
+ givePastedPictures(
3887
+ Array.from(editorEl.querySelectorAll('img')).filter((img) => !before.has(img)),
3888
+ pastedPictures
3889
+ );
3890
+ }
3891
+ pastedPictures = null;
2612
3892
  // What the paste brought is made safe as HTML from anywhere else is: a browser takes the
2613
3893
  // scripts out of a paste itself, but leaves a form, an <iframe>, or a block with
2614
3894
  // position: fixed that covers the page.
@@ -2909,7 +4189,11 @@
2909
4189
  onMount(() => {
2910
4190
  if (!editorEl) return;
2911
4191
  document.addEventListener('selectionchange', trackSelection);
2912
- const stopTracking = () => document.removeEventListener('selectionchange', trackSelection);
4192
+ const stopTracking = () => {
4193
+ document.removeEventListener('selectionchange', trackSelection);
4194
+ history?.destroy();
4195
+ history = null;
4196
+ };
2913
4197
  if (autosave) {
2914
4198
  let saved: string | null = null;
2915
4199
  try {
@@ -2920,6 +4204,7 @@
2920
4204
  // origin's storage can write it.
2921
4205
  if (showDocument(saved)) {
2922
4206
  updateCounts();
4207
+ history = createHistory(editorEl);
2923
4208
  return stopTracking;
2924
4209
  }
2925
4210
  // (A draft that cannot be shown was dropped without a word; it is said now, and
@@ -2934,9 +4219,33 @@
2934
4219
  // used to go up through the component as it was made, and there was no editor.)
2935
4220
  if (!showDocument(content || EMPTY_DOCUMENT)) showError(NOT_SHOWN);
2936
4221
  updateCounts();
4222
+ // (From the document as it is first shown: there is nothing before it to undo to.)
4223
+ history = createHistory(editorEl);
2937
4224
  return stopTracking;
2938
4225
  });
2939
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
+
2940
4249
  // Suppress unused warning for importing state (used in template)
2941
4250
  $effect(() => { void importing; });
2942
4251
  </script>
@@ -2963,53 +4272,83 @@
2963
4272
  <svelte:window
2964
4273
  onkeydown={(e) => {
2965
4274
  if (copyFormat !== 'off' && e.key === 'Escape') stopCopyFormat();
4275
+ linkArmed = !readonly && (e.metaKey || e.ctrlKey);
4276
+ // Typing: the note at a link is in the way of the words.
4277
+ if (linkHint && e.key !== 'Meta' && e.key !== 'Control') hideLinkHint();
4278
+ }}
4279
+ onkeyup={(e) => (linkArmed = !readonly && (e.metaKey || e.ctrlKey))}
4280
+ onblur={() => {
4281
+ linkArmed = false;
4282
+ hideLinkHint();
4283
+ }}
4284
+ onresize={() => {
4285
+ placeCopySourceBox();
4286
+ hideLinkHint();
2966
4287
  }}
2967
- onresize={placeCopySourceBox}
2968
4288
  />
2969
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 -->
2970
4294
  <div
2971
4295
  class="ink-editor"
4296
+ onpointerdowncapture={() => history?.step()}
4297
+ onclickcapture={() => history?.step()}
2972
4298
  style:--ink-min-height={minHeight}
2973
4299
  style:--ink-font-family={screenFontFamily}
2974
4300
  style:--ink-font-size="{screenFontSize}pt"
2975
4301
  >
2976
- {#if showToolbar && !readonly}
2977
- <Toolbar
2978
- {formatState}
2979
- blockType={currentBlock}
2980
- onexec={exec}
2981
- onblock={setBlock}
2982
- oninsertlink={openLinkModal}
2983
- oninsertimage={openImageModal}
2984
- fontSize={currentFontSize}
2985
- fontSizes={sizeChoices}
2986
- onfontsize={setFontSize}
2987
- copyingFormat={copyFormat !== 'off'}
2988
- oncopyformat={toggleCopyFormat}
2989
- />
2990
- {/if}
4302
+ {#if !readonly && (showToolbar || copyFormat !== 'off')}
4303
+ <div class="ink-head" class:sticky={stickyToolbar} bind:this={headEl}>
4304
+ {#if showToolbar}
4305
+ <Toolbar
4306
+ {formatState}
4307
+ blockType={currentBlock}
4308
+ onexec={exec}
4309
+ onblock={setBlock}
4310
+ oninsertlink={openLinkModal}
4311
+ oninsertimage={openImageModal}
4312
+ oninserttable={openTableModal}
4313
+ fontSize={currentFontSize}
4314
+ fontSizes={sizeChoices}
4315
+ onfontsize={setFontSize}
4316
+ font={currentFont}
4317
+ fonts={fontList}
4318
+ documentFont={fontChoices([fontFamily])[0]?.name ?? DEFAULT_FONT_FAMILY}
4319
+ onfont={setFont}
4320
+ spacing={currentSpacing}
4321
+ copyingFormat={copyFormat !== 'off'}
4322
+ oncopyformat={toggleCopyFormat}
4323
+ />
4324
+ {/if}
2991
4325
 
2992
- {#if copyFormat !== 'off' && !readonly}
2993
- <div class="ink-copy-format" role="status">
2994
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="14" height="6" rx="1.5"/><path d="M17 6h3v5h-9v3"/><rect x="9.5" y="14" width="3" height="7" rx="1"/></svg>
2995
- <span>
2996
- {copyFormat === 'pick'
2997
- ? 'Copy format: click the paragraph to copy from.'
2998
- : 'Format copied. Click each paragraph that should get it.'}
2999
- </span>
3000
- <button type="button" class="ink-copy-format-done" onmousedown={(e) => e.preventDefault()} onclick={stopCopyFormat}>
3001
- {copyFormat === 'pick' ? 'Cancel' : 'Done'}
3002
- </button>
3003
- <span class="ink-copy-format-key">or press Esc</span>
4326
+ {#if copyFormat !== 'off'}
4327
+ <div class="ink-copy-format" role="status">
4328
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="14" height="6" rx="1.5"/><path d="M17 6h3v5h-9v3"/><rect x="9.5" y="14" width="3" height="7" rx="1"/></svg>
4329
+ <span>
4330
+ {copyFormat === 'pick'
4331
+ ? 'Copy format: click the paragraph to copy from.'
4332
+ : 'Format copied. Click each paragraph that should get it.'}
4333
+ </span>
4334
+ <button type="button" class="ink-copy-format-done" onmousedown={(e) => e.preventDefault()} onclick={stopCopyFormat}>
4335
+ {copyFormat === 'pick' ? 'Cancel' : 'Done'}
4336
+ </button>
4337
+ <span class="ink-copy-format-key">or press Esc</span>
4338
+ </div>
4339
+ {/if}
3004
4340
  </div>
3005
4341
  {/if}
3006
4342
 
3007
4343
  <div class="ink-content-wrap" bind:this={contentWrapEl}>
3008
- <!-- svelte-ignore a11y_no_static_element_interactions -->
4344
+ <!-- (The pointer over a link shows a note of how the pointer opens it: there is nothing
4345
+ in it for the keyboard, which opens a link from the browser's own menu.) -->
4346
+ <!-- svelte-ignore a11y_no_static_element_interactions, a11y_mouse_events_have_key_events -->
3009
4347
  <div
3010
4348
  class="ink-content"
3011
4349
  class:copy-format-pick={copyFormat === 'pick'}
3012
4350
  class:copy-format-apply={copyFormat === 'apply'}
4351
+ class:links-open={linkArmed && linkHint !== null}
3013
4352
  contenteditable={!readonly}
3014
4353
  role="textbox"
3015
4354
  tabindex="0"
@@ -3018,17 +4357,31 @@
3018
4357
  aria-readonly={readonly ? 'true' : undefined}
3019
4358
  spellcheck="true"
3020
4359
  bind:this={editorEl}
4360
+ onbeforeinput={handleBeforeInput}
3021
4361
  oninput={handleInput}
4362
+ oncompositionstart={() => history?.composing(true)}
4363
+ oncompositionend={() => history?.composing(false)}
3022
4364
  onmouseup={caretMoved}
3023
4365
  onkeyup={caretMoved}
3024
4366
  onscroll={contentScrolled}
3025
4367
  onkeydown={handleKeydown}
3026
- onmousedown={() => (tabLeavesEditor = false)}
4368
+ onmousedown={() => {
4369
+ tabLeavesEditor = false;
4370
+ hideLinkHint();
4371
+ }}
4372
+ onmouseover={linkHovered}
4373
+ onmouseout={linkLeft}
3027
4374
  onblur={() => (tabLeavesEditor = false)}
3028
4375
  onpaste={handlePaste}
3029
4376
  onclick={handleContentClick}
3030
- ondragstart={() => (draggedFromHere = true)}
3031
- ondragend={() => (draggedFromHere = false)}
4377
+ ondragstart={(e) => {
4378
+ draggedFromHere = true;
4379
+ pictureDragStarted(e);
4380
+ }}
4381
+ ondragend={() => {
4382
+ draggedFromHere = false;
4383
+ draggedPicture = null;
4384
+ }}
3032
4385
  ondragover={handleDragOver}
3033
4386
  ondrop={handleDrop}
3034
4387
  data-placeholder={placeholder}
@@ -3044,16 +4397,34 @@
3044
4397
  ></div>
3045
4398
  {/if}
3046
4399
 
4400
+ {#if linkHint && !readonly}
4401
+ <div
4402
+ class="ink-link-hint"
4403
+ class:above={linkHint.above}
4404
+ role="tooltip"
4405
+ style:top="{linkHint.top}px"
4406
+ style:left="{linkHint.left}px"
4407
+ >
4408
+ <span class="ink-link-hint-address">{linkHint.href}</span>
4409
+ <span class="ink-link-hint-how">{OPEN_HINT}</span>
4410
+ </div>
4411
+ {/if}
4412
+
3047
4413
  {#if !readonly}
3048
4414
  <ImageOverlay
3049
4415
  bind:this={overlayRef}
3050
4416
  target={selectedImage}
3051
4417
  bounds={contentWrapEl}
3052
4418
  within={editorEl}
3053
- maxWidth={contentWidth}
4419
+ maxWidth={pictureRoom}
3054
4420
  onchange={handleImageEdited}
3055
4421
  onremove={removeSelectedImage}
3056
4422
  oncaption={focusCaption}
4423
+ place={picturePlace}
4424
+ onmove={moveSelectedImage}
4425
+ onbeside={toggleBeside}
4426
+ ongap={setPictureGap}
4427
+ onresizing={pictureResizing}
3057
4428
  />
3058
4429
  {/if}
3059
4430
  </div>
@@ -3096,6 +4467,26 @@
3096
4467
  {/snippet}
3097
4468
  </Modal>
3098
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
+
3099
4490
  <!-- Image Modal -->
3100
4491
  <Modal title="Insert Image" open={imageModalOpen} onclose={() => (imageModalOpen = false)}>
3101
4492
  <button class="ink-file-pick" onclick={chooseImageFiles}>
@@ -3156,6 +4547,22 @@
3156
4547
  width: 100%;
3157
4548
  }
3158
4549
 
4550
+ /* The toolbar, and under it the note of a format being copied. It stays in sight while a
4551
+ long document is scrolled, at the top of the window or of the scrolling element the
4552
+ editor is in: under a header of the page's own, --ink-toolbar-top is that header's
4553
+ height. Its ground is the toolbar's, so that no words show between its parts. */
4554
+ .ink-head {
4555
+ margin: 24px 0 16px;
4556
+ border-radius: var(--radius, 8px);
4557
+ background: var(--bg-toolbar, #fff);
4558
+ }
4559
+
4560
+ .ink-head.sticky {
4561
+ position: sticky;
4562
+ top: var(--ink-toolbar-top, 0px);
4563
+ z-index: 30;
4564
+ }
4565
+
3159
4566
  /* Anchors the image selection frame, which lives outside the
3160
4567
  contenteditable area so it never lands in the exported HTML. */
3161
4568
  .ink-content-wrap {
@@ -3214,7 +4621,7 @@
3214
4621
  display: flex;
3215
4622
  align-items: center;
3216
4623
  gap: 10px;
3217
- margin: -8px 0 12px;
4624
+ margin: 8px 0 0;
3218
4625
  padding: 8px 12px;
3219
4626
  border: 1px solid var(--accent, #6e56cf);
3220
4627
  border-radius: var(--radius-sm, 5px);
@@ -3259,6 +4666,64 @@
3259
4666
  pointer-events: none;
3260
4667
  }
3261
4668
 
4669
+ /* The note at a link under the pointer: where it goes, and how to open it. */
4670
+ .ink-link-hint {
4671
+ position: absolute;
4672
+ z-index: 5;
4673
+ box-sizing: border-box;
4674
+ max-width: min(320px, 100%);
4675
+ display: flex;
4676
+ flex-direction: column;
4677
+ gap: 2px;
4678
+ padding: 6px 10px;
4679
+ border-radius: 8px;
4680
+ background: var(--ink, #1a1714);
4681
+ color: #fff;
4682
+ font-family: 'DM Sans', system-ui, sans-serif;
4683
+ font-size: 12px;
4684
+ line-height: 1.35;
4685
+ box-shadow: 0 4px 14px rgba(0, 0, 0, 0.18);
4686
+ pointer-events: none;
4687
+ /* Not at once: the pointer crosses links on its way elsewhere. */
4688
+ animation: ink-link-hint-in 120ms ease 350ms both;
4689
+ }
4690
+
4691
+ .ink-link-hint.above {
4692
+ transform: translateY(-100%);
4693
+ }
4694
+
4695
+ .ink-link-hint-address {
4696
+ overflow: hidden;
4697
+ white-space: nowrap;
4698
+ text-overflow: ellipsis;
4699
+ opacity: 0.75;
4700
+ }
4701
+
4702
+ .ink-link-hint-how {
4703
+ font-weight: 600;
4704
+ white-space: nowrap;
4705
+ }
4706
+
4707
+ @keyframes ink-link-hint-in {
4708
+ from {
4709
+ opacity: 0;
4710
+ }
4711
+ to {
4712
+ opacity: 1;
4713
+ }
4714
+ }
4715
+
4716
+ @media (prefers-reduced-motion: reduce) {
4717
+ .ink-link-hint {
4718
+ animation-duration: 1ms;
4719
+ }
4720
+ }
4721
+
4722
+ /* Ctrl or Cmd is down: a click will open the link. */
4723
+ .ink-content.links-open :global(a[href]) {
4724
+ cursor: pointer;
4725
+ }
4726
+
3262
4727
  /* Placeholder */
3263
4728
  .ink-content:empty::before {
3264
4729
  content: attr(data-placeholder);
@@ -3358,10 +4823,54 @@
3358
4823
  margin-bottom: 12px;
3359
4824
  }
3360
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
+
3361
4851
  .ink-content :global(li) {
3362
4852
  margin-bottom: 4px;
3363
4853
  }
3364
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
+
3365
4874
  .ink-content :global(a) {
3366
4875
  color: var(--accent, #d4622b);
3367
4876
  text-decoration: underline;
@@ -3376,8 +4885,31 @@
3376
4885
  }
3377
4886
 
3378
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.) */
3379
4892
  .ink-content :global(figure) {
3380
- 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;
3381
4913
  }
3382
4914
 
3383
4915
  .ink-content :global(figure img) {
@@ -3491,6 +5023,45 @@
3491
5023
  color: var(--text-muted, #8a7e72);
3492
5024
  }
3493
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
+
3494
5065
  .ink-modal-error {
3495
5066
  margin: 0 0 12px;
3496
5067
  font-size: 12px;