@open-document/core 0.12.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 (48) hide show
  1. package/dist/{build-DfUfpeTR.js → build-CbgIk6bA.js} +1 -1
  2. package/dist/{check-CHxiOkQG.js → check-BTroj-5Z.js} +3 -3
  3. package/dist/cli/bin.js +47 -10
  4. package/dist/config-BWtOZ1jc.d.ts +45 -0
  5. package/dist/{config-9IdbhVuT.js → config-DKKNIbvO.js} +68 -320
  6. package/dist/{context-BLI1-64_.js → context-DXNP8v9I.js} +2 -1
  7. package/dist/deploy-gcp-BUiSuqz7.js +758 -0
  8. package/dist/{dev-yNYKv5mm.js → dev-YXumw5iX.js} +1 -1
  9. package/dist/{diagram-BK4jTZr4.js → diagram-CKf3ptOE.js} +293 -13
  10. package/dist/{diff-Bs205mOx.js → diff-CTFfU4Tz.js} +2 -2
  11. package/dist/{export-tkquS5O5.js → export-D2QLtF84.js} +3 -3
  12. package/dist/{sdk-CHEGeINh.d.ts → flow-CS5apebG.d.ts} +72 -3
  13. package/dist/{import-D1hIKIr3.js → import-CcmrFetU.js} +2 -2
  14. package/dist/index.d.ts +155 -59
  15. package/dist/index.js +896 -90
  16. package/dist/open-doc-plugin-DnX5usgI.js +320 -0
  17. package/dist/ops/index.d.ts +2 -2
  18. package/dist/ops/index.js +2 -2
  19. package/dist/{ops-Dgqujq5a.js → ops-DmEecq1k.js} +2 -1
  20. package/dist/{preview-BImdTH6K.js → preview-_mHpBhMk.js} +1 -1
  21. package/dist/{templates-DT5zzqHq.js → templates-MMblHwmT.js} +3 -3
  22. package/dist/vite/index.d.ts +1 -1
  23. package/dist/vite/index.js +2 -1
  24. package/package.json +1 -1
  25. package/skills/doc-authoring/SKILL.md +15 -16
  26. package/skills/doc-authoring/references/long-form.md +43 -2
  27. package/skills/doc-authoring/references/pagination.md +14 -2
  28. package/skills/doc-authoring/references/tables-and-charts.md +21 -17
  29. package/src/app/components/callout.tsx +101 -0
  30. package/src/app/components/chart.tsx +191 -33
  31. package/src/app/components/code-block.tsx +249 -0
  32. package/src/app/components/data-table.tsx +146 -18
  33. package/src/app/components/flow-page.tsx +57 -8
  34. package/src/app/components/numbering.tsx +226 -12
  35. package/src/app/components/page-frame.tsx +42 -0
  36. package/src/app/lib/chart.test.ts +15 -0
  37. package/src/app/lib/chart.ts +134 -9
  38. package/src/app/lib/diagnostics.ts +45 -1
  39. package/src/app/lib/export-dom.ts +15 -2
  40. package/src/app/lib/export-pdf.ts +9 -1
  41. package/src/app/lib/flow-measure.ts +33 -4
  42. package/src/app/lib/flow.test.ts +20 -1
  43. package/src/app/lib/flow.ts +120 -20
  44. package/src/app/lib/labels.ts +29 -10
  45. package/src/app/lib/sdk.ts +6 -0
  46. package/src/app/lib/use-doc-pages.ts +23 -8
  47. package/src/app/routes/doc.tsx +1 -0
  48. package/dist/config-P61niZMf.d.ts +0 -24
