@open-document/core 0.11.0 → 0.13.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 (105) hide show
  1. package/dist/{build-BHFGY8eF.js → build-CbgIk6bA.js} +1 -1
  2. package/dist/{check-UEBmDfT_.js → check-BTroj-5Z.js} +3 -3
  3. package/dist/cli/bin.js +58 -34
  4. package/dist/config-BWtOZ1jc.d.ts +45 -0
  5. package/dist/{config-B_pdNbYg.js → config-DKKNIbvO.js} +1458 -983
  6. package/dist/{context-BM9_-u9P.js → context-DXNP8v9I.js} +3 -2
  7. package/dist/deploy-gcp-BUiSuqz7.js +758 -0
  8. package/dist/{dev-DX3QMIRi.js → dev-YXumw5iX.js} +1 -1
  9. package/dist/{diagram-BK4jTZr4.js → diagram-CKf3ptOE.js} +293 -13
  10. package/dist/{diff-DayvbXfX.js → diff-CTFfU4Tz.js} +2 -2
  11. package/dist/{export-BPsXj1i6.js → export-D2QLtF84.js} +11 -4
  12. package/dist/flow-CS5apebG.d.ts +252 -0
  13. package/dist/{import-71wlAsrd.js → import-CcmrFetU.js} +3 -2
  14. package/dist/index.d.ts +155 -59
  15. package/dist/index.js +945 -104
  16. package/dist/open-doc-plugin-DnX5usgI.js +320 -0
  17. package/dist/ops/index.d.ts +112 -3
  18. package/dist/ops/index.js +3 -3
  19. package/dist/{ops-BUo67DaP.js → ops-DmEecq1k.js} +86 -164
  20. package/dist/package-version-C89gtYSk.js +36 -0
  21. package/dist/{preview-D3m1-gUL.js → preview-_mHpBhMk.js} +1 -1
  22. package/dist/templates-MMblHwmT.js +34 -0
  23. package/dist/vite/index.d.ts +1 -1
  24. package/dist/vite/index.js +2 -1
  25. package/package.json +2 -1
  26. package/skills/apply-comments/SKILL.md +3 -1
  27. package/skills/create-doc/SKILL.md +2 -0
  28. package/skills/doc-authoring/SKILL.md +17 -16
  29. package/skills/doc-authoring/references/long-form.md +43 -2
  30. package/skills/doc-authoring/references/pagination.md +14 -2
  31. package/skills/doc-authoring/references/tables-and-charts.md +21 -17
  32. package/src/app/components/browser/browser-ui.tsx +21 -0
  33. package/src/app/components/browser/new-document-dialog.tsx +208 -0
  34. package/src/app/components/callout.tsx +101 -0
  35. package/src/app/components/changes/changes-overlay.tsx +68 -0
  36. package/src/app/components/changes/changes-panel.tsx +341 -0
  37. package/src/app/components/changes/use-changes.ts +85 -0
  38. package/src/app/components/chart.tsx +191 -33
  39. package/src/app/components/code-block.tsx +249 -0
  40. package/src/app/components/comments/comments-overlay.tsx +50 -0
  41. package/src/app/components/comments/comments-panel.tsx +272 -0
  42. package/src/app/components/comments/use-comments.ts +61 -0
  43. package/src/app/components/data-table.tsx +146 -18
  44. package/src/app/components/doc-sidebar.tsx +32 -2
  45. package/src/app/components/flow-page.tsx +57 -8
  46. package/src/app/components/inspector/field-source.tsx +41 -0
  47. package/src/app/components/inspector/inspector.tsx +64 -65
  48. package/src/app/components/numbering.tsx +226 -12
  49. package/src/app/components/overlay-frame.tsx +79 -0
  50. package/src/app/components/page-frame.tsx +46 -0
  51. package/src/app/components/page-placement.ts +68 -0
  52. package/src/app/components/record-picker.tsx +79 -0
  53. package/src/app/components/themes/theme-preview.tsx +5 -4
  54. package/src/app/lib/agent-bridge.ts +29 -1
  55. package/src/app/lib/chart.test.ts +15 -0
  56. package/src/app/lib/chart.ts +134 -9
  57. package/src/app/lib/diagnostics.ts +45 -1
  58. package/src/app/lib/docx/ooxml.test.ts +24 -1
  59. package/src/app/lib/docx/ooxml.ts +27 -1
  60. package/src/app/lib/export-docx.ts +3 -1
  61. package/src/app/lib/export-dom.ts +17 -3
  62. package/src/app/lib/export-html.ts +4 -2
  63. package/src/app/lib/export-image.ts +2 -1
  64. package/src/app/lib/export-pdf.ts +9 -1
  65. package/src/app/lib/flow-measure.test.ts +30 -0
  66. package/src/app/lib/flow-measure.ts +68 -14
  67. package/src/app/lib/flow.test.ts +20 -1
  68. package/src/app/lib/flow.ts +120 -20
  69. package/src/app/lib/i18n-ja/browser.ts +10 -0
  70. package/src/app/lib/i18n-ja/doc.ts +4 -0
  71. package/src/app/lib/i18n-ja/panels.ts +40 -0
  72. package/src/app/lib/i18n-ko/browser.ts +10 -0
  73. package/src/app/lib/i18n-ko/doc.ts +4 -0
  74. package/src/app/lib/i18n-ko/panels.ts +39 -0
  75. package/src/app/lib/i18n-zh-cn/browser.ts +10 -0
  76. package/src/app/lib/i18n-zh-cn/doc.ts +4 -0
  77. package/src/app/lib/i18n-zh-cn/panels.ts +38 -0
  78. package/src/app/lib/i18n-zh-tw/browser.ts +10 -0
  79. package/src/app/lib/i18n-zh-tw/doc.ts +4 -0
  80. package/src/app/lib/i18n-zh-tw/panels.ts +38 -0
  81. package/src/app/lib/labels.ts +29 -10
  82. package/src/app/lib/records.test.ts +38 -0
  83. package/src/app/lib/records.ts +127 -0
  84. package/src/app/lib/sdk.ts +35 -0
  85. package/src/app/lib/use-doc-module.ts +7 -0
  86. package/src/app/lib/use-doc-pages.ts +38 -17
  87. package/src/app/routes/doc.tsx +275 -13
  88. package/src/app/routes/home.tsx +30 -5
  89. package/src/app/styles.css +23 -0
  90. package/templates/blank/index.tsx +63 -0
  91. package/templates/blank/template.json +6 -0
  92. package/templates/certificate/data/recipients.csv +4 -0
  93. package/templates/certificate/index.tsx +128 -0
  94. package/templates/certificate/template.json +6 -0
  95. package/templates/letter/index.tsx +106 -0
  96. package/templates/letter/template.json +5 -0
  97. package/templates/meeting-notes/index.tsx +194 -0
  98. package/templates/meeting-notes/template.json +6 -0
  99. package/templates/proposal/index.tsx +264 -0
  100. package/templates/proposal/template.json +6 -0
  101. package/templates/report/data/metrics.csv +5 -0
  102. package/templates/report/index.tsx +224 -0
  103. package/templates/report/template.json +6 -0
  104. package/dist/config-P61niZMf.d.ts +0 -24
  105. package/dist/sdk-CpDEGRIo.d.ts +0 -138
