svelte-rtf-editor 1.5.2 → 1.6.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 CHANGED
@@ -163,7 +163,7 @@ editor.importRtf() // → void — open the file picker to import .rtf
163
163
  ```ts
164
164
  import {
165
165
  rtfToHtml, htmlToRtf, estimateRtfBytes, readRtfFile, htmlToMarkdown, downloadFile,
166
- DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE
166
+ DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE, isSafeLinkUrl
167
167
  } from 'svelte-rtf-editor';
168
168
  ```
169
169
 
@@ -172,6 +172,7 @@ import {
172
172
  | `rtfToHtml(rtf: string, options?: { fontSize? }): string` | Parse an RTF string and return an HTML string. `fontSize` is the size of the screen it will be shown on (default 12) |
173
173
  | `htmlToRtf(el: HTMLElement, options?: { fontFamily?, fontSize? }): string` | Convert a DOM element's content to RTF, in Arial 12 pt unless told otherwise |
174
174
  | `estimateRtfBytes(el: HTMLElement): number` | Approximate RTF size of a DOM element without converting it |
175
+ | `isSafeLinkUrl(url: string): boolean` | Whether a link address is a web, mail or phone address; `htmlToRtf` writes any other link as its text alone |
175
176
  | `readRtfFile(file: File): Promise<string>` | Read a `.rtf` File object and return HTML |
176
177
  | `htmlToMarkdown(el: HTMLElement): string` | Convert a DOM element's content to Markdown |
177
178
  | `downloadFile(name, content, mime): void` | Trigger a file download in the browser |
@@ -231,6 +232,12 @@ The components use CSS custom properties with sensible fallbacks, so they work o
231
232
  | `Ctrl+K` | Insert link |
232
233
  | `Ctrl+S` | Save (fires `onsave`) |
233
234
  | `Backspace` / `Delete` | Remove the selected image |
235
+ | `Tab` | Insert a tab (sent to RTF as `\tab`); two spaces in a code block |
236
+ | `Shift+Tab` | Remove one tab from the start of the line |
237
+ | `Esc`, then `Tab` / `Shift+Tab` | Move focus out of the editor |
238
+
239
+ Tab stays in the editor so a line can be indented. To leave the editor from the keyboard, press
240
+ `Esc` first. A readonly editor leaves Tab to the browser.
234
241
 
235
242
  ---
236
243
 
@@ -56,6 +56,7 @@
56
56
  import {
57
57
  htmlToRtf,
58
58
  estimateRtfBytes,
59
+ isSafeLinkUrl,
59
60
  cssFontFamily,
60
61
  normalizeFontSize,
61
62
  DEFAULT_FONT_FAMILY,
@@ -148,6 +149,7 @@
148
149
  let linkModalOpen: boolean = $state(false);
149
150
  let imageModalOpen: boolean = $state(false);
150
151
  let linkUrl: string = $state('');
152
+ let linkError: string = $state('');
151
153
  let linkText: string = $state('');
152
154
  let imageUrl: string = $state('');
153
155
  let imageAlt: string = $state('');
@@ -363,11 +365,20 @@
363
365
  saveSelection();
364
366
  linkUrl = '';
365
367
  linkText = '';
368
+ linkError = '';
366
369
  linkModalOpen = true;
367
370
  }
368
371
 
369
372
  function applyLink(): void {
370
373
  if (!linkUrl) { linkModalOpen = false; return; }
374
+ // Only a web, mail or phone address becomes a link; a javascript: address would
375
+ // run when clicked in the editor and in any viewer of the stored HTML. The dialog
376
+ // stays open and says why, rather than closing as if the link had been added.
377
+ if (!isSafeLinkUrl(linkUrl)) {
378
+ linkError = 'Enter a web address (https://…), an email address (mailto:…) or a phone number (tel:…).';
379
+ return;
380
+ }
381
+ linkError = '';
371
382
  restoreSelection();
372
383
  editorEl?.focus();
373
384
 
@@ -736,12 +747,123 @@
736
747
  return;
737
748
  }
738
749
 
739
- if (e.key === 'Tab') {
740
- const sel = window.getSelection();
741
- if (sel?.anchorNode?.parentElement?.closest?.('pre')) {
742
- e.preventDefault();
743
- document.execCommand('insertHTML', false, ' ');
750
+ if (e.key === 'Tab') handleTab(e);
751
+ else tabLeavesEditor = e.key === 'Escape';
752
+ }
753
+
754
+ // ── Tab ──
755
+ // Tab types a tab, as in a word processor, so a pathologist can indent a line; before this it
756
+ // left the editor for the next control on the page. Escape, then Tab or Shift+Tab, still moves
757
+ // focus on, so the keyboard is never trapped here. A readonly editor keeps the browser's Tab.
758
+ let tabLeavesEditor = false;
759
+
760
+ function handleTab(e: KeyboardEvent): void {
761
+ if (readonly || e.ctrlKey || e.metaKey || e.altKey) return;
762
+ if (tabLeavesEditor) {
763
+ tabLeavesEditor = false;
764
+ return;
765
+ }
766
+ const sel = window.getSelection();
767
+ if (!sel || !sel.anchorNode || !editorEl?.contains(sel.anchorNode)) return;
768
+ e.preventDefault();
769
+
770
+ if (sel.anchorNode.parentElement?.closest?.('pre')) {
771
+ if (!e.shiftKey) document.execCommand('insertText', false, ' ');
772
+ return;
773
+ }
774
+ if (!e.shiftKey) {
775
+ insertTab(sel);
776
+ return;
777
+ }
778
+ // Shift+Tab takes one tab off the start of the line the caret is on, wherever the caret is
779
+ // on it, as a word processor outdents.
780
+ if (sel.isCollapsed) removeLeadingTab(sel);
781
+ }
782
+
783
+ /**
784
+ * Type a tab, on the undo stack. Chromium and WebKit wrap it in <span style="white-space:pre">,
785
+ * which the RTF writer sends as \tab. Firefox types spaces instead, so there the typing is
786
+ * undone and the same span is inserted, with the caret put after it so the text that follows
787
+ * is not typed inside it.
788
+ */
789
+ function insertTab(sel: Selection): void {
790
+ document.execCommand('insertText', false, '\t');
791
+ if (textBeforeCaret(sel).endsWith('\t')) return;
792
+ document.execCommand('undo');
793
+ document.execCommand('insertHTML', false, '<span style="white-space:pre">\t</span>');
794
+ const node = sel.anchorNode;
795
+ const span = (node instanceof Element ? node : node?.parentElement)?.closest('span');
796
+ if (span && span.textContent === '\t' && editorEl?.contains(span)) {
797
+ const after = document.createRange();
798
+ after.setStartAfter(span);
799
+ after.collapse(true);
800
+ sel.removeAllRanges();
801
+ sel.addRange(after);
802
+ }
803
+ }
804
+
805
+ function textBeforeCaret(sel: Selection): string {
806
+ if (!editorEl || sel.rangeCount === 0) return '';
807
+ const range = sel.getRangeAt(0).cloneRange();
808
+ range.collapse(true);
809
+ range.setStart(editorEl, 0);
810
+ return range.toString();
811
+ }
812
+
813
+ const LINE_BLOCKS = 'p, div, li, td, th, h1, h2, h3, h4, h5, h6, blockquote';
814
+
815
+ /** The first tab of the caret's line, if the line starts with one: its text node and offset. */
816
+ function leadingTab(sel: Selection): { node: Text; offset: number } | null {
817
+ if (!editorEl || !sel.anchorNode) return null;
818
+ const anchorEl = sel.anchorNode instanceof Element ? sel.anchorNode : sel.anchorNode.parentElement;
819
+ const found = anchorEl?.closest(LINE_BLOCKS);
820
+ const block = found && editorEl.contains(found) && found !== editorEl ? found : editorEl;
821
+ const caret = sel.getRangeAt(0);
822
+
823
+ // Walk the block's text and line breaks up to the caret. A <br>, or text in a different
824
+ // block from the text before it, starts a new line.
825
+ const walker = document.createTreeWalker(block, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);
826
+ let lineStart: { node: Text; offset: number } | null = null;
827
+ let lineHasText = false;
828
+ let lastBlock: Element | null = null;
829
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) {
830
+ if (caret.comparePoint(n, 0) > 0) break;
831
+ if (n.nodeName === 'BR') {
832
+ lineStart = null;
833
+ lineHasText = false;
834
+ continue;
835
+ }
836
+ if (n.nodeType !== Node.TEXT_NODE) continue;
837
+ const textBlock = n.parentElement?.closest(LINE_BLOCKS) ?? block;
838
+ if (textBlock !== lastBlock) {
839
+ lastBlock = textBlock;
840
+ lineStart = null;
841
+ lineHasText = false;
744
842
  }
843
+ if (!lineHasText) {
844
+ const text = (n as Text).data;
845
+ if (text.length === 0) continue;
846
+ lineHasText = true;
847
+ lineStart = text[0] === '\t' ? { node: n as Text, offset: 0 } : null;
848
+ }
849
+ }
850
+ return lineStart;
851
+ }
852
+
853
+ function removeLeadingTab(sel: Selection): void {
854
+ const tab = leadingTab(sel);
855
+ if (!tab) return;
856
+ const caret = sel.getRangeAt(0).cloneRange();
857
+ const range = document.createRange();
858
+ range.setStart(tab.node, tab.offset);
859
+ range.setEnd(tab.node, tab.offset + 1);
860
+ // Delete through execCommand so Ctrl+Z puts the tab back, then return the caret.
861
+ sel.removeAllRanges();
862
+ sel.addRange(range);
863
+ document.execCommand('delete');
864
+ if (caret.startContainer.isConnected) {
865
+ sel.removeAllRanges();
866
+ sel.addRange(caret);
745
867
  }
746
868
  }
747
869
 
@@ -837,6 +959,8 @@
837
959
  onmouseup={updateToolbarState}
838
960
  onkeyup={updateToolbarState}
839
961
  onkeydown={handleKeydown}
962
+ onmousedown={() => (tabLeavesEditor = false)}
963
+ onblur={() => (tabLeavesEditor = false)}
840
964
  onpaste={handlePaste}
841
965
  onclick={handleContentClick}
842
966
  ondragover={handleDragOver}
@@ -875,7 +999,12 @@
875
999
  placeholder="https://example.com"
876
1000
  bind:value={linkUrl}
877
1001
  onkeydown={(e) => e.key === 'Enter' && applyLink()}
1002
+ aria-invalid={linkError ? 'true' : undefined}
1003
+ aria-describedby={linkError ? 'ink-link-error' : undefined}
878
1004
  />
1005
+ {#if linkError}
1006
+ <p class="ink-modal-error" id="ink-link-error" role="alert">{linkError}</p>
1007
+ {/if}
879
1008
  {#snippet actions()}
880
1009
  <button class="ink-btn-ghost" onclick={() => (linkModalOpen = false)}>Cancel</button>
881
1010
  <button class="ink-btn-primary" onclick={applyLink}>Insert</button>
@@ -1178,6 +1307,12 @@
1178
1307
  color: var(--text-muted, #8a7e72);
1179
1308
  }
1180
1309
 
1310
+ .ink-modal-error {
1311
+ margin: 0 0 12px;
1312
+ font-size: 12px;
1313
+ color: var(--danger, #b42318);
1314
+ }
1315
+
1181
1316
  .ink-modal-or {
1182
1317
  display: flex;
1183
1318
  align-items: center;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { default as RtfViewer } from './RtfViewer.svelte';
2
2
  export { default as InkEditor } from './components/InkEditor.svelte';
3
3
  export { rtfToHtml, readRtfFile } from './rtf-parser.js';
4
- export { htmlToRtf, estimateRtfBytes, DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE } from './rtf-writer.js';
4
+ export { htmlToRtf, estimateRtfBytes, isSafeLinkUrl, DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE } from './rtf-writer.js';
5
5
  export type { RtfWriteOptions } from './rtf-writer.js';
6
6
  export type { RtfReadOptions } from './rtf-parser.js';
7
7
  export { htmlToMarkdown, downloadFile } from './utils.js';
package/dist/index.js CHANGED
@@ -3,5 +3,5 @@ export { default as RtfViewer } from './RtfViewer.svelte';
3
3
  export { default as InkEditor } from './components/InkEditor.svelte';
4
4
  // RTF utilities
5
5
  export { rtfToHtml, readRtfFile } from './rtf-parser.js';
6
- export { htmlToRtf, estimateRtfBytes, DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE } from './rtf-writer.js';
6
+ export { htmlToRtf, estimateRtfBytes, isSafeLinkUrl, DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE } from './rtf-writer.js';
7
7
  export { htmlToMarkdown, downloadFile } from './utils.js';
@@ -47,6 +47,10 @@ const HEX_NIBBLE = (() => {
47
47
  }
48
48
  return table;
49
49
  })();
50
+ /** A tab as the editor's Tab key inserts it (Chromium's own shape for a typed tab). */
51
+ const TAB_HTML = '<span style="white-space:pre">\t</span>';
52
+ /** A paragraph so far holding only a list marker: a bullet, or a number and a period. */
53
+ const LIST_MARKER = /^(?:<[^>]+>)*\s*(?:\u2022|\d+\.)\s*(?:<\/[^>]+>)*$/;
50
54
  /** Hex picture data → base64, without depending on btoa/Buffer. */
51
55
  function hexToBase64(hex) {
52
56
  const byteCount = hex.length >> 1;
@@ -691,7 +695,11 @@ export function rtfToHtml(rtfString, options = {}) {
691
695
  paragraphHasText = true;
692
696
  break;
693
697
  case 'tab':
694
- currentParagraph += '&emsp;';
698
+ // A real tab, in the shape the editor's Tab key inserts, so it shows as
699
+ // one and is written back as \tab (an em space came back as \u8195).
700
+ // After a list marker ("\bullet\tab", "1.\tab") the gap stays an em
701
+ // space: lists are read as plain lines, and a full tab there is too wide.
702
+ currentParagraph += LIST_MARKER.test(currentParagraph) ? '&emsp;' : TAB_HTML;
695
703
  paragraphHasText = true;
696
704
  break;
697
705
  case 'pntext':
@@ -50,6 +50,19 @@ export declare const HEADING_SCALE: {
50
50
  * characters are the same number.
51
51
  */
52
52
  export declare function estimateRtfBytes(editorEl: HTMLElement): number;
53
+ /**
54
+ * The address a link should carry in the RTF, or null if it should not be a link.
55
+ *
56
+ * Only an absolute web, mail or phone address qualifies. A relative path, a UNC path
57
+ * (\\server\share) or a javascript:, data:, file: or vbscript: address is refused: the
58
+ * receiving system opens a link in its own context, where a relative or UNC path names
59
+ * a file on the reader's network. The address returned is the parsed one, which
60
+ * percent-encodes characters such as a quote that would otherwise end the field's
61
+ * address and add switches of its own.
62
+ */
63
+ export declare function linkTarget(url: string): string | null;
64
+ /** Whether a link address is an absolute web, mail or phone address (see linkTarget). */
65
+ export declare function isSafeLinkUrl(url: string): boolean;
53
66
  /**
54
67
  * CSS font-family value for a font name, with the generic fallback that
55
68
  * matches it, e.g. "Arial", sans-serif.
@@ -86,7 +86,10 @@ function escapeRtf(text) {
86
86
  else if (ch === '}')
87
87
  out += '\\}';
88
88
  else if (code > 127) {
89
- out += `\\u${code}\\'3f`;
89
+ // RTF's \uN is a SIGNED 16-bit number: from U+8000 up, and for each half of
90
+ // an emoji's surrogate pair, it is written as N - 65536. Written unsigned,
91
+ // Word and Epic read it as a different character.
92
+ out += `\\u${code > 32767 ? code - 65536 : code}\\'3f`;
90
93
  }
91
94
  else {
92
95
  out += ch;
@@ -94,6 +97,30 @@ function escapeRtf(text) {
94
97
  }
95
98
  return out;
96
99
  }
100
+ /**
101
+ * Text with its tabs written as RTF's \tab when the screen shows them as tabs. Any other tab is
102
+ * passed through as before (1.5.3), unchanged by this.
103
+ */
104
+ function escapeTabs(text, tabsShow) {
105
+ if (!tabsShow || !text.includes('\t'))
106
+ return escapeRtf(text);
107
+ return text.split('\t').map(escapeRtf).join('\\tab ');
108
+ }
109
+ /**
110
+ * Whether a text node's tabs show as tabs: it sits inside an element whose inline white-space
111
+ * keeps them. That is what the editor's Tab key inserts (Chromium's
112
+ * <span style="white-space:pre">\t</span>) and Safari's older Apple-tab-span.
113
+ */
114
+ function showsTabs(node) {
115
+ for (let el = node.parentElement; el; el = el.parentElement) {
116
+ const ws = el.style?.whiteSpace;
117
+ if (ws)
118
+ return ws === 'pre' || ws === 'pre-wrap' || ws === 'break-spaces';
119
+ if (el.classList?.contains('Apple-tab-span'))
120
+ return true;
121
+ }
122
+ return false;
123
+ }
97
124
  // ── Image helpers ──
98
125
  const B64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
99
126
  const B64_LOOKUP = (() => {
@@ -301,8 +328,28 @@ const BLOCK_OVERHEAD_BYTES = {
301
328
  figcaption: 29,
302
329
  tr: 45,
303
330
  td: 55,
304
- th: 69 // a header cell also carries \clbrdrb\brdrs
331
+ th: 69, // a header cell also carries \clbrdrb\brdrs
332
+ // Inline formatting: the control words on either side of the text.
333
+ b: 7, // "\b " + "\b0 "
334
+ strong: 7,
335
+ i: 7,
336
+ em: 7,
337
+ u: 12, // "\ul " + "\ulnone "
338
+ s: 17, // "\strike " + "\strike0 "
339
+ strike: 17,
340
+ del: 17,
341
+ sup: 19, // "\super " + "\nosupersub "
342
+ sub: 17,
343
+ code: 8, // "\f1 " + "\f0 "
344
+ br: 6, // "\line "
345
+ hr: 154, // "\pard\qc " + 20 x "\emdash" + "\par "
346
+ ul: 0,
347
+ ol: 0
305
348
  };
349
+ /** Elements that write a paragraph of their own, which inside a table cell carries \intbl. */
350
+ const CELL_PARAGRAPH_TAGS = new Set(['p', 'div', 'h1', 'h2', 'h3', 'li', 'blockquote', 'pre', 'hr', 'figure', 'figcaption']);
351
+ /** The field wrapper around a link, apart from its address. */
352
+ const LINK_OVERHEAD_BYTES = '{\\field{\\*\\fldinst HYPERLINK ""}{\\fldrslt\\ul\\cf1 \\cf0\\ulnone }}'.length;
306
353
  /**
307
354
  * Size htmlToRtf would produce, without doing the conversion.
308
355
  *
@@ -321,17 +368,78 @@ export function estimateRtfBytes(editorEl) {
321
368
  for (const img of Array.from(editorEl.querySelectorAll('img'))) {
322
369
  const src = img.getAttribute('src') || '';
323
370
  const comma = src.indexOf(',');
324
- // A picture that cannot be embedded costs only its placeholder text.
325
- if (!src.startsWith('data:image/') || comma < 0)
371
+ if (!src.startsWith('data:image/') || comma < 0) {
372
+ // A picture that cannot be embedded costs its placeholder text.
373
+ total += `\\i [Image: ]\\i0 `.length + escapeRtf(img.getAttribute('alt') || src || 'image').length;
326
374
  continue;
375
+ }
327
376
  total += base64ByteLength(src.slice(comma + 1)) * 2 + PICTURE_OVERHEAD_BYTES;
328
377
  }
329
- total += (editorEl.textContent || '').length;
378
+ // Text at its escaped length: a character outside ASCII costs its \uN\'3f escape,
379
+ // six to nine bytes rather than one.
380
+ total += escapeRtf(editorEl.textContent || '').length;
381
+ // A tab that shows is written as "\tab " (5) and counted as 1; counting every tab that way
382
+ // can only overestimate.
383
+ total += ((editorEl.textContent || '').match(/\t/g)?.length ?? 0) * 4;
330
384
  for (const el of Array.from(editorEl.querySelectorAll('*'))) {
331
- total += BLOCK_OVERHEAD_BYTES[el.tagName.toLowerCase()] ?? 0;
385
+ const tag = el.tagName.toLowerCase();
386
+ total += BLOCK_OVERHEAD_BYTES[tag] ?? 0;
387
+ if (tag === 'a') {
388
+ const target = linkTarget(el.getAttribute('href') || '');
389
+ if (target)
390
+ total += LINK_OVERHEAD_BYTES + escapeRtf(target).length;
391
+ }
392
+ // Each line break in a code block is written as "\line " (6) and counted as 1.
393
+ if (tag === 'pre')
394
+ total += ((el.textContent || '').match(/\r\n|\r|\n/g)?.length ?? 0) * 5;
395
+ // A paragraph a block writes inside a table cell also carries \intbl (6). A list
396
+ // writes one paragraph per item, so the item is counted, not the list.
397
+ if (CELL_PARAGRAPH_TAGS.has(tag) && el.closest('td, th'))
398
+ total += 6;
399
+ // Every cell in a row with a header cell carries \clbrdrb\brdrs.
400
+ if (tag === 'td' && el.parentElement?.querySelector(':scope > th'))
401
+ total += 14;
402
+ // A figure with a caption and no picture writes its caption twice.
403
+ if (tag === 'figure' && !el.querySelector('img'))
404
+ total += escapeRtf(el.textContent || '').length;
405
+ // A color costs "\cfN " on and off and, the first time, its color-table entry (at most
406
+ // 22 bytes, "\red255\green255\blue255;"); a size costs "\fsNN " on and off.
407
+ if (el.style?.color || (tag === 'font' && el.hasAttribute('color')))
408
+ total += 10 + 22;
409
+ if (el.style?.fontSize)
410
+ total += 14; // "\fsNNN " on and off, for sizes up to 499 pt
332
411
  }
333
412
  return total;
334
413
  }
414
+ // ── Link helpers ──
415
+ /**
416
+ * The address a link should carry in the RTF, or null if it should not be a link.
417
+ *
418
+ * Only an absolute web, mail or phone address qualifies. A relative path, a UNC path
419
+ * (\\server\share) or a javascript:, data:, file: or vbscript: address is refused: the
420
+ * receiving system opens a link in its own context, where a relative or UNC path names
421
+ * a file on the reader's network. The address returned is the parsed one, which
422
+ * percent-encodes characters such as a quote that would otherwise end the field's
423
+ * address and add switches of its own.
424
+ */
425
+ export function linkTarget(url) {
426
+ const value = url.trim();
427
+ if (!/^(https?:\/\/|mailto:|tel:)/i.test(value) || value.includes('\\'))
428
+ return null;
429
+ try {
430
+ const parsed = new URL(value);
431
+ if (!['http:', 'https:', 'mailto:', 'tel:'].includes(parsed.protocol))
432
+ return null;
433
+ return parsed.href.replace(/"/g, '%22');
434
+ }
435
+ catch {
436
+ return null;
437
+ }
438
+ }
439
+ /** Whether a link address is an absolute web, mail or phone address (see linkTarget). */
440
+ export function isSafeLinkUrl(url) {
441
+ return linkTarget(url) !== null;
442
+ }
335
443
  // ── Font helpers ──
336
444
  /**
337
445
  * A single font name, safe for the font table. A CSS list such as
@@ -411,7 +519,15 @@ export function htmlToRtf(editorEl, options = {}) {
411
519
  inPre: false,
412
520
  listCounter: 0,
413
521
  inTableCell: false,
414
- root: editorEl
522
+ root: editorEl,
523
+ bold: false,
524
+ italic: false,
525
+ underline: false,
526
+ strike: false,
527
+ size: bodySize,
528
+ color: 0,
529
+ script: null,
530
+ mono: false
415
531
  });
416
532
  const rtf = '{\\rtf1\\ansi\\ansicpg1252\\deff0' +
417
533
  fontTable +
@@ -451,16 +567,17 @@ function walkChildren(parent, ctx) {
451
567
  // Whitespace between two blocks (the newline in "</p>\n<p>") shows as
452
568
  // nothing in a browser. Written out, it became a space at the start of
453
569
  // the next paragraph.
454
- if (!ctx.inPre && COLLAPSIBLE_WHITESPACE.test(text) && besideBlock(node))
570
+ const tabsShow = ctx.inPre || showsTabs(node);
571
+ if (!tabsShow && COLLAPSIBLE_WHITESPACE.test(text) && besideBlock(node))
455
572
  continue;
456
573
  if (ctx.inPre) {
457
574
  // Split before escaping — escapeRtf collapses newlines, so the
458
575
  // line structure a <pre> block depends on has to become \line
459
576
  // first. Handles CR, LF and CRLF alike.
460
- rtf += text.split(/\r\n|\r|\n/).map(escapeRtf).join('\\line ');
577
+ rtf += text.split(/\r\n|\r|\n/).map((line) => escapeTabs(line, true)).join('\\line ');
461
578
  }
462
579
  else {
463
- rtf += escapeRtf(text);
580
+ rtf += escapeTabs(text, tabsShow);
464
581
  }
465
582
  continue;
466
583
  }
@@ -470,34 +587,57 @@ function walkChildren(parent, ctx) {
470
587
  const tag = el.tagName.toLowerCase();
471
588
  switch (tag) {
472
589
  // Heading sizes keep their ratio to the body (HEADING_SCALE).
473
- case 'h1':
474
- rtf += `\\pard\\f0\\fs${scaled(ctx, HEADING_SCALE.h1)}\\b ${walkChildren(el, ctx)}\\b0\\fs${ctx.bodySize}\\par `;
590
+ case 'h1': {
591
+ const size = scaled(ctx, HEADING_SCALE.h1);
592
+ rtf += `\\pard${inCell(ctx)}\\f0\\fs${size}\\b ${walkChildren(el, { ...ctx, bold: true, size })}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size}\\par `;
475
593
  break;
476
- case 'h2':
477
- rtf += `\\pard\\f0\\fs${scaled(ctx, HEADING_SCALE.h2)}\\b ${walkChildren(el, ctx)}\\b0\\fs${ctx.bodySize}\\par `;
594
+ }
595
+ case 'h2': {
596
+ const size = scaled(ctx, HEADING_SCALE.h2);
597
+ rtf += `\\pard${inCell(ctx)}\\f0\\fs${size}\\b ${walkChildren(el, { ...ctx, bold: true, size })}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size}\\par `;
478
598
  break;
479
- case 'h3':
480
- rtf += `\\pard\\f0\\fs${scaled(ctx, HEADING_SCALE.h3)}\\b ${walkChildren(el, ctx)}\\b0\\fs${ctx.bodySize}\\par `;
599
+ }
600
+ case 'h3': {
601
+ const size = scaled(ctx, HEADING_SCALE.h3);
602
+ rtf += `\\pard${inCell(ctx)}\\f0\\fs${size}\\b ${walkChildren(el, { ...ctx, bold: true, size })}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size}\\par `;
481
603
  break;
604
+ }
482
605
  case 'p':
483
606
  case 'div': {
484
- // Inside a table cell \pard is already declared; just emit inline content.
607
+ // Inside a table cell the cell has already declared \pard\intbl. Each paragraph
608
+ // ends with \par, so two paragraphs in one cell stay two (the cell drops the last
609
+ // one's); one that follows a list or heading in the cell restates \pard\intbl,
610
+ // so it does not inherit that block's indent.
611
+ // Text typed straight into the parent before this block ("abc<div>def</div>",
612
+ // the shape Chrome makes on Enter) has no paragraph of its own: end it here, or
613
+ // the two lines run together.
614
+ const afterLooseText = followsInlineContent(el);
485
615
  if (ctx.inTableCell) {
486
- rtf += walkChildren(el, ctx);
616
+ const restate = afterLooseText
617
+ ? '\\par \\pard\\intbl '
618
+ : el.previousElementSibling ? '\\pard\\intbl ' : '';
619
+ if (isBlankLine(el)) {
620
+ rtf += `${restate}\\par `;
621
+ break;
622
+ }
623
+ const colorIdx = colorIndexOf(el, ctx);
624
+ const inner = walkChildren(el, colorIdx != null ? { ...ctx, color: colorIdx } : ctx);
625
+ rtf += colorIdx != null
626
+ ? `${restate}\\cf${colorIdx} ${inner}\\cf${ctx.color} \\par `
627
+ : `${restate}${inner}\\par `;
487
628
  break;
488
629
  }
489
630
  // A <p> with no children or only a single <br> is a blank line —
490
631
  // emit a bare \par rather than \pard \line\par, which adds an extra line.
491
- const isBlankLine = el.childNodes.length === 0 ||
492
- (el.childNodes.length === 1 && el.childNodes[0].nodeName === 'BR');
493
- if (isBlankLine) {
494
- rtf += '\\par ';
632
+ if (isBlankLine(el)) {
633
+ rtf += afterLooseText ? '\\par \\par ' : '\\par ';
495
634
  break;
496
635
  }
497
- const inlineRtf = walkChildren(el, ctx);
498
- const colorPrefix = getColorPrefix(el, ctx);
499
- const colorSuffix = colorPrefix ? '\\cf0 ' : '';
500
- rtf += `\\pard ${colorPrefix}${inlineRtf}${colorSuffix}\\par `;
636
+ const colorIdx = colorIndexOf(el, ctx);
637
+ const inlineRtf = walkChildren(el, colorIdx != null ? { ...ctx, color: colorIdx } : ctx);
638
+ const colorPrefix = colorIdx != null ? `\\cf${colorIdx} ` : '';
639
+ const colorSuffix = colorIdx != null ? `\\cf${ctx.color} ` : '';
640
+ rtf += `${afterLooseText ? '\\par ' : ''}\\pard ${colorPrefix}${inlineRtf}${colorSuffix}\\par `;
501
641
  break;
502
642
  }
503
643
  case 'table': {
@@ -529,7 +669,7 @@ function walkChildren(parent, ctx) {
529
669
  // Cell bodies
530
670
  const cellCtx = { ...ctx, inTableCell: true };
531
671
  for (const cell of cells) {
532
- const content = walkChildren(cell, cellCtx);
672
+ const content = withoutTrailingPar(walkChildren(cell, cellCtx));
533
673
  rowRtf += `{\\pard\\intbl \\f0 \\sa0 \\li0 \\fi0 ${content}\\par}\\cell`;
534
674
  }
535
675
  rowRtf += '}\\intbl\\row}';
@@ -538,18 +678,20 @@ function walkChildren(parent, ctx) {
538
678
  break;
539
679
  }
540
680
  case 'blockquote':
541
- rtf += `\\pard\\li720\\i ${walkChildren(el, ctx)}\\i0\\par `;
681
+ rtf += `\\pard${inCell(ctx)}\\li720\\i ${walkChildren(el, { ...ctx, italic: true })}${ctx.italic ? '' : '\\i0'}\\par `;
542
682
  break;
543
- case 'pre':
544
- rtf += `\\pard\\f1\\fs${scaled(ctx, PRE_SCALE)} ${walkChildren(el, { ...ctx, inPre: true })}\\f0\\fs${ctx.bodySize}\\par `;
683
+ case 'pre': {
684
+ const size = scaled(ctx, PRE_SCALE);
685
+ rtf += `\\pard${inCell(ctx)}\\f1\\fs${size} ${walkChildren(el, { ...ctx, inPre: true, size })}\\f0\\fs${ctx.size}\\par `;
545
686
  break;
687
+ }
546
688
  case 'hr':
547
- rtf += `\\pard\\qc \\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\par `;
689
+ rtf += `\\pard${inCell(ctx)}\\qc \\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\emdash\\par `;
548
690
  break;
549
691
  case 'ul': {
550
692
  const items = el.querySelectorAll(':scope > li');
551
693
  items.forEach((li) => {
552
- rtf += `\\pard\\li720\\fi-360\\bullet\\tab ${walkChildren(li, ctx)}\\par `;
694
+ rtf += `\\pard${inCell(ctx)}\\li720\\fi-360\\bullet\\tab ${walkChildren(li, ctx)}\\par `;
553
695
  });
554
696
  break;
555
697
  }
@@ -557,7 +699,7 @@ function walkChildren(parent, ctx) {
557
699
  let counter = 1;
558
700
  const items = el.querySelectorAll(':scope > li');
559
701
  items.forEach((li) => {
560
- rtf += `\\pard\\li720\\fi-360 ${counter}.\\tab ${walkChildren(li, ctx)}\\par `;
702
+ rtf += `\\pard${inCell(ctx)}\\li720\\fi-360 ${counter}.\\tab ${walkChildren(li, ctx)}\\par `;
561
703
  counter++;
562
704
  });
563
705
  break;
@@ -567,42 +709,50 @@ function walkChildren(parent, ctx) {
567
709
  break;
568
710
  case 'strong':
569
711
  case 'b':
570
- rtf += `\\b ${walkChildren(el, ctx)}\\b0 `;
712
+ rtf += ctx.bold ? walkChildren(el, ctx) : `\\b ${walkChildren(el, { ...ctx, bold: true })}\\b0 `;
571
713
  break;
572
714
  case 'em':
573
715
  case 'i':
574
- rtf += `\\i ${walkChildren(el, ctx)}\\i0 `;
716
+ rtf += ctx.italic ? walkChildren(el, ctx) : `\\i ${walkChildren(el, { ...ctx, italic: true })}\\i0 `;
575
717
  break;
576
718
  case 'u':
577
- rtf += `\\ul ${walkChildren(el, ctx)}\\ulnone `;
719
+ rtf += ctx.underline ? walkChildren(el, ctx) : `\\ul ${walkChildren(el, { ...ctx, underline: true })}\\ulnone `;
578
720
  break;
579
721
  case 's':
580
722
  case 'strike':
581
723
  case 'del':
582
- rtf += `\\strike ${walkChildren(el, ctx)}\\strike0 `;
724
+ rtf += ctx.strike ? walkChildren(el, ctx) : `\\strike ${walkChildren(el, { ...ctx, strike: true })}\\strike0 `;
583
725
  break;
584
726
  case 'sup':
585
- rtf += `\\super ${walkChildren(el, ctx)}\\nosupersub `;
586
- break;
587
- case 'sub':
588
- rtf += `\\sub ${walkChildren(el, ctx)}\\nosupersub `;
727
+ case 'sub': {
728
+ const script = tag === 'sup' ? 'super' : 'sub';
729
+ if (ctx.script === script) {
730
+ rtf += walkChildren(el, ctx);
731
+ break;
732
+ }
733
+ const restore = ctx.script ? `\\${ctx.script} ` : '\\nosupersub ';
734
+ rtf += `\\${script} ${walkChildren(el, { ...ctx, script })}${restore}`;
589
735
  break;
736
+ }
590
737
  case 'code':
591
- if (!ctx.inPre) {
592
- rtf += `\\f1 ${walkChildren(el, ctx)}\\f0 `;
738
+ if (!ctx.inPre && !ctx.mono) {
739
+ rtf += `\\f1 ${walkChildren(el, { ...ctx, mono: true })}\\f0 `;
593
740
  }
594
741
  else {
595
742
  rtf += walkChildren(el, ctx);
596
743
  }
597
744
  break;
598
745
  case 'a': {
599
- const href = el.getAttribute('href') || '';
600
- const inner = walkChildren(el, ctx);
601
- if (href) {
602
- rtf += `{\\field{\\*\\fldinst HYPERLINK "${escapeRtf(href)}"}{\\fldrslt\\ul\\cf1 ${inner}\\cf0\\ulnone }}`;
746
+ // A link is written only for an absolute web, mail or phone address; anything
747
+ // else (a relative or UNC path, javascript:, data:, file:) as its text alone.
748
+ const target = linkTarget(el.getAttribute('href') || '');
749
+ if (target) {
750
+ const inner = walkChildren(el, { ...ctx, underline: true, color: 1 });
751
+ const underlineOff = ctx.underline ? '' : '\\ulnone';
752
+ rtf += `{\\field{\\*\\fldinst HYPERLINK "${escapeRtf(target)}"}{\\fldrslt\\ul\\cf1 ${inner}\\cf${ctx.color}${underlineOff} }}`;
603
753
  }
604
754
  else {
605
- rtf += inner;
755
+ rtf += walkChildren(el, ctx);
606
756
  }
607
757
  break;
608
758
  }
@@ -616,11 +766,11 @@ function walkChildren(parent, ctx) {
616
766
  const caption = (el.querySelector('figcaption')?.textContent || '').trim();
617
767
  const align = alignControl(el);
618
768
  if (img)
619
- rtf += `\\pard${align} ${imageBody(img)}\\par `;
769
+ rtf += `\\pard${inCell(ctx)}${align} ${imageBody(img)}\\par `;
620
770
  else
621
771
  rtf += walkChildren(el, ctx);
622
772
  if (caption) {
623
- rtf += `{\\*\\inkcap}\\pard${align}\\i ${escapeRtf(caption)}\\i0\\par `;
773
+ rtf += `{\\*\\inkcap}\\pard${inCell(ctx)}${align}\\i ${escapeRtf(caption)}${ctx.italic ? '' : '\\i0'}\\par `;
624
774
  }
625
775
  break;
626
776
  }
@@ -635,18 +785,22 @@ function walkChildren(parent, ctx) {
635
785
  rtf += '\\line ';
636
786
  break;
637
787
  case 'span': {
638
- const colorPfx = getColorPrefix(el, ctx);
639
- const sizePfx = getSizePrefix(el);
640
- const sizesfx = sizePfx ? `\\fs${ctx.bodySize} ` : '';
641
- const colorSfx = colorPfx ? '\\cf0 ' : '';
642
- rtf += `${colorPfx}${sizePfx}${walkChildren(el, ctx)}${sizesfx}${colorSfx}`;
788
+ const colorIdx = colorIndexOf(el, ctx);
789
+ const size = sizeOf(el);
790
+ const colorPfx = colorIdx != null ? `\\cf${colorIdx} ` : '';
791
+ const sizePfx = size != null ? `\\fs${size} ` : '';
792
+ const sizeSfx = size != null ? `\\fs${ctx.size} ` : '';
793
+ const colorSfx = colorIdx != null ? `\\cf${ctx.color} ` : '';
794
+ const inner = walkChildren(el, { ...ctx, color: colorIdx ?? ctx.color, size: size ?? ctx.size });
795
+ rtf += `${colorPfx}${sizePfx}${inner}${sizeSfx}${colorSfx}`;
643
796
  break;
644
797
  }
645
798
  // <font color="..."> is produced by execCommand('foreColor') in contenteditable
646
799
  case 'font': {
647
- const colorPfx = getColorPrefix(el, ctx);
648
- const colorSfx = colorPfx ? '\\cf0 ' : '';
649
- rtf += `${colorPfx}${walkChildren(el, ctx)}${colorSfx}`;
800
+ const colorIdx = colorIndexOf(el, ctx);
801
+ const colorPfx = colorIdx != null ? `\\cf${colorIdx} ` : '';
802
+ const colorSfx = colorIdx != null ? `\\cf${ctx.color} ` : '';
803
+ rtf += `${colorPfx}${walkChildren(el, { ...ctx, color: colorIdx ?? ctx.color })}${colorSfx}`;
650
804
  break;
651
805
  }
652
806
  default:
@@ -678,33 +832,63 @@ function besideBlock(node) {
678
832
  const next = node.nextSibling;
679
833
  return isBlock(prev) || isBlock(next) || (!prev && !next && isBlock(node.parentNode));
680
834
  }
681
- function getColorPrefix(el, ctx) {
835
+ /** A <p> or <div> with no content, or only a <br>: a blank line. */
836
+ function isBlankLine(el) {
837
+ return el.childNodes.length === 0 || (el.childNodes.length === 1 && el.childNodes[0].nodeName === 'BR');
838
+ }
839
+ /**
840
+ * Whether the nearest sibling before this element, skipping collapsible whitespace, is
841
+ * text or an inline element: content with no paragraph of its own.
842
+ */
843
+ function followsInlineContent(el) {
844
+ let prev = el.previousSibling;
845
+ while (prev && prev.nodeType === Node.TEXT_NODE && COLLAPSIBLE_WHITESPACE.test(prev.textContent || '')) {
846
+ prev = prev.previousSibling;
847
+ }
848
+ if (!prev)
849
+ return false;
850
+ if (prev.nodeType === Node.TEXT_NODE)
851
+ return true;
852
+ return prev.nodeType === Node.ELEMENT_NODE && !isBlock(prev);
853
+ }
854
+ /**
855
+ * The cell's own \par ends its last paragraph, so that paragraph's mark is dropped. Only a
856
+ * real control word: "\par " preceded by an odd run of backslashes is escaped text.
857
+ */
858
+ function withoutTrailingPar(content) {
859
+ if (!content.endsWith('\\par '))
860
+ return content;
861
+ let slashes = 0;
862
+ for (let i = content.length - 6; i >= 0 && content[i] === '\\'; i--)
863
+ slashes++;
864
+ return slashes % 2 === 0 ? content.slice(0, -5) : content;
865
+ }
866
+ /** \intbl for a paragraph a block writes inside a table cell, so it stays in the cell. */
867
+ function inCell(ctx) {
868
+ return ctx.inTableCell ? '\\intbl' : '';
869
+ }
870
+ /** Color-table index of the element's own color, or null when it sets none. */
871
+ function colorIndexOf(el, ctx) {
682
872
  // Support both inline style.color (spans) and the color attribute (<font>)
683
873
  const color = el.style?.color ||
684
874
  (el.tagName.toLowerCase() === 'font' ? (el.getAttribute('color') ?? '') : '');
685
875
  if (!color)
686
- return '';
876
+ return null;
687
877
  const c = parseColor(color);
688
878
  if (!c)
689
- return '';
690
- const idx = ctx.colorIndex.get(colorKey(c));
691
- if (idx != null)
692
- return `\\cf${idx} `;
693
- return '';
879
+ return null;
880
+ return ctx.colorIndex.get(colorKey(c)) ?? null;
694
881
  }
695
- function getSizePrefix(el) {
882
+ /** The element's own font size in half-points, or null when it sets none. */
883
+ function sizeOf(el) {
696
884
  const fs = el.style?.fontSize;
697
885
  if (!fs)
698
- return '';
886
+ return null;
699
887
  const ptMatch = fs.match(/([\d.]+)\s*pt/);
700
- if (ptMatch) {
701
- const halfPoints = Math.round(parseFloat(ptMatch[1]) * 2);
702
- return `\\fs${halfPoints} `;
703
- }
888
+ if (ptMatch)
889
+ return Math.round(parseFloat(ptMatch[1]) * 2);
704
890
  const pxMatch = fs.match(/([\d.]+)\s*px/);
705
- if (pxMatch) {
706
- const halfPoints = Math.round(parseFloat(pxMatch[1]) * 0.75 * 2);
707
- return `\\fs${halfPoints} `;
708
- }
709
- return '';
891
+ if (pxMatch)
892
+ return Math.round(parseFloat(pxMatch[1]) * 0.75 * 2);
893
+ return null;
710
894
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "svelte-rtf-editor",
3
- "version": "1.5.2",
3
+ "version": "1.6.0",
4
4
  "description": "RTF viewer and rich-text editor components for Svelte 5",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/jcelano/svelte-rtf-editor#readme",