svelte-rtf-editor 1.9.0 → 1.11.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.
@@ -3,14 +3,18 @@
3
3
  * InkEditor — A reusable Svelte 5 Rich Text Editor component.
4
4
  *
5
5
  * Props:
6
- * content — Initial HTML content (string). Default: empty paragraph.
6
+ * content — Initial HTML content (string). Default: an empty paragraph. It is made
7
+ * safe before it is shown (see sanitize.ts): scripts, event handlers and
8
+ * the like are taken out.
7
9
  * placeholder — Placeholder text shown when editor is empty.
8
- * autosave — Enable localStorage auto-save. Default: true.
10
+ * autosave — Keep a draft in localStorage and restore it on mount, in place of
11
+ * `content`. Default: false. Give each document its own storageKey.
9
12
  * storageKey — localStorage key for auto-save. Default: 'ink-editor-content'.
10
13
  * showToolbar — Show the formatting toolbar. Default: true.
11
14
  * showStatusBar — Show the word/char count status bar. Default: true.
12
15
  * minHeight — CSS min-height of the editing area. Default: '40vh'.
13
16
  * readonly — If true, editor is not editable. Default: false.
17
+ * ariaLabel — The name of the editing area for a screen reader. Default: 'Document'.
14
18
  * maxImageEdge — Longest edge (px) an inserted image is scaled down to.
15
19
  * 0 keeps the original dimensions. Default: 1600.
16
20
  * maxImageDisplayWidth
@@ -26,9 +30,22 @@
26
30
  * maxRtfBytes — The largest RTF file Import reads. Default: 52428800 (50 MB);
27
31
  * 0 reads any size.
28
32
  * fontFamily — Font for the document, both on screen and in the RTF.
29
- * Default: 'Arial'.
33
+ * Default: DEFAULT_FONT_FAMILY (rtf-writer.ts).
30
34
  * fontSize — Body text size in points, both on screen and in the RTF.
31
35
  * Headings scale from it. Default: 12.
36
+ * fontSizes — The sizes, in points, the toolbar's size list offers for the
37
+ * selected text. The body size is always among them. An empty
38
+ * list takes the size list off the toolbar.
39
+ * Default: 8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 36.
40
+ * keepAttributes — `data-` attributes the application's documents carry, which
41
+ * the editor leaves on their elements: a mark on a paragraph that
42
+ * the application reads back (`data-section="2"`). Every other
43
+ * attribute the editor does not know is taken off HTML as it comes
44
+ * in, set or pasted. Names that do not start with `data-` are not
45
+ * kept. Default: none.
46
+ * keepClasses — Class names of the application's own that stay in an element's
47
+ * class list the same way (`<pre class="summary">`). Every other
48
+ * class is taken off. Default: none.
32
49
  *
33
50
  * Events (callback props):
34
51
  * onchange — Fires on content change with
@@ -54,6 +71,7 @@
54
71
  import Modal from './Modal.svelte';
55
72
  import ImageOverlay from './ImageOverlay.svelte';
56
73
  import { htmlToMarkdown, downloadFile } from '../utils.js';
74
+ import { keptMarks, pasteNotes, removeWordHidden, sanitizedNodes, sanitizeTree, type PasteNotes } from '../sanitize.js';
57
75
  import { readRtfFile, DEFAULT_MAX_RTF_BYTES } from '../rtf-parser.js';
58
76
  import {
59
77
  htmlToRtf,
@@ -76,15 +94,21 @@
76
94
  } from '../images.js';
77
95
 
78
96
  interface ChangePayload {
79
- html: string;
80
- text: string;
97
+ /**
98
+ * `html`, `text` and `estimatedRtfBytes` are worked out when the handler reads them, and
99
+ * once: on a long document each is work, and most handlers read one of them or none.
100
+ * They are the document as it is when first read, so read them in the handler. A payload
101
+ * kept and read after a later edit gives the document as it is by then.
102
+ */
103
+ readonly html: string;
104
+ readonly text: string;
81
105
  wordCount: number;
82
106
  charCount: number;
83
107
  /**
84
108
  * Approximate size of this document as RTF. Pictures dominate it and are
85
109
  * counted exactly; see getRtfSize() for the precise figure.
86
110
  */
87
- estimatedRtfBytes: number;
111
+ readonly estimatedRtfBytes: number;
88
112
  }
89
113
 
90
114
  interface Props {
@@ -96,6 +120,7 @@
96
120
  showStatusBar?: boolean;
97
121
  minHeight?: string;
98
122
  readonly?: boolean;
123
+ ariaLabel?: string;
99
124
  maxImageEdge?: number;
100
125
  maxImageBytes?: number;
101
126
  maxImageDisplayWidth?: number;
@@ -103,32 +128,54 @@
103
128
  maxRtfBytes?: number;
104
129
  fontFamily?: string;
105
130
  fontSize?: number;
131
+ fontSizes?: number[];
132
+ /** `data-` attributes of the application's own, kept on HTML that is set or pasted. */
133
+ keepAttributes?: string[];
134
+ /** Class names of the application's own, kept the same way. */
135
+ keepClasses?: string[];
106
136
  onchange?: (payload: ChangePayload) => void;
107
137
  onsave?: (payload: { html: string }) => void;
108
138
  onimport?: (payload: { html: string }) => void;
109
139
  }
110
140
 
141
+ /**
142
+ * An empty document: one paragraph with the line break that gives it height. Without the
143
+ * break the paragraph has no line to put the caret in, the first words typed land outside it,
144
+ * and the RTF then carries the empty paragraph as a blank line the screen never showed.
145
+ */
146
+ const EMPTY_DOCUMENT = '<p><br></p>';
147
+
148
+ /** The sizes, in points, the toolbar's size list offers unless `fontSizes` says otherwise. */
149
+ const DEFAULT_FONT_SIZES = [8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 36];
150
+ const NO_KEPT_ATTRIBUTES: string[] = [];
151
+
111
152
  // ── Props ──
112
153
  let {
113
- content = '<p></p>',
154
+ content = EMPTY_DOCUMENT,
114
155
  placeholder = 'Start writing something beautiful...',
115
- autosave = true,
156
+ autosave = false,
116
157
  storageKey = 'ink-editor-content',
117
158
  showToolbar = true,
118
159
  showStatusBar = true,
119
160
  minHeight = '40vh',
120
161
  readonly = false,
162
+ ariaLabel = 'Document',
121
163
  maxImageEdge = DEFAULT_MAX_IMAGE_EDGE,
122
164
  maxImageBytes = DEFAULT_MAX_IMAGE_BYTES,
123
165
  maxImageDisplayWidth = DEFAULT_MAX_IMAGE_DISPLAY_WIDTH,
124
166
  maxRtfBytes = DEFAULT_MAX_RTF_BYTES,
125
167
  fontFamily = DEFAULT_FONT_FAMILY,
126
168
  fontSize = DEFAULT_FONT_SIZE,
169
+ fontSizes = DEFAULT_FONT_SIZES,
170
+ keepAttributes = NO_KEPT_ATTRIBUTES,
171
+ keepClasses = NO_KEPT_ATTRIBUTES,
127
172
  onchange,
128
173
  onsave,
129
174
  onimport
130
175
  }: Props = $props();
