grimoire3d 0.3.1 → 0.3.2-dev.134ed8c

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 (111) hide show
  1. package/README.md +20 -8
  2. package/cli/cli.js +29 -12
  3. package/cli/content.js +93 -20
  4. package/cli/markdown.js +51 -0
  5. package/cli/shelf-groups.d.ts +7 -0
  6. package/cli/shelf-groups.js +38 -0
  7. package/cli/static-pages.js +51 -30
  8. package/dist/site/assets/BookReader-CMVm2j3P.js +2 -0
  9. package/dist/site/assets/{BookScene-DgLf6Enk.js → BookScene-CIoKx_8t.js} +1 -1
  10. package/dist/site/assets/DiagramViewer-CYbBEQgH.js +1 -0
  11. package/dist/site/assets/MermaidDiagram-B1zz-cJX.js +44 -0
  12. package/dist/site/assets/{PageMarkdown-BDd7uOW4.js → PageMarkdown-nxVv69Vf.js} +57 -57
  13. package/dist/site/assets/SearchDialog--R9gfmZJ.css +1 -0
  14. package/dist/site/assets/SearchDialog-Df-utrwU.js +1 -0
  15. package/dist/site/assets/{abnfDiagram-S7VZAUFO-Y8BZ4vf8.js → abnfDiagram-S7VZAUFO-BR8IGxQB.js} +1 -1
  16. package/dist/site/assets/{architecture-WOLXFQ4H-TQCyxI9u.js → architecture-WOLXFQ4H-90MJGgT8.js} +1 -1
  17. package/dist/site/assets/{architectureDiagram-YGSQEFNW-Bn495Re4.js → architectureDiagram-YGSQEFNW-DxpbuJaR.js} +1 -1
  18. package/dist/site/assets/{blockDiagram-APKKGZFW-hTc94DZr.js → blockDiagram-APKKGZFW-CKWSsD8U.js} +1 -1
  19. package/dist/site/assets/{c4Diagram-KJ2TOQU5-3w_jvLJE.js → c4Diagram-KJ2TOQU5-CdqoyEn3.js} +1 -1
  20. package/dist/site/assets/{chunk-6MUBBAK2-BkD8UD1y.js → chunk-6MUBBAK2-Dgz7ppMx.js} +1 -1
  21. package/dist/site/assets/{chunk-AXFCVDMN-Rq07LJGo.js → chunk-AXFCVDMN-BqHDIzr7.js} +1 -1
  22. package/dist/site/assets/{chunk-BG4553SI-BbFZng8F.js → chunk-BG4553SI-DKMzv0Bz.js} +1 -1
  23. package/dist/site/assets/{chunk-DQASFODM-8AEVeEgt.js → chunk-DQASFODM-BeNhzMJf.js} +1 -1
  24. package/dist/site/assets/{chunk-HFQBQIA3-C40nK8Y3.js → chunk-HFQBQIA3-Bm5lhsd5.js} +1 -1
  25. package/dist/site/assets/{chunk-KQLB2F66-Bf_S_2K6.js → chunk-KQLB2F66-UC6157Ue.js} +1 -1
  26. package/dist/site/assets/{chunk-KS47KZWR-CV-CVFml.js → chunk-KS47KZWR-BSd8af6M.js} +1 -1
  27. package/dist/site/assets/{chunk-LEVMRMFU-OVwQP4HJ.js → chunk-LEVMRMFU-D0PIc1p1.js} +1 -1
  28. package/dist/site/assets/{chunk-M57EVK23-BEQIQAdR.js → chunk-M57EVK23-D-ico1Th.js} +1 -1
  29. package/dist/site/assets/{chunk-OY52VR5R-3JkK4aqh.js → chunk-OY52VR5R-C_8A3BNy.js} +1 -1
  30. package/dist/site/assets/{chunk-QB3YPZ4I-CLGXTebg.js → chunk-QB3YPZ4I-D90x0rRF.js} +1 -1
  31. package/dist/site/assets/{chunk-R3KSYZAL-Co3KR3vY.js → chunk-R3KSYZAL-B7THQv9a.js} +1 -1
  32. package/dist/site/assets/{chunk-STOXU5M4-BbHn-JCi.js → chunk-STOXU5M4-DQXfE8bD.js} +1 -1
  33. package/dist/site/assets/{chunk-TU62E6Q5-DkhMx9Q4.js → chunk-TU62E6Q5-B5cs1tiB.js} +1 -1
  34. package/dist/site/assets/{chunk-X4PVCEUW-Cw_6SQQl.js → chunk-X4PVCEUW-DGKUon3k.js} +1 -1
  35. package/dist/site/assets/{chunk-XXDRQBXY-CRYRc_Wt.js → chunk-XXDRQBXY-B0eE8T6-.js} +1 -1
  36. package/dist/site/assets/{classDiagram-v2-L25IHNXF-DjHToGrh.js → classDiagram-v2-L25IHNXF-Cz-9fhlG.js} +1 -1
  37. package/dist/site/assets/{cose-bilkent-JH36ORCC-7nTgLcm_.js → cose-bilkent-JH36ORCC-B92ZVq5z.js} +1 -1
  38. package/dist/site/assets/cynefin-EF2NZ3EQ-B3m7fpVf.js +1 -0
  39. package/dist/site/assets/{cynefinDiagram-L36ESFBY-D6H0WCez.js → cynefinDiagram-L36ESFBY-yKHt1pcs.js} +1 -1
  40. package/dist/site/assets/{d3-selection-_ztfYxKb.js → d3-selection-CVxgF8Ya.js} +1 -1
  41. package/dist/site/assets/{dagre-SPEB5RXH-CqCGPgYG.js → dagre-SPEB5RXH-BIZik_0j.js} +1 -1
  42. package/dist/site/assets/{diagram-3B7GL73J-DDNF89rH.js → diagram-3B7GL73J-BwMAsTa9.js} +1 -1
  43. package/dist/site/assets/{diagram-DNEMPZML-DnHTiWSl.js → diagram-DNEMPZML-BQUlAJPu.js} +1 -1
  44. package/dist/site/assets/{diagram-L3MUGCDN-BP4RDryv.js → diagram-L3MUGCDN-fUIimxx6.js} +1 -1
  45. package/dist/site/assets/{diagram-LA4NIPWU-YhfaR52L.js → diagram-LA4NIPWU-5Of_CE5j.js} +1 -1
  46. package/dist/site/assets/{diagram-MHCOC4E2-B2CokZ6p.js → diagram-MHCOC4E2-B_2Yly0I.js} +1 -1
  47. package/dist/site/assets/{diagram-XPFHEONP-BiXyQAhI.js → diagram-XPFHEONP-CbTOu_Cl.js} +1 -1
  48. package/dist/site/assets/{dist-DNnrlBGx.js → dist-CAxpCi_w.js} +1 -1
  49. package/dist/site/assets/{ebnfDiagram-UZSYDL2S-HqUNigiS.js → ebnfDiagram-UZSYDL2S-CPiUy3zC.js} +1 -1
  50. package/dist/site/assets/{elk-XV6XMXQE-B1gKu4To.js → elk-XV6XMXQE-g9F7LdsC.js} +1 -1
  51. package/dist/site/assets/{erDiagram-EYBAPDEH-87mLelxm.js → erDiagram-EYBAPDEH-Cqnqz-s8.js} +1 -1
  52. package/dist/site/assets/{eventmodeling-K75KTNOO-DlYKH73r.js → eventmodeling-K75KTNOO--5jIqQqd.js} +1 -1
  53. package/dist/site/assets/flowDiagram-MALGAFMO-BaEkQXGW.js +1 -0
  54. package/dist/site/assets/{ganttDiagram-23REXITY-BW5D0BwF.js → ganttDiagram-23REXITY-C6aslBaf.js} +1 -1
  55. package/dist/site/assets/gitGraph-VSP46ZUC-D9rN03e-.js +1 -0
  56. package/dist/site/assets/{gitGraphDiagram-STJD7YCW-C1OitBdM.js → gitGraphDiagram-STJD7YCW-RAWwBnxA.js} +1 -1
  57. package/dist/site/assets/index-DMzLZTw8.css +1 -0
  58. package/dist/site/assets/index-GvaNKs5v.js +2 -0
  59. package/dist/site/assets/info-OHQRW6UA-WHh3stkK.js +1 -0
  60. package/dist/site/assets/{infoDiagram-KBXO4MBG-DYvBfRFf.js → infoDiagram-KBXO4MBG-DyBbty8F.js} +1 -1
  61. package/dist/site/assets/{ishikawaDiagram-M35NCXHK-HxvcNDvi.js → ishikawaDiagram-M35NCXHK-CSWNOLwv.js} +1 -1
  62. package/dist/site/assets/{journeyDiagram-OPLOXDXO-YgjSYtDU.js → journeyDiagram-OPLOXDXO-BZPCEVyH.js} +1 -1
  63. package/dist/site/assets/{kanban-definition-BZKZHSQY-B60A1uY_.js → kanban-definition-BZKZHSQY-DteyA0IO.js} +1 -1
  64. package/dist/site/assets/{mermaid-parser.core-CqUMb98c.js → mermaid-parser.core-PxovB7hr.js} +3 -3
  65. package/dist/site/assets/{mindmap-definition-I2QAS2VK-Bbg1xV3W.js → mindmap-definition-I2QAS2VK-Bmmuqiot.js} +1 -1
  66. package/dist/site/assets/packet-JDAUHWVQ-C_UAajnp.js +1 -0
  67. package/dist/site/assets/{pegDiagram-FD4XPPHP-BzXEwr79.js → pegDiagram-FD4XPPHP-qhSCN5AW.js} +1 -1
  68. package/dist/site/assets/pie-XZMESJXO-UzrpEVGj.js +1 -0
  69. package/dist/site/assets/{pieDiagram-J4AKIIQI--1HbHEjB.js → pieDiagram-J4AKIIQI-C_q7bEoU.js} +1 -1
  70. package/dist/site/assets/{quadrantDiagram-XTYBLID2-4ICy76mk.js → quadrantDiagram-XTYBLID2-uB-u2czb.js} +1 -1
  71. package/dist/site/assets/radar-ABXABTNO-DzC9Oc5w.js +1 -0
  72. package/dist/site/assets/railroad-I3PHUGI6-D8bliAMX.js +1 -0
  73. package/dist/site/assets/{railroad-abnf-LNEFI6M7-DA6sDEMP.js → railroad-abnf-LNEFI6M7-DUVxlunf.js} +1 -1
  74. package/dist/site/assets/{railroad-ebnf-DWYD2UWJ-fdx4cu4d.js → railroad-ebnf-DWYD2UWJ-CP_ugtYj.js} +1 -1
  75. package/dist/site/assets/{railroad-peg-JR7BVNR7-D2sGopBU.js → railroad-peg-JR7BVNR7-CbBki0GK.js} +1 -1
  76. package/dist/site/assets/{railroadDiagram-MRQ6NCDL-DfWDmouy.js → railroadDiagram-MRQ6NCDL-D-k3w0vd.js} +1 -1
  77. package/dist/site/assets/{requirementDiagram-Y7LWUY3S-Dfwwar5x.js → requirementDiagram-Y7LWUY3S-D5Skozo6.js} +1 -1
  78. package/dist/site/assets/{sankeyDiagram-WGJFYUXA-CQgnTJdB.js → sankeyDiagram-WGJFYUXA-DrulYzdK.js} +1 -1
  79. package/dist/site/assets/{sequenceDiagram-5NDRBG5M-DjlGr37h.js → sequenceDiagram-5NDRBG5M-yKGWhmS2.js} +1 -1
  80. package/dist/site/assets/shelf-plate-VGKVAZYL.webp +0 -0
  81. package/dist/site/assets/shelf-screw-left-C1fF6P1A.webp +0 -0
  82. package/dist/site/assets/shelf-screw-right-BRDCLkfl.webp +0 -0
  83. package/dist/site/assets/{stateDiagram-v2-FJ4FJNEA-C8hPnY9-.js → stateDiagram-v2-FJ4FJNEA-CUKsGWYN.js} +1 -1
  84. package/dist/site/assets/{swimlanes-UMQ2AFYF-BJByBjS8.js → swimlanes-UMQ2AFYF-Do_WCZrU.js} +1 -1
  85. package/dist/site/assets/swimlanesDiagram-OMPLPG4O-D3pKyr1_.js +8 -0
  86. package/dist/site/assets/{timeline-definition-SEUHKTQE-HH42rWWR.js → timeline-definition-SEUHKTQE-CWHDDSE-.js} +1 -1
  87. package/dist/site/assets/treeView-D4JQ5SDB-DxTMmZMx.js +1 -0
  88. package/dist/site/assets/treemap-SAJKECNS-Bzf9exlH.js +1 -0
  89. package/dist/site/assets/{usecaseDiagram-AFA6YXN4-D5o7N3Yj.js → usecaseDiagram-AFA6YXN4-BHxDH4ur.js} +1 -1
  90. package/dist/site/assets/{vennDiagram-NNMJR3RB-DwQU-u3H.js → vennDiagram-NNMJR3RB-Bogzeqil.js} +1 -1
  91. package/dist/site/assets/wardley-7MLQ67FV-D7NEUI5n.js +1 -0
  92. package/dist/site/assets/{wardleyDiagram-S7YFUSEH-FsHgD8JM.js → wardleyDiagram-S7YFUSEH-BA5OORVq.js} +1 -1
  93. package/dist/site/assets/{xychartDiagram-GGNKY7IX-DJx6ZmCD.js → xychartDiagram-GGNKY7IX-DbEC6gtH.js} +1 -1
  94. package/dist/site/index.html +2 -2
  95. package/package.json +3 -2
  96. package/dist/site/assets/BookReader-DCWs90gY.js +0 -2
  97. package/dist/site/assets/MermaidDiagram-DzLLjQd2.js +0 -44
  98. package/dist/site/assets/cynefin-EF2NZ3EQ-Cu61kdvu.js +0 -1
  99. package/dist/site/assets/flowDiagram-MALGAFMO-KSUWrWQ2.js +0 -1
  100. package/dist/site/assets/gitGraph-VSP46ZUC-BJLoizwA.js +0 -1
  101. package/dist/site/assets/index-DeHKbPiY.js +0 -2
  102. package/dist/site/assets/index-ETbk37vV.css +0 -1
  103. package/dist/site/assets/info-OHQRW6UA-BCub5SIv.js +0 -1
  104. package/dist/site/assets/packet-JDAUHWVQ-m4zlsMGW.js +0 -1
  105. package/dist/site/assets/pie-XZMESJXO-csYvMoQI.js +0 -1
  106. package/dist/site/assets/radar-ABXABTNO-DFrK7OJ2.js +0 -1
  107. package/dist/site/assets/railroad-I3PHUGI6--GZDM0oV.js +0 -1
  108. package/dist/site/assets/swimlanesDiagram-OMPLPG4O-B2wKaVby.js +0 -8
  109. package/dist/site/assets/treeView-D4JQ5SDB-98lIHgvt.js +0 -1
  110. package/dist/site/assets/treemap-SAJKECNS-BtSu7-Ys.js +0 -1
  111. package/dist/site/assets/wardley-7MLQ67FV-WT1ESs67.js +0 -1
