svelte-rtf-editor 1.6.0 → 1.7.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
@@ -202,6 +202,24 @@ The font has to be installed on the machine that displays the document. The RTF
202
202
 
203
203
  ---
204
204
 
205
+ ## Paragraph formatting
206
+
207
+ A `<p>` or `<div>` keeps its own indents, spacing and tab stops in the RTF, so a layout made of ordinary paragraphs, such as a bold label, a tab, and text in a column with later lines hanging under it, reaches the receiving system:
208
+
209
+ | HTML on the paragraph | RTF |
210
+ |---|---|
211
+ | `margin-left: 1.75in` | `\li2520` |
212
+ | `text-indent: -1.75in` | `\fi-2520` |
213
+ | `margin-top: 5pt` / `margin-bottom: 5pt` | `\sb100` / `\sa100` |
214
+ | `break-after: avoid` or `page-break-after: avoid` | `\keepn` |
215
+ | `data-rtf-tab-stops="1.75in"` (comma-separated) | `\tx2520` |
216
+
217
+ - Lengths in `in`, `pt`, `cm`, `mm` or `px` (15 twips per px), rounded to whole twips. Only `text-indent` may be negative. A value the writer cannot read, or zero, writes nothing.
218
+ - CSS has no absolute tab stop, hence the `data-` attribute. On screen, `white-space: pre-wrap; tab-size: 1.75in` with that hanging indent puts the browser's first stop at the same place, and `pre-wrap` makes the writer send the tab as `\tab`.
219
+ - `margin-left` adds to the indent of the blocks around the paragraph (an indent pasted from a browser, or a `<div>` with a margin that holds paragraphs), and is written as one `\li`.
220
+ - Inside a table cell the cell declares its own paragraph: only alignment and the left indent are written there, not spacing, tab stops or keep-with-next.
221
+ - `rtfToHtml` does not yet read them back, so `RtfViewer` shows such a document without its indents.
222
+
205
223
  ## Theming
206
224
 
207
225
  The components use CSS custom properties with sensible fallbacks, so they work out of the box but are easy to customise. Override these in your own CSS:
@@ -232,10 +250,14 @@ The components use CSS custom properties with sensible fallbacks, so they work o
232
250
  | `Ctrl+K` | Insert link |
233
251
  | `Ctrl+S` | Save (fires `onsave`) |
