@open-document/core 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/dist/{build-CFL7nhz0.js → build-DJMLK50m.js} +1 -1
  2. package/dist/{check-CL0-0eB8.js → check-CUKuufBm.js} +3 -3
  3. package/dist/cli/bin.js +10 -6
  4. package/dist/{config-4nz5NnxW.js → config-CvzpyAUA.js} +558 -546
  5. package/dist/{context-BH8C-dSW.js → context-B4ip7SoI.js} +1 -1
  6. package/dist/{dev-BCSUczXW.js → dev-dnH7DTlD.js} +1 -1
  7. package/dist/{diagram-xlVDekYk.js → diagram-BK4jTZr4.js} +231 -158
  8. package/dist/diff-QTo0A5Rx.js +44 -0
  9. package/dist/{export-CmVJdl9a.js → export-BrRFrexj.js} +3 -3
  10. package/dist/{import-E6vRo7xm.js → import-C14Vn9ER.js} +2 -2
  11. package/dist/index.d.ts +54 -3
  12. package/dist/index.js +457 -18
  13. package/dist/ops/index.d.ts +72 -17
  14. package/dist/ops/index.js +3 -3
  15. package/dist/{ops-OZZVBgsM.js → ops-DKidjLXP.js} +642 -124
  16. package/dist/{preview-CwCrw-i3.js → preview-wKM4C6Uk.js} +1 -1
  17. package/dist/{sdk-BqU6mwD_.d.ts → sdk-CpDEGRIo.d.ts} +2 -0
  18. package/dist/vite/index.js +1 -1
  19. package/package.json +2 -2
  20. package/skills/doc-authoring/SKILL.md +13 -6
  21. package/skills/doc-authoring/references/pagination.md +1 -1
  22. package/skills/doc-authoring/references/tables-and-charts.md +18 -1
  23. package/src/app/components/browser/browser-ui.tsx +105 -0
  24. package/src/app/components/chart.tsx +239 -0
  25. package/src/app/components/command-palette.tsx +284 -0
  26. package/src/app/components/design-panel/design-panel.tsx +22 -20
  27. package/src/app/components/design-panel/design-provider.tsx +4 -2
  28. package/src/app/components/diagram.tsx +11 -1
  29. package/src/app/components/doc-assets.tsx +6 -5
  30. package/src/app/components/doc-search.tsx +12 -10
  31. package/src/app/components/doc-sidebar.tsx +24 -18
  32. package/src/app/components/flow-page.tsx +2 -0
  33. package/src/app/components/inspector/inspector.tsx +75 -48
  34. package/src/app/components/language-toggle.tsx +38 -0
  35. package/src/app/components/palette-items.ts +128 -0
  36. package/src/app/components/panel/edit-save-card.tsx +4 -2
  37. package/src/app/components/panel/fields.tsx +5 -2
  38. package/src/app/components/panel/save-card.tsx +18 -10
  39. package/src/app/components/sidebar/folder-item.tsx +10 -8
  40. package/src/app/components/sidebar/icon-picker.tsx +3 -1
  41. package/src/app/components/sidebar/sidebar.tsx +44 -13
  42. package/src/app/components/theme-toggle.tsx +5 -3
  43. package/src/app/components/ui/menu.tsx +5 -0
  44. package/src/app/lib/agent-bridge.ts +8 -2
  45. package/src/app/lib/chart.test.ts +108 -0
  46. package/src/app/lib/chart.ts +343 -0
  47. package/src/app/lib/doc-preview.tsx +0 -10
  48. package/src/app/lib/docs.ts +3 -0
  49. package/src/app/lib/docx/from-dom.ts +11 -11
  50. package/src/app/lib/docx/ooxml.test.ts +25 -9
  51. package/src/app/lib/docx/ooxml.ts +58 -37
  52. package/src/app/lib/export-docx.ts +13 -8
  53. package/src/app/lib/export-dom.ts +4 -0
  54. package/src/app/lib/export-image.ts +2 -0
  55. package/src/app/lib/export-pdf.ts +6 -0
  56. package/src/app/lib/flow-measure.ts +3 -0
  57. package/src/app/lib/flow.ts +1 -1
  58. package/src/app/lib/i18n-ja/browser.ts +88 -0
  59. package/src/app/lib/i18n-ja/doc.ts +65 -0
  60. package/src/app/lib/i18n-ja/index.ts +5 -0
  61. package/src/app/lib/i18n-ja/panels.ts +104 -0
  62. package/src/app/lib/i18n-ko/browser.ts +87 -0
  63. package/src/app/lib/i18n-ko/doc.ts +65 -0
  64. package/src/app/lib/i18n-ko/index.ts +5 -0
  65. package/src/app/lib/i18n-ko/panels.ts +102 -0
  66. package/src/app/lib/i18n-zh-cn/browser.ts +84 -0
  67. package/src/app/lib/i18n-zh-cn/doc.ts +64 -0
  68. package/src/app/lib/i18n-zh-cn/index.ts +5 -0
  69. package/src/app/lib/i18n-zh-cn/panels.ts +98 -0
  70. package/src/app/lib/i18n-zh-tw/browser.ts +84 -0
  71. package/src/app/lib/i18n-zh-tw/doc.ts +64 -0
  72. package/src/app/lib/i18n-zh-tw/index.ts +5 -0
  73. package/src/app/lib/i18n-zh-tw/panels.ts +99 -0
  74. package/src/app/lib/i18n.test.ts +24 -0
  75. package/src/app/lib/i18n.tsx +109 -0
  76. package/src/app/lib/outline.ts +23 -0
  77. package/src/app/lib/page-range.test.ts +10 -1
  78. package/src/app/lib/page-range.ts +26 -0
  79. package/src/app/lib/sdk.ts +2 -0
  80. package/src/app/lib/svg-ids.ts +37 -0
  81. package/src/app/main.tsx +4 -1
  82. package/src/app/routes/assets.tsx +193 -132
  83. package/src/app/routes/doc.tsx +666 -310
  84. package/src/app/routes/home-shell.tsx +115 -88
  85. package/src/app/routes/home.tsx +200 -67
  86. package/src/app/routes/themes.tsx +42 -35
  87. package/src/app/styles.css +99 -0
  88. package/src/app/virtual.d.ts +1 -0
