diff --git a/CHANGELOG.md b/CHANGELOG.md
index 97f35e0..038add8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,15 @@
# Changelog
+## 0.6.0 — 2026-10-11
+
+- **3D view:** a **3D ▾** menu in the diagram toolbar, styled like Archify's own menus, switches any diagram to 3D. Nodes become raised blocks topped with the node as Archify draws it, relationships become lit pipes along Archify's routes, and the canvas, frames, lanes and legend form the floor. Works for all five diagram kinds, in every theme and style.
+- The menu also holds **Levels** (*Flat*, or *Stacked* by kind) and **Camera** (*Reset view*, *From above*).
+- **Animation follows 2D:** the 3D view mirrors Archify's own animations live: the trace when the diagram opens (replayed when 3D is chosen), node pulses, the hover trace, and the Semantic Passport, Path and Lens flows. *Live* off and reduced motion keep it still.
+- In 3D, clicking a block focuses it as in 2D (Semantic Passport, fading); hover shows the one-hop trace; trackpad scrolling pans, pinch and the mouse wheel zoom; the zoom buttons and +/-/0 move the camera; **Export → 3D view** saves a PNG.
+- **Performance:** the 3D view draws only when something moves (no GPU use while idle), uses lighter textures and pixel density, and the hidden 2D diagram is no longer painted. Hover and animations never rebuild textures.
+- New setting `archify.defaultView` (`2d` or `3d`). Each open diagram remembers its view, camera and levels.
+- The source code is reorganised by job (`commands/`, `views/`, `webview/`, `archify/`, `sources/`, `language/`, `util/`); no change in behaviour.
+
## 0.5.2 — 2026-10-10
- **Right-click menus:** the Archify commands (Archify | New Diagram…, Archify | Open Preview, Archify | Render to HTML File…, Archify | Open in HTML Viewer) now sit in their own section at the very bottom of the Explorer and editor-tab menus, instead of between New File, New Folder and the other built-in entries.
diff --git a/README.md b/README.md
index 6269714..373b507 100644
--- a/README.md
+++ b/README.md
@@ -70,6 +70,31 @@ The Archify CLI and the AI agents that use it write diagrams as JSON, named `nam
- **Export**: the diagram's own Export menu (PNG, SVG, share card, …) saves through a VS Code save dialog.
- **Commands**: *Archify | New Diagram…*, *Archify | Render to HTML File…*, *Archify | Open in Browser*, *Archify | Refresh Preview*, *Archify | Show Source*.
+## 3D view
+
+Every diagram can also be seen in 3D. Open the **3D ▾** menu next to **Export** in the diagram's toolbar and choose **3D**; choose **2D** to go back. The button wears a cyan ring while the 3D view is on.
+
+
+
+The 3D view is built from the diagram Archify draws, so it looks the same: each node becomes a raised block whose top is the node as Archify draws it, relationships become pipes along Archify's routes with their colours, dashes and arrowheads, and the canvas, frames, lanes and legend form the floor. It works for all five diagram kinds, in every theme and style (Classic, Signal Flow, Blueprint, Editorial).
+
+The menu has three groups:
+
+- **View**: 2D or 3D.
+- **Levels**: *Flat* keeps every node on the floor; *Stacked* lifts nodes into levels by kind: clients and external systems on top, security below them, services in the middle, data on the floor.
+- **Camera**: *Reset view* (or 0) flies back to the whole diagram, wherever you have moved to; *From above* looks straight down, like 2D.
+
+Moving around:
+
+- Drag to turn, right-drag to move. On a trackpad, scroll with two fingers to move in any direction and pinch to zoom; a mouse wheel zooms. The diagram's zoom buttons and the + and - keys work too, beyond the 2D limits.
+- Click a block to focus it, as in 2D: the Semantic Passport opens and unrelated parts fade. Hover a block to see its one-hop trace. Double-click a block to fly to it, or empty space to show everything.
+
+Animation follows 2D exactly, because the 3D view reads Archify's own animations as they play: the trace (relationships drawing in, nodes pulsing) when the diagram opens or 3D is chosen, the hover trace, and the flows from the Semantic Passport, Path and Lens. *Live* off, or reduced motion, keeps it still.
+
+**Export → 3D view** saves the current 3D view as a PNG. Each open diagram remembers whether it was in 3D, its camera and its levels; set `archify.defaultView` to `3d` to open diagrams in 3D.
+
+The 3D view draws only when something moves, so an idle diagram costs no GPU time.
+
## Source evidence
A diagram that declares `meta.repository` and `sources` is verified against a local Git checkout whose `origin` and pinned commit match. The extension uses the Git top-level directory of the diagram file, or `archify.repoRoot` when set.
@@ -81,6 +106,7 @@ When verification fails, the default (`archify.sourceEvidence: "fallback"`) stil
| Setting | Default | Description |
|---|---|---|
| `archify.theme` | `vscode` | `vscode` follows the color theme; `dark` or `light` force one; `diagram` keeps the diagram's own choice. |
+| `archify.defaultView` | `2d` | `3d` opens diagrams in the 3D view. Each open diagram remembers its own choice. |
| `archify.preview.liveUpdate` | `true` | Re-render while typing; when off, re-render on save. |
| `archify.preview.debounceMs` | `400` | Delay before re-rendering after an edit. |
| `archify.validation.enabled` | `true` | Report validation results in Problems. |
@@ -91,7 +117,7 @@ When verification fails, the default (`archify.sourceEvidence: "fallback"`) stil
## Security
-Diagrams run in a webview with a strict content security policy. Only the page's own inline scripts run (via a per-render nonce), there is no network access for scripts or fetches, and links open through VS Code.
+Diagrams run in a webview with a strict content security policy. Only the page's own inline scripts and the extension's bundled 3D viewer run (via a per-render nonce), there is no network access for scripts or fetches, and links open through VS Code.
## Development
@@ -105,6 +131,20 @@ npm run package # build archify-vscode-ext-.vsix
Press F5 to launch an Extension Development Host with the test fixtures.
+### Code layout
+
+| Folder | What it holds |
+|---|---|
+| `src/extension.ts` | Activation: creates the views and registers everything |
+| `src/commands/` | Command handlers, grouped by job, and the editor context keys |
+| `src/views/` | The diagram view (editor for `.archify`, side preview for JSON) and the HTML viewer |
+| `src/webview/` | The page the views show: CSP, the bridge script, messages from the page |
+| `src/archify/` | Running the bundled Archify CLI: render, validate, runtime settings |
+| `src/sources/` | Reading diagram files: type detection, YAML/JSON, source evidence |
+| `src/language/` | Editor help: Problems, brand completion, templates |
+| `src/util/` | Logging, settings, file reading |
+| `src/viewer3d/` | The 3D view; runs inside the Archify page and is bundled to `dist/viewer3d.js` with three.js |
+
### Updating the bundled renderer
`vendor/archify/` and `schemas/` are generated from an Archify checkout:
diff --git a/docs/preview-3d.png b/docs/preview-3d.png
new file mode 100644
index 0000000..57cc3ec
Binary files /dev/null and b/docs/preview-3d.png differ
diff --git a/esbuild.mjs b/esbuild.mjs
index 9ce0143..ba1b66e 100644
--- a/esbuild.mjs
+++ b/esbuild.mjs
@@ -33,16 +33,27 @@ if (tests) {
sourcemap: true,
});
} else {
- const ctx = await esbuild.context({
- ...common,
- entryPoints: ['src/extension.ts'],
- outfile: 'dist/extension.js',
- external: ['vscode'],
- });
+ const contexts = await Promise.all([
+ esbuild.context({
+ ...common,
+ entryPoints: ['src/extension.ts'],
+ outfile: 'dist/extension.js',
+ external: ['vscode'],
+ }),
+ // Runs inside the Archify page in the webview; three.js is bundled in.
+ esbuild.context({
+ ...common,
+ format: 'iife',
+ platform: 'browser',
+ target: 'es2022',
+ entryPoints: ['src/viewer3d/index.ts'],
+ outfile: 'dist/viewer3d.js',
+ }),
+ ]);
if (watch) {
- await ctx.watch();
+ await Promise.all(contexts.map((ctx) => ctx.watch()));
} else {
- await ctx.rebuild();
- await ctx.dispose();
+ await Promise.all(contexts.map((ctx) => ctx.rebuild()));
+ await Promise.all(contexts.map((ctx) => ctx.dispose()));
}
}
diff --git a/package-lock.json b/package-lock.json
index 347c168..8f87824 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,18 +1,20 @@
{
"name": "archify-vscode-ext",
- "version": "0.5.2",
+ "version": "0.6.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "archify-vscode-ext",
- "version": "0.5.2",
+ "version": "0.6.0",
"license": "MIT",
"dependencies": {
+ "three": "^0.186.1",
"yaml": "^2.9.1"
},
"devDependencies": {
"@types/node": "^22.0.0",
+ "@types/three": "^0.186.0",
"@types/vscode": "~1.100.0",
"@vscode/test-electron": "^3.1.0",
"@vscode/vsce": "^3.0.0",
@@ -246,6 +248,13 @@
"node": ">=6.9.0"
}
},
+ "node_modules/@dimforge/rapier3d-compat": {
+ "version": "0.12.0",
+ "resolved": "https://registry.npmjs.org/@dimforge/rapier3d-compat/-/rapier3d-compat-0.12.0.tgz",
+ "integrity": "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==",
+ "dev": true,
+ "license": "Apache-2.0"
+ },
"node_modules/@esbuild/aix-ppc64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",
@@ -999,6 +1008,13 @@
"@textlint/ast-node-types": "15.8.0"
}
},
+ "node_modules/@tweenjs/tween.js": {
+ "version": "23.1.3",
+ "resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-23.1.3.tgz",
+ "integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@types/node": {
"version": "22.20.4",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.4.tgz",
@@ -1023,6 +1039,28 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@types/stats.js": {
+ "version": "0.17.4",
+ "resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz",
+ "integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/three": {
+ "version": "0.186.0",
+ "resolved": "https://registry.npmjs.org/@types/three/-/three-0.186.0.tgz",
+ "integrity": "sha512-mxYSBpDC+D0pLfSP6sW4WZTcT+nrtmZcimMqnVmy36Hte3XpeYSrvgg4TRdaM1GemGog1AWzI5qL2VoIfMXbJQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@dimforge/rapier3d-compat": "~0.12.0",
+ "@tweenjs/tween.js": "~23.1.3",
+ "@types/stats.js": "*",
+ "@types/webxr": ">=0.5.17",
+ "fflate": "~0.8.3",
+ "meshoptimizer": "~1.1.1"
+ }
+ },
"node_modules/@types/vscode": {
"version": "1.100.0",
"resolved": "https://registry.npmjs.org/@types/vscode/-/vscode-1.100.0.tgz",
@@ -1030,6 +1068,13 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@types/webxr": {
+ "version": "0.5.24",
+ "resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz",
+ "integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@typespec/ts-http-runtime": {
"version": "0.3.9",
"resolved": "https://registry.npmjs.org/@typespec/ts-http-runtime/-/ts-http-runtime-0.3.9.tgz",
@@ -2162,6 +2207,13 @@
"reusify": "^1.0.4"
}
},
+ "node_modules/fflate": {
+ "version": "0.8.3",
+ "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
+ "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/fill-range": {
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
@@ -3097,6 +3149,13 @@
"node": ">= 8"
}
},
+ "node_modules/meshoptimizer": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.1.1.tgz",
+ "integrity": "sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/micromatch": {
"version": "4.0.8",
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
@@ -4423,6 +4482,12 @@
"url": "https://bevry.me/fund"
}
},
+ "node_modules/three": {
+ "version": "0.186.1",
+ "resolved": "https://registry.npmjs.org/three/-/three-0.186.1.tgz",
+ "integrity": "sha512-blFeqb49wRCSGUGj7gtpfnSGHy2lwDk94RhUmS1c/hTby70kvChbWpkJ4Pm1390LqzzvTmzgXKHPEafJwCb8jA==",
+ "license": "MIT"
+ },
"node_modules/tmp": {
"version": "0.2.7",
"resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.7.tgz",
diff --git a/package.json b/package.json
index 244fd96..7a1b28b 100644
--- a/package.json
+++ b/package.json
@@ -1,8 +1,8 @@
{
"name": "archify-vscode-ext",
"displayName": "Archify Diagram Viewer",
- "description": "Archify diagrams in VS Code. Write diagrams as .archify files in YAML: they open as the interactive diagram, with live updates, validation, templates and completion. Also previews Archify's own JSON files (*.architecture.json, \u2026) and opens rendered Archify HTML.",
- "version": "0.5.2",
+ "description": "Archify diagrams in VS Code. Write diagrams as .archify files in YAML: they open as the interactive diagram, with live updates, validation, templates and completion. Also previews Archify's own JSON files (*.architecture.json, …) and opens rendered Archify HTML.",
+ "version": "0.6.0",
"publisher": "root-at-skic",
"license": "MIT",
"icon": "media/icon.png",
@@ -41,7 +41,7 @@
"commands": [
{
"command": "archify.newDiagram",
- "title": "Archify | New Diagram\u2026",
+ "title": "Archify | New Diagram…",
"icon": "$(new-file)"
},
{
@@ -61,7 +61,7 @@
},
{
"command": "archify.renderToHtml",
- "title": "Archify | Render to HTML File\u2026",
+ "title": "Archify | Render to HTML File…",
"icon": "$(file-code)"
},
{
@@ -257,6 +257,19 @@
"default": "vscode",
"description": "Theme used when showing Archify diagrams."
},
+ "archify.defaultView": {
+ "type": "string",
+ "enum": [
+ "2d",
+ "3d"
+ ],
+ "enumDescriptions": [
+ "Open diagrams as Archify draws them.",
+ "Open diagrams in the 3D view. The 3D button in the diagram toolbar switches back."
+ ],
+ "default": "2d",
+ "description": "How diagrams open. Each open diagram remembers its own choice."
+ },
"archify.preview.liveUpdate": {
"type": "boolean",
"default": true,
@@ -340,6 +353,7 @@
},
"devDependencies": {
"@types/node": "^22.0.0",
+ "@types/three": "^0.186.0",
"@types/vscode": "~1.100.0",
"@vscode/test-electron": "^3.1.0",
"@vscode/vsce": "^3.0.0",
@@ -353,6 +367,7 @@
},
"homepage": "https://gitea.lego-cloud.eu/vscode-extensions/archify-vscode-ext#readme",
"dependencies": {
+ "three": "^0.186.1",
"yaml": "^2.9.1"
}
}
diff --git a/src/renderer.ts b/src/archify/cli.ts
similarity index 98%
rename from src/renderer.ts
rename to src/archify/cli.ts
index add4c06..808f3c0 100644
--- a/src/renderer.ts
+++ b/src/archify/cli.ts
@@ -1,7 +1,8 @@
import { spawn } from 'node:child_process';
import fs from 'node:fs/promises';
import path from 'node:path';
-import { DiagramSource, DiagramType, hasSourceEvidence, stripSourceEvidence } from './detect';
+import { DiagramSource, DiagramType } from '../sources/detect';
+import { hasSourceEvidence, stripSourceEvidence } from '../sources/evidence';
export interface RuntimeOptions {
/** Absolute path to vendor/archify/bin/archify.mjs. */
diff --git a/src/runtime.ts b/src/archify/runtime.ts
similarity index 66%
rename from src/runtime.ts
rename to src/archify/runtime.ts
index b5286ac..41841b8 100644
--- a/src/runtime.ts
+++ b/src/archify/runtime.ts
@@ -1,15 +1,8 @@
import { execFile } from 'node:child_process';
import path from 'node:path';
import * as vscode from 'vscode';
-import { RuntimeOptions } from './renderer';
-import { ViewerTheme } from './webviewHtml';
-
-let output: vscode.LogOutputChannel | undefined;
-
-export function log(): vscode.LogOutputChannel {
- output ??= vscode.window.createOutputChannel('Archify', { log: true });
- return output;
-}
+import { log } from '../util/log';
+import { RuntimeOptions } from './cli';
const gitRoots = new Map>();
@@ -60,18 +53,3 @@ export async function runtimeFor(context: vscode.ExtensionContext, uri: vscode.U
export function evidenceMode(uri: vscode.Uri | undefined): 'fallback' | 'strict' {
return vscode.workspace.getConfiguration('archify', uri).get<'fallback' | 'strict'>('sourceEvidence', 'fallback');
}
-
-export function viewerTheme(): ViewerTheme {
- const setting = vscode.workspace.getConfiguration('archify').get('theme', 'vscode');
- if (setting === 'dark' || setting === 'light') return setting;
- if (setting === 'diagram') return undefined;
- const kind = vscode.window.activeColorTheme.kind;
- return kind === vscode.ColorThemeKind.Light || kind === vscode.ColorThemeKind.HighContrastLight ? 'light' : 'dark';
-}
-
-/** Current text of a document: the open editor buffer, else the file on disk. */
-export async function readText(uri: vscode.Uri): Promise {
- const open = vscode.workspace.textDocuments.find((doc) => doc.uri.toString() === uri.toString());
- if (open) return open.getText();
- return new TextDecoder('utf-8').decode(await vscode.workspace.fs.readFile(uri));
-}
diff --git a/src/commands/context.ts b/src/commands/context.ts
new file mode 100644
index 0000000..5909150
--- /dev/null
+++ b/src/commands/context.ts
@@ -0,0 +1,38 @@
+import * as vscode from 'vscode';
+import { HTML_VIEW_TYPE, HtmlViewerProvider } from '../views/htmlViewer';
+import { DiagramViewManager } from '../views/diagramView';
+
+/** What command handlers share: the extension context and the open views. */
+export interface CommandContext {
+ extension: vscode.ExtensionContext;
+ views: DiagramViewManager;
+ htmlViewer: HtmlViewerProvider;
+}
+
+export function isHtmlUri(uri: vscode.Uri): boolean {
+ return /\.html?$/i.test(uri.path);
+}
+
+/** The file a command applies to: explicit argument, focused preview or viewer, then the text editor. */
+export function targetUri(ctx: CommandContext, arg?: unknown): vscode.Uri | undefined {
+ if (arg instanceof vscode.Uri) return arg;
+ return ctx.views.activePreview?.uri ?? ctx.htmlViewer.activeUri ?? vscode.window.activeTextEditor?.document.uri;
+}
+
+export function sourceUri(ctx: CommandContext, arg?: unknown): vscode.Uri | undefined {
+ const uri = targetUri(ctx, arg);
+ if (!uri) vscode.window.showWarningMessage('Archify: open a .archify diagram first.');
+ return uri;
+}
+
+export const openHtmlViewer = (uri: vscode.Uri, viewColumn?: vscode.ViewColumn) =>
+ vscode.commands.executeCommand('vscode.openWith', uri, HTML_VIEW_TYPE, viewColumn);
+
+export async function exists(uri: vscode.Uri): Promise {
+ try {
+ await vscode.workspace.fs.stat(uri);
+ return true;
+ } catch {
+ return false;
+ }
+}
diff --git a/src/commands/contextKeys.ts b/src/commands/contextKeys.ts
new file mode 100644
index 0000000..6aaf8b9
--- /dev/null
+++ b/src/commands/contextKeys.ts
@@ -0,0 +1,34 @@
+import * as vscode from 'vscode';
+import { clearGitRootCache } from '../archify/runtime';
+import { isArchifyFile, isArchifyHtml, isDiagramFileName, readDiagramSource } from '../sources/detect';
+
+const JSON_LANGUAGES = new Set(['json', 'jsonc']);
+
+/** Keeps the archify.* context keys (editor title buttons, keybindings) up to date. */
+export function registerContextKeys(context: vscode.ExtensionContext): void {
+ let contextTimer: NodeJS.Timeout | undefined;
+ const updateContext = () => {
+ const doc = vscode.window.activeTextEditor?.document;
+ const diagram = Boolean(
+ doc &&
+ (isArchifyFile(doc.fileName) ||
+ (JSON_LANGUAGES.has(doc.languageId) && (isDiagramFileName(doc.fileName) || readDiagramSource(doc.getText(), doc.fileName)))),
+ );
+ const html = Boolean(doc && doc.languageId === 'html' && isArchifyHtml(doc.getText()));
+ void vscode.commands.executeCommand('setContext', 'archify.isDiagramSource', diagram);
+ void vscode.commands.executeCommand('setContext', 'archify.isArchifyHtml', html);
+ };
+ context.subscriptions.push(
+ vscode.window.onDidChangeActiveTextEditor(updateContext),
+ vscode.workspace.onDidChangeTextDocument((event) => {
+ if (event.document !== vscode.window.activeTextEditor?.document) return;
+ clearTimeout(contextTimer);
+ contextTimer = setTimeout(updateContext, 300);
+ }),
+ vscode.workspace.onDidChangeConfiguration((event) => {
+ if (event.affectsConfiguration('archify.repoRoot')) clearGitRootCache();
+ }),
+ { dispose: () => clearTimeout(contextTimer) },
+ );
+ updateContext();
+}
diff --git a/src/commands/newDiagram.ts b/src/commands/newDiagram.ts
new file mode 100644
index 0000000..dd45852
--- /dev/null
+++ b/src/commands/newDiagram.ts
@@ -0,0 +1,59 @@
+import * as vscode from 'vscode';
+import { diagramFromTemplate, diagramName, invalidNameReason, TEMPLATES } from '../language/templates';
+import { diagramBaseName, isArchifyFile } from '../sources/detect';
+import { readText } from '../util/files';
+import { DIAGRAM_EDITOR_VIEW_TYPE } from '../views/diagramView';
+import { CommandContext, exists } from './context';
+
+/** Folder for a new diagram: the clicked folder (or a file's folder), else a workspace folder. */
+async function newDiagramFolder(arg?: unknown): Promise {
+ if (arg instanceof vscode.Uri) {
+ const stat = await vscode.workspace.fs.stat(arg);
+ return stat.type & vscode.FileType.Directory ? arg : vscode.Uri.joinPath(arg, '..');
+ }
+ const folders = vscode.workspace.workspaceFolders ?? [];
+ if (folders.length <= 1) return folders[0]?.uri;
+ return (await vscode.window.showWorkspaceFolderPick({ placeHolder: 'Folder for the new diagram' }))?.uri;
+}
+
+export function newDiagramCommands(ctx: CommandContext): vscode.Disposable[] {
+ return [
+ vscode.commands.registerCommand('archify.newDiagram', async (arg?: unknown) => {
+ const template = await vscode.window.showQuickPick(
+ TEMPLATES.map((item) => ({ label: item.label, description: item.description, template: item })),
+ { title: 'Archify | New Diagram', placeHolder: 'Kind of diagram' },
+ );
+ if (!template) return;
+ const { file, defaultName } = template.template;
+
+ const folder = await newDiagramFolder(arg);
+ let target: vscode.Uri | undefined;
+ if (folder) {
+ const name = await vscode.window.showInputBox({
+ title: 'Archify | New Diagram',
+ prompt: `File name in ${vscode.workspace.asRelativePath(folder, true)}`,
+ value: defaultName,
+ validateInput: async (value) =>
+ invalidNameReason(value) ??
+ ((await exists(vscode.Uri.joinPath(folder, `${diagramName(value)}.archify`))) ? `${diagramName(value)}.archify already exists.` : undefined),
+ });
+ if (name === undefined) return;
+ target = vscode.Uri.joinPath(folder, `${diagramName(name)}.archify`);
+ } else {
+ // No workspace: let the user choose where to save.
+ target = await vscode.window.showSaveDialog({
+ title: 'Archify | New Diagram',
+ filters: { 'Archify Diagram': ['archify'] },
+ saveLabel: 'Create',
+ });
+ if (!target) return;
+ if (!isArchifyFile(target.path)) target = target.with({ path: `${target.path}.archify` });
+ }
+
+ const templateText = await readText(vscode.Uri.joinPath(ctx.extension.extensionUri, 'templates', file));
+ const text = diagramFromTemplate(templateText, diagramBaseName(target.path));
+ await vscode.workspace.fs.writeFile(target, Buffer.from(text, 'utf8'));
+ await vscode.commands.executeCommand('vscode.openWith', target, DIAGRAM_EDITOR_VIEW_TYPE);
+ }),
+ ];
+}
diff --git a/src/commands/renderCommands.ts b/src/commands/renderCommands.ts
new file mode 100644
index 0000000..deb0f44
--- /dev/null
+++ b/src/commands/renderCommands.ts
@@ -0,0 +1,90 @@
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import * as vscode from 'vscode';
+import { isEvidenceError, renderDiagram, renderToFile } from '../archify/cli';
+import { evidenceMode, runtimeFor } from '../archify/runtime';
+import { diagramBaseName, readDiagramSource } from '../sources/detect';
+import { log } from '../util/log';
+import { readText } from '../util/files';
+import { CommandContext, isHtmlUri, openHtmlViewer, sourceUri } from './context';
+
+export function renderCommands(ctx: CommandContext): vscode.Disposable[] {
+ return [
+ vscode.commands.registerCommand('archify.renderToHtml', async (arg?: unknown) => {
+ const uri = sourceUri(ctx, arg);
+ if (!uri) return;
+ const text = await readText(uri);
+ const source = readDiagramSource(text, uri.path);
+ if (!source) {
+ vscode.window.showWarningMessage(`Archify: ${path.basename(uri.path)} has no "diagram_type" (architecture, workflow, sequence, dataflow or lifecycle).`);
+ return;
+ }
+ const meta = (source.diagram.meta ?? {}) as { output?: unknown };
+ const authored = typeof meta.output === 'string' && !/[\\/]/.test(meta.output) ? meta.output : undefined;
+ const fileName = authored ?? `${diagramBaseName(uri.path)}.html`;
+ const defaultUri = uri.scheme === 'file' ? vscode.Uri.joinPath(uri, '..', fileName) : undefined;
+ const target = await vscode.window.showSaveDialog({
+ defaultUri,
+ filters: { HTML: ['html'] },
+ saveLabel: 'Render',
+ });
+ if (!target) return;
+
+ const runtime = await runtimeFor(ctx.extension, uri);
+ let result = await vscode.window.withProgress(
+ { location: vscode.ProgressLocation.Notification, title: 'Archify: rendering…' },
+ () => renderToFile(runtime, source, target.fsPath),
+ );
+ if (!result.ok && isEvidenceError(result.error)) {
+ const choice = await vscode.window.showWarningMessage(
+ 'Archify could not verify the diagram\'s source evidence against a local checkout.',
+ { modal: true, detail: result.error },
+ 'Render Without Source Links',
+ );
+ if (choice) result = await renderToFile(runtime, source, target.fsPath, true);
+ else return;
+ }
+ if (!result.ok) {
+ log().error(result.error ?? 'render failed');
+ vscode.window.showErrorMessage('Archify: render failed.', { modal: true, detail: result.error });
+ return;
+ }
+ const choice = await vscode.window.showInformationMessage(
+ `Rendered ${path.basename(target.fsPath)}`,
+ 'Open in Viewer',
+ 'Open in Browser',
+ );
+ if (choice === 'Open in Viewer') await openHtmlViewer(target);
+ if (choice === 'Open in Browser') await vscode.env.openExternal(target);
+ }),
+
+ vscode.commands.registerCommand('archify.openInBrowser', async (arg?: unknown) => {
+ const uri = sourceUri(ctx, arg);
+ if (!uri) return;
+ if (isHtmlUri(uri)) {
+ await vscode.env.openExternal(uri);
+ return;
+ }
+ const text = await readText(uri);
+ const source = readDiagramSource(text, uri.path);
+ if (!source) {
+ vscode.window.showWarningMessage(`Archify: ${path.basename(uri.path)} has no "diagram_type" (architecture, workflow, sequence, dataflow or lifecycle).`);
+ return;
+ }
+ const runtime = await runtimeFor(ctx.extension, uri);
+ const result = await vscode.window.withProgress(
+ { location: vscode.ProgressLocation.Notification, title: 'Archify: rendering…' },
+ () => renderDiagram(runtime, source, evidenceMode(uri)),
+ );
+ if (!result.ok || !result.html) {
+ vscode.window.showErrorMessage('Archify: render failed.', { modal: true, detail: result.error });
+ return;
+ }
+ const dir = path.join(ctx.extension.globalStorageUri.fsPath, 'browser');
+ await fs.mkdir(dir, { recursive: true });
+ const file = path.join(dir, `${diagramBaseName(uri.path)}.html`);
+ await fs.writeFile(file, result.html, 'utf8');
+ await vscode.env.openExternal(vscode.Uri.file(file));
+ }),
+ ];
+}
diff --git a/src/commands/viewCommands.ts b/src/commands/viewCommands.ts
new file mode 100644
index 0000000..78af58e
--- /dev/null
+++ b/src/commands/viewCommands.ts
@@ -0,0 +1,52 @@
+import * as vscode from 'vscode';
+import { isArchifyFile } from '../sources/detect';
+import { DIAGRAM_EDITOR_VIEW_TYPE } from '../views/diagramView';
+import { CommandContext, isHtmlUri, openHtmlViewer, sourceUri } from './context';
+
+export function viewCommands(ctx: CommandContext): vscode.Disposable[] {
+ return [
+ vscode.commands.registerCommand('archify.showPreview', (arg?: unknown) => {
+ const uri = sourceUri(ctx, arg);
+ if (!uri) return;
+ if (isHtmlUri(uri)) return openHtmlViewer(uri);
+ if (isArchifyFile(uri.path)) return vscode.commands.executeCommand('vscode.openWith', uri, DIAGRAM_EDITOR_VIEW_TYPE);
+ ctx.views.show(uri, vscode.window.activeTextEditor?.viewColumn ?? vscode.ViewColumn.Active);
+ }),
+
+ vscode.commands.registerCommand('archify.showPreviewToSide', (arg?: unknown) => {
+ const uri = sourceUri(ctx, arg);
+ if (!uri) return;
+ if (isHtmlUri(uri)) return openHtmlViewer(uri, vscode.ViewColumn.Beside);
+ if (isArchifyFile(uri.path)) {
+ return vscode.commands.executeCommand('vscode.openWith', uri, DIAGRAM_EDITOR_VIEW_TYPE, {
+ viewColumn: vscode.ViewColumn.Beside,
+ preserveFocus: true,
+ });
+ }
+ ctx.views.show(uri, vscode.ViewColumn.Beside, true);
+ }),
+
+ vscode.commands.registerCommand('archify.openHtmlViewer', (arg?: unknown) => {
+ const uri = sourceUri(ctx, arg);
+ if (uri) return openHtmlViewer(uri);
+ }),
+
+ vscode.commands.registerCommand('archify.refreshPreview', () => ctx.views.activePreview?.update(true)),
+
+ vscode.commands.registerCommand('archify.showSource', async () => {
+ const preview = ctx.views.activePreview;
+ if (preview?.isEditor) {
+ // The diagram is the editor; open the YAML text beside it.
+ await vscode.commands.executeCommand('vscode.openWith', preview.uri, 'default', vscode.ViewColumn.Beside);
+ return;
+ }
+ if (preview) {
+ const column = preview.panel.viewColumn === vscode.ViewColumn.One ? vscode.ViewColumn.Two : vscode.ViewColumn.One;
+ await vscode.window.showTextDocument(preview.uri, { viewColumn: column });
+ return;
+ }
+ const html = ctx.htmlViewer.activeUri;
+ if (html) await vscode.commands.executeCommand('vscode.openWith', html, 'default');
+ }),
+ ];
+}
diff --git a/src/extension.ts b/src/extension.ts
index 55d8a0c..8d0d029 100644
--- a/src/extension.ts
+++ b/src/extension.ts
@@ -1,254 +1,32 @@
-import fs from 'node:fs/promises';
-import path from 'node:path';
import * as vscode from 'vscode';
-import { BRAND_COMPLETION_SELECTOR, BrandCompletionProvider } from './brandCompletion';
-import { diagramBaseName, isArchifyFile, isArchifyHtml, isDiagramFileName, readDiagramSource } from './detect';
-import { DiagnosticsController } from './diagnostics';
-import { HTML_VIEW_TYPE, HtmlViewerProvider } from './htmlViewer';
-import { DIAGRAM_EDITOR_VIEW_TYPE, PreviewManager } from './preview';
-import { isEvidenceError, renderDiagram, renderToFile } from './renderer';
-import { clearGitRootCache, evidenceMode, log, readText, runtimeFor } from './runtime';
-import { diagramFromTemplate, diagramName, invalidNameReason, TEMPLATES } from './templates';
-
-const JSON_LANGUAGES = new Set(['json', 'jsonc']);
-
-function isHtmlUri(uri: vscode.Uri): boolean {
- return /\.html?$/i.test(uri.path);
-}
+import { CommandContext } from './commands/context';
+import { registerContextKeys } from './commands/contextKeys';
+import { newDiagramCommands } from './commands/newDiagram';
+import { renderCommands } from './commands/renderCommands';
+import { viewCommands } from './commands/viewCommands';
+import { BRAND_COMPLETION_SELECTOR, BrandCompletionProvider } from './language/brandCompletion';
+import { DiagnosticsController } from './language/diagnostics';
+import { log } from './util/log';
+import { HtmlViewerProvider } from './views/htmlViewer';
+import { DiagramViewManager } from './views/diagramView';
export function activate(context: vscode.ExtensionContext): void {
- const previews = new PreviewManager(context);
- const htmlViewer = new HtmlViewerProvider();
+ const ctx: CommandContext = {
+ extension: context,
+ views: new DiagramViewManager(context),
+ htmlViewer: new HtmlViewerProvider(context.extensionUri),
+ };
context.subscriptions.push(
- previews,
- htmlViewer,
+ ctx.views,
+ ctx.htmlViewer,
new DiagnosticsController(context),
log(),
vscode.languages.registerCompletionItemProvider(BRAND_COMPLETION_SELECTOR, new BrandCompletionProvider(context.extensionPath), ' ', '"'),
+ ...viewCommands(ctx),
+ ...newDiagramCommands(ctx),
+ ...renderCommands(ctx),
);
-
- /** The file a command applies to: explicit argument, focused preview or viewer, then the text editor. */
- function targetUri(arg?: unknown): vscode.Uri | undefined {
- if (arg instanceof vscode.Uri) return arg;
- return previews.activePreview?.uri ?? htmlViewer.activeUri ?? vscode.window.activeTextEditor?.document.uri;
- }
-
- function sourceUri(arg?: unknown): vscode.Uri | undefined {
- const uri = targetUri(arg);
- if (!uri) vscode.window.showWarningMessage('Archify: open a .archify diagram first.');
- return uri;
- }
-
- // Context keys for editor title buttons and keybindings.
- let contextTimer: NodeJS.Timeout | undefined;
- const updateContext = () => {
- const doc = vscode.window.activeTextEditor?.document;
- const diagram = Boolean(
- doc &&
- (isArchifyFile(doc.fileName) ||
- (JSON_LANGUAGES.has(doc.languageId) && (isDiagramFileName(doc.fileName) || readDiagramSource(doc.getText(), doc.fileName)))),
- );
- const html = Boolean(doc && doc.languageId === 'html' && isArchifyHtml(doc.getText()));
- void vscode.commands.executeCommand('setContext', 'archify.isDiagramSource', diagram);
- void vscode.commands.executeCommand('setContext', 'archify.isArchifyHtml', html);
- };
- context.subscriptions.push(
- vscode.window.onDidChangeActiveTextEditor(updateContext),
- vscode.workspace.onDidChangeTextDocument((event) => {
- if (event.document !== vscode.window.activeTextEditor?.document) return;
- clearTimeout(contextTimer);
- contextTimer = setTimeout(updateContext, 300);
- }),
- vscode.workspace.onDidChangeConfiguration((event) => {
- if (event.affectsConfiguration('archify.repoRoot')) clearGitRootCache();
- }),
- { dispose: () => clearTimeout(contextTimer) },
- );
- updateContext();
-
- const openHtmlViewer = (uri: vscode.Uri, viewColumn?: vscode.ViewColumn) =>
- vscode.commands.executeCommand('vscode.openWith', uri, HTML_VIEW_TYPE, viewColumn);
-
- const exists = async (uri: vscode.Uri) => {
- try {
- await vscode.workspace.fs.stat(uri);
- return true;
- } catch {
- return false;
- }
- };
-
- /** Folder for a new diagram: the clicked folder (or a file's folder), else a workspace folder. */
- async function newDiagramFolder(arg?: unknown): Promise {
- if (arg instanceof vscode.Uri) {
- const stat = await vscode.workspace.fs.stat(arg);
- return stat.type & vscode.FileType.Directory ? arg : vscode.Uri.joinPath(arg, '..');
- }
- const folders = vscode.workspace.workspaceFolders ?? [];
- if (folders.length <= 1) return folders[0]?.uri;
- return (await vscode.window.showWorkspaceFolderPick({ placeHolder: 'Folder for the new diagram' }))?.uri;
- }
-
- context.subscriptions.push(
- vscode.commands.registerCommand('archify.showPreview', (arg?: unknown) => {
- const uri = sourceUri(arg);
- if (!uri) return;
- if (isHtmlUri(uri)) return openHtmlViewer(uri);
- if (isArchifyFile(uri.path)) return vscode.commands.executeCommand('vscode.openWith', uri, DIAGRAM_EDITOR_VIEW_TYPE);
- previews.show(uri, vscode.window.activeTextEditor?.viewColumn ?? vscode.ViewColumn.Active);
- }),
-
- vscode.commands.registerCommand('archify.showPreviewToSide', (arg?: unknown) => {
- const uri = sourceUri(arg);
- if (!uri) return;
- if (isHtmlUri(uri)) return openHtmlViewer(uri, vscode.ViewColumn.Beside);
- if (isArchifyFile(uri.path)) {
- return vscode.commands.executeCommand('vscode.openWith', uri, DIAGRAM_EDITOR_VIEW_TYPE, {
- viewColumn: vscode.ViewColumn.Beside,
- preserveFocus: true,
- });
- }
- previews.show(uri, vscode.ViewColumn.Beside, true);
- }),
-
- vscode.commands.registerCommand('archify.openHtmlViewer', (arg?: unknown) => {
- const uri = sourceUri(arg);
- if (uri) return openHtmlViewer(uri);
- }),
-
- vscode.commands.registerCommand('archify.newDiagram', async (arg?: unknown) => {
- const template = await vscode.window.showQuickPick(
- TEMPLATES.map((item) => ({ label: item.label, description: item.description, template: item })),
- { title: 'Archify | New Diagram', placeHolder: 'Kind of diagram' },
- );
- if (!template) return;
- const { file, defaultName } = template.template;
-
- const folder = await newDiagramFolder(arg);
- let target: vscode.Uri | undefined;
- if (folder) {
- const name = await vscode.window.showInputBox({
- title: 'Archify | New Diagram',
- prompt: `File name in ${vscode.workspace.asRelativePath(folder, true)}`,
- value: defaultName,
- validateInput: async (value) =>
- invalidNameReason(value) ??
- ((await exists(vscode.Uri.joinPath(folder, `${diagramName(value)}.archify`))) ? `${diagramName(value)}.archify already exists.` : undefined),
- });
- if (name === undefined) return;
- target = vscode.Uri.joinPath(folder, `${diagramName(name)}.archify`);
- } else {
- // No workspace: let the user choose where to save.
- target = await vscode.window.showSaveDialog({
- title: 'Archify | New Diagram',
- filters: { 'Archify Diagram': ['archify'] },
- saveLabel: 'Create',
- });
- if (!target) return;
- if (!isArchifyFile(target.path)) target = target.with({ path: `${target.path}.archify` });
- }
-
- const templateText = await readText(vscode.Uri.joinPath(context.extensionUri, 'templates', file));
- const text = diagramFromTemplate(templateText, diagramBaseName(target.path));
- await vscode.workspace.fs.writeFile(target, Buffer.from(text, 'utf8'));
- await vscode.commands.executeCommand('vscode.openWith', target, DIAGRAM_EDITOR_VIEW_TYPE);
- }),
-
- vscode.commands.registerCommand('archify.refreshPreview', () => previews.activePreview?.update(true)),
-
- vscode.commands.registerCommand('archify.showSource', async () => {
- const preview = previews.activePreview;
- if (preview?.isEditor) {
- // The diagram is the editor; open the YAML text beside it.
- await vscode.commands.executeCommand('vscode.openWith', preview.uri, 'default', vscode.ViewColumn.Beside);
- return;
- }
- if (preview) {
- const column = preview.panel.viewColumn === vscode.ViewColumn.One ? vscode.ViewColumn.Two : vscode.ViewColumn.One;
- await vscode.window.showTextDocument(preview.uri, { viewColumn: column });
- return;
- }
- const html = htmlViewer.activeUri;
- if (html) await vscode.commands.executeCommand('vscode.openWith', html, 'default');
- }),
-
- vscode.commands.registerCommand('archify.renderToHtml', async (arg?: unknown) => {
- const uri = sourceUri(arg);
- if (!uri) return;
- const text = await readText(uri);
- const source = readDiagramSource(text, uri.path);
- if (!source) {
- vscode.window.showWarningMessage(`Archify: ${path.basename(uri.path)} has no "diagram_type" (architecture, workflow, sequence, dataflow or lifecycle).`);
- return;
- }
- const meta = (source.diagram.meta ?? {}) as { output?: unknown };
- const authored = typeof meta.output === 'string' && !/[\\/]/.test(meta.output) ? meta.output : undefined;
- const fileName = authored ?? `${diagramBaseName(uri.path)}.html`;
- const defaultUri = uri.scheme === 'file' ? vscode.Uri.joinPath(uri, '..', fileName) : undefined;
- const target = await vscode.window.showSaveDialog({
- defaultUri,
- filters: { HTML: ['html'] },
- saveLabel: 'Render',
- });
- if (!target) return;
-
- const runtime = await runtimeFor(context, uri);
- let result = await vscode.window.withProgress(
- { location: vscode.ProgressLocation.Notification, title: 'Archify: rendering…' },
- () => renderToFile(runtime, source, target.fsPath),
- );
- if (!result.ok && isEvidenceError(result.error)) {
- const choice = await vscode.window.showWarningMessage(
- 'Archify could not verify the diagram\'s source evidence against a local checkout.',
- { modal: true, detail: result.error },
- 'Render Without Source Links',
- );
- if (choice) result = await renderToFile(runtime, source, target.fsPath, true);
- else return;
- }
- if (!result.ok) {
- log().error(result.error ?? 'render failed');
- vscode.window.showErrorMessage('Archify: render failed.', { modal: true, detail: result.error });
- return;
- }
- const choice = await vscode.window.showInformationMessage(
- `Rendered ${path.basename(target.fsPath)}`,
- 'Open in Viewer',
- 'Open in Browser',
- );
- if (choice === 'Open in Viewer') await openHtmlViewer(target);
- if (choice === 'Open in Browser') await vscode.env.openExternal(target);
- }),
-
- vscode.commands.registerCommand('archify.openInBrowser', async (arg?: unknown) => {
- const uri = sourceUri(arg);
- if (!uri) return;
- if (isHtmlUri(uri)) {
- await vscode.env.openExternal(uri);
- return;
- }
- const text = await readText(uri);
- const source = readDiagramSource(text, uri.path);
- if (!source) {
- vscode.window.showWarningMessage(`Archify: ${path.basename(uri.path)} has no "diagram_type" (architecture, workflow, sequence, dataflow or lifecycle).`);
- return;
- }
- const runtime = await runtimeFor(context, uri);
- const result = await vscode.window.withProgress(
- { location: vscode.ProgressLocation.Notification, title: 'Archify: rendering…' },
- () => renderDiagram(runtime, source, evidenceMode(uri)),
- );
- if (!result.ok || !result.html) {
- vscode.window.showErrorMessage('Archify: render failed.', { modal: true, detail: result.error });
- return;
- }
- const dir = path.join(context.globalStorageUri.fsPath, 'browser');
- await fs.mkdir(dir, { recursive: true });
- const file = path.join(dir, `${diagramBaseName(uri.path)}.html`);
- await fs.writeFile(file, result.html, 'utf8');
- await vscode.env.openExternal(vscode.Uri.file(file));
- }),
- );
+ registerContextKeys(context);
}
export function deactivate(): void {}
diff --git a/src/brandCompletion.ts b/src/language/brandCompletion.ts
similarity index 95%
rename from src/brandCompletion.ts
rename to src/language/brandCompletion.ts
index 7d59bda..98c30c8 100644
--- a/src/brandCompletion.ts
+++ b/src/language/brandCompletion.ts
@@ -1,8 +1,8 @@
import path from 'node:path';
import * as vscode from 'vscode';
+import { isArchifyFile } from '../sources/detect';
+import { log } from '../util/log';
import { Brand, brandValueAt, loadBrandCatalog } from './brands';
-import { isArchifyFile } from './detect';
-import { log } from './runtime';
const JSON_SOURCES = '**/*.{architecture,workflow,sequence,dataflow,lifecycle}.json';
diff --git a/src/brands.ts b/src/language/brands.ts
similarity index 100%
rename from src/brands.ts
rename to src/language/brands.ts
diff --git a/src/diagnostics.ts b/src/language/diagnostics.ts
similarity index 95%
rename from src/diagnostics.ts
rename to src/language/diagnostics.ts
index 5097945..5376286 100644
--- a/src/diagnostics.ts
+++ b/src/language/diagnostics.ts
@@ -1,9 +1,10 @@
import { parse, ParseError } from 'jsonc-parser';
import * as vscode from 'vscode';
-import { isArchifyFile, readDiagramSource } from './detect';
+import { ArchifyDiagnostic, isEvidenceError, validate } from '../archify/cli';
+import { evidenceMode, runtimeFor } from '../archify/runtime';
+import { isArchifyFile, readDiagramSource } from '../sources/detect';
+import { log } from '../util/log';
import { diagnosticPointer, rangeForPointer, rangeForPointerYaml, yamlSyntaxProblems } from './jsonPointer';
-import { ArchifyDiagnostic, isEvidenceError, validate } from './renderer';
-import { evidenceMode, log, runtimeFor } from './runtime';
const JSON_LANGUAGES = new Set(['json', 'jsonc']);
diff --git a/src/jsonPointer.ts b/src/language/jsonPointer.ts
similarity index 100%
rename from src/jsonPointer.ts
rename to src/language/jsonPointer.ts
diff --git a/src/templates.ts b/src/language/templates.ts
similarity index 98%
rename from src/templates.ts
rename to src/language/templates.ts
index 79c2517..761141e 100644
--- a/src/templates.ts
+++ b/src/language/templates.ts
@@ -1,5 +1,5 @@
import { isMap, parseDocument } from 'yaml';
-import { DiagramType } from './detect';
+import { DiagramType } from '../sources/detect';
export interface DiagramTemplate {
/** File name under templates/. */
diff --git a/src/detect.ts b/src/sources/detect.ts
similarity index 74%
rename from src/detect.ts
rename to src/sources/detect.ts
index 85ccfa9..c7bc343 100644
--- a/src/detect.ts
+++ b/src/sources/detect.ts
@@ -4,15 +4,6 @@ import { parse as parseYaml } from 'yaml';
export const DIAGRAM_TYPES = ['architecture', 'workflow', 'sequence', 'dataflow', 'lifecycle'] as const;
export type DiagramType = (typeof DIAGRAM_TYPES)[number];
-/** Node collection that may carry `sources` evidence, per diagram type. */
-export const EVIDENCE_COLLECTIONS: Record = {
- architecture: 'components',
- workflow: 'nodes',
- sequence: 'participants',
- dataflow: 'nodes',
- lifecycle: 'states',
-};
-
const FILENAME_RE = /\.(architecture|workflow|sequence|dataflow|lifecycle)\.json$/i;
const ARCHIFY_EXT_RE = /\.archify$/i;
const MAX_SNIFF_BYTES = 8 * 1024 * 1024;
@@ -92,24 +83,3 @@ export function isArchifyHtml(text: string): boolean {
const head = text.slice(0, 4096);
return /): boolean {
- const meta = diagram.meta as Record | undefined;
- if (meta && meta.repository) return true;
- const nodes = diagram[EVIDENCE_COLLECTIONS[type]];
- return Array.isArray(nodes) && nodes.some((node) => Array.isArray(node?.sources) && node.sources.length > 0);
-}
-
-/** Returns a copy of the diagram with repository evidence removed. */
-export function stripSourceEvidence(type: DiagramType, diagram: Record): Record {
- const copy = structuredClone(diagram);
- const meta = copy.meta as Record | undefined;
- if (meta) delete meta.repository;
- const nodes = copy[EVIDENCE_COLLECTIONS[type]];
- if (Array.isArray(nodes)) {
- for (const node of nodes) {
- if (node && typeof node === 'object') delete node.sources;
- }
- }
- return copy;
-}
diff --git a/src/sources/evidence.ts b/src/sources/evidence.ts
new file mode 100644
index 0000000..69126b0
--- /dev/null
+++ b/src/sources/evidence.ts
@@ -0,0 +1,31 @@
+import { DiagramType } from './detect';
+
+/** Node collection that may carry `sources` evidence, per diagram type. */
+export const EVIDENCE_COLLECTIONS: Record = {
+ architecture: 'components',
+ workflow: 'nodes',
+ sequence: 'participants',
+ dataflow: 'nodes',
+ lifecycle: 'states',
+};
+
+export function hasSourceEvidence(type: DiagramType, diagram: Record): boolean {
+ const meta = diagram.meta as Record | undefined;
+ if (meta && meta.repository) return true;
+ const nodes = diagram[EVIDENCE_COLLECTIONS[type]];
+ return Array.isArray(nodes) && nodes.some((node) => Array.isArray(node?.sources) && node.sources.length > 0);
+}
+
+/** Returns a copy of the diagram with repository evidence removed. */
+export function stripSourceEvidence(type: DiagramType, diagram: Record): Record {
+ const copy = structuredClone(diagram);
+ const meta = copy.meta as Record | undefined;
+ if (meta) delete meta.repository;
+ const nodes = copy[EVIDENCE_COLLECTIONS[type]];
+ if (Array.isArray(nodes)) {
+ for (const node of nodes) {
+ if (node && typeof node === 'object') delete node.sources;
+ }
+ }
+ return copy;
+}
diff --git a/src/util/files.ts b/src/util/files.ts
new file mode 100644
index 0000000..b5cc00c
--- /dev/null
+++ b/src/util/files.ts
@@ -0,0 +1,8 @@
+import * as vscode from 'vscode';
+
+/** Current text of a document: the open editor buffer, else the file on disk. */
+export async function readText(uri: vscode.Uri): Promise {
+ const open = vscode.workspace.textDocuments.find((doc) => doc.uri.toString() === uri.toString());
+ if (open) return open.getText();
+ return new TextDecoder('utf-8').decode(await vscode.workspace.fs.readFile(uri));
+}
diff --git a/src/util/log.ts b/src/util/log.ts
new file mode 100644
index 0000000..356def6
--- /dev/null
+++ b/src/util/log.ts
@@ -0,0 +1,8 @@
+import * as vscode from 'vscode';
+
+let output: vscode.LogOutputChannel | undefined;
+
+export function log(): vscode.LogOutputChannel {
+ output ??= vscode.window.createOutputChannel('Archify', { log: true });
+ return output;
+}
diff --git a/src/util/settings.ts b/src/util/settings.ts
new file mode 100644
index 0000000..c178dff
--- /dev/null
+++ b/src/util/settings.ts
@@ -0,0 +1,11 @@
+import * as vscode from 'vscode';
+import { ViewerTheme } from '../webview/page';
+
+/** Diagram theme from archify.theme: forced, VS Code's, or the diagram's own. */
+export function viewerTheme(): ViewerTheme {
+ const setting = vscode.workspace.getConfiguration('archify').get('theme', 'vscode');
+ if (setting === 'dark' || setting === 'light') return setting;
+ if (setting === 'diagram') return undefined;
+ const kind = vscode.window.activeColorTheme.kind;
+ return kind === vscode.ColorThemeKind.Light || kind === vscode.ColorThemeKind.HighContrastLight ? 'light' : 'dark';
+}
diff --git a/src/viewer3d/index.ts b/src/viewer3d/index.ts
new file mode 100644
index 0000000..19638a5
--- /dev/null
+++ b/src/viewer3d/index.ts
@@ -0,0 +1,558 @@
+import { layerMarkup, rasterize } from './raster';
+import { CameraState, Layers, Stage } from './stage';
+import { DiagramModel, readModel } from './svgModel';
+import { STYLE } from './style';
+
+/**
+ * 3D mode for the Archify viewer. It adds a 3D menu to Archify's toolbar
+ * and, when on, replaces the 2D canvas with a three.js stage built from the
+ * live SVG. Archify keeps owning the diagram: clicks in 3D go to the SVG
+ * nodes, so focus, Semantic Passport, reach and lens work as in 2D; the
+ * stage redraws whenever Archify changes the SVG, theme or preset, and
+ * follows Archify's animations as they play.
+ */
+
+interface Host {
+ defaultView: '2d' | '3d';
+ post(message: unknown): void;
+ getState(): Record;
+ setState(patch: Record): void;
+}
+
+interface SavedView {
+ active?: boolean;
+ layered?: boolean;
+ camera?: CameraState;
+}
+
+declare global {
+ interface Window {
+ __archifyHost?: Host;
+ }
+}
+
+const REDRAW_MS = 220;
+const MARGIN = 80;
+/** Texture pixels per SVG unit; more costs memory and upload time for little gain. */
+const TEXTURE_SCALE = 2;
+
+type MenuValue = '2d' | '3d' | 'flat' | 'stacked' | 'reset' | 'top';
+
+interface MenuEntry {
+ value: MenuValue;
+ title: string;
+ hint: string;
+ /** Radio group; actions have none. */
+ group?: 'view' | 'levels';
+ shortcut?: string;
+}
+
+const MENU: { heading: string; entries: MenuEntry[] }[] = [
+ {
+ heading: 'View',
+ entries: [
+ { value: '2d', group: 'view', title: '2D', hint: 'The diagram as Archify draws it' },
+ { value: '3d', group: 'view', title: '3D', hint: 'Blocks and pipes you can turn' },
+ ],
+ },
+ {
+ heading: 'Levels',
+ entries: [
+ { value: 'flat', group: 'levels', title: 'Flat', hint: 'Every node on the floor' },
+ { value: 'stacked', group: 'levels', title: 'Stacked', hint: 'Clients on top, data at the bottom' },
+ ],
+ },
+ {
+ heading: 'Camera',
+ entries: [
+ { value: 'reset', title: 'Reset view', hint: 'Show the whole diagram', shortcut: '0' },
+ { value: 'top', title: 'From above', hint: 'Look straight down, like 2D' },
+ ],
+ },
+];
+
+
+class Viewer3D {
+ private stage: Stage | undefined;
+ private model: DiagramModel | undefined;
+ private active = false;
+ private redrawTimer: number | undefined;
+ private drawing: Promise | undefined;
+ private pendingRedraw = false;
+ private readonly observer = new MutationObserver((records) => this.onMutation(records));
+ /** Keeps Archify's zoom buttons usable in 3D (see holdZoomButtons). */
+ private readonly zoomObserver = new MutationObserver(() => this.enableZoomButtons());
+ private zoomDisabled = new Map();
+ private readonly button: HTMLButtonElement;
+ private readonly menu: HTMLDivElement;
+ private ambientReplayed = false;
+ private exportItem: HTMLButtonElement | undefined;
+ private saved: SavedView;
+
+ constructor(
+ private readonly host: Host,
+ private readonly container: HTMLElement,
+ private readonly svg: SVGSVGElement,
+ ) {
+ this.saved = (host.getState().view3d as SavedView | undefined) ?? {};
+ ({ button: this.button, menu: this.menu } = this.buildMenu());
+ this.addExportItem();
+ this.interceptViewerControls();
+ if (this.saved.active ?? host.defaultView === '3d') this.setActive(true);
+ }
+
+ // -------------------------------------------------------------- chrome
+
+ /**
+ * The 3D menu: a toolbar button with a dropdown, built from Archify's own
+ * style-menu classes so it looks and behaves like the menus beside it.
+ */
+ private buildMenu(): { button: HTMLButtonElement; menu: HTMLDivElement } {
+ const wrap = document.createElement('div');
+ wrap.className = 'preset-wrap archify-3d-wrap';
+ const button = document.createElement('button');
+ button.id = 'btn-3d';
+ button.type = 'button';
+ button.title = '3D view: switch 2D / 3D, levels and camera';
+ button.setAttribute('aria-label', '3D view options');
+ button.setAttribute('aria-haspopup', 'menu');
+ button.setAttribute('aria-expanded', 'false');
+ button.setAttribute('aria-controls', 'archify-3d-menu');
+ // Same make-up as Archify's Export button: a label and a chevron.
+ button.innerHTML = '3D ';
+
+ const menu = document.createElement('div');
+ menu.id = 'archify-3d-menu';
+ menu.className = 'preset-menu archify-3d-menu';
+ menu.setAttribute('role', 'menu');
+ menu.setAttribute('aria-label', 'View options');
+ for (const section of MENU) {
+ const heading = document.createElement('div');
+ heading.className = 'preset-menu-heading';
+ heading.setAttribute('role', 'presentation');
+ heading.innerHTML = `${section.heading}`;
+ menu.appendChild(heading);
+ for (const entry of section.entries) {
+ const option = document.createElement('button');
+ option.type = 'button';
+ option.className = 'preset-option archify-3d-option';
+ option.tabIndex = -1;
+ option.dataset.archify3d = entry.value;
+ option.setAttribute('role', entry.group ? 'menuitemradio' : 'menuitem');
+ if (entry.group) option.setAttribute('aria-checked', 'false');
+ option.innerHTML =
+ `` +
+ `${entry.title}${entry.hint}` +
+ (entry.group
+ ? ''
+ : `${entry.shortcut ?? ''}`);
+ option.addEventListener('click', (event) => {
+ event.stopPropagation();
+ if (option.getAttribute('aria-disabled') === 'true') return;
+ this.choose(entry.value);
+ if (!entry.group) this.closeMenu();
+ else this.syncButtons();
+ });
+ menu.appendChild(option);
+ }
+ }
+
+ button.addEventListener('click', (event) => {
+ event.stopPropagation();
+ if (menu.classList.contains('open')) this.closeMenu();
+ else this.openMenu();
+ });
+ menu.addEventListener('keydown', (event) => this.menuKey(event));
+ document.addEventListener('click', (event) => {
+ if (menu.classList.contains('open') && !wrap.contains(event.target as Node)) this.closeMenu();
+ });
+ document.addEventListener('keydown', (event) => {
+ if (event.key === 'Escape' && menu.classList.contains('open')) {
+ this.closeMenu();
+ button.focus();
+ }
+ });
+
+ wrap.append(button, menu);
+ // Beside Export, outside the tools capsule, as its twin.
+ const exportWrap = document.querySelector('.toolbar .export-wrap');
+ if (exportWrap?.parentElement) exportWrap.parentElement.insertBefore(wrap, exportWrap);
+ else document.querySelector('.toolbar')?.appendChild(wrap);
+ return { button, menu };
+ }
+
+ private options(): HTMLButtonElement[] {
+ return [...this.menu.querySelectorAll('.archify-3d-option')].filter((o) => o.getAttribute('aria-disabled') !== 'true');
+ }
+
+ private openMenu(): void {
+ // Only one toolbar menu at a time: close Archify's own.
+ document.querySelectorAll('.toolbar .preset-menu.open, .toolbar .export-menu.open').forEach((m) => {
+ if (m !== this.menu) (m.previousElementSibling as HTMLElement | null)?.click();
+ });
+ this.syncButtons();
+ this.menu.classList.add('open');
+ this.button.setAttribute('aria-expanded', 'true');
+ const checked = this.options().find((o) => o.getAttribute('aria-checked') === 'true');
+ (checked ?? this.options()[0])?.focus();
+ }
+
+ private closeMenu(): void {
+ this.menu.classList.remove('open');
+ this.button.setAttribute('aria-expanded', 'false');
+ }
+
+ private menuKey(event: KeyboardEvent): void {
+ const options = this.options();
+ const index = options.indexOf(document.activeElement as HTMLButtonElement);
+ const move = (to: number) => {
+ event.preventDefault();
+ options[(to + options.length) % options.length]?.focus();
+ };
+ if (event.key === 'ArrowDown') move(index + 1);
+ else if (event.key === 'ArrowUp') move(index - 1);
+ else if (event.key === 'Home') move(0);
+ else if (event.key === 'End') move(options.length - 1);
+ else if (event.key === 'Tab') this.closeMenu();
+ }
+
+ private choose(value: MenuValue): void {
+ switch (value) {
+ case '2d':
+ case '3d':
+ if ((value === '3d') !== this.active) this.setActive(value === '3d');
+ return;
+ case 'flat':
+ case 'stacked':
+ this.stage?.setLayered(value === 'stacked');
+ this.save();
+ return;
+ case 'reset':
+ this.stage?.fit();
+ return;
+ case 'top':
+ this.stage?.top();
+ return;
+ }
+ }
+
+ private addExportItem(): void {
+ const png = document.querySelector('.export-menu button[data-format="png"]');
+ if (!png?.parentElement) return;
+ const item = document.createElement('button');
+ item.type = 'button';
+ item.setAttribute('role', 'menuitem');
+ item.tabIndex = -1;
+ item.hidden = true;
+ item.dataset.archify3dExport = '';
+ item.innerHTML = '3D viewPNG of the current 3D view';
+ item.addEventListener('click', (event) => {
+ event.stopPropagation();
+ document.getElementById('btn-export')?.click();
+ this.exportPng();
+ });
+ png.parentElement.insertBefore(item, png);
+ this.exportItem = item;
+ }
+
+ /** Archify's zoom buttons and keys drive the 3D camera while 3D is on. */
+ private interceptViewerControls(): void {
+ this.container.addEventListener(
+ 'click',
+ (event) => {
+ if (!this.active || !this.stage) return;
+ const button = (event.target as Element | null)?.closest?.('[data-view]');
+ const view = button?.getAttribute('data-view');
+ if (!view) return;
+ event.stopPropagation();
+ event.preventDefault();
+ if (view === 'in') this.stage.zoom(1.25);
+ else if (view === 'out') this.stage.zoom(0.8);
+ else if (view === 'reset') this.stage.fit();
+ },
+ true,
+ );
+ window.addEventListener(
+ 'keydown',
+ (event) => {
+ if (!this.active || !this.stage || event.metaKey || event.ctrlKey || event.altKey) return;
+ const target = event.target as HTMLElement | null;
+ if (target && (target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName))) return;
+ const actions: Record void> = {
+ '0': () => this.stage!.fit(),
+ '+': () => this.stage!.zoom(1.25),
+ '=': () => this.stage!.zoom(1.25),
+ '-': () => this.stage!.zoom(0.8),
+ };
+ const action = actions[event.key];
+ if (!action) return;
+ event.stopPropagation();
+ event.preventDefault();
+ action();
+ },
+ true,
+ );
+ }
+
+ private syncButtons(): void {
+ const layered = !!this.stage?.layered;
+ this.button.toggleAttribute('data-active', this.active);
+ for (const option of this.menu.querySelectorAll('.archify-3d-option')) {
+ const value = option.dataset.archify3d as MenuValue;
+ if (value === '2d' || value === '3d') option.setAttribute('aria-checked', String((value === '3d') === this.active));
+ if (value === 'flat' || value === 'stacked') option.setAttribute('aria-checked', String((value === 'stacked') === layered));
+ // Levels and camera only apply to the 3D view.
+ if (value !== '2d' && value !== '3d') option.setAttribute('aria-disabled', String(!this.active));
+ }
+ if (this.exportItem) this.exportItem.hidden = !this.active;
+ }
+
+ // ---------------------------------------------------------------- mode
+
+ setActive(on: boolean): void {
+ this.active = on;
+ document.documentElement.classList.toggle('archify-3d-on', on);
+ if (on) {
+ if (!this.stage) this.createStage();
+ this.container.appendChild(this.stage!.element);
+ this.stage!.start();
+ this.observer.observe(this.svg, { subtree: true, attributes: true, childList: true, characterData: true });
+ this.observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme', 'data-preset'] });
+ this.holdZoomButtons(true);
+ void this.redraw().then(() => this.replayAmbient());
+ } else {
+ this.holdZoomButtons(false);
+ this.observer.disconnect();
+ this.stage?.stop();
+ this.stage?.element.remove();
+ }
+ this.syncButtons();
+ this.save();
+ }
+
+ private zoomButtons(): HTMLButtonElement[] {
+ return [...this.container.querySelectorAll('button[data-view="in"], button[data-view="out"]')];
+ }
+
+ /**
+ * Archify disables its zoom buttons at the 2D limits (100% and 300%). The
+ * 3D camera has its own range, so the buttons stay enabled while 3D is on,
+ * and get Archify's state back when 3D is turned off.
+ */
+ private holdZoomButtons(on: boolean): void {
+ if (on) {
+ this.zoomDisabled = new Map(this.zoomButtons().map((b) => [b, b.disabled]));
+ for (const button of this.zoomButtons()) this.zoomObserver.observe(button, { attributes: true, attributeFilter: ['disabled'] });
+ this.enableZoomButtons();
+ } else {
+ this.zoomObserver.disconnect();
+ for (const [button, disabled] of this.zoomDisabled) button.disabled = disabled;
+ }
+ }
+
+ private enableZoomButtons(): void {
+ for (const button of this.zoomButtons()) if (button.disabled) button.disabled = false;
+ }
+
+ private createStage(): void {
+ const stage = new Stage();
+ stage.onPick = (id) => this.pick(id);
+ stage.onHover = (id) => this.hover(id);
+ stage.onCameraChange = () => this.save();
+ if (this.saved.layered) stage.setLayered(true, false);
+ if (this.saved.camera) stage.restoreCamera(this.saved.camera);
+ this.stage = stage;
+ }
+
+ /**
+ * Archify plays its ambient trace once, when the page opens. Opening 3D
+ * later replays it once, so the 3D view starts the way 2D did. Readers who
+ * paused motion (Live off) or prefer reduced motion get no replay.
+ */
+ private replayAmbient(): void {
+ const html = document.documentElement;
+ if (this.ambientReplayed || !this.active) return;
+ // The load-time pass may still be playing (usually under the not-yet-built
+ // 3D view): wait for it to settle, then replay it in 3D.
+ if (html.getAttribute('data-ambient-motion') === 'running') {
+ const wait = new MutationObserver(() => {
+ if (html.getAttribute('data-ambient-motion') === 'running') return;
+ wait.disconnect();
+ this.replayAmbient();
+ });
+ wait.observe(html, { attributes: true, attributeFilter: ['data-ambient-motion'] });
+ return;
+ }
+ this.ambientReplayed = true;
+ if (html.getAttribute('data-ambient-motion') !== 'settled' || html.getAttribute('data-motion') === 'still') return;
+ if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
+ if (!this.svg.querySelector('[data-animate]')) return;
+ // Restart Archify's CSS trace: the "settled" state must be applied
+ // (style flushed) before "running" again, or the animations do not restart.
+ html.setAttribute('data-ambient-motion', 'settled');
+ void getComputedStyle(this.svg.querySelector('[data-animate]')!).animationName;
+ html.setAttribute('data-ambient-motion', 'running');
+ const settle = () => html.setAttribute('data-ambient-motion', 'settled');
+ const done = () => {
+ if (this.svg.getAnimations({ subtree: true }).some((anim) => anim.playState === 'running')) return;
+ this.svg.removeEventListener('animationend', done, true);
+ this.svg.removeEventListener('animationcancel', done, true);
+ settle();
+ };
+ this.svg.addEventListener('animationend', done, true);
+ this.svg.addEventListener('animationcancel', done, true);
+ // Safety net if an animation never reports its end.
+ window.setTimeout(settle, 12000);
+ }
+
+ private save(): void {
+ this.saved = { active: this.active, layered: this.stage?.layered ?? this.saved.layered, camera: this.stage?.cameraState() ?? this.saved.camera };
+ this.host.setState({ view3d: this.saved });
+ }
+
+ // ------------------------------------------------------------- picking
+
+ /** Hands a 3D click to Archify, as if the reader had clicked the 2D node. */
+ private pick(id: string | undefined): void {
+ const target = id ? this.svg.querySelector(`[data-node-id="${CSS.escape(id)}"]`) : this.svg;
+ target?.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
+ }
+
+ private hovered: Element | undefined;
+
+ /**
+ * Hands 3D hover to Archify as pointer events on the SVG node, so its
+ * intent trace (one-hop flows, fading the rest) plays as in 2D.
+ */
+ private hover(id: string | undefined): void {
+ const next = id ? this.svg.querySelector(`[data-node-id="${CSS.escape(id)}"]`) ?? undefined : undefined;
+ if (next === this.hovered) return;
+ const init = { bubbles: true, cancelable: true, pointerType: 'mouse', isPrimary: true, view: window };
+ this.hovered?.dispatchEvent(new PointerEvent('pointerout', init));
+ next?.dispatchEvent(new PointerEvent('pointerover', init));
+ this.hovered = next;
+ }
+
+ // -------------------------------------------------------------- redraw
+
+ private onMutation(records: MutationRecord[]): void {
+ if (!records.some((r) => this.changesDrawing(r))) return;
+ window.clearTimeout(this.redrawTimer);
+ // Let Archify's 140–200ms state transitions finish before sampling styles.
+ this.redrawTimer = window.setTimeout(() => void this.redraw(), REDRAW_MS);
+ }
+
+ /**
+ * Whether a mutation changes what the textures show. Archify's camera
+ * (the SVG root's style), its temporary overlays and the ambient-motion
+ * flag only change motion, which the stage follows live.
+ */
+ private changesDrawing(record: MutationRecord): boolean {
+ const target = record.target as Element;
+ if (target === this.svg && record.attributeName === 'style') return false;
+ if (target === document.documentElement) return record.attributeName === 'data-theme' || record.attributeName === 'data-preset';
+ // Intent trace only fades and draws flows; the stage mirrors both live.
+ if (record.attributeName?.startsWith('data-intent-trace')) return false;
+ const inOverlay = (node: Node) => node instanceof Element && !!node.closest('[data-relationship-pulse-overlay], [data-intent-trace-overlay], [data-route-probe-overlay], [data-route-journey-overlay], [data-semantic-lens-overlay], [data-story-overlay], [data-story-carrier-overlay], [data-chapter-handoff-overlay], [data-relationship-hit-overlay]');
+ if (record.type === 'childList') {
+ const nodes = [...record.addedNodes, ...record.removedNodes].filter((n) => n.nodeType === Node.ELEMENT_NODE);
+ if (nodes.length && nodes.every((n) => inOverlay(n) || [...(n as Element).getAttributeNames()].some((a) => a.endsWith('-overlay')))) return false;
+ return nodes.length > 0 || !inOverlay(target);
+ }
+ return !inOverlay(target);
+ }
+
+ private async redraw(): Promise {
+ if (this.drawing) {
+ this.pendingRedraw = true;
+ return this.drawing;
+ }
+ this.drawing = this.draw().finally(() => {
+ this.drawing = undefined;
+ if (this.pendingRedraw) {
+ this.pendingRedraw = false;
+ void this.redraw();
+ }
+ });
+ return this.drawing;
+ }
+
+ private async draw(): Promise {
+ if (!this.active || !this.stage) return;
+ await document.fonts?.ready;
+ const model = readModel(this.svg);
+ this.model = model;
+ const { viewBox } = model;
+ const area = { x: viewBox.x - MARGIN, y: viewBox.y - MARGIN, w: viewBox.w + MARGIN * 2, h: viewBox.h + MARGIN * 2 };
+ const scale = Math.min(TEXTURE_SCALE, 8192 / Math.max(area.w, area.h));
+ const root = getComputedStyle(document.documentElement);
+ const containerStyle = getComputedStyle(this.container);
+ const background = opaque(containerStyle.backgroundColor) ?? (root.getPropertyValue('--bg').trim() || '#020617');
+ const dot = root.getPropertyValue('--canvas-dot').trim();
+
+ const paintFloor = (ctx: CanvasRenderingContext2D) => {
+ ctx.fillStyle = background;
+ ctx.fillRect(area.x, area.y, area.w, area.h);
+ if (dot) {
+ ctx.fillStyle = dot;
+ for (let x = Math.ceil(area.x / 20) * 20; x < area.x + area.w; x += 20) {
+ for (let y = Math.ceil(area.y / 20) * 20; y < area.y + area.h; y += 20) {
+ ctx.beginPath();
+ ctx.arc(x, y, 0.9, 0, Math.PI * 2);
+ ctx.fill();
+ }
+ }
+ }
+ };
+
+ const [floor, nodes, labels] = await Promise.all([
+ rasterize(layerMarkup(this.svg, viewBox, { keep: ['floor'] }, scale), viewBox, area, scale, paintFloor),
+ rasterize(layerMarkup(this.svg, viewBox, { keep: ['node'], opaqueNodes: true }, scale), viewBox, area, scale),
+ rasterize(layerMarkup(this.svg, viewBox, { keep: ['label'] }, scale), viewBox, area, scale),
+ ]);
+ if (!this.active || this.model !== model) return;
+ const layers: Layers = { floor, nodes, labels };
+ const mask = root.getPropertyValue('--mask').trim() || '#0f172a';
+ this.stage.build(model, layers, { mask, dark: document.documentElement.getAttribute('data-theme') !== 'light' });
+ }
+
+ // -------------------------------------------------------------- export
+
+ private exportPng(): void {
+ if (!this.stage) return;
+ const shot = new Image();
+ shot.onload = () => {
+ const canvas = document.createElement('canvas');
+ canvas.width = shot.width;
+ canvas.height = shot.height;
+ const ctx = canvas.getContext('2d')!;
+ ctx.fillStyle = opaque(getComputedStyle(this.container).backgroundColor) ?? getComputedStyle(document.documentElement).getPropertyValue('--bg');
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
+ ctx.drawImage(shot, 0, 0);
+ const data = canvas.toDataURL('image/png');
+ const title = (document.querySelector('.header h1')?.textContent ?? 'archify').trim().replace(/[^\w.-]+/g, '-').toLowerCase();
+ this.host.post({ type: 'save', filename: `${title || 'archify'}-3d.png`, base64: data.slice(data.indexOf(',') + 1) });
+ };
+ shot.src = this.stage.snapshot();
+ }
+}
+
+/** A CSS colour if it is not fully transparent. */
+function opaque(value: string): string | undefined {
+ if (!value || value === 'transparent' || /rgba\([^)]*,\s*0\)$/.test(value)) return undefined;
+ return value;
+}
+
+function start(): void {
+ const host = window.__archifyHost;
+ const container = document.querySelector('.diagram-container');
+ const svg = container?.querySelector(':scope > svg');
+ if (!host || !container || !svg) return;
+ const style = document.createElement('style');
+ style.textContent = STYLE;
+ document.head.appendChild(style);
+ new Viewer3D(host, container, svg);
+}
+
+if (document.readyState === 'complete') start();
+else window.addEventListener('load', start, { once: true });
diff --git a/src/viewer3d/raster.ts b/src/viewer3d/raster.ts
new file mode 100644
index 0000000..7cd44a8
--- /dev/null
+++ b/src/viewer3d/raster.ts
@@ -0,0 +1,126 @@
+import { Box, Role, roleOf } from './svgModel';
+
+/**
+ * Turns parts of the live Archify SVG into images. Each element's computed
+ * style is written inline into a standalone copy, so the image carries the
+ * current theme, preset, focus and dimming exactly as the 2D view shows them.
+ */
+
+/** Presentation properties copied from computed style. */
+const PROPS = [
+ 'fill', 'fill-opacity', 'fill-rule',
+ 'stroke', 'stroke-width', 'stroke-opacity', 'stroke-dasharray', 'stroke-dashoffset',
+ 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit',
+ // visibility is left out: the 3D view hides the 2D SVG with it.
+ 'opacity', 'display', 'filter', 'paint-order',
+ 'font-family', 'font-size', 'font-weight', 'font-style', 'letter-spacing', 'text-anchor',
+ 'dominant-baseline', 'text-transform',
+];
+
+let fontCss: string | undefined;
+
+/** The page's @font-face rules (Archify embeds JetBrains Mono as data URIs). */
+function fontFaces(): string {
+ if (fontCss !== undefined) return fontCss;
+ const rules: string[] = [];
+ for (const sheet of [...document.styleSheets]) {
+ let list: CSSRuleList;
+ try {
+ list = sheet.cssRules;
+ } catch {
+ continue;
+ }
+ for (const rule of [...list]) if (rule instanceof CSSFontFaceRule) rules.push(rule.cssText);
+ }
+ fontCss = rules.join('\n');
+ return fontCss;
+}
+
+export interface LayerOptions {
+ /** Roles whose elements are drawn; everything else is hidden. */
+ keep: Role[];
+ /** Draw kept nodes fully opaque; the 3D view applies their dimming itself. */
+ opaqueNodes?: boolean;
+}
+
+/** Copies computed styles from the live tree onto a clone with the same shape. */
+function inlineStyles(live: Element, copy: Element, options: LayerOptions, inherited: Role | undefined, root: boolean): void {
+ const role = inherited ?? roleOf(live);
+ const isDefs = live.tagName === 'defs' || !!live.closest('defs');
+ const style = getComputedStyle(live);
+ const parts: string[] = [];
+ for (const prop of PROPS) {
+ const value = style.getPropertyValue(prop);
+ if (value) parts.push(`${prop}:${value}`);
+ }
+ let hidden = false;
+ if (root) {
+ // The root carries viewer state (camera transform, our fade); keep only
+ // what its children inherit.
+ copy.setAttribute('style', parts.filter((p) => /^(font|letter|text)/.test(p)).join(';'));
+ } else {
+ if (!isDefs) {
+ if (role) hidden = !options.keep.includes(role);
+ else if (live.children.length === 0) hidden = !options.keep.includes('floor');
+ }
+ if (options.opaqueNodes && role === 'node' && !inherited) parts.push('opacity:1');
+ if (hidden) parts.push('display:none');
+ copy.setAttribute('style', parts.join(';'));
+ }
+ copy.removeAttribute('class');
+ if (hidden) return;
+ const liveKids = live.children;
+ const copyKids = copy.children;
+ for (let i = 0; i < liveKids.length && i < copyKids.length; i++) {
+ inlineStyles(liveKids[i], copyKids[i], options, role, false);
+ }
+}
+
+/**
+ * Standalone SVG markup for one layer of the diagram, sized at `scale`
+ * pixels per user unit so the browser rasterizes it sharply.
+ */
+export function layerMarkup(svg: SVGSVGElement, viewBox: Box, options: LayerOptions, scale: number): string {
+ const copy = svg.cloneNode(true) as SVGSVGElement;
+ inlineStyles(svg, copy, options, undefined, true);
+ // Viewer-only children (focus overlays, hit areas) carry no data roles but
+ // are not part of the authored drawing.
+ copy.querySelectorAll('[data-viewer-only], .no-export').forEach((el) => el.remove());
+ copy.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
+ copy.setAttribute('viewBox', `${viewBox.x} ${viewBox.y} ${viewBox.w} ${viewBox.h}`);
+ copy.setAttribute('width', String(Math.round(viewBox.w * scale)));
+ copy.setAttribute('height', String(Math.round(viewBox.h * scale)));
+ const style = document.createElementNS('http://www.w3.org/2000/svg', 'style');
+ style.textContent = fontFaces();
+ copy.insertBefore(style, copy.firstChild);
+ return new XMLSerializer().serializeToString(copy);
+}
+
+export interface Raster {
+ canvas: HTMLCanvasElement;
+ /** Pixels per SVG user unit. */
+ scale: number;
+ /** SVG area the canvas covers (the view box plus a margin). */
+ area: Box;
+}
+
+/** Rasterizes SVG markup over `area` (in user units) at `scale` pixels per unit. */
+export async function rasterize(markup: string, viewBox: Box, area: Box, scale: number, paint?: (ctx: CanvasRenderingContext2D) => void): Promise {
+ const canvas = document.createElement('canvas');
+ canvas.width = Math.max(1, Math.round(area.w * scale));
+ canvas.height = Math.max(1, Math.round(area.h * scale));
+ const ctx = canvas.getContext('2d')!;
+ ctx.scale(scale, scale);
+ ctx.translate(-area.x, -area.y);
+ paint?.(ctx);
+ const url = URL.createObjectURL(new Blob([markup], { type: 'image/svg+xml' }));
+ try {
+ const image = new Image();
+ image.src = url;
+ await image.decode();
+ ctx.drawImage(image, viewBox.x, viewBox.y, viewBox.w, viewBox.h);
+ } finally {
+ URL.revokeObjectURL(url);
+ }
+ return { canvas, scale, area };
+}
diff --git a/src/viewer3d/stage.ts b/src/viewer3d/stage.ts
new file mode 100644
index 0000000..0c014d2
--- /dev/null
+++ b/src/viewer3d/stage.ts
@@ -0,0 +1,1019 @@
+import * as THREE from 'three';
+import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
+import type { Raster } from './raster';
+import { DiagramModel, EdgeShape, FrameShape, LabelShape, NodeShape, effectiveOpacity, FLOW_SELECTOR } from './svgModel';
+
+/**
+ * The 3D scene. World units are Archify's SVG user units: x is the SVG x,
+ * z the SVG y, and y points up. The floor is the diagram itself; nodes rise
+ * from it as slabs whose top face is the node as Archify draws it.
+ */
+
+const NODE_HEIGHT = 16;
+/** Pipes run at mid-height of the blocks, so they plug into their sides. */
+const PIPE_Y = NODE_HEIGHT / 2;
+/** Height offsets that let crossing pipes pass over each other. */
+const PIPE_LANES = [0, 3.5, -3.5];
+const FRAME_WALL = 12;
+const FLY_MS = 650;
+/** Glowing flows (focus pulse, traces) run in a slightly wider pipe over the relationship. */
+const FLOW_SCALE = 1.4;
+
+/** Height tier per semantic kind, for the stacked view. */
+const KIND_TIER: Record = { external: 3, frontend: 3, security: 2, backend: 1, cloud: 1, messagebus: 1, database: 0 };
+
+export interface Layers {
+ floor: Raster;
+ nodes: Raster;
+ labels: Raster;
+}
+
+export interface Palette {
+ mask: string;
+ dark: boolean;
+}
+
+interface NodeView {
+ shape: NodeShape;
+ group: THREE.Group;
+ body: THREE.Mesh;
+ materials: THREE.Material[];
+ lift: number;
+ /** Extra height while Archify's node pulse plays. */
+ pulse: number;
+ /** Opacity at build time; live dimming (intent trace) multiplies it. */
+ baseOpacity: number;
+ dim: number;
+}
+
+interface EdgeView {
+ shape: EdgeShape;
+ tube: THREE.Mesh;
+ material: THREE.MeshStandardMaterial;
+ cap: THREE.Mesh;
+ arrow?: THREE.Mesh;
+ arrowLength: number;
+ radius: number;
+ bias: number;
+ /** Opacity of the path's ancestors; the path's own opacity is read live. */
+ baseOpacity: number;
+ /** Archify's dashes are sized for a thin stroke; pipes stretch them by this. */
+ dashScale: number;
+ /** The route as built, for flows that run along it. */
+ path?: THREE.CurvePath;
+ pipeLength: number;
+ /** Last mirrored stroke-dasharray, stroke-dashoffset and opacity. */
+ mirrored: string;
+}
+
+/** A glowing flow Archify draws over a relationship (focus pulse, trace, lens…). */
+interface FlowView {
+ el: SVGPathElement;
+ edge: EdgeView;
+ mesh: THREE.Mesh;
+ material: THREE.MeshBasicMaterial;
+}
+
+interface LabelView {
+ shape: LabelShape;
+ mesh: THREE.Mesh;
+ edge?: EdgeView;
+}
+
+interface FrameView {
+ shape: FrameShape;
+ wall: THREE.Mesh;
+ rim: THREE.Line;
+ members: NodeShape[];
+}
+
+export interface CameraState {
+ position: [number, number, number];
+ target: [number, number, number];
+}
+
+/**
+ * True for a trackpad two-finger scroll, false for a mouse wheel. Trackpads
+ * send pixel deltas, often sideways or fractional; wheels send coarse
+ * vertical steps.
+ */
+function isTrackpadScroll(event: WheelEvent): boolean {
+ if (event.deltaMode !== WheelEvent.DOM_DELTA_PIXEL) return false;
+ if (event.deltaX !== 0) return true;
+ return !Number.isInteger(event.deltaY) || Math.abs(event.deltaY) < 40;
+}
+
+const reducedMotion = () => window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+
+function cssColor(value: string, fallback = '#888'): THREE.Color {
+ try {
+ return new THREE.Color().setStyle(value && value !== 'none' ? value : fallback);
+ } catch {
+ return new THREE.Color(fallback);
+ }
+}
+
+function canvasTexture(canvas: HTMLCanvasElement): THREE.CanvasTexture {
+ const texture = new THREE.CanvasTexture(canvas);
+ texture.colorSpace = THREE.SRGBColorSpace;
+ texture.anisotropy = 8;
+ texture.generateMipmaps = true;
+ texture.minFilter = THREE.LinearMipmapLinearFilter;
+ return texture;
+}
+
+/** A soft blurred rectangle, stretched under each node as a contact shadow. */
+const shadowTexture = (() => {
+ let texture: THREE.CanvasTexture | undefined;
+ return () => {
+ if (texture) return texture;
+ const canvas = document.createElement('canvas');
+ canvas.width = canvas.height = 128;
+ const ctx = canvas.getContext('2d')!;
+ ctx.filter = 'blur(12px)';
+ ctx.fillStyle = '#000';
+ ctx.fillRect(28, 28, 72, 72);
+ texture = new THREE.CanvasTexture(canvas);
+ return texture;
+ };
+})();
+
+/** Parses a computed stroke-dasharray ("10px, 8px", "none") into numbers. */
+function parseDashes(value: string): number[] {
+ if (!value || value === 'none') return [];
+ return value.split(/[\s,]+/).map((v) => parseFloat(v)).filter((v) => v >= 0 && Number.isFinite(v));
+}
+
+const dashCache = new Map();
+
+/** Alpha stripes for a dash pattern; textures are shared per pattern. */
+function dashFor(dasharray: number[]): { texture: THREE.Texture; period: number } | undefined {
+ if (!dasharray.length || dasharray.every((d) => d === 0)) return undefined;
+ const key = dasharray.map((d) => d.toFixed(4)).join(',');
+ let entry = dashCache.get(key);
+ if (!entry) {
+ entry = dashTexture(dasharray);
+ dashCache.set(key, entry);
+ }
+ // A clone shares the image but has its own repeat/offset.
+ const texture = entry.texture.clone();
+ texture.needsUpdate = true;
+ return { texture, period: entry.period };
+}
+
+/** Alpha stripes for a dashed relationship, from its stroke-dasharray. */
+function dashTexture(dasharray: number[]): { texture: THREE.CanvasTexture; period: number } {
+ const pattern = dasharray.length % 2 ? [...dasharray, ...dasharray] : dasharray;
+ const period = pattern.reduce((a, b) => a + b, 0);
+ const canvas = document.createElement('canvas');
+ // Enough pixels per period for both 10px dashes and pathLength=1 patterns.
+ const px = Math.min(4096, Math.max(8, 512 / Math.max(period, 1e-6))) ;
+ canvas.width = Math.max(2, Math.min(4096, Math.round(period * px)));
+ canvas.height = 1;
+ const ctx = canvas.getContext('2d')!;
+ let x = 0;
+ pattern.forEach((len, i) => {
+ ctx.fillStyle = i % 2 ? '#000' : '#fff';
+ ctx.fillRect(Math.round(x * px), 0, Math.ceil(len * px), 1);
+ x += len;
+ });
+ const texture = new THREE.CanvasTexture(canvas);
+ texture.wrapS = THREE.RepeatWrapping;
+ texture.magFilter = THREE.NearestFilter;
+ return { texture, period };
+}
+
+function disposeObject(root: THREE.Object3D): void {
+ root.traverse((obj) => {
+ const mesh = obj as THREE.Mesh;
+ mesh.geometry?.dispose();
+ const material = mesh.material as THREE.Material | THREE.Material[] | undefined;
+ for (const m of Array.isArray(material) ? material : material ? [material] : []) {
+ for (const value of Object.values(m)) if (value instanceof THREE.Texture && value !== shadowTexture() && ![...dashCache.values()].some((d) => d.texture === value)) value.dispose();
+ m.dispose();
+ }
+ });
+}
+
+export class Stage {
+ readonly element: HTMLDivElement;
+ private readonly renderer: THREE.WebGLRenderer;
+ private readonly scene = new THREE.Scene();
+ private readonly camera = new THREE.PerspectiveCamera(32, 1, 1, 40000);
+ private readonly controls: OrbitControls;
+ private world = new THREE.Group();
+ private model: DiagramModel | undefined;
+ private nodes = new Map();
+ private edges: EdgeView[] = [];
+ private flows = new Map();
+ /** Edge views by their SVG path data, to place Archify's flow overlays. */
+ private edgesByPath = new Map();
+ private glowColor = new THREE.Color('#34d399');
+ private pulsing = new Set();
+ /** Something changed that the next frame must draw. */
+ private dirty = true;
+ private motionActive = false;
+ private labels: LabelView[] = [];
+ private frames: FrameView[] = [];
+ private textures: THREE.Texture[] = [];
+ private levels = new Map();
+ private levelGap = 60;
+ private levelMix = 0;
+ private levelTarget = 0;
+ private hovered: string | undefined;
+ private frameId = 0;
+ private lastTime = 0;
+ private flight: { from: THREE.Vector3; to: THREE.Vector3; fromTarget: THREE.Vector3; toTarget: THREE.Vector3; start: number } | undefined;
+ private fitted = false;
+ private readonly raycaster = new THREE.Raycaster();
+ private downAt: { x: number; y: number } | undefined;
+ private panTimer: number | undefined;
+
+ /** Called with a node id, or undefined for empty space. */
+ onPick: (id: string | undefined) => void = () => {};
+ /** Called when the pointer moves onto another node, or off all nodes. */
+ onHover: (id: string | undefined) => void = () => {};
+ /** Called when the camera settles after the reader moves it. */
+ onCameraChange: () => void = () => {};
+
+ constructor() {
+ this.element = document.createElement('div');
+ this.element.className = 'archify-3d-stage';
+ this.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
+ // Full retina density costs 4x the pixels for little gain on a moving scene.
+ this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.5));
+ this.renderer.setClearColor(0x000000, 0);
+ this.element.appendChild(this.renderer.domElement);
+
+ this.controls = new OrbitControls(this.camera, this.renderer.domElement);
+ this.controls.enableDamping = true;
+ this.controls.dampingFactor = 0.09;
+ this.controls.screenSpacePanning = false;
+ this.controls.maxPolarAngle = Math.PI * 0.47;
+ this.controls.zoomToCursor = true;
+ this.controls.addEventListener('end', () => this.onCameraChange());
+ this.controls.addEventListener('change', () => (this.dirty = true));
+
+ this.scene.add(new THREE.HemisphereLight(0xffffff, 0x8090a0, 2.2));
+ const sun = new THREE.DirectionalLight(0xffffff, 1.4);
+ sun.position.set(-0.4, 1, 0.6);
+ this.scene.add(sun);
+ this.scene.add(this.world);
+
+ const canvas = this.renderer.domElement;
+ // Keep Archify's 2D pan and zoom (which start on the container) out of
+ // 3D input. pointermove/pointerup must still reach the document, where
+ // OrbitControls tracks a drag.
+ for (const type of ['pointerdown', 'wheel', 'dblclick']) {
+ canvas.addEventListener(type, (event) => event.stopPropagation());
+ }
+ canvas.addEventListener('pointerdown', (event) => (this.downAt = { x: event.clientX, y: event.clientY }));
+ // Archify dismisses focus on document-level clicks outside the SVG. Catch
+ // the canvas click at window capture, before those listeners, and hand
+ // Archify a click on the node instead.
+ window.addEventListener(
+ 'click',
+ (event) => {
+ if (event.target !== canvas) return;
+ event.stopPropagation();
+ const still = this.downAt && Math.hypot(event.clientX - this.downAt.x, event.clientY - this.downAt.y) <= 4;
+ this.downAt = undefined;
+ if (still) this.onPick(this.pick(event));
+ },
+ true,
+ );
+ canvas.addEventListener('pointermove', (event) => {
+ const id = this.pick(event);
+ if (id !== this.hovered) {
+ this.dirty = true;
+ this.onHover(id);
+ }
+ this.hovered = id;
+ canvas.style.cursor = id ? 'pointer' : 'grab';
+ });
+ canvas.addEventListener('pointerleave', () => {
+ if (this.hovered) this.onHover(undefined);
+ this.hovered = undefined;
+ this.dirty = true;
+ });
+ canvas.addEventListener('dblclick', (event) => {
+ const id = this.pick(event);
+ if (id) this.focusNode(id);
+ else this.fit();
+ });
+
+ // Trackpad scrolling pans across the floor, in both directions, like
+ // scrolling over the 2D diagram. Pinch (ctrl+wheel) and mouse wheels
+ // fall through to OrbitControls, which zooms.
+ this.element.addEventListener(
+ 'wheel',
+ (event) => {
+ if (event.ctrlKey || !isTrackpadScroll(event)) return;
+ event.preventDefault();
+ event.stopPropagation();
+ this.flight = undefined;
+ this.panBy(event.deltaX, event.deltaY);
+ },
+ { capture: true, passive: false },
+ );
+
+ new ResizeObserver(() => this.resize()).observe(this.element);
+ }
+
+ /** Moves camera and target along the floor by a scroll delta in pixels. */
+ private panBy(dx: number, dy: number): void {
+ const distance = this.camera.position.distanceTo(this.controls.target);
+ const perPixel = (2 * distance * Math.tan(THREE.MathUtils.degToRad(this.camera.fov / 2))) / Math.max(1, this.element.clientHeight);
+ const forward = this.controls.target.clone().sub(this.camera.position).setY(0);
+ if (forward.lengthSq() < 1e-6) forward.set(0, 0, -1).applyQuaternion(this.camera.quaternion).setY(0);
+ if (forward.lengthSq() < 1e-6) forward.set(0, 0, -1);
+ forward.normalize();
+ const right = new THREE.Vector3().crossVectors(forward, new THREE.Vector3(0, 1, 0)).normalize();
+ // Scrolling down reveals what is below: move towards the reader.
+ const move = right.multiplyScalar(dx * perPixel).addScaledVector(forward, -dy * perPixel);
+ this.camera.position.add(move);
+ this.controls.target.add(move);
+ this.controls.update();
+ window.clearTimeout(this.panTimer);
+ this.panTimer = window.setTimeout(() => this.onCameraChange(), 250);
+ }
+
+ // ---------------------------------------------------------------- build
+
+ /** Rebuilds the scene from the current SVG state. The camera is kept. */
+ build(model: DiagramModel, layers: Layers, palette: Palette): void {
+ disposeObject(this.world);
+ this.scene.remove(this.world);
+ for (const t of this.textures) t.dispose();
+ this.world = new THREE.Group();
+ this.scene.add(this.world);
+ this.model = model;
+ this.nodes.clear();
+ this.edges = [];
+ this.edgesByPath.clear();
+ this.flows.clear();
+ this.pulsing.clear();
+ this.mirrored = false;
+ const root = getComputedStyle(document.documentElement);
+ this.glowColor = cssColor(root.getPropertyValue('--arrow-emphasis').trim(), '#34d399');
+ this.labels = [];
+ this.frames = [];
+
+ const floorTexture = canvasTexture(layers.floor.canvas);
+ const nodeTexture = canvasTexture(layers.nodes.canvas);
+ const labelTexture = canvasTexture(layers.labels.canvas);
+ this.textures = [floorTexture, nodeTexture, labelTexture];
+
+ this.computeLevels(model);
+ this.buildFloor(layers.floor, floorTexture);
+ for (const shape of model.nodes) this.buildNode(shape, layers.nodes, nodeTexture, palette);
+ model.edges.forEach((shape, index) => this.buildEdge(shape, index));
+ for (const shape of model.labels) this.buildLabel(shape, layers.labels, labelTexture);
+ for (const shape of model.frames) this.buildFrame(shape, model);
+ this.layout();
+
+ if (!this.fitted) {
+ this.fit(false);
+ this.fitted = true;
+ }
+ this.dirty = true;
+ }
+
+ private mirrored = false;
+
+ private computeLevels(model: DiagramModel): void {
+ const tiers = new Map(model.nodes.map((n) => [n.id, KIND_TIER[n.kind] ?? 1]));
+ const used = [...new Set(tiers.values())].sort((a, b) => a - b);
+ this.levels = new Map([...tiers].map(([id, tier]) => [id, used.indexOf(tier)]));
+ const { w, h } = model.viewBox;
+ this.levelGap = Math.max(48, Math.min(140, Math.max(w, h) * 0.08));
+ }
+
+ private levelY(id: string): number {
+ return (this.levels.get(id) ?? 0) * this.levelGap * this.levelMix;
+ }
+
+ private buildFloor(raster: Raster, texture: THREE.Texture): void {
+ const { area } = raster;
+ const floor = new THREE.Mesh(
+ new THREE.PlaneGeometry(area.w, area.h).rotateX(-Math.PI / 2),
+ new THREE.MeshBasicMaterial({ map: texture }),
+ );
+ floor.position.set(area.x + area.w / 2, 0, area.y + area.h / 2);
+ floor.renderOrder = -1;
+ this.world.add(floor);
+ }
+
+ private buildNode(shape: NodeShape, raster: Raster, texture: THREE.Texture, palette: Palette): void {
+ const { x, y, w, h } = shape;
+ const r = Math.min(shape.rx, w / 2, h / 2);
+ const outline = new THREE.Shape();
+ outline.moveTo(x + r, y);
+ outline.lineTo(x + w - r, y);
+ outline.quadraticCurveTo(x + w, y, x + w, y + r);
+ outline.lineTo(x + w, y + h - r);
+ outline.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
+ outline.lineTo(x + r, y + h);
+ outline.quadraticCurveTo(x, y + h, x, y + h - r);
+ outline.lineTo(x, y + r);
+ outline.quadraticCurveTo(x, y, x + r, y);
+
+ const geometry = new THREE.ExtrudeGeometry(outline, { depth: NODE_HEIGHT, bevelEnabled: false, curveSegments: 6 });
+ // Map the caps onto the node layer: same SVG coordinates, same pixels.
+ const pos = geometry.getAttribute('position');
+ const uv = geometry.getAttribute('uv');
+ const { area } = raster;
+ for (let i = 0; i < pos.count; i++) {
+ uv.setXY(i, (pos.getX(i) - area.x) / area.w, 1 - (pos.getY(i) - area.y) / area.h);
+ }
+ // Shape y (SVG y, downwards) becomes world z; the extrusion becomes height.
+ geometry.rotateX(Math.PI / 2);
+ geometry.translate(0, NODE_HEIGHT, 0);
+ // Group 0 holds both caps; keep only the top one. The bottom cap carries
+ // the same picture and shows through when a faded block turns see-through.
+ const caps = geometry.groups[0];
+ const half = caps.count / 2;
+ const bottomFirst = geometry.getAttribute('position').getY(caps.start) < NODE_HEIGHT / 2;
+ caps.start += bottomFirst ? half : 0;
+ caps.count = half;
+
+ const body = this.model ? getComputedStyle(shape.el.querySelector(`rect.c-${CSS.escape(shape.kind)}`) ?? shape.el) : undefined;
+ const stroke = cssColor(body?.stroke ?? '', '#64748b');
+ const side = stroke.clone().lerp(cssColor(palette.mask), palette.dark ? 0.45 : 0.25);
+ const capMaterial = new THREE.MeshBasicMaterial({ map: texture, transparent: true, side: THREE.DoubleSide });
+ const sideMaterial = new THREE.MeshLambertMaterial({ color: side, transparent: true, side: THREE.DoubleSide });
+ const mesh = new THREE.Mesh(geometry, [capMaterial, sideMaterial]);
+ mesh.userData.id = shape.id;
+
+ // Contact shadow on the floor.
+ const shadowMaterial = new THREE.MeshBasicMaterial({
+ map: shadowTexture(),
+ transparent: true,
+ opacity: palette.dark ? 0.55 : 0.22,
+ depthWrite: false,
+ });
+ const shadow = new THREE.Mesh(new THREE.PlaneGeometry(w * 1.55, h * 1.9).rotateX(-Math.PI / 2), shadowMaterial);
+ shadow.position.set(x + w / 2, 0.15, y + h / 2 + 6);
+ shadow.renderOrder = 0;
+ this.world.add(shadow);
+
+ const group = new THREE.Group();
+ group.add(mesh);
+ this.world.add(group);
+
+ const opacity = effectiveOpacity(shape.el, this.model!.svg);
+ for (const m of [capMaterial, sideMaterial]) m.opacity = opacity;
+ shadowMaterial.opacity *= opacity;
+ this.nodes.set(shape.id, { shape, group, body: mesh, materials: [capMaterial, sideMaterial, shadowMaterial], lift: 0, pulse: 0, baseOpacity: opacity, dim: 1 });
+ }
+
+ private buildEdge(shape: EdgeShape, index: number): void {
+ const style = getComputedStyle(shape.path);
+ const width = parseFloat(style.strokeWidth) || 1.5;
+ const color = cssColor(style.stroke, '#94a3b8');
+ const parent: Element | null = shape.path.parentElement;
+ const baseOpacity = (parent && parent !== this.model!.svg ? effectiveOpacity(parent, this.model!.svg) : 1) * (Number(style.strokeOpacity) || 1);
+ const radius = Math.min(4.5, Math.max(2.4, width * 2));
+ const material = new THREE.MeshStandardMaterial({
+ color,
+ roughness: 0.32,
+ metalness: 0.18,
+ emissive: color,
+ emissiveIntensity: 0.14,
+ transparent: true,
+ opacity: baseOpacity * Number(style.opacity || 1),
+ });
+ const tube = new THREE.Mesh(new THREE.BufferGeometry(), material);
+ const cap = new THREE.Mesh(new THREE.SphereGeometry(radius, 12, 8), material);
+ this.world.add(tube, cap);
+
+ // Arrowhead: a cone in the colour of Archify's marker, tip at the route end.
+ let arrow: THREE.Mesh | undefined;
+ const arrowLength = radius * 4.2;
+ const marker = /url\(["']?#([^"')]+)["']?\)/.exec(shape.path.getAttribute('marker-end') ?? '')?.[1];
+ const polygon = marker ? this.model!.svg.querySelector(`marker#${CSS.escape(marker)} polygon, marker#${CSS.escape(marker)} path`) : null;
+ if (polygon) {
+ const fill = cssColor(getComputedStyle(polygon).fill, style.stroke);
+ const geometry = new THREE.ConeGeometry(radius * 2.1, arrowLength, 16);
+ geometry.rotateZ(-Math.PI / 2);
+ geometry.translate(-arrowLength / 2, 0, 0);
+ arrow = new THREE.Mesh(
+ geometry,
+ new THREE.MeshStandardMaterial({ color: fill, roughness: 0.32, metalness: 0.18, emissive: fill, emissiveIntensity: 0.18, transparent: true, opacity: material.opacity }),
+ );
+ this.world.add(arrow);
+ }
+ const view: EdgeView = {
+ shape,
+ tube,
+ material,
+ cap,
+ arrow,
+ arrowLength: arrow ? arrowLength : 0,
+ radius,
+ bias: PIPE_LANES[index % PIPE_LANES.length],
+ baseOpacity,
+ // Archify's dash lengths suit a thin stroke; stretch them to the pipe's
+ // thickness so a dashed pipe reads as separate pipe sections.
+ dashScale: Math.max(1, (radius * 2) / (width * 2.2)),
+ pipeLength: shape.length,
+ mirrored: '',
+ };
+ this.edges.push(view);
+ const d = shape.path.getAttribute('d');
+ if (d) this.edgesByPath.set(d.trim(), view);
+ this.mirrorEdge(view);
+ }
+
+ /**
+ * Copies the live dash, offset and opacity of the 2D path onto its pipe.
+ * Archify animates exactly these (trace draw-in, focus, Live); mirroring
+ * them keeps the 3D motion in step with 2D, in every preset.
+ */
+ private mirrorEdge(view: EdgeView): boolean {
+ const style = getComputedStyle(view.shape.path);
+ const key = `${style.strokeDasharray}|${style.strokeDashoffset}|${style.opacity}`;
+ if (key === view.mirrored) return false;
+ const dashKey = view.mirrored.split('|')[0];
+ view.mirrored = key;
+ const material = view.material;
+ if (style.strokeDasharray !== dashKey) {
+ const dash = dashFor(parseDashes(style.strokeDasharray).map((d) => d * view.dashScale));
+ material.alphaMap?.dispose();
+ material.alphaMap = dash?.texture ?? null;
+ material.alphaTest = dash ? 0.5 : 0;
+ material.userData.period = dash?.period ?? 1;
+ material.needsUpdate = true;
+ }
+ const alpha = material.alphaMap;
+ if (alpha) {
+ const period = material.userData.period as number;
+ alpha.repeat.set(view.pipeLength / period, 1);
+ alpha.offset.x = ((parseFloat(style.strokeDashoffset) || 0) * view.dashScale) / period;
+ }
+ const opacity = view.baseOpacity * Number(style.opacity || 1);
+ material.opacity = opacity;
+ // A relationship that is animating glows a little, as Signal Flow does in 2D.
+ const animating = view.shape.path.getAnimations().some((anim) => anim.playState === 'running');
+ material.emissiveIntensity = animating ? 0.45 : 0.14;
+ const arrowMaterial = view.arrow?.material as THREE.MeshStandardMaterial | undefined;
+ if (arrowMaterial) arrowMaterial.opacity = opacity;
+ return true;
+ }
+
+ private buildLabel(shape: LabelShape, raster: Raster, texture: THREE.Texture): void {
+ const { area } = raster;
+ const map = texture.clone();
+ map.repeat.set(shape.w / area.w, shape.h / area.h);
+ map.offset.set((shape.x - area.x) / area.w, 1 - (shape.y - area.y + shape.h) / area.h);
+ map.needsUpdate = true;
+ this.textures.push(map);
+ const mesh = new THREE.Mesh(
+ new THREE.PlaneGeometry(shape.w, shape.h),
+ new THREE.MeshBasicMaterial({ map, transparent: true, depthWrite: false, side: THREE.DoubleSide }),
+ );
+ mesh.renderOrder = 2;
+ this.world.add(mesh);
+ this.labels.push({ shape, mesh, edge: this.edges.find((e) => e.shape.key === shape.key) });
+ }
+
+ private buildFrame(shape: FrameShape, model: DiagramModel): void {
+ if (shape.kind === 'lane') return;
+ const style = getComputedStyle(shape.el);
+ const color = cssColor(style.stroke, '#64748b');
+ const r = Math.min(shape.rx, shape.w / 2, shape.h / 2);
+ const outline = new THREE.Shape();
+ const { x, y, w, h } = shape;
+ outline.moveTo(x + r, y);
+ outline.lineTo(x + w - r, y);
+ outline.quadraticCurveTo(x + w, y, x + w, y + r);
+ outline.lineTo(x + w, y + h - r);
+ outline.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
+ outline.lineTo(x + r, y + h);
+ outline.quadraticCurveTo(x, y + h, x, y + h - r);
+ outline.lineTo(x, y + r);
+ outline.quadraticCurveTo(x, y, x + r, y);
+ const points = outline.getPoints(8);
+
+ // A vertical strip along the outline; its height is set in layout().
+ const positions: number[] = [];
+ for (let i = 0; i < points.length - 1; i++) {
+ const a = points[i];
+ const b = points[i + 1];
+ positions.push(a.x, 0, a.y, b.x, 0, b.y, b.x, 1, b.y, a.x, 0, a.y, b.x, 1, b.y, a.x, 1, a.y);
+ }
+ const geometry = new THREE.BufferGeometry();
+ geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
+ const wall = new THREE.Mesh(
+ geometry,
+ new THREE.MeshBasicMaterial({ color, transparent: true, opacity: 0.07, side: THREE.DoubleSide, depthWrite: false }),
+ );
+ const rim = new THREE.Line(
+ new THREE.BufferGeometry().setFromPoints(points.map((p) => new THREE.Vector3(p.x, 1, p.y))),
+ new THREE.LineBasicMaterial({ color, transparent: true, opacity: 0.55 }),
+ );
+ this.world.add(wall, rim);
+ const members = model.nodes.filter((n) => n.x + n.w / 2 > x && n.x + n.w / 2 < x + w && n.y + n.h / 2 > y && n.y + n.h / 2 < y + h);
+ this.frames.push({ shape, wall, rim, members });
+ }
+
+ /** Positions that depend on the level mix and hover. */
+ private layout(): void {
+ for (const view of this.nodes.values()) view.group.position.y = this.levelY(view.shape.id) + view.lift + view.pulse;
+
+ for (const view of this.edges) {
+ const { points, from, to } = view.shape;
+ const y0 = this.levelY(from);
+ const y1 = this.levelY(to);
+ const n = points.length;
+ const pts: THREE.Vector3[] = [];
+ for (let i = 0; i < n; i++) {
+ const s = i / (n - 1);
+ const k = s * s * (3 - 2 * s);
+ pts.push(new THREE.Vector3(points[i][0], PIPE_Y + view.bias + y0 + (y1 - y0) * k, points[i][1]));
+ }
+ const end = pts[n - 1];
+ // The pipe stops where the arrowhead's base begins.
+ let cut = n - 1;
+ while (cut > 1 && pts[cut].distanceTo(end) < view.arrowLength * 0.85) cut--;
+ const path = new THREE.CurvePath();
+ for (let i = 1; i <= cut; i++) path.add(new THREE.LineCurve3(pts[i - 1], pts[i]));
+ view.tube.geometry.dispose();
+ view.tube.geometry = new THREE.TubeGeometry(path, Math.max(2, cut), view.radius, 10, false);
+ view.cap.position.copy(pts[0]);
+ view.path = path;
+ view.pipeLength = path.getLength();
+ view.mirrored = '';
+ this.mirrorEdge(view);
+ if (view.arrow) {
+ const t = end.clone().sub(pts[Math.max(0, n - 4)]).normalize();
+ const side = new THREE.Vector3().crossVectors(t, new THREE.Vector3(0, 1, 0));
+ if (side.lengthSq() < 1e-6) side.set(1, 0, 0);
+ side.normalize();
+ const normal = new THREE.Vector3().crossVectors(side, t);
+ view.arrow.quaternion.setFromRotationMatrix(new THREE.Matrix4().makeBasis(t, normal, side));
+ view.arrow.position.copy(end);
+ }
+ }
+
+ for (const view of this.labels) {
+ const { shape } = view;
+ const cx = shape.x + shape.w / 2;
+ const cz = shape.y + shape.h / 2;
+ // Labels lie on top of their pipe.
+ let y = PIPE_Y + (view.edge ? view.edge.bias + view.edge.radius : 4) + 1.2;
+ if (view.edge && this.levelMix > 0) {
+ const { points, from, to } = view.edge.shape;
+ let best = 0;
+ let bestD = Infinity;
+ points.forEach(([px, pz], i) => {
+ const d = (px - cx) ** 2 + (pz - cz) ** 2;
+ if (d < bestD) (bestD = d), (best = i);
+ });
+ const s = best / Math.max(1, points.length - 1);
+ const k = s * s * (3 - 2 * s);
+ y += this.levelY(from) + (this.levelY(to) - this.levelY(from)) * k;
+ }
+ view.mesh.position.set(cx, y + (this.levelMix > 0.5 ? shape.h / 2 : 0), cz);
+ view.mesh.userData.billboard = this.levelMix > 0.5;
+ if (!view.mesh.userData.billboard) view.mesh.rotation.set(-Math.PI / 2, 0, 0);
+ }
+
+ for (const view of this.frames) {
+ const top = view.members.length
+ ? Math.max(...view.members.map((m) => this.levelY(m.id))) + NODE_HEIGHT + FRAME_WALL
+ : FRAME_WALL;
+ view.wall.scale.y = top;
+ view.rim.position.y = top - 1;
+ }
+ for (const flow of this.flows.values()) this.removeFlow(flow);
+ this.dirty = true;
+ }
+
+ // --------------------------------------------------------------- motion
+
+ /**
+ * Follows Archify's own animations, which keep running on the hidden 2D
+ * SVG: the ambient trace (relationships drawing in, nodes pulsing) and the
+ * flows drawn over relationships (focus pulse, intent trace, route probe,
+ * lens, story). Returns true while anything moves.
+ */
+ private syncMotion(): boolean {
+ const svg = this.model?.svg;
+ if (!svg) return false;
+ const running = svg.getAnimations({ subtree: true }).filter((a) => a.playState === 'running');
+ const overlays = svg.querySelectorAll(FLOW_SELECTOR);
+ if (!running.length && !overlays.length && !this.flows.size && !this.motionActive) return false;
+
+ let changed = false;
+ for (const view of this.edges) changed = this.mirrorEdge(view) || changed;
+ for (const view of this.nodes.values()) changed = this.mirrorNode(view) || changed;
+
+ // Node pulses: Archify animates glow and stroke on [data-animate="node"].
+ const pulsing = new Set();
+ for (const animation of running) {
+ const name = (animation as CSSAnimation).animationName ?? '';
+ if (!/node-pulse/.test(name)) continue;
+ const target = (animation.effect as KeyframeEffect | null)?.target as Element | null;
+ const id = target?.closest('[data-node-id]')?.getAttribute('data-node-id');
+ const view = id ? this.nodes.get(id) : undefined;
+ if (!view) continue;
+ const p = animation.effect?.getComputedTiming().progress ?? 0;
+ // Archify's envelope: rise to 18%, hold to 36%, fall back by 72%.
+ const f = p < 0.18 ? p / 0.18 : p < 0.36 ? 1 : p < 0.72 ? 1 - (p - 0.36) / 0.36 : 0;
+ this.setPulse(view, f);
+ pulsing.add(view);
+ }
+ for (const view of this.pulsing) if (!pulsing.has(view)) this.setPulse(view, 0);
+ this.pulsing = pulsing;
+
+ // Flows over relationships.
+ const seen = new Set();
+ overlays.forEach((el) => {
+ const edge = this.edgesByPath.get((el.getAttribute('d') ?? '').trim());
+ if (!edge?.path) return;
+ seen.add(el);
+ let flow = this.flows.get(el);
+ if (!flow) {
+ flow = this.addFlow(el, edge);
+ if (!flow) return;
+ }
+ this.mirrorFlow(flow);
+ });
+ for (const flow of [...this.flows.values()]) if (!seen.has(flow.el)) this.removeFlow(flow);
+
+ const active = running.length > 0 || this.flows.size > 0;
+ const result = changed || active || pulsing.size > 0 || this.motionActive !== active;
+ this.motionActive = active;
+ return result;
+ }
+
+ /**
+ * Live node dimming: Archify's intent trace fades unrelated nodes with
+ * fill/stroke opacity, set from attributes that do not rebuild textures.
+ */
+ private mirrorNode(view: NodeView): boolean {
+ const dim = Math.max(0.18, Number(getComputedStyle(view.shape.el).fillOpacity || 1));
+ if (Math.abs(dim - view.dim) < 0.01) return false;
+ view.dim = dim;
+ const [cap, side, shadow] = view.materials;
+ cap.opacity = side.opacity = view.baseOpacity * dim;
+ shadow.opacity = (shadow.userData.base ??= shadow.opacity) * dim;
+ return true;
+ }
+
+ private setPulse(view: NodeView, f: number): void {
+ const side = view.materials[1] as THREE.MeshLambertMaterial;
+ side.emissive.copy(this.glowColor);
+ side.emissiveIntensity = f * 0.9;
+ view.pulse = f * 3;
+ view.group.position.y = this.levelY(view.shape.id) + view.lift + view.pulse;
+ }
+
+ private addFlow(el: SVGPathElement, edge: EdgeView): FlowView | undefined {
+ if (!edge.path) return undefined;
+ const material = new THREE.MeshBasicMaterial({ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending });
+ const mesh = new THREE.Mesh(new THREE.TubeGeometry(edge.path, Math.max(2, Math.round(edge.pipeLength / 3)), edge.radius * FLOW_SCALE, 10, false), material);
+ mesh.renderOrder = 3;
+ this.world.add(mesh);
+ const flow: FlowView = { el, edge, mesh, material };
+ this.flows.set(el, flow);
+ return flow;
+ }
+
+ /** Flows use pathLength="1": their dashes are fractions of the route. */
+ private mirrorFlow(flow: FlowView): void {
+ const style = getComputedStyle(flow.el);
+ const material = flow.material;
+ material.color = cssColor(style.stroke, '#34d399');
+ material.opacity = effectiveOpacity(flow.el, this.model!.svg) * Number(style.strokeOpacity || 1);
+ const pattern = parseDashes(style.strokeDasharray);
+ const key = pattern.join(',');
+ if (material.userData.dashKey !== key) {
+ material.alphaMap?.dispose();
+ const dash = dashFor(pattern);
+ material.alphaMap = dash?.texture ?? null;
+ material.alphaTest = dash ? 0.5 : 0;
+ material.userData = { dashKey: key, period: dash?.period ?? 1 };
+ material.needsUpdate = true;
+ }
+ if (material.alphaMap) {
+ const period = material.userData.period as number;
+ material.alphaMap.repeat.set(1 / period, 1);
+ material.alphaMap.offset.x = (parseFloat(style.strokeDashoffset) || 0) / period;
+ }
+ }
+
+ private removeFlow(flow: FlowView): void {
+ this.world.remove(flow.mesh);
+ flow.mesh.geometry.dispose();
+ flow.material.alphaMap?.dispose();
+ flow.material.dispose();
+ this.flows.delete(flow.el);
+ }
+
+ // --------------------------------------------------------------- camera
+
+ private bounds(): THREE.Box3 {
+ const box = new THREE.Box3();
+ if (!this.model) return box;
+ const { x, y, w, h } = this.model.viewBox;
+ box.expandByPoint(new THREE.Vector3(x, 0, y));
+ box.expandByPoint(new THREE.Vector3(x + w, NODE_HEIGHT + this.levelGap * this.levelMix * 3, y + h));
+ return box;
+ }
+
+ private flyTo(position: THREE.Vector3, target: THREE.Vector3, animate = true): void {
+ if (!animate || reducedMotion()) {
+ this.flight = undefined;
+ this.camera.position.copy(position);
+ this.controls.target.copy(target);
+ this.controls.update();
+ this.dirty = true;
+ return;
+ }
+ this.flight = { from: this.camera.position.clone(), to: position, fromTarget: this.controls.target.clone(), toTarget: target, start: performance.now() };
+ }
+
+ /**
+ * Camera position looking at the box centre from `direction`, close enough
+ * that every corner of the box projects inside the view (with a margin).
+ */
+ private framing(box: THREE.Box3, direction: THREE.Vector3, margin = 0.9): { position: THREE.Vector3; target: THREE.Vector3 } {
+ const target = box.getCenter(new THREE.Vector3());
+ const corners: THREE.Vector3[] = [];
+ for (const x of [box.min.x, box.max.x]) for (const y of [box.min.y, box.max.y]) for (const z of [box.min.z, box.max.z]) corners.push(new THREE.Vector3(x, y, z));
+ const probe = this.camera.clone();
+ const fits = (distance: number) => {
+ probe.position.copy(target).addScaledVector(direction, distance);
+ probe.up.set(0, 1, 0);
+ probe.lookAt(target);
+ probe.updateMatrixWorld();
+ probe.updateProjectionMatrix();
+ return corners.every((c) => {
+ const p = c.clone().project(probe);
+ return Math.abs(p.x) <= margin && Math.abs(p.y) <= margin && p.z < 1;
+ });
+ };
+ let lo = 1;
+ let hi = box.getSize(new THREE.Vector3()).length() * 4 + 100;
+ while (!fits(hi)) hi *= 2;
+ for (let i = 0; i < 32; i++) {
+ const mid = (lo + hi) / 2;
+ if (fits(mid)) hi = mid;
+ else lo = mid;
+ }
+ return { position: target.clone().addScaledVector(direction, hi), target };
+ }
+
+ /** Frames the whole diagram from the front, raised like a reading desk. */
+ fit(animate = true): void {
+ const { position, target } = this.framing(this.bounds(), new THREE.Vector3(-0.16, 1.25, 1).normalize());
+ this.flyTo(position, target, animate);
+ }
+
+ /** Straight down, like the 2D view. */
+ top(animate = true): void {
+ const { position, target } = this.framing(this.bounds(), new THREE.Vector3(0, 1, 0.0001).normalize(), 0.95);
+ this.flyTo(position, target, animate);
+ }
+
+ focusNode(id: string): void {
+ const view = this.nodes.get(id);
+ if (!view) return;
+ const { x, y, w, h } = view.shape;
+ const target = new THREE.Vector3(x + w / 2, this.levelY(id) + NODE_HEIGHT, y + h / 2);
+ const offset = this.camera.position.clone().sub(this.controls.target).setLength(Math.max(w, h) * 4.5 + 120);
+ this.flyTo(target.clone().add(offset), target);
+ }
+
+ zoom(factor: number): void {
+ const offset = this.camera.position.clone().sub(this.controls.target).multiplyScalar(1 / factor);
+ this.flyTo(this.controls.target.clone().add(offset), this.controls.target.clone());
+ }
+
+ /** The camera, once the scene has been framed. */
+ cameraState(): CameraState | undefined {
+ if (!this.fitted) return undefined;
+ return { position: this.camera.position.toArray() as CameraState['position'], target: this.controls.target.toArray() as CameraState['target'] };
+ }
+
+ restoreCamera(state: CameraState): void {
+ this.flyTo(new THREE.Vector3(...state.position), new THREE.Vector3(...state.target), false);
+ this.fitted = true;
+ }
+
+ get layered(): boolean {
+ return this.levelTarget === 1;
+ }
+
+ setLayered(on: boolean, animate = true): void {
+ this.levelTarget = on ? 1 : 0;
+ this.dirty = true;
+ if (!animate || reducedMotion()) {
+ this.levelMix = this.levelTarget;
+ this.layout();
+ }
+ }
+
+ // -------------------------------------------------------------- picking
+
+ private pick(event: MouseEvent): string | undefined {
+ const rect = this.renderer.domElement.getBoundingClientRect();
+ const pointer = new THREE.Vector2(((event.clientX - rect.left) / rect.width) * 2 - 1, -((event.clientY - rect.top) / rect.height) * 2 + 1);
+ this.raycaster.setFromCamera(pointer, this.camera);
+ const hit = this.raycaster.intersectObjects([...this.nodes.values()].map((v) => v.body), false)[0];
+ return hit?.object.userData.id;
+ }
+
+ // ---------------------------------------------------------------- loop
+
+ private resize(): void {
+ const { clientWidth: w, clientHeight: h } = this.element;
+ if (!w || !h) return;
+ this.renderer.setSize(w, h);
+ this.camera.aspect = w / h;
+ this.camera.updateProjectionMatrix();
+ this.dirty = true;
+ }
+
+ start(): void {
+ if (this.frameId) return;
+ this.resize();
+ this.lastTime = performance.now();
+ const tick = (now: number) => {
+ this.frameId = requestAnimationFrame(tick);
+ this.frame(now);
+ };
+ this.frameId = requestAnimationFrame(tick);
+ }
+
+ stop(): void {
+ cancelAnimationFrame(this.frameId);
+ this.frameId = 0;
+ }
+
+ /**
+ * One animation frame. The scene is drawn only when something changed:
+ * the camera, a transition, hover, or one of Archify's animations. An idle
+ * diagram costs no GPU time.
+ */
+ private frame(now: number): void {
+ const dt = Math.min(0.1, (now - this.lastTime) / 1000);
+ this.lastTime = now;
+ let draw = this.dirty;
+ this.dirty = false;
+
+ if (this.levelMix !== this.levelTarget) {
+ const step = dt / 0.7;
+ this.levelMix = this.levelTarget > this.levelMix ? Math.min(1, this.levelMix + step) : Math.max(0, this.levelMix - step);
+ this.layout();
+ draw = true;
+ }
+ for (const view of this.nodes.values()) {
+ const goal = view.shape.id === this.hovered ? 4 : 0;
+ if (Math.abs(view.lift - goal) > 0.01) {
+ view.lift += (goal - view.lift) * Math.min(1, dt * 14);
+ view.group.position.y = this.levelY(view.shape.id) + view.lift + view.pulse;
+ draw = true;
+ }
+ }
+
+ if (this.flight) {
+ const t = Math.min(1, (now - this.flight.start) / FLY_MS);
+ const k = 1 - Math.pow(1 - t, 3);
+ this.camera.position.lerpVectors(this.flight.from, this.flight.to, k);
+ this.controls.target.lerpVectors(this.flight.fromTarget, this.flight.toTarget, k);
+ draw = true;
+ if (t === 1) {
+ this.flight = undefined;
+ this.onCameraChange();
+ }
+ }
+
+ if (this.syncMotion()) draw = true;
+ // update() returns true while the camera moves (including damping).
+ if (this.controls.update()) draw = true;
+ if (!draw) return;
+
+ for (const view of this.labels) {
+ if (view.mesh.userData.billboard) view.mesh.quaternion.copy(this.camera.quaternion);
+ }
+ this.renderer.render(this.scene, this.camera);
+ }
+
+ /** PNG of the current view. */
+ snapshot(): string {
+ this.renderer.render(this.scene, this.camera);
+ return this.renderer.domElement.toDataURL('image/png');
+ }
+
+ dispose(): void {
+ this.stop();
+ disposeObject(this.world);
+ for (const t of this.textures) t.dispose();
+ this.controls.dispose();
+ this.renderer.dispose();
+ this.element.remove();
+ }
+}
diff --git a/src/viewer3d/style.ts b/src/viewer3d/style.ts
new file mode 100644
index 0000000..aebf40b
--- /dev/null
+++ b/src/viewer3d/style.ts
@@ -0,0 +1,45 @@
+/** Styles for the 3D mode; they reuse Archify's tokens so every preset fits. */
+export const STYLE = `
+.diagram-container { position: relative; }
+/* The 2D SVG stays in the page (its styles and animations drive the 3D
+ view) but is not painted while 3D is on. */
+html.archify-3d-on .diagram-container > svg { visibility: hidden !important; pointer-events: none !important; }
+html.archify-3d-on .diagram-container { min-height: max(420px, 62vh); }
+.archify-3d-stage { position: absolute; inset: 0; z-index: 1; border-radius: inherit; overflow: hidden; }
+.archify-3d-stage canvas { display: block; touch-action: none; cursor: grab; }
+.archify-3d-stage canvas:active { cursor: grabbing; }
+html.archify-3d-on .diagram-container > :not(svg):not(.archify-3d-stage) { z-index: 2; }
+
+/* The 3D button is Export's twin: same pill, same type, same menu. */
+.toolbar #btn-3d { padding-right: 0.95rem; padding-left: 1rem; color: var(--bg); font-weight: 550; }
+.toolbar #btn-3d::before { inset: 0.25rem 0; border-radius: 0.6875rem; background: var(--text);
+ box-shadow: 0 1px 2px rgba(15, 23, 42, 0.12), 0 6px 16px -8px rgba(15, 23, 42, 0.4); }
+.toolbar #btn-3d:hover,
+.toolbar #btn-3d[aria-expanded="true"] { color: var(--bg); }
+.toolbar #btn-3d:hover::before,
+.toolbar #btn-3d[aria-expanded="true"]::before { background: color-mix(in srgb, var(--text) 86%, var(--bg)); }
+/* While the 3D view is on, the pill wears a cyan ring. */
+.toolbar #btn-3d[data-active]::before { box-shadow: 0 0 0 2px var(--frontend-stroke), 0 6px 16px -8px rgba(15, 23, 42, 0.4); }
+.toolbar .archify-3d-wrap .archify-3d-menu { right: 0; }
+.toolbar .export-menu button[data-archify3d-export]::before { -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3E%3Cg fill='none' stroke='black' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M10 2.5l7 4v7l-7 4-7-4v-7z'/%3E%3Cpath d='M3 6.5l7 4 7-4M10 10.5v7'/%3E%3C/g%3E%3C/svg%3E"); mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3E%3Cg fill='none' stroke='black' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M10 2.5l7 4v7l-7 4-7-4v-7z'/%3E%3Cpath d='M3 6.5l7 4 7-4M10 10.5v7'/%3E%3C/g%3E%3C/svg%3E"); }
+
+/* Menu rows: Archify's .preset-option layout, with an icon swatch. */
+.toolbar .archify-3d-menu { width: 18.5rem; }
+.toolbar .archify-3d-menu .preset-menu-heading { padding-top: 0.6rem; }
+.toolbar .archify-3d-menu .preset-menu-heading:first-child { padding-top: 0.45rem; }
+.archify-3d-swatch { display: grid; place-items: center; width: 2.375rem; height: 1.75rem; border-radius: 0.4375rem; color: var(--text-muted);
+ background: color-mix(in srgb, var(--text) 5%, transparent); box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--text) 14%, transparent);
+ transition: box-shadow 0.14s ease, color 0.14s ease; }
+.toolbar .archify-3d-option[aria-checked="true"] .archify-3d-swatch { color: var(--frontend-stroke); box-shadow: 0 0 0 2px var(--toolbar-menu-bg), 0 0 0 3.5px var(--frontend-stroke); }
+.archify-3d-swatch-icon { width: 1.05rem; height: 1.05rem; background: currentColor; -webkit-mask: center / contain no-repeat; mask: center / contain no-repeat; }
+.archify-3d-i-2d { -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3E%3Cg fill='none' stroke='black' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='3' y='4' width='14' height='12' rx='1.5'/%3E%3Cpath d='M6 8h3M6 11h5M12.5 8h1.5'/%3E%3C/g%3E%3C/svg%3E"); mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3E%3Cg fill='none' stroke='black' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='3' y='4' width='14' height='12' rx='1.5'/%3E%3Cpath d='M6 8h3M6 11h5M12.5 8h1.5'/%3E%3C/g%3E%3C/svg%3E"); }
+.archify-3d-i-3d { -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3E%3Cg fill='none' stroke='black' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M10 2.5l7 4v7l-7 4-7-4v-7z'/%3E%3Cpath d='M3 6.5l7 4 7-4M10 10.5v7'/%3E%3C/g%3E%3C/svg%3E"); mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3E%3Cg fill='none' stroke='black' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M10 2.5l7 4v7l-7 4-7-4v-7z'/%3E%3Cpath d='M3 6.5l7 4 7-4M10 10.5v7'/%3E%3C/g%3E%3C/svg%3E"); }
+.archify-3d-i-flat { -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3E%3Cg fill='none' stroke='black' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M10 6 17.5 9.8 10 13.6 2.5 9.8z'/%3E%3C/g%3E%3C/svg%3E"); mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3E%3Cg fill='none' stroke='black' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M10 6 17.5 9.8 10 13.6 2.5 9.8z'/%3E%3C/g%3E%3C/svg%3E"); }
+.archify-3d-i-stacked { -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3E%3Cg fill='none' stroke='black' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M10 2.5 17.5 6.3 10 10 2.5 6.3z'/%3E%3Cpath d='m2.5 10 7.5 3.8 7.5-3.8M2.5 13.7 10 17.5l7.5-3.8'/%3E%3C/g%3E%3C/svg%3E"); mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3E%3Cg fill='none' stroke='black' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M10 2.5 17.5 6.3 10 10 2.5 6.3z'/%3E%3Cpath d='m2.5 10 7.5 3.8 7.5-3.8M2.5 13.7 10 17.5l7.5-3.8'/%3E%3C/g%3E%3C/svg%3E"); }
+.archify-3d-i-reset { -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3E%3Cg fill='none' stroke='black' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M3.5 10a6.5 6.5 0 1 0 2-4.7'/%3E%3Cpath d='M3.5 3.5v3.5H7'/%3E%3C/g%3E%3C/svg%3E"); mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3E%3Cg fill='none' stroke='black' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M3.5 10a6.5 6.5 0 1 0 2-4.7'/%3E%3Cpath d='M3.5 3.5v3.5H7'/%3E%3C/g%3E%3C/svg%3E"); }
+.archify-3d-i-top { -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3E%3Cg fill='none' stroke='black' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M10 2.5v9M6.5 8l3.5 3.5L13.5 8'/%3E%3Cpath d='M3 14.5h14M5 17.5h10'/%3E%3C/g%3E%3C/svg%3E"); mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3E%3Cg fill='none' stroke='black' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M10 2.5v9M6.5 8l3.5 3.5L13.5 8'/%3E%3Cpath d='M3 14.5h14M5 17.5h10'/%3E%3C/g%3E%3C/svg%3E"); }
+.toolbar .archify-3d-option[aria-disabled="true"] { opacity: 0.42; cursor: default; }
+.toolbar .archify-3d-option[aria-disabled="true"]:hover { background: transparent; }
+.archify-3d-kbd { justify-self: end; min-width: 1rem; color: var(--text-faint); font: inherit; font-size: 0.6875rem; text-align: center; }
+.archify-3d-kbd:empty { visibility: hidden; }
+`;
diff --git a/src/viewer3d/svgModel.ts b/src/viewer3d/svgModel.ts
new file mode 100644
index 0000000..a61b42b
--- /dev/null
+++ b/src/viewer3d/svgModel.ts
@@ -0,0 +1,181 @@
+/**
+ * Reads the semantic parts of a rendered Archify SVG: nodes, routed
+ * relationships, their labels and structural frames. Archify marks them
+ * with the same data attributes in all five diagram types, so the 3D view
+ * needs no per-type code.
+ */
+
+export interface Box {
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+}
+
+export interface NodeShape extends Box {
+ id: string;
+ kind: string;
+ rx: number;
+ el: SVGGElement;
+}
+
+export interface EdgeShape {
+ key: string;
+ from: string;
+ to: string;
+ path: SVGPathElement;
+ /** Points along the route, every SAMPLE_STEP user units. */
+ points: [number, number][];
+ length: number;
+ animated: boolean;
+}
+
+export interface LabelShape extends Box {
+ key: string;
+ el: SVGGElement;
+}
+
+export interface FrameShape extends Box {
+ kind: string;
+ rx: number;
+ el: SVGRectElement;
+}
+
+export interface DiagramModel {
+ svg: SVGSVGElement;
+ viewBox: Box;
+ nodes: NodeShape[];
+ edges: EdgeShape[];
+ labels: LabelShape[];
+ frames: FrameShape[];
+}
+
+const SAMPLE_STEP = 3;
+
+/** Role of an element for the 3D view; descendants share their ancestor's role. */
+export type Role = 'node' | 'edge' | 'label' | 'floor' | 'overlay';
+
+/**
+ * Archify's temporary viewer layers (focus pulse, intent trace, route probe,
+ * journey, lens, story) are marked data-…-overlay. They are animated in 3D
+ * from the live SVG and never baked into the textures.
+ */
+function isOverlay(el: Element): boolean {
+ for (const name of el.getAttributeNames()) if (name.startsWith('data-') && name.endsWith('-overlay')) return true;
+ return false;
+}
+
+/** Flow paths inside those overlays: clones of a relationship path with pathLength="1". */
+export const FLOW_SELECTOR = [
+ 'relationship-pulse',
+ 'intent-trace',
+ 'route-probe',
+ 'route-journey',
+ 'semantic-lens',
+ 'story',
+ 'story-carrier',
+ 'chapter-handoff',
+].map((name) => `[data-${name}-overlay] path[pathLength]`).join(', ');
+
+export function roleOf(el: Element): Role | undefined {
+ if (isOverlay(el)) return 'overlay';
+ if (el.hasAttribute('data-node-id')) return 'node';
+ if (el.getAttribute('data-graph-role') === 'automatic-crossover') return 'edge';
+ if (el.tagName === 'path' && el.hasAttribute('data-edge-from')) return 'edge';
+ if (el.getAttribute('data-graph-role') === 'automatic-crossover-underlay') return 'edge';
+ if (el.tagName === 'g' && el.hasAttribute('data-edge-key') && el.querySelector('text')) return 'label';
+ return undefined;
+}
+
+function num(el: Element, name: string): number {
+ return Number(el.getAttribute(name) ?? 0) || 0;
+}
+
+function rectBox(rect: SVGRectElement): Box & { rx: number } {
+ return { x: num(rect, 'x'), y: num(rect, 'y'), w: num(rect, 'width'), h: num(rect, 'height'), rx: num(rect, 'rx') };
+}
+
+function nodeShape(el: SVGGElement): NodeShape | undefined {
+ const id = el.getAttribute('data-node-id');
+ if (!id) return undefined;
+ const kind = el.getAttribute('data-node-kind') ?? 'backend';
+ // The node body is the semantic rect (c-); c-mask sits under it.
+ const rect =
+ el.querySelector(`:scope > rect.c-${CSS.escape(kind)}`) ??
+ el.querySelector(':scope > rect:not(.c-mask)') ??
+ el.querySelector(':scope > rect');
+ if (rect) return { id, kind, el, ...rectBox(rect) };
+ const bbox = el.getBBox();
+ return { id, kind, el, x: bbox.x, y: bbox.y, w: bbox.width, h: bbox.height, rx: 0 };
+}
+
+function samplePath(path: SVGPathElement): { points: [number, number][]; length: number } {
+ const length = path.getTotalLength();
+ const steps = Math.max(2, Math.ceil(length / SAMPLE_STEP));
+ const points: [number, number][] = [];
+ for (let i = 0; i <= steps; i++) {
+ const p = path.getPointAtLength((length * i) / steps);
+ points.push([p.x, p.y]);
+ }
+ return { points, length };
+}
+
+export function readModel(svg: SVGSVGElement): DiagramModel {
+ const vb = svg.viewBox.baseVal;
+ const viewBox = vb && vb.width > 0 ? { x: vb.x, y: vb.y, w: vb.width, h: vb.height } : { x: 0, y: 0, w: svg.clientWidth, h: svg.clientHeight };
+
+ const nodes = [...svg.querySelectorAll('g[data-node-id]')]
+ .map(nodeShape)
+ .filter((n): n is NodeShape => !!n && n.w > 0 && n.h > 0);
+
+ const edges: EdgeShape[] = [];
+ svg.querySelectorAll('path[data-edge-from]:not([data-graph-role])').forEach((path, index) => {
+ const from = path.getAttribute('data-edge-from') ?? '';
+ const to = path.getAttribute('data-edge-to') ?? '';
+ const group = path.parentElement;
+ const { points, length } = samplePath(path);
+ if (length <= 0) return;
+ edges.push({
+ key: path.getAttribute('data-edge-key') ?? `e${index}`,
+ from,
+ to,
+ path,
+ points,
+ length,
+ animated: path.hasAttribute('data-animate') || !!group?.hasAttribute('data-animate'),
+ });
+ });
+
+ const labels: LabelShape[] = [];
+ svg.querySelectorAll('g[data-edge-key]').forEach((el) => {
+ if (roleOf(el) !== 'label') return;
+ const rect = el.querySelector(':scope > rect');
+ const box = rect ? rectBox(rect) : (() => {
+ const b = el.getBBox();
+ return { x: b.x, y: b.y, w: b.width, h: b.height, rx: 0 };
+ })();
+ if (box.w > 0 && box.h > 0) labels.push({ key: el.getAttribute('data-edge-key') ?? '', el, ...box });
+ });
+
+ const frames = [...svg.querySelectorAll('rect[data-graph-role="structural-frame"]')].map((el) => ({
+ kind: el.getAttribute('data-composition-frame-kind') ?? 'region',
+ el,
+ ...rectBox(el),
+ }));
+
+ return { svg, viewBox, nodes, edges, labels, frames };
+}
+
+/**
+ * Opacity of an element including its ancestors below the SVG root. The
+ * root is left out: the 3D view hides the 2D SVG by fading the root.
+ */
+export function effectiveOpacity(el: Element, root: Element): number {
+ let value = 1;
+ for (let cur: Element | null = el; cur && cur !== root; cur = cur.parentElement) {
+ const style = getComputedStyle(cur);
+ if (style.display === 'none') return 0;
+ value *= Number(style.opacity || 1);
+ }
+ return value;
+}
diff --git a/src/preview.ts b/src/views/diagramView.ts
similarity index 92%
rename from src/preview.ts
rename to src/views/diagramView.ts
index 45f68c6..68a9e33 100644
--- a/src/preview.ts
+++ b/src/views/diagramView.ts
@@ -1,10 +1,14 @@
import path from 'node:path';
import * as vscode from 'vscode';
-import { isArchifyFile, readDiagramSource } from './detect';
-import { renderDiagram } from './renderer';
-import { evidenceMode, log, readText, runtimeFor, viewerTheme } from './runtime';
-import { handleWebviewMessage, WebviewMessage } from './webviewMessages';
-import { makeNonce, messagePage, prepareDiagramHtml } from './webviewHtml';
+import { renderDiagram } from '../archify/cli';
+import { evidenceMode, runtimeFor } from '../archify/runtime';
+import { isArchifyFile, readDiagramSource } from '../sources/detect';
+import { readText } from '../util/files';
+import { log } from '../util/log';
+import { viewerTheme } from '../util/settings';
+import { handleWebviewMessage, WebviewMessage } from '../webview/messages';
+import { makeNonce, messagePage, prepareDiagramHtml } from '../webview/page';
+import { viewer3dOption, viewerRoots } from '../webview/viewer3d';
export const PREVIEW_VIEW_TYPE = 'archify.preview';
/** Default editor for .archify files: the rendered diagram. */
@@ -34,7 +38,7 @@ class DiagramPreview implements vscode.Disposable {
readonly isEditor = false,
) {
this.hash = state?.hash;
- panel.webview.options = { enableScripts: true, localResourceRoots: [] };
+ panel.webview.options = { enableScripts: true, localResourceRoots: viewerRoots(this.context.extensionUri) };
if (!isEditor) {
panel.iconPath = vscode.Uri.joinPath(context.extensionUri, 'media', 'preview.svg');
panel.title = `Preview ${path.basename(uri.path)}`;
@@ -134,6 +138,7 @@ class DiagramPreview implements vscode.Disposable {
hash: this.hash,
state: this.state(),
notice: result.evidenceNotice ? { kind: 'warning', text: result.evidenceNotice } : undefined,
+ viewer3d: viewer3dOption(this.panel.webview, this.context.extensionUri),
});
// Nonces differ per render, so compare the renderer output instead.
const fingerprint = `${viewerTheme()}\u0000${result.evidenceNotice ?? ''}\u0000${result.html}`;
@@ -158,7 +163,7 @@ function firstLines(text: string | undefined, count = 6): string {
return (text ?? '').split('\n').slice(0, count).join('\n');
}
-export class PreviewManager
+export class DiagramViewManager
implements vscode.Disposable, vscode.WebviewPanelSerializer, vscode.CustomTextEditorProvider
{
/** Side previews, one per source file. */
@@ -204,7 +209,7 @@ export class PreviewManager
/** Opening a .archify file lands here: the diagram is the editor. */
async resolveCustomTextEditor(document: vscode.TextDocument, panel: vscode.WebviewPanel): Promise {
- panel.webview.options = { enableScripts: true, localResourceRoots: [] };
+ panel.webview.options = { enableScripts: true, localResourceRoots: viewerRoots(this.context.extensionUri) };
this.track(new DiagramPreview(this.context, panel, document.uri, undefined, true));
}
@@ -218,7 +223,7 @@ export class PreviewManager
PREVIEW_VIEW_TYPE,
`Preview ${path.basename(uri.path)}`,
{ viewColumn, preserveFocus },
- { enableScripts: true, retainContextWhenHidden: true, enableFindWidget: true, localResourceRoots: [] },
+ { enableScripts: true, retainContextWhenHidden: true, enableFindWidget: true, localResourceRoots: viewerRoots(this.context.extensionUri) },
);
this.track(new DiagramPreview(this.context, panel, uri));
}
diff --git a/src/htmlViewer.ts b/src/views/htmlViewer.ts
similarity index 88%
rename from src/htmlViewer.ts
rename to src/views/htmlViewer.ts
index 117f87c..739665b 100644
--- a/src/htmlViewer.ts
+++ b/src/views/htmlViewer.ts
@@ -1,9 +1,10 @@
import path from 'node:path';
import * as vscode from 'vscode';
-import { isArchifyHtml } from './detect';
-import { viewerTheme } from './runtime';
-import { handleWebviewMessage, WebviewMessage } from './webviewMessages';
-import { makeNonce, messagePage, prepareDiagramHtml } from './webviewHtml';
+import { isArchifyHtml } from '../sources/detect';
+import { viewerTheme } from '../util/settings';
+import { handleWebviewMessage, WebviewMessage } from '../webview/messages';
+import { makeNonce, messagePage, prepareDiagramHtml } from '../webview/page';
+import { viewer3dOption, viewerRoots } from '../webview/viewer3d';
export const HTML_VIEW_TYPE = 'archify.htmlViewer';
@@ -18,7 +19,7 @@ export class HtmlViewerProvider implements vscode.CustomReadonlyEditorProvider {
const uri = document.uri;
let hash: string | undefined;
- panel.webview.options = { enableScripts: true, localResourceRoots: [] };
+ panel.webview.options = { enableScripts: true, localResourceRoots: viewerRoots(this.extensionUri) };
const reload = async () => {
let text: string;
@@ -70,6 +71,7 @@ export class HtmlViewerProvider implements vscode.CustomReadonlyEditorProvider]*\bnonce=)/gi, `\n`;
+ page = /<\/head>/i.test(page) ? page.replace(/<\/head>/i, `${tag}`) : `${tag}${page}`;
+ }
+
const headMatch = /]*>/i.exec(page);
if (headMatch) {
const at = headMatch.index + headMatch[0].length;
diff --git a/src/webview/viewer3d.ts b/src/webview/viewer3d.ts
new file mode 100644
index 0000000..201de7b
--- /dev/null
+++ b/src/webview/viewer3d.ts
@@ -0,0 +1,15 @@
+import * as vscode from 'vscode';
+
+/** Folder of the bundled webview scripts; webviews may load files from it. */
+export function viewerRoots(extensionUri: vscode.Uri): vscode.Uri[] {
+ return [vscode.Uri.joinPath(extensionUri, 'dist')];
+}
+
+/** Page option that adds the 3D viewer to an Archify page. */
+export function viewer3dOption(webview: vscode.Webview, extensionUri: vscode.Uri): { scriptUri: string; defaultView: '2d' | '3d' } {
+ const defaultView = vscode.workspace.getConfiguration('archify').get('defaultView', '2d') === '3d' ? '3d' : '2d';
+ return {
+ scriptUri: webview.asWebviewUri(vscode.Uri.joinPath(extensionUri, 'dist', 'viewer3d.js')).toString(),
+ defaultView,
+ };
+}
diff --git a/test/brands.test.ts b/test/brands.test.ts
index ac19170..ecb5896 100644
--- a/test/brands.test.ts
+++ b/test/brands.test.ts
@@ -1,8 +1,8 @@
import assert from 'node:assert/strict';
import path from 'node:path';
import { test } from 'node:test';
-import { brandValueAt, loadBrandCatalog } from '../src/brands';
-import { diagnosticPointer } from '../src/jsonPointer';
+import { brandValueAt, loadBrandCatalog } from '../src/language/brands';
+import { diagnosticPointer } from '../src/language/jsonPointer';
const root = path.resolve(__dirname, '..', '..');
const catalogFile = path.join(root, 'vendor', 'archify', 'brand-marks', 'catalog.json');
diff --git a/test/detect.test.ts b/test/detect.test.ts
index fd66f45..a0923ff 100644
--- a/test/detect.test.ts
+++ b/test/detect.test.ts
@@ -1,7 +1,8 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
-import { hasSourceEvidence, isArchifyHtml, readDiagramSource, stripSourceEvidence, typeFromFilename } from '../src/detect';
-import { pointerSegments, rangeForPointer, rangeForPointerYaml, yamlSyntaxProblems } from '../src/jsonPointer';
+import { pointerSegments, rangeForPointer, rangeForPointerYaml, yamlSyntaxProblems } from '../src/language/jsonPointer';
+import { isArchifyHtml, readDiagramSource, typeFromFilename } from '../src/sources/detect';
+import { hasSourceEvidence, stripSourceEvidence } from '../src/sources/evidence';
test('reads diagram_type from content', () => {
const source = readDiagramSource('{"schema_version":1,"diagram_type":"sequence","meta":{}}', 'plain.json');
@@ -49,7 +50,7 @@ test('json pointer ranges point at keys for containers and values for leaves', (
});
test('.archify files are diagram sources typed by their content', async () => {
- const { diagramBaseName, isArchifyFile, isDiagramFileName } = await import('../src/detect');
+ const { diagramBaseName, isArchifyFile, isDiagramFileName } = await import('../src/sources/detect');
assert.ok(isArchifyFile('/w/My Platform.archify'));
assert.ok(isDiagramFileName('/w/x.ARCHIFY'));
assert.ok(isDiagramFileName('/w/x.workflow.json'));
diff --git a/test/webviewHtml.test.ts b/test/page.test.ts
similarity index 51%
rename from test/webviewHtml.test.ts
rename to test/page.test.ts
index afcbec7..693bf03 100644
--- a/test/webviewHtml.test.ts
+++ b/test/page.test.ts
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
-import { prepareDiagramHtml } from '../src/webviewHtml';
+import { prepareDiagramHtml } from '../src/webview/page';
const page = `
@@ -12,7 +12,7 @@ test('adds one CSP and nonces every inline script', () => {
const html = prepareDiagramHtml(page, { cspSource: 'vscode-resource:', nonce: 'N0NCE', theme: 'light' });
const csps = html.match(/Content-Security-Policy/g) ?? [];
assert.equal(csps.length, 1);
- assert.match(html, /script-src ('|')nonce-N0NCE/);
+ assert.match(html, /script-src vscode-resource: ('|')nonce-N0NCE/);
const scripts = html.match(/