@open-document/core 0.13.1 → 0.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1386,6 +1386,8 @@ function tokenStyle(kind) {
1386
1386
  default: return;
1387
1387
  }
1388
1388
  }
1389
+ /** Marks a framed component whose parts the Word export keeps inside one frame. */
1390
+ const PANEL_ATTR = "data-od-panel";
1389
1391
  /**
1390
1392
  * Print-ready syntax-highlighted code block with optional header bar, line
1391
1393
  * numbers, and highlighted lines. Uses `--od-*` variables so it harmonizes with
@@ -1396,6 +1398,7 @@ function CodeBlock({ code, children, lang, title, lineNumbers = false, highlight
1396
1398
  const highlighted = new Set(highlightLines ?? []);
1397
1399
  return /* @__PURE__ */ jsxs("div", {
1398
1400
  ...sourceAttrs(loc),
1401
+ [PANEL_ATTR]: "",
1399
1402
  className,
1400
1403
  style: {
1401
1404
  border: "1px solid var(--od-rule, #e5e7eb)",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-document/core",
3
- "version": "0.13.1",
3
+ "version": "0.13.2",
4
4
  "description": "Runtime and CLI for open-doc — write documents in docs/, we handle the pages, print layout, and export.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -126,6 +126,9 @@ function tokenStyle(kind: TokenKind): CSSProperties | undefined {
126
126
  }
127
127
  }
128
128
 
129
+ /** Marks a framed component whose parts the Word export keeps inside one frame. */
130
+ export const PANEL_ATTR = 'data-od-panel';
131
+
129
132
  /**
130
133
  * Print-ready syntax-highlighted code block with optional header bar, line
131
134
  * numbers, and highlighted lines. Uses `--od-*` variables so it harmonizes with
@@ -149,6 +152,7 @@ export function CodeBlock({
149
152
  return (
150
153
  <div
151
154
  {...sourceAttrs(loc)}
155
+ {...{ [PANEL_ATTR]: '' }}
152
156
  className={className}
153
157
  style={{
154
158
  border: '1px solid var(--od-rule, #e5e7eb)',
@@ -13,6 +13,7 @@
13
13
  * but it is there, and nothing around it has to be retyped.
14
14
  */
15
15
 
16
+ import { PANEL_ATTR } from '../../components/code-block';
16
17
  import { FLOW_BLOCK_ATTR } from '../../components/flow-page';
17
18
  import { FOOTNOTE_ID_ATTR } from '../../components/footnote';
18
19
  import { elementToPng } from '../export-image';
@@ -28,6 +29,7 @@ import {
28
29
  PX_TO_HALF_POINTS,
29
30
  PX_TO_TWIPS,
30
31
  type Run,
32
+ type SectionLayout,
31
33
  type StyleId,
32
34
  type Table,
33
35
  type TableCell,
@@ -59,6 +61,8 @@ export type WalkResult = {
59
61
  images: ImagePart[];
60
62
  lists: Array<'bullet' | 'decimal'>;
61
63
  finalRunning: boolean;
64
+ finalColumns?: SectionLayout['columns'];
65
+ finalContinuous?: boolean;
62
66
  };
63
67
 
64
68
  type Ctx = WalkOptions & {
@@ -119,7 +123,9 @@ function place(block: Block, box: { top: number; bottom: number }) {
119
123
  }
120
124
 
121
125
  function isHidden(el: Element): boolean {
122
- if (el.getAttribute('aria-hidden') === 'true') return true;
126
+ // A drawing is hidden from a screen reader because it says nothing in words —
127
+ // a sparkline — not because it is off the page.
128
+ if (el.getAttribute('aria-hidden') === 'true' && !(el instanceof SVGSVGElement)) return true;
123
129
  const style = getComputedStyle(el);
124
130
  return style.display === 'none' || style.visibility === 'hidden';
125
131
  }
@@ -480,8 +486,11 @@ async function blockOfElement(el: Element, ctx: Ctx, out: Block[], style: StyleI
480
486
  return;
481
487
  }
482
488
  if (tag === 'PRE') {
483
- const paragraph = await paragraphOf(Array.from(el.childNodes), 'Code', el, ctx);
484
- if (paragraph) out.push(...boxed([paragraph], el));
489
+ out.push(...boxed(await codeLines(el, ctx), el));
490
+ return;
491
+ }
492
+ if (el.hasAttribute(PANEL_ATTR)) {
493
+ out.push(...(await panelOf(el, ctx, style)));
485
494
  return;
486
495
  }
487
496
  if (tag === 'FIGURE') {
@@ -501,6 +510,11 @@ async function blockOfElement(el: Element, ctx: Ctx, out: Block[], style: StyleI
501
510
  out.push(...(paragraphs.length === inner.length ? boxed(paragraphs, el) : inner));
502
511
  return;
503
512
  }
513
+ const row = await sideBySideOf(el, ctx, style);
514
+ if (row) {
515
+ out.push(row);
516
+ return;
517
+ }
504
518
  if (isTabbedRow(el, ctx)) {
505
519
  const pieces = Array.from(el.children).filter((child) => !skip(child, ctx));
506
520
  const inlines: Inline[] = [];
@@ -527,6 +541,147 @@ async function blockOfElement(el: Element, ctx: Ctx, out: Block[], style: StyleI
527
541
  await blocksOf(el, ctx, out, style);
528
542
  }
529
543
 
544
+ /**
545
+ * A `<pre>` whose lines are elements of their own — a highlighted code block —
546
+ * has no newlines in its text for Word to break at, so each line is a
547
+ * paragraph, and a highlighted one keeps its tint.
548
+ */
549
+ async function codeLines(pre: Element, ctx: Ctx): Promise<Paragraph[]> {
550
+ const lines = Array.from(pre.children).filter((child) => !skip(child, ctx) && isBlock(child));
551
+ if (lines.length === 0) {
552
+ const paragraph = await paragraphOf(Array.from(pre.childNodes), 'Code', pre, ctx);
553
+ return paragraph ? [paragraph] : [];
554
+ }
555
+ const out: Paragraph[] = [];
556
+ for (const line of lines) {
557
+ const paragraph = (await paragraphOf(Array.from(line.childNodes), 'Code', line, ctx)) ?? {
558
+ type: 'paragraph',
559
+ style: 'Code',
560
+ inlines: [],
561
+ };
562
+ const shade = hexColor(getComputedStyle(line).backgroundColor);
563
+ out.push({ ...paragraph, spacingBefore: 0, spacingAfter: 0, ...(shade ? { shade } : {}) });
564
+ }
565
+ return out;
566
+ }
567
+
568
+ /**
569
+ * A framed component — a code block with its title bar — as a one-column
570
+ * table, one row per part, so each part keeps its own tint and inset inside
571
+ * the frame the way it printed.
572
+ */
573
+ async function panelOf(el: Element, ctx: Ctx, style: StyleId): Promise<Block[]> {
574
+ const frame = getComputedStyle(el);
575
+ const fill = hexColor(frame.backgroundColor) ?? undefined;
576
+ const parts = Array.from(el.children).filter((child) => !skip(child, ctx));
577
+ const width = el.getBoundingClientRect().width * PX_TO_TWIPS;
578
+ const drawn: Array<{ part: Element; blocks: Block[] }> = [];
579
+ for (const part of parts) {
580
+ const blocks: Block[] = [];
581
+ await blockOf(part, ctx, blocks, style);
582
+ drawn.push({ part, blocks });
583
+ }
584
+ const all = drawn.flatMap((entry) => entry.blocks);
585
+ if (all.length === 0) return [];
586
+ if (all.some((block) => block.type !== 'paragraph')) return all;
587
+
588
+ let inset = 0;
589
+ const rows: Table['rows'] = drawn.map(({ part, blocks }, at) => {
590
+ const look = getComputedStyle(part);
591
+ // A <pre> carries its inset on itself; a title bar carries its own.
592
+ const padding = getComputedStyle(part.querySelector('pre') ?? part);
593
+ const pad = (side: string) =>
594
+ (Number.parseFloat(padding.getPropertyValue(`padding-${side}`)) || 0) * PX_TO_TWIPS;
595
+ inset = Math.max(inset, pad('left'));
596
+ const borders: NonNullable<TableCell['borders']> = {};
597
+ for (const side of ['Left', 'Right'] as const) {
598
+ const rule = border(frame, side);
599
+ if (rule) borders[side.toLowerCase() as 'left'] = rule;
600
+ }
601
+ const top = at === 0 ? border(frame, 'Top') : undefined;
602
+ if (top) borders.top = top;
603
+ const bottom = at === drawn.length - 1 ? border(frame, 'Bottom') : border(look, 'Bottom');
604
+ if (bottom) borders.bottom = bottom;
605
+ const tint = hexColor(look.backgroundColor) ?? fill;
606
+ const paragraphs = blocks as Paragraph[];
607
+ return {
608
+ header: false,
609
+ cells: [
610
+ {
611
+ blocks: paragraphs.map((paragraph, index) => ({
612
+ ...paragraph,
613
+ ...(index === 0 ? { spacingBefore: 0 } : {}),
614
+ ...(index === paragraphs.length - 1 ? { spacingAfter: 0 } : {}),
615
+ // A tab to the right edge of the page would land outside the frame.
616
+ ...(paragraph.rightTab !== undefined ? { rightTab: width - pad('left') * 2 } : {}),
617
+ })),
618
+ borders,
619
+ ...(tint ? { fill: tint } : {}),
620
+ padding: {
621
+ top: pad('top'),
622
+ left: pad('left'),
623
+ bottom: pad('bottom'),
624
+ right: pad('right'),
625
+ },
626
+ },
627
+ ],
628
+ };
629
+ });
630
+ const table: Table = {
631
+ type: 'table',
632
+ columns: [width],
633
+ rows,
634
+ cellMargin: { left: inset, right: inset },
635
+ };
636
+ // A table has no space after of its own; the frame's margin is a spacer.
637
+ const { spacingAfter = 0 } = spacing(el);
638
+ if (spacingAfter <= 0) return [table];
639
+ return [
640
+ table,
641
+ { type: 'paragraph', inlines: [], spacingBefore: 0, spacingAfter: 0, lineExact: spacingAfter },
642
+ ];
643
+ }
644
+
645
+ /**
646
+ * Framed boxes laid side by side — two callouts in a grid — as one row of a
647
+ * table, each box a cell and the gap an empty one, rather than a stack of
648
+ * boxes each as narrow as its column was.
649
+ */
650
+ async function sideBySideOf(el: Element, ctx: Ctx, style: StyleId): Promise<Table | null> {
651
+ const display = getComputedStyle(el).display;
652
+ if (!display.includes('grid') && !display.includes('flex')) return null;
653
+ const boxes = Array.from(el.children).filter((child) => !skip(child, ctx));
654
+ if (boxes.length < 2) return null;
655
+ // Decided before walking, so a row that turns out not to qualify has not
656
+ // already drawn its pictures and numbered its notes once.
657
+ const framed = (box: Element) =>
658
+ box.tagName === 'BLOCKQUOTE' || box.tagName === 'PRE' || box.hasAttribute(PANEL_ATTR);
659
+ if (!boxes.every(framed)) return null;
660
+ const rects = boxes.map((box) => box.getBoundingClientRect());
661
+ const top = rects[0]?.top ?? 0;
662
+ if (rects.some((rect) => Math.abs(rect.top - top) > 2)) return null;
663
+ const cells: TableCell[] = [];
664
+ const columns: number[] = [];
665
+ for (const [at, box] of boxes.entries()) {
666
+ const drawn: Block[] = [];
667
+ await blockOf(box, ctx, drawn, style);
668
+ const table = drawn[0];
669
+ const cell =
670
+ table?.type === 'table' && table.rows.length === 1 ? table.rows[0]?.cells[0] : null;
671
+ if (drawn.length !== 1 || !cell || table?.type !== 'table' || table.columns.length !== 1) {
672
+ return null;
673
+ }
674
+ if (at > 0) {
675
+ const gap = (rects[at]?.left ?? 0) - (rects[at - 1]?.right ?? 0);
676
+ columns.push(Math.max(0, gap) * PX_TO_TWIPS);
677
+ cells.push({ blocks: [], padding: { top: 0, left: 0, bottom: 0, right: 0 } });
678
+ }
679
+ columns.push((rects[at]?.width ?? 0) * PX_TO_TWIPS);
680
+ cells.push(cell);
681
+ }
682
+ return { type: 'table', columns, rows: [{ header: false, cells }] };
683
+ }
684
+
530
685
  function tocOf(el: Element, ctx: Ctx): Block {
531
686
  const entries = Array.from(el.querySelectorAll('[data-od-toc-entry]')).map((row) => {
532
687
  const id = row.getAttribute('data-od-toc-entry') ?? '';
@@ -538,7 +693,41 @@ function tocOf(el: Element, ctx: Ctx): Block {
538
693
  return { type: 'toc', entries };
539
694
  }
540
695
 
696
+ /**
697
+ * An item of a list drawn without markers — a bibliography whose `[1]` is its
698
+ * own element. Word would number it a second time, so it is a plain paragraph,
699
+ * its label hanging to the left of the text as it sat beside it on the page.
700
+ */
701
+ async function looseItemOf(item: Element, ctx: Ctx): Promise<Paragraph | null> {
702
+ const pieces = Array.from(item.children).filter((piece) => !skip(piece, ctx));
703
+ const label = pieces[0];
704
+ const text = pieces[1];
705
+ if (!getComputedStyle(item).display.includes('flex') || !label || !text) {
706
+ return paragraphOf(Array.from(item.childNodes), 'Normal', item, ctx);
707
+ }
708
+ const hang = Math.max(
709
+ 0,
710
+ (text.getBoundingClientRect().left - item.getBoundingClientRect().left) * PX_TO_TWIPS,
711
+ );
712
+ const inlines: Inline[] = [...tidy(await inlinesOf([label], ctx.baselines.Normal, ctx))];
713
+ inlines.push({ type: 'tab' });
714
+ for (const [at, piece] of pieces.slice(1).entries()) {
715
+ if (at > 0) inlines.push({ type: 'text', text: ' ' });
716
+ inlines.push(...tidy(await inlinesOf([piece], ctx.baselines.Normal, ctx)));
717
+ }
718
+ return { type: 'paragraph', inlines, ...spacing(item), indent: hang, hanging: hang };
719
+ }
720
+
541
721
  async function listOf(el: Element, ctx: Ctx, out: Block[], level: number) {
722
+ const first = Array.from(el.children).find((item) => item.tagName === 'LI');
723
+ if (first && getComputedStyle(first).listStyleType === 'none') {
724
+ for (const item of Array.from(el.children)) {
725
+ if (item.tagName !== 'LI' || skip(item, ctx)) continue;
726
+ const paragraph = await looseItemOf(item, ctx);
727
+ if (paragraph) out.push(paragraph);
728
+ }
729
+ return;
730
+ }
542
731
  ctx.lists.push(el.tagName === 'OL' ? 'decimal' : 'bullet');
543
732
  const numId = ctx.lists.length;
544
733
  for (const item of Array.from(el.children)) {
@@ -715,6 +904,25 @@ async function figureParts(figure: Element, ctx: Ctx, out: Block[]) {
715
904
  // Pages
716
905
  // ---------------------------------------------------------------------------
717
906
 
907
+ /** The multi-column box a flow page's blocks sit in, if they sit in one. */
908
+ function columnBoxOf(host: HTMLElement): { el: Element; count: number; gap: number } | null {
909
+ const block = host.querySelector(`[${FLOW_BLOCK_ATTR}]`);
910
+ for (let el = block?.parentElement; el && el !== host; el = el.parentElement) {
911
+ const style = getComputedStyle(el);
912
+ const count = Number.parseInt(style.columnCount, 10);
913
+ if (count > 1) return { el, count, gap: Number.parseFloat(style.columnGap) || 0 };
914
+ }
915
+ return null;
916
+ }
917
+
918
+ /** Which column of the box a block starts in, from where it was drawn. */
919
+ function columnIndexOf(block: Element, box: { el: Element; count: number; gap: number }): number {
920
+ const frame = box.el.getBoundingClientRect();
921
+ const width = (frame.width - box.gap * (box.count - 1)) / box.count;
922
+ const left = block.getBoundingClientRect().left - frame.left;
923
+ return Math.max(0, Math.min(box.count - 1, Math.floor((left + 1) / (width + box.gap))));
924
+ }
925
+
718
926
  /**
719
927
  * The document in reading order. A fixed page is its own sheet in Word too, so
720
928
  * it starts on a new page; a flow section's later pages continue it, and Word
@@ -735,7 +943,7 @@ export async function docxFromPages(
735
943
  page: { top: 0, bottom: 0, fixed: true, first: true },
736
944
  };
737
945
  const blocks: Block[] = [];
738
- let previousRunning = true;
946
+ let previous: SectionLayout = { running: true };
739
947
 
740
948
  for (const [index, host] of hosts.entries()) {
741
949
  const info = pages[index] ?? { continues: false };
@@ -748,8 +956,39 @@ export async function docxFromPages(
748
956
  };
749
957
  const own: Block[] = [];
750
958
  const flowBlocks = Array.from(host.querySelectorAll(`[${FLOW_BLOCK_ATTR}]`));
959
+ const columnsHere = flowBlocks.length > 0 ? columnBoxOf(host) : null;
751
960
  if (flowBlocks.length > 0) {
752
- for (const block of flowBlocks) await blockOf(block, ctx, own, 'Normal');
961
+ // A later page of a section in columns starts after a break as well: from
962
+ // the last column of the page before, Word's next column is this page's first.
963
+ let column = columnsHere && info.continues ? -1 : 0;
964
+ for (const block of flowBlocks) {
965
+ const start = own.length;
966
+ await blockOf(block, ctx, own, 'Normal');
967
+ // Word fills a column to the foot of the page before it starts the
968
+ // next, and Pages never balances them; a break where the printed
969
+ // page's next column began sets the columns as they printed.
970
+ const at = columnsHere ? columnIndexOf(block, columnsHere) : 0;
971
+ if (at > column && own.length > start) {
972
+ const first = own[start];
973
+ if (first?.type === 'paragraph' && at === column + 1) {
974
+ first.columnBreakBefore = true;
975
+ } else {
976
+ const breaks = Array.from(
977
+ { length: at - column },
978
+ (): Paragraph => ({
979
+ type: 'paragraph',
980
+ inlines: [],
981
+ columnBreakBefore: true,
982
+ spacingBefore: 0,
983
+ spacingAfter: 0,
984
+ lineExact: 20,
985
+ }),
986
+ );
987
+ own.splice(start, 0, ...breaks);
988
+ }
989
+ column = at;
990
+ }
991
+ }
753
992
  } else {
754
993
  await blocksOf(host, ctx, own);
755
994
  }
@@ -762,10 +1001,26 @@ export async function docxFromPages(
762
1001
  if (ctx.page.fixed) {
763
1002
  let bottom = rect.top + options.margin;
764
1003
  let previous: Paragraph | null = null;
1004
+ // Blocks that sat side by side on the sheet — a contents list beside a
1005
+ // list of figures — are stacked in Word, and the height that adds comes
1006
+ // out of the gaps below them, or the sheet's foot spills onto a page of
1007
+ // its own.
1008
+ let stacked = 0;
1009
+ // Every paragraph of a list is placed at the list's box; one box is one block of height.
1010
+ const counted = new Set<string>();
765
1011
  for (const block of own) {
766
1012
  const box = placed.get(block);
767
1013
  if (!box) continue;
768
- const gap = Math.max(0, box.top - bottom);
1014
+ const key = `${box.top}:${box.bottom}`;
1015
+ const repeat = counted.has(key);
1016
+ counted.add(key);
1017
+ if (!repeat && box.top < bottom) {
1018
+ stacked += box.bottom - box.top - Math.max(0, box.bottom - bottom);
1019
+ }
1020
+ let gap = Math.max(0, box.top - bottom);
1021
+ const taken = Math.min(gap, stacked);
1022
+ gap -= taken;
1023
+ stacked -= taken;
769
1024
  if (block.type === 'paragraph') {
770
1025
  block.spacingBefore = gap * PX_TO_TWIPS;
771
1026
  if (previous) previous.spacingAfter = 0;
@@ -794,14 +1049,28 @@ export async function docxFromPages(
794
1049
  }
795
1050
  }
796
1051
  // Flow pages carry the section's running header and footer; a fixed sheet
797
- // prints its own running lines, so it sits in a section without them. The
798
- // section break itself starts the next page.
799
- const running = !ctx.page.fixed;
800
- const breaksSection = own.length > 0 && blocks.length > 0 && running !== previousRunning;
1052
+ // prints its own running lines, so it sits in a section without them. A
1053
+ // flow set in columns is a section of that many columns. The section
1054
+ // break itself starts the next page.
1055
+ const layout: SectionLayout = { running: !ctx.page.fixed };
1056
+ if (!ctx.page.fixed && columnsHere) {
1057
+ layout.columns = { count: columnsHere.count, gap: columnsHere.gap * PX_TO_TWIPS };
1058
+ }
1059
+ const breaksSection =
1060
+ own.length > 0 &&
1061
+ blocks.length > 0 &&
1062
+ (layout.running !== previous.running ||
1063
+ (layout.columns?.count ?? 1) !== (previous.columns?.count ?? 1));
1064
+ // Columns fill one at a time to the foot of the page unless a continuous
1065
+ // break ends them, so the section after a set of columns starts on their
1066
+ // page and breaks to its own with the first paragraph instead.
1067
+ const afterColumns =
1068
+ breaksSection && (previous.columns?.count ?? 1) > 1 && layout.running === previous.running;
1069
+ if (afterColumns) layout.continuous = true;
801
1070
  if (breaksSection) {
802
1071
  const last = blocks[blocks.length - 1];
803
1072
  if (last?.type === 'paragraph' && !last.sectionEnd) {
804
- last.sectionEnd = { running: previousRunning };
1073
+ last.sectionEnd = previous;
805
1074
  } else {
806
1075
  blocks.push({
807
1076
  type: 'paragraph',
@@ -809,13 +1078,13 @@ export async function docxFromPages(
809
1078
  spacingBefore: 0,
810
1079
  spacingAfter: 0,
811
1080
  lineExact: 20,
812
- sectionEnd: { running: previousRunning },
1081
+ sectionEnd: previous,
813
1082
  });
814
1083
  }
815
1084
  }
816
1085
  const first = own[0];
817
1086
  if (first) {
818
- const newPage = index > 0 && !info.continues && !breaksSection;
1087
+ const newPage = index > 0 && !info.continues && (!breaksSection || afterColumns);
819
1088
  // Word and Pages drop the space before the first paragraph on a page —
820
1089
  // at the top of the document and after a break alike — so a gap there,
821
1090
  // a cover's title low on its sheet or a closing line centred, is held
@@ -835,7 +1104,7 @@ export async function docxFromPages(
835
1104
  });
836
1105
  }
837
1106
  }
838
- if (own.length > 0) previousRunning = running;
1107
+ if (own.length > 0) previous = layout;
839
1108
  blocks.push(...own);
840
1109
  }
841
1110
 
@@ -856,7 +1125,15 @@ export async function docxFromPages(
856
1125
  });
857
1126
  }
858
1127
 
859
- return { blocks, footnotes, images: ctx.images, lists: ctx.lists, finalRunning: previousRunning };
1128
+ return {
1129
+ blocks,
1130
+ footnotes,
1131
+ images: ctx.images,
1132
+ lists: ctx.lists,
1133
+ finalRunning: previous.running,
1134
+ ...(previous.columns ? { finalColumns: previous.columns } : {}),
1135
+ ...(previous.continuous ? { finalContinuous: true } : {}),
1136
+ };
860
1137
  }
861
1138
 
862
1139
  /** Runs for one element — the footer the orchestrator renders on its own. */
@@ -43,6 +43,13 @@ describe('hexColor', () => {
43
43
  expect(hexColor('#abc')).toBe('aabbcc');
44
44
  expect(hexColor('rgba(0, 0, 0, 0)')).toBeNull();
45
45
  });
46
+
47
+ it('reads color-mix results and flattens a translucent tint onto white', () => {
48
+ expect(hexColor('color(srgb 0.0863 0.0941 0.1137)')).toBe('16181d');
49
+ expect(hexColor('rgba(37, 99, 235, 0.1)')).toBe('e9effd');
50
+ expect(hexColor('color(srgb 0.145 0.388 0.922 / 0.1)')).toBe('e9effd');
51
+ expect(hexColor('color(srgb 0 0 0 / 0)')).toBeNull();
52
+ });
46
53
  });
47
54
 
48
55
  describe('escapeXml', () => {
@@ -314,6 +321,87 @@ describe('buildDocxParts', () => {
314
321
  expect(doc).toContain('</w:tcPr><w:p/></w:tc>');
315
322
  });
316
323
 
324
+ it('shades a paragraph and hangs its first line', () => {
325
+ const doc = buildDocxParts({
326
+ ...MODEL,
327
+ blocks: [
328
+ {
329
+ type: 'paragraph',
330
+ style: 'Code',
331
+ shade: 'e9effd',
332
+ inlines: [{ type: 'text', text: 'x' }],
333
+ },
334
+ {
335
+ type: 'paragraph',
336
+ indent: 480,
337
+ hanging: 480,
338
+ inlines: [
339
+ { type: 'text', text: '[1]' },
340
+ { type: 'tab' },
341
+ { type: 'text', text: 'Knuth' },
342
+ ],
343
+ },
344
+ ],
345
+ })['word/document.xml'] as string;
346
+ // Shading sits after the style and before spacing, where the schema puts it.
347
+ expect(doc).toContain(
348
+ '<w:pPr><w:pStyle w:val="Code"/><w:shd w:val="clear" w:color="auto" w:fill="e9effd"/></w:pPr>',
349
+ );
350
+ expect(doc).toContain('<w:ind w:left="480" w:hanging="480"/>');
351
+ });
352
+
353
+ it('sets a section in columns, ending the one before it', () => {
354
+ const doc = buildDocxParts({
355
+ ...MODEL,
356
+ blocks: [
357
+ {
358
+ type: 'paragraph',
359
+ inlines: [{ type: 'text', text: 'One' }],
360
+ sectionEnd: { running: true },
361
+ },
362
+ { type: 'paragraph', inlines: [{ type: 'text', text: 'Two' }] },
363
+ ],
364
+ finalColumns: { count: 2, gap: 420 },
365
+ })['word/document.xml'] as string;
366
+ expect(doc).toMatch(/<w:pgMar[^>]*\/><\/w:sectPr>.*One/);
367
+ expect(doc).toMatch(/Two.*<w:pgMar[^>]*\/><w:cols w:num="2" w:space="420"\/><\/w:sectPr>/);
368
+ expect(doc.match(/<w:cols /g)).toHaveLength(1);
369
+ });
370
+
371
+ it('stamps the watermark behind the text from every header', () => {
372
+ const parts = buildDocxParts({
373
+ ...MODEL,
374
+ blocks: [
375
+ {
376
+ type: 'paragraph',
377
+ inlines: [{ type: 'text', text: 'Cover' }],
378
+ sectionEnd: { running: false },
379
+ },
380
+ { type: 'paragraph', inlines: [{ type: 'text', text: 'Body' }] },
381
+ ],
382
+ images: [
383
+ ...MODEL.images,
384
+ {
385
+ name: 'watermark',
386
+ ext: 'png',
387
+ bytes: new Uint8Array([3]),
388
+ width: 7562850,
389
+ height: 10696575,
390
+ },
391
+ ],
392
+ watermark: 'watermark',
393
+ });
394
+ for (const header of ['word/header1.xml', 'word/header2.xml']) {
395
+ const xml = parts[header] as string;
396
+ expect(xml).toContain('behindDoc="1"');
397
+ expect(xml).toContain('<wp:positionH relativeFrom="page"><wp:posOffset>0</wp:posOffset>');
398
+ expect(xml).toContain('<wp:extent cx="7562850" cy="10696575"/>');
399
+ expect(parts[header.replace('word/', 'word/_rels/').concat('.rels')]).toContain(
400
+ 'Target="media/watermark.png"',
401
+ );
402
+ }
403
+ });
404
+
317
405
  it('gives each ordered list its own count', () => {
318
406
  const numbering = text('word/numbering.xml');
319
407
  expect(numbering).toContain('<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>');
@@ -66,12 +66,18 @@ export type Paragraph = {
66
66
  inlines: Inline[];
67
67
  list?: { numId: number; level: number };
68
68
  pageBreakBefore?: boolean;
69
+ /** Starts in the next column — where the printed page's next column began. */
70
+ columnBreakBefore?: boolean;
69
71
  keepNext?: boolean;
70
72
  /** Twips. */
71
73
  spacingBefore?: number;
72
74
  spacingAfter?: number;
73
75
  /** Left indent, twips, over the style's own. */
74
76
  indent?: number;
77
+ /** The first line starts this far left of `indent`, twips — a label hanging in the margin. */
78
+ hanging?: number;
79
+ /** Background behind the paragraph, `rrggbb` — a highlighted line of code. */
80
+ shade?: string;
75
81
  /** An exact line height, twips — a spacer that holds open a gap. */
76
82
  lineExact?: number;
77
83
  /**
@@ -80,7 +86,7 @@ export type Paragraph = {
80
86
  * Fixed sheets print their own running lines, so they sit in sections
81
87
  * without one.
82
88
  */
83
- sectionEnd?: { running: boolean };
89
+ sectionEnd?: SectionLayout;
84
90
  /** Right-aligned tab stop, twips from the left margin — a footer's page number. */
85
91
  rightTab?: number;
86
92
  /** Dots leading to the right tab, as a contents entry has. */
@@ -89,6 +95,18 @@ export type Paragraph = {
89
95
  bookmark?: string;
90
96
  };
91
97
 
98
+ /** What a section's pages carry: the running header and footer, and how many columns. */
99
+ export type SectionLayout = {
100
+ running: boolean;
101
+ /** Text columns and the gap between them, twips; absent means one. */
102
+ columns?: { count: number; gap: number };
103
+ /**
104
+ * Starts on the page the section before it ended on. Word balances the
105
+ * columns of a section only where a continuous break ends it.
106
+ */
107
+ continuous?: boolean;
108
+ };
109
+
92
110
  export type CellBorder = { color: string /** Eighths of a point. */; size: number };
93
111
 
94
112
  export type TableCell = {
@@ -166,6 +184,11 @@ export type DocxModel = {
166
184
  footer?: Paragraph;
167
185
  /** Whether the last section carries the header and footer. Defaults to true. */
168
186
  finalRunning?: boolean;
187
+ /** The last section's columns and start, as `SectionLayout`. */
188
+ finalColumns?: SectionLayout['columns'];
189
+ finalContinuous?: boolean;
190
+ /** A picture behind the text of every page, the size of the sheet — `meta.watermark`. */
191
+ watermark?: string;
169
192
  images: ImagePart[];
170
193
  /** One entry per list; ordered lists restart at 1 each. */
171
194
  lists: Array<'bullet' | 'decimal'>;
@@ -285,18 +308,38 @@ function fontTableXml(fonts: DocxModel['fonts']): string {
285
308
  );
286
309
  }
287
310
 
288
- /** `rgb(22, 24, 29)` or `#16181d` as `16181d`; null for anything transparent. */
311
+ /**
312
+ * `rgb(22, 24, 29)`, `#16181d` or `color(srgb 0.09 0.09 0.11)` as `16181d`;
313
+ * null for anything transparent. Word has no alpha, so a translucent colour is
314
+ * flattened onto white paper — the tint `color-mix(… transparent)` drew there.
315
+ */
289
316
  export function hexColor(css: string): string | null {
290
317
  const hex = css.trim().match(/^#([0-9a-f]{6})$/i);
291
318
  if (hex?.[1]) return hex[1].toLowerCase();
292
319
  const short = css.trim().match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
293
320
  if (short)
294
321
  return `${short[1]}${short[1]}${short[2]}${short[2]}${short[3]}${short[3]}`.toLowerCase();
295
- const rgb = css.match(/rgba?\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)(?:[\s,/]+([\d.]+))?/i);
296
- if (!rgb) return null;
297
- if (rgb[4] !== undefined && Number(rgb[4]) === 0) return null;
298
- return [rgb[1], rgb[2], rgb[3]]
299
- .map((channel) => Number(channel).toString(16).padStart(2, '0'))
322
+ const alphaOf = (value: string | undefined) =>
323
+ value === undefined ? 1 : value.endsWith('%') ? Number.parseFloat(value) / 100 : Number(value);
324
+ let channels: number[];
325
+ let alpha: number;
326
+ const srgb = css.match(
327
+ /color\(\s*srgb\s+([\d.e-]+)\s+([\d.e-]+)\s+([\d.e-]+)(?:\s*\/\s*([\d.]+%?))?\s*\)/i,
328
+ );
329
+ const rgb = css.match(/rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)(?:[\s,/]+([\d.]+%?))?/i);
330
+ if (srgb) {
331
+ channels = [srgb[1], srgb[2], srgb[3]].map((value) => Number(value) * 255);
332
+ alpha = alphaOf(srgb[4]);
333
+ } else if (rgb) {
334
+ channels = [rgb[1], rgb[2], rgb[3]].map(Number);
335
+ alpha = alphaOf(rgb[4]);
336
+ } else {
337
+ return null;
338
+ }
339
+ if (!(alpha > 0)) return null;
340
+ return channels
341
+ .map((channel) => Math.round(Math.min(255, Math.max(0, channel * alpha + 255 * (1 - alpha)))))
342
+ .map((channel) => channel.toString(16).padStart(2, '0'))
300
343
  .join('');
301
344
  }
302
345
 
@@ -311,8 +354,8 @@ type WriteContext = {
311
354
  imageIds: Map<string, string>;
312
355
  drawingId: { value: number };
313
356
  bookmarkId?: { value: number };
314
- /** A section's properties, with or without the running header and footer. */
315
- section?: (running: boolean) => string;
357
+ /** A section's properties: its running header and footer, and its columns. */
358
+ section?: (layout: SectionLayout) => string;
316
359
  };
317
360
 
318
361
  const REL_HYPERLINK =
@@ -376,6 +419,30 @@ function imageXml(name: string, ctx: WriteContext): string {
376
419
  );
377
420
  }
378
421
 
422
+ /** A picture pinned to the page's corner behind the text — how Word itself stores a watermark. */
423
+ function anchoredImageXml(name: string, ctx: WriteContext): string {
424
+ const image = ctx.model.images.find((candidate) => candidate.name === name);
425
+ if (!image) return '';
426
+ const rel = relFor(ctx, REL_IMAGE, `media/${image.name}.${image.ext}`);
427
+ const id = ctx.drawingId.value++;
428
+ const extent = `cx="${Math.round(image.width)}" cy="${Math.round(image.height)}"`;
429
+ return (
430
+ '<w:r><w:drawing>' +
431
+ '<wp:anchor distT="0" distB="0" distL="0" distR="0" simplePos="0" relativeHeight="0" behindDoc="1" locked="1" layoutInCell="1" allowOverlap="1">' +
432
+ '<wp:simplePos x="0" y="0"/>' +
433
+ '<wp:positionH relativeFrom="page"><wp:posOffset>0</wp:posOffset></wp:positionH>' +
434
+ '<wp:positionV relativeFrom="page"><wp:posOffset>0</wp:posOffset></wp:positionV>' +
435
+ `<wp:extent ${extent}/><wp:effectExtent l="0" t="0" r="0" b="0"/><wp:wrapNone/>` +
436
+ `<wp:docPr id="${id}" name="Watermark ${id}"/>` +
437
+ '<wp:cNvGraphicFramePr><a:graphicFrameLocks noChangeAspect="1"/></wp:cNvGraphicFramePr>' +
438
+ '<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
439
+ `<pic:pic><pic:nvPicPr><pic:cNvPr id="${id}" name="${escapeXml(image.name)}"/><pic:cNvPicPr/></pic:nvPicPr>` +
440
+ `<pic:blipFill><a:blip r:embed="${rel}"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill>` +
441
+ `<pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext ${extent}/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr>` +
442
+ '</pic:pic></a:graphicData></a:graphic></wp:anchor></w:drawing></w:r>'
443
+ );
444
+ }
445
+
379
446
  function runXml(run: Run, ctx: WriteContext, linked = false): string {
380
447
  switch (run.type) {
381
448
  case 'text': {
@@ -424,6 +491,8 @@ export function paragraphXml(paragraph: Paragraph, ctx: WriteContext): string {
424
491
  `<w:numPr><w:ilvl w:val="${paragraph.list.level}"/><w:numId w:val="${paragraph.list.numId}"/></w:numPr>`,
425
492
  );
426
493
  }
494
+ if (paragraph.shade)
495
+ props.push(`<w:shd w:val="clear" w:color="auto" w:fill="${paragraph.shade}"/>`);
427
496
  if (paragraph.rightTab !== undefined) {
428
497
  const leader = paragraph.leader ? ' w:leader="dot"' : '';
429
498
  props.push(
@@ -449,13 +518,17 @@ export function paragraphXml(paragraph: Paragraph, ctx: WriteContext): string {
449
518
  : '';
450
519
  props.push(`<w:spacing${before}${after}${line}/>`);
451
520
  }
452
- if (paragraph.indent !== undefined)
453
- props.push(`<w:ind w:left="${Math.round(paragraph.indent)}"/>`);
521
+ if (paragraph.indent !== undefined || paragraph.hanging !== undefined) {
522
+ const hanging = paragraph.hanging ? ` w:hanging="${Math.round(paragraph.hanging)}"` : '';
523
+ props.push(`<w:ind w:left="${Math.round(paragraph.indent ?? 0)}"${hanging}/>`);
524
+ }
454
525
  if (paragraph.align && paragraph.align !== 'left')
455
526
  props.push(`<w:jc w:val="${paragraph.align}"/>`);
456
- if (paragraph.sectionEnd && ctx.section) props.push(ctx.section(paragraph.sectionEnd.running));
527
+ if (paragraph.sectionEnd && ctx.section) props.push(ctx.section(paragraph.sectionEnd));
457
528
  const pPr = props.length > 0 ? `<w:pPr>${props.join('')}</w:pPr>` : '';
458
- const runs = paragraph.inlines.map((inline) => inlineXml(inline, ctx)).join('');
529
+ const runs =
530
+ (paragraph.columnBreakBefore ? '<w:r><w:br w:type="column"/></w:r>' : '') +
531
+ paragraph.inlines.map((inline) => inlineXml(inline, ctx)).join('');
459
532
  if (!paragraph.bookmark) return `<w:p>${pPr}${runs}</w:p>`;
460
533
  ctx.bookmarkId ??= { value: 0 };
461
534
  const id = ctx.bookmarkId.value++;
@@ -660,7 +733,9 @@ export function buildDocxParts(model: DocxModel): Record<string, string | Uint8A
660
733
  model.finalRunning === false ||
661
734
  model.blocks.some((block) => block.type === 'paragraph' && block.sectionEnd?.running === false);
662
735
  const running = (kind: 'header' | 'footer') => {
663
- if (!model[kind]) return { full: null, bare: null };
736
+ // The watermark is drawn from the header, so a document with one needs a
737
+ // header even when it has no running line to put there.
738
+ if (!model[kind] && !(kind === 'header' && model.watermark)) return { full: null, bare: null };
664
739
  return {
665
740
  full: relFor(docCtx, `${REL_BASE}/${kind}`, `${kind}1.xml`),
666
741
  bare: bare ? relFor(docCtx, `${REL_BASE}/${kind}`, `${kind}2.xml`) : null,
@@ -671,20 +746,30 @@ export function buildDocxParts(model: DocxModel): Record<string, string | Uint8A
671
746
 
672
747
  const { page } = model;
673
748
  const margin = Math.round(page.margin);
674
- docCtx.section = (on) => {
749
+ docCtx.section = ({ running: on, columns, continuous }) => {
675
750
  const header = on ? headerRels.full : headerRels.bare;
676
751
  const footer = on ? footerRels.full : footerRels.bare;
752
+ const cols =
753
+ columns && columns.count > 1
754
+ ? `<w:cols w:num="${columns.count}" w:space="${Math.round(columns.gap)}"/>`
755
+ : '';
677
756
  return (
678
757
  '<w:sectPr>' +
679
758
  (header ? `<w:headerReference w:type="default" r:id="${header}"/>` : '') +
680
759
  (footer ? `<w:footerReference w:type="default" r:id="${footer}"/>` : '') +
760
+ (continuous ? '<w:type w:val="continuous"/>' : '') +
681
761
  `<w:pgSz w:w="${Math.round(page.width)}" w:h="${Math.round(page.height)}"${page.landscape ? ' w:orient="landscape"' : ''}/>` +
682
762
  `<w:pgMar w:top="${margin}" w:right="${margin}" w:bottom="${margin}" w:left="${margin}" w:header="${Math.round(margin / 2)}" w:footer="${Math.round(margin / 2)}" w:gutter="0"/>` +
763
+ cols +
683
764
  '</w:sectPr>'
684
765
  );
685
766
  };
686
767
  const body = model.blocks.map((block) => blockXml(block, docCtx)).join('');
687
- const sectPr = docCtx.section(model.finalRunning !== false);
768
+ const sectPr = docCtx.section({
769
+ running: model.finalRunning !== false,
770
+ ...(model.finalColumns ? { columns: model.finalColumns } : {}),
771
+ ...(model.finalContinuous ? { continuous: true } : {}),
772
+ });
688
773
  const documentXml = `${XML_HEAD}<w:document ${NS}><w:body>${body}${sectPr}</w:body></w:document>`;
689
774
 
690
775
  // Footnotes and the footer are parts of their own, with their own rels.
@@ -721,17 +806,23 @@ export function buildDocxParts(model: DocxModel): Record<string, string | Uint8A
721
806
  ['header', headerRels, 'hdr', 'Header'],
722
807
  ['footer', footerRels, 'ftr', 'Footer'],
723
808
  ] as const) {
724
- const line = model[kind];
725
- if (!line || !rels.full) continue;
726
- const ctx: WriteContext = { model, rels: [], imageIds: new Map(), drawingId };
727
- runningParts[`word/${kind}1.xml`] =
728
- `${XML_HEAD}<w:${tag} ${NS}>${paragraphXml({ ...line, style: line.style ?? (style as StyleId) }, ctx)}</w:${tag}>`;
729
- if (ctx.rels.length > 0) runningParts[`word/_rels/${kind}1.xml.rels`] = relsXml(ctx.rels);
730
- runningTypes.push(`/word/${kind}1.xml|${kind}`);
731
- if (rels.bare) {
732
- runningParts[`word/${kind}2.xml`] = `${XML_HEAD}<w:${tag} ${NS}><w:p/></w:${tag}>`;
733
- runningTypes.push(`/word/${kind}2.xml|${kind}`);
734
- }
809
+ if (!rels.full) continue;
810
+ const line: Paragraph = model[kind] ?? { type: 'paragraph', inlines: [] };
811
+ const stamp = kind === 'header' ? model.watermark : undefined;
812
+ const part = (name: string, paragraph: Paragraph) => {
813
+ const ctx: WriteContext = { model, rels: [], imageIds: new Map(), drawingId };
814
+ // The watermark rides in the header's own paragraph, anchored to the
815
+ // page behind the text, so it adds no height to the header.
816
+ const xml = paragraphXml(
817
+ { ...paragraph, style: paragraph.style ?? (style as StyleId) },
818
+ ctx,
819
+ ).replace(/<\/w:p>$/, `${stamp ? anchoredImageXml(stamp, ctx) : ''}</w:p>`);
820
+ runningParts[`word/${name}.xml`] = `${XML_HEAD}<w:${tag} ${NS}>${xml}</w:${tag}>`;
821
+ if (ctx.rels.length > 0) runningParts[`word/_rels/${name}.xml.rels`] = relsXml(ctx.rels);
822
+ runningTypes.push(`/word/${name}.xml|${kind}`);
823
+ };
824
+ part(`${kind}1`, line);
825
+ if (rels.bare) part(`${kind}2`, { type: 'paragraph', inlines: [] });
735
826
  }
736
827
 
737
828
  const settingsXml =
@@ -19,11 +19,13 @@ import {
19
19
  hexColor,
20
20
  type Inline,
21
21
  type Paragraph,
22
+ PX_TO_EMU,
22
23
  PX_TO_HALF_POINTS,
23
24
  PX_TO_TWIPS,
24
25
  type StyleId,
25
26
  } from './docx/ooxml';
26
27
  import { downloadBlob, withRenderedPages } from './export-dom';
28
+ import { elementToPng } from './export-image';
27
29
  import { type DocEntry, type FlowSection, isFlowSection } from './flow';
28
30
  import { DocPageProvider } from './page-context';
29
31
  import { nextFrame, waitForFonts } from './print-ready';
@@ -170,8 +172,34 @@ export async function buildDocDocx(
170
172
  margin: design.margin,
171
173
  };
172
174
 
173
- const content = await withRenderedPages(pages, geometry, doc, (hosts, container) =>
174
- docxFromPages(hosts, pageInfo(pages), container, walk),
175
+ let watermark: string | undefined;
176
+ const content = await withRenderedPages(
177
+ pages,
178
+ geometry,
179
+ doc,
180
+ async (hosts, container) => {
181
+ const result = await docxFromPages(hosts, pageInfo(pages), container, walk);
182
+ // Word has no stamp across the sheet, so the one the page drew is a
183
+ // picture behind the text, set in the header so every page carries it.
184
+ const mark = container.querySelector('[data-od-watermark]');
185
+ if (mark) {
186
+ try {
187
+ const { bytes } = await elementToPng(mark, doc);
188
+ watermark = 'watermark';
189
+ result.images.push({
190
+ name: watermark,
191
+ ext: 'png',
192
+ bytes,
193
+ width: geometry.width * PX_TO_EMU,
194
+ height: geometry.height * PX_TO_EMU,
195
+ });
196
+ } catch {
197
+ /* A document without its watermark is still the document. */
198
+ }
199
+ }
200
+ return result;
201
+ },
202
+ { includeWatermark: Boolean(doc.meta?.watermark) },
175
203
  );
176
204
  const header = await runningLineOf('header', doc, design, textWidth, walk);
177
205
  const footer = await runningLineOf('footer', doc, design, textWidth, walk);
@@ -210,6 +238,7 @@ export async function buildDocDocx(
210
238
  ...content,
211
239
  ...(header ? { header } : {}),
212
240
  ...(footer ? { footer } : {}),
241
+ ...(watermark ? { watermark } : {}),
213
242
  };
214
243
 
215
244
  const parts = buildDocxParts(model);
@@ -10,7 +10,7 @@ import { SheetWatermark } from '../components/page-frame';
10
10
  import { designToCssVars } from './design';
11
11
  import { PAGE_ATTR, PAGE_INDEX_ATTR } from './outline';
12
12
  import { DocPageProvider } from './page-context';
13
- import { nextFrame, waitForFonts, waitForImages } from './print-ready';
13
+ import { nextFrame, sleep, waitForFonts, waitForImages } from './print-ready';
14
14
  import { captureScan, restoreScan, scanDocument } from './scan';
15
15
  import { type DocModule, type PageGeometry, pageLang } from './sdk';
16
16
  import { scopeSvgIds } from './svg-ids';
@@ -57,6 +57,11 @@ export async function withRenderedPages<T>(
57
57
  host.setAttribute('lang', pageLang(doc.meta));
58
58
  host.style.width = `${geometry.width}px`;
59
59
  host.style.height = `${geometry.height}px`;
60
+ // As the sheet in the viewer is: what a page places absolutely — the
61
+ // watermark, a fixed page's footer — is placed on that page, not on the
62
+ // column of every page stacked in the container.
63
+ host.style.position = 'relative';
64
+ host.style.overflow = 'hidden';
60
65
  if (designVars) {
61
66
  for (const [k, v] of Object.entries(designVars)) host.style.setProperty(k, v);
62
67
  }
@@ -80,7 +85,11 @@ export async function withRenderedPages<T>(
80
85
  await waitForFonts();
81
86
  await waitForImages(container);
82
87
  scanDocument(container, doc.meta);
88
+ // As the print copy waits: a busy machine can let two frames pass before
89
+ // React has drawn the numbers the scan resolved, and a reference read then
90
+ // is still unresolved.
83
91
  await nextFrame();
92
+ await sleep(50);
84
93
  await nextFrame();
85
94
  hosts.forEach((host, i) => {
86
95
  scopeSvgIds(host, `export-${i}`);