@@ -0,0 +1,343 @@
1
+ /**
2
+ * Chart geometry, kept pure so it can be tested without a DOM.
3
+ *
4
+ * A chart is laid out synchronously from its data into a fixed box — no
5
+ * measuring pass, no async load — because the flow packer measures the page
6
+ * as it first renders, and a chart that settled a tick later would settle
7
+ * after the page break was decided. Text widths come from the same estimate
8
+ * the diagram compiler uses, for the same reason.
9
+ */
10
+
11
+ import { measureText } from '../../diagram/layout';
12
+
13
+ export type ChartType = 'bar' | 'line' | 'pie';
14
+
15
+ export type ChartFormat = 'number' | 'integer' | 'percent' | ((value: number) => string);
16
+
17
+ export type ChartSpec = {
18
+ type: ChartType;
19
+ data: Array<Record<string, unknown>>;
20
+ x: string;
21
+ y: string[];
22
+ /** Legend names per `y` key. */
23
+ labels?: Record<string, string>;
24
+ stacked?: boolean;
25
+ format?: ChartFormat;
26
+ width: number;
27
+ height: number;
28
+ /** Print each value on its bar, point or slice. */
29
+ values?: boolean;
30
+ };
31
+
32
+ export type Rect = { x: number; y: number; width: number; height: number };
33
+ export type Tick = { value: number; at: number; label: string };
34
+ export type CategoryLabel = { text: string; x: number };
35
+ export type LegendItem = { name: string; series: number; x: number; y: number };
36
+ export type ValueLabel = { text: string; x: number; y: number; anchor: 'middle' | 'start' };
37
+ export type Bar = Rect & { series: number; value: number };
38
+ export type Line = { series: number; points: Array<{ x: number; y: number; value: number }> };
39
+ export type Slice = { series: number; path: string; share: number; name: string };
40
+
41
+ export type ChartLayout = {
42
+ width: number;
43
+ height: number;
44
+ plot: Rect;
45
+ /** Where zero sits on the value axis, when the axis has one. */
46
+ baseline: number | null;
47
+ ticks: Tick[];
48
+ categories: CategoryLabel[];
49
+ bars: Bar[];
50
+ lines: Line[];
51
+ slices: Slice[];
52
+ legend: LegendItem[];
53
+ values: ValueLabel[];
54
+ };
55
+
56
+ export const CHART_FONT_SIZE = 10;
57
+ const LEGEND_SWATCH = 9;
58
+ const LEGEND_GAP = 14;
59
+
60
+ /** A number read the way a CSV cell or a typed literal would hold it. */
61
+ export function toNumber(value: unknown): number | null {
62
+ if (typeof value === 'number') return Number.isFinite(value) ? value : null;
63
+ if (typeof value === 'string' && value.trim() !== '') {
64
+ const n = Number(value.replace(/,/g, ''));
65
+ return Number.isFinite(n) ? n : null;
66
+ }
67
+ return null;
68
+ }
69
+
70
+ export function formatChartValue(value: number, format: ChartFormat | undefined): string {
71
+ if (typeof format === 'function') return format(value);
72
+ if (format === 'integer') return Math.round(value).toLocaleString();
73
+ if (format === 'percent')
74
+ return `${(value * 100).toLocaleString(undefined, { maximumFractionDigits: 1 })}%`;
75
+ return value.toLocaleString(undefined, { maximumFractionDigits: 2 });
76
+ }
77
+
78
+ /**
79
+ * Round tick values over a range — 0, 20, 40 rather than 0, 17.3, 34.6 —
80
+ * stepping by 1, 2 or 5 times a power of ten.
81
+ */
82
+ export function niceTicks(min: number, max: number, count = 5): number[] {
83
+ if (min === max) {
84
+ if (min === 0) return [0, 1];
85
+ const pad = Math.abs(min) * 0.5;
86
+ return niceTicks(Math.min(0, min - pad), Math.max(0, max + pad), count);
87
+ }
88
+ const span = max - min;
89
+ const rough = span / Math.max(1, count);
90
+ const power = 10 ** Math.floor(Math.log10(rough));
91
+ const step = [1, 2, 5, 10].map((m) => m * power).find((s) => s >= rough) ?? 10 * power;
92
+ const first = Math.floor(min / step) * step;
93
+ const last = Math.ceil(max / step) * step;
94
+ const ticks: number[] = [];
95
+ // Rounded to the step's precision, so 0.1 + 0.2 never prints as 0.30000000000000004.
96
+ const digits = Math.max(0, -Math.floor(Math.log10(step)));
97
+ for (let value = first; value <= last + step / 2; value += step) {
98
+ ticks.push(Number(value.toFixed(digits)));
99
+ }
100
+ return ticks;
101
+ }
102
+
103
+ function seriesName(spec: ChartSpec, key: string): string {
104
+ return spec.labels?.[key] ?? key;
105
+ }
106
+
107
+ function legendRow(names: string[], left: number, top: number): LegendItem[] {
108
+ let x = left;
109
+ return names.map((name, series) => {
110
+ const item = { name, series, x, y: top };
111
+ x += LEGEND_SWATCH + 5 + measureText(name, CHART_FONT_SIZE) + LEGEND_GAP;
112
+ return item;
113
+ });
114
+ }
115
+
116
+ function slicePath(cx: number, cy: number, r: number, from: number, to: number): string {
117
+ // A slice that is the whole pie is a circle; an arc from a point to itself draws nothing.
118
+ if (to - from >= Math.PI * 2 - 1e-9) {
119
+ return `M${cx - r},${cy} a${r},${r} 0 1 0 ${r * 2},0 a${r},${r} 0 1 0 ${-r * 2},0 Z`;
120
+ }
121
+ const point = (angle: number) => ({
122
+ x: cx + r * Math.sin(angle),
123
+ y: cy - r * Math.cos(angle),
124
+ });
125
+ const start = point(from);
126
+ const end = point(to);
127
+ const large = to - from > Math.PI ? 1 : 0;
128
+ return (
129
+ `M${cx},${cy} L${round(start.x)},${round(start.y)} ` +
130
+ `A${r},${r} 0 ${large} 1 ${round(end.x)},${round(end.y)} Z`
131
+ );
132
+ }
133
+
134
+ function round(value: number): number {
135
+ return Math.round(value * 100) / 100;
136
+ }
137
+
138
+ function layoutPie(spec: ChartSpec): ChartLayout {
139
+ const key = spec.y[0] ?? '';
140
+ const rows = spec.data
141
+ .map((row) => ({ name: String(row[spec.x] ?? ''), value: toNumber(row[key]) ?? 0 }))
142
+ .filter((row) => row.value > 0);
143
+ const total = rows.reduce((sum, row) => sum + row.value, 0);
144
+
145
+ const r = Math.max(10, Math.min(spec.height / 2 - 6, spec.width * 0.25));
146
+ const cx = r + 6;
147
+ const cy = spec.height / 2;
148
+ const slices: Slice[] = [];
149
+ const values: ValueLabel[] = [];
150
+ let angle = 0;
151
+ rows.forEach((row, series) => {
152
+ const share = total > 0 ? row.value / total : 0;
153
+ const next = angle + share * Math.PI * 2;
154
+ slices.push({ series, path: slicePath(cx, cy, r, angle, next), share, name: row.name });
155
+ if (spec.values && share >= 0.06) {
156
+ const mid = (angle + next) / 2;
157
+ values.push({
158
+ text: formatChartValue(share, 'percent'),
159
+ x: round(cx + r * 0.62 * Math.sin(mid)),
160
+ y: round(cy - r * 0.62 * Math.cos(mid) + CHART_FONT_SIZE * 0.35),
161
+ anchor: 'middle',
162
+ });
163
+ }
164
+ angle = next;
165
+ });
166
+
167
+ // The legend reads down the side: name and share, one per slice.
168
+ const legendLeft = cx + r + 24;
169
+ const lineHeight = CHART_FONT_SIZE * 1.8;
170
+ const legendTop = cy - (rows.length * lineHeight) / 2 + lineHeight / 2;
171
+ const legend = slices.map((slice, series) => ({
172
+ name: `${slice.name} ${formatChartValue(slice.share, 'percent')}`,
173
+ series,
174
+ x: legendLeft,
175
+ y: round(legendTop + series * lineHeight),
176
+ }));
177
+
178
+ return {
179
+ width: spec.width,
180
+ height: spec.height,
181
+ plot: { x: cx - r, y: cy - r, width: r * 2, height: r * 2 },
182
+ baseline: null,
183
+ ticks: [],
184
+ categories: [],
185
+ bars: [],
186
+ lines: [],
187
+ slices,
188
+ legend,
189
+ values,
190
+ };
191
+ }
192
+
193
+ export function layoutChart(spec: ChartSpec): ChartLayout {
194
+ if (spec.type === 'pie') return layoutPie(spec);
195
+
196
+ const names = spec.y.map((key) => seriesName(spec, key));
197
+ const categories = spec.data.map((row) => String(row[spec.x] ?? ''));
198
+ const matrix = spec.data.map((row) => spec.y.map((key) => toNumber(row[key])));
199
+
200
+ // The value range, with stacked bars summed per category. Bars always stand
201
+ // on zero; a line keeps zero in view unless its values sit far above it.
202
+ let lo = Number.POSITIVE_INFINITY;
203
+ let hi = Number.NEGATIVE_INFINITY;
204
+ for (const values of matrix) {
205
+ if (spec.type === 'bar' && spec.stacked) {
206
+ const up = values.reduce<number>((sum, v) => sum + Math.max(0, v ?? 0), 0);
207
+ const down = values.reduce<number>((sum, v) => sum + Math.min(0, v ?? 0), 0);
208
+ lo = Math.min(lo, down);
209
+ hi = Math.max(hi, up);
210
+ } else {
211
+ for (const v of values) {
212
+ if (v === null) continue;
213
+ lo = Math.min(lo, v);
214
+ hi = Math.max(hi, v);
215
+ }
216
+ }
217
+ }
218
+ if (!Number.isFinite(lo)) {
219
+ lo = 0;
220
+ hi = 1;
221
+ }
222
+ if (spec.type === 'bar' || (lo >= 0 && lo <= hi * 0.5)) lo = Math.min(0, lo);
223
+ if (spec.type === 'bar') hi = Math.max(0, hi);
224
+
225
+ const tickValues = niceTicks(lo, hi);
226
+ const min = tickValues[0] ?? 0;
227
+ const max = tickValues[tickValues.length - 1] ?? 1;
228
+ const tickLabels = tickValues.map((value) => formatChartValue(value, spec.format));
229
+
230
+ const legendHeight = spec.y.length > 1 ? CHART_FONT_SIZE * 2.2 : 0;
231
+ const top = 6 + legendHeight + (spec.values ? CHART_FONT_SIZE : 0);
232
+ // The width estimate runs a little short for digits in most faces; the
233
+ // margin errs wide so the longest tick label never clips at the edge.
234
+ const left =
235
+ Math.ceil(Math.max(...tickLabels.map((t) => measureText(t, CHART_FONT_SIZE))) * 1.2) + 12;
236
+ const bottom = CHART_FONT_SIZE * 2;
237
+ const right = 6;
238
+ const plot: Rect = {
239
+ x: left,
240
+ y: top,
241
+ width: Math.max(10, spec.width - left - right),
242
+ height: Math.max(10, spec.height - top - bottom),
243
+ };
244
+ const yOf = (value: number) =>
245
+ round(plot.y + plot.height - ((value - min) / (max - min)) * plot.height);
246
+
247
+ const ticks = tickValues.map((value, i) => ({
248
+ value,
249
+ at: yOf(value),
250
+ label: tickLabels[i] ?? '',
251
+ }));
252
+
253
+ const band = plot.width / Math.max(1, categories.length);
254
+ // Labels that would collide thin out to every k-th, rather than overlap.
255
+ const widest = Math.max(0, ...categories.map((c) => measureText(c, CHART_FONT_SIZE)));
256
+ const every = Math.max(1, Math.ceil((widest + 6) / band));
257
+ const categoryLabels = categories
258
+ .map((text, i) => ({ text, x: round(plot.x + band * (i + 0.5)) }))
259
+ .filter((_, i) => i % every === 0);
260
+
261
+ const bars: Bar[] = [];
262
+ const lines: Line[] = [];
263
+ const values: ValueLabel[] = [];
264
+
265
+ if (spec.type === 'bar') {
266
+ const group = band * 0.68;
267
+ const each = spec.stacked ? group : group / Math.max(1, spec.y.length);
268
+ matrix.forEach((row, i) => {
269
+ const start = plot.x + band * i + (band - group) / 2;
270
+ let up = 0;
271
+ let down = 0;
272
+ row.forEach((value, series) => {
273
+ if (value === null) return;
274
+ let from: number;
275
+ let to: number;
276
+ if (spec.stacked) {
277
+ from = value >= 0 ? up : down;
278
+ to = from + value;
279
+ if (value >= 0) up = to;
280
+ else down = to;
281
+ } else {
282
+ from = 0;
283
+ to = value;
284
+ }
285
+ const y1 = yOf(Math.max(from, to));
286
+ const y2 = yOf(Math.min(from, to));
287
+ const x = round(spec.stacked ? start : start + each * series);
288
+ const width = round(Math.max(1, each - (spec.stacked ? 0 : 2)));
289
+ bars.push({ x, y: y1, width, height: round(Math.max(0, y2 - y1)), series, value });
290
+ if (spec.values && !spec.stacked) {
291
+ values.push({
292
+ text: formatChartValue(value, spec.format),
293
+ x: round(x + width / 2),
294
+ y: round(value >= 0 ? y1 - 3 : y2 + CHART_FONT_SIZE + 2),
295
+ anchor: 'middle',
296
+ });
297
+ }
298
+ });
299
+ if (spec.values && spec.stacked) {
300
+ values.push({
301
+ text: formatChartValue(up + down, spec.format),
302
+ x: round(start + group / 2),
303
+ y: round(yOf(up) - 3),
304
+ anchor: 'middle',
305
+ });
306
+ }
307
+ });
308
+ } else {
309
+ spec.y.forEach((_, series) => {
310
+ const points = matrix.flatMap((row, i) => {
311
+ const value = row[series];
312
+ return value === null || value === undefined
313
+ ? []
314
+ : [{ x: round(plot.x + band * (i + 0.5)), y: yOf(value), value }];
315
+ });
316
+ lines.push({ series, points });
317
+ if (spec.values) {
318
+ for (const point of points) {
319
+ values.push({
320
+ text: formatChartValue(point.value, spec.format),
321
+ x: point.x,
322
+ y: round(point.y - 6),
323
+ anchor: 'middle',
324
+ });
325
+ }
326
+ }
327
+ });
328
+ }
329
+
330
+ return {
331
+ width: spec.width,
332
+ height: spec.height,
333
+ plot,
334
+ baseline: min <= 0 && max >= 0 ? yOf(0) : null,
335
+ ticks,
336
+ categories: categoryLabels,
337
+ bars,
338
+ lines,
339
+ slices: [],
340
+ legend: spec.y.length > 1 ? legendRow(names, plot.x, 6 + CHART_FONT_SIZE * 0.8) : [],
341
+ values,
342
+ };
343
+ }
@@ -17,13 +17,3 @@ export function coverContent(doc: DocModule | null | undefined): ReactNode {
17
17
  blockIndices: entry.blocks.map((_, index) => index),
18
18
  });
