svelte-rtf-editor 1.8.3 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,17 +2,25 @@
2
2
  * HTML to RTF converter
3
3
  *
4
4
  * Walks a contenteditable DOM tree and produces a valid RTF 1.x string.
5
- * Supports: a document font and body size (Arial 12 pt by default, set with
6
- * RtfWriteOptions), bold, italic, underline, strikethrough, font sizes (h1–h3),
7
- * foreground colors (\cf), paragraphs, bullet/numbered lists, blockquotes,
8
- * code blocks, hyperlinks, images (embedded as \pict picture groups with
9
- * their captions), horizontal rules, line breaks, and Unicode characters.
5
+ * Supports: a document font and body size (DEFAULT_FONT_FAMILY at DEFAULT_FONT_SIZE
6
+ * points by default, set with RtfWriteOptions), bold, italic, underline, strikethrough, font sizes, headings
7
+ * (h1–h6), foreground colors (\cf), paragraphs with their alignment and indents,
8
+ * bullet/numbered lists and lists inside them, blockquotes, code blocks,
9
+ * hyperlinks, tables with merged cells, images (embedded as \pict picture groups
10
+ * with their captions), horizontal rules, page breaks, line breaks, and Unicode
11
+ * characters.
10
12
  *
11
13
  * Background color is intentionally not written — RTF highlight support
12
14
  * is inconsistent across viewers (TextEdit uses \AppleHighlight, not \highlight).
13
15
  */
14
- /** Font used when no fontFamily is given. */
15
- export const DEFAULT_FONT_FAMILY = 'Arial';
16
+ import { tableModel, columnShares, tableRowsInOrder, rowCells } from './table-model.js';
17
+ /**
18
+ * Font used when no fontFamily is given: what the editor and the viewer show, and what the RTF
19
+ * names. This is the one place the default is named; the size estimate, the components and the
20
+ * tests follow it. An application that wants another font does not change this: it passes
21
+ * `fontFamily` to the editor, to the viewer and to htmlToRtf.
22
+ */
23
+ export const DEFAULT_FONT_FAMILY = 'Segoe UI';
16
24
  /** Body text size, in points, used when no fontSize is given. */
17
25
  export const DEFAULT_FONT_SIZE = 12;
18
26
  /** Largest font size RTF readers accept (Word's limit), in points. */
@@ -22,25 +30,56 @@ const MAX_FONT_SIZE = 1638;
22
30
  * and h3 14 pt. The parser reads headings back with the same ratios.
23
31
  */
24
32
  export const HEADING_SCALE = { h1: 2, h2: 1.5, h3: 7 / 6 };
25
- /** Code blocks are set slightly smaller than the body: 10 pt at 12 pt. */
26
- const PRE_SCALE = 5 / 6;
33
+ /**
34
+ * Every heading level's size as a multiple of the body size. The editor offers h1 to h3; h4, h5
35
+ * and h6 arrive in pasted text and are written at the sizes a browser shows them: the body
36
+ * size, 0.83 and 0.67 of it.
37
+ */
38
+ const ALL_HEADING_SCALES = { ...HEADING_SCALE, h4: 1, h5: 5 / 6, h6: 2 / 3 };
39
+ const HEADING_TAGS = new Set(Object.keys(ALL_HEADING_SCALES));
40
+ /**
41
+ * Code blocks are set slightly smaller than the body: 10 pt at 12 pt. The parser reads a code
42
+ * block back by the same ratio.
43
+ */
44
+ export const PRE_SCALE = 5 / 6;
45
+ /**
46
+ * The color of link text. A document with a link carries it as the first entry of its color
47
+ * table, so a link can be told from underlined text; the parser drops it again inside a link,
48
+ * where the <a> already says it.
49
+ */
50
+ export const LINK_COLOR = { r: 0, g: 0, b: 255 };
27
51
  /** 1 px at 96 dpi = 15 twips (1 twip = 1/1440 in). */
28
52
  const TWIPS_PER_PX = 15;
53
+ /**
54
+ * The longest length written, in twips: 22 inches, the largest page Word has. An indent, a tab
55
+ * stop or a picture's size beyond it means nothing on any page, and a number of ten digits or
56
+ * more is past what RTF's 32-bit parameters hold.
57
+ */
58
+ const MAX_TWIPS = 31680;
59
+ /**
60
+ * The deepest nesting of elements written element by element. A browser's HTML parser stops at
61
+ * 512, so only a DOM built by script goes deeper; a few thousand deep, walking it one call per
62
+ * element ran out of stack. Past this depth an element is written as its text.
63
+ */
64
+ const MAX_ELEMENT_DEPTH = 600;
29
65
  // ── Color helpers ──
