svelte-rtf-editor 1.12.0 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,6 +11,10 @@
11
11
  * `content`. Default: false. Give each document its own storageKey.
12
12
  * storageKey — localStorage key for auto-save. Default: 'ink-editor-content'.
13
13
  * showToolbar — Show the formatting toolbar. Default: true.
14
+ * stickyToolbar — Keep the toolbar in sight while a long document is scrolled: it
15
+ * stays at the top of the window, or of the scrolling element the
16
+ * editor is in. Default: true. Under a header of your own that stays
17
+ * too, set the CSS variable --ink-toolbar-top to its height.
14
18
  * showStatusBar — Show the word/char count status bar. Default: true.
15
19
  * minHeight — CSS min-height of the editing area. Default: '40vh'.
16
20
  * readonly — If true, editor is not editable. Default: false.
@@ -30,13 +34,22 @@
30
34
  * maxRtfBytes — The largest RTF file Import reads. Default: 52428800 (50 MB);
31
35
  * 0 reads any size.
32
36
  * fontFamily — Font for the document, both on screen and in the RTF.
33
- * Default: DEFAULT_FONT_FAMILY (rtf-writer.ts).
37
+ * Given a CSS list ('Segoe UI, Selawik, sans-serif'), the first
38
+ * family is the font, and the rest is what a screen without it
39
+ * shows. Default: DEFAULT_FONT_FAMILY (rtf-writer.ts).
34
40
  * fontSize — Body text size in points, both on screen and in the RTF.
35
41
  * Headings scale from it. Default: 12.
36
42
  * fontSizes — The sizes, in points, the toolbar's size list offers for the
37
43
  * selected text. The body size is always among them. An empty
38
44
  * list takes the size list off the toolbar.
39
45
  * Default: 8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 36.
46
+ * fonts — The fonts the toolbar's font list offers for the selected text,
47
+ * beside the document's own: names ('Calibri'), or CSS lists whose
48
+ * first family is the name ('Calibri, Carlito, sans-serif'). Text
49
+ * in one of them is written in it to the RTF and read back in it;
50
+ * any other font is taken off HTML as it comes in, set or pasted.
51
+ * Default: none: there is no font list, and no font but the
52
+ * document's is let in.
40
53
  * keepAttributes — `data-` attributes the application's documents carry, which
41
54
  * the editor leaves on their elements: a mark on a paragraph that
42
55
  * the application reads back (`data-section="2"`). Every other
@@ -65,6 +78,8 @@
65
78
  * exportFile(format) — Downloads as 'html', 'md', or 'rtf'.
66
79
  * importRtf() — Opens the file picker to import an RTF file.
67
80
  * setFontSize(points) — Sets the size of the selected text, or of what is typed next.
81
+ * setFont(name) — Sets the font of the selected text, or of what is typed next, to
82
+ * one of `fonts`; '' or the document font's name sets it back.
68
83
  * clearFormatting() — Takes bold, italic, underline, strike, color, size and font off
69
84
  * the selected text. Headings, lists, links, alignment, indents and
70
85
  * the application's own marks stay.
@@ -75,13 +90,17 @@
75
90
  import Modal from './Modal.svelte';
76
91
  import ImageOverlay from './ImageOverlay.svelte';
77
92
  import { htmlToMarkdown, downloadFile } from '../utils.js';
78
- import { keptMarks, pasteHasWords, pasteNotes, removeWordHidden, sanitizedNodes, sanitizeTree, type PasteNotes } from '../sanitize.js';
93
+ import { keptMarks, pasteHasWords, pasteNotes, pasteWithoutFrames, removeWordHidden, sanitizedNodes, sanitizeTree, type PasteNotes } from '../sanitize.js';
94
+ import { givePastedPictures, pastePictures, type PastePictures } from '../paste-pictures.js';
79
95
  import { readRtfFile, DEFAULT_MAX_RTF_BYTES } from '../rtf-parser.js';
80
96
  import {
81
97
  htmlToRtf,
82
98
  estimateRtfBytes,
83
99
  isSafeLinkUrl,
100
+ linkTarget,
84
101
  cssFontFamily,
102
+ fontChoices,
103
+ fontKey,
85
104
  normalizeFontSize,
86
105
  DEFAULT_FONT_FAMILY,
87
106
  DEFAULT_FONT_SIZE
@@ -121,6 +140,7 @@
121
140
  autosave?: boolean;
122
141
  storageKey?: string;
123
142
  showToolbar?: boolean;
143
+ stickyToolbar?: boolean;
124
144
  showStatusBar?: boolean;
125
145
  minHeight?: string;
126
146
  readonly?: boolean;
@@ -133,6 +153,8 @@
133
153
  fontFamily?: string;
134
154
  fontSize?: number;
135
155
  fontSizes?: number[];
156
+ /** The fonts offered for text, beside the document's own; none unless given. */
157
+ fonts?: string[];
136
158
  /** `data-` attributes of the application's own, kept on HTML that is set or pasted. */
137
159
  keepAttributes?: string[];
138
160
  /** Class names of the application's own, kept the same way. */
@@ -163,6 +185,7 @@
163
185
  autosave = false,
164
186
  storageKey = 'ink-editor-content',
165
187
  showToolbar = true,
188
+ stickyToolbar = true,
166
189
  showStatusBar = true,
167
190
  minHeight = '40vh',
168
191
  readonly = false,
@@ -174,6 +197,7 @@
174
197
  fontFamily = DEFAULT_FONT_FAMILY,
175
198
  fontSize = DEFAULT_FONT_SIZE,
176
199
  fontSizes = DEFAULT_FONT_SIZES,
200
+ fonts = NO_KEPT_ATTRIBUTES,
177
201
  keepAttributes = NO_KEPT_ATTRIBUTES,
178
202
  keepClasses = NO_KEPT_ATTRIBUTES,
179
203
  onchange,
@@ -181,12 +205,15 @@
181
205
  onimport
182
206
  }: Props = $props();
183
207
 