19
19
  }
20
-
21
- /** "9 pages" for fixed docs; flow docs read "3 sections" until they are opened. */
22
- export function pageCountLabel(doc: DocModule | null | undefined): string {
23
- const entries = (doc?.default as DocEntry[] | undefined) ?? [];
24
- if (entries.length === 0) return '0 pages';
25
- const flowCount = entries.filter(isFlowSection).length;
26
- if (flowCount === 0) return `${entries.length} pages`;
27
- const fixed = entries.length - flowCount;
28
- return fixed > 0 ? `${fixed} + flow` : 'flow';
29
- }
@@ -3,12 +3,15 @@ import {
3
3
  docIds as ids,
4
4
  loadDoc as load,
5
5
  docThemes as themes,
6
+ docTitles as titles,
6
7
  } from 'virtual:open-doc/docs';
7
8
  import type { DocModule } from './sdk';
8
9
 
9
10
  export const docIds: string[] = ids;
10
11
  export const docCreatedAt: Record<string, number> = createdAt;
11
12
  export const docThemes: Record<string, string> = themes;
13
+ /** Titles read from `meta` at build time — for search and sorting, before any document loads. */
14
+ export const docTitles: Record<string, string> = titles;
12
15
 
13
16
  export function docsByTheme(themeId: string): string[] {
14
17
  return docIds.filter((id) => docThemes[id] === themeId);
@@ -58,7 +58,7 @@ export type WalkResult = {
58
58
  footnotes: Array<{ id: number; paragraphs: Paragraph[] }>;
59
59
  images: ImagePart[];
60
60
  lists: Array<'bullet' | 'decimal'>;
61
- finalFooter: boolean;
61
+ finalRunning: boolean;
62
62
  };
63
63
 
64
64
  type Ctx = WalkOptions & {
@@ -735,7 +735,7 @@ export async function docxFromPages(
735
735
  page: { top: 0, bottom: 0, fixed: true, first: true },
736
736
  };
737
737
  const blocks: Block[] = [];
738
- let previousFooter = true;
738
+ let previousRunning = true;
739
739
 
740
740
  for (const [index, host] of hosts.entries()) {
741
741
  const info = pages[index] ?? { continues: false };
@@ -793,15 +793,15 @@ export async function docxFromPages(
793
793
  }
794
794
  }
795
795
  }
796
- // Flow pages carry the section footer; a fixed sheet prints its own
797
- // running lines, so it sits in a section without one. The section break
798
- // itself starts the next page.
799
- const footer = !ctx.page.fixed;
800
- const breaksSection = own.length > 0 && blocks.length > 0 && footer !== previousFooter;
796
+ // 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;
801
801
  if (breaksSection) {
802
802
  const last = blocks[blocks.length - 1];
803
803
  if (last?.type === 'paragraph' && !last.sectionEnd) {
804
- last.sectionEnd = { footer: previousFooter };
804
+ last.sectionEnd = { running: previousRunning };
805
805
  } else {
806
806
  blocks.push({
807
807
  type: 'paragraph',
@@ -809,7 +809,7 @@ export async function docxFromPages(
809
809
  spacingBefore: 0,
810
810
  spacingAfter: 0,
811
811
  lineExact: 20,
812
- sectionEnd: { footer: previousFooter },
812
+ sectionEnd: { running: previousRunning },
813
813
  });
814
814
  }
815
815
  }
@@ -835,7 +835,7 @@ export async function docxFromPages(
835
835
  });
836
836
  }
