svelte-rtf-editor 1.8.2 → 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;
@@ -330,15 +386,15 @@ function parseColorTable(group) {
330
386
  for (const node of group.children) {
331
387
  if (node.type === 'control') {
332
388
  if (node.word === 'red') {
333
- r = node.param ?? 0;
389
+ r = colorComponent(node.param);
334
390
  hasComponents = true;
335
391
  }
336
392
  else if (node.word === 'green') {
337
- g = node.param ?? 0;
393
+ g = colorComponent(node.param);
338
394
  hasComponents = true;
339
395
  }
340
396
  else if (node.word === 'blue') {
341
- b = node.param ?? 0;
397
+ b = colorComponent(node.param);
342
398
  hasComponents = true;
343
399
  }
344
400
  }
@@ -357,27 +413,100 @@ function parseColorTable(group) {
357
413
  return colors;
358
414
  }
359
415
  // ── Font table parser ──
360
- function parseFontTable(group) {
361
- const fonts = new Map();
362
- for (const child of group.children) {
363
- if (child.type === 'group') {
364
- let fNum = 0;
365
- let fName = '';
366
- for (const node of child.children) {
367
- if (node.type === 'control' && node.word === 'f' && node.param != null) {
368
- 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;
369
441
  }
370
- if (node.type === 'text') {
371
- fName += node.value;
442
+ else if (node.word === 'fmodern' || (node.word === 'fprq' && node.param === 1)) {
443
+ fixed = true;
372
444
  }
373
445
  }
374
- // Remove trailing semicolons
375
- fName = fName.replace(/;$/, '').trim();
376
- if (fName)
377
- 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;
378
490
  }
379
491
  }
380
- 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] ?? '') ?? '';
381
510
  }
382
511
  // ── Body size ──
383
512
  /** Groups whose content is not document text. */
@@ -386,6 +515,8 @@ const destinationWords = new Set([
386
515
  'headerl', 'headerr', 'headerf', 'footerl', 'footerr', 'footerf',
387
516
  // \nonshppict duplicates the picture already carried by \*\shppict
388
517
  'nonshppict',
518
+ // {\nonesttables \par} is for readers that do not know nested tables; \nestrow is read here
519
+ 'nonesttables',
389
520
  'object', 'fldinst', 'xmlnstbl', 'listtable', 'listoverridetable',
390
521
  'rsidtbl', 'generator', 'datafield', 'themedata', 'colorschememapping',
391
522
  'latentstyles', 'datastore', 'mmathPr', 'author', 'operator',
@@ -400,67 +531,106 @@ function resetIndents(state) {
400
531
  state.rightIndent = 0;
401
532
  state.firstLineIndent = 0;
402
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
+ }
403
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
+ }
404
602
  const tokens = tokenize(rtfString);
405
603
  const tree = buildTree(tokens);
406
604
  let colorTable = [''];
407
- let fontTable = new Map();
408
- let currentParagraph = '';
409
- const paragraphs = [];
410
- const paragraphAligns = [];
411
- const paragraphIndents = [];
412
- const paragraphFigureIndents = [];
413
- const paragraphCaptions = [];
414
- 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;
415
611
  let paragraphHasListMarker = false;
416
612
  let paragraphIsCaption = false;
417
- /** Append a finished paragraph, keeping the parallel metadata arrays in sync. */
418
- function pushParagraph(html, align, isCaption = false) {
419
- paragraphs.push(html);
420
- paragraphAligns.push(align);
421
- const inTable = inTableCell || html.startsWith('<table');
422
- paragraphIndents.push(inTable ? '' : indentStyle());
423
- paragraphFigureIndents.push(inTable ? '' : figureIndentStyle());
424
- paragraphCaptions.push(isCaption);
425
- }
426
613
  // Paragraph alignment (reset by \pard, affects cells and paragraphs)
427
614
  let currentAlign = 'left';
428
- /**
429
- * The current indents as CSS, in points (20 twips), which the writer reads back as the same
430
- * \li, \ri and \fi: "margin-left:36pt;text-indent:-36pt". A first line may not start left of
431
- * the page margin, where a browser would clip it.
432
- */
433
- function indentStyle() {
434
- const { leftIndent, rightIndent, firstLineIndent } = currentState();
435
- const left = Math.max(0, leftIndent);
436
- const first = Math.max(-left, firstLineIndent);
437
- const parts = [];
438
- if (left > 0)
439
- parts.push(`margin-left:${twipsToPt(left)}`);
440
- if (rightIndent > 0)
441
- parts.push(`margin-right:${twipsToPt(rightIndent)}`);
442
- if (first !== 0)
443
- parts.push(`text-indent:${twipsToPt(first)}`);
444
- return parts.join(';');
445
- }
446
- /**
447
- * The indent of a picture's paragraph: where its one line starts, as a left margin. A figure
448
- * is written back with a left indent only, and a first-line indent on it would be passed on to
449
- * its caption.
450
- */
451
- function figureIndentStyle() {
452
- const { leftIndent, firstLineIndent } = currentState();
453
- const start = Math.max(0, leftIndent) + Math.max(-Math.max(0, leftIndent), firstLineIndent);
454
- return start > 0 ? `margin-left:${twipsToPt(start)}` : '';
455
- }
456
615
  // Table state
457
616
  let tableRows = [];
458
617
  let currentRowCells = [];
459
- let currentRowIsHeader = false;
460
- let currentRowCellRights = [];
461
- 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 };
462
626
  let inTableCell = false;
463
- 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
+ }
464
634
  // First pass: extract color table and font table from the root group
