svelte-rtf-editor 1.9.0 → 1.10.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,13 @@
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.
32
40
  *
33
41
  * Events (callback props):
34
42
  * onchange — Fires on content change with
@@ -54,6 +62,7 @@
54
62
  import Modal from './Modal.svelte';
55
63
  import ImageOverlay from './ImageOverlay.svelte';
56
64
  import { htmlToMarkdown, downloadFile } from '../utils.js';
65
+ import { pasteNotes, removeWordHidden, sanitizedNodes, sanitizeTree, type PasteNotes } from '../sanitize.js';
57
66
  import { readRtfFile, DEFAULT_MAX_RTF_BYTES } from '../rtf-parser.js';
58
67
  import {
59
68
  htmlToRtf,
@@ -76,15 +85,21 @@
76
85
  } from '../images.js';
77
86
 
78
87
  interface ChangePayload {
79
- html: string;
80
- text: string;
88
+ /**
89
+ * `html`, `text` and `estimatedRtfBytes` are worked out when the handler reads them, and
90
+ * once: on a long document each is work, and most handlers read one of them or none.
91
+ * They are the document as it is when first read, so read them in the handler. A payload
92
+ * kept and read after a later edit gives the document as it is by then.
93
+ */
94
+ readonly html: string;
95
+ readonly text: string;
81
96
  wordCount: number;
82
97
  charCount: number;
83
98
  /**
84
99
  * Approximate size of this document as RTF. Pictures dominate it and are
85
100
  * counted exactly; see getRtfSize() for the precise figure.
86
101
  */
87
- estimatedRtfBytes: number;
102
+ readonly estimatedRtfBytes: number;
88
103
  }
89
104
 
90
105
  interface Props {
@@ -96,6 +111,7 @@
96
111
  showStatusBar?: boolean;
97
112
  minHeight?: string;
98
113
  readonly?: boolean;
114
+ ariaLabel?: string;
99
115
  maxImageEdge?: number;
100
116
  maxImageBytes?: number;
101
117
  maxImageDisplayWidth?: number;
@@ -103,27 +119,40 @@
103
119
  maxRtfBytes?: number;
104
120
  fontFamily?: string;
105
121
  fontSize?: number;
122
+ fontSizes?: number[];
106
123
  onchange?: (payload: ChangePayload) => void;
107
124
  onsave?: (payload: { html: string }) => void;
108
125
  onimport?: (payload: { html: string }) => void;
109
126
  }
110
127
 
128
+ /**
129
+ * An empty document: one paragraph with the line break that gives it height. Without the
130
+ * break the paragraph has no line to put the caret in, the first words typed land outside it,
131
+ * and the RTF then carries the empty paragraph as a blank line the screen never showed.
132
+ */
133
+ const EMPTY_DOCUMENT = '<p><br></p>';
134
+
135
+ /** The sizes, in points, the toolbar's size list offers unless `fontSizes` says otherwise. */
136
+ const DEFAULT_FONT_SIZES = [8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 36];
137
+
111
138
  // ── Props ──
