@open-document/core 0.10.0 → 0.12.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 (86) hide show
  1. package/dist/{build-DJMLK50m.js → build-DfUfpeTR.js} +1 -1
  2. package/dist/{check-CUKuufBm.js → check-CHxiOkQG.js} +3 -3
  3. package/dist/cli/bin.js +20 -33
  4. package/dist/{config-CvzpyAUA.js → config-9IdbhVuT.js} +2015 -725
  5. package/dist/{context-B4ip7SoI.js → context-BLI1-64_.js} +2 -2
  6. package/dist/{dev-dnH7DTlD.js → dev-yNYKv5mm.js} +1 -1
  7. package/dist/{diff-QTo0A5Rx.js → diff-Bs205mOx.js} +2 -2
  8. package/dist/{export-BrRFrexj.js → export-tkquS5O5.js} +11 -4
  9. package/dist/{import-C14Vn9ER.js → import-D1hIKIr3.js} +3 -2
  10. package/dist/index.d.ts +2 -2
  11. package/dist/index.js +63 -28
  12. package/dist/ops/index.d.ts +111 -2
  13. package/dist/ops/index.js +3 -3
  14. package/dist/{ops-DKidjLXP.js → ops-Dgqujq5a.js} +85 -164
  15. package/dist/package-version-C89gtYSk.js +36 -0
  16. package/dist/{preview-wKM4C6Uk.js → preview-BImdTH6K.js} +1 -1
  17. package/dist/{sdk-CpDEGRIo.d.ts → sdk-CHEGeINh.d.ts} +46 -1
  18. package/dist/templates-DT5zzqHq.js +34 -0
  19. package/dist/vite/index.js +1 -1
  20. package/package.json +2 -1
  21. package/skills/apply-comments/SKILL.md +3 -1
  22. package/skills/create-doc/SKILL.md +2 -0
  23. package/skills/doc-authoring/SKILL.md +2 -0
  24. package/src/app/components/browser/browser-ui.tsx +21 -0
  25. package/src/app/components/browser/new-document-dialog.tsx +208 -0
  26. package/src/app/components/changes/changes-overlay.tsx +68 -0
  27. package/src/app/components/changes/changes-panel.tsx +341 -0
  28. package/src/app/components/changes/use-changes.ts +85 -0
  29. package/src/app/components/comments/comments-overlay.tsx +50 -0
  30. package/src/app/components/comments/comments-panel.tsx +272 -0
  31. package/src/app/components/comments/use-comments.ts +61 -0
  32. package/src/app/components/doc-sidebar.tsx +32 -2
  33. package/src/app/components/inspector/field-source.tsx +41 -0
  34. package/src/app/components/inspector/format-section.tsx +434 -0
  35. package/src/app/components/inspector/inspector.tsx +311 -118
  36. package/src/app/components/inspector/use-style-edits.ts +210 -0
  37. package/src/app/components/overlay-frame.tsx +79 -0
  38. package/src/app/components/page-frame.tsx +4 -0
  39. package/src/app/components/page-placement.ts +68 -0
  40. package/src/app/components/panel/fields.tsx +95 -7
  41. package/src/app/components/record-picker.tsx +79 -0
  42. package/src/app/components/themes/theme-preview.tsx +5 -4
  43. package/src/app/lib/agent-bridge.ts +29 -1
  44. package/src/app/lib/docx/ooxml.test.ts +24 -1
  45. package/src/app/lib/docx/ooxml.ts +27 -1
  46. package/src/app/lib/export-docx.ts +3 -1
  47. package/src/app/lib/export-dom.ts +2 -1
  48. package/src/app/lib/export-html.ts +4 -2
  49. package/src/app/lib/export-image.ts +2 -1
  50. package/src/app/lib/flow-measure.test.ts +30 -0
  51. package/src/app/lib/flow-measure.ts +35 -10
  52. package/src/app/lib/i18n-ja/browser.ts +10 -0
  53. package/src/app/lib/i18n-ja/doc.ts +4 -0
  54. package/src/app/lib/i18n-ja/panels.ts +92 -5
  55. package/src/app/lib/i18n-ko/browser.ts +10 -0
  56. package/src/app/lib/i18n-ko/doc.ts +4 -0
  57. package/src/app/lib/i18n-ko/panels.ts +90 -5
  58. package/src/app/lib/i18n-zh-cn/browser.ts +10 -0
  59. package/src/app/lib/i18n-zh-cn/doc.ts +4 -0
  60. package/src/app/lib/i18n-zh-cn/panels.ts +88 -5
  61. package/src/app/lib/i18n-zh-tw/browser.ts +10 -0
  62. package/src/app/lib/i18n-zh-tw/doc.ts +4 -0
  63. package/src/app/lib/i18n-zh-tw/panels.ts +88 -5
  64. package/src/app/lib/inspector/format.ts +156 -0
  65. package/src/app/lib/records.test.ts +38 -0
  66. package/src/app/lib/records.ts +127 -0
  67. package/src/app/lib/sdk.ts +29 -0
  68. package/src/app/lib/use-doc-module.ts +7 -0
  69. package/src/app/lib/use-doc-pages.ts +15 -9
  70. package/src/app/routes/doc.tsx +274 -11
  71. package/src/app/routes/home.tsx +30 -5
  72. package/src/app/styles.css +23 -0
  73. package/templates/blank/index.tsx +63 -0
  74. package/templates/blank/template.json +6 -0
  75. package/templates/certificate/data/recipients.csv +4 -0
  76. package/templates/certificate/index.tsx +128 -0
  77. package/templates/certificate/template.json +6 -0
  78. package/templates/letter/index.tsx +106 -0
  79. package/templates/letter/template.json +5 -0
  80. package/templates/meeting-notes/index.tsx +194 -0
  81. package/templates/meeting-notes/template.json +6 -0
  82. package/templates/proposal/index.tsx +264 -0
  83. package/templates/proposal/template.json +6 -0
  84. package/templates/report/data/metrics.csv +5 -0
  85. package/templates/report/index.tsx +224 -0
  86. package/templates/report/template.json +6 -0
