svelte-rtf-editor 1.9.0 → 1.11.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,8 +2,8 @@
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, headings
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
7
  * (h1–h6), foreground colors (\cf), paragraphs with their alignment and indents,
8
8
  * bullet/numbered lists and lists inside them, blockquotes, code blocks,
9
9
  * hyperlinks, tables with merged cells, images (embedded as \pict picture groups
@@ -14,8 +14,13 @@
14
14
  * is inconsistent across viewers (TextEdit uses \AppleHighlight, not \highlight).
15
15
  */
16
16
  import { tableModel, columnShares, tableRowsInOrder, rowCells } from './table-model.js';
17
- /** Font used when no fontFamily is given. */
18
- export const DEFAULT_FONT_FAMILY = 'Arial';
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';
19
24
  /** Body text size, in points, used when no fontSize is given. */
20
25
  export const DEFAULT_FONT_SIZE = 12;
21
26
  /** Largest font size RTF readers accept (Word's limit), in points. */
@@ -45,21 +50,36 @@ export const PRE_SCALE = 5 / 6;
45
50
  export const LINK_COLOR = { r: 0, g: 0, b: 255 };
46
51
  /** 1 px at 96 dpi = 15 twips (1 twip = 1/1440 in). */
47
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;
48
65
  // ── Color helpers ──
49
66
  function parseColor(colorStr) {
50
67
  if (!colorStr)
51
68
  return null;
52
69
  const s = colorStr.trim().toLowerCase();
53
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.)
54
72
  const rgbMatch = s.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
55
73
  if (rgbMatch) {
56
- 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]) };
57
76
  }
