Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.
HTML agent-skillsai-agentsarchitecture-diagramclaude-codeclaude-skillscodexcoding-agentsdeepseek-harnessdeveloper-toolsdiagramsdiagrams-as-codedsh-pluginflowchartllmmermaidopencodesequence-diagramsoftware-architecturesystem-designvisualization
feat: architecture grid placement and layout inspect (#8, #9)
tt-a1i5fe0ec8aef59
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 798d95c1..abdf19e2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,8 +5,8 @@ All notable changes are documented here. Format loosely follows [Keep a Changelo## [Unreleased]### Added-- **Layout principles in SKILL.md** — main-path-first guidance, side-branch rules, and pointers to `archify-repo` / `maka-architecture` examples.-- **Validator fix suggestions (#7)** — label overlap and component proximity errors now include rects plus concrete `labelAt` / `labelDy` or `pos` nudges.+- **Architecture grid placement (#8).** Optional `layout.mode: "grid"` with `row`/`col` per component; explicit `pos` still overrides a cell. Example: `examples/archify-repo-grid.architecture.json`.+- **Layout inspect (#9).** `archify inspect architecture <file.json>` (alias: `validate --layout-json`) prints computed component rects, boundaries, connection paths, and label boxes as JSON.## [2.9.0] — 2026-07-05diff --git a/README.md b/README.mdindex 2c8904d6..bbd1b351 100644--- a/README.md+++ b/README.md@@ -61,6 +61,7 @@ Sample SaaS diagram: [`examples/web-app.html`](examples/web-app.html).Real-repo examples (renderer-backed JSON IR):- [`examples/archify-repo.html`](examples/archify-repo.html) — this project's skill → JSON IR → renderers pipeline+- [`examples/archify-repo-grid.html`](examples/archify-repo-grid.html) — same pipeline with `layout.mode: "grid"` (`row`/`col` placement)- [`examples/maka-architecture.html`](examples/maka-architecture.html) — third-party desktop agent workbench (Maka)Workflow is not trying to replace every general-purpose flowchart. It is a technical communication diagram: swimlanes, semantic colors, a clear happy path, and secondary async / approval / trace paths.diff --git a/archify.zip b/archify.zipindex ed52c150..992b55ff 100644Binary files a/archify.zip and b/archify.zip differdiff --git a/archify/SKILL.md b/archify/SKILL.mdindex e823a340..93615e7f 100644--- a/archify/SKILL.md+++ b/archify/SKILL.md@@ -204,11 +204,37 @@ Architecture has the same read-schema-then-render loop as the other modes — pr}```-Render: `node renderers/architecture/render-architecture.mjs <input>.json <output>.html`.+Render: `node bin/archify.mjs render architecture <input>.json <output>.html`.++**Free placement** — `pos: [x, y]` is the component's top-left; `size: [w, h]` defaults to `[120, 60]`. Unlike typed modes there is no lane/stage grid — asymmetric placement is yours to choose. `meta.viewBox` is optional (auto-fitted).++**Grid placement (#8)** — when manual coordinates are painful, set semantic cells instead of doing arithmetic:++```json+{+ "layout": { "mode": "grid", "cols": 7, "origin": [40, 100], "gapX": 24, "gapY": 48, "cellW": 120, "cellH": 60 },+ "components": [+ { "id": "agents", "type": "frontend", "label": "Agent Hosts", "row": 1, "col": 1 },+ { "id": "ir", "type": "messagebus", "label": "JSON IR", "row": 1, "col": 2 }+ ]+}+```++`pos` still wins when present (override one cell). This is **not** auto-layout — spacing is fixed cell math. Example: `examples/archify-repo-grid.architecture.json`.++**Inspect layout (#9)** — after editing JSON, dump computed boxes without opening HTML:++```bash+node bin/archify.mjs inspect architecture my.architecture.json+# or: node bin/archify.mjs validate architecture my.architecture.json --layout-json+```++Output includes component rects, boundaries, connection point paths, and label positions.**The renderer does the mechanical work that used to be hand-tuned**, so you only choose coordinates and meaning:- **Free coordinates** — `pos: [x, y]` is the component's top-left; `size: [w, h]` defaults to `[120, 60]`. Unlike the typed modes there is no lane/stage grid — asymmetric placement is yours to choose. `meta.viewBox` is optional (auto-fitted to your components + a legend row).+- **Grid placement** — optional `layout.mode: "grid"` with `row`/`col` per component (see above). Not dagre; fixed cell spacing only.- **Boundaries from `wraps`** — list the component ids a `region` (dashed amber) or `security-group` (dashed rose) encloses; the renderer computes the box with correct 30/50 padding automatically. Never hand-arithmetic a boundary again.- **Connections** route like edges (`variant`, `fromSide`/`toSide`, `route: straight|orthogonal-h|orthogonal-v|auto`, `via`, `labelDx/labelDy/labelAt`). For a vertical labeled connection, push the label into the gap with `labelDy` (the validator will tell you if it lands on a box).- The renderer auto-emits the two-rect `c-mask` pattern, draws arrows before boxes (z-order), builds the legend from the component types you used, and **fails fast on component overlap, off-canvas components/boundaries, unknown wraps/connection ids, label-vs-component collisions, and non-finite coordinates** — the same reliability the other four modes already had.diff --git a/archify/bin/archify.mjs b/archify/bin/archify.mjsindex f060d3d8..00a01f2e 100755--- a/archify/bin/archify.mjs+++ b/archify/bin/archify.mjs@@ -14,7 +14,8 @@ const TYPES = new Set(['architecture', 'workflow', 'sequence', 'dataflow', 'lifefunction usage() {return `Usage:archify render <type> <input.json> [output.html]- archify validate <type> <input.json> [--json]+ archify validate <type> <input.json> [--json] [--layout-json]+ archify inspect <type> <input.json>archify check <output.html>archify examples@@ -69,10 +70,25 @@ function commandExamples() {function commandValidate(args) {const json = args.includes('--json');- const rest = args.filter((arg) => arg !== '--json');+ const layoutJson = args.includes('--layout-json');+ const rest = args.filter((arg) => arg !== '--json' && arg !== '--layout-json');const [type, input] = rest;if (!type || !input) fail(usage());+ if (layoutJson) {+ if (type !== 'architecture') {+ fail('--layout-json is currently supported for architecture diagrams only.');+ }+ const result = runNode([rendererPath(type), input, '/dev/null', '--layout-json'], { stdio: 'pipe' });+ if (result.status !== 0) {+ if (result.stderr) process.stderr.write(result.stderr);+ if (result.stdout) process.stdout.write(result.stdout);+ process.exit(result.status ?? 1);+ }+ process.stdout.write(result.stdout);+ return;+ }+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-validate-'));const out = path.join(tmp, `${type}.html`);let exitCode = 0;@@ -125,6 +141,9 @@ switch (command) {case 'validate':commandValidate(args);break;+ case 'inspect':+ commandValidate([...args, '--layout-json']);+ break;case 'check':commandCheck(args);break;diff --git a/archify/renderers/architecture/grid.mjs b/archify/renderers/architecture/grid.mjsnew file mode 100644index 00000000..ce0003f6--- /dev/null+++ b/archify/renderers/architecture/grid.mjs@@ -0,0 +1,62 @@+/** Grid placement for architecture IR (#8). Not auto-layout — fixed cell math only. */++export const DEFAULT_GRID = {+ mode: 'grid',+ origin: [40, 80],+ cols: 4,+ gapX: 30,+ gapY: 40,+ cellW: 130,+ cellH: 64,+};++export function gridLayout(arch) {+ const raw = arch.layout;+ if (!raw || raw.mode !== 'grid') return null;+ return { ...DEFAULT_GRID, ...raw };+}++export function resolveComponentPos(component, grid) {+ if (Array.isArray(component.pos) && component.pos.length === 2) {+ return component.pos;+ }+ if (!grid) return [NaN, NaN];+ if (!Number.isInteger(component.row) || !Number.isInteger(component.col)) {+ return [NaN, NaN];+ }+ const [ox, oy] = grid.origin;+ const stepX = grid.cellW + grid.gapX;+ const stepY = grid.cellH + grid.gapY;+ return [ox + component.col * stepX, oy + component.row * stepY];+}++export function validateGridPlacement(arch, grid, problems) {+ if (!grid) return;+ if (arch.layout !== undefined && arch.layout.mode !== 'grid') {+ problems.push('layout.mode must be "grid" when layout is set (free placement omits layout entirely).');+ return;+ }+ const seen = new Map();+ for (const c of arch.components ?? []) {+ const hasPos = Array.isArray(c.pos) && c.pos.length === 2;+ const hasCell = Number.isInteger(c.row) && Number.isInteger(c.col);+ if (hasPos && hasCell) continue; // pos wins; row/col are hints only+ if (!hasPos && !hasCell) {+ problems.push(`Component "${c.id}" needs pos [x,y] or grid row/col when layout.mode is "grid".`);+ continue;+ }+ if (c.row < 0 || c.col < 0) {+ problems.push(`Component "${c.id}" row/col must be non-negative integers.`);+ continue;+ }+ if (c.col >= grid.cols) {+ problems.push(`Component "${c.id}" col ${c.col} exceeds layout.cols ${grid.cols} (valid: 0..${grid.cols - 1}).`);+ }+ const key = `${c.row},${c.col}`;+ if (seen.has(key)) {+ problems.push(`Components "${seen.get(key)}" and "${c.id}" share grid cell row ${c.row} col ${c.col}.`);+ } else {+ seen.set(key, c.id);+ }+ }+}diff --git a/archify/renderers/architecture/render-architecture.mjs b/archify/renderers/architecture/render-architecture.mjsindex bf1b7eda..2b52d20f 100644--- a/archify/renderers/architecture/render-architecture.mjs+++ b/archify/renderers/architecture/render-architecture.mjs@@ -2,6 +2,8 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';import { esc, renderDefinitions, textUnits } from '../shared/utils.mjs';import { animateAttr, loadDiagram, writeDiagram, svgRootAttrs } from '../shared/cli.mjs';+import { componentBox, boundaryBox, connectionPath } from '../shared/layout-report.mjs';+import { gridLayout, resolveComponentPos, validateGridPlacement } from './grid.mjs';import {asArray,isFinitePoint,@@ -22,12 +24,17 @@ import {} from '../shared/geometry.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));+const layoutJsonMode = process.argv.includes('--layout-json');+const cliArgs = process.argv.filter((arg) => arg !== '--layout-json');const { diagram: arch, template, outPath } = loadDiagram({rendererDir: __dirname,diagramType: 'architecture',defaultExample: 'web-app.architecture.json',+ argv: cliArgs,});+const grid = gridLayout(arch);+const layout = {defaultW: 120,defaultH: 60,@@ -41,7 +48,7 @@ const layout = {// ---- Measure components from free coordinates --------------------------------function measureComponent(c) {- const [x, y] = Array.isArray(c.pos) ? c.pos : [NaN, NaN];+ const [x, y] = resolveComponentPos(c, grid);const [w, h] = Array.isArray(c.size) ? c.size : [layout.defaultW, layout.defaultH];return { ...c, x, y, width: w, height: h, cx: x + w / 2, cy: y + h / 2 };}@@ -110,8 +117,14 @@ function validateArchitecture() {if (arch.boundaries !== undefined && !Array.isArray(arch.boundaries)) problems.push('Architecture "boundaries" must be an array.');if (arch.cards !== undefined && !Array.isArray(arch.cards)) problems.push('Architecture "cards" must be an array.');if (components.size !== asArray(arch.components).length) problems.push('Component ids must be unique.');- if (problems.length) {- throw new Error(`Architecture layout validation failed:\n- ${problems.join('\n- ')}`);+ if (grid) {+ validateGridPlacement(arch, grid, problems);+ } else {+ for (const c of asArray(arch.components)) {+ if (!Array.isArray(c.pos) || c.pos.length !== 2) {+ problems.push(`Component "${c.id}" must include pos [x, y] when layout.mode is omitted (free placement).`);+ }+ }}for (const c of components.values()) {@@ -182,6 +195,39 @@ function validateArchitecture() {}}+function buildLayoutReport() {+ const labels = [];+ for (const conn of asArray(arch.connections)) {+ if (!conn.label || !components.has(conn.from) || !components.has(conn.to)) continue;+ const [lx, ly] = labelPoint(conn, pathFor(conn).points);+ const w = Math.max(30, textUnits(conn.label) * 4.8 + 10);+ labels.push({+ text: conn.label,+ x: Math.round(lx - w / 2),+ y: Math.round(ly - 10),+ width: Math.round(w),+ height: 14,+ labelAt: [Math.round(lx), Math.round(ly)],+ });+ }+ return {+ ok: true,+ diagram_type: 'architecture',+ layout: grid ? { mode: 'grid', ...grid } : { mode: 'free' },+ viewBox,+ components: [...components.values()].map(componentBox),+ boundaries: boundaries.map(boundaryBox),+ connections: asArray(arch.connections)+ .filter((conn) => components.has(conn.from) && components.has(conn.to))+ .map((conn) => {+ const routed = pathFor(conn);+ const labelAt = conn.label ? labelPoint(conn, routed.points) : null;+ return connectionPath(conn, routed, labelAt);+ }),+ labels,+ };+}+// ---- Connection routing ------------------------------------------------------function routeVia(conn, from, to, start, end) {if (conn.via) return conn.via;@@ -307,6 +353,10 @@ ${renderLegend()}}validateArchitecture();+if (layoutJsonMode) {+ console.log(JSON.stringify(buildLayoutReport(), null, 2));+ process.exit(0);+}writeDiagram({outPath,template,diff --git a/archify/renderers/shared/cli.mjs b/archify/renderers/shared/cli.mjsindex a4fd8fc6..d4fc122f 100644--- a/archify/renderers/shared/cli.mjs+++ b/archify/renderers/shared/cli.mjs@@ -4,15 +4,15 @@ import { applyTemplate, renderCards, esc } from './utils.mjs';import { validateSchema } from './validator.mjs';// Common CLI head: node render-<type>.mjs [input.json] [output.html]-export function loadDiagram({ rendererDir, diagramType, defaultExample }) {+export function loadDiagram({ rendererDir, diagramType, defaultExample, argv = process.argv }) {const skillRoot = path.resolve(rendererDir, '../..');- const inputPath = path.resolve(process.argv[2] || path.join(skillRoot, 'examples', defaultExample));+ const inputPath = path.resolve(argv[2] || path.join(skillRoot, 'examples', defaultExample));const diagram = JSON.parse(fs.readFileSync(inputPath, 'utf8'));validateSchema(diagramType, diagram);const template = fs.readFileSync(path.join(skillRoot, 'assets/template.html'), 'utf8');// Optional chaining: in degraded mode (no ajv) malformed input must still// reach the renderer's friendly layout checks instead of crashing here.- const outPath = path.resolve(process.cwd(), process.argv[3] || diagram.meta?.output || `${diagramType}.html`);+ const outPath = path.resolve(process.cwd(), argv[3] || diagram.meta?.output || `${diagramType}.html`);return { diagram, template, outPath };}diff --git a/archify/renderers/shared/layout-report.mjs b/archify/renderers/shared/layout-report.mjsnew file mode 100644index 00000000..3128a65a--- /dev/null+++ b/archify/renderers/shared/layout-report.mjs@@ -0,0 +1,40 @@+/** Serialize computed layout for dry-run / inspect (#9). */++export function componentBox(c) {+ return {+ id: c.id,+ type: c.type,+ label: c.label,+ x: Math.round(c.x),+ y: Math.round(c.y),+ width: c.width,+ height: c.height,+ ...(Number.isInteger(c.row) ? { row: c.row } : {}),+ ...(Number.isInteger(c.col) ? { col: c.col } : {}),+ ...(Array.isArray(c.pos) ? { pos: c.pos.map(Math.round) } : {}),+ };+}++export function boundaryBox(b) {+ return {+ kind: b.kind,+ label: b.label,+ x: Math.round(b.x),+ y: Math.round(b.y),+ width: Math.round(b.width),+ height: Math.round(b.height),+ wraps: b.wraps,+ };+}++export function connectionPath(conn, routed, labelAt) {+ return {+ from: conn.from,+ to: conn.to,+ label: conn.label ?? null,+ variant: conn.variant ?? 'default',+ route: conn.route ?? 'auto',+ points: routed.points.map(([x, y]) => [Math.round(x), Math.round(y)]),+ ...(labelAt ? { labelAt: labelAt.map(Math.round) } : {}),+ };+}diff --git a/archify/schemas/architecture.schema.json b/archify/schemas/architecture.schema.jsonindex 73abb915..710c1e75 100644--- a/archify/schemas/architecture.schema.json+++ b/archify/schemas/architecture.schema.json@@ -29,19 +29,35 @@}}},+ "layout": {+ "type": "object",+ "additionalProperties": false,+ "required": ["mode"],+ "properties": {+ "mode": { "enum": ["grid"] },+ "origin": { "$ref": "common.schema.json#/$defs/point" },+ "cols": { "type": "integer", "minimum": 1, "maximum": 12 },+ "gapX": { "type": "number", "minimum": 0 },+ "gapY": { "type": "number", "minimum": 0 },+ "cellW": { "type": "number", "minimum": 40 },+ "cellH": { "type": "number", "minimum": 24 }+ }+ },"components": {"type": "array","minItems": 1,"items": {"type": "object","additionalProperties": false,- "required": ["id", "type", "label", "pos"],+ "required": ["id", "type", "label"],"properties": {"id": { "$ref": "common.schema.json#/$defs/id" },"type": { "$ref": "common.schema.json#/$defs/componentType" },"label": { "type": "string", "minLength": 1 },"sublabel": { "type": "string" },"tag": { "type": "string" },+ "row": { "type": "integer", "minimum": 0 },+ "col": { "type": "integer", "minimum": 0 },"pos": { "$ref": "common.schema.json#/$defs/point" },"size": { "$ref": "common.schema.json#/$defs/point" }}diff --git a/archify/test/cli.test.mjs b/archify/test/cli.test.mjsindex 8a1f2086..ad790651 100644--- a/archify/test/cli.test.mjs+++ b/archify/test/cli.test.mjs@@ -57,6 +57,18 @@ test('cli: validate emits structured json without keeping html output', () => {assert.deepEqual(new Set(fs.readdirSync(tmp)), before);});+test('cli: inspect emits architecture layout json', () => {+ const input = path.resolve(skillRoot, '../examples/archify-repo-grid.architecture.json');+ const result = run(['inspect', 'architecture', input]);+ assert.equal(result.status, 0, result.stderr);+ const parsed = JSON.parse(result.stdout);+ assert.equal(parsed.ok, true);+ assert.equal(parsed.diagram_type, 'architecture');+ assert.equal(parsed.layout.mode, 'grid');+ assert.ok(parsed.components.length >= 5);+ assert.ok(parsed.connections.length >= 1);+});+test('cli: validate returns renderer errors for bad input', () => {const input = path.join(tmp, 'bad.workflow.json');const validateTmp = path.join(tmp, 'validate-failure-tmp');diff --git a/archify/test/grid.test.mjs b/archify/test/grid.test.mjsnew file mode 100644index 00000000..33f69520--- /dev/null+++ b/archify/test/grid.test.mjs@@ -0,0 +1,35 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { gridLayout, resolveComponentPos, validateGridPlacement } from '../renderers/architecture/grid.mjs';++test('gridLayout returns null for free placement', () => {+ assert.equal(gridLayout({}), null);+ assert.equal(gridLayout({ layout: undefined }), null);+});++test('resolveComponentPos prefers explicit pos over row/col', () => {+ const grid = gridLayout({ layout: { mode: 'grid' } });+ assert.deepEqual(resolveComponentPos({ pos: [9, 8], row: 0, col: 0 }, grid), [9, 8]);+});++test('resolveComponentPos maps row/col to pixel origin', () => {+ const grid = gridLayout({+ layout: { mode: 'grid', origin: [40, 80], gapX: 30, gapY: 40, cellW: 130, cellH: 64 },+ });+ assert.deepEqual(resolveComponentPos({ row: 0, col: 0 }, grid), [40, 80]);+ assert.deepEqual(resolveComponentPos({ row: 1, col: 2 }, grid), [40 + 2 * 160, 80 + 104]);+});++test('validateGridPlacement rejects duplicate cells and missing row/col', () => {+ const grid = gridLayout({ layout: { mode: 'grid', cols: 4 } });+ const problems = [];+ validateGridPlacement({+ components: [+ { id: 'a', row: 0, col: 0 },+ { id: 'b', row: 0, col: 0 },+ { id: 'c' },+ ],+ }, grid, problems);+ assert.ok(problems.some((p) => p.includes('share grid cell')));+ assert.ok(problems.some((p) => p.includes('"c" needs pos')));+});diff --git a/examples/archify-repo-grid.architecture.json b/examples/archify-repo-grid.architecture.jsonnew file mode 100644index 00000000..92199351--- /dev/null+++ b/examples/archify-repo-grid.architecture.json@@ -0,0 +1,57 @@+{+ "schema_version": 1,+ "diagram_type": "architecture",+ "meta": {+ "title": "Archify Pipeline",+ "subtitle": "Grid placement demo — row/col instead of manual pos",+ "output": "examples/archify-repo-grid.html"+ },+ "layout": {+ "mode": "grid",+ "origin": [40, 100],+ "cols": 7,+ "gapX": 24,+ "gapY": 48,+ "cellW": 120,+ "cellH": 60+ },+ "components": [+ { "id": "user", "type": "external", "label": "You", "sublabel": "NL / Mermaid", "row": 1, "col": 0 },+ { "id": "agents", "type": "frontend", "label": "Agent Hosts", "sublabel": "Claude · Codex", "row": 1, "col": 1 },+ { "id": "skill", "type": "frontend", "label": "SKILL.md", "sublabel": "layout rules", "row": 0, "col": 1 },+ { "id": "ir", "type": "messagebus", "label": "JSON IR", "sublabel": "schema v1", "row": 1, "col": 2 },+ { "id": "schemas", "type": "security", "label": "Schema", "sublabel": "ajv", "row": 0, "col": 2 },+ { "id": "renderers", "type": "backend", "label": "Renderers ×5", "row": 1, "col": 3 },+ { "id": "template", "type": "frontend", "label": "template.html", "row": 1, "col": 4 },+ { "id": "checker", "type": "security", "label": "Output Check", "row": 1, "col": 5 },+ { "id": "html", "type": "cloud", "label": "HTML", "sublabel": "artifact", "row": 1, "col": 6 }+ ],+ "boundaries": [+ {+ "kind": "region",+ "label": "archify/ skill package",+ "wraps": ["ir", "schemas", "renderers", "template", "checker"]+ }+ ],+ "connections": [+ { "from": "user", "to": "agents", "variant": "emphasis" },+ { "from": "agents", "to": "skill", "fromSide": "top", "toSide": "bottom" },+ { "from": "agents", "to": "ir", "variant": "emphasis" },+ { "from": "ir", "to": "schemas", "variant": "security", "fromSide": "top", "toSide": "bottom" },+ { "from": "ir", "to": "renderers", "variant": "emphasis" },+ { "from": "renderers", "to": "template", "variant": "emphasis" },+ { "from": "template", "to": "checker", "variant": "emphasis" },+ { "from": "checker", "to": "html", "variant": "emphasis" }+ ],+ "cards": [+ {+ "dot": "cyan",+ "title": "Grid mode",+ "items": [+ "Set layout.mode grid and place components with row/col",+ "pos still overrides a cell when you need fine tuning",+ "Not auto-layout — fixed cell spacing only"+ ]+ }+ ]+}diff --git a/examples/archify-repo-grid.html b/examples/archify-repo-grid.htmlnew file mode 100644index 00000000..c440d692--- /dev/null+++ b/examples/archify-repo-grid.html@@ -0,0 +1,1190 @@+<!DOCTYPE html>+<html lang="en" data-theme="dark">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <meta name="generator" content="archify 2.9.0">+ <title>Archify Pipeline Diagram</title>+ <script>+ // Resolve the theme before first paint so light-preference users don't+ // see a dark flash. The toolbar script below re-applies with UI state.+ (function () {+ try {+ var theme = null;+ try {+ var param = new URLSearchParams(window.location.search).get('theme');+ if (param === 'light' || param === 'dark') theme = param;+ } catch (_) {}+ if (!theme) {+ try { theme = localStorage.getItem('archify-theme'); } catch (_) {}+ }+ if (theme !== 'light' && theme !== 'dark') {+ theme = window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';+ }+ document.documentElement.setAttribute('data-theme', theme);+ } catch (_) {}+ })();+ </script>+ <!-- Async font load: a blackholed network must not block first paint.+ The body font stack falls back to system monospace until it lands. -->+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>+ <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600;700&display=swap"+ rel="stylesheet" media="print" onload="this.media='all'">+ <noscript>+ <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600;700&display=swap" rel="stylesheet">+ </noscript>+ <style>+ /* ==========================================================+ THEME VARIABLES — switch by toggling [data-theme] on <html>+ ========================================================== */+ :root,+ [data-theme="dark"] {+ --bg: #020617;+ --grid: #1e293b;+ --text: #ffffff;+ --text-muted: #94a3b8;+ --text-dim: #475569;+ /* UI chrome (menu hints, footer) needs more contrast than SVG .t-dim accents */+ --text-faint: #7d8da1;++ --panel: rgba(15, 23, 42, 0.5);+ --panel-border: #1e293b;+ --lane-fill: rgba(15, 23, 42, 0.22);+ --lane-stroke: #334155;++ --arrow: #64748b;+ --arrow-emphasis: #34d399;++ /* Opaque mask color used behind semi-transparent component fills+ so the arrows drawn underneath are properly hidden. */+ --mask: #0f172a;++ --frontend-fill: rgba(8, 51, 68, 0.4);+ --frontend-stroke: #22d3ee;+ --backend-fill: rgba(6, 78, 59, 0.4);+ --backend-stroke: #34d399;+ --database-fill: rgba(76, 29, 149, 0.4);+ --database-stroke: #a78bfa;+ --cloud-fill: rgba(120, 53, 15, 0.3);+ --cloud-stroke: #fbbf24;+ --security-fill: rgba(136, 19, 55, 0.4);+ --security-stroke: #fb7185;+ --messagebus-fill: rgba(251, 146, 60, 0.3);+ --messagebus-stroke:#fb923c;+ --external-fill: rgba(30, 41, 59, 0.5);+ --external-stroke: #94a3b8;++ --toolbar-bg: rgba(15, 23, 42, 0.8);+ --toolbar-border: #334155;+ --toolbar-text: #e2e8f0;+ --toolbar-hover: rgba(15, 23, 42, 0.95);+ --toolbar-menu-bg: #0f172a;+ }++ [data-theme="light"] {+ --bg: #f8fafc;+ --grid: #e2e8f0;+ --text: #0f172a;+ --text-muted: #64748b;+ --text-dim: #94a3b8;+ --text-faint: #64748b;++ --panel: #ffffff;+ --panel-border: #e2e8f0;+ --lane-fill: rgba(248, 250, 252, 0.65);+ --lane-stroke: #cbd5e1;++ --arrow: #94a3b8;+ --arrow-emphasis: #059669;++ --mask: #ffffff;++ --frontend-fill: rgba(34, 211, 238, 0.15);+ --frontend-stroke: #0891b2;+ --backend-fill: rgba(52, 211, 153, 0.18);+ --backend-stroke: #059669;+ --database-fill: rgba(167, 139, 250, 0.2);+ --database-stroke: #7c3aed;+ --cloud-fill: rgba(251, 191, 36, 0.18);+ --cloud-stroke: #d97706;+ --security-fill: rgba(251, 113, 133, 0.15);+ --security-stroke: #e11d48;+ --messagebus-fill: rgba(251, 146, 60, 0.15);+ --messagebus-stroke:#ea580c;+ --external-fill: rgba(148, 163, 184, 0.18);+ --external-stroke: #64748b;++ --toolbar-bg: rgba(255, 255, 255, 0.92);+ --toolbar-border: #cbd5e1;+ --toolbar-text: #334155;+ --toolbar-hover: #ffffff;+ --toolbar-menu-bg: #ffffff;+ }++ * { margin: 0; padding: 0; box-sizing: border-box; }++ body {+ font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, 'DejaVu Sans Mono', 'Liberation Mono', 'Noto Sans Mono CJK SC', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', monospace;+ background: var(--bg);+ min-height: 100vh;+ padding: 2rem;+ color: var(--text);+ transition: background 0.2s ease, color 0.2s ease;+ }++ .container { max-width: 1200px; margin: 0 auto; }++ .header { margin-bottom: 2rem; }++ .header-row {+ display: flex;+ align-items: center;+ gap: 1rem;+ margin-bottom: 0.5rem;+ }++ .pulse-dot {+ width: 12px;+ height: 12px;+ background: var(--frontend-stroke);+ border-radius: 50%;+ animation: pulse 2s infinite;+ }++ @keyframes pulse {+ 0%, 100% { opacity: 1; }+ 50% { opacity: 0.5; }+ }++ h1 {+ font-size: 1.5rem;+ font-weight: 700;+ letter-spacing: -0.025em;+ }++ .subtitle {+ color: var(--text-muted);+ font-size: 0.875rem;+ margin-left: 1.75rem;+ }++ .diagram-container {+ background: var(--panel);+ border-radius: 1rem;+ border: 1px solid var(--panel-border);+ padding: 1.5rem;+ overflow-x: auto;+ }++ svg {+ width: 100%;+ min-width: min(900px, 100%);+ display: block;+ }++ .cards {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));+ gap: 1rem;+ margin-top: 2rem;+ }++ .card {+ background: var(--panel);+ border-radius: 0.75rem;+ border: 1px solid var(--panel-border);+ padding: 1.25rem;+ }++ .card-header {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ margin-bottom: 0.75rem;+ }++ .card-dot {+ width: 8px;+ height: 8px;+ border-radius: 50%;+ }++ .card-dot.cyan { background: var(--frontend-stroke); }+ .card-dot.emerald { background: var(--backend-stroke); }+ .card-dot.violet { background: var(--database-stroke); }+ .card-dot.amber { background: var(--cloud-stroke); }+ .card-dot.rose { background: var(--security-stroke); }+ .card-dot.orange { background: var(--messagebus-stroke); }+ .card-dot.slate { background: var(--external-stroke); }++ .card h3 { font-size: 0.875rem; font-weight: 600; color: var(--text); }++ .card ul {+ list-style: none;+ color: var(--text-muted);+ font-size: 0.75rem;+ }++ .card li { margin-bottom: 0.375rem; }++ .footer {+ text-align: center;+ margin-top: 1.5rem;+ color: var(--text-faint);+ font-size: 0.75rem;+ }++ /* ==========================================================+ Print stylesheet — hide interactive controls, force light,+ drop the grid so the diagram doesn't waste ink, use landscape+ so wide diagrams fit, pack summary cards into 2 columns to+ avoid an orphan card on a trailing page.+ ========================================================== */+ @page { size: landscape; margin: 1.5cm; }++ @media print {+ /* Force the FULL light palette — including component fills/strokes and+ lane/arrow colors — so printing from dark theme doesn't put neon+ strokes and translucent dark fills on white paper. */+ :root, [data-theme="dark"], [data-theme="light"] {+ --bg: #ffffff;+ --grid: transparent;+ --panel: #ffffff;+ --panel-border: #e2e8f0;+ --text: #0f172a;+ --text-muted: #475569;+ --text-dim: #94a3b8;+ --text-faint: #64748b;+ --mask: #ffffff;+ --lane-fill: rgba(248, 250, 252, 0.65);+ --lane-stroke: #cbd5e1;+ --arrow: #94a3b8;+ --arrow-emphasis: #059669;+ --frontend-fill: rgba(34, 211, 238, 0.15);+ --frontend-stroke: #0891b2;+ --backend-fill: rgba(52, 211, 153, 0.18);+ --backend-stroke: #059669;+ --database-fill: rgba(167, 139, 250, 0.2);+ --database-stroke: #7c3aed;+ --cloud-fill: rgba(251, 191, 36, 0.18);+ --cloud-stroke: #d97706;+ --security-fill: rgba(251, 113, 133, 0.15);+ --security-stroke: #e11d48;+ --messagebus-fill: rgba(251, 146, 60, 0.15);+ --messagebus-stroke:#ea580c;+ --external-fill: rgba(148, 163, 184, 0.18);+ --external-stroke: #64748b;+ }+ body { background: #ffffff !important; padding: 0; }+ .container { max-width: none; }+ .toolbar, .archify-toast, .no-print { display: none !important; }+ .diagram-container, .card { box-shadow: none; border-color: #e2e8f0; }+ .cards { grid-template-columns: 1fr 1fr; }+ /* Ensure elements break sensibly across pages */+ .card { break-inside: avoid; page-break-inside: avoid; }+ .diagram-container { break-inside: avoid; page-break-inside: avoid; }+ h1, .subtitle { color: #0f172a; }+ }++ /* ==========================================================+ TOOLBAR (theme toggle + export menu)+ ========================================================== */+ .toolbar {+ position: fixed;+ top: 1rem;+ right: 1rem;+ display: flex;+ gap: 0.5rem;+ z-index: 100;+ }+ .toolbar button {+ background: var(--toolbar-bg);+ color: var(--toolbar-text);+ border: 1px solid var(--toolbar-border);+ padding: 0.5rem 0.875rem;+ border-radius: 0.5rem;+ font-family: inherit;+ font-size: 0.75rem;+ font-weight: 500;+ cursor: pointer;+ backdrop-filter: blur(8px);+ transition: background 0.15s, border-color 0.15s;+ display: inline-flex;+ align-items: center;+ gap: 0.375rem;+ }+ .toolbar button:hover {+ background: var(--toolbar-hover);+ border-color: var(--arrow);+ }+ .toolbar button:focus-visible {+ outline: 2px solid var(--frontend-stroke);+ outline-offset: 2px;+ }+ .toolbar .export-wrap { position: relative; }+ .toolbar .export-menu {+ position: absolute;+ top: calc(100% + 0.375rem);+ right: 0;+ background: var(--toolbar-menu-bg);+ border: 1px solid var(--toolbar-border);+ border-radius: 0.5rem;+ padding: 0.375rem;+ min-width: 160px;+ display: none;+ flex-direction: column;+ box-shadow: 0 4px 20px rgba(0,0,0,0.25);+ }+ .toolbar .export-menu.open { display: flex; }+ .toolbar .export-menu button {+ background: transparent;+ border: 0;+ justify-content: space-between;+ width: 100%;+ text-align: left;+ padding: 0.5rem 0.75rem;+ }+ .toolbar .export-menu button:hover {+ background: var(--toolbar-hover);+ }+ .toolbar .export-menu .hint {+ color: var(--text-faint);+ font-size: 0.625rem;+ }+ .toolbar .export-menu hr {+ border: 0;+ border-top: 1px solid var(--toolbar-border);+ margin: 0.25rem 0.375rem;+ opacity: 0.5;+ }++ /* Toast — brief feedback for actions like "copied" */+ .archify-toast {+ position: fixed;+ top: 1rem;+ left: 50%;+ transform: translateX(-50%) translateY(-8px);+ background: var(--toolbar-menu-bg);+ color: var(--text);+ border: 1px solid var(--toolbar-border);+ padding: 0.5rem 1rem;+ border-radius: 0.5rem;+ font-family: inherit;+ font-size: 0.75rem;+ opacity: 0;+ transition: opacity 0.2s, transform 0.2s;+ z-index: 200;+ pointer-events: none;+ box-shadow: 0 4px 20px rgba(0,0,0,0.25);+ }+ .archify-toast.show {+ opacity: 1;+ transform: translateX(-50%) translateY(0);+ }++ @media (max-width: 720px) {+ body { padding: 1rem; }+ .toolbar {+ position: static;+ justify-content: flex-end;+ margin-bottom: 1rem;+ }+ .header { margin-bottom: 1.25rem; }+ .header-row {+ gap: 0.75rem;+ align-items: flex-start;+ }+ h1 {+ font-size: 1.25rem;+ line-height: 1.25;+ }+ .subtitle {+ margin-left: 0;+ font-size: 0.8125rem;+ line-height: 1.55;+ }+ .diagram-container {+ padding: 0.75rem;+ border-radius: 0.75rem;+ }+ .cards {+ grid-template-columns: 1fr;+ margin-top: 1rem;+ }+ }++ /* ==========================================================+ SVG SEMANTIC CLASSES — use these instead of inline fill/stroke+ ========================================================== */+ .c-grid { stroke: var(--grid); fill: none; }+ .c-mask { fill: var(--mask); stroke: none; }++ .c-frontend { fill: var(--frontend-fill); stroke: var(--frontend-stroke); }+ .c-backend { fill: var(--backend-fill); stroke: var(--backend-stroke); }+ .c-database { fill: var(--database-fill); stroke: var(--database-stroke); }+ .c-cloud { fill: var(--cloud-fill); stroke: var(--cloud-stroke); }+ .c-security { fill: var(--security-fill); stroke: var(--security-stroke); }+ .c-messagebus { fill: var(--messagebus-fill); stroke: var(--messagebus-stroke); }+ .c-external { fill: var(--external-fill); stroke: var(--external-stroke); }++ /* Text helpers */+ .t-primary { fill: var(--text); }+ .t-muted { fill: var(--text-muted); }+ .t-dim { fill: var(--text-dim); }+ .t-frontend { fill: var(--frontend-stroke); }+ .t-backend { fill: var(--backend-stroke); }+ .t-database { fill: var(--database-stroke); }+ .t-cloud { fill: var(--cloud-stroke); }+ .t-security { fill: var(--security-stroke); }+ .t-messagebus { fill: var(--messagebus-stroke); }+ .t-external { fill: var(--external-stroke); }++ /* Arrows */+ .a-default { stroke: var(--arrow); fill: none; }+ .a-emphasis { stroke: var(--arrow-emphasis); fill: none; }+ .a-security { stroke: var(--security-stroke); fill: none; stroke-dasharray: 5,5; }+ .a-dashed { stroke: var(--database-stroke); fill: none; stroke-dasharray: 4,4; }++ /* Arrowhead markers reference these */+ .m-default { fill: var(--arrow); }+ .m-emphasis { fill: var(--arrow-emphasis); }+ .m-security { fill: var(--security-stroke); }+ .m-dashed { fill: var(--database-stroke); }++ /* Dashed boundary variants */+ .c-security-group { fill: transparent; stroke: var(--security-stroke); stroke-dasharray: 4,4; }+ .c-region { fill: rgba(251, 191, 36, 0.05); stroke: var(--cloud-stroke); stroke-dasharray: 8,4; }+ .c-lane { fill: var(--lane-fill); stroke: var(--lane-stroke); stroke-dasharray: 6,6; }++ /* Optional trace animation, enabled only by meta.animation = "trace".+ Static diagrams do not carry data-animation and render exactly as before. */+ svg[data-animation="trace"] [data-animate="edge"] {+ stroke-dasharray: 10 8;+ stroke-dashoffset: 54;+ animation: archify-edge-flow 2.4s linear infinite;+ animation-delay: calc(var(--step, 0) * 160ms);+ }+ svg[data-animation="trace"] [data-animate="node"] {+ transform-box: fill-box;+ transform-origin: center;+ animation: archify-node-pulse 3.6s ease-in-out infinite;+ animation-delay: calc(var(--step, 0) * 160ms);+ }+ @keyframes archify-edge-flow {+ to { stroke-dashoffset: 0; }+ }+ @keyframes archify-node-pulse {+ 0%, 72%, 100% { filter: none; stroke-width: 1.5; }+ 18%, 36% {+ filter: drop-shadow(0 0 8px var(--arrow-emphasis));+ stroke-width: 2.4;+ }+ }+ @media (prefers-reduced-motion: reduce) {+ svg[data-animation="trace"] [data-animate] {+ animation: none !important;+ stroke-dashoffset: 0;+ }+ }+ </style>+</head>+<body>+ <!-- Toolbar: theme toggle + export menu (present on every generated diagram)+ Keyboard: T toggles theme, E opens export menu (when no input focused) -->+ <div class="toolbar" role="toolbar" aria-label="Diagram actions">+ <button id="btn-theme" type="button"+ title="Toggle theme (T)"+ aria-label="Toggle color theme"+ aria-pressed="false">+ <span id="theme-icon" aria-hidden="true">☾</span>+ <span id="theme-label">Dark</span>+ </button>+ <div class="export-wrap">+ <button id="btn-export" type="button"+ title="Export diagram (E)"+ aria-label="Export diagram"+ aria-haspopup="menu"+ aria-expanded="false"+ aria-controls="export-menu">+ Export <span aria-hidden="true">▾</span>+ </button>+ <div class="export-menu" id="export-menu" role="menu" aria-label="Export">+ <button data-action="copy" type="button" role="menuitem" tabindex="-1">Copy to clipboard <span class="hint">PNG</span></button>+ <hr role="separator">+ <button data-format="png" type="button" role="menuitem" tabindex="-1">Download PNG</button>+ <button data-format="jpeg" type="button" role="menuitem" tabindex="-1">Download JPEG</button>+ <button data-format="webp" type="button" role="menuitem" tabindex="-1">Download WebP</button>+ <hr role="separator">+ <button data-format="svg" type="button" role="menuitem" tabindex="-1">Download SVG <span class="hint">vector</span></button>+ </div>+ </div>+ </div>++ <div class="container">+ <!-- Header -->+ <div class="header">+ <div class="header-row">+ <div class="pulse-dot"></div>+ <h1>Archify Pipeline</h1>+ </div>+ <p class="subtitle">Grid placement demo — row/col instead of manual pos</p>+ </div>++ <!-- Main Diagram -->+ <div class="diagram-container">+ <svg viewBox="0 0 1064 356" role="img" aria-label="Archify Pipeline — Grid placement demo — row/col instead of manual pos (architecture diagram)">+ <!-- Definitions -->+ <defs>+ <marker id="arrowhead" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">+ <polygon points="0 0, 10 3.5, 0 7" class="m-default" />+ </marker>+ <marker id="arrowhead-emphasis" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">+ <polygon points="0 0, 10 3.5, 0 7" class="m-emphasis" />+ </marker>+ <marker id="arrowhead-security" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">+ <polygon points="0 0, 10 3.5, 0 7" class="m-security" />+ </marker>+ <marker id="arrowhead-dashed" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">+ <polygon points="0 0, 10 3.5, 0 7" class="m-dashed" />+ </marker>+ <pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse">+ <path d="M 40 0 L 0 0 0 40" class="c-grid" stroke-width="0.5"/>+ </pattern>+ </defs>++ <!-- Background Grid -->+ <rect width="100%" height="100%" fill="url(#grid)" />++ <!-- Boundaries (behind everything) -->+ <rect x="298" y="70" width="612" height="218" rx="12" class="c-region" stroke-width="1"/>+ <text x="306" y="88" class="t-cloud" font-size="9" font-weight="600">archify/ skill package</text>++ <!-- Connection paths (before components for correct z-order) -->+ <path d="M 160 238 L 184 238" class="a-emphasis" stroke-width="1.8" marker-end="url(#arrowhead-emphasis)"/>+ <path d="M 244 208 L 244 160" class="a-default" stroke-width="1.5" marker-end="url(#arrowhead)"/>+ <path d="M 304 238 L 328 238" class="a-emphasis" stroke-width="1.8" marker-end="url(#arrowhead-emphasis)"/>+ <path d="M 388 208 L 388 160" class="a-security" stroke-width="1.5" marker-end="url(#arrowhead-security)"/>+ <path d="M 448 238 L 472 238" class="a-emphasis" stroke-width="1.8" marker-end="url(#arrowhead-emphasis)"/>+ <path d="M 592 238 L 616 238" class="a-emphasis" stroke-width="1.8" marker-end="url(#arrowhead-emphasis)"/>+ <path d="M 736 238 L 760 238" class="a-emphasis" stroke-width="1.8" marker-end="url(#arrowhead-emphasis)"/>+ <path d="M 880 238 L 904 238" class="a-emphasis" stroke-width="1.8" marker-end="url(#arrowhead-emphasis)"/>++ <!-- Components -->+ <rect x="40" y="208" width="120" height="60" rx="6" class="c-mask"/>+ <rect x="40" y="208" width="120" height="60" rx="6" class="c-external" stroke-width="1.5"/>+ <text x="100" y="236" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">You</text>+ <text x="100" y="252" class="t-muted" font-size="9" text-anchor="middle">NL / Mermaid</text>++ <rect x="184" y="208" width="120" height="60" rx="6" class="c-mask"/>+ <rect x="184" y="208" width="120" height="60" rx="6" class="c-frontend" stroke-width="1.5"/>+ <text x="244" y="236" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">Agent Hosts</text>+ <text x="244" y="252" class="t-muted" font-size="9" text-anchor="middle">Claude · Codex</text>++ <rect x="184" y="100" width="120" height="60" rx="6" class="c-mask"/>+ <rect x="184" y="100" width="120" height="60" rx="6" class="c-frontend" stroke-width="1.5"/>+ <text x="244" y="128" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">SKILL.md</text>+ <text x="244" y="144" class="t-muted" font-size="9" text-anchor="middle">layout rules</text>++ <rect x="328" y="208" width="120" height="60" rx="6" class="c-mask"/>+ <rect x="328" y="208" width="120" height="60" rx="6" class="c-messagebus" stroke-width="1.5"/>+ <text x="388" y="236" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">JSON IR</text>+ <text x="388" y="252" class="t-muted" font-size="9" text-anchor="middle">schema v1</text>++ <rect x="328" y="100" width="120" height="60" rx="6" class="c-mask"/>+ <rect x="328" y="100" width="120" height="60" rx="6" class="c-security" stroke-width="1.5"/>+ <text x="388" y="128" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">Schema</text>+ <text x="388" y="144" class="t-muted" font-size="9" text-anchor="middle">ajv</text>++ <rect x="472" y="208" width="120" height="60" rx="6" class="c-mask"/>+ <rect x="472" y="208" width="120" height="60" rx="6" class="c-backend" stroke-width="1.5"/>+ <text x="532" y="242" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">Renderers ×5</text>++ <rect x="616" y="208" width="120" height="60" rx="6" class="c-mask"/>+ <rect x="616" y="208" width="120" height="60" rx="6" class="c-frontend" stroke-width="1.5"/>+ <text x="676" y="242" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">template.html</text>++ <rect x="760" y="208" width="120" height="60" rx="6" class="c-mask"/>+ <rect x="760" y="208" width="120" height="60" rx="6" class="c-security" stroke-width="1.5"/>+ <text x="820" y="242" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">Output Check</text>++ <rect x="904" y="208" width="120" height="60" rx="6" class="c-mask"/>+ <rect x="904" y="208" width="120" height="60" rx="6" class="c-cloud" stroke-width="1.5"/>+ <text x="964" y="236" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">HTML</text>+ <text x="964" y="252" class="t-muted" font-size="9" text-anchor="middle">artifact</text>++ <!-- Connection labels -->++++++++++ <!-- Legend -->+ <text x="40" y="327" class="t-primary" font-size="9" font-weight="600">Legend</text>+ <rect x="40" y="332" width="14" height="9" rx="2" class="c-external" stroke-width="1"/>+ <text x="60" y="340" class="t-muted" font-size="8">External</text>+ <rect x="138" y="332" width="14" height="9" rx="2" class="c-frontend" stroke-width="1"/>+ <text x="158" y="340" class="t-muted" font-size="8">Frontend</text>+ <rect x="236" y="332" width="14" height="9" rx="2" class="c-messagebus" stroke-width="1"/>+ <text x="256" y="340" class="t-muted" font-size="8">Message bus</text>+ <rect x="349" y="332" width="14" height="9" rx="2" class="c-security" stroke-width="1"/>+ <text x="369" y="340" class="t-muted" font-size="8">Security</text>+ <rect x="447" y="332" width="14" height="9" rx="2" class="c-backend" stroke-width="1"/>+ <text x="467" y="340" class="t-muted" font-size="8">Backend</text>+ <rect x="540" y="332" width="14" height="9" rx="2" class="c-cloud" stroke-width="1"/>+ <text x="560" y="340" class="t-muted" font-size="8">Cloud</text>+ </svg>+ </div>++ <!-- Info Cards -->+ <div class="cards">+ <div class="card">+ <div class="card-header">+ <div class="card-dot cyan"></div>+ <h3>Grid mode</h3>+ </div>+ <ul>+ <li>• Set layout.mode grid and place components with row/col</li>+ <li>• pos still overrides a cell when you need fine tuning</li>+ <li>• Not auto-layout — fixed cell spacing only</li>+ </ul>+ </div>+ </div>++ <!-- Footer -->+ <p class="footer">+ Architecture diagram • Built with Archify<span class="no-print"> • Press <kbd>T</kbd> for theme and <kbd>E</kbd> for export</span>+ </p>+ </div>++ <script>+ /* ============================================================+ Theme toggle — persists to localStorage, respects system pref+ ============================================================ */+ var Archify = {};++ Archify.theme = (function () {+ var STORAGE_KEY = 'archify-theme';+ var html = document.documentElement;+ var btn = document.getElementById('btn-theme');+ var icon = document.getElementById('theme-icon');+ var label = document.getElementById('theme-label');++ // localStorage can throw (blocked cookies, sandboxed iframes); the whole+ // script element dies on an uncaught error, so guard every access.+ function readStored() {+ try { return localStorage.getItem(STORAGE_KEY); } catch (_) { return null; }+ }+ function writeStored(value) {+ try { localStorage.setItem(STORAGE_KEY, value); } catch (_) {}+ }+ function urlOverride() {+ // URL param wins (useful for deterministic screenshots / share links)+ try {+ var param = new URLSearchParams(window.location.search).get('theme');+ if (param === 'light' || param === 'dark') return param;+ } catch (_) {}+ return null;+ }++ function resolveInitial() {+ var fromUrl = urlOverride();+ if (fromUrl) return fromUrl;+ var saved = readStored();+ if (saved === 'light' || saved === 'dark') return saved;+ return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';+ }++ function apply(theme) {+ html.setAttribute('data-theme', theme);+ icon.textContent = theme === 'dark' ? '\u263E' : '\u263C';+ label.textContent = theme === 'dark' ? 'Dark' : 'Light';+ btn.setAttribute('aria-pressed', theme === 'light' ? 'true' : 'false');+ }++ function toggle() {+ var next = html.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';+ apply(next);+ writeStored(next);+ }++ apply(resolveInitial());+ btn.addEventListener('click', toggle);++ // Follow live OS theme changes while the user has no explicit preference.+ try {+ var media = window.matchMedia('(prefers-color-scheme: light)');+ var onChange = function (e) {+ var saved = readStored();+ if (urlOverride() || saved === 'light' || saved === 'dark') return;+ apply(e.matches ? 'light' : 'dark');+ };+ if (media.addEventListener) media.addEventListener('change', onChange);+ else if (media.addListener) media.addListener(onChange);+ } catch (_) {}++ return { toggle: toggle };+ })();++ /* ============================================================+ Export — PNG / JPEG / WebP / SVG (download) and Copy PNG (clipboard)++ Raster exports are always rendered at 4x source resolution for+ maximum sharpness. The trick: we set the serialized SVG's+ `width`/`height` to viewBox * 4 so the browser rasterizes the+ vectors at that resolution natively. drawImage then draws at+ the image's natural size (no upscaling = no blur).++ JPEG/WebP paint the current theme's background explicitly since+ those formats have no alpha channel.+ ============================================================ */+ (function () {+ var RASTER_SCALE = 4;++ function diagramFilename() {+ var title = (document.title || 'diagram')+ .replace(/\s+Architecture(\s+Diagram)?$/i, '')+ .replace(/\s+Diagram$/i, '')+ .trim();+ return title.replace(/[^a-z0-9_\-]+/gi, '-')+ .toLowerCase()+ .replace(/^-+|-+$/g, '') || 'diagram';+ }++ function currentBg() {+ return getComputedStyle(document.body).backgroundColor || '#ffffff';+ }++ /**+ * Serialize the main SVG into a standalone document.+ *+ * Two modes:+ * - Default (opts.autoTheme=false) — locks the serialized SVG to the+ * viewer's current theme. Used by the raster pipeline+ * (PNG/JPEG/WebP/clipboard) because canvas rasterization needs+ * deterministic colors; a raster cannot react to+ * prefers-color-scheme after encoding.+ * - autoTheme=true — emits BOTH dark and light variable sets plus a+ * `@media (prefers-color-scheme)` rule so the resulting SVG+ * self-themes when embedded in GitHub READMEs or other hosts that+ * expose a color scheme. Used for "Download SVG".+ */+ function serializeSvg(scale, opts) {+ // scale: integer multiplier for intrinsic SVG pixel dimensions used by+ // the raster path. Defaults to 1 (natural size) for SVG download.+ scale = scale || 1;+ opts = opts || {};+ var autoTheme = opts.autoTheme === true;++ var svg = document.querySelector('.diagram-container svg');+ var clone = svg.cloneNode(true);++ var vb = svg.viewBox.baseVal;+ // Scale width/height so the browser rasterizes the vectors at target+ // resolution directly. viewBox stays unchanged so coordinates don't+ // shift. This is the key to sharp rasters — do NOT scale later via+ // canvas upscaling.+ clone.setAttribute('width', vb.width * scale);+ clone.setAttribute('height', vb.height * scale);+ clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');++ // Only the SVG-relevant rules: semantic classes, markers, and the+ // theme variable blocks. Toolbar/cards/print CSS can never apply+ // inside a standalone SVG and would only bloat the export.+ var hostStyle = (function () {+ var out = [];+ Array.prototype.forEach.call(document.styleSheets, function (sheet) {+ var rules;+ try { rules = sheet.cssRules; } catch (_) { return; } // cross-origin+ if (!rules) return;+ Array.prototype.forEach.call(rules, function (rule) {+ if (rule.type !== 1) return; // plain style rules only+ var sel = rule.selectorText || '';+ if (/(^|,)\s*(svg|:root|\[data-theme|\.c-|\.t-|\.a-|\.m-)/.test(sel)) {+ out.push(rule.cssText);+ }+ });+ });+ return out.join('\n');+ })();++ // Derive the variable list from the stylesheet so newly added theme+ // variables can never be missed by the export pipeline again+ // (--lane-fill/--lane-stroke once were).+ var varNames = (function () {+ var seen = {};+ var names = [];+ (hostStyle.match(/--[a-zA-Z0-9-]+(?=\s*:)/g) || []).forEach(function (n) {+ if (!seen[n]) { seen[n] = true; names.push(n); }+ });+ return names;+ })();++ // Resolve the full variable set for a given data-theme via an+ // off-DOM probe, independent of what the viewer is currently set to.+ function resolveVars(themeAttr) {+ var probe = document.createElement('div');+ probe.setAttribute('data-theme', themeAttr);+ probe.style.cssText = 'position:absolute;width:0;height:0;visibility:hidden;';+ document.body.appendChild(probe);+ try {+ var c = getComputedStyle(probe);+ return varNames.map(function (n) {+ return n + ': ' + c.getPropertyValue(n).trim() + ';';+ }).join(' ');+ } finally {+ document.body.removeChild(probe);+ }+ }++ // Prepend a local()-only @font-face block for each weight so that the+ // sandboxed image-rendering context used during PNG/JPEG/WebP export+ // can find JetBrains Mono if the user has it installed locally, and+ // falls through cleanly to the monospace stack otherwise. The usual+ // Google-Fonts <link> in the host document is unreachable from the+ // serialized SVG, so url()-sourced faces would just hang.+ var fontFallback = [400, 500, 600, 700].map(function (w) {+ return "@font-face { font-family: 'JetBrains Mono'; font-weight: " + w ++ "; src: local('JetBrains Mono'), local('JetBrainsMono-Regular'); }";+ }).join('\n');++ var style = document.createElementNS('http://www.w3.org/2000/svg', 'style');+ var bgRect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');+ bgRect.setAttribute('width', '100%');+ bgRect.setAttribute('height', '100%');++ if (autoTheme) {+ // Dual-theme SVG. Dark is the default (so hosts without+ // prefers-color-scheme still render), light swaps in via media+ // query, and svg[data-theme="..."] still lets downstream+ // consumers force a specific theme.+ var darkVars = resolveVars('dark');+ var lightVars = resolveVars('light');++ style.textContent =+ fontFallback + "\n" ++ "svg { font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, 'DejaVu Sans Mono', 'Liberation Mono', 'Noto Sans Mono CJK SC', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', monospace; }\n" ++ hostStyle + "\n" ++ ":root, svg { " + darkVars + " }\n" ++ "@media (prefers-color-scheme: light) { :root, svg { " + lightVars + " } }\n" ++ "svg[data-theme=\"light\"] { " + lightVars + " }\n" ++ "svg[data-theme=\"dark\"] { " + darkVars + " }\n" ++ "rect.c-bg-rect { fill: var(--bg); }\n";++ // Don't lock the serialized SVG to the viewer's current theme.+ clone.removeAttribute('data-theme');+ // Background follows the CSS variable, not a fixed color, so it+ // swaps with the media query.+ bgRect.setAttribute('class', 'c-bg-rect');+ } else {+ // Raster path: lock to the viewer's current theme.+ var theme = document.documentElement.getAttribute('data-theme') || 'dark';+ var themeHost = document.querySelector('[data-theme="' + theme + '"]') || document.documentElement;+ var computed = getComputedStyle(themeHost);+ var vars = varNames.map(function (n) {+ return n + ': ' + computed.getPropertyValue(n).trim() + ';';+ }).join(' ');++ // IMPORTANT: inject the resolved variables AFTER hostStyle,+ // otherwise hostStyle's ":root, [data-theme=\"dark\"] { ... }" rule+ // overrides our chosen theme via later-in-cascade equal-specificity.+ // Keep this order.+ style.textContent =+ fontFallback + "\n" ++ "svg { font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, 'DejaVu Sans Mono', 'Liberation Mono', 'Noto Sans Mono CJK SC', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', monospace; }\n" ++ hostStyle + "\n" ++ ":root, svg { " + vars + " }\n";++ bgRect.setAttribute('fill', computed.getPropertyValue('--bg').trim() || '#ffffff');+ }++ clone.insertBefore(style, clone.firstChild);+ clone.insertBefore(bgRect, style.nextSibling);++ return {+ svgString: new XMLSerializer().serializeToString(clone),+ width: vb.width * scale,+ height: vb.height * scale+ };+ }++ function download(blob, filename) {+ var url = URL.createObjectURL(blob);+ var a = document.createElement('a');+ a.href = url;+ a.download = filename;+ document.body.appendChild(a);+ a.click();+ a.remove();+ setTimeout(function () { URL.revokeObjectURL(url); }, 1000);+ }++ // Conservative upper bound on total canvas pixels. Older Safari on iOS+ // silently produces a blank canvas above ~16 Mpx; Chrome / Firefox /+ // desktop Safari are far higher but start failing on memory-constrained+ // devices. We pick the largest integer scale in {4,3,2,1} whose target+ // pixel count fits under this cap.+ var MAX_CANVAS_PIXELS = 16 * 1024 * 1024;++ function pickSafeScale(vbW, vbH) {+ for (var s = RASTER_SCALE; s >= 1; s--) {+ if (vbW * s * vbH * s <= MAX_CANVAS_PIXELS) return s;+ }+ return 1;+ }++ function rasterize(format) {+ // Serialize at a safe scale (RASTER_SCALE=4 by default, reduced if the+ // resulting canvas would exceed MAX_CANVAS_PIXELS). The SVG itself is+ // rasterized at target resolution natively; drawImage draws at natural+ // size — no upsampling blur.+ var svg = document.querySelector('.diagram-container svg');+ var vb = svg.viewBox.baseVal;+ var scale = pickSafeScale(vb.width, vb.height);+ var data = serializeSvg(scale);+ var svgBlob = new Blob([data.svgString], { type: 'image/svg+xml;charset=utf-8' });+ var svgUrl = URL.createObjectURL(svgBlob);++ return new Promise(function (resolve, reject) {+ var img = new Image();+ img.onload = function () {+ var canvas = document.createElement('canvas');+ canvas.width = data.width;+ canvas.height = data.height;+ var ctx = canvas.getContext('2d');+ if (format === 'jpeg') {+ ctx.fillStyle = currentBg();+ ctx.fillRect(0, 0, canvas.width, canvas.height);+ }+ // Draw at natural size — SVG was already rasterized at target res.+ ctx.drawImage(img, 0, 0);+ URL.revokeObjectURL(svgUrl);+ var mime = format === 'jpeg' ? 'image/jpeg' :+ format === 'webp' ? 'image/webp' : 'image/png';+ var quality = format === 'png' ? undefined : 0.95;+ canvas.toBlob(function (blob) {+ if (!blob) reject(new Error('toBlob returned null for ' + format));+ else resolve(blob);+ }, mime, quality);+ };+ img.onerror = function (e) {+ URL.revokeObjectURL(svgUrl);+ reject(e);+ };+ img.src = svgUrl;+ });+ }++ var menu = document.getElementById('export-menu');+ var btn = document.getElementById('btn-export');+ var items = function () {+ return Array.prototype.slice.call(menu.querySelectorAll('button[role="menuitem"]'));+ };++ // ---- Clipboard support ----------------------------------------------+ function canCopyImage() {+ return typeof ClipboardItem !== 'undefined' &&+ navigator.clipboard &&+ typeof navigator.clipboard.write === 'function';+ }++ // ---- Raster format detection ----------------------------------------+ // canvas.toBlob('image/webp') silently returns a PNG on browsers without+ // WebP encoding (older Safari), so detect explicitly.+ function supports(format) {+ if (format === 'svg' || format === 'png') return true;+ var mime = format === 'jpeg' ? 'image/jpeg' : 'image/webp';+ try {+ var c = document.createElement('canvas');+ c.width = c.height = 2;+ return c.toDataURL(mime).indexOf('data:' + mime) === 0;+ } catch (_) { return false; }+ }++ // Gray out unsupported items.+ items().forEach(function (it) {+ if (it.dataset.format && !supports(it.dataset.format)) {+ it.disabled = true;+ it.title = 'Not supported by this browser';+ it.style.opacity = '0.5';+ }+ if (it.dataset.action === 'copy' && !canCopyImage()) {+ it.disabled = true;+ it.title = 'Clipboard image write not supported by this browser';+ it.style.opacity = '0.5';+ }+ });++ // ---- Toast ----------------------------------------------------------+ // A live region only announces CHANGES to an existing node, so the toast+ // element is created once up front and updated in place.+ var toastEl = document.createElement('div');+ toastEl.className = 'archify-toast';+ toastEl.setAttribute('role', 'status');+ document.body.appendChild(toastEl);+ var toastTimer = null;++ function toast(msg) {+ toastEl.textContent = '';+ requestAnimationFrame(function () {+ toastEl.textContent = msg;+ toastEl.classList.add('show');+ });+ clearTimeout(toastTimer);+ toastTimer = setTimeout(function () { toastEl.classList.remove('show'); }, 1500);+ }++ function open(focusLast) {+ menu.classList.add('open');+ btn.setAttribute('aria-expanded', 'true');+ var available = items().filter(function (i) { return !i.disabled; });+ var target = focusLast ? available[available.length - 1] : available[0];+ if (target) target.focus();+ }+ function close(focusTrigger) {+ menu.classList.remove('open');+ btn.setAttribute('aria-expanded', 'false');+ if (focusTrigger) btn.focus();+ }+ function isOpen() { return menu.classList.contains('open'); }++ btn.addEventListener('click', function (e) {+ e.stopPropagation();+ if (isOpen()) close(false);+ else open();+ });+ // APG menu-button pattern: ArrowDown/ArrowUp on the trigger opens the menu.+ btn.addEventListener('keydown', function (e) {+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {+ e.preventDefault();+ if (!isOpen()) open(e.key === 'ArrowUp');+ }+ });+ document.addEventListener('click', function (e) {+ if (!menu.contains(e.target) && e.target !== btn) close(false);+ });++ // Keyboard navigation inside the menu.+ // Menu items: Up/Down, Home/End.+ // Esc closes + returns focus to trigger; Tab closes.+ menu.addEventListener('keydown', function (e) {+ if (e.key === 'Escape') { e.preventDefault(); close(true); return; }+ if (e.key === 'Tab') { close(false); return; }++ var available = items().filter(function (i) { return !i.disabled; });+ var current = available.indexOf(document.activeElement);+ switch (e.key) {+ case 'ArrowDown':+ e.preventDefault();+ if (available.length) available[(current + 1 + available.length) % available.length].focus();+ break;+ case 'ArrowUp':+ e.preventDefault();+ if (available.length) available[(current - 1 + available.length) % available.length].focus();+ break;+ case 'Home':+ e.preventDefault();+ if (available[0]) available[0].focus();+ break;+ case 'End':+ e.preventDefault();+ if (available.length) available[available.length - 1].focus();+ break;+ }+ });++ function runExport(format) {+ var base = diagramFilename();+ close(true);+ return (format === 'svg'+ ? Promise.resolve(serializeSvg(1, { autoTheme: true })).then(function (d) {+ download(new Blob([d.svgString], { type: 'image/svg+xml;charset=utf-8' }), base + '.svg');+ })+ : rasterize(format).then(function (blob) {+ download(blob, base + '.' + format);+ })+ ).catch(function (err) {+ console.error(err);+ alert('Export failed: ' + (err && err.message ? err.message : format));+ });+ }++ function runCopy() {+ close(true);+ if (!canCopyImage()) {+ alert('Clipboard image write not supported in this browser.');+ return;+ }+ // WebKit requires ClipboardItem to be constructed synchronously inside+ // the user gesture — pass the pending Promise<Blob> as the item value.+ // Browsers that reject promise values throw synchronously; fall back+ // to awaiting the blob first (works in Chromium/Firefox).+ var blobPromise = rasterize('png');+ var writePromise;+ try {+ writePromise = navigator.clipboard.write([new ClipboardItem({ 'image/png': blobPromise })]);+ } catch (_) {+ writePromise = blobPromise.then(function (blob) {+ return navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);+ });+ }+ return writePromise.then(function () {+ toast('Copied PNG to clipboard');+ }).catch(function (err) {+ console.error(err);+ alert('Copy failed: ' + (err && err.message ? err.message : 'unknown'));+ });+ }++ menu.addEventListener('click', function (e) {+ var copyBtn = e.target.closest('button[data-action="copy"]');+ if (copyBtn && !copyBtn.disabled) { runCopy(); return; }++ var formatBtn = e.target.closest('button[data-format]');+ if (formatBtn && !formatBtn.disabled) { runExport(formatBtn.dataset.format); }+ });++ Archify.exportMenu = { open: open, close: close, isOpen: isOpen, run: runExport };++ // Auto-open on page load for demo/screenshot purposes: ?openExport=1+ // Wait for fonts (so the menu doesn't flash before typography lands)+ // and paint before opening. Fallback timeout for browsers without the+ // Font Loading API.+ try {+ if (new URLSearchParams(window.location.search).get('openExport') === '1') {+ var openWhenReady = function () {+ requestAnimationFrame(function () { requestAnimationFrame(open); });+ };+ if (document.fonts && document.fonts.ready) {+ document.fonts.ready.then(openWhenReady);+ } else {+ setTimeout(openWhenReady, 200);+ }+ }+ } catch (_) {}+ })();++ /* ============================================================+ Global keyboard shortcuts+ T -> toggle theme+ E -> open export menu+ Ignored when focus is inside an input/textarea/contenteditable.+ ============================================================ */+ document.addEventListener('keydown', function (e) {+ if (e.metaKey || e.ctrlKey || e.altKey) return;+ var t = e.target;+ if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return;+ if (e.key === 't' || e.key === 'T') {+ e.preventDefault();+ Archify.theme.toggle();+ } else if (e.key === 'e' || e.key === 'E') {+ e.preventDefault();+ if (!Archify.exportMenu.isOpen()) Archify.exportMenu.open();+ }+ });+ </script>+</body>+</html>