184
- const keptNames = $derived(keptMarks({ keepAttributes, keepClasses }));
208
+ const keptNames = $derived(keptMarks({ keepAttributes, keepClasses, fonts, fontFamily }));
185
209
 
186
210
  // The same font and size go to the screen and to the RTF, so the editor
187
211
  // shows what the receiving system will show.
188
- const rtfOptions = $derived({ fontFamily, fontSize });
212
+ const rtfOptions = $derived({ fontFamily, fontSize, fonts });
189
213
  const screenFontFamily = $derived(cssFontFamily(fontFamily));
214
+ /** The name the document font is looked up by, and the fonts offered beside it. */
215
+ const documentFontKey = $derived(fontKey(screenFontFamily));
216
+ const fontList = $derived(fontChoices(fonts).filter((choice) => choice.key !== documentFontKey));
190
217
  const screenFontSize = $derived(normalizeFontSize(fontSize));
191
218
 
192
219
  // ── Internal state ──
@@ -198,6 +225,8 @@
198
225
  let currentBlock: string = $state('p');
199
226
  /** The size of the text at the caret, in points, for the toolbar. */
200
227
  let currentFontSize: number | null = $state(null);
228
+ /** The font at the selection, by its key: '' for the document font, null where it has more than one. */
229
+ let currentFont: string | null = $state('');
201
230
 
