@open-document/core 0.13.1 → 0.13.3

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.3",
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,9 @@ export type WalkResult = {
59
61
  images: ImagePart[];
60
62
  lists: Array<'bullet' | 'decimal'>;
61
63
  finalRunning: boolean;
64
+ finalColumns?: SectionLayout['columns'];
65
+ finalContinuous?: boolean;
66
+ finalFoot?: Paragraph;
62
67
  };
63
68
 
64
69
  type Ctx = WalkOptions & {
@@ -112,14 +117,20 @@ const INLINE_DISPLAYS = new Set([
112
117
  const STRUCTURE = 'p,h1,h2,h3,h4,h5,h6,table,ul,ol,pre,blockquote';
113
118
 
114
119
  /** Where each block sat on its sheet, for fixed pages whose layout is by position. */
115
- const placed = new WeakMap<Block, { top: number; bottom: number }>();
120
+ type Box = { top: number; bottom: number; left: number; right: number };
116
121
 
117
- function place(block: Block, box: { top: number; bottom: number }) {
118
- if (!placed.has(block)) placed.set(block, { top: box.top, bottom: box.bottom });
122
+ const placed = new WeakMap<Block, Box>();
123
+
124
+ function place(block: Block, box: Box) {
125
+ if (!placed.has(block)) {
126
+ placed.set(block, { top: box.top, bottom: box.bottom, left: box.left, right: box.right });
127
+ }
119
128
  }
120
129
 
121
130
  function isHidden(el: Element): boolean {
122
- if (el.getAttribute('aria-hidden') === 'true') return true;
131
+ // A drawing is hidden from a screen reader because it says nothing in words —
132
+ // a sparkline — not because it is off the page.
133
+ if (el.getAttribute('aria-hidden') === 'true' && !(el instanceof SVGSVGElement)) return true;
123
134
  const style = getComputedStyle(el);
124
135
  return style.display === 'none' || style.visibility === 'hidden';
125
136
  }
@@ -297,12 +308,32 @@ async function inlinesOf(
297
308
  );
298
309
  out.push({ type: 'link', href: node.getAttribute('href') as string, runs });
299
310
  } else {
300
- out.push(...(await inlinesOf(Array.from(node.childNodes), base, ctx, linked)));
311
+ const inner = await inlinesOf(Array.from(node.childNodes), base, ctx, linked);
312
+ out.push(...shaded(node, inner));
301
313
  }
302
314
  }
303
315
  return out;
304
316
  }
305
317
 
318
+ /**
319
+ * Words set on a tint of their own — a pill, a badge — keep it as a character
320
+ * background, and a pill's side padding as a space on either side.
321
+ */
322
+ function shaded(el: Element, inlines: Inline[]): Inline[] {
323
+ const style = getComputedStyle(el);
324
+ if (!INLINE_DISPLAYS.has(style.display) || style.display === 'contents') return inlines;
325
+ const shade = hexColor(style.backgroundColor);
326
+ if (!shade) return inlines;
327
+ const tinted = inlines.map(
328
+ (inline): Inline =>
329
+ inline.type === 'text' ? { ...inline, shade: inline.shade ?? shade } : inline,
330
+ );
331
+ const first = tinted.find((inline): inline is TextRun => inline.type === 'text');
332
+ if (!first || (Number.parseFloat(style.paddingLeft) || 0) < 4) return tinted;
333
+ const pad: TextRun = { ...first, text: '\u00a0' };
334
+ return [pad, ...tinted, { ...pad }];
335
+ }
336
+
306
337
  /** Trims the whitespace a browser would not draw: at either end, and doubled between runs. */
307
338
  function tidy(inlines: Inline[]): Inline[] {
308
339
  const texts: TextRun[] = [];
@@ -480,8 +511,11 @@ async function blockOfElement(el: Element, ctx: Ctx, out: Block[], style: StyleI
480
511
  return;
481
512
  }
482
513
  if (tag === 'PRE') {
483
- const paragraph = await paragraphOf(Array.from(el.childNodes), 'Code', el, ctx);
484
- if (paragraph) out.push(...boxed([paragraph], el));
514
+ out.push(...boxed(await codeLines(el, ctx), el));
515
+ return;
516
+ }
517
+ if (el.hasAttribute(PANEL_ATTR)) {
518
+ out.push(...(await panelOf(el, ctx, style)));
485
519
  return;
486
520
  }
487
521
  if (tag === 'FIGURE') {
@@ -501,6 +535,11 @@ async function blockOfElement(el: Element, ctx: Ctx, out: Block[], style: StyleI
501
535
  out.push(...(paragraphs.length === inner.length ? boxed(paragraphs, el) : inner));
502
536
  return;
503
537
  }
538
+ const row = await sideBySideOf(el, ctx, style);
539
+ if (row) {
540
+ out.push(row);
541
+ return;
542
+ }
504
543
  if (isTabbedRow(el, ctx)) {
505
544
  const pieces = Array.from(el.children).filter((child) => !skip(child, ctx));
506
545
  const inlines: Inline[] = [];
@@ -509,10 +548,20 @@ async function blockOfElement(el: Element, ctx: Ctx, out: Block[], style: StyleI
509
548
  inlines.push(...tidy(await inlinesOf([piece], ctx.baselines[style], ctx)));
510
549
  }
511
550
  if (inlines.some((inline) => inline.type !== 'tab')) {
551
+ const look = getComputedStyle(el);
552
+ const rule = border(look, 'Top');
512
553
  out.push({
513
554
  type: 'paragraph',
514
555
  inlines,
515
556
  rightTab: ctx.textWidth * PX_TO_TWIPS,
557
+ ...(rule
558
+ ? {
559
+ ruleAbove: {
560
+ ...rule,
561
+ gap: (Number.parseFloat(look.paddingTop) || 0) * PX_TO_TWIPS,
562
+ },
563
+ }
564
+ : {}),
516
565
  ...spacing(el),
517
566
  ...(style !== 'Normal' ? { style } : {}),
518
567
  });
@@ -527,6 +576,147 @@ async function blockOfElement(el: Element, ctx: Ctx, out: Block[], style: StyleI
527
576
  await blocksOf(el, ctx, out, style);
528
577
  }
529
578
 
579
+ /**
580
+ * A `<pre>` whose lines are elements of their own — a highlighted code block —
581
+ * has no newlines in its text for Word to break at, so each line is a
582
+ * paragraph, and a highlighted one keeps its tint.
583
+ */
584
+ async function codeLines(pre: Element, ctx: Ctx): Promise<Paragraph[]> {
585
+ const lines = Array.from(pre.children).filter((child) => !skip(child, ctx) && isBlock(child));
586
+ if (lines.length === 0) {
587
+ const paragraph = await paragraphOf(Array.from(pre.childNodes), 'Code', pre, ctx);
588
+ return paragraph ? [paragraph] : [];
589
+ }
590
+ const out: Paragraph[] = [];
591
+ for (const line of lines) {
592
+ const paragraph = (await paragraphOf(Array.from(line.childNodes), 'Code', line, ctx)) ?? {
593
+ type: 'paragraph',
594
+ style: 'Code',
595
+ inlines: [],
596
+ };
597
+ const shade = hexColor(getComputedStyle(line).backgroundColor);
598
+ out.push({ ...paragraph, spacingBefore: 0, spacingAfter: 0, ...(shade ? { shade } : {}) });
599
+ }
600
+ return out;
601
+ }
602
+
603
+ /**
604
+ * A framed component — a code block with its title bar — as a one-column
605
+ * table, one row per part, so each part keeps its own tint and inset inside
606
+ * the frame the way it printed.
607
+ */
608
+ async function panelOf(el: Element, ctx: Ctx, style: StyleId): Promise<Block[]> {
609
+ const frame = getComputedStyle(el);
610
+ const fill = hexColor(frame.backgroundColor) ?? undefined;
611
+ const parts = Array.from(el.children).filter((child) => !skip(child, ctx));
612
+ const width = el.getBoundingClientRect().width * PX_TO_TWIPS;
613
+ const drawn: Array<{ part: Element; blocks: Block[] }> = [];
614
+ for (const part of parts) {
615
+ const blocks: Block[] = [];
616
+ await blockOf(part, ctx, blocks, style);
617
+ drawn.push({ part, blocks });
618
+ }
619
+ const all = drawn.flatMap((entry) => entry.blocks);
620
+ if (all.length === 0) return [];
621
+ if (all.some((block) => block.type !== 'paragraph')) return all;
622
+
623
+ let inset = 0;
624
+ const rows: Table['rows'] = drawn.map(({ part, blocks }, at) => {
625
+ const look = getComputedStyle(part);
626
+ // A <pre> carries its inset on itself; a title bar carries its own.
627
+ const padding = getComputedStyle(part.querySelector('pre') ?? part);
628
+ const pad = (side: string) =>
629
+ (Number.parseFloat(padding.getPropertyValue(`padding-${side}`)) || 0) * PX_TO_TWIPS;
630
+ inset = Math.max(inset, pad('left'));
631
+ const borders: NonNullable<TableCell['borders']> = {};
632
+ for (const side of ['Left', 'Right'] as const) {
633
+ const rule = border(frame, side);
634
+ if (rule) borders[side.toLowerCase() as 'left'] = rule;
635
+ }
636
+ const top = at === 0 ? border(frame, 'Top') : undefined;
637
+ if (top) borders.top = top;
638
+ const bottom = at === drawn.length - 1 ? border(frame, 'Bottom') : border(look, 'Bottom');
639
+ if (bottom) borders.bottom = bottom;
640
+ const tint = hexColor(look.backgroundColor) ?? fill;
641
+ const paragraphs = blocks as Paragraph[];
642
+ return {
643
+ header: false,
644
+ cells: [
645
+ {
646
+ blocks: paragraphs.map((paragraph, index) => ({
647
+ ...paragraph,
648
+ ...(index === 0 ? { spacingBefore: 0 } : {}),
649
+ ...(index === paragraphs.length - 1 ? { spacingAfter: 0 } : {}),
650
+ // A tab to the right edge of the page would land outside the frame.
651
+ ...(paragraph.rightTab !== undefined ? { rightTab: width - pad('left') * 2 } : {}),
652
+ })),
653
+ borders,
654
+ ...(tint ? { fill: tint } : {}),
655
+ padding: {
656
+ top: pad('top'),
657
+ left: pad('left'),
658
+ bottom: pad('bottom'),
659
+ right: pad('right'),
660
+ },
661
+ },
662
+ ],
663
+ };
664
+ });
665
+ const table: Table = {
666
+ type: 'table',
667
+ columns: [width],
668
+ rows,
669
+ cellMargin: { left: inset, right: inset },
670
+ };
671
+ // A table has no space after of its own; the frame's margin is a spacer.
672
+ const { spacingAfter = 0 } = spacing(el);
673
+ if (spacingAfter <= 0) return [table];
674
+ return [
675
+ table,
676
+ { type: 'paragraph', inlines: [], spacingBefore: 0, spacingAfter: 0, lineExact: spacingAfter },
677
+ ];
678
+ }
679
+
680
+ /**
681
+ * Framed boxes laid side by side — two callouts in a grid — as one row of a
682
+ * table, each box a cell and the gap an empty one, rather than a stack of
683
+ * boxes each as narrow as its column was.
684
+ */
685
+ async function sideBySideOf(el: Element, ctx: Ctx, style: StyleId): Promise<Table | null> {
686
+ const display = getComputedStyle(el).display;
687
+ if (!display.includes('grid') && !display.includes('flex')) return null;
688
+ const boxes = Array.from(el.children).filter((child) => !skip(child, ctx));
689
+ if (boxes.length < 2) return null;
690
+ // Decided before walking, so a row that turns out not to qualify has not
691
+ // already drawn its pictures and numbered its notes once.
692
+ const framed = (box: Element) =>
693
+ box.tagName === 'BLOCKQUOTE' || box.tagName === 'PRE' || box.hasAttribute(PANEL_ATTR);
694
+ if (!boxes.every(framed)) return null;
695
+ const rects = boxes.map((box) => box.getBoundingClientRect());
696
+ const top = rects[0]?.top ?? 0;
697
+ if (rects.some((rect) => Math.abs(rect.top - top) > 2)) return null;
698
+ const cells: TableCell[] = [];
699
+ const columns: number[] = [];
700
+ for (const [at, box] of boxes.entries()) {
701
+ const drawn: Block[] = [];
702
+ await blockOf(box, ctx, drawn, style);
703
+ const table = drawn[0];
704
+ const cell =
705
+ table?.type === 'table' && table.rows.length === 1 ? table.rows[0]?.cells[0] : null;
706
+ if (drawn.length !== 1 || !cell || table?.type !== 'table' || table.columns.length !== 1) {
707
+ return null;
708
+ }
709
+ if (at > 0) {
710
+ const gap = (rects[at]?.left ?? 0) - (rects[at - 1]?.right ?? 0);
711
+ columns.push(Math.max(0, gap) * PX_TO_TWIPS);
712
+ cells.push({ blocks: [], padding: { top: 0, left: 0, bottom: 0, right: 0 } });
713
+ }
714
+ columns.push((rects[at]?.width ?? 0) * PX_TO_TWIPS);
715
+ cells.push(cell);
716
+ }
717
+ return { type: 'table', columns, rows: [{ header: false, cells }] };
718
+ }
719
+
530
720
  function tocOf(el: Element, ctx: Ctx): Block {
531
721
  const entries = Array.from(el.querySelectorAll('[data-od-toc-entry]')).map((row) => {
532
722
  const id = row.getAttribute('data-od-toc-entry') ?? '';
@@ -538,7 +728,41 @@ function tocOf(el: Element, ctx: Ctx): Block {
538
728
  return { type: 'toc', entries };
539
729
  }
540
730
 
731
+ /**
732
+ * An item of a list drawn without markers — a bibliography whose `[1]` is its
733
+ * own element. Word would number it a second time, so it is a plain paragraph,
734
+ * its label hanging to the left of the text as it sat beside it on the page.
735
+ */
736
+ async function looseItemOf(item: Element, ctx: Ctx): Promise<Paragraph | null> {
737
+ const pieces = Array.from(item.children).filter((piece) => !skip(piece, ctx));
738
+ const label = pieces[0];
739
+ const text = pieces[1];
740
+ if (!getComputedStyle(item).display.includes('flex') || !label || !text) {
741
+ return paragraphOf(Array.from(item.childNodes), 'Normal', item, ctx);
742
+ }
743
+ const hang = Math.max(
744
+ 0,
745
+ (text.getBoundingClientRect().left - item.getBoundingClientRect().left) * PX_TO_TWIPS,
746
+ );
747
+ const inlines: Inline[] = [...tidy(await inlinesOf([label], ctx.baselines.Normal, ctx))];
748
+ inlines.push({ type: 'tab' });
749
+ for (const [at, piece] of pieces.slice(1).entries()) {
750
+ if (at > 0) inlines.push({ type: 'text', text: ' ' });
751
+ inlines.push(...tidy(await inlinesOf([piece], ctx.baselines.Normal, ctx)));
752
+ }
753
+ return { type: 'paragraph', inlines, ...spacing(item), indent: hang, hanging: hang };
754
+ }
755
+
541
756
  async function listOf(el: Element, ctx: Ctx, out: Block[], level: number) {
757
+ const first = Array.from(el.children).find((item) => item.tagName === 'LI');
758
+ if (first && getComputedStyle(first).listStyleType === 'none') {
759
+ for (const item of Array.from(el.children)) {
760
+ if (item.tagName !== 'LI' || skip(item, ctx)) continue;
761
+ const paragraph = await looseItemOf(item, ctx);
762
+ if (paragraph) out.push(paragraph);
763
+ }
764
+ return;
765
+ }
542
766
  ctx.lists.push(el.tagName === 'OL' ? 'decimal' : 'bullet');
543
767
  const numId = ctx.lists.length;
544
768
  for (const item of Array.from(el.children)) {
@@ -640,10 +864,15 @@ async function tableOf(table: HTMLTableElement, ctx: Ctx): Promise<Table> {
640
864
  const edge = border(style, side);
641
865
  if (edge) borders[side.toLowerCase() as 'top'] = edge;
642
866
  }
867
+ const fill =
868
+ dataBarFill(style) ??
869
+ hexColor(style.backgroundColor) ??
870
+ hexColor(getComputedStyle(row).backgroundColor);
643
871
  cells.push({
644
872
  blocks: paragraphs,
645
873
  ...(cell.colSpan > 1 ? { span: cell.colSpan } : {}),
646
874
  borders,
875
+ ...(fill ? { fill } : {}),
647
876
  padding: {
648
877
  top: (Number.parseFloat(style.paddingTop) || 0) * PX_TO_TWIPS,
649
878
  left: (Number.parseFloat(style.paddingLeft) || 0) * PX_TO_TWIPS,
@@ -657,6 +886,31 @@ async function tableOf(table: HTMLTableElement, ctx: Ctx): Promise<Table> {
657
886
  return out;
658
887
  }
659
888
 
889
+ /**
890
+ * A cell drawn with a bar behind its value — `linear-gradient(to right, tint
891
+ * n%, transparent n%)`, a data bar. Neither Word nor Pages can fill part of a
892
+ * cell, and Pages drops a picture pinned inside one, so the value is told by
893
+ * how deep the cell's tint is instead of how far it reaches.
894
+ */
895
+ function dataBarFill(style: CSSStyleDeclaration): string | null {
896
+ const gradient = style.backgroundImage.match(
897
+ /^linear-gradient\(to right,\s*((?:rgba?|color)\([^)]*\))\s+([\d.]+)%/,
898
+ );
899
+ if (!gradient?.[1] || !gradient[2]) return null;
900
+ const tint = hexColor(gradient[1]);
901
+ const ratio = Math.min(1, Number(gradient[2]) / 100);
902
+ if (!tint || !(ratio > 0)) return null;
903
+ const depth = 0.25 + 0.75 * ratio;
904
+ return [0, 2, 4]
905
+ .map((at) => {
906
+ const channel = Number.parseInt(tint.slice(at, at + 2), 16);
907
+ return Math.round(255 - (255 - channel) * depth)
908
+ .toString(16)
909
+ .padStart(2, '0');
910
+ })
911
+ .join('');
912
+ }
913
+
660
914
  async function figureOf(figure: Element, ctx: Ctx, out: Block[]) {
661
915
  const start = out.length;
662
916
  await figureParts(figure, ctx, out);
@@ -715,6 +969,25 @@ async function figureParts(figure: Element, ctx: Ctx, out: Block[]) {
715
969
  // Pages
716
970
  // ---------------------------------------------------------------------------
717
971
 
972
+ /** The multi-column box a flow page's blocks sit in, if they sit in one. */
973
+ function columnBoxOf(host: HTMLElement): { el: Element; count: number; gap: number } | null {
974
+ const block = host.querySelector(`[${FLOW_BLOCK_ATTR}]`);
975
+ for (let el = block?.parentElement; el && el !== host; el = el.parentElement) {
976
+ const style = getComputedStyle(el);
977
+ const count = Number.parseInt(style.columnCount, 10);
978
+ if (count > 1) return { el, count, gap: Number.parseFloat(style.columnGap) || 0 };
979
+ }
980
+ return null;
981
+ }
982
+
983
+ /** Which column of the box a block starts in, from where it was drawn. */
984
+ function columnIndexOf(block: Element, box: { el: Element; count: number; gap: number }): number {
985
+ const frame = box.el.getBoundingClientRect();
986
+ const width = (frame.width - box.gap * (box.count - 1)) / box.count;
987
+ const left = block.getBoundingClientRect().left - frame.left;
988
+ return Math.max(0, Math.min(box.count - 1, Math.floor((left + 1) / (width + box.gap))));
989
+ }
990
+
718
991
  /**
719
992
  * The document in reading order. A fixed page is its own sheet in Word too, so
720
993
  * it starts on a new page; a flow section's later pages continue it, and Word
@@ -735,7 +1008,7 @@ export async function docxFromPages(
735
1008
  page: { top: 0, bottom: 0, fixed: true, first: true },
736
1009
  };
737
1010
  const blocks: Block[] = [];
738
- let previousRunning = true;
1011
+ let previous: SectionLayout = { running: true };
739
1012
 
740
1013
  for (const [index, host] of hosts.entries()) {
741
1014
  const info = pages[index] ?? { continues: false };
@@ -747,9 +1020,41 @@ export async function docxFromPages(
747
1020
  first: index === 0,
748
1021
  };
749
1022
  const own: Block[] = [];
1023
+ let foot: Paragraph | undefined;
750
1024
  const flowBlocks = Array.from(host.querySelectorAll(`[${FLOW_BLOCK_ATTR}]`));
1025
+ const columnsHere = flowBlocks.length > 0 ? columnBoxOf(host) : null;
751
1026
  if (flowBlocks.length > 0) {
752
- for (const block of flowBlocks) await blockOf(block, ctx, own, 'Normal');
1027
+ // A later page of a section in columns starts after a break as well: from
1028
+ // the last column of the page before, Word's next column is this page's first.
1029
+ let column = columnsHere && info.continues ? -1 : 0;
1030
+ for (const block of flowBlocks) {
1031
+ const start = own.length;
1032
+ await blockOf(block, ctx, own, 'Normal');
1033
+ // Word fills a column to the foot of the page before it starts the
1034
+ // next, and Pages never balances them; a break where the printed
1035
+ // page's next column began sets the columns as they printed.
1036
+ const at = columnsHere ? columnIndexOf(block, columnsHere) : 0;
1037
+ if (at > column && own.length > start) {
1038
+ const first = own[start];
1039
+ if (first?.type === 'paragraph' && at === column + 1) {
1040
+ first.columnBreakBefore = true;
1041
+ } else {
1042
+ const breaks = Array.from(
1043
+ { length: at - column },
1044
+ (): Paragraph => ({
1045
+ type: 'paragraph',
1046
+ inlines: [],
1047
+ columnBreakBefore: true,
1048
+ spacingBefore: 0,
1049
+ spacingAfter: 0,
1050
+ lineExact: 20,
1051
+ }),
1052
+ );
1053
+ own.splice(start, 0, ...breaks);
1054
+ }
1055
+ column = at;
1056
+ }
1057
+ }
753
1058
  } else {
754
1059
  await blocksOf(host, ctx, own);
755
1060
  }
@@ -762,10 +1067,26 @@ export async function docxFromPages(
762
1067
  if (ctx.page.fixed) {
763
1068
  let bottom = rect.top + options.margin;
764
1069
  let previous: Paragraph | null = null;
1070
+ // Blocks that sat side by side on the sheet — a contents list beside a
1071
+ // list of figures — are stacked in Word, and the height that adds comes
1072
+ // out of the gaps below them, or the sheet's foot spills onto a page of
1073
+ // its own.
1074
+ let stacked = 0;
1075
+ // Every paragraph of a list is placed at the list's box; one box is one block of height.
1076
+ const counted = new Set<string>();
765
1077
  for (const block of own) {
766
1078
  const box = placed.get(block);
767
1079
  if (!box) continue;
768
- const gap = Math.max(0, box.top - bottom);
1080
+ const key = `${box.top}:${box.bottom}`;
1081
+ const repeat = counted.has(key);
1082
+ counted.add(key);
1083
+ if (!repeat && box.top < bottom) {
1084
+ stacked += box.bottom - box.top - Math.max(0, box.bottom - bottom);
1085
+ }
1086
+ let gap = Math.max(0, box.top - bottom);
1087
+ const taken = Math.min(gap, stacked);
1088
+ gap -= taken;
1089
+ stacked -= taken;
769
1090
  if (block.type === 'paragraph') {
770
1091
  block.spacingBefore = gap * PX_TO_TWIPS;
771
1092
  if (previous) previous.spacingAfter = 0;
@@ -775,6 +1096,22 @@ export async function docxFromPages(
775
1096
  }
776
1097
  bottom = Math.max(bottom, box.bottom);
777
1098
  }
1099
+ // A last line laid out against the foot of the sheet — a cover's byline,
1100
+ // pushed down by `justify-content: space-between` — becomes this page's
1101
+ // footer: as flowed text its place would depend on how tall everything
1102
+ // above it came out in Word, which is never quite what the page drew.
1103
+ const last = own[own.length - 1];
1104
+ const lastBox = last ? placed.get(last) : undefined;
1105
+ if (
1106
+ last?.type === 'paragraph' &&
1107
+ lastBox &&
1108
+ own.length > 1 &&
1109
+ rect.bottom - options.margin - lastBox.bottom < 24 &&
1110
+ (last.spacingBefore ?? 0) > 48 * PX_TO_TWIPS
1111
+ ) {
1112
+ own.pop();
1113
+ foot = { ...last, spacingBefore: 0, spacingAfter: 0 };
1114
+ }
778
1115
  // Word sets a heading's line from the font's own height, taller than the
779
1116
  // page's CSS line-height, so a sheet laid out to its last pixel — a
780
1117
  // cover's byline at the foot — would spill its last lines onto a page of
@@ -794,14 +1131,30 @@ export async function docxFromPages(
794
1131
  }
795
1132
  }
796
1133
  // 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;
1134
+ // prints its own running lines, so it sits in a section without them. A
1135
+ // flow set in columns is a section of that many columns. The section
1136
+ // break itself starts the next page.
1137
+ const layout: SectionLayout = { running: !ctx.page.fixed, ...(foot ? { foot } : {}) };
1138
+ if (!ctx.page.fixed && columnsHere) {
1139
+ layout.columns = { count: columnsHere.count, gap: columnsHere.gap * PX_TO_TWIPS };
1140
+ }
1141
+ const breaksSection =
1142
+ own.length > 0 &&
1143
+ blocks.length > 0 &&
1144
+ (layout.running !== previous.running ||
1145
+ (layout.columns?.count ?? 1) !== (previous.columns?.count ?? 1) ||
1146
+ Boolean(layout.foot) ||
1147
+ Boolean(previous.foot));
1148
+ // Columns fill one at a time to the foot of the page unless a continuous
1149
+ // break ends them, so the section after a set of columns starts on their
1150
+ // page and breaks to its own with the first paragraph instead.
1151
+ const afterColumns =
1152
+ breaksSection && (previous.columns?.count ?? 1) > 1 && layout.running === previous.running;
1153
+ if (afterColumns) layout.continuous = true;
801
1154
  if (breaksSection) {
802
1155
  const last = blocks[blocks.length - 1];
803
1156
  if (last?.type === 'paragraph' && !last.sectionEnd) {
804
- last.sectionEnd = { running: previousRunning };
1157
+ last.sectionEnd = previous;
805
1158
  } else {
806
1159
  blocks.push({
807
1160
  type: 'paragraph',
@@ -809,13 +1162,13 @@ export async function docxFromPages(
809
1162
  spacingBefore: 0,
810
1163
  spacingAfter: 0,
811
1164
  lineExact: 20,
812
- sectionEnd: { running: previousRunning },
1165
+ sectionEnd: previous,
813
1166
  });
814
1167
  }
815
1168
  }
816
1169
  const first = own[0];
817
1170
  if (first) {
818
- const newPage = index > 0 && !info.continues && !breaksSection;
1171
+ const newPage = index > 0 && !info.continues && (!breaksSection || afterColumns);
819
1172
  // Word and Pages drop the space before the first paragraph on a page —
820
1173
  // at the top of the document and after a break alike — so a gap there,
821
1174
  // a cover's title low on its sheet or a closing line centred, is held
@@ -835,7 +1188,7 @@ export async function docxFromPages(
835
1188
  });
836
1189
  }
837
1190
  }
838
- if (own.length > 0) previousRunning = running;
1191
+ if (own.length > 0) previous = layout;
839
1192
  blocks.push(...own);
840
1193
  }
841
1194
 
@@ -856,7 +1209,16 @@ export async function docxFromPages(
856
1209
  });
857
1210
  }
858
1211
 
859
- return { blocks, footnotes, images: ctx.images, lists: ctx.lists, finalRunning: previousRunning };
1212
+ return {
1213
+ blocks,
1214
+ footnotes,
1215
+ images: ctx.images,
1216
+ lists: ctx.lists,
1217
+ finalRunning: previous.running,
1218
+ ...(previous.columns ? { finalColumns: previous.columns } : {}),
1219
+ ...(previous.continuous ? { finalContinuous: true } : {}),
1220
+ ...(previous.foot ? { finalFoot: previous.foot } : {}),
1221
+ };
860
1222
  }
861
1223
 
862
1224
  /** Runs for one element — the footer the orchestrator renders on its own. */
@@ -28,6 +28,11 @@ describe('fontsFor', () => {
28
28
  });
29
29
  });
30
30
 
31
+ it('skips Apple system faces no app can pick by name', () => {
32
+ expect(fontsFor('ui-monospace, "SF Mono", Menlo, monospace', 'mono').ascii).toBe('Menlo');
33
+ expect(fontsFor('"SF Pro Text", Helvetica, sans-serif', 'sans').ascii).toBe('Helvetica');
34
+ });
35
+
31
36
  it('falls back by generic family when nothing is named', () => {
32
37
  expect(fontsFor('system-ui, sans-serif', 'sans').ascii).toBe('Arial');
33
38
  expect(fontsFor('serif', 'sans').ascii).toBe('Times New Roman');
@@ -43,6 +48,13 @@ describe('hexColor', () => {
43
48
  expect(hexColor('#abc')).toBe('aabbcc');
44
49
  expect(hexColor('rgba(0, 0, 0, 0)')).toBeNull();
45
50
  });
51
+
52
+ it('reads color-mix results and flattens a translucent tint onto white', () => {
53
+ expect(hexColor('color(srgb 0.0863 0.0941 0.1137)')).toBe('16181d');
54
+ expect(hexColor('rgba(37, 99, 235, 0.1)')).toBe('e9effd');
55
+ expect(hexColor('color(srgb 0.145 0.388 0.922 / 0.1)')).toBe('e9effd');
56
+ expect(hexColor('color(srgb 0 0 0 / 0)')).toBeNull();
57
+ });
46
58
  });
47
59
 
48
60
  describe('escapeXml', () => {
@@ -314,6 +326,140 @@ describe('buildDocxParts', () => {
314
326
  expect(doc).toContain('</w:tcPr><w:p/></w:tc>');
315
327
  });
316
328
 
329
+ it('shades a paragraph and hangs its first line', () => {
330
+ const doc = buildDocxParts({
331
+ ...MODEL,
332
+ blocks: [
333
+ {
334
+ type: 'paragraph',
335
+ style: 'Code',
336
+ shade: 'e9effd',
337
+ inlines: [{ type: 'text', text: 'x' }],
338
+ },
339
+ {
340
+ type: 'paragraph',
341
+ indent: 480,
342
+ hanging: 480,
343
+ inlines: [
344
+ { type: 'text', text: '[1]' },
345
+ { type: 'tab' },
346
+ { type: 'text', text: 'Knuth' },
347
+ ],
348
+ },
349
+ ],
350
+ })['word/document.xml'] as string;
351
+ // Shading sits after the style and before spacing, where the schema puts it.
352
+ expect(doc).toContain(
353
+ '<w:pPr><w:pStyle w:val="Code"/><w:shd w:val="clear" w:color="auto" w:fill="e9effd"/></w:pPr>',
354
+ );
355
+ expect(doc).toContain('<w:ind w:left="480" w:hanging="480"/>');
356
+ });
357
+
358
+ it('sets a section in columns, ending the one before it', () => {
359
+ const doc = buildDocxParts({
360
+ ...MODEL,
361
+ blocks: [
362
+ {
363
+ type: 'paragraph',
364
+ inlines: [{ type: 'text', text: 'One' }],
365
+ sectionEnd: { running: true },
366
+ },
367
+ { type: 'paragraph', inlines: [{ type: 'text', text: 'Two' }] },
368
+ ],
369
+ finalColumns: { count: 2, gap: 420 },
370
+ })['word/document.xml'] as string;
371
+ expect(doc).toMatch(/<w:pgMar[^>]*\/><\/w:sectPr>.*One/);
372
+ expect(doc).toMatch(/Two.*<w:pgMar[^>]*\/><w:cols w:num="2" w:space="420"\/><\/w:sectPr>/);
373
+ expect(doc.match(/<w:cols /g)).toHaveLength(1);
374
+ });
375
+
376
+ it('shades a pill and rules a line above a paragraph', () => {
377
+ const doc = buildDocxParts({
378
+ ...MODEL,
379
+ blocks: [
380
+ {
381
+ type: 'paragraph',
382
+ ruleAbove: { color: 'e2e8f0', size: 6, gap: 210 },
383
+ inlines: [{ type: 'text', text: 'OPEN-DOC', shade: 'e9effd' }],
384
+ },
385
+ ],
386
+ })['word/document.xml'] as string;
387
+ expect(doc).toContain(
388
+ '<w:pBdr><w:top w:val="single" w:sz="6" w:space="11" w:color="e2e8f0"/></w:pBdr>',
389
+ );
390
+ expect(doc).toContain(
391
+ '<w:rPr><w:shd w:val="clear" w:color="auto" w:fill="e9effd"/></w:rPr><w:t xml:space="preserve">OPEN-DOC</w:t>',
392
+ );
393
+ });
394
+
395
+ it('gives a sheet’s own foot a footer of its section, and the rest an empty one', () => {
396
+ const parts = buildDocxParts({
397
+ ...MODEL,
398
+ footer: undefined,
399
+ blocks: [
400
+ {
401
+ type: 'paragraph',
402
+ inlines: [{ type: 'text', text: 'Cover' }],
403
+ sectionEnd: {
404
+ running: false,
405
+ foot: { type: 'paragraph', inlines: [{ type: 'text', text: 'Byline' }] },
406
+ },
407
+ },
408
+ { type: 'paragraph', inlines: [{ type: 'text', text: 'Body' }] },
409
+ ],
410
+ });
411
+ const doc = parts['word/document.xml'] as string;
412
+ const rels = parts['word/_rels/document.xml.rels'] as string;
413
+ const id = (target: string) =>
414
+ rels.match(new RegExp(`Id="(rId\\d+)"[^>]*Target="${target}"`))?.[1];
415
+ expect(parts['word/footer3.xml']).toContain('Byline');
416
+ // Set in the body's style, and placed a page margin above the sheet's edge.
417
+ expect(parts['word/footer3.xml']).not.toContain('w:val="Footer"');
418
+ expect(doc).toMatch(
419
+ new RegExp(
420
+ `<w:footerReference w:type="default" r:id="${id('footer3.xml')}"/>.*w:footer="1140".*Cover`,
421
+ ),
422
+ );
423
+ // Without a footer of its own, the next section would inherit the cover's.
424
+ expect(doc).toMatch(
425
+ new RegExp(`Body.*<w:footerReference w:type="default" r:id="${id('footer2.xml')}"/>`),
426
+ );
427
+ });
428
+
429
+ it('stamps the watermark behind the text from every header', () => {
430
+ const parts = buildDocxParts({
431
+ ...MODEL,
432
+ blocks: [
433
+ {
434
+ type: 'paragraph',
435
+ inlines: [{ type: 'text', text: 'Cover' }],
436
+ sectionEnd: { running: false },
437
+ },
438
+ { type: 'paragraph', inlines: [{ type: 'text', text: 'Body' }] },
439
+ ],
440
+ images: [
441
+ ...MODEL.images,
442
+ {
443
+ name: 'watermark',
444
+ ext: 'png',
445
+ bytes: new Uint8Array([3]),
446
+ width: 7562850,
447
+ height: 10696575,
448
+ },
449
+ ],
450
+ watermark: 'watermark',
451
+ });
452
+ for (const header of ['word/header1.xml', 'word/header2.xml']) {
453
+ const xml = parts[header] as string;
454
+ expect(xml).toContain('behindDoc="1"');
455
+ expect(xml).toContain('<wp:positionH relativeFrom="page"><wp:posOffset>0</wp:posOffset>');
456
+ expect(xml).toContain('<wp:extent cx="7562850" cy="10696575"/>');
457
+ expect(parts[header.replace('word/', 'word/_rels/').concat('.rels')]).toContain(
458
+ 'Target="media/watermark.png"',
459
+ );
460
+ }
461
+ });
462
+
317
463
  it('gives each ordered list its own count', () => {
318
464
  const numbering = text('word/numbering.xml');
319
465
  expect(numbering).toContain('<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>');
@@ -27,6 +27,8 @@ export type TextRun = {
27
27
  /** Font size in half-points, only when it differs from the paragraph style's. */
28
28
  halfPoints?: number;
29
29
  vert?: 'superscript' | 'subscript';
30
+ /** Background behind the characters, `rrggbb` — an inline pill or badge. */
31
+ shade?: string;
30
32
  };
31
33
 
32
34
  export type Run =
@@ -66,12 +68,20 @@ export type Paragraph = {
66
68
  inlines: Inline[];
67
69
  list?: { numId: number; level: number };
68
70
  pageBreakBefore?: boolean;
71
+ /** Starts in the next column — where the printed page's next column began. */
72
+ columnBreakBefore?: boolean;
69
73
  keepNext?: boolean;
70
74
  /** Twips. */
71
75
  spacingBefore?: number;
72
76
  spacingAfter?: number;
73
77
  /** Left indent, twips, over the style's own. */
74
78
  indent?: number;
79
+ /** The first line starts this far left of `indent`, twips — a label hanging in the margin. */
80
+ hanging?: number;
81
+ /** Background behind the paragraph, `rrggbb` — a highlighted line of code. */
82
+ shade?: string;
83
+ /** A rule above the paragraph and the gap between it and the text, twips. */
84
+ ruleAbove?: { color: string; size: number; gap: number };
75
85
  /** An exact line height, twips — a spacer that holds open a gap. */
76
86
  lineExact?: number;
77
87
  /**
@@ -80,7 +90,7 @@ export type Paragraph = {
80
90
  * Fixed sheets print their own running lines, so they sit in sections
81
91
  * without one.
82
92
  */
83
- sectionEnd?: { running: boolean };
93
+ sectionEnd?: SectionLayout;
84
94
  /** Right-aligned tab stop, twips from the left margin — a footer's page number. */
85
95
  rightTab?: number;
86
96
  /** Dots leading to the right tab, as a contents entry has. */
@@ -89,6 +99,24 @@ export type Paragraph = {
89
99
  bookmark?: string;
90
100
  };
91
101
 
102
+ /** What a section's pages carry: the running header and footer, and how many columns. */
103
+ export type SectionLayout = {
104
+ running: boolean;
105
+ /** Text columns and the gap between them, twips; absent means one. */
106
+ columns?: { count: number; gap: number };
107
+ /**
108
+ * Starts on the page the section before it ended on. Word balances the
109
+ * columns of a section only where a continuous break ends it.
110
+ */
111
+ continuous?: boolean;
112
+ /**
113
+ * A line the sheet laid out against its own foot — a cover's byline. It is
114
+ * this section's footer, so it sits at the foot of the page whatever came
115
+ * out above it.
116
+ */
117
+ foot?: Paragraph;
118
+ };
119
+
92
120
  export type CellBorder = { color: string /** Eighths of a point. */; size: number };
93
121
 
94
122
  export type TableCell = {
@@ -166,6 +194,12 @@ export type DocxModel = {
166
194
  footer?: Paragraph;
167
195
  /** Whether the last section carries the header and footer. Defaults to true. */
168
196
  finalRunning?: boolean;
197
+ /** The last section's columns and start, as `SectionLayout`. */
198
+ finalColumns?: SectionLayout['columns'];
199
+ finalContinuous?: boolean;
200
+ finalFoot?: Paragraph;
201
+ /** A picture behind the text of every page, the size of the sheet — `meta.watermark`. */
202
+ watermark?: string;
169
203
  images: ImagePart[];
170
204
  /** One entry per list; ordered lists restart at 1 each. */
171
205
  lists: Array<'bullet' | 'decimal'>;
@@ -230,6 +264,13 @@ const GENERIC = new Set([
230
264
  'inherit',
231
265
  ]);
232
266
 
267
+ /**
268
+ * Apple's system faces: a page draws in them, but no app outside the system can
269
+ * pick one by name, so Pages and Word would fall back to Courier or Times. The
270
+ * next family in the stack — Menlo, Helvetica — is the one that will be there.
271
+ */
272
+ const SYSTEM_ONLY = /^(\.?sf ?(mono|pro|compact)|sfmono-|sfns)/i;
273
+
233
274
  const CJK_FONT =
234
275
  /noto (sans|serif) (tc|sc|jp|kr|hk|cjk)|pingfang|hiragino|jhenghei|yahei|正黑|明體|楷|source han|思源|yu gothic|yu mincho|meiryo|malgun|ms mincho|ms gothic|heiti|songti|kaiti|biaukai|dfkai|simsun|simhei|mingliu|gulim|batang|lxgw|霞鶩/i;
235
276
 
@@ -245,7 +286,9 @@ export function fontsFor(stack: string, fallback: 'sans' | 'serif' | 'mono'): Fo
245
286
  .split(',')
246
287
  .map((family) => family.trim().replace(/^['"]|['"]$/g, ''))
247
288
  .filter((family) => family !== '');
248
- const real = families.filter((family) => !GENERIC.has(family.toLowerCase()));
289
+ const real = families.filter(
290
+ (family) => !GENERIC.has(family.toLowerCase()) && !SYSTEM_ONLY.test(family),
291
+ );
249
292
  const generic =
250
293
  families.find((family) => ['serif', 'monospace', 'ui-monospace'].includes(family)) ?? '';
251
294
  const kind = generic === 'serif' ? 'serif' : generic.includes('monospace') ? 'mono' : fallback;
@@ -285,18 +328,38 @@ function fontTableXml(fonts: DocxModel['fonts']): string {
285
328
  );
286
329
  }
287
330
 
288
- /** `rgb(22, 24, 29)` or `#16181d` as `16181d`; null for anything transparent. */
331
+ /**
332
+ * `rgb(22, 24, 29)`, `#16181d` or `color(srgb 0.09 0.09 0.11)` as `16181d`;
333
+ * null for anything transparent. Word has no alpha, so a translucent colour is
334
+ * flattened onto white paper — the tint `color-mix(… transparent)` drew there.
335
+ */
289
336
  export function hexColor(css: string): string | null {
290
337
  const hex = css.trim().match(/^#([0-9a-f]{6})$/i);
291
338
  if (hex?.[1]) return hex[1].toLowerCase();
292
339
  const short = css.trim().match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
293
340
  if (short)
294
341
  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'))
342
+ const alphaOf = (value: string | undefined) =>
343
+ value === undefined ? 1 : value.endsWith('%') ? Number.parseFloat(value) / 100 : Number(value);
344
+ let channels: number[];
345
+ let alpha: number;
346
+ const srgb = css.match(
347
+ /color\(\s*srgb\s+([\d.e-]+)\s+([\d.e-]+)\s+([\d.e-]+)(?:\s*\/\s*([\d.]+%?))?\s*\)/i,
348
+ );
349
+ const rgb = css.match(/rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)(?:[\s,/]+([\d.]+%?))?/i);
350
+ if (srgb) {
351
+ channels = [srgb[1], srgb[2], srgb[3]].map((value) => Number(value) * 255);
352
+ alpha = alphaOf(srgb[4]);
353
+ } else if (rgb) {
354
+ channels = [rgb[1], rgb[2], rgb[3]].map(Number);
355
+ alpha = alphaOf(rgb[4]);
356
+ } else {
357
+ return null;
358
+ }
359
+ if (!(alpha > 0)) return null;
360
+ return channels
361
+ .map((channel) => Math.round(Math.min(255, Math.max(0, channel * alpha + 255 * (1 - alpha)))))
362
+ .map((channel) => channel.toString(16).padStart(2, '0'))
300
363
  .join('');
301
364
  }
302
365
 
@@ -311,8 +374,8 @@ type WriteContext = {
311
374
  imageIds: Map<string, string>;
312
375
  drawingId: { value: number };
313
376
  bookmarkId?: { value: number };
314
- /** A section's properties, with or without the running header and footer. */
315
- section?: (running: boolean) => string;
377
+ /** A section's properties: its running header and footer, and its columns. */
378
+ section?: (layout: SectionLayout) => string;
316
379
  };
317
380
 
318
381
  const REL_HYPERLINK =
@@ -345,6 +408,7 @@ function runPropsXml(run: TextRun, ctx: WriteContext): string {
345
408
  if (run.halfPoints)
346
409
  parts.push(`<w:sz w:val="${run.halfPoints}"/><w:szCs w:val="${run.halfPoints}"/>`);
347
410
  if (run.underline) parts.push('<w:u w:val="single"/>');
411
+ if (run.shade) parts.push(`<w:shd w:val="clear" w:color="auto" w:fill="${run.shade}"/>`);
348
412
  if (run.vert) parts.push(`<w:vertAlign w:val="${run.vert}"/>`);
349
413
  return parts.length > 0 ? `<w:rPr>${parts.join('')}</w:rPr>` : '';
350
414
  }
@@ -376,6 +440,30 @@ function imageXml(name: string, ctx: WriteContext): string {
376
440
  );
377
441
  }
378
442
 
443
+ /** A picture pinned to the page's corner behind the text — how Word itself stores a watermark. */
444
+ function anchoredImageXml(name: string, ctx: WriteContext): string {
445
+ const image = ctx.model.images.find((candidate) => candidate.name === name);
446
+ if (!image) return '';
447
+ const rel = relFor(ctx, REL_IMAGE, `media/${image.name}.${image.ext}`);
448
+ const id = ctx.drawingId.value++;
449
+ const extent = `cx="${Math.round(image.width)}" cy="${Math.round(image.height)}"`;
450
+ return (
451
+ '<w:r><w:drawing>' +
452
+ '<wp:anchor distT="0" distB="0" distL="0" distR="0" simplePos="0" relativeHeight="0" behindDoc="1" locked="1" layoutInCell="1" allowOverlap="1">' +
453
+ '<wp:simplePos x="0" y="0"/>' +
454
+ '<wp:positionH relativeFrom="page"><wp:posOffset>0</wp:posOffset></wp:positionH>' +
455
+ '<wp:positionV relativeFrom="page"><wp:posOffset>0</wp:posOffset></wp:positionV>' +
456
+ `<wp:extent ${extent}/><wp:effectExtent l="0" t="0" r="0" b="0"/><wp:wrapNone/>` +
457
+ `<wp:docPr id="${id}" name="Watermark ${id}"/>` +
458
+ '<wp:cNvGraphicFramePr><a:graphicFrameLocks noChangeAspect="1"/></wp:cNvGraphicFramePr>' +
459
+ '<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">' +
460
+ `<pic:pic><pic:nvPicPr><pic:cNvPr id="${id}" name="${escapeXml(image.name)}"/><pic:cNvPicPr/></pic:nvPicPr>` +
461
+ `<pic:blipFill><a:blip r:embed="${rel}"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill>` +
462
+ `<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>` +
463
+ '</pic:pic></a:graphicData></a:graphic></wp:anchor></w:drawing></w:r>'
464
+ );
465
+ }
466
+
379
467
  function runXml(run: Run, ctx: WriteContext, linked = false): string {
380
468
  switch (run.type) {
381
469
  case 'text': {
@@ -424,6 +512,16 @@ export function paragraphXml(paragraph: Paragraph, ctx: WriteContext): string {
424
512
  `<w:numPr><w:ilvl w:val="${paragraph.list.level}"/><w:numId w:val="${paragraph.list.numId}"/></w:numPr>`,
425
513
  );
426
514
  }
515
+ if (paragraph.ruleAbove) {
516
+ const { color, size, gap } = paragraph.ruleAbove;
517
+ // A border's space is in points, and Word allows no more than 31.
518
+ const space = Math.min(31, Math.round(gap / 20));
519
+ props.push(
520
+ `<w:pBdr><w:top w:val="single" w:sz="${size}" w:space="${space}" w:color="${color}"/></w:pBdr>`,
521
+ );
522
+ }
523
+ if (paragraph.shade)
524
+ props.push(`<w:shd w:val="clear" w:color="auto" w:fill="${paragraph.shade}"/>`);
427
525
  if (paragraph.rightTab !== undefined) {
428
526
  const leader = paragraph.leader ? ' w:leader="dot"' : '';
429
527
  props.push(
@@ -449,13 +547,17 @@ export function paragraphXml(paragraph: Paragraph, ctx: WriteContext): string {
449
547
  : '';
450
548
  props.push(`<w:spacing${before}${after}${line}/>`);
451
549
  }
452
- if (paragraph.indent !== undefined)
453
- props.push(`<w:ind w:left="${Math.round(paragraph.indent)}"/>`);
550
+ if (paragraph.indent !== undefined || paragraph.hanging !== undefined) {
551
+ const hanging = paragraph.hanging ? ` w:hanging="${Math.round(paragraph.hanging)}"` : '';
552
+ props.push(`<w:ind w:left="${Math.round(paragraph.indent ?? 0)}"${hanging}/>`);
553
+ }
454
554
  if (paragraph.align && paragraph.align !== 'left')
455
555
  props.push(`<w:jc w:val="${paragraph.align}"/>`);
456
- if (paragraph.sectionEnd && ctx.section) props.push(ctx.section(paragraph.sectionEnd.running));
556
+ if (paragraph.sectionEnd && ctx.section) props.push(ctx.section(paragraph.sectionEnd));
457
557
  const pPr = props.length > 0 ? `<w:pPr>${props.join('')}</w:pPr>` : '';
458
- const runs = paragraph.inlines.map((inline) => inlineXml(inline, ctx)).join('');
558
+ const runs =
559
+ (paragraph.columnBreakBefore ? '<w:r><w:br w:type="column"/></w:r>' : '') +
560
+ paragraph.inlines.map((inline) => inlineXml(inline, ctx)).join('');
459
561
  if (!paragraph.bookmark) return `<w:p>${pPr}${runs}</w:p>`;
460
562
  ctx.bookmarkId ??= { value: 0 };
461
563
  const id = ctx.bookmarkId.value++;
@@ -659,11 +761,19 @@ export function buildDocxParts(model: DocxModel): Record<string, string | Uint8A
659
761
  const bare =
660
762
  model.finalRunning === false ||
661
763
  model.blocks.some((block) => block.type === 'paragraph' && block.sectionEnd?.running === false);
764
+ // A section with a foot of its own changes the footer, so every other
765
+ // section needs a footer to point at, if only an empty one.
766
+ const feet =
767
+ Boolean(model.finalFoot) ||
768
+ model.blocks.some((block) => block.type === 'paragraph' && block.sectionEnd?.foot);
662
769
  const running = (kind: 'header' | 'footer') => {
663
- if (!model[kind]) return { full: null, bare: null };
770
+ // The watermark is drawn from the header, so a document with one needs a
771
+ // header even when it has no running line to put there.
772
+ const full = Boolean(model[kind]) || (kind === 'header' && Boolean(model.watermark));
773
+ const empty = full ? bare : kind === 'footer' && feet;
664
774
  return {
665
- full: relFor(docCtx, `${REL_BASE}/${kind}`, `${kind}1.xml`),
666
- bare: bare ? relFor(docCtx, `${REL_BASE}/${kind}`, `${kind}2.xml`) : null,
775
+ full: full ? relFor(docCtx, `${REL_BASE}/${kind}`, `${kind}1.xml`) : null,
776
+ bare: empty ? relFor(docCtx, `${REL_BASE}/${kind}`, `${kind}2.xml`) : null,
667
777
  };
668
778
  };
669
779
  const headerRels = running('header');
@@ -671,20 +781,40 @@ export function buildDocxParts(model: DocxModel): Record<string, string | Uint8A
671
781
 
672
782
  const { page } = model;
673
783
  const margin = Math.round(page.margin);
674
- docCtx.section = (on) => {
784
+ const footParts: Array<{ name: string; paragraph: Paragraph }> = [];
785
+ docCtx.section = ({ running: on, columns, continuous, foot }) => {
675
786
  const header = on ? headerRels.full : headerRels.bare;
676
- const footer = on ? footerRels.full : footerRels.bare;
787
+ let footer = on ? (footerRels.full ?? footerRels.bare) : footerRels.bare;
788
+ if (foot) {
789
+ const name = `footer${footParts.length + 3}`;
790
+ footParts.push({ name, paragraph: foot });
791
+ footer = relFor(docCtx, `${REL_BASE}/footer`, `${name}.xml`);
792
+ }
793
+ // The foot sat a page margin above the sheet's edge; a footer is placed by
794
+ // its distance from that edge.
795
+ const footerAt = foot ? margin : Math.round(margin / 2);
796
+ const cols =
797
+ columns && columns.count > 1
798
+ ? `<w:cols w:num="${columns.count}" w:space="${Math.round(columns.gap)}"/>`
799
+ : '';
677
800
  return (
678
801
  '<w:sectPr>' +
679
802
  (header ? `<w:headerReference w:type="default" r:id="${header}"/>` : '') +
680
803
  (footer ? `<w:footerReference w:type="default" r:id="${footer}"/>` : '') +
804
+ (continuous ? '<w:type w:val="continuous"/>' : '') +
681
805
  `<w:pgSz w:w="${Math.round(page.width)}" w:h="${Math.round(page.height)}"${page.landscape ? ' w:orient="landscape"' : ''}/>` +
682
- `<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"/>` +
806
+ `<w:pgMar w:top="${margin}" w:right="${margin}" w:bottom="${margin}" w:left="${margin}" w:header="${Math.round(margin / 2)}" w:footer="${footerAt}" w:gutter="0"/>` +
807
+ cols +
683
808
  '</w:sectPr>'
684
809
  );
685
810
  };
686
811
  const body = model.blocks.map((block) => blockXml(block, docCtx)).join('');
687
- const sectPr = docCtx.section(model.finalRunning !== false);
812
+ const sectPr = docCtx.section({
813
+ running: model.finalRunning !== false,
814
+ ...(model.finalColumns ? { columns: model.finalColumns } : {}),
815
+ ...(model.finalContinuous ? { continuous: true } : {}),
816
+ ...(model.finalFoot ? { foot: model.finalFoot } : {}),
817
+ });
688
818
  const documentXml = `${XML_HEAD}<w:document ${NS}><w:body>${body}${sectPr}</w:body></w:document>`;
689
819
 
690
820
  // Footnotes and the footer are parts of their own, with their own rels.
@@ -721,16 +851,26 @@ export function buildDocxParts(model: DocxModel): Record<string, string | Uint8A
721
851
  ['header', headerRels, 'hdr', 'Header'],
722
852
  ['footer', footerRels, 'ftr', 'Footer'],
723
853
  ] 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}`);
854
+ const line: Paragraph = model[kind] ?? { type: 'paragraph', inlines: [] };
855
+ const stamp = kind === 'header' ? model.watermark : undefined;
856
+ const part = (name: string, paragraph: Paragraph) => {
857
+ const ctx: WriteContext = { model, rels: [], imageIds: new Map(), drawingId };
858
+ // The watermark rides in the header's own paragraph, anchored to the
859
+ // page behind the text, so it adds no height to the header.
860
+ const xml = paragraphXml(
861
+ { ...paragraph, style: paragraph.style ?? (style as StyleId) },
862
+ ctx,
863
+ ).replace(/<\/w:p>$/, `${stamp ? anchoredImageXml(stamp, ctx) : ''}</w:p>`);
864
+ runningParts[`word/${name}.xml`] = `${XML_HEAD}<w:${tag} ${NS}>${xml}</w:${tag}>`;
865
+ if (ctx.rels.length > 0) runningParts[`word/_rels/${name}.xml.rels`] = relsXml(ctx.rels);
866
+ runningTypes.push(`/word/${name}.xml|${kind}`);
867
+ };
868
+ if (rels.full) part(`${kind}1`, line);
869
+ if (rels.bare) part(`${kind}2`, { type: 'paragraph', inlines: [] });
870
+ // A sheet's own foot is set in the body's style: its runs say only how
871
+ // they differ from that, not from the running footer's.
872
+ if (kind === 'footer') {
873
+ for (const foot of footParts) part(foot.name, { ...foot.paragraph, style: 'Normal' });
734
874
  }
735
875
  }
736
876
 
@@ -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}`);