30
66
  function parseColor(colorStr) {
31
67
  if (!colorStr)
32
68
  return null;
33
69
  const s = colorStr.trim().toLowerCase();
34
70
  // rgb(r, g, b) or rgba(r, g, b, a)
71
+ // (A component is 0 to 255: a color table that says \red999 is not one every reader accepts.)
35
72
  const rgbMatch = s.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
36
73
  if (rgbMatch) {
37
- return { r: +rgbMatch[1], g: +rgbMatch[2], b: +rgbMatch[3] };
74
+ const part = (digits) => Math.min(255, +digits);
75
+ return { r: part(rgbMatch[1]), g: part(rgbMatch[2]), b: part(rgbMatch[3]) };
38
76
  }
39
- // Hex
40
- const hexMatch = s.match(/^#([0-9a-f]{3,8})$/);
77
+ // Hex: #rgb, #rgba, #rrggbb or #rrggbbaa, and no other length. "#abcd" read as six digits
78
+ // had no blue, and was written to the color table as \blueNaN.
79
+ const hexMatch = s.match(/^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/);
41
80
  if (hexMatch) {
42
81
  let hex = hexMatch[1];
43
- if (hex.length === 3)
82
+ if (hex.length <= 4)
44
83
  hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
45
84
  return {
46
85
  r: parseInt(hex.substring(0, 2), 16),
@@ -79,7 +118,17 @@ function escapeRtf(text) {
79
118
  for (let i = 0; i < source.length; i++) {
80
119
  const ch = source[i];
81
120
  const code = source.charCodeAt(i);
82
- if (ch === '\\')
121
+ if (code < 32 || code === 127) {
122
+ // A control character is not text. Written as it is, it reaches the receiving
123
+ // system as a raw byte, and 0x0B and 0x1C are the bytes that start and end an HL7
124
+ // message on the wire. A tab is passed through (see escapeTabs); a vertical tab
125
+ // or a form feed, which a browser shows as a space, is one; the rest are dropped.
126
+ if (code === 9)
127
+ out += ch;
128
+ else if (code === 11 || code === 12)
129
+ out += ' ';
130
+ }
131
+ else if (ch === '\\')
83
132
  out += '\\\\';
84
133
  else if (ch === '{')
85
134
  out += '\\{';
@@ -121,6 +170,75 @@ function showsTabs(node) {
121
170
  }
122
171
  return false;
123
172
  }
173
+ /**
174
+ * Whether a text node's line breaks show as line breaks: it sits inside an element whose inline
175
+ * white-space keeps them (pre-wrap is what many editors and mail programs set on pasted text).
176
+ */
177
+ function showsLineBreaks(node) {
178
+ for (let el = node.parentElement; el; el = el.parentElement) {
179
+ const ws = el.style?.whiteSpace;
180
+ if (ws)
181
+ return ws === 'pre' || ws === 'pre-wrap' || ws === 'pre-line' || ws === 'break-spaces';
182
+ }
183
+ return false;
184
+ }
185
+ // ── Elements that are not shown ──
186
+ /** Elements whose content is never shown: a stylesheet, a script, a template. */
187
+ const UNSHOWN_TAGS = new Set(['style', 'script', 'template', 'noscript', 'head', 'title', 'meta', 'link', 'base']);
188
+ /**
189
+ * Whether an element is not shown on screen, so that nothing in it is written: a pasted page's
190
+ * <style> or <script>, an element with `hidden`, display: none or visibility: hidden, and Word's
191
+ * hidden text (mso-hide: all). What the person does not see must not reach the report.
192
+ */
193
+ function isHidden(el) {
194
+ if (UNSHOWN_TAGS.has(el.tagName.toLowerCase()))
195
+ return true;
196
+ if (el.hasAttribute('hidden'))
197
+ return true;
198
+ const style = el.style;
199
+ if (style?.display === 'none')
200
+ return true;
201
+ // visibility: hidden hides an element's text but not what an element inside it shows again
202
+ // with visibility: visible. Only without one of those is the whole of it left out; with
203
+ // one, each piece of text is asked (isUnseen).
204
+ if (style?.visibility === 'hidden' && !Array.from(el.querySelectorAll('[style]')).some((d) => d.style?.visibility === 'visible')) {
205
+ return true;
206
+ }
207
+ return /mso-hide\s*:\s*all/i.test(el.getAttribute('style') ?? '');
208
+ }
209
+ /** Whether a text node or a picture sits in an element with visibility: hidden that nothing nearer shows again. */
210
+ function isUnseen(node) {
211
+ for (let el = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement; el; el = el.parentElement) {
212
+ const visibility = el.style?.visibility;
213
+ if (visibility === 'visible')
214
+ return false;
215
+ if (visibility === 'hidden')
216
+ return true;
217
+ }
218
+ return false;
219
+ }
220
+ /** The text of an element that the screen shows: without what is hidden in it. */
221
+ function shownText(el) {
222
+ let text = '';
223
+ for (const child of Array.from(el.childNodes)) {
224
+ if (child.nodeType === Node.TEXT_NODE) {
225
+ if (!isUnseen(child))
226
+ text += child.textContent || '';
227
+ }
228
+ else if (child.nodeType === Node.ELEMENT_NODE && !isHidden(child)) {
229
+ text += shownText(child);
230
+ }
231
+ }
232
+ return text;
233
+ }
234
+ /** Whether an element, or anything around it up to `root`, is not shown: a cell in a hidden row. */
235
+ function hiddenWithin(el, root) {
236
+ for (let at = el; at && at !== root; at = at.parentElement) {
237
+ if (isHidden(at))
238
+ return true;
239
+ }
240
+ return false;
241
+ }
124
242
  // ── Image helpers ──
125
243
  const B64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
126
244
  const B64_LOOKUP = (() => {
@@ -242,6 +360,12 @@ function displaySize(el, natural) {
242
360
  let h = parsePx(el.style?.height) || (Number.isFinite(attrH) ? attrH : 0);
243
361
  if (!h)
244
362
  h = nw && nh ? Math.round((w * nh) / nw) : nh;
363
+ // No wider or taller than the largest page (MAX_TWIPS), keeping its shape: a width of
364
+ // 99999999999 in pasted markup was written as a \picwgoal no reader can use.
365
+ const most = MAX_TWIPS / TWIPS_PER_PX;
366
+ const over = Math.max(w, h) / most;
367
+ if (over > 1)
368
+ return { w: Math.max(1, Math.round(w / over)), h: Math.max(1, Math.round(h / over)) };
245
369
  return { w, h };
246
370
  }
247
371
  /**
@@ -254,7 +378,8 @@ function pictureRtf(el) {
254
378
  // Accept any image data URL and let the bytes decide the format — the label
255
379
  // is not trustworthy, and a correctly-labelled PNG is not the only way to
256
380
  // arrive at PNG bytes.
257
- const m = src.match(/^data:image\/[a-z0-9.+-]+;base64,([\s\S]+)$/i);
381
+ // (A data URL may carry parameters before ";base64": "data:image/png;name=scan.png;base64,".)
382
+ const m = src.match(/^data:image\/[a-z0-9.+-]+(?:;[^;,]*)*;base64,([\s\S]+)$/i);
258
383
  if (!m)
259
384
  return '';
260
385
  const bytes = base64ToBytes(m[1]);
@@ -284,20 +409,30 @@ function imageBody(el) {
284
409
  const pict = pictureRtf(el);
285
410
  if (pict)
286
411
  return pict;
287
- const label = el.getAttribute('alt') || el.getAttribute('src') || 'image';
412
+ // Its description, or else its address. Never picture data: a picture that cannot be
413
+ // embedded and has no description was written as its whole data URL, hundreds of
414
+ // kilobytes of base64 in the text of the report.
415
+ const src = el.getAttribute('src') || '';
416
+ const label = el.getAttribute('alt') || (/^\s*data:/i.test(src) ? '' : src) || 'image';
288
417
  return `\\i [Image: ${escapeRtf(label)}]\\i0 `;
289
418
  }
290
- /** \ql / \qc / \qr / \qj for a block's text-align. */
291
- function alignControl(el) {
419
+ /** \ql / \qc / \qr / \qj for a block's own text-align, or null when it sets none. */
420
+ function ownAlign(el) {
292
421
  // Firefox's Center writes <p align="center">, not a style.
293
- const align = (el.style?.textAlign || el.getAttribute?.('align') || '').toLowerCase();
422
+ const align = (el.style?.textAlign || el.getAttribute?.('align') || (el.tagName === 'CENTER' ? 'center' : '')).toLowerCase();
294
423
  if (align === 'center')
295
424
  return '\\qc';
296
- if (align === 'right')
425
+ if (align === 'right' || align === 'end')
297
426
  return '\\qr';
298
427
  if (align === 'justify')
299
428
  return '\\qj';
300
- return '\\ql';
429
+ if (align === 'left' || align === 'start')
430
+ return '\\ql';
431
+ return null;
432
+ }
433
+ /** \ql / \qc / \qr / \qj for a block's text-align; left when it sets none. */
434
+ function alignControl(el) {
435
+ return ownAlign(el) ?? '\\ql';
301
436
  }
302
437
  /** Decoded byte length of a base64 payload, without decoding it. */
303
438
  function base64ByteLength(base64) {
@@ -305,10 +440,10 @@ function base64ByteLength(base64) {
305
440
  return Math.max(0, Math.floor((base64.length * 3) / 4) - padding);
306
441
  }
307
442
  /**
308
- * Bytes of RTF header, font table and colour table that precede the body, with
309
- * the default font. Another font name changes it by the difference in length.
443
+ * Bytes of RTF header, font table and colour table that precede the body, without
444
+ * the name of the document font, which is counted by its own length.
310
445
  */
311
- const RTF_PREAMBLE_BYTES = 165;
446
+ const RTF_PREAMBLE_BYTES = 160;
312
447
  /** Control words wrapping one \pict group. */
313
448
  const PICTURE_OVERHEAD_BYTES = 80;
314
449
  /**
@@ -322,20 +457,29 @@ const BLOCK_OVERHEAD_BYTES = {
322
457
  h1: 29,
323
458
  h2: 29,
324
459
  h3: 29,
460
+ h4: 29,
461
+ h5: 29,
462
+ h6: 29,
325
463
  li: 35,
326
464
  blockquote: 22,
327
465
  pre: 27,
328
466
  figure: 15,
329
467
  figcaption: 29,
468
+ caption: 20, // "\pard\intbl\qc " + "\par "
469
+ table: 8, // "\lastrow"
330
470
  tr: 45,
331
- td: 55,
332
- th: 69, // a header cell also carries \clbrdrb\brdrs
471
+ td: 51, // "{\pard\intbl \f0 \sa0 \li0 \fi0 " + "\cell}" + "\cellxNNNN", and 3 to spare
472
+ th: 65, // a header cell also carries \clbrdrb\brdrs
333
473
  // Inline formatting: the control words on either side of the text.
334
474
  b: 7, // "\b " + "\b0 "
335
475
  strong: 7,
336
476
  i: 7,
337
477
  em: 7,
478
+ cite: 7,
479
+ var: 7,
480
+ dfn: 7,
338
481
  u: 12, // "\ul " + "\ulnone "
482
+ ins: 12,
339
483
  s: 17, // "\strike " + "\strike0 "
340
484
  strike: 17,
341
485
  del: 17,
@@ -347,8 +491,22 @@ const BLOCK_OVERHEAD_BYTES = {
347
491
  ul: 0,
348
492
  ol: 0
349
493
  };
494
+ /**
495
+ * Blocks that are written as a <div> is: a paragraph when they hold text, a container when they
496
+ * hold blocks. Pasted pages are made of them, and each one not known as a block had its lines
497
+ * joined to its neighbours': a definition list read "SpecimenColonMarginsNegative".
498
+ */
499
+ const DIV_LIKE_TAGS = new Set([
500
+ 'section', 'article', 'aside', 'nav', 'header', 'footer', 'main', 'address', 'details', 'summary',
501
+ 'center', 'fieldset', 'legend', 'form', 'dl', 'dt', 'dd', 'hgroup'
502
+ ]);
503
+ /** An element's tag in lower case, with every block written as a <div> named "div". */
504
+ function tagOf(el) {
505
+ const tag = el.tagName.toLowerCase();
506
+ return DIV_LIKE_TAGS.has(tag) ? 'div' : tag;
507
+ }
350
508
  /** Elements that write a paragraph of their own, which inside a table cell carries \intbl. */
351
- const CELL_PARAGRAPH_TAGS = new Set(['p', 'div', 'h1', 'h2', 'h3', 'li', 'blockquote', 'pre', 'hr', 'figure', 'figcaption']);
509
+ const CELL_PARAGRAPH_TAGS = new Set(['p', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li', 'blockquote', 'pre', 'hr', 'figure', 'figcaption']);
352
510
  /** The field wrapper around a link, apart from its address. */
353
511
  const LINK_OVERHEAD_BYTES = '{\\field{\\*\\fldinst HYPERLINK ""}{\\fldrslt\\ul\\cf1 \\cf0\\ulnone }}'.length;
354
512
  /**
@@ -363,31 +521,64 @@ const LINK_OVERHEAD_BYTES = '{\\field{\\*\\fldinst HYPERLINK ""}{\\fldrslt\\ul\\
363
521
  * is negligible precisely when the number matters, and never more than a few
364
522
  * hundred bytes even when it does not. The output is ASCII, so bytes and
365
523
  * characters are the same number.
524
+ *
525
+ * Give it the options htmlToRtf is called with: a longer font name is part of the size, and so
526
+ * are the extra digits of a large body size.
366
527
  */
367
- export function estimateRtfBytes(editorEl) {
368
- let total = RTF_PREAMBLE_BYTES;
528
+ export function estimateRtfBytes(editorEl, options = {}) {
529
+ // The font table names the font ("\froman" is as long as "\fswiss", "\fmodern" one longer).
530
+ const font = cleanFontName(options.fontFamily);
531
+ const fontName = escapeRtf(font);
532
+ const fontClass = fontFamilyClass(font) === 'modern' ? 1 : 0;
533
+ // \fsN is counted with two digits everywhere; the largest size written is a first-level
534
+ // heading's, twice the body.
535
+ const sizeDigits = Math.max(0, String(bodyHalfPoints(options.fontSize) * 2).length - 2);
536
+ let total = RTF_PREAMBLE_BYTES + fontName.length + fontClass + sizeDigits;
369
537
  for (const img of Array.from(editorEl.querySelectorAll('img'))) {
370
538
  const src = img.getAttribute('src') || '';
371
539
  const comma = src.indexOf(',');
540
+ // A picture straight in the editor is a paragraph of its own ("\pard " and "\par ").
541
+ if (img.parentNode === editorEl)
542
+ total += 11;
543
+ // A picture that cannot be embedded costs its placeholder text.
544
+ // (As imageBody writes it: its description, or its address unless that is picture data.
545
+ // Escaping the whole data URL of every picture without a description, on each keystroke,
546
+ // was half of what a keystroke cost in a document with pictures.)
547
+ const isData = /^\s*data:/i.test(src);
548
+ const placeholder = `\\i [Image: ]\\i0 `.length + escapeRtf(img.getAttribute('alt') || (isData ? '' : src) || 'image').length;
372
549
  if (!src.startsWith('data:image/') || comma < 0) {
373
- // A picture that cannot be embedded costs its placeholder text.
374
- total += `\\i [Image: ]\\i0 `.length + escapeRtf(img.getAttribute('alt') || src || 'image').length;
550
+ total += placeholder;
375
551
  continue;
376
552
  }
377
- total += base64ByteLength(src.slice(comma + 1)) * 2 + PICTURE_OVERHEAD_BYTES;
553
+ // Picture data that is neither PNG nor JPEG is written as the placeholder too.
554
+ total += Math.max(placeholder, base64ByteLength(src.slice(comma + 1)) * 2 + PICTURE_OVERHEAD_BYTES);
378
555
  }
556
+ // A document with a link carries the link color in its color table ("\red0\green0\blue255;").
557
+ if (hasLink(editorEl))
558
+ total += 22;
559
+ const blockSelector = ['p', 'div', 'li', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'pre', 'blockquote', 'figure', 'figcaption', ...DIV_LIKE_TAGS].join(', ');
379
560
  // Text at its escaped length: a character outside ASCII costs its \uN\'3f escape,
380
561
  // six to nine bytes rather than one.
381
- total += escapeRtf(editorEl.textContent || '').length;
562
+ // (Each line break is counted, not each run of them: text is written node by node, and a
563
+ // run that crosses from one node into the next is a space in each.)
564
+ total += escapeRtf((editorEl.textContent || '').replace(/[\r\n]/g, ' ')).length;
382
565
  // A tab that shows is written as "\tab " (5) and counted as 1; counting every tab that way
383
566
  // can only overestimate.
384
567
  total += ((editorEl.textContent || '').match(/\t/g)?.length ?? 0) * 4;
385
568
  // A block's alignment (\qc, 3) and left indent (\liN, up to 7) are written per paragraph,
386
569
  // for every block inside an indented one too: count 12 for each block that could carry them.
387
570
  // A paragraph's own right indent (\\riN) and first-line indent (\\fi-N) are up to 8 more each.
388
- for (const block of Array.from(editorEl.querySelectorAll('p, div, li, h1, h2, h3, h4, h5, h6, pre, blockquote'))) {
389
- if (block.closest('[style*="margin"], [style*="text-align"], [align]'))
571
+ for (const block of Array.from(editorEl.querySelectorAll(blockSelector))) {
572
+ if (block.closest('center, [style*="margin"], [style*="text-align"], [align]'))
390
573
  total += 12;
574
+ // A quotation and a list indent what is in them with no style of their own. An item is
575
+ // counted with a three-digit indent (\li720); a level further in has four or five.
576
+ else if (block.tagName === 'LI') {
577
+ if (block.parentElement?.closest('li, blockquote, ul ul, ul ol, ol ul, ol ol'))
578
+ total += 2;
579
+ }
580
+ else if (block.parentElement?.closest('blockquote'))
581
+ total += 6; // "\li720"
391
582
  if (block.style?.marginRight)
392
583
  total += 8;
393
584
  if (block.style?.textIndent)
@@ -404,16 +595,53 @@ export function estimateRtfBytes(editorEl) {
404
595
  return format;
405
596
  };
406
597
  for (const el of Array.from(editorEl.querySelectorAll('*'))) {
407
- const tag = el.tagName.toLowerCase();
408
- total += BLOCK_OVERHEAD_BYTES[tag] ?? 0;
598
+ const tag = tagOf(el);
599
+ // A <div> that only holds blocks writes nothing of its own: its blocks are counted.
600
+ const container = tag === 'div' && Array.from(el.children).some(isBlock) && !startsWithInline(el) && !endsWithInline(el);
601
+ if (!container)
602
+ total += BLOCK_OVERHEAD_BYTES[tag] ?? 0;
603
+ // A heading and a code block each write their size and the size around them.
604
+ if (HEADING_TAGS.has(tag) || tag === 'pre')
605
+ total += 2 * sizeDigits;
606
+ // Bold, italic, a line under or through, and raised or lowered text set by a style cost
607
+ // what the tags for them do; counting each that is named can only overestimate.
608
+ const style = el.style;
609
+ if (style) {
610
+ if (style.fontWeight)
611
+ total += 7;
612
+ if (style.fontStyle)
613
+ total += 7;
614
+ if (style.textDecoration || style.textDecorationLine)
615
+ total += 12 + 17;
616
+ if (style.verticalAlign)
617
+ total += 19;
618
+ // Each line break kept by white-space is "\line " (6), as in a code block.
619
+ if (tag !== 'pre' && /^(pre|pre-wrap|pre-line|break-spaces)$/.test(style.whiteSpace)) {
620
+ total += ((el.textContent || '').match(/\r\n|\r|\n/g)?.length ?? 0) * 6;
621
+ }
622
+ }
409
623
  if (tag === 'a') {
410
624
  const target = linkTarget(el.getAttribute('href') || '');
411
625
  if (target)
412
626
  total += LINK_OVERHEAD_BYTES + escapeRtf(target).length;
413
627
  }
414
- // Each line break in a code block is written as "\line " (6) and counted as 1.
628
+ // Each line break in a code block is written as "\line " (6). It is counted as 1 with
629
+ // the text, or as nothing where it follows another: a run of them is counted there as
630
+ // one space.
415
631
  if (tag === 'pre')
416
- total += ((el.textContent || '').match(/\r\n|\r|\n/g)?.length ?? 0) * 5;
632
+ total += ((el.textContent || '').match(/\r\n|\r|\n/g)?.length ?? 0) * 6;
633
+ // A paragraph that follows loose text first ends that text's line ("\par ").
634
+ if ((tag === 'p' || tag === 'div' || BREAKS_LOOSE_TEXT.has(tag)) && followsInlineContent(el, editorEl))
635
+ total += 5;
636
+ // A heading, code block or quotation inside a list item, quotation or paragraph restates the
637
+ // paragraph around it (\pard, the indent, \par) in ways the counts above do not follow
638
+ // exactly: up to 10 more each, so the estimate stays above the real size.
639
+ if (/^(h[1-6]|pre|blockquote)$/.test(tag) && el.parentElement !== editorEl && el.parentElement?.closest('li, blockquote, p'))
640
+ total += 10;
641
+ // In a list item, text after a wrapper that ends with a block starts a paragraph again
642
+ // ("\pard\intbl\liN\fi-N ", at most 24).
643
+ if (!isBlock(el) && el.closest('li') && endsWithBlock(el))
644
+ total += 24;
417
645
  // A paragraph a block writes inside a table cell also carries \intbl (6). A list
418
646
  // writes one paragraph per item, so the item is counted, not the list.
419
647
  if (CELL_PARAGRAPH_TAGS.has(tag) && el.closest('td, th'))
@@ -427,18 +655,73 @@ export function estimateRtfBytes(editorEl) {
427
655
  if (para || (prev && formatCache.get(prev)))
428
656
  total += para.length + 6;
429
657
  }
430
- // Every cell in a row with a header cell carries \clbrdrb\brdrs.
431
- if (tag === 'td' && el.parentElement?.querySelector(':scope > th'))
432
- total += 14;
433
- // A figure with a caption and no picture writes its caption twice.
658
+ // A cell's own alignment is written on its paragraph (\qc, 3). A cell down several rows
659
+ // is written once in each of them, marked \clvmgf or \clvmrg (7). A table inside a cell
660
+ // is written as text, which costs less than the cells counted for it.
661
+ if (tag === 'td' || tag === 'th') {
662
+ // (Its own, or the one a block around the table hands down.)
663
+ if (el.closest('center, [style*="text-align"], [align]'))
664
+ total += 3;
665
+ const rows = parseInt(el.getAttribute('rowspan') ?? '', 10);
666
+ if (rows !== 1 && Number.isFinite(rows) && !el.parentElement?.closest('td, th')) {
667
+ // rowspan="0" reaches the last row; no span reaches past the table.
668
+ const rowCount = el.closest('table')?.querySelectorAll('tr').length ?? 1;
669
+ const spanned = Math.min(rowCount, rows > 0 ? rows : rowCount);
670
+ total += 7 + (spanned - 1) * ((BLOCK_OVERHEAD_BYTES[tag] ?? 0) + 7);
671
+ }
672
+ }
673
+ // A row with fewer cells than the table has columns is filled with empty ones.
674
+ if (tag === 'table' && !el.parentElement?.closest('td, th')) {
675
+ const model = tableModel(el);
676
+ for (const row of model.rows)
677
+ total += row.filter((slot) => slot === null).length * BLOCK_OVERHEAD_BYTES.td;
678
+ }
679
+ // Anything in a table that is in no cell is written before it, each run a paragraph
680
+ // ("\pard\intbl\qc\liN " and "\par ", at most 27).
681
+ if (tag === 'table' || tag === 'thead' || tag === 'tbody' || tag === 'tfoot' || tag === 'tr') {
682
+ for (const child of Array.from(el.childNodes)) {
683
+ const name = child.nodeName.toLowerCase();
684
+ if (/^(caption|colgroup|col|thead|tbody|tfoot|tr|td|th|#comment)$/.test(name))
685
+ continue;
686
+ if (child.nodeType === Node.TEXT_NODE && COLLAPSIBLE_WHITESPACE.test(child.textContent || ''))
687
+ continue;
688
+ total += 27;
689
+ }
690
+ }
691
+ // Text or an inline element after a block starts a paragraph of its own where that
692
+ // block set an indent or alignment ("\pard\intbl\qc\li1440 ", and its "\par ").
693
+ if (isBlock(el) && followedByInline(el))
694
+ total += 27;
695
+ // So does text written straight into a list, between its items.
696
+ if (tag === 'ul' || tag === 'ol') {
697
+ for (const child of Array.from(el.childNodes)) {
698
+ if (child.nodeType === Node.TEXT_NODE ? !COLLAPSIBLE_WHITESPACE.test(child.textContent || '') : !isBlock(child))
699
+ total += 27;
700
+ }
701
+ }
702
+ // A paragraph inside a list item is written at the item's indent (\liN, up to 7).
703
+ if ((tag === 'p' || tag === 'div') && el.parentElement?.tagName === 'LI')
704
+ total += 8;
705
+ // A numbered item's number is counted as one digit; a list that starts high has more.
706
+ if (tag === 'ol') {
707
+ const last = (parseInt(el.getAttribute('start') ?? '', 10) || 1) + el.children.length;
708
+ total += el.children.length * Math.max(0, String(last).length - 1);
709
+ }
710
+ // A figure with no picture is a paragraph of what it holds: "\pard\intbl\qc\liN " and
711
+ // "\par " (at most 30).
434
712
  if (tag === 'figure' && !el.querySelector('img'))
435
- total += escapeRtf(el.textContent || '').length;
436
- // A color costs "\cfN " on and off and, the first time, its color-table entry (at most
437
- // 22 bytes, "\red255\green255\blue255;"); a size costs "\fsNN " on and off.
438
- if (el.style?.color || (tag === 'font' && el.hasAttribute('color')))
439
- total += 10 + 22;
440
- if (el.style?.fontSize)
441
- total += 14; // "\fsNNN " on and off, for sizes up to 499 pt
713
+ total += 30;
714
+ // A color costs "\cfN " on and off (up to "\cf123 " each, in a document of many colors)
715
+ // and, the first time, its color-table entry (at most 25 bytes,
716
+ // "\red255\green255\blue255;"); a size costs "\fsNN " on and off.
717
+ if (el.style?.color)
718
+ total += 14 + 25;
719
+ // (A <font> with a color attribute and a color style names two colors, and both are in the table.)
720
+ if (tag === 'font' && el.hasAttribute('color'))
721
+ total += el.style?.color ? 25 : 14 + 25;
722
+ // "\fsNNN " on and off, for sizes up to 499 pt
723
+ if (el.style?.fontSize || (tag === 'font' && el.hasAttribute('size')))
724
+ total += 14 + sizeDigits;
442
725
  }
443
726
  return total;
444
727
  }
@@ -467,6 +750,10 @@ export function linkTarget(url) {
467
750
  return null;
468
751
  }
469
752
  }
753
+ /** Whether any link in the element is one the writer writes as a link. */
754
+ function hasLink(el) {
755
+ return Array.from(el.querySelectorAll('a[href]')).some((a) => linkTarget(a.getAttribute('href') || '') !== null);
756
+ }
470
757
  /** Whether a link address is an absolute web, mail or phone address (see linkTarget). */
471
758
  export function isSafeLinkUrl(url) {
472
759
  return linkTarget(url) !== null;
@@ -483,10 +770,18 @@ function cleanFontName(name) {
483
770
  const cleaned = first.replace(/[\\{};]/g, '').trim();
484
771
  return cleaned || DEFAULT_FONT_FAMILY;
485
772
  }
773
+ /**
774
+ * Whether a font name is a monospace font's: Courier New, Consolas, Menlo, a "… Mono" family
775
+ * (Roboto Mono, DejaVu Sans Mono), and their PostScript names (CourierNewPSMT, SFMono-Regular).
776
+ * Monotype Corsiva is not one, and neither is American Typewriter, which is proportional.
777
+ */
778
+ export function isMonospaceFontName(name) {
779
+ return /courier|mono(?!type|ton|fett)|consolas|menlo|monaco|lucida ?console|lucida ?sans ?typewriter|ocr[ -]?[ab]\b|source ?code|fira ?code|cascadia|jetbrains/.test(name.toLowerCase());
780
+ }
486
781
  /** RTF font family class for a font name: \froman, \fmodern or \fswiss. */
487
782
  function fontFamilyClass(name) {
488
783
  const n = name.toLowerCase();
489
- if (/courier|mono|consolas|menlo|monaco|typewriter|lucida console/.test(n))
784
+ if (isMonospaceFontName(n))
490
785
  return 'modern';
491
786
  if (/times|georgia|garamond|cambria|palatino|antiqua|schoolbook|baskerville|didot|bodoni|serif/.test(n) &&
492
787
  !/sans/.test(n)) {
@@ -524,6 +819,10 @@ export function htmlToRtf(editorEl, options = {}) {
524
819
  const fontName = cleanFontName(options.fontFamily);
525
820
  const bodySize = bodyHalfPoints(options.fontSize);
526
821
  const colorMap = new Map();
822
+ // A link's text is \cf1. In a document with a link that entry is the link color, so a
823
+ // link can be told from underlined text; in any other it is black, as it always was.
824
+ if (hasLink(editorEl))
825
+ colorMap.set(colorKey(LINK_COLOR), { ...LINK_COLOR });
527
826
  colorMap.set('0,0,0', { r: 0, g: 0, b: 0 });
528
827
  collectColors(editorEl, colorMap);
529
828
  const colors = Array.from(colorMap.values());
@@ -551,6 +850,7 @@ export function htmlToRtf(editorEl, options = {}) {
551
850
  listCounter: 0,
552
851
  inTableCell: false,
553
852
  root: editorEl,
853
+ shownBefore: new Map(),
554
854
  bold: false,
555
855
  italic: false,
556
856
  underline: false,
@@ -559,7 +859,8 @@ export function htmlToRtf(editorEl, options = {}) {
559
859
  color: 0,
560
860
  script: null,
561
861
  mono: false,
562
- indent: 0
862
+ indent: 0,
863
+ cellAlign: ''
563
864
  });
564
865
  const rtf = '{\\rtf1\\ansi\\ansicpg1252\\deff0' +
565
866
  fontTable +
@@ -581,308 +882,684 @@ function addColor(colorStr, colorMap) {
581
882
  if (c)
582
883
  colorMap.set(colorKey(c), c);
583
884
  }
584
- function collectColors(el, colorMap) {
585
- addColor(el.style?.color, colorMap);
586
- // <font color="..."> is produced by execCommand('foreColor')
587
- if (el.tagName?.toLowerCase() === 'font')
588
- addColor(el.getAttribute('color'), colorMap);
589
- for (const child of el.children)
590
- collectColors(child, colorMap);
885
+ function collectColors(root, colorMap) {
886
+ // (In document order, as the color table has always been written, and without a call per
887
+ // level of nesting.)
888
+ for (const el of [root, ...Array.from(root.querySelectorAll('*'))]) {
889
+ addColor(el.style?.color, colorMap);
890
+ // <font color="..."> is produced by execCommand('foreColor')
891
+ if (el.tagName?.toLowerCase() === 'font')
892
+ addColor(el.getAttribute('color'), colorMap);
893
+ }
894
+ }
895
+ /** How many elements deep the walker is (see MAX_ELEMENT_DEPTH). */
896
+ let walkDepth = 0;
897
+ /** The text an element shows, read without a call per level of nesting. */
898
+ function flatText(root) {
899
+ let text = '';
900
+ const pending = [root];
901
+ while (pending.length > 0) {
902
+ const node = pending.pop();
903
+ if (node.nodeType === Node.TEXT_NODE) {
904
+ text += node.textContent || '';
905
+ }
906
+ else if (node.nodeType === Node.ELEMENT_NODE && !isHidden(node)) {
907
+ for (let i = node.childNodes.length - 1; i >= 0; i--)
908
+ pending.push(node.childNodes[i]);
909
+ }
910
+ }
911
+ return text;
591
912
  }
592
913
  function walkChildren(parent, ctx) {
593
914
  let rtf = '';
594
915
  const children = parent.childNodes;
595
- for (let i = 0; i < children.length; i++) {
596
- const node = children[i];
597
- if (node.nodeType === Node.TEXT_NODE) {
598
- const text = node.textContent || '';
599
- // Whitespace between two blocks (the newline in "</p>\n<p>") shows as
600
- // nothing in a browser. Written out, it became a space at the start of
601
- // the next paragraph.
602
- const tabsShow = ctx.inPre || showsTabs(node);
603
- if (!tabsShow && COLLAPSIBLE_WHITESPACE.test(text) && besideBlock(node))
604
- continue;
605
- if (!ctx.inPre)
606
- rtf += restateAfterBlock(node, ctx);
607
- if (ctx.inPre) {
608
- // Split before escaping — escapeRtf collapses newlines, so the
609
- // line structure a <pre> block depends on has to become \line
610
- // first. Handles CR, LF and CRLF alike.
611
- rtf += text.split(/\r\n|\r|\n/).map((line) => escapeTabs(line, true)).join('\\line ');
612
- }
613
- else {
614
- rtf += escapeTabs(text, tabsShow);
615
- }
616
- continue;
916
+ for (let i = 0; i < children.length; i++)
917
+ rtf += walkNode(children[i], ctx);
918
+ return rtf;
919
+ }
920
+ /**
921
+ * One node as RTF. `restate` is off where the caller has already started the paragraph the node
922
+ * goes in (a list item's lines). `endLooseText` is off where the caller has already ended the
923
+ * line before a block (flowRtf).
924
+ */
925
+ function walkNode(node, ctx, restate = true, endLooseText = true) {
926
+ if (node.nodeType === Node.ELEMENT_NODE && walkDepth >= MAX_ELEMENT_DEPTH) {
927
+ return isHidden(node) ? '' : escapeRtf(flatText(node));
928
+ }
929
+ walkDepth++;
930
+ try {
931
+ return walkNodeAt(node, ctx, restate, endLooseText);
932
+ }
933
+ finally {
934
+ walkDepth--;
935
+ }
936
+ }
937
+ function walkNodeAt(node, ctx, restate, endLooseText) {
938
+ let rtf = '';
939
+ if (node.nodeType === Node.TEXT_NODE) {
940
+ if (isUnseen(node))
941
+ return '';
942
+ const text = node.textContent || '';
943
+ // Whitespace between two blocks (the newline in "</p>\n<p>") shows as
944
+ // nothing in a browser. Written out, it became a space at the start of
945
+ // the next paragraph.
946
+ const tabsShow = ctx.inPre || showsTabs(node);
947
+ if (!tabsShow && COLLAPSIBLE_WHITESPACE.test(text) && besideBlock(node))
948
+ return '';
949
+ if (!ctx.inPre && restate)
950
+ rtf += restateAfterBlock(node, ctx);
951
+ if (ctx.inPre || showsLineBreaks(node)) {
952
+ // Split before escaping — escapeRtf collapses newlines, so the
953
+ // line structure a <pre> block depends on has to become \line
954
+ // first. Handles CR, LF and CRLF alike. Text whose own white-space
955
+ // keeps its line breaks (pre-wrap) is the same.
956
+ rtf += text.split(/\r\n|\r|\n/).map((line) => escapeTabs(line, tabsShow)).join('\\line ');
617
957
  }
618
- if (node.nodeType !== Node.ELEMENT_NODE)
619
- continue;
620
- const el = node;
621
- const tag = el.tagName.toLowerCase();
622
- // A picture directly under the root writes its own paragraph.
623
- if (!isBlock(el) && !(tag === 'img' && el.parentNode === ctx.root))
624
- rtf += restateAfterBlock(el, ctx);
625
- switch (tag) {
626
- // Heading sizes keep their ratio to the body (HEADING_SCALE).
627
- case 'h1': {
628
- const size = scaled(ctx, HEADING_SCALE.h1);
629
- rtf += `\\pard${inCell(ctx)}${headingLayout(el, ctx)}\\f0\\fs${size}\\b ${walkChildren(el, { ...ctx, bold: true, size })}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size}\\par `;
630
- break;
631
- }
632
- case 'h2': {
633
- const size = scaled(ctx, HEADING_SCALE.h2);
634
- rtf += `\\pard${inCell(ctx)}${headingLayout(el, ctx)}\\f0\\fs${size}\\b ${walkChildren(el, { ...ctx, bold: true, size })}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size}\\par `;
958
+ else {
959
+ rtf += escapeTabs(text, tabsShow);
960
+ }
961
+ return rtf;
962
+ }
963
+ if (node.nodeType !== Node.ELEMENT_NODE)
964
+ return '';
965
+ const el = node;
966
+ if (isHidden(el))
967
+ return '';
968
+ const tag = tagOf(el);
969
+ // Text typed straight into the parent before a block ("Diagnosis:<ul>…", the shape Chrome
970
+ // makes when the line after it becomes a list) has no paragraph of its own: it is ended here,
971
+ // or \pard would carry it into the block's first line. A <p> or <div>, and a table inside a
972
+ // cell, end it themselves.
973
+ if (endLooseText && BREAKS_LOOSE_TEXT.has(tag) && !(tag === 'table' && ctx.inTableCell) && followsInlineContent(el, ctx.root)) {
974
+ rtf += '\\par ';
975
+ }
976
+ // A picture directly under the root writes its own paragraph.
977
+ if (restate && !isBlock(el) && !(tag === 'img' && el.parentNode === ctx.root))
978
+ rtf += restateAfterBlock(el, ctx);
979
+ switch (tag) {
980
+ // Heading sizes keep their ratio to the body (HEADING_SCALE). <h4> to <h6> come in with
981
+ // pasted text; each is a paragraph of its own, as large as a browser shows it.
982
+ case 'h1':
983
+ case 'h2':
984
+ case 'h3':
985
+ case 'h4':
986
+ case 'h5':
987
+ case 'h6': {
988
+ const size = scaled(ctx, ALL_HEADING_SCALES[tag]);
989
+ // The heading's own color and the like, on top of its size and bold.
990
+ const own = charFormat(el, tag, { ...ctx, bold: true, size }, true);
991
+ // A heading that holds a block (a list made in it with the browser's list command)
992
+ // is not a paragraph itself; what is inside is written at the heading's size, bold.
993
+ if (Array.from(el.children).some(isBlock)) {
994
+ rtf += `\\fs${size}${ctx.bold ? '' : '\\b'} ${own.on}${walkChildren(el, own.ctx)}${own.off}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size} `;
635
995
  break;
636
996
  }
637
- case 'h3': {
638
- const size = scaled(ctx, HEADING_SCALE.h3);
639
- rtf += `\\pard${inCell(ctx)}${headingLayout(el, ctx)}\\f0\\fs${size}\\b ${walkChildren(el, { ...ctx, bold: true, size })}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size}\\par `;
997
+ rtf += `\\pard${inCell(ctx)}${headingLayout(el, ctx)}\\f0\\fs${size}\\b ${own.on}${walkChildren(el, own.ctx)}${own.off}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size}\\par `;
998
+ break;
999
+ }
1000
+ case 'p':
1001
+ case 'div': {
1002
+ // Inside a table cell the cell has already declared \pard\intbl. Each paragraph
1003
+ // ends with \par, so two paragraphs in one cell stay two (the cell drops the last
1004
+ // one's); one that follows a list or heading in the cell restates \pard\intbl,
1005
+ // so it does not inherit that block's indent.
1006
+ // Text typed straight into the parent before this block ("abc<div>def</div>",
1007
+ // the shape Chrome makes on Enter) has no paragraph of its own: end it here, or
1008
+ // the two lines run together.
1009
+ const afterLooseText = followsInlineContent(el, ctx.root);
1010
+ // A <div> that holds blocks (pasted content wraps paragraphs in one) is not a
1011
+ // paragraph itself: each block inside writes its own \\pard, which would drop the
1012
+ // div's indent, and the div's own \\par would add a blank line. Its left margin is
1013
+ // carried into the blocks instead, and loose text in it gets a paragraph. A <p> that
1014
+ // holds a block is the same: no parser makes one, but a browser's own list command
1015
+ // does, leaving the list inside the paragraph it was made from (<p><ul>…</ul></p>).
1016
+ // The block's own color, and bold and the like where its style sets them.
1017
+ const own = charFormat(el, tag, ctx, true);
1018
+ if (Array.from(el.children).some(isBlock)) {
1019
+ const indent = ctx.indent + leftMarginTwips(el);
1020
+ // Its alignment is that of the blocks inside it that set none: text-align is
1021
+ // inherited, and pasted pages center a run of paragraphs with one <div>.
1022
+ const inner = { ...own.ctx, indent, cellAlign: inheritedAlign(el, ctx) };
1023
+ const lead = startsWithInline(el) ? `\\pard${inCell(ctx)}${cellAlign(inner)}${liControl(indent)} ` : '';
1024
+ const tail = endsWithInline(el) ? '\\par ' : '';
1025
+ rtf += `${afterLooseText ? '\\par ' : ''}${lead}${own.on}${walkChildren(el, inner)}${own.off}${tail}`;
640
1026
  break;
641
1027
  }
642
- case 'p':
643
- case 'div': {
644
- // Inside a table cell the cell has already declared \pard\intbl. Each paragraph
645
- // ends with \par, so two paragraphs in one cell stay two (the cell drops the last
646
- // one's); one that follows a list or heading in the cell restates \pard\intbl,
647
- // so it does not inherit that block's indent.
648
- // Text typed straight into the parent before this block ("abc<div>def</div>",
649
- // the shape Chrome makes on Enter) has no paragraph of its own: end it here, or
650
- // the two lines run together.
651
- const afterLooseText = followsInlineContent(el);
652
- if (ctx.inTableCell) {
653
- // Alignment or an indent needs a paragraph of its own, even as the cell's first.
654
- const layout = paragraphLayout(el, ctx);
655
- const restate = afterLooseText
656
- ? `\\par \\pard\\intbl${layout} `
657
- : el.previousElementSibling || layout ? `\\pard\\intbl${layout} ` : '';
658
- if (isBlankLine(el)) {
659
- rtf += `${restate}\\par `;
660
- break;
661
- }
662
- const colorIdx = colorIndexOf(el, ctx);
663
- const inner = walkChildren(el, colorIdx != null ? { ...ctx, color: colorIdx } : ctx);
664
- rtf += colorIdx != null
665
- ? `${restate}\\cf${colorIdx} ${inner}\\cf${ctx.color} \\par `
666
- : `${restate}${inner}\\par `;
667
- break;
668
- }
669
- // A <div> that holds blocks (pasted content wraps paragraphs in one) is not a
670
- // paragraph itself: each block inside writes its own \\pard, which would drop the
671
- // div's indent, and the div's own \\par would add a blank line. Its left margin is
672
- // carried into the blocks instead, and loose text in it gets a paragraph.
673
- if (tag === 'div' && Array.from(el.children).some(isBlock)) {
674
- const indent = ctx.indent + leftMarginTwips(el);
675
- const colorIdx = colorIndexOf(el, ctx);
676
- const inner = { ...ctx, indent, color: colorIdx ?? ctx.color };
677
- const lead = startsWithInline(el) ? `\\pard${liControl(indent)} ` : '';
678
- const tail = endsWithInline(el) ? '\\par ' : '';
679
- const colorPrefix = colorIdx != null ? `\\cf${colorIdx} ` : '';
680
- const colorSuffix = colorIdx != null ? `\\cf${ctx.color} ` : '';
681
- rtf += `${afterLooseText ? '\\par ' : ''}${lead}${colorPrefix}${walkChildren(el, inner)}${colorSuffix}${tail}`;
682
- break;
683
- }
684
- // The paragraph's alignment, indents, spacing, keep-with-next and tab stops, if it
685
- // sets any.
686
- const para = paragraphFormat(el, ctx);
687
- // A <p> with no children or only a single <br> is a blank line —
688
- // emit a bare \par rather than \pard \line\par, which adds an extra line.
689
- // A bare \par keeps the formatting of the paragraph before it, so a blank line after a
690
- // formatted paragraph, or with formatting of its own, restates \pard.
1028
+ if (ctx.inTableCell) {
1029
+ // Alignment or an indent needs a paragraph of its own, even as the cell's first.
1030
+ const layout = paragraphLayout(el, ctx);
1031
+ const restate = afterLooseText
1032
+ ? `\\par \\pard\\intbl${layout} `
1033
+ : el.previousElementSibling || layout ? `\\pard\\intbl${layout} ` : '';
691
1034
  if (isBlankLine(el)) {
692
- const reset = para || followsFormattedParagraph(el, ctx) ? `\\pard${para} ` : '';
693
- rtf += `${afterLooseText ? '\\par ' : ''}${reset}\\par `;
1035
+ rtf += `${restate}\\par `;
694
1036
  break;
695
1037
  }
696
- const colorIdx = colorIndexOf(el, ctx);
697
- const inlineRtf = walkChildren(el, colorIdx != null ? { ...ctx, color: colorIdx } : ctx);
698
- const colorPrefix = colorIdx != null ? `\\cf${colorIdx} ` : '';
699
- const colorSuffix = colorIdx != null ? `\\cf${ctx.color} ` : '';
700
- rtf += `${afterLooseText ? '\\par ' : ''}\\pard${para} ${colorPrefix}${inlineRtf}${colorSuffix}\\par `;
1038
+ rtf += `${restate}${own.on}${walkChildren(el, own.ctx)}${own.off}\\par `;
701
1039
  break;
702
1040
  }
703
- case 'table': {
704
- const PAGE_WIDTH = 8640; // twips ≈ 6 in (standard letter body width)
705
- const rows = Array.from(el.querySelectorAll(':scope > tr, :scope > thead > tr, :scope > tbody > tr, :scope > tfoot > tr'));
706
- for (const row of rows) {
707
- const cells = Array.from(row.querySelectorAll(':scope > td, :scope > th'));
708
- if (cells.length === 0)
709
- continue;
710
- const isHeader = cells.some(c => c.tagName.toLowerCase() === 'th');
711
- // Derive right-edge twip positions from the width:X% style set by the parser.
712
- // Fall back to equal column widths if the style is absent.
713
- const cellRights = [];
714
- let cumTwips = 0;
715
- for (const cell of cells) {
716
- const pct = parseFloat(cell.style.width) || (100 / cells.length);
717
- cumTwips += Math.round((pct / 100) * PAGE_WIDTH);
718
- cellRights.push(cumTwips);
719
- }
720
- cellRights[cellRights.length - 1] = PAGE_WIDTH; // snap last edge to avoid rounding drift
721
- // Row definition
722
- let rowRtf = '{\\trowd\\trgaph120';
723
- for (let ci = 0; ci < cells.length; ci++) {
724
- if (isHeader)
725
- rowRtf += `\\clbrdrb\\brdrs`;
726
- rowRtf += `\\cellx${cellRights[ci]}`;
727
- }
728
- rowRtf += '\\trkeep\\intbl{';
729
- // Cell bodies
730
- const cellCtx = { ...ctx, inTableCell: true };
731
- for (const cell of cells) {
732
- const content = withoutTrailingPar(walkChildren(cell, cellCtx));
733
- rowRtf += `{\\pard\\intbl \\f0 \\sa0 \\li0 \\fi0 ${content}\\par}\\cell`;
734
- }
735
- rowRtf += '}\\intbl\\row}';
736
- rtf += rowRtf;
737
- }
1041
+ // The paragraph's alignment, indents, spacing, keep-with-next and tab stops, if it
1042
+ // sets any.
1043
+ const para = paragraphFormat(el, ctx);
1044
+ // A <p> with no children or only a single <br> is a blank line —
1045
+ // emit a bare \par rather than \pard \line\par, which adds an extra line.
1046
+ // A bare \par keeps the formatting of the paragraph before it, so a blank line after a
1047
+ // formatted paragraph, or with formatting of its own, restates \pard.
1048
+ if (isBlankLine(el)) {
1049
+ const reset = para || followsFormattedParagraph(el, ctx) ? `\\pard${para} ` : '';
1050
+ rtf += `${afterLooseText ? '\\par ' : ''}${reset}\\par `;
738
1051
  break;
739
1052
  }
740
- case 'blockquote': {
741
- // The browser's Indent wraps the lines in a blockquote with a left margin and
742
- // border: none (Chromium, WebKit, Gmail): that is an indent, not a quotation, so it
743
- // is not italic. A quotation is indented half an inch, plus any margin of its own.
744
- // Either way the blocks inside carry the indent, and loose text gets a paragraph.
745
- const quote = !isIndentBlockquote(el);
746
- const indent = ctx.indent + leftMarginTwips(el) + (quote ? 720 : 0);
747
- const inner = { ...ctx, indent, italic: ctx.italic || quote };
748
- const lead = startsWithInline(el) ? `\\pard${inCell(ctx)}${liControl(indent)}` : '';
749
- const tail = endsWithInline(el) ? '\\par ' : '';
750
- const content = walkChildren(el, inner);
751
- const italicOn = quote && !ctx.italic;
752
- const italicOff = italicOn ? (tail ? '\\i0' : '\\i0 ') : '';
753
- rtf += `${lead}${italicOn ? '\\i ' : lead ? ' ' : ''}${content}${italicOff}${tail}`;
1053
+ rtf += `${afterLooseText ? '\\par ' : ''}\\pard${para} ${own.on}${walkChildren(el, own.ctx)}${own.off}\\par `;
1054
+ break;
1055
+ }
1056
+ case 'table':
1057
+ rtf += ctx.inTableCell ? nestedTableRtf(el, ctx) : tableRtf(el, ctx);
1058
+ break;
1059
+ case 'blockquote': {
1060
+ // The browser's Indent wraps the lines in a blockquote with a left margin and
1061
+ // border: none (Chromium, WebKit, Gmail): that is an indent, not a quotation, so it
1062
+ // is not italic. A quotation is indented half an inch, plus any margin of its own.
1063
+ // Either way the blocks inside carry the indent, and loose text gets a paragraph.
1064
+ const quote = !isIndentBlockquote(el);
1065
+ const indent = ctx.indent + leftMarginTwips(el) + (quote ? 720 : 0);
1066
+ const inner = { ...ctx, indent, italic: ctx.italic || quote };
1067
+ const lead = startsWithInline(el) ? `\\pard${inCell(ctx)}${cellAlign(ctx)}${liControl(indent)}` : '';
1068
+ const tail = endsWithInline(el) ? '\\par ' : '';
1069
+ const content = walkChildren(el, inner);
1070
+ const italicOn = quote && !ctx.italic;
1071
+ const italicOff = italicOn ? (tail ? '\\i0' : '\\i0 ') : '';
1072
+ rtf += `${lead}${italicOn ? '\\i ' : lead ? ' ' : ''}${content}${italicOff}${tail}`;
1073
+ break;
1074
+ }
1075
+ case 'pre': {
1076
+ const size = scaled(ctx, PRE_SCALE);
1077
+ rtf += `\\pard${inCell(ctx)}${cellAlign(ctx)}${liControl(ctx.indent + leftMarginTwips(el))}\\f1\\fs${size} ${walkChildren(el, { ...ctx, inPre: true, size })}\\f0\\fs${ctx.size}\\par `;
1078
+ break;
1079
+ }
1080
+ case 'hr':
1081
+ // A page break read from RTF is shown as a rule that says so, and goes back as \page.
1082
+ if (!ctx.inTableCell && isPageBreak(el)) {
1083
+ rtf += '\\page ';
754
1084
  break;
755
1085
  }
756
- case 'pre': {
757
- const size = scaled(ctx, PRE_SCALE);
758
- rtf += `\\pard${inCell(ctx)}${liControl(ctx.indent + leftMarginTwips(el))}\\f1\\fs${size} ${walkChildren(el, { ...ctx, inPre: true, size })}\\f0\\fs${ctx.size}\\par `;
759
- break;
1086
+ 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 `;
1087
+ break;
1088
+ case 'ul':
1089
+ case 'ol':
1090
+ rtf += listRtf(el, ctx);
1091
+ break;
1092
+ case 'li': {
1093
+ // An item with no list around it (a pasted fragment) shows with a bullet.
1094
+ const left = ctx.indent + LIST_STEP;
1095
+ const start = `\\pard${inCell(ctx)}${listAlign(ctx)}${liControl(left)}`;
1096
+ const own = charFormat(el, tag, ctx, true);
1097
+ rtf += `${own.on}${flowRtf(Array.from(el.childNodes), { ...own.ctx, indent: left }, `${start}\\fi-${LIST_HANG}\\bullet\\tab `, `${start} `)}${own.off}`;
1098
+ break;
1099
+ }
1100
+ case 'code': {
1101
+ const own = charFormat(el, tag, ctx);
1102
+ if (!ctx.inPre && !ctx.mono) {
1103
+ rtf += `${own.on}\\f1 ${walkChildren(el, { ...own.ctx, mono: true })}\\f0 ${own.off}`;
760
1104
  }
761
- case 'hr':
762
- 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 `;
763
- break;
764
- case 'ul': {
765
- const items = el.querySelectorAll(':scope > li');
766
- const li = liControl(ctx.indent + leftMarginTwips(el) + 720);
767
- items.forEach((item) => {
768
- rtf += `\\pard${inCell(ctx)}${li}\\fi-360\\bullet\\tab ${walkChildren(item, ctx)}\\par `;
769
- });
770
- break;
1105
+ else {
1106
+ rtf += `${own.on}${walkChildren(el, own.ctx)}${own.off}`;
771
1107
  }
772
- case 'ol': {
773
- let counter = 1;
774
- const items = el.querySelectorAll(':scope > li');
775
- const li = liControl(ctx.indent + leftMarginTwips(el) + 720);
776
- items.forEach((item) => {
777
- rtf += `\\pard${inCell(ctx)}${li}\\fi-360 ${counter}.\\tab ${walkChildren(item, ctx)}\\par `;
778
- counter++;
779
- });
780
- break;
1108
+ break;
1109
+ }
1110
+ case 'a': {
1111
+ const own = charFormat(el, tag, ctx);
1112
+ // A link is written only for an absolute web, mail or phone address; anything
1113
+ // else (a relative or UNC path, javascript:, data:, file:) as its text alone.
1114
+ const target = linkTarget(el.getAttribute('href') || '');
1115
+ if (target) {
1116
+ const inner = walkChildren(el, { ...own.ctx, underline: true, color: 1 });
1117
+ const underlineOff = own.ctx.underline ? '' : '\\ulnone';
1118
+ rtf += `${own.on}{\\field{\\*\\fldinst HYPERLINK "${escapeRtf(target)}"}{\\fldrslt\\ul\\cf1 ${inner}\\cf${own.ctx.color}${underlineOff} }}${own.off}`;
781
1119
  }
782
- case 'li':
783
- rtf += walkChildren(el, ctx);
784
- break;
785
- case 'strong':
786
- case 'b':
787
- rtf += ctx.bold ? walkChildren(el, ctx) : `\\b ${walkChildren(el, { ...ctx, bold: true })}\\b0 `;
788
- break;
789
- case 'em':
790
- case 'i':
791
- rtf += ctx.italic ? walkChildren(el, ctx) : `\\i ${walkChildren(el, { ...ctx, italic: true })}\\i0 `;
792
- break;
793
- case 'u':
794
- rtf += ctx.underline ? walkChildren(el, ctx) : `\\ul ${walkChildren(el, { ...ctx, underline: true })}\\ulnone `;
795
- break;
796
- case 's':
797
- case 'strike':
798
- case 'del':
799
- rtf += ctx.strike ? walkChildren(el, ctx) : `\\strike ${walkChildren(el, { ...ctx, strike: true })}\\strike0 `;
800
- break;
801
- case 'sup':
802
- case 'sub': {
803
- const script = tag === 'sup' ? 'super' : 'sub';
804
- if (ctx.script === script) {
805
- rtf += walkChildren(el, ctx);
806
- break;
807
- }
808
- const restore = ctx.script ? `\\${ctx.script} ` : '\\nosupersub ';
809
- rtf += `\\${script} ${walkChildren(el, { ...ctx, script })}${restore}`;
810
- break;
1120
+ else {
1121
+ rtf += `${own.on}${walkChildren(el, own.ctx)}${own.off}`;
811
1122
  }
812
- case 'code':
813
- if (!ctx.inPre && !ctx.mono) {
814
- rtf += `\\f1 ${walkChildren(el, { ...ctx, mono: true })}\\f0 `;
815
- }
816
- else {
817
- rtf += walkChildren(el, ctx);
818
- }
819
- break;
820
- case 'a': {
821
- // A link is written only for an absolute web, mail or phone address; anything
822
- // else (a relative or UNC path, javascript:, data:, file:) as its text alone.
823
- const target = linkTarget(el.getAttribute('href') || '');
824
- if (target) {
825
- const inner = walkChildren(el, { ...ctx, underline: true, color: 1 });
826
- const underlineOff = ctx.underline ? '' : '\\ulnone';
827
- rtf += `{\\field{\\*\\fldinst HYPERLINK "${escapeRtf(target)}"}{\\fldrslt\\ul\\cf1 ${inner}\\cf${ctx.color}${underlineOff} }}`;
828
- }
829
- else {
830
- rtf += walkChildren(el, ctx);
831
- }
832
- break;
1123
+ break;
1124
+ }
1125
+ // <figure><img><figcaption>caption</figcaption></figure> — the shape the
1126
+ // editor inserts. The caption is written as its own paragraph below the
1127
+ // picture, tagged with an ignorable {\*\inkcap} destination so it can be
1128
+ // re-attached to the figure on import. Other RTF readers skip the tag and
1129
+ // simply show an italic line under the image.
1130
+ case 'figure': {
1131
+ // The editor's figure is one picture and its caption. A figure with more in it (a
1132
+ // second picture, text typed beside the picture) is written as the block of what it
1133
+ // holds, like one with no picture: everything in it is kept, where only its first
1134
+ // picture was.
1135
+ // (What is hidden in a figure is no part of it: a picture, a caption, a note in one.)
1136
+ const within = (found) => found.filter((f) => !hiddenWithin(f, el) && !isUnseen(f));
1137
+ const pictures = within(Array.from(el.querySelectorAll('img')));
1138
+ const anyCaption = within(Array.from(el.querySelectorAll('figcaption')))[0] ?? null;
1139
+ const img = pictures.length === 1 && !hasTextOutside(el, anyCaption) ? pictures[0] : null;
1140
+ // A figure with a picture takes the caption the editor gives it, wherever it sits. One
1141
+ // with no picture takes only its own (a child): a caption further in belongs to what
1142
+ // holds it (a figure inside this one), and is written there.
1143
+ const captionEl = img ? anyCaption : Array.from(el.children).find((c) => c.tagName === 'FIGCAPTION' && !isHidden(c));
1144
+ const caption = (captionEl ? shownText(captionEl) : '').trim();
1145
+ const align = `${ownAlign(el) ?? (cellAlign(ctx) || '\\ql')}${liControl(ctx.indent + leftMarginTwips(el))}`;
1146
+ if (img) {
1147
+ rtf += `\\pard${inCell(ctx)}${align} ${imageBody(img)}\\par `;
833
1148
  }
834
- // <figure><img><figcaption>caption</figcaption></figure> — the shape the
835
- // editor inserts. The caption is written as its own paragraph below the
836
- // picture, tagged with an ignorable {\*\inkcap} destination so it can be
837
- // re-attached to the figure on import. Other RTF readers skip the tag and
838
- // simply show an italic line under the image.
839
- case 'figure': {
840
- const img = el.querySelector('img');
841
- const caption = (el.querySelector('figcaption')?.textContent || '').trim();
842
- const align = `${alignControl(el)}${liControl(ctx.indent + leftMarginTwips(el))}`;
843
- if (img)
844
- rtf += `\\pard${inCell(ctx)}${align} ${imageBody(img)}\\par `;
845
- else
846
- rtf += walkChildren(el, ctx);
847
- if (caption) {
848
- rtf += `{\\*\\inkcap}\\pard${inCell(ctx)}${align}\\i ${escapeRtf(caption)}${ctx.italic ? '' : '\\i0'}\\par `;
849
- }
850
- break;
1149
+ else {
1150
+ // A figure with no picture is a block of what it holds: its lines end with \par, as a
1151
+ // <div>'s do, or its text ran into the next paragraph. Its caption is written below.
1152
+ const held = Array.from(el.childNodes).filter((n) => n !== captionEl);
1153
+ rtf += flowRtf(held, ctx, null, `\\pard${inCell(ctx)}${align} `);
851
1154
  }
852
- case 'img': {
853
- // A picture directly under the editor root has no paragraph of its
854
- // own; anywhere else it is inline content of the enclosing block.
855
- const standalone = el.parentNode === ctx.root;
856
- rtf += standalone ? `\\pard ${imageBody(el)}\\par ` : imageBody(el);
857
- break;
1155
+ if (caption) {
1156
+ rtf += `{\\*\\inkcap}\\pard${inCell(ctx)}${align}\\i ${escapeRtf(caption)}${ctx.italic ? '' : '\\i0'}\\par `;
858
1157
  }
859
- case 'br':
860
- rtf += '\\line ';
861
- break;
862
- case 'span': {
863
- const colorIdx = colorIndexOf(el, ctx);
864
- const size = sizeOf(el);
865
- const colorPfx = colorIdx != null ? `\\cf${colorIdx} ` : '';
866
- const sizePfx = size != null ? `\\fs${size} ` : '';
867
- const sizeSfx = size != null ? `\\fs${ctx.size} ` : '';
868
- const colorSfx = colorIdx != null ? `\\cf${ctx.color} ` : '';
869
- const inner = walkChildren(el, { ...ctx, color: colorIdx ?? ctx.color, size: size ?? ctx.size });
870
- rtf += `${colorPfx}${sizePfx}${inner}${sizeSfx}${colorSfx}`;
1158
+ break;
1159
+ }
1160
+ case 'img': {
1161
+ // A picture directly under the editor root has no paragraph of its
1162
+ // own; anywhere else it is inline content of the enclosing block.
1163
+ if (isUnseen(el))
871
1164
  break;
1165
+ const standalone = el.parentNode === ctx.root;
1166
+ rtf += standalone ? `\\pard ${imageBody(el)}\\par ` : imageBody(el);
1167
+ break;
1168
+ }
1169
+ case 'br':
1170
+ // The <br> a browser leaves at the end of a paragraph shows as nothing; written
1171
+ // as \line it added an empty line.
1172
+ if (ctx.inPre || !isTrailingBreak(el, ctx))
1173
+ rtf += '\\line ';
1174
+ break;
1175
+ // Every other element is inline: <b>, <em>, <sup>, <span>, <font color> (which
1176
+ // execCommand('foreColor') makes) and whatever a paste brings. What it does to its text
1177
+ // is its tag's meaning and its own style (charFormat).
1178
+ default: {
1179
+ const own = charFormat(el, tag, ctx);
1180
+ rtf += `${own.on}${walkChildren(el, own.ctx)}${own.off}`;
1181
+ break;
1182
+ }
1183
+ }
1184
+ return rtf;
1185
+ }
1186
+ // ── Character formatting ──
1187
+ /** What a tag by itself does to its text. */
1188
+ const TAG_FORMAT = {
1189
+ b: { bold: true },
1190
+ strong: { bold: true },
1191
+ i: { italic: true },
1192
+ em: { italic: true },
1193
+ cite: { italic: true },
1194
+ var: { italic: true },
1195
+ dfn: { italic: true },
1196
+ u: { underline: true },
1197
+ ins: { underline: true },
1198
+ s: { strike: true },
1199
+ strike: { strike: true },
1200
+ del: { strike: true },
1201
+ sup: { script: 'super' },
1202
+ sub: { script: 'sub' }
1203
+ };
1204
+ /** Whether a font-weight is bold; null when it does not say. */
1205
+ function cssBold(weight) {
1206
+ if (!weight)
1207
+ return null;
1208
+ if (weight === 'bold' || weight === 'bolder')
1209
+ return true;
1210
+ if (weight === 'normal' || weight === 'lighter')
1211
+ return false;
1212
+ const n = Number(weight);
1213
+ return Number.isFinite(n) ? n >= 600 : null;
1214
+ }
1215
+ /**
1216
+ * The character formatting an element gives its text, as the control words that turn it on and
1217
+ * the ones that put back what was in force before, and the context its children are written in.
1218
+ *
1219
+ * It is what the tag means (<b>, <sup>), unless the element's own style says otherwise. Google
1220
+ * Docs wraps everything it pastes in <b style="font-weight:normal">, which is not bold, and writes
1221
+ * bold, italic, underline, strikethrough, superscript and subscript as styles on a <span>, which
1222
+ * are. Only what differs from the text around it is written: <b> inside <b> writes nothing.
1223
+ *
1224
+ * A block (`block`) takes its color and these toggles; a size is read from inline elements only.
1225
+ */
1226
+ function charFormat(el, rawTag, ctx, block = false) {
1227
+ const style = el.style;
1228
+ const tagFormat = TAG_FORMAT[rawTag] ?? {};
1229
+ const weight = cssBold(style?.fontWeight);
1230
+ const bold = weight ?? (tagFormat.bold || ctx.bold);
1231
+ const fontStyle = style?.fontStyle ?? '';
1232
+ const italic = fontStyle === 'normal' ? false : fontStyle === 'italic' || fontStyle.startsWith('oblique') || tagFormat.italic || ctx.italic;
1233
+ // A line under or through text cannot be taken off by an element inside it (CSS draws it
1234
+ // across everything within), so "none" only stops the element's own tag: <u> or <s>.
1235
+ const decoration = `${style?.textDecorationLine ?? ''} ${style?.textDecoration ?? ''}`;
1236
+ const noLine = /\bnone\b/.test(decoration);
1237
+ const underline = /\bunderline\b/.test(decoration) || (!noLine && tagFormat.underline) || ctx.underline;
1238
+ const strike = /\bline-through\b/.test(decoration) || (!noLine && tagFormat.strike) || ctx.strike;
1239
+ const vertical = style?.verticalAlign ?? '';
1240
+ const script = vertical === 'super' ? 'super' : vertical === 'sub' ? 'sub' : vertical === 'baseline' ? null : (tagFormat.script ?? ctx.script);
1241
+ const color = colorIndexOf(el, ctx);
1242
+ const size = block ? null : sizeOf(el);
1243
+ let on = '';
1244
+ let off = '';
1245
+ if (color != null) {
1246
+ on += `\\cf${color} `;
1247
+ off = `\\cf${ctx.color} `;
1248
+ }
1249
+ if (size != null) {
1250
+ on += `\\fs${size} `;
1251
+ off = `\\fs${ctx.size} ${off}`;
1252
+ }
1253
+ if (bold !== ctx.bold) {
1254
+ on += bold ? '\\b ' : '\\b0 ';
1255
+ off = `${ctx.bold ? '\\b ' : '\\b0 '}${off}`;
1256
+ }
1257
+ if (italic !== ctx.italic) {
1258
+ on += italic ? '\\i ' : '\\i0 ';
1259
+ off = `${ctx.italic ? '\\i ' : '\\i0 '}${off}`;
1260
+ }
1261
+ if (underline !== ctx.underline) {
1262
+ on += '\\ul ';
1263
+ off = `\\ulnone ${off}`;
1264
+ }
1265
+ if (strike !== ctx.strike) {
1266
+ on += '\\strike ';
1267
+ off = `\\strike0 ${off}`;
1268
+ }
1269
+ if (script !== ctx.script) {
1270
+ on += script ? `\\${script} ` : '\\nosupersub ';
1271
+ off = `${ctx.script ? `\\${ctx.script} ` : '\\nosupersub '}${off}`;
1272
+ }
1273
+ if (!on)
1274
+ return { on, off, ctx };
1275
+ return { on, off, ctx: { ...ctx, bold, italic, underline, strike, script, color: color ?? ctx.color, size: size ?? ctx.size } };
1276
+ }
1277
+ /** Whether an element is shown and holds text or a picture: an empty <form> or a hidden <input> does not. */
1278
+ function holdsSomething(el) {
1279
+ return !isHidden(el) && (el.tagName === 'IMG' || el.querySelector('img') !== null || hasTextOutside(el, null));
1280
+ }
1281
+ /** Whether an element holds text that shows, outside `skip`: any text other than collapsible whitespace. */
1282
+ function hasTextOutside(el, skip) {
1283
+ // (With a list of what is still to look at, not a call for each level of nesting.)
1284
+ const pending = [el];
1285
+ while (pending.length > 0) {
1286
+ for (const child of Array.from(pending.pop().childNodes)) {
1287
+ if (child === skip)
1288
+ continue;
1289
+ if (child.nodeType === Node.TEXT_NODE) {
1290
+ if (!COLLAPSIBLE_WHITESPACE.test(child.textContent || '') && !isUnseen(child))
1291
+ return true;
872
1292
  }
873
- // <font color="..."> is produced by execCommand('foreColor') in contenteditable
874
- case 'font': {
875
- const colorIdx = colorIndexOf(el, ctx);
876
- const colorPfx = colorIdx != null ? `\\cf${colorIdx} ` : '';
877
- const colorSfx = colorIdx != null ? `\\cf${ctx.color} ` : '';
878
- rtf += `${colorPfx}${walkChildren(el, { ...ctx, color: colorIdx ?? ctx.color })}${colorSfx}`;
879
- break;
1293
+ else if (child.nodeType === Node.ELEMENT_NODE && !isHidden(child)) {
1294
+ pending.push(child);
880
1295
  }
881
- default:
882
- rtf += walkChildren(el, ctx);
883
- break;
884
1296
  }
885
1297
  }
1298
+ return false;
1299
+ }
1300
+ // ── Lists ──
1301
+ /** Each level of a list is indented half an inch further (\li720). */
1302
+ const LIST_STEP = 720;
1303
+ /** A list item's first line hangs a quarter inch left of its text, where the marker sits (\fi-360). */
1304
+ const LIST_HANG = 360;
1305
+ /**
1306
+ * A <ul> or <ol>: one hanging paragraph per item, opened by a bullet or the item's number and a
1307
+ * tab. A list inside an item, or straight inside the list (<ul><ul>, as some editors nest), is
1308
+ * indented one level further. Numbers start at the list's `start`.
1309
+ */
1310
+ function listRtf(list, ctx) {
1311
+ // A list straight inside a list is written from here, not through walkNode, so the depth is
1312
+ // counted here too: six thousand of them, one in the next, ran out of stack.
1313
+ if (walkDepth >= MAX_ELEMENT_DEPTH)
1314
+ return isHidden(list) ? '' : escapeRtf(flatText(list));
1315
+ walkDepth++;
1316
+ try {
1317
+ return listRtfAt(list, ctx);
1318
+ }
1319
+ finally {
1320
+ walkDepth--;
1321
+ }
1322
+ }
1323
+ function listRtfAt(list, ctx) {
1324
+ const ordered = tagOf(list) === 'ol';
1325
+ // A list read back from RTF carries the indent beyond its level's own as a margin, which
1326
+ // is negative for a list nested by less than half an inch.
1327
+ const margin = lengthTwips(list.style?.marginLeft, true) ?? 0;
1328
+ const left = Math.max(LIST_HANG, ctx.indent + margin + LIST_STEP);
1329
+ const start = parseInt(list.getAttribute('start') ?? '', 10);
1330
+ let counter = ordered && Number.isFinite(start) ? start : 1;
1331
+ const itemCtx = { ...ctx, indent: left, cellAlign: listAlign(ctx) };
1332
+ const paragraph = `\\pard${inCell(ctx)}${listAlign(ctx)}${liControl(left)}`;
1333
+ let rtf = '';
1334
+ /** Text or inline elements written straight into the list, between its items. */
1335
+ let loose = [];
1336
+ const flushLoose = () => {
1337
+ if (loose.length > 0)
1338
+ rtf += flowRtf(loose, itemCtx, null, `${paragraph} `);
1339
+ loose = [];
1340
+ };
1341
+ for (const child of Array.from(list.childNodes)) {
1342
+ const tag = child.nodeType === Node.ELEMENT_NODE ? tagOf(child) : '';
1343
+ if (tag && isHidden(child))
1344
+ continue;
1345
+ if (tag === 'li') {
1346
+ flushLoose();
1347
+ const marker = ordered ? ` ${counter}.\\tab ` : '\\bullet\\tab ';
1348
+ // The item's own color and the like; its marker takes them too, as on screen.
1349
+ const own = charFormat(child, tag, itemCtx, true);
1350
+ rtf += `${own.on}${flowRtf(Array.from(child.childNodes), own.ctx, `${paragraph}\\fi-${LIST_HANG}${marker}`, `${paragraph} `)}${own.off}`;
1351
+ counter++;
1352
+ }
1353
+ else if (tag === 'ul' || tag === 'ol') {
1354
+ flushLoose();
1355
+ rtf += listRtf(child, itemCtx);
1356
+ }
1357
+ else if (child.nodeType === Node.TEXT_NODE && COLLAPSIBLE_WHITESPACE.test(child.textContent || '')) {
1358
+ // The line breaks of the source between items.
1359
+ }
1360
+ else {
1361
+ loose.push(child);
1362
+ }
1363
+ }
1364
+ flushLoose();
1365
+ return rtf;
1366
+ }
1367
+ /**
1368
+ * The alignment a list's items are written with: the table cell's, inside one. Anywhere else a
1369
+ * list is written left-aligned, whatever a <div> around it says, because only a left-aligned
1370
+ * list is read back as a list; centered, its items came back as paragraphs with a bullet typed
1371
+ * in front.
1372
+ */
1373
+ function listAlign(ctx) {
1374
+ return ctx.inTableCell ? ctx.cellAlign : '';
1375
+ }
1376
+ /**
1377
+ * The content of a list item, or of any place where text and blocks mix, as paragraphs. Text
1378
+ * and inline elements in a row are one paragraph; the first opens with `first` (the item's
1379
+ * marker) and any later one with `plain` (the same indent, no marker). A <p> inside the item,
1380
+ * which is how Word and Google Docs paste a list, is the item's text, not a block after it. A
1381
+ * list or other block inside the item is written as itself, at the item's indent.
1382
+ */
1383
+ function flowRtf(nodes, ctx, first, plain) {
1384
+ let rtf = '';
1385
+ let marker = first;
1386
+ let open = false;
1387
+ const start = () => {
1388
+ if (open)
1389
+ return;
1390
+ rtf += marker ?? plain;
1391
+ marker = null;
1392
+ open = true;
1393
+ };
1394
+ const end = () => {
1395
+ if (open)
1396
+ rtf += '\\par ';
1397
+ open = false;
1398
+ };
1399
+ for (const node of nodes) {
1400
+ if (node.nodeType === Node.TEXT_NODE) {
1401
+ if (COLLAPSIBLE_WHITESPACE.test(node.textContent || '') && !showsTabs(node) && besideBlock(node))
1402
+ continue;
1403
+ start();
1404
+ rtf += walkNode(node, ctx, false);
1405
+ continue;
1406
+ }
1407
+ if (node.nodeType !== Node.ELEMENT_NODE)
1408
+ continue;
1409
+ const el = node;
1410
+ if (isHidden(el))
1411
+ continue;
1412
+ const tag = tagOf(el);
1413
+ // A caption outside a figure is text where it stands, as everywhere else.
1414
+ if (!endsItsLine(el)) {
1415
+ start();
1416
+ rtf += walkNode(el, ctx, false);
1417
+ // A wrapper that ends with a block (<b><p>a</p></b>) has ended the line itself.
1418
+ if (endsWithBlock(el))
1419
+ open = false;
1420
+ continue;
1421
+ }
1422
+ end();
1423
+ if ((tag === 'p' || tag === 'div') && !Array.from(el.children).some(isBlock)) {
1424
+ start();
1425
+ const own = charFormat(el, tag, ctx, true);
1426
+ rtf += `${own.on}${walkChildren(el, own.ctx)}${own.off}`;
1427
+ end();
1428
+ continue;
1429
+ }
1430
+ // An item that begins with a block keeps its marker on a line of its own, except
1431
+ // before a list of its own, where the first marker shown is that list's.
1432
+ if (marker && tag !== 'ul' && tag !== 'ol')
1433
+ rtf += `${marker}\\par `;
1434
+ marker = null;
1435
+ rtf += walkNode(el, ctx, true, false);
1436
+ }
1437
+ end();
1438
+ // An empty item still shows its marker.
1439
+ if (marker)
1440
+ rtf += `${marker}\\par `;
1441
+ return rtf;
1442
+ }
1443
+ // ── Tables ──
1444
+ /** The width a table is written at, in twips: 6 in, the text width of a Letter page with 1.25 in margins. */
1445
+ const PAGE_WIDTH = 8640;
1446
+ /**
1447
+ * A <table> as RTF rows. RTF has no table element: each row declares where its cells end
1448
+ * (\cellx), so the columns only line up if every row is written against the same column edges.
1449
+ * They are worked out once for the table (tableModel, columnShares), and then:
1450
+ *
1451
+ * - a cell across several columns (colspan) is one cell that ends at the right edge of the last
1452
+ * column it covers;
1453
+ * - a cell down several rows (rowspan) is \clvmgf where it starts and an empty \clvmrg cell in
1454
+ * the same columns of each row below, which is how RTF says "merged with the cell above";
1455
+ * - a row with fewer cells than the table has columns is filled with empty cells.
1456
+ *
1457
+ * A <th> gets a bottom border, which is how the parser knows a header cell, and a cell's own
1458
+ * text-align is its paragraphs' alignment.
1459
+ *
1460
+ * A cell's text ends with \cell inside its group and no \par before it. With "\par}\cell", as
1461
+ * cells were written up to 1.9.0, Apple's reader (TextEdit, Pages, Mail) put an empty paragraph
1462
+ * at the end of every cell, so every row was twice as tall. The last row carries \lastrow, which
1463
+ * is what tells a reader that a table following straight after is another table.
1464
+ */
1465
+ function tableRtf(table, ctx) {
1466
+ const model = tableModel(table);
1467
+ let rtf = tableCaptionRtf(table, ctx, `\\pard${inCell(ctx)}`);
1468
+ if (model.columns === 0)
1469
+ return rtf;
1470
+ let cumulative = 0;
1471
+ const edges = columnShares(model, table).map((share) => {
1472
+ cumulative += share;
1473
+ return Math.round(cumulative * PAGE_WIDTH);
1474
+ });
1475
+ edges[edges.length - 1] = PAGE_WIDTH; // snap last edge to avoid rounding drift
1476
+ const started = new Set();
1477
+ for (let r = 0; r < model.rows.length; r++) {
1478
+ const row = model.rows[r];
1479
+ let definition = '';
1480
+ let bodies = '';
1481
+ for (let c = 0; c < model.columns;) {
1482
+ const cell = row[c];
1483
+ // The run of columns this cell covers in this row. A slot no cell covers is an
1484
+ // empty cell of one column.
1485
+ let last = c;
1486
+ while (cell !== null && last + 1 < model.columns && row[last + 1] === cell)
1487
+ last++;
1488
+ const origin = cell !== null && cell.row === r && !started.has(cell);
1489
+ if (cell && origin)
1490
+ started.add(cell);
1491
+ const merged = cell !== null && cell.rowspan > 1;
1492
+ if (merged)
1493
+ definition += origin ? '\\clvmgf' : '\\clvmrg';
1494
+ if (cell?.el.tagName.toLowerCase() === 'th')
1495
+ definition += '\\clbrdrb\\brdrs';
1496
+ definition += `\\cellx${edges[last]}`;
1497
+ // A cell with no alignment of its own takes that of what the table is in.
1498
+ const align = cell && origin ? alignOf(cell.el, ctx) : '';
1499
+ let content = '';
1500
+ // (A cell that is not shown keeps its place in the row, empty.)
1501
+ if (cell && origin && !hiddenWithin(cell.el, table)) {
1502
+ // The cell's own color and the like. They end with the cell's group.
1503
+ const own = charFormat(cell.el, 'td', { ...ctx, inTableCell: true, cellAlign: align }, true);
1504
+ content = `${own.on}${withoutTrailingPar(walkChildren(cell.el, own.ctx))}`;
1505
+ }
1506
+ bodies += `{\\pard\\intbl${align} \\f0 \\sa0 \\li0 \\fi0 ${content}\\cell}`;
1507
+ c = last + 1;
1508
+ }
1509
+ const lastRow = r === model.rows.length - 1 ? '\\lastrow' : '';
1510
+ rtf += `{\\trowd\\trgaph120${definition}\\trkeep\\intbl{${bodies}}\\intbl${lastRow}\\row}`;
1511
+ }
1512
+ return rtf;
1513
+ }
1514
+ /**
1515
+ * A table's <caption>, as a centered paragraph before the table, which is where and how a
1516
+ * browser shows it. Anything else in a table that is in no cell (text a script put between the
1517
+ * rows) is written before the table too: nothing in a table is dropped for being outside a cell.
1518
+ */
1519
+ function tableCaptionRtf(table, ctx, paragraph) {
1520
+ let rtf = '';
1521
+ const loose = [];
1522
+ const collect = (parent, depth) => {
1523
+ for (const child of Array.from(parent.childNodes)) {
1524
+ const tag = child.nodeType === Node.ELEMENT_NODE ? child.tagName.toLowerCase() : '';
1525
+ if (tag === 'caption') {
1526
+ if (isHidden(child))
1527
+ continue;
1528
+ const align = ownAlign(child) ?? '\\qc';
1529
+ rtf += flowRtf(Array.from(child.childNodes), ctx, null, `${paragraph}${align === '\\ql' ? '' : align}${liControl(ctx.indent)} `);
1530
+ }
1531
+ else if (tag === 'td' || tag === 'th' || tag === 'colgroup' || tag === 'col') {
1532
+ // A cell is written in its row; a column definition holds no text.
1533
+ }
1534
+ else if (depth < 2 && (tag === 'thead' || tag === 'tbody' || tag === 'tfoot' || tag === 'tr')) {
1535
+ collect(child, tag === 'tr' ? 2 : depth + 1);
1536
+ }
1537
+ else if (tag ? holdsSomething(child) : child.nodeType === Node.TEXT_NODE && !COLLAPSIBLE_WHITESPACE.test(child.textContent || '')) {
1538
+ loose.push(child);
1539
+ }
1540
+ }
1541
+ };
1542
+ collect(table, 0);
1543
+ if (loose.length > 0)
1544
+ rtf += flowRtf(loose, ctx, null, `${paragraph}${cellAlign(ctx)}${liControl(ctx.indent)} `);
1545
+ return rtf;
1546
+ }
1547
+ /**
1548
+ * A table inside a table cell. RTF can nest tables (\itap, \nestcell), but many readers show a
1549
+ * nested table wrongly or not at all, and opening a row inside a cell, as the writer did, is not
1550
+ * valid RTF. So the inner table is written as lines of text in the cell it is in: each of its
1551
+ * rows a paragraph, its cells a tab apart. Every word is kept; the inner grid is not.
1552
+ */
1553
+ function nestedTableRtf(table, ctx) {
1554
+ let rtf = followsInlineContent(table, ctx.root) ? '\\par ' : '';
1555
+ rtf += tableCaptionRtf(table, ctx, '\\pard\\intbl');
1556
+ for (const row of tableRowsInOrder(table)) {
1557
+ const cells = rowCells(row);
1558
+ if (cells.length === 0)
1559
+ continue;
1560
+ const line = cells.map((cell) => (hiddenWithin(cell, table) ? '' : withoutTrailingPar(walkChildren(cell, ctx)))).join('\\tab ');
1561
+ rtf += `\\pard\\intbl${cellAlign(ctx)} ${line}\\par `;
1562
+ }
886
1563
  return rtf;
887
1564
  }
888
1565
  /** Body size times a ratio, in half-points. */
@@ -898,8 +1575,9 @@ const BLOCK_TAGS = new Set([
898
1575
  'p', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li', 'table', 'thead',
899
1576
  'tbody', 'tfoot', 'tr', 'td', 'th', 'blockquote', 'pre', 'hr', 'figure', 'figcaption'
900
1577
  ]);
1578
+ /** (An element that is not shown is no block: it ends no line, and the space beside it is still a space.) */
901
1579
  function isBlock(node) {
902
- return node?.nodeType === Node.ELEMENT_NODE && BLOCK_TAGS.has(node.tagName.toLowerCase());
1580
+ return node?.nodeType === Node.ELEMENT_NODE && BLOCK_TAGS.has(tagOf(node)) && !isHidden(node);
903
1581
  }
904
1582
  /** A text node with a block element on either side, or at the edge of one. */
905
1583
  function besideBlock(node) {
@@ -907,27 +1585,130 @@ function besideBlock(node) {
907
1585
  const next = node.nextSibling;
908
1586
  return isBlock(prev) || isBlock(next) || (!prev && !next && isBlock(node.parentNode));
909
1587
  }
1588
+ /**
1589
+ * Whether a <br> is one a browser shows nothing for: the last thing in its block, where an editor
1590
+ * leaves one so the line has height, or right before a block, which starts a new line anyway.
1591
+ */
1592
+ function isTrailingBreak(br, ctx) {
1593
+ let node = br;
1594
+ for (;;) {
1595
+ let next = node.nextSibling;
1596
+ while (next &&
1597
+ (next.nodeType === Node.COMMENT_NODE ||
1598
+ (next.nodeType === Node.ELEMENT_NODE && isHidden(next)) ||
1599
+ (next.nodeType === Node.TEXT_NODE && COLLAPSIBLE_WHITESPACE.test(next.textContent || '') && !showsTabs(next)))) {
1600
+ next = next.nextSibling;
1601
+ }
1602
+ if (next)
1603
+ return isBlock(next);
1604
+ const parent = node.parentNode;
1605
+ if (!parent || parent === ctx.root || isBlock(parent))
1606
+ return true;
1607
+ node = parent;
1608
+ }
1609
+ }
1610
+ /** Blocks other than <p> and <div> that end the loose text before them (walkNode). */
1611
+ const BREAKS_LOOSE_TEXT = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'table', 'blockquote', 'pre', 'hr', 'ul', 'ol', 'li', 'figure']);
910
1612
  /** A <p> or <div> with no content, or only a <br>: a blank line. */
911
1613
  function isBlankLine(el) {
912
1614
  return el.childNodes.length === 0 || (el.childNodes.length === 1 && el.childNodes[0].nodeName === 'BR');
913
1615
  }
1616
+ /** Collapsible whitespace, a comment, or an element that is not shown: nothing that shows. */
1617
+ function showsNothing(node) {
1618
+ if (node.nodeType === Node.ELEMENT_NODE)
1619
+ return isHidden(node);
1620
+ return node.nodeType === Node.COMMENT_NODE || (node.nodeType === Node.TEXT_NODE && COLLAPSIBLE_WHITESPACE.test(node.textContent || ''));
1621
+ }
914
1622
  /**
915
- * Whether the nearest sibling before this element, skipping collapsible whitespace, is
916
- * text or an inline element: content with no paragraph of its own.
1623
+ * Whether a block ends its own line in the RTF. Every block does, except a <figcaption> outside a
1624
+ * figure, whose text is written where it stands.
917
1625
  */
918
- function followsInlineContent(el) {
919
- let prev = el.previousSibling;
920
- while (prev && prev.nodeType === Node.TEXT_NODE && COLLAPSIBLE_WHITESPACE.test(prev.textContent || '')) {
921
- prev = prev.previousSibling;
1626
+ function endsItsLine(node) {
1627
+ return isBlock(node) && node.nodeName !== 'FIGCAPTION';
1628
+ }
1629
+ /** Whether an inline element's content ends with a block, which has ended its own line. */
1630
+ function endsWithBlock(el) {
1631
+ // (Down the last thing in the last thing, in a loop: no call for each level of nesting.)
1632
+ for (let at = el;;) {
1633
+ let last = at.lastChild;
1634
+ while (last && showsNothing(last))
1635
+ last = last.previousSibling;
1636
+ if (!last || last.nodeType !== Node.ELEMENT_NODE)
1637
+ return false;
1638
+ if (endsItsLine(last))
1639
+ return true;
1640
+ at = last;
922
1641
  }
923
- if (!prev)
1642
+ }
1643
+ /**
1644
+ * Whether the nearest sibling before this element, skipping collapsible whitespace and comments,
1645
+ * is text or an inline element: content with no paragraph of its own. Not when that content has
1646
+ * already ended its line: a picture straight under `root` writes its own paragraph, and a wrapper
1647
+ * whose last child is a block (Google Docs wraps a paste in <b id="docs-internal-guid-…">) ends
1648
+ * with that block's.
1649
+ */
1650
+ function followsInlineContent(el, root = null) {
1651
+ let node = el;
1652
+ for (;;) {
1653
+ let prev = node.previousSibling;
1654
+ while (prev && showsNothing(prev))
1655
+ prev = prev.previousSibling;
1656
+ if (prev) {
1657
+ if (prev.nodeType === Node.TEXT_NODE)
1658
+ return true;
1659
+ if (prev.nodeType !== Node.ELEMENT_NODE || endsItsLine(prev))
1660
+ return false;
1661
+ if (prev.nodeName === 'IMG' && root !== null && prev.parentNode === root)
1662
+ return false;
1663
+ return !endsWithBlock(prev);
1664
+ }
1665
+ // The first thing in an inline wrapper (<b><p>…</p></b>, the wrapper of a Google Docs
1666
+ // paste, a <span> around a list) follows what the wrapper follows: text typed before
1667
+ // the paste was run into its first paragraph.
1668
+ const parent = node.parentNode;
1669
+ if (!parent || parent === root || parent.nodeType !== Node.ELEMENT_NODE || isBlock(parent))
1670
+ return false;
1671
+ node = parent;
1672
+ }
1673
+ }
1674
+ /**
1675
+ * The nearest sibling before a node that shows something, past white space, comments and hidden
1676
+ * elements. Each node passed on the way is remembered with the same answer, so a page of
1677
+ * thousands of comments in a row is looked back over once, not from every piece of text among
1678
+ * them: that took seconds, and in a test DOM, where stepping to a sibling is itself slow, far more.
1679
+ */
1680
+ function shownBefore(node, ctx) {
1681
+ const passed = [];
1682
+ let found = ctx.shownBefore.get(node);
1683
+ for (let at = node; found === undefined;) {
1684
+ passed.push(at);
1685
+ const prev = at.previousSibling;
1686
+ if (!prev || !showsNothing(prev))
1687
+ found = prev;
1688
+ else {
1689
+ found = ctx.shownBefore.get(prev);
1690
+ at = prev;
1691
+ }
1692
+ }
1693
+ for (const each of passed)
1694
+ ctx.shownBefore.set(each, found);
1695
+ return found;
1696
+ }
1697
+ /** Whether the nearest sibling after this element, skipping collapsible whitespace, is text or an inline element. */
1698
+ function followedByInline(el) {
1699
+ let next = el.nextSibling;
1700
+ while (next && showsNothing(next))
1701
+ next = next.nextSibling;
1702
+ if (!next)
924
1703
  return false;
925
- if (prev.nodeType === Node.TEXT_NODE)
926
- return true;
927
- return prev.nodeType === Node.ELEMENT_NODE && !isBlock(prev);
1704
+ return next.nodeType === Node.TEXT_NODE || (next.nodeType === Node.ELEMENT_NODE && !isBlock(next));
928
1705
  }
929
- /** Blocks whose last paragraph always carries an indent or alignment of its own. */
930
- const FORMATTED_BLOCK_TAGS = new Set(['ul', 'ol', 'blockquote', 'figure', 'hr']);
1706
+ /**
1707
+ * Blocks whose last paragraph always carries an indent or alignment of its own. A table is one:
1708
+ * its rows are a group, and when the group ends the paragraph formatting in force is that of
1709
+ * whatever came before the table.
1710
+ */
1711
+ const FORMATTED_BLOCK_TAGS = new Set(['ul', 'ol', 'li', 'blockquote', 'figure', 'hr', 'table']);
931
1712
  /**
932
1713
  * Loose text or an inline element right after a block has no paragraph of its own, and would
933
1714
  * keep that block's alignment and indent (a centered line's \qc, a list's \li). Start a plain
@@ -935,19 +1716,17 @@ const FORMATTED_BLOCK_TAGS = new Set(['ul', 'ol', 'blockquote', 'figure', 'hr'])
935
1716
  * nothing is written, as before.
936
1717
  */
937
1718
  function restateAfterBlock(node, ctx) {
938
- let prev = node.previousSibling;
939
- while (prev && prev.nodeType === Node.TEXT_NODE && COLLAPSIBLE_WHITESPACE.test(prev.textContent || '')) {
940
- prev = prev.previousSibling;
941
- }
1719
+ const prev = shownBefore(node, ctx);
942
1720
  if (!isBlock(prev))
943
1721
  return '';
944
1722
  const block = prev;
945
- const tag = block.tagName.toLowerCase();
1723
+ const tag = tagOf(block);
946
1724
  const formatted = FORMATTED_BLOCK_TAGS.has(tag) ||
947
- (['p', 'div'].includes(tag) && (ctx.inTableCell ? paragraphLayout(block, ctx) : paragraphFormat(block, ctx)) !== '') ||
948
- (['h1', 'h2', 'h3'].includes(tag) && headingLayout(block, ctx) !== '') ||
1725
+ // (A container's own alignment or indent is its blocks': what is inside it had them.)
1726
+ (['p', 'div'].includes(tag) && ((ctx.inTableCell ? paragraphLayout(block, ctx) : paragraphFormat(block, ctx)) !== '' || Array.from(block.children).some(isBlock))) ||
1727
+ (HEADING_TAGS.has(tag) && headingLayout(block, ctx) !== '') ||
949
1728
  (tag === 'pre' && ctx.indent + leftMarginTwips(block) > 0);
950
- return formatted ? `\\pard${inCell(ctx)}${liControl(ctx.indent)} ` : '';
1729
+ return formatted ? `\\pard${inCell(ctx)}${cellAlign(ctx)}${liControl(ctx.indent)} ` : '';
951
1730
  }
952
1731
  /**
953
1732
  * The cell's own \par ends its last paragraph, so that paragraph's mark is dropped. Only a
@@ -974,7 +1753,7 @@ function lengthTwips(value, allowNegative = false) {
974
1753
  const twips = Math.round(parseFloat(m[1]) * TWIPS_PER_UNIT[m[2]]);
975
1754
  if (twips < 0 && !allowNegative)
976
1755
  return null;
977
- return twips;
1756
+ return Math.max(-MAX_TWIPS, Math.min(MAX_TWIPS, twips));
978
1757
  }
979
1758
  /**
980
1759
  * An element's own left margin in twips, from its inline style: what the browser's Indent sets
@@ -993,19 +1772,28 @@ function isIndentBlockquote(el) {
993
1772
  }
994
1773
  /** \liN for a left indent in twips, or nothing when there is none. */
995
1774
  function liControl(twips) {
996
- return twips > 0 ? `\\li${twips}` : '';
1775
+ // (Indents add up through nested blocks: the sum is kept on the page too.)
1776
+ return twips > 0 ? `\\li${Math.min(twips, MAX_TWIPS)}` : '';
997
1777
  }
998
- /** \qc, \qr or \qj; left is the default and is not written. */
999
- function alignOf(el) {
1000
- const align = alignControl(el);
1001
- return align === '\\ql' ? '' : align;
1778
+ /**
1779
+ * \qc, \qr or \qj; left is the default and is not written. Inside a table cell that is aligned
1780
+ * itself, a block with no alignment of its own takes the cell's, and one set left says so.
1781
+ */
1782
+ function alignOf(el, ctx) {
1783
+ const own = ownAlign(el);
1784
+ const cell = ctx ? cellAlign(ctx) : '';
1785
+ if (own == null)
1786
+ return cell;
1787
+ if (own === '\\ql')
1788
+ return cell ? own : '';
1789
+ return own;
1002
1790
  }
1003
1791
  /**
1004
1792
  * A heading's, or a paragraph's inside a table cell: its alignment, and \liN for the indent of
1005
1793
  * the blocks around it plus its own margin.
1006
1794
  */
1007
1795
  function paragraphLayout(el, ctx) {
1008
- return `${alignOf(el)}${liControl(ctx.indent + leftMarginTwips(el))}`;
1796
+ return `${alignOf(el, ctx)}${liControl(ctx.indent + leftMarginTwips(el))}`;
1009
1797
  }
1010
1798
  /**
1011
1799
  * A heading's layout: its alignment and left indent, and outside a table cell its right and
@@ -1025,7 +1813,14 @@ function edgeIndents(el) {
1025
1813
  * indent of the blocks around it plus its own margin.
1026
1814
  */
1027
1815
  function paragraphFormat(el, ctx) {
1028
- return `${alignOf(el)}${paragraphControls(el, ctx.indent + leftMarginTwips(el))}`;
1816
+ return `${alignOf(el, ctx)}${paragraphControls(el, ctx.indent + leftMarginTwips(el))}`;
1817
+ }
1818
+ /** The alignment a container hands to the blocks inside it: its own, or the one it was handed. */
1819
+ function inheritedAlign(el, ctx) {
1820
+ const own = ownAlign(el);
1821
+ if (own == null)
1822
+ return ctx.cellAlign;
1823
+ return own === '\\ql' ? '' : own;
1029
1824
  }
1030
1825
  /**
1031
1826
  * The RTF paragraph controls for a <p> or <div>'s own formatting, or '' when it sets none:
@@ -1072,7 +1867,7 @@ function followsFormattedParagraph(el, ctx) {
1072
1867
  const prev = el.previousElementSibling;
1073
1868
  if (!prev)
1074
1869
  return false;
1075
- const tag = prev.tagName.toLowerCase();
1870
+ const tag = tagOf(prev);
1076
1871
  return (tag === 'p' || tag === 'div') && paragraphFormat(prev, ctx) !== '';
1077
1872
  }
1078
1873
  /** Whether a container's first (or last) content is loose text or an inline element, not a block. */
@@ -1087,7 +1882,7 @@ function edgeIsInline(el, edge) {
1087
1882
  if (edge === 'last')
1088
1883
  nodes.reverse();
1089
1884
  for (const n of nodes) {
1090
- if (n.nodeType === Node.TEXT_NODE && COLLAPSIBLE_WHITESPACE.test(n.textContent || ''))
1885
+ if (showsNothing(n))
1091
1886
  continue;
1092
1887
  return !isBlock(n);
1093
1888
  }
@@ -1097,6 +1892,18 @@ function edgeIsInline(el, edge) {
1097
1892
  function inCell(ctx) {
1098
1893
  return ctx.inTableCell ? '\\intbl' : '';
1099
1894
  }
1895
+ /**
1896
+ * The alignment a block takes when it sets none (\qc, \qr or \qj): that of the table cell the
1897
+ * walker is in, or of a <div> or <center> around the block.
1898
+ */
1899
+ function cellAlign(ctx) {
1900
+ return ctx.cellAlign;
1901
+ }
1902
+ /** Whether a rule stands for a page break: <hr style="break-after:page">, as the parser writes \page. */
1903
+ function isPageBreak(el) {
1904
+ const value = (prop) => el.style?.getPropertyValue(prop).trim();
1905
+ return value('break-after') === 'page' || value('page-break-after') === 'always';
1906
+ }
1100
1907
  /** Color-table index of the element's own color, or null when it sets none. */
1101
1908
  function colorIndexOf(el, ctx) {
1102
1909
  // Support both inline style.color (spans) and the color attribute (<font>)
@@ -1109,16 +1916,25 @@ function colorIndexOf(el, ctx) {
1109
1916
  return null;
1110
1917
  return ctx.colorIndex.get(colorKey(c)) ?? null;
1111
1918
  }
1919
+ /**
1920
+ * The sizes of <font size="1"> to <font size="7">, in half-points, as browsers show them
1921
+ * (10, 13, 16, 18, 24, 32 and 48 px). Older pages and mail carry their sizes this way.
1922
+ */
1923
+ const FONT_SIZE_ATTRIBUTE = [15, 20, 24, 27, 36, 48, 72];
1112
1924
  /** The element's own font size in half-points, or null when it sets none. */
1113
1925
  function sizeOf(el) {
1114
1926
  const fs = el.style?.fontSize;
1115
- if (!fs)
1116
- return null;
1927
+ if (!fs) {
1928
+ const step = el.tagName === 'FONT' ? /^\s*([1-7])\s*$/.exec(el.getAttribute('size') ?? '') : null;
1929
+ return step ? FONT_SIZE_ATTRIBUTE[Number(step[1]) - 1] : null;
1930
+ }
1931
+ // From half a point to Word's largest size; a size that is no number, or zero, is no size.
1932
+ const halfPoints = (points) => Number.isFinite(points) && points > 0 ? Math.min(MAX_FONT_SIZE * 2, Math.max(1, Math.round(points * 2))) : null;
1117
1933
  const ptMatch = fs.match(/([\d.]+)\s*pt/);
1118
1934
  if (ptMatch)
1119
- return Math.round(parseFloat(ptMatch[1]) * 2);
1935
+ return halfPoints(parseFloat(ptMatch[1]));
1120
1936
  const pxMatch = fs.match(/([\d.]+)\s*px/);
1121
1937
  if (pxMatch)
1122
- return Math.round(parseFloat(pxMatch[1]) * 0.75 * 2);
1938
+ return halfPoints(parseFloat(pxMatch[1]) * 0.75);
1123
1939
  return null;
1124
1940
  }