@@ -1,9 +1,8 @@
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 assetImportPath, D as validateAssetName, E as resolveScopedAssetsDir, S as writeManifest, T as resolveScopedAssetFile, b as validateIcon, c as createDocument, f as listDocIds, g as resolveEntry, k as DOC_ID_RE, n as parseFrontmatter$1, s as OpsError, t as createViteConfig, v as newFolderId, w as countAssetUsages, x as validateName, y as readManifest } from "./config-CvzpyAUA.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";
3
3
  import path from "node:path";
4
4
  import fs from "node:fs/promises";
5
5
  import { existsSync } from "node:fs";
6
- import fg from "fast-glob";
7
6
  import { createServer, mergeConfig } from "vite";
8
7
  import { execFile } from "node:child_process";
9
8
  import { promisify } from "node:util";
@@ -91,7 +90,7 @@ async function createRenderSession(opts) {
91
90
  throw new Error(`Document "${docId}" never finished rendering.${detail}`);
92
91
  }
93
92
  const status = await page.evaluate("globalThis.__openDoc.status()");
94
- return {
93
+ const renderer = {
95
94
  status,
96
95
  diagnose: () => page.evaluate("globalThis.__openDoc.diagnose()"),
97
96
  async pdf() {
@@ -144,8 +143,15 @@ async function createRenderSession(opts) {
144
143
  },
145
144
  html: () => page.evaluate("globalThis.__openDoc.htmlBundle()"),
146
145
  docx: () => page.evaluate("globalThis.__openDoc.docxBundle()"),
146
+ async setRecord(index, pattern) {
147
+ const { name } = await page.evaluate(`globalThis.__openDoc.setRecord(${JSON.stringify(index)}, ${pattern === void 0 ? "undefined" : JSON.stringify(pattern)})`);
148
+ await page.waitForFunction(`(() => { const s = globalThis.__openDoc.status(); return s.ready && s.record === ${JSON.stringify(index)}; })()`, void 0, { timeout });
149
+ renderer.status = await page.evaluate("globalThis.__openDoc.status()");
150
+ return name;
151
+ },
147
152
  close: () => page.close()
148
153
  };
154
+ return renderer;
149
155
  },
150
156
  async compareImages(before, after) {
151
157
  const page = await browser.newPage();
@@ -646,6 +652,35 @@ async function diffDocument(ctx, docId, opts = {}) {
646
652
  }
647
653
  }
648
654
  //#endregion
655
+ //#region src/import/lang.ts
656
+ const TRADITIONAL = "們這個說為國來會時對過還後點經學發應麼與實體關開種現當於從際";
657
+ const SIMPLIFIED = "们这个说为国来会时对过还后点经学发应么与实体关开种现当于从际";
658
+ const count = (text, re) => text.match(re)?.length ?? 0;
659
+ /**
660
+ * The language a Markdown file is written in, when it is one whose sheets
661
+ * need to say so — Chinese, Japanese, Korean — or `undefined` for anything
662
+ * else, which the document then leaves at its default.
663
+ */
664
+ function detectLang(text) {
665
+ const han = count(text, /\p{Script=Han}/gu);
666
+ const kana = count(text, /[\p{Script=Hiragana}\p{Script=Katakana}]/gu);
667
+ const hangul = count(text, /\p{Script=Hangul}/gu);
668
+ const latin = count(text, /\p{Script=Latin}/gu);
669
+ const cjk = han + kana + hangul;
670
+ if (cjk === 0 || cjk < latin * .25) return void 0;
671
+ if (hangul > han + kana) return "ko";
672
+ if (kana > 0 && kana >= han * .05) return "ja";
673
+ let traditional = 0;
674
+ let simplified = 0;
675
+ for (const char of text) {
676
+ const t = TRADITIONAL.indexOf(char);
677
+ const s = SIMPLIFIED.indexOf(char);
678
+ if (t !== -1 && SIMPLIFIED[t] !== char) traditional++;
679
+ if (s !== -1 && TRADITIONAL[s] !== char) simplified++;
680
+ }
681
+ return simplified > traditional ? "zh-Hans" : "zh-Hant";
682
+ }
683
+ //#endregion
649
684
  //#region src/import/markdown.ts
650
685
  const FENCE_RE = /^(```|~~~)\s*([^\s`]*)\s*$/;
