@venizia/vulcan 0.4.8 → 0.4.9-1

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 (179) hide show
  1. package/base/extensions/vulcan-guards.ts +48 -41
  2. package/base/hooks/antigravity-guards.ts +4 -3
  3. package/base/hooks/codex-guards.ts +17 -6
  4. package/base/hooks/guard-git.ts +8 -8
  5. package/base/hooks/guard-manifest.ts +5 -5
  6. package/base/hooks/guard-outside.ts +8 -8
  7. package/base/hooks/guard-package.ts +6 -6
  8. package/base/hooks/guard-remote-hosts.ts +14 -9
  9. package/base/hooks/guard-scripting.ts +6 -6
  10. package/base/hooks/guard-writes.ts +20 -11
  11. package/base/hooks/post-tool.ts +4 -3
  12. package/base/hooks/prompt-submit.ts +4 -3
  13. package/base/hooks/session-start.ts +5 -3
  14. package/base/hooks/stop.ts +4 -3
  15. package/base/hooks/subagent-start.ts +2 -2
  16. package/base/make/vulcan.mk +1 -4
  17. package/base/skills/build-a-feature/SKILL.md +1 -1
  18. package/base/skills/docs-update/SKILL.md +11 -5
  19. package/base/skills/docs-update/evals/evals.json +1 -1
  20. package/base/skills/docs-writing/SKILL.md +1 -1
  21. package/base/skills/plan-a-change/references/spec-card.md +1 -1
  22. package/base/skills/ship/SKILL.md +1 -1
  23. package/base/skills/visualize-work/SKILL.md +29 -6
  24. package/base/skills/visualize-work/references/spec.md +16 -5
  25. package/package.json +5 -6
  26. package/src/agents/atlas-block.ts +43 -43
  27. package/src/agents/codex-hooks.ts +55 -52
  28. package/src/agents/common/types.ts +1 -1
  29. package/src/agents/detect.ts +19 -16
  30. package/src/agents/exclude.ts +97 -98
  31. package/src/agents/hooks-json.ts +41 -43
  32. package/src/agents/local.ts +46 -43
  33. package/src/agents/prompt.ts +45 -42
  34. package/src/agents/render.ts +203 -201
  35. package/src/agents/resolve.ts +133 -134
  36. package/src/agents/table.ts +12 -8
  37. package/src/cli.ts +3 -1
  38. package/src/commands/add.command.ts +2 -2
  39. package/src/commands/agents.command.ts +11 -17
  40. package/src/commands/clean.command.ts +6 -6
  41. package/src/commands/doctor.command.ts +6 -4
  42. package/src/commands/help.command.ts +11 -9
  43. package/src/commands/init.command.ts +14 -8
  44. package/src/commands/preset.command.ts +2 -2
  45. package/src/commands/profile.command.ts +43 -50
  46. package/src/commands/sync.command.ts +109 -111
  47. package/src/commands/upgrade.command.ts +85 -78
  48. package/src/commands/visualize.command.ts +20 -5
  49. package/src/commands/x.command.ts +55 -50
  50. package/src/common/format.ts +23 -21
  51. package/src/common/index.ts +2 -0
  52. package/src/common/json.ts +8 -5
  53. package/src/common/layout-folder.ts +96 -111
  54. package/src/common/paths.ts +14 -12
  55. package/src/common/record.ts +7 -0
  56. package/src/common/text.ts +7 -0
  57. package/src/config/common/constants.ts +13 -1
  58. package/src/config/common/types.ts +8 -1
  59. package/src/config/loader.ts +53 -48
  60. package/src/config/packages.ts +17 -11
  61. package/src/config/schema.ts +54 -7
  62. package/src/create/add-app.ts +604 -493
  63. package/src/create/add-lib.ts +249 -242
  64. package/src/create/bunfig.ts +26 -23
  65. package/src/create/checks.ts +36 -34
  66. package/src/create/common/constants.ts +1 -0
  67. package/src/create/common/failure.ts +10 -0
  68. package/src/create/common/index.ts +2 -0
  69. package/src/create/common/preset-path.ts +11 -0
  70. package/src/create/common/types.ts +7 -2
  71. package/src/create/diff.ts +21 -23
  72. package/src/create/dockerignore.ts +26 -24
  73. package/src/create/files.ts +7 -5
  74. package/src/create/init-monorepo.ts +78 -80
  75. package/src/create/lib-preset.ts +62 -61
  76. package/src/create/manifest-json.ts +10 -4
  77. package/src/create/names.ts +217 -210
  78. package/src/create/next.ts +27 -24
  79. package/src/create/plan.ts +15 -12
  80. package/src/create/preset-diff.ts +415 -240
  81. package/src/create/preset-menu.ts +40 -34
  82. package/src/create/preset.ts +207 -194
  83. package/src/create/process.ts +80 -71
  84. package/src/create/scratch.ts +49 -48
  85. package/src/create/workspace.ts +423 -398
  86. package/src/doctor/checks.ts +1069 -998
  87. package/src/doctor/makefile.ts +17 -13
  88. package/src/doctor/runner.ts +88 -116
  89. package/src/doctor/skills.ts +97 -95
  90. package/src/doctor/tags.ts +44 -41
  91. package/src/hooks/codex-patch.ts +27 -24
  92. package/src/hooks/command-view.ts +44 -39
  93. package/src/hooks/common/constants.ts +0 -3
  94. package/src/hooks/common/types.ts +15 -1
  95. package/src/hooks/decision.ts +38 -42
  96. package/src/hooks/guard-git.ts +52 -50
  97. package/src/hooks/guard-manifest.ts +58 -55
  98. package/src/hooks/guard-outside.ts +109 -88
  99. package/src/hooks/guard-package.ts +86 -77
  100. package/src/hooks/guard-scripting.ts +20 -15
  101. package/src/hooks/guard-writes.ts +169 -111
  102. package/src/hooks/owner-reply.ts +128 -128
  103. package/src/hooks/post-tool.ts +94 -93
  104. package/src/hooks/project-guards.ts +93 -55
  105. package/src/hooks/project-tmp.ts +27 -24
  106. package/src/hooks/remote-hosts.ts +157 -149
  107. package/src/hooks/session-digest.ts +99 -95
  108. package/src/hooks/shell.ts +519 -500
  109. package/src/hooks/subagent-card.ts +11 -7
  110. package/src/hooks/trusted-scripts.ts +158 -80
  111. package/src/init/common/types.ts +1 -1
  112. package/src/init/scaffold.ts +137 -134
  113. package/src/local/clean.ts +39 -37
  114. package/src/local/format.ts +21 -17
  115. package/src/local/scan.ts +146 -140
  116. package/src/manifest/render.ts +127 -112
  117. package/src/owner/card.ts +51 -46
  118. package/src/owner/profile.ts +100 -96
  119. package/src/owner/reply-switch.ts +9 -6
  120. package/src/owner/shape.ts +72 -70
  121. package/src/owner/survey.ts +175 -164
  122. package/src/owner/view.ts +62 -59
  123. package/src/owner/violations.ts +119 -123
  124. package/src/router.ts +4 -1
  125. package/src/rules/base.ts +15 -11
  126. package/src/rules/common/types.ts +1 -1
  127. package/src/rules/parser.ts +39 -32
  128. package/src/rules/slots.ts +8 -6
  129. package/src/signals/claims.ts +30 -28
  130. package/src/signals/classify.ts +36 -33
  131. package/src/signals/loop.ts +39 -37
  132. package/src/signals/state.ts +80 -85
  133. package/src/skills/frontmatter.ts +28 -28
  134. package/src/sync/agent-files.ts +217 -199
  135. package/src/sync/agent-removal.ts +62 -68
  136. package/src/sync/atlas-block.ts +45 -43
  137. package/src/sync/base-rules.ts +32 -30
  138. package/src/sync/claude-launch.ts +74 -37
  139. package/src/sync/common/constants.ts +4 -0
  140. package/src/sync/common/index.ts +1 -0
  141. package/src/sync/common/symlink.ts +9 -0
  142. package/src/sync/common/types.ts +2 -2
  143. package/src/sync/exclude.ts +77 -69
  144. package/src/sync/local-choice.ts +50 -47
  145. package/src/sync/planner.ts +64 -68
  146. package/src/sync/prune.ts +52 -48
  147. package/src/sync/settings.ts +167 -168
  148. package/src/ui/capability.ts +12 -7
  149. package/src/ui/keyboard.ts +35 -33
  150. package/src/ui/prompt.ts +81 -77
  151. package/src/visualize/assets.ts +379 -195
  152. package/src/visualize/charts.ts +188 -176
  153. package/src/visualize/compare-css.ts +31 -0
  154. package/src/visualize/compare-render.ts +196 -0
  155. package/src/visualize/compare-schema.ts +81 -0
  156. package/src/visualize/compare-validate.ts +126 -0
  157. package/src/visualize/constants.ts +29 -3
  158. package/src/visualize/diagrams.ts +189 -174
  159. package/src/visualize/gate.ts +136 -0
  160. package/src/visualize/grid-span.ts +34 -0
  161. package/src/visualize/icons.ts +9 -4
  162. package/src/visualize/index.ts +2 -0
  163. package/src/visualize/kinds-css.ts +54 -0
  164. package/src/visualize/kinds-render.ts +698 -0
  165. package/src/visualize/kinds-schema.ts +148 -0
  166. package/src/visualize/kinds-validate.ts +186 -0
  167. package/src/visualize/labels-vi.ts +109 -0
  168. package/src/visualize/labels.ts +53 -0
  169. package/src/visualize/layout.ts +112 -92
  170. package/src/visualize/page.ts +140 -114
  171. package/src/visualize/render.ts +158 -114
  172. package/src/visualize/schema.ts +21 -1
  173. package/src/visualize/sections.ts +401 -309
  174. package/src/visualize/sources.ts +270 -0
  175. package/src/visualize/theme.ts +474 -0
  176. package/src/visualize/validate.ts +15 -5
  177. package/src/wiki/anchors.ts +39 -37
  178. package/src/wiki/command.ts +4 -4
  179. package/src/wiki/source-links.ts +49 -49