837
837
  }
838
- if (own.length > 0) previousFooter = footer;
838
+ if (own.length > 0) previousRunning = running;
839
839
  blocks.push(...own);
840
840
  }
841
841
 
@@ -856,7 +856,7 @@ export async function docxFromPages(
856
856
  });
857
857
  }
858
858
 
859
- return { blocks, footnotes, images: ctx.images, lists: ctx.lists, finalFooter: previousFooter };
859
+ return { blocks, footnotes, images: ctx.images, lists: ctx.lists, finalRunning: previousRunning };
860
860
  }
861
861
 
862
862
  /** Runs for one element — the footer the orchestrator renders on its own. */
@@ -145,31 +145,47 @@ describe('buildDocxParts', () => {
145
145
  expect(text('[Content_Types].xml')).toContain('/word/fontTable.xml');
146
146
  });
147
147
 
148
- it('keeps the footer off sections that end without one', () => {
148
+ it('keeps the running header and footer off sections that end without them', () => {
149
149
  const sectioned = buildDocxParts({
150
150
  ...MODEL,
151
+ header: {
152
+ type: 'paragraph',
153
+ inlines: [
154
+ { type: 'text', text: 'Running head · ' },
155
+ { type: 'field', instr: 'PAGE', cached: '1' },
156
+ ],
157
+ },
151
158
  blocks: [
152
159
  {
153
160
  type: 'paragraph',
154
161
  inlines: [{ type: 'text', text: 'Cover' }],
155
- sectionEnd: { footer: false },
162
+ sectionEnd: { running: false },
156
163
  },
157
164
  { type: 'paragraph', inlines: [{ type: 'text', text: 'Body' }] },
158
165
  ],
159
166
  });
160
167
  const doc = sectioned['word/document.xml'] as string;
161
168
  const rels = sectioned['word/_rels/document.xml.rels'] as string;
162
- const bare = rels.match(/Id="(rId\d+)"[^>]*Target="footer2\.xml"/)?.[1];
163
- const full = rels.match(/Id="(rId\d+)"[^>]*Target="footer1\.xml"/)?.[1];
169
+ const id = (target: string) =>
170
+ rels.match(new RegExp(`Id="(rId\\d+)"[^>]*Target="${target}"`))?.[1];
171
+ const refs = (header?: string, footer?: string) =>
172
+ `<w:sectPr><w:headerReference w:type="default" r:id="${header}"/><w:footerReference w:type="default" r:id="${footer}"/>`;
164
173
  // The paragraph that ends a section holds its properties, ahead of its text.
165
- expect(doc).toMatch(
166
- new RegExp(`<w:sectPr><w:footerReference w:type="default" r:id="${bare}"/>.*?Cover`),
167
- );
168
- expect(doc).toMatch(
169
- new RegExp(`Body.*<w:sectPr><w:footerReference w:type="default" r:id="${full}"/>`),
174
+ expect(doc).toContain(`${refs(id('header2.xml'), id('footer2.xml'))}`);
175
+ expect(doc.indexOf(refs(id('header2.xml'), id('footer2.xml')))).toBeLessThan(
176
+ doc.indexOf('Cover'),
170
177
  );
178
+ expect(doc).toMatch(new RegExp(`Body.*${refs(id('header1.xml'), id('footer1.xml'))}`));
179
+ expect(sectioned['word/header1.xml']).toContain('<w:hdr');
180
+ expect(sectioned['word/header1.xml']).toContain('<w:pStyle w:val="Header"/>');
181
+ expect(sectioned['word/header1.xml']).toContain('<w:fldSimple w:instr=" PAGE ">');
182
+ expect(sectioned['word/header2.xml']).toContain('<w:hdr');
171
183
  expect(sectioned['word/footer2.xml']).toContain('<w:ftr');
184
+ expect(sectioned['[Content_Types].xml']).toContain(
185
+ '<Override PartName="/word/header1.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml"/>',
186
+ );
172
187
  expect(parts['word/footer2.xml']).toBeUndefined();
188
+ expect(parts['word/header1.xml']).toBeUndefined();
173
189
  });
174
190
 
175
191
  it('shades a cell and keeps code out of the spelling check', () => {
@@ -75,11 +75,12 @@ export type Paragraph = {
75
75
  /** An exact line height, twips — a spacer that holds open a gap. */
76
76
  lineExact?: number;
77
77
  /**
78
- * Ends a section here — whether that section's pages carry the footer.
78
+ * Ends a section here — whether that section's pages carry the running
79
+ * header and footer.
79
80
  * Fixed sheets print their own running lines, so they sit in sections
80
81
  * without one.
81
82
  */
82
- sectionEnd?: { footer: boolean };
83
+ sectionEnd?: { running: boolean };
83
84
  /** Right-aligned tab stop, twips from the left margin — a footer's page number. */
84
85
  rightTab?: number;
85
86
  /** Dots leading to the right tab, as a contents entry has. */
@@ -161,9 +162,10 @@ export type DocxModel = {
161
162
  line: number;
162
163
  blocks: Block[];
163
164
  footnotes: Array<{ id: number; paragraphs: Paragraph[] }>;
165
+ header?: Paragraph;
164
166
  footer?: Paragraph;
165
- /** Whether the last section carries the footer. Defaults to true. */
166
- finalFooter?: boolean;
167
+ /** Whether the last section carries the header and footer. Defaults to true. */
168
+ finalRunning?: boolean;
167
169
  images: ImagePart[];
168
170
  /** One entry per list; ordered lists restart at 1 each. */
169
171
  lists: Array<'bullet' | 'decimal'>;
@@ -283,8 +285,8 @@ type WriteContext = {
283
285
  imageIds: Map<string, string>;
284
286
  drawingId: { value: number };
285
287
  bookmarkId?: { value: number };
286
- /** A section's properties, with or without the footer. */
287
- section?: (footer: boolean) => string;
288
+ /** A section's properties, with or without the running header and footer. */
289
+ section?: (running: boolean) => string;
288
290
  };
289
291
 
290
292
  const REL_HYPERLINK =
@@ -425,7 +427,7 @@ export function paragraphXml(paragraph: Paragraph, ctx: WriteContext): string {
425
427
  props.push(`<w:ind w:left="${Math.round(paragraph.indent)}"/>`);
426
428
  if (paragraph.align && paragraph.align !== 'left')
427
429
  props.push(`<w:jc w:val="${paragraph.align}"/>`);
428
- if (paragraph.sectionEnd && ctx.section) props.push(ctx.section(paragraph.sectionEnd.footer));
430
+ if (paragraph.sectionEnd && ctx.section) props.push(ctx.section(paragraph.sectionEnd.running));
429
431
  const pPr = props.length > 0 ? `<w:pPr>${props.join('')}</w:pPr>` : '';
430
432
  const runs = paragraph.inlines.map((inline) => inlineXml(inline, ctx)).join('');
431
433
  if (!paragraph.bookmark) return `<w:p>${pPr}${runs}</w:p>`;
@@ -562,6 +564,7 @@ function stylesXml(model: DocxModel): string {
562
564
  `<w:style w:type="paragraph" w:styleId="FootnoteText"><w:name w:val="footnote text"/><w:basedOn w:val="Normal"/><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:rPr><w:color w:val="${colors.muted}"/><w:sz w:val="${sizes.caption}"/><w:szCs w:val="${sizes.caption}"/></w:rPr></w:style>` +
563
565
  '<w:style w:type="character" w:styleId="FootnoteReference"><w:name w:val="footnote reference"/><w:rPr><w:vertAlign w:val="superscript"/></w:rPr></w:style>' +
564
566
  `<w:style w:type="character" w:styleId="Hyperlink"><w:name w:val="Hyperlink"/><w:rPr><w:color w:val="${colors.accent}"/><w:u w:val="single"/></w:rPr></w:style>` +
567
+ `<w:style w:type="paragraph" w:styleId="Header"><w:name w:val="header"/><w:basedOn w:val="Normal"/><w:pPr><w:spacing w:after="0"/></w:pPr><w:rPr><w:color w:val="${colors.muted}"/><w:sz w:val="${sizes.caption}"/><w:szCs w:val="${sizes.caption}"/></w:rPr></w:style>` +
565
568
  `<w:style w:type="paragraph" w:styleId="Footer"><w:name w:val="footer"/><w:basedOn w:val="Normal"/><w:pPr><w:spacing w:after="0"/></w:pPr><w:rPr><w:color w:val="${colors.muted}"/><w:sz w:val="${sizes.caption}"/><w:szCs w:val="${sizes.caption}"/></w:rPr></w:style>` +
566
569
  `<w:style w:type="paragraph" w:styleId="TOCHeading"><w:name w:val="TOC Heading"/><w:basedOn w:val="Heading1"/><w:next w:val="Normal"/><w:pPr><w:outlineLvl w:val="9"/></w:pPr></w:style>` +
567
570
  toc(1) +
@@ -624,32 +627,38 @@ export function buildDocxParts(model: DocxModel): Record<string, string | Uint8A
624
627
  ],
625
628
  ] as const;
626
629
  for (const [type, target] of fixedRels) relFor(docCtx, type, target);
627
- const REL_FOOTER = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer';
628
- const footerRel = model.footer ? relFor(docCtx, REL_FOOTER, 'footer1.xml') : null;
629
- // A section with no footer reference inherits the one before it, so a
630
- // section meant to have none points at an empty footer instead.
631
- const bareFooter =
632
- footerRel &&
633
- (model.finalFooter === false ||
634
- model.blocks.some(
635
- (block) => block.type === 'paragraph' && block.sectionEnd?.footer === false,
636
- ));
637
- const bareRel = bareFooter ? relFor(docCtx, REL_FOOTER, 'footer2.xml') : null;
630
+ const REL_BASE = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships';
631
+ // A section with no header or footer reference inherits the one before it,
632
+ // so a section meant to have none points at an empty part instead.
633
+ const bare =
634
+ model.finalRunning === false ||
635
+ model.blocks.some((block) => block.type === 'paragraph' && block.sectionEnd?.running === false);
636
+ const running = (kind: 'header' | 'footer') => {
637
+ if (!model[kind]) return { full: null, bare: null };
638
+ return {
639
+ full: relFor(docCtx, `${REL_BASE}/${kind}`, `${kind}1.xml`),
640
+ bare: bare ? relFor(docCtx, `${REL_BASE}/${kind}`, `${kind}2.xml`) : null,
641
+ };
642
+ };
643
+ const headerRels = running('header');
644
+ const footerRels = running('footer');
638
645
 
639
646
  const { page } = model;
640
647
  const margin = Math.round(page.margin);
641
- docCtx.section = (footer) => {
642
- const rel = footer ? footerRel : bareRel;
648
+ docCtx.section = (on) => {
649
+ const header = on ? headerRels.full : headerRels.bare;
650
+ const footer = on ? footerRels.full : footerRels.bare;
643
651
  return (
644
652
  '<w:sectPr>' +
645
- (rel ? `<w:footerReference w:type="default" r:id="${rel}"/>` : '') +
653
+ (header ? `<w:headerReference w:type="default" r:id="${header}"/>` : '') +
654
+ (footer ? `<w:footerReference w:type="default" r:id="${footer}"/>` : '') +
646
655
  `<w:pgSz w:w="${Math.round(page.width)}" w:h="${Math.round(page.height)}"${page.landscape ? ' w:orient="landscape"' : ''}/>` +
647
656
  `<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"/>` +
648
657
  '</w:sectPr>'
649
658
  );
650
659
  };
651
660
  const body = model.blocks.map((block) => blockXml(block, docCtx)).join('');
652
- const sectPr = docCtx.section(model.finalFooter !== false);
661
+ const sectPr = docCtx.section(model.finalRunning !== false);
653
662
  const documentXml = `${XML_HEAD}<w:document ${NS}><w:body>${body}${sectPr}</w:body></w:document>`;
654
663
 
655
664
  // Footnotes and the footer are parts of their own, with their own rels.
@@ -678,10 +687,26 @@ export function buildDocxParts(model: DocxModel): Record<string, string | Uint8A
678
687
  '<w:footnote w:type="continuationSeparator" w:id="0"><w:p><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:continuationSeparator/></w:r></w:p></w:footnote>' +
679
688
  `${notes}</w:footnotes>`;
680
689
 
681
- const footerCtx: WriteContext = { model, rels: [], imageIds: new Map(), drawingId };
682
- const footerXml = model.footer
683
- ? `${XML_HEAD}<w:ftr ${NS}>${paragraphXml({ ...model.footer, style: model.footer.style ?? ('Footer' as StyleId) }, footerCtx)}</w:ftr>`
684
- : null;
690
+ // The running header and footer: each a part with its own rels, plus an
691
+ // empty twin for the sections that carry none.
692
+ const runningParts: Record<string, string> = {};
693
+ const runningTypes: string[] = [];
694
+ for (const [kind, rels, tag, style] of [
695
+ ['header', headerRels, 'hdr', 'Header'],
696
+ ['footer', footerRels, 'ftr', 'Footer'],
697
+ ] as const) {
698
+ const line = model[kind];
699
+ if (!line || !rels.full) continue;
700
+ const ctx: WriteContext = { model, rels: [], imageIds: new Map(), drawingId };
701
+ runningParts[`word/${kind}1.xml`] =
702
+ `${XML_HEAD}<w:${tag} ${NS}>${paragraphXml({ ...line, style: line.style ?? (style as StyleId) }, ctx)}</w:${tag}>`;
703
+ if (ctx.rels.length > 0) runningParts[`word/_rels/${kind}1.xml.rels`] = relsXml(ctx.rels);
704
+ runningTypes.push(`/word/${kind}1.xml|${kind}`);
705
+ if (rels.bare) {
706
+ runningParts[`word/${kind}2.xml`] = `${XML_HEAD}<w:${tag} ${NS}><w:p/></w:${tag}>`;
707
+ runningTypes.push(`/word/${kind}2.xml|${kind}`);
708
+ }
709
+ }
685
710
 
686
711
  const settingsXml =
687
712
  `${XML_HEAD}<w:settings ${NS}>` +
@@ -717,12 +742,12 @@ export function buildDocxParts(model: DocxModel): Record<string, string | Uint8A
717
742
  '<Override PartName="/word/footnotes.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml"/>' +
718
743
  '<Override PartName="/word/numbering.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml"/>' +
719
744
  '<Override PartName="/word/fontTable.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml"/>' +
720
- (footerXml
721
- ? '<Override PartName="/word/footer1.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml"/>'
722
- : '') +
723
- (bareRel
724
- ? '<Override PartName="/word/footer2.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml"/>'
725
- : '') +
745
+ runningTypes
746
+ .map((entry) => {
747
+ const [part, kind] = entry.split('|');
748
+ return `<Override PartName="${part}" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.${kind}+xml"/>`;
749
+ })
750
+ .join('') +
726
751
  '<Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>' +
727
752
  '</Types>';
728
753
 
@@ -745,11 +770,7 @@ export function buildDocxParts(model: DocxModel): Record<string, string | Uint8A
745
770
  'word/footnotes.xml': footnotesXml,
746
771
  };
747
772
  if (noteCtx.rels.length > 0) parts['word/_rels/footnotes.xml.rels'] = relsXml(noteCtx.rels);
748
- if (footerXml) {
749
- parts['word/footer1.xml'] = footerXml;
750
- if (footerCtx.rels.length > 0) parts['word/_rels/footer1.xml.rels'] = relsXml(footerCtx.rels);
751
- }
752
- if (bareRel) parts['word/footer2.xml'] = `${XML_HEAD}<w:ftr ${NS}><w:p/></w:ftr>`;
773
+ Object.assign(parts, runningParts);
753
774
  for (const image of model.images) parts[`word/media/${image.name}.${image.ext}`] = image.bytes;
754
775
  return parts;
755
776
  }