202
231
  let formatState = $state({
203
232
  bold: false,
@@ -493,6 +522,8 @@
493
522
  indentUndo = [];
494
523
  pastedOver = null;
495
524
  pastedLoss = null;
525
+ pastedPictures = null;
526
+ commentsBefore = null;
496
527
  // (A selection kept from the document before points at nothing in the new one.)
497
528
  savedSelection = null;
498
529
  dialogSelection = null;
@@ -736,7 +767,7 @@
736
767
  if (autosave) scheduleAutoSave();
737
768
  }
738
769
 
739
- /** The size of the text at the selection, for the toolbar: null where it starts and ends in different sizes. */
770
+ /** The size of the text at the selection, for the toolbar: null where the text selected is in more than one. */
740
771
  function sizeAtSelection(): number | null {
741
772
  if (pendingSize !== null) return pendingSize;
742
773
  const selection = window.getSelection();
@@ -754,7 +785,137 @@
754
785
  const first = start ? shownSize(start) : null;
755
786
  if (range.collapsed) return first;
756
787
  const end = holder(range.endContainer, range.endOffset, true);
757
- return end && shownSize(end) === first ? first : null;
788
+ if (!end || shownSize(end) !== first) return null;
789
+ // The same at both ends, and another in between: the list shows none, as for two.
790
+ return throughout(range, (el) => shownSize(el) ?? 0) === null ? null : first;
791
+ }
792
+
793
+ // ── Font ──
794
+ // The browser's own command does all of it: it writes <font face="…"> around the selected
795
+ // text, cuts a font that is there already in two rather than putting one inside another,
796
+ // and keeps the font for what is typed next at a caret. So a change of font is undone and
797
+ // redone with everything else. Which fonts there may be is the application's to say
798
+ // (`fonts`): the sanitizer takes any other off what comes in.
799
+
800
+ /** The font chosen at a caret and not yet typed in: the document has no element to show it by. */
801
+ let pendingFont: string | null = null;
802
+
803
+ /**
804
+ * Set the font of the selected text; with nothing selected, of what is typed next. The name
805
+ * is one of `fonts`; '' or the document font's own name sets the text back to the document
806
+ * font. A font that is not offered is not set. Also what the toolbar's font list calls.
807
+ */
808
+ export function setFont(name: string | null): void {
809
+ if (readonly || !editorEl) return;
810
+ const key = fontKey(name);
811
+ const choice = fontList.find((font) => font.key === key);
812
+ if (key !== '' && key !== documentFontKey && !choice) return;
813
+ restoreSelection();
814
+ editorEl.focus();
815
+ const selection = window.getSelection();
816
+ if (!selection || selection.rangeCount === 0 || !selectionInEditor()) return;
817
+ const wanted = choice?.key ?? '';
818
+ // Nothing to change: no step is made that would undo to the same thing.
819
+ if (fontAtSelection() === wanted) {
820
+ updateToolbarState();
821
+ return;
822
+ }
823
+ // (Given the document font as the screen has it, Chromium and Safari take the font off
824
+ // the text; Firefox writes it, which the writer and the font list read as no font.)
825
+ document.execCommand('fontName', false, choice ? choice.css : screenFontFamily);
826
+ // With text selected the font is on it now. At a caret it waits for the typing.
827
+ pendingFont = selection.isCollapsed ? wanted : null;
828
+ updateToolbarState();
829
+ }
830
+
831
+ /** The font an element's text is in, by its key: '' for the document font, or a font that is not offered. */
832
+ function fontOfElement(el: Element | null): string {
833
+ for (let at = el; at && at !== editorEl; at = at.parentElement) {
834
+ const key = fontKey((at as HTMLElement).style?.fontFamily || (at.tagName === 'FONT' ? at.getAttribute('face') : ''));
835
+ if (key) return fontList.some((font) => font.key === key) ? key : '';
836
+ }
837
+ return '';
838
+ }
839
+
840
+ /** The font of the text at the selection, for the toolbar: null where the text selected is in more than one. */
841
+ function fontAtSelection(): string | null {
842
+ if (pendingFont !== null) return pendingFont;
843
+ const selection = window.getSelection();
844
+ if (!editorEl || !selection || selection.rangeCount === 0) return '';
845
+ const range = selection.getRangeAt(0);
846
+ if (!editorEl.contains(range.startContainer)) return '';
847
+ if (range.collapsed) {
848
+ const at = range.startContainer;
849
+ return fontOfElement(at.nodeType === Node.ELEMENT_NODE ? (at as Element) : at.parentElement);
850
+ }
851
+ const font = throughout(range, fontOfElement);
852
+ return font === undefined ? '' : font;
853
+ }
854
+
855
+ /** Lists, tables and the document itself: white space between their parts is not text one sees. */
856
+ const HOLDS_BLOCKS = new Set(['UL', 'OL', 'TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TR']);
857
+
858
+ /**
859
+ * What all the text selected has in common, as `of` reads it from the element a text is in:
860
+ * its font, its size. null where two texts differ, so that the toolbar's list shows none
861
+ * rather than the one the selection happens to start in. undefined where no text is selected.
862
+ *
863
+ * From the first text selected to the last: a selection often starts at the end of the text
864
+ * before it (Safari leaves it there after the command), which is in another font.
865
+ */
866
+ function throughout<T>(range: Range, of: (el: Element) => T): T | null | undefined {
867
+ const first = textAtEdge(range, false);
868
+ const last = textAtEdge(range, true);
869
+ if (!editorEl || !first || !last) return undefined;
870
+ if (first !== last && !(first.compareDocumentPosition(last) & Node.DOCUMENT_POSITION_FOLLOWING)) return undefined;
871
+ const walker = document.createTreeWalker(editorEl, NodeFilter.SHOW_TEXT);
872
+ walker.currentNode = first;
873
+ let seen: Element | null = null;
874
+ let value: T | undefined;
875
+ for (let text: Text | null = first; text; text = walker.nextNode() as Text | null) {
876
+ const parent = text.parentElement;
877
+ const unseen = (parent === editorEl || HOLDS_BLOCKS.has(parent?.tagName ?? '')) && text.data.trim() === '';
878
+ if (parent && parent !== seen && text.data !== '' && !unseen) {
879
+ const here = of(parent);
880
+ if (seen && here !== value) return null;
881
+ value = here;
882
+ seen = parent;
883
+ }
884
+ if (text === last) break;
885
+ }
886
+ return value;
887
+ }
888
+
889
+ /** The first text a range has a character of, or the last. */
890
+ function textAtEdge(range: Range, last: boolean): Text | null {
891
+ if (!editorEl) return null;
892
+ const walker = document.createTreeWalker(editorEl, NodeFilter.SHOW_TEXT);
893
+ const node = last ? range.endContainer : range.startContainer;
894
+ const offset = last ? range.endOffset : range.startOffset;
895
+ const step = () => (last ? walker.previousNode() : walker.nextNode()) as Text | null;
896
+ let text: Text | null;
897
+ if (node.nodeType === Node.TEXT_NODE) {
898
+ walker.currentNode = node;
899
+ const inside = last ? offset > 0 : offset < (node as Text).data.length;
900
+ text = inside ? (node as Text) : step();
901
+ } else {
902
+ // From the point between two children: into the child on the range's side of it, or
903
+ // on from the element where it has none there.
904
+ const child = node.childNodes[last ? offset - 1 : offset];
905
+ if (child) {
906
+ let edge: Node = child;
907
+ if (last) while (edge.lastChild) edge = edge.lastChild;
908
+ walker.currentNode = edge;
909
+ text = edge.nodeType === Node.TEXT_NODE ? (edge as Text) : step();
910
+ } else {
911
+ let edge: Node = node;
912
+ if (!last) while (edge.lastChild) edge = edge.lastChild;
913
+ walker.currentNode = edge;
914
+ text = step();
915
+ }
916
+ }
917
+ while (text && text.data === '') text = step();
918
+ return text && range.intersectsNode(text) ? text : null;
758
919
  }
759
920
 
760
921
  /** The sizes the list offers: those asked for, and always the body size. */
@@ -934,6 +1095,7 @@
934
1095
  if (sel.isCollapsed) {
935
1096
  // At a caret there is nothing to clear but what was chosen for the words typed next.
936
1097
  pendingSize = null;
1098
+ pendingFont = null;
937
1099
  document.execCommand('removeFormat');
938
1100
  updateToolbarState();
939
1101
  return;
@@ -1653,6 +1815,7 @@
1653
1815
  // temporarily moved to a toolbar element (e.g. colour picker, select).
1654
1816
  saveSelection();
1655
1817
  currentFontSize = sizeAtSelection();
1818
+ currentFont = fontList.length > 0 ? fontAtSelection() : '';
1656
1819
 
1657
1820
  formatState = {
1658
1821
  bold: document.queryCommandState('bold'),
@@ -1674,11 +1837,48 @@
1674
1837
  */
1675
1838
  function caretMoved(): void {
1676
1839
  pendingSize = null;
1840
+ pendingFont = null;
1677
1841
  updateToolbarState();
1842
+ keepCaretInSight();
1843
+ }
1844
+
1845
+ let headEl: HTMLDivElement | undefined = $state();
1846
+
1847
+ /**
1848
+ * The browser scrolls a caret into the window, and knows nothing of the toolbar that stays
1849
+ * at the top of it: a caret moved up with the keys ends under the toolbar. The page is
1850
+ * scrolled by what the toolbar covers of the caret's line.
1851
+ */
1852
+ function keepCaretInSight(): void {
1853
+ if (!stickyToolbar || !headEl || !editorEl) return;
1854
+ const selection = window.getSelection();
1855
+ if (!selection || selection.rangeCount === 0 || !selectionInEditor()) return;
1856
+ const focus = document.createRange();
1857
+ try {
1858
+ focus.setStart(selection.focusNode!, selection.focusOffset);
1859
+ } catch {
1860
+ return;
1861
+ }
1862
+ const caret = focus.getClientRects()[0];
1863
+ if (!caret) return;
1864
+ const head = headEl.getBoundingClientRect();
1865
+ // Only where the toolbar is over the document, which it is not until the page is scrolled.
1866
+ if (head.bottom <= editorEl.getBoundingClientRect().top) return;
1867
+ const covered = head.bottom + 8 - caret.top;
1868
+ if (covered <= 0 || caret.bottom < head.top) return;
1869
+ for (let at: HTMLElement | null = editorEl.parentElement; at; at = at.parentElement) {
1870
+ const overflow = getComputedStyle(at).overflowY;
1871
+ if ((overflow === 'auto' || overflow === 'scroll') && at.scrollHeight > at.clientHeight) {
1872
+ at.scrollTop -= covered;
1873
+ return;
1874
+ }
1875
+ }
1876
+ window.scrollBy(0, -covered);
1678
1877
  }
1679
1878
 
1680
1879
  /** The editing area was scrolled sideways (a wide table): what is drawn over it moves with it. */
1681
1880
  function contentScrolled(): void {
1881
+ hideLinkHint();
1682
1882
  overlayRef?.reposition();
1683
1883
  placeCopySourceBox();
1684
1884
  }
@@ -1700,7 +1900,7 @@
1700
1900
  // every keystroke: with a few pictures in the document it took a tenth of a second. Each is
1701
1901
  // worked out when the handler asks for it, once, and not at all if it never does.
1702
1902
  const el = editorEl;
1703
- const options = { fontFamily, fontSize };
1903
+ const options = { fontFamily, fontSize, fonts };
1704
1904
  const once = <T,>(read: () => T): (() => T) => {
1705
1905
  let value: { v: T } | null = null;
1706
1906
  return () => (value ??= { v: read() }).v;
@@ -1807,6 +2007,7 @@
1807
2007
  applyPendingSize();
1808
2008
  }
1809
2009
  pendingSize = null;
2010
+ pendingFont = null;
1810
2011
  updateToolbarState();
1811
2012
  // Typing means the user is editing text, not the picture. Dropping the
1812
2013
  // selection here keeps Backspace editing that text instead of deleting a
@@ -2115,12 +2316,101 @@
2115
2316
  }
2116
2317
 
2117
2318
  // ── Image selection / editing ──
2319
+ // ── Opening a link ──
2320
+ // A click in text one can edit puts the caret there, in a link as anywhere else, so that the
2321
+ // link's words can be changed: the browser follows no link in it. As in Word, a click with
2322
+ // Ctrl (Cmd on a Mac) opens the link, in a new tab, and a note at the link under the pointer
2323
+ // says so. The note is the editor's own and no part of the document.
2324
+
2325
+ const ON_MAC = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent);
2326
+ const OPEN_HINT = ON_MAC ? '\u2318 Command-click to open link' : 'Ctrl+click to open link';
2327
+ /** Room kept for the note beside the link, so that it is not cut off at the right. */
2328
+ const HINT_WIDTH = 320;
2329
+
2330
+ let linkHint: { top: number; left: number; above: boolean; href: string } | null = $state(null);
2331
+ /**
2332
+ * Ctrl or Cmd is down: the link under the pointer shows the hand it will be opened with.
2333
+ * (Only with the pointer at a link: the keys are down for every shortcut, and the document's
2334
+ * element is not to change its class with each.)
2335
+ */
2336
+ let linkArmed = $state(false);
2337
+ let hintedLink: Element | null = null;
2338
+
2339
+ /** The link an event is at, where it has an address a link may have. */
2340
+ function linkAt(e: Event): Element | null {
2341
+ const link = e.target instanceof Element ? e.target.closest('a[href]') : null;
2342
+ return link && editorEl?.contains(link) && linkTarget(link.getAttribute('href') ?? '') !== null ? link : null;
2343
+ }
2344
+
2345
+ function hideLinkHint(): void {
2346
+ hintedLink = null;
2347
+ linkHint = null;
2348
+ }
2349
+
2350
+ function linkHovered(e: MouseEvent): void {
2351
+ linkArmed = !readonly && (e.metaKey || e.ctrlKey);
2352
+ // (Not with a button down: the pointer is selecting text, and the note would be in its way.)
2353
+ if (readonly || copyFormat !== 'off' || e.buttons !== 0 || !contentWrapEl) return;
2354
+ const link = linkAt(e);
2355
+ if (!link || link === hintedLink) return;
2356
+ hintedLink = link;
2357
+ const wrap = contentWrapEl.getBoundingClientRect();
2358
+ // The line of the link the pointer is on: a link may run over two.
2359
+ const line = Array.from(link.getClientRects()).find((r) => e.clientY >= r.top && e.clientY <= r.bottom) ?? link.getBoundingClientRect();
2360
+ // Below the line, or above it where there is no room left in the window.
2361
+ const above = line.bottom + 64 > window.innerHeight;
2362
+ linkHint = {
2363
+ top: (above ? line.top - 6 : line.bottom + 6) - wrap.top,
2364
+ left: Math.max(0, Math.min(line.left - wrap.left, wrap.width - HINT_WIDTH)),
2365
+ above,
2366
+ href: link.getAttribute('href') ?? ''
2367
+ };
2368
+ }
2369
+
2370
+ function linkLeft(e: MouseEvent): void {
2371
+ if (!hintedLink) return;
2372
+ const to = e.relatedTarget;
2373
+ if (!(to instanceof Node) || !hintedLink.contains(to)) hideLinkHint();
2374
+ }
2375
+
2376
+ /** Open a link in a tab of its own, which is not handed this page. */
2377
+ function openLink(address: string): void {
2378
+ const target = linkTarget(address);
2379
+ if (target === null) return;
2380
+ const link = document.createElement('a');
2381
+ link.href = target;
2382
+ link.target = '_blank';
2383
+ link.rel = 'noopener noreferrer';
2384
+ link.click();
2385
+ }
2386
+
2387
+ /**
2388
+ * A click on a link: with Ctrl or Cmd it is opened. Where the document cannot be edited a
2389
+ * plain click opens it, as in the viewer, and in a new tab too: the browser would open it
2390
+ * in this one, in place of the application. True where the click was the link's.
2391
+ */
2392
+ function followLink(e: MouseEvent): boolean {
2393
+ const modified = e.metaKey || e.ctrlKey;
2394
+ // (Read only, a click with a key down is the browser's own: a new tab, a new window.)
2395
+ if (readonly ? modified || e.shiftKey || e.altKey : !modified) return false;
2396
+ const link = e.target instanceof Element ? e.target.closest('a[href]') : null;
2397
+ if (!link || !editorEl?.contains(link)) return false;
2398
+ e.preventDefault();
2399
+ hideLinkHint();
2400
+ openLink(link.getAttribute('href') ?? '');
2401
+ return true;
2402
+ }
2403
+
2118
2404
  function handleContentClick(e: MouseEvent): void {
2119
- if (readonly) return;
2405
+ if (readonly) {
2406
+ followLink(e);
2407
+ return;
2408
+ }
2120
2409
  if (copyFormat !== 'off') {
2121
2410
  handleCopyFormatClick(e);
2122
2411
  return;
2123
2412
  }
2413
+ if (followLink(e)) return;
2124
2414
  const target = e.target as HTMLElement | null;
2125
2415
  selectedImage = target?.tagName === 'IMG' ? (target as HTMLImageElement) : null;
2126
2416
  }
@@ -2179,9 +2469,19 @@
2179
2469
  // that sends what is typed in it somewhere else, a frame showing another site.)
2180
2470
  expectInsertion(draggedFromHere);
2181
2471
  // What the browser may lose of it, as of a paste: it begins where it is dropped.
2182
- const notes = pasteNotes(e.dataTransfer?.getData?.('text/html') ?? '');
2472
+ const dropped = e.dataTransfer?.getData?.('text/html') ?? '';
2473
+ pastedPictures = pastePictures(dropped, e.dataTransfer?.getData?.('text/rtf') ?? '');
2474
+ const notes = pasteNotes(dropped);
2183
2475
  const at = notes ? rangeAtPoint(e.clientX, e.clientY) : null;
2184
2476
  pastedLoss = notes && at && editorEl?.contains(at.startContainer) ? { notes, from: shownCharsBefore(at.startContainer, at.startOffset), dropped: true } : null;
2477
+ // What holds a frame is put in here, made safe and without it (see pasteWithoutFrames).
2478
+ const unframed = pasteWithoutFrames(dropped, keptNames);
2479
+ if (unframed !== null) {
2480
+ e.preventDefault();
2481
+ editorEl?.focus();
2482
+ placeCaretAtPoint(e.clientX, e.clientY);
2483
+ document.execCommand('insertHTML', false, unframed);
2484
+ }
2185
2485
  return;
2186
2486
  }