112
139
  let {
113
- content = '<p></p>',
140
+ content = EMPTY_DOCUMENT,
114
141
  placeholder = 'Start writing something beautiful...',
115
- autosave = true,
142
+ autosave = false,
116
143
  storageKey = 'ink-editor-content',
117
144
  showToolbar = true,
118
145
  showStatusBar = true,
119
146
  minHeight = '40vh',
120
147
  readonly = false,
148
+ ariaLabel = 'Document',
121
149
  maxImageEdge = DEFAULT_MAX_IMAGE_EDGE,
122
150
  maxImageBytes = DEFAULT_MAX_IMAGE_BYTES,
123
151
  maxImageDisplayWidth = DEFAULT_MAX_IMAGE_DISPLAY_WIDTH,
124
152
  maxRtfBytes = DEFAULT_MAX_RTF_BYTES,
125
153
  fontFamily = DEFAULT_FONT_FAMILY,
126
154
  fontSize = DEFAULT_FONT_SIZE,
155
+ fontSizes = DEFAULT_FONT_SIZES,
127
156
  onchange,
128
157
  onsave,
129
158
  onimport
@@ -142,6 +171,8 @@
142
171
  let charCount: number = $state(0);
143
172
  let lastSaved: string = $state('');
144
173
  let currentBlock: string = $state('p');
174
+ /** The size of the text at the caret, in points, for the toolbar. */
175
+ let currentFontSize: number | null = $state(null);
145
176
 
146
177
  let formatState = $state({
147
178
  bold: false,
@@ -186,12 +217,31 @@
186
217
  if (editorEl) {
187
218
  selectedImage = null;
188
219
  documentReplaced();
189
- editorEl.innerHTML = html;
220
+ showDocument(html);
190
221
  updateCounts();
191
222
  if (autosave) scheduleAutoSave();
192
223
  }
193
224
  }
194
225
 
226
+ /**
227
+ * Put HTML from outside in the editor: made safe first, and with a line in every empty
228
+ * paragraph, so it shows as the blank line the RTF writes for it. The nodes that were checked
229
+ * are the nodes shown (see sanitizedNodes): the HTML is read once.
230
+ */
231
+ function showDocument(html: string): void {
232
+ if (!editorEl) return;
233
+ // An id the page already uses outside an editor is not the document's to take: see
234
+ // sanitize.ts. (Another editor on the page may hold a document with the same ids.)
235
+ const idTaken = (id: string) => {
236
+ const owner = document.getElementById(id);
237
+ return owner !== null && owner.closest('.ink-content') === null;
238
+ };
239
+ editorEl.replaceChildren(...sanitizedNodes(html, document, idTaken));
240
+ for (const p of Array.from(editorEl.querySelectorAll('p'))) {
241
+ if (p.childNodes.length === 0) p.appendChild(document.createElement('br'));
242
+ }
243
+ }
244
+
195
245
  export function getMarkdown(): string {
196
246
  if (!editorEl) return '';
197
247
  return htmlToMarkdown(editorEl);
@@ -218,7 +268,8 @@
218
268
  if (editorEl) {
219
269
  selectedImage = null;
220
270
  documentReplaced();
221
- editorEl.innerHTML = '<p></p>';
271
+ editorEl.innerHTML = EMPTY_DOCUMENT;
272
+ clearTimeout(saveTimer);
222
273
  try { localStorage.removeItem(storageKey); } catch (e) {}
223
274
  updateCounts();
224
275
  lastSaved = '';
@@ -264,6 +315,7 @@
264
315
  function documentReplaced(): void {
265
316
  indentUndo = [];
266
317
  pastedOver = null;
318
+ pastedLoss = null;
267
319
  stopCopyFormat();
268
320
  }
269
321
 
@@ -297,6 +349,179 @@
297
349
  }
298
350
  }
299
351
 
352
+ // ── Font size ──
353
+ // The size of the selected text, or of what is typed next, is set with the browser's own
354
+ // command: it wraps exactly the selection, takes a size already there out of it, and its
355
+ // steps can be undone with everything else. But it knows only seven sizes and writes them as
356
+ // <font size="1"> to <font size="7">. So it is asked for size 7, which nothing else in the
357
+ // editor makes, and each element it marked that way is then given the size meant, in points
358
+ // (<font style="font-size:14pt">), which is what the RTF writer reads. Only attributes are
359
+ // changed, never the elements, so the browser's undo still finds what it made.
360
+ //
361
+ // Undo puts back what the browser itself recorded, which is right: the element goes, or gets
362
+ // back the size it had. Redo is not: the browser does its own step again, the mark for size 7
363
+ // and nothing after it, and the text came back at 36 pt. So each change of size is remembered
364
+ // here with the size every element was given, and after a redo the elements that are marked
365
+ // again are given theirs again.
366
+ //
367
+ // And undo is only right where the browser recorded something to put back. It records the
368
+ // size it takes off an element, not the one given here afterwards. So a <font> element is
369
+ // never left without a size of its own: where the text is to have the size of the text around
370
+ // it, the size stated is 1em, which is that size. The writer reads 1em as no size.
371
+ const SIZE_MARK = '7';
372
+ /** The size that is the size of the text around: what "no size of its own" is written as. */
373
+ const SIZE_AROUND = '1em';
374
+ /** One change of size: the elements it sized, each with the font-size it was given. */
375
+ type SizeStep = Map<HTMLElement, string>;
376
+ /** The changes of size made, in order; those from `sizeStepsApplied` on were undone and can be redone. */
377
+ let sizeSteps: SizeStep[] = [];
378
+ let sizeStepsApplied = 0;
379
+ /** Every element this editor has given a size: a mark on one of these is the browser redoing a step. */
380
+ const sizedHere = new WeakSet<Element>();
381
+ /** The size chosen and not yet given to an element: a caret has no text to carry it until something is typed. */
382
+ let pendingSize: number | null = null;
383
+ /** Elements that were marked size 7 before the command (pasted that way): not ours to change. */
384
+ let markedBefore = new Set<Element>();
385
+
386
+ /** The size of an element's text as the screen shows it, in points to the half-point; null if unknown. */
387
+ function shownSize(el: Element): number | null {
388
+ const px = parseFloat(getComputedStyle(el).fontSize);
389
+ return Number.isFinite(px) && px > 0 ? Math.round(px * 0.75 * 2) / 2 : null;
390
+ }
391
+
392
+ /** Take the mark off an element and state the size it is to have. */
393
+ function sizeElement(font: HTMLElement, fontSize: string): void {
394
+ font.removeAttribute('size');
395
+ font.style.fontSize = fontSize;
396
+ }
397
+
398
+ const markedElements = (): HTMLElement[] =>
399
+ editorEl ? Array.from(editorEl.querySelectorAll<HTMLElement>(`font[size="${SIZE_MARK}"]`)) : [];
400
+
401
+ /** Give the elements the command marked the size that was chosen, and remember the step. */
402
+ function applyPendingSize(): void {
403
+ if (!editorEl || pendingSize === null) return;
404
+ const step: SizeStep = new Map();
405
+ for (const font of markedElements()) {
406
+ if (markedBefore.has(font)) continue;
407
+ sizeElement(font, SIZE_AROUND);
408
+ // Where the text around it has that size already (body text set back to the body
409
+ // size, a heading to the heading's), it stays at the size around it: the text then
410
+ // follows the document's size, as text that was never sized does.
411
+ if (shownSize(font) !== pendingSize) sizeElement(font, `${pendingSize}pt`);
412
+ step.set(font, font.style.fontSize);
413
+ sizedHere.add(font);
414
+ }
415
+ if (step.size === 0) return;
416
+ // A new change: what was undone before it can no longer be redone.
417
+ sizeSteps = [...sizeSteps.slice(0, sizeStepsApplied), step];
418
+ sizeStepsApplied = sizeSteps.length;
419
+ }
420
+
421
+ /** Whether a change of size is in the document as it was made: every element there, with its size. */
422
+ function stepStands(step: SizeStep | undefined): boolean {
423
+ if (!step) return false;
424
+ for (const [font, fontSize] of step) {
425
+ if (!font.isConnected || font.getAttribute('size') === SIZE_MARK || font.style.fontSize !== fontSize) return false;
426
+ }
427
+ return true;
428
+ }
429
+
430
+ /** After an undo or a redo: follow which changes of size are in the document, and finish a redone one. */
431
+ function afterHistory(): void {
432
+ const next = sizeSteps[sizeStepsApplied];
433
+ const marked = markedElements().filter((font) => sizedHere.has(font));
434
+ if (marked.length > 0) {
435
+ // The browser redid its part of a change of size. (A mark with no step to go with it
436
+ // should not happen; it is then taken off, and the text has the size around it,
437
+ // which is better than 36 pt.)
438
+ for (const font of marked) sizeElement(font, next?.get(font) ?? SIZE_AROUND);
439
+ if (next) sizeStepsApplied++;
440
+ } else if (stepStands(next)) {
441
+ // Redone, and nothing was marked: the step only made elements, which came back as they were.
442
+ sizeStepsApplied++;
443
+ } else if (sizeStepsApplied > 0 && !stepStands(sizeSteps[sizeStepsApplied - 1])) {
444
+ sizeStepsApplied--;
445
+ }
446
+ }
447
+
448
+ /** Whether all the text selected has this size already. */
449
+ function selectionHasSize(points: number): boolean {
450
+ const selection = window.getSelection();
451
+ if (!editorEl || !selection || selection.rangeCount === 0 || selection.isCollapsed) return false;
452
+ const range = selection.getRangeAt(0);
453
+ const walker = document.createTreeWalker(range.commonAncestorContainer, NodeFilter.SHOW_TEXT);
454
+ let texts = 0;
455
+ for (let node = walker.currentNode.nodeType === Node.TEXT_NODE ? walker.currentNode : walker.nextNode(); node; node = walker.nextNode()) {
456
+ if (!range.intersectsNode(node) || !(node.textContent || '').trim() || !node.parentElement) continue;
457
+ if (shownSize(node.parentElement) !== points) return false;
458
+ texts++;
459
+ }
460
+ return texts > 0;
461
+ }
462
+
463
+ /**
464
+ * Set the size, in points, of the selected text; with nothing selected, of what is typed next.
465
+ * Also what the toolbar's size list calls.
466
+ */
467
+ export function setFontSize(points: number): void {
468
+ if (readonly || !editorEl) return;
469
+ if (typeof points !== 'number' || !Number.isFinite(points) || points <= 0) return;
470
+ restoreSelection();
471
+ editorEl.focus();
472
+ // The document changes outside an input event: earlier indent steps no longer undo.
473
+ indentUndo = [];
474
+ const size = normalizeFontSize(points);
475
+ // Nothing to change: no step is made that would undo to the same thing.
476
+ if (selectionHasSize(size)) {
477
+ updateToolbarState();
478
+ return;
479
+ }
480
+ markedBefore = new Set(markedElements());
481
+ // The command may use a <font> element that is there already (one pasted with a color),
482
+ // and undo then puts back only a size the command itself took off it: see SIZE_AROUND.
483
+ for (const font of Array.from(editorEl.querySelectorAll<HTMLElement>('font'))) {
484
+ if (!font.style.fontSize && !markedBefore.has(font)) font.style.fontSize = SIZE_AROUND;
485
+ }
486
+ pendingSize = size;
487
+ document.execCommand('fontSize', false, SIZE_MARK);
488
+ applyPendingSize();
489
+ // With text selected the size is on it now. At a caret it waits for the typing.
490
+ const selection = window.getSelection();
491
+ if (selection && !selection.isCollapsed) pendingSize = null;
492
+ updateToolbarState();
493
+ fireChange();
494
+ if (autosave) scheduleAutoSave();
495
+ }
496
+
497
+ /** The size of the text at the selection, for the toolbar: null where it starts and ends in different sizes. */
498
+ function sizeAtSelection(): number | null {
499
+ if (pendingSize !== null) return pendingSize;
500
+ const selection = window.getSelection();
501
+ if (!editorEl || !selection || selection.rangeCount === 0) return null;
502
+ const range = selection.getRangeAt(0);
503
+ if (!editorEl.contains(range.startContainer)) return null;
504
+ const holder = (node: Node, offset: number, atEnd: boolean): Element | null => {
505
+ if (node.nodeType === Node.ELEMENT_NODE) {
506
+ const child = node.childNodes[atEnd ? offset - 1 : offset];
507
+ return child?.nodeType === Node.ELEMENT_NODE ? (child as Element) : (node as Element);
508
+ }
509
+ return node.parentElement;
510
+ };
511
+ const start = holder(range.startContainer, range.startOffset, false);
512
+ const first = start ? shownSize(start) : null;
513
+ if (range.collapsed) return first;
514
+ const end = holder(range.endContainer, range.endOffset, true);
515
+ return end && shownSize(end) === first ? first : null;
516
+ }
517
+
518
+ /** The sizes the list offers: those asked for, and always the body size. */
519
+ const sizeChoices = $derived.by(() => {
520
+ const sizes = fontSizes.map((size) => normalizeFontSize(size));
521
+ if (sizes.length === 0) return sizes;
522
+ return Array.from(new Set([...sizes, screenFontSize])).sort((a, b) => a - b);
523
+ });
524
+
300
525
  // ── Exec command ──
301
526
  function exec(cmd: string, value: string | null = null): void {
302
527
  restoreSelection();
@@ -318,6 +543,7 @@
318
543
  }
319
544
  if (cmd === 'undo' && undoIndent()) return;
320
545
  document.execCommand(cmd, false, value ?? undefined);
546
+ if (cmd === 'undo' || cmd === 'redo') afterHistory();
321
547
  updateToolbarState();
322
548
  }
323
549
 
@@ -896,6 +1122,7 @@
896
1122
  // Snapshot the selection so exec/setBlock can restore it even if focus
897
1123
  // temporarily moved to a toolbar element (e.g. colour picker, select).
898
1124
  saveSelection();
1125
+ currentFontSize = sizeAtSelection();
899
1126
 
900
1127
  formatState = {
901
1128
  bold: document.queryCommandState('bold'),
@@ -912,21 +1139,52 @@
912
1139
  updateCounts();
913
1140
  }
914
1141
 
1142
+ /**
1143
+ * A click or a key in the text. A size chosen at a caret and not yet typed in is given up: the
1144
+ * browser drops it when the caret moves, and the toolbar must not go on showing it.
1145
+ */
1146
+ function caretMoved(): void {
1147
+ pendingSize = null;
1148
+ updateToolbarState();
1149
+ }
1150
+
1151
+ /** The editing area was scrolled sideways (a wide table): what is drawn over it moves with it. */
1152
+ function contentScrolled(): void {
1153
+ overlayRef?.reposition();
1154
+ placeCopySourceBox();
1155
+ }
1156
+
915
1157
  function updateCounts(): void {
916
1158
  if (!editorEl) return;
917
- const text = editorEl.innerText || '';
1159
+ const shown = editorEl.innerText || '';
1160
+ // A document with nothing in it is a paragraph with a line break, which innerText gives
1161
+ // as one character: an empty report then counted one, and so did one of blank lines only.
1162
+ const text = shown.trim() === '' && !editorEl.querySelector('img, table, hr') ? '' : shown;
918
1163
  const words = text.trim().split(/\s+/).filter((w) => w.length > 0);
919
1164
  wordCount = words.length;
920
1165
  charCount = text.length;
921
1166
  }
922
1167
 
923
1168
  function fireChange(): void {
924
- onchange?.({
925
- html: editorEl?.innerHTML || '',
926
- text: editorEl?.innerText || '',
1169
+ if (!onchange) return;
1170
+ // The HTML, the text and the size estimate each read the whole document, and this runs on
1171
+ // every keystroke: with a few pictures in the document it took a tenth of a second. Each is
1172
+ // worked out when the handler asks for it, once, and not at all if it never does.
1173
+ const el = editorEl;
1174
+ const options = { fontFamily, fontSize };
1175
+ const once = <T,>(read: () => T): (() => T) => {
1176
+ let value: { v: T } | null = null;
1177
+ return () => (value ??= { v: read() }).v;
1178
+ };
1179
+ const html = once(() => el?.innerHTML || '');
1180
+ const text = once(() => el?.innerText || '');
1181
+ const estimate = once(() => (el ? estimateRtfBytes(el, options) : 0));
1182
+ onchange({
1183
+ get html() { return html(); },
1184
+ get text() { return text(); },
927
1185
  wordCount,
928
1186
  charCount,
929
- estimatedRtfBytes: editorEl ? estimateRtfBytes(editorEl) : 0
1187
+ get estimatedRtfBytes() { return estimate(); }
930
1188
  });
931
1189
  }
932
1190
 
@@ -953,13 +1211,23 @@
953
1211
  }
954
1212
 
955
1213
  // ── Input handler ──
956
- function handleInput(): void {
1214
+ function handleInput(e?: Event): void {
957
1215
  placeCopySourceBox();
958
1216
  if (pastedOver) {
959
1217
  tidyPasted(pastedOver);
960
1218
  pastedOver = null;
961
1219
  }
962
1220
  indentUndo = [];
1221
+ const kind = (e as InputEvent | undefined)?.inputType ?? '';
1222
+ if (kind === 'historyUndo' || kind === 'historyRedo') {
1223
+ afterHistory();
1224
+ } else {
1225
+ // An edit: what was undone can no longer be redone.
1226
+ sizeSteps = sizeSteps.slice(0, sizeStepsApplied);
1227
+ // What was typed at a caret after a size was chosen came in marked: give it the size.
1228
+ applyPendingSize();
1229
+ }
1230
+ pendingSize = null;
963
1231
  updateToolbarState();
964
1232
  // Typing means the user is editing text, not the picture. Dropping the
965
1233
  // selection here keeps Backspace editing that text instead of deleting a
@@ -999,7 +1267,7 @@
999
1267
  const range = sel.getRangeAt(0);
1000
1268
  range.deleteContents();
1001
1269
  const a = document.createElement('a');
1002
- a.href = linkUrl;
1270
+ a.href = linkUrl.trim();
1003
1271
  a.textContent = linkText;
1004
1272
  range.insertNode(a);
1005
1273
  range.setStartAfter(a);
@@ -1007,9 +1275,24 @@
1007
1275
  sel.addRange(range);
1008
1276
  }
1009
1277
  } else {
1010
- document.execCommand('createLink', false, linkUrl);
1278
+ document.execCommand('createLink', false, linkUrl.trim());
1011
1279
  }
1012
1280
  linkModalOpen = false;
1281
+ updateCounts();
1282
+ fireChange();
1283
+ if (autosave) scheduleAutoSave();
1284
+ }
1285
+
1286
+ /**
1287
+ * Enter in a dialog's field does what the dialog's button does. The key press ends here: the
1288
+ * dialog hands the keyboard back to the document, where the same Enter would go on to replace
1289
+ * the selected text with a new line.
1290
+ */
1291
+ function onEnter(e: KeyboardEvent, act: () => void): void {
1292
+ if (e.key !== 'Enter' || e.isComposing) return;
1293
+ e.preventDefault();
1294
+ e.stopPropagation();
1295
+ act();
1013
1296
  }
1014
1297
 
1015
1298
  // ── Images ──
@@ -1053,7 +1336,18 @@
1053
1336
 
1054
1337
  insertingImages = true;
1055
1338
  try {
1056
- const { src, embedded } = await urlToImageSrc(url, imageLimits());
1339
+ const { src, embedded, tooLarge, unreadable } = await urlToImageSrc(url, imageLimits());
1340
+ // Picture data over the size limit that could not be reduced is not inserted:
1341
+ // once in the document it would be written to the RTF at its full size.
1342
+ if (tooLarge) {
1343
+ showError(TOO_LARGE_MESSAGE);
1344
+ return;
1345
+ }
1346
+ // Nor is picture data the browser cannot open: it would show as a broken picture.
1347
+ if (unreadable) {
1348
+ showError(UNREADABLE_MESSAGE);
1349
+ return;
1350
+ }
1057
1351
  restoreSelection();
1058
1352
  editorEl?.focus();
1059
1353
  finishInsert(insertFigure(src, alt || caption, caption));
@@ -1066,6 +1360,13 @@
1066
1360
  }
1067
1361
  }
