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
Add workflow diagram renderer
tt-a1i3f6cd078dc3c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ed1b9d83..1a051848 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,17 @@All notable changes are documented here. Format loosely follows [Keep a Changelog](https://keepachangelog.com/).+## [Unreleased]++### Added+- **Workflow diagram mode.** Archify now includes a renderer-backed workflow diagram type for technical flows, approval chains, tool calls, CI/CD paths, runbooks, and process ownership diagrams. Workflow diagrams use a JSON IR with lanes, nodes, routed edges, and summary cards, then render into the same standalone HTML shell with theme toggle and export menu.+- **Workflow JSON Schema.** Added `archify/schemas/workflow.schema.json` to document and validate the workflow IR shape.+- **Workflow example.** Added a rendered agent tool-call workflow example at `examples/workflow-agent-tool-call-rendered.html`.++### Changed+- **Template responsive polish.** The shared HTML template now handles narrow viewports better: the toolbar no longer overlaps the title, diagrams can scale down to the available width, and cards stack cleanly on mobile.+- **Subtle swimlane styling.** Added `c-lane` for workflow/process swimlanes so workflow boundaries do not visually overpower the main path.+## [2.4.0] — 2026-04-18### Changeddiff --git a/README.md b/README.mdindex 03b7903d..e9db49bc 100644--- a/README.md+++ b/README.md@@ -2,11 +2,12 @@# Archify-**聊两句就画出好看的架构图。深色 / 浅色一键切。导出 4× 清晰 PNG / JPEG / WebP / SVG,或直接复制到剪贴板。**+**聊两句就画出好看的架构图和技术流程图。深色 / 浅色一键切。导出 4× 清晰 PNG / JPEG / WebP / SVG,或直接复制到剪贴板。**-Archify 是一个 [Claude Skill](https://support.claude.com/en/articles/12512180-using-skills-in-claude):你用大白话描述自己的系统,它就把你的描述变成一张做工精细的架构图 —— 一个单文件 HTML,在浏览器里打开就能切主题、复制到剪贴板、导出成各种图片格式。+Archify 是一个 [Claude Skill](https://support.claude.com/en/articles/12512180-using-skills-in-claude):你用大白话描述自己的系统或流程,它就把你的描述变成一张做工精细的技术图 —— 一个单文件 HTML,在浏览器里打开就能切主题、复制到剪贴板、导出成各种图片格式。- **不需要会画图** —— 把组件和连接关系说给 Claude 就行+- **支持 workflow** —— 技术流程、审批链、工具调用、CI/CD、运维 runbook 都可以用泳道图表达- **内置主题切换** —— 深色 / 浅色一键切,浏览器记住偏好- **一键复制到剪贴板** —— 直接贴到 Slack、飞书、微信、Notion、GitHub issue- **导出图片超清晰** —— PNG / JPEG / WebP 全部由浏览器在 4× 源分辨率下**原生光栅化**(不是位图放大,没有糊),或导出 SVG 做真矢量@@ -35,6 +36,24 @@ Export 菜单 —— 复制到剪贴板 + 四种格式下载:想亲自玩一下:克隆仓库后打开 [`examples/web-app.html`](examples/web-app.html),按 <kbd>T</kbd> 切主题,<kbd>E</kbd> 打开导出菜单。给 URL 加上 `?theme=light` 或 `?openExport=1` 可以强制初始状态。+## 图表类型++Archify 现在有两种主要输出:++| 类型 | 适合画什么 | 怎么用 |+|---|---|---|+| **Architecture** | 系统组件、云资源、数据库、缓存、服务边界、安全组 | 直接描述系统结构 |+| **Workflow** | 请求生命周期、审批流程、工具调用、CI/CD、运维 runbook、事故响应 | 说明参与方、步骤顺序、关键分支 |++Workflow 不是通用流程图的替代品,它更偏“技术沟通图”:有泳道、有语义颜色、有主路径和异步/审批/观测路径。比如:++```+用 archify 画一个 workflow:+用户提交请求 -> Agent 规划 -> 需要审批时进入 Approval Gate -> 调工具 -> 记录 trace -> 返回结果+```++本仓库里有一个可打开的示例:[`examples/workflow-agent-tool-call-rendered.html`](examples/workflow-agent-tool-call-rendered.html)。+## 版本演进Archify 基于 [Cocoon-AI/architecture-diagram-generator](https://github.com/Cocoon-AI/architecture-diagram-generator) v1.0(只有深色主题的 HTML 输出)fork 重写。**2.0** 把模板重构成 CSS 变量驱动的可主题化系统,加入客户端导出流水线。**2.1** 加入剪贴板复制 + 键盘导航。**2.2** 加入打印样式 + 本地字体回退。**2.3** 修了一个存在已久的位图升采样 bug,所有光栅导出改为 4× 原生渲染(同时移除了 v2.1 引入的 1×/2×/4× 选择器 —— 那个选择器只是在诱导用户选出更糊的图)。**2.4** SVG 导出升级成双主题自持版 —— 同一个 `.svg` 文件贴在 GitHub README 里,读者切深浅色图会自己跟着切。diff --git a/README_EN.md b/README_EN.mdindex 25e261b2..d104504a 100644--- a/README_EN.md+++ b/README_EN.md@@ -2,11 +2,12 @@# Archify-**Generate beautiful architecture diagrams in chat. Switch dark / light. Copy to clipboard or export crisp 4× PNG / JPEG / WebP / SVG.**+**Generate beautiful architecture and technical workflow diagrams in chat. Switch dark / light. Copy to clipboard or export crisp 4× PNG / JPEG / WebP / SVG.**-Archify is a [Claude Skill](https://support.claude.com/en/articles/12512180-using-skills-in-claude) that turns a plain-English description of your system into a polished, self-contained architecture diagram — a single HTML file you can open, toggle themes on, copy to the clipboard, and export at maximum resolution.+Archify is a [Claude Skill](https://support.claude.com/en/articles/12512180-using-skills-in-claude) that turns a plain-English description of your system or process into a polished, self-contained technical diagram — a single HTML file you can open, toggle themes on, copy to the clipboard, and export at maximum resolution.- **No design skills needed** — describe your architecture in English, get a diagram+- **Workflow diagrams too** — technical flows, approvals, tool calls, CI/CD, and runbooks can be drawn as swimlane diagrams- **Built-in theme toggle** — one click between dark and light, persists across sessions- **Copy PNG to clipboard** — one click, paste straight into Slack / Notion / GitHub- **Ultra-crisp image export** — PNG / JPEG / WebP rendered natively at 4× source resolution (no upsampling blur), or SVG for true vector@@ -34,6 +35,24 @@ The Export menu — Copy PNG to clipboard plus 4 download formats (all raster exLive example: [`examples/web-app.html`](examples/web-app.html) — open in a browser, press <kbd>T</kbd> to toggle theme, <kbd>E</kbd> to open Export. Append `?theme=light` or `?openExport=1` to the URL for deterministic screenshots.+## Diagram types++Archify now has two primary outputs:++| Type | Good for | How to ask |+|---|---|---|+| **Architecture** | System components, cloud resources, databases, caches, services, boundaries, security groups | Describe the system structure |+| **Workflow** | Request lifecycles, approval flows, tool calls, CI/CD, runbooks, incident response | Describe participants, step order, and key branches |++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.++```text+Use archify to draw a workflow:+User submits a request -> Agent plans -> Approval Gate if needed -> Tool Call -> Trace Log -> Final Reply+```++Open the example here: [`examples/workflow-agent-tool-call-rendered.html`](examples/workflow-agent-tool-call-rendered.html).+## What's newArchify is based on [Cocoon-AI/architecture-diagram-generator](https://github.com/Cocoon-AI/architecture-diagram-generator) v1.0 (dark-only, HTML output). **2.0** rewrote the template around a themeable CSS-variable system and added a client-side export pipeline. **2.1** added copy-to-clipboard + keyboard nav. **2.2** added a print stylesheet + local-font fallback. **2.3** fixed a long-standing upsampling bug and made every raster export genuinely sharp at 4× source resolution (the 1× / 2× / 4× selector introduced in 2.1 was removed at the same time — it only encouraged picking a soft-looking scale). **2.4** upgraded the SVG export to a dual-theme self-contained file — drop the same `.svg` into a GitHub README and it follows the reader's dark/light preference automatically.diff --git a/ROADMAP.md b/ROADMAP.mdindex 4801289b..6981541f 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -99,6 +99,12 @@ The experiment tested whether auto-layout (dagre) + archify CSS (version B) look- SKILL.md updated to mention Mermaid as an accepted input dialect (prompt engineering, not parser).- README updated to describe the new stable-iteration workflow.+### Workflow renderer pilot (2026-04-24)++Workflow diagrams became the first concrete test of typed diagram renderers inside Archify. The pilot uses a dedicated `diagram_type: "workflow"` JSON IR with lanes, semantic nodes, anchored edges, route presets, and validation checks for common visual failures such as overlapping nodes, labels on short links, unreadable arrow lengths, and legends outside the viewBox.++This does not reverse the anti-auto-layout decision above. The workflow renderer is intentionally a constrained layout assistant, not a generic graph layout engine: lanes and columns provide stability, while Claude still chooses the semantic grouping, lane order, route intent, labels, and summary cards.+---## Not planneddiff --git a/archify.zip b/archify.zipindex 044c71e9..d9283888 100644Binary files a/archify.zip and b/archify.zip differdiff --git a/archify/SKILL.md b/archify/SKILL.mdindex bc0584d2..93a75bf2 100644--- a/archify/SKILL.md+++ b/archify/SKILL.md@@ -1,6 +1,6 @@---name: archify-description: Create professional architecture diagrams as standalone HTML files with SVG graphics, a built-in dark/light theme toggle, and one-click export to PNG / JPEG / WebP / SVG. Use when the user asks for system architecture diagrams, infrastructure diagrams, cloud architecture visualizations, security diagrams, network topology diagrams, or any technical diagram showing system components and their relationships.+description: Create professional architecture and workflow diagrams as standalone HTML files with SVG graphics, a built-in dark/light theme toggle, and one-click export to PNG / JPEG / WebP / SVG. Use when the user asks for system architecture diagrams, infrastructure diagrams, cloud architecture visualizations, security diagrams, network topology diagrams, technical workflows, approval flows, runbooks, CI/CD flows, or process diagrams.license: MITmetadata:version: "2.4"@@ -18,6 +18,60 @@ Every diagram this skill produces ships with:- An **Export menu** with **Copy PNG to clipboard** plus downloads for **PNG / JPEG / WebP** (all rasterized natively at 4× source resolution for maximum sharpness) and **SVG** (vector, styles inlined). The SVG download is **dual-theme self-contained**: it ships with both dark and light variable sets plus a `@media (prefers-color-scheme)` rule, so embedding it in a GitHub README (or any `<img>` host that exposes a color scheme) makes it follow the reader's dark/light preference automatically. All rendering happens in-browser, no server.- A **CSS-variable-driven color system** so both themes remain visually consistent with the same SVG markup.+## Diagram Types++Archify supports two technical diagram modes:++| Type | Use for | Output path |+|------|---------|-------------|+| `architecture` | System components, cloud resources, services, storage, security boundaries, and infrastructure relationships | Hand-place SVG components inside `assets/template.html` |+| `workflow` | Technical flows, request lifecycles, approval gates, tool calls, runbooks, CI/CD paths, incident response, and process ownership | Prefer `renderers/workflow/render-workflow.mjs` with a workflow JSON file |++When the user says "architecture", "system diagram", "cloud diagram", or asks to understand a codebase structure, use the `architecture` mode unless the requested output is clearly process-oriented.++When the user says "workflow", "flow", "process", "runbook", "sequence of steps", "approval", "CI/CD", "incident", or asks how work moves through actors/systems over time, use the `workflow` mode.++### Workflow Mode++Workflow diagrams use a compact JSON IR:++```json+{+ "schema_version": 1,+ "diagram_type": "workflow",+ "meta": {+ "title": "Release Workflow",+ "subtitle": "PR to production deployment",+ "output": "release-workflow.html",+ "viewBox": [720, 780]+ },+ "lanes": [+ { "id": "dev", "label": "Developer" },+ { "id": "ci", "label": "CI" }+ ],+ "nodes": [],+ "edges": [],+ "cards": []+}+```++If you have filesystem/tool access, create a workflow JSON file and render it with:++```bash+node archify/renderers/workflow/render-workflow.mjs workflow.json workflow.html+```++The renderer:++- Places nodes by lane + column instead of raw SVG coordinates+- Routes edges through explicit anchors and orthogonal route presets+- Uses `c-lane` swimlanes plus the normal semantic component classes+- Hides labels on short adjacent links unless a label is truly necessary+- Adds a `c-mask` label background for routed labels+- Fails fast when nodes overlap, leave their lane, or short arrows become unreadable++Use workflow labels sparingly. Adjacent steps should often be unlabeled; reserve labels for cross-lane transitions, approval decisions, async trace writes, and return paths.+## The Cardinal Rule: Use CSS Classes, Not Inline ColorsThe theme toggle works by switching CSS custom properties. If you hardcode `fill="rgba(...)"` or `stroke="#22d3ee"` on SVG elements, those values will NOT update when the theme changes. Always prefer the class-based system.@@ -80,6 +134,7 @@ Always set `stroke-width` on the line (e.g., `1.5`) — the class only sets colo|---------------------|------------------------------------|| `c-security-group` | Dashed rose boundary for SGs || `c-region` | Large dashed amber region/cluster |+| `c-lane` | Subtle swimlane for workflow/process diagrams |### Typographydiff --git a/archify/assets/template.html b/archify/assets/template.htmlindex 70256ac0..c5433698 100644--- a/archify/assets/template.html+++ b/archify/assets/template.html@@ -19,6 +19,8 @@--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;@@ -58,6 +60,8 @@--panel: #ffffff;--panel-border: #e2e8f0;+ --lane-fill: rgba(248, 250, 252, 0.65);+ --lane-stroke: #cbd5e1;--arrow: #94a3b8;--arrow-emphasis: #059669;@@ -143,7 +147,7 @@svg {width: 100%;- min-width: 900px;+ min-width: min(900px, 100%);display: block;}@@ -325,6 +329,37 @@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========================================================== */@@ -366,6 +401,7 @@/* 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; }</style></head><body>diff --git a/archify/examples/agent-tool-call.workflow.json b/archify/examples/agent-tool-call.workflow.jsonnew file mode 100644index 00000000..74f68cdb--- /dev/null+++ b/archify/examples/agent-tool-call.workflow.json@@ -0,0 +1,73 @@+{+ "schema_version": 1,+ "diagram_type": "workflow",+ "meta": {+ "title": "Agent Tool Call Workflow",+ "subtitle": "Renderer-driven workflow prototype with lanes, anchored nodes, and orthogonal edges",+ "output": "examples/workflow-agent-tool-call-rendered.html",+ "viewBox": [720, 780]+ },+ "lanes": [+ { "id": "ui", "label": "User Interface" },+ { "id": "agent", "label": "Agent Runtime" },+ { "id": "policy", "label": "Policy Boundary" },+ { "id": "tools", "label": "Tool Execution" },+ { "id": "trace", "label": "Observability" }+ ],+ "nodes": [+ { "id": "user", "lane": "ui", "col": 0, "type": "external", "label": "User", "sublabel": "asks for work" },+ { "id": "chat", "lane": "ui", "col": 1, "type": "frontend", "label": "Chat Surface", "sublabel": "thread + files" },+ { "id": "final", "lane": "ui", "col": 5, "type": "backend", "label": "Final Reply", "sublabel": "answer + changes" },+ { "id": "planner", "lane": "agent", "col": 2, "type": "backend", "label": "Agent Planner", "sublabel": "plan next step", "tag": "context aware" },+ { "id": "router", "lane": "agent", "col": 3, "type": "backend", "label": "Tool Router", "sublabel": "choose capability" },+ { "id": "approval", "lane": "policy", "col": 3, "type": "security", "label": "Approval Gate", "sublabel": "scope + consent", "tag": "block risky ops" },+ { "id": "tool", "lane": "tools", "col": 4, "type": "messagebus", "label": "Tool Call", "sublabel": "shell / browser / MCP", "tag": "structured result" },+ { "id": "external", "lane": "tools", "col": 5, "type": "cloud", "label": "External API", "sublabel": "network service" },+ { "id": "store", "lane": "trace", "col": 1, "type": "database", "label": "Context Store", "sublabel": "repo + memory" },+ { "id": "trace", "lane": "trace", "col": 4, "type": "database", "label": "Trace Log", "sublabel": "events + output" }+ ],+ "edges": [+ { "from": "user", "to": "chat", "variant": "default" },+ { "from": "chat", "to": "planner", "label": "plan", "variant": "emphasis", "fromSide": "bottom", "toSide": "top", "route": "drop", "labelSegment": 1 },+ { "from": "planner", "to": "router", "variant": "default" },+ { "from": "router", "to": "approval", "label": "needs approval?", "variant": "security", "fromSide": "bottom", "toSide": "top", "route": "drop", "labelSegment": 0, "labelDx": 34, "labelDy": 18 },+ { "from": "approval", "to": "tool", "label": "approved", "variant": "emphasis", "fromSide": "bottom", "toSide": "top", "route": "drop-right", "labelSegment": 1, "labelDy": 14 },+ { "from": "tool", "to": "external", "variant": "default" },+ { "from": "external", "to": "trace", "label": "record result", "variant": "dashed", "fromSide": "bottom", "toSide": "bottom", "route": "bottom-channel", "labelSegment": 1 },+ { "from": "trace", "to": "final", "label": "summarize outcome", "variant": "emphasis", "fromSide": "right", "toSide": "right", "route": "outside-right", "labelSegment": 1, "labelDx": -22 },+ { "from": "planner", "to": "store", "label": "load context", "variant": "dashed", "fromSide": "bottom", "toSide": "top", "route": "drop-left", "labelSegment": 1 },+ { "from": "store", "to": "trace", "label": "write trace + memory", "variant": "dashed", "labelAt": [380, 622] }+ ],+ "cards": [+ {+ "dot": "cyan",+ "title": "Renderer Rules",+ "items": [+ "Lanes and columns determine node placement",+ "Edges attach to explicit node anchors",+ "Cross-lane paths use orthogonal routing",+ "Short adjacent links stay unlabeled"+ ]+ },+ {+ "dot": "rose",+ "title": "Workflow Semantics",+ "items": [+ "Approval is a first-class policy step",+ "Consent gates are visible in the main path",+ "External calls stay inside the tool lane",+ "Trace writes are separate from the hot path"+ ]+ },+ {+ "dot": "emerald",+ "title": "Why It Matters",+ "items": [+ "This is closer to a diagram_type renderer",+ "The graph can be edited without SVG surgery",+ "Layout rules can be tested and improved",+ "A future IR can reuse this shape directly"+ ]+ }+ ]+}diff --git a/archify/renderers/workflow/README.md b/archify/renderers/workflow/README.mdnew file mode 100644index 00000000..b6487559--- /dev/null+++ b/archify/renderers/workflow/README.md@@ -0,0 +1,52 @@+# Workflow Renderer++Render `diagram_type: "workflow"` JSON files into the standard Archify HTML+template.++```bash+node archify/renderers/workflow/render-workflow.mjs input.workflow.json output.html+```++If `output.html` is omitted, the renderer uses `meta.output` from the JSON file+or falls back to `workflow.html` in the current working directory.++## Input++Workflow JSON files must set:++```json+{+ "schema_version": 1,+ "diagram_type": "workflow",+ "meta": {+ "title": "Agent Tool Call Workflow",+ "subtitle": "Renderer-driven workflow prototype",+ "viewBox": [720, 780]+ },+ "lanes": [],+ "nodes": [],+ "edges": [],+ "cards": []+}+```++The schema lives at:++```text+archify/schemas/workflow.schema.json+```++## Design Rules++- Use lanes for ownership or runtime boundaries.+- Place nodes with lane IDs and column indexes, not raw SVG coordinates.+- Leave short adjacent links unlabeled; the arrow is enough.+- Use labels for cross-lane decisions, approvals, async traces, and return paths.+- Prefer route presets such as `drop`, `drop-left`, `drop-right`,+ `outside-right`, and `bottom-channel` before using raw `via` points.+- Keep workflow examples compact enough to render well in narrow chat/browser+ previews.++The renderer fails when it can detect layout problems, including node overlap,+nodes outside their lanes, unknown edge targets, legends outside the viewBox, or+straight arrows that are too short to read cleanly.diff --git a/archify/renderers/workflow/render-workflow.mjs b/archify/renderers/workflow/render-workflow.mjsnew file mode 100644index 00000000..08ddac01--- /dev/null+++ b/archify/renderers/workflow/render-workflow.mjs@@ -0,0 +1,432 @@+import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const skillRoot = path.resolve(__dirname, '../..');+const repoRoot = path.resolve(skillRoot, '..');+const inputPath = path.resolve(process.argv[2] || path.join(skillRoot, 'examples/agent-tool-call.workflow.json'));+const workflow = JSON.parse(fs.readFileSync(inputPath, 'utf8'));++const templatePath = path.join(skillRoot, 'assets/template.html');+const template = fs.readFileSync(templatePath, 'utf8');++const outPath = path.resolve(process.cwd(), process.argv[3] || workflow.meta.output || 'workflow.html');++const viewBox = workflow.meta.viewBox || [1000, 720];+const layout = {+ laneX: 40,+ laneY: 52,+ laneW: 640,+ laneH: 104,+ laneGap: 20,+ laneTitleH: 30,+ colXs: [88, 220, 300, 430, 500, 625],+ nodeW: 92,+ nodeH: 52+};++const typeClass = {+ frontend: 'c-frontend',+ backend: 'c-backend',+ database: 'c-database',+ cloud: 'c-cloud',+ security: 'c-security',+ messagebus: 'c-messagebus',+ external: 'c-external'+};++const textClass = {+ frontend: 't-frontend',+ backend: 't-backend',+ database: 't-database',+ cloud: 't-cloud',+ security: 't-security',+ messagebus: 't-messagebus',+ external: 't-external'+};++const arrowClass = {+ default: ['a-default', 'arrowhead'],+ emphasis: ['a-emphasis', 'arrowhead-emphasis'],+ security: ['a-security', 'arrowhead-security'],+ dashed: ['a-dashed', 'arrowhead-dashed']+};++const laneIndex = new Map(workflow.lanes.map((lane, index) => [lane.id, index]));++function esc(value) {+ return String(value).replace(/[&<>"']/g, (c) => ({+ '&': '&',+ '<': '<',+ '>': '>',+ '"': '"',+ "'": '''+ }[c]));+}++function laneTop(id) {+ return layout.laneY + laneIndex.get(id) * (layout.laneH + layout.laneGap);+}++function lastLaneBottom() {+ return layout.laneY + workflow.lanes.length * layout.laneH + (workflow.lanes.length - 1) * layout.laneGap;+}++function legendY() {+ return lastLaneBottom() + 44;+}++function measureNode(node) {+ const width = node.width || layout.nodeW;+ const height = node.height || (node.tag ? 68 : layout.nodeH);+ const cx = layout.colXs[node.col];+ const contentH = layout.laneH - layout.laneTitleH;+ const y = laneTop(node.lane) + layout.laneTitleH + (contentH - height) / 2 + (node.yOffset || 0);+ return {+ ...node,+ width,+ height,+ x: cx - width / 2,+ y,+ cx,+ cy: y + height / 2+ };+}++const nodes = new Map(workflow.nodes.map((node) => [node.id, measureNode(node)]));++function rectsOverlap(a, b, gap = 0) {+ return !(+ a.x + a.width + gap <= b.x ||+ b.x + b.width + gap <= a.x ||+ a.y + a.height + gap <= b.y ||+ b.y + b.height + gap <= a.y+ );+}++function validateWorkflow() {+ const problems = [];+ if (workflow.schema_version !== 1) {+ problems.push('Workflow files must set "schema_version": 1.');+ }+ if (workflow.diagram_type && workflow.diagram_type !== 'workflow') {+ problems.push(`Unsupported diagram_type "${workflow.diagram_type}". Expected "workflow".`);+ }+ if (!workflow.meta || !workflow.meta.title) {+ problems.push('Workflow files must include meta.title.');+ }+ if (!Array.isArray(workflow.lanes) || !workflow.lanes.length) {+ problems.push('Workflow files must include at least one lane.');+ }+ if (!Array.isArray(workflow.nodes)) {+ problems.push('Workflow files must include a nodes array.');+ }+ if (!Array.isArray(workflow.edges)) {+ problems.push('Workflow files must include an edges array.');+ }+ if (problems.length) {+ throw new Error(`Workflow layout validation failed:\n- ${problems.join('\n- ')}`);+ }++ const laneIds = new Set(workflow.lanes.map((lane) => lane.id));+ if (laneIds.size !== workflow.lanes.length) {+ problems.push('Lane ids must be unique.');+ }+ if (nodes.size !== workflow.nodes.length) {+ problems.push('Node ids must be unique.');+ }++ for (const node of nodes.values()) {+ if (!laneIds.has(node.lane)) {+ problems.push(`Node "${node.id}" uses unknown lane "${node.lane}".`);+ continue;+ }+ if (node.col < 0 || node.col >= layout.colXs.length) {+ problems.push(`Node "${node.id}" uses column ${node.col}, but only ${layout.colXs.length} columns exist.`);+ }++ const top = laneTop(node.lane);+ const contentTop = top + layout.laneTitleH;+ const laneRight = layout.laneX + layout.laneW;+ if (node.x < layout.laneX || node.x + node.width > laneRight) {+ problems.push(`Node "${node.id}" exceeds the horizontal bounds of lane "${node.lane}".`);+ }+ if (node.y < contentTop || node.y + node.height > top + layout.laneH) {+ problems.push(`Node "${node.id}" collides with the title or boundary of lane "${node.lane}".`);+ }+ }++ const byLane = new Map();+ for (const node of nodes.values()) {+ byLane.set(node.lane, [...(byLane.get(node.lane) || []), node]);+ }+ for (const [lane, laneNodes] of byLane) {+ for (let i = 0; i < laneNodes.length; i += 1) {+ for (let j = i + 1; j < laneNodes.length; j += 1) {+ if (rectsOverlap(laneNodes[i], laneNodes[j], 8)) {+ problems.push(`Nodes "${laneNodes[i].id}" and "${laneNodes[j].id}" are too close in lane "${lane}".`);+ }+ }+ }+ }++ for (const edge of workflow.edges) {+ if (!nodes.has(edge.from)) problems.push(`Edge "${edge.label || edge.from}" references unknown source "${edge.from}".`);+ if (!nodes.has(edge.to)) problems.push(`Edge "${edge.label || edge.to}" references unknown target "${edge.to}".`);+ if (nodes.has(edge.from) && nodes.has(edge.to)) {+ const routed = pathFor(edge);+ if (routed.points.length === 2) {+ const [start, end] = routed.points;+ const segmentLength = Math.hypot(end[0] - start[0], end[1] - start[1]);+ if (segmentLength < 28) {+ problems.push(`Edge "${edge.from}" -> "${edge.to}" is too short (${Math.round(segmentLength)}px).`);+ }+ }+ }+ }++ if (legendY() + 18 > viewBox[1]) {+ problems.push(`Legend exceeds viewBox height ${viewBox[1]}.`);+ }++ if (problems.length) {+ throw new Error(`Workflow layout validation failed:\n- ${problems.join('\n- ')}`);+ }+}++function anchor(node, side) {+ switch (side || 'auto') {+ case 'left': return [node.x, node.cy];+ case 'right': return [node.x + node.width, node.cy];+ case 'top': return [node.cx, node.y];+ case 'bottom': return [node.cx, node.y + node.height];+ default:+ return [node.x + node.width, node.cy];+ }+}++function defaultTargetSide(from, to) {+ if (to.cx < from.cx) return 'right';+ if (to.cx > from.cx) return 'left';+ if (to.cy > from.cy) return 'top';+ return 'bottom';+}++function defaultFromSide(from, to) {+ if (to.cx < from.cx) return 'left';+ if (to.cx > from.cx) return 'right';+ if (to.cy > from.cy) return 'bottom';+ return 'top';+}++function pathFor(edge) {+ const from = nodes.get(edge.from);+ const to = nodes.get(edge.to);+ const start = anchor(from, edge.fromSide || defaultFromSide(from, to));+ const end = anchor(to, edge.toSide || defaultTargetSide(from, to));+ const points = [start, ...routeVia(edge, from, to, start, end), end];+ return {+ d: points.map(([x, y], index) => `${index === 0 ? 'M' : 'L'} ${x} ${y}`).join(' '),+ points+ };+}++function gapYBetween(fromLane, toLane, bias = 0.5) {+ const a = laneTop(fromLane) + layout.laneH;+ const b = laneTop(toLane);+ return a + (b - a) * bias;+}++function routeVia(edge, from, to, start, end) {+ if (edge.via) return edge.via;+ switch (edge.route || 'auto') {+ case 'straight':+ return [];+ case 'drop': {+ const y = gapYBetween(from.lane, to.lane, edge.bias || 0.5);+ return [[start[0], y], [end[0], y]];+ }+ case 'drop-right': {+ const y = gapYBetween(from.lane, to.lane, edge.bias || 0.5);+ return [[start[0], y], [end[0], y]];+ }+ case 'drop-left': {+ const y = gapYBetween(from.lane, to.lane, edge.bias || 0.5);+ return [[start[0], y], [end[0], y]];+ }+ case 'same-lane':+ return [];+ case 'outside-right': {+ const x = edge.channelX || layout.laneX + layout.laneW + 12;+ return [[x, start[1]], [x, end[1]]];+ }+ case 'return-left': {+ const x = edge.channelX || Math.min(from.x, to.x) - 28;+ return [[x, start[1]], [x, end[1]]];+ }+ case 'bottom-channel': {+ const y = edge.channelY || Math.max(from.y + from.height, to.y + to.height) + 32;+ return [[start[0], y], [end[0], y]];+ }+ case 'up-channel': {+ const y = edge.channelY || Math.min(from.y, to.y) - 28;+ return [[start[0], y], [end[0], y]];+ }+ case 'auto':+ default: {+ if (from.lane === to.lane) return [];+ const y = gapYBetween(from.lane, to.lane, edge.bias || 0.5);+ return [[start[0], y], [end[0], y]];+ }+ }+}++function labelPoint(edge, points) {+ if (edge.labelAt) return edge.labelAt;+ if (points.length === 2) {+ return [+ (points[0][0] + points[1][0]) / 2 + (edge.labelDx || 0),+ points[0][1] - 10 + (edge.labelDy || 0)+ ];+ }+ const segmentIndex = Math.min(points.length - 2, Math.max(0, edge.labelSegment ?? 1));+ const a = points[segmentIndex];+ const b = points[segmentIndex + 1];+ return [(a[0] + b[0]) / 2 + (edge.labelDx || 0), (a[1] + b[1]) / 2 - 10 + (edge.labelDy || 0)];+}++function renderDefinitions() {+ return ` <!-- 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>`;+}++function renderLane(lane, index) {+ const y = layout.laneY + index * (layout.laneH + layout.laneGap);+ return ` <rect x="${layout.laneX}" y="${y}" width="${layout.laneW}" height="${layout.laneH}" rx="10" class="c-lane" stroke-width="1"/>+ <text x="${layout.laneX + 14}" y="${y + 22}" class="t-dim" font-size="10" font-weight="600">${String(index + 1).padStart(2, '0')} / ${esc(lane.label)}</text>`;+}++function renderNode(node) {+ const fill = typeClass[node.type] || 'c-external';+ const accent = textClass[node.type] || 't-muted';+ const tag = node.tag+ ? `\n <text x="${node.cx}" y="${node.y + node.height - 12}" class="${accent}" font-size="7" text-anchor="middle">${esc(node.tag)}</text>`+ : '';+ return ` <rect x="${node.x}" y="${node.y}" width="${node.width}" height="${node.height}" rx="6" class="c-mask"/>+ <rect x="${node.x}" y="${node.y}" width="${node.width}" height="${node.height}" rx="6" class="${fill}" stroke-width="1.5"/>+ <text x="${node.cx}" y="${node.y + 21}" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">${esc(node.label)}</text>+ <text x="${node.cx}" y="${node.y + 38}" class="t-muted" font-size="8" text-anchor="middle">${esc(node.sublabel || '')}</text>${tag}`;+}++function edgeAccent(edge) {+ return edge.variant === 'security'+ ? 't-security'+ : edge.variant === 'emphasis'+ ? 't-backend'+ : edge.variant === 'dashed'+ ? 't-database'+ : 't-muted';+}++function renderEdgePath(edge) {+ const [cls, marker] = arrowClass[edge.variant || 'default'] || arrowClass.default;+ const routed = pathFor(edge);+ const strokeWidth = edge.width || (edge.variant === 'emphasis' ? 1.8 : 1.4);+ return ` <path d="${routed.d}" class="${cls}" stroke-width="${strokeWidth}" marker-end="url(#${marker})"/>`;+}++function renderEdgeLabel(edge) {+ if (!edge.label) return '';+ const routed = pathFor(edge);+ const [lx, ly] = labelPoint(edge, routed.points);+ const labelW = Math.max(30, edge.label.length * 4.8 + 10);+ return ` <rect x="${lx - labelW / 2}" y="${ly - 10}" width="${labelW}" height="14" rx="3" class="c-mask"/>+ <text x="${lx}" y="${ly}" class="${edgeAccent(edge)}" font-size="8" text-anchor="middle">${esc(edge.label)}</text>`;+}++function renderLegend() {+ const y = legendY();+ return ` <text x="175" y="${y - 20}" class="t-primary" font-size="10" font-weight="600">Legend</text>+ <rect x="175" y="${y - 8}" width="14" height="9" rx="2" class="c-frontend" stroke-width="1"/>+ <text x="195" y="${y}" class="t-muted" font-size="7">User UI</text>+ <rect x="260" y="${y - 8}" width="14" height="9" rx="2" class="c-backend" stroke-width="1"/>+ <text x="280" y="${y}" class="t-muted" font-size="7">Agent logic</text>+ <rect x="370" y="${y - 8}" width="14" height="9" rx="2" class="c-security" stroke-width="1"/>+ <text x="390" y="${y}" class="t-muted" font-size="7">Policy</text>+ <rect x="455" y="${y - 8}" width="14" height="9" rx="2" class="c-messagebus" stroke-width="1"/>+ <text x="475" y="${y}" class="t-muted" font-size="7">Tool action</text>+ <rect x="565" y="${y - 8}" width="14" height="9" rx="2" class="c-database" stroke-width="1"/>+ <text x="585" y="${y}" class="t-muted" font-size="7">Context / trace</text>`;+}++function renderSvg() {+ return ` <svg viewBox="0 0 ${viewBox[0]} ${viewBox[1]}">+${renderDefinitions()}++ <!-- Background Grid -->+ <rect width="100%" height="100%" fill="url(#grid)" />++ <!-- Swimlanes -->+${workflow.lanes.map(renderLane).join('\n\n')}++ <!-- Edge paths -->+${workflow.edges.map(renderEdgePath).join('\n')}++ <!-- Nodes -->+${[...nodes.values()].map(renderNode).join('\n\n')}++ <!-- Edge labels -->+${workflow.edges.map(renderEdgeLabel).join('\n')}++ <!-- Legend -->+${renderLegend()}+ </svg>`;+}++function renderCards() {+ const cards = workflow.cards || [];+ return ` <!-- Info Cards -->+ <div class="cards">+${cards.map((card) => ` <div class="card">+ <div class="card-header">+ <div class="card-dot ${esc(card.dot)}"></div>+ <h3>${esc(card.title)}</h3>+ </div>+ <ul>+${card.items.map((item) => ` <li>• ${esc(item)}</li>`).join('\n')}+ </ul>+ </div>`).join('\n\n')}+ </div>`;+}++function applyTemplate(svg, cards) {+ return template+ .replace('<title>[PROJECT NAME] Architecture Diagram</title>', `<title>${esc(workflow.meta.title)} Diagram</title>`)+ .replace('<h1>[PROJECT NAME] Architecture</h1>', `<h1>${esc(workflow.meta.title)}</h1>`)+ .replace('<p class="subtitle">[Subtitle description]</p>', `<p class="subtitle">${esc(workflow.meta.subtitle || '')}</p>`)+ .replace(/ <svg viewBox="0 0 1000 680">[\s\S]*? <\/svg>/, svg)+ .replace(/ <!-- Info Cards -->[\s\S]*? <!-- Footer -->/, `${cards}\n\n <!-- Footer -->`)+ .replace('[Project Name] • [Additional metadata]', 'Workflow diagram • Built with Archify • Press <kbd>T</kbd> for theme and <kbd>E</kbd> for export');+}++fs.mkdirSync(path.dirname(outPath), { recursive: true });+validateWorkflow();+fs.writeFileSync(outPath, applyTemplate(renderSvg(), renderCards()));+console.log(outPath);diff --git a/archify/schemas/workflow.schema.json b/archify/schemas/workflow.schema.jsonnew file mode 100644index 00000000..75a07233--- /dev/null+++ b/archify/schemas/workflow.schema.json@@ -0,0 +1,138 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://github.com/tt-a1i/archify/schemas/workflow.schema.json",+ "title": "Archify Workflow Diagram",+ "type": "object",+ "additionalProperties": false,+ "required": ["schema_version", "diagram_type", "meta", "lanes", "nodes", "edges"],+ "properties": {+ "schema_version": {+ "const": 1+ },+ "diagram_type": {+ "const": "workflow"+ },+ "meta": {+ "type": "object",+ "additionalProperties": false,+ "required": ["title"],+ "properties": {+ "title": { "type": "string", "minLength": 1 },+ "subtitle": { "type": "string" },+ "output": { "type": "string" },+ "viewBox": {+ "type": "array",+ "prefixItems": [+ { "type": "number", "minimum": 320 },+ { "type": "number", "minimum": 240 }+ ],+ "items": false,+ "minItems": 2,+ "maxItems": 2+ }+ }+ },+ "lanes": {+ "type": "array",+ "minItems": 1,+ "items": {+ "type": "object",+ "additionalProperties": false,+ "required": ["id", "label"],+ "properties": {+ "id": { "$ref": "#/$defs/id" },+ "label": { "type": "string", "minLength": 1 }+ }+ }+ },+ "nodes": {+ "type": "array",+ "minItems": 1,+ "items": {+ "type": "object",+ "additionalProperties": false,+ "required": ["id", "lane", "col", "type", "label"],+ "properties": {+ "id": { "$ref": "#/$defs/id" },+ "lane": { "$ref": "#/$defs/id" },+ "col": { "type": "integer", "minimum": 0 },+ "type": {+ "enum": ["frontend", "backend", "database", "cloud", "security", "messagebus", "external"]+ },+ "label": { "type": "string", "minLength": 1 },+ "sublabel": { "type": "string" },+ "tag": { "type": "string" },+ "width": { "type": "number", "minimum": 32 },+ "height": { "type": "number", "minimum": 32 },+ "yOffset": { "type": "number" }+ }+ }+ },+ "edges": {+ "type": "array",+ "items": {+ "type": "object",+ "additionalProperties": false,+ "required": ["from", "to"],+ "properties": {+ "from": { "$ref": "#/$defs/id" },+ "to": { "$ref": "#/$defs/id" },+ "label": { "type": "string" },+ "variant": { "enum": ["default", "emphasis", "security", "dashed"] },+ "fromSide": { "$ref": "#/$defs/side" },+ "toSide": { "$ref": "#/$defs/side" },+ "route": {+ "enum": ["auto", "straight", "drop", "drop-right", "drop-left", "same-lane", "outside-right", "return-left", "bottom-channel", "up-channel"]+ },+ "via": {+ "type": "array",+ "items": { "$ref": "#/$defs/point" }+ },+ "labelAt": { "$ref": "#/$defs/point" },+ "labelDx": { "type": "number" },+ "labelDy": { "type": "number" },+ "labelSegment": { "type": "integer", "minimum": 0 },+ "channelX": { "type": "number" },+ "channelY": { "type": "number" },+ "bias": { "type": "number", "minimum": 0, "maximum": 1 },+ "width": { "type": "number", "minimum": 0.5 }+ }+ }+ },+ "cards": {+ "type": "array",+ "items": {+ "type": "object",+ "additionalProperties": false,+ "required": ["dot", "title", "items"],+ "properties": {+ "dot": { "enum": ["cyan", "emerald", "violet", "amber", "rose", "orange", "slate"] },+ "title": { "type": "string", "minLength": 1 },+ "items": {+ "type": "array",+ "items": { "type": "string" }+ }+ }+ }+ }+ },+ "$defs": {+ "id": {+ "type": "string",+ "pattern": "^[a-zA-Z][a-zA-Z0-9_-]*$"+ },+ "side": {+ "enum": ["auto", "left", "right", "top", "bottom"]+ },+ "point": {+ "type": "array",+ "prefixItems": [+ { "type": "number" },+ { "type": "number" }+ ],+ "items": false,+ "minItems": 2,+ "maxItems": 2+ }+ }+}diff --git a/examples/workflow-agent-tool-call-rendered.html b/examples/workflow-agent-tool-call-rendered.htmlnew file mode 100644index 00000000..a4cb6f19--- /dev/null+++ b/examples/workflow-agent-tool-call-rendered.html@@ -0,0 +1,1095 @@+<!DOCTYPE html>+<html lang="en" data-theme="dark">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Agent Tool Call Workflow Diagram</title>+ <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600;700&display=swap" rel="stylesheet">+ <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;++ --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;++ --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, 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-dim);+ 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 {+ :root, [data-theme="dark"], [data-theme="light"] {+ --bg: #ffffff;+ --grid: transparent;+ --panel: #ffffff;+ --panel-border: #e2e8f0;+ --text: #0f172a;+ --text-muted: #475569;+ --text-dim: #94a3b8;+ --mask: #ffffff;+ }+ body { background: #ffffff !important; padding: 0; }+ .container { max-width: none; }+ .toolbar, .archify-toast { 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-dim);+ 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; }+ </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" aria-hidden="true">+ <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" aria-hidden="true">+ <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>Agent Tool Call Workflow</h1>+ </div>+ <p class="subtitle">Renderer-driven workflow prototype with lanes, anchored nodes, and orthogonal edges</p>+ </div>++ <!-- Main Diagram -->+ <div class="diagram-container">+ <svg viewBox="0 0 720 780">+ <!-- 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)" />++ <!-- Swimlanes -->+ <rect x="40" y="52" width="640" height="104" rx="10" class="c-lane" stroke-width="1"/>+ <text x="54" y="74" class="t-dim" font-size="10" font-weight="600">01 / User Interface</text>++ <rect x="40" y="176" width="640" height="104" rx="10" class="c-lane" stroke-width="1"/>+ <text x="54" y="198" class="t-dim" font-size="10" font-weight="600">02 / Agent Runtime</text>++ <rect x="40" y="300" width="640" height="104" rx="10" class="c-lane" stroke-width="1"/>+ <text x="54" y="322" class="t-dim" font-size="10" font-weight="600">03 / Policy Boundary</text>++ <rect x="40" y="424" width="640" height="104" rx="10" class="c-lane" stroke-width="1"/>+ <text x="54" y="446" class="t-dim" font-size="10" font-weight="600">04 / Tool Execution</text>++ <rect x="40" y="548" width="640" height="104" rx="10" class="c-lane" stroke-width="1"/>+ <text x="54" y="570" class="t-dim" font-size="10" font-weight="600">05 / Observability</text>++ <!-- Edge paths -->+ <path d="M 134 119 L 174 119" class="a-default" stroke-width="1.4" marker-end="url(#arrowhead)"/>+ <path d="M 220 145 L 220 166 L 300 166 L 300 209" class="a-emphasis" stroke-width="1.8" marker-end="url(#arrowhead-emphasis)"/>+ <path d="M 346 243 L 384 243" class="a-default" stroke-width="1.4" marker-end="url(#arrowhead)"/>+ <path d="M 430 269 L 430 290 L 430 290 L 430 333" class="a-security" stroke-width="1.4" marker-end="url(#arrowhead-security)"/>+ <path d="M 430 401 L 430 414 L 500 414 L 500 457" class="a-emphasis" stroke-width="1.8" marker-end="url(#arrowhead-emphasis)"/>+ <path d="M 546 491 L 579 491" class="a-default" stroke-width="1.4" marker-end="url(#arrowhead)"/>+ <path d="M 625 517 L 625 673 L 500 673 L 500 641" class="a-dashed" stroke-width="1.4" marker-end="url(#arrowhead-dashed)"/>+ <path d="M 546 615 L 692 615 L 692 119 L 671 119" class="a-emphasis" stroke-width="1.8" marker-end="url(#arrowhead-emphasis)"/>+ <path d="M 300 277 L 300 414 L 220 414 L 220 589" class="a-dashed" stroke-width="1.4" marker-end="url(#arrowhead-dashed)"/>+ <path d="M 266 615 L 454 615" class="a-dashed" stroke-width="1.4" marker-end="url(#arrowhead-dashed)"/>++ <!-- Nodes -->+ <rect x="42" y="93" width="92" height="52" rx="6" class="c-mask"/>+ <rect x="42" y="93" width="92" height="52" rx="6" class="c-external" stroke-width="1.5"/>+ <text x="88" y="114" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">User</text>+ <text x="88" y="131" class="t-muted" font-size="8" text-anchor="middle">asks for work</text>++ <rect x="174" y="93" width="92" height="52" rx="6" class="c-mask"/>+ <rect x="174" y="93" width="92" height="52" rx="6" class="c-frontend" stroke-width="1.5"/>+ <text x="220" y="114" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">Chat Surface</text>+ <text x="220" y="131" class="t-muted" font-size="8" text-anchor="middle">thread + files</text>++ <rect x="579" y="93" width="92" height="52" rx="6" class="c-mask"/>+ <rect x="579" y="93" width="92" height="52" rx="6" class="c-backend" stroke-width="1.5"/>+ <text x="625" y="114" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">Final Reply</text>+ <text x="625" y="131" class="t-muted" font-size="8" text-anchor="middle">answer + changes</text>++ <rect x="254" y="209" width="92" height="68" rx="6" class="c-mask"/>+ <rect x="254" y="209" width="92" height="68" rx="6" class="c-backend" stroke-width="1.5"/>+ <text x="300" y="230" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">Agent Planner</text>+ <text x="300" y="247" class="t-muted" font-size="8" text-anchor="middle">plan next step</text>+ <text x="300" y="265" class="t-backend" font-size="7" text-anchor="middle">context aware</text>++ <rect x="384" y="217" width="92" height="52" rx="6" class="c-mask"/>+ <rect x="384" y="217" width="92" height="52" rx="6" class="c-backend" stroke-width="1.5"/>+ <text x="430" y="238" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">Tool Router</text>+ <text x="430" y="255" class="t-muted" font-size="8" text-anchor="middle">choose capability</text>++ <rect x="384" y="333" width="92" height="68" rx="6" class="c-mask"/>+ <rect x="384" y="333" width="92" height="68" rx="6" class="c-security" stroke-width="1.5"/>+ <text x="430" y="354" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">Approval Gate</text>+ <text x="430" y="371" class="t-muted" font-size="8" text-anchor="middle">scope + consent</text>+ <text x="430" y="389" class="t-security" font-size="7" text-anchor="middle">block risky ops</text>++ <rect x="454" y="457" width="92" height="68" rx="6" class="c-mask"/>+ <rect x="454" y="457" width="92" height="68" rx="6" class="c-messagebus" stroke-width="1.5"/>+ <text x="500" y="478" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">Tool Call</text>+ <text x="500" y="495" class="t-muted" font-size="8" text-anchor="middle">shell / browser / MCP</text>+ <text x="500" y="513" class="t-messagebus" font-size="7" text-anchor="middle">structured result</text>++ <rect x="579" y="465" width="92" height="52" rx="6" class="c-mask"/>+ <rect x="579" y="465" width="92" height="52" rx="6" class="c-cloud" stroke-width="1.5"/>+ <text x="625" y="486" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">External API</text>+ <text x="625" y="503" class="t-muted" font-size="8" text-anchor="middle">network service</text>++ <rect x="174" y="589" width="92" height="52" rx="6" class="c-mask"/>+ <rect x="174" y="589" width="92" height="52" rx="6" class="c-database" stroke-width="1.5"/>+ <text x="220" y="610" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">Context Store</text>+ <text x="220" y="627" class="t-muted" font-size="8" text-anchor="middle">repo + memory</text>++ <rect x="454" y="589" width="92" height="52" rx="6" class="c-mask"/>+ <rect x="454" y="589" width="92" height="52" rx="6" class="c-database" stroke-width="1.5"/>+ <text x="500" y="610" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">Trace Log</text>+ <text x="500" y="627" class="t-muted" font-size="8" text-anchor="middle">events + output</text>++ <!-- Edge labels -->++ <rect x="245" y="146" width="30" height="14" rx="3" class="c-mask"/>+ <text x="260" y="156" class="t-backend" font-size="8" text-anchor="middle">plan</text>++ <rect x="423" y="277.5" width="82" height="14" rx="3" class="c-mask"/>+ <text x="464" y="287.5" class="t-security" font-size="8" text-anchor="middle">needs approval?</text>+ <rect x="440.8" y="408" width="48.4" height="14" rx="3" class="c-mask"/>+ <text x="465" y="418" class="t-backend" font-size="8" text-anchor="middle">approved</text>++ <rect x="526.3" y="653" width="72.4" height="14" rx="3" class="c-mask"/>+ <text x="562.5" y="663" class="t-database" font-size="8" text-anchor="middle">record result</text>+ <rect x="624.2" y="347" width="91.6" height="14" rx="3" class="c-mask"/>+ <text x="670" y="357" class="t-backend" font-size="8" text-anchor="middle">summarize outcome</text>+ <rect x="226.2" y="394" width="67.6" height="14" rx="3" class="c-mask"/>+ <text x="260" y="404" class="t-database" font-size="8" text-anchor="middle">load context</text>+ <rect x="327" y="612" width="106" height="14" rx="3" class="c-mask"/>+ <text x="380" y="622" class="t-database" font-size="8" text-anchor="middle">write trace + memory</text>++ <!-- Legend -->+ <text x="175" y="676" class="t-primary" font-size="10" font-weight="600">Legend</text>+ <rect x="175" y="688" width="14" height="9" rx="2" class="c-frontend" stroke-width="1"/>+ <text x="195" y="696" class="t-muted" font-size="7">User UI</text>+ <rect x="260" y="688" width="14" height="9" rx="2" class="c-backend" stroke-width="1"/>+ <text x="280" y="696" class="t-muted" font-size="7">Agent logic</text>+ <rect x="370" y="688" width="14" height="9" rx="2" class="c-security" stroke-width="1"/>+ <text x="390" y="696" class="t-muted" font-size="7">Policy</text>+ <rect x="455" y="688" width="14" height="9" rx="2" class="c-messagebus" stroke-width="1"/>+ <text x="475" y="696" class="t-muted" font-size="7">Tool action</text>+ <rect x="565" y="688" width="14" height="9" rx="2" class="c-database" stroke-width="1"/>+ <text x="585" y="696" class="t-muted" font-size="7">Context / trace</text>+ </svg>+ </div>++ <!-- Info Cards -->+ <div class="cards">+ <div class="card">+ <div class="card-header">+ <div class="card-dot cyan"></div>+ <h3>Renderer Rules</h3>+ </div>+ <ul>+ <li>• Lanes and columns determine node placement</li>+ <li>• Edges attach to explicit node anchors</li>+ <li>• Cross-lane paths use orthogonal routing</li>+ <li>• Short adjacent links stay unlabeled</li>+ </ul>+ </div>++ <div class="card">+ <div class="card-header">+ <div class="card-dot rose"></div>+ <h3>Workflow Semantics</h3>+ </div>+ <ul>+ <li>• Approval is a first-class policy step</li>+ <li>• Consent gates are visible in the main path</li>+ <li>• External calls stay inside the tool lane</li>+ <li>• Trace writes are separate from the hot path</li>+ </ul>+ </div>++ <div class="card">+ <div class="card-header">+ <div class="card-dot emerald"></div>+ <h3>Why It Matters</h3>+ </div>+ <ul>+ <li>• This is closer to a diagram_type renderer</li>+ <li>• The graph can be edited without SVG surgery</li>+ <li>• Layout rules can be tested and improved</li>+ <li>• A future IR can reuse this shape directly</li>+ </ul>+ </div>+ </div>++ <!-- Footer -->+ <p class="footer">+ Workflow diagram • Built with Archify • Press <kbd>T</kbd> for theme and <kbd>E</kbd> for export+ </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');++ function resolveInitial() {+ // 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 (_) {}+ var saved = localStorage.getItem(STORAGE_KEY);+ 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);+ localStorage.setItem(STORAGE_KEY, next);+ }++ apply(resolveInitial());+ btn.addEventListener('click', toggle);++ 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, '').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');++ var hostStyle = Array.prototype.map.call(document.querySelectorAll('style'), function (s) {+ return s.textContent;+ }).join('\n');++ var varNames = [+ '--bg','--grid','--text','--text-muted','--text-dim',+ '--arrow','--arrow-emphasis','--mask',+ '--frontend-fill','--frontend-stroke',+ '--backend-fill','--backend-stroke',+ '--database-fill','--database-stroke',+ '--cloud-fill','--cloud-stroke',+ '--security-fill','--security-stroke',+ '--messagebus-fill','--messagebus-stroke',+ '--external-fill','--external-stroke'+ ];++ // 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, 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, 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 ----------------------------------------------------------+ function toast(msg) {+ var t = document.createElement('div');+ t.className = 'archify-toast';+ t.textContent = msg;+ document.body.appendChild(t);+ requestAnimationFrame(function () { t.classList.add('show'); });+ setTimeout(function () {+ t.classList.remove('show');+ setTimeout(function () { t.remove(); }, 300);+ }, 1500);+ }++ function open() {+ menu.classList.add('open');+ btn.setAttribute('aria-expanded', 'true');+ var first = items().filter(function (i) { return !i.disabled; })[0];+ if (first) first.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();+ });+ 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(false);+ 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(false);+ if (!canCopyImage()) {+ alert('Clipboard image write not supported in this browser.');+ return;+ }+ return rasterize('png').then(function (blob) {+ return navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);+ }).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>