svelte-rtf-editor 1.5.3 → 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
@@ -232,6 +232,12 @@ The components use CSS custom properties with sensible fallbacks, so they work o
232
232
  | `Ctrl+K` | Insert link |
233
233
  | `Ctrl+S` | Save (fires `onsave`) |
234
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.
235
241
 
236
242
  ---
237
243
 
@@ -747,12 +747,123 @@
747
747
  return;
748
748
  }
749
749
 
750
- if (e.key === 'Tab') {
751
- const sel = window.getSelection();
752
- if (sel?.anchorNode?.parentElement?.closest?.('pre')) {
753
- e.preventDefault();
754
- 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;
755
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;
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);
756
867
  }
757
868
  }
758
869
 
@@ -848,6 +959,8 @@
848
959
  onmouseup={updateToolbarState}
849
960
  onkeyup={updateToolbarState}
850
961
  onkeydown={handleKeydown}
962
+ onmousedown={() => (tabLeavesEditor = false)}
963
+ onblur={() => (tabLeavesEditor = false)}
851
964
  onpaste={handlePaste}
852
965
  onclick={handleContentClick}
853
966
  ondragover={handleDragOver}
@@ -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':
@@ -97,6 +97,30 @@ function escapeRtf(text) {
97
97
  }
98
98
  return out;
99
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
+ }
100
124
  // ── Image helpers ──
101
125
  const B64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
102
126
  const B64_LOOKUP = (() => {
@@ -354,6 +378,9 @@ export function estimateRtfBytes(editorEl) {
354
378
  // Text at its escaped length: a character outside ASCII costs its \uN\'3f escape,
355
379
  // six to nine bytes rather than one.
356
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;
357
384
  for (const el of Array.from(editorEl.querySelectorAll('*'))) {
358
385
  const tag = el.tagName.toLowerCase();
359
386
  total += BLOCK_OVERHEAD_BYTES[tag] ?? 0;
@@ -540,16 +567,17 @@ function walkChildren(parent, ctx) {
540
567
  // Whitespace between two blocks (the newline in "</p>\n<p>") shows as
541
568
  // nothing in a browser. Written out, it became a space at the start of
542
569
  // the next paragraph.
543
- 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))
544
572
  continue;
545
573
  if (ctx.inPre) {
546
574
  // Split before escaping — escapeRtf collapses newlines, so the
547
575
  // line structure a <pre> block depends on has to become \line
548
576
  // first. Handles CR, LF and CRLF alike.
549
- 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 ');
550
578
  }
551
579
  else {
552
- rtf += escapeRtf(text);
580
+ rtf += escapeTabs(text, tabsShow);
553
581
  }
554
582
  continue;
555
583
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "svelte-rtf-editor",
3
- "version": "1.5.3",
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",