465
635
  const rootGroup = tree.children[0]?.type === 'group' ? tree.children[0] : tree;
466
636
  for (let i = 0; i < rootGroup.children.length; i++) {
@@ -471,13 +641,21 @@ export function rtfToHtml(rtfString, options = {}) {
471
641
  colorTable = parseColorTable(child);
472
642
  }
473
643
  else if (firstControl?.word === 'fonttbl') {
474
- fontTable = parseFontTable(child);
644
+ monoFonts = monospaceFonts(child);
475
645
  }
476
646
  }
647
+ else if (child.type === 'control' && child.word === 'deff' && child.param != null) {
648
+ defaultFont = child.param;
649
+ }
477
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})`;
478
654
  // The screen's body size, in half-points. It is given, not guessed from the
479
655
  // document: guessing misread short documents and ones set below 12 pt.
480
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);
481
659
  // State stack for nested groups
482
660
  function defaultState() {
483
661
  return {
@@ -490,9 +668,10 @@ export function rtfToHtml(rtfString, options = {}) {
490
668
  fontSize: 24, // 12pt default
491
669
  colorIndex: 0,
492
670
  highlightIndex: 0,
493
- fontIndex: 0,
671
+ fontIndex: defaultFont,
494
672
  ucSkip: 1,
495
673
  inList: false,
674
+ link: '',
496
675
  leftIndent: 0,
497
676
  rightIndent: 0,
498
677
  firstLineIndent: 0,
@@ -505,410 +684,874 @@ export function rtfToHtml(rtfString, options = {}) {
505
684
  function cloneState() {
506
685
  return { ...currentState() };
507
686
  }
508
- function buildSpanOpen(state, withSize = true) {
509
- const styles = [];
510
- if (state.colorIndex > 0 && state.colorIndex < colorTable.length) {
511
- const color = colorTable[state.colorIndex];
512
- if (color && color !== 'rgb(0,0,0)') {
513
- styles.push(`color:${color}`);
514
- }
515
- }
516
- if (state.highlightIndex > 0) {
517
- const bg = HIGHLIGHT_COLORS[state.highlightIndex];
518
- if (bg)
519
- styles.push(`background-color:${bg}`);
520
- }
521
- if (withSize && state.fontSize && state.fontSize !== bodySize) {
522
- styles.push(`font-size:${state.fontSize / 2}pt`);
523
- }
524
- if (styles.length === 0)
525
- return '';
526
- 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
+ };
527
708
  }
528
- function wrapText(text, state) {
709
+ // ── Writing a paragraph's pieces as HTML ──
710
+ function renderText(text, fmt, opts) {
529
711
  if (!text)
530
712
  return '';
531
713
  // A size on spaces alone is not shown and would be read as the
532
714
  // paragraph's size, so it is dropped. Underline, strikethrough and
533
715
  // highlight are kept: an underlined blank is a signature line.
534
- const onlySpaces = /^[ \t\r\n\f]*$/.test(text);
535
- let result = text
536
- .replace(/&/g, '&amp;')
537
- .replace(/</g, '&lt;')
538
- .replace(/>/g, '&gt;');
539
- // Apply span styles
540
- const spanOpen = buildSpanOpen(state, !onlySpaces);
541
- if (spanOpen) {
542
- result = `${spanOpen}${result}</span>`;
543
- }
544
- 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)
545
731
  result = `<strong>${result}</strong>`;
546
- if (state.italic)
732
+ if (fmt.italic)
547
733
  result = `<em>${result}</em>`;
548
- if (state.underline)
734
+ if (fmt.underline)
549
735
  result = `<u>${result}</u>`;
550
- if (state.strike)
736
+ if (fmt.strike)
551
737
  result = `<s>${result}</s>`;
552
- if (state.super_)
738
+ if (fmt.super_)
553
739
  result = `<sup>${result}</sup>`;
554
- if (state.sub)
740
+ if (fmt.sub)
555
741
  result = `<sub>${result}</sub>`;
556
742
  return result;
557
743
  }
558
- 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;
559
896
  function flushTable() {
560
897
  if (tableRows.length === 0)
561
898
  return;
562
- let html = '<table style="border-collapse:collapse;width:100%;margin:4px 0">';
563
- for (const row of tableRows) {
564
- html += '<tr>';
565
- const tag = row.isHeader ? 'th' : 'td';
566
- const total = row.cellRights[row.cellRights.length - 1] || 1;
899
+ const rows = tableRows;
900
+ tableRows = [];
901
+ const placedRows = rows.map((row) => {
902
+ const placed = [];
567
903
  let prevRight = 0;
904
+ let step = 0;
568
905
  for (let ci = 0; ci < row.cells.length; ci++) {
569
- const right = row.cellRights[ci] ?? total;
570
- const pct = ((right - prevRight) / total * 100).toFixed(1);
571
- prevRight = right;
572
- const align = row.cellAligns[ci] ?? 'left';
573
- const alignStyle = align !== 'left' ? `;text-align:${align}` : '';
574
- const style = row.isHeader
575
- ? `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}%`
576
994
  : `padding:2px 6px;width:${pct}%${alignStyle}`;
577
- 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}>`;
578
998
  }