234
252
  | `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 |
253
+ | `Ctrl+]` / `Cmd+]` | Increase indent of the selected paragraphs by 0.5 in (RTF `\li720` per step) |
254
+ | `Ctrl+[` / `Cmd+[` | Decrease indent |
255
+ | `Tab` | Insert a tab (sent to RTF as `\tab`); two spaces in a code block. With several lines selected, increase their indent |
256
+ | `Shift+Tab` | Remove one tab from the start of the line. With several lines selected, decrease their indent |
237
257
  | `Esc`, then `Tab` / `Shift+Tab` | Move focus out of the editor |
238
258
 
259
+ The toolbar's Increase indent and Decrease indent buttons do the same as `Ctrl+]` and `Ctrl+[`. Undo reverses an indent step until the next edit. Paragraph alignment (left, center, right, justify) is written to RTF as `\qc`, `\qr` or `\qj`.
260
+
239
261
  Tab stays in the editor so a line can be indented. To leave the editor from the keyboard, press
240
262
  `Esc` first. A readonly editor leaves Tab to the browser.
241
263
 
@@ -180,6 +180,7 @@
180
180
  export function setHTML(html: string): void {
181
181
  if (editorEl) {
182
182
  selectedImage = null;
183
+ indentUndo = [];
183
184
  editorEl.innerHTML = html;
184
185
  updateCounts();
185
186
  if (autosave) scheduleAutoSave();
@@ -211,6 +212,7 @@
211
212
  export function clear(): void {
212
213
  if (editorEl) {
213
214
  selectedImage = null;
215
+ indentUndo = [];
214
216
  editorEl.innerHTML = '<p></p>';
215
217
  try { localStorage.removeItem(storageKey); } catch (e) {}
216
218
  updateCounts();
@@ -276,10 +278,199 @@
276
278
  const sel = window.getSelection();
277
279
  if (!sel || sel.isCollapsed) return;
278
280
  }
281
+ if (cmd === 'indent' || cmd === 'outdent') {
282
+ indentBlocks(cmd);
283
+ return;
284
+ }
285
+ if (cmd === 'undo' && undoIndent()) return;
279
286
  document.execCommand(cmd, false, value ?? undefined);
280
287
  updateToolbarState();
281
288
  }
282
289
 
290
+ // ── Indent ──
291
+ // Indent and Outdent move the paragraphs the selection touches by half an inch (48px, written
292
+ // to RTF as \li720) per press, as margin-left on each paragraph. The browser's own commands are
293
+ // not used: Chromium's Outdent strips the first paragraph to loose text ("one<br>"), and the
294
+ // browsers disagree on the markup. Only a style changes (and a line of loose text gets a
295
+ // paragraph of its own), so earlier typing stays undoable; the editor keeps its own undo for
296
+ // these steps until the next edit.
297
+ const INDENT_STEP_PX = 48;
298
+ const INDENT_TARGETS = 'p, div, h1, h2, h3, h4, h5, h6, pre, ul, ol, blockquote, figure';
299
+ /** CSS lengths a margin is written in, in px. */
300
+ const PX_PER_UNIT: Record<string, number> = { px: 1, pt: 96 / 72, in: 96, cm: 96 / 2.54, mm: 96 / 25.4 };
301
+
302
+ /** One block an Indent or Outdent changed, and how to put it back. */
303
+ interface IndentChange {
304
+ el: HTMLElement;
305
+ before: string | null;
306
+ after: string | null;
307
+ /** The block is a paragraph this step made around loose text, and the <br> that ended it. */
308
+ wrapped: { br: HTMLBRElement | null } | null;
309
+ }
310
+ let indentUndo: IndentChange[][] = [];
311
+
312
+ function indentBlocks(cmd: 'indent' | 'outdent'): void {
313
+ if (readonly || !editorEl) return;
314
+ editorEl.focus();
315
+ const sel = window.getSelection();
316
+ if (!sel || sel.rangeCount === 0 || !sel.anchorNode || !editorEl.contains(sel.anchorNode)) return;
317
+ const { anchorNode, anchorOffset, focusNode, focusOffset } = sel;
318
+ const wrapped = new Map<HTMLElement, HTMLBRElement | null>();
319
+ const targets = indentTargets(sel.getRangeAt(0), cmd, wrapped);
320
+ // Wrapping loose text moves the selected text nodes, which collapses the selection; put it
321
+ // back so the next press moves the same lines.
322
+ if (wrapped.size > 0 && anchorNode instanceof Text && focusNode instanceof Text && anchorNode.isConnected && focusNode.isConnected) {
323
+ sel.setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset);
324
+ }
325
+ const step: IndentChange[] = [];
326
+ for (const el of targets) {
327
+ const current = marginLeftPx(el);
328
+ const next = cmd === 'indent' ? current + INDENT_STEP_PX : Math.max(0, current - INDENT_STEP_PX);
329
+ if (next === current) continue;
330
+ const before = el.getAttribute('style');
331
+ el.style.marginLeft = next > 0 ? `${Math.round(next * 100) / 100}px` : '';
332
+ if (!el.getAttribute('style')) el.removeAttribute('style');
333
+ const br = wrapped.get(el);
334
+ step.push({ el, before, after: el.getAttribute('style'), wrapped: br === undefined ? null : { br } });
335
+ }
336
+ if (step.length === 0) return;
337
+ indentUndo.push(step);
338
+ indentChanged();
339
+ }
340
+
341
+ /** An element's left margin in px: its own, from the inline style, or 0. */
342
+ function marginLeftPx(el: HTMLElement): number {
343
+ const value = el.style.marginLeft.trim().toLowerCase();
344
+ if (!value) return 0;
345
+ const m = /^(-?\d*\.?\d+)(px|pt|in|cm|mm)$/.exec(value);
346
+ const px = m ? parseFloat(m[1]) * PX_PER_UNIT[m[2]] : parseFloat(getComputedStyle(el).marginLeft);
347
+ return Math.max(0, px || 0);
348
+ }
349
+
350
+ /**
351
+ * The indent shape Chromium, WebKit and Gmail paste: a blockquote with a left margin and
352
+ * border: none. A quotation keeps its border. The RTF writer reads it the same way.
353
+ */
354
+ function isIndentBlockquote(el: Element): el is HTMLElement {
355
+ return el instanceof HTMLElement && el.tagName === 'BLOCKQUOTE' && el.style.borderLeftStyle === 'none';
356
+ }
357
+
358
+ /** Undo the last Indent or Outdent, if nothing has changed since. */
359
+ function undoIndent(): boolean {
360
+ const step = indentUndo.pop();
361
+ if (!step) return false;
362
+ // Content replaced or edited since (setHTML, an import, a link): the step no longer applies.
363
+ if (step.some(({ el, after }) => !el.isConnected || el.getAttribute('style') !== after)) {
364
+ indentUndo = [];
365
+ return false;
366
+ }
367
+ for (const { el, before, wrapped } of step) {
368
+ if (before === null) el.removeAttribute('style');
369
+ else el.setAttribute('style', before);
370
+ if (wrapped) {
371
+ if (wrapped.br) el.after(wrapped.br);
372
+ el.replaceWith(...Array.from(el.childNodes));
373
+ }
374
+ }
375
+ indentChanged();
376
+ return true;
377
+ }
378
+
379
+ function indentChanged(): void {
380
+ updateToolbarState();
381
+ fireChange();
382
+ if (autosave) scheduleAutoSave();
383
+ }
384
+
385
+ /**
386
+ * The blocks Indent moves: each line's paragraph, and a list, a quotation or a picture as a
387
+ * whole. A line of loose text (typed straight into the editor or a table cell) is first given a
388
+ * paragraph of its own, so the margin moves that line only. Outdent on a line with no margin
389
+ * of its own moves the pasted indent around it (isIndentBlockquote) instead.
390
+ */
391
+ function indentTargets(
392
+ range: Range,
393
+ cmd: 'indent' | 'outdent',
394
+ wrapped: Map<HTMLElement, HTMLBRElement | null>
395
+ ): HTMLElement[] {
396
+ if (!editorEl) return [];
397
+ const root = editorEl;
398
+ const found: HTMLElement[] = [];
399
+ const add = (el: HTMLElement | null) => {
400
+ if (el && !found.includes(el)) found.push(el);
401
+ };
402
+ const blockFor = (node: Node): HTMLElement | null => {
403
+ if (node === root || !root.contains(node)) return null;
404
+ const el = node instanceof Element ? node : node.parentElement;
405
+ if (!el) return null;
406
+ const cell = el.closest('td, th');
407
+ const inScope = (b: Element | null | undefined): b is HTMLElement =>
408
+ b instanceof HTMLElement && b !== root && root.contains(b) && (!cell || cell.contains(b));
409
+ const item = el.closest('li');
410
+ const closest = el.closest(INDENT_TARGETS);
411
+ const block = inScope(item) ? item.parentElement : inScope(closest) ? closest : null;
412
+ if (cmd === 'outdent' && (!block || marginLeftPx(block) === 0)) {
413
+ for (let a = (block ?? el).parentElement; inScope(a); a = a.parentElement) {
414
+ if (isIndentBlockquote(a) && marginLeftPx(a) > 0) return a;
415
+ }
416
+ return block;
417
+ }
418
+ if (inScope(block)) return block;
419
+ if (cmd === 'outdent') return null;
420
+ const made = wrapLooseLine(node);
421
+ if (made) wrapped.set(made.p, made.br);
422
+ return made?.p ?? null;
423
+ };
424
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
425
+ const texts: Text[] = [];
426
+ for (let n = walker.nextNode() as Text | null; n; n = walker.nextNode() as Text | null) {
427
+ if (!n.data.trim() || !range.intersectsNode(n)) continue;
428
+ // A selection that only touches a line's edge (dragged to the start of the next line)
429
+ // does not move that line.
430
+ if (n === range.endContainer && range.endOffset === 0 && !range.collapsed) continue;
431
+ if (n === range.startContainer && range.startOffset === n.length && !range.collapsed) continue;
432
+ texts.push(n);
433
+ }
434
+ if (texts.length === 0) add(blockFor(range.startContainer));
435
+ for (const t of texts) add(blockFor(t));
436
+ return found;
437
+ }
438
+
439
+ /**
440
+ * Put the run of loose text and inline elements around a node into a <p>, and return it with
441
+ * the <br> that ended the run, which the paragraph replaces.
442
+ */
443
+ function wrapLooseLine(node: Node): { p: HTMLElement; br: HTMLBRElement | null } | null {
444
+ if (!editorEl || node === editorEl || !editorEl.contains(node)) return null;
445
+ let start: Node = node;
446
+ while (start.parentNode && start.parentNode !== editorEl && !(start.parentNode as Element).matches?.('td, th')) {
447
+ start = start.parentNode;
448
+ }
449
+ const parent = start.parentNode;
450
+ if (!parent || !editorEl.contains(parent)) return null;
451
+ const isBreak = (n: Node | null) =>
452
+ !n || (n instanceof Element && (n.matches(INDENT_TARGETS) || n.matches('br, table, hr')));
453
+ if (isBreak(start)) return null;
454
+ let first: Node = start;
455
+ while (!isBreak(first.previousSibling)) first = first.previousSibling!;
456
+ let last: Node = start;
457
+ while (!isBreak(last.nextSibling)) last = last.nextSibling!;
458
+ const p = document.createElement('p');
459
+ parent.insertBefore(p, first);
460
+ let n: Node | null = first;
461
+ while (n) {
462
+ const next: Node | null = n === last ? null : n.nextSibling;
463
+ p.appendChild(n);
464
+ n = next;
465
+ }
466
+ let br: HTMLBRElement | null = null;
467
+ if (p.nextSibling instanceof HTMLBRElement) {
468
+ br = p.nextSibling;
469
+ br.remove();
470
+ }
471
+ return { p, br };
472
+ }
473
+
283
474
  // ── Block type ──
284
475
  function setBlock(tag: string): void {
285
476
  restoreSelection();
@@ -351,6 +542,7 @@
351
542
 
352
543
  // ── Input handler ──
353
544
  function handleInput(): void {
545
+ indentUndo = [];
354
546
  updateToolbarState();
355
547
  // Typing means the user is editing text, not the picture. Dropping the
356
548
  // selection here keeps Backspace editing that text instead of deleting a
@@ -379,6 +571,8 @@
379
571
  return;
380
572
  }
381
573
  linkError = '';
574
+ // Inserting changes the document outside an input event: earlier indent steps no longer undo.
575
+ indentUndo = [];
382
576
  restoreSelection();
383
577
  editorEl?.focus();
384
578
 
@@ -504,6 +698,7 @@
504
698
  caption: string
505
699
  ): { img: HTMLImageElement; after: HTMLElement } | null {
506
700
  if (!editorEl) return null;
701
+ indentUndo = [];
507
702
 
508
703
  const figure = document.createElement('figure');
509
704
  const img = document.createElement('img');
@@ -708,6 +903,7 @@
708
903
  const html = await readRtfFile(file, { fontSize });
709
904
  if (editorEl) {
710
905
  selectedImage = null;
906
+ indentUndo = [];
711
907
  editorEl.innerHTML = html;
712
908
  updateCounts();
713
909
  fireChange();
@@ -730,6 +926,9 @@
730
926
  if (mod && e.key === 'u') { e.preventDefault(); exec('underline'); }
731
927
  if (mod && e.key === 'k') { e.preventDefault(); openLinkModal(); }
732
928
  if (mod && e.key === 's') { e.preventDefault(); autoSaveNow(); }
929
+ if (mod && !e.shiftKey && e.key.toLowerCase() === 'z' && undoIndent()) { e.preventDefault(); return; }
930
+ if (mod && e.key === ']') { e.preventDefault(); indentBlocks('indent'); return; }
931
+ if (mod && e.key === '[') { e.preventDefault(); indentBlocks('outdent'); return; }
733
932
 
734
933
  // Moving the caret leaves the picture behind, so drop its selection frame.
735
934
  // Deliberately falls through: these keys still have their normal meaning,
@@ -771,6 +970,12 @@
771
970
  if (!e.shiftKey) document.execCommand('insertText', false, ' ');
772
971
  return;
773
972
  }
973
+ // Several lines selected: Tab and Shift+Tab indent and outdent them all, as a word
974
+ // processor does. Within one line, Tab types a tab.
975
+ if (selectionSpansLines(sel)) {
976
+ indentBlocks(e.shiftKey ? 'outdent' : 'indent');
977
+ return;
978
+ }
774
979
  if (!e.shiftKey) {
775
980
  insertTab(sel);
776
981
  return;
@@ -810,6 +1015,16 @@
810
1015
  return range.toString();
811
1016
  }
812
1017
 
1018
+ /** Whether a selection runs across more than one paragraph or line. */
1019
+ function selectionSpansLines(sel: Selection): boolean {
1020
+ if (sel.isCollapsed || sel.rangeCount === 0 || !editorEl) return false;
1021
+ const range = sel.getRangeAt(0);
1022
+ const blockOf = (n: Node) =>
1023
+ (n instanceof Element ? n : n.parentElement)?.closest(LINE_BLOCKS) ?? editorEl;
1024
+ if (blockOf(range.startContainer) !== blockOf(range.endContainer)) return true;
1025
+ return range.cloneContents().querySelector('br') !== null;
1026
+ }
1027
+
813
1028
  const LINE_BLOCKS = 'p, div, li, td, th, h1, h2, h3, h4, h5, h6, blockquote';
814
1029
 
815
1030
  /** The first tab of the caret's line, if the line starts with one: its text node and offset. */
@@ -1147,6 +1362,18 @@
1147
1362
  border-radius: 0 var(--radius-sm, 5px) var(--radius-sm, 5px) 0;
1148
1363
  }
1149
1364
 
1365
+ /* The indent Chromium, WebKit and Gmail paste (border: none) is an indent, not a quotation:
1366
+ the RTF writes it plain, so it shows plain here too. */
1367
+ .ink-content :global(blockquote[style*='border: none']),
1368
+ .ink-content :global(blockquote[style*='border:none']),
1369
+ .ink-content :global(blockquote[style*='border-style: none']),
1370
+ .ink-content :global(blockquote[style*='border-left: none']) {
1371
+ font-style: normal;
1372
+ color: inherit;
1373
+ background: none;
1374
+ border-radius: 0;
1375
+ }
1376
+
1150
1377
  .ink-content :global(pre) {
1151
1378
  background: var(--ink, #1a1714);
1152
1379
  color: #e8e2da;
@@ -96,6 +96,18 @@
96
96
 
97
97
  <div class="toolbar-divider"></div>
98
98
 
99
+ <!-- Indent -->
100
+ <div class="toolbar-group">
101
+ <ToolbarButton title="Decrease indent (Ctrl+[)" onclick={() => exec('outdent')}>
102
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="5" x2="21" y2="5"/><line x1="11" y1="10" x2="21" y2="10"/><line x1="11" y1="14" x2="21" y2="14"/><line x1="3" y1="19" x2="21" y2="19"/><polyline points="7 9 4 12 7 15"/></svg>
103
+ </ToolbarButton>
104
+ <ToolbarButton title="Increase indent (Ctrl+])" onclick={() => exec('indent')}>
105
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="5" x2="21" y2="5"/><line x1="11" y1="10" x2="21" y2="10"/><line x1="11" y1="14" x2="21" y2="14"/><line x1="3" y1="19" x2="21" y2="19"/><polyline points="4 9 7 12 4 15"/></svg>
106
+ </ToolbarButton>
107
+ </div>
108
+
109
+ <div class="toolbar-divider"></div>
110
+
99
111
  <!-- Insert -->
100
112
  <div class="toolbar-group">
101
113
  <ToolbarButton title="Insert link (Ctrl+K)" onclick={oninsertlink}>
@@ -287,9 +287,10 @@ function imageBody(el) {
287
287
  const label = el.getAttribute('alt') || el.getAttribute('src') || 'image';
288
288
  return `\\i [Image: ${escapeRtf(label)}]\\i0 `;
289
289
  }
290
- /** \ql / \qc / \qr for a figure's text-align. */
290
+ /** \ql / \qc / \qr / \qj for a block's text-align. */
291
291
  function alignControl(el) {
292
- const align = (el.style?.textAlign || '').toLowerCase();
292
+ // Firefox's Center writes <p align="center">, not a style.
293
+ const align = (el.style?.textAlign || el.getAttribute?.('align') || '').toLowerCase();
293
294
  if (align === 'center')
294
295
  return '\\qc';
295
296
  if (align === 'right')
@@ -381,6 +382,22 @@ export function estimateRtfBytes(editorEl) {
381
382
  // A tab that shows is written as "\tab " (5) and counted as 1; counting every tab that way
382
383
  // can only overestimate.
383
384
  total += ((editorEl.textContent || '').match(/\t/g)?.length ?? 0) * 4;
385
+ // A block's alignment (\qc, 3) and left indent (\liN, up to 7) are written per paragraph,
386
+ // for every block inside an indented one too: count 12 for each block that could carry them.
387
+ for (const block of Array.from(editorEl.querySelectorAll('p, div, li, h1, h2, h3, h4, h5, h6, pre, blockquote'))) {
388
+ if (block.closest('[style*="margin"], [style*="text-align"], [align]'))
389
+ total += 12;
390
+ }
391
+ // Each paragraph's formatting, worked out once: a blank line looks at the one before it.
392
+ const formatCache = new Map();
393
+ const ownFormat = (el) => {
394
+ let format = formatCache.get(el);
395
+ if (format === undefined) {
396
+ format = `${alignOf(el)}${paragraphControls(el, leftMarginTwips(el))}`;
397
+ formatCache.set(el, format);
398
+ }
399
+ return format;
400
+ };
384
401
  for (const el of Array.from(editorEl.querySelectorAll('*'))) {
385
402
  const tag = el.tagName.toLowerCase();
386
403
  total += BLOCK_OVERHEAD_BYTES[tag] ?? 0;
@@ -396,6 +413,15 @@ export function estimateRtfBytes(editorEl) {
396
413
  // writes one paragraph per item, so the item is counted, not the list.
397
414
  if (CELL_PARAGRAPH_TAGS.has(tag) && el.closest('td, th'))
398
415
  total += 6;
416
+ // A paragraph's own formatting costs its controls, and a blank line after one restates
417
+ // \pard (5); counting both on every such paragraph can only overestimate. The indent of
418
+ // the blocks around it is counted above.
419
+ if ((tag === 'p' || tag === 'div') && !el.closest('td, th')) {
420
+ const para = ownFormat(el);
421
+ const prev = el.previousElementSibling;
422
+ if (para || (prev && formatCache.get(prev)))
423
+ total += para.length + 6;
424
+ }
399
425
  // Every cell in a row with a header cell carries \clbrdrb\brdrs.
400
426
  if (tag === 'td' && el.parentElement?.querySelector(':scope > th'))
401
427
  total += 14;
@@ -527,7 +553,8 @@ export function htmlToRtf(editorEl, options = {}) {
527
553
  size: bodySize,
528
554
  color: 0,
529
555
  script: null,
530
- mono: false
556
+ mono: false,
557
+ indent: 0
531
558
  });
532
559
  const rtf = '{\\rtf1\\ansi\\ansicpg1252\\deff0' +
533
560
  fontTable +
@@ -570,6 +597,8 @@ function walkChildren(parent, ctx) {
570
597
  const tabsShow = ctx.inPre || showsTabs(node);
571
598
  if (!tabsShow && COLLAPSIBLE_WHITESPACE.test(text) && besideBlock(node))
572
599
  continue;
600
+ if (!ctx.inPre)
601
+ rtf += restateAfterBlock(node, ctx);
573
602
  if (ctx.inPre) {
574
603
  // Split before escaping — escapeRtf collapses newlines, so the
575
604
  // line structure a <pre> block depends on has to become \line
@@ -585,21 +614,24 @@ function walkChildren(parent, ctx) {
585
614
  continue;
586
615
  const el = node;
587
616
  const tag = el.tagName.toLowerCase();
617
+ // A picture directly under the root writes its own paragraph.
618
+ if (!isBlock(el) && !(tag === 'img' && el.parentNode === ctx.root))
619
+ rtf += restateAfterBlock(el, ctx);
588
620
  switch (tag) {
589
621
  // Heading sizes keep their ratio to the body (HEADING_SCALE).
590
622
  case 'h1': {
591
623
  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 `;
624
+ rtf += `\\pard${inCell(ctx)}${paragraphLayout(el, ctx)}\\f0\\fs${size}\\b ${walkChildren(el, { ...ctx, bold: true, size })}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size}\\par `;
593
625
  break;
594
626
  }
595
627
  case 'h2': {
596
628
  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 `;
629
+ rtf += `\\pard${inCell(ctx)}${paragraphLayout(el, ctx)}\\f0\\fs${size}\\b ${walkChildren(el, { ...ctx, bold: true, size })}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size}\\par `;
598
630
  break;
599
631
  }
600
632
  case 'h3': {
601
633
  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 `;
634
+ rtf += `\\pard${inCell(ctx)}${paragraphLayout(el, ctx)}\\f0\\fs${size}\\b ${walkChildren(el, { ...ctx, bold: true, size })}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size}\\par `;
603
635
  break;
604
636
  }
