@warlock.js/grimoire 5.56.0 → 5.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/esm/book/build.d.mts.map +1 -1
  3. package/esm/book/build.mjs +2 -1
  4. package/esm/book/build.mjs.map +1 -1
  5. package/esm/book/render.mjs +10 -0
  6. package/esm/book/render.mjs.map +1 -1
  7. package/esm/bookmap/build.d.mts.map +1 -1
  8. package/esm/bookmap/build.mjs +2 -2
  9. package/esm/bookmap/build.mjs.map +1 -1
  10. package/esm/bookmap/steps.mjs +53 -38
  11. package/esm/bookmap/steps.mjs.map +1 -1
  12. package/esm/check/check-grimoire.d.mts.map +1 -1
  13. package/esm/check/check-grimoire.mjs +4 -1
  14. package/esm/check/check-grimoire.mjs.map +1 -1
  15. package/esm/check/rules/criteria.mjs +21 -2
  16. package/esm/check/rules/criteria.mjs.map +1 -1
  17. package/esm/check/rules/screenshots.mjs +57 -0
  18. package/esm/check/rules/screenshots.mjs.map +1 -0
  19. package/esm/codes/codes.d.mts +12 -0
  20. package/esm/codes/codes.d.mts.map +1 -1
  21. package/esm/codes/codes.mjs +6 -0
  22. package/esm/codes/codes.mjs.map +1 -1
  23. package/esm/contracts/adapter.d.mts +6 -0
  24. package/esm/contracts/adapter.d.mts.map +1 -1
  25. package/esm/contracts/book.d.mts +2 -0
  26. package/esm/contracts/book.d.mts.map +1 -1
  27. package/esm/contracts/book.mjs.map +1 -1
  28. package/esm/contracts/bookmap.d.mts +19 -1
  29. package/esm/contracts/bookmap.d.mts.map +1 -1
  30. package/esm/contracts/snapshot.d.mts +11 -0
  31. package/esm/contracts/snapshot.d.mts.map +1 -1
  32. package/esm/contracts/test-results.d.mts +34 -0
  33. package/esm/contracts/test-results.d.mts.map +1 -1
  34. package/esm/contracts/written.d.mts +44 -0
  35. package/esm/contracts/written.d.mts.map +1 -1
  36. package/esm/contracts/written.mjs.map +1 -1
  37. package/esm/devtools/data.mjs +126 -4
  38. package/esm/devtools/data.mjs.map +1 -1
  39. package/esm/devtools/index.d.mts +31 -1
  40. package/esm/devtools/index.d.mts.map +1 -1
  41. package/esm/devtools/index.mjs +94 -5
  42. package/esm/devtools/index.mjs.map +1 -1
  43. package/esm/devtools/product-map.d.mts +14 -0
  44. package/esm/devtools/product-map.d.mts.map +1 -0
  45. package/esm/devtools/product-map.mjs +385 -0
  46. package/esm/devtools/product-map.mjs.map +1 -0
  47. package/esm/devtools/site.d.mts.map +1 -1
  48. package/esm/devtools/site.mjs +97 -21
  49. package/esm/devtools/site.mjs.map +1 -1
  50. package/esm/devtools/snapshot-source.mjs +71 -22
  51. package/esm/devtools/snapshot-source.mjs.map +1 -1
  52. package/esm/graph/index.d.mts +10 -1
  53. package/esm/graph/index.d.mts.map +1 -1
  54. package/esm/graph/index.mjs +3 -2
  55. package/esm/graph/index.mjs.map +1 -1
  56. package/esm/index.d.mts +4 -4
  57. package/esm/paths/index.d.mts +2 -0
  58. package/esm/paths/index.d.mts.map +1 -1
  59. package/esm/paths/index.mjs +3 -1
  60. package/esm/paths/index.mjs.map +1 -1
  61. package/esm/scry/compact.mjs +169 -0
  62. package/esm/scry/compact.mjs.map +1 -0
  63. package/esm/scry/format.d.mts.map +1 -1
  64. package/esm/scry/format.mjs +7 -1
  65. package/esm/scry/format.mjs.map +1 -1
  66. package/esm/scry/query.d.mts.map +1 -1
  67. package/esm/scry/query.mjs +12 -1
  68. package/esm/scry/query.mjs.map +1 -1
  69. package/esm/test-results/index.d.mts +7 -2
  70. package/esm/test-results/index.d.mts.map +1 -1
  71. package/esm/test-results/index.mjs +79 -12
  72. package/esm/test-results/index.mjs.map +1 -1
  73. package/esm/vitest/index.d.mts +6 -0
  74. package/esm/vitest/index.d.mts.map +1 -1
  75. package/esm/vitest/index.mjs +22 -6
  76. package/esm/vitest/index.mjs.map +1 -1
  77. package/esm/warlock/adapter.d.mts.map +1 -1
  78. package/esm/warlock/adapter.mjs +6 -2
  79. package/esm/warlock/adapter.mjs.map +1 -1
  80. package/esm/warlock/mcp-tools.mjs +48 -12
  81. package/esm/warlock/mcp-tools.mjs.map +1 -1
  82. package/esm/workspace/index.d.mts.map +1 -1
  83. package/esm/workspace/index.mjs +4 -2
  84. package/esm/workspace/index.mjs.map +1 -1
  85. package/esm/written/apps.mjs +4 -2
  86. package/esm/written/apps.mjs.map +1 -1
  87. package/esm/written/features.mjs +119 -6
  88. package/esm/written/features.mjs.map +1 -1
  89. package/esm/written/markdown.mjs +66 -1
  90. package/esm/written/markdown.mjs.map +1 -1
  91. package/esm/written/parse-grimoire.d.mts.map +1 -1
  92. package/esm/written/parse-grimoire.mjs +1 -1
  93. package/esm/written/parse-grimoire.mjs.map +1 -1
  94. package/llms-full.txt +77 -2
  95. package/package.json +3 -3
  96. package/skills/backfill-a-grimoire/SKILL.md +5 -0
  97. package/skills/describe-an-app/SKILL.md +12 -0
  98. package/skills/record-a-change/SKILL.md +8 -0
  99. package/skills/use-the-grimoire/SKILL.md +15 -0
  100. package/skills/write-a-feature/SKILL.md +37 -2
  101. package/ui/grimoire-static.js +4 -0
  102. package/ui/grimoire-view.js +2283 -428
  103. package/ui/grimoire.css +1036 -45
  104. package/ui/product-map.css +636 -0
  105. package/ui/product-map.js +817 -0
@@ -7,8 +7,11 @@
7
7
  * Keep the last line as it is: the static export swaps it out to inline this file.
8
8
  */
9
9
 