1068
1362
 
1363
+ /** Said when picture data given by address or pasted is over the size limit and cannot be reduced. */
1364
+ const TOO_LARGE_MESSAGE = 'That picture is over the size limit and could not be made smaller, so it was not inserted';
1365
+
1366
+ /** Said when picture data given by address is in a format the browser cannot show, or is damaged. */
1367
+ const UNREADABLE_MESSAGE =
1368
+ 'That picture could not be opened (the browser cannot show its format, or it is damaged), so it was not inserted';
1369
+
1069
1370
  /** Caps applied to a picture as it is inserted. */
1070
1371
  function imageLimits(): { maxEdge: number; maxBytes: number } {
1071
1372
  return { maxEdge: maxImageEdge, maxBytes: maxImageBytes };
@@ -1216,9 +1517,14 @@
1216
1517
  finishInsert(inserted);
1217
1518
  }
1218
1519
 
1520
+ let errorTimer: ReturnType<typeof setTimeout> | undefined;
1521
+
1219
1522
  function showError(message: string): void {
1220
1523
  importError = message;
1221
- setTimeout(() => (importError = ''), 4000);
1524
+ // Up for long enough to be read: four seconds, and longer for a message that says more
1525
+ // than one thing. An earlier message's timer must not take a later message down early.
1526
+ clearTimeout(errorTimer);
1527
+ errorTimer = setTimeout(() => (importError = ''), Math.max(4000, message.length * 50));
1222
1528
  }