579
999
  html += '</tr>';
580
1000
  }
581
1001
  html += '</table>';
582
- pushParagraph(html, 'left');
583
- tableRows = [];
1002
+ blocks.push({ kind: 'table', html });
584
1003
  }
585
1004
  function flushParagraph() {
1005
+ const state = currentState();
1006
+ if (pendingHighSurrogate) {
1007
+ pendingHighSurrogate = 0;
1008
+ pushText('\ufffd', state);
1009
+ }
586
1010
  flushTable();
587
- const trimmed = currentParagraph.trim();
588
- if (trimmed || !paragraphHasListMarker) {
589
- 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
+ });
590
1024
  }
591
- currentParagraph = '';
592
- paragraphHasText = false;
1025
+ runs = [];
1026
+ marker = null;
593
1027
  paragraphHasListMarker = false;
594
1028
  paragraphIsCaption = false;
595
1029
  currentAlign = 'left';
1030
+ nestTabPending = false;
596
1031
  }
597
1032
  let pendingUnicodeSkip = 0;
598
- function walk(nodes) {
599
- for (let i = 0; i < nodes.length; i++) {
600
- const node = nodes[i];
601
- 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());
602
1053
  continue;
603
1054
  }
604
- if (node.type === 'group') {
605
- if (skipDepth > 0) {
606
- skipDepth++;
607
- walk(node.children);
608
- skipDepth--;
609
- 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());
610
1066
  }