10
- const NAV = [
11
- ["", "Home"],
10
+ /** The tabs: `[route, label]`. */
11
+ const TABS = [
12
+ ["product", "Product map"],
13
+ ["", "Overview"],
14
+ ["features", "Features"],
12
15
  ["apps", "Apps"],
13
16
  ["tasks", "Tasks"],
14
17
  ["releases", "Releases"],
@@ -19,6 +22,11 @@ const NAV = [
19
22
  const SVG_WIDTH = 720;
20
23
  const SVG_HEIGHT = 440;
21
24
 
25
+ /** How long a view may take before the skeleton is shown instead of waiting for it (ms). */
26
+ const SKELETON_AFTER = 150;
27
+
28
+ const BUILD_HINT = "Run warlock grimoire build, then reload.";
29
+
22
30
  /** Decode one hash segment; a malformed escape stays as written. */
23
31
  function decodeSegment(segment) {
24
32
  try {
@@ -33,6 +41,41 @@ function plain(field) {
33
41
  return field !== null && typeof field === "object" && "value" in field ? field.value : field;
34
42
  }
35
43
 
44
+ function plural(count, word) {
45
+ return `${count} ${word}${count === 1 ? "" : "s"}`;
46
+ }
47
+
48
+ /** Which tab a hash route belongs to; `null` when it belongs to none. */
49
+ function tabOf(route) {
50
+ const type = (route.split("?")[0] ?? "").split("/")[0] ?? "";
51
+
52
+ switch (type) {
53
+ case "product":
54
+ return "product";
55
+ case "features":
56
+ case "feature":
57
+ case "flow":
58
+ return "features";
59
+ case "apps":
60
+ case "page":
61
+ return "apps";
62
+ case "tasks":
63
+ case "task":
64
+ return "tasks";
65
+ case "releases":
66
+ case "release":
67
+ return "releases";
68
+ case "check":
69
+ return "check";
70
+ case "modules":
71
+ case "file":
72
+ case "route":
73
+ return "modules";
74
+ default:
75
+ return "";
76
+ }
77
+ }
78
+
36
79
  /** The hash route (without `#grimoire/`) of a search hit or graph node id, or `null`. */
37
80
  function targetOf(type, id) {
38
81
  const encode = encodeURIComponent;
@@ -92,20 +135,561 @@ function shorten(text, max = 26) {
92
135
  }
93
136
 
94
137
  const NODE_COLOURS = {
95
- center: "var(--accent)",
96
- feature: "var(--good)",
97
- flow: "var(--bar)",
98
- app: "var(--warn)",
99
- block: "var(--bar)",
100
- layout: "var(--muted)",
101
- module: "var(--accent)",
102
- file: "var(--muted)",
138
+ center: "var(--brand)",
139
+ feature: "var(--chart-2)",
140
+ flow: "var(--chart-1)",
141
+ app: "var(--chart-3)",
142
+ block: "var(--chart-4)",
143
+ layout: "var(--muted-foreground)",
144
+ module: "var(--brand)",
145
+ file: "var(--muted-foreground)",
103
146
  };
104
147
 
148
+ // ── Building blocks ─────────────────────────────────────────────────────────
149
+
150
+ function link(ctx, text, target, attrs = {}) {
151
+ return ctx.el("a", { href: ctx.href(target), text, ...attrs });
152
+ }
153
+
154
+ /** The tone (`good`, `info`, `warn`, `bad`, or none) a status word is shown in. */
155
+ function toneOf(status) {
156
+ switch (status) {
157
+ case "shipped":
158
+ case "passing":
159
+ case "pass":
160
+ case "confirmed":
161
+ case "done":
162
+ case "fresh":
163
+ case "cached":
164
+ case "clean":
165
+ return "good";
166
+ case "building":
167
+ case "open":
168
+ return "info";
169
+ case "proposed":
170
+ case "inferred":
171
+ case "warning":
172
+ case "waiting":
173
+ case "stale":
174
+ case "missing":
175
+ case "untested":
176
+ case "not-run":
177
+ case "no-test":
178
+ return "warn";
179
+ case "failing":
180
+ case "fail":
181
+ case "error":
182
+ return "bad";
183
+ default:
184
+ return "";
185
+ }
186
+ }
187
+
188
+ function pill(ctx, text, tone = "") {
189
+ return ctx.el("span", { class: tone ? `grimoire-pill is-${tone}` : "grimoire-pill", text });
190
+ }
191
+
192
+ function mono(ctx, text) {
193
+ return ctx.el("span", { class: "grimoire-mono", text });
194
+ }
195
+
196
+ function muted(ctx, text) {
197
+ return ctx.el("span", { class: "grimoire-muted", text });
198
+ }
199
+
200
+ function list(ctx, items) {
201
+ return ctx.el(
202
+ "ul",
203
+ { class: "grimoire-list" },
204
+ items.map((item) => ctx.el("li", {}, item)),
205
+ );
206
+ }
207
+
208
+ /** A table that scrolls inside its card instead of widening the page. */
209
+ function table(ctx, headings, rows) {
210
+ return ctx.el("div", { class: "grimoire-scroll" }, [
211
+ ctx.el("table", { class: "grimoire-table" }, [
212
+ ctx.el("thead", {}, [
213
+ ctx.el(
214
+ "tr",
215
+ {},
216
+ headings.map((heading) => ctx.el("th", { scope: "col", text: heading })),
217
+ ),
218
+ ]),
219
+ ctx.el(
220
+ "tbody",
221
+ {},
222
+ rows.map((row) =>
223
+ ctx.el(
224
+ "tr",
225
+ {},
226
+ row.map((cell, column) =>
227
+ ctx.el("td", { "data-label": headings[column] ?? "" }, cell),
228
+ ),
229
+ ),
230
+ ),
231
+ ),
232
+ ]),
233
+ ]);
234
+ }
235
+
236
+ /** A card with a heading. */
237
+ function section(ctx, title, children = []) {
238
+ return ctx.el("section", { class: "grimoire-card" }, [
239
+ ctx.el("h3", { text: title }),
240
+ ...children,
241
+ ]);
242
+ }
243
+
244
+ /** Label and value pairs. */
245
+ function facts(ctx, rows) {
246
+ return ctx.el(
247
+ "dl",
248
+ { class: "grimoire-facts" },
249
+ rows.flatMap(([label, value]) => [
250
+ ctx.el("dt", { text: label }),
251
+ ctx.el("dd", {}, value ?? muted(ctx, "none")),
252
+ ]),
253
+ );
254
+ }
255
+
256
+ /** A trail of links back up the hierarchy; the last crumb is the current view. */
257
+ function crumbs(ctx, trail) {
258
+ return ctx.el("nav", { class: "grimoire-crumbs", "aria-label": "Breadcrumb" }, [
259
+ ctx.el(
260
+ "ol",
261
+ {},
262
+ trail.map(([label, target], index) =>
263
+ ctx.el("li", {}, [
264
+ index < trail.length - 1 && target !== undefined
265
+ ? link(ctx, label, target)
266
+ : ctx.el("span", { "aria-current": "page", text: label }),
267
+ ]),
268
+ ),
269
+ ),
270
+ ]);
271
+ }
272
+
273
+ /** The title block of a detail view. */
274
+ function heading(ctx, title, extras = []) {
275
+ return ctx.el("header", { class: "grimoire-heading" }, [
276
+ ctx.el("h2", { text: title }),
277
+ extras.length ? ctx.el("div", { class: "grimoire-heading-meta" }, extras) : "",
278
+ ]);
279
+ }
280
+
281
+ /** Items as compact chips; past `limit` the rest sits behind a "+N more" button. */
282
+ function chipList(ctx, items, make, limit = 8) {
283
+ if (!items.length) return muted(ctx, "none");
284
+
285
+ const nodes = items.map(make);
286
+ const holder = ctx.el("div", { class: "grimoire-chips" });
287
+ const more = ctx.el("button", { type: "button", class: "grimoire-more" });
288
+ let open = false;
289
+
290
+ const paint = () => {
291
+ const visible = open ? nodes : nodes.slice(0, limit);
292
+
293
+ more.textContent = open ? "Show fewer" : `+${nodes.length - limit} more`;
294
+ more.setAttribute("aria-expanded", String(open));
295
+ holder.replaceChildren(...visible, ...(nodes.length > limit ? [more] : []));
296
+ };
297
+
298
+ more.addEventListener("click", () => {
299
+ open = !open;
300
+ paint();
301
+ });
302
+ paint();
303
+ return holder;
304
+ }
305
+
306
+ function fileLink(ctx, file) {
307
+ return link(ctx, file, `file/${encodeURIComponent(file)}`, { class: "grimoire-chip" });
308
+ }
309
+
310
+ function fileChips(ctx, files, limit = 8) {
311
+ return chipList(ctx, files, (file) => fileLink(ctx, file), limit);
312
+ }
313
+
314
+ /** `<feature>/<flow>` as a link. */
315
+ function flowLink(ctx, ref) {
316
+ const target = targetOf("flow", ref);
317
+ return target === null ? ref : link(ctx, ref, target);
318
+ }
319
+
320
+ function routeLink(ctx, method, path) {
321
+ return link(
322
+ ctx,
323
+ `${method} ${path}`,
324
+ `route/${encodeURIComponent(method)}/${encodeURIComponent(path)}`,
325
+ );
326
+ }
327
+
328
+ /** Split a hash route into its path and its query (`check?code=GR3006&feature=cart`). */
329
+ function parseRoute(route) {
330
+ const at = route.indexOf("?");
331
+ const query = {};
332
+
333
+ if (at >= 0) {
334
+ for (const [key, value] of new URLSearchParams(route.slice(at + 1))) query[key] = value;
335
+ }
336
+
337
+ return { path: at < 0 ? route : route.slice(0, at), query };
338
+ }
339
+
340
+ /** The hash route of the Check tab for a filter; empty values are left out. */
341
+ function checkTarget(filter) {
342
+ const params = new URLSearchParams();
343
+
344
+ for (const key of ["code", "feature", "flow", "severity", "state", "offset", "limit"]) {
345
+ const value = filter[key];
346
+
347
+ if (value !== undefined && value !== null && value !== "") params.set(key, String(value));
348
+ }
349
+
350
+ const text = params.toString();
351
+
352
+ return text ? `check?${text}` : "check";
353
+ }
354
+
355
+ /**
356
+ * Text with `` `code` `` spans as nodes: plain strings and `<code>` elements.
357
+ * Every part is set as text. Unbalanced backticks stay as written.
358
+ */
359
+ function codeText(ctx, text) {
360
+ const value = String(text ?? "");
361
+
362
+ if (!value.includes("`")) return value;
363
+
364
+ const parts = value.split("`");
365
+
366
+ if (parts.length % 2 === 0) return value;
367
+
368
+ return parts
369
+ .map((part, index) =>
370
+ index % 2 === 1 ? ctx.el("code", { class: "grimoire-code", text: part }) : part,
371
+ )
372
+ .filter((part) => part !== "");
373
+ }
374
+
375
+ /** The reason of a "does not apply" case, without the words the view groups it under. */
376
+ function stripDoesNotApply(answer) {
377
+ const rest = String(answer ?? "")
378
+ .replace(/^does not apply\b[:\s—-]*/i, "")
379
+ .trim();
380
+
381
+ return rest || "no reason written";
382
+ }
383
+
384
+ /** Select a node's text so the reader can copy it by hand. */
385
+ function selectNode(node, done) {
386
+ try {
387
+ const selection = globalThis.getSelection?.();
388
+ const range = globalThis.document?.createRange?.();
389
+
390
+ if (selection && range) {
391
+ range.selectNodeContents(node);
392
+ selection.removeAllRanges();
393
+ selection.addRange(range);
394
+ done("Selected. Press Ctrl+C to copy.");
395
+ return;
396
+ }
397
+ } catch {
398
+ // Fall through to the plain message.
399
+ }
400
+
401
+ done("Select the line and copy it by hand.");
402
+ }
403
+
404
+ /** Copy text with the clipboard API; fall back to selecting `node`. Never throws. */
405
+ function copyText(text, node, done) {
406
+ try {
407
+ const clipboard = globalThis.navigator?.clipboard;
408
+
409
+ if (clipboard && typeof clipboard.writeText === "function") {
410
+ Promise.resolve(clipboard.writeText(text)).then(
411
+ () => done("Copied."),
412
+ () => selectNode(node, done),
413
+ );
414
+ return;
415
+ }
416
+ } catch {
417
+ // Fall through to selecting.
418
+ }
419
+
420
+ selectNode(node, done);
421
+ }
422
+
423
+ const STEP_ICONS = {
424
+ page: [["rect", { x: "3", y: "4", width: "18", height: "14", rx: "2" }], ["path", { d: "M3 9h18" }]],
425
+ route: [["path", { d: "M5 12h14M13 6l6 6-6 6" }]],
426
+ mail: [["rect", { x: "3", y: "5", width: "18", height: "14", rx: "2" }], ["path", { d: "M3 7l9 6 9-6" }]],
427
+ notification: [["path", { d: "M6 16v-5a6 6 0 0 1 12 0v5l2 2H4zM10 21h4" }]],
428
+ job: [["circle", { cx: "12", cy: "12", r: "9" }], ["path", { d: "M12 7v5l3 2" }]],
429
+ event: [["path", { d: "M13 2L4 14h7l-1 8 9-12h-7z" }]],
430
+ "outside service": [["path", { d: "M7 18a4 4 0 0 1 0-8 5 5 0 0 1 9.6-1.2A4 4 0 0 1 17 18z" }]],
431
+ affects: [
432
+ ["path", { d: "M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1" }],
433
+ ],
434
+ };
435
+
436
+ /** A small icon for a flow step type. */
437
+ function stepIcon(ctx, type) {
438
+ const { svg } = ctx;
439
+ const shapes = STEP_ICONS[type] ?? STEP_ICONS.route;
440
+
441
+ return svg(
442
+ "svg",
443
+ {
444
+ viewBox: "0 0 24 24",
445
+ width: "18",
446
+ height: "18",
447
+ fill: "none",
448
+ stroke: "currentColor",
449
+ "stroke-width": "1.8",
450
+ "stroke-linecap": "round",
451
+ "stroke-linejoin": "round",
452
+ "aria-hidden": "true",
453
+ class: "grimoire-step-icon",
454
+ },
455
+ shapes.map(([tag, attrs]) => svg(tag, attrs)),
456
+ );
457
+ }
458
+
459
+ /** Show a node's children only while open; the content is built on the first open. */
460
+ function expander(ctx, label, make) {
461
+ const panel = ctx.el("div", { class: "grimoire-expand" });
462
+ let node = null;
463
+ let open = false;
464
+ const button = ctx.el("button", {
465
+ type: "button",
466
+ class: "grimoire-more",
467
+ "aria-expanded": "false",
468
+ text: label,
469
+ onclick: () => {
470
+ open = !open;
471
+ if (open && node === null) node = make();
472
+ panel.replaceChildren(...(open && node ? [node] : []));
473
+ button.setAttribute("aria-expanded", String(open));
474
+ button.textContent = open ? "Hide" : label;
475
+ },
476
+ });
477
+
478
+ return { button, panel };
479
+ }
480
+
481
+ /**
482
+ * Findings loaded page by page from the check route: `filter` is a
483
+ * `GrimoireCheckFilter`; "Load more" appends the next page.
484
+ */
485
+ function pagedFindings(ctx, filter, options = {}) {
486
+ const { el } = ctx;
487
+ const size = options.size ?? 20;
488
+ const list = el("ul", { class: "grimoire-findings" });
489
+ const status = el("p", { class: "grimoire-muted", role: "status" });
490
+ const more = el("button", { type: "button", class: "grimoire-filter", text: "Load more" });
491
+ const holder = el("div", { class: "grimoire-paged" });
492
+ let offset = 0;
493
+ let busy = false;
494
+
495
+ function paint(total, failed) {
496
+ status.textContent = failed
497
+ ? `Could not load the findings: ${failed}. Try again.`
498
+ : `Showing ${offset} of ${total}`;
499
+ more.textContent = failed ? "Try again" : `Load ${Math.min(size, total - offset)} more`;
500
+ holder.replaceChildren(list, status, failed || offset < total ? more : "");
501
+ }
502
+
503
+ async function load() {
504
+ if (busy) return;
505
+ busy = true;
506
+
507
+ try {
508
+ const page = await ctx.api(checkTarget({ ...filter, offset, limit: size }));
509
+
510
+ for (const finding of page.findings) list.append(findingItem(ctx, finding, options));
511
+ offset += page.findings.length;
512
+ paint(page.total, null);
513
+ } catch (error) {
514
+ paint(0, error && error.message ? error.message : String(error));
515
+ }
516
+
517
+ busy = false;
518
+ }
519
+
520
+ more.addEventListener("click", load);
521
+ holder.append(el("p", { class: "grimoire-muted", role: "status", text: "Loading findings…" }));
522
+ load();
523
+ return holder;
524
+ }
525
+
526
+ /**
527
+ * A filterable, sortable listing: a text box, status buttons with counts, an
528
+ * optional sort menu and an "N of M" line. `render(shown)` returns the one
529
+ * node that fills the body each time the filters change.
530
+ */
531
+ function listing(ctx, options) {
532
+ const { el } = ctx;
533
+ const { items, noun, render } = options;
534
+ const state = { text: "", status: "", sort: options.sorts?.[0]?.[0] ?? "" };
535
+ const body = el("div", { class: "grimoire-listing-body" });
536
+ const count = el("p", {
537
+ class: "grimoire-listing-count",
538
+ role: "status",
539
+ "aria-live": "polite",
540
+ });
541
+ const buttons = [];
542
+ const bar = el("div", { class: "grimoire-toolbar" });
543
+
544
+ bar.append(
545
+ el("input", {
546
+ type: "search",
547
+ class: "grimoire-filter-input",
548
+ placeholder: `Filter ${noun}`,
549
+ "aria-label": `Filter ${noun}`,
550
+ oninput: (event) => {
551
+ state.text = event.target.value;
552
+ paint();
553
+ },
554
+ }),
555
+ );
556
+
557
+ if (options.statusOf) {
558
+ const found = [...new Set(items.map(options.statusOf))];
559
+ const order = options.statusOrder ?? [];
560
+ const statuses = found.sort(
561
+ (left, right) =>
562
+ (order.indexOf(left) < 0 ? 99 : order.indexOf(left)) -
563
+ (order.indexOf(right) < 0 ? 99 : order.indexOf(right)) || left.localeCompare(right),
564
+ );
565
+
566
+ if (statuses.length > 1) {
567
+ const group = el("div", { class: "grimoire-filters", role: "group", "aria-label": "Status" });
568
+
569
+ for (const status of ["", ...statuses]) {
570
+ const total = status
571
+ ? items.filter((item) => options.statusOf(item) === status).length
572
+ : items.length;
573
+ const button = el("button", {
574
+ type: "button",
575
+ class: "grimoire-filter",
576
+ "aria-pressed": "false",
577
+ text: `${status || "all"} ${total}`,
578
+ onclick: () => {
579
+ state.status = status;
580
+ paint();
581
+ },
582
+ });
583
+
584
+ buttons.push([button, status]);
585
+ group.append(button);
586
+ }
587
+
588
+ bar.append(group);
589
+ }
590
+ }
591
+
592
+ if (options.sorts && options.sorts.length > 1) {
593
+ bar.append(
594
+ el(
595
+ "select",
596
+ {
597
+ class: "grimoire-sort",
598
+ "aria-label": "Sort",
599
+ onchange: (event) => {
600
+ state.sort = event.target.value;
601
+ paint();
602
+ },
603
+ },
604
+ options.sorts.map(([key, label]) => el("option", { value: key, text: `Sort: ${label}` })),
605
+ ),
606
+ );
607
+ }
608
+
609
+ function paint() {
610
+ const query = state.text.trim().toLowerCase();
611
+ let shown = items.filter(
612
+ (item) =>
613
+ (!state.status || options.statusOf(item) === state.status) &&
614
+ (!query || options.textOf(item).toLowerCase().includes(query)),
615
+ );
616
+ const sort = options.sorts?.find(([key]) => key === state.sort);
617
+
618
+ if (sort) shown = [...shown].sort(sort[2]);
619
+
620
+ for (const [button, status] of buttons) {
621
+ button.setAttribute("aria-pressed", String(status === state.status));
622
+ }
623
+
624
+ count.textContent = `${shown.length} of ${items.length} ${noun}`;
625
+ body.replaceChildren(
626
+ shown.length
627
+ ? render(shown, items)
628
+ : ctx.empty(`No ${noun} match these filters. Clear the filter to see all ${items.length}.`),
629
+ );
630
+ }
631
+
632
+ paint();
633
+ return el("div", { class: "grimoire-listing" }, [bar, count, body]);
634
+ }
635
+
636
+ /** One finding: severity, code, message, what to do (unless `hints` is `false`), and where. */
637
+ function findingItem(ctx, finding, options = {}) {
638
+ const place = finding.at ? `${finding.at.file}:${finding.at.line}` : null;
639
+ const file = finding.subject.file;
640
+
641
+ return ctx.el("li", { class: "grimoire-finding" }, [
642
+ ctx.el("div", { class: "grimoire-finding-head" }, [
643
+ pill(ctx, finding.severity, toneOf(finding.severity)),
644
+ finding.expected ? pill(ctx, "expected") : "",
645
+ mono(ctx, finding.code),
646
+ ]),
647
+ ctx.el("p", { class: "grimoire-finding-message" }, codeText(ctx, finding.message)),
648
+ finding.hint && options.hints !== false
649
+ ? ctx.el("p", { class: "grimoire-muted" }, codeText(ctx, finding.hint))
650
+ : "",
651
+ place || file
652
+ ? ctx.el("div", { class: "grimoire-chips" }, [
653
+ place ? mono(ctx, place) : "",
654
+ file && file !== finding.at?.file ? fileLink(ctx, file) : "",
655
+ ])
656
+ : "",
657
+ ]);
658
+ }
659
+
660
+ /** A list of findings: severity, code, message, what to do, and where. */
661
+ function findingList(ctx, findings, options = {}) {
662
+ return ctx.el(
663
+ "ul",
664
+ { class: "grimoire-findings" },
665
+ findings.map((finding) => findingItem(ctx, finding, options)),
666
+ );
667
+ }
668
+
669
+ function changesView(ctx, changes) {
670
+ if (!changes.length) return ctx.empty("No changelog entries.");
671
+ return list(
672
+ ctx,
673
+ changes.map((change) => [
674
+ pill(ctx, change.word),
675
+ ` ${plain(change.version)} `,
676
+ change.flow ? [flowLink(ctx, `${change.feature}/${change.flow}`), " "] : "",
677
+ codeText(ctx, change.text),
678
+ change.release
679
+ ? ` (release ${change.release}${change.date ? `, ${change.date}` : ""})`
680
+ : " (not released)",
681
+ ]),
682
+ );
683
+ }
684
+
685
+ // ── Graphs ──────────────────────────────────────────────────────────────────
686
+
105
687
  /** Plain SVG for a graph answer: the centre node in the middle, the others on one or two rings. */
106
688
  function graphView(ctx, graph, title) {
107
689
  const { el, svg, empty, href } = ctx;
108
- const card = el("section", { class: "card grimoire-graph" }, [el("h3", { text: title })]);
690
+ const card = el("section", { class: "grimoire-card grimoire-graph" }, [
691
+ el("h3", { text: title }),
692
+ ]);
109
693
 
110
694
  if (!graph.nodes.length) {
111
695
  card.append(empty("Nothing to draw."));
@@ -152,13 +736,17 @@ function graphView(ctx, graph, title) {
152
736
  y1: from[1].toFixed(1),
153
737
  x2: to[0].toFixed(1),
154
738
  y2: to[1].toFixed(1),
155
- stroke: "var(--line)",
739
+ stroke: "var(--input)",
156
740
  "stroke-width": edge.weight ? String(Math.min(1 + Math.log2(edge.weight), 5)) : "1.2",
157
741
  }),
158
742
  );
159
743
  }
160
744
 
161
- for (const node of graph.nodes) {
745
+ // Labels overlap on a crowded ring: stagger them, and past 40 nodes name only the centre
746
+ // (every node keeps its tooltip, and the module list sits under the graph).
747
+ const labelled = graph.nodes.length <= 40;
748
+
749
+ for (const [position, node] of graph.nodes.entries()) {
162
750
  const at = place.get(node.id);
163
751
  if (!at) continue;
164
752
  const target = nodeTarget(node.id);
@@ -166,163 +754,305 @@ function graphView(ctx, graph, title) {
166
754
  cx: at[0].toFixed(1),
167
755
  cy: at[1].toFixed(1),
168
756
  r: node.type === "center" ? "9" : "6",
169
- fill: NODE_COLOURS[node.type] ?? "var(--muted)",
757
+ fill: NODE_COLOURS[node.type] ?? "var(--muted-foreground)",
170
758
  });
171
759
  const label = svg("text", {
172
760
  x: at[0].toFixed(1),
173
- y: (at[1] + (node.type === "center" ? 24 : 18)).toFixed(1),
761
+ y: (at[1] + (node.type === "center" ? 24 : 18 + (position % 2) * 12)).toFixed(1),
174
762
  "text-anchor": "middle",
175
- fill: "var(--text)",
763
+ fill: "var(--foreground)",
176
764
  "font-size": "11",
177
- text: shorten(node.label),
765
+ text: shorten(node.label, node.type === "center" ? 26 : 16),
178
766
  });
179
- const group = svg("g", {}, [svg("title", { text: node.label }), circle, label]);
767
+ const group = svg(
768
+ "g",
769
+ {},
770
+ [svg("title", { text: node.label }), circle, labelled || node.type === "center" ? label : ""].filter(
771
+ (child) => child !== "",
772
+ ),
773
+ );
180
774
  canvas.append(target === null ? group : svg("a", { href: href(target) }, [group]));
181
775
  }
182
776
 
183
- card.append(canvas);
777
+ card.append(el("div", { class: "grimoire-scroll" }, [canvas]));
778
+ if (!labelled) {
779
+ card.append(
780
+ el("p", {
781
+ class: "grimoire-muted",
782
+ text: "Too many nodes to label. Point at a node for its name; every module is listed below.",
783
+ }),
784
+ );
785
+ }
184
786
  return card;
185
787
  }
186
788
 
187
- /** One section card with a heading. */
188
- function section(ctx, title, children = []) {
189
- return ctx.el("section", { class: "card detail" }, [ctx.el("h3", { text: title }), ...children]);
190
- }
191
-
192
- function link(ctx, text, target, attrs = {}) {
193
- return ctx.el("a", { href: ctx.href(target), text, ...attrs });
194
- }
195
-
196
- function badge(ctx, text, tone = "") {
197
- return ctx.el("span", { class: tone ? `badge ${tone}` : "badge", text });
198
- }
789
+ // ── Views ───────────────────────────────────────────────────────────────────
199
790
 
200
- function list(ctx, items) {
791
+ /** One overview card: a number, what it counts, and where it leads. */
792
+ function stat(ctx, { label, value, sub, target, tone = "" }) {
201
793
  return ctx.el(
202
- "ul",
203
- { class: "grimoire-list" },
204
- items.map((item) => ctx.el("li", {}, item)),
794
+ "a",
795
+ { class: tone ? `grimoire-stat is-${tone}` : "grimoire-stat", href: ctx.href(target) },
796
+ [
797
+ ctx.el("span", { class: "grimoire-stat-label", text: label }),
798
+ ctx.el("span", { class: "grimoire-stat-value", text: String(value) }),
799
+ ctx.el("span", { class: "grimoire-stat-sub", text: sub }),
800
+ ],
205
801
  );
206
802
  }
207
803
 
208
- function table(ctx, headings, rows) {
209
- return ctx.el("table", { class: "grimoire-table" }, [
210
- ctx.el("thead", {}, [
211
- ctx.el(
212
- "tr",
213
- {},
214
- headings.map((heading) => ctx.el("th", { text: heading })),
215
- ),
216
- ]),
217
- ctx.el(
218
- "tbody",
219
- {},
220
- rows.map((row) =>
221
- ctx.el(
222
- "tr",
223
- {},
224
- row.map((cell) => ctx.el("td", {}, cell)),
225
- ),
226
- ),
227
- ),
228
- ]);
229
- }
230
-
231
- function statusTone(status) {
232
- if (status === "shipped" || status === "passing" || status === "pass") return "good";
233
- if (status === "retired" || status === "failing" || status === "fail" || status === "error")
234
- return "bad";
235
- return "";
236
- }
237
-
238
- /** `<feature>/<flow>` as a link. */
239
- function flowLink(ctx, ref) {
240
- const target = targetOf("flow", ref);
241
- return target === null ? ref : link(ctx, ref, target);
242
- }
243
-
244
- function fileLink(ctx, file) {
245
- return link(ctx, file, `file/${encodeURIComponent(file)}`);
246
- }
247
-
248
- function fileList(ctx, files, limit = 12) {
249
- if (!files.length) return ctx.el("span", { class: "muted", text: "none" });
250
- const shown = files.slice(0, limit);
251
- const items = shown.map((file) => [fileLink(ctx, file)]);
252
- if (files.length > limit)
253
- items.push([ctx.el("span", { class: "muted", text: `+${files.length - limit} more` })]);
254
- return list(ctx, items);
255
- }
256
-
257
- // ── Views ───────────────────────────────────────────────────────────────────
804
+ const STATUS_ORDER = ["shipped", "building", "proposed", "retired"];
258
805
 
259
- async function homeView(ctx) {
260
- const data = await ctx.api("summary");
806
+ async function overviewView(ctx, summaryRequest) {
807
+ const [data, check, releases] = await Promise.all([
808
+ summaryRequest,
809
+ ctx.api("check/groups").catch(() => null),
810
+ ctx.api("releases").catch(() => null),
811
+ ]);
261
812
  const { el } = ctx;
813
+ const features = data.features.features;
814
+ const byStatus = new Map();
815
+
816
+ for (const item of features) byStatus.set(item.status, (byStatus.get(item.status) ?? 0) + 1);
817
+
818
+ const flows = features.reduce((total, item) => total + item.flows.length, 0);
819
+ const statusLine = [...byStatus.entries()]
820
+ .sort(([a], [b]) => STATUS_ORDER.indexOf(a) - STATUS_ORDER.indexOf(b))
821
+ .map(([status, total]) => `${total} ${status}`)
822
+ .join(", ");
823
+ const waiting = data.tasks.waiting.length;
824
+ const open = data.tasks.open.length - waiting;
825
+ const stale = data.routes === "stale" || data.routes === "missing";
262
826
  const out = el("div", { class: "grimoire-view" });
263
- const cards = el("div", { class: "grimoire-cards" }, [
264
- el("div", { class: "card" }, [
265
- el("h3", { text: "Check" }),
266
- link(ctx, `${data.counts.errors} errors, ${data.counts.warnings} warnings`, "check"),
267
- el("p", { class: "muted", text: `${data.counts.expected} expected (proposed work)` }),
268
- ]),
269
- el("div", { class: "card" }, [
270
- el("h3", { text: "Tasks" }),
271
- link(
272
- ctx,
273
- `${data.tasks.open.length - data.tasks.waiting.length} open, ${data.tasks.waiting.length} waiting`,
274
- "tasks",
275
- ),
276
- el("p", { class: "muted", text: `${data.tasks.done.length} done` }),
277
- ]),
278
- el("div", { class: "card" }, [
279
- el("h3", { text: "Book" }),
280
- link(ctx, `${data.book.files} files in ${data.book.modules} modules`, "modules"),
281
- el("p", { class: "muted", text: `routes: ${data.routes}` }),
827
+
828
+ out.append(
829
+ el("div", { class: "grimoire-stats" }, [
830
+ stat(ctx, {
831
+ label: "Features",
832
+ value: features.length,
833
+ sub: features.length ? `${statusLine}; ${plural(flows, "flow")}` : "none written yet",
834
+ target: "features",
835
+ }),
836
+ stat(ctx, {
837
+ label: "Apps",
838
+ value: data.apps ? data.apps.apps : "-",
839
+ sub: data.apps
840
+ ? `${plural(data.apps.pages, "page")}, ${plural(data.apps.screens, "screen")}`
841
+ : "not counted",
842
+ target: "apps",
843
+ }),
844
+ stat(ctx, {
845
+ label: "Tasks",
846
+ value: open,
847
+ sub: `${open} open, ${waiting} waiting, ${data.tasks.done.length} done`,
848
+ target: "tasks",
849
+ tone: waiting ? "warn" : "",
850
+ }),
851
+ stat(ctx, {
852
+ label: "Check errors",
853
+ value: data.counts.errors,
854
+ sub: `${plural(data.counts.errors, "error")}, ${plural(data.counts.warnings, "warning")}, ${data.counts.expected} expected`,
855
+ target: "check",
856
+ tone: data.counts.errors ? "bad" : data.counts.warnings ? "warn" : "good",
857
+ }),
858
+ stat(ctx, {
859
+ label: "Book",
860
+ value: data.book.files,
861
+ sub: `files in ${plural(data.book.modules, "module")}`,
862
+ target: "modules",
863
+ }),
864
+ stat(ctx, {
865
+ label: "Route facts",
866
+ value: data.routes,
867
+ sub: stale ? "need a refresh" : "up to date",
868
+ target: "check",
869
+ tone: toneOf(data.routes),
870
+ }),
282
871
  ]),
283
- ]);
284
- out.append(cards);
872
+ );
285
873
 
286
- if (data.routes === "stale" || data.routes === "missing") {
874
+ if (stale) {
287
875
  out.append(
288
876
  el("p", {
289
- class: "muted",
877
+ class: "grimoire-note",
290
878
  text: "The route facts are old or missing. Run warlock grimoire build to refresh them.",
291
879
  }),
292
880
  );
293
881
  }
294
882
 
295
- const features = data.features.features;
296
-
297
883
  if (!features.length) {
298
884
  out.append(
299
885
  ctx.empty(
300
886
  data.book.files
301
- ? `No features are written yet. The book below lists ${data.book.files} files; search it above, or open the module graph. Ask your agent to write the features (skill use-the-grimoire).`
887
+ ? `No features are written yet. The book lists ${data.book.files} files; search it above, or open the module graph. Ask your agent to write the features (skill use-the-grimoire).`
302
888
  : "The book is empty. Run warlock grimoire build.",
303
889
  ),
304
890
  );
305
- return out;
306
891
  }
307
892
 
893
+ // Errors first, then the biggest groups; each leads to the Check tab filtered to its code.
894
+ const problems = (check?.groups ?? [])
895
+ .filter((group) => group.count > 0)
896
+ .sort(
897
+ (left, right) =>
898
+ (left.severity === "error" ? 0 : 1) - (right.severity === "error" ? 0 : 1) ||
899
+ right.count - left.count ||
900
+ left.code.localeCompare(right.code),
901
+ )
902
+ .slice(0, 5);
903
+ const recent = [...(releases?.releases ?? [])]
904
+ .sort((left, right) => right.date.localeCompare(left.date))
905
+ .slice(0, 5);
906
+
308
907
  out.append(
309
- section(ctx, "Features", [
310
- table(
311
- ctx,
312
- ["Feature", "Title", "Status", "Version", "Flows"],
313
- features.map((item) => [
314
- [link(ctx, item.id, `feature/${encodeURIComponent(item.id)}`)],
315
- [item.title],
316
- [badge(ctx, item.status, statusTone(item.status))],
317
- [item.version],
318
- [item.flows.map((flow) => flow.id).join(", ")],
319
- ]),
320
- ),
908
+ el("div", { class: "grimoire-split" }, [
909
+ section(ctx, "Top problems", [
910
+ check
911
+ ? problems.length
912
+ ? list(
913
+ ctx,
914
+ problems.map((group) => [
915
+ pill(ctx, group.severity, toneOf(group.severity)),
916
+ " ",
917
+ link(ctx, group.code, checkTarget({ code: group.code }), { class: "grimoire-mono" }),
918
+ " ",
919
+ ...[codeText(ctx, group.title)].flat(),
920
+ " ",
921
+ pill(ctx, String(group.count)),
922
+ ]),
923
+ )
924
+ : el("p", {}, [pill(ctx, "clean", "good"), " Nothing to fix."])
925
+ : ctx.empty("The check report could not be loaded."),
926
+ check ? el("p", {}, [link(ctx, "Open the check report", "check")]) : "",
927
+ ]),
928
+ section(ctx, "Recent releases", [
929
+ recent.length
930
+ ? list(
931
+ ctx,
932
+ recent.map((item) => [
933
+ link(ctx, item.release, `release/${encodeURIComponent(item.release)}`),
934
+ " ",
935
+ muted(ctx, item.date),
936
+ ]),
937
+ )
938
+ : ctx.empty(
939
+ releases ? "No releases are written yet." : "The releases could not be loaded.",
940
+ ),
941
+ recent.length ? el("p", {}, [link(ctx, "All releases", "releases")]) : "",
942
+ ]),
321
943
  ]),
322
944
  );
945
+
946
+ if (features.length) {
947
+ const latest = [...features]
948
+ .sort((left, right) => right.updated.localeCompare(left.updated))
949
+ .slice(0, 6);
950
+
951
+ out.append(
952
+ section(ctx, "Recently updated features", [
953
+ list(
954
+ ctx,
955
+ latest.map((item) => [
956
+ link(ctx, item.id, `feature/${encodeURIComponent(item.id)}`),
957
+ " ",
958
+ pill(ctx, item.status, toneOf(item.status)),
959
+ " ",
960
+ muted(ctx, `${item.title}, updated ${item.updated}`),
961
+ ]),
962
+ ),
963
+ el("p", {}, [link(ctx, `All ${features.length} features`, "features")]),
964
+ ]),
965
+ );
966
+ }
967
+
323
968
  return out;
324
969
  }
325
970
 
971
+ const FEATURE_SORTS = [
972
+ ["id", "name", (a, b) => a.id.localeCompare(b.id)],
973
+ [
974
+ "status",
975
+ "status",
976
+ (a, b) =>
977
+ STATUS_ORDER.indexOf(a.status) - STATUS_ORDER.indexOf(b.status) || a.id.localeCompare(b.id),
978
+ ],
979
+ ["flows", "most flows", (a, b) => b.flows.length - a.flows.length || a.id.localeCompare(b.id)],
980
+ [
981
+ "updated",
982
+ "recently updated",
983
+ (a, b) => b.updated.localeCompare(a.updated) || a.id.localeCompare(b.id),
984
+ ],
985
+ ];
986
+
987
+ async function featuresView(ctx) {
988
+ const data = await ctx.api("features");
989
+ const { el } = ctx;
990
+ const items = data.features;
991
+
992
+ if (!items.length) {
993
+ return ctx.empty(
994
+ "No features are written yet. Ask your agent to write them (skill use-the-grimoire), then run warlock grimoire build.",
995
+ );
996
+ }
997
+
998
+ return el("div", { class: "grimoire-view" }, [
999
+ heading(ctx, "Features"),
1000
+ listing(ctx, {
1001
+ items,
1002
+ noun: "features",
1003
+ placeholder: "Filter features",
1004
+ textOf: (item) =>
1005
+ [item.id, item.title, item.summary ?? "", ...item.flows.map((flow) => flow.id)].join(" "),
1006
+ statusOf: (item) => item.status,
1007
+ statusOrder: STATUS_ORDER,
1008
+ sorts: FEATURE_SORTS,
1009
+ render: (shown) =>
1010
+ el(
1011
+ "div",
1012
+ { class: "grimoire-feature-grid" },
1013
+ shown.map((item) => {
1014
+ const tone = toneOf(item.status);
1015
+
1016
+ return el(
1017
+ "article",
1018
+ { class: tone ? `grimoire-feature is-${tone}` : "grimoire-feature" },
1019
+ [
1020
+ el("header", {}, [
1021
+ el("h3", {}, [
1022
+ link(ctx, item.title || item.id, `feature/${encodeURIComponent(item.id)}`),
1023
+ ]),
1024
+ pill(ctx, item.status, tone),
1025
+ ]),
1026
+ el("p", { class: "grimoire-feature-id" }, [
1027
+ mono(ctx, item.id),
1028
+ ` version ${item.version}, updated ${item.updated}`,
1029
+ ]),
1030
+ item.summary ? el("p", { class: "grimoire-clamp", text: item.summary }) : "",
1031
+ el("div", { class: "grimoire-feature-flows" }, [
1032
+ muted(ctx, plural(item.flows.length, "flow")),
1033
+ item.flows.length
1034
+ ? chipList(
1035
+ ctx,
1036
+ item.flows,
1037
+ (flow) =>
1038
+ link(
1039
+ ctx,
1040
+ flow.id,
1041
+ `flow/${encodeURIComponent(item.id)}/${encodeURIComponent(flow.id)}`,
1042
+ { class: "grimoire-chip", title: flow.heading ?? flow.id },
1043
+ ),
1044
+ 6,
1045
+ )
1046
+ : "",
1047
+ ]),
1048
+ ],
1049
+ );
1050
+ }),
1051
+ ),
1052
+ }),
1053
+ ]);
1054
+ }
1055
+
326
1056
  async function featureView(ctx, id) {
327
1057
  const [data, graph] = await Promise.all([
328
1058
  ctx.api(`features/${encodeURIComponent(id)}`),
@@ -330,15 +1060,19 @@ async function featureView(ctx, id) {
330
1060
  ]);
331
1061
  const { el } = ctx;
332
1062
  const readme = data.readme;
1063
+ const status = plain(readme.status);
333
1064
  const out = el("div", { class: "grimoire-view" }, [
334
- el("h2", { text: `${plain(readme.title)} (${plain(readme.id)})` }),
335
- el("p", {}, [
336
- badge(ctx, plain(readme.status), statusTone(plain(readme.status))),
337
- ` version ${plain(readme.version)}, updated ${plain(readme.updated)}`,
1065
+ crumbs(ctx, [["Features", "features"], [String(plain(readme.id))]]),
1066
+ heading(ctx, plain(readme.title), [
1067
+ mono(ctx, plain(readme.id)),
1068
+ pill(ctx, status, toneOf(status)),
1069
+ pill(ctx, `version ${plain(readme.version)}`),
1070
+ readme.origin ? pill(ctx, plain(readme.origin), toneOf(plain(readme.origin))) : "",
1071
+ muted(ctx, `updated ${plain(readme.updated)}`),
338
1072
  ]),
339
1073
  ]);
340
1074
 
341
- if (readme.summary) out.append(el("p", { text: readme.summary }));
1075
+ if (readme.summary) out.append(el("p", { class: "grimoire-lede", text: readme.summary }));
342
1076
 
343
1077
  out.append(
344
1078
  section(ctx, "Flows", [
@@ -354,7 +1088,7 @@ async function featureView(ctx, id) {
354
1088
  `flow/${encodeURIComponent(plain(readme.id))}/${encodeURIComponent(flow.id)}`,
355
1089
  ),
356
1090
  ],
357
- [badge(ctx, flow.status, statusTone(flow.status))],
1091
+ [pill(ctx, flow.status, toneOf(flow.status))],
358
1092
  [flow.since],
359
1093
  [flow.heading ?? ""],
360
1094
  ]),
@@ -366,24 +1100,23 @@ async function featureView(ctx, id) {
366
1100
  const map = data.bookmap;
367
1101
  out.append(
368
1102
  section(ctx, "Code", [
369
- el("p", {
370
- text: `${map.own.length} own files, ${map.borrowed.length} borrowed, ${map.routes.length} routes, ${map.unreached.length} not reached by any flow.`,
371
- }),
1103
+ facts(ctx, [
1104
+ ["Own files", String(map.own.length)],
1105
+ ["Borrowed", String(map.borrowed.length)],
1106
+ ["Routes", String(map.routes.length)],
1107
+ ["Not reached by a flow", String(map.unreached.length)],
1108
+ ]),
372
1109
  el("h4", { text: "Routes" }),
373
1110
  map.routes.length
374
1111
  ? list(
375
1112
  ctx,
376
1113
  map.routes.map((item) => [
377
- link(
378
- ctx,
379
- `${item.method} ${item.path}`,
380
- `route/${encodeURIComponent(item.method)}/${encodeURIComponent(item.path)}`,
381
- ),
1114
+ routeLink(ctx, item.method, item.path),
382
1115
  " in ",
383
1116
  fileLink(ctx, item.file),
384
1117
  ]),
385
1118
  )
386
- : el("p", { class: "muted", text: "none" }),
1119
+ : muted(ctx, "none"),
387
1120
  el("h4", { text: "Pages and screens" }),
388
1121
  Object.keys(map.pages).length
389
1122
  ? list(
@@ -398,9 +1131,11 @@ async function featureView(ctx, id) {
398
1131
  ]),
399
1132
  ),
400
1133
  )
401
- : el("p", { class: "muted", text: "none" }),
1134
+ : muted(ctx, "none"),
1135
+ el("h4", { text: "Own files" }),
1136
+ fileChips(ctx, map.own, 12),
402
1137
  el("h4", { text: "Files no flow reaches" }),
403
- fileList(ctx, map.unreached),
1138
+ fileChips(ctx, map.unreached, 12),
404
1139
  ]),
405
1140
  );
406
1141
 
@@ -410,9 +1145,11 @@ async function featureView(ctx, id) {
410
1145
  list(
411
1146
  ctx,
412
1147
  data.tasks.map((task) => [
413
- link(ctx, task.id, `task/${encodeURIComponent(task.id)}`),
414
- ` ${task.title} `,
415
- badge(ctx, task.status),
1148
+ link(ctx, task.id, `task/${encodeURIComponent(task.id)}`, { class: "grimoire-nowrap" }),
1149
+ " ",
1150
+ codeText(ctx, task.title),
1151
+ " ",
1152
+ pill(ctx, task.status, toneOf(task.status)),
416
1153
  ]),
417
1154
  ),
418
1155
  ]),
@@ -421,45 +1158,319 @@ async function featureView(ctx, id) {
421
1158
 
422
1159
  out.append(section(ctx, "Recent changes", [changesView(ctx, data.changes)]));
423
1160
 
424
- if (data.findings.length)
425
- out.append(section(ctx, "Findings", [findingsView(ctx, data.findings)]));
1161
+ if (data.findings.length) out.append(section(ctx, "Findings", [findingList(ctx, data.findings)]));
426
1162
  if (graph) out.append(graphView(ctx, graph, "The feature and its neighbours"));
427
1163
  return out;
428
1164
  }
429
1165
 
430
- function changesView(ctx, changes) {
431
- if (!changes.length) return ctx.empty("No changelog entries.");
432
- return list(
433
- ctx,
434
- changes.map((change) => [
435
- badge(ctx, change.word),
436
- ` ${plain(change.version)} `,
437
- change.flow ? [flowLink(ctx, `${change.feature}/${change.flow}`), " "] : "",
438
- change.text,
439
- change.release
440
- ? ` (release ${change.release}${change.date ? `, ${change.date}` : ""})`
441
- : " (not released)",
442
- ]),
1166
+ const STEP_FILE_SETS = [
1167
+ ["direct", "Direct imports", "direct"],
1168
+ ["feature", "In this feature", "feature"],
1169
+ ["reachable", "All reachable", "reachable"],
1170
+ ["type-only", "Type-only", "typeOnly"],
1171
+ ];
1172
+
1173
+ /** The files behind one step, loaded a page at a time from the step files route. */
1174
+ function stepFilesPanel(ctx, feature, flowId, step) {
1175
+ const { el } = ctx;
1176
+ const counts = step.counts ?? { direct: 0, feature: 0, reachable: 0, typeOnly: 0 };
1177
+ const sets = STEP_FILE_SETS.filter(([, , key]) => key !== "typeOnly" || counts[key] > 0);
1178
+ const body = el("div", { class: "grimoire-step-files-body" });
1179
+ const tabs = el("div", { class: "grimoire-subtabs", role: "tablist", "aria-label": "File set" });
1180
+ const loaded = new Map();
1181
+ const buttons = [];
1182
+
1183
+ function paint(state) {
1184
+ const groups = new Map();
1185
+
1186
+ for (const item of state.files) groups.set(item.module, [...(groups.get(item.module) ?? []), item]);
1187
+
1188
+ state.box.replaceChildren(
1189
+ ...[...groups.entries()].map(([name, items]) =>
1190
+ el("div", { class: "grimoire-module-group" }, [
1191
+ el("h5", { text: `${name || "(no module)"} (${items.length})` }),
1192
+ el(
1193
+ "div",
1194
+ { class: "grimoire-chips" },
1195
+ items.map((item) => fileLink(ctx, item.file)),
1196
+ ),
1197
+ ]),
1198
+ ),
1199
+ state.files.length || state.error ? "" : muted(ctx, "No files in this set."),
1200
+ state.error
1201
+ ? el("p", { class: "grimoire-error-title", text: `Could not load the files: ${state.error}. Try again.` })
1202
+ : "",
1203
+ state.files.length < state.total || state.error
1204
+ ? el("button", {
1205
+ type: "button",
1206
+ class: "grimoire-filter",
1207
+ text: state.error ? "Try again" : `Load ${Math.min(STEP_FILES_PAGE, state.total - state.files.length)} more`,
1208
+ onclick: () => fetchPage(state),
1209
+ })
1210
+ : "",
1211
+ );
1212
+ }
1213
+
1214
+ async function fetchPage(state) {
1215
+ if (state.busy) return;
1216
+ state.busy = true;
1217
+
1218
+ try {
1219
+ const answer = await ctx.api(
1220
+ `flows/${encodeURIComponent(feature)}/${encodeURIComponent(flowId)}/steps/${step.index}/files?set=${state.set}&offset=${state.files.length}`,
1221
+ );
1222
+
1223
+ state.files.push(...answer.files);
1224
+ state.total = answer.total;
1225
+ state.error = null;
1226
+ } catch (error) {
1227
+ state.error = error && error.message ? error.message : String(error);
1228
+ }
1229
+
1230
+ state.busy = false;
1231
+ paint(state);
1232
+ }
1233
+
1234
+ function open(set) {
1235
+ let state = loaded.get(set);
1236
+
1237
+ if (!state) {
1238
+ state = { set, files: [], total: 0, error: null, busy: false, box: el("div", {}) };
1239
+ state.box.append(muted(ctx, "Loading files…"));
1240
+ loaded.set(set, state);
1241
+ fetchPage(state);
1242
+ }
1243
+
1244
+ for (const [button, key] of buttons) {
1245
+ button.setAttribute("aria-selected", String(key === set));
1246
+ button.setAttribute("class", key === set ? "grimoire-subtab is-active" : "grimoire-subtab");
1247
+ }
1248
+
1249
+ body.replaceChildren(state.box);
1250
+ }
1251
+
1252
+ for (const [key, label, countKey] of sets) {
1253
+ const button = el("button", {
1254
+ type: "button",
1255
+ role: "tab",
1256
+ class: "grimoire-subtab",
1257
+ "aria-selected": "false",
1258
+ text: `${label} ${counts[countKey]}`,
1259
+ onclick: () => open(key),
1260
+ });
1261
+
1262
+ buttons.push([button, key]);
1263
+ tabs.append(button);
1264
+ }
1265
+
1266
+ open("direct");
1267
+ return el("div", { class: "grimoire-step-files" }, [tabs, body]);
1268
+ }
1269
+
1270
+ const STEP_FILES_PAGE = 200;
1271
+
1272
+ /** A number tile that leads nowhere. */
1273
+ function tile(ctx, { label, value, sub, tone = "" }) {
1274
+ return ctx.el("div", { class: tone ? `grimoire-stat is-${tone}` : "grimoire-stat" }, [
1275
+ ctx.el("span", { class: "grimoire-stat-label", text: label }),
1276
+ ctx.el("span", { class: "grimoire-stat-value", text: String(value) }),
1277
+ ctx.el("span", { class: "grimoire-stat-sub", text: sub }),
1278
+ ]);
1279
+ }
1280
+
1281
+ /** How many files a step reaches, in words. */
1282
+ function countsLine(counts) {
1283
+ const parts = [
1284
+ `${counts.direct} direct`,
1285
+ `${counts.feature} in feature`,
1286
+ `${counts.reachable} reachable`,
1287
+ ];
1288
+
1289
+ if (counts.typeOnly > 0) parts.push(`${counts.typeOnly} type-only`);
1290
+
1291
+ return parts.join(" · ");
1292
+ }
1293
+
1294
+ /** The journey: steps as a vertical stepper. */
1295
+ function journey(ctx, feature, flowId, flow, steps) {
1296
+ const { el } = ctx;
1297
+
1298
+ if (!steps.length) return ctx.empty("This flow has no steps.");
1299
+
1300
+ return el(
1301
+ "ol",
1302
+ { class: "grimoire-stepper" },
1303
+ steps.map((step) => {
1304
+ const written = (flow.steps ?? []).find((item) => item.index === step.index);
1305
+ const note = written && written.note ? written.note : null;
1306
+ const counts = step.counts ?? { direct: 0, feature: 0, reachable: 0, typeOnly: 0 };
1307
+ const shown = expander(ctx, "Show files", () => stepFilesPanel(ctx, feature, flowId, step));
1308
+ const space = step.target.indexOf(" ");
1309
+
1310
+ return el("li", { class: "grimoire-step" }, [
1311
+ el("span", { class: "grimoire-step-marker" }, [stepIcon(ctx, step.type)]),
1312
+ el("div", { class: "grimoire-step-body" }, [
1313
+ el("div", { class: "grimoire-step-head" }, [
1314
+ mono(ctx, `${step.index}`),
1315
+ pill(ctx, step.type),
1316
+ step.type === "route" && space > 0
1317
+ ? routeLink(ctx, step.target.slice(0, space), step.target.slice(space + 1))
1318
+ : el("span", { class: "grimoire-step-target", text: step.target }),
1319
+ step.found === false ? pill(ctx, "not found in the book", "bad") : "",
1320
+ ]),
1321
+ note ? el("p", { class: "grimoire-muted" }, codeText(ctx, note)) : "",
1322
+ step.linked
1323
+ ? el("p", { class: "grimoire-linked" }, [
1324
+ "Affects ",
1325
+ flowLink(ctx, step.linked.ref),
1326
+ step.linked.heading ? ` (${step.linked.heading})` : "",
1327
+ step.linked.summary ? el("span", { class: "grimoire-muted" }, [" ", step.linked.summary]) : "",
1328
+ ])
1329
+ : "",
1330
+ step.entry ? el("p", {}, [muted(ctx, "Starts at "), fileLink(ctx, step.entry)]) : "",
1331
+ counts.reachable || counts.direct
1332
+ ? el("div", { class: "grimoire-step-counts" }, [muted(ctx, countsLine(counts)), shown.button])
1333
+ : "",
1334
+ shown.panel,
1335
+ ]),
1336
+ ]);
1337
+ }),
443
1338
  );
444
1339
  }
445
1340
 
446
- function findingsView(ctx, findings) {
447
- return table(
448
- ctx,
449
- ["Code", "Severity", "Message", "Where"],
450
- findings.map((finding) => [
451
- [finding.code],
452
- [
453
- badge(
454
- ctx,
455
- finding.expected ? `${finding.severity} (expected)` : finding.severity,
456
- finding.severity === "error" && !finding.expected ? "bad" : "",
457
- ),
458
- ],
459
- [finding.message],
460
- [finding.at ? `${finding.at.file}:${finding.at.line}` : (finding.subject.file ?? "")],
1341
+ /** The health numbers; older answers have none, so they are counted from the criteria. */
1342
+ function flowHealth(data) {
1343
+ if (data.health) return data.health;
1344
+
1345
+ const criteria = data.bookmap.criteria;
1346
+ const byStatus = { pass: 0, fail: 0, stale: 0, "not-run": 0, "no-test": 0 };
1347
+
1348
+ for (const item of criteria) byStatus[item.status] = (byStatus[item.status] ?? 0) + 1;
1349
+
1350
+ return {
1351
+ criteria: { total: criteria.length, proven: byStatus.pass, byStatus },
1352
+ steps: {
1353
+ total: data.bookmap.steps.length,
1354
+ resolved: data.bookmap.steps.filter((step) => step.found !== false).length,
1355
+ },
1356
+ findings: { errors: 0, warnings: 0, expected: 0 },
1357
+ };
1358
+ }
1359
+
1360
+ /** The first criterion to work on: failing, then without a test, then not run or stale. */
1361
+ function fixNextCriterion(criteria) {
1362
+ for (const status of ["fail", "no-test", "not-run", "stale"]) {
1363
+ const found = criteria.find((item) => item.status === status);
1364
+
1365
+ if (found) return found;
1366
+ }
1367
+
1368
+ return null;
1369
+ }
1370
+
1371
+ /** The "Fix next" box. */
1372
+ function fixNextBox(ctx, ref, criterion) {
1373
+ const { el } = ctx;
1374
+
1375
+ if (!criterion) {
1376
+ return el("section", { class: "grimoire-card grimoire-fixnext is-good" }, [
1377
+ el("h3", { text: "Fix next" }),
1378
+ el("p", {}, [pill(ctx, "done", "good"), " Every criterion is proven by a passing test."]),
1379
+ ]);
1380
+ }
1381
+
1382
+ const status = criterion.status;
1383
+ const first = criterion.tests[0];
1384
+ const line = `// @proves ${ref} ${criterion.id}`;
1385
+ const lead =
1386
+ status === "fail"
1387
+ ? `${criterion.id} fails${first ? ` in ${first.file}:${first.line}` : ""}. Fix the code or the test, then run the tests again.`
1388
+ : status === "no-test"
1389
+ ? `${criterion.id} has no test. Put this line directly above the test that proves it.`
1390
+ : status === "stale"
1391
+ ? `${criterion.id} has a result older than its test file. Run the tests again.`
1392
+ : `${criterion.id} has a test that has not run. Run the tests with the Grimoire reporter.`;
1393
+ const code = el("code", { class: "grimoire-code grimoire-proof-line", text: line });
1394
+ const note = el("span", { class: "grimoire-muted", role: "status" });
1395
+ const body = [
1396
+ el("p", { class: "grimoire-fixnext-lead" }, [
1397
+ pill(ctx, status, toneOf(status)),
1398
+ " ",
1399
+ codeText(ctx, lead),
461
1400
  ]),
462
- );
1401
+ el("p", { class: "grimoire-muted" }, codeText(ctx, criterion.text)),
1402
+ ];
1403
+
1404
+ if (status === "no-test") {
1405
+ body.push(
1406
+ el("div", { class: "grimoire-copyline" }, [
1407
+ code,
1408
+ el("button", {
1409
+ type: "button",
1410
+ class: "grimoire-filter",
1411
+ text: "Copy",
1412
+ onclick: () => copyText(line, code, (message) => (note.textContent = message)),
1413
+ }),
1414
+ note,
1415
+ ]),
1416
+ );
1417
+ }
1418
+
1419
+ return el("section", { class: "grimoire-card grimoire-fixnext" }, [el("h3", { text: "Fix next" }), ...body]);
1420
+ }
1421
+
1422
+ /** One criterion with one status pill and the tests behind it. */
1423
+ function proofRow(ctx, criterion, untracked) {
1424
+ const { el } = ctx;
1425
+ // Tagged tests with no results file read "tagged", not "not-run".
1426
+ const label = (status) => (untracked && status === "not-run" ? "tagged" : status);
1427
+ const tone = (status) => (untracked && status === "not-run" ? "" : toneOf(status));
1428
+
1429
+ return el("li", { class: "grimoire-proof", id: `grimoire-ac-${criterion.id}` }, [
1430
+ el("div", { class: "grimoire-proof-head" }, [
1431
+ mono(ctx, criterion.id),
1432
+ criterion.app ? pill(ctx, criterion.app) : "",
1433
+ pill(ctx, label(criterion.status), tone(criterion.status)),
1434
+ ]),
1435
+ el("p", { class: "grimoire-proof-text" }, codeText(ctx, criterion.text)),
1436
+ criterion.tests.length
1437
+ ? el(
1438
+ "ul",
1439
+ { class: "grimoire-proof-tests" },
1440
+ criterion.tests.map((test) =>
1441
+ el("li", {}, [
1442
+ fileLink(ctx, test.file),
1443
+ mono(ctx, `:${test.line}`),
1444
+ test.name ? el("span", {}, [" ", test.name]) : "",
1445
+ " ",
1446
+ pill(
1447
+ ctx,
1448
+ test.stale ? `${label(test.result)}, stale` : label(test.result),
1449
+ test.stale ? "warn" : tone(test.result),
1450
+ ),
1451
+ ]),
1452
+ ),
1453
+ )
1454
+ : "",
1455
+ ]);
1456
+ }
1457
+
1458
+ /** A flow's neighbours in the README order. */
1459
+ function neighbours(ctx, feature, data, className) {
1460
+ const make = (item, arrow) =>
1461
+ item
1462
+ ? link(ctx, arrow === "prev" ? `‹ ${item.heading ?? item.id}` : `${item.heading ?? item.id} ›`, `flow/${encodeURIComponent(feature)}/${encodeURIComponent(item.id)}`, {
1463
+ class: `grimoire-neighbour is-${arrow}`,
1464
+ rel: arrow,
1465
+ })
1466
+ : "";
1467
+
1468
+ if (!data.previous && !data.next) return "";
1469
+
1470
+ return ctx.el("nav", { class: className, "aria-label": "Other flows of this feature" }, [
1471
+ make(data.previous, "prev"),
1472
+ make(data.next, "next"),
1473
+ ]);
463
1474
  }
464
1475
 
465
1476
  async function flowView(ctx, feature, flowId) {
@@ -467,78 +1478,194 @@ async function flowView(ctx, feature, flowId) {
467
1478
  const { el } = ctx;
468
1479
  const flow = data.flow;
469
1480
  const map = data.bookmap;
470
- const out = el("div", { class: "grimoire-view" }, [
471
- el("h2", { text: `${plain(flow.heading) ?? plain(flow.id)} (${feature}/${flowId})` }),
472
- el("p", {}, [
473
- badge(ctx, plain(flow.status), statusTone(plain(flow.status))),
474
- ` since ${plain(flow.since)}, for ${plain(flow.who)}. `,
475
- link(ctx, `Back to ${feature}`, `feature/${encodeURIComponent(feature)}`),
1481
+ const ref = `${feature}/${flowId}`;
1482
+ const status = plain(flow.status);
1483
+ const origin = flow.origin ? plain(flow.origin) : null;
1484
+ const title = plain(flow.heading) ?? plain(flow.id);
1485
+ const summary = plain(flow.summary) ?? null;
1486
+ const health = flowHealth(data);
1487
+ const results = data.results ?? null;
1488
+ const untracked = Boolean(results && results.recorded === false && results.proofs > 0);
1489
+ const apps = data.feature && data.feature.apps ? data.feature.apps : [];
1490
+ const problems = health.findings.errors + health.findings.warnings;
1491
+ const proven = health.criteria.proven;
1492
+ const total = health.criteria.total;
1493
+ const failing = health.criteria.byStatus.fail ?? 0;
1494
+ const out = el("div", { class: "grimoire-view grimoire-flow" }, [
1495
+ el("div", { class: "grimoire-minihead" }, [
1496
+ el("strong", { text: title }),
1497
+ pill(ctx, status, toneOf(status)),
1498
+ muted(ctx, `${proven}/${total} proven`),
1499
+ ]),
1500
+ crumbs(ctx, [
1501
+ ["Features", "features"],
1502
+ [(data.feature && data.feature.title) || feature, `feature/${encodeURIComponent(feature)}`],
1503
+ [title],
1504
+ ]),
1505
+ heading(ctx, title, [
1506
+ mono(ctx, ref),
1507
+ pill(ctx, status, toneOf(status)),
1508
+ origin ? pill(ctx, origin, toneOf(origin)) : "",
1509
+ muted(ctx, `since ${plain(flow.since)}, for ${plain(flow.who)}`),
1510
+ ...apps.map((app) => pill(ctx, app)),
1511
+ neighbours(ctx, feature, data, "grimoire-switcher"),
1512
+ ]),
1513
+ summary
1514
+ ? el("p", { class: "grimoire-lede" }, codeText(ctx, summary))
1515
+ : el("p", {
1516
+ class: "grimoire-muted",
1517
+ text: "No summary yet. Add one sentence under the title of the flow file.",
1518
+ }),
1519
+ el("div", { class: "grimoire-stats grimoire-health" }, [
1520
+ tile(ctx, {
1521
+ label: "Criteria proven",
1522
+ value: `${proven}/${total}`,
1523
+ sub: failing ? `${plural(failing, "criterion")} failing` : total ? "passing tests" : "none written",
1524
+ tone: failing ? "bad" : total && proven === total ? "good" : total ? "warn" : "",
1525
+ }),
1526
+ el("div", { class: "grimoire-stat" }, [
1527
+ el("span", { class: "grimoire-stat-label", text: "Last test run" }),
1528
+ el("span", {
1529
+ class: "grimoire-stat-value grimoire-stat-small",
1530
+ text: results && results.recorded && results.updatedAt ? results.updatedAt.slice(0, 10) : "none",
1531
+ }),
1532
+ el("span", {
1533
+ class: "grimoire-stat-sub",
1534
+ text: results && results.recorded ? "results recorded" : "no results recorded",
1535
+ }),
1536
+ ]),
1537
+ stat(ctx, {
1538
+ label: "Findings",
1539
+ value: problems,
1540
+ sub: `${plural(health.findings.errors, "error")}, ${plural(health.findings.warnings, "warning")}`,
1541
+ target: checkTarget({ flow: ref }),
1542
+ tone: health.findings.errors ? "bad" : problems ? "warn" : "good",
1543
+ }),
1544
+ el("div", { class: "grimoire-stat" }, [
1545
+ el("span", { class: "grimoire-stat-label", text: "Steps resolved" }),
1546
+ el("span", {
1547
+ class: "grimoire-stat-value",
1548
+ text: `${health.steps.resolved}/${health.steps.total}`,
1549
+ }),
1550
+ el("span", { class: "grimoire-stat-sub", text: "found in the book" }),
1551
+ ]),
476
1552
  ]),
477
1553
  ]);
478
1554
 
479
- out.append(
480
- section(ctx, "Steps", [
481
- map.steps.length
482
- ? table(
483
- ctx,
484
- ["#", "Type", "Target", "Found", "Files"],
485
- map.steps.map((step) => [
486
- [String(step.index)],
487
- [step.type],
488
- [
489
- step.type === "route" && step.target.includes(" ")
490
- ? link(
491
- ctx,
492
- step.target,
493
- `route/${encodeURIComponent(step.target.split(" ")[0])}/${encodeURIComponent(step.target.slice(step.target.indexOf(" ") + 1))}`,
494
- )
495
- : step.target,
496
- ],
497
- [step.found === null ? "" : step.found ? "yes" : "no"],
498
- [step.files.length ? fileList(ctx, step.files, 6) : ""],
499
- ]),
500
- )
501
- : ctx.empty("This flow has no steps."),
502
- ]),
503
- );
1555
+ if (untracked) {
1556
+ out.append(
1557
+ el("div", { class: "grimoire-note", role: "note" }, [
1558
+ el("strong", { text: "No test results recorded yet. " }),
1559
+ codeText(
1560
+ ctx,
1561
+ `${results.proofs} tagged ${results.proofs === 1 ? "test is" : "tests are"} waiting for a result. Add \`grimoireReporter()\` to the Vitest config and run the tests, or set the panel option \`testResultsFile\`. Looking in ${results.file}.`,
1562
+ ),
1563
+ ]),
1564
+ );
1565
+ }
504
1566
 
1567
+ out.append(fixNextBox(ctx, ref, fixNextCriterion(map.criteria)));
1568
+ out.append(section(ctx, "Journey", [journey(ctx, feature, flowId, flow, map.steps)]));
505
1569
  out.append(
506
- section(ctx, "Acceptance criteria", [
1570
+ section(ctx, "Proof", [
507
1571
  map.criteria.length
508
- ? table(
509
- ctx,
510
- ["Id", "App", "Criterion", "Result", "Tests"],
511
- map.criteria.map((criterion) => [
512
- [criterion.id],
513
- [criterion.app ?? "all"],
514
- [criterion.text],
515
- [badge(ctx, criterion.status, statusTone(criterion.status))],
516
- [
517
- criterion.tests.length
518
- ? list(
519
- ctx,
520
- criterion.tests.map((test) => [
521
- fileLink(ctx, test.file),
522
- `:${test.line} `,
523
- test.name ?? "",
524
- " ",
525
- badge(
526
- ctx,
527
- test.stale ? `${test.result}, stale` : test.result,
528
- statusTone(test.result),
529
- ),
530
- ]),
531
- )
532
- : el("span", { class: "muted", text: "no test" }),
533
- ],
534
- ]),
1572
+ ? el(
1573
+ "ul",
1574
+ { class: "grimoire-proofs" },
1575
+ map.criteria.map((criterion) => proofRow(ctx, criterion, untracked)),
535
1576
  )
536
1577
  : ctx.empty("No criteria written."),
537
1578
  ]),
538
1579
  );
539
1580
 
1581
+ if ((flow.differs ?? []).length) {
1582
+ out.append(
1583
+ section(ctx, "Differs by app", [
1584
+ list(
1585
+ ctx,
1586
+ flow.differs.map((item) => [mono(ctx, item.name), " ", codeText(ctx, item.text)]),
1587
+ ),
1588
+ ]),
1589
+ );
1590
+ }
1591
+
1592
+ if (flow.cases.length) {
1593
+ const handled = flow.cases.filter((item) => !item.doesNotApply);
1594
+ const skipped = flow.cases.filter((item) => item.doesNotApply);
1595
+ const jump = (id) =>
1596
+ el("button", {
1597
+ type: "button",
1598
+ class: "grimoire-chip",
1599
+ title: `Go to ${id}`,
1600
+ text: id,
1601
+ onclick: () => {
1602
+ const target = out.findAll
1603
+ ? out.findAll((node) => node.attributes && node.attributes.id === `grimoire-ac-${id}`)[0]
1604
+ : out.querySelector?.(`[id="grimoire-ac-${id}"]`);
1605
+
1606
+ target?.scrollIntoView?.({ block: "center" });
1607
+ },
1608
+ });
1609
+
1610
+ out.append(
1611
+ section(ctx, "Cases", [
1612
+ handled.length
1613
+ ? el(
1614
+ "ul",
1615
+ { class: "grimoire-cases" },
1616
+ handled.map((item) =>
1617
+ el("li", {}, [
1618
+ el("strong", { text: item.question }),
1619
+ " ",
1620
+ codeText(ctx, item.answer),
1621
+ (item.criteria ?? []).length
1622
+ ? el("span", { class: "grimoire-chips" }, [" proven by ", ...item.criteria.map(jump)])
1623
+ : "",
1624
+ ]),
1625
+ ),
1626
+ )
1627
+ : muted(ctx, "No handled cases written."),
1628
+ skipped.length
1629
+ ? el("details", { class: "grimoire-details" }, [
1630
+ el("summary", { text: `Does not apply (${skipped.length})` }),
1631
+ list(
1632
+ ctx,
1633
+ skipped.map((item) => [
1634
+ el("strong", { text: item.question }),
1635
+ " ",
1636
+ codeText(ctx, stripDoesNotApply(item.answer)),
1637
+ ]),
1638
+ ),
1639
+ ])
1640
+ : "",
1641
+ ]),
1642
+ );
1643
+ }
1644
+
1645
+ if ((flow.notHandled ?? []).length) {
1646
+ out.append(
1647
+ section(ctx, "Not handled", [
1648
+ list(
1649
+ ctx,
1650
+ flow.notHandled.map((item) => [el("strong", { text: item.name }), " ", codeText(ctx, item.text)]),
1651
+ ),
1652
+ ]),
1653
+ );
1654
+ }
1655
+
1656
+ if (flow.unknowns.length) {
1657
+ out.append(
1658
+ section(ctx, "Unknowns", [
1659
+ list(
1660
+ ctx,
1661
+ flow.unknowns.map((item) => [codeText(ctx, item.text)]),
1662
+ ),
1663
+ ]),
1664
+ );
1665
+ }
1666
+
540
1667
  out.append(
541
- section(ctx, "Shown by", [
1668
+ section(ctx, "Where users see it", [
542
1669
  map.shownBy.length
543
1670
  ? list(
544
1671
  ctx,
@@ -556,36 +1683,14 @@ async function flowView(ctx, feature, flowId) {
556
1683
  : ctx.empty("No app page shows this flow."),
557
1684
  ]),
558
1685
  );
1686
+ out.append(section(ctx, "History", [changesView(ctx, data.history)]));
559
1687
 
560
- if (flow.cases.length) {
561
- out.append(
562
- section(ctx, "Cases", [
563
- table(
564
- ctx,
565
- ["Question", "Answer"],
566
- flow.cases.map((item) => [
567
- [item.question],
568
- [item.doesNotApply ? `does not apply: ${item.answer}` : item.answer],
569
- ]),
570
- ),
571
- ]),
572
- );
573
- }
1688
+ // Missing tests are already shown per criterion above, so they are not listed twice.
1689
+ const rest = data.findings.filter((finding) => finding.code !== "GR4001");
574
1690
 
575
- if (flow.unknowns.length) {
576
- out.append(
577
- section(ctx, "Unknowns", [
578
- list(
579
- ctx,
580
- flow.unknowns.map((item) => [item.text]),
581
- ),
582
- ]),
583
- );
584
- }
1691
+ if (rest.length) out.append(section(ctx, "Findings", [findingList(ctx, rest)]));
585
1692
 
586
- out.append(section(ctx, "History", [changesView(ctx, data.history)]));
587
- if (data.findings.length)
588
- out.append(section(ctx, "Findings", [findingsView(ctx, data.findings)]));
1693
+ out.append(neighbours(ctx, feature, data, "grimoire-pager"));
589
1694
  return out;
590
1695
  }
591
1696
 
@@ -599,13 +1704,20 @@ async function pageView(ctx, app, key) {
599
1704
  ]);
600
1705
  const { el } = ctx;
601
1706
  const page = data.page;
1707
+ const title = plain(page.heading) ?? page.id;
1708
+ const route = plain(page.route) ?? plain(page.screen) ?? page.id;
1709
+ const origin = page.origin ? plain(page.origin) : null;
602
1710
  const out = el("div", { class: "grimoire-view" }, [
603
- el("h2", {
604
- text: `${plain(page.heading) ?? page.id} (${app} ${plain(page.route) ?? plain(page.screen) ?? page.id})`,
605
- }),
1711
+ crumbs(ctx, [["Apps", "apps"], [app, "apps"], [title]]),
1712
+ heading(ctx, title, [
1713
+ pill(ctx, page.type === "screen" ? "screen" : "page"),
1714
+ mono(ctx, route),
1715
+ muted(ctx, app),
1716
+ origin ? pill(ctx, origin, toneOf(origin)) : "",
1717
+ ]),
606
1718
  ]);
607
1719
 
608
- if (page.purpose) out.append(el("p", { text: page.purpose }));
1720
+ if (page.purpose) out.append(el("p", { class: "grimoire-lede", text: page.purpose }));
609
1721
 
610
1722
  const rows = [
611
1723
  ...(data.layout ? data.layout.blocks.map((row) => ({ row, from: "layout" })) : []),
@@ -619,7 +1731,7 @@ async function pageView(ctx, app, key) {
619
1731
  ["Block", "From", "Flow", "Who", "Changes with"],
620
1732
  rows.map(({ row, from }) => [
621
1733
  [row.block],
622
- [from],
1734
+ [pill(ctx, from)],
623
1735
  [row.flow ? flowLink(ctx, row.flow) : ""],
624
1736
  [row.who.everyone ? "everyone" : row.who.conditions.join(", ")],
625
1737
  [
@@ -656,13 +1768,16 @@ async function pageView(ctx, app, key) {
656
1768
  if (data.book) {
657
1769
  out.append(
658
1770
  section(ctx, "In the code", [
659
- el("p", {}, [fileLink(ctx, data.book.file)]),
660
- data.book.layouts?.length
661
- ? el("p", {}, ["Layouts: ", fileList(ctx, data.book.layouts)])
662
- : "",
663
- data.book.requires?.length
664
- ? el("p", { text: `Requires: ${data.book.requires.join(", ")}` })
665
- : "",
1771
+ facts(ctx, [
1772
+ ["File", fileLink(ctx, data.book.file)],
1773
+ ["Layouts", data.book.layouts?.length ? fileChips(ctx, data.book.layouts) : null],
1774
+ [
1775
+ "Requires",
1776
+ data.book.requires?.length
1777
+ ? chipList(ctx, data.book.requires, (item) => mono(ctx, item))
1778
+ : null,
1779
+ ],
1780
+ ]),
666
1781
  ]),
667
1782
  );
668
1783
  }
@@ -671,116 +1786,523 @@ async function pageView(ctx, app, key) {
671
1786
  return out;
672
1787
  }
673
1788
 
1789
+ /** The group a page or screen is listed under: the first segment of its route, or the top level. */
1790
+ function groupOf(row) {
1791
+ const segments = (row.route ?? row.id)
1792
+ .split("/")
1793
+ .filter((segment) => segment && !segment.startsWith(":") && !segment.startsWith("["));
1794
+ const first = segments[0]?.replace(/^\(.*\)$/, "") ?? "";
1795
+
1796
+ return segments.length > 1 && first ? first : "";
1797
+ }
1798
+
1799
+ function appIcon(ctx, type) {
1800
+ const { svg } = ctx;
1801
+ const common = {
1802
+ viewBox: "0 0 24 24",
1803
+ width: "22",
1804
+ height: "22",
1805
+ fill: "none",
1806
+ stroke: "currentColor",
1807
+ "stroke-width": "1.8",
1808
+ "stroke-linecap": "round",
1809
+ "stroke-linejoin": "round",
1810
+ "aria-hidden": "true",
1811
+ class: "grimoire-app-icon",
1812
+ };
1813
+
1814
+ return type === "mobile"
1815
+ ? svg("svg", common, [
1816
+ svg("rect", { x: "7", y: "2.5", width: "10", height: "19", rx: "2.2" }),
1817
+ svg("path", { d: "M11 18.5h2" }),
1818
+ ])
1819
+ : svg("svg", common, [
1820
+ svg("rect", { x: "3", y: "4", width: "18", height: "12", rx: "2" }),
1821
+ svg("path", { d: "M9 20h6M12 16v4" }),
1822
+ ]);
1823
+ }
1824
+
674
1825
  async function appsView(ctx) {
675
1826
  const data = await ctx.api("apps");
676
- if (!data.apps.length) return ctx.empty("No apps are written in grimoire/apps.");
677
- return ctx.el(
678
- "div",
679
- { class: "grimoire-view" },
680
- data.apps.map((app) =>
681
- section(ctx, `${app.id} (${app.type})`, [
682
- ctx.el("p", { class: "muted", text: app.root }),
683
- app.pages.length || app.screens.length
684
- ? list(
685
- ctx,
686
- [...app.pages, ...app.screens].map((id) => [
687
- link(ctx, id, `page/${encodeURIComponent(app.id)}/${encodeURIComponent(id)}`),
1827
+ const { el } = ctx;
1828
+
1829
+ if (!data.apps.length)
1830
+ return ctx.empty(
1831
+ "No apps are written in grimoire/apps. Ask your agent to write them (skill use-the-grimoire).",
1832
+ );
1833
+
1834
+ // Older answers list ids only.
1835
+ const rowsOf = (app) =>
1836
+ app.rows ?? [
1837
+ ...app.pages.map((id) => ({ id, type: "page" })),
1838
+ ...app.screens.map((id) => ({ id, type: "screen" })),
1839
+ ];
1840
+ const items = data.apps.flatMap((app) =>
1841
+ rowsOf(app).map((row) => ({
1842
+ route: null,
1843
+ heading: null,
1844
+ origin: null,
1845
+ layout: null,
1846
+ blocks: null,
1847
+ ...row,
1848
+ app: app.id,
1849
+ })),
1850
+ );
1851
+
1852
+ const renderApp = (app, rows, filtered) => {
1853
+ const own = items.filter((row) => row.app === app.id);
1854
+ const confirmed = own.filter((row) => row.origin === "confirmed").length;
1855
+ const inferred = own.filter((row) => row.origin === "inferred").length;
1856
+ const groups = new Map();
1857
+
1858
+ for (const row of rows) {
1859
+ const name = groupOf(row);
1860
+
1861
+ groups.set(name, [...(groups.get(name) ?? []), row]);
1862
+ }
1863
+
1864
+ return el("section", { class: "grimoire-card grimoire-app-card" }, [
1865
+ el("header", { class: "grimoire-app-head" }, [
1866
+ appIcon(ctx, app.type),
1867
+ el("h3", { text: app.id }),
1868
+ pill(ctx, app.type === "mobile" ? "mobile app" : "site"),
1869
+ mono(ctx, app.root),
1870
+ ]),
1871
+ el("p", { class: "grimoire-muted" }, [
1872
+ `${plural(app.pages.length, "page")}, ${plural(app.screens.length, "screen")}`,
1873
+ confirmed || inferred ? `; ${confirmed} confirmed, ${inferred} inferred` : "",
1874
+ filtered ? `; showing ${rows.length}` : "",
1875
+ ]),
1876
+ own.length
1877
+ ? [...groups.entries()]
1878
+ .sort(([a], [b]) => (a === "" ? -1 : b === "" ? 1 : a.localeCompare(b)))
1879
+ .map(([name, group]) =>
1880
+ el("div", { class: "grimoire-group" }, [
1881
+ el("h4", { text: `${name ? `/${name}` : "Top level"} (${group.length})` }),
1882
+ table(
1883
+ ctx,
1884
+ ["Page", "Route or screen", "Title", "Layout", "Blocks", "Status"],
1885
+ [...group]
1886
+ .sort((a, b) => (a.route ?? a.id).localeCompare(b.route ?? b.id))
1887
+ .map((row) => [
1888
+ [
1889
+ link(
1890
+ ctx,
1891
+ row.id,
1892
+ `page/${encodeURIComponent(app.id)}/${encodeURIComponent(row.id)}`,
1893
+ ),
1894
+ row.type === "screen" ? [" ", pill(ctx, "screen")] : "",
1895
+ ],
1896
+ [row.route ? mono(ctx, row.route) : ""],
1897
+ [row.heading ?? ""],
1898
+ [row.layout ?? ""],
1899
+ [row.blocks === null ? "" : String(row.blocks)],
1900
+ [
1901
+ row.origin
1902
+ ? pill(ctx, row.origin, toneOf(row.origin))
1903
+ : muted(ctx, "unmarked"),
1904
+ ],
1905
+ ]),
1906
+ ),
688
1907
  ]),
689
1908
  )
690
- : ctx.empty("No pages written."),
691
- ]),
692
- ),
693
- );
1909
+ : ctx.empty("No pages written."),
1910
+ ]);
1911
+ };
1912
+
1913
+ return el("div", { class: "grimoire-view" }, [
1914
+ heading(ctx, "Apps"),
1915
+ items.length
1916
+ ? listing(ctx, {
1917
+ items,
1918
+ noun: "pages and screens",
1919
+ placeholder: "Filter pages and screens",
1920
+ textOf: (row) => [row.app, row.id, row.route ?? "", row.heading ?? ""].join(" "),
1921
+ statusOf: (row) => row.origin ?? "unmarked",
1922
+ statusOrder: ["confirmed", "inferred", "unmarked"],
1923
+ render: (shown, all) =>
1924
+ el(
1925
+ "div",
1926
+ { class: "grimoire-app-list" },
1927
+ data.apps
1928
+ .filter(
1929
+ (app) => shown.length === all.length || shown.some((row) => row.app === app.id),
1930
+ )
1931
+ .map((app) =>
1932
+ renderApp(
1933
+ app,
1934
+ shown.filter((row) => row.app === app.id),
1935
+ shown.length !== all.length,
1936
+ ),
1937
+ ),
1938
+ ),
1939
+ })
1940
+ : el(
1941
+ "div",
1942
+ { class: "grimoire-app-list" },
1943
+ data.apps.map((app) => renderApp(app, [], false)),
1944
+ ),
1945
+ ]);
1946
+ }
1947
+
1948
+ /** One task's header facts. */
1949
+ function taskCard(ctx, task) {
1950
+ return section(ctx, task.id, [
1951
+ facts(ctx, [
1952
+ ["Title", codeText(ctx, task.title)],
1953
+ ["Type", task.type],
1954
+ ["Status", pill(ctx, task.status, toneOf(task.status))],
1955
+ [
1956
+ "Feature",
1957
+ task.feature
1958
+ ? link(ctx, task.feature, `feature/${encodeURIComponent(task.feature)}`)
1959
+ : null,
1960
+ ],
1961
+ ["Flow", task.feature && task.flow ? flowLink(ctx, `${task.feature}/${task.flow}`) : null],
1962
+ ["Apps", task.apps?.length ? task.apps.join(", ") : null],
1963
+ ["File", mono(ctx, task.file)],
1964
+ ["Decision needed", task.decisionNeeded ?? null],
1965
+ ["Shipped in", task.shipped ? `${task.shipped.feature} ${task.shipped.version}` : null],
1966
+ ]),
1967
+ ]);
694
1968
  }
695
1969
 
696
1970
  async function tasksView(ctx, only) {
697
1971
  const data = await ctx.api("tasks");
698
- // `waiting` is the part of `open` that waits for the owner: each task shows in one group only.
699
- const waiting = new Set(data.waiting.map((task) => task.id));
700
- const groups = [
701
- ["Open", data.open.filter((task) => !waiting.has(task.id))],
702
- ["Waiting for approval", data.waiting],
703
- ["Done", data.done],
704
- ]
705
- .map(([title, items]) => [title, only ? items.filter((task) => task.id === only) : items])
706
- .filter(([, items]) => items.length);
1972
+ const { el } = ctx;
1973
+
1974
+ if (only) {
1975
+ const task = [...data.open, ...data.waiting, ...data.done].find((item) => item.id === only);
707
1976
 
708
- if (!groups.length) {
709
- return ctx.empty(only ? `No task ${only}.` : "No tasks are written in grimoire/tasks.");
1977
+ return el("div", { class: "grimoire-view" }, [
1978
+ crumbs(ctx, [["Tasks", "tasks"], [only]]),
1979
+ task
1980
+ ? taskCard(ctx, task)
1981
+ : ctx.empty(`No task ${only}. Open the task list to see the ids that exist.`),
1982
+ ]);
710
1983
  }
711
1984
 
712
- return ctx.el(
713
- "div",
714
- { class: "grimoire-view" },
715
- groups.map(([title, items]) =>
716
- section(ctx, `${title} (${items.length})`, [
717
- table(
718
- ctx,
719
- ["Task", "Type", "Status", "Feature", "Title", "Decision needed"],
720
- items.map((task) => [
721
- [link(ctx, task.id, `task/${encodeURIComponent(task.id)}`)],
722
- [task.type],
723
- [badge(ctx, task.status)],
724
- [
725
- task.feature
726
- ? link(ctx, task.feature, `feature/${encodeURIComponent(task.feature)}`)
727
- : "",
728
- ],
729
- [task.title],
730
- [task.decisionNeeded ?? ""],
731
- ]),
1985
+ // `waiting` is the part of `open` that waits for the owner: each task shows in one group only.
1986
+ const waiting = new Set(data.waiting.map((task) => task.id));
1987
+ const groups = [
1988
+ ["open", "Open", data.open.filter((task) => !waiting.has(task.id))],
1989
+ ["waiting", "Waiting for approval", data.waiting],
1990
+ ["done", "Done", data.done],
1991
+ ];
1992
+ const items = groups.flatMap(([group, , tasks]) => tasks.map((task) => ({ ...task, group })));
1993
+
1994
+ if (!items.length) return ctx.empty("No tasks are written in grimoire/tasks.");
1995
+
1996
+ return el("div", { class: "grimoire-view" }, [
1997
+ heading(ctx, "Tasks"),
1998
+ listing(ctx, {
1999
+ items,
2000
+ noun: "tasks",
2001
+ textOf: (task) =>
2002
+ [task.id, task.title, task.type, task.feature ?? "", task.decisionNeeded ?? ""].join(" "),
2003
+ statusOf: (task) => task.group,
2004
+ statusOrder: ["open", "waiting", "done"],
2005
+ render: (shown) =>
2006
+ el(
2007
+ "div",
2008
+ { class: "grimoire-view-groups" },
2009
+ groups
2010
+ .map(([group, title]) => [title, shown.filter((task) => task.group === group), group])
2011
+ .filter(([, tasks]) => tasks.length)
2012
+ .map(([title, tasks, group]) =>
2013
+ section(ctx, `${title} (${tasks.length})`, [
2014
+ table(
2015
+ ctx,
2016
+ ["Task", "Title", "Type", "Status", "Feature", "Decision needed"],
2017
+ tasks.map((task) => [
2018
+ [
2019
+ link(ctx, task.id, `task/${encodeURIComponent(task.id)}`, {
2020
+ class: "grimoire-nowrap",
2021
+ }),
2022
+ ],
2023
+ [codeText(ctx, task.title)],
2024
+ [task.type],
2025
+ [pill(ctx, task.status, toneOf(group))],
2026
+ [
2027
+ task.feature
2028
+ ? link(ctx, task.feature, `feature/${encodeURIComponent(task.feature)}`)
2029
+ : "",
2030
+ ],
2031
+ [task.decisionNeeded ?? ""],
2032
+ ]),
2033
+ ),
2034
+ ]),
2035
+ ),
732
2036
  ),
733
- ]),
734
- ),
735
- );
2037
+ }),
2038
+ ]);
736
2039
  }
737
2040
 
738
2041
  async function releasesView(ctx) {
739
2042
  const data = await ctx.api("releases");
2043
+ const { el } = ctx;
2044
+
740
2045
  if (!data.releases.length) return ctx.empty("No releases are written in grimoire/releases.");
741
- return section(ctx, "Releases", [
742
- table(
743
- ctx,
744
- ["Release", "Date", "File"],
745
- data.releases.map((item) => [
746
- [link(ctx, item.release, `release/${encodeURIComponent(item.release)}`)],
747
- [item.date],
748
- [item.file],
749
- ]),
750
- ),
2046
+
2047
+ return el("div", { class: "grimoire-view" }, [
2048
+ heading(ctx, "Releases"),
2049
+ listing(ctx, {
2050
+ items: data.releases,
2051
+ noun: "releases",
2052
+ textOf: (item) => `${item.release} ${item.date} ${item.file}`,
2053
+ sorts: [
2054
+ ["newest", "newest first", (a, b) => b.date.localeCompare(a.date)],
2055
+ ["oldest", "oldest first", (a, b) => a.date.localeCompare(b.date)],
2056
+ ],
2057
+ render: (shown) =>
2058
+ section(ctx, "Releases", [
2059
+ table(
2060
+ ctx,
2061
+ ["Release", "Date", "File"],
2062
+ shown.map((item) => [
2063
+ [link(ctx, item.release, `release/${encodeURIComponent(item.release)}`)],
2064
+ [item.date],
2065
+ [mono(ctx, item.file)],
2066
+ ]),
2067
+ ),
2068
+ ]),
2069
+ }),
751
2070
  ]);
752
2071
  }
753
2072
 
754
2073
  async function releaseView(ctx, id) {
755
2074
  const data = await ctx.api(`releases/${encodeURIComponent(id)}`);
2075
+ const { el } = ctx;
756
2076
  const entries = data.collected?.entries ?? [];
757
- return ctx.el("div", { class: "grimoire-view" }, [
758
- ctx.el("h2", { text: `Release ${plain(data.release)} (${plain(data.date)})` }),
759
- data.brief ? ctx.el("p", { text: data.brief }) : "",
760
- section(ctx, "Collected entries", [
761
- entries.length
762
- ? list(
763
- ctx,
764
- entries.map((entry) => [
765
- `${entry.feature} ${entry.version}: ${entry.text ?? JSON.stringify(entry)}`,
766
- ]),
767
- )
768
- : ctx.empty("Nothing is listed for this release."),
2077
+ const byFeature = new Map();
2078
+
2079
+ for (const entry of entries)
2080
+ byFeature.set(entry.feature, [...(byFeature.get(entry.feature) ?? []), entry]);
2081
+
2082
+ return el("div", { class: "grimoire-view" }, [
2083
+ crumbs(ctx, [["Releases", "releases"], [`Release ${plain(data.release)}`]]),
2084
+ heading(ctx, `Release ${plain(data.release)}`, [muted(ctx, plain(data.date))]),
2085
+ data.brief ? el("p", { class: "grimoire-lede", text: data.brief }) : "",
2086
+ entries.length
2087
+ ? [...byFeature.entries()].map(([feature, items]) =>
2088
+ section(ctx, `${feature} (${items.length})`, [
2089
+ list(
2090
+ ctx,
2091
+ items.map((entry) => [
2092
+ `${entry.feature} ${entry.version}: ${entry.text ?? JSON.stringify(entry)}`,
2093
+ ]),
2094
+ ),
2095
+ ]),
2096
+ )
2097
+ : section(ctx, "Collected entries", [ctx.empty("Nothing is listed for this release.")]),
2098
+ ]);
2099
+ }
2100
+
2101
+ /** One link of a filter row; the active one is marked. */
2102
+ function filterLink(ctx, label, target, active) {
2103
+ return ctx.el("a", {
2104
+ href: ctx.href(target),
2105
+ class: active ? "grimoire-filter is-active" : "grimoire-filter",
2106
+ ...(active ? { "aria-current": "true" } : {}),
2107
+ text: label,
2108
+ });
2109
+ }
2110
+
2111
+ /** A select that opens the Check tab with one more filter set. */
2112
+ function filterSelect(ctx, label, key, options, query) {
2113
+ return ctx.el(
2114
+ "select",
2115
+ {
2116
+ class: "grimoire-sort",
2117
+ "aria-label": label,
2118
+ onchange: (event) => ctx.navigate(checkTarget({ ...query, [key]: event.target.value })),
2119
+ },
2120
+ [
2121
+ ctx.el("option", { value: "", text: `${label}: all` }),
2122
+ ...options.map((option) =>
2123
+ ctx.el("option", {
2124
+ value: option,
2125
+ text: option,
2126
+ ...(query[key] === option ? { selected: "selected" } : {}),
2127
+ }),
2128
+ ),
2129
+ ],
2130
+ );
2131
+ }
2132
+
2133
+ /** One code of the check: its title, the fix once, and its features with a count and "Show". */
2134
+ function checkGroupCard(ctx, group, mode, query) {
2135
+ const { el } = ctx;
2136
+ const count = mode === "expected" ? group.expected : group.count;
2137
+ const filter = { state: mode, ...(query.severity ? { severity: query.severity } : {}) };
2138
+ // Files no flow reaches are one finding per file: shown one row per feature, files on request.
2139
+ const perFeature = group.code === "GR3006";
2140
+ const features = group.features;
2141
+
2142
+ return el("section", { class: "grimoire-card grimoire-check-group" }, [
2143
+ el("header", { class: "grimoire-check-head" }, [
2144
+ pill(ctx, group.severity, mode === "expected" ? "" : toneOf(group.severity)),
2145
+ mono(ctx, group.code),
2146
+ el("h3", {}, codeText(ctx, group.title)),
2147
+ pill(ctx, String(count)),
769
2148
  ]),
2149
+ group.fix ? el("p", { class: "grimoire-muted" }, codeText(ctx, group.fix)) : "",
2150
+ features.length
2151
+ ? el(
2152
+ "ul",
2153
+ { class: "grimoire-check-features" },
2154
+ features.map((item) => {
2155
+ const shown = expander(ctx, perFeature ? "Show files" : "Show", () =>
2156
+ pagedFindings(
2157
+ ctx,
2158
+ { ...filter, code: group.code, ...(item.feature === "(none)" ? {} : { feature: item.feature }) },
2159
+ { hints: false },
2160
+ ),
2161
+ );
2162
+
2163
+ return el("li", { class: "grimoire-check-feature" }, [
2164
+ el("div", { class: "grimoire-check-feature-row" }, [
2165
+ item.feature === "(none)"
2166
+ ? muted(ctx, "no feature")
2167
+ : link(
2168
+ ctx,
2169
+ item.feature,
2170
+ checkTarget({ ...filter, code: group.code, feature: item.feature }),
2171
+ ),
2172
+ pill(ctx, plural(item.count, perFeature ? "file" : "finding")),
2173
+ shown.button,
2174
+ ]),
2175
+ shown.panel,
2176
+ ]);
2177
+ }),
2178
+ )
2179
+ : "",
2180
+ perFeature
2181
+ ? ""
2182
+ : (() => {
2183
+ const all = expander(ctx, `Show all ${count}`, () =>
2184
+ pagedFindings(ctx, { ...filter, code: group.code }, { hints: false }),
2185
+ );
2186
+
2187
+ return el("div", {}, [all.button, all.panel]);
2188
+ })(),
770
2189
  ]);
771
2190
  }
772
2191
 
773
- async function checkView(ctx) {
774
- const report = await ctx.api("check");
2192
+ async function checkView(ctx, query = {}) {
2193
+ const report = await ctx.api("check/groups");
775
2194
  const { counts } = report;
776
- return ctx.el("div", { class: "grimoire-view" }, [
777
- ctx.el("h2", { text: report.ok ? "Check: no unexpected errors" : "Check: errors found" }),
778
- ctx.el("p", {
779
- class: "muted",
780
- text: `${counts.errors} errors, ${counts.warnings} warnings, ${counts.expected} expected; routes ${report.routes}`,
2195
+ const { el } = ctx;
2196
+ const groups = report.groups ?? [];
2197
+ const kinds = groups.filter((group) => group.count > 0).length;
2198
+ const expectedMode = query.state === "expected";
2199
+ const matches = (group) =>
2200
+ (!query.code || group.code === query.code) &&
2201
+ (!query.severity || group.severity === query.severity) &&
2202
+ (!query.feature || group.features.some((item) => item.feature === query.feature));
2203
+ const main = expectedMode ? [] : groups.filter((group) => group.count > 0 && matches(group));
2204
+ const expected = groups.filter(
2205
+ (group) => group.expected > 0 && (expectedMode || group.count === 0) && matches(group),
2206
+ );
2207
+ const flat = Boolean(query.flow || query.feature);
2208
+ const names = [...new Set(groups.flatMap((group) => group.features.map((item) => item.feature)))]
2209
+ .filter((name) => name !== "(none)")
2210
+ .sort();
2211
+ const active = ["code", "feature", "flow", "severity", "state"].filter((key) => query[key]);
2212
+
2213
+ const out = el("div", { class: "grimoire-view" }, [
2214
+ heading(ctx, "Check", [
2215
+ pill(ctx, `${plural(counts.errors, "error")}`, counts.errors ? "bad" : "good"),
2216
+ pill(ctx, plural(counts.warnings, "warning"), counts.warnings ? "warn" : ""),
2217
+ pill(ctx, `${counts.expected} expected`),
2218
+ muted(ctx, `routes ${report.routes ?? "cached"}`),
2219
+ ]),
2220
+ el("p", {
2221
+ class: "grimoire-headline",
2222
+ text: `${plural(counts.errors, "error")} · ${plural(counts.warnings, "warning")} in ${plural(kinds, "kind")}`,
781
2223
  }),
782
- report.findings.length ? findingsView(ctx, report.findings) : ctx.empty("No findings."),
2224
+ el("div", { class: "grimoire-toolbar grimoire-check-filters" }, [
2225
+ el("div", { class: "grimoire-filters", role: "group", "aria-label": "Severity" }, [
2226
+ filterLink(ctx, "all", checkTarget({ ...query, severity: "" }), !query.severity),
2227
+ filterLink(ctx, "errors", checkTarget({ ...query, severity: "error" }), query.severity === "error"),
2228
+ filterLink(ctx, "warnings", checkTarget({ ...query, severity: "warning" }), query.severity === "warning"),
2229
+ ]),
2230
+ el("div", { class: "grimoire-filters", role: "group", "aria-label": "State" }, [
2231
+ filterLink(ctx, "to fix", checkTarget({ ...query, state: "" }), !query.state),
2232
+ filterLink(ctx, "expected", checkTarget({ ...query, state: "expected" }), expectedMode),
2233
+ ]),
2234
+ filterSelect(ctx, "Code", "code", groups.map((group) => group.code), query),
2235
+ filterSelect(ctx, "Feature", "feature", names, query),
2236
+ ]),
2237
+ active.some((key) => key === "code" || key === "feature" || key === "flow")
2238
+ ? el(
2239
+ "div",
2240
+ { class: "grimoire-chips" },
2241
+ ["code", "feature", "flow"]
2242
+ .filter((key) => query[key])
2243
+ .map((key) =>
2244
+ link(ctx, `${key}: ${query[key]} ×`, checkTarget({ ...query, [key]: "" }), {
2245
+ class: "grimoire-chip",
2246
+ title: `Clear the ${key} filter`,
2247
+ }),
2248
+ ),
2249
+ )
2250
+ : "",
783
2251
  ]);
2252
+
2253
+ if (flat) {
2254
+ out.append(
2255
+ section(ctx, "Findings", [
2256
+ pagedFindings(
2257
+ ctx,
2258
+ {
2259
+ code: query.code,
2260
+ feature: query.feature,
2261
+ flow: query.flow,
2262
+ severity: query.severity,
2263
+ state: query.state ?? "unexpected",
2264
+ },
2265
+ { size: 50 },
2266
+ ),
2267
+ ]),
2268
+ );
2269
+ return out;
2270
+ }
2271
+
2272
+ if (!main.length && !expected.length) {
2273
+ out.append(
2274
+ ctx.empty(
2275
+ active.length
2276
+ ? "No findings match these filters. Clear a filter to see more."
2277
+ : "No findings. The written files and the code agree.",
2278
+ ),
2279
+ );
2280
+ return out;
2281
+ }
2282
+
2283
+ if (main.length) {
2284
+ out.append(
2285
+ el("div", { class: "grimoire-view-groups" }, [
2286
+ el("h3", { class: "grimoire-subhead", text: `To fix (${plural(main.length, "kind")})` }),
2287
+ ...main.map((group) => checkGroupCard(ctx, group, "unexpected", query)),
2288
+ ]),
2289
+ );
2290
+ }
2291
+
2292
+ if (expected.length) {
2293
+ out.append(
2294
+ el("div", { class: "grimoire-view-groups" }, [
2295
+ el("h3", { class: "grimoire-subhead", text: `Expected: proposed work (${plural(expected.length, "kind")})` }),
2296
+ el("p", {
2297
+ class: "grimoire-muted",
2298
+ text: "These concern features or flows that are still proposed, so the code does not exist yet. They never fail the check.",
2299
+ }),
2300
+ ...expected.map((group) => checkGroupCard(ctx, group, "expected", query)),
2301
+ ]),
2302
+ );
2303
+ }
2304
+
2305
+ return out;
784
2306
  }
785
2307
 
786
2308
  async function fileView(ctx, path) {
@@ -791,34 +2313,47 @@ async function fileView(ctx, path) {
791
2313
  const { el } = ctx;
792
2314
  const entry = data.entry;
793
2315
  const out = el("div", { class: "grimoire-view" }, [
794
- el("h2", { text: entry.file }),
795
- el("p", { class: "muted", text: `${entry.type} in ${entry.module}, ${entry.lines} lines` }),
2316
+ crumbs(ctx, [["Modules", "modules"], [entry.file]]),
2317
+ heading(ctx, entry.file, [
2318
+ pill(ctx, entry.type),
2319
+ mono(ctx, entry.module),
2320
+ muted(ctx, `${entry.lines} lines`),
2321
+ ]),
796
2322
  ]);
797
- if (entry.about) out.append(el("p", { text: entry.about }));
798
-
799
- const owner = [];
800
- if (entry.feature)
801
- owner.push(
802
- "Owned by ",
803
- link(ctx, entry.feature, `feature/${encodeURIComponent(entry.feature)}`),
804
- ". ",
805
- );
806
- if (entry.borrowedBy.length) owner.push("Borrowed by ", entry.borrowedBy.join(", "), ". ");
807
- if (entry.flows.length)
808
- owner.push("Used by flows: ", ...entry.flows.flatMap((flow) => [flowLink(ctx, flow), " "]));
809
- if (owner.length) out.append(el("p", {}, owner));
2323
+ if (entry.about) out.append(el("p", { class: "grimoire-lede", text: entry.about }));
810
2324
 
811
2325
  out.append(
2326
+ section(ctx, "Who uses it", [
2327
+ facts(ctx, [
2328
+ [
2329
+ "Owned by",
2330
+ entry.feature
2331
+ ? link(ctx, entry.feature, `feature/${encodeURIComponent(entry.feature)}`)
2332
+ : null,
2333
+ ],
2334
+ ["Borrowed by", entry.borrowedBy.length ? entry.borrowedBy.join(", ") : null],
2335
+ [
2336
+ "Used by flows",
2337
+ entry.flows.length
2338
+ ? el(
2339
+ "span",
2340
+ {},
2341
+ entry.flows.flatMap((flow) => [flowLink(ctx, flow), " "]),
2342
+ )
2343
+ : null,
2344
+ ],
2345
+ ]),
2346
+ ]),
812
2347
  section(ctx, "Exports", [
813
2348
  entry.exports.length
814
2349
  ? list(
815
2350
  ctx,
816
- entry.exports.map((item) => [`${item.name}${item.about ? `: ${item.about}` : ""}`]),
2351
+ entry.exports.map((item) => [mono(ctx, item.name), item.about ? ` ${item.about}` : ""]),
817
2352
  )
818
- : el("span", { class: "muted", text: "none" }),
2353
+ : muted(ctx, "none"),
819
2354
  ]),
820
- section(ctx, "Imports", [fileList(ctx, entry.imports, 20)]),
821
- section(ctx, "Imported by", [fileList(ctx, entry.importedBy, 20)]),
2355
+ section(ctx, "Imports", [fileChips(ctx, entry.imports, 20)]),
2356
+ section(ctx, "Imported by", [fileChips(ctx, entry.importedBy, 20)]),
822
2357
  );
823
2358
 
824
2359
  if (entry.routes.length) {
@@ -826,14 +2361,7 @@ async function fileView(ctx, path) {
826
2361
  section(ctx, "Routes", [
827
2362
  list(
828
2363
  ctx,
829
- entry.routes.map((item) => [
830
- link(
831
- ctx,
832
- `${item.method} ${item.path}`,
833
- `route/${encodeURIComponent(item.method)}/${encodeURIComponent(item.path)}`,
834
- ),
835
- ` (${item.via})`,
836
- ]),
2364
+ entry.routes.map((item) => [routeLink(ctx, item.method, item.path), ` (${item.via})`]),
837
2365
  ),
838
2366
  ]),
839
2367
  );
@@ -850,19 +2378,19 @@ async function routeView(ctx, method, path) {
850
2378
  const { el } = ctx;
851
2379
  const found = data.route;
852
2380
  const out = el("div", { class: "grimoire-view" }, [
853
- el("h2", { text: `${found.method} ${found.path}` }),
854
- el("p", { class: "muted", text: found.description ?? found.handler }),
2381
+ crumbs(ctx, [["Modules", "modules"], [`${found.method} ${found.path}`]]),
2382
+ heading(ctx, `${found.method} ${found.path}`, [muted(ctx, found.description ?? found.handler)]),
855
2383
  ]);
856
2384
  if (found.handlerFile) out.append(el("p", {}, ["Handler: ", fileLink(ctx, found.handlerFile)]));
857
2385
  out.append(
858
- section(ctx, "Files behind it", [fileList(ctx, data.files, 20)]),
2386
+ section(ctx, "Files behind it", [fileChips(ctx, data.files, 20)]),
859
2387
  section(ctx, "Flow steps", [
860
2388
  data.steps.length
861
2389
  ? list(
862
2390
  ctx,
863
2391
  data.steps.map((step) => [flowLink(ctx, step.flow), ` step ${step.index}`]),
864
2392
  )
865
- : el("span", { class: "muted", text: "none" }),
2393
+ : muted(ctx, "none"),
866
2394
  ]),
867
2395
  );
868
2396
  return out;
@@ -870,22 +2398,80 @@ async function routeView(ctx, method, path) {
870
2398
 
871
2399
  async function modulesView(ctx) {
872
2400
  const graph = await ctx.api("graph/modules");
873
- return ctx.el("div", { class: "grimoire-view" }, [
874
- ctx.el("h2", { text: "Module coupling" }),
875
- ctx.el("p", {
876
- class: "muted",
2401
+ const { el } = ctx;
2402
+ const weight = new Map();
2403
+
2404
+ for (const edge of graph.edges) {
2405
+ for (const end of [edge.from, edge.to])
2406
+ weight.set(end, (weight.get(end) ?? 0) + (edge.weight ?? 1));
2407
+ }
2408
+
2409
+ const items = graph.nodes.map((node) => ({ label: node.label, links: weight.get(node.id) ?? 0 }));
2410
+
2411
+ return el("div", { class: "grimoire-view" }, [
2412
+ heading(ctx, "Module coupling"),
2413
+ el("p", {
2414
+ class: "grimoire-muted",
877
2415
  text: "Lines are imports between modules; thicker means more imports. The most connected modules are drawn.",
878
2416
  }),
879
2417
  graphView(ctx, graph, "Modules"),
2418
+ items.length
2419
+ ? listing(ctx, {
2420
+ items,
2421
+ noun: "modules",
2422
+ textOf: (item) => item.label,
2423
+ sorts: [
2424
+ [
2425
+ "links",
2426
+ "most imports",
2427
+ (a, b) => b.links - a.links || a.label.localeCompare(b.label),
2428
+ ],
2429
+ ["name", "name", (a, b) => a.label.localeCompare(b.label)],
2430
+ ],
2431
+ render: (shown) =>
2432
+ section(ctx, "Modules", [
2433
+ table(
2434
+ ctx,
2435
+ ["Module", "Imports to and from"],
2436
+ shown.map((item) => [[mono(ctx, item.label)], [String(item.links)]]),
2437
+ ),
2438
+ ]),
2439
+ })
2440
+ : "",
880
2441
  ]);
881
2442
  }
882
2443
 
2444
+ // ── Shell ───────────────────────────────────────────────────────────────────
2445
+
2446
+ /**
2447
+ * An asset URL `import()` accepts. A host may hand out a page-relative path
2448
+ * (`panels/grimoire/x.js`), which `import()` reads as a bare module specifier
2449
+ * and refuses; resolve it against the page first.
2450
+ */
2451
+ function moduleUrl(url) {
2452
+ const base = globalThis.document?.baseURI ?? globalThis.location?.href;
2453
+
2454
+ try {
2455
+ return base ? new URL(url, base).href : url;
2456
+ } catch {
2457
+ return url;
2458
+ }
2459
+ }
2460
+
883
2461
  /** Pick the view for the hash route. */
884
- async function body(ctx) {
885
- const parts = ctx.route ? ctx.route.split("/").map(decodeSegment) : [];
2462
+ async function body(ctx, summaryRequest) {
2463
+ const { path, query } = parseRoute(ctx.route ?? "");
2464
+ const parts = path ? path.split("/").map(decodeSegment) : [];
886
2465
  const [type = "", first = "", second = ""] = parts;
887
2466
 
888
2467
  switch (type) {
2468
+ case "product": {
2469
+ const map = globalThis.grimoireProductMap ?? (await import(/* @vite-ignore */ moduleUrl(ctx.asset("product-map.js"))));
2470
+
2471
+ return map.productMapView(ctx, parts.slice(1));
2472
+ }
2473
+ case "features":
2474
+ return featuresView(ctx);
889
2475
  case "feature":
890
2476
  return featureView(ctx, first);
891
2477
  case "flow":
@@ -903,7 +2489,7 @@ async function body(ctx) {
903
2489
  case "release":
904
2490
  return releaseView(ctx, first);
905
2491
  case "check":
906
- return checkView(ctx);
2492
+ return checkView(ctx, query);
907
2493
  case "file":
908
2494
  return fileView(ctx, first);
909
2495
  case "route":
@@ -911,67 +2497,317 @@ async function body(ctx) {
911
2497
  case "modules":
912
2498
  return modulesView(ctx);
913
2499
  default:
914
- return homeView(ctx);
2500
+ return overviewView(ctx, summaryRequest);
915
2501
  }
916
2502
  }
917
2503
 
918
- /** The header: navigation and the one search box. Results appear under the box. */
919
- function header(ctx) {
2504
+ /** What the view is about, for error messages, and the list to go back to. */
2505
+ function describe(route) {
2506
+ const type = (route.split("?")[0] ?? "").split("/")[0] ?? "";
2507
+ const map = {
2508
+ product: ["the product map", null],
2509
+ features: ["the features", null],
2510
+ feature: ["the feature", ["Features", "features"]],
2511
+ flow: ["the flow", ["Features", "features"]],
2512
+ apps: ["the apps", null],
2513
+ page: ["the page", ["Apps", "apps"]],
2514
+ tasks: ["the tasks", null],
2515
+ task: ["the task", ["Tasks", "tasks"]],
2516
+ releases: ["the releases", null],
2517
+ release: ["the release", ["Releases", "releases"]],
2518
+ check: ["the check report", null],
2519
+ modules: ["the module graph", null],
2520
+ file: ["the file", ["Modules", "modules"]],
2521
+ route: ["the route", ["Modules", "modules"]],
2522
+ };
2523
+
2524
+ return map[type] ?? ["the overview", null];
2525
+ }
2526
+
2527
+ /** The loading state: shown at once, so a large book never leaves a blank area. */
2528
+ function skeleton(ctx) {
2529
+ const { el } = ctx;
2530
+
2531
+ return el("div", { class: "grimoire-skeleton", role: "status" }, [
2532
+ el("p", { class: "grimoire-skeleton-title", text: "Opening the book…" }),
2533
+ el("p", {
2534
+ class: "grimoire-muted",
2535
+ text: "A large book can take a few seconds to open the first time.",
2536
+ }),
2537
+ el(
2538
+ "div",
2539
+ { class: "grimoire-skeleton-grid", "aria-hidden": "true" },
2540
+ [1, 2, 3, 4, 5, 6].map(() => el("div", { class: "grimoire-skeleton-block" })),
2541
+ ),
2542
+ ]);
2543
+ }
2544
+
2545
+ /** A failed view: what failed, why, what to do, and a way to try again. */
2546
+ function errorBox(ctx, route, error) {
2547
+ const { el } = ctx;
2548
+ const [what, back] = describe(route);
2549
+ const message = error && error.message ? error.message : String(error);
2550
+ const needsApp = message.includes("running app");
2551
+
2552
+ return el("div", { class: "grimoire-error", role: "alert" }, [
2553
+ el("p", { class: "grimoire-error-title", text: `Could not load ${what}: ${message}` }),
2554
+ el("p", {
2555
+ class: "grimoire-muted",
2556
+ text: needsApp
2557
+ ? "Open the Grimoire tab in the devtools dashboard to see this answer."
2558
+ : back
2559
+ ? `It may have been renamed or removed. Go back to the list, or run warlock grimoire build and reload.`
2560
+ : BUILD_HINT,
2561
+ }),
2562
+ el("p", {}, [
2563
+ el("button", {
2564
+ type: "button",
2565
+ class: "grimoire-filter",
2566
+ text: "Try again",
2567
+ onclick: () => ctx.refresh(),
2568
+ }),
2569
+ back ? [" ", link(ctx, `Back to ${back[0]}`, back[1])] : "",
2570
+ ]),
2571
+ ]);
2572
+ }
2573
+
2574
+ let shortcutHandler = null;
2575
+
2576
+ /** `/` focuses the search box from anywhere that is not a text field; the newest view owns the key. */
2577
+ function bindShortcut(input) {
2578
+ if (typeof document === "undefined" || typeof document.addEventListener !== "function") return;
2579
+ if (shortcutHandler) document.removeEventListener("keydown", shortcutHandler);
2580
+
2581
+ shortcutHandler = (event) => {
2582
+ if (event.key !== "/" || event.metaKey || event.ctrlKey || event.altKey) return;
2583
+
2584
+ const target = event.target;
2585
+ const tag = target && target.tagName;
2586
+
2587
+ if (
2588
+ tag === "INPUT" ||
2589
+ tag === "TEXTAREA" ||
2590
+ tag === "SELECT" ||
2591
+ (target && target.isContentEditable)
2592
+ )
2593
+ return;
2594
+ if (!input.isConnected) return;
2595
+
2596
+ event.preventDefault();
2597
+ input.focus();
2598
+ };
2599
+ document.addEventListener("keydown", shortcutHandler);
2600
+ }
2601
+
2602
+ /** The header: the tabs and the one search box. Results appear under the box, grouped by type. */
2603
+ function header(ctx, route, summaryRequest) {
920
2604
  const { el } = ctx;
921
2605
  const results = el("div", { class: "grimoire-results" });
2606
+ const active = tabOf(route);
2607
+ const badges = new Map();
2608
+ let activeTab = null;
922
2609
  let token = 0;
923
2610
  let timer = null;
2611
+ let rows = [];
2612
+ let current = -1;
2613
+
2614
+ function highlight(index) {
2615
+ current = index;
2616
+ rows.forEach((row, position) => {
2617
+ row.node.setAttribute(
2618
+ "class",
2619
+ position === index ? "grimoire-hit is-active" : "grimoire-hit",
2620
+ );
2621
+ row.node.setAttribute("aria-selected", String(position === index));
2622
+ });
2623
+ if (rows[index]) {
2624
+ input.setAttribute("aria-activedescendant", `grimoire-hit-${index}`);
2625
+ rows[index].node.scrollIntoView?.({ block: "nearest" });
2626
+ }
2627
+ }
2628
+
2629
+ function clear() {
2630
+ token += 1;
2631
+ rows = [];
2632
+ current = -1;
2633
+ results.replaceChildren();
2634
+ input.setAttribute("aria-expanded", "false");
2635
+ input.removeAttribute?.("aria-activedescendant");
2636
+ }
924
2637
 
925
2638
  async function run(text) {
926
2639
  const mine = ++token;
927
- results.replaceChildren?.();
928
- if (!text.trim()) return;
2640
+ rows = [];
2641
+ current = -1;
2642
+ results.replaceChildren();
2643
+ if (!text.trim()) {
2644
+ input.setAttribute("aria-expanded", "false");
2645
+ return;
2646
+ }
2647
+ input.setAttribute("aria-expanded", "true");
929
2648
  try {
930
2649
  const answer = await ctx.api(`search?q=${encodeURIComponent(text.trim())}&limit=15`);
931
2650
  if (mine !== token) return;
932
- results.replaceChildren?.();
2651
+ results.replaceChildren();
933
2652
  if (!answer.hits.length) {
934
- results.append(ctx.empty(`Nothing matches "${text.trim()}".`));
2653
+ results.append(
2654
+ ctx.empty(
2655
+ `Nothing matches "${text.trim()}". Try a shorter word, or a file or route name.`,
2656
+ ),
2657
+ );
935
2658
  return;
936
2659
  }
937
- results.append(
938
- list(
939
- ctx,
940
- answer.hits.map((hit) => {
941
- const target = targetOf(hit.type, hit.id);
942
- return [
943
- badge(ctx, hit.type),
944
- " ",
945
- target === null ? hit.id : link(ctx, hit.id, target),
946
- hit.detail ? el("span", { class: "muted", text: ` ${hit.detail}` }) : "",
947
- ];
948
- }),
949
- ),
950
- );
2660
+
2661
+ const groups = new Map();
2662
+
2663
+ for (const hit of answer.hits) groups.set(hit.type, [...(groups.get(hit.type) ?? []), hit]);
2664
+
2665
+ for (const [type, hits] of groups) {
2666
+ const group = el(
2667
+ "div",
2668
+ { class: "grimoire-hit-group", role: "group", "aria-label": type },
2669
+ [
2670
+ el("p", {
2671
+ class: "grimoire-hit-title",
2672
+ "aria-hidden": "true",
2673
+ text: `${type} (${hits.length})`,
2674
+ }),
2675
+ ],
2676
+ );
2677
+
2678
+ for (const hit of hits) {
2679
+ const target = targetOf(hit.type, hit.id);
2680
+ const inner = [
2681
+ pill(ctx, hit.type),
2682
+ mono(ctx, hit.id),
2683
+ hit.detail ? muted(ctx, hit.detail) : "",
2684
+ ];
2685
+
2686
+ if (target === null) {
2687
+ group.append(el("div", { class: "grimoire-hit is-plain" }, inner));
2688
+ continue;
2689
+ }
2690
+
2691
+ const node = el(
2692
+ "a",
2693
+ {
2694
+ href: ctx.href(target),
2695
+ class: "grimoire-hit",
2696
+ role: "option",
2697
+ id: `grimoire-hit-${rows.length}`,
2698
+ "aria-selected": "false",
2699
+ },
2700
+ inner,
2701
+ );
2702
+
2703
+ rows.push({ node, target });
2704
+ group.append(node);
2705
+ }
2706
+
2707
+ results.append(group);
2708
+ }
951
2709
  } catch (error) {
952
2710
  if (mine === token)
953
- results.append(el("p", { class: "error", text: `Search failed: ${error.message}` }));
2711
+ results.append(
2712
+ el("p", {
2713
+ class: "grimoire-error-title",
2714
+ text: `Search failed: ${error.message}. Run warlock grimoire build, then search again.`,
2715
+ }),
2716
+ );
954
2717
  }
955
2718
  }
956
2719
 
957
2720
  const input = el("input", {
958
2721
  type: "search",
959
2722
  class: "grimoire-search",
960
- placeholder: "Search flows, blocks, routes, files and tasks",
2723
+ role: "combobox",
2724
+ placeholder: "Search flows, blocks, routes, files and tasks (press /)",
961
2725
  "aria-label": "Search the Grimoire",
2726
+ "aria-autocomplete": "list",
2727
+ "aria-expanded": "false",
2728
+ autocomplete: "off",
962
2729
  oninput: (event) => {
963
2730
  const text = event.target.value;
964
2731
  if (timer !== null) clearTimeout(timer);
965
2732
  timer = setTimeout(() => run(text), 150);
966
2733
  },
2734
+ onkeydown: (event) => {
2735
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
2736
+ if (!rows.length) return;
2737
+ event.preventDefault?.();
2738
+ const step = event.key === "ArrowDown" ? 1 : -1;
2739
+ highlight((current + step + rows.length) % rows.length);
2740
+ } else if (event.key === "Enter") {
2741
+ const row = rows[current] ?? rows[0];
2742
+ if (!row) return;
2743
+ event.preventDefault?.();
2744
+ ctx.navigate(row.target);
2745
+ } else if (event.key === "Escape") {
2746
+ if (timer !== null) clearTimeout(timer);
2747
+ input.value = "";
2748
+ clear();
2749
+ }
2750
+ },
967
2751
  });
2752
+
968
2753
  const nav = el(
969
2754
  "nav",
970
- { class: "grimoire-nav" },
971
- NAV.map(([target, label]) => link(ctx, label, target)),
2755
+ { class: "grimoire-tabs", "aria-label": "Grimoire" },
2756
+ TABS.map(([target, label]) => {
2757
+ const badge = el("span", { class: "grimoire-tab-count" });
2758
+
2759
+ badges.set(target, badge);
2760
+
2761
+ const tab = el(
2762
+ "a",
2763
+ {
2764
+ href: ctx.href(target),
2765
+ class: target === active ? "grimoire-tab is-active" : "grimoire-tab",
2766
+ ...(target === active ? { "aria-current": "page" } : {}),
2767
+ },
2768
+ [label, " ", badge],
2769
+ );
2770
+
2771
+ if (target === active) activeTab = tab;
2772
+
2773
+ return tab;
2774
+ }),
2775
+ );
2776
+
2777
+ bindShortcut(input);
2778
+
2779
+ // The counts arrive with the summary; a view that does not need it still shows them.
2780
+ summaryRequest.then(
2781
+ (data) => {
2782
+ const set = (key, value) => {
2783
+ const badge = badges.get(key);
2784
+ if (badge && value !== undefined && value !== null) badge.textContent = String(value);
2785
+ };
2786
+ set("features", data.features?.features?.length);
2787
+ set("apps", data.apps?.apps);
2788
+ set("tasks", data.tasks ? data.tasks.open.length : undefined);
2789
+ set("releases", data.releases);
2790
+ set("check", data.counts ? data.counts.errors + data.counts.warnings : undefined);
2791
+ },
2792
+ () => undefined,
972
2793
  );
973
2794
 
974
- return { element: el("div", { class: "grimoire-header" }, [nav, input, results]), run, input };
2795
+ return {
2796
+ element: el("div", { class: "grimoire-header" }, [
2797
+ nav,
2798
+ el("div", { class: "grimoire-searchbox" }, [input, results]),
2799
+ ]),
2800
+ run,
2801
+ input,
2802
+ /** Bring the open tab into view in a scrolling tab bar (phones). */
2803
+ revealActive: () => {
2804
+ try {
2805
+ activeTab?.scrollIntoView?.({ inline: "center", block: "nearest" });
2806
+ } catch {
2807
+ // A host without scrollIntoView options keeps the bar where it is.
2808
+ }
2809
+ },
2810
+ };
975
2811
  }
976
2812
 
977
2813
  /** The context with `el()` flattening nested child lists and skipping empty ones. */
@@ -988,17 +2824,36 @@ function withFlatChildren(context) {
988
2824
  async function renderGrimoire(context) {
989
2825
  const ctx = withFlatChildren(context);
990
2826
  const { root, el } = ctx;
2827
+ const route = ctx.route ?? "";
2828
+
991
2829
  if (typeof ctx.asset === "function")
992
2830
  root.append(el("link", { rel: "stylesheet", href: ctx.asset("grimoire.css") }));
993
- const top = header(ctx);
994
- const content = el("div", { class: "grimoire-body" });
995
- root.append(top.element, content);
996
2831
 
997
- try {
998
- content.append(await body(ctx));
999
- } catch (error) {
1000
- content.append(el("p", { class: "error", text: `Could not load this view: ${error.message}` }));
1001
- }
2832
+ // The tab counts and the overview share one summary request.
2833
+ const summaryRequest = Promise.resolve().then(() => ctx.api("summary"));
2834
+
2835
+ summaryRequest.catch(() => undefined);
2836
+
2837
+ const top = header(ctx, route, summaryRequest);
2838
+ const content = el("div", { class: "grimoire-body", "aria-busy": "true" });
2839
+
2840
+ content.append(skeleton(ctx));
2841
+ root.append(el("div", { class: "grimoire-root" }, [top.element, content]));
2842
+ top.revealActive();
2843
+
2844
+ const loaded = (async () => {
2845
+ try {
2846
+ content.replaceChildren(await body(ctx, summaryRequest));
2847
+ } catch (error) {
2848
+ content.replaceChildren(errorBox(ctx, route, error));
2849
+ }
2850
+ content.setAttribute("aria-busy", "false");
2851
+ })();
2852
+
2853
+ // A quick answer is shown filled in; a slow one hands back the skeleton at once and fills in later.
2854
+ await (typeof setTimeout === "function"
2855
+ ? Promise.race([loaded, new Promise((resolve) => setTimeout(resolve, SKELETON_AFTER))])
2856
+ : loaded);
1002
2857
  return root;
1003
2858
  }
1004
2859