@@ -0,0 +1,320 @@
1
+ import path from "node:path";
2
+ import fs from "node:fs/promises";
3
+ import { existsSync, realpathSync } from "node:fs";
4
+ import fg from "fast-glob";
5
+ import { loadConfigFromFile, normalizePath } from "vite";
6
+ //#region src/vite/open-doc-plugin.ts
7
+ const DOC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
8
+ const CONFIG_FILE = "open-doc.config.ts";
9
+ const DOCS_VMOD = "virtual:open-doc/docs";
10
+ const CONFIG_VMOD = "virtual:open-doc/config";
11
+ const FOLDERS_VMOD = "virtual:open-doc/folders";
12
+ async function readFoldersManifest(file) {
13
+ try {
14
+ const parsed = JSON.parse(await fs.readFile(file, "utf8"));
15
+ return {
16
+ folders: Array.isArray(parsed.folders) ? parsed.folders : [],
17
+ assignments: parsed.assignments && typeof parsed.assignments === "object" ? parsed.assignments : {}
18
+ };
19
+ } catch (err) {
20
+ if (err.code === "ENOENT") return {
21
+ folders: [],
22
+ assignments: {}
23
+ };
24
+ throw err;
25
+ }
26
+ }
27
+ function resolved(id) {
28
+ return `\0${id}`;
29
+ }
30
+ async function findDocs(userCwd, docsDir) {
31
+ const abs = path.resolve(userCwd, docsDir);
32
+ if (!existsSync(abs)) return [];
33
+ return (await fg("*/index.{tsx,jsx,ts,js}", {
34
+ cwd: abs,
35
+ absolute: true,
36
+ onlyFiles: true
37
+ })).sort();
38
+ }
39
+ function toId(absFile, docsRoot) {
40
+ return path.relative(docsRoot, absFile).split(path.sep)[0];
41
+ }
42
+ const META_CREATED_AT_RE = /(?:^|[\s,{])createdAt\s*:\s*['"]([^'"]+)['"]/;
43
+ const META_THEME_RE = /(?:^|[\s,{])theme\s*:\s*['"]([^'"]+)['"]/;
44
+ const META_TITLE_RE = /(?:^|[\s,{])title\s*:\s*(['"`])((?:\\.|(?!\1)[^\\])*)\1/;
45
+ /**
46
+ * Reads `meta` with a brace-matched regex instead of parsing: the plugin runs on
47
+ * every discovery pass, and the fields it needs (sort order, theme back-link,
48
+ * the title search and sorting use without loading every document) are
49
+ * contractually string literals.
50
+ */
51
+ function extractMeta(src) {
52
+ const empty = {
53
+ theme: null,
54
+ createdAt: null,
55
+ title: null
56
+ };
57
+ const metaStart = src.search(/export\s+const\s+meta\b/);
58
+ if (metaStart === -1) return empty;
59
+ const openBrace = src.indexOf("{", src.indexOf("=", metaStart));
60
+ if (openBrace === -1) return empty;
61
+ let depth = 0;
62
+ let closeBrace = -1;
63
+ for (let i = openBrace; i < src.length; i++) {
64
+ const ch = src[i];
65
+ if (ch === "{") depth++;
66
+ else if (ch === "}") {
67
+ depth--;
68
+ if (depth === 0) {
69
+ closeBrace = i;
70
+ break;
71
+ }
72
+ }
73
+ }
74
+ if (closeBrace === -1) return empty;
75
+ const body = src.slice(openBrace + 1, closeBrace);
76
+ return {
77
+ theme: body.match(META_THEME_RE)?.[1] ?? null,
78
+ createdAt: body.match(META_CREATED_AT_RE)?.[1] ?? null,
79
+ title: unescapeLiteral(body.match(META_TITLE_RE)?.[2] ?? null)
80
+ };
81
+ }
82
+ function unescapeLiteral(raw) {
83
+ return raw === null ? null : raw.replace(/\\(.)/g, "$1");
84
+ }
85
+ function parseCreatedAtMs(iso) {
86
+ if (!iso) return null;
87
+ const ms = Date.parse(iso);
88
+ return Number.isFinite(ms) ? ms : null;
89
+ }
90
+ async function readMeta(abs) {
91
+ try {
92
+ return extractMeta(await fs.readFile(abs, "utf8"));
93
+ } catch {
94
+ return {
95
+ theme: null,
96
+ createdAt: null,
97
+ title: null
98
+ };
99
+ }
100
+ }
101
+ const warnedInvalidDocIds = /* @__PURE__ */ new Set();
102
+ async function generateDocsModule(files, docsRoot, isDev) {
103
+ const scanned = await Promise.all(files.map(async (abs) => {
104
+ const meta = await readMeta(abs);
105
+ return {
106
+ id: toId(abs, docsRoot),
107
+ importPath: isDev ? `@fs/${normalizePath(abs).replace(/^\/+/, "")}` : abs,
108
+ theme: meta.theme,
109
+ title: meta.title,
110
+ createdAt: parseCreatedAtMs(meta.createdAt)
111
+ };
112
+ }));
113
+ const entries = scanned.filter((e) => DOC_ID_RE.test(e.id));
114
+ const ignored = scanned.filter((e) => !DOC_ID_RE.test(e.id)).map((e) => e.id);
115
+ const ids = JSON.stringify(entries.map((e) => e.id).sort());
116
+ const createdAtMap = {};
117
+ const themesMap = {};
118
+ const titlesMap = {};
119
+ for (const e of entries) {
120
+ if (e.createdAt !== null) createdAtMap[e.id] = e.createdAt;
121
+ if (e.theme) themesMap[e.id] = e.theme;
122
+ if (e.title) titlesMap[e.id] = e.title;
123
+ }
124
+ const importTokens = JSON.stringify(Object.fromEntries(entries.map((e) => [e.id, 0])));
125
+ const devRuntime = isDev ? `
126
+ const docImportTokens = ${importTokens};
127
+ if (import.meta.hot) {
128
+ import.meta.hot.on('open-doc:doc-changed', (data) => {
129
+ const ids = Array.isArray(data?.docIds) ? data.docIds : data?.docId ? [data.docId] : [];
130
+ const token = Date.now();
131
+ for (const id of ids) {
132
+ if (Object.prototype.hasOwnProperty.call(docImportTokens, id)) docImportTokens[id] = token;
133
+ }
134
+ });
135
+ }
136
+ ` : "";
137
+ const cases = entries.map((e) => {
138
+ const importExpr = isDev ? `import(/* @vite-ignore */ import.meta.env.BASE_URL + ${JSON.stringify(`${e.importPath}?t=`)} + docImportTokens[${JSON.stringify(e.id)}])` : `import(${JSON.stringify(e.importPath)})`;
139
+ return ` case ${JSON.stringify(e.id)}: return ${importExpr};`;
140
+ }).join("\n");
141
+ return {
142
+ code: `// virtual:open-doc/docs — generated
143
+ export const docIds = ${ids};
144
+ export const docCreatedAt = ${JSON.stringify(createdAtMap)};
145
+ export const docThemes = ${JSON.stringify(themesMap)};
146
+ export const docTitles = ${JSON.stringify(titlesMap)};
147
+ ${devRuntime}
148
+
149
+ export async function loadDoc(id) {
150
+ switch (id) {
151
+ ${cases}
152
+ default: throw new Error('Document not found: ' + id);
153
+ }
154
+ }
155
+ `,
156
+ ignored
157
+ };
158
+ }
159
+ function openDocPlugin(opts) {
160
+ const { userCwd, config, coreVersion } = opts;
161
+ const docsDir = config.docsDir ?? "docs";
162
+ const docsRoot = path.resolve(userCwd, docsDir);
163
+ const foldersManifestPath = path.join(docsRoot, ".folders.json");
164
+ let isDev = false;
165
+ let listedIds = "";
166
+ const docIdForEntry = (p) => {
167
+ const roots = [docsRoot];
168
+ try {
169
+ if (existsSync(docsRoot)) {
170
+ const real = realpathSync(docsRoot);
171
+ if (real !== docsRoot) roots.push(real);
172
+ }
173
+ } catch {}
174
+ for (const root of roots) {
175
+ const rel = path.relative(root, p);
176
+ if (rel.startsWith("..") || path.isAbsolute(rel)) continue;
177
+ const parts = rel.split(path.sep);
178
+ if (parts.length !== 2) continue;
179
+ if (!/^index\.(tsx|jsx|ts|js)$/.test(parts[1])) continue;
180
+ return parts[0];
181
+ }
182
+ return null;
183
+ };
184
+ let docChangeTimer = null;
185
+ const pendingDocChanges = /* @__PURE__ */ new Set();
186
+ const queueDocChanged = (server, id) => {
187
+ pendingDocChanges.add(id);
188
+ if (docChangeTimer) clearTimeout(docChangeTimer);
189
+ docChangeTimer = setTimeout(() => {
190
+ docChangeTimer = null;
191
+ const mod = server.moduleGraph.getModuleById(resolved(DOCS_VMOD));
192
+ if (mod) server.moduleGraph.invalidateModule(mod);
193
+ const docIds = Array.from(pendingDocChanges);
194
+ pendingDocChanges.clear();
195
+ server.ws.send({
196
+ type: "custom",
197
+ event: "open-doc:doc-changed",
198
+ data: { docIds }
199
+ });
200
+ }, 100);
201
+ };
202
+ return {
203
+ name: "open-doc",
204
+ config(_c, env) {
205
+ isDev = env.command === "serve";
206
+ return { server: { fs: { allow: [userCwd] } } };
207
+ },
208
+ resolveId(id) {
209
+ if (id === DOCS_VMOD) return resolved(DOCS_VMOD);
210
+ if (id === CONFIG_VMOD) return resolved(CONFIG_VMOD);
211
+ if (id === FOLDERS_VMOD) return resolved(FOLDERS_VMOD);
212
+ return null;
213
+ },
214
+ async load(id) {
215
+ if (id === resolved(DOCS_VMOD)) {
216
+ const files = await findDocs(userCwd, docsDir);
217
+ listedIds = JSON.stringify(files.map((file) => toId(file, docsRoot)).sort());
218
+ const { code, ignored } = await generateDocsModule(files, docsRoot, isDev);
219
+ for (const docId of ignored) {
220
+ if (warnedInvalidDocIds.has(docId)) continue;
221
+ warnedInvalidDocIds.add(docId);
222
+ this.warn(`Ignoring document folder "${docId}": ids must match ${DOC_ID_RE} (letters, digits, "-", "_"). Rename it under "${docsDir}/" to a kebab-case id so it shows up.`);
223
+ }
224
+ return code;
225
+ }
226
+ if (id === resolved(CONFIG_VMOD)) {
227
+ const userBuild = config.build ?? {};
228
+ const build = isDev ? {
229
+ showDocBrowser: true,
230
+ allowHtmlExport: true
231
+ } : {
232
+ showDocBrowser: userBuild.showDocBrowser ?? true,
233
+ allowHtmlExport: userBuild.allowHtmlExport ?? true
234
+ };
235
+ return `export default ${JSON.stringify({
236
+ ...config,
237
+ build,
238
+ version: coreVersion
239
+ })};\n`;
240
+ }
241
+ if (id === resolved(FOLDERS_VMOD)) {
242
+ const manifest = await readFoldersManifest(foldersManifestPath);
243
+ return `export default ${JSON.stringify(manifest)};\n`;
244
+ }
245
+ return null;
246
+ },
247
+ handleHotUpdate(ctx) {
248
+ const docId = docIdForEntry(ctx.file);
249
+ if (!docId) return;
250
+ queueDocChanged(ctx.server, docId);
251
+ return [];
252
+ },
253
+ configureServer(server) {
254
+ const isDocEntry = (p) => docIdForEntry(p) !== null;
255
+ let reloadTimer = null;
256
+ const reload = () => {
257
+ if (reloadTimer) clearTimeout(reloadTimer);
258
+ reloadTimer = setTimeout(() => {
259
+ reloadTimer = null;
260
+ const mod = server.moduleGraph.getModuleById(resolved(DOCS_VMOD));
261
+ if (mod) server.moduleGraph.invalidateModule(mod);
262
+ server.ws.send({ type: "full-reload" });
263
+ }, 150);
264
+ };
265
+ server.watcher.add(docsRoot);
266
+ server.watcher.on("add", (p) => {
267
+ if (isDocEntry(p)) reload();
268
+ });
269
+ server.watcher.on("change", (p) => {
270
+ const docId = docIdForEntry(p);
271
+ if (docId) queueDocChanged(server, docId);
272
+ });
273
+ server.middlewares.use("/__docs-rescan", async (_req, res) => {
274
+ const files = await findDocs(userCwd, docsDir);
275
+ const changed = JSON.stringify(files.map((file) => toId(file, docsRoot)).sort()) !== listedIds;
276
+ if (changed) reload();
277
+ res.setHeader("content-type", "application/json");
278
+ res.end(JSON.stringify({ changed }));
279
+ });
280
+ server.watcher.on("unlink", (p) => {
281
+ if (isDocEntry(p)) reload();
282
+ });
283
+ server.watcher.on("unlinkDir", (p) => {
284
+ if (path.dirname(p) === docsRoot) reload();
285
+ });
286
+ let foldersTimer = null;
287
+ const foldersChanged = () => {
288
+ if (foldersTimer) clearTimeout(foldersTimer);
289
+ foldersTimer = setTimeout(() => {
290
+ foldersTimer = null;
291
+ const mod = server.moduleGraph.getModuleById(resolved(FOLDERS_VMOD));
292
+ if (mod) server.moduleGraph.invalidateModule(mod);
293
+ server.ws.send({
294
+ type: "custom",
295
+ event: "open-doc:files-changed",
296
+ data: {}
297
+ });
298
+ }, 100);
299
+ };
300
+ server.watcher.add(foldersManifestPath);
301
+ for (const event of [
302
+ "add",
303
+ "change",
304
+ "unlink"
305
+ ]) server.watcher.on(event, (p) => {
306
+ if (p === foldersManifestPath) foldersChanged();
307
+ });
308
+ }
309
+ };
310
+ }
311
+ async function loadUserConfig(userCwd) {
312
+ const file = path.join(userCwd, CONFIG_FILE);
313
+ if (!existsSync(file)) return {};
314
+ return (await loadConfigFromFile({
315
+ command: "serve",
316
+ mode: "development"
317
+ }, file, userCwd, "silent"))?.config ?? {};
318
+ }
319
+ //#endregion
320
+ export { loadUserConfig as n, openDocPlugin as r, DOC_ID_RE as t };
@@ -1,4 +1,4 @@
1
- import { c as ExportFormat, d as Orientation, h as PageSizeName, p as PAGE_SIZE_NAMES, s as EXPORT_FORMATS, u as ORIENTATIONS } from "../sdk-CHEGeINh.js";
1
+ import { _ as Orientation, g as ORIENTATIONS, m as ExportFormat, p as EXPORT_FORMATS, x as PageSizeName, y as PAGE_SIZE_NAMES } from "../flow-CS5apebG.js";
2
2
  import { ReactNode } from "react";
3
3
  import "vite";
4
4
  //#region src/vite/routes/context.d.ts
@@ -94,7 +94,7 @@ declare function revertChange(ctx: ApiContext, docId: string, opts: {
94
94
  }>;
95
95
  //#endregion
96
96
  //#region src/app/lib/diagnostics.d.ts
97
- type LayoutRule = 'unresolved-ref' | 'page-overflow' | 'off-page' | 'blank-page' | 'oversized-block' | 'orphan-heading' | 'tiny-text' | 'broken-image';
97
+ type LayoutRule = 'unresolved-ref' | 'duplicate-id' | 'heading-skip' | 'page-overflow' | 'off-page' | 'blank-page' | 'oversized-block' | 'orphan-heading' | 'tiny-text' | 'broken-image';
98
98
  type LayoutSeverity = 'error' | 'warn';
99
99
  type LayoutFinding = {
100
100
  /** 1-based sheet the problem is on. */
package/dist/ops/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  import { i as ORIENTATIONS, o as PAGE_SIZE_NAMES, r as EXPORT_FORMATS } from "../sdk-CqNZzbkz.js";
2
- import { A as renameDocument, C as createDocument, D as listDocIds, E as duplicateDocument, M as writeDocument, N as makeContext, O as listDocuments, S as OpsError, T as docDir, _ as writeAsset, a as writeTexts, b as readChanges, c as suggestDocId, d as fileDocument, f as findAssetUsages, g as readTheme, h as listThemes, i as writeText, j as resolveEntry, k as readDocument, l as createFolder, m as listFolders, n as addComment, o as createFromTemplate, p as listAssets, r as readText, s as listTemplates, u as deleteAsset, w as deleteDocument, x as revertChange, y as listRevisions } from "../config-9IdbhVuT.js";
3
- import { a as importMarkdown, i as renderDocPage, n as closeRenderSession, o as slugify, r as exportDocument, s as diffDocument, t as checkLayout } from "../ops-Dgqujq5a.js";
2
+ import { A as renameDocument, C as createDocument, D as listDocIds, E as duplicateDocument, M as writeDocument, N as makeContext, O as listDocuments, S as OpsError, T as docDir, _ as writeAsset, a as writeTexts, b as readChanges, c as suggestDocId, d as fileDocument, f as findAssetUsages, g as readTheme, h as listThemes, i as writeText, j as resolveEntry, k as readDocument, l as createFolder, m as listFolders, n as addComment, o as createFromTemplate, p as listAssets, r as readText, s as listTemplates, u as deleteAsset, w as deleteDocument, x as revertChange, y as listRevisions } from "../config-DKKNIbvO.js";
3
+ import { a as importMarkdown, i as renderDocPage, n as closeRenderSession, o as slugify, r as exportDocument, s as diffDocument, t as checkLayout } from "../ops-DmEecq1k.js";
4
4
  export { EXPORT_FORMATS, ORIENTATIONS, OpsError, PAGE_SIZE_NAMES, addComment, checkLayout, closeRenderSession, createDocument, createFolder, createFromTemplate, deleteAsset, deleteDocument, diffDocument, docDir, duplicateDocument, exportDocument, fileDocument, findAssetUsages, importMarkdown, listAssets, listDocIds, listDocuments, listFolders, listRevisions, listTemplates, listThemes, makeContext, readChanges, readDocument, readText, readTheme, renameDocument, renderDocPage, resolveEntry, revertChange, slugify, suggestDocId, writeAsset, writeDocument, writeText, writeTexts };
@@ -1,5 +1,6 @@
1
1
  import { c as isPageSizeName, i as ORIENTATIONS, o as PAGE_SIZE_NAMES, s as isOrientation } from "./sdk-CqNZzbkz.js";
2
- import { C as createDocument, D as listDocIds, P as DOC_ID_RE, S as OpsError, j as resolveEntry, t as createViteConfig, v as validateAssetName } from "./config-9IdbhVuT.js";
2
+ import { t as DOC_ID_RE } from "./open-doc-plugin-DnX5usgI.js";
3
+ import { C as createDocument, D as listDocIds, S as OpsError, j as resolveEntry, t as createViteConfig, v as validateAssetName } from "./config-DKKNIbvO.js";
3
4
  import path from "node:path";
4
5
  import fs from "node:fs/promises";
5
6
  import { existsSync } from "node:fs";
@@ -1,4 +1,4 @@
1
- import { t as createViteConfig } from "./config-9IdbhVuT.js";
1
+ import { t as createViteConfig } from "./config-DKKNIbvO.js";
2
2
  import { mergeConfig, preview as preview$1 } from "vite";
3
3
  //#region src/cli/preview.ts
4
4
  async function preview(opts = {}) {
@@ -1,6 +1,6 @@
1
- import { o as createFromTemplate, s as listTemplates } from "./config-9IdbhVuT.js";
2
- import "./ops-Dgqujq5a.js";
3
- import { t as cliContext } from "./context-BLI1-64_.js";
1
+ import { o as createFromTemplate, s as listTemplates } from "./config-DKKNIbvO.js";
2
+ import "./ops-DmEecq1k.js";
3
+ import { t as cliContext } from "./context-DXNP8v9I.js";
4
4
  import chalk from "chalk";
5
5
  //#region src/cli/templates.ts
6
6
  /**
@@ -1,4 +1,4 @@
1
- import { n as OpenDocConfig } from "../config-P61niZMf.js";
1
+ import { n as OpenDocConfig } from "../config-BWtOZ1jc.js";
2
2
  import { InlineConfig, Plugin } from "vite";
3
3
  //#region src/vite/open-doc-plugin.d.ts
4
4
  type OpenDocPluginOptions = {
@@ -1,2 +1,3 @@
1
- import { I as openDocPlugin, t as createViteConfig } from "../config-9IdbhVuT.js";
1
+ import { r as openDocPlugin } from "../open-doc-plugin-DnX5usgI.js";
2
+ import { t as createViteConfig } from "../config-DKKNIbvO.js";
2
3
  export { createViteConfig, openDocPlugin };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-document/core",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "description": "Runtime and CLI for open-doc — write documents in docs/, we handle the pages, print layout, and export.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -17,11 +17,11 @@ Read the matching reference **before** using a primitive:
17
17
  | Primitive | Read before | File |
18
18
  | --- | --- | --- |
19
19
  | `design` const + `var(--od-*)` tokens | writing any new document | `references/design-system.md` |
20
- | `flow()` auto-pagination | any body content (the default) | `references/pagination.md` |
20
+ | `flow()` auto-pagination & multi-column | any body content (the default) | `references/pagination.md` |
21
21
  | Vertical budget (fixed pages) | laying out a cover or divider by hand | `references/pagination.md` |
22
- | Tables, stat rows, inline charts | rendering data of any kind | `references/tables-and-charts.md` |
22
+ | Tables, stat rows, `<Chart>`, `<Sparkline>`, `<Callout>` | rendering data or callouts | `references/tables-and-charts.md` |
23
23
  | Assets + `<ImagePlaceholder>` | importing images or leaving a placeholder | `references/assets.md` |
24
- | Footnotes, `<Figure>`, `<Ref>`, `<DataTable>` | any note, numbered figure, cross-reference, or `.csv` | `references/long-form.md` |
24
+ | Footnotes, `<Figure>`, `<Ref>`, `<DataTable>`, `<Cite>`, `<Bibliography>`, `<CodeBlock>` | notes, figures, cross-references, citations, code blocks, or `.csv` | `references/long-form.md` |
25
25
 
26
26
  ## Themes
27
27
 
@@ -62,6 +62,7 @@ export default [Cover, Body] satisfies DocPage[];
62
62
  - `meta.pageSize` is `'A4' | 'B4' | 'A3'` (default `'A4'`) and `meta.orientation` is `'portrait' | 'landscape'` (default portrait). **These six combinations are the only sheets there are** — there is no Letter, no A5, no custom size, and no way to set a page's dimensions by hand. The same value drives the on-screen page, the `@page` size when printing, and the HTML export.
63
63
  - `meta.lang` is the document's language as a BCP 47 tag — **set it for anything not in English**: `'zh-Hant-TW'`, `'zh-Hans'`, `'ja'`, `'ko'`. Every sheet carries it, so it decides the glyph shapes of shared Han characters, the line-breaking rules (no `,。」` at the start of a line), and the language exported HTML and Word declare. The sheet already sets CJK text properly — strict kinsoku, and an eighth-em gap where a CJK character meets a Latin letter or digit with no space typed — so don't hand-insert spaces for that; a block that must not get the gap takes `textAutospace: 'no-autospace'`.
64
64
  - **One document per row of data** (certificates, letters, quotes): `export const records = rows` (an imported `.csv`) makes the document print once per row. Pages read the current row with `useRecord()` or print one value with `<Field name="company" />`; `meta.recordName: 'certificate-{name}'` names each row's file (`{#}` is the row number) and `meta.recordLabel` names rows in the viewer's picker. `open-doc export <id> --each` writes one file per row. A flow section's blocks are fixed when the module loads, so content that varies by row goes **inside** blocks — a block can render nothing for a row — never as a different number of blocks.
65
+ - `meta.watermark` (optional string, e.g. `'CONFIDENTIAL'` or `'DRAFT'`) renders a subtle diagonal watermark across every sheet in the viewer and exports.
65
66
  - `meta.createdAt` is an **ISO 8601 string literal** set once when the doc is scaffolded — the home page sorts on it. **Immediately before writing the file, run `node -e "console.log(new Date().toISOString())"` and paste the exact output.** It must stay a plain string literal (no `new Date(...)`): the framework reads it with a regex at build time, it never evaluates the module.
66
67
 
67
68
  ## Two ways to fill pages
@@ -154,11 +155,12 @@ contents list does. Read `references/long-form.md` before using any of them.
154
155
  content in one unbreakable block. `<ListOfFigures />` / `<ListOfTables />`
155
156
  build the lists.
156
157
  - **`<Ref to="id" />`** — "Figure 3", plus the page when the target is elsewhere.
157
- - **`<DataTable rows={…}>`** — a print-shaped table from an imported `.csv`.
158
- - **`<Diagram chart={…} caption>`** — an architecture or flow drawing from an
159
- imported `.mmd`. Given a caption it numbers as a figure, like `<Figure>`.
160
- - **`<Chart data x y caption>`** — a bar, line or pie chart from rows, in the
161
- document's colours; numbers as a figure. See `references/tables-and-charts.md`.
158
+ - **`<Cite id="…" source="…" />` & `<Bibliography />`** — academic/report citations numbered in order of first appearance (`[1]`), deduplicated by `id`, and listed by `<Bibliography />`.
159
+ - **`<DataTable rows={…} splittable summaryRow>`** — a print-shaped table from an imported `.csv` (supports automatic multi-page splitting with repeated headers when `splittable` is set, plus `summaryRow`, `dataBar`, `'currency'`, and `'delta'` formats).
160
+ - **`<CodeBlock code={…} lang="ts" lineNumbers highlightLines={[…]} caption="…" />`** — zero-dependency syntax-highlighted code block with optional line numbers, highlighted lines, and figure numbering when given `caption`.
161
+ - **`<Callout type="note|tip|warning|danger" title="…">`** — semantic callout box styled with `--od-*` tokens.
162
+ - **`<Diagram chart={…} caption>`** — an architecture, flow, or sequence drawing from an imported `.mmd`. Given a caption it numbers as a figure, like `<Figure>`.
163
+ - **`<Chart data x y caption>` & `<Sparkline data={…} />`** — `bar`, `horizontal-bar`, `line`, `area`, or `pie` charts from rows, plus inline SVG `<Sparkline>` for tables and stat cards. See `references/tables-and-charts.md`.
162
164
 
163
165
  `meta.labels` sets what they are called (`圖`, `表`) — the numbering itself is
164
166
  structural.
@@ -188,13 +190,10 @@ It is compiled to SVG at build time and drawn with the document's own theme
188
190
  variables, so it prints with the same ink and faces as the prose around it.
189
191
  Never reach for an image of a diagram when the diagram can be written.
190
192
 
191
- Supported: `flowchart`/`graph` with `TD` or `LR`; nodes as `A[box]`, `A(round)`,
192
- `A([stadium])`, `A[(database)]`, `A{decision}`, `A((circle))`; links `-->`,
193
- `---`, `-.->`, `==>` with optional `|labels|`; chains `A --> B --> C`; `%%`
194
- comments. A link back to an earlier step is drawn round the side, clear of the
195
- steps in between. Anything else
196
- in Mermaid's syntax — subgraphs, class diagrams, sequence diagrams — is not
197
- supported, and a bad diagram fails the build with the line to fix.
193
+ Supported:
194
+ - `flowchart`/`graph` with `TD` or `LR`; nodes as `A[box]`, `A(round)`, `A([stadium])`, `A[(database)]`, `A{decision}`, `A((circle))`; links `-->`, `---`, `-.->`, `==>` with optional `|labels|`; chains `A --> B --> C`; `subgraph id [Title] ... end` clusters; `%%` comments. A link back to an earlier step is drawn round the side, clear of the steps in between.
195
+ - `sequenceDiagram` with `participant Id as Label`, message arrows (`->>`, `-->>`, `->`, `-->`), and `Note over A,B: text` (or `Note left of` / `Note right of`).
196
+ - Anything else in Mermaid's syntax is not supported, and a bad diagram fails the build with the line to fix.
198
197
 
199
198
  Keep `width` inside the text block: a drawing wider than the column is a layout
200
199
  fault, and `open-doc check` reports it as one.
@@ -416,7 +415,7 @@ confirms it.
416
415
  - [ ] `docs/<id>/index.tsx` `export default`s a non-empty `DocEntry[]`, with body content in a `flow()` section rather than hand-split pages.
417
416
  - [ ] Every page's root fills `100% × 100%` and sets `boxSizing: 'border-box'` with the margin as padding.
418
417
  - [ ] **For every fixed page, sum (font_size × line_height × lines) + gaps + 2×margin ≤ page height.** If close, split — or move the content into the flow section. No `overflow: auto` escape hatches.
419
- - [ ] No block inside a `flow()` section is taller than one page (a long table has to be split by hand — the framework never splits a block).
418
+ - [ ] No unbreakable block inside a `flow()` section is taller than one page (pass `splittable` on long `<DataTable>` instances so the framework splits rows across pages with repeated headers).
420
419
  - [ ] Body type ≥ 13px; nothing on the page under 9px.
421
420
  - [ ] Section titles are real `h1`/`h2`/`h3` elements, so the outline and TOC pick them up.
422
421
  - [ ] Contents page uses `<TableOfContents />`, not a hand-written list.
@@ -120,8 +120,10 @@ import services from './data/services.csv';
120
120
  arrives after the layout is decided.
121
121
  - Columns default to the keys of the first row. A column whose values are all
122
122
  numbers aligns right and gets `tabular-nums` without being told.
123
- - `format`: `'integer'`, `'number'`, `'percent'`, `'text'`, or your own
124
- `(value, row) => ReactNode`.
123
+ - `format`: `'integer'`, `'number'`, `'percent'`, `'currency'` (uses `column.currency ?? 'USD'`), `'delta'` (`+` prefix for positives, `−` for negatives), `'text'`, or your own `(value, row) => ReactNode`.
124
+ - `dataBar`: `true` or `{ color?: string; max?: number }` on a numeric column draws an inline proportional bar behind the cell's number.
125
+ - `summaryRow`: `'sum' | 'avg'` (aggregates all numeric columns automatically) or a custom record `{ service: 'Total', requests: 'sum', error_rate: 'avg' }` rendered in `<tfoot>`.
126
+ - `splittable`: when `true` inside a `flow()` section, automatically splits long tables across pages, repeating `<thead>` and appending `meta.labels?.continued ?? ' (continued)'` to the caption on continuation sheets.
125
127
  - `caption` numbers the table and prints the caption above it; without one you
126
128
  get a plain table.
127
129
  - `limit` prints the first N rows and says how many were left out — never
@@ -129,3 +131,42 @@ import services from './data/services.csv';
129
131
 
130
132
  **Retyping numbers into JSX is the thing this replaces.** If the user has the
131
133
  data in a file, import the file.
134
+
135
+ ## Citations and bibliography (`<Cite>` & `<Bibliography>`)
136
+
137
+ ```tsx
138
+ import { Bibliography, Cite } from '@open-document/core';
139
+
140
+ <p style={p}>
141
+ Tail latency dominates fan-out services <Cite id="dean2013" label="p. 75" source="J. Dean and L. A. Barroso, 'The Tail at Scale,' Communications of the ACM, vol. 56, no. 2, pp. 74–80, 2013." />.
142
+ </p>
143
+
144
+ <Bibliography title="References" />
145
+ ```
146
+
147
+ - `<Cite id="…" />` numbers citations `[1]`, `[2]` in order of first appearance across the entire document. Citing the same `id` again reuses the same number; pass `source` on at least the first occurrence, and optional `label` (e.g. `"p. 42"`) to render `[1, p. 42]`.
148
+ - `<Bibliography />` prints the numbered reference list in order of appearance. An entry cited without any `source` renders `[?id]` so missing bibliography text is immediately visible.
149
+
150
+ ## Syntax-highlighted code (`<CodeBlock>`)
151
+
152
+ ```tsx
153
+ import { CodeBlock } from '@open-document/core';
154
+
155
+ <CodeBlock
156
+ id="retry-policy"
157
+ caption="Exponential backoff retry policy"
158
+ lang="ts"
159
+ lineNumbers
160
+ highlightLines={[3, 4]}
161
+ code={`export async function withRetry<T>(fn: () => Promise<T>, retries = 3): Promise<T> {
162
+ for (let i = 0; i < retries; i++) {
163
+ try { return await fn(); }
164
+ catch (err) { if (i === retries - 1) throw err; }
165
+ }
166
+ throw new Error('Unreachable');
167
+ }`}
168
+ />
169
+ ```
170
+
171
+ - Highlights keywords, strings, comments, numbers, and types at render time with zero external dependencies using `--od-*` variables.
172
+ - Passing `caption` numbers the code block as a figure (retrievable via `<Ref to="retry-policy" />`).
@@ -41,13 +41,25 @@ export default [Cover, Contents, Body] satisfies DocEntry[];
41
41
  | Heading never last on a page | `data-od-keep-with-next` | **on** for `h1`–`h4` |
42
42
  | Caption stays with its figure | `data-od-keep-with-previous` on the caption | off |
43
43
  | Force a new page here | `data-od-break-before` | off |
44
+ | Span all columns in multi-column flow | `data-od-column-span="all"` | **on** for `h1` |
44
45
 
45
46
  Set `data-od-keep-with-next="false"` on a heading if you deliberately want it to end a page.
46
47
 
48
+ ### Multi-column flow (`columns` & `columnGap`)
49
+
50
+ Pass `columns: 2` (or `3`) and optional `columnGap` (default `24`) to `flow(children, { columns: 2, columnGap: 24, footer: Footer })` to pack blocks into balanced newspaper/academic columns on each page:
51
+
52
+ - Blocks flow down column 1 first, then column 2, then open a new page.
53
+ - `<h1>` elements (and any block carrying `data-od-column-span="all"`) span the full text-block width across all columns and flush the columns above them.
54
+ - Footnotes lifted from any column on a page share the single page-wide footnote area at the bottom of the sheet.
55
+
56
+ ### Splittable tables (`<DataTable splittable />`)
57
+
58
+ By default, blocks in `flow()` are atomic. However, `<DataTable splittable rows={…} />` is measured row-by-row and automatically sliced across as many flow pages as needed, repeating `<thead>` on every continuation page and appending the continuation suffix (`meta.labels?.continued ?? ' (continued)'`) to the caption.
59
+
47
60
  ### What flow does not do
48
61
 
49
- - **It never splits a block.** A 40-row table taller than one page stays whole and overflows — split it yourself into two tables with a repeated header.
50
- - **It does not balance pages.** Content fills top-down; the last page can be short.
62
+ - **It never splits an arbitrary block** unless it is a `<DataTable splittable />` (or bears `data-od-splittable="table"`).
51
63
  - **It does not reorder anything.** Blocks keep the order you wrote them in.
52
64
 
53
65
  ## Fixed pages and the vertical budget
@@ -67,7 +67,7 @@ Rules:
67
67
 
68
68
  ### Long tables
69
69
 
70
- Split by row groups across pages. Repeat the full header row and mark the continuation in the caption ("Table 3 (continued)"). Never let a header land on one page and its rows on the next.
70
+ Inside a `flow()` section, pass `splittable` to `<DataTable rows={…} splittable />` so the framework automatically slices rows across pages, repeats the `<thead>` header row, and marks the continuation in the caption ("Table 3 (continued)"). For hand-written `<table>` elements on fixed pages, split by row groups across pages and repeat the header row yourself. Never let a header land on one page and its rows on the next.
71
71
 
72
72
  ## Stat rows
73
73
 
@@ -106,13 +106,24 @@ import costs from './data/costs.csv';
106
106
  <Chart type="pie" data={services} x="service" y="cost" values caption="費用占比" />
107
107
  ```
108
108
 
109
- - `type`: `bar` (default), `line`, `pie`. `y` takes one key or several (one series each); a pie reads the first.
110
- - `stacked` stacks bar series instead of grouping them; `values` prints each value on its bar, point or slice.
111
- - `format`: `number`, `integer`, `percent`, or a function — the same vocabulary as `<DataTable>`.
109
+ - `type`: `'bar'` (default), `'horizontal-bar'`, `'line'`, `'area'`, `'pie'`. `y` takes one key or several (one series each); a pie reads the first.
110
+ - `stacked` stacks `bar`, `horizontal-bar`, or `area` series instead of grouping/overlapping them; `values` prints each value on its bar, point or slice.
111
+ - `format`: `'number'`, `'integer'`, `'percent'`, `'currency'`, `'delta'`, or a function — the same vocabulary as `<DataTable>`.
112
112
  - `width` / `height` are the drawn size in px (default 560 × 260); it scales down to the column.
113
113
  - It lays out synchronously into a fixed box, so it paginates like any block. In Word it arrives as a picture.
114
114
 
115
- Anything `<Chart>` doesn't draw — a sparkline in a stat row, an annotated timeline — write as **inline SVG** sized in absolute px:
115
+ ### Inline sparklines (`<Sparkline>`)
116
+
117
+ For compact trend lines or mini bar strips inside a `<DataTable>` cell, stat card, or prose paragraph, use **`<Sparkline>`**:
118
+
119
+ ```tsx
120
+ import { Sparkline } from '@open-document/core';
121
+
122
+ <Sparkline data={[38, 42, 40, 49, 55, 61]} type="area" width={88} height={22} showEndDot />
123
+ <Sparkline data={[12, 18, 15, 24, 29]} type="bar" width={72} height={20} />
124
+ ```
125
+
126
+ Anything `<Chart>` or `<Sparkline>` doesn't draw — an annotated timeline or bespoke diagram — write as **inline SVG** sized in absolute px:
116
127
 
117
128
  ```tsx
118
129
  const Bars = () => {
@@ -158,21 +169,14 @@ Rules:
158
169
 
159
170
  ## Callouts
160
171
 
161
- One box style, used sparingly (at most one or two per page):
172
+ Use the built-in **`<Callout>`** primitive (`type`: `'note' | 'tip' | 'warning' | 'danger'`, default `'note'`) sparingly — at most one or two per page:
162
173
 
163
174
  ```tsx
164
- <div
165
- style={{
166
- borderLeft: '3px solid var(--od-accent)',
167
- background: '#f8fafc',
168
- padding: '12px 14px',
169
- borderRadius: 'var(--od-radius)',
170
- fontSize: 12,
171
- }}
172
- >
173
- <strong style={{ display: 'block', marginBottom: 4 }}>Recommendation</strong>
175
+ import { Callout } from '@open-document/core';
176
+
177
+ <Callout type="warning" title="Recommendation">
174
178
  Move the checkout queue to its own cluster before the November peak.
175
- </div>
179
+ </Callout>
176
180
  ```
177
181
 
178
182
  Reserve callouts for recommendations, risks, and definitions. A page where everything is boxed emphasizes nothing.