611
- const firstCtrl = node.children.find((n) => n.type === 'control');
612
- if (firstCtrl?.word === 'pict') {
613
- const img = renderPicture(node);
614
- if (img) {
615
- currentParagraph += img;
616
- paragraphHasText = true;
617
- }
618
- continue;
1067
+ else if (dest?.word === 'inkcap') {
1068
+ // Marks the paragraph that follows as a picture caption.
1069
+ paragraphIsCaption = true;
619
1070
  }
620
- if (firstCtrl && destinationWords.has(firstCtrl.word)) {
621
- 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++;
622
1076
  }
623
- const hasStarDest = node.children.length >= 2 &&
624
- node.children[0].type === 'control' && node.children[0].word === '*';
625
- if (hasStarDest) {
626
- const dest = node.children.find((n) => n.type === 'control' && n.word !== '*');
627
- // Word wraps pictures in {\*\shppict{\pict …}} — descend into it
628
- // rather than dropping the picture with the rest of the ignorables.
629
- if (dest?.word === 'shppict') {
630
- stateStack.push(cloneState());
631
- walk(node.children);
632
- 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++;
633
1163
  }
634
- else if (dest?.word === 'inkcap') {
635
- // Marks the paragraph that follows as a picture caption.
636
- 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();
637
1169
  }
638
- 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;
639
1298
  }
640
- stateStack.push(cloneState());
641
- walk(node.children);
642
- stateStack.pop();
643
- }
644
- else if (node.type === 'control') {
645
- const state = currentState();
646
- const w = node.word;
647
- const p = node.param;
648
- switch (w) {
649
- case 'b':
650
- state.bold = p !== 0;
651
- break;
652
- case 'i':
653
- state.italic = p !== 0;
654
- break;
655
- case 'ul':
656
- case 'ulnone':
657
- state.underline = w === 'ul' && p !== 0;
658
- break;
659
- case 'strike':
660
- state.strike = p !== 0;
661
- break;
662
- case 'super':
663
- state.super_ = true;
664
- state.sub = false;
665
- break;
666
- case 'sub':
667
- state.sub = true;
668
- state.super_ = false;
669
- break;
670
- case 'nosupersub':
671
- state.super_ = false;
672
- state.sub = false;
673
- break;
674
- case 'fs':
675
- if (p != null)
676
- state.fontSize = p;
677
- break;
678
- case 'cf':
679
- if (p != null)
680
- state.colorIndex = p;
681
- break;
682
- case 'cb':
683
- break; // \cb not rendered on import
684
- case 'highlight':
685
- if (p != null)
686
- state.highlightIndex = p;
687
- break;
688
- case 'f':
689
- if (p != null)
690
- state.fontIndex = p;
691
- break;
692
- case 'ql':
693
- currentAlign = 'left';
694
- break;
695
- case 'qr':
696
- currentAlign = 'right';
697
- break;
698
- case 'qc':
699
- currentAlign = 'center';
700
- break;
701
- case 'qj':
702
- currentAlign = 'justify';
703
- break;
704
- case 'li':
705
- state.leftIndent = p ?? 0;
706
- break;
707
- case 'ri':
708
- state.rightIndent = p ?? 0;
709
- break;
710
- case 'fi':
711
- state.firstLineIndent = p ?? 0;
712
- break;
713
- case 'par':
714
- if (!inTableCell)
715
- flushParagraph();
716
- break;
717
- case 'trowd':
718
- currentRowCells = [];
719
- currentRowIsHeader = false;
720
- currentRowCellRights = [];
721
- pendingBottomBorder = false;
722
- break;
723
- case 'trgaph':
724
- case 'trkeep':
725
- case 'trleft':
726
- case 'trhdr':
727
- case 'clbrdrr':
728
- case 'clbrdrl':
729
- case 'clbrdrt':
730
- pendingBottomBorder = false;
731
- break; // table formatting, ignored
732
- case 'clbrdrb':
733
- pendingBottomBorder = true;
734
- break;
735
- case 'brdrnone':
736
- case 'brdrnil':
737
- pendingBottomBorder = false;
738
- break;
739
- case 'brdrs':
740
- case 'brdrdb':
741
- case 'brdrth':
742
- case 'brdrdot':
743
- case 'brdrdash':
744
- if (pendingBottomBorder)
745
- currentRowIsHeader = true;
746
- pendingBottomBorder = false;
747
- break;
748
- case 'cellx':
749
- if (p != null)
750
- currentRowCellRights.push(p);
751
- break;
752
- case 'intbl':
753
- inTableCell = true;
754
- break;
755
- case 'cell':
756
- currentRowCells.push(currentParagraph.trim());
757
- currentRowCellAligns.push(currentAlign);
758
- currentParagraph = '';
759
- paragraphHasText = false;
760
- currentAlign = 'left';
761
- break;
762
- case 'row':
763
- tableRows.push({ cells: currentRowCells, isHeader: currentRowIsHeader, cellRights: currentRowCellRights, cellAligns: currentRowCellAligns });
764
- currentRowCells = [];
765
- currentRowIsHeader = false;
766
- currentRowCellRights = [];
767
- 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)
768
1310
  inTableCell = false;
769
- // The cell's indents end with the table, in whichever group set them:
770
- // \row may sit in a group of its own ({\row}).
771
- stateStack.forEach(resetIndents);
772
- break;
773
- case 'pard':
774
- state.bold = false;
775
- state.italic = false;
776
- state.underline = false;
777
- state.strike = false;
778
- currentAlign = 'left';
779
- resetIndents(state);
780
- break;
781
- case 'line':
782
- currentParagraph += '<br>';
783
- paragraphHasText = true;
784
- break;
785
- case 'tab':
786
- // A real tab, in the shape the editor's Tab key inserts, so it shows as
787
- // one and is written back as \tab (an em space came back as \u8195).
788
- // After a list marker ("\bullet\tab", "1.\tab") the gap stays an em
789
- // space: lists are read as plain lines, and a full tab there is too wide.
790
- currentParagraph += LIST_MARKER.test(currentParagraph) ? '&emsp;' : TAB_HTML;
791
- paragraphHasText = true;
792
- break;
793
- case 'pntext':
794
- case 'listtext':
795
- state.inList = true;
796
- paragraphHasListMarker = true;
797
- break;
798
- case 'u': {
799
- if (p != null) {
800
- let codePoint = p;
801
- if (codePoint < 0)
802
- codePoint += 65536;
803
- currentParagraph += wrapText(String.fromCodePoint(codePoint), state);
804
- paragraphHasText = true;
805
- 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;
806
1335
  }
807
- break;
808
- }
809
- case 'uc':
810
- if (p != null) {
811
- 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);
812
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++;
813
1368
  break;
814
- case 'plain':
815
- state.bold = false;
816
- state.italic = false;
817
- state.underline = false;
818
- state.strike = false;
819
- state.super_ = false;
820
- state.sub = false;
821
- state.fontSize = 24;
822
- state.colorIndex = 0;
823
- state.highlightIndex = 0;
824
- state.fontIndex = 0;
825
- break;
826
- case 'page':
1369
+ }
1370
+ for (; cellBreaks > 0; cellBreaks--)
827
1371
  flushParagraph();