@@ -0,0 +1,698 @@
1
+ import { SpecCharts } from './charts.ts';
2
+ import type { TChrome } from './constants.ts';
3
+ import { FigureLayout } from './layout.ts';
4
+ import { LifecycleKinds, MessageKinds } from './kinds-schema.ts';
5
+ import type { ITreeNode, TLifecycle, TSequence, TTree } from './kinds-schema.ts';
6
+ import type { INewKindsSpec } from './kinds-validate.ts';
7
+ import { SpecSections } from './sections.ts';
8
+
9
+ /** What a section of the new kinds needs: its slice of the spec, the page's words, and the figure widths to register. */
10
+ export interface INewKindsContext {
11
+ spec: INewKindsSpec;
12
+ chrome: TChrome;
13
+ fits: Set<number>;
14
+ }
15
+
16
+ /** A figure, the width it needs to keep its text readable, the list that replaces it on a phone, and its sentences. */
17
+ export interface IKindDrawing {
18
+ svg: string;
19
+ width: number;
20
+ list: string;
21
+ caption: string;
22
+ label: string;
23
+ }
24
+
25
+ /** The few words these figures say that the page's words may not have yet: English until the chrome has them. */
26
+ const KIND_WORDS = {
27
+ kindCall: 'call',
28
+ kindReply: 'reply',
29
+ kindAsync: 'async',
30
+ stateStart: 'start',
31
+ stateEnd: 'end',
32
+ countMessages: 'messages',
33
+ countStates: 'states',
34
+ countTransitions: 'transitions',
35
+ countItems: 'items',
36
+ } as const;
37
+
38
+ const escaped = (value: string): string => FigureLayout.escapeText({ value });
39
+
40
+ const wordOf = (opts: { chrome: TChrome; key: keyof typeof KIND_WORDS }): string => {
41
+ const given: Record<string, unknown> = opts.chrome;
42
+ const value = given[opts.key];
43
+
44
+ return typeof value === 'string' ? value : KIND_WORDS[opts.key];
45
+ };
46
+
47
+ const MARGIN = 24;
48
+ /** No figure is narrower than this, so on a phone (390 px) the list always takes its place. */
49
+ const MIN_WIDTH = 480;
50
+ const LABEL_PX = 8.2;
51
+ const SMALL_PX = 6.6;
52
+
53
+ /** Greedy wrap into lines of at most `chars` characters; a word longer than a line is cut. */
54
+ const wrapLines = (opts: { text: string; chars: number }): string[] => {
55
+ const lines: string[] = [];
56
+ let line = '';
57
+
58
+ for (const word of opts.text.split(/\s+/).filter((part) => part !== '')) {
59
+ let rest = [...word];
60
+
61
+ while (rest.length > opts.chars) {
62
+ if (line !== '') {
63
+ lines.push(line);
64
+ line = '';
65
+ }
66
+
67
+ lines.push(rest.slice(0, opts.chars).join(''));
68
+ rest = rest.slice(opts.chars);
69
+ }
70
+
71
+ const piece = rest.join('');
72
+ const next = line === '' ? piece : `${line} ${piece}`;
73
+
74
+ if (next.length > opts.chars && line !== '') {
75
+ lines.push(line);
76
+ line = piece;
77
+ } else {
78
+ line = next;
79
+ }
80
+ }
81
+
82
+ if (line !== '') {
83
+ lines.push(line);
84
+ }
85
+
86
+ return lines;
87
+ };
88
+
89
+ /** One `<text>` of several lines; a line ends with a space so the text reads whole without the layout. */
90
+ const textLines = (opts: {
91
+ cls: string;
92
+ x: number;
93
+ y: number;
94
+ lines: string[];
95
+ step: number;
96
+ anchor?: string;
97
+ }): string =>
98
+ `<text class="${opts.cls}" x="${opts.x}" y="${opts.y}"${opts.anchor === undefined ? '' : ` text-anchor="${opts.anchor}"`}>${opts.lines
99
+ .map(
100
+ (line, index) =>
101
+ `<tspan x="${opts.x}" dy="${index === 0 ? 0 : opts.step}">${escaped(line)}${index < opts.lines.length - 1 ? ' ' : ''}</tspan>`,
102
+ )
103
+ .join('')}</text>`;
104
+
105
+ /** An arrowhead at a tip, pointing along (dx, dy): filled, or two open strokes. */
106
+ const head = (opts: { x: number; y: number; dx: number; dy: number; open?: boolean }): string => {
107
+ const { x, y, dx, dy } = opts;
108
+ const bx = x - dx * 10;
109
+ const by = y - dy * 10;
110
+ const px = -dy * 5;
111
+ const py = dx * 5;
112
+
113
+ return opts.open === true
114
+ ? `<path class="kopen" d="M${bx + px} ${by + py}L${x} ${y}L${bx - px} ${by - py}"/>`
115
+ : `<path class="khead" d="M${x} ${y}L${bx + px} ${by + py}L${bx - px} ${by - py}Z"/>`;
116
+ };
117
+
118
+ const svgOf = (opts: { width: number; height: number; label: string; body: string }): string =>
119
+ `<svg class="kf" width="${opts.width}" height="${opts.height}" viewBox="0 0 ${opts.width} ${opts.height}" role="group" aria-label="${escaped(opts.label)}">${opts.body}</svg>`;
120
+
121
+ // -----------------------------------------------------------------------------------------------------------------
122
+ // Sequence
123
+ // -----------------------------------------------------------------------------------------------------------------
124
+
125
+ const MESSAGE_WORD: Record<string, keyof typeof KIND_WORDS> = {
126
+ call: 'kindCall',
127
+ reply: 'kindReply',
128
+ async: 'kindAsync',
129
+ };
130
+
131
+ const renderSequence = (opts: { sequence: TSequence; chrome: TChrome }): IKindDrawing => {
132
+ const { sequence, chrome } = opts;
133
+ const count = sequence.participants.length;
134
+ const lane = Math.max(190, Math.floor(600 / count));
135
+ const width = MARGIN * 2 + count * lane;
136
+ const boxWidth = lane - 24;
137
+ const centre = (index: number): number => MARGIN + lane * index + lane / 2;
138
+ const positions = new Map(sequence.participants.map((part, index) => [part.id, index]));
139
+ const heads = sequence.participants.map((part) => {
140
+ const labelLines = wrapLines({
141
+ text: part.label,
142
+ chars: Math.floor((boxWidth - 20) / LABEL_PX),
143
+ });
144
+ const subLines =
145
+ part.sublabel === undefined
146
+ ? []
147
+ : wrapLines({ text: part.sublabel, chars: Math.floor((boxWidth - 20) / SMALL_PX) });
148
+ const last = 24 + (labelLines.length - 1) * 17;
149
+ const bottom = subLines.length === 0 ? last : last + 17 + (subLines.length - 1) * 15;
150
+
151
+ return { part, labelLines, subLines, last, height: bottom + 14 };
152
+ });
153
+ const headHeight = Math.max(...heads.map((item) => item.height));
154
+ const hasNote = sequence.messages.some((message) => message.note !== undefined);
155
+ const rowHeight = hasNote ? 66 : 52;
156
+ const firstY = 8 + headHeight + (hasNote ? 48 : 40);
157
+ const lastY = firstY + (sequence.messages.length - 1) * rowHeight;
158
+ const kinds = [...new Set(sequence.messages.map((message) => message.kind ?? MessageKinds.CALL))];
159
+ const legendHeight = kinds.length > 1 ? 34 : 0;
160
+ const height = lastY + (hasNote ? 40 : 28) + legendHeight;
161
+ const lifelines = heads
162
+ .map(
163
+ (_, index) =>
164
+ `<path class="klife" d="M${centre(index)} ${8 + headHeight}V${height - legendHeight - 8}"/>`,
165
+ )
166
+ .join('');
167
+ const boxes = heads
168
+ .map((item, index) => {
169
+ const x = centre(index) - boxWidth / 2;
170
+
171
+ return `<g><rect class="kbox" x="${x}" y="8" width="${boxWidth}" height="${headHeight}" rx="4"/>${textLines({ cls: 'kt', x: centre(index), y: 8 + 24, lines: item.labelLines, step: 17, anchor: 'middle' })}${item.subLines.length === 0 ? '' : textLines({ cls: 'ks', x: centre(index), y: 8 + item.last + 17, lines: item.subLines, step: 15, anchor: 'middle' })}</g>`;
172
+ })
173
+ .join('');
174
+ const messages = sequence.messages
175
+ .map((message, order) => {
176
+ const from = positions.get(message.from);
177
+ const to = positions.get(message.to);
178
+
179
+ if (from === undefined || to === undefined || from === to) {
180
+ return '';
181
+ }
182
+
183
+ const kind = message.kind ?? MessageKinds.CALL;
184
+ const sign = to > from ? 1 : -1;
185
+ const y = firstY + order * rowHeight;
186
+ const x1 = centre(from) + sign * 6;
187
+ const x2 = centre(to) - sign * 6;
188
+
189
+ return `<g class="kmsg k-${kind}">${message.note === undefined ? '' : `<title>${escaped(message.note)}</title>`}<path class="kline${kind === MessageKinds.REPLY ? ' kdash' : ''}" d="M${x1} ${y}H${x2}"/>${head({ x: x2, y, dx: sign, dy: 0, open: kind === MessageKinds.ASYNC })}<text class="ke kh" x="${(x1 + x2) / 2}" y="${y - 9}" text-anchor="middle"><tspan class="knum">${order + 1}.</tspan> ${escaped(message.label)}</text>${message.note === undefined ? '' : `<text class="ks kh" x="${(x1 + x2) / 2}" y="${y + 18}" text-anchor="middle">${escaped(message.note)}</text>`}</g>`;
190
+ })
191
+ .join('');
192
+ const legend =
193
+ kinds.length > 1
194
+ ? kinds
195
+ .map((kind, index) => {
196
+ const x = MARGIN + index * 150;
197
+ const y = height - 18;
198
+
199
+ return `<g class="klegend"><path class="kline${kind === MessageKinds.REPLY ? ' kdash' : ''}" d="M${x} ${y}H${x + 34}"/>${head({ x: x + 34, y, dx: 1, dy: 0, open: kind === MessageKinds.ASYNC })}<text class="ks" x="${x + 46}" y="${y + 4}">${escaped(wordOf({ chrome, key: MESSAGE_WORD[kind] ?? 'kindCall' }))}</text></g>`;
200
+ })
201
+ .join('')
202
+ : '';
203
+ const names = sequence.participants.map((part) => part.label).join(', ');
204
+ const nameOf = (id: string): string =>
205
+ sequence.participants.find((part) => part.id === id)?.label ?? id;
206
+
207
+ return {
208
+ svg: svgOf({
209
+ width,
210
+ height,
211
+ label: `${chrome.sequence}: ${names}`,
212
+ body: `${lifelines}${boxes}${messages}${legend}`,
213
+ }),
214
+ width,
215
+ list: `<div class="path kl ksq"><ul class="kparts">${sequence.participants.map((part) => `<li><b>${escaped(part.label)}</b>${part.sublabel === undefined ? '' : ` <span class="mut">${escaped(part.sublabel)}</span>`}</li>`).join('')}</ul><ol class="kmsgs">${sequence.messages
216
+ .map((message) => {
217
+ const kind = message.kind ?? MessageKinds.CALL;
218
+
219
+ return `<li class="k-${kind}"><b>${escaped(nameOf(message.from))}</b><span class="verb kv-${kind}">${escaped(message.label)}</span><b>${escaped(nameOf(message.to))}</b>${kind === MessageKinds.CALL ? '' : ` <span class="kword">${escaped(wordOf({ chrome, key: MESSAGE_WORD[kind] ?? 'kindCall' }))}</span>`}${message.note === undefined ? '' : `<span class="knote">${escaped(message.note)}</span>`}</li>`;
220
+ })
221
+ .join('')}</ol></div>`,
222
+ caption:
223
+ sequence.caption ??
224
+ `${names}: ${sequence.messages.length} ${wordOf({ chrome, key: 'countMessages' })}`,
225
+ label: `${chrome.sequence}: ${names}`,
226
+ };
227
+ };
228
+
229
+ // -----------------------------------------------------------------------------------------------------------------
230
+ // Lifecycle
231
+ // -----------------------------------------------------------------------------------------------------------------
232
+
233
+ type TState = TLifecycle['states'][number];
234
+
235
+ /** From the start by the transitions, breadth first; the ends last, so the figure runs toward them. */
236
+ const orderStates = (opts: { lifecycle: TLifecycle }): TState[] => {
237
+ const { lifecycle } = opts;
238
+ const byId = new Map(lifecycle.states.map((state) => [state.id, state]));
239
+ const start = lifecycle.states.find((state) => state.kind === LifecycleKinds.START);
240
+ const seen = new Set<string>();
241
+ const found: TState[] = [];
242
+ const queue = start === undefined ? [] : [start.id];
243
+
244
+ if (start !== undefined) {
245
+ seen.add(start.id);
246
+ }
247
+
248
+ while (queue.length > 0) {
249
+ const at = queue.shift() ?? '';
250
+ const state = byId.get(at);
251
+
252
+ if (state !== undefined) {
253
+ found.push(state);
254
+ }
255
+
256
+ for (const transition of lifecycle.transitions) {
257
+ if (transition.from === at && byId.has(transition.to) && !seen.has(transition.to)) {
258
+ seen.add(transition.to);
259
+ queue.push(transition.to);
260
+ }
261
+ }
262
+ }
263
+
264
+ for (const state of lifecycle.states) {
265
+ if (!seen.has(state.id)) {
266
+ found.push(state);
267
+ }
268
+ }
269
+
270
+ return [
271
+ ...found.filter((state) => state.kind !== LifecycleKinds.END),
272
+ ...found.filter((state) => state.kind === LifecycleKinds.END),
273
+ ];
274
+ };
275
+
276
+ const BOX_WIDTH = 148;
277
+ const GAP = 104;
278
+ const LEFT = 48;
279
+ const LEVEL = 22;
280
+
281
+ /** The offset of the n-th line leaving one side of a box: the middle, then to either side. */
282
+ const portOffset = (opts: { index: number }): number =>
283
+ opts.index === 0
284
+ ? 0
285
+ : Math.max(-64, Math.min(64, (opts.index % 2 === 1 ? 1 : -1) * Math.ceil(opts.index / 2) * 16));
286
+
287
+ type TSide = 'top' | 'bottom';
288
+
289
+ interface IRoute {
290
+ from: string;
291
+ to: string;
292
+ label: string;
293
+ /** `h` and `v` are straight between neighbours, `arc` runs over or under a row, `cross` through the gap between rows. */
294
+ shape: 'h' | 'v' | 'arc' | 'cross';
295
+ gutter?: 'top' | 'gap' | 'bottom';
296
+ level?: number;
297
+ }
298
+
299
+ const renderLifecycle = (opts: { lifecycle: TLifecycle; chrome: TChrome }): IKindDrawing => {
300
+ const { lifecycle, chrome } = opts;
301
+ const order = orderStates({ lifecycle });
302
+ const count = order.length;
303
+ const perRow = count <= 5 ? count : Math.ceil(count / 2);
304
+ const rows = count <= 5 ? 1 : 2;
305
+ const places = new Map(
306
+ order.map((state, index) => {
307
+ const row = index < perRow ? 0 : 1;
308
+ const col = row === 0 ? index : perRow - 1 - (index - perRow);
309
+
310
+ return [state.id, { state, row, col }] as const;
311
+ }),
312
+ );
313
+ const wordFor = (state: TState): string | undefined =>
314
+ state.kind === LifecycleKinds.START
315
+ ? wordOf({ chrome, key: 'stateStart' })
316
+ : state.kind === LifecycleKinds.END
317
+ ? wordOf({ chrome, key: 'stateEnd' })
318
+ : undefined;
319
+ const contents = order.map((state) => {
320
+ const labelLines = wrapLines({
321
+ text: state.label,
322
+ chars: Math.floor((BOX_WIDTH - 24) / LABEL_PX),
323
+ });
324
+ const subLines =
325
+ state.sublabel === undefined
326
+ ? []
327
+ : wrapLines({ text: state.sublabel, chars: Math.floor((BOX_WIDTH - 24) / SMALL_PX) });
328
+ const word = wordFor(state);
329
+ const wordBase = 21;
330
+ const first = word === undefined ? 24 : 40;
331
+ const last = first + (labelLines.length - 1) * 17;
332
+ const bottom = subLines.length === 0 ? last : last + 17 + (subLines.length - 1) * 15;
333
+
334
+ return { state, labelLines, subLines, word, wordBase, first, last, height: bottom + 14 };
335
+ });
336
+ const boxHeight = Math.max(72, ...contents.map((item) => item.height));
337
+
338
+ // Classify every transition, and give each line that runs around a row its own level, so no two share one.
339
+ const used = { top: 0, gap: 0, bottom: 0 };
340
+ const pairs = new Map<string, number>();
341
+ const routes: IRoute[] = [];
342
+
343
+ for (const transition of lifecycle.transitions) {
344
+ const a = places.get(transition.from);
345
+ const b = places.get(transition.to);
346
+
347
+ if (a === undefined || b === undefined || a === b) {
348
+ continue;
349
+ }
350
+
351
+ const route: IRoute = {
352
+ from: transition.from,
353
+ to: transition.to,
354
+ label: transition.label,
355
+ shape: 'arc',
356
+ };
357
+
358
+ if (a.row === b.row && Math.abs(a.col - b.col) === 1) {
359
+ route.shape = 'h';
360
+ } else if (a.row !== b.row && a.col === b.col) {
361
+ route.shape = 'v';
362
+ } else if (a.row !== b.row) {
363
+ route.shape = 'cross';
364
+ route.gutter = 'gap';
365
+ route.level = used.gap;
366
+ used.gap += 1;
367
+ } else {
368
+ route.gutter =
369
+ rows === 1 ? (b.col > a.col ? 'top' : 'bottom') : a.row === 0 ? 'top' : 'bottom';
370
+ route.level = used[route.gutter];
371
+ used[route.gutter] += 1;
372
+ }
373
+
374
+ if (route.shape === 'h' || route.shape === 'v') {
375
+ const key = [transition.from, transition.to].sort().join('>');
376
+
377
+ pairs.set(key, (pairs.get(key) ?? 0) + 1);
378
+ }
379
+
380
+ routes.push(route);
381
+ }
382
+
383
+ const topGutter = used.top === 0 ? 16 : 30 + used.top * LEVEL;
384
+ const gapGutter = rows === 1 ? 0 : Math.max(80, 40 + used.gap * LEVEL);
385
+ const bottomGutter = used.bottom === 0 ? 16 : 36 + used.bottom * LEVEL;
386
+ const rowTop = (row: number): number => topGutter + row * (boxHeight + gapGutter);
387
+ const colX = (col: number): number => LEFT + col * (BOX_WIDTH + GAP);
388
+ const width = Math.max(MIN_WIDTH, LEFT + perRow * BOX_WIDTH + (perRow - 1) * GAP + MARGIN);
389
+ const height = topGutter + rows * boxHeight + (rows - 1) * gapGutter + bottomGutter;
390
+ const ports = new Map<string, number>();
391
+
392
+ // A straight line between two stacked boxes sits in the middle of their facing sides: arcs start beside it.
393
+ for (const route of routes) {
394
+ const a = places.get(route.from);
395
+ const b = places.get(route.to);
396
+
397
+ if (route.shape === 'v' && a !== undefined && b !== undefined) {
398
+ ports.set(`${a.state.id}:${a.row === 0 ? 'bottom' : 'top'}`, 1);
399
+ ports.set(`${b.state.id}:${b.row === 0 ? 'bottom' : 'top'}`, 1);
400
+ }
401
+ }
402
+
403
+ const take = (port: { id: string; side: TSide }): number => {
404
+ const key = `${port.id}:${port.side}`;
405
+ const index = ports.get(key) ?? 0;
406
+
407
+ ports.set(key, index + 1);
408
+
409
+ return portOffset({ index });
410
+ };
411
+ const drawn = routes.map((route): { line: string; text: string } => {
412
+ const a = places.get(route.from);
413
+ const b = places.get(route.to);
414
+
415
+ if (a === undefined || b === undefined) {
416
+ return { line: '', text: '' };
417
+ }
418
+
419
+ const double = (pairs.get([route.from, route.to].sort().join('>')) ?? 0) > 1;
420
+ const labelHalo = 'ke kh';
421
+
422
+ if (route.shape === 'h') {
423
+ const right = b.col > a.col;
424
+ const offset = double ? (right ? -9 : 9) : 0;
425
+ const y = rowTop(a.row) + boxHeight / 2 + offset;
426
+ const x1 = right ? colX(a.col) + BOX_WIDTH : colX(a.col);
427
+ const x2 = right ? colX(b.col) : colX(b.col) + BOX_WIDTH;
428
+ const sign = right ? 1 : -1;
429
+ const label = wrapLines({ text: route.label, chars: Math.floor((GAP - 16) / 6.6) });
430
+ const above = !double || right;
431
+ const labelY = above ? y - 7 - (label.length - 1) * 14 : y + 17;
432
+
433
+ return {
434
+ line: `<path class="kline" d="M${x1} ${y}H${x2}"/>${head({ x: x2, y, dx: sign, dy: 0 })}`,
435
+ text: textLines({
436
+ cls: labelHalo,
437
+ x: (x1 + x2) / 2,
438
+ y: labelY,
439
+ lines: label,
440
+ step: 14,
441
+ anchor: 'middle',
442
+ }),
443
+ };
444
+ }
445
+
446
+ if (route.shape === 'v') {
447
+ const down = b.row > a.row;
448
+ const offset = double ? (down ? -9 : 9) : 0;
449
+ const x = colX(a.col) + BOX_WIDTH / 2 + offset;
450
+ const y1 = down ? rowTop(a.row) + boxHeight : rowTop(a.row);
451
+ const y2 = down ? rowTop(b.row) : rowTop(b.row) + boxHeight;
452
+ const left = double && down;
453
+
454
+ return {
455
+ line: `<path class="kline" d="M${x} ${y1}V${y2}"/>${head({ x, y: y2, dx: 0, dy: down ? 1 : -1 })}`,
456
+ text: `<text class="${labelHalo}" x="${left ? x - 8 : x + 8}" y="${(y1 + y2) / 2 + 4}" text-anchor="${left ? 'end' : 'start'}">${escaped(route.label)}</text>`,
457
+ };
458
+ }
459
+
460
+ if (route.shape === 'cross') {
461
+ const aSide: TSide = a.row === 0 ? 'bottom' : 'top';
462
+ const bSide: TSide = b.row === 0 ? 'bottom' : 'top';
463
+ const x1 = colX(a.col) + BOX_WIDTH / 2 + take({ id: a.state.id, side: aSide });
464
+ const x2 = colX(b.col) + BOX_WIDTH / 2 + take({ id: b.state.id, side: bSide });
465
+ const down = b.row > a.row;
466
+ const y1 = aSide === 'bottom' ? rowTop(a.row) + boxHeight : rowTop(a.row);
467
+ const y2 = bSide === 'bottom' ? rowTop(b.row) + boxHeight : rowTop(b.row);
468
+ const level = rowTop(0) + boxHeight + 28 + (route.level ?? 0) * LEVEL;
469
+
470
+ return {
471
+ line: `<path class="kline" d="M${x1} ${y1}V${level}H${x2}V${y2}"/>${head({ x: x2, y: y2, dx: 0, dy: down ? 1 : -1 })}`,
472
+ text: `<text class="${labelHalo}" x="${(x1 + x2) / 2}" y="${level - 6}" text-anchor="middle">${escaped(route.label)}</text>`,
473
+ };
474
+ }
475
+
476
+ // An arc over the top of a row, or under the bottom of it.
477
+ const side: TSide = route.gutter === 'top' ? 'top' : 'bottom';
478
+ const x1 = colX(a.col) + BOX_WIDTH / 2 + take({ id: a.state.id, side });
479
+ const x2 = colX(b.col) + BOX_WIDTH / 2 + take({ id: b.state.id, side });
480
+ const edge = side === 'top' ? rowTop(a.row) : rowTop(a.row) + boxHeight;
481
+ const level =
482
+ side === 'top'
483
+ ? rowTop(0) - 24 - (route.level ?? 0) * LEVEL
484
+ : rowTop(rows - 1) + boxHeight + 24 + (route.level ?? 0) * LEVEL;
485
+
486
+ return {
487
+ line: `<path class="kline" d="M${x1} ${edge}V${level}H${x2}V${edge}"/>${head({ x: x2, y: edge, dx: 0, dy: side === 'top' ? 1 : -1 })}`,
488
+ text: `<text class="${labelHalo}" x="${(x1 + x2) / 2}" y="${level - 6}" text-anchor="middle">${escaped(route.label)}</text>`,
489
+ };
490
+ });
491
+ const lines = drawn.map((item) => item.line).join('');
492
+ const labels = drawn.map((item) => item.text).join('');
493
+ const boxes = contents
494
+ .map((item) => {
495
+ const place = places.get(item.state.id);
496
+
497
+ if (place === undefined) {
498
+ return '';
499
+ }
500
+
501
+ const x = colX(place.col);
502
+ const y = rowTop(place.row);
503
+ const kind = item.state.kind ?? LifecycleKinds.NORMAL;
504
+
505
+ return `<g class="kstate kk-${kind}"><rect class="kbox" x="${x}" y="${y}" width="${BOX_WIDTH}" height="${boxHeight}" rx="4"/>${kind === LifecycleKinds.END ? `<rect class="kinner" x="${x + 5}" y="${y + 5}" width="${BOX_WIDTH - 10}" height="${boxHeight - 10}" rx="2"/>` : ''}${item.word === undefined ? '' : `<text class="kw" x="${x + 14}" y="${y + item.wordBase}">${escaped(item.word)}</text>`}${textLines({ cls: 'kt', x: x + 14, y: y + item.first, lines: item.labelLines, step: 17 })}${item.subLines.length === 0 ? '' : textLines({ cls: 'ks', x: x + 14, y: y + item.last + 17, lines: item.subLines, step: 15 })}</g>`;
506
+ })
507
+ .join('');
508
+ const [first] = order;
509
+ const firstPlace = first === undefined ? undefined : places.get(first.id);
510
+ const marker =
511
+ first !== undefined &&
512
+ first.kind === LifecycleKinds.START &&
513
+ firstPlace !== undefined &&
514
+ firstPlace.row === 0 &&
515
+ firstPlace.col === 0
516
+ ? `<g class="klink"><circle class="kdot" cx="14" cy="${rowTop(0) + boxHeight / 2}" r="7"/><path class="kline" d="M22 ${rowTop(0) + boxHeight / 2}H${LEFT - 2}"/>${head({ x: LEFT - 2, y: rowTop(0) + boxHeight / 2, dx: 1, dy: 0 })}</g>`
517
+ : '';
518
+ const nameOf = (id: string): string =>
519
+ lifecycle.states.find((state) => state.id === id)?.label ?? id;
520
+ const label = `${chrome.lifecycle}: ${order.map((state) => state.label).join(', ')}`;
521
+
522
+ return {
523
+ svg: svgOf({ width, height, label, body: `${marker}${lines}${boxes}${labels}` }),
524
+ width,
525
+ list: `<ul class="path kl klc">${order
526
+ .map((state) => {
527
+ const word = wordFor(state);
528
+ const out = lifecycle.transitions.filter((transition) => transition.from === state.id);
529
+
530
+ return `<li class="kst kk-${state.kind ?? LifecycleKinds.NORMAL}"><b>${escaped(state.label)}</b>${state.sublabel === undefined ? '' : ` <span class="mut">${escaped(state.sublabel)}</span>`}${word === undefined ? '' : ` <span class="kword">${escaped(word)}</span>`}${out.length === 0 ? '' : `<ul class="kout">${out.map((transition) => `<li><span class="verb">${escaped(transition.label)}</span><b>${escaped(nameOf(transition.to))}</b></li>`).join('')}</ul>`}</li>`;
531
+ })
532
+ .join('')}</ul>`,
533
+ caption:
534
+ lifecycle.caption ??
535
+ `${order.length} ${wordOf({ chrome, key: 'countStates' })}, ${lifecycle.transitions.length} ${wordOf({ chrome, key: 'countTransitions' })}`,
536
+ label,
537
+ };
538
+ };
539
+
540
+ // -----------------------------------------------------------------------------------------------------------------
541
+ // Tree
542
+ // -----------------------------------------------------------------------------------------------------------------
543
+
544
+ interface IRow {
545
+ node: ITreeNode;
546
+ depth: number;
547
+ parent: number | undefined;
548
+ }
549
+
550
+ const INDENT = 36;
551
+ const TREE_TOP = 12;
552
+ const ROW_GAP = 10;
553
+
554
+ const renderTree = (opts: { tree: TTree; chrome: TChrome }): IKindDrawing => {
555
+ const { tree, chrome } = opts;
556
+ const rows: IRow[] = [];
557
+ const walk = (node: ITreeNode, depth: number, parent: number | undefined): void => {
558
+ const index = rows.length;
559
+
560
+ rows.push({ node, depth, parent });
561
+
562
+ for (const child of node.children ?? []) {
563
+ walk(child, depth + 1, index);
564
+ }
565
+ };
566
+
567
+ walk(tree.root, 0, undefined);
568
+
569
+ const sized = rows.map((row) => {
570
+ const word =
571
+ row.node.state === undefined
572
+ ? undefined
573
+ : SpecSections.stateWord({ chrome, state: row.node.state });
574
+ const hasSub = row.node.sublabel !== undefined;
575
+ const icon = row.node.state === undefined ? 0 : 26;
576
+ const wordWidth = word === undefined ? 0 : Math.ceil(word.length * 7.4) + 20;
577
+ const textWidth = Math.max(
578
+ Math.ceil(row.node.label.length * LABEL_PX) + wordWidth,
579
+ Math.ceil((row.node.sublabel?.length ?? 0) * SMALL_PX),
580
+ );
581
+ const boxWidth = Math.max(160, textWidth + 28 + icon);
582
+
583
+ return { ...row, word, hasSub, icon, boxWidth, boxHeight: hasSub ? 50 : 36 };
584
+ });
585
+ let cursor = TREE_TOP;
586
+ const placed = sized.map((row) => {
587
+ const placement = { ...row, x: MARGIN + row.depth * INDENT, y: cursor };
588
+
589
+ cursor += row.boxHeight + ROW_GAP;
590
+
591
+ return placement;
592
+ });
593
+ const width = Math.max(
594
+ MIN_WIDTH,
595
+ Math.max(...placed.map((row) => row.x + row.boxWidth)) + MARGIN,
596
+ );
597
+ const height = cursor - ROW_GAP + TREE_TOP;
598
+ const guides = placed
599
+ .map((row, index) => {
600
+ const children = placed.filter((other) => other.parent === index);
601
+
602
+ if (children.length === 0) {
603
+ return '';
604
+ }
605
+
606
+ const trunk = row.x + 14;
607
+ const lastCentre = Math.max(...children.map((child) => child.y + child.boxHeight / 2));
608
+
609
+ return `<path class="kguide" d="M${trunk} ${row.y + row.boxHeight}V${lastCentre}${children.map((child) => `M${trunk} ${child.y + child.boxHeight / 2}H${child.x}`).join('')}"/>`;
610
+ })
611
+ .join('');
612
+ const boxes = placed
613
+ .map((row) => {
614
+ const centre = row.y + row.boxHeight / 2;
615
+ const textX = row.x + 14 + row.icon;
616
+ const state = row.node.state;
617
+
618
+ return `<g class="knode${state === undefined ? '' : ` kn-${state.replaceAll(' ', '-')}`}"><rect class="kbox" x="${row.x}" y="${row.y}" width="${row.boxWidth}" height="${row.boxHeight}" rx="4"/>${state === undefined ? '' : `<g class="kic" transform="translate(${row.x + 12} ${centre - 8})">${SpecCharts.stateIcon({ state, size: 16 }).replace('<svg', '<svg x="0" y="0"')}</g>`}<text class="kt" x="${textX}" y="${row.hasSub ? row.y + 21 : centre + 5}">${escaped(row.node.label)}</text>${row.word === undefined ? '' : `<text class="kw" x="${row.x + row.boxWidth - 12}" y="${row.hasSub ? row.y + 21 : centre + 4}" text-anchor="end">${escaped(row.word)}</text>`}${row.node.sublabel === undefined ? '' : `<text class="ks" x="${textX}" y="${row.y + 39}">${escaped(row.node.sublabel)}</text>`}</g>`;
619
+ })
620
+ .join('');
621
+ const outline = (node: ITreeNode): string => {
622
+ const state =
623
+ node.state === undefined ? '' : ` ${SpecSections.chip({ chrome, state: node.state })}`;
624
+ const inner =
625
+ node.children === undefined || node.children.length === 0
626
+ ? ''
627
+ : `<ul class="kt-in">${node.children.map(outline).join('')}</ul>`;
628
+
629
+ return `<li><b>${escaped(node.label)}</b>${node.sublabel === undefined ? '' : ` <span class="mut">${escaped(node.sublabel)}</span>`}${state}${inner}</li>`;
630
+ };
631
+ const label = `${chrome.tree}: ${tree.root.label}`;
632
+
633
+ return {
634
+ svg: svgOf({ width, height, label, body: `${guides}${boxes}` }),
635
+ width,
636
+ list: `<ul class="path kl ktr">${outline(tree.root)}</ul>`,
637
+ caption:
638
+ tree.caption ?? `${tree.root.label}: ${rows.length} ${wordOf({ chrome, key: 'countItems' })}`,
639
+ label,
640
+ };
641
+ };
642
+
643
+ // -----------------------------------------------------------------------------------------------------------------
644
+ // Sections
645
+ // -----------------------------------------------------------------------------------------------------------------
646
+
647
+ /** A figure in its frame, its list as a sibling for the page to swap in on a phone, and its caption. */
648
+ const frame = (opts: { ctx: INewKindsContext; drawing: IKindDrawing }): string => {
649
+ const width = Math.round(opts.drawing.width);
650
+
651
+ opts.ctx.fits.add(width);
652
+
653
+ return `<figure class="kfig"><div class="fig f${width}">${opts.drawing.svg}</div>${opts.drawing.list}<figcaption>${escaped(opts.drawing.caption)}</figcaption></figure>`;
654
+ };
655
+
656
+ export class KindsRender {
657
+ static sequenceSection(opts: { ctx: INewKindsContext }): string {
658
+ const { sequence } = opts.ctx.spec;
659
+
660
+ return sequence === undefined
661
+ ? ''
662
+ : SpecSections.section({
663
+ id: 'sequence',
664
+ title: opts.ctx.chrome.sequence,
665
+ body: frame({
666
+ ctx: opts.ctx,
667
+ drawing: renderSequence({ sequence, chrome: opts.ctx.chrome }),
668
+ }),
669
+ });
670
+ }
671
+
672
+ static lifecycleSection(opts: { ctx: INewKindsContext }): string {
673
+ const { lifecycle } = opts.ctx.spec;
674
+
675
+ return lifecycle === undefined
676
+ ? ''
677
+ : SpecSections.section({
678
+ id: 'lifecycle',
679
+ title: opts.ctx.chrome.lifecycle,
680
+ body: frame({
681
+ ctx: opts.ctx,
682
+ drawing: renderLifecycle({ lifecycle, chrome: opts.ctx.chrome }),
683
+ }),
684
+ });
685
+ }
686
+
687
+ static treeSection(opts: { ctx: INewKindsContext }): string {
688
+ const { tree } = opts.ctx.spec;
689
+
690
+ return tree === undefined
691
+ ? ''
692
+ : SpecSections.section({
693
+ id: 'tree',
694
+ title: opts.ctx.chrome.tree,
695
+ body: frame({ ctx: opts.ctx, drawing: renderTree({ tree, chrome: opts.ctx.chrome }) }),
696
+ });
697
+ }
698
+ }