2187
2487
  e.preventDefault();
@@ -2231,7 +2531,7 @@
2231
2531
  importing = true;
2232
2532
 
2233
2533
  try {
2234
- const html = await readRtfFile(file, { fontSize, maxBytes: maxRtfBytes });
2534
+ const html = await readRtfFile(file, { fontSize, fontFamily, fonts, maxBytes: maxRtfBytes });
2235
2535
  if (editorEl) {
2236
2536
  selectedImage = null;
2237
2537
  documentReplaced();
@@ -2464,6 +2764,14 @@
2464
2764
  notes && start && editorEl.contains(start.startContainer)
2465
2765
  ? { notes, from: shownCharsBefore(start.startContainer, start.startOffset) }
2466
2766
  : null;
2767
+ // The pictures Word's HTML only names, from its RTF (see pastePictures).
2768
+ pastedPictures = pastePictures(html, e.clipboardData?.getData('text/rtf') ?? '');
2769
+ // What holds a frame is put in here, made safe and without it (see pasteWithoutFrames).
2770
+ const unframed = pasteWithoutFrames(html, keptNames);
2771
+ if (unframed !== null) {
2772
+ e.preventDefault();
2773
+ document.execCommand('insertHTML', false, unframed);
2774
+ }
2467
2775
  }
2468
2776
  }
