@open-document/core 0.13.0 → 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.
@@ -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}`);