package/README.md CHANGED
@@ -8,14 +8,22 @@ Turn Markdown into 3D books you can open and flip through in a browser.
8
8
 
9
9
  [Read the documentation](https://kkm-horikawa.github.io/grimoire3d/)
10
10
 
11
+ ## Quick start
12
+
13
+ Run `npx grimoire3d serve` from your project directory and open the URL it prints. Grimoire3D looks for Markdown in the `docs/` folder directly under that directory by default. Existing Markdown works without a scaffold. See the [configuration guide](https://kkm-horikawa.github.io/grimoire3d/read/publishing/metadata/) when you want to customize the library.
14
+
15
+ If your Markdown lives in `handbook/`, add `--docs-dir handbook` to either `serve` or `build`.
16
+
11
17
  ## Install
12
18
 
13
- Use a maintained Node.js 22, 24, or 26 release. Install Grimoire3D from npm in the project where you want to write your books. If the project has no `package.json`, run `npm init -y` first.
19
+ Use a maintained Node.js 22, 24, or 26 release. To pin the CLI for your project, add it as a development dependency.
14
20
 
15
21
  ```sh
16
22
  npm install --save-dev grimoire3d
17
23
  ```
18
24
 
25
+ For a global installation, run `npm install -g grimoire3d`, then use `grimo serve` or `grimo build`.
26
+
19
27
  ## Write and preview
20
28
 
21
29
  Create `docs/field-notes/index.md`.
@@ -26,21 +34,25 @@ Create `docs/field-notes/index.md`.
26
34
  This is my first 3D book.
27
35
  ```
28
36
 
29
- `docs` 直下の各フォルダが1冊、その中のMarkdownが章になります。`docs` 直下に並べたMarkdownは、まとめて別の1冊になります。入れ子のフォルダは同じ本の章グループです。
37
+ Each folder directly under `docs/` becomes a book, and its Markdown files become chapters. Loose Markdown files directly in `docs/` share a separate book. Nested folders form chapter groups within the same book.
38
+
39
+ Books use the title or top-level heading in their `index.md`, then the first heading in their `README.md`. The default title is **Overview** for loose files and the folder name for each folder book.
30
40
 
31
41
  ```text
32
42
  docs/
33
- ├── index.md # docs直下のMarkdownで1冊
43
+ ├── index.md # Book of loose Markdown files
34
44
  ├── notes.md
35
- └── field-notes/ # 別の1冊
36
- ├── index.md # 本の導入・設定
45
+ └── field-notes/ # Another book
46
+ ├── index.md # Introduction and book settings
37
47
  ├── setup.md
38
- └── examples/ # 同じ本の章グループ
48
+ └── examples/ # Chapter group in the same book
39
49
  ├── index.md
40
50
  └── cli.md
41
51
  ```
42
52
 
43
- 各 `index.md` のYAMLに `chapters: [setup.md, examples/]` と書くと、導入の後を指定順に並べられます。未指定の章は後ろにファイル名順で続きます。本が7冊以上、またはカテゴリー・公開日を設定すると検索欄が表示されます。
53
+ Set `chapters: [setup.md, examples/]` in each folder's `index.md` front matter to choose what follows its introduction. Unlisted chapters follow in natural filename order.
54
+
55
+ Choose **Search text** in the library to search across books, or **Search this book** in the reader to search only the current book. Select a result to open the matching section. The **Find a book** title filter appears with seven or more books, or when a book has a category or publication date.
44
56
 
45
57
  ```sh
46
58
  npx grimoire3d serve
@@ -58,6 +70,6 @@ npx grimoire3d build
58
70
 
59
71
  Deploy the contents of `dist/` to any static host, including Cloudflare Pages and GitHub Pages. Use `--out-dir site` to choose a different output directory.
60
72
 
61
- 引用、リスト、チェックリスト、折りたたみ、数式、用語定義、コードの色分け、脚注に対応します。[記述例と実際の表示](https://kkm-horikawa.github.io/grimoire3d/read/writing/formatting/)と、[SEO・YAML設定例](https://kkm-horikawa.github.io/grimoire3d/read/publishing/metadata/)を公式ドキュメントで確認できます。
73
+ Block quotes, lists, task lists, collapsible notes, math, definition lists, syntax highlighting, and footnotes are supported. See the [syntax and rendered examples](https://kkm-horikawa.github.io/grimoire3d/read/writing/formatting/) and [site settings and SEO examples](https://kkm-horikawa.github.io/grimoire3d/read/publishing/metadata/).
62
74
 
63
75
  [Contributing](CONTRIBUTING.md) · [MIT License](LICENSE)
package/cli/cli.js CHANGED
@@ -78,6 +78,11 @@ function serializedLibrary(library) {
78
78
  return new Map([
79
79
  ["library.json", json(library.manifest)],
80
80
  ...library.books.map((book) => [`books/${book.id}.json`, json(book)]),
81
+ ["search/library.json", json(library.searchBooks)],
82
+ ...library.searchBooks.map((book) => [
83
+ `search/books/${book.id}.json`,
84
+ json([book]),
85
+ ]),
81
86
  ]);
82
87
  }
83
88
 
@@ -140,8 +145,10 @@ function snapshot(library) {
140
145
  };
141
146
  }
142
147
 
143
- function serve(cwd, port, initial) {
148
+ function serve(cwd, port, initial, docsDir) {
144
149
  let current = snapshot(initial);
150
+ let watchedDirectory = initial.docsDirectory;
151
+ let docsWatcher = watch(watchedDirectory, { recursive: true }, schedule);
145
152
  let timer;
146
153
  let changes = 0;
147
154
  const clients = new Set();
@@ -151,8 +158,18 @@ function serve(cwd, port, initial) {
151
158
  async function refresh() {
152
159
  const revision = ++changes;
153
160
  try {
154
- const library = await readLibrary(cwd, await readSettings(cwd));
161
+ const library = await readLibrary(cwd, await readSettings(cwd), docsDir);
155
162
  if (revision !== changes) return;
163
+ if (library.docsDirectory !== watchedDirectory) {
164
+ const nextWatcher = watch(
165
+ library.docsDirectory,
166
+ { recursive: true },
167
+ schedule
168
+ );
169
+ docsWatcher.close();
170
+ docsWatcher = nextWatcher;
171
+ watchedDirectory = library.docsDirectory;
172
+ }
156
173
  current = snapshot(library);
157
174
  showIssues(library);
158
175
  } catch (error) {
@@ -166,12 +183,9 @@ function serve(cwd, port, initial) {
166
183
  clearTimeout(timer);
167
184
  timer = setTimeout(() => void refresh(), 140);
168
185
  }
169
- const watchers = [
170
- watch(join(cwd, "docs"), { recursive: true }, schedule),
171
- watch(cwd, (_event, name) => {
172
- if (name === "grimoire.yml") schedule();
173
- }),
174
- ];
186
+ const settingsWatcher = watch(cwd, (_event, name) => {
187
+ if (name === "grimoire.yml") schedule();
188
+ });
175
189
 
176
190
  const server = createServer(async (request, response) => {
177
191
  try {
@@ -285,7 +299,8 @@ function serve(cwd, port, initial) {
285
299
  });
286
300
  const stopWatchers = () => {
287
301
  clearTimeout(timer);
288
- for (const watcher of watchers) watcher.close();
302
+ docsWatcher.close();
303
+ settingsWatcher.close();
289
304
  };
290
305
  server.on("error", (error) => {
291
306
  stopWatchers();
@@ -307,12 +322,13 @@ async function main() {
307
322
  options: {
308
323
  help: { type: "boolean", short: "h" },
309
324
  port: { type: "string" },
325
+ "docs-dir": { type: "string" },
310
326
  "out-dir": { type: "string" },
311
327
  },
312
328
  });
313
329
  if (!command || values.help) {
314
330
  console.log(
315
- "grimoire3d serve [--port 3000]\ngrimoire3d build [--out-dir dist]"
331
+ "grimoire3d serve [--docs-dir docs] [--port 3000]\ngrimoire3d build [--docs-dir docs] [--out-dir dist]"
316
332
  );
317
333
  return;
318
334
  }
@@ -320,7 +336,8 @@ async function main() {
320
336
  throw new Error(`Unknown command: ${command}. See --help.`);
321
337
  const cwd = process.cwd();
322
338
  const settings = await readSettings(cwd);
323
- const library = await readLibrary(cwd, settings);
339
+ const docsDir = values["docs-dir"];
340
+ const library = await readLibrary(cwd, settings, docsDir);
324
341
  showIssues(library);
325
342
  if (command === "build") {
326
343
  const output = await writeStaticSite(
@@ -341,7 +358,7 @@ async function main() {
341
358
  : "--port must be an integer from 0 to 65535."
342
359
  );
343
360
  }
344
- serve(cwd, port, library);
361
+ serve(cwd, port, library, docsDir);
345
362
  }
346
363
 
347
364
  main().catch((error) => {
package/cli/content.js CHANGED
@@ -1,5 +1,14 @@
1
1
  import { readdir, readFile, realpath, stat } from "node:fs/promises";
2
- import { extname, isAbsolute, join, posix, relative, sep } from "node:path";
2
+ import {
3
+ basename,
4
+ extname,
5
+ isAbsolute,
6
+ join,
7
+ posix,
8
+ relative,
9
+ resolve,
10
+ sep,
11
+ } from "node:path";
3
12
  import { parse } from "yaml";
4
13
  import { coverOptions } from "./cover-options.js";
5
14
  import { readMarkdown } from "./markdown.js";
@@ -32,7 +41,7 @@ function encodePath(path) {
32
41
  return path.split("/").map(encodeURIComponent).join("/");
33
42
  }
34
43
 
35
- async function readPages(root, directory, nested) {
44
+ async function readPages(root, directory, nested, standalone) {
36
45
  const entries = (
37
46
  await readdir(join(root, directory), { withFileTypes: true })
38
47
  )
@@ -51,6 +60,7 @@ async function readPages(root, directory, nested) {
51
60
  path: indexPath,
52
61
  ...readMarkdown(await readFile(join(root, indexPath), "utf8")),
53
62
  };
63
+ const ownBook = directory.includes("/") && introduction?.metadata.book;
54
64
  const order = introduction?.metadata.chapters;
55
65
  const selected = [];
56
66
  if (order !== undefined) {
@@ -80,6 +90,7 @@ async function readPages(root, directory, nested) {
80
90
  }
81
91
  }
82
92
  const pages = introduction ? [introduction] : [];
93
+ if (ownBook) standalone.set(directory, pages);
83
94
  for (const entry of [
84
95
  ...selected,
85
96
  ...entries.filter((entry) => !selected.includes(entry)),
@@ -87,7 +98,7 @@ async function readPages(root, directory, nested) {
87
98
  if (entry === index) continue;
88
99
  const path = posix.join(directory, entry.name);
89
100
  if (entry.isDirectory()) {
90
- pages.push(...(await readPages(root, path, true)));
101
+ pages.push(...(await readPages(root, path, true, standalone)));
91
102
  } else {
92
103
  pages.push({
93
104
  path,
@@ -95,7 +106,7 @@ async function readPages(root, directory, nested) {
95
106
  });
96
107
  }
97
108
  }
98
- return pages;
109
+ return ownBook ? [] : pages;
99
110
  }
100
111
 
101
112
  function readPublicationDate(index) {
@@ -116,13 +127,25 @@ function readPublicationDate(index) {
116
127
  );
117
128
  }
118
129
 
119
- function describeBook(pages, folder, fallback) {
130
+ function describeBook(pages, folder, fallback, configuredTitle) {
120
131
  const index = pages.find(
121
132
  (page) =>
122
133
  page.path.toLowerCase() === posix.join(folder, "index.md").toLowerCase()
123
134
  );
124
- const id = folder || rootId;
125
- const title = index?.metadata.title || index?.heading || fallback;
135
+ const readme = pages.find(
136
+ (page) =>
137
+ page.path.toLowerCase() === posix.join(folder, "README.md").toLowerCase()
138
+ );
139
+ // Reserve a prefix that ordinary top-level folder names cannot use.
140
+ const id = folder.includes("/")
141
+ ? `_book-${folder.replaceAll("-", "-h").replaceAll("/", "--")}`
142
+ : folder || rootId;
143
+ const title =
144
+ index?.metadata.title ||
145
+ index?.heading ||
146
+ configuredTitle ||
147
+ readme?.firstHeading ||
148
+ fallback;
126
149
  const cover = index?.metadata.cover;
127
150
  if (cover && !Object.hasOwn(coverOptions, cover)) {
128
151
  throw new Error(
@@ -164,6 +187,7 @@ function describeBook(pages, folder, fallback) {
164
187
  metadata: page.metadata,
165
188
  hasTitle: Boolean(page.heading),
166
189
  excerpt: page.excerpt,
190
+ searchSections: page.searchSections,
167
191
  markdown: page.markdown,
168
192
  headingIds: page.headingIds,
169
193
  urls: page.urls,
@@ -200,6 +224,7 @@ export async function readSettings(cwd) {
200
224
  const {
201
225
  locale = "en",
202
226
  title,
227
+ docsDir,
203
228
  outDir,
204
229
  description,
205
230
  siteUrl,
@@ -220,10 +245,13 @@ export async function readSettings(cwd) {
220
245
  }
221
246
  if (
222
247
  (title !== undefined && typeof title !== "string") ||
223
- (outDir !== undefined && (typeof outDir !== "string" || !outDir.trim()))
248
+ [docsDir, outDir].some(
249
+ (value) =>
250
+ value !== undefined && (typeof value !== "string" || !value.trim())
251
+ )
224
252
  ) {
225
253
  throw new Error(
226
- "grimoire.yml: title and outDir must be text / title と outDir は文字列で指定してください。"
254
+ "grimoire.yml: title, docsDir and outDir must be text / title、docsDir、outDir は文字列で指定してください。"
227
255
  );
228
256
  }
229
257
  if (
@@ -240,6 +268,7 @@ export async function readSettings(cwd) {
240
268
  return {
241
269
  locale,
242
270
  title,
271
+ docsDir,
243
272
  outDir,
244
273
  description,
245
274
  socialImage,
@@ -336,26 +365,55 @@ async function loadLink(url, page, links, docs, assets, issues) {
336
365
  }
337
366
  }
338
367
 
339
- export async function readLibrary(cwd, settings) {
368
+ async function projectTitle(cwd) {
369
+ const filename = join(cwd, "package.json");
370
+ try {
371
+ const name = JSON.parse(await readFile(filename, "utf8"))?.name;
372
+ if (typeof name === "string" && name.trim()) return name.trim();
373
+ } catch (error) {
374
+ if (error.code !== "ENOENT" && !(error instanceof SyntaxError)) throw error;
375
+ }
376
+ return basename(cwd);
377
+ }
378
+
379
+ export async function readLibrary(
380
+ cwd,
381
+ settings,
382
+ docsDir = settings.docsDir ?? "docs"
383
+ ) {
340
384
  const { locale, title } = settings;
341
- const docs = await realpath(join(cwd, "docs")).catch((error) => {
342
- if (error.code === "ENOENT") throw missingMarkdown(locale);
385
+ if (!docsDir.trim()) throw new Error("--docs-dir must name a directory.");
386
+ const docs = await realpath(resolve(cwd, docsDir)).catch((error) => {
387
+ if (["ENOENT", "ENOTDIR"].includes(error.code))
388
+ throw missingMarkdown(locale, docsDir);
343
389
  throw error;
344
390
  });
345
- const entries = (await readdir(docs, { withFileTypes: true }))
391
+ const entries = (
392
+ await readdir(docs, { withFileTypes: true }).catch((error) => {
393
+ if (error.code === "ENOTDIR") throw missingMarkdown(locale, docsDir);
394
+ throw error;
395
+ })
396
+ )
346
397
  .filter((entry) => entry.isDirectory() && visibleEntry(entry.name))
347
398
  .sort((a, b) => sortNames(a.name, b.name));
348
399
  const books = [];
349
400
  const rootPages = await readPages(docs, "", false);
350
401
  if (rootPages.length)
351
- books.push(describeBook(rootPages, "", title ?? "Grimoire3D"));
402
+ books.push(
403
+ describeBook(rootPages, "", locale === "ja" ? "概要" : "Overview", title)
404
+ );
352
405
 
353
406
  for (const { name } of entries) {
354
- const pages = await readPages(docs, name, true);
407
+ const standalone = new Map();
408
+ const pages = await readPages(docs, name, true, standalone);
355
409
  if (pages.length)
356
410
  books.push(describeBook(pages, name, titleFromPath(name)));
411
+ for (const [folder, chapters] of standalone)
412
+ books.push(
413
+ describeBook(chapters, folder, titleFromPath(posix.basename(folder)))
414
+ );
357
415
  }
358
- if (!books.length) throw missingMarkdown(locale);
416
+ if (!books.length) throw missingMarkdown(locale, docsDir);
359
417
 
360
418
  const shelf = books.some((book) => book.id !== rootId);
361
419
  const assets = new Map();
@@ -391,6 +449,7 @@ export async function readLibrary(cwd, settings) {
391
449
  const summaries = [];
392
450
  const publishedBooks = [];
393
451
  const documents = [];
452
+ const searchBooks = [];
394
453
  for (const {
395
454
  id,
396
455
  title,
@@ -419,6 +478,17 @@ export async function readLibrary(cwd, settings) {
419
478
  }
420
479
  }
421
480
  summaries.push({ id, title, cover, category, date, coverImage: artwork });
481
+ searchBooks.push({
482
+ id,
483
+ title,
484
+ sections: chapters.flatMap((chapter) =>
485
+ chapter.searchSections.map((section) => ({
486
+ chapter: chapter.id,
487
+ title: chapter.title,
488
+ ...section,
489
+ }))
490
+ ),
491
+ });
422
492
  const pages = [];
423
493
  for (const chapter of chapters) {
424
494
  const {
@@ -467,10 +537,11 @@ export async function readLibrary(cwd, settings) {
467
537
  publishedBooks.push({ id, title, cover, pages });
468
538
  }
469
539
  return {
540
+ docsDirectory: docs,
470
541
  manifest: {
471
542
  locale,
472
543
  shelf,
473
- title: title ?? "Grimoire3D",
544
+ title: title ?? (await projectTitle(cwd)),
474
545
  description: settings.description,
475
546
  siteUrl: settings.siteUrl,
476
547
  socialImage,
@@ -481,15 +552,17 @@ export async function readLibrary(cwd, settings) {
481
552
  },
482
553
  books: publishedBooks,
483
554
  documents,
555
+ searchBooks,
484
556
  assets,
485
557
  issues: [...new Set(issues)].sort(sortNames),
486
558
  };
487
559
  }
488
560
 
489
- function missingMarkdown(locale) {
561
+ function missingMarkdown(locale, docsDir) {
562
+ const index = join(docsDir, "index.md");
490
563
  return new Error(
491
564
  locale === "ja"
492
- ? "docs/ に Markdown がありません。docs/index.md に「# 最初の本」と書いてください。"
493
- : 'No Markdown in docs/. Start with "# My first book" in docs/index.md.'
565
+ ? `${docsDir} に Markdown がありません。${index} に「# 最初の本」と書いてください。`
566
+ : `No Markdown in ${docsDir}. Start with "# My first book" in ${index}.`
494
567
  );
495
568
  }
package/cli/markdown.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { fromHtmlIsomorphic } from "hast-util-from-html-isomorphic";
2
+ import { toText } from "hast-util-to-text";
1
3
  import remarkParse from "remark-parse";
2
4
  import { unified } from "unified";
3
5
  import { parse } from "yaml";
@@ -22,6 +24,52 @@ function isDefinition(node) {
22
24
  return node.type === "definition" || node.type === "footnoteDefinition";
23
25
  }
24
26
 
27
+ function searchableText(node) {
28
+ if (node.type === "html")
29
+ return toText(fromHtmlIsomorphic(node.value, { fragment: true }));
30
+ if (node.type === "image") return node.alt ?? "";
31
+ if (node.value !== undefined) return node.value;
32
+ if (node.type === "break") return " ";
33
+ const separator = [
34
+ "paragraph",
35
+ "heading",
36
+ "emphasis",
37
+ "strong",
38
+ "delete",
39
+ "link",
40
+ "textDirective",
41
+ ].includes(node.type)
42
+ ? ""
43
+ : " ";
44
+ return node.children?.map(searchableText).join(separator) ?? "";
45
+ }
46
+
47
+ function searchableSections(nodes, headings, chapterHeading) {
48
+ let heading;
49
+ let blocks = [];
50
+ const sections = [];
51
+ function addSection() {
52
+ const text = blocks.join(" ").replace(/\s+/g, " ").trim().normalize("NFC");
53
+ if (heading || text || !sections.length) {
54
+ sections.push({ anchor: heading?.id, heading: heading?.title, text });
55
+ }
56
+ blocks = [];
57
+ }
58
+ for (const node of nodes) {
59
+ if (node === chapterHeading || node.type === "definition") continue;
60
+ const current = headings.get(node);
61
+ if (current) {
62
+ addSection();
63
+ heading = current;
64
+ } else {
65
+ const text = searchableText(node);
66
+ if (text.trim()) blocks.push(text);
67
+ }
68
+ }
69
+ addSection();
70
+ return sections;
71
+ }
72
+
25
73
  export function readMarkdown(source) {
26
74
  const front = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(source);
27
75
  let raw;
@@ -121,6 +169,7 @@ export function readMarkdown(source) {
121
169
  : "";
122
170
  return {
123
171
  heading: headings.get(heading)?.title,
172
+ firstHeading: headings.values().next().value?.title,
124
173
  metadata: {
125
174
  cover:
126
175
  typeof metadata.cover === "string" ? metadata.cover.trim() : undefined,
@@ -140,6 +189,7 @@ export function readMarkdown(source) {
140
189
  : undefined,
141
190
  date: metadata.date,
142
191
  chapters: metadata.chapters,
192
+ book: metadata.book === true,
143
193
  noindex: metadata.noindex === true,
144
194
  coverImage:
145
195
  typeof metadata.coverImage === "string"
@@ -147,6 +197,7 @@ export function readMarkdown(source) {
147
197
  : undefined,
148
198
  },
149
199
  excerpt: [...excerpt].slice(0, 170).join(""),
200
+ searchSections: searchableSections(tree.children, headings, heading),
150
201
  markdown,
151
202
  headingIds: Object.fromEntries(
152
203
  headingOffsets.map(({ offset, id }) => [offset, id])
@@ -0,0 +1,7 @@
1
+ import type { ReactElement } from "react";
2
+
3
+ export function shelfGroups<T extends { category?: string }>(
4
+ books: T[]
5
+ ): { category?: string; books: T[] }[];
6
+
7
+ export function ShelfPlate(props: { category: string }): ReactElement;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Put books from the same category together in the order each category first appeared.
3
+ * @template {{category?: string}} T
4
+ * @param {T[]} books
5
+ */
6
+ export function shelfGroups(books) {
7
+ /** @type {Map<string, T[]>} */
8
+ const groups = new Map();
9
+ /** @type {T[]} */
10
+ const others = [];
11
+ for (const book of books) {
12
+ if (!book.category) {
13
+ others.push(book);
14
+ continue;
15
+ }
16
+ const category = groups.get(book.category) ?? [];
17
+ category.push(book);
18
+ groups.set(book.category, category);
19
+ }
20
+ /** @type {{category?: string, books: T[]}[]} */
21
+ const sections = [...groups].map(([category, books]) => ({
22
+ category,
23
+ books,
24
+ }));
25
+ if (others.length) sections.push({ books: others });
26
+ return sections;
27
+ }
28
+
29
+ import { createElement as element } from "react";
30
+
31
+ /** @param {{ category: string }} props */
32
+ export function ShelfPlate({ category }) {
33
+ return element(
34
+ "div",
35
+ { className: "shelf-label-rail" },
36
+ element("h2", { className: "shelf-plate" }, category)
37
+ );
38
+ }
@@ -8,6 +8,7 @@ import { coverOptions, selectCover } from "./cover-options.js";
8
8
  import { LibraryFooter } from "./library-footer.js";
9
9
  import { markdownOptions, rehypePlugins, remarkPlugins } from "./markup.js";
10
10
  import { readerPath, readLegacyRoute } from "./routes.js";
11
+ import { ShelfPlate, shelfGroups } from "./shelf-groups.js";
11
12
  import { videoEmbed } from "./video-url.js";
12
13
 
13
14
  function escapeHtml(value) {
@@ -266,46 +267,65 @@ function assetNamed(assets, prefix, name, ext = ".avif") {
266
267
  }
267
268
 
268
269
  function staticShelf(site, prefix, assets, label) {
269
- const books = site.books.slice(0, 12);
270
+ const categorized = site.books.some((book) => book.category);
271
+ const ordered = categorized
272
+ ? shelfGroups(site.books).flatMap((group) => group.books)
273
+ : site.books;
274
+ const books = ordered.slice(0, 12);
270
275
  // Enhance the entire bookshelf together when adding catalog controls or custom art.
271
276
  const reuseShelfArt = !site.books.some(
272
277
  (book) => book.category || book.date || book.coverImage
273
278
  );
279
+ const reserveSearch =
280
+ site.books.length <= 6 &&
281
+ !site.books.some((book) => book.category || book.date)
282
+ ? '<div class="library-tools library-tools-reserve" aria-hidden="true"></div>'
283
+ : "";
274
284
  const button = site.locale === "ja" ? "目録" : "Index";
275
285
  const titleStyle = (finish) =>
276
286
  finish.lettering
277
287
  ? `--cover-lettering:${finish.lettering};--cover-title-shadow:0 1px 1px #fbe9c6b0;`
278
288
  : "";
279
- const covers = books
280
- .map((book, index) => {
281
- const finish = coverOptions[selectCover(book.id, book.cover)];
282
- const cover = assets.find(
283
- (file) =>
284
- file.startsWith(`cover-${finish.base}-`) &&
285
- !file.startsWith(`cover-${finish.base}-mobile-`) &&
286
- file.endsWith(".avif")
287
- );
288
- const mobileCover = assetNamed(
289
- assets,
290
- prefix,
291
- `cover-${finish.base}-mobile`
292
- );
293
- const style = `--cover-filter:${finish.filter};${titleStyle(finish)}`;
294
- const face = renderToStaticMarkup(
295
- element(BookCover, {
296
- title: book.title,
297
- src: cover && `${prefix}assets/${cover}`,
298
- compact: mobileCover,
299
- artwork: book.coverImage && prefix + book.coverImage.slice(2),
300
- loading: index < 3 ? "eager" : "lazy",
289
+ function coverMarkup(book) {
290
+ const finish = coverOptions[selectCover(book.id, book.cover)];
291
+ const cover = assets.find(
292
+ (file) =>
293
+ file.startsWith(`cover-${finish.base}-`) &&
294
+ !file.startsWith(`cover-${finish.base}-mobile-`) &&
295
+ file.endsWith(".avif")
296
+ );
297
+ const mobileCover = assetNamed(
298
+ assets,
299
+ prefix,
300
+ `cover-${finish.base}-mobile`
301
+ );
302
+ const style = `--cover-filter:${finish.filter};${titleStyle(finish)}`;
303
+ const face = renderToStaticMarkup(
304
+ element(BookCover, {
305
+ title: book.title,
306
+ src: cover && `${prefix}assets/${cover}`,
307
+ compact: mobileCover,
308
+ artwork: book.coverImage && prefix + book.coverImage.slice(2),
309
+ loading: books.indexOf(book) < 3 ? "eager" : "lazy",
310
+ })
311
+ );
312
+ return `<div class="shelf-cell"><a class="volume" href="${prefix + escapeHtml(readerPath(book.id))}" aria-label="${escapeHtml(book.title)}" style="${style}">${face}</a></div>`;
313
+ }
314
+ const grid = (items) =>
315
+ `<div class="shelf-grid">${items.map(coverMarkup).join("")}</div>`;
316
+ const contents = categorized
317
+ ? shelfGroups(books)
318
+ .map((group) => {
319
+ const category =
320
+ group.category ??
321
+ (site.locale === "ja" ? "その他の本" : "Other books");
322
+ return `<section class="category-shelf shelf-grid" aria-label="${escapeHtml(category)}">${renderToStaticMarkup(element(ShelfPlate, { category }))}${group.books.map(coverMarkup).join("")}</section>`;
301
323
  })
302
- );
303
- return `<div class="shelf-cell"><a class="volume" href="${prefix + escapeHtml(readerPath(book.id))}" aria-label="${escapeHtml(book.title)}" style="${style}">${face}</a></div>`;
304
- })
305
- .join("");
324
+ .join("")
325
+ : `<div class="shelf-art"${reuseShelfArt ? " data-initial-shelf" : ""} aria-hidden="true"></div>${grid(books)}`;
306
326
  return `<main class="library"><header class="library-brand brand">${escapeHtml(site.title)}</header>
307
- <div class="library-heading${site.books.length > 6 ? " library-heading-sticky" : ""}"><h1>${label}</h1></div>
308
- <div class="shelf resting-shelf${site.books.length > 6 ? " shelf-many" : ""}"${books.length >= 3 && books.length <= 4 ? ' data-mobile-rows="2"' : ""}><div class="shelf-art"${reuseShelfArt ? " data-initial-shelf" : ""} aria-hidden="true"></div><div class="shelf-grid">${covers}</div></div>
327
+ <div class="library-heading${site.books.length > 6 ? " library-heading-sticky" : ""}"><h1>${label}</h1>${reserveSearch}</div>
328
+ <div class="shelf ${categorized ? "shelf-categorized shelf-many" : `resting-shelf${site.books.length > 6 ? " shelf-many" : ""}`}"${!categorized && books.length >= 3 && books.length <= 4 ? ' data-mobile-rows="2"' : ""}>${contents}</div>
309
329
  ${site.books.length > 12 ? `<details><summary>${button}</summary>${linkList(site.books.map((book) => ({ title: book.title, href: prefix + readerPath(book.id) })))}</details>` : ""}
310
330
  ${renderToStaticMarkup(element(LibraryFooter, { publisher: site.footer }))}
311
331
  </main>`;
@@ -420,7 +440,8 @@ export async function writeStaticPages(
420
440
  if (!segments.length && site.shelf) {
421
441
  const alcove = assetNamed(assets, prefix, "alcove");
422
442
  const cabinet =
423
- site.books.length === 3 || site.books.length === 4
443
+ !site.books.some((book) => book.category) &&
444
+ (site.books.length === 3 || site.books.length === 4)
424
445
  ? assetNamed(assets, prefix, "mobile-cabinet")
425
446
  : alcove;
426
447
  if (alcove)