58
- // Hex
59
- 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})$/);
60
80
  if (hexMatch) {
61
81
  let hex = hexMatch[1];
62
- if (hex.length === 3)
82
+ if (hex.length <= 4)
63
83
  hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
64
84
  return {
65
85
  r: parseInt(hex.substring(0, 2), 16),
@@ -98,7 +118,17 @@ function escapeRtf(text) {
98
118
  for (let i = 0; i < source.length; i++) {
99
119
  const ch = source[i];
100
120
  const code = source.charCodeAt(i);
101
- 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 === '\\')
102
132
  out += '\\\\';
103
133
  else if (ch === '{')
104
134
  out += '\\{';
@@ -140,6 +170,75 @@ function showsTabs(node) {
140
170
  }
141
171
  return false;
142
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
+ }
143
242
  // ── Image helpers ──
144
243
  const B64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
145
244
  const B64_LOOKUP = (() => {
@@ -261,6 +360,12 @@ function displaySize(el, natural) {
261
360
  let h = parsePx(el.style?.height) || (Number.isFinite(attrH) ? attrH : 0);
262
361
  if (!h)
263
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)) };
264
369
  return { w, h };
265
370
  }
266
371
  /**
@@ -273,7 +378,8 @@ function pictureRtf(el) {
273
378
  // Accept any image data URL and let the bytes decide the format — the label
274
379
  // is not trustworthy, and a correctly-labelled PNG is not the only way to
275
380
  // arrive at PNG bytes.
276
- 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);
277
383
  if (!m)
278
384
  return '';
279
385
  const bytes = base64ToBytes(m[1]);
@@ -303,13 +409,17 @@ function imageBody(el) {
303
409
  const pict = pictureRtf(el);
304
410
  if (pict)
305
411
  return pict;
306
- 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';
307
417
  return `\\i [Image: ${escapeRtf(label)}]\\i0 `;
308
418
  }
309
419
  /** \ql / \qc / \qr / \qj for a block's own text-align, or null when it sets none. */
310
420
  function ownAlign(el) {
311
421
  // Firefox's Center writes <p align="center">, not a style.
312
- const align = (el.style?.textAlign || el.getAttribute?.('align') || '').toLowerCase();
422
+ const align = (el.style?.textAlign || el.getAttribute?.('align') || (el.tagName === 'CENTER' ? 'center' : '')).toLowerCase();
313
423
  if (align === 'center')
314
424
  return '\\qc';
315
425
  if (align === 'right' || align === 'end')
@@ -330,10 +440,10 @@ function base64ByteLength(base64) {
330
440
  return Math.max(0, Math.floor((base64.length * 3) / 4) - padding);
331
441
  }
332
442
  /**
333
- * Bytes of RTF header, font table and colour table that precede the body, with
334
- * 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.
335
445
  */
336
- const RTF_PREAMBLE_BYTES = 165;
446
+ const RTF_PREAMBLE_BYTES = 160;
337
447
  /** Control words wrapping one \pict group. */
338
448
  const PICTURE_OVERHEAD_BYTES = 80;
339
449
  /**
@@ -355,15 +465,21 @@ const BLOCK_OVERHEAD_BYTES = {
355
465
  pre: 27,
356
466
  figure: 15,
357
467
  figcaption: 29,
468
+ caption: 20, // "\pard\intbl\qc " + "\par "
469
+ table: 8, // "\lastrow"
358
470
  tr: 45,
359
- td: 55,
360
- 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
361
473
  // Inline formatting: the control words on either side of the text.
362
474
  b: 7, // "\b " + "\b0 "
363
475
  strong: 7,
364
476
  i: 7,
365
477
  em: 7,
478
+ cite: 7,
479
+ var: 7,
480
+ dfn: 7,
366
481
  u: 12, // "\ul " + "\ulnone "
482
+ ins: 12,
367
483
  s: 17, // "\strike " + "\strike0 "
368
484
  strike: 17,
369
485
  del: 17,
@@ -375,6 +491,20 @@ const BLOCK_OVERHEAD_BYTES = {
375
491
  ul: 0,
376
492
  ol: 0
377
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
+ }
378
508
  /** Elements that write a paragraph of their own, which inside a table cell carries \intbl. */
379
509
  const CELL_PARAGRAPH_TAGS = new Set(['p', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li', 'blockquote', 'pre', 'hr', 'figure', 'figcaption']);
380
510
  /** The field wrapper around a link, apart from its address. */
@@ -391,34 +521,64 @@ const LINK_OVERHEAD_BYTES = '{\\field{\\*\\fldinst HYPERLINK ""}{\\fldrslt\\ul\\
391
521
  * is negligible precisely when the number matters, and never more than a few
392
522
  * hundred bytes even when it does not. The output is ASCII, so bytes and
393
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.
394
527
  */
395
- export function estimateRtfBytes(editorEl) {
396
- 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;
397
537
  for (const img of Array.from(editorEl.querySelectorAll('img'))) {
398
538
  const src = img.getAttribute('src') || '';
399
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;
400
549
  if (!src.startsWith('data:image/') || comma < 0) {
401
- // A picture that cannot be embedded costs its placeholder text.
402
- total += `\\i [Image: ]\\i0 `.length + escapeRtf(img.getAttribute('alt') || src || 'image').length;
550
+ total += placeholder;
403
551
  continue;
404
552
  }
405
- 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);
406
555
  }
407
556
  // A document with a link carries the link color in its color table ("\red0\green0\blue255;").
408
557
  if (hasLink(editorEl))
409
558
  total += 22;
559
+ const blockSelector = ['p', 'div', 'li', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'pre', 'blockquote', 'figure', 'figcaption', ...DIV_LIKE_TAGS].join(', ');
410
560
  // Text at its escaped length: a character outside ASCII costs its \uN\'3f escape,
411
561
  // six to nine bytes rather than one.
412
- 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;
413
565
  // A tab that shows is written as "\tab " (5) and counted as 1; counting every tab that way
414
566
  // can only overestimate.
415
567
  total += ((editorEl.textContent || '').match(/\t/g)?.length ?? 0) * 4;
416
568
  // A block's alignment (\qc, 3) and left indent (\liN, up to 7) are written per paragraph,
417
569
  // for every block inside an indented one too: count 12 for each block that could carry them.
418
570
  // A paragraph's own right indent (\\riN) and first-line indent (\\fi-N) are up to 8 more each.
419
- for (const block of Array.from(editorEl.querySelectorAll('p, div, li, h1, h2, h3, h4, h5, h6, pre, blockquote'))) {
420
- 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]'))
421
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"
422
582
  if (block.style?.marginRight)
423
583
  total += 8;
424
584
  if (block.style?.textIndent)
@@ -435,8 +595,31 @@ export function estimateRtfBytes(editorEl) {
435
595
  return format;
436
596
  };
437
597
  for (const el of Array.from(editorEl.querySelectorAll('*'))) {
438
- const tag = el.tagName.toLowerCase();
439
- 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
+ }
440
623
  if (tag === 'a') {
441
624
  const target = linkTarget(el.getAttribute('href') || '');
442
625
  if (target)
@@ -476,7 +659,8 @@ export function estimateRtfBytes(editorEl) {
476
659
  // is written once in each of them, marked \clvmgf or \clvmrg (7). A table inside a cell
477
660
  // is written as text, which costs less than the cells counted for it.
478
661
  if (tag === 'td' || tag === 'th') {
479
- if (el.style?.textAlign || el.hasAttribute('align'))
662
+ // (Its own, or the one a block around the table hands down.)
663
+ if (el.closest('center, [style*="text-align"], [align]'))
480
664
  total += 3;
481
665
  const rows = parseInt(el.getAttribute('rowspan') ?? '', 10);
482
666
  if (rows !== 1 && Number.isFinite(rows) && !el.parentElement?.closest('td, th')) {
@@ -492,6 +676,18 @@ export function estimateRtfBytes(editorEl) {
492
676
  for (const row of model.rows)
493
677
  total += row.filter((slot) => slot === null).length * BLOCK_OVERHEAD_BYTES.td;
494
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
+ }
495
691
  // Text or an inline element after a block starts a paragraph of its own where that
496
692
  // block set an indent or alignment ("\pard\intbl\qc\li1440 ", and its "\par ").
497
693
  if (isBlock(el) && followedByInline(el))
@@ -515,12 +711,17 @@ export function estimateRtfBytes(editorEl) {
515
711
  // "\par " (at most 30).
516
712
  if (tag === 'figure' && !el.querySelector('img'))
517
713
  total += 30;
518
- // A color costs "\cfN " on and off and, the first time, its color-table entry (at most
519
- // 22 bytes, "\red255\green255\blue255;"); a size costs "\fsNN " on and off.
520
- if (el.style?.color || (tag === 'font' && el.hasAttribute('color')))
521
- total += 10 + 22;
522
- if (el.style?.fontSize)
523
- total += 14; // "\fsNNN " on and off, for sizes up to 499 pt
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;
524
725
  }
525
726
  return total;
526
727
  }
@@ -649,6 +850,7 @@ export function htmlToRtf(editorEl, options = {}) {
649
850
  listCounter: 0,
650
851
  inTableCell: false,
651
852
  root: editorEl,
853
+ shownBefore: new Map(),
652
854
  bold: false,
653
855
  italic: false,
654
856
  underline: false,
@@ -680,13 +882,33 @@ function addColor(colorStr, colorMap) {
680
882
  if (c)
681
883
  colorMap.set(colorKey(c), c);
682
884
  }
683
- function collectColors(el, colorMap) {
684
- addColor(el.style?.color, colorMap);
685
- // <font color="..."> is produced by execCommand('foreColor')
686
- if (el.tagName?.toLowerCase() === 'font')
687
- addColor(el.getAttribute('color'), colorMap);
688
- for (const child of el.children)
689
- 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;
690
912
  }
691
913
  function walkChildren(parent, ctx) {
692
914
  let rtf = '';
@@ -701,8 +923,22 @@ function walkChildren(parent, ctx) {
701
923
  * line before a block (flowRtf).
702
924
  */
703
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) {
704
938
  let rtf = '';
705
939
  if (node.nodeType === Node.TEXT_NODE) {
940
+ if (isUnseen(node))
941
+ return '';
706
942
  const text = node.textContent || '';
707
943
  // Whitespace between two blocks (the newline in "</p>\n<p>") shows as
708
944
  // nothing in a browser. Written out, it became a space at the start of
@@ -712,11 +948,12 @@ function walkNode(node, ctx, restate = true, endLooseText = true) {
712
948
  return '';
713
949
  if (!ctx.inPre && restate)
714
950
  rtf += restateAfterBlock(node, ctx);
715
- if (ctx.inPre) {
951
+ if (ctx.inPre || showsLineBreaks(node)) {
716
952
  // Split before escaping — escapeRtf collapses newlines, so the
717
953
  // line structure a <pre> block depends on has to become \line
718
- // first. Handles CR, LF and CRLF alike.
719
- rtf += text.split(/\r\n|\r|\n/).map((line) => escapeTabs(line, true)).join('\\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 ');
720
957
  }
721
958
  else {
722
959
  rtf += escapeTabs(text, tabsShow);
@@ -726,7 +963,9 @@ function walkNode(node, ctx, restate = true, endLooseText = true) {
726
963
  if (node.nodeType !== Node.ELEMENT_NODE)
727
964
  return '';
728
965
  const el = node;
729
- const tag = el.tagName.toLowerCase();
966
+ if (isHidden(el))
967
+ return '';
968
+ const tag = tagOf(el);
730
969
  // Text typed straight into the parent before a block ("Diagnosis:<ul>…", the shape Chrome
731
970
  // makes when the line after it becomes a list) has no paragraph of its own: it is ended here,
732
971
  // or \pard would carry it into the block's first line. A <p> or <div>, and a table inside a
@@ -747,13 +986,15 @@ function walkNode(node, ctx, restate = true, endLooseText = true) {
747
986
  case 'h5':
748
987
  case 'h6': {
749
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);
750
991
  // A heading that holds a block (a list made in it with the browser's list command)
751
992
  // is not a paragraph itself; what is inside is written at the heading's size, bold.
752
993
  if (Array.from(el.children).some(isBlock)) {
753
- rtf += `\\fs${size}${ctx.bold ? '' : '\\b'} ${walkChildren(el, { ...ctx, bold: true, size })}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size} `;
994
+ rtf += `\\fs${size}${ctx.bold ? '' : '\\b'} ${own.on}${walkChildren(el, own.ctx)}${own.off}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size} `;
754
995
  break;
755
996
  }
756
- 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 `;
757
998
  break;
758
999
  }
759
1000
  case 'p':
@@ -772,15 +1013,16 @@ function walkNode(node, ctx, restate = true, endLooseText = true) {
772
1013
  // carried into the blocks instead, and loose text in it gets a paragraph. A <p> that
773
1014
  // holds a block is the same: no parser makes one, but a browser's own list command
774
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);
775
1018
  if (Array.from(el.children).some(isBlock)) {
776
1019
  const indent = ctx.indent + leftMarginTwips(el);
777
- const colorIdx = colorIndexOf(el, ctx);
778
- const inner = { ...ctx, indent, color: colorIdx ?? ctx.color };
779
- const lead = startsWithInline(el) ? `\\pard${inCell(ctx)}${cellAlign(ctx)}${liControl(indent)} ` : '';
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)} ` : '';
780
1024
  const tail = endsWithInline(el) ? '\\par ' : '';
781
- const colorPrefix = colorIdx != null ? `\\cf${colorIdx} ` : '';
782
- const colorSuffix = colorIdx != null ? `\\cf${ctx.color} ` : '';
783
- rtf += `${afterLooseText ? '\\par ' : ''}${lead}${colorPrefix}${walkChildren(el, inner)}${colorSuffix}${tail}`;
1025
+ rtf += `${afterLooseText ? '\\par ' : ''}${lead}${own.on}${walkChildren(el, inner)}${own.off}${tail}`;
784
1026
  break;
785
1027
  }
786
1028
  if (ctx.inTableCell) {
@@ -793,11 +1035,7 @@ function walkNode(node, ctx, restate = true, endLooseText = true) {
793
1035
  rtf += `${restate}\\par `;
794
1036
  break;
795
1037
  }
796
- const colorIdx = colorIndexOf(el, ctx);
797
- const inner = walkChildren(el, colorIdx != null ? { ...ctx, color: colorIdx } : ctx);
798
- rtf += colorIdx != null
799
- ? `${restate}\\cf${colorIdx} ${inner}\\cf${ctx.color} \\par `
800
- : `${restate}${inner}\\par `;
1038
+ rtf += `${restate}${own.on}${walkChildren(el, own.ctx)}${own.off}\\par `;
801
1039
  break;
802
1040
  }
803
1041
  // The paragraph's alignment, indents, spacing, keep-with-next and tab stops, if it
@@ -812,11 +1050,7 @@ function walkNode(node, ctx, restate = true, endLooseText = true) {
812
1050
  rtf += `${afterLooseText ? '\\par ' : ''}${reset}\\par `;
813
1051
  break;
814
1052
  }
815
- const colorIdx = colorIndexOf(el, ctx);
816
- const inlineRtf = walkChildren(el, colorIdx != null ? { ...ctx, color: colorIdx } : ctx);
817
- const colorPrefix = colorIdx != null ? `\\cf${colorIdx} ` : '';
818
- const colorSuffix = colorIdx != null ? `\\cf${ctx.color} ` : '';
819
- rtf += `${afterLooseText ? '\\par ' : ''}\\pard${para} ${colorPrefix}${inlineRtf}${colorSuffix}\\par `;
1053
+ rtf += `${afterLooseText ? '\\par ' : ''}\\pard${para} ${own.on}${walkChildren(el, own.ctx)}${own.off}\\par `;
820
1054
  break;
821
1055
  }
822
1056
  case 'table':
@@ -858,56 +1092,33 @@ function walkNode(node, ctx, restate = true, endLooseText = true) {
858
1092
  case 'li': {
859
1093
  // An item with no list around it (a pasted fragment) shows with a bullet.
860
1094
  const left = ctx.indent + LIST_STEP;
861
- const start = `\\pard${inCell(ctx)}${cellAlign(ctx)}${liControl(left)}`;
862
- rtf += flowRtf(Array.from(el.childNodes), { ...ctx, indent: left }, `${start}\\fi-${LIST_HANG}\\bullet\\tab `, `${start} `);
863
- break;
864
- }
865
- case 'strong':
866
- case 'b':
867
- rtf += ctx.bold ? walkChildren(el, ctx) : `\\b ${walkChildren(el, { ...ctx, bold: true })}\\b0 `;
868
- break;
869
- case 'em':
870
- case 'i':
871
- rtf += ctx.italic ? walkChildren(el, ctx) : `\\i ${walkChildren(el, { ...ctx, italic: true })}\\i0 `;
872
- break;
873
- case 'u':
874
- rtf += ctx.underline ? walkChildren(el, ctx) : `\\ul ${walkChildren(el, { ...ctx, underline: true })}\\ulnone `;
875
- break;
876
- case 's':
877
- case 'strike':
878
- case 'del':
879
- rtf += ctx.strike ? walkChildren(el, ctx) : `\\strike ${walkChildren(el, { ...ctx, strike: true })}\\strike0 `;
880
- break;
881
- case 'sup':
882
- case 'sub': {
883
- const script = tag === 'sup' ? 'super' : 'sub';
884
- if (ctx.script === script) {
885
- rtf += walkChildren(el, ctx);
886
- break;
887
- }
888
- const restore = ctx.script ? `\\${ctx.script} ` : '\\nosupersub ';
889
- rtf += `\\${script} ${walkChildren(el, { ...ctx, script })}${restore}`;
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}`;
890
1098
  break;
891
1099
  }
892
- case 'code':
1100
+ case 'code': {
1101
+ const own = charFormat(el, tag, ctx);
893
1102
  if (!ctx.inPre && !ctx.mono) {
894
- rtf += `\\f1 ${walkChildren(el, { ...ctx, mono: true })}\\f0 `;
1103
+ rtf += `${own.on}\\f1 ${walkChildren(el, { ...own.ctx, mono: true })}\\f0 ${own.off}`;
895
1104
  }
896
1105
  else {
897
- rtf += walkChildren(el, ctx);
1106
+ rtf += `${own.on}${walkChildren(el, own.ctx)}${own.off}`;
898
1107
  }
899
1108
  break;
1109
+ }
900
1110
  case 'a': {
1111
+ const own = charFormat(el, tag, ctx);
901
1112
  // A link is written only for an absolute web, mail or phone address; anything
902
1113
  // else (a relative or UNC path, javascript:, data:, file:) as its text alone.
903
1114
  const target = linkTarget(el.getAttribute('href') || '');
904
1115
  if (target) {
905
- const inner = walkChildren(el, { ...ctx, underline: true, color: 1 });
906
- const underlineOff = ctx.underline ? '' : '\\ulnone';
907
- rtf += `{\\field{\\*\\fldinst HYPERLINK "${escapeRtf(target)}"}{\\fldrslt\\ul\\cf1 ${inner}\\cf${ctx.color}${underlineOff} }}`;
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}`;
908
1119
  }
909
1120
  else {
910
- rtf += walkChildren(el, ctx);
1121
+ rtf += `${own.on}${walkChildren(el, own.ctx)}${own.off}`;
911
1122
  }
912
1123
  break;
913
1124
  }
@@ -917,12 +1128,20 @@ function walkNode(node, ctx, restate = true, endLooseText = true) {
917
1128
  // re-attached to the figure on import. Other RTF readers skip the tag and
918
1129
  // simply show an italic line under the image.
919
1130
  case 'figure': {
920
- const img = el.querySelector('img');
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;
921
1140
  // A figure with a picture takes the caption the editor gives it, wherever it sits. One
922
1141
  // with no picture takes only its own (a child): a caption further in belongs to what
923
1142
  // holds it (a figure inside this one), and is written there.
924
- const captionEl = img ? el.querySelector('figcaption') : Array.from(el.children).find((c) => c.tagName === 'FIGCAPTION');
925
- const caption = (captionEl?.textContent || '').trim();
1143
+ const captionEl = img ? anyCaption : Array.from(el.children).find((c) => c.tagName === 'FIGCAPTION' && !isHidden(c));
1144
+ const caption = (captionEl ? shownText(captionEl) : '').trim();
926
1145
  const align = `${ownAlign(el) ?? (cellAlign(ctx) || '\\ql')}${liControl(ctx.indent + leftMarginTwips(el))}`;
927
1146
  if (img) {
928
1147
  rtf += `\\pard${inCell(ctx)}${align} ${imageBody(img)}\\par `;
@@ -941,6 +1160,8 @@ function walkNode(node, ctx, restate = true, endLooseText = true) {
941
1160
  case 'img': {
942
1161
  // A picture directly under the editor root has no paragraph of its
943
1162
  // own; anywhere else it is inline content of the enclosing block.
1163
+ if (isUnseen(el))
1164
+ break;
944
1165
  const standalone = el.parentNode === ctx.root;
945
1166
  rtf += standalone ? `\\pard ${imageBody(el)}\\par ` : imageBody(el);
946
1167
  break;
@@ -951,31 +1172,131 @@ function walkNode(node, ctx, restate = true, endLooseText = true) {
951
1172
  if (ctx.inPre || !isTrailingBreak(el, ctx))
952
1173
  rtf += '\\line ';
953
1174
  break;
954
- case 'span': {
955
- const colorIdx = colorIndexOf(el, ctx);
956
- const size = sizeOf(el);
957
- const colorPfx = colorIdx != null ? `\\cf${colorIdx} ` : '';
958
- const sizePfx = size != null ? `\\fs${size} ` : '';
959
- const sizeSfx = size != null ? `\\fs${ctx.size} ` : '';
960
- const colorSfx = colorIdx != null ? `\\cf${ctx.color} ` : '';
961
- const inner = walkChildren(el, { ...ctx, color: colorIdx ?? ctx.color, size: size ?? ctx.size });
962
- rtf += `${colorPfx}${sizePfx}${inner}${sizeSfx}${colorSfx}`;
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}`;
963
1181
  break;
964
1182
  }
965
- // <font color="..."> is produced by execCommand('foreColor') in contenteditable
966
- case 'font': {
967
- const colorIdx = colorIndexOf(el, ctx);
968
- const colorPfx = colorIdx != null ? `\\cf${colorIdx} ` : '';
969
- const colorSfx = colorIdx != null ? `\\cf${ctx.color} ` : '';
970
- rtf += `${colorPfx}${walkChildren(el, { ...ctx, color: colorIdx ?? ctx.color })}${colorSfx}`;
971
- break;
972
- }
973
- default:
974
- rtf += walkChildren(el, ctx);
975
- break;
976
1183
  }
977
1184
  return rtf;
978
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;
1292
+ }
1293
+ else if (child.nodeType === Node.ELEMENT_NODE && !isHidden(child)) {
1294
+ pending.push(child);
1295
+ }
1296
+ }
1297
+ }
1298
+ return false;
1299
+ }
979
1300
  // ── Lists ──
980
1301
  /** Each level of a list is indented half an inch further (\li720). */
981
1302
  const LIST_STEP = 720;
@@ -987,15 +1308,28 @@ const LIST_HANG = 360;
987
1308
  * indented one level further. Numbers start at the list's `start`.
988
1309
  */
989
1310
  function listRtf(list, ctx) {
990
- const ordered = list.tagName.toLowerCase() === 'ol';
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';
991
1325
  // A list read back from RTF carries the indent beyond its level's own as a margin, which
992
1326
  // is negative for a list nested by less than half an inch.
993
1327
  const margin = lengthTwips(list.style?.marginLeft, true) ?? 0;
994
1328
  const left = Math.max(LIST_HANG, ctx.indent + margin + LIST_STEP);
995
1329
  const start = parseInt(list.getAttribute('start') ?? '', 10);
996
1330
  let counter = ordered && Number.isFinite(start) ? start : 1;
997
- const itemCtx = { ...ctx, indent: left };
998
- const paragraph = `\\pard${inCell(ctx)}${cellAlign(ctx)}${liControl(left)}`;
1331
+ const itemCtx = { ...ctx, indent: left, cellAlign: listAlign(ctx) };
1332
+ const paragraph = `\\pard${inCell(ctx)}${listAlign(ctx)}${liControl(left)}`;
999
1333
  let rtf = '';
1000
1334
  /** Text or inline elements written straight into the list, between its items. */
1001
1335
  let loose = [];
@@ -1005,11 +1339,15 @@ function listRtf(list, ctx) {
1005
1339
  loose = [];
1006
1340
  };
1007
1341
  for (const child of Array.from(list.childNodes)) {
1008
- const tag = child.nodeType === Node.ELEMENT_NODE ? child.tagName.toLowerCase() : '';
1342
+ const tag = child.nodeType === Node.ELEMENT_NODE ? tagOf(child) : '';
1343
+ if (tag && isHidden(child))
1344
+ continue;
1009
1345
  if (tag === 'li') {
1010
1346
  flushLoose();
1011
1347
  const marker = ordered ? ` ${counter}.\\tab ` : '\\bullet\\tab ';
1012
- rtf += flowRtf(Array.from(child.childNodes), itemCtx, `${paragraph}\\fi-${LIST_HANG}${marker}`, `${paragraph} `);
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}`;
1013
1351
  counter++;
1014
1352
  }
1015
1353
  else if (tag === 'ul' || tag === 'ol') {
@@ -1026,6 +1364,15 @@ function listRtf(list, ctx) {
1026
1364
  flushLoose();
1027
1365
  return rtf;
1028
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
+ }
1029
1376
  /**
1030
1377
  * The content of a list item, or of any place where text and blocks mix, as paragraphs. Text
1031
1378
  * and inline elements in a row are one paragraph; the first opens with `first` (the item's
@@ -1060,7 +1407,9 @@ function flowRtf(nodes, ctx, first, plain) {
1060
1407
  if (node.nodeType !== Node.ELEMENT_NODE)
1061
1408
  continue;
1062
1409
  const el = node;
1063
- const tag = el.tagName.toLowerCase();
1410
+ if (isHidden(el))
1411
+ continue;
1412
+ const tag = tagOf(el);
1064
1413
  // A caption outside a figure is text where it stands, as everywhere else.
1065
1414
  if (!endsItsLine(el)) {
1066
1415
  start();
@@ -1073,10 +1422,8 @@ function flowRtf(nodes, ctx, first, plain) {
1073
1422
  end();
1074
1423
  if ((tag === 'p' || tag === 'div') && !Array.from(el.children).some(isBlock)) {
1075
1424
  start();
1076
- const colorIdx = colorIndexOf(el, ctx);
1077
- rtf += colorIdx != null
1078
- ? `\\cf${colorIdx} ${walkChildren(el, { ...ctx, color: colorIdx })}\\cf${ctx.color} `
1079
- : walkChildren(el, ctx);
1425
+ const own = charFormat(el, tag, ctx, true);
1426
+ rtf += `${own.on}${walkChildren(el, own.ctx)}${own.off}`;
1080
1427
  end();
1081
1428
  continue;
1082
1429
  }
@@ -1109,18 +1456,23 @@ const PAGE_WIDTH = 8640;
1109
1456
  *
1110
1457
  * A <th> gets a bottom border, which is how the parser knows a header cell, and a cell's own
1111
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.
1112
1464
  */
1113
1465
  function tableRtf(table, ctx) {
1114
1466
  const model = tableModel(table);
1467
+ let rtf = tableCaptionRtf(table, ctx, `\\pard${inCell(ctx)}`);
1115
1468
  if (model.columns === 0)
1116
- return '';
1469
+ return rtf;
1117
1470
  let cumulative = 0;
1118
- const edges = columnShares(model).map((share) => {
1471
+ const edges = columnShares(model, table).map((share) => {
1119
1472
  cumulative += share;
1120
1473
  return Math.round(cumulative * PAGE_WIDTH);
1121
1474
  });
1122
1475
  edges[edges.length - 1] = PAGE_WIDTH; // snap last edge to avoid rounding drift
1123
- let rtf = '';
1124
1476
  const started = new Set();
1125
1477
  for (let r = 0; r < model.rows.length; r++) {
1126
1478
  const row = model.rows[r];
@@ -1142,17 +1494,56 @@ function tableRtf(table, ctx) {
1142
1494
  if (cell?.el.tagName.toLowerCase() === 'th')
1143
1495
  definition += '\\clbrdrb\\brdrs';
1144
1496
  definition += `\\cellx${edges[last]}`;
1145
- const align = cell && origin ? alignOf(cell.el) : '';
1146
- const content = cell && origin
1147
- ? withoutTrailingPar(walkChildren(cell.el, { ...ctx, inTableCell: true, cellAlign: align }))
1148
- : '';
1149
- bodies += `{\\pard\\intbl${align} \\f0 \\sa0 \\li0 \\fi0 ${content}\\par}\\cell`;
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}`;
1150
1507
  c = last + 1;
1151
1508
  }
1152
- rtf += `{\\trowd\\trgaph120${definition}\\trkeep\\intbl{${bodies}}\\intbl\\row}`;
1509
+ const lastRow = r === model.rows.length - 1 ? '\\lastrow' : '';
1510
+ rtf += `{\\trowd\\trgaph120${definition}\\trkeep\\intbl{${bodies}}\\intbl${lastRow}\\row}`;
1153
1511
  }
1154
1512
  return rtf;
1155
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
+ }
1156
1547
  /**
1157
1548
  * A table inside a table cell. RTF can nest tables (\itap, \nestcell), but many readers show a
1158
1549
  * nested table wrongly or not at all, and opening a row inside a cell, as the writer did, is not
@@ -1161,11 +1552,12 @@ function tableRtf(table, ctx) {
1161
1552
  */
1162
1553
  function nestedTableRtf(table, ctx) {
1163
1554
  let rtf = followsInlineContent(table, ctx.root) ? '\\par ' : '';
1555
+ rtf += tableCaptionRtf(table, ctx, '\\pard\\intbl');
1164
1556
  for (const row of tableRowsInOrder(table)) {
1165
1557
  const cells = rowCells(row);
1166
1558
  if (cells.length === 0)
1167
1559
  continue;
1168
- const line = cells.map((cell) => withoutTrailingPar(walkChildren(cell, ctx))).join('\\tab ');
1560
+ const line = cells.map((cell) => (hiddenWithin(cell, table) ? '' : withoutTrailingPar(walkChildren(cell, ctx)))).join('\\tab ');
1169
1561
  rtf += `\\pard\\intbl${cellAlign(ctx)} ${line}\\par `;
1170
1562
  }
1171
1563
  return rtf;
@@ -1183,8 +1575,9 @@ const BLOCK_TAGS = new Set([
1183
1575
  'p', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li', 'table', 'thead',
1184
1576
  'tbody', 'tfoot', 'tr', 'td', 'th', 'blockquote', 'pre', 'hr', 'figure', 'figcaption'
1185
1577
  ]);
1578
+ /** (An element that is not shown is no block: it ends no line, and the space beside it is still a space.) */
1186
1579
  function isBlock(node) {
1187
- 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);
1188
1581
  }
1189
1582
  /** A text node with a block element on either side, or at the edge of one. */
1190
1583
  function besideBlock(node) {
@@ -1202,6 +1595,7 @@ function isTrailingBreak(br, ctx) {
1202
1595
  let next = node.nextSibling;
1203
1596
  while (next &&
1204
1597
  (next.nodeType === Node.COMMENT_NODE ||
1598
+ (next.nodeType === Node.ELEMENT_NODE && isHidden(next)) ||
1205
1599
  (next.nodeType === Node.TEXT_NODE && COLLAPSIBLE_WHITESPACE.test(next.textContent || '') && !showsTabs(next)))) {
1206
1600
  next = next.nextSibling;
1207
1601
  }
@@ -1219,8 +1613,10 @@ const BREAKS_LOOSE_TEXT = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'table',
1219
1613
  function isBlankLine(el) {
1220
1614
  return el.childNodes.length === 0 || (el.childNodes.length === 1 && el.childNodes[0].nodeName === 'BR');
1221
1615
  }
1222
- /** Collapsible whitespace or a comment: nothing that shows. */
1616
+ /** Collapsible whitespace, a comment, or an element that is not shown: nothing that shows. */
1223
1617
  function showsNothing(node) {
1618
+ if (node.nodeType === Node.ELEMENT_NODE)
1619
+ return isHidden(node);
1224
1620
  return node.nodeType === Node.COMMENT_NODE || (node.nodeType === Node.TEXT_NODE && COLLAPSIBLE_WHITESPACE.test(node.textContent || ''));
1225
1621
  }
1226
1622
  /**
@@ -1232,12 +1628,17 @@ function endsItsLine(node) {
1232
1628
  }
1233
1629
  /** Whether an inline element's content ends with a block, which has ended its own line. */
1234
1630
  function endsWithBlock(el) {
1235
- let last = el.lastChild;
1236
- while (last && showsNothing(last))
1237
- last = last.previousSibling;
1238
- if (!last || last.nodeType !== Node.ELEMENT_NODE)
1239
- return false;
1240
- return endsItsLine(last) || endsWithBlock(last);
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;
1641
+ }
1241
1642
  }
1242
1643
  /**
1243
1644
  * Whether the nearest sibling before this element, skipping collapsible whitespace and comments,
@@ -1247,31 +1648,67 @@ function endsWithBlock(el) {
1247
1648
  * with that block's.
1248
1649
  */
1249
1650
  function followsInlineContent(el, root = null) {
1250
- let prev = el.previousSibling;
1251
- while (prev && showsNothing(prev))
1252
- prev = prev.previousSibling;
1253
- if (!prev)
1254
- return false;
1255
- if (prev.nodeType === Node.TEXT_NODE)
1256
- return true;
1257
- if (prev.nodeType !== Node.ELEMENT_NODE || endsItsLine(prev))
1258
- return false;
1259
- if (prev.nodeName === 'IMG' && root !== null && prev.parentNode === root)
1260
- return false;
1261
- return !endsWithBlock(prev);
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;
1262
1696
  }
1263
1697
  /** Whether the nearest sibling after this element, skipping collapsible whitespace, is text or an inline element. */
1264
1698
  function followedByInline(el) {
1265
1699
  let next = el.nextSibling;
1266
- while (next && next.nodeType === Node.TEXT_NODE && COLLAPSIBLE_WHITESPACE.test(next.textContent || '')) {
1700
+ while (next && showsNothing(next))
1267
1701
  next = next.nextSibling;
1268
- }
1269
1702
  if (!next)
1270
1703
  return false;
1271
1704
  return next.nodeType === Node.TEXT_NODE || (next.nodeType === Node.ELEMENT_NODE && !isBlock(next));
1272
1705
  }
1273
- /** Blocks whose last paragraph always carries an indent or alignment of its own. */
1274
- const FORMATTED_BLOCK_TAGS = new Set(['ul', 'ol', 'li', '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']);
1275
1712
  /**
1276
1713
  * Loose text or an inline element right after a block has no paragraph of its own, and would
1277
1714
  * keep that block's alignment and indent (a centered line's \qc, a list's \li). Start a plain
@@ -1279,16 +1716,14 @@ const FORMATTED_BLOCK_TAGS = new Set(['ul', 'ol', 'li', 'blockquote', 'figure',
1279
1716
  * nothing is written, as before.
1280
1717
  */
1281
1718
  function restateAfterBlock(node, ctx) {
1282
- let prev = node.previousSibling;
1283
- while (prev && prev.nodeType === Node.TEXT_NODE && COLLAPSIBLE_WHITESPACE.test(prev.textContent || '')) {
1284
- prev = prev.previousSibling;
1285
- }
1719
+ const prev = shownBefore(node, ctx);
1286
1720
  if (!isBlock(prev))
1287
1721
  return '';
1288
1722
  const block = prev;
1289
- const tag = block.tagName.toLowerCase();
1723
+ const tag = tagOf(block);
1290
1724
  const formatted = FORMATTED_BLOCK_TAGS.has(tag) ||
1291
- (['p', 'div'].includes(tag) && (ctx.inTableCell ? paragraphLayout(block, ctx) : paragraphFormat(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))) ||
1292
1727
  (HEADING_TAGS.has(tag) && headingLayout(block, ctx) !== '') ||
1293
1728
  (tag === 'pre' && ctx.indent + leftMarginTwips(block) > 0);
1294
1729
  return formatted ? `\\pard${inCell(ctx)}${cellAlign(ctx)}${liControl(ctx.indent)} ` : '';
@@ -1318,7 +1753,7 @@ function lengthTwips(value, allowNegative = false) {
1318
1753
  const twips = Math.round(parseFloat(m[1]) * TWIPS_PER_UNIT[m[2]]);
1319
1754
  if (twips < 0 && !allowNegative)
1320
1755
  return null;
1321
- return twips;
1756
+ return Math.max(-MAX_TWIPS, Math.min(MAX_TWIPS, twips));
1322
1757
  }
1323
1758
  /**
1324
1759
  * An element's own left margin in twips, from its inline style: what the browser's Indent sets
@@ -1337,7 +1772,8 @@ function isIndentBlockquote(el) {
1337
1772
  }
1338
1773
  /** \liN for a left indent in twips, or nothing when there is none. */
1339
1774
  function liControl(twips) {
1340
- 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)}` : '';
1341
1777
  }
1342
1778
  /**
1343
1779
  * \qc, \qr or \qj; left is the default and is not written. Inside a table cell that is aligned
@@ -1377,7 +1813,14 @@ function edgeIndents(el) {
1377
1813
  * indent of the blocks around it plus its own margin.
1378
1814
  */
1379
1815
  function paragraphFormat(el, ctx) {
1380
- 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;
1381
1824
  }
1382
1825
  /**
1383
1826
  * The RTF paragraph controls for a <p> or <div>'s own formatting, or '' when it sets none:
@@ -1424,7 +1867,7 @@ function followsFormattedParagraph(el, ctx) {
1424
1867
  const prev = el.previousElementSibling;
1425
1868
  if (!prev)
1426
1869
  return false;
1427
- const tag = prev.tagName.toLowerCase();
1870
+ const tag = tagOf(prev);
1428
1871
  return (tag === 'p' || tag === 'div') && paragraphFormat(prev, ctx) !== '';
1429
1872
  }
1430
1873
  /** Whether a container's first (or last) content is loose text or an inline element, not a block. */
@@ -1439,7 +1882,7 @@ function edgeIsInline(el, edge) {
1439
1882
  if (edge === 'last')
1440
1883
  nodes.reverse();
1441
1884
  for (const n of nodes) {
1442
- if (n.nodeType === Node.TEXT_NODE && COLLAPSIBLE_WHITESPACE.test(n.textContent || ''))
1885
+ if (showsNothing(n))
1443
1886
  continue;
1444
1887
  return !isBlock(n);
1445
1888
  }
@@ -1449,9 +1892,12 @@ function edgeIsInline(el, edge) {
1449
1892
  function inCell(ctx) {
1450
1893
  return ctx.inTableCell ? '\\intbl' : '';
1451
1894
  }
1452
- /** The alignment of the table cell the walker is in (\qc, \qr or \qj), which its paragraphs share. */
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
+ */
1453
1899
  function cellAlign(ctx) {
1454
- return ctx.inTableCell ? ctx.cellAlign : '';
1900
+ return ctx.cellAlign;
1455
1901
  }
1456
1902
  /** Whether a rule stands for a page break: <hr style="break-after:page">, as the parser writes \page. */
1457
1903
  function isPageBreak(el) {
@@ -1470,16 +1916,25 @@ function colorIndexOf(el, ctx) {
1470
1916
  return null;
1471
1917
  return ctx.colorIndex.get(colorKey(c)) ?? null;
1472
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];
1473
1924
  /** The element's own font size in half-points, or null when it sets none. */
1474
1925
  function sizeOf(el) {
1475
1926
  const fs = el.style?.fontSize;
1476
- if (!fs)
1477
- 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;
1478
1933
  const ptMatch = fs.match(/([\d.]+)\s*pt/);
1479
1934
  if (ptMatch)
1480
- return Math.round(parseFloat(ptMatch[1]) * 2);
1935
+ return halfPoints(parseFloat(ptMatch[1]));
1481
1936
  const pxMatch = fs.match(/([\d.]+)\s*px/);
1482
1937
  if (pxMatch)
1483
- return Math.round(parseFloat(pxMatch[1]) * 0.75 * 2);
1938
+ return halfPoints(parseFloat(pxMatch[1]) * 0.75);
1484
1939
  return null;
1485
1940
  }