651
686
  const ATX_RE = /^(#{1,6})\s+(.*?)\s*#*\s*$/;
@@ -1280,6 +1315,7 @@ function generateDocumentSource(parsed, opts) {
1280
1315
  const theme = opts.theme ?? parsed.frontmatter.theme;
1281
1316
  const pageSize = opts.pageSize ?? parsed.frontmatter.pageSize;
1282
1317
  const orientation = opts.orientation ?? parsed.frontmatter.orientation;
1318
+ const lang = opts.lang ?? parsed.frontmatter.lang;
1283
1319
  const cover = opts.cover !== false;
1284
1320
  let blocks = parsed.blocks;
1285
1321
  const first = blocks[0];
@@ -1331,6 +1367,7 @@ ${blocks.map((block) => renderBlock(block, images, " ")).join("\n")}
1331
1367
  ...pageSize ? [` pageSize: ${jsString(pageSize)},`] : [],
1332
1368
  ...orientation ? [` orientation: ${jsString(orientation)},`] : [],
1333
1369
  ...theme ? [` theme: ${jsString(theme)},`] : [],
1370
+ ...lang ? [` lang: ${jsString(lang)},`] : [],
1334
1371
  ` createdAt: ${jsString(opts.createdAt)},`
1335
1372
  ];
1336
1373
  const entries = [
@@ -1396,6 +1433,7 @@ async function importMarkdown(ctx, opts) {
1396
1433
  }
1397
1434
  if (markdown.trim() === "") throw new OpsError(422, "the markdown is empty");
1398
1435
  const parsed = parseMarkdown(markdown);
1436
+ const language = opts.lang ?? (parsed.frontmatter.lang ? void 0 : detectLang(markdown));
1399
1437
  const pageSize = opts.pageSize ?? parsed.frontmatter.pageSize;
1400
1438
  if (pageSize !== void 0 && !isPageSizeName(pageSize)) throw new OpsError(422, `unsupported pageSize \`${pageSize}\` — use ${PAGE_SIZE_NAMES.join(", ")}`);
1401
1439
  const orientation = opts.orientation ?? parsed.frontmatter.orientation;
@@ -1441,6 +1479,7 @@ async function importMarkdown(ctx, opts) {
1441
1479
  ...opts.theme !== void 0 ? { theme: opts.theme } : {},
1442
1480
  ...opts.pageSize !== void 0 ? { pageSize: opts.pageSize } : {},
1443
1481
  ...opts.orientation !== void 0 ? { orientation: opts.orientation } : {},
1482
+ ...language ? { lang: language } : {},
1444
1483
  ...opts.cover !== void 0 ? { cover: opts.cover } : {},
1445
1484
  ...opts.contents !== void 0 ? { contents: opts.contents } : {},
1446
1485
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -1569,183 +1608,65 @@ function resolveOutDir(ctx, outDir) {
1569
1608
  if (resolved !== ctx.userCwd && !resolved.startsWith(ctx.userCwd + path.sep)) throw new OpsError(400, `outDir must stay inside the workspace: ${outDir}`);
1570
1609
  return resolved;
1571
1610
  }
1611
+ /**
1612
+ * Writes the document's files. With `each`, a document that exports
1613
+ * `records` is laid out and written once per row — `name` (or
1614
+ * `meta.recordName`) names each row's files.
1615
+ */
1572
1616
  async function exportDocument(ctx, docId, opts = {}) {
1573
1617
  const format = opts.format ?? "pdf";
1574
1618
  const dir = resolveOutDir(ctx, opts.outDir ?? "out");
1575
1619
  return withDoc(ctx, docId, async (renderer) => {
1576
1620
  await fs.mkdir(dir, { recursive: true });
1577
1621
  const written = [];
1622
+ const taken = /* @__PURE__ */ new Set();
1578
1623
  const write = async (name, bytes) => {
1579
1624
  const file = path.join(dir, name);
1580
1625
  await fs.writeFile(file, bytes);
1581
1626
  written.push(path.relative(ctx.userCwd, file));
1582
1627
  };
1583
- if (format === "pdf") await write(`${docId}.pdf`, await renderer.pdf());
1584
- else if (format === "html" || format === "docx") {
1585
- const bundle = format === "html" ? await renderer.html() : await renderer.docx();
1586
- if (!bundle) throw new OpsError(422, `document has no pages: ${docId}`);
1587
- await write(bundle.filename, Buffer.from(bundle.base64, "base64"));
1588
- } else {
1589
- const width = String(renderer.status.pageCount).length;
1590
- for (let page = 1; page <= renderer.status.pageCount; page++) await write(`${docId}-${String(page).padStart(width, "0")}.png`, await renderer.screenshot(page));
1628
+ const free = (base) => {
1629
+ let name = base;
1630
+ for (let n = 2; taken.has(name); n++) name = `${base}-${n}`;
1631
+ taken.add(name);
1632
+ return name;
1633
+ };
1634
+ const writeCopy = async (base) => {
1635
+ if (format === "pdf") await write(`${base}.pdf`, await renderer.pdf());
1636
+ else if (format === "html" || format === "docx") {
1637
+ const bundle = format === "html" ? await renderer.html() : await renderer.docx();
1638
+ if (!bundle) throw new OpsError(422, `document has no pages: ${docId}`);
1639
+ await write(`${base}${path.extname(bundle.filename)}`, Buffer.from(bundle.base64, "base64"));
1640
+ } else {
1641
+ const width = String(renderer.status.pageCount).length;
1642
+ for (let page = 1; page <= renderer.status.pageCount; page++) await write(`${base}-${String(page).padStart(width, "0")}.png`, await renderer.screenshot(page));
1643
+ }
1644
+ };
1645
+ if (!opts.each) {
1646
+ await writeCopy(docId);
1647
+ return {
1648
+ docId,
1649
+ format,
1650
+ pageCount: renderer.status.pageCount,
1651
+ files: written
1652
+ };
1653
+ }
1654
+ const records = renderer.status.records;
1655
+ if (records === 0) throw new OpsError(422, `${docId} has no records — export \`records\` (rows from a .csv) to write one copy per row`);
1656
+ let pageCount = 0;
1657
+ for (let index = 0; index < records; index++) {
1658
+ const name = await renderer.setRecord(index, opts.name);
1659
+ pageCount += renderer.status.pageCount;
1660
+ await writeCopy(free(name));
1591
1661
  }
1592
1662
  return {
1593
1663
  docId,
1594
1664
  format,
1595
- pageCount: renderer.status.pageCount,
1596
- files: written
1665
+ pageCount,
1666
+ files: written,
1667
+ records
1597
1668
  };
1598
1669
  });
1599
1670
  }
1600
1671
  //#endregion
1601
- //#region src/ops/library.ts
1602
- function themesRoot(ctx, themesDir = "themes") {
1603
- return path.resolve(ctx.userCwd, themesDir);
1604
- }
1605
- async function themeFiles(root) {
1606
- if (!existsSync(root)) return [];
1607
- return (await fg("*.md", {
1608
- cwd: root,
1609
- absolute: true,
1610
- onlyFiles: true
1611
- })).sort();
1612
- }
1613
- function demoFor(root, id) {
1614
- for (const cand of [
1615
- `${id}.demo.tsx`,
1616
- `${id}.demo.jsx`,
1617
- `${id}.demo.ts`,
1618
- `${id}.demo.js`
1619
- ]) {
1620
- const p = path.join(root, cand);
1621
- if (existsSync(p)) return p;
1622
- }
1623
- return null;
1624
- }
1625
- async function listThemes(ctx, themesDir) {
1626
- const root = themesRoot(ctx, themesDir);
1627
- const out = [];
1628
- for (const file of await themeFiles(root)) {
1629
- const id = path.basename(file, ".md");
1630
- const { fm } = parseFrontmatter$1(await fs.readFile(file, "utf8"), id);
1631
- out.push({
1632
- id,
1633
- name: fm.name,
1634
- description: fm.description,
1635
- pageSize: fm.pageSize,
1636
- mode: fm.mode,
1637
- hasDemo: demoFor(root, id) !== null
1638
- });
1639
- }
1640
- return out;
1641
- }
1642
- /**
1643
- * The full theme document. This is what an agent reads before writing a doc —
1644
- * the palette, type scale, and paste-ready components live in the body.
1645
- */
1646
- async function readTheme(ctx, themeId, themesDir) {
1647
- const root = themesRoot(ctx, themesDir);
1648
- const file = path.join(root, `${themeId}.md`);
1649
- if (!file.startsWith(root + path.sep) || !existsSync(file)) throw new OpsError(404, `theme not found: ${themeId}`);
1650
- const { fm, body } = parseFrontmatter$1(await fs.readFile(file, "utf8"), themeId);
1651
- const demoAbs = demoFor(root, themeId);
1652
- return {
1653
- id: themeId,
1654
- frontmatter: fm,
1655
- body,
1656
- demo: demoAbs ? await fs.readFile(demoAbs, "utf8") : void 0
1657
- };
1658
- }
1659
- /** `scope` is a document id, or `global` for the shared assets directory. */
1660
- async function listAssets(ctx, scope) {
1661
- const dir = resolveScopedAssetsDir(ctx.docsRoot, ctx.globalAssetsRoot, scope);
1662
- if (!dir) throw new OpsError(400, `invalid scope: ${scope}`);
1663
- if (!existsSync(dir)) return [];
1664
- const names = await fs.readdir(dir);
1665
- const out = [];
1666
- for (const filename of names.sort()) {
1667
- const stat = await fs.stat(path.join(dir, filename)).catch(() => null);
1668
- if (!stat?.isFile()) continue;
1669
- out.push({
1670
- scope,
1671
- filename,
1672
- bytes: stat.size,
1673
- importPath: assetImportPath(scope, filename)
1674
- });
1675
- }
1676
- return out;
1677
- }
1678
- async function writeAsset(ctx, scope, filename, data) {
1679
- const name = validateAssetName(filename);
1680
- if (!name) throw new OpsError(400, "invalid filename");
1681
- const dir = resolveScopedAssetsDir(ctx.docsRoot, ctx.globalAssetsRoot, scope);
1682
- if (!dir) throw new OpsError(400, `invalid scope: ${scope}`);
1683
- await fs.mkdir(dir, { recursive: true });
1684
- const file = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, name);
1685
- if (!file) throw new OpsError(400, "invalid filename");
1686
- await fs.writeFile(file, data);
1687
- return {
1688
- scope,
1689
- filename: name,
1690
- bytes: data.byteLength,
1691
- importPath: assetImportPath(scope, name)
1692
- };
1693
- }
1694
- async function deleteAsset(ctx, scope, filename) {
1695
- const file = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, filename);
1696
- if (!file) throw new OpsError(400, "invalid filename");
1697
- if (!existsSync(file)) throw new OpsError(404, `asset not found: ${scope}/${filename}`);
1698
- await fs.rm(file);
1699
- }
1700
- /** Which documents import this asset — check before deleting one. */
1701
- async function findAssetUsages(ctx, scope, filename) {
1702
- const importPath = assetImportPath(scope, filename);
1703
- const out = [];
1704
- for (const id of await listDocIds(ctx)) {
1705
- const entry = resolveEntry(ctx, id);
1706
- if (!entry) continue;
1707
- const count = countAssetUsages(await fs.readFile(entry, "utf8"), importPath);
1708
- if (count > 0) out.push({
1709
- docId: id,
1710
- count
1711
- });
1712
- }
1713
- return out;
1714
- }
1715
- async function listFolders(ctx) {
1716
- const manifest = await readManifest(ctx.manifestPath);
1717
- return {
1718
- folders: manifest.folders,
1719
- assignments: manifest.assignments
1720
- };
1721
- }
1722
- /** Folders always carry an icon; agents rarely care, so this is the fallback. */
1723
- const DEFAULT_FOLDER_ICON = {
1724
- type: "color",
1725
- value: "#6b7280"
1726
- };
1727
- async function createFolder(ctx, rawName, rawIcon) {
1728
- const name = validateName(rawName);
1729
- if (!name) throw new OpsError(400, "invalid folder name");
1730
- const icon = validateIcon(rawIcon ?? DEFAULT_FOLDER_ICON);
1731
- if (!icon) throw new OpsError(400, "invalid icon");
1732
- const manifest = await readManifest(ctx.manifestPath);
1733
- const folder = {
1734
- id: newFolderId(),
1735
- name,
1736
- icon
1737
- };
1738
- manifest.folders.push(folder);
1739
- await writeManifest(ctx.manifestPath, manifest);
1740
- return folder;
1741
- }
1742
- /** Filing only edits assignments — a document id never moves on disk. */
1743
- async function fileDocument(ctx, docId, folderId) {
1744
- const manifest = await readManifest(ctx.manifestPath);
1745
- if (folderId !== null && !manifest.folders.some((f) => f.id === folderId)) throw new OpsError(404, `folder not found: ${folderId}`);
1746
- if (folderId === null) delete manifest.assignments[docId];
1747
- else manifest.assignments[docId] = folderId;
1748
- await writeManifest(ctx.manifestPath, manifest);
1749
- }
1750
- //#endregion
1751
- export { listAssets as a, readTheme as c, closeRenderSession as d, exportDocument as f, diffDocument as g, slugify as h, findAssetUsages as i, writeAsset as l, importMarkdown as m, deleteAsset as n, listFolders as o, renderDocPage as p, fileDocument as r, listThemes as s, createFolder as t, checkLayout as u };
1672
+ export { importMarkdown as a, renderDocPage as i, closeRenderSession as n, slugify as o, exportDocument as r, diffDocument as s, checkLayout as t };
@@ -0,0 +1,36 @@
1
+ import path from "node:path";
2
+ import { fileURLToPath } from "node:url";
3
+ import { readFile } from "node:fs/promises";
4
+ //#region src/cli/package-version.ts
5
+ const PACKAGE_NAME = "@open-document/core";
6
+ /**
7
+ * Walks up for this package's own `package.json` instead of assuming a fixed
8
+ * depth: the bundler decides which chunk a module lands in, so `../../` is
9
+ * right from `dist/cli/` and wrong from `dist/`. Getting that wrong is silent —
10
+ * it reports `0.0.0`, or finds no templates, rather than failing.
11
+ */
12
+ async function findCorePackage() {
13
+ let dir = path.dirname(fileURLToPath(import.meta.url));
14
+ for (let up = 0; up < 6; up += 1) {
15
+ try {
16
+ const pkg = JSON.parse(await readFile(path.join(dir, "package.json"), "utf8"));
17
+ if (pkg.name === PACKAGE_NAME && pkg.version !== void 0) return {
18
+ root: dir,
19
+ version: pkg.version
20
+ };
21
+ } catch {}
22
+ const parent = path.dirname(dir);
23
+ if (parent === dir) break;
24
+ dir = parent;
25
+ }
26
+ return null;
27
+ }
28
+ async function readCoreVersion() {
29
+ return (await findCorePackage())?.version ?? "0.0.0";
30
+ }
31
+ /** The installed package's root — where `skills/` and `templates/` ship. */
32
+ async function corePackageRoot() {
33
+ return (await findCorePackage())?.root ?? null;
34
+ }
35
+ //#endregion
36
+ export { readCoreVersion as n, corePackageRoot as t };
@@ -1,4 +1,4 @@
1
- import { t as createViteConfig } from "./config-CvzpyAUA.js";
1
+ import { t as createViteConfig } from "./config-9IdbhVuT.js";
2
2
  import { mergeConfig, preview as preview$1 } from "vite";
3
3
  //#region src/cli/preview.ts
4
4
  async function preview(opts = {}) {
@@ -65,6 +65,32 @@ declare function designToCssVars(d: DesignSystem): Record<string, string>;
65
65
  declare function cssVarsToString(vars: Record<string, string>): string;
66
66
  declare const defaultDesign: DesignSystem;
67
67
  //#endregion
68
+ //#region src/app/lib/records.d.ts
69
+ /** One row of a document's `records` — usually a line of an imported `.csv`. */
70
+ type DataRecord = Record<string, unknown>;
71
+ /**
72
+ * The row this copy of the document is printed for. A document that exports
73
+ * `records` is laid out once per row; every page reads the same one. Outside a
74
+ * document with records — a card in the document list — it is `undefined`.
75
+ */
76
+ declare function useRecord<T extends DataRecord = DataRecord>(): T | undefined;
77
+ type FieldProps = {
78
+ /** The column to print. */
79
+ name: string;
80
+ /** Printed when the row has no value for it. */
81
+ fallback?: ReactNode;
82
+ };
83
+ /**
84
+ * One value of the current row, as text. Where no row is set — a document
85
+ * card, a theme preview — it prints the column's name in guillemets, so the
86
+ * layout still shows what goes where.
87
+ */
88
+ declare function Field({ name, fallback }: FieldProps): import("react").DetailedReactHTMLElement<{
89
+ style: {
90
+ opacity: number;
91
+ };
92
+ }, HTMLElement> | import("react").DetailedReactHTMLElement<import("react").HTMLAttributes<HTMLElement>, HTMLElement> | null;
93
+ //#endregion
68
94
  //#region src/app/lib/sdk.d.ts
69
95
  /** The only sheets a document may be laid out on. */
70
96
  declare const PAGE_SIZE_NAMES: readonly ["A4", "B4", "A3"];
@@ -127,12 +153,31 @@ type DocMeta = {
127
153
  createdAt?: string;
128
154
  /** What numbered items are called — `圖`/`表` instead of `Figure`/`Table`. */
129
155
  labels?: Partial<LabelVocabulary>;
156
+ /**
157
+ * The language the document is written in, as a BCP 47 tag — `zh-Hant-TW`,
158
+ * `ja`, `ko`, `en-GB`. It decides glyph shapes for shared Han characters,
159
+ * which line-breaking rules apply, and the language an exported file
160
+ * declares. English when unset.
161
+ */
162
+ lang?: string;
163
+ /**
164
+ * With `records`: the file name for each row's copy — `{column}` takes the
165
+ * row's value, `{#}` its number. `<id>-{#}` when unset.
166
+ */
167
+ recordName?: string;
168
+ /** With `records`: the column that names a row in the viewer's picker. */
169
+ recordLabel?: string;
130
170
  };
131
171
  type DocModule = {
132
172
  default: DocEntry[];
133
173
  meta?: DocMeta;
134
174
  design?: DesignSystem;
175
+ /**
176
+ * Rows to print the document for, one copy each — usually an imported
177
+ * `.csv`. Pages read the current row with `useRecord()` or `<Field>`.
178
+ */
179
+ records?: DataRecord[];
135
180
  };
136
181
  declare function resolvePageGeometry(meta?: DocMeta): PageGeometry;
137
182
  //#endregion
138
- export { useDocLabels as A, cssVarsToString as C, LabelKind as D, LabelEntry as E, LabelVocabulary as O, DesignTypeScale as S, designToCssVars as T, isPageSizeName as _, DocModule as a, DesignPalette as b, ExportFormat as c, Orientation as d, PAGE_SIZES as f, isOrientation as g, PageSizeName as h, DocMeta as i, useDocLabel as k, FlowSection as l, PageGeometry as m, DEFAULT_PAGE_SIZE as n, DocPage as o, PAGE_SIZE_NAMES as p, DocEntry as r, EXPORT_FORMATS as s, DEFAULT_ORIENTATION as t, ORIENTATIONS as u, resolvePageGeometry as v, defaultDesign as w, DesignSystem as x, DesignFonts as y };
183
+ export { LabelEntry as A, DesignFonts as C, cssVarsToString as D, DesignTypeScale as E, LabelVocabulary as M, useDocLabel as N, defaultDesign as O, useDocLabels as P, useRecord as S, DesignSystem as T, isPageSizeName as _, DocModule as a, Field as b, ExportFormat as c, Orientation as d, PAGE_SIZES as f, isOrientation as g, PageSizeName as h, DocMeta as i, LabelKind as j, designToCssVars as k, FlowSection as l, PageGeometry as m, DEFAULT_PAGE_SIZE as n, DocPage as o, PAGE_SIZE_NAMES as p, DocEntry as r, EXPORT_FORMATS as s, DEFAULT_ORIENTATION as t, ORIENTATIONS as u, resolvePageGeometry as v, DesignPalette as w, FieldProps as x, DataRecord as y };
@@ -0,0 +1,34 @@
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";
4
+ import chalk from "chalk";
5
+ //#region src/cli/templates.ts
6
+ /**
7
+ * Every template a document can start from, with the name `new --template`
8
+ * takes in the first column — the list is the documentation of the names.
9
+ */
10
+ async function printTemplates(opts = {}) {
11
+ const ctx = await cliContext();
12
+ const templates = await listTemplates(ctx);
13
+ if (opts.json) {
14
+ process.stdout.write(`${JSON.stringify(templates, null, 2)}\n`);
15
+ return;
16
+ }
17
+ const width = Math.max(...templates.map((t) => t.name.length), 4);
18
+ for (const template of templates) {
19
+ const where = template.source === "workspace" ? chalk.cyan(" (this workspace)") : "";
20
+ process.stdout.write(` ${chalk.bold(template.name.padEnd(width))} ${template.title}${where}\n` + (template.description ? ` ${" ".repeat(width)} ${chalk.dim(template.description)}\n` : ""));
21
+ }
22
+ process.stdout.write(chalk.dim(`\nopen-doc new <id> --template <name> · your own: templates/<name>/index.tsx\n`));
23
+ }
24
+ async function newDoc(docId, opts = {}) {
25
+ const ctx = await cliContext();
26
+ const result = await createFromTemplate(ctx, {
27
+ template: opts.template ?? "blank",
28
+ ...docId ? { docId } : {},
29
+ ...opts.title !== void 0 ? { title: opts.title } : {}
30
+ });
31
+ process.stdout.write(`${chalk.green("✓")} ${chalk.bold(result.id)} → ${result.entry} ${chalk.dim(`(from ${opts.template ?? "blank"})`)}\n`);
32
+ }
33
+ //#endregion
34
+ export { newDoc, printTemplates };
@@ -1,2 +1,2 @@
1
- import { j as openDocPlugin, t as createViteConfig } from "../config-CvzpyAUA.js";
1
+ import { I as openDocPlugin, t as createViteConfig } from "../config-9IdbhVuT.js";
2
2
  export { createViteConfig, openDocPlugin };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-document/core",
3
- "version": "0.10.0",
3
+ "version": "0.12.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": {
@@ -29,6 +29,7 @@
29
29
  "env.d.ts",
30
30
  "src/app",
31
31
  "skills",
32
+ "templates",
32
33
  "README.md",
33
34
  "README.zh-TW.md"
34
35
  ],
@@ -5,7 +5,7 @@ description: Use this skill when the user asks to apply, process, or clear the c
5
5
 
6
6
  # Apply inspector comments
7
7
 
8
- The dev UI's **Inspect** mode lets the user click any element on a page and leave a note. Each note is written into the document source as a marker:
8
+ In the viewer the user leaves notes from the **Comments** panel (`M`) or the element panel in edit mode, and the panel's **Copy request for the agent** button hands you `/apply-comments docs/<id>` — when a path is given, work on that document only. Each note is written into the document source as a marker:
9
9
 
10
10
  ```tsx
11
11
  <p style={p}>
@@ -18,6 +18,8 @@ The marker is always the **first child of the element the note is about** — th
18
18
 
19
19
  ## Step 1 — Find the pending comments
20
20
 
21
+ If the request named a document (`docs/<id>`), look only there.
22
+
21
23
  ```bash
22
24
  grep -rn "@doc-comment" docs/
23
25
  ```
@@ -11,6 +11,8 @@ You only write files under `docs/<id>/`. Never modify `package.json`, `open-doc.
11
11
 
12
12
  **If the user already has the content written as Markdown, don't retype it into JSX.** `open-doc import <file.md> --id <id>` produces a real document — `flow()` body, cover, contents, local images copied into the document's assets — which you then refine. Steps 0–2 still apply for the parts the import cannot know (theme, page size, visual direction).
13
13
 
14
+ **If a template fits the kind of document, start from it.** `open-doc templates` lists them — built-in (`report`, `proposal`, `meeting-notes`, `letter`, `certificate`, `blank`) and the workspace's own under `templates/<name>/` — with the name to pass on. `open-doc new <id> --template <name> --title "<title>"` copies one into `docs/<id>/`, retitled and dated today, and you then replace its stand-in content with the real substance (Steps 1–2 still apply). Over MCP, the same is `list_templates` and `create_from_template`.
15
+
14
16
  ## Step 0 — Pick a theme
15
17
 
16
18
  List files under `themes/`. If any theme markdown exists (anything other than `README.md`), call `AskUserQuestion` with each theme id as an option plus a final **"no theme — design from scratch"** option. (`AskUserQuestion` holds at most 4 options — with 4+ themes, offer the 3 most relevant plus "no theme"; the auto-added "Other" lets the user name an omitted one.)
@@ -60,6 +60,8 @@ export default [Cover, Body] satisfies DocPage[];
60
60
  - `export default` is a **non-empty array of entries**. An entry is either a zero-prop React component (one fixed page) or a `flow(<>…</>)` section the framework paginates by measuring. Mix them freely — the usual shape is a fixed cover, a fixed contents page, then one flow section for the body.
61
61
  - **Default to `flow()` for body content.** Hand-splitting prose into fixed pages produces documents where every heading starts a half-empty page. Read `references/pagination.md` before writing either kind.
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
+ - `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
+ - **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.
63
65
  - `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.
64
66
 
65
67
  ## Two ways to fill pages
@@ -19,6 +19,27 @@ export const CARD_GRID =
19
19
  * card has to know how wide its column came out. Starts at the narrowest width
20
20
  * so the first paint already has the right shape.
21
21
  */
22
+ /** Every card's preview box: a portrait A4, the sheet most documents print on. */
23
+ const FRAME_RATIO = 297 / 210;
24
+
25
+ /**
26
+ * How a sheet sits in a card's preview box. The box is the same for every
27
+ * card, so titles line up along a row; the sheet is scaled to fit inside it
28
+ * whole and centred — a landscape page is letterboxed on the canvas colour,
29
+ * never cropped, since a preview that hides part of the page misreports it.
30
+ */
31
+ export function fitInCard(
32
+ cardWidth: number,
33
+ sheet: { width: number; height: number },
34
+ ): { frameHeight: number; scale: number } {
35
+ const frameHeight = cardWidth * FRAME_RATIO;
36
+ const scale =
37
+ sheet.width > 0 && sheet.height > 0
38
+ ? Math.min(cardWidth / sheet.width, frameHeight / sheet.height)
39
+ : 0;
40
+ return { frameHeight, scale };
41
+ }
42
+
22
43
  export function useCardWidth<T extends HTMLElement>(): [RefObject<T>, number] {
23
44
  const ref = useRef<T>(null);
24
45
  const [width, setWidth] = useState(CARD_WIDTH);