svelte-rtf-editor 1.8.3 → 1.9.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.
@@ -4,13 +4,14 @@
4
4
  * Parses RTF control words and groups into an HTML string.
5
5
  * Supports: bold, italic, underline, strikethrough, super/subscript,
6
6
  * font size, foreground color (\cf), highlight background color (\highlight),
7
- * color table, font table, paragraphs, bullet/numbered lists, tables,
8
- * embedded pictures (\pict PNG/JPEG blips, with captions),
9
- * Unicode characters, hex escapes, and nested groups.
7
+ * color table, font table (monospace text reads as code), paragraphs with their
8
+ * alignment and indents, headings, bullet/numbered lists, hyperlinks, tables with
9
+ * merged cells, embedded pictures (\pict PNG/JPEG blips, with captions),
10
+ * Unicode characters, Windows-1252 hex escapes, and nested groups.
10
11
  *
11
12
  * \cb (character background) is silently ignored on import.
12
13
  */
13
- import { HEADING_SCALE, normalizeFontSize } from './rtf-writer.js';
14
+ import { HEADING_SCALE, PRE_SCALE, LINK_COLOR, isMonospaceFontName, linkTarget, normalizeFontSize } from './rtf-writer.js';
14
15
  // ── Highlight palette (RTF \highlight 1-16) ──