@@ -141,4 +141,42 @@ export const PANELS: Record<string, string> = {
141
141
  'Custom font': '自訂字型',
142
142
  Done: '完成',
143
143
  '{count} elements print from this line of source': '這一行原始碼印出 {count} 個元素',
144
+ Changes: '變更',
145
+ 'Changes ({count})': '變更({count})',
146
+ 'Changes since the last commit': '上次 commit 之後的變更',
147
+ 'Close the changes panel': '關閉變更面板',
148
+ 'Show changes since the last commit': '顯示上次 commit 之後的變更',
149
+ 'Previous change': '上一個變更',
150
+ 'Next change': '下一個變更',
151
+ Since: '比較',
152
+ 'Compare with': '比較對象',
153
+ 'Last commit': '上次 commit',
154
+ 'git is not installed': '沒有安裝 git',
155
+ 'Not a git repository': '不是 git 儲存庫',
156
+ 'No changes': '沒有變更',
157
+ 'Page {page}, changed': '第 {page} 頁,有變更',
158
+ Files: '檔案',
159
+ 'Revert this change': '還原這個變更',
160
+ 'that change is no longer there — reload the changes': '這個變更已經不在了,請重新載入變更',
161
+ 'the file changed since the diff was read': '讀取差異之後檔案又被改過了',
162
+ 'reverting this change alone would break the source — revert the changes around it too':
163
+ '單獨還原這個變更會讓原始碼出錯,請連同周圍的變更一起還原',
164
+ 'a binary file cannot be reverted here': '二進位檔無法在這裡還原',
165
+ 'this workspace is not under git': '這個工作區沒有使用 git',
166
+ Comments: '留言',
167
+ 'Comments ({count})': '留言({count})',
168
+ 'Close the comments panel': '關閉留言面板',
169
+ 'Show comments': '顯示留言',
170
+ 'New comment': '新增留言',
171
+ Resolve: '標為已解決',
172
+ 'Copy request for the agent': '複製給 Agent 的指令',
173
+ 'No comments': '沒有留言',
174
+ 'p.{page}': '第 {page} 頁',
175
+ 'Page {page}, with comments': '第 {page} 頁,有留言',
176
+ 'Could not resolve the comment': '無法標為已解決',
177
+ 'Pick an element on the page': '在頁面上點選元素',
178
+ 'Click the element to comment on · Esc to cancel': '點選要留言的元素 · Esc 取消',
179
+ Records: '資料',
180
+ 'Row {row} of {count}': '第 {row} 列,共 {count} 列',
181
+ 'Esc to deselect': 'Esc 取消選取',
144
182
  };
