100+ AI Agents, Agent Skills and RAG Apps - Free and Open Source.
feat: add Excaliflow hand-drawn diagramming and animated flow app
ci6e81043a0346
diff --git a/README.md b/README.mdindex e8b91511..2d7e13a7 100644--- a/README.md+++ b/README.md@@ -203,6 +203,7 @@ streamlit run travel_agent.py* [✈️ MCP Apps Generative UI Showcase](generative_ui_agents/mcp-apps-generative-ui-showcase/) - MCP apps that render real interactive UI, flight search included* [🎛️ AI Shadcn Component Generator](generative_ui_agents/ai-shadcn-component-generator/) - Chat your way to production-ready shadcn components* [🔍 AI Deep Research Agent](generative_ui_agents/ai-deep-research-agent/) - Research where every tool call renders as a live workspace card+* [✏️ Excaliflow](generative_ui_agents/excaliflow/) - Hand-drawn system diagrams with live animated flows and video export### 🎮 Autonomous Game-Playing Agentsdiff --git a/generative_ui_agents/excaliflow/.gitignore b/generative_ui_agents/excaliflow/.gitignorenew file mode 100644index 00000000..8b56f7f1--- /dev/null+++ b/generative_ui_agents/excaliflow/.gitignore@@ -0,0 +1,4 @@+node_modules/+.DS_Store+*.log+.envdiff --git a/generative_ui_agents/excaliflow/README.md b/generative_ui_agents/excaliflow/README.mdnew file mode 100644index 00000000..298c44a7--- /dev/null+++ b/generative_ui_agents/excaliflow/README.md@@ -0,0 +1,68 @@+# Excaliflow++**Hand-drawn diagrams with live animated flows.** Sketch out AI agents, RAG pipelines, or system architectures just like in Excalidraw, and watch data flow through your arrows in real time. Connect shapes, customize colors and sketch styles, and export a crisp 2x PNG or a 60fps video loop. Runs in a single HTML file with zero dependencies.++## Features++- **Hand-drawn look and feel.** Draw boxes, circles, decision diamonds, freehand sketches, and sticky notes using Excalidraw's hand-drawn fonts (`Excalifont`, `Virgil`, `Cascadia`) and sketch fills.+- **Live animated arrows.** Connect any two shapes and watch comets, pulses, neon streaks, or dashed streams travel along your arrows in order from start to finish.+- **Easy arrow editing.** Drag any arrow endpoint around the edge of a shape, pull the middle of an arrow to curve it, or double-click an arrow to straighten it.+- **Fast diagram building.** Press `Tab` or click a `+` port on any selected shape to add and connect the next step automatically, or drop a shape onto an existing arrow to split it in two.+- **Ready-made starter templates.** Load built-in diagrams for **AI Agent Swarm**, **RAG Pipeline**, **How Browsers Work**, and **Microservices** in one click.+- **Light & dark canvas + instant export.** Switch between a clean white canvas and a pitch-black neon canvas, then export a cropped 2x PNG, copy to clipboard, record a `.webm` video loop, or save and load `.excaliflow` / `.excalidraw` JSON files.++## How to Get Started++Requires **Node.js 18+** (or open `index.html` directly in any modern browser). Excaliflow has no external npm dependencies, so no install step is needed.++```sh+git clone https://github.com/Shubhamsaboo/awesome-llm-apps.git+cd awesome-llm-apps/generative_ui_agents/excaliflow+npm start+```++Open **http://localhost:3000** in your browser.++## Keyboard Shortcuts++| Shortcut | Action |+| --- | --- |+| `V` or `1` | Select, move, resize shapes, or bend arrows |+| `H` or `Space + Drag` | Pan around the canvas |+| `R` or `2` | Rectangle |+| `D` or `3` | Diamond / Decision |+| `O` or `4` | Circle / Ellipse |+| `A` or `5` | Animated Arrow |+| `P` or `7` | Freehand Pen |+| `T` or `8` | Text |+| `N` or `9` | Sticky Note |+| `K` | Laser Pointer |+| `E` or `0` | Eraser |+| `Q` | Keep selected tool active (Tool Lock) |+| `Tab` | Add and connect the next shape |+| `Double-click` | Add a node on empty canvas, edit text, or straighten an arrow |+| `Alt / Option + Drag` | Duplicate selection while dragging |+| `⌘Z` / `⇧⌘Z` | Undo / Redo |+| `⌘D` | Duplicate selection |+| `⌘\` | Show or hide the left style panel |++## Project Structure++```text+excaliflow/+|-- index.html Complete single-file app (UI, sketch renderer, and animation loop)+|-- server.js Zero-dependency local static server (http://localhost:3000)+|-- verify.js Automated test suite for geometry, arrows, and interactions+|-- package.json Start and test scripts+`-- README.md+```++## Development++Run the automated verification checks:++```sh+npm test+```++Licensed under the repository's [Apache-2.0 license](../../LICENSE).diff --git a/generative_ui_agents/excaliflow/index.html b/generative_ui_agents/excaliflow/index.htmlnew file mode 100644index 00000000..05b2d470--- /dev/null+++ b/generative_ui_agents/excaliflow/index.html@@ -0,0 +1,4623 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />+ <title>Excaliflow — Hand-Drawn Diagramming & Live Causal Flow</title>+ <link rel="preconnect" href="https://fonts.googleapis.com" />+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />+ <link href="https://fonts.googleapis.com/css2?family=Assistant:wght@400;500;600;700&family=Architects+Daughter&family=Caveat:wght@500;700&family=Geist+Mono:wght@400;500;600&family=Geist:wght@400;500;600;700&family=Inter:wght@400;500;600;700&family=Nunito:wght@400;500;600;700&family=Patrick+Hand&display=swap" rel="stylesheet" />+ <style>+ /* Official Excalidraw Web Fonts (Excalifont, Virgil, Cascadia) */+ @font-face {+ font-family: 'Excalifont';+ src: url('https://esm.sh/@excalidraw/[email protected]/dist/prod/fonts/Excalifont/Excalifont-Regular-a88b72a24fb54c9f94e3b5fdaa7481c9.woff2') format('woff2');+ font-weight: 400;+ font-style: normal;+ font-display: swap;+ }+ @font-face {+ font-family: 'Virgil';+ src: url('https://unpkg.com/@excalidraw/[email protected]/dist/excalidraw-assets/Virgil.woff2') format('woff2');+ font-weight: 400;+ font-style: normal;+ font-display: swap;+ }+ @font-face {+ font-family: 'Cascadia';+ src: url('https://unpkg.com/@excalidraw/[email protected]/dist/excalidraw-assets/Cascadia.woff2') format('woff2');+ font-weight: 400;+ font-style: normal;+ font-display: swap;+ }++ :root {+ --bg-canvas: #ffffff;+ --panel-bg: rgba(255, 255, 255, 0.94);+ --panel-border: rgba(15, 23, 42, 0.09);+ --panel-shadow: 0 4px 20px -2px rgba(15, 23, 42, 0.08), 0 1px 3px rgba(15, 23, 42, 0.05);+ --text-primary: #1b1b1f;+ --text-secondary: #495057;+ --text-muted: #868e96;+ --surface-hover: #f1f0ff;+ --surface-subtle: #f8f9fa;+ --surface-active: #e0dfff;+ --accent: #6965db;+ --accent-strong: #5753d0;+ --selection-blue: #6965db;+ --danger: #e03131;+ --emerald: #10b981;+ --divider: rgba(15, 23, 42, 0.08);+ --font-sans: 'Assistant', 'Nunito', 'Geist', 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;+ --font-mono: 'Cascadia', 'Geist Mono', monospace;+ --font-hand: 'Excalifont', 'Virgil', 'Patrick Hand', 'Architects Daughter', 'Caveat', cursive;+ }++ body.dark-canvas {+ --bg-canvas: #000000;+ --panel-bg: rgba(22, 22, 27, 0.92);+ --panel-border: rgba(255, 255, 255, 0.11);+ --panel-shadow: 0 8px 28px -4px rgba(0, 0, 0, 0.8), 0 0 0 1px rgba(255, 255, 255, 0.06);+ --text-primary: #f1f5f9;+ --text-secondary: #cbd5e1;+ --text-muted: #64748b;+ --surface-hover: rgba(165, 162, 255, 0.12);+ --surface-subtle: rgba(255, 255, 255, 0.05);+ --surface-active: rgba(105, 101, 219, 0.28);+ --accent: #a5a2ff;+ --accent-strong: #8b87ff;+ --selection-blue: #8b87ff;+ --divider: rgba(255, 255, 255, 0.09);+ }++ * {+ box-sizing: border-box;+ margin: 0;+ padding: 0;+ user-select: none;+ -webkit-user-select: none;+ }++ html, body {+ width: 100%;+ height: 100%;+ overflow: hidden;+ background-color: var(--bg-canvas);+ font-family: var(--font-sans);+ color: var(--text-primary);+ -webkit-font-smoothing: antialiased;+ }++ /* Dual-Layer Retina Canvas Pipeline */+ #canvasStage {+ position: fixed;+ inset: 0;+ width: 100vw;+ height: 100vh;+ overflow: hidden;+ background-color: var(--bg-canvas);+ transition: background-color 0.16s ease;+ }++ #staticCanvas,+ #interactiveCanvas {+ position: absolute;+ top: 0;+ left: 0;+ width: 100%;+ height: 100%;+ display: block;+ }++ #staticCanvas {+ z-index: 1;+ pointer-events: none;+ }++ #interactiveCanvas {+ z-index: 2;+ touch-action: none;+ cursor: default;+ }++ /* Clean Excaliflow Floating Islands */+ .glass-panel {+ background: var(--panel-bg);+ backdrop-filter: blur(14px) saturate(160%);+ -webkit-backdrop-filter: blur(14px) saturate(160%);+ border: 1px solid var(--panel-border);+ box-shadow: var(--panel-shadow);+ border-radius: 10px;+ color: var(--text-primary);+ }++ /* Top Bar Layout */+ #topHeaderBar {+ position: fixed;+ top: 12px;+ left: 12px;+ right: 12px;+ z-index: 20;+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 10px;+ pointer-events: none;+ }++ .header-group {+ display: flex;+ align-items: center;+ gap: 4px;+ padding: 4px 6px;+ pointer-events: auto;+ }++ .brand-badge {+ display: flex;+ align-items: center;+ gap: 7px;+ padding: 2px 8px 2px 4px;+ font-weight: 700;+ font-size: 14px;+ letter-spacing: -0.02em;+ color: var(--text-primary);+ }++ .brand-icon {+ width: 24px;+ height: 24px;+ border-radius: 6px;+ background: #6965db;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ color: #fff;+ font-family: var(--font-hand);+ font-size: 15px;+ font-weight: 700;+ }++ .v-divider {+ width: 1px;+ height: 20px;+ background: var(--divider);+ margin: 0 3px;+ }++ .ui-btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: 5px;+ height: 32px;+ padding: 0 10px;+ border: 1px solid transparent;+ border-radius: 7px;+ background: transparent;+ color: var(--text-secondary);+ font-family: var(--font-sans);+ font-size: 12px;+ font-weight: 500;+ cursor: pointer;+ transition: background 0.12s ease, color 0.12s ease, transform 0.08s ease;+ white-space: nowrap;+ }++ .ui-btn:hover {+ background: var(--surface-hover);+ color: var(--text-primary);+ }++ .ui-btn:active {+ transform: scale(0.97);+ }++ .ui-btn:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 1px;+ }++ .ui-btn.active {+ background: var(--surface-active);+ color: var(--accent);+ font-weight: 600;+ }++ .ui-btn.primary {+ background: #6965db;+ color: #ffffff;+ font-weight: 600;+ }++ .ui-btn.primary:hover {+ background: #5753d0;+ color: #ffffff;+ }++ .ui-btn:disabled {+ opacity: 0.35;+ pointer-events: none;+ }++ .ui-btn.danger:hover {+ background: rgba(224, 49, 49, 0.12);+ color: var(--danger);+ }++ /* Excaliflow Top-Center Iconic Tool Island */+ #bottomToolDock {+ display: flex;+ align-items: center;+ gap: 2px;+ padding: 4px;+ pointer-events: auto;+ }++ .dock-tool-btn {+ position: relative;+ width: 36px;+ height: 36px;+ border: 1px solid transparent;+ border-radius: 8px;+ background: transparent;+ color: var(--text-secondary);+ cursor: pointer;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ transition: background 0.12s ease, color 0.12s ease, transform 0.08s ease;+ }++ .dock-tool-btn svg {+ width: 17px;+ height: 17px;+ stroke: currentColor;+ stroke-width: 1.85;+ fill: none;+ stroke-linecap: round;+ stroke-linejoin: round;+ }++ .dock-tool-btn:hover {+ background: var(--surface-hover);+ color: var(--text-primary);+ }++ .dock-tool-btn:active {+ transform: scale(0.94);+ }++ .dock-tool-btn.active {+ background: var(--surface-active);+ color: var(--accent);+ }++ .dock-key {+ position: absolute;+ bottom: 2px;+ right: 3.5px;+ font-family: var(--font-sans);+ font-size: 8.5px;+ font-weight: 600;+ opacity: 0.58;+ line-height: 1;+ pointer-events: none;+ }++ /* Master Flow Pill */+ #masterFlowPill {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 0 4px;+ }++ .flow-status-dot {+ width: 7px;+ height: 7px;+ border-radius: 50%;+ background: #10b981;+ box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7);+ animation: flowPulseDot 1.8s infinite;+ }++ .flow-status-dot.paused {+ background: #94a3b8;+ box-shadow: none;+ animation: none;+ }++ @keyframes flowPulseDot {+ 0% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.65); }+ 70% { box-shadow: 0 0 0 6px rgba(16, 185, 129, 0); }+ 100% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); }+ }++ .flow-badge-meta {+ font-family: var(--font-mono);+ font-size: 10px;+ font-weight: 600;+ color: var(--accent);+ padding: 2px 6px;+ border-radius: 5px;+ background: var(--surface-active);+ }++ /* Dropdown Popover Menu (Export / Share & Templates) */+ .dropdown-wrap {+ position: relative;+ display: inline-flex;+ }++ .dropdown-menu {+ position: absolute;+ top: calc(100% + 8px);+ right: 0;+ min-width: 196px;+ padding: 6px;+ display: none;+ flex-direction: column;+ gap: 2px;+ z-index: 35;+ }++ .dropdown-menu.align-left {+ right: auto;+ left: 0;+ }++ .dropdown-menu.open {+ display: flex;+ }++ .menu-item {+ width: 100%;+ justify-content: space-between;+ height: 31px;+ padding: 0 10px;+ font-size: 12px;+ border-radius: 6px;+ }++ .menu-sep {+ height: 1px;+ background: var(--divider);+ margin: 4px 2px;+ }++ /* Left Properties Panel (#leftSidebar) - Clean Excaliflow Inspector */+ #leftSidebar {+ position: fixed;+ top: 64px;+ left: 12px;+ max-height: calc(100vh - 132px);+ width: 218px;+ z-index: 18;+ padding: 12px;+ overflow-y: auto;+ display: flex;+ flex-direction: column;+ gap: 12px;+ transition: transform 0.2s cubic-bezier(0.16, 1, 0.3, 1), opacity 0.16s ease;+ }++ #leftSidebar.collapsed {+ transform: translateX(-240px);+ opacity: 0;+ pointer-events: none;+ }++ #leftSidebar::-webkit-scrollbar {+ width: 4px;+ }++ #leftSidebar::-webkit-scrollbar-thumb {+ background: var(--divider);+ border-radius: 4px;+ }++ .sidebar-section {+ display: flex;+ flex-direction: column;+ gap: 5px;+ }++ .section-title {+ font-size: 11px;+ font-weight: 500;+ color: var(--text-secondary);+ display: flex;+ align-items: center;+ justify-content: space-between;+ }++ .grid-2x2 {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 4px;+ }++ .segmented-row {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(34px, 1fr));+ gap: 3px;+ background: var(--surface-subtle);+ padding: 3px;+ border-radius: 8px;+ border: 1px solid var(--divider);+ }++ .seg-btn {+ height: 26px;+ border: none;+ border-radius: 6px;+ background: transparent;+ color: var(--text-secondary);+ font-family: var(--font-sans);+ font-size: 11px;+ font-weight: 500;+ cursor: pointer;+ transition: all 0.12s ease;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: 3px;+ }++ .seg-btn:hover {+ color: var(--text-primary);+ background: var(--surface-hover);+ }++ .seg-btn.active {+ background: var(--surface-active);+ color: var(--accent);+ font-weight: 600;+ }++ /* Color Swatches */+ .swatch-row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 4px;+ padding: 2px 0;+ }++ .color-swatch {+ width: 22px;+ height: 22px;+ border-radius: 6px;+ border: 1.5px solid rgba(0, 0, 0, 0.12);+ cursor: pointer;+ transition: transform 0.12s ease, box-shadow 0.12s ease;+ }++ .color-swatch:hover {+ transform: scale(1.1);+ }++ .color-swatch.active {+ box-shadow: 0 0 0 2px var(--bg-canvas), 0 0 0 3.5px var(--accent);+ }++ /* Floating Contextual Selection Toolbar (#quickHud) */+ #quickHud {+ position: fixed;+ z-index: 25;+ display: none;+ align-items: center;+ gap: 4px;+ padding: 4px 7px;+ transform: translate(-50%, -100%);+ pointer-events: auto;+ white-space: nowrap;+ }++ #quickHud.visible {+ display: inline-flex;+ }++ .hud-dot {+ width: 16px;+ height: 16px;+ border-radius: 4px;+ border: 1px solid rgba(0, 0, 0, 0.15);+ cursor: pointer;+ transition: transform 0.1s ease;+ }++ .hud-dot:hover,+ .hud-dot.active {+ transform: scale(1.16);+ box-shadow: 0 0 0 2px var(--accent);+ }++ /* Bottom-Left Undo/Redo & Bottom-Right Zoom Pill */+ #bottomLeftBar {+ position: fixed;+ bottom: 14px;+ left: 14px;+ z-index: 20;+ display: flex;+ align-items: center;+ gap: 2px;+ padding: 3px 5px;+ }++ #zoomPill {+ position: fixed;+ bottom: 14px;+ right: 14px;+ z-index: 20;+ display: flex;+ align-items: center;+ gap: 2px;+ padding: 3px 5px;+ }++ /* Subtle Onboarding Hint Pill */+ #canvasHintPill {+ position: fixed;+ bottom: 16px;+ left: 50%;+ transform: translateX(-50%);+ z-index: 15;+ padding: 5px 12px;+ font-size: 11.5px;+ color: var(--text-muted);+ pointer-events: none;+ display: flex;+ align-items: center;+ gap: 10px;+ border-radius: 999px;+ }++ .hint-key {+ font-family: var(--font-mono);+ font-size: 10px;+ padding: 1px 5px;+ border-radius: 4px;+ background: var(--surface-subtle);+ border: 1px solid var(--divider);+ color: var(--text-secondary);+ }++ /* Inline Textarea Editor */+ #inlineEditorWrap {+ position: fixed;+ z-index: 30;+ display: none;+ pointer-events: auto;+ }++ #inlineTextEditor {+ min-width: 80px;+ min-height: 30px;+ padding: 4px 8px;+ border: 1.5px solid var(--accent);+ border-radius: 6px;+ background: var(--panel-bg);+ color: var(--text-primary);+ text-align: center;+ resize: none;+ outline: none;+ overflow: hidden;+ line-height: 1.3;+ box-shadow: 0 4px 16px rgba(105, 101, 219, 0.22);+ }++ /* Toast status notification */+ #studioToast {+ position: fixed;+ bottom: 60px;+ left: 50%;+ transform: translateX(-50%) translateY(8px);+ z-index: 40;+ padding: 6px 14px;+ font-size: 12px;+ font-weight: 500;+ opacity: 0;+ pointer-events: none;+ transition: all 0.18s ease;+ }++ #studioToast.show {+ opacity: 1;+ transform: translateX(-50%) translateY(0);+ }+ </style>+</head>+<body>+ <!-- Dual-Layer Retina Canvas Pipeline -->+ <div id="canvasStage">+ <canvas id="staticCanvas"></canvas>+ <canvas id="interactiveCanvas"></canvas>+ </div>++ <!-- Top Bar: Left Brand/Templates | Center Excaliflow Tool Island | Right Flow/Theme/Export -->+ <header id="topHeaderBar">+ <!-- Left Island -->+ <div class="header-group glass-panel">+ <button id="sidebarToggleBtn" class="ui-btn" title="Toggle Properties Panel (⌘\)">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="15" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>+ </button>+ <div class="brand-badge">+ <span class="brand-icon">E</span>+ <span>Excaliflow</span>+ </div>+ <div class="v-divider"></div>+ <div class="dropdown-wrap">+ <button id="templatesMenuBtn" class="ui-btn" title="Starter Architecture Templates">+ <span>Templates</span>+ <span style="font-size:9px;opacity:0.65">▾</span>+ </button>+ <div id="templatesDropdown" class="dropdown-menu align-left glass-panel">+ <button class="ui-btn menu-item" data-template="AI Agent Swarm"><span>AI Agent Swarm</span><span style="opacity:0.5">5 nodes</span></button>+ <button class="ui-btn menu-item" data-template="How Browsers Work"><span>How Browsers Work</span><span style="opacity:0.5">5 nodes</span></button>+ <button class="ui-btn menu-item" data-template="RAG Pipeline"><span>RAG Pipeline</span><span style="opacity:0.5">5 nodes</span></button>+ <button class="ui-btn menu-item" data-template="Microservices"><span>Microservices</span><span style="opacity:0.5">6 nodes</span></button>+ </div>+ </div>+ </div>++ <!-- Center Island: Iconic Excaliflow Tool Dock -->+ <nav id="bottomToolDock" class="glass-panel" aria-label="Drawing Tools">+ <button id="toolLockBtn" class="dock-tool-btn" title="Keep selected tool active after drawing (Q)">+ <svg viewBox="0 0 24 24"><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg>+ <span class="dock-key">Q</span>+ </button>+ <div class="v-divider"></div>+ <button class="dock-tool-btn active" data-tool="select" title="Selection — Move, resize, bend arrows (V or 1)">+ <svg viewBox="0 0 24 24"><path d="M4 4l7.07 17 2.51-7.39L21 11.07z"/></svg>+ <span class="dock-key">1</span>+ </button>+ <button class="dock-tool-btn" data-tool="hand" title="Hand — Pan canvas (H or Space)">+ <svg viewBox="0 0 24 24"><path d="M18 11V6a2 2 0 0 0-4 0v4"/><path d="M14 10V4a2 2 0 0 0-4 0v6"/><path d="M10 10.5V6a2 2 0 0 0-4 0v8"/><path d="M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15"/></svg>+ <span class="dock-key">H</span>+ </button>+ <button class="dock-tool-btn" data-tool="rectangle" title="Rectangle (R or 2)">+ <svg viewBox="0 0 24 24"><rect x="3" y="5" width="18" height="14" rx="3"/></svg>+ <span class="dock-key">2</span>+ </button>+ <button class="dock-tool-btn" data-tool="diamond" title="Diamond / Decision (D or 3)">+ <svg viewBox="0 0 24 24"><path d="M12 3l9 9-9 9-9-9z"/></svg>+ <span class="dock-key">3</span>+ </button>+ <button class="dock-tool-btn" data-tool="ellipse" title="Ellipse / Circle (O or 4)">+ <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/></svg>+ <span class="dock-key">4</span>+ </button>+ <button class="dock-tool-btn" data-tool="arrow" title="Causal Flow Arrow (A or 5)">+ <svg viewBox="0 0 24 24"><line x1="5" y1="19" x2="19" y2="5"/><polyline points="9 5 19 5 19 15"/></svg>+ <span class="dock-key">5</span>+ </button>+ <button class="dock-tool-btn" data-tool="freedraw" title="Draw Freehand (P or 7)">+ <svg viewBox="0 0 24 24"><path d="M12 19l7-7 3 3-7 7-3-3z"/><path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"/></svg>+ <span class="dock-key">7</span>+ </button>+ <button class="dock-tool-btn" data-tool="text" title="Text (T or 8)">+ <svg viewBox="0 0 24 24"><polyline points="4 7 4 4 20 4 20 7"/><line x1="9" y1="20" x2="15" y2="20"/><line x1="12" y1="4" x2="12" y2="20"/></svg>+ <span class="dock-key">8</span>+ </button>+ <button class="dock-tool-btn" data-tool="sticky" title="Sticky Note (N or 9)">+ <svg viewBox="0 0 24 24"><path d="M15.5 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V8.5L15.5 3Z"/><polyline points="14 3 14 9 21 9"/></svg>+ <span class="dock-key">9</span>+ </button>+ <button class="dock-tool-btn" data-tool="laser" title="Laser Pointer (K)">+ <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"/><path d="M12 2v3M12 19v3M2 12h3M19 12h3M4.93 4.93l2.12 2.12M16.95 16.95l2.12 2.12M19.07 4.93l-2.12 2.12M7.05 16.95l-2.12 2.12"/></svg>+ <span class="dock-key">K</span>+ </button>+ <button class="dock-tool-btn" data-tool="eraser" title="Eraser (E or 0)">+ <svg viewBox="0 0 24 24"><path d="m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21"/><path d="M22 21H7"/><path d="m5 11 9 9"/></svg>+ <span class="dock-key">0</span>+ </button>+ </nav>++ <!-- Right Island: Live Flow Pill + Canvas Theme + Share/Export -->+ <div class="header-group glass-panel">+ <div id="masterFlowPill">+ <span id="flowStatusDot" class="flow-status-dot"></span>+ <button id="masterFlowBtn" class="ui-btn active" title="Toggle Live 60fps Causal Data Flow">Flow: ON</button>+ <span id="flowBadgeText" class="flow-badge-meta">COMETS · 1X</span>+ </div>+ <div class="v-divider"></div>+ <button id="bgWhiteBtn" class="ui-btn active" title="Pure White Canvas (#ffffff)">☀</button>+ <button id="bgBlackBtn" class="ui-btn" title="Pitch-Black Neon Canvas (#000000)">☾</button>+ <div class="v-divider"></div>+ <button id="btnSavePng" class="ui-btn primary" title="Export Cropped 2x Retina PNG">Export PNG</button>+ <div class="dropdown-wrap">+ <button id="exportMenuBtn" class="ui-btn" title="More Export & Scene Actions">⋯</button>+ <div id="exportDropdown" class="dropdown-menu glass-panel">+ <button id="btnCopyPng" class="ui-btn menu-item"><span>Copy 2x PNG</span><span>⌘⇧C</span></button>+ <button id="btnRecordVideo" class="ui-btn menu-item"><span>Record 60fps Video</span><span>.webm</span></button>+ <div class="menu-sep"></div>+ <button id="btnSaveJson" class="ui-btn menu-item"><span>Save Scene</span><span>JSON</span></button>+ <button id="btnLoadJson" class="ui-btn menu-item"><span>Load Scene</span><span>Open</span></button>+ <input type="file" id="jsonFileInput" accept=".json,.excaliflow,.excalidraw" style="display:none" />+ <div class="menu-sep"></div>+ <button id="btnClearScene" class="ui-btn menu-item danger"><span>Clear Canvas</span><span>⌫</span></button>+ </div>+ </div>+ </div>+ </header>++ <!-- Left Properties Inspector (#leftSidebar) -->+ <aside id="leftSidebar" class="glass-panel">+ <!-- Stroke Color Swatches -->+ <div class="sidebar-section">+ <div class="section-title"><span>Stroke</span></div>+ <div class="swatch-row" id="sidebarSwatches">+ <button class="color-swatch active" data-color="#171717" title="Carbon (#171717)" style="background:#171717"></button>+ <button class="color-swatch" data-color="#0070f3" title="Blue (#0070f3)" style="background:#0070f3"></button>+ <button class="color-swatch" data-color="#7928ca" title="Purple (#7928ca)" style="background:#7928ca"></button>+ <button class="color-swatch" data-color="#10b981" title="Emerald (#10b981)" style="background:#10b981"></button>+ <button class="color-swatch" data-color="#f59e0b" title="Amber (#f59e0b)" style="background:#f59e0b"></button>+ <button class="color-swatch" data-color="#ef4444" title="Rose (#ef4444)" style="background:#ef4444"></button>+ <button class="color-swatch" data-color="#06b6d4" title="Cyan (#06b6d4)" style="background:#06b6d4"></button>+ </div>+ </div>++ <!-- Fill Style -->+ <div class="sidebar-section">+ <div class="section-title"><span>Fill</span></div>+ <div class="segmented-row" id="fillStyleRow">+ <button class="seg-btn active" data-fill-style="hachure" title="Hachure Sketch Fill">Sketch</button>+ <button class="seg-btn" data-fill-style="cross-hatch" title="Cross-Hatch Fill">Cross</button>+ <button class="seg-btn" data-fill-style="solid" title="Solid Tint Fill">Solid</button>+ <button class="seg-btn" data-fill-style="none" title="Outline Only">None</button>+ </div>+ </div>++ <!-- Stroke Width & Style -->+ <div class="sidebar-section">+ <div class="section-title"><span>Stroke Width & Style</span></div>+ <div class="segmented-row" id="strokeWidthRow">+ <button class="seg-btn" data-stroke-width="1.5">Thin</button>+ <button class="seg-btn active" data-stroke-width="2.2">Bold</button>+ <button class="seg-btn" data-stroke-width="3.6">Heavy</button>+ </div>+ <div class="segmented-row" id="strokeStyleRow">+ <button class="seg-btn active" data-stroke-style="solid">Solid</button>+ <button class="seg-btn" data-stroke-style="dashed">Dashed</button>+ <button class="seg-btn" data-stroke-style="dotted">Dotted</button>+ </div>+ </div>++ <!-- Sloppiness & Arrow Type -->+ <div class="sidebar-section">+ <div class="section-title"><span>Sloppiness & Arrow</span></div>+ <div class="segmented-row" id="roughnessRow">+ <button class="seg-btn" data-roughness="0">Clean</button>+ <button class="seg-btn active" data-roughness="0.85">Artist</button>+ <button class="seg-btn" data-roughness="1.75">Cartoon</button>+ </div>+ <div class="segmented-row" id="curveTypeRow">+ <button class="seg-btn active" data-curve-type="curved">Curved</button>+ <button class="seg-btn" data-curve-type="elbow">Elbow</button>+ <button class="seg-btn" data-curve-type="straight">Straight</button>+ </div>+ </div>++ <!-- Typography -->+ <div class="sidebar-section">+ <div class="section-title"><span>Typography</span></div>+ <div class="segmented-row" id="fontFamilyRow">+ <button class="seg-btn active" data-font-family="hand" style="font-family:var(--font-hand);font-size:13px">Hand</button>+ <button class="seg-btn" data-font-family="sans">Normal</button>+ <button class="seg-btn" data-font-family="code" style="font-family:var(--font-mono);font-size:10.5px">Code</button>+ </div>+ <div class="segmented-row" id="fontSizeRow">+ <button class="seg-btn" data-font-size="13">S</button>+ <button class="seg-btn active" data-font-size="15">M</button>+ <button class="seg-btn" data-font-size="19">L</button>+ <button class="seg-btn" data-font-size="24">XL</button>+ </div>+ </div>++ <!-- Live Flow Animation -->+ <div class="sidebar-section">+ <div class="section-title"><span>Flow Animation</span></div>+ <div class="grid-2x2" id="flowModeGrid">+ <button class="seg-btn active" data-flow-mode="comets">☄ Comets</button>+ <button class="seg-btn" data-flow-mode="pulses">◎ Pulses</button>+ <button class="seg-btn" data-flow-mode="neon">⚡ Neon</button>+ <button class="seg-btn" data-flow-mode="dashed">⋯ Stream</button>+ </div>+ <div class="segmented-row" id="flowSpeedRow">+ <button class="seg-btn" data-flow-speed="0.6">0.6x</button>+ <button class="seg-btn active" data-flow-speed="1">1x</button>+ <button class="seg-btn" data-flow-speed="1.8">1.8x</button>+ </div>+ </div>++ <!-- Quick Insert / Chain -->+ <div class="sidebar-section">+ <div class="section-title"><span>Quick Chain</span></div>+ <div class="grid-2x2">+ <button class="seg-btn" data-quick-add="rectangle">+ Box</button>+ <button class="seg-btn" data-quick-add="ellipse">+ Circle</button>+ <button class="seg-btn" data-quick-add="diamond">+ Decision</button>+ <button class="seg-btn" data-quick-add="sticky">+ Sticky</button>+ </div>+ </div>+ </aside>++ <!-- Floating Contextual Selection Toolbar (#quickHud) -->+ <div id="quickHud" class="glass-panel">+ <div id="hudColorDots" style="display:inline-flex;align-items:center;gap:4px"></div>+ <div class="v-divider"></div>+ <div id="hudFontGroup" style="display:inline-flex;align-items:center;gap:2px">+ <button class="ui-btn" data-hud-font="hand" title="Hand-drawn font">Hand</button>+ <button class="ui-btn" data-hud-font="sans" title="Normal font">Sans</button>+ <button class="ui-btn" data-hud-font="code" title="Code font">Code</button>+ </div>+ <div class="v-divider"></div>+ <!-- Node-specific morph & flow actions -->+ <div id="hudNodeControls" style="display:inline-flex;align-items:center;gap:2px">+ <button class="ui-btn" data-hud-morph="rectangle" title="Morph to Box">▭</button>+ <button class="ui-btn" data-hud-morph="ellipse" title="Morph to Circle">◯</button>+ <button class="ui-btn" data-hud-morph="diamond" title="Morph to Decision">◇</button>+ <button id="hudPulseBtn" class="ui-btn" title="Send Pulse Burst">⚡ Pulse</button>+ <button id="hudNextBtn" class="ui-btn" title="Chain Next Node (Tab)">+ Next</button>+ </div>+ <!-- Arrow-specific actions -->+ <div id="hudArrowControls" style="display:none;align-items:center;gap:2px">+ <button class="ui-btn" data-hud-curve="curved">Curved</button>+ <button class="ui-btn" data-hud-curve="straight">Straight</button>+ <button id="hudArrowFlowBtn" class="ui-btn">Flow ON</button>+ <button id="hudFlipArrowBtn" class="ui-btn" title="Reverse Arrow Direction">⇄</button>+ </div>+ <div class="v-divider"></div>+ <button id="hudDuplicateBtn" class="ui-btn" title="Duplicate (⌘D)">⧉</button>+ <button id="hudDeleteBtn" class="ui-btn danger" title="Delete (⌫)">✕</button>+ </div>++ <!-- Bottom-Left Undo/Redo Pill (Excaliflow Standard Placement) -->+ <div id="bottomLeftBar" class="glass-panel">+ <button id="btnUndo" class="ui-btn" title="Undo (⌘Z)">↶</button>+ <button id="btnRedo" class="ui-btn" title="Redo (⇧⌘Z)">↷</button>+ </div>++ <!-- Subtle Canvas Interaction Hint -->+ <div id="canvasHintPill" class="glass-panel">+ <span><span class="hint-key">Double-click</span> canvas to add node</span>+ <span><span class="hint-key">Drag</span> arrow ends to slide around shapes</span>+ <span><span class="hint-key">Tab</span> to chain</span>+ </div>++ <!-- Bottom-Right Zoom Pill -->+ <div id="zoomPill" class="glass-panel">+ <button id="zoomOutBtn" class="ui-btn" title="Zoom Out">−</button>+ <button id="zoomResetBtn" class="ui-btn" title="Reset Zoom to 100%">100%</button>+ <button id="zoomInBtn" class="ui-btn" title="Zoom In">+</button>+ <div class="v-divider"></div>+ <button id="zoomFitBtn" class="ui-btn" title="Fit Diagram to Screen">Fit</button>+ </div>++ <!-- Inline Text Editor -->+ <div id="inlineEditorWrap">+ <textarea id="inlineTextEditor" rows="1" spellcheck="false"></textarea>+ </div>++ <!-- Toast Status Pill -->+ <div id="studioToast" class="glass-panel"></div>++ <script>+ /* =========================================================================+ * EXCALIFLOW — ZERO-DEPENDENCY HAND-DRAWN DIAGRAMMING & 60FPS FLOW ENGINE+ * ========================================================================= */++ const SEMANTIC_COLORS = [+ { hex: '#171717', name: 'Carbon', lightFill: 'rgba(23, 23, 23, 0.07)', darkFill: 'rgba(248, 250, 252, 0.14)', darkStroke: '#f8fafc' },+ { hex: '#0070f3', name: 'Blue', lightFill: 'rgba(0, 112, 243, 0.12)', darkFill: 'rgba(56, 189, 248, 0.20)', darkStroke: '#38bdf8' },+ { hex: '#7928ca', name: 'Purple', lightFill: 'rgba(121, 40, 202, 0.12)', darkFill: 'rgba(192, 132, 252, 0.22)', darkStroke: '#c084fc' },+ { hex: '#10b981', name: 'Emerald',lightFill: 'rgba(16, 185, 129, 0.13)', darkFill: 'rgba(52, 211, 153, 0.20)', darkStroke: '#34d399' },+ { hex: '#f59e0b', name: 'Amber', lightFill: 'rgba(245, 158, 11, 0.15)', darkFill: 'rgba(251, 191, 36, 0.22)', darkStroke: '#fbbf24' },+ { hex: '#ef4444', name: 'Rose', lightFill: 'rgba(239, 68, 68, 0.13)', darkFill: 'rgba(248, 113, 113, 0.22)', darkStroke: '#f87171' },+ { hex: '#06b6d4', name: 'Cyan', lightFill: 'rgba(6, 182, 212, 0.14)', darkFill: 'rgba(34, 211, 238, 0.22)', darkStroke: '#22d3ee' }+ ];++ // Matches Excalidraw's FONT_FAMILY (Excalifont / Virgil for hand, Assistant / Nunito for normal, Cascadia for code)+ const FONT_MAP = {+ hand: "'Excalifont', 'Virgil', 'Patrick Hand', 'Architects Daughter', 'Caveat', cursive",+ sans: "'Assistant', 'Nunito', 'Geist', 'Inter', -apple-system, BlinkMacSystemFont, sans-serif",+ code: "'Cascadia', 'Geist Mono', monospace"+ };++ // Excalidraw unitless line-height metric from packages/common/src/font-metadata.ts+ const EXCALIDRAW_LINE_HEIGHT = 1.25;++ function normalizeFontFamily(family) {+ if (!family) return 'hand';+ if (typeof family === 'number') {+ if (family === 3 || family === 8) return 'code';+ if (family === 2 || family === 4 || family === 6 || family === 9 || family === 10) return 'sans';+ return 'hand';+ }+ const f = String(family).toLowerCase();+ if (f === 'hand' || f.includes('excalifont') || f.includes('virgil') || f.includes('patrick') || f.includes('caveat')) return 'hand';+ if (f === 'sans' || f === 'normal' || f.includes('assistant') || f.includes('nunito') || (f.includes('geist') && !f.includes('mono')) || f.includes('inter')) return 'sans';+ if (f === 'code' || f === 'mono' || f.includes('cascadia') || f.includes('mono')) return 'code';+ return 'hand';+ }++ function getFontCss(family, fontSize, weight = null) {+ const key = normalizeFontFamily(family);+ const cssFamily = FONT_MAP[key] || FONT_MAP.hand;+ const sz = Number(fontSize) || 16;+ const resolvedWeight = weight !== null ? weight : (key === 'hand' ? 400 : 500);+ return `${resolvedWeight} ${sz}px ${cssFamily}`;+ }++ function getColorEntry(hex) {+ const norm = (hex || '#171717').toLowerCase();+ return SEMANTIC_COLORS.find(c => c.hex.toLowerCase() === norm) || SEMANTIC_COLORS[0];+ }++ function resolveStrokeColor(hex, canvasBg) {+ const entry = getColorEntry(hex);+ const isDark = (canvasBg || state.canvasBg) === '#000000';+ if (isDark) return entry.darkStroke || entry.hex;+ return entry.hex;+ }++ function resolveFillTint(hex, canvasBg, isSticky = false) {+ const entry = getColorEntry(hex);+ const isDark = (canvasBg || state.canvasBg) === '#000000';+ if (isSticky) {+ if (entry.hex === '#171717') return isDark ? 'rgba(251, 191, 36, 0.20)' : '#fef3c7';+ }+ return isDark ? entry.darkFill : entry.lightFill;+ }++ /* -------------------------------------------------------------------------+ * 1. Deterministic Seeded PRNG (mulberry32)+ * ------------------------------------------------------------------------- */+ function mulberry32(seed) {+ let a = (Number(seed) || 1) >>> 0;+ return function () {+ a |= 0;+ a = (a + 0x6D2B79F5) | 0;+ let t = Math.imul(a ^ (a >>> 15), 1 | a);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+ }++ let idCounter = 1000;+ function nextId(prefix = 'el') {+ idCounter += 1;+ return `${prefix}_${idCounter}_${Math.floor(Math.random() * 9000 + 1000)}`;+ }++ /* -------------------------------------------------------------------------+ * 2. Scene State+ * ------------------------------------------------------------------------- */+ const state = {+ elements: [],+ selectedIds: new Set(),+ hoveredId: null,+ hoveredPort: null,+ hoveredArrowHandle: null,+ hoveredResizeHandle: null,+ splitTargetArrowId: null,+ snapPreview: null,+ activeTool: 'select',+ toolLocked: false,+ canvasBg: '#ffffff',+ scrollX: 0,+ scrollY: 0,+ zoom: 1,+ flowEnabled: true,+ flowMode: 'comets',+ flowSpeed: 1.0,+ activePulses: [],+ laserPoints: [],+ nodeArrivalEnergy: new Map(),+ defaults: {+ strokeColor: '#171717',+ fillStyle: 'hachure',+ fontFamily: 'hand',+ fontSize: 15,+ roughness: 0.85,+ strokeWidth: 2.2,+ strokeStyle: 'solid',+ curveType: 'curved'+ },+ history: {+ undoStack: [],+ redoStack: []+ },+ clipboard: [],+ pasteCount: 0,+ drag: null,+ editingId: null,+ isSpacePanning: false+ };++ /* -------------------------------------------------------------------------+ * 3. Zero-Bleed Analytical Interior Clipping & Procedural Sketch Engine+ * ------------------------------------------------------------------------- */+ function clampPointToShapeInterior(el, px, py, inset = 1.5) {+ const w = Math.max(2, el.width || 0);+ const h = Math.max(2, el.height || 0);+ const cx = el.x + w / 2;+ const cy = el.y + h / 2;+ const ins = Math.min(Math.max(0, inset), Math.min(w, h) * 0.35);++ if (el.type === 'ellipse') {+ const rx = Math.max(1, w / 2 - ins);+ const ry = Math.max(1, h / 2 - ins);+ const ux = (px - cx) / rx;+ const vy = (py - cy) / ry;+ const d2 = ux * ux + vy * vy;+ if (d2 > 0.999) {+ const s = 0.995 / Math.sqrt(d2);+ return [cx + (px - cx) * s, cy + (py - cy) * s];+ }+ return [px, py];+ }++ if (el.type === 'diamond') {+ const hw = Math.max(1, w / 2 - ins);+ const hh = Math.max(1, h / 2 - ins);+ const l1 = Math.abs(px - cx) / hw + Math.abs(py - cy) / hh;+ if (l1 > 0.999) {+ const s = 0.995 / l1;+ return [cx + (px - cx) * s, cy + (py - cy) * s];+ }+ return [px, py];+ }++ const xL = el.x + ins;+ const xR = el.x + w - ins;+ const yT = el.y + ins;+ const yB = el.y + h - ins;+ let nx = Math.max(xL, Math.min(xR, px));+ let ny = Math.max(yT, Math.min(yB, py));+ const r = Math.max(0, Math.min(14, w / 4, h / 4) - ins * 0.5);+ if (r > 0.5) {+ const corners = [+ [xL + r, yT + r, nx < xL + r && ny < yT + r],+ [xR - r, yT + r, nx > xR - r && ny < yT + r],+ [xR - r, yB - r, nx > xR - r && ny > yB - r],+ [xL + r, yB - r, nx < xL + r && ny > yB - r]+ ];+ for (const [kx, ky, inCorner] of corners) {+ if (inCorner) {+ const dx = nx - kx;+ const dy = ny - ky;+ const d = Math.hypot(dx, dy);+ if (d > r * 0.995) {+ const s = (r * 0.99) / d;+ nx = kx + dx * s;+ ny = ky + dy * s;+ }+ }+ }+ }+ return [nx, ny];+ }++ function clipSegmentToShape(el, x1, y1, x2, y2, inset = 1.8) {+ if (!el) return null;+ const w = Number(el.width) || 0;+ const h = Number(el.height) || 0;+ if (w <= 2 || h <= 2) return null;++ const cx = el.x + w / 2;+ const cy = el.y + h / 2;+ const ins = Math.min(Math.max(0, Number(inset) || 0), Math.min(w, h) * 0.35);+ const dx = x2 - x1;+ const dy = y2 - y1;++ if (el.type === 'ellipse') {+ const rx = Math.max(1, w / 2 - ins);+ const ry = Math.max(1, h / 2 - ins);+ const u1 = (x1 - cx) / rx;+ const v1 = (y1 - cy) / ry;+ const du = dx / rx;+ const dv = dy / ry;++ const A = du * du + dv * dv;+ const B = 2 * (u1 * du + v1 * dv);+ const C = u1 * u1 + v1 * v1 - 1;++ if (A < 1e-12) {+ return C <= 0 ? [x1, y1, x2, y2] : null;+ }+ const disc = B * B - 4 * A * C;+ if (disc <= 0) return null;++ const sqrtD = Math.sqrt(disc);+ const t0 = (-B - sqrtD) / (2 * A);+ const t1 = (-B + sqrtD) / (2 * A);+ const tMin = Math.max(0, Math.min(t0, t1));+ const tMax = Math.min(1, Math.max(t0, t1));+ if (tMin >= tMax - 1e-5) return null;++ const [cx1, cy1] = clampPointToShapeInterior(el, x1 + tMin * dx, y1 + tMin * dy, ins);+ const [cx2, cy2] = clampPointToShapeInterior(el, x1 + tMax * dx, y1 + tMax * dy, ins);+ return [cx1, cy1, cx2, cy2];+ }++ if (el.type === 'diamond') {+ const hw = Math.max(1, w / 2 - ins);+ const hh = Math.max(1, h / 2 - ins);+ let tMin = 0;+ let tMax = 1;++ const signs = [[1, 1], [1, -1], [-1, 1], [-1, -1]];+ for (let i = 0; i < 4; i++) {+ const sx = signs[i][0];+ const sy = signs[i][1];+ const p = sx * (dx / hw) + sy * (dy / hh);+ const q = 1 - (sx * ((x1 - cx) / hw) + sy * ((y1 - cy) / hh));+ if (Math.abs(p) < 1e-12) {+ if (q < 0) return null;+ } else if (p > 0) {+ tMax = Math.min(tMax, q / p);+ } else {+ tMin = Math.max(tMin, q / p);+ }+ if (tMin >= tMax - 1e-5) return null;+ }++ const [cx1, cy1] = clampPointToShapeInterior(el, x1 + tMin * dx, y1 + tMin * dy, ins);+ const [cx2, cy2] = clampPointToShapeInterior(el, x1 + tMax * dx, y1 + tMax * dy, ins);+ return [cx1, cy1, cx2, cy2];+ }++ const xL = el.x + ins;+ const xR = el.x + w - ins;+ const yT = el.y + ins;+ const yB = el.y + h - ins;+ if (xL >= xR || yT >= yB) return null;++ let tMin = 0;+ let tMax = 1;+ const pArr = [-dx, dx, -dy, dy];+ const qArr = [x1 - xL, xR - x1, y1 - yT, yB - y1];+ for (let i = 0; i < 4; i++) {+ const p = pArr[i];+ const q = qArr[i];+ if (Math.abs(p) < 1e-12) {+ if (q < 0) return null;+ } else {+ const r = q / p;+ if (p < 0) tMin = Math.max(tMin, r);+ else tMax = Math.min(tMax, r);+ if (tMin >= tMax - 1e-5) return null;+ }+ }++ const r = isStickyType(el.type) ? 4 : Math.max(0, Math.min(14, w / 4, h / 4) - ins * 0.5);+ if (r > 0.5) {+ const clipCornerCircle = (tVal, isStart) => {+ const px = x1 + tVal * dx;+ const py = y1 + tVal * dy;+ let kx = null;+ let ky = null;+ if (px < xL + r && py < yT + r) { kx = xL + r; ky = yT + r; }+ else if (px > xR - r && py < yT + r) { kx = xR - r; ky = yT + r; }+ else if (px > xR - r && py > yB - r) { kx = xR - r; ky = yB - r; }+ else if (px < xL + r && py > yB - r) { kx = xL + r; ky = yB - r; }+ if (kx === null) return tVal;++ const ox = x1 - kx;+ const oy = y1 - ky;+ if (ox * ox + oy * oy <= r * r && !isStart) return tVal;+ const A = dx * dx + dy * dy;+ const B = 2 * (ox * dx + oy * dy);+ const C = ox * ox + oy * oy - r * r;+ const disc = B * B - 4 * A * C;+ if (disc <= 0 || A < 1e-12) return null;+ const sD = Math.sqrt(disc);+ const ca = (-B - sD) / (2 * A);+ const cb = (-B + sD) / (2 * A);+ return isStart ? Math.max(tVal, Math.min(ca, cb)) : Math.min(tVal, Math.max(ca, cb));+ };++ const ntMin = clipCornerCircle(tMin, true);+ const ntMax = clipCornerCircle(tMax, false);+ if (ntMin === null || ntMax === null || ntMin >= ntMax - 1e-5) return null;+ tMin = ntMin;+ tMax = ntMax;+ }++ const [cx1, cy1] = clampPointToShapeInterior(el, x1 + tMin * dx, y1 + tMin * dy, ins);+ const [cx2, cy2] = clampPointToShapeInterior(el, x1 + tMax * dx, y1 + tMax * dy, ins);+ return [cx1, cy1, cx2, cy2];+ }++ function isStickyType(type) {+ return type === 'sticky';+ }++ function roughEdge(path, x1, y1, x2, y2, rng, roughness = 0.85) {+ const r = Number(roughness) || 0;+ if (r <= 0.001) {+ path.moveTo(x1, y1);+ path.lineTo(x2, y2);+ return;+ }+ const len = Math.hypot(x2 - x1, y2 - y1);+ const amp = Math.min(2.6, Math.max(0.4, len * 0.012)) * r;+ for (let pass = 0; pass < 2; pass++) {+ const pScale = pass === 0 ? 1 : 0.65;+ const sx = x1 + (rng() - 0.5) * amp * pScale;+ const sy = y1 + (rng() - 0.5) * amp * pScale;+ const ex = x2 + (rng() - 0.5) * amp * pScale;+ const ey = y2 + (rng() - 0.5) * amp * pScale;+ const cp1x = x1 + (x2 - x1) * 0.33 + (rng() - 0.5) * amp * 1.5;+ const cp1y = y1 + (y2 - y1) * 0.33 + (rng() - 0.5) * amp * 1.5;+ const cp2x = x1 + (x2 - x1) * 0.67 + (rng() - 0.5) * amp * 1.5;+ const cp2y = y1 + (y2 - y1) * 0.67 + (rng() - 0.5) * amp * 1.5;+ path.moveTo(sx, sy);+ path.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, ex, ey);+ }+ }++ function buildCleanRoundRectPath(path, x, y, w, h, r) {+ const cr = Math.max(0, Math.min(r, w / 2, h / 2));+ path.moveTo(x + cr, y);+ path.lineTo(x + w - cr, y);+ path.quadraticCurveTo(x + w, y, x + w, y + cr);+ path.lineTo(x + w, y + h - cr);+ path.quadraticCurveTo(x + w, y + h, x + w - cr, y + h);+ path.lineTo(x + cr, y + h);+ path.quadraticCurveTo(x, y + h, x, y + h - cr);+ path.lineTo(x, y + cr);+ path.quadraticCurveTo(x, y, x + cr, y);+ path.closePath();+ }++ function roughRoundRect(path, x, y, w, h, r, rng, roughness = 0.85) {+ const cr = Math.max(0, Math.min(r, w / 4, h / 4));+ if (!roughness || roughness <= 0.001) {+ buildCleanRoundRectPath(path, x, y, w, h, cr);+ return;+ }+ const passes = 2;+ for (let p = 0; p < passes; p++) {+ const jit = ((p === 0 ? 1 : 0.65) * roughness * 1.15);+ const j = () => (rng() - 0.5) * jit;+ path.moveTo(x + cr + j(), y + j());+ path.lineTo(x + w - cr + j(), y + j());+ path.quadraticCurveTo(x + w + j(), y + j(), x + w + j(), y + cr + j());+ path.lineTo(x + w + j(), y + h - cr + j());+ path.quadraticCurveTo(x + w + j(), y + h + j(), x + w - cr + j(), y + h + j());+ path.lineTo(x + cr + j(), y + h + j());+ path.quadraticCurveTo(x + j(), y + h + j(), x + j(), y + h - cr + j());+ path.lineTo(x + j(), y + cr + j());+ path.quadraticCurveTo(x + j(), y + j(), x + cr + j(), y + j());+ }+ }++ function roughEllipse(path, cx, cy, rx, ry, rng, roughness = 0.85) {+ if (!roughness || roughness <= 0.001) {+ path.ellipse(cx, cy, Math.max(1, rx), Math.max(1, ry), 0, 0, Math.PI * 2);+ return;+ }+ const steps = 16;+ for (let pass = 0; pass < 2; pass++) {+ const amp = (pass === 0 ? 1 : 0.6) * roughness * 1.25;+ const pts = [];+ for (let i = 0; i < steps; i++) {+ const theta = (i / steps) * Math.PI * 2;+ const px = cx + Math.cos(theta) * rx + (rng() - 0.5) * amp;+ const py = cy + Math.sin(theta) * ry + (rng() - 0.5) * amp;+ pts.push([px, py]);+ }+ const firstMidX = (pts[steps - 1][0] + pts[0][0]) / 2;+ const firstMidY = (pts[steps - 1][1] + pts[0][1]) / 2;+ path.moveTo(firstMidX, firstMidY);+ for (let i = 0; i < steps; i++) {+ const curr = pts[i];+ const next = pts[(i + 1) % steps];+ const midX = (curr[0] + next[0]) / 2;+ const midY = (curr[1] + next[1]) / 2;+ path.quadraticCurveTo(curr[0], curr[1], midX, midY);+ }+ }+ }++ const ShapeCache = {+ cache: new Map(),++ keyFor(el) {+ return [+ el.id,+ el.type,+ Math.round(el.x * 10) / 10,+ Math.round(el.y * 10) / 10,+ Math.round((el.width || 0) * 10) / 10,+ Math.round((el.height || 0) * 10) / 10,+ el.seed || 1,+ el.versionNonce || 1,+ el.roughness ?? 0.85,+ el.fillStyle || 'hachure',+ el.strokeWidth || 2.2+ ].join('|');+ },++ generate(el) {+ const rng = mulberry32((Number(el.seed) || 1) ^ (Number(el.versionNonce) || 1));+ const fillPath = new Path2D();+ const strokePath = new Path2D();+ const hachurePath = new Path2D();++ const x = Number(el.x) || 0;+ const y = Number(el.y) || 0;+ const w = Math.max(2, Number(el.width) || 0);+ const h = Math.max(2, Number(el.height) || 0);+ const cx = x + w / 2;+ const cy = y + h / 2;+ const roughness = el.roughness ?? 0.85;++ if (el.type === 'ellipse') {+ const rx = Math.max(1, w / 2);+ const ry = Math.max(1, h / 2);+ fillPath.ellipse(cx, cy, rx, ry, 0, 0, Math.PI * 2);+ roughEllipse(strokePath, cx, cy, rx, ry, rng, roughness);+ } else if (el.type === 'diamond') {+ const top = [cx, y];+ const right = [x + w, cy];+ const bottom = [cx, y + h];+ const left = [x, cy];+ fillPath.moveTo(top[0], top[1]);+ fillPath.lineTo(right[0], right[1]);+ fillPath.lineTo(bottom[0], bottom[1]);+ fillPath.lineTo(left[0], left[1]);+ fillPath.closePath();++ roughEdge(strokePath, top[0], top[1], right[0], right[1], rng, roughness);+ roughEdge(strokePath, right[0], right[1], bottom[0], bottom[1], rng, roughness);+ roughEdge(strokePath, bottom[0], bottom[1], left[0], left[1], rng, roughness);+ roughEdge(strokePath, left[0], left[1], top[0], top[1], rng, roughness);+ } else if (el.type === 'rectangle' || el.type === 'sticky') {+ const r = el.type === 'sticky' ? 4 : Math.min(14, w / 4, h / 4);+ buildCleanRoundRectPath(fillPath, x, y, w, h, r);+ roughRoundRect(strokePath, x, y, w, h, r, rng, el.type === 'sticky' ? roughness * 0.45 : roughness);+ }++ const fillStyle = el.fillStyle || 'hachure';+ if ((fillStyle === 'hachure' || fillStyle === 'cross-hatch') &&+ (el.type === 'rectangle' || el.type === 'ellipse' || el.type === 'diamond' || el.type === 'sticky')) {+ const spacing = 8.5;+ const inset = Math.max(2.2, (Number(el.strokeWidth) || 2) * 0.9);+ const diag = w + h;++ for (let d = -diag; d <= diag; d += spacing) {+ const rawX1 = x + d;+ const rawY1 = y + h;+ const rawX2 = x + d + h;+ const rawY2 = y;+ const clipped = clipSegmentToShape(el, rawX1, rawY1, rawX2, rawY2, inset);+ if (clipped) {+ const [cx1, cy1, cx2, cy2] = clipped;+ if (Math.hypot(cx2 - cx1, cy2 - cy1) > 1.5) {+ const rawMx = (cx1 + cx2) / 2 + (rng() - 0.5) * roughness * 0.9;+ const rawMy = (cy1 + cy2) / 2 + (rng() - 0.5) * roughness * 0.9;+ const [mx, my] = clampPointToShapeInterior(el, rawMx, rawMy, inset);+ hachurePath.moveTo(cx1, cy1);+ hachurePath.quadraticCurveTo(mx, my, cx2, cy2);+ }+ }+ }++ if (fillStyle === 'cross-hatch') {+ for (let d = -diag; d <= diag; d += spacing * 1.05) {+ const rawX1 = x + d;+ const rawY1 = y;+ const rawX2 = x + d + h;+ const rawY2 = y + h;+ const clipped = clipSegmentToShape(el, rawX1, rawY1, rawX2, rawY2, inset);+ if (clipped) {+ const [cx1, cy1, cx2, cy2] = clipped;+ if (Math.hypot(cx2 - cx1, cy2 - cy1) > 1.5) {+ const rawMx = (cx1 + cx2) / 2 + (rng() - 0.5) * roughness * 0.9;+ const rawMy = (cy1 + cy2) / 2 + (rng() - 0.5) * roughness * 0.9;+ const [mx, my] = clampPointToShapeInterior(el, rawMx, rawMy, inset);+ hachurePath.moveTo(cx1, cy1);+ hachurePath.quadraticCurveTo(mx, my, cx2, cy2);+ }+ }+ }+ }+ }++ return { fillPath, strokePath, hachurePath };+ },++ get(el) {+ const key = this.keyFor(el);+ let entry = this.cache.get(el.id);+ if (!entry || entry.key !== key) {+ const paths = this.generate(el);+ entry = { key, paths };+ this.cache.set(el.id, entry);+ }+ return entry.paths;+ },++ invalidate(el) {+ if (!el) return;+ const id = typeof el === 'string' ? el : el.id;+ if (typeof el === 'object' && el !== null) {+ el.versionNonce = (Number(el.versionNonce) || 1) + 1;+ }+ this.cache.delete(id);+ },++ clear() {+ this.cache.clear();+ }+ };++ /* -------------------------------------------------------------------------+ * 4. Perimeter Sliding (focusAngle) & Arrow Geometry Engine+ * ------------------------------------------------------------------------- */+ function isNodeElement(el) {+ return el && (el.type === 'rectangle' || el.type === 'ellipse' || el.type === 'diamond' || el.type === 'sticky' || el.type === 'text');+ }++ function angleToSide(angle) {+ if (typeof angle !== 'number' || Number.isNaN(angle)) return 'right';+ const deg = (angle * 180) / Math.PI;+ if (deg >= -45 && deg <= 45) return 'right';+ if (deg > 45 && deg < 135) return 'bottom';+ if (deg >= -135 && deg < -45) return 'top';+ return 'left';+ }++ function computeBindingForShape(shape, worldPt) {+ if (!shape || !worldPt) return null;+ const cx = shape.x + shape.width / 2;+ const cy = shape.y + shape.height / 2;+ const dx = worldPt.x - cx;+ const dy = worldPt.y - cy;+ const rx = Math.max(1, shape.width / 2);+ const ry = Math.max(1, shape.height / 2);+ const normDist = Math.hypot(dx / rx, dy / ry);++ let focusAngle = null;+ if (normDist >= 0.35 || (Math.abs(dx) > 0.001 || Math.abs(dy) > 0.001)) {+ focusAngle = Math.atan2(dy, dx);+ }+ const coreCenter = normDist < 0.35;+ return {+ elementId: shape.id,+ focusAngle,+ coreCenter,+ side: angleToSide(focusAngle ?? 0),+ gap: 4+ };+ }++ function getBindingBoundaryPoint(shape, binding, fallbackRefPt, gap = 4) {+ if (!shape) return fallbackRefPt || { x: 0, y: 0 };+ const cx = shape.x + shape.width / 2;+ const cy = shape.y + shape.height / 2;++ let theta = 0;+ if (binding && typeof binding.focusAngle === 'number' && !Number.isNaN(binding.focusAngle) && !binding.coreCenter) {+ theta = binding.focusAngle;+ } else if (fallbackRefPt && (Math.abs(fallbackRefPt.x - cx) > 0.01 || Math.abs(fallbackRefPt.y - cy) > 0.01)) {+ theta = Math.atan2(fallbackRefPt.y - cy, fallbackRefPt.x - cx);+ } else if (binding && typeof binding.focusAngle === 'number') {+ theta = binding.focusAngle;+ }++ const ux = Math.cos(theta);+ const uy = Math.sin(theta);+ const g = (binding && typeof binding.gap === 'number') ? binding.gap : (Number(gap) || 0);+ const hw = Math.max(1, shape.width / 2 + g);+ const hh = Math.max(1, shape.height / 2 + g);++ if (shape.type === 'ellipse') {+ const denom = Math.hypot(ux / hw, uy / hh) || 1;+ const t = 1 / denom;+ return { x: cx + t * ux, y: cy + t * uy, angle: theta };+ }++ if (shape.type === 'diamond') {+ const denom = (Math.abs(ux) / hw + Math.abs(uy) / hh) || 1;+ const t = 1 / denom;+ return { x: cx + t * ux, y: cy + t * uy, angle: theta };+ }++ const tx = Math.abs(ux) > 1e-9 ? hw / Math.abs(ux) : Infinity;+ const ty = Math.abs(uy) > 1e-9 ? hh / Math.abs(uy) : Infinity;+ const t = Math.min(tx, ty);+ return { x: cx + t * ux, y: cy + t * uy, angle: theta };+ }++ function distanceToShapeBoundary(shape, wx, wy) {+ if (!shape) return Infinity;+ const cx = shape.x + shape.width / 2;+ const cy = shape.y + shape.height / 2;+ const hw = Math.max(1, shape.width / 2);+ const hh = Math.max(1, shape.height / 2);+ const dx = wx - cx;+ const dy = wy - cy;++ if (shape.type === 'ellipse') {+ const norm = Math.hypot(dx / hw, dy / hh);+ if (norm <= 1) return 0;+ const theta = Math.atan2(dy, dx);+ const bx = cx + Math.cos(theta) * hw;+ const by = cy + Math.sin(theta) * hh;+ return Math.hypot(wx - bx, wy - by);+ }++ if (shape.type === 'diamond') {+ const l1 = Math.abs(dx) / hw + Math.abs(dy) / hh;+ if (l1 <= 1) return 0;+ const pt = getBindingBoundaryPoint(shape, { focusAngle: Math.atan2(dy, dx), gap: 0 }, null, 0);+ return Math.hypot(wx - pt.x, wy - pt.y);+ }++ const clampedX = Math.max(shape.x, Math.min(shape.x + shape.width, wx));+ const clampedY = Math.max(shape.y, Math.min(shape.y + shape.height, wy));+ return Math.hypot(wx - clampedX, wy - clampedY);+ }++ function findMagneticShape(wx, wy, excludeId = null) {+ const snapRadius = 42 / (state.zoom || 1);+ let bestShape = null;+ let bestScore = Infinity;++ for (let i = state.elements.length - 1; i >= 0; i--) {+ const el = state.elements[i];+ if (!isNodeElement(el) || el.id === excludeId) continue;+ const d = distanceToShapeBoundary(el, wx, wy);+ if (d <= snapRadius && d < bestScore) {+ bestScore = d;+ bestShape = el;+ }+ }+ return bestShape;+ }++ function getElementMap(elements = state.elements) {+ const map = new Map();+ for (const el of elements) map.set(el.id, el);+ return map;+ }++ function getArrowGeometry(el, elementsMap = null) {+ const map = elementsMap || getElementMap();+ const startShape = el.startBinding?.elementId ? map.get(el.startBinding.elementId) : null;+ const endShape = el.endBinding?.elementId ? map.get(el.endBinding.elementId) : null;++ let rawP0 = { x: Number(el.x) || 0, y: Number(el.y) || 0 };+ let rawP1 = {+ x: typeof el.x2 === 'number' ? el.x2 : (rawP0.x + (Number(el.width) || 120)),+ y: typeof el.y2 === 'number' ? el.y2 : (rawP0.y + (Number(el.height) || 0))+ };++ const startCenter = startShape+ ? { x: startShape.x + startShape.width / 2, y: startShape.y + startShape.height / 2 }+ : rawP0;+ const endCenter = endShape+ ? { x: endShape.x + endShape.width / 2, y: endShape.y + endShape.height / 2 }+ : rawP1;++ const p0 = startShape+ ? getBindingBoundaryPoint(startShape, el.startBinding, endShape ? endCenter : rawP1, 4)+ : rawP0;+ const p1 = endShape+ ? getBindingBoundaryPoint(endShape, el.endBinding, startShape ? startCenter : p0, 4)+ : rawP1;++ el.x = p0.x;+ el.y = p0.y;+ el.x2 = p1.x;+ el.y2 = p1.y;+ el.width = p1.x - p0.x;+ el.height = p1.y - p0.y;++ const chordDx = p1.x - p0.x;+ const chordDy = p1.y - p0.y;+ const chordLen = Math.hypot(chordDx, chordDy) || 1;+ const nx = -chordDy / chordLen;+ const ny = chordDx / chordLen;+ const midX = (p0.x + p1.x) / 2;+ const midY = (p0.y + p1.y) / 2;++ const curveType = el.curveType || 'curved';+ const curveOffset = curveType === 'straight' ? 0 : (Number(el.curveOffset) || 0);+ const cp = {+ x: midX + nx * curveOffset,+ y: midY + ny * curveOffset+ };+ const curveHandlePt = {+ x: midX + nx * (curveOffset * 0.5),+ y: midY + ny * (curveOffset * 0.5)+ };++ const N = 40;+ const samples = [];+ const cumLen = new Float64Array(N + 1);+ let totalLen = 0;++ if (curveType === 'elbow') {+ const elbowX = midX + (Number(el.curveOffset) || 0) * 0.5;+ const waypoints = [+ { x: p0.x, y: p0.y },+ { x: elbowX, y: p0.y },+ { x: elbowX, y: p1.y },+ { x: p1.x, y: p1.y }+ ];+ const segLens = [];+ let polyLen = 0;+ for (let i = 0; i < waypoints.length - 1; i++) {+ const sl = Math.hypot(waypoints[i + 1].x - waypoints[i].x, waypoints[i + 1].y - waypoints[i].y);+ segLens.push(sl);+ polyLen += sl;+ }+ polyLen = Math.max(1, polyLen);++ for (let i = 0; i <= N; i++) {+ const targetD = (i / N) * polyLen;+ let acc = 0;+ let pt = { x: p1.x, y: p1.y, tx: 1, ty: 0 };+ for (let s = 0; s < segLens.length; s++) {+ const sl = segLens[s];+ if (acc + sl >= targetD || s === segLens.length - 1) {+ const localT = sl > 1e-6 ? Math.max(0, Math.min(1, (targetD - acc) / sl)) : 0;+ const a = waypoints[s];+ const b = waypoints[s + 1];+ const tx = sl > 1e-6 ? (b.x - a.x) / sl : 1;+ const ty = sl > 1e-6 ? (b.y - a.y) / sl : 0;+ pt = {+ x: a.x + (b.x - a.x) * localT,+ y: a.y + (b.y - a.y) * localT,+ tx,+ ty+ };+ break;+ }+ acc += sl;+ }+ samples.push(pt);+ if (i > 0) {+ totalLen += Math.hypot(pt.x - samples[i - 1].x, pt.y - samples[i - 1].y);+ }+ cumLen[i] = totalLen;+ }+ curveHandlePt.x = elbowX;+ curveHandlePt.y = (p0.y + p1.y) / 2;+ } else {+ for (let i = 0; i <= N; i++) {+ const t = i / N;+ const mt = 1 - t;+ const x = mt * mt * p0.x + 2 * mt * t * cp.x + t * t * p1.x;+ const y = mt * mt * p0.y + 2 * mt * t * cp.y + t * t * p1.y;+ const dxdt = 2 * mt * (cp.x - p0.x) + 2 * t * (p1.x - cp.x);+ const dydt = 2 * mt * (cp.y - p0.y) + 2 * t * (p1.y - cp.y);+ const dLen = Math.hypot(dxdt, dydt) || 1;+ const pt = { x, y, tx: dxdt / dLen, ty: dydt / dLen };+ samples.push(pt);+ if (i > 0) {+ totalLen += Math.hypot(x - samples[i - 1].x, y - samples[i - 1].y);+ }+ cumLen[i] = totalLen;+ }+ }++ const midDist = totalLen * 0.5;+ const labelPt = pointAtArcLength({ samples, cumLen, totalLen }, midDist);++ // Arrows are always unbroken and clean — no text or gaps cut in between them+ return {+ p0,+ p1,+ cp,+ curveHandlePt,+ samples,+ cumLen,+ totalLen: Math.max(1, totalLen),+ labelPt,+ labelBox: null,+ gapStartDist: -1,+ gapEndDist: -1+ };+ }++ function pointAtArcLength(geom, dist) {+ const samples = geom.samples;+ const cumLen = geom.cumLen;+ const N = samples.length - 1;+ if (N <= 0) return { x: 0, y: 0, tx: 1, ty: 0 };+ const clamped = Math.max(0, Math.min(geom.totalLen, dist));+ let lo = 0;+ let hi = N;+ while (lo < hi) {+ const mid = (lo + hi) >> 1;+ if (cumLen[mid] < clamped) lo = mid + 1;+ else hi = mid;+ }+ const idx = Math.max(1, lo);+ const d0 = cumLen[idx - 1];+ const d1 = cumLen[idx];+ const seg = d1 - d0;+ const f = seg > 1e-6 ? (clamped - d0) / seg : 0;+ const a = samples[idx - 1];+ const b = samples[idx];+ return {+ x: a.x + (b.x - a.x) * f,+ y: a.y + (b.y - a.y) * f,+ tx: a.tx + (b.tx - a.tx) * f,+ ty: a.ty + (b.ty - a.ty) * f+ };+ }++ /* -------------------------------------------------------------------------+ * 5. Causal Topological Wave Timing (BFS computeGraphDepths) & Node Pulses+ * ------------------------------------------------------------------------- */+ function computeGraphDepths(elements = state.elements) {+ const nodeDepths = new Map();+ const arrowDepths = new Map();+ const adj = new Map();+ const inDeg = new Map();++ const nodes = elements.filter(isNodeElement);+ const arrows = elements.filter(e => e.type === 'arrow');++ for (const n of nodes) {+ adj.set(n.id, []);+ inDeg.set(n.id, 0);+ }++ for (const arr of arrows) {+ const u = arr.startBinding?.elementId;+ const v = arr.endBinding?.elementId;+ if (u && v && adj.has(u) && adj.has(v)) {+ adj.get(u).push({ target: v, arrowId: arr.id });+ inDeg.set(v, (inDeg.get(v) || 0) + 1);+ }+ }++ const queue = [];+ for (const n of nodes) {+ if ((inDeg.get(n.id) || 0) === 0) {+ nodeDepths.set(n.id, 0);+ queue.push(n.id);+ }+ }++ if (queue.length === 0 && nodes.length > 0) {+ nodeDepths.set(nodes[0].id, 0);+ queue.push(nodes[0].id);+ }++ let head = 0;+ while (head < queue.length) {+ const u = queue[head++];+ const d = nodeDepths.get(u) || 0;+ const edges = adj.get(u) || [];+ for (const edge of edges) {+ arrowDepths.set(edge.arrowId, d);+ if (!nodeDepths.has(edge.target)) {+ nodeDepths.set(edge.target, d + 1);+ queue.push(edge.target);+ }+ }+ }++ for (const n of nodes) {+ if (!nodeDepths.has(n.id)) nodeDepths.set(n.id, 0);+ }+ for (const arr of arrows) {+ if (!arrowDepths.has(arr.id)) {+ const u = arr.startBinding?.elementId;+ arrowDepths.set(arr.id, u && nodeDepths.has(u) ? nodeDepths.get(u) : 0);+ }+ }++ return { nodeDepths, arrowDepths };+ }++ function triggerNodePulse(nodeId) {+ const targetIds = nodeId ? [nodeId] : Array.from(state.selectedIds);+ let spawned = 0;+ const now = performance.now() / 1000;++ for (const id of targetIds) {+ const outgoing = state.elements.filter(+ el => el.type === 'arrow' && el.startBinding?.elementId === id+ );+ const targetArrows = outgoing.length > 0+ ? outgoing+ : state.elements.filter(el => el.type === 'arrow' && el.id === id);++ for (const arr of targetArrows) {+ for (let b = 0; b < 3; b++) {+ state.activePulses.push({+ id: nextId('pulse'),+ arrowId: arr.id,+ progress: -b * 0.14,+ speed: 1.35,+ color: arr.strokeColor || '#0070f3',+ createdAt: now+ });+ spawned++;+ }+ }+ }+ return spawned;+ }++ /* -------------------------------------------------------------------------+ * 6. Multi-Pass Occlusion-Free Rendering Engine+ * ------------------------------------------------------------------------- */+ // Exact Excalidraw dash array formulas from packages/element/src/shape.ts+ function applyDashStyle(ctx, strokeStyle, strokeWidth) {+ const sw = Number(strokeWidth) || 2;+ if (strokeStyle === 'dashed') {+ ctx.setLineDash([8, 8 + sw]);+ } else if (strokeStyle === 'dotted') {+ ctx.setLineDash([1.5, 6 + sw]);+ } else {+ ctx.setLineDash([]);+ }+ }++ function drawStaticElement(ctx, el, opts = {}) {+ if (!el || el.type === 'arrow') return;+ const canvasBg = opts.canvasBg || state.canvasBg;+ const strokeColor = resolveStrokeColor(el.strokeColor, canvasBg);+ const fillTint = resolveFillTint(el.strokeColor, canvasBg, el.type === 'sticky');+ const sw = Number(el.strokeWidth) || 2.2;++ ctx.save();+ ctx.lineCap = 'round';+ ctx.lineJoin = 'round';++ const auraEnergy = state.nodeArrivalEnergy.get(el.id) || 0;+ if (auraEnergy > 0.02 && isNodeElement(el) && el.type !== 'text') {+ ctx.save();+ ctx.shadowColor = strokeColor;+ ctx.shadowBlur = 16 * auraEnergy;+ ctx.strokeStyle = strokeColor;+ ctx.globalAlpha = Math.min(0.45, auraEnergy * 0.45);+ ctx.lineWidth = sw + 2;+ const paths = ShapeCache.get(el);+ ctx.stroke(paths.fillPath);+ ctx.restore();+ }++ if (el.type === 'freedraw') {+ const pts = el.points || [];+ if (pts.length > 0) {+ ctx.strokeStyle = strokeColor;+ ctx.lineWidth = sw;+ applyDashStyle(ctx, el.strokeStyle, sw);+ ctx.beginPath();+ ctx.moveTo(el.x + pts[0][0], el.y + pts[0][1]);+ for (let i = 1; i < pts.length; i++) {+ const pPrev = pts[i - 1];+ const pCurr = pts[i];+ const mx = el.x + (pPrev[0] + pCurr[0]) / 2;+ const my = el.y + (pPrev[1] + pCurr[1]) / 2;+ ctx.quadraticCurveTo(el.x + pPrev[0], el.y + pPrev[1], mx, my);+ }+ const last = pts[pts.length - 1];+ ctx.lineTo(el.x + last[0], el.y + last[1]);+ ctx.stroke();+ }+ ctx.restore();+ return;+ }++ if (el.type === 'text') {+ ctx.restore();+ return;+ }++ const paths = ShapeCache.get(el);+ const fillStyle = el.fillStyle || 'hachure';++ if (fillStyle !== 'none') {+ ctx.save();+ ctx.fillStyle = fillTint;+ if (el.type === 'sticky') {+ ctx.shadowColor = 'rgba(0, 0, 0, 0.14)';+ ctx.shadowBlur = 12;+ ctx.shadowOffsetY = 4;+ }+ ctx.fill(paths.fillPath);+ ctx.restore();+ }++ if (fillStyle === 'hachure' || fillStyle === 'cross-hatch') {+ ctx.save();+ ctx.clip(paths.fillPath);+ ctx.strokeStyle = strokeColor;+ ctx.globalAlpha = canvasBg === '#000000' ? 0.44 : 0.36;+ // Excalidraw shape.ts: fillWeight = element.strokeWidth / 2+ ctx.lineWidth = Math.max(1.0, sw * 0.5);+ ctx.setLineDash([]);+ ctx.stroke(paths.hachurePath);+ ctx.restore();+ }++ ctx.strokeStyle = strokeColor;+ // Excalidraw shape.ts: for non-solid strokes, increase width by +0.5+ ctx.lineWidth = (el.strokeStyle && el.strokeStyle !== 'solid') ? sw + 0.5 : sw;+ applyDashStyle(ctx, el.strokeStyle, sw);+ ctx.stroke(paths.strokePath);++ ctx.restore();+ }++ function drawArrowAndParticles(ctx, el, geom, depth, timeSec, opts = {}) {+ const canvasBg = opts.canvasBg || state.canvasBg;+ const isSplitTarget = state.splitTargetArrowId === el.id;+ const strokeColor = isSplitTarget ? '#10b981' : resolveStrokeColor(el.strokeColor, canvasBg);+ const baseSw = Number(el.strokeWidth) || 2.2;+ const sw = isSplitTarget ? Math.max(3.2, baseSw + 1.2) : baseSw;++ ctx.save();+ ctx.lineCap = 'round';+ ctx.lineJoin = 'round';+ ctx.strokeStyle = strokeColor;+ ctx.lineWidth = (el.strokeStyle && el.strokeStyle !== 'solid') ? sw + 0.5 : sw;+ applyDashStyle(ctx, el.strokeStyle, sw);++ if (isSplitTarget) {+ ctx.shadowColor = '#10b981';+ ctx.shadowBlur = 12;+ }++ const samples = geom.samples;+ ctx.beginPath();+ for (let i = 0; i < samples.length; i++) {+ if (i === 0) ctx.moveTo(samples[i].x, samples[i].y);+ else ctx.lineTo(samples[i].x, samples[i].y);+ }+ ctx.stroke();++ // Excalidraw solid hand-drawn arrows have a subtle organic second pass+ const roughness = el.roughness ?? 0.85;+ if (roughness > 0.01 && (!el.strokeStyle || el.strokeStyle === 'solid') && (el.curveType || 'curved') !== 'elbow') {+ const rng = mulberry32((Number(el.seed) || 1) + 77);+ const jit = roughness * 1.1;+ ctx.save();+ ctx.lineWidth = Math.max(1.2, sw * 0.85);+ ctx.globalAlpha = 0.78;+ ctx.beginPath();+ ctx.moveTo(geom.p0.x + (rng() - 0.5) * jit, geom.p0.y + (rng() - 0.5) * jit);+ ctx.quadraticCurveTo(+ geom.cp.x + (rng() - 0.5) * jit * 2.2,+ geom.cp.y + (rng() - 0.5) * jit * 2.2,+ geom.p1.x + (rng() - 0.5) * jit * 0.5,+ geom.p1.y + (rng() - 0.5) * jit * 0.5+ );+ ctx.stroke();+ ctx.restore();+ }++ // Excalidraw solid arrowhead cap (~25 degree spread)+ ctx.setLineDash([]);+ const endSample = samples[samples.length - 1];+ const tipAngle = Math.atan2(endSample.ty, endSample.tx);+ const headLen = Math.max(11, sw * 4.6);+ const spread = 0.44;+ ctx.beginPath();+ ctx.moveTo(+ geom.p1.x - headLen * Math.cos(tipAngle - spread),+ geom.p1.y - headLen * Math.sin(tipAngle - spread)+ );+ ctx.lineTo(geom.p1.x, geom.p1.y);+ ctx.lineTo(+ geom.p1.x - headLen * Math.cos(tipAngle + spread),+ geom.p1.y - headLen * Math.sin(tipAngle + spread)+ );+ ctx.stroke();++ const arrowFlowActive = state.flowEnabled && (el.flowEnabled !== false);+ if (arrowFlowActive && geom.totalLen > 24) {+ const packetCount = Math.max(1, Math.min(4, Math.round(geom.totalLen / 150)));+ const speed = (Number(state.flowSpeed) || 1.0) * 0.55;+ const hopOffset = -(Number(depth) || 0) * 0.38;+ const mode = state.flowMode || 'comets';++ for (let k = 0; k < packetCount; k++) {+ let phase = (timeSec * speed + hopOffset + k / packetCount) % 1;+ if (phase < 0) phase += 1;++ if (phase > 0.82 && el.endBinding?.elementId) {+ const boost = (phase - 0.82) / 0.18;+ const prev = state.nodeArrivalEnergy.get(el.endBinding.elementId) || 0;+ state.nodeArrivalEnergy.set(el.endBinding.elementId, Math.max(prev, Math.sin(boost * Math.PI)));+ }++ const dist = phase * geom.totalLen;+ drawFlowParticleAt(ctx, geom, dist, phase, strokeColor, sw, mode, canvasBg);+ }+ }++ for (let i = state.activePulses.length - 1; i >= 0; i--) {+ const pulse = state.activePulses[i];+ if (pulse.arrowId !== el.id) continue;+ if (pulse.progress >= 0 && pulse.progress <= 1) {+ const dist = pulse.progress * geom.totalLen;+ drawFlowParticleAt(ctx, geom, dist, pulse.progress, strokeColor, sw * 1.45, 'neon', canvasBg, true);+ if (pulse.progress > 0.8 && el.endBinding?.elementId) {+ state.nodeArrivalEnergy.set(el.endBinding.elementId, 1.0);+ }+ }+ }++ ctx.restore();+ }++ function drawFlowParticleAt(ctx, geom, dist, phase, color, sw, mode, canvasBg, isBurst = false) {+ const pt = pointAtArcLength(geom, dist);+ const isDark = canvasBg === '#000000';+ const coreColor = isDark || isBurst ? '#ffffff' : color;++ ctx.save();+ if (mode === 'comets') {+ const tailLen = Math.min(34, geom.totalLen * 0.22);+ const segs = 7;+ for (let s = 0; s < segs; s++) {+ const d0 = Math.max(0, dist - (s / segs) * tailLen);+ const d1 = Math.max(0, dist - ((s + 1) / segs) * tailLen);+ if (d0 <= d1) continue;+ const pA = pointAtArcLength(geom, d0);+ const pB = pointAtArcLength(geom, d1);+ const frac = 1 - s / segs;+ ctx.beginPath();+ ctx.strokeStyle = color;+ ctx.globalAlpha = frac * (isDark ? 0.92 : 0.82);+ ctx.lineWidth = Math.max(1.2, sw * 2.1 * frac);+ ctx.moveTo(pA.x, pA.y);+ ctx.lineTo(pB.x, pB.y);+ ctx.stroke();+ }+ ctx.beginPath();+ ctx.shadowColor = color;+ ctx.shadowBlur = isDark ? 14 : 8;+ ctx.fillStyle = coreColor;+ ctx.arc(pt.x, pt.y, Math.max(2.8, sw * 1.35), 0, Math.PI * 2);+ ctx.fill();+ } else if (mode === 'pulses') {+ const ringExpand = (phase * 4) % 1;+ ctx.beginPath();+ ctx.strokeStyle = color;+ ctx.globalAlpha = (1 - ringExpand) * 0.75;+ ctx.lineWidth = 1.8;+ ctx.arc(pt.x, pt.y, 3 + ringExpand * 11, 0, Math.PI * 2);+ ctx.stroke();++ ctx.beginPath();+ ctx.fillStyle = color;+ ctx.arc(pt.x, pt.y, Math.max(3, sw * 1.3), 0, Math.PI * 2);+ ctx.fill();+ } else if (mode === 'neon') {+ const tailLen = Math.min(28, geom.totalLen * 0.18);+ const pTail = pointAtArcLength(geom, Math.max(0, dist - tailLen));+ ctx.beginPath();+ ctx.shadowColor = color;+ ctx.shadowBlur = isDark ? 18 : 12;+ ctx.strokeStyle = color;+ ctx.lineWidth = sw * 2.6;+ ctx.globalAlpha = 0.85;+ ctx.moveTo(pTail.x, pTail.y);+ ctx.lineTo(pt.x, pt.y);+ ctx.stroke();++ ctx.beginPath();+ ctx.strokeStyle = '#ffffff';+ ctx.lineWidth = Math.max(1.4, sw * 0.95);+ ctx.globalAlpha = 0.95;+ ctx.moveTo(pTail.x, pTail.y);+ ctx.lineTo(pt.x, pt.y);+ ctx.stroke();+ } else if (mode === 'dashed') {+ const segLen = 10;+ const pBack = pointAtArcLength(geom, Math.max(0, dist - segLen));+ ctx.beginPath();+ ctx.strokeStyle = color;+ ctx.lineWidth = sw * 1.9;+ ctx.moveTo(pBack.x, pBack.y);+ ctx.lineTo(pt.x, pt.y);+ ctx.stroke();+ }+ ctx.restore();+ }++ function drawElementText(ctx, el, opts = {}) {+ // Never render text on arrows+ if (!el || el.type === 'arrow' || !el.text || String(el.text).trim().length === 0) return;+ if (state.editingId === el.id && !opts.forExport) return;++ const canvasBg = opts.canvasBg || state.canvasBg;+ const strokeColor = resolveStrokeColor(el.strokeColor, canvasBg);+ const fontSize = Number(el.fontSize) || 16;+ const lineHeight = Math.round(fontSize * EXCALIDRAW_LINE_HEIGHT);+ const lines = String(el.text).split('\n');++ ctx.save();+ ctx.font = getFontCss(el.fontFamily, fontSize);+ ctx.textAlign = 'center';+ ctx.textBaseline = 'middle';++ const centerX = el.x + (el.width || 0) / 2;+ const centerY = el.y + (el.height || 0) / 2;+ const totalTextH = lines.length * lineHeight;+ const startY = centerY - totalTextH / 2 + lineHeight / 2;++ ctx.fillStyle = strokeColor;+ for (let i = 0; i < lines.length; i++) {+ ctx.fillText(lines[i], centerX, startY + i * lineHeight);+ }++ ctx.restore();+ }++ function renderScenePasses(ctx, timeSec = 0, opts = {}) {+ const elements = opts.elements || state.elements;+ const elementsMap = getElementMap(elements);+ const { arrowDepths } = computeGraphDepths(elements);++ for (const [nodeId, val] of state.nodeArrivalEnergy.entries()) {+ const nextVal = val * 0.91;+ if (nextVal < 0.01) state.nodeArrivalEnergy.delete(nodeId);+ else state.nodeArrivalEnergy.set(nodeId, nextVal);+ }++ const arrowGeoms = new Map();+ for (const el of elements) {+ if (el.type === 'arrow') {+ arrowGeoms.set(el.id, getArrowGeometry(el, elementsMap));+ }+ }++ for (const el of elements) {+ if (el.type !== 'arrow') {+ drawStaticElement(ctx, el, opts);+ }+ }++ for (const el of elements) {+ if (el.type === 'arrow') {+ const geom = arrowGeoms.get(el.id);+ const depth = arrowDepths.get(el.id) || 0;+ drawArrowAndParticles(ctx, el, geom, depth, timeSec, opts);+ }+ }++ for (const el of elements) {+ if (el.type !== 'arrow') {+ drawElementText(ctx, el, opts);+ }+ }++ return arrowGeoms;+ }++ /* -------------------------------------------------------------------------+ * 7. Hit Testing, 8-Way Resize Handles, Ports & Inline Node Splitting+ * ------------------------------------------------------------------------- */+ function getResizeHandles(el) {+ if (!isNodeElement(el) || el.type === 'text') return [];+ const pad = 6 / (state.zoom || 1);+ const x = el.x - pad;+ const y = el.y - pad;+ const w = (el.width || 0) + pad * 2;+ const h = (el.height || 0) + pad * 2;+ return [+ { dir: 'nw', x: x, y: y, cursor: 'nwse-resize' },+ { dir: 'n', x: x + w / 2, y: y, cursor: 'ns-resize' },+ { dir: 'ne', x: x + w, y: y, cursor: 'nesw-resize' },+ { dir: 'e', x: x + w, y: y + h / 2, cursor: 'ew-resize' },+ { dir: 'se', x: x + w, y: y + h, cursor: 'nwse-resize' },+ { dir: 's', x: x + w / 2, y: y + h, cursor: 'ns-resize' },+ { dir: 'sw', x: x, y: y + h, cursor: 'nesw-resize' },+ { dir: 'w', x: x, y: y + h / 2, cursor: 'ew-resize' }+ ];+ }++ function hitTestResizeHandles(wx, wy) {+ if (state.selectedIds.size !== 1) return null;+ const id = Array.from(state.selectedIds)[0];+ const el = state.elements.find(e => e.id === id);+ if (!el || !isNodeElement(el) || el.type === 'text') return null;++ const tol = 8 / (state.zoom || 1);+ for (const h of getResizeHandles(el)) {+ if (Math.hypot(wx - h.x, wy - h.y) <= tol) {+ return { elementId: el.id, dir: h.dir, cursor: h.cursor };+ }+ }+ return null;+ }++ function getQuickConnectPorts(el) {+ if (!isNodeElement(el) || el.type === 'text') return [];+ const gap = 18 / (state.zoom || 1);+ const cx = el.x + el.width / 2;+ const cy = el.y + el.height / 2;+ return [+ { dir: 'top', x: cx, y: el.y - gap, angle: -Math.PI / 2 },+ { dir: 'right', x: el.x + el.width + gap, y: cy, angle: 0 },+ { dir: 'bottom', x: cx, y: el.y + el.height + gap, angle: Math.PI / 2 },+ { dir: 'left', x: el.x - gap, y: cy, angle: Math.PI }+ ];+ }++ function hitTestQuickPorts(wx, wy) {+ const candidateIds = new Set(state.selectedIds);+ if (state.hoveredId) candidateIds.add(state.hoveredId);+ const hitRadius = 12 / (state.zoom || 1);++ for (const id of candidateIds) {+ const el = state.elements.find(e => e.id === id);+ if (!el || !isNodeElement(el) || el.type === 'text') continue;+ const ports = getQuickConnectPorts(el);+ for (const p of ports) {+ if (Math.hypot(wx - p.x, wy - p.y) <= hitRadius) {+ return { elementId: el.id, dir: p.dir, x: p.x, y: p.y };+ }+ }+ }+ return null;+ }++ function hitTestArrowHandle(wx, wy) {+ const radius = 18 / (state.zoom || 1);+ const elementsMap = getElementMap();++ const arrows = state.elements.filter(e => e.type === 'arrow');+ arrows.sort((a, b) => {+ const aPri = (state.selectedIds.has(a.id) || state.hoveredId === a.id) ? 1 : 0;+ const bPri = (state.selectedIds.has(b.id) || state.hoveredId === b.id) ? 1 : 0;+ return bPri - aPri;+ });++ for (const arr of arrows) {+ const geom = getArrowGeometry(arr, elementsMap);+ if (Math.hypot(wx - geom.p0.x, wy - geom.p0.y) <= radius) {+ return { elementId: arr.id, handle: 'start', point: geom.p0 };+ }+ if (Math.hypot(wx - geom.p1.x, wy - geom.p1.y) <= radius) {+ return { elementId: arr.id, handle: 'end', point: geom.p1 };+ }+ if (Math.hypot(wx - geom.curveHandlePt.x, wy - geom.curveHandlePt.y) <= radius) {+ return { elementId: arr.id, handle: 'curve', point: geom.curveHandlePt };+ }+ }+ return null;+ }++ function distanceToArrowShaft(arrow, wx, wy, elementsMap = null) {+ const geom = getArrowGeometry(arrow, elementsMap);+ let minDist = Infinity;+ const samples = geom.samples;+ for (let i = 0; i < samples.length - 1; i++) {+ const a = samples[i];+ const b = samples[i + 1];+ const dx = b.x - a.x;+ const dy = b.y - a.y;+ const len2 = dx * dx + dy * dy;+ const t = len2 > 1e-6 ? Math.max(0, Math.min(1, ((wx - a.x) * dx + (wy - a.y) * dy) / len2)) : 0;+ const px = a.x + t * dx;+ const py = a.y + t * dy;+ const d = Math.hypot(wx - px, wy - py);+ if (d < minDist) minDist = d;+ }+ return minDist;+ }++ function hitTestElement(wx, wy) {+ const elementsMap = getElementMap();+ const arrowTol = 11 / (state.zoom || 1);++ for (let i = state.elements.length - 1; i >= 0; i--) {+ const el = state.elements[i];+ if (el.type === 'arrow') {+ if (distanceToArrowShaft(el, wx, wy, elementsMap) <= arrowTol) {+ return el;+ }+ continue;+ }+ if (el.type === 'freedraw') {+ const pts = el.points || [];+ for (const p of pts) {+ if (Math.hypot(wx - (el.x + p[0]), wy - (el.y + p[1])) <= 10 / (state.zoom || 1)) {+ return el;+ }+ }+ continue;+ }+ if (el.type === 'ellipse') {+ const cx = el.x + el.width / 2;+ const cy = el.y + el.height / 2;+ const rx = Math.max(4, el.width / 2 + 4);+ const ry = Math.max(4, el.height / 2 + 4);+ if (((wx - cx) / rx) ** 2 + ((wy - cy) / ry) ** 2 <= 1) return el;+ continue;+ }+ if (el.type === 'diamond') {+ const cx = el.x + el.width / 2;+ const cy = el.y + el.height / 2;+ const hw = Math.max(4, el.width / 2 + 4);+ const hh = Math.max(4, el.height / 2 + 4);+ if (Math.abs(wx - cx) / hw + Math.abs(wy - cy) / hh <= 1) return el;+ continue;+ }+ if (wx >= el.x && wx <= el.x + el.width && wy >= el.y && wy <= el.y + el.height) {+ return el;+ }+ }+ return null;+ }++ function findSplitTargetArrow(node) {+ if (!node || !isNodeElement(node) || node.type === 'text') return null;+ const cx = node.x + node.width / 2;+ const cy = node.y + node.height / 2;+ const elementsMap = getElementMap();+ const threshold = Math.min(node.width, node.height) * 0.45;++ for (const el of state.elements) {+ if (el.type !== 'arrow') continue;+ if (el.startBinding?.elementId === node.id || el.endBinding?.elementId === node.id) continue;+ const d = distanceToArrowShaft(el, cx, cy, elementsMap);+ if (d <= threshold) return el;+ }+ return null;+ }++ function trySplitArrowWithNode(node) {+ const arrow = findSplitTargetArrow(node);+ if (!arrow) return false;++ const origEndBinding = arrow.endBinding ? { ...arrow.endBinding } : null;+ const origX2 = arrow.x2;+ const origY2 = arrow.y2;++ const nodeCenter = { x: node.x + node.width / 2, y: node.y + node.height / 2 };+ const geom = getArrowGeometry(arrow);++ arrow.endBinding = computeBindingForShape(node, geom.p0);+ arrow.curveOffset = 0;++ const newArrow = createElement('arrow', {+ x: nodeCenter.x,+ y: nodeCenter.y,+ x2: origX2,+ y2: origY2,+ strokeColor: arrow.strokeColor,+ strokeWidth: arrow.strokeWidth,+ strokeStyle: arrow.strokeStyle,+ curveType: arrow.curveType,+ curveOffset: 0,+ startBinding: computeBindingForShape(node, geom.p1),+ endBinding: origEndBinding,+ flowEnabled: arrow.flowEnabled !== false+ });++ state.elements.push(newArrow);+ state.splitTargetArrowId = null;+ return true;+ }++ /* -------------------------------------------------------------------------+ * 8. Auto-Fitting Multi-Line Text & Element Factory+ * ------------------------------------------------------------------------- */+ let measureCtx = null;+ function getMeasureCtx() {+ if (!measureCtx && typeof document !== 'undefined') {+ const c = document.createElement('canvas');+ measureCtx = c.getContext('2d');+ }+ return measureCtx;+ }++ function autoFitElementToText(el, text) {+ if (!el || el.type === 'arrow') return;+ el.text = text;+ const lines = String(text || '').split('\n');+ const fontSize = Number(el.fontSize) || 15;+ const lineHeight = Math.round(fontSize * EXCALIDRAW_LINE_HEIGHT);++ const mCtx = getMeasureCtx();+ let maxLineW = 0;+ if (mCtx) {+ mCtx.font = getFontCss(el.fontFamily, fontSize);+ for (const line of lines) {+ maxLineW = Math.max(maxLineW, mCtx.measureText(line || ' ').width);+ }+ } else {+ for (const line of lines) {+ maxLineW = Math.max(maxLineW, (line || '').length * fontSize * 0.58);+ }+ }++ const cx = el.x + el.width / 2;+ const cy = el.y + el.height / 2;+ const padX = el.type === 'diamond' ? Math.max(56, maxLineW * 0.65) : (el.type === 'ellipse' ? 42 : 32);+ const padY = el.type === 'diamond' ? Math.max(44, lines.length * lineHeight * 0.65) : 28;+ const minW = el.type === 'text' ? 40 : 110;+ const minH = el.type === 'text' ? 26 : 54;++ const nextW = Math.max(el.width || minW, minW, Math.ceil(maxLineW + padX));+ const nextH = Math.max(el.height || minH, minH, Math.ceil(lines.length * lineHeight + padY));++ if (nextW !== el.width || nextH !== el.height) {+ el.width = nextW;+ el.height = nextH;+ el.x = cx - nextW / 2;+ el.y = cy - nextH / 2;+ ShapeCache.invalidate(el);+ }+ }++ function createElement(type, props = {}) {+ const d = state.defaults;+ const seed = props.seed || Math.floor(Math.random() * 1000000) + 1;+ const base = {+ id: props.id || nextId(type),+ type,+ x: props.x ?? 0,+ y: props.y ?? 0,+ width: props.width ?? (type === 'sticky' ? 150 : (type === 'diamond' ? 148 : 144)),+ height: props.height ?? (type === 'sticky' ? 110 : (type === 'diamond' ? 86 : 68)),+ strokeColor: props.strokeColor || d.strokeColor,+ fillStyle: props.fillStyle ?? (type === 'sticky' ? 'solid' : d.fillStyle),+ fontFamily: normalizeFontFamily(props.fontFamily || d.fontFamily),+ fontSize: Number(props.fontSize || d.fontSize),+ roughness: props.roughness !== undefined ? Number(props.roughness) : d.roughness,+ strokeWidth: Number(props.strokeWidth || d.strokeWidth),+ strokeStyle: props.strokeStyle || d.strokeStyle,+ curveType: props.curveType || d.curveType,+ curveOffset: Number(props.curveOffset) || 0,+ text: type === 'arrow' ? '' : (props.text ?? ''),+ seed,+ versionNonce: 1,+ flowEnabled: props.flowEnabled !== false,+ startBinding: props.startBinding || null,+ endBinding: props.endBinding || null,+ x2: props.x2,+ y2: props.y2,+ points: props.points || []+ };+ if (base.text && isNodeElement(base)) {+ autoFitElementToText(base, base.text);+ }+ return base;+ }++ /* -------------------------------------------------------------------------+ * 9. History Stack (Undo / Redo)+ * ------------------------------------------------------------------------- */+ function snapshotScene() {+ return JSON.stringify(state.elements);+ }++ function pushHistory(customSnap = null) {+ const snap = customSnap || snapshotScene();+ const stack = state.history.undoStack;+ if (stack.length > 0 && stack[stack.length - 1] === snap) return;+ stack.push(snap);+ if (stack.length > 60) stack.shift();+ state.history.redoStack = [];+ updateHeaderButtons();+ }++ function discardRedundantUndoSnapshot() {+ const stack = state.history.undoStack;+ if (stack.length > 0 && stack[stack.length - 1] === snapshotScene()) {+ stack.pop();+ updateHeaderButtons();+ }+ }++ function undo() {+ const currentSnap = snapshotScene();+ while (state.history.undoStack.length > 0 && state.history.undoStack[state.history.undoStack.length - 1] === currentSnap) {+ state.history.undoStack.pop();+ }+ if (state.history.undoStack.length === 0) {+ updateHeaderButtons();+ return;+ }+ state.history.redoStack.push(currentSnap);+ const prev = state.history.undoStack.pop();+ state.elements = JSON.parse(prev);+ state.selectedIds.clear();+ ShapeCache.clear();+ updateHeaderButtons();+ syncUIWithSelection();+ }++ function redo() {+ if (state.history.redoStack.length === 0) return;+ state.history.undoStack.push(snapshotScene());+ const next = state.history.redoStack.pop();+ state.elements = JSON.parse(next);+ state.selectedIds.clear();+ ShapeCache.clear();+ updateHeaderButtons();+ syncUIWithSelection();+ }++ /* -------------------------------------------------------------------------+ * 10. Quick-Add Chaining, Tab Chaining & Starter Templates+ * ------------------------------------------------------------------------- */+ function chainNodeFrom(sourceNode, dir = 'right', type = null, openEditor = false) {+ pushHistory();+ const targetType = type || (sourceNode.type === 'text' ? 'rectangle' : sourceNode.type);+ const stepX = 220;+ const stepY = 150;+ const scx = sourceNode.x + sourceNode.width / 2;+ const scy = sourceNode.y + sourceNode.height / 2;++ let ncx = scx + stepX;+ let ncy = scy;+ let outAngle = 0;+ let inAngle = Math.PI;++ if (dir === 'left') { ncx = scx - stepX; outAngle = Math.PI; inAngle = 0; }+ else if (dir === 'top') { ncx = scx; ncy = scy - stepY; outAngle = -Math.PI / 2; inAngle = Math.PI / 2; }+ else if (dir === 'bottom') { ncx = scx; ncy = scy + stepY; outAngle = Math.PI / 2; inAngle = -Math.PI / 2; }++ const newW = targetType === 'diamond' ? 148 : 144;+ const newH = targetType === 'diamond' ? 86 : 68;+ const newNode = createElement(targetType, {+ x: ncx - newW / 2,+ y: ncy - newH / 2,+ width: newW,+ height: newH,+ strokeColor: sourceNode.strokeColor || state.defaults.strokeColor,+ fillStyle: sourceNode.fillStyle || state.defaults.fillStyle,+ fontFamily: sourceNode.fontFamily || state.defaults.fontFamily,+ fontSize: sourceNode.fontSize || state.defaults.fontSize,+ text: 'Next Step'+ });++ const newArrow = createElement('arrow', {+ x: scx,+ y: scy,+ x2: ncx,+ y2: ncy,+ strokeColor: sourceNode.strokeColor || state.defaults.strokeColor,+ startBinding: { elementId: sourceNode.id, focusAngle: outAngle, side: dir, gap: 4 },+ endBinding: { elementId: newNode.id, focusAngle: inAngle, side: angleToSide(inAngle), gap: 4 }+ });++ state.elements.push(newNode, newArrow);+ state.selectedIds.clear();+ state.selectedIds.add(newNode.id);+ syncUIWithSelection();++ if (openEditor) {+ startInlineEditing(newNode);+ }+ return newNode;+ }++ function quickAddShape(type = 'rectangle') {+ const selectedNodes = Array.from(state.selectedIds)+ .map(id => state.elements.find(e => e.id === id))+ .filter(el => el && isNodeElement(el));++ if (selectedNodes.length === 1) {+ return chainNodeFrom(selectedNodes[0], 'right', type, false);+ }++ pushHistory();+ const vw = (typeof window !== 'undefined' ? window.innerWidth : 1280);+ const vh = (typeof window !== 'undefined' ? window.innerHeight : 800);+ const centerWorld = screenToWorld(vw / 2, vh / 2);+ const offset = (state.elements.length % 5) * 24;+ const w = type === 'sticky' ? 156 : (type === 'diamond' ? 150 : 144);+ const h = type === 'sticky' ? 114 : (type === 'diamond' ? 88 : 68);+ const defaultLabels = {+ rectangle: 'Service Node',+ ellipse: 'State / Cache',+ diamond: 'Decision?',+ sticky: 'Architecture Note'+ };+ const el = createElement(type, {+ x: centerWorld.x - w / 2 + offset,+ y: centerWorld.y - h / 2 + offset,+ width: w,+ height: h,+ text: defaultLabels[type] || 'Node'+ });+ state.elements.push(el);+ state.selectedIds.clear();+ state.selectedIds.add(el.id);+ syncUIWithSelection();+ return el;+ }++ function loadTemplate(templateName) {+ pushHistory();+ state.elements = [];+ state.selectedIds.clear();+ state.activePulses = [];+ ShapeCache.clear();++ const addNode = (id, type, x, y, w, h, text, color, fillStyle = 'hachure') => {+ const el = createElement(type, { id, x, y, width: w, height: h, text, strokeColor: color, fillStyle });+ state.elements.push(el);+ return el;+ };++ const addEdge = (fromEl, toEl, curveOffset = 0, color = null) => {+ const fc = { x: fromEl.x + fromEl.width / 2, y: fromEl.y + fromEl.height / 2 };+ const tc = { x: toEl.x + toEl.width / 2, y: toEl.y + toEl.height / 2 };+ const angOut = Math.atan2(tc.y - fc.y, tc.x - fc.x);+ const angIn = Math.atan2(fc.y - tc.y, fc.x - tc.x);+ const arr = createElement('arrow', {+ x: fc.x,+ y: fc.y,+ x2: tc.x,+ y2: tc.y,+ text: '',+ curveOffset,+ curveType: Math.abs(curveOffset) > 1 ? 'curved' : state.defaults.curveType,+ strokeColor: color || fromEl.strokeColor,+ startBinding: { elementId: fromEl.id, focusAngle: angOut, side: angleToSide(angOut), gap: 4 },+ endBinding: { elementId: toEl.id, focusAngle: angIn, side: angleToSide(angIn), gap: 4 }+ });+ state.elements.push(arr);+ return arr;+ };++ if (templateName === 'How Browsers Work') {+ const n1 = addNode('b_url', 'ellipse', 70, 220, 148, 70, 'URL Request\nHTTPS / DNS', '#0070f3');+ const n2 = addNode('b_html', 'rectangle', 295, 125, 156, 70, 'HTML Parser\nDOM Tree', '#7928ca');+ const n3 = addNode('b_css', 'rectangle', 295, 315, 156, 70, 'CSS Parser\nCSSOM', '#06b6d4');+ const n4 = addNode('b_render', 'diamond', 530, 208, 174, 96, 'Render Tree\n& Layout', '#f59e0b');+ const n5 = addNode('b_paint', 'rectangle', 780, 220, 162, 70, 'Composite &\n60fps Paint', '#10b981');+ addEdge(n1, n2, -20, '#0070f3');+ addEdge(n1, n3, 20, '#06b6d4');+ addEdge(n2, n4, 16, '#7928ca');+ addEdge(n3, n4, -16, '#06b6d4');+ addEdge(n4, n5, 0, '#10b981');+ } else if (templateName === 'RAG Pipeline') {+ const n1 = addNode('r_q', 'ellipse', 70, 225, 146, 70, 'User Query', '#0070f3');+ const n2 = addNode('r_emb', 'rectangle', 285, 225, 158, 70, 'Embedding\nEncoder', '#7928ca');+ const n3 = addNode('r_vec', 'diamond', 515, 120, 170, 94, 'Vector DB\nTop-K Search', '#06b6d4');+ const n4 = addNode('r_rerank', 'rectangle', 520, 320, 158, 70, 'Cross-Encoder\nReranker', '#f59e0b');+ const n5 = addNode('r_llm', 'rectangle', 765, 225, 164, 72, 'LLM Context\nSynthesizer', '#10b981');+ addEdge(n1, n2, 0, '#0070f3');+ addEdge(n2, n3, -18, '#7928ca');+ addEdge(n3, n4, 0, '#06b6d4');+ addEdge(n4, n5, 18, '#f59e0b');+ addEdge(n2, n5, -28, '#10b981');+ } else if (templateName === 'Microservices') {+ const n1 = addNode('m_gw', 'diamond', 70, 215, 166, 94, 'API Gateway\nRate Limiter', '#0070f3');+ const n2 = addNode('m_auth', 'rectangle', 315, 100, 152, 68, 'Auth Service\nJWT Verify', '#7928ca');+ const n3 = addNode('m_ord', 'rectangle', 315, 228, 152, 68, 'Order Engine', '#10b981');+ const n4 = addNode('m_pay', 'rectangle', 315, 355, 152, 68, 'Payment Worker', '#f59e0b');+ const n5 = addNode('m_kafka', 'ellipse', 565, 228, 160, 72, 'Event Bus\nKafka Stream', '#ef4444');+ const n6 = addNode('m_db', 'rectangle', 800, 228, 156, 70, 'Read Replica\nAnalytics', '#06b6d4');+ addEdge(n1, n2, -20, '#7928ca');+ addEdge(n1, n3, 0, '#0070f3');+ addEdge(n1, n4, 20, '#f59e0b');+ addEdge(n3, n5, 0, '#10b981');+ addEdge(n4, n5, -18, '#f59e0b');+ addEdge(n5, n6, 0, '#ef4444');+ } else {+ const n1 = addNode('a_user', 'ellipse', 70, 225, 146, 70, 'User Task\nSpec', '#0070f3');+ const n2 = addNode('a_plan', 'diamond', 285, 212, 170, 94, 'Orchestrator\nPlanner', '#7928ca');+ const n3 = addNode('a_code', 'rectangle', 530, 115, 160, 70, 'Coder Agent\nSandbox', '#10b981');+ const n4 = addNode('a_res', 'rectangle', 530, 325, 160, 70, 'Research Agent\nWeb & Docs', '#06b6d4');+ const n5 = addNode('a_ver', 'rectangle', 780, 225, 164, 70, 'Verifier Agent\nTest Runner', '#f59e0b');+ addEdge(n1, n2, 0, '#0070f3');+ addEdge(n2, n3, -20, '#7928ca');+ addEdge(n2, n4, 20, '#7928ca');+ addEdge(n3, n5, 18, '#10b981');+ addEdge(n4, n5, -18, '#06b6d4');+ }++ fitToScreen();+ syncUIWithSelection();+ }++ /* -------------------------------------------------------------------------+ * 11. Camera Transforms & Interactive Overlay Rendering+ * ------------------------------------------------------------------------- */+ function worldToScreen(wx, wy) {+ return {+ x: (wx + state.scrollX) * state.zoom,+ y: (wy + state.scrollY) * state.zoom+ };+ }++ function screenToWorld(sx, sy) {+ return {+ x: sx / state.zoom - state.scrollX,+ y: sy / state.zoom - state.scrollY+ };+ }++ function drawInteractiveOverlay(ctx, arrowGeoms) {+ const zoom = state.zoom || 1;+ const isDark = state.canvasBg === '#000000';+ const accent = isDark ? '#8b87ff' : '#6965db';++ ctx.save();++ // 1. Magnetic snap target outline, center-to-perimeter angle ray & glowing ring+ if (state.snapPreview) {+ const sp = state.snapPreview;+ const targetShape = state.elements.find(e => e.id === sp.shapeId);+ if (targetShape) {+ const paths = ShapeCache.get(targetShape);+ const scx = targetShape.x + targetShape.width / 2;+ const scy = targetShape.y + targetShape.height / 2;++ ctx.save();+ ctx.strokeStyle = accent;+ ctx.lineWidth = 2.4 / zoom;+ ctx.shadowColor = accent;+ ctx.shadowBlur = 12;+ ctx.stroke(paths.fillPath);++ // Dashed radial guide from shape center to perimeter attachment point+ ctx.beginPath();+ ctx.setLineDash([4 / zoom, 4 / zoom]);+ ctx.lineWidth = 1.3 / zoom;+ ctx.globalAlpha = 0.65;+ ctx.moveTo(scx, scy);+ ctx.lineTo(sp.point.x, sp.point.y);+ ctx.stroke();+ ctx.setLineDash([]);+ ctx.globalAlpha = 1;++ // Glowing perimeter anchor ring+ ctx.beginPath();+ ctx.fillStyle = '#ffffff';+ ctx.strokeStyle = accent;+ ctx.lineWidth = 2.5 / zoom;+ ctx.arc(sp.point.x, sp.point.y, 6.5 / zoom, 0, Math.PI * 2);+ ctx.fill();+ ctx.stroke();+ ctx.restore();+ }+ }++ // 2. Subtle hover cue on hovered unselected node+ if (state.hoveredId && !state.selectedIds.has(state.hoveredId) && !state.drag) {+ const hovEl = state.elements.find(e => e.id === state.hoveredId);+ if (hovEl && isNodeElement(hovEl) && hovEl.type !== 'text') {+ ctx.save();+ ctx.strokeStyle = accent;+ ctx.globalAlpha = 0.35;+ ctx.lineWidth = 1.5 / zoom;+ const pad = 5 / zoom;+ ctx.strokeRect(hovEl.x - pad, hovEl.y - pad, (hovEl.width || 0) + pad * 2, (hovEl.height || 0) + pad * 2);+ ctx.restore();+ }+ }++ // 3. Selection Bounding Box + 8-Way Resize Handles + Quick-Connect '+' Ports+ const portOwnerIds = new Set(state.selectedIds);+ if (state.hoveredId) portOwnerIds.add(state.hoveredId);++ for (const id of state.selectedIds) {+ const el = state.elements.find(e => e.id === id);+ if (!el || el.type === 'arrow') continue;+ ctx.save();+ ctx.strokeStyle = accent;+ ctx.lineWidth = 1.4 / zoom;+ const pad = 6 / zoom;+ ctx.strokeRect(el.x - pad, el.y - pad, (el.width || 0) + pad * 2, (el.height || 0) + pad * 2);++ // Draw 8 resize handles when single shape is selected+ if (state.selectedIds.size === 1 && isNodeElement(el) && el.type !== 'text') {+ const hs = 4.2 / zoom;+ for (const h of getResizeHandles(el)) {+ ctx.fillStyle = isDark ? '#1e1e24' : '#ffffff';+ ctx.strokeStyle = accent;+ ctx.lineWidth = 1.5 / zoom;+ ctx.beginPath();+ ctx.rect(h.x - hs, h.y - hs, hs * 2, hs * 2);+ ctx.fill();+ ctx.stroke();+ }+ }+ ctx.restore();+ }++ if (state.activeTool === 'select') {+ for (const id of portOwnerIds) {+ const el = state.elements.find(e => e.id === id);+ if (!el || !isNodeElement(el) || el.type === 'text') continue;+ const ports = getQuickConnectPorts(el);+ for (const p of ports) {+ const isHoveredPort = state.hoveredPort &&+ state.hoveredPort.elementId === el.id &&+ state.hoveredPort.dir === p.dir;+ const r = (isHoveredPort ? 9.5 : 7.2) / zoom;+ ctx.save();+ ctx.beginPath();+ ctx.fillStyle = isHoveredPort ? accent : (isDark ? '#1e1e26' : '#ffffff');+ ctx.strokeStyle = accent;+ ctx.lineWidth = 1.6 / zoom;+ ctx.arc(p.x, p.y, r, 0, Math.PI * 2);+ ctx.fill();+ ctx.stroke();++ const arm = 3.3 / zoom;+ ctx.beginPath();+ ctx.strokeStyle = isHoveredPort ? '#ffffff' : accent;+ ctx.lineWidth = 1.6 / zoom;+ ctx.moveTo(p.x - arm, p.y);+ ctx.lineTo(p.x + arm, p.y);+ ctx.moveTo(p.x, p.y - arm);+ ctx.lineTo(p.x, p.y + arm);+ ctx.stroke();+ ctx.restore();+ }+ }+ }++ // 4. Hover-Visible & Selected Arrow Endpoint Handles ('start', 'curve', 'end')+ for (const el of state.elements) {+ if (el.type !== 'arrow') continue;+ const showHandles = state.selectedIds.has(el.id) || state.hoveredId === el.id ||+ (state.hoveredArrowHandle && state.hoveredArrowHandle.elementId === el.id);+ if (!showHandles) continue;++ const geom = arrowGeoms.get(el.id) || getArrowGeometry(el);+ const handles = [+ { name: 'start', pt: geom.p0, bound: Boolean(el.startBinding?.elementId) },+ { name: 'curve', pt: geom.curveHandlePt, bound: false },+ { name: 'end', pt: geom.p1, bound: Boolean(el.endBinding?.elementId) }+ ];++ for (const h of handles) {+ const isHot = state.hoveredArrowHandle &&+ state.hoveredArrowHandle.elementId === el.id &&+ state.hoveredArrowHandle.handle === h.name;+ const r = (isHot ? 7.4 : 5.6) / zoom;+ ctx.save();+ ctx.beginPath();+ ctx.fillStyle = h.bound ? accent : (isDark ? '#18181f' : '#ffffff');+ ctx.strokeStyle = accent;+ ctx.lineWidth = 2 / zoom;+ ctx.arc(h.pt.x, h.pt.y, r, 0, Math.PI * 2);+ ctx.fill();+ ctx.stroke();+ ctx.restore();+ }+ }++ // 5. Live Port-Wire Drag Preview+ if (state.drag && state.drag.mode === 'port-wire') {+ const d = state.drag;+ ctx.save();+ ctx.strokeStyle = accent;+ ctx.lineWidth = 2.2 / zoom;+ ctx.setLineDash([6 / zoom, 4 / zoom]);+ ctx.beginPath();+ ctx.moveTo(d.startPt.x, d.startPt.y);+ const mx = (d.startPt.x + d.currPt.x) / 2;+ const my = (d.startPt.y + d.currPt.y) / 2 - 24 / zoom;+ ctx.quadraticCurveTo(mx, my, d.currPt.x, d.currPt.y);+ ctx.stroke();+ ctx.restore();+ }++ // 6. Marquee Selection Box+ if (state.drag && state.drag.mode === 'marquee') {+ const d = state.drag;+ const x = Math.min(d.startX, d.currX);+ const y = Math.min(d.startY, d.currY);+ const w = Math.abs(d.currX - d.startX);+ const h = Math.abs(d.currY - d.startY);+ ctx.save();+ ctx.fillStyle = 'rgba(105, 101, 219, 0.09)';+ ctx.strokeStyle = accent;+ ctx.lineWidth = 1.2 / zoom;+ ctx.fillRect(x, y, w, h);+ ctx.strokeRect(x, y, w, h);+ ctx.restore();+ }++ // 7. Laser Pointer 900ms Decaying Red Glow Trail+ const nowMs = performance.now();+ state.laserPoints = state.laserPoints.filter(p => nowMs - p.t < 900);+ if (state.laserPoints.length > 1) {+ ctx.save();+ ctx.lineCap = 'round';+ ctx.lineJoin = 'round';+ for (let i = 1; i < state.laserPoints.length; i++) {+ const p0 = state.laserPoints[i - 1];+ const p1 = state.laserPoints[i];+ const age = (nowMs - p1.t) / 900;+ const alpha = Math.max(0, 1 - age);+ ctx.beginPath();+ ctx.strokeStyle = '#ef4444';+ ctx.shadowColor = '#ef4444';+ ctx.shadowBlur = 12;+ ctx.globalAlpha = alpha;+ ctx.lineWidth = (4.5 * alpha) / zoom;+ ctx.moveTo(p0.x, p0.y);+ ctx.lineTo(p1.x, p1.y);+ ctx.stroke();+ }+ ctx.restore();+ }++ ctx.restore();+ }++ /* -------------------------------------------------------------------------+ * 12. Pointer Interaction Engine (World-Space & DOM Events)+ * ------------------------------------------------------------------------- */+ function updateInteractiveCursor() {+ if (typeof document === 'undefined') return;+ const ic = document.getElementById('interactiveCanvas');+ if (!ic) return;++ if (state.drag) {+ if (state.drag.mode === 'pan' || state.drag.mode === 'move' || state.drag.mode === 'arrow-handle') {+ ic.style.cursor = 'grabbing';+ return;+ }+ if (state.drag.mode === 'resize') {+ ic.style.cursor = state.drag.cursor || 'nwse-resize';+ return;+ }+ }++ if (state.activeTool === 'hand' || state.isSpacePanning) {+ ic.style.cursor = 'grab';+ return;+ }+ if (state.activeTool !== 'select') {+ ic.style.cursor = 'crosshair';+ return;+ }++ if (state.hoveredResizeHandle) {+ ic.style.cursor = state.hoveredResizeHandle.cursor;+ } else if (state.hoveredPort) {+ ic.style.cursor = 'pointer';+ } else if (state.hoveredArrowHandle) {+ ic.style.cursor = 'grab';+ } else if (state.hoveredId) {+ ic.style.cursor = 'move';+ } else {+ ic.style.cursor = 'default';+ }+ }++ function cloneElementsWithBindings(sourceElements, offsetX = 0, offsetY = 0) {+ if (!Array.isArray(sourceElements) || sourceElements.length === 0) return [];+ const idMap = new Map();+ const clones = [];+ for (const el of sourceElements) {+ const newId = nextId(el.type);+ idMap.set(el.id, newId);+ const copy = JSON.parse(JSON.stringify(el));+ copy.id = newId;+ copy.x = (Number(copy.x) || 0) + offsetX;+ copy.y = (Number(copy.y) || 0) + offsetY;+ if (typeof copy.x2 === 'number') copy.x2 += offsetX;+ if (typeof copy.y2 === 'number') copy.y2 += offsetY;+ copy.seed = Math.floor(Math.random() * 1000000) + 1;+ clones.push(copy);+ }+ for (const c of clones) {+ if (c.startBinding?.elementId && idMap.has(c.startBinding.elementId)) {+ c.startBinding.elementId = idMap.get(c.startBinding.elementId);+ }+ if (c.endBinding?.elementId && idMap.has(c.endBinding.elementId)) {+ c.endBinding.elementId = idMap.get(c.endBinding.elementId);+ }+ state.elements.push(c);+ }+ state.selectedIds = new Set(clones.map(c => c.id));+ return clones;+ }++ function cloneSelectedForAltDrag() {+ const selected = state.elements.filter(el => state.selectedIds.has(el.id));+ cloneElementsWithBindings(selected, 0, 0);+ }++ function pointerDownWorld(wx, wy, opts = {}) {+ if (state.editingId) commitInlineEditor();+ closeAllDropdowns();++ const shiftKey = Boolean(opts.shiftKey);+ const altKey = Boolean(opts.altKey);+ const tool = state.activeTool;++ if (tool === 'hand' || state.isSpacePanning) {+ state.drag = {+ mode: 'pan',+ startScreenX: opts.screenX ?? wx * state.zoom,+ startScreenY: opts.screenY ?? wy * state.zoom,+ origScrollX: state.scrollX,+ origScrollY: state.scrollY+ };+ updateInteractiveCursor();+ return;+ }++ if (tool === 'laser') {+ state.laserPoints.push({ x: wx, y: wy, t: performance.now() });+ state.drag = { mode: 'laser' };+ return;+ }++ if (tool === 'eraser') {+ pushHistory();+ const hit = hitTestElement(wx, wy);+ if (hit) deleteElementById(hit.id);+ state.drag = { mode: 'eraser' };+ return;+ }++ if (tool === 'freedraw') {+ pushHistory();+ const el = createElement('freedraw', {+ x: wx,+ y: wy,+ width: 1,+ height: 1,+ points: [[0, 0]]+ });+ state.elements.push(el);+ state.selectedIds.clear();+ state.selectedIds.add(el.id);+ state.drag = { mode: 'freedraw', element: el };+ return;+ }++ if (tool === 'text' || tool === 'sticky') {+ pushHistory();+ const w = tool === 'sticky' ? 156 : 120;+ const h = tool === 'sticky' ? 112 : 38;+ const el = createElement(tool, {+ x: wx - w / 2,+ y: wy - h / 2,+ width: w,+ height: h,+ text: tool === 'sticky' ? 'Sticky Note' : 'Label'+ });+ state.elements.push(el);+ state.selectedIds.clear();+ state.selectedIds.add(el.id);+ if (!state.toolLocked) setTool('select');+ syncUIWithSelection();+ startInlineEditing(el);+ return;+ }++ if (tool === 'rectangle' || tool === 'ellipse' || tool === 'diamond') {+ pushHistory();+ const el = createElement(tool, {+ x: wx,+ y: wy,+ width: 4,+ height: 4,+ text: ''+ });+ state.elements.push(el);+ state.selectedIds.clear();+ state.selectedIds.add(el.id);+ state.drag = { mode: 'draw-shape', element: el, startX: wx, startY: wy };+ return;+ }++ if (tool === 'arrow') {+ pushHistory();+ const startShape = findMagneticShape(wx, wy, null);+ const startBinding = startShape ? computeBindingForShape(startShape, { x: wx, y: wy }) : null;+ const startPt = startShape+ ? getBindingBoundaryPoint(startShape, startBinding, { x: wx, y: wy }, 4)+ : { x: wx, y: wy };++ const arrow = createElement('arrow', {+ x: startPt.x,+ y: startPt.y,+ x2: wx,+ y2: wy,+ startBinding,+ endBinding: null+ });+ state.elements.push(arrow);+ state.selectedIds.clear();+ state.selectedIds.add(arrow.id);+ state.drag = { mode: 'arrow-handle', arrow, handle: 'end' };+ return;+ }++ // SELECT MODE+ // 0. Check 8-Way Resize Handles on selected node+ const resizeHit = hitTestResizeHandles(wx, wy);+ if (resizeHit) {+ const el = state.elements.find(e => e.id === resizeHit.elementId);+ if (el) {+ pushHistory();+ state.drag = {+ mode: 'resize',+ element: el,+ dir: resizeHit.dir,+ cursor: resizeHit.cursor,+ startX: wx,+ startY: wy,+ origX: el.x,+ origY: el.y,+ origW: el.width,+ origH: el.height+ };+ updateInteractiveCursor();+ return;+ }+ }++ // 1. Check Quick-Connect '+' Ports+ const portHit = hitTestQuickPorts(wx, wy);+ if (portHit) {+ const sourceEl = state.elements.find(e => e.id === portHit.elementId);+ if (sourceEl) {+ state.drag = {+ mode: 'port-wire',+ sourceEl,+ dir: portHit.dir,+ startPt: { x: portHit.x, y: portHit.y },+ currPt: { x: wx, y: wy },+ moved: false+ };+ return;+ }+ }++ // 2. Check 1-Click Arrow Endpoint / Curve Handle Grabbing (18px / zoom radius across ALL arrows)+ const handleHit = hitTestArrowHandle(wx, wy);+ if (handleHit) {+ pushHistory();+ const arrow = state.elements.find(e => e.id === handleHit.elementId);+ if (arrow) {+ state.selectedIds.clear();+ state.selectedIds.add(arrow.id);+ syncUIWithSelection();+ state.drag = { mode: 'arrow-handle', arrow, handle: handleHit.handle };+ updateInteractiveCursor();+ return;+ }+ }++ // 3. Hit-test scene elements+ const hitEl = hitTestElement(wx, wy);+ if (hitEl) {+ pushHistory();++ if (hitEl.type === 'arrow' && !altKey) {+ state.selectedIds.clear();+ state.selectedIds.add(hitEl.id);+ syncUIWithSelection();++ const geom = getArrowGeometry(hitEl);+ const endGrabRadius = 32 / (state.zoom || 1);+ let handle = 'curve';+ if (Math.hypot(wx - geom.p0.x, wy - geom.p0.y) <= endGrabRadius) {+ handle = 'start';+ } else if (Math.hypot(wx - geom.p1.x, wy - geom.p1.y) <= endGrabRadius) {+ handle = 'end';+ }+ state.drag = { mode: 'arrow-handle', arrow: hitEl, handle };+ updateInteractiveCursor();+ return;+ }++ if (shiftKey) {+ if (state.selectedIds.has(hitEl.id)) state.selectedIds.delete(hitEl.id);+ else state.selectedIds.add(hitEl.id);+ } else if (!state.selectedIds.has(hitEl.id)) {+ state.selectedIds.clear();+ state.selectedIds.add(hitEl.id);+ }++ if (altKey) {+ cloneSelectedForAltDrag();+ }++ const initialPositions = new Map();+ for (const id of state.selectedIds) {+ const item = state.elements.find(e => e.id === id);+ if (item) {+ initialPositions.set(id, {+ x: item.x,+ y: item.y,+ x2: item.x2,+ y2: item.y2+ });+ }+ }+ syncUIWithSelection();+ state.drag = {+ mode: 'move',+ startX: wx,+ startY: wy,+ initialPositions+ };+ updateInteractiveCursor();+ return;+ }++ // 4. Empty Canvas -> Marquee Selection+ state.selectedIds.clear();+ syncUIWithSelection();+ state.drag = {+ mode: 'marquee',+ startX: wx,+ startY: wy,+ currX: wx,+ currY: wy+ };+ }++ function pointerMoveWorld(wx, wy, opts = {}) {+ if (!state.drag) {+ state.hoveredResizeHandle = hitTestResizeHandles(wx, wy);+ state.hoveredPort = state.hoveredResizeHandle ? null : hitTestQuickPorts(wx, wy);+ state.hoveredArrowHandle = (state.hoveredResizeHandle || state.hoveredPort) ? null : hitTestArrowHandle(wx, wy);+ const elHit = hitTestElement(wx, wy);+ state.hoveredId = elHit ? elHit.id : null;+ updateInteractiveCursor();+ return;+ }++ const d = state.drag;+ if (d.mode === 'pan') {+ const sx = opts.screenX ?? wx * state.zoom;+ const sy = opts.screenY ?? wy * state.zoom;+ state.scrollX = d.origScrollX + (sx - d.startScreenX) / state.zoom;+ state.scrollY = d.origScrollY + (sy - d.startScreenY) / state.zoom;+ updateQuickHudPosition();+ return;+ }++ if (d.mode === 'resize') {+ const el = d.element;+ const dx = wx - d.startX;+ const dy = wy - d.startY;+ const minW = 64;+ const minH = 42;+ let nx = d.origX;+ let ny = d.origY;+ let nw = d.origW;+ let nh = d.origH;++ if (d.dir.includes('e')) nw = Math.max(minW, d.origW + dx);+ if (d.dir.includes('s')) nh = Math.max(minH, d.origH + dy);+ if (d.dir.includes('w')) {+ const possibleW = d.origW - dx;+ if (possibleW >= minW) {+ nw = possibleW;+ nx = d.origX + dx;+ }+ }+ if (d.dir.includes('n')) {+ const possibleH = d.origH - dy;+ if (possibleH >= minH) {+ nh = possibleH;+ ny = d.origY + dy;+ }+ }+ el.x = nx;+ el.y = ny;+ el.width = nw;+ el.height = nh;+ ShapeCache.invalidate(el);+ updateQuickHudPosition();+ return;+ }++ if (d.mode === 'laser') {+ state.laserPoints.push({ x: wx, y: wy, t: performance.now() });+ return;+ }++ if (d.mode === 'eraser') {+ const hit = hitTestElement(wx, wy);+ if (hit) deleteElementById(hit.id);+ return;+ }++ if (d.mode === 'freedraw') {+ const el = d.element;+ el.points.push([wx - el.x, wy - el.y]);+ return;+ }++ if (d.mode === 'draw-shape') {+ const el = d.element;+ el.x = Math.min(d.startX, wx);+ el.y = Math.min(d.startY, wy);+ el.width = Math.max(24, Math.abs(wx - d.startX));+ el.height = Math.max(24, Math.abs(wy - d.startY));+ ShapeCache.invalidate(el);+ return;+ }++ if (d.mode === 'arrow-handle') {+ const arrow = d.arrow;+ if (d.handle === 'start') {+ const otherId = arrow.endBinding?.elementId || null;+ const targetShape = findMagneticShape(wx, wy, otherId);+ if (targetShape) {+ const binding = computeBindingForShape(targetShape, { x: wx, y: wy });+ arrow.startBinding = binding;+ const bPt = getBindingBoundaryPoint(targetShape, binding, { x: arrow.x2 || wx, y: arrow.y2 || wy }, 4);+ arrow.x = bPt.x;+ arrow.y = bPt.y;+ state.snapPreview = { shapeId: targetShape.id, point: bPt, angle: binding.focusAngle };+ } else {+ arrow.startBinding = null;+ arrow.x = wx;+ arrow.y = wy;+ state.snapPreview = null;+ }+ } else if (d.handle === 'end') {+ const otherId = arrow.startBinding?.elementId || null;+ const targetShape = findMagneticShape(wx, wy, otherId);+ if (targetShape) {+ const binding = computeBindingForShape(targetShape, { x: wx, y: wy });+ arrow.endBinding = binding;+ const bPt = getBindingBoundaryPoint(targetShape, binding, { x: arrow.x || wx, y: arrow.y || wy }, 4);+ arrow.x2 = bPt.x;+ arrow.y2 = bPt.y;+ state.snapPreview = { shapeId: targetShape.id, point: bPt, angle: binding.focusAngle };+ } else {+ arrow.endBinding = null;+ arrow.x2 = wx;+ arrow.y2 = wy;+ state.snapPreview = null;+ }+ } else if (d.handle === 'curve') {+ const elementsMap = getElementMap();+ const startShape = arrow.startBinding?.elementId ? elementsMap.get(arrow.startBinding.elementId) : null;+ const endShape = arrow.endBinding?.elementId ? elementsMap.get(arrow.endBinding.elementId) : null;+ const p0 = startShape+ ? getBindingBoundaryPoint(startShape, arrow.startBinding, { x: arrow.x2, y: arrow.y2 }, 4)+ : { x: arrow.x, y: arrow.y };+ const p1 = endShape+ ? getBindingBoundaryPoint(endShape, arrow.endBinding, p0, 4)+ : { x: arrow.x2, y: arrow.y2 };+ const chordDx = p1.x - p0.x;+ const chordDy = p1.y - p0.y;+ const chordLen = Math.hypot(chordDx, chordDy) || 1;+ const nx = -chordDy / chordLen;+ const ny = chordDx / chordLen;+ const mx = (p0.x + p1.x) / 2;+ const my = (p0.y + p1.y) / 2;+ const proj = (wx - mx) * nx + (wy - my) * ny;+ if (arrow.curveType === 'straight' && Math.abs(proj) > 4) {+ arrow.curveType = 'curved';+ }+ arrow.curveOffset = proj * 2;+ }+ updateQuickHudPosition();+ return;+ }++ if (d.mode === 'port-wire') {+ d.currPt = { x: wx, y: wy };+ if (Math.hypot(wx - d.startPt.x, wy - d.startPt.y) > 8 / (state.zoom || 1)) {+ d.moved = true;+ }+ const targetShape = findMagneticShape(wx, wy, d.sourceEl.id);+ if (targetShape) {+ const binding = computeBindingForShape(targetShape, { x: wx, y: wy });+ const bPt = getBindingBoundaryPoint(targetShape, binding, d.startPt, 4);+ state.snapPreview = { shapeId: targetShape.id, point: bPt, angle: binding.focusAngle };+ } else {+ state.snapPreview = null;+ }+ return;+ }++ if (d.mode === 'move') {+ const dx = wx - d.startX;+ const dy = wy - d.startY;+ let singleNode = null;++ for (const [id, initPos] of d.initialPositions.entries()) {+ const el = state.elements.find(e => e.id === id);+ if (!el) continue;+ el.x = initPos.x + dx;+ el.y = initPos.y + dy;+ if (el.type === 'arrow') {+ if (!el.startBinding?.elementId && typeof initPos.x === 'number') el.x = initPos.x + dx;+ if (!el.endBinding?.elementId && typeof initPos.x2 === 'number') {+ el.x2 = initPos.x2 + dx;+ el.y2 = initPos.y2 + dy;+ }+ } else {+ ShapeCache.invalidate(el);+ if (d.initialPositions.size === 1 && isNodeElement(el)) {+ singleNode = el;+ }+ }+ }++ if (singleNode) {+ const splitArrow = findSplitTargetArrow(singleNode);+ state.splitTargetArrowId = splitArrow ? splitArrow.id : null;+ } else {+ state.splitTargetArrowId = null;+ }+ updateQuickHudPosition();+ return;+ }++ if (d.mode === 'marquee') {+ d.currX = wx;+ d.currY = wy;+ const x1 = Math.min(d.startX, d.currX);+ const y1 = Math.min(d.startY, d.currY);+ const x2 = Math.max(d.startX, d.currX);+ const y2 = Math.max(d.startY, d.currY);+ state.selectedIds.clear();+ for (const el of state.elements) {+ const ex1 = el.type === 'arrow' ? Math.min(el.x, el.x2 ?? el.x) : el.x;+ const ey1 = el.type === 'arrow' ? Math.min(el.y, el.y2 ?? el.y) : el.y;+ const ex2 = el.type === 'arrow' ? Math.max(el.x, el.x2 ?? el.x) : el.x + (el.width || 0);+ const ey2 = el.type === 'arrow' ? Math.max(el.y, el.y2 ?? el.y) : el.y + (el.height || 0);+ if (ex2 >= x1 && ex1 <= x2 && ey2 >= y1 && ey1 <= y2) {+ state.selectedIds.add(el.id);+ }+ }+ syncUIWithSelection();+ }+ }++ function pointerUpWorld(wx, wy) {+ if (!state.drag) return;+ const d = state.drag;+ state.drag = null;+ state.snapPreview = null;+ updateInteractiveCursor();++ if (d.mode === 'draw-shape') {+ const el = d.element;+ if (el.width < 32 && el.height < 32) {+ el.width = el.type === 'diamond' ? 148 : 144;+ el.height = el.type === 'diamond' ? 86 : 68;+ el.text = el.type === 'diamond' ? 'Decision?' : 'Node';+ ShapeCache.invalidate(el);+ }+ if (!state.toolLocked) setTool('select');+ syncUIWithSelection();+ return;+ }++ if (d.mode === 'arrow-handle') {+ if (!state.toolLocked && state.activeTool === 'arrow') {+ setTool('select');+ }+ discardRedundantUndoSnapshot();+ syncUIWithSelection();+ return;+ }++ if (d.mode === 'port-wire') {+ if (!d.moved) {+ chainNodeFrom(d.sourceEl, d.dir, null, true);+ } else {+ pushHistory();+ const targetShape = findMagneticShape(wx, wy, d.sourceEl.id);+ const sc = { x: d.sourceEl.x + d.sourceEl.width / 2, y: d.sourceEl.y + d.sourceEl.height / 2 };+ const outAng = Math.atan2(wy - sc.y, wx - sc.x);++ if (targetShape) {+ const endBind = computeBindingForShape(targetShape, { x: wx, y: wy });+ const arr = createElement('arrow', {+ x: d.startPt.x,+ y: d.startPt.y,+ x2: wx,+ y2: wy,+ strokeColor: d.sourceEl.strokeColor,+ startBinding: { elementId: d.sourceEl.id, focusAngle: outAng, side: d.dir, gap: 4 },+ endBinding: endBind+ });+ state.elements.push(arr);+ state.selectedIds.clear();+ state.selectedIds.add(arr.id);+ } else {+ const newW = 144;+ const newH = 68;+ const newNode = createElement(d.sourceEl.type === 'text' ? 'rectangle' : d.sourceEl.type, {+ x: wx - newW / 2,+ y: wy - newH / 2,+ width: newW,+ height: newH,+ strokeColor: d.sourceEl.strokeColor,+ text: 'Connected Node'+ });+ const inAng = Math.atan2(sc.y - wy, sc.x - wx);+ const arr = createElement('arrow', {+ x: d.startPt.x,+ y: d.startPt.y,+ x2: wx,+ y2: wy,+ strokeColor: d.sourceEl.strokeColor,+ startBinding: { elementId: d.sourceEl.id, focusAngle: outAng, side: d.dir, gap: 4 },+ endBinding: { elementId: newNode.id, focusAngle: inAng, side: angleToSide(inAng), gap: 4 }+ });+ state.elements.push(newNode, arr);+ state.selectedIds.clear();+ state.selectedIds.add(newNode.id);+ startInlineEditing(newNode);+ }+ syncUIWithSelection();+ }+ return;+ }++ if (d.mode === 'move' || d.mode === 'resize') {+ if (d.mode === 'move' && state.splitTargetArrowId && state.selectedIds.size === 1) {+ const nodeId = Array.from(state.selectedIds)[0];+ const node = state.elements.find(e => e.id === nodeId);+ if (node) trySplitArrowWithNode(node);+ }+ state.splitTargetArrowId = null;+ discardRedundantUndoSnapshot();+ syncUIWithSelection();+ }+ }++ function deleteElementById(id) {+ state.elements = state.elements.filter(el => el.id !== id);+ for (const el of state.elements) {+ if (el.type === 'arrow') {+ if (el.startBinding?.elementId === id) el.startBinding = null;+ if (el.endBinding?.elementId === id) el.endBinding = null;+ }+ }+ state.selectedIds.delete(id);+ ShapeCache.invalidate(id);+ syncUIWithSelection();+ }++ function deleteSelection() {+ if (state.selectedIds.size === 0) return;+ pushHistory();+ const ids = Array.from(state.selectedIds);+ for (const id of ids) deleteElementById(id);+ }++ function duplicateSelection() {+ const selected = state.elements.filter(el => state.selectedIds.has(el.id));+ if (selected.length === 0) return [];+ pushHistory();+ const clones = cloneElementsWithBindings(selected, 28, 28);+ syncUIWithSelection();+ return clones;+ }++ /* -------------------------------------------------------------------------+ * 13. Inline Text Editor & Keyboard Shortcuts+ * ------------------------------------------------------------------------- */+ function startInlineEditing(el) {+ if (!el || el.type === 'arrow' || typeof document === 'undefined') return;+ state.editingId = el.id;+ state.editingPreSnap = snapshotScene();+ const wrap = document.getElementById('inlineEditorWrap');+ const ta = document.getElementById('inlineTextEditor');+ if (!wrap || !ta) return;++ const cx = el.x + (el.width || 0) / 2;+ const cy = el.y + (el.height || 0) / 2;++ const scr = worldToScreen(cx, cy);+ const fontSize = (Number(el.fontSize) || 16) * state.zoom;+ const w = Math.max(120, ((el.width || 120) - 12) * state.zoom);+ const h = Math.max(36, ((el.height || 44) - 8) * state.zoom);++ wrap.style.display = 'block';+ wrap.style.left = `${scr.x - w / 2}px`;+ wrap.style.top = `${scr.y - h / 2}px`;+ ta.style.width = `${w}px`;+ ta.style.height = `${h}px`;+ ta.style.fontFamily = FONT_MAP[normalizeFontFamily(el.fontFamily)];+ ta.style.fontSize = `${fontSize}px`;+ ta.style.color = resolveStrokeColor(el.strokeColor, state.canvasBg);+ ta.value = el.text || '';+ ta.focus?.();+ ta.select?.();+ }++ function commitInlineEditor() {+ if (!state.editingId) return;+ const el = state.elements.find(e => e.id === state.editingId);+ const wrap = typeof document !== 'undefined' ? document.getElementById('inlineEditorWrap') : null;+ const ta = typeof document !== 'undefined' ? document.getElementById('inlineTextEditor') : null;+ if (el && ta) {+ if (state.editingPreSnap && ta.value !== el.text) {+ pushHistory(state.editingPreSnap);+ }+ autoFitElementToText(el, ta.value);+ }+ state.editingId = null;+ state.editingPreSnap = null;+ if (wrap) wrap.style.display = 'none';+ }++ function setTool(tool) {+ state.activeTool = tool;+ if (typeof document === 'undefined') return;+ document.querySelectorAll('#bottomToolDock [data-tool]').forEach(btn => {+ btn.classList.toggle('active', btn.getAttribute('data-tool') === tool);+ });+ updateInteractiveCursor();+ }++ function toggleToolLock(forceVal) {+ state.toolLocked = typeof forceVal === 'boolean' ? forceVal : !state.toolLocked;+ if (typeof document !== 'undefined') {+ const btn = document.getElementById('toolLockBtn');+ if (btn) btn.classList.toggle('active', state.toolLocked);+ }+ return state.toolLocked;+ }++ function handleKeyDown(e) {+ const isEditing = Boolean(state.editingId);+ if (isEditing) {+ if (e.key === 'Escape') {+ e.preventDefault?.();+ commitInlineEditor();+ return;+ }+ if (e.key === 'Tab') {+ e.preventDefault?.();+ const editedEl = state.elements.find(el => el.id === state.editingId);+ commitInlineEditor();+ if (editedEl && isNodeElement(editedEl)) {+ chainNodeFrom(editedEl, 'right', null, true);+ }+ return;+ }+ return;+ }++ if (e.key === 'Escape') {+ closeAllDropdowns();+ if (state.selectedIds.size > 0) {+ state.selectedIds.clear();+ syncUIWithSelection();+ }+ if (state.activeTool !== 'select' && !state.toolLocked) {+ setTool('select');+ }+ return;+ }++ const meta = e.metaKey || e.ctrlKey;+ const key = String(e.key || '').toLowerCase();++ if (meta && key === '\\') {+ e.preventDefault?.();+ toggleSidebar();+ return;+ }+ if (meta && key === 'z') {+ e.preventDefault?.();+ if (e.shiftKey) redo();+ else undo();+ return;+ }+ if (meta && key === 'd') {+ e.preventDefault?.();+ duplicateSelection();+ return;+ }+ if (meta && key === 'a') {+ e.preventDefault?.();+ state.selectedIds = new Set(state.elements.map(el => el.id));+ syncUIWithSelection();+ return;+ }+ if (meta && key === 'c') {+ e.preventDefault?.();+ state.clipboard = JSON.parse(JSON.stringify(+ state.elements.filter(el => state.selectedIds.has(el.id))+ ));+ state.pasteCount = 0;+ return;+ }+ if (meta && key === 'v') {+ e.preventDefault?.();+ if (state.clipboard.length > 0) {+ pushHistory();+ state.pasteCount += 1;+ const offset = 28 * state.pasteCount;+ cloneElementsWithBindings(state.clipboard, offset, offset);+ syncUIWithSelection();+ }+ return;+ }++ if (e.key === 'Tab') {+ const selectedNodes = Array.from(state.selectedIds)+ .map(id => state.elements.find(el => el.id === id))+ .filter(el => el && isNodeElement(el));+ if (selectedNodes.length === 1) {+ e.preventDefault?.();+ chainNodeFrom(selectedNodes[0], 'right', null, true);+ return;+ }+ }++ if (e.key === 'Backspace' || e.key === 'Delete') {+ e.preventDefault?.();+ deleteSelection();+ return;+ }++ const shortcutMap = {+ '1': 'select',+ 'v': 'select',+ 'h': 'hand',+ '2': 'rectangle',+ 'r': 'rectangle',+ '3': 'diamond',+ 'd': 'diamond',+ '4': 'ellipse',+ 'o': 'ellipse',+ '5': 'arrow',+ '6': 'arrow',+ 'a': 'arrow',+ '7': 'freedraw',+ 'p': 'freedraw',+ '8': 'text',+ 't': 'text',+ '9': 'sticky',+ 'n': 'sticky',+ 'k': 'laser',+ '0': 'eraser',+ 'e': 'eraser'+ };++ if (key === 'q') {+ e.preventDefault?.();+ toggleToolLock();+ return;+ }++ if (shortcutMap[key]) {+ e.preventDefault?.();+ setTool(shortcutMap[key]);+ }+ }++ /* -------------------------------------------------------------------------+ * 14. Studio Exports (2x Retina PNG, Clipboard, 60fps WebM Video, JSON)+ * ------------------------------------------------------------------------- */+ function getDiagramExportBounds(padding = 48) {+ if (state.elements.length === 0) {+ return { x: 0, y: 0, width: 800, height: 500 };+ }+ let minX = Infinity;+ let minY = Infinity;+ let maxX = -Infinity;+ let maxY = -Infinity;+ const elementsMap = getElementMap();++ for (const el of state.elements) {+ if (el.type === 'arrow') {+ const geom = getArrowGeometry(el, elementsMap);+ for (const pt of geom.samples) {+ minX = Math.min(minX, pt.x);+ minY = Math.min(minY, pt.y);+ maxX = Math.max(maxX, pt.x);+ maxY = Math.max(maxY, pt.y);+ }+ } else if (el.type === 'freedraw') {+ for (const p of (el.points || [[0, 0]])) {+ minX = Math.min(minX, el.x + p[0]);+ minY = Math.min(minY, el.y + p[1]);+ maxX = Math.max(maxX, el.x + p[0]);+ maxY = Math.max(maxY, el.y + p[1]);+ }+ } else {+ minX = Math.min(minX, el.x);+ minY = Math.min(minY, el.y);+ maxX = Math.max(maxX, el.x + (el.width || 0));+ maxY = Math.max(maxY, el.y + (el.height || 0));+ }+ }++ return {+ x: Math.floor(minX - padding),+ y: Math.floor(minY - padding),+ width: Math.max(120, Math.ceil(maxX - minX + padding * 2)),+ height: Math.max(120, Math.ceil(maxY - minY + padding * 2))+ };+ }++ function renderCroppedOffscreenCanvas(scale = 2, timeSec = performance.now() / 1000) {+ const bounds = getDiagramExportBounds(48);+ const offCanvas = document.createElement('canvas');+ offCanvas.width = bounds.width * scale;+ offCanvas.height = bounds.height * scale;+ const offCtx = offCanvas.getContext('2d');++ offCtx.save();+ offCtx.fillStyle = state.canvasBg;+ offCtx.fillRect(0, 0, offCanvas.width, offCanvas.height);+ offCtx.scale(scale, scale);+ offCtx.translate(-bounds.x, -bounds.y);+ renderScenePasses(offCtx, timeSec, { canvasBg: state.canvasBg, forExport: true });+ offCtx.restore();+ return offCanvas;+ }++ function showToast(msg) {+ if (typeof document === 'undefined') return;+ const t = document.getElementById('studioToast');+ if (!t) return;+ t.textContent = msg;+ t.classList.add('show');+ clearTimeout(t._timer);+ t._timer = setTimeout(() => t.classList.remove('show'), 2200);+ }++ function save2xPng() {+ closeAllDropdowns();+ const offCanvas = renderCroppedOffscreenCanvas(2);+ offCanvas.toBlob(blob => {+ if (!blob) return;+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = 'excaliflow-2x.png';+ a.click();+ URL.revokeObjectURL(url);+ showToast('Saved 2x Retina PNG (excaliflow-2x.png)');+ }, 'image/png');+ }++ async function copy2xPng() {+ closeAllDropdowns();+ const offCanvas = renderCroppedOffscreenCanvas(2);+ offCanvas.toBlob(async blob => {+ if (!blob) return;+ try {+ await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);+ showToast('Copied 2x Retina PNG to Clipboard');+ } catch (err) {+ showToast('Clipboard write unavailable in this context');+ }+ }, 'image/png');+ }++ function recordWebmVideo() {+ closeAllDropdowns();+ if (typeof MediaRecorder === 'undefined') {+ showToast('MediaRecorder is not supported in this browser');+ return;+ }+ const bounds = getDiagramExportBounds(48);+ const scale = 2;+ const offCanvas = document.createElement('canvas');+ offCanvas.width = bounds.width * scale;+ offCanvas.height = bounds.height * scale;+ const offCtx = offCanvas.getContext('2d');++ const stream = offCanvas.captureStream(60);+ const mimeType = MediaRecorder.isTypeSupported('video/webm;codecs=vp9')+ ? 'video/webm;codecs=vp9'+ : 'video/webm';+ const recorder = new MediaRecorder(stream, { mimeType, videoBitsPerSecond: 8_000_000 });+ const chunks = [];++ recorder.ondataavailable = e => {+ if (e.data && e.data.size > 0) chunks.push(e.data);+ };+ recorder.onstop = () => {+ const blob = new Blob(chunks, { type: 'video/webm' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = 'excaliflow-flow.webm';+ a.click();+ URL.revokeObjectURL(url);+ showToast('Exported 60fps Video Loop (excaliflow-flow.webm)');+ };++ showToast('Recording 4s 60fps WebM Loop...');+ recorder.start();++ const totalFrames = 240;+ let frame = 0;+ const baseTime = performance.now() / 1000;+ const interval = setInterval(() => {+ const simTime = baseTime + frame / 60;+ offCtx.save();+ offCtx.fillStyle = state.canvasBg;+ offCtx.fillRect(0, 0, offCanvas.width, offCanvas.height);+ offCtx.scale(scale, scale);+ offCtx.translate(-bounds.x, -bounds.y);+ renderScenePasses(offCtx, simTime, { canvasBg: state.canvasBg, forExport: true });+ offCtx.restore();++ frame++;+ if (frame >= totalFrames) {+ clearInterval(interval);+ recorder.stop();+ }+ }, 1000 / 60);+ }++ function exportExcalidrawJson() {+ closeAllDropdowns();+ const payload = {+ type: 'excaliflow',+ version: 2,+ source: 'Excaliflow',+ elements: state.elements,+ appState: {+ viewBackgroundColor: state.canvasBg,+ scrollX: state.scrollX,+ scrollY: state.scrollY,+ zoom: { value: state.zoom },+ flowEnabled: state.flowEnabled,+ flowMode: state.flowMode,+ flowSpeed: state.flowSpeed+ }+ };+ const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = 'diagram.excaliflow';+ a.click();+ URL.revokeObjectURL(url);+ showToast('Saved diagram.excaliflow');+ }++ function importExcalidrawJson(jsonString) {+ closeAllDropdowns();+ try {+ const data = JSON.parse(jsonString);+ if (Array.isArray(data.elements)) {+ pushHistory();+ state.elements = data.elements+ .filter(el => el && !el.isDeleted && typeof el.type === 'string')+ .map(el => createElement(el.type === 'line' ? 'arrow' : el.type, {+ ...el,+ text: el.type === 'arrow' ? '' : (el.text ?? '')+ }));+ if (data.appState) {+ if (data.appState.viewBackgroundColor) setCanvasBackground(data.appState.viewBackgroundColor);+ if (data.appState.flowMode) state.flowMode = data.appState.flowMode;+ if (data.appState.flowSpeed) state.flowSpeed = Number(data.appState.flowSpeed) || 1;+ }+ state.selectedIds.clear();+ ShapeCache.clear();+ fitToScreen();+ syncUIWithSelection();+ showToast('Loaded Excaliflow scene');+ return true;+ }+ } catch (err) {+ showToast('Invalid JSON file');+ }+ return false;+ }++ /* -------------------------------------------------------------------------+ * 15. UI Chrome Synchronization & Viewport Controls+ * ------------------------------------------------------------------------- */+ function closeAllDropdowns() {+ if (typeof document === 'undefined') return;+ document.querySelectorAll('.dropdown-menu.open').forEach(m => m.classList.remove('open'));+ }++ function setCanvasBackground(color) {+ state.canvasBg = color === '#000000' ? '#000000' : '#ffffff';+ if (typeof document === 'undefined') return;+ document.body.classList.toggle('dark-canvas', state.canvasBg === '#000000');+ document.getElementById('bgWhiteBtn')?.classList.toggle('active', state.canvasBg === '#ffffff');+ document.getElementById('bgBlackBtn')?.classList.toggle('active', state.canvasBg === '#000000');+ }++ function setZoom(nextZoom, centerScreenX, centerScreenY) {+ const clamped = Math.max(0.25, Math.min(3.0, nextZoom));+ const vw = typeof window !== 'undefined' ? window.innerWidth : 1280;+ const vh = typeof window !== 'undefined' ? window.innerHeight : 800;+ const sx = centerScreenX ?? vw / 2;+ const sy = centerScreenY ?? vh / 2;++ const worldBefore = screenToWorld(sx, sy);+ state.zoom = clamped;+ state.scrollX = sx / state.zoom - worldBefore.x;+ state.scrollY = sy / state.zoom - worldBefore.y;++ if (typeof document !== 'undefined') {+ const zBtn = document.getElementById('zoomResetBtn');+ if (zBtn) zBtn.textContent = `${Math.round(state.zoom * 100)}%`;+ }+ updateQuickHudPosition();+ }++ function fitToScreen() {+ const bounds = getDiagramExportBounds(64);+ const vw = typeof window !== 'undefined' ? window.innerWidth : 1280;+ const vh = typeof window !== 'undefined' ? window.innerHeight : 800;+ const sidebarOffset = (typeof document !== 'undefined' &&+ !document.getElementById('leftSidebar')?.classList.contains('collapsed')) ? 115 : 0;++ const availW = Math.max(320, vw - sidebarOffset - 80);+ const availH = Math.max(240, vh - 140);+ const nextZoom = Math.max(0.25, Math.min(1.5, Math.min(availW / bounds.width, availH / bounds.height)));++ state.zoom = nextZoom;+ state.scrollX = (vw + sidebarOffset) / (2 * state.zoom) - (bounds.x + bounds.width / 2);+ state.scrollY = vh / (2 * state.zoom) - (bounds.y + bounds.height / 2);++ if (typeof document !== 'undefined') {+ const zBtn = document.getElementById('zoomResetBtn');+ if (zBtn) zBtn.textContent = `${Math.round(state.zoom * 100)}%`;+ }+ updateQuickHudPosition();+ }++ function toggleSidebar() {+ if (typeof document === 'undefined') return;+ const sb = document.getElementById('leftSidebar');+ if (sb) sb.classList.toggle('collapsed');+ }++ function updateHeaderButtons() {+ if (typeof document === 'undefined') return;+ const u = document.getElementById('btnUndo');+ const r = document.getElementById('btnRedo');+ if (u) u.disabled = state.history.undoStack.length === 0;+ if (r) r.disabled = state.history.redoStack.length === 0;++ const dot = document.getElementById('flowStatusDot');+ const mBtn = document.getElementById('masterFlowBtn');+ const badge = document.getElementById('flowBadgeText');+ if (dot) dot.classList.toggle('paused', !state.flowEnabled);+ if (mBtn) {+ mBtn.textContent = state.flowEnabled ? 'Flow: ON' : 'Flow: OFF';+ mBtn.classList.toggle('active', state.flowEnabled);+ }+ if (badge) {+ badge.textContent = `${state.flowMode.toUpperCase()} · ${state.flowSpeed}X`;+ }+ }++ function updateQuickHudPosition() {+ if (typeof document === 'undefined') return;+ const hud = document.getElementById('quickHud');+ if (!hud) return;++ if (state.selectedIds.size === 0 || state.editingId) {+ hud.classList.remove('visible');+ return;+ }++ const selected = state.elements.filter(el => state.selectedIds.has(el.id));+ if (selected.length === 0) {+ hud.classList.remove('visible');+ return;+ }++ let minX = Infinity, minY = Infinity, maxX = -Infinity;+ for (const el of selected) {+ if (el.type === 'arrow') {+ const geom = getArrowGeometry(el);+ for (const p of geom.samples) {+ minX = Math.min(minX, p.x);+ minY = Math.min(minY, p.y);+ maxX = Math.max(maxX, p.x);+ }+ } else {+ minX = Math.min(minX, el.x);+ minY = Math.min(minY, el.y);+ maxX = Math.max(maxX, el.x + (el.width || 0));+ }+ }++ const topCenterScreen = worldToScreen((minX + maxX) / 2, minY);+ const clampedX = Math.max(220, Math.min(window.innerWidth - 220, topCenterScreen.x));+ const clampedY = Math.max(108, topCenterScreen.y - 18);++ hud.style.left = `${clampedX}px`;+ hud.style.top = `${clampedY}px`;+ hud.classList.add('visible');++ const first = selected[0];+ const isArrowOnly = selected.every(e => e.type === 'arrow');+ const nodeCtrls = document.getElementById('hudNodeControls');+ const arrowCtrls = document.getElementById('hudArrowControls');+ if (nodeCtrls) nodeCtrls.style.display = isArrowOnly ? 'none' : 'inline-flex';+ if (arrowCtrls) arrowCtrls.style.display = isArrowOnly ? 'inline-flex' : 'none';++ if (isArrowOnly) {+ const flowBtn = document.getElementById('hudArrowFlowBtn');+ if (flowBtn) {+ const on = first.flowEnabled !== false;+ flowBtn.textContent = on ? 'Flow ON' : 'Flow OFF';+ flowBtn.classList.toggle('active', on);+ }+ }+ }++ function syncUIWithSelection() {+ if (typeof document === 'undefined') return;+ const selected = state.elements.filter(el => state.selectedIds.has(el.id));+ const ref = selected[0] || state.defaults;++ const setActiveAttr = (selector, attr, val) => {+ document.querySelectorAll(selector).forEach(btn => {+ btn.classList.toggle('active', String(btn.getAttribute(attr)) === String(val));+ });+ };++ setActiveAttr('#sidebarSwatches .color-swatch', 'data-color', ref.strokeColor);+ setActiveAttr('#fillStyleRow .seg-btn', 'data-fill-style', ref.fillStyle);+ setActiveAttr('#fontFamilyRow .seg-btn', 'data-font-family', normalizeFontFamily(ref.fontFamily));+ setActiveAttr('#fontSizeRow .seg-btn', 'data-font-size', ref.fontSize);+ setActiveAttr('#roughnessRow .seg-btn', 'data-roughness', ref.roughness);+ setActiveAttr('#strokeWidthRow .seg-btn', 'data-stroke-width', ref.strokeWidth);+ setActiveAttr('#strokeStyleRow .seg-btn', 'data-stroke-style', ref.strokeStyle);+ setActiveAttr('#curveTypeRow .seg-btn', 'data-curve-type', ref.curveType);+ setActiveAttr('#hudColorDots .hud-dot', 'data-color', ref.strokeColor);+ setActiveAttr('#hudFontGroup .ui-btn', 'data-hud-font', normalizeFontFamily(ref.fontFamily));++ updateHeaderButtons();+ updateQuickHudPosition();+ }++ function applyStyleProperty(prop, value) {+ if (prop === 'fontFamily') value = normalizeFontFamily(value);+ state.defaults[prop] = value;++ if (state.selectedIds.size > 0) {+ pushHistory();+ for (const id of state.selectedIds) {+ const el = state.elements.find(e => e.id === id);+ if (!el) continue;+ el[prop] = value;+ if (prop === 'fontFamily' || prop === 'fontSize') {+ autoFitElementToText(el, el.text);+ }+ ShapeCache.invalidate(el);+ }+ }+ syncUIWithSelection();+ }++ /* -------------------------------------------------------------------------+ * 16. DOM Wiring & 60fps Animation Loop+ * ------------------------------------------------------------------------- */+ function initStudioDOM() {+ if (typeof window === 'undefined' || typeof document === 'undefined') return;+ const staticCanvas = document.getElementById('staticCanvas');+ const interactiveCanvas = document.getElementById('interactiveCanvas');+ if (!staticCanvas || !interactiveCanvas) return;++ const hudDots = document.getElementById('hudColorDots');+ if (hudDots && hudDots.children.length === 0) {+ for (const c of SEMANTIC_COLORS) {+ const dot = document.createElement('button');+ dot.className = 'hud-dot';+ dot.style.background = c.hex;+ dot.setAttribute?.('data-color', c.hex);+ dot.title = c.name;+ dot.addEventListener('click', () => applyStyleProperty('strokeColor', c.hex));+ hudDots.appendChild(dot);+ }+ }++ const resizeCanvases = () => {+ const dpr = window.devicePixelRatio || 1;+ const w = window.innerWidth;+ const h = window.innerHeight;+ for (const c of [staticCanvas, interactiveCanvas]) {+ c.width = Math.floor(w * dpr);+ c.height = Math.floor(h * dpr);+ c.style.width = `${w}px`;+ c.style.height = `${h}px`;+ }+ };+ resizeCanvases();+ window.addEventListener('resize', resizeCanvases);++ interactiveCanvas.addEventListener('pointerdown', e => {+ interactiveCanvas.setPointerCapture?.(e.pointerId);+ const pt = screenToWorld(e.clientX, e.clientY);+ pointerDownWorld(pt.x, pt.y, {+ shiftKey: e.shiftKey,+ altKey: e.altKey,+ screenX: e.clientX,+ screenY: e.clientY+ });+ });++ interactiveCanvas.addEventListener('pointermove', e => {+ const pt = screenToWorld(e.clientX, e.clientY);+ pointerMoveWorld(pt.x, pt.y, {+ shiftKey: e.shiftKey,+ altKey: e.altKey,+ screenX: e.clientX,+ screenY: e.clientY+ });+ });++ interactiveCanvas.addEventListener('pointerup', e => {+ const pt = screenToWorld(e.clientX, e.clientY);+ pointerUpWorld(pt.x, pt.y);+ });++ interactiveCanvas.addEventListener('dblclick', e => {+ const pt = screenToWorld(e.clientX, e.clientY);+ const hit = hitTestElement(pt.x, pt.y);+ if (hit) {+ if (hit.type === 'arrow') {+ pushHistory();+ hit.curveOffset = 0;+ syncUIWithSelection();+ return;+ }+ startInlineEditing(hit);+ } else {+ pushHistory();+ const box = createElement('rectangle', {+ x: pt.x - 72,+ y: pt.y - 34,+ width: 144,+ height: 68,+ text: 'New Node'+ });+ state.elements.push(box);+ state.selectedIds.clear();+ state.selectedIds.add(box.id);+ syncUIWithSelection();+ startInlineEditing(box);+ }+ });++ interactiveCanvas.addEventListener('wheel', e => {+ e.preventDefault();+ if (e.ctrlKey || e.metaKey) {+ const factor = e.deltaY < 0 ? 1.08 : 0.92;+ setZoom(state.zoom * factor, e.clientX, e.clientY);+ } else {+ state.scrollX -= e.deltaX / state.zoom;+ state.scrollY -= e.deltaY / state.zoom;+ updateQuickHudPosition();+ }+ }, { passive: false });++ const ta = document.getElementById('inlineTextEditor');+ if (ta) {+ ta.addEventListener('input', () => {+ const el = state.elements.find(e => e.id === state.editingId);+ if (el) {+ autoFitElementToText(el, ta.value);+ const scr = worldToScreen(el.x + (el.width || 0) / 2, el.y + (el.height || 0) / 2);+ const w = Math.max(120, (el.width || 120) * state.zoom);+ const h = Math.max(36, (el.height || 44) * state.zoom);+ const wrap = document.getElementById('inlineEditorWrap');+ if (wrap) {+ wrap.style.left = `${scr.x - w / 2}px`;+ wrap.style.top = `${scr.y - h / 2}px`;+ }+ ta.style.width = `${w}px`;+ ta.style.height = `${h}px`;+ }+ });+ ta.addEventListener('blur', () => commitInlineEditor());+ }++ window.addEventListener('keydown', e => {+ if (e.code === 'Space' && !state.editingId) {+ state.isSpacePanning = true;+ updateInteractiveCursor();+ }+ handleKeyDown(e);+ });+ window.addEventListener('keyup', e => {+ if (e.code === 'Space') {+ state.isSpacePanning = false;+ updateInteractiveCursor();+ }+ });++ // Drag-and-drop .excaliflow / .excalidraw / .json scene files directly onto the window+ window.addEventListener('dragover', e => e.preventDefault?.());+ window.addEventListener('drop', e => {+ e.preventDefault?.();+ const file = e.dataTransfer?.files?.[0];+ if (!file) return;+ const reader = new FileReader();+ reader.onload = ev => importExcalidrawJson(String(ev.target?.result || ''));+ reader.readAsText(file);+ });++ // Dropdown toggles+ document.getElementById('templatesMenuBtn')?.addEventListener('click', e => {+ e.stopPropagation();+ const menu = document.getElementById('templatesDropdown');+ const wasOpen = menu?.classList.contains('open');+ closeAllDropdowns();+ if (!wasOpen) menu?.classList.add('open');+ });+ document.getElementById('exportMenuBtn')?.addEventListener('click', e => {+ e.stopPropagation();+ const menu = document.getElementById('exportDropdown');+ const wasOpen = menu?.classList.contains('open');+ closeAllDropdowns();+ if (!wasOpen) menu?.classList.add('open');+ });+ window.addEventListener('click', () => closeAllDropdowns());++ document.getElementById('sidebarToggleBtn')?.addEventListener('click', toggleSidebar);+ document.getElementById('btnUndo')?.addEventListener('click', undo);+ document.getElementById('btnRedo')?.addEventListener('click', redo);+ document.getElementById('bgWhiteBtn')?.addEventListener('click', () => setCanvasBackground('#ffffff'));+ document.getElementById('bgBlackBtn')?.addEventListener('click', () => setCanvasBackground('#000000'));++ document.getElementById('masterFlowBtn')?.addEventListener('click', () => {+ state.flowEnabled = !state.flowEnabled;+ updateHeaderButtons();+ });++ document.getElementById('btnSavePng')?.addEventListener('click', save2xPng);+ document.getElementById('btnCopyPng')?.addEventListener('click', copy2xPng);+ document.getElementById('btnRecordVideo')?.addEventListener('click', recordWebmVideo);+ document.getElementById('btnSaveJson')?.addEventListener('click', exportExcalidrawJson);+ document.getElementById('btnLoadJson')?.addEventListener('click', () => {+ document.getElementById('jsonFileInput')?.click();+ });+ document.getElementById('jsonFileInput')?.addEventListener('change', e => {+ const file = e.target.files?.[0];+ if (!file) return;+ const reader = new FileReader();+ reader.onload = ev => importExcalidrawJson(String(ev.target?.result || ''));+ reader.readAsText(file);+ });+ document.getElementById('btnClearScene')?.addEventListener('click', () => {+ closeAllDropdowns();+ pushHistory();+ state.elements = [];+ state.selectedIds.clear();+ ShapeCache.clear();+ syncUIWithSelection();+ });++ document.querySelectorAll('[data-quick-add]').forEach(btn => {+ btn.addEventListener('click', () => quickAddShape(btn.getAttribute('data-quick-add')));+ });++ document.querySelectorAll('#flowModeGrid [data-flow-mode]').forEach(btn => {+ btn.addEventListener('click', () => {+ state.flowMode = btn.getAttribute('data-flow-mode');+ document.querySelectorAll('#flowModeGrid [data-flow-mode]').forEach(b => {+ b.classList.toggle('active', b === btn);+ });+ updateHeaderButtons();+ });+ });++ document.querySelectorAll('#flowSpeedRow [data-flow-speed]').forEach(btn => {+ btn.addEventListener('click', () => {+ state.flowSpeed = Number(btn.getAttribute('data-flow-speed')) || 1;+ document.querySelectorAll('#flowSpeedRow [data-flow-speed]').forEach(b => {+ b.classList.toggle('active', b === btn);+ });+ updateHeaderButtons();+ });+ });++ document.querySelectorAll('#sidebarSwatches .color-swatch').forEach(btn => {+ btn.addEventListener('click', () => applyStyleProperty('strokeColor', btn.getAttribute('data-color')));+ });+ document.querySelectorAll('#fillStyleRow .seg-btn').forEach(btn => {+ btn.addEventListener('click', () => applyStyleProperty('fillStyle', btn.getAttribute('data-fill-style')));+ });+ document.querySelectorAll('#fontFamilyRow .seg-btn').forEach(btn => {+ btn.addEventListener('click', () => applyStyleProperty('fontFamily', btn.getAttribute('data-font-family')));+ });+ document.querySelectorAll('#fontSizeRow .seg-btn').forEach(btn => {+ btn.addEventListener('click', () => applyStyleProperty('fontSize', Number(btn.getAttribute('data-font-size'))));+ });+ document.querySelectorAll('#roughnessRow .seg-btn').forEach(btn => {+ btn.addEventListener('click', () => applyStyleProperty('roughness', Number(btn.getAttribute('data-roughness'))));+ });+ document.querySelectorAll('#strokeWidthRow .seg-btn').forEach(btn => {+ btn.addEventListener('click', () => applyStyleProperty('strokeWidth', Number(btn.getAttribute('data-stroke-width'))));+ });+ document.querySelectorAll('#strokeStyleRow .seg-btn').forEach(btn => {+ btn.addEventListener('click', () => applyStyleProperty('strokeStyle', btn.getAttribute('data-stroke-style')));+ });+ document.querySelectorAll('#curveTypeRow .seg-btn').forEach(btn => {+ btn.addEventListener('click', () => applyStyleProperty('curveType', btn.getAttribute('data-curve-type')));+ });+ document.querySelectorAll('[data-template]').forEach(btn => {+ btn.addEventListener('click', () => {+ closeAllDropdowns();+ loadTemplate(btn.getAttribute('data-template'));+ });+ });++ document.querySelectorAll('#hudFontGroup [data-hud-font]').forEach(btn => {+ btn.addEventListener('click', () => applyStyleProperty('fontFamily', btn.getAttribute('data-hud-font')));+ });+ document.querySelectorAll('#hudNodeControls [data-hud-morph]').forEach(btn => {+ btn.addEventListener('click', () => {+ const newType = btn.getAttribute('data-hud-morph');+ pushHistory();+ for (const id of state.selectedIds) {+ const el = state.elements.find(e => e.id === id);+ if (el && isNodeElement(el)) {+ el.type = newType;+ autoFitElementToText(el, el.text);+ ShapeCache.invalidate(el);+ }+ }+ syncUIWithSelection();+ });+ });+ document.getElementById('hudPulseBtn')?.addEventListener('click', () => triggerNodePulse());+ document.getElementById('hudNextBtn')?.addEventListener('click', () => {+ const firstId = Array.from(state.selectedIds)[0];+ const el = state.elements.find(e => e.id === firstId);+ if (el && isNodeElement(el)) chainNodeFrom(el, 'right', null, true);+ });+ document.querySelectorAll('#hudArrowControls [data-hud-curve]').forEach(btn => {+ btn.addEventListener('click', () => applyStyleProperty('curveType', btn.getAttribute('data-hud-curve')));+ });+ document.getElementById('hudArrowFlowBtn')?.addEventListener('click', () => {+ pushHistory();+ for (const id of state.selectedIds) {+ const el = state.elements.find(e => e.id === id);+ if (el && el.type === 'arrow') el.flowEnabled = el.flowEnabled === false;+ }+ syncUIWithSelection();+ });+ document.getElementById('hudFlipArrowBtn')?.addEventListener('click', () => {+ pushHistory();+ for (const id of state.selectedIds) {+ const el = state.elements.find(e => e.id === id);+ if (el && el.type === 'arrow') {+ const tmpBind = el.startBinding;+ el.startBinding = el.endBinding;+ el.endBinding = tmpBind;+ const tx = el.x, ty = el.y;+ el.x = el.x2; el.y = el.y2;+ el.x2 = tx; el.y2 = ty;+ el.curveOffset = -(Number(el.curveOffset) || 0);+ }+ }+ syncUIWithSelection();+ });+ document.getElementById('hudDuplicateBtn')?.addEventListener('click', duplicateSelection);+ document.getElementById('hudDeleteBtn')?.addEventListener('click', deleteSelection);++ document.getElementById('toolLockBtn')?.addEventListener('click', () => toggleToolLock());+ document.querySelectorAll('#bottomToolDock [data-tool]').forEach(btn => {+ btn.addEventListener('click', () => setTool(btn.getAttribute('data-tool')));+ });++ document.getElementById('zoomOutBtn')?.addEventListener('click', () => setZoom(state.zoom * 0.85));+ document.getElementById('zoomInBtn')?.addEventListener('click', () => setZoom(state.zoom * 1.15));+ document.getElementById('zoomResetBtn')?.addEventListener('click', () => setZoom(1.0));+ document.getElementById('zoomFitBtn')?.addEventListener('click', fitToScreen);++ // Warm up official Excalidraw web fonts (Excalifont, Virgil, Cascadia, Assistant)+ if (document.fonts && document.fonts.load) {+ Promise.allSettled([+ document.fonts.load('16px Excalifont'),+ document.fonts.load('16px Virgil'),+ document.fonts.load('16px Cascadia'),+ document.fonts.load('500 16px Assistant')+ ]);+ }++ loadTemplate('AI Agent Swarm');+ state.history.undoStack = [];+ updateHeaderButtons();++ let lastFrameTime = performance.now() / 1000;+ const tick = (nowMs) => {+ const timeSec = nowMs / 1000;+ const dt = Math.min(0.05, Math.max(0.001, timeSec - lastFrameTime));+ lastFrameTime = timeSec;++ for (let i = state.activePulses.length - 1; i >= 0; i--) {+ const p = state.activePulses[i];+ p.progress += dt * (p.speed || 1.35);+ if (p.progress > 1.05) {+ state.activePulses.splice(i, 1);+ }+ }++ const dpr = window.devicePixelRatio || 1;+ const sCtx = staticCanvas.getContext('2d');+ const iCtx = interactiveCanvas.getContext('2d');++ sCtx.save();+ sCtx.setTransform(1, 0, 0, 1, 0, 0);+ sCtx.fillStyle = state.canvasBg;+ sCtx.fillRect(0, 0, staticCanvas.width, staticCanvas.height);+ sCtx.scale(dpr * state.zoom, dpr * state.zoom);+ sCtx.translate(state.scrollX, state.scrollY);+ const arrowGeoms = renderScenePasses(sCtx, timeSec, { canvasBg: state.canvasBg });+ sCtx.restore();++ iCtx.save();+ iCtx.setTransform(1, 0, 0, 1, 0, 0);+ iCtx.clearRect(0, 0, interactiveCanvas.width, interactiveCanvas.height);+ iCtx.scale(dpr * state.zoom, dpr * state.zoom);+ iCtx.translate(state.scrollX, state.scrollY);+ drawInteractiveOverlay(iCtx, arrowGeoms);+ iCtx.restore();++ requestAnimationFrame(tick);+ };+ requestAnimationFrame(tick);+ }++ if (typeof window !== 'undefined') {+ Object.assign(window, {+ state,+ mulberry32,+ clipSegmentToShape,+ clampPointToShapeInterior,+ roughEdge,+ roughRoundRect,+ roughEllipse,+ ShapeCache,+ drawStaticElement,+ drawElementText,+ computeGraphDepths,+ triggerNodePulse,+ getArrowGeometry,+ computeBindingForShape,+ getBindingBoundaryPoint,+ findMagneticShape,+ hitTestArrowHandle,+ hitTestQuickPorts,+ hitTestElement,+ autoFitElementToText,+ findSplitTargetArrow,+ trySplitArrowWithNode,+ getDiagramExportBounds,+ renderScenePasses,+ pointerDownWorld,+ pointerMoveWorld,+ pointerUpWorld,+ handleKeyDown,+ setTool,+ toggleToolLock,+ loadTemplate,+ quickAddShape,+ createElement,+ cloneElementsWithBindings,+ undo,+ redo,+ importExcalidrawJson+ });+ window.addEventListener('DOMContentLoaded', initStudioDOM);+ }+ </script>+</body>+</html>diff --git a/generative_ui_agents/excaliflow/package.json b/generative_ui_agents/excaliflow/package.jsonnew file mode 100644index 00000000..0112f9fb--- /dev/null+++ b/generative_ui_agents/excaliflow/package.json@@ -0,0 +1,14 @@+{+ "name": "excaliflow",+ "version": "1.0.0",+ "description": "Hand-drawn system diagrams with live animated data flows and video export",+ "main": "server.js",+ "scripts": {+ "start": "node server.js",+ "test": "node verify.js"+ },+ "engines": {+ "node": ">=18.0.0"+ },+ "license": "Apache-2.0"+}diff --git a/generative_ui_agents/excaliflow/server.js b/generative_ui_agents/excaliflow/server.jsnew file mode 100644index 00000000..4b9d806c--- /dev/null+++ b/generative_ui_agents/excaliflow/server.js@@ -0,0 +1,92 @@+const http = require('http');+const fs = require('fs');+const path = require('path');++const PORT = Number(process.env.PORT) || 3000;+const ROOT = path.resolve(__dirname);++const MIME_TYPES = {+ '.html': 'text/html; charset=utf-8',+ '.js': 'application/javascript; charset=utf-8',+ '.css': 'text/css; charset=utf-8',+ '.json': 'application/json; charset=utf-8',+ '.excaliflow': 'application/json; charset=utf-8',+ '.excalidraw': 'application/json; charset=utf-8',+ '.png': 'image/png',+ '.webp': 'image/webp',+ '.svg': 'image/svg+xml',+ '.ico': 'image/x-icon',+ '.woff2': 'font/woff2',+ '.woff': 'font/woff',+ '.ttf': 'font/ttf',+ '.webm': 'video/webm',+ '.mp4': 'video/mp4'+};++const server = http.createServer((req, res) => {+ if (req.method !== 'GET' && req.method !== 'HEAD') {+ res.writeHead(405, { 'Content-Type': 'text/plain; charset=utf-8' });+ res.end('405 Method Not Allowed');+ return;+ }++ let decodedUrl = '/';+ try {+ decodedUrl = decodeURIComponent((req.url || '/').split('?')[0]);+ } catch {+ res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' });+ res.end('400 Bad Request');+ return;+ }++ const relPath = decodedUrl === '/' ? 'index.html' : decodedUrl.replace(/^\/+/, '');+ const safePath = path.resolve(ROOT, relPath);++ if (safePath !== ROOT && !safePath.startsWith(ROOT + path.sep)) {+ res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' });+ res.end('403 Forbidden');+ return;+ }++ fs.stat(safePath, (statErr, stats) => {+ if (statErr || !stats.isFile()) {+ res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });+ res.end('404 Not Found');+ return;+ }++ const ext = path.extname(safePath).toLowerCase();+ const contentType = MIME_TYPES[ext] || 'application/octet-stream';++ if (req.method === 'HEAD') {+ res.writeHead(200, {+ 'Content-Type': contentType,+ 'Content-Length': stats.size,+ 'Cache-Control': 'no-cache'+ });+ res.end();+ return;+ }++ fs.readFile(safePath, (readErr, data) => {+ if (readErr) {+ res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' });+ res.end('500 Internal Server Error');+ return;+ }+ res.writeHead(200, {+ 'Content-Type': contentType,+ 'Cache-Control': 'no-cache'+ });+ res.end(data);+ });+ });+});++if (require.main === module) {+ server.listen(PORT, () => {+ console.log(`Excaliflow Studio running at http://localhost:${PORT}`);+ });+}++module.exports = server;diff --git a/generative_ui_agents/excaliflow/verify.js b/generative_ui_agents/excaliflow/verify.jsnew file mode 100644index 00000000..67f52061--- /dev/null+++ b/generative_ui_agents/excaliflow/verify.js@@ -0,0 +1,348 @@+const fs = require('fs');+const path = require('path');+const vm = require('vm');+const assert = require('assert');++const htmlPath = path.join(__dirname, 'index.html');+const html = fs.readFileSync(htmlPath, 'utf8');++const scriptMatch = html.match(/<script>([\s\S]*?)<\/script>/);+assert(scriptMatch, 'Could not find <script> block in index.html');+const scriptCode = scriptMatch[1];++// Instrumented Path2D that records every point added to it+class MockPath2D {+ constructor() {+ this.ops = [];+ this.points = [];+ }+ moveTo(x, y) {+ this.ops.push({ type: 'moveTo', x, y });+ this.points.push({ x, y });+ }+ lineTo(x, y) {+ this.ops.push({ type: 'lineTo', x, y });+ this.points.push({ x, y });+ }+ quadraticCurveTo(cpx, cpy, x, y) {+ this.ops.push({ type: 'quadraticCurveTo', cpx, cpy, x, y });+ this.points.push({ x: cpx, y: cpy }, { x, y });+ }+ bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) {+ this.ops.push({ type: 'bezierCurveTo', cp1x, cp1y, cp2x, cp2y, x, y });+ this.points.push({ x: cp1x, y: cp1y }, { x: cp2x, y: cp2y }, { x, y });+ }+ ellipse(cx, cy, rx, ry, rot, start, end) {+ this.ops.push({ type: 'ellipse', cx, cy, rx, ry, rot, start, end });+ }+ closePath() {+ this.ops.push({ type: 'closePath' });+ }+}++function createMockCtx() {+ const calls = [];+ const fontsUsed = [];+ let currentFont = '';+ return {+ calls,+ fontsUsed,+ get font() { return currentFont; },+ set font(v) { currentFont = v; fontsUsed.push(v); },+ save() { calls.push({ fn: 'save' }); },+ restore() { calls.push({ fn: 'restore' }); },+ beginPath() { calls.push({ fn: 'beginPath' }); },+ closePath() { calls.push({ fn: 'closePath' }); },+ moveTo(x, y) { calls.push({ fn: 'moveTo', x, y }); },+ lineTo(x, y) { calls.push({ fn: 'lineTo', x, y }); },+ quadraticCurveTo(cpx, cpy, x, y) { calls.push({ fn: 'quadraticCurveTo', cpx, cpy, x, y }); },+ bezierCurveTo(a, b, c, d, e, f) { calls.push({ fn: 'bezierCurveTo', a, b, c, d, e, f }); },+ arc(x, y, r, s, e) { calls.push({ fn: 'arc', x, y, r, s, e }); },+ ellipse(x, y, rx, ry) { calls.push({ fn: 'ellipse', x, y, rx, ry }); },+ fill(pathObj) { calls.push({ fn: 'fill', pathObj }); },+ stroke(pathObj) { calls.push({ fn: 'stroke', pathObj }); },+ clip(pathObj) { calls.push({ fn: 'clip', pathObj }); },+ fillRect(x, y, w, h) { calls.push({ fn: 'fillRect', x, y, w, h }); },+ strokeRect(x, y, w, h) { calls.push({ fn: 'strokeRect', x, y, w, h }); },+ clearRect(x, y, w, h) { calls.push({ fn: 'clearRect', x, y, w, h }); },+ setLineDash(d) { calls.push({ fn: 'setLineDash', d }); },+ setTransform() {},+ scale() {},+ translate() {},+ fillText(text, x, y) { calls.push({ fn: 'fillText', text, x, y, font: currentFont }); },+ measureText(text) { return { width: String(text || '').length * 8.5 }; }+ };+}++const mockCanvas = {+ width: 1440,+ height: 900,+ style: {},+ attrs: {},+ setAttribute(k, v) { this.attrs[k] = v; },+ getAttribute(k) { return this.attrs[k]; },+ getContext: () => createMockCtx(),+ addEventListener: () => {}+};++const sandbox = {+ console,+ Math,+ Number,+ String,+ Boolean,+ Array,+ Object,+ Set,+ Map,+ Float64Array,+ JSON,+ Path2D: MockPath2D,+ performance: { now: () => 1234.5 },+ requestAnimationFrame: () => 1,+ setTimeout: () => 1,+ clearTimeout: () => {},+ setInterval: () => 1,+ clearInterval: () => {},+ window: {+ innerWidth: 1440,+ innerHeight: 900,+ devicePixelRatio: 2,+ addEventListener: () => {}+ },+ document: {+ body: { classList: { toggle: () => {} } },+ getElementById: () => ({+ width: 1440,+ height: 900,+ style: {},+ children: [],+ classList: { toggle: () => {}, add: () => {}, remove: () => {}, contains: () => false },+ addEventListener: () => {},+ appendChild: () => {},+ getContext: () => createMockCtx()+ }),+ querySelectorAll: () => [],+ createElement: () => mockCanvas+ }+};++console.log('--- Excaliflow Automated Verification Suite ---');+assert(html.includes('Excaliflow') && !html.includes('AtelierFlow'), 'index.html should use Excaliflow branding everywhere');++// 1. Verify Zero Syntax or Runtime Initialization Errors+vm.createContext(sandbox);+vm.runInContext(scriptCode, sandbox);+sandbox.initStudioDOM();+const app = sandbox.window;+assert(app.state.elements.length > 0, 'Initial template should populate elements');+console.log('[PASS] 1. Zero syntax or runtime initialization errors (initial scene loaded)');++// 2. Verify Zero-Bleed Analytical Hachure & Cross-Hatch Clipping + ctx.clip(paths.fillPath)+for (const fillStyle of ['hachure', 'cross-hatch']) {+ const ellipseEl = app.createElement('ellipse', {+ x: 120,+ y: 160,+ width: 180,+ height: 110,+ fillStyle,+ roughness: 1.75+ });+ const ellipsePaths = app.ShapeCache.generate(ellipseEl);+ assert(ellipsePaths.hachurePath.points.length > 10, `Ellipse ${fillStyle} should generate hatch points`);++ const ecx = ellipseEl.x + ellipseEl.width / 2;+ const ecy = ellipseEl.y + ellipseEl.height / 2;+ const erx = ellipseEl.width / 2;+ const ery = ellipseEl.height / 2;+ for (const pt of ellipsePaths.hachurePath.points) {+ const normDist = ((pt.x - ecx) / erx) ** 2 + ((pt.y - ecy) / ery) ** 2;+ assert(+ normDist <= 1.0001,+ `Ellipse ${fillStyle} point (${pt.x.toFixed(2)}, ${pt.y.toFixed(2)}) bled outside boundary: normDist=${normDist}`+ );+ }++ const diamondEl = app.createElement('diamond', {+ x: 340,+ y: 160,+ width: 190,+ height: 120,+ fillStyle,+ roughness: 1.75+ });+ const diamondPaths = app.ShapeCache.generate(diamondEl);+ assert(diamondPaths.hachurePath.points.length > 10, `Diamond ${fillStyle} should generate hatch points`);++ const dcx = diamondEl.x + diamondEl.width / 2;+ const dcy = diamondEl.y + diamondEl.height / 2;+ const dhw = diamondEl.width / 2;+ const dhh = diamondEl.height / 2;+ for (const pt of diamondPaths.hachurePath.points) {+ const l1Dist = Math.abs(pt.x - dcx) / dhw + Math.abs(pt.y - dcy) / dhh;+ assert(+ l1Dist <= 1.0001,+ `Diamond ${fillStyle} point (${pt.x.toFixed(2)}, ${pt.y.toFixed(2)}) bled outside boundary: l1Dist=${l1Dist}`+ );+ }++ // Verify drawStaticElement calls ctx.clip(paths.fillPath) before stroking hachurePath+ const testCtx = createMockCtx();+ const cached = app.ShapeCache.get(ellipseEl);+ app.drawStaticElement(testCtx, ellipseEl);+ const clipIdx = testCtx.calls.findIndex(c => c.fn === 'clip' && c.pathObj === cached.fillPath);+ const hachureStrokeIdx = testCtx.calls.findIndex(c => c.fn === 'stroke' && c.pathObj === cached.hachurePath);+ assert(clipIdx !== -1, 'drawStaticElement must invoke ctx.clip(paths.fillPath)');+ assert(hachureStrokeIdx > clipIdx, 'hachurePath stroke must occur after ctx.clip(paths.fillPath)');+}+console.log('[PASS] 2. Zero-bleed analytical interior clipping & double-safety ctx.clip(paths.fillPath) verified');++// 3. Verify 1-Click Unselected Arrow Endpoint Grabbing, Perimeter Sliding (focusAngle) & Cross-Shape Rebinding+app.state.elements = [];+app.state.selectedIds.clear();+app.state.zoom = 1;++const boxA = app.createElement('rectangle', { id: 'node_A', x: 100, y: 200, width: 140, height: 80, text: 'Node A' });+const boxB = app.createElement('rectangle', { id: 'node_B', x: 420, y: 200, width: 140, height: 80, text: 'Node B' });+const boxC = app.createElement('ellipse', { id: 'node_C', x: 420, y: 380, width: 150, height: 90, text: 'Node C' });+const arrowAB = app.createElement('arrow', {+ id: 'arrow_AB',+ x: 240,+ y: 240,+ x2: 420,+ y2: 240,+ startBinding: { elementId: 'node_A', focusAngle: 0, gap: 4 },+ endBinding: { elementId: 'node_B', focusAngle: Math.PI, gap: 4 }+});+app.state.elements.push(boxA, boxB, boxC, arrowAB);++// Ensure arrowAB is NOT selected initially+assert(!app.state.selectedIds.has('arrow_AB'), 'Arrow should start unselected');+const geomAB = app.getArrowGeometry(arrowAB);+const hitEnd = app.hitTestArrowHandle(geomAB.p1.x + 6, geomAB.p1.y - 4);+assert(hitEnd && hitEnd.elementId === 'arrow_AB' && hitEnd.handle === 'end', 'hitTestArrowHandle must grab unselected arrow endpoint');++// Verify computeBindingForShape & getBindingBoundaryPoint slide across top and bottom perimeters+const topPt = { x: boxB.x + boxB.width / 2, y: boxB.y - 2 };+const bindTop = app.computeBindingForShape(boxB, topPt);+assert(Math.abs(bindTop.focusAngle - (-Math.PI / 2)) < 0.05, 'Top perimeter focusAngle should be ~ -PI/2');+const boundTopPt = app.getBindingBoundaryPoint(boxB, bindTop, geomAB.p0, 4);+assert(Math.abs(boundTopPt.y - (boxB.y - 4)) < 1.5, 'Boundary point should lie on top edge of boxB');++const bottomPt = { x: boxB.x + boxB.width / 2, y: boxB.y + boxB.height + 2 };+const bindBottom = app.computeBindingForShape(boxB, bottomPt);+assert(Math.abs(bindBottom.focusAngle - (Math.PI / 2)) < 0.05, 'Bottom perimeter focusAngle should be ~ +PI/2');+const boundBottomPt = app.getBindingBoundaryPoint(boxB, bindBottom, geomAB.p0, 4);+assert(Math.abs(boundBottomPt.y - (boxB.y + boxB.height + 4)) < 1.5, 'Boundary point should lie on bottom edge of boxB');++// Drag arrowAB's end handle from boxB across to boxC+app.setTool('select');+app.pointerDownWorld(geomAB.p1.x, geomAB.p1.y);+app.pointerMoveWorld(boxC.x + 8, boxC.y + boxC.height / 2);+app.pointerUpWorld(boxC.x + 8, boxC.y + boxC.height / 2);+assert.strictEqual(arrowAB.endBinding?.elementId, 'node_C', 'Dragging arrow endpoint onto Node C must rebind endBinding.elementId');+console.log('[PASS] 3. 1-click unselected arrow endpoint grabbing, perimeter sliding (focusAngle), and cross-shape rebinding verified');++// 4. Verify Direct Bound-Arrow Middle Drag in Select Mode Updates arrow.curveOffset+arrowAB.curveOffset = 0;+const currentGeom = app.getArrowGeometry(arrowAB);+const midPt = currentGeom.curveHandlePt;+app.state.selectedIds.clear(); // Even without prior selection, clicking & dragging bound arrow shaft in Select mode bends curve+app.pointerDownWorld(midPt.x, midPt.y);+app.pointerMoveWorld(midPt.x - 50, midPt.y + 50);+app.pointerUpWorld(midPt.x - 50, midPt.y + 50);+assert(Math.abs(arrowAB.curveOffset) > 40, `Expected arrow.curveOffset to update when dragging middle shaft, got ${arrowAB.curveOffset}`);+console.log('[PASS] 4. Direct bound-arrow middle shaft drag in Select mode updates arrow.curveOffset');++// 5. Verify Excalidraw Font Families (Excalifont/Virgil, Assistant/Nunito, Cascadia), Unbroken Arrows (no text/gaps), Tool Lock (Q), Laser Pointer (K), Number Shortcuts (1-9, 0), and triggerNodePulse+const fontTestCtx = createMockCtx();+for (const [fam, expectedSubstrs] of [+ ['hand', ['Excalifont', 'Virgil', 'Patrick Hand']],+ ['sans', ['Assistant', 'Nunito', 'Geist']],+ ['code', ['Cascadia', 'Geist Mono']]+]) {+ const fNode = app.createElement('rectangle', { x: 50, y: 50, width: 120, height: 60, text: 'Hello', fontFamily: fam });+ app.drawElementText(fontTestCtx, fNode, { forExport: true });+ const lastFont = fontTestCtx.fontsUsed[fontTestCtx.fontsUsed.length - 1];+ for (const sub of expectedSubstrs) {+ assert(lastFont.includes(sub), `Font family '${fam}' should include '${sub}', got '${lastFont}'`);+ }+}++// Verify arrows never render text or create gaps in between arrows+const arrowWithText = app.createElement('arrow', { x: 100, y: 100, x2: 300, y2: 100, text: 'ShouldNotRender' });+const arrowGeomCheck = app.getArrowGeometry(arrowWithText);+assert.strictEqual(arrowGeomCheck.labelBox, null, 'Arrows must not have labelBox');+assert.strictEqual(arrowGeomCheck.gapStartDist, -1, 'Arrows must not cut gaps in between shafts');+const arrowTextCtx = createMockCtx();+app.drawElementText(arrowTextCtx, arrowWithText, { forExport: true });+assert.strictEqual(arrowTextCtx.calls.filter(c => c.fn === 'fillText').length, 0, 'drawElementText must never write text on arrows');++// Tool Lock ('Q')+assert.strictEqual(app.state.toolLocked, false, 'Tool lock starts false');+app.handleKeyDown({ key: 'q' });+assert.strictEqual(app.state.toolLocked, true, 'Pressing Q should enable toolLock');+app.handleKeyDown({ key: 'q' });+assert.strictEqual(app.state.toolLocked, false, 'Pressing Q again should disable toolLock');++// Laser Pointer ('K')+app.handleKeyDown({ key: 'k' });+assert.strictEqual(app.state.activeTool, 'laser', 'Pressing K should select laser tool');+app.pointerDownWorld(200, 200);+app.pointerMoveWorld(240, 220);+app.pointerUpWorld(240, 220);+assert(app.state.laserPoints.length >= 2, 'Laser tool drag should record glowing trail points');++// Number shortcuts (1-9, 0)+const expectedNumberTools = {+ '1': 'select',+ '2': 'rectangle',+ '3': 'diamond',+ '4': 'ellipse',+ '5': 'arrow',+ '6': 'arrow',+ '7': 'freedraw',+ '8': 'text',+ '9': 'sticky',+ '0': 'eraser'+};+for (const [numKey, expectedTool] of Object.entries(expectedNumberTools)) {+ app.handleKeyDown({ key: numKey });+ assert.strictEqual(app.state.activeTool, expectedTool, `Shortcut '${numKey}' should activate '${expectedTool}'`);+}++// triggerNodePulse+const prevPulseCount = app.state.activePulses.length;+const spawned = app.triggerNodePulse('node_A');+assert(spawned > 0 && app.state.activePulses.length > prevPulseCount, 'triggerNodePulse should spawn active burst packets along outgoing arrows');+assert(html.includes('<span>Excaliflow</span>') && !html.includes('AtelierFlow'), 'Brand name must be Excaliflow everywhere');+console.log('[PASS] 5. Font families (Hand/Sans/Code), Tool Lock (Q), Laser Pointer (K), shortcuts (1-9, 0), and triggerNodePulse verified');++// 6. Verify Port-Wire Drag to Empty Canvas, Undo Stack Click Integrity & Subgraph Cloning+app.setTool('select');+app.state.selectedIds.clear();+app.state.selectedIds.add('node_A');+app.state.history.undoStack = [];+const undoCountBeforeClick = app.state.history.undoStack.length;+// Click on node_A without moving it+app.pointerDownWorld(boxA.x + 20, boxA.y + 20);+app.pointerUpWorld(boxA.x + 20, boxA.y + 20);+assert.strictEqual(app.state.history.undoStack.length, undoCountBeforeClick, 'Clicking a node without moving must not leave a no-op snapshot on undoStack');++// Drag from node_A right quick-connect port onto empty canvas (800, 500)+const rightPortX = boxA.x + boxA.width + 18;+const rightPortY = boxA.y + boxA.height / 2;+const elemCountBeforeWire = app.state.elements.length;+app.pointerDownWorld(rightPortX, rightPortY);+app.pointerMoveWorld(800, 500);+app.pointerUpWorld(800, 500);+assert.strictEqual(app.state.elements.length, elemCountBeforeWire + 2, 'Dragging port-wire onto empty canvas must create a connected node + arrow');++// Clone subgraph and verify internal bindings remap+const cloned = app.cloneElementsWithBindings([boxA, boxC, arrowAB], 40, 40);+assert.strictEqual(cloned.length, 3, 'Should clone 3 elements');+const clonedArrow = cloned.find(c => c.type === 'arrow');+assert(clonedArrow.startBinding.elementId !== 'node_A' && clonedArrow.endBinding.elementId !== 'node_C', 'Cloned arrow bindings must remap to cloned node IDs');+console.log('[PASS] 6. Port-wire drag to empty canvas, no-op click undo guard, and subgraph binding clone verified');++console.log('\nALL EXCALIFLOW VERIFICATION CHECKS PASSED SUCCESSFULLY!');