@open-document/core 0.2.0 → 0.3.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 (46) hide show
  1. package/dist/{build-U81g9Hnk.js → build-C3pMGxJN.js} +1 -1
  2. package/dist/check-Dtwb1wvU.js +42 -0
  3. package/dist/cli/bin.js +24 -3
  4. package/dist/config-Dg1AMP0r.js +2461 -0
  5. package/dist/context-FoX0afRf.js +26 -0
  6. package/dist/{dev-DwwFT6uX.js → dev-Cdd7NZRQ.js} +1 -1
  7. package/dist/diagram-xlVDekYk.js +763 -0
  8. package/dist/export-ClJ4T1uU.js +36 -0
  9. package/dist/import-D7Psi8WK.js +25 -0
  10. package/dist/index.d.ts +235 -90
  11. package/dist/index.js +515 -49
  12. package/dist/ops/index.d.ts +96 -1
  13. package/dist/ops/index.js +3 -199
  14. package/dist/ops-Ci5Xw6QG.js +1270 -0
  15. package/dist/{preview-C_jbySle.js → preview-BhbCiAKC.js} +1 -1
  16. package/dist/sdk-CWMsH9Ms.d.ts +123 -0
  17. package/dist/vite/index.d.ts +6 -0
  18. package/dist/vite/index.js +1 -2
  19. package/env.d.ts +33 -1
  20. package/package.json +10 -1
  21. package/skills/create-doc/SKILL.md +6 -2
  22. package/skills/doc-authoring/SKILL.md +79 -0
  23. package/skills/doc-authoring/references/long-form.md +131 -0
  24. package/src/app/components/data-table.tsx +196 -0
  25. package/src/app/components/diagram.tsx +76 -0
  26. package/src/app/components/flow-page.tsx +20 -3
  27. package/src/app/components/footnote.tsx +196 -0
  28. package/src/app/components/numbering.tsx +208 -0
  29. package/src/app/lib/agent-bridge.ts +128 -0
  30. package/src/app/lib/diagnostics.ts +282 -0
  31. package/src/app/lib/export-html.ts +35 -11
  32. package/src/app/lib/export-pdf.ts +54 -19
  33. package/src/app/lib/flow-measure.ts +100 -31
  34. package/src/app/lib/flow.test.ts +46 -0
  35. package/src/app/lib/flow.ts +28 -3
  36. package/src/app/lib/footnotes.test.tsx +102 -0
  37. package/src/app/lib/footnotes.ts +94 -0
  38. package/src/app/lib/labels.ts +175 -0
  39. package/src/app/lib/page-context.tsx +6 -1
  40. package/src/app/lib/scan.ts +26 -0
  41. package/src/app/lib/sdk.ts +3 -0
  42. package/src/app/lib/use-doc-pages.ts +50 -15
  43. package/src/app/routes/doc.tsx +7 -4
  44. package/dist/config-8zkUElGq.js +0 -1169
  45. package/dist/design-IyRSwCtK.js +0 -52
  46. package/dist/edit-ops-D2W2plpc.js +0 -1190
@@ -1,9 +1,10 @@
1
1
  import { createElement } from 'react';
2
2
  import { createRoot, type Root } from 'react-dom/client';
3
3
  import { designToCssVars } from './design';
4
- import { collectOutline, getOutline, PAGE_ATTR, PAGE_INDEX_ATTR, setOutline } from './outline';
4
+ import { PAGE_ATTR, PAGE_INDEX_ATTR } from './outline';
5
5
  import { DocPageProvider } from './page-context';
6
6
  import { nextFrame, waitForFonts, waitForImages } from './print-ready';
7
+ import { captureScan, restoreScan, scanDocument } from './scan';
7
8
  import { type DocModule, type PageGeometry, resolvePageGeometry } from './sdk';
8
9
  import type { ExpandedPage } from './use-doc-pages';
9
10
 
@@ -11,12 +12,23 @@ type AssetEntry = { name: string; bytes: Uint8Array };
11
12
 