1223
1529
 
1224
1530
  // ── Image selection / editing ──
@@ -1325,7 +1631,9 @@
1325
1631
  if (editorEl) {
1326
1632
  selectedImage = null;
1327
1633
  documentReplaced();
1328
- editorEl.innerHTML = html;
1634
+ // (What the reader writes is safe as it stands; it goes the same way as any other
1635
+ // HTML so there is one way in.)
1636
+ showDocument(html);
1329
1637
  updateCounts();
1330
1638
  fireChange();
1331
1639
  if (autosave) scheduleAutoSave();
@@ -1533,15 +1841,59 @@
1533
1841
  if (!readonly && editorEl) {
1534
1842
  const snapshot = new Set(editorEl.querySelectorAll('*'));
1535
1843
  pastedOver = snapshot;
1844
+ // What the browser's paste may lose (see pasteNotes), and where the paste begins.
1845
+ const notes = pasteNotes(e.clipboardData?.getData('text/html') ?? '');
1846
+ const start = sel && sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
1847
+ pastedLoss =
1848
+ notes && start && editorEl.contains(start.startContainer)
1849
+ ? { notes, from: shownCharsBefore(start.startContainer, start.startOffset) }
1850
+ : null;
1536
1851
  // A paste that inserts nothing (an empty clipboard, a host that cancels it) raises no
1537
1852
  // input event. Left set, the snapshot would make the next keystroke treat the whole
1538
1853
  // document as pasted.
1539
1854
  setTimeout(() => {
1540
- if (pastedOver === snapshot) pastedOver = null;
1855
+ if (pastedOver === snapshot) {
1856
+ pastedOver = null;
1857
+ pastedLoss = null;
1858
+ }
1541
1859
  }, 0);
1542
1860
  }
1543
1861
  }