605
637
  case 'p':
@@ -613,9 +645,11 @@ function walkChildren(parent, ctx) {
613
645
  // the two lines run together.
614
646
  const afterLooseText = followsInlineContent(el);
615
647
  if (ctx.inTableCell) {
648
+ // Alignment or an indent needs a paragraph of its own, even as the cell's first.
649
+ const layout = paragraphLayout(el, ctx);
616
650
  const restate = afterLooseText
617
- ? '\\par \\pard\\intbl '
618
- : el.previousElementSibling ? '\\pard\\intbl ' : '';
651
+ ? `\\par \\pard\\intbl${layout} `
652
+ : el.previousElementSibling || layout ? `\\pard\\intbl${layout} ` : '';
619
653
  if (isBlankLine(el)) {
620
654
  rtf += `${restate}\\par `;
621
655
  break;
@@ -627,17 +661,38 @@ function walkChildren(parent, ctx) {
627
661
  : `${restate}${inner}\\par `;
628
662
  break;
629
663
  }
664
+ // A <div> that holds blocks (pasted content wraps paragraphs in one) is not a
665
+ // paragraph itself: each block inside writes its own \\pard, which would drop the
666
+ // div's indent, and the div's own \\par would add a blank line. Its left margin is
667
+ // carried into the blocks instead, and loose text in it gets a paragraph.
668
+ if (tag === 'div' && Array.from(el.children).some(isBlock)) {
669
+ const indent = ctx.indent + leftMarginTwips(el);
670
+ const colorIdx = colorIndexOf(el, ctx);
671
+ const inner = { ...ctx, indent, color: colorIdx ?? ctx.color };
672
+ const lead = startsWithInline(el) ? `\\pard${liControl(indent)} ` : '';
673
+ const tail = endsWithInline(el) ? '\\par ' : '';
674
+ const colorPrefix = colorIdx != null ? `\\cf${colorIdx} ` : '';
675
+ const colorSuffix = colorIdx != null ? `\\cf${ctx.color} ` : '';
676
+ rtf += `${afterLooseText ? '\\par ' : ''}${lead}${colorPrefix}${walkChildren(el, inner)}${colorSuffix}${tail}`;
677
+ break;
678
+ }
679
+ // The paragraph's alignment, indents, spacing, keep-with-next and tab stops, if it
680
+ // sets any.
681
+ const para = paragraphFormat(el, ctx);
630
682
  // A <p> with no children or only a single <br> is a blank line —
631
683
  // emit a bare \par rather than \pard \line\par, which adds an extra line.
684
+ // A bare \par keeps the formatting of the paragraph before it, so a blank line after a
685
+ // formatted paragraph, or with formatting of its own, restates \pard.
632
686
  if (isBlankLine(el)) {
633
- rtf += afterLooseText ? '\\par \\par ' : '\\par ';
687
+ const reset = para || followsFormattedParagraph(el, ctx) ? `\\pard${para} ` : '';
688
+ rtf += `${afterLooseText ? '\\par ' : ''}${reset}\\par `;
634
689
  break;
635
690
  }
636
691
  const colorIdx = colorIndexOf(el, ctx);
637
692
  const inlineRtf = walkChildren(el, colorIdx != null ? { ...ctx, color: colorIdx } : ctx);
638
693
  const colorPrefix = colorIdx != null ? `\\cf${colorIdx} ` : '';
639
694
  const colorSuffix = colorIdx != null ? `\\cf${ctx.color} ` : '';
640
- rtf += `${afterLooseText ? '\\par ' : ''}\\pard ${colorPrefix}${inlineRtf}${colorSuffix}\\par `;
695
+ rtf += `${afterLooseText ? '\\par ' : ''}\\pard${para} ${colorPrefix}${inlineRtf}${colorSuffix}\\par `;
641
696
  break;
642
697
  }
643
698
  case 'table': {
@@ -677,12 +732,25 @@ function walkChildren(parent, ctx) {
677
732
  }
678
733
  break;
679
734
  }
680
- case 'blockquote':
681
- rtf += `\\pard${inCell(ctx)}\\li720\\i ${walkChildren(el, { ...ctx, italic: true })}${ctx.italic ? '' : '\\i0'}\\par `;
735
+ case 'blockquote': {
736
+ // The browser's Indent wraps the lines in a blockquote with a left margin and
737
+ // border: none (Chromium, WebKit, Gmail): that is an indent, not a quotation, so it
738
+ // is not italic. A quotation is indented half an inch, plus any margin of its own.
739
+ // Either way the blocks inside carry the indent, and loose text gets a paragraph.
740
+ const quote = !isIndentBlockquote(el);
741
+ const indent = ctx.indent + leftMarginTwips(el) + (quote ? 720 : 0);
742
+ const inner = { ...ctx, indent, italic: ctx.italic || quote };
743
+ const lead = startsWithInline(el) ? `\\pard${inCell(ctx)}${liControl(indent)}` : '';
744
+ const tail = endsWithInline(el) ? '\\par ' : '';
745
+ const content = walkChildren(el, inner);
746
+ const italicOn = quote && !ctx.italic;
747
+ const italicOff = italicOn ? (tail ? '\\i0' : '\\i0 ') : '';
748
+ rtf += `${lead}${italicOn ? '\\i ' : lead ? ' ' : ''}${content}${italicOff}${tail}`;
682
749
  break;
750
+ }
683
751
  case 'pre': {
684
752
  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 `;
753
+ rtf += `\\pard${inCell(ctx)}${liControl(ctx.indent + leftMarginTwips(el))}\\f1\\fs${size} ${walkChildren(el, { ...ctx, inPre: true, size })}\\f0\\fs${ctx.size}\\par `;
686
754
  break;
687
755
  }
688
756
  case 'hr':
@@ -690,16 +758,18 @@ function walkChildren(parent, ctx) {
690
758
  break;
691
759
  case 'ul': {
692
760
  const items = el.querySelectorAll(':scope > li');
693
- items.forEach((li) => {
694
- rtf += `\\pard${inCell(ctx)}\\li720\\fi-360\\bullet\\tab ${walkChildren(li, ctx)}\\par `;
761
+ const li = liControl(ctx.indent + leftMarginTwips(el) + 720);
762
+ items.forEach((item) => {
763
+ rtf += `\\pard${inCell(ctx)}${li}\\fi-360\\bullet\\tab ${walkChildren(item, ctx)}\\par `;
695
764
  });
696
765
  break;
697
766
  }
698
767
  case 'ol': {
699
768
  let counter = 1;
700
769
  const items = el.querySelectorAll(':scope > li');
701
- items.forEach((li) => {
702
- rtf += `\\pard${inCell(ctx)}\\li720\\fi-360 ${counter}.\\tab ${walkChildren(li, ctx)}\\par `;
770
+ const li = liControl(ctx.indent + leftMarginTwips(el) + 720);
771
+ items.forEach((item) => {
772
+ rtf += `\\pard${inCell(ctx)}${li}\\fi-360 ${counter}.\\tab ${walkChildren(item, ctx)}\\par `;
703
773
  counter++;
704
774
  });
705
775
  break;
@@ -764,7 +834,7 @@ function walkChildren(parent, ctx) {
764
834
  case 'figure': {
765
835
  const img = el.querySelector('img');
766
836
  const caption = (el.querySelector('figcaption')?.textContent || '').trim();
767
- const align = alignControl(el);
837
+ const align = `${alignControl(el)}${liControl(ctx.indent + leftMarginTwips(el))}`;
768
838
  if (img)
769
839
  rtf += `\\pard${inCell(ctx)}${align} ${imageBody(img)}\\par `;
770
840
  else
@@ -851,6 +921,29 @@ function followsInlineContent(el) {
851
921
  return true;
852
922
  return prev.nodeType === Node.ELEMENT_NODE && !isBlock(prev);
853
923
  }
924
+ /** Blocks whose last paragraph always carries an indent or alignment of its own. */
925
+ const FORMATTED_BLOCK_TAGS = new Set(['ul', 'ol', 'blockquote', 'figure', 'hr']);
926
+ /**
927
+ * Loose text or an inline element right after a block has no paragraph of its own, and would
928
+ * keep that block's alignment and indent (a centered line's \qc, a list's \li). Start a plain
929
+ * one, at the indent of the blocks around it. After a block with no formatting of its own,
930
+ * nothing is written, as before.
931
+ */
932
+ function restateAfterBlock(node, ctx) {
933
+ let prev = node.previousSibling;
934
+ while (prev && prev.nodeType === Node.TEXT_NODE && COLLAPSIBLE_WHITESPACE.test(prev.textContent || '')) {
935
+ prev = prev.previousSibling;
936
+ }
937
+ if (!isBlock(prev))
938
+ return '';
939
+ const block = prev;
940
+ const tag = block.tagName.toLowerCase();
941
+ const formatted = FORMATTED_BLOCK_TAGS.has(tag) ||
942
+ (['p', 'div'].includes(tag) && (ctx.inTableCell ? paragraphLayout(block, ctx) : paragraphFormat(block, ctx)) !== '') ||
943
+ (['h1', 'h2', 'h3'].includes(tag) && paragraphLayout(block, ctx) !== '') ||
944
+ (tag === 'pre' && ctx.indent + leftMarginTwips(block) > 0);
945
+ return formatted ? `\\pard${inCell(ctx)}${liControl(ctx.indent)} ` : '';
946
+ }
854
947
  /**
855
948
  * The cell's own \par ends its last paragraph, so that paragraph's mark is dropped. Only a
856
949
  * real control word: "\par " preceded by an odd run of backslashes is escaped text.
@@ -863,6 +956,126 @@ function withoutTrailingPar(content) {
863
956
  slashes++;
864
957
  return slashes % 2 === 0 ? content.slice(0, -5) : content;
865
958
  }
959
+ // ── Paragraph formatting ──
960
+ const TWIPS_PER_UNIT = { in: 1440, pt: 20, cm: 1440 / 2.54, mm: 144 / 2.54, px: TWIPS_PER_PX };
961
+ /**
962
+ * A CSS length in whole twips, or null when it cannot be read: a unit other than in, pt, cm, mm or
963
+ * px, a percentage, a keyword, or a negative value where one is not allowed.
964
+ */
965
+ function lengthTwips(value, allowNegative = false) {
966
+ const m = (value ?? '').trim().toLowerCase().match(/^(-?\d+(?:\.\d+)?|-?\.\d+)(in|pt|cm|mm|px)$/);
967
+ if (!m)
968
+ return null;
969
+ const twips = Math.round(parseFloat(m[1]) * TWIPS_PER_UNIT[m[2]]);
970
+ if (twips < 0 && !allowNegative)
971
+ return null;
972
+ return twips;
973
+ }
974
+ /**
975
+ * An element's own left margin in twips, from its inline style: what the browser's Indent sets
976
+ * (Firefox puts margin-left on the paragraph; Chromium and WebKit on a wrapping blockquote).
977
+ * Units a reader cannot pin to a length (%, em) count as none.
978
+ */
979
+ function leftMarginTwips(el) {
980
+ return lengthTwips(el.style?.marginLeft) ?? 0;
981
+ }
982
+ /**
983
+ * The indent shape Chromium, WebKit and Gmail write: a blockquote with border: none, where a
984
+ * quotation keeps its border. The editor's Indent reads it the same way.
985
+ */
986
+ function isIndentBlockquote(el) {
987
+ return el.style?.borderLeftStyle === 'none';
988
+ }
989
+ /** \liN for a left indent in twips, or nothing when there is none. */
990
+ function liControl(twips) {
991
+ return twips > 0 ? `\\li${twips}` : '';
992
+ }
993
+ /** \qc, \qr or \qj; left is the default and is not written. */
994
+ function alignOf(el) {
995
+ const align = alignControl(el);
996
+ return align === '\\ql' ? '' : align;
997
+ }
998
+ /**
999
+ * A heading's, or a paragraph's inside a table cell: its alignment, and \liN for the indent of
1000
+ * the blocks around it plus its own margin.
1001
+ */
1002
+ function paragraphLayout(el, ctx) {
1003
+ return `${alignOf(el)}${liControl(ctx.indent + leftMarginTwips(el))}`;
1004
+ }
1005
+ /**
1006
+ * A <p> or <div>'s formatting outside a table cell: its alignment, then paragraphControls with the
1007
+ * indent of the blocks around it plus its own margin.
1008
+ */
1009
+ function paragraphFormat(el, ctx) {
1010
+ return `${alignOf(el)}${paragraphControls(el, ctx.indent + leftMarginTwips(el))}`;
1011
+ }
1012
+ /**
1013
+ * The RTF paragraph controls for a <p> or <div>'s own formatting, or '' when it sets none:
1014
+ *
1015
+ * | HTML | RTF |
1016
+ * |--------------------------------------------------|-------------------|
1017
+ * | data-rtf-tab-stops="1.75in" (comma-separated) | \tx2520 |
1018
+ * | margin-left: 1.75in (the left indent, given) | \li2520 |
1019
+ * | text-indent: -1.75in | \fi-2520 |
1020
+ * | margin-top: 5pt / margin-bottom: 5pt | \sb100 / \sa100 |
1021
+ * | break-after: avoid, or page-break-after: avoid | \keepn |
1022
+ *
1023
+ * CSS has no absolute tab stop, hence the data- attribute. A value that cannot be read writes
1024
+ * nothing, and so does zero, which is what \pard already sets. Not written inside a table cell,
1025
+ * where the cell declares its own paragraph.
1026
+ */
1027
+ function paragraphControls(el, leftTwips) {
1028
+ let out = '';
1029
+ const stops = (el.getAttribute('data-rtf-tab-stops') ?? '')
1030
+ .split(',')
1031
+ .map((v) => lengthTwips(v))
1032
+ .filter((t) => t != null && t > 0);
1033
+ for (const t of Array.from(new Set(stops)).sort((a, b) => a - b))
1034
+ out += `\\tx${t}`;
1035
+ out += liControl(leftTwips);
1036
+ const style = el.style;
1037
+ if (!style)
1038
+ return out;
1039
+ const fi = lengthTwips(style.textIndent, true);
1040
+ if (fi)
1041
+ out += `\\fi${fi}`;
1042
+ const sb = lengthTwips(style.marginTop);
1043
+ if (sb)
1044
+ out += `\\sb${sb}`;
1045
+ const sa = lengthTwips(style.marginBottom);
1046
+ if (sa)
1047
+ out += `\\sa${sa}`;
1048
+ const keep = (prop) => style.getPropertyValue(prop).trim() === 'avoid';
1049
+ if (keep('break-after') || keep('page-break-after'))
1050
+ out += '\\keepn';
1051
+ return out;
1052
+ }
1053
+ /** Whether the nearest element before this one is a <p> or <div> with formatting of its own. */
1054
+ function followsFormattedParagraph(el, ctx) {
1055
+ const prev = el.previousElementSibling;
1056
+ if (!prev)
1057
+ return false;
1058
+ const tag = prev.tagName.toLowerCase();
1059
+ return (tag === 'p' || tag === 'div') && paragraphFormat(prev, ctx) !== '';
1060
+ }
1061
+ /** Whether a container's first (or last) content is loose text or an inline element, not a block. */
1062
+ function startsWithInline(el) {
1063
+ return edgeIsInline(el, 'first');
1064
+ }
1065
+ function endsWithInline(el) {
1066
+ return edgeIsInline(el, 'last');
1067
+ }
1068
+ function edgeIsInline(el, edge) {
1069
+ const nodes = Array.from(el.childNodes);
1070
+ if (edge === 'last')
1071
+ nodes.reverse();
1072
+ for (const n of nodes) {
1073
+ if (n.nodeType === Node.TEXT_NODE && COLLAPSIBLE_WHITESPACE.test(n.textContent || ''))
1074
+ continue;
1075
+ return !isBlock(n);
1076
+ }
1077
+ return false;
1078
+ }
866
1079
  /** \intbl for a paragraph a block writes inside a table cell, so it stays in the cell. */
867
1080
  function inCell(ctx) {
868
1081
  return ctx.inTableCell ? '\\intbl' : '';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "svelte-rtf-editor",
3
- "version": "1.6.0",
3
+ "version": "1.7.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",