2469
2777
 
@@ -2478,6 +2786,8 @@
2478
2786
  pastedOver = snapshot;
2479
2787
  pastedOwn = own;
2480
2788
  pastedLoss = null;
2789
+ pastedPictures = null;
2790
+ commentsBefore = new Set(commentsIn(editorEl));
2481
2791
  // A paste that inserts nothing (an empty clipboard, a host that cancels it) raises no
2482
2792
  // input event. Left set, the snapshot would make the next keystroke treat the whole
2483
2793
  // document as pasted.
@@ -2485,6 +2795,8 @@
2485
2795
  if (pastedOver === snapshot) {
2486
2796
  pastedOver = null;
2487
2797
  pastedLoss = null;
2798
+ pastedPictures = null;
2799
+ commentsBefore = null;
2488
2800
  }
2489
2801
  }, 0);
2490
2802
  }
@@ -2516,9 +2828,19 @@
2516
2828
  if (!sel || sel.rangeCount === 0 || !editorEl.contains(sel.anchorNode) || !editorEl.contains(sel.focusNode)) return;
2517
2829
  if (!sel.isCollapsed && !loss.dropped) return;
2518
2830
  const range = sel.getRangeAt(0);
2519
- const from = sel.isCollapsed ? loss.from : shownCharsBefore(range.startContainer, range.startOffset);
2520
- const to = shownCharsBefore(range.endContainer, range.endOffset);
2831
+ let from = sel.isCollapsed ? loss.from : shownCharsBefore(range.startContainer, range.startOffset);
2832
+ let to = shownCharsBefore(range.endContainer, range.endOffset);
2521
2833
  const came = new Set(Array.from(editorEl.querySelectorAll('*')).filter((el) => !before.has(el)));
2834
+ // Firefox leaves the caret before a whole page it has pasted (a copy made in Word, with
2835
+ // its <head>), not after it. The paste is then the elements that came in, from the
2836
+ // first to the end of the last. (Text that is not the paste's own, to the character,
2837
+ // is left alone as ever: see removeWordHidden.)
2838
+ if (sel.isCollapsed && to <= from && came.size > 0) {
2839
+ const outer = Array.from(came).filter((el) => el.parentElement && !came.has(el.parentElement));
2840
+ const index = (el: Element) => Array.prototype.indexOf.call(el.parentNode!.childNodes, el);
2841
+ from = Math.min(...outer.map((el) => shownCharsBefore(el.parentNode!, index(el))));
2842
+ to = Math.max(...outer.map((el) => shownCharsBefore(el.parentNode!, index(el) + 1)));
2843
+ }
2522
2844
  if (takeHidden(from, to, loss.notes, (el) => came.has(el))) {
2523
2845
  hiddenTaken.push({ notes: loss.notes, from, came, emptied: Array.from(came).filter((el) => !el.isConnected) });
2524
2846
  }