1544
1862
 
1863
+ /** How many characters that are not white space the document has before a place in it. */
1864
+ function shownCharsBefore(node: Node, offset: number): number {
1865
+ if (!editorEl) return 0;
1866
+ const range = document.createRange();
1867
+ range.selectNodeContents(editorEl);
1868
+ range.setEnd(node, offset);
1869
+ return range.toString().replace(/\s/g, '').length;
1870
+ }
1871
+
1872
+ /**
1873
+ * Set right what the browser's paste changed before it could be looked at: Word's hidden
1874
+ * text shown as text, and a text box left empty.
1875
+ */
1876
+ function restorePasteLoss(before: Set<Element>, loss: { notes: PasteNotes; from: number }): void {
1877
+ if (!editorEl) return;
1878
+ const areas = Array.from(editorEl.querySelectorAll('textarea')).filter((area) => !before.has(area));
1879
+ if (areas.length === loss.notes.textareas.length) {
1880
+ areas.forEach((area, i) => {
1881
+ if (area.value === '') area.textContent = loss.notes.textareas[i];
1882
+ });
1883
+ }
1884
+ // After a paste the caret is at its end.
1885
+ const sel = window.getSelection();
1886
+ if (!sel || sel.rangeCount === 0 || !sel.isCollapsed || !editorEl.contains(sel.anchorNode)) return;
1887
+ const caret = sel.getRangeAt(0);
1888
+ const to = shownCharsBefore(caret.startContainer, caret.startOffset);
1889
+ // A pasted element left with nothing in it goes, but not the one the caret is in: that
1890
+ // one becomes an empty line, to type in. (Taken out as well, a paste of hidden text
1891
+ // alone left the caret in no line at all, and the next words typed were in none.)
1892
+ const held = sel.anchorNode instanceof Element ? sel.anchorNode : (sel.anchorNode?.parentElement ?? null);
1893
+ if (!removeWordHidden(editorEl, loss.from, to, loss.notes, (el) => !before.has(el) && !(held !== null && el.contains(held)))) return;
1894
+ if (held && held !== editorEl && held.isConnected && held.childNodes.length === 0) held.appendChild(document.createElement('br'));
1895
+ }
1896
+
1545
1897
  // ── Pasted formatting ──
1546
1898
  // A browser copies a paragraph with its looks written out: Chromium turns the editor's own
1547
1899
  // spacing into "margin: 0px 0px 0.2em 96px" on the copy, and repeats the id. Pasted back, the
@@ -1552,9 +1904,17 @@
1552
1904
  const PASTED_SPACING = ['margin-top', 'margin-right', 'margin-bottom', 'margin-left', 'text-indent'];
1553
1905
  /** The elements in the editor just before a paste; what is not in it came from the paste. */
1554
1906
  let pastedOver: Set<Element> | null = null;
1907
+ /** What the paste under way may lose, and how much text the document had before it. */
1908
+ let pastedLoss: { notes: PasteNotes; from: number } | null = null;
1555
1909
 