131
176
 
177
+ const keptNames = $derived(keptMarks({ keepAttributes, keepClasses }));
178
+
132
179
  // The same font and size go to the screen and to the RTF, so the editor
133
180
  // shows what the receiving system will show.
134
181
  const rtfOptions = $derived({ fontFamily, fontSize });
@@ -142,6 +189,8 @@
142
189
  let charCount: number = $state(0);
143
190
  let lastSaved: string = $state('');
144
191
  let currentBlock: string = $state('p');
192
+ /** The size of the text at the caret, in points, for the toolbar. */
193
+ let currentFontSize: number | null = $state(null);
145
194
 
146
195
  let formatState = $state({
147
196
  bold: false,
@@ -186,12 +235,31 @@
186
235
  if (editorEl) {
187
236
  selectedImage = null;
188
237
  documentReplaced();
189
- editorEl.innerHTML = html;
238
+ showDocument(html);
190
239
  updateCounts();
191
240
  if (autosave) scheduleAutoSave();
192
241
  }
193
242
  }
194
243
 
244
+ /**
245
+ * Put HTML from outside in the editor: made safe first, and with a line in every empty
246
+ * paragraph, so it shows as the blank line the RTF writes for it. The nodes that were checked
247
+ * are the nodes shown (see sanitizedNodes): the HTML is read once.
248
+ */
249
+ function showDocument(html: string): void {
250
+ if (!editorEl) return;
251
+ // An id the page already uses outside an editor is not the document's to take: see
252
+ // sanitize.ts. (Another editor on the page may hold a document with the same ids.)
253
+ const idTaken = (id: string) => {
254
+ const owner = document.getElementById(id);
255
+ return owner !== null && owner.closest('.ink-content') === null;
256
+ };
257
+ editorEl.replaceChildren(...sanitizedNodes(html, document, idTaken, keptNames));
258
+ for (const p of Array.from(editorEl.querySelectorAll('p'))) {
259
+ if (p.childNodes.length === 0) p.appendChild(document.createElement('br'));
260
+ }
261
+ }
262
+
195
263
  export function getMarkdown(): string {
196
264
  if (!editorEl) return '';
197
265
  return htmlToMarkdown(editorEl);
@@ -218,7 +286,8 @@
218
286
  if (editorEl) {
219
287
  selectedImage = null;
220
288
  documentReplaced();
221
- editorEl.innerHTML = '<p></p>';
289
+ editorEl.innerHTML = EMPTY_DOCUMENT;
290
+ clearTimeout(saveTimer);
222
291
  try { localStorage.removeItem(storageKey); } catch (e) {}
223
292
  updateCounts();
224
293
  lastSaved = '';
@@ -264,6 +333,7 @@
264
333
  function documentReplaced(): void {
265
334
  indentUndo = [];
266
335
  pastedOver = null;
336
+ pastedLoss = null;
267
337
  stopCopyFormat();
268
338
  }
269
339
 
@@ -297,6 +367,179 @@
297
367
  }
298
368
  }
299
369
 
370
+ // ── Font size ──
371
+ // The size of the selected text, or of what is typed next, is set with the browser's own
372
+ // command: it wraps exactly the selection, takes a size already there out of it, and its
373
+ // steps can be undone with everything else. But it knows only seven sizes and writes them as
374
+ // <font size="1"> to <font size="7">. So it is asked for size 7, which nothing else in the
375
+ // editor makes, and each element it marked that way is then given the size meant, in points
376
+ // (<font style="font-size:14pt">), which is what the RTF writer reads. Only attributes are
377
+ // changed, never the elements, so the browser's undo still finds what it made.
378
+ //
379
+ // Undo puts back what the browser itself recorded, which is right: the element goes, or gets
380
+ // back the size it had. Redo is not: the browser does its own step again, the mark for size 7
381
+ // and nothing after it, and the text came back at 36 pt. So each change of size is remembered
382
+ // here with the size every element was given, and after a redo the elements that are marked
383
+ // again are given theirs again.
384
+ //
385
+ // And undo is only right where the browser recorded something to put back. It records the
386
+ // size it takes off an element, not the one given here afterwards. So a <font> element is
387
+ // never left without a size of its own: where the text is to have the size of the text around
388
+ // it, the size stated is 1em, which is that size. The writer reads 1em as no size.
389
+ const SIZE_MARK = '7';
390
+ /** The size that is the size of the text around: what "no size of its own" is written as. */
391
+ const SIZE_AROUND = '1em';
392
+ /** One change of size: the elements it sized, each with the font-size it was given. */
393
+ type SizeStep = Map<HTMLElement, string>;
394
+ /** The changes of size made, in order; those from `sizeStepsApplied` on were undone and can be redone. */
395
+ let sizeSteps: SizeStep[] = [];
396
+ let sizeStepsApplied = 0;
397
+ /** Every element this editor has given a size: a mark on one of these is the browser redoing a step. */
398
+ const sizedHere = new WeakSet<Element>();
399
+ /** The size chosen and not yet given to an element: a caret has no text to carry it until something is typed. */
400
+ let pendingSize: number | null = null;
401
+ /** Elements that were marked size 7 before the command (pasted that way): not ours to change. */
402
+ let markedBefore = new Set<Element>();
403
+
404
+ /** The size of an element's text as the screen shows it, in points to the half-point; null if unknown. */
405
+ function shownSize(el: Element): number | null {
406
+ const px = parseFloat(getComputedStyle(el).fontSize);
407
+ return Number.isFinite(px) && px > 0 ? Math.round(px * 0.75 * 2) / 2 : null;
408
+ }
409
+
410
+ /** Take the mark off an element and state the size it is to have. */
411
+ function sizeElement(font: HTMLElement, fontSize: string): void {
412
+ font.removeAttribute('size');
413
+ font.style.fontSize = fontSize;
414
+ }
415
+
416
+ const markedElements = (): HTMLElement[] =>
417
+ editorEl ? Array.from(editorEl.querySelectorAll<HTMLElement>(`font[size="${SIZE_MARK}"]`)) : [];
418
+
419
+ /** Give the elements the command marked the size that was chosen, and remember the step. */
420
+ function applyPendingSize(): void {
421
+ if (!editorEl || pendingSize === null) return;
422
+ const step: SizeStep = new Map();
423
+ for (const font of markedElements()) {
424
+ if (markedBefore.has(font)) continue;
425
+ sizeElement(font, SIZE_AROUND);
426
+ // Where the text around it has that size already (body text set back to the body
427
+ // size, a heading to the heading's), it stays at the size around it: the text then
428
+ // follows the document's size, as text that was never sized does.
429
+ if (shownSize(font) !== pendingSize) sizeElement(font, `${pendingSize}pt`);
430
+ step.set(font, font.style.fontSize);
431
+ sizedHere.add(font);
432
+ }
433
+ if (step.size === 0) return;
434
+ // A new change: what was undone before it can no longer be redone.
435
+ sizeSteps = [...sizeSteps.slice(0, sizeStepsApplied), step];
436
+ sizeStepsApplied = sizeSteps.length;
437
+ }
438
+
439
+ /** Whether a change of size is in the document as it was made: every element there, with its size. */
440
+ function stepStands(step: SizeStep | undefined): boolean {
441
+ if (!step) return false;
442
+ for (const [font, fontSize] of step) {
443
+ if (!font.isConnected || font.getAttribute('size') === SIZE_MARK || font.style.fontSize !== fontSize) return false;
444
+ }
445
+ return true;
446
+ }
447
+
448
+ /** After an undo or a redo: follow which changes of size are in the document, and finish a redone one. */
449
+ function afterHistory(): void {
450
+ const next = sizeSteps[sizeStepsApplied];
451
+ const marked = markedElements().filter((font) => sizedHere.has(font));
452
+ if (marked.length > 0) {
453
+ // The browser redid its part of a change of size. (A mark with no step to go with it
454
+ // should not happen; it is then taken off, and the text has the size around it,
455
+ // which is better than 36 pt.)
456
+ for (const font of marked) sizeElement(font, next?.get(font) ?? SIZE_AROUND);
457
+ if (next) sizeStepsApplied++;
458
+ } else if (stepStands(next)) {
459
+ // Redone, and nothing was marked: the step only made elements, which came back as they were.
460
+ sizeStepsApplied++;
461
+ } else if (sizeStepsApplied > 0 && !stepStands(sizeSteps[sizeStepsApplied - 1])) {
462
+ sizeStepsApplied--;
463
+ }
464
+ }
465
+
466
+ /** Whether all the text selected has this size already. */
467
+ function selectionHasSize(points: number): boolean {
468
+ const selection = window.getSelection();
469
+ if (!editorEl || !selection || selection.rangeCount === 0 || selection.isCollapsed) return false;
470
+ const range = selection.getRangeAt(0);
471
+ const walker = document.createTreeWalker(range.commonAncestorContainer, NodeFilter.SHOW_TEXT);
472
+ let texts = 0;
473
+ for (let node = walker.currentNode.nodeType === Node.TEXT_NODE ? walker.currentNode : walker.nextNode(); node; node = walker.nextNode()) {
474
+ if (!range.intersectsNode(node) || !(node.textContent || '').trim() || !node.parentElement) continue;
475
+ if (shownSize(node.parentElement) !== points) return false;
476
+ texts++;
477
+ }
478
+ return texts > 0;
479
+ }
480
+
481
+ /**
482
+ * Set the size, in points, of the selected text; with nothing selected, of what is typed next.
483
+ * Also what the toolbar's size list calls.
484
+ */
485
+ export function setFontSize(points: number): void {
486
+ if (readonly || !editorEl) return;
487
+ if (typeof points !== 'number' || !Number.isFinite(points) || points <= 0) return;
488
+ restoreSelection();
489
+ editorEl.focus();
490
+ // The document changes outside an input event: earlier indent steps no longer undo.
491
+ indentUndo = [];
492
+ const size = normalizeFontSize(points);
493
+ // Nothing to change: no step is made that would undo to the same thing.
494
+ if (selectionHasSize(size)) {
495
+ updateToolbarState();
496
+ return;
497
+ }
498
+ markedBefore = new Set(markedElements());
499
+ // The command may use a <font> element that is there already (one pasted with a color),
500
+ // and undo then puts back only a size the command itself took off it: see SIZE_AROUND.
501
+ for (const font of Array.from(editorEl.querySelectorAll<HTMLElement>('font'))) {
502
+ if (!font.style.fontSize && !markedBefore.has(font)) font.style.fontSize = SIZE_AROUND;
503
+ }
504
+ pendingSize = size;
505
+ document.execCommand('fontSize', false, SIZE_MARK);
506
+ applyPendingSize();
507
+ // With text selected the size is on it now. At a caret it waits for the typing.
508
+ const selection = window.getSelection();
509
+ if (selection && !selection.isCollapsed) pendingSize = null;
510
+ updateToolbarState();
511
+ fireChange();
512
+ if (autosave) scheduleAutoSave();
513
+ }
514
+
515
+ /** The size of the text at the selection, for the toolbar: null where it starts and ends in different sizes. */
516
+ function sizeAtSelection(): number | null {
517
+ if (pendingSize !== null) return pendingSize;
518
+ const selection = window.getSelection();
519
+ if (!editorEl || !selection || selection.rangeCount === 0) return null;
520
+ const range = selection.getRangeAt(0);
521
+ if (!editorEl.contains(range.startContainer)) return null;
522
+ const holder = (node: Node, offset: number, atEnd: boolean): Element | null => {
523
+ if (node.nodeType === Node.ELEMENT_NODE) {
524
+ const child = node.childNodes[atEnd ? offset - 1 : offset];
525
+ return child?.nodeType === Node.ELEMENT_NODE ? (child as Element) : (node as Element);
526
+ }
527
+ return node.parentElement;
528
+ };
529
+ const start = holder(range.startContainer, range.startOffset, false);
530
+ const first = start ? shownSize(start) : null;
531
+ if (range.collapsed) return first;
532
+ const end = holder(range.endContainer, range.endOffset, true);
533
+ return end && shownSize(end) === first ? first : null;
534
+ }
535
+
536
+ /** The sizes the list offers: those asked for, and always the body size. */
537
+ const sizeChoices = $derived.by(() => {
538
+ const sizes = fontSizes.map((size) => normalizeFontSize(size));
539
+ if (sizes.length === 0) return sizes;
540
+ return Array.from(new Set([...sizes, screenFontSize])).sort((a, b) => a - b);
541
+ });
542
+
300
543
  // ── Exec command ──
301
544
  function exec(cmd: string, value: string | null = null): void {
302
545
  restoreSelection();
@@ -318,6 +561,7 @@
318
561
  }
319
562
  if (cmd === 'undo' && undoIndent()) return;
320
563
  document.execCommand(cmd, false, value ?? undefined);
564
+ if (cmd === 'undo' || cmd === 'redo') afterHistory();
321
565
  updateToolbarState();
322
566
  }