@@ -2529,6 +2851,9 @@
2529
2851
  * character shown, or with null for `to`, the paste Redo has put back from the `from`th on
2530
2852
  * (see removeWordHidden). Returns whether anything was taken out.
2531
2853
  */
2854
+ /** Word's mark on text it hides, as a paste carries it in a style. */
2855
+ const WORD_HIDES = /mso-hide\s*:\s*all/i;
2856
+
2532
2857
  function takeHidden(from: number, to: number | null, notes: PasteNotes, came: (el: Element) => boolean): boolean {
2533
2858
  if (!editorEl) return false;
2534
2859
  // A pasted element left with nothing in it goes, but not the one the caret is in: that
@@ -2536,7 +2861,34 @@
2536
2861
  // alone left the caret in no line at all, and the next words typed were in none.)
2537
2862
  const sel = window.getSelection();
2538
2863
  const at = sel && sel.rangeCount > 0 && editorEl.contains(sel.anchorNode) ? sel.anchorNode : null;
2539
- const held = at instanceof Element ? at : (at?.parentElement ?? null);
2864
+ let held = at instanceof Element ? at : (at?.parentElement ?? null);
2865
+ // Firefox pastes Word's hidden text as an element that is not displayed, and leaves the
2866
+ // caret inside it: what was typed next was typed where it is not seen, and what is not
2867
+ // seen is not written. The caret is put before a hidden piece of a line, which then
2868
+ // goes with its text; a hidden paragraph the caret is in becomes the empty line, shown.
2869
+ let unseen: HTMLElement | null = null;
2870
+ for (let el = held; el && el !== editorEl; el = el.parentElement) {
2871
+ // (Word's own mark is still on it as the style it came with: the browser knows no
2872
+ // such property, and what came in has not been made safe yet.)
2873
+ const hidden = el instanceof HTMLElement && (WORD_HIDES.test(el.getAttribute('style') ?? '') || el.style.display === 'none' || el.style.visibility === 'hidden' || el.hasAttribute('hidden'));
2874
+ if (hidden && came(el)) unseen = el as HTMLElement;
2875
+ }
2876
+ if (unseen && sel) {
2877
+ if (/^(P|DIV|LI|H[1-6]|BLOCKQUOTE|PRE|TD|TH)$/.test(unseen.tagName)) {
2878
+ unseen.setAttribute('style', (unseen.getAttribute('style') ?? '').replace(new RegExp(`${WORD_HIDES.source}\\s*;?`, 'gi'), ''));
2879
+ unseen.style.removeProperty('display');
2880
+ unseen.style.removeProperty('visibility');
2881
+ unseen.removeAttribute('hidden');
2882
+ if (!unseen.getAttribute('style')?.trim()) unseen.removeAttribute('style');
2883
+ } else {
2884
+ const before = document.createRange();
2885
+ before.setStartBefore(unseen);
2886
+ before.collapse(true);
2887
+ sel.removeAllRanges();
2888
+ sel.addRange(before);
2889
+ held = unseen.parentElement;
2890
+ }
2891
+ }
2540
2892
  if (!removeWordHidden(editorEl, from, to, notes, (el) => came(el) && !(held !== null && el.contains(held)))) return false;
2541
2893
  if (held && held !== editorEl && held.isConnected && held.childNodes.length === 0) held.appendChild(document.createElement('br'));
2542
2894
  return true;
@@ -2566,6 +2918,26 @@
2566
2918
  const broughtIn = new Map<Element, { style: string | null; own: boolean }>();
2567
2919
  /** What the paste or the drop under way may lose, and how much text the document had before it. */
2568
2920
  let pastedLoss: { notes: PasteNotes; from: number; dropped?: boolean } | null = null;
2921
+ /** The pictures of the paste that is coming in, where its HTML only names them (see pastePictures). */
2922
+ let pastedPictures: PastePictures | null = null;
2923
+
2924
+ // ── Comments that come in ──
2925
+ // HTML copied in another program may hold comments. What is in one is not shown and not
2926
+ // written to the RTF, but it is kept in the HTML that is saved, and Word writes in one the
2927
+ // address of each copied picture: a file on the writer's own disk, with the name of the
2928
+ // writer's account in it. A browser leaves comments out of a paste; Firefox keeps those of
2929
+ // markup that is dropped. So a comment that comes in is emptied. It is not taken out: Firefox
2930
+ // cannot undo a drop from which a node is gone, and an empty comment says nothing. Those the
2931
+ // application's own HTML has are not the editor's to judge, and stay as they are.
2932
+ /** The comments in the document just before a paste or a drop; what is not among them came with it. */
2933
+ let commentsBefore: Set<Comment> | null = null;
2934
+
2935
+ function commentsIn(root: Node): Comment[] {
2936
+ const found: Comment[] = [];
2937
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_COMMENT);
2938
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) found.push(node as Comment);
2939
+ return found;
2940
+ }
2569
2941
 
