The best way to control Claude Code, Codex and more from any computer or phone

main
astro 546 lines 14.9 KB
Raw
1 ---
2 import DomainIcon from "./domain/DomainIcon.astro";
3 import DomainNode from "./domain/DomainNode.astro";
4 import { KIND_ORDER, KINDS, type Kind } from "./domain/kinds.ts";
5
6 /**
7 * `<DAG />` — server-rendered SVG of a small directed acyclic graph.
8 *
9 * Used in concept docs to illustrate resource dependency graphs and
10 * lifecycle flows. Auto-layouts nodes left-to-right using longest-path
11 * layering, then positions each node within its layer to minimize
12 * crossings (centered, tie-broken by input order).
13 *
14 * Styled to match the brand (parchment panel, moss accents, walnut
15 * text, JetBrains Mono labels).
16 *
17 * Usage in MDX:
18 * import DAG from "../../../components/DAG.astro";
19 * <DAG
20 * nodes={[
21 * { id: "Bucket", label: "Bucket", type: "Cloudflare.R2Bucket" },
22 * { id: "Sessions", label: "Sessions", type: "Cloudflare.KVNamespace" },
23 * { id: "Queue", label: "Queue", type: "AWS.SQS.Queue" },
24 * { id: "Worker", label: "Worker", type: "Cloudflare.Worker" },
25 * ]}
26 * edges={[
27 * { from: "Bucket", to: "Queue" },
28 * { from: "Bucket", to: "Worker" },
29 * { from: "Sessions", to: "Worker" },
30 * { from: "Queue", to: "Worker" },
31 * ]}
32 * />
33 */
34
35 export interface NodeIn {
36 id: string;
37 /** Visible label inside the node (defaults to `id`). */
38 label?: string;
39 /** Smaller subtitle below the label (e.g. resource type). */
40 type?: string;
41 /** Optional layer override (0-indexed left-to-right). Otherwise computed. */
42 layer?: number;
43 /**
44 * Fixed grid placement. When every node has `col` and `row`, auto-layout is
45 * skipped and edges are routed by direction: straight along a row or a
46 * column, or an elbow (down, then across) between rows.
47 */
48 col?: number;
49 row?: number;
50 /** Visual tone for the node. Defaults to "default". */
51 tone?: "default" | "accent" | "warn" | "danger";
52 /**
53 * What the node is in a domain model. Draws it with that kind's shape, icon
54 * and colour (see `./domain/kinds.ts`), and adds a legend of the kinds shown.
55 */
56 kind?: Kind;
57 }
58
59 export type { Kind } from "./domain/kinds.ts";
60
61 export interface EdgeIn {
62 from: string;
63 to: string;
64 /** Optional small label drawn near the edge midpoint. */
65 label?: string;
66 /** Render as a dashed line (e.g. for "later" / "deferred" edges). */
67 dashed?: boolean;
68 }
69
70 interface Props {
71 nodes: NodeIn[];
72 edges: EdgeIn[];
73 /** Layout direction. Defaults to "LR" (left-to-right). */
74 direction?: "LR" | "TB";
75 /** Optional caption rendered below the graph. */
76 caption?: string;
77 }
78
79 const { nodes, edges, direction = "LR", caption } = Astro.props as Props;
80
81 const kindsShown = KIND_ORDER.filter((k) => nodes.some((n) => n.kind === k));
82
83 // ---------- Layout ----------
84
85 // Domain nodes carry an icon beside their label, so they get a little more room.
86 const NODE_W = nodes.some((n) => n.kind) ? 164 : 140;
87 const NODE_H = 56;
88 const NODE_H_TYPED = 64; // slightly taller when subtitle present
89 const COL_GAP = 80;
90 const ROW_GAP = 28;
91 const PAD = 24;
92
93 const idIndex = new Map(nodes.map((n, i) => [n.id, i]));
94
95 // Longest-path layering: layer(v) = 1 + max(layer(u)) over predecessors.
96 const incoming = new Map<string, string[]>();
97 const outgoing = new Map<string, string[]>();
98 for (const n of nodes) {
99 incoming.set(n.id, []);
100 outgoing.set(n.id, []);
101 }
102 for (const e of edges) {
103 outgoing.get(e.from)?.push(e.to);
104 incoming.get(e.to)?.push(e.from);
105 }
106
107 // Longest-path layering, cycle-safe: any predecessor edge that would
108 // re-enter a node currently on the recursion stack is treated as a
109 // back-edge and ignored for the purposes of layer assignment. This
110 // keeps cyclic graphs (A binds B, B binds A) layoutable side-by-side.
111 const layerOf = new Map<string, number>();
112 const visiting = new Set<string>();
113 const visit = (id: string): number => {
114 const cached = layerOf.get(id);
115 if (cached !== undefined) return cached;
116 const override = nodes[idIndex.get(id)!]?.layer;
117 if (override !== undefined) {
118 layerOf.set(id, override);
119 return override;
120 }
121 if (visiting.has(id)) {
122 // Back-edge: caller will Math.max with our placeholder; returning
123 // -1 means "don't push my dependent down a layer for this edge".
124 return -1;
125 }
126 visiting.add(id);
127 const preds = incoming.get(id) ?? [];
128 const predLayers = preds.map(visit).filter((l) => l >= 0);
129 const l = predLayers.length === 0 ? 0 : Math.max(...predLayers) + 1;
130 visiting.delete(id);
131 layerOf.set(id, l);
132 return l;
133 };
134 nodes.forEach((n) => visit(n.id));
135
136 const layers: string[][] = [];
137 for (const n of nodes) {
138 const l = layerOf.get(n.id)!;
139 if (!layers[l]) layers[l] = [];
140 layers[l].push(n.id);
141 }
142
143 // Heights — bump rows that have a subtitle.
144 const heightOf = (id: string): number =>
145 nodes[idIndex.get(id)!]?.type ? NODE_H_TYPED : NODE_H;
146
147 // Position nodes within each layer; center on the tallest layer.
148 const colMaxHeight = layers.map((col) =>
149 col.reduce((acc, id) => acc + heightOf(id) + ROW_GAP, -ROW_GAP),
150 );
151 const tallest = Math.max(...colMaxHeight);
152
153 const positions = new Map<string, { x: number; y: number; h: number }>();
154
155 const GRID_ROW_GAP = 56;
156 const grid = nodes.every((n) => n.col !== undefined && n.row !== undefined);
157
158 if (grid) {
159 for (const n of nodes) {
160 positions.set(n.id, {
161 x: PAD + n.col! * (NODE_W + COL_GAP),
162 y: PAD + n.row! * (NODE_H_TYPED + GRID_ROW_GAP),
163 h: NODE_H_TYPED,
164 });
165 }
166 } else if (direction === "LR") {
167 layers.forEach((col, ci) => {
168 const colH = colMaxHeight[ci]!;
169 let y = PAD + (tallest - colH) / 2;
170 for (const id of col) {
171 const h = heightOf(id);
172 positions.set(id, {
173 x: PAD + ci * (NODE_W + COL_GAP),
174 y,
175 h,
176 });
177 y += h + ROW_GAP;
178 }
179 });
180 } else {
181 // TB — swap roles: each "layer" becomes a row.
182 layers.forEach((row, ri) => {
183 const rowW = row.length * (NODE_W + COL_GAP) - COL_GAP;
184 const totalW = Math.max(
185 ...layers.map((r) => r.length * (NODE_W + COL_GAP) - COL_GAP),
186 );
187 let x = PAD + (totalW - rowW) / 2;
188 for (const id of row) {
189 const h = heightOf(id);
190 positions.set(id, {
191 x,
192 y: PAD + ri * (NODE_H_TYPED + 60),
193 h,
194 });
195 x += NODE_W + COL_GAP;
196 }
197 });
198 }
199
200 const hasBackEdge = edges.some(
201 (e) => (layerOf.get(e.to) ?? 0) <= (layerOf.get(e.from) ?? 0),
202 );
203 const BACK_EDGE_GUTTER = 56;
204
205 const gridCols = grid ? Math.max(...nodes.map((n) => n.col!)) + 1 : 0;
206 const gridRows = grid ? Math.max(...nodes.map((n) => n.row!)) + 1 : 0;
207
208 const W = grid
209 ? PAD * 2 + gridCols * NODE_W + (gridCols - 1) * COL_GAP
210 :
211 direction === "LR"
212 ? PAD * 2 +
213 layers.length * NODE_W +
214 (layers.length - 1) * COL_GAP +
215 (hasBackEdge ? BACK_EDGE_GUTTER : 0)
216 : PAD * 2 +
217 Math.max(...layers.map((r) => r.length * (NODE_W + COL_GAP) - COL_GAP));
218 const H = grid
219 ? PAD * 2 + gridRows * NODE_H_TYPED + (gridRows - 1) * GRID_ROW_GAP
220 :
221 direction === "LR"
222 ? PAD * 2 + tallest + (hasBackEdge ? BACK_EDGE_GUTTER : 0)
223 : PAD * 2 +
224 layers.length * (NODE_H_TYPED + 60) -
225 60 +
226 (hasBackEdge ? BACK_EDGE_GUTTER : 0);
227
228 // ---------- Edge geometry ----------
229
230 interface Edge {
231 d: string;
232 midX: number;
233 midY: number;
234 label?: string;
235 dashed?: boolean;
236 }
237
238 const TIP = 6;
239
240 const gridEdge = (e: EdgeIn): Edge => {
241 const a = positions.get(e.from)!;
242 const b = positions.get(e.to)!;
243 const done = (d: string, midX: number, midY: number): Edge => ({
244 d,
245 midX,
246 midY,
247 label: e.label,
248 dashed: e.dashed,
249 });
250 const ay = a.y + a.h / 2;
251 const by = b.y + b.h / 2;
252 if (a.y === b.y) {
253 // Along a row, either way.
254 const [x1, x2] = b.x > a.x ? [a.x + NODE_W, b.x - TIP] : [a.x, b.x + NODE_W + TIP];
255 return done(`M ${x1} ${ay} L ${x2} ${by}`, (x1 + x2) / 2, ay);
256 }
257 const ax = a.x + NODE_W / 2;
258 if (a.x === b.x) {
259 // Along a column, either way.
260 const [y1, y2] = b.y > a.y ? [a.y + a.h, b.y - TIP] : [a.y, b.y + b.h + TIP];
261 return done(`M ${ax} ${y1} L ${ax} ${y2}`, ax, (y1 + y2) / 2);
262 }
263 // An elbow: leave from the top or bottom, then run across into the target's side.
264 const y1 = b.y > a.y ? a.y + a.h : a.y;
265 const x2 = b.x > a.x ? b.x - TIP : b.x + NODE_W + TIP;
266 return done(`M ${ax} ${y1} L ${ax} ${by} L ${x2} ${by}`, (ax + x2) / 2, by);
267 };
268
269 const buildEdges = (): Edge[] =>
270 edges.map((e) => {
271 if (grid) return gridEdge(e);
272 const a = positions.get(e.from)!;
273 const b = positions.get(e.to)!;
274 const aLayer = layerOf.get(e.from)!;
275 const bLayer = layerOf.get(e.to)!;
276 const isBack =
277 direction === "LR" ? bLayer <= aLayer : bLayer <= aLayer;
278
279 if (direction === "LR") {
280 if (!isBack) {
281 // Forward edge — straight cubic from source.right to target.left.
282 const x1 = a.x + NODE_W;
283 const y1 = a.y + a.h / 2;
284 const x2 = b.x - TIP;
285 const y2 = b.y + b.h / 2;
286 const cx = x1 + (x2 - x1) * 0.5;
287 const d = `M ${x1} ${y1} C ${cx} ${y1}, ${cx} ${y2}, ${x2} ${y2}`;
288 return {
289 d,
290 midX: (x1 + x2) / 2,
291 midY: (y1 + y2) / 2,
292 label: e.label,
293 dashed: e.dashed,
294 };
295 }
296 // Back-edge — arc beneath both nodes from source.bottom to target.bottom
297 // so arrow remains visibly between/under the nodes (not behind them).
298 const x1 = a.x + NODE_W * 0.5;
299 const y1 = a.y + a.h;
300 const x2 = b.x + NODE_W * 0.5;
301 const y2 = b.y + b.h + TIP;
302 const dropMax = 36;
303 const cy = Math.max(y1, y2) + dropMax;
304 const d = `M ${x1} ${y1} C ${x1} ${cy}, ${x2} ${cy}, ${x2} ${y2}`;
305 return {
306 d,
307 midX: (x1 + x2) / 2,
308 midY: cy,
309 label: e.label,
310 dashed: e.dashed,
311 };
312 }
313
314 // TB direction.
315 if (!isBack) {
316 const x1 = a.x + NODE_W / 2;
317 const y1 = a.y + a.h;
318 const x2 = b.x + NODE_W / 2;
319 const y2 = b.y - TIP;
320 const cy = y1 + (y2 - y1) * 0.5;
321 const d = `M ${x1} ${y1} C ${x1} ${cy}, ${x2} ${cy}, ${x2} ${y2}`;
322 return {
323 d,
324 midX: (x1 + x2) / 2,
325 midY: (y1 + y2) / 2,
326 label: e.label,
327 dashed: e.dashed,
328 };
329 }
330 // TB back-edge — arc to the right.
331 const x1 = a.x + NODE_W;
332 const y1 = a.y + a.h / 2;
333 const x2 = b.x + NODE_W + TIP;
334 const y2 = b.y + b.h / 2;
335 const dx = 36;
336 const cx = Math.max(x1, x2) + dx;
337 const d = `M ${x1} ${y1} C ${cx} ${y1}, ${cx} ${y2}, ${x2} ${y2}`;
338 return {
339 d,
340 midX: cx,
341 midY: (y1 + y2) / 2,
342 label: e.label,
343 dashed: e.dashed,
344 };
345 });
346
347 const edgeShapes = buildEdges();
348 ---
349
350 <figure class="alc-dag not-content" data-nosnippet>
351 <svg
352 class="alc-dag__svg"
353 viewBox={`0 0 ${W} ${H}`}
354 role="img"
355 aria-label={caption ?? "Dependency graph"}
356 >
357 <defs>
358 <marker
359 id="alc-dag-arrow"
360 viewBox="0 0 10 10"
361 refX="8"
362 refY="5"
363 markerWidth="6"
364 markerHeight="6"
365 orient="auto-start-reverse"
366 >
367 <path d="M 0 0 L 10 5 L 0 10 z" fill="var(--alc-accent)" />
368 </marker>
369 </defs>
370
371 {/* Edges first so they sit beneath nodes. */}
372 {edgeShapes.map((e) => (
373 <g class="alc-dag__edge">
374 <path
375 d={e.d}
376 fill="none"
377 stroke="var(--alc-accent-60)"
378 stroke-width="1.5"
379 stroke-dasharray={e.dashed ? "4 4" : undefined}
380 marker-end="url(#alc-dag-arrow)"
381 />
382 {e.label && (
383 <text
384 x={e.midX}
385 y={e.midY - 6}
386 class="alc-dag__edge-label"
387 text-anchor="middle"
388 >
389 {e.label}
390 </text>
391 )}
392 </g>
393 ))}
394
395 {/* Nodes. */}
396 {nodes.map((n) => {
397 const p = positions.get(n.id)!;
398 const tone = n.tone ?? "default";
399 if (n.kind) {
400 return (
401 <g transform={`translate(${p.x}, ${p.y})`}>
402 <DomainNode
403 kind={n.kind}
404 width={NODE_W}
405 height={p.h}
406 label={n.label ?? n.id}
407 type={n.type}
408 />
409 </g>
410 );
411 }
412 return (
413 <g class={`alc-dag__node alc-dag__node--${tone}`} transform={`translate(${p.x}, ${p.y})`}>
414 <rect
415 width={NODE_W}
416 height={p.h}
417 rx="8"
418 ry="8"
419 class="alc-dag__node-bg"
420 />
421 <text
422 x={NODE_W / 2}
423 y={n.type ? p.h / 2 - 4 : p.h / 2 + 1}
424 class="alc-dag__node-label"
425 text-anchor="middle"
426 dominant-baseline="middle"
427 >
428 {n.label ?? n.id}
429 </text>
430 {n.type && (
431 <text
432 x={NODE_W / 2}
433 y={p.h / 2 + 14}
434 class="alc-dag__node-type"
435 text-anchor="middle"
436 dominant-baseline="middle"
437 >
438 {n.type}
439 </text>
440 )}
441 </g>
442 );
443 })}
444 </svg>
445
446 {
447 kindsShown.length > 0 && (
448 <div class="alc-dag__legend">
449 {kindsShown.map((k) => (
450 <span class="alc-dag__key">
451 <DomainIcon kind={k} />
452 {KINDS[k].name}
453 </span>
454 ))}
455 </div>
456 )
457 }
458 {caption && <figcaption class="alc-dag__caption">{caption}</figcaption>}
459 </figure>
460
461 <style>
462 .alc-dag {
463 margin: 1.5rem 0;
464 background: var(--alc-bg-elev-1);
465 border: 1px solid var(--alc-hairline-2);
466 border-radius: var(--alc-radius);
467 padding: 0.75rem;
468 overflow-x: auto;
469 }
470
471 .alc-dag__svg {
472 display: block;
473 width: 100%;
474 height: auto;
475 max-width: 100%;
476 }
477
478 .alc-dag__node-bg {
479 fill: var(--alc-bg-elev-2);
480 stroke: var(--alc-accent-40);
481 stroke-width: 1.5;
482 transition: stroke 200ms ease, fill 200ms ease;
483 }
484
485 .alc-dag__node--accent .alc-dag__node-bg {
486 stroke: var(--alc-accent);
487 fill: color-mix(in srgb, var(--alc-accent-soft) 60%, var(--alc-bg-elev-2));
488 }
489
490 .alc-dag__node--warn .alc-dag__node-bg {
491 stroke: var(--alc-warn);
492 fill: color-mix(in srgb, var(--alc-warn) 12%, var(--alc-bg-elev-2));
493 }
494
495 .alc-dag__node--danger .alc-dag__node-bg {
496 stroke: var(--alc-danger);
497 fill: color-mix(in srgb, var(--alc-danger) 10%, var(--alc-bg-elev-2));
498 }
499
500
501
502 .alc-dag__legend {
503 display: flex;
504 flex-wrap: wrap;
505 justify-content: center;
506 gap: 0.35rem 1rem;
507 margin-top: 0.5rem;
508 font-family: var(--alc-font-mono);
509 font-size: 11.5px;
510 color: var(--alc-fg-3);
511 }
512
513 .alc-dag__key {
514 display: inline-flex;
515 align-items: center;
516 gap: 0.4rem;
517 }
518
519
520 .alc-dag__node-label {
521 font-family: var(--alc-font-mono);
522 font-size: 13px;
523 font-weight: 600;
524 fill: var(--alc-fg-1);
525 }
526
527 .alc-dag__node-type {
528 font-family: var(--alc-font-mono);
529 font-size: 10.5px;
530 fill: var(--alc-fg-3);
531 }
532
533 .alc-dag__edge-label {
534 font-family: var(--alc-font-mono);
535 font-size: 10.5px;
536 fill: var(--alc-fg-3);
537 }
538
539 .alc-dag__caption {
540 margin-top: 0.5rem;
541 font-family: var(--alc-font-sans);
542 font-size: 13px;
543 color: var(--alc-fg-3);
544 text-align: center;
545 }
546 </style>