1556
1910
  function tidyPasted(before: Set<Element>): void {
1557
1911
  if (!editorEl) return;
1912
+ if (pastedLoss) restorePasteLoss(before, pastedLoss);
1913
+ pastedLoss = null;
1914
+ // What the paste brought is made safe as HTML from anywhere else is: a browser takes the
1915
+ // scripts out of a paste itself, but leaves a form, an <iframe>, or a block with
1916
+ // position: fixed that covers the page.
1917
+ sanitizeTree(editorEl, (el) => !before.has(el));
1558
1918
  for (const el of Array.from(editorEl.querySelectorAll<HTMLElement>('*'))) {
1559
1919
  if (before.has(el)) continue;
1560
1920
  el.removeAttribute('id');
@@ -1574,43 +1934,100 @@
1574
1934
  // JPEG data held in the document reaches the RTF, so each one goes through the same step as
1575
1935
  // the image dialog: fetched, converted and scaled as needed.
1576
1936
  const pasted = Array.from(editorEl.querySelectorAll('img')).filter((img) => !before.has(img));
1577
- if (pasted.length > 0) void embedPastedImages(pasted);
1937
+ if (pasted.length === 0) return;
1938
+ // A browser pasting a block into an empty line puts the block in the line's place. If the
1939
+ // pictures of the paste are then taken out, that line is put back (removePastedImages).
1940
+ const replaced = Array.from(before).find(
1941
+ (el) => !el.isConnected && el.parentNode === null && el.matches('p, div') && showsNothing(el)
1942
+ );
1943
+ void embedPastedImages(pasted, before, replaced ?? null);
1578
1944
  }
1579
1945
 
1580
1946
  /**
1581
1947
  * Fetch each pasted picture and hold its data in the document. One that cannot be fetched
1582
1948
  * (the site forbids it, or there is no network) still shows, but leaves in the RTF as an
1583
1949
  * "[Image: …]" placeholder: the editor says so now, rather than letting it be found downstream.
1950
+ * `before` is what was in the document before the paste, and `replaced` an empty line of it
1951
+ * whose place the paste took.
1584
1952
  */
1585
- async function embedPastedImages(images: HTMLImageElement[]): Promise<void> {
1953
+ async function embedPastedImages(images: HTMLImageElement[], before: Set<Element>, replaced: Element | null): Promise<void> {
1586
1954
  let failed = 0;
1587
1955
  let changed = false;
1956
+ // Pictures that must not stay: pasted picture data over the size limit that could not be
1957
+ // reduced, which left in the document would be written to the RTF at its full size, and
1958
+ // picture data the browser cannot open, which would show as a broken picture.
1959
+ const leftOut = new Map<HTMLImageElement, 'tooLarge' | 'unreadable'>();
1960
+ const embed = async (img: HTMLImageElement): Promise<void> => {
1961
+ const url = img.getAttribute('src') || '';
1962
+ if (!isSafeImageUrl(url)) {
1963
+ failed++;
1964
+ return;
1965
+ }
1966
+ const { src, embedded, tooLarge, unreadable } = await urlToImageSrc(url, imageLimits());
1967
+ // It may have been deleted or replaced while it was fetched.
1968
+ if (!img.isConnected || img.getAttribute('src') !== url) return;
1969
+ if (tooLarge || unreadable) {
1970
+ leftOut.set(img, tooLarge ? 'tooLarge' : 'unreadable');
1971
+ } else if (!embedded) {
1972
+ failed++;
1973
+ } else if (src !== url) {
1974
+ img.setAttribute('src', src);
1975
+ changed = true;
1976
+ }
1977
+ };
1978
+ /** What to say of the pictures left out so far; they are taken out as this is asked. */
1979
+ const takeOut = (): string[] => {
1980
+ const gone = images.filter((img) => leftOut.has(img) && img.isConnected);
1981
+ if (gone.length > 0) {
1982
+ removePastedImages(gone, before, replaced);
1983
+ updateCounts();
1984
+ fireChange();
1985
+ if (autosave) scheduleAutoSave();
1986
+ }
1987
+ const count = (kind: 'tooLarge' | 'unreadable') => Array.from(leftOut.values()).filter((k) => k === kind).length;
1988
+ const tooLarge = count('tooLarge');
1989
+ const unreadable = count('unreadable');
1990
+ const said: string[] = [];
1991
+ if (tooLarge > 0) {
1992
+ said.push(
1993
+ tooLarge === 1
1994
+ ? 'A pasted picture was over the size limit and could not be made smaller, so it was left out'
1995
+ : `${tooLarge} pasted pictures were over the size limit and could not be made smaller, so they were left out`
1996
+ );
1997
+ }
1998
+ if (unreadable > 0) {
1999
+ said.push(
2000
+ unreadable === 1
2001
+ ? 'A pasted picture could not be opened (the browser cannot show its format, or it is damaged), so it was left out'
2002
+ : `${unreadable} pasted pictures could not be opened (the browser cannot show their format, or they are damaged), so they were left out`
2003
+ );
2004
+ }
2005
+ return said;
2006
+ };
2007
+
1588
2008
  // 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
- );
2009
+ const isData = (img: HTMLImageElement) => /^\s*data:/i.test(img.getAttribute('src') || '');
2010
+ const fetched = images.filter((img) => !isData(img)).map(embed);
2011
+ // Picture data needs no network. Once all of it is settled, what has to go is taken out
2012
+ // in one pass in the order of the document, without waiting for a slow site: in the
2013
+ // order each happened to finish, what is left of a figure would depend on chance.
2014
+ await Promise.all(images.filter(isData).map(embed));
2015
+ const saidFirst = takeOut();
2016
+ if (saidFirst.length > 0) showError(saidFirst.join('. '));
2017
+
2018
+ await Promise.all(fetched);
2019
+ // One paste can do all of it, and each is something the user has to know: a picture that
2020
+ // is gone, and a picture that is there but will leave as a placeholder. So what was said
2021
+ // of the first is said again with the second, not replaced by it.
2022
+ const said = takeOut();
1607
2023
  if (failed > 0) {
1608
- showError(
2024
+ said.push(
1609
2025
  failed === 1
1610
2026
  ? 'A pasted image could not be embedded — it will export as a placeholder'
1611
2027
  : `${failed} pasted images could not be embedded — they will export as placeholders`
1612
2028
  );
1613
2029
  }
2030
+ if (failed > 0 || said.length > saidFirst.length) showError(said.join('. '));
1614
2031
  if (changed) {
1615
2032
  updateCounts();
1616
2033
  fireChange();
@@ -1618,6 +2035,176 @@
1618
2035
  }
1619
2036
  }
1620
2037
 
2038
+ /** Things that show without holding any text; an element with one of these is not empty. */
2039
+ const SHOWN_WITHOUT_TEXT = 'img, table, hr, svg, video, audio, canvas, iframe, object, embed, input, select, textarea, button, math';
2040
+
2041
+ /** Whether an element shows nothing. A figure's caption does not count: it describes the picture. */
2042
+ function showsNothing(el: Element): boolean {
2043
+ let check = el;
2044
+ if (el.tagName === 'FIGURE') {
2045
+ check = el.cloneNode(true) as Element;
2046
+ for (const caption of Array.from(check.querySelectorAll('figcaption'))) caption.remove();
2047
+ }
2048
+ return !check.querySelector(SHOWN_WITHOUT_TEXT) && (check.textContent || '').trim().length === 0;
2049
+ }
2050
+
2051
+ /**
2052
+ * The next thing shown after a node (`forward`) or before it, in or beyond what it ends or
2053
+ * starts: an element or some text. Not a line break, a comment or white space.
2054
+ */
2055
+ function shownBeside(node: Node, root: Element, forward: boolean): Node | null {
2056
+ for (let at: Node | null = node; at && at !== root; at = at.parentNode) {
2057
+ for (let near = forward ? at.nextSibling : at.previousSibling; near; near = forward ? near.nextSibling : near.previousSibling) {
2058
+ if (near.nodeType === Node.ELEMENT_NODE ? (near as Element).tagName !== 'BR' : near.nodeType === Node.TEXT_NODE && (near.textContent || '').trim()) {
2059
+ return near;
2060
+ }
2061
+ }
2062
+ }
2063
+ return null;
2064
+ }
2065
+
2066
+ /**
2067
+ * Whether this is a figure holding a caption and nothing else, or a wrapper around such a
2068
+ * figure and nothing else (a <div>, a <section>, a link).
2069
+ */
2070
+ function isCaptionAlone(el: Element): boolean {
2071
+ const figure = el.tagName === 'FIGURE' ? el : el.querySelector('figure');
2072
+ if (!figure || !figure.querySelector('figcaption') || !showsNothing(figure)) return false;
2073
+ if (figure === el) return true;
2074
+ const rest = el.cloneNode(true) as Element;
2075
+ rest.querySelector('figure')?.remove();
2076
+ return showsNothing(rest);
2077
+ }
2078
+
2079
+ /** Lines of text: an empty one that was in the document before the paste stays a line. */
2080
+ const LINES = 'p, div, li, h1, h2, h3, h4, h5, h6, blockquote, pre';
2081
+
2082
+ /**
2083
+ * Take pasted pictures out of the document, each with everything that was only there for it:
2084
+ * its figure and caption, a link around it, a paragraph or list item that held nothing else.
2085
+ * Left behind, the caption of a picture that is not there and an empty paragraph went into the
2086
+ * RTF. Text that shared a paragraph with a picture stays, and so does whatever was in the
2087
+ * document before the paste; a table cell stays, since the table needs it. `replaced` is an
2088
+ * empty line whose place the paste took: if nothing of the paste is left, it is put back.
2089
+ */
2090
+ function removePastedImages(images: HTMLImageElement[], before: Set<Element>, replaced: Element | null): void {
2091
+ if (!editorEl) return;
2092
+ const root = editorEl;
2093
+ const selection = window.getSelection();
2094
+ const caret = selection?.anchorNode && root.contains(selection.anchorNode) ? selection.anchorNode : null;
2095
+ // Holds the caret's place once what the caret was in has gone. (Written this way so the
2096
+ // type checker does not take it to be null for good: it is set inside `take`.)
2097
+ let place = null as Comment | null;
2098
+ // Holds the place of the first thing taken out, for the line the paste took the place of.
2099
+ let first = null as Comment | null;
2100
+ // What is put in here, as opposed to what the paste brought.
2101
+ const made = new Set<Element>();
2102
+ const take = (node: Element): void => {
2103
+ if (place ? node.contains(place) : !!caret && node.contains(caret)) {
2104
+ place ??= document.createComment('');
2105
+ node.after(place);
2106
+ }
2107
+ if (first && node.contains(first)) node.after(first);
2108
+ node.remove();
2109
+ };
2110
+ /** Take a node out, and after it each thing around it that came with the paste and now shows nothing. */
2111
+ const takeWithEmptied = (start: Element): void => {
2112
+ let node = start;
2113
+ let parent: Element | null;
2114
+ let next: Node | null;
2115
+ for (;;) {
2116
+ parent = node.parentElement;
2117
+ next = node.nextSibling;
2118
+ take(node);
2119
+ if (!parent || parent === root || before.has(parent) || parent.matches('td, th')) break;
2120
+ if (!showsNothing(parent)) break;
2121
+ node = parent;
2122
+ }
2123
+ if (!parent) return;
2124
+ if (!first) {
2125
+ first = document.createComment('');
2126
+ parent.insertBefore(first, next);
2127
+ }
2128
+ // A line that was in the document before the paste and is empty again stays a line.
2129
+ if (parent !== root && before.has(parent) && parent.matches(LINES) && showsNothing(parent) && !parent.querySelector('br')) {
2130
+ const lineBreak = document.createElement('br');
2131
+ made.add(lineBreak);
2132
+ parent.appendChild(lineBreak);
2133
+ }
2134
+ };
2135
+ const pastedPicture = (node: Node | null) =>
2136
+ node instanceof Element && node.isConnected && !before.has(node) && (node.tagName === 'IMG' || node.querySelector('img') !== null);
2137
+
2138
+ for (const img of images) {
2139
+ if (!img.isConnected) continue;
2140
+ // The overlay and the Backspace key act on the selected picture: not on one that is gone.
2141
+ if (selectedImage === img) selectedImage = null;
2142
+ const after = shownBeside(img, root, true);
2143
+ const prior = shownBeside(img, root, false);
2144
+ takeWithEmptied(img);
2145
+
2146
+ // Chromium, pasting a figure at the end of a line of text, moves its pictures into that
2147
+ // line and leaves the figure after them with the caption alone (inside the wrapper the
2148
+ // figure came in, if it had one). A pasted caption alone, straight after the picture, is
2149
+ // that picture's, and goes with it, unless another picture pasted with it is still
2150
+ // there before it: the caption is then that one's too.
2151
+ if (after instanceof Element && after.isConnected && !before.has(after) && isCaptionAlone(after) && !pastedPicture(prior)) {
2152
+ takeWithEmptied(after);
2153
+ }
2154
+ }
2155
+
2156
+ // The paste took the place of an empty line, and nothing of the paste that shows is
2157
+ // left: the line is put back where the paste stood, as if nothing had been pasted.
2158
+ let line: HTMLElement | null = null;
2159
+ const holder = (first as Comment | null)?.parentElement ?? null;
2160
+ if (replaced && !replaced.isConnected && holder && !holder.matches('ul, ol, table, thead, tbody, tfoot, tr')) {
2161
+ const left = Array.from(root.querySelectorAll('*')).some((el) => !before.has(el) && !made.has(el) && !showsNothing(el));
2162
+ if (!left) {
2163
+ line = replaced as HTMLElement;
2164
+ // (Chromium takes the line's own line break out before it takes the line out.)
2165
+ if (!line.querySelector('br')) line.appendChild(document.createElement('br'));
2166
+ first!.before(line);
2167
+ }
2168
+ }
2169
+ first?.remove();
2170
+
2171
+ // The caret goes back into the line that was put back: it was there when the paste was made.
2172
+ if (line && caret) {
2173
+ placeCaret(line);
2174
+ place?.remove();
2175
+ return;
2176
+ }
2177
+
2178
+ // The caret went with what was removed: put it where typing carries on from.
2179
+ if (place?.isConnected) {
2180
+ const textBlock = (el: Element | null) => (el && !el.matches(`figure, ${SHOWN_WITHOUT_TEXT}`) ? (el as HTMLElement) : null);
2181
+ const previous = textBlock(place.previousElementSibling);
2182
+ const next = textBlock(place.nextElementSibling);
2183
+ if (place.parentElement && place.parentElement !== root) {
2184
+ // Inside something that stays (a line of text, a table cell): where it was.
2185
+ const range = document.createRange();
2186
+ range.setStartBefore(place);
2187
+ range.collapse(true);
2188
+ selection?.removeAllRanges();
2189
+ selection?.addRange(range);
2190
+ savedSelection = range.cloneRange();
2191
+ } else if (previous) {
2192
+ placeCaret(previous, false);
2193
+ } else if (next) {
2194
+ placeCaret(next, true);
2195
+ } else {
2196
+ // Nothing to type in next to it (the document is empty, or a table or another
2197
+ // picture is all there is): leave one empty line.
2198
+ const empty = document.createElement('p');
2199
+ empty.appendChild(document.createElement('br'));
2200
+ place.before(empty);
2201
+ placeCaret(empty);
2202
+ }
2203
+ }
2204
+ place?.remove();
2205
+ }
2206
+
2207
+
1621
2208
  // ── Lifecycle ──
1622
2209
  onMount(() => {
1623
2210
  if (!editorEl) return;
@@ -1625,7 +2212,9 @@
1625
2212
  try {
1626
2213
  const saved = localStorage.getItem(storageKey);
1627
2214
  if (saved) {
1628
- editorEl.innerHTML = saved;
2215
+ // A draft is HTML from outside like any other: anything that can write to this
2216
+ // origin's storage can write it.
2217
+ showDocument(saved);
1629
2218
  updateCounts();
1630
2219
  return;
1631
2220
  }
@@ -1634,7 +2223,7 @@
1634
2223
  // Always write the initial content prop so the div isn't empty.
1635
2224
  // {#html content} must NOT be used inside the contenteditable div —
1636
2225
  // Svelte would re-inject it on every reactive update, duplicating text.
1637
- editorEl.innerHTML = content || '<p></p>';
2226
+ showDocument(content || EMPTY_DOCUMENT);
1638
2227
  updateCounts();
1639
2228
  });
1640
2229
 
@@ -1682,6 +2271,9 @@
1682
2271
  onblock={setBlock}
1683
2272
  oninsertlink={openLinkModal}
1684
2273
  oninsertimage={openImageModal}
2274
+ fontSize={currentFontSize}
2275
+ fontSizes={sizeChoices}
2276
+ onfontsize={setFontSize}
1685
2277
  copyingFormat={copyFormat !== 'off'}
1686
2278
  oncopyformat={toggleCopyFormat}
1687
2279
  />
@@ -1709,11 +2301,17 @@
1709
2301
  class:copy-format-pick={copyFormat === 'pick'}
1710
2302
  class:copy-format-apply={copyFormat === 'apply'}
1711
2303
  contenteditable={!readonly}
2304
+ role="textbox"
2305
+ tabindex="0"
2306
+ aria-multiline="true"
2307
+ aria-label={ariaLabel}
2308
+ aria-readonly={readonly ? 'true' : undefined}
1712
2309
  spellcheck="true"
1713
2310
  bind:this={editorEl}
1714
2311
  oninput={handleInput}
1715
- onmouseup={updateToolbarState}
1716
- onkeyup={updateToolbarState}
2312
+ onmouseup={caretMoved}
2313
+ onkeyup={caretMoved}
2314
+ onscroll={contentScrolled}
1717
2315
  onkeydown={handleKeydown}
1718
2316
  onmousedown={() => (tabLeavesEditor = false)}
1719
2317
  onblur={() => (tabLeavesEditor = false)}
@@ -1739,6 +2337,7 @@
1739
2337
  bind:this={overlayRef}
1740
2338
  target={selectedImage}
1741
2339
  bounds={contentWrapEl}
2340
+ within={editorEl}
1742
2341
  maxWidth={contentWidth}
1743
2342
  onchange={handleImageEdited}
1744
2343
  onremove={removeSelectedImage}
@@ -1759,12 +2358,20 @@
1759
2358
 
1760
2359
  <!-- Link Modal -->
1761
2360
  <Modal title="Insert Link" open={linkModalOpen} onclose={() => (linkModalOpen = false)}>
1762
- <input type="text" placeholder="Link text (leave empty to use selection)" bind:value={linkText} />
2361
+ <input
2362
+ type="text"
2363
+ placeholder="Link text (leave empty to use selection)"
2364
+ aria-label="Link text"
2365
+ bind:value={linkText}
2366
+ onkeydown={(e) => onEnter(e, applyLink)}
2367
+ />
1763
2368
  <input
1764
2369
  type="url"
1765
2370
  placeholder="https://example.com"
2371
+ aria-label="Link address"
2372
+ data-autofocus
1766
2373
  bind:value={linkUrl}
1767
- onkeydown={(e) => e.key === 'Enter' && applyLink()}
2374
+ onkeydown={(e) => onEnter(e, applyLink)}
1768
2375
  aria-invalid={linkError ? 'true' : undefined}
1769
2376
  aria-describedby={linkError ? 'ink-link-error' : undefined}
1770
2377
  />
@@ -1795,17 +2402,18 @@
1795
2402
  <input
1796
2403
  type="url"
1797
2404
  placeholder="https://example.com/image.jpg"
2405
+ aria-label="Image address"
1798
2406
  bind:value={imageUrl}
1799
- onkeydown={(e) => e.key === 'Enter' && applyImage()}
2407
+ onkeydown={(e) => onEnter(e, () => void applyImage())}
1800
2408
  />
1801
2409
  {/if}
1802
2410
 
1803
2411
  {#if pendingImageFiles.length > 1}
1804
2412
  <p class="ink-modal-hint">Add a description under each image after inserting.</p>
1805
2413
  {:else}
1806
- <input type="text" placeholder="Description shown below the image (optional)" bind:value={imageCaption} />
2414
+ <input type="text" placeholder="Description shown below the image (optional)" aria-label="Description shown below the image" bind:value={imageCaption} />
1807
2415
  {/if}
1808
- <input type="text" placeholder="Alt text for screen readers (optional)" bind:value={imageAlt} />
2416
+ <input type="text" placeholder="Alt text for screen readers (optional)" aria-label="Alt text for screen readers" bind:value={imageAlt} />
1809
2417
 
1810
2418
  {#snippet actions()}
1811
2419
  <button class="ink-btn-ghost" onclick={() => (imageModalOpen = false)}>Cancel</button>
@@ -1821,7 +2429,7 @@
1821
2429
 
1822
2430
  <!-- Import Error Toast -->
1823
2431
  {#if importError}
1824
- <div class="ink-toast-error">
2432
+ <div class="ink-toast-error" role="alert">
1825
2433
  <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
2434
  {importError}
1827
2435
  </div>
@@ -1844,6 +2452,9 @@
1844
2452
 
1845
2453
  /* ── Content Area ── */
1846
2454
  .ink-content {
2455
+ /* Nothing in the document is drawn outside the editing area, whatever its styles: a table
2456
+ wider than the area scrolls inside it, and does not run out over the page beside it. */
2457
+ overflow: auto;
1847
2458
  min-height: var(--ink-min-height, 40vh);
1848
2459
  padding: 48px 56px;
1849
2460
  background: white;
@@ -1851,7 +2462,7 @@
1851
2462
  border-radius: var(--radius, 8px);
1852
2463
  box-shadow: var(--shadow-md, 0 4px 12px rgba(44, 37, 32, 0.08));
1853
2464
  outline: none;
1854
- font-family: var(--ink-font-family, Arial, sans-serif);
2465
+ font-family: var(--ink-font-family, sans-serif);
1855
2466
  font-size: var(--ink-font-size, 12pt);
1856
2467
  line-height: 1.75;
1857
2468
  color: var(--text, #2c2520);