323
567
 
@@ -896,6 +1140,7 @@
896
1140
  // Snapshot the selection so exec/setBlock can restore it even if focus
897
1141
  // temporarily moved to a toolbar element (e.g. colour picker, select).
898
1142
  saveSelection();
1143
+ currentFontSize = sizeAtSelection();
899
1144
 
900
1145
  formatState = {
901
1146
  bold: document.queryCommandState('bold'),
@@ -912,21 +1157,52 @@
912
1157
  updateCounts();
913
1158
  }
914
1159
 
1160
+ /**
1161
+ * A click or a key in the text. A size chosen at a caret and not yet typed in is given up: the
1162
+ * browser drops it when the caret moves, and the toolbar must not go on showing it.
1163
+ */
1164
+ function caretMoved(): void {
1165
+ pendingSize = null;
1166
+ updateToolbarState();
1167
+ }
1168
+
1169
+ /** The editing area was scrolled sideways (a wide table): what is drawn over it moves with it. */
1170
+ function contentScrolled(): void {
1171
+ overlayRef?.reposition();
1172
+ placeCopySourceBox();
1173
+ }
1174
+
915
1175
  function updateCounts(): void {
916
1176
  if (!editorEl) return;
917
- const text = editorEl.innerText || '';
1177
+ const shown = editorEl.innerText || '';
1178
+ // A document with nothing in it is a paragraph with a line break, which innerText gives
1179
+ // as one character: an empty report then counted one, and so did one of blank lines only.
1180
+ const text = shown.trim() === '' && !editorEl.querySelector('img, table, hr') ? '' : shown;
918
1181
  const words = text.trim().split(/\s+/).filter((w) => w.length > 0);
919
1182
  wordCount = words.length;
920
1183
  charCount = text.length;
921
1184
  }