15
16
  const HIGHLIGHT_COLORS = {
16
17
  1: '#000000', // Black
@@ -49,8 +50,47 @@ const HEX_NIBBLE = (() => {
49
50
  })();
50
51
  /** A tab as the editor's Tab key inserts it (Chromium's own shape for a typed tab). */
51
52
  const TAB_HTML = '<span style="white-space:pre">\t</span>';
52
- /** A paragraph so far holding only a list marker: a bullet, or a number and a period. */
53
- const LIST_MARKER = /^(?:<[^>]+>)*\s*(?:\u2022|\d+\.)\s*(?:<\/[^>]+>)*$/;
53
+ /** Text so far holding only a list marker: a bullet, or a number and a period. */
54
+ const LIST_MARKER = /^\s*(?:\u2022|(\d+)\.)\s*$/;
55
+ /**
56
+ * The bullet Word writes inside {\listtext …} and {\pntext …}: byte B7 of the Symbol font, which
57
+ * arrives as a middle dot or as the font's private-use character.
58
+ */
59
+ const SYMBOL_BULLET = /^\s*[\u00b7\uf0b7]\s*$/;
60
+ /** Text a browser shows as nothing but space. */
61
+ const ONLY_SPACES = /^[ \t\r\n\f]*$/;
62
+ /** The rule the writer sends for <hr>: a centered line of this many em dashes. */
63
+ const RULE_DASHES = '\u2014'.repeat(20);
64
+ /** A hanging indent of this many twips is the one the writer gives a list item (\fi-360). */
65
+ const LIST_HANG = 360;
66
+ /** The longest number a numbered list item is read with. */
67
+ const MAX_LIST_NUMBER_DIGITS = 9;
68
+ /** Each level of a list is indented this much further (\li720). */
69
+ const LIST_STEP = 720;
70
+ /**
71
+ * The largest RTF string rtfToHtml reads unless told otherwise: 50 MB. A document is parsed in
72
+ * one go on the main thread, and a picture is decoded from two characters per byte, so the size
73
+ * of what is handed in is the only bound on how long the page stops responding.
74
+ */
75
+ export const DEFAULT_MAX_RTF_BYTES = 50 * 1024 * 1024;
76
+ /** A byte count as people read it: "52.4 MB", rounded up when asked. */
77
+ function megabytes(n, roundUp = false) {
78
+ const tenths = (n / (1024 * 1024)) * 10;
79
+ return `${((roundUp ? Math.ceil(tenths) : Math.round(tenths)) / 10).toFixed(1)} MB`;
80
+ }
81
+ /**
82
+ * "52.4 MB, and the limit is 50.0 MB". A size just over the limit is rounded up, so it does not
83
+ * read as "50.0 MB, and the limit is 50.0 MB".
84
+ */
85
+ function overLimit(size, limit) {
86
+ let shown = megabytes(size);
87
+ if (shown === megabytes(limit))
88
+ shown = megabytes(size, true);
89
+ // Still the same at a tenth of a megabyte (a limit of its own, just under the size): bytes.
90
+ if (shown === megabytes(limit))
91
+ return `${size} bytes, and the limit is ${limit} bytes`;
92
+ return `${shown}, and the limit is ${megabytes(limit)}`;
93
+ }
54
94
  /** Hex picture data → base64, without depending on btoa/Buffer. */
55
95
  function hexToBase64(hex) {
56
96
  const byteCount = hex.length >> 1;
@@ -166,6 +206,14 @@ const WINDOWS_1252_C1 = [
166
206
  0x90, 0x2018, 0x2019, 0x201c, 0x201d, 0x2022, 0x2013, 0x2014,
167
207
  0x02dc, 0x2122, 0x0161, 0x203a, 0x0153, 0x9d, 0x017e, 0x0178
168
208
  ];
209
+ /**
210
+ * The character a \'xx byte stands for. A NUL is no character and decodes to nothing: it would
211
+ * end the text where a browser or a receiving system reads it.
212
+ */
213
+ function cp1252Char(byte) {
214
+ const code = WINDOWS_1252_C1[byte - 0x80] ?? byte;
215
+ return code ? String.fromCharCode(code) : '';
216
+ }
169
217
  function tokenize(rtf) {
170
218
  const tokens = [];
171
219
  let i = 0;
@@ -185,15 +233,17 @@ function tokenize(rtf) {
185
233
  if (i >= len)
186
234
  break;
187
235
  const next = rtf[i];
188
- // Hex escape \'xx. One without two hex digits after it is damaged: it is dropped, and
189
- // what follows it is read as usual, rather than turned into a NUL or a control character.
236
+ // Hex escape \'xx: one byte of Windows-1252.
190
237
  if (next === "'") {
191
238
  i++;
192
- const hex = rtf.substring(i, i + 2);
193
- if (/^[0-9a-fA-F]{2}$/.test(hex)) {
239
+ const hi = HEX_NIBBLE[rtf.charCodeAt(i)] ?? -1;
240
+ const lo = HEX_NIBBLE[rtf.charCodeAt(i + 1)] ?? -1;
241
+ // A \' with no two hex digits after it is damage, not a character: it is
242
+ // dropped, and what follows is read as it stands. (parseInt on it gave NaN,
243
+ // which became a NUL in the HTML.)
244
+ if (hi >= 0 && lo >= 0) {
194
245
  i += 2;
195
- const code = parseInt(hex, 16);
196
- tokens.push({ type: 'text', value: String.fromCharCode(WINDOWS_1252_C1[code - 0x80] ?? code) });
246
+ tokens.push({ type: 'text', value: cp1252Char((hi << 4) | lo), hex: true });
197
247
  }
198
248
  }
199
249
  // Special escapes
@@ -241,7 +291,9 @@ function tokenize(rtf) {
241
291
  numStr += rtf[i];
242
292
  i++;
243
293
  }
244
- param = parseInt(numStr, 10);
294
+ // A lone "-" is no number.
295
+ const value = parseInt(numStr, 10);
296
+ param = Number.isFinite(value) ? value : null;
245
297
  }
246
298
  // Consume optional trailing space delimiter
247
299
  if (i < len && rtf[i] === ' ')
@@ -310,12 +362,16 @@ function buildTree(tokens) {
310
362
  current.children.push({ type: 'control', word: tok.word, param: tok.param ?? null });
311
363
  }
312
364
  else if (tok.type === 'text') {
313
- current.children.push({ type: 'text', value: tok.value });
365
+ current.children.push(tok.hex ? { type: 'text', value: tok.value, hex: true } : { type: 'text', value: tok.value });
314
366
  }
315
367
  }
316
368
  return root;
317
369
  }
318
370
  // ── Color table parser ──
371
+ /** A color component as a reader may use it: a damaged table can hold \red999 or \green-5. */
372
+ function colorComponent(value) {
373
+ return Math.min(255, Math.max(0, value ?? 0));
374
+ }
319
375
  function parseColorTable(group) {
320
376
  const colors = ['']; // index 0 = auto/default
321
377
  let r = 0, g = 0, b = 0;
@@ -329,18 +385,16 @@ function parseColorTable(group) {
329
385
  }
330
386
  for (const node of group.children) {
331
387
  if (node.type === 'control') {
332
- // A component outside 0 to 255 is damaged: it is held to the nearest end of the range.
333
- const value = Math.min(255, Math.max(0, node.param ?? 0));
334
388
  if (node.word === 'red') {
335
- r = value;
389
+ r = colorComponent(node.param);
336
390
  hasComponents = true;
337
391
  }
338
392
  else if (node.word === 'green') {
339
- g = value;
393
+ g = colorComponent(node.param);
340
394
  hasComponents = true;
341
395
  }
342
396
  else if (node.word === 'blue') {
343
- b = value;
397
+ b = colorComponent(node.param);
344
398
  hasComponents = true;
345
399
  }
346
400
  }
@@ -359,27 +413,100 @@ function parseColorTable(group) {
359
413
  return colors;
360
414
  }
361
415
  // ── Font table parser ──
362
- function parseFontTable(group) {
363
- const fonts = new Map();
364
- for (const child of group.children) {
365
- if (child.type === 'group') {
366
- let fNum = 0;
367
- let fName = '';
368
- for (const node of child.children) {
369
- if (node.type === 'control' && node.word === 'f' && node.param != null) {
370
- fNum = node.param;
416
+ /**
417
+ * The numbers of the fonts that are monospace: named like one (Courier New, Consolas), or declared
418
+ * \fmodern or fixed-pitch (\fprq1). Reads both shapes a font table comes in: one group per font
419
+ * ({\f1\fmodern Courier New;}), and TextEdit's run of entries with no groups
420
+ * (\f0\fswiss Helvetica;\f1\fmodern Courier;).
421
+ */
422
+ function monospaceFonts(group) {
423
+ const mono = new Set();
424
+ let num = null;
425
+ let name = '';
426
+ let fixed = false;
427
+ const finish = () => {
428
+ if (num != null && (fixed || isMonospaceFontName(name)))
429
+ mono.add(num);
430
+ num = null;
431
+ name = '';
432
+ fixed = false;
433
+ };
434
+ const read = (nodes) => {
435
+ for (const node of nodes) {
436
+ if (node.type === 'control') {
437
+ if (node.word === 'f' && node.param != null) {
438
+ if (num != null)
439
+ finish();
440
+ num = node.param;
371
441
  }
372
- if (node.type === 'text') {
373
- fName += node.value;
442
+ else if (node.word === 'fmodern' || (node.word === 'fprq' && node.param === 1)) {
443
+ fixed = true;
374
444
  }
375
445
  }
376
- // Remove trailing semicolons
377
- fName = fName.replace(/;$/, '').trim();
378
- if (fName)
379
- fonts.set(fNum, fName);
446
+ else if (node.type === 'text') {
447
+ // A name ends at its ';'.
448
+ const parts = node.value.split(';');
449
+ name += parts[0];
450
+ if (parts.length > 1)
451
+ finish();
452
+ }
453
+ // A group inside an entry ({\*\panose …}, {\*\falt …}) is not part of the name.
454
+ }
455
+ };
456
+ for (const child of group.children) {
457
+ if (child.type === 'group') {
458
+ read(child.children);
459
+ finish();
460
+ }
461
+ }
462
+ read(group.children.filter((n) => n.type !== 'group'));
463
+ finish();
464
+ return mono;
465
+ }
466
+ // ── Links ──
467
+ /** The longest field instruction looked at for a link's address. */
468
+ const MAX_FIELD_INSTRUCTION = 8192;
469
+ /**
470
+ * The text of a field's instruction group, {\*\fldinst HYPERLINK "…"}, or null when it holds a
471
+ * \u escape: the address would then be the fallback character's, not the one meant.
472
+ */
473
+ function fieldInstruction(group) {
474
+ let text = '';
475
+ const pending = [...group.children].reverse();
476
+ while (pending.length > 0) {
477
+ const node = pending.pop();
478
+ if (node.type === 'group') {
479
+ for (let i = node.children.length - 1; i >= 0; i--)
480
+ pending.push(node.children[i]);
481
+ }
482
+ else if (node.type === 'control') {
483
+ if (node.word === 'u')
484
+ return null;
485
+ }
486
+ else {
487
+ text += node.value;
488
+ if (text.length > MAX_FIELD_INSTRUCTION)
489
+ return null;
380
490
  }
381
491
  }
382
- return fonts;
492
+ return text;
493
+ }
494
+ /**
495
+ * The address a {\field …} group links to, or '' when it is not a link, or not one that may be
496
+ * followed. Only what the writer itself would write is accepted (linkTarget): an absolute web,
497
+ * mail or phone address. A javascript: or file: address, or a link to a bookmark, stays text.
498
+ */
499
+ function fieldLink(field) {
500
+ const instruction = field.children.find((n) => n.type === 'group' && n.children.some((c) => c.type === 'control' && c.word === 'fldinst'));
501
+ if (!instruction)
502
+ return '';
503
+ const text = fieldInstruction(instruction);
504
+ if (text == null)
505
+ return '';
506
+ const m = text.match(/^\s*HYPERLINK\s+(?:"([^"]*)"|([^\s"\\]\S*))/i);
507
+ if (!m)
508
+ return '';
509
+ return linkTarget(m[1] ?? m[2] ?? '') ?? '';
383
510
  }
384
511
  // ── Body size ──
385
512
  /** Groups whose content is not document text. */
@@ -388,6 +515,8 @@ const destinationWords = new Set([
388
515
  'headerl', 'headerr', 'headerf', 'footerl', 'footerr', 'footerf',
389
516
  // \nonshppict duplicates the picture already carried by \*\shppict
390
517
  'nonshppict',
518
+ // {\nonesttables \par} is for readers that do not know nested tables; \nestrow is read here
519
+ 'nonesttables',
391
520
  'object', 'fldinst', 'xmlnstbl', 'listtable', 'listoverridetable',
392
521
  'rsidtbl', 'generator', 'datafield', 'themedata', 'colorschememapping',
393
522
  'latentstyles', 'datastore', 'mmathPr', 'author', 'operator',
@@ -402,67 +531,106 @@ function resetIndents(state) {
402
531
  state.rightIndent = 0;
403
532
  state.firstLineIndent = 0;
404
533
  }
534
+ /**
535
+ * A paragraph's indents as CSS, in points (20 twips), which the writer reads back as the same
536
+ * \li, \ri and \fi: "margin-left:36pt;text-indent:-36pt". A first line may not start left of
537
+ * the page margin, where a browser would clip it.
538
+ */
539
+ function indentStyle(block) {
540
+ const left = Math.max(0, block.left);
541
+ const first = Math.max(-left, block.first);
542
+ const parts = [];
543
+ if (left > 0)
544
+ parts.push(`margin-left:${twipsToPt(left)}`);
545
+ if (block.right > 0)
546
+ parts.push(`margin-right:${twipsToPt(block.right)}`);
547
+ if (first !== 0)
548
+ parts.push(`text-indent:${twipsToPt(first)}`);
549
+ return parts.join(';');
550
+ }
551
+ /**
552
+ * The indent of a picture's paragraph: where its one line starts, as a left margin. A figure
553
+ * is written back with a left indent only, and a first-line indent on it would be passed on to
554
+ * its caption.
555
+ */
556
+ function figureIndentStyle(block) {
557
+ const left = Math.max(0, block.left);
558
+ const start = left + Math.max(-left, block.first);
559
+ return start > 0 ? `margin-left:${twipsToPt(start)}` : '';
560
+ }
561
+ /**
562
+ * A paragraph's HTML without the spaces at its ends, which a browser does not show. Only those:
563
+ * a non-breaking space or an em space there is text someone put there, and is kept.
564
+ */
565
+ function trimSpaces(html) {
566
+ return html.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, '');
567
+ }
568
+ function escapeText(text) {
569
+ return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
570
+ }
571
+ /** Text as an attribute value in double quotes. */
572
+ function escapeAttribute(text) {
573
+ return escapeText(text).replace(/"/g, '&quot;');
574
+ }
575
+ function sameFormat(a, b) {
576
+ return (a.bold === b.bold &&
577
+ a.italic === b.italic &&
578
+ a.underline === b.underline &&
579
+ a.strike === b.strike &&
580
+ a.super_ === b.super_ &&
581
+ a.sub === b.sub &&
582
+ a.fontSize === b.fontSize &&
583
+ sameFormatButSize(a, b));
584
+ }
585
+ function sameFormatButSize(a, b) {
586
+ return (a.bold === b.bold &&
587
+ a.italic === b.italic &&
588
+ a.underline === b.underline &&
589
+ a.strike === b.strike &&
590
+ a.super_ === b.super_ &&
591
+ a.sub === b.sub &&
592
+ a.color === b.color &&
593
+ a.background === b.background &&
594
+ a.mono === b.mono &&
595
+ a.link === b.link);
596
+ }
405
597
  export function rtfToHtml(rtfString, options = {}) {
598
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_RTF_BYTES;
599
+ if (maxBytes > 0 && rtfString.length > maxBytes) {
600
+ throw new RangeError(`This document is too large to show: ${overLimit(rtfString.length, maxBytes)}`);
601
+ }
406
602
  const tokens = tokenize(rtfString);
407
603
  const tree = buildTree(tokens);
408
604
  let colorTable = [''];
409
- let fontTable = new Map();
410
- let currentParagraph = '';
411
- const paragraphs = [];
412
- const paragraphAligns = [];
413
- const paragraphIndents = [];
414
- const paragraphFigureIndents = [];
415
- const paragraphCaptions = [];
416
- let paragraphHasText = false;
605
+ let monoFonts = new Set();
606
+ let defaultFont = 0;
607
+ const blocks = [];
608
+ // The paragraph being read
609
+ let runs = [];
610
+ let marker = null;
417
611
  let paragraphHasListMarker = false;
418
612
  let paragraphIsCaption = false;
419
- /** Append a finished paragraph, keeping the parallel metadata arrays in sync. */
420
- function pushParagraph(html, align, isCaption = false) {
421
- paragraphs.push(html);
422
- paragraphAligns.push(align);
423
- const inTable = inTableCell || html.startsWith('<table');
424
- paragraphIndents.push(inTable ? '' : indentStyle());
425
- paragraphFigureIndents.push(inTable ? '' : figureIndentStyle());
426
- paragraphCaptions.push(isCaption);
427
- }
428
613
  // Paragraph alignment (reset by \pard, affects cells and paragraphs)
429
614
  let currentAlign = 'left';
430
- /**
431
- * The current indents as CSS, in points (20 twips), which the writer reads back as the same
432
- * \li, \ri and \fi: "margin-left:36pt;text-indent:-36pt". A first line may not start left of
433
- * the page margin, where a browser would clip it.
434
- */
435
- function indentStyle() {
436
- const { leftIndent, rightIndent, firstLineIndent } = currentState();
437
- const left = Math.max(0, leftIndent);
438
- const first = Math.max(-left, firstLineIndent);
439
- const parts = [];
440
- if (left > 0)
441
- parts.push(`margin-left:${twipsToPt(left)}`);
442
- if (rightIndent > 0)
443
- parts.push(`margin-right:${twipsToPt(rightIndent)}`);
444
- if (first !== 0)
445
- parts.push(`text-indent:${twipsToPt(first)}`);
446
- return parts.join(';');
447
- }
448
- /**
449
- * The indent of a picture's paragraph: where its one line starts, as a left margin. A figure
450
- * is written back with a left indent only, and a first-line indent on it would be passed on to
451
- * its caption.
452
- */
453
- function figureIndentStyle() {
454
- const { leftIndent, firstLineIndent } = currentState();
455
- const start = Math.max(0, leftIndent) + Math.max(-Math.max(0, leftIndent), firstLineIndent);
456
- return start > 0 ? `margin-left:${twipsToPt(start)}` : '';
457
- }
458
615
  // Table state
459
616
  let tableRows = [];
460
617
  let currentRowCells = [];
461
- let currentRowIsHeader = false;
462
- let currentRowCellRights = [];
463
- let currentRowCellAligns = [];
618
+ let currentRowDefs = [];
619
+ /** The definition of the row before, which a row with no \trowd of its own repeats. */
620
+ let lastRowDefs = [];
621
+ let pendingDef = newCellDef();
622
+ /** The side a \clbrdrX just named, until a border type (\brdrs...) confirms or \brdrnone clears it. */
623
+ let pendingSide = null;
624
+ /** The sides of the cell being defined that have a real border. */
625
+ let cellBorders = { b: false, other: false };
464
626
  let inTableCell = false;
465
- let pendingBottomBorder = false; // set by \clbrdrb, confirmed by a real border type
627
+ /** \par seen in a table cell since its last text: line breaks owed if more text follows. */
628
+ let cellBreaks = 0;
629
+ /** \nestcell seen: a tab is owed if more text follows on the line. */
630
+ let nestTabPending = false;
631
+ function newCellDef() {
632
+ return { right: 0, header: false, vmgf: false, vmrg: false, hmgf: false, hmrg: false };
633
+ }
466
634
  // First pass: extract color table and font table from the root group
467
635
  const rootGroup = tree.children[0]?.type === 'group' ? tree.children[0] : tree;
468
636
  for (let i = 0; i < rootGroup.children.length; i++) {
@@ -473,13 +641,21 @@ export function rtfToHtml(rtfString, options = {}) {
473
641
  colorTable = parseColorTable(child);
474
642
  }
475
643
  else if (firstControl?.word === 'fonttbl') {
476
- fontTable = parseFontTable(child);
644
+ monoFonts = monospaceFonts(child);
477
645
  }
478
646
  }
647
+ else if (child.type === 'control' && child.word === 'deff' && child.param != null) {
648
+ defaultFont = child.param;
649
+ }
479
650
  }
651
+ // In a document whose own font is monospace, code cannot be told from text by its font.
652
+ const documentIsMono = monoFonts.has(defaultFont);
653
+ const linkColor = `rgb(${LINK_COLOR.r},${LINK_COLOR.g},${LINK_COLOR.b})`;
480
654
  // The screen's body size, in half-points. It is given, not guessed from the
481
655
  // document: guessing misread short documents and ones set below 12 pt.
482
656
  const bodySize = normalizeFontSize(options.fontSize) * 2;
657
+ /** The size the writer sets a code block in, in half-points. */
658
+ const preSize = Math.round(bodySize * PRE_SCALE);
483
659
  // State stack for nested groups
484
660
  function defaultState() {
485
661
  return {
@@ -492,9 +668,10 @@ export function rtfToHtml(rtfString, options = {}) {
492
668
  fontSize: 24, // 12pt default
493
669
  colorIndex: 0,
494
670
  highlightIndex: 0,
495
- fontIndex: 0,
671
+ fontIndex: defaultFont,
496
672
  ucSkip: 1,
497
673
  inList: false,
674
+ link: '',
498
675
  leftIndent: 0,
499
676
  rightIndent: 0,
500
677
  firstLineIndent: 0,
@@ -507,410 +684,874 @@ export function rtfToHtml(rtfString, options = {}) {
507
684
  function cloneState() {
508
685
  return { ...currentState() };
509
686
  }
510
- function buildSpanOpen(state, withSize = true) {
511
- const styles = [];
512
- if (state.colorIndex > 0 && state.colorIndex < colorTable.length) {
513
- const color = colorTable[state.colorIndex];
514
- if (color && color !== 'rgb(0,0,0)') {
515
- styles.push(`color:${color}`);
516
- }
517
- }
518
- if (state.highlightIndex > 0) {
519
- const bg = HIGHLIGHT_COLORS[state.highlightIndex];
520
- if (bg)
521
- styles.push(`background-color:${bg}`);
522
- }
523
- if (withSize && state.fontSize && state.fontSize !== bodySize) {
524
- styles.push(`font-size:${state.fontSize / 2}pt`);
525
- }
526
- if (styles.length === 0)
527
- return '';
528
- return `<span style="${styles.join(';')}">`;
687
+ function formatOf(state) {
688
+ let color = state.colorIndex > 0 && state.colorIndex < colorTable.length ? colorTable[state.colorIndex] : '';
689
+ // Black is the color text has anyway, and a link's own color is the <a>'s to give.
690
+ if (color === 'rgb(0,0,0)' || (state.link && color === linkColor))
691
+ color = '';
692
+ return {
693
+ bold: state.bold,
694
+ italic: state.italic,
695
+ // A link is underlined as a link; the writer adds that underline itself.
696
+ underline: state.underline && !state.link,
697
+ strike: state.strike,
698
+ super_: state.super_,
699
+ sub: state.sub,
700
+ fontSize: state.fontSize || bodySize,
701
+ color,
702
+ background: (state.highlightIndex > 0 && HIGHLIGHT_COLORS[state.highlightIndex]) || '',
703
+ // A list marker is set in whatever font the list uses (Word's second-level "o" is in
704
+ // Courier New): it is not code.
705
+ mono: !documentIsMono && !state.inList && monoFonts.has(state.fontIndex),
706
+ link: state.link
707
+ };
529
708
  }
530
- function wrapText(text, state) {
709
+ // ── Writing a paragraph's pieces as HTML ──
710
+ function renderText(text, fmt, opts) {
531
711
  if (!text)
532
712
  return '';
533
713
  // A size on spaces alone is not shown and would be read as the
534
714
  // paragraph's size, so it is dropped. Underline, strikethrough and
535
715
  // highlight are kept: an underlined blank is a signature line.
536
- const onlySpaces = /^[ \t\r\n\f]*$/.test(text);
537
- let result = text
538
- .replace(/&/g, '&amp;')
539
- .replace(/</g, '&lt;')
540
- .replace(/>/g, '&gt;');
541
- // Apply span styles
542
- const spanOpen = buildSpanOpen(state, !onlySpaces);
543
- if (spanOpen) {
544
- result = `${spanOpen}${result}</span>`;
545
- }
546
- if (state.bold)
716
+ const onlySpaces = ONLY_SPACES.test(text);
717
+ let result = escapeText(text);
718
+ const styles = [];
719
+ if (fmt.color)
720
+ styles.push(`color:${fmt.color}`);
721
+ if (fmt.background)
722
+ styles.push(`background-color:${fmt.background}`);
723
+ if (!onlySpaces && fmt.fontSize !== bodySize && fmt.fontSize !== opts.dropSize) {
724
+ styles.push(`font-size:${fmt.fontSize / 2}pt`);
725
+ }
726
+ if (styles.length > 0)
727
+ result = `<span style="${styles.join(';')}">${result}</span>`;
728
+ if (fmt.mono && !opts.pre)
729
+ result = `<code>${result}</code>`;
730
+ if (fmt.bold && !opts.dropBold)
547
731
  result = `<strong>${result}</strong>`;
548
- if (state.italic)
732
+ if (fmt.italic)
549
733
  result = `<em>${result}</em>`;
550
- if (state.underline)
734
+ if (fmt.underline)
551
735
  result = `<u>${result}</u>`;
552
- if (state.strike)
736
+ if (fmt.strike)
553
737
  result = `<s>${result}</s>`;
554
- if (state.super_)
738
+ if (fmt.super_)
555
739
  result = `<sup>${result}</sup>`;
556
- if (state.sub)
740
+ if (fmt.sub)
557
741
  result = `<sub>${result}</sub>`;
558
742
  return result;
559
743
  }
560
- let skipDepth = 0;
744
+ function renderRun(run, opts) {
745
+ if (run.type === 'text')
746
+ return renderText(run.text, run.fmt, opts);
747
+ if (opts.pre && run.kind === 'br')
748
+ return '\n';
749
+ if (opts.pre && run.kind === 'tab')
750
+ return '\t';
751
+ return run.html;
752
+ }
753
+ /** The opening tag of a link. The address has been through linkTarget; a web page opens in a tab of its own. */
754
+ function linkOpen(href) {
755
+ const newTab = /^https?:/i.test(href) ? ' target="_blank" rel="noopener noreferrer"' : '';
756
+ return `<a href="${escapeAttribute(href)}"${newTab}>`;
757
+ }
758
+ function renderRuns(list, opts = {}) {
759
+ // A line break that ends the paragraph (\line\par) leaves an empty last line. A browser
760
+ // shows nothing for a <br> at the end of a block, so that one is written twice; the
761
+ // writer, which drops a closing <br>, then sends the one \line back.
762
+ let closing = -1;
763
+ if (!opts.pre) {
764
+ let k = list.length - 1;
765
+ while (k >= 0 && list[k].type === 'text' && ONLY_SPACES.test(list[k].text))
766
+ k--;
767
+ if (k >= 0 && list[k].type === 'html' && list[k].kind === 'br')
768
+ closing = k;
769
+ }
770
+ const render = (i) => renderRun(list[i], opts) + (i === closing ? '<br>' : '');
771
+ let out = '';
772
+ for (let i = 0; i < list.length;) {
773
+ const link = list[i].fmt.link;
774
+ if (!link) {
775
+ out += render(i++);
776
+ continue;
777
+ }
778
+ // Every piece in a row that carries the same address is one link.
779
+ let inner = '';
780
+ while (i < list.length && list[i].fmt.link === link)
781
+ inner += render(i++);
782
+ out += `${linkOpen(link)}${inner}</a>`;
783
+ }
784
+ return out;
785
+ }
786
+ // ── Collecting a paragraph ──
787
+ /** Half of a surrogate pair read from \uN, waiting for the \uN that completes the character. */
788
+ let pendingHighSurrogate = 0;
789
+ function pushText(text, state) {
790
+ if (!text)
791
+ return;
792
+ const fmt = formatOf(state);
793
+ const last = runs[runs.length - 1];
794
+ if (last && last.type === 'text') {
795
+ // Text in the same formatting as the text before it is one piece: "caf" and the
796
+ // \'e9 after it, or the two \u halves of an emoji, are not two elements.
797
+ if (sameFormat(last.fmt, fmt)) {
798
+ last.text += text;
799
+ return;
800
+ }
801
+ // A size does not show on spaces, so spaces go with the text beside them
802
+ // whatever size they were set in.
803
+ if (sameFormatButSize(last.fmt, fmt)) {
804
+ if (ONLY_SPACES.test(text)) {
805
+ last.text += text;
806
+ return;
807
+ }
808
+ if (ONLY_SPACES.test(last.text)) {
809
+ last.text += text;
810
+ last.fmt = fmt;
811
+ return;
812
+ }
813
+ }
814
+ }
815
+ runs.push({ type: 'text', text, fmt });
816
+ }
817
+ /** What is owed before the next piece of a paragraph: see cellBreaks and nestTabPending. */
818
+ function beforeContent(state) {
819
+ if (pendingHighSurrogate) {
820
+ // A lone half of a pair is no character.
821
+ pendingHighSurrogate = 0;
822
+ pushText('\ufffd', state);
823
+ }
824
+ if (cellBreaks > 0) {
825
+ const count = cellBreaks;
826
+ cellBreaks = 0;
827
+ if (inTableCell) {
828
+ // A paragraph mark inside a cell: the cell's text goes on, on a new line.
829
+ for (let k = 0; k < count; k++)
830
+ runs.push({ type: 'html', kind: 'br', html: '<br>', fmt: formatOf(state) });
831
+ }
832
+ else {
833
+ // \pard has left the table without a \cell: what was read is a paragraph.
834
+ for (let k = 0; k < count; k++)
835
+ flushParagraph();
836
+ }
837
+ }
838
+ if (nestTabPending) {
839
+ nestTabPending = false;
840
+ runs.push({ type: 'html', kind: 'tab', html: TAB_HTML, fmt: formatOf(state) });
841
+ }
842
+ }
843
+ function appendText(text, state) {
844
+ if (!text)
845
+ return;
846
+ beforeContent(state);
847
+ pushText(text, state);
848
+ }
849
+ function appendHtml(kind, html, state) {
850
+ beforeContent(state);
851
+ runs.push({ type: 'html', kind, html, fmt: formatOf(state) });
852
+ }
853
+ /** The text of the line being read, back to the last line break, if text is all it holds. */
854
+ function lineText() {
855
+ let text = '';
856
+ for (let i = runs.length - 1; i >= 0; i--) {
857
+ const run = runs[i];
858
+ if (run.type === 'html' && run.kind === 'br')
859
+ break;
860
+ if (run.type !== 'text')
861
+ return null;
862
+ text = run.text + text;
863
+ }
864
+ return text;
865
+ }
866
+ function appendTab(state) {
867
+ beforeContent(state);
868
+ // A real tab, in the shape the editor's Tab key inserts, so it shows as
869
+ // one and is written back as \tab (an em space came back as 膕).
870
+ // After a list marker ("\bullet\tab", "1.\tab") the gap stays an em
871
+ // space where the line is read as a plain one: a full tab there is too wide.
872
+ const lead = lineText();
873
+ // Only a marker that opens the paragraph can make it a list item.
874
+ const opensParagraph = marker === null && runs.every((r) => r.type === 'text');
875
+ const listed = lead != null ? lead.match(LIST_MARKER) : null;
876
+ if (listed) {
877
+ runs.push({ type: 'html', kind: 'gap', html: '&emsp;', fmt: formatOf(state) });
878
+ // (A number too long to be an item's number is text, and so is one written with a
879
+ // leading zero, "01.": a list would show it as "1.".)
880
+ if (opensParagraph && (!listed[1] || (listed[1].length <= MAX_LIST_NUMBER_DIGITS && !/^0\d/.test(listed[1])))) {
881
+ marker = listed[1]
882
+ ? { kind: 'ol', number: Number(listed[1]), end: runs.length }
883
+ : { kind: 'ul', number: 0, end: runs.length };
884
+ }
885
+ return;
886
+ }
887
+ runs.push({ type: 'html', kind: 'tab', html: TAB_HTML, fmt: formatOf(state) });
888
+ // Word's bullet, inside {\listtext …} or {\pntext …}.
889
+ if (opensParagraph && lead != null && state.inList && SYMBOL_BULLET.test(lead)) {
890
+ marker = { kind: 'ul', number: 0, end: runs.length };
891
+ }
892
+ }
893
+ // ── Tables ──
894
+ /** Column edges closer than this, in twips (2 px), are the same edge. */
895
+ const EDGE_TOLERANCE = 30;
561
896
  function flushTable() {
562
897
  if (tableRows.length === 0)
563
898
  return;
564
- let html = '<table style="border-collapse:collapse;width:100%;margin:4px 0">';
565
- for (const row of tableRows) {
566
- html += '<tr>';
567
- const tag = row.isHeader ? 'th' : 'td';
568
- const total = row.cellRights[row.cellRights.length - 1] || 1;
899
+ const rows = tableRows;
900
+ tableRows = [];
901
+ const placedRows = rows.map((row) => {
902
+ const placed = [];
569
903
  let prevRight = 0;
904
+ let step = 0;
570
905
  for (let ci = 0; ci < row.cells.length; ci++) {
571
- const right = row.cellRights[ci] ?? total;
572
- const pct = ((right - prevRight) / total * 100).toFixed(1);
573
- prevRight = right;
574
- const align = row.cellAligns[ci] ?? 'left';
575
- const alignStyle = align !== 'left' ? `;text-align:${align}` : '';
576
- const style = row.isHeader
577
- ? `border-bottom:1px solid;padding:2px 6px;text-align:${align};width:${pct}%`
906
+ const def = row.defs[ci] ?? { ...newCellDef(), right: prevRight + (step || 1440) };
907
+ const cell = row.cells[ci];
908
+ const last = placed[placed.length - 1];
909
+ if (def.hmrg && last) {
910
+ last.right = Math.max(last.right, def.right);
911
+ if (cell.html)
912
+ last.html += (last.html ? ' ' : '') + cell.html;
913
+ }
914
+ else {
915
+ placed.push({
916
+ html: cell.html, align: cell.align, def,
917
+ left: prevRight, right: Math.max(def.right, prevRight),
918
+ start: 0, end: 0, rowspan: 1, merged: false
919
+ });
920
+ }
921
+ step = Math.max(1, def.right - prevRight);
922
+ prevRight = Math.max(def.right, prevRight);
923
+ }
924
+ return placed;
925
+ });
926
+ // One set of columns for the table: every edge any row has. A cell that crosses edges
927
+ // of other rows spans those columns.
928
+ const allEdges = placedRows.flatMap((row) => row.map((c) => c.right)).sort((a, b) => a - b);
929
+ const edges = [];
930
+ for (const e of allEdges) {
931
+ if (edges.length === 0 || e - edges[edges.length - 1] > EDGE_TOLERANCE)
932
+ edges.push(e);
933
+ }
934
+ // The column whose edge is nearest, the earlier one on a tie. A binary search over the
935
+ // sorted edges: a scan of every edge for every cell froze the page on a row of 100,000
936
+ // cells (14 s for 2 MB).
937
+ const columnOf = (right) => {
938
+ let lo = 0;
939
+ let hi = edges.length - 1;
940
+ while (lo < hi) {
941
+ const mid = (lo + hi) >> 1;
942
+ if (edges[mid] < right)
943
+ lo = mid + 1;
944
+ else
945
+ hi = mid;
946
+ }
947
+ if (lo > 0 && Math.abs(edges[lo - 1] - right) <= Math.abs(edges[lo] - right))
948
+ return lo - 1;
949
+ return lo;
950
+ };
951
+ for (const row of placedRows) {
952
+ let start = 0;
953
+ for (const cell of row) {
954
+ cell.start = start;
955
+ cell.end = Math.max(start, columnOf(cell.right));
956
+ start = cell.end + 1;
957
+ }
958
+ }
959
+ // A vertical merge: the cell marked \clvmgf takes in each \clvmrg cell under it, row
960
+ // after row. A \clvmrg cell with nothing above it to join stays an ordinary cell.
961
+ for (let r = 0; r < placedRows.length; r++) {
962
+ for (const cell of placedRows[r]) {
963
+ if (!cell.def.vmgf || cell.merged)
964
+ continue;
965
+ for (let below = r + 1; below < placedRows.length; below++) {
966
+ const under = placedRows[below].find((c) => c.start === cell.start && c.def.vmrg && !c.merged);
967
+ if (!under)
968
+ break;
969
+ under.merged = true;
970
+ cell.rowspan++;
971
+ // A merged cell is empty; if a damaged file has text there, it is kept.
972
+ if (under.html)
973
+ cell.html += (cell.html ? '<br>' : '') + under.html;
974
+ }
975
+ }
976
+ }
977
+ const total = edges[edges.length - 1] || 1;
978
+ // A cell's width is the difference of where it ends and where it starts, each as a
979
+ // share of the table rounded to a hundredth of a percent. Written that way the widths
980
+ // of a row add up exactly, and the writer puts every column edge back where it was;
981
+ // each width rounded by itself moved an edge a few twips on every save.
982
+ const shareAt = (edge) => Math.round((edge / total) * 10000) / 100;
983
+ let html = '<table style="border-collapse:collapse;width:100%;margin:4px 0">';
984
+ for (const row of placedRows) {
985
+ html += '<tr>';
986
+ for (const cell of row) {
987
+ if (cell.merged)
988
+ continue;
989
+ const tag = cell.def.header ? 'th' : 'td';
990
+ const pct = (shareAt(cell.right) - shareAt(cell.left)).toFixed(2).replace(/0$/, '');
991
+ const alignStyle = cell.align !== 'left' ? `;text-align:${cell.align}` : '';
992
+ const style = cell.def.header
993
+ ? `border-bottom:1px solid;padding:2px 6px;text-align:${cell.align};width:${pct}%`
578
994
  : `padding:2px 6px;width:${pct}%${alignStyle}`;
579
- html += `<${tag} style="${style}">${row.cells[ci] || ''}</${tag}>`;
995
+ const colspan = cell.end > cell.start ? ` colspan="${cell.end - cell.start + 1}"` : '';
996
+ const rowspan = cell.rowspan > 1 ? ` rowspan="${cell.rowspan}"` : '';
997
+ html += `<${tag}${colspan}${rowspan} style="${style}">${cell.html}</${tag}>`;
580
998
  }
581
999
  html += '</tr>';
582
1000
  }
583
1001
  html += '</table>';
584
- pushParagraph(html, 'left');
585
- tableRows = [];
1002
+ blocks.push({ kind: 'table', html });
586
1003
  }
587
1004
  function flushParagraph() {
1005
+ const state = currentState();
1006
+ if (pendingHighSurrogate) {
1007
+ pendingHighSurrogate = 0;
1008
+ pushText('\ufffd', state);
1009
+ }
588
1010
  flushTable();
589
- const trimmed = currentParagraph.trim();
590
- if (trimmed || !paragraphHasListMarker) {
591
- pushParagraph(currentParagraph, currentAlign, paragraphIsCaption);
1011
+ // A paragraph that held a list marker and nothing else is no line of its own.
1012
+ if (!paragraphHasListMarker || trimSpaces(renderRuns(runs))) {
1013
+ blocks.push({
1014
+ kind: 'paragraph',
1015
+ runs,
1016
+ align: currentAlign,
1017
+ left: state.leftIndent,
1018
+ right: state.rightIndent,
1019
+ first: state.firstLineIndent,
1020
+ caption: paragraphIsCaption,
1021
+ marker,
1022
+ inTable: inTableCell
1023
+ });
592
1024
  }
593
- currentParagraph = '';
594
- paragraphHasText = false;
1025
+ runs = [];
1026
+ marker = null;
595
1027
  paragraphHasListMarker = false;
596
1028
  paragraphIsCaption = false;
597
1029
  currentAlign = 'left';
1030
+ nestTabPending = false;
598
1031
  }
599
1032
  let pendingUnicodeSkip = 0;
600
- function walk(nodes) {
601
- for (let i = 0; i < nodes.length; i++) {
602
- const node = nodes[i];
603
- if (skipDepth > 0 && node.type !== 'group') {
1033
+ const frames = [{ nodes: rootGroup.children, index: 0, scoped: false }];
1034
+ const enterGroup = (group, state) => {
1035
+ stateStack.push(state);
1036
+ frames.push({ nodes: group.children, index: 0, scoped: true });
1037
+ };
1038
+ while (frames.length > 0) {
1039
+ const frame = frames[frames.length - 1];
1040
+ if (frame.index >= frame.nodes.length) {
1041
+ frames.pop();
1042
+ if (frame.scoped)
1043
+ stateStack.pop();
1044
+ continue;
1045
+ }
1046
+ const node = frame.nodes[frame.index++];
1047
+ if (node.type === 'group') {
1048
+ const firstCtrl = node.children.find((n) => n.type === 'control');
1049
+ if (firstCtrl?.word === 'pict') {
1050
+ const img = renderPicture(node);
1051
+ if (img)
1052
+ appendHtml('img', img, currentState());
604
1053
  continue;
605
1054
  }
606
- if (node.type === 'group') {
607
- if (skipDepth > 0) {
608
- skipDepth++;
609
- walk(node.children);
610
- skipDepth--;
611
- continue;
1055
+ if (firstCtrl && destinationWords.has(firstCtrl.word)) {
1056
+ continue;
1057
+ }
1058
+ const hasStarDest = node.children.length >= 2 &&
1059
+ node.children[0].type === 'control' && node.children[0].word === '*';
1060
+ if (hasStarDest) {
1061
+ const dest = node.children.find((n) => n.type === 'control' && n.word !== '*');
1062
+ // Word wraps pictures in {\*\shppict{\pict …}} — descend into it
1063
+ // rather than dropping the picture with the rest of the ignorables.
1064
+ if (dest?.word === 'shppict') {
1065
+ enterGroup(node, cloneState());
612
1066
  }
613
- const firstCtrl = node.children.find((n) => n.type === 'control');
614
- if (firstCtrl?.word === 'pict') {
615
- const img = renderPicture(node);
616
- if (img) {
617
- currentParagraph += img;
618
- paragraphHasText = true;
619
- }
620
- continue;
1067
+ else if (dest?.word === 'inkcap') {
1068
+ // Marks the paragraph that follows as a picture caption.
1069
+ paragraphIsCaption = true;
621
1070
  }
622
- if (firstCtrl && destinationWords.has(firstCtrl.word)) {
623
- continue;
1071
+ else if (dest?.word === 'nesttableprops') {
1072
+ // Word ends each row of a table inside a cell with this group, which holds
1073
+ // the row's definition and its \nestrow.
1074
+ nestTabPending = false;
1075
+ cellBreaks++;
624
1076
  }
625
- const hasStarDest = node.children.length >= 2 &&
626
- node.children[0].type === 'control' && node.children[0].word === '*';
627
- if (hasStarDest) {
628
- const dest = node.children.find((n) => n.type === 'control' && n.word !== '*');
629
- // Word wraps pictures in {\*\shppict{\pict …}} — descend into it
630
- // rather than dropping the picture with the rest of the ignorables.
631
- if (dest?.word === 'shppict') {
632
- stateStack.push(cloneState());
633
- walk(node.children);
634
- stateStack.pop();
1077
+ continue;
1078
+ }
1079
+ const state = cloneState();
1080
+ // {\field{\*\fldinst HYPERLINK "…"}{\fldrslt text}}: the text is a link, if the
1081
+ // address is one the writer would write.
1082
+ if (firstCtrl?.word === 'field') {
1083
+ const href = fieldLink(node);
1084
+ if (href)
1085
+ state.link = href;
1086
+ }
1087
+ enterGroup(node, state);
1088
+ }
1089
+ else if (node.type === 'control') {
1090
+ const state = currentState();
1091
+ const w = node.word;
1092
+ const p = node.param;
1093
+ switch (w) {
1094
+ case 'b':
1095
+ state.bold = p !== 0;
1096
+ break;
1097
+ case 'i':
1098
+ state.italic = p !== 0;
1099
+ break;
1100
+ case 'ul':
1101
+ case 'ulnone':
1102
+ state.underline = w === 'ul' && p !== 0;
1103
+ break;
1104
+ case 'strike':
1105
+ state.strike = p !== 0;
1106
+ break;
1107
+ case 'super':
1108
+ state.super_ = true;
1109
+ state.sub = false;
1110
+ break;
1111
+ case 'sub':
1112
+ state.sub = true;
1113
+ state.super_ = false;
1114
+ break;
1115
+ case 'nosupersub':
1116
+ state.super_ = false;
1117
+ state.sub = false;
1118
+ break;
1119
+ case 'fs':
1120
+ if (p != null)
1121
+ state.fontSize = p;
1122
+ break;
1123
+ case 'cf':
1124
+ if (p != null)
1125
+ state.colorIndex = p;
1126
+ break;
1127
+ case 'cb':
1128
+ break; // \cb not rendered on import
1129
+ case 'highlight':
1130
+ if (p != null)
1131
+ state.highlightIndex = p;
1132
+ break;
1133
+ case 'f':
1134
+ if (p != null)
1135
+ state.fontIndex = p;
1136
+ break;
1137
+ case 'ql':
1138
+ currentAlign = 'left';
1139
+ break;
1140
+ case 'qr':
1141
+ currentAlign = 'right';
1142
+ break;
1143
+ case 'qc':
1144
+ currentAlign = 'center';
1145
+ break;
1146
+ case 'qj':
1147
+ currentAlign = 'justify';
1148
+ break;
1149
+ case 'li':
1150
+ state.leftIndent = p ?? 0;
1151
+ break;
1152
+ case 'ri':
1153
+ state.rightIndent = p ?? 0;
1154
+ break;
1155
+ case 'fi':
1156
+ state.firstLineIndent = p ?? 0;
1157
+ break;
1158
+ case 'par':
1159
+ case 'sect':
1160
+ // \sect ends a section, and with it the paragraph: "A\sect B" is two lines.
1161
+ if (inTableCell) {
1162
+ cellBreaks++;
635
1163
  }
636
- else if (dest?.word === 'inkcap') {
637
- // Marks the paragraph that follows as a picture caption.
638
- paragraphIsCaption = true;
1164
+ else {
1165
+ // Paragraph marks from a cell that \pard has since left end paragraphs too.
1166
+ for (; cellBreaks > 0; cellBreaks--)
1167
+ flushParagraph();
1168
+ flushParagraph();
639
1169
  }
640
- continue;
1170
+ break;
1171
+ case 'trowd':
1172
+ // A row's definition, not its start: Word writes the definition before the
1173
+ // cells and again before \row, so the cells read so far are kept.
1174
+ currentRowDefs = [];
1175
+ pendingDef = newCellDef();
1176
+ pendingSide = null;
1177
+ cellBorders = { b: false, other: false };
1178
+ break;
1179
+ case 'trgaph':
1180
+ case 'trkeep':
1181
+ case 'trleft':
1182
+ case 'trhdr':
1183
+ pendingSide = null;
1184
+ break; // table formatting, ignored
1185
+ case 'clbrdrr':
1186
+ case 'clbrdrl':
1187
+ case 'clbrdrt':
1188
+ pendingSide = 'other';
1189
+ break;
1190
+ case 'clbrdrb':
1191
+ pendingSide = 'b';
1192
+ break;
1193
+ case 'brdrnone':
1194
+ case 'brdrnil':
1195
+ pendingSide = null;
1196
+ break;
1197
+ // Every border style RTF names: any of them makes the side a border.
1198
+ case 'brdrs':
1199
+ case 'brdrdb':
1200
+ case 'brdrth':
1201
+ case 'brdrsh':
1202
+ case 'brdrdot':
1203
+ case 'brdrdash':
1204
+ case 'brdrhair':
1205
+ case 'brdrdashsm':
1206
+ case 'brdrdashd':
1207
+ case 'brdrdashdd':
1208
+ case 'brdrdashdotstr':
1209
+ case 'brdrtriple':
1210
+ case 'brdrtnthsg':
1211
+ case 'brdrthtnsg':
1212
+ case 'brdrtnthtnsg':
1213
+ case 'brdrtnthmg':
1214
+ case 'brdrthtnmg':
1215
+ case 'brdrtnthtnmg':
1216
+ case 'brdrtnthlg':
1217
+ case 'brdrthtnlg':
1218
+ case 'brdrtnthtnlg':
1219
+ case 'brdrwavy':
1220
+ case 'brdrwavydb':
1221
+ case 'brdremboss':
1222
+ case 'brdrengrave':
1223
+ case 'brdroutset':
1224
+ case 'brdrinset':
1225
+ if (pendingSide)
1226
+ cellBorders[pendingSide] = true;
1227
+ pendingSide = null;
1228
+ break;
1229
+ case 'clvmgf':
1230
+ pendingDef.vmgf = true;
1231
+ break;
1232
+ case 'clvmrg':
1233
+ pendingDef.vmrg = true;
1234
+ break;
1235
+ case 'clmgf':
1236
+ pendingDef.hmgf = true;
1237
+ break;
1238
+ case 'clmrg':
1239
+ pendingDef.hmrg = true;
1240
+ break;
1241
+ case 'cellx':
1242
+ if (p != null) {
1243
+ pendingDef.right = p;
1244
+ pendingDef.header = cellBorders.b && !cellBorders.other;
1245
+ currentRowDefs.push(pendingDef);
1246
+ }
1247
+ pendingDef = newCellDef();
1248
+ pendingSide = null;
1249
+ cellBorders = { b: false, other: false };
1250
+ break;
1251
+ case 'intbl':
1252
+ inTableCell = true;
1253
+ break;
1254
+ case 'cell':
1255
+ if (pendingHighSurrogate) {
1256
+ pendingHighSurrogate = 0;
1257
+ pushText('\ufffd', state);
1258
+ }
1259
+ currentRowCells.push({ html: trimSpaces(renderRuns(runs)), align: currentAlign });
1260
+ runs = [];
1261
+ marker = null;
1262
+ currentAlign = 'left';
1263
+ // The paragraph mark that ends a cell's last paragraph adds no line.
1264
+ cellBreaks = 0;
1265
+ nestTabPending = false;
1266
+ break;
1267
+ case 'nestcell':
1268
+ // A table inside a cell is read as lines of text in that cell: its cells a
1269
+ // tab apart, each of its rows a line. The writer sends one the same way.
1270
+ nestTabPending = true;
1271
+ break;
1272
+ case 'nestrow':
1273
+ nestTabPending = false;
1274
+ cellBreaks++;
1275
+ break;
1276
+ case 'row': {
1277
+ // Text after the row's last \cell is a cell that was not closed, not the
1278
+ // start of the paragraph after the table.
1279
+ if (trimSpaces(renderRuns(runs))) {
1280
+ currentRowCells.push({ html: trimSpaces(renderRuns(runs)), align: currentAlign });
1281
+ runs = [];
1282
+ marker = null;
1283
+ }
1284
+ // A row with no definition of its own repeats the one before it.
1285
+ const defs = currentRowDefs.length > 0 ? currentRowDefs : lastRowDefs;
1286
+ tableRows.push({ cells: currentRowCells, defs });
1287
+ lastRowDefs = defs;
1288
+ currentRowCells = [];
1289
+ currentRowDefs = [];
1290
+ pendingDef = newCellDef();
1291
+ inTableCell = false;
1292
+ cellBreaks = 0;
1293
+ nestTabPending = false;
1294
+ // The cell's indents end with the table, in whichever group set them:
1295
+ // \row may sit in a group of its own ({\row}).
1296
+ stateStack.forEach(resetIndents);
1297
+ break;
641
1298
  }
642
- stateStack.push(cloneState());
643
- walk(node.children);
644
- stateStack.pop();
645
- }
646
- else if (node.type === 'control') {
647
- const state = currentState();
648
- const w = node.word;
649
- const p = node.param;
650
- switch (w) {
651
- case 'b':
652
- state.bold = p !== 0;
653
- break;
654
- case 'i':
655
- state.italic = p !== 0;
656
- break;
657
- case 'ul':
658
- case 'ulnone':
659
- state.underline = w === 'ul' && p !== 0;
660
- break;
661
- case 'strike':
662
- state.strike = p !== 0;
663
- break;
664
- case 'super':
665
- state.super_ = true;
666
- state.sub = false;
667
- break;
668
- case 'sub':
669
- state.sub = true;
670
- state.super_ = false;
671
- break;
672
- case 'nosupersub':
673
- state.super_ = false;
674
- state.sub = false;
675
- break;
676
- case 'fs':
677
- if (p != null)
678
- state.fontSize = p;
679
- break;
680
- case 'cf':
681
- if (p != null)
682
- state.colorIndex = p;
683
- break;
684
- case 'cb':
685
- break; // \cb not rendered on import
686
- case 'highlight':
687
- if (p != null)
688
- state.highlightIndex = p;
689
- break;
690
- case 'f':
691
- if (p != null)
692
- state.fontIndex = p;
693
- break;
694
- case 'ql':
695
- currentAlign = 'left';
696
- break;
697
- case 'qr':
698
- currentAlign = 'right';
699
- break;
700
- case 'qc':
701
- currentAlign = 'center';
702
- break;
703
- case 'qj':
704
- currentAlign = 'justify';
705
- break;
706
- case 'li':
707
- state.leftIndent = p ?? 0;
708
- break;
709
- case 'ri':
710
- state.rightIndent = p ?? 0;
711
- break;
712
- case 'fi':
713
- state.firstLineIndent = p ?? 0;
714
- break;
715
- case 'par':
716
- if (!inTableCell)
717
- flushParagraph();
718
- break;
719
- case 'trowd':
720
- currentRowCells = [];
721
- currentRowIsHeader = false;
722
- currentRowCellRights = [];
723
- pendingBottomBorder = false;
724
- break;
725
- case 'trgaph':
726
- case 'trkeep':
727
- case 'trleft':
728
- case 'trhdr':
729
- case 'clbrdrr':
730
- case 'clbrdrl':
731
- case 'clbrdrt':
732
- pendingBottomBorder = false;
733
- break; // table formatting, ignored
734
- case 'clbrdrb':
735
- pendingBottomBorder = true;
736
- break;
737
- case 'brdrnone':
738
- case 'brdrnil':
739
- pendingBottomBorder = false;
740
- break;
741
- case 'brdrs':
742
- case 'brdrdb':
743
- case 'brdrth':
744
- case 'brdrdot':
745
- case 'brdrdash':
746
- if (pendingBottomBorder)
747
- currentRowIsHeader = true;
748
- pendingBottomBorder = false;
749
- break;
750
- case 'cellx':
751
- if (p != null)
752
- currentRowCellRights.push(p);
753
- break;
754
- case 'intbl':
755
- inTableCell = true;
756
- break;
757
- case 'cell':
758
- currentRowCells.push(currentParagraph.trim());
759
- currentRowCellAligns.push(currentAlign);
760
- currentParagraph = '';
761
- paragraphHasText = false;
762
- currentAlign = 'left';
763
- break;
764
- case 'row':
765
- tableRows.push({ cells: currentRowCells, isHeader: currentRowIsHeader, cellRights: currentRowCellRights, cellAligns: currentRowCellAligns });
766
- currentRowCells = [];
767
- currentRowIsHeader = false;
768
- currentRowCellRights = [];
769
- currentRowCellAligns = [];
1299
+ case 'pard':
1300
+ // \pard resets the paragraph, not the characters: bold, italic, underline
1301
+ // and strikethrough carry on until \plain or their own \b0. Word relies on it.
1302
+ currentAlign = 'left';
1303
+ resetIndents(state);
1304
+ // Being in a table is a paragraph property too. Without this, one \intbl with
1305
+ // no \row made a single cell of the rest of the document. The marker group
1306
+ // of a list item ({\listtext\pard …}) resets only itself. Between a row's
1307
+ // first \cell and its \row the table goes on whatever \pard says: a writer
1308
+ // that leaves \intbl out there still means the next cell.
1309
+ if (!state.inList && currentRowCells.length === 0)
770
1310
  inTableCell = false;
771
- // The cell's indents end with the table, in whichever group set them:
772
- // \row may sit in a group of its own ({\row}).
773
- stateStack.forEach(resetIndents);
774
- break;
775
- case 'pard':
776
- state.bold = false;
777
- state.italic = false;
778
- state.underline = false;
779
- state.strike = false;
780
- currentAlign = 'left';
781
- resetIndents(state);
782
- break;
783
- case 'line':
784
- currentParagraph += '<br>';
785
- paragraphHasText = true;
786
- break;
787
- case 'tab':
788
- // A real tab, in the shape the editor's Tab key inserts, so it shows as
789
- // one and is written back as \tab (an em space came back as \u8195).
790
- // After a list marker ("\bullet\tab", "1.\tab") the gap stays an em
791
- // space: lists are read as plain lines, and a full tab there is too wide.
792
- currentParagraph += LIST_MARKER.test(currentParagraph) ? '&emsp;' : TAB_HTML;
793
- paragraphHasText = true;
794
- break;
795
- case 'pntext':
796
- case 'listtext':
797
- state.inList = true;
798
- paragraphHasListMarker = true;
799
- break;
800
- case 'u': {
801
- if (p != null) {
802
- let codePoint = p;
803
- if (codePoint < 0)
804
- codePoint += 65536;
805
- currentParagraph += wrapText(String.fromCodePoint(codePoint), state);
806
- paragraphHasText = true;
807
- pendingUnicodeSkip = state.ucSkip ?? 1;
1311
+ break;
1312
+ case 'line':
1313
+ appendHtml('br', '<br>', state);
1314
+ break;
1315
+ case 'tab':
1316
+ appendTab(state);
1317
+ break;
1318
+ case 'pntext':
1319
+ case 'listtext':
1320
+ state.inList = true;
1321
+ paragraphHasListMarker = true;
1322
+ break;
1323
+ case 'u': {
1324
+ if (p != null) {
1325
+ pendingUnicodeSkip = state.ucSkip ?? 1;
1326
+ // \uN is a signed 16-bit number; some writers give the code point itself.
1327
+ const code = p < 0 ? p + 65536 : p;
1328
+ if (code <= 0 || code > 0x10ffff)
1329
+ break; // no character: a NUL, or out of range
1330
+ if (code >= 0xd800 && code <= 0xdbff) {
1331
+ // The first half of a pair: one character with the \u that follows.
1332
+ if (pendingHighSurrogate)
1333
+ appendText('\ufffd', state);
1334
+ pendingHighSurrogate = code;
808
1335
  }
809
- break;
810
- }
811
- case 'uc':
812
- if (p != null) {
813
- state.ucSkip = p;
1336
+ else if (code >= 0xdc00 && code <= 0xdfff) {
1337
+ const high = pendingHighSurrogate;
1338
+ pendingHighSurrogate = 0;
1339
+ appendText(high ? String.fromCharCode(high, code) : '\ufffd', state);
814
1340
  }
1341
+ else {
1342
+ appendText(String.fromCodePoint(code), state);
1343
+ }
1344
+ }
1345
+ break;
1346
+ }
1347
+ case 'uc':
1348
+ if (p != null) {
1349
+ state.ucSkip = Math.max(0, p);
1350
+ }
1351
+ break;
1352
+ case 'plain':
1353
+ state.bold = false;
1354
+ state.italic = false;
1355
+ state.underline = false;
1356
+ state.strike = false;
1357
+ state.super_ = false;
1358
+ state.sub = false;
1359
+ state.fontSize = 24;
1360
+ state.colorIndex = 0;
1361
+ state.highlightIndex = 0;
1362
+ state.fontIndex = defaultFont;
1363
+ break;
1364
+ case 'page':
1365
+ // A page break. On screen it is a rule; the writer sends it back as \page.
1366
+ if (inTableCell) {
1367
+ cellBreaks++;
815
1368
  break;
816
- case 'plain':
817
- state.bold = false;
818
- state.italic = false;
819
- state.underline = false;
820
- state.strike = false;
821
- state.super_ = false;
822
- state.sub = false;
823
- state.fontSize = 24;
824
- state.colorIndex = 0;
825
- state.highlightIndex = 0;
826
- state.fontIndex = 0;
827
- break;
828
- case 'page':
1369
+ }
1370
+ for (; cellBreaks > 0; cellBreaks--)
829
1371
  flushParagraph();
830
- pushParagraph('<hr>', 'left');
831
- break;
832
- case 'emspace':
833
- case 'enspace':
834
- currentParagraph += '&emsp;';
835
- paragraphHasText = true;
836
- break;
837
- case 'emdash':
838
- currentParagraph += '—';
839
- paragraphHasText = true;
840
- break;
841
- case 'endash':
842
- currentParagraph += '–';
843
- paragraphHasText = true;
844
- break;
845
- case 'lquote':
846
- currentParagraph += '\u2018';
847
- paragraphHasText = true;
848
- break;
849
- case 'rquote':
850
- currentParagraph += '\u2019';
851
- paragraphHasText = true;
852
- break;
853
- case 'ldblquote':
854
- currentParagraph += '\u201C';
855
- paragraphHasText = true;
856
- break;
857
- case 'rdblquote':
858
- currentParagraph += '\u201D';
859
- paragraphHasText = true;
860
- break;
861
- case 'bullet':
862
- currentParagraph += '\u2022';
863
- paragraphHasText = true;
864
- break;
865
- default:
866
- break;
867
- }
1372
+ if (runs.length > 0)
1373
+ flushParagraph();
1374
+ flushTable();
1375
+ blocks.push({ kind: 'rule', pageBreak: true });
1376
+ break;
1377
+ case 'emspace':
1378
+ case 'enspace':
1379
+ appendHtml('gap', '&emsp;', state);
1380
+ break;
1381
+ case 'emdash':
1382
+ appendText('\u2014', state);
1383
+ break;
1384
+ case 'endash':
1385
+ appendText('\u2013', state);
1386
+ break;
1387
+ case 'lquote':
1388
+ appendText('\u2018', state);
1389
+ break;
1390
+ case 'rquote':
1391
+ appendText('\u2019', state);
1392
+ break;
1393
+ case 'ldblquote':
1394
+ appendText('\u201C', state);
1395
+ break;
1396
+ case 'rdblquote':
1397
+ appendText('\u201D', state);
1398
+ break;
1399
+ case 'bullet':
1400
+ appendText('\u2022', state);
1401
+ break;
1402
+ default:
1403
+ break;
868
1404
  }
869
- else if (node.type === 'text') {
870
- if (skipDepth > 0)
871
- continue;
872
- const state = currentState();
873
- if (pendingUnicodeSkip > 0) {
874
- const skipCount = Math.min(pendingUnicodeSkip, node.value.length);
875
- pendingUnicodeSkip -= skipCount;
876
- const remainder = node.value.slice(skipCount);
877
- if (remainder) {
878
- currentParagraph += wrapText(remainder, state);
879
- if (/[^\s]/.test(remainder))
880
- paragraphHasText = true;
881
- }
1405
+ }
1406
+ else {
1407
+ const state = currentState();
1408
+ if (pendingUnicodeSkip > 0) {
1409
+ // The characters after \uN that stand in for it where Unicode is not read.
1410
+ if (node.hex) {
1411
+ pendingUnicodeSkip--;
882
1412
  continue;
883
1413
  }
884
- currentParagraph += wrapText(node.value, state);
885
- if (/[^\s]/.test(node.value))
886
- paragraphHasText = true;
1414
+ const skipCount = Math.min(pendingUnicodeSkip, node.value.length);
1415
+ pendingUnicodeSkip -= skipCount;
1416
+ appendText(node.value.slice(skipCount), state);
1417
+ continue;
887
1418
  }
1419
+ appendText(node.value, state);
888
1420
  }
889
1421
  }
890
- walk(rootGroup.children);
1422
+ if (pendingHighSurrogate) {
1423
+ pendingHighSurrogate = 0;
1424
+ pushText('\ufffd', currentState());
1425
+ }
1426
+ // A row the file ends in the middle of, with cells and no \row, is still a row.
1427
+ if (currentRowCells.length > 0) {
1428
+ tableRows.push({ cells: currentRowCells, defs: currentRowDefs.length > 0 ? currentRowDefs : lastRowDefs });
1429
+ currentRowCells = [];
1430
+ inTableCell = false;
1431
+ }
891
1432
  flushTable(); // flush any trailing table rows
892
1433
  // Only flush if there's actually pending content — the final \par in most RTF
893
1434
  // files already flushed the last paragraph, so an unconditional call here
894
1435
  // would push a spurious empty paragraph that becomes a trailing <p><br></p>.
895
- if (currentParagraph || paragraphHasText) {
1436
+ if (runs.length > 0) {
896
1437
  flushParagraph();
897
1438
  }
898
- // Build final HTML from paragraphs (collapse repeated empty lines)
1439
+ // ── Building the HTML ──
1440
+ /** Each block as an ordinary paragraph's content: what it is unless it turns out to be more. */
1441
+ const plain = blocks.map((b) => (b.kind === 'paragraph' ? trimSpaces(renderRuns(b.runs)) : b.kind === 'table' ? b.html : '<hr>'));
1442
+ const items = blocks.map((b) => {
1443
+ if (b.kind !== 'paragraph' || !b.marker || b.inTable || b.caption)
1444
+ return null;
1445
+ if (b.first !== -LIST_HANG || b.left < LIST_HANG || b.right !== 0 || b.align !== 'left')
1446
+ return null;
1447
+ return {
1448
+ kind: b.marker.kind,
1449
+ number: b.marker.number,
1450
+ left: b.left,
1451
+ html: trimSpaces(renderRuns(b.runs.slice(b.marker.end)))
1452
+ };
1453
+ });
1454
+ /** Consecutive list items as nested <ul> and <ol>, one string per list at the top level. */
1455
+ function renderLists(list) {
1456
+ const out = [];
1457
+ let html = '';
1458
+ const open = [];
1459
+ const closeList = () => {
1460
+ const done = open.pop();
1461
+ html += `</li></${done.kind}>`;
1462
+ if (open.length === 0) {
1463
+ out.push(html);
1464
+ html = '';
1465
+ }
1466
+ };
1467
+ for (const item of list) {
1468
+ // A smaller indent ends the lists nested deeper than it.
1469
+ while (open.length > 0 && item.left < open[open.length - 1].left)
1470
+ closeList();
1471
+ const top = open[open.length - 1];
1472
+ if (top && item.left === top.left && item.kind === top.kind && (item.kind === 'ul' || item.number === top.next)) {
1473
+ html += '</li><li>';
1474
+ top.next = item.number + 1;
1475
+ }
1476
+ else {
1477
+ // A change from bullets to numbers, or a number out of sequence, is a new list
1478
+ // in the same place.
1479
+ if (top && item.left === top.left)
1480
+ closeList();
1481
+ const parent = open[open.length - 1];
1482
+ // What the indent adds to the half inch a list level has by itself.
1483
+ const margin = item.left - (parent ? parent.left : 0) - LIST_STEP;
1484
+ const style = margin !== 0 ? ` style="margin-left:${twipsToPt(margin)}"` : '';
1485
+ const start = item.kind === 'ol' && item.number !== 1 ? ` start="${item.number}"` : '';
1486
+ html += `<${item.kind}${start}${style}><li>`;
1487
+ open.push({ kind: item.kind, left: item.left, next: item.number + 1 });
1488
+ }
1489
+ html += item.html || '<br>';
1490
+ }
1491
+ while (open.length > 0)
1492
+ closeList();
1493
+ return out;
1494
+ }
1495
+ /** Whether a paragraph is a heading or a code block, from the formatting of all its text. */
1496
+ function classify(b) {
1497
+ const visible = b.runs.filter((r) => r.type === 'text' && !ONLY_SPACES.test(r.text));
1498
+ if (visible.length === 0 || b.runs.some((r) => r.type === 'html' && r.kind === 'img'))
1499
+ return null;
1500
+ // The size must be the whole paragraph's: one large word does not make a heading.
1501
+ const size = visible[0].fmt.fontSize;
1502
+ if (visible.some((r) => r.fmt.fontSize !== size))
1503
+ return null;
1504
+ if (size === preSize && visible.every((r) => r.fmt.mono))
1505
+ return { tag: 'pre' };
1506
+ if (size === bodySize)
1507
+ return null;
1508
+ const allBold = visible.every((r) => r.fmt.bold);
1509
+ // At the default 12 pt, size alone makes a heading, as it always has. At
1510
+ // another screen size, ordinary 12 pt text can be a step above the body,
1511
+ // so a heading must also be bold, as every heading the writer emits is.
1512
+ if (bodySize !== 24 && !allBold)
1513
+ return null;
1514
+ // Compared in half-points, rounded the way the writer rounds them, so
1515
+ // a heading written at any body size is read back as the same level.
1516
+ for (const tag of ['h1', 'h2', 'h3']) {
1517
+ const nominal = Math.round(bodySize * HEADING_SCALE[tag]);
1518
+ // The heading's own size and bold are the element's: only a size that differs
1519
+ // from it is kept inside.
1520
+ if (size >= nominal)
1521
+ return { tag, options: { dropSize: nominal, dropBold: true } };
1522
+ }
1523
+ return null;
1524
+ }
899
1525
  const rendered = [];
900
- const trimmedParagraphs = paragraphs.map((p) => p.trim());
901
- const isListLine = (text) => /^[-\u2022]/.test(text.replace(/^&emsp;+/g, ''));
902
- for (let i = 0; i < trimmedParagraphs.length; i++) {
903
- const trimmed = trimmedParagraphs[i];
904
- const align = paragraphAligns[i] ?? 'left';
1526
+ // A typed line that starts with a dash or a bullet; a rebuilt list item is not one.
1527
+ const isListLine = (i) => i >= 0 && i < plain.length && !items[i] && /^[-\u2022]/.test(plain[i].replace(/^&emsp;+/g, ''));
1528
+ for (let i = 0; i < blocks.length; i++) {
1529
+ const block = blocks[i];
1530
+ const trimmed = plain[i];
1531
+ if (block.kind === 'rule') {
1532
+ rendered.push(block.pageBreak ? '<hr style="break-after:page">' : '<hr>');
1533
+ continue;
1534
+ }
1535
+ if (block.kind === 'table') {
1536
+ rendered.push(trimmed);
1537
+ continue;
1538
+ }
1539
+ if (items[i]) {
1540
+ const list = [];
1541
+ for (; i < blocks.length && items[i]; i++)
1542
+ list.push(items[i]);
1543
+ i--;
1544
+ rendered.push(...renderLists(list));
1545
+ continue;
1546
+ }
1547
+ const align = block.align;
905
1548
  // The paragraph's style attribute: its alignment, then its indents.
906
- const blockStyle = [align !== 'left' ? `text-align:${align}` : '', paragraphIndents[i] ?? '']
1549
+ const blockStyle = [align !== 'left' ? `text-align:${align}` : '', block.inTable ? '' : indentStyle(block)]
907
1550
  .filter(Boolean)
908
1551
  .join(';');
909
1552
  const styleAttr = blockStyle ? ` style="${blockStyle}"` : '';
910
- const prev = i > 0 ? trimmedParagraphs[i - 1] : '';
911
- const next = i + 1 < trimmedParagraphs.length ? trimmedParagraphs[i + 1] : '';
912
1553
  if (!trimmed) {
913
- if (isListLine(prev) && isListLine(next)) {
1554
+ if (isListLine(i - 1) && isListLine(i + 1)) {
914
1555
  continue;
915
1556
  }
916
1557
  const last = rendered[rendered.length - 1];
@@ -920,16 +1561,15 @@ export function rtfToHtml(rtfString, options = {}) {
920
1561
  rendered.push('<p><br></p>');
921
1562
  continue;
922
1563
  }
923
- if (trimmed === '<hr>') {
1564
+ // The rule the writer sends for <hr>: a centered line of em dashes, and nothing else.
1565
+ if (align === 'center' &&
1566
+ block.runs.every((r) => r.type === 'text' && !r.fmt.bold && !r.fmt.italic && !r.fmt.underline && !r.fmt.strike && !r.fmt.link) &&
1567
+ block.runs.map((r) => (r.type === 'text' ? r.text : '')).join('') === RULE_DASHES) {
924
1568
  rendered.push('<hr>');
925
1569
  continue;
926
1570
  }
927
- if (trimmed.startsWith('<table')) {
928
- rendered.push(trimmed);
929
- continue;
930
- }
931
1571
  // A paragraph tagged by {\*\inkcap} is the description of the figure above it.
932
- if (paragraphCaptions[i]) {
1572
+ if (block.caption) {
933
1573
  const last = rendered.length - 1;
934
1574
  if (last >= 0 && rendered[last].startsWith('<figure') && !rendered[last].includes('<figcaption')) {
935
1575
  rendered[last] = rendered[last].replace('</figure>', `<figcaption>${stripWrappingEm(trimmed)}</figcaption></figure>`);
@@ -939,51 +1579,52 @@ export function rtfToHtml(rtfString, options = {}) {
939
1579
  // A paragraph holding nothing but pictures becomes a figure, so it can carry
940
1580
  // a caption and be aligned/resized as a unit in the editor.
941
1581
  if (IMAGE_ONLY_PARAGRAPH.test(trimmed)) {
942
- const figureStyle = [align !== 'left' ? `text-align:${align}` : '', paragraphFigureIndents[i] ?? '']
1582
+ const figureStyle = [align !== 'left' ? `text-align:${align}` : '', block.inTable ? '' : figureIndentStyle(block)]
943
1583
  .filter(Boolean)
944
1584
  .join(';');
945
1585
  rendered.push(`<figure${figureStyle ? ` style="${figureStyle}"` : ''}>${trimmed}</figure>`);
946
1586
  continue;
947
1587
  }
948
- const sizeMatch = trimmed.match(/font-size:\s*([\d.]+)pt/);
949
- if (sizeMatch) {
950
- // Compared in half-points, rounded the way the writer rounds them, so
951
- // a heading written at any body size is read back as the same level.
952
- const halfPoints = Math.round(parseFloat(sizeMatch[1]) * 2);
953
- const atLeast = (scale) => halfPoints >= Math.round(bodySize * scale);
954
- // At the default 12 pt, size alone makes a heading, as it always has. At
955
- // another screen size, ordinary 12 pt text can be a step above the body,
956
- // so a heading must also be bold, as every heading the writer emits is.
957
- const looksLikeHeading = bodySize === 24 || /^<strong>/.test(trimmed);
958
- if (looksLikeHeading && atLeast(HEADING_SCALE.h1)) {
959
- rendered.push(`<h1${styleAttr}>${stripSizeSpan(trimmed)}</h1>`);
960
- continue;
961
- }
962
- if (looksLikeHeading && atLeast(HEADING_SCALE.h2)) {
963
- rendered.push(`<h2${styleAttr}>${stripSizeSpan(trimmed)}</h2>`);
964
- continue;
965
- }
966
- if (looksLikeHeading && atLeast(HEADING_SCALE.h3)) {
967
- rendered.push(`<h3${styleAttr}>${stripSizeSpan(trimmed)}</h3>`);
968
- continue;
1588
+ const kind = classify(block);
1589
+ if (kind?.tag === 'pre') {
1590
+ // A code block keeps its spaces, and is written back with a left indent only.
1591
+ const left = block.inTable ? 0 : Math.max(0, block.left);
1592
+ const preStyle = left > 0 ? ` style="margin-left:${twipsToPt(left)}"` : '';
1593
+ rendered.push(`<pre${preStyle}>${renderRuns(block.runs, { pre: true, dropSize: preSize })}</pre>`);
1594
+ continue;
1595
+ }
1596
+ if (kind) {
1597
+ // A heading is bold throughout, on screen and when it is written again, so its
1598
+ // pieces are joined as if they all were: what differed only in bold is one piece.
1599
+ const bold = [];
1600
+ for (const run of block.runs) {
1601
+ const fmt = { ...run.fmt, bold: true };
1602
+ const last = bold[bold.length - 1];
1603
+ if (run.type === 'text' && last?.type === 'text' && sameFormat(last.fmt, fmt))
1604
+ last.text += run.text;
1605
+ else
1606
+ bold.push({ ...run, fmt });
969
1607
  }
1608
+ rendered.push(`<${kind.tag}${styleAttr}>${trimSpaces(renderRuns(bold, kind.options))}</${kind.tag}>`);
1609
+ continue;
970
1610
  }
971
1611
  rendered.push(`<p${styleAttr}>${trimmed}</p>`);
972
1612
  }
973
1613
  const output = rendered.join('\n');
974
- // fontTable is parsed (for future font rendering) but not yet used in output
975
- void fontTable;
976
1614
  return output || '<p></p>';
977
1615
  }
978
- function stripSizeSpan(html) {
979
- return html.replace(/^<span style="[^"]*font-size:[^"]*">([\s\S]*)<\/span>$/, '$1');
980
- }
981
1616
  /** Captions are written as italic text; <figcaption> supplies its own styling. */
982
1617
  function stripWrappingEm(html) {
983
1618
  return html.replace(/^<em>([\s\S]*)<\/em>$/, '$1');
984
1619
  }
985
1620
  export function readRtfFile(file, options = {}) {
986
1621
  return new Promise((resolve, reject) => {
1622
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_RTF_BYTES;
1623
+ // Refused before it is read: reading is what takes the memory.
1624
+ if (maxBytes > 0 && file.size > maxBytes) {
1625
+ reject(new Error(`This file is too large to import: ${overLimit(file.size, maxBytes)}`));
1626
+ return;
1627
+ }
987
1628
  const reader = new FileReader();
988
1629
  reader.onload = () => {
989
1630
  try {