svelte-rtf-editor 1.8.3 → 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.
- package/README.md +212 -26
- package/dist/RtfViewer.svelte +69 -7
- package/dist/RtfViewer.svelte.d.ts +2 -1
- package/dist/components/ImageOverlay.svelte +11 -3
- package/dist/components/ImageOverlay.svelte.d.ts +2 -0
- package/dist/components/InkEditor.svelte +705 -35
- package/dist/components/InkEditor.svelte.d.ts +14 -3
- package/dist/components/Modal.svelte +57 -3
- package/dist/components/Toolbar.svelte +44 -1
- package/dist/components/Toolbar.svelte.d.ts +5 -0
- package/dist/components/ToolbarButton.svelte +8 -2
- package/dist/components/ToolbarButton.svelte.d.ts +4 -0
- package/dist/images.d.ts +60 -7
- package/dist/images.js +268 -59
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/rtf-parser.d.ts +16 -3
- package/dist/rtf-parser.js +1682 -534
- package/dist/rtf-writer.d.ts +40 -9
- package/dist/rtf-writer.js +1175 -359
- package/dist/sanitize.d.ts +77 -0
- package/dist/sanitize.js +755 -0
- package/dist/table-model.d.ts +49 -0
- package/dist/table-model.js +203 -0
- package/dist/utils.js +689 -87
- package/package.json +16 -12
|
@@ -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 —
|
|
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
|
|
@@ -23,10 +27,16 @@
|
|
|
23
27
|
* which is what bounds the RTF payload — it costs two hex
|
|
24
28
|
* characters per byte. 0 disables. Default: 524288 (512 KB,
|
|
25
29
|
* about 1 MB of document per image).
|
|
30
|
+
* maxRtfBytes — The largest RTF file Import reads. Default: 52428800 (50 MB);
|
|
31
|
+
* 0 reads any size.
|
|
26
32
|
* fontFamily — Font for the document, both on screen and in the RTF.
|
|
27
|
-
* Default:
|
|
33
|
+
* Default: DEFAULT_FONT_FAMILY (rtf-writer.ts).
|
|
28
34
|
* fontSize — Body text size in points, both on screen and in the RTF.
|
|
29
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.
|
|
30
40
|
*
|
|
31
41
|
* Events (callback props):
|
|
32
42
|
* onchange — Fires on content change with
|
|
@@ -52,7 +62,8 @@
|
|
|
52
62
|
import Modal from './Modal.svelte';
|
|
53
63
|
import ImageOverlay from './ImageOverlay.svelte';
|
|
54
64
|
import { htmlToMarkdown, downloadFile } from '../utils.js';
|
|
55
|
-
import {
|
|
65
|
+
import { pasteNotes, removeWordHidden, sanitizedNodes, sanitizeTree, type PasteNotes } from '../sanitize.js';
|
|
66
|
+
import { readRtfFile, DEFAULT_MAX_RTF_BYTES } from '../rtf-parser.js';
|
|
56
67
|
import {
|
|
57
68
|
htmlToRtf,
|
|
58
69
|
estimateRtfBytes,
|
|
@@ -74,15 +85,21 @@
|
|
|
74
85
|
} from '../images.js';
|
|
75
86
|
|
|
76
87
|
interface ChangePayload {
|
|
77
|
-
|
|
78
|
-
|
|
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;
|
|
79
96
|
wordCount: number;
|
|
80
97
|
charCount: number;
|
|
81
98
|
/**
|
|
82
99
|
* Approximate size of this document as RTF. Pictures dominate it and are
|
|
83
100
|
* counted exactly; see getRtfSize() for the precise figure.
|
|
84
101
|
*/
|
|
85
|
-
estimatedRtfBytes: number;
|
|
102
|
+
readonly estimatedRtfBytes: number;
|
|
86
103
|
}
|
|
87
104
|
|
|
88
105
|
interface Props {
|
|
@@ -94,31 +111,48 @@
|
|
|
94
111
|
showStatusBar?: boolean;
|
|
95
112
|
minHeight?: string;
|
|
96
113
|
readonly?: boolean;
|
|
114
|
+
ariaLabel?: string;
|
|
97
115
|
maxImageEdge?: number;
|
|
98
116
|
maxImageBytes?: number;
|
|
99
117
|
maxImageDisplayWidth?: number;
|
|
118
|
+
/** The largest RTF file Import reads (readRtfFile's maxBytes); 0 for no limit. */
|
|
119
|
+
maxRtfBytes?: number;
|
|
100
120
|
fontFamily?: string;
|
|
101
121
|
fontSize?: number;
|
|
122
|
+
fontSizes?: number[];
|
|
102
123
|
onchange?: (payload: ChangePayload) => void;
|
|
103
124
|
onsave?: (payload: { html: string }) => void;
|
|
104
125
|
onimport?: (payload: { html: string }) => void;
|
|
105
126
|
}
|
|
106
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
|
+
|
|
107
138
|
// ── Props ──
|
|
108
139
|
let {
|
|
109
|
-
content =
|
|
140
|
+
content = EMPTY_DOCUMENT,
|
|
110
141
|
placeholder = 'Start writing something beautiful...',
|
|
111
|
-
autosave =
|
|
142
|
+
autosave = false,
|
|
112
143
|
storageKey = 'ink-editor-content',
|
|
113
144
|
showToolbar = true,
|
|
114
145
|
showStatusBar = true,
|
|
115
146
|
minHeight = '40vh',
|
|
116
147
|
readonly = false,
|
|
148
|
+
ariaLabel = 'Document',
|
|
117
149
|
maxImageEdge = DEFAULT_MAX_IMAGE_EDGE,
|
|
118
150
|
maxImageBytes = DEFAULT_MAX_IMAGE_BYTES,
|
|
119
151
|
maxImageDisplayWidth = DEFAULT_MAX_IMAGE_DISPLAY_WIDTH,
|
|
152
|
+
maxRtfBytes = DEFAULT_MAX_RTF_BYTES,
|
|
120
153
|
fontFamily = DEFAULT_FONT_FAMILY,
|
|
121
154
|
fontSize = DEFAULT_FONT_SIZE,
|
|
155
|
+
fontSizes = DEFAULT_FONT_SIZES,
|
|
122
156
|
onchange,
|
|
123
157
|
onsave,
|
|
124
158
|
onimport
|
|
@@ -137,6 +171,8 @@
|
|
|
137
171
|
let charCount: number = $state(0);
|
|
138
172
|
let lastSaved: string = $state('');
|
|
139
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);
|
|
140
176
|
|
|
141
177
|
let formatState = $state({
|
|
142
178
|
bold: false,
|
|
@@ -181,12 +217,31 @@
|
|
|
181
217
|
if (editorEl) {
|
|
182
218
|
selectedImage = null;
|
|
183
219
|
documentReplaced();
|
|
184
|
-
|
|
220
|
+
showDocument(html);
|
|
185
221
|
updateCounts();
|
|
186
222
|
if (autosave) scheduleAutoSave();
|
|
187
223
|
}
|
|
188
224
|
}
|
|
189
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
|
+
|
|
190
245
|
export function getMarkdown(): string {
|
|
191
246
|
if (!editorEl) return '';
|
|
192
247
|
return htmlToMarkdown(editorEl);
|
|
@@ -213,7 +268,8 @@
|
|
|
213
268
|
if (editorEl) {
|
|
214
269
|
selectedImage = null;
|
|
215
270
|
documentReplaced();
|
|
216
|
-
editorEl.innerHTML =
|
|
271
|
+
editorEl.innerHTML = EMPTY_DOCUMENT;
|
|
272
|
+
clearTimeout(saveTimer);
|
|
217
273
|
try { localStorage.removeItem(storageKey); } catch (e) {}
|
|
218
274
|
updateCounts();
|
|
219
275
|
lastSaved = '';
|
|
@@ -259,6 +315,7 @@
|
|
|
259
315
|
function documentReplaced(): void {
|
|
260
316
|
indentUndo = [];
|
|
261
317
|
pastedOver = null;
|
|
318
|
+
pastedLoss = null;
|
|
262
319
|
stopCopyFormat();
|
|
263
320
|
}
|
|
264
321
|
|
|
@@ -292,6 +349,179 @@
|
|
|
292
349
|
}
|
|
293
350
|
}
|
|
294
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
|
+
|
|
295
525
|
// ── Exec command ──
|
|
296
526
|
function exec(cmd: string, value: string | null = null): void {
|
|
297
527
|
restoreSelection();
|
|
@@ -313,6 +543,7 @@
|
|
|
313
543
|
}
|
|
314
544
|
if (cmd === 'undo' && undoIndent()) return;
|
|
315
545
|
document.execCommand(cmd, false, value ?? undefined);
|
|
546
|
+
if (cmd === 'undo' || cmd === 'redo') afterHistory();
|
|
316
547
|
updateToolbarState();
|
|
317
548
|
}
|
|
318
549
|
|
|
@@ -891,6 +1122,7 @@
|
|
|
891
1122
|
// Snapshot the selection so exec/setBlock can restore it even if focus
|
|
892
1123
|
// temporarily moved to a toolbar element (e.g. colour picker, select).
|
|
893
1124
|
saveSelection();
|
|
1125
|
+
currentFontSize = sizeAtSelection();
|
|
894
1126
|
|
|
895
1127
|
formatState = {
|
|
896
1128
|
bold: document.queryCommandState('bold'),
|
|
@@ -907,21 +1139,52 @@
|
|
|
907
1139
|
updateCounts();
|
|
908
1140
|
}
|
|
909
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
|
+
|
|
910
1157
|
function updateCounts(): void {
|
|
911
1158
|
if (!editorEl) return;
|
|
912
|
-
const
|
|
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;
|
|
913
1163
|
const words = text.trim().split(/\s+/).filter((w) => w.length > 0);
|
|
914
1164
|
wordCount = words.length;
|
|
915
1165
|
charCount = text.length;
|
|
916
1166
|
}
|
|
917
1167
|
|
|
918
1168
|
function fireChange(): void {
|
|
919
|
-
onchange
|
|
920
|
-
|
|
921
|
-
|
|
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(); },
|
|
922
1185
|
wordCount,
|
|
923
1186
|
charCount,
|
|
924
|
-
estimatedRtfBytes
|
|
1187
|
+
get estimatedRtfBytes() { return estimate(); }
|
|
925
1188
|
});
|
|
926
1189
|
}
|
|
927
1190
|
|
|
@@ -948,13 +1211,23 @@
|
|
|
948
1211
|
}
|
|
949
1212
|
|
|
950
1213
|
// ── Input handler ──
|
|
951
|
-
function handleInput(): void {
|
|
1214
|
+
function handleInput(e?: Event): void {
|
|
952
1215
|
placeCopySourceBox();
|
|
953
1216
|
if (pastedOver) {
|
|
954
1217
|
tidyPasted(pastedOver);
|
|
955
1218
|
pastedOver = null;
|
|
956
1219
|
}
|
|
957
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;
|
|
958
1231
|
updateToolbarState();
|
|
959
1232
|
// Typing means the user is editing text, not the picture. Dropping the
|
|
960
1233
|
// selection here keeps Backspace editing that text instead of deleting a
|
|
@@ -994,7 +1267,7 @@
|
|
|
994
1267
|
const range = sel.getRangeAt(0);
|
|
995
1268
|
range.deleteContents();
|
|
996
1269
|
const a = document.createElement('a');
|
|
997
|
-
a.href = linkUrl;
|
|
1270
|
+
a.href = linkUrl.trim();
|
|
998
1271
|
a.textContent = linkText;
|
|
999
1272
|
range.insertNode(a);
|
|
1000
1273
|
range.setStartAfter(a);
|
|
@@ -1002,9 +1275,24 @@
|
|
|
1002
1275
|
sel.addRange(range);
|
|
1003
1276
|
}
|
|
1004
1277
|
} else {
|
|
1005
|
-
document.execCommand('createLink', false, linkUrl);
|
|
1278
|
+
document.execCommand('createLink', false, linkUrl.trim());
|
|
1006
1279
|
}
|
|
1007
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();
|
|
1008
1296
|
}
|
|
1009
1297
|
|
|
1010
1298
|
// ── Images ──
|
|
@@ -1048,7 +1336,18 @@
|
|
|
1048
1336
|
|
|
1049
1337
|
insertingImages = true;
|
|
1050
1338
|
try {
|
|
1051
|
-
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
|
+
}
|
|
1052
1351
|
restoreSelection();
|
|
1053
1352
|
editorEl?.focus();
|
|
1054
1353
|
finishInsert(insertFigure(src, alt || caption, caption));
|
|
@@ -1061,6 +1360,13 @@
|
|
|
1061
1360
|
}
|
|
1062
1361
|
}
|
|
1063
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
|
+
|
|
1064
1370
|
/** Caps applied to a picture as it is inserted. */
|
|
1065
1371
|
function imageLimits(): { maxEdge: number; maxBytes: number } {
|
|
1066
1372
|
return { maxEdge: maxImageEdge, maxBytes: maxImageBytes };
|
|
@@ -1211,9 +1517,14 @@
|
|
|
1211
1517
|
finishInsert(inserted);
|
|
1212
1518
|
}
|
|
1213
1519
|
|
|
1520
|
+
let errorTimer: ReturnType<typeof setTimeout> | undefined;
|
|
1521
|
+
|
|
1214
1522
|
function showError(message: string): void {
|
|
1215
1523
|
importError = message;
|
|
1216
|
-
|
|
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));
|
|
1217
1528
|
}
|
|
1218
1529
|
|
|
1219
1530
|
// ── Image selection / editing ──
|
|
@@ -1316,11 +1627,13 @@
|
|
|
1316
1627
|
importing = true;
|
|
1317
1628
|
|
|
1318
1629
|
try {
|
|
1319
|
-
const html = await readRtfFile(file, { fontSize });
|
|
1630
|
+
const html = await readRtfFile(file, { fontSize, maxBytes: maxRtfBytes });
|
|
1320
1631
|
if (editorEl) {
|
|
1321
1632
|
selectedImage = null;
|
|
1322
1633
|
documentReplaced();
|
|
1323
|
-
|
|
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);
|
|
1324
1637
|
updateCounts();
|
|
1325
1638
|
fireChange();
|
|
1326
1639
|
if (autosave) scheduleAutoSave();
|
|
@@ -1528,15 +1841,59 @@
|
|
|
1528
1841
|
if (!readonly && editorEl) {
|
|
1529
1842
|
const snapshot = new Set(editorEl.querySelectorAll('*'));
|
|
1530
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;
|
|
1531
1851
|
// A paste that inserts nothing (an empty clipboard, a host that cancels it) raises no
|
|
1532
1852
|
// input event. Left set, the snapshot would make the next keystroke treat the whole
|
|
1533
1853
|
// document as pasted.
|
|
1534
1854
|
setTimeout(() => {
|
|
1535
|
-
if (pastedOver === snapshot)
|
|
1855
|
+
if (pastedOver === snapshot) {
|
|
1856
|
+
pastedOver = null;
|
|
1857
|
+
pastedLoss = null;
|
|
1858
|
+
}
|
|
1536
1859
|
}, 0);
|
|
1537
1860
|
}
|
|
1538
1861
|
}
|
|
1539
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
|
+
|
|
1540
1897
|
// ── Pasted formatting ──
|
|
1541
1898
|
// A browser copies a paragraph with its looks written out: Chromium turns the editor's own
|
|
1542
1899
|
// spacing into "margin: 0px 0px 0.2em 96px" on the copy, and repeats the id. Pasted back, the
|
|
@@ -1547,9 +1904,17 @@
|
|
|
1547
1904
|
const PASTED_SPACING = ['margin-top', 'margin-right', 'margin-bottom', 'margin-left', 'text-indent'];
|
|
1548
1905
|
/** The elements in the editor just before a paste; what is not in it came from the paste. */
|
|
1549
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;
|
|
1550
1909
|
|
|
1551
1910
|
function tidyPasted(before: Set<Element>): void {
|
|
1552
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));
|
|
1553
1918
|
for (const el of Array.from(editorEl.querySelectorAll<HTMLElement>('*'))) {
|
|
1554
1919
|
if (before.has(el)) continue;
|
|
1555
1920
|
el.removeAttribute('id');
|
|
@@ -1564,8 +1929,282 @@
|
|
|
1564
1929
|
}
|
|
1565
1930
|
if (!el.getAttribute('style')) el.removeAttribute('style');
|
|
1566
1931
|
}
|
|
1932
|
+
// A picture copied with its text comes in by address (<img src="https://…">), or as data in
|
|
1933
|
+
// a format the RTF cannot carry (GIF, WebP, SVG) or larger than maxImageBytes. Only PNG or
|
|
1934
|
+
// JPEG data held in the document reaches the RTF, so each one goes through the same step as
|
|
1935
|
+
// the image dialog: fetched, converted and scaled as needed.
|
|
1936
|
+
const pasted = Array.from(editorEl.querySelectorAll('img')).filter((img) => !before.has(img));
|
|
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);
|
|
1567
1944
|
}
|
|
1568
1945
|
|
|
1946
|
+
/**
|
|
1947
|
+
* Fetch each pasted picture and hold its data in the document. One that cannot be fetched
|
|
1948
|
+
* (the site forbids it, or there is no network) still shows, but leaves in the RTF as an
|
|
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.
|
|
1952
|
+
*/
|
|
1953
|
+
async function embedPastedImages(images: HTMLImageElement[], before: Set<Element>, replaced: Element | null): Promise<void> {
|
|
1954
|
+
let failed = 0;
|
|
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
|
+
|
|
2008
|
+
// All at once, each with its own timeout, so one slow site does not hold up the rest.
|
|
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();
|
|
2023
|
+
if (failed > 0) {
|
|
2024
|
+
said.push(
|
|
2025
|
+
failed === 1
|
|
2026
|
+
? 'A pasted image could not be embedded — it will export as a placeholder'
|
|
2027
|
+
: `${failed} pasted images could not be embedded — they will export as placeholders`
|
|
2028
|
+
);
|
|
2029
|
+
}
|
|
2030
|
+
if (failed > 0 || said.length > saidFirst.length) showError(said.join('. '));
|
|
2031
|
+
if (changed) {
|
|
2032
|
+
updateCounts();
|
|
2033
|
+
fireChange();
|
|
2034
|
+
if (autosave) scheduleAutoSave();
|
|
2035
|
+
}
|
|
2036
|
+
}
|
|
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
|
+
|
|
1569
2208
|
// ── Lifecycle ──
|
|
1570
2209
|
onMount(() => {
|
|
1571
2210
|
if (!editorEl) return;
|
|
@@ -1573,7 +2212,9 @@
|
|
|
1573
2212
|
try {
|
|
1574
2213
|
const saved = localStorage.getItem(storageKey);
|
|
1575
2214
|
if (saved) {
|
|
1576
|
-
|
|
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);
|
|
1577
2218
|
updateCounts();
|
|
1578
2219
|
return;
|
|
1579
2220
|
}
|
|
@@ -1582,7 +2223,7 @@
|
|
|
1582
2223
|
// Always write the initial content prop so the div isn't empty.
|
|
1583
2224
|
// {#html content} must NOT be used inside the contenteditable div —
|
|
1584
2225
|
// Svelte would re-inject it on every reactive update, duplicating text.
|
|
1585
|
-
|
|
2226
|
+
showDocument(content || EMPTY_DOCUMENT);
|
|
1586
2227
|
updateCounts();
|
|
1587
2228
|
});
|
|
1588
2229
|
|
|
@@ -1630,6 +2271,9 @@
|
|
|
1630
2271
|
onblock={setBlock}
|
|
1631
2272
|
oninsertlink={openLinkModal}
|
|
1632
2273
|
oninsertimage={openImageModal}
|
|
2274
|
+
fontSize={currentFontSize}
|
|
2275
|
+
fontSizes={sizeChoices}
|
|
2276
|
+
onfontsize={setFontSize}
|
|
1633
2277
|
copyingFormat={copyFormat !== 'off'}
|
|
1634
2278
|
oncopyformat={toggleCopyFormat}
|
|
1635
2279
|
/>
|
|
@@ -1657,11 +2301,17 @@
|
|
|
1657
2301
|
class:copy-format-pick={copyFormat === 'pick'}
|
|
1658
2302
|
class:copy-format-apply={copyFormat === 'apply'}
|
|
1659
2303
|
contenteditable={!readonly}
|
|
2304
|
+
role="textbox"
|
|
2305
|
+
tabindex="0"
|
|
2306
|
+
aria-multiline="true"
|
|
2307
|
+
aria-label={ariaLabel}
|
|
2308
|
+
aria-readonly={readonly ? 'true' : undefined}
|
|
1660
2309
|
spellcheck="true"
|
|
1661
2310
|
bind:this={editorEl}
|
|
1662
2311
|
oninput={handleInput}
|
|
1663
|
-
onmouseup={
|
|
1664
|
-
onkeyup={
|
|
2312
|
+
onmouseup={caretMoved}
|
|
2313
|
+
onkeyup={caretMoved}
|
|
2314
|
+
onscroll={contentScrolled}
|
|
1665
2315
|
onkeydown={handleKeydown}
|
|
1666
2316
|
onmousedown={() => (tabLeavesEditor = false)}
|
|
1667
2317
|
onblur={() => (tabLeavesEditor = false)}
|
|
@@ -1687,6 +2337,7 @@
|
|
|
1687
2337
|
bind:this={overlayRef}
|
|
1688
2338
|
target={selectedImage}
|
|
1689
2339
|
bounds={contentWrapEl}
|
|
2340
|
+
within={editorEl}
|
|
1690
2341
|
maxWidth={contentWidth}
|
|
1691
2342
|
onchange={handleImageEdited}
|
|
1692
2343
|
onremove={removeSelectedImage}
|
|
@@ -1707,12 +2358,20 @@
|
|
|
1707
2358
|
|
|
1708
2359
|
<!-- Link Modal -->
|
|
1709
2360
|
<Modal title="Insert Link" open={linkModalOpen} onclose={() => (linkModalOpen = false)}>
|
|
1710
|
-
<input
|
|
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
|
+
/>
|
|
1711
2368
|
<input
|
|
1712
2369
|
type="url"
|
|
1713
2370
|
placeholder="https://example.com"
|
|
2371
|
+
aria-label="Link address"
|
|
2372
|
+
data-autofocus
|
|
1714
2373
|
bind:value={linkUrl}
|
|
1715
|
-
onkeydown={(e) => e
|
|
2374
|
+
onkeydown={(e) => onEnter(e, applyLink)}
|
|
1716
2375
|
aria-invalid={linkError ? 'true' : undefined}
|
|
1717
2376
|
aria-describedby={linkError ? 'ink-link-error' : undefined}
|
|
1718
2377
|
/>
|
|
@@ -1743,17 +2402,18 @@
|
|
|
1743
2402
|
<input
|
|
1744
2403
|
type="url"
|
|
1745
2404
|
placeholder="https://example.com/image.jpg"
|
|
2405
|
+
aria-label="Image address"
|
|
1746
2406
|
bind:value={imageUrl}
|
|
1747
|
-
onkeydown={(e) => e
|
|
2407
|
+
onkeydown={(e) => onEnter(e, () => void applyImage())}
|
|
1748
2408
|
/>
|
|
1749
2409
|
{/if}
|
|
1750
2410
|
|
|
1751
2411
|
{#if pendingImageFiles.length > 1}
|
|
1752
2412
|
<p class="ink-modal-hint">Add a description under each image after inserting.</p>
|
|
1753
2413
|
{:else}
|
|
1754
|
-
<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} />
|
|
1755
2415
|
{/if}
|
|
1756
|
-
<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} />
|
|
1757
2417
|
|
|
1758
2418
|
{#snippet actions()}
|
|
1759
2419
|
<button class="ink-btn-ghost" onclick={() => (imageModalOpen = false)}>Cancel</button>
|
|
@@ -1769,7 +2429,7 @@
|
|
|
1769
2429
|
|
|
1770
2430
|
<!-- Import Error Toast -->
|
|
1771
2431
|
{#if importError}
|
|
1772
|
-
<div class="ink-toast-error">
|
|
2432
|
+
<div class="ink-toast-error" role="alert">
|
|
1773
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>
|
|
1774
2434
|
{importError}
|
|
1775
2435
|
</div>
|
|
@@ -1792,6 +2452,9 @@
|
|
|
1792
2452
|
|
|
1793
2453
|
/* ── Content Area ── */
|
|
1794
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;
|
|
1795
2458
|
min-height: var(--ink-min-height, 40vh);
|
|
1796
2459
|
padding: 48px 56px;
|
|
1797
2460
|
background: white;
|
|
@@ -1799,7 +2462,7 @@
|
|
|
1799
2462
|
border-radius: var(--radius, 8px);
|
|
1800
2463
|
box-shadow: var(--shadow-md, 0 4px 12px rgba(44, 37, 32, 0.08));
|
|
1801
2464
|
outline: none;
|
|
1802
|
-
font-family: var(--ink-font-family,
|
|
2465
|
+
font-family: var(--ink-font-family, sans-serif);
|
|
1803
2466
|
font-size: var(--ink-font-size, 12pt);
|
|
1804
2467
|
line-height: 1.75;
|
|
1805
2468
|
color: var(--text, #2c2520);
|
|
@@ -2032,6 +2695,13 @@
|
|
|
2032
2695
|
margin: 32px 0;
|
|
2033
2696
|
}
|
|
2034
2697
|
|
|
2698
|
+
/* A page break read from RTF (\page): a dashed rule, written back as \page. */
|
|
2699
|
+
.ink-content :global(hr[style*='break-after']) {
|
|
2700
|
+
height: 0;
|
|
2701
|
+
background: none;
|
|
2702
|
+
border-top: 1px dashed var(--text-muted, #8a7e72);
|
|
2703
|
+
}
|
|
2704
|
+
|
|
2035
2705
|
/* ── Status Bar ── */
|
|
2036
2706
|
.ink-status-bar {
|
|
2037
2707
|
display: flex;
|