922
1185
 
923
1186
  function fireChange(): void {
924
- onchange?.({
925
- html: editorEl?.innerHTML || '',
926
- text: editorEl?.innerText || '',
1187
+ if (!onchange) return;
1188
+ // The HTML, the text and the size estimate each read the whole document, and this runs on
1189
+ // every keystroke: with a few pictures in the document it took a tenth of a second. Each is
1190
+ // worked out when the handler asks for it, once, and not at all if it never does.
1191
+ const el = editorEl;
1192
+ const options = { fontFamily, fontSize };
1193
+ const once = <T,>(read: () => T): (() => T) => {
1194
+ let value: { v: T } | null = null;
1195
+ return () => (value ??= { v: read() }).v;
1196
+ };
1197
+ const html = once(() => el?.innerHTML || '');
1198
+ const text = once(() => el?.innerText || '');
1199
+ const estimate = once(() => (el ? estimateRtfBytes(el, options) : 0));
1200
+ onchange({
1201
+ get html() { return html(); },
1202
+ get text() { return text(); },
927
1203
  wordCount,
928
1204
  charCount,
929
- estimatedRtfBytes: editorEl ? estimateRtfBytes(editorEl) : 0
1205
+ get estimatedRtfBytes() { return estimate(); }
930
1206
  });
931
1207
  }
932
1208
 
@@ -953,13 +1229,23 @@
953
1229
  }
954
1230
 
955
1231
  // ── Input handler ──
956
- function handleInput(): void {
1232
+ function handleInput(e?: Event): void {
957
1233
  placeCopySourceBox();
958
1234
  if (pastedOver) {
959
1235
  tidyPasted(pastedOver);
960
1236
  pastedOver = null;
961
1237
  }
962
1238
  indentUndo = [];
1239
+ const kind = (e as InputEvent | undefined)?.inputType ?? '';
1240
+ if (kind === 'historyUndo' || kind === 'historyRedo') {
1241
+ afterHistory();
1242
+ } else {
1243
+ // An edit: what was undone can no longer be redone.
1244
+ sizeSteps = sizeSteps.slice(0, sizeStepsApplied);
1245
+ // What was typed at a caret after a size was chosen came in marked: give it the size.
1246
+ applyPendingSize();
1247
+ }
1248
+ pendingSize = null;
963
1249
  updateToolbarState();
964
1250
  // Typing means the user is editing text, not the picture. Dropping the
965
1251
  // selection here keeps Backspace editing that text instead of deleting a
@@ -999,7 +1285,7 @@
999
1285
  const range = sel.getRangeAt(0);
1000
1286
  range.deleteContents();
1001
1287
  const a = document.createElement('a');
1002
- a.href = linkUrl;
1288
+ a.href = linkUrl.trim();
1003
1289
  a.textContent = linkText;
1004
1290
  range.insertNode(a);
1005
1291
  range.setStartAfter(a);
@@ -1007,9 +1293,24 @@
1007
1293
  sel.addRange(range);
1008
1294
  }
1009
1295
  } else {
1010
- document.execCommand('createLink', false, linkUrl);
1296
+ document.execCommand('createLink', false, linkUrl.trim());
1011
1297
  }
1012
1298
  linkModalOpen = false;
1299
+ updateCounts();
1300
+ fireChange();
1301
+ if (autosave) scheduleAutoSave();
1302
+ }
1303
+
1304
+ /**
1305
+ * Enter in a dialog's field does what the dialog's button does. The key press ends here: the
1306
+ * dialog hands the keyboard back to the document, where the same Enter would go on to replace
1307
+ * the selected text with a new line.
1308
+ */
1309
+ function onEnter(e: KeyboardEvent, act: () => void): void {
1310
+ if (e.key !== 'Enter' || e.isComposing) return;
1311
+ e.preventDefault();
1312
+ e.stopPropagation();
1313
+ act();
1013
1314
  }
1014
1315
 
1015
1316
  // ── Images ──
@@ -1053,7 +1354,18 @@
1053
1354
 
1054
1355
  insertingImages = true;
1055
1356
  try {
1056
- const { src, embedded } = await urlToImageSrc(url, imageLimits());
1357
+ const { src, embedded, tooLarge, unreadable } = await urlToImageSrc(url, imageLimits());
1358
+ // Picture data over the size limit that could not be reduced is not inserted:
1359
+ // once in the document it would be written to the RTF at its full size.
1360
+ if (tooLarge) {
1361
+ showError(TOO_LARGE_MESSAGE);
1362
+ return;
1363
+ }
1364
+ // Nor is picture data the browser cannot open: it would show as a broken picture.
1365
+ if (unreadable) {
1366
+ showError(UNREADABLE_MESSAGE);
1367
+ return;
1368
+ }
1057
1369
  restoreSelection();
1058
1370
  editorEl?.focus();
1059
1371
  finishInsert(insertFigure(src, alt || caption, caption));
@@ -1066,6 +1378,13 @@
1066
1378
  }
1067
1379
  }
1068
1380
 
1381
+ /** Said when picture data given by address or pasted is over the size limit and cannot be reduced. */
1382
+ const TOO_LARGE_MESSAGE = 'That picture is over the size limit and could not be made smaller, so it was not inserted';
1383
+
1384
+ /** Said when picture data given by address is in a format the browser cannot show, or is damaged. */
1385
+ const UNREADABLE_MESSAGE =
1386
+ 'That picture could not be opened (the browser cannot show its format, or it is damaged), so it was not inserted';
1387
+
1069
1388
  /** Caps applied to a picture as it is inserted. */
1070
1389
  function imageLimits(): { maxEdge: number; maxBytes: number } {
1071
1390
  return { maxEdge: maxImageEdge, maxBytes: maxImageBytes };
@@ -1216,9 +1535,14 @@
1216
1535
  finishInsert(inserted);
1217
1536
  }
1218
1537
 
1538
+ let errorTimer: ReturnType<typeof setTimeout> | undefined;
1539
+
1219
1540
  function showError(message: string): void {
1220
1541
  importError = message;
1221
- setTimeout(() => (importError = ''), 4000);
1542
+ // Up for long enough to be read: four seconds, and longer for a message that says more
1543
+ // than one thing. An earlier message's timer must not take a later message down early.
1544
+ clearTimeout(errorTimer);
1545
+ errorTimer = setTimeout(() => (importError = ''), Math.max(4000, message.length * 50));
1222
1546
  }