@@ -1,7 +1,7 @@
1
1
  import { useSyncExternalStore } from 'react';
2
2
  import { PAGE_ATTR, PAGE_INDEX_ATTR } from './outline';
3
3
 
4
- export type LabelKind = 'figure' | 'table' | 'footnote';
4
+ export type LabelKind = 'figure' | 'table' | 'footnote' | 'citation';
5
5
 
6
6
  export type LabelEntry = {
7
7
  /** Author-supplied id for `<Ref to>`, or a generated one. */
@@ -29,6 +29,8 @@ export type LabelVocabulary = {
29
29
  table: string;
30
30
  /** Heading above a page's footnotes. Empty string renders no heading. */
31
31
  footnotes: string;
32
+ /** Heading above a bibliography section when not overridden. */
33
+ bibliography: string;
32
34
  /** Page suffix for a cross-reference. `{page}` is replaced. */
33
35
  onPage: string;
34
36
  };
@@ -37,6 +39,7 @@ export const defaultVocabulary: LabelVocabulary = {
37
39
  figure: 'Figure',
38
40
  table: 'Table',
39
41
  footnotes: '',
42
+ bibliography: 'References',
40
43
  onPage: ' (p. {page})',
41
44
  };
42
45
 
@@ -47,7 +50,7 @@ export type LabelSnapshot = {
47
50
 
48
51
  const EMPTY: LabelSnapshot = { entries: [], vocabulary: defaultVocabulary };
49
52
 
50
- const KINDS: LabelKind[] = ['figure', 'table', 'footnote'];
53
+ const KINDS: LabelKind[] = ['figure', 'table', 'footnote', 'citation'];
51
54
 
52
55
  function isKind(value: string | null): value is LabelKind {
53
56
  return value !== null && (KINDS as string[]).includes(value);
@@ -61,7 +64,12 @@ function isKind(value: string | null): value is LabelKind {
61
64
  */
62
65
  export function collectLabels(root: ParentNode): LabelEntry[] {
63
66
  const entries: LabelEntry[] = [];
64
- const counters: Record<LabelKind, number> = { figure: 0, table: 0, footnote: 0 };
67
+ const counters: Record<LabelKind, number> = {
68
+ figure: 0,
69
+ table: 0,
70
+ footnote: 0,
71
+ citation: 0,
72
+ };
65
73
  const frames = Array.from(root.querySelectorAll<HTMLElement>(`[${PAGE_ATTR}]`));
66
74
 
67
75
  frames.forEach((frame, fallbackIndex) => {
@@ -73,17 +81,23 @@ export function collectLabels(root: ParentNode): LabelEntry[] {
73
81
  if (!isKind(kind)) continue;
74
82
  const id = el.getAttribute(LABEL_ID_ATTR);
75
83
  if (!id) continue;
84
+ const text = (el.getAttribute(LABEL_TEXT_ATTR) ?? el.textContent ?? '')
85
+ .replace(/\s+/g, ' ')
86
+ .trim();
76
87
  // A footnote's marker and the note at the foot of the page carry the same
77
- // id; the marker is what fixes its position in the sequence.
78
- if (entries.some((entry) => entry.id === id)) continue;
88
+ // id; the marker is what fixes its position in the sequence. Same for repeated `<Cite id>`
89
+ // calls — the first appearance fixes its citation number, and later ones reuse it.
90
+ const existing = entries.find((entry) => entry.kind === kind && entry.id === id);
91
+ if (existing) {
92
+ if (!existing.text && text) existing.text = text;
93
+ continue;
94
+ }
79
95
  counters[kind] += 1;
80
96
  entries.push({
81
97
  id,
82
98
  kind,
83
99
  number: counters[kind],
84
- text: (el.getAttribute(LABEL_TEXT_ATTR) ?? el.textContent ?? '')
85
- .replace(/\s+/g, ' ')
86
- .trim(),
100
+ text,
87
101
  page,
88
102
  });
89
103
  }
@@ -124,6 +138,7 @@ function sameVocabulary(a: LabelVocabulary, b: LabelVocabulary): boolean {
124
138
  a.figure === b.figure &&
125
139
  a.table === b.table &&
126
140
  a.footnotes === b.footnotes &&
141
+ a.bibliography === b.bibliography &&
127
142
  a.onPage === b.onPage
128
143
  );
129
144
  }
@@ -162,8 +177,12 @@ export function useDocLabels(kind: LabelKind): LabelEntry[] {
162
177
  }
163
178
 
164
179
  /** One numbered item by id, once the scan has run. */
165
- export function useDocLabel(id: string): LabelEntry | null {
166
- return useLabelSnapshot().entries.find((entry) => entry.id === id) ?? null;
180
+ export function useDocLabel(id: string, kind?: LabelKind): LabelEntry | null {
181
+ return (
182
+ useLabelSnapshot().entries.find(
183
+ (entry) => entry.id === id && (kind === undefined || entry.kind === kind),
184
+ ) ?? null
185
+ );
167
186
  }
168
187
 
169
188
  export function useLabelVocabulary(): LabelVocabulary {
@@ -0,0 +1,38 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { getRecordState, recordFileName, recordLabel, setRecordIndex, setRecords } from './records';
3
+
4
+ describe('recordFileName', () => {
5
+ const row = { name: 'Lin Mei', company: 'Acme / Asia', score: 92 };
6
+
7
+ it('fills columns and the row number', () => {
8
+ expect(recordFileName('certificate-{name}', row, 2, 120)).toBe('certificate-Lin Mei');
9
+ expect(recordFileName('{#}-{company}', row, 2, 120)).toBe('003-Acme - Asia');
10
+ });
11
+
12
+ it('numbers a pattern without placeholders, so each row gets its own file', () => {
13
+ expect(recordFileName('awards', row, 0, 9)).toBe('awards-1');
14
+ });
15
+
16
+ it('falls back to the number when the pattern fills to nothing', () => {
17
+ expect(recordFileName('{missing}', row, 4, 12)).toBe('05');
18
+ });
19
+ });
20
+
21
+ describe('recordLabel', () => {
22
+ it('uses the named column, else the first value', () => {
23
+ expect(recordLabel({ id: '', name: 'Ada' }, 0)).toBe('Ada');
24
+ expect(recordLabel({ id: 'x7', name: 'Ada' }, 0, 'name')).toBe('Ada');
25
+ expect(recordLabel(undefined, 3)).toBe('4');
26
+ });
27
+ });
28
+
29
+ describe('the record store', () => {
30
+ it('keeps the index inside the rows', () => {
31
+ setRecords([{ a: 1 }, { a: 2 }], 5);
32
+ expect(getRecordState().index).toBe(1);
33
+ setRecordIndex(-3);
34
+ expect(getRecordState().index).toBe(0);
35
+ setRecords(undefined);
36
+ expect(getRecordState()).toEqual({ records: [], index: 0 });
37
+ });
38
+ });
@@ -0,0 +1,127 @@
1
+ import { createElement, type ReactNode, useSyncExternalStore } from 'react';
2
+
3
+ /** One row of a document's `records` — usually a line of an imported `.csv`. */
4
+ export type DataRecord = Record<string, unknown>;
5
+
6
+ // Shared through globalThis for the same reason as the outline store: the
7
+ // viewer and the exporters set the record from the source copy of this module,
8
+ // while a document's `useRecord()` and `<Field>` read it from the published
9
+ // bundle. Two stores would mean pages that never change record.
10
+ const GLOBAL_KEY = '__open_doc_record_store__';
11
+ type RecordStore = {
12
+ records: DataRecord[];
13
+ index: number;
14
+ listeners: Set<() => void>;
15
+ };
16
+ type GlobalWithStore = typeof globalThis & { [GLOBAL_KEY]?: RecordStore };
17
+ const g = globalThis as GlobalWithStore;
18
+ if (!g[GLOBAL_KEY]) g[GLOBAL_KEY] = { records: [], index: 0, listeners: new Set() };
19
+ const store = g[GLOBAL_KEY];
20
+
21
+ const notify = () => {
22
+ for (const listener of store.listeners) listener();
23
+ };
24
+
25
+ /** The rows the open document prints from, or none — the viewer sets this as a document loads. */
26
+ export function setRecords(records: DataRecord[] | undefined, index = 0): void {
27
+ const next = Array.isArray(records) ? records : [];
28
+ const at = Math.min(Math.max(0, index), Math.max(0, next.length - 1));
29
+ if (store.records === next && store.index === at) return;
30
+ store.records = next;
31
+ store.index = at;
32
+ notify();
33
+ }
34
+
35
+ export function setRecordIndex(index: number): void {
36
+ const at = Math.min(Math.max(0, index), Math.max(0, store.records.length - 1));
37
+ if (store.index === at) return;
38
+ store.index = at;
39
+ notify();
40
+ }
41
+
42
+ export function getRecordState(): { records: DataRecord[]; index: number } {
43
+ return { records: store.records, index: store.index };
44
+ }
45
+
46
+ function subscribe(listener: () => void): () => void {
47
+ store.listeners.add(listener);
48
+ return () => store.listeners.delete(listener);
49
+ }
50
+
51
+ const getIndex = () => store.index;
52
+ const getCount = () => store.records.length;
53
+ const getCurrent = (): DataRecord | undefined => store.records[store.index];
54
+
55
+ export function useRecordIndex(): number {
56
+ return useSyncExternalStore(subscribe, getIndex, getIndex);
57
+ }
58
+
59
+ export function useRecordCount(): number {
60
+ return useSyncExternalStore(subscribe, getCount, getCount);
61
+ }
62
+
63
+ /**
64
+ * The row this copy of the document is printed for. A document that exports
65
+ * `records` is laid out once per row; every page reads the same one. Outside a
66
+ * document with records — a card in the document list — it is `undefined`.
67
+ */
68
+ export function useRecord<T extends DataRecord = DataRecord>(): T | undefined {
69
+ return useSyncExternalStore(subscribe, getCurrent, getCurrent) as T | undefined;
70
+ }
71
+
72
+ export type FieldProps = {
73
+ /** The column to print. */
74
+ name: string;
75
+ /** Printed when the row has no value for it. */
76
+ fallback?: ReactNode;
77
+ };
78
+
79
+ /**
80
+ * One value of the current row, as text. Where no row is set — a document
81
+ * card, a theme preview — it prints the column's name in guillemets, so the
82
+ * layout still shows what goes where.
83
+ */
84
+ export function Field({ name, fallback }: FieldProps) {
85
+ const record = useRecord();
86
+ if (!record) return createElement('span', { style: { opacity: 0.55 } }, `‹${name}›`);
87
+ const value = record[name];
88
+ if (value === null || value === undefined || value === '') {
89
+ return fallback === undefined ? null : createElement('span', null, fallback);
90
+ }
91
+ return createElement('span', null, String(value));
92
+ }
93
+
94
+ /** How a row is named in the viewer's picker: the chosen column, else the first non-empty one. */
95
+ export function recordLabel(record: DataRecord | undefined, index: number, key?: string): string {
96
+ if (!record) return String(index + 1);
97
+ const value = key ? record[key] : Object.values(record).find((v) => v !== '' && v != null);
98
+ return value === undefined || value === null || value === '' ? String(index + 1) : String(value);
99
+ }
100
+
101
+ // Characters no file system takes in a name, and the separators.
102
+ const UNSAFE = /[\\/:*?"<>|\p{Cc}]+/gu;
103
+
104
+ /**
105
+ * A file name for one row: `{column}` takes the row's value and `{#}` its
106
+ * 1-based number, padded to the width of the count. A pattern-free name gets
107
+ * the number appended, so every row still lands in its own file.
108
+ */
109
+ export function recordFileName(
110
+ pattern: string,
111
+ record: DataRecord | undefined,
112
+ index: number,
113
+ count: number,
114
+ ): string {
115
+ const number = String(index + 1).padStart(String(count).length, '0');
116
+ const filled = pattern.replace(/\{([^{}]+)\}/g, (_, key: string) =>
117
+ key === '#' ? number : String(record?.[key.trim()] ?? ''),
118
+ );
119
+ const named = /\{[^{}]+\}/.test(pattern) ? filled : `${filled}-${number}`;
120
+ return (
121
+ named
122
+ .replace(UNSAFE, '-')
123
+ .replace(/\s+/g, ' ')
124
+ .replace(/^[\s.-]+|[\s.-]+$/g, '')
125
+ .slice(0, 120) || number
126
+ );
127
+ }
@@ -1,6 +1,7 @@
1
1
  import type { ComponentType, ReactNode } from 'react';
2
2
  import type { DesignSystem } from './design.ts';
3
3
  import type { LabelVocabulary } from './labels.ts';
4
+ import type { DataRecord } from './records.ts';
4
5
 
5
6
  /** The only sheets a document may be laid out on. */
6
7
  export const PAGE_SIZE_NAMES = ['A4', 'B4', 'A3'] as const;
@@ -61,6 +62,10 @@ export type FlowSection = {
61
62
  footer?: ComponentType;
62
63
  /** Page padding override in px; defaults to the design's `margin`. */
63
64
  padding?: number;
65
+ /** Number of columns for body content inside each page of this flow section. */
66
+ columns?: 1 | 2 | 3;
67
+ /** Gap in px between columns when `columns > 1`; defaults to 24. */
68
+ columnGap?: number;
64
69
  };
65
70
 
66
71
  /** What a document's default export may contain: fixed pages, flow sections, or both. */
@@ -86,8 +91,33 @@ export type DocMeta = {
86
91
  createdAt?: string;
87
92
  /** What numbered items are called — `圖`/`表` instead of `Figure`/`Table`. */
88
93
  labels?: Partial<LabelVocabulary>;
94
+ /**
95
+ * The language the document is written in, as a BCP 47 tag — `zh-Hant-TW`,
96
+ * `ja`, `ko`, `en-GB`. It decides glyph shapes for shared Han characters,
97
+ * which line-breaking rules apply, and the language an exported file
98
+ * declares. English when unset.
99
+ */
100
+ lang?: string;
101
+ /**
102
+ * With `records`: the file name for each row's copy — `{column}` takes the
103
+ * row's value, `{#}` its number. `<id>-{#}` when unset.
104
+ */
105
+ recordName?: string;
106
+ /** With `records`: the column that names a row in the viewer's picker. */
107
+ recordLabel?: string;
108
+ /** Diagonal watermark text stamped across every sheet (e.g. 'CONFIDENTIAL', 'DRAFT'). */
109
+ watermark?: string;
89
110
  };
90
111
 
112
+ /**
113
+ * The `lang` every sheet carries. Always set, never inherited: a sheet that
114
+ * took its language from the viewer would break lines and pick glyphs by the
115
+ * reader's interface language, and print differently for each reader.
116
+ */
117
+ export function pageLang(meta?: DocMeta): string {
118
+ return meta?.lang?.trim() || 'en';
119
+ }
120
+
91
121
  export type FolderIcon = { type: 'emoji'; value: string } | { type: 'color'; value: string };
92
122
 
93
123
  export type Folder = {
@@ -105,6 +135,11 @@ export type DocModule = {
105
135
  default: DocEntry[];
106
136
  meta?: DocMeta;
107
137
  design?: DesignSystem;
138
+ /**
139
+ * Rows to print the document for, one copy each — usually an imported
140
+ * `.csv`. Pages read the current row with `useRecord()` or `<Field>`.
141
+ */
142
+ records?: DataRecord[];
108
143
  };
109
144
 
110
145
  export function resolvePageGeometry(meta?: DocMeta): PageGeometry {
@@ -15,6 +15,7 @@ export function useDocModule(docId: string | undefined): DocState {
15
15
  useEffect(() => {
16
16
  if (!docId) return;
17
17
  let cancelled = false;
18
+ let rescanned = false;
18
19
 
19
20
  const read = () => {
20
21
  loadDoc(docId)
@@ -23,6 +24,12 @@ export function useDocModule(docId: string | undefined): DocState {
23
24
  })
24
25
  .catch((err: unknown) => {
25
26
  if (cancelled) return;
27
+ // A document created a moment ago may not be in the list yet; the
28
+ // dev server rescans and reloads the page if it is on disk.
29
+ if (import.meta.env.DEV && !rescanned) {
30
+ rescanned = true;
31
+ void fetch('/__docs-rescan').catch(() => {});
32
+ }
26
33
  setState({
27
34
  status: 'error',
28
35
  doc: null,
@@ -1,10 +1,17 @@
1
1
  import { createElement, type ReactNode, useEffect, useMemo, useState } from 'react';
2
2
  import { FlowPage } from '../components/flow-page';
3
3
  import type { DesignSystem } from './design';
4
- import { type DocEntry, type FlowSection, isFlowSection, paginateBlocks } from './flow';
4
+ import {
5
+ type BlockSlice,
6
+ type DocEntry,
7
+ type FlowSection,
8
+ isFlowSection,
9
+ paginateBlocks,
10
+ } from './flow';
5
11
  import { type MeasurableSection, measureFlowSections } from './flow-measure';
6
12
  import { extractSectionFootnotes, notesForPage, type PreparedSection } from './footnotes';
7
- import type { DocModule, PageGeometry } from './sdk';
13
+ import { useRecordIndex } from './records';
14
+ import { type DocModule, type PageGeometry, pageLang } from './sdk';
8
15
 
9
16
  export type ExpandedPage = {
10
17
  key: string;
@@ -12,17 +19,18 @@ export type ExpandedPage = {
12
19
  };
13
20
 
14
21
  type Plan = {
15
- /** Section index → block indices per page. */
16
- bySection: number[][][];
22
+ /** Section index → block slices per page. */
23
+ bySection: BlockSlice[][][];
17
24
  overflowing: Array<{ section: number; block: number }>;
18
25
  };
19
26
 
20
27
  const EMPTY_PLAN: Plan = { bySection: [], overflowing: [] };
21
28
 
22
29
  /** A plan is only current for the sections it was measured from. */
23
- type Measured = { plan: Plan; sections: FlowSection[] | null };
30
+ /** What was measured: these sections, printed for this record. */
31
+ type Measured = { plan: Plan; sections: FlowSection[] | null; record: number };
24
32
 
25
- const NOT_MEASURED: Measured = { plan: EMPTY_PLAN, sections: null };
33
+ const NOT_MEASURED: Measured = { plan: EMPTY_PLAN, sections: null, record: -1 };
26
34
 
27
35
  function entriesOf(doc: DocModule | null): DocEntry[] {
28
36
  return (doc?.default ?? []) as DocEntry[];
@@ -40,6 +48,10 @@ export function useDocPages(
40
48
  const entries = useMemo(() => entriesOf(doc), [doc]);
41
49
  const sections = useMemo(() => entries.filter(isFlowSection), [entries]);
42
50
  const design = doc?.design as DesignSystem | undefined;
51
+ const lang = pageLang(doc?.meta);
52
+ // A row's own words wrap differently from the last one's, so a new record
53
+ // is a new measurement — the same reason a new document is.
54
+ const record = useRecordIndex();
43
55
 
44
56
  // Footnotes come out of the blocks before anything is measured: what they
45
57
  // cost at the foot of a page is part of that page's budget.
@@ -53,6 +65,8 @@ export function useDocPages(
53
65
  blocks: prepared[index].blocks,
54
66
  notesByBlock: prepared[index].notesByBlock,
55
67
  ...(section.padding !== undefined ? { padding: section.padding } : {}),
68
+ ...(section.columns !== undefined ? { columns: section.columns } : {}),
69
+ ...(section.columnGap !== undefined ? { columnGap: section.columnGap } : {}),
56
70
  })),
57
71
  [sections, prepared],
58
72
  );
@@ -62,37 +76,37 @@ export function useDocPages(
62
76
  // one commit after the document loads, and anything reading the page list in
63
77
  // that window — the outline scan, the headless bridge — sees a whole flow
64
78
  // section as one unpaginated page.
65
- const measuring = sections.length > 0 && state.sections !== sections;
79
+ const measuring = sections.length > 0 && (state.sections !== sections || state.record !== record);
66
80
 
67
81
  useEffect(() => {
68
82
  if (sections.length === 0) {
69
- setState({ plan: EMPTY_PLAN, sections });
83
+ setState({ plan: EMPTY_PLAN, sections, record });
70
84
  return;
71
85
  }
72
86
  let cancelled = false;
73
- measureFlowSections(measurable, { geometry, design })
87
+ measureFlowSections(measurable, { geometry, design, lang })
74
88
  .then((measurements) => {
75
89
  if (cancelled) return;
76
- const bySection: number[][][] = [];
90
+ const bySection: BlockSlice[][][] = [];
77
91
  const overflowing: Plan['overflowing'] = [];
78
92
  measurements.forEach((measurement, sectionIndex) => {
79
93
  const result = paginateBlocks(measurement.metrics, measurement.available, {
80
94
  footnoteOverhead: measurement.footnoteOverhead,
81
95
  });
82
- bySection.push(result.pages);
96
+ bySection.push(result.slices);
83
97
  for (const block of result.overflowing) {
84
98
  overflowing.push({ section: sectionIndex, block });
85
99
  }
86
100
  });
87
- setState({ plan: { bySection, overflowing }, sections });
101
+ setState({ plan: { bySection, overflowing }, sections, record });
88
102
  })
89
103
  .catch(() => {
90
- if (!cancelled) setState({ plan: EMPTY_PLAN, sections });
104
+ if (!cancelled) setState({ plan: EMPTY_PLAN, sections, record });
91
105
  });
92
106
  return () => {
93
107
  cancelled = true;
94
108
  };
95
- }, [sections, measurable, geometry, design]);
109
+ }, [sections, measurable, geometry, design, lang, record]);
96
110
 
97
111
  const plan = state.plan;
98
112
 
@@ -112,16 +126,23 @@ export function useDocPages(
112
126
  const blocks = ready?.blocks ?? section.blocks;
113
127
  // Before measurement lands, render the section as a single page so the
114
128
  // viewer shows something rather than flashing empty.
115
- const chunks = plan.bySection[sectionIndex] ?? [blocks.map((_, i) => i)];
116
- chunks.forEach((blockIndices, pageIndex) => {
129
+ const chunks: BlockSlice[][] = plan.bySection[sectionIndex] ?? [
130
+ blocks.map((_, index) => ({ index })),
131
+ ];
132
+ chunks.forEach((blockSlices, pageIndex) => {
133
+ const blockIndices = blockSlices.map((s) => s.index);
134
+ const noteIndices = blockSlices
135
+ .filter((s) => s.rowStart === undefined || s.rowStart === 0)
136
+ .map((s) => s.index);
117
137
  out.push({
118
138
  key: `f${entryIndex}-${pageIndex}`,
119
139
  content: createElement(FlowPage, {
120
140
  section,
121
141
  design,
122
142
  blockIndices,
143
+ blockSlices,
123
144
  blocks,
124
- notes: ready ? notesForPage(ready.notesByBlock, blockIndices) : [],
145
+ notes: ready ? notesForPage(ready.notesByBlock, noteIndices) : [],
125
146
  }),
126
147
  });
127
148
  });