828
- pushParagraph('<hr>', 'left');
829
- break;
830
- case 'emspace':
831
- case 'enspace':
832
- currentParagraph += '&emsp;';
833
- paragraphHasText = true;
834
- break;
835
- case 'emdash':
836
- currentParagraph += '—';
837
- paragraphHasText = true;
838
- break;
839
- case 'endash':
840
- currentParagraph += '–';
841
- paragraphHasText = true;
842
- break;
843
- case 'lquote':
844
- currentParagraph += '\u2018';
845
- paragraphHasText = true;
846
- break;
847
- case 'rquote':
848
- currentParagraph += '\u2019';
849
- paragraphHasText = true;
850
- break;
851
- case 'ldblquote':
852
- currentParagraph += '\u201C';
853
- paragraphHasText = true;
854
- break;
855
- case 'rdblquote':
856
- currentParagraph += '\u201D';
857
- paragraphHasText = true;
858
- break;
859
- case 'bullet':
860
- currentParagraph += '\u2022';
861
- paragraphHasText = true;
862
- break;
863
- default:
864
- break;
865
- }
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;
866
1404
  }
867
- else if (node.type === 'text') {
868
- if (skipDepth > 0)
869
- continue;
870
- const state = currentState();
871
- if (pendingUnicodeSkip > 0) {
872
- const skipCount = Math.min(pendingUnicodeSkip, node.value.length);
873
- pendingUnicodeSkip -= skipCount;
874
- const remainder = node.value.slice(skipCount);
875
- if (remainder) {
876
- currentParagraph += wrapText(remainder, state);
877
- if (/[^\s]/.test(remainder))
878
- paragraphHasText = true;
879
- }
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--;
880
1412
  continue;
881
1413
  }
882
- currentParagraph += wrapText(node.value, state);
883
- if (/[^\s]/.test(node.value))
884
- paragraphHasText = true;
1414
+ const skipCount = Math.min(pendingUnicodeSkip, node.value.length);
1415
+ pendingUnicodeSkip -= skipCount;
1416
+ appendText(node.value.slice(skipCount), state);
1417
+ continue;
885
1418
  }
