Skip to content

Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.

Add sequence diagram renderer

tt-a1i7fb88d974cd9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1a051848..ad922de6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,9 @@ All notable changes are documented here. Format loosely follows [Keep a Changelo
- **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`.
+- **Sequence diagram mode.** Added a renderer-backed sequence diagram type for API call chains, request lifecycles, cache fallback paths, authentication checks, async trace emission, and service interactions over time.
+- **Sequence JSON Schema.** Added `archify/schemas/sequence.schema.json` to document and validate the sequence IR shape.
+- **Sequence example.** Added a rendered cache-miss request sequence example at `examples/sequence-cache-miss-request.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.
diff --git a/README.md b/README.md
index e9db49bc..067aa655 100644
--- a/README.md
+++ b/README.md
@@ -2,12 +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,在浏览器里打开就能切主题、复制到剪贴板、导出成各种图片格式。
- **不需要会画图** —— 把组件和连接关系说给 Claude 就行
-- **支持 workflow** —— 技术流程、审批链、工具调用、CI/CD、运维 runbook 都可以用泳道图表达
+- **支持 workflow / sequence** —— 技术流程、审批链、工具调用、CI/CD、请求调用链都可以画
- **内置主题切换** —— 深色 / 浅色一键切,浏览器记住偏好
- **一键复制到剪贴板** —— 直接贴到 Slack、飞书、微信、Notion、GitHub issue
- **导出图片超清晰** —— PNG / JPEG / WebP 全部由浏览器在 4× 源分辨率下**原生光栅化**(不是位图放大,没有糊),或导出 SVG 做真矢量
@@ -38,12 +38,13 @@ Export 菜单 —— 复制到剪贴板 + 四种格式下载:
## 图表类型
-Archify 现在有两种主要输出:
+Archify 现在有三种主要输出:
| 类型 | 适合画什么 | 怎么用 |
|---|---|---|
| **Architecture** | 系统组件、云资源、数据库、缓存、服务边界、安全组 | 直接描述系统结构 |
| **Workflow** | 请求生命周期、审批流程、工具调用、CI/CD、运维 runbook、事故响应 | 说明参与方、步骤顺序、关键分支 |
+| **Sequence** | API 调用链、请求生命周期、缓存回源、鉴权、异步 trace、服务交互 | 说明谁调用谁、先后顺序、返回路径 |
Workflow 不是通用流程图的替代品,它更偏“技术沟通图”:有泳道、有语义颜色、有主路径和异步/审批/观测路径。比如:
@@ -54,6 +55,15 @@ Workflow 不是通用流程图的替代品,它更偏“技术沟通图”:
本仓库里有一个可打开的示例:[`examples/workflow-agent-tool-call-rendered.html`](examples/workflow-agent-tool-call-rendered.html)。
+Sequence 用来解释更细的交互顺序,比如:
+
+```
+用 archify 画一个 sequence diagram:
+用户打开页面,前端请求 API,API 校验 JWT,读取 Redis,缓存未命中则查 Postgres,返回结果并写入 trace。
+```
+
+示例:[`examples/sequence-cache-miss-request.html`](examples/sequence-cache-miss-request.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.md
index d104504a..dc1a297b 100644
--- a/README_EN.md
+++ b/README_EN.md
@@ -2,12 +2,12 @@
# Archify
-**Generate beautiful architecture and technical workflow diagrams in chat. Switch dark / light. Copy to clipboard or export crisp 4× PNG / JPEG / WebP / SVG.**
+**Generate beautiful architecture, technical workflow, and sequence 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 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
+- **Workflow and sequence diagrams too** — technical flows, approvals, tool calls, CI/CD, runbooks, and request call chains can be drawn
- **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
@@ -37,12 +37,13 @@ Live example: [`examples/web-app.html`](examples/web-app.html) — open in a bro
## Diagram types
-Archify now has two primary outputs:
+Archify now has three 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 |
+| **Sequence** | API call chains, request lifecycles, cache fallback, auth checks, async trace, service interactions | Describe who calls whom, in what order, and what returns |
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.
@@ -53,6 +54,15 @@ User submits a request -> Agent plans -> Approval Gate if needed -> Tool Call ->
Open the example here: [`examples/workflow-agent-tool-call-rendered.html`](examples/workflow-agent-tool-call-rendered.html).
+Sequence diagrams explain a narrower interaction over time:
+
+```text
+Use archify to draw a sequence diagram:
+User opens a page, the frontend calls the API, the API verifies JWT, reads Redis, falls back to Postgres on cache miss, returns JSON, and emits trace.
+```
+
+Open the example here: [`examples/sequence-cache-miss-request.html`](examples/sequence-cache-miss-request.html).
+
## What's new
Archify 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.md
index 6981541f..20aada75 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -105,6 +105,12 @@ Workflow diagrams became the first concrete test of typed diagram renderers insi
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.
+### Sequence renderer pilot (2026-04-24)
+
+Sequence diagrams became the second typed renderer pilot. They use `diagram_type: "sequence"` JSON with participants, time segments, messages, activations, and summary cards. The goal is to explain API call chains, request lifecycles, auth checks, cache fallback, async trace/logging, and return paths with Archify's theme/export shell.
+
+Like workflow, sequence is not a generic auto-layout target. The renderer enforces readable spacing and semantic styling, while Claude still decides which participants matter, how the story is grouped, which messages deserve labels, and which return/async paths should stay quiet.
+
---
## Not planned
diff --git a/archify.zip b/archify.zip
index d9283888..ef6dddf5 100644
Binary files a/archify.zip and b/archify.zip differ
diff --git a/archify/SKILL.md b/archify/SKILL.md
index 93a75bf2..ee6e8246 100644
--- a/archify/SKILL.md
+++ b/archify/SKILL.md
@@ -1,6 +1,6 @@
---
name: archify
-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.
+description: Create professional architecture, workflow, and sequence 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, process diagrams, API call sequences, request lifecycles, or interaction diagrams.
license: MIT
metadata:
version: "2.4"
@@ -20,17 +20,20 @@ Every diagram this skill produces ships with:
## Diagram Types
-Archify supports two technical diagram modes:
+Archify supports three 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 |
+| `sequence` | API calls, request lifecycles, service interactions, cache fallback paths, async trace/logging, and return paths over time | Prefer `renderers/sequence/render-sequence.mjs` with a sequence 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.
+When the user says "sequence", "interaction", "call sequence", "request lifecycle", "API call chain", "who calls whom", or asks how multiple participants interact over time, use the `sequence` mode.
+
### Workflow Mode
Workflow diagrams use a compact JSON IR:
@@ -72,6 +75,46 @@ The renderer:
Use workflow labels sparingly. Adjacent steps should often be unlabeled; reserve labels for cross-lane transitions, approval decisions, async trace writes, and return paths.
+### Sequence Mode
+
+Sequence diagrams use a compact JSON IR:
+
+```json
+{
+ "schema_version": 1,
+ "diagram_type": "sequence",
+ "meta": {
+ "title": "Cache Miss Request Sequence",
+ "subtitle": "Frontend request path with auth and cache fallback",
+ "output": "cache-miss-request.html",
+ "viewBox": [820, 760]
+ },
+ "participants": [
+ { "id": "web", "type": "frontend", "label": "Web App", "sublabel": "React UI" },
+ { "id": "api", "type": "backend", "label": "API", "sublabel": "request handler" }
+ ],
+ "messages": [],
+ "activations": [],
+ "cards": []
+}
+```
+
+If you have filesystem/tool access, create a sequence JSON file and render it with:
+
+```bash
+node archify/renderers/sequence/render-sequence.mjs sequence.json sequence.html
+```
+
+The renderer:
+
+- Places participants across the top and time downward
+- Uses semantic message variants: `emphasis`, `security`, `return`, and `dashed`
+- Uses activation bars to show ownership duration
+- Uses light segment bands as story landmarks
+- Fails fast when participants overflow, message endpoints are unknown, or message rows are too tight
+
+Use sequence diagrams when the important thing is order over time. Keep labels short; prefer "GET /path", "verify JWT", "cache miss", "emit trace", and "200 JSON" over prose sentences.
+
## The Cardinal Rule: Use CSS Classes, Not Inline Colors
The 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.
diff --git a/archify/examples/cache-miss-request.sequence.json b/archify/examples/cache-miss-request.sequence.json
new file mode 100644
index 00000000..6a10a97e
--- /dev/null
+++ b/archify/examples/cache-miss-request.sequence.json
@@ -0,0 +1,75 @@
+{
+ "schema_version": 1,
+ "diagram_type": "sequence",
+ "meta": {
+ "title": "Cache Miss Request Sequence",
+ "subtitle": "Frontend request path with auth, cache fallback, persistence, and async trace",
+ "output": "examples/sequence-cache-miss-request.html",
+ "viewBox": [820, 760]
+ },
+ "participants": [
+ { "id": "user", "type": "external", "label": "User", "sublabel": "browser session" },
+ { "id": "web", "type": "frontend", "label": "Web App", "sublabel": "React UI" },
+ { "id": "api", "type": "backend", "label": "API", "sublabel": "request handler" },
+ { "id": "auth", "type": "security", "label": "Auth", "sublabel": "JWT verify" },
+ { "id": "redis", "type": "database", "label": "Redis", "sublabel": "cache" },
+ { "id": "db", "type": "database", "label": "Postgres", "sublabel": "source of truth" },
+ { "id": "trace", "type": "messagebus", "label": "Trace", "sublabel": "async event" }
+ ],
+ "segments": [
+ { "from": 150, "to": 295, "label": "Request" },
+ { "from": 315, "to": 505, "label": "Fallback" },
+ { "from": 525, "to": 665, "label": "Response + trace" }
+ ],
+ "messages": [
+ { "from": "user", "to": "web", "y": 185, "label": "open page", "variant": "default" },
+ { "from": "web", "to": "api", "y": 228, "label": "GET /dashboard", "variant": "emphasis" },
+ { "from": "api", "to": "auth", "y": 270, "label": "verify JWT", "variant": "security" },
+ { "from": "auth", "to": "api", "y": 305, "label": "claims ok", "variant": "return" },
+ { "from": "api", "to": "redis", "y": 354, "label": "read cache", "variant": "default" },
+ { "from": "redis", "to": "api", "y": 391, "label": "miss", "variant": "return" },
+ { "from": "api", "to": "db", "y": 443, "label": "query profile + metrics", "variant": "emphasis" },
+ { "from": "db", "to": "api", "y": 489, "label": "rows", "variant": "return" },
+ { "from": "api", "to": "redis", "y": 536, "label": "set cache", "variant": "dashed" },
+ { "from": "api", "to": "trace", "y": 580, "label": "emit trace", "variant": "dashed" },
+ { "from": "api", "to": "web", "y": 625, "label": "200 JSON", "variant": "return" },
+ { "from": "web", "to": "user", "y": 662, "label": "render", "variant": "return" }
+ ],
+ "activations": [
+ { "participant": "web", "from": 220, "to": 668, "type": "frontend" },
+ { "participant": "api", "from": 228, "to": 632, "type": "backend" },
+ { "participant": "auth", "from": 265, "to": 310, "type": "security" },
+ { "participant": "redis", "from": 349, "to": 398, "type": "database" },
+ { "participant": "db", "from": 438, "to": 496, "type": "database" },
+ { "participant": "trace", "from": 575, "to": 630, "type": "messagebus" }
+ ],
+ "cards": [
+ {
+ "dot": "emerald",
+ "title": "Happy Path",
+ "items": [
+ "The main request is Web App -> API -> data source -> response",
+ "Return messages are quieter than forward calls",
+ "Activation bars make ownership duration visible"
+ ]
+ },
+ {
+ "dot": "rose",
+ "title": "Policy + Fallback",
+ "items": [
+ "JWT verification is colored as a security interaction",
+ "Cache miss is visible without overpowering the main path",
+ "Database access only appears after cache fallback"
+ ]
+ },
+ {
+ "dot": "orange",
+ "title": "Async Trace",
+ "items": [
+ "Trace emission is dashed and secondary",
+ "It does not block the response path",
+ "The diagram separates user-facing latency from observability"
+ ]
+ }
+ ]
+}
diff --git a/archify/renderers/sequence/README.md b/archify/renderers/sequence/README.md
new file mode 100644
index 00000000..a0830beb
--- /dev/null
+++ b/archify/renderers/sequence/README.md
@@ -0,0 +1,55 @@
+# Sequence Renderer
+
+Render `diagram_type: "sequence"` JSON files into the standard Archify HTML
+template.
+
+```bash
+node archify/renderers/sequence/render-sequence.mjs input.sequence.json output.html
+```
+
+If `output.html` is omitted, the renderer uses `meta.output` from the JSON file
+or falls back to `sequence.html` in the current working directory.
+
+## Input
+
+Sequence JSON files must set:
+
+```json
+{
+ "schema_version": 1,
+ "diagram_type": "sequence",
+ "meta": {
+ "title": "Cache Miss Request Sequence",
+ "subtitle": "Frontend request path with auth and cache fallback",
+ "viewBox": [820, 760]
+ },
+ "participants": [],
+ "segments": [],
+ "messages": [],
+ "activations": [],
+ "cards": []
+}
+```
+
+The schema lives at:
+
+```text
+archify/schemas/sequence.schema.json
+```
+
+## Design Rules
+
+- Put participants across the top, ordered by the story the reader should
+ follow.
+- Time moves downward.
+- Use `emphasis` for the main request path.
+- Use `security` for auth, consent, permission, and policy calls.
+- Use `return` for quiet response messages.
+- Use `dashed` for async trace, event, logging, and non-blocking work.
+- Use segments as light background guides; keep segment labels short.
+- Keep labels short enough to fit in narrow previews.
+
+The renderer fails when it can detect layout problems, including missing
+participants, duplicate participant IDs, unknown message endpoints, messages
+outside the readable timeline, overly tight vertical message spacing, invalid
+activation ranges, or participants that exceed the viewBox.
diff --git a/archify/renderers/sequence/render-sequence.mjs b/archify/renderers/sequence/render-sequence.mjs
new file mode 100644
index 00000000..55f58ba7
--- /dev/null
+++ b/archify/renderers/sequence/render-sequence.mjs
@@ -0,0 +1,270 @@
+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 inputPath = path.resolve(process.argv[2] || path.join(skillRoot, 'examples/cache-miss-request.sequence.json'));
+const sequence = 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] || sequence.meta.output || 'sequence.html');
+
+const viewBox = sequence.meta.viewBox || [920, 760];
+const layout = {
+ topY: 72,
+ participantW: 86,
+ participantH: 54,
+ lifelineTop: 142,
+ lifelineBottom: 695,
+ leftX: 62,
+ colGap: 108,
+ labelH: 16
+};
+
+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'],
+ return: ['a-default', 'arrowhead']
+};
+
+function esc(value) {
+ return String(value ?? '').replace(/[&<>"']/g, (c) => ({
+ '&': '&amp;',
+ '<': '&lt;',
+ '>': '&gt;',
+ '"': '&quot;',
+ "'": '&#39;'
+ }[c]));
+}
+
+function participantX(index) {
+ return layout.leftX + index * layout.colGap;
+}
+
+const participants = new Map(sequence.participants.map((participant, index) => [
+ participant.id,
+ {
+ ...participant,
+ index,
+ cx: participantX(index),
+ x: participantX(index) - layout.participantW / 2
+ }
+]));
+
+function validateSequence() {
+ const problems = [];
+ if (sequence.schema_version !== 1) problems.push('Sequence files must set "schema_version": 1.');
+ if (sequence.diagram_type !== 'sequence') problems.push('Sequence files must set "diagram_type": "sequence".');
+ if (!sequence.meta?.title) problems.push('Sequence files must include meta.title.');
+ if (!Array.isArray(sequence.participants) || sequence.participants.length < 2) {
+ problems.push('Sequence diagrams need at least two participants.');
+ }
+ if (participants.size !== sequence.participants.length) problems.push('Participant ids must be unique.');
+
+ for (const message of sequence.messages || []) {
+ if (!participants.has(message.from)) problems.push(`Message "${message.label}" references unknown source "${message.from}".`);
+ if (!participants.has(message.to)) problems.push(`Message "${message.label}" references unknown target "${message.to}".`);
+ if (typeof message.y !== 'number') problems.push(`Message "${message.label}" must provide a numeric y.`);
+ if (message.y < layout.lifelineTop + 18 || message.y > layout.lifelineBottom - 18) {
+ problems.push(`Message "${message.label}" sits outside the readable timeline.`);
+ }
+ if (participants.has(message.from) && participants.has(message.to)) {
+ const distance = Math.abs(participants.get(message.to).cx - participants.get(message.from).cx);
+ if (distance < 60) problems.push(`Message "${message.label}" is too short to read cleanly.`);
+ }
+ }
+
+ const sorted = [...(sequence.messages || [])].sort((a, b) => a.y - b.y);
+ for (let i = 1; i < sorted.length; i += 1) {
+ if (sorted[i].y - sorted[i - 1].y < 28) {
+ problems.push(`Messages "${sorted[i - 1].label}" and "${sorted[i].label}" are too close vertically.`);
+ }
+ }
+
+ for (const activation of sequence.activations || []) {
+ if (!participants.has(activation.participant)) problems.push(`Activation references unknown participant "${activation.participant}".`);
+ if (activation.to <= activation.from) problems.push(`Activation for "${activation.participant}" has invalid time range.`);
+ }
+
+ const lastParticipant = sequence.participants[sequence.participants.length - 1];
+ if (lastParticipant && participants.get(lastParticipant.id).cx + layout.participantW / 2 > viewBox[0] - 40) {
+ problems.push('Participants exceed viewBox width.');
+ }
+
+ if (problems.length) {
+ throw new Error(`Sequence layout validation failed:\n- ${problems.join('\n- ')}`);
+ }
+}
+
+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 renderParticipant(participant) {
+ const fill = typeClass[participant.type] || 'c-external';
+ return ` <rect x="${participant.x}" y="${layout.topY}" width="${layout.participantW}" height="${layout.participantH}" rx="6" class="c-mask"/>
+ <rect x="${participant.x}" y="${layout.topY}" width="${layout.participantW}" height="${layout.participantH}" rx="6" class="${fill}" stroke-width="1.5"/>
+ <text x="${participant.cx}" y="${layout.topY + 22}" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">${esc(participant.label)}</text>
+ <text x="${participant.cx}" y="${layout.topY + 39}" class="t-muted" font-size="7" text-anchor="middle">${esc(participant.sublabel)}</text>`;
+}
+
+function renderLifeline(participant) {
+ return ` <path d="M ${participant.cx} ${layout.lifelineTop} L ${participant.cx} ${layout.lifelineBottom}" class="a-default" stroke-width="0.8" stroke-dasharray="3,7"/>`;
+}
+
+function renderSegment(segment) {
+ return ` <rect x="48" y="${segment.from}" width="${viewBox[0] - 96}" height="${segment.to - segment.from}" rx="10" class="c-lane" stroke-width="1"/>
+ <text x="62" y="${segment.from + 18}" class="t-dim" font-size="9" font-weight="600">${esc(segment.label)}</text>`;
+}
+
+function renderActivation(activation) {
+ const participant = participants.get(activation.participant);
+ const fill = typeClass[activation.type] || typeClass[participant.type] || 'c-external';
+ const x = participant.cx - 5;
+ const height = activation.to - activation.from;
+ return ` <rect x="${x}" y="${activation.from}" width="10" height="${height}" rx="3" class="c-mask"/>
+ <rect x="${x}" y="${activation.from}" width="10" height="${height}" rx="3" class="${fill}" stroke-width="1"/>`;
+}
+
+function messageLabel(message, x1, x2) {
+ const center = (x1 + x2) / 2;
+ const y = message.y - 10;
+ const labelW = Math.max(34, message.label.length * 5.2 + 12);
+ const accent = message.variant === 'security'
+ ? 't-security'
+ : message.variant === 'dashed'
+ ? 't-messagebus'
+ : message.variant === 'return'
+ ? 't-muted'
+ : 't-backend';
+ return ` <rect x="${center - labelW / 2}" y="${y - 10}" width="${labelW}" height="${layout.labelH}" rx="3" class="c-mask"/>
+ <text x="${center}" y="${y}" class="${accent}" font-size="9" text-anchor="middle">${esc(message.label)}</text>`;
+}
+
+function renderMessage(message) {
+ const from = participants.get(message.from);
+ const to = participants.get(message.to);
+ const direction = to.cx > from.cx ? 1 : -1;
+ const start = from.cx + direction * 7;
+ const end = to.cx - direction * 7;
+ const [cls, marker] = arrowClass[message.variant || 'default'] || arrowClass.default;
+ const strokeWidth = message.variant === 'emphasis' ? 1.8 : 1.4;
+ const dash = message.variant === 'return' ? ' stroke-dasharray="3,5"' : '';
+ const note = message.note
+ ? `\n <text x="${Math.min(start, end) + 12}" y="${message.y + 18}" class="t-dim" font-size="7">${esc(message.note)}</text>`
+ : '';
+ return ` <path d="M ${start} ${message.y} L ${end} ${message.y}" class="${cls}" stroke-width="${strokeWidth}"${dash} marker-end="url(#${marker})"/>
+${messageLabel(message, start, end)}${note}`;
+}
+
+function renderLegend() {
+ const y = 706;
+ return ` <text x="150" y="${y - 20}" class="t-primary" font-size="10" font-weight="600">Legend</text>
+ <path d="M 150 ${y} L 184 ${y}" class="a-emphasis" stroke-width="1.8" marker-end="url(#arrowhead-emphasis)"/>
+ <text x="193" y="${y + 3}" class="t-muted" font-size="8">request</text>
+ <path d="M 270 ${y} L 304 ${y}" class="a-default" stroke-width="1.4" stroke-dasharray="3,5" marker-end="url(#arrowhead)"/>
+ <text x="313" y="${y + 3}" class="t-muted" font-size="8">return</text>
+ <path d="M 385 ${y} L 419 ${y}" class="a-security" stroke-width="1.4" marker-end="url(#arrowhead-security)"/>
+ <text x="428" y="${y + 3}" class="t-muted" font-size="8">security</text>
+ <path d="M 530 ${y} L 564 ${y}" class="a-dashed" stroke-width="1.4" marker-end="url(#arrowhead-dashed)"/>
+ <text x="573" y="${y + 3}" class="t-muted" font-size="8">async trace</text>`;
+}
+
+function renderSvg() {
+ const participantList = [...participants.values()];
+ return ` <svg viewBox="0 0 ${viewBox[0]} ${viewBox[1]}">
+${renderDefinitions()}
+
+ <!-- Background Grid -->
+ <rect width="100%" height="100%" fill="url(#grid)" />
+
+ <!-- Time Segments -->
+${(sequence.segments || []).map(renderSegment).join('\n\n')}
+
+ <!-- Lifelines -->
+${participantList.map(renderLifeline).join('\n')}
+
+ <!-- Messages -->
+${(sequence.messages || []).map(renderMessage).join('\n\n')}
+
+ <!-- Activations -->
+${(sequence.activations || []).map(renderActivation).join('\n')}
+
+ <!-- Participants -->
+${participantList.map(renderParticipant).join('\n\n')}
+
+ <!-- Legend -->
+${renderLegend()}
+ </svg>`;
+}
+
+function renderCards() {
+ return ` <!-- Info Cards -->
+ <div class="cards">
+${(sequence.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>&bull; ${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(sequence.meta.title)} Diagram</title>`)
+ .replace('<h1>[PROJECT NAME] Architecture</h1>', `<h1>${esc(sequence.meta.title)}</h1>`)
+ .replace('<p class="subtitle">[Subtitle description]</p>', `<p class="subtitle">${esc(sequence.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] &bull; [Additional metadata]', 'Sequence diagram &bull; Built with Archify &bull; Press <kbd>T</kbd> for theme and <kbd>E</kbd> for export');
+}
+
+validateSequence();
+fs.mkdirSync(path.dirname(outPath), { recursive: true });
+fs.writeFileSync(outPath, applyTemplate(renderSvg(), renderCards()));
+console.log(outPath);
diff --git a/archify/schemas/sequence.schema.json b/archify/schemas/sequence.schema.json
new file mode 100644
index 00000000..2564842a
--- /dev/null
+++ b/archify/schemas/sequence.schema.json
@@ -0,0 +1,123 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://github.com/tt-a1i/archify/schemas/sequence.schema.json",
+ "title": "Archify Sequence Diagram",
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["schema_version", "diagram_type", "meta", "participants", "messages"],
+ "properties": {
+ "schema_version": {
+ "const": 1
+ },
+ "diagram_type": {
+ "const": "sequence"
+ },
+ "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
+ }
+ }
+ },
+ "participants": {
+ "type": "array",
+ "minItems": 2,
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["id", "type", "label"],
+ "properties": {
+ "id": { "$ref": "#/$defs/id" },
+ "type": {
+ "enum": ["frontend", "backend", "database", "cloud", "security", "messagebus", "external"]
+ },
+ "label": { "type": "string", "minLength": 1 },
+ "sublabel": { "type": "string" }
+ }
+ }
+ },
+ "segments": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["from", "to", "label"],
+ "properties": {
+ "from": { "type": "number" },
+ "to": { "type": "number" },
+ "label": { "type": "string", "minLength": 1 }
+ }
+ }
+ },
+ "messages": {
+ "type": "array",
+ "minItems": 1,
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["from", "to", "y", "label"],
+ "properties": {
+ "from": { "$ref": "#/$defs/id" },
+ "to": { "$ref": "#/$defs/id" },
+ "y": { "type": "number" },
+ "label": { "type": "string", "minLength": 1 },
+ "variant": {
+ "enum": ["default", "emphasis", "security", "dashed", "return"]
+ },
+ "note": { "type": "string" }
+ }
+ }
+ },
+ "activations": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["participant", "from", "to"],
+ "properties": {
+ "participant": { "$ref": "#/$defs/id" },
+ "from": { "type": "number" },
+ "to": { "type": "number" },
+ "type": {
+ "enum": ["frontend", "backend", "database", "cloud", "security", "messagebus", "external"]
+ }
+ }
+ }
+ },
+ "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_-]*$"
+ }
+ }
+}
diff --git a/examples/sequence-cache-miss-request.html b/examples/sequence-cache-miss-request.html
new file mode 100644
index 00000000..c7bf0376
--- /dev/null
+++ b/examples/sequence-cache-miss-request.html
@@ -0,0 +1,1107 @@
+<!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>Cache Miss Request Sequence 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">&#9790;</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">&#9662;</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>Cache Miss Request Sequence</h1>
+ </div>
+ <p class="subtitle">Frontend request path with auth, cache fallback, persistence, and async trace</p>
+ </div>
+
+ <!-- Main Diagram -->
+ <div class="diagram-container">
+ <svg viewBox="0 0 820 760">
+ <!-- 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)" />
+
+ <!-- Time Segments -->
+ <rect x="48" y="150" width="724" height="145" rx="10" class="c-lane" stroke-width="1"/>
+ <text x="62" y="168" class="t-dim" font-size="9" font-weight="600">Request</text>
+
+ <rect x="48" y="315" width="724" height="190" rx="10" class="c-lane" stroke-width="1"/>
+ <text x="62" y="333" class="t-dim" font-size="9" font-weight="600">Fallback</text>
+
+ <rect x="48" y="525" width="724" height="140" rx="10" class="c-lane" stroke-width="1"/>
+ <text x="62" y="543" class="t-dim" font-size="9" font-weight="600">Response + trace</text>
+
+ <!-- Lifelines -->
+ <path d="M 62 142 L 62 695" class="a-default" stroke-width="0.8" stroke-dasharray="3,7"/>
+ <path d="M 170 142 L 170 695" class="a-default" stroke-width="0.8" stroke-dasharray="3,7"/>
+ <path d="M 278 142 L 278 695" class="a-default" stroke-width="0.8" stroke-dasharray="3,7"/>
+ <path d="M 386 142 L 386 695" class="a-default" stroke-width="0.8" stroke-dasharray="3,7"/>
+ <path d="M 494 142 L 494 695" class="a-default" stroke-width="0.8" stroke-dasharray="3,7"/>
+ <path d="M 602 142 L 602 695" class="a-default" stroke-width="0.8" stroke-dasharray="3,7"/>
+ <path d="M 710 142 L 710 695" class="a-default" stroke-width="0.8" stroke-dasharray="3,7"/>
+
+ <!-- Messages -->
+ <path d="M 69 185 L 163 185" class="a-default" stroke-width="1.4" marker-end="url(#arrowhead)"/>
+ <rect x="86.6" y="165" width="58.800000000000004" height="16" rx="3" class="c-mask"/>
+ <text x="116" y="175" class="t-backend" font-size="9" text-anchor="middle">open page</text>
+
+ <path d="M 177 228 L 271 228" class="a-emphasis" stroke-width="1.8" marker-end="url(#arrowhead-emphasis)"/>
+ <rect x="181.6" y="208" width="84.8" height="16" rx="3" class="c-mask"/>
+ <text x="224" y="218" class="t-backend" font-size="9" text-anchor="middle">GET /dashboard</text>
+
+ <path d="M 285 270 L 379 270" class="a-security" stroke-width="1.4" marker-end="url(#arrowhead-security)"/>
+ <rect x="300" y="250" width="64" height="16" rx="3" class="c-mask"/>
+ <text x="332" y="260" class="t-security" font-size="9" text-anchor="middle">verify JWT</text>
+
+ <path d="M 379 305 L 285 305" class="a-default" stroke-width="1.4" stroke-dasharray="3,5" marker-end="url(#arrowhead)"/>
+ <rect x="302.6" y="285" width="58.800000000000004" height="16" rx="3" class="c-mask"/>
+ <text x="332" y="295" class="t-muted" font-size="9" text-anchor="middle">claims ok</text>
+
+ <path d="M 285 354 L 487 354" class="a-default" stroke-width="1.4" marker-end="url(#arrowhead)"/>
+ <rect x="354" y="334" width="64" height="16" rx="3" class="c-mask"/>
+ <text x="386" y="344" class="t-backend" font-size="9" text-anchor="middle">read cache</text>
+
+ <path d="M 487 391 L 285 391" class="a-default" stroke-width="1.4" stroke-dasharray="3,5" marker-end="url(#arrowhead)"/>
+ <rect x="369" y="371" width="34" height="16" rx="3" class="c-mask"/>
+ <text x="386" y="381" class="t-muted" font-size="9" text-anchor="middle">miss</text>
+
+ <path d="M 285 443 L 595 443" class="a-emphasis" stroke-width="1.8" marker-end="url(#arrowhead-emphasis)"/>
+ <rect x="374.2" y="423" width="131.60000000000002" height="16" rx="3" class="c-mask"/>
+ <text x="440" y="433" class="t-backend" font-size="9" text-anchor="middle">query profile + metrics</text>
+
+ <path d="M 595 489 L 285 489" class="a-default" stroke-width="1.4" stroke-dasharray="3,5" marker-end="url(#arrowhead)"/>
+ <rect x="423" y="469" width="34" height="16" rx="3" class="c-mask"/>
+ <text x="440" y="479" class="t-muted" font-size="9" text-anchor="middle">rows</text>
+
+ <path d="M 285 536 L 487 536" class="a-dashed" stroke-width="1.4" marker-end="url(#arrowhead-dashed)"/>
+ <rect x="356.6" y="516" width="58.800000000000004" height="16" rx="3" class="c-mask"/>
+ <text x="386" y="526" class="t-messagebus" font-size="9" text-anchor="middle">set cache</text>
+
+ <path d="M 285 580 L 703 580" class="a-dashed" stroke-width="1.4" marker-end="url(#arrowhead-dashed)"/>
+ <rect x="462" y="560" width="64" height="16" rx="3" class="c-mask"/>
+ <text x="494" y="570" class="t-messagebus" font-size="9" text-anchor="middle">emit trace</text>
+
+ <path d="M 271 625 L 177 625" class="a-default" stroke-width="1.4" stroke-dasharray="3,5" marker-end="url(#arrowhead)"/>
+ <rect x="197.2" y="605" width="53.6" height="16" rx="3" class="c-mask"/>
+ <text x="224" y="615" class="t-muted" font-size="9" text-anchor="middle">200 JSON</text>
+
+ <path d="M 163 662 L 69 662" class="a-default" stroke-width="1.4" stroke-dasharray="3,5" marker-end="url(#arrowhead)"/>
+ <rect x="94.4" y="642" width="43.2" height="16" rx="3" class="c-mask"/>
+ <text x="116" y="652" class="t-muted" font-size="9" text-anchor="middle">render</text>
+
+ <!-- Activations -->
+ <rect x="165" y="220" width="10" height="448" rx="3" class="c-mask"/>
+ <rect x="165" y="220" width="10" height="448" rx="3" class="c-frontend" stroke-width="1"/>
+ <rect x="273" y="228" width="10" height="404" rx="3" class="c-mask"/>
+ <rect x="273" y="228" width="10" height="404" rx="3" class="c-backend" stroke-width="1"/>
+ <rect x="381" y="265" width="10" height="45" rx="3" class="c-mask"/>
+ <rect x="381" y="265" width="10" height="45" rx="3" class="c-security" stroke-width="1"/>
+ <rect x="489" y="349" width="10" height="49" rx="3" class="c-mask"/>
+ <rect x="489" y="349" width="10" height="49" rx="3" class="c-database" stroke-width="1"/>
+ <rect x="597" y="438" width="10" height="58" rx="3" class="c-mask"/>
+ <rect x="597" y="438" width="10" height="58" rx="3" class="c-database" stroke-width="1"/>
+ <rect x="705" y="575" width="10" height="55" rx="3" class="c-mask"/>
+ <rect x="705" y="575" width="10" height="55" rx="3" class="c-messagebus" stroke-width="1"/>
+
+ <!-- Participants -->
+ <rect x="19" y="72" width="86" height="54" rx="6" class="c-mask"/>
+ <rect x="19" y="72" width="86" height="54" rx="6" class="c-external" stroke-width="1.5"/>
+ <text x="62" y="94" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">User</text>
+ <text x="62" y="111" class="t-muted" font-size="7" text-anchor="middle">browser session</text>
+
+ <rect x="127" y="72" width="86" height="54" rx="6" class="c-mask"/>
+ <rect x="127" y="72" width="86" height="54" rx="6" class="c-frontend" stroke-width="1.5"/>
+ <text x="170" y="94" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">Web App</text>
+ <text x="170" y="111" class="t-muted" font-size="7" text-anchor="middle">React UI</text>
+
+ <rect x="235" y="72" width="86" height="54" rx="6" class="c-mask"/>
+ <rect x="235" y="72" width="86" height="54" rx="6" class="c-backend" stroke-width="1.5"/>
+ <text x="278" y="94" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">API</text>
+ <text x="278" y="111" class="t-muted" font-size="7" text-anchor="middle">request handler</text>
+
+ <rect x="343" y="72" width="86" height="54" rx="6" class="c-mask"/>
+ <rect x="343" y="72" width="86" height="54" rx="6" class="c-security" stroke-width="1.5"/>
+ <text x="386" y="94" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">Auth</text>
+ <text x="386" y="111" class="t-muted" font-size="7" text-anchor="middle">JWT verify</text>
+
+ <rect x="451" y="72" width="86" height="54" rx="6" class="c-mask"/>
+ <rect x="451" y="72" width="86" height="54" rx="6" class="c-database" stroke-width="1.5"/>
+ <text x="494" y="94" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">Redis</text>
+ <text x="494" y="111" class="t-muted" font-size="7" text-anchor="middle">cache</text>
+
+ <rect x="559" y="72" width="86" height="54" rx="6" class="c-mask"/>
+ <rect x="559" y="72" width="86" height="54" rx="6" class="c-database" stroke-width="1.5"/>
+ <text x="602" y="94" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">Postgres</text>
+ <text x="602" y="111" class="t-muted" font-size="7" text-anchor="middle">source of truth</text>
+
+ <rect x="667" y="72" width="86" height="54" rx="6" class="c-mask"/>
+ <rect x="667" y="72" width="86" height="54" rx="6" class="c-messagebus" stroke-width="1.5"/>
+ <text x="710" y="94" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">Trace</text>
+ <text x="710" y="111" class="t-muted" font-size="7" text-anchor="middle">async event</text>
+
+ <!-- Legend -->
+ <text x="150" y="686" class="t-primary" font-size="10" font-weight="600">Legend</text>
+ <path d="M 150 706 L 184 706" class="a-emphasis" stroke-width="1.8" marker-end="url(#arrowhead-emphasis)"/>
+ <text x="193" y="709" class="t-muted" font-size="8">request</text>
+ <path d="M 270 706 L 304 706" class="a-default" stroke-width="1.4" stroke-dasharray="3,5" marker-end="url(#arrowhead)"/>
+ <text x="313" y="709" class="t-muted" font-size="8">return</text>
+ <path d="M 385 706 L 419 706" class="a-security" stroke-width="1.4" marker-end="url(#arrowhead-security)"/>
+ <text x="428" y="709" class="t-muted" font-size="8">security</text>
+ <path d="M 530 706 L 564 706" class="a-dashed" stroke-width="1.4" marker-end="url(#arrowhead-dashed)"/>
+ <text x="573" y="709" class="t-muted" font-size="8">async trace</text>
+ </svg>
+ </div>
+
+ <!-- Info Cards -->
+ <div class="cards">
+ <div class="card">
+ <div class="card-header">
+ <div class="card-dot emerald"></div>
+ <h3>Happy Path</h3>
+ </div>
+ <ul>
+ <li>&bull; The main request is Web App -&gt; API -&gt; data source -&gt; response</li>
+ <li>&bull; Return messages are quieter than forward calls</li>
+ <li>&bull; Activation bars make ownership duration visible</li>
+ </ul>
+ </div>
+
+ <div class="card">
+ <div class="card-header">
+ <div class="card-dot rose"></div>
+ <h3>Policy + Fallback</h3>
+ </div>
+ <ul>
+ <li>&bull; JWT verification is colored as a security interaction</li>
+ <li>&bull; Cache miss is visible without overpowering the main path</li>
+ <li>&bull; Database access only appears after cache fallback</li>
+ </ul>
+ </div>
+
+ <div class="card">
+ <div class="card-header">
+ <div class="card-dot orange"></div>
+ <h3>Async Trace</h3>
+ </div>
+ <ul>
+ <li>&bull; Trace emission is dashed and secondary</li>
+ <li>&bull; It does not block the response path</li>
+ <li>&bull; The diagram separates user-facing latency from observability</li>
+ </ul>
+ </div>
+ </div>
+
+ <!-- Footer -->
+ <p class="footer">
+ Sequence diagram &bull; Built with Archify &bull; 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>