2570
2942
  /**
2571
2943
  * Take off the elements `came` accepts, the ones a paste or a drop brought in, their id and
@@ -2607,8 +2979,30 @@
2607
2979
 
2608
2980
  function tidyPasted(before: Set<Element>): void {
2609
2981
  if (!editorEl) return;
2982
+ // Firefox pastes the <style> of a copied page into the document with its words. It is
2983
+ // taken out below with all that is not safe; here first, because its rules count as text
2984
+ // of the paste, and Word's hidden words are found by the paste's text, to the character:
2985
+ // with a style sheet among them they were not found, and stayed in the document, unseen.
2986
+ for (const el of Array.from(editorEl.querySelectorAll('style, script, template, title'))) {
2987
+ if (!before.has(el)) el.remove();
2988
+ }
2989
+ if (commentsBefore) {
2990
+ for (const comment of commentsIn(editorEl)) {
2991
+ if (!commentsBefore.has(comment) && comment.data !== '') comment.data = '';
2992
+ }
2993
+ }
2994
+ commentsBefore = null;
2610
2995
  if (pastedLoss) restorePasteLoss(before, pastedLoss);
2611
2996
  pastedLoss = null;
2997
+ // Before what came in is made safe: an image that names a file on a disk loses that
2998
+ // address there, and is then an image of nothing.
2999
+ if (pastedPictures) {
3000
+ givePastedPictures(
3001
+ Array.from(editorEl.querySelectorAll('img')).filter((img) => !before.has(img)),
3002
+ pastedPictures
3003
+ );
3004
+ }
3005
+ pastedPictures = null;
2612
3006
  // What the paste brought is made safe as HTML from anywhere else is: a browser takes the
2613
3007
  // scripts out of a paste itself, but leaves a form, an <iframe>, or a block with
2614
3008
  // position: fixed that covers the page.
@@ -2963,8 +3357,19 @@
2963
3357
  <svelte:window
2964
3358
  onkeydown={(e) => {
2965
3359
  if (copyFormat !== 'off' && e.key === 'Escape') stopCopyFormat();
3360
+ linkArmed = !readonly && (e.metaKey || e.ctrlKey);
3361
+ // Typing: the note at a link is in the way of the words.
3362
+ if (linkHint && e.key !== 'Meta' && e.key !== 'Control') hideLinkHint();
3363
+ }}
3364
+ onkeyup={(e) => (linkArmed = !readonly && (e.metaKey || e.ctrlKey))}
3365
+ onblur={() => {
3366
+ linkArmed = false;
3367
+ hideLinkHint();
3368
+ }}
3369
+ onresize={() => {
3370
+ placeCopySourceBox();
3371
+ hideLinkHint();
2966
3372
  }}
2967
- onresize={placeCopySourceBox}
2968
3373
  />
2969
3374
 
2970
3375
  <div
@@ -2973,43 +3378,54 @@
2973
3378
  style:--ink-font-family={screenFontFamily}
2974
3379
  style:--ink-font-size="{screenFontSize}pt"
2975
3380
  >
2976
- {#if showToolbar && !readonly}
2977
- <Toolbar
2978
- {formatState}
2979
- blockType={currentBlock}
2980
- onexec={exec}
2981
- onblock={setBlock}
2982
- oninsertlink={openLinkModal}
2983
- oninsertimage={openImageModal}
2984
- fontSize={currentFontSize}
2985
- fontSizes={sizeChoices}
2986
- onfontsize={setFontSize}
2987
- copyingFormat={copyFormat !== 'off'}
2988
- oncopyformat={toggleCopyFormat}
2989
- />
2990
- {/if}
3381
+ {#if !readonly && (showToolbar || copyFormat !== 'off')}
3382
+ <div class="ink-head" class:sticky={stickyToolbar} bind:this={headEl}>
3383
+ {#if showToolbar}
3384
+ <Toolbar
3385
+ {formatState}
3386
+ blockType={currentBlock}
3387
+ onexec={exec}
3388
+ onblock={setBlock}
3389
+ oninsertlink={openLinkModal}
3390
+ oninsertimage={openImageModal}
3391
+ fontSize={currentFontSize}
3392
+ fontSizes={sizeChoices}
3393
+ onfontsize={setFontSize}
3394
+ font={currentFont}
3395
+ fonts={fontList}
3396
+ documentFont={fontChoices([fontFamily])[0]?.name ?? DEFAULT_FONT_FAMILY}
3397
+ onfont={setFont}
3398
+ copyingFormat={copyFormat !== 'off'}
3399
+ oncopyformat={toggleCopyFormat}
3400
+ />
3401
+ {/if}
2991
3402
 
2992
- {#if copyFormat !== 'off' && !readonly}
2993
- <div class="ink-copy-format" role="status">
2994
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="14" height="6" rx="1.5"/><path d="M17 6h3v5h-9v3"/><rect x="9.5" y="14" width="3" height="7" rx="1"/></svg>
2995
- <span>
2996
- {copyFormat === 'pick'
2997
- ? 'Copy format: click the paragraph to copy from.'
2998
- : 'Format copied. Click each paragraph that should get it.'}
2999
- </span>
3000
- <button type="button" class="ink-copy-format-done" onmousedown={(e) => e.preventDefault()} onclick={stopCopyFormat}>
3001
- {copyFormat === 'pick' ? 'Cancel' : 'Done'}
3002
- </button>
3003
- <span class="ink-copy-format-key">or press Esc</span>
3403
+ {#if copyFormat !== 'off'}
3404
+ <div class="ink-copy-format" role="status">
3405
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="14" height="6" rx="1.5"/><path d="M17 6h3v5h-9v3"/><rect x="9.5" y="14" width="3" height="7" rx="1"/></svg>
3406
+ <span>
3407
+ {copyFormat === 'pick'
3408
+ ? 'Copy format: click the paragraph to copy from.'
3409
+ : 'Format copied. Click each paragraph that should get it.'}
3410
+ </span>
3411
+ <button type="button" class="ink-copy-format-done" onmousedown={(e) => e.preventDefault()} onclick={stopCopyFormat}>
3412
+ {copyFormat === 'pick' ? 'Cancel' : 'Done'}
3413
+ </button>
3414
+ <span class="ink-copy-format-key">or press Esc</span>
3415
+ </div>
3416
+ {/if}
3004
3417
  </div>
3005
3418
  {/if}
3006
3419
 
3007
3420
  <div class="ink-content-wrap" bind:this={contentWrapEl}>
3008
- <!-- svelte-ignore a11y_no_static_element_interactions -->
3421
+ <!-- (The pointer over a link shows a note of how the pointer opens it: there is nothing
3422
+ in it for the keyboard, which opens a link from the browser's own menu.) -->
3423
+ <!-- svelte-ignore a11y_no_static_element_interactions, a11y_mouse_events_have_key_events -->
3009
3424
  <div
3010
3425
  class="ink-content"
3011
3426
  class:copy-format-pick={copyFormat === 'pick'}
3012
3427
  class:copy-format-apply={copyFormat === 'apply'}
3428
+ class:links-open={linkArmed && linkHint !== null}
3013
3429
  contenteditable={!readonly}
3014
3430
  role="textbox"
3015
3431
  tabindex="0"
@@ -3023,7 +3439,12 @@
3023
3439
  onkeyup={caretMoved}
3024
3440
  onscroll={contentScrolled}
3025
3441
  onkeydown={handleKeydown}
3026
- onmousedown={() => (tabLeavesEditor = false)}
3442
+ onmousedown={() => {
3443
+ tabLeavesEditor = false;
3444
+ hideLinkHint();
3445
+ }}
3446
+ onmouseover={linkHovered}
3447
+ onmouseout={linkLeft}
3027
3448
  onblur={() => (tabLeavesEditor = false)}
3028
3449
  onpaste={handlePaste}
3029
3450
  onclick={handleContentClick}
@@ -3044,6 +3465,19 @@
3044
3465
  ></div>
3045
3466
  {/if}
3046
3467
 
3468
+ {#if linkHint && !readonly}
3469
+ <div
3470
+ class="ink-link-hint"
3471
+ class:above={linkHint.above}
3472
+ role="tooltip"
3473
+ style:top="{linkHint.top}px"
3474
+ style:left="{linkHint.left}px"
3475
+ >
3476
+ <span class="ink-link-hint-address">{linkHint.href}</span>
3477
+ <span class="ink-link-hint-how">{OPEN_HINT}</span>
3478
+ </div>
3479
+ {/if}
3480
+
3047
3481
  {#if !readonly}
3048
3482
  <ImageOverlay
3049
3483
  bind:this={overlayRef}
@@ -3156,6 +3590,22 @@
3156
3590
  width: 100%;
3157
3591
  }
3158
3592
 
3593
+ /* The toolbar, and under it the note of a format being copied. It stays in sight while a
3594
+ long document is scrolled, at the top of the window or of the scrolling element the
3595
+ editor is in: under a header of the page's own, --ink-toolbar-top is that header's
3596
+ height. Its ground is the toolbar's, so that no words show between its parts. */
3597
+ .ink-head {
3598
+ margin: 24px 0 16px;
3599
+ border-radius: var(--radius, 8px);
3600
+ background: var(--bg-toolbar, #fff);
3601
+ }
3602
+
3603
+ .ink-head.sticky {
3604
+ position: sticky;
3605
+ top: var(--ink-toolbar-top, 0px);
3606
+ z-index: 30;
3607
+ }
3608
+
3159
3609
  /* Anchors the image selection frame, which lives outside the
3160
3610
  contenteditable area so it never lands in the exported HTML. */
3161
3611
  .ink-content-wrap {
@@ -3214,7 +3664,7 @@
3214
3664
  display: flex;
3215
3665
  align-items: center;
3216
3666
  gap: 10px;
3217
- margin: -8px 0 12px;
3667
+ margin: 8px 0 0;
3218
3668
  padding: 8px 12px;
3219
3669
  border: 1px solid var(--accent, #6e56cf);
3220
3670
  border-radius: var(--radius-sm, 5px);
@@ -3259,6 +3709,64 @@
3259
3709
  pointer-events: none;
3260
3710
  }
3261
3711
 
3712
+ /* The note at a link under the pointer: where it goes, and how to open it. */
3713
+ .ink-link-hint {
3714
+ position: absolute;
3715
+ z-index: 5;
3716
+ box-sizing: border-box;
3717
+ max-width: min(320px, 100%);
3718
+ display: flex;
3719
+ flex-direction: column;
3720
+ gap: 2px;
3721
+ padding: 6px 10px;
3722
+ border-radius: 8px;
3723
+ background: var(--ink, #1a1714);
3724
+ color: #fff;
3725
+ font-family: 'DM Sans', system-ui, sans-serif;
3726
+ font-size: 12px;
3727
+ line-height: 1.35;
3728
+ box-shadow: 0 4px 14px rgba(0, 0, 0, 0.18);
3729
+ pointer-events: none;
3730
+ /* Not at once: the pointer crosses links on its way elsewhere. */
3731
+ animation: ink-link-hint-in 120ms ease 350ms both;
3732
+ }
3733
+
3734
+ .ink-link-hint.above {
3735
+ transform: translateY(-100%);
3736
+ }
3737
+
3738
+ .ink-link-hint-address {
3739
+ overflow: hidden;
3740
+ white-space: nowrap;
3741
+ text-overflow: ellipsis;
3742
+ opacity: 0.75;
3743
+ }
3744
+
3745
+ .ink-link-hint-how {
3746
+ font-weight: 600;
3747
+ white-space: nowrap;
3748
+ }
3749
+
3750
+ @keyframes ink-link-hint-in {
3751
+ from {
3752
+ opacity: 0;
3753
+ }
3754
+ to {
3755
+ opacity: 1;
3756
+ }
3757
+ }
3758
+
3759
+ @media (prefers-reduced-motion: reduce) {
3760
+ .ink-link-hint {
3761
+ animation-duration: 1ms;
3762
+ }
3763
+ }
3764
+
3765
+ /* Ctrl or Cmd is down: a click will open the link. */
3766
+ .ink-content.links-open :global(a[href]) {
3767
+ cursor: pointer;
3768
+ }
3769
+
3262
3770
  /* Placeholder */
3263
3771
  .ink-content:empty::before {
3264
3772
  content: attr(data-placeholder);