1419
+ appendText(node.value, state);
886
1420
  }
887
1421
  }
888
- 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
+ }
889
1432
  flushTable(); // flush any trailing table rows
890
1433
  // Only flush if there's actually pending content — the final \par in most RTF
891
1434
  // files already flushed the last paragraph, so an unconditional call here
892
1435
  // would push a spurious empty paragraph that becomes a trailing <p><br></p>.
893
- if (currentParagraph || paragraphHasText) {
1436
+ if (runs.length > 0) {
894
1437
  flushParagraph();
895
1438
  }
896
- // 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
+ }
897
1525
  const rendered = [];
898
- const trimmedParagraphs = paragraphs.map((p) => p.trim());
899
- const isListLine = (text) => /^[-\u2022]/.test(text.replace(/^&emsp;+/g, ''));
900
- for (let i = 0; i < trimmedParagraphs.length; i++) {
901
- const trimmed = trimmedParagraphs[i];
902
- 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;
903
1548
  // The paragraph's style attribute: its alignment, then its indents.
904
- const blockStyle = [align !== 'left' ? `text-align:${align}` : '', paragraphIndents[i] ?? '']
1549
+ const blockStyle = [align !== 'left' ? `text-align:${align}` : '', block.inTable ? '' : indentStyle(block)]
905
1550
  .filter(Boolean)
906
1551
  .join(';');
907
1552
  const styleAttr = blockStyle ? ` style="${blockStyle}"` : '';
908
- const prev = i > 0 ? trimmedParagraphs[i - 1] : '';
909
- const next = i + 1 < trimmedParagraphs.length ? trimmedParagraphs[i + 1] : '';
910
1553
  if (!trimmed) {
911
- if (isListLine(prev) && isListLine(next)) {
1554
+ if (isListLine(i - 1) && isListLine(i + 1)) {
912
1555
  continue;
913
1556
  }
914
1557
  const last = rendered[rendered.length - 1];
@@ -918,16 +1561,15 @@ export function rtfToHtml(rtfString, options = {}) {
918
1561
  rendered.push('<p><br></p>');
919
1562
  continue;
920
1563
  }
921
- 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) {
922
1568
  rendered.push('<hr>');
923
1569
  continue;
924
1570
  }
925
- if (trimmed.startsWith('<table')) {
926
- rendered.push(trimmed);
927
- continue;
928
- }
929
1571
  // A paragraph tagged by {\*\inkcap} is the description of the figure above it.
930
- if (paragraphCaptions[i]) {
1572
+ if (block.caption) {
931
1573
  const last = rendered.length - 1;
932
1574
  if (last >= 0 && rendered[last].startsWith('<figure') && !rendered[last].includes('<figcaption')) {
933
1575
  rendered[last] = rendered[last].replace('</figure>', `<figcaption>${stripWrappingEm(trimmed)}</figcaption></figure>`);
@@ -937,51 +1579,52 @@ export function rtfToHtml(rtfString, options = {}) {
937
1579
  // A paragraph holding nothing but pictures becomes a figure, so it can carry
938
1580
  // a caption and be aligned/resized as a unit in the editor.
939
1581
  if (IMAGE_ONLY_PARAGRAPH.test(trimmed)) {
940
- const figureStyle = [align !== 'left' ? `text-align:${align}` : '', paragraphFigureIndents[i] ?? '']
1582
+ const figureStyle = [align !== 'left' ? `text-align:${align}` : '', block.inTable ? '' : figureIndentStyle(block)]
941
1583
  .filter(Boolean)
942
1584
  .join(';');
943
1585
  rendered.push(`<figure${figureStyle ? ` style="${figureStyle}"` : ''}>${trimmed}</figure>`);
944
1586
  continue;
945
1587
  }
946
- const sizeMatch = trimmed.match(/font-size:\s*([\d.]+)pt/);
947
- if (sizeMatch) {
948
- // Compared in half-points, rounded the way the writer rounds them, so
949
- // a heading written at any body size is read back as the same level.
950
- const halfPoints = Math.round(parseFloat(sizeMatch[1]) * 2);
951
- const atLeast = (scale) => halfPoints >= Math.round(bodySize * scale);
952
- // At the default 12 pt, size alone makes a heading, as it always has. At
953
- // another screen size, ordinary 12 pt text can be a step above the body,
954
- // so a heading must also be bold, as every heading the writer emits is.
955
- const looksLikeHeading = bodySize === 24 || /^<strong>/.test(trimmed);
956
- if (looksLikeHeading && atLeast(HEADING_SCALE.h1)) {
957
- rendered.push(`<h1${styleAttr}>${stripSizeSpan(trimmed)}</h1>`);
958
- continue;
959
- }
960
- if (looksLikeHeading && atLeast(HEADING_SCALE.h2)) {
961
- rendered.push(`<h2${styleAttr}>${stripSizeSpan(trimmed)}</h2>`);
962
- continue;
963
- }
964
- if (looksLikeHeading && atLeast(HEADING_SCALE.h3)) {
965
- rendered.push(`<h3${styleAttr}>${stripSizeSpan(trimmed)}</h3>`);
966
- 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 });
967
1607
  }
1608
+ rendered.push(`<${kind.tag}${styleAttr}>${trimSpaces(renderRuns(bold, kind.options))}</${kind.tag}>`);
1609
+ continue;
968
1610
  }
969
1611
  rendered.push(`<p${styleAttr}>${trimmed}</p>`);
970
1612
  }
971
1613
  const output = rendered.join('\n');
972
- // fontTable is parsed (for future font rendering) but not yet used in output
973
- void fontTable;
974
1614
  return output || '<p></p>';
975
1615
  }
976
- function stripSizeSpan(html) {
977
- return html.replace(/^<span style="[^"]*font-size:[^"]*">([\s\S]*)<\/span>$/, '$1');
978
- }
979
1616
  /** Captions are written as italic text; <figcaption> supplies its own styling. */
980
1617
  function stripWrappingEm(html) {
981
1618
  return html.replace(/^<em>([\s\S]*)<\/em>$/, '$1');
982
1619
  }
983
1620
  export function readRtfFile(file, options = {}) {
984
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
+ }
985
1628
  const reader = new FileReader();
986
1629
  reader.onload = () => {
987
1630
  try {