12
13
  const ASSET_EXT_RE = /\.(?:png|jpe?g|gif|svg|webp|avif|woff2?|ttf|otf)(?:\?[^#]*)?(?:#.*)?$/i;
13
14
 
14
- export async function exportDocAsHtml(
15
+ export type HtmlBundle = {
16
+ filename: string;
17
+ mimeType: 'text/html' | 'application/zip';
18
+ bytes: Uint8Array;
19
+ };
20
+
21
+ /**
22
+ * Serializes the document into a self-contained page — a plain `.html` when
23
+ * nothing is referenced, a zip alongside its assets when something is. The
24
+ * browser downloads it; the headless exporter writes it to disk.
25
+ */
26
+ export async function buildDocHtmlBundle(
15
27
  doc: DocModule,
16
28
  docId: string,
17
29
  pages: ExpandedPage[],
18
- ): Promise<void> {
19
- if (pages.length === 0) return;
30
+ ): Promise<HtmlBundle | null> {
31
+ if (pages.length === 0) return null;
20
32
 
21
33
  const title = doc.meta?.title ?? docId;
22
34
  const geometry = resolvePageGeometry(doc.meta);
@@ -53,8 +65,7 @@ export async function exportDocAsHtml(
53
65
  const htmlBytes = new TextEncoder().encode(html);
54
66
 
55
67
  if (assets.size === 0) {
56
- downloadBlob(new Blob([htmlBytes as BlobPart], { type: 'text/html' }), `${docId}.html`);
57
- return;
68
+ return { filename: `${docId}.html`, mimeType: 'text/html', bytes: htmlBytes };
58
69
  }
59
70
 
60
71
  const { zipSync } = await import('fflate');
@@ -65,8 +76,21 @@ export async function exportDocAsHtml(
65
76
  for (const { name, bytes } of assets.values()) {
66
77
  (zipTree.assets as Record<string, Uint8Array>)[name] = bytes;
67
78
  }
68
- const zipped = zipSync(zipTree as Parameters<typeof zipSync>[0]);
69
- downloadBlob(new Blob([zipped as BlobPart], { type: 'application/zip' }), `${docId}.zip`);
79
+ return {
80
+ filename: `${docId}.zip`,
81
+ mimeType: 'application/zip',
82
+ bytes: zipSync(zipTree as Parameters<typeof zipSync>[0]),
83
+ };
84
+ }
85
+
86
+ export async function exportDocAsHtml(
87
+ doc: DocModule,
88
+ docId: string,
89
+ pages: ExpandedPage[],
90
+ ): Promise<void> {
91
+ const bundle = await buildDocHtmlBundle(doc, docId, pages);
92
+ if (!bundle) return;
93
+ downloadBlob(new Blob([bundle.bytes as BlobPart], { type: bundle.mimeType }), bundle.filename);
70
94
  }
71
95
 
72
96
  async function renderPagesToHtml(
@@ -87,7 +111,7 @@ async function renderPagesToHtml(
87
111
  const designVars = doc.design ? designToCssVars(doc.design) : null;
88
112
  const roots: Root[] = [];
89
113
  const hosts: HTMLElement[] = [];
90
- const previousOutline = getOutline();
114
+ const previousScan = captureScan();
91
115
 
92
116
  try {
93
117
  for (let i = 0; i < pages.length; i++) {
@@ -111,7 +135,7 @@ async function renderPagesToHtml(
111
135
  await nextFrame();
112
136
  await waitForFonts();
113
137
  await waitForImages(container);
114
- setOutline(collectOutline(container));
138
+ scanDocument(container, doc.meta);
115
139
  await nextFrame();
116
140
  await nextFrame();
117
141
 
@@ -119,7 +143,7 @@ async function renderPagesToHtml(
119
143
  } finally {
120
144
  for (const root of roots) root.unmount();
121
145
  container.remove();
122
- setOutline(previousOutline);
146
+ restoreScan(previousScan);
123
147
  }
124
148
  }
125
149
 
@@ -1,13 +1,15 @@
1
1
  import { createElement } from 'react';
2
2
  import { createRoot, type Root } from 'react-dom/client';
3
3
  import { designToCssVars } from './design';
4
- import { collectOutline, getOutline, PAGE_ATTR, PAGE_INDEX_ATTR, setOutline } from './outline';
4
+ import { PAGE_ATTR, PAGE_INDEX_ATTR } from './outline';
5
5
  import { DocPageProvider } from './page-context';
6
6
  import { nextFrame, sleep, waitForDataWaitfor, waitForFonts, waitForImages } from './print-ready';
7
+ import { captureScan, restoreScan, scanDocument } from './scan';
7
8
  import { type DocModule, resolvePageGeometry } from './sdk';
8
9
  import type { ExpandedPage } from './use-doc-pages';
9
10
 
10
- const PRINT_ROOT_ID = 'od-print-root';
11
+ export const PRINT_ROOT_ID = 'od-print-root';
12
+ export const PRINT_PAGE_CLASS = 'od-print-page';
11
13
  const PRINT_STYLE_ID = 'od-print-style';
12
14
 
13
15
  function printStyles(geometry: { width: number; height: number; css: string }): string {
@@ -38,7 +40,7 @@ function printStyles(geometry: { width: number; height: number; css: string }):
38
40
  pointer-events: auto !important;
39
41
  background: #fff !important;
40
42
  }
41
- #${PRINT_ROOT_ID} .od-print-page {
43
+ #${PRINT_ROOT_ID} .${PRINT_PAGE_CLASS} {
42
44
  width: ${geometry.width}px !important;
43
45
  height: ${geometry.height}px !important;
44
46
  overflow: hidden;
@@ -50,7 +52,7 @@ function printStyles(geometry: { width: number; height: number; css: string }):
50
52
  -webkit-print-color-adjust: exact;
51
53
  print-color-adjust: exact;
52
54
  }
53
- #${PRINT_ROOT_ID} .od-print-page:last-child {
55
+ #${PRINT_ROOT_ID} .${PRINT_PAGE_CLASS}:last-child {
54
56
  page-break-after: auto;
55
57
  break-after: auto;
56
58
  }
@@ -70,14 +72,24 @@ export type PdfExportProgress = {
70
72
  percent: number;
71
73
  };
72
74
 
73
- export async function exportDocAsPdf(
75
+ export type PrintCopy = {
76
+ /** The offscreen container holding one `.od-print-page` per sheet, at true size. */
77
+ root: HTMLElement;
78
+ dispose: () => void;
79
+ };
80
+
81
+ /**
82
+ * Renders every page into an offscreen copy laid out at the real sheet size,
83
+ * with the print stylesheet installed. Callers decide what to do with it —
84
+ * hand it to the print engine, screenshot it, or measure it — and must call
85
+ * `dispose()` when done.
86
+ */
87
+ export async function mountPrintCopy(
74
88
  doc: DocModule,
75
89
  docId: string,
76
90
  pages: ExpandedPage[],
77
91
  onProgress?: (progress: PdfExportProgress) => void,
78
- ): Promise<void> {
79
- if (pages.length === 0) return;
80
-
92
+ ): Promise<PrintCopy> {
81
93
  const total = pages.length;
82
94
  const geometry = resolvePageGeometry(doc.meta);
83
95
  onProgress?.({ phase: 'rendering', current: 0, total, percent: 0 });
@@ -99,7 +111,7 @@ export async function exportDocAsPdf(
99
111
  const page = pages[i];
100
112
  if (!page) continue;
101
113
  const host = document.createElement('div');
102
- host.className = 'od-print-page';
114
+ host.className = PRINT_PAGE_CLASS;
103
115
  host.setAttribute(PAGE_ATTR, '');
104
116
  host.setAttribute(PAGE_INDEX_ATTR, String(i));
105
117
  host.style.width = `${geometry.width}px`;
@@ -122,33 +134,56 @@ export async function exportDocAsPdf(
122
134
  }
123
135
 
124
136
  const previousTitle = document.title;
125
- const previousOutline = getOutline();
137
+ const previousScan = captureScan();
126
138
  document.title = doc.meta?.title ?? docId;
127
139
 
140
+ const dispose = () => {
141
+ document.title = previousTitle;
142
+ for (const r of reactRoots) r.unmount();
143
+ root.remove();
144
+ style.remove();
145
+ restoreScan(previousScan);
146
+ };
147
+
128
148
  try {
129
149
  await nextFrame();
130
150
  await waitForFonts();
131
151
  await waitForImages(root);
132
152
  await waitForDataWaitfor(root);
133
153
 
134
- // A `<TableOfContents>` reads the outline store, which is only filled by a
135
- // DOM scan. Scan the print copy and let React commit the filled TOC before
136
- // handing the pages to the print engine.
137
- setOutline(collectOutline(root));
154
+ // A `<TableOfContents>`, a `<Ref>`, a figure's number: all of them read a
155
+ // store that only a DOM scan fills. Scan the print copy and let React commit
156
+ // the resolved values before handing the pages to whoever asked for them.
157
+ scanDocument(root, doc.meta);
138
158
  await nextFrame();
139
159
  await sleep(50);
160
+ } catch (err) {
161
+ dispose();
162
+ throw err;
163
+ }
140
164
 
165
+ return { root, dispose };
166
+ }
167
+
168
+ export async function exportDocAsPdf(
169
+ doc: DocModule,
170
+ docId: string,
171
+ pages: ExpandedPage[],
172
+ onProgress?: (progress: PdfExportProgress) => void,
173
+ ): Promise<void> {
174
+ if (pages.length === 0) return;
175
+
176
+ const total = pages.length;
177
+ const copy = await mountPrintCopy(doc, docId, pages, onProgress);
178
+
179
+ try {
141
180
  onProgress?.({ phase: 'printing', current: total, total, percent: 99 });
142
181
  const printDone = waitForAfterPrint();
143
182
  window.print();
144
183
  await printDone;
145
184
  } finally {
146
185
  onProgress?.({ phase: 'done', current: total, total, percent: 100 });
147
- document.title = previousTitle;
148
- for (const r of reactRoots) r.unmount();
149
- root.remove();
150
- style.remove();
151
- setOutline(previousOutline);
186
+ copy.dispose();
152
187
  }
153
188
  }
154
189
 
@@ -1,14 +1,24 @@
1
- import { createElement } from 'react';
1
+ import { createElement, type ReactNode } from 'react';
2
2
  import { createRoot } from 'react-dom/client';
3
3
  import { FLOW_BLOCK_ATTR, FlowBlock } from '../components/flow-page';
4
+ import { FOOTNOTE_AREA_MARGIN_TOP, FOOTNOTE_ROW_ATTR, Footnotes } from '../components/footnote';
4
5
  import { type DesignSystem, designToCssVars } from './design';
5
- import type { BlockMetrics, FlowSection } from './flow';
6
+ import type { BlockMetrics } from './flow';
7
+ import type { ExtractedNote } from './footnotes';
6
8
  import { nextFrame, waitForFonts } from './print-ready';
7
9
  import type { PageGeometry } from './sdk';
8
10
 
9
11
  const HEADING_TAGS = new Set(['H1', 'H2', 'H3', 'H4']);
10
12
 
11
- function metricsFor(el: HTMLElement, height: number): BlockMetrics {
13
+ /** A flow section reduced to what measurement needs: blocks, and their notes. */
14
+ export type MeasurableSection = {
15
+ blocks: ReactNode[];
16
+ /** Index-aligned with `blocks`. */
17
+ notesByBlock: ExtractedNote[][];
18
+ padding?: number;
19
+ };
20
+
21
+ function metricsFor(el: HTMLElement, height: number, footnoteHeight: number): BlockMetrics {
12
22
  const inner = el.firstElementChild;
13
23
  const tag = inner?.tagName ?? '';
14
24
  const declaredKeepNext = inner?.getAttribute('data-od-keep-with-next');
@@ -17,6 +27,7 @@ function metricsFor(el: HTMLElement, height: number): BlockMetrics {
17
27
 
18
28
  return {
19
29
  height,
30
+ footnoteHeight,
20
31
  // A heading alone at the bottom of a page is the most visible layout error
21
32
  // in a report, so headings glue to whatever follows them by default.
22
33
  keepWithNext: declaredKeepNext !== null ? declaredKeepNext !== 'false' : HEADING_TAGS.has(tag),
@@ -29,15 +40,39 @@ export type FlowMeasurement = {
29
40
  metrics: BlockMetrics[];
30
41
  /** Usable height of one page for this section. */
31
42
  available: number;
43
+ /** What a page's footnote area costs before its first note. */
44
+ footnoteOverhead: number;
32
45
  };
33
46
 
47
+ /**
48
+ * How much vertical space each node claims, measured from where the next one
49
+ * starts — which is what already accounts for collapsed margins.
50
+ *
51
+ * Offsets are taken relative to the container's own box, not `offsetTop`: every
52
+ * container shares one positioned host, so `offsetTop` is host-relative while
53
+ * the container's height is not, and mixing the two silently measures the last
54
+ * node of every container after the first as zero.
55
+ */
56
+ function stackedHeights(container: HTMLElement, selector: string): number[] {
57
+ const nodes = Array.from(container.querySelectorAll<HTMLElement>(selector));
58
+ const origin = container.getBoundingClientRect();
59
+ const tops = nodes.map((node) => node.getBoundingClientRect().top - origin.top);
60
+ return nodes.map((_, index) =>
61
+ Math.max(0, (index + 1 < tops.length ? tops[index + 1] : origin.height) - tops[index]),
62
+ );
63
+ }
64
+
34
65
  /**
35
66
  * Renders each section's blocks offscreen at the real page width and reads back
36
67
  * their stacked heights. Measuring the live DOM is the only way to know how a
37
68
  * paragraph wraps or how tall a table grew.
69
+ *
70
+ * Footnotes are measured in the same pass, in the component that prints them,
71
+ * because the space they claim at the foot of a page is space the packer must
72
+ * not hand to body content.
38
73
  */
39
74
  export async function measureFlowSections(
40
- sections: FlowSection[],
75
+ sections: MeasurableSection[],
41
76
  opts: { geometry: PageGeometry; design?: DesignSystem },
42
77
  ): Promise<FlowMeasurement[]> {
43
78
  if (sections.length === 0) return [];
@@ -55,29 +90,48 @@ export async function measureFlowSections(
55
90
 
56
91
  const designVars = opts.design ? designToCssVars(opts.design) : null;
57
92
  const roots: Array<ReturnType<typeof createRoot>> = [];
58
- const containers: HTMLElement[] = [];
93
+ const blockContainers: HTMLElement[] = [];
94
+ const noteContainers: Array<HTMLElement | null> = [];
95
+
96
+ const paddingOf = (section: MeasurableSection) => section.padding ?? opts.design?.margin ?? 76;
97
+
98
+ const makeContainer = (width: number): HTMLElement => {
99
+ const container = document.createElement('div');
100
+ container.style.width = `${width}px`;
101
+ container.style.fontFamily = 'var(--od-font-body)';
102
+ container.style.fontSize = 'var(--od-size-body)';
103
+ container.style.lineHeight = 'var(--od-leading)';
104
+ if (designVars) {
105
+ for (const [k, v] of Object.entries(designVars)) container.style.setProperty(k, v);
106
+ }
107
+ host.appendChild(container);
108
+ return container;
109
+ };
59
110
 
60
111
  try {
61
112
  for (const section of sections) {
62
- const padding = section.padding ?? opts.design?.margin ?? 76;
63
- const container = document.createElement('div');
64
- container.style.width = `${opts.geometry.width - padding * 2}px`;
65
- container.style.fontFamily = 'var(--od-font-body)';
66
- container.style.fontSize = 'var(--od-size-body)';
67
- container.style.lineHeight = 'var(--od-leading)';
68
- if (designVars) {
69
- for (const [k, v] of Object.entries(designVars)) container.style.setProperty(k, v);
70
- }
71
- host.appendChild(container);
72
- containers.push(container);
113
+ const width = opts.geometry.width - paddingOf(section) * 2;
73
114
 
74
- const root = createRoot(container);
75
- root.render(
115
+ const blocks = makeContainer(width);
116
+ blockContainers.push(blocks);
117
+ const blockRoot = createRoot(blocks);
118
+ blockRoot.render(
76
119
  section.blocks.map((block, index) =>
77
120
  createElement(FlowBlock, { key: index }, block),
78
- ) as unknown as Parameters<typeof root.render>[0],
121
+ ) as unknown as Parameters<typeof blockRoot.render>[0],
79
122
  );
80
- roots.push(root);
123
+ roots.push(blockRoot);
124
+
125
+ const allNotes = section.notesByBlock.flat();
126
+ if (allNotes.length === 0) {
127
+ noteContainers.push(null);
128
+ continue;
129
+ }
130
+ const notes = makeContainer(width);
131
+ noteContainers.push(notes);
132
+ const noteRoot = createRoot(notes);
133
+ noteRoot.render(createElement(Footnotes, { notes: allNotes }));
134
+ roots.push(noteRoot);
81
135
  }
82
136
 
83
137
  await nextFrame();
@@ -85,22 +139,37 @@ export async function measureFlowSections(
85
139
  await nextFrame();
86
140
 
87
141
  return sections.map((section, sectionIndex) => {
88
- const container = containers[sectionIndex];
89
- const padding = section.padding ?? opts.design?.margin ?? 76;
142
+ const padding = paddingOf(section);
143
+ const blocks = blockContainers[sectionIndex];
144
+ const blockHeights = stackedHeights(blocks, `:scope > [${FLOW_BLOCK_ATTR}]`);
145
+
146
+ const noteContainer = noteContainers[sectionIndex];
147
+ let rowHeights: number[] = [];
148
+ let footnoteOverhead = 0;
149
+ if (noteContainer) {
150
+ rowHeights = stackedHeights(noteContainer, `[${FOOTNOTE_ROW_ATTR}]`);
151
+ const area = noteContainer.getBoundingClientRect().height;
152
+ const rows = rowHeights.reduce((sum, height) => sum + height, 0);
153
+ footnoteOverhead = Math.max(0, area - rows) + FOOTNOTE_AREA_MARGIN_TOP;
154
+ }
155
+
156
+ let noteCursor = 0;
90
157
  const nodes = Array.from(
91
- container.querySelectorAll<HTMLElement>(`:scope > [${FLOW_BLOCK_ATTR}]`),
158
+ blocks.querySelectorAll<HTMLElement>(`:scope > [${FLOW_BLOCK_ATTR}]`),
92
159
  );
93
- const total = container.getBoundingClientRect().height;
94
- const tops = nodes.map((node) => node.offsetTop);
95
-
96
160
  const metrics = nodes.map((node, index) => {
97
- const next = index + 1 < tops.length ? tops[index + 1] : total;
98
- // Successive offsets already account for collapsed margins, which is
99
- // what actually decides where the next block starts.
100
- return metricsFor(node, Math.max(0, next - tops[index]));
161
+ const count = section.notesByBlock[index]?.length ?? 0;
162
+ let notesHeight = 0;
163
+ for (let i = 0; i < count; i++) notesHeight += rowHeights[noteCursor + i] ?? 0;
164
+ noteCursor += count;
165
+ return metricsFor(node, blockHeights[index] ?? 0, notesHeight);
101
166
  });
102
167
 
103
- return { metrics, available: opts.geometry.height - padding * 2 };
168
+ return {
169
+ metrics,
170
+ available: opts.geometry.height - padding * 2,
171
+ footnoteOverhead,
172
+ };
104
173
  });
105
174
  } finally {
106
175
  for (const root of roots) root.unmount();
@@ -62,3 +62,49 @@ describe('paginateBlocks', () => {
62
62
  expect(paginateBlocks([], 1000)).toEqual({ pages: [], overflowing: [] });
63
63
  });
64
64
  });
65
+
66
+ describe('paginateBlocks with footnotes', () => {
67
+ const block = (height: number, footnoteHeight = 0): BlockMetrics => ({ height, footnoteHeight });
68
+
69
+ it('gives a page less body room when its blocks carry notes', () => {
70
+ // Three 300px blocks fit 1000px on their own.
71
+ expect(paginateBlocks([block(300), block(300), block(300)], 1000).pages).toEqual([[0, 1, 2]]);
72
+
73
+ // Add 100px of notes to the first block plus 20px of area chrome and the
74
+ // third no longer fits: notes print on the page their marker landed on.
75
+ const withNotes = paginateBlocks([block(300, 100), block(300), block(300)], 1000, {
76
+ footnoteOverhead: 20,
77
+ });
78
+ expect(withNotes.pages).toEqual([[0, 1], [2]]);
79
+ });
80
+
81
+ it('charges the area chrome once per page, not once per note', () => {
82
+ const blocks = [block(300, 50), block(300, 50), block(300)];
83
+ // 900 body + 100 notes + 20 chrome = 1020 > 1000.
84
+ expect(paginateBlocks(blocks, 1000, { footnoteOverhead: 20 }).pages).toEqual([[0, 1], [2]]);
85
+ // Without the chrome it is exactly 1000 and all three stay together.
86
+ expect(paginateBlocks(blocks, 1000, { footnoteOverhead: 0 }).pages).toEqual([[0, 1, 2]]);
87
+ });
88
+
89
+ it('recomputes the notes budget for blocks that move to the next page', () => {
90
+ const blocks: BlockMetrics[] = [
91
+ { height: 300, footnoteHeight: 100 },
92
+ { height: 100, keepWithNext: true },
93
+ { height: 700 },
94
+ ];
95
+ const result = paginateBlocks(blocks, 1000, { footnoteOverhead: 20 });
96
+ // The heading travels with the block it introduces, and its page's budget
97
+ // is recomputed without the first block's notes.
98
+ expect(result.pages).toEqual([[0], [1, 2]]);
99
+ });
100
+
101
+ it('flags a block whose own notes make it taller than a page', () => {
102
+ const result = paginateBlocks([block(900, 200)], 1000, { footnoteOverhead: 20 });
103
+ expect(result.overflowing).toEqual([0]);
104
+ });
105
+
106
+ it('leaves documents without notes packing exactly as before', () => {
107
+ const blocks = [block(400), block(400), block(400)];
108
+ expect(paginateBlocks(blocks, 1000, { footnoteOverhead: 20 }).pages).toEqual([[0, 1], [2]]);
109
+ });
110
+ });
@@ -38,6 +38,8 @@ export function isFlowSection(entry: DocEntry): entry is FlowSection {
38
38
 
39
39
  export type BlockMetrics = {
40
40
  height: number;
41
+ /** Height this block's footnotes add to the foot of whatever page it lands on. */
42
+ footnoteHeight?: number;
41
43
  /** A heading must not be the last block on a page. */
42
44
  keepWithNext?: boolean;
43
45
  /** A caption must not open a page without the figure it belongs to. */
@@ -53,33 +55,54 @@ export type PaginationResult = {
53
55
  overflowing: number[];
54
56
  };
55
57
 
58
+ export type PaginateOptions = {
59
+ /** Rule and padding a page's footnote area costs before its first note. */
60
+ footnoteOverhead?: number;
61
+ };
62
+
56
63
  /**
57
64
  * Greedy top-to-bottom packing: fill a page until the next block would cross
58
65
  * the bottom edge, then push that block — plus anything glued to it — onto the
59
66
  * next page. Blocks are atomic; nothing is split mid-block.
67
+ *
68
+ * Footnotes are packed from the same budget: a block that carries notes brings
69
+ * their height with it, because those notes print at the foot of whichever page
70
+ * the block lands on.
60
71
  */
61
- export function paginateBlocks(blocks: BlockMetrics[], available: number): PaginationResult {
72
+ export function paginateBlocks(
73
+ blocks: BlockMetrics[],
74
+ available: number,
75
+ opts: PaginateOptions = {},
76
+ ): PaginationResult {
77
+ const overhead = opts.footnoteOverhead ?? 0;
62
78
  const pages: number[][] = [];
63
79
  const overflowing: number[] = [];
64
80
  let current: number[] = [];
65
81
  let used = 0;
82
+ let notes = 0;
66
83
 
67
84
  const heightOf = (indices: number[]) =>
68
85
  indices.reduce((sum, index) => sum + (blocks[index]?.height ?? 0), 0);
86
+ const notesOf = (indices: number[]) =>
87
+ indices.reduce((sum, index) => sum + (blocks[index]?.footnoteHeight ?? 0), 0);
88
+ /** A page with no notes pays nothing; the first note also pays for the rule. */
89
+ const reserve = (total: number) => (total > 0 ? total + overhead : 0);
69
90
 
70
91
  const closePage = () => {
71
92
  if (current.length === 0) return;
72
93
  pages.push(current);
73
94
  current = [];
74
95
  used = 0;
96
+ notes = 0;
75
97
  };
76
98
 
77
99
  blocks.forEach((block, index) => {
78
- if (block.height > available) overflowing.push(index);
100
+ const own = block.footnoteHeight ?? 0;
101
+ if (block.height + reserve(own) > available) overflowing.push(index);
79
102
 
80
103
  if (block.breakBefore) closePage();
81
104
 
82
- if (current.length > 0 && used + block.height > available) {
105
+ if (current.length > 0 && used + block.height + reserve(notes + own) > available) {
83
106
  // Everything glued to this block travels with it: trailing headings
84
107
  // (keep-with-next) and, when this block is a caption, its figure.
85
108
  let splitAt = current.length;
@@ -91,6 +114,7 @@ export function paginateBlocks(blocks: BlockMetrics[], available: number): Pagin
91
114
  pages.push(current.slice(0, splitAt));
92
115
  current = moved;
93
116
  used = heightOf(moved);
117
+ notes = notesOf(moved);
94
118
  } else {
95
119
  closePage();
96
120
  }
@@ -98,6 +122,7 @@ export function paginateBlocks(blocks: BlockMetrics[], available: number): Pagin
98
122
 
99
123
  current.push(index);
100
124
  used += block.height;
125
+ notes += own;
101
126
  });
102
127
 
103
128
  closePage();
@@ -0,0 +1,102 @@
1
+ import { createElement, isValidElement, type ReactNode } from 'react';
2
+ import { describe, expect, it } from 'vitest';
3
+ import { Footnote } from '../components/footnote';
4
+ import { extractBlockFootnotes, extractSectionFootnotes, notesForPage } from './footnotes';
5
+
6
+ function childrenOf(node: ReactNode): ReactNode {
7
+ return isValidElement(node) ? (node.props as { children?: ReactNode }).children : undefined;
8
+ }
9
+
10
+ describe('extractBlockFootnotes', () => {
11
+ it('lifts a note out and leaves a marker in its place', () => {
12
+ const block = (
13
+ <p>
14
+ A claim
15
+ <Footnote>Source: Q3 billing export.</Footnote>
16
+ and the rest.
17
+ </p>
18
+ );
19
+
20
+ const { node, notes } = extractBlockFootnotes(block, 'fn-0-0');
21
+ expect(notes).toHaveLength(1);
22
+ expect(notes[0].id).toBe('fn-0-0-1');
23
+ expect(notes[0].content).toBe('Source: Q3 billing export.');
24
+
25
+ const rendered = JSON.stringify(node, (key, value) => (key === 'type' ? undefined : value));
26
+ expect(rendered).not.toContain('Source: Q3 billing export.');
27
+ expect(node).not.toBe(block);
28
+ });
29
+
30
+ it('honours an author id so a Ref can point at the note', () => {
31
+ const { notes } = extractBlockFootnotes(
32
+ <p>
33
+ x<Footnote id="billing">note</Footnote>
34
+ </p>,
35
+ 'fn-0-0',
36
+ );
37
+ expect(notes[0].id).toBe('billing');
38
+ });
39
+
40
+ it('finds notes nested several elements deep', () => {
41
+ const { notes } = extractBlockFootnotes(
42
+ <div>
43
+ <ul>
44
+ <li>
45
+ one<Footnote>first</Footnote>
46
+ </li>
47
+ <li>
48
+ two<Footnote>second</Footnote>
49
+ </li>
50
+ </ul>
51
+ </div>,
52
+ 'fn-1-2',
53
+ );
54
+ expect(notes.map((note) => note.content)).toEqual(['first', 'second']);
55
+ expect(notes.map((note) => note.id)).toEqual(['fn-1-2-1', 'fn-1-2-2']);
56
+ });
57
+
58
+ it('returns the block untouched when it has no footnotes', () => {
59
+ const block = <p>Nothing to lift.</p>;
60
+ const { node, notes } = extractBlockFootnotes(block, 'fn-0-0');
61
+ expect(node).toBe(block);
62
+ expect(notes).toEqual([]);
63
+ });
64
+
65
+ it('leaves a render-prop child alone rather than walking into a function', () => {
66
+ const block = createElement('div', null, (() => null) as unknown as ReactNode);
67
+ expect(extractBlockFootnotes(block, 'fn-0-0').node).toBe(block);
68
+ });
69
+
70
+ it('keeps surrounding text intact', () => {
71
+ const { node } = extractBlockFootnotes(
72
+ <p>
73
+ before<Footnote>note</Footnote>after
74
+ </p>,
75
+ 'fn-0-0',
76
+ );
77
+ const children = childrenOf(node) as ReactNode[];
78
+ expect(children[0]).toBe('before');
79
+ expect(children[2]).toBe('after');
80
+ });
81
+ });
82
+
83
+ describe('extractSectionFootnotes', () => {
84
+ it('keeps notes index-aligned with their blocks', () => {
85
+ const prepared = extractSectionFootnotes(
86
+ [
87
+ <p key="a">plain</p>,
88
+ <p key="b">
89
+ x<Footnote>note</Footnote>
90
+ </p>,
91
+ ],
92
+ 0,
93
+ );
94
+ expect(prepared.notesByBlock[0]).toEqual([]);
95
+ expect(prepared.notesByBlock[1]).toHaveLength(1);
96
+ });
97
+
98
+ it('collects only the notes belonging to a page', () => {
99
+ const notesByBlock = [[{ id: 'a', content: 'A' }], [], [{ id: 'c', content: 'C' }]];
100
+ expect(notesForPage(notesByBlock, [1, 2]).map((note) => note.id)).toEqual(['c']);
101
+ });
102
+ });