1223
1547
 
1224
1548
  // ── Image selection / editing ──
@@ -1325,7 +1649,9 @@
1325
1649
  if (editorEl) {
1326
1650
  selectedImage = null;
1327
1651
  documentReplaced();
1328
- editorEl.innerHTML = html;
1652
+ // (What the reader writes is safe as it stands; it goes the same way as any other
1653
+ // HTML so there is one way in.)
1654
+ showDocument(html);
1329
1655
  updateCounts();
1330
1656
  fireChange();
1331
1657
  if (autosave) scheduleAutoSave();
@@ -1533,15 +1859,59 @@
1533
1859
  if (!readonly && editorEl) {
1534
1860
  const snapshot = new Set(editorEl.querySelectorAll('*'));
1535
1861
  pastedOver = snapshot;
1862
+ // What the browser's paste may lose (see pasteNotes), and where the paste begins.
1863
+ const notes = pasteNotes(e.clipboardData?.getData('text/html') ?? '');
1864
+ const start = sel && sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
1865
+ pastedLoss =
1866
+ notes && start && editorEl.contains(start.startContainer)
1867
+ ? { notes, from: shownCharsBefore(start.startContainer, start.startOffset) }
1868
+ : null;
1536
1869
  // A paste that inserts nothing (an empty clipboard, a host that cancels it) raises no
1537
1870
  // input event. Left set, the snapshot would make the next keystroke treat the whole
1538
1871
  // document as pasted.
1539
1872
  setTimeout(() => {
1540
- if (pastedOver === snapshot) pastedOver = null;
1873
+ if (pastedOver === snapshot) {
1874
+ pastedOver = null;
1875
+ pastedLoss = null;
1876
+ }
1541
1877
  }, 0);
1542
1878
  }
1543
1879
  }
1544
1880
 
1881
+ /** How many characters that are not white space the document has before a place in it. */
1882
+ function shownCharsBefore(node: Node, offset: number): number {
1883
+ if (!editorEl) return 0;
1884
+ const range = document.createRange();
1885
+ range.selectNodeContents(editorEl);
1886
+ range.setEnd(node, offset);
1887
+ return range.toString().replace(/\s/g, '').length;
1888
+ }
1889
+
1890
+ /**
1891
+ * Set right what the browser's paste changed before it could be looked at: Word's hidden
1892
+ * text shown as text, and a text box left empty.
1893
+ */
1894
+ function restorePasteLoss(before: Set<Element>, loss: { notes: PasteNotes; from: number }): void {
1895
+ if (!editorEl) return;
1896
+ const areas = Array.from(editorEl.querySelectorAll('textarea')).filter((area) => !before.has(area));
1897
+ if (areas.length === loss.notes.textareas.length) {
1898
+ areas.forEach((area, i) => {
1899
+ if (area.value === '') area.textContent = loss.notes.textareas[i];
1900
+ });
1901
+ }
1902
+ // After a paste the caret is at its end.
1903
+ const sel = window.getSelection();
1904
+ if (!sel || sel.rangeCount === 0 || !sel.isCollapsed || !editorEl.contains(sel.anchorNode)) return;
1905
+ const caret = sel.getRangeAt(0);
1906
+ const to = shownCharsBefore(caret.startContainer, caret.startOffset);
1907
+ // A pasted element left with nothing in it goes, but not the one the caret is in: that
1908
+ // one becomes an empty line, to type in. (Taken out as well, a paste of hidden text
1909
+ // alone left the caret in no line at all, and the next words typed were in none.)
1910
+ const held = sel.anchorNode instanceof Element ? sel.anchorNode : (sel.anchorNode?.parentElement ?? null);
1911
+ if (!removeWordHidden(editorEl, loss.from, to, loss.notes, (el) => !before.has(el) && !(held !== null && el.contains(held)))) return;
1912
+ if (held && held !== editorEl && held.isConnected && held.childNodes.length === 0) held.appendChild(document.createElement('br'));
1913
+ }
1914
+
1545
1915
  // ── Pasted formatting ──
1546
1916
  // A browser copies a paragraph with its looks written out: Chromium turns the editor's own
1547
1917
  // spacing into "margin: 0px 0px 0.2em 96px" on the copy, and repeats the id. Pasted back, the
@@ -1552,9 +1922,17 @@
1552
1922
  const PASTED_SPACING = ['margin-top', 'margin-right', 'margin-bottom', 'margin-left', 'text-indent'];
1553
1923
  /** The elements in the editor just before a paste; what is not in it came from the paste. */
1554
1924
  let pastedOver: Set<Element> | null = null;
1925
+ /** What the paste under way may lose, and how much text the document had before it. */
1926
+ let pastedLoss: { notes: PasteNotes; from: number } | null = null;
1555
1927
 
1556
1928
  function tidyPasted(before: Set<Element>): void {
1557
1929
  if (!editorEl) return;
1930
+ if (pastedLoss) restorePasteLoss(before, pastedLoss);
1931
+ pastedLoss = null;
1932
+ // What the paste brought is made safe as HTML from anywhere else is: a browser takes the
1933
+ // scripts out of a paste itself, but leaves a form, an <iframe>, or a block with
1934
+ // position: fixed that covers the page.
1935
+ sanitizeTree(editorEl, (el) => !before.has(el), undefined, keptNames);
1558
1936
  for (const el of Array.from(editorEl.querySelectorAll<HTMLElement>('*'))) {
1559
1937
  if (before.has(el)) continue;
1560
1938
  el.removeAttribute('id');
@@ -1574,43 +1952,100 @@
1574
1952
  // JPEG data held in the document reaches the RTF, so each one goes through the same step as
1575
1953
  // the image dialog: fetched, converted and scaled as needed.
1576
1954
  const pasted = Array.from(editorEl.querySelectorAll('img')).filter((img) => !before.has(img));
1577
- if (pasted.length > 0) void embedPastedImages(pasted);
1955
+ if (pasted.length === 0) return;
1956
+ // A browser pasting a block into an empty line puts the block in the line's place. If the
1957
+ // pictures of the paste are then taken out, that line is put back (removePastedImages).
1958
+ const replaced = Array.from(before).find(
1959
+ (el) => !el.isConnected && el.parentNode === null && el.matches('p, div') && showsNothing(el)
1960
+ );
1961
+ void embedPastedImages(pasted, before, replaced ?? null);
1578
1962
  }
1579
1963
 
1580
1964
  /**
1581
1965
  * Fetch each pasted picture and hold its data in the document. One that cannot be fetched
1582
1966
  * (the site forbids it, or there is no network) still shows, but leaves in the RTF as an
1583
1967
  * "[Image: …]" placeholder: the editor says so now, rather than letting it be found downstream.
1968
+ * `before` is what was in the document before the paste, and `replaced` an empty line of it
1969
+ * whose place the paste took.
1584
1970
  */
1585
- async function embedPastedImages(images: HTMLImageElement[]): Promise<void> {
1971
+ async function embedPastedImages(images: HTMLImageElement[], before: Set<Element>, replaced: Element | null): Promise<void> {
1586
1972
  let failed = 0;
1587
1973
  let changed = false;
1974
+ // Pictures that must not stay: pasted picture data over the size limit that could not be
1975
+ // reduced, which left in the document would be written to the RTF at its full size, and
1976
+ // picture data the browser cannot open, which would show as a broken picture.
1977
+ const leftOut = new Map<HTMLImageElement, 'tooLarge' | 'unreadable'>();
1978
+ const embed = async (img: HTMLImageElement): Promise<void> => {
1979
+ const url = img.getAttribute('src') || '';
1980
+ if (!isSafeImageUrl(url)) {
1981
+ failed++;
1982
+ return;
1983
+ }
1984
+ const { src, embedded, tooLarge, unreadable } = await urlToImageSrc(url, imageLimits());
1985
+ // It may have been deleted or replaced while it was fetched.
1986
+ if (!img.isConnected || img.getAttribute('src') !== url) return;
1987
+ if (tooLarge || unreadable) {
1988
+ leftOut.set(img, tooLarge ? 'tooLarge' : 'unreadable');
1989
+ } else if (!embedded) {
1990
+ failed++;
1991
+ } else if (src !== url) {
1992
+ img.setAttribute('src', src);
1993
+ changed = true;
1994
+ }
1995
+ };
1996
+ /** What to say of the pictures left out so far; they are taken out as this is asked. */
1997
+ const takeOut = (): string[] => {
1998
+ const gone = images.filter((img) => leftOut.has(img) && img.isConnected);
1999
+ if (gone.length > 0) {
2000
+ removePastedImages(gone, before, replaced);
2001
+ updateCounts();
2002
+ fireChange();
2003
+ if (autosave) scheduleAutoSave();
2004
+ }
2005
+ const count = (kind: 'tooLarge' | 'unreadable') => Array.from(leftOut.values()).filter((k) => k === kind).length;
2006
+ const tooLarge = count('tooLarge');
2007
+ const unreadable = count('unreadable');
2008
+ const said: string[] = [];
2009
+ if (tooLarge > 0) {
2010
+ said.push(
2011
+ tooLarge === 1
2012
+ ? 'A pasted picture was over the size limit and could not be made smaller, so it was left out'
2013
+ : `${tooLarge} pasted pictures were over the size limit and could not be made smaller, so they were left out`
2014
+ );
2015
+ }
2016
+ if (unreadable > 0) {
2017
+ said.push(
2018
+ unreadable === 1
2019
+ ? 'A pasted picture could not be opened (the browser cannot show its format, or it is damaged), so it was left out'
2020
+ : `${unreadable} pasted pictures could not be opened (the browser cannot show their format, or they are damaged), so they were left out`
2021
+ );
2022
+ }
2023
+ return said;
2024
+ };
2025
+
1588
2026
  // All at once, each with its own timeout, so one slow site does not hold up the rest.
1589
- await Promise.all(
1590
- images.map(async (img) => {
1591
- const url = img.getAttribute('src') || '';
1592
- if (!isSafeImageUrl(url)) {
1593
- failed++;
1594
- return;
1595
- }
1596
- const { src, embedded } = await urlToImageSrc(url, imageLimits());
1597
- // It may have been deleted or replaced while it was fetched.
1598
- if (!img.isConnected || img.getAttribute('src') !== url) return;
1599
- if (!embedded) {
1600
- failed++;
1601
- } else if (src !== url) {
1602
- img.setAttribute('src', src);
1603
- changed = true;
1604
- }
1605
- })
1606
- );
2027
+ const isData = (img: HTMLImageElement) => /^\s*data:/i.test(img.getAttribute('src') || '');
2028
+ const fetched = images.filter((img) => !isData(img)).map(embed);
2029
+ // Picture data needs no network. Once all of it is settled, what has to go is taken out
2030
+ // in one pass in the order of the document, without waiting for a slow site: in the
2031
+ // order each happened to finish, what is left of a figure would depend on chance.
2032
+ await Promise.all(images.filter(isData).map(embed));
2033
+ const saidFirst = takeOut();
2034
+ if (saidFirst.length > 0) showError(saidFirst.join('. '));
2035
+
2036
+ await Promise.all(fetched);
2037
+ // One paste can do all of it, and each is something the user has to know: a picture that
2038
+ // is gone, and a picture that is there but will leave as a placeholder. So what was said
2039
+ // of the first is said again with the second, not replaced by it.
2040
+ const said = takeOut();
1607
2041
  if (failed > 0) {
1608
- showError(
2042
+ said.push(
1609
2043
  failed === 1
1610
2044
  ? 'A pasted image could not be embedded — it will export as a placeholder'
1611
2045
  : `${failed} pasted images could not be embedded — they will export as placeholders`
1612
2046
  );
1613
2047
  }
2048
+ if (failed > 0 || said.length > saidFirst.length) showError(said.join('. '));
1614
2049
  if (changed) {
1615
2050
  updateCounts();
1616
2051
  fireChange();
@@ -1618,6 +2053,176 @@
1618
2053
  }
1619
2054
  }
1620
2055
 
2056
+ /** Things that show without holding any text; an element with one of these is not empty. */
2057
+ const SHOWN_WITHOUT_TEXT = 'img, table, hr, svg, video, audio, canvas, iframe, object, embed, input, select, textarea, button, math';
2058
+
2059
+ /** Whether an element shows nothing. A figure's caption does not count: it describes the picture. */
2060
+ function showsNothing(el: Element): boolean {
2061
+ let check = el;
2062
+ if (el.tagName === 'FIGURE') {
2063
+ check = el.cloneNode(true) as Element;
2064
+ for (const caption of Array.from(check.querySelectorAll('figcaption'))) caption.remove();
2065
+ }
2066
+ return !check.querySelector(SHOWN_WITHOUT_TEXT) && (check.textContent || '').trim().length === 0;
2067
+ }
2068
+
2069
+ /**
2070
+ * The next thing shown after a node (`forward`) or before it, in or beyond what it ends or
2071
+ * starts: an element or some text. Not a line break, a comment or white space.
2072
+ */
2073
+ function shownBeside(node: Node, root: Element, forward: boolean): Node | null {
2074
+ for (let at: Node | null = node; at && at !== root; at = at.parentNode) {
2075
+ for (let near = forward ? at.nextSibling : at.previousSibling; near; near = forward ? near.nextSibling : near.previousSibling) {
2076
+ if (near.nodeType === Node.ELEMENT_NODE ? (near as Element).tagName !== 'BR' : near.nodeType === Node.TEXT_NODE && (near.textContent || '').trim()) {
2077
+ return near;
2078
+ }
2079
+ }
2080
+ }
2081
+ return null;
2082
+ }
2083
+
2084
+ /**
2085
+ * Whether this is a figure holding a caption and nothing else, or a wrapper around such a
2086
+ * figure and nothing else (a <div>, a <section>, a link).
2087
+ */
2088
+ function isCaptionAlone(el: Element): boolean {
2089
+ const figure = el.tagName === 'FIGURE' ? el : el.querySelector('figure');
2090
+ if (!figure || !figure.querySelector('figcaption') || !showsNothing(figure)) return false;
2091
+ if (figure === el) return true;
2092
+ const rest = el.cloneNode(true) as Element;
2093
+ rest.querySelector('figure')?.remove();
2094
+ return showsNothing(rest);
2095
+ }
2096
+
2097
+ /** Lines of text: an empty one that was in the document before the paste stays a line. */
2098
+ const LINES = 'p, div, li, h1, h2, h3, h4, h5, h6, blockquote, pre';
2099
+
2100
+ /**
2101
+ * Take pasted pictures out of the document, each with everything that was only there for it:
2102
+ * its figure and caption, a link around it, a paragraph or list item that held nothing else.
2103
+ * Left behind, the caption of a picture that is not there and an empty paragraph went into the
2104
+ * RTF. Text that shared a paragraph with a picture stays, and so does whatever was in the
2105
+ * document before the paste; a table cell stays, since the table needs it. `replaced` is an
2106
+ * empty line whose place the paste took: if nothing of the paste is left, it is put back.
2107
+ */
2108
+ function removePastedImages(images: HTMLImageElement[], before: Set<Element>, replaced: Element | null): void {
2109
+ if (!editorEl) return;
2110
+ const root = editorEl;
2111
+ const selection = window.getSelection();
2112
+ const caret = selection?.anchorNode && root.contains(selection.anchorNode) ? selection.anchorNode : null;
2113
+ // Holds the caret's place once what the caret was in has gone. (Written this way so the
2114
+ // type checker does not take it to be null for good: it is set inside `take`.)
2115
+ let place = null as Comment | null;
2116
+ // Holds the place of the first thing taken out, for the line the paste took the place of.
2117
+ let first = null as Comment | null;
2118
+ // What is put in here, as opposed to what the paste brought.
2119
+ const made = new Set<Element>();
2120
+ const take = (node: Element): void => {
2121
+ if (place ? node.contains(place) : !!caret && node.contains(caret)) {
2122
+ place ??= document.createComment('');
2123
+ node.after(place);
2124
+ }
2125
+ if (first && node.contains(first)) node.after(first);
2126
+ node.remove();
2127
+ };
2128
+ /** Take a node out, and after it each thing around it that came with the paste and now shows nothing. */
2129
+ const takeWithEmptied = (start: Element): void => {
2130
+ let node = start;
2131
+ let parent: Element | null;
2132
+ let next: Node | null;
2133
+ for (;;) {
2134
+ parent = node.parentElement;
2135
+ next = node.nextSibling;
2136
+ take(node);
2137
+ if (!parent || parent === root || before.has(parent) || parent.matches('td, th')) break;
2138
+ if (!showsNothing(parent)) break;
2139
+ node = parent;
2140
+ }
2141
+ if (!parent) return;
2142
+ if (!first) {
2143
+ first = document.createComment('');
2144
+ parent.insertBefore(first, next);
2145
+ }
2146
+ // A line that was in the document before the paste and is empty again stays a line.
2147
+ if (parent !== root && before.has(parent) && parent.matches(LINES) && showsNothing(parent) && !parent.querySelector('br')) {
2148
+ const lineBreak = document.createElement('br');
2149
+ made.add(lineBreak);
2150
+ parent.appendChild(lineBreak);
2151
+ }
2152
+ };
2153
+ const pastedPicture = (node: Node | null) =>
2154
+ node instanceof Element && node.isConnected && !before.has(node) && (node.tagName === 'IMG' || node.querySelector('img') !== null);
2155
+
2156
+ for (const img of images) {
2157
+ if (!img.isConnected) continue;
2158
+ // The overlay and the Backspace key act on the selected picture: not on one that is gone.
2159
+ if (selectedImage === img) selectedImage = null;
2160
+ const after = shownBeside(img, root, true);
2161
+ const prior = shownBeside(img, root, false);
2162
+ takeWithEmptied(img);
2163
+
2164
+ // Chromium, pasting a figure at the end of a line of text, moves its pictures into that
2165
+ // line and leaves the figure after them with the caption alone (inside the wrapper the
2166
+ // figure came in, if it had one). A pasted caption alone, straight after the picture, is
2167
+ // that picture's, and goes with it, unless another picture pasted with it is still
2168
+ // there before it: the caption is then that one's too.
2169
+ if (after instanceof Element && after.isConnected && !before.has(after) && isCaptionAlone(after) && !pastedPicture(prior)) {
2170
+ takeWithEmptied(after);
2171
+ }
2172
+ }
2173
+
2174
+ // The paste took the place of an empty line, and nothing of the paste that shows is
2175
+ // left: the line is put back where the paste stood, as if nothing had been pasted.
2176
+ let line: HTMLElement | null = null;
2177
+ const holder = (first as Comment | null)?.parentElement ?? null;
2178
+ if (replaced && !replaced.isConnected && holder && !holder.matches('ul, ol, table, thead, tbody, tfoot, tr')) {
2179
+ const left = Array.from(root.querySelectorAll('*')).some((el) => !before.has(el) && !made.has(el) && !showsNothing(el));
2180
+ if (!left) {
2181
+ line = replaced as HTMLElement;
2182
+ // (Chromium takes the line's own line break out before it takes the line out.)
2183
+ if (!line.querySelector('br')) line.appendChild(document.createElement('br'));
2184
+ first!.before(line);
2185
+ }
2186
+ }
2187
+ first?.remove();
2188
+
2189
+ // The caret goes back into the line that was put back: it was there when the paste was made.
2190
+ if (line && caret) {
2191
+ placeCaret(line);
2192
+ place?.remove();
2193
+ return;
2194
+ }
2195
+
2196
+ // The caret went with what was removed: put it where typing carries on from.
2197
+ if (place?.isConnected) {
2198
+ const textBlock = (el: Element | null) => (el && !el.matches(`figure, ${SHOWN_WITHOUT_TEXT}`) ? (el as HTMLElement) : null);
2199
+ const previous = textBlock(place.previousElementSibling);
2200
+ const next = textBlock(place.nextElementSibling);
2201
+ if (place.parentElement && place.parentElement !== root) {
2202
+ // Inside something that stays (a line of text, a table cell): where it was.
2203
+ const range = document.createRange();
2204
+ range.setStartBefore(place);
2205
+ range.collapse(true);
2206
+ selection?.removeAllRanges();
2207
+ selection?.addRange(range);
2208
+ savedSelection = range.cloneRange();
2209
+ } else if (previous) {
2210
+ placeCaret(previous, false);
2211
+ } else if (next) {
2212
+ placeCaret(next, true);
2213
+ } else {
2214
+ // Nothing to type in next to it (the document is empty, or a table or another
2215
+ // picture is all there is): leave one empty line.
2216
+ const empty = document.createElement('p');
2217
+ empty.appendChild(document.createElement('br'));
2218
+ place.before(empty);
2219
+ placeCaret(empty);
2220
+ }
2221
+ }
2222
+ place?.remove();
2223
+ }
2224
+
2225
+
1621
2226
  // ── Lifecycle ──
1622
2227
  onMount(() => {
1623
2228
  if (!editorEl) return;
@@ -1625,7 +2230,9 @@
1625
2230
  try {
1626
2231
  const saved = localStorage.getItem(storageKey);
1627
2232
  if (saved) {
1628
- editorEl.innerHTML = saved;
2233
+ // A draft is HTML from outside like any other: anything that can write to this
2234
+ // origin's storage can write it.
2235
+ showDocument(saved);
1629
2236
  updateCounts();
1630
2237
  return;
1631
2238
  }
@@ -1634,7 +2241,7 @@
1634
2241
  // Always write the initial content prop so the div isn't empty.
1635
2242
  // {#html content} must NOT be used inside the contenteditable div —
1636
2243
  // Svelte would re-inject it on every reactive update, duplicating text.
1637
- editorEl.innerHTML = content || '<p></p>';
2244
+ showDocument(content || EMPTY_DOCUMENT);
1638
2245
  updateCounts();
1639
2246
  });
1640
2247
 
@@ -1682,6 +2289,9 @@
1682
2289
  onblock={setBlock}
1683
2290
  oninsertlink={openLinkModal}
1684
2291
  oninsertimage={openImageModal}
2292
+ fontSize={currentFontSize}
2293
+ fontSizes={sizeChoices}
2294
+ onfontsize={setFontSize}
1685
2295
  copyingFormat={copyFormat !== 'off'}
1686
2296
  oncopyformat={toggleCopyFormat}
1687
2297
  />
@@ -1709,11 +2319,17 @@
1709
2319
  class:copy-format-pick={copyFormat === 'pick'}
1710
2320
  class:copy-format-apply={copyFormat === 'apply'}
1711
2321
  contenteditable={!readonly}
2322
+ role="textbox"
2323
+ tabindex="0"
2324
+ aria-multiline="true"
2325
+ aria-label={ariaLabel}
2326
+ aria-readonly={readonly ? 'true' : undefined}
1712
2327
  spellcheck="true"
1713
2328
  bind:this={editorEl}
1714
2329
  oninput={handleInput}
1715
- onmouseup={updateToolbarState}
1716
- onkeyup={updateToolbarState}
2330
+ onmouseup={caretMoved}
2331
+ onkeyup={caretMoved}
2332
+ onscroll={contentScrolled}
1717
2333
  onkeydown={handleKeydown}
1718
2334
  onmousedown={() => (tabLeavesEditor = false)}
1719
2335
  onblur={() => (tabLeavesEditor = false)}
@@ -1739,6 +2355,7 @@
1739
2355
  bind:this={overlayRef}
1740
2356
  target={selectedImage}
1741
2357
  bounds={contentWrapEl}
2358
+ within={editorEl}
1742
2359
  maxWidth={contentWidth}
1743
2360
  onchange={handleImageEdited}
1744
2361
  onremove={removeSelectedImage}
@@ -1759,12 +2376,20 @@
1759
2376
 
1760
2377
  <!-- Link Modal -->
1761
2378
  <Modal title="Insert Link" open={linkModalOpen} onclose={() => (linkModalOpen = false)}>
1762
- <input type="text" placeholder="Link text (leave empty to use selection)" bind:value={linkText} />
2379
+ <input
2380
+ type="text"
2381
+ placeholder="Link text (leave empty to use selection)"
2382
+ aria-label="Link text"
2383
+ bind:value={linkText}
2384
+ onkeydown={(e) => onEnter(e, applyLink)}
2385
+ />
1763
2386
  <input
1764
2387
  type="url"
1765
2388
  placeholder="https://example.com"
2389
+ aria-label="Link address"
2390
+ data-autofocus
1766
2391
  bind:value={linkUrl}
1767
- onkeydown={(e) => e.key === 'Enter' && applyLink()}
2392
+ onkeydown={(e) => onEnter(e, applyLink)}
1768
2393
  aria-invalid={linkError ? 'true' : undefined}
1769
2394
  aria-describedby={linkError ? 'ink-link-error' : undefined}
1770
2395
  />
@@ -1795,17 +2420,18 @@
1795
2420
  <input
1796
2421
  type="url"
1797
2422
  placeholder="https://example.com/image.jpg"
2423
+ aria-label="Image address"
1798
2424
  bind:value={imageUrl}
1799
- onkeydown={(e) => e.key === 'Enter' && applyImage()}
2425
+ onkeydown={(e) => onEnter(e, () => void applyImage())}
1800
2426
  />
1801
2427
  {/if}
1802
2428
 
1803
2429
  {#if pendingImageFiles.length > 1}
1804
2430
  <p class="ink-modal-hint">Add a description under each image after inserting.</p>
1805
2431
  {:else}
1806
- <input type="text" placeholder="Description shown below the image (optional)" bind:value={imageCaption} />
2432
+ <input type="text" placeholder="Description shown below the image (optional)" aria-label="Description shown below the image" bind:value={imageCaption} />
1807
2433
  {/if}
1808
- <input type="text" placeholder="Alt text for screen readers (optional)" bind:value={imageAlt} />
2434
+ <input type="text" placeholder="Alt text for screen readers (optional)" aria-label="Alt text for screen readers" bind:value={imageAlt} />
1809
2435
 
1810
2436
  {#snippet actions()}
1811
2437
  <button class="ink-btn-ghost" onclick={() => (imageModalOpen = false)}>Cancel</button>
@@ -1821,7 +2447,7 @@
1821
2447
 
1822
2448
  <!-- Import Error Toast -->
1823
2449
  {#if importError}
1824
- <div class="ink-toast-error">
2450
+ <div class="ink-toast-error" role="alert">
1825
2451
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>
1826
2452
  {importError}
1827
2453
  </div>
@@ -1844,6 +2470,9 @@
1844
2470
 
1845
2471
  /* ── Content Area ── */
1846
2472
  .ink-content {
2473
+ /* Nothing in the document is drawn outside the editing area, whatever its styles: a table
2474
+ wider than the area scrolls inside it, and does not run out over the page beside it. */
2475
+ overflow: auto;
1847
2476
  min-height: var(--ink-min-height, 40vh);
1848
2477
  padding: 48px 56px;
1849
2478
  background: white;
@@ -1851,7 +2480,7 @@
1851
2480
  border-radius: var(--radius, 8px);
1852
2481
  box-shadow: var(--shadow-md, 0 4px 12px rgba(44, 37, 32, 0.08));
1853
2482
  outline: none;
1854
- font-family: var(--ink-font-family, Arial, sans-serif);
2483
+ font-family: var(--ink-font-family, sans-serif);
1855
2484
  font-size: var(--ink-font-size, 12pt);
1856
2485
  line-height: 1.75;
1857
2486
  color: var(--text, #2c2520);