AI-native design editor. Open-source Figma alternative.
Refactor architecture boundaries across core, app, and packages (#234)
Danila Poyarkov6545f20c537f
diff --git a/AGENTS.md b/AGENTS.mdindex ee6574710..01def8fb6 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -2,7 +2,7 @@Vue 3 + CanvasKit (Skia WASM) + Yoga WASM design editor. Tauri v2 desktop, also runs in browser.-**Roadmap:** `plan.md` — phases, tech stack, CLI architecture, test strategy, keyboard shortcuts.+**Roadmap:** `PLAN.md` — phases, tech stack, CLI architecture, test strategy, keyboard shortcuts.## Monorepo@@ -15,7 +15,7 @@ Bun workspace with three packages:- `packages/vue` — `@open-pencil/vue`: headless Vue 3 SDK (Reka UI-style) for building custom OpenPencil-powered editor shells and embedded editing surfaces. Renderless components and composables. The app is one consumer of the SDK.-The root app (`src/`) is the Tauri/Vite desktop editor. Its `src/engine/` files are thin re-export shims from `@open-pencil/core`. `src/composables/use-canvas.ts` re-exports from `@open-pencil/vue`.+The root app (`src/`) is the Tauri/Vite desktop editor. App-specific editor, document, AI, collaboration, shell, tabs, demo, and automation code lives under `src/app/*`. The app consumes `@open-pencil/core` through targeted core subpath exports and `@open-pencil/vue` through the public Vue SDK entrypoint.### Core subpath exports@@ -66,7 +66,7 @@ Each module exports a factory: `createXxxActions(ctx: EditorContext) => { ... }``create.ts` assembles context + all modules, spreads into a flat return object.`Editor` type = `ReturnType<typeof createEditor>`.-The app store (`src/stores/editor.ts`) is a thin Vue wrapper: creates `shallowReactive` state, calls `createEditor()`, adds Vue-specific concerns (computed refs, file I/O, autosave, export, image placement, mobile clipboard).+The app editor session (`src/app/editor/session/create.ts`) is a thin Vue wrapper: creates `shallowReactive` state, calls `createEditor()`, and assembles app-specific modules for document I/O, autosave, export, vector edit, pen resume, flashes, profiler, and mobile clipboard. Tabs live in `src/app/tabs/`; active editor access lives in `src/app/editor/active-store/`.## Commands@@ -176,21 +176,21 @@ Release commits are the exception: keep using `Release v0.x.y`.- Each tool has: name, description, typed params, and an `execute(figma: FigmaAPI, args)` function- `defineTool()` gives type-safe params in the execute body; the array `ALL_TOOLS` erases the generics for adapters- AI adapter (`packages/core/src/tools/ai-adapter.ts`): `toolsToAI()` converts ToolDefs → valibot schemas + Vercel AI `tool()` wrappers-- `src/ai/tools.ts` is just a thin wire: creates FigmaAPI from editor store, calls `toolsToAI()`+- `src/app/ai/tools/index.ts` is just a thin wire: creates FigmaAPI from editor store, calls `toolsToAI()`- CLI commands (`packages/cli/src/commands/`) are **not** generated from ToolDefs — they have custom agentfmt formatting, tree walking, pagination. The `eval` command is the CLI's access to all ToolDef operations via FigmaAPI.- MCP adapter (`packages/mcp/src/server.ts`): `startServer()` creates unified HTTP + WebSocket server. Registers all ToolDefs as MCP tools (zod schemas). Single entry point: `index.ts` (Hono + Streamable HTTP with sessions). Browser connects via WebSocket, tool calls proxied through.- MCP-only tools (`open_file`, `new_document`, `save_file`, `get_codegen_prompt`) are registered directly in `server.ts`, not as ToolDefs — they need Node.js fs access or don't operate on the scene graph- `open_file` and `new_document` are only registered when `OPENPENCIL_MCP_ROOT` is set (path scoping for security)- Export tools (`export_image`, `export_svg`, `get_jsx`) accept an optional `path` param — when provided and `OPENPENCIL_MCP_ROOT` is set, the MCP server writes output to disk and returns `{ written, byteLength }` instead of the raw data-- Prompts (`CODEGEN_PROMPT`, `JSX_REFERENCE`) live as markdown files in `packages/core/src/tools/prompts/`, loaded via raw-md bundler plugin+- Core prompts (`CODEGEN_PROMPT`, `JSX_REFERENCE`) live as markdown files in `packages/core/src/tools/prompts/`, loaded via raw-md bundler plugin; app chat/ACP prompts live under `src/app/ai/**` markdown files.- To add a new tool: add a `defineTool()` in the appropriate domain file, add to `ALL_TOOLS` in `registry.ts` — it's instantly available in AI chat, MCP, and via `eval` in CLI-- `FigmaAPI` (`packages/core/src/figma-api.ts`) is the execution target for all tools — Figma Plugin API compatible, uses Symbols for hidden internals+- `FigmaAPI` (`packages/core/src/figma-api/`) is the execution target for all tools — Figma Plugin API compatible, uses Symbols for hidden internals## ACP (Agent Client Protocol)-- ACP transport (`src/ai/acp-transport.ts`) spawns agents via dynamic import of `@tauri-apps/plugin-shell`-- Pure mapping logic in `src/ai/acp-map-update.ts` — converts `SessionUpdate` → `UIMessageChunk`-- System prompt (`ACP_DESIGN_CONTEXT`) in `src/constants.ts`+- ACP transport (`src/app/ai/acp/transport.ts`) spawns agents via dynamic import of `@tauri-apps/plugin-shell`+- Pure mapping logic in `src/app/ai/acp/map-update.ts` — converts `SessionUpdate` → `UIMessageChunk`+- ACP design context prompt (`ACP_DESIGN_CONTEXT`) is authored in `src/app/ai/acp/design-context.md` and re-exported from `src/constants.ts`- Agent definitions (`ACP_AGENTS`) in `packages/core/src/constants.ts`- MCP server: Vite plugin in dev, `openpencil-mcp` via shell plugin in production Tauri (requires `npm i -g @open-pencil/mcp`; follow-up: bundle as Tauri sidecar)- Architecture: browser ↔ WebSocket :7601 ↔ MCP server :7600 ↔ HTTP ↔ agent subprocess@@ -204,7 +204,7 @@ Release commits are the exception: keep using `Release v0.x.y`.- Yjs CRDT for document state sync. Awareness protocol for cursors/selections/presence.- y-indexeddb for local persistence — room survives page refresh.- Constants in `src/constants.ts`: `TRYSTERO_APP_ID`, `PEER_COLORS`, `ROOM_ID_LENGTH`, `ROOM_ID_CHARS`, `YJS_JSON_FIELDS`-- `src/composables/use-collab.ts` — composable: connect/disconnect, cursor/selection broadcasting, follow mode, Yjs ↔ SceneGraph sync+- `src/app/collab/use.ts` — composable: connect/disconnect, cursor/selection broadcasting, follow mode, Yjs ↔ SceneGraph sync- Provided via `COLLAB_KEY` injection — `useCollabInjected()` in child components- ICE servers: Google STUN + Cloudflare STUN + Open Relay TURN (TCP + UDP)- Room IDs use `crypto.getRandomValues()` — no `Math.random()` anywhere in codebase@@ -212,16 +212,30 @@ Release commits are the exception: keep using `Release v0.x.y`.## Code conventions-- `@/` import alias for app cross-directory imports, relative imports within core+### File and folder naming++OpenPencil follows a Reka UI-inspired component namespace structure:++- Vue component namespace folders use PascalCase: `ColorPicker/`, `Toolbar/`, `ProviderSettings/`.+- Vue component files use PascalCase: `ColorPickerRoot.vue`, `ToolbarItem.vue`.+- Component-scoped composables use camelCase: `useToolbarState.ts`, `usePageList.ts`.+- Non-component domain folders use lowercase or kebab-case: `scene-graph/`, `figma-api/`, `node-edit/`.+- Non-component TypeScript files use lowercase or kebab-case unless they are conventional entrypoints such as `index.ts`, `types.ts`, `context.ts`, or `use.ts`.+- Multi-file root components live inside their component namespace folder, not beside it.+- Use subfolders for multi-file domains instead of many sibling files with repeated prefixes. Prefer `selection/container.ts`, `selection/hit-test.ts`, `selection/overlays.ts` over `selection-container.ts`, `selection-hit-test.ts`, `selection-overlays.ts`; prefer `tools/schema.ts`, `tools/registration.ts` over `tool-schema.ts`, `tool-registration.ts`. A short prefix is acceptable only when there are one or two files, for conventional test names, or when splitting would create empty wrapper directories.++- `@/` import alias for app cross-directory imports; app feature code lives under `src/app/*`+- Use package-local aliases inside workspace packages: `#vue/*` in `packages/vue`, `#cli/*` in `packages/cli`, `#mcp/*` in `packages/mcp`, and `#core/*` when core code needs an alias. Prefer relative imports within nearby core modules when that is clearer than an alias.- No `any` — use proper types, generics, declaration merging- No `!` non-null assertions — use guards, `?.`, `??`- No `Math.random()` — use `crypto.getRandomValues()` everywhere-- No inline type definitions when a named type exists — use `Color` not `{ r: number; g: number; b: number; a: number }`, use `Vector` not `{ x: number; y: number }`, use `SceneNode` / `Effect` / `Fill` / `Stroke` from `scene-graph.ts` instead of re-spelling their shapes inline+- No inline type definitions when a named type exists — use `Color` not `{ r: number; g: number; b: number; a: number }`, use `Vector` not `{ x: number; y: number }`, use `SceneNode` / `Effect` / `Fill` / `Stroke` from `@open-pencil/core/scene-graph` instead of re-spelling their shapes inline- Shared types (GUID, Color, Vector, Matrix, Rect) live in `packages/core/src/types.ts`-- Domain types (SceneNode, Fill, Stroke, Effect, BlendMode, etc.) live in `packages/core/src/scene-graph.ts`+- Domain types (SceneNode, Fill, Stroke, Effect, BlendMode, etc.) live in `packages/core/src/scene-graph/` and are exported from `@open-pencil/core/scene-graph`- Window API extensions (showOpenFilePicker, queryLocalFonts) live in `src/global.d.ts` and `packages/core/src/global.d.ts`- Use `culori` for color conversions — don't reimplement parseColor/colorToRgba- Use `@vueuse/core` hooks — prefer higher-level composables (`useBreakpoints`, `useEventListener`, `onClickOutside`, etc.) over raw APIs (`useMediaQuery`, manual `addEventListener`)+- Prefer VueUse utilities for simple browser/timer state: `refAutoReset` for temporary copied/saved flags, `promiseTimeout` for async sleeps/retry backoff, `useClipboard`/`useFileDialog`/`useLocalStorage` where they fit the local state model. Don't force VueUse when direct APIs are clearer: one-shot `requestAnimationFrame` focus/defer calls, explicit service-owned reconnect/permission timers, or nanostores-backed state can stay hand-rolled.- No module-level mutable state in components — use the editor store- Prefer `tw-animate-css` for animations — don't hand-write `<style>` transition keyframes- No duplicated component logic — if two components share data (icon maps, util functions, constants), export from one place and import in both@@ -303,9 +317,9 @@ Self-review checklist:## File format-- .fig files use Kiwi binary codec — schema in `packages/core/src/kiwi/codec.ts`+- .fig files use Kiwi binary codec — schema in `packages/core/src/kiwi/binary/codec.ts`- `NodeChange` is the central type for Kiwi encode/decode-- Vector data uses reverse-engineered `vectorNetworkBlob` binary format — encoder/decoder in `packages/core/src/vector.ts`+- Vector data uses reverse-engineered `vectorNetworkBlob` binary format — encoder/decoder in `packages/core/src/vector/`- showOpenFilePicker/showSaveFilePicker are File System Access API (Chrome/Edge), not Tauri-only — code has fallbacks- Safari save: no File System Access API → uses `<a>` download link with deferred `revokeObjectURL`. SafariBanner warns users about limitations.- Tauri detection: `IS_TAURI` constant from `packages/core/src/constants.ts` — don't use `'__TAURI_INTERNALS__' in window` inlinediff --git a/CHANGELOG.md b/CHANGELOG.mdindex b9e96adcf..4728780c6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,13 @@## Unreleased+### Changed++- Refactor the editor architecture across core, app, Vue SDK, CLI, MCP, docs, and desktop into smaller domain modules with structural lint rules to keep package boundaries explicit.+- Add targeted core subpath exports and package-local import aliases for cleaner app, Vue SDK, CLI, and MCP imports.+- Split the canvas into separate scene and overlay render layers so rulers, labels, selections, and input overlays are isolated from scene rendering.+- Use `@use-gesture/vanilla` for wheel gesture lifecycle handling and faster trackpad zoom behavior.+### Fixes- Fix `@open-pencil/vue` failing to import from npm — `getAbsolutePositionFull` was imported from `@open-pencil/core/canvas/coordinate`, an unexported subpath. Re-exported the function from `@open-pencil/core/canvas` and updated the vue import.@@ -10,10 +17,16 @@- Improve Figma render fidelity for exports — preserve flipped vector bounds, render Figma stroke geometry for shapes/vectors, fix clipped visual overflow, and render drop shadows for stroked shapes from the stroke outline.- Fix text editing inside selected components and instances on double-click.- Prevent browser/Safari from intercepting app-level Cmd/Ctrl shortcuts such as undo/redo.+- Fix undo/redo shortcuts firing twice during modifier-key release by handling command shortcuts with event-based dispatch.+- Fix option-drag duplicate undo/redo so undo removes duplicated subtrees and redo restores them instead of moving the copy back.+- Fix section drawing errors and color input attribute forwarding in the property panel.+- Fix demo component instances by laying out source components before creating instances, and restore explicit badge dot/text spacing.+- Keep the global startup loader visible until CanvasKit fonts load and the first font-backed render completes, avoiding a flash of missing text in opened files and the demo.### Performance- Cache instance override resolution and lazily populate opened `.fig` pages to reduce load time for large community files.+- Reduce zoom and overlay rendering work by separating scene rendering from rulers, selection, labels, and input overlays.## 0.11.8 — 2026-04-23diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 0d7be46c2..57e27c661 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -50,6 +50,7 @@ See [`AGENTS.md`](./AGENTS.md) for the full architecture reference, code convent- Use `crypto.getRandomValues()`, never `Math.random()`- Icons via unplugin-icons (`<icon-lucide-*>`)- Use existing deps and Reka UI components before hand-rolling (see AGENTS.md → Code quality)+- Follow the Reka UI-inspired file structure: PascalCase component namespace folders and Vue files, lowercase/kebab non-component domains, and multi-file root components colocated inside their namespace folder## Test IDs (`data-test-id`)diff --git a/bun.lock b/bun.lockindex 130bceda7..24e3f76d3 100644--- a/bun.lock+++ b/bun.lock@@ -24,6 +24,7 @@"@tauri-apps/plugin-opener": "^2","@tauri-apps/plugin-shell": "^2.3.5","@unhead/vue": "^2.1.10",+ "@use-gesture/vanilla": "^10.3.1","@vueuse/core": "^14.2.1","ai": "^6.0.116","canvaskit-wasm": "^0.40.0",@@ -39,6 +40,7 @@"tailwind-merge": "^3.5.0","tailwind-variants": "^3.2.2","tailwindcss": "^4.2.1",+ "tinykeys": "^3.0.0","trystero": "^0.22.0","valibot": "^1.2.0","vue": "^3.5.29",@@ -88,7 +90,7 @@},"packages/cli": {"name": "@open-pencil/cli",- "version": "0.11.6",+ "version": "0.11.8","bin": {"openpencil": "./src/index.ts",},@@ -104,7 +106,7 @@},"packages/core": {"name": "@open-pencil/core",- "version": "0.11.6",+ "version": "0.11.8","dependencies": {"@iconify/utils": "^3.1.0","canvaskit-wasm": "^0.40.0",@@ -139,7 +141,7 @@},"packages/mcp": {"name": "@open-pencil/mcp",- "version": "0.11.6",+ "version": "0.11.8","bin": {"openpencil-mcp": "./dist/index.js",},@@ -158,10 +160,11 @@},"packages/vue": {"name": "@open-pencil/vue",- "version": "0.11.6",+ "version": "0.11.8","dependencies": {"@nanostores/i18n": "^1.2.2","@nanostores/vue": "^1.1.0",+ "@use-gesture/vanilla": "^10.3.1","@vueuse/core": "^14.2.1","nanostores": "^1.2.0",},@@ -1115,6 +1118,10 @@"@unhead/vue": ["@unhead/[email protected]", "", { "dependencies": { "hookable": "^6.0.1", "unhead": "2.1.12" }, "peerDependencies": { "vue": ">=3.5.18" } }, "sha512-zEWqg0nZM8acpuTZE40wkeUl8AhIe0tU0OkilVi1D4fmVjACrwoh5HP6aNqJ8kUnKsoy6D+R3Vi/O+fmdNGO7g=="],+ "@use-gesture/core": ["@use-gesture/[email protected]", "", {}, "sha512-WcINiDt8WjqBdUXye25anHiNxPc0VOrlT8F6LLkU6cycrOGUDyY/yyFmsg3k8i5OLvv25llc0QC45GhR/C8llw=="],++ "@use-gesture/vanilla": ["@use-gesture/[email protected]", "", { "dependencies": { "@use-gesture/core": "10.3.1" } }, "sha512-lT4scGLu59ovA3zmtUonukAGcA0AdOOh+iwNDS05Bsu7Lq9aZToDHhI6D8Q2qvsVraovtsLLYwPrWdG/noMAKw=="],+"@valibot/to-json-schema": ["@valibot/[email protected]", "", { "peerDependencies": { "valibot": "^1.3.0" } }, "sha512-d6rYyK5KVa2XdqamWgZ4/Nr+cXhxjy7lmpe6Iajw15J/jmU+gyxl2IEd1Otg1d7Rl3gOQL5reulnSypzBtYy1A=="],"@vercel/oidc": ["@vercel/[email protected]", "", {}, "sha512-Fw28YZpRnA3cAHHDlkt7xQHiJ0fcL+NRcIqsocZQUSmbzeIKRpwttJjik5ZGanXP+vlA4SbTg+AbA3bP363l+w=="],@@ -2347,6 +2354,8 @@"tinyglobby": ["[email protected]", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.3" } }, "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ=="],+ "tinykeys": ["[email protected]", "", {}, "sha512-nazawuGv5zx6MuDfDY0rmfXjuOGhD5XU2z0GLURQ1nzl0RUe9OuCJq+0u8xxJZINHe+mr7nw8PWYYZ9WhMFujw=="],+"tinypool": ["[email protected]", "", {}, "sha512-Pugqs6M0m7Lv1I7FtxN4aoyToKg1C4tu+/381vH35y8oENM/Ai7f7C4StcoK4/+BSw9ebcS8jRiVrORFKCALLw=="],"to-regex-range": ["[email protected]", "", { "dependencies": { "is-number": "^7.0.0" } }, "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ=="],diff --git a/desktop/src/fig_container.rs b/desktop/src/fig_container.rsnew file mode 100644index 000000000..16e206e8c--- /dev/null+++ b/desktop/src/fig_container.rs@@ -0,0 +1,67 @@+use serde::Deserialize;+use std::io::{Cursor, Write};++#[derive(Deserialize)]+pub struct ImageEntry {+ name: String,+ data: Vec<u8>,+}++#[tauri::command]+pub fn build_fig_file(+ schema_deflated: Vec<u8>,+ kiwi_data: Vec<u8>,+ thumbnail_png: Vec<u8>,+ meta_json: String,+ images: Option<Vec<ImageEntry>>,+ fig_kiwi_version: Option<u32>,+) -> Result<Vec<u8>, String> {+ let mut encoder = zstd::Encoder::new(Vec::new(), 3).map_err(|e| e.to_string())?;+ encoder+ .include_contentsize(true)+ .map_err(|e| e.to_string())?;+ encoder+ .set_pledged_src_size(Some(kiwi_data.len() as u64))+ .map_err(|e| e.to_string())?;+ encoder.write_all(&kiwi_data).map_err(|e| e.to_string())?;+ let zstd_data = encoder.finish().map_err(|e| e.to_string())?;++ let version: u32 = fig_kiwi_version.unwrap_or(101);+ let fig_kiwi_len = 8 + 4 + 4 + schema_deflated.len() + 4 + zstd_data.len();+ let mut fig_kiwi = Vec::with_capacity(fig_kiwi_len);+ fig_kiwi.extend_from_slice(b"fig-kiwi");+ fig_kiwi.extend_from_slice(&version.to_le_bytes());+ fig_kiwi.extend_from_slice(&(schema_deflated.len() as u32).to_le_bytes());+ fig_kiwi.extend_from_slice(&schema_deflated);+ fig_kiwi.extend_from_slice(&(zstd_data.len() as u32).to_le_bytes());+ fig_kiwi.extend_from_slice(&zstd_data);++ let buf = Cursor::new(Vec::new());+ let mut zip = zip::ZipWriter::new(buf);+ let options =+ zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);++ zip.start_file("canvas.fig", options)+ .map_err(|e| e.to_string())?;+ zip.write_all(&fig_kiwi).map_err(|e| e.to_string())?;++ zip.start_file("thumbnail.png", options)+ .map_err(|e| e.to_string())?;+ zip.write_all(&thumbnail_png).map_err(|e| e.to_string())?;++ zip.start_file("meta.json", options)+ .map_err(|e| e.to_string())?;+ zip.write_all(meta_json.as_bytes())+ .map_err(|e| e.to_string())?;++ if let Some(image_entries) = images {+ for entry in image_entries {+ zip.start_file(&entry.name, options)+ .map_err(|e| e.to_string())?;+ zip.write_all(&entry.data).map_err(|e| e.to_string())?;+ }+ }++ let result = zip.finish().map_err(|e| e.to_string())?;+ Ok(result.into_inner())+}diff --git a/desktop/src/fonts.rs b/desktop/src/fonts.rsnew file mode 100644index 000000000..213564026--- /dev/null+++ b/desktop/src/fonts.rs@@ -0,0 +1,127 @@+use font_kit::source::SystemSource;+use serde::Serialize;+use std::sync::OnceLock;++#[derive(Serialize, Clone)]+pub struct FontFamily {+ family: String,+ styles: Vec<String>,+}++static FONT_CACHE: OnceLock<Vec<FontFamily>> = OnceLock::new();++fn enumerate_system_fonts() -> Vec<FontFamily> {+ let source = SystemSource::new();+ let mut families: Vec<FontFamily> = Vec::new();++ if let Ok(family_names) = source.all_families() {+ for name in &family_names {+ if let Ok(handle) = source.select_family_by_name(name) {+ let styles: Vec<String> = handle+ .fonts()+ .iter()+ .filter_map(|f| {+ f.load().ok().map(|font| {+ let props = font.properties();+ let mut style = match props.weight.0 as i32 {+ 0..=150 => "Thin",+ 151..=250 => "ExtraLight",+ 251..=350 => "Light",+ 351..=450 => "Regular",+ 451..=550 => "Medium",+ 551..=650 => "SemiBold",+ 651..=750 => "Bold",+ 751..=850 => "ExtraBold",+ _ => "Black",+ }+ .to_string();+ if props.style == font_kit::properties::Style::Italic {+ style.push_str(" Italic");+ }+ style+ })+ })+ .collect();++ if !styles.is_empty() {+ families.push(FontFamily {+ family: name.clone(),+ styles,+ });+ }+ }+ }+ }++ families.sort_by(|a, b| a.family.cmp(&b.family));+ families+}++#[tauri::command]+pub async fn list_system_fonts() -> Vec<FontFamily> {+ if let Some(cached) = FONT_CACHE.get() {+ return cached.clone();+ }++ let families = tauri::async_runtime::spawn_blocking(enumerate_system_fonts)+ .await+ .unwrap_or_default();+ let _ = FONT_CACHE.set(families.clone());+ families+}++fn load_system_font_blocking(family: String, style: String) -> Result<Vec<u8>, String> {+ let source = SystemSource::new();+ let family_handle = source+ .select_family_by_name(&family)+ .map_err(|e| format!("Font family not found: {e}"))?;++ let is_italic = style.contains("Italic");+ let weight_str = style.replace(" Italic", "");+ let weight = match weight_str.as_str() {+ "Thin" => font_kit::properties::Weight::THIN,+ "ExtraLight" => font_kit::properties::Weight::EXTRA_LIGHT,+ "Light" => font_kit::properties::Weight::LIGHT,+ "Regular" | "" => font_kit::properties::Weight::NORMAL,+ "Medium" => font_kit::properties::Weight::MEDIUM,+ "SemiBold" => font_kit::properties::Weight::SEMIBOLD,+ "Bold" => font_kit::properties::Weight::BOLD,+ "ExtraBold" => font_kit::properties::Weight::EXTRA_BOLD,+ "Black" => font_kit::properties::Weight::BLACK,+ _ => font_kit::properties::Weight::NORMAL,+ };+ let style_prop = if is_italic {+ font_kit::properties::Style::Italic+ } else {+ font_kit::properties::Style::Normal+ };++ for handle in family_handle.fonts() {+ if let Ok(font) = handle.load() {+ let props = font.properties();+ let w_diff = (props.weight.0 - weight.0).abs();+ if w_diff < 50.0 && props.style == style_prop {+ if let Some(data) = font.copy_font_data() {+ return Ok((*data).clone());+ }+ }+ }+ }++ if let Some(handle) = family_handle.fonts().first() {+ if let Ok(font) = handle.load() {+ if let Some(data) = font.copy_font_data() {+ return Ok((*data).clone());+ }+ }+ }++ Err(format!("Could not load font {family} {style}"))+}++#[tauri::command]+pub async fn load_system_font(family: String, style: String) -> Result<Vec<u8>, String> {+ tauri::async_runtime::spawn_blocking(move || load_system_font_blocking(family, style))+ .await+ .map_err(|e| format!("Font load task failed: {e}"))?+}diff --git a/desktop/src/lib.rs b/desktop/src/lib.rsindex a95d64c00..6e953e882 100644--- a/desktop/src/lib.rs+++ b/desktop/src/lib.rs@@ -1,218 +1,14 @@-use tauri::{- menu::{MenuBuilder, MenuItemBuilder, PredefinedMenuItem, SubmenuBuilder},- Emitter, Manager,-};--use font_kit::source::SystemSource;-use serde::Serialize;-use std::sync::OnceLock;--#[derive(Serialize, Clone)]-struct FontFamily {- family: String,- styles: Vec<String>,-}--static FONT_CACHE: OnceLock<Vec<FontFamily>> = OnceLock::new();--fn enumerate_system_fonts() -> Vec<FontFamily> {- let source = SystemSource::new();- let mut families: Vec<FontFamily> = Vec::new();-- if let Ok(family_names) = source.all_families() {- for name in &family_names {- if let Ok(handle) = source.select_family_by_name(name) {- let styles: Vec<String> = handle- .fonts()- .iter()- .filter_map(|f| {- f.load().ok().map(|font| {- let props = font.properties();- let mut style = match props.weight.0 as i32 {- 0..=150 => "Thin",- 151..=250 => "ExtraLight",- 251..=350 => "Light",- 351..=450 => "Regular",- 451..=550 => "Medium",- 551..=650 => "SemiBold",- 651..=750 => "Bold",- 751..=850 => "ExtraBold",- _ => "Black",- }- .to_string();- if props.style == font_kit::properties::Style::Italic {- style.push_str(" Italic");- }- style- })- })- .collect();-- if !styles.is_empty() {- families.push(FontFamily {- family: name.clone(),- styles,- });- }- }- }- }-- families.sort_by(|a, b| a.family.cmp(&b.family));- families-}--#[tauri::command]-async fn list_system_fonts() -> Vec<FontFamily> {- if let Some(cached) = FONT_CACHE.get() {- return cached.clone();- }-- let families = tauri::async_runtime::spawn_blocking(enumerate_system_fonts)- .await- .unwrap_or_default();- let _ = FONT_CACHE.set(families.clone());- families-}--fn load_system_font_blocking(family: String, style: String) -> Result<Vec<u8>, String> {- let source = SystemSource::new();- let family_handle = source- .select_family_by_name(&family)- .map_err(|e| format!("Font family not found: {e}"))?;-- let is_italic = style.contains("Italic");- let weight_str = style.replace(" Italic", "");- let weight = match weight_str.as_str() {- "Thin" => font_kit::properties::Weight::THIN,- "ExtraLight" => font_kit::properties::Weight::EXTRA_LIGHT,- "Light" => font_kit::properties::Weight::LIGHT,- "Regular" | "" => font_kit::properties::Weight::NORMAL,- "Medium" => font_kit::properties::Weight::MEDIUM,- "SemiBold" => font_kit::properties::Weight::SEMIBOLD,- "Bold" => font_kit::properties::Weight::BOLD,- "ExtraBold" => font_kit::properties::Weight::EXTRA_BOLD,- "Black" => font_kit::properties::Weight::BLACK,- _ => font_kit::properties::Weight::NORMAL,- };- let style_prop = if is_italic {- font_kit::properties::Style::Italic- } else {- font_kit::properties::Style::Normal- };-- for handle in family_handle.fonts() {- if let Ok(font) = handle.load() {- let props = font.properties();- let w_diff = (props.weight.0 - weight.0).abs();- if w_diff < 50.0 && props.style == style_prop {- if let Some(data) = font.copy_font_data() {- return Ok((*data).clone());- }- }- }- }-- // Fallback: return first font in family- if let Some(handle) = family_handle.fonts().first() {- if let Ok(font) = handle.load() {- if let Some(data) = font.copy_font_data() {- return Ok((*data).clone());- }- }- }-- Err(format!("Could not load font {family} {style}"))-}--#[tauri::command]-async fn load_system_font(family: String, style: String) -> Result<Vec<u8>, String> {- tauri::async_runtime::spawn_blocking(move || load_system_font_blocking(family, style))- .await- .map_err(|e| format!("Font load task failed: {e}"))?-}--#[derive(serde::Deserialize)]-struct ImageEntry {- name: String,- data: Vec<u8>,-}--#[tauri::command]-fn build_fig_file(- schema_deflated: Vec<u8>,- kiwi_data: Vec<u8>,- thumbnail_png: Vec<u8>,- meta_json: String,- images: Option<Vec<ImageEntry>>,- fig_kiwi_version: Option<u32>,-) -> Result<Vec<u8>, String> {- use std::io::{Cursor, Write};-- // Zstd-compress kiwi data with content size in frame header- let mut encoder = zstd::Encoder::new(Vec::new(), 3).map_err(|e| e.to_string())?;- encoder- .include_contentsize(true)- .map_err(|e| e.to_string())?;- encoder- .set_pledged_src_size(Some(kiwi_data.len() as u64))- .map_err(|e| e.to_string())?;- encoder.write_all(&kiwi_data).map_err(|e| e.to_string())?;- let zstd_data = encoder.finish().map_err(|e| e.to_string())?;-- // Build fig-kiwi container- let version: u32 = fig_kiwi_version.unwrap_or(101);- let fig_kiwi_len = 8 + 4 + 4 + schema_deflated.len() + 4 + zstd_data.len();- let mut fig_kiwi = Vec::with_capacity(fig_kiwi_len);- fig_kiwi.extend_from_slice(b"fig-kiwi");- fig_kiwi.extend_from_slice(&version.to_le_bytes());- fig_kiwi.extend_from_slice(&(schema_deflated.len() as u32).to_le_bytes());- fig_kiwi.extend_from_slice(&schema_deflated);- fig_kiwi.extend_from_slice(&(zstd_data.len() as u32).to_le_bytes());- fig_kiwi.extend_from_slice(&zstd_data);-- // Deflate-compress the schema for verification it's already deflated- // (schema_deflated is already deflated, we just pass it through)-- // Build ZIP with canvas.fig + thumbnail.png + meta.json (all STORED)- let buf = Cursor::new(Vec::new());- let mut zip = zip::ZipWriter::new(buf);- let options =- zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);-- zip.start_file("canvas.fig", options)- .map_err(|e| e.to_string())?;- zip.write_all(&fig_kiwi).map_err(|e| e.to_string())?;-- zip.start_file("thumbnail.png", options)- .map_err(|e| e.to_string())?;- zip.write_all(&thumbnail_png).map_err(|e| e.to_string())?;-- zip.start_file("meta.json", options)- .map_err(|e| e.to_string())?;- zip.write_all(meta_json.as_bytes())- .map_err(|e| e.to_string())?;-- if let Some(image_entries) = images {- for entry in image_entries {- zip.start_file(&entry.name, options)- .map_err(|e| e.to_string())?;- zip.write_all(&entry.data)- .map_err(|e| e.to_string())?;- }- }-- let result = zip.finish().map_err(|e| e.to_string())?;- Ok(result.into_inner())-}--fn show_main_window<R: tauri::Runtime>(app: &tauri::AppHandle<R>) {- if let Some(window) = app.get_webview_window("main") {- let _ = window.unminimize();- let _ = window.show();- let _ = window.set_focus();- }-}+mod fig_container;+mod fonts;+mod menu;+mod menu_events;+mod window;++use fig_container::build_fig_file;+use fonts::{list_system_fonts, load_system_font};+use menu::install_app_menu;+use menu_events::handle_menu_event;+use window::show_main_window;#[cfg_attr(mobile, tauri::mobile_entry_point)]pub fn run() {@@ -228,263 +24,9 @@ pub fn run() {.plugin(tauri_plugin_fs::init()).plugin(tauri_plugin_shell::init()).on_menu_event(|app, event| {- #[cfg(debug_assertions)]- if event.id().0.as_str() == "dev-tools" {- if let Some(window) = app.get_webview_window("main") {- if window.is_devtools_open() {- window.close_devtools();- } else {- window.open_devtools();- }- }- return;- }- let _ = app.emit("menu-event", event.id().0.as_str());- })- .setup(|app| {- #[cfg(target_os = "macos")]- let app_menu = SubmenuBuilder::new(app, "OpenPencil")- .item(&PredefinedMenuItem::about(- app,- Some("About OpenPencil"),- None,- )?)- .separator()- .item(&PredefinedMenuItem::services(app, None)?)- .separator()- .item(&PredefinedMenuItem::hide(app, None)?)- .item(&PredefinedMenuItem::hide_others(app, None)?)- .item(&PredefinedMenuItem::show_all(app, None)?)- .separator()- .item(&PredefinedMenuItem::quit(app, None)?)- .build()?;-- #[allow(unused_mut)]- let mut file_menu_builder = SubmenuBuilder::new(app, "File")- .item(- &MenuItemBuilder::new("New")- .id("new")- .accelerator("CmdOrCtrl+N")- .build(app)?,- )- .item(- &MenuItemBuilder::new("Open…")- .id("open")- .accelerator("CmdOrCtrl+O")- .build(app)?,- )- .separator()- .item(- &MenuItemBuilder::new("Save")- .id("save")- .accelerator("CmdOrCtrl+S")- .build(app)?,- )- .item(- &MenuItemBuilder::new("Save As…")- .id("save-as")- .accelerator("CmdOrCtrl+Shift+S")- .build(app)?,- )- .separator()- .item(- &MenuItemBuilder::new("Export…")- .id("export")- .accelerator("CmdOrCtrl+Shift+E")- .build(app)?,- )- .separator()- .item(- &MenuItemBuilder::new("Close Tab")- .id("close")- .accelerator("CmdOrCtrl+W")- .build(app)?,- );- #[cfg(not(target_os = "macos"))]- {- file_menu_builder = file_menu_builder- .separator()- .item(&PredefinedMenuItem::quit(app, None)?);- }- let file_menu = file_menu_builder.build()?;-- let edit_menu = SubmenuBuilder::new(app, "Edit")- .item(&PredefinedMenuItem::undo(app, None)?)- .item(&PredefinedMenuItem::redo(app, None)?)- .separator()- .item(&PredefinedMenuItem::cut(app, None)?)- .item(&PredefinedMenuItem::copy(app, None)?)- .item(&PredefinedMenuItem::paste(app, None)?)- .item(- &MenuItemBuilder::new("Paste in Place")- .id("paste-in-place")- .accelerator("CmdOrCtrl+Shift+V")- .build(app)?,- )- .item(&PredefinedMenuItem::select_all(app, None)?)- .separator()- .item(- &MenuItemBuilder::new("Duplicate")- .id("duplicate")- .accelerator("CmdOrCtrl+D")- .build(app)?,- )- .item(- &MenuItemBuilder::new("Delete")- .id("delete")- .accelerator("Backspace")- .build(app)?,- )- .build()?;-- let view_menu = SubmenuBuilder::new(app, "View")- .item(- &MenuItemBuilder::new("Zoom In")- .id("zoom-in")- .accelerator("CmdOrCtrl+=")- .build(app)?,- )- .item(- &MenuItemBuilder::new("Zoom Out")- .id("zoom-out")- .accelerator("CmdOrCtrl+-")- .build(app)?,- )- .item(- &MenuItemBuilder::new("Zoom to Fit")- .id("zoom-fit")- .accelerator("CmdOrCtrl+1")- .build(app)?,- )- .item(- &MenuItemBuilder::new("Zoom to 100%")- .id("zoom-100")- .accelerator("CmdOrCtrl+0")- .build(app)?,- )- .separator()- .item(- &MenuItemBuilder::new("Toggle Rulers")- .id("toggle-rulers")- .accelerator("Shift+R")- .build(app)?,- )- .item(- &MenuItemBuilder::new("Toggle Grid")- .id("toggle-grid")- .accelerator("CmdOrCtrl+'")- .build(app)?,- )- .separator()- .item(- &MenuItemBuilder::new("Toggle UI")- .id("toggle-ui")- .accelerator("CmdOrCtrl+\\")- .build(app)?,- )- .item(&PredefinedMenuItem::fullscreen(app, None)?)- .separator()- .item(- &MenuItemBuilder::new("Developer Tools")- .id("dev-tools")- .accelerator("CmdOrCtrl+Alt+I")- .build(app)?,- )- .build()?;-- let object_menu = SubmenuBuilder::new(app, "Object")- .item(- &MenuItemBuilder::new("Group Selection")- .id("group")- .accelerator("CmdOrCtrl+G")- .build(app)?,- )- .item(- &MenuItemBuilder::new("Ungroup Selection")- .id("ungroup")- .accelerator("CmdOrCtrl+Shift+G")- .build(app)?,- )- .item(- &MenuItemBuilder::new("Frame Selection")- .id("frame-selection")- .accelerator("CmdOrCtrl+Alt+G")- .build(app)?,- )- .separator()- .item(- &MenuItemBuilder::new("Bring to Front")- .id("bring-front")- .accelerator("CmdOrCtrl+]")- .build(app)?,- )- .item(- &MenuItemBuilder::new("Send to Back")- .id("send-back")- .accelerator("CmdOrCtrl+[")- .build(app)?,- )- .separator()- .item(- &MenuItemBuilder::new("Flip Horizontal")- .id("flip-h")- .accelerator("Shift+H")- .build(app)?,- )- .item(- &MenuItemBuilder::new("Flip Vertical")- .id("flip-v")- .accelerator("Shift+V")- .build(app)?,- )- .build()?;-- let window_menu = SubmenuBuilder::new(app, "Window")- .item(&PredefinedMenuItem::minimize(app, None)?)- .item(&PredefinedMenuItem::maximize(app, None)?)- .separator()- .item(&PredefinedMenuItem::close_window(app, None)?)- .build()?;-- #[allow(unused_mut)]- let mut help_menu_builder = SubmenuBuilder::new(app, "Help").item(- &MenuItemBuilder::new("Keyboard Shortcuts")- .id("shortcuts")- .accelerator("CmdOrCtrl+/")- .build(app)?,- );- #[cfg(not(target_os = "macos"))]- {- help_menu_builder = help_menu_builder- .separator()- .item(&PredefinedMenuItem::about(- app,- Some("About OpenPencil"),- None,- )?);- }- let help_menu = help_menu_builder.build()?;-- let mut builder = MenuBuilder::new(app);- #[cfg(target_os = "macos")]- {- builder = builder.item(&app_menu);- }- let menu = builder- .items(&[- &file_menu,- &edit_menu,- &view_menu,- &object_menu,- &window_menu,- &help_menu,- ])- .build()?;-- app.set_menu(menu)?;-- Ok(())+ handle_menu_event(app, event.id().0.as_str());})+ .setup(|app| Ok(install_app_menu(app)?)).build(tauri::generate_context!()).expect("error while building tauri application").run(|app, event| {diff --git a/desktop/src/menu.rs b/desktop/src/menu.rsnew file mode 100644index 000000000..1242ee91d--- /dev/null+++ b/desktop/src/menu.rs@@ -0,0 +1,245 @@+use tauri::menu::{MenuBuilder, MenuItemBuilder, PredefinedMenuItem, SubmenuBuilder};++pub fn install_app_menu<R: tauri::Runtime>(app: &mut tauri::App<R>) -> tauri::Result<()> {+ #[cfg(target_os = "macos")]+ let app_menu = SubmenuBuilder::new(app, "OpenPencil")+ .item(&PredefinedMenuItem::about(+ app,+ Some("About OpenPencil"),+ None,+ )?)+ .separator()+ .item(&PredefinedMenuItem::services(app, None)?)+ .separator()+ .item(&PredefinedMenuItem::hide(app, None)?)+ .item(&PredefinedMenuItem::hide_others(app, None)?)+ .item(&PredefinedMenuItem::show_all(app, None)?)+ .separator()+ .item(&PredefinedMenuItem::quit(app, None)?)+ .build()?;++ #[allow(unused_mut)]+ let mut file_menu_builder = SubmenuBuilder::new(app, "File")+ .item(+ &MenuItemBuilder::new("New")+ .id("new")+ .accelerator("CmdOrCtrl+N")+ .build(app)?,+ )+ .item(+ &MenuItemBuilder::new("Open…")+ .id("open")+ .accelerator("CmdOrCtrl+O")+ .build(app)?,+ )+ .separator()+ .item(+ &MenuItemBuilder::new("Save")+ .id("save")+ .accelerator("CmdOrCtrl+S")+ .build(app)?,+ )+ .item(+ &MenuItemBuilder::new("Save As…")+ .id("save-as")+ .accelerator("CmdOrCtrl+Shift+S")+ .build(app)?,+ )+ .separator()+ .item(+ &MenuItemBuilder::new("Export…")+ .id("export")+ .accelerator("CmdOrCtrl+Shift+E")+ .build(app)?,+ )+ .separator()+ .item(+ &MenuItemBuilder::new("Close Tab")+ .id("close")+ .accelerator("CmdOrCtrl+W")+ .build(app)?,+ );+ #[cfg(not(target_os = "macos"))]+ {+ file_menu_builder = file_menu_builder+ .separator()+ .item(&PredefinedMenuItem::quit(app, None)?);+ }+ let file_menu = file_menu_builder.build()?;++ let edit_menu = SubmenuBuilder::new(app, "Edit")+ .item(&PredefinedMenuItem::undo(app, None)?)+ .item(&PredefinedMenuItem::redo(app, None)?)+ .separator()+ .item(&PredefinedMenuItem::cut(app, None)?)+ .item(&PredefinedMenuItem::copy(app, None)?)+ .item(&PredefinedMenuItem::paste(app, None)?)+ .item(+ &MenuItemBuilder::new("Paste in Place")+ .id("paste-in-place")+ .accelerator("CmdOrCtrl+Shift+V")+ .build(app)?,+ )+ .item(&PredefinedMenuItem::select_all(app, None)?)+ .separator()+ .item(+ &MenuItemBuilder::new("Duplicate")+ .id("duplicate")+ .accelerator("CmdOrCtrl+D")+ .build(app)?,+ )+ .item(+ &MenuItemBuilder::new("Delete")+ .id("delete")+ .accelerator("Backspace")+ .build(app)?,+ )+ .build()?;++ let view_menu = SubmenuBuilder::new(app, "View")+ .item(+ &MenuItemBuilder::new("Zoom In")+ .id("zoom-in")+ .accelerator("CmdOrCtrl+=")+ .build(app)?,+ )+ .item(+ &MenuItemBuilder::new("Zoom Out")+ .id("zoom-out")+ .accelerator("CmdOrCtrl+-")+ .build(app)?,+ )+ .item(+ &MenuItemBuilder::new("Zoom to Fit")+ .id("zoom-fit")+ .accelerator("CmdOrCtrl+1")+ .build(app)?,+ )+ .item(+ &MenuItemBuilder::new("Zoom to 100%")+ .id("zoom-100")+ .accelerator("CmdOrCtrl+0")+ .build(app)?,+ )+ .separator()+ .item(+ &MenuItemBuilder::new("Toggle Rulers")+ .id("toggle-rulers")+ .accelerator("Shift+R")+ .build(app)?,+ )+ .item(+ &MenuItemBuilder::new("Toggle Grid")+ .id("toggle-grid")+ .accelerator("CmdOrCtrl+'")+ .build(app)?,+ )+ .separator()+ .item(+ &MenuItemBuilder::new("Toggle UI")+ .id("toggle-ui")+ .accelerator("CmdOrCtrl+\\")+ .build(app)?,+ )+ .item(&PredefinedMenuItem::fullscreen(app, None)?)+ .separator()+ .item(+ &MenuItemBuilder::new("Developer Tools")+ .id("dev-tools")+ .accelerator("CmdOrCtrl+Alt+I")+ .build(app)?,+ )+ .build()?;++ let object_menu = SubmenuBuilder::new(app, "Object")+ .item(+ &MenuItemBuilder::new("Group Selection")+ .id("group")+ .accelerator("CmdOrCtrl+G")+ .build(app)?,+ )+ .item(+ &MenuItemBuilder::new("Ungroup Selection")+ .id("ungroup")+ .accelerator("CmdOrCtrl+Shift+G")+ .build(app)?,+ )+ .item(+ &MenuItemBuilder::new("Frame Selection")+ .id("frame-selection")+ .accelerator("CmdOrCtrl+Alt+G")+ .build(app)?,+ )+ .separator()+ .item(+ &MenuItemBuilder::new("Bring to Front")+ .id("bring-front")+ .accelerator("CmdOrCtrl+]")+ .build(app)?,+ )+ .item(+ &MenuItemBuilder::new("Send to Back")+ .id("send-back")+ .accelerator("CmdOrCtrl+[")+ .build(app)?,+ )+ .separator()+ .item(+ &MenuItemBuilder::new("Flip Horizontal")+ .id("flip-h")+ .accelerator("Shift+H")+ .build(app)?,+ )+ .item(+ &MenuItemBuilder::new("Flip Vertical")+ .id("flip-v")+ .accelerator("Shift+V")+ .build(app)?,+ )+ .build()?;++ let window_menu = SubmenuBuilder::new(app, "Window")+ .item(&PredefinedMenuItem::minimize(app, None)?)+ .item(&PredefinedMenuItem::maximize(app, None)?)+ .separator()+ .item(&PredefinedMenuItem::close_window(app, None)?)+ .build()?;++ #[allow(unused_mut)]+ let mut help_menu_builder = SubmenuBuilder::new(app, "Help").item(+ &MenuItemBuilder::new("Keyboard Shortcuts")+ .id("shortcuts")+ .accelerator("CmdOrCtrl+/")+ .build(app)?,+ );+ #[cfg(not(target_os = "macos"))]+ {+ help_menu_builder = help_menu_builder+ .separator()+ .item(&PredefinedMenuItem::about(+ app,+ Some("About OpenPencil"),+ None,+ )?);+ }+ let help_menu = help_menu_builder.build()?;++ let mut builder = MenuBuilder::new(app);+ #[cfg(target_os = "macos")]+ {+ builder = builder.item(&app_menu);+ }+ let menu = builder+ .items(&[+ &file_menu,+ &edit_menu,+ &view_menu,+ &object_menu,+ &window_menu,+ &help_menu,+ ])+ .build()?;++ app.set_menu(menu)?;+ Ok(())+}diff --git a/desktop/src/menu_events.rs b/desktop/src/menu_events.rsnew file mode 100644index 000000000..a85d3e3f4--- /dev/null+++ b/desktop/src/menu_events.rs@@ -0,0 +1,16 @@+use tauri::{Emitter, Manager};++pub fn handle_menu_event<R: tauri::Runtime>(app: &tauri::AppHandle<R>, event_id: &str) {+ #[cfg(debug_assertions)]+ if event_id == "dev-tools" {+ if let Some(window) = app.get_webview_window("main") {+ if window.is_devtools_open() {+ window.close_devtools();+ } else {+ window.open_devtools();+ }+ }+ return;+ }+ let _ = app.emit("menu-event", event_id);+}diff --git a/desktop/src/window.rs b/desktop/src/window.rsnew file mode 100644index 000000000..d20cad5be--- /dev/null+++ b/desktop/src/window.rs@@ -0,0 +1,9 @@+use tauri::Manager;++pub fn show_main_window<R: tauri::Runtime>(app: &tauri::AppHandle<R>) {+ if let Some(window) = app.get_webview_window("main") {+ let _ = window.unminimize();+ let _ = window.show();+ let _ = window.set_focus();+ }+}diff --git a/docs/eval-command.md b/docs/eval-command.mdindex 9f7c45018..c1ebc4f66 100644--- a/docs/eval-command.md+++ b/docs/eval-command.md@@ -61,8 +61,8 @@ bun open-pencil eval design.fig --code '...' -o modified.fig| Class | Location | Role ||-------|----------|------|-| `FigmaAPI` | `packages/core/src/figma-api.ts` | Proxy object implementing `figma.*` methods against `SceneGraph` |-| `FigmaNode` | `packages/core/src/figma-api.ts` | Proxy wrapping `SceneNode` with Figma-style property access (`.fills`, `.resize()`, `.appendChild()`, etc.) |+| `FigmaAPI` | `packages/core/src/figma-api/` | Proxy object implementing `figma.*` methods against `SceneGraph` |+| `FigmaNode` | `packages/core/src/figma-api/` | Proxy wrapping `SceneNode` with Figma-style property access (`.fills`, `.resize()`, `.appendChild()`, etc.) || `eval` command | `packages/cli/src/commands/eval.ts` | CLI command that loads doc, creates API, executes code |### Why in `@open-pencil/core`?@@ -330,16 +330,10 @@ Options:## Shared with AI Tools-The `FigmaAPI` class is the **same API surface** that AI tools use. Currently `src/ai/tools.ts` calls `store.createShape()`, `store.updateNodeWithUndo()`, etc. — these should be refactored to go through `FigmaAPI`:+The `FigmaAPI` class is the **same API surface** that AI tools use. App AI tools are wired from `src/app/ai/tools/index.ts` through the shared core tool definitions, so CLI scripts, MCP calls, and chat tool calls execute the same scene-graph operations:```ts-// Before (current AI tools)-execute: async ({ type, x, y, width, height }) => {- const id = store.createShape(type, x, y, width, height)- return { id }-}--// After (using FigmaAPI)+// Tool implementation using FigmaAPIexecute: async ({ type, x, y, width, height }) => {const frame = figma.createFrame()frame.resize(width, height)@@ -355,13 +349,14 @@ This ensures CLI scripts and AI tools behave identically.```packages/core/src/- figma-api.ts # FigmaAPI class + FigmaNode proxy (Phase 1–4)- figma-api.test.ts # Unit tests against headless SceneGraph+ figma-api/ # FigmaAPI class + FigmaNode proxy+ tools/ # Shared ToolDef operations used by AI, MCP, and eval helperspackages/cli/src/commands/eval.ts # CLI command-packages/cli/src/commands/eval.test.ts # Integration tests+src/app/ai/tools/+ index.ts # App chat wiring for shared core tool definitions```## Test Plan@@ -398,7 +393,7 @@ packages/cli/src/commands/eval.test.ts # Integration tests3. **CLI `eval` command** — argument parsing, code wrapping, output formatting4. **Unit tests** — all 12 test groups above5. **CLI integration tests** — all 7 test groups above-6. **Wire to AI tools** — refactor `src/ai/tools.ts` to use `FigmaAPI` where possible+6. **Wire to AI tools** — expose shared core tool definitions through `src/app/ai/tools/index.ts`7. **Phase 2** — components & instances8. **Phase 3** — variables9. **Phase 4** — styles, boolean ops, JSX rendererdiff --git a/lint/plugin.js b/lint/plugin.jsindex 639ea583b..181e7f6b4 100644--- a/lint/plugin.js+++ b/lint/plugin.js@@ -1,16 +1,30 @@+import { existsSync } from 'node:fs'++function normalizedFilename(context) {+ return (context.filename ?? context.getFilename?.() ?? '').replace(/\\/g, '/')+}++function importSource(node) {+ return typeof node.source?.value === 'string' ? node.source.value : null+}++function isUnknownTypeAnnotation(typeAnnotation) {+ return typeAnnotation?.type === 'TSUnknownKeyword'+}+const noInlineNamedTypes = {meta: {docs: {- description: 'Disallow inline type literals that duplicate a named type',+ description: 'Disallow inline type literals that duplicate a named type'},schema: [{type: 'object',additionalProperties: {- type: 'string',- },- },- ],+ type: 'string'+ }+ }+ ]},create(context) {const typesOption = context.options[0]@@ -24,7 +38,7 @@ const noInlineNamedTypes = {return {TSTypeLiteral(node) {const props = node.members?.filter(- (m) => m.type === 'TSPropertySignature' && m.key?.type === 'Identifier',+ (m) => m.type === 'TSPropertySignature' && m.key?.type === 'Identifier')if (!props || props.length < 2) return@@ -37,9 +51,15 @@ const noInlineNamedTypes = {let typeName = 'unknown'if (typeNode) {switch (typeNode.type) {- case 'TSNumberKeyword': typeName = 'number'; break- case 'TSStringKeyword': typeName = 'string'; break- case 'TSBooleanKeyword': typeName = 'boolean'; break+ case 'TSNumberKeyword':+ typeName = 'number'+ break+ case 'TSStringKeyword':+ typeName = 'string'+ break+ case 'TSBooleanKeyword':+ typeName = 'boolean'+ break}}return `${m.key.name}:${typeName}`@@ -51,32 +71,39 @@ const noInlineNamedTypes = {if (namedType) {context.report({node,- message: `Use '${namedType}' instead of inline type literal. Import from '@open-pencil/core'.`,+ message: `Use '${namedType}' instead of inline type literal. Import from '@open-pencil/core'.`})}- },+ }}- },+ }}const noStructuredCloneSceneArrays = {meta: {docs: {description:- 'Disallow structuredClone on fills/strokes/effects — use typed copy helpers from copy.ts',+ 'Disallow structuredClone on fills/strokes/effects — use typed copy helpers from copy.ts'},schema: [{type: 'array',items: { type: 'string' },- description: 'Property names that should use typed copy helpers',- },- ],+ description: 'Property names that should use typed copy helpers'+ }+ ]},create(context) {- const props = new Set(context.options[0] ?? [- 'fills', 'strokes', 'effects', 'styleRuns', 'fillGeometry', 'strokeGeometry',- ])+ const props = new Set(+ context.options[0] ?? [+ 'fills',+ 'strokes',+ 'effects',+ 'styleRuns',+ 'fillGeometry',+ 'strokeGeometry'+ ]+ )return {CallExpression(node) {if (node.callee?.type !== 'Identifier' || node.callee.name !== 'structuredClone') return@@ -86,20 +113,20 @@ const noStructuredCloneSceneArrays = {if (props.has(arg.property.name)) {context.report({node,- message: `Use the typed copy helper instead of structuredClone for '${arg.property.name}'. Import from '@open-pencil/core'.`,+ message: `Use the typed copy helper instead of structuredClone for '${arg.property.name}'. Import from '@open-pencil/core'.`})}}- },+ }}- },+ }}const noMathRandom = {meta: {docs: {- description: 'Disallow Math.random() — use crypto.getRandomValues() instead',- },+ description: 'Disallow Math.random() — use crypto.getRandomValues() instead'+ }},create(context) {return {@@ -113,24 +140,24 @@ const noMathRandom = {) {context.report({node,- message: 'Use crypto.getRandomValues() instead of Math.random().',+ message: 'Use crypto.getRandomValues() instead of Math.random().'})}- },+ }}- },+ }}const noHandRolledColor = {meta: {docs: {description:- 'Disallow hand-rolled color conversions — use helpers from color.ts (colorToCSS, colorToHex, parseColor, etc.)',- },+ 'Disallow hand-rolled color conversions — use helpers from color.ts (colorToCSS, colorToHex, parseColor, etc.)'+ }},create(context) {- const file = (context.filename ?? context.getFilename?.())?.replace(/\\/g, '/')- if (file?.includes('/color') && /(?:color\.ts|color\/index\.ts)$/.test(file)) return {}+ const file = normalizedFilename(context)+ if (file.includes('/color') && /(?:color\.ts|color\/index\.ts)$/.test(file)) return {}return {TemplateLiteral(node) {@@ -138,21 +165,21 @@ const noHandRolledColor = {if (/rgba?\s*\(/.test(raw)) {context.report({node,- message: "Use colorToCSS() or colorToHex() from color.ts instead of hand-rolled rgba()/rgb() strings.",+ message:+ 'Use colorToCSS() or colorToHex() from color.ts instead of hand-rolled rgba()/rgb() strings.'})}- },-+ }}- },+ }}const noRawConsoleFormat = {meta: {docs: {description:- 'Disallow hand-rolled formatting in console.log — use agentfmt helpers (bold, dim, kv, entity, fmtTree, fmtList, etc.)',- },+ 'Disallow hand-rolled formatting in console.log — use agentfmt helpers (bold, dim, kv, entity, fmtTree, fmtList, etc.)'+ }},create(context) {return {@@ -163,67 +190,67 @@ const noRawConsoleFormat = {node.callee.object.name !== 'console' ||node.callee.property?.type !== 'Identifier' ||node.callee.property.name !== 'log'- ) return+ )+ returnif (!node.arguments?.length) returnfor (const arg of node.arguments) {if (arg.type === 'TemplateLiteral' && arg.expressions?.length > 0) {context.report({node,- message: 'Use agentfmt helpers (bold, dim, kv, entity, etc.) instead of template literals in console.log.',+ message:+ 'Use agentfmt helpers (bold, dim, kv, entity, etc.) instead of template literals in console.log.'})return}if (arg.type === 'BinaryExpression' && arg.operator === '+') {context.report({node,- message: 'Use agentfmt helpers (bold, dim, kv, entity, etc.) instead of string concatenation in console.log.',+ message:+ 'Use agentfmt helpers (bold, dim, kv, entity, etc.) instead of string concatenation in console.log.'})return}}- },+ }}- },+ }}const noSilentCatch = {meta: {docs: {description:- 'Disallow empty catch blocks — log a warning or re-throw instead of silently swallowing errors',- },+ 'Disallow empty catch blocks — log a warning or re-throw instead of silently swallowing errors'+ }},create(context) {return {CatchClause(node) {const body = node.bodyif (!body || !body.body) return- const stmts = body.body.filter(- (s) => s.type !== 'EmptyStatement',- )+ const stmts = body.body.filter((s) => s.type !== 'EmptyStatement')if (stmts.length === 0) {context.report({node,message:- 'Empty catch block silently swallows errors. Add console.warn(), re-throw, or an explicit // oxlint-ignore-next-line comment.',+ 'Empty catch block silently swallows errors. Add console.warn(), re-throw, or an explicit // oxlint-ignore-next-line comment.'})}- },+ }}- },+ }}const noTypeofWindowCheck = {meta: {docs: {- description:- 'Disallow raw typeof window checks — use IS_BROWSER or IS_TAURI from constants',- },+ description: 'Disallow raw typeof window checks — use IS_BROWSER or IS_TAURI from constants'+ }},create(context) {- const file = (context.filename ?? context.getFilename?.())?.replace(/\\/g, '/')- if (file?.endsWith('constants.ts')) return {}+ const file = normalizedFilename(context)+ if (file.endsWith('constants.ts')) return {}return {BinaryExpression(node) {@@ -237,12 +264,925 @@ const noTypeofWindowCheck = {context.report({node,message:- "Use IS_BROWSER or IS_TAURI from constants instead of raw 'typeof window' checks.",+ "Use IS_BROWSER or IS_TAURI from constants instead of raw 'typeof window' checks."+ })+ }+ }+ }+ }+}++const noLegacyAppImports = {+ meta: {+ docs: {+ description:+ 'Disallow imports from removed app/store compatibility shims — import canonical src/app modules instead'+ }+ },+ create(context) {+ return {+ ImportDeclaration(node) {+ const source = importSource(node)+ if (!source) return+ const legacyPrefixes = [+ '@/ai/',+ '@/automation/',+ '@/stores/',+ '@/composables/use-canvas',+ '@/composables/use-canvas-input',+ '@/composables/use-collab',+ '@/composables/use-keyboard'+ ]+ if (legacyPrefixes.some((prefix) => source === prefix || source.startsWith(prefix))) {+ context.report({+ node,+ message: `Import from the canonical src/app module instead of legacy shim '${source}'.`})}+ }+ }+ }+}++const noVueSelfPackageImports = {+ meta: {+ docs: {+ description: 'Disallow @open-pencil/vue self-imports inside the Vue SDK — use #vue/* aliases'+ }+ },+ create(context) {+ const file = normalizedFilename(context)+ if (!file.includes('/packages/vue/src/')) return {}++ return {+ ImportDeclaration(node) {+ const source = importSource(node)+ if (!source?.startsWith('@open-pencil/vue')) return+ context.report({+ node,+ message: `Use #vue/* for internal Vue SDK imports instead of self-package import '${source}'.`+ })+ }+ }+ }+}++const noCrossPackageSourceImports = {+ meta: {+ docs: {+ description:+ 'Disallow imports that reach into another workspace package source tree — use package exports or package-local aliases'+ }+ },+ create(context) {+ return {+ ImportDeclaration(node) {+ const source = importSource(node)+ if (!source) return+ if (+ source.includes('/packages/') ||+ /^(?:\.\.\/){2,}packages\//.test(source) ||+ /^(?:\.\.\/)+(?:core|vue|cli|mcp)\/src\//.test(source)+ ) {+ context.report({+ node,+ message: `Use workspace package exports or package-local aliases instead of cross-package source import '${source}'.`+ })+ }+ }+ }+ }+}++const noStaleViteAppPaths = {+ meta: {+ docs: {+ description: 'Disallow stale Vite config paths to removed top-level app folders'+ }+ },+ create(context) {+ const file = normalizedFilename(context)+ if (!file.endsWith('/vite.config.ts')) return {}++ function reportIfStale(node, value) {+ if (typeof value !== 'string') return+ if (!value.includes('src/automation') && !value.includes('src/shims')) return+ context.report({+ node,+ message: 'Use current src/app/* paths instead of removed src/automation or src/shims paths.'+ })+ }++ return {+ Literal(node) {+ reportIfStale(node, node.value)},+ TemplateElement(node) {+ reportIfStale(node, node.value?.raw)+ }+ }+ }+}++function createParentRelativeImportRule({ description, applies, message }) {+ return {+ meta: {+ docs: { description }+ },+ create(context) {+ const file = normalizedFilename(context)+ if (!applies(file)) return {}++ function reportSource(node, source) {+ if (!source?.startsWith('../')) return+ if (/^(?:\.\.\/)+package\.json$/.test(source)) return+ context.report({ node, message })+ }++ function reportParentRelative(node) {+ reportSource(node, importSource(node))+ }++ return {+ ExportAllDeclaration: reportParentRelative,+ ExportNamedDeclaration: reportParentRelative,+ ImportDeclaration: reportParentRelative,+ ImportExpression(node) {+ reportSource(node, typeof node.source?.value === 'string' ? node.source.value : null)+ }+ }+ }+ }+}++const noCoreParentRelativeImports = createParentRelativeImportRule({+ description: 'Disallow parent-relative imports in core internals — use #core/* aliases',+ applies: (file) =>+ file.includes('/packages/core/src/') && !file.includes('/packages/core/src/kiwi/kiwi-schema/'),+ message: 'Use the #core/* package-local alias instead of parent-relative core imports.'+})++const noMcpParentRelativeImports = createParentRelativeImportRule({+ description: 'Disallow parent-relative imports in MCP internals — use #mcp/* aliases',+ applies: (file) => file.includes('/packages/mcp/src/'),+ message: 'Use the #mcp/* package-local alias instead of parent-relative MCP imports.'+})++const noVueParentRelativeImports = createParentRelativeImportRule({+ description: 'Disallow parent-relative imports in Vue SDK internals — use #vue/* aliases',+ applies: (file) => file.includes('/packages/vue/src/'),+ message: 'Use the #vue/* package-local alias instead of parent-relative Vue SDK imports.'+})++const noCliParentRelativeImports = createParentRelativeImportRule({+ description: 'Disallow parent-relative imports in CLI internals — use #cli/* aliases',+ applies: (file) => file.includes('/packages/cli/src/'),+ message: 'Use the #cli/* package-local alias instead of parent-relative CLI imports.'+})++const noRootDemoModule = {+ meta: {+ docs: {+ description: 'Disallow root src/demo.ts — keep demo builders under src/app/demo'+ }+ },+ create(context) {+ const file = normalizedFilename(context)+ if (!file.endsWith('/src/demo.ts')) return {}++ return {+ Program(node) {+ context.report({+ node,+ message: 'Move demo document builders under src/app/demo instead of root src/demo.ts.'+ })+ }+ }+ }+}++function createExactCoreBarrelImportRule({ description, applies, message }) {+ return {+ meta: {+ docs: { description }+ },+ create(context) {+ const file = normalizedFilename(context)+ if (!applies(file)) return {}++ return {+ ImportDeclaration(node) {+ const source = importSource(node)+ if (source !== '@open-pencil/core') return+ context.report({ node, message })+ }+ }+ }+ }+}++const noMcpCoreBarrelImports = createExactCoreBarrelImportRule({+ description: 'Disallow MCP imports from @open-pencil/core root barrel — use domain subpaths',+ applies: (file) => file.includes('/packages/mcp/src/'),+ message: 'Use a targeted @open-pencil/core subpath in MCP code instead of the compatibility barrel.'+})++const noCliCoreBarrelImports = createExactCoreBarrelImportRule({+ description: 'Disallow CLI imports from @open-pencil/core root barrel — use domain subpaths',+ applies: (file) => file.includes('/packages/cli/src/'),+ message: 'Use a targeted @open-pencil/core subpath in CLI code instead of the compatibility barrel.'+})++const noScriptCoreBarrelImports = createExactCoreBarrelImportRule({+ description: 'Disallow script imports from @open-pencil/core root barrel — use domain subpaths',+ applies: (file) => file.includes('/scripts/'),+ message: 'Use a targeted @open-pencil/core subpath or #core/* alias in scripts instead of the compatibility barrel.'+})++const noCoreSelfPackageImports = {+ meta: {+ docs: {+ description: 'Disallow @open-pencil/core self-imports inside packages/core/src'+ }+ },+ create(context) {+ const file = normalizedFilename(context)+ if (!file.includes('/packages/core/src/')) return {}++ return {+ ImportDeclaration(node) {+ const source = importSource(node)+ if (!source?.startsWith('@open-pencil/core')) return+ context.report({+ node,+ message:+ 'Core internals must import local modules directly instead of importing the @open-pencil/core public package entrypoints.'+ })+ }+ }+ }+}++const noInlinePromptConstants = {+ meta: {+ docs: {+ description: 'Disallow inline prompt/context template literals — use markdown prompt files'+ }+ },+ create(context) {+ return {+ VariableDeclarator(node) {+ if (node.id?.type !== 'Identifier') return+ if (!/(?:PROMPT|CONTEXT)/.test(node.id.name)) return+ if (node.init?.type !== 'TemplateLiteral') return+ context.report({+ node,+ message:+ 'Move prompt/context text to a dedicated markdown file and import it instead of using an inline template literal.'+ })+ }+ }+ }+}++const noLegacyAppSupportImports = {+ meta: {+ docs: {+ description: 'Disallow imports from legacy top-level app support folders'+ }+ },+ create(context) {+ return {+ ImportDeclaration(node) {+ const source = importSource(node)+ if (!source || !/^@\/(?:utils|engine)\//.test(source)) return+ context.report({+ node,+ message:+ 'Move app support imports to cohesive src/app modules instead of using legacy @/utils/* or @/engine/* paths.'+ })+ }+ }+ }+}++const noAppVueCoreBarrelImports = createExactCoreBarrelImportRule({+ description:+ 'Disallow app and Vue SDK imports from @open-pencil/core root barrel — use domain subpaths',+ applies: (file) =>+ (file.includes('/src/') && !file.includes('/packages/')) ||+ file.includes('/packages/vue/src/'),+ message:+ 'Use a targeted @open-pencil/core subpath (editor, scene-graph, constants, io, etc.) instead of the compatibility barrel.'+})++const noAppImportsInPackages = {+ meta: {+ docs: {+ description: 'Disallow app-shell imports from workspace packages'+ }+ },+ create(context) {+ const file = normalizedFilename(context)+ if (!file.includes('/packages/')) return {}++ return {+ ImportDeclaration(node) {+ const source = importSource(node)+ if (!source?.startsWith('@/')) return+ context.report({+ node,+ message: `Workspace packages must not import app-shell alias '${source}'.`+ })+ }+ }+ }+}++const noCoreFrameworkImports = {+ meta: {+ docs: {+ description: 'Keep @open-pencil/core framework-agnostic by disallowing Vue/Tauri/app imports'+ }+ },+ create(context) {+ const file = normalizedFilename(context)+ if (!file.includes('/packages/core/src/')) return {}++ return {+ ImportDeclaration(node) {+ const source = importSource(node)+ if (!source) return+ if (+ source === 'vue' ||+ source.startsWith('@vue/') ||+ source.startsWith('@open-pencil/vue') ||+ source.startsWith('@tauri-apps/') ||+ source.startsWith('@/')+ ) {+ context.report({+ node,+ message: `@open-pencil/core must stay framework-agnostic; do not import '${source}'.`+ })+ }+ }+ }+ }+}++const noDirectStorageAccess = {+ meta: {+ docs: {+ description:+ 'Disallow direct localStorage/sessionStorage access outside dedicated storage modules'+ }+ },+ create(context) {+ const file = normalizedFilename(context)+ const allowedFiles = [+ '/src/app/ai/chat/storage.ts',+ '/src/app/shell/layout-storage.ts',+ '/packages/vue/src/i18n/locale.ts'+ ]+ if (allowedFiles.some((suffix) => file.endsWith(suffix))) return {}++ function reportStorage(node, name) {+ context.report({+ node,+ message: `Use a dedicated storage module instead of direct ${name} access.`+ })+ }++ return {+ Identifier(node) {+ if (node.name !== 'localStorage' && node.name !== 'sessionStorage') return+ reportStorage(node, node.name)+ }+ }+ }+}++const noLegacyShimFiles = {+ meta: {+ docs: {+ description: 'Disallow recreating removed compatibility shim files'+ }+ },+ create(context) {+ const file = normalizedFilename(context)+ const blocked = [+ '/src/stores/editor.ts',+ '/src/stores/tabs.ts',+ '/src/composables/use-canvas.ts',+ '/src/composables/use-canvas-input.ts',+ '/src/composables/use-collab.ts',+ '/src/composables/use-keyboard.ts'+ ]+ const blockedDirs = ['/src/ai/', '/src/automation/']+ const isBlocked =+ blocked.some((suffix) => file.endsWith(suffix)) ||+ blockedDirs.some((segment) => file.includes(segment))++ if (!isBlocked) return {}++ return {+ Program(node) {+ context.report({+ node,+ message: 'Do not recreate removed compatibility shims; use the canonical src/app module.'+ })+ }+ }+ }+}++const noLegacyTestAppImports = {+ meta: {+ docs: {+ description: 'Disallow tests importing removed top-level app modules'+ }+ },+ create(context) {+ const file = normalizedFilename(context)+ if (!file.includes('/tests/')) return {}++ function reportLegacyTestImport(node) {+ const source = importSource(node)+ if (!source || !/^(?:\.\.\/)+src\/(?:ai|automation|composables|stores|utils|engine)\//.test(source)) {+ return+ }+ context.report({+ node,+ message: 'Use the current src/app/* module path instead of a removed top-level app module.'+ })+ }++ return {+ ExportAllDeclaration: reportLegacyTestImport,+ ExportNamedDeclaration: reportLegacyTestImport,+ ImportDeclaration: reportLegacyTestImport+ }+ }+}++const noTestCoreSourceImports = {+ meta: {+ docs: {+ description: 'Disallow tests importing non-vendored core internals by relative source path'+ }+ },+ create(context) {+ const file = normalizedFilename(context)+ if (!file.includes('/tests/')) return {}++ function reportCoreSourceImport(node) {+ const source = importSource(node)+ if (!source || !/^(?:\.\.\/)+packages\/core\/src\/(?!kiwi\/kiwi-schema)/.test(source)) {+ return+ }+ context.report({+ node,+ message: 'Use #core/* instead of a relative packages/core/src import in tests.'+ })+ }++ return {+ ExportAllDeclaration: reportCoreSourceImport,+ ExportNamedDeclaration: reportCoreSourceImport,+ ImportDeclaration: reportCoreSourceImport,+ ImportExpression: reportCoreSourceImport+ }+ }+}++const noBroadDoubleCast = {+ meta: {+ docs: {+ description: 'Disallow broad `as unknown as` casts in app and Vue SDK code'+ }+ },+ create(context) {+ const file = normalizedFilename(context)+ const applies = file.includes('/src/app/') || file.includes('/packages/vue/src/')+ if (!applies) return {}++ return {+ TSAsExpression(node) {+ if (isUnknownTypeAnnotation(node.expression?.typeAnnotation)) {+ context.report({+ node,+ message: 'Avoid `as unknown as ...`; model the value with a precise type or helper.'+ })+ }+ }+ }+ }+}++const noCoreBrowserGlobals = {+ meta: {+ docs: {+ description:+ 'Disallow direct browser globals in core outside explicit platform boundary modules'+ }+ },+ create(context) {+ const file = normalizedFilename(context)+ if (!file.includes('/packages/core/src/')) return {}++ const allowedFiles = [+ '/packages/core/src/constants.ts',+ '/packages/core/src/editor/create.ts',+ '/packages/core/src/canvas/renderer.ts',+ '/packages/core/src/text/fonts.ts',+ '/packages/core/src/profiler/render-profiler.ts',+ '/packages/core/src/figma-api/index.ts'+ ]+ if (allowedFiles.some((suffix) => file.endsWith(suffix))) return {}++ return {+ Identifier(node) {+ if (node.name !== 'window' && node.name !== 'document' && node.name !== 'navigator') return+ context.report({+ node,+ message: `Do not use browser global '${node.name}' in core; route it through a platform boundary.`+ })+ }+ }+ }+}++const noDirectGraphEmitterSubscriptions = {+ meta: {+ docs: {+ description: 'Disallow direct graph.emitter.on subscriptions outside SceneGraph helpers'+ }+ },+ create(context) {+ const file = normalizedFilename(context)+ if (file.endsWith('/packages/core/src/scene-graph/index.ts')) return {}++ return {+ CallExpression(node) {+ const callee = node.callee+ if (callee?.type !== 'MemberExpression') return+ if (callee.property?.type !== 'Identifier' || callee.property.name !== 'on') return+ const object = callee.object+ if (object?.type !== 'MemberExpression') return+ if (object.property?.type !== 'Identifier' || object.property.name !== 'emitter') return+ context.report({+ node,+ message: 'Use SceneGraph.onNodeEvents() instead of subscribing to graph.emitter directly.'+ })+ }+ }+ }+}++const noOnUnmountedInCompositionRoots = {+ meta: {+ docs: {+ description: 'Prefer tryOnScopeDispose over onUnmounted in composable roots'+ }+ },+ create(context) {+ const file = normalizedFilename(context)+ const applies =+ (file.includes('/src/app/') || file.includes('/packages/vue/src/')) &&+ /\/(?:use|create)\.ts$/.test(file)+ if (!applies) return {}++ return {+ CallExpression(node) {+ if (node.callee?.type !== 'Identifier' || node.callee.name !== 'onUnmounted') return+ context.report({+ node,+ message:+ 'Use tryOnScopeDispose() for composable cleanup so callers outside component setup are handled safely.'+ })+ }+ }+ }+}++const noComposableStateWrappers = {+ meta: {+ docs: {+ description: 'Disallow create*ComposableState wrapper factories in app and Vue SDK code'}},+ create(context) {+ const file = normalizedFilename(context)+ const applies = file.includes('/src/app/') || file.includes('/packages/vue/src/')+ if (!applies) return {}++ return {+ FunctionDeclaration(node) {+ if (!node.id?.name || !/^create\w*ComposableState$/.test(node.id.name)) return+ context.report({+ node,+ message:+ 'Avoid wrapper-of-wrapper composable state factories; keep setup local or extract a cohesive domain helper.'+ })+ }+ }+ }+}++const preferVueUseIntervals = {+ meta: {+ docs: {+ description: 'Prefer VueUse interval helpers over manual setInterval/clearInterval pairs'+ }+ },+ create(context) {+ const file = normalizedFilename(context)+ const applies = file.includes('/src/app/') || file.includes('/packages/vue/src/')+ if (!applies) return {}++ function intervalName(callee) {+ if (callee?.type === 'Identifier') return callee.name+ if (callee?.type === 'MemberExpression' && callee.property?.type === 'Identifier') {+ return callee.property.name+ }+ return null+ }++ return {+ CallExpression(node) {+ const name = intervalName(node.callee)+ if (name !== 'setInterval' && name !== 'clearInterval') return+ context.report({+ node,+ message: 'Use useIntervalFn() from @vueuse/core instead of manual interval cleanup.'+ })+ }+ }+ }+}++const preferVueUseTimeouts = {+ meta: {+ docs: {+ description: 'Prefer VueUse timeout helpers over manual timeout cleanup in composables'+ }+ },+ create(context) {+ const file = normalizedFilename(context)+ const applies =+ ((file.includes('/src/app/') || file.includes('/packages/vue/src/')) &&+ /\/(?:use|create)\.ts$/.test(file)) ||+ file.endsWith('/src/app/shell/toast/action.ts')+ if (!applies) return {}++ return {+ CallExpression(node) {+ if (node.callee?.type !== 'Identifier' || node.callee.name !== 'clearTimeout') return+ context.report({+ node,+ message:+ 'Use useTimeoutFn() from @vueuse/core instead of manual timeout cleanup in composables.'+ })+ }+ }+ }+}++const maxCompositionRootLines = {+ meta: {+ docs: {+ description:+ 'Keep composition roots small; extract domain helpers before they become cleanup projects'+ },+ schema: [+ {+ type: 'object',+ properties: {+ max: { type: 'number' }+ },+ additionalProperties: false+ }+ ]+ },+ create(context) {+ const file = normalizedFilename(context)+ const applies =+ (file.includes('/src/app/') || file.includes('/packages/vue/src/')) &&+ /\/(?:use|create)\.ts$/.test(file)+ if (!applies) return {}++ const max = context.options[0]?.max ?? 260++ return {+ Program(node) {+ const lineCount = context.sourceCode.getText().split('\n').length+ if (lineCount <= max) return+ context.report({+ node,+ message: `Composition root is ${lineCount} lines; extract helpers before exceeding ${max} lines.`+ })+ }+ }+ }+}++function isPascalCaseName(name) {+ return /^[A-Z][A-Za-z0-9]*$/.test(name)+}++function isKebabOrLowercaseName(name) {+ return /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(name)+}++const vueComponentFilePascalCase = {+ meta: {+ docs: {+ description: 'Require Vue component files to use PascalCase names'+ }+ },+ create(context) {+ const file = normalizedFilename(context)+ if (!file.endsWith('.vue')) return {}++ return {+ Program(node) {+ const basename = file.split('/').at(-1)?.replace(/\.vue$/, '') ?? ''+ if (isPascalCaseName(basename)) return+ context.report({+ node,+ message: 'Vue component files must use PascalCase names.'+ })+ }+ }+ }+}++const componentNamespacePascalCase = {+ meta: {+ docs: {+ description: 'Require component namespace folders to use PascalCase names'+ }+ },+ create(context) {+ const file = normalizedFilename(context)++ return {+ Program(node) {+ const primitiveMatch = file.match(/\/packages\/vue\/src\/primitives\/([^/]+)/)+ if (primitiveMatch && !isPascalCaseName(primitiveMatch[1])) {+ context.report({+ node,+ message: `Vue primitive namespace folder '${primitiveMatch[1]}' must use PascalCase.`+ })+ return+ }++ const componentMatch = file.match(/\/src\/components\/(.+)$/)+ if (!componentMatch) return++ const parts = componentMatch[1].split('/')+ const first = parts[0]+ const second = parts[1]+ const allowedGroups = new Set(['chat', 'properties', 'ui'])++ if (parts.length > 1 && !allowedGroups.has(first) && !isPascalCaseName(first)) {+ context.report({+ node,+ message: `Component namespace folder '${first}' must use PascalCase.`+ })+ return+ }++ if (+ parts.length > 2 &&+ (first === 'chat' || first === 'properties') &&+ second !== undefined &&+ !isPascalCaseName(second)+ ) {+ context.report({+ node,+ message: `Nested component namespace folder '${first}/${second}' must use PascalCase.`+ })+ }+ }+ }+ }+}++const nonComponentSourceDirectoriesKebabCase = {+ meta: {+ docs: {+ description: 'Require non-component source directories to use lowercase or kebab-case names'+ }+ },+ create(context) {+ const file = normalizedFilename(context)++ const roots = [+ '/src/app/',+ '/packages/core/src/',+ '/packages/cli/src/',+ '/packages/mcp/src/',+ '/packages/vue/src/canvas/',+ '/packages/vue/src/controls/',+ '/packages/vue/src/document/',+ '/packages/vue/src/editor/',+ '/packages/vue/src/i18n/',+ '/packages/vue/src/internal/',+ '/packages/vue/src/shared/',+ '/packages/vue/src/variables/'+ ]++ const root = roots.find((candidate) => file.includes(candidate))+ if (!root) return {}++ return {+ Program(node) {+ const relativePath = file.slice(file.indexOf(root) + root.length)+ const directories = relativePath.split('/').slice(0, -1)+ const invalid = directories.find((part) => !isKebabOrLowercaseName(part))+ if (!invalid) return+ context.report({+ node,+ message: `Non-component source directory '${invalid}' must use lowercase or kebab-case.`+ })+ }+ }+ }+}++const noComponentRootSiblingFolder = {+ meta: {+ docs: {+ description: 'Disallow multi-file component roots beside their namespace folder'+ }+ },+ create(context) {+ const file = normalizedFilename(context)+ const match = file.match(/\/src\/components\/(?:chat\/|properties\/)?([A-Z][A-Za-z0-9]*)\.vue$/)+ if (!match) return {}++ return {+ Program(node) {+ const dir = file.replace(/\.vue$/, '')+ if (!existsSync(dir)) return+ context.report({+ node,+ message: `Move '${match[1]}.vue' inside its '${match[1]}/' component namespace folder.`+ })+ }+ }+ }+}++const noFunctionAliasImports = {+ meta: {+ docs: {+ description: 'Disallow import aliases ending in Fn for facade delegation'+ }+ },+ create(context) {+ return {+ ImportSpecifier(node) {+ if (!node.imported || !node.local) return+ if (node.imported.type !== 'Identifier' || node.local.type !== 'Identifier') return+ if (node.imported.name === node.local.name) return+ if (!node.local.name.endsWith('Fn')) return+ context.report({+ node,+ message:+ 'Avoid aliasing imports as *Fn. Use a namespace import or give the exported helper a clearer domain name.'+ })+ }+ }+ }+}++const noFlatKiwiModules = {+ meta: {+ docs: {+ description: 'Disallow flat top-level Kiwi modules — group code under Kiwi subdomains'+ }+ },+ create(context) {+ const file = normalizedFilename(context)+ const marker = '/packages/core/src/kiwi/'+ const start = file.indexOf(marker)+ if (start === -1) return {}++ const relativePath = file.slice(start + marker.length)+ if (relativePath.includes('/') || relativePath === 'index.ts') return {}++ return {+ Program(node) {+ context.report({+ node,+ message:+ 'Move Kiwi modules under binary/, fig/, node-change/, instance-overrides/, or kiwi-schema/ instead of adding flat top-level files.'+ })+ }+ }+ }}const plugin = {@@ -255,7 +1195,43 @@ const plugin = {'no-raw-console-format': noRawConsoleFormat,'no-silent-catch': noSilentCatch,'no-typeof-window-check': noTypeofWindowCheck,- },+ 'no-legacy-app-imports': noLegacyAppImports,+ 'no-vue-self-package-imports': noVueSelfPackageImports,+ 'no-cross-package-source-imports': noCrossPackageSourceImports,+ 'no-core-parent-relative-imports': noCoreParentRelativeImports,+ 'no-mcp-parent-relative-imports': noMcpParentRelativeImports,+ 'no-vue-parent-relative-imports': noVueParentRelativeImports,+ 'no-stale-vite-app-paths': noStaleViteAppPaths,+ 'no-cli-parent-relative-imports': noCliParentRelativeImports,+ 'no-root-demo-module': noRootDemoModule,+ 'no-mcp-core-barrel-imports': noMcpCoreBarrelImports,+ 'no-cli-core-barrel-imports': noCliCoreBarrelImports,+ 'no-script-core-barrel-imports': noScriptCoreBarrelImports,+ 'no-core-self-package-imports': noCoreSelfPackageImports,+ 'no-inline-prompt-constants': noInlinePromptConstants,+ 'no-legacy-app-support-imports': noLegacyAppSupportImports,+ 'no-app-vue-core-barrel-imports': noAppVueCoreBarrelImports,+ 'no-app-imports-in-packages': noAppImportsInPackages,+ 'no-core-framework-imports': noCoreFrameworkImports,+ 'no-direct-storage-access': noDirectStorageAccess,+ 'no-legacy-shim-files': noLegacyShimFiles,+ 'no-legacy-test-app-imports': noLegacyTestAppImports,+ 'no-test-core-source-imports': noTestCoreSourceImports,+ 'no-broad-double-cast': noBroadDoubleCast,+ 'no-core-browser-globals': noCoreBrowserGlobals,+ 'no-direct-graph-emitter-subscriptions': noDirectGraphEmitterSubscriptions,+ 'no-on-unmounted-in-composition-roots': noOnUnmountedInCompositionRoots,+ 'no-composable-state-wrappers': noComposableStateWrappers,+ 'prefer-vueuse-intervals': preferVueUseIntervals,+ 'prefer-vueuse-timeouts': preferVueUseTimeouts,+ 'max-composition-root-lines': maxCompositionRootLines,+ 'vue-component-file-pascal-case': vueComponentFilePascalCase,+ 'component-namespace-pascal-case': componentNamespacePascalCase,+ 'non-component-source-directories-kebab-case': nonComponentSourceDirectoriesKebabCase,+ 'no-component-root-sibling-folder': noComponentRootSiblingFolder,+ 'no-function-alias-imports': noFunctionAliasImports,+ 'no-flat-kiwi-modules': noFlatKiwiModules+ }}export default plugindiff --git a/oxlint.json b/oxlint.jsonindex 18e397162..0a81a2a71 100644--- a/oxlint.json+++ b/oxlint.json@@ -1,14 +1,7 @@{"$schema": "./node_modules/oxlint/configuration_schema.json",- "plugins": [- "typescript",- "import",- "unicorn",- "vue"- ],- "jsPlugins": [- "./lint/plugin.js"- ],+ "plugins": ["typescript", "import", "unicorn", "vue"],+ "jsPlugins": ["./lint/plugin.js"],"env": {"browser": true,"es2024": true@@ -31,22 +24,12 @@],"patterns": [{- "group": [- "@/engine/*"- ],+ "group": ["@/engine/*"],"message": "Import from @open-pencil/core unless the module adds platform-specific logic.",- "allowImportNames": [- "loadFont",- "listFamilies",- "listFonts",- "preloadFonts"- ]+ "allowImportNames": ["loadFont", "listFamilies", "listFonts", "preloadFonts"]},{- "group": [- "../../packages/*",- "../../../packages/*"- ],+ "group": ["../../packages/*", "../../../packages/*"],"message": "Use the workspace package name (e.g. @open-pencil/core) instead of relative paths to packages/."}]@@ -119,14 +102,22 @@"open-pencil/no-hand-rolled-color": "error","open-pencil/no-raw-console-format": "off","open-pencil/no-silent-catch": "error",- "open-pencil/no-typeof-window-check": "error"+ "open-pencil/no-typeof-window-check": "error",+ "open-pencil/no-legacy-app-imports": "error",+ "open-pencil/no-vue-self-package-imports": "error",+ "open-pencil/no-cross-package-source-imports": "error",+ "open-pencil/no-app-imports-in-packages": "error",+ "open-pencil/no-core-framework-imports": "error",+ "open-pencil/no-direct-storage-access": "error",+ "open-pencil/no-legacy-shim-files": "error",+ "open-pencil/no-broad-double-cast": "error",+ "open-pencil/no-core-browser-globals": "error",+ "open-pencil/no-function-alias-imports": "error",+ "open-pencil/max-composition-root-lines": ["error", { "max": 260 }]},"overrides": [{- "files": [- "**/*.test.ts",- "**/*.test.tsx"- ],+ "files": ["**/*.test.ts", "**/*.test.tsx"],"rules": {"typescript/no-explicit-any": "off","typescript/no-non-null-assertion": "off",@@ -134,33 +125,13 @@}},{- "files": [- "**/tools/ai-adapter.ts"- ],+ "files": ["**/tools/ai-adapter.ts"],"rules": {"typescript/no-explicit-any": "off"}},{- "files": [- "**/figma-api.ts"- ],- "rules": {- "no-console": "off"- }- },- {- "files": [- "**/render/render.ts"- ],- "rules": {- "typescript/no-implied-eval": "off"- }- },- {- "files": [- "**/kiwi/kiwi-schema/**"- ],+ "files": ["**/kiwi/kiwi-schema/**"],"rules": {"typescript/no-explicit-any": "off","typescript/no-non-null-assertion": "off",@@ -177,37 +148,17 @@}},{- "files": [- "src/stores/editor.ts",- "src/composables/use-canvas-input.ts",- "src/demo.ts"- ],- "rules": {- "max-lines": "off"- }- },- {- "files": [- "packages/cli/src/**",- "packages/mcp/src/**"- ],+ "files": ["packages/cli/src/**", "packages/mcp/src/**"],"rules": {"no-console": "off"}},{- "files": [- "packages/cli/src/commands/**"- ],+ "files": ["packages/cli/src/commands/**"],"rules": {"open-pencil/no-raw-console-format": "error"}}],- "ignorePatterns": [- "node_modules",- "dist",- "desktop",- "*.config.*"- ]+ "ignorePatterns": ["node_modules", "dist", "desktop", "*.config.*"]}diff --git a/oxlint.structure.json b/oxlint.structure.jsonnew file mode 100644index 000000000..1f80605cd--- /dev/null+++ b/oxlint.structure.json@@ -0,0 +1,54 @@+{+ "$schema": "./node_modules/oxlint/configuration_schema.json",+ "jsPlugins": ["./lint/plugin.js"],+ "env": {+ "browser": true,+ "es2024": true+ },+ "overrides": [+ {+ "files": ["tests/**/*.ts"],+ "rules": {+ "no-unused-vars": "off"+ }+ }+ ],+ "rules": {+ "open-pencil/no-legacy-app-imports": "error",+ "open-pencil/no-vue-self-package-imports": "error",+ "open-pencil/no-cross-package-source-imports": "error",+ "open-pencil/no-core-parent-relative-imports": "error",+ "open-pencil/no-mcp-parent-relative-imports": "error",+ "open-pencil/no-vue-parent-relative-imports": "error",+ "open-pencil/no-stale-vite-app-paths": "error",+ "open-pencil/no-cli-parent-relative-imports": "error",+ "open-pencil/no-root-demo-module": "error",+ "open-pencil/no-mcp-core-barrel-imports": "error",+ "open-pencil/no-cli-core-barrel-imports": "error",+ "open-pencil/no-script-core-barrel-imports": "error",+ "open-pencil/no-core-self-package-imports": "error",+ "open-pencil/no-inline-prompt-constants": "error",+ "open-pencil/no-legacy-app-support-imports": "error",+ "open-pencil/no-app-vue-core-barrel-imports": "error",+ "open-pencil/no-app-imports-in-packages": "error",+ "open-pencil/no-core-framework-imports": "error",+ "open-pencil/no-direct-storage-access": "error",+ "open-pencil/no-legacy-shim-files": "error",+ "open-pencil/no-legacy-test-app-imports": "error",+ "open-pencil/no-test-core-source-imports": "error",+ "open-pencil/no-broad-double-cast": "error",+ "open-pencil/no-core-browser-globals": "error",+ "open-pencil/no-direct-graph-emitter-subscriptions": "error",+ "open-pencil/no-on-unmounted-in-composition-roots": "error",+ "open-pencil/no-composable-state-wrappers": "error",+ "open-pencil/prefer-vueuse-intervals": "error",+ "open-pencil/prefer-vueuse-timeouts": "error",+ "open-pencil/max-composition-root-lines": ["error", { "max": 260 }],+ "open-pencil/vue-component-file-pascal-case": "error",+ "open-pencil/component-namespace-pascal-case": "error",+ "open-pencil/non-component-source-directories-kebab-case": "error",+ "open-pencil/no-component-root-sibling-folder": "error",+ "open-pencil/no-flat-kiwi-modules": "error"+ },+ "ignorePatterns": ["node_modules", "dist", "desktop"]+}diff --git a/package.json b/package.jsonindex 61e55eb36..599f7a40d 100644--- a/package.json+++ b/package.json@@ -1,18 +1,19 @@{"name": "open-pencil-app",- "private": true,"version": "0.11.8",+ "private": true,"license": "MIT",- "type": "module","workspaces": ["packages/*"],+ "type": "module","scripts": {"dev": "vite","build": "bun run lint && vite build","preview": "vite preview","tauri": "tauri",- "lint": "oxlint -c oxlint.json --type-aware --type-check src/ packages/core/src/ packages/cli/src/ packages/mcp/src/",+ "lint": "bun run lint:structure && oxlint -c oxlint.json --type-aware --type-check src/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/",+ "lint:structure": "oxlint -c oxlint.structure.json vite.config.ts vite/ src/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ tests/ scripts/","format": "oxfmt --write src/ packages/core/src/ packages/cli/src/ packages/mcp/src/ packages/vue/src/","check": "bun run lint && tsgo --noEmit && bun run check:vue","check:vue": "vue-tsc --noEmit -p tsconfig.json && vue-tsc --noEmit -p packages/vue/tsconfig.json",@@ -49,6 +50,7 @@"@tauri-apps/plugin-opener": "^2","@tauri-apps/plugin-shell": "^2.3.5","@unhead/vue": "^2.1.10",+ "@use-gesture/vanilla": "^10.3.1","@vueuse/core": "^14.2.1","ai": "^6.0.116","canvaskit-wasm": "^0.40.0",@@ -64,6 +66,7 @@"tailwind-merge": "^3.5.0","tailwind-variants": "^3.2.2","tailwindcss": "^4.2.1",+ "tinykeys": "^3.0.0","trystero": "^0.22.0","valibot": "^1.2.0","vue": "^3.5.29",@@ -90,8 +93,6 @@"@types/ws": "^8.18.1","@typescript/native-preview": "^7.0.0-dev.20260228.1","@vitejs/plugin-vue": "^6.0.5",- "unplugin-vue": "^7.1.1",- "unplugin-raw": "^0.6.4","esbuild": "^0.27.3","hono": "^4.12.5","jscpd": "^4.0.8",@@ -99,14 +100,16 @@"oxfmt": "^0.35.0","oxlint": "^1.50.0","oxlint-tsgolint": "^0.16.0",+ "tsdown": "^0.21.7","tw-animate-css": "^1.4.0","typescript": "~5.8.3","unplugin-icons": "^23.0.1",+ "unplugin-raw": "^0.6.4",+ "unplugin-vue": "^7.1.1","unplugin-vue-components": "^31.0.0","vite": "^8.0.0","vite-plugin-pwa": "^1.2.0","vue-tsc": "^3.2.5",- "tsdown": "^0.21.7","workbox-window": "^7.4.0","ws": "^8.19.0"}diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex b2f0c750e..4da42d86d 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -3,6 +3,9 @@"version": "0.11.8","license": "MIT","type": "module",+ "imports": {+ "#cli/*": "./src/*"+ },"bin": {"openpencil": "./src/index.ts"},diff --git a/packages/cli/src/app-client.ts b/packages/cli/src/app-client.tsindex 63ae8fe7f..95a38f034 100644--- a/packages/cli/src/app-client.ts+++ b/packages/cli/src/app-client.ts@@ -1,4 +1,4 @@-import { AUTOMATION_HTTP_PORT } from '@open-pencil/core'+import { AUTOMATION_HTTP_PORT } from '@open-pencil/core/constants'const HEALTH_URL = `http://127.0.0.1:${AUTOMATION_HTTP_PORT}/health`const RPC_URL = `http://127.0.0.1:${AUTOMATION_HTTP_PORT}/rpc`diff --git a/packages/cli/src/commands/analyze/clusters.ts b/packages/cli/src/commands/analyze/clusters.tsindex 5743d959c..c0238347c 100644--- a/packages/cli/src/commands/analyze/clusters.ts+++ b/packages/cli/src/commands/analyze/clusters.ts@@ -1,12 +1,11 @@import { defineCommand } from 'citty'-import { executeRpcCommand, calcClusterConfidence } from '@open-pencil/core'+import { calcClusterConfidence } from '@open-pencil/core/tools'-import { isAppMode, requireFile, rpc } from '../../app-client'-import { bold, fmtList, fmtSummary } from '../../format'-import { loadDocument } from '../../headless'+import { loadRpcData } from '#cli/rpc-data'+import { bold, fmtList, fmtSummary } from '#cli/format'-import type { AnalyzeClustersResult } from '@open-pencil/core'+import type { AnalyzeClustersResult } from '@open-pencil/core/rpc'function formatSignature(sig: string): string {const [typeSize, children] = sig.split('|')@@ -25,20 +24,6 @@ function formatSignature(sig: string): string {return `${typeName} > [${childParts.join(', ')}]`}-async function getData(- file: string | undefined,- args: { limit?: string; 'min-size'?: string; 'min-count'?: string }-): Promise<AnalyzeClustersResult> {- const rpcArgs = {- limit: Number(args.limit ?? 20),- minSize: Number(args['min-size'] ?? 30),- minCount: Number(args['min-count'] ?? 2)- }- if (isAppMode(file)) return rpc<AnalyzeClustersResult>('analyze_clusters', rpcArgs)- const graph = await loadDocument(requireFile(file))- return executeRpcCommand(graph, 'analyze_clusters', rpcArgs) as AnalyzeClustersResult-}-export default defineCommand({meta: { description: 'Find repeated design patterns (potential components)' },args: {@@ -53,7 +38,11 @@ export default defineCommand({json: { type: 'boolean', description: 'Output as JSON' }},async run({ args }) {- const data = await getData(args.file, args)+ const data = await loadRpcData<AnalyzeClustersResult>(args.file, 'analyze_clusters', {+ limit: Number(args.limit),+ minSize: Number(args['min-size']),+ minCount: Number(args['min-count'])+ })if (args.json) {console.log(JSON.stringify(data, null, 2))diff --git a/packages/cli/src/commands/analyze/colors.ts b/packages/cli/src/commands/analyze/colors.tsindex 806f64cc4..a0a106298 100644--- a/packages/cli/src/commands/analyze/colors.ts+++ b/packages/cli/src/commands/analyze/colors.ts@@ -1,22 +1,9 @@import { defineCommand } from 'citty'-import { executeRpcCommand } from '@open-pencil/core'+import { loadRpcData } from '#cli/rpc-data'+import { bold, fmtHistogram, fmtList, fmtSummary } from '#cli/format'-import { isAppMode, requireFile, rpc } from '../../app-client'-import { bold, fmtHistogram, fmtList, fmtSummary } from '../../format'-import { loadDocument } from '../../headless'--import type { AnalyzeColorsResult } from '@open-pencil/core'--async function getData(- file: string | undefined,- args: { threshold?: string; similar?: boolean }-): Promise<AnalyzeColorsResult> {- const rpcArgs = { threshold: Number(args.threshold ?? 15), similar: args.similar }- if (isAppMode(file)) return rpc<AnalyzeColorsResult>('analyze_colors', rpcArgs)- const graph = await loadDocument(requireFile(file))- return executeRpcCommand(graph, 'analyze_colors', rpcArgs) as AnalyzeColorsResult-}+import type { AnalyzeColorsResult } from '@open-pencil/core/rpc'export default defineCommand({meta: { description: 'Analyze color palette usage' },@@ -36,7 +23,10 @@ export default defineCommand({json: { type: 'boolean', description: 'Output as JSON' }},async run({ args }) {- const data = await getData(args.file, args)+ const data = await loadRpcData<AnalyzeColorsResult>(args.file, 'analyze_colors', {+ threshold: Number(args.threshold),+ similar: args.similar+ })const limit = Number(args.limit)if (args.json) {diff --git a/packages/cli/src/commands/analyze/spacing.ts b/packages/cli/src/commands/analyze/spacing.tsindex 8543f0fc2..e1a82f019 100644--- a/packages/cli/src/commands/analyze/spacing.ts+++ b/packages/cli/src/commands/analyze/spacing.ts@@ -1,18 +1,9 @@import { defineCommand } from 'citty'-import { executeRpcCommand } from '@open-pencil/core'+import { loadRpcData } from '#cli/rpc-data'+import { bold, kv, fmtHistogram, fmtSummary } from '#cli/format'-import { isAppMode, requireFile, rpc } from '../../app-client'-import { bold, kv, fmtHistogram, fmtSummary } from '../../format'-import { loadDocument } from '../../headless'--import type { AnalyzeSpacingResult } from '@open-pencil/core'--async function getData(file?: string): Promise<AnalyzeSpacingResult> {- if (isAppMode(file)) return rpc<AnalyzeSpacingResult>('analyze_spacing')- const graph = await loadDocument(requireFile(file))- return executeRpcCommand(graph, 'analyze_spacing', undefined) as AnalyzeSpacingResult-}+import type { AnalyzeSpacingResult } from '@open-pencil/core/rpc'export default defineCommand({meta: { description: 'Analyze spacing values (gap, padding)' },@@ -26,7 +17,7 @@ export default defineCommand({json: { type: 'boolean', description: 'Output as JSON' }},async run({ args }) {- const data = await getData(args.file)+ const data = await loadRpcData<AnalyzeSpacingResult>(args.file, 'analyze_spacing')const gridSize = Number(args.grid)if (args.json) {diff --git a/packages/cli/src/commands/analyze/typography.ts b/packages/cli/src/commands/analyze/typography.tsindex c0694fc86..0d856e5e6 100644--- a/packages/cli/src/commands/analyze/typography.ts+++ b/packages/cli/src/commands/analyze/typography.ts@@ -1,12 +1,9 @@import { defineCommand } from 'citty'-import { executeRpcCommand } from '@open-pencil/core'+import { loadRpcData } from '#cli/rpc-data'+import { bold, fmtHistogram, fmtSummary } from '#cli/format'-import { isAppMode, requireFile, rpc } from '../../app-client'-import { bold, fmtHistogram, fmtSummary } from '../../format'-import { loadDocument } from '../../headless'--import type { AnalyzeTypographyResult } from '@open-pencil/core'+import type { AnalyzeTypographyResult } from '@open-pencil/core/rpc'function weightName(w: number): string {if (w <= 100) return 'Thin'@@ -20,12 +17,6 @@ function weightName(w: number): string {return 'Black'}-async function getData(file?: string): Promise<AnalyzeTypographyResult> {- if (isAppMode(file)) return rpc<AnalyzeTypographyResult>('analyze_typography')- const graph = await loadDocument(requireFile(file))- return executeRpcCommand(graph, 'analyze_typography', {}) as AnalyzeTypographyResult-}-export default defineCommand({meta: { description: 'Analyze typography usage' },args: {@@ -42,7 +33,7 @@ export default defineCommand({json: { type: 'boolean', description: 'Output as JSON' }},async run({ args }) {- const data = await getData(args.file)+ const data = await loadRpcData<AnalyzeTypographyResult>(args.file, 'analyze_typography', {})const limit = Number(args.limit)const groupBy = args['group-by']diff --git a/packages/cli/src/commands/convert.ts b/packages/cli/src/commands/convert.tsindex 04673dcf9..d52681e87 100644--- a/packages/cli/src/commands/convert.ts+++ b/packages/cli/src/commands/convert.ts@@ -2,18 +2,19 @@ import { basename, extname, resolve } from 'node:path'import { defineCommand } from 'citty'-import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core'+import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'-import { requireFile } from '../app-client'-import { ok, printError } from '../format'-import { loadDocument } from '../headless'+import { requireFile } from '#cli/app-client'+import { ok, printError } from '#cli/format'+import { loadDocument } from '#cli/headless'const io = new IORegistry(BUILTIN_IO_FORMATS)-const WRITABLE_FORMATS = ['FIG'] as const-type WritableFormat = (typeof WRITABLE_FORMATS)[number]+function writableFormatIds(): string[] {+ return io.listWritableFormats().map((format) => format.id)+}-function defaultOutput(file: string, format: WritableFormat): string {+function defaultOutput(file: string, format: string): string {const base = basename(file, extname(file))return resolve(`${base}.${format.toLowerCase()}`)}@@ -40,15 +41,16 @@ export default defineCommand({}},async run({ args }) {- const format = args.format.toUpperCase() as WritableFormat- if (!WRITABLE_FORMATS.includes(format)) {- printError(`Invalid format "${args.format}". Use fig.`)+ const format = args.format.toLowerCase()+ const writableFormats = writableFormatIds()+ if (!writableFormats.includes(format)) {+ printError(`Invalid format "${args.format}". Use ${writableFormats.join(', ')}.`)process.exit(1)}const file = requireFile(args.file)const graph = await loadDocument(file)- const result = await io.writeDocument(format.toLowerCase(), graph)+ const result = await io.writeDocument(format, graph)const output = args.output ? resolve(args.output) : defaultOutput(file, format)await Bun.write(output, result.data as Uint8Array)console.log(ok(`Converted ${file} → ${output}`))diff --git a/packages/cli/src/commands/eval.ts b/packages/cli/src/commands/eval.tsindex bccf2dc0c..4e6ba0b8f 100644--- a/packages/cli/src/commands/eval.ts+++ b/packages/cli/src/commands/eval.ts@@ -1,10 +1,10 @@import { defineCommand } from 'citty'-import { FigmaAPI } from '@open-pencil/core'+import { FigmaAPI } from '@open-pencil/core/figma-api'-import { isAppMode, requireFile, rpc } from '../app-client'-import { printError } from '../format'-import { loadDocument } from '../headless'+import { isAppMode, requireFile, rpc } from '#cli/app-client'+import { printError } from '#cli/format'+import { loadDocument } from '#cli/headless'function printResult(value: unknown, json: boolean) {if (json || !process.stdout.isTTY) {@@ -89,7 +89,7 @@ export default defineCommand({}if (args.write || args.output) {- const { BUILTIN_IO_FORMATS, IORegistry } = await import('@open-pencil/core')+ const { BUILTIN_IO_FORMATS, IORegistry } = await import('@open-pencil/core/io')const io = new IORegistry(BUILTIN_IO_FORMATS)const outPath = args.output ? args.output : fileconst result = await io.writeDocument('fig', graph)diff --git a/packages/cli/src/commands/export.ts b/packages/cli/src/commands/export.tsindex dd317c3a1..b4a217d5c 100644--- a/packages/cli/src/commands/export.ts+++ b/packages/cli/src/commands/export.ts@@ -2,13 +2,13 @@ import { basename, extname, resolve } from 'node:path'import { defineCommand } from 'citty'-import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core'+import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'-import { isAppMode, requireFile, rpc } from '../app-client'-import { ok, printError } from '../format'-import { loadDocument } from '../headless'+import { isAppMode, requireFile, rpc } from '#cli/app-client'+import { ok, printError } from '#cli/format'+import { loadDocument } from '#cli/headless'-import type { RasterExportFormat } from '@open-pencil/core'+import type { RasterExportFormat } from '@open-pencil/core/io'const io = new IORegistry(BUILTIN_IO_FORMATS)const RASTER_FORMATS = ['PNG', 'JPG', 'WEBP']diff --git a/packages/cli/src/commands/find.ts b/packages/cli/src/commands/find.tsindex edfe9082d..e263957d1 100644--- a/packages/cli/src/commands/find.ts+++ b/packages/cli/src/commands/find.ts@@ -1,27 +1,9 @@import { defineCommand } from 'citty'-import { executeRpcCommand } from '@open-pencil/core'+import { loadRpcData } from '#cli/rpc-data'+import { printNodeResults } from '#cli/format'-import { isAppMode, requireFile, rpc } from '../app-client'-import { printNodeResults } from '../format'-import { loadDocument } from '../headless'--import type { FindNodeResult } from '@open-pencil/core'--async function getData(- file: string | undefined,- args: { name?: string; type?: string; page?: string; limit?: string }-): Promise<FindNodeResult[]> {- const rpcArgs = {- name: args.name,- type: args.type,- page: args.page,- limit: args.limit ? Number(args.limit) : undefined- }- if (isAppMode(file)) return rpc<FindNodeResult[]>('find', rpcArgs)- const graph = await loadDocument(requireFile(file))- return executeRpcCommand(graph, 'find', rpcArgs) as FindNodeResult[]-}+import type { FindNodeResult } from '@open-pencil/core/rpc'export default defineCommand({meta: { description: 'Find nodes by name or type' },@@ -38,7 +20,12 @@ export default defineCommand({json: { type: 'boolean', description: 'Output as JSON' }},async run({ args }) {- const results = await getData(args.file, args)+ const results = await loadRpcData<FindNodeResult[]>(args.file, 'find', {+ name: args.name,+ type: args.type,+ page: args.page,+ limit: args.limit ? Number(args.limit) : undefined+ })if (args.json) {console.log(JSON.stringify(results, null, 2))diff --git a/packages/cli/src/commands/formats.ts b/packages/cli/src/commands/formats.tsindex a6fb374ba..e0635989f 100644--- a/packages/cli/src/commands/formats.ts+++ b/packages/cli/src/commands/formats.ts@@ -1,8 +1,8 @@import { defineCommand } from 'citty'-import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core'+import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'-import { bold, fmtList, kv } from '../format'+import { bold, fmtList, kv } from '#cli/format'const io = new IORegistry(BUILTIN_IO_FORMATS)diff --git a/packages/cli/src/commands/info.ts b/packages/cli/src/commands/info.tsindex b676a2400..fe4992a40 100644--- a/packages/cli/src/commands/info.ts+++ b/packages/cli/src/commands/info.ts@@ -1,18 +1,9 @@import { defineCommand } from 'citty'-import { executeRpcCommand } from '@open-pencil/core'+import { loadRpcData } from '#cli/rpc-data'+import { bold, fmtHistogram, fmtSummary, kv } from '#cli/format'-import { isAppMode, requireFile, rpc } from '../app-client'-import { bold, fmtHistogram, fmtSummary, kv } from '../format'-import { loadDocument } from '../headless'--import type { InfoResult } from '@open-pencil/core'--async function getData(file?: string): Promise<InfoResult> {- if (isAppMode(file)) return rpc<InfoResult>('info')- const graph = await loadDocument(requireFile(file))- return executeRpcCommand(graph, 'info', undefined) as InfoResult-}+import type { InfoResult } from '@open-pencil/core/rpc'export default defineCommand({meta: { description: 'Show document info (pages, node counts, fonts)' },@@ -25,7 +16,7 @@ export default defineCommand({json: { type: 'boolean', description: 'Output as JSON' }},async run({ args }) {- const data = await getData(args.file)+ const data = await loadRpcData<InfoResult>(args.file, 'info')if (args.json) {console.log(JSON.stringify(data, null, 2))diff --git a/packages/cli/src/commands/lint.ts b/packages/cli/src/commands/lint.tsindex fcc4cce0e..48f43be58 100644--- a/packages/cli/src/commands/lint.ts+++ b/packages/cli/src/commands/lint.ts@@ -1,9 +1,9 @@import { defineCommand } from 'citty'-import { allRules, createLinter, presets, type LintMessage } from '@open-pencil/core'+import { allRules, createLinter, presets, type LintMessage } from '@open-pencil/core/lint'-import { bold, dim, fail, fmtList, ok } from '../format'-import { loadDocument } from '../headless'+import { bold, dim, fail, fmtList, ok } from '#cli/format'+import { loadDocument } from '#cli/headless'function formatSeverity(severity: LintMessage['severity']) {if (severity === 'error') return fail('error')diff --git a/packages/cli/src/commands/node.ts b/packages/cli/src/commands/node.tsindex 538cb51b8..e4f171a58 100644--- a/packages/cli/src/commands/node.ts+++ b/packages/cli/src/commands/node.ts@@ -1,21 +1,11 @@import { defineCommand } from 'citty'-import { executeRpcCommand, colorToHex } from '@open-pencil/core'+import { colorToHex } from '@open-pencil/core/color'+import { loadRpcData } from '#cli/rpc-data'+import { fmtNode, printError, formatType } from '#cli/format'-import { isAppMode, requireFile, rpc } from '../app-client'-import { fmtNode, printError, formatType } from '../format'-import { loadDocument } from '../headless'--import type { Color, NodeResult } from '@open-pencil/core'--async function getData(- file: string | undefined,- id: string-): Promise<NodeResult | { error: string }> {- if (isAppMode(file)) return rpc<NodeResult>('node', { id })- const graph = await loadDocument(requireFile(file))- return executeRpcCommand(graph, 'node', { id }) as NodeResult | { error: string }-}+import type { NodeResult } from '@open-pencil/core/rpc'+import type { Color } from '@open-pencil/core/types'export default defineCommand({meta: { description: 'Show detailed node properties by ID' },@@ -29,7 +19,7 @@ export default defineCommand({json: { type: 'boolean', description: 'Output as JSON' }},async run({ args }) {- const data = await getData(args.file, args.id)+ const data = await loadRpcData<NodeResult | { error: string }>(args.file, 'node', { id: args.id })if ('error' in data) {printError(data.error)diff --git a/packages/cli/src/commands/pages.ts b/packages/cli/src/commands/pages.tsindex e457c3a46..57860e0c4 100644--- a/packages/cli/src/commands/pages.ts+++ b/packages/cli/src/commands/pages.ts@@ -1,18 +1,9 @@import { defineCommand } from 'citty'-import { executeRpcCommand } from '@open-pencil/core'+import { loadRpcData } from '#cli/rpc-data'+import { bold, fmtList, entity } from '#cli/format'-import { isAppMode, requireFile, rpc } from '../app-client'-import { bold, fmtList, entity } from '../format'-import { loadDocument } from '../headless'--import type { PageItem } from '@open-pencil/core'--async function getData(file?: string): Promise<PageItem[]> {- if (isAppMode(file)) return rpc<PageItem[]>('pages')- const graph = await loadDocument(requireFile(file))- return executeRpcCommand(graph, 'pages', undefined) as PageItem[]-}+import type { PageItem } from '@open-pencil/core/rpc'export default defineCommand({meta: { description: 'List pages in a document' },@@ -25,7 +16,7 @@ export default defineCommand({json: { type: 'boolean', description: 'Output as JSON' }},async run({ args }) {- const pages = await getData(args.file)+ const pages = await loadRpcData<PageItem[]>(args.file, 'pages')if (args.json) {console.log(JSON.stringify(pages, null, 2))diff --git a/packages/cli/src/commands/query.ts b/packages/cli/src/commands/query.tsindex ee578ec9b..3316c0036 100644--- a/packages/cli/src/commands/query.ts+++ b/packages/cli/src/commands/query.ts@@ -1,26 +1,9 @@import { defineCommand } from 'citty'-import { executeRpcCommand } from '@open-pencil/core'+import { loadRpcData } from '#cli/rpc-data'+import { printNodeResults, printError } from '#cli/format'-import { isAppMode, requireFile, rpc } from '../app-client'-import { printNodeResults, printError } from '../format'-import { loadDocument } from '../headless'--import type { QueryNodeResult } from '@open-pencil/core'--async function getData(- file: string | undefined,- args: { selector: string; page?: string; limit?: string }-): Promise<QueryNodeResult[] | { error: string }> {- const rpcArgs = {- selector: args.selector,- page: args.page,- limit: args.limit ? Number(args.limit) : undefined- }- if (isAppMode(file)) return rpc<QueryNodeResult[]>('query', rpcArgs)- const graph = await loadDocument(requireFile(file))- return (await executeRpcCommand(graph, 'query', rpcArgs)) as QueryNodeResult[] | { error: string }-}+import type { QueryNodeResult } from '@open-pencil/core/rpc'export default defineCommand({meta: {@@ -42,10 +25,10 @@ export default defineCommand({json: { type: 'boolean', description: 'Output as JSON' }},async run({ args }) {- const results = await getData(args.file, {+ const results = await loadRpcData<QueryNodeResult[] | { error: string }>(args.file, 'query', {selector: args.selector,page: args.page,- limit: args.limit+ limit: args.limit ? Number(args.limit) : undefined})if ('error' in results) {diff --git a/packages/cli/src/commands/selection.ts b/packages/cli/src/commands/selection.tsindex a80d88d69..a6c345010 100644--- a/packages/cli/src/commands/selection.ts+++ b/packages/cli/src/commands/selection.ts@@ -1,7 +1,7 @@import { defineCommand } from 'citty'-import { rpc } from '../app-client'-import { bold, entity, fmtList, formatType, printError } from '../format'+import { rpc } from '#cli/app-client'+import { bold, entity, fmtList, formatType, printError } from '#cli/format'interface SelectionNode {id: stringdiff --git a/packages/cli/src/commands/tree.ts b/packages/cli/src/commands/tree.tsindex 957010893..89ee47ebc 100644--- a/packages/cli/src/commands/tree.ts+++ b/packages/cli/src/commands/tree.ts@@ -1,12 +1,9 @@import { defineCommand } from 'citty'-import { executeRpcCommand } from '@open-pencil/core'+import { loadRpcData } from '#cli/rpc-data'+import { fmtTree, printError, entity, formatType } from '#cli/format'-import { isAppMode, requireFile, rpc } from '../app-client'-import { fmtTree, printError, entity, formatType } from '../format'-import { loadDocument } from '../headless'--import type { TreeResult, TreeNodeResult } from '@open-pencil/core'+import type { TreeNodeResult, TreeResult } from '@open-pencil/core/rpc'import type { TreeNode } from 'agentfmt'function toAgentfmtTree(node: TreeNodeResult, maxDepth: number, depth = 0): TreeNode {@@ -19,16 +16,6 @@ function toAgentfmtTree(node: TreeNodeResult, maxDepth: number, depth = 0): Treereturn treeNode}-async function getData(- file: string | undefined,- args: { page?: string; depth?: string }-): Promise<TreeResult | { error: string }> {- const rpcArgs = { page: args.page, depth: args.depth ? Number(args.depth) : undefined }- if (isAppMode(file)) return rpc<TreeResult>('tree', rpcArgs)- const graph = await loadDocument(requireFile(file))- return executeRpcCommand(graph, 'tree', rpcArgs) as TreeResult | { error: string }-}-export default defineCommand({meta: { description: 'Print the node tree' },args: {@@ -42,7 +29,10 @@ export default defineCommand({json: { type: 'boolean', description: 'Output as JSON' }},async run({ args }) {- const data = await getData(args.file, args)+ const data = await loadRpcData<TreeResult | { error: string }>(args.file, 'tree', {+ page: args.page,+ depth: args.depth ? Number(args.depth) : undefined+ })const maxDepth = args.depth ? Number(args.depth) : Infinityif ('error' in data) {diff --git a/packages/cli/src/commands/variables.ts b/packages/cli/src/commands/variables.tsindex c50b30936..c5d564014 100644--- a/packages/cli/src/commands/variables.ts+++ b/packages/cli/src/commands/variables.ts@@ -1,22 +1,9 @@import { defineCommand } from 'citty'-import { executeRpcCommand } from '@open-pencil/core'+import { loadRpcData } from '#cli/rpc-data'+import { bold, entity, fmtList, fmtSummary } from '#cli/format'-import { isAppMode, requireFile, rpc } from '../app-client'-import { bold, entity, fmtList, fmtSummary } from '../format'-import { loadDocument } from '../headless'--import type { VariablesResult } from '@open-pencil/core'--async function getData(- file: string | undefined,- args: { collection?: string; type?: string }-): Promise<VariablesResult> {- const rpcArgs = { collection: args.collection, type: args.type }- if (isAppMode(file)) return rpc<VariablesResult>('variables', rpcArgs)- const graph = await loadDocument(requireFile(file))- return executeRpcCommand(graph, 'variables', rpcArgs) as VariablesResult-}+import type { VariablesResult } from '@open-pencil/core/rpc'export default defineCommand({meta: { description: 'List design variables and collections' },@@ -31,7 +18,10 @@ export default defineCommand({json: { type: 'boolean', description: 'Output as JSON' }},async run({ args }) {- const data = await getData(args.file, args)+ const data = await loadRpcData<VariablesResult>(args.file, 'variables', {+ collection: args.collection,+ type: args.type+ })if (data.totalVariables === 0) {console.log('No variables found.')diff --git a/packages/cli/src/format.ts b/packages/cli/src/format.tsindex c33a0f8ae..ec41f65fb 100644--- a/packages/cli/src/format.ts+++ b/packages/cli/src/format.ts@@ -14,7 +14,7 @@ import {summary as fmtSummary} from 'agentfmt'-import type { SceneNode, SceneGraph } from '@open-pencil/core'+import type { SceneGraph, SceneNode } from '@open-pencil/core/scene-graph'import type { TreeNode, ListItem, NodeData } from 'agentfmt'export {diff --git a/packages/cli/src/headless.ts b/packages/cli/src/headless.tsindex 0c93c6ba3..d74083ff3 100644--- a/packages/cli/src/headless.ts+++ b/packages/cli/src/headless.ts@@ -1,10 +1,7 @@-import {- BUILTIN_IO_FORMATS,- IORegistry,- computeAllLayouts,- initCanvasKit,- type SceneGraph-} from '@open-pencil/core'+import { BUILTIN_IO_FORMATS, IORegistry, initCanvasKit } from '@open-pencil/core/io'+import { computeAllLayouts } from '@open-pencil/core/layout'++import type { SceneGraph } from '@open-pencil/core/scene-graph'export { initCanvasKit }diff --git a/packages/cli/src/rpc-data.ts b/packages/cli/src/rpc-data.tsnew file mode 100644index 000000000..f4dd510cd--- /dev/null+++ b/packages/cli/src/rpc-data.ts@@ -0,0 +1,14 @@+import { executeRpcCommand } from '@open-pencil/core/rpc'++import { isAppMode, requireFile, rpc } from '#cli/app-client'+import { loadDocument } from '#cli/headless'++export async function loadRpcData<Result>(+ file: string | undefined,+ command: string,+ args?: unknown+): Promise<Result> {+ if (isAppMode(file)) return rpc<Result>(command, args)+ const graph = await loadDocument(requireFile(file))+ return executeRpcCommand(graph, command, args) as Result+}diff --git a/packages/cli/tsconfig.json b/packages/cli/tsconfig.jsonindex 32f2561ce..09a27eaca 100644--- a/packages/cli/tsconfig.json+++ b/packages/cli/tsconfig.json@@ -6,6 +6,9 @@"strict": true,"skipLibCheck": true,"declaration": true,+ "paths": {+ "#cli/*": ["./src/*"]+ },"outDir": "dist","rootDir": "src"},diff --git a/packages/core/package.json b/packages/core/package.jsonindex bfb1f1d0f..b1f29de0a 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -3,6 +3,9 @@"version": "0.11.8","license": "MIT","type": "module",+ "imports": {+ "#core/*": "./src/*"+ },"sideEffects": false,"exports": {".": {@@ -115,6 +118,16 @@"bun": "./src/constants.ts","default": "./src/constants.ts"},+ "./random": {+ "types": "./src/random.ts",+ "bun": "./src/random.ts",+ "default": "./src/random.ts"+ },+ "./xpath": {+ "types": "./src/xpath.ts",+ "bun": "./src/xpath.ts",+ "default": "./src/xpath.ts"+ },"./types": {"types": "./src/types.ts","bun": "./src/types.ts",@@ -266,6 +279,16 @@"import": "./dist/constants.js","default": "./dist/constants.js"},+ "./random": {+ "types": "./dist/random.d.ts",+ "import": "./dist/random.js",+ "default": "./dist/random.js"+ },+ "./xpath": {+ "types": "./dist/xpath.d.ts",+ "import": "./dist/xpath.js",+ "default": "./dist/xpath.js"+ },"./types": {"types": "./dist/types.d.ts","import": "./dist/types.js",diff --git a/packages/core/src/canvas/ai-overlays.ts b/packages/core/src/canvas/ai-overlays.tsindex 70a52d016..29f665955 100644--- a/packages/core/src/canvas/ai-overlays.ts+++ b/packages/core/src/canvas/ai-overlays.ts@@ -3,10 +3,10 @@ import {AI_DONE_COLOR,AI_PULSE_PERIOD_MS,AI_DONE_DURATION_MS-} from '../constants'+} from '#core/constants'import { drawNodeHighlightRect } from './highlight-rect'-import type { SceneGraph } from '../scene-graph'+import type { SceneGraph } from '#core/scene-graph'import type { SkiaRenderer } from './renderer'import type { Canvas } from 'canvaskit-wasm'diff --git a/packages/core/src/canvas/coordinate.ts b/packages/core/src/canvas/coordinate.tsindex fef1622c4..954efc208 100644--- a/packages/core/src/canvas/coordinate.ts+++ b/packages/core/src/canvas/coordinate.ts@@ -1,6 +1,7 @@-import Matrix, { type Mat3 } from '@open-pencil/core/canvas/matrix'+import Matrix, { type Mat3 } from './matrix'-import type { SceneGraph, SceneNode, Vector } from '@open-pencil/core'+import type { SceneGraph, SceneNode } from '#core/scene-graph'+import type { Vector } from '#core/types'export function getWorldMatrix(node: SceneNode, graph: SceneGraph): Mat3 {const chain: SceneNode[] = []diff --git a/packages/core/src/canvas/effects.ts b/packages/core/src/canvas/effects.tsindex ca400e72a..e866d589d 100644--- a/packages/core/src/canvas/effects.ts+++ b/packages/core/src/canvas/effects.ts@@ -1,4 +1,4 @@-import type { SceneNode } from '../scene-graph'+import type { SceneNode } from '#core/scene-graph'import type { SkiaRenderer } from './renderer'import type { Canvas, ImageFilter, MaskFilter } from 'canvaskit-wasm'@@ -62,3 +62,172 @@ export function applyClippedBlur(canvas.restore()canvas.restore()}++export function nodeHasRadius(node: SceneNode): boolean {+ return (+ node.cornerRadius > 0 ||+ (node.independentCorners &&+ (node.topLeftRadius > 0 ||+ node.topRightRadius > 0 ||+ node.bottomRightRadius > 0 ||+ node.bottomLeftRadius > 0))+ )+}++function drawShapeDropShadow(+ r: SkiaRenderer,+ canvas: Canvas,+ node: SceneNode,+ effect: SceneNode['effects'][number],+ hasRadius: boolean,+ shadowShapeChild?: SceneNode | null+): void {+ const sp = effect.spread+ const shapeNode = shadowShapeChild ?? node+ const shapeHasRadius = shadowShapeChild ? nodeHasRadius(shadowShapeChild) : hasRadius+ const strokeShadow =+ !shadowShapeChild && !node.fills.some((fill) => fill.visible) && node.strokeGeometry.length > 0+ ? r.getStrokeGeometry(node)+ : null++ r.auxFill.setColor(r.color4f(effect.color.r, effect.color.g, effect.color.b, effect.color.a))+ r.auxFill.setMaskFilter(r.getCachedMaskBlur(effect.radius / 2))+ r.auxFill.setImageFilter(null)+ canvas.save()+ canvas.translate(+ effect.offset.x + (shadowShapeChild?.x ?? 0),+ effect.offset.y + (shadowShapeChild?.y ?? 0)+ )+ if (strokeShadow) {+ for (const path of strokeShadow) canvas.drawPath(path, r.auxFill)+ } else if (shapeNode.type === 'ELLIPSE') {+ canvas.drawOval(r.ltrb(-sp, -sp, shapeNode.width + sp, shapeNode.height + sp), r.auxFill)+ } else if (shapeHasRadius) {+ canvas.drawRRect(r.makeRRectWithSpread(shapeNode, sp), r.auxFill)+ } else {+ canvas.drawRect(r.ltrb(-sp, -sp, shapeNode.width + sp, shapeNode.height + sp), r.auxFill)+ }+ canvas.restore()+ r.auxFill.setMaskFilter(null)+}++function renderDropShadow(+ r: SkiaRenderer,+ canvas: Canvas,+ node: SceneNode,+ effect: SceneNode['effects'][number],+ hasRadius: boolean,+ shadowShapeChild?: SceneNode | null+): void {+ if (node.type !== 'TEXT') {+ drawShapeDropShadow(r, canvas, node, effect, hasRadius, shadowShapeChild)+ return+ }++ const shadowColor = r.ck.Color4f(effect.color.r, effect.color.g, effect.color.b, effect.color.a)+ const dropFilter = r.getCachedDropShadow(+ effect.offset.x,+ effect.offset.y,+ effect.radius / 2,+ shadowColor+ )+ r.effectLayerPaint.setImageFilter(dropFilter)+ canvas.saveLayer(r.effectLayerPaint)+ r.renderText(canvas, node)+ canvas.restore()+}++export function renderEffects(+ r: SkiaRenderer,+ canvas: Canvas,+ node: SceneNode,+ rect: Float32Array,+ hasRadius: boolean,+ pass: 'behind' | 'front',+ shadowShapeChild?: SceneNode | null+): void {+ for (const effect of node.effects) {+ if (!effect.visible) continue++ if (pass === 'behind' && effect.type === 'DROP_SHADOW') {+ renderDropShadow(r, canvas, node, effect, hasRadius, shadowShapeChild)+ }++ if (pass === 'behind' && effect.type === 'BACKGROUND_BLUR') {+ r.applyClippedBlur(canvas, node, rect, hasRadius, effect.radius / 2)+ }++ if (pass === 'front' && effect.type === 'INNER_SHADOW') {+ if (node.type === 'TEXT') {+ r.effectLayerPaint.setImageFilter(r.getCachedDecalBlur(effect.radius))+ r.effectLayerPaint.setColorFilter(+ r.ck.ColorFilter.MakeBlend(+ r.ck.Color4f(effect.color.r, effect.color.g, effect.color.b, effect.color.a),+ r.ck.BlendMode.SrcIn+ )+ )+ canvas.saveLayer(r.effectLayerPaint)+ canvas.save()+ canvas.translate(effect.offset.x, effect.offset.y)+ r.renderText(canvas, node)+ canvas.restore()+ canvas.restore()+ r.effectLayerPaint.setColorFilter(null)+ continue+ }+ const sp = effect.spread+ r.auxFill.setColor(+ r.ck.Color4f(effect.color.r, effect.color.g, effect.color.b, effect.color.a)+ )+ r.auxFill.setImageFilter(r.getCachedDecalBlur(effect.radius))++ canvas.save()+ r.clipNodeShape(canvas, node, rect, hasRadius)++ const expand = effect.radius * 2+ const big = r.ck.LTRBRect(+ -expand + effect.offset.x,+ -expand + effect.offset.y,+ node.width + expand + effect.offset.x,+ node.height + expand + effect.offset.y+ )+ const bigPath = new r.ck.Path()+ bigPath.addRect(big)+ if (node.type === 'ELLIPSE') {+ const innerPath = new r.ck.Path()+ const offsetRect = r.ck.LTRBRect(+ effect.offset.x + sp,+ effect.offset.y + sp,+ node.width + effect.offset.x - sp,+ node.height + effect.offset.y - sp+ )+ innerPath.addOval(offsetRect)+ bigPath.op(innerPath, r.ck.PathOp.Difference)+ innerPath.delete()+ } else if (hasRadius) {+ const innerPath = new r.ck.Path()+ innerPath.addRRect(+ r.makeRRectWithOffset(node, effect.offset.x + sp, effect.offset.y + sp, -sp)+ )+ bigPath.op(innerPath, r.ck.PathOp.Difference)+ innerPath.delete()+ } else {+ const innerPath = new r.ck.Path()+ innerPath.addRect(+ r.ck.LTRBRect(+ effect.offset.x + sp,+ effect.offset.y + sp,+ node.width + effect.offset.x - sp,+ node.height + effect.offset.y - sp+ )+ )+ bigPath.op(innerPath, r.ck.PathOp.Difference)+ innerPath.delete()+ }+ canvas.drawPath(bigPath, r.auxFill)+ bigPath.delete()+ canvas.restore()+ r.auxFill.setImageFilter(null)+ }+ }+}diff --git a/packages/core/src/canvas/fills.ts b/packages/core/src/canvas/fills.tsindex 080c7742c..0a83f3896 100644--- a/packages/core/src/canvas/fills.ts+++ b/packages/core/src/canvas/fills.ts@@ -1,4 +1,4 @@-import type { SceneNode, SceneGraph, Fill } from '../scene-graph'+import type { SceneNode, SceneGraph, Fill } from '#core/scene-graph'import type { SkiaRenderer } from './renderer'import type { Canvas, Paint } from 'canvaskit-wasm'@@ -78,6 +78,25 @@ export function applyFill(return false}+function makeGradientLocalMatrix(+ r: SkiaRenderer,+ width: number,+ height: number,+ transform: NonNullable<Fill['gradientTransform']>+) {+ return r.ck.Matrix.multiply(r.ck.Matrix.scaled(width, height), [+ transform.m00,+ transform.m01,+ transform.m02,+ transform.m10,+ transform.m11,+ transform.m12,+ 0,+ 0,+ 1+ ])+}+export function applyGradientFill(r: SkiaRenderer,fill: Fill,@@ -125,17 +144,7 @@ export function applyGradientFill(// Figma's gradientTransform maps gradient space (center 0.5,0.5, radius 0.5)// to the node's normalized [0,1] coordinate space. The full local matrix// converts to pixel coordinates: scale(w, h) * gradientTransform.- const localMatrix = r.ck.Matrix.multiply(r.ck.Matrix.scaled(w, h), [- t.m00,- t.m01,- t.m02,- t.m10,- t.m11,- t.m12,- 0,- 0,- 1- ])+ const localMatrix = makeGradientLocalMatrix(r, w, h, t)const shader = r.ck.Shader.MakeRadialGradient([0.5, 0.5],0.5,@@ -146,17 +155,7 @@ export function applyGradientFill()r.fillPaint.setShader(shader)} else if (fill.type === 'GRADIENT_ANGULAR') {- const localMatrix = r.ck.Matrix.multiply(r.ck.Matrix.scaled(w, h), [- t.m00,- t.m01,- t.m02,- t.m10,- t.m11,- t.m12,- 0,- 0,- 1- ])+ const localMatrix = makeGradientLocalMatrix(r, w, h, t)const shader = r.ck.Shader.MakeSweepGradient(0.5,0.5,diff --git a/packages/core/src/canvas/highlight-rect.ts b/packages/core/src/canvas/highlight-rect.tsindex c9d3baab9..9d6300f3a 100644--- a/packages/core/src/canvas/highlight-rect.ts+++ b/packages/core/src/canvas/highlight-rect.ts@@ -1,6 +1,6 @@-import { FLASH_PADDING, FLASH_STROKE_WIDTH, FLASH_RADIUS } from '../constants'+import { FLASH_PADDING, FLASH_STROKE_WIDTH, FLASH_RADIUS } from '#core/constants'-import type { SceneGraph } from '../scene-graph'+import type { SceneGraph } from '#core/scene-graph'import type { SkiaRenderer } from './renderer'import type { Canvas, Paint } from 'canvaskit-wasm'diff --git a/packages/core/src/canvas/index.ts b/packages/core/src/canvas/index.tsindex 7e18dca36..91a825fda 100644--- a/packages/core/src/canvas/index.ts+++ b/packages/core/src/canvas/index.ts@@ -1,2 +1,2 @@export { SkiaRenderer, type RenderOverlays } from './renderer'-export { getAbsolutePositionFull } from './coordinate'+export { getAbsolutePositionFull, getAbsoluteRotation, getWorldHandles } from './coordinate'diff --git a/packages/core/src/canvas/label-cache.ts b/packages/core/src/canvas/labels/cache.tssimilarity index 73%rename from packages/core/src/canvas/label-cache.tsrename to packages/core/src/canvas/labels/cache.tsindex 17548e46a..8c78b5c93 100644--- a/packages/core/src/canvas/label-cache.ts+++ b/packages/core/src/canvas/labels/cache.ts@@ -1,4 +1,4 @@-import type { SceneGraph, SceneNode } from '../scene-graph'+import type { SceneGraph, SceneNode } from '#core/scene-graph'export interface CachedSection {nodeId: string@@ -27,6 +27,25 @@ function isInViewport(absX: number, absY: number, w: number, h: number, vp: Viewreturn absX + w >= vp.x && absY + h >= vp.y && absX <= vp.x + vp.w && absY <= vp.y + vp.h}+function collectVisibleLabels<+ T extends { nodeId: string; absX: number; absY: number },+ U extends object+>(+ graph: SceneGraph,+ viewport: Viewport,+ cachedItems: T[],+ metadata: (cached: T) => U+): Array<{ node: SceneNode; absX: number; absY: number } & U> {+ const result: Array<{ node: SceneNode; absX: number; absY: number } & U> = []+ for (const cached of cachedItems) {+ const node = graph.getNode(cached.nodeId)+ if (!node || !isInViewport(cached.absX, cached.absY, node.width, node.height, viewport))+ continue+ result.push({ node, absX: cached.absX, absY: cached.absY, ...metadata(cached) })+ }+ return result+}+export class LabelCache {private sections: CachedSection[] = []private components: CachedComponent[] = []@@ -51,33 +70,18 @@ export class LabelCache {graph: SceneGraph,viewport: Viewport): Array<{ node: SceneNode; absX: number; absY: number; nested: boolean }> {- const result: Array<{ node: SceneNode; absX: number; absY: number; nested: boolean }> = []- for (const cached of this.sections) {- const node = graph.getNode(cached.nodeId)- if (!node || !isInViewport(cached.absX, cached.absY, node.width, node.height, viewport))- continue- result.push({ node, absX: cached.absX, absY: cached.absY, nested: cached.nested })- }- return result+ return collectVisibleLabels(graph, viewport, this.sections, (cached) => ({+ nested: cached.nested+ }))}getComponents(graph: SceneGraph,viewport: Viewport): Array<{ node: SceneNode; absX: number; absY: number; inside: boolean }> {- const result: Array<{ node: SceneNode; absX: number; absY: number; inside: boolean }> = []- for (const cached of this.components) {- const node = graph.getNode(cached.nodeId)- if (!node || !isInViewport(cached.absX, cached.absY, node.width, node.height, viewport))- continue- result.push({- node,- absX: cached.absX,- absY: cached.absY,- inside: cached.parentType === 'COMPONENT_SET'- })- }- return result+ return collectVisibleLabels(graph, viewport, this.components, (cached) => ({+ inside: cached.parentType === 'COMPONENT_SET'+ }))}private rebuild(graph: SceneGraph, pageId: string | null): void {diff --git a/packages/core/src/canvas/labels.ts b/packages/core/src/canvas/labels/draw.tssimilarity index 97%rename from packages/core/src/canvas/labels.tsrename to packages/core/src/canvas/labels/draw.tsindex 7a460faea..e791993a0 100644--- a/packages/core/src/canvas/labels.ts+++ b/packages/core/src/canvas/labels/draw.ts@@ -7,10 +7,10 @@ import {COMPONENT_LABEL_GAP,COMPONENT_LABEL_ICON_SIZE,COMPONENT_LABEL_ICON_GAP-} from '../constants'+} from '#core/constants'-import type { SceneNode, SceneGraph } from '../scene-graph'-import type { SkiaRenderer } from './renderer'+import type { SceneNode, SceneGraph } from '#core/scene-graph'+import type { SkiaRenderer } from '#core/canvas/renderer'import type { Canvas, Font } from 'canvaskit-wasm'export function drawSectionTitles(r: SkiaRenderer, canvas: Canvas, graph: SceneGraph): void {diff --git a/packages/core/src/canvas/labels/hit-test.ts b/packages/core/src/canvas/labels/hit-test.tsnew file mode 100644index 000000000..a313910e4--- /dev/null+++ b/packages/core/src/canvas/labels/hit-test.ts@@ -0,0 +1,153 @@+import {+ COMPONENT_LABEL_FONT_SIZE,+ COMPONENT_LABEL_GAP,+ COMPONENT_LABEL_ICON_GAP,+ COMPONENT_LABEL_ICON_SIZE,+ LABEL_FONT_SIZE,+ LABEL_OFFSET_Y,+ SECTION_TITLE_GAP,+ SECTION_TITLE_HEIGHT,+ SECTION_TITLE_PADDING_X+} from '#core/constants'++import type { SceneGraph, SceneNode } from '#core/scene-graph'+import type { Vector } from '#core/types'+import type { Font } from 'canvaskit-wasm'++function measureGlyphWidth(font: Font, text: string): number {+ const glyphIds = font.getGlyphIDs(text)+ const widths = font.getGlyphWidths(glyphIds)+ let total = 0+ for (const w of widths) total += w+ return total+}++function rotatePoint(x: number, y: number, rotation: number): Vector {+ if (rotation === 0) return { x, y }+ const rad = (-rotation * Math.PI) / 180+ const cos = Math.cos(rad)+ const sin = Math.sin(rad)+ return { x: x * cos - y * sin, y: x * sin + y * cos }+}++function hitInRect(px: number, py: number, x: number, y: number, w: number, h: number): boolean {+ return px >= x && px <= x + w && py >= y && py <= y + h+}++type LabelWalkerCallback = (+ child: SceneNode,+ parent: SceneNode,+ absX: number,+ absY: number,+ insideSection: boolean+) => SceneNode | null | undefined++function walkLabelTree(+ graph: SceneGraph,+ pageId: string,+ callback: LabelWalkerCallback+): SceneNode | null {+ let result: SceneNode | null = null++ const walk = (parentId: string, ox: number, oy: number, insideSection: boolean) => {+ const parent = graph.getNode(parentId)+ if (!parent) return+ for (let i = parent.childIds.length - 1; i >= 0; i--) {+ if (result) return+ const child = graph.getNode(parent.childIds[i])+ if (!child || !child.visible) continue+ const ax = ox + child.x+ const ay = oy + child.y+ const hit = callback(child, parent, ax, ay, insideSection)+ if (hit) {+ result = hit+ return+ }+ if (child.type === 'SECTION') {+ walk(child.id, ax, ay, true)+ } else if (child.childIds.length > 0) {+ walk(child.id, ax, ay, insideSection)+ }+ }+ }++ const pageNode = graph.getNode(pageId)+ if (pageNode) walk(pageNode.id, 0, 0, false)+ return result+}++export function hitTestSectionTitle(+ graph: SceneGraph,+ canvasX: number,+ canvasY: number,+ zoom: number,+ pageId: string,+ font: Font | null+): SceneNode | null {+ if (!font) return null++ return walkLabelTree(graph, pageId, (child, _parent, ax, ay, insideSection) => {+ if (child.type !== 'SECTION') return undefined++ const textW = measureGlyphWidth(font, child.name)+ const pillW = Math.min(textW + SECTION_TITLE_PADDING_X * 2, child.width * zoom) / zoom+ const pillH = SECTION_TITLE_HEIGHT / zoom+ const gap = SECTION_TITLE_GAP / zoom+ const hit = rotatePoint(canvasX - ax, canvasY - ay, child.rotation)+ const pillY = insideSection ? gap : -pillH - gap++ return hitInRect(hit.x, hit.y, 0, pillY, pillW, pillH) ? child : undefined+ })+}++export function hitTestComponentLabel(+ graph: SceneGraph,+ canvasX: number,+ canvasY: number,+ zoom: number,+ pageId: string,+ font: Font | null+): SceneNode | null {+ if (!font) return null++ const LABEL_TYPES = new Set(['COMPONENT', 'COMPONENT_SET'])++ return walkLabelTree(graph, pageId, (child, parent, ax, ay) => {+ if (!LABEL_TYPES.has(child.type)) return undefined++ const textW = measureGlyphWidth(font, child.name)+ const labelW = (COMPONENT_LABEL_ICON_SIZE + COMPONENT_LABEL_ICON_GAP + textW) / zoom+ const labelH = COMPONENT_LABEL_FONT_SIZE / zoom+ const gap = COMPONENT_LABEL_GAP / zoom+ const labelY = parent.type === 'COMPONENT_SET' ? ay + gap : ay - labelH - gap++ return hitInRect(canvasX, canvasY, ax, labelY, labelW, labelH) ? child : undefined+ })+}++export function hitTestFrameTitle(+ graph: SceneGraph,+ canvasX: number,+ canvasY: number,+ zoom: number,+ selectedIds: Set<string>,+ font: Font | null+): SceneNode | null {+ if (!font || selectedIds.size !== 1) return null++ const id = [...selectedIds][0]+ const node = graph.getNode(id)+ if (node?.type !== 'FRAME') return null++ const parent = node.parentId ? graph.getNode(node.parentId) : null+ const isTopLevel = !parent || parent.type === 'CANVAS' || parent.type === 'SECTION'+ if (!isTopLevel) return null++ const abs = graph.getAbsolutePosition(id)+ const labelW = measureGlyphWidth(font, node.name) / zoom+ const labelH = LABEL_FONT_SIZE / zoom+ const hit = rotatePoint(canvasX - abs.x, canvasY - abs.y, node.rotation)+ const labelY = -LABEL_OFFSET_Y / zoom - labelH++ return hitInRect(hit.x, hit.y, 0, labelY, labelW, labelH) ? node : null+}diff --git a/packages/core/src/canvas/matrix.ts b/packages/core/src/canvas/matrix.tsindex 118aa5ba2..4b4a3a286 100644--- a/packages/core/src/canvas/matrix.ts+++ b/packages/core/src/canvas/matrix.ts@@ -1,4 +1,4 @@-import type { Vector } from '@open-pencil/core'+import type { Vector } from '#core/types'export type Mat3 = number[]diff --git a/packages/core/src/canvas/node-edit-overlay.ts b/packages/core/src/canvas/node-edit-overlay.tsindex c851755eb..43318255b 100644--- a/packages/core/src/canvas/node-edit-overlay.ts+++ b/packages/core/src/canvas/node-edit-overlay.ts@@ -1,9 +1,9 @@-import { PEN_HANDLE_RADIUS, PEN_VERTEX_RADIUS } from '../constants'-import { vectorNetworkToPath } from '../vector'-import { computeAccurateBounds } from '../vector/bezier'+import { PEN_HANDLE_RADIUS, PEN_VERTEX_RADIUS } from '#core/constants'+import { vectorNetworkToPath } from '#core/vector'+import { computeAccurateBounds } from '#core/vector/bezier'-import type { VectorVertex, VectorSegment, VectorRegion, SceneGraph } from '../scene-graph'-import type { Vector } from '../types'+import type { VectorVertex, VectorSegment, VectorRegion, SceneGraph } from '#core/scene-graph'+import type { Vector } from '#core/types'import type { SkiaRenderer, RenderOverlays } from './renderer'import type { Canvas, Paint } from 'canvaskit-wasm'diff --git a/packages/core/src/canvas/overlays/feedback.ts b/packages/core/src/canvas/overlays/feedback.tsnew file mode 100644index 000000000..e3de5bd0e--- /dev/null+++ b/packages/core/src/canvas/overlays/feedback.ts@@ -0,0 +1,109 @@+import { drawNodeHighlightRect } from '#core/canvas/highlight-rect'+import {+ FLASH_ATTACK_MS,+ FLASH_COLOR,+ FLASH_HOLD_MS,+ FLASH_OVERSHOOT,+ FLASH_RELEASE_MS,+ LAYOUT_INDICATOR_STROKE,+ MARQUEE_FILL_ALPHA+} from '#core/constants'++import type { RenderOverlays, SkiaRenderer } from '#core/canvas/renderer'+import type { SceneGraph } from '#core/scene-graph'+import type { SnapGuide } from '#core/scene-graph/snap'+import type { Rect } from '#core/types'+import type { Canvas } from 'canvaskit-wasm'++export function drawSnapGuides(r: SkiaRenderer, canvas: Canvas, guides?: SnapGuide[]): void {+ if (!guides || guides.length === 0) return++ for (const guide of guides) {+ if (guide.axis === 'x') {+ const x = guide.position * r.zoom + r.panX+ const y1 = guide.from * r.zoom + r.panY+ const y2 = guide.to * r.zoom + r.panY+ canvas.drawLine(x, y1, x, y2, r.snapPaint)+ } else {+ const y = guide.position * r.zoom + r.panY+ const x1 = guide.from * r.zoom + r.panX+ const x2 = guide.to * r.zoom + r.panX+ canvas.drawLine(x1, y, x2, y, r.snapPaint)+ }+ }+}++export function drawMarquee(r: SkiaRenderer, canvas: Canvas, marquee?: Rect | null): void {+ if (!marquee || marquee.width <= 0 || marquee.height <= 0) return++ const x1 = marquee.x * r.zoom + r.panX+ const y1 = marquee.y * r.zoom + r.panY+ const x2 = (marquee.x + marquee.width) * r.zoom + r.panX+ const y2 = (marquee.y + marquee.height) * r.zoom + r.panY+ const rect = r.ck.LTRBRect(x1, y1, x2, y2)++ r.auxFill.setColor(r.selColor(MARQUEE_FILL_ALPHA))+ canvas.drawRect(rect, r.auxFill)+ canvas.drawRect(rect, r.selectionPaint)+}++export function drawFlashes(r: SkiaRenderer, canvas: Canvas, graph: SceneGraph): void {+ if (r._flashes.length === 0) return++ const now = performance.now()+ const totalMs = FLASH_ATTACK_MS + FLASH_HOLD_MS + FLASH_RELEASE_MS++ for (let i = r._flashes.length - 1; i >= 0; i--) {+ const flash = r._flashes[i]+ const elapsed = now - flash.startTime+ if (elapsed > totalMs) {+ r._flashes.splice(i, 1)+ continue+ }++ let opacity: number+ let extraPad: number++ if (elapsed < FLASH_ATTACK_MS) {+ const t = elapsed / FLASH_ATTACK_MS+ const ease = t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2+ opacity = ease+ extraPad = (1 - ease) * FLASH_OVERSHOOT+ } else if (elapsed < FLASH_ATTACK_MS + FLASH_HOLD_MS) {+ opacity = 1+ extraPad = 0+ } else {+ const t = (elapsed - FLASH_ATTACK_MS - FLASH_HOLD_MS) / FLASH_RELEASE_MS+ opacity = 1 - t * t+ extraPad = 0+ }++ if (!drawNodeHighlightRect(r, canvas, graph, flash.nodeId, FLASH_COLOR, opacity, extraPad)) {+ r._flashes.splice(i, 1)+ }+ }+}++export function drawLayoutInsertIndicator(+ r: SkiaRenderer,+ canvas: Canvas,+ indicator?: RenderOverlays['layoutInsertIndicator']+): void {+ if (!indicator) return++ r.auxStroke.setStrokeWidth(LAYOUT_INDICATOR_STROKE)+ r.auxStroke.setColor(r.selColor())+ r.auxStroke.setPathEffect(null)++ if (indicator.direction === 'HORIZONTAL') {+ const y = indicator.y * r.zoom + r.panY+ const x1 = indicator.x * r.zoom + r.panX+ const x2 = (indicator.x + indicator.length) * r.zoom + r.panX+ canvas.drawLine(x1, y, x2, y, r.auxStroke)+ } else {+ const x = indicator.x * r.zoom + r.panX+ const y1 = indicator.y * r.zoom + r.panY+ const y2 = (indicator.y + indicator.length) * r.zoom + r.panY+ canvas.drawLine(x, y1, x, y2, r.auxStroke)+ }+}diff --git a/packages/core/src/canvas/overlays/index.ts b/packages/core/src/canvas/overlays/index.tsnew file mode 100644index 000000000..298e956b0--- /dev/null+++ b/packages/core/src/canvas/overlays/index.ts@@ -0,0 +1,16 @@+export {+ drawEnteredContainer,+ drawGroupBounds,+ drawHandle,+ drawHoverHighlight,+ drawNodeOutline,+ drawNodeSelection,+ drawParentFrameOutlines,+ drawSelection,+ getRotatedCorners+} from './selection'+export { drawFlashes, drawLayoutInsertIndicator, drawMarquee, drawSnapGuides } from './feedback'+export { drawTextEditOverlay } from './text-edit'+export { drawSelectionLabels } from '#core/canvas/selection-labels'+export { drawPenOverlay, drawRemoteCursors } from '#core/canvas/pen-overlay'+export { drawNodeEditOverlay } from '#core/canvas/node-edit-overlay'diff --git a/packages/core/src/canvas/overlays.ts b/packages/core/src/canvas/overlays/selection.tssimilarity index 57%rename from packages/core/src/canvas/overlays.tsrename to packages/core/src/canvas/overlays/selection.tsindex 51a273d3f..b212ee7de 100644--- a/packages/core/src/canvas/overlays.ts+++ b/packages/core/src/canvas/overlays/selection.ts@@ -1,28 +1,11 @@-import { getWorldMatrix } from '@open-pencil/core/canvas/coordinate'--import Matrix from '../canvas/matrix'-import {- FLASH_ATTACK_MS,- FLASH_COLOR,- FLASH_HOLD_MS,- FLASH_OVERSHOOT,- FLASH_RELEASE_MS,- HANDLE_HALF_SIZE,- LAYOUT_INDICATOR_STROKE,- MARQUEE_FILL_ALPHA,- SELECTION_DASH_ALPHA,- TEXT_CARET_COLOR,- TEXT_CARET_WIDTH,- TEXT_SELECTION_COLOR-} from '../constants'-import { rotatedCorners } from '../geometry'-import { drawNodeHighlightRect } from './highlight-rect'--import type { SceneGraph, SceneNode } from '../scene-graph'-import type { TextEditor } from '../text/editor'-import type { Rect, Vector } from '../types'-import type { RenderOverlays, SkiaRenderer } from './renderer'-import type { SnapGuide } from '@open-pencil/core'+import { getWorldMatrix } from '#core/canvas/coordinate'+import Matrix from '#core/canvas/matrix'+import { HANDLE_HALF_SIZE, SELECTION_DASH_ALPHA } from '#core/constants'+import { rotatedCorners } from '#core/geometry'++import type { RenderOverlays, SkiaRenderer } from '#core/canvas/renderer'+import type { SceneGraph, SceneNode } from '#core/scene-graph'+import type { Vector } from '#core/types'import type { Canvas } from 'canvaskit-wasm'function getNodeTransformChain(graph: SceneGraph, node: SceneNode): SceneNode[] {@@ -125,9 +108,9 @@ export function drawSelection(r.selectionPaint.setColor(useComponentColor ? r.compColor() : r.selColor())r.selectionPaint.setStrokeWidth(1 / r.zoom)- const _rotation =+ const rotation =overlays.rotationPreview?.nodeId === id ? overlays.rotationPreview.angle : node.rotation- r.drawNodeSelection(canvas, node, _rotation, graph)+ r.drawNodeSelection(canvas, node, rotation, graph)r.drawSelectionLabels(canvas, graph, selectedIds, overlays)r.selectionPaint.setColor(r.selColor())@@ -168,13 +151,7 @@ function withNodeBounds(graph: SceneGraph,draw: (x1: number, y1: number, x2: number, y2: number) => void): void {- const worldMatrix = getWorldMatrix(- {- ...node,- rotation- },- graph- )+ const worldMatrix = getWorldMatrix({ ...node, rotation }, graph)canvas.save()canvas.translate(r.panX, r.panY)@@ -185,34 +162,52 @@ function withNodeBounds(canvas.restore()}-export function drawNodeSelection(+function drawBoundsHandles(+ r: SkiaRenderer,+ canvas: Canvas,+ minX: number,+ minY: number,+ maxX: number,+ maxY: number+): void {+ r.drawHandle(canvas, minX, minY)+ r.drawHandle(canvas, maxX, minY)+ r.drawHandle(canvas, minX, maxY)+ r.drawHandle(canvas, maxX, maxY)+ const midX = (minX + maxX) / 2+ const midY = (minY + maxY) / 2+ const rotationHandleY = minY - 24 / r.zoom+ canvas.drawLine(midX, minY, midX, rotationHandleY, r.selectionPaint)+ r.drawHandle(canvas, midX, rotationHandleY)+ r.drawHandle(canvas, midX, minY)+ r.drawHandle(canvas, midX, maxY)+ r.drawHandle(canvas, minX, midY)+ r.drawHandle(canvas, maxX, midY)+}++function drawSelectionRect(r: SkiaRenderer,canvas: Canvas,node: SceneNode,rotation: number,- graph: SceneGraph+ graph: SceneGraph,+ afterDraw?: (x1: number, y1: number, x2: number, y2: number) => void): void {withNodeBounds(r, canvas, node, rotation, graph, (x1, y1, x2, y2) => {canvas.drawRect(r.ck.LTRBRect(x1, y1, x2, y2), r.selectionPaint)+ afterDraw?.(x1, y1, x2, y2)+ })+}- const drawHandle = (x: number, y: number) => {- r.drawHandle(canvas, x, y)- }-- // corners- drawHandle(x1, y1)- drawHandle(x2, y1)- drawHandle(x1, y2)- drawHandle(x2, y2)-- // center- const mx = (x1 + x2) / 2- const my = (y1 + y2) / 2-- drawHandle(mx, y1)- drawHandle(mx, y2)- drawHandle(x1, my)- drawHandle(x2, my)+export function drawNodeSelection(+ r: SkiaRenderer,+ canvas: Canvas,+ node: SceneNode,+ rotation: number,+ graph: SceneGraph+): void {+ drawSelectionRect(r, canvas, node, rotation, graph, (x1, y1, x2, y2) => {+ drawBoundsHandles(r, canvas, x1, y1, x2, y2)})}@@ -237,9 +232,7 @@ export function drawParentFrameOutlines(drawn.add(parent.id)const world = getWorldMatrix(parent, graph)-const view = Matrix.multiply(Matrix.translated(r.panX, r.panY), Matrix.scaled(r.zoom, r.zoom))-const m = Matrix.multiply(view, world)const pts = Matrix.mapPoints(m, [@@ -271,9 +264,7 @@ export function drawNodeOutline(rotation: number,graph: SceneGraph): void {- withNodeBounds(r, canvas, node, rotation, graph, (x1, y1, x2, y2) => {- canvas.drawRect(r.ck.LTRBRect(x1, y1, x2, y2), r.selectionPaint)- })+ drawSelectionRect(r, canvas, node, rotation, graph)}export function drawGroupBounds(@@ -315,16 +306,7 @@ export function drawGroupBounds(canvas.drawRect(r.ck.LTRBRect(minX, minY, maxX, maxY), r.auxStroke)- r.drawHandle(canvas, minX, minY)- r.drawHandle(canvas, maxX, minY)- r.drawHandle(canvas, minX, maxY)- r.drawHandle(canvas, maxX, maxY)- const gmx = (minX + maxX) / 2- const gmy = (minY + maxY) / 2- r.drawHandle(canvas, gmx, minY)- r.drawHandle(canvas, gmx, maxY)- r.drawHandle(canvas, minX, gmy)- r.drawHandle(canvas, maxX, gmy)+ drawBoundsHandles(r, canvas, minX, minY, maxX, maxY)}export function getRotatedCorners(r: SkiaRenderer, n: SceneNode, abs: Vector): Vector[] {@@ -335,8 +317,6 @@ export function getRotatedCorners(r: SkiaRenderer, n: SceneNode, abs: Vector): Vreturn rotatedCorners(cx, cy, hw, hh, n.rotation)}-export { drawSelectionLabels } from './selection-labels'-export function drawHandle(r: SkiaRenderer, canvas: Canvas, x: number, y: number): void {r.auxFill.setColor(r.ck.WHITE)const rect = r.ck.LTRBRect(@@ -348,140 +328,3 @@ export function drawHandle(r: SkiaRenderer, canvas: Canvas, x: number, y: numbercanvas.drawRect(rect, r.auxFill)canvas.drawRect(rect, r.selectionPaint)}--export function drawSnapGuides(r: SkiaRenderer, canvas: Canvas, guides?: SnapGuide[]): void {- if (!guides || guides.length === 0) return-- for (const guide of guides) {- if (guide.axis === 'x') {- const x = guide.position * r.zoom + r.panX- const y1 = guide.from * r.zoom + r.panY- const y2 = guide.to * r.zoom + r.panY- canvas.drawLine(x, y1, x, y2, r.snapPaint)- } else {- const y = guide.position * r.zoom + r.panY- const x1 = guide.from * r.zoom + r.panX- const x2 = guide.to * r.zoom + r.panX- canvas.drawLine(x1, y, x2, y, r.snapPaint)- }- }-}--export function drawMarquee(r: SkiaRenderer, canvas: Canvas, marquee?: Rect | null): void {- if (!marquee || marquee.width <= 0 || marquee.height <= 0) return-- const x1 = marquee.x * r.zoom + r.panX- const y1 = marquee.y * r.zoom + r.panY- const x2 = (marquee.x + marquee.width) * r.zoom + r.panX- const y2 = (marquee.y + marquee.height) * r.zoom + r.panY- const rect = r.ck.LTRBRect(x1, y1, x2, y2)-- r.auxFill.setColor(r.selColor(MARQUEE_FILL_ALPHA))- canvas.drawRect(rect, r.auxFill)- canvas.drawRect(rect, r.selectionPaint)-}--export function drawFlashes(r: SkiaRenderer, canvas: Canvas, graph: SceneGraph): void {- if (r._flashes.length === 0) return-- const now = performance.now()- const totalMs = FLASH_ATTACK_MS + FLASH_HOLD_MS + FLASH_RELEASE_MS-- for (let i = r._flashes.length - 1; i >= 0; i--) {- const flash = r._flashes[i]- const elapsed = now - flash.startTime- if (elapsed > totalMs) {- r._flashes.splice(i, 1)- continue- }-- let opacity: number- let extraPad: number-- if (elapsed < FLASH_ATTACK_MS) {- const t = elapsed / FLASH_ATTACK_MS- const ease = t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2- opacity = ease- extraPad = (1 - ease) * FLASH_OVERSHOOT- } else if (elapsed < FLASH_ATTACK_MS + FLASH_HOLD_MS) {- opacity = 1- extraPad = 0- } else {- const t = (elapsed - FLASH_ATTACK_MS - FLASH_HOLD_MS) / FLASH_RELEASE_MS- opacity = 1 - t * t- extraPad = 0- }-- if (!drawNodeHighlightRect(r, canvas, graph, flash.nodeId, FLASH_COLOR, opacity, extraPad)) {- r._flashes.splice(i, 1)- }- }-}--export function drawLayoutInsertIndicator(- r: SkiaRenderer,- canvas: Canvas,- indicator?: RenderOverlays['layoutInsertIndicator']-): void {- if (!indicator) return-- r.auxStroke.setStrokeWidth(LAYOUT_INDICATOR_STROKE)- r.auxStroke.setColor(r.selColor())- r.auxStroke.setPathEffect(null)-- if (indicator.direction === 'HORIZONTAL') {- const y = indicator.y * r.zoom + r.panY- const x1 = indicator.x * r.zoom + r.panX- const x2 = (indicator.x + indicator.length) * r.zoom + r.panX- canvas.drawLine(x1, y, x2, y, r.auxStroke)- } else {- const x = indicator.x * r.zoom + r.panX- const y1 = indicator.y * r.zoom + r.panY- const y2 = (indicator.y + indicator.length) * r.zoom + r.panY- canvas.drawLine(x, y1, x, y2, r.auxStroke)- }-}--export function drawTextEditOverlay(- r: SkiaRenderer,- canvas: Canvas,- node: SceneNode,- editor: TextEditor-): void {- r.auxStroke.setStrokeWidth(1 / r.zoom)- r.auxStroke.setColor(r.selColor())- r.auxStroke.setPathEffect(null)- canvas.drawRect(r.ck.LTRBRect(0, 0, node.width, node.height), r.auxStroke)-- const selRects = editor.getSelectionRects()- if (selRects.length > 0) {- r.auxFill.setColor(- r.ck.Color4f(- TEXT_SELECTION_COLOR.r,- TEXT_SELECTION_COLOR.g,- TEXT_SELECTION_COLOR.b,- TEXT_SELECTION_COLOR.a- )- )- for (const sel of selRects) {- canvas.drawRect(r.ck.LTRBRect(sel.x, sel.y, sel.x + sel.width, sel.y + sel.height), r.auxFill)- }- }-- if (editor.caretVisible && !editor.hasSelection()) {- const caret = editor.getCaretRect()- if (caret) {- r.auxFill.setColor(- r.ck.Color4f(TEXT_CARET_COLOR.r, TEXT_CARET_COLOR.g, TEXT_CARET_COLOR.b, TEXT_CARET_COLOR.a)- )- const w = TEXT_CARET_WIDTH / r.zoom- canvas.drawRect(- r.ck.LTRBRect(caret.x - w / 2, caret.y0, caret.x + w / 2, caret.y1),- r.auxFill- )- }- }-}--export { drawPenOverlay, drawRemoteCursors } from './pen-overlay'-export { drawNodeEditOverlay } from './node-edit-overlay'diff --git a/packages/core/src/canvas/overlays/text-edit.ts b/packages/core/src/canvas/overlays/text-edit.tsnew file mode 100644index 000000000..8c6c9b5d1--- /dev/null+++ b/packages/core/src/canvas/overlays/text-edit.ts@@ -0,0 +1,47 @@+import { TEXT_CARET_COLOR, TEXT_CARET_WIDTH, TEXT_SELECTION_COLOR } from '#core/constants'++import type { SkiaRenderer } from '#core/canvas/renderer'+import type { SceneNode } from '#core/scene-graph'+import type { TextEditor } from '#core/text/editor'+import type { Canvas } from 'canvaskit-wasm'++export function drawTextEditOverlay(+ r: SkiaRenderer,+ canvas: Canvas,+ node: SceneNode,+ editor: TextEditor+): void {+ r.auxStroke.setStrokeWidth(1 / r.zoom)+ r.auxStroke.setColor(r.selColor())+ r.auxStroke.setPathEffect(null)+ canvas.drawRect(r.ck.LTRBRect(0, 0, node.width, node.height), r.auxStroke)++ const selRects = editor.getSelectionRects()+ if (selRects.length > 0) {+ r.auxFill.setColor(+ r.ck.Color4f(+ TEXT_SELECTION_COLOR.r,+ TEXT_SELECTION_COLOR.g,+ TEXT_SELECTION_COLOR.b,+ TEXT_SELECTION_COLOR.a+ )+ )+ for (const sel of selRects) {+ canvas.drawRect(r.ck.LTRBRect(sel.x, sel.y, sel.x + sel.width, sel.y + sel.height), r.auxFill)+ }+ }++ if (editor.caretVisible && !editor.hasSelection()) {+ const caret = editor.getCaretRect()+ if (caret) {+ r.auxFill.setColor(+ r.ck.Color4f(TEXT_CARET_COLOR.r, TEXT_CARET_COLOR.g, TEXT_CARET_COLOR.b, TEXT_CARET_COLOR.a)+ )+ const w = TEXT_CARET_WIDTH / r.zoom+ canvas.drawRect(+ r.ck.LTRBRect(caret.x - w / 2, caret.y0, caret.x + w / 2, caret.y1),+ r.auxFill+ )+ }+ }+}diff --git a/packages/core/src/canvas/pen-overlay.ts b/packages/core/src/canvas/pen-overlay.tsindex a0669a030..5f0b5a4e9 100644--- a/packages/core/src/canvas/pen-overlay.ts+++ b/packages/core/src/canvas/pen-overlay.ts@@ -1,7 +1,7 @@-import { PEN_HANDLE_RADIUS, PEN_VERTEX_RADIUS, PEN_CLOSE_RADIUS_BOOST } from '../constants'+import { PEN_HANDLE_RADIUS, PEN_VERTEX_RADIUS, PEN_CLOSE_RADIUS_BOOST } from '#core/constants'-import type { SceneGraph } from '../scene-graph'-import type { Vector } from '../types'+import type { SceneGraph } from '#core/scene-graph'+import type { Vector } from '#core/types'import type { SkiaRenderer, RenderOverlays } from './renderer'import type { Canvas, Paint } from 'canvaskit-wasm'diff --git a/packages/core/src/canvas/renderer.ts b/packages/core/src/canvas/renderer.tsindex 39bd5e4aa..59fc434be 100644--- a/packages/core/src/canvas/renderer.ts+++ b/packages/core/src/canvas/renderer.ts@@ -1,130 +1,39 @@-import {- resolveNodeFillColor,- resolveNodeStrokeColor,- type ResolvedRenderColor-} from '../color/management'-/* eslint-disable max-lines -- SkiaRenderer class; text, pen-overlay, fills, scene already extracted */+import type { ResolvedRenderColor } from '#core/color/management'+/* eslint-disable max-lines -- SkiaRenderer facade owns CanvasKit state and delegates domain drawing */import {SELECTION_COLOR,COMPONENT_COLOR,- SNAP_COLOR,CANVAS_BG_COLOR,- PEN_PATH_STROKE_WIDTH,- PARENT_OUTLINE_ALPHA,- PARENT_OUTLINE_DASH,DEFAULT_FONT_SIZE,- LABEL_FONT_SIZE,- LABEL_OFFSET_Y,- SIZE_FONT_SIZE,- SECTION_TITLE_FONT_SIZE,- SECTION_TITLE_HEIGHT,- SECTION_TITLE_PADDING_X,- SECTION_TITLE_GAP,COMPONENT_SET_DASH,COMPONENT_SET_DASH_GAP,COMPONENT_SET_BORDER_WIDTH,- COMPONENT_LABEL_FONT_SIZE,- COMPONENT_LABEL_GAP,- COMPONENT_LABEL_ICON_SIZE,- COMPONENT_LABEL_ICON_GAP,- RULER_BG_COLOR,- RULER_TICK_COLOR,- RULER_TEXT_COLOR,- DEFAULT_FONT_FAMILY,IS_BROWSER-} from '../constants'-import { computeDescendantVisualBounds } from '../geometry'-import { RenderProfiler } from '../profiler'-import { drawAiOverlays as drawAiOverlaysFn } from './ai-overlays'-import {- getCachedDropShadow as getCachedDropShadowFn,- getCachedBlur as getCachedBlurFn,- getCachedDecalBlur as getCachedDecalBlurFn,- getCachedMaskBlur as getCachedMaskBlurFn,- applyClippedBlur as applyClippedBlurFn-} from './effects'-import {- drawNodeFill as drawNodeFillFn,- applyFill as applyFillFn,- applyGradientFill as applyGradientFillFn,- applyImageFill as applyImageFillFn,- drawArc as drawArcFn-} from './fills'-import { LabelCache } from './label-cache'-import {- drawSectionTitles as drawSectionTitlesFn,- drawComponentLabels as drawComponentLabelsFn-} from './labels'-import { drawNodeEditOverlay as drawNodeEditOverlayFn } from './node-edit-overlay'-import {- drawHoverHighlight as drawHoverHighlightFn,- drawEnteredContainer as drawEnteredContainerFn,- drawSelection as drawSelectionFn,- drawNodeSelection as drawNodeSelectionFn,- drawSelectionLabels as drawSelectionLabelsFn,- drawParentFrameOutlines as drawParentFrameOutlinesFn,- drawNodeOutline as drawNodeOutlineFn,- drawGroupBounds as drawGroupBoundsFn,- getRotatedCorners as getRotatedCornersFn,- drawHandle as drawHandleFn,- drawSnapGuides as drawSnapGuidesFn,- drawMarquee as drawMarqueeFn,- drawFlashes as drawFlashesFn,- drawLayoutInsertIndicator as drawLayoutInsertIndicatorFn,- drawTextEditOverlay as drawTextEditOverlayFn-} from './overlays'-import {- drawPenOverlay as drawPenOverlayFn,- drawRemoteCursors as drawRemoteCursorsFn-} from './pen-overlay'-import { drawRulers as drawRulersFn } from './rulers'-import {- renderNode as renderNodeFn,- renderSection as renderSectionFn,- renderComponentSet as renderComponentSetFn,- renderShape as renderShapeFn,- renderShapeUncached as renderShapeUncachedFn,- renderEffects as renderEffectsFn,- renderText as renderTextFn-} from './scene'-import {- makeNodeShapePath as makeNodeShapePathFn,- makePolygonPath as makePolygonPathFn,- makeRRect as makeRRectFn,- makeRRectWithSpread as makeRRectWithSpreadFn,- makeRRectWithOffset as makeRRectWithOffsetFn,- clipNodeShape as clipNodeShapeFn,- getVectorPaths as getVectorPathsFn,- getFillGeometry as getFillGeometryFn,- getStrokeGeometry as getStrokeGeometryFn-} from './shapes'-import {- drawNodeStroke as drawNodeStrokeFn,- drawStrokeWithAlign as drawStrokeWithAlignFn,- drawRRectStrokeWithAlign as drawRRectStrokeWithAlignFn,- drawIndividualSideStrokes as drawIndividualSideStrokesFn,- strokeNodeShape as strokeNodeShapeFn-} from './strokes'-import {- measureTextNode as measureTextNodeFn,- isNodeFontLoaded as isNodeFontLoadedFn,- buildTextPicture as buildTextPictureFn,- buildParagraph as buildParagraphFn-} from './text'--import type { EditorState } from '../editor/types'+} from '#core/constants'+import * as LabelHitTest from './labels/hit-test'+import { RenderProfiler } from '#core/profiler'+import { LabelCache } from './labels/cache'+import { installRendererDomainMethods } from './renderer/methods'+import * as RendererFonts from './renderer/fonts'+import { destroyRenderer } from './renderer/lifecycle'+import * as RendererState from './renderer/state'+import * as RenderColors from './renderer/colors'+import { initializeRendererPaints } from './renderer/paints'+import * as RenderPipeline from './renderer/pipeline'+import * as RenderText from './text'++import type { EditorState } from '#core/editor/types'import type {SceneNode,SceneGraph,Fill,- Stroke,- VectorVertex,- VectorRegion-} from '../scene-graph'-import type { SnapGuide } from '../scene-graph/snap'-import type { TextEditor } from '../text/editor'-import type { Color, Rect, Vector } from '../types'-import type { NodeEditOverlayState } from './node-edit-overlay'+ Stroke+} from '#core/scene-graph'+import type { SnapGuide } from '#core/scene-graph/snap'+import type { TextEditor } from '#core/text/editor'+import type { Color, Rect, Vector } from '#core/types'+export type { RenderOverlays } from './renderer/types'+import type { RenderOverlays } from './renderer/types'import type {Image as CKImage,Path,@@ -141,72 +50,18 @@ import type {Paragraph} from 'canvaskit-wasm'-export interface RenderOverlays {- hoveredNodeId?: string | null- enteredContainerId?: string | null- editingTextId?: string | null- textEditor?: TextEditor | null- marquee?: Rect | null- snapGuides?: SnapGuide[]- rotationPreview?: { nodeId: string; angle: number } | null- dropTargetId?: string | null- layoutInsertIndicator?: {- x: number- y: number- length: number- direction: 'HORIZONTAL' | 'VERTICAL'- } | null- penState?: {- vertices: Vector[]- segments: Array<{- start: number- end: number- tangentStart: Vector- tangentEnd: Vector- }>- dragTangent: Vector | null- oppositeDragTangent?: Vector | null- closingToFirst: boolean- pendingClose?: boolean- cursorX?: number- cursorY?: number- } | null- nodeEditState?: {- nodeId: string- vertices: VectorVertex[]- segments: Array<{- start: number- end: number- tangentStart: Vector- tangentEnd: Vector- }>- regions: VectorRegion[]- selectedVertexIndices: Set<number>- /** Set of selected handles as "segIdx:tangentField" strings */- selectedHandles?: Set<string>- hoveredHandleInfo?: { segmentIndex: number; tangentField: 'tangentStart' | 'tangentEnd' } | null- } | null- remoteCursors?: Array<{- name: string- color: Color- x: number- y: number- selection?: string[]- }>-}-export class SkiaRenderer {ck: CanvasKitsurface: Surface- fillPaint: Paint- strokePaint: Paint- selectionPaint: Paint- parentOutlinePaint: Paint- snapPaint: Paint- auxFill: Paint- auxStroke: Paint- opacityPaint: Paint- effectLayerPaint: Paint+ declare fillPaint: Paint+ declare strokePaint: Paint+ declare selectionPaint: Paint+ declare parentOutlinePaint: Paint+ declare snapPaint: Paint+ declare auxFill: Paint+ declare auxStroke: Paint+ declare opacityPaint: Paint+ declare effectLayerPaint: PaintimageFilterCache = new Map<string, ImageFilter | null>()maskFilterCache = new Map<number, MaskFilter | null>()_tmpColor = new Float32Array(4)@@ -230,17 +85,17 @@ export class SkiaRenderer {readonly labelCache = new LabelCache()readonly profiler: RenderProfiler- rulerBgPaint: Paint- rulerTickPaint: Paint- rulerTextPaint: Paint- rulerHlPaint: Paint- rulerBadgePaint: Paint- rulerLabelPaint: Paint- penPathPaint: Paint- penLiveStrokePaint: Paint- penHandlePaint: Paint- penVertexFill: Paint- penVertexStroke: Paint+ declare rulerBgPaint: Paint+ declare rulerTickPaint: Paint+ declare rulerTextPaint: Paint+ declare rulerHlPaint: Paint+ declare rulerBadgePaint: Paint+ declare rulerLabelPaint: Paint+ declare penPathPaint: Paint+ declare penLiveStrokePaint: Paint+ declare penHandlePaint: Paint+ declare penVertexFill: Paint+ declare penVertexStroke: PaintpanX = 0panY = 0@@ -265,6 +120,111 @@ export class SkiaRenderer {readonly COMPONENT_SET_DASH = COMPONENT_SET_DASHreadonly COMPONENT_SET_DASH_GAP = COMPONENT_SET_DASH_GAP++ declare drawHoverHighlight: (+ canvas: Canvas,+ graph: SceneGraph,+ hoveredNodeId?: string | null+ ) => void+ declare drawEnteredContainer: (+ canvas: Canvas,+ graph: SceneGraph,+ enteredContainerId?: string | null+ ) => void+ declare drawSelection: (+ canvas: Canvas,+ graph: SceneGraph,+ selectedIds: Set<string>,+ overlays: RenderOverlays+ ) => void+ declare drawNodeSelection: (canvas: Canvas, node: SceneNode, rotation: number, graph: SceneGraph) => void+ declare drawSelectionLabels: (+ canvas: Canvas,+ graph: SceneGraph,+ selectedIds: Set<string>,+ overlays?: RenderOverlays+ ) => void+ declare drawParentFrameOutlines: (canvas: Canvas, graph: SceneGraph, selectedIds: Set<string>) => void+ declare drawNodeOutline: (canvas: Canvas, node: SceneNode, rotation: number, graph: SceneGraph) => void+ declare drawGroupBounds: (canvas: Canvas, nodes: SceneNode[], graph: SceneGraph) => void+ declare getRotatedCorners: (node: SceneNode, abs: Vector) => Vector[]+ declare drawHandle: (canvas: Canvas, x: number, y: number) => void+ declare drawSnapGuides: (canvas: Canvas, guides?: SnapGuide[]) => void+ declare drawMarquee: (canvas: Canvas, marquee?: Rect | null) => void+ declare drawFlashes: (canvas: Canvas, graph: SceneGraph) => void+ declare drawLayoutInsertIndicator: (+ canvas: Canvas,+ indicator?: RenderOverlays['layoutInsertIndicator']+ ) => void+ declare drawTextEditOverlay: (canvas: Canvas, node: SceneNode, editor: TextEditor) => void+ declare drawNodeEditOverlay: (+ canvas: Canvas,+ graph: SceneGraph,+ editState?: RenderOverlays['nodeEditState']+ ) => void+ declare drawPenOverlay: (canvas: Canvas, penState: RenderOverlays['penState']) => void+ declare drawRemoteCursors: (+ canvas: Canvas,+ graph: SceneGraph,+ cursors?: RenderOverlays['remoteCursors']+ ) => void+ declare drawRulers: (canvas: Canvas, graph: SceneGraph, selectedIds: Set<string>) => void+ declare drawSectionTitles: (canvas: Canvas, graph: SceneGraph) => void+ declare drawComponentLabels: (canvas: Canvas, graph: SceneGraph) => void+ declare renderNode: (canvas: Canvas, graph: SceneGraph, nodeId: string, overlays: RenderOverlays) => void+ declare renderSection: (canvas: Canvas, node: SceneNode, graph: SceneGraph) => void+ declare renderComponentSet: (canvas: Canvas, node: SceneNode, graph: SceneGraph) => void+ declare renderShape: (canvas: Canvas, node: SceneNode, graph: SceneGraph) => void+ declare renderShapeUncached: (canvas: Canvas, node: SceneNode, graph: SceneGraph) => void+ declare renderEffects: (+ canvas: Canvas,+ node: SceneNode,+ rect: Float32Array,+ hasRadius: boolean,+ pass: 'behind' | 'front',+ shadowShapeChild?: SceneNode | null+ ) => void+ declare renderText: (canvas: Canvas, node: SceneNode) => void+ declare drawNodeFill: (canvas: Canvas, node: SceneNode, rect: Float32Array, hasRadius: boolean) => void+ declare applyFill: (fill: Fill, node: SceneNode, graph: SceneGraph, fillIndex?: number) => boolean+ declare applyGradientFill: (fill: Fill, node: SceneNode, graph: SceneGraph) => void+ declare applyImageFill: (fill: Fill, node: SceneNode, graph: SceneGraph) => boolean+ declare drawArc: (canvas: Canvas, node: SceneNode, paint: Paint) => void+ declare drawNodeStroke: (canvas: Canvas, node: SceneNode, rect: Float32Array, hasRadius: boolean) => void+ declare drawStrokeWithAlign: (+ canvas: Canvas,+ node: SceneNode,+ rect: Float32Array,+ hasRadius: boolean,+ align: 'INSIDE' | 'CENTER' | 'OUTSIDE'+ ) => void+ declare drawRRectStrokeWithAlign: (canvas: Canvas, rrect: Float32Array, node: SceneNode, stroke: Stroke) => void+ declare drawIndividualSideStrokes: (+ canvas: Canvas,+ node: SceneNode,+ align: 'INSIDE' | 'CENTER' | 'OUTSIDE'+ ) => void+ declare strokeNodeShape: (canvas: Canvas, node: SceneNode, paint: Paint) => void+ declare makeNodeShapePath: (node: SceneNode, rect: Float32Array, hasRadius: boolean) => Path+ declare makePolygonPath: (node: SceneNode) => Path+ declare makeRRect: (node: SceneNode) => Float32Array+ declare makeRRectWithSpread: (node: SceneNode, spread: number) => Float32Array+ declare makeRRectWithOffset: (node: SceneNode, ox: number, oy: number, spread: number) => Float32Array+ declare clipNodeShape: (canvas: Canvas, node: SceneNode, rect: Float32Array, hasRadius: boolean) => void+ declare getVectorPaths: (node: SceneNode) => Path[] | null+ declare getFillGeometry: (node: SceneNode) => Path[] | null+ declare getStrokeGeometry: (node: SceneNode) => Path[] | null+ declare getCachedDropShadow: (dx: number, dy: number, sigma: number, color: Float32Array) => ImageFilter+ declare getCachedBlur: (sigma: number) => ImageFilter+ declare getCachedDecalBlur: (sigma: number) => ImageFilter+ declare getCachedMaskBlur: (sigma: number) => MaskFilter+ declare applyClippedBlur: (+ canvas: Canvas,+ node: SceneNode,+ rect: Float32Array,+ hasRadius: boolean,+ sigma: number+ ) => voidcolor4f(r: number, g: number, b: number, a: number): Float32Array {const c = this._tmpColorc[0] = r@@ -324,172 +284,23 @@ export class SkiaRenderer {this.ck = ckthis.surface = surfacethis.profiler = new RenderProfiler(ck, gl ?? null)-- this.fillPaint = new ck.Paint()- this.fillPaint.setStyle(ck.PaintStyle.Fill)- this.fillPaint.setAntiAlias(true)-- this.strokePaint = new ck.Paint()- this.strokePaint.setStyle(ck.PaintStyle.Stroke)- this.strokePaint.setAntiAlias(true)-- this.selectionPaint = new ck.Paint()- this.selectionPaint.setStyle(ck.PaintStyle.Stroke)- this.selectionPaint.setStrokeWidth(1)- this.selectionPaint.setColor(this.selColor())- this.selectionPaint.setAntiAlias(true)-- this.parentOutlinePaint = new ck.Paint()- this.parentOutlinePaint.setStyle(ck.PaintStyle.Stroke)- this.parentOutlinePaint.setStrokeWidth(1)- this.parentOutlinePaint.setColor(this.selColor(PARENT_OUTLINE_ALPHA))- this.parentOutlinePaint.setAntiAlias(true)- this.parentOutlinePaint.setPathEffect(- ck.PathEffect.MakeDash([PARENT_OUTLINE_DASH, PARENT_OUTLINE_DASH], 0)- )-- this.snapPaint = new ck.Paint()- this.snapPaint.setStyle(ck.PaintStyle.Stroke)- this.snapPaint.setStrokeWidth(1)- this.snapPaint.setColor(this.ck.Color4f(SNAP_COLOR.r, SNAP_COLOR.g, SNAP_COLOR.b, 1))- this.snapPaint.setAntiAlias(true)-- this.auxFill = new ck.Paint()- this.auxFill.setStyle(ck.PaintStyle.Fill)- this.auxFill.setAntiAlias(true)-- this.auxStroke = new ck.Paint()- this.auxStroke.setStyle(ck.PaintStyle.Stroke)- this.auxStroke.setAntiAlias(true)-- this.opacityPaint = new ck.Paint()- this.effectLayerPaint = new ck.Paint()-- this.textFont = new ck.Font(null, DEFAULT_FONT_SIZE)-- const bg = RULER_BG_COLOR- this.rulerBgPaint = new ck.Paint()- this.rulerBgPaint.setColor(ck.Color4f(bg.r, bg.g, bg.b, 1))-- this.rulerTickPaint = new ck.Paint()- this.rulerTickPaint.setColor(- ck.Color4f(RULER_TICK_COLOR.r, RULER_TICK_COLOR.g, RULER_TICK_COLOR.b, 1)- )- this.rulerTickPaint.setStrokeWidth(1)- this.rulerTickPaint.setAntiAlias(true)-- const tc = RULER_TEXT_COLOR- this.rulerTextPaint = new ck.Paint()- this.rulerTextPaint.setColor(ck.Color4f(tc.r, tc.g, tc.b, 1))- this.rulerTextPaint.setAntiAlias(true)-- this.rulerHlPaint = new ck.Paint()- this.rulerHlPaint.setAntiAlias(true)-- this.rulerBadgePaint = new ck.Paint()- this.rulerBadgePaint.setAntiAlias(true)-- this.rulerLabelPaint = new ck.Paint()- this.rulerLabelPaint.setColor(ck.Color4f(1, 1, 1, 1))- this.rulerLabelPaint.setAntiAlias(true)-- // Technical outline: 1px grey (same as node-edit techStroke)- this.penPathPaint = new ck.Paint()- this.penPathPaint.setStyle(ck.PaintStyle.Stroke)- this.penPathPaint.setStrokeWidth(1)- this.penPathPaint.setColor(ck.Color4f(0.698, 0.698, 0.698, 1))- this.penPathPaint.setAntiAlias(true)-- // Live stroke preview: 2px black (actual object style)- this.penLiveStrokePaint = new ck.Paint()- this.penLiveStrokePaint.setStyle(ck.PaintStyle.Stroke)- this.penLiveStrokePaint.setStrokeWidth(PEN_PATH_STROKE_WIDTH)- this.penLiveStrokePaint.setColor(ck.Color4f(0, 0, 0, 1))- this.penLiveStrokePaint.setAntiAlias(true)-- this.penHandlePaint = new ck.Paint()- this.penHandlePaint.setStyle(ck.PaintStyle.Stroke)- this.penHandlePaint.setStrokeWidth(1)- this.penHandlePaint.setColor(this.selColor(PARENT_OUTLINE_ALPHA))- this.penHandlePaint.setAntiAlias(true)-- this.penVertexFill = new ck.Paint()- this.penVertexFill.setStyle(ck.PaintStyle.Fill)- this.penVertexFill.setColor(ck.WHITE)- this.penVertexFill.setAntiAlias(true)-- // Vertex circle outline: 1px blue- this.penVertexStroke = new ck.Paint()- this.penVertexStroke.setStyle(ck.PaintStyle.Stroke)- this.penVertexStroke.setStrokeWidth(1)- this.penVertexStroke.setColor(this.selColor())- this.penVertexStroke.setAntiAlias(true)+ initializeRendererPaints(this)}getFontProvider(): TypefaceFontProvider | null {- return this.fontProvider+ return RendererFonts.getFontProvider(this)}async loadFonts(): Promise<void> {- this.fontProvider = this.ck.TypefaceFontProvider.Make()-- const { initFontService, loadFont, ensureArabicFallback, ensureCJKFallback } =- await import('../text/fonts')- initFontService(this.ck, this.fontProvider)-- const fontData = await loadFont(DEFAULT_FONT_FAMILY, 'Regular')- if (fontData) {- const typeface = this.ck.Typeface.MakeFreeTypeFaceFromData(fontData)- if (typeface) {- this.textFont?.delete()- this.labelFont?.delete()- this.sizeFont?.delete()- this.sectionTitleFont?.delete()- this.componentLabelFont?.delete()- this.textFont = new this.ck.Font(typeface, DEFAULT_FONT_SIZE)- this.labelFont = new this.ck.Font(typeface, LABEL_FONT_SIZE)- this.sizeFont = new this.ck.Font(typeface, SIZE_FONT_SIZE)- this.sectionTitleFont = new this.ck.Font(typeface, SECTION_TITLE_FONT_SIZE)- this.componentLabelFont = new this.ck.Font(typeface, COMPONENT_LABEL_FONT_SIZE)- this.profiler.setTypeface(typeface)- }- this.fontMgr = this.ck.FontMgr.FromData(fontData) ?? null- }-- this.fontsLoaded = true- this.invalidateAllPictures()-- void ensureCJKFallback().then((families) => {- if (families.length > 0) this.invalidateAllPictures()- })- void ensureArabicFallback().then((families) => {- if (families.length > 0) this.invalidateAllPictures()- })+ await RendererFonts.loadFonts(this)}- /**- * Load document fonts and set up text measurement for layout.- * Call after `loadFonts()` and before rendering a document headlessly.- * Collects all font family+weight pairs used by `nodeIds`, loads them,- * wires up the text measurer for Yoga layout, and recomputes layout.- */async prepareForExport(graph: SceneGraph,pageId: string,nodeIds: string[]): Promise<() => void> {- const { collectFontKeys, loadFont } = await import('../text/fonts')- const { getTextMeasurer, setTextMeasurer, computeAllLayouts } = await import('../layout')-- const previousTextMeasurer = getTextMeasurer()- setTextMeasurer((node, maxWidth) => this.measureTextNode(node, maxWidth))-- const fontKeys = collectFontKeys(graph, nodeIds)- await Promise.all(fontKeys.map(([family, style]) => loadFont(family, style)))-- computeAllLayouts(graph, pageId)-- return () => setTextMeasurer(previousTextMeasurer)+ return RendererFonts.prepareForExport(this, graph, pageId, nodeIds)}replaceSurface(surface: Surface): void {@@ -499,181 +310,55 @@ export class SkiaRenderer {}invalidateScenePicture(): void {- this.scenePicture?.delete()- this.scenePicture = null- this.scenePictureVersion = -1+ RendererState.invalidateScenePicture(this)}invalidateAllPictures(): void {- this.invalidateScenePicture()- for (const pic of this.nodePictureCache.values()) pic?.delete()- this.nodePictureCache.clear()+ RendererState.invalidateAllPictures(this)}invalidateNodePicture(nodeId: string): void {- const pic = this.nodePictureCache.get(nodeId)- if (pic) {- pic.delete()- this.nodePictureCache.delete(nodeId)- }+ RendererState.invalidateNodePicture(this, nodeId)}flashNode(nodeId: string): void {- this._flashes.push({ nodeId, startTime: performance.now() })+ RendererState.flashNode(this, nodeId)}aiMarkActive(nodeIds: string[]): void {- for (const id of nodeIds) this._aiActiveNodes.add(id)+ RendererState.aiMarkActive(this, nodeIds)}aiMarkDone(nodeIds: string[]): void {- const now = performance.now()- for (const id of nodeIds) {- if (this._aiActiveNodes.delete(id)) {- this._aiDoneFlashes.push({ nodeId: id, startTime: now })- }- }+ RendererState.aiMarkDone(this, nodeIds)}aiFlashDone(nodeIds: string[]): void {- const now = performance.now()- for (const id of nodeIds) {- this._aiDoneFlashes.push({ nodeId: id, startTime: now })- }+ RendererState.aiFlashDone(this, nodeIds)}aiClearActive(): void {- this._aiActiveNodes.clear()+ RendererState.aiClearActive(this)}aiClearAll(): void {- this._aiActiveNodes.clear()- this._aiDoneFlashes = []+ RendererState.aiClearAll(this)}get hasActiveFlashes(): boolean {- return (- this._flashes.length > 0 || this._aiActiveNodes.size > 0 || this._aiDoneFlashes.length > 0- )+ return RendererState.hasActiveFlashes(this)}hitTestSectionTitle(graph: SceneGraph, canvasX: number, canvasY: number): SceneNode | null {- if (!this.sectionTitleFont) return null-- const pageNode = graph.getNode(this.pageId ?? graph.rootId)- if (!pageNode) return null-- const font = this.sectionTitleFont- let result: SceneNode | null = null-- const check = (parentId: string, ox: number, oy: number, insideSection: boolean) => {- const parent = graph.getNode(parentId)- if (!parent) return- for (let i = parent.childIds.length - 1; i >= 0; i--) {- if (result) return- const childId = parent.childIds[i]- const child = graph.getNode(childId)- if (!child || !child.visible) continue- const ax = ox + child.x- const ay = oy + child.y- if (child.type === 'SECTION') {- const glyphIds = font.getGlyphIDs(child.name)- const widths = font.getGlyphWidths(glyphIds)- let textW = 0- for (const w of widths) textW += w-- const pillW =- Math.min(textW + SECTION_TITLE_PADDING_X * 2, child.width * this.zoom) / this.zoom- const pillH = SECTION_TITLE_HEIGHT / this.zoom- const gap = SECTION_TITLE_GAP / this.zoom- const localX = canvasX - ax- const localY = canvasY - ay-- let hitX = localX- let hitY = localY- if (child.rotation !== 0) {- const rad = (-child.rotation * Math.PI) / 180- const cos = Math.cos(rad)- const sin = Math.sin(rad)- hitX = localX * cos - localY * sin- hitY = localX * sin + localY * cos- }-- const pillX = 0- const pillY = insideSection ? gap : -pillH - gap-- if (hitX >= pillX && hitX <= pillX + pillW && hitY >= pillY && hitY <= pillY + pillH) {- result = child- return- }-- check(childId, ax, ay, true)- } else if (child.childIds.length > 0) {- check(childId, ax, ay, insideSection)- }- }- }-- check(pageNode.id, 0, 0, false)- return result+ return LabelHitTest.hitTestSectionTitle(+ graph, canvasX, canvasY, this.zoom, this.pageId ?? graph.rootId, this.sectionTitleFont+ )}hitTestComponentLabel(graph: SceneGraph, canvasX: number, canvasY: number): SceneNode | null {- if (!this.componentLabelFont) return null-- const pageNode = graph.getNode(this.pageId ?? graph.rootId)- if (!pageNode) return null-- const font = this.componentLabelFont- const LABEL_TYPES = new Set(['COMPONENT', 'COMPONENT_SET'])- let result: SceneNode | null = null-- const check = (parentId: string, ox: number, oy: number) => {- const parent = graph.getNode(parentId)- if (!parent) return- for (let i = parent.childIds.length - 1; i >= 0; i--) {- if (result) return- const childId = parent.childIds[i]- const child = graph.getNode(childId)- if (!child || !child.visible) continue- const ax = ox + child.x- const ay = oy + child.y- if (LABEL_TYPES.has(child.type)) {- const glyphIds = font.getGlyphIDs(child.name)- const widths = font.getGlyphWidths(glyphIds)- let textW = 0- for (const w of widths) textW += w- const labelW = (COMPONENT_LABEL_ICON_SIZE + COMPONENT_LABEL_ICON_GAP + textW) / this.zoom- const labelH = COMPONENT_LABEL_FONT_SIZE / this.zoom- const gap = COMPONENT_LABEL_GAP / this.zoom-- const isInsideSet = parent.type === 'COMPONENT_SET'- const labelX = ax- let labelY: number- if (isInsideSet) {- labelY = ay + gap- } else {- labelY = ay - labelH - gap- }-- if (- canvasX >= labelX &&- canvasX <= labelX + labelW &&- canvasY >= labelY &&- canvasY <= labelY + labelH- ) {- result = child- return- }- }- if (child.childIds.length > 0) {- check(childId, ax, ay)- }- }- }-- check(pageNode.id, 0, 0)- return result+ return LabelHitTest.hitTestComponentLabel(+ graph, canvasX, canvasY, this.zoom, this.pageId ?? graph.rootId, this.componentLabelFont+ )}hitTestFrameTitle(@@ -682,58 +367,11 @@ export class SkiaRenderer {canvasY: number,selectedIds: Set<string>): SceneNode | null {- if (!this.labelFont || selectedIds.size !== 1) return null-- const id = [...selectedIds][0]- const node = graph.getNode(id)- if (node?.type !== 'FRAME') return null-- const parent = node.parentId ? graph.getNode(node.parentId) : null- const isTopLevel = !parent || parent.type === 'CANVAS' || parent.type === 'SECTION'- if (!isTopLevel) return null-- const abs = graph.getAbsolutePosition(id)- const font = this.labelFont- const glyphIds = font.getGlyphIDs(node.name)- const widths = font.getGlyphWidths(glyphIds)- let textW = 0- for (const w of widths) textW += w-- const labelW = textW / this.zoom- const labelH = LABEL_FONT_SIZE / this.zoom- const localX = canvasX - abs.x- const localY = canvasY - abs.y-- let hitX = localX- let hitY = localY- if (node.rotation !== 0) {- const rad = (-node.rotation * Math.PI) / 180- const cos = Math.cos(rad)- const sin = Math.sin(rad)- hitX = localX * cos - localY * sin- hitY = localX * sin + localY * cos- }-- const labelX = 0- const labelY = -LABEL_OFFSET_Y / this.zoom - labelH-- if (hitX >= labelX && hitX <= labelX + labelW && hitY >= labelY && hitY <= labelY + labelH) {- return node- }-- return null+ return LabelHitTest.hitTestFrameTitle(graph, canvasX, canvasY, this.zoom, selectedIds, this.labelFont)}renderSceneToCanvas(canvas: Canvas, graph: SceneGraph, pageId: string): void {- const prevViewport = this.worldViewport- this.worldViewport = { x: -1e9, y: -1e9, w: 2e9, h: 2e9 }- const pageNode = graph.getNode(pageId)- if (pageNode) {- for (const childId of pageNode.childIds) {- this.renderNode(canvas, graph, childId, {})- }- }- this.worldViewport = prevViewport+ RenderPipeline.renderSceneToCanvas(this, canvas, graph, pageId)}renderFromEditorState(@@ -742,44 +380,20 @@ export class SkiaRenderer {textEditor: unknown,viewportWidth: number,viewportHeight: number,- showRulers = true+ showRulers = true,+ layer: RenderPipeline.RenderLayer = 'full'): void {- const extendedState = state as EditorState & {- nodeEditState?: RenderOverlays['nodeEditState']- }- this.dpr = IS_BROWSER ? window.devicePixelRatio || 1 : 1- this.panX = state.panX- this.panY = state.panY- this.zoom = state.zoom- this.viewportWidth = viewportWidth- this.viewportHeight = viewportHeight- this.showRulers = showRulers- this.pageColor = state.pageColor- this.pageId = state.currentPageId- this.render(+ const dpr = IS_BROWSER ? window.devicePixelRatio || 1 : 1+ RenderPipeline.renderFromEditorState(+ this,+ state,graph,- state.selectedIds,- {- hoveredNodeId: state.hoveredNodeId,- enteredContainerId: state.enteredContainerId,- editingTextId: state.editingTextId,- textEditor: textEditor as RenderOverlays['textEditor'],- marquee: state.marquee,- snapGuides: state.snapGuides,- rotationPreview: state.rotationPreview,- dropTargetId: state.dropTargetId,- layoutInsertIndicator: state.layoutInsertIndicator,- penState: state.penState- ? ({- ...state.penState,- cursorX: state.penCursorX ?? undefined,- cursorY: state.penCursorY ?? undefined- } as RenderOverlays['penState'])- : null,- nodeEditState: extendedState.nodeEditState ?? null,- remoteCursors: state.remoteCursors- },- state.sceneVersion+ textEditor,+ viewportWidth,+ viewportHeight,+ showRulers,+ dpr,+ layer)}@@ -787,155 +401,10 @@ export class SkiaRenderer {graph: SceneGraph,selectedIds: Set<string>,overlays: RenderOverlays = {},- sceneVersion = -1+ sceneVersion = -1,+ layer: RenderPipeline.RenderLayer = 'full'): void {- const p = this.profiler- p.beginFrame()-- graph.clearAbsPosCache()-- const canvas = this.surface.getCanvas()- canvas.clear(this.ck.Color4f(this.pageColor.r, this.pageColor.g, this.pageColor.b, 1))-- this.worldViewport = {- x: -this.panX / this.zoom,- y: -this.panY / this.zoom,- w: this.viewportWidth / this.zoom,- h: this.viewportHeight / this.zoom- }-- const hasVolatileOverlays =- overlays.dropTargetId != null ||- overlays.rotationPreview != null ||- overlays.editingTextId != null ||- overlays.nodeEditState != null-- const canUsePicture =- !hasVolatileOverlays &&- this.scenePicture &&- sceneVersion === this.scenePictureVersion &&- this.pageId === this.scenePicturePageId-- p.setCacheHit(!!canUsePicture)-- canvas.save()- canvas.scale(this.dpr, this.dpr)- canvas.translate(this.panX, this.panY)- canvas.scale(this.zoom, this.zoom)-- p.beginPhase('render:scene')- if (canUsePicture) {- p.beginPhase('render:drawPicture')- if (this.scenePicture) canvas.drawPicture(this.scenePicture)- p.endPhase('render:drawPicture')- } else if (hasVolatileOverlays) {- this._nodeCount = 0- this._culledCount = 0- p.beginPhase('render:volatile')- const pageNode = graph.getNode(this.pageId ?? graph.rootId)- if (pageNode) {- for (const childId of pageNode.childIds) {- this.renderNode(canvas, graph, childId, overlays)- }- }- p.endPhase('render:volatile')- } else {- this._nodeCount = 0- this._culledCount = 0- p.beginPhase('render:recordPicture')- this.recordScenePicture(canvas, graph, sceneVersion)- p.endPhase('render:recordPicture')- }- p.endPhase('render:scene')-- canvas.restore()-- canvas.save()- canvas.scale(this.dpr, this.dpr)- this.labelCache.update(graph, this.pageId, sceneVersion)- p.beginPhase('render:sectionTitles')- this.drawSectionTitles(canvas, graph)- p.endPhase('render:sectionTitles')- p.beginPhase('render:componentLabels')- this.drawComponentLabels(canvas, graph)- p.endPhase('render:componentLabels')- canvas.restore()-- canvas.save()- canvas.scale(this.dpr, this.dpr)-- this.drawHoverHighlight(- canvas,- graph,- overlays.hoveredNodeId === overlays.nodeEditState?.nodeId ? null : overlays.hoveredNodeId- )- this.drawEnteredContainer(canvas, graph, overlays.enteredContainerId)- p.beginPhase('render:selection')- this.drawSelection(canvas, graph, selectedIds, overlays)- p.endPhase('render:selection')- this.drawFlashes(canvas, graph)- this.drawSnapGuides(canvas, overlays.snapGuides)- this.drawMarquee(canvas, overlays.marquee)- this.drawLayoutInsertIndicator(canvas, overlays.layoutInsertIndicator)- this.drawNodeEditOverlay(canvas, graph, overlays.nodeEditState)- this.drawPenOverlay(canvas, overlays.penState)- this.drawRemoteCursors(canvas, graph, overlays.remoteCursors)- p.beginPhase('render:rulers')- if (this.showRulers) this.drawRulers(canvas, graph, selectedIds)- p.endPhase('render:rulers')-- p.drawHUD(canvas, this.showRulers)-- canvas.restore()-- p.beginPhase('render:flush')- this.surface.flush()- p.endPhase('render:flush')-- p.setNodeCounts(this._nodeCount, this._culledCount)- p.endFrame()- }-- private recordScenePicture(canvas: Canvas, graph: SceneGraph, sceneVersion: number): void {- this.scenePicture?.delete()- const prevViewport = this.worldViewport- this.worldViewport = { x: -1e6, y: -1e6, w: 2e6, h: 2e6 }- const recorder = new this.ck.PictureRecorder()- const pageNode = graph.getNode(this.pageId ?? graph.rootId)- const sceneContentBounds = pageNode- ? computeDescendantVisualBounds(- pageNode.childIds,- (id) => graph.getNode(id),- (id) => graph.getAbsolutePosition(id)- )- : null- const sceneBounds = sceneContentBounds- ? {- x: sceneContentBounds.minX,- y: sceneContentBounds.minY,- width: sceneContentBounds.maxX - sceneContentBounds.minX,- height: sceneContentBounds.maxY - sceneContentBounds.minY- }- : { x: 0, y: 0, width: 1, height: 1 }- const padding = 1024- const bounds = this.ck.LTRBRect(- sceneBounds.x - padding,- sceneBounds.y - padding,- sceneBounds.x + sceneBounds.width + padding,- sceneBounds.y + sceneBounds.height + padding- )- const recCanvas = recorder.beginRecording(bounds)- if (pageNode) {- for (const childId of pageNode.childIds) {- this.renderNode(recCanvas, graph, childId, {})- }- }- this.scenePicture = recorder.finishRecordingAsPicture()- recorder.delete()- this.worldViewport = prevViewport- this.scenePictureVersion = sceneVersion- this.scenePicturePageId = this.pageId- canvas.drawPicture(this.scenePicture)+ RenderPipeline.render(this, graph, selectedIds, overlays, sceneVersion, layer)}invalidateVectorPath(nodeId: string): void {@@ -954,15 +423,15 @@ export class SkiaRenderer {}measureTextNode(node: SceneNode, maxWidth?: number): { width: number; height: number } | null {- return measureTextNodeFn(this, node, maxWidth)+ return RenderText.measureTextNode(this, node, maxWidth)}isNodeFontLoaded(node: SceneNode): boolean {- return isNodeFontLoadedFn(this, node)+ return RenderText.isNodeFontLoaded(this, node)}buildTextPicture(node: SceneNode): Uint8Array | null {- return buildTextPictureFn(this, node)+ return RenderText.buildTextPicture(this, node)}buildParagraph(@@ -970,7 +439,7 @@ export class SkiaRenderer {color?: Float32Array,opts?: { halfLeading?: boolean }): Paragraph {- return buildParagraphFn(this, node, color, opts)+ return RenderText.buildParagraph(this, node, color, opts)}resolveFillColorInfo(@@ -979,26 +448,11 @@ export class SkiaRenderer {node: SceneNode,graph: SceneGraph): ResolvedRenderColor {- const varId = node.boundVariables[`fills/${fillIndex}/color`]- if (varId) {- const resolved = graph.resolveColorVariable(varId)- if (resolved) {- return {- color: resolved,- cssColor: '',- sourceSpace: 'srgb',- targetSpace: graph.documentColorSpace,- clipped: false- }- }- }- return resolveNodeFillColor(fill, fillIndex, node, {- documentColorSpace: graph.documentColorSpace- })+ return RenderColors.resolveFillColorInfo(fill, fillIndex, node, graph)}resolveFillColor(fill: Fill, fillIndex: number, node: SceneNode, graph: SceneGraph): Color {- return this.resolveFillColorInfo(fill, fillIndex, node, graph).color+ return RenderColors.resolveFillColor(fill, fillIndex, node, graph)}resolveStrokeColorInfo(@@ -1007,22 +461,7 @@ export class SkiaRenderer {node: SceneNode,graph: SceneGraph): ResolvedRenderColor {- const varId = node.boundVariables[`strokes/${strokeIndex}/color`]- if (varId) {- const resolved = graph.resolveColorVariable(varId)- if (resolved) {- return {- color: resolved,- cssColor: '',- sourceSpace: 'srgb',- targetSpace: graph.documentColorSpace,- clipped: false- }- }- }- return resolveNodeStrokeColor(stroke, strokeIndex, node, {- documentColorSpace: graph.documentColorSpace- })+ return RenderColors.resolveStrokeColorInfo(stroke, strokeIndex, node, graph)}resolveStrokeColor(@@ -1031,7 +470,7 @@ export class SkiaRenderer {node: SceneNode,graph: SceneGraph): Color {- return this.resolveStrokeColorInfo(stroke, strokeIndex, node, graph).color+ return RenderColors.resolveStrokeColor(stroke, strokeIndex, node, graph)}screenToCanvas(sx: number, sy: number): Vector {@@ -1044,318 +483,9 @@ export class SkiaRenderer {destroyed = falsedestroy(): void {- if (this.destroyed) return- this.destroyed = true-- for (const img of this.imageCache.values()) img.delete()- this.imageCache.clear()- for (const cache of [this.vectorPathCache, this.fillGeometryCache, this.strokeGeometryCache]) {- for (const paths of cache.values()) {- for (const p of paths) p.delete()- }- cache.clear()- }- this.fillPaint.delete()- this.strokePaint.delete()- this.selectionPaint.delete()- this.snapPaint.delete()- this.auxFill.delete()- this.auxStroke.delete()- this.opacityPaint.delete()- this.textFont?.delete()- this.labelFont?.delete()- this.sizeFont?.delete()- this.fontMgr?.delete()- this.fontProvider?.delete()- this.rulerBgPaint.delete()- this.rulerTickPaint.delete()- this.rulerTextPaint.delete()- this.rulerHlPaint.delete()- this.rulerBadgePaint.delete()- this.rulerLabelPaint.delete()- this.penPathPaint.delete()- this.penLiveStrokePaint.delete()- this.penHandlePaint.delete()- this.penVertexFill.delete()- this.penVertexStroke.delete()- this.effectLayerPaint.delete()- for (const filter of this.imageFilterCache.values()) filter?.delete()- this.imageFilterCache.clear()- for (const filter of this.maskFilterCache.values()) filter?.delete()- this.maskFilterCache.clear()- for (const pic of this.nodePictureCache.values()) pic?.delete()- this.nodePictureCache.clear()- this.scenePicture?.delete()- this._flashPaint?.delete()- this.profiler.destroy()- this.surface.delete()- }-- // --- Delegation methods ----- private drawHoverHighlight(- canvas: Canvas,- graph: SceneGraph,- hoveredNodeId?: string | null- ): void {- drawHoverHighlightFn(this, canvas, graph, hoveredNodeId)- }-- private drawEnteredContainer(- canvas: Canvas,- graph: SceneGraph,- enteredContainerId?: string | null- ): void {- drawEnteredContainerFn(this, canvas, graph, enteredContainerId)- }-- private drawSelection(- canvas: Canvas,- graph: SceneGraph,- selectedIds: Set<string>,- overlays: RenderOverlays- ): void {- drawSelectionFn(this, canvas, graph, selectedIds, overlays)- }-- drawNodeSelection(canvas: Canvas, node: SceneNode, rotation: number, graph: SceneGraph): void {- drawNodeSelectionFn(this, canvas, node, rotation, graph)- }-- drawSelectionLabels(- canvas: Canvas,- graph: SceneGraph,- selectedIds: Set<string>,- overlays?: RenderOverlays- ): void {- drawSelectionLabelsFn(this, canvas, graph, selectedIds, overlays)- }-- drawParentFrameOutlines(canvas: Canvas, graph: SceneGraph, selectedIds: Set<string>): void {- drawParentFrameOutlinesFn(this, canvas, graph, selectedIds)- }-- drawNodeOutline(canvas: Canvas, node: SceneNode, rotation: number, graph: SceneGraph): void {- drawNodeOutlineFn(this, canvas, node, rotation, graph)- }-- drawGroupBounds(canvas: Canvas, nodes: SceneNode[], graph: SceneGraph): void {- drawGroupBoundsFn(this, canvas, nodes, graph)- }-- getRotatedCorners(n: SceneNode, abs: Vector): Vector[] {- return getRotatedCornersFn(this, n, abs)- }-- drawHandle(canvas: Canvas, x: number, y: number): void {- drawHandleFn(this, canvas, x, y)- }-- private drawSnapGuides(canvas: Canvas, guides?: SnapGuide[]): void {- drawSnapGuidesFn(this, canvas, guides)- }-- private drawMarquee(canvas: Canvas, marquee?: Rect | null): void {- drawMarqueeFn(this, canvas, marquee)- }-- private drawFlashes(canvas: Canvas, graph: SceneGraph): void {- drawFlashesFn(this, canvas, graph)- drawAiOverlaysFn(this, canvas, graph)- }-- private drawLayoutInsertIndicator(- canvas: Canvas,- indicator?: RenderOverlays['layoutInsertIndicator']- ): void {- drawLayoutInsertIndicatorFn(this, canvas, indicator)- }-- drawTextEditOverlay(canvas: Canvas, node: SceneNode, editor: TextEditor): void {- drawTextEditOverlayFn(this, canvas, node, editor)- }-- private drawNodeEditOverlay(- canvas: Canvas,- graph: SceneGraph,- editState: RenderOverlays['nodeEditState']- ): void {- drawNodeEditOverlayFn(this, canvas, graph, editState as NodeEditOverlayState | null)- }-- private drawPenOverlay(canvas: Canvas, penState: RenderOverlays['penState']): void {- drawPenOverlayFn(this, canvas, penState)- }-- private drawRemoteCursors(- canvas: Canvas,- graph: SceneGraph,- cursors?: RenderOverlays['remoteCursors']- ): void {- drawRemoteCursorsFn(this, canvas, graph, cursors)- }-- private drawRulers(canvas: Canvas, graph: SceneGraph, selectedIds: Set<string>): void {- drawRulersFn(this, canvas, graph, selectedIds)- }-- private drawSectionTitles(canvas: Canvas, graph: SceneGraph): void {- drawSectionTitlesFn(this, canvas, graph)- }-- private drawComponentLabels(canvas: Canvas, graph: SceneGraph): void {- drawComponentLabelsFn(this, canvas, graph)- }-- renderNode(canvas: Canvas, graph: SceneGraph, nodeId: string, overlays: RenderOverlays): void {- renderNodeFn(this, canvas, graph, nodeId, overlays)- }-- renderSection(canvas: Canvas, node: SceneNode, graph: SceneGraph): void {- renderSectionFn(this, canvas, node, graph)- }-- renderComponentSet(canvas: Canvas, node: SceneNode, graph: SceneGraph): void {- renderComponentSetFn(this, canvas, node, graph)- }-- renderShape(canvas: Canvas, node: SceneNode, graph: SceneGraph): void {- renderShapeFn(this, canvas, node, graph)+ destroyRenderer(this)}- renderShapeUncached(canvas: Canvas, node: SceneNode, graph: SceneGraph): void {- renderShapeUncachedFn(this, canvas, node, graph)- }-- renderEffects(- canvas: Canvas,- node: SceneNode,- rect: Float32Array,- hasRadius: boolean,- pass: 'behind' | 'front',- shadowShapeChild?: SceneNode | null- ): void {- renderEffectsFn(this, canvas, node, rect, hasRadius, pass, shadowShapeChild)- }-- renderText(canvas: Canvas, node: SceneNode): void {- renderTextFn(this, canvas, node)- }-- drawNodeFill(canvas: Canvas, node: SceneNode, rect: Float32Array, hasRadius: boolean): void {- drawNodeFillFn(this, canvas, node, rect, hasRadius)- }-- applyFill(fill: Fill, node: SceneNode, graph: SceneGraph, fillIndex = 0): boolean {- return applyFillFn(this, fill, node, graph, fillIndex)- }-- applyGradientFill(fill: Fill, node: SceneNode, graph: SceneGraph): void {- applyGradientFillFn(this, fill, node, graph)- }-- applyImageFill(fill: Fill, node: SceneNode, graph: SceneGraph): boolean {- return applyImageFillFn(this, fill, node, graph)- }-- drawArc(canvas: Canvas, node: SceneNode, paint: Paint): void {- drawArcFn(this, canvas, node, paint)- }-- drawNodeStroke(canvas: Canvas, node: SceneNode, rect: Float32Array, hasRadius: boolean): void {- drawNodeStrokeFn(this, canvas, node, rect, hasRadius)- }-- drawStrokeWithAlign(- canvas: Canvas,- node: SceneNode,- rect: Float32Array,- hasRadius: boolean,- align: 'INSIDE' | 'CENTER' | 'OUTSIDE'- ): void {- drawStrokeWithAlignFn(this, canvas, node, rect, hasRadius, align)- }-- drawRRectStrokeWithAlign(- canvas: Canvas,- rrect: Float32Array,- node: SceneNode,- stroke: Stroke- ): void {- drawRRectStrokeWithAlignFn(this, canvas, rrect, node, stroke)- }-- drawIndividualSideStrokes(- canvas: Canvas,- node: SceneNode,- align: 'INSIDE' | 'CENTER' | 'OUTSIDE'- ): void {- drawIndividualSideStrokesFn(this, canvas, node, align)- }-- strokeNodeShape(canvas: Canvas, node: SceneNode, paint: Paint): void {- strokeNodeShapeFn(this, canvas, node, paint)- }-- makeNodeShapePath(node: SceneNode, rect: Float32Array, hasRadius: boolean): Path {- return makeNodeShapePathFn(this, node, rect, hasRadius)- }-- makePolygonPath(node: SceneNode): Path {- return makePolygonPathFn(this, node)- }-- makeRRect(node: SceneNode): Float32Array {- return makeRRectFn(this, node)- }-- makeRRectWithSpread(node: SceneNode, spread: number): Float32Array {- return makeRRectWithSpreadFn(this, node, spread)- }-- makeRRectWithOffset(node: SceneNode, ox: number, oy: number, spread: number): Float32Array {- return makeRRectWithOffsetFn(this, node, ox, oy, spread)- }-- clipNodeShape(canvas: Canvas, node: SceneNode, rect: Float32Array, hasRadius: boolean): void {- clipNodeShapeFn(this, canvas, node, rect, hasRadius)- }-- getVectorPaths(node: SceneNode): Path[] | null {- return getVectorPathsFn(this, node)- }-- getFillGeometry(node: SceneNode): Path[] | null {- return getFillGeometryFn(this, node)- }-- getStrokeGeometry(node: SceneNode): Path[] | null {- return getStrokeGeometryFn(this, node)- }-- getCachedDropShadow(dx: number, dy: number, sigma: number, color: Float32Array): ImageFilter {- return getCachedDropShadowFn(this, dx, dy, sigma, color)- }-- getCachedBlur(sigma: number): ImageFilter {- return getCachedBlurFn(this, sigma)- }-- getCachedDecalBlur(sigma: number): ImageFilter {- return getCachedDecalBlurFn(this, sigma)- }-- getCachedMaskBlur(sigma: number): MaskFilter {- return getCachedMaskBlurFn(this, sigma)- }-- applyClippedBlur(- canvas: Canvas,- node: SceneNode,- rect: Float32Array,- hasRadius: boolean,- sigma: number- ): void {- applyClippedBlurFn(this, canvas, node, rect, hasRadius, sigma)- }}++installRendererDomainMethods(SkiaRenderer.prototype)diff --git a/packages/core/src/canvas/renderer/colors.ts b/packages/core/src/canvas/renderer/colors.tsnew file mode 100644index 000000000..cbb0a5cf0--- /dev/null+++ b/packages/core/src/canvas/renderer/colors.ts@@ -0,0 +1,65 @@+import { resolveNodeFillColor, resolveNodeStrokeColor } from '#core/color/management'++import type { ResolvedRenderColor } from '#core/color/management'+import type { Fill, SceneGraph, SceneNode, Stroke } from '#core/scene-graph'+import type { Color } from '#core/types'++function resolvedVariableColor(color: Color, graph: SceneGraph): ResolvedRenderColor {+ return {+ color,+ cssColor: '',+ sourceSpace: 'srgb',+ targetSpace: graph.documentColorSpace,+ clipped: false+ }+}++export function resolveFillColorInfo(+ fill: Fill,+ fillIndex: number,+ node: SceneNode,+ graph: SceneGraph+): ResolvedRenderColor {+ const varId = node.boundVariables[`fills/${fillIndex}/color`]+ if (varId) {+ const resolved = graph.resolveColorVariable(varId)+ if (resolved) return resolvedVariableColor(resolved, graph)+ }+ return resolveNodeFillColor(fill, fillIndex, node, {+ documentColorSpace: graph.documentColorSpace+ })+}++export function resolveFillColor(+ fill: Fill,+ fillIndex: number,+ node: SceneNode,+ graph: SceneGraph+): Color {+ return resolveFillColorInfo(fill, fillIndex, node, graph).color+}++export function resolveStrokeColorInfo(+ stroke: Stroke,+ strokeIndex: number,+ node: SceneNode,+ graph: SceneGraph+): ResolvedRenderColor {+ const varId = node.boundVariables[`strokes/${strokeIndex}/color`]+ if (varId) {+ const resolved = graph.resolveColorVariable(varId)+ if (resolved) return resolvedVariableColor(resolved, graph)+ }+ return resolveNodeStrokeColor(stroke, strokeIndex, node, {+ documentColorSpace: graph.documentColorSpace+ })+}++export function resolveStrokeColor(+ stroke: Stroke,+ strokeIndex: number,+ node: SceneNode,+ graph: SceneGraph+): Color {+ return resolveStrokeColorInfo(stroke, strokeIndex, node, graph).color+}diff --git a/packages/core/src/canvas/renderer/fonts.ts b/packages/core/src/canvas/renderer/fonts.tsnew file mode 100644index 000000000..be514cfa3--- /dev/null+++ b/packages/core/src/canvas/renderer/fonts.ts@@ -0,0 +1,72 @@+import {+ COMPONENT_LABEL_FONT_SIZE,+ DEFAULT_FONT_FAMILY,+ DEFAULT_FONT_SIZE,+ LABEL_FONT_SIZE,+ SECTION_TITLE_FONT_SIZE,+ SIZE_FONT_SIZE+} from '#core/constants'++import type { SceneGraph } from '#core/scene-graph'+import type { SkiaRenderer } from '#core/canvas/renderer'++export function getFontProvider(r: SkiaRenderer) {+ return r.fontProvider+}++export async function loadFonts(r: SkiaRenderer): Promise<void> {+ r.fontProvider = r.ck.TypefaceFontProvider.Make()++ const { initFontService, loadFont, ensureArabicFallback, ensureCJKFallback } =+ await import('#core/text/fonts')+ initFontService(r.ck, r.fontProvider)++ const fontData = await loadFont(DEFAULT_FONT_FAMILY, 'Regular')+ if (fontData) {+ const typeface = r.ck.Typeface.MakeFreeTypeFaceFromData(fontData)+ if (typeface) {+ r.textFont?.delete()+ r.labelFont?.delete()+ r.sizeFont?.delete()+ r.sectionTitleFont?.delete()+ r.componentLabelFont?.delete()+ r.textFont = new r.ck.Font(typeface, DEFAULT_FONT_SIZE)+ r.labelFont = new r.ck.Font(typeface, LABEL_FONT_SIZE)+ r.sizeFont = new r.ck.Font(typeface, SIZE_FONT_SIZE)+ r.sectionTitleFont = new r.ck.Font(typeface, SECTION_TITLE_FONT_SIZE)+ r.componentLabelFont = new r.ck.Font(typeface, COMPONENT_LABEL_FONT_SIZE)+ r.profiler.setTypeface(typeface)+ }+ r.fontMgr = r.ck.FontMgr.FromData(fontData) ?? null+ }++ r.fontsLoaded = true+ r.invalidateAllPictures()++ void ensureCJKFallback().then((families) => {+ if (families.length > 0) r.invalidateAllPictures()+ })+ void ensureArabicFallback().then((families) => {+ if (families.length > 0) r.invalidateAllPictures()+ })+}++export async function prepareForExport(+ r: SkiaRenderer,+ graph: SceneGraph,+ pageId: string,+ nodeIds: string[]+): Promise<() => void> {+ const { collectFontKeys, loadFont } = await import('#core/text/fonts')+ const { getTextMeasurer, setTextMeasurer, computeAllLayouts } = await import('#core/layout')++ const previousTextMeasurer = getTextMeasurer()+ setTextMeasurer((node, maxWidth) => r.measureTextNode(node, maxWidth))++ const fontKeys = collectFontKeys(graph, nodeIds)+ await Promise.all(fontKeys.map(([family, style]) => loadFont(family, style)))++ computeAllLayouts(graph, pageId)++ return () => setTextMeasurer(previousTextMeasurer)+}diff --git a/packages/core/src/canvas/renderer/lifecycle.ts b/packages/core/src/canvas/renderer/lifecycle.tsnew file mode 100644index 000000000..e70996fa6--- /dev/null+++ b/packages/core/src/canvas/renderer/lifecycle.ts@@ -0,0 +1,49 @@+import type { SkiaRenderer } from '#core/canvas/renderer'++export function destroyRenderer(r: SkiaRenderer): void {+ if (r.destroyed) return+ r.destroyed = true++ for (const img of r.imageCache.values()) img.delete()+ r.imageCache.clear()+ for (const cache of [r.vectorPathCache, r.fillGeometryCache, r.strokeGeometryCache]) {+ for (const paths of cache.values()) {+ for (const p of paths) p.delete()+ }+ cache.clear()+ }+ r.fillPaint.delete()+ r.strokePaint.delete()+ r.selectionPaint.delete()+ r.snapPaint.delete()+ r.auxFill.delete()+ r.auxStroke.delete()+ r.opacityPaint.delete()+ r.textFont?.delete()+ r.labelFont?.delete()+ r.sizeFont?.delete()+ r.fontMgr?.delete()+ r.fontProvider?.delete()+ r.rulerBgPaint.delete()+ r.rulerTickPaint.delete()+ r.rulerTextPaint.delete()+ r.rulerHlPaint.delete()+ r.rulerBadgePaint.delete()+ r.rulerLabelPaint.delete()+ r.penPathPaint.delete()+ r.penLiveStrokePaint.delete()+ r.penHandlePaint.delete()+ r.penVertexFill.delete()+ r.penVertexStroke.delete()+ r.effectLayerPaint.delete()+ for (const filter of r.imageFilterCache.values()) filter?.delete()+ r.imageFilterCache.clear()+ for (const filter of r.maskFilterCache.values()) filter?.delete()+ r.maskFilterCache.clear()+ for (const pic of r.nodePictureCache.values()) pic?.delete()+ r.nodePictureCache.clear()+ r.scenePicture?.delete()+ r._flashPaint?.delete()+ r.profiler.destroy()+ r.surface.delete()+}diff --git a/packages/core/src/canvas/renderer/methods.ts b/packages/core/src/canvas/renderer/methods.tsnew file mode 100644index 000000000..82760f48b--- /dev/null+++ b/packages/core/src/canvas/renderer/methods.ts@@ -0,0 +1,291 @@+import * as AiOverlays from '#core/canvas/ai-overlays'+import * as Effects from '#core/canvas/effects'+import * as Fills from '#core/canvas/fills'+import * as Labels from '#core/canvas/labels/draw'+import * as NodeEditOverlay from '#core/canvas/node-edit-overlay'+import * as Overlays from '#core/canvas/overlays'+import * as PenOverlay from '#core/canvas/pen-overlay'+import * as Rulers from '#core/canvas/rulers'+import * as SceneRender from '#core/canvas/scene'+import * as Shapes from '#core/canvas/shapes'+import * as Strokes from '#core/canvas/strokes'+import type { Fill, SceneGraph, SceneNode, Stroke } from '#core/scene-graph'+import type { SnapGuide } from '#core/scene-graph/snap'+import type { TextEditor } from '#core/text/editor'+import type { Rect, Vector } from '#core/types'+import type { ImageFilter, MaskFilter, Canvas, Paint, Path } from 'canvaskit-wasm'+import type { NodeEditOverlayState } from '#core/canvas/node-edit-overlay'+import type { RenderOverlays } from '#core/canvas/renderer/types'+import type { SkiaRenderer } from '#core/canvas/renderer'++const rendererMethods: ThisType<SkiaRenderer> = {+drawHoverHighlight(+ canvas: Canvas,+ graph: SceneGraph,+ hoveredNodeId?: string | null+): void {+ Overlays.drawHoverHighlight(this, canvas, graph, hoveredNodeId)+},++drawEnteredContainer(+ canvas: Canvas,+ graph: SceneGraph,+ enteredContainerId?: string | null+): void {+ Overlays.drawEnteredContainer(this, canvas, graph, enteredContainerId)+},++drawSelection(+ canvas: Canvas,+ graph: SceneGraph,+ selectedIds: Set<string>,+ overlays: RenderOverlays+): void {+ Overlays.drawSelection(this, canvas, graph, selectedIds, overlays)+},++drawNodeSelection(canvas: Canvas, node: SceneNode, rotation: number, graph: SceneGraph): void {+ Overlays.drawNodeSelection(this, canvas, node, rotation, graph)+},++drawSelectionLabels(+ canvas: Canvas,+ graph: SceneGraph,+ selectedIds: Set<string>,+ overlays?: RenderOverlays+): void {+ Overlays.drawSelectionLabels(this, canvas, graph, selectedIds, overlays)+},++drawParentFrameOutlines(canvas: Canvas, graph: SceneGraph, selectedIds: Set<string>): void {+ Overlays.drawParentFrameOutlines(this, canvas, graph, selectedIds)+},++drawNodeOutline(canvas: Canvas, node: SceneNode, rotation: number, graph: SceneGraph): void {+ Overlays.drawNodeOutline(this, canvas, node, rotation, graph)+},++drawGroupBounds(canvas: Canvas, nodes: SceneNode[], graph: SceneGraph): void {+ Overlays.drawGroupBounds(this, canvas, nodes, graph)+},++getRotatedCorners(n: SceneNode, abs: Vector): Vector[] {+ return Overlays.getRotatedCorners(this, n, abs)+},++drawHandle(canvas: Canvas, x: number, y: number): void {+ Overlays.drawHandle(this, canvas, x, y)+},++drawSnapGuides(canvas: Canvas, guides?: SnapGuide[]): void {+ Overlays.drawSnapGuides(this, canvas, guides)+},++drawMarquee(canvas: Canvas, marquee?: Rect | null): void {+ Overlays.drawMarquee(this, canvas, marquee)+},++drawFlashes(canvas: Canvas, graph: SceneGraph): void {+ Overlays.drawFlashes(this, canvas, graph)+ AiOverlays.drawAiOverlays(this, canvas, graph)+},++drawLayoutInsertIndicator(+ canvas: Canvas,+ indicator?: RenderOverlays['layoutInsertIndicator']+): void {+ Overlays.drawLayoutInsertIndicator(this, canvas, indicator)+},++drawTextEditOverlay(canvas: Canvas, node: SceneNode, editor: TextEditor): void {+ Overlays.drawTextEditOverlay(this, canvas, node, editor)+},++drawNodeEditOverlay(+ canvas: Canvas,+ graph: SceneGraph,+ editState: RenderOverlays['nodeEditState']+): void {+ NodeEditOverlay.drawNodeEditOverlay(this, canvas, graph, editState as NodeEditOverlayState | null)+},++drawPenOverlay(canvas: Canvas, penState: RenderOverlays['penState']): void {+ PenOverlay.drawPenOverlay(this, canvas, penState)+},++drawRemoteCursors(+ canvas: Canvas,+ graph: SceneGraph,+ cursors?: RenderOverlays['remoteCursors']+): void {+ PenOverlay.drawRemoteCursors(this, canvas, graph, cursors)+},++drawRulers(canvas: Canvas, graph: SceneGraph, selectedIds: Set<string>): void {+ Rulers.drawRulers(this, canvas, graph, selectedIds)+},++drawSectionTitles(canvas: Canvas, graph: SceneGraph): void {+ Labels.drawSectionTitles(this, canvas, graph)+},++drawComponentLabels(canvas: Canvas, graph: SceneGraph): void {+ Labels.drawComponentLabels(this, canvas, graph)+},++renderNode(canvas: Canvas, graph: SceneGraph, nodeId: string, overlays: RenderOverlays): void {+ SceneRender.renderNode(this, canvas, graph, nodeId, overlays)+},++renderSection(canvas: Canvas, node: SceneNode, graph: SceneGraph): void {+ SceneRender.renderSection(this, canvas, node, graph)+},++renderComponentSet(canvas: Canvas, node: SceneNode, graph: SceneGraph): void {+ SceneRender.renderComponentSet(this, canvas, node, graph)+},++renderShape(canvas: Canvas, node: SceneNode, graph: SceneGraph): void {+ SceneRender.renderShape(this, canvas, node, graph)+},++renderShapeUncached(canvas: Canvas, node: SceneNode, graph: SceneGraph): void {+ SceneRender.renderShapeUncached(this, canvas, node, graph)+},++renderEffects(+ canvas: Canvas,+ node: SceneNode,+ rect: Float32Array,+ hasRadius: boolean,+ pass: 'behind' | 'front',+ shadowShapeChild?: SceneNode | null+): void {+ Effects.renderEffects(this, canvas, node, rect, hasRadius, pass, shadowShapeChild)+},++renderText(canvas: Canvas, node: SceneNode): void {+ SceneRender.renderText(this, canvas, node)+},++drawNodeFill(canvas: Canvas, node: SceneNode, rect: Float32Array, hasRadius: boolean): void {+ Fills.drawNodeFill(this, canvas, node, rect, hasRadius)+},++applyFill(fill: Fill, node: SceneNode, graph: SceneGraph, fillIndex = 0): boolean {+ return Fills.applyFill(this, fill, node, graph, fillIndex)+},++applyGradientFill(fill: Fill, node: SceneNode, graph: SceneGraph): void {+ Fills.applyGradientFill(this, fill, node, graph)+},++applyImageFill(fill: Fill, node: SceneNode, graph: SceneGraph): boolean {+ return Fills.applyImageFill(this, fill, node, graph)+},++drawArc(canvas: Canvas, node: SceneNode, paint: Paint): void {+ Fills.drawArc(this, canvas, node, paint)+},++drawNodeStroke(canvas: Canvas, node: SceneNode, rect: Float32Array, hasRadius: boolean): void {+ Strokes.drawNodeStroke(this, canvas, node, rect, hasRadius)+},++drawStrokeWithAlign(+ canvas: Canvas,+ node: SceneNode,+ rect: Float32Array,+ hasRadius: boolean,+ align: 'INSIDE' | 'CENTER' | 'OUTSIDE'+): void {+ Strokes.drawStrokeWithAlign(this, canvas, node, rect, hasRadius, align)+},++drawRRectStrokeWithAlign(+ canvas: Canvas,+ rrect: Float32Array,+ node: SceneNode,+ stroke: Stroke+): void {+ Strokes.drawRRectStrokeWithAlign(this, canvas, rrect, node, stroke)+},++drawIndividualSideStrokes(+ canvas: Canvas,+ node: SceneNode,+ align: 'INSIDE' | 'CENTER' | 'OUTSIDE'+): void {+ Strokes.drawIndividualSideStrokes(this, canvas, node, align)+},++strokeNodeShape(canvas: Canvas, node: SceneNode, paint: Paint): void {+ Strokes.strokeNodeShape(this, canvas, node, paint)+},++makeNodeShapePath(node: SceneNode, rect: Float32Array, hasRadius: boolean): Path {+ return Shapes.makeNodeShapePath(this, node, rect, hasRadius)+},++makePolygonPath(node: SceneNode): Path {+ return Shapes.makePolygonPath(this, node)+},++makeRRect(node: SceneNode): Float32Array {+ return Shapes.makeRRect(this, node)+},++makeRRectWithSpread(node: SceneNode, spread: number): Float32Array {+ return Shapes.makeRRectWithSpread(this, node, spread)+},++makeRRectWithOffset(node: SceneNode, ox: number, oy: number, spread: number): Float32Array {+ return Shapes.makeRRectWithOffset(this, node, ox, oy, spread)+},++clipNodeShape(canvas: Canvas, node: SceneNode, rect: Float32Array, hasRadius: boolean): void {+ Shapes.clipNodeShape(this, canvas, node, rect, hasRadius)+},++getVectorPaths(node: SceneNode): Path[] | null {+ return Shapes.getVectorPaths(this, node)+},++getFillGeometry(node: SceneNode): Path[] | null {+ return Shapes.getFillGeometry(this, node)+},++getStrokeGeometry(node: SceneNode): Path[] | null {+ return Shapes.getStrokeGeometry(this, node)+},++getCachedDropShadow(dx: number, dy: number, sigma: number, color: Float32Array): ImageFilter {+ return Effects.getCachedDropShadow(this, dx, dy, sigma, color)+},++getCachedBlur(sigma: number): ImageFilter {+ return Effects.getCachedBlur(this, sigma)+},++getCachedDecalBlur(sigma: number): ImageFilter {+ return Effects.getCachedDecalBlur(this, sigma)+},++getCachedMaskBlur(sigma: number): MaskFilter {+ return Effects.getCachedMaskBlur(this, sigma)+},++applyClippedBlur(+ canvas: Canvas,+ node: SceneNode,+ rect: Float32Array,+ hasRadius: boolean,+ sigma: number+): void {+ Effects.applyClippedBlur(this, canvas, node, rect, hasRadius, sigma)+}+}++export function installRendererDomainMethods(prototype: object): void {+ Object.assign(prototype, rendererMethods)+}diff --git a/packages/core/src/canvas/renderer/paints.ts b/packages/core/src/canvas/renderer/paints.tsnew file mode 100644index 000000000..8ad38e054--- /dev/null+++ b/packages/core/src/canvas/renderer/paints.ts@@ -0,0 +1,110 @@+import {+ DEFAULT_FONT_SIZE,+ PARENT_OUTLINE_ALPHA,+ PARENT_OUTLINE_DASH,+ PEN_PATH_STROKE_WIDTH,+ RULER_BG_COLOR,+ RULER_TEXT_COLOR,+ RULER_TICK_COLOR,+ SNAP_COLOR+} from '#core/constants'++import type { SkiaRenderer } from '#core/canvas/renderer'++export function initializeRendererPaints(r: SkiaRenderer): void {+ const ck = r.ck++ r.fillPaint = new ck.Paint()+ r.fillPaint.setStyle(ck.PaintStyle.Fill)+ r.fillPaint.setAntiAlias(true)++ r.strokePaint = new ck.Paint()+ r.strokePaint.setStyle(ck.PaintStyle.Stroke)+ r.strokePaint.setAntiAlias(true)++ r.selectionPaint = new ck.Paint()+ r.selectionPaint.setStyle(ck.PaintStyle.Stroke)+ r.selectionPaint.setStrokeWidth(1)+ r.selectionPaint.setColor(r.selColor())+ r.selectionPaint.setAntiAlias(true)++ r.parentOutlinePaint = new ck.Paint()+ r.parentOutlinePaint.setStyle(ck.PaintStyle.Stroke)+ r.parentOutlinePaint.setStrokeWidth(1)+ r.parentOutlinePaint.setColor(r.selColor(PARENT_OUTLINE_ALPHA))+ r.parentOutlinePaint.setAntiAlias(true)+ r.parentOutlinePaint.setPathEffect(+ ck.PathEffect.MakeDash([PARENT_OUTLINE_DASH, PARENT_OUTLINE_DASH], 0)+ )++ r.snapPaint = new ck.Paint()+ r.snapPaint.setStyle(ck.PaintStyle.Stroke)+ r.snapPaint.setStrokeWidth(1)+ r.snapPaint.setColor(ck.Color4f(SNAP_COLOR.r, SNAP_COLOR.g, SNAP_COLOR.b, 1))+ r.snapPaint.setAntiAlias(true)++ r.auxFill = new ck.Paint()+ r.auxFill.setStyle(ck.PaintStyle.Fill)+ r.auxFill.setAntiAlias(true)++ r.auxStroke = new ck.Paint()+ r.auxStroke.setStyle(ck.PaintStyle.Stroke)+ r.auxStroke.setAntiAlias(true)++ r.opacityPaint = new ck.Paint()+ r.effectLayerPaint = new ck.Paint()+ r.textFont = new ck.Font(null, DEFAULT_FONT_SIZE)++ const bg = RULER_BG_COLOR+ r.rulerBgPaint = new ck.Paint()+ r.rulerBgPaint.setColor(ck.Color4f(bg.r, bg.g, bg.b, 1))++ r.rulerTickPaint = new ck.Paint()+ r.rulerTickPaint.setColor(ck.Color4f(RULER_TICK_COLOR.r, RULER_TICK_COLOR.g, RULER_TICK_COLOR.b, 1))+ r.rulerTickPaint.setStrokeWidth(1)+ r.rulerTickPaint.setAntiAlias(true)++ const tc = RULER_TEXT_COLOR+ r.rulerTextPaint = new ck.Paint()+ r.rulerTextPaint.setColor(ck.Color4f(tc.r, tc.g, tc.b, 1))+ r.rulerTextPaint.setAntiAlias(true)++ r.rulerHlPaint = new ck.Paint()+ r.rulerHlPaint.setAntiAlias(true)++ r.rulerBadgePaint = new ck.Paint()+ r.rulerBadgePaint.setAntiAlias(true)++ r.rulerLabelPaint = new ck.Paint()+ r.rulerLabelPaint.setColor(ck.Color4f(1, 1, 1, 1))+ r.rulerLabelPaint.setAntiAlias(true)++ r.penPathPaint = new ck.Paint()+ r.penPathPaint.setStyle(ck.PaintStyle.Stroke)+ r.penPathPaint.setStrokeWidth(1)+ r.penPathPaint.setColor(ck.Color4f(0.698, 0.698, 0.698, 1))+ r.penPathPaint.setAntiAlias(true)++ r.penLiveStrokePaint = new ck.Paint()+ r.penLiveStrokePaint.setStyle(ck.PaintStyle.Stroke)+ r.penLiveStrokePaint.setStrokeWidth(PEN_PATH_STROKE_WIDTH)+ r.penLiveStrokePaint.setColor(ck.Color4f(0, 0, 0, 1))+ r.penLiveStrokePaint.setAntiAlias(true)++ r.penHandlePaint = new ck.Paint()+ r.penHandlePaint.setStyle(ck.PaintStyle.Stroke)+ r.penHandlePaint.setStrokeWidth(1)+ r.penHandlePaint.setColor(r.selColor(PARENT_OUTLINE_ALPHA))+ r.penHandlePaint.setAntiAlias(true)++ r.penVertexFill = new ck.Paint()+ r.penVertexFill.setStyle(ck.PaintStyle.Fill)+ r.penVertexFill.setColor(ck.WHITE)+ r.penVertexFill.setAntiAlias(true)++ r.penVertexStroke = new ck.Paint()+ r.penVertexStroke.setStyle(ck.PaintStyle.Stroke)+ r.penVertexStroke.setStrokeWidth(1)+ r.penVertexStroke.setColor(r.selColor())+ r.penVertexStroke.setAntiAlias(true)+}diff --git a/packages/core/src/canvas/renderer/pipeline.ts b/packages/core/src/canvas/renderer/pipeline.tsnew file mode 100644index 000000000..18f682fb1--- /dev/null+++ b/packages/core/src/canvas/renderer/pipeline.ts@@ -0,0 +1,256 @@+import { computeDescendantVisualBounds } from '#core/geometry'++import type { RenderOverlays, SkiaRenderer } from '#core/canvas/renderer'+import type { EditorState } from '#core/editor/types'+import type { SceneGraph } from '#core/scene-graph'+import type { Canvas } from 'canvaskit-wasm'++export function renderSceneToCanvas(+ r: SkiaRenderer,+ canvas: Canvas,+ graph: SceneGraph,+ pageId: string+): void {+ const prevViewport = r.worldViewport+ r.worldViewport = { x: -1e9, y: -1e9, w: 2e9, h: 2e9 }+ const pageNode = graph.getNode(pageId)+ if (pageNode) {+ for (const childId of pageNode.childIds) {+ r.renderNode(canvas, graph, childId, {})+ }+ }+ r.worldViewport = prevViewport+}++export type RenderLayer = 'full' | 'scene' | 'overlays'++export function renderFromEditorState(+ r: SkiaRenderer,+ state: EditorState,+ graph: SceneGraph,+ textEditor: unknown,+ viewportWidth: number,+ viewportHeight: number,+ showRulers = true,+ dpr = 1,+ layer: RenderLayer = 'full'+): void {+ const extendedState = state as EditorState & {+ nodeEditState?: RenderOverlays['nodeEditState']+ }+ r.dpr = dpr+ r.panX = state.panX+ r.panY = state.panY+ r.zoom = state.zoom+ r.viewportWidth = viewportWidth+ r.viewportHeight = viewportHeight+ r.showRulers = showRulers+ r.pageColor = state.pageColor+ r.pageId = state.currentPageId+ render(+ r,+ graph,+ state.selectedIds,+ {+ hoveredNodeId: state.hoveredNodeId,+ enteredContainerId: state.enteredContainerId,+ editingTextId: state.editingTextId,+ textEditor: textEditor as RenderOverlays['textEditor'],+ marquee: state.marquee,+ snapGuides: state.snapGuides,+ rotationPreview: state.rotationPreview,+ dropTargetId: state.dropTargetId,+ layoutInsertIndicator: state.layoutInsertIndicator,+ penState: state.penState+ ? ({+ ...state.penState,+ cursorX: state.penCursorX ?? undefined,+ cursorY: state.penCursorY ?? undefined+ } as RenderOverlays['penState'])+ : null,+ nodeEditState: extendedState.nodeEditState ?? null,+ remoteCursors: state.remoteCursors+ },+ state.sceneVersion,+ layer+ )+}++export function render(+ r: SkiaRenderer,+ graph: SceneGraph,+ selectedIds: Set<string>,+ overlays: RenderOverlays = {},+ sceneVersion = -1,+ layer: RenderLayer = 'full'+): void {+ const p = r.profiler+ p.beginFrame()++ graph.clearAbsPosCache()++ const canvas = r.surface.getCanvas()+ if (layer === 'overlays') {+ canvas.clear(r.ck.Color4f(0, 0, 0, 0))+ } else {+ canvas.clear(r.ck.Color4f(r.pageColor.r, r.pageColor.g, r.pageColor.b, 1))+ }++ r.worldViewport = {+ x: -r.panX / r.zoom,+ y: -r.panY / r.zoom,+ w: r.viewportWidth / r.zoom,+ h: r.viewportHeight / r.zoom+ }++ const hasVolatileOverlays =+ overlays.dropTargetId != null ||+ overlays.rotationPreview != null ||+ overlays.editingTextId != null ||+ overlays.nodeEditState != null++ const canUsePicture =+ !hasVolatileOverlays &&+ r.scenePicture &&+ sceneVersion === r.scenePictureVersion &&+ r.pageId === r.scenePicturePageId++ p.setCacheHit(!!canUsePicture)++ if (layer !== 'overlays') {+ canvas.save()+ canvas.scale(r.dpr, r.dpr)+ canvas.translate(r.panX, r.panY)+ canvas.scale(r.zoom, r.zoom)++ p.beginPhase('render:scene')+ if (canUsePicture) {+ p.beginPhase('render:drawPicture')+ if (r.scenePicture) canvas.drawPicture(r.scenePicture)+ p.endPhase('render:drawPicture')+ } else if (hasVolatileOverlays) {+ r._nodeCount = 0+ r._culledCount = 0+ p.beginPhase('render:volatile')+ renderPageChildren(r, canvas, graph, overlays)+ p.endPhase('render:volatile')+ } else {+ r._nodeCount = 0+ r._culledCount = 0+ p.beginPhase('render:recordPicture')+ recordScenePicture(r, canvas, graph, sceneVersion)+ if (r.scenePicture) canvas.drawPicture(r.scenePicture)+ p.endPhase('render:recordPicture')+ }+ p.endPhase('render:scene')++ canvas.restore()+ }++ if (layer !== 'scene') {+ canvas.save()+ canvas.scale(r.dpr, r.dpr)+ r.labelCache.update(graph, r.pageId, sceneVersion)+ p.beginPhase('render:sectionTitles')+ r.drawSectionTitles(canvas, graph)+ p.endPhase('render:sectionTitles')+ p.beginPhase('render:componentLabels')+ r.drawComponentLabels(canvas, graph)+ p.endPhase('render:componentLabels')+ canvas.restore()++ canvas.save()+ canvas.scale(r.dpr, r.dpr)++ r.drawHoverHighlight(+ canvas,+ graph,+ overlays.hoveredNodeId === overlays.nodeEditState?.nodeId ? null : overlays.hoveredNodeId+ )+ r.drawEnteredContainer(canvas, graph, overlays.enteredContainerId)+ p.beginPhase('render:selection')+ r.drawSelection(canvas, graph, selectedIds, overlays)+ p.endPhase('render:selection')+ r.drawFlashes(canvas, graph)+ r.drawSnapGuides(canvas, overlays.snapGuides)+ r.drawMarquee(canvas, overlays.marquee)+ r.drawLayoutInsertIndicator(canvas, overlays.layoutInsertIndicator)+ r.drawNodeEditOverlay(canvas, graph, overlays.nodeEditState)+ r.drawPenOverlay(canvas, overlays.penState)+ r.drawRemoteCursors(canvas, graph, overlays.remoteCursors)+ p.beginPhase('render:rulers')+ if (r.showRulers) r.drawRulers(canvas, graph, selectedIds)+ p.endPhase('render:rulers')++ p.drawHUD(canvas, r.showRulers)++ canvas.restore()+ }++ p.beginPhase('render:flush')+ r.surface.flush()+ p.endPhase('render:flush')++ p.setNodeCounts(r._nodeCount, r._culledCount)+ p.endFrame()+}++function renderPageChildren(+ r: SkiaRenderer,+ canvas: Canvas,+ graph: SceneGraph,+ overlays: RenderOverlays+): void {+ const pageNode = graph.getNode(r.pageId ?? graph.rootId)+ if (!pageNode) return+ for (const childId of pageNode.childIds) {+ r.renderNode(canvas, graph, childId, overlays)+ }+}++function recordScenePicture(+ r: SkiaRenderer,+ canvas: Canvas,+ graph: SceneGraph,+ sceneVersion: number+): void {+ r.scenePicture?.delete()+ const prevViewport = r.worldViewport+ r.worldViewport = { x: -1e6, y: -1e6, w: 2e6, h: 2e6 }+ const recorder = new r.ck.PictureRecorder()+ const pageNode = graph.getNode(r.pageId ?? graph.rootId)+ const sceneContentBounds = pageNode+ ? computeDescendantVisualBounds(+ pageNode.childIds,+ (id) => graph.getNode(id),+ (id) => graph.getAbsolutePosition(id)+ )+ : null+ const sceneBounds = sceneContentBounds+ ? {+ x: sceneContentBounds.minX,+ y: sceneContentBounds.minY,+ width: sceneContentBounds.maxX - sceneContentBounds.minX,+ height: sceneContentBounds.maxY - sceneContentBounds.minY+ }+ : { x: 0, y: 0, width: 1, height: 1 }+ const padding = 1024+ const bounds = r.ck.LTRBRect(+ sceneBounds.x - padding,+ sceneBounds.y - padding,+ sceneBounds.x + sceneBounds.width + padding,+ sceneBounds.y + sceneBounds.height + padding+ )+ const recCanvas = recorder.beginRecording(bounds)+ if (pageNode) {+ for (const childId of pageNode.childIds) {+ r.renderNode(recCanvas, graph, childId, {})+ }+ }+ r.scenePicture = recorder.finishRecordingAsPicture()+ recorder.delete()+ r.worldViewport = prevViewport+ r.scenePictureVersion = sceneVersion+ r.scenePicturePageId = r.pageId+ canvas.drawPicture(r.scenePicture)+}diff --git a/packages/core/src/canvas/renderer/state.ts b/packages/core/src/canvas/renderer/state.tsnew file mode 100644index 000000000..dfc07d3a8--- /dev/null+++ b/packages/core/src/canvas/renderer/state.ts@@ -0,0 +1,58 @@+import type { SkiaRenderer } from '#core/canvas/renderer'++export function invalidateScenePicture(r: SkiaRenderer): void {+ r.scenePicture?.delete()+ r.scenePicture = null+ r.scenePictureVersion = -1+}++export function invalidateAllPictures(r: SkiaRenderer): void {+ invalidateScenePicture(r)+ for (const pic of r.nodePictureCache.values()) pic?.delete()+ r.nodePictureCache.clear()+}++export function invalidateNodePicture(r: SkiaRenderer, nodeId: string): void {+ const pic = r.nodePictureCache.get(nodeId)+ if (pic) {+ pic.delete()+ r.nodePictureCache.delete(nodeId)+ }+}++export function flashNode(r: SkiaRenderer, nodeId: string): void {+ r._flashes.push({ nodeId, startTime: performance.now() })+}++export function aiMarkActive(r: SkiaRenderer, nodeIds: string[]): void {+ for (const id of nodeIds) r._aiActiveNodes.add(id)+}++export function aiMarkDone(r: SkiaRenderer, nodeIds: string[]): void {+ const now = performance.now()+ for (const id of nodeIds) {+ if (r._aiActiveNodes.delete(id)) {+ r._aiDoneFlashes.push({ nodeId: id, startTime: now })+ }+ }+}++export function aiFlashDone(r: SkiaRenderer, nodeIds: string[]): void {+ const now = performance.now()+ for (const id of nodeIds) {+ r._aiDoneFlashes.push({ nodeId: id, startTime: now })+ }+}++export function aiClearActive(r: SkiaRenderer): void {+ r._aiActiveNodes.clear()+}++export function aiClearAll(r: SkiaRenderer): void {+ r._aiActiveNodes.clear()+ r._aiDoneFlashes = []+}++export function hasActiveFlashes(r: SkiaRenderer): boolean {+ return r._flashes.length > 0 || r._aiActiveNodes.size > 0 || r._aiDoneFlashes.length > 0+}diff --git a/packages/core/src/canvas/renderer/types.ts b/packages/core/src/canvas/renderer/types.tsnew file mode 100644index 000000000..1be8c55bb--- /dev/null+++ b/packages/core/src/canvas/renderer/types.ts@@ -0,0 +1,58 @@+import type { SnapGuide } from '#core/scene-graph/snap'+import type { TextEditor } from '#core/text/editor'+import type { Color, Rect, Vector } from '#core/types'+import type { VectorRegion, VectorVertex } from '#core/scene-graph'++export interface RenderOverlays {+ hoveredNodeId?: string | null+ enteredContainerId?: string | null+ editingTextId?: string | null+ textEditor?: TextEditor | null+ marquee?: Rect | null+ snapGuides?: SnapGuide[]+ rotationPreview?: { nodeId: string; angle: number } | null+ dropTargetId?: string | null+ layoutInsertIndicator?: {+ x: number+ y: number+ length: number+ direction: 'HORIZONTAL' | 'VERTICAL'+ } | null+ penState?: {+ vertices: Vector[]+ segments: Array<{+ start: number+ end: number+ tangentStart: Vector+ tangentEnd: Vector+ }>+ dragTangent: Vector | null+ oppositeDragTangent?: Vector | null+ closingToFirst: boolean+ pendingClose?: boolean+ cursorX?: number+ cursorY?: number+ } | null+ nodeEditState?: {+ nodeId: string+ vertices: VectorVertex[]+ segments: Array<{+ start: number+ end: number+ tangentStart: Vector+ tangentEnd: Vector+ }>+ regions: VectorRegion[]+ selectedVertexIndices: Set<number>+ /** Set of selected handles as "segIdx:tangentField" strings */+ selectedHandles?: Set<string>+ hoveredHandleInfo?: { segmentIndex: number; tangentField: 'tangentStart' | 'tangentEnd' } | null+ } | null+ remoteCursors?: Array<{+ name: string+ color: Color+ x: number+ y: number+ selection?: string[]+ }>+}diff --git a/packages/core/src/canvas/rulers.ts b/packages/core/src/canvas/rulers.tsindex 27975461a..f498983c4 100644--- a/packages/core/src/canvas/rulers.ts+++ b/packages/core/src/canvas/rulers.ts@@ -10,10 +10,10 @@ import {RULER_HIGHLIGHT_ALPHA,RULER_TARGET_PIXEL_SPACING,RULER_MAJOR_TOLERANCE-} from '../constants'-import { computeAbsoluteBounds } from '../geometry'+} from '#core/constants'+import { computeAbsoluteBounds } from '#core/geometry'-import type { SceneNode, SceneGraph } from '../scene-graph'+import type { SceneNode, SceneGraph } from '#core/scene-graph'import type { SkiaRenderer } from './renderer'import type { Canvas, CanvasKit } from 'canvaskit-wasm'diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.tsindex 7f99dfdc7..61902e8e7 100644--- a/packages/core/src/canvas/scene.ts+++ b/packages/core/src/canvas/scene.ts@@ -1,10 +1,28 @@-import { DROP_HIGHLIGHT_ALPHA, DROP_HIGHLIGHT_STROKE, SECTION_CORNER_RADIUS } from '../constants'+import { DROP_HIGHLIGHT_ALPHA, DROP_HIGHLIGHT_STROKE, SECTION_CORNER_RADIUS } from '#core/constants'-import type { SceneNode, SceneGraph } from '../scene-graph'-import type { Color } from '../types'+import { nodeHasRadius } from './effects'++import type { SceneNode, SceneGraph } from '#core/scene-graph'+import type { Color } from '#core/types'import type { SkiaRenderer, RenderOverlays } from './renderer'import type { Canvas, EmbindEnumEntity, Path } from 'canvaskit-wasm'+function drawVisibleFills(+ r: SkiaRenderer,+ node: SceneNode,+ graph: SceneGraph,+ draw: () => void+): void {+ for (let fi = 0; fi < node.fills.length; fi++) {+ const fill = node.fills[fi]+ if (!fill.visible) continue+ if (!r.applyFill(fill, node, graph, fi)) continue+ r.fillPaint.setAlphaf(fill.opacity)+ draw()+ r.fillPaint.setShader(null)+ }+}+function isCulled(r: SkiaRenderer, node: SceneNode, absX: number, absY: number): boolean {const canCull =node.childIds.length === 0 ||@@ -163,38 +181,45 @@ export function renderNode(canvas.restore()}+function makeNodeRRect(r: SkiaRenderer, node: SceneNode, radius: number): Float32Array {+ const rect = r.ck.LTRBRect(0, 0, node.width, node.height)+ return r.ck.RRectXY(rect, radius, radius)+}++function forVisibleStrokes(+ r: SkiaRenderer,+ node: SceneNode,+ graph: SceneGraph,+ draw: (+ stroke: SceneNode['strokes'][number],+ color: Color+ ) => void+): void {+ for (let index = 0; index < node.strokes.length; index++) {+ const stroke = node.strokes[index]+ if (!stroke.visible) continue+ draw(stroke, r.resolveStrokeColor(stroke, index, node, graph))+ }+}+export function renderSection(r: SkiaRenderer,canvas: Canvas,node: SceneNode,graph: SceneGraph): void {- const rect = r.ck.LTRBRect(0, 0, node.width, node.height)- const rrect = r.ck.RRectXY(rect, SECTION_CORNER_RADIUS, SECTION_CORNER_RADIUS)+ const rrect = makeNodeRRect(r, node, SECTION_CORNER_RADIUS)- for (let fi = 0; fi < node.fills.length; fi++) {- const fill = node.fills[fi]- if (!fill.visible) continue- if (!r.applyFill(fill, node, graph, fi)) continue- r.fillPaint.setAlphaf(fill.opacity)- canvas.drawRRect(rrect, r.fillPaint)- r.fillPaint.setShader(null)- }+ drawVisibleFills(r, node, graph, () => canvas.drawRRect(rrect, r.fillPaint))- for (let si = 0; si < node.strokes.length; si++) {- const stroke = node.strokes[si]- if (!stroke.visible) continue- const sc = r.resolveStrokeColor(stroke, si, node, graph)- r.strokePaint.setColor(r.ck.Color4f(sc.r, sc.g, sc.b, sc.a))+ forVisibleStrokes(r, node, graph, (stroke, color) => {+ r.strokePaint.setColor(r.ck.Color4f(color.r, color.g, color.b, color.a))r.strokePaint.setStrokeWidth(stroke.weight)r.strokePaint.setAlphaf(stroke.opacity)- if (node.independentStrokeWeights) {- r.drawIndividualSideStrokes(canvas, node, stroke.align)- } else {- r.drawRRectStrokeWithAlign(canvas, rrect, node, stroke)- }- }+ if (node.independentStrokeWeights) r.drawIndividualSideStrokes(canvas, node, stroke.align)+ else r.drawRRectStrokeWithAlign(canvas, rrect, node, stroke)+ })}export function renderComponentSet(@@ -203,17 +228,9 @@ export function renderComponentSet(node: SceneNode,graph: SceneGraph): void {- const rect = r.ck.LTRBRect(0, 0, node.width, node.height)- const rrect = r.ck.RRectXY(rect, 5, 5)+ const rrect = makeNodeRRect(r, node, 5)- for (let fi = 0; fi < node.fills.length; fi++) {- const fill = node.fills[fi]- if (!fill.visible) continue- if (!r.applyFill(fill, node, graph, fi)) continue- r.fillPaint.setAlphaf(fill.opacity)- canvas.drawRRect(rrect, r.fillPaint)- r.fillPaint.setShader(null)- }+ drawVisibleFills(r, node, graph, () => canvas.drawRRect(rrect, r.fillPaint))r.auxStroke.setStrokeWidth(r.COMPONENT_SET_BORDER_WIDTH / r.zoom)r.auxStroke.setColor(r.compColor())@@ -253,17 +270,6 @@ export function renderShape(}}-function nodeHasRadius(node: SceneNode): boolean {- return (- node.cornerRadius > 0 ||- (node.independentCorners &&- (node.topLeftRadius > 0 ||- node.topRightRadius > 0 ||- node.bottomRightRadius > 0 ||- node.bottomLeftRadius > 0))- )-}-/*** When a container has no visible fills, Figma renders drop shadows* using the shape of its children rather than its own rectangle.@@ -456,25 +462,14 @@ export function renderShapeUncached(const shadowChild = getShadowShapeChild(node, graph)r.renderEffects(canvas, node, rect, hasRadius, 'behind', shadowChild)- for (let fi = 0; fi < node.fills.length; fi++) {- const fill = node.fills[fi]- if (!fill.visible) continue- if (!r.applyFill(fill, node, graph, fi)) continue- r.fillPaint.setAlphaf(fill.opacity)- r.drawNodeFill(canvas, node, rect, hasRadius)- r.fillPaint.setShader(null)- }+ drawVisibleFills(r, node, graph, () => r.drawNodeFill(canvas, node, rect, hasRadius))const sg = node.strokeGeometry.length > 0 ? r.getStrokeGeometry(node) : nullconst vectorPaths = node.type === 'VECTOR' ? r.getVectorPaths(node) : nullconst vectorStroke = node.type === 'VECTOR' ? vectorStrokePaths(r, node) : null- for (let si = 0; si < node.strokes.length; si++) {- const stroke = node.strokes[si]- if (!stroke.visible) continue- const sc = r.resolveStrokeColor(stroke, si, node, graph)-- drawNodeStroke(r, canvas, node, rect, hasRadius, stroke, sc, sg, vectorPaths, vectorStroke)- }+ forVisibleStrokes(r, node, graph, (stroke, color) => {+ drawNodeStroke(r, canvas, node, rect, hasRadius, stroke, color, sg, vectorPaths, vectorStroke)+ })if (vectorStroke) {for (const path of vectorStroke) path.delete()}@@ -482,173 +477,6 @@ export function renderShapeUncached(r.renderEffects(canvas, node, rect, hasRadius, 'front')}-function drawShapeDropShadow(- r: SkiaRenderer,- canvas: Canvas,- node: SceneNode,- effect: SceneNode['effects'][number],- hasRadius: boolean,- shadowShapeChild?: SceneNode | null-): void {- const sp = effect.spread- const shapeNode = shadowShapeChild ?? node- const shapeHasRadius = shadowShapeChild ? nodeHasRadius(shadowShapeChild) : hasRadius- const strokeShadow =- !shadowShapeChild && !node.fills.some((fill) => fill.visible) && node.strokeGeometry.length > 0- ? r.getStrokeGeometry(node)- : null-- r.auxFill.setColor(r.color4f(effect.color.r, effect.color.g, effect.color.b, effect.color.a))- r.auxFill.setMaskFilter(r.getCachedMaskBlur(effect.radius / 2))- r.auxFill.setImageFilter(null)- canvas.save()- canvas.translate(- effect.offset.x + (shadowShapeChild?.x ?? 0),- effect.offset.y + (shadowShapeChild?.y ?? 0)- )- if (strokeShadow) {- for (const path of strokeShadow) canvas.drawPath(path, r.auxFill)- } else if (shapeNode.type === 'ELLIPSE') {- canvas.drawOval(r.ltrb(-sp, -sp, shapeNode.width + sp, shapeNode.height + sp), r.auxFill)- } else if (shapeHasRadius) {- canvas.drawRRect(r.makeRRectWithSpread(shapeNode, sp), r.auxFill)- } else {- canvas.drawRect(r.ltrb(-sp, -sp, shapeNode.width + sp, shapeNode.height + sp), r.auxFill)- }- canvas.restore()- r.auxFill.setMaskFilter(null)-}--function renderDropShadow(- r: SkiaRenderer,- canvas: Canvas,- node: SceneNode,- effect: SceneNode['effects'][number],- hasRadius: boolean,- shadowShapeChild?: SceneNode | null-): void {- if (node.type !== 'TEXT') {- drawShapeDropShadow(r, canvas, node, effect, hasRadius, shadowShapeChild)- return- }-- const shadowColor = r.ck.Color4f(effect.color.r, effect.color.g, effect.color.b, effect.color.a)- const dropFilter = r.getCachedDropShadow(- effect.offset.x,- effect.offset.y,- effect.radius / 2,- shadowColor- )- r.effectLayerPaint.setImageFilter(dropFilter)- canvas.saveLayer(r.effectLayerPaint)- r.renderText(canvas, node)- canvas.restore()-}--export function renderEffects(- r: SkiaRenderer,- canvas: Canvas,- node: SceneNode,- rect: Float32Array,- hasRadius: boolean,- pass: 'behind' | 'front',- shadowShapeChild?: SceneNode | null-): void {- for (const effect of node.effects) {- if (!effect.visible) continue-- if (pass === 'behind' && effect.type === 'DROP_SHADOW') {- renderDropShadow(r, canvas, node, effect, hasRadius, shadowShapeChild)- }-- if (pass === 'behind' && effect.type === 'BACKGROUND_BLUR') {- r.applyClippedBlur(canvas, node, rect, hasRadius, effect.radius / 2)- }-- if (pass === 'front' && effect.type === 'INNER_SHADOW') {- if (node.type === 'TEXT') {- r.effectLayerPaint.setImageFilter(r.getCachedDecalBlur(effect.radius))- r.effectLayerPaint.setColorFilter(- r.ck.ColorFilter.MakeBlend(- r.ck.Color4f(effect.color.r, effect.color.g, effect.color.b, effect.color.a),- r.ck.BlendMode.SrcIn- )- )- canvas.saveLayer(r.effectLayerPaint)- canvas.save()- canvas.translate(effect.offset.x, effect.offset.y)- r.renderText(canvas, node)- canvas.restore()- canvas.restore()- r.effectLayerPaint.setColorFilter(null)- continue- }- const sp = effect.spread- r.auxFill.setColor(- r.ck.Color4f(effect.color.r, effect.color.g, effect.color.b, effect.color.a)- )- r.auxFill.setImageFilter(r.getCachedDecalBlur(effect.radius))-- canvas.save()- if (node.type === 'ELLIPSE') {- const path = new r.ck.Path()- path.addOval(rect)- canvas.clipPath(path, r.ck.ClipOp.Intersect, true)- path.delete()- } else if (hasRadius) {- canvas.clipRRect(r.makeRRect(node), r.ck.ClipOp.Intersect, true)- } else {- canvas.clipRect(rect, r.ck.ClipOp.Intersect, true)- }-- const expand = effect.radius * 2- const big = r.ck.LTRBRect(- -expand + effect.offset.x,- -expand + effect.offset.y,- node.width + expand + effect.offset.x,- node.height + expand + effect.offset.y- )- const bigPath = new r.ck.Path()- bigPath.addRect(big)- if (node.type === 'ELLIPSE') {- const innerPath = new r.ck.Path()- const offsetRect = r.ck.LTRBRect(- effect.offset.x + sp,- effect.offset.y + sp,- node.width + effect.offset.x - sp,- node.height + effect.offset.y - sp- )- innerPath.addOval(offsetRect)- bigPath.op(innerPath, r.ck.PathOp.Difference)- innerPath.delete()- } else if (hasRadius) {- const innerPath = new r.ck.Path()- innerPath.addRRect(- r.makeRRectWithOffset(node, effect.offset.x + sp, effect.offset.y + sp, -sp)- )- bigPath.op(innerPath, r.ck.PathOp.Difference)- innerPath.delete()- } else {- const innerPath = new r.ck.Path()- innerPath.addRect(- r.ck.LTRBRect(- effect.offset.x + sp,- effect.offset.y + sp,- node.width + effect.offset.x - sp,- node.height + effect.offset.y - sp- )- )- bigPath.op(innerPath, r.ck.PathOp.Difference)- innerPath.delete()- }- canvas.drawPath(bigPath, r.auxFill)- bigPath.delete()- canvas.restore()- r.auxFill.setImageFilter(null)- }- }-}-export function renderText(r: SkiaRenderer, canvas: Canvas, node: SceneNode): void {const text = node.textif (!text) returndiff --git a/packages/core/src/canvas/selection-labels.ts b/packages/core/src/canvas/selection-labels.tsindex dd1c4966f..6f3d98292 100644--- a/packages/core/src/canvas/selection-labels.ts+++ b/packages/core/src/canvas/selection-labels.ts@@ -1,4 +1,4 @@-import { getAbsolutePosition, getWorldMatrix } from '../canvas/coordinate'+import { getAbsolutePosition, getWorldMatrix } from '#core/canvas/coordinate'import {LABEL_OFFSET_Y,SIZE_PILL_PADDING_X,@@ -6,10 +6,10 @@ import {SIZE_PILL_HEIGHT,SIZE_PILL_RADIUS,SIZE_PILL_TEXT_OFFSET_Y-} from '../constants'-import { rotatedCorners } from '../geometry'+} from '#core/constants'+import { rotatedCorners } from '#core/geometry'-import type { SceneNode, SceneGraph } from '../scene-graph'+import type { SceneNode, SceneGraph } from '#core/scene-graph'import type { SkiaRenderer, RenderOverlays } from './renderer'import type { Canvas } from 'canvaskit-wasm'@@ -90,6 +90,44 @@ function drawSingleFrameTitle(canvas.restore()}+function measureTextWidth(sizeFont: NonNullable<SkiaRenderer['sizeFont']>, text: string): number {+ const glyphIds = sizeFont.getGlyphIDs(text)+ const widths = sizeFont.getGlyphWidths(glyphIds)+ let textWidth = 0+ for (const width of widths) textWidth += width+ return textWidth+}++function drawSizePill(+ r: SkiaRenderer,+ canvas: Canvas,+ sizeFont: NonNullable<SkiaRenderer['sizeFont']>,+ text: string,+ x: number,+ y: number,+ color: ReturnType<SkiaRenderer['selColor']>+): void {+ const pillW = measureTextWidth(sizeFont, text) + SIZE_PILL_PADDING_X * 2+ const pillX = x - pillW / 2+ const pillY = y + SIZE_PILL_PADDING_Y+ r.auxFill.setColor(color)+ const rrect = r.ck.RRectXY(+ r.ck.LTRBRect(pillX, pillY, pillX + pillW, pillY + SIZE_PILL_HEIGHT),+ SIZE_PILL_RADIUS,+ SIZE_PILL_RADIUS+ )+ canvas.drawRRect(rrect, r.auxFill)++ r.auxFill.setColor(r.ck.WHITE)+ canvas.drawText(+ text,+ pillX + SIZE_PILL_PADDING_X,+ pillY + SIZE_PILL_TEXT_OFFSET_Y,+ r.auxFill,+ sizeFont+ )+}+export function drawSingleSelectionSize(r: SkiaRenderer,canvas: Canvas,@@ -99,13 +137,6 @@ export function drawSingleSelectionSize(sizeFont: NonNullable<SkiaRenderer['sizeFont']>): void {const sizeText = `${Math.round(node.width)} × ${Math.round(node.height)}`- const glyphIds = sizeFont.getGlyphIDs(sizeText)- const widths = sizeFont.getGlyphWidths(glyphIds)- let textWidth = 0- for (const w of widths) textWidth += w-- const pillW = textWidth + SIZE_PILL_PADDING_X * 2- const pillH = SIZE_PILL_HEIGHTconst pillColor = r.isComponentType(node.type) ? r.compColor() : r.selColor()const overlayRotation = getOverlayRotation(node, overlays)@@ -123,25 +154,7 @@ export function drawSingleSelectionSize(const sx = bottomCenterX * r.zoom + r.panXconst sy = bottomCenterY * r.zoom + r.panY- const pillX = sx - pillW / 2- const pillY = sy + SIZE_PILL_PADDING_Y-- r.auxFill.setColor(pillColor)- const rrect = r.ck.RRectXY(- r.ck.LTRBRect(pillX, pillY, pillX + pillW, pillY + pillH),- SIZE_PILL_RADIUS,- SIZE_PILL_RADIUS- )- canvas.drawRRect(rrect, r.auxFill)-- r.auxFill.setColor(r.ck.WHITE)- canvas.drawText(- sizeText,- pillX + SIZE_PILL_PADDING_X,- pillY + SIZE_PILL_TEXT_OFFSET_Y,- r.auxFill,- sizeFont- )+ drawSizePill(r, canvas, sizeFont, sizeText, sx, sy, pillColor)}function drawMultiSelectionSize(r: SkiaRenderer,@@ -154,37 +167,14 @@ function drawMultiSelectionSize(sizeFont: NonNullable<SkiaRenderer['sizeFont']>): void {const sizeText = `${Math.round(maxX - minX)} × ${Math.round(maxY - minY)}`- const glyphIds = sizeFont.getGlyphIDs(sizeText)- const widths = sizeFont.getGlyphWidths(glyphIds)- let textWidth = 0- for (const width of widths) textWidth += width- const pillW = textWidth + SIZE_PILL_PADDING_X * 2- const pillH = SIZE_PILL_HEIGHTconst sx1 = minX * r.zoom + r.panXconst sx2 = maxX * r.zoom + r.panXconst sy2 = maxY * r.zoom + r.panYconst smx = (sx1 + sx2) / 2- const pillX = smx - pillW / 2- const pillY = sy2 + SIZE_PILL_PADDING_Yconst allComponents = nodes.length > 0 && nodes.every((n) => r.isComponentType(n.type))const pillColor = allComponents ? r.compColor() : r.selColor()- r.auxFill.setColor(pillColor)- const rrect = r.ck.RRectXY(- r.ck.LTRBRect(pillX, pillY, pillX + pillW, pillY + pillH),- SIZE_PILL_RADIUS,- SIZE_PILL_RADIUS- )- canvas.drawRRect(rrect, r.auxFill)-- r.auxFill.setColor(r.ck.WHITE)- canvas.drawText(- sizeText,- pillX + SIZE_PILL_PADDING_X,- pillY + SIZE_PILL_TEXT_OFFSET_Y,- r.auxFill,- sizeFont- )+ drawSizePill(r, canvas, sizeFont, sizeText, smx, sy2, pillColor)}export function drawSelectionLabels(diff --git a/packages/core/src/canvas/shapes.ts b/packages/core/src/canvas/shapes.tsindex c05614879..c9a5471a1 100644--- a/packages/core/src/canvas/shapes.ts+++ b/packages/core/src/canvas/shapes.ts@@ -1,6 +1,7 @@-import { vectorNetworkToPath, geometryBlobToPath } from '../vector'+import { polygonVertices } from '#core/geometry'+import { vectorNetworkToPath, geometryBlobToPath } from '#core/vector'-import type { SceneNode } from '../scene-graph'+import type { SceneNode } from '#core/scene-graph'import type { SkiaRenderer } from './renderer'import type { Canvas, Path } from 'canvaskit-wasm'@@ -41,25 +42,10 @@ export function makeNodeShapePath(export function makePolygonPath(r: SkiaRenderer, node: SceneNode): Path {const path = new r.ck.Path()- const cx = node.width / 2- const cy = node.height / 2- const rx = node.width / 2- const ry = node.height / 2- const n = Math.max(3, node.pointCount)- const isStar = node.type === 'STAR'- const innerRatio = isStar ? node.starInnerRadius : 1- const totalPoints = isStar ? n * 2 : n- const angleOffset = -Math.PI / 2-- for (let i = 0; i < totalPoints; i++) {- const angle = angleOffset + (2 * Math.PI * i) / totalPoints- const isInner = isStar && i % 2 === 1- const rad = isInner ? innerRatio : 1- const px = cx + rx * rad * Math.cos(angle)- const py = cy + ry * rad * Math.sin(angle)- if (i === 0) path.moveTo(px, py)- else path.lineTo(px, py)- }+ polygonVertices(node).forEach((point, index) => {+ if (index === 0) path.moveTo(point.x, point.y)+ else path.lineTo(point.x, point.y)+ })path.close()return path}diff --git a/packages/core/src/canvas/strokes.ts b/packages/core/src/canvas/strokes.tsindex 375866d4d..8e45b907f 100644--- a/packages/core/src/canvas/strokes.ts+++ b/packages/core/src/canvas/strokes.ts@@ -1,4 +1,4 @@-import type { SceneNode, Stroke } from '../scene-graph'+import type { SceneNode, Stroke } from '#core/scene-graph'import type { SkiaRenderer } from './renderer'import type { Canvas, Paint } from 'canvaskit-wasm'diff --git a/packages/core/src/canvas/text.ts b/packages/core/src/canvas/text.tsindex 10008896f..1ce294834 100644--- a/packages/core/src/canvas/text.ts+++ b/packages/core/src/canvas/text.ts@@ -1,15 +1,15 @@-import { getCanvasKit } from '../canvaskit'-import { resolveRGBAForPreview } from '../color/management'-import { DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE } from '../constants'-import { resolveNodeTextDirection } from '../text/direction'+import { getCanvasKit } from '#core/canvaskit'+import { resolveRGBAForPreview } from '#core/color/management'+import { DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE } from '#core/constants'+import { resolveNodeTextDirection } from '#core/text/direction'import {getArabicFallbackFamilies,getCJKFallbackFamilies,getFontProvider,isFontLoaded-} from '../text/fonts'+} from '#core/text/fonts'-import type { SceneNode } from '../scene-graph'+import type { SceneNode } from '#core/scene-graph'import type { CanvasKit, FontWeight, Paragraph, TypefaceFontProvider } from 'canvaskit-wasm'interface TextRenderer {diff --git a/packages/core/src/clipboard.ts b/packages/core/src/clipboard.tsindex ed58ff821..e45b66ec2 100644--- a/packages/core/src/clipboard.ts+++ b/packages/core/src/clipboard.ts@@ -1,9 +1,9 @@import { inflateSync, deflateSync } from 'fflate'-import { initCodec, getCompiledSchema, getSchemaBytes } from './kiwi/codec'-import { nodeChangeToProps, sortChildren } from './kiwi/convert'+import { initCodec, getCompiledSchema, getSchemaBytes } from './kiwi/binary/codec'import { populateAndApplyOverrides } from './kiwi/instance-overrides'import { decodeBinarySchema, compileSchema, ByteBuffer } from './kiwi/kiwi-schema'+import { nodeChangeToProps, sortChildren } from './kiwi/node-change/convert'import {sceneNodeToKiwi,buildFigKiwi,@@ -12,11 +12,11 @@ import {makeDocumentNodeChange,makeCanvasNodeChange,buildFontDigestMap-} from './kiwi/serialize'+} from './kiwi/node-change/serialize'import { randomInt } from './random'import { buildDerivedTextDataV4 } from './text/clipboard-derived-text'-import type { NodeChange as KiwiNodeChange } from './kiwi/codec'+import type { NodeChange as KiwiNodeChange } from './kiwi/binary/codec'import type { InstanceNodeChange } from './kiwi/instance-overrides'import type { SceneGraph, SceneNode } from './scene-graph'@@ -376,111 +376,9 @@ export async function buildFigmaClipboardHTML()}-// --- Internal copy/paste (OpenPencil ↔ OpenPencil) -----export interface OpenPencilClipboardData {- nodes: Array<SceneNode & { children?: SceneNode[] }>- images: Map<string, Uint8Array>-}--export function parseOpenPencilClipboard(html: string): OpenPencilClipboardData | null {- const match = html.match(/<!--\(openpencil\)(.*?)\(\/openpencil\)-->/s)- if (!match) return null-- try {- const raw = Uint8Array.fromBase64(match[1])- let bytes: Uint8Array- try {- bytes = inflateSync(raw)- } catch {- bytes = raw- }- const decoded = JSON.parse(new TextDecoder().decode(bytes))- if (decoded.format === 'openpencil/v1' && Array.isArray(decoded.nodes)) {- restoreTextPictures(decoded.nodes)- const images = new Map<string, Uint8Array>()- if (decoded.images && typeof decoded.images === 'object') {- for (const [hash, b64] of Object.entries(decoded.images)) {- if (typeof b64 === 'string') {- images.set(hash, Uint8Array.fromBase64(b64))- }- }- }- return { nodes: decoded.nodes, images }- }- } catch (e) {- console.warn('Failed to parse OpenPencil clipboard data:', e)- }- return null-}--function restoreTextPictures(nodes: Array<Record<string, unknown>>): void {- for (const node of nodes) {- if (typeof node.textPicture === 'string') {- node.textPicture = Uint8Array.fromBase64(node.textPicture)- }- if (Array.isArray(node.children)) {- restoreTextPictures(node.children)- }- }-}--export type TextPictureBuilder = (node: SceneNode) => Uint8Array | null--function collectImageHashes(nodes: SceneNode[], graph: SceneGraph): Set<string> {- const hashes = new Set<string>()- function walk(nodeList: SceneNode[]) {- for (const node of nodeList) {- for (const fill of node.fills) {- if (fill.imageHash) hashes.add(fill.imageHash)- }- walk(graph.getChildren(node.id))- }- }- walk(nodes)- return hashes-}--export function buildOpenPencilClipboardHTML(- nodes: SceneNode[],- graph: SceneGraph,- textPictureBuilder?: TextPictureBuilder-): string {- const nodeTree = collectNodeTree(nodes, graph, textPictureBuilder)- const hashes = collectImageHashes(nodes, graph)- const images: Record<string, string> = {}- for (const hash of hashes) {- const bytes = graph.images.get(hash)- if (bytes) images[hash] = bytes.toBase64()- }- const data = {- format: 'openpencil/v1',- nodes: nodeTree,- images- }- const compressed = deflateSync(new TextEncoder().encode(JSON.stringify(data)))- return `<!--(openpencil)${compressed.toBase64()}(/openpencil)-->`-}--function collectNodeTree(- nodes: SceneNode[],- graph: SceneGraph,- textPictureBuilder?: TextPictureBuilder-): Array<Record<string, unknown>> {- return nodes.map((node) => {- const children = graph.getChildren(node.id)- const serialized: Record<string, unknown> = { ...node }-- if (node.type === 'TEXT' && node.text && textPictureBuilder) {- const pic = node.textPicture ?? textPictureBuilder(node)- if (pic) serialized.textPicture = pic.toBase64()- } else {- delete serialized.textPicture- }-- if (children.length > 0) {- serialized.children = collectNodeTree(children, graph, textPictureBuilder)- }- return serialized- })-}+export {+ buildOpenPencilClipboardHTML,+ parseOpenPencilClipboard,+ type OpenPencilClipboardData,+ type TextPictureBuilder+} from './clipboard/openpencil'diff --git a/packages/core/src/clipboard/openpencil.ts b/packages/core/src/clipboard/openpencil.tsnew file mode 100644index 000000000..adf760d08--- /dev/null+++ b/packages/core/src/clipboard/openpencil.ts@@ -0,0 +1,112 @@+import { deflateSync, inflateSync } from 'fflate'++import type { SceneGraph, SceneNode } from '#core/scene-graph'++// --- Internal copy/paste (OpenPencil ↔ OpenPencil) ---++export interface OpenPencilClipboardData {+ nodes: Array<SceneNode & { children?: SceneNode[] }>+ images: Map<string, Uint8Array>+}++export function parseOpenPencilClipboard(html: string): OpenPencilClipboardData | null {+ const match = html.match(/<!--\(openpencil\)(.*?)\(\/openpencil\)-->/s)+ if (!match) return null++ try {+ const raw = Uint8Array.fromBase64(match[1])+ let bytes: Uint8Array+ try {+ bytes = inflateSync(raw)+ } catch {+ bytes = raw+ }+ const decoded = JSON.parse(new TextDecoder().decode(bytes))+ if (decoded.format === 'openpencil/v1' && Array.isArray(decoded.nodes)) {+ restoreTextPictures(decoded.nodes)+ const images = new Map<string, Uint8Array>()+ if (decoded.images && typeof decoded.images === 'object') {+ for (const [hash, b64] of Object.entries(decoded.images)) {+ if (typeof b64 === 'string') {+ images.set(hash, Uint8Array.fromBase64(b64))+ }+ }+ }+ return { nodes: decoded.nodes, images }+ }+ } catch (e) {+ console.warn('Failed to parse OpenPencil clipboard data:', e)+ }+ return null+}++function restoreTextPictures(nodes: Array<Record<string, unknown>>): void {+ for (const node of nodes) {+ if (typeof node.textPicture === 'string') {+ node.textPicture = Uint8Array.fromBase64(node.textPicture)+ }+ if (Array.isArray(node.children)) {+ restoreTextPictures(node.children)+ }+ }+}++export type TextPictureBuilder = (node: SceneNode) => Uint8Array | null++function collectImageHashes(nodes: SceneNode[], graph: SceneGraph): Set<string> {+ const hashes = new Set<string>()+ function walk(nodeList: SceneNode[]) {+ for (const node of nodeList) {+ for (const fill of node.fills) {+ if (fill.imageHash) hashes.add(fill.imageHash)+ }+ walk(graph.getChildren(node.id))+ }+ }+ walk(nodes)+ return hashes+}++export function buildOpenPencilClipboardHTML(+ nodes: SceneNode[],+ graph: SceneGraph,+ textPictureBuilder?: TextPictureBuilder+): string {+ const nodeTree = collectNodeTree(nodes, graph, textPictureBuilder)+ const hashes = collectImageHashes(nodes, graph)+ const images: Record<string, string> = {}+ for (const hash of hashes) {+ const bytes = graph.images.get(hash)+ if (bytes) images[hash] = bytes.toBase64()+ }+ const data = {+ format: 'openpencil/v1',+ nodes: nodeTree,+ images+ }+ const compressed = deflateSync(new TextEncoder().encode(JSON.stringify(data)))+ return `<!--(openpencil)${compressed.toBase64()}(/openpencil)-->`+}++function collectNodeTree(+ nodes: SceneNode[],+ graph: SceneGraph,+ textPictureBuilder?: TextPictureBuilder+): Array<Record<string, unknown>> {+ return nodes.map((node) => {+ const children = graph.getChildren(node.id)+ const serialized: Record<string, unknown> = { ...node }++ if (node.type === 'TEXT' && node.text && textPictureBuilder) {+ const pic = node.textPicture ?? textPictureBuilder(node)+ if (pic) serialized.textPicture = pic.toBase64()+ } else {+ delete serialized.textPicture+ }++ if (children.length > 0) {+ serialized.children = collectNodeTree(children, graph, textPictureBuilder)+ }+ return serialized+ })+}diff --git a/packages/core/src/color/index.ts b/packages/core/src/color/index.tsindex 976f6d616..f211fe973 100644--- a/packages/core/src/color/index.ts+++ b/packages/core/src/color/index.ts@@ -1,8 +1,12 @@+export * from './management'+export { normalizeColor } from './normalize'+export * from './okhcl'+import { parse, formatHex, formatHex8, formatRgb, converter, differenceEuclidean } from 'culori'-import { BLACK } from '../constants'+import { BLACK } from '#core/constants'-import type { Color } from '../types'+import type { Color } from '#core/types'const toRgb = converter('rgb')@@ -18,11 +22,6 @@ export function parseColor(input: string): Color {}}-export function normalizeColor(color?: Partial<Color>): Color {- if (!color) return { ...BLACK }- return { r: color.r ?? 0, g: color.g ?? 0, b: color.b ?? 0, a: color.a ?? 1 }-}-export function colorToHex(color: Color): string {return formatHex({ mode: 'rgb', r: color.r, g: color.g, b: color.b }).toUpperCase()}diff --git a/packages/core/src/color/management.ts b/packages/core/src/color/management.tsindex 7d34bbd1d..429b207a1 100644--- a/packages/core/src/color/management.ts+++ b/packages/core/src/color/management.ts@@ -1,10 +1,10 @@import { converter, formatCss, formatRgb, inGamut, toGamut } from 'culori'-import { normalizeColor } from './'+import { normalizeColor } from './normalize'import { getFillOkHCL, getStrokeOkHCL, type OkHCLColor } from './okhcl'-import type { DocumentColorSpace, Fill, SceneNode, Stroke } from '../scene-graph'-import type { Color } from '../types'+import type { DocumentColorSpace, Fill, SceneNode, Stroke } from '#core/scene-graph'+import type { Color } from '#core/types'export type RenderColorSpace = 'srgb' | 'display-p3'export type ColorIntentSpace = 'oklch' | 'srgb'diff --git a/packages/core/src/color/normalize.ts b/packages/core/src/color/normalize.tsnew file mode 100644index 000000000..5762c508e--- /dev/null+++ b/packages/core/src/color/normalize.ts@@ -0,0 +1,8 @@+import { BLACK } from '#core/constants'++import type { Color } from '#core/types'++export function normalizeColor(color?: Partial<Color>): Color {+ if (!color) return { ...BLACK }+ return { r: color.r ?? 0, g: color.g ?? 0, b: color.b ?? 0, a: color.a ?? 1 }+}diff --git a/packages/core/src/color/okhcl.ts b/packages/core/src/color/okhcl.tsindex 45db7a35c..27e3b06bc 100644--- a/packages/core/src/color/okhcl.ts+++ b/packages/core/src/color/okhcl.ts@@ -1,10 +1,10 @@import { converter, toGamut } from 'culori'-import { copyFill, copyStroke } from '../scene-graph/copy'-import { normalizeColor } from './'+import { copyFill, copyStroke } from '#core/scene-graph/copy'+import { normalizeColor } from './normalize'-import type { SceneNode } from '../scene-graph'-import type { Color } from '../types'+import type { SceneNode } from '#core/scene-graph'+import type { Color } from '#core/types'export interface OkHCLColor {h: numberdiff --git a/packages/core/src/design-jsx/index.ts b/packages/core/src/design-jsx/index.tsindex 00c1c4fbe..4236f9896 100644--- a/packages/core/src/design-jsx/index.ts+++ b/packages/core/src/design-jsx/index.ts@@ -33,4 +33,5 @@ export { createElement } from './mini-react'export { renderJSX, renderTreeNode, buildComponent } from './render'-export { sceneNodeToJSX, selectionToJSX, type JSXFormat } from '../io/formats/jsx'+export { sceneNodeToJSX, selectionToJSX, type JSXFormat } from '#core/io/formats/jsx'+export { default as JSX_REFERENCE } from '#core/tools/prompts/jsx-reference.md'diff --git a/packages/core/src/design-jsx/props-overrides.ts b/packages/core/src/design-jsx/props-overrides.tsnew file mode 100644index 000000000..7e14858ed--- /dev/null+++ b/packages/core/src/design-jsx/props-overrides.ts@@ -0,0 +1,454 @@+import { colorToFill, parseColor } from '#core/color'+import { TRANSPARENT } from '#core/constants'++import type { GridTrack, LayoutMode, SceneNode, Stroke } from '#core/scene-graph'++const WEIGHT_MAP: Record<string, number> = {+ normal: 400,+ medium: 500,+ bold: 700+}++const ALIGN_MAP: Record<string, SceneNode['primaryAxisAlign']> = {+ start: 'MIN',+ end: 'MAX',+ center: 'CENTER',+ between: 'SPACE_BETWEEN'+}++const COUNTER_ALIGN_MAP: Record<string, 'MIN' | 'MAX' | 'CENTER' | 'STRETCH'> = {+ start: 'MIN',+ end: 'MAX',+ center: 'CENTER',+ stretch: 'STRETCH'+}++const TEXT_ALIGN_MAP: Record<string, SceneNode['textAlignHorizontal']> = {+ left: 'LEFT',+ center: 'CENTER',+ right: 'RIGHT',+ justified: 'JUSTIFIED'+}++const TEXT_AUTO_RESIZE_MAP: Record<string, SceneNode['textAutoResize']> = {+ none: 'NONE',+ width: 'WIDTH_AND_HEIGHT',+ height: 'HEIGHT'+}++const DIRECTION_MAP: Record<string, SceneNode['textDirection']> = {+ auto: 'AUTO',+ ltr: 'LTR',+ rtl: 'RTL'+}++function parseDirection(value: unknown): SceneNode['textDirection'] | undefined {+ if (typeof value !== 'string') return undefined+ return DIRECTION_MAP[value.toLowerCase()] ?? 'AUTO'+}++function parseStroke(value: string, width: number): Stroke {+ const color = parseColor(value)+ return {+ color,+ opacity: color.a,+ visible: true,+ weight: width,+ align: 'INSIDE'+ }+}++export function applySizeOverrides(+ props: Record<string, unknown>,+ o: Partial<SceneNode>,+ parentLayout: SceneNode['layoutMode']+): { w: unknown; h: unknown } {+ const w = props.w ?? props.width+ const h = props.h ?? props.height+ if (typeof w === 'number') o.width = w+ if (typeof h === 'number') o.height = h++ const isParentRow = parentLayout === 'HORIZONTAL'+ const isParentCol = parentLayout === 'VERTICAL'+ const isParentGrid = parentLayout === 'GRID'++ applyFillSizing(w, 'width', isParentGrid, isParentRow, isParentCol, o)+ applyFillSizing(h, 'height', isParentGrid, isParentRow, isParentCol, o)++ if (props.x !== undefined) o.x = props.x as number+ if (props.y !== undefined) o.y = props.y as number+ if (props.top !== undefined) o.y = props.top as number+ if (props.left !== undefined) o.x = props.left as number++ if (props.position === 'absolute') o.layoutPositioning = 'ABSOLUTE'+ const hasExplicitPosition =+ props.x !== undefined ||+ props.y !== undefined ||+ props.top !== undefined ||+ props.left !== undefined+ if (hasExplicitPosition && parentLayout !== 'NONE') {+ o.layoutPositioning = 'ABSOLUTE'+ }++ return { w, h }+}++function applyFillSizing(+ dim: unknown,+ axis: 'width' | 'height',+ isGrid: boolean,+ isRow: boolean,+ isCol: boolean,+ o: Partial<SceneNode>+): void {+ if (dim !== 'fill') return+ const isPrimary = axis === 'width' ? isRow : isCol+ const isCross = axis === 'width' ? isCol : isRow+ if (isGrid || isCross) o.layoutAlignSelf = 'STRETCH'+ else if (isPrimary) o.layoutGrow = 1+ else {+ o.layoutGrow = 1+ o.layoutAlignSelf = 'STRETCH'+ }+}++function applyVisualOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {+ const bg = props.bg ?? props.fill+ if (typeof bg === 'string') {+ o.fills = [colorToFill(bg)]+ }++ if (typeof props.stroke === 'string') {+ const strokeWidth = (props.strokeWidth as number | undefined) ?? 1+ o.strokes = [parseStroke(props.stroke, strokeWidth)]+ }++ const rounded = props.rounded ?? props.cornerRadius+ if (typeof rounded === 'number') {+ o.cornerRadius = rounded+ }+ if (+ props.roundedTL !== undefined ||+ props.roundedTR !== undefined ||+ props.roundedBL !== undefined ||+ props.roundedBR !== undefined+ ) {+ o.independentCorners = true+ if (props.roundedTL !== undefined) o.topLeftRadius = props.roundedTL as number+ if (props.roundedTR !== undefined) o.topRightRadius = props.roundedTR as number+ if (props.roundedBL !== undefined) o.bottomLeftRadius = props.roundedBL as number+ if (props.roundedBR !== undefined) o.bottomRightRadius = props.roundedBR as number+ }+ if (props.cornerSmoothing !== undefined) o.cornerSmoothing = props.cornerSmoothing as number++ if (props.opacity !== undefined) o.opacity = props.opacity as number+ if (props.rotate !== undefined) o.rotation = props.rotate as number+ if (props.blendMode !== undefined) {+ o.blendMode = (props.blendMode as string).toUpperCase() as SceneNode['blendMode']+ }+ if (props.overflow === 'hidden') o.clipsContent = true+}++function applyPaddingOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {+ const p = props.p ?? props.padding+ if (typeof p === 'number') {+ o.paddingTop = p+ o.paddingRight = p+ o.paddingBottom = p+ o.paddingLeft = p+ }+ const px = props.px as number | undefined+ const py = props.py as number | undefined+ if (px !== undefined) {+ o.paddingLeft = px+ o.paddingRight = px+ }+ if (py !== undefined) {+ o.paddingTop = py+ o.paddingBottom = py+ }+ if (props.pt !== undefined) o.paddingTop = props.pt as number+ if (props.pr !== undefined) o.paddingRight = props.pr as number+ if (props.pb !== undefined) o.paddingBottom = props.pb as number+ if (props.pl !== undefined) o.paddingLeft = props.pl as number+}++const PADDING_KEYS = ['p', 'padding', 'px', 'py', 'pt', 'pr', 'pb', 'pl'] as const+const AUTO_LAYOUT_TRIGGER_KEYS = [...PADDING_KEYS, 'justify', 'items'] as const++function hasAutoLayoutTriggerProps(props: Record<string, unknown>): boolean {+ return AUTO_LAYOUT_TRIGGER_KEYS.some((k) => props[k] !== undefined)+}++function parseTrack(token: string): GridTrack {+ if (token.endsWith('fr')) {+ return { sizing: 'FR', value: parseFloat(token) || 1 }+ }+ if (token === 'auto') {+ return { sizing: 'AUTO', value: 0 }+ }+ return { sizing: 'FIXED', value: parseFloat(token) || 0 }+}++function parseTrackList(value: string): GridTrack[] {+ return value.trim().split(/\s+/).map(parseTrack)+}++function applyGridOverrides(+ props: Record<string, unknown>,+ o: Partial<SceneNode>,+ w: unknown,+ h: unknown+): void {+ o.layoutMode = 'GRID'++ if (typeof w === 'number') o.width = w+ if (typeof h === 'number') o.height = h++ if (typeof props.columns === 'string') {+ o.gridTemplateColumns = parseTrackList(props.columns)+ } else if (typeof props.columns === 'number') {+ o.gridTemplateColumns = Array.from({ length: props.columns }, () => ({+ sizing: 'FR' as const,+ value: 1+ }))+ }++ if (typeof props.rows === 'string') {+ o.gridTemplateRows = parseTrackList(props.rows)+ } else if (typeof props.rows === 'number') {+ o.gridTemplateRows = Array.from({ length: props.rows }, () => ({+ sizing: 'FR' as const,+ value: 1+ }))+ }++ if (typeof props.columnGap === 'number') o.gridColumnGap = props.columnGap+ if (typeof props.rowGap === 'number') o.gridRowGap = props.rowGap+ if (typeof props.gap === 'number') {+ o.gridColumnGap = props.gap+ o.gridRowGap = props.gap+ }++ if (props.rows === undefined && typeof h !== 'number') {+ o.height = 0+ }+}++function applyGridChildOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {+ const col = props.colStart ?? props.col+ const row = props.rowStart ?? props.row+ const colSpan = (props.colSpan as number | undefined) ?? 1+ const rowSpan = (props.rowSpan as number | undefined) ?? 1++ if (col !== undefined || row !== undefined) {+ o.gridPosition = {+ column: (col as number | undefined) ?? 0,+ row: (row as number | undefined) ?? 0,+ columnSpan: colSpan,+ rowSpan: rowSpan+ }+ }+}++function applyAutoLayoutSizing(+ o: Partial<SceneNode>,+ props: Record<string, unknown>,+ w: unknown,+ h: unknown+): void {+ const dir = (props.flex as string | undefined) ?? 'col'+ const isVertical = dir === 'col' || dir === 'column'+ o.layoutMode = (isVertical ? 'VERTICAL' : 'HORIZONTAL') as LayoutMode++ o.primaryAxisSizing = 'HUG'+ o.counterAxisSizing = 'HUG'++ const primaryDim = isVertical ? h : w+ const counterDim = isVertical ? w : h++ if (typeof primaryDim === 'number') o.primaryAxisSizing = 'FIXED'+ if (typeof counterDim === 'number') o.counterAxisSizing = 'FIXED'+ if (primaryDim === 'hug') o.primaryAxisSizing = 'HUG'+ if (counterDim === 'hug') o.counterAxisSizing = 'HUG'+}++function shouldEnableAutoLayout(props: Record<string, unknown>, isText: boolean): boolean {+ if (props.flex !== undefined) return true+ if (!isText && hasAutoLayoutTriggerProps(props)) return true+ return false+}++function applyLayoutOverrides(+ props: Record<string, unknown>,+ o: Partial<SceneNode>,+ w: unknown,+ h: unknown,+ isText: boolean,+ parentLayout: SceneNode['layoutMode']+): void {+ if (props.grid) {+ applyGridOverrides(props, o, w, h)+ applyPaddingOverrides(props, o)+ if (props.grow !== undefined) o.layoutGrow = props.grow as number+ return+ }++ if (parentLayout === 'GRID') {+ applyGridChildOverrides(props, o)+ }++ if (shouldEnableAutoLayout(props, isText)) {+ applyAutoLayoutSizing(o, props, w, h)+ }++ o.layoutDirection =+ parseDirection(props.flow ?? (!isText ? props.dir : undefined)) ?? o.layoutDirection++ if (props.gap !== undefined) o.itemSpacing = props.gap as number++ if (props.wrap) {+ o.layoutWrap = 'WRAP'+ if (props.rowGap !== undefined) o.counterAxisSpacing = props.rowGap as number+ }++ if (props.justify) {+ o.primaryAxisAlign = ALIGN_MAP[props.justify as string] ?? 'MIN'+ }+ if (props.items) {+ o.counterAxisAlign = COUNTER_ALIGN_MAP[props.items as string] ?? 'MIN'+ }++ applyPaddingOverrides(props, o)++ if (props.grow !== undefined) o.layoutGrow = props.grow as number++ if (props.minW !== undefined) o.width = Math.max(o.width ?? 0, props.minW as number)+ if (props.maxW !== undefined) o.width = Math.min(o.width ?? Infinity, props.maxW as number)+}++function applyTextStyleOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {+ const fontSize = props.size ?? props.fontSize+ if (typeof fontSize === 'number') o.fontSize = fontSize++ const fontFamily = props.font ?? props.fontFamily+ if (typeof fontFamily === 'string') o.fontFamily = fontFamily++ const weight = props.weight ?? props.fontWeight+ if (typeof weight === 'number') {+ o.fontWeight = weight+ } else if (typeof weight === 'string') {+ o.fontWeight = WEIGHT_MAP[weight] ?? 400+ }++ if (typeof props.color === 'string') {+ o.fills = [colorToFill(props.color)]+ }++ if (props.lineHeight !== undefined) o.lineHeight = props.lineHeight as number+ if (props.letterSpacing !== undefined) o.letterSpacing = props.letterSpacing as number+ if (props.textDecoration !== undefined)+ o.textDecoration = (props.textDecoration as string).toUpperCase() as SceneNode['textDecoration']+ if (props.textCase !== undefined)+ o.textCase = (props.textCase as string).toUpperCase() as SceneNode['textCase']+ if (props.maxLines !== undefined) {+ o.maxLines = props.maxLines as number+ o.textTruncation = 'ENDING'+ }+ if (props.truncate) {+ o.textTruncation = 'ENDING'+ }++ if (props.textAlign) {+ o.textAlignHorizontal = TEXT_ALIGN_MAP[props.textAlign as string] ?? 'LEFT'+ }+}++function applyTextAutoResize(+ props: Record<string, unknown>,+ o: Partial<SceneNode>,+ parentLayout: SceneNode['layoutMode']+): void {+ const w = props.w ?? props.width+ const hasExplicitWidth = w !== undefined+ const fillsParent = w === 'fill' || (props.grow as number) > 0+ const isInsideAutoLayout = parentLayout !== 'NONE'++ // DO NOT CHANGE these defaults without testing headless layout (no CanvasKit).+ // WIDTH_AND_HEIGHT relies on MeasureFunc — without it, text keeps the 100×100+ // default SceneNode size and blows up every HUG container. layout.ts has a+ // fallback estimator, but changing this logic can silently break all JSX rendering.+ if (props.textAutoResize) {+ o.textAutoResize = TEXT_AUTO_RESIZE_MAP[props.textAutoResize as string] ?? 'NONE'+ } else if (hasExplicitWidth || (isInsideAutoLayout && fillsParent)) {+ o.textAutoResize = 'HEIGHT'+ } else {+ o.textAutoResize = 'WIDTH_AND_HEIGHT'+ }+}++function applyTextOverrides(+ props: Record<string, unknown>,+ o: Partial<SceneNode>,+ parentLayout: SceneNode['layoutMode']+): void {+ applyTextStyleOverrides(props, o)+ o.textDirection = parseDirection(props.dir) ?? o.textDirection+ applyTextAutoResize(props, o, parentLayout)+}++function applyShapeAndEffectOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {+ if (props.points !== undefined) o.pointCount = props.points as number+ if (props.innerRadius !== undefined) o.starInnerRadius = props.innerRadius as number+ if (props.pointCount !== undefined) o.pointCount = props.pointCount as number++ if (typeof props.shadow === 'string') {+ const parts = props.shadow.split(/\s+/)+ if (parts.length >= 4) {+ const c = parseColor(parts.slice(3).join(' '))+ o.effects = [+ ...(o.effects ?? []),+ {+ type: 'DROP_SHADOW',+ color: c,+ offset: { x: parseFloat(parts[0]), y: parseFloat(parts[1]) },+ radius: parseFloat(parts[2]),+ spread: 0,+ visible: true+ }+ ]+ }+ }++ if (typeof props.blur === 'number') {+ o.effects = [+ ...(o.effects ?? []),+ {+ type: 'LAYER_BLUR',+ radius: props.blur,+ visible: true,+ color: { ...TRANSPARENT },+ offset: { x: 0, y: 0 },+ spread: 0+ }+ ]+ }+}++export function propsToOverrides(+ props: Record<string, unknown>,+ isText: boolean,+ parentLayout: SceneNode['layoutMode']+): Partial<SceneNode> {+ const o: Partial<SceneNode> = {}++ if (props.name) o.name = props.name as string++ const { w, h } = applySizeOverrides(props, o, parentLayout)+ applyVisualOverrides(props, o)+ applyLayoutOverrides(props, o, w, h, isText, parentLayout)+ if (isText) applyTextOverrides(props, o, parentLayout)+ applyShapeAndEffectOverrides(props, o)++ return o+}diff --git a/packages/core/src/design-jsx/render.ts b/packages/core/src/design-jsx/render.tsindex 930b869c2..c39303189 100644--- a/packages/core/src/design-jsx/render.ts+++ b/packages/core/src/design-jsx/render.ts@@ -4,7 +4,7 @@ import * as React from './mini-react'import { renderTree, type RenderResult } from './renderer'import { resolveToTree, type TreeNode } from './tree'-import type { SceneGraph } from '../scene-graph'+import type { SceneGraph } from '#core/scene-graph'/*** Build a component function from a JSX string using sucrase.diff --git a/packages/core/src/design-jsx/renderer.ts b/packages/core/src/design-jsx/renderer.tsindex e4f752fa9..fe154584e 100644--- a/packages/core/src/design-jsx/renderer.ts+++ b/packages/core/src/design-jsx/renderer.ts@@ -1,11 +1,11 @@-import { parseColor, colorToFill } from '../color'-import { TRANSPARENT } from '../constants'-import { fetchIcons } from '../icons'-import { createIconFromPaths } from '../icons/render'-import { computeAllLayouts } from '../layout'+import { parseColor } from '#core/color'+import { fetchIcons } from '#core/icons'+import { createIconFromPaths } from '#core/icons/render'+import { computeAllLayouts } from '#core/layout'import { isTreeNode } from './tree'+import { applySizeOverrides, propsToOverrides } from './props-overrides'-import type { SceneGraph, SceneNode, NodeType, LayoutMode, GridTrack, Stroke } from '../scene-graph'+import type { SceneGraph, SceneNode, NodeType } from '#core/scene-graph'import type { TreeNode } from './tree'const TYPE_MAP: Partial<Record<string, NodeType>> = {@@ -24,61 +24,6 @@ const TYPE_MAP: Partial<Record<string, NodeType>> = {component: 'COMPONENT'}-const WEIGHT_MAP: Record<string, number> = {- normal: 400,- medium: 500,- bold: 700-}--const ALIGN_MAP: Record<string, SceneNode['primaryAxisAlign']> = {- start: 'MIN',- end: 'MAX',- center: 'CENTER',- between: 'SPACE_BETWEEN'-}--const COUNTER_ALIGN_MAP: Record<string, 'MIN' | 'MAX' | 'CENTER' | 'STRETCH'> = {- start: 'MIN',- end: 'MAX',- center: 'CENTER',- stretch: 'STRETCH'-}--const TEXT_ALIGN_MAP: Record<string, SceneNode['textAlignHorizontal']> = {- left: 'LEFT',- center: 'CENTER',- right: 'RIGHT',- justified: 'JUSTIFIED'-}--const TEXT_AUTO_RESIZE_MAP: Record<string, SceneNode['textAutoResize']> = {- none: 'NONE',- width: 'WIDTH_AND_HEIGHT',- height: 'HEIGHT'-}--const DIRECTION_MAP: Record<string, SceneNode['textDirection']> = {- auto: 'AUTO',- ltr: 'LTR',- rtl: 'RTL'-}--function parseDirection(value: unknown): SceneNode['textDirection'] | undefined {- if (typeof value !== 'string') return undefined- return DIRECTION_MAP[value.toLowerCase()] ?? 'AUTO'-}--function parseStroke(value: string, width: number): Stroke {- const color = parseColor(value)- return {- color,- opacity: color.a,- visible: true,- weight: width,- align: 'INSIDE'- }-}-interface RenderOptions {x?: numbery?: number@@ -172,398 +117,3 @@ async function renderNode(graph: SceneGraph, tree: TreeNode, parentId: string):return node}--function applySizeOverrides(- props: Record<string, unknown>,- o: Partial<SceneNode>,- parentLayout: SceneNode['layoutMode']-): { w: unknown; h: unknown } {- const w = props.w ?? props.width- const h = props.h ?? props.height- if (typeof w === 'number') o.width = w- if (typeof h === 'number') o.height = h-- const isParentRow = parentLayout === 'HORIZONTAL'- const isParentCol = parentLayout === 'VERTICAL'- const isParentGrid = parentLayout === 'GRID'-- applyFillSizing(w, 'width', isParentGrid, isParentRow, isParentCol, o)- applyFillSizing(h, 'height', isParentGrid, isParentRow, isParentCol, o)-- if (props.x !== undefined) o.x = props.x as number- if (props.y !== undefined) o.y = props.y as number- if (props.top !== undefined) o.y = props.top as number- if (props.left !== undefined) o.x = props.left as number-- if (props.position === 'absolute') o.layoutPositioning = 'ABSOLUTE'- const hasExplicitPosition =- props.x !== undefined ||- props.y !== undefined ||- props.top !== undefined ||- props.left !== undefined- if (hasExplicitPosition && parentLayout !== 'NONE') {- o.layoutPositioning = 'ABSOLUTE'- }-- return { w, h }-}--function applyFillSizing(- dim: unknown,- axis: 'width' | 'height',- isGrid: boolean,- isRow: boolean,- isCol: boolean,- o: Partial<SceneNode>-): void {- if (dim !== 'fill') return- const isPrimary = axis === 'width' ? isRow : isCol- const isCross = axis === 'width' ? isCol : isRow- if (isGrid || isCross) o.layoutAlignSelf = 'STRETCH'- else if (isPrimary) o.layoutGrow = 1- else {- o.layoutGrow = 1- o.layoutAlignSelf = 'STRETCH'- }-}--function applyVisualOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {- const bg = props.bg ?? props.fill- if (typeof bg === 'string') {- o.fills = [colorToFill(bg)]- }-- if (typeof props.stroke === 'string') {- const strokeWidth = (props.strokeWidth as number | undefined) ?? 1- o.strokes = [parseStroke(props.stroke, strokeWidth)]- }-- const rounded = props.rounded ?? props.cornerRadius- if (typeof rounded === 'number') {- o.cornerRadius = rounded- }- if (- props.roundedTL !== undefined ||- props.roundedTR !== undefined ||- props.roundedBL !== undefined ||- props.roundedBR !== undefined- ) {- o.independentCorners = true- if (props.roundedTL !== undefined) o.topLeftRadius = props.roundedTL as number- if (props.roundedTR !== undefined) o.topRightRadius = props.roundedTR as number- if (props.roundedBL !== undefined) o.bottomLeftRadius = props.roundedBL as number- if (props.roundedBR !== undefined) o.bottomRightRadius = props.roundedBR as number- }- if (props.cornerSmoothing !== undefined) o.cornerSmoothing = props.cornerSmoothing as number-- if (props.opacity !== undefined) o.opacity = props.opacity as number- if (props.rotate !== undefined) o.rotation = props.rotate as number- if (props.blendMode !== undefined) {- o.blendMode = (props.blendMode as string).toUpperCase() as SceneNode['blendMode']- }- if (props.overflow === 'hidden') o.clipsContent = true-}--function applyPaddingOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {- const p = props.p ?? props.padding- if (typeof p === 'number') {- o.paddingTop = p- o.paddingRight = p- o.paddingBottom = p- o.paddingLeft = p- }- const px = props.px as number | undefined- const py = props.py as number | undefined- if (px !== undefined) {- o.paddingLeft = px- o.paddingRight = px- }- if (py !== undefined) {- o.paddingTop = py- o.paddingBottom = py- }- if (props.pt !== undefined) o.paddingTop = props.pt as number- if (props.pr !== undefined) o.paddingRight = props.pr as number- if (props.pb !== undefined) o.paddingBottom = props.pb as number- if (props.pl !== undefined) o.paddingLeft = props.pl as number-}--const PADDING_KEYS = ['p', 'padding', 'px', 'py', 'pt', 'pr', 'pb', 'pl'] as const-const AUTO_LAYOUT_TRIGGER_KEYS = [...PADDING_KEYS, 'justify', 'items'] as const--function hasAutoLayoutTriggerProps(props: Record<string, unknown>): boolean {- return AUTO_LAYOUT_TRIGGER_KEYS.some((k) => props[k] !== undefined)-}--function parseTrack(token: string): GridTrack {- if (token.endsWith('fr')) {- return { sizing: 'FR', value: parseFloat(token) || 1 }- }- if (token === 'auto') {- return { sizing: 'AUTO', value: 0 }- }- return { sizing: 'FIXED', value: parseFloat(token) || 0 }-}--function parseTrackList(value: string): GridTrack[] {- return value.trim().split(/\s+/).map(parseTrack)-}--function applyGridOverrides(- props: Record<string, unknown>,- o: Partial<SceneNode>,- w: unknown,- h: unknown-): void {- o.layoutMode = 'GRID'-- if (typeof w === 'number') o.width = w- if (typeof h === 'number') o.height = h-- if (typeof props.columns === 'string') {- o.gridTemplateColumns = parseTrackList(props.columns)- } else if (typeof props.columns === 'number') {- o.gridTemplateColumns = Array.from({ length: props.columns }, () => ({- sizing: 'FR' as const,- value: 1- }))- }-- if (typeof props.rows === 'string') {- o.gridTemplateRows = parseTrackList(props.rows)- } else if (typeof props.rows === 'number') {- o.gridTemplateRows = Array.from({ length: props.rows }, () => ({- sizing: 'FR' as const,- value: 1- }))- }-- if (typeof props.columnGap === 'number') o.gridColumnGap = props.columnGap- if (typeof props.rowGap === 'number') o.gridRowGap = props.rowGap- if (typeof props.gap === 'number') {- o.gridColumnGap = props.gap- o.gridRowGap = props.gap- }-- if (props.rows === undefined && typeof h !== 'number') {- o.height = 0- }-}--function applyGridChildOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {- const col = props.colStart ?? props.col- const row = props.rowStart ?? props.row- const colSpan = (props.colSpan as number | undefined) ?? 1- const rowSpan = (props.rowSpan as number | undefined) ?? 1-- if (col !== undefined || row !== undefined) {- o.gridPosition = {- column: (col as number | undefined) ?? 0,- row: (row as number | undefined) ?? 0,- columnSpan: colSpan,- rowSpan: rowSpan- }- }-}--function applyAutoLayoutSizing(- o: Partial<SceneNode>,- props: Record<string, unknown>,- w: unknown,- h: unknown-): void {- const dir = (props.flex as string | undefined) ?? 'col'- const isVertical = dir === 'col' || dir === 'column'- o.layoutMode = (isVertical ? 'VERTICAL' : 'HORIZONTAL') as LayoutMode-- o.primaryAxisSizing = 'HUG'- o.counterAxisSizing = 'HUG'-- const primaryDim = isVertical ? h : w- const counterDim = isVertical ? w : h-- if (typeof primaryDim === 'number') o.primaryAxisSizing = 'FIXED'- if (typeof counterDim === 'number') o.counterAxisSizing = 'FIXED'- if (primaryDim === 'hug') o.primaryAxisSizing = 'HUG'- if (counterDim === 'hug') o.counterAxisSizing = 'HUG'-}--function shouldEnableAutoLayout(props: Record<string, unknown>, isText: boolean): boolean {- if (props.flex !== undefined) return true- if (!isText && hasAutoLayoutTriggerProps(props)) return true- return false-}--function applyLayoutOverrides(- props: Record<string, unknown>,- o: Partial<SceneNode>,- w: unknown,- h: unknown,- isText: boolean,- parentLayout: SceneNode['layoutMode']-): void {- if (props.grid) {- applyGridOverrides(props, o, w, h)- applyPaddingOverrides(props, o)- if (props.grow !== undefined) o.layoutGrow = props.grow as number- return- }-- if (parentLayout === 'GRID') {- applyGridChildOverrides(props, o)- }-- if (shouldEnableAutoLayout(props, isText)) {- applyAutoLayoutSizing(o, props, w, h)- }-- o.layoutDirection =- parseDirection(props.flow ?? (!isText ? props.dir : undefined)) ?? o.layoutDirection-- if (props.gap !== undefined) o.itemSpacing = props.gap as number-- if (props.wrap) {- o.layoutWrap = 'WRAP'- if (props.rowGap !== undefined) o.counterAxisSpacing = props.rowGap as number- }-- if (props.justify) {- o.primaryAxisAlign = ALIGN_MAP[props.justify as string] ?? 'MIN'- }- if (props.items) {- o.counterAxisAlign = COUNTER_ALIGN_MAP[props.items as string] ?? 'MIN'- }-- applyPaddingOverrides(props, o)-- if (props.grow !== undefined) o.layoutGrow = props.grow as number-- if (props.minW !== undefined) o.width = Math.max(o.width ?? 0, props.minW as number)- if (props.maxW !== undefined) o.width = Math.min(o.width ?? Infinity, props.maxW as number)-}--function applyTextStyleOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {- const fontSize = props.size ?? props.fontSize- if (typeof fontSize === 'number') o.fontSize = fontSize-- const fontFamily = props.font ?? props.fontFamily- if (typeof fontFamily === 'string') o.fontFamily = fontFamily-- const weight = props.weight ?? props.fontWeight- if (typeof weight === 'number') {- o.fontWeight = weight- } else if (typeof weight === 'string') {- o.fontWeight = WEIGHT_MAP[weight] ?? 400- }-- if (typeof props.color === 'string') {- o.fills = [colorToFill(props.color)]- }-- if (props.lineHeight !== undefined) o.lineHeight = props.lineHeight as number- if (props.letterSpacing !== undefined) o.letterSpacing = props.letterSpacing as number- if (props.textDecoration !== undefined)- o.textDecoration = (props.textDecoration as string).toUpperCase() as SceneNode['textDecoration']- if (props.textCase !== undefined)- o.textCase = (props.textCase as string).toUpperCase() as SceneNode['textCase']- if (props.maxLines !== undefined) {- o.maxLines = props.maxLines as number- o.textTruncation = 'ENDING'- }- if (props.truncate) {- o.textTruncation = 'ENDING'- }-- if (props.textAlign) {- o.textAlignHorizontal = TEXT_ALIGN_MAP[props.textAlign as string] ?? 'LEFT'- }-}--function applyTextAutoResize(- props: Record<string, unknown>,- o: Partial<SceneNode>,- parentLayout: SceneNode['layoutMode']-): void {- const w = props.w ?? props.width- const hasExplicitWidth = w !== undefined- const fillsParent = w === 'fill' || (props.grow as number) > 0- const isInsideAutoLayout = parentLayout !== 'NONE'-- // DO NOT CHANGE these defaults without testing headless layout (no CanvasKit).- // WIDTH_AND_HEIGHT relies on MeasureFunc — without it, text keeps the 100×100- // default SceneNode size and blows up every HUG container. layout.ts has a- // fallback estimator, but changing this logic can silently break all JSX rendering.- if (props.textAutoResize) {- o.textAutoResize = TEXT_AUTO_RESIZE_MAP[props.textAutoResize as string] ?? 'NONE'- } else if (hasExplicitWidth || (isInsideAutoLayout && fillsParent)) {- o.textAutoResize = 'HEIGHT'- } else {- o.textAutoResize = 'WIDTH_AND_HEIGHT'- }-}--function applyTextOverrides(- props: Record<string, unknown>,- o: Partial<SceneNode>,- parentLayout: SceneNode['layoutMode']-): void {- applyTextStyleOverrides(props, o)- o.textDirection = parseDirection(props.dir) ?? o.textDirection- applyTextAutoResize(props, o, parentLayout)-}--function applyShapeAndEffectOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {- if (props.points !== undefined) o.pointCount = props.points as number- if (props.innerRadius !== undefined) o.starInnerRadius = props.innerRadius as number- if (props.pointCount !== undefined) o.pointCount = props.pointCount as number-- if (typeof props.shadow === 'string') {- const parts = props.shadow.split(/\s+/)- if (parts.length >= 4) {- const c = parseColor(parts.slice(3).join(' '))- o.effects = [- ...(o.effects ?? []),- {- type: 'DROP_SHADOW',- color: c,- offset: { x: parseFloat(parts[0]), y: parseFloat(parts[1]) },- radius: parseFloat(parts[2]),- spread: 0,- visible: true- }- ]- }- }-- if (typeof props.blur === 'number') {- o.effects = [- ...(o.effects ?? []),- {- type: 'LAYER_BLUR',- radius: props.blur,- visible: true,- color: { ...TRANSPARENT },- offset: { x: 0, y: 0 },- spread: 0- }- ]- }-}--function propsToOverrides(- props: Record<string, unknown>,- isText: boolean,- parentLayout: SceneNode['layoutMode']-): Partial<SceneNode> {- const o: Partial<SceneNode> = {}-- if (props.name) o.name = props.name as string-- const { w, h } = applySizeOverrides(props, o, parentLayout)- applyVisualOverrides(props, o)- applyLayoutOverrides(props, o, w, h, isText, parentLayout)- if (isText) applyTextOverrides(props, o, parentLayout)- applyShapeAndEffectOverrides(props, o)-- return o-}diff --git a/packages/core/src/editor/alignment.ts b/packages/core/src/editor/alignment.tsindex 029c30ec9..5a87212bd 100644--- a/packages/core/src/editor/alignment.ts+++ b/packages/core/src/editor/alignment.ts@@ -1,7 +1,10 @@-import { computeAbsoluteBounds } from '../geometry'+import { createFlipRotateActions } from '#core/editor/alignment/flip-rotate'+import { computeAbsoluteBounds } from '#core/geometry'-import type { SceneNode } from '../scene-graph'-import type { Vector } from '../types'+import { collectNodePositions, pushPositionUndo } from './history/position'++import type { SceneNode } from '#core/scene-graph'+import type { Vector } from '#core/types'import type { EditorContext } from './types'function computeAlignTarget(@@ -76,8 +79,10 @@ export function createAlignmentActions(ctx: EditorContext) {.filter((n): n is SceneNode => n != null)if (nodes.length === 0) return- const originals = new Map<string, Vector>()- for (const n of nodes) originals.set(n.id, { x: n.x, y: n.y })+ const originals = collectNodePositions(+ ctx,+ nodes.map((node) => node.id)+ )if (nodes.length === 1) {alignSingleNode(ctx, nodes[0], axis, align)@@ -85,89 +90,14 @@ export function createAlignmentActions(ctx: EditorContext) {alignMultipleNodes(ctx, nodes, axis, align)}- const finals = new Map<string, Vector>()- for (const n of nodes) finals.set(n.id, { x: n.x, y: n.y })-- ctx.undo.push({- label: 'Align',- forward: () => {- for (const [id, pos] of finals) {- ctx.graph.updateNode(id, pos)- ctx.runLayoutForNode(id)- }- },- inverse: () => {- for (const [id, pos] of originals) {- ctx.graph.updateNode(id, pos)- ctx.runLayoutForNode(id)- }- }- })+ const finals = collectNodePositions(ctx, originals.keys())+ pushPositionUndo(ctx, 'Align', originals, finals)for (const id of nodeIds) ctx.runLayoutForNode(id)ctx.requestRender()}- function flipNodes(nodeIds: string[], axis: 'horizontal' | 'vertical') {- if (nodeIds.length === 0) return-- const originals = new Map<string, { flipX: boolean; flipY: boolean }>()- for (const id of nodeIds) {- const node = ctx.graph.getNode(id)- if (!node) continue- originals.set(id, { flipX: node.flipX, flipY: node.flipY })- const changes = axis === 'horizontal' ? { flipX: !node.flipX } : { flipY: !node.flipY }- ctx.graph.updateNode(id, changes)- }-- const finals = new Map<string, { flipX: boolean; flipY: boolean }>()- for (const [id] of originals) {- const node = ctx.graph.getNode(id)- if (node) finals.set(id, { flipX: node.flipX, flipY: node.flipY })- }-- ctx.undo.push({- label: 'Flip',- forward: () => {- for (const [id, val] of finals) ctx.graph.updateNode(id, val)- },- inverse: () => {- for (const [id, val] of originals) ctx.graph.updateNode(id, val)- }- })-- ctx.requestRender()- }-- function rotateNodes(nodeIds: string[], degrees: number) {- if (nodeIds.length === 0) return-- const originals = new Map<string, number>()- for (const id of nodeIds) {- const node = ctx.graph.getNode(id)- if (!node) continue- originals.set(id, node.rotation)- ctx.graph.updateNode(id, { rotation: (((node.rotation + degrees) % 360) + 360) % 360 })- }-- const finals = new Map<string, number>()- for (const [id] of originals) {- const node = ctx.graph.getNode(id)- if (node) finals.set(id, node.rotation)- }-- ctx.undo.push({- label: 'Rotate',- forward: () => {- for (const [id, rot] of finals) ctx.graph.updateNode(id, { rotation: rot })- },- inverse: () => {- for (const [id, rot] of originals) ctx.graph.updateNode(id, { rotation: rot })- }- })-- ctx.requestRender()- }+ const { flipNodes, rotateNodes } = createFlipRotateActions(ctx)return { alignNodes, flipNodes, rotateNodes }}diff --git a/packages/core/src/editor/alignment/flip-rotate.ts b/packages/core/src/editor/alignment/flip-rotate.tsnew file mode 100644index 000000000..5a7cfb721--- /dev/null+++ b/packages/core/src/editor/alignment/flip-rotate.ts@@ -0,0 +1,66 @@+import type { EditorContext } from '#core/editor/types'++export function createFlipRotateActions(ctx: EditorContext) {+ function flipNodes(nodeIds: string[], axis: 'horizontal' | 'vertical') {+ if (nodeIds.length === 0) return++ const originals = new Map<string, { flipX: boolean; flipY: boolean }>()+ for (const id of nodeIds) {+ const node = ctx.graph.getNode(id)+ if (!node) continue+ originals.set(id, { flipX: node.flipX, flipY: node.flipY })+ const changes = axis === 'horizontal' ? { flipX: !node.flipX } : { flipY: !node.flipY }+ ctx.graph.updateNode(id, changes)+ }++ const finals = new Map<string, { flipX: boolean; flipY: boolean }>()+ for (const [id] of originals) {+ const node = ctx.graph.getNode(id)+ if (node) finals.set(id, { flipX: node.flipX, flipY: node.flipY })+ }++ ctx.undo.push({+ label: 'Flip',+ forward: () => {+ for (const [id, val] of finals) ctx.graph.updateNode(id, val)+ },+ inverse: () => {+ for (const [id, val] of originals) ctx.graph.updateNode(id, val)+ }+ })++ ctx.requestRender()+ }++ function rotateNodes(nodeIds: string[], degrees: number) {+ if (nodeIds.length === 0) return++ const originals = new Map<string, number>()+ for (const id of nodeIds) {+ const node = ctx.graph.getNode(id)+ if (!node) continue+ originals.set(id, node.rotation)+ ctx.graph.updateNode(id, { rotation: (((node.rotation + degrees) % 360) + 360) % 360 })+ }++ const finals = new Map<string, number>()+ for (const [id] of originals) {+ const node = ctx.graph.getNode(id)+ if (node) finals.set(id, node.rotation)+ }++ ctx.undo.push({+ label: 'Rotate',+ forward: () => {+ for (const [id, rot] of finals) ctx.graph.updateNode(id, { rotation: rot })+ },+ inverse: () => {+ for (const [id, rot] of originals) ctx.graph.updateNode(id, { rotation: rot })+ }+ })++ ctx.requestRender()+ }++ return { flipNodes, rotateNodes }+}diff --git a/packages/core/src/editor/bridges/clipboard.ts b/packages/core/src/editor/bridges/clipboard.tsnew file mode 100644index 000000000..71c24bc0b--- /dev/null+++ b/packages/core/src/editor/bridges/clipboard.ts@@ -0,0 +1,21 @@+import type { createClipboardActions } from '#core/editor/clipboard'+import type { createSelectionActions } from '#core/editor/selection'++type ClipboardActions = ReturnType<typeof createClipboardActions>+type SelectionActions = ReturnType<typeof createSelectionActions>++export function createClipboardBridge(clipboard: ClipboardActions, selection: SelectionActions) {+ return {+ duplicateSelected: () => clipboard.duplicateSelected(selection.getSelectedNodes()),+ writeCopyData: (data: DataTransfer) =>+ clipboard.writeCopyData(data, selection.getSelectedNodes()),+ pasteFromHTML: clipboard.pasteFromHTML,+ deleteSelected: clipboard.deleteSelected,+ storeImage: clipboard.storeImage,+ placeImageFiles: clipboard.placeImageFiles,+ loadFontsForNodes: clipboard.loadFontsForNodes,+ copySelectionAsText: clipboard.copySelectionAsText,+ copySelectionAsSVG: clipboard.copySelectionAsSVG,+ copySelectionAsJSX: clipboard.copySelectionAsJSX+ }+}diff --git a/packages/core/src/editor/bridges/components.ts b/packages/core/src/editor/bridges/components.tsnew file mode 100644index 000000000..b434797d7--- /dev/null+++ b/packages/core/src/editor/bridges/components.ts@@ -0,0 +1,33 @@+import type { createComponentActions } from '#core/editor/components'+import type { createPageActions } from '#core/editor/pages'+import type { createSelectionActions } from '#core/editor/selection'+import type { createStructureActions } from '#core/editor/structure'++type ComponentActions = ReturnType<typeof createComponentActions>+type PageActions = ReturnType<typeof createPageActions>+type SelectionActions = ReturnType<typeof createSelectionActions>+type StructureActions = ReturnType<typeof createStructureActions>++export function createComponentBridge(+ components: ComponentActions,+ selection: SelectionActions,+ structure: StructureActions,+ pages: PageActions+) {+ return {+ createComponentFromSelection: () =>+ components.createComponentFromSelection(+ selection.getSelectedNodes(),+ structure.wrapSelectionInContainer+ ),+ createComponentSetFromComponents: () =>+ components.createComponentSetFromComponents(+ selection.getSelectedNodes(),+ structure.wrapSelectionInContainer+ ),+ createInstanceFromComponent: components.createInstanceFromComponent,+ detachInstance: () => components.detachInstance(selection.getSelectedNode()),+ goToMainComponent: () =>+ components.goToMainComponent(selection.getSelectedNode(), pages.switchPage)+ }+}diff --git a/packages/core/src/editor/bridges/structure.ts b/packages/core/src/editor/bridges/structure.tsnew file mode 100644index 000000000..b99c11dc2--- /dev/null+++ b/packages/core/src/editor/bridges/structure.ts@@ -0,0 +1,13 @@+import type { createSelectionActions } from '#core/editor/selection'+import type { createStructureActions } from '#core/editor/structure'++type SelectionActions = ReturnType<typeof createSelectionActions>+type StructureActions = ReturnType<typeof createStructureActions>++export function createStructureBridge(structure: StructureActions, selection: SelectionActions) {+ return {+ wrapInAutoLayout: () => structure.wrapInAutoLayout(selection.getSelectedNodes()),+ groupSelected: () => structure.groupSelected(selection.getSelectedNodes()),+ ungroupSelected: () => structure.ungroupSelected(selection.getSelectedNode())+ }+}diff --git a/packages/core/src/editor/bridges/undo.ts b/packages/core/src/editor/bridges/undo.tsnew file mode 100644index 000000000..ce0edd3a8--- /dev/null+++ b/packages/core/src/editor/bridges/undo.ts@@ -0,0 +1,21 @@+import type { createSelectionActions } from '#core/editor/selection'+import type { createUndoActions } from '#core/editor/undo'++type SelectionActions = ReturnType<typeof createSelectionActions>+type UndoActions = ReturnType<typeof createUndoActions>++export function createUndoBridge(undoActions: UndoActions, selection: SelectionActions) {+ return {+ commitMove: undoActions.commitMove,+ commitMoveWithReparent: undoActions.commitMoveWithReparent,+ commitDuplicateMove: undoActions.commitDuplicateMove,+ commitResize: undoActions.commitResize,+ commitRotation: undoActions.commitRotation,+ commitNodeUpdate: undoActions.commitNodeUpdate,+ undoAction: () => undoActions.undoAction(selection.validateEnteredContainer),+ redoAction: () => undoActions.redoAction(selection.validateEnteredContainer),+ snapshotPage: undoActions.snapshotPage,+ restorePageFromSnapshot: undoActions.restorePageFromSnapshot,+ pushUndoEntry: undoActions.pushUndoEntry+ }+}diff --git a/packages/core/src/editor/clipboard.ts b/packages/core/src/editor/clipboard.tsindex fa4578f02..80f898512 100644--- a/packages/core/src/editor/clipboard.ts+++ b/packages/core/src/editor/clipboard.ts@@ -1,75 +1,22 @@-import { buildFigmaClipboardHTML, importClipboardNodes, parseFigmaClipboard } from '../clipboard'-import { selectionToJSX } from '../design-jsx'-import { computeImageHash } from '../figma-api'-import { computeBounds } from '../geometry'-import { renderNodesToSVG } from '../io/formats/svg'-import { computeAllLayouts } from '../layout'-import { collectFontKeys } from '../text/fonts'--import type { Fill, SceneGraph, SceneNode } from '../scene-graph'-import type { Vector } from '../types'+import {+ importClipboardNodes,+ parseFigmaClipboard,+ parseOpenPencilClipboard+} from '#core/clipboard'+import { computeAllLayouts } from '#core/layout'++import { createClipboardCopyActions } from './clipboard/copy'+import { createClipboardExportActions } from './clipboard/export'+import { createClipboardFontActions } from './clipboard/fonts'+import { createClipboardImageActions } from './clipboard/images'+import { createClipboardPlacementActions } from './clipboard/placement'+import { collectSubtrees, restoreSubtree, snapshotSubtree } from './clipboard/subtree-history'++import type { SceneNode } from '#core/scene-graph'+import type { Vector } from '#core/types'import type { EditorContext } from './types'export function createClipboardActions(ctx: EditorContext) {- function collectSubtrees(g: SceneGraph, rootIds: string[]): SceneNode[] {- const result: SceneNode[] = []- function walk(id: string) {- const node = g.getNode(id)- if (!node) return- result.push({ ...node })- for (const childId of node.childIds) walk(childId)- }- for (const id of rootIds) walk(id)- return result- }-- function centerNodesAt(nodeIds: string[], cx: number, cy: number) {- const items = nodeIds.map((id) => ctx.graph.getNode(id)).filter((n) => n != null)- const b = computeBounds(items)- if (b.width === 0 && b.height === 0 && items.length === 0) return- const dx = cx - (b.x + b.width / 2)- const dy = cy - (b.y + b.height / 2)- for (const id of nodeIds) {- const n = ctx.graph.getNode(id)- if (n) ctx.graph.updateNode(id, { x: n.x + dx, y: n.y + dy })- }- }-- async function loadFontsForNodes(nodeIds: string[]) {- const toLoad = collectFontKeys(ctx.graph, nodeIds)- if (toLoad.length === 0) return []-- const results = await Promise.all(toLoad.map(([family, style]) => ctx.loadFont(family, style)))- const failed = toLoad.filter((_, i) => results[i] === null)- computeAllLayouts(ctx.graph, ctx.state.currentPageId)- return failed- }-- function snapshotSubtree(rootId: string): Map<string, SceneNode> {- const index = new Map<string, SceneNode>()- const walk = (id: string) => {- const node = ctx.graph.getNode(id)- if (!node) return- index.set(id, structuredClone(node))- for (const childId of node.childIds) walk(childId)- }- walk(rootId)- return index- }-- function restoreSubtree(- snapshot: SceneNode,- parentId: string,- index: Map<string, SceneNode>- ): void {- const { parentId: _p, childIds, ...rest } = snapshot- ctx.graph.createNode(snapshot.type, parentId, { ...rest, id: snapshot.id })- for (const childId of childIds) {- const child = index.get(childId)- if (child) restoreSubtree(child, snapshot.id, index)- }- }-function duplicateSelected(selectedNodes: SceneNode[]) {const prevSelection = new Set(ctx.state.selectedIds)const selectedSet = new Set(selectedNodes.map((n) => n.id))@@ -87,7 +34,7 @@ export function createClipboardActions(ctx: EditorContext) {})if (!clone) continuenewRootIds.push(clone.id)- const subtree = snapshotSubtree(clone.id)+ const subtree = snapshotSubtree(ctx.graph, clone.id)for (const [id, snap] of subtree) allSnapshots.set(id, snap)}@@ -100,7 +47,7 @@ export function createClipboardActions(ctx: EditorContext) {const snapshot = allSnapshots.get(rootId)if (!snapshot) continueconst parentId = snapshot.parentId ?? ctx.state.currentPageId- restoreSubtree(snapshot, parentId, allSnapshots)+ restoreSubtree(ctx.graph, snapshot, parentId, allSnapshots)}ctx.state.selectedIds = new Set(newRootIds)},@@ -112,16 +59,13 @@ export function createClipboardActions(ctx: EditorContext) {}}- async function writeCopyData(clipboardData: DataTransfer, selectedNodes: SceneNode[]) {- if (selectedNodes.length === 0) return-- const names = selectedNodes.map((n) => n.name).join('\n')- const html = await buildFigmaClipboardHTML(selectedNodes, ctx.graph)- if (html) clipboardData.setData('text/html', html)- clipboardData.setData('text/plain', names)- }-function pasteFromHTML(html: string, cursorPos?: Vector) {+ const openPencil = parseOpenPencilClipboard(html)+ if (openPencil) {+ pasteOpenPencilNodes(openPencil.nodes, openPencil.images, cursorPos)+ return+ }+void parseFigmaClipboard(html).then((figma) => {if (figma) {const prevSelection = new Set(ctx.state.selectedIds)@@ -137,7 +81,7 @@ export function createClipboardActions(ctx: EditorContext) {const { width: viewW, height: viewH } = ctx.getViewportSize()const cx = cursorPos?.x ?? (-ctx.state.panX + viewW / 2) / ctx.state.zoomconst cy = cursorPos?.y ?? (-ctx.state.panY + viewH / 2) / ctx.state.zoom- centerNodesAt(created, cx, cy)+ placementActions.centerNodesAt(created, cx, cy)computeAllLayouts(ctx.graph, ctx.state.currentPageId)ctx.state.selectedIds = new Set(created)@@ -161,13 +105,63 @@ export function createClipboardActions(ctx: EditorContext) {ctx.state.selectedIds = prevSelection}})- void loadFontsForNodes(created)+ void fontActions.loadFontsForNodes(created)warnMissingImages(created)}}})}+ function pasteOpenPencilNodes(+ nodes: Array<SceneNode & { children?: SceneNode[] }>,+ images: Map<string, Uint8Array>,+ cursorPos?: Vector+ ) {+ const prevSelection = new Set(ctx.state.selectedIds)+ for (const [hash, bytes] of images) ctx.graph.images.set(hash, bytes)++ const created: string[] = []+ const createNodeTree = (source: SceneNode & { children?: SceneNode[] }, parentId: string) => {+ const { id: _id, childIds: _childIds, children = [], parentId: _parentId, ...rest } = source+ const node = ctx.graph.createNode(source.type, parentId, {+ ...structuredClone(rest),+ x: source.x + 20,+ y: source.y + 20,+ childIds: []+ })+ for (const child of children) createNodeTree(child, node.id)+ return node.id+ }++ for (const node of nodes) created.push(createNodeTree(node, ctx.state.currentPageId))+ if (created.length === 0) return++ if (cursorPos) placementActions.centerNodesAt(created, cursorPos.x, cursorPos.y)+ computeAllLayouts(ctx.graph, ctx.state.currentPageId)+ ctx.state.selectedIds = new Set(created)++ const allNodes = collectSubtrees(ctx.graph, created)+ const pageId = ctx.state.currentPageId+ ctx.undo.push({+ label: 'Paste',+ forward: () => {+ for (const snapshot of allNodes) {+ ctx.graph.createNode(snapshot.type, snapshot.parentId ?? pageId, {+ ...snapshot,+ childIds: []+ })+ }+ computeAllLayouts(ctx.graph, pageId)+ ctx.state.selectedIds = new Set(created)+ },+ inverse: () => {+ for (const id of [...created].reverse()) ctx.graph.deleteNode(id)+ computeAllLayouts(ctx.graph, pageId)+ ctx.state.selectedIds = prevSelection+ }+ })+ }+function warnMissingImages(nodeIds: string[]) {const allNodes = collectSubtrees(ctx.graph, nodeIds)return allNodes.some((n) =>@@ -188,7 +182,7 @@ export function createClipboardActions(ctx: EditorContext) {const parentId = node.parentId ?? ctx.state.currentPageIdconst parent = ctx.graph.getNode(parentId)const index = parent?.childIds.indexOf(id) ?? -1- entries.push({ id, parentId, index, subtree: snapshotSubtree(id) })+ entries.push({ id, parentId, index, subtree: snapshotSubtree(ctx.graph, id) })}if (entries.length === 0) return@@ -204,7 +198,7 @@ export function createClipboardActions(ctx: EditorContext) {inverse: () => {for (const { id, parentId, index, subtree } of [...entries].reverse()) {const rootSnap = subtree.get(id)- if (rootSnap) restoreSubtree(rootSnap, parentId, subtree)+ if (rootSnap) restoreSubtree(ctx.graph, rootSnap, parentId, subtree)if (index >= 0) ctx.graph.reorderChild(id, parentId, index)}ctx.state.selectedIds = prevSelection@@ -213,132 +207,22 @@ export function createClipboardActions(ctx: EditorContext) {ctx.state.selectedIds = new Set()}- function storeImage(bytes: Uint8Array): string {- const hash = computeImageHash(bytes)- ctx.graph.images.set(hash, bytes)- return hash- }-- const IMAGE_MAX_DIMENSION = 4096- const IMAGE_GAP = 20-- function decodeImageDimensions(bytes: Uint8Array): { w: number; h: number } | null {- const ck = ctx.getCk()- if (!ck) return null- const skImg = ck.MakeImageFromEncoded(bytes)- if (!skImg) return null- let w = skImg.width()- let h = skImg.height()- skImg.delete()- if (w > IMAGE_MAX_DIMENSION || h > IMAGE_MAX_DIMENSION) {- const ratio = Math.min(IMAGE_MAX_DIMENSION / w, IMAGE_MAX_DIMENSION / h)- w = Math.round(w * ratio)- h = Math.round(h * ratio)- }- return { w, h }- }-- function placeImageNode(- bytes: Uint8Array,- x: number,- y: number,- w: number,- h: number,- name = 'Image'- ): string | null {- const hash = storeImage(bytes)- const displayName = name.replace(/\.[^.]+$/, '')- const pid = ctx.state.currentPageId- const fill: Fill = {- type: 'IMAGE',- imageHash: hash,- imageScaleMode: 'FILL',- color: { r: 0, g: 0, b: 0, a: 0 },- opacity: 1,- visible: true- }- const node = ctx.graph.createNode('RECTANGLE', pid, {- name: displayName,- x,- y,- width: w,- height: h,- fills: [fill]- })- const id = node.id- const snapshot = { ...node }- ctx.undo.push({- label: 'Place image',- forward: () => {- ctx.graph.images.set(hash, bytes)- ctx.graph.createNode(snapshot.type, pid, snapshot)- },- inverse: () => {- ctx.graph.deleteNode(id)- ctx.graph.images.delete(hash)- const next = new Set(ctx.state.selectedIds)- next.delete(id)- ctx.state.selectedIds = next- }- })- return id- }-- async function placeImageFiles(files: File[], cx: number, cy: number) {- const prepared: Array<{ bytes: Uint8Array; name: string; w: number; h: number }> = []- for (const file of files) {- const bytes = new Uint8Array(await file.arrayBuffer())- const dims = decodeImageDimensions(bytes)- if (dims) prepared.push({ bytes, name: file.name, ...dims })- }- if (!prepared.length) return-- let totalW = 0- for (const p of prepared) totalW += p.w- totalW += IMAGE_GAP * (prepared.length - 1)- const maxH = Math.max(...prepared.map((p) => p.h))-- let curX = cx - totalW / 2- const topY = cy - maxH / 2- const ids: string[] = []- for (const p of prepared) {- const id = placeImageNode(p.bytes, curX, topY, p.w, p.h, p.name)- if (id) ids.push(id)- curX += p.w + IMAGE_GAP- }- if (ids.length) {- ctx.state.selectedIds = new Set(ids)- ctx.requestRender()- }- }-- function copySelectionAsText(ids: string[]): string {- return ids.map((id) => ctx.graph.getNode(id)?.name ?? id).join('\n')- }-- function copySelectionAsSVG(ids: string[]): string | null {- const nodeIds =- ids.length > 0 ? ids : ctx.graph.getChildren(ctx.state.currentPageId).map((n) => n.id)- return renderNodesToSVG(ctx.graph, ctx.state.currentPageId, nodeIds)- }-- function copySelectionAsJSX(ids: string[]): string | null {- return ids.length > 0 ? selectionToJSX(ids, ctx.graph) : null- }+ const copyActions = createClipboardCopyActions(ctx)+ const exportActions = createClipboardExportActions(ctx)+ const fontActions = createClipboardFontActions(ctx)+ const imageActions = createClipboardImageActions(ctx)+ const placementActions = createClipboardPlacementActions(ctx)return {collectSubtrees,- centerNodesAt,- loadFontsForNodes,+ ...placementActions,+ ...fontActions,duplicateSelected,- writeCopyData,+ ...copyActions,pasteFromHTML,warnMissingImages,deleteSelected,- storeImage,- placeImageFiles,- copySelectionAsText,- copySelectionAsSVG,- copySelectionAsJSX+ ...imageActions,+ ...exportActions}}diff --git a/packages/core/src/editor/clipboard/copy.ts b/packages/core/src/editor/clipboard/copy.tsnew file mode 100644index 000000000..63a6a476b--- /dev/null+++ b/packages/core/src/editor/clipboard/copy.ts@@ -0,0 +1,19 @@+import { buildFigmaClipboardHTML, buildOpenPencilClipboardHTML } from '#core/clipboard'++import type { EditorContext } from '#core/editor/types'+import type { SceneNode } from '#core/scene-graph'++export function createClipboardCopyActions(ctx: EditorContext) {+ async function writeCopyData(clipboardData: DataTransfer, selectedNodes: SceneNode[]) {+ if (selectedNodes.length === 0) return++ const names = selectedNodes.map((n) => n.name).join('\n')+ clipboardData.setData('text/html', buildOpenPencilClipboardHTML(selectedNodes, ctx.graph))+ clipboardData.setData('text/plain', names)++ const html = await buildFigmaClipboardHTML(selectedNodes, ctx.graph)+ if (html) clipboardData.setData('text/html', html)+ }++ return { writeCopyData }+}diff --git a/packages/core/src/editor/clipboard/export.ts b/packages/core/src/editor/clipboard/export.tsnew file mode 100644index 000000000..b54020e27--- /dev/null+++ b/packages/core/src/editor/clipboard/export.ts@@ -0,0 +1,22 @@+import { selectionToJSX } from '#core/design-jsx'+import { renderNodesToSVG } from '#core/io/formats/svg'++import type { EditorContext } from '#core/editor/types'++export function createClipboardExportActions(ctx: EditorContext) {+ function copySelectionAsText(ids: string[]): string {+ return ids.map((id) => ctx.graph.getNode(id)?.name ?? id).join('\n')+ }++ function copySelectionAsSVG(ids: string[]): string | null {+ const nodeIds =+ ids.length > 0 ? ids : ctx.graph.getChildren(ctx.state.currentPageId).map((n) => n.id)+ return renderNodesToSVG(ctx.graph, ctx.state.currentPageId, nodeIds)+ }++ function copySelectionAsJSX(ids: string[]): string | null {+ return ids.length > 0 ? selectionToJSX(ids, ctx.graph) : null+ }++ return { copySelectionAsText, copySelectionAsSVG, copySelectionAsJSX }+}diff --git a/packages/core/src/editor/clipboard/fonts.ts b/packages/core/src/editor/clipboard/fonts.tsnew file mode 100644index 000000000..a61fd2e96--- /dev/null+++ b/packages/core/src/editor/clipboard/fonts.ts@@ -0,0 +1,18 @@+import { computeAllLayouts } from '#core/layout'+import { collectFontKeys } from '#core/text/fonts'++import type { EditorContext } from '#core/editor/types'++export function createClipboardFontActions(ctx: EditorContext) {+ async function loadFontsForNodes(nodeIds: string[]) {+ const toLoad = collectFontKeys(ctx.graph, nodeIds)+ if (toLoad.length === 0) return []++ const results = await Promise.all(toLoad.map(([family, style]) => ctx.loadFont(family, style)))+ const failed = toLoad.filter((_, i) => results[i] === null)+ computeAllLayouts(ctx.graph, ctx.state.currentPageId)+ return failed+ }++ return { loadFontsForNodes }+}diff --git a/packages/core/src/editor/clipboard/images.ts b/packages/core/src/editor/clipboard/images.tsnew file mode 100644index 000000000..10ccb6032--- /dev/null+++ b/packages/core/src/editor/clipboard/images.ts@@ -0,0 +1,107 @@+import { computeImageHash } from '#core/figma-api'++import type { Fill } from '#core/scene-graph'+import type { EditorContext } from '#core/editor/types'++const IMAGE_MAX_DIMENSION = 4096+const IMAGE_GAP = 20++export function createClipboardImageActions(ctx: EditorContext) {+ function storeImage(bytes: Uint8Array): string {+ const hash = computeImageHash(bytes)+ ctx.graph.images.set(hash, bytes)+ return hash+ }++ function decodeImageDimensions(bytes: Uint8Array): { w: number; h: number } | null {+ const ck = ctx.getCk()+ if (!ck) return null+ const skImg = ck.MakeImageFromEncoded(bytes)+ if (!skImg) return null+ let w = skImg.width()+ let h = skImg.height()+ skImg.delete()+ if (w > IMAGE_MAX_DIMENSION || h > IMAGE_MAX_DIMENSION) {+ const ratio = Math.min(IMAGE_MAX_DIMENSION / w, IMAGE_MAX_DIMENSION / h)+ w = Math.round(w * ratio)+ h = Math.round(h * ratio)+ }+ return { w, h }+ }++ function placeImageNode(+ bytes: Uint8Array,+ x: number,+ y: number,+ w: number,+ h: number,+ name = 'Image'+ ): string | null {+ const hash = storeImage(bytes)+ const displayName = name.replace(/\.[^.]+$/, '')+ const pid = ctx.state.currentPageId+ const fill: Fill = {+ type: 'IMAGE',+ imageHash: hash,+ imageScaleMode: 'FILL',+ color: { r: 0, g: 0, b: 0, a: 0 },+ opacity: 1,+ visible: true+ }+ const node = ctx.graph.createNode('RECTANGLE', pid, {+ name: displayName,+ x,+ y,+ width: w,+ height: h,+ fills: [fill]+ })+ const id = node.id+ const snapshot = { ...node }+ ctx.undo.push({+ label: 'Place image',+ forward: () => {+ ctx.graph.images.set(hash, bytes)+ ctx.graph.createNode(snapshot.type, pid, snapshot)+ },+ inverse: () => {+ ctx.graph.deleteNode(id)+ ctx.graph.images.delete(hash)+ const next = new Set(ctx.state.selectedIds)+ next.delete(id)+ ctx.state.selectedIds = next+ }+ })+ return id+ }++ async function placeImageFiles(files: File[], cx: number, cy: number) {+ const prepared: Array<{ bytes: Uint8Array; name: string; w: number; h: number }> = []+ for (const file of files) {+ const bytes = new Uint8Array(await file.arrayBuffer())+ const dims = decodeImageDimensions(bytes)+ if (dims) prepared.push({ bytes, name: file.name, ...dims })+ }+ if (!prepared.length) return++ let totalW = 0+ for (const p of prepared) totalW += p.w+ totalW += IMAGE_GAP * (prepared.length - 1)+ const maxH = Math.max(...prepared.map((p) => p.h))++ let curX = cx - totalW / 2+ const topY = cy - maxH / 2+ const ids: string[] = []+ for (const p of prepared) {+ const id = placeImageNode(p.bytes, curX, topY, p.w, p.h, p.name)+ if (id) ids.push(id)+ curX += p.w + IMAGE_GAP+ }+ if (ids.length) {+ ctx.state.selectedIds = new Set(ids)+ ctx.requestRender()+ }+ }++ return { storeImage, placeImageFiles }+}diff --git a/packages/core/src/editor/clipboard/placement.ts b/packages/core/src/editor/clipboard/placement.tsnew file mode 100644index 000000000..7f5d8958d--- /dev/null+++ b/packages/core/src/editor/clipboard/placement.ts@@ -0,0 +1,19 @@+import { computeBounds } from '#core/geometry'++import type { EditorContext } from '#core/editor/types'++export function createClipboardPlacementActions(ctx: EditorContext) {+ function centerNodesAt(nodeIds: string[], cx: number, cy: number) {+ const items = nodeIds.map((id) => ctx.graph.getNode(id)).filter((node) => node != null)+ const bounds = computeBounds(items)+ if (bounds.width === 0 && bounds.height === 0 && items.length === 0) return+ const dx = cx - (bounds.x + bounds.width / 2)+ const dy = cy - (bounds.y + bounds.height / 2)+ for (const id of nodeIds) {+ const node = ctx.graph.getNode(id)+ if (node) ctx.graph.updateNode(id, { x: node.x + dx, y: node.y + dy })+ }+ }++ return { centerNodesAt }+}diff --git a/packages/core/src/editor/clipboard/subtree-history.ts b/packages/core/src/editor/clipboard/subtree-history.tsnew file mode 100644index 000000000..ce2641dd4--- /dev/null+++ b/packages/core/src/editor/clipboard/subtree-history.ts@@ -0,0 +1,39 @@+import type { SceneGraph, SceneNode } from '#core/scene-graph'++export function collectSubtrees(graph: SceneGraph, rootIds: string[]): SceneNode[] {+ const result: SceneNode[] = []+ function walk(id: string) {+ const node = graph.getNode(id)+ if (!node) return+ result.push({ ...node })+ for (const childId of node.childIds) walk(childId)+ }+ for (const id of rootIds) walk(id)+ return result+}++export function snapshotSubtree(graph: SceneGraph, rootId: string): Map<string, SceneNode> {+ const index = new Map<string, SceneNode>()+ const walk = (id: string) => {+ const node = graph.getNode(id)+ if (!node) return+ index.set(id, structuredClone(node))+ for (const childId of node.childIds) walk(childId)+ }+ walk(rootId)+ return index+}++export function restoreSubtree(+ graph: SceneGraph,+ snapshot: SceneNode,+ parentId: string,+ index: Map<string, SceneNode>+): void {+ const { parentId: _parentId, childIds, ...rest } = snapshot+ graph.createNode(snapshot.type, parentId, { ...rest, id: snapshot.id })+ for (const childId of childIds) {+ const child = index.get(childId)+ if (child) restoreSubtree(graph, child, snapshot.id, index)+ }+}diff --git a/packages/core/src/editor/color-space.ts b/packages/core/src/editor/color-space.tsindex 81fb8be1a..5a237845e 100644--- a/packages/core/src/editor/color-space.ts+++ b/packages/core/src/editor/color-space.ts@@ -1,12 +1,16 @@-import { resolveOkHCLForPreview } from '../color/management'-import { rgbaToOkHCL } from '../color/okhcl'-import { copyEffects, copyFill, copyStyleRuns, copyStroke } from '../scene-graph/copy'+import { resolveOkHCLForPreview } from '#core/color/management'+import { rgbaToOkHCL } from '#core/color/okhcl'+import { copyEffects, copyFill, copyStyleRuns, copyStroke } from '#core/scene-graph/copy'-import type { DocumentColorSpace, SceneNode } from '../scene-graph'+import type { DocumentColorSpace, SceneNode } from '#core/scene-graph'import type { EditorContext } from './types'export type DocumentColorProfileMode = 'assign' | 'convert'+function remapColor(color: SceneNode['fills'][number]['color'], target: DocumentColorSpace) {+ return resolveOkHCLForPreview(rgbaToOkHCL(color), { documentColorSpace: target }).color+}+function remapNodeColors(node: SceneNode,target: DocumentColorSpace,@@ -17,40 +21,32 @@ function remapNodeColors(const fills = node.fills.map((fill) => {const next = copyFill(fill)if (fill.type === 'SOLID') {- const resolved = resolveOkHCLForPreview(rgbaToOkHCL(fill.color), {- documentColorSpace: target- }).color+ const resolved = remapColor(fill.color, target)next.color = resolvednext.opacity = resolved.areturn next}if (fill.gradientStops) {- next.gradientStops = fill.gradientStops.map((stop) => {- const resolved = resolveOkHCLForPreview(rgbaToOkHCL(stop.color), {- documentColorSpace: target- }).color- return { ...stop, color: resolved }- })+ next.gradientStops = fill.gradientStops.map((stop) => ({+ ...stop,+ color: remapColor(stop.color, target)+ }))}return next})const strokes = node.strokes.map((stroke) => {const next = copyStroke(stroke)- const resolved = resolveOkHCLForPreview(rgbaToOkHCL(stroke.color), {- documentColorSpace: target- }).color+ const resolved = remapColor(stroke.color, target)next.color = resolvednext.opacity = resolved.areturn next})- const effects = copyEffects(node.effects).map((effect) => {- const resolved = resolveOkHCLForPreview(rgbaToOkHCL(effect.color), {- documentColorSpace: target- }).color- return { ...effect, color: resolved }- })+ const effects = copyEffects(node.effects).map((effect) => ({+ ...effect,+ color: remapColor(effect.color, target)+ }))const styleRuns = copyStyleRuns(node.styleRuns).map((run) => ({...run,@@ -59,9 +55,7 @@ function remapNodeColors(fills: run.style.fills?.map((fill) => {const next = copyFill(fill)if (fill.type === 'SOLID') {- const resolved = resolveOkHCLForPreview(rgbaToOkHCL(fill.color), {- documentColorSpace: target- }).color+ const resolved = remapColor(fill.color, target)next.color = resolvednext.opacity = resolved.a}diff --git a/packages/core/src/editor/component-sync.ts b/packages/core/src/editor/component-sync.tsnew file mode 100644index 000000000..f69cb0750--- /dev/null+++ b/packages/core/src/editor/component-sync.ts@@ -0,0 +1,37 @@+import type { SceneGraph } from '#core/scene-graph'++export function createComponentSyncScheduler(getGraph: () => SceneGraph, requestRender: () => void) {+ let pendingComponentSync: Set<string> | null = null++ function flushComponentSync() {+ const ids = pendingComponentSync+ if (!ids) return+ pendingComponentSync = null+ const graph = getGraph()+ const componentIds = new Set<string>()+ for (const id of ids) {+ let current = graph.getNode(id)+ while (current) {+ if (current.type === 'COMPONENT') {+ componentIds.add(current.id)+ break+ }+ current = current.parentId ? graph.getNode(current.parentId) : undefined+ }+ }+ for (const compId of componentIds) {+ graph.syncInstances(compId)+ }+ if (componentIds.size > 0) requestRender()+ }++ function scheduleComponentSync(nodeId: string) {+ if (!pendingComponentSync) {+ pendingComponentSync = new Set()+ queueMicrotask(flushComponentSync)+ }+ pendingComponentSync.add(nodeId)+ }++ return { scheduleComponentSync }+}diff --git a/packages/core/src/editor/components.ts b/packages/core/src/editor/components.tsindex 296f863b3..fe6c664c9 100644--- a/packages/core/src/editor/components.ts+++ b/packages/core/src/editor/components.ts@@ -1,4 +1,7 @@-import type { SceneNode } from '../scene-graph'+import { createComponentFocusActions } from './components/focus'+import { createComponentInstanceActions } from './components/instances'++import type { SceneNode } from '#core/scene-graph'import type { EditorContext } from './types'export function createComponentActions(ctx: EditorContext) {@@ -54,88 +57,13 @@ export function createComponentActions(ctx: EditorContext) {wrapSelectionInContainer('COMPONENT_SET', selectedNodes)}- function createInstanceFromComponent(componentId: string, x?: number, y?: number) {- const component = ctx.graph.getNode(componentId)- if (component?.type !== 'COMPONENT') return null-- const parentId = component.parentId ?? ctx.state.currentPageId- const instance = ctx.graph.createInstance(componentId, parentId, {- x: x ?? component.x + component.width + 40,- y: y ?? component.y- })- if (!instance) return null-- const instanceId = instance.id- ctx.state.selectedIds = new Set([instanceId])-- ctx.undo.push({- label: 'Create instance',- forward: () => {- ctx.graph.createInstance(componentId, parentId, { ...instance })- ctx.state.selectedIds = new Set([instanceId])- },- inverse: () => {- ctx.graph.deleteNode(instanceId)- ctx.state.selectedIds = new Set([componentId])- }- })- return instanceId- }-- function detachInstance(selectedNode: SceneNode | undefined) {- if (selectedNode?.type !== 'INSTANCE') return-- const prevComponentId = selectedNode.componentId-- ctx.graph.detachInstance(selectedNode.id)- ctx.state.selectedIds = new Set([selectedNode.id])-- ctx.undo.push({- label: 'Detach instance',- forward: () => {- ctx.graph.detachInstance(selectedNode.id)- ctx.requestRender()- },- inverse: () => {- ctx.graph.updateNode(selectedNode.id, {- type: 'INSTANCE',- componentId: prevComponentId,- overrides: {}- })- }- })- }-- function goToMainComponent(- selectedNode: SceneNode | undefined,- switchPage: (pageId: string) => Promise<void>- ) {- if (!selectedNode?.componentId) return- const main = ctx.graph.getMainComponent(selectedNode.id)- if (!main) return-- let current: SceneNode | undefined = main- while (current && current.type !== 'CANVAS') {- current = current.parentId ? ctx.graph.getNode(current.parentId) : undefined- }- if (current && current.id !== ctx.state.currentPageId) {- void switchPage(current.id)- }-- ctx.state.selectedIds = new Set([main.id])-- const abs = ctx.graph.getAbsolutePosition(main.id)- const { width: viewW, height: viewH } = ctx.getViewportSize()- ctx.state.panX = viewW / 2 - (abs.x + main.width / 2) * ctx.state.zoom- ctx.state.panY = viewH / 2 - (abs.y + main.height / 2) * ctx.state.zoom- ctx.requestRender()- }+ const focusActions = createComponentFocusActions(ctx)+ const instanceActions = createComponentInstanceActions(ctx)return {createComponentFromSelection,createComponentSetFromComponents,- createInstanceFromComponent,- detachInstance,- goToMainComponent+ ...instanceActions,+ ...focusActions}}diff --git a/packages/core/src/editor/components/focus.ts b/packages/core/src/editor/components/focus.tsnew file mode 100644index 000000000..024f9f9ad--- /dev/null+++ b/packages/core/src/editor/components/focus.ts@@ -0,0 +1,31 @@+import type { SceneNode } from '#core/scene-graph'+import type { EditorContext } from '#core/editor/types'++export function createComponentFocusActions(ctx: EditorContext) {+ function goToMainComponent(+ selectedNode: SceneNode | undefined,+ switchPage: (pageId: string) => Promise<void>+ ) {+ if (!selectedNode?.componentId) return+ const main = ctx.graph.getMainComponent(selectedNode.id)+ if (!main) return++ let current: SceneNode | undefined = main+ while (current && current.type !== 'CANVAS') {+ current = current.parentId ? ctx.graph.getNode(current.parentId) : undefined+ }+ if (current && current.id !== ctx.state.currentPageId) {+ void switchPage(current.id)+ }++ ctx.state.selectedIds = new Set([main.id])++ const abs = ctx.graph.getAbsolutePosition(main.id)+ const { width: viewW, height: viewH } = ctx.getViewportSize()+ ctx.state.panX = viewW / 2 - (abs.x + main.width / 2) * ctx.state.zoom+ ctx.state.panY = viewH / 2 - (abs.y + main.height / 2) * ctx.state.zoom+ ctx.requestRender()+ }++ return { goToMainComponent }+}diff --git a/packages/core/src/editor/components/instances.ts b/packages/core/src/editor/components/instances.tsnew file mode 100644index 000000000..fbcb53328--- /dev/null+++ b/packages/core/src/editor/components/instances.ts@@ -0,0 +1,58 @@+import type { SceneNode } from '#core/scene-graph'+import type { EditorContext } from '#core/editor/types'++export function createComponentInstanceActions(ctx: EditorContext) {+ function createInstanceFromComponent(componentId: string, x?: number, y?: number) {+ const component = ctx.graph.getNode(componentId)+ if (component?.type !== 'COMPONENT') return null++ const parentId = component.parentId ?? ctx.state.currentPageId+ const instance = ctx.graph.createInstance(componentId, parentId, {+ x: x ?? component.x + component.width + 40,+ y: y ?? component.y+ })+ if (!instance) return null++ const instanceId = instance.id+ ctx.state.selectedIds = new Set([instanceId])++ ctx.undo.push({+ label: 'Create instance',+ forward: () => {+ ctx.graph.createInstance(componentId, parentId, { ...instance })+ ctx.state.selectedIds = new Set([instanceId])+ },+ inverse: () => {+ ctx.graph.deleteNode(instanceId)+ ctx.state.selectedIds = new Set([componentId])+ }+ })+ return instanceId+ }++ function detachInstance(selectedNode: SceneNode | undefined) {+ if (selectedNode?.type !== 'INSTANCE') return++ const prevComponentId = selectedNode.componentId++ ctx.graph.detachInstance(selectedNode.id)+ ctx.state.selectedIds = new Set([selectedNode.id])++ ctx.undo.push({+ label: 'Detach instance',+ forward: () => {+ ctx.graph.detachInstance(selectedNode.id)+ ctx.requestRender()+ },+ inverse: () => {+ ctx.graph.updateNode(selectedNode.id, {+ type: 'INSTANCE',+ componentId: prevComponentId,+ overrides: {}+ })+ }+ })+ }++ return { createInstanceFromComponent, detachInstance }+}diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.tsindex 658949099..7322478ca 100644--- a/packages/core/src/editor/create.ts+++ b/packages/core/src/editor/create.ts@@ -1,56 +1,38 @@-import { prefetchFigmaSchema } from '../clipboard'-import { getDefaultCanvasBgColor, IS_BROWSER } from '../constants'-import { computeAllLayouts, computeLayout, setTextMeasurer } from '../layout'-import { SceneGraph } from '../scene-graph'-import { UndoManager } from '../scene-graph/undo'-import { TextEditor } from '../text/editor'-import { loadFont as defaultLoadFont } from '../text/fonts'+import { prefetchFigmaSchema } from '#core/clipboard'+import { IS_BROWSER } from '#core/constants'+import { setTextMeasurer } from '#core/layout'+import { SceneGraph } from '#core/scene-graph'+import { UndoManager } from '#core/scene-graph/undo'+import { TextEditor } from '#core/text/editor'+import { loadFont as defaultLoadFont } from '#core/text/fonts'+import { createClipboardBridge } from './bridges/clipboard'+import { createComponentBridge } from './bridges/components'+import { createStructureBridge } from './bridges/structure'+import { createUndoBridge } from './bridges/undo'import { createAlignmentActions } from './alignment'import { createClipboardActions } from './clipboard'import { createColorSpaceActions } from './color-space'import { createComponentActions } from './components'+import { createComponentSyncScheduler } from './component-sync'+import { createGraphEventSubscription } from './graph-events'+import { createGraphReadActions } from './graph-reads'+import { createLayoutRunner } from './layout-runner'import { createNodeActions } from './nodes'import { createPageActions } from './pages'import { createSelectionActions } from './selection'import { createShapeActions } from './shapes'+import { createDefaultEditorState } from './state'import { createStructureActions } from './structure'import { createTextActions } from './text'import { createUndoActions } from './undo'import { createVariableActions } from './variables'import { createViewportActions } from './viewport'-import type { SkiaRenderer } from '../canvas/renderer'-import type { SceneNode } from '../scene-graph'+import type { SkiaRenderer } from '#core/canvas/renderer'import type { EditorContext, EditorOptions, EditorState } from './types'import type { CanvasKit } from 'canvaskit-wasm'-export function createDefaultEditorState(pageId: string): EditorState {- return {- activeTool: 'SELECT',- currentPageId: pageId,- selectedIds: new Set<string>(),- marquee: null,- snapGuides: [],- rotationPreview: null,- dropTargetId: null,- layoutInsertIndicator: null,- hoveredNodeId: null,- editingTextId: null,- penState: null,- penCursorX: null,- penCursorY: null,- remoteCursors: [],- documentName: 'Untitled',- panX: 0,- pageColor: { ...getDefaultCanvasBgColor() },- panY: 0,- zoom: 1,- renderVersion: 0,- sceneVersion: 0,- loading: false,- enteredContainerId: null- }-}+export { createDefaultEditorState } from './state'export function createEditor(options?: EditorOptions) {let _graph = options?.graph ?? new SceneGraph()@@ -65,6 +47,7 @@ export function createEditor(options?: EditorOptions) {})let _ck: CanvasKit | null = nulllet _renderer: SkiaRenderer | null = null+ const _renderers = new Set<SkiaRenderer>()let _textEditor: TextEditor | null = nullvoid prefetchFigmaSchema()@@ -80,79 +63,16 @@ export function createEditor(options?: EditorOptions) {state.renderVersion++}- function runLayoutForNode(id: string) {- const node = _graph.getNode(id)- if (!node) return-- computeAllLayouts(_graph, id)-- let parent = node.parentId ? _graph.getNode(node.parentId) : undefined- while (parent) {- if (parent.layoutMode !== 'NONE') {- computeLayout(_graph, parent.id)- }- parent = parent.parentId ? _graph.getNode(parent.parentId) : undefined- }- }+ const graphReads = createGraphReadActions(() => _graph)+ const { runLayoutForNode } = createLayoutRunner(() => _graph)+ const { scheduleComponentSync } = createComponentSyncScheduler(() => _graph, requestRender)- // Microtask-batched component sync- let pendingComponentSync: Set<string> | null = null-- function flushComponentSync() {- const ids = pendingComponentSync- if (!ids) return- pendingComponentSync = null- const componentIds = new Set<string>()- for (const id of ids) {- let current = _graph.getNode(id)- while (current) {- if (current.type === 'COMPONENT') {- componentIds.add(current.id)- break- }- current = current.parentId ? _graph.getNode(current.parentId) : undefined- }- }- for (const compId of componentIds) {- _graph.syncInstances(compId)- }- if (componentIds.size > 0) requestRender()- }-- function scheduleComponentSync(nodeId: string) {- if (!pendingComponentSync) {- pendingComponentSync = new Set()- queueMicrotask(flushComponentSync)- }- pendingComponentSync.add(nodeId)- }-- function onNodeUpdated(id: string, changes: Partial<SceneNode>) {- if ('vectorNetwork' in changes) {- _renderer?.invalidateVectorPath(id)- }- _renderer?.invalidateNodePicture(id)- scheduleComponentSync(id)- requestRender()- }-- function onNodeStructureChanged(nodeId: string) {- scheduleComponentSync(nodeId)- requestRender()- }-- let graphUnbinds: Array<() => void> = []-- function subscribeToGraph() {- for (const u of graphUnbinds) u()- graphUnbinds = [- _graph.emitter.on('node:updated', onNodeUpdated),- _graph.emitter.on('node:created', (node) => onNodeStructureChanged(node.id)),- _graph.emitter.on('node:deleted', onNodeStructureChanged),- _graph.emitter.on('node:reparented', onNodeStructureChanged),- _graph.emitter.on('node:reordered', onNodeStructureChanged)- ]- }+ const { subscribeToGraph } = createGraphEventSubscription({+ getGraph: () => _graph,+ getRenderers: () => _renderers,+ scheduleComponentSync,+ requestRender+ })if (!skipInitialGraphSetup) {subscribeToGraph()@@ -193,14 +113,26 @@ export function createEditor(options?: EditorOptions) {const nodes = createNodeActions(ctx)const variables = createVariableActions(ctx)const alignment = createAlignmentActions(ctx)+ const clipboardBridge = createClipboardBridge(clipboard, selection)+ const componentBridge = createComponentBridge(components, selection, structure, pages)+ const structureBridge = createStructureBridge(structure, selection)+ const undoBridge = createUndoBridge(undoActions, selection)function setCanvasKit(ck: CanvasKit, renderer: SkiaRenderer) {_ck = ck_renderer = renderer- _textEditor = new TextEditor(ck)+ _renderers.add(renderer)+ _textEditor ??= new TextEditor(ck)setTextMeasurer((node, maxWidth) => renderer.measureTextNode(node, maxWidth))}+ function removeCanvasRenderer(renderer: SkiaRenderer) {+ _renderers.delete(renderer)+ if (_renderer === renderer) {+ _renderer = _renderers.values().next().value ?? null+ }+ }+function replaceGraph(newGraph: SceneGraph) {_graph = newGraphsubscribeToGraph()@@ -225,15 +157,13 @@ export function createEditor(options?: EditorOptions) {state,// Graph reads- getNode: (id: string) => _graph.getNode(id),- getImage: (hash: string) => _graph.images.get(hash),- getChildren: (id: string) => _graph.getChildren(id),- getPages: (includeInternal?: boolean) => _graph.getPages(includeInternal),+ ...graphReads,// LifecyclerequestRender,requestRepaint,setCanvasKit,+ removeCanvasRenderer,replaceGraph,subscribeToGraph,@@ -265,52 +195,18 @@ export function createEditor(options?: EditorOptions) {...viewport,// Undo — bridge functions that need cross-module refs- commitMove: undoActions.commitMove,- commitMoveWithReparent: undoActions.commitMoveWithReparent,- commitResize: undoActions.commitResize,- commitRotation: undoActions.commitRotation,- commitNodeUpdate: undoActions.commitNodeUpdate,- undoAction: () => undoActions.undoAction(selection.validateEnteredContainer),- redoAction: () => undoActions.redoAction(selection.validateEnteredContainer),- snapshotPage: undoActions.snapshotPage,- restorePageFromSnapshot: undoActions.restorePageFromSnapshot,- pushUndoEntry: undoActions.pushUndoEntry,+ ...undoBridge,setDocumentColorSpace: colorSpace.setDocumentColorSpace,// Clipboard — bridge functions that need selectedNodes- duplicateSelected: () => clipboard.duplicateSelected(selection.getSelectedNodes()),- writeCopyData: (data: DataTransfer) =>- clipboard.writeCopyData(data, selection.getSelectedNodes()),- pasteFromHTML: clipboard.pasteFromHTML,- deleteSelected: clipboard.deleteSelected,- storeImage: clipboard.storeImage,- placeImageFiles: clipboard.placeImageFiles,- loadFontsForNodes: clipboard.loadFontsForNodes,- copySelectionAsText: clipboard.copySelectionAsText,- copySelectionAsSVG: clipboard.copySelectionAsSVG,- copySelectionAsJSX: clipboard.copySelectionAsJSX,+ ...clipboardBridge,// Components — bridge functions- createComponentFromSelection: () =>- components.createComponentFromSelection(- selection.getSelectedNodes(),- structure.wrapSelectionInContainer- ),- createComponentSetFromComponents: () =>- components.createComponentSetFromComponents(- selection.getSelectedNodes(),- structure.wrapSelectionInContainer- ),- createInstanceFromComponent: components.createInstanceFromComponent,- detachInstance: () => components.detachInstance(selection.getSelectedNode()),- goToMainComponent: () =>- components.goToMainComponent(selection.getSelectedNode(), pages.switchPage),+ ...componentBridge,// Structure — bridge functions that need selectedNodes- wrapInAutoLayout: () => structure.wrapInAutoLayout(selection.getSelectedNodes()),- groupSelected: () => structure.groupSelected(selection.getSelectedNodes()),- ungroupSelected: () => structure.ungroupSelected(selection.getSelectedNode())+ ...structureBridge}}diff --git a/packages/core/src/editor/graph-events.ts b/packages/core/src/editor/graph-events.tsnew file mode 100644index 000000000..de01c4c95--- /dev/null+++ b/packages/core/src/editor/graph-events.ts@@ -0,0 +1,40 @@+import type { SkiaRenderer } from '#core/canvas/renderer'+import type { SceneGraph, SceneNode } from '#core/scene-graph'++type GraphEventOptions = {+ getGraph: () => SceneGraph+ getRenderers: () => Iterable<SkiaRenderer>+ scheduleComponentSync: (nodeId: string) => void+ requestRender: () => void+}++export function createGraphEventSubscription(options: GraphEventOptions) {+ let unbindGraphEvents: (() => void) | null = null++ function onNodeUpdated(id: string, changes: Partial<SceneNode>) {+ for (const renderer of options.getRenderers()) {+ if ('vectorNetwork' in changes) renderer.invalidateVectorPath(id)+ renderer.invalidateNodePicture(id)+ }+ options.scheduleComponentSync(id)+ options.requestRender()+ }++ function onNodeStructureChanged(nodeId: string) {+ options.scheduleComponentSync(nodeId)+ options.requestRender()+ }++ function subscribeToGraph() {+ unbindGraphEvents?.()+ unbindGraphEvents = options.getGraph().onNodeEvents({+ updated: onNodeUpdated,+ created: (node) => onNodeStructureChanged(node.id),+ deleted: onNodeStructureChanged,+ reparented: onNodeStructureChanged,+ reordered: onNodeStructureChanged+ })+ }++ return { subscribeToGraph }+}diff --git a/packages/core/src/editor/graph-reads.ts b/packages/core/src/editor/graph-reads.tsnew file mode 100644index 000000000..8bc138bf4--- /dev/null+++ b/packages/core/src/editor/graph-reads.ts@@ -0,0 +1,10 @@+import type { SceneGraph } from '#core/scene-graph'++export function createGraphReadActions(getGraph: () => SceneGraph) {+ return {+ getNode: (id: string) => getGraph().getNode(id),+ getImage: (hash: string) => getGraph().images.get(hash),+ getChildren: (id: string) => getGraph().getChildren(id),+ getPages: (includeInternal?: boolean) => getGraph().getPages(includeInternal)+ }+}diff --git a/packages/core/src/editor/history/position.ts b/packages/core/src/editor/history/position.tsnew file mode 100644index 000000000..f94d7e132--- /dev/null+++ b/packages/core/src/editor/history/position.ts@@ -0,0 +1,34 @@+import type { EditorContext } from '#core/editor/types'+import type { Vector } from '#core/types'++export function collectNodePositions(+ ctx: EditorContext,+ ids: Iterable<string>+): Map<string, Vector> {+ const positions = new Map<string, Vector>()+ for (const id of ids) {+ const node = ctx.graph.getNode(id)+ if (node) positions.set(id, { x: node.x, y: node.y })+ }+ return positions+}++export function pushPositionUndo(+ ctx: EditorContext,+ label: string,+ originals: Map<string, Vector>,+ finals: Map<string, Vector>+): void {+ ctx.undo.push({+ label,+ forward: () => applyPositions(ctx, finals),+ inverse: () => applyPositions(ctx, originals)+ })+}++function applyPositions(ctx: EditorContext, positions: Map<string, Vector>): void {+ for (const [id, pos] of positions) {+ ctx.graph.updateNode(id, pos)+ ctx.runLayoutForNode(id)+ }+}diff --git a/packages/core/src/editor/history/snapshot.ts b/packages/core/src/editor/history/snapshot.tsnew file mode 100644index 000000000..1e3f61b9b--- /dev/null+++ b/packages/core/src/editor/history/snapshot.ts@@ -0,0 +1,50 @@+import { computeAllLayouts } from '#core/layout'++import type { EditorContext } from '#core/editor/types'+import type { SceneGraph, SceneNode } from '#core/scene-graph'++export type PageSnapshot = Map<string, SceneNode>++export function snapshotPage(graph: SceneGraph, pageId: string): PageSnapshot {+ const snapshot: PageSnapshot = new Map()+ const walk = (id: string) => {+ const node = graph.getNode(id)+ if (!node) return+ snapshot.set(id, structuredClone(node))+ for (const childId of node.childIds) walk(childId)+ }+ walk(pageId)+ return snapshot+}++export function restorePageFromSnapshot(ctx: EditorContext, snapshot: PageSnapshot): void {+ const pageId = ctx.state.currentPageId+ const page = ctx.graph.getNode(pageId)+ const pageSnap = snapshot.get(pageId)+ if (!page || !pageSnap) return++ for (const childId of page.childIds.slice()) ctx.graph.deleteNode(childId)+ restoreChildren(ctx.graph, snapshot, pageId, pageSnap.childIds)++ ctx.graph.clearAbsPosCache()+ computeAllLayouts(ctx.graph, pageId)+ ctx.state.selectedIds = new Set()+ ctx.state.hoveredNodeId = null+ ctx.requestRender()+}++function restoreChildren(+ graph: SceneGraph,+ snapshot: PageSnapshot,+ parentId: string,+ childIds: string[]+): void {+ for (const childId of childIds) {+ const snap = snapshot.get(childId)+ if (!snap) continue+ const { parentId: _snapParentId, childIds: snapChildIds, ...rest } = snap+ graph.createNode(snap.type, parentId, { ...rest, childIds: [] })+ graph.reorderChild(snap.id, parentId, childIds.indexOf(childId))+ restoreChildren(graph, snapshot, snap.id, snapChildIds)+ }+}diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.tsindex 5cd8693c1..a309beb3b 100644--- a/packages/core/src/editor/index.ts+++ b/packages/core/src/editor/index.ts@@ -1,5 +1,6 @@export { createDefaultEditorState, createEditor } from './create'export type { Editor } from './create'export { createTextActions } from './text'-export { EDITOR_TOOLS, TOOL_SHORTCUTS } from './types'-export type { EditorContext, EditorOptions, EditorState, EditorToolDef, Tool } from './types'+export { EDITOR_TOOLS, TOOL_SHORTCUTS } from './tool-registry'+export type { EditorToolDef } from './tool-registry'+export type { EditorContext, EditorOptions, EditorState, Tool } from './types'diff --git a/packages/core/src/editor/layout-mode.ts b/packages/core/src/editor/layout-mode.tsnew file mode 100644index 000000000..49ebd2092--- /dev/null+++ b/packages/core/src/editor/layout-mode.ts@@ -0,0 +1,124 @@+import { computeLayout } from '#core/layout'++import type { LayoutMode, SceneNode } from '#core/scene-graph'+import type { EditorContext } from './types'++export function createLayoutModeActions(ctx: EditorContext) {+ function setLayoutMode(id: string, mode: LayoutMode) {+ const node = ctx.graph.getNode(id)+ if (!node) return++ const previous = captureLayoutState(node)+ const updates = layoutModeUpdates(ctx, node, id, mode)++ ctx.graph.updateNode(id, updates)+ if (mode !== 'NONE') computeLayout(ctx.graph, id)+ ctx.runLayoutForNode(id)++ const updated = ctx.graph.getNode(id)+ if (!updated) return+ const finalState = pickState(updated, Object.keys(previous) as (keyof SceneNode)[])++ ctx.undo.push({+ label: mode === 'NONE' ? 'Remove auto layout' : 'Add auto layout',+ forward: () => {+ ctx.graph.updateNode(id, finalState)+ if (mode !== 'NONE') computeLayout(ctx.graph, id)+ ctx.runLayoutForNode(id)+ },+ inverse: () => {+ ctx.graph.updateNode(id, previous)+ ctx.runLayoutForNode(id)+ }+ })+ }++ return { setLayoutMode }+}++function captureLayoutState(node: SceneNode): Partial<SceneNode> {+ return {+ layoutMode: node.layoutMode,+ itemSpacing: node.itemSpacing,+ paddingTop: node.paddingTop,+ paddingRight: node.paddingRight,+ paddingBottom: node.paddingBottom,+ paddingLeft: node.paddingLeft,+ primaryAxisSizing: node.primaryAxisSizing,+ counterAxisSizing: node.counterAxisSizing,+ primaryAxisAlign: node.primaryAxisAlign,+ counterAxisAlign: node.counterAxisAlign,+ gridTemplateColumns: node.gridTemplateColumns,+ gridTemplateRows: node.gridTemplateRows,+ gridColumnGap: node.gridColumnGap,+ gridRowGap: node.gridRowGap,+ width: node.width,+ height: node.height+ }+}++function pickState(node: SceneNode, keys: (keyof SceneNode)[]): Partial<SceneNode> {+ return Object.fromEntries(keys.map((key) => [key, node[key]])) as Partial<SceneNode>+}++function layoutModeUpdates(+ ctx: EditorContext,+ node: SceneNode,+ id: string,+ mode: LayoutMode+): Partial<SceneNode> {+ const updates: Partial<SceneNode> = { layoutMode: mode }+ if (mode === 'GRID' && node.layoutMode !== 'GRID') {+ applyGridDefaults(ctx, node, id, updates)+ } else if (mode !== 'NONE' && node.layoutMode === 'NONE') {+ Object.assign(updates, autoLayoutDefaults())+ }+ return updates+}++function applyGridDefaults(+ ctx: EditorContext,+ node: SceneNode,+ id: string,+ updates: Partial<SceneNode>+) {+ const children = ctx.graph.getChildren(id)+ const cols = Math.max(2, Math.ceil(Math.sqrt(children.length)))+ const rows = Math.max(1, Math.ceil(children.length / cols))+ updates.gridTemplateColumns = Array.from({ length: cols }, () => ({+ sizing: 'FR' as const,+ value: 1+ }))+ updates.gridTemplateRows = Array.from({ length: rows }, () => ({+ sizing: 'FR' as const,+ value: 1+ }))+ updates.gridColumnGap = 0+ updates.gridRowGap = 0+ updates.primaryAxisSizing = 'FIXED'+ updates.counterAxisSizing = 'FIXED'+ if (node.primaryAxisSizing === 'HUG' || node.counterAxisSizing === 'HUG') {+ const maxChildW = Math.max(...children.map((child) => child.width), 100)+ const maxChildH = Math.max(...children.map((child) => child.height), 100)+ updates.width = maxChildW * cols+ updates.height = maxChildH * rows+ }+ updates.paddingTop = 0+ updates.paddingRight = 0+ updates.paddingBottom = 0+ updates.paddingLeft = 0+}++function autoLayoutDefaults(): Partial<SceneNode> {+ return {+ itemSpacing: 0,+ paddingTop: 0,+ paddingRight: 0,+ paddingBottom: 0,+ paddingLeft: 0,+ primaryAxisSizing: 'HUG',+ counterAxisSizing: 'HUG',+ primaryAxisAlign: 'MIN',+ counterAxisAlign: 'MIN'+ }+}diff --git a/packages/core/src/editor/layout-runner.ts b/packages/core/src/editor/layout-runner.tsnew file mode 100644index 000000000..60dedf285--- /dev/null+++ b/packages/core/src/editor/layout-runner.ts@@ -0,0 +1,23 @@+import { computeAllLayouts, computeLayout } from '#core/layout'++import type { SceneGraph } from '#core/scene-graph'++export function createLayoutRunner(getGraph: () => SceneGraph) {+ function runLayoutForNode(id: string) {+ const graph = getGraph()+ const node = graph.getNode(id)+ if (!node) return++ computeAllLayouts(graph, id)++ let parent = node.parentId ? graph.getNode(node.parentId) : undefined+ while (parent) {+ if (parent.layoutMode !== 'NONE') {+ computeLayout(graph, parent.id)+ }+ parent = parent.parentId ? graph.getNode(parent.parentId) : undefined+ }+ }++ return { runLayoutForNode }+}diff --git a/packages/core/src/editor/nodes.ts b/packages/core/src/editor/nodes.tsindex bd65ee92b..4b2126c83 100644--- a/packages/core/src/editor/nodes.ts+++ b/packages/core/src/editor/nodes.ts@@ -1,12 +1,15 @@-import { computeLayout } from '../layout'+import { createLayoutModeActions } from './layout-mode'+import { createNudgeActions } from './nudge'+import { createVariableBindingActions } from './variable-bindings'-import type { LayoutMode, SceneNode } from '../scene-graph'-import type { Vector } from '../types'+import type { SceneNode } from '#core/scene-graph'import type { EditorContext } from './types'-const NUDGE_COMMIT_DELAY = 300-export function createNodeActions(ctx: EditorContext) {+ const layoutModeActions = createLayoutModeActions(ctx)+ const nudgeActions = createNudgeActions(ctx)+ const variableBindingActions = createVariableBindingActions(ctx)+function updateNode(id: string, changes: Partial<SceneNode>) {ctx.graph.updateNode(id, changes)ctx.runLayoutForNode(id)@@ -34,209 +37,11 @@ export function createNodeActions(ctx: EditorContext) {ctx.requestRender()}- function setLayoutMode(id: string, mode: LayoutMode) {- const node = ctx.graph.getNode(id)- if (!node) return-- const previous: Partial<SceneNode> = {- layoutMode: node.layoutMode,- itemSpacing: node.itemSpacing,- paddingTop: node.paddingTop,- paddingRight: node.paddingRight,- paddingBottom: node.paddingBottom,- paddingLeft: node.paddingLeft,- primaryAxisSizing: node.primaryAxisSizing,- counterAxisSizing: node.counterAxisSizing,- primaryAxisAlign: node.primaryAxisAlign,- counterAxisAlign: node.counterAxisAlign,- gridTemplateColumns: node.gridTemplateColumns,- gridTemplateRows: node.gridTemplateRows,- gridColumnGap: node.gridColumnGap,- gridRowGap: node.gridRowGap,- width: node.width,- height: node.height- }-- const updates: Partial<SceneNode> = { layoutMode: mode }- if (mode === 'GRID' && node.layoutMode !== 'GRID') {- const children = ctx.graph.getChildren(id)- const cols = Math.max(2, Math.ceil(Math.sqrt(children.length)))- const rows = Math.max(1, Math.ceil(children.length / cols))- updates.gridTemplateColumns = Array.from({ length: cols }, () => ({- sizing: 'FR' as const,- value: 1- }))- updates.gridTemplateRows = Array.from({ length: rows }, () => ({- sizing: 'FR' as const,- value: 1- }))- updates.gridColumnGap = 0- updates.gridRowGap = 0- updates.primaryAxisSizing = 'FIXED'- updates.counterAxisSizing = 'FIXED'- if (node.primaryAxisSizing === 'HUG' || node.counterAxisSizing === 'HUG') {- const maxChildW = Math.max(...children.map((c) => c.width), 100)- const maxChildH = Math.max(...children.map((c) => c.height), 100)- updates.width = maxChildW * cols- updates.height = maxChildH * rows- }- updates.paddingTop = 0- updates.paddingRight = 0- updates.paddingBottom = 0- updates.paddingLeft = 0- } else if (mode !== 'NONE' && node.layoutMode === 'NONE') {- updates.itemSpacing = 0- updates.paddingTop = 0- updates.paddingRight = 0- updates.paddingBottom = 0- updates.paddingLeft = 0- updates.primaryAxisSizing = 'HUG'- updates.counterAxisSizing = 'HUG'- updates.primaryAxisAlign = 'MIN'- updates.counterAxisAlign = 'MIN'- }-- ctx.graph.updateNode(id, updates)- if (mode !== 'NONE') computeLayout(ctx.graph, id)- ctx.runLayoutForNode(id)-- const updated = ctx.graph.getNode(id)- if (!updated) return- const finalState = Object.fromEntries(- (Object.keys(previous) as (keyof SceneNode)[]).map((key) => [key, updated[key]])- ) as Partial<SceneNode>-- ctx.undo.push({- label: mode === 'NONE' ? 'Remove auto layout' : 'Add auto layout',- forward: () => {- ctx.graph.updateNode(id, finalState)- if (mode !== 'NONE') computeLayout(ctx.graph, id)- ctx.runLayoutForNode(id)- },- inverse: () => {- ctx.graph.updateNode(id, previous)- ctx.runLayoutForNode(id)- }- })- }-- function bindVariable(nodeId: string, path: string, variableId: string) {- const node = ctx.graph.getNode(nodeId)- if (!node) return- const prevVarId = node.boundVariables[path]- ctx.graph.bindVariable(nodeId, path, variableId)- ctx.undo.push({- label: 'Bind variable',- forward: () => {- ctx.graph.bindVariable(nodeId, path, variableId)- ctx.requestRender()- },- inverse: () => {- if (prevVarId) ctx.graph.bindVariable(nodeId, path, prevVarId)- else ctx.graph.unbindVariable(nodeId, path)- ctx.requestRender()- }- })- ctx.requestRender()- }-- function unbindVariable(nodeId: string, path: string) {- const node = ctx.graph.getNode(nodeId)- if (!node) return- const prevVarId = node.boundVariables[path]- if (!prevVarId) return- ctx.graph.unbindVariable(nodeId, path)- ctx.undo.push({- label: 'Unbind variable',- forward: () => {- ctx.graph.unbindVariable(nodeId, path)- ctx.requestRender()- },- inverse: () => {- ctx.graph.bindVariable(nodeId, path, prevVarId)- ctx.requestRender()- }- })- ctx.requestRender()- }-- let nudgeOriginals: Map<string, Vector> | null = null- let nudgeCommitTimer: ReturnType<typeof setTimeout> | null = null-- function commitNudge() {- if (!nudgeOriginals) return- const originals = nudgeOriginals- nudgeOriginals = null- nudgeCommitTimer = null-- const finals = new Map<string, Vector>()- for (const [id] of originals) {- const node = ctx.graph.getNode(id)- if (node) finals.set(id, { x: node.x, y: node.y })- }- ctx.undo.push({- label: 'Nudge',- forward: () => {- for (const [id, pos] of finals) {- ctx.graph.updateNode(id, pos)- ctx.runLayoutForNode(id)- }- },- inverse: () => {- for (const [id, pos] of originals) {- ctx.graph.updateNode(id, pos)- ctx.runLayoutForNode(id)- }- }- })- }-- function nudgeSelected(dx: number, dy: number) {- const ids = [...ctx.state.selectedIds]- if (ids.length === 0) return-- const movable: string[] = []- for (const id of ids) {- const node = ctx.graph.getNode(id)- if (node && !node.locked) movable.push(id)- }- if (movable.length === 0) return-- if (!nudgeOriginals) {- nudgeOriginals = new Map()- for (const id of movable) {- const node = ctx.graph.getNode(id)- if (node) nudgeOriginals.set(id, { x: node.x, y: node.y })- }- }-- for (const id of movable) {- const node = ctx.graph.getNode(id)- if (!node) continue- ctx.graph.updateNode(id, { x: node.x + dx, y: node.y + dy })- ctx.runLayoutForNode(id)- }-- if (nudgeCommitTimer) clearTimeout(nudgeCommitTimer)- nudgeCommitTimer = setTimeout(commitNudge, NUDGE_COMMIT_DELAY)-- ctx.requestRender()- }-- function flushNudge() {- if (nudgeCommitTimer) {- clearTimeout(nudgeCommitTimer)- commitNudge()- }- }-return {updateNode,updateNodeWithUndo,- setLayoutMode,- bindVariable,- unbindVariable,- nudgeSelected,- flushNudge+ ...layoutModeActions,+ ...variableBindingActions,+ ...nudgeActions}}diff --git a/packages/core/src/editor/nudge.ts b/packages/core/src/editor/nudge.tsnew file mode 100644index 000000000..a33a95c50--- /dev/null+++ b/packages/core/src/editor/nudge.ts@@ -0,0 +1,62 @@+import { collectNodePositions, pushPositionUndo } from './history/position'++import type { Vector } from '#core/types'+import type { EditorContext } from './types'++const NUDGE_COMMIT_DELAY = 300++export function createNudgeActions(ctx: EditorContext) {+ let nudgeOriginals: Map<string, Vector> | null = null+ let nudgeCommitTimer: ReturnType<typeof setTimeout> | null = null++ function commitNudge() {+ if (!nudgeOriginals) return+ const originals = nudgeOriginals+ nudgeOriginals = null+ nudgeCommitTimer = null++ const finals = collectNodePositions(ctx, originals.keys())+ pushPositionUndo(ctx, 'Nudge', originals, finals)+ }++ function nudgeSelected(dx: number, dy: number) {+ const ids = [...ctx.state.selectedIds]+ if (ids.length === 0) return++ const movable: string[] = []+ for (const id of ids) {+ const node = ctx.graph.getNode(id)+ if (node && !node.locked) movable.push(id)+ }+ if (movable.length === 0) return++ if (!nudgeOriginals) {+ nudgeOriginals = new Map()+ for (const id of movable) {+ const node = ctx.graph.getNode(id)+ if (node) nudgeOriginals.set(id, { x: node.x, y: node.y })+ }+ }++ for (const id of movable) {+ const node = ctx.graph.getNode(id)+ if (!node) continue+ ctx.graph.updateNode(id, { x: node.x + dx, y: node.y + dy })+ ctx.runLayoutForNode(id)+ }++ if (nudgeCommitTimer) clearTimeout(nudgeCommitTimer)+ nudgeCommitTimer = setTimeout(commitNudge, NUDGE_COMMIT_DELAY)++ ctx.requestRender()+ }++ function flushNudge() {+ if (nudgeCommitTimer) {+ clearTimeout(nudgeCommitTimer)+ commitNudge()+ }+ }++ return { nudgeSelected, flushNudge }+}diff --git a/packages/core/src/editor/page-viewports.ts b/packages/core/src/editor/page-viewports.tsnew file mode 100644index 000000000..31862c0a2--- /dev/null+++ b/packages/core/src/editor/page-viewports.ts@@ -0,0 +1,50 @@+import { getDefaultCanvasBgColor } from '#core/constants'++import type { Color } from '#core/types'+import type { EditorContext } from './types'++interface PageViewport {+ panX: number+ panY: number+ zoom: number+ pageColor: Color+}++export function createPageViewportStore(ctx: EditorContext) {+ const pageViewports = new Map<string, PageViewport>()++ function saveCurrentPageViewport() {+ pageViewports.set(ctx.state.currentPageId, {+ panX: ctx.state.panX,+ panY: ctx.state.panY,+ zoom: ctx.state.zoom,+ pageColor: { ...ctx.state.pageColor }+ })+ }++ function restorePageViewport(pageId: string) {+ const viewport = pageViewports.get(pageId)+ if (viewport) {+ ctx.state.panX = viewport.panX+ ctx.state.panY = viewport.panY+ ctx.state.zoom = viewport.zoom+ ctx.state.pageColor = { ...viewport.pageColor }+ return+ }++ ctx.state.panX = 0+ ctx.state.panY = 0+ ctx.state.zoom = 1+ ctx.state.pageColor = { ...getDefaultCanvasBgColor() }+ }++ function deletePageViewport(pageId: string) {+ pageViewports.delete(pageId)+ }++ function clearPageViewports() {+ pageViewports.clear()+ }++ return { saveCurrentPageViewport, restorePageViewport, deletePageViewport, clearPageViewports }+}diff --git a/packages/core/src/editor/pages.ts b/packages/core/src/editor/pages.tsindex 2e50c3073..cccdf5977 100644--- a/packages/core/src/editor/pages.ts+++ b/packages/core/src/editor/pages.ts@@ -1,47 +1,25 @@-import { getDefaultCanvasBgColor } from '../constants'-import { computeAllLayouts } from '../layout'-import { collectFontKeys } from '../text/fonts'+import { computeAllLayouts } from '#core/layout'+import { collectFontKeys } from '#core/text/fonts'-import type { Color } from '../types'-import type { EditorContext } from './types'+import { createPageViewportStore } from './page-viewports'-interface PageViewport {- panX: number- panY: number- zoom: number- pageColor: Color-}+import type { Color } from '#core/types'+import type { EditorContext } from './types'export function createPageActions(ctx: EditorContext) {- const pageViewports = new Map<string, PageViewport>()+ const pageViewportStore = createPageViewportStore(ctx)async function switchPage(pageId: string) {const page = ctx.graph.getNode(pageId)if (page?.type !== 'CANVAS') return- pageViewports.set(ctx.state.currentPageId, {- panX: ctx.state.panX,- panY: ctx.state.panY,- zoom: ctx.state.zoom,- pageColor: { ...ctx.state.pageColor }- })+ pageViewportStore.saveCurrentPageViewport()ctx.state.currentPageId = pageIdctx.state.enteredContainerId = nullctx.state.selectedIds = new Set()- const vp = pageViewports.get(pageId)- if (vp) {- ctx.state.panX = vp.panX- ctx.state.panY = vp.panY- ctx.state.zoom = vp.zoom- ctx.state.pageColor = { ...vp.pageColor }- } else {- ctx.state.panX = 0- ctx.state.panY = 0- ctx.state.zoom = 1- ctx.state.pageColor = { ...getDefaultCanvasBgColor() }- }+ pageViewportStore.restorePageViewport(pageId)const toLoad = collectFontKeys(ctx.graph,@@ -69,7 +47,7 @@ export function createPageActions(ctx: EditorContext) {if (pages.length <= 1) returnconst idx = pages.findIndex((p) => p.id === pageId)ctx.graph.deleteNode(pageId)- pageViewports.delete(pageId)+ pageViewportStore.deletePageViewport(pageId)if (ctx.state.currentPageId === pageId) {const newIdx = Math.min(idx, pages.length - 2)const remaining = ctx.graph.getPages()@@ -86,9 +64,12 @@ export function createPageActions(ctx: EditorContext) {ctx.requestRender()}- function clearPageViewports() {- pageViewports.clear()+ return {+ switchPage,+ addPage,+ deletePage,+ renamePage,+ setPageColor,+ clearPageViewports: pageViewportStore.clearPageViewports}-- return { switchPage, addPage, deletePage, renamePage, setPageColor, clearPageViewports }}diff --git a/packages/core/src/editor/selection.ts b/packages/core/src/editor/selection.tsindex b445bbd31..da5339374 100644--- a/packages/core/src/editor/selection.ts+++ b/packages/core/src/editor/selection.ts@@ -1,6 +1,7 @@-import type { SceneNode } from '../scene-graph'-import type { SnapGuide } from '../scene-graph/snap'-import type { Rect } from '../types'+import { createSelectionContainerActions } from './selection/container'+import { createSelectionHitTestActions } from './selection/hit-test'+import { createSelectionOverlayActions } from './selection/overlays'+import { createSelectionReadActions } from './selection/read'import type { EditorContext } from './types'export function createSelectionActions(ctx: EditorContext) {@@ -26,126 +27,18 @@ export function createSelectionActions(ctx: EditorContext) {ctx.state.selectedIds = new Set(children.map((n) => n.id))}- function setMarquee(rect: Rect | null) {- ctx.state.marquee = rect- ctx.requestRepaint()- }-- function setSnapGuides(guides: SnapGuide[]) {- ctx.state.snapGuides = guides- ctx.requestRepaint()- }-- function setRotationPreview(preview: { nodeId: string; angle: number } | null) {- ctx.state.rotationPreview = preview- ctx.requestRepaint()- }-- function setHoveredNode(id: string | null) {- if (ctx.state.hoveredNodeId === id) return- ctx.state.hoveredNodeId = id- ctx.requestRepaint()- }-- function setDropTarget(id: string | null) {- ctx.state.dropTargetId = id- ctx.requestRepaint()- }-- function setLayoutInsertIndicator(indicator: typeof ctx.state.layoutInsertIndicator) {- ctx.state.layoutInsertIndicator = indicator- ctx.requestRepaint()- }-- function validateEnteredContainer() {- if (ctx.state.enteredContainerId && !ctx.graph.getNode(ctx.state.enteredContainerId)) {- ctx.state.enteredContainerId = null- }- }-- function enterContainer(id: string) {- ctx.state.enteredContainerId = id- }-- function exitContainer() {- const entered = ctx.state.enteredContainerId- if (!entered) return- const node = ctx.graph.getNode(entered)- const parentId = node?.parentId- if (parentId && parentId !== ctx.state.currentPageId) {- ctx.state.enteredContainerId = parentId- } else {- ctx.state.enteredContainerId = null- }- ctx.state.selectedIds = new Set(entered ? [entered] : [])- }-- function getSelectedNodes() {- const nodes = []- for (const id of ctx.state.selectedIds) {- const n = ctx.graph.getNode(id)- if (n) nodes.push({ ...n })- }- return nodes- }-- function getSelectedNode() {- if (ctx.state.selectedIds.size !== 1) return undefined- const id = ctx.state.selectedIds.values().next().value as string- const n = ctx.graph.getNode(id)- return n ? { ...n } : undefined- }-- function getLayerTree() {- return ctx.graph.flattenTree(ctx.state.currentPageId)- }-- function hitTestAtPoint(cx: number, cy: number, deep = false): SceneNode | null {- const renderer = ctx.getRenderer()- if (!renderer) return null- const scopeId = ctx.state.enteredContainerId- if (scopeId) {- const scopeNode = ctx.graph.getNode(scopeId)- if (!scopeNode) {- ctx.state.enteredContainerId = null- } else {- const abs = ctx.graph.getAbsolutePosition(scopeId)- const lx = cx - abs.x- const ly = cy - abs.y- return deep ? ctx.graph.hitTestDeep(lx, ly, scopeId) : ctx.graph.hitTest(lx, ly, scopeId)- }- }- return deep- ? ctx.graph.hitTestDeep(cx, cy, ctx.state.currentPageId)- : ctx.graph.hitTest(cx, cy, ctx.state.currentPageId)- }-- function selectAtPoint(cx: number, cy: number) {- const hit = hitTestAtPoint(cx, cy)- if (hit) {- if (!ctx.state.selectedIds.has(hit.id)) select([hit.id])- } else {- clearSelection()- }- }+ const containerActions = createSelectionContainerActions(ctx)+ const hitTestActions = createSelectionHitTestActions(ctx, select, clearSelection)+ const overlayActions = createSelectionOverlayActions(ctx)+ const readActions = createSelectionReadActions(ctx)return {select,clearSelection,selectAll,- setMarquee,- setSnapGuides,- setRotationPreview,- setHoveredNode,- setDropTarget,- setLayoutInsertIndicator,- validateEnteredContainer,- enterContainer,- exitContainer,- getSelectedNodes,- getSelectedNode,- getLayerTree,- hitTestAtPoint,- selectAtPoint+ ...overlayActions,+ ...containerActions,+ ...readActions,+ ...hitTestActions}}diff --git a/packages/core/src/editor/selection/container.ts b/packages/core/src/editor/selection/container.tsnew file mode 100644index 000000000..4537d0bb6--- /dev/null+++ b/packages/core/src/editor/selection/container.ts@@ -0,0 +1,28 @@+import type { EditorContext } from '#core/editor/types'++export function createSelectionContainerActions(ctx: EditorContext) {+ function validateEnteredContainer() {+ if (ctx.state.enteredContainerId && !ctx.graph.getNode(ctx.state.enteredContainerId)) {+ ctx.state.enteredContainerId = null+ }+ }++ function enterContainer(id: string) {+ ctx.state.enteredContainerId = id+ }++ function exitContainer() {+ const entered = ctx.state.enteredContainerId+ if (!entered) return+ const node = ctx.graph.getNode(entered)+ const parentId = node?.parentId+ if (parentId && parentId !== ctx.state.currentPageId) {+ ctx.state.enteredContainerId = parentId+ } else {+ ctx.state.enteredContainerId = null+ }+ ctx.state.selectedIds = new Set(entered ? [entered] : [])+ }++ return { validateEnteredContainer, enterContainer, exitContainer }+}diff --git a/packages/core/src/editor/selection/hit-test.ts b/packages/core/src/editor/selection/hit-test.tsnew file mode 100644index 000000000..5259816c5--- /dev/null+++ b/packages/core/src/editor/selection/hit-test.ts@@ -0,0 +1,39 @@+import type { SceneNode } from '#core/scene-graph'+import type { EditorContext } from '#core/editor/types'++export function createSelectionHitTestActions(+ ctx: EditorContext,+ select: (ids: string[], additive?: boolean) => void,+ clearSelection: () => void+) {+ function hitTestAtPoint(cx: number, cy: number, deep = false): SceneNode | null {+ const renderer = ctx.getRenderer()+ if (!renderer) return null+ const scopeId = ctx.state.enteredContainerId+ if (scopeId) {+ const scopeNode = ctx.graph.getNode(scopeId)+ if (!scopeNode) {+ ctx.state.enteredContainerId = null+ } else {+ const abs = ctx.graph.getAbsolutePosition(scopeId)+ const lx = cx - abs.x+ const ly = cy - abs.y+ return deep ? ctx.graph.hitTestDeep(lx, ly, scopeId) : ctx.graph.hitTest(lx, ly, scopeId)+ }+ }+ return deep+ ? ctx.graph.hitTestDeep(cx, cy, ctx.state.currentPageId)+ : ctx.graph.hitTest(cx, cy, ctx.state.currentPageId)+ }++ function selectAtPoint(cx: number, cy: number) {+ const hit = hitTestAtPoint(cx, cy)+ if (hit) {+ if (!ctx.state.selectedIds.has(hit.id)) select([hit.id])+ } else {+ clearSelection()+ }+ }++ return { hitTestAtPoint, selectAtPoint }+}diff --git a/packages/core/src/editor/selection/overlays.ts b/packages/core/src/editor/selection/overlays.tsnew file mode 100644index 000000000..52e578808--- /dev/null+++ b/packages/core/src/editor/selection/overlays.ts@@ -0,0 +1,45 @@+import type { SnapGuide } from '#core/scene-graph/snap'+import type { Rect } from '#core/types'+import type { EditorContext } from '#core/editor/types'++export function createSelectionOverlayActions(ctx: EditorContext) {+ function setMarquee(rect: Rect | null) {+ ctx.state.marquee = rect+ ctx.requestRepaint()+ }++ function setSnapGuides(guides: SnapGuide[]) {+ ctx.state.snapGuides = guides+ ctx.requestRepaint()+ }++ function setRotationPreview(preview: { nodeId: string; angle: number } | null) {+ ctx.state.rotationPreview = preview+ ctx.requestRepaint()+ }++ function setHoveredNode(id: string | null) {+ if (ctx.state.hoveredNodeId === id) return+ ctx.state.hoveredNodeId = id+ ctx.requestRepaint()+ }++ function setDropTarget(id: string | null) {+ ctx.state.dropTargetId = id+ ctx.requestRepaint()+ }++ function setLayoutInsertIndicator(indicator: typeof ctx.state.layoutInsertIndicator) {+ ctx.state.layoutInsertIndicator = indicator+ ctx.requestRepaint()+ }++ return {+ setMarquee,+ setSnapGuides,+ setRotationPreview,+ setHoveredNode,+ setDropTarget,+ setLayoutInsertIndicator+ }+}diff --git a/packages/core/src/editor/selection/read.ts b/packages/core/src/editor/selection/read.tsnew file mode 100644index 000000000..69106eda5--- /dev/null+++ b/packages/core/src/editor/selection/read.ts@@ -0,0 +1,25 @@+import type { EditorContext } from '#core/editor/types'++export function createSelectionReadActions(ctx: EditorContext) {+ function getSelectedNodes() {+ const nodes = []+ for (const id of ctx.state.selectedIds) {+ const node = ctx.graph.getNode(id)+ if (node) nodes.push({ ...node })+ }+ return nodes+ }++ function getSelectedNode() {+ if (ctx.state.selectedIds.size !== 1) return undefined+ const id = ctx.state.selectedIds.values().next().value as string+ const node = ctx.graph.getNode(id)+ return node ? { ...node } : undefined+ }++ function getLayerTree() {+ return ctx.graph.flattenTree(ctx.state.currentPageId)+ }++ return { getSelectedNodes, getSelectedNode, getLayerTree }+}diff --git a/packages/core/src/editor/shapes.ts b/packages/core/src/editor/shapes.tsindex 9677899d8..294b70988 100644--- a/packages/core/src/editor/shapes.ts+++ b/packages/core/src/editor/shapes.ts@@ -3,25 +3,13 @@ import {DEFAULT_SHAPE_FILL,SECTION_DEFAULT_FILL,SECTION_DEFAULT_STROKE-} from '../constants'-import { computeVectorBounds } from '../vector'+} from '#core/constants'+import { createPenActions } from './shapes/pen'+import { adoptNodesIntoSection as adoptNodesIntoSectionImpl } from './shapes/section-adopt'-import type {- Fill,- NodeType,- SceneNode,- VectorNetwork,- VectorRegion,- VectorSegment-} from '../scene-graph'-import type { Vector } from '../types'+import type { Fill, NodeType, SceneNode } from '#core/scene-graph'import type { EditorContext } from './types'--export interface PenDragOptions {- keepOpposite?: boolean- constrainToOpposite?: boolean- oppositeTangent?: Vector | null-}+export type { PenDragOptions } from './shapes/pen'const BLACK_FILL: Fill = {type: 'SOLID',@@ -30,14 +18,6 @@ const BLACK_FILL: Fill = {visible: true}-const PEN_DEFAULT_STROKE: SceneNode['strokes'][number] = {- color: { r: 0, g: 0, b: 0, a: 1 },- weight: 2,- opacity: 1,- visible: true,- align: 'CENTER'-}-const DEFAULT_FILLS: Record<string, Fill> = {FRAME: DEFAULT_FRAME_FILL,SECTION: SECTION_DEFAULT_FILL,@@ -49,32 +29,6 @@ const DEFAULT_FILLS: Record<string, Fill> = {TEXT: BLACK_FILL}-function projectTangentToAxis(active: Vector, opposite: Vector): Vector {- const axis = { x: -opposite.x, y: -opposite.y }- const axisLen = Math.hypot(axis.x, axis.y)- if (axisLen <= 1e-6) return active- const dir = { x: axis.x / axisLen, y: axis.y / axisLen }- const len = Math.max(0, active.x * dir.x + active.y * dir.y)- return { x: dir.x * len, y: dir.y * len }-}--function applyAnchorTangent(- tangent: Vector,- isClosing: boolean,- firstSeg: VectorSegment | undefined,- lastSeg: VectorSegment | undefined-): void {- if (isClosing) {- if (!firstSeg) return- if (firstSeg.start === 0) firstSeg.tangentStart = { x: tangent.x, y: tangent.y }- else if (firstSeg.end === 0) firstSeg.tangentEnd = { x: tangent.x, y: tangent.y }- return- }- if (lastSeg) {- lastSeg.tangentEnd = { x: tangent.x, y: tangent.y }- }-}-export function createShapeActions(ctx: EditorContext) {function createShape(type: NodeType,@@ -122,235 +76,7 @@ export function createShapeActions(ctx: EditorContext) {return id}- function penAddVertex(x: number, y: number) {- if (!ctx.state.penState) {- ctx.state.penState = {- vertices: [{ x, y }],- segments: [],- dragTangent: null,- oppositeDragTangent: null,- pendingClose: false,- closingToFirst: false- }- ctx.requestRender()- return- }-- const ps = ctx.state.penState- const prevIdx = ps.vertices.length - 1-- ps.vertices.push({ x, y })- const newIdx = ps.vertices.length - 1- ps.segments.push({- start: prevIdx,- end: newIdx,- tangentStart: ps.dragTangent ?? { x: 0, y: 0 },- tangentEnd: { x: 0, y: 0 }- })- ps.dragTangent = null- ps.oppositeDragTangent = null- ps.pendingClose = false- ctx.requestRender()- }-- function penSetDragTangent(tx: number, ty: number, options?: PenDragOptions) {- if (!ctx.state.penState) return- const ps = ctx.state.penState- let active = { x: tx, y: ty }- const isClosing = !!ps.pendingClose && ps.vertices.length > 2- const anchorIndex = isClosing ? 0 : ps.vertices.length - 1- const lastSeg = ps.segments.length > 0 ? ps.segments[ps.segments.length - 1] : undefined- const firstSeg = ps.segments.length > 0 ? ps.segments[0] : undefined- const opposite =- options?.oppositeTangent ??- ps.oppositeDragTangent ??- (lastSeg ? lastSeg.tangentEnd : { x: -tx, y: -ty })-- if (options?.constrainToOpposite) {- active = projectTangentToAxis(active, opposite)- }-- ps.dragTangent = active- const keepOpposite = options?.keepOpposite ?? isClosing- if (keepOpposite) {- ps.oppositeDragTangent = { x: opposite.x, y: opposite.y }- applyAnchorTangent(opposite, isClosing, firstSeg, lastSeg)- if (options?.constrainToOpposite) {- ps.vertices[anchorIndex].handleMirroring = 'ANGLE'- } else {- ps.vertices[anchorIndex].handleMirroring = 'NONE'- }- } else {- const symmetric = { x: -active.x, y: -active.y }- ps.oppositeDragTangent = symmetric- applyAnchorTangent(symmetric, isClosing, firstSeg, lastSeg)- ps.vertices[anchorIndex].handleMirroring = 'ANGLE_AND_LENGTH'- }- ctx.requestRender()- }-- function penSetClosingToFirst(closing: boolean) {- if (!ctx.state.penState) return- ctx.state.penState.closingToFirst = closing- ctx.requestRender()- }-- function penSetPendingClose(closing: boolean) {- if (!ctx.state.penState) return- ctx.state.penState.pendingClose = closing- ctx.requestRepaint()- }-- function penSetKnotPosition(x: number, y: number) {- if (!ctx.state.penState) return- const ps = ctx.state.penState- const isClosing = !!ps.pendingClose && ps.vertices.length > 2- const anchorIndex = isClosing ? 0 : ps.vertices.length - 1- ps.vertices[anchorIndex].x = x- ps.vertices[anchorIndex].y = y- ctx.requestRender()- }-- function penCommit(closed: boolean) {- const ps = ctx.state.penState- if (!ps || ps.vertices.length < 2) {- ctx.state.penState = null- ctx.state.penCursorX = null- ctx.state.penCursorY = null- return- }-- if (closed && ps.pendingClose && ps.vertices.length > 2) {- const prevIdx = ps.vertices.length - 1- ps.segments.push({- start: prevIdx,- end: 0,- tangentStart: { x: 0, y: 0 },- tangentEnd: ps.dragTangent ?? { x: 0, y: 0 }- })- }-- const regions: VectorRegion[] = closed- ? [{ windingRule: 'NONZERO', loops: [ps.segments.map((_, i) => i)] }]- : []-- const network: VectorNetwork = {- vertices: ps.vertices.map((v) => ({ ...v })),- segments: ps.segments.map((s) => ({- ...s,- tangentStart: { ...s.tangentStart },- tangentEnd: { ...s.tangentEnd }- })),- regions- }-- const bounds = computeVectorBounds(network)-- const normalizedVertices = network.vertices.map((v) => ({- ...v,- x: v.x - bounds.x,- y: v.y - bounds.y- }))-- const normalizedNetwork: VectorNetwork = {- vertices: normalizedVertices,- segments: network.segments,- regions: network.regions- }-- const penStyle = ps as typeof ps & {- resumedFills?: Fill[]- resumedStrokes?: SceneNode['strokes']- }- const fills = penStyle.resumedFills ? penStyle.resumedFills.map((f) => ({ ...f })) : []- const strokes = penStyle.resumedStrokes- ? penStyle.resumedStrokes.map((s) => ({ ...s }))- : [{ ...PEN_DEFAULT_STROKE }]-- const nodeId = createShape('VECTOR', bounds.x, bounds.y, bounds.width, bounds.height)- ctx.graph.updateNode(nodeId, {- vectorNetwork: normalizedNetwork,- name: 'Vector',- fills,- strokes- })- ctx.state.selectedIds = new Set([nodeId])-- ctx.state.penState = null- ctx.state.penCursorX = null- ctx.state.penCursorY = null- ctx.state.activeTool = 'SELECT'- ctx.requestRender()- }-- function penCancel() {- ctx.state.penState = null- ctx.state.penCursorX = null- ctx.state.penCursorY = null- ctx.state.activeTool = 'SELECT'- ctx.requestRender()- }-- function adoptNodesIntoSection(sectionId: string) {- const section = ctx.graph.getNode(sectionId)- if (section?.type !== 'SECTION') return-- const parentId = section.parentId ?? ctx.state.currentPageId- const siblings = ctx.graph.getChildren(parentId)-- const sx = section.x- const sy = section.y- const sx2 = sx + section.width- const sy2 = sy + section.height-- const toAdopt: string[] = []- for (const sibling of siblings) {- if (sibling.id === sectionId) continue- const nx = sibling.x- const ny = sibling.y- const nx2 = nx + sibling.width- const ny2 = ny + sibling.height- if (nx >= sx && ny >= sy && nx2 <= sx2 && ny2 <= sy2) {- toAdopt.push(sibling.id)- }- }-- if (toAdopt.length === 0) return-- const undoOps: Array<{- id: string- oldParent: string- oldX: number- oldY: number- newX: number- newY: number- }> = []- for (const id of toAdopt) {- const node = ctx.graph.getNode(id)- if (!node) continue- const newX = node.x - sx- const newY = node.y - sy- undoOps.push({ id, oldParent: parentId, oldX: node.x, oldY: node.y, newX, newY })- ctx.graph.reparentNode(id, sectionId)- ctx.graph.updateNode(id, { x: newX, y: newY })- }-- ctx.undo.push({- label: 'Adopt into section',- forward: () => {- for (const op of undoOps) {- ctx.graph.reparentNode(op.id, sectionId)- ctx.graph.updateNode(op.id, { x: op.newX, y: op.newY })- }- },- inverse: () => {- for (const op of undoOps) {- ctx.graph.reparentNode(op.id, op.oldParent)- ctx.graph.updateNode(op.id, { x: op.oldX, y: op.oldY })- }- }- })- }+ const penActions = createPenActions(ctx, createShape)function setTool(tool: typeof ctx.state.activeTool) {ctx.state.activeTool = tool@@ -358,14 +84,8 @@ export function createShapeActions(ctx: EditorContext) {return {createShape,- penAddVertex,- penSetDragTangent,- penSetClosingToFirst,- penSetPendingClose,- penSetKnotPosition,- penCommit,- penCancel,- adoptNodesIntoSection,+ ...penActions,+ adoptNodesIntoSection: (sectionId: string) => adoptNodesIntoSectionImpl(ctx, sectionId),setTool}}diff --git a/packages/core/src/editor/shapes/pen.ts b/packages/core/src/editor/shapes/pen.tsnew file mode 100644index 000000000..ee50816ec--- /dev/null+++ b/packages/core/src/editor/shapes/pen.ts@@ -0,0 +1,235 @@+import { computeVectorBounds } from '#core/vector'++import type { Fill, SceneNode, VectorNetwork, VectorRegion, VectorSegment } from '#core/scene-graph'+import type { Vector } from '#core/types'+import type { EditorContext } from '#core/editor/types'++export interface PenDragOptions {+ keepOpposite?: boolean+ constrainToOpposite?: boolean+ oppositeTangent?: Vector | null+}++type CreateShape = (+ type: 'VECTOR',+ x: number,+ y: number,+ w: number,+ h: number,+ parentId?: string+) => string++const PEN_DEFAULT_STROKE: SceneNode['strokes'][number] = {+ color: { r: 0, g: 0, b: 0, a: 1 },+ weight: 2,+ opacity: 1,+ visible: true,+ align: 'CENTER'+}++function projectTangentToAxis(active: Vector, opposite: Vector): Vector {+ const axis = { x: -opposite.x, y: -opposite.y }+ const axisLen = Math.hypot(axis.x, axis.y)+ if (axisLen <= 1e-6) return active+ const dir = { x: axis.x / axisLen, y: axis.y / axisLen }+ const len = Math.max(0, active.x * dir.x + active.y * dir.y)+ return { x: dir.x * len, y: dir.y * len }+}++function applyAnchorTangent(+ tangent: Vector,+ isClosing: boolean,+ firstSeg: VectorSegment | undefined,+ lastSeg: VectorSegment | undefined+): void {+ if (isClosing) {+ if (!firstSeg) return+ if (firstSeg.start === 0) firstSeg.tangentStart = { x: tangent.x, y: tangent.y }+ else if (firstSeg.end === 0) firstSeg.tangentEnd = { x: tangent.x, y: tangent.y }+ return+ }+ if (lastSeg) {+ lastSeg.tangentEnd = { x: tangent.x, y: tangent.y }+ }+}++export function createPenActions(ctx: EditorContext, createShape: CreateShape) {+ function penAddVertex(x: number, y: number) {+ if (!ctx.state.penState) {+ ctx.state.penState = {+ vertices: [{ x, y }],+ segments: [],+ dragTangent: null,+ oppositeDragTangent: null,+ pendingClose: false,+ closingToFirst: false+ }+ ctx.requestRender()+ return+ }++ const ps = ctx.state.penState+ const prevIdx = ps.vertices.length - 1++ ps.vertices.push({ x, y })+ const newIdx = ps.vertices.length - 1+ ps.segments.push({+ start: prevIdx,+ end: newIdx,+ tangentStart: ps.dragTangent ?? { x: 0, y: 0 },+ tangentEnd: { x: 0, y: 0 }+ })+ ps.dragTangent = null+ ps.oppositeDragTangent = null+ ps.pendingClose = false+ ctx.requestRender()+ }++ function penSetDragTangent(tx: number, ty: number, options?: PenDragOptions) {+ if (!ctx.state.penState) return+ const ps = ctx.state.penState+ let active = { x: tx, y: ty }+ const isClosing = !!ps.pendingClose && ps.vertices.length > 2+ const anchorIndex = isClosing ? 0 : ps.vertices.length - 1+ const lastSeg = ps.segments.length > 0 ? ps.segments[ps.segments.length - 1] : undefined+ const firstSeg = ps.segments.length > 0 ? ps.segments[0] : undefined+ const opposite =+ options?.oppositeTangent ??+ ps.oppositeDragTangent ??+ (lastSeg ? lastSeg.tangentEnd : { x: -tx, y: -ty })++ if (options?.constrainToOpposite) {+ active = projectTangentToAxis(active, opposite)+ }++ ps.dragTangent = active+ const keepOpposite = options?.keepOpposite ?? isClosing+ if (keepOpposite) {+ ps.oppositeDragTangent = { x: opposite.x, y: opposite.y }+ applyAnchorTangent(opposite, isClosing, firstSeg, lastSeg)+ if (options?.constrainToOpposite) {+ ps.vertices[anchorIndex].handleMirroring = 'ANGLE'+ } else {+ ps.vertices[anchorIndex].handleMirroring = 'NONE'+ }+ } else {+ const symmetric = { x: -active.x, y: -active.y }+ ps.oppositeDragTangent = symmetric+ applyAnchorTangent(symmetric, isClosing, firstSeg, lastSeg)+ ps.vertices[anchorIndex].handleMirroring = 'ANGLE_AND_LENGTH'+ }+ ctx.requestRender()+ }++ function penSetClosingToFirst(closing: boolean) {+ if (!ctx.state.penState) return+ ctx.state.penState.closingToFirst = closing+ ctx.requestRender()+ }++ function penSetPendingClose(closing: boolean) {+ if (!ctx.state.penState) return+ ctx.state.penState.pendingClose = closing+ ctx.requestRepaint()+ }++ function penSetKnotPosition(x: number, y: number) {+ if (!ctx.state.penState) return+ const ps = ctx.state.penState+ const isClosing = !!ps.pendingClose && ps.vertices.length > 2+ const anchorIndex = isClosing ? 0 : ps.vertices.length - 1+ ps.vertices[anchorIndex].x = x+ ps.vertices[anchorIndex].y = y+ ctx.requestRender()+ }++ function penCommit(closed: boolean) {+ const ps = ctx.state.penState+ if (!ps || ps.vertices.length < 2) {+ ctx.state.penState = null+ ctx.state.penCursorX = null+ ctx.state.penCursorY = null+ return+ }++ if (closed && ps.pendingClose && ps.vertices.length > 2) {+ const prevIdx = ps.vertices.length - 1+ ps.segments.push({+ start: prevIdx,+ end: 0,+ tangentStart: { x: 0, y: 0 },+ tangentEnd: ps.dragTangent ?? { x: 0, y: 0 }+ })+ }++ const regions: VectorRegion[] = closed+ ? [{ windingRule: 'NONZERO', loops: [ps.segments.map((_, i) => i)] }]+ : []++ const network: VectorNetwork = {+ vertices: ps.vertices.map((v) => ({ ...v })),+ segments: ps.segments.map((s) => ({+ ...s,+ tangentStart: { ...s.tangentStart },+ tangentEnd: { ...s.tangentEnd }+ })),+ regions+ }++ const bounds = computeVectorBounds(network)++ const normalizedVertices = network.vertices.map((v) => ({+ ...v,+ x: v.x - bounds.x,+ y: v.y - bounds.y+ }))++ const normalizedNetwork: VectorNetwork = {+ vertices: normalizedVertices,+ segments: network.segments,+ regions: network.regions+ }++ const penStyle = ps as typeof ps & {+ resumedFills?: Fill[]+ resumedStrokes?: SceneNode['strokes']+ }+ const fills = penStyle.resumedFills ? penStyle.resumedFills.map((f) => ({ ...f })) : []+ const strokes = penStyle.resumedStrokes+ ? penStyle.resumedStrokes.map((s) => ({ ...s }))+ : [{ ...PEN_DEFAULT_STROKE }]++ const nodeId = createShape('VECTOR', bounds.x, bounds.y, bounds.width, bounds.height)+ ctx.graph.updateNode(nodeId, {+ vectorNetwork: normalizedNetwork,+ name: 'Vector',+ fills,+ strokes+ })+ ctx.state.selectedIds = new Set([nodeId])++ ctx.state.penState = null+ ctx.state.penCursorX = null+ ctx.state.penCursorY = null+ ctx.state.activeTool = 'SELECT'+ ctx.requestRender()+ }++ function penCancel() {+ ctx.state.penState = null+ ctx.state.penCursorX = null+ ctx.state.penCursorY = null+ ctx.state.activeTool = 'SELECT'+ ctx.requestRender()+ }++ return {+ penAddVertex,+ penSetDragTangent,+ penSetClosingToFirst,+ penSetPendingClose,+ penSetKnotPosition,+ penCommit,+ penCancel+ }+}diff --git a/packages/core/src/editor/shapes/section-adopt.ts b/packages/core/src/editor/shapes/section-adopt.tsnew file mode 100644index 000000000..c0d99798b--- /dev/null+++ b/packages/core/src/editor/shapes/section-adopt.ts@@ -0,0 +1,62 @@+import type { EditorContext } from '#core/editor/types'++export function adoptNodesIntoSection(ctx: EditorContext, sectionId: string) {+ const section = ctx.graph.getNode(sectionId)+ if (section?.type !== 'SECTION') return++ const parentId = section.parentId ?? ctx.state.currentPageId+ const siblings = ctx.graph.getChildren(parentId)++ const sx = section.x+ const sy = section.y+ const sx2 = sx + section.width+ const sy2 = sy + section.height++ const toAdopt: string[] = []+ for (const sibling of siblings) {+ if (sibling.id === sectionId) continue+ const nx = sibling.x+ const ny = sibling.y+ const nx2 = nx + sibling.width+ const ny2 = ny + sibling.height+ if (nx >= sx && ny >= sy && nx2 <= sx2 && ny2 <= sy2) {+ toAdopt.push(sibling.id)+ }+ }++ if (toAdopt.length === 0) return++ const undoOps: Array<{+ id: string+ oldParent: string+ oldX: number+ oldY: number+ newX: number+ newY: number+ }> = []+ for (const id of toAdopt) {+ const node = ctx.graph.getNode(id)+ if (!node) continue+ const newX = node.x - sx+ const newY = node.y - sy+ undoOps.push({ id, oldParent: parentId, oldX: node.x, oldY: node.y, newX, newY })+ ctx.graph.reparentNode(id, sectionId)+ ctx.graph.updateNode(id, { x: newX, y: newY })+ }++ ctx.undo.push({+ label: 'Adopt into section',+ forward: () => {+ for (const op of undoOps) {+ ctx.graph.reparentNode(op.id, sectionId)+ ctx.graph.updateNode(op.id, { x: op.newX, y: op.newY })+ }+ },+ inverse: () => {+ for (const op of undoOps) {+ ctx.graph.reparentNode(op.id, op.oldParent)+ ctx.graph.updateNode(op.id, { x: op.oldX, y: op.oldY })+ }+ }+ })+}diff --git a/packages/core/src/editor/state.ts b/packages/core/src/editor/state.tsnew file mode 100644index 000000000..5a9605fdf--- /dev/null+++ b/packages/core/src/editor/state.ts@@ -0,0 +1,31 @@+import { getDefaultCanvasBgColor } from '#core/constants'++import type { EditorState } from '#core/editor/types'++export function createDefaultEditorState(pageId: string): EditorState {+ return {+ activeTool: 'SELECT',+ currentPageId: pageId,+ selectedIds: new Set<string>(),+ marquee: null,+ snapGuides: [],+ rotationPreview: null,+ dropTargetId: null,+ layoutInsertIndicator: null,+ hoveredNodeId: null,+ editingTextId: null,+ penState: null,+ penCursorX: null,+ penCursorY: null,+ remoteCursors: [],+ documentName: 'Untitled',+ panX: 0,+ pageColor: { ...getDefaultCanvasBgColor() },+ panY: 0,+ zoom: 1,+ renderVersion: 0,+ sceneVersion: 0,+ loading: false,+ enteredContainerId: null+ }+}diff --git a/packages/core/src/editor/structure.ts b/packages/core/src/editor/structure.tsindex daa9fcbd0..e1a5012cc 100644--- a/packages/core/src/editor/structure.ts+++ b/packages/core/src/editor/structure.ts@@ -1,10 +1,15 @@-import { computeAbsoluteBounds } from '../geometry'-import { computeLayout } from '../layout'+import { wrapInAutoLayout as wrapInAutoLayoutImpl } from './structure/auto-layout-wrap'+import { wrapSelectionInContainer as wrapSelectionInContainerImpl } from './structure/container-wrap'+import { ungroupSelected as ungroupImpl } from './structure/group'+import { createStructureReorderActions } from './structure/reorder'+import { createStructureStateActions } from './structure/state'-import type { LayoutMode, NodeType, SceneNode } from '../scene-graph'+import type { NodeType, SceneNode } from '#core/scene-graph'import type { EditorContext } from './types'export function createStructureActions(ctx: EditorContext) {+ const reorderActions = createStructureReorderActions(ctx)+ const stateActions = createStructureStateActions(ctx)function defaultNodeName(type: NodeType): string {return type.charAt(0) + type.slice(1).toLowerCase()}@@ -13,80 +18,6 @@ export function createStructureActions(ctx: EditorContext) {return !parentId || parentId === ctx.graph.rootId || parentId === ctx.state.currentPageId}- function doReorderChild(nodeId: string, parentId: string, insertIndex: number) {- const node = ctx.graph.getNode(nodeId)- if (!node) return-- if (node.parentId !== parentId) {- const absPos = ctx.graph.getAbsolutePosition(nodeId)- const parentAbs = ctx.graph.getAbsolutePosition(parentId)- ctx.graph.updateNode(nodeId, { x: absPos.x - parentAbs.x, y: absPos.y - parentAbs.y })- }-- ctx.graph.reorderChild(nodeId, parentId, insertIndex)- computeLayout(ctx.graph, parentId)- ctx.runLayoutForNode(parentId)- }-- function reorderInAutoLayout(nodeId: string, parentId: string, insertIndex: number) {- const parent = ctx.graph.getNode(parentId)- if (!parent || parent.layoutMode === 'NONE') return-- const node = ctx.graph.getNode(nodeId)- if (!node) return- const origParentId = node.parentId ?? ctx.state.currentPageId- const origX = node.x- const origY = node.y- const origIndex = ctx.graph.getNode(origParentId)?.childIds.indexOf(nodeId) ?? -1-- doReorderChild(nodeId, parentId, insertIndex)-- ctx.undo.push({- label: 'Reorder',- forward: () => {- doReorderChild(nodeId, parentId, insertIndex)- },- inverse: () => {- ctx.graph.reorderChild(nodeId, origParentId, origIndex >= 0 ? origIndex : 0)- ctx.graph.updateNode(nodeId, { x: origX, y: origY })- computeLayout(ctx.graph, origParentId)- ctx.runLayoutForNode(origParentId)- if (origParentId !== parentId) {- computeLayout(ctx.graph, parentId)- ctx.runLayoutForNode(parentId)- }- }- })- }-- function reorderChildWithUndo(nodeId: string, newParentId: string, insertIndex: number) {- const node = ctx.graph.getNode(nodeId)- if (!node) return- const origParentId = node.parentId ?? ctx.state.currentPageId- const origIndex = ctx.graph.getNode(origParentId)?.childIds.indexOf(nodeId) ?? 0- const origX = node.x- const origY = node.y-- ctx.graph.reorderChild(nodeId, newParentId, insertIndex)- ctx.runLayoutForNode(newParentId)- if (origParentId !== newParentId) ctx.runLayoutForNode(origParentId)-- ctx.undo.push({- label: 'Reorder',- forward: () => {- ctx.graph.reorderChild(nodeId, newParentId, insertIndex)- ctx.runLayoutForNode(newParentId)- if (origParentId !== newParentId) ctx.runLayoutForNode(origParentId)- },- inverse: () => {- ctx.graph.reorderChild(nodeId, origParentId, origIndex)- ctx.graph.updateNode(nodeId, { x: origX, y: origY })- ctx.runLayoutForNode(origParentId)- if (origParentId !== newParentId) ctx.runLayoutForNode(newParentId)- }- })- }-function reparentNodes(nodeIds: string[], newParentId: string) {const parent = ctx.graph.getNode(newParentId)for (const id of nodeIds) {@@ -107,163 +38,11 @@ export function createStructureActions(ctx: EditorContext) {selectedNodes: SceneNode[],extraProps?: Partial<SceneNode>) {- if (selectedNodes.length === 0) return null-- const parentId = selectedNodes[0].parentId ?? ctx.state.currentPageId- const sameParent = selectedNodes.every(- (n) => (n.parentId ?? ctx.state.currentPageId) === parentId- )- if (!sameParent) return null-- const parent = ctx.graph.getNode(parentId)- if (!parent) return null-- const prevSelection = new Set(ctx.state.selectedIds)- const nodeIds = selectedNodes.map((n) => n.id)- const origPositions = selectedNodes.map((n) => ({ id: n.id, x: n.x, y: n.y }))-- const {- x: minX,- y: minY,- width: bw,- height: bh- } = computeAbsoluteBounds(selectedNodes, (id) => ctx.graph.getAbsolutePosition(id))- const maxX = minX + bw- const maxY = minY + bh-- const parentAbs = isTopLevel(parentId)- ? { x: 0, y: 0 }- : ctx.graph.getAbsolutePosition(parentId)- const firstIndex = Math.min(...nodeIds.map((id) => parent.childIds.indexOf(id)))-- const padding = containerType === 'COMPONENT_SET' ? 40 : 0- const containerNames: Record<string, string> = {- COMPONENT_SET: selectedNodes[0].name.split('/')[0]?.trim() || 'Component Set',- COMPONENT: 'Component',- GROUP: 'Group',- FRAME: 'Frame'- }- const containerNode = ctx.graph.createNode(containerType, parentId, {- name: containerNames[containerType] ?? containerType,- x: minX - parentAbs.x - padding,- y: minY - parentAbs.y - padding,- width: maxX - minX + padding * 2,- height: maxY - minY + padding * 2,- fills:- containerType === 'COMPONENT_SET'- ? [- {- type: 'SOLID',- color: { r: 0.96, g: 0.96, b: 0.96, a: 1 },- opacity: 1,- visible: true- }- ]- : [],- ...extraProps- })- const containerId = containerNode.id-- ctx.graph.insertChildAt(containerId, parentId, firstIndex)-- for (const n of selectedNodes) {- ctx.graph.reparentNode(n.id, containerId)- }-- ctx.state.selectedIds = new Set([containerId])-- ctx.undo.push({- label: `Create ${containerType.toLowerCase().replace('_', ' ')}`,- forward: () => {- const c = ctx.graph.createNode(containerType, parentId, {- ...containerNode,- ...extraProps,- id: containerId- })- ctx.graph.insertChildAt(c.id, parentId, firstIndex)- for (const n of origPositions) ctx.graph.reparentNode(n.id, c.id)- ctx.state.selectedIds = new Set([c.id])- },- inverse: () => {- for (const orig of origPositions) {- ctx.graph.reparentNode(orig.id, parentId)- ctx.graph.updateNode(orig.id, { x: orig.x, y: orig.y })- }- ctx.graph.deleteNode(containerId)- ctx.state.selectedIds = prevSelection- }- })-- return containerId+ return wrapSelectionInContainerImpl(ctx, isTopLevel, containerType, selectedNodes, extraProps)}function wrapInAutoLayout(selectedNodes: SceneNode[]) {- if (selectedNodes.length === 0) return-- const parentId = selectedNodes[0].parentId ?? ctx.state.currentPageId- const sameParent = selectedNodes.every(- (n) => (n.parentId ?? ctx.state.currentPageId) === parentId- )- if (!sameParent) return-- const prevSelection = new Set(ctx.state.selectedIds)- const origPositions = selectedNodes.map((n) => ({ id: n.id, x: n.x, y: n.y, parentId }))-- const bounds = computeAbsoluteBounds(selectedNodes, (id) => ctx.graph.getAbsolutePosition(id))-- const parentAbs = isTopLevel(parentId)- ? { x: 0, y: 0 }- : ctx.graph.getAbsolutePosition(parentId)-- const direction: LayoutMode =- selectedNodes.length <= 1 || bounds.height > bounds.width ? 'VERTICAL' : 'HORIZONTAL'-- const frame = ctx.graph.createNode('FRAME', parentId, {- name: 'Frame',- x: bounds.x - parentAbs.x,- y: bounds.y - parentAbs.y,- width: bounds.width,- height: bounds.height,- layoutMode: direction,- primaryAxisSizing: 'HUG',- counterAxisSizing: 'HUG',- primaryAxisAlign: 'MIN',- counterAxisAlign: 'MIN',- fills: []- })- const frameId = frame.id-- const sortedIds = selectedNodes- .map((n) => ({ id: n.id, pos: ctx.graph.getAbsolutePosition(n.id) }))- .sort((a, b) => a.pos.y - b.pos.y || a.pos.x - b.pos.x)- .map((n) => n.id)-- for (const id of sortedIds) {- ctx.graph.reparentNode(id, frameId)- }-- computeLayout(ctx.graph, frameId)- ctx.runLayoutForNode(frameId)- ctx.state.selectedIds = new Set([frameId])-- ctx.undo.push({- label: 'Wrap in auto layout',- forward: () => {- const f = ctx.graph.createNode('FRAME', parentId, { ...frame, id: frameId })- for (const n of origPositions) ctx.graph.reparentNode(n.id, f.id)- computeLayout(ctx.graph, f.id)- ctx.runLayoutForNode(f.id)- ctx.state.selectedIds = new Set([f.id])- },- inverse: () => {- for (const orig of origPositions) {- ctx.graph.reparentNode(orig.id, orig.parentId)- ctx.graph.updateNode(orig.id, { x: orig.x, y: orig.y })- }- ctx.graph.deleteNode(frameId)- ctx.state.selectedIds = prevSelection- }- })+ wrapInAutoLayoutImpl(ctx, isTopLevel, selectedNodes)}function groupSelected(selectedNodes: SceneNode[]) {@@ -271,102 +50,7 @@ export function createStructureActions(ctx: EditorContext) {}function ungroupSelected(selectedNode: SceneNode | undefined) {- if (selectedNode?.type !== 'GROUP') return-- const node = selectedNode- const parentId = node.parentId ?? ctx.state.currentPageId- const parent = ctx.graph.getNode(parentId)- if (!parent) return-- const groupIndex = parent.childIds.indexOf(node.id)- const childIds = [...node.childIds]- const prevSelection = new Set(ctx.state.selectedIds)- const origPositions = childIds.map((id) => {- const child = ctx.graph.getNode(id)- if (!child) return { id, x: 0, y: 0 }- return { id, x: child.x, y: child.y }- })- const groupId = node.id- const groupSnapshot = { ...node, childIds: [...node.childIds] }-- for (let i = 0; i < childIds.length; i++) {- ctx.graph.reparentNode(childIds[i], parentId)- ctx.graph.insertChildAt(childIds[i], parentId, groupIndex + i)- }-- ctx.graph.deleteNode(node.id)- ctx.state.selectedIds = new Set(childIds)-- ctx.undo.push({- label: 'Ungroup',- forward: () => {- for (let i = 0; i < childIds.length; i++) {- ctx.graph.reparentNode(childIds[i], parentId)- ctx.graph.insertChildAt(childIds[i], parentId, groupIndex + i)- }- ctx.graph.deleteNode(groupId)- ctx.state.selectedIds = new Set(childIds)- },- inverse: () => {- const g = ctx.graph.createNode('GROUP', parentId, {- ...groupSnapshot,- childIds: [],- id: groupId- })- ctx.graph.insertChildAt(g.id, parentId, groupIndex)- for (const orig of origPositions) {- ctx.graph.reparentNode(orig.id, g.id)- ctx.graph.updateNode(orig.id, { x: orig.x, y: orig.y })- }- ctx.state.selectedIds = prevSelection- }- })- }-- function bringToFront() {- for (const id of ctx.state.selectedIds) {- const node = ctx.graph.getNode(id)- if (!node?.parentId) continue- const parent = ctx.graph.getNode(node.parentId)- if (!parent) continue- const idx = parent.childIds.indexOf(id)- if (idx === parent.childIds.length - 1) continue- ctx.graph.insertChildAt(id, node.parentId, parent.childIds.length)- }- ctx.requestRender()- }-- function sendToBack() {- for (const id of ctx.state.selectedIds) {- const node = ctx.graph.getNode(id)- if (!node?.parentId) continue- const parent = ctx.graph.getNode(node.parentId)- if (!parent) continue- const idx = parent.childIds.indexOf(id)- if (idx === 0) continue- ctx.graph.insertChildAt(id, node.parentId, 0)- }- ctx.requestRender()- }-- function toggleNodeVisibility(id: string) {- const node = ctx.graph.getNode(id)- if (!node) return- ctx.graph.updateNode(id, { visible: !node.visible })- }-- function toggleNodeLock(id: string) {- const node = ctx.graph.getNode(id)- if (!node) return- ctx.graph.updateNode(id, { locked: !node.locked })- }-- function toggleVisibility() {- for (const id of ctx.state.selectedIds) toggleNodeVisibility(id)- }-- function toggleLock() {- for (const id of ctx.state.selectedIds) toggleNodeLock(id)+ ungroupImpl(ctx, selectedNode)}function moveToPage(pageId: string) {@@ -388,19 +72,13 @@ export function createStructureActions(ctx: EditorContext) {return {isTopLevel,- reorderInAutoLayout,- reorderChildWithUndo,+ ...reorderActions,reparentNodes,wrapSelectionInContainer,wrapInAutoLayout,groupSelected,ungroupSelected,- bringToFront,- sendToBack,- toggleNodeVisibility,- toggleNodeLock,- toggleVisibility,- toggleLock,+ ...stateActions,moveToPage,renameNode}diff --git a/packages/core/src/editor/structure/auto-layout-wrap.ts b/packages/core/src/editor/structure/auto-layout-wrap.tsnew file mode 100644index 000000000..536eebe83--- /dev/null+++ b/packages/core/src/editor/structure/auto-layout-wrap.ts@@ -0,0 +1,78 @@+import { computeAbsoluteBounds } from '#core/geometry'+import { computeLayout } from '#core/layout'++import type { LayoutMode, SceneNode } from '#core/scene-graph'+import type { EditorContext } from '#core/editor/types'++export function wrapInAutoLayout(+ ctx: EditorContext,+ isTopLevel: (parentId: string | null) => boolean,+ selectedNodes: SceneNode[]+) {+ if (selectedNodes.length === 0) return++ const parentId = selectedNodes[0].parentId ?? ctx.state.currentPageId+ const sameParent = selectedNodes.every(+ (n) => (n.parentId ?? ctx.state.currentPageId) === parentId+ )+ if (!sameParent) return++ const prevSelection = new Set(ctx.state.selectedIds)+ const origPositions = selectedNodes.map((n) => ({ id: n.id, x: n.x, y: n.y, parentId }))++ const bounds = computeAbsoluteBounds(selectedNodes, (id) => ctx.graph.getAbsolutePosition(id))++ const parentAbs = isTopLevel(parentId)+ ? { x: 0, y: 0 }+ : ctx.graph.getAbsolutePosition(parentId)++ const direction: LayoutMode =+ selectedNodes.length <= 1 || bounds.height > bounds.width ? 'VERTICAL' : 'HORIZONTAL'++ const frame = ctx.graph.createNode('FRAME', parentId, {+ name: 'Frame',+ x: bounds.x - parentAbs.x,+ y: bounds.y - parentAbs.y,+ width: bounds.width,+ height: bounds.height,+ layoutMode: direction,+ primaryAxisSizing: 'HUG',+ counterAxisSizing: 'HUG',+ primaryAxisAlign: 'MIN',+ counterAxisAlign: 'MIN',+ fills: []+ })+ const frameId = frame.id++ const sortedIds = selectedNodes+ .map((n) => ({ id: n.id, pos: ctx.graph.getAbsolutePosition(n.id) }))+ .sort((a, b) => a.pos.y - b.pos.y || a.pos.x - b.pos.x)+ .map((n) => n.id)++ for (const id of sortedIds) {+ ctx.graph.reparentNode(id, frameId)+ }++ computeLayout(ctx.graph, frameId)+ ctx.runLayoutForNode(frameId)+ ctx.state.selectedIds = new Set([frameId])++ ctx.undo.push({+ label: 'Wrap in auto layout',+ forward: () => {+ const f = ctx.graph.createNode('FRAME', parentId, { ...frame, id: frameId })+ for (const n of origPositions) ctx.graph.reparentNode(n.id, f.id)+ computeLayout(ctx.graph, f.id)+ ctx.runLayoutForNode(f.id)+ ctx.state.selectedIds = new Set([f.id])+ },+ inverse: () => {+ for (const orig of origPositions) {+ ctx.graph.reparentNode(orig.id, orig.parentId)+ ctx.graph.updateNode(orig.id, { x: orig.x, y: orig.y })+ }+ ctx.graph.deleteNode(frameId)+ ctx.state.selectedIds = prevSelection+ }+ })+}diff --git a/packages/core/src/editor/structure/container-wrap.ts b/packages/core/src/editor/structure/container-wrap.tsnew file mode 100644index 000000000..4cfb52f1c--- /dev/null+++ b/packages/core/src/editor/structure/container-wrap.ts@@ -0,0 +1,101 @@+import { computeAbsoluteBounds } from '#core/geometry'++import type { SceneNode } from '#core/scene-graph'+import type { EditorContext } from '#core/editor/types'++export function wrapSelectionInContainer(+ ctx: EditorContext,+ isTopLevel: (parentId: string | null) => boolean,+ containerType: 'GROUP' | 'FRAME' | 'COMPONENT' | 'COMPONENT_SET',+ selectedNodes: SceneNode[],+ extraProps?: Partial<SceneNode>+) {+ if (selectedNodes.length === 0) return null++ const parentId = selectedNodes[0].parentId ?? ctx.state.currentPageId+ const sameParent = selectedNodes.every(+ (n) => (n.parentId ?? ctx.state.currentPageId) === parentId+ )+ if (!sameParent) return null++ const parent = ctx.graph.getNode(parentId)+ if (!parent) return null++ const prevSelection = new Set(ctx.state.selectedIds)+ const nodeIds = selectedNodes.map((n) => n.id)+ const origPositions = selectedNodes.map((n) => ({ id: n.id, x: n.x, y: n.y }))++ const {+ x: minX,+ y: minY,+ width: bw,+ height: bh+ } = computeAbsoluteBounds(selectedNodes, (id) => ctx.graph.getAbsolutePosition(id))+ const maxX = minX + bw+ const maxY = minY + bh++ const parentAbs = isTopLevel(parentId)+ ? { x: 0, y: 0 }+ : ctx.graph.getAbsolutePosition(parentId)+ const firstIndex = Math.min(...nodeIds.map((id) => parent.childIds.indexOf(id)))++ const padding = containerType === 'COMPONENT_SET' ? 40 : 0+ const containerNames: Record<string, string> = {+ COMPONENT_SET: selectedNodes[0].name.split('/')[0]?.trim() || 'Component Set',+ COMPONENT: 'Component',+ GROUP: 'Group',+ FRAME: 'Frame'+ }+ const containerNode = ctx.graph.createNode(containerType, parentId, {+ name: containerNames[containerType] ?? containerType,+ x: minX - parentAbs.x - padding,+ y: minY - parentAbs.y - padding,+ width: maxX - minX + padding * 2,+ height: maxY - minY + padding * 2,+ fills:+ containerType === 'COMPONENT_SET'+ ? [+ {+ type: 'SOLID',+ color: { r: 0.96, g: 0.96, b: 0.96, a: 1 },+ opacity: 1,+ visible: true+ }+ ]+ : [],+ ...extraProps+ })+ const containerId = containerNode.id++ ctx.graph.insertChildAt(containerId, parentId, firstIndex)++ for (const n of selectedNodes) {+ ctx.graph.reparentNode(n.id, containerId)+ }++ ctx.state.selectedIds = new Set([containerId])++ ctx.undo.push({+ label: `Create ${containerType.toLowerCase().replace('_', ' ')}`,+ forward: () => {+ const c = ctx.graph.createNode(containerType, parentId, {+ ...containerNode,+ ...extraProps,+ id: containerId+ })+ ctx.graph.insertChildAt(c.id, parentId, firstIndex)+ for (const n of origPositions) ctx.graph.reparentNode(n.id, c.id)+ ctx.state.selectedIds = new Set([c.id])+ },+ inverse: () => {+ for (const orig of origPositions) {+ ctx.graph.reparentNode(orig.id, parentId)+ ctx.graph.updateNode(orig.id, { x: orig.x, y: orig.y })+ }+ ctx.graph.deleteNode(containerId)+ ctx.state.selectedIds = prevSelection+ }+ })++ return containerId+}diff --git a/packages/core/src/editor/structure/group.ts b/packages/core/src/editor/structure/group.tsnew file mode 100644index 000000000..f5f122b9a--- /dev/null+++ b/packages/core/src/editor/structure/group.ts@@ -0,0 +1,55 @@+import type { SceneNode } from '#core/scene-graph'+import type { EditorContext } from '#core/editor/types'++export function ungroupSelected(ctx: EditorContext, selectedNode: SceneNode | undefined) {+ if (selectedNode?.type !== 'GROUP') return++ const node = selectedNode+ const parentId = node.parentId ?? ctx.state.currentPageId+ const parent = ctx.graph.getNode(parentId)+ if (!parent) return++ const groupIndex = parent.childIds.indexOf(node.id)+ const childIds = [...node.childIds]+ const prevSelection = new Set(ctx.state.selectedIds)+ const origPositions = childIds.map((id) => {+ const child = ctx.graph.getNode(id)+ if (!child) return { id, x: 0, y: 0 }+ return { id, x: child.x, y: child.y }+ })+ const groupId = node.id+ const groupSnapshot = { ...node, childIds: [...node.childIds] }++ for (let i = 0; i < childIds.length; i++) {+ ctx.graph.reparentNode(childIds[i], parentId)+ ctx.graph.insertChildAt(childIds[i], parentId, groupIndex + i)+ }++ ctx.graph.deleteNode(node.id)+ ctx.state.selectedIds = new Set(childIds)++ ctx.undo.push({+ label: 'Ungroup',+ forward: () => {+ for (let i = 0; i < childIds.length; i++) {+ ctx.graph.reparentNode(childIds[i], parentId)+ ctx.graph.insertChildAt(childIds[i], parentId, groupIndex + i)+ }+ ctx.graph.deleteNode(groupId)+ ctx.state.selectedIds = new Set(childIds)+ },+ inverse: () => {+ const g = ctx.graph.createNode('GROUP', parentId, {+ ...groupSnapshot,+ childIds: [],+ id: groupId+ })+ ctx.graph.insertChildAt(g.id, parentId, groupIndex)+ for (const orig of origPositions) {+ ctx.graph.reparentNode(orig.id, g.id)+ ctx.graph.updateNode(orig.id, { x: orig.x, y: orig.y })+ }+ ctx.state.selectedIds = prevSelection+ }+ })+}diff --git a/packages/core/src/editor/structure/reorder.ts b/packages/core/src/editor/structure/reorder.tsnew file mode 100644index 000000000..f7c06fc73--- /dev/null+++ b/packages/core/src/editor/structure/reorder.ts@@ -0,0 +1,110 @@+import { computeLayout } from '#core/layout'++import type { EditorContext } from '#core/editor/types'++export function createStructureReorderActions(ctx: EditorContext) {+ function doReorderChild(nodeId: string, parentId: string, insertIndex: number) {+ const node = ctx.graph.getNode(nodeId)+ if (!node) return++ if (node.parentId !== parentId) {+ const absPos = ctx.graph.getAbsolutePosition(nodeId)+ const parentAbs = ctx.graph.getAbsolutePosition(parentId)+ ctx.graph.updateNode(nodeId, { x: absPos.x - parentAbs.x, y: absPos.y - parentAbs.y })+ }++ ctx.graph.reorderChild(nodeId, parentId, insertIndex)+ computeLayout(ctx.graph, parentId)+ ctx.runLayoutForNode(parentId)+ }++ function reorderInAutoLayout(nodeId: string, parentId: string, insertIndex: number) {+ const parent = ctx.graph.getNode(parentId)+ if (!parent || parent.layoutMode === 'NONE') return++ const node = ctx.graph.getNode(nodeId)+ if (!node) return+ const origParentId = node.parentId ?? ctx.state.currentPageId+ const origX = node.x+ const origY = node.y+ const origIndex = ctx.graph.getNode(origParentId)?.childIds.indexOf(nodeId) ?? -1++ doReorderChild(nodeId, parentId, insertIndex)++ ctx.undo.push({+ label: 'Reorder',+ forward: () => {+ doReorderChild(nodeId, parentId, insertIndex)+ },+ inverse: () => {+ ctx.graph.reorderChild(nodeId, origParentId, origIndex >= 0 ? origIndex : 0)+ ctx.graph.updateNode(nodeId, { x: origX, y: origY })+ computeLayout(ctx.graph, origParentId)+ ctx.runLayoutForNode(origParentId)+ if (origParentId !== parentId) {+ computeLayout(ctx.graph, parentId)+ ctx.runLayoutForNode(parentId)+ }+ }+ })+ }++ function reorderChildWithUndo(nodeId: string, newParentId: string, insertIndex: number) {+ const node = ctx.graph.getNode(nodeId)+ if (!node) return+ const origParentId = node.parentId ?? ctx.state.currentPageId+ const origIndex = ctx.graph.getNode(origParentId)?.childIds.indexOf(nodeId) ?? 0+ const origX = node.x+ const origY = node.y++ ctx.graph.reorderChild(nodeId, newParentId, insertIndex)+ ctx.runLayoutForNode(newParentId)+ if (origParentId !== newParentId) ctx.runLayoutForNode(origParentId)++ ctx.undo.push({+ label: 'Reorder',+ forward: () => {+ ctx.graph.reorderChild(nodeId, newParentId, insertIndex)+ ctx.runLayoutForNode(newParentId)+ if (origParentId !== newParentId) ctx.runLayoutForNode(origParentId)+ },+ inverse: () => {+ ctx.graph.reorderChild(nodeId, origParentId, origIndex)+ ctx.graph.updateNode(nodeId, { x: origX, y: origY })+ ctx.runLayoutForNode(origParentId)+ if (origParentId !== newParentId) ctx.runLayoutForNode(newParentId)+ }+ })+ }++ function moveSelectionInZOrder(+ isAlreadyPlaced: (currentIndex: number, childCount: number) => boolean,+ insertIndex: (childCount: number) => number+ ) {+ for (const id of ctx.state.selectedIds) {+ const node = ctx.graph.getNode(id)+ if (!node?.parentId) continue+ const parent = ctx.graph.getNode(node.parentId)+ if (!parent) continue+ if (isAlreadyPlaced(parent.childIds.indexOf(id), parent.childIds.length)) continue+ ctx.graph.insertChildAt(id, node.parentId, insertIndex(parent.childIds.length))+ }+ ctx.requestRender()+ }++ function bringToFront() {+ moveSelectionInZOrder(+ (currentIndex, childCount) => currentIndex === childCount - 1,+ (childCount) => childCount+ )+ }++ function sendToBack() {+ moveSelectionInZOrder(+ (currentIndex) => currentIndex === 0,+ () => 0+ )+ }++ return { reorderInAutoLayout, reorderChildWithUndo, bringToFront, sendToBack }+}diff --git a/packages/core/src/editor/structure/state.ts b/packages/core/src/editor/structure/state.tsnew file mode 100644index 000000000..275d0ee46--- /dev/null+++ b/packages/core/src/editor/structure/state.ts@@ -0,0 +1,25 @@+import type { EditorContext } from '#core/editor/types'++export function createStructureStateActions(ctx: EditorContext) {+ function toggleNodeVisibility(id: string) {+ const node = ctx.graph.getNode(id)+ if (!node) return+ ctx.graph.updateNode(id, { visible: !node.visible })+ }++ function toggleNodeLock(id: string) {+ const node = ctx.graph.getNode(id)+ if (!node) return+ ctx.graph.updateNode(id, { locked: !node.locked })+ }++ function toggleVisibility() {+ for (const id of ctx.state.selectedIds) toggleNodeVisibility(id)+ }++ function toggleLock() {+ for (const id of ctx.state.selectedIds) toggleNodeLock(id)+ }++ return { toggleNodeVisibility, toggleNodeLock, toggleVisibility, toggleLock }+}diff --git a/packages/core/src/editor/text.ts b/packages/core/src/editor/text.tsindex 1f90be45d..f6b7f2d76 100644--- a/packages/core/src/editor/text.ts+++ b/packages/core/src/editor/text.ts@@ -1,19 +1,21 @@-import { copyStyleRuns } from '../scene-graph/copy'+import {+ createTextEditSession,+ snapshotTextNode,+ textSnapshotChanged,+ type TextEditSession+} from './text/session'-import type { SceneNode } from '../scene-graph'import type { EditorContext } from './types'export function createTextActions(ctx: EditorContext) {- let textBeforeEdit: string | null = null- let styleRunsBeforeEdit: SceneNode['styleRuns'] | null = null+ let activeSession: TextEditSession | null = nullfunction startTextEditing(nodeId: string) {const te = ctx.getTextEditor()if (ctx.state.editingTextId) commitTextEdit()const node = ctx.graph.getNode(nodeId)if (!node) return- textBeforeEdit = node.text- styleRunsBeforeEdit = copyStyleRuns(node.styleRuns)+ activeSession = createTextEditSession(node)ctx.state.editingTextId = nodeIdif (te) {te.setRenderer(ctx.getRenderer())@@ -26,38 +28,32 @@ export function createTextActions(ctx: EditorContext) {const te = ctx.getTextEditor()if (!te?.isActive) {ctx.state.editingTextId = null- textBeforeEdit = null- styleRunsBeforeEdit = null+ activeSession = nullreturn}const result = te.stop()if (!result) {ctx.state.editingTextId = null- textBeforeEdit = null- styleRunsBeforeEdit = null+ activeSession = nullctx.requestRender()return}- const prevText = textBeforeEdit ?? ''- const prevRuns = styleRunsBeforeEdit ?? []- const newText = result.text+ const before = activeSession?.before ?? { text: '', styleRuns: [] }const node = ctx.graph.getNode(result.nodeId)- const newRuns = node ? copyStyleRuns(node.styleRuns) : []- ctx.graph.updateNode(result.nodeId, { text: newText, styleRuns: newRuns })+ const after = snapshotTextNode(node, result.text)+ after.text = result.text+ ctx.graph.updateNode(result.nodeId, { text: after.text, styleRuns: after.styleRuns })ctx.state.editingTextId = null- textBeforeEdit = null- styleRunsBeforeEdit = null+ activeSession = null- const textChanged = prevText !== newText- const runsChanged = JSON.stringify(prevRuns) !== JSON.stringify(newRuns)- if (textChanged || runsChanged) {+ if (textSnapshotChanged(before, after)) {ctx.undo.push({label: 'Edit text',forward: () => {- ctx.graph.updateNode(result.nodeId, { text: newText, styleRuns: newRuns })+ ctx.graph.updateNode(result.nodeId, { text: after.text, styleRuns: after.styleRuns })},inverse: () => {- ctx.graph.updateNode(result.nodeId, { text: prevText, styleRuns: prevRuns })+ ctx.graph.updateNode(result.nodeId, { text: before.text, styleRuns: before.styleRuns })}})}diff --git a/packages/core/src/editor/text/session.ts b/packages/core/src/editor/text/session.tsnew file mode 100644index 000000000..c2b171c9e--- /dev/null+++ b/packages/core/src/editor/text/session.ts@@ -0,0 +1,81 @@+import { copyStyleRuns } from '#core/scene-graph/copy'++import type { SceneNode, StyleRun } from '#core/scene-graph'++export type TextEditSnapshot = {+ text: string+ styleRuns: StyleRun[]+}++export type TextEditSession = {+ nodeId: string+ before: TextEditSnapshot+}++export function createTextEditSession(node: SceneNode): TextEditSession {+ return {+ nodeId: node.id,+ before: {+ text: node.text,+ styleRuns: copyStyleRuns(node.styleRuns)+ }+ }+}++export function snapshotTextNode(node: SceneNode | undefined, fallbackText = ''): TextEditSnapshot {+ return {+ text: node?.text ?? fallbackText,+ styleRuns: node ? copyStyleRuns(node.styleRuns) : []+ }+}++export function textSnapshotChanged(before: TextEditSnapshot, after: TextEditSnapshot): boolean {+ return before.text !== after.text || !styleRunsEqual(before.styleRuns, after.styleRuns)+}++function styleRunsEqual(a: StyleRun[], b: StyleRun[]): boolean {+ if (a.length !== b.length) return false+ return a.every((run, index) => styleRunEqual(run, b[index]))+}++function styleRunEqual(a: StyleRun, b: StyleRun): boolean {+ return a.start === b.start && a.length === b.length && styleEqual(a.style, b.style)+}++function styleEqual(a: StyleRun['style'], b: StyleRun['style']): boolean {+ return (+ a.fontWeight === b.fontWeight &&+ a.italic === b.italic &&+ a.textDecoration === b.textDecoration &&+ a.fontSize === b.fontSize &&+ a.fontFamily === b.fontFamily &&+ a.letterSpacing === b.letterSpacing &&+ a.lineHeight === b.lineHeight &&+ fillsEqual(a.fills ?? [], b.fills ?? [])+ )+}++function fillsEqual(+ a: NonNullable<StyleRun['style']['fills']>,+ b: NonNullable<StyleRun['style']['fills']>+) {+ if (a.length !== b.length) return false+ return a.every((fill, index) => deepEqual(fill, b[index]))+}++function deepEqual(a: unknown, b: unknown): boolean {+ if (Object.is(a, b)) return true+ if (typeof a !== typeof b) return false+ if (a === null || b === null) return false+ if (typeof a !== 'object' || typeof b !== 'object') return false+ if (Array.isArray(a) || Array.isArray(b)) {+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false+ return a.every((item, index) => deepEqual(item, b[index]))+ }+ const aRecord = a as Record<string, unknown>+ const bRecord = b as Record<string, unknown>+ const aKeys = Object.keys(aRecord)+ const bKeys = Object.keys(bRecord)+ if (aKeys.length !== bKeys.length) return false+ return aKeys.every((key) => Object.hasOwn(bRecord, key) && deepEqual(aRecord[key], bRecord[key]))+}diff --git a/packages/core/src/editor/tool-registry.ts b/packages/core/src/editor/tool-registry.tsnew file mode 100644index 000000000..43f5aef8f--- /dev/null+++ b/packages/core/src/editor/tool-registry.ts@@ -0,0 +1,34 @@+import type { Tool } from './types'++export interface EditorToolDef {+ key: Tool+ label: string+ shortcut: string+ flyout?: Tool[]+}++export const EDITOR_TOOLS: EditorToolDef[] = [+ { key: 'SELECT', label: 'Move', shortcut: 'V' },+ { key: 'FRAME', label: 'Frame', shortcut: 'F', flyout: ['FRAME', 'SECTION'] },+ {+ key: 'RECTANGLE',+ label: 'Rectangle',+ shortcut: 'R',+ flyout: ['RECTANGLE', 'LINE', 'ELLIPSE', 'POLYGON', 'STAR']+ },+ { key: 'PEN', label: 'Pen', shortcut: 'P' },+ { key: 'TEXT', label: 'Text', shortcut: 'T' },+ { key: 'HAND', label: 'Hand', shortcut: 'H' }+]++export const TOOL_SHORTCUTS: Partial<Record<string, Tool>> = {+ KeyV: 'SELECT',+ KeyF: 'FRAME',+ KeyS: 'SECTION',+ KeyR: 'RECTANGLE',+ KeyO: 'ELLIPSE',+ KeyL: 'LINE',+ KeyT: 'TEXT',+ KeyP: 'PEN',+ KeyH: 'HAND'+}diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.tsindex 964f093b1..a2b078da6 100644--- a/packages/core/src/editor/types.ts+++ b/packages/core/src/editor/types.ts@@ -1,9 +1,9 @@-import type { SkiaRenderer } from '../canvas/renderer'-import type { SceneGraph, VectorSegment, VectorVertex } from '../scene-graph'-import type { SnapGuide } from '../scene-graph/snap'-import type { UndoManager } from '../scene-graph/undo'-import type { TextEditor } from '../text/editor'-import type { Color, Rect, Vector } from '../types'+import type { SkiaRenderer } from '#core/canvas/renderer'+import type { SceneGraph, VectorSegment, VectorVertex } from '#core/scene-graph'+import type { SnapGuide } from '#core/scene-graph/snap'+import type { UndoManager } from '#core/scene-graph/undo'+import type { TextEditor } from '#core/text/editor'+import type { Color, Rect, Vector } from '#core/types'import type { CanvasKit } from 'canvaskit-wasm'export type Tool =@@ -19,39 +19,6 @@ export type Tool =| 'PEN'| 'HAND'-export interface EditorToolDef {- key: Tool- label: string- shortcut: string- flyout?: Tool[]-}--export const EDITOR_TOOLS: EditorToolDef[] = [- { key: 'SELECT', label: 'Move', shortcut: 'V' },- { key: 'FRAME', label: 'Frame', shortcut: 'F', flyout: ['FRAME', 'SECTION'] },- {- key: 'RECTANGLE',- label: 'Rectangle',- shortcut: 'R',- flyout: ['RECTANGLE', 'LINE', 'ELLIPSE', 'POLYGON', 'STAR']- },- { key: 'PEN', label: 'Pen', shortcut: 'P' },- { key: 'TEXT', label: 'Text', shortcut: 'T' },- { key: 'HAND', label: 'Hand', shortcut: 'H' }-]--export const TOOL_SHORTCUTS: Partial<Record<string, Tool>> = {- KeyV: 'SELECT',- KeyF: 'FRAME',- KeyS: 'SECTION',- KeyR: 'RECTANGLE',- KeyO: 'ELLIPSE',- KeyL: 'LINE',- KeyT: 'TEXT',- KeyP: 'PEN',- KeyH: 'HAND'-}-export interface EditorState {activeTool: ToolcurrentPageId: stringdiff --git a/packages/core/src/editor/undo.ts b/packages/core/src/editor/undo.tsindex 44a9bfddc..3f4971f8e 100644--- a/packages/core/src/editor/undo.ts+++ b/packages/core/src/editor/undo.ts@@ -1,32 +1,19 @@-import { computeAllLayouts } from '../layout'--import type { SceneNode } from '../scene-graph'-import type { UndoEntry } from '../scene-graph/undo'-import type { Rect, Vector } from '../types'+import { restoreSubtree, snapshotSubtree } from './clipboard/subtree-history'+import { collectNodePositions, pushPositionUndo } from './history/position'+import {+ restorePageFromSnapshot as restorePageSnapshot,+ snapshotPage as createPageSnapshot,+ type PageSnapshot+} from './history/snapshot'++import type { SceneNode } from '#core/scene-graph'+import type { UndoEntry } from '#core/scene-graph/undo'+import type { Rect, Vector } from '#core/types'import type { EditorContext } from './types'export function createUndoActions(ctx: EditorContext) {function commitMove(originals: Map<string, Vector>) {- const finals = new Map<string, Vector>()- for (const [id] of originals) {- const n = ctx.graph.getNode(id)- if (n) finals.set(id, { x: n.x, y: n.y })- }- ctx.undo.push({- label: 'Move',- forward: () => {- for (const [id, pos] of finals) {- ctx.graph.updateNode(id, pos)- ctx.runLayoutForNode(id)- }- },- inverse: () => {- for (const [id, pos] of originals) {- ctx.graph.updateNode(id, pos)- ctx.runLayoutForNode(id)- }- }- })+ pushPositionUndo(ctx, 'Move', originals, collectNodePositions(ctx, originals.keys()))}function commitMoveWithReparent(@@ -56,6 +43,33 @@ export function createUndoActions(ctx: EditorContext) {})}+ function commitDuplicateMove(rootIds: string[], previousSelection: Set<string>) {+ const snapshots = new Map<string, SceneNode>()+ for (const id of rootIds) {+ const subtree = snapshotSubtree(ctx.graph, id)+ for (const [nodeId, snapshot] of subtree) snapshots.set(nodeId, snapshot)+ }+ const nextSelection = new Set(rootIds)++ ctx.undo.push({+ label: 'Duplicate',+ forward: () => {+ for (const id of rootIds) {+ if (ctx.graph.getNode(id)) continue+ const snapshot = snapshots.get(id)+ if (!snapshot) continue+ restoreSubtree(ctx.graph, snapshot, snapshot.parentId ?? ctx.state.currentPageId, snapshots)+ ctx.runLayoutForNode(id)+ }+ ctx.state.selectedIds = new Set(nextSelection)+ },+ inverse: () => {+ for (const id of rootIds.toReversed()) ctx.graph.deleteNode(id)+ ctx.state.selectedIds = new Set(previousSelection)+ }+ })+ }+function commitResize(nodeId: string, origRect: Rect) {const node = ctx.graph.getNode(nodeId)if (!node) return@@ -119,46 +133,12 @@ export function createUndoActions(ctx: EditorContext) {ctx.requestRender()}- function snapshotPage(): Map<string, SceneNode> {- const snapshot = new Map<string, SceneNode>()- const walk = (id: string) => {- const node = ctx.graph.getNode(id)- if (!node) return- snapshot.set(id, structuredClone(node))- for (const childId of node.childIds) walk(childId)- }- walk(ctx.state.currentPageId)- return snapshot+ function snapshotPage(): PageSnapshot {+ return createPageSnapshot(ctx.graph, ctx.state.currentPageId)}- function restorePageFromSnapshot(snapshot: Map<string, SceneNode>) {- const pageId = ctx.state.currentPageId- const page = ctx.graph.getNode(pageId)- const pageSnap = snapshot.get(pageId)- if (!page || !pageSnap) return-- for (const childId of page.childIds.slice()) {- ctx.graph.deleteNode(childId)- }-- const restoreChildren = (parentId: string, childIds: string[]) => {- for (const childId of childIds) {- const snap = snapshot.get(childId)- if (!snap) continue- const { id: _snapId, parentId: _snapParentId, childIds: snapChildIds, ...rest } = snap- const restored = ctx.graph.createNode(snap.type, parentId, rest)- ctx.graph.reorderChild(restored.id, parentId, childIds.indexOf(childId))- restoreChildren(restored.id, snapChildIds)- }- }-- restoreChildren(pageId, pageSnap.childIds)-- ctx.graph.clearAbsPosCache()- computeAllLayouts(ctx.graph, pageId)- ctx.state.selectedIds = new Set()- ctx.state.hoveredNodeId = null- ctx.requestRender()+ function restorePageFromSnapshot(snapshot: PageSnapshot) {+ restorePageSnapshot(ctx, snapshot)}function pushUndoEntry(entry: UndoEntry) {@@ -168,6 +148,7 @@ export function createUndoActions(ctx: EditorContext) {return {commitMove,commitMoveWithReparent,+ commitDuplicateMove,commitResize,commitRotation,commitNodeUpdate,diff --git a/packages/core/src/editor/variable-bindings.ts b/packages/core/src/editor/variable-bindings.tsnew file mode 100644index 000000000..cb0b1c179--- /dev/null+++ b/packages/core/src/editor/variable-bindings.ts@@ -0,0 +1,45 @@+import type { EditorContext } from './types'++export function createVariableBindingActions(ctx: EditorContext) {+ function bindVariable(nodeId: string, path: string, variableId: string) {+ const node = ctx.graph.getNode(nodeId)+ if (!node) return+ const prevVarId = node.boundVariables[path]+ ctx.graph.bindVariable(nodeId, path, variableId)+ ctx.undo.push({+ label: 'Bind variable',+ forward: () => {+ ctx.graph.bindVariable(nodeId, path, variableId)+ ctx.requestRender()+ },+ inverse: () => {+ if (prevVarId) ctx.graph.bindVariable(nodeId, path, prevVarId)+ else ctx.graph.unbindVariable(nodeId, path)+ ctx.requestRender()+ }+ })+ ctx.requestRender()+ }++ function unbindVariable(nodeId: string, path: string) {+ const node = ctx.graph.getNode(nodeId)+ if (!node) return+ const prevVarId = node.boundVariables[path]+ if (!prevVarId) return+ ctx.graph.unbindVariable(nodeId, path)+ ctx.undo.push({+ label: 'Unbind variable',+ forward: () => {+ ctx.graph.unbindVariable(nodeId, path)+ ctx.requestRender()+ },+ inverse: () => {+ ctx.graph.bindVariable(nodeId, path, prevVarId)+ ctx.requestRender()+ }+ })+ ctx.requestRender()+ }++ return { bindVariable, unbindVariable }+}diff --git a/packages/core/src/editor/variables.ts b/packages/core/src/editor/variables.tsindex 209035771..14284c271 100644--- a/packages/core/src/editor/variables.ts+++ b/packages/core/src/editor/variables.ts@@ -1,4 +1,4 @@-import type { Variable, VariableCollection, VariableType, VariableValue } from '../scene-graph'+import type { Variable, VariableCollection, VariableType, VariableValue } from '#core/scene-graph'import type { EditorContext } from './types'export function createVariableActions(ctx: EditorContext) {diff --git a/packages/core/src/editor/viewport.ts b/packages/core/src/editor/viewport.tsindex 194a4234b..16d8d6a5a 100644--- a/packages/core/src/editor/viewport.ts+++ b/packages/core/src/editor/viewport.ts@@ -1,5 +1,5 @@-import { ZOOM_DIVISOR, ZOOM_SCALE_MAX, ZOOM_SCALE_MIN } from '../constants'-import { computeBounds, computeAbsoluteBounds } from '../geometry'+import { ZOOM_DIVISOR, ZOOM_SCALE_MAX, ZOOM_SCALE_MIN } from '#core/constants'+import { computeBounds, computeAbsoluteBounds } from '#core/geometry'import type { EditorContext } from './types'@@ -11,16 +11,20 @@ export function createViewportActions(ctx: EditorContext) {}}+ function setZoomAroundPoint(level: number, centerX: number, centerY: number) {+ const newZoom = Math.max(0.02, Math.min(256, level))+ ctx.state.panX = centerX - (centerX - ctx.state.panX) * (newZoom / ctx.state.zoom)+ ctx.state.panY = centerY - (centerY - ctx.state.panY) * (newZoom / ctx.state.zoom)+ ctx.state.zoom = newZoom+ ctx.requestRepaint()+ }+function applyZoom(delta: number, centerX: number, centerY: number) {const factor = Math.min(ZOOM_SCALE_MAX,Math.max(ZOOM_SCALE_MIN, Math.exp(-delta / ZOOM_DIVISOR)))- const newZoom = Math.max(0.02, Math.min(256, ctx.state.zoom * factor))- ctx.state.panX = centerX - (centerX - ctx.state.panX) * (newZoom / ctx.state.zoom)- ctx.state.panY = centerY - (centerY - ctx.state.panY) * (newZoom / ctx.state.zoom)- ctx.state.zoom = newZoom- ctx.requestRepaint()+ setZoomAroundPoint(ctx.state.zoom * factor, centerX, centerY)}function pan(dx: number, dy: number) {@@ -80,6 +84,7 @@ export function createViewportActions(ctx: EditorContext) {return {screenToCanvas,+ setZoomAroundPoint,applyZoom,pan,zoomToBounds,diff --git a/packages/core/src/figma-api/accessor-utils.ts b/packages/core/src/figma-api/accessor-utils.tsnew file mode 100644index 000000000..e4b1d40ff--- /dev/null+++ b/packages/core/src/figma-api/accessor-utils.ts@@ -0,0 +1,32 @@+import type { SceneGraph, SceneNode } from '#core/scene-graph'++export interface NodeProxyInternals {+ id: symbol+ graph: symbol+ api: symbol+}++export type ProxyThis = Record<symbol, unknown>++export function nodeId(target: ProxyThis, internals: NodeProxyInternals): string {+ return target[internals.id] as string+}++export function graph(target: ProxyThis, internals: NodeProxyInternals): SceneGraph {+ return target[internals.graph] as SceneGraph+}++export function raw(target: ProxyThis, internals: NodeProxyInternals): SceneNode {+ const id = nodeId(target, internals)+ const node = graph(target, internals).getNode(id)+ if (!node) throw new Error(`Node ${id} has been removed`)+ return node+}++export function updateNode(+ target: ProxyThis,+ internals: NodeProxyInternals,+ changes: Partial<SceneNode>+): void {+ graph(target, internals).updateNode(nodeId(target, internals), changes)+}diff --git a/packages/core/src/figma-api/accessors/basic.ts b/packages/core/src/figma-api/accessors/basic.tsnew file mode 100644index 000000000..75654df69--- /dev/null+++ b/packages/core/src/figma-api/accessors/basic.ts@@ -0,0 +1,100 @@+import { graph, nodeId, raw, type NodeProxyInternals, type ProxyThis } from '#core/figma-api/accessor-utils'++import type { SceneNode } from '#core/scene-graph'+import type { Rect } from '#core/types'+import type { NodeProxyHost } from '#core/figma-api/proxy'++export function installBasicNodeProxyAccessors(+ prototype: object,+ internals: NodeProxyInternals+): void {+ Object.defineProperties(prototype, {+ id: {+ get(this: ProxyThis): string {+ return nodeId(this, internals)+ }+ },+ type: {+ get(this: ProxyThis): SceneNode['type'] {+ return raw(this, internals).type+ }+ },+ name: {+ get(this: ProxyThis): string {+ return raw(this, internals).name+ },+ set(this: ProxyThis, value: string) {+ graph(this, internals).updateNode(nodeId(this, internals), { name: value })+ }+ },+ removed: {+ get(this: ProxyThis): boolean {+ return !graph(this, internals).getNode(nodeId(this, internals))+ }+ },+ x: {+ get(this: ProxyThis): number {+ return raw(this, internals).x+ },+ set(this: ProxyThis, value: number) {+ graph(this, internals).updateNode(nodeId(this, internals), { x: value })+ }+ },+ y: {+ get(this: ProxyThis): number {+ return raw(this, internals).y+ },+ set(this: ProxyThis, value: number) {+ graph(this, internals).updateNode(nodeId(this, internals), { y: value })+ }+ },+ width: {+ get(this: ProxyThis): number {+ return raw(this, internals).width+ }+ },+ height: {+ get(this: ProxyThis): number {+ return raw(this, internals).height+ }+ },+ rotation: {+ get(this: ProxyThis): number {+ return raw(this, internals).rotation+ },+ set(this: ProxyThis, value: number) {+ graph(this, internals).updateNode(nodeId(this, internals), { rotation: value })+ }+ },+ absoluteTransform: {+ get(this: ProxyThis): [[number, number, number], [number, number, number]] {+ const pos = graph(this, internals).getAbsolutePosition(nodeId(this, internals))+ return [+ [1, 0, pos.x],+ [0, 1, pos.y]+ ]+ }+ },+ absoluteBoundingBox: {+ get(this: ProxyThis): Rect {+ return graph(this, internals).getAbsoluteBounds(nodeId(this, internals))+ }+ },+ absoluteRenderBounds: {+ get(this: ProxyThis): Rect {+ return graph(this, internals).getAbsoluteBounds(nodeId(this, internals))+ }+ }+ })++ Object.assign(prototype, {+ resize(this: ProxyThis, width: number, height: number): void {+ graph(this, internals).updateNode(nodeId(this, internals), { width, height })+ },+ resizeWithoutConstraints(this: ProxyThis, width: number, height: number): void {+ ;(this as unknown as { resize(width: number, height: number): void }).resize(width, height)+ }+ })+}++export type { NodeProxyHost }diff --git a/packages/core/src/figma-api/accessors/layout.ts b/packages/core/src/figma-api/accessors/layout.tsnew file mode 100644index 000000000..b7c66d65c--- /dev/null+++ b/packages/core/src/figma-api/accessors/layout.ts@@ -0,0 +1,152 @@+import { raw, updateNode, type NodeProxyInternals, type ProxyThis } from '#core/figma-api/accessor-utils'++import type { LayoutMode, SceneGraph, SceneNode } from '#core/scene-graph'++function graph(target: ProxyThis, internals: NodeProxyInternals): SceneGraph {+ return target[internals.graph] as SceneGraph+}++function parentLayout(target: ProxyThis, internals: NodeProxyInternals): 'HORIZONTAL' | 'VERTICAL' | 'NONE' {+ const node = raw(target, internals)+ if (!node.parentId) return 'NONE'+ const parent = graph(target, internals).getNode(node.parentId)+ if (!parent) return 'NONE'+ const mode = parent.layoutMode+ return mode === 'HORIZONTAL' || mode === 'VERTICAL' ? mode : 'NONE'+}++function setLayoutSizing(+ target: ProxyThis,+ internals: NodeProxyInternals,+ axis: 'HORIZONTAL' | 'VERTICAL',+ value: string+): void {+ const node = raw(target, internals)+ const layout = node.layoutMode !== 'NONE' ? node.layoutMode : parentLayout(target, internals)+ const isHorizontal = axis === 'HORIZONTAL'+ const usesCounterAxis = isHorizontal ? layout === 'VERTICAL' : layout === 'HORIZONTAL'+ const updates: Partial<SceneNode> = usesCounterAxis+ ? { counterAxisSizing: value as SceneNode['counterAxisSizing'] }+ : { primaryAxisSizing: value as SceneNode['primaryAxisSizing'] }+ if (parentLayout(target, internals) === axis) updates.layoutGrow = value === 'FILL' ? 1 : 0+ updateNode(target, internals, updates)+}++export function installLayoutNodeProxyAccessors(+ prototype: object,+ internals: NodeProxyInternals+): void {+ Object.defineProperties(prototype, {+ layoutMode: simpleAccessor(internals, 'layoutMode'),+ layoutDirection: {+ get(this: ProxyThis): string {+ const node = raw(this, internals)+ return Object.hasOwn(node, 'layoutDirection') ? node.layoutDirection : 'AUTO'+ },+ set(this: ProxyThis, value: string) {+ updateNode(this, internals, { layoutDirection: value as SceneNode['layoutDirection'] })+ }+ },+ primaryAxisAlignItems: mappedAccessor(internals, 'primaryAxisAlign'),+ counterAxisAlignItems: mappedAccessor(internals, 'counterAxisAlign'),+ itemSpacing: simpleAccessor(internals, 'itemSpacing'),+ counterAxisSpacing: simpleAccessor(internals, 'counterAxisSpacing'),+ paddingTop: simpleAccessor(internals, 'paddingTop'),+ paddingRight: simpleAccessor(internals, 'paddingRight'),+ paddingBottom: simpleAccessor(internals, 'paddingBottom'),+ paddingLeft: simpleAccessor(internals, 'paddingLeft'),+ layoutWrap: mappedAccessor(internals, 'layoutWrap'),+ primaryAxisSizingMode: axisSizingModeAccessor(internals, 'primaryAxisSizing'),+ counterAxisSizingMode: axisSizingModeAccessor(internals, 'counterAxisSizing'),+ counterAxisAlignContent: mappedAccessor(internals, 'counterAxisAlignContent'),+ itemReverseZIndex: simpleAccessor(internals, 'itemReverseZIndex'),+ strokesIncludedInLayout: simpleAccessor(internals, 'strokesIncludedInLayout'),+ layoutPositioning: mappedAccessor(internals, 'layoutPositioning'),+ layoutGrow: simpleAccessor(internals, 'layoutGrow'),+ layoutAlign: {+ get(this: ProxyThis): string {+ const node = raw(this, internals)+ return node.layoutAlignSelf === 'AUTO' ? 'INHERIT' : node.layoutAlignSelf+ },+ set(this: ProxyThis, value: string) {+ const mapped = value === 'INHERIT' ? 'AUTO' : value+ updateNode(this, internals, { layoutAlignSelf: mapped as SceneNode['layoutAlignSelf'] })+ }+ },+ layoutSizingHorizontal: layoutSizingAccessor(internals, 'HORIZONTAL'),+ layoutSizingVertical: layoutSizingAccessor(internals, 'VERTICAL'),+ constraints: {+ get(this: ProxyThis): { horizontal: string; vertical: string } {+ const node = raw(this, internals)+ return { horizontal: node.horizontalConstraint, vertical: node.verticalConstraint }+ },+ set(this: ProxyThis, value: { horizontal: string; vertical: string }) {+ updateNode(this, internals, {+ horizontalConstraint: value.horizontal as SceneNode['horizontalConstraint'],+ verticalConstraint: value.vertical as SceneNode['verticalConstraint']+ })+ }+ },+ minWidth: simpleAccessor(internals, 'minWidth'),+ maxWidth: simpleAccessor(internals, 'maxWidth'),+ minHeight: simpleAccessor(internals, 'minHeight'),+ maxHeight: simpleAccessor(internals, 'maxHeight')+ })+}++function axisSizingModeAccessor(+ internals: NodeProxyInternals,+ field: 'primaryAxisSizing' | 'counterAxisSizing'+): PropertyDescriptor {+ return {+ get(this: ProxyThis): string {+ const value = raw(this, internals)[field]+ return value === 'HUG' ? 'AUTO' : value+ },+ set(this: ProxyThis, value: string) {+ const mapped = value === 'AUTO' ? 'HUG' : value+ updateNode(this, internals, { [field]: mapped } as Partial<SceneNode>)+ }+ }+}++function layoutSizingAccessor(+ internals: NodeProxyInternals,+ axis: 'HORIZONTAL' | 'VERTICAL'+): PropertyDescriptor {+ return {+ get(this: ProxyThis): string {+ const node = raw(this, internals)+ const layout = node.layoutMode !== 'NONE' ? node.layoutMode : parentLayout(this, internals)+ if (layout === 'NONE') return 'FIXED'+ return layout === axis ? node.primaryAxisSizing : node.counterAxisSizing+ },+ set(this: ProxyThis, value: string) {+ setLayoutSizing(this, internals, axis, value)+ }+ }+}++function simpleAccessor(internals: NodeProxyInternals, field: keyof SceneNode): PropertyDescriptor {+ return {+ get(this: ProxyThis): unknown {+ return raw(this, internals)[field]+ },+ set(this: ProxyThis, value: unknown) {+ updateNode(this, internals, { [field]: value } as Partial<SceneNode>)+ }+ }+}++function mappedAccessor(internals: NodeProxyInternals, field: keyof SceneNode): PropertyDescriptor {+ return {+ get(this: ProxyThis): unknown {+ return raw(this, internals)[field]+ },+ set(this: ProxyThis, value: string) {+ updateNode(this, internals, { [field]: value } as Partial<SceneNode>)+ }+ }+}++export type { LayoutMode }diff --git a/packages/core/src/figma-api/accessors/visual.ts b/packages/core/src/figma-api/accessors/visual.tsnew file mode 100644index 000000000..0a664a1c3--- /dev/null+++ b/packages/core/src/figma-api/accessors/visual.ts@@ -0,0 +1,136 @@+import { normalizeColor } from '#core/color'+import { copyEffects, copyFills, copyStrokes } from '#core/scene-graph/copy'++import { raw, updateNode, type NodeProxyInternals, type ProxyThis } from '#core/figma-api/accessor-utils'++import type { Effect, Fill, SceneNode, Stroke } from '#core/scene-graph'++export function installVisualNodeProxyAccessors(+ prototype: object,+ internals: NodeProxyInternals,+ mixed: symbol+): void {+ Object.defineProperties(prototype, {+ fills: {+ get(this: ProxyThis): readonly Fill[] {+ return Object.freeze(copyFills(raw(this, internals).fills))+ },+ set(this: ProxyThis, value: readonly Fill[]) {+ updateNode(this, internals, {+ fills: value.map((fill) => ({+ ...fill,+ color: normalizeColor(fill.color),+ gradientStops: fill.gradientStops?.map((stop) => ({+ ...stop,+ color: normalizeColor(stop.color)+ }))+ }))+ })+ }+ },+ strokes: {+ get(this: ProxyThis): readonly Stroke[] {+ return Object.freeze(copyStrokes(raw(this, internals).strokes))+ },+ set(this: ProxyThis, value: readonly Stroke[]) {+ updateNode(this, internals, {+ strokes: value.map((stroke) => ({ ...stroke, color: normalizeColor(stroke.color) }))+ })+ }+ },+ effects: {+ get(this: ProxyThis): readonly Effect[] {+ return Object.freeze(copyEffects(raw(this, internals).effects))+ },+ set(this: ProxyThis, value: readonly Effect[]) {+ updateNode(this, internals, {+ effects: value.map((effect) => ({ ...effect, color: normalizeColor(effect.color) }))+ })+ }+ },+ opacity: {+ get(this: ProxyThis): number {+ return raw(this, internals).opacity+ },+ set(this: ProxyThis, value: number) {+ updateNode(this, internals, { opacity: value })+ }+ },+ visible: {+ get(this: ProxyThis): boolean {+ return raw(this, internals).visible+ },+ set(this: ProxyThis, value: boolean) {+ updateNode(this, internals, { visible: value })+ }+ },+ locked: {+ get(this: ProxyThis): boolean {+ return raw(this, internals).locked+ },+ set(this: ProxyThis, value: boolean) {+ updateNode(this, internals, { locked: value })+ }+ },+ blendMode: {+ get(this: ProxyThis): string {+ return raw(this, internals).blendMode+ },+ set(this: ProxyThis, value: string) {+ updateNode(this, internals, { blendMode: value as SceneNode['blendMode'] })+ }+ },+ clipsContent: {+ get(this: ProxyThis): boolean {+ return raw(this, internals).clipsContent+ },+ set(this: ProxyThis, value: boolean) {+ updateNode(this, internals, { clipsContent: value })+ }+ },+ cornerRadius: {+ get(this: ProxyThis): number | symbol {+ const node = raw(this, internals)+ if (node.independentCorners) return mixed+ return node.cornerRadius+ },+ set(this: ProxyThis, value: number | symbol) {+ if (value === mixed) return+ updateNode(this, internals, {+ cornerRadius: value as number,+ topLeftRadius: value as number,+ topRightRadius: value as number,+ bottomRightRadius: value as number,+ bottomLeftRadius: value as number,+ independentCorners: false+ })+ }+ },+ topLeftRadius: cornerAccessor(internals, 'topLeftRadius'),+ topRightRadius: cornerAccessor(internals, 'topRightRadius'),+ bottomLeftRadius: cornerAccessor(internals, 'bottomLeftRadius'),+ bottomRightRadius: cornerAccessor(internals, 'bottomRightRadius'),+ cornerSmoothing: {+ get(this: ProxyThis): number {+ return raw(this, internals).cornerSmoothing+ },+ set(this: ProxyThis, value: number) {+ updateNode(this, internals, { cornerSmoothing: value })+ }+ }+ })+}++function cornerAccessor(+ internals: NodeProxyInternals,+ field: 'topLeftRadius' | 'topRightRadius' | 'bottomLeftRadius' | 'bottomRightRadius'+): PropertyDescriptor {+ return {+ get(this: ProxyThis): number {+ return raw(this, internals)[field]+ },+ set(this: ProxyThis, value: number) {+ updateNode(this, internals, { [field]: value, independentCorners: true })+ }+ }+}diff --git a/packages/core/src/figma-api/fonts.ts b/packages/core/src/figma-api/fonts.tsnew file mode 100644index 000000000..df6e74e81--- /dev/null+++ b/packages/core/src/figma-api/fonts.ts@@ -0,0 +1,25 @@+import { FONT_WEIGHT_NAMES } from '#core/text/fonts'++export type FigmaFontName = { family: string; style: string }+export type FigmaFont = { fontName: FigmaFontName }++export function weightToStyleName(weight: number, italic: boolean): string {+ const base = FONT_WEIGHT_NAMES[weight] ?? 'Regular'+ return italic ? `${base} Italic` : base+}++const STYLE_NAME_TO_WEIGHT: Record<string, number> = Object.fromEntries([+ ...Object.entries(FONT_WEIGHT_NAMES).map(([w, name]) => [name.toLowerCase(), Number(w)]),+ ['ultra light', 200],+ ['', 400],+ ['demi bold', 600],+ ['ultra bold', 800],+ ['heavy', 900]+])++export function styleNameToWeight(style: string): { weight: number; italic: boolean } {+ const lower = style.toLowerCase()+ const italic = lower.includes('italic')+ const clean = lower.replace(/italic/i, '').trim()+ return { weight: STYLE_NAME_TO_WEIGHT[clean] ?? 400, italic }+}diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.tsindex dc22f011d..8e1d51c18 100644--- a/packages/core/src/figma-api/index.ts+++ b/packages/core/src/figma-api/index.ts@@ -1,6 +1,6 @@-import { IS_BROWSER } from '../constants'-import { computeBounds } from '../geometry'-import { copyFills, copyStrokes, copyEffects } from '../scene-graph/copy'+import { IS_BROWSER } from '#core/constants'+import { computeBounds } from '#core/geometry'+import { copyFills, copyStrokes, copyEffects } from '#core/scene-graph/copy'import {FigmaNodeProxy,INTERNAL_ID,@@ -10,7 +10,7 @@ import {type NodeProxyHost} from './proxy'-import type { RasterExportFormat } from '../io/formats/raster'+import type { RasterExportFormat } from '#core/io/formats/raster'import type {SceneGraph,NodeType,@@ -18,8 +18,8 @@ import type {VariableCollection,VariableType,VariableValue-} from '../scene-graph'-import type { Rect, Vector } from '../types'+} from '#core/scene-graph'+import type { Rect, Vector } from '#core/types'export { FigmaNodeProxy } from './proxy'export type { FigmaFont, FigmaFontName } from './proxy'diff --git a/packages/core/src/figma-api/plugin-data.ts b/packages/core/src/figma-api/plugin-data.tsnew file mode 100644index 000000000..d901f53e6--- /dev/null+++ b/packages/core/src/figma-api/plugin-data.ts@@ -0,0 +1,53 @@+import type { SceneGraph, SceneNode } from '#core/scene-graph'++const OPEN_PENCIL_PLUGIN_DATA_NAMESPACE = 'open-pencil'++export function getPluginData(node: SceneNode, key: string): string {+ return (+ node.pluginData.find(+ (entry) => entry.pluginId === OPEN_PENCIL_PLUGIN_DATA_NAMESPACE && entry.key === key+ )?.value ?? ''+ )+}++export function setPluginData(graph: SceneGraph, node: SceneNode, key: string, value: string): void {+ const pluginData = node.pluginData.filter(+ (entry) => !(entry.pluginId === OPEN_PENCIL_PLUGIN_DATA_NAMESPACE && entry.key === key)+ )+ if (value !== '') {+ pluginData.push({ pluginId: OPEN_PENCIL_PLUGIN_DATA_NAMESPACE, key, value })+ }+ graph.updateNode(node.id, { pluginData })+}++export function getPluginDataKeys(node: SceneNode): string[] {+ return node.pluginData+ .filter((entry) => entry.pluginId === OPEN_PENCIL_PLUGIN_DATA_NAMESPACE)+ .map((entry) => entry.key)+}++export function getSharedPluginData(node: SceneNode, namespace: string, key: string): string {+ return node.sharedPluginData.find((entry) => entry.namespace === namespace && entry.key === key)?.value ?? ''+}++export function setSharedPluginData(+ graph: SceneGraph,+ node: SceneNode,+ namespace: string,+ key: string,+ value: string+): void {+ const sharedPluginData = node.sharedPluginData.filter(+ (entry) => !(entry.namespace === namespace && entry.key === key)+ )+ if (value !== '') {+ sharedPluginData.push({ namespace, key, value })+ }+ graph.updateNode(node.id, { sharedPluginData })+}++export function getSharedPluginDataKeys(node: SceneNode, namespace: string): string[] {+ return node.sharedPluginData+ .filter((entry) => entry.namespace === namespace)+ .map((entry) => entry.key)+}diff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.tsindex c8012cb2c..26642ef2a 100644--- a/packages/core/src/figma-api/proxy.ts+++ b/packages/core/src/figma-api/proxy.ts@@ -1,9 +1,16 @@-import { normalizeColor } from '../color'-import { getFillOkHCL, getStrokeOkHCL, setNodeFillOkHCL, setNodeStrokeOkHCL } from '../color/okhcl'-import { copyFills, copyStrokes, copyEffects } from '../scene-graph/copy'-import { FONT_WEIGHT_NAMES } from '../text/fonts'--import type { OkHCLColor, OkHCLPayload } from '../color/okhcl'+import { getFillOkHCL, getStrokeOkHCL, setNodeFillOkHCL, setNodeStrokeOkHCL } from '#core/color/okhcl'+import type { FigmaFontName } from './fonts'+import { nodeProxyToJSON } from './serialization'+import * as TextProxy from './text'+import {+ setFirstStrokeAlign,+ setFirstStrokeWeight,+ setIndependentStrokeWeight+} from './strokes'+import * as Traversal from './traversal'+import * as PluginData from './plugin-data'++import type { OkHCLColor, OkHCLPayload } from '#core/color/okhcl'/* eslint-disable max-lines -- Figma Plugin API proxy; FigmaAPI already in separate file */import type {SceneGraph,@@ -13,41 +20,20 @@ import type {Stroke,Effect,LayoutMode-} from '../scene-graph'-import type { Rect } from '../types'+} from '#core/scene-graph'+import { installBasicNodeProxyAccessors } from './accessors/basic'+import { installLayoutNodeProxyAccessors } from './accessors/layout'+import { installVisualNodeProxyAccessors } from './accessors/visual'+import type { Rect } from '#core/types'const MIXED = Symbol('mixed')-export type FigmaFontName = { family: string; style: string }-export type FigmaFont = { fontName: FigmaFontName }--export function weightToStyleName(weight: number, italic: boolean): string {- const base = FONT_WEIGHT_NAMES[weight] ?? 'Regular'- return italic ? `${base} Italic` : base-}--const STYLE_NAME_TO_WEIGHT: Record<string, number> = Object.fromEntries([- ...Object.entries(FONT_WEIGHT_NAMES).map(([w, name]) => [name.toLowerCase(), Number(w)]),- ['ultra light', 200],- ['', 400],- ['demi bold', 600],- ['ultra bold', 800],- ['heavy', 900]-])--export function styleNameToWeight(style: string): { weight: number; italic: boolean } {- const lower = style.toLowerCase()- const italic = lower.includes('italic')- const clean = lower.replace(/italic/i, '').trim()- return { weight: STYLE_NAME_TO_WEIGHT[clean] ?? 400, italic }-}+export { styleNameToWeight, weightToStyleName, type FigmaFont, type FigmaFontName } from './fonts'export const INTERNAL_ID = Symbol('id')export const INTERNAL_GRAPH = Symbol('graph')export const INTERNAL_API = Symbol('api')-const OPEN_PENCIL_PLUGIN_DATA_NAMESPACE = 'open-pencil'-export interface NodeProxyHost {wrapNode(id: string): FigmaNodeProxyreadonly currentPageId: string@@ -55,11 +41,69 @@ export interface NodeProxyHost {export { MIXED }+export class FigmaNodeProxy {[INTERNAL_ID]: string;[INTERNAL_GRAPH]: SceneGraph;[INTERNAL_API]: NodeProxyHost+ declare readonly id: string+ declare readonly type: NodeType+ declare name: string+ declare readonly removed: boolean+ declare x: number+ declare y: number+ declare readonly width: number+ declare readonly height: number+ declare rotation: number+ declare resize: (width: number, height: number) => void+ declare resizeWithoutConstraints: (width: number, height: number) => void+ declare readonly absoluteTransform: [[number, number, number], [number, number, number]]+ declare readonly absoluteBoundingBox: Rect+ declare readonly absoluteRenderBounds: Rect++ declare fills: readonly Fill[]+ declare strokes: readonly Stroke[]+ declare effects: readonly Effect[]+ declare opacity: number+ declare visible: boolean+ declare locked: boolean+ declare blendMode: string+ declare clipsContent: boolean+ declare cornerRadius: number | typeof MIXED+ declare topLeftRadius: number+ declare topRightRadius: number+ declare bottomLeftRadius: number+ declare bottomRightRadius: number+ declare cornerSmoothing: number++ declare layoutMode: LayoutMode+ declare layoutDirection: string+ declare primaryAxisAlignItems: string+ declare counterAxisAlignItems: string+ declare itemSpacing: number+ declare counterAxisSpacing: number+ declare paddingTop: number+ declare paddingRight: number+ declare paddingBottom: number+ declare paddingLeft: number+ declare layoutWrap: string+ declare primaryAxisSizingMode: string+ declare counterAxisSizingMode: string+ declare counterAxisAlignContent: string+ declare itemReverseZIndex: boolean+ declare strokesIncludedInLayout: boolean+ declare layoutPositioning: string+ declare layoutGrow: number+ declare layoutAlign: string+ declare layoutSizingHorizontal: string+ declare layoutSizingVertical: string+ declare constraints: { horizontal: string; vertical: string }+ declare minWidth: number | null+ declare maxWidth: number | null+ declare minHeight: number | null+ declare maxHeight: number | null+constructor(id: string, graph: SceneGraph, api: NodeProxyHost) {this[INTERNAL_ID] = idthis[INTERNAL_GRAPH] = graph@@ -72,241 +116,6 @@ export class FigmaNodeProxy {return n}- _parentLayout(): 'HORIZONTAL' | 'VERTICAL' | 'NONE' {- const n = this._raw()- if (!n.parentId) return 'NONE'- const parent = this[INTERNAL_GRAPH].getNode(n.parentId)- if (!parent) return 'NONE'- const mode = parent.layoutMode- return mode === 'HORIZONTAL' || mode === 'VERTICAL' ? mode : 'NONE'- }-- get id(): string {- return this[INTERNAL_ID]- }-- get type(): NodeType {- return this._raw().type- }-- get name(): string {- return this._raw().name- }-- set name(v: string) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { name: v })- }-- get removed(): boolean {- return !this[INTERNAL_GRAPH].getNode(this[INTERNAL_ID])- }-- // --- Geometry ----- get x(): number {- return this._raw().x- }-- set x(v: number) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { x: v })- }-- get y(): number {- return this._raw().y- }-- set y(v: number) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { y: v })- }-- get width(): number {- return this._raw().width- }-- get height(): number {- return this._raw().height- }-- get rotation(): number {- return this._raw().rotation- }-- set rotation(v: number) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { rotation: v })- }-- resize(width: number, height: number): void {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { width, height })- }-- resizeWithoutConstraints(width: number, height: number): void {- this.resize(width, height)- }-- get absoluteTransform(): [[number, number, number], [number, number, number]] {- const pos = this[INTERNAL_GRAPH].getAbsolutePosition(this[INTERNAL_ID])- return [- [1, 0, pos.x],- [0, 1, pos.y]- ]- }-- get absoluteBoundingBox(): Rect {- return this[INTERNAL_GRAPH].getAbsoluteBounds(this[INTERNAL_ID])- }-- get absoluteRenderBounds(): Rect {- return this.absoluteBoundingBox- }-- // --- Visual ----- get fills(): readonly Fill[] {- return Object.freeze(copyFills(this._raw().fills))- }-- set fills(v: readonly Fill[]) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {- fills: v.map((f) => ({- ...f,- color: normalizeColor(f.color),- gradientStops: f.gradientStops?.map((s) => ({ ...s, color: normalizeColor(s.color) }))- }))- })- }-- get strokes(): readonly Stroke[] {- return Object.freeze(copyStrokes(this._raw().strokes))- }-- set strokes(v: readonly Stroke[]) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {- strokes: v.map((s) => ({ ...s, color: normalizeColor(s.color) }))- })- }-- get effects(): readonly Effect[] {- return Object.freeze(copyEffects(this._raw().effects))- }-- set effects(v: readonly Effect[]) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {- effects: v.map((e) => ({ ...e, color: normalizeColor(e.color) }))- })- }-- get opacity(): number {- return this._raw().opacity- }-- set opacity(v: number) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { opacity: v })- }-- get visible(): boolean {- return this._raw().visible- }-- set visible(v: boolean) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { visible: v })- }-- get locked(): boolean {- return this._raw().locked- }-- set locked(v: boolean) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { locked: v })- }-- get blendMode(): string {- return this._raw().blendMode- }-- set blendMode(v: string) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { blendMode: v as SceneNode['blendMode'] })- }-- get clipsContent(): boolean {- return this._raw().clipsContent- }-- set clipsContent(v: boolean) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { clipsContent: v })- }-- // --- Corner Radius ----- get cornerRadius(): number | typeof MIXED {- const n = this._raw()- if (n.independentCorners) return MIXED- return n.cornerRadius- }-- set cornerRadius(v: number | typeof MIXED) {- if (v === MIXED) return- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {- cornerRadius: v,- topLeftRadius: v,- topRightRadius: v,- bottomRightRadius: v,- bottomLeftRadius: v,- independentCorners: false- })- }-- get topLeftRadius(): number {- return this._raw().topLeftRadius- }-- set topLeftRadius(v: number) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {- topLeftRadius: v,- independentCorners: true- })- }-- get topRightRadius(): number {- return this._raw().topRightRadius- }-- set topRightRadius(v: number) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {- topRightRadius: v,- independentCorners: true- })- }-- get bottomLeftRadius(): number {- return this._raw().bottomLeftRadius- }-- set bottomLeftRadius(v: number) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {- bottomLeftRadius: v,- independentCorners: true- })- }-- get bottomRightRadius(): number {- return this._raw().bottomRightRadius- }-- set bottomRightRadius(v: number) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {- bottomRightRadius: v,- independentCorners: true- })- }-- get cornerSmoothing(): number {- return this._raw().cornerSmoothing- }-- set cornerSmoothing(v: number) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { cornerSmoothing: v })- }-// --- Stroke details ---get strokeWeight(): number {@@ -315,12 +124,7 @@ export class FigmaNodeProxy {}set strokeWeight(v: number) {- const n = this._raw()- if (n.strokes.length > 0) {- const strokes = copyStrokes(n.strokes)- strokes[0].weight = v- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { strokes })- }+ setFirstStrokeWeight(this[INTERNAL_GRAPH], this._raw(), v)}get strokeAlign(): string {@@ -329,12 +133,7 @@ export class FigmaNodeProxy {}set strokeAlign(v: string) {- const n = this._raw()- if (n.strokes.length > 0) {- const strokes = copyStrokes(n.strokes)- strokes[0].align = v as Stroke['align']- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { strokes })- }+ setFirstStrokeAlign(this[INTERNAL_GRAPH], this._raw(), v)}get dashPattern(): readonly number[] {@@ -374,10 +173,7 @@ export class FigmaNodeProxy {}set strokeTopWeight(v: number) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {- borderTopWeight: v,- independentStrokeWeights: true- })+ setIndependentStrokeWeight(this[INTERNAL_GRAPH], this[INTERNAL_ID], 'borderTopWeight', v)}get strokeBottomWeight(): number {@@ -385,10 +181,7 @@ export class FigmaNodeProxy {}set strokeBottomWeight(v: number) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {- borderBottomWeight: v,- independentStrokeWeights: true- })+ setIndependentStrokeWeight(this[INTERNAL_GRAPH], this[INTERNAL_ID], 'borderBottomWeight', v)}get strokeLeftWeight(): number {@@ -396,10 +189,7 @@ export class FigmaNodeProxy {}set strokeLeftWeight(v: number) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {- borderLeftWeight: v,- independentStrokeWeights: true- })+ setIndependentStrokeWeight(this[INTERNAL_GRAPH], this[INTERNAL_ID], 'borderLeftWeight', v)}get strokeRightWeight(): number {@@ -407,10 +197,7 @@ export class FigmaNodeProxy {}set strokeRightWeight(v: number) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {- borderRightWeight: v,- independentStrokeWeights: true- })+ setIndependentStrokeWeight(this[INTERNAL_GRAPH], this[INTERNAL_ID], 'borderRightWeight', v)}// --- Text ---@@ -432,17 +219,11 @@ export class FigmaNodeProxy {}get fontName(): FigmaFontName {- const n = this._raw()- return { family: n.fontFamily, style: weightToStyleName(n.fontWeight, n.italic) }+ return TextProxy.getFontName(this._raw())}set fontName(v: FigmaFontName) {- const { weight, italic } = styleNameToWeight(v.style)- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {- fontFamily: v.family,- fontWeight: weight,- italic- })+ TextProxy.setFontName(this[INTERNAL_GRAPH], this[INTERNAL_ID], v)}get fontWeight(): number {@@ -554,285 +335,13 @@ export class FigmaNodeProxy {}insertCharacters(start: number, characters: string): void {- const n = this._raw()- const text = n.text.slice(0, start) + characters + n.text.slice(start)- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { text })+ TextProxy.insertCharacters(this[INTERNAL_GRAPH], this._raw(), start, characters)}deleteCharacters(start: number, end: number): void {- const n = this._raw()- const text = n.text.slice(0, start) + n.text.slice(end)- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { text })- }-- // --- Auto-layout ----- get layoutMode(): LayoutMode {- return this._raw().layoutMode- }-- set layoutMode(v: LayoutMode) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { layoutMode: v })- }-- get layoutDirection(): string {- const raw = this._raw()- return Object.hasOwn(raw, 'layoutDirection') ? raw.layoutDirection : 'AUTO'- }-- set layoutDirection(v: string) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {- layoutDirection: v as SceneNode['layoutDirection']- })- }-- get primaryAxisAlignItems(): string {- return this._raw().primaryAxisAlign- }-- set primaryAxisAlignItems(v: string) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {- primaryAxisAlign: v as SceneNode['primaryAxisAlign']- })- }-- get counterAxisAlignItems(): string {- return this._raw().counterAxisAlign- }-- set counterAxisAlignItems(v: string) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {- counterAxisAlign: v as SceneNode['counterAxisAlign']- })- }-- get itemSpacing(): number {- return this._raw().itemSpacing- }-- set itemSpacing(v: number) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { itemSpacing: v })- }-- get counterAxisSpacing(): number {- return this._raw().counterAxisSpacing- }-- set counterAxisSpacing(v: number) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { counterAxisSpacing: v })- }-- get paddingTop(): number {- return this._raw().paddingTop- }-- set paddingTop(v: number) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { paddingTop: v })- }-- get paddingRight(): number {- return this._raw().paddingRight- }-- set paddingRight(v: number) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { paddingRight: v })- }-- get paddingBottom(): number {- return this._raw().paddingBottom- }-- set paddingBottom(v: number) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { paddingBottom: v })- }-- get paddingLeft(): number {- return this._raw().paddingLeft- }-- set paddingLeft(v: number) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { paddingLeft: v })- }-- get layoutWrap(): string {- return this._raw().layoutWrap- }-- set layoutWrap(v: string) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { layoutWrap: v as SceneNode['layoutWrap'] })- }-- get primaryAxisSizingMode(): string {- return this._raw().primaryAxisSizing === 'HUG' ? 'AUTO' : this._raw().primaryAxisSizing- }-- set primaryAxisSizingMode(v: string) {- const mapped = v === 'AUTO' ? 'HUG' : v- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {- primaryAxisSizing: mapped as SceneNode['primaryAxisSizing']- })- }-- get counterAxisSizingMode(): string {- return this._raw().counterAxisSizing === 'HUG' ? 'AUTO' : this._raw().counterAxisSizing- }-- set counterAxisSizingMode(v: string) {- const mapped = v === 'AUTO' ? 'HUG' : v- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {- counterAxisSizing: mapped as SceneNode['counterAxisSizing']- })- }-- get counterAxisAlignContent(): string {- return this._raw().counterAxisAlignContent- }-- set counterAxisAlignContent(v: string) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {- counterAxisAlignContent: v as SceneNode['counterAxisAlignContent']- })- }-- get itemReverseZIndex(): boolean {- return this._raw().itemReverseZIndex+ TextProxy.deleteCharacters(this[INTERNAL_GRAPH], this._raw(), start, end)}- set itemReverseZIndex(v: boolean) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { itemReverseZIndex: v })- }-- get strokesIncludedInLayout(): boolean {- return this._raw().strokesIncludedInLayout- }-- set strokesIncludedInLayout(v: boolean) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { strokesIncludedInLayout: v })- }-- // --- Layout child props ----- get layoutPositioning(): string {- return this._raw().layoutPositioning- }-- set layoutPositioning(v: string) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {- layoutPositioning: v as SceneNode['layoutPositioning']- })- }-- get layoutGrow(): number {- return this._raw().layoutGrow- }-- set layoutGrow(v: number) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { layoutGrow: v })- }-- get layoutAlign(): string {- const n = this._raw()- if (n.layoutAlignSelf === 'AUTO') return 'INHERIT'- return n.layoutAlignSelf- }-- set layoutAlign(v: string) {- const mapped = v === 'INHERIT' ? 'AUTO' : v- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {- layoutAlignSelf: mapped as SceneNode['layoutAlignSelf']- })- }-- get layoutSizingHorizontal(): string {- const n = this._raw()- const layout = n.layoutMode !== 'NONE' ? n.layoutMode : this._parentLayout()- if (layout === 'NONE') return 'FIXED'- return layout === 'HORIZONTAL' ? n.primaryAxisSizing : n.counterAxisSizing- }-- set layoutSizingHorizontal(v: string) {- const n = this._raw()- const layout = n.layoutMode !== 'NONE' ? n.layoutMode : this._parentLayout()- const parentLayout = this._parentLayout()- const isMainAxis = parentLayout === 'HORIZONTAL'- const updates: Partial<SceneNode> =- layout === 'VERTICAL'- ? { counterAxisSizing: v as SceneNode['counterAxisSizing'] }- : { primaryAxisSizing: v as SceneNode['primaryAxisSizing'] }- if (isMainAxis) updates.layoutGrow = v === 'FILL' ? 1 : 0- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], updates)- }-- get layoutSizingVertical(): string {- const n = this._raw()- const layout = n.layoutMode !== 'NONE' ? n.layoutMode : this._parentLayout()- if (layout === 'NONE') return 'FIXED'- return layout === 'VERTICAL' ? n.primaryAxisSizing : n.counterAxisSizing- }-- set layoutSizingVertical(v: string) {- const n = this._raw()- const layout = n.layoutMode !== 'NONE' ? n.layoutMode : this._parentLayout()- const parentLayout = this._parentLayout()- const isMainAxis = parentLayout === 'VERTICAL'- const updates: Partial<SceneNode> =- layout === 'HORIZONTAL'- ? { counterAxisSizing: v as SceneNode['counterAxisSizing'] }- : { primaryAxisSizing: v as SceneNode['primaryAxisSizing'] }- if (isMainAxis) updates.layoutGrow = v === 'FILL' ? 1 : 0- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], updates)- }-- // --- Constraints ----- get constraints(): { horizontal: string; vertical: string } {- const n = this._raw()- return { horizontal: n.horizontalConstraint, vertical: n.verticalConstraint }- }-- set constraints(v: { horizontal: string; vertical: string }) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {- horizontalConstraint: v.horizontal as SceneNode['horizontalConstraint'],- verticalConstraint: v.vertical as SceneNode['verticalConstraint']- })- }-- // --- Dimension constraints ----- get minWidth(): number | null {- return this._raw().minWidth- }-- set minWidth(v: number | null) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { minWidth: v })- }-- get maxWidth(): number | null {- return this._raw().maxWidth- }-- set maxWidth(v: number | null) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { maxWidth: v })- }-- get minHeight(): number | null {- return this._raw().minHeight- }-- set minHeight(v: number | null) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { minHeight: v })- }-- get maxHeight(): number | null {- return this._raw().maxHeight- }-- set maxHeight(v: number | null) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { maxHeight: v })- }-- // --- Mask ----get isMask(): boolean {return this._raw().isMask}@@ -914,101 +423,49 @@ export class FigmaNodeProxy {}findAll(callback?: (node: FigmaNodeProxy) => boolean): FigmaNodeProxy[] {- const results: FigmaNodeProxy[] = []- const walk = (id: string) => {- for (const child of this[INTERNAL_GRAPH].getChildren(id)) {- const proxy = this[INTERNAL_API].wrapNode(child.id)- if (!callback || callback(proxy)) results.push(proxy)- walk(child.id)- }- }- walk(this[INTERNAL_ID])- return results+ return Traversal.findAll(this[INTERNAL_GRAPH], this[INTERNAL_API], this[INTERNAL_ID], callback)}findOne(callback: (node: FigmaNodeProxy) => boolean): FigmaNodeProxy | null {- const walk = (id: string): FigmaNodeProxy | null => {- for (const child of this[INTERNAL_GRAPH].getChildren(id)) {- const proxy = this[INTERNAL_API].wrapNode(child.id)- if (callback(proxy)) return proxy- const found = walk(child.id)- if (found) return found- }- return null- }- return walk(this[INTERNAL_ID])+ return Traversal.findOne(this[INTERNAL_GRAPH], this[INTERNAL_API], this[INTERNAL_ID], callback)}findChild(callback: (node: FigmaNodeProxy) => boolean): FigmaNodeProxy | null {- for (const child of this[INTERNAL_GRAPH].getChildren(this[INTERNAL_ID])) {- const proxy = this[INTERNAL_API].wrapNode(child.id)- if (callback(proxy)) return proxy- }- return null+ return Traversal.findChild(this[INTERNAL_GRAPH], this[INTERNAL_API], this[INTERNAL_ID], callback)}findChildren(callback?: (node: FigmaNodeProxy) => boolean): FigmaNodeProxy[] {- return this[INTERNAL_GRAPH]- .getChildren(this[INTERNAL_ID])- .map((c) => this[INTERNAL_API].wrapNode(c.id))- .filter((proxy) => !callback || callback(proxy))+ return Traversal.findChildren(this[INTERNAL_GRAPH], this[INTERNAL_API], this[INTERNAL_ID], callback)}findAllWithCriteria(criteria: { types?: string[] }): FigmaNodeProxy[] {- const types = criteria.types ? new Set(criteria.types) : null- return this.findAll((node) => !types || types.has(node.type))+ return Traversal.findAllWithCriteria(this[INTERNAL_GRAPH], this[INTERNAL_API], this[INTERNAL_ID], criteria)}// --- Plugin data ---getPluginData(key: string): string {- return (- this._raw().pluginData.find(- (entry) => entry.pluginId === OPEN_PENCIL_PLUGIN_DATA_NAMESPACE && entry.key === key- )?.value ?? ''- )+ return PluginData.getPluginData(this._raw(), key)}setPluginData(key: string, value: string): void {- const node = this._raw()- const pluginData = node.pluginData.filter(- (entry) => !(entry.pluginId === OPEN_PENCIL_PLUGIN_DATA_NAMESPACE && entry.key === key)- )- if (value !== '') {- pluginData.push({ pluginId: OPEN_PENCIL_PLUGIN_DATA_NAMESPACE, key, value })- }- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { pluginData })+ PluginData.setPluginData(this[INTERNAL_GRAPH], this._raw(), key, value)}getPluginDataKeys(): string[] {- return this._raw()- .pluginData.filter((entry) => entry.pluginId === OPEN_PENCIL_PLUGIN_DATA_NAMESPACE)- .map((entry) => entry.key)+ return PluginData.getPluginDataKeys(this._raw())}getSharedPluginData(namespace: string, key: string): string {- return (- this._raw().sharedPluginData.find(- (entry) => entry.namespace === namespace && entry.key === key- )?.value ?? ''- )+ return PluginData.getSharedPluginData(this._raw(), namespace, key)}setSharedPluginData(namespace: string, key: string, value: string): void {- const node = this._raw()- const sharedPluginData = node.sharedPluginData.filter(- (entry) => !(entry.namespace === namespace && entry.key === key)- )- if (value !== '') {- sharedPluginData.push({ namespace, key, value })- }- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { sharedPluginData })+ PluginData.setSharedPluginData(this[INTERNAL_GRAPH], this._raw(), namespace, key, value)}getSharedPluginDataKeys(namespace: string): string[] {- return this._raw()- .sharedPluginData.filter((entry) => entry.namespace === namespace)- .map((entry) => entry.key)+ return PluginData.getSharedPluginDataKeys(this._raw(), namespace)}getFillOkHCL(index = 0): OkHCLPayload | null {@@ -1033,40 +490,7 @@ export class FigmaNodeProxy {// --- Serialization ---toJSON(maxDepth?: number, currentDepth = 0): Record<string, unknown> {- const n = this._raw()- const obj: Record<string, unknown> = {- id: n.id,- type: n.type,- name: n.name,- x: n.x,- y: n.y,- width: n.width,- height: n.height- }- if (n.fills.length > 0) obj.fills = n.fills- if (n.strokes.length > 0) obj.strokes = n.strokes- if (n.effects.length > 0) obj.effects = n.effects- if (n.opacity !== 1) obj.opacity = n.opacity- if (n.cornerRadius > 0) obj.cornerRadius = n.cornerRadius- if (!n.visible) obj.visible = false- if (n.text) obj.characters = n.text- if (n.type === 'TEXT') obj.textDirection = n.textDirection- if (n.layoutMode !== 'NONE') {- obj.layoutMode = n.layoutMode- obj.layoutDirection = n.layoutDirection- obj.itemSpacing = n.itemSpacing- }- const children = this[INTERNAL_GRAPH].getChildren(this[INTERNAL_ID])- if (children.length > 0) {- if (maxDepth !== undefined && currentDepth >= maxDepth) {- obj.childCount = children.length- } else {- obj.children = children.map((c) =>- this[INTERNAL_API].wrapNode(c.id).toJSON(maxDepth, currentDepth + 1)- )- }- }- return obj+ return nodeProxyToJSON(this[INTERNAL_GRAPH], this[INTERNAL_API], this[INTERNAL_ID], maxDepth, currentDepth)}toString(): string {@@ -1078,3 +502,21 @@ export class FigmaNodeProxy {return this.toString()}}++installBasicNodeProxyAccessors(FigmaNodeProxy.prototype, {+ id: INTERNAL_ID,+ graph: INTERNAL_GRAPH,+ api: INTERNAL_API+})++installVisualNodeProxyAccessors(+ FigmaNodeProxy.prototype,+ { id: INTERNAL_ID, graph: INTERNAL_GRAPH, api: INTERNAL_API },+ MIXED+)++installLayoutNodeProxyAccessors(FigmaNodeProxy.prototype, {+ id: INTERNAL_ID,+ graph: INTERNAL_GRAPH,+ api: INTERNAL_API+})diff --git a/packages/core/src/figma-api/serialization.ts b/packages/core/src/figma-api/serialization.tsnew file mode 100644index 000000000..466c78c70--- /dev/null+++ b/packages/core/src/figma-api/serialization.ts@@ -0,0 +1,47 @@+import type { SceneGraph } from '#core/scene-graph'+import type { NodeProxyHost } from './proxy'++export function nodeProxyToJSON(+ graph: SceneGraph,+ api: NodeProxyHost,+ nodeId: string,+ maxDepth?: number,+ currentDepth = 0+): Record<string, unknown> {+ const n = graph.getNode(nodeId)+ if (!n) return { id: nodeId, removed: true }++ const obj: Record<string, unknown> = {+ id: n.id,+ type: n.type,+ name: n.name,+ x: n.x,+ y: n.y,+ width: n.width,+ height: n.height+ }+ if (n.fills.length > 0) obj.fills = n.fills+ if (n.strokes.length > 0) obj.strokes = n.strokes+ if (n.effects.length > 0) obj.effects = n.effects+ if (n.opacity !== 1) obj.opacity = n.opacity+ if (n.cornerRadius > 0) obj.cornerRadius = n.cornerRadius+ if (!n.visible) obj.visible = false+ if (n.text) obj.characters = n.text+ if (n.type === 'TEXT') obj.textDirection = n.textDirection+ if (n.layoutMode !== 'NONE') {+ obj.layoutMode = n.layoutMode+ obj.layoutDirection = n.layoutDirection+ obj.itemSpacing = n.itemSpacing+ }+ const children = graph.getChildren(nodeId)+ if (children.length > 0) {+ if (maxDepth !== undefined && currentDepth >= maxDepth) {+ obj.childCount = children.length+ } else {+ obj.children = children.map((child) =>+ api.wrapNode(child.id).toJSON(maxDepth, currentDepth + 1)+ )+ }+ }+ return obj+}diff --git a/packages/core/src/figma-api/strokes.ts b/packages/core/src/figma-api/strokes.tsnew file mode 100644index 000000000..024dc11e7--- /dev/null+++ b/packages/core/src/figma-api/strokes.ts@@ -0,0 +1,29 @@+import { copyStrokes } from '#core/scene-graph/copy'++import type { SceneGraph, SceneNode, Stroke } from '#core/scene-graph'++export function setFirstStrokeWeight(graph: SceneGraph, node: SceneNode, weight: number): void {+ if (node.strokes.length === 0) return+ const strokes = copyStrokes(node.strokes)+ strokes[0].weight = weight+ graph.updateNode(node.id, { strokes })+}++export function setFirstStrokeAlign(graph: SceneGraph, node: SceneNode, align: string): void {+ if (node.strokes.length === 0) return+ const strokes = copyStrokes(node.strokes)+ strokes[0].align = align as Stroke['align']+ graph.updateNode(node.id, { strokes })+}++export function setIndependentStrokeWeight(+ graph: SceneGraph,+ nodeId: string,+ field: 'borderTopWeight' | 'borderRightWeight' | 'borderBottomWeight' | 'borderLeftWeight',+ value: number+): void {+ graph.updateNode(nodeId, {+ [field]: value,+ independentStrokeWeights: true+ })+}diff --git a/packages/core/src/figma-api/text.ts b/packages/core/src/figma-api/text.tsnew file mode 100644index 000000000..c7ef85e4b--- /dev/null+++ b/packages/core/src/figma-api/text.ts@@ -0,0 +1,36 @@+import { styleNameToWeight, weightToStyleName, type FigmaFontName } from './fonts'++import type { SceneGraph, SceneNode } from '#core/scene-graph'++export function getFontName(node: SceneNode): FigmaFontName {+ return { family: node.fontFamily, style: weightToStyleName(node.fontWeight, node.italic) }+}++export function setFontName(graph: SceneGraph, nodeId: string, fontName: FigmaFontName): void {+ const { weight, italic } = styleNameToWeight(fontName.style)+ graph.updateNode(nodeId, {+ fontFamily: fontName.family,+ fontWeight: weight,+ italic+ })+}++export function insertCharacters(+ graph: SceneGraph,+ node: SceneNode,+ start: number,+ characters: string+): void {+ const text = node.text.slice(0, start) + characters + node.text.slice(start)+ graph.updateNode(node.id, { text })+}++export function deleteCharacters(+ graph: SceneGraph,+ node: SceneNode,+ start: number,+ end: number+): void {+ const text = node.text.slice(0, start) + node.text.slice(end)+ graph.updateNode(node.id, { text })+}diff --git a/packages/core/src/figma-api/traversal.ts b/packages/core/src/figma-api/traversal.tsnew file mode 100644index 000000000..a9b5485f0--- /dev/null+++ b/packages/core/src/figma-api/traversal.ts@@ -0,0 +1,73 @@+import type { SceneGraph } from '#core/scene-graph'+import type { FigmaNodeProxy, NodeProxyHost } from './proxy'++export function findAll(+ graph: SceneGraph,+ api: NodeProxyHost,+ rootId: string,+ callback?: (node: FigmaNodeProxy) => boolean+): FigmaNodeProxy[] {+ const results: FigmaNodeProxy[] = []+ const walk = (id: string) => {+ for (const child of graph.getChildren(id)) {+ const proxy = api.wrapNode(child.id)+ if (!callback || callback(proxy)) results.push(proxy)+ walk(child.id)+ }+ }+ walk(rootId)+ return results+}++export function findOne(+ graph: SceneGraph,+ api: NodeProxyHost,+ rootId: string,+ callback: (node: FigmaNodeProxy) => boolean+): FigmaNodeProxy | null {+ const walk = (id: string): FigmaNodeProxy | null => {+ for (const child of graph.getChildren(id)) {+ const proxy = api.wrapNode(child.id)+ if (callback(proxy)) return proxy+ const found = walk(child.id)+ if (found) return found+ }+ return null+ }+ return walk(rootId)+}++export function findChild(+ graph: SceneGraph,+ api: NodeProxyHost,+ rootId: string,+ callback: (node: FigmaNodeProxy) => boolean+): FigmaNodeProxy | null {+ for (const child of graph.getChildren(rootId)) {+ const proxy = api.wrapNode(child.id)+ if (callback(proxy)) return proxy+ }+ return null+}++export function findChildren(+ graph: SceneGraph,+ api: NodeProxyHost,+ rootId: string,+ callback?: (node: FigmaNodeProxy) => boolean+): FigmaNodeProxy[] {+ return graph+ .getChildren(rootId)+ .map((child) => api.wrapNode(child.id))+ .filter((proxy) => !callback || callback(proxy))+}++export function findAllWithCriteria(+ graph: SceneGraph,+ api: NodeProxyHost,+ rootId: string,+ criteria: { types?: string[] }+): FigmaNodeProxy[] {+ const types = criteria.types ? new Set(criteria.types) : null+ return findAll(graph, api, rootId, (node) => !types || types.has(node.type))+}diff --git a/packages/core/src/geometry.ts b/packages/core/src/geometry.tsindex b75c6270f..411f332cd 100644--- a/packages/core/src/geometry.ts+++ b/packages/core/src/geometry.ts@@ -67,19 +67,72 @@ export function rotatedBBox(return { left, right, top, bottom, centerX: (left + right) / 2, centerY: (top + bottom) / 2 }}+interface BoundsAccumulator {+ minX: number+ minY: number+ maxX: number+ maxY: number+}++function createBoundsAccumulator(): BoundsAccumulator {+ return { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity }+}++function includePoint(bounds: BoundsAccumulator, x: number, y: number): void {+ bounds.minX = Math.min(bounds.minX, x)+ bounds.minY = Math.min(bounds.minY, y)+ bounds.maxX = Math.max(bounds.maxX, x)+ bounds.maxY = Math.max(bounds.maxY, y)+}++function includeRect(bounds: BoundsAccumulator, rect: Rect): void {+ includePoint(bounds, rect.x, rect.y)+ includePoint(bounds, rect.x + rect.width, rect.y + rect.height)+}++function boundsToRect(bounds: BoundsAccumulator): Rect {+ return bounds.minX === Infinity+ ? { x: 0, y: 0, width: 0, height: 0 }+ : {+ x: bounds.minX,+ y: bounds.minY,+ width: bounds.maxX - bounds.minX,+ height: bounds.maxY - bounds.minY+ }+}+export function computeBounds(items: Iterable<Rect>): Rect {- let minX = Infinity,- minY = Infinity,- maxX = -Infinity,- maxY = -Infinity- for (const item of items) {- minX = Math.min(minX, item.x)- minY = Math.min(minY, item.y)- maxX = Math.max(maxX, item.x + item.width)- maxY = Math.max(maxY, item.y + item.height)- }- if (minX === Infinity) return { x: 0, y: 0, width: 0, height: 0 }- return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }+ const bounds = createBoundsAccumulator()+ for (const item of items) includeRect(bounds, item)+ return boundsToRect(bounds)+}++export function polygonVertices(node: {+ width: number+ height: number+ pointCount: number+ type: string+ starInnerRadius: number+}): Vector[] {+ const cx = node.width / 2+ const cy = node.height / 2+ const rx = node.width / 2+ const ry = node.height / 2+ const pointCount = Math.max(3, node.pointCount)+ const isStar = node.type === 'STAR'+ const innerRatio = isStar ? node.starInnerRadius : 1+ const totalPoints = isStar ? pointCount * 2 : pointCount+ const angleOffset = -Math.PI / 2++ return Array.from({ length: totalPoints }, (_, index) => {+ const angle = angleOffset + (2 * Math.PI * index) / totalPoints+ const isInner = isStar && index % 2 === 1+ const radius = isInner ? innerRatio : 1+ return {+ x: cx + rx * radius * Math.cos(angle),+ y: cy + ry * radius * Math.sin(angle)+ }+ })}function strokeOverflow(strokes?: Stroke[]): number {@@ -123,19 +176,12 @@ export function computeAbsoluteBounds(nodes: Iterable<{ id: string; width: number; height: number }>,getAbsolutePosition: (id: string) => Vector): Rect {- let minX = Infinity,- minY = Infinity,- maxX = -Infinity,- maxY = -Infinity+ const bounds = createBoundsAccumulator()for (const n of nodes) {const abs = getAbsolutePosition(n.id)- minX = Math.min(minX, abs.x)- minY = Math.min(minY, abs.y)- maxX = Math.max(maxX, abs.x + n.width)- maxY = Math.max(maxY, abs.y + n.height)+ includeRect(bounds, { x: abs.x, y: abs.y, width: n.width, height: n.height })}- if (minX === Infinity) return { x: 0, y: 0, width: 0, height: 0 }- return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }+ return boundsToRect(bounds)}export function computeVisualBounds(@@ -149,24 +195,18 @@ export function computeVisualBounds(}>,getAbsolutePosition: (id: string) => Vector): Rect {- let minX = Infinity,- minY = Infinity,- maxX = -Infinity,- maxY = -Infinity+ const bounds = createBoundsAccumulator()for (const n of nodes) {const abs = getAbsolutePosition(n.id)const bbox = rotatedBBox(abs.x, abs.y, n.width, n.height, n.rotation ?? 0)const stroke = strokeOverflow(n.strokes)const effects = effectOverflow(n.effects)- minX = Math.min(minX, bbox.left - stroke - effects.left)- minY = Math.min(minY, bbox.top - stroke - effects.top)- maxX = Math.max(maxX, bbox.right + stroke + effects.right)- maxY = Math.max(maxY, bbox.bottom + stroke + effects.bottom)+ includePoint(bounds, bbox.left - stroke - effects.left, bbox.top - stroke - effects.top)+ includePoint(bounds, bbox.right + stroke + effects.right, bbox.bottom + stroke + effects.bottom)}- if (minX === Infinity) return { x: 0, y: 0, width: 0, height: 0 }- return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }+ return boundsToRect(bounds)}export interface VisualBounds {@@ -223,10 +263,7 @@ function geometryCommandCoordCount(command: number): number | null {}export function geometryBlobBounds(paths: Array<{ commandsBlob: Uint8Array }>): Rect | null {- let minX = Infinity- let minY = Infinity- let maxX = -Infinity- let maxY = -Infinity+ const bounds = createBoundsAccumulator()for (const path of paths) {const blob = path.commandsBlob@@ -240,16 +277,13 @@ export function geometryBlobBounds(paths: Array<{ commandsBlob: Uint8Array }>):if (offset + 8 > blob.length) breakconst x = dv.getFloat32(offset, true)const y = dv.getFloat32(offset + 4, true)- minX = Math.min(minX, x)- minY = Math.min(minY, y)- maxX = Math.max(maxX, x)- maxY = Math.max(maxY, y)+ includePoint(bounds, x, y)offset += 8}}}- return minX === Infinity ? null : { x: minX, y: minY, width: maxX - minX, height: maxY - minY }+ return bounds.minX === Infinity ? null : boundsToRect(bounds)}function transformLocalPoint(node: VisualBoundsNode, point: Vector): Vector {diff --git a/packages/core/src/icons/api.ts b/packages/core/src/icons/api.tsnew file mode 100644index 000000000..47df6da59--- /dev/null+++ b/packages/core/src/icons/api.ts@@ -0,0 +1,41 @@+import type { IconifyResponse, IconSearchResult } from './types'++const ICONIFY_API = 'https://api.iconify.design'+const FETCH_TIMEOUT_MS = 10_000++function fetchWithTimeout(url: string): Promise<Response> {+ return fetch(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) })+}++export async function fetchIconifyCollection(+ prefix: string,+ iconNames: string[]+): Promise<IconifyResponse> {+ const url = `${ICONIFY_API}/${prefix}.json?icons=${iconNames.map(encodeURIComponent).join(',')}`+ const response = await fetchWithTimeout(url)+ if (!response.ok) throw new Error(`Iconify API error: ${response.status} for prefix "${prefix}"`)+ return (await response.json()) as IconifyResponse+}++export async function searchIconify(+ query: string,+ options?: {+ limit?: number+ prefix?: string+ }+): Promise<IconSearchResult> {+ const params = new URLSearchParams({ query })+ if (options?.limit) params.set('limit', String(options.limit))+ if (options?.prefix) params.set('prefix', options.prefix)++ const response = await fetchWithTimeout(`${ICONIFY_API}/search?${params}`)+ if (!response.ok) throw new Error(`Iconify search error: ${response.status}`)+ const data = await response.json()+ const icons: string[] = data.icons ?? []+ const limit = options?.limit ?? 5+ return {+ icons: icons.slice(0, limit),+ total: data.total ?? 0,+ collections: data.collections ?? {},+ }+}diff --git a/packages/core/src/icons/index.ts b/packages/core/src/icons/index.tsindex ea5d2db05..99882f761 100644--- a/packages/core/src/icons/index.ts+++ b/packages/core/src/icons/index.ts@@ -1,53 +1,9 @@-import { iconToSVG } from '@iconify/utils'-import svgpath from 'svgpath'+import { fetchIconifyCollection, searchIconify } from './api'+import { buildIconData } from './svg'-import { parseSVGPath } from '../io/formats/svg/parse-path'+import type { IconData, IconSearchResult } from './types'-import type { VectorNetwork, WindingRule } from '../scene-graph'--const ICONIFY_API = 'https://api.iconify.design'-const FETCH_TIMEOUT_MS = 10_000--interface PathInfo {- d: string- fill: string | null- stroke: string | null- strokeWidth: number- strokeCap: string- strokeJoin: string- fillRule: WindingRule-}--export interface IconPath {- vectorNetwork: VectorNetwork- fill: string | null- stroke: string | null- strokeWidth: number- strokeCap: string- strokeJoin: string-}--export interface IconData {- prefix: string- name: string- width: number- height: number- paths: IconPath[]-}--interface IconifyIconEntry {- body: string- width?: number- height?: number-}--interface IconifyResponse {- prefix: string- width?: number- height?: number- icons: { [key: string]: IconifyIconEntry | undefined }- aliases?: { [key: string]: { parent: string } | undefined }-}+export type { IconData, IconPath, IconSearchResult } from './types'const iconCache = new Map<string, IconData>()@@ -65,170 +21,6 @@ function parseIconName(name: string): { prefix: string; iconName: string } {return { prefix: name.slice(0, colonIdx), iconName: name.slice(colonIdx + 1) }}-function attrValue(tag: string, attr: string): string | null {- const re = new RegExp(`\\b${attr}="([^"]*)"`)- const m = tag.match(re)- return m ? m[1] : null-}--function num(tag: string, attr: string, fallback = 0): number {- const v = attrValue(tag, attr)- return v !== null ? parseFloat(v) : fallback-}--function shapeToD(tagName: string, tag: string): string | null {- switch (tagName) {- case 'circle': {- const cx = num(tag, 'cx'),- cy = num(tag, 'cy'),- r = num(tag, 'r')- return r > 0- ? `M${cx - r},${cy}A${r},${r},0,1,0,${cx + r},${cy}A${r},${r},0,1,0,${cx - r},${cy}Z`- : null- }- case 'ellipse': {- const cx = num(tag, 'cx'),- cy = num(tag, 'cy'),- rx = num(tag, 'rx'),- ry = num(tag, 'ry')- return rx > 0 && ry > 0- ? `M${cx - rx},${cy}A${rx},${ry},0,1,0,${cx + rx},${cy}A${rx},${ry},0,1,0,${cx - rx},${cy}Z`- : null- }- case 'rect': {- const x = num(tag, 'x'),- y = num(tag, 'y'),- w = num(tag, 'width'),- h = num(tag, 'height')- if (w <= 0 || h <= 0) return null- const rx = Math.min(num(tag, 'rx'), w / 2),- ry = Math.min(num(tag, 'ry', rx), h / 2)- if (rx > 0 || ry > 0) {- const arx = rx || ry,- ary = ry || rx- return `M${x + arx},${y}H${x + w - arx}A${arx},${ary},0,0,1,${x + w},${y + ary}V${y + h - ary}A${arx},${ary},0,0,1,${x + w - arx},${y + h}H${x + arx}A${arx},${ary},0,0,1,${x},${y + h - ary}V${y + ary}A${arx},${ary},0,0,1,${x + arx},${y}Z`- }- return `M${x},${y}H${x + w}V${y + h}H${x}Z`- }- case 'line': {- const x1 = num(tag, 'x1'),- y1 = num(tag, 'y1'),- x2 = num(tag, 'x2'),- y2 = num(tag, 'y2')- return `M${x1},${y1}L${x2},${y2}`- }- case 'polygon':- case 'polyline': {- const points = attrValue(tag, 'points')- if (!points) return null- const nums = points- .trim()- .split(/[\s,]+/)- .map(Number)- if (nums.length < 4) return null- let d = `M${nums[0]},${nums[1]}`- for (let i = 2; i < nums.length; i += 2) d += `L${nums[i]},${nums[i + 1]}`- if (tagName === 'polygon') d += 'Z'- return d- }- default:- return null- }-}--function resolveAttr(- explicit: string | null,- group: string | null,- fallback: string | null-): string | null {- if (explicit !== null) return explicit === 'none' ? null : explicit- if (group !== null) return group === 'none' ? null : group- return fallback-}--function extractPaths(svgBody: string): PathInfo[] {- const groupAttrs = {- fill: null as string | null,- stroke: null as string | null,- strokeWidth: null as string | null,- strokeCap: null as string | null,- strokeJoin: null as string | null- }- const groupRe = /<g\b[^>]*>/g- let gm- while ((gm = groupRe.exec(svgBody)) !== null) {- groupAttrs.fill ??= attrValue(gm[0], 'fill')- groupAttrs.stroke ??= attrValue(gm[0], 'stroke')- groupAttrs.strokeWidth ??= attrValue(gm[0], 'stroke-width')- groupAttrs.strokeCap ??= attrValue(gm[0], 'stroke-linecap')- groupAttrs.strokeJoin ??= attrValue(gm[0], 'stroke-linejoin')- }-- const result: PathInfo[] = []- const shapeRe = /<(path|circle|ellipse|rect|line|polygon|polyline)\b[^>]*>/g- let match- while ((match = shapeRe.exec(svgBody)) !== null) {- const tag = match[0],- tagName = match[1]- const d = tagName === 'path' ? attrValue(tag, 'd') : shapeToD(tagName, tag)- if (!d) continue-- const fillRuleAttr = attrValue(tag, 'fill-rule')- result.push({- d,- fill: resolveAttr(attrValue(tag, 'fill'), groupAttrs.fill, 'currentColor'),- stroke: resolveAttr(attrValue(tag, 'stroke'), groupAttrs.stroke, null),- strokeWidth: parseFloat(attrValue(tag, 'stroke-width') ?? groupAttrs.strokeWidth ?? '1'),- strokeCap: attrValue(tag, 'stroke-linecap') ?? groupAttrs.strokeCap ?? 'butt',- strokeJoin: attrValue(tag, 'stroke-linejoin') ?? groupAttrs.strokeJoin ?? 'miter',- fillRule: fillRuleAttr === 'evenodd' ? 'EVENODD' : 'NONZERO'- })- }- return result-}--function buildIconData(- iconEntry: IconifyIconEntry,- prefix: string,- iconName: string,- defaultW: number,- defaultH: number,- size: number-): IconData {- const rendered = iconToSVG({- body: iconEntry.body,- width: iconEntry.width ?? defaultW,- height: iconEntry.height ?? defaultH- })- const [, , vbW, vbH] = rendered.viewBox- const sx = size / vbW- const sy = size / vbH-- const pathInfos = extractPaths(rendered.body)-- return {- prefix,- name: iconName,- width: size,- height: size,- paths: pathInfos.map((p) => {- const scaledD = sx === 1 && sy === 1 ? p.d : svgpath(p.d).scale(sx, sy).round(2).toString()- return {- vectorNetwork: parseSVGPath(scaledD, p.fillRule),- fill: p.fill,- stroke: p.stroke,- strokeWidth: p.strokeWidth * Math.min(sx, sy),- strokeCap: p.strokeCap,- strokeJoin: p.strokeJoin- }- })- }-}--function fetchWithTimeout(url: string): Promise<Response> {- return fetch(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) })-}-export async function fetchIcon(name: string, size = 24): Promise<IconData> {const results = await fetchIcons([name], size)const result = results.get(name)@@ -255,11 +47,7 @@ export async function fetchIcons(names: string[], size = 24): Promise<Map<string}const fetches = [...toFetch.entries()].map(async ([prefix, iconNames]) => {- const url = `${ICONIFY_API}/${prefix}.json?icons=${iconNames.map(encodeURIComponent).join(',')}`- const response = await fetchWithTimeout(url)- if (!response.ok)- throw new Error(`Iconify API error: ${response.status} for prefix "${prefix}"`)- const data = (await response.json()) as IconifyResponse+ const data = await fetchIconifyCollection(prefix, iconNames)const defaultW = data.width ?? 24const defaultH = data.height ?? 24@@ -281,12 +69,6 @@ export async function fetchIcons(names: string[], size = 24): Promise<Map<stringreturn results}-export interface IconSearchResult {- icons: string[]- total: number- collections: Record<string, { name: string; total: number; category?: string }>-}-export async function searchIcons(query: string,options?: {@@ -294,20 +76,7 @@ export async function searchIcons(prefix?: string}): Promise<IconSearchResult> {- const params = new URLSearchParams({ query })- if (options?.limit) params.set('limit', String(options.limit))- if (options?.prefix) params.set('prefix', options.prefix)-- const response = await fetchWithTimeout(`${ICONIFY_API}/search?${params}`)- if (!response.ok) throw new Error(`Iconify search error: ${response.status}`)- const data = await response.json()- const icons: string[] = data.icons ?? []- const limit = options?.limit ?? 5- return {- icons: icons.slice(0, limit),- total: data.total ?? 0,- collections: data.collections ?? {}- }+ return searchIconify(query, options)}export async function searchIconsBatch(diff --git a/packages/core/src/icons/render.ts b/packages/core/src/icons/render.tsindex db83a53f3..12ebbb7ce 100644--- a/packages/core/src/icons/render.ts+++ b/packages/core/src/icons/render.ts@@ -1,8 +1,8 @@-import { parseColor } from '../color'+import { parseColor } from '#core/color'-import type { SceneGraph, SceneNode, Stroke } from '../scene-graph'-import type { Color } from '../types'-import type { IconData } from './'+import type { SceneGraph, SceneNode, Stroke } from '#core/scene-graph'+import type { Color } from '#core/types'+import type { IconData } from './types'const STROKE_CAP_MAP: Record<string, SceneNode['strokeCap']> = {butt: 'NONE',diff --git a/packages/core/src/icons/svg.ts b/packages/core/src/icons/svg.tsnew file mode 100644index 000000000..8797d1dca--- /dev/null+++ b/packages/core/src/icons/svg.ts@@ -0,0 +1,166 @@+import { iconToSVG } from '@iconify/utils'+import svgpath from 'svgpath'++import { parseSVGPath } from '#core/io/formats/svg/parse-path'++import type { IconData, IconifyIconEntry, IconPathInfo } from './types'++function attrValue(tag: string, attr: string): string | null {+ const re = new RegExp(`\\b${attr}="([^"]*)"`)+ const match = tag.match(re)+ return match ? match[1] : null+}++function num(tag: string, attr: string, fallback = 0): number {+ const value = attrValue(tag, attr)+ return value !== null ? parseFloat(value) : fallback+}++function shapeToD(tagName: string, tag: string): string | null {+ switch (tagName) {+ case 'circle': {+ const cx = num(tag, 'cx'),+ cy = num(tag, 'cy'),+ r = num(tag, 'r')+ return r > 0+ ? `M${cx - r},${cy}A${r},${r},0,1,0,${cx + r},${cy}A${r},${r},0,1,0,${cx - r},${cy}Z`+ : null+ }+ case 'ellipse': {+ const cx = num(tag, 'cx'),+ cy = num(tag, 'cy'),+ rx = num(tag, 'rx'),+ ry = num(tag, 'ry')+ return rx > 0 && ry > 0+ ? `M${cx - rx},${cy}A${rx},${ry},0,1,0,${cx + rx},${cy}A${rx},${ry},0,1,0,${cx - rx},${cy}Z`+ : null+ }+ case 'rect': {+ const x = num(tag, 'x'),+ y = num(tag, 'y'),+ width = num(tag, 'width'),+ height = num(tag, 'height')+ if (width <= 0 || height <= 0) return null+ const rx = Math.min(num(tag, 'rx'), width / 2),+ ry = Math.min(num(tag, 'ry', rx), height / 2)+ if (rx > 0 || ry > 0) {+ const arx = rx || ry,+ ary = ry || rx+ return `M${x + arx},${y}H${x + width - arx}A${arx},${ary},0,0,1,${x + width},${y + ary}V${y + height - ary}A${arx},${ary},0,0,1,${x + width - arx},${y + height}H${x + arx}A${arx},${ary},0,0,1,${x},${y + height - ary}V${y + ary}A${arx},${ary},0,0,1,${x + arx},${y}Z`+ }+ return `M${x},${y}H${x + width}V${y + height}H${x}Z`+ }+ case 'line': {+ const x1 = num(tag, 'x1'),+ y1 = num(tag, 'y1'),+ x2 = num(tag, 'x2'),+ y2 = num(tag, 'y2')+ return `M${x1},${y1}L${x2},${y2}`+ }+ case 'polygon':+ case 'polyline': {+ const points = attrValue(tag, 'points')+ if (!points) return null+ const values = points.trim().split(/[\s,]+/).map(Number)+ if (values.length < 4) return null+ let d = `M${values[0]},${values[1]}`+ for (let i = 2; i < values.length; i += 2) d += `L${values[i]},${values[i + 1]}`+ if (tagName === 'polygon') d += 'Z'+ return d+ }+ default:+ return null+ }+}++function resolveAttr(+ explicit: string | null,+ group: string | null,+ fallback: string | null+): string | null {+ if (explicit !== null) return explicit === 'none' ? null : explicit+ if (group !== null) return group === 'none' ? null : group+ return fallback+}++function extractPaths(svgBody: string): IconPathInfo[] {+ const groupAttrs = {+ fill: null as string | null,+ stroke: null as string | null,+ strokeWidth: null as string | null,+ strokeCap: null as string | null,+ strokeJoin: null as string | null,+ }+ const groupRe = /<g\b[^>]*>/g+ let groupMatch+ while ((groupMatch = groupRe.exec(svgBody)) !== null) {+ groupAttrs.fill ??= attrValue(groupMatch[0], 'fill')+ groupAttrs.stroke ??= attrValue(groupMatch[0], 'stroke')+ groupAttrs.strokeWidth ??= attrValue(groupMatch[0], 'stroke-width')+ groupAttrs.strokeCap ??= attrValue(groupMatch[0], 'stroke-linecap')+ groupAttrs.strokeJoin ??= attrValue(groupMatch[0], 'stroke-linejoin')+ }++ const result: IconPathInfo[] = []+ const shapeRe = /<(path|circle|ellipse|rect|line|polygon|polyline)\b[^>]*>/g+ let match+ while ((match = shapeRe.exec(svgBody)) !== null) {+ const tag = match[0],+ tagName = match[1]+ const d = tagName === 'path' ? attrValue(tag, 'd') : shapeToD(tagName, tag)+ if (!d) continue++ const fillRuleAttr = attrValue(tag, 'fill-rule')+ result.push({+ d,+ fill: resolveAttr(attrValue(tag, 'fill'), groupAttrs.fill, 'currentColor'),+ stroke: resolveAttr(attrValue(tag, 'stroke'), groupAttrs.stroke, null),+ strokeWidth: parseFloat(attrValue(tag, 'stroke-width') ?? groupAttrs.strokeWidth ?? '1'),+ strokeCap: attrValue(tag, 'stroke-linecap') ?? groupAttrs.strokeCap ?? 'butt',+ strokeJoin: attrValue(tag, 'stroke-linejoin') ?? groupAttrs.strokeJoin ?? 'miter',+ fillRule: fillRuleAttr === 'evenodd' ? 'EVENODD' : 'NONZERO',+ })+ }+ return result+}++export function buildIconData(+ iconEntry: IconifyIconEntry,+ prefix: string,+ iconName: string,+ defaultW: number,+ defaultH: number,+ size: number+): IconData {+ const rendered = iconToSVG({+ body: iconEntry.body,+ width: iconEntry.width ?? defaultW,+ height: iconEntry.height ?? defaultH,+ })+ const [, , viewBoxWidth, viewBoxHeight] = rendered.viewBox+ const scaleX = size / viewBoxWidth+ const scaleY = size / viewBoxHeight++ const pathInfos = extractPaths(rendered.body)++ return {+ prefix,+ name: iconName,+ width: size,+ height: size,+ paths: pathInfos.map((path) => {+ const scaledD =+ scaleX === 1 && scaleY === 1+ ? path.d+ : svgpath(path.d).scale(scaleX, scaleY).round(2).toString()+ return {+ vectorNetwork: parseSVGPath(scaledD, path.fillRule),+ fill: path.fill,+ stroke: path.stroke,+ strokeWidth: path.strokeWidth * Math.min(scaleX, scaleY),+ strokeCap: path.strokeCap,+ strokeJoin: path.strokeJoin,+ }+ }),+ }+}diff --git a/packages/core/src/icons/types.ts b/packages/core/src/icons/types.tsnew file mode 100644index 000000000..3ed0e0244--- /dev/null+++ b/packages/core/src/icons/types.ts@@ -0,0 +1,48 @@+import type { VectorNetwork, WindingRule } from '#core/scene-graph'++export interface IconPath {+ vectorNetwork: VectorNetwork+ fill: string | null+ stroke: string | null+ strokeWidth: number+ strokeCap: string+ strokeJoin: string+}++export interface IconData {+ prefix: string+ name: string+ width: number+ height: number+ paths: IconPath[]+}++export interface IconifyIconEntry {+ body: string+ width?: number+ height?: number+}++export interface IconifyResponse {+ prefix: string+ width?: number+ height?: number+ icons: { [key: string]: IconifyIconEntry | undefined }+ aliases?: { [key: string]: { parent: string } | undefined }+}++export interface IconSearchResult {+ icons: string[]+ total: number+ collections: Record<string, { name: string; total: number; category?: string }>+}++export interface IconPathInfo {+ d: string+ fill: string | null+ stroke: string | null+ strokeWidth: number+ strokeCap: string+ strokeJoin: string+ fillRule: WindingRule+}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 0cdd5a951..14bd9e7b5 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -140,7 +140,7 @@ export type {TypographyStyle} from './rpc'export { SkiaRenderer, type RenderOverlays } from './canvas'-export { LabelCache, type CachedSection, type CachedComponent } from './canvas/label-cache'+export { LabelCache, type CachedSection, type CachedComponent } from './canvas/labels/cache'export {RenderProfiler,FrameStats,@@ -243,7 +243,7 @@ export {type NetworkNearestResult} from './vector/bezier'export { computeSelectionBounds, computeSnap, type SnapGuide } from './scene-graph/snap'-export { UndoManager, type UndoEntry } from './scene-graph/undo'+export { UndoManager, type UndoEntry, type UndoManagerOptions } from './scene-graph/undo'export { TextEditor, type TextCaret, type TextEditorState } from './text/editor'export {getStyleAt,@@ -295,7 +295,7 @@ export {sceneNodeToKiwi,fractionalPosition,mapToFigmaType-} from './kiwi/serialize'+} from './kiwi/node-change/serialize'export { buildDerivedTextDataV4 } from './text/clipboard-derived-text'export {diff --git a/packages/core/src/io/formats.ts b/packages/core/src/io/formats.tsindex b6db8e55f..f471859ae 100644--- a/packages/core/src/io/formats.ts+++ b/packages/core/src/io/formats.ts@@ -1,9 +1,9 @@-import { sceneNodeToJSX, selectionToJSX } from '../design-jsx'+import { sceneNodeToJSX, selectionToJSX } from '#core/design-jsx'import { exportFigFile, parseFigFile } from './formats/fig'import { parsePenFile } from './formats/pen'import { headlessRenderNodes, renderNodesToImage, type RasterExportFormat } from './formats/raster'import { renderNodesToSVG } from './formats/svg'-import { extractExportGraph } from './subgraph'+import { extractExportGraph, findPageId } from './subgraph'import type {ExportRequest,@@ -27,17 +27,6 @@ function ensureSingleNode(target: ExportRequest['target']): string | null {return null}-function findPageId(graph: ExportRequest['graph'], nodeId: string): string | null {- let current = graph.getNode(nodeId)- while (current?.parentId) {- const parent = graph.getNode(current.parentId)- if (!parent) return null- if (parent.type === 'CANVAS') return parent.id- current = parent- }- return current?.type === 'CANVAS' ? current.id : null-}-function resolveExportNodes(request: ExportRequest): { pageId: string; nodeIds: string[] } | null {switch (request.target.scope) {case 'document': {diff --git a/packages/core/src/io/formats/fig/compress.ts b/packages/core/src/io/formats/fig/compress.tsindex 7478ebf03..fb7ba260a 100644--- a/packages/core/src/io/formats/fig/compress.ts+++ b/packages/core/src/io/formats/fig/compress.ts@@ -1,7 +1,6 @@+import { buildFigKiwi } from '#core/kiwi/node-change/serialize'import { zipSync, type Zippable } from 'fflate'-import { buildFigKiwi } from '../../../kiwi/serialize'-export function compressFigDataSync(schemaDeflated: Uint8Array,kiwiData: Uint8Array,diff --git a/packages/core/src/io/formats/fig/export.ts b/packages/core/src/io/formats/fig/export.tsindex 25d0a7010..1050f151d 100644--- a/packages/core/src/io/formats/fig/export.ts+++ b/packages/core/src/io/formats/fig/export.ts@@ -1,8 +1,7 @@-import { deflateSync } from 'fflate'--import { CANVAS_BG_COLOR, IS_BROWSER, IS_TAURI } from '../../../constants'-import { initCodec, getCompiledSchema, getSchemaBytes } from '../../../kiwi/codec'-import { stringToGuid } from '../../../kiwi/convert'+import { CANVAS_BG_COLOR, IS_BROWSER, IS_TAURI } from '#core/constants'+import { renderThumbnail } from '#core/io/formats/raster'+import { initCodec, getCompiledSchema, getSchemaBytes } from '#core/kiwi/binary/codec'+import { stringToGuid } from '#core/kiwi/node-change/convert'import {sceneNodeToKiwi,fractionalPosition,@@ -10,14 +9,15 @@ import {safeColor,makeDocumentNodeChange,makeCanvasNodeChange-} from '../../../kiwi/serialize'-import { renderThumbnail } from '../raster'+} from '#core/kiwi/node-change/serialize'+import { deflateSync } from 'fflate'+import { compressFigDataSync } from './compress'-import type { SkiaRenderer } from '../../../canvas'-import type { NodeChange } from '../../../kiwi/codec'-import type { SceneGraph, VariableValue } from '../../../scene-graph'-import type { GUID } from '../../../types'+import type { SkiaRenderer } from '#core/canvas'+import type { NodeChange } from '#core/kiwi/binary/codec'+import type { SceneGraph, VariableValue } from '#core/scene-graph'+import type { GUID } from '#core/types'import type { CanvasKit } from 'canvaskit-wasm'const THUMBNAIL_1X1 = Uint8Array.from(diff --git a/packages/core/src/io/formats/fig/read.ts b/packages/core/src/io/formats/fig/read.tsindex 05b9ceb55..85ca2dfea 100644--- a/packages/core/src/io/formats/fig/read.ts+++ b/packages/core/src/io/formats/fig/read.ts@@ -1,10 +1,10 @@-import { IS_BROWSER } from '../../../constants'-import { importNodeChanges } from '../../../kiwi/fig-import'-import { parseFigBuffer } from '../../../kiwi/fig-parse-core'-import { deserializeSceneGraph } from '../../../kiwi/graph-transfer'+import { IS_BROWSER } from '#core/constants'+import { importNodeChanges } from '#core/kiwi/fig/import'+import { parseFigBuffer } from '#core/kiwi/fig/parse/core'+import { deserializeSceneGraph } from '#core/kiwi/fig/parse/transfer'-import type { SerializedSceneGraph } from '../../../kiwi/graph-transfer'-import type { SceneGraph } from '../../../scene-graph'+import type { SerializedSceneGraph } from '#core/kiwi/fig/parse/transfer'+import type { SceneGraph } from '#core/scene-graph'export interface ParseFigFileOptions {populate?: 'all' | 'first-page'@@ -24,7 +24,7 @@ interface WorkerParseResult {function parseViaWorker(buffer: ArrayBuffer, options: ParseFigFileOptions): Promise<SceneGraph> {return new Promise((resolve, reject) => {- const worker = new Worker(new URL('../../../kiwi/fig-parse-worker.ts', import.meta.url), {+ const worker = new Worker(new URL('../../../kiwi/fig/parse/worker.ts', import.meta.url), {type: 'module'})diff --git a/packages/core/src/io/formats/jsx/export.ts b/packages/core/src/io/formats/jsx/export.tsindex 6c0e73973..dc54ddb5e 100644--- a/packages/core/src/io/formats/jsx/export.ts+++ b/packages/core/src/io/formats/jsx/export.ts@@ -1,26 +1,20 @@-/* eslint-disable max-lines -- JSX export formats share helpers and node walking logic */-import { colorToHex8, colorToCSSCompact } from '../../../color'-import { DEFAULT_FONT_FAMILY } from '../../../constants'+import { DEFAULT_FONT_FAMILY } from '#core/constants'+import { resolveNodeTextDirection } from '#core/text/direction'+import { collectTailwindClasses } from './tailwind-classes'import {- pxToSpacing,- colorToTwClass,- fontSizeToTw,- fontWeightToTw,- borderRadiusToTw,- opacityToTw-} from '../../../design-jsx/tailwind'-import { resolveNodeTextDirection } from '../../../text/direction'--import type {- SceneGraph,- SceneNode,- Fill,- Stroke,- Effect,- NodeType,- Color,- GridTrack-} from '../../../scene-graph'+ collectCornerRadii,+ collectPadding,+ emitPadding,+ escapeJSXText,+ formatProp,+ formatShadow,+ formatTracks,+ getNodeContext,+ solidFillColor,+ solidStroke+} from './helpers'++import type { SceneGraph, SceneNode, NodeType } from '#core/scene-graph'export type JSXFormat = 'openpencil' | 'tailwind'@@ -58,132 +52,6 @@ const NODE_TYPE_TO_TW_TAG: Partial<Record<NodeType, string>> = {INSTANCE: 'div'}-function formatColor(color: Color, opacity = 1): string {- return colorToHex8(color, opacity)-}--function solidFillColor(fills: Fill[]): string | null {- const visible = fills.filter((f) => f.visible && f.type === 'SOLID')- if (visible.length !== 1) return null- return formatColor(visible[0].color, visible[0].opacity)-}--function solidStroke(strokes: Stroke[]): { color: string; weight: number } | null {- const visible = strokes.filter((s) => s.visible)- if (visible.length !== 1) return null- return {- color: formatColor(visible[0].color, visible[0].opacity),- weight: visible[0].weight- }-}--function formatShadow(e: Effect): string | null {- if (e.type !== 'DROP_SHADOW' && e.type !== 'INNER_SHADOW') return null- return `${e.offset.x} ${e.offset.y} ${e.radius} ${formatColor(e.color, e.color.a)}`-}--function formatTailwindShadow(e: Effect): string | null {- if (e.type !== 'DROP_SHADOW' && e.type !== 'INNER_SHADOW') return null- const color = colorToCSSCompact(e.color)- const inset = e.type === 'INNER_SHADOW' ? 'inset_' : ''- const spread = e.spread !== 0 ? `_${e.spread}px` : ''- return `${inset}${e.offset.x}px_${e.offset.y}px_${e.radius}px${spread}_${color}`-}--function formatTailwindAngle(degrees: number): string {- const rounded = Number(degrees.toFixed(2))- const integer = Math.round(rounded)- const named = new Set([0, 1, 2, 3, 6, 12, 45, 90, 180])- if (rounded === integer && named.has(integer)) return String(integer)- return `[${rounded}deg]`-}--function formatTailwindFontFamily(fontFamily: string): string {- const escaped = fontFamily.replace(/\\/g, '\\\\').replace(/'/g, "\\'")- return `['${escaped}']`-}--const JSX_ENTITY: Record<string, string> = {- '{': '{',- '}': '}',- '<': '<',- '>': '>',- '&': '&'-}--function escapeJSXText(text: string): string {- return text.replace(/[{}<>&]/g, (c) => JSX_ENTITY[c])-}--function formatProp(key: string, value: unknown): string {- if (typeof value === 'string') return `${key}="${value}"`- if (typeof value === 'number') return `${key}={${value}}`- if (typeof value === 'boolean') return value ? key : `${key}={false}`- return `${key}={${JSON.stringify(value)}}`-}--function getNodeContext(node: SceneNode, graph: SceneGraph) {- const parent = node.parentId ? graph.getNode(node.parentId) : null- return {- isAutoLayout: node.layoutMode !== 'NONE',- isGrid: node.layoutMode === 'GRID',- isFlex: node.layoutMode === 'HORIZONTAL' || node.layoutMode === 'VERTICAL',- parentIsAutoLayout: parent ? parent.layoutMode !== 'NONE' : false,- parentIsGrid: parent ? parent.layoutMode === 'GRID' : false- }-}--type PaddingEdges = { pt: number; pr: number; pb: number; pl: number }--function collectPadding(node: SceneNode): PaddingEdges | null {- const { paddingTop: pt, paddingRight: pr, paddingBottom: pb, paddingLeft: pl } = node- if (pt === 0 && pr === 0 && pb === 0 && pl === 0) return null- return { pt, pr, pb, pl }-}--function emitPadding<T>(- edges: PaddingEdges,- uniform: (v: number) => T,- symmetric: (y: number, x: number) => T[],- individual: (edges: PaddingEdges) => T[]-): T[] {- const { pt, pr, pb, pl } = edges- if (pt === pr && pr === pb && pb === pl) return [uniform(pt)]- if (pt === pb && pl === pr) return symmetric(pt, pl)- return individual(edges)-}--interface CornerRadii {- tl: number- tr: number- br: number- bl: number-}--function collectCornerRadii(node: SceneNode): CornerRadii | null {- if (node.cornerRadius <= 0) return null- if (node.independentCorners) {- return {- tl: node.topLeftRadius,- tr: node.topRightRadius,- br: node.bottomRightRadius,- bl: node.bottomLeftRadius- }- }- const r = node.cornerRadius- return { tl: r, tr: r, br: r, bl: r }-}--function formatTrack(t: GridTrack): string {- if (t.sizing === 'FR') return `${t.value}fr`- if (t.sizing === 'FIXED') return `${t.value}px`- return 'auto'-}--function formatTracks(tracks: GridTrack[]): string {- return tracks.map(formatTrack).join(' ')-}-// --- OpenPencil format helpers ---function collectGridSizingProps(node: SceneNode, props: [string, unknown][]): void {@@ -426,176 +294,6 @@ function collectProps(node: SceneNode, graph: SceneGraph): [string, unknown][] {return props}-// --- Tailwind CSS v4 format helpers -----function twRounded(prefix: string, px: number): string {- const r = borderRadiusToTw(px)- return r ? `${prefix}-${r}` : prefix-}--function gridTemplateTw(tracks: GridTrack[]): string {- const allEqual1Fr = tracks.every((t) => t.sizing === 'FR' && t.value === 1)- if (allEqual1Fr) return String(tracks.length)- return `[${tracks.map(formatTrack).join('_')}]`-}--function collectTwGridClasses(node: SceneNode, classes: string[]): void {- classes.push('grid')- if (node.gridTemplateColumns.length > 0)- classes.push(`grid-cols-${gridTemplateTw(node.gridTemplateColumns)}`)- if (node.gridTemplateRows.length > 0)- classes.push(`grid-rows-${gridTemplateTw(node.gridTemplateRows)}`)- if (node.width > 0) classes.push(`w-${pxToSpacing(node.width)}`)- if (node.gridTemplateRows.length > 0 && node.height > 0)- classes.push(`h-${pxToSpacing(node.height)}`)- if (node.gridColumnGap > 0) classes.push(`gap-x-${pxToSpacing(node.gridColumnGap)}`)- if (node.gridRowGap > 0) classes.push(`gap-y-${pxToSpacing(node.gridRowGap)}`)-}--function collectTwFlexSizingClasses(node: SceneNode, classes: string[]): void {- classes.push('flex')- if (node.layoutDirection === 'RTL') classes.push('[direction:rtl]')- if (node.layoutMode === 'VERTICAL') classes.push('flex-col')-- const primaryAxis = node.layoutMode === 'HORIZONTAL' ? 'width' : 'height'- const crossAxis = node.layoutMode === 'HORIZONTAL' ? 'height' : 'width'- const wProp = primaryAxis === 'width' ? 'w' : 'h'- const hProp = crossAxis === 'width' ? 'w' : 'h'-- if (node.primaryAxisSizing === 'FILL') classes.push(`${wProp}-full`)- else if (node.primaryAxisSizing !== 'HUG')- classes.push(`${wProp}-${pxToSpacing(node[primaryAxis])}`)-- if (node.counterAxisSizing === 'FILL') classes.push(`${hProp}-full`)- else if (node.counterAxisSizing !== 'HUG')- classes.push(`${hProp}-${pxToSpacing(node[crossAxis])}`)-}--function collectTwGridPositionClasses(node: SceneNode, classes: string[]): void {- if (!node.gridPosition) return- const pos = node.gridPosition- if (pos.column > 0) classes.push(`col-start-${pos.column}`)- if (pos.row > 0) classes.push(`row-start-${pos.row}`)- if (pos.columnSpan > 1) classes.push(`col-span-${pos.columnSpan}`)- if (pos.rowSpan > 1) classes.push(`row-span-${pos.rowSpan}`)-}--function collectTwFlexAlignmentClasses(node: SceneNode, classes: string[]): void {- if (node.itemSpacing > 0) classes.push(`gap-${pxToSpacing(node.itemSpacing)}`)-- if (node.layoutWrap === 'WRAP') {- classes.push('flex-wrap')- if (node.counterAxisSpacing > 0) classes.push(`gap-y-${pxToSpacing(node.counterAxisSpacing)}`)- }-- if (node.primaryAxisAlign === 'CENTER') classes.push('justify-center')- else if (node.primaryAxisAlign === 'MAX') classes.push('justify-end')- else if (node.primaryAxisAlign === 'SPACE_BETWEEN') classes.push('justify-between')-- if (node.counterAxisAlign === 'CENTER') classes.push('items-center')- else if (node.counterAxisAlign === 'MAX') classes.push('items-end')- else if (node.counterAxisAlign === 'STRETCH') classes.push('items-stretch')-}--function collectTwPaddingClasses(node: SceneNode, classes: string[]): void {- const pad = collectPadding(node)- if (!pad) return- classes.push(- ...emitPadding(- pad,- (v) => `p-${pxToSpacing(v)}`,- (y, x) => [`py-${pxToSpacing(y)}`, `px-${pxToSpacing(x)}`],- ({ pt, pr, pb, pl }) => {- const r: string[] = []- if (pt > 0) r.push(`pt-${pxToSpacing(pt)}`)- if (pr > 0) r.push(`pr-${pxToSpacing(pr)}`)- if (pb > 0) r.push(`pb-${pxToSpacing(pb)}`)- if (pl > 0) r.push(`pl-${pxToSpacing(pl)}`)- return r- }- )- )-}--function collectTwCornerRadiiClasses(node: SceneNode, classes: string[]): void {- const corners = collectCornerRadii(node)- if (!corners) return- const { tl, tr, br, bl } = corners- if (tl === tr && tr === br && br === bl) {- classes.push(twRounded('rounded', tl))- } else {- if (tl > 0) classes.push(twRounded('rounded-tl', tl))- if (tr > 0) classes.push(twRounded('rounded-tr', tr))- if (br > 0) classes.push(twRounded('rounded-br', br))- if (bl > 0) classes.push(twRounded('rounded-bl', bl))- }-}--function collectTwAppearanceClasses(node: SceneNode, classes: string[]): void {- const bg = solidFillColor(node.fills)- if (bg && node.type !== 'TEXT') classes.push(`bg-${colorToTwClass(bg)}`)-- const stroke = solidStroke(node.strokes)- if (stroke) {- if (stroke.weight !== 1) classes.push(`border-${pxToSpacing(stroke.weight)}`)- else classes.push('border')- classes.push(`border-${colorToTwClass(stroke.color)}`)- }-- collectTwCornerRadiiClasses(node, classes)-- if (node.opacity < 1) classes.push(`opacity-${opacityToTw(node.opacity)}`)- if (node.rotation !== 0) classes.push(`rotate-${formatTailwindAngle(node.rotation)}`)- if (node.clipsContent) classes.push('overflow-hidden')-- for (const effect of node.effects) {- if (!effect.visible) continue- if (effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW') {- const shadow = formatTailwindShadow(effect)- if (shadow) classes.push(`shadow-[${shadow}]`)- } else if (effect.type === 'LAYER_BLUR' || effect.type === 'FOREGROUND_BLUR') {- classes.push(`blur-[${effect.radius}px]`)- } else {- classes.push(`backdrop-blur-[${effect.radius}px]`)- }- }-}--function collectTwTextClasses(node: SceneNode, classes: string[]): void {- classes.push(`text-${fontSizeToTw(node.fontSize)}`)- if (resolveNodeTextDirection(node) === 'RTL') classes.push('[direction:rtl]')- if (node.fontFamily && node.fontFamily !== DEFAULT_FONT_FAMILY) {- classes.push(`font-${formatTailwindFontFamily(node.fontFamily)}`)- }- if (node.fontWeight !== 400) classes.push(`font-${fontWeightToTw(node.fontWeight)}`)- if (node.textAlignHorizontal !== 'LEFT') {- classes.push(`text-${node.textAlignHorizontal.toLowerCase()}`)- }- const textColor = solidFillColor(node.fills)- if (textColor) classes.push(`text-${colorToTwClass(textColor)}`)-}--function collectTailwindClasses(node: SceneNode, graph: SceneGraph): string[] {- const classes: string[] = []- const ctx = getNodeContext(node, graph)-- if (ctx.isGrid) collectTwGridClasses(node, classes)- else if (ctx.isFlex) collectTwFlexSizingClasses(node, classes)- else {- if (node.width > 0) classes.push(`w-${pxToSpacing(node.width)}`)- if (node.height > 0) classes.push(`h-${pxToSpacing(node.height)}`)- }-- if (ctx.parentIsAutoLayout && node.layoutGrow > 0) classes.push('grow')- if (ctx.parentIsGrid) collectTwGridPositionClasses(node, classes)- if (ctx.isFlex) collectTwFlexAlignmentClasses(node, classes)- if (ctx.isAutoLayout) collectTwPaddingClasses(node, classes)- collectTwAppearanceClasses(node, classes)- if (node.type === 'TEXT') collectTwTextClasses(node, classes)-- return classes-}-// --- JSX rendering ---function nodeToJSX(node: SceneNode, graph: SceneGraph, indent: number, format: JSXFormat): string {diff --git a/packages/core/src/io/formats/jsx/helpers.ts b/packages/core/src/io/formats/jsx/helpers.tsnew file mode 100644index 000000000..91688261e--- /dev/null+++ b/packages/core/src/io/formats/jsx/helpers.ts@@ -0,0 +1,130 @@+import { colorToHex8, colorToCSSCompact } from '#core/color'++import type { SceneGraph, SceneNode, Fill, Stroke, Effect, Color, GridTrack } from '#core/scene-graph'++export function formatColor(color: Color, opacity = 1): string {+ return colorToHex8(color, opacity)+}++export function solidFillColor(fills: Fill[]): string | null {+ const visible = fills.filter((f) => f.visible && f.type === 'SOLID')+ if (visible.length !== 1) return null+ return formatColor(visible[0].color, visible[0].opacity)+}++export function solidStroke(strokes: Stroke[]): { color: string; weight: number } | null {+ const visible = strokes.filter((s) => s.visible)+ if (visible.length !== 1) return null+ return {+ color: formatColor(visible[0].color, visible[0].opacity),+ weight: visible[0].weight+ }+}++export function formatShadow(e: Effect): string | null {+ if (e.type !== 'DROP_SHADOW' && e.type !== 'INNER_SHADOW') return null+ return `${e.offset.x} ${e.offset.y} ${e.radius} ${formatColor(e.color, e.color.a)}`+}++export function formatTailwindShadow(e: Effect): string | null {+ if (e.type !== 'DROP_SHADOW' && e.type !== 'INNER_SHADOW') return null+ const color = colorToCSSCompact(e.color)+ const inset = e.type === 'INNER_SHADOW' ? 'inset_' : ''+ const spread = e.spread !== 0 ? `_${e.spread}px` : ''+ return `${inset}${e.offset.x}px_${e.offset.y}px_${e.radius}px${spread}_${color}`+}++export function formatTailwindAngle(degrees: number): string {+ const rounded = Number(degrees.toFixed(2))+ const integer = Math.round(rounded)+ const named = new Set([0, 1, 2, 3, 6, 12, 45, 90, 180])+ if (rounded === integer && named.has(integer)) return String(integer)+ return `[${rounded}deg]`+}++export function formatTailwindFontFamily(fontFamily: string): string {+ const escaped = fontFamily.replace(/\\/g, '\\\\').replace(/'/g, "\\'")+ return `['${escaped}']`+}++const JSX_ENTITY: Record<string, string> = {+ '{': '{',+ '}': '}',+ '<': '<',+ '>': '>',+ '&': '&'+}++export function escapeJSXText(text: string): string {+ return text.replace(/[{}<>&]/g, (c) => JSX_ENTITY[c])+}++export function formatProp(key: string, value: unknown): string {+ if (typeof value === 'string') return `${key}="${value}"`+ if (typeof value === 'number') return `${key}={${value}}`+ if (typeof value === 'boolean') return value ? key : `${key}={false}`+ return `${key}={${JSON.stringify(value)}}`+}++export function getNodeContext(node: SceneNode, graph: SceneGraph) {+ const parent = node.parentId ? graph.getNode(node.parentId) : null+ return {+ isAutoLayout: node.layoutMode !== 'NONE',+ isGrid: node.layoutMode === 'GRID',+ isFlex: node.layoutMode === 'HORIZONTAL' || node.layoutMode === 'VERTICAL',+ parentIsAutoLayout: parent ? parent.layoutMode !== 'NONE' : false,+ parentIsGrid: parent ? parent.layoutMode === 'GRID' : false+ }+}++export type PaddingEdges = { pt: number; pr: number; pb: number; pl: number }++export function collectPadding(node: SceneNode): PaddingEdges | null {+ const { paddingTop: pt, paddingRight: pr, paddingBottom: pb, paddingLeft: pl } = node+ if (pt === 0 && pr === 0 && pb === 0 && pl === 0) return null+ return { pt, pr, pb, pl }+}++export function emitPadding<T>(+ edges: PaddingEdges,+ uniform: (v: number) => T,+ symmetric: (y: number, x: number) => T[],+ individual: (edges: PaddingEdges) => T[]+): T[] {+ const { pt, pr, pb, pl } = edges+ if (pt === pr && pr === pb && pb === pl) return [uniform(pt)]+ if (pt === pb && pl === pr) return symmetric(pt, pl)+ return individual(edges)+}++export interface CornerRadii {+ tl: number+ tr: number+ br: number+ bl: number+}++export function collectCornerRadii(node: SceneNode): CornerRadii | null {+ if (node.cornerRadius <= 0) return null+ if (node.independentCorners) {+ return {+ tl: node.topLeftRadius,+ tr: node.topRightRadius,+ br: node.bottomRightRadius,+ bl: node.bottomLeftRadius+ }+ }+ const r = node.cornerRadius+ return { tl: r, tr: r, br: r, bl: r }+}++export function formatTrack(t: GridTrack): string {+ if (t.sizing === 'FR') return `${t.value}fr`+ if (t.sizing === 'FIXED') return `${t.value}px`+ return 'auto'+}++export function formatTracks(tracks: GridTrack[]): string {+ return tracks.map(formatTrack).join(' ')+}+diff --git a/packages/core/src/io/formats/jsx/tailwind-classes.ts b/packages/core/src/io/formats/jsx/tailwind-classes.tsnew file mode 100644index 000000000..f3e658635--- /dev/null+++ b/packages/core/src/io/formats/jsx/tailwind-classes.ts@@ -0,0 +1,193 @@+import { DEFAULT_FONT_FAMILY } from '#core/constants'+import {+ pxToSpacing,+ colorToTwClass,+ fontSizeToTw,+ fontWeightToTw,+ borderRadiusToTw,+ opacityToTw+} from '#core/design-jsx/tailwind'+import { resolveNodeTextDirection } from '#core/text/direction'+import {+ collectCornerRadii,+ collectPadding,+ emitPadding,+ formatTailwindAngle,+ formatTailwindFontFamily,+ formatTailwindShadow,+ formatTrack,+ getNodeContext,+ solidFillColor,+ solidStroke+} from './helpers'++import type { GridTrack, SceneGraph, SceneNode } from '#core/scene-graph'++function twRounded(prefix: string, px: number): string {+ const r = borderRadiusToTw(px)+ return r ? `${prefix}-${r}` : prefix+}++function gridTemplateTw(tracks: GridTrack[]): string {+ const allEqual1Fr = tracks.every((t) => t.sizing === 'FR' && t.value === 1)+ if (allEqual1Fr) return String(tracks.length)+ return `[${tracks.map(formatTrack).join('_')}]`+}++function collectTwGridClasses(node: SceneNode, classes: string[]): void {+ classes.push('grid')+ if (node.gridTemplateColumns.length > 0)+ classes.push(`grid-cols-${gridTemplateTw(node.gridTemplateColumns)}`)+ if (node.gridTemplateRows.length > 0)+ classes.push(`grid-rows-${gridTemplateTw(node.gridTemplateRows)}`)+ if (node.width > 0) classes.push(`w-${pxToSpacing(node.width)}`)+ if (node.gridTemplateRows.length > 0 && node.height > 0)+ classes.push(`h-${pxToSpacing(node.height)}`)+ if (node.gridColumnGap > 0) classes.push(`gap-x-${pxToSpacing(node.gridColumnGap)}`)+ if (node.gridRowGap > 0) classes.push(`gap-y-${pxToSpacing(node.gridRowGap)}`)+}++function collectTwFlexSizingClasses(node: SceneNode, classes: string[]): void {+ classes.push('flex')+ if (node.layoutDirection === 'RTL') classes.push('[direction:rtl]')+ if (node.layoutMode === 'VERTICAL') classes.push('flex-col')++ const primaryAxis = node.layoutMode === 'HORIZONTAL' ? 'width' : 'height'+ const crossAxis = node.layoutMode === 'HORIZONTAL' ? 'height' : 'width'+ const wProp = primaryAxis === 'width' ? 'w' : 'h'+ const hProp = crossAxis === 'width' ? 'w' : 'h'++ if (node.primaryAxisSizing === 'FILL') classes.push(`${wProp}-full`)+ else if (node.primaryAxisSizing !== 'HUG')+ classes.push(`${wProp}-${pxToSpacing(node[primaryAxis])}`)++ if (node.counterAxisSizing === 'FILL') classes.push(`${hProp}-full`)+ else if (node.counterAxisSizing !== 'HUG')+ classes.push(`${hProp}-${pxToSpacing(node[crossAxis])}`)+}++function collectTwGridPositionClasses(node: SceneNode, classes: string[]): void {+ if (!node.gridPosition) return+ const pos = node.gridPosition+ if (pos.column > 0) classes.push(`col-start-${pos.column}`)+ if (pos.row > 0) classes.push(`row-start-${pos.row}`)+ if (pos.columnSpan > 1) classes.push(`col-span-${pos.columnSpan}`)+ if (pos.rowSpan > 1) classes.push(`row-span-${pos.rowSpan}`)+}++function collectTwFlexAlignmentClasses(node: SceneNode, classes: string[]): void {+ if (node.itemSpacing > 0) classes.push(`gap-${pxToSpacing(node.itemSpacing)}`)++ if (node.layoutWrap === 'WRAP') {+ classes.push('flex-wrap')+ if (node.counterAxisSpacing > 0) classes.push(`gap-y-${pxToSpacing(node.counterAxisSpacing)}`)+ }++ if (node.primaryAxisAlign === 'CENTER') classes.push('justify-center')+ else if (node.primaryAxisAlign === 'MAX') classes.push('justify-end')+ else if (node.primaryAxisAlign === 'SPACE_BETWEEN') classes.push('justify-between')++ if (node.counterAxisAlign === 'CENTER') classes.push('items-center')+ else if (node.counterAxisAlign === 'MAX') classes.push('items-end')+ else if (node.counterAxisAlign === 'STRETCH') classes.push('items-stretch')+}++function collectTwPaddingClasses(node: SceneNode, classes: string[]): void {+ const pad = collectPadding(node)+ if (!pad) return+ classes.push(+ ...emitPadding(+ pad,+ (v) => `p-${pxToSpacing(v)}`,+ (y, x) => [`py-${pxToSpacing(y)}`, `px-${pxToSpacing(x)}`],+ ({ pt, pr, pb, pl }) => {+ const r: string[] = []+ if (pt > 0) r.push(`pt-${pxToSpacing(pt)}`)+ if (pr > 0) r.push(`pr-${pxToSpacing(pr)}`)+ if (pb > 0) r.push(`pb-${pxToSpacing(pb)}`)+ if (pl > 0) r.push(`pl-${pxToSpacing(pl)}`)+ return r+ }+ )+ )+}++function collectTwCornerRadiiClasses(node: SceneNode, classes: string[]): void {+ const corners = collectCornerRadii(node)+ if (!corners) return+ const { tl, tr, br, bl } = corners+ if (tl === tr && tr === br && br === bl) {+ classes.push(twRounded('rounded', tl))+ } else {+ if (tl > 0) classes.push(twRounded('rounded-tl', tl))+ if (tr > 0) classes.push(twRounded('rounded-tr', tr))+ if (br > 0) classes.push(twRounded('rounded-br', br))+ if (bl > 0) classes.push(twRounded('rounded-bl', bl))+ }+}++function collectTwAppearanceClasses(node: SceneNode, classes: string[]): void {+ const bg = solidFillColor(node.fills)+ if (bg && node.type !== 'TEXT') classes.push(`bg-${colorToTwClass(bg)}`)++ const stroke = solidStroke(node.strokes)+ if (stroke) {+ if (stroke.weight !== 1) classes.push(`border-${pxToSpacing(stroke.weight)}`)+ else classes.push('border')+ classes.push(`border-${colorToTwClass(stroke.color)}`)+ }++ collectTwCornerRadiiClasses(node, classes)++ if (node.opacity < 1) classes.push(`opacity-${opacityToTw(node.opacity)}`)+ if (node.rotation !== 0) classes.push(`rotate-${formatTailwindAngle(node.rotation)}`)+ if (node.clipsContent) classes.push('overflow-hidden')++ for (const effect of node.effects) {+ if (!effect.visible) continue+ if (effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW') {+ const shadow = formatTailwindShadow(effect)+ if (shadow) classes.push(`shadow-[${shadow}]`)+ } else if (effect.type === 'LAYER_BLUR' || effect.type === 'FOREGROUND_BLUR') {+ classes.push(`blur-[${effect.radius}px]`)+ } else {+ classes.push(`backdrop-blur-[${effect.radius}px]`)+ }+ }+}++function collectTwTextClasses(node: SceneNode, classes: string[]): void {+ classes.push(`text-${fontSizeToTw(node.fontSize)}`)+ if (resolveNodeTextDirection(node) === 'RTL') classes.push('[direction:rtl]')+ if (node.fontFamily && node.fontFamily !== DEFAULT_FONT_FAMILY) {+ classes.push(`font-${formatTailwindFontFamily(node.fontFamily)}`)+ }+ if (node.fontWeight !== 400) classes.push(`font-${fontWeightToTw(node.fontWeight)}`)+ if (node.textAlignHorizontal !== 'LEFT') {+ classes.push(`text-${node.textAlignHorizontal.toLowerCase()}`)+ }+ const textColor = solidFillColor(node.fills)+ if (textColor) classes.push(`text-${colorToTwClass(textColor)}`)+}++export function collectTailwindClasses(node: SceneNode, graph: SceneGraph): string[] {+ const classes: string[] = []+ const ctx = getNodeContext(node, graph)++ if (ctx.isGrid) collectTwGridClasses(node, classes)+ else if (ctx.isFlex) collectTwFlexSizingClasses(node, classes)+ else {+ if (node.width > 0) classes.push(`w-${pxToSpacing(node.width)}`)+ if (node.height > 0) classes.push(`h-${pxToSpacing(node.height)}`)+ }++ if (ctx.parentIsAutoLayout && node.layoutGrow > 0) classes.push('grow')+ if (ctx.parentIsGrid) collectTwGridPositionClasses(node, classes)+ if (ctx.isFlex) collectTwFlexAlignmentClasses(node, classes)+ if (ctx.isAutoLayout) collectTwPaddingClasses(node, classes)+ collectTwAppearanceClasses(node, classes)+ if (node.type === 'TEXT') collectTwTextClasses(node, classes)++ return classes+}+diff --git a/packages/core/src/io/formats/pen/convert.ts b/packages/core/src/io/formats/pen/convert.tsindex 59678bbc2..927a78ea2 100644--- a/packages/core/src/io/formats/pen/convert.ts+++ b/packages/core/src/io/formats/pen/convert.ts@@ -1,5 +1,5 @@-import { parseColor } from '../../../color'-import { generateId } from '../../../scene-graph'+import { parseColor } from '#core/color'+import { generateId } from '#core/scene-graph'import type {Color,@@ -21,8 +21,8 @@ import type {VariableCollectionMode,VariableType,VariableValue-} from '../../../scene-graph'-import type { Vector } from '../../../types'+} from '#core/scene-graph'+import type { Vector } from '#core/types'export interface PenDocument {version: stringdiff --git a/packages/core/src/io/formats/pen/read.ts b/packages/core/src/io/formats/pen/read.tsindex 98dd16533..50e4cd3b8 100644--- a/packages/core/src/io/formats/pen/read.ts+++ b/packages/core/src/io/formats/pen/read.ts@@ -1,7 +1,7 @@-import { SceneGraph } from '../../../scene-graph'-import { copyEffects, copyFills, copyStrokes } from '../../../scene-graph/copy'-import { populateInstanceChildren } from '../../../scene-graph/instances'-import { parseSVGPath } from '../svg/parse-path'+import { SceneGraph } from '#core/scene-graph'+import { copyEffects, copyFills, copyStrokes } from '#core/scene-graph/copy'+import { populateInstanceChildren } from '#core/scene-graph/instances'+import { parseSVGPath } from '#core/io/formats/svg/parse-path'import {applyCornerRadius,applyPadding,@@ -24,7 +24,7 @@ import {type VarContext} from './convert'-import type { LayoutMode, LayoutSizing, SceneNode, VectorNetwork } from '../../../scene-graph'+import type { LayoutMode, LayoutSizing, SceneNode, VectorNetwork } from '#core/scene-graph'function scaleVectorNetwork(vn: VectorNetwork, targetW: number, targetH: number): void {if (vn.vertices.length === 0) returndiff --git a/packages/core/src/io/formats/raster/headless.ts b/packages/core/src/io/formats/raster/headless.tsindex a9d5444aa..9672ed608 100644--- a/packages/core/src/io/formats/raster/headless.ts+++ b/packages/core/src/io/formats/raster/headless.ts@@ -1,7 +1,7 @@-import { SkiaRenderer } from '../../../canvas'+import { SkiaRenderer } from '#core/canvas'import { renderNodesToImage, renderThumbnail, type ExportFormat } from './render'-import type { SceneGraph } from '../../../scene-graph'+import type { SceneGraph } from '#core/scene-graph'import type { CanvasKit } from 'canvaskit-wasm'let cachedCk: CanvasKit | null = nulldiff --git a/packages/core/src/io/formats/raster/render.ts b/packages/core/src/io/formats/raster/render.tsindex 27c1e8e6f..912d3a847 100644--- a/packages/core/src/io/formats/raster/render.ts+++ b/packages/core/src/io/formats/raster/render.ts@@ -1,9 +1,9 @@-import { computeDescendantVisualBounds } from '../../../geometry'-import { extractExportGraph } from '../../subgraph'+import { computeDescendantVisualBounds } from '#core/geometry'+import { extractExportGraph, findPageId } from '#core/io/subgraph'-import type { SkiaRenderer } from '../../../canvas'-import type { RenderColorSpace } from '../../../color/management'-import type { SceneGraph } from '../../../scene-graph'+import type { SkiaRenderer } from '#core/canvas'+import type { RenderColorSpace } from '#core/color/management'+import type { SceneGraph } from '#core/scene-graph'import type { CanvasKit, Canvas } from 'canvaskit-wasm'export type RasterExportFormat = 'PNG' | 'JPG' | 'WEBP'@@ -16,17 +16,6 @@ interface RenderOptions {colorSpace?: RenderColorSpace}-function findPageId(graph: SceneGraph, nodeId: string): string | null {- let current = graph.getNode(nodeId)- while (current?.parentId) {- const parent = graph.getNode(current.parentId)- if (!parent) return null- if (parent.type === 'CANVAS') return parent.id- current = parent- }- return current?.type === 'CANVAS' ? current.id : null-}-function ensureSinglePageSelection(graph: SceneGraph, pageId: string, nodeIds: string[]): boolean {return nodeIds.every((nodeId) => findPageId(graph, nodeId) === pageId)}diff --git a/packages/core/src/io/formats/svg/defs.ts b/packages/core/src/io/formats/svg/defs.tsindex 692f3f597..73db8c9d8 100644--- a/packages/core/src/io/formats/svg/defs.ts+++ b/packages/core/src/io/formats/svg/defs.ts@@ -1,11 +1,11 @@-import { colorToHex } from '../../../color'-import { colorToDisplayCss, getDefaultRenderColorSpace } from '../../../color/management'+import { colorToHex } from '#core/color'+import { colorToDisplayCss, getDefaultRenderColorSpace } from '#core/color/management'import { svg, type SVGNode } from './node'import { round } from './paths'-import type { RenderColorSpace } from '../../../color/management'-import type { Effect, Fill, SceneGraph, SceneNode } from '../../../scene-graph'-import type { Color } from '../../../types'+import type { RenderColorSpace } from '#core/color/management'+import type { Effect, Fill, SceneGraph, SceneNode } from '#core/scene-graph'+import type { Color } from '#core/types'export interface SVGExportContext {defs: SVGNode[]diff --git a/packages/core/src/io/formats/svg/export.ts b/packages/core/src/io/formats/svg/export.tsindex 8b3ca69f6..fd6111561 100644--- a/packages/core/src/io/formats/svg/export.ts+++ b/packages/core/src/io/formats/svg/export.ts@@ -1,5 +1,5 @@-import { resolveNodeTextDirection } from '../../../text/direction'-import { computeContentBounds } from '../raster'+import { resolveNodeTextDirection } from '#core/text/direction'+import { computeContentBounds } from '#core/io/formats/raster'import {nextDefId,formatColor,@@ -29,7 +29,7 @@ import type {Fill,Stroke,CharacterStyleOverride-} from '../../../scene-graph'+} from '#core/scene-graph'import type { SVGExportContext } from './defs'import type { SVGNode } from './node'diff --git a/packages/core/src/io/formats/svg/parse-path.ts b/packages/core/src/io/formats/svg/parse-path.tsindex dd73a294b..05caf52fc 100644--- a/packages/core/src/io/formats/svg/parse-path.ts+++ b/packages/core/src/io/formats/svg/parse-path.ts@@ -6,7 +6,7 @@ import type {VectorSegment,VectorRegion,WindingRule-} from '../../../scene-graph'+} from '#core/scene-graph'interface SubPath {startVertexIndex: numberdiff --git a/packages/core/src/io/formats/svg/paths.ts b/packages/core/src/io/formats/svg/paths.tsindex d4cb05901..ef452d9fa 100644--- a/packages/core/src/io/formats/svg/paths.ts+++ b/packages/core/src/io/formats/svg/paths.ts@@ -1,4 +1,6 @@-import type { SceneNode, VectorNetwork, VectorSegment, VectorVertex } from '../../../scene-graph'+import { polygonVertices } from '#core/geometry'++import type { SceneNode, VectorNetwork, VectorSegment, VectorVertex } from '#core/scene-graph'const CMD_CLOSE = 0const CMD_MOVE_TO = 1@@ -107,24 +109,9 @@ export function vectorNetworkToSVGPaths(network: VectorNetwork): string[] {}export function makePolygonPoints(node: SceneNode): string {- const cx = node.width / 2- const cy = node.height / 2- const rx = node.width / 2- const ry = node.height / 2- const n = Math.max(3, node.pointCount)- const isStar = node.type === 'STAR'- const innerRatio = isStar ? node.starInnerRadius : 1- const totalPoints = isStar ? n * 2 : n- const angleOffset = -Math.PI / 2-- const points: string[] = []- for (let i = 0; i < totalPoints; i++) {- const angle = angleOffset + (2 * Math.PI * i) / totalPoints- const isInner = isStar && i % 2 === 1- const r = isInner ? innerRatio : 1- points.push(`${round(cx + rx * r * Math.cos(angle))},${round(cy + ry * r * Math.sin(angle))}`)- }- return points.join(' ')+ return polygonVertices(node)+ .map((point) => `${round(point.x)},${round(point.y)}`)+ .join(' ')}export function hasRadius(node: SceneNode): boolean {diff --git a/packages/core/src/io/registry.ts b/packages/core/src/io/registry.tsindex edc9464f9..98a3eb584 100644--- a/packages/core/src/io/registry.ts+++ b/packages/core/src/io/registry.ts@@ -1,4 +1,4 @@-import type { SceneGraph } from '../scene-graph'+import type { SceneGraph } from '#core/scene-graph'import type { ExportRequest, IOContext, IOFormatAdapter, ReadDocumentInput } from './types'export class IORegistry {diff --git a/packages/core/src/io/subgraph.ts b/packages/core/src/io/subgraph.tsindex 71c339781..3f4e299e9 100644--- a/packages/core/src/io/subgraph.ts+++ b/packages/core/src/io/subgraph.ts@@ -1,4 +1,4 @@-import { SceneGraph } from '../scene-graph'+import { SceneGraph } from '#core/scene-graph'import type { ExportTarget } from './types'@@ -116,6 +116,17 @@ function collectDescendants(source: SceneGraph, id: string, out: Set<string>) {}}+export function findPageId(source: SceneGraph, nodeId: string): string | null {+ let current = source.getNode(nodeId)+ while (current?.parentId) {+ const parent = source.getNode(current.parentId)+ if (!parent) return null+ if (parent.type === 'CANVAS') return parent.id+ current = parent+ }+ return current?.type === 'CANVAS' ? current.id : null+}+function ancestorChain(source: SceneGraph, id: string): string[] {const chain: string[] = []let current = source.getNode(id)diff --git a/packages/core/src/io/types.ts b/packages/core/src/io/types.tsindex 49ec19788..c55ca8191 100644--- a/packages/core/src/io/types.ts+++ b/packages/core/src/io/types.ts@@ -1,7 +1,7 @@-import type { SkiaRenderer } from '../canvas'-import type { RenderColorSpace } from '../color/management'-import type { JSXFormat } from '../design-jsx'-import type { SceneGraph } from '../scene-graph'+import type { SkiaRenderer } from '#core/canvas'+import type { RenderColorSpace } from '#core/color/management'+import type { JSXFormat } from '#core/design-jsx'+import type { SceneGraph } from '#core/scene-graph'import type { RasterExportFormat } from './formats/raster'import type { CanvasKit } from 'canvaskit-wasm'diff --git a/packages/core/src/kiwi/codec.ts b/packages/core/src/kiwi/binary/codec.tssimilarity index 72%rename from packages/core/src/kiwi/codec.tsrename to packages/core/src/kiwi/binary/codec.tsindex ee734927d..e81eaa1bf 100644--- a/packages/core/src/kiwi/codec.ts+++ b/packages/core/src/kiwi/binary/codec.ts@@ -7,12 +7,13 @@* - fzstd: Browser-compatible Zstd decompression*/+import { parseColor } from '#core/color'+import { compileSchema, encodeBinarySchema } from '#core/kiwi/kiwi-schema'import { decompress as zstdDecompress } from 'fzstd'-import { parseColor } from '../color'-import { compileSchema, encodeBinarySchema } from './kiwi-schema'import { isZstdCompressed, getKiwiMessageType } from './protocol'import figmaSchema from './schema'+import * as VariableBindings from './variable-bindings'interface CompiledSchema {encodeMessage(message: unknown): Uint8Array@@ -122,7 +123,7 @@ export function encodeMessage(message: FigmaMessage): Uint8Array {// Build nodeChanges array with our encoded nodesconst ncBytes: number[] = [0x04] // field 4- ncBytes.push(...encodeVarint(nodeChangeBytes.length)) // array length+ ncBytes.push(...VariableBindings.encodeVarint(nodeChangeBytes.length)) // array lengthfor (const ncArr of nodeChangeBytes) {ncBytes.push(...Array.from(ncArr))}@@ -164,9 +165,9 @@ export function peekMessageType(data: Uint8Array): number | null {// Type definitions-export type { GUID, Color } from '../types'+export type { GUID, Color } from '#core/types'-import type { Color, GUID, Matrix, Vector } from '../types'+import type { Color, GUID, Matrix, Vector } from '#core/types'export type { Matrix, Vector }@@ -489,26 +490,6 @@ export function createNodeChange(opts: {/*** Encode a varint (variable-length integer)*/-function encodeVarint(value: number): number[] {- const bytes: number[] = []- while (value > 0x7f) {- bytes.push((value & 0x7f) | 0x80)- value >>>= 7- }- bytes.push(value)- return bytes-}--/**- * Encode a Paint with optional variable binding- *- * Figma's variable binding format (discovered via WS traffic analysis):- * - Field 21 = 1 (binding type)- * - Field 4 = 1 (flag)- * - Raw sessionID varint (no field number)- * - Raw localID varint (no field number)- * - Terminators: 00 00 02 03 03 04 00 00- */export function encodePaintWithVariableBinding(paint: Paint,variableSessionID: number,@@ -517,140 +498,19 @@ export function encodePaintWithVariableBinding(if (!compiledSchema) {throw new Error('Codec not initialized. Call initCodec() first.')}-- const { colorVariableBinding: _, ...basePaint } = paint-- const baseBytes = compiledSchema.encodePaint(basePaint)- const baseArray = Array.from(baseBytes)-- // Remove trailing 00- if (baseArray[baseArray.length - 1] === 0) {- baseArray.pop()- }-- // Add variable binding in Figma's exact format:- // Field 21 (0x15) = 1 (binding type)- baseArray.push(0x15, 0x01)- // Field 4 = 1 (flag)- baseArray.push(0x04, 0x01)- // Raw varints: sessionID, localID (no field numbers!)- baseArray.push(...encodeVarint(variableSessionID))- baseArray.push(...encodeVarint(variableLocalID))- // Terminators observed in Figma traffic- baseArray.push(0x00, 0x00, 0x02, 0x03, 0x03, 0x04)- // Final terminators- baseArray.push(0x00, 0x00)-- return new Uint8Array(baseArray)+ return VariableBindings.encodePaintWithVariableBinding(+ compiledSchema,+ paint,+ variableSessionID,+ variableLocalID+ )}-/**- * Parse a variable ID string (e.g., "VariableID:38448:122296")- * Returns sessionID and localID- */-export function parseVariableId(variableId: string): GUID | null {- const match = variableId.match(/VariableID:(\d+):(\d+)/)- if (!match) return null- return {- sessionID: parseInt(match[1] ?? '0', 10),- localID: parseInt(match[2] ?? '0', 10)- }-}+export { parseVariableId } from './variable-bindings'-/**- * Encode a NodeChange with variable bindings in fillPaints and/or strokePaints- * This is needed because kiwi-schema cannot produce Figma's exact variable binding format- */export function encodeNodeChangeWithVariables(nodeChange: NodeChange): Uint8Array {if (!compiledSchema) {throw new Error('Codec not initialized. Call initCodec() first.')}-- const hasFillBinding = nodeChange.fillPaints?.some((p) => p.colorVariableBinding)- const hasStrokeBinding = nodeChange.strokePaints?.some((p) => p.colorVariableBinding)-- if (!hasFillBinding && !hasStrokeBinding) {- return compiledSchema.encodeNodeChange(nodeChange)- }-- // Create a copy without variable bindings for base encoding- const cleanNodeChange = { ...nodeChange }- if (cleanNodeChange.fillPaints) {- cleanNodeChange.fillPaints = cleanNodeChange.fillPaints.map(- ({ colorVariableBinding: _, ...rest }) => rest- )- }- if (cleanNodeChange.strokePaints) {- cleanNodeChange.strokePaints = cleanNodeChange.strokePaints.map(- ({ colorVariableBinding: _, ...rest }) => rest- )- }-- // Encode clean version- const baseBytes = compiledSchema.encodeNodeChange(cleanNodeChange)- let hex = Buffer.from(baseBytes).toString('hex')-- // Inject fill variable binding (field 38 = 0x26)- const fillBinding = nodeChange.fillPaints?.[0]?.colorVariableBinding- if (hasFillBinding && fillBinding) {- hex = injectVariableBinding(hex, '2601', fillBinding)- }-- // Inject stroke variable binding (field 39 = 0x27)- const strokeBinding = nodeChange.strokePaints?.[0]?.colorVariableBinding- if (hasStrokeBinding && strokeBinding) {- hex = injectVariableBinding(hex, '2701', strokeBinding)- }-- return new Uint8Array(hex.match(/.{2}/g)?.map((b) => parseInt(b, 16)) ?? [])-}--/**- * Inject variable binding into a paint at the specified marker- */-function injectVariableBinding(hex: string, marker: string, binding: { variableID: GUID }): string {- const markerIdx = hex.indexOf(marker)- if (markerIdx === -1) return hex-- // Find visible=true pattern (04 01) after the marker- const visiblePattern = '0401'- const patternIdx = hex.indexOf(visiblePattern, markerIdx)- if (patternIdx === -1) return hex-- // Move past 0401 to find where to insert- let insertPoint = patternIdx + visiblePattern.length-- // Check if blendMode follows (05 01)- if (hex.slice(insertPoint, insertPoint + 4) === '0501') {- insertPoint += 4- }-- // Build variable binding bytes- const varBytes = [- 0x15,- 0x01, // Field 21 (variableBinding) = 1- 0x04,- 0x01, // Nested field 4 = 1- ...encodeVarint(binding.variableID.sessionID),- ...encodeVarint(binding.variableID.localID),- 0x00,- 0x00,- 0x02,- 0x03,- 0x03,- 0x04,- 0x00,- 0x00 // Terminators- ]- const varHex = Buffer.from(varBytes).toString('hex')-- const beforeVar = hex.slice(0, insertPoint)- // Skip original paint terminator (00) - our varHex includes terminators- let afterIdx = insertPoint- if (hex.slice(afterIdx, afterIdx + 2) === '00') {- afterIdx += 2- }- const afterVar = hex.slice(afterIdx)-- return beforeVar + varHex + afterVar+ return VariableBindings.encodeNodeChangeWithVariables(compiledSchema, nodeChange)}diff --git a/packages/core/src/kiwi/protocol.ts b/packages/core/src/kiwi/binary/protocol.tssimilarity index 100%rename from packages/core/src/kiwi/protocol.tsrename to packages/core/src/kiwi/binary/protocol.tsdiff --git a/packages/core/src/kiwi/schema.ts b/packages/core/src/kiwi/binary/schema.tssimilarity index 99%rename from packages/core/src/kiwi/schema.tsrename to packages/core/src/kiwi/binary/schema.tsindex 4d7f101db..e5a434312 100644--- a/packages/core/src/kiwi/schema.ts+++ b/packages/core/src/kiwi/binary/schema.ts@@ -1,5 +1,5 @@/* eslint-disable max-lines -- generated kiwi schema definition */-import { parseSchema } from './kiwi-schema'+import { parseSchema } from '#core/kiwi/kiwi-schema'const schemaText = `package Fig;diff --git a/packages/core/src/kiwi/binary/variable-bindings.ts b/packages/core/src/kiwi/binary/variable-bindings.tsnew file mode 100644index 000000000..9ea35b9bc--- /dev/null+++ b/packages/core/src/kiwi/binary/variable-bindings.ts@@ -0,0 +1,132 @@+import type { GUID } from '#core/types'+import type { NodeChange, Paint } from './codec'++export interface VariableBindingCodec {+ encodePaint(paint: Paint): Uint8Array+ encodeNodeChange(nodeChange: NodeChange): Uint8Array+}++export function encodeVarint(value: number): number[] {+ const bytes: number[] = []+ while (value > 0x7f) {+ bytes.push((value & 0x7f) | 0x80)+ value >>>= 7+ }+ bytes.push(value)+ return bytes+}++export function encodePaintWithVariableBinding(+ codec: VariableBindingCodec,+ paint: Paint,+ variableSessionID: number,+ variableLocalID: number+): Uint8Array {+ const { colorVariableBinding: _, ...basePaint } = paint++ const baseBytes = codec.encodePaint(basePaint)+ const baseArray = Array.from(baseBytes)++ if (baseArray[baseArray.length - 1] === 0) {+ baseArray.pop()+ }++ baseArray.push(0x15, 0x01)+ baseArray.push(0x04, 0x01)+ baseArray.push(...encodeVarint(variableSessionID))+ baseArray.push(...encodeVarint(variableLocalID))+ baseArray.push(0x00, 0x00, 0x02, 0x03, 0x03, 0x04)+ baseArray.push(0x00, 0x00)++ return new Uint8Array(baseArray)+}++export function parseVariableId(variableId: string): GUID | null {+ const match = variableId.match(/VariableID:(\d+):(\d+)/)+ if (!match) return null+ return {+ sessionID: parseInt(match[1] ?? '0', 10),+ localID: parseInt(match[2] ?? '0', 10)+ }+}++export function encodeNodeChangeWithVariables(+ codec: VariableBindingCodec,+ nodeChange: NodeChange+): Uint8Array {+ const hasFillBinding = nodeChange.fillPaints?.some((p) => p.colorVariableBinding)+ const hasStrokeBinding = nodeChange.strokePaints?.some((p) => p.colorVariableBinding)++ if (!hasFillBinding && !hasStrokeBinding) {+ return codec.encodeNodeChange(nodeChange)+ }++ const cleanNodeChange = { ...nodeChange }+ if (cleanNodeChange.fillPaints) {+ cleanNodeChange.fillPaints = cleanNodeChange.fillPaints.map(+ ({ colorVariableBinding: _, ...rest }) => rest+ )+ }+ if (cleanNodeChange.strokePaints) {+ cleanNodeChange.strokePaints = cleanNodeChange.strokePaints.map(+ ({ colorVariableBinding: _, ...rest }) => rest+ )+ }++ const baseBytes = codec.encodeNodeChange(cleanNodeChange)+ let hex = Buffer.from(baseBytes).toString('hex')++ const fillBinding = nodeChange.fillPaints?.[0]?.colorVariableBinding+ if (hasFillBinding && fillBinding) {+ hex = injectVariableBinding(hex, '2601', fillBinding)+ }++ const strokeBinding = nodeChange.strokePaints?.[0]?.colorVariableBinding+ if (hasStrokeBinding && strokeBinding) {+ hex = injectVariableBinding(hex, '2701', strokeBinding)+ }++ return new Uint8Array(hex.match(/.{2}/g)?.map((b) => parseInt(b, 16)) ?? [])+}++function injectVariableBinding(hex: string, marker: string, binding: { variableID: GUID }): string {+ const markerIdx = hex.indexOf(marker)+ if (markerIdx === -1) return hex++ const visiblePattern = '0401'+ const patternIdx = hex.indexOf(visiblePattern, markerIdx)+ if (patternIdx === -1) return hex++ let insertPoint = patternIdx + visiblePattern.length++ if (hex.slice(insertPoint, insertPoint + 4) === '0501') {+ insertPoint += 4+ }++ const varBytes = [+ 0x15,+ 0x01,+ 0x04,+ 0x01,+ ...encodeVarint(binding.variableID.sessionID),+ ...encodeVarint(binding.variableID.localID),+ 0x00,+ 0x00,+ 0x02,+ 0x03,+ 0x03,+ 0x04,+ 0x00,+ 0x00+ ]+ const varHex = Buffer.from(varBytes).toString('hex')++ const beforeVar = hex.slice(0, insertPoint)+ let afterIdx = insertPoint+ if (hex.slice(afterIdx, afterIdx + 2) === '00') {+ afterIdx += 2+ }+ const afterVar = hex.slice(afterIdx)++ return beforeVar + varHex + afterVar+}diff --git a/packages/core/src/kiwi/fig-file.ts b/packages/core/src/kiwi/fig-file.tsdeleted file mode 100644index 0db10e7e9..000000000--- a/packages/core/src/kiwi/fig-file.ts+++ /dev/null@@ -1 +0,0 @@-export { parseFigFile, readFigFile } from '../io/formats/fig/read'diff --git a/packages/core/src/kiwi/fig/file.ts b/packages/core/src/kiwi/fig/file.tsnew file mode 100644index 000000000..dd4329ae4--- /dev/null+++ b/packages/core/src/kiwi/fig/file.ts@@ -0,0 +1 @@+export { parseFigFile, readFigFile } from '#core/io/formats/fig/read'diff --git a/packages/core/src/kiwi/fig-import.ts b/packages/core/src/kiwi/fig/import.tssimilarity index 97%rename from packages/core/src/kiwi/fig-import.tsrename to packages/core/src/kiwi/fig/import.tsindex b9133109a..d2be292b3 100644--- a/packages/core/src/kiwi/fig-import.ts+++ b/packages/core/src/kiwi/fig/import.ts@@ -1,16 +1,16 @@-import { SceneGraph } from '../scene-graph'+import { populateAndApplyOverrides } from '#core/kiwi/instance-overrides'import {guidToString,nodeChangeToProps,sortChildren,setVariableColorResolver,VARIABLE_BINDING_FIELDS_INVERSE-} from './convert'-import { populateAndApplyOverrides } from './instance-overrides'+} from '#core/kiwi/node-change/convert'+import { SceneGraph } from '#core/scene-graph'-import type { VariableType, VariableValue } from '../scene-graph'-import type { NodeChange, VariableDataValuesEntry, Color, GUID } from './codec'-import type { InstanceNodeChange } from './instance-overrides'+import type { NodeChange, VariableDataValuesEntry, Color, GUID } from '#core/kiwi/binary/codec'+import type { InstanceNodeChange } from '#core/kiwi/instance-overrides'+import type { VariableType, VariableValue } from '#core/scene-graph'type AssetRef = { key: string; version?: string }type AliasRef = { guid?: GUID; assetRef?: AssetRef }diff --git a/packages/core/src/kiwi/fig-parse-core.ts b/packages/core/src/kiwi/fig/parse/core.tssimilarity index 93%rename from packages/core/src/kiwi/fig-parse-core.tsrename to packages/core/src/kiwi/fig/parse/core.tsindex 87ad988c9..087493b92 100644--- a/packages/core/src/kiwi/fig-parse-core.ts+++ b/packages/core/src/kiwi/fig/parse/core.ts@@ -1,10 +1,9 @@+import { isZstdCompressed } from '#core/kiwi/binary/protocol'+import { decodeBinarySchema, compileSchema, ByteBuffer } from '#core/kiwi/kiwi-schema'import { unzipSync, inflateSync } from 'fflate'import { decompress as zstdDecompress } from 'fzstd'-import { decodeBinarySchema, compileSchema, ByteBuffer } from './kiwi-schema'-import { isZstdCompressed } from './protocol'--import type { FigmaMessage, NodeChange } from './codec'+import type { FigmaMessage, NodeChange } from '#core/kiwi/binary/codec'interface FigKiwiPayload {schemaDeflated: Uint8Arraydiff --git a/packages/core/src/kiwi/graph-transfer.ts b/packages/core/src/kiwi/fig/parse/transfer.tssimilarity index 94%rename from packages/core/src/kiwi/graph-transfer.tsrename to packages/core/src/kiwi/fig/parse/transfer.tsindex 457bd4cba..c22a79468 100644--- a/packages/core/src/kiwi/graph-transfer.ts+++ b/packages/core/src/kiwi/fig/parse/transfer.ts@@ -1,6 +1,6 @@-import { SceneGraph } from '../scene-graph'+import { SceneGraph } from '#core/scene-graph'-import type { SceneNode, Variable, VariableCollection, DocumentColorSpace } from '../scene-graph'+import type { SceneNode, Variable, VariableCollection, DocumentColorSpace } from '#core/scene-graph'export interface SerializedSceneGraph {rootId: stringdiff --git a/packages/core/src/kiwi/fig-parse-worker.ts b/packages/core/src/kiwi/fig/parse/worker.tssimilarity index 79%rename from packages/core/src/kiwi/fig-parse-worker.tsrename to packages/core/src/kiwi/fig/parse/worker.tsindex 8e9562514..a44e72cde 100644--- a/packages/core/src/kiwi/fig-parse-worker.ts+++ b/packages/core/src/kiwi/fig/parse/worker.ts@@ -1,6 +1,7 @@-import { importNodeChanges } from './fig-import'-import { parseFigBuffer } from './fig-parse-core'-import { serializeSceneGraph } from './graph-transfer'+import { importNodeChanges } from '#core/kiwi/fig/import'+import { serializeSceneGraph } from '#core/kiwi/fig/parse/transfer'++import { parseFigBuffer } from './core'interface WorkerParseRequest {buffer: ArrayBufferdiff --git a/packages/core/src/kiwi/index.ts b/packages/core/src/kiwi/index.tsindex dd6dbc7af..bd02450f0 100644--- a/packages/core/src/kiwi/index.ts+++ b/packages/core/src/kiwi/index.ts@@ -1,5 +1,6 @@-export { readFigFile, parseFigFile } from './fig-file'-export { importNodeChanges } from './fig-import'+export { prefetchFigmaSchema } from '#core/clipboard'+export { readFigFile, parseFigFile } from './fig/file'+export { importNodeChanges } from './fig/import'export {initCodec,encodeMessage,@@ -27,7 +28,7 @@ export {type VariableDataValuesEntry,type ParentIndex,type FigmaMessage-} from './codec'+} from './binary/codec'export {MESSAGE_TYPES,NODE_TYPES,@@ -46,4 +47,4 @@ export {getKiwiMessageType,parseVarint,FIG_WIRE_MAGIC-} from './protocol'+} from './binary/protocol'diff --git a/packages/core/src/kiwi/instance-overrides/constraints.ts b/packages/core/src/kiwi/instance-overrides/constraints.tsindex dfc9d52bf..a258d9cfd 100644--- a/packages/core/src/kiwi/instance-overrides/constraints.ts+++ b/packages/core/src/kiwi/instance-overrides/constraints.ts@@ -1,7 +1,8 @@-import { copyGeometryPaths } from '../../scene-graph/copy'+import { copyGeometryPaths } from '#core/scene-graph/copy'+import { buildClonesMap } from './sync'-import type { GeometryPath, SceneGraph, SceneNode, VectorNetwork } from '../../scene-graph'+import type { GeometryPath, SceneGraph, SceneNode, VectorNetwork } from '#core/scene-graph'import type { OverrideContext } from './types'/**diff --git a/packages/core/src/kiwi/instance-overrides/dsd.ts b/packages/core/src/kiwi/instance-overrides/dsd.tsindex f50c332a3..326f7d382 100644--- a/packages/core/src/kiwi/instance-overrides/dsd.ts+++ b/packages/core/src/kiwi/instance-overrides/dsd.ts@@ -1,9 +1,14 @@-import { copyGeometryPaths } from '../../scene-graph/copy'-import { convertLetterSpacing, convertLineHeight, resolveGeometryPaths } from '../convert'+import {+ convertLetterSpacing,+ convertLineHeight,+ resolveGeometryPaths+} from '#core/kiwi/node-change/convert'+import { copyGeometryPaths } from '#core/scene-graph/copy'+import { resolveOverrideTarget } from './resolve'import { buildClonesMap } from './sync'-import type { SceneNode, GeometryPath } from '../../scene-graph'+import type { SceneNode, GeometryPath } from '#core/scene-graph'import type { OverrideContext, DerivedSymbolOverride } from './types'function scaleGeometryBlobs(geom: GeometryPath[], sx: number, sy: number): GeometryPath[] {diff --git a/packages/core/src/kiwi/instance-overrides/index.ts b/packages/core/src/kiwi/instance-overrides/index.tsindex 3aec09272..4c9708cd5 100644--- a/packages/core/src/kiwi/instance-overrides/index.ts+++ b/packages/core/src/kiwi/instance-overrides/index.ts@@ -10,32 +10,42 @@ export type {SymbolOverride} from './types'-import { copyFills } from '../../scene-graph/copy'-import { guidToString } from '../convert'+import { guidToString } from '#core/kiwi/node-change/convert'+import { copyFills } from '#core/scene-graph/copy'+import { applyConstraintScaling } from './constraints'import { applyDerivedSymbolData } from './dsd'import { populateInstances } from './populate'import { applyComponentProperties } from './props'import { preComputeRoots } from './resolve'-import { applySymbolOverrides } from './symbol-overrides'+import { applySymbolOverrides } from './symbol/overrides'import { propagateOverridesTransitively } from './sync'-import type { SceneGraph } from '../../scene-graph'+import type { SceneGraph } from '#core/scene-graph'import type { InstanceNodeChange, OverrideContext, ComponentPropValue } from './types'/*** Identify nodes whose kiwi NC has explicit property values that DIFFER* from their component source. Only these need protection from sync.*/+function* changedNodeEntries(+ changeMap: Map<string, InstanceNodeChange>,+ guidToNodeId: Map<string, string>+): Generator<[string, InstanceNodeChange]> {+ for (const [figmaId, nodeId] of guidToNodeId) {+ const nc = changeMap.get(figmaId)+ if (nc) yield [nodeId, nc]+ }+}+function buildKiwiPropertyNodes(graph: SceneGraph,changeMap: Map<string, InstanceNodeChange>,guidToNodeId: Map<string, string>): Set<string> {const result = new Set<string>()- for (const [figmaId, nodeId] of guidToNodeId) {- const nc = changeMap.get(figmaId) as Record<string, unknown> | undefined- if (!nc) continue+ for (const [nodeId, change] of changedNodeEntries(changeMap, guidToNodeId)) {+ const nc = change as Record<string, unknown>const node = graph.getNode(nodeId)if (!node?.componentId) continueconst comp = graph.getNode(node.componentId)@@ -54,9 +64,7 @@ function buildKiwiGeometryNodes(guidToNodeId: Map<string, string>): Set<string> {const result = new Set<string>()- for (const [figmaId, nodeId] of guidToNodeId) {- const nc = changeMap.get(figmaId)- if (!nc) continue+ for (const [nodeId, nc] of changedNodeEntries(changeMap, guidToNodeId)) {if (nc.fillGeometry?.length || nc.strokeGeometry?.length) result.add(nodeId)}return resultdiff --git a/packages/core/src/kiwi/instance-overrides/populate.ts b/packages/core/src/kiwi/instance-overrides/populate.tsindex 28937358a..b58699f40 100644--- a/packages/core/src/kiwi/instance-overrides/populate.ts+++ b/packages/core/src/kiwi/instance-overrides/populate.ts@@ -1,4 +1,4 @@-import type { SceneGraph } from '../../scene-graph'+import type { SceneGraph } from '#core/scene-graph'/*** Populate empty INSTANCE nodes from their source components.diff --git a/packages/core/src/kiwi/instance-overrides/props.ts b/packages/core/src/kiwi/instance-overrides/props.tsindex a565c3504..3eb67be1f 100644--- a/packages/core/src/kiwi/instance-overrides/props.ts+++ b/packages/core/src/kiwi/instance-overrides/props.ts@@ -1,4 +1,5 @@-import { guidToString } from '../convert'+import { guidToString } from '#core/kiwi/node-change/convert'+import { resolveOverrideTarget, repopulateInstance } from './resolve'import type {diff --git a/packages/core/src/kiwi/instance-overrides/resolve.ts b/packages/core/src/kiwi/instance-overrides/resolve.tsindex 1ebf5f958..392b20df7 100644--- a/packages/core/src/kiwi/instance-overrides/resolve.ts+++ b/packages/core/src/kiwi/instance-overrides/resolve.ts@@ -1,7 +1,7 @@-import { guidToString } from '../convert'+import { guidToString } from '#core/kiwi/node-change/convert'-import type { SceneNode } from '../../scene-graph'-import type { GUID } from '../codec'+import type { GUID } from '#core/kiwi/binary/codec'+import type { SceneNode } from '#core/scene-graph'import type { InstanceNodeChange, OverrideContext } from './types'const MAX_CHAIN_DEPTH = 20diff --git a/packages/core/src/kiwi/instance-overrides/symbol-overrides.ts b/packages/core/src/kiwi/instance-overrides/symbol/overrides.tssimilarity index 88%rename from packages/core/src/kiwi/instance-overrides/symbol-overrides.tsrename to packages/core/src/kiwi/instance-overrides/symbol/overrides.tsindex 9214bf249..34967f5d0 100644--- a/packages/core/src/kiwi/instance-overrides/symbol-overrides.ts+++ b/packages/core/src/kiwi/instance-overrides/symbol/overrides.ts@@ -1,9 +1,10 @@-import { guidToString } from '../convert'-import { convertOverrideToProps } from '../convert-overrides'-import { resolveOverrideTarget, repopulateInstance } from './resolve'+import { guidToString } from '#core/kiwi/node-change/convert'-import type { SceneNode } from '../../scene-graph'-import type { OverrideContext } from './types'+import { resolveOverrideTarget, repopulateInstance } from '#core/kiwi/instance-overrides/resolve'+import { convertOverrideToProps } from './props'++import type { SceneNode } from '#core/scene-graph'+import type { OverrideContext } from '#core/kiwi/instance-overrides/types'function isActiveInstance(ctx: OverrideContext, nodeId: string | undefined): nodeId is string {return nodeId !== undefined && (!ctx.activeNodeIds || ctx.activeNodeIds.has(nodeId))diff --git a/packages/core/src/kiwi/convert-overrides.ts b/packages/core/src/kiwi/instance-overrides/symbol/props.tssimilarity index 96%rename from packages/core/src/kiwi/convert-overrides.tsrename to packages/core/src/kiwi/instance-overrides/symbol/props.tsindex e87a241e9..752a0f407 100644--- a/packages/core/src/kiwi/convert-overrides.ts+++ b/packages/core/src/kiwi/instance-overrides/symbol/props.ts@@ -1,4 +1,3 @@-import { styleToWeight } from '../text/fonts'import {convertFills,mapStackSizing,@@ -12,10 +11,11 @@ import {importStyleRuns,convertStrokes,convertEffects-} from './convert'+} from '#core/kiwi/node-change/convert'+import { styleToWeight } from '#core/text/fonts'-import type { SceneNode, ArcData, TextAutoResize } from '../scene-graph'-import type { NodeChange, Paint, Effect as KiwiEffect } from './codec'+import type { NodeChange, Paint, Effect as KiwiEffect } from '#core/kiwi/binary/codec'+import type { SceneNode, ArcData, TextAutoResize } from '#core/scene-graph'function applyOverridePaints(ov: Record<string, unknown>, updates: Partial<SceneNode>): void {if (ov.textData != null) {diff --git a/packages/core/src/kiwi/instance-overrides/sync.ts b/packages/core/src/kiwi/instance-overrides/sync.tsindex e006c8205..f5289e4eb 100644--- a/packages/core/src/kiwi/instance-overrides/sync.ts+++ b/packages/core/src/kiwi/instance-overrides/sync.ts@@ -1,6 +1,6 @@-import { copyFills, copyStrokes, copyEffects, copyStyleRuns } from '../../scene-graph/copy'+import { copyFills, copyStrokes, copyEffects, copyStyleRuns } from '#core/scene-graph/copy'-import type { SceneGraph, SceneNode } from '../../scene-graph'+import type { SceneGraph, SceneNode } from '#core/scene-graph'/*** Copy appearance props from source to target (text, visibility, fills, etc.).diff --git a/packages/core/src/kiwi/instance-overrides/types.ts b/packages/core/src/kiwi/instance-overrides/types.tsindex f4d752331..71ae24f6e 100644--- a/packages/core/src/kiwi/instance-overrides/types.ts+++ b/packages/core/src/kiwi/instance-overrides/types.ts@@ -1,6 +1,6 @@-import type { SceneGraph } from '../../scene-graph'-import type { Matrix, Vector } from '../../types'-import type { GUID, NodeChange } from '../codec'+import type { GUID, NodeChange } from '#core/kiwi/binary/codec'+import type { SceneGraph } from '#core/scene-graph'+import type { Matrix, Vector } from '#core/types'export interface SymbolOverride {guidPath?: { guids?: GUID[] }diff --git a/packages/core/src/kiwi/convert.ts b/packages/core/src/kiwi/node-change/convert.tssimilarity index 55%rename from packages/core/src/kiwi/convert.tsrename to packages/core/src/kiwi/node-change/convert.tsindex e54985675..fd0f1bc46 100644--- a/packages/core/src/kiwi/convert.ts+++ b/packages/core/src/kiwi/node-change/convert.ts@@ -1,19 +1,30 @@/* eslint-disable max-lines -- kiwi↔scene conversion helpers are tightly coupled */-import { normalizeColor } from '../color'-import { DEFAULT_FONT_FAMILY, DEFAULT_STROKE_MITER_LIMIT } from '../constants'-import { styleToWeight } from '../text/fonts'-import { decodeVectorNetworkBlob } from '../vector'-+import { DEFAULT_FONT_FAMILY, DEFAULT_STROKE_MITER_LIMIT } from '#core/constants'+import { styleToWeight } from '#core/text/fonts'+import { guidToString } from './guid'+import { convertEffects, convertFills, convertStrokes } from './paint'+import { importStyleRuns } from './style-runs'+export { importStyleRuns } from './style-runs'+import { convertLetterSpacing, convertLineHeight, mapTextDecoration } from './text-values'+export { convertEffects, convertFills, convertStrokes, setVariableColorResolver } from './paint'+export { convertLetterSpacing, convertLineHeight, mapTextDecoration } from './text-values'+import {+ extractBoundVariables,+ extractPluginData,+ extractPluginRelaunchData,+ extractSharedPluginData,+ getOpenPencilPluginValue,+ LAYOUT_DIRECTION_PLUGIN_KEY,+ TEXT_DIRECTION_PLUGIN_KEY+} from './plugin-data'+import { resolveGeometryPaths, resolveVectorNetwork } from './vector-geometry'+export { resolveGeometryPaths } from './vector-geometry'++import type { NodeChange } from '#core/kiwi/binary/codec'import type {SceneNode,NodeType,Fill,- FillType,- Stroke,- Effect,- BlendMode,- ImageScaleMode,- GradientTransform,StrokeCap,StrokeJoin,LayoutMode,@@ -25,34 +36,12 @@ import type {TextAutoResize,TextAlignVertical,TextCase,- TextDecoration,ArcData,- VectorNetwork,- GeometryPath,- StyleRun,- CharacterStyleOverride,- WindingRule,- PluginDataEntry,- SharedPluginDataEntry,- PluginRelaunchDataEntry-} from '../scene-graph'-import type { Color, Matrix, Vector } from '../types'-import type { NodeChange, Paint, Effect as KiwiEffect, GUID } from './codec'--const OPEN_PENCIL_PLUGIN_ID = 'open-pencil'-const TEXT_DIRECTION_PLUGIN_KEY = 'textDirection'-const LAYOUT_DIRECTION_PLUGIN_KEY = 'layoutDirection'+ VectorNetwork+} from '#core/scene-graph'+import type { GUID } from '#core/types'-export function guidToString(guid: GUID): string {- return `${guid.sessionID}:${guid.localID}`-}--export function stringToGuid(str: string): GUID {- const match = str.match(/^(?:VariableID:|VariableCollectionId:)?(\d+):(\d+)$/)- if (match) return { sessionID: parseInt(match[1], 10), localID: parseInt(match[2], 10) }- const [session, local] = str.split(':')- return { sessionID: parseInt(session, 10), localID: parseInt(local, 10) }-}+export { guidToString, stringToGuid } from './guid'export const VARIABLE_BINDING_FIELDS: Record<string, string> = {cornerRadius: 'CORNER_RADIUS',@@ -80,114 +69,6 @@ export const VARIABLE_BINDING_FIELDS_INVERSE: Record<string, string> = Object.frObject.entries(VARIABLE_BINDING_FIELDS).map(([k, v]) => [v, k]))-const convertColor = normalizeColor--function imageHashToString(hash: Record<string, number>): string {- const bytes = Object.keys(hash)- .sort((a, b) => Number(a) - Number(b))- .map((k) => hash[Number(k)])- return bytes.map((b) => b.toString(16).padStart(2, '0')).join('')-}--function convertGradientTransform(t?: Matrix): GradientTransform | undefined {- if (!t) return undefined- return { m00: t.m00, m01: t.m01, m02: t.m02, m10: t.m10, m11: t.m11, m12: t.m12 }-}--type VariableAliasRef = NonNullable<NonNullable<NonNullable<Paint['colorVar']>['value']>['alias']>--let variableColorResolver: ((alias: VariableAliasRef) => Color | null) | null = null--export function setVariableColorResolver(- resolver: ((alias: VariableAliasRef) => Color | null) | null-): void {- variableColorResolver = resolver-}--function resolveColorVar(paint: Paint): Color | undefined {- const alias = paint.colorVar?.value?.alias- if (!alias || !variableColorResolver) return undefined- return variableColorResolver(alias) ?? undefined-}--export function convertFills(paints?: Paint[]): Fill[] {- if (!paints) return []- return paints.map((p) => {- const base: Fill = {- type: p.type as FillType,- color: convertColor(resolveColorVar(p) ?? p.color),- opacity: p.opacity ?? 1,- visible: p.visible ?? true,- blendMode: (p.blendMode ?? 'NORMAL') as BlendMode- }-- if (p.type.startsWith('GRADIENT') && p.stops) {- base.gradientStops = p.stops.map((s) => ({- color: convertColor(s.color),- position: s.position- }))- if (p.transform) {- base.gradientTransform = convertGradientTransform(p.transform)- }- }-- if (p.type === 'IMAGE') {- if (p.image && typeof p.image === 'object') {- const img = p.image as { hash: string | Record<string, number> }- if (typeof img.hash === 'object') {- base.imageHash = imageHashToString(img.hash)- } else if (typeof img.hash === 'string') {- base.imageHash = img.hash- }- }- base.imageScaleMode = (p.imageScaleMode ?? 'FILL') as ImageScaleMode- if (p.transform) {- base.imageTransform = convertGradientTransform(p.transform)- }- }-- return base- })-}--export function convertStrokes(- paints?: Paint[],- weight?: number,- align?: string,- cap?: StrokeCap,- join?: StrokeJoin,- dashPattern?: number[]-): Stroke[] {- if (!paints) return []- let strokeAlign: 'INSIDE' | 'OUTSIDE' | 'CENTER' = 'CENTER'- if (align === 'INSIDE') strokeAlign = 'INSIDE'- else if (align === 'OUTSIDE') strokeAlign = 'OUTSIDE'-- return paints.map((p) => ({- color: convertColor(resolveColorVar(p) ?? p.color),- weight: weight ?? 1,- opacity: p.opacity ?? 1,- visible: p.visible ?? true,- align: strokeAlign,- cap: cap ?? 'NONE',- join: join ?? 'MITER',- dashPattern: dashPattern ?? []- }))-}--export function convertEffects(effects?: KiwiEffect[]): Effect[] {- if (!effects) return []- return effects.map((e) => ({- type: e.type,- color: convertColor(e.color),- offset: e.offset ?? { x: 0, y: 0 },- radius: e.radius ?? 0,- spread: e.spread ?? 0,- visible: e.visible ?? true,- blendMode: (e.blendMode ?? 'NORMAL') as BlendMode- }))-}-const NODE_TYPE_MAP: Record<string, NodeType | 'DOCUMENT' | 'VARIABLE'> = {DOCUMENT: 'DOCUMENT',VARIABLE: 'VARIABLE',@@ -301,38 +182,6 @@ function mapConstraint(c?: string): ConstraintType {}}-export function mapTextDecoration(d?: string): TextDecoration {- switch (d) {- case 'UNDERLINE':- return 'UNDERLINE'- case 'STRIKETHROUGH':- return 'STRIKETHROUGH'- default:- return 'NONE'- }-}--export function convertLineHeight(- lh?: { value: number; units: string },- fontSize?: number-): number | null {- if (!lh) return null- if (lh.units === 'PIXELS') return lh.value- if (lh.units === 'PERCENT') return (lh.value / 100) * (fontSize ?? 14)- if (lh.units === 'RAW') return lh.value * (fontSize ?? 14)- return null-}--export function convertLetterSpacing(- ls?: { value: number; units: string },- fontSize?: number-): number {- if (!ls) return 0- if (ls.units === 'PIXELS') return ls.value- if (ls.units === 'PERCENT') return (ls.value / 100) * (fontSize ?? 14)- return ls.value-}-export function mapArcData(data?: Partial<ArcData>): ArcData | null {if (!data) return nullreturn {@@ -342,205 +191,6 @@ export function mapArcData(data?: Partial<ArcData>): ArcData | null {}}-function convertStyleOverride(- override: NodeChange,- fallbackFontSize: number | undefined-): CharacterStyleOverride {- const style: CharacterStyleOverride = {}- if (override.fontName) {- style.fontFamily = override.fontName.family- style.fontWeight = styleToWeight(override.fontName.style)- style.italic = override.fontName.style.toLowerCase().includes('italic')- }- if (override.fontSize !== undefined) style.fontSize = override.fontSize- if (override.letterSpacing) {- style.letterSpacing = convertLetterSpacing(- override.letterSpacing,- override.fontSize ?? fallbackFontSize- )- }- if (override.lineHeight) {- const lh = convertLineHeight(override.lineHeight, override.fontSize ?? fallbackFontSize)- if (lh != null) style.lineHeight = lh- }- const deco = override.textDecoration- if (deco) style.textDecoration = mapTextDecoration(deco)- if (override.fillPaints) {- const fills = convertFills(override.fillPaints)- if (fills.length > 0) style.fills = fills- }- return style-}--function buildStyleMap(- table: NodeChange[],- fallbackFontSize: number | undefined-): Map<number, CharacterStyleOverride> {- const styleMap = new Map<number, CharacterStyleOverride>()- for (const override of table) {- const id = override.styleID as number | undefined- if (id === undefined) continue- const style = convertStyleOverride(override, fallbackFontSize)- if (Object.keys(style).length > 0) styleMap.set(id, style)- }- return styleMap-}--function collectStyleRuns(- ids: number[],- styleMap: Map<number, CharacterStyleOverride>-): StyleRun[] {- const runs: StyleRun[] = []- let currentId = ids[0]- let start = 0-- for (let i = 1; i <= ids.length; i++) {- if (i === ids.length || ids[i] !== currentId) {- if (currentId !== 0) {- const style = styleMap.get(currentId)- if (style) runs.push({ start, length: i - start, style })- }- if (i < ids.length) {- currentId = ids[i]- start = i- }- }- }- return runs-}--export function importStyleRuns(nc: NodeChange): StyleRun[] {- const td = nc.textData- if (!td?.characterStyleIDs || !td.styleOverrideTable) return []-- const ids = td.characterStyleIDs- if (ids.length === 0 || td.styleOverrideTable.length === 0) return []-- const styleMap = buildStyleMap(td.styleOverrideTable, nc.fontSize)- if (styleMap.size === 0) return []-- return collectStyleRuns(ids, styleMap)-}--function resolveVectorNetwork(nc: NodeChange, blobs: Uint8Array[]): VectorNetwork | null {- const vectorData = nc.vectorData as- | {- vectorNetworkBlob?: number- normalizedSize?: Vector- styleOverrideTable?: Array<{ styleID: number; handleMirroring?: string }>- }- | undefined-- if (vectorData?.vectorNetworkBlob === undefined) return null- const idx = vectorData.vectorNetworkBlob- if (idx < 0 || idx >= blobs.length) return null-- try {- const network = decodeVectorNetworkBlob(blobs[idx], vectorData.styleOverrideTable)-- const ns = vectorData.normalizedSize- const nodeW = nc.size?.x ?? 0- const nodeH = nc.size?.y ?? 0- if (ns && nodeW > 0 && nodeH > 0 && (ns.x !== nodeW || ns.y !== nodeH)) {- const sx = nodeW / ns.x- const sy = nodeH / ns.y- for (const v of network.vertices) {- v.x *= sx- v.y *= sy- }- for (const seg of network.segments) {- seg.tangentStart = { x: seg.tangentStart.x * sx, y: seg.tangentStart.y * sy }- seg.tangentEnd = { x: seg.tangentEnd.x * sx, y: seg.tangentEnd.y * sy }- }- }-- return network- } catch {- return null- }-}--interface KiwiPath {- windingRule?: string- commandsBlob?: number-}--export function resolveGeometryPaths(- paths: KiwiPath[] | undefined,- blobs: Uint8Array[]-): GeometryPath[] {- if (!paths || paths.length === 0) return []- const result: GeometryPath[] = []- for (const p of paths) {- if (p.commandsBlob === undefined || p.commandsBlob < 0 || p.commandsBlob >= blobs.length)- continue- const blob = blobs[p.commandsBlob]- if (blob.length === 0) continue- result.push({- windingRule: (p.windingRule === 'EVENODD' ? 'EVENODD' : 'NONZERO') as WindingRule,- commandsBlob: blob- })- }- return result-}--function extractBoundVariables(nc: NodeChange): Record<string, string> {- const bindings: Record<string, string> = {}- nc.fillPaints?.forEach((paint, i) => {- if (paint.colorVariableBinding) {- bindings[`fills/${i}/color`] = guidToString(paint.colorVariableBinding.variableID)- }- })- nc.strokePaints?.forEach((paint, i) => {- if (paint.colorVariableBinding) {- bindings[`strokes/${i}/color`] = guidToString(paint.colorVariableBinding.variableID)- }- })- return bindings-}--function extractPluginData(nc: NodeChange): PluginDataEntry[] {- return (nc.pluginData ?? []).map((entry) => ({- pluginId: entry.pluginID,- key: entry.key,- value: entry.value- }))-}--function getOpenPencilPluginValue(nc: NodeChange, key: string): string | null {- return (- nc.pluginData?.find((entry) => entry.pluginID === OPEN_PENCIL_PLUGIN_ID && entry.key === key)- ?.value ?? null- )-}--function extractSharedPluginData(nc: NodeChange): SharedPluginDataEntry[] {- return extractPluginData(nc).map((entry) => {- const slashIndex = entry.key.indexOf('/')- if (slashIndex === -1) {- return {- namespace: entry.pluginId,- key: entry.key,- value: entry.value- }- }- return {- namespace: entry.key.slice(0, slashIndex),- key: entry.key.slice(slashIndex + 1),- value: entry.value- }- })-}--function extractPluginRelaunchData(nc: NodeChange): PluginRelaunchDataEntry[] {- return (nc.pluginRelaunchData ?? []).map((entry) => ({- pluginId: entry.pluginID,- command: entry.command,- message: entry.message,- isDeleted: entry.isDeleted- }))-}-function convertTransformProps(nc: NodeChange): Pick<SceneNode, 'x' | 'y' | 'width' | 'height' | 'rotation' | 'flipX' | 'flipY'> {diff --git a/packages/core/src/kiwi/node-export.ts b/packages/core/src/kiwi/node-change/export-node.tssimilarity index 96%rename from packages/core/src/kiwi/node-export.tsrename to packages/core/src/kiwi/node-change/export-node.tsindex 0e03cd1b8..91d2f780f 100644--- a/packages/core/src/kiwi/node-export.ts+++ b/packages/core/src/kiwi/node-change/export-node.ts@@ -1,8 +1,8 @@import { mergePluginData, serializePluginRelaunchData } from './plugin-data'-import type { SceneGraph, SceneNode } from '../scene-graph'-import type { Color, GUID, Matrix } from '../types'-import type { NodeChange, Paint } from './codec'+import type { NodeChange, Paint } from '#core/kiwi/binary/codec'+import type { SceneGraph, SceneNode } from '#core/scene-graph'+import type { Color, GUID, Matrix } from '#core/types'export type KiwiNodeChange = NodeChange & Record<string, unknown>diff --git a/packages/core/src/kiwi/node-change/fig/container.ts b/packages/core/src/kiwi/node-change/fig/container.tsnew file mode 100644index 000000000..5ac08bb10--- /dev/null+++ b/packages/core/src/kiwi/node-change/fig/container.ts@@ -0,0 +1,64 @@+import { deflateSync, inflateSync } from 'fflate'++export const FIG_KIWI_DEFAULT_VERSION = 101++export function parseFigKiwiChunks(binary: Uint8Array): Uint8Array[] | null {+ const header = new TextDecoder().decode(binary.slice(0, 8))+ if (header !== 'fig-kiwi') return null++ const view = new DataView(binary.buffer, binary.byteOffset, binary.byteLength)+ let offset = 12++ const chunks: Uint8Array[] = []+ while (offset < binary.length) {+ const chunkLen = view.getUint32(offset, true)+ offset += 4+ chunks.push(binary.slice(offset, offset + chunkLen))+ offset += chunkLen+ }+ return chunks.length >= 2 ? chunks : null+}++export function decompressFigKiwiData(compressed: Uint8Array): Uint8Array {+ try {+ return inflateSync(compressed)+ } catch {+ throw new Error('Failed to decompress fig-kiwi data')+ }+}++export async function decompressFigKiwiDataAsync(compressed: Uint8Array): Promise<Uint8Array> {+ try {+ return inflateSync(compressed)+ } catch {+ const fzstd = await import('fzstd')+ return fzstd.decompress(compressed)+ }+}++export function buildFigKiwi(+ schemaDeflated: Uint8Array,+ dataRaw: Uint8Array,+ version = FIG_KIWI_DEFAULT_VERSION+): Uint8Array {+ const dataDeflated = deflateSync(dataRaw)++ const total = 8 + 4 + 4 + schemaDeflated.length + 4 + dataDeflated.length+ const out = new Uint8Array(total)+ const view = new DataView(out.buffer)++ out.set(new TextEncoder().encode('fig-kiwi'), 0)+ view.setUint32(8, version, true)++ let offset = 12+ view.setUint32(offset, schemaDeflated.length, true)+ offset += 4+ out.set(schemaDeflated, offset)+ offset += schemaDeflated.length++ view.setUint32(offset, dataDeflated.length, true)+ offset += 4+ out.set(dataDeflated, offset)++ return out+}diff --git a/packages/core/src/kiwi/node-change/font-digests.ts b/packages/core/src/kiwi/node-change/font-digests.tsnew file mode 100644index 000000000..05432f28c--- /dev/null+++ b/packages/core/src/kiwi/node-change/font-digests.ts@@ -0,0 +1,47 @@+import { getLoadedFontData, weightToStyle } from '#core/text/fonts'++import type { SceneGraph } from '#core/scene-graph'++const fontDigestCache = new Map<string, Uint8Array>()++async function computeFontDigest(data: ArrayBuffer): Promise<Uint8Array> {+ if (typeof crypto !== 'undefined') {+ const hash = await crypto.subtle.digest('SHA-1', data)+ return new Uint8Array(hash)+ }+ return new Uint8Array(20)+}++async function getFontDigest(family: string, style: string): Promise<Uint8Array | null> {+ const key = `${family}|${style}`+ const cached = fontDigestCache.get(key)+ if (cached) return cached+ const data = getLoadedFontData(family, style)+ if (!data) return null+ const digest = await computeFontDigest(data)+ fontDigestCache.set(key, digest)+ return digest+}++export async function buildFontDigestMap(graph: SceneGraph): Promise<Map<string, Uint8Array>> {+ const fontKeys = new Set<string>()+ for (const node of graph.getAllNodes()) {+ if (node.type !== 'TEXT') continue+ const baseStyle = weightToStyle(node.fontWeight, node.italic)+ fontKeys.add(`${node.fontFamily}|${baseStyle}`)+ for (const run of node.styleRuns) {+ const family = run.style.fontFamily ?? node.fontFamily+ const weight = run.style.fontWeight ?? node.fontWeight+ const italic = run.style.italic ?? node.italic+ fontKeys.add(`${family}|${weightToStyle(weight, italic)}`)+ }+ }++ const result = new Map<string, Uint8Array>()+ for (const key of fontKeys) {+ const [family, style] = key.split('|')+ const digest = await getFontDigest(family, style)+ if (digest) result.set(key, digest)+ }+ return result+}diff --git a/packages/core/src/kiwi/node-change/guid.ts b/packages/core/src/kiwi/node-change/guid.tsnew file mode 100644index 000000000..035ad6ffa--- /dev/null+++ b/packages/core/src/kiwi/node-change/guid.ts@@ -0,0 +1,12 @@+import type { GUID } from '#core/kiwi/binary/codec'++export function guidToString(guid: GUID): string {+ return `${guid.sessionID}:${guid.localID}`+}++export function stringToGuid(str: string): GUID {+ const match = str.match(/^(?:VariableID:|VariableCollectionId:)?(\d+):(\d+)$/)+ if (match) return { sessionID: parseInt(match[1], 10), localID: parseInt(match[2], 10) }+ const [session, local] = str.split(':')+ return { sessionID: parseInt(session, 10), localID: parseInt(local, 10) }+}diff --git a/packages/core/src/kiwi/node-change/paint.ts b/packages/core/src/kiwi/node-change/paint.tsnew file mode 100644index 000000000..1dae47b5a--- /dev/null+++ b/packages/core/src/kiwi/node-change/paint.ts@@ -0,0 +1,123 @@+import { normalizeColor } from '#core/color'++import type { Paint, Effect as KiwiEffect } from '#core/kiwi/binary/codec'+import type {+ Fill,+ FillType,+ Stroke,+ Effect,+ BlendMode,+ ImageScaleMode,+ GradientTransform,+ StrokeCap,+ StrokeJoin+} from '#core/scene-graph'+import type { Color, Matrix } from '#core/types'++const convertColor = normalizeColor++function imageHashToString(hash: Record<string, number>): string {+ const bytes = Object.keys(hash)+ .sort((a, b) => Number(a) - Number(b))+ .map((k) => hash[Number(k)])+ return bytes.map((b) => b.toString(16).padStart(2, '0')).join('')+}++function convertGradientTransform(t?: Matrix): GradientTransform | undefined {+ if (!t) return undefined+ return { m00: t.m00, m01: t.m01, m02: t.m02, m10: t.m10, m11: t.m11, m12: t.m12 }+}++type VariableAliasRef = NonNullable<NonNullable<NonNullable<Paint['colorVar']>['value']>['alias']>++let variableColorResolver: ((alias: VariableAliasRef) => Color | null) | null = null++export function setVariableColorResolver(+ resolver: ((alias: VariableAliasRef) => Color | null) | null+): void {+ variableColorResolver = resolver+}++function resolveColorVar(paint: Paint): Color | undefined {+ const alias = paint.colorVar?.value?.alias+ if (!alias || !variableColorResolver) return undefined+ return variableColorResolver(alias) ?? undefined+}++export function convertFills(paints?: Paint[]): Fill[] {+ if (!paints) return []+ return paints.map((p) => {+ const base: Fill = {+ type: p.type as FillType,+ color: convertColor(resolveColorVar(p) ?? p.color),+ opacity: p.opacity ?? 1,+ visible: p.visible ?? true,+ blendMode: (p.blendMode ?? 'NORMAL') as BlendMode+ }++ if (p.type.startsWith('GRADIENT') && p.stops) {+ base.gradientStops = p.stops.map((s) => ({+ color: convertColor(s.color),+ position: s.position+ }))+ if (p.transform) {+ base.gradientTransform = convertGradientTransform(p.transform)+ }+ }++ if (p.type === 'IMAGE') {+ if (p.image && typeof p.image === 'object') {+ const img = p.image as { hash: string | Record<string, number> }+ if (typeof img.hash === 'object') {+ base.imageHash = imageHashToString(img.hash)+ } else if (typeof img.hash === 'string') {+ base.imageHash = img.hash+ }+ }+ base.imageScaleMode = (p.imageScaleMode ?? 'FILL') as ImageScaleMode+ if (p.transform) {+ base.imageTransform = convertGradientTransform(p.transform)+ }+ }++ return base+ })+}++export function convertStrokes(+ paints?: Paint[],+ weight?: number,+ align?: string,+ cap?: StrokeCap,+ join?: StrokeJoin,+ dashPattern?: number[]+): Stroke[] {+ if (!paints) return []+ let strokeAlign: 'INSIDE' | 'OUTSIDE' | 'CENTER' = 'CENTER'+ if (align === 'INSIDE') strokeAlign = 'INSIDE'+ else if (align === 'OUTSIDE') strokeAlign = 'OUTSIDE'++ return paints.map((p) => ({+ color: convertColor(resolveColorVar(p) ?? p.color),+ weight: weight ?? 1,+ opacity: p.opacity ?? 1,+ visible: p.visible ?? true,+ align: strokeAlign,+ cap: cap ?? 'NONE',+ join: join ?? 'MITER',+ dashPattern: dashPattern ?? []+ }))+}++export function convertEffects(effects?: KiwiEffect[]): Effect[] {+ if (!effects) return []+ return effects.map((e) => ({+ type: e.type,+ color: convertColor(e.color),+ offset: e.offset ?? { x: 0, y: 0 },+ radius: e.radius ?? 0,+ spread: e.spread ?? 0,+ visible: e.visible ?? true,+ blendMode: (e.blendMode ?? 'NORMAL') as BlendMode+ }))+}diff --git a/packages/core/src/kiwi/node-change/plugin-data.ts b/packages/core/src/kiwi/node-change/plugin-data.tsnew file mode 100644index 000000000..a67d28b39--- /dev/null+++ b/packages/core/src/kiwi/node-change/plugin-data.ts@@ -0,0 +1,110 @@+import { guidToString } from './guid'++import type {+ NodeChange,+ PluginData,+ PluginRelaunchData+} from '#core/kiwi/binary/codec'+import type {+ PluginDataEntry,+ PluginRelaunchDataEntry,+ SharedPluginDataEntry+} from '#core/scene-graph'++export const OPEN_PENCIL_PLUGIN_ID = 'open-pencil'+export const TEXT_DIRECTION_PLUGIN_KEY = 'textDirection'+export const LAYOUT_DIRECTION_PLUGIN_KEY = 'layoutDirection'++export function upsertPluginData(node: { pluginData: PluginDataEntry[] }, key: string, value: string): void {+ const pluginData = node.pluginData.filter(+ (entry) => !(entry.pluginId === OPEN_PENCIL_PLUGIN_ID && entry.key === key)+ )+ pluginData.push({ pluginId: OPEN_PENCIL_PLUGIN_ID, key, value })+ node.pluginData = pluginData+}++export function extractBoundVariables(nc: NodeChange): Record<string, string> {+ const bindings: Record<string, string> = {}+ nc.fillPaints?.forEach((paint, i) => {+ if (paint.colorVariableBinding) {+ bindings[`fills/${i}/color`] = guidToString(paint.colorVariableBinding.variableID)+ }+ })+ nc.strokePaints?.forEach((paint, i) => {+ if (paint.colorVariableBinding) {+ bindings[`strokes/${i}/color`] = guidToString(paint.colorVariableBinding.variableID)+ }+ })+ return bindings+}++export function extractPluginData(nc: NodeChange): PluginDataEntry[] {+ return (nc.pluginData ?? []).map((entry) => ({+ pluginId: entry.pluginID,+ key: entry.key,+ value: entry.value+ }))+}++export function getOpenPencilPluginValue(nc: NodeChange, key: string): string | null {+ return (+ nc.pluginData?.find((entry) => entry.pluginID === OPEN_PENCIL_PLUGIN_ID && entry.key === key)+ ?.value ?? null+ )+}++export function extractSharedPluginData(nc: NodeChange): SharedPluginDataEntry[] {+ return extractPluginData(nc).map((entry) => {+ const slashIndex = entry.key.indexOf('/')+ if (slashIndex === -1) {+ return {+ namespace: entry.pluginId,+ key: entry.key,+ value: entry.value+ }+ }+ return {+ namespace: entry.key.slice(0, slashIndex),+ key: entry.key.slice(slashIndex + 1),+ value: entry.value+ }+ })+}++export function extractPluginRelaunchData(nc: NodeChange): PluginRelaunchDataEntry[] {+ return (nc.pluginRelaunchData ?? []).map((entry) => ({+ pluginId: entry.pluginID,+ command: entry.command,+ message: entry.message,+ isDeleted: entry.isDeleted+ }))+}++export function mergePluginData(+ pluginData: PluginDataEntry[],+ sharedPluginData: SharedPluginDataEntry[]+): PluginData[] {+ return [+ ...pluginData.map((entry) => ({+ pluginID: entry.pluginId,+ key: entry.key,+ value: entry.value+ })),+ ...sharedPluginData.map((entry) => ({+ pluginID: entry.namespace,+ key: `${entry.namespace}/${entry.key}`,+ value: entry.value+ }))+ ]+}++export function serializePluginRelaunchData(+ entries: PluginRelaunchDataEntry[]+): PluginRelaunchData[] {+ return entries.map((entry) => ({+ pluginID: entry.pluginId,+ command: entry.command,+ message: entry.message,+ isDeleted: entry.isDeleted+ }))+}diff --git a/packages/core/src/kiwi/serialize.ts b/packages/core/src/kiwi/node-change/serialize.tssimilarity index 76%rename from packages/core/src/kiwi/serialize.tsrename to packages/core/src/kiwi/node-change/serialize.tsindex ff4948928..103c346d7 100644--- a/packages/core/src/kiwi/serialize.ts+++ b/packages/core/src/kiwi/node-change/serialize.ts@@ -1,132 +1,27 @@-export const FIG_KIWI_DEFAULT_VERSION = 101+import { buildDerivedTextData as buildSharedDerivedTextData } from '#core/text/derived-text-data'+import { normalizeFontFamily, weightToStyle } from '#core/text/fonts'+import { getGlyphOutlineCommandsSync } from '#core/text/opentype'+import { encodeVectorNetworkBlob, buildStyleOverrideTable } from '#core/vector'+export {+ buildFigKiwi,+ decompressFigKiwiData,+ decompressFigKiwiDataAsync,+ FIG_KIWI_DEFAULT_VERSION,+ parseFigKiwiChunks+} from './fig/container'+export { buildFontDigestMap } from './font-digests'-import { deflateSync, inflateSync } from 'fflate'--import { getLoadedFontData, normalizeFontFamily, weightToStyle } from '../text/fonts'-import { getGlyphOutlineCommandsSync } from '../text/opentype'-import { encodeVectorNetworkBlob, buildStyleOverrideTable } from '../vector'import { stringToGuid, VARIABLE_BINDING_FIELDS } from './convert'-import { sceneNodeToKiwiWithContext, type KiwiNodeChange } from './node-export'--import type { SceneGraph, SceneNode, CharacterStyleOverride } from '../scene-graph'-import type { Color, GUID, Matrix } from '../types'-import type { NodeChange, Paint, VariableConsumptionEntry } from './codec'--const fontDigestCache = new Map<string, Uint8Array>()-const OPEN_PENCIL_PLUGIN_ID = 'open-pencil'-const TEXT_DIRECTION_PLUGIN_KEY = 'textDirection'-const LAYOUT_DIRECTION_PLUGIN_KEY = 'layoutDirection'--function upsertPluginData(node: SceneNode, key: string, value: string): void {- const pluginData = node.pluginData.filter(- (entry) => !(entry.pluginId === OPEN_PENCIL_PLUGIN_ID && entry.key === key)- )- pluginData.push({ pluginId: OPEN_PENCIL_PLUGIN_ID, key, value })- node.pluginData = pluginData-}+import { sceneNodeToKiwiWithContext, type KiwiNodeChange } from './export-node'+import {+ LAYOUT_DIRECTION_PLUGIN_KEY,+ TEXT_DIRECTION_PLUGIN_KEY,+ upsertPluginData+} from './plugin-data'-async function computeFontDigest(data: ArrayBuffer): Promise<Uint8Array> {- if (typeof crypto !== 'undefined') {- const hash = await crypto.subtle.digest('SHA-1', data)- return new Uint8Array(hash)- }- return new Uint8Array(20)-}--async function getFontDigest(family: string, style: string): Promise<Uint8Array | null> {- const key = `${family}|${style}`- const cached = fontDigestCache.get(key)- if (cached) return cached- const data = getLoadedFontData(family, style)- if (!data) return null- const digest = await computeFontDigest(data)- fontDigestCache.set(key, digest)- return digest-}--export async function buildFontDigestMap(graph: SceneGraph): Promise<Map<string, Uint8Array>> {- const fontKeys = new Set<string>()- for (const node of graph.getAllNodes()) {- if (node.type !== 'TEXT') continue- const baseStyle = weightToStyle(node.fontWeight, node.italic)- fontKeys.add(`${node.fontFamily}|${baseStyle}`)- for (const run of node.styleRuns) {- const family = run.style.fontFamily ?? node.fontFamily- const weight = run.style.fontWeight ?? node.fontWeight- const italic = run.style.italic ?? node.italic- fontKeys.add(`${family}|${weightToStyle(weight, italic)}`)- }- }-- const result = new Map<string, Uint8Array>()- for (const key of fontKeys) {- const [family, style] = key.split('|')- const digest = await getFontDigest(family, style)- if (digest) result.set(key, digest)- }- return result-}--export function parseFigKiwiChunks(binary: Uint8Array): Uint8Array[] | null {- const header = new TextDecoder().decode(binary.slice(0, 8))- if (header !== 'fig-kiwi') return null-- const view = new DataView(binary.buffer, binary.byteOffset, binary.byteLength)- let offset = 12-- const chunks: Uint8Array[] = []- while (offset < binary.length) {- const chunkLen = view.getUint32(offset, true)- offset += 4- chunks.push(binary.slice(offset, offset + chunkLen))- offset += chunkLen- }- return chunks.length >= 2 ? chunks : null-}--export function decompressFigKiwiData(compressed: Uint8Array): Uint8Array {- try {- return inflateSync(compressed)- } catch {- throw new Error('Failed to decompress fig-kiwi data')- }-}--export async function decompressFigKiwiDataAsync(compressed: Uint8Array): Promise<Uint8Array> {- try {- return inflateSync(compressed)- } catch {- const fzstd = await import('fzstd')- return fzstd.decompress(compressed)- }-}--export function buildFigKiwi(- schemaDeflated: Uint8Array,- dataRaw: Uint8Array,- version = FIG_KIWI_DEFAULT_VERSION-): Uint8Array {- const dataDeflated = deflateSync(dataRaw)-- const total = 8 + 4 + 4 + schemaDeflated.length + 4 + dataDeflated.length- const out = new Uint8Array(total)- const view = new DataView(out.buffer)-- out.set(new TextEncoder().encode('fig-kiwi'), 0)- view.setUint32(8, version, true)-- let offset = 12- view.setUint32(offset, schemaDeflated.length, true)- offset += 4- out.set(schemaDeflated, offset)- offset += schemaDeflated.length-- view.setUint32(offset, dataDeflated.length, true)- offset += 4- out.set(dataDeflated, offset)-- return out-}+import type { NodeChange, Paint, VariableConsumptionEntry } from '#core/kiwi/binary/codec'+import type { SceneGraph, SceneNode, CharacterStyleOverride } from '#core/scene-graph'+import type { Color, GUID, Matrix } from '#core/types'export function mapToFigmaType(type: SceneNode['type']): string {switch (type) {@@ -227,25 +122,16 @@ function buildDerivedTextData((_, index) => index * glyphAdvance)- return {- layoutSize: { x: node.width, y: node.height },- baselines: [- {- firstCharacter: 0,- endCharacter: Math.max(node.text.length - 1, 0),- position: { x: 0, y: lineHeight },- width: node.width,- lineHeight,- lineAscent: Math.max(lineHeight - node.fontSize * 0.2, 0)- }- ],+ return buildSharedDerivedTextData({+ node,glyphs,fontMetaData: fontMeta,- logicalIndexToCharacterOffsetMap,- derivedLines: [{ directionality: 'LTR' }],- truncationStartIndex: -1,- truncatedHeight: -1- }+ baseline: lineHeight,+ width: node.width,+ lineHeight,+ lineAscent: Math.max(lineHeight - node.fontSize * 0.2, 0),+ logicalIndexToCharacterOffsetMap+ })}function exportTextData(node: SceneNode): NodeChange['textData'] {diff --git a/packages/core/src/kiwi/node-change/style-runs.ts b/packages/core/src/kiwi/node-change/style-runs.tsnew file mode 100644index 000000000..91be2b0b0--- /dev/null+++ b/packages/core/src/kiwi/node-change/style-runs.ts@@ -0,0 +1,86 @@+import { styleToWeight } from '#core/text/fonts'+import { convertFills } from './paint'+import { convertLetterSpacing, convertLineHeight, mapTextDecoration } from './text-values'++import type { NodeChange } from '#core/kiwi/binary/codec'+import type { CharacterStyleOverride, StyleRun } from '#core/scene-graph'++function convertStyleOverride(+ override: NodeChange,+ fallbackFontSize: number | undefined+): CharacterStyleOverride {+ const style: CharacterStyleOverride = {}+ if (override.fontName) {+ style.fontFamily = override.fontName.family+ style.fontWeight = styleToWeight(override.fontName.style)+ style.italic = override.fontName.style.toLowerCase().includes('italic')+ }+ if (override.fontSize !== undefined) style.fontSize = override.fontSize+ if (override.letterSpacing) {+ style.letterSpacing = convertLetterSpacing(+ override.letterSpacing,+ override.fontSize ?? fallbackFontSize+ )+ }+ if (override.lineHeight) {+ const lh = convertLineHeight(override.lineHeight, override.fontSize ?? fallbackFontSize)+ if (lh != null) style.lineHeight = lh+ }+ const deco = override.textDecoration+ if (deco) style.textDecoration = mapTextDecoration(deco)+ if (override.fillPaints) {+ const fills = convertFills(override.fillPaints)+ if (fills.length > 0) style.fills = fills+ }+ return style+}++function buildStyleMap(+ table: NodeChange[],+ fallbackFontSize: number | undefined+): Map<number, CharacterStyleOverride> {+ const styleMap = new Map<number, CharacterStyleOverride>()+ for (const override of table) {+ const id = override.styleID as number | undefined+ if (id === undefined) continue+ const style = convertStyleOverride(override, fallbackFontSize)+ if (Object.keys(style).length > 0) styleMap.set(id, style)+ }+ return styleMap+}++function collectStyleRuns(+ ids: number[],+ styleMap: Map<number, CharacterStyleOverride>+): StyleRun[] {+ const runs: StyleRun[] = []+ let currentId = ids[0]+ let start = 0++ for (let i = 1; i <= ids.length; i++) {+ if (i === ids.length || ids[i] !== currentId) {+ if (currentId !== 0) {+ const style = styleMap.get(currentId)+ if (style) runs.push({ start, length: i - start, style })+ }+ if (i < ids.length) {+ currentId = ids[i]+ start = i+ }+ }+ }+ return runs+}++export function importStyleRuns(nc: NodeChange): StyleRun[] {+ const td = nc.textData+ if (!td?.characterStyleIDs || !td.styleOverrideTable) return []++ const ids = td.characterStyleIDs+ if (ids.length === 0 || td.styleOverrideTable.length === 0) return []++ const styleMap = buildStyleMap(td.styleOverrideTable, nc.fontSize)+ if (styleMap.size === 0) return []++ return collectStyleRuns(ids, styleMap)+}diff --git a/packages/core/src/kiwi/node-change/text-values.ts b/packages/core/src/kiwi/node-change/text-values.tsnew file mode 100644index 000000000..b14ffb383--- /dev/null+++ b/packages/core/src/kiwi/node-change/text-values.ts@@ -0,0 +1,33 @@+import type { TextDecoration } from '#core/scene-graph'++export function mapTextDecoration(d?: string): TextDecoration {+ switch (d) {+ case 'UNDERLINE':+ return 'UNDERLINE'+ case 'STRIKETHROUGH':+ return 'STRIKETHROUGH'+ default:+ return 'NONE'+ }+}++export function convertLineHeight(+ lh?: { value: number; units: string },+ fontSize?: number+): number | null {+ if (!lh) return null+ if (lh.units === 'PIXELS') return lh.value+ if (lh.units === 'PERCENT') return (lh.value / 100) * (fontSize ?? 14)+ if (lh.units === 'RAW') return lh.value * (fontSize ?? 14)+ return null+}++export function convertLetterSpacing(+ ls?: { value: number; units: string },+ fontSize?: number+): number {+ if (!ls) return 0+ if (ls.units === 'PIXELS') return ls.value+ if (ls.units === 'PERCENT') return (ls.value / 100) * (fontSize ?? 14)+ return ls.value+}diff --git a/packages/core/src/kiwi/node-change/vector-geometry.ts b/packages/core/src/kiwi/node-change/vector-geometry.tsnew file mode 100644index 000000000..6fe3e7c97--- /dev/null+++ b/packages/core/src/kiwi/node-change/vector-geometry.ts@@ -0,0 +1,67 @@+import { decodeVectorNetworkBlob } from '#core/vector'++import type { NodeChange } from '#core/kiwi/binary/codec'+import type { GeometryPath, VectorNetwork, WindingRule } from '#core/scene-graph'+import type { Vector } from '#core/types'++export function resolveVectorNetwork(nc: NodeChange, blobs: Uint8Array[]): VectorNetwork | null {+ const vectorData = nc.vectorData as+ | {+ vectorNetworkBlob?: number+ normalizedSize?: Vector+ styleOverrideTable?: Array<{ styleID: number; handleMirroring?: string }>+ }+ | undefined++ if (vectorData?.vectorNetworkBlob === undefined) return null+ const idx = vectorData.vectorNetworkBlob+ if (idx < 0 || idx >= blobs.length) return null++ try {+ const network = decodeVectorNetworkBlob(blobs[idx], vectorData.styleOverrideTable)++ const ns = vectorData.normalizedSize+ const nodeW = nc.size?.x ?? 0+ const nodeH = nc.size?.y ?? 0+ if (ns && nodeW > 0 && nodeH > 0 && (ns.x !== nodeW || ns.y !== nodeH)) {+ const sx = nodeW / ns.x+ const sy = nodeH / ns.y+ for (const v of network.vertices) {+ v.x *= sx+ v.y *= sy+ }+ for (const seg of network.segments) {+ seg.tangentStart = { x: seg.tangentStart.x * sx, y: seg.tangentStart.y * sy }+ seg.tangentEnd = { x: seg.tangentEnd.x * sx, y: seg.tangentEnd.y * sy }+ }+ }++ return network+ } catch {+ return null+ }+}++interface KiwiPath {+ windingRule?: string+ commandsBlob?: number+}++export function resolveGeometryPaths(+ paths: KiwiPath[] | undefined,+ blobs: Uint8Array[]+): GeometryPath[] {+ if (!paths || paths.length === 0) return []+ const result: GeometryPath[] = []+ for (const p of paths) {+ if (p.commandsBlob === undefined || p.commandsBlob < 0 || p.commandsBlob >= blobs.length)+ continue+ const blob = blobs[p.commandsBlob]+ if (blob.length === 0) continue+ result.push({+ windingRule: (p.windingRule === 'EVENODD' ? 'EVENODD' : 'NONZERO') as WindingRule,+ commandsBlob: blob+ })+ }+ return result+}diff --git a/packages/core/src/kiwi/plugin-data.ts b/packages/core/src/kiwi/plugin-data.tsdeleted file mode 100644index 34464a3bd..000000000--- a/packages/core/src/kiwi/plugin-data.ts+++ /dev/null@@ -1,35 +0,0 @@-import type {- PluginDataEntry,- PluginRelaunchDataEntry,- SharedPluginDataEntry-} from '../scene-graph'-import type { PluginData, PluginRelaunchData } from './codec'--export function mergePluginData(- pluginData: PluginDataEntry[],- sharedPluginData: SharedPluginDataEntry[]-): PluginData[] {- return [- ...pluginData.map((entry) => ({- pluginID: entry.pluginId,- key: entry.key,- value: entry.value- })),- ...sharedPluginData.map((entry) => ({- pluginID: entry.namespace,- key: `${entry.namespace}/${entry.key}`,- value: entry.value- }))- ]-}--export function serializePluginRelaunchData(- entries: PluginRelaunchDataEntry[]-): PluginRelaunchData[] {- return entries.map((entry) => ({- pluginID: entry.pluginId,- command: entry.command,- message: entry.message,- isDeleted: entry.isDeleted- }))-}diff --git a/packages/core/src/layout.ts b/packages/core/src/layout.tsindex c76a35c26..499426791 100644--- a/packages/core/src/layout.ts+++ b/packages/core/src/layout.ts@@ -1,73 +1,38 @@-/* eslint-disable max-lines -- layout tree building is a single recursive pass */-import Yoga, {+import {Align,Direction,Display,FlexDirection,- GridTrackType,Gutter,- Justify,Edge,MeasureMode,Overflow,- PositionType,Wrap,type Node as YogaNode} from 'yoga-layout'+import { applyYogaLayout } from './layout/apply'+import { buildGridTree, createGridChildNode } from './layout/grid'import { resolveNodeLayoutDirection } from './text/direction'-import { weightToStyle } from './text/fonts'-import { measureTextWithOpenType } from './text/opentype'--import type { GridTrack, SceneGraph, SceneNode } from './scene-graph'--export type TextMeasurer = (- node: SceneNode,- maxWidth?: number-) => { width: number; height: number } | null--let globalTextMeasurer: TextMeasurer | null = null--const GLYPH_WIDTH_FACTOR = 0.6-const yogaConfig = Yoga.Config.create()-yogaConfig.setPointScaleFactor(0)--function createYogaNode(): YogaNode {- return Yoga.Node.create(yogaConfig)-}--// Rough estimate for text size when CanvasKit/font is not available.-// DO NOT REMOVE: without this, text nodes keep their 100×100 default size-// and blow up every HUG container. The real MeasureFunc (CanvasKit) overrides-// this when available — this is only the fallback.-function estimateTextSize(node: SceneNode, maxWidth?: number): { width: number; height: number } {- const fontSize = node.fontSize || 14- const family = node.fontFamily || 'Inter'- const style = weightToStyle(node.fontWeight || 400, node.italic)- const text = node.text || ''-- const explicitLineH = (node.lineHeight ?? 0) > 0 ? (node.lineHeight as number) : undefined- const measured = measureTextWithOpenType(text, fontSize, family, style, maxWidth, explicitLineH)- if (measured) return measured-- const charWidth = fontSize * GLYPH_WIDTH_FACTOR- const singleLineWidth = Math.ceil(text.length * charWidth)- const lineH = (node.lineHeight ?? 0) > 0 ? (node.lineHeight as number) : Math.ceil(fontSize * 1.4)-- if (maxWidth && maxWidth > 0 && singleLineWidth > maxWidth) {- const lines = Math.ceil(singleLineWidth / maxWidth)- return { width: maxWidth, height: Math.ceil(lines * lineH) }- }- return { width: singleLineWidth, height: lineH }-}--export function getTextMeasurer(): TextMeasurer | null {- return globalTextMeasurer-}--export function setTextMeasurer(measurer: TextMeasurer | null): void {- globalTextMeasurer = measurer-}+export {+ estimateTextSize,+ getTextMeasurer,+ setTextMeasurer,+ type TextMeasurer+} from './layout/text-measurement'+import { estimateTextSize, getTextMeasurer } from './layout/text-measurement'+import {+ applyMinMaxConstraints,+ configureAbsoluteChild,+ createYogaNode,+ freeYogaTree,+ mapAlign,+ mapAlignSelf,+ mapGridTrack,+ mapJustify+} from './layout/yoga-helpers'++import type { SceneGraph, SceneNode } from './scene-graph'export function computeLayout(graph: SceneGraph, frameId: string): void {const frame = graph.getNode(frameId)@@ -83,7 +48,7 @@ export function computeLayout(graph: SceneGraph, frameId: string): void {undefined,rootDirection === 'RTL' ? Direction.RTL : Direction.LTR)- applyYogaLayout(graph, frame, yogaRoot)+ applyYogaLayout(graph, frame, yogaRoot, computeLayout)freeYogaTree(yogaRoot)}@@ -115,108 +80,6 @@ function computeLayoutsBottomUp(graph: SceneGraph, nodeId: string, visited: Set<}}-// --- Grid layout -----function mapGridTrack(track: GridTrack): { type: GridTrackType; value: number } {- switch (track.sizing) {- case 'FR':- return { type: GridTrackType.Fr, value: track.value }- case 'FIXED':- return { type: GridTrackType.Points, value: track.value }- default:- return { type: GridTrackType.Auto, value: 0 }- }-}--function configureAsGrid(- yogaNode: YogaNode,- node: SceneNode,- direction: Exclude<SceneNode['layoutDirection'], 'AUTO'>-): void {- yogaNode.setDisplay(Display.Grid)- yogaNode.setDirection(direction === 'RTL' ? Direction.RTL : Direction.LTR)- yogaNode.setWidth(node.width)- if (node.gridTemplateRows.length > 0 || node.height > 0) {- yogaNode.setHeight(node.height)- }-- if (node.gridTemplateColumns.length > 0) {- yogaNode.setGridTemplateColumns(node.gridTemplateColumns.map(mapGridTrack))- }- if (node.gridTemplateRows.length > 0) {- yogaNode.setGridTemplateRows(node.gridTemplateRows.map(mapGridTrack))- }-- yogaNode.setGap(Gutter.Column, node.gridColumnGap)- yogaNode.setGap(Gutter.Row, node.gridRowGap)-- yogaNode.setPadding(Edge.Top, node.paddingTop)- yogaNode.setPadding(Edge.Right, node.paddingRight)- yogaNode.setPadding(Edge.Bottom, node.paddingBottom)- yogaNode.setPadding(Edge.Left, node.paddingLeft)-}--function createGridChildNode(child: SceneNode): YogaNode {- const yogaChild = createYogaNode()- if (!child.visible) {- yogaChild.setDisplay(Display.None)- } else {- const pos = child.gridPosition- if (pos) {- yogaChild.setGridColumnStart(pos.column)- yogaChild.setGridColumnEndSpan(pos.columnSpan)- yogaChild.setGridRowStart(pos.row)- yogaChild.setGridRowEndSpan(pos.rowSpan)- }- const hasLayout = child.layoutMode !== 'NONE'- const explicitStretch = child.layoutGrow > 0 || child.layoutAlignSelf === 'STRETCH'-- if (explicitStretch || hasLayout) {- yogaChild.setWidthStretch()- } else {- yogaChild.setWidth(child.width)- }- if (explicitStretch) {- yogaChild.setHeightStretch()- } else {- yogaChild.setHeight(child.height)- }- }- return yogaChild-}--function buildGridTree(- graph: SceneGraph,- frame: SceneNode,- inheritedDirection: 'LTR' | 'RTL'-): YogaNode {- const root = createYogaNode()- const direction = resolveNodeLayoutDirection(frame, inheritedDirection)- configureAsGrid(root, frame, direction)-- const children = graph.getChildren(frame.id)- for (const child of children) {- if (child.layoutPositioning === 'ABSOLUTE') {- const yogaChild = createYogaNode()- configureAbsoluteChild(yogaChild, child)- root.insertChild(yogaChild, root.getChildCount())- } else {- const yogaChild = createGridChildNode(child)- if (- child.layoutMode === 'GRID' ||- child.layoutMode === 'HORIZONTAL' ||- child.layoutMode === 'VERTICAL'- ) {- const childDirection = resolveNodeLayoutDirection(child, direction)- yogaChild.setDirection(childDirection === 'RTL' ? Direction.RTL : Direction.LTR)- }- root.insertChild(yogaChild, root.getChildCount())- }- }-- return root-}-// --- Flex layout ---function buildYogaTree(@@ -260,14 +123,6 @@ function buildYogaTree(return root}-function configureAbsoluteChild(yogaChild: YogaNode, child: SceneNode): void {- yogaChild.setPositionType(PositionType.Absolute)- yogaChild.setPosition(Edge.Left, child.x)- yogaChild.setPosition(Edge.Top, child.y)- yogaChild.setWidth(child.width)- yogaChild.setHeight(child.height)-}-function configureFlexContainer(yogaNode: YogaNode,node: SceneNode,@@ -370,13 +225,6 @@ function configureChildAsGrid(}}-function applyMinMaxConstraints(yogaNode: YogaNode, node: SceneNode): void {- if (node.minWidth != null) yogaNode.setMinWidth(node.minWidth)- if (node.maxWidth != null) yogaNode.setMaxWidth(node.maxWidth)- if (node.minHeight != null) yogaNode.setMinHeight(node.minHeight)- if (node.maxHeight != null) yogaNode.setMaxHeight(node.maxHeight)-}-function configureChildAsAutoLayout(yogaChild: YogaNode,child: SceneNode,@@ -432,11 +280,12 @@ function configureChildAsLeaf(yogaChild: YogaNode, child: SceneNode, parent: Sce: parent.counterAxisAlign === 'STRETCH'const isText = child.type === 'TEXT'- const needsMeasureFunc = isText && globalTextMeasurer && child.textAutoResize !== 'NONE'+ const textMeasurer = getTextMeasurer()+ const needsMeasureFunc = isText && textMeasurer && child.textAutoResize !== 'NONE'if (needsMeasureFunc) {configureTextLeaf(yogaChild, child, parent)- } else if (isText && !globalTextMeasurer && child.textAutoResize !== 'NONE') {+ } else if (isText && !textMeasurer && child.textAutoResize !== 'NONE') {// No CanvasKit — prefer stored dimensions from .fig import (Figma's// ground truth) over the rough character-count estimate. Only fall back// to estimateTextSize for newly-created nodes that still carry the@@ -495,7 +344,7 @@ function configureTextLeaf(yogaChild: YogaNode, child: SceneNode, parent: SceneNconst cached = cache.get(cacheKey)if (cached) return cached- const measured = globalTextMeasurer?.(child, maxW)+ const measured = getTextMeasurer()?.(child, maxW)const result = measured ?? estimateTextSize(child, maxW)cache.set(cacheKey, result)return result@@ -523,7 +372,7 @@ function configureTextLeaf(yogaChild: YogaNode, child: SceneNode, parent: SceneNconst cached = cache.get(cacheKey)if (cached) return cached- const measured = globalTextMeasurer?.(child, constraintW)+ const measured = getTextMeasurer()?.(child, constraintW)const result = {width: constraintW,height: measured?.height ?? estimateTextSize(child, constraintW).height@@ -607,143 +456,3 @@ function setCrossAxisSizing(break}}--function applyFrameSize(graph: SceneGraph, frame: SceneNode, yogaNode: YogaNode): void {- if (frame.layoutMode === 'GRID') {- if (frame.gridTemplateRows.length === 0) {- graph.updateNode(frame.id, { height: yogaNode.getComputedHeight() })- }- return- }-- if (frame.primaryAxisSizing !== 'HUG' && frame.counterAxisSizing !== 'HUG') return-- const computedW = yogaNode.getComputedWidth()- const computedH = yogaNode.getComputedHeight()- const updates: Partial<SceneNode> = {}-- const derived = frame.figmaDerivedLayout- if (frame.primaryAxisSizing === 'HUG') {- if (frame.layoutMode === 'HORIZONTAL') updates.width = derived?.width ?? computedW- else updates.height = derived?.height ?? computedH- }- if (frame.counterAxisSizing === 'HUG') {- if (frame.layoutMode === 'HORIZONTAL') updates.height = derived?.height ?? computedH- else updates.width = derived?.width ?? computedW- }-- graph.updateNode(frame.id, updates)-}--function updateChildFromYoga(graph: SceneGraph, child: SceneNode, yogaChild: YogaNode): void {- if (!child.visible || child.layoutPositioning === 'ABSOLUTE' || child.type === 'INSTANCE') return-- const derived = child.figmaDerivedLayout- graph.updateNode(child.id, {- x: derived?.x ?? yogaChild.getComputedLeft(),- y: derived?.y ?? yogaChild.getComputedTop(),- width: derived?.width ?? yogaChild.getComputedWidth(),- height: derived?.height ?? yogaChild.getComputedHeight()- })-}--function applyYogaLayout(graph: SceneGraph, frame: SceneNode, yogaNode: YogaNode): void {- applyFrameSize(graph, frame, yogaNode)-- const children = graph.getChildren(frame.id)- let yogaIndex = 0- for (const child of children) {- const yogaChild = yogaNode.getChild(yogaIndex)- yogaIndex++- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition- if (!yogaChild) continue-- updateChildFromYoga(graph, child, yogaChild)-- if (child.layoutMode !== 'NONE') {- if (child.layoutMode === 'GRID' && child.visible && child.layoutPositioning !== 'ABSOLUTE') {- computeLayout(graph, child.id)- } else if (- frame.layoutMode === 'GRID' &&- child.visible &&- child.layoutPositioning !== 'ABSOLUTE'- ) {- recomputeGridChild(graph, child)- } else {- applyYogaLayout(graph, child, yogaChild)- }- }- }-}--function recomputeGridChild(graph: SceneGraph, child: SceneNode): void {- const updated = graph.getNode(child.id)- if (!updated || updated.layoutMode === 'NONE') return-- const savedPrimary = updated.primaryAxisSizing- const savedCounter = updated.counterAxisSizing- const updates: Partial<SceneNode> = {}-- if (savedPrimary === 'HUG') updates.primaryAxisSizing = 'FIXED'- if (savedCounter === 'HUG') updates.counterAxisSizing = 'FIXED'- if (Object.keys(updates).length > 0) graph.updateNode(child.id, updates)-- computeLayout(graph, child.id)-- const restore: Partial<SceneNode> = {}- if (updates.primaryAxisSizing) restore.primaryAxisSizing = savedPrimary- if (updates.counterAxisSizing) restore.counterAxisSizing = savedCounter- if (Object.keys(restore).length > 0) graph.updateNode(child.id, restore)-}--function freeYogaTree(node: YogaNode): void {- for (let i = node.getChildCount() - 1; i >= 0; i--) {- freeYogaTree(node.getChild(i))- }- if ('free' in node) (node as { free(): void }).free()-}--function mapJustify(align: string): Justify {- switch (align) {- case 'CENTER':- return Justify.Center- case 'MAX':- return Justify.FlexEnd- case 'SPACE_BETWEEN':- return Justify.SpaceBetween- default:- return Justify.FlexStart- }-}--function mapAlign(align: string): Align {- switch (align) {- case 'CENTER':- return Align.Center- case 'MAX':- return Align.FlexEnd- case 'STRETCH':- return Align.Stretch- case 'BASELINE':- return Align.Baseline- default:- return Align.FlexStart- }-}--function mapAlignSelf(alignSelf: string): Align | null {- switch (alignSelf) {- case 'MIN':- return Align.FlexStart- case 'CENTER':- return Align.Center- case 'MAX':- return Align.FlexEnd- case 'STRETCH':- return Align.Stretch- case 'BASELINE':- return Align.Baseline- default:- return null- }-}diff --git a/packages/core/src/layout/apply.ts b/packages/core/src/layout/apply.tsnew file mode 100644index 000000000..543b1d403--- /dev/null+++ b/packages/core/src/layout/apply.ts@@ -0,0 +1,100 @@+import type { SceneGraph, SceneNode } from '#core/scene-graph'+import type { Node as YogaNode } from 'yoga-layout'++export type ComputeLayoutFn = (graph: SceneGraph, frameId: string) => void++function applyFrameSize(graph: SceneGraph, frame: SceneNode, yogaNode: YogaNode): void {+ if (frame.layoutMode === 'GRID') {+ if (frame.gridTemplateRows.length === 0) {+ graph.updateNode(frame.id, { height: yogaNode.getComputedHeight() })+ }+ return+ }++ if (frame.primaryAxisSizing !== 'HUG' && frame.counterAxisSizing !== 'HUG') return++ const computedW = yogaNode.getComputedWidth()+ const computedH = yogaNode.getComputedHeight()+ const updates: Partial<SceneNode> = {}++ const derived = frame.figmaDerivedLayout+ if (frame.primaryAxisSizing === 'HUG') {+ if (frame.layoutMode === 'HORIZONTAL') updates.width = derived?.width ?? computedW+ else updates.height = derived?.height ?? computedH+ }+ if (frame.counterAxisSizing === 'HUG') {+ if (frame.layoutMode === 'HORIZONTAL') updates.height = derived?.height ?? computedH+ else updates.width = derived?.width ?? computedW+ }++ graph.updateNode(frame.id, updates)+}++function updateChildFromYoga(graph: SceneGraph, child: SceneNode, yogaChild: YogaNode): void {+ if (!child.visible || child.layoutPositioning === 'ABSOLUTE' || child.type === 'INSTANCE') return++ const derived = child.figmaDerivedLayout+ graph.updateNode(child.id, {+ x: derived?.x ?? yogaChild.getComputedLeft(),+ y: derived?.y ?? yogaChild.getComputedTop(),+ width: derived?.width ?? yogaChild.getComputedWidth(),+ height: derived?.height ?? yogaChild.getComputedHeight()+ })+}++function recomputeGridChild(+ graph: SceneGraph,+ child: SceneNode,+ computeLayout: ComputeLayoutFn+): void {+ const updated = graph.getNode(child.id)+ if (!updated || updated.layoutMode === 'NONE') return++ const savedPrimary = updated.primaryAxisSizing+ const savedCounter = updated.counterAxisSizing+ const updates: Partial<SceneNode> = {}++ if (savedPrimary === 'HUG') updates.primaryAxisSizing = 'FIXED'+ if (savedCounter === 'HUG') updates.counterAxisSizing = 'FIXED'+ if (Object.keys(updates).length > 0) graph.updateNode(child.id, updates)++ computeLayout(graph, child.id)++ const restore: Partial<SceneNode> = {}+ if (updates.primaryAxisSizing) restore.primaryAxisSizing = savedPrimary+ if (updates.counterAxisSizing) restore.counterAxisSizing = savedCounter+ if (Object.keys(restore).length > 0) graph.updateNode(child.id, restore)+}++export function applyYogaLayout(+ graph: SceneGraph,+ frame: SceneNode,+ yogaNode: YogaNode,+ computeLayout: ComputeLayoutFn+): void {+ applyFrameSize(graph, frame, yogaNode)++ const children = graph.getChildren(frame.id)+ let yogaIndex = 0+ for (const child of children) {+ if (yogaIndex >= yogaNode.getChildCount()) continue+ const yogaChild = yogaNode.getChild(yogaIndex)+ yogaIndex++++ updateChildFromYoga(graph, child, yogaChild)++ if (child.layoutMode !== 'NONE') {+ if (child.layoutMode === 'GRID' && child.visible && child.layoutPositioning !== 'ABSOLUTE') {+ computeLayout(graph, child.id)+ } else if (+ frame.layoutMode === 'GRID' &&+ child.visible &&+ child.layoutPositioning !== 'ABSOLUTE'+ ) {+ recomputeGridChild(graph, child, computeLayout)+ } else {+ applyYogaLayout(graph, child, yogaChild, computeLayout)+ }+ }+ }+}diff --git a/packages/core/src/layout/grid.ts b/packages/core/src/layout/grid.tsnew file mode 100644index 000000000..dcce33b09--- /dev/null+++ b/packages/core/src/layout/grid.ts@@ -0,0 +1,96 @@+import { Direction, Display, Gutter, Edge, type Node as YogaNode } from 'yoga-layout'++import { resolveNodeLayoutDirection } from '#core/text/direction'+import { configureAbsoluteChild, createYogaNode, mapGridTrack } from './yoga-helpers'++import type { SceneGraph, SceneNode } from '#core/scene-graph'++function configureAsGrid(+ yogaNode: YogaNode,+ node: SceneNode,+ direction: Exclude<SceneNode['layoutDirection'], 'AUTO'>+): void {+ yogaNode.setDisplay(Display.Grid)+ yogaNode.setDirection(direction === 'RTL' ? Direction.RTL : Direction.LTR)+ yogaNode.setWidth(node.width)+ if (node.gridTemplateRows.length > 0 || node.height > 0) {+ yogaNode.setHeight(node.height)+ }++ if (node.gridTemplateColumns.length > 0) {+ yogaNode.setGridTemplateColumns(node.gridTemplateColumns.map(mapGridTrack))+ }+ if (node.gridTemplateRows.length > 0) {+ yogaNode.setGridTemplateRows(node.gridTemplateRows.map(mapGridTrack))+ }++ yogaNode.setGap(Gutter.Column, node.gridColumnGap)+ yogaNode.setGap(Gutter.Row, node.gridRowGap)++ yogaNode.setPadding(Edge.Top, node.paddingTop)+ yogaNode.setPadding(Edge.Right, node.paddingRight)+ yogaNode.setPadding(Edge.Bottom, node.paddingBottom)+ yogaNode.setPadding(Edge.Left, node.paddingLeft)+}++export function createGridChildNode(child: SceneNode): YogaNode {+ const yogaChild = createYogaNode()+ if (!child.visible) {+ yogaChild.setDisplay(Display.None)+ } else {+ const pos = child.gridPosition+ if (pos) {+ yogaChild.setGridColumnStart(pos.column)+ yogaChild.setGridColumnEndSpan(pos.columnSpan)+ yogaChild.setGridRowStart(pos.row)+ yogaChild.setGridRowEndSpan(pos.rowSpan)+ }+ const hasLayout = child.layoutMode !== 'NONE'+ const explicitStretch = child.layoutGrow > 0 || child.layoutAlignSelf === 'STRETCH'++ if (explicitStretch || hasLayout) {+ yogaChild.setWidthStretch()+ } else {+ yogaChild.setWidth(child.width)+ }+ if (explicitStretch) {+ yogaChild.setHeightStretch()+ } else {+ yogaChild.setHeight(child.height)+ }+ }+ return yogaChild+}++export function buildGridTree(+ graph: SceneGraph,+ frame: SceneNode,+ inheritedDirection: 'LTR' | 'RTL'+): YogaNode {+ const root = createYogaNode()+ const direction = resolveNodeLayoutDirection(frame, inheritedDirection)+ configureAsGrid(root, frame, direction)++ const children = graph.getChildren(frame.id)+ for (const child of children) {+ if (child.layoutPositioning === 'ABSOLUTE') {+ const yogaChild = createYogaNode()+ configureAbsoluteChild(yogaChild, child)+ root.insertChild(yogaChild, root.getChildCount())+ } else {+ const yogaChild = createGridChildNode(child)+ if (+ child.layoutMode === 'GRID' ||+ child.layoutMode === 'HORIZONTAL' ||+ child.layoutMode === 'VERTICAL'+ ) {+ const childDirection = resolveNodeLayoutDirection(child, direction)+ yogaChild.setDirection(childDirection === 'RTL' ? Direction.RTL : Direction.LTR)+ }+ root.insertChild(yogaChild, root.getChildCount())+ }+ }++ return root+}+diff --git a/packages/core/src/layout/text-measurement.ts b/packages/core/src/layout/text-measurement.tsnew file mode 100644index 000000000..107b53afd--- /dev/null+++ b/packages/core/src/layout/text-measurement.ts@@ -0,0 +1,45 @@+import { weightToStyle } from '#core/text/fonts'+import { measureTextWithOpenType } from '#core/text/opentype'++import type { SceneNode } from '#core/scene-graph'++export type TextMeasurer = (+ node: SceneNode,+ maxWidth?: number+) => { width: number; height: number } | null++let globalTextMeasurer: TextMeasurer | null = null++const GLYPH_WIDTH_FACTOR = 0.6++export function estimateTextSize(+ node: SceneNode,+ maxWidth?: number+): { width: number; height: number } {+ const fontSize = node.fontSize || 14+ const family = node.fontFamily || 'Inter'+ const style = weightToStyle(node.fontWeight || 400, node.italic)+ const text = node.text || ''++ const explicitLineH = (node.lineHeight ?? 0) > 0 ? (node.lineHeight as number) : undefined+ const measured = measureTextWithOpenType(text, fontSize, family, style, maxWidth, explicitLineH)+ if (measured) return measured++ const charWidth = fontSize * GLYPH_WIDTH_FACTOR+ const singleLineWidth = Math.ceil(text.length * charWidth)+ const lineH = (node.lineHeight ?? 0) > 0 ? (node.lineHeight as number) : Math.ceil(fontSize * 1.4)++ if (maxWidth && maxWidth > 0 && singleLineWidth > maxWidth) {+ const lines = Math.ceil(singleLineWidth / maxWidth)+ return { width: maxWidth, height: Math.ceil(lines * lineH) }+ }+ return { width: singleLineWidth, height: lineH }+}++export function getTextMeasurer(): TextMeasurer | null {+ return globalTextMeasurer+}++export function setTextMeasurer(measurer: TextMeasurer | null): void {+ globalTextMeasurer = measurer+}diff --git a/packages/core/src/layout/yoga-helpers.ts b/packages/core/src/layout/yoga-helpers.tsnew file mode 100644index 000000000..0b8f6e06f--- /dev/null+++ b/packages/core/src/layout/yoga-helpers.ts@@ -0,0 +1,95 @@+import Yoga, {+ Align,+ Edge,+ GridTrackType,+ Justify,+ PositionType,+ type Node as YogaNode+} from 'yoga-layout'++import type { GridTrack, SceneNode } from '#core/scene-graph'++const yogaConfig = Yoga.Config.create()+yogaConfig.setPointScaleFactor(0)++export function createYogaNode(): YogaNode {+ return Yoga.Node.create(yogaConfig)+}++export function configureAbsoluteChild(yogaChild: YogaNode, child: SceneNode): void {+ yogaChild.setPositionType(PositionType.Absolute)+ yogaChild.setPosition(Edge.Left, child.x)+ yogaChild.setPosition(Edge.Top, child.y)+ yogaChild.setWidth(child.width)+ yogaChild.setHeight(child.height)+}++export function applyMinMaxConstraints(yogaNode: YogaNode, node: SceneNode): void {+ if (node.minWidth != null) yogaNode.setMinWidth(node.minWidth)+ if (node.maxWidth != null) yogaNode.setMaxWidth(node.maxWidth)+ if (node.minHeight != null) yogaNode.setMinHeight(node.minHeight)+ if (node.maxHeight != null) yogaNode.setMaxHeight(node.maxHeight)+}++export function mapGridTrack(track: GridTrack): { type: GridTrackType; value: number } {+ switch (track.sizing) {+ case 'FR':+ return { type: GridTrackType.Fr, value: track.value }+ case 'FIXED':+ return { type: GridTrackType.Points, value: track.value }+ default:+ return { type: GridTrackType.Auto, value: 0 }+ }+}++export function freeYogaTree(node: YogaNode): void {+ for (let i = node.getChildCount() - 1; i >= 0; i--) {+ freeYogaTree(node.getChild(i))+ }+ if ('free' in node) (node as { free(): void }).free()+}++export function mapJustify(align: string): Justify {+ switch (align) {+ case 'CENTER':+ return Justify.Center+ case 'MAX':+ return Justify.FlexEnd+ case 'SPACE_BETWEEN':+ return Justify.SpaceBetween+ default:+ return Justify.FlexStart+ }+}++export function mapAlign(align: string): Align {+ switch (align) {+ case 'CENTER':+ return Align.Center+ case 'MAX':+ return Align.FlexEnd+ case 'STRETCH':+ return Align.Stretch+ case 'BASELINE':+ return Align.Baseline+ default:+ return Align.FlexStart+ }+}++export function mapAlignSelf(alignSelf: string): Align | null {+ switch (alignSelf) {+ case 'MIN':+ return Align.FlexStart+ case 'CENTER':+ return Align.Center+ case 'MAX':+ return Align.FlexEnd+ case 'STRETCH':+ return Align.Stretch+ case 'BASELINE':+ return Align.Baseline+ default:+ return null+ }+}diff --git a/packages/core/src/lint/linter.ts b/packages/core/src/lint/linter.tsindex 5be82919b..64da8479c 100644--- a/packages/core/src/lint/linter.ts+++ b/packages/core/src/lint/linter.ts@@ -2,7 +2,7 @@ import { presets } from './presets'import { allRules } from './rules'import { getNodePath } from './utils'-import type { SceneGraph, SceneNode } from '../scene-graph'+import type { SceneGraph, SceneNode } from '#core/scene-graph'import type {LintConfig,LintMessage,diff --git a/packages/core/src/lint/rules/color-contrast.ts b/packages/core/src/lint/rules/color-contrast.tsindex 4caa8f3a6..5e855b34e 100644--- a/packages/core/src/lint/rules/color-contrast.ts+++ b/packages/core/src/lint/rules/color-contrast.ts@@ -1,5 +1,5 @@-import { defineRule } from '../rule'-import { contrastRatio } from '../utils'+import { defineRule } from '#core/lint/rule'+import { contrastRatio } from '#core/lint/utils'export default defineRule({meta: {diff --git a/packages/core/src/lint/rules/consistent-radius.ts b/packages/core/src/lint/rules/consistent-radius.tsindex 5bea350b1..89ed17c52 100644--- a/packages/core/src/lint/rules/consistent-radius.ts+++ b/packages/core/src/lint/rules/consistent-radius.ts@@ -1,4 +1,4 @@-import { defineRule } from '../rule'+import { defineRule } from '#core/lint/rule'const SCALE = [0, 2, 4, 6, 8, 12, 16, 20, 24, 32, 9999]export default defineRule({meta: {diff --git a/packages/core/src/lint/rules/consistent-spacing.ts b/packages/core/src/lint/rules/consistent-spacing.tsindex 248450acc..a97b01117 100644--- a/packages/core/src/lint/rules/consistent-spacing.ts+++ b/packages/core/src/lint/rules/consistent-spacing.ts@@ -1,5 +1,5 @@-import { defineRule } from '../rule'-import { isMultipleOf, SPACING_SCALE } from '../utils'+import { defineRule } from '#core/lint/rule'+import { isMultipleOf, SPACING_SCALE } from '#core/lint/utils'export default defineRule({meta: {diff --git a/packages/core/src/lint/rules/effect-style-required.ts b/packages/core/src/lint/rules/effect-style-required.tsindex 16e59ae7c..9d95e1d5f 100644--- a/packages/core/src/lint/rules/effect-style-required.ts+++ b/packages/core/src/lint/rules/effect-style-required.ts@@ -1,4 +1,4 @@-import { defineRule } from '../rule'+import { defineRule } from '#core/lint/rule'export default defineRule({meta: {diff --git a/packages/core/src/lint/rules/index.ts b/packages/core/src/lint/rules/index.tsindex 8be8088f0..855c83aa2 100644--- a/packages/core/src/lint/rules/index.ts+++ b/packages/core/src/lint/rules/index.ts@@ -34,7 +34,7 @@ import preferAutoLayout from './prefer-auto-layout'import textStyleRequired from './text-style-required'import touchTargetSize from './touch-target-size'-import type { Rule } from '../types'+import type { Rule } from '#core/lint/types'export const allRules: Record<string, Rule> = {'no-hardcoded-colors': noHardcodedColors,diff --git a/packages/core/src/lint/rules/min-text-size.ts b/packages/core/src/lint/rules/min-text-size.tsindex a23701183..4a93dceec 100644--- a/packages/core/src/lint/rules/min-text-size.ts+++ b/packages/core/src/lint/rules/min-text-size.ts@@ -1,4 +1,4 @@-import { defineRule } from '../rule'+import { defineRule } from '#core/lint/rule'export default defineRule({meta: {diff --git a/packages/core/src/lint/rules/no-deeply-nested.ts b/packages/core/src/lint/rules/no-deeply-nested.tsindex b44f0a16c..c07542ad2 100644--- a/packages/core/src/lint/rules/no-deeply-nested.ts+++ b/packages/core/src/lint/rules/no-deeply-nested.ts@@ -1,4 +1,4 @@-import { defineRule } from '../rule'+import { defineRule } from '#core/lint/rule'export default defineRule({meta: {diff --git a/packages/core/src/lint/rules/no-default-names.ts b/packages/core/src/lint/rules/no-default-names.tsindex 13edd6331..7c0dcc615 100644--- a/packages/core/src/lint/rules/no-default-names.ts+++ b/packages/core/src/lint/rules/no-default-names.ts@@ -1,5 +1,5 @@-import { defineRule } from '../rule'-import { isDefaultName } from '../utils'+import { defineRule } from '#core/lint/rule'+import { isDefaultName } from '#core/lint/utils'export default defineRule({meta: {diff --git a/packages/core/src/lint/rules/no-detached-instances.ts b/packages/core/src/lint/rules/no-detached-instances.tsindex f1eee1ca1..f7475fcf6 100644--- a/packages/core/src/lint/rules/no-detached-instances.ts+++ b/packages/core/src/lint/rules/no-detached-instances.ts@@ -1,4 +1,4 @@-import { defineRule } from '../rule'+import { defineRule } from '#core/lint/rule'const PATTERNS = [/^(button|btn)/i,/^(input|field|text-?field)/i,diff --git a/packages/core/src/lint/rules/no-empty-frames.ts b/packages/core/src/lint/rules/no-empty-frames.tsindex 561f314d4..9f807cb70 100644--- a/packages/core/src/lint/rules/no-empty-frames.ts+++ b/packages/core/src/lint/rules/no-empty-frames.ts@@ -1,4 +1,4 @@-import { defineRule } from '../rule'+import { defineRule } from '#core/lint/rule'export default defineRule({meta: {id: 'no-empty-frames',diff --git a/packages/core/src/lint/rules/no-groups.ts b/packages/core/src/lint/rules/no-groups.tsindex cf5408ed3..3baf18927 100644--- a/packages/core/src/lint/rules/no-groups.ts+++ b/packages/core/src/lint/rules/no-groups.ts@@ -1,4 +1,4 @@-import { defineRule } from '../rule'+import { defineRule } from '#core/lint/rule'export default defineRule({meta: {id: 'no-groups',diff --git a/packages/core/src/lint/rules/no-hardcoded-colors.ts b/packages/core/src/lint/rules/no-hardcoded-colors.tsindex d42ac7d3b..f419fa1bd 100644--- a/packages/core/src/lint/rules/no-hardcoded-colors.ts+++ b/packages/core/src/lint/rules/no-hardcoded-colors.ts@@ -1,4 +1,4 @@-import { defineRule } from '../rule'+import { defineRule } from '#core/lint/rule'export default defineRule({meta: {diff --git a/packages/core/src/lint/rules/no-hidden-layers.ts b/packages/core/src/lint/rules/no-hidden-layers.tsindex 1819a834d..e378789d7 100644--- a/packages/core/src/lint/rules/no-hidden-layers.ts+++ b/packages/core/src/lint/rules/no-hidden-layers.ts@@ -1,4 +1,4 @@-import { defineRule } from '../rule'+import { defineRule } from '#core/lint/rule'export default defineRule({meta: {id: 'no-hidden-layers',diff --git a/packages/core/src/lint/rules/no-mixed-styles.ts b/packages/core/src/lint/rules/no-mixed-styles.tsindex 77d123ee2..9f3044a96 100644--- a/packages/core/src/lint/rules/no-mixed-styles.ts+++ b/packages/core/src/lint/rules/no-mixed-styles.ts@@ -1,4 +1,4 @@-import { defineRule } from '../rule'+import { defineRule } from '#core/lint/rule'export default defineRule({meta: {diff --git a/packages/core/src/lint/rules/pixel-perfect.ts b/packages/core/src/lint/rules/pixel-perfect.tsindex 4990d1239..4a16f1f31 100644--- a/packages/core/src/lint/rules/pixel-perfect.ts+++ b/packages/core/src/lint/rules/pixel-perfect.ts@@ -1,4 +1,4 @@-import { defineRule } from '../rule'+import { defineRule } from '#core/lint/rule'export default defineRule({meta: {diff --git a/packages/core/src/lint/rules/prefer-auto-layout.ts b/packages/core/src/lint/rules/prefer-auto-layout.tsindex a1796d497..66dd0faba 100644--- a/packages/core/src/lint/rules/prefer-auto-layout.ts+++ b/packages/core/src/lint/rules/prefer-auto-layout.ts@@ -1,4 +1,4 @@-import { defineRule } from '../rule'+import { defineRule } from '#core/lint/rule'export default defineRule({meta: {diff --git a/packages/core/src/lint/rules/text-style-required.ts b/packages/core/src/lint/rules/text-style-required.tsindex 8a93a38b6..fde11bc30 100644--- a/packages/core/src/lint/rules/text-style-required.ts+++ b/packages/core/src/lint/rules/text-style-required.ts@@ -1,4 +1,4 @@-import { defineRule } from '../rule'+import { defineRule } from '#core/lint/rule'export default defineRule({meta: {diff --git a/packages/core/src/lint/rules/touch-target-size.ts b/packages/core/src/lint/rules/touch-target-size.tsindex c8075cd0b..92b1802aa 100644--- a/packages/core/src/lint/rules/touch-target-size.ts+++ b/packages/core/src/lint/rules/touch-target-size.ts@@ -1,4 +1,4 @@-import { defineRule } from '../rule'+import { defineRule } from '#core/lint/rule'const PATTERNS = [/button/i,/btn/i,diff --git a/packages/core/src/profiler/capture-session.ts b/packages/core/src/profiler/capture-session.tsnew file mode 100644index 000000000..842048f78--- /dev/null+++ b/packages/core/src/profiler/capture-session.ts@@ -0,0 +1,35 @@+import { CaptureStack } from './frame/capture'++import type { FrameStats } from './frame/stats'+import type { GPUTimer } from './gpu-timer'+import type { FrameCapture } from './frame/capture'++export type CaptureSession = {+ stack: CaptureStack+ frameStart: number+}++export function createCaptureSession(frameStart: number): CaptureSession {+ const stack = new CaptureStack()+ stack.reset(frameStart)+ return { stack, frameStart }+}++export function createFrameCapture(+ session: CaptureSession,+ stats: FrameStats,+ gpuTimer: GPUTimer,+ now: () => number+): FrameCapture {+ return {+ timestamp: session.frameStart,+ totalTimeMs: now() - session.frameStart,+ cpuTimeMs: stats.cpuTime,+ gpuTimeMs: gpuTimer.lastGpuTimeMs,+ totalNodes: stats.totalNodes,+ culledNodes: stats.culledNodes,+ drawCalls: stats.drawCalls,+ scenePictureCacheHit: stats.scenePictureCacheHit,+ rootProfiles: session.stack.getRootProfiles()+ }+}diff --git a/packages/core/src/profiler/frame-capture.ts b/packages/core/src/profiler/frame/capture.tssimilarity index 100%rename from packages/core/src/profiler/frame-capture.tsrename to packages/core/src/profiler/frame/capture.tsdiff --git a/packages/core/src/profiler/frame-stats.ts b/packages/core/src/profiler/frame/stats.tssimilarity index 100%rename from packages/core/src/profiler/frame-stats.tsrename to packages/core/src/profiler/frame/stats.tsdiff --git a/packages/core/src/profiler/hud-controller.ts b/packages/core/src/profiler/hud-controller.tsnew file mode 100644index 000000000..b2bf413a1--- /dev/null+++ b/packages/core/src/profiler/hud-controller.ts@@ -0,0 +1,30 @@+import { HudRenderer } from './hud-renderer'++import type { FrameStats } from './frame/stats'+import type { PhaseTimer } from './phase-timer'+import type { CanvasKit, Canvas, Typeface } from 'canvaskit-wasm'++export class HudController {+ private hud: HudRenderer | null = null+ private typeface: Typeface | null = null++ constructor(private ck: CanvasKit) {}++ setTypeface(typeface: Typeface): void {+ this.typeface = typeface+ this.hud?.setTypeface(typeface)+ }++ draw(canvas: Canvas, stats: FrameStats, phases: PhaseTimer, showRulers: boolean): void {+ if (!this.hud) {+ this.hud = new HudRenderer(this.ck)+ if (this.typeface) this.hud.setTypeface(this.typeface)+ }+ this.hud.draw(canvas, stats, phases.averages, showRulers)+ }++ destroy(): void {+ this.hud?.destroy()+ this.hud = null+ }+}diff --git a/packages/core/src/profiler/hud-renderer.ts b/packages/core/src/profiler/hud-renderer.tsindex 394ea93fe..f61e72b97 100644--- a/packages/core/src/profiler/hud-renderer.ts+++ b/packages/core/src/profiler/hud-renderer.ts@@ -1,4 +1,4 @@-import type { FrameStats } from './frame-stats'+import type { FrameStats } from './frame/stats'import type { CanvasKit, Canvas, Paint, Font, Typeface } from 'canvaskit-wasm'const BUFFER_SIZE = 120diff --git a/packages/core/src/profiler/index.ts b/packages/core/src/profiler/index.tsindex f2eb6daa3..0b4921ef4 100644--- a/packages/core/src/profiler/index.ts+++ b/packages/core/src/profiler/index.ts@@ -1,8 +1,8 @@export { RenderProfiler } from './render-profiler'-export { FrameStats } from './frame-stats'+export { FrameStats } from './frame/stats'export { GPUTimer } from './gpu-timer'export { DrawCallCounter } from './draw-call-counter'export { PhaseTimer } from './phase-timer'export { HudRenderer } from './hud-renderer'-export { CaptureStack, toSpeedscopeJSON } from './frame-capture'-export type { NodeProfile, FrameCapture } from './frame-capture'+export { CaptureStack, toSpeedscopeJSON } from './frame/capture'+export type { NodeProfile, FrameCapture } from './frame/capture'diff --git a/packages/core/src/profiler/render-profiler.ts b/packages/core/src/profiler/render-profiler.tsindex d2abc2020..193b44d38 100644--- a/packages/core/src/profiler/render-profiler.ts+++ b/packages/core/src/profiler/render-profiler.ts@@ -1,11 +1,13 @@+import { createCaptureSession, createFrameCapture } from './capture-session'import { DrawCallCounter } from './draw-call-counter'-import { CaptureStack, toSpeedscopeJSON } from './frame-capture'-import { FrameStats } from './frame-stats'+import { FrameStats } from './frame/stats'import { GPUTimer } from './gpu-timer'-import { HudRenderer } from './hud-renderer'+import { HudController } from './hud-controller'import { PhaseTimer } from './phase-timer'+import { exportSpeedscopeCapture } from './speedscope-export'-import type { FrameCapture } from './frame-capture'+import type { CaptureSession } from './capture-session'+import type { FrameCapture } from './frame/capture'import type { CanvasKit, Canvas, Typeface } from 'canvaskit-wasm'const now = typeof performance !== 'undefined' ? () => performance.now() : () => 0@@ -20,19 +22,18 @@ export class RenderProfiler {readonly gpuTimer: GPUTimerreadonly drawCallCounter: DrawCallCounter- private hud: HudRenderer | null = null- private typeface: Typeface | null = null- private captureStack: CaptureStack | null = null- private captureFrameStart = 0+ private readonly hud: HudController+ private captureSession: CaptureSession | null = nullprivate lastCapture: FrameCapture | null = nullprivate renderStartTime = 0constructor(- private ck: CanvasKit,+ ck: CanvasKit,gl: WebGL2RenderingContext | null) {this.gpuTimer = new GPUTimer(gl)this.drawCallCounter = new DrawCallCounter(gl)+ this.hud = new HudController(ck)}toggle(): void {@@ -84,38 +85,25 @@ export class RenderProfiler {beginCapture(): void {this.capturing = true- this.captureStack = new CaptureStack()- this.captureFrameStart = now()- this.captureStack.reset(this.captureFrameStart)+ this.captureSession = createCaptureSession(now())}endCapture(): FrameCapture | null {- if (!this.capturing || !this.captureStack) return null+ if (!this.capturing || !this.captureSession) return nullthis.capturing = false- const capture: FrameCapture = {- timestamp: this.captureFrameStart,- totalTimeMs: now() - this.captureFrameStart,- cpuTimeMs: this.stats.cpuTime,- gpuTimeMs: this.gpuTimer.lastGpuTimeMs,- totalNodes: this.stats.totalNodes,- culledNodes: this.stats.culledNodes,- drawCalls: this.stats.drawCalls,- scenePictureCacheHit: this.stats.scenePictureCacheHit,- rootProfiles: this.captureStack.getRootProfiles()- }-+ const capture = createFrameCapture(this.captureSession, this.stats, this.gpuTimer, now)this.lastCapture = capture- this.captureStack = null+ this.captureSession = nullreturn capture}beginNode(nodeId: string, name: string, type: string, culled: boolean): void {- this.captureStack?.begin(nodeId, name, type, culled)+ this.captureSession?.stack.begin(nodeId, name, type, culled)}endNode(drawCallsBefore: number): void {- this.captureStack?.end(this.drawCallCounter.count - drawCallsBefore)+ this.captureSession?.stack.end(this.drawCallCounter.count - drawCallsBefore)}getLastCapture(): FrameCapture | null {@@ -123,8 +111,7 @@ export class RenderProfiler {}exportSpeedscope(): string | null {- if (!this.lastCapture) return null- return toSpeedscopeJSON(this.lastCapture)+ return exportSpeedscopeCapture(this.lastCapture)}downloadSpeedscope(): void {@@ -140,24 +127,18 @@ export class RenderProfiler {}setTypeface(typeface: Typeface): void {- this.typeface = typeface- this.hud?.setTypeface(typeface)+ this.hud.setTypeface(typeface)}drawHUD(canvas: Canvas, showRulers: boolean): void {if (!this.hudVisible) return- if (!this.hud) {- this.hud = new HudRenderer(this.ck)- if (this.typeface) this.hud.setTypeface(this.typeface)- }- this.hud.draw(canvas, this.stats, this.phases.averages, showRulers)+ this.hud.draw(canvas, this.stats, this.phases, showRulers)}destroy(): void {this.gpuTimer.destroy()this.drawCallCounter.destroy()- this.hud?.destroy()- this.hud = null+ this.hud.destroy()this.phases.clearPhases()}}diff --git a/packages/core/src/profiler/speedscope-export.ts b/packages/core/src/profiler/speedscope-export.tsnew file mode 100644index 000000000..4f63c5be0--- /dev/null+++ b/packages/core/src/profiler/speedscope-export.ts@@ -0,0 +1,7 @@+import { toSpeedscopeJSON } from './frame/capture'++import type { FrameCapture } from './frame/capture'++export function exportSpeedscopeCapture(capture: FrameCapture | null): string | null {+ return capture ? toSpeedscopeJSON(capture) : null+}diff --git a/packages/core/src/random.ts b/packages/core/src/random.tsindex 5f2244672..79764fdba 100644--- a/packages/core/src/random.ts+++ b/packages/core/src/random.ts@@ -1,4 +1,7 @@export function randomHex(bytes = 16): string {+ if (!Number.isInteger(bytes) || bytes < 0) {+ throw new RangeError('bytes must be a non-negative integer')+ }const buf = crypto.getRandomValues(new Uint8Array(bytes))let hex = ''for (const b of buf) hex += b.toString(16).padStart(2, '0')@@ -10,5 +13,16 @@ export function randomInt(): number {}export function randomIndex(length: number): number {- return crypto.getRandomValues(new Uint8Array(1))[0] % length+ if (!Number.isInteger(length) || length <= 0) {+ throw new RangeError('length must be a positive integer')+ }+ const max = 0x1_0000_0000+ const limit = max - (max % length)+ const buffer = new Uint32Array(1)++ do {+ crypto.getRandomValues(buffer)+ } while (buffer[0] >= limit)++ return buffer[0] % length}diff --git a/packages/core/src/rpc/analyze-commands.ts b/packages/core/src/rpc/analyze-commands.tsnew file mode 100644index 000000000..aec600cdc--- /dev/null+++ b/packages/core/src/rpc/analyze-commands.ts@@ -0,0 +1,299 @@+import { colorToHex, colorDistance as colorDist } from '#core/color'++import type { SceneGraph, SceneNode } from '#core/scene-graph'+import type { Color } from '#core/types'+import type { RpcCommand } from './types'++// ── analyze colors ──++export interface AnalyzeColorsArgs {+ threshold?: number+ similar?: boolean+}++interface ColorInfo {+ hex: string+ color: Color+ count: number+ variableName: string | null+}++interface ColorCluster {+ colors: ColorInfo[]+ suggestedHex: string+ totalCount: number+}++function clusterColors(colors: ColorInfo[], threshold: number): ColorCluster[] {+ const clusters: ColorCluster[] = []+ const used = new Set<string>()+ const sorted = [...colors].sort((a, b) => b.count - a.count)++ for (const color of sorted) {+ if (used.has(color.hex)) continue+ const cluster: ColorCluster = {+ colors: [color],+ suggestedHex: color.hex,+ totalCount: color.count+ }+ used.add(color.hex)++ for (const other of sorted) {+ if (used.has(other.hex)) continue+ if (colorDist(color.color, other.color) <= threshold) {+ cluster.colors.push(other)+ cluster.totalCount += other.count+ used.add(other.hex)+ }+ }++ if (cluster.colors.length > 1) clusters.push(cluster)+ }++ return clusters.sort((a, b) => b.colors.length - a.colors.length)+}++function collectColors(graph: SceneGraph): { colors: ColorInfo[]; totalNodes: number } {+ const colorMap = new Map<string, ColorInfo>()+ let totalNodes = 0++ const addColor = (c: Color, variableName: string | null) => {+ const hex = colorToHex(c).toLowerCase()+ const existing = colorMap.get(hex)+ if (existing) {+ existing.count+++ if (variableName && !existing.variableName) existing.variableName = variableName+ } else {+ colorMap.set(hex, { hex, color: c, count: 1, variableName })+ }+ }++ for (const node of graph.getAllNodes()) {+ if (node.type === 'CANVAS') continue+ totalNodes++++ for (const fill of node.fills) {+ if (!fill.visible || fill.type !== 'SOLID') continue+ addColor(fill.color, null)+ }+ for (const stroke of node.strokes) {+ if (!stroke.visible) continue+ addColor(stroke.color, null)+ }+ for (const effect of node.effects) {+ if (!effect.visible) continue+ addColor(effect.color, null)+ }++ for (const [field, varId] of Object.entries(node.boundVariables)) {+ if (!field.includes('fill') && !field.includes('stroke') && !field.includes('color')) continue+ const variable = graph.variables.get(varId)+ if (variable) {+ const resolvedColor = graph.resolveColorVariable(varId)+ if (resolvedColor) {+ const hex = colorToHex(resolvedColor).toLowerCase()+ const existing = colorMap.get(hex)+ if (existing) existing.variableName = variable.name+ }+ }+ }+ }++ return { colors: [...colorMap.values()], totalNodes }+}++export interface AnalyzeColorsResult {+ colors: ColorInfo[]+ totalNodes: number+ clusters: ColorCluster[]+}++export const analyzeColorsCommand: RpcCommand<AnalyzeColorsArgs, AnalyzeColorsResult> = {+ name: 'analyze_colors',+ execute: (graph, args) => {+ const { colors, totalNodes } = collectColors(graph)+ const clusters = args.similar+ ? clusterColors(+ colors.filter((c) => !c.variableName),+ args.threshold ?? 15+ )+ : []+ return { colors: colors.sort((a, b) => b.count - a.count), totalNodes, clusters }+ }+}++// ── analyze typography ──++export interface AnalyzeTypographyArgs {}++export interface TypographyStyle {+ family: string+ size: number+ weight: number+ lineHeight: string+ count: number+}++export interface AnalyzeTypographyResult {+ styles: TypographyStyle[]+ totalTextNodes: number+}++export const analyzeTypographyCommand: RpcCommand<AnalyzeTypographyArgs, AnalyzeTypographyResult> =+ {+ name: 'analyze_typography',+ execute: (graph) => {+ const styleMap = new Map<string, TypographyStyle>()+ let totalTextNodes = 0++ for (const node of graph.getAllNodes()) {+ if (node.type !== 'TEXT') continue+ totalTextNodes++++ const lh = node.lineHeight === null ? 'auto' : `${node.lineHeight}px`+ const key = `${node.fontFamily}|${node.fontSize}|${node.fontWeight}|${lh}`+ const existing = styleMap.get(key)+ if (existing) {+ existing.count+++ } else {+ styleMap.set(key, {+ family: node.fontFamily,+ size: node.fontSize,+ weight: node.fontWeight,+ lineHeight: lh,+ count: 1+ })+ }+ }++ return { styles: [...styleMap.values()].sort((a, b) => b.count - a.count), totalTextNodes }+ }+ }++// ── analyze spacing ──++export interface SpacingValue {+ value: number+ count: number+}++export interface AnalyzeSpacingResult {+ gaps: SpacingValue[]+ paddings: SpacingValue[]+ totalNodes: number+}++export const analyzeSpacingCommand: RpcCommand<void, AnalyzeSpacingResult> = {+ name: 'analyze_spacing',+ execute: (graph) => {+ const gapMap = new Map<number, number>()+ const paddingMap = new Map<number, number>()+ let totalNodes = 0++ for (const node of graph.getAllNodes()) {+ if (node.type === 'CANVAS' || node.layoutMode === 'NONE') continue+ totalNodes++++ if (node.itemSpacing > 0)+ gapMap.set(node.itemSpacing, (gapMap.get(node.itemSpacing) ?? 0) + 1)+ if (node.counterAxisSpacing > 0)+ gapMap.set(node.counterAxisSpacing, (gapMap.get(node.counterAxisSpacing) ?? 0) + 1)++ for (const pad of [+ node.paddingTop,+ node.paddingRight,+ node.paddingBottom,+ node.paddingLeft+ ]) {+ if (pad > 0) paddingMap.set(pad, (paddingMap.get(pad) ?? 0) + 1)+ }+ }++ const toValues = (map: Map<number, number>) =>+ [...map.entries()]+ .map(([value, count]) => ({ value, count }))+ .sort((a, b) => b.count - a.count)++ return { gaps: toValues(gapMap), paddings: toValues(paddingMap), totalNodes }+ }+}++// ── analyze clusters ──++export interface AnalyzeClustersArgs {+ limit?: number+ minSize?: number+ minCount?: number+}++interface ClusterNode {+ id: string+ name: string+ type: string+ width: number+ height: number+ childCount: number+}++export interface AnalyzeClustersResult {+ clusters: Array<{+ signature: string+ nodes: ClusterNode[]+ }>+ totalNodes: number+}++function buildSignature(graph: SceneGraph, node: SceneNode): string {+ const childTypes = new Map<string, number>()+ for (const childId of node.childIds) {+ const child = graph.getNode(childId)+ if (!child) continue+ childTypes.set(child.type, (childTypes.get(child.type) ?? 0) + 1)+ }+ const childPart = [...childTypes.entries()]+ .sort((a, b) => a[0].localeCompare(b[0]))+ .map(([t, c]) => `${t}:${c}`)+ .join(',')+ const w = Math.round(node.width / 10) * 10+ const h = Math.round(node.height / 10) * 10+ return `${node.type}:${w}x${h}|${childPart}`+}++export const analyzeClustersCommand: RpcCommand<AnalyzeClustersArgs, AnalyzeClustersResult> = {+ name: 'analyze_clusters',+ execute: (graph, args) => {+ const minSize = args.minSize ?? 30+ const minCount = args.minCount ?? 2+ const limit = args.limit ?? 20+ const sigMap = new Map<string, ClusterNode[]>()+ let totalNodes = 0++ for (const node of graph.getAllNodes()) {+ if (node.type === 'CANVAS') continue+ totalNodes+++ if (node.width < minSize || node.height < minSize) continue+ if (node.childIds.length === 0) continue++ const sig = buildSignature(graph, node)+ const arr = sigMap.get(sig) ?? []+ arr.push({+ id: node.id,+ name: node.name,+ type: node.type,+ width: Math.round(node.width),+ height: Math.round(node.height),+ childCount: node.childIds.length+ })+ sigMap.set(sig, arr)+ }++ const clusters = [...sigMap.entries()]+ .filter(([, nodes]) => nodes.length >= minCount)+ .map(([signature, nodes]) => ({ signature, nodes }))+ .sort((a, b) => b.nodes.length - a.nodes.length)+ .slice(0, limit)++ return { clusters, totalNodes }+ }+}+diff --git a/packages/core/src/rpc/commands.ts b/packages/core/src/rpc/commands.tsindex c29814ec7..70ca1a90b 100644--- a/packages/core/src/rpc/commands.ts+++ b/packages/core/src/rpc/commands.ts@@ -1,711 +1,26 @@-/* eslint-disable max-lines -- RPC commands are cohesive; splitting adds indirection */-import { colorToHex, colorDistance as colorDist } from '../color'-import { queryByXPath } from '../xpath'--import type { SceneGraph, SceneNode, Variable } from '../scene-graph'-import type { Color } from '../types'--export interface RpcCommand<A = unknown, R = unknown> {- name: string- execute: (graph: SceneGraph, args: A) => R | Promise<R>-}--/** Walk descendants. Callback returns `false` to stop traversal. */-function walkNodes(graph: SceneGraph, rootId: string, fn: (node: SceneNode) => boolean): boolean {- const node = graph.getNode(rootId)- if (!node) return true- if (!fn(node)) return false- for (const childId of node.childIds) {- if (!walkNodes(graph, childId, fn)) return false- }- return true-}--function countNodes(graph: SceneGraph, pageId: string): number {- let count = 0- const page = graph.getNode(pageId)- if (page)- for (const cid of page.childIds)- walkNodes(graph, cid, () => {- count++- return true- })- return count-}--// ── info ──--export interface InfoResult {- pages: number- totalNodes: number- types: Record<string, number>- fonts: string[]- pageCounts: Record<string, number>-}--export const infoCommand: RpcCommand<void, InfoResult> = {- name: 'info',- execute: (graph) => {- const pages = graph.getPages()- let totalNodes = 0- const types: Record<string, number> = {}- const fonts = new Set<string>()- const pageCounts: Record<string, number> = {}-- for (const page of pages) {- let pageCount = 0- for (const cid of page.childIds) {- walkNodes(graph, cid, (node) => {- totalNodes++- pageCount++- types[node.type] = (types[node.type] ?? 0) + 1- if (node.fontFamily) fonts.add(node.fontFamily)- return true- })- }- pageCounts[page.name] = pageCount- }-- return { pages: pages.length, totalNodes, types, fonts: [...fonts].sort(), pageCounts }- }-}--// ── pages ──--export interface PageItem {- id: string- name: string- nodes: number-}--export const pagesCommand: RpcCommand<void, PageItem[]> = {- name: 'pages',- execute: (graph) => {- return graph.getPages().map((p) => ({ id: p.id, name: p.name, nodes: countNodes(graph, p.id) }))- }-}--// ── tree ──--export interface TreeArgs {- page?: string- depth?: number-}--export interface TreeNodeResult {- id: string- name: string- type: string- x: number- y: number- width: number- height: number- children?: TreeNodeResult[]-}--function buildTreeNode(- graph: SceneGraph,- id: string,- depth: number,- maxDepth: number-): TreeNodeResult | null {- const node = graph.getNode(id)- if (!node) return null- const result: TreeNodeResult = {- id: node.id,- name: node.name,- type: node.type,- x: Math.round(node.x),- y: Math.round(node.y),- width: Math.round(node.width),- height: Math.round(node.height)- }- if (node.childIds.length > 0 && depth < maxDepth) {- result.children = node.childIds- .map((cid) => buildTreeNode(graph, cid, depth + 1, maxDepth))- .filter((n): n is TreeNodeResult => n !== null)- }- return result-}--export interface TreeResult {- page: { id: string; name: string; type: string }- children: TreeNodeResult[]-}--export const treeCommand: RpcCommand<TreeArgs, TreeResult | { error: string }> = {- name: 'tree',- execute: (graph, args) => {- const pages = graph.getPages()- const maxDepth = args.depth ?? Infinity- const page = args.page ? pages.find((p) => p.name === args.page) : pages[0]- if (!page)- return {- error: `Page "${args.page}" not found. Available: ${pages.map((p) => p.name).join(', ')}`- }-- return {- page: { id: page.id, name: page.name, type: page.type },- children: page.childIds- .map((cid) => buildTreeNode(graph, cid, 0, maxDepth))- .filter((n): n is TreeNodeResult => n !== null)- }- }-}--// ── find ──--export interface FindArgs {- name?: string- type?: string- page?: string- limit?: number-}--export interface FindNodeResult {- id: string- name: string- type: string- width: number- height: number-}--export const findCommand: RpcCommand<FindArgs, FindNodeResult[]> = {- name: 'find',- execute: (graph, args) => {- const pages = graph.getPages()- const max = args.limit ?? 100- const namePattern = args.name?.toLowerCase()- const typeFilter = args.type?.toUpperCase()- const results: FindNodeResult[] = []-- const searchPage = (page: SceneNode) => {- for (const cid of page.childIds) {- const cont = walkNodes(graph, cid, (node) => {- if (results.length >= max) return false- const matchesName = !namePattern || node.name.toLowerCase().includes(namePattern)- const matchesType = !typeFilter || node.type === typeFilter- if (matchesName && matchesType) {- results.push({- id: node.id,- name: node.name,- type: node.type,- width: Math.round(node.width),- height: Math.round(node.height)- })- }- return true- })- if (!cont) break- }- }-- if (args.page) {- const page = pages.find((p) => p.name === args.page)- if (page) searchPage(page)- } else {- for (const page of pages) searchPage(page)- }-- return results- }-}--// ── query (xpath) ──--export interface QueryArgs {- selector: string- page?: string- limit?: number-}--export interface QueryNodeResult {- id: string- name: string- type: string- x: number- y: number- width: number- height: number-}--export const queryCommand: RpcCommand<QueryArgs, QueryNodeResult[] | { error: string }> = {- name: 'query',- execute: async (graph, args) => {- try {- const nodes = await queryByXPath(graph, args.selector, {- page: args.page,- limit: args.limit- })- return nodes.map((n) => ({- id: n.id,- name: n.name,- type: n.type,- x: Math.round(n.x),- y: Math.round(n.y),- width: Math.round(n.width),- height: Math.round(n.height)- }))- } catch (err) {- return { error: `XPath error: ${err instanceof Error ? err.message : String(err)}` }- }- }-}--// ── node ──--export interface NodeArgs {- id: string-}--export interface NodeResult {- id: string- name: string- type: string- x: number- y: number- width: number- height: number- visible: boolean- locked: boolean- opacity: number- rotation: number- fills: unknown[]- strokes: unknown[]- effects: unknown[]- cornerRadius: number- blendMode: string- layoutMode: string- layoutDirection: string- fontFamily: string- fontSize: number- fontWeight: number- textDirection: string- text: string | null- parent: { id: string; name: string; type: string } | null- children: number- boundVariables: Record<string, string>-}--export const nodeCommand: RpcCommand<NodeArgs, NodeResult | { error: string }> = {- name: 'node',- execute: (graph, args) => {- const node = graph.getNode(args.id)- if (!node) return { error: `Node "${args.id}" not found` }-- const parent = node.parentId ? graph.getNode(node.parentId) : undefined- const boundVars: Record<string, string> = {}- for (const [field, varId] of Object.entries(node.boundVariables)) {- const variable = graph.variables.get(varId)- boundVars[field] = variable?.name ?? varId- }-- return {- id: node.id,- name: node.name,- type: node.type,- x: Math.round(node.x),- y: Math.round(node.y),- width: Math.round(node.width),- height: Math.round(node.height),- visible: node.visible,- locked: node.locked,- opacity: node.opacity,- rotation: node.rotation,- fills: node.fills,- strokes: node.strokes,- effects: node.effects,- cornerRadius: node.cornerRadius,- blendMode: node.blendMode,- layoutMode: node.layoutMode,- layoutDirection: node.layoutDirection,- fontFamily: node.fontFamily,- fontSize: node.fontSize,- fontWeight: node.fontWeight,- textDirection: node.textDirection,- text: (() => {- if (!node.text.length) return null- if (node.text.length > 200) return node.text.slice(0, 200) + '…'- return node.text- })(),- parent: parent ? { id: parent.id, name: parent.name, type: parent.type } : null,- children: node.childIds.length,- boundVariables: boundVars- }- }-}--// ── variables ──--export interface VariablesArgs {- collection?: string- type?: string-}--function formatVariableValue(variable: Variable, graph: SceneGraph): string {- const modeId = graph.getActiveModeId(variable.collectionId)- const raw = variable.valuesByMode[modeId]-- if (typeof raw === 'object' && 'aliasId' in raw) {- const alias = graph.variables.get(raw.aliasId)- return alias ? `→ ${alias.name}` : `→ ${raw.aliasId}`- }-- if (typeof raw === 'object' && 'r' in raw) {- return colorToHex(raw).toLowerCase()- }-- return String(raw)-}--export interface VariablesResult {- collections: Array<{- id: string- name: string- modes: string[]- variables: Array<{- id: string- name: string- type: string- value: string- }>- }>- totalVariables: number- totalCollections: number-}--export const variablesCommand: RpcCommand<VariablesArgs, VariablesResult> = {- name: 'variables',- execute: (graph, args) => {- const typeFilter = args.type?.toUpperCase()- const collFilter = args.collection?.toLowerCase()-- const result: VariablesResult = {- collections: [],- totalVariables: graph.variables.size,- totalCollections: graph.variableCollections.size- }-- for (const coll of graph.variableCollections.values()) {- if (collFilter && !coll.name.toLowerCase().includes(collFilter)) continue-- const collVars = graph- .getVariablesForCollection(coll.id)- .filter((v) => !typeFilter || v.type === typeFilter)-- if (collVars.length === 0) continue-- result.collections.push({- id: coll.id,- name: coll.name,- modes: coll.modes.map((m) => m.name),- variables: collVars.map((v) => ({- id: v.id,- name: v.name,- type: v.type,- value: formatVariableValue(v, graph)- }))- })- }-- return result- }-}--// ── analyze colors ──--export interface AnalyzeColorsArgs {- threshold?: number- similar?: boolean-}--interface ColorInfo {- hex: string- color: Color- count: number- variableName: string | null-}--interface ColorCluster {- colors: ColorInfo[]- suggestedHex: string- totalCount: number-}--function clusterColors(colors: ColorInfo[], threshold: number): ColorCluster[] {- const clusters: ColorCluster[] = []- const used = new Set<string>()- const sorted = [...colors].sort((a, b) => b.count - a.count)-- for (const color of sorted) {- if (used.has(color.hex)) continue- const cluster: ColorCluster = {- colors: [color],- suggestedHex: color.hex,- totalCount: color.count- }- used.add(color.hex)-- for (const other of sorted) {- if (used.has(other.hex)) continue- if (colorDist(color.color, other.color) <= threshold) {- cluster.colors.push(other)- cluster.totalCount += other.count- used.add(other.hex)- }- }-- if (cluster.colors.length > 1) clusters.push(cluster)- }-- return clusters.sort((a, b) => b.colors.length - a.colors.length)-}--function collectColors(graph: SceneGraph): { colors: ColorInfo[]; totalNodes: number } {- const colorMap = new Map<string, ColorInfo>()- let totalNodes = 0-- const addColor = (c: Color, variableName: string | null) => {- const hex = colorToHex(c).toLowerCase()- const existing = colorMap.get(hex)- if (existing) {- existing.count++- if (variableName && !existing.variableName) existing.variableName = variableName- } else {- colorMap.set(hex, { hex, color: c, count: 1, variableName })- }- }-- for (const node of graph.getAllNodes()) {- if (node.type === 'CANVAS') continue- totalNodes++-- for (const fill of node.fills) {- if (!fill.visible || fill.type !== 'SOLID') continue- addColor(fill.color, null)- }- for (const stroke of node.strokes) {- if (!stroke.visible) continue- addColor(stroke.color, null)- }- for (const effect of node.effects) {- if (!effect.visible) continue- addColor(effect.color, null)- }-- for (const [field, varId] of Object.entries(node.boundVariables)) {- if (!field.includes('fill') && !field.includes('stroke') && !field.includes('color')) continue- const variable = graph.variables.get(varId)- if (variable) {- const resolvedColor = graph.resolveColorVariable(varId)- if (resolvedColor) {- const hex = colorToHex(resolvedColor).toLowerCase()- const existing = colorMap.get(hex)- if (existing) existing.variableName = variable.name- }- }- }- }-- return { colors: [...colorMap.values()], totalNodes }-}--export interface AnalyzeColorsResult {- colors: ColorInfo[]- totalNodes: number- clusters: ColorCluster[]-}--export const analyzeColorsCommand: RpcCommand<AnalyzeColorsArgs, AnalyzeColorsResult> = {- name: 'analyze_colors',- execute: (graph, args) => {- const { colors, totalNodes } = collectColors(graph)- const clusters = args.similar- ? clusterColors(- colors.filter((c) => !c.variableName),- args.threshold ?? 15- )- : []- return { colors: colors.sort((a, b) => b.count - a.count), totalNodes, clusters }- }-}--// ── analyze typography ──--export interface AnalyzeTypographyArgs {}--export interface TypographyStyle {- family: string- size: number- weight: number- lineHeight: string- count: number-}--export interface AnalyzeTypographyResult {- styles: TypographyStyle[]- totalTextNodes: number-}--export const analyzeTypographyCommand: RpcCommand<AnalyzeTypographyArgs, AnalyzeTypographyResult> =- {- name: 'analyze_typography',- execute: (graph) => {- const styleMap = new Map<string, TypographyStyle>()- let totalTextNodes = 0-- for (const node of graph.getAllNodes()) {- if (node.type !== 'TEXT') continue- totalTextNodes++-- const lh = node.lineHeight === null ? 'auto' : `${node.lineHeight}px`- const key = `${node.fontFamily}|${node.fontSize}|${node.fontWeight}|${lh}`- const existing = styleMap.get(key)- if (existing) {- existing.count++- } else {- styleMap.set(key, {- family: node.fontFamily,- size: node.fontSize,- weight: node.fontWeight,- lineHeight: lh,- count: 1- })- }- }-- return { styles: [...styleMap.values()].sort((a, b) => b.count - a.count), totalTextNodes }- }- }--// ── analyze spacing ──--export interface SpacingValue {- value: number- count: number-}--export interface AnalyzeSpacingResult {- gaps: SpacingValue[]- paddings: SpacingValue[]- totalNodes: number-}--export const analyzeSpacingCommand: RpcCommand<void, AnalyzeSpacingResult> = {- name: 'analyze_spacing',- execute: (graph) => {- const gapMap = new Map<number, number>()- const paddingMap = new Map<number, number>()- let totalNodes = 0-- for (const node of graph.getAllNodes()) {- if (node.type === 'CANVAS' || node.layoutMode === 'NONE') continue- totalNodes++-- if (node.itemSpacing > 0)- gapMap.set(node.itemSpacing, (gapMap.get(node.itemSpacing) ?? 0) + 1)- if (node.counterAxisSpacing > 0)- gapMap.set(node.counterAxisSpacing, (gapMap.get(node.counterAxisSpacing) ?? 0) + 1)-- for (const pad of [- node.paddingTop,- node.paddingRight,- node.paddingBottom,- node.paddingLeft- ]) {- if (pad > 0) paddingMap.set(pad, (paddingMap.get(pad) ?? 0) + 1)- }- }-- const toValues = (map: Map<number, number>) =>- [...map.entries()]- .map(([value, count]) => ({ value, count }))- .sort((a, b) => b.count - a.count)-- return { gaps: toValues(gapMap), paddings: toValues(paddingMap), totalNodes }- }-}--// ── analyze clusters ──--export interface AnalyzeClustersArgs {- limit?: number- minSize?: number- minCount?: number-}--interface ClusterNode {- id: string- name: string- type: string- width: number- height: number- childCount: number-}--export interface AnalyzeClustersResult {- clusters: Array<{- signature: string- nodes: ClusterNode[]- }>- totalNodes: number-}--function buildSignature(graph: SceneGraph, node: SceneNode): string {- const childTypes = new Map<string, number>()- for (const childId of node.childIds) {- const child = graph.getNode(childId)- if (!child) continue- childTypes.set(child.type, (childTypes.get(child.type) ?? 0) + 1)- }- const childPart = [...childTypes.entries()]- .sort((a, b) => a[0].localeCompare(b[0]))- .map(([t, c]) => `${t}:${c}`)- .join(',')- const w = Math.round(node.width / 10) * 10- const h = Math.round(node.height / 10) * 10- return `${node.type}:${w}x${h}|${childPart}`-}--export const analyzeClustersCommand: RpcCommand<AnalyzeClustersArgs, AnalyzeClustersResult> = {- name: 'analyze_clusters',- execute: (graph, args) => {- const minSize = args.minSize ?? 30- const minCount = args.minCount ?? 2- const limit = args.limit ?? 20- const sigMap = new Map<string, ClusterNode[]>()- let totalNodes = 0-- for (const node of graph.getAllNodes()) {- if (node.type === 'CANVAS') continue- totalNodes++- if (node.width < minSize || node.height < minSize) continue- if (node.childIds.length === 0) continue-- const sig = buildSignature(graph, node)- const arr = sigMap.get(sig) ?? []- arr.push({- id: node.id,- name: node.name,- type: node.type,- width: Math.round(node.width),- height: Math.round(node.height),- childCount: node.childIds.length- })- sigMap.set(sig, arr)- }-- const clusters = [...sigMap.entries()]- .filter(([, nodes]) => nodes.length >= minCount)- .map(([signature, nodes]) => ({ signature, nodes }))- .sort((a, b) => b.nodes.length - a.nodes.length)- .slice(0, limit)+import {+ findCommand,+ infoCommand,+ nodeCommand,+ pagesCommand,+ queryCommand,+ treeCommand+} from './read-commands'+import {+ analyzeClustersCommand,+ analyzeColorsCommand,+ analyzeSpacingCommand,+ analyzeTypographyCommand+} from './analyze-commands'+import { variablesCommand } from './variables-command'- return { clusters, totalNodes }- }-}+import type { SceneGraph } from '#core/scene-graph'+import type { RpcCommand } from './types'-// ── registry ──+export type { RpcCommand } from './types'+export * from './read-commands'+export * from './variables-command'+export * from './analyze-commands'export const ALL_RPC_COMMANDS = [infoCommand,diff --git a/packages/core/src/rpc/read-commands.ts b/packages/core/src/rpc/read-commands.tsnew file mode 100644index 000000000..5e8366525--- /dev/null+++ b/packages/core/src/rpc/read-commands.ts@@ -0,0 +1,333 @@+import { queryByXPath } from '#core/xpath'++import type { SceneGraph, SceneNode } from '#core/scene-graph'+import type { RpcCommand } from './types'++/** Walk descendants. Callback returns `false` to stop traversal. */+function walkNodes(graph: SceneGraph, rootId: string, fn: (node: SceneNode) => boolean): boolean {+ const node = graph.getNode(rootId)+ if (!node) return true+ if (!fn(node)) return false+ for (const childId of node.childIds) {+ if (!walkNodes(graph, childId, fn)) return false+ }+ return true+}++function countNodes(graph: SceneGraph, pageId: string): number {+ let count = 0+ const page = graph.getNode(pageId)+ if (page)+ for (const cid of page.childIds)+ walkNodes(graph, cid, () => {+ count+++ return true+ })+ return count+}++function nodeFrame(node: SceneNode) {+ return {+ x: Math.round(node.x),+ y: Math.round(node.y),+ width: Math.round(node.width),+ height: Math.round(node.height)+ }+}++// ── info ──++export interface InfoResult {+ pages: number+ totalNodes: number+ types: Record<string, number>+ fonts: string[]+ pageCounts: Record<string, number>+}++export const infoCommand: RpcCommand<void, InfoResult> = {+ name: 'info',+ execute: (graph) => {+ const pages = graph.getPages()+ let totalNodes = 0+ const types: Record<string, number> = {}+ const fonts = new Set<string>()+ const pageCounts: Record<string, number> = {}++ for (const page of pages) {+ let pageCount = 0+ for (const cid of page.childIds) {+ walkNodes(graph, cid, (node) => {+ totalNodes+++ pageCount+++ types[node.type] = (types[node.type] ?? 0) + 1+ if (node.fontFamily) fonts.add(node.fontFamily)+ return true+ })+ }+ pageCounts[page.name] = pageCount+ }++ return { pages: pages.length, totalNodes, types, fonts: [...fonts].sort(), pageCounts }+ }+}++// ── pages ──++export interface PageItem {+ id: string+ name: string+ nodes: number+}++export const pagesCommand: RpcCommand<void, PageItem[]> = {+ name: 'pages',+ execute: (graph) => {+ return graph.getPages().map((p) => ({ id: p.id, name: p.name, nodes: countNodes(graph, p.id) }))+ }+}++// ── tree ──++export interface TreeArgs {+ page?: string+ depth?: number+}++export interface TreeNodeResult {+ id: string+ name: string+ type: string+ x: number+ y: number+ width: number+ height: number+ children?: TreeNodeResult[]+}++function buildTreeNode(+ graph: SceneGraph,+ id: string,+ depth: number,+ maxDepth: number+): TreeNodeResult | null {+ const node = graph.getNode(id)+ if (!node) return null+ const result: TreeNodeResult = {+ id: node.id,+ name: node.name,+ type: node.type,+ ...nodeFrame(node)+ }+ if (node.childIds.length > 0 && depth < maxDepth) {+ result.children = node.childIds+ .map((cid) => buildTreeNode(graph, cid, depth + 1, maxDepth))+ .filter((n): n is TreeNodeResult => n !== null)+ }+ return result+}++export interface TreeResult {+ page: { id: string; name: string; type: string }+ children: TreeNodeResult[]+}++export const treeCommand: RpcCommand<TreeArgs, TreeResult | { error: string }> = {+ name: 'tree',+ execute: (graph, args) => {+ const pages = graph.getPages()+ const maxDepth = args.depth ?? Infinity+ const page = args.page ? pages.find((p) => p.name === args.page) : pages[0]+ if (!page)+ return {+ error: `Page "${args.page}" not found. Available: ${pages.map((p) => p.name).join(', ')}`+ }++ return {+ page: { id: page.id, name: page.name, type: page.type },+ children: page.childIds+ .map((cid) => buildTreeNode(graph, cid, 0, maxDepth))+ .filter((n): n is TreeNodeResult => n !== null)+ }+ }+}++// ── find ──++export interface FindArgs {+ name?: string+ type?: string+ page?: string+ limit?: number+}++export interface FindNodeResult {+ id: string+ name: string+ type: string+ width: number+ height: number+}++export const findCommand: RpcCommand<FindArgs, FindNodeResult[]> = {+ name: 'find',+ execute: (graph, args) => {+ const pages = graph.getPages()+ const max = args.limit ?? 100+ const namePattern = args.name?.toLowerCase()+ const typeFilter = args.type?.toUpperCase()+ const results: FindNodeResult[] = []++ const searchPage = (page: SceneNode) => {+ for (const cid of page.childIds) {+ const cont = walkNodes(graph, cid, (node) => {+ if (results.length >= max) return false+ const matchesName = !namePattern || node.name.toLowerCase().includes(namePattern)+ const matchesType = !typeFilter || node.type === typeFilter+ if (matchesName && matchesType) {+ results.push({+ id: node.id,+ name: node.name,+ type: node.type,+ width: Math.round(node.width),+ height: Math.round(node.height)+ })+ }+ return true+ })+ if (!cont) break+ }+ }++ if (args.page) {+ const page = pages.find((p) => p.name === args.page)+ if (page) searchPage(page)+ } else {+ for (const page of pages) searchPage(page)+ }++ return results+ }+}++// ── query (xpath) ──++export interface QueryArgs {+ selector: string+ page?: string+ limit?: number+}++export interface QueryNodeResult {+ id: string+ name: string+ type: string+ x: number+ y: number+ width: number+ height: number+}++export const queryCommand: RpcCommand<QueryArgs, QueryNodeResult[] | { error: string }> = {+ name: 'query',+ execute: async (graph, args) => {+ try {+ const nodes = await queryByXPath(graph, args.selector, {+ page: args.page,+ limit: args.limit+ })+ return nodes.map((n) => ({+ id: n.id,+ name: n.name,+ type: n.type,+ x: Math.round(n.x),+ y: Math.round(n.y),+ width: Math.round(n.width),+ height: Math.round(n.height)+ }))+ } catch (err) {+ return { error: `XPath error: ${err instanceof Error ? err.message : String(err)}` }+ }+ }+}++// ── node ──++export interface NodeArgs {+ id: string+}++export interface NodeResult {+ id: string+ name: string+ type: string+ x: number+ y: number+ width: number+ height: number+ visible: boolean+ locked: boolean+ opacity: number+ rotation: number+ fills: unknown[]+ strokes: unknown[]+ effects: unknown[]+ cornerRadius: number+ blendMode: string+ layoutMode: string+ layoutDirection: string+ fontFamily: string+ fontSize: number+ fontWeight: number+ textDirection: string+ text: string | null+ parent: { id: string; name: string; type: string } | null+ children: number+ boundVariables: Record<string, string>+}++export const nodeCommand: RpcCommand<NodeArgs, NodeResult | { error: string }> = {+ name: 'node',+ execute: (graph, args) => {+ const node = graph.getNode(args.id)+ if (!node) return { error: `Node "${args.id}" not found` }++ const parent = node.parentId ? graph.getNode(node.parentId) : undefined+ const boundVars: Record<string, string> = {}+ for (const [field, varId] of Object.entries(node.boundVariables)) {+ const variable = graph.variables.get(varId)+ boundVars[field] = variable?.name ?? varId+ }++ return {+ id: node.id,+ name: node.name,+ type: node.type,+ ...nodeFrame(node),+ visible: node.visible,+ locked: node.locked,+ opacity: node.opacity,+ rotation: node.rotation,+ fills: node.fills,+ strokes: node.strokes,+ effects: node.effects,+ cornerRadius: node.cornerRadius,+ blendMode: node.blendMode,+ layoutMode: node.layoutMode,+ layoutDirection: node.layoutDirection,+ fontFamily: node.fontFamily,+ fontSize: node.fontSize,+ fontWeight: node.fontWeight,+ textDirection: node.textDirection,+ text: (() => {+ if (!node.text.length) return null+ if (node.text.length > 200) return node.text.slice(0, 200) + '…'+ return node.text+ })(),+ parent: parent ? { id: parent.id, name: parent.name, type: parent.type } : null,+ children: node.childIds.length,+ boundVariables: boundVars+ }+ }+}+diff --git a/packages/core/src/rpc/types.ts b/packages/core/src/rpc/types.tsnew file mode 100644index 000000000..99814523d--- /dev/null+++ b/packages/core/src/rpc/types.ts@@ -0,0 +1,6 @@+import type { SceneGraph } from '#core/scene-graph'++export interface RpcCommand<A = unknown, R = unknown> {+ name: string+ execute: (graph: SceneGraph, args: A) => R | Promise<R>+}diff --git a/packages/core/src/rpc/variables-command.ts b/packages/core/src/rpc/variables-command.tsnew file mode 100644index 000000000..c3cf5b299--- /dev/null+++ b/packages/core/src/rpc/variables-command.ts@@ -0,0 +1,82 @@+import { colorToHex } from '#core/color'++import type { SceneGraph, Variable } from '#core/scene-graph'+import type { RpcCommand } from './types'++// ── variables ──++export interface VariablesArgs {+ collection?: string+ type?: string+}++function formatVariableValue(variable: Variable, graph: SceneGraph): string {+ const modeId = graph.getActiveModeId(variable.collectionId)+ const raw = variable.valuesByMode[modeId]++ if (typeof raw === 'object' && 'aliasId' in raw) {+ const alias = graph.variables.get(raw.aliasId)+ return alias ? `→ ${alias.name}` : `→ ${raw.aliasId}`+ }++ if (typeof raw === 'object' && 'r' in raw) {+ return colorToHex(raw).toLowerCase()+ }++ return String(raw)+}++export interface VariablesResult {+ collections: Array<{+ id: string+ name: string+ modes: string[]+ variables: Array<{+ id: string+ name: string+ type: string+ value: string+ }>+ }>+ totalVariables: number+ totalCollections: number+}++export const variablesCommand: RpcCommand<VariablesArgs, VariablesResult> = {+ name: 'variables',+ execute: (graph, args) => {+ const typeFilter = args.type?.toUpperCase()+ const collFilter = args.collection?.toLowerCase()++ const result: VariablesResult = {+ collections: [],+ totalVariables: graph.variables.size,+ totalCollections: graph.variableCollections.size+ }++ for (const coll of graph.variableCollections.values()) {+ if (collFilter && !coll.name.toLowerCase().includes(collFilter)) continue++ const collVars = graph+ .getVariablesForCollection(coll.id)+ .filter((v) => !typeFilter || v.type === typeFilter)++ if (collVars.length === 0) continue++ result.collections.push({+ id: coll.id,+ name: coll.name,+ modes: coll.modes.map((m) => m.name),+ variables: collVars.map((v) => ({+ id: v.id,+ name: v.name,+ type: v.type,+ value: formatVariableValue(v, graph)+ }))+ })+ }++ return result+ }+}+diff --git a/packages/core/src/scene-graph/hit-test.ts b/packages/core/src/scene-graph/hit-test.tsindex e9dfd534a..30dd46730 100644--- a/packages/core/src/scene-graph/hit-test.ts+++ b/packages/core/src/scene-graph/hit-test.ts@@ -1,6 +1,6 @@-import Matrix from '@open-pencil/core/canvas/matrix'+import Matrix from '#core/canvas/matrix'-import { getWorldMatrix } from '../canvas/coordinate'+import { getWorldMatrix } from '#core/canvas/coordinate'import type { SceneGraph, SceneNode, NodeType } from './'diff --git a/packages/core/src/scene-graph/index.ts b/packages/core/src/scene-graph/index.tsindex e373493c5..02f963fbe 100644--- a/packages/core/src/scene-graph/index.ts+++ b/packages/core/src/scene-graph/index.ts@@ -1,587 +1,40 @@-/* eslint-disable max-lines -- core class; instance, hit-test methods already extracted */-import { createNanoEvents } from 'nanoevents'--import { BLACK, DEFAULT_FONT_FAMILY, DEFAULT_STROKE_MITER_LIMIT } from '../constants'-import {- hitTest as hitTestFn,- hitTestDeep as hitTestDeepFn,- hitTestFrame as hitTestFrameFn-} from './hit-test'-import {- createInstance as createInstanceFn,- populateInstanceChildren as populateInstanceChildrenFn,- syncInstances as syncInstancesFn,- detachInstance as detachInstanceFn,- getMainComponent as getMainComponentFn,- getInstances as getInstancesFn-} from './instances'--export type { GUID, Color } from '../types'-import { getAbsolutePosition } from '@open-pencil/core/canvas/coordinate'--import type { Matrix, Vector, Color, Rect } from '../types'-import type { Emitter } from 'nanoevents'--export interface SceneGraphEvents {- 'node:created': (node: SceneNode) => void- 'node:updated': (id: string, changes: Partial<SceneNode>) => void- 'node:deleted': (id: string) => void- 'node:reparented': (nodeId: string, oldParentId: string | null, newParentId: string) => void- 'node:reordered': (nodeId: string, parentId: string, index: number) => void-}--export type DocumentColorSpace = 'srgb' | 'display-p3'--export type HandleMirroring = 'NONE' | 'ANGLE' | 'ANGLE_AND_LENGTH'-export type WindingRule = 'NONZERO' | 'EVENODD'--export interface VectorVertex {- x: number- y: number- strokeCap?: string- strokeJoin?: string- cornerRadius?: number- handleMirroring?: HandleMirroring-}--export interface VectorSegment {- start: number- end: number- tangentStart: Vector- tangentEnd: Vector-}--export interface VectorRegion {- windingRule: WindingRule- loops: number[][]-}--export interface VectorNetwork {- vertices: VectorVertex[]- segments: VectorSegment[]- regions: VectorRegion[]-}--/** Deep-copy a VectorNetwork, stripping any Vue Proxy wrappers. */-export function cloneVectorNetwork(vn: VectorNetwork): VectorNetwork {- return {- vertices: vn.vertices.map((v) => ({ ...v })),- segments: vn.segments.map((s) => ({- ...s,- tangentStart: { ...s.tangentStart },- tangentEnd: { ...s.tangentEnd }- })),- regions: vn.regions.map((r) => ({- windingRule: r.windingRule,- loops: r.loops.map((l) => [...l])- }))- }-}--/**- * Validate a VectorNetwork structure, returning an array of error messages.- * Empty array means the network is valid.- */-export function validateVectorNetwork(vn: VectorNetwork): string[] {- const errors: string[] = []- if (!Array.isArray(vn.vertices)) {- errors.push('vertices must be an array')- return errors- }- if (!Array.isArray(vn.segments)) {- errors.push('segments must be an array')- return errors- }- if (!Array.isArray(vn.regions)) errors.push('regions must be an array')- const vertexCount = vn.vertices.length- for (let i = 0; i < vn.vertices.length; i++) {- const v = vn.vertices[i]- if (typeof v.x !== 'number' || typeof v.y !== 'number') {- errors.push(`vertex[${i}]: x and y must be numbers`)- }- }- for (let i = 0; i < vn.segments.length; i++) {- const s = vn.segments[i]- if (typeof s.start !== 'number' || typeof s.end !== 'number') {- errors.push(`segment[${i}]: start and end must be numbers`)- } else {- if (s.start < 0 || s.start >= vertexCount)- errors.push(`segment[${i}]: start index ${s.start} out of range`)- if (s.end < 0 || s.end >= vertexCount)- errors.push(`segment[${i}]: end index ${s.end} out of range`)- }- }- return errors-}--/**- * Ensure every segment has tangentStart/tangentEnd.- * Missing tangents default to {x:0, y:0} (straight line segments).- * Use at system boundaries where input may come from JSON/MCP.- */-export function normalizeVectorNetwork(vn: VectorNetwork): VectorNetwork {- const ZERO: Vector = { x: 0, y: 0 }- return {- vertices: vn.vertices,- segments: vn.segments.map((s) => ({- start: s.start,- end: s.end,- tangentStart: (s as Partial<VectorSegment>).tangentStart ?? { ...ZERO },- tangentEnd: (s as Partial<VectorSegment>).tangentEnd ?? { ...ZERO }- })),- regions: vn.regions- }-}--export interface GeometryPath {- windingRule: WindingRule- commandsBlob: Uint8Array-}--export type NodeType =- | 'CANVAS'- | 'FRAME'- | 'RECTANGLE'- | 'ROUNDED_RECTANGLE'- | 'ELLIPSE'- | 'TEXT'- | 'LINE'- | 'STAR'- | 'POLYGON'- | 'VECTOR'- | 'GROUP'- | 'SECTION'- | 'COMPONENT'- | 'COMPONENT_SET'- | 'INSTANCE'- | 'CONNECTOR'- | 'SHAPE_WITH_TEXT'--export type FillType =- | 'SOLID'- | 'GRADIENT_LINEAR'- | 'GRADIENT_RADIAL'- | 'GRADIENT_ANGULAR'- | 'GRADIENT_DIAMOND'- | 'IMAGE'-export type BlendMode =- | 'NORMAL'- | 'DARKEN'- | 'MULTIPLY'- | 'COLOR_BURN'- | 'LIGHTEN'- | 'SCREEN'- | 'COLOR_DODGE'- | 'OVERLAY'- | 'SOFT_LIGHT'- | 'HARD_LIGHT'- | 'DIFFERENCE'- | 'EXCLUSION'- | 'HUE'- | 'SATURATION'- | 'COLOR'- | 'LUMINOSITY'- | 'PASS_THROUGH'-export type ImageScaleMode = 'FILL' | 'FIT' | 'CROP' | 'TILE'--export interface GradientStop {- color: Color- position: number-}+export * from './snap'+export { UndoManager, type UndoEntry, type UndoManagerOptions } from './undo'-export type GradientTransform = Matrix--export interface Fill {- type: FillType- color: Color- opacity: number- visible: boolean- blendMode?: BlendMode- gradientStops?: GradientStop[]- gradientTransform?: GradientTransform- imageHash?: string- imageScaleMode?: ImageScaleMode- imageTransform?: GradientTransform-}--export type StrokeCap = 'NONE' | 'ROUND' | 'SQUARE' | 'ARROW_LINES' | 'ARROW_EQUILATERAL'-export type StrokeJoin = 'MITER' | 'BEVEL' | 'ROUND'-export type MaskType = 'ALPHA' | 'VECTOR' | 'LUMINANCE'--export interface Stroke {- color: Color- weight: number- opacity: number- visible: boolean- align: 'INSIDE' | 'CENTER' | 'OUTSIDE'- cap?: StrokeCap- join?: StrokeJoin- dashPattern?: number[]-}--export interface Effect {- type: 'DROP_SHADOW' | 'INNER_SHADOW' | 'LAYER_BLUR' | 'BACKGROUND_BLUR' | 'FOREGROUND_BLUR'- color: Color- offset: Vector- radius: number- spread: number- visible: boolean- blendMode?: BlendMode-}--export type ConstraintType = 'MIN' | 'CENTER' | 'MAX' | 'STRETCH' | 'SCALE'-export type TextAutoResize = 'NONE' | 'HEIGHT' | 'WIDTH_AND_HEIGHT' | 'TRUNCATE'-export type TextAlignVertical = 'TOP' | 'CENTER' | 'BOTTOM'-export type TextCase = 'ORIGINAL' | 'UPPER' | 'LOWER' | 'TITLE'-export type TextDecoration = 'NONE' | 'UNDERLINE' | 'STRIKETHROUGH'-export type TextDirection = 'AUTO' | 'LTR' | 'RTL'-export type LayoutDirection = 'AUTO' | 'LTR' | 'RTL'--export interface CharacterStyleOverride {- fontWeight?: number- italic?: boolean- textDecoration?: TextDecoration- fontSize?: number- fontFamily?: string- letterSpacing?: number- lineHeight?: number | null- fills?: Fill[]-}--export interface StyleRun {- start: number- length: number- style: CharacterStyleOverride-}--export interface ArcData {- startingAngle: number- endingAngle: number- innerRadius: number-}--export type LayoutMode = 'NONE' | 'HORIZONTAL' | 'VERTICAL' | 'GRID'-export type LayoutSizing = 'FIXED' | 'HUG' | 'FILL'--export type GridTrackSizing = 'FIXED' | 'FR' | 'AUTO'--export interface GridTrack {- sizing: GridTrackSizing- value: number-}--export interface GridPosition {- column: number- row: number- columnSpan: number- rowSpan: number-}-export type LayoutAlign = 'MIN' | 'CENTER' | 'MAX' | 'SPACE_BETWEEN'-export type LayoutCounterAlign = 'MIN' | 'CENTER' | 'MAX' | 'STRETCH' | 'BASELINE'-export type LayoutAlignSelf = 'AUTO' | 'MIN' | 'CENTER' | 'MAX' | 'STRETCH' | 'BASELINE'-export type LayoutWrap = 'NO_WRAP' | 'WRAP'--export interface PluginDataEntry {- pluginId: string- key: string- value: string-}--export interface SharedPluginDataEntry {- namespace: string- key: string- value: string-}--export interface PluginRelaunchDataEntry {- pluginId: string- command: string- message: string- isDeleted: boolean-}--export interface SceneNode {- id: string- type: NodeType- name: string- parentId: string | null- childIds: string[]-- x: number- y: number- width: number- height: number- rotation: number- figmaDerivedLayout: { x?: number; y?: number; width?: number; height?: number } | null-- fills: Fill[]- strokes: Stroke[]- effects: Effect[]- opacity: number-- cornerRadius: number- topLeftRadius: number- topRightRadius: number- bottomRightRadius: number- bottomLeftRadius: number- independentCorners: boolean- cornerSmoothing: number-- visible: boolean- locked: boolean- clipsContent: boolean-- blendMode: BlendMode-- text: string- fontSize: number- fontFamily: string- fontWeight: number- italic: boolean- textAlignHorizontal: 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED'- textDirection: TextDirection- textAlignVertical: TextAlignVertical- textAutoResize: TextAutoResize- textCase: TextCase- textDecoration: TextDecoration- lineHeight: number | null- letterSpacing: number- maxLines: number | null- styleRuns: StyleRun[]-- horizontalConstraint: ConstraintType- verticalConstraint: ConstraintType-- layoutMode: LayoutMode- layoutDirection: LayoutDirection- layoutWrap: LayoutWrap- primaryAxisAlign: LayoutAlign- counterAxisAlign: LayoutCounterAlign- primaryAxisSizing: LayoutSizing- counterAxisSizing: LayoutSizing- itemSpacing: number- counterAxisSpacing: number- paddingTop: number- paddingRight: number- paddingBottom: number- paddingLeft: number-- layoutPositioning: 'AUTO' | 'ABSOLUTE'- layoutGrow: number- layoutAlignSelf: LayoutAlignSelf-- vectorNetwork: VectorNetwork | null- fillGeometry: GeometryPath[]- strokeGeometry: GeometryPath[]-- arcData: ArcData | null-- strokeCap: StrokeCap- strokeJoin: StrokeJoin- dashPattern: number[]-- borderTopWeight: number- borderRightWeight: number- borderBottomWeight: number- borderLeftWeight: number- independentStrokeWeights: boolean-- strokeMiterLimit: number-- minWidth: number | null- maxWidth: number | null- minHeight: number | null- maxHeight: number | null-- isMask: boolean- maskType: MaskType-- gridTemplateColumns: GridTrack[]- gridTemplateRows: GridTrack[]- gridColumnGap: number- gridRowGap: number- gridPosition: GridPosition | null-- counterAxisAlignContent: 'AUTO' | 'SPACE_BETWEEN'- itemReverseZIndex: boolean- strokesIncludedInLayout: boolean-- expanded: boolean- textTruncation: 'DISABLED' | 'ENDING'- autoRename: boolean-- pointCount: number- starInnerRadius: number-- componentId: string | null- overrides: Record<string, unknown>-- boundVariables: Record<string, string>-- pluginData: PluginDataEntry[]- sharedPluginData: SharedPluginDataEntry[]- pluginRelaunchData: PluginRelaunchDataEntry[]-- internalOnly: boolean-- flipX: boolean- flipY: boolean-- textPicture: Uint8Array | null-}+import { createNanoEvents } from 'nanoevents'-export type VariableType = 'COLOR' | 'FLOAT' | 'STRING' | 'BOOLEAN'-export type VariableValue = Color | number | string | boolean | { aliasId: string }--export interface Variable {- id: string- name: string- type: VariableType- collectionId: string- valuesByMode: Record<string, VariableValue>- description: string- hiddenFromPublishing: boolean-}+import * as HitTest from './hit-test'+import * as Instances from './instances'+import { CONTAINER_TYPES, createDefaultNode } from './node-defaults'+import { normalizeVectorNetwork } from './vector-network'+import * as Variables from './variables'-export interface VariableCollectionMode {- modeId: string- name: string-}+export type { GUID, Color } from '#core/types'+export * from './types'-export interface VariableCollection {- id: string- name: string- modes: VariableCollectionMode[]- defaultModeId: string- variableIds: string[]-}+import { getAbsolutePosition } from '#core/canvas/coordinate'+import type { Color, Rect, Vector } from '#core/types'+import type { Emitter } from 'nanoevents'+import type {+ DocumentColorSpace,+ NodeType,+ SceneGraphEventHandlers,+ SceneGraphEvents,+ SceneNode,+ Variable,+ VariableCollection,+ VariableType,+ VariableValue+} from './types'++export { cloneVectorNetwork, normalizeVectorNetwork, validateVectorNetwork } from './vector-network'let nextLocalID = 1export function generateId(): string {return `0:${nextLocalID++}`}-function createDefaultNode(type: NodeType, overrides: Partial<SceneNode> = {}): SceneNode {- return {- id: generateId(),- type,- name: type.charAt(0) + type.slice(1).toLowerCase(),- parentId: null,- childIds: [],- x: 0,- y: 0,- width: 100,- height: 100,- rotation: 0,- figmaDerivedLayout: null,- fills:- type === 'TEXT'- ? [{ type: 'SOLID' as const, color: { r: 0, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }]- : [],- strokes: [],- effects: [],- opacity: 1,- cornerRadius: 0,- topLeftRadius: 0,- topRightRadius: 0,- bottomRightRadius: 0,- bottomLeftRadius: 0,- independentCorners: false,- cornerSmoothing: 0,- visible: true,- locked: false,- clipsContent: false,- text: '',- fontSize: 14,- fontFamily: DEFAULT_FONT_FAMILY,- fontWeight: 400,- italic: false,- textAlignHorizontal: 'LEFT',- textDirection: 'AUTO',- lineHeight: null,- letterSpacing: 0,- layoutMode: 'NONE',- layoutDirection: 'AUTO',- layoutWrap: 'NO_WRAP',- primaryAxisAlign: 'MIN',- counterAxisAlign: 'MIN',- primaryAxisSizing: 'FIXED',- counterAxisSizing: 'FIXED',- itemSpacing: 0,- counterAxisSpacing: 0,- paddingTop: 0,- paddingRight: 0,- paddingBottom: 0,- paddingLeft: 0,- blendMode: 'PASS_THROUGH',- layoutPositioning: 'AUTO',- layoutGrow: 0,- layoutAlignSelf: 'AUTO',- vectorNetwork: null,- fillGeometry: [],- strokeGeometry: [],- arcData: null,- textAlignVertical: 'TOP',- textAutoResize: 'NONE',- textCase: 'ORIGINAL',- textDecoration: 'NONE',- maxLines: null,- styleRuns: [],- horizontalConstraint: 'MIN',- verticalConstraint: 'MIN',- strokeCap: 'NONE',- strokeJoin: 'MITER',- dashPattern: [],- borderTopWeight: 0,- borderRightWeight: 0,- borderBottomWeight: 0,- borderLeftWeight: 0,- independentStrokeWeights: false,- strokeMiterLimit: DEFAULT_STROKE_MITER_LIMIT,- minWidth: null,- maxWidth: null,- minHeight: null,- maxHeight: null,- isMask: false,- maskType: 'ALPHA',- gridTemplateColumns: [],- gridTemplateRows: [],- gridColumnGap: 0,- gridRowGap: 0,- gridPosition: null,- counterAxisAlignContent: 'AUTO',- itemReverseZIndex: false,- strokesIncludedInLayout: false,- expanded: true,- textTruncation: 'DISABLED',- autoRename: true,- pointCount: 5,- starInnerRadius: 0.38,- componentId: null,- overrides: {},- boundVariables: {},- pluginData: [],- sharedPluginData: [],- pluginRelaunchData: [],- internalOnly: false,- flipX: false,- flipY: false,- textPicture: null,- ...overrides- }-}--const CONTAINER_TYPES = new Set<NodeType>([- 'CANVAS',- 'FRAME',- 'GROUP',- 'SECTION',- 'COMPONENT',- 'COMPONENT_SET',- 'INSTANCE'-])-export class SceneGraph {nodes = new Map<string, SceneNode>()images = new Map<string, Uint8Array>()@@ -596,7 +49,7 @@ export class SceneGraph {instanceIndex = new Map<string, Set<string>>()constructor() {- const root = createDefaultNode('FRAME', {+ const root = createDefaultNode(generateId, 'FRAME', {name: 'Document',width: 0,height: 0@@ -625,36 +78,32 @@ export class SceneGraph {return this.nodes.get(id)}+ onNodeEvents(handlers: SceneGraphEventHandlers): () => void {+ const unbinds = [+ handlers.created ? this.emitter.on('node:created', handlers.created) : null,+ handlers.updated ? this.emitter.on('node:updated', handlers.updated) : null,+ handlers.deleted ? this.emitter.on('node:deleted', handlers.deleted) : null,+ handlers.reparented ? this.emitter.on('node:reparented', handlers.reparented) : null,+ handlers.reordered ? this.emitter.on('node:reordered', handlers.reordered) : null+ ].filter((unbind): unbind is () => void => !!unbind)++ return () => {+ for (const unbind of unbinds) unbind()+ }+ }+// --- Variables ---addVariable(variable: Variable): void {- this.variables.set(variable.id, variable)- const collection = this.variableCollections.get(variable.collectionId)- if (collection && !collection.variableIds.includes(variable.id)) {- collection.variableIds.push(variable.id)- }+ Variables.addVariable(this, variable)}removeVariable(id: string): void {- const variable = this.variables.get(id)- if (!variable) return- this.variables.delete(id)- const collection = this.variableCollections.get(variable.collectionId)- if (collection) {- collection.variableIds = collection.variableIds.filter((vid) => vid !== id)- }- for (const node of this.nodes.values()) {- for (const [field, varId] of Object.entries(node.boundVariables)) {- if (varId === id) delete node.boundVariables[field]- }- }+ Variables.removeVariable(this, id)}addCollection(collection: VariableCollection): void {- this.variableCollections.set(collection.id, collection)- if (!this.activeMode.has(collection.id)) {- this.activeMode.set(collection.id, collection.defaultModeId)- }+ Variables.addCollection(this, collection)}createVariable(@@ -663,72 +112,23 @@ export class SceneGraph {collectionId: string,value?: VariableValue): Variable {- const collection = this.variableCollections.get(collectionId)- if (!collection) throw new Error(`Collection "${collectionId}" not found`)- const id = generateId()- let defaultValue: VariableValue- if (value !== undefined) {- defaultValue = value- } else if (type === 'COLOR') {- defaultValue = { ...BLACK }- } else if (type === 'FLOAT') {- defaultValue = 0- } else if (type === 'BOOLEAN') {- defaultValue = false- } else {- defaultValue = ''- }- const valuesByMode: Record<string, VariableValue> = {}- for (const mode of collection.modes) {- valuesByMode[mode.modeId] = structuredClone(defaultValue)- }- const variable: Variable = {- id,- name,- type,- collectionId,- valuesByMode,- description: '',- hiddenFromPublishing: false- }- this.addVariable(variable)- return variable+ return Variables.createVariable(this, generateId, name, type, collectionId, value)}createCollection(name: string): VariableCollection {- const id = generateId()- const modeId = generateId()- const collection: VariableCollection = {- id,- name,- modes: [{ modeId, name: 'Mode 1' }],- defaultModeId: modeId,- variableIds: []- }- this.addCollection(collection)- return collection+ return Variables.createCollection(this, generateId, name)}removeCollection(id: string): void {- const collection = this.variableCollections.get(id)- if (collection) {- for (const varId of Array.from(collection.variableIds)) {- this.removeVariable(varId)- }- }- this.variableCollections.delete(id)- this.activeMode.delete(id)+ Variables.removeCollection(this, id)}getActiveModeId(collectionId: string): string {- const mode = this.activeMode.get(collectionId)- if (mode) return mode- const collection = this.variableCollections.get(collectionId)- return collection?.defaultModeId ?? ''+ return Variables.getActiveModeId(this, collectionId)}setActiveMode(collectionId: string, modeId: string): void {- this.activeMode.set(collectionId, modeId)+ Variables.setActiveMode(this, collectionId, modeId)}resolveVariable(@@ -736,62 +136,31 @@ export class SceneGraph {modeId?: string,visited?: Set<string>): VariableValue | undefined {- if (visited?.has(variableId)) return undefined- const variable = this.variables.get(variableId)- if (!variable) return undefined- const collection = this.variableCollections.get(variable.collectionId)- const preferredModeId = modeId ?? this.getActiveModeId(variable.collectionId)- const fallbackModeId = collection?.defaultModeId- let value = Object.hasOwn(variable.valuesByMode, preferredModeId)- ? variable.valuesByMode[preferredModeId]- : undefined- if (- value === undefined &&- fallbackModeId &&- Object.hasOwn(variable.valuesByMode, fallbackModeId)- ) {- value = variable.valuesByMode[fallbackModeId]- }- value ??= Object.values(variable.valuesByMode)[0]- if (value && typeof value === 'object' && 'aliasId' in value) {- const seen = visited ?? new Set<string>()- seen.add(variableId)- return this.resolveVariable(value.aliasId, preferredModeId, seen)- }- return value+ return Variables.resolveVariable(this, variableId, modeId, visited)}resolveColorVariable(variableId: string): Color | undefined {- const value = this.resolveVariable(variableId)- if (value && typeof value === 'object' && 'r' in value) return value- return undefined+ return Variables.resolveColorVariable(this, variableId)}resolveNumberVariable(variableId: string): number | undefined {- const value = this.resolveVariable(variableId)- return typeof value === 'number' ? value : undefined+ return Variables.resolveNumberVariable(this, variableId)}getVariablesForCollection(collectionId: string): Variable[] {- const collection = this.variableCollections.get(collectionId)- if (!collection) return []- return collection.variableIds- .map((id) => this.variables.get(id))- .filter((v): v is Variable => v !== undefined)+ return Variables.getVariablesForCollection(this, collectionId)}getVariablesByType(type: VariableType): Variable[] {- return [...this.variables.values()].filter((v) => v.type === type)+ return Variables.getVariablesByType(this, type)}bindVariable(nodeId: string, field: string, variableId: string): void {- const node = this.nodes.get(nodeId)- if (node) node.boundVariables[field] = variableId+ Variables.bindVariable(this, nodeId, field, variableId)}unbindVariable(nodeId: string, field: string): void {- const node = this.nodes.get(nodeId)- if (node) delete node.boundVariables[field]+ Variables.unbindVariable(this, nodeId, field)}getChildren(id: string): SceneNode[] {@@ -844,7 +213,7 @@ export class SceneGraph {}createNode(type: NodeType, parentId: string, overrides: Partial<SceneNode> = {}): SceneNode {- const node = createDefaultNode(type, overrides)+ const node = createDefaultNode(generateId, type, overrides)node.parentId = parentIdthis.nodes.set(node.id, node)@@ -1022,11 +391,11 @@ export class SceneGraph {}hitTest(px: number, py: number, scopeId?: string): SceneNode | null {- return hitTestFn(this, px, py, scopeId)+ return HitTest.hitTest(this, px, py, scopeId)}hitTestDeep(px: number, py: number, scopeId?: string): SceneNode | null {- return hitTestDeepFn(this, px, py, scopeId)+ return HitTest.hitTestDeep(this, px, py, scopeId)}hitTestFrame(@@ -1035,7 +404,7 @@ export class SceneGraph {excludeIds: Set<string>,scopeId?: string): SceneNode | null {- return hitTestFrameFn(this, px, py, excludeIds, scopeId)+ return HitTest.hitTestFrame(this, px, py, excludeIds, scopeId)}cloneTree(@@ -1061,27 +430,27 @@ export class SceneGraph {parentId: string,overrides: Partial<SceneNode> = {}): SceneNode | null {- return createInstanceFn(this, componentId, parentId, overrides)+ return Instances.createInstance(this, componentId, parentId, overrides)}populateInstanceChildren(instanceId: string, componentId: string): void {- populateInstanceChildrenFn(this, instanceId, componentId)+ Instances.populateInstanceChildren(this, instanceId, componentId)}syncInstances(componentId: string): void {- syncInstancesFn(this, componentId)+ Instances.syncInstances(this, componentId)}detachInstance(instanceId: string): void {- detachInstanceFn(this, instanceId)+ Instances.detachInstance(this, instanceId)}getMainComponent(instanceId: string): SceneNode | undefined {- return getMainComponentFn(this, instanceId)+ return Instances.getMainComponent(this, instanceId)}getInstances(componentId: string): SceneNode[] {- return getInstancesFn(this, componentId)+ return Instances.getInstances(this, componentId)}flattenTree(parentId?: string, depth = 0): Array<{ node: SceneNode; depth: number }> {diff --git a/packages/core/src/scene-graph/node-defaults.ts b/packages/core/src/scene-graph/node-defaults.tsnew file mode 100644index 000000000..65854d609--- /dev/null+++ b/packages/core/src/scene-graph/node-defaults.ts@@ -0,0 +1,127 @@+import { DEFAULT_FONT_FAMILY, DEFAULT_STROKE_MITER_LIMIT } from '#core/constants'++import type { NodeType, SceneNode } from './types'++export function createDefaultNode(+ generateId: () => string,+ type: NodeType,+ overrides: Partial<SceneNode> = {}+): SceneNode {+ return {+ id: generateId(),+ type,+ name: type.charAt(0) + type.slice(1).toLowerCase(),+ parentId: null,+ childIds: [],+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ rotation: 0,+ figmaDerivedLayout: null,+ fills:+ type === 'TEXT'+ ? [{ type: 'SOLID' as const, color: { r: 0, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }]+ : [],+ strokes: [],+ effects: [],+ opacity: 1,+ cornerRadius: 0,+ topLeftRadius: 0,+ topRightRadius: 0,+ bottomRightRadius: 0,+ bottomLeftRadius: 0,+ independentCorners: false,+ cornerSmoothing: 0,+ visible: true,+ locked: false,+ clipsContent: false,+ text: '',+ fontSize: 14,+ fontFamily: DEFAULT_FONT_FAMILY,+ fontWeight: 400,+ italic: false,+ textAlignHorizontal: 'LEFT',+ textDirection: 'AUTO',+ lineHeight: null,+ letterSpacing: 0,+ layoutMode: 'NONE',+ layoutDirection: 'AUTO',+ layoutWrap: 'NO_WRAP',+ primaryAxisAlign: 'MIN',+ counterAxisAlign: 'MIN',+ primaryAxisSizing: 'FIXED',+ counterAxisSizing: 'FIXED',+ itemSpacing: 0,+ counterAxisSpacing: 0,+ paddingTop: 0,+ paddingRight: 0,+ paddingBottom: 0,+ paddingLeft: 0,+ blendMode: 'PASS_THROUGH',+ layoutPositioning: 'AUTO',+ layoutGrow: 0,+ layoutAlignSelf: 'AUTO',+ vectorNetwork: null,+ fillGeometry: [],+ strokeGeometry: [],+ arcData: null,+ textAlignVertical: 'TOP',+ textAutoResize: 'NONE',+ textCase: 'ORIGINAL',+ textDecoration: 'NONE',+ maxLines: null,+ styleRuns: [],+ horizontalConstraint: 'MIN',+ verticalConstraint: 'MIN',+ strokeCap: 'NONE',+ strokeJoin: 'MITER',+ dashPattern: [],+ borderTopWeight: 0,+ borderRightWeight: 0,+ borderBottomWeight: 0,+ borderLeftWeight: 0,+ independentStrokeWeights: false,+ strokeMiterLimit: DEFAULT_STROKE_MITER_LIMIT,+ minWidth: null,+ maxWidth: null,+ minHeight: null,+ maxHeight: null,+ isMask: false,+ maskType: 'ALPHA',+ gridTemplateColumns: [],+ gridTemplateRows: [],+ gridColumnGap: 0,+ gridRowGap: 0,+ gridPosition: null,+ counterAxisAlignContent: 'AUTO',+ itemReverseZIndex: false,+ strokesIncludedInLayout: false,+ expanded: true,+ textTruncation: 'DISABLED',+ autoRename: true,+ pointCount: 5,+ starInnerRadius: 0.38,+ componentId: null,+ overrides: {},+ boundVariables: {},+ pluginData: [],+ sharedPluginData: [],+ pluginRelaunchData: [],+ internalOnly: false,+ flipX: false,+ flipY: false,+ textPicture: null,+ ...overrides+ }+}++export const CONTAINER_TYPES = new Set<NodeType>([+ 'CANVAS',+ 'FRAME',+ 'GROUP',+ 'SECTION',+ 'COMPONENT',+ 'COMPONENT_SET',+ 'INSTANCE'+])diff --git a/packages/core/src/scene-graph/snap.ts b/packages/core/src/scene-graph/snap.tsindex 9defb0d45..c2715b2f3 100644--- a/packages/core/src/scene-graph/snap.ts+++ b/packages/core/src/scene-graph/snap.ts@@ -1,6 +1,6 @@-import { rotatedBBox } from '../geometry'+import { rotatedBBox } from '#core/geometry'-import type { Rect } from '../types'+import type { Rect } from '#core/types'import type { SceneNode } from './'const SNAP_THRESHOLD = 5diff --git a/packages/core/src/scene-graph/types.ts b/packages/core/src/scene-graph/types.tsnew file mode 100644index 000000000..84173d458--- /dev/null+++ b/packages/core/src/scene-graph/types.ts@@ -0,0 +1,373 @@+import type { Color, Matrix, Vector } from '#core/types'++export interface SceneGraphEvents {+ 'node:created': (node: SceneNode) => void+ 'node:updated': (id: string, changes: Partial<SceneNode>) => void+ 'node:deleted': (id: string) => void+ 'node:reparented': (nodeId: string, oldParentId: string | null, newParentId: string) => void+ 'node:reordered': (nodeId: string, parentId: string, index: number) => void+}++export type SceneGraphEventHandlers = Partial<{+ created: (node: SceneNode) => void+ updated: (id: string, changes: Partial<SceneNode>) => void+ deleted: (id: string) => void+ reparented: (nodeId: string, oldParentId: string | null, newParentId: string) => void+ reordered: (nodeId: string, parentId: string, index: number) => void+}>++export type DocumentColorSpace = 'srgb' | 'display-p3'++export type HandleMirroring = 'NONE' | 'ANGLE' | 'ANGLE_AND_LENGTH'+export type WindingRule = 'NONZERO' | 'EVENODD'++export interface VectorVertex {+ x: number+ y: number+ strokeCap?: string+ strokeJoin?: string+ cornerRadius?: number+ handleMirroring?: HandleMirroring+}++export interface VectorSegment {+ start: number+ end: number+ tangentStart: Vector+ tangentEnd: Vector+}++export interface VectorRegion {+ windingRule: WindingRule+ loops: number[][]+}++export interface VectorNetwork {+ vertices: VectorVertex[]+ segments: VectorSegment[]+ regions: VectorRegion[]+}++export interface GeometryPath {+ windingRule: WindingRule+ commandsBlob: Uint8Array+}++export type NodeType =+ | 'CANVAS'+ | 'FRAME'+ | 'RECTANGLE'+ | 'ROUNDED_RECTANGLE'+ | 'ELLIPSE'+ | 'TEXT'+ | 'LINE'+ | 'STAR'+ | 'POLYGON'+ | 'VECTOR'+ | 'GROUP'+ | 'SECTION'+ | 'COMPONENT'+ | 'COMPONENT_SET'+ | 'INSTANCE'+ | 'CONNECTOR'+ | 'SHAPE_WITH_TEXT'++export type FillType =+ | 'SOLID'+ | 'GRADIENT_LINEAR'+ | 'GRADIENT_RADIAL'+ | 'GRADIENT_ANGULAR'+ | 'GRADIENT_DIAMOND'+ | 'IMAGE'+export type BlendMode =+ | 'NORMAL'+ | 'DARKEN'+ | 'MULTIPLY'+ | 'COLOR_BURN'+ | 'LIGHTEN'+ | 'SCREEN'+ | 'COLOR_DODGE'+ | 'OVERLAY'+ | 'SOFT_LIGHT'+ | 'HARD_LIGHT'+ | 'DIFFERENCE'+ | 'EXCLUSION'+ | 'HUE'+ | 'SATURATION'+ | 'COLOR'+ | 'LUMINOSITY'+ | 'PASS_THROUGH'+export type ImageScaleMode = 'FILL' | 'FIT' | 'CROP' | 'TILE'++export interface GradientStop {+ color: Color+ position: number+}++export type GradientTransform = Matrix++export interface Fill {+ type: FillType+ color: Color+ opacity: number+ visible: boolean+ blendMode?: BlendMode+ gradientStops?: GradientStop[]+ gradientTransform?: GradientTransform+ imageHash?: string+ imageScaleMode?: ImageScaleMode+ imageTransform?: GradientTransform+}++export type StrokeCap = 'NONE' | 'ROUND' | 'SQUARE' | 'ARROW_LINES' | 'ARROW_EQUILATERAL'+export type StrokeJoin = 'MITER' | 'BEVEL' | 'ROUND'+export type MaskType = 'ALPHA' | 'VECTOR' | 'LUMINANCE'++export interface Stroke {+ color: Color+ weight: number+ opacity: number+ visible: boolean+ align: 'INSIDE' | 'CENTER' | 'OUTSIDE'+ cap?: StrokeCap+ join?: StrokeJoin+ dashPattern?: number[]+}++export interface Effect {+ type: 'DROP_SHADOW' | 'INNER_SHADOW' | 'LAYER_BLUR' | 'BACKGROUND_BLUR' | 'FOREGROUND_BLUR'+ color: Color+ offset: Vector+ radius: number+ spread: number+ visible: boolean+ blendMode?: BlendMode+}++export type ConstraintType = 'MIN' | 'CENTER' | 'MAX' | 'STRETCH' | 'SCALE'+export type TextAutoResize = 'NONE' | 'HEIGHT' | 'WIDTH_AND_HEIGHT' | 'TRUNCATE'+export type TextAlignVertical = 'TOP' | 'CENTER' | 'BOTTOM'+export type TextCase = 'ORIGINAL' | 'UPPER' | 'LOWER' | 'TITLE'+export type TextDecoration = 'NONE' | 'UNDERLINE' | 'STRIKETHROUGH'+export type TextDirection = 'AUTO' | 'LTR' | 'RTL'+export type LayoutDirection = 'AUTO' | 'LTR' | 'RTL'++export interface CharacterStyleOverride {+ fontWeight?: number+ italic?: boolean+ textDecoration?: TextDecoration+ fontSize?: number+ fontFamily?: string+ letterSpacing?: number+ lineHeight?: number | null+ fills?: Fill[]+}++export interface StyleRun {+ start: number+ length: number+ style: CharacterStyleOverride+}++export interface ArcData {+ startingAngle: number+ endingAngle: number+ innerRadius: number+}++export type LayoutMode = 'NONE' | 'HORIZONTAL' | 'VERTICAL' | 'GRID'+export type LayoutSizing = 'FIXED' | 'HUG' | 'FILL'++export type GridTrackSizing = 'FIXED' | 'FR' | 'AUTO'++export interface GridTrack {+ sizing: GridTrackSizing+ value: number+}++export interface GridPosition {+ column: number+ row: number+ columnSpan: number+ rowSpan: number+}+export type LayoutAlign = 'MIN' | 'CENTER' | 'MAX' | 'SPACE_BETWEEN'+export type LayoutCounterAlign = 'MIN' | 'CENTER' | 'MAX' | 'STRETCH' | 'BASELINE'+export type LayoutAlignSelf = 'AUTO' | 'MIN' | 'CENTER' | 'MAX' | 'STRETCH' | 'BASELINE'+export type LayoutWrap = 'NO_WRAP' | 'WRAP'++export interface PluginDataEntry {+ pluginId: string+ key: string+ value: string+}++export interface SharedPluginDataEntry {+ namespace: string+ key: string+ value: string+}++export interface PluginRelaunchDataEntry {+ pluginId: string+ command: string+ message: string+ isDeleted: boolean+}++export interface SceneNode {+ id: string+ type: NodeType+ name: string+ parentId: string | null+ childIds: string[]++ x: number+ y: number+ width: number+ height: number+ rotation: number+ figmaDerivedLayout: { x?: number; y?: number; width?: number; height?: number } | null++ fills: Fill[]+ strokes: Stroke[]+ effects: Effect[]+ opacity: number++ cornerRadius: number+ topLeftRadius: number+ topRightRadius: number+ bottomRightRadius: number+ bottomLeftRadius: number+ independentCorners: boolean+ cornerSmoothing: number++ visible: boolean+ locked: boolean+ clipsContent: boolean++ blendMode: BlendMode++ text: string+ fontSize: number+ fontFamily: string+ fontWeight: number+ italic: boolean+ textAlignHorizontal: 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED'+ textDirection: TextDirection+ textAlignVertical: TextAlignVertical+ textAutoResize: TextAutoResize+ textCase: TextCase+ textDecoration: TextDecoration+ lineHeight: number | null+ letterSpacing: number+ maxLines: number | null++ styleRuns: StyleRun[]++ horizontalConstraint: ConstraintType+ verticalConstraint: ConstraintType++ layoutMode: LayoutMode+ layoutDirection: LayoutDirection+ layoutWrap: LayoutWrap+ primaryAxisAlign: LayoutAlign+ counterAxisAlign: LayoutCounterAlign+ primaryAxisSizing: LayoutSizing+ counterAxisSizing: LayoutSizing+ itemSpacing: number+ counterAxisSpacing: number+ paddingTop: number+ paddingRight: number+ paddingBottom: number+ paddingLeft: number++ layoutPositioning: 'AUTO' | 'ABSOLUTE'+ layoutGrow: number+ layoutAlignSelf: LayoutAlignSelf++ vectorNetwork: VectorNetwork | null+ fillGeometry: GeometryPath[]+ strokeGeometry: GeometryPath[]++ arcData: ArcData | null++ strokeCap: StrokeCap+ strokeJoin: StrokeJoin+ dashPattern: number[]++ borderTopWeight: number+ borderRightWeight: number+ borderBottomWeight: number+ borderLeftWeight: number+ independentStrokeWeights: boolean++ strokeMiterLimit: number++ minWidth: number | null+ maxWidth: number | null+ minHeight: number | null+ maxHeight: number | null++ isMask: boolean+ maskType: MaskType++ gridTemplateColumns: GridTrack[]+ gridTemplateRows: GridTrack[]+ gridColumnGap: number+ gridRowGap: number+ gridPosition: GridPosition | null++ counterAxisAlignContent: 'AUTO' | 'SPACE_BETWEEN'+ itemReverseZIndex: boolean+ strokesIncludedInLayout: boolean++ expanded: boolean+ textTruncation: 'DISABLED' | 'ENDING'+ autoRename: boolean++ pointCount: number+ starInnerRadius: number++ componentId: string | null+ overrides: Record<string, unknown>++ boundVariables: Record<string, string>++ pluginData: PluginDataEntry[]+ sharedPluginData: SharedPluginDataEntry[]+ pluginRelaunchData: PluginRelaunchDataEntry[]++ internalOnly: boolean++ flipX: boolean+ flipY: boolean++ textPicture: Uint8Array | null+}++export type VariableType = 'COLOR' | 'FLOAT' | 'STRING' | 'BOOLEAN'+export type VariableValue = Color | number | string | boolean | { aliasId: string }++export interface Variable {+ id: string+ name: string+ type: VariableType+ collectionId: string+ valuesByMode: Record<string, VariableValue>+ description: string+ hiddenFromPublishing: boolean+}++export interface VariableCollectionMode {+ modeId: string+ name: string+}++export interface VariableCollection {+ id: string+ name: string+ modes: VariableCollectionMode[]+ defaultModeId: string+ variableIds: string[]+}diff --git a/packages/core/src/scene-graph/undo.ts b/packages/core/src/scene-graph/undo.tsindex 78a4e1654..4be260ece 100644--- a/packages/core/src/scene-graph/undo.ts+++ b/packages/core/src/scene-graph/undo.ts@@ -4,29 +4,47 @@ export interface UndoEntry {inverse: () => void}+export interface UndoManagerOptions {+ limit?: number+}++interface UndoBatch {+ label: string+ entries: UndoEntry[]+}++const DEFAULT_HISTORY_LIMIT = 200+export class UndoManager {private undoStack: UndoEntry[] = []private redoStack: UndoEntry[] = []- private batchEntries: UndoEntry[] | null = null- private batchLabel = ''+ private batches: UndoBatch[] = []+ private readonly limit: number++ constructor(options: UndoManagerOptions = {}) {+ this.limit = options.limit ?? DEFAULT_HISTORY_LIMIT+ }apply(entry: UndoEntry): void {+ this.execute(entry)+ }++ execute(entry: UndoEntry): void {entry.forward()- if (this.batchEntries) {- this.batchEntries.push(entry)- } else {- this.undoStack.push(entry)- this.redoStack = []- }+ this.record(entry)}push(entry: UndoEntry): void {- if (this.batchEntries) {- this.batchEntries.push(entry)- } else {- this.undoStack.push(entry)- this.redoStack = []+ this.record(entry)+ }++ record(entry: UndoEntry): void {+ const batch = this.currentBatch+ if (batch) {+ batch.entries.push(entry)+ return}+ this.pushUndoEntry(entry)}undo(): string | null {@@ -46,31 +64,41 @@ export class UndoManager {}beginBatch(label: string): void {- this.batchLabel = label- this.batchEntries = []+ this.batches.push({ label, entries: [] })}commitBatch(): void {- if (!this.batchEntries || this.batchEntries.length === 0) {- this.batchEntries = null- return+ const batch = this.batches.pop()+ if (!batch || batch.entries.length === 0) return++ const entry = this.createBatchEntry(batch)+ const parentBatch = this.currentBatch+ if (parentBatch) parentBatch.entries.push(entry)+ else this.pushUndoEntry(entry)+ }++ runBatch<T>(label: string, fn: () => T): T {+ this.beginBatch(label)+ try {+ const result = fn()+ this.commitBatch()+ return result+ } catch (error) {+ this.rollbackBatch()+ throw error}- const entries = this.batchEntries- const label = this.batchLabel- this.batchEntries = null-- this.undoStack.push({- label,- forward: () => entries.forEach((e) => e.forward()),- inverse: () => [...entries].reverse().forEach((e) => e.inverse())- })- this.redoStack = []+ }++ rollbackBatch(): void {+ const batch = this.batches.pop()+ if (!batch) return+ for (const entry of batch.entries.toReversed()) entry.inverse()}clear(): void {this.undoStack = []this.redoStack = []- this.batchEntries = null+ this.batches = []}get canUndo(): boolean {@@ -88,4 +116,28 @@ export class UndoManager {get redoLabel(): string | null {return this.redoStack.at(-1)?.label ?? null}++ private get currentBatch(): UndoBatch | null {+ return this.batches.at(-1) ?? null+ }++ private createBatchEntry(batch: UndoBatch): UndoEntry {+ return {+ label: batch.label,+ forward: () => batch.entries.forEach((entry) => entry.forward()),+ inverse: () => batch.entries.toReversed().forEach((entry) => entry.inverse())+ }+ }++ private pushUndoEntry(entry: UndoEntry): void {+ this.undoStack.push(entry)+ this.redoStack = []+ this.trimUndoStack()+ }++ private trimUndoStack(): void {+ if (!Number.isFinite(this.limit) || this.limit <= 0) return+ const overflow = this.undoStack.length - this.limit+ if (overflow > 0) this.undoStack.splice(0, overflow)+ }}diff --git a/packages/core/src/scene-graph/variables.ts b/packages/core/src/scene-graph/variables.tsnew file mode 100644index 000000000..121b22e01--- /dev/null+++ b/packages/core/src/scene-graph/variables.ts@@ -0,0 +1,168 @@+import { BLACK } from '#core/constants'++import type { Color } from '#core/types'+import type { SceneGraph } from './index'+import type { Variable, VariableCollection, VariableType, VariableValue } from './types'++export function addVariable(graph: SceneGraph, variable: Variable): void {+ graph.variables.set(variable.id, variable)+ const collection = graph.variableCollections.get(variable.collectionId)+ if (collection && !collection.variableIds.includes(variable.id)) {+ collection.variableIds.push(variable.id)+ }+}++export function removeVariable(graph: SceneGraph, id: string): void {+ const variable = graph.variables.get(id)+ if (!variable) return+ graph.variables.delete(id)+ const collection = graph.variableCollections.get(variable.collectionId)+ if (collection) {+ collection.variableIds = collection.variableIds.filter((vid) => vid !== id)+ }+ for (const node of graph.nodes.values()) {+ for (const [field, varId] of Object.entries(node.boundVariables)) {+ if (varId === id) delete node.boundVariables[field]+ }+ }+}++export function addCollection(graph: SceneGraph, collection: VariableCollection): void {+ graph.variableCollections.set(collection.id, collection)+ if (!graph.activeMode.has(collection.id)) {+ graph.activeMode.set(collection.id, collection.defaultModeId)+ }+}++function defaultVariableValue(type: VariableType, value?: VariableValue): VariableValue {+ if (value !== undefined) return value+ if (type === 'COLOR') return { ...BLACK }+ if (type === 'FLOAT') return 0+ if (type === 'BOOLEAN') return false+ return ''+}++export function createVariable(+ graph: SceneGraph,+ generateId: () => string,+ name: string,+ type: VariableType,+ collectionId: string,+ value?: VariableValue+): Variable {+ const collection = graph.variableCollections.get(collectionId)+ if (!collection) throw new Error(`Collection "${collectionId}" not found`)+ const id = generateId()+ const defaultValue = defaultVariableValue(type, value)+ const valuesByMode: Record<string, VariableValue> = {}+ for (const mode of collection.modes) {+ valuesByMode[mode.modeId] = structuredClone(defaultValue)+ }+ const variable: Variable = {+ id,+ name,+ type,+ collectionId,+ valuesByMode,+ description: '',+ hiddenFromPublishing: false+ }+ addVariable(graph, variable)+ return variable+}++export function createCollection(graph: SceneGraph, generateId: () => string, name: string): VariableCollection {+ const id = generateId()+ const modeId = generateId()+ const collection: VariableCollection = {+ id,+ name,+ modes: [{ modeId, name: 'Mode 1' }],+ defaultModeId: modeId,+ variableIds: []+ }+ addCollection(graph, collection)+ return collection+}++export function removeCollection(graph: SceneGraph, id: string): void {+ const collection = graph.variableCollections.get(id)+ if (collection) {+ for (const varId of Array.from(collection.variableIds)) {+ removeVariable(graph, varId)+ }+ }+ graph.variableCollections.delete(id)+ graph.activeMode.delete(id)+}++export function getActiveModeId(graph: SceneGraph, collectionId: string): string {+ const mode = graph.activeMode.get(collectionId)+ if (mode) return mode+ const collection = graph.variableCollections.get(collectionId)+ return collection?.defaultModeId ?? ''+}++export function setActiveMode(graph: SceneGraph, collectionId: string, modeId: string): void {+ graph.activeMode.set(collectionId, modeId)+}++export function resolveVariable(+ graph: SceneGraph,+ variableId: string,+ modeId?: string,+ visited?: Set<string>+): VariableValue | undefined {+ if (visited?.has(variableId)) return undefined+ const variable = graph.variables.get(variableId)+ if (!variable) return undefined+ const collection = graph.variableCollections.get(variable.collectionId)+ const preferredModeId = modeId ?? getActiveModeId(graph, variable.collectionId)+ const fallbackModeId = collection?.defaultModeId+ let value = Object.hasOwn(variable.valuesByMode, preferredModeId)+ ? variable.valuesByMode[preferredModeId]+ : undefined+ if (value === undefined && fallbackModeId && Object.hasOwn(variable.valuesByMode, fallbackModeId)) {+ value = variable.valuesByMode[fallbackModeId]+ }+ value ??= Object.values(variable.valuesByMode)[0]+ if (value && typeof value === 'object' && 'aliasId' in value) {+ const seen = visited ?? new Set<string>()+ seen.add(variableId)+ return resolveVariable(graph, value.aliasId, preferredModeId, seen)+ }+ return value+}++export function resolveColorVariable(graph: SceneGraph, variableId: string): Color | undefined {+ const value = resolveVariable(graph, variableId)+ if (value && typeof value === 'object' && 'r' in value) return value+ return undefined+}++export function resolveNumberVariable(graph: SceneGraph, variableId: string): number | undefined {+ const value = resolveVariable(graph, variableId)+ return typeof value === 'number' ? value : undefined+}++export function getVariablesForCollection(graph: SceneGraph, collectionId: string): Variable[] {+ const collection = graph.variableCollections.get(collectionId)+ if (!collection) return []+ return collection.variableIds+ .map((id) => graph.variables.get(id))+ .filter((v): v is Variable => v !== undefined)+}++export function getVariablesByType(graph: SceneGraph, type: VariableType): Variable[] {+ return [...graph.variables.values()].filter((v) => v.type === type)+}++export function bindVariable(graph: SceneGraph, nodeId: string, field: string, variableId: string): void {+ const node = graph.nodes.get(nodeId)+ if (node) node.boundVariables[field] = variableId+}++export function unbindVariable(graph: SceneGraph, nodeId: string, field: string): void {+ const node = graph.nodes.get(nodeId)+ if (node) delete node.boundVariables[field]+}diff --git a/packages/core/src/scene-graph/vector-network.ts b/packages/core/src/scene-graph/vector-network.tsnew file mode 100644index 000000000..02c347f40--- /dev/null+++ b/packages/core/src/scene-graph/vector-network.ts@@ -0,0 +1,73 @@+import type { Vector } from '#core/types'+import type { VectorNetwork, VectorSegment } from './types'++/** Deep-copy a VectorNetwork, stripping any Vue Proxy wrappers. */+export function cloneVectorNetwork(vn: VectorNetwork): VectorNetwork {+ return {+ vertices: vn.vertices.map((v) => ({ ...v })),+ segments: vn.segments.map((s) => ({+ ...s,+ tangentStart: { ...s.tangentStart },+ tangentEnd: { ...s.tangentEnd }+ })),+ regions: vn.regions.map((r) => ({+ windingRule: r.windingRule,+ loops: r.loops.map((l) => [...l])+ }))+ }+}++/**+ * Validate a VectorNetwork structure, returning an array of error messages.+ * Empty array means the network is valid.+ */+export function validateVectorNetwork(vn: VectorNetwork): string[] {+ const errors: string[] = []+ if (!Array.isArray(vn.vertices)) {+ errors.push('vertices must be an array')+ return errors+ }+ if (!Array.isArray(vn.segments)) {+ errors.push('segments must be an array')+ return errors+ }+ if (!Array.isArray(vn.regions)) errors.push('regions must be an array')+ const vertexCount = vn.vertices.length+ for (let i = 0; i < vn.vertices.length; i++) {+ const v = vn.vertices[i]+ if (typeof v.x !== 'number' || typeof v.y !== 'number') {+ errors.push(`vertex[${i}]: x and y must be numbers`)+ }+ }+ for (let i = 0; i < vn.segments.length; i++) {+ const s = vn.segments[i]+ if (typeof s.start !== 'number' || typeof s.end !== 'number') {+ errors.push(`segment[${i}]: start and end must be numbers`)+ } else {+ if (s.start < 0 || s.start >= vertexCount)+ errors.push(`segment[${i}]: start index ${s.start} out of range`)+ if (s.end < 0 || s.end >= vertexCount)+ errors.push(`segment[${i}]: end index ${s.end} out of range`)+ }+ }+ return errors+}++/**+ * Ensure every segment has tangentStart/tangentEnd.+ * Missing tangents default to {x:0, y:0} (straight line segments).+ * Use at system boundaries where input may come from JSON/MCP.+ */+export function normalizeVectorNetwork(vn: VectorNetwork): VectorNetwork {+ const ZERO: Vector = { x: 0, y: 0 }+ return {+ vertices: vn.vertices,+ segments: vn.segments.map((s) => ({+ start: s.start,+ end: s.end,+ tangentStart: (s as Partial<VectorSegment>).tangentStart ?? { ...ZERO },+ tangentEnd: (s as Partial<VectorSegment>).tangentEnd ?? { ...ZERO }+ })),+ regions: vn.regions+ }+}\ No newline at end of filediff --git a/packages/core/src/text/clipboard-derived-text.ts b/packages/core/src/text/clipboard-derived-text.tsindex 731ade851..033a9b45d 100644--- a/packages/core/src/text/clipboard-derived-text.ts+++ b/packages/core/src/text/clipboard-derived-text.ts@@ -1,8 +1,9 @@+import { buildDerivedTextData } from './derived-text-data'import { normalizeFontFamily, weightToStyle } from './fonts'import { getGlyphOutlineCommandsSync } from './opentype'-import type { NodeChange } from '../kiwi/codec'-import type { SceneNode } from '../scene-graph'+import type { NodeChange } from '#core/kiwi/binary/codec'+import type { SceneNode } from '#core/scene-graph'export interface ShapedClipboardText {lineHeight: number@@ -45,18 +46,8 @@ export async function buildDerivedTextDataV4(}})- return {- layoutSize: { x: node.width, y: node.height },- baselines: [- {- firstCharacter: 0,- endCharacter: Math.max(node.text.length - 1, 0),- position: { x: 0, y: shaped?.baseline ?? lineHeightFallback },- width: shaped?.lineWidth ?? node.width,- lineHeight: shaped?.lineHeight ?? lineHeightFallback,- lineAscent: shaped?.lineAscent ?? Math.max(lineHeightFallback - node.fontSize * 0.2, 0)- }- ],+ return buildDerivedTextData({+ node,glyphs,fontMetaData: [{@@ -67,11 +58,12 @@ export async function buildDerivedTextDataV4(fontWeight: node.fontWeight}],+ baseline: shaped?.baseline ?? lineHeightFallback,+ width: shaped?.lineWidth ?? node.width,+ lineHeight: shaped?.lineHeight ?? lineHeightFallback,+ lineAscent: shaped?.lineAscent ?? Math.max(lineHeightFallback - node.fontSize * 0.2, 0),logicalIndexToCharacterOffsetMap:shaped?.logicalIndexToCharacterOffsetMap ??- Array.from({ length: node.text.length + 1 }, () => 0),- derivedLines: [{ directionality: 'LTR' }],- truncationStartIndex: -1,- truncatedHeight: -1- }+ Array.from({ length: node.text.length + 1 }, () => 0)+ })}diff --git a/packages/core/src/text/derived-text-data.ts b/packages/core/src/text/derived-text-data.tsnew file mode 100644index 000000000..00be9e820--- /dev/null+++ b/packages/core/src/text/derived-text-data.ts@@ -0,0 +1,37 @@+import type { NodeChange } from '#core/kiwi/binary/codec'+import type { SceneNode } from '#core/scene-graph'++interface DerivedTextDataOptions {+ node: SceneNode+ glyphs: NonNullable<NodeChange['derivedTextData']>['glyphs']+ fontMetaData: NonNullable<NodeChange['derivedTextData']>['fontMetaData']+ baseline: number+ width: number+ lineHeight: number+ lineAscent: number+ logicalIndexToCharacterOffsetMap: number[]+}++export function buildDerivedTextData(+ options: DerivedTextDataOptions+): NodeChange['derivedTextData'] {+ return {+ layoutSize: { x: options.node.width, y: options.node.height },+ baselines: [+ {+ firstCharacter: 0,+ endCharacter: Math.max(options.node.text.length - 1, 0),+ position: { x: 0, y: options.baseline },+ width: options.width,+ lineHeight: options.lineHeight,+ lineAscent: options.lineAscent+ }+ ],+ glyphs: options.glyphs,+ fontMetaData: options.fontMetaData,+ logicalIndexToCharacterOffsetMap: options.logicalIndexToCharacterOffsetMap,+ derivedLines: [{ directionality: 'LTR' }],+ truncationStartIndex: -1,+ truncatedHeight: -1+ }+}diff --git a/packages/core/src/text/direction.ts b/packages/core/src/text/direction.tsindex 2e7110303..d1ec1d087 100644--- a/packages/core/src/text/direction.ts+++ b/packages/core/src/text/direction.ts@@ -1,4 +1,4 @@-import type { LayoutDirection, SceneNode, TextDirection } from '../scene-graph'+import type { LayoutDirection, SceneNode, TextDirection } from '#core/scene-graph'const RTL_CHAR_RE =/\p{Script=Arabic}|\p{Script=Hebrew}|\p{Script=Syriac}|\p{Script=Thaana}|\p{Script=Nko}|\p{Script=Adlam}/udiff --git a/packages/core/src/text/editor.ts b/packages/core/src/text/editor.tsindex 424a1120c..4b7350625 100644--- a/packages/core/src/text/editor.ts+++ b/packages/core/src/text/editor.ts@@ -1,8 +1,8 @@import { resolveNodeTextDirection } from './direction'-import type { SkiaRenderer } from '../canvas'-import type { SceneNode } from '../scene-graph'-import type { Rect } from '../types'+import type { SkiaRenderer } from '#core/canvas'+import type { SceneNode } from '#core/scene-graph'+import type { Rect } from '#core/types'import type { CanvasKit, Paragraph } from 'canvaskit-wasm'export interface TextCaret {@@ -38,6 +38,31 @@ export class TextEditor {return s}+ private replaceRange(start: number, end: number, text: string): TextEditorState | null {+ const s = this._state+ if (!s) return null+ s.text = s.text.slice(0, start) + text + s.text.slice(end)+ s.cursor = start + text.length+ s.selectionAnchor = null+ return s+ }++ private currentLineMetrics() {+ const s = this._state+ if (!s?.paragraph) return null+ const lineNum = s.paragraph.getLineNumberAt(s.cursor)+ return lineNum < 0 ? null : s.paragraph.getLineMetricsAt(lineNum)+ }++ private collapseSelectionTo(edge: 0 | 1): boolean {+ const s = this._state+ if (!s || !this.hasSelection()) return false+ const range = this.getSelectionRange()+ if (range) s.cursor = range[edge]+ s.selectionAnchor = null+ return true+ }+get state(): TextEditorState | null {return this._state}@@ -160,135 +185,124 @@ export class TextEditor {insert(text: string, node: SceneNode): void {const s = this._stateif (!s) return- const range = this.getSelectionRange()- if (range) {- s.text = s.text.slice(0, range[0]) + text + s.text.slice(range[1])- s.cursor = range[0] + text.length- } else {- s.text = s.text.slice(0, s.cursor) + text + s.text.slice(s.cursor)- s.cursor += text.length- }- s.selectionAnchor = null+ const range = this.getSelectionRange() ?? [s.cursor, s.cursor]+ this.replaceRange(range[0], range[1], text)this.rebuildParagraph(node)}backspace(node: SceneNode): void {const s = this._stateif (!s) return- const range = this.getSelectionRange()- if (range) {- s.text = s.text.slice(0, range[0]) + s.text.slice(range[1])- s.cursor = range[0]- } else if (s.cursor > 0) {- s.text = s.text.slice(0, s.cursor - 1) + s.text.slice(s.cursor)- s.cursor--- }- s.selectionAnchor = null+ const range = this.getSelectionRange() ?? (s.cursor > 0 ? [s.cursor - 1, s.cursor] : null)+ if (range) this.replaceRange(range[0], range[1], '')this.rebuildParagraph(node)}delete(node: SceneNode): void {const s = this._stateif (!s) return- const range = this.getSelectionRange()- if (range) {- s.text = s.text.slice(0, range[0]) + s.text.slice(range[1])- s.cursor = range[0]- } else if (s.cursor < s.text.length) {- s.text = s.text.slice(0, s.cursor) + s.text.slice(s.cursor + 1)- }- s.selectionAnchor = null+ const range =+ this.getSelectionRange() ?? (s.cursor < s.text.length ? [s.cursor, s.cursor + 1] : null)+ if (range) this.replaceRange(range[0], range[1], '')this.rebuildParagraph(node)}- moveLeft(extend = false): void {+ private moveHorizontal(extend: boolean, visualDirection: 'left' | 'right'): void {const s = this._stateif (!s) return- if (!extend && this.hasSelection()) {- const range = this.getSelectionRange()- if (range) s.cursor = range[0]- s.selectionAnchor = null- return- }+ if (!extend && this.collapseSelectionTo(visualDirection === 'left' ? 0 : 1)) returnthis.prepareMove(extend)- if (s.textDirection === 'RTL') {- if (s.cursor < s.text.length) s.cursor++- } else if (s.cursor > 0) s.cursor--+ const movesForward = (visualDirection === 'left') === (s.textDirection === 'RTL')+ const step = movesForward ? 1 : -1+ const next = s.cursor + step+ if (next >= 0 && next <= s.text.length) s.cursor = next+ }++ moveLeft(extend = false): void {+ this.moveHorizontal(extend, 'left')}moveRight(extend = false): void {- const s = this._state- if (!s) return- if (!extend && this.hasSelection()) {- const range = this.getSelectionRange()- if (range) s.cursor = range[1]- s.selectionAnchor = null- return- }- this.prepareMove(extend)- if (s.textDirection === 'RTL') {- if (s.cursor > 0) s.cursor--- } else if (s.cursor < s.text.length) s.cursor+++ this.moveHorizontal(extend, 'right')}- moveUp(extend = false): void {+ private moveVertical(extend: boolean, edge: 'up' | 'down'): void {const s = this._stateif (!s?.paragraph) returnthis.prepareMove(extend)const caret = this.getCaretRect()if (!caret) returnconst fontSize = s.paragraph.getLineMetrics()[0]?.height ?? 14- s.cursor = s.paragraph.getGlyphPositionAtCoordinate(caret.x, caret.y0 - fontSize / 2).pos+ const y = edge === 'up' ? caret.y0 - fontSize / 2 : caret.y1 + fontSize / 2+ s.cursor = s.paragraph.getGlyphPositionAtCoordinate(caret.x, y).pos+ }++ moveUp(extend = false): void {+ this.moveVertical(extend, 'up')}moveDown(extend = false): void {- const s = this._state- if (!s?.paragraph) return- this.prepareMove(extend)- const caret = this.getCaretRect()- if (!caret) return- const fontSize = s.paragraph.getLineMetrics()[0]?.height ?? 14- s.cursor = s.paragraph.getGlyphPositionAtCoordinate(caret.x, caret.y1 + fontSize / 2).pos+ this.moveVertical(extend, 'down')}- moveToLineStart(extend = false): void {+ private moveToLineEdge(extend: boolean, edge: 'start' | 'end'): void {const s = this._stateif (!s?.paragraph) returnthis.prepareMove(extend)- const lineNum = s.paragraph.getLineNumberAt(s.cursor)- if (lineNum < 0) return- const metrics = s.paragraph.getLineMetricsAt(lineNum)+ const metrics = this.currentLineMetrics()if (!metrics) return- s.cursor = s.textDirection === 'RTL' ? metrics.endExcludingWhitespaces : metrics.startIndex+ const isRtlStart = s.textDirection === 'RTL' && edge === 'start'+ const isLtrEnd = s.textDirection !== 'RTL' && edge === 'end'+ s.cursor = isRtlStart || isLtrEnd ? metrics.endExcludingWhitespaces : metrics.startIndex+ }++ moveToLineStart(extend = false): void {+ this.moveToLineEdge(extend, 'start')}moveToLineEnd(extend = false): void {- const s = this._state- if (!s?.paragraph) return- this.prepareMove(extend)- const lineNum = s.paragraph.getLineNumberAt(s.cursor)- if (lineNum < 0) return- const metrics = s.paragraph.getLineMetricsAt(lineNum)- if (!metrics) return- s.cursor = s.textDirection === 'RTL' ? metrics.startIndex : metrics.endExcludingWhitespaces+ this.moveToLineEdge(extend, 'end')}- moveWordLeft(extend = false): void {+ private moveWord(extend: boolean, direction: 'left' | 'right'): void {const s = this.prepareMove(extend)if (!s) return- let pos = s.cursor- while (pos > 0 && isWordBoundary(s.text[pos - 1])) pos--- while (pos > 0 && !isWordBoundary(s.text[pos - 1])) pos--+ const movingLeft = direction === 'left'+ let pos = this.skipWordBoundaryRun(s.text, s.cursor, movingLeft)+ pos = this.skipWordInteriorRun(s.text, pos, movingLeft)s.cursor = pos}+ private skipWordBoundaryRun(text: string, start: number, movingLeft: boolean): number {+ return this.advanceWhile(text, start, movingLeft, (boundary) => movingLeft === boundary)+ }++ private skipWordInteriorRun(text: string, start: number, movingLeft: boolean): number {+ return this.advanceWhile(text, start, movingLeft, (boundary) => movingLeft !== boundary)+ }++ private advanceWhile(+ text: string,+ start: number,+ movingLeft: boolean,+ shouldMove: (isBoundary: boolean) => boolean+ ): number {+ let pos = start+ const step = movingLeft ? -1 : 1+ while (movingLeft ? pos > 0 : pos < text.length) {+ const char = movingLeft ? text[pos - 1] : text[pos]+ if (!shouldMove(isWordBoundary(char))) break+ pos += step+ }+ return pos+ }++ moveWordLeft(extend = false): void {+ this.moveWord(extend, 'left')+ }+moveWordRight(extend = false): void {- const s = this.prepareMove(extend)- if (!s) return- let pos = s.cursor- while (pos < s.text.length && !isWordBoundary(s.text[pos])) pos++- while (pos < s.text.length && isWordBoundary(s.text[pos])) pos++- s.cursor = pos+ this.moveWord(extend, 'right')}getCaretRect(): TextCaret | null {diff --git a/packages/core/src/text/fonts.ts b/packages/core/src/text/fonts.tsindex 9efeab812..cad60c617 100644--- a/packages/core/src/text/fonts.ts+++ b/packages/core/src/text/fonts.ts@@ -6,9 +6,9 @@ import {CJK_FALLBACK_FAMILIES_LINUX,CJK_GOOGLE_FONTS,GOOGLE_FONTS_API_KEY-} from '../constants'+} from '#core/constants'-import type { SceneGraph } from '../scene-graph'+import type { SceneGraph } from '#core/scene-graph'import type { CanvasKit, TypefaceFontProvider } from 'canvaskit-wasm'export interface FontInfo {@@ -160,8 +160,8 @@ export async function fetchBundledFont(url: string): Promise<ArrayBuffer | null>const response = await fetch(url)return response.arrayBuffer()}- const { readFile } = await import('node:fs/promises')- const { fileURLToPath } = await import('node:url')+ const { readFile } = await import(/* @vite-ignore */ 'node:fs/promises')+ const { fileURLToPath } = await import(/* @vite-ignore */ 'node:url')const assetPath = fileURLToPath(new URL(`../../assets${url}`, import.meta.url))const buf = await readFile(assetPath)return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)diff --git a/packages/core/src/text/opentype.ts b/packages/core/src/text/opentype.tsindex c62775048..62d232ee9 100644--- a/packages/core/src/text/opentype.ts+++ b/packages/core/src/text/opentype.ts@@ -79,13 +79,6 @@ export function measureTextWithOpenType(return { width: Math.ceil(singleLineWidth), height: lineH }}-let openTypeModulePromise: Promise<OpenTypeModule> | null = null--async function loadOpenTypeModule() {- openTypeModulePromise ??= import('opentype.js') as Promise<typeof OpenTypeSync & OpenTypeModule>- return openTypeModulePromise-}-function commandsToFigmaNumbers(commands: OutlineCommand[]): Array<string | number> {const result: Array<string | number> = []for (const command of commands) {@@ -122,8 +115,7 @@ export async function probeGlyphOutlineCommands(const bytes = getLoadedFontData(family, style)if (!bytes) return null- const openType = await loadOpenTypeModule()- const font = openType.parse(bytes.slice(0))+ const font = (OpenTypeSync as OpenTypeModule).parse(bytes.slice(0))const glyphs = font.stringToGlyphs(text)const firstGlyph = glyphs.find((glyph: OutlineGlyph) => glyph.path.commands.length > 0)const firstGlyphCommandSample = (firstGlyph?.getPath(0, 0, fontSize).commands ?? []).slice(0, 12)diff --git a/packages/core/src/text/style-runs.ts b/packages/core/src/text/style-runs.tsindex f9dd69a60..5ce2e6bfb 100644--- a/packages/core/src/text/style-runs.ts+++ b/packages/core/src/text/style-runs.ts@@ -1,4 +1,4 @@-import type { CharacterStyleOverride, StyleRun, TextDecoration } from '../scene-graph'+import type { CharacterStyleOverride, StyleRun, TextDecoration } from '#core/scene-graph'export function getStyleAt(runs: StyleRun[], index: number): CharacterStyleOverride {for (const run of runs) {diff --git a/packages/core/src/tools/ai-adapter.ts b/packages/core/src/tools/ai-adapter.tsindex 00495b92c..0721f0597 100644--- a/packages/core/src/tools/ai-adapter.ts+++ b/packages/core/src/tools/ai-adapter.ts@@ -5,7 +5,7 @@* functions with FigmaAPI instantiation.*/-import type { FigmaAPI } from '../figma-api'+import type { FigmaAPI } from '#core/figma-api'import type { ToolDef, ParamDef, ParamType } from './schema'import type * as valibot from 'valibot'diff --git a/packages/core/src/tools/analyze.ts b/packages/core/src/tools/analyze.tsindex 51e1749d9..9ac6fc864 100644--- a/packages/core/src/tools/analyze.ts+++ b/packages/core/src/tools/analyze.ts@@ -1,628 +1,6 @@-/* eslint-disable max-lines -- analysis tools share helpers and collection logic */-import { createTwoFilesPatch } from 'diff'--import { colorDistance, colorToHex, parseColor } from '../color'-import { defineTool } from './schema'--import type { FigmaAPI } from '../figma-api'-import type { SceneNode } from '../scene-graph'-import type { Color } from '../types'--interface SizedItem {- width: number- height: number- childCount: number-}--export function calcClusterConfidence(nodes: SizedItem[]): number {- if (nodes.length < 2) return 100- const base = nodes[0]- let score = 0- for (const n of nodes.slice(1)) {- const sizeDiff = Math.abs(n.width - base.width) + Math.abs(n.height - base.height)- const childDiff = Math.abs(n.childCount - base.childCount)- if (sizeDiff <= 4 && childDiff === 0) score++- else if (sizeDiff <= 10 && childDiff <= 1) score += 0.8- else if (sizeDiff <= 20 && childDiff <= 2) score += 0.6- else score += 0.4- }- return Math.round((score / (nodes.length - 1)) * 100)-}--interface ColorEntry {- hex: string- color: Color- count: number- variableName: string | null-}--function trackColor(colorMap: Map<string, ColorEntry>, color: Color, variableName: string | null) {- const hex = colorToHex(color)- const entry = colorMap.get(hex)- if (entry) {- entry.count++- if (!entry.variableName && variableName) entry.variableName = variableName- } else {- colorMap.set(hex, { hex, color, count: 1, variableName })- }-}--// ─── Diff helpers ─────────────────────────────────────────────--function serializePaintProps(raw: SceneNode, lines: string[]): void {- const solidFill = raw.fills.find((f) => f.type === 'SOLID' && f.visible)- if (solidFill) lines.push(`fill: ${colorToHex(solidFill.color)}`)-- const solidStroke = raw.strokes.find((s) => s.visible)- if (solidStroke) {- lines.push(`stroke: ${colorToHex(solidStroke.color)}`)- if (solidStroke.weight) lines.push(`strokeWeight: ${solidStroke.weight}`)- }-}--function serializeCornerRadii(raw: SceneNode, lines: string[]): void {- const tl = raw.topLeftRadius- const tr = raw.topRightRadius- const br = raw.bottomRightRadius- const bl = raw.bottomLeftRadius- if (tl || tr || br || bl) {- if (tl === tr && tr === br && br === bl) {- lines.push(`radius: ${tl}`)- } else {- lines.push(`radii: ${tl} ${tr} ${br} ${bl}`)- }- }-}--function serializeEffects(raw: SceneNode, lines: string[]): void {- for (const effect of raw.effects) {- const parts: string[] = [effect.type]- parts.push(`r=${effect.radius}`)- parts.push(`c=${colorToHex(effect.color)}`)- parts.push(`x=${effect.offset.x} y=${effect.offset.y}`)- parts.push(`s=${effect.spread}`)- lines.push(`effect: ${parts.join(' ')}`)- }-}--function serializeTextProps(raw: SceneNode, lines: string[]): void {- if (raw.type !== 'TEXT') return- if (raw.text) lines.push(`text: ${JSON.stringify(raw.text)}`)- if (raw.fontSize) lines.push(`fontSize: ${raw.fontSize}`)- if (raw.fontFamily) lines.push(`fontFamily: ${raw.fontFamily}`)- if (raw.fontWeight) lines.push(`fontWeight: ${raw.fontWeight}`)-}--function serializeNodeProps(raw: SceneNode): string {- const lines: string[] = []- lines.push(`type: ${raw.type}`)- lines.push(`size: ${raw.width} ${raw.height}`)- lines.push(`pos: ${raw.x} ${raw.y}`)-- serializePaintProps(raw, lines)-- if (raw.opacity !== 1) lines.push(`opacity: ${Math.round(raw.opacity * 100) / 100}`)-- serializeCornerRadii(raw, lines)-- if (raw.blendMode !== 'NORMAL') lines.push(`blendMode: ${raw.blendMode}`)- if (raw.rotation !== 0) lines.push(`rotation: ${Math.round(raw.rotation * 100) / 100}`)- if (raw.clipsContent) lines.push(`clipsContent: true`)-- serializeEffects(raw, lines)- serializeTextProps(raw, lines)-- if (!raw.visible) lines.push(`visible: false`)- if (raw.locked) lines.push(`locked: true`)-- return lines.join('\n')-}--function collectNodeTree(- figma: FigmaAPI,- nodeId: string,- parentPath: string,- depth: number,- maxDepth: number-): Map<string, { path: string; id: string; serialized: string }> {- const result = new Map<string, { path: string; id: string; serialized: string }>()- const raw = figma.graph.getNode(nodeId)- if (!raw) return result-- const path = parentPath ? `${parentPath}/${raw.name}` : `/${raw.name}`- result.set(path, { path, id: raw.id, serialized: serializeNodeProps(raw) })-- if (depth < maxDepth) {- for (const childId of raw.childIds) {- const childNodes = collectNodeTree(figma, childId, path, depth + 1, maxDepth)- for (const [k, v] of childNodes) result.set(k, v)- }- }- return result-}--function createUnifiedDiff(- oldFilename: string,- newFilename: string,- oldContent: string,- newContent: string-): string {- const patch = createTwoFilesPatch(oldFilename, newFilename, oldContent, newContent, '', '')- return patch- .split('\n')- .filter(- (l) =>- !l.startsWith('Index:') &&- l !== '==================================================================='- )- .join('\n')- .trim()-}--// ─── Analyze tools ────────────────────────────────────────────--export const analyzeColors = defineTool({- name: 'analyze_colors',- description:- 'Analyze color palette usage across the current page. Shows frequency, variable bindings, and optionally clusters similar colors.',- params: {- limit: { type: 'number', description: 'Max colors to return (default: 30)' },- show_similar: {- type: 'boolean',- description: 'Include similar-color clusters for potential merging'- },- threshold: {- type: 'number',- description: 'Distance threshold for clustering (0-50, default: 15)'- }- },- execute: (figma, args) => {- const limit = args.limit ?? 30- const threshold = args.threshold ?? 15- const page = figma.currentPage- const colorMap = new Map<string, ColorEntry>()- let totalNodes = 0-- page.findAll((node) => {- totalNodes++- const raw = figma.graph.getNode(node.id)- if (!raw) return false-- const boundVars = raw.boundVariables- for (const fill of raw.fills) {- if (fill.type === 'SOLID' && fill.visible) {- trackColor(colorMap, fill.color, boundVars['fills'] ? String(boundVars['fills']) : null)- }- }- for (const stroke of raw.strokes) {- if (stroke.visible) {- trackColor(- colorMap,- stroke.color,- boundVars['strokes'] ? String(boundVars['strokes']) : null- )- }- }- return false- })-- const colors = [...colorMap.values()].sort((a, b) => b.count - a.count).slice(0, limit)-- const result: Record<string, unknown> = {- totalNodes,- uniqueColors: colorMap.size,- colors: colors.map((c) => ({ hex: c.hex, count: c.count, variableName: c.variableName }))- }-- if (args.show_similar) {- const hardcoded = [...colorMap.values()]- .filter((c) => !c.variableName)- .sort((a, b) => b.count - a.count)- const used = new Set<string>()- const clusters: { colors: string[]; totalCount: number; suggestedHex: string }[] = []-- for (const color of hardcoded) {- if (used.has(color.hex)) continue- const cluster = [color]- used.add(color.hex)- for (const other of hardcoded) {- if (used.has(other.hex)) continue- if (colorDistance(color.color, other.color) <= threshold) {- cluster.push(other)- used.add(other.hex)- }- }- if (cluster.length > 1) {- clusters.push({- colors: cluster.map((c) => c.hex),- totalCount: cluster.reduce((sum, c) => sum + c.count, 0),- suggestedHex: color.hex- })- }- }-- result.similarClusters = clusters.sort((a, b) => b.colors.length - a.colors.length)- }-- return result- }-})--export const analyzeTypography = defineTool({- name: 'analyze_typography',- description:- 'Analyze typography usage across the current page. Shows font families, sizes, weights, and their frequencies.',- params: {- limit: { type: 'number', description: 'Max styles to return (default: 30)' },- group_by: {- type: 'string',- description: 'Group results by a property',- enum: ['family', 'size', 'weight']- }- },- execute: (figma, args) => {- const limit = args.limit ?? 30- const page = figma.currentPage- const styleMap = new Map<- string,- { family: string; size: number; weight: number; lineHeight: string; count: number }- >()- let totalTextNodes = 0-- page.findAll((node) => {- if (node.type !== 'TEXT') return false- totalTextNodes++- const raw = figma.graph.getNode(node.id)- if (!raw) return false- const lh = raw.lineHeight === null ? 'auto' : `${raw.lineHeight}`- const key = `${raw.fontFamily}|${raw.fontSize}|${raw.fontWeight}|${lh}`- const entry = styleMap.get(key)- if (entry) {- entry.count++- } else {- styleMap.set(key, {- family: raw.fontFamily,- size: raw.fontSize,- weight: raw.fontWeight,- lineHeight: lh,- count: 1- })- }- return false- })-- const styles = [...styleMap.values()].sort((a, b) => b.count - a.count)-- if (args.group_by === 'family') {- const byFamily = new Map<string, number>()- for (const s of styles) byFamily.set(s.family, (byFamily.get(s.family) ?? 0) + s.count)- return {- totalTextNodes,- groups: [...byFamily.entries()]- .sort((a, b) => b[1] - a[1])- .map(([family, count]) => ({ family, count }))- }- }-- if (args.group_by === 'size') {- const bySize = new Map<number, number>()- for (const s of styles) bySize.set(s.size, (bySize.get(s.size) ?? 0) + s.count)- return {- totalTextNodes,- groups: [...bySize.entries()]- .sort((a, b) => a[0] - b[0])- .map(([size, count]) => ({ size, count }))- }- }-- if (args.group_by === 'weight') {- const byWeight = new Map<number, number>()- for (const s of styles) byWeight.set(s.weight, (byWeight.get(s.weight) ?? 0) + s.count)- return {- totalTextNodes,- groups: [...byWeight.entries()]- .sort((a, b) => b[1] - a[1])- .map(([weight, count]) => ({ weight, count }))- }- }-- return {- totalTextNodes,- uniqueStyles: styleMap.size,- styles: styles.slice(0, limit)- }- }-})--export const analyzeSpacing = defineTool({- name: 'analyze_spacing',- description:- 'Analyze spacing values (gap, padding) across the current page. Checks grid compliance.',- params: {- grid: { type: 'number', description: 'Base grid size to check against (default: 8)' }- },- execute: (figma, args) => {- const gridSize = args.grid ?? 8- const page = figma.currentPage- const gapMap = new Map<number, number>()- const paddingMap = new Map<number, number>()- let totalNodes = 0-- page.findAll((node) => {- totalNodes++- const raw = figma.graph.getNode(node.id)- if (!raw) return false-- if (raw.layoutMode !== 'NONE' && raw.itemSpacing > 0) {- gapMap.set(raw.itemSpacing, (gapMap.get(raw.itemSpacing) ?? 0) + 1)- }-- for (const p of [raw.paddingTop, raw.paddingRight, raw.paddingBottom, raw.paddingLeft]) {- if (p > 0) {- paddingMap.set(p, (paddingMap.get(p) ?? 0) + 1)- }- }- return false- })-- const gaps = [...gapMap.entries()]- .sort((a, b) => b[1] - a[1])- .map(([value, count]) => ({ value, count, onGrid: value % gridSize === 0 }))-- const paddings = [...paddingMap.entries()]- .sort((a, b) => b[1] - a[1])- .map(([value, count]) => ({ value, count, onGrid: value % gridSize === 0 }))-- const offGridGaps = gaps.filter((g) => !g.onGrid)- const offGridPaddings = paddings.filter((p) => !p.onGrid)-- return {- totalNodes,- gridSize,- gaps,- paddings,- offGridGaps: offGridGaps.map((g) => g.value),- offGridPaddings: offGridPaddings.map((p) => p.value)- }- }-})--export const analyzeClusters = defineTool({- name: 'analyze_clusters',- description:- 'Find repeated design patterns (potential components). Groups nodes by structural signature — type, size, and child structure.',- params: {- min_count: { type: 'number', description: 'Min instances to form a cluster (default: 2)' },- min_size: { type: 'number', description: 'Min node size in px (default: 30)' },- limit: { type: 'number', description: 'Max clusters to return (default: 20)' }- },- execute: (figma, args) => {- const minCount = args.min_count ?? 2- const minSize = args.min_size ?? 30- const limit = args.limit ?? 20- const page = figma.currentPage-- const signatureMap = new Map<- string,- {- id: string- name: string- type: string- width: number- height: number- childCount: number- }[]- >()- let totalNodes = 0-- page.findAll((node) => {- totalNodes++- const raw = figma.graph.getNode(node.id)- if (!raw) return false- if (raw.width < minSize || raw.height < minSize) return false- if (raw.type === 'CANVAS' || raw.type === 'INSTANCE') return false-- const childTypes = new Map<string, number>()- for (const childId of raw.childIds) {- const child = figma.graph.getNode(childId)- if (child) childTypes.set(child.type, (childTypes.get(child.type) ?? 0) + 1)- }-- const w = Math.round(raw.width / 10) * 10- const h = Math.round(raw.height / 10) * 10- const childSig = [...childTypes.entries()]- .sort(([a], [b]) => a.localeCompare(b))- .map(([t, c]) => `${t}:${c}`)- .join(',')- const signature = `${raw.type}:${w}x${h}|${childSig}`-- const list = signatureMap.get(signature) ?? []- list.push({- id: raw.id,- name: raw.name,- type: raw.type,- width: raw.width,- height: raw.height,- childCount: raw.childIds.length- })- signatureMap.set(signature, list)- return false- })-- const clusters = [...signatureMap.entries()]- .filter(([, nodes]) => nodes.length >= minCount)- .map(([signature, nodes]) => {- const avgW = nodes.reduce((s, n) => s + n.width, 0) / nodes.length- const avgH = nodes.reduce((s, n) => s + n.height, 0) / nodes.length- const widths = nodes.map((n) => n.width)- const heights = nodes.map((n) => n.height)- const widthRange = Math.max(...widths) - Math.min(...widths)- const heightRange = Math.max(...heights) - Math.min(...heights)-- const confidence = calcClusterConfidence(nodes)-- return {- signature,- count: nodes.length,- avgWidth: Math.round(avgW),- avgHeight: Math.round(avgH),- widthRange: Math.round(widthRange),- heightRange: Math.round(heightRange),- confidence,- examples: nodes.slice(0, 3).map((n) => ({ id: n.id, name: n.name }))- }- })- .sort((a, b) => b.count - a.count)- .slice(0, limit)-- return { totalNodes, clusters }- }-})--// ─── Diff tools ───────────────────────────────────────────────--export const diffCreate = defineTool({- name: 'diff_create',- description:- 'Create a structural diff between two node trees. Compares properties (fills, strokes, effects, text, size, position) in unified diff format.',- params: {- from: { type: 'string', description: 'Source node ID', required: true },- to: { type: 'string', description: 'Target node ID', required: true },- depth: { type: 'number', description: 'Max tree depth (default: 10)' }- },- execute: (figma, args) => {- const maxDepth = args.depth ?? 10- const fromNode = figma.graph.getNode(args.from)- const toNode = figma.graph.getNode(args.to)- if (!fromNode) return { error: `Node "${args.from}" not found` }- if (!toNode) return { error: `Node "${args.to}" not found` }-- const fromNodes = collectNodeTree(figma, args.from, '', 0, maxDepth)- const toNodes = collectNodeTree(figma, args.to, '', 0, maxDepth)- const allPaths = new Set([...fromNodes.keys(), ...toNodes.keys()])-- const patches: string[] = []- for (const path of allPaths) {- const fromEntry = fromNodes.get(path)- const toEntry = toNodes.get(path)-- if (!fromEntry && toEntry) {- const filename = `${path} #${toEntry.id}`- const newLines = toEntry.serialized.split('\n')- patches.push(- `--- /dev/null\n+++ ${filename}\n@@ -0,0 +1,${newLines.length} @@\n${newLines.map((l) => `+${l}`).join('\n')}`- )- } else if (fromEntry && !toEntry) {- const filename = `${path} #${fromEntry.id}`- const oldLines = fromEntry.serialized.split('\n')- patches.push(- `--- ${filename}\n+++ /dev/null\n@@ -1,${oldLines.length} +0,0 @@\n${oldLines.map((l) => `-${l}`).join('\n')}`- )- } else if (fromEntry && toEntry && fromEntry.serialized !== toEntry.serialized) {- patches.push(- createUnifiedDiff(- `${path} #${fromEntry.id}`,- `${path} #${toEntry.id}`,- fromEntry.serialized,- toEntry.serialized- )- )- }- }-- if (patches.length === 0) return { diff: null, message: 'No differences found' }- return { diff: patches.join('\n') }- }-})--export const diffShow = defineTool({- name: 'diff_show',- description:- 'Preview what would change if properties were applied to a node. Shows a unified diff of current vs proposed state.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- props: {- type: 'string',- description:- 'JSON object of new properties, e.g. \'{"opacity": 1, "fill": "#FF0000", "width": 200}\'',- required: true- }- },- execute: (figma, args) => {- const raw = figma.graph.getNode(args.id)- if (!raw) return { error: `Node "${args.id}" not found` }-- const oldContent = serializeNodeProps(raw)-- let newProps: Record<string, unknown>- try {- newProps = JSON.parse(args.props)- } catch {- return { error: 'Invalid JSON in props' }- }-- const modified: SceneNode = structuredClone(raw)- if (newProps.fill) {- modified.fills = [- { type: 'SOLID', color: parseColor(newProps.fill as string), opacity: 1, visible: true }- ]- }- if (newProps.stroke) {- modified.strokes = [- {- color: parseColor(newProps.stroke as string),- weight: modified.strokes[0]?.weight ?? 1,- opacity: 1,- visible: true,- align: modified.strokes[0]?.align ?? 'INSIDE'- }- ]- }- if (newProps.opacity !== undefined) modified.opacity = Number(newProps.opacity)- if (newProps.radius !== undefined) {- const r = Number(newProps.radius)- modified.cornerRadius = r- modified.topLeftRadius = r- modified.topRightRadius = r- modified.bottomRightRadius = r- modified.bottomLeftRadius = r- }- if (newProps.width !== undefined) modified.width = Number(newProps.width)- if (newProps.height !== undefined) modified.height = Number(newProps.height)- if (newProps.x !== undefined) modified.x = Number(newProps.x)- if (newProps.y !== undefined) modified.y = Number(newProps.y)- if (newProps.visible !== undefined) modified.visible = Boolean(newProps.visible)- if (newProps.locked !== undefined) modified.locked = Boolean(newProps.locked)- if (newProps.rotation !== undefined) modified.rotation = Number(newProps.rotation)- if (newProps.text !== undefined) modified.text = newProps.text as string-- const newContent = serializeNodeProps(modified)-- if (oldContent === newContent) return { diff: null, message: 'No changes' }-- const filename = `/${raw.name} #${args.id}`- return { diff: createUnifiedDiff(filename, filename, oldContent, newContent) }- }-})--// ─── Eval escape hatch ────────────────────────────────────────--export const evalCode = defineTool({- name: 'eval',- description:- 'Execute JavaScript with full Figma Plugin API access. Use for operations not covered by other tools. The `figma` global is available.',- params: {- code: { type: 'string', description: 'JavaScript code to execute', required: true }- },- mutates: true,- execute: async (figma, { code }) => {- // eslint-disable-next-line no-empty-function- const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor- const wrapped = code.trim().startsWith('return') ? code : `return (async () => { ${code} })()`- const fn = new AsyncFunction('figma', wrapped)- const result = await fn(figma)- if (result && typeof result === 'object' && 'toJSON' in result) return result.toJSON()- if (result !== undefined && result !== null) return result- return { ok: true, message: 'Code executed (no return value)' }- }-})+export { analyzeClusters, calcClusterConfidence } from './analyze/clusters'+export { analyzeColors } from './analyze/colors'+export { diffCreate, diffShow } from './analyze/diff'+export { evalCode } from './analyze/eval'+export { analyzeSpacing } from './analyze/spacing'+export { analyzeTypography } from './analyze/typography'diff --git a/packages/core/src/tools/analyze/clusters.ts b/packages/core/src/tools/analyze/clusters.tsnew file mode 100644index 000000000..db1f0ec77--- /dev/null+++ b/packages/core/src/tools/analyze/clusters.ts@@ -0,0 +1,113 @@+import { defineTool } from '#core/tools/schema'++interface SizedItem {+ width: number+ height: number+ childCount: number+}++export function calcClusterConfidence(nodes: SizedItem[]): number {+ if (nodes.length < 2) return 100+ const base = nodes[0]+ let score = 0+ for (const node of nodes.slice(1)) {+ const sizeDiff = Math.abs(node.width - base.width) + Math.abs(node.height - base.height)+ const childDiff = Math.abs(node.childCount - base.childCount)+ if (sizeDiff <= 4 && childDiff === 0) score+++ else if (sizeDiff <= 10 && childDiff <= 1) score += 0.8+ else if (sizeDiff <= 20 && childDiff <= 2) score += 0.6+ else score += 0.4+ }+ return Math.round((score / (nodes.length - 1)) * 100)+}++export const analyzeClusters = defineTool({+ name: 'analyze_clusters',+ description:+ 'Find repeated design patterns (potential components). Groups nodes by structural signature — type, size, and child structure.',+ params: {+ min_count: { type: 'number', description: 'Min instances to form a cluster (default: 2)' },+ min_size: { type: 'number', description: 'Min node size in px (default: 30)' },+ limit: { type: 'number', description: 'Max clusters to return (default: 20)' },+ },+ execute: (figma, args) => {+ const minCount = args.min_count ?? 2+ const minSize = args.min_size ?? 30+ const limit = args.limit ?? 20+ const page = figma.currentPage++ const signatureMap = new Map<+ string,+ {+ id: string+ name: string+ type: string+ width: number+ height: number+ childCount: number+ }[]+ >()+ let totalNodes = 0++ page.findAll((node) => {+ totalNodes+++ const raw = figma.graph.getNode(node.id)+ if (!raw) return false+ if (raw.width < minSize || raw.height < minSize) return false+ if (raw.type === 'CANVAS' || raw.type === 'INSTANCE') return false++ const childTypes = new Map<string, number>()+ for (const childId of raw.childIds) {+ const child = figma.graph.getNode(childId)+ if (child) childTypes.set(child.type, (childTypes.get(child.type) ?? 0) + 1)+ }++ const width = Math.round(raw.width / 10) * 10+ const height = Math.round(raw.height / 10) * 10+ const childSignature = [...childTypes.entries()]+ .sort(([a], [b]) => a.localeCompare(b))+ .map(([type, count]) => `${type}:${count}`)+ .join(',')+ const signature = `${raw.type}:${width}x${height}|${childSignature}`++ const list = signatureMap.get(signature) ?? []+ list.push({+ id: raw.id,+ name: raw.name,+ type: raw.type,+ width: raw.width,+ height: raw.height,+ childCount: raw.childIds.length,+ })+ signatureMap.set(signature, list)+ return false+ })++ const clusters = [...signatureMap.entries()]+ .filter(([, nodes]) => nodes.length >= minCount)+ .map(([signature, nodes]) => {+ const avgWidth = nodes.reduce((sum, node) => sum + node.width, 0) / nodes.length+ const avgHeight = nodes.reduce((sum, node) => sum + node.height, 0) / nodes.length+ const widths = nodes.map((node) => node.width)+ const heights = nodes.map((node) => node.height)+ const widthRange = Math.max(...widths) - Math.min(...widths)+ const heightRange = Math.max(...heights) - Math.min(...heights)+ const confidence = calcClusterConfidence(nodes)++ return {+ signature,+ count: nodes.length,+ avgWidth: Math.round(avgWidth),+ avgHeight: Math.round(avgHeight),+ widthRange: Math.round(widthRange),+ heightRange: Math.round(heightRange),+ confidence,+ examples: nodes.slice(0, 3).map((node) => ({ id: node.id, name: node.name })),+ }+ })+ .sort((a, b) => b.count - a.count)+ .slice(0, limit)++ return { totalNodes, clusters }+ },+})diff --git a/packages/core/src/tools/analyze/colors.ts b/packages/core/src/tools/analyze/colors.tsnew file mode 100644index 000000000..3b67ae17f--- /dev/null+++ b/packages/core/src/tools/analyze/colors.ts@@ -0,0 +1,112 @@+import { colorDistance, colorToHex } from '#core/color'+import { defineTool } from '#core/tools/schema'++import type { Color } from '#core/types'++interface ColorEntry {+ hex: string+ color: Color+ count: number+ variableName: string | null+}++function trackColor(colorMap: Map<string, ColorEntry>, color: Color, variableName: string | null) {+ const hex = colorToHex(color)+ const entry = colorMap.get(hex)+ if (entry) {+ entry.count+++ if (!entry.variableName && variableName) entry.variableName = variableName+ } else {+ colorMap.set(hex, { hex, color, count: 1, variableName })+ }+}++// ─── Analyze tools ────────────────────────────────────────────++export const analyzeColors = defineTool({+ name: 'analyze_colors',+ description:+ 'Analyze color palette usage across the current page. Shows frequency, variable bindings, and optionally clusters similar colors.',+ params: {+ limit: { type: 'number', description: 'Max colors to return (default: 30)' },+ show_similar: {+ type: 'boolean',+ description: 'Include similar-color clusters for potential merging'+ },+ threshold: {+ type: 'number',+ description: 'Distance threshold for clustering (0-50, default: 15)'+ }+ },+ execute: (figma, args) => {+ const limit = args.limit ?? 30+ const threshold = args.threshold ?? 15+ const page = figma.currentPage+ const colorMap = new Map<string, ColorEntry>()+ let totalNodes = 0++ page.findAll((node) => {+ totalNodes+++ const raw = figma.graph.getNode(node.id)+ if (!raw) return false++ const boundVars = raw.boundVariables+ for (const fill of raw.fills) {+ if (fill.type === 'SOLID' && fill.visible) {+ trackColor(colorMap, fill.color, boundVars['fills'] ? String(boundVars['fills']) : null)+ }+ }+ for (const stroke of raw.strokes) {+ if (stroke.visible) {+ trackColor(+ colorMap,+ stroke.color,+ boundVars['strokes'] ? String(boundVars['strokes']) : null+ )+ }+ }+ return false+ })++ const colors = [...colorMap.values()].sort((a, b) => b.count - a.count).slice(0, limit)++ const result: Record<string, unknown> = {+ totalNodes,+ uniqueColors: colorMap.size,+ colors: colors.map((c) => ({ hex: c.hex, count: c.count, variableName: c.variableName }))+ }++ if (args.show_similar) {+ const hardcoded = [...colorMap.values()]+ .filter((c) => !c.variableName)+ .sort((a, b) => b.count - a.count)+ const used = new Set<string>()+ const clusters: { colors: string[]; totalCount: number; suggestedHex: string }[] = []++ for (const color of hardcoded) {+ if (used.has(color.hex)) continue+ const cluster = [color]+ used.add(color.hex)+ for (const other of hardcoded) {+ if (used.has(other.hex)) continue+ if (colorDistance(color.color, other.color) <= threshold) {+ cluster.push(other)+ used.add(other.hex)+ }+ }+ if (cluster.length > 1) {+ clusters.push({+ colors: cluster.map((c) => c.hex),+ totalCount: cluster.reduce((sum, c) => sum + c.count, 0),+ suggestedHex: color.hex+ })+ }+ }++ result.similarClusters = clusters.sort((a, b) => b.colors.length - a.colors.length)+ }++ return result+ }+})+diff --git a/packages/core/src/tools/analyze/diff.ts b/packages/core/src/tools/analyze/diff.tsnew file mode 100644index 000000000..43a3f4ec6--- /dev/null+++ b/packages/core/src/tools/analyze/diff.ts@@ -0,0 +1,244 @@+import { createTwoFilesPatch } from 'diff'++import { colorToHex, parseColor } from '#core/color'+import { defineTool } from '#core/tools/schema'++import type { FigmaAPI } from '#core/figma-api'+import type { SceneNode } from '#core/scene-graph'++function serializePaintProps(raw: SceneNode, lines: string[]): void {+ const solidFill = raw.fills.find((f) => f.type === 'SOLID' && f.visible)+ if (solidFill) lines.push(`fill: ${colorToHex(solidFill.color)}`)++ const solidStroke = raw.strokes.find((s) => s.visible)+ if (solidStroke) {+ lines.push(`stroke: ${colorToHex(solidStroke.color)}`)+ if (solidStroke.weight) lines.push(`strokeWeight: ${solidStroke.weight}`)+ }+}++function serializeCornerRadii(raw: SceneNode, lines: string[]): void {+ const tl = raw.topLeftRadius+ const tr = raw.topRightRadius+ const br = raw.bottomRightRadius+ const bl = raw.bottomLeftRadius+ if (tl || tr || br || bl) {+ if (tl === tr && tr === br && br === bl) {+ lines.push(`radius: ${tl}`)+ } else {+ lines.push(`radii: ${tl} ${tr} ${br} ${bl}`)+ }+ }+}++function serializeEffects(raw: SceneNode, lines: string[]): void {+ for (const effect of raw.effects) {+ const parts: string[] = [effect.type]+ parts.push(`r=${effect.radius}`)+ parts.push(`c=${colorToHex(effect.color)}`)+ parts.push(`x=${effect.offset.x} y=${effect.offset.y}`)+ parts.push(`s=${effect.spread}`)+ lines.push(`effect: ${parts.join(' ')}`)+ }+}++function serializeTextProps(raw: SceneNode, lines: string[]): void {+ if (raw.type !== 'TEXT') return+ if (raw.text) lines.push(`text: ${JSON.stringify(raw.text)}`)+ if (raw.fontSize) lines.push(`fontSize: ${raw.fontSize}`)+ if (raw.fontFamily) lines.push(`fontFamily: ${raw.fontFamily}`)+ if (raw.fontWeight) lines.push(`fontWeight: ${raw.fontWeight}`)+}++function serializeNodeProps(raw: SceneNode): string {+ const lines: string[] = []+ lines.push(`type: ${raw.type}`)+ lines.push(`size: ${raw.width} ${raw.height}`)+ lines.push(`pos: ${raw.x} ${raw.y}`)++ serializePaintProps(raw, lines)++ if (raw.opacity !== 1) lines.push(`opacity: ${Math.round(raw.opacity * 100) / 100}`)++ serializeCornerRadii(raw, lines)++ if (raw.blendMode !== 'NORMAL') lines.push(`blendMode: ${raw.blendMode}`)+ if (raw.rotation !== 0) lines.push(`rotation: ${Math.round(raw.rotation * 100) / 100}`)+ if (raw.clipsContent) lines.push(`clipsContent: true`)++ serializeEffects(raw, lines)+ serializeTextProps(raw, lines)++ if (!raw.visible) lines.push(`visible: false`)+ if (raw.locked) lines.push(`locked: true`)++ return lines.join('\n')+}++function collectNodeTree(+ figma: FigmaAPI,+ nodeId: string,+ parentPath: string,+ depth: number,+ maxDepth: number+): Map<string, { path: string; id: string; serialized: string }> {+ const result = new Map<string, { path: string; id: string; serialized: string }>()+ const raw = figma.graph.getNode(nodeId)+ if (!raw) return result++ const path = parentPath ? `${parentPath}/${raw.name}` : `/${raw.name}`+ result.set(path, { path, id: raw.id, serialized: serializeNodeProps(raw) })++ if (depth < maxDepth) {+ for (const childId of raw.childIds) {+ const childNodes = collectNodeTree(figma, childId, path, depth + 1, maxDepth)+ for (const [k, v] of childNodes) result.set(k, v)+ }+ }+ return result+}++function createUnifiedDiff(+ oldFilename: string,+ newFilename: string,+ oldContent: string,+ newContent: string+): string {+ const patch = createTwoFilesPatch(oldFilename, newFilename, oldContent, newContent, '', '')+ return patch+ .split('\n')+ .filter(+ (l) =>+ !l.startsWith('Index:') &&+ l !== '==================================================================='+ )+ .join('\n')+ .trim()+}++// ─── Diff tools ───────────────────────────────────────────────++export const diffCreate = defineTool({+ name: 'diff_create',+ description:+ 'Create a structural diff between two node trees. Compares properties (fills, strokes, effects, text, size, position) in unified diff format.',+ params: {+ from: { type: 'string', description: 'Source node ID', required: true },+ to: { type: 'string', description: 'Target node ID', required: true },+ depth: { type: 'number', description: 'Max tree depth (default: 10)' }+ },+ execute: (figma, args) => {+ const maxDepth = args.depth ?? 10+ const fromNode = figma.graph.getNode(args.from)+ const toNode = figma.graph.getNode(args.to)+ if (!fromNode) return { error: `Node "${args.from}" not found` }+ if (!toNode) return { error: `Node "${args.to}" not found` }++ const fromNodes = collectNodeTree(figma, args.from, '', 0, maxDepth)+ const toNodes = collectNodeTree(figma, args.to, '', 0, maxDepth)+ const allPaths = new Set([...fromNodes.keys(), ...toNodes.keys()])++ const patches: string[] = []+ for (const path of allPaths) {+ const fromEntry = fromNodes.get(path)+ const toEntry = toNodes.get(path)++ if (!fromEntry && toEntry) {+ const filename = `${path} #${toEntry.id}`+ const newLines = toEntry.serialized.split('\n')+ patches.push(+ `--- /dev/null\n+++ ${filename}\n@@ -0,0 +1,${newLines.length} @@\n${newLines.map((l) => `+${l}`).join('\n')}`+ )+ } else if (fromEntry && !toEntry) {+ const filename = `${path} #${fromEntry.id}`+ const oldLines = fromEntry.serialized.split('\n')+ patches.push(+ `--- ${filename}\n+++ /dev/null\n@@ -1,${oldLines.length} +0,0 @@\n${oldLines.map((l) => `-${l}`).join('\n')}`+ )+ } else if (fromEntry && toEntry && fromEntry.serialized !== toEntry.serialized) {+ patches.push(+ createUnifiedDiff(+ `${path} #${fromEntry.id}`,+ `${path} #${toEntry.id}`,+ fromEntry.serialized,+ toEntry.serialized+ )+ )+ }+ }++ if (patches.length === 0) return { diff: null, message: 'No differences found' }+ return { diff: patches.join('\n') }+ }+})++export const diffShow = defineTool({+ name: 'diff_show',+ description:+ 'Preview what would change if properties were applied to a node. Shows a unified diff of current vs proposed state.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ props: {+ type: 'string',+ description:+ 'JSON object of new properties, e.g. \'{"opacity": 1, "fill": "#FF0000", "width": 200}\'',+ required: true+ }+ },+ execute: (figma, args) => {+ const raw = figma.graph.getNode(args.id)+ if (!raw) return { error: `Node "${args.id}" not found` }++ const oldContent = serializeNodeProps(raw)++ let newProps: Record<string, unknown>+ try {+ newProps = JSON.parse(args.props)+ } catch {+ return { error: 'Invalid JSON in props' }+ }++ const modified: SceneNode = structuredClone(raw)+ if (newProps.fill) {+ modified.fills = [+ { type: 'SOLID', color: parseColor(newProps.fill as string), opacity: 1, visible: true }+ ]+ }+ if (newProps.stroke) {+ modified.strokes = [+ {+ color: parseColor(newProps.stroke as string),+ weight: modified.strokes[0]?.weight ?? 1,+ opacity: 1,+ visible: true,+ align: modified.strokes[0]?.align ?? 'INSIDE'+ }+ ]+ }+ if (newProps.opacity !== undefined) modified.opacity = Number(newProps.opacity)+ if (newProps.radius !== undefined) {+ const r = Number(newProps.radius)+ modified.cornerRadius = r+ modified.topLeftRadius = r+ modified.topRightRadius = r+ modified.bottomRightRadius = r+ modified.bottomLeftRadius = r+ }+ if (newProps.width !== undefined) modified.width = Number(newProps.width)+ if (newProps.height !== undefined) modified.height = Number(newProps.height)+ if (newProps.x !== undefined) modified.x = Number(newProps.x)+ if (newProps.y !== undefined) modified.y = Number(newProps.y)+ if (newProps.visible !== undefined) modified.visible = Boolean(newProps.visible)+ if (newProps.locked !== undefined) modified.locked = Boolean(newProps.locked)+ if (newProps.rotation !== undefined) modified.rotation = Number(newProps.rotation)+ if (newProps.text !== undefined) modified.text = newProps.text as string++ const newContent = serializeNodeProps(modified)++ if (oldContent === newContent) return { diff: null, message: 'No changes' }++ const filename = `/${raw.name} #${args.id}`+ return { diff: createUnifiedDiff(filename, filename, oldContent, newContent) }+ }+})+diff --git a/packages/core/src/tools/analyze/eval.ts b/packages/core/src/tools/analyze/eval.tsnew file mode 100644index 000000000..a219b23c7--- /dev/null+++ b/packages/core/src/tools/analyze/eval.ts@@ -0,0 +1,21 @@+import { defineTool } from '#core/tools/schema'++export const evalCode = defineTool({+ name: 'eval',+ description:+ 'Execute JavaScript with full Figma Plugin API access. Use for operations not covered by other tools. The `figma` global is available.',+ params: {+ code: { type: 'string', description: 'JavaScript code to execute', required: true }+ },+ mutates: true,+ execute: async (figma, { code }) => {+ // eslint-disable-next-line no-empty-function+ const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor+ const wrapped = code.trim().startsWith('return') ? code : `return (async () => { ${code} })()`+ const fn = new AsyncFunction('figma', wrapped)+ const result = await fn(figma)+ if (result && typeof result === 'object' && 'toJSON' in result) return result.toJSON()+ if (result !== undefined && result !== null) return result+ return { ok: true, message: 'Code executed (no return value)' }+ }+})diff --git a/packages/core/src/tools/analyze/spacing.ts b/packages/core/src/tools/analyze/spacing.tsnew file mode 100644index 000000000..2ecc6fb4d--- /dev/null+++ b/packages/core/src/tools/analyze/spacing.ts@@ -0,0 +1,54 @@+import { defineTool } from '#core/tools/schema'++export const analyzeSpacing = defineTool({+ name: 'analyze_spacing',+ description:+ 'Analyze spacing values (gap, padding) across the current page. Checks grid compliance.',+ params: {+ grid: { type: 'number', description: 'Base grid size to check against (default: 8)' },+ },+ execute: (figma, args) => {+ const gridSize = args.grid ?? 8+ const page = figma.currentPage+ const gapMap = new Map<number, number>()+ const paddingMap = new Map<number, number>()+ let totalNodes = 0++ page.findAll((node) => {+ totalNodes+++ const raw = figma.graph.getNode(node.id)+ if (!raw) return false++ if (raw.layoutMode !== 'NONE' && raw.itemSpacing > 0) {+ gapMap.set(raw.itemSpacing, (gapMap.get(raw.itemSpacing) ?? 0) + 1)+ }++ for (const padding of [raw.paddingTop, raw.paddingRight, raw.paddingBottom, raw.paddingLeft]) {+ if (padding > 0) {+ paddingMap.set(padding, (paddingMap.get(padding) ?? 0) + 1)+ }+ }+ return false+ })++ const gaps = [...gapMap.entries()]+ .sort((a, b) => b[1] - a[1])+ .map(([value, count]) => ({ value, count, onGrid: value % gridSize === 0 }))++ const paddings = [...paddingMap.entries()]+ .sort((a, b) => b[1] - a[1])+ .map(([value, count]) => ({ value, count, onGrid: value % gridSize === 0 }))++ const offGridGaps = gaps.filter((gap) => !gap.onGrid)+ const offGridPaddings = paddings.filter((padding) => !padding.onGrid)++ return {+ totalNodes,+ gridSize,+ gaps,+ paddings,+ offGridGaps: offGridGaps.map((gap) => gap.value),+ offGridPaddings: offGridPaddings.map((padding) => padding.value),+ }+ },+})diff --git a/packages/core/src/tools/analyze/typography.ts b/packages/core/src/tools/analyze/typography.tsnew file mode 100644index 000000000..9062ffc81--- /dev/null+++ b/packages/core/src/tools/analyze/typography.ts@@ -0,0 +1,88 @@+import { defineTool } from '#core/tools/schema'++export const analyzeTypography = defineTool({+ name: 'analyze_typography',+ description:+ 'Analyze typography usage across the current page. Shows font families, sizes, weights, and their frequencies.',+ params: {+ limit: { type: 'number', description: 'Max styles to return (default: 30)' },+ group_by: {+ type: 'string',+ description: 'Group results by a property',+ enum: ['family', 'size', 'weight']+ }+ },+ execute: (figma, args) => {+ const limit = args.limit ?? 30+ const page = figma.currentPage+ const styleMap = new Map<+ string,+ { family: string; size: number; weight: number; lineHeight: string; count: number }+ >()+ let totalTextNodes = 0++ page.findAll((node) => {+ if (node.type !== 'TEXT') return false+ totalTextNodes+++ const raw = figma.graph.getNode(node.id)+ if (!raw) return false+ const lh = raw.lineHeight === null ? 'auto' : `${raw.lineHeight}`+ const key = `${raw.fontFamily}|${raw.fontSize}|${raw.fontWeight}|${lh}`+ const entry = styleMap.get(key)+ if (entry) {+ entry.count+++ } else {+ styleMap.set(key, {+ family: raw.fontFamily,+ size: raw.fontSize,+ weight: raw.fontWeight,+ lineHeight: lh,+ count: 1+ })+ }+ return false+ })++ const styles = [...styleMap.values()].sort((a, b) => b.count - a.count)++ if (args.group_by === 'family') {+ const byFamily = new Map<string, number>()+ for (const s of styles) byFamily.set(s.family, (byFamily.get(s.family) ?? 0) + s.count)+ return {+ totalTextNodes,+ groups: [...byFamily.entries()]+ .sort((a, b) => b[1] - a[1])+ .map(([family, count]) => ({ family, count }))+ }+ }++ if (args.group_by === 'size') {+ const bySize = new Map<number, number>()+ for (const s of styles) bySize.set(s.size, (bySize.get(s.size) ?? 0) + s.count)+ return {+ totalTextNodes,+ groups: [...bySize.entries()]+ .sort((a, b) => a[0] - b[0])+ .map(([size, count]) => ({ size, count }))+ }+ }++ if (args.group_by === 'weight') {+ const byWeight = new Map<number, number>()+ for (const s of styles) byWeight.set(s.weight, (byWeight.get(s.weight) ?? 0) + s.count)+ return {+ totalTextNodes,+ groups: [...byWeight.entries()]+ .sort((a, b) => b[1] - a[1])+ .map(([weight, count]) => ({ weight, count }))+ }+ }++ return {+ totalTextNodes,+ uniqueStyles: styleMap.size,+ styles: styles.slice(0, limit)+ }+ }+})+diff --git a/packages/core/src/tools/codegen.ts b/packages/core/src/tools/codegen.tsindex 6b8d13ff5..b48f7fe4c 100644--- a/packages/core/src/tools/codegen.ts+++ b/packages/core/src/tools/codegen.ts@@ -1,416 +1,2 @@-import { colorToHex } from '../color'-import { defineTool } from './schema'--import type { FigmaAPI } from '../figma-api'-import type {- SceneGraph,- Variable,- VariableCollection,- VariableValue,- SceneNode-} from '../scene-graph'-import type { Color } from '../types'--function slugify(name: string): string {- return name- .replace(/\//g, '-')- .replace(/\s+/g, '-')- .replace(/[^a-zA-Z0-9-]/g, '')- .replace(/-+/g, '-')- .replace(/^-|-$/g, '')- .toLowerCase()-}--function toCamelCase(name: string): string {- return slugify(name).replace(/-([a-z])/g, (_, c) => c.toUpperCase())-}--function isColor(value: VariableValue): value is Color {- return typeof value === 'object' && 'r' in value && 'g' in value && 'b' in value-}--function isAlias(value: VariableValue): value is { aliasId: string } {- return typeof value === 'object' && 'aliasId' in value-}--function resolveValue(- value: VariableValue,- variables: Map<string, Variable>,- visited = new Set<string>()-): VariableValue {- if (!isAlias(value)) return value- if (visited.has(value.aliasId)) return value- visited.add(value.aliasId)- const target = variables.get(value.aliasId)- if (!target) return value- const modeId = Object.keys(target.valuesByMode)[0]- if (!modeId) return value- return resolveValue(target.valuesByMode[modeId], variables, visited)-}--function formatCSSValue(value: VariableValue, variables: Map<string, Variable>): string {- const resolved = resolveValue(value, variables)- if (isColor(resolved)) return colorToHex(resolved)- if (typeof resolved === 'number') return String(resolved)- if (typeof resolved === 'string') return resolved- if (typeof resolved === 'boolean') return resolved ? '1' : '0'- if (isAlias(resolved)) return `/* unresolved alias: ${resolved.aliasId} */`- return String(resolved)-}--interface TokenEntry {- name: string- cssVar: string- type: string- values: Partial<Record<string, string>>-}--function buildTokens(- variables: Variable[],- collections: VariableCollection[],- allVars: Map<string, Variable>-): { tokens: TokenEntry[]; modes: { id: string; name: string; collectionName: string }[] } {- const collectionMap = new Map<string, VariableCollection>()- for (const c of collections) collectionMap.set(c.id, c)-- const modes: { id: string; name: string; collectionName: string }[] = []- const seenModes = new Set<string>()- for (const c of collections) {- for (const m of c.modes) {- if (!seenModes.has(m.modeId)) {- seenModes.add(m.modeId)- modes.push({ id: m.modeId, name: m.name, collectionName: c.name })- }- }- }-- const tokens: TokenEntry[] = []- for (const v of variables) {- const col = collectionMap.get(v.collectionId)- const prefix = col ? slugify(col.name) : 'token'- const cssVar = `--${prefix}-${slugify(v.name)}`-- const values: Record<string, string> = {}- for (const [modeId, val] of Object.entries(v.valuesByMode)) {- values[modeId] = formatCSSValue(val, allVars)- }-- tokens.push({ name: v.name, cssVar, type: v.type, values })- }-- return { tokens, modes }-}--function renderCSS(- tokens: TokenEntry[],- modes: { id: string; name: string; collectionName: string }[]-): string {- if (tokens.length === 0) return '/* No design tokens found */\n'-- const defaultModeId = modes[0]?.id ?? ''- const lines: string[] = [':root {']-- for (const t of tokens) {- const val = t.values[defaultModeId] ?? Object.values(t.values)[0] ?? ''- lines.push(` ${t.cssVar}: ${val};`)- }- lines.push('}')-- for (const mode of modes.slice(1)) {- const className = slugify(mode.name)- lines.push('')- lines.push(`/* ${mode.collectionName} / ${mode.name} */`)- lines.push(`.${className} {`)- for (const t of tokens) {- const val = t.values[mode.id]- if (val !== undefined) lines.push(` ${t.cssVar}: ${val};`)- }- lines.push('}')- }-- return lines.join('\n') + '\n'-}--function renderTailwindTheme(tokens: TokenEntry[], modes: { id: string; name: string }[]): string {- const defaultModeId = modes[0]?.id ?? ''- const colors: Record<string, string> = {}- const spacing: Record<string, string> = {}- const other: Record<string, string> = {}-- for (const t of tokens) {- const key = toCamelCase(t.name)- const val = t.values[defaultModeId] ?? Object.values(t.values)[0] ?? ''- if (t.type === 'COLOR') colors[key] = val- else if (t.type === 'FLOAT') spacing[key] = `${val}px`- else other[key] = val- }-- const theme: Record<string, unknown> = {}- if (Object.keys(colors).length > 0) theme.colors = colors- if (Object.keys(spacing).length > 0) theme.spacing = spacing-- return `// Auto-extracted from Figma design tokens-export const designTokens = ${JSON.stringify(theme, null, 2)} as const-`-}--function renderJSON(tokens: TokenEntry[], modes: { id: string; name: string }[]): string {- const result: Record<string, Record<string, string>> = {}-- for (const mode of modes) {- const modeTokens: Record<string, string> = {}- for (const t of tokens) {- const val = t.values[mode.id]- if (val !== undefined) modeTokens[t.cssVar] = val- }- result[mode.name] = modeTokens- }-- return JSON.stringify(result, null, 2)-}--export const designToTokens = defineTool({- name: 'design_to_tokens',- description:- 'Extract design tokens from Figma variables as CSS custom properties, Tailwind theme config, or JSON. Resolves aliases, handles multiple modes (light/dark).',- params: {- format: {- type: 'string',- description: 'Output format',- enum: ['css', 'tailwind', 'json'],- default: 'css'- },- collection: {- type: 'string',- description: 'Filter by collection name (substring, case-insensitive)'- },- type: {- type: 'string',- description: 'Filter by variable type',- enum: ['COLOR', 'FLOAT', 'STRING', 'BOOLEAN']- }- },- execute: (figma, args) => {- const format = args.format ?? 'css'-- let variables = figma.getLocalVariables()- const collections = figma.getLocalVariableCollections()- const allVars = new Map<string, Variable>()- for (const v of variables) allVars.set(v.id, v)-- if (args.collection) {- const q = args.collection.toLowerCase()- const matchingIds = new Set(- collections.filter((c) => c.name.toLowerCase().includes(q)).map((c) => c.id)- )- variables = variables.filter((v) => matchingIds.has(v.collectionId))- }-- if (args.type) {- variables = variables.filter((v) => v.type === args.type)- }-- if (variables.length === 0) {- return { output: '/* No matching variables found */', tokenCount: 0 }- }-- const { tokens, modes } = buildTokens(variables, collections, allVars)-- let output: string- if (format === 'tailwind') output = renderTailwindTheme(tokens, modes)- else if (format === 'json') output = renderJSON(tokens, modes)- else output = renderCSS(tokens, modes)-- return { output, tokenCount: tokens.length, modeCount: modes.length }- }-})--interface ComponentInfo {- id: string- name: string- type: string- width: number- height: number- variants: string[]- instanceCount: number- propCandidates: string[]- usedOnScreens: string[]-}--interface ScreenInfo {- id: string- name: string- width: number- height: number- componentRefs: { id: string; name: string; count: number }[]- topLevelSections: number-}--function collectInstanceCounts(figma: FigmaAPI, componentIds: Set<string>): Map<string, number> {- const counts = new Map<string, number>()- const page = figma.currentPage-- page.findAll((node) => {- if (node.type !== 'INSTANCE') return false- const raw = figma.graph.getNode(node.id)- if (!raw?.componentId) return false- if (componentIds.has(raw.componentId)) {- counts.set(raw.componentId, (counts.get(raw.componentId) ?? 0) + 1)- }- return false- })-- return counts-}--function detectPropCandidates(node: SceneNode, graph: SceneGraph): string[] {- const props: string[] = []-- for (const childId of node.childIds) {- const child = graph.getNode(childId)- if (!child) continue- if (child.type === 'TEXT' && child.text) {- props.push(`text:${child.name}`)- }- if (child.fills.some((f) => f.visible && f.type === 'SOLID')) {- const hasBoundVar = Object.keys(child.boundVariables).length > 0- if (hasBoundVar) props.push(`color:${child.name}`)- }- if (child.type === 'FRAME' || child.type === 'GROUP') {- props.push(`slot:${child.name}`)- }- }-- return props-}--function detectVariants(componentNode: SceneNode, graph: SceneGraph): string[] {- if (componentNode.type !== 'COMPONENT_SET') return []-- const variants: string[] = []- for (const childId of componentNode.childIds) {- const child = graph.getNode(childId)- if (child?.type === 'COMPONENT') variants.push(child.name)- }- return variants-}--function buildScreenInfo(- figma: FigmaAPI,- frameNode: SceneNode,- componentIds: Set<string>-): ScreenInfo {- const refs = new Map<string, { name: string; count: number }>()- let topLevelSections = 0-- const walk = (nodeId: string) => {- const node = figma.graph.getNode(nodeId)- if (!node) return- if (node.type === 'SECTION') topLevelSections++- if (node.type === 'INSTANCE' && node.componentId && componentIds.has(node.componentId)) {- const entry = refs.get(node.componentId)- if (entry) entry.count++- else {- const comp = figma.graph.getNode(node.componentId)- refs.set(node.componentId, { name: comp?.name ?? node.componentId, count: 1 })- }- }- for (const childId of node.childIds) walk(childId)- }-- for (const childId of frameNode.childIds) walk(childId)-- return {- id: frameNode.id,- name: frameNode.name,- width: frameNode.width,- height: frameNode.height,- componentRefs: [...refs.entries()].map(([id, { name, count }]) => ({ id, name, count })),- topLevelSections- }-}--export const designToComponentMap = defineTool({- name: 'design_to_component_map',- description:- 'Analyze the document and return a structured component decomposition: components (with variants, props, instance counts), screens, and a dependency overview.',- params: {- page: {- type: 'string',- description: 'Page name to analyze (default: current page)'- }- },- execute: (figma, args) => {- if (args.page) {- const target = figma.root.children.find((p) => p.name === args.page)- if (target) figma.currentPage = target- else return { error: `Page "${args.page}" not found` }- }-- const page = figma.currentPage- const components: ComponentInfo[] = []- const componentIds = new Set<string>()-- page.findAll((node) => {- if (node.type !== 'COMPONENT' && node.type !== 'COMPONENT_SET') return false- const raw = figma.graph.getNode(node.id)- if (!raw) return false-- componentIds.add(raw.id)- components.push({- id: raw.id,- name: raw.name,- type: raw.type,- width: raw.width,- height: raw.height,- variants: detectVariants(raw, figma.graph),- instanceCount: 0,- propCandidates: detectPropCandidates(raw, figma.graph),- usedOnScreens: []- })- return false- })-- const instanceCounts = collectInstanceCounts(figma, componentIds)- for (const comp of components) {- comp.instanceCount = instanceCounts.get(comp.id) ?? 0- }-- const screens: ScreenInfo[] = []- const topFrames = page.children.filter((child) => {- const raw = figma.graph.getNode(child.id)- if (!raw) return false- if (raw.type === 'COMPONENT' || raw.type === 'COMPONENT_SET') return false- if (raw.type === 'SECTION') return false- return raw.width >= 200 && raw.height >= 200- })-- for (const frame of topFrames) {- const raw = figma.graph.getNode(frame.id)- if (!raw) continue- const screen = buildScreenInfo(figma, raw, componentIds)- screens.push(screen)-- for (const ref of screen.componentRefs) {- const comp = components.find((c) => c.id === ref.id)- if (comp) comp.usedOnScreens.push(screen.name)- }- }-- const sections: { id: string; name: string; childCount: number }[] = []- for (const child of page.children) {- const raw = figma.graph.getNode(child.id)- if (raw?.type === 'SECTION') {- sections.push({ id: raw.id, name: raw.name, childCount: raw.childIds.length })- }- }-- return {- componentCount: components.length,- screenCount: screens.length,- components: components.sort((a, b) => b.instanceCount - a.instanceCount),- screens,- sections- }- }-})+export { designToComponentMap } from './codegen/component-map'+export { designToTokens } from './codegen/tokens'diff --git a/packages/core/src/tools/codegen/component-map.ts b/packages/core/src/tools/codegen/component-map.tsnew file mode 100644index 000000000..b91d2ac71--- /dev/null+++ b/packages/core/src/tools/codegen/component-map.ts@@ -0,0 +1,194 @@+import { defineTool } from '#core/tools/schema'++import type { FigmaAPI } from '#core/figma-api'+import type { SceneGraph, SceneNode } from '#core/scene-graph'++interface ComponentInfo {+ id: string+ name: string+ type: string+ width: number+ height: number+ variants: string[]+ instanceCount: number+ propCandidates: string[]+ usedOnScreens: string[]+}++interface ScreenInfo {+ id: string+ name: string+ width: number+ height: number+ componentRefs: { id: string; name: string; count: number }[]+ topLevelSections: number+}++function collectInstanceCounts(figma: FigmaAPI, componentIds: Set<string>): Map<string, number> {+ const counts = new Map<string, number>()+ const page = figma.currentPage++ page.findAll((node) => {+ if (node.type !== 'INSTANCE') return false+ const raw = figma.graph.getNode(node.id)+ if (!raw?.componentId) return false+ if (componentIds.has(raw.componentId)) {+ counts.set(raw.componentId, (counts.get(raw.componentId) ?? 0) + 1)+ }+ return false+ })++ return counts+}++function detectPropCandidates(node: SceneNode, graph: SceneGraph): string[] {+ const props: string[] = []++ for (const childId of node.childIds) {+ const child = graph.getNode(childId)+ if (!child) continue+ if (child.type === 'TEXT' && child.text) {+ props.push(`text:${child.name}`)+ }+ if (child.fills.some((fill) => fill.visible && fill.type === 'SOLID')) {+ const hasBoundVar = Object.keys(child.boundVariables).length > 0+ if (hasBoundVar) props.push(`color:${child.name}`)+ }+ if (child.type === 'FRAME' || child.type === 'GROUP') {+ props.push(`slot:${child.name}`)+ }+ }++ return props+}++function detectVariants(componentNode: SceneNode, graph: SceneGraph): string[] {+ if (componentNode.type !== 'COMPONENT_SET') return []++ const variants: string[] = []+ for (const childId of componentNode.childIds) {+ const child = graph.getNode(childId)+ if (child?.type === 'COMPONENT') variants.push(child.name)+ }+ return variants+}++function buildScreenInfo(+ figma: FigmaAPI,+ frameNode: SceneNode,+ componentIds: Set<string>+): ScreenInfo {+ const refs = new Map<string, { name: string; count: number }>()+ let topLevelSections = 0++ const walk = (nodeId: string) => {+ const node = figma.graph.getNode(nodeId)+ if (!node) return+ if (node.type === 'SECTION') topLevelSections+++ if (node.type === 'INSTANCE' && node.componentId && componentIds.has(node.componentId)) {+ const entry = refs.get(node.componentId)+ if (entry) entry.count+++ else {+ const component = figma.graph.getNode(node.componentId)+ refs.set(node.componentId, { name: component?.name ?? node.componentId, count: 1 })+ }+ }+ for (const childId of node.childIds) walk(childId)+ }++ for (const childId of frameNode.childIds) walk(childId)++ return {+ id: frameNode.id,+ name: frameNode.name,+ width: frameNode.width,+ height: frameNode.height,+ componentRefs: [...refs.entries()].map(([id, { name, count }]) => ({ id, name, count })),+ topLevelSections,+ }+}++export const designToComponentMap = defineTool({+ name: 'design_to_component_map',+ description:+ 'Analyze the document and return a structured component decomposition: components (with variants, props, instance counts), screens, and a dependency overview.',+ params: {+ page: {+ type: 'string',+ description: 'Page name to analyze (default: current page)',+ },+ },+ execute: (figma, args) => {+ if (args.page) {+ const target = figma.root.children.find((page) => page.name === args.page)+ if (target) figma.currentPage = target+ else return { error: `Page "${args.page}" not found` }+ }++ const page = figma.currentPage+ const components: ComponentInfo[] = []+ const componentIds = new Set<string>()++ page.findAll((node) => {+ if (node.type !== 'COMPONENT' && node.type !== 'COMPONENT_SET') return false+ const raw = figma.graph.getNode(node.id)+ if (!raw) return false++ componentIds.add(raw.id)+ components.push({+ id: raw.id,+ name: raw.name,+ type: raw.type,+ width: raw.width,+ height: raw.height,+ variants: detectVariants(raw, figma.graph),+ instanceCount: 0,+ propCandidates: detectPropCandidates(raw, figma.graph),+ usedOnScreens: [],+ })+ return false+ })++ const instanceCounts = collectInstanceCounts(figma, componentIds)+ for (const component of components) {+ component.instanceCount = instanceCounts.get(component.id) ?? 0+ }++ const screens: ScreenInfo[] = []+ const topFrames = page.children.filter((child) => {+ const raw = figma.graph.getNode(child.id)+ if (!raw) return false+ if (raw.type === 'COMPONENT' || raw.type === 'COMPONENT_SET') return false+ if (raw.type === 'SECTION') return false+ return raw.width >= 200 && raw.height >= 200+ })++ for (const frame of topFrames) {+ const raw = figma.graph.getNode(frame.id)+ if (!raw) continue+ const screen = buildScreenInfo(figma, raw, componentIds)+ screens.push(screen)++ for (const ref of screen.componentRefs) {+ const component = components.find((candidate) => candidate.id === ref.id)+ if (component) component.usedOnScreens.push(screen.name)+ }+ }++ const sections: { id: string; name: string; childCount: number }[] = []+ for (const child of page.children) {+ const raw = figma.graph.getNode(child.id)+ if (raw?.type === 'SECTION') {+ sections.push({ id: raw.id, name: raw.name, childCount: raw.childIds.length })+ }+ }++ return {+ componentCount: components.length,+ screenCount: screens.length,+ components: components.sort((a, b) => b.instanceCount - a.instanceCount),+ screens,+ sections,+ }+ },+})diff --git a/packages/core/src/tools/codegen/tokens.ts b/packages/core/src/tools/codegen/tokens.tsnew file mode 100644index 000000000..c2f7b8982--- /dev/null+++ b/packages/core/src/tools/codegen/tokens.ts@@ -0,0 +1,219 @@+import { colorToHex } from '#core/color'+import { defineTool } from '#core/tools/schema'++import type { Color } from '#core/types'+import type { Variable, VariableCollection, VariableValue } from '#core/scene-graph'++function slugify(name: string): string {+ return name+ .replace(/\//g, '-')+ .replace(/\s+/g, '-')+ .replace(/[^a-zA-Z0-9-]/g, '')+ .replace(/-+/g, '-')+ .replace(/^-|-$/g, '')+ .toLowerCase()+}++function toCamelCase(name: string): string {+ return slugify(name).replace(/-([a-z])/g, (_, c) => c.toUpperCase())+}++function isColor(value: VariableValue): value is Color {+ return typeof value === 'object' && 'r' in value && 'g' in value && 'b' in value+}++function isAlias(value: VariableValue): value is { aliasId: string } {+ return typeof value === 'object' && 'aliasId' in value+}++function resolveValue(+ value: VariableValue,+ variables: Map<string, Variable>,+ visited = new Set<string>()+): VariableValue {+ if (!isAlias(value)) return value+ if (visited.has(value.aliasId)) return value+ visited.add(value.aliasId)+ const target = variables.get(value.aliasId)+ if (!target) return value+ const modeId = Object.keys(target.valuesByMode)[0]+ if (!modeId) return value+ return resolveValue(target.valuesByMode[modeId], variables, visited)+}++function formatCSSValue(value: VariableValue, variables: Map<string, Variable>): string {+ const resolved = resolveValue(value, variables)+ if (isColor(resolved)) return colorToHex(resolved)+ if (typeof resolved === 'number') return String(resolved)+ if (typeof resolved === 'string') return resolved+ if (typeof resolved === 'boolean') return resolved ? '1' : '0'+ if (isAlias(resolved)) return `/* unresolved alias: ${resolved.aliasId} */`+ return String(resolved)+}++interface TokenEntry {+ name: string+ cssVar: string+ type: string+ values: Partial<Record<string, string>>+}++function buildTokens(+ variables: Variable[],+ collections: VariableCollection[],+ allVars: Map<string, Variable>+): { tokens: TokenEntry[]; modes: { id: string; name: string; collectionName: string }[] } {+ const collectionMap = new Map<string, VariableCollection>()+ for (const collection of collections) collectionMap.set(collection.id, collection)++ const modes: { id: string; name: string; collectionName: string }[] = []+ const seenModes = new Set<string>()+ for (const collection of collections) {+ for (const mode of collection.modes) {+ if (!seenModes.has(mode.modeId)) {+ seenModes.add(mode.modeId)+ modes.push({ id: mode.modeId, name: mode.name, collectionName: collection.name })+ }+ }+ }++ const tokens: TokenEntry[] = []+ for (const variable of variables) {+ const collection = collectionMap.get(variable.collectionId)+ const prefix = collection ? slugify(collection.name) : 'token'+ const cssVar = `--${prefix}-${slugify(variable.name)}`++ const values: Record<string, string> = {}+ for (const [modeId, value] of Object.entries(variable.valuesByMode)) {+ values[modeId] = formatCSSValue(value, allVars)+ }++ tokens.push({ name: variable.name, cssVar, type: variable.type, values })+ }++ return { tokens, modes }+}++function renderCSS(+ tokens: TokenEntry[],+ modes: { id: string; name: string; collectionName: string }[]+): string {+ if (tokens.length === 0) return '/* No design tokens found */\n'++ const defaultModeId = modes[0]?.id ?? ''+ const lines: string[] = [':root {']++ for (const token of tokens) {+ const value = token.values[defaultModeId] ?? Object.values(token.values)[0] ?? ''+ lines.push(` ${token.cssVar}: ${value};`)+ }+ lines.push('}')++ for (const mode of modes.slice(1)) {+ const className = slugify(mode.name)+ lines.push('')+ lines.push(`/* ${mode.collectionName} / ${mode.name} */`)+ lines.push(`.${className} {`)+ for (const token of tokens) {+ const value = token.values[mode.id]+ if (value !== undefined) lines.push(` ${token.cssVar}: ${value};`)+ }+ lines.push('}')+ }++ return `${lines.join('\n')}\n`+}++function renderTailwindTheme(tokens: TokenEntry[], modes: { id: string; name: string }[]): string {+ const defaultModeId = modes[0]?.id ?? ''+ const colors: Record<string, string> = {}+ const spacing: Record<string, string> = {}++ for (const token of tokens) {+ const key = toCamelCase(token.name)+ const value = token.values[defaultModeId] ?? Object.values(token.values)[0] ?? ''+ if (token.type === 'COLOR') colors[key] = value+ else if (token.type === 'FLOAT') spacing[key] = `${value}px`+ }++ const theme: Record<string, unknown> = {}+ if (Object.keys(colors).length > 0) theme.colors = colors+ if (Object.keys(spacing).length > 0) theme.spacing = spacing++ return `// Auto-extracted from Figma design tokens+export const designTokens = ${JSON.stringify(theme, null, 2)} as const+`+}++function renderJSON(tokens: TokenEntry[], modes: { id: string; name: string }[]): string {+ const result: Record<string, Record<string, string>> = {}++ for (const mode of modes) {+ const modeTokens: Record<string, string> = {}+ for (const token of tokens) {+ const value = token.values[mode.id]+ if (value !== undefined) modeTokens[token.cssVar] = value+ }+ result[mode.name] = modeTokens+ }++ return JSON.stringify(result, null, 2)+}++export const designToTokens = defineTool({+ name: 'design_to_tokens',+ description:+ 'Extract design tokens from Figma variables as CSS custom properties, Tailwind theme config, or JSON. Resolves aliases, handles multiple modes (light/dark).',+ params: {+ format: {+ type: 'string',+ description: 'Output format',+ enum: ['css', 'tailwind', 'json'],+ default: 'css',+ },+ collection: {+ type: 'string',+ description: 'Filter by collection name (substring, case-insensitive)',+ },+ type: {+ type: 'string',+ description: 'Filter by variable type',+ enum: ['COLOR', 'FLOAT', 'STRING', 'BOOLEAN'],+ },+ },+ execute: (figma, args) => {+ const format = args.format ?? 'css'++ let variables = figma.getLocalVariables()+ const collections = figma.getLocalVariableCollections()+ const allVars = new Map<string, Variable>()+ for (const variable of variables) allVars.set(variable.id, variable)++ if (args.collection) {+ const query = args.collection.toLowerCase()+ const matchingIds = new Set(+ collections+ .filter((collection) => collection.name.toLowerCase().includes(query))+ .map((collection) => collection.id)+ )+ variables = variables.filter((variable) => matchingIds.has(variable.collectionId))+ }++ if (args.type) {+ variables = variables.filter((variable) => variable.type === args.type)+ }++ if (variables.length === 0) {+ return { output: '/* No matching variables found */', tokenCount: 0 }+ }++ const { tokens, modes } = buildTokens(variables, collections, allVars)++ let output: string+ if (format === 'tailwind') output = renderTailwindTheme(tokens, modes)+ else if (format === 'json') output = renderJSON(tokens, modes)+ else output = renderCSS(tokens, modes)++ return { output, tokenCount: tokens.length, modeCount: modes.length }+ },+})diff --git a/packages/core/src/tools/create-icons.ts b/packages/core/src/tools/create-icons.tsnew file mode 100644index 000000000..23a7d934f--- /dev/null+++ b/packages/core/src/tools/create-icons.ts@@ -0,0 +1,122 @@+import { parseColor } from '#core/color'+import { fetchIcons, searchIconsBatch } from '#core/icons'+import { createIconFromPaths } from '#core/icons/render'+import { defineTool } from './schema'++export const fetchIconsTool = defineTool({+ name: 'fetch_icons',+ description:+ 'Pre-fetch icons from Iconify into cache. Batches by prefix (one HTTP request per set). Call this once with all needed icons, then use insert_icon to place them instantly. Popular sets: lucide (outline), mdi (filled), heroicons, tabler, solar, mingcute, ri (remix).',+ params: {+ names: {+ type: 'string[]',+ description: 'Icon names as prefix:name (e.g. ["lucide:heart", "lucide:home", "mdi:star"])',+ required: true,+ },+ size: { type: 'number', description: 'Icon size in pixels (default: 24)' },+ },+ execute: async (_figma, args) => {+ const size = args.size ?? 24+ try {+ const icons = await fetchIcons(args.names, size)+ const fetched = [...icons.keys()]+ const notFound = args.names.filter((name) => !icons.has(name))+ const result: Record<string, unknown> = { fetched, count: fetched.length }+ if (notFound.length > 0) result.not_found = notFound+ return result+ } catch (e) {+ return { error: (e as Error).message }+ }+ },+})++export const insertIcon = defineTool({+ name: 'insert_icon',+ mutates: true,+ description:+ 'Insert one or more vector icons onto the canvas. Pass a single name or multiple names to batch-insert into the same parent. If already cached by fetch_icons — instant, no network request.',+ params: {+ names: {+ type: 'string[]',+ description:+ 'Icon names as prefix:name (e.g. ["lucide:heart"] or ["lucide:heart","lucide:home","lucide:star"])',+ },+ name: {+ type: 'string',+ description: 'Single icon name (shorthand for names with one icon)',+ },+ size: { type: 'number', description: 'Icon size in pixels (default: 24)' },+ color: {+ type: 'color',+ description: 'Icon color hex (replaces currentColor). Default: #000000',+ },+ parent_id: { type: 'string', description: 'Parent node ID for all icons' },+ },+ execute: async (figma, args) => {+ const names = args.names ?? (args.name ? [args.name] : [])+ if (names.length === 0) return { error: 'Provide "names" (array) or "name" (string)' }++ const size = args.size ?? 24+ const color = args.color ?? '#000000'+ const parsedColor = parseColor(color)++ let icons+ try {+ icons = await fetchIcons(names, size)+ } catch (e) {+ return { error: (e as Error).message }+ }++ const inserted: { id: string; name: string; icon: string }[] = []+ const notFound: string[] = []++ for (const name of names) {+ const icon = icons.get(name)+ if (!icon || icon.paths.length === 0) {+ notFound.push(name)+ continue+ }+ const parentId = args.parent_id ?? figma.currentPage.id+ const frame = createIconFromPaths(figma.graph, icon, name, size, parsedColor, parentId)+ inserted.push({ id: frame.id, name: frame.name, icon: name })+ }++ if (args.name && inserted.length === 1) {+ return { id: inserted[0].id, name: inserted[0].name, type: 'FRAME' as const }+ }++ const result: Record<string, unknown> = { inserted }+ if (notFound.length > 0) result.not_found = notFound+ return result+ },+})++export const searchIconsTool = defineTool({+ name: 'search_icons',+ description:+ 'Search Iconify for icons by keyword. Accepts multiple queries — all searched in parallel. Returns results keyed by query.',+ params: {+ queries: {+ type: 'string[]',+ description: 'Search keywords (e.g. ["heart", "arrow", "settings"])',+ required: true,+ },+ limit: { type: 'number', description: 'Max results per query (default: 5)' },+ prefix: { type: 'string', description: 'Filter by icon set prefix (e.g. "lucide", "mdi")' },+ },+ execute: async (_figma, args) => {+ try {+ const results = await searchIconsBatch(args.queries, {+ limit: args.limit ?? 5,+ prefix: args.prefix,+ })+ const output: Record<string, { icons: string[]; total: number }> = {}+ for (const [query, result] of results) {+ output[query] = { icons: result.icons, total: result.total }+ }+ return output+ } catch (e) {+ return { error: (e as Error).message }+ }+ },+})diff --git a/packages/core/src/tools/create.ts b/packages/core/src/tools/create.tsindex 26b62aae8..b1f4796fb 100644--- a/packages/core/src/tools/create.ts+++ b/packages/core/src/tools/create.ts@@ -1,357 +1,5 @@-import { parseColor } from '../color'-import { fetchIcons, searchIconsBatch } from '../icons'-import { createIconFromPaths } from '../icons/render'-import { normalizeVectorNetwork, validateVectorNetwork } from '../scene-graph'-import { defineTool, nodeSummary } from './schema'--import type { FigmaNodeProxy } from '../figma-api'-import type { VectorNetwork } from '../scene-graph'--export const createShape = defineTool({- name: 'create_shape',- mutates: true,- description:- 'Create a shape on the canvas. Use FRAME for containers/cards, RECTANGLE for solid blocks, ELLIPSE for circles, TEXT for labels, SECTION for page sections.',- params: {- type: {- type: 'string',- description: 'Node type',- required: true,- enum: ['FRAME', 'RECTANGLE', 'ELLIPSE', 'TEXT', 'LINE', 'STAR', 'POLYGON', 'SECTION']- },- x: { type: 'number', description: 'X position', required: true },- y: { type: 'number', description: 'Y position', required: true },- width: { type: 'number', description: 'Width in pixels', required: true, min: 1 },- height: { type: 'number', description: 'Height in pixels', required: true, min: 1 },- name: { type: 'string', description: 'Node name shown in layers panel' },- parent_id: { type: 'string', description: 'Parent node ID to nest inside' }- },- execute: (figma, args) => {- const parentId = args.parent_id- const parent = parentId ? figma.getNodeById(parentId) : null- const createMap: Record<string, () => FigmaNodeProxy> = {- FRAME: () => figma.createFrame(),- RECTANGLE: () => figma.createRectangle(),- ELLIPSE: () => figma.createEllipse(),- TEXT: () => figma.createText(),- LINE: () => figma.createLine(),- STAR: () => figma.createStar(),- POLYGON: () => figma.createPolygon(),- SECTION: () => figma.createSection()- }- const node = createMap[args.type]()- node.x = args.x- node.y = args.y- node.resize(args.width, args.height)- if (args.name) node.name = args.name- if (parent) parent.appendChild(node)- return nodeSummary(node)- }-})--export const render = defineTool({- name: 'render',- mutates: true,- description:- 'Render JSX to design nodes. Use replace_id to swap a skeleton placeholder with real content (keeps position in parent). Example: <Frame name="Card" w={320} h="hug" flex="col" gap={16} p={24} bg="#FFF" rounded={16}><Text size={18} weight="bold">Title</Text></Frame>',- params: {- replace_id: {- type: 'string',- description: 'Node ID to replace — new node takes its position in parent, old node is deleted'- },- parent_id: { type: 'string', description: 'Parent node ID to render into' },- insert_index: {- type: 'number',- description: 'Position among siblings (0 = first child). Omit to append at end.'- },- x: { type: 'number', description: 'X position of the root node' },- y: { type: 'number', description: 'Y position of the root node' },- jsx: { type: 'string', description: 'JSX string to render', required: true }- },- execute: async (figma, args) => {- const { renderJSX } = await import('../design-jsx/render.js')-- let parentId = args.parent_id ?? figma.currentPageId- let replaceIndex = -1-- if (args.replace_id) {- const target = figma.graph.getNode(args.replace_id)- if (target?.parentId) {- parentId = target.parentId- const parent = figma.graph.getNode(parentId)- if (parent) {- replaceIndex = parent.childIds.indexOf(args.replace_id)- }- }- }-- const results = await renderJSX(figma.graph, args.jsx, {- parentId,- x: args.x,- y: args.y- })- const result = results[0]-- if (args.replace_id && replaceIndex >= 0) {- figma.graph.reorderChild(result.id, parentId, replaceIndex)- figma.graph.deleteNode(args.replace_id)- } else if (args.insert_index !== undefined) {- figma.graph.reorderChild(result.id, parentId, args.insert_index)- }-- return {- id: result.id,- name: result.name,- type: result.type,- children: result.childIds,- ...(results.length > 1- ? { siblings: results.slice(1).map((r) => ({ id: r.id, name: r.name, type: r.type })) }- : {})- }- }-})--export const createComponent = defineTool({- name: 'create_component',- mutates: true,- description: 'Convert a frame/group into a component.',- params: {- id: { type: 'string', description: 'Node ID to convert', required: true }- },- execute: (figma, { id }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- const comp = figma.createComponentFromNode(node)- return nodeSummary(comp)- }-})--export const createInstance = defineTool({- name: 'create_instance',- mutates: true,- description: 'Create an instance of a component.',- params: {- component_id: { type: 'string', description: 'Component node ID', required: true },- x: { type: 'number', description: 'X position' },- y: { type: 'number', description: 'Y position' }- },- execute: (figma, args) => {- const comp = figma.getNodeById(args.component_id)- if (!comp) return { error: `Component "${args.component_id}" not found` }- const instance = comp.createInstance()- if (args.x !== undefined) instance.x = args.x- if (args.y !== undefined) instance.y = args.y- return nodeSummary(instance)- }-})--export const createPage = defineTool({- name: 'create_page',- mutates: true,- description: 'Create a new page.',- params: {- name: { type: 'string', description: 'Page name', required: true }- },- execute: (figma, { name }) => {- const page = figma.createPage()- page.name = name- return { id: page.id, name }- }-})--export const createVector = defineTool({- name: 'create_vector',- mutates: true,- description: 'Create a vector node with optional path data.',- params: {- x: { type: 'number', description: 'X position', required: true },- y: { type: 'number', description: 'Y position', required: true },- name: { type: 'string', description: 'Node name' },- path: { type: 'string', description: 'VectorNetwork JSON' },- fill: { type: 'color', description: 'Fill color (hex)' },- stroke: { type: 'color', description: 'Stroke color (hex)' },- stroke_weight: { type: 'number', description: 'Stroke weight' },- parent_id: { type: 'string', description: 'Parent node ID' }- },- execute: (figma, args) => {- const node = figma.createVector()- node.x = args.x- node.y = args.y- if (args.name) node.name = args.name- if (args.path) {- let parsed: VectorNetwork- try {- parsed = JSON.parse(args.path) as VectorNetwork- } catch {- return { error: 'Invalid JSON in path parameter' }- }- const errors = validateVectorNetwork(parsed)- if (errors.length > 0) return { error: `Invalid VectorNetwork: ${errors.join('; ')}` }- figma.graph.updateNode(node.id, { vectorNetwork: normalizeVectorNetwork(parsed) })- }- if (args.fill) {- node.fills = [{ type: 'SOLID', color: parseColor(args.fill), opacity: 1, visible: true }]- }- if (args.stroke) {- node.strokes = [- {- color: parseColor(args.stroke),- weight: args.stroke_weight ?? 1,- opacity: 1,- visible: true,- align: 'CENTER'- }- ]- }- if (args.parent_id) {- const parent = figma.getNodeById(args.parent_id)- if (parent) parent.appendChild(node)- }- return nodeSummary(node)- }-})--export const createSlice = defineTool({- name: 'create_slice',- mutates: true,- description: 'Create a slice (export region) on the canvas.',- params: {- x: { type: 'number', description: 'X position', required: true },- y: { type: 'number', description: 'Y position', required: true },- width: { type: 'number', description: 'Width', required: true, min: 1 },- height: { type: 'number', description: 'Height', required: true, min: 1 },- name: { type: 'string', description: 'Slice name' },- parent_id: { type: 'string', description: 'Parent node ID' }- },- execute: (figma, args) => {- const node = figma.createFrame()- node.x = args.x- node.y = args.y- node.resize(args.width, args.height)- node.name = args.name ?? 'Slice'- node.fills = []- if (args.parent_id) {- const parent = figma.getNodeById(args.parent_id)- if (parent) parent.appendChild(node)- }- return nodeSummary(node)- }-})--export const fetchIconsTool = defineTool({- name: 'fetch_icons',- description:- 'Pre-fetch icons from Iconify into cache. Batches by prefix (one HTTP request per set). Call this once with all needed icons, then use insert_icon to place them instantly. Popular sets: lucide (outline), mdi (filled), heroicons, tabler, solar, mingcute, ri (remix).',- params: {- names: {- type: 'string[]',- description: 'Icon names as prefix:name (e.g. ["lucide:heart", "lucide:home", "mdi:star"])',- required: true- },- size: { type: 'number', description: 'Icon size in pixels (default: 24)' }- },- execute: async (_figma, args) => {- const size = args.size ?? 24- try {- const icons = await fetchIcons(args.names, size)- const fetched = [...icons.keys()]- const notFound = args.names.filter((n) => !icons.has(n))- const result: Record<string, unknown> = { fetched, count: fetched.length }- if (notFound.length > 0) result.not_found = notFound- return result- } catch (e) {- return { error: (e as Error).message }- }- }-})--export const insertIcon = defineTool({- name: 'insert_icon',- mutates: true,- description:- 'Insert one or more vector icons onto the canvas. Pass a single name or multiple names to batch-insert into the same parent. If already cached by fetch_icons — instant, no network request.',- params: {- names: {- type: 'string[]',- description:- 'Icon names as prefix:name (e.g. ["lucide:heart"] or ["lucide:heart","lucide:home","lucide:star"])'- },- name: {- type: 'string',- description: 'Single icon name (shorthand for names with one icon)'- },- size: { type: 'number', description: 'Icon size in pixels (default: 24)' },- color: {- type: 'color',- description: 'Icon color hex (replaces currentColor). Default: #000000'- },- parent_id: { type: 'string', description: 'Parent node ID for all icons' }- },- execute: async (figma, args) => {- const names = args.names ?? (args.name ? [args.name] : [])- if (names.length === 0) return { error: 'Provide "names" (array) or "name" (string)' }-- const size = args.size ?? 24- const color = args.color ?? '#000000'- const parsedColor = parseColor(color)-- let icons- try {- icons = await fetchIcons(names, size)- } catch (e) {- return { error: (e as Error).message }- }-- const inserted: { id: string; name: string; icon: string }[] = []- const notFound: string[] = []-- for (const name of names) {- const icon = icons.get(name)- if (!icon || icon.paths.length === 0) {- notFound.push(name)- continue- }- const parentId = args.parent_id ?? figma.currentPage.id- const frame = createIconFromPaths(figma.graph, icon, name, size, parsedColor, parentId)- inserted.push({ id: frame.id, name: frame.name, icon: name })- }-- if (args.name && inserted.length === 1) {- return { id: inserted[0].id, name: inserted[0].name, type: 'FRAME' as const }- }-- const result: Record<string, unknown> = { inserted }- if (notFound.length > 0) result.not_found = notFound- return result- }-})--export const searchIconsTool = defineTool({- name: 'search_icons',- description:- 'Search Iconify for icons by keyword. Accepts multiple queries — all searched in parallel. Returns results keyed by query.',- params: {- queries: {- type: 'string[]',- description: 'Search keywords (e.g. ["heart", "arrow", "settings"])',- required: true- },- limit: { type: 'number', description: 'Max results per query (default: 5)' },- prefix: { type: 'string', description: 'Filter by icon set prefix (e.g. "lucide", "mdi")' }- },- execute: async (_figma, args) => {- try {- const results = await searchIconsBatch(args.queries, {- limit: args.limit ?? 5,- prefix: args.prefix- })- const output: Record<string, { icons: string[]; total: number }> = {}- for (const [query, result] of results) {- output[query] = { icons: result.icons, total: result.total }- }- return output- } catch (e) {- return { error: (e as Error).message }- }- }-})+export { createPage, createShape, createSlice } from './create/basic'+export { createComponent, createInstance } from './create/components'+export { fetchIconsTool, insertIcon, searchIconsTool } from './create-icons'+export { render } from './create/render'+export { createVector } from './create/vector'diff --git a/packages/core/src/tools/create/basic.ts b/packages/core/src/tools/create/basic.tsnew file mode 100644index 000000000..211f4eff0--- /dev/null+++ b/packages/core/src/tools/create/basic.ts@@ -0,0 +1,86 @@+import { defineTool, nodeSummary } from '#core/tools/schema'++import type { FigmaNodeProxy } from '#core/figma-api'++export const createShape = defineTool({+ name: 'create_shape',+ mutates: true,+ description:+ 'Create a shape on the canvas. Use FRAME for containers/cards, RECTANGLE for solid blocks, ELLIPSE for circles, TEXT for labels, SECTION for page sections.',+ params: {+ type: {+ type: 'string',+ description: 'Node type',+ required: true,+ enum: ['FRAME', 'RECTANGLE', 'ELLIPSE', 'TEXT', 'LINE', 'STAR', 'POLYGON', 'SECTION'],+ },+ x: { type: 'number', description: 'X position', required: true },+ y: { type: 'number', description: 'Y position', required: true },+ width: { type: 'number', description: 'Width in pixels', required: true, min: 1 },+ height: { type: 'number', description: 'Height in pixels', required: true, min: 1 },+ name: { type: 'string', description: 'Node name shown in layers panel' },+ parent_id: { type: 'string', description: 'Parent node ID to nest inside' },+ },+ execute: (figma, args) => {+ const parentId = args.parent_id+ const parent = parentId ? figma.getNodeById(parentId) : null+ const createMap: Record<string, () => FigmaNodeProxy> = {+ FRAME: () => figma.createFrame(),+ RECTANGLE: () => figma.createRectangle(),+ ELLIPSE: () => figma.createEllipse(),+ TEXT: () => figma.createText(),+ LINE: () => figma.createLine(),+ STAR: () => figma.createStar(),+ POLYGON: () => figma.createPolygon(),+ SECTION: () => figma.createSection(),+ }+ const node = createMap[args.type]()+ node.x = args.x+ node.y = args.y+ node.resize(args.width, args.height)+ if (args.name) node.name = args.name+ if (parent) parent.appendChild(node)+ return nodeSummary(node)+ },+})++export const createPage = defineTool({+ name: 'create_page',+ mutates: true,+ description: 'Create a new page.',+ params: {+ name: { type: 'string', description: 'Page name', required: true },+ },+ execute: (figma, { name }) => {+ const page = figma.createPage()+ page.name = name+ return { id: page.id, name }+ },+})++export const createSlice = defineTool({+ name: 'create_slice',+ mutates: true,+ description: 'Create a slice (export region) on the canvas.',+ params: {+ x: { type: 'number', description: 'X position', required: true },+ y: { type: 'number', description: 'Y position', required: true },+ width: { type: 'number', description: 'Width', required: true, min: 1 },+ height: { type: 'number', description: 'Height', required: true, min: 1 },+ name: { type: 'string', description: 'Slice name' },+ parent_id: { type: 'string', description: 'Parent node ID' },+ },+ execute: (figma, args) => {+ const node = figma.createFrame()+ node.x = args.x+ node.y = args.y+ node.resize(args.width, args.height)+ node.name = args.name ?? 'Slice'+ node.fills = []+ if (args.parent_id) {+ const parent = figma.getNodeById(args.parent_id)+ if (parent) parent.appendChild(node)+ }+ return nodeSummary(node)+ },+})diff --git a/packages/core/src/tools/create/components.ts b/packages/core/src/tools/create/components.tsnew file mode 100644index 000000000..33658679b--- /dev/null+++ b/packages/core/src/tools/create/components.ts@@ -0,0 +1,35 @@+import { defineTool, nodeSummary } from '#core/tools/schema'++export const createComponent = defineTool({+ name: 'create_component',+ mutates: true,+ description: 'Convert a frame/group into a component.',+ params: {+ id: { type: 'string', description: 'Node ID to convert', required: true },+ },+ execute: (figma, { id }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ const component = figma.createComponentFromNode(node)+ return nodeSummary(component)+ },+})++export const createInstance = defineTool({+ name: 'create_instance',+ mutates: true,+ description: 'Create an instance of a component.',+ params: {+ component_id: { type: 'string', description: 'Component node ID', required: true },+ x: { type: 'number', description: 'X position' },+ y: { type: 'number', description: 'Y position' },+ },+ execute: (figma, args) => {+ const component = figma.getNodeById(args.component_id)+ if (!component) return { error: `Component "${args.component_id}" not found` }+ const instance = component.createInstance()+ if (args.x !== undefined) instance.x = args.x+ if (args.y !== undefined) instance.y = args.y+ return nodeSummary(instance)+ },+})diff --git a/packages/core/src/tools/create/render.ts b/packages/core/src/tools/create/render.tsnew file mode 100644index 000000000..94f2aed6f--- /dev/null+++ b/packages/core/src/tools/create/render.ts@@ -0,0 +1,63 @@+import { defineTool } from '#core/tools/schema'++export const render = defineTool({+ name: 'render',+ mutates: true,+ description:+ 'Render JSX to design nodes. Use replace_id to swap a skeleton placeholder with real content (keeps position in parent). Example: <Frame name="Card" w={320} h="hug" flex="col" gap={16} p={24} bg="#FFF" rounded={16}><Text size={18} weight="bold">Title</Text></Frame>',+ params: {+ replace_id: {+ type: 'string',+ description: 'Node ID to replace — new node takes its position in parent, old node is deleted',+ },+ parent_id: { type: 'string', description: 'Parent node ID to render into' },+ insert_index: {+ type: 'number',+ description: 'Position among siblings (0 = first child). Omit to append at end.',+ },+ x: { type: 'number', description: 'X position of the root node' },+ y: { type: 'number', description: 'Y position of the root node' },+ jsx: { type: 'string', description: 'JSX string to render', required: true },+ },+ execute: async (figma, args) => {+ const { renderJSX } = await import('#core/design-jsx/render.js')++ let parentId = args.parent_id ?? figma.currentPageId+ let replaceIndex = -1++ if (args.replace_id) {+ const target = figma.graph.getNode(args.replace_id)+ if (target?.parentId) {+ parentId = target.parentId+ const parent = figma.graph.getNode(parentId)+ if (parent) {+ replaceIndex = parent.childIds.indexOf(args.replace_id)+ }+ }+ }++ const results = await renderJSX(figma.graph, args.jsx, {+ parentId,+ x: args.x,+ y: args.y,+ })+ const result = results[0]++ if (args.replace_id && replaceIndex >= 0) {+ figma.graph.reorderChild(result.id, parentId, replaceIndex)+ figma.graph.deleteNode(args.replace_id)+ } else if (args.insert_index !== undefined) {+ figma.graph.reorderChild(result.id, parentId, args.insert_index)+ }++ return {+ id: result.id,+ name: result.name,+ type: result.type,+ children: result.childIds,+ ...(results.length > 1+ ? { siblings: results.slice(1).map((node) => ({ id: node.id, name: node.name, type: node.type })) }+ : {}),+ }+ },+})diff --git a/packages/core/src/tools/create/vector.ts b/packages/core/src/tools/create/vector.tsnew file mode 100644index 000000000..0b2cbcb59--- /dev/null+++ b/packages/core/src/tools/create/vector.ts@@ -0,0 +1,57 @@+import { parseColor } from '#core/color'+import { normalizeVectorNetwork, validateVectorNetwork } from '#core/scene-graph'+import { defineTool, nodeSummary } from '#core/tools/schema'++import type { VectorNetwork } from '#core/scene-graph'++export const createVector = defineTool({+ name: 'create_vector',+ mutates: true,+ description: 'Create a vector node with optional path data.',+ params: {+ x: { type: 'number', description: 'X position', required: true },+ y: { type: 'number', description: 'Y position', required: true },+ name: { type: 'string', description: 'Node name' },+ path: { type: 'string', description: 'VectorNetwork JSON' },+ fill: { type: 'color', description: 'Fill color (hex)' },+ stroke: { type: 'color', description: 'Stroke color (hex)' },+ stroke_weight: { type: 'number', description: 'Stroke weight' },+ parent_id: { type: 'string', description: 'Parent node ID' },+ },+ execute: (figma, args) => {+ const node = figma.createVector()+ node.x = args.x+ node.y = args.y+ if (args.name) node.name = args.name+ if (args.path) {+ let parsed: VectorNetwork+ try {+ parsed = JSON.parse(args.path) as VectorNetwork+ } catch {+ return { error: 'Invalid JSON in path parameter' }+ }+ const errors = validateVectorNetwork(parsed)+ if (errors.length > 0) return { error: `Invalid VectorNetwork: ${errors.join('; ')}` }+ figma.graph.updateNode(node.id, { vectorNetwork: normalizeVectorNetwork(parsed) })+ }+ if (args.fill) {+ node.fills = [{ type: 'SOLID', color: parseColor(args.fill), opacity: 1, visible: true }]+ }+ if (args.stroke) {+ node.strokes = [+ {+ color: parseColor(args.stroke),+ weight: args.stroke_weight ?? 1,+ opacity: 1,+ visible: true,+ align: 'CENTER',+ },+ ]+ }+ if (args.parent_id) {+ const parent = figma.getNodeById(args.parent_id)+ if (parent) parent.appendChild(node)+ }+ return nodeSummary(node)+ },+})diff --git a/packages/core/src/tools/describe.ts b/packages/core/src/tools/describe.tsdeleted file mode 100644index 0489d61b0..000000000--- a/packages/core/src/tools/describe.ts+++ /dev/null@@ -1,276 +0,0 @@-import { colorToHex } from '../color'-import { detectIssues } from './describe-issues'-import { looksLikeButton } from './describe-shared'-import { defineTool } from './schema'--import type { SceneGraph, SceneNode } from '../scene-graph'-import type { DescribeIssue } from './describe-issues'--const NAME_ROLE_PATTERNS: { pattern: RegExp; role: string }[] = [- { pattern: /^icon$/i, role: 'icon' },- { pattern: /^icon[-_]/i, role: 'icon' },- { pattern: /^button$/i, role: 'button' },- { pattern: /^btn[-_\s]/i, role: 'button' },- { pattern: /[-_\s]btn$/i, role: 'button' },- { pattern: /^cta$/i, role: 'button' },- { pattern: /^icon[-_]?button$/i, role: 'button' },- { pattern: /^link$/i, role: 'link' },- { pattern: /^text[-_]?link$/i, role: 'link' },- { pattern: /^input$/i, role: 'textbox' },- { pattern: /^text[-_]?field$/i, role: 'textbox' },- { pattern: /^search$/i, role: 'searchbox' },- { pattern: /^checkbox$/i, role: 'checkbox' },- { pattern: /^toggle$/i, role: 'switch' },- { pattern: /^switch$/i, role: 'switch' },- { pattern: /^radio$/i, role: 'radio' },- { pattern: /^select$/i, role: 'combobox' },- { pattern: /^dropdown$/i, role: 'combobox' },- { pattern: /^slider$/i, role: 'slider' },- { pattern: /^tab$/i, role: 'tab' },- { pattern: /^tabs$/i, role: 'tablist' },- { pattern: /^nav(bar|igation)?$/i, role: 'navigation' },- { pattern: /^header$/i, role: 'banner' },- { pattern: /^footer$/i, role: 'contentinfo' },- { pattern: /^sidebar$/i, role: 'complementary' },- { pattern: /^modal$/i, role: 'dialog' },- { pattern: /^dialog$/i, role: 'dialog' },- { pattern: /^tooltip$/i, role: 'tooltip' },- { pattern: /^card$/i, role: 'article' },- { pattern: /^avatar$/i, role: 'img' },- { pattern: /^badge$/i, role: 'status' },- { pattern: /^toast$/i, role: 'alert' },- { pattern: /^alert$/i, role: 'alert' },- { pattern: /^list$/i, role: 'list' },- { pattern: /^menu$/i, role: 'menu' },- { pattern: /^breadcrumb/i, role: 'navigation' },- { pattern: /^progress$/i, role: 'progressbar' },- { pattern: /^spinner$/i, role: 'progressbar' },- { pattern: /^divider$/i, role: 'separator' },- { pattern: /^separator$/i, role: 'separator' }-]--function detectRoleFromName(name: string): string | null {- const base = (name.split(/[/,=]/)[0] ?? name).trim()- for (const { pattern, role } of NAME_ROLE_PATTERNS) {- if (pattern.test(base) || pattern.test(name)) return role- }- return null-}--function headingLevel(fontSize: number): number | null {- if (fontSize >= 32) return 1- if (fontSize >= 24) return 2- if (fontSize >= 20) return 3- if (fontSize >= 18) return 4- return null-}--function looksLikeSeparator(node: SceneNode): boolean {- if (node.width <= 2 && node.height > 10) return true- if (node.height <= 2 && node.width > 10) return true- const ratio = Math.max(node.width, node.height) / Math.max(1, Math.min(node.width, node.height))- return ratio > 10 && Math.min(node.width, node.height) <= 4-}--function describeVisual(node: SceneNode): string {- const parts: string[] = []- const fill = node.fills.find((f) => f.type === 'SOLID' && f.visible)- if (fill) parts.push(`${colorToHex(fill.color)} fill`)- if (node.strokes.length > 0 && node.strokes[0]?.visible) parts.push('bordered')- if (node.cornerRadius > 0) parts.push('rounded')- if (node.clipsContent) parts.push('clipped')- for (const e of node.effects) {- if (!e.visible) continue- if (e.type === 'DROP_SHADOW') parts.push('drop shadow')- else if (e.type === 'INNER_SHADOW') parts.push('inner shadow')- else if (e.type === 'LAYER_BLUR' || e.type === 'FOREGROUND_BLUR') parts.push('blurred')- else parts.push('backdrop blur')- }- return parts.join(', ') || 'no visual styles'-}--const JUSTIFY_LABELS: Record<string, string> = {- MIN: 'start',- CENTER: 'center',- MAX: 'end',- SPACE_BETWEEN: 'between'-}--const ITEMS_LABELS: Record<string, string> = {- MIN: 'start',- CENTER: 'center',- MAX: 'end',- STRETCH: 'stretch',- BASELINE: 'baseline'-}--function describeLayout(node: SceneNode): string | null {- if (node.layoutMode === 'NONE') return null- const dir = node.layoutMode === 'HORIZONTAL' ? 'horizontal' : 'vertical'- const parts = [dir]- if (node.primaryAxisAlign !== 'MIN')- parts.push(`justify=${JUSTIFY_LABELS[node.primaryAxisAlign] ?? node.primaryAxisAlign}`)- if (node.counterAxisAlign !== 'MIN')- parts.push(`items=${ITEMS_LABELS[node.counterAxisAlign] ?? node.counterAxisAlign}`)- if (node.itemSpacing > 0) parts.push(`${node.itemSpacing}px gap`)- const pad = [node.paddingTop, node.paddingRight, node.paddingBottom, node.paddingLeft]- const allSame = pad.every((p) => p === pad[0])- const first = pad[0]- if (allSame && first > 0) parts.push(`${first}px padding`)- else if (pad.some((p) => p > 0)) parts.push(`padding ${pad.join('/')}`)- if (node.primaryAxisSizing !== 'FIXED') parts.push(`${node.primaryAxisSizing.toLowerCase()} main`)- if (node.counterAxisSizing !== 'FIXED')- parts.push(`${node.counterAxisSizing.toLowerCase()} cross`)- if (node.layoutWrap === 'WRAP') parts.push('wrap')- return parts.join(', ')-}--function detectRole(node: SceneNode): string {- const nameDetected = detectRoleFromName(node.name)- if (nameDetected) return nameDetected- if (node.type === 'TEXT') {- const level = headingLevel(node.fontSize)- return level ? `heading(${level})` : 'StaticText'- }- if (looksLikeSeparator(node)) return 'separator'- if (looksLikeButton(node)) return 'button'- return 'generic'-}--interface ChildDescription {- role: string- name: string- summary: string- id: string- issues?: DescribeIssue[]- children?: ChildDescription[]-}--function summarizeContainer(node: SceneNode): string {- const parts = [`${node.width}×${node.height}`]- const fill = node.fills.find((f) => f.type === 'SOLID' && f.visible)- if (fill) parts.push(colorToHex(fill.color))- if (node.cornerRadius > 0) parts.push('rounded')- const layout = describeLayout(node)- if (layout) parts.push(layout)- return parts.join(', ')-}--function summarizeText(node: SceneNode): string {- const text = node.text.slice(0, 60)- let summary = `"${text}" ${node.fontSize}px ${node.fontFamily}`- if (node.fontWeight >= 700) summary += ' bold'- else if (node.fontWeight >= 500) summary += ' medium'- const textColor = node.fills.find((f) => f.type === 'SOLID' && f.visible)- if (textColor) summary += `, ${colorToHex(textColor.color)}`- if (node.textAutoResize === 'HEIGHT') summary += ', wraps'- else if (node.textAutoResize === 'NONE') summary += ', fixed-size'- if (node.maxLines !== null && node.maxLines > 0) summary += `, max ${node.maxLines} lines`- return summary-}--function describeChild(- node: SceneNode,- graph: SceneGraph,- depth: number,- gridSize: number-): ChildDescription {- const role = detectRole(node)- const summary = node.type === 'TEXT' ? summarizeText(node) : summarizeContainer(node)- const result: ChildDescription = { role, name: node.name, summary, id: node.id }-- const issues = detectIssues(node, gridSize, graph)- if (issues.length > 0) result.issues = issues-- if (depth > 0 && node.childIds.length > 0) {- const kids: ChildDescription[] = []- for (const childId of node.childIds) {- const child = graph.getNode(childId)- if (!child || !child.visible) continue- kids.push(describeChild(child, graph, depth - 1, gridSize))- }- if (kids.length > 0) result.children = kids- }- return result-}--function describeOneNode(- figma: { graph: SceneGraph },- nodeId: string,- depth: number,- gridSize: number-): Record<string, unknown> {- const raw = figma.graph.getNode(nodeId)- if (!raw) return { id: nodeId, error: `Node "${nodeId}" not found` }-- const role = detectRole(raw)- const visual = describeVisual(raw)- const layout = describeLayout(raw)- const issues = detectIssues(raw, gridSize, figma.graph)-- const children: ChildDescription[] = []- for (const childId of raw.childIds) {- const child = figma.graph.getNode(childId)- if (!child || !child.visible) continue- children.push(describeChild(child, figma.graph, depth - 1, gridSize))- }-- const result: Record<string, unknown> = {- id: raw.id,- name: raw.name,- type: raw.type,- role,- size: `${raw.width}×${raw.height}`,- visual- }- if (layout) result.layout = layout- if (children.length > 0) result.children = children- if (issues.length > 0) result.issues = issues- return result-}--function countDescendants(graph: SceneGraph, nodeId: string): number {- const node = graph.getNode(nodeId)- if (!node) return 0- let count = 0- for (const childId of node.childIds) {- count += 1 + countDescendants(graph, childId)- }- return count-}--function autoDepth(graph: SceneGraph, nodeId: string): number {- const size = countDescendants(graph, nodeId)- if (size <= 15) return 4- if (size <= 40) return 3- if (size <= 100) return 2- return 1-}--export const describe = defineTool({- name: 'describe',- description:- 'Semantic description of one or more nodes. Pass `id` for a single node, or `ids` for multiple nodes in one call. Omit depth for auto — adapts to subtree size (small block → deeper, large page → shallower).',- params: {- id: { type: 'string', description: 'Node ID (single node)' },- ids: { type: 'string[]', description: 'Node IDs (multiple nodes in one call)' },- depth: { type: 'number', description: 'Override depth (auto if omitted, max: 5)' },- grid: { type: 'number', description: 'Grid size for alignment checks (default: 8)' }- },- execute: (figma, args) => {- const gridSize = args.grid ?? 8-- if (args.ids && Array.isArray(args.ids)) {- return {- nodes: args.ids.map((nodeId) => {- const depth = Math.min(args.depth ?? autoDepth(figma.graph, nodeId), 5)- return describeOneNode(figma, nodeId, depth, gridSize)- })- }- }-- if (!args.id) return { error: 'Provide id (string) or ids (string[])' }- const depth = Math.min(args.depth ?? autoDepth(figma.graph, args.id), 5)- return describeOneNode(figma, args.id, depth, gridSize)- }-})diff --git a/packages/core/src/tools/describe/index.ts b/packages/core/src/tools/describe/index.tsnew file mode 100644index 000000000..fb5760508--- /dev/null+++ b/packages/core/src/tools/describe/index.ts@@ -0,0 +1,30 @@+import { autoDepth, describeOneNode } from './tree'+import { defineTool } from '#core/tools/schema'++export const describe = defineTool({+ name: 'describe',+ description:+ 'Semantic description of one or more nodes. Pass `id` for a single node, or `ids` for multiple nodes in one call. Omit depth for auto — adapts to subtree size (small block → deeper, large page → shallower).',+ params: {+ id: { type: 'string', description: 'Node ID (single node)' },+ ids: { type: 'string[]', description: 'Node IDs (multiple nodes in one call)' },+ depth: { type: 'number', description: 'Override depth (auto if omitted, max: 5)' },+ grid: { type: 'number', description: 'Grid size for alignment checks (default: 8)' },+ },+ execute: (figma, args) => {+ const gridSize = args.grid ?? 8++ if (args.ids && Array.isArray(args.ids)) {+ return {+ nodes: args.ids.map((nodeId) => {+ const depth = Math.min(args.depth ?? autoDepth(figma.graph, nodeId), 5)+ return describeOneNode(figma, nodeId, depth, gridSize)+ }),+ }+ }++ if (!args.id) return { error: 'Provide id (string) or ids (string[])' }+ const depth = Math.min(args.depth ?? autoDepth(figma.graph, args.id), 5)+ return describeOneNode(figma, args.id, depth, gridSize)+ },+})diff --git a/packages/core/src/tools/describe-issues.ts b/packages/core/src/tools/describe/issues.tssimilarity index 98%rename from packages/core/src/tools/describe-issues.tsrename to packages/core/src/tools/describe/issues.tsindex dde73e20b..30438c36a 100644--- a/packages/core/src/tools/describe-issues.ts+++ b/packages/core/src/tools/describe/issues.ts@@ -1,8 +1,8 @@-import { colorDistance, colorToHex } from '../color'-import { detectLayoutIssues } from './describe-layout-issues'-import { CONTAINER_TYPES, findAncestorBackground, looksLikeButton } from './describe-shared'+import { colorDistance, colorToHex } from '#core/color'+import { detectLayoutIssues } from './layout-issues'+import { CONTAINER_TYPES, findAncestorBackground, looksLikeButton } from './shared'-import type { SceneGraph, SceneNode } from '../scene-graph'+import type { SceneGraph, SceneNode } from '#core/scene-graph'const MIN_FILL_OPACITY = 0.15const MIN_STROKE_OPACITY = 0.2diff --git a/packages/core/src/tools/describe-layout-issues.ts b/packages/core/src/tools/describe/layout-issues.tssimilarity index 96%rename from packages/core/src/tools/describe-layout-issues.tsrename to packages/core/src/tools/describe/layout-issues.tsindex db17aef48..82f484295 100644--- a/packages/core/src/tools/describe-layout-issues.ts+++ b/packages/core/src/tools/describe/layout-issues.ts@@ -1,11 +1,11 @@import { wcagLuminance } from 'culori'-import { colorToHex } from '../color'-import { CONTAINER_TYPES, findAncestorBackground } from './describe-shared'+import { colorToHex } from '#core/color'+import { CONTAINER_TYPES, findAncestorBackground } from './shared'-import type { SceneGraph, SceneNode } from '../scene-graph'-import type { Color } from '../types'-import type { DescribeIssue } from './describe-issues'+import type { SceneGraph, SceneNode } from '#core/scene-graph'+import type { Color } from '#core/types'+import type { DescribeIssue } from './issues'const DARK_BG_LUMINANCE = 0.35@@ -267,12 +267,16 @@ function checkSiblingHeightConsistency(ctx: LayoutContext): void {}}+function visibleChildren(node: SceneNode, graph: SceneGraph): SceneNode[] {+ return node.childIds+ .map((childId) => graph.getNode(childId))+ .filter((child): child is SceneNode => child?.visible === true)+}+function checkChildUndersize(ctx: LayoutContext): void {const { node, graph, issues } = ctxif (node.layoutMode !== 'NONE') return- for (const childId of node.childIds) {- const child = graph.getNode(childId)- if (!child?.visible) continue+ for (const child of visibleChildren(node, graph)) {if (child.width > 0 &&node.width > 0 &&@@ -308,9 +312,7 @@ function checkCrossAxisOverflow(ctx: LayoutContext): void {function checkFillWithoutFlex(ctx: LayoutContext): void {const { node, graph, issues } = ctxif (node.layoutMode !== 'NONE') return- for (const childId of node.childIds) {- const child = graph.getNode(childId)- if (!child?.visible) continue+ for (const child of visibleChildren(node, graph)) {if (!CONTAINER_TYPES.has(child.type)) continueif (child.primaryAxisSizing === 'FILL' || child.counterAxisSizing === 'FILL') {issues.push({@@ -383,9 +385,7 @@ function checkNestedFlexWithoutFill(ctx: LayoutContext): void {function checkDuplicateNames(ctx: LayoutContext): void {const { node, graph, issues } = ctxconst nameCounts = new Map<string, number>()- for (const childId of node.childIds) {- const child = graph.getNode(childId)- if (!child?.visible) continue+ for (const child of visibleChildren(node, graph)) {nameCounts.set(child.name, (nameCounts.get(child.name) ?? 0) + 1)}for (const [name, count] of nameCounts) {diff --git a/packages/core/src/tools/describe/roles.ts b/packages/core/src/tools/describe/roles.tsnew file mode 100644index 000000000..0a139ba3d--- /dev/null+++ b/packages/core/src/tools/describe/roles.ts@@ -0,0 +1,81 @@+import { looksLikeButton } from './shared'++import type { SceneNode } from '#core/scene-graph'++const NAME_ROLE_PATTERNS: { pattern: RegExp; role: string }[] = [+ { pattern: /^icon$/i, role: 'icon' },+ { pattern: /^icon[-_]/i, role: 'icon' },+ { pattern: /^button$/i, role: 'button' },+ { pattern: /^btn[-_\s]/i, role: 'button' },+ { pattern: /[-_\s]btn$/i, role: 'button' },+ { pattern: /^cta$/i, role: 'button' },+ { pattern: /^icon[-_]?button$/i, role: 'button' },+ { pattern: /^link$/i, role: 'link' },+ { pattern: /^text[-_]?link$/i, role: 'link' },+ { pattern: /^input$/i, role: 'textbox' },+ { pattern: /^text[-_]?field$/i, role: 'textbox' },+ { pattern: /^search$/i, role: 'searchbox' },+ { pattern: /^checkbox$/i, role: 'checkbox' },+ { pattern: /^toggle$/i, role: 'switch' },+ { pattern: /^switch$/i, role: 'switch' },+ { pattern: /^radio$/i, role: 'radio' },+ { pattern: /^select$/i, role: 'combobox' },+ { pattern: /^dropdown$/i, role: 'combobox' },+ { pattern: /^slider$/i, role: 'slider' },+ { pattern: /^tab$/i, role: 'tab' },+ { pattern: /^tabs$/i, role: 'tablist' },+ { pattern: /^nav(bar|igation)?$/i, role: 'navigation' },+ { pattern: /^header$/i, role: 'banner' },+ { pattern: /^footer$/i, role: 'contentinfo' },+ { pattern: /^sidebar$/i, role: 'complementary' },+ { pattern: /^modal$/i, role: 'dialog' },+ { pattern: /^dialog$/i, role: 'dialog' },+ { pattern: /^tooltip$/i, role: 'tooltip' },+ { pattern: /^card$/i, role: 'article' },+ { pattern: /^avatar$/i, role: 'img' },+ { pattern: /^badge$/i, role: 'status' },+ { pattern: /^toast$/i, role: 'alert' },+ { pattern: /^alert$/i, role: 'alert' },+ { pattern: /^list$/i, role: 'list' },+ { pattern: /^menu$/i, role: 'menu' },+ { pattern: /^breadcrumb/i, role: 'navigation' },+ { pattern: /^progress$/i, role: 'progressbar' },+ { pattern: /^spinner$/i, role: 'progressbar' },+ { pattern: /^divider$/i, role: 'separator' },+ { pattern: /^separator$/i, role: 'separator' },+]++function detectRoleFromName(name: string): string | null {+ const base = (name.split(/[/,=]/)[0] ?? name).trim()+ for (const { pattern, role } of NAME_ROLE_PATTERNS) {+ if (pattern.test(base) || pattern.test(name)) return role+ }+ return null+}++function headingLevel(fontSize: number): number | null {+ if (fontSize >= 32) return 1+ if (fontSize >= 24) return 2+ if (fontSize >= 20) return 3+ if (fontSize >= 18) return 4+ return null+}++function looksLikeSeparator(node: SceneNode): boolean {+ if (node.width <= 2 && node.height > 10) return true+ if (node.height <= 2 && node.width > 10) return true+ const ratio = Math.max(node.width, node.height) / Math.max(1, Math.min(node.width, node.height))+ return ratio > 10 && Math.min(node.width, node.height) <= 4+}++export function detectRole(node: SceneNode): string {+ const nameDetected = detectRoleFromName(node.name)+ if (nameDetected) return nameDetected+ if (node.type === 'TEXT') {+ const level = headingLevel(node.fontSize)+ return level ? `heading(${level})` : 'StaticText'+ }+ if (looksLikeSeparator(node)) return 'separator'+ if (looksLikeButton(node)) return 'button'+ return 'generic'+}diff --git a/packages/core/src/tools/describe-shared.ts b/packages/core/src/tools/describe/shared.tssimilarity index 91%rename from packages/core/src/tools/describe-shared.tsrename to packages/core/src/tools/describe/shared.tsindex 3bebe1d6c..227c0de1b 100644--- a/packages/core/src/tools/describe-shared.ts+++ b/packages/core/src/tools/describe/shared.ts@@ -1,5 +1,5 @@-import type { SceneGraph, SceneNode } from '../scene-graph'-import type { Color } from '../types'+import type { SceneGraph, SceneNode } from '#core/scene-graph'+import type { Color } from '#core/types'export const CONTAINER_TYPES = new Set(['FRAME', 'COMPONENT', 'INSTANCE'])diff --git a/packages/core/src/tools/describe/summaries.ts b/packages/core/src/tools/describe/summaries.tsnew file mode 100644index 000000000..8e567de4e--- /dev/null+++ b/packages/core/src/tools/describe/summaries.ts@@ -0,0 +1,82 @@+import { colorToHex } from '#core/color'++import type { SceneNode } from '#core/scene-graph'++export function describeVisual(node: SceneNode): string {+ const parts: string[] = []+ const fill = node.fills.find((candidate) => candidate.type === 'SOLID' && candidate.visible)+ if (fill) parts.push(`${colorToHex(fill.color)} fill`)+ if (node.strokes.length > 0 && node.strokes[0]?.visible) parts.push('bordered')+ if (node.cornerRadius > 0) parts.push('rounded')+ if (node.clipsContent) parts.push('clipped')+ for (const effect of node.effects) {+ if (!effect.visible) continue+ if (effect.type === 'DROP_SHADOW') parts.push('drop shadow')+ else if (effect.type === 'INNER_SHADOW') parts.push('inner shadow')+ else if (effect.type === 'LAYER_BLUR' || effect.type === 'FOREGROUND_BLUR') parts.push('blurred')+ else parts.push('backdrop blur')+ }+ return parts.join(', ') || 'no visual styles'+}++const JUSTIFY_LABELS: Record<string, string> = {+ MIN: 'start',+ CENTER: 'center',+ MAX: 'end',+ SPACE_BETWEEN: 'between',+}++const ITEMS_LABELS: Record<string, string> = {+ MIN: 'start',+ CENTER: 'center',+ MAX: 'end',+ STRETCH: 'stretch',+ BASELINE: 'baseline',+}++export function describeLayout(node: SceneNode): string | null {+ if (node.layoutMode === 'NONE') return null+ const direction = node.layoutMode === 'HORIZONTAL' ? 'horizontal' : 'vertical'+ const parts = [direction]+ if (node.primaryAxisAlign !== 'MIN') {+ parts.push(`justify=${JUSTIFY_LABELS[node.primaryAxisAlign] ?? node.primaryAxisAlign}`)+ }+ if (node.counterAxisAlign !== 'MIN') {+ parts.push(`items=${ITEMS_LABELS[node.counterAxisAlign] ?? node.counterAxisAlign}`)+ }+ if (node.itemSpacing > 0) parts.push(`${node.itemSpacing}px gap`)+ const padding = [node.paddingTop, node.paddingRight, node.paddingBottom, node.paddingLeft]+ const allSame = padding.every((value) => value === padding[0])+ const first = padding[0]+ if (allSame && first > 0) parts.push(`${first}px padding`)+ else if (padding.some((value) => value > 0)) parts.push(`padding ${padding.join('/')}`)+ if (node.primaryAxisSizing !== 'FIXED') parts.push(`${node.primaryAxisSizing.toLowerCase()} main`)+ if (node.counterAxisSizing !== 'FIXED') {+ parts.push(`${node.counterAxisSizing.toLowerCase()} cross`)+ }+ if (node.layoutWrap === 'WRAP') parts.push('wrap')+ return parts.join(', ')+}++export function summarizeContainer(node: SceneNode): string {+ const parts = [`${node.width}×${node.height}`]+ const fill = node.fills.find((candidate) => candidate.type === 'SOLID' && candidate.visible)+ if (fill) parts.push(colorToHex(fill.color))+ if (node.cornerRadius > 0) parts.push('rounded')+ const layout = describeLayout(node)+ if (layout) parts.push(layout)+ return parts.join(', ')+}++export function summarizeText(node: SceneNode): string {+ const text = node.text.slice(0, 60)+ let summary = `"${text}" ${node.fontSize}px ${node.fontFamily}`+ if (node.fontWeight >= 700) summary += ' bold'+ else if (node.fontWeight >= 500) summary += ' medium'+ const textColor = node.fills.find((fill) => fill.type === 'SOLID' && fill.visible)+ if (textColor) summary += `, ${colorToHex(textColor.color)}`+ if (node.textAutoResize === 'HEIGHT') summary += ', wraps'+ else if (node.textAutoResize === 'NONE') summary += ', fixed-size'+ if (node.maxLines !== null && node.maxLines > 0) summary += `, max ${node.maxLines} lines`+ return summary+}diff --git a/packages/core/src/tools/describe/tree.ts b/packages/core/src/tools/describe/tree.tsnew file mode 100644index 000000000..93a6ed8d9--- /dev/null+++ b/packages/core/src/tools/describe/tree.ts@@ -0,0 +1,93 @@+import { detectIssues } from './issues'+import { detectRole } from './roles'+import { describeLayout, describeVisual, summarizeContainer, summarizeText } from './summaries'++import type { SceneGraph, SceneNode } from '#core/scene-graph'+import type { DescribeIssue } from './issues'++interface ChildDescription {+ role: string+ name: string+ summary: string+ id: string+ issues?: DescribeIssue[]+ children?: ChildDescription[]+}++function describeChild(+ node: SceneNode,+ graph: SceneGraph,+ depth: number,+ gridSize: number,+): ChildDescription {+ const role = detectRole(node)+ const summary = node.type === 'TEXT' ? summarizeText(node) : summarizeContainer(node)+ const result: ChildDescription = { role, name: node.name, summary, id: node.id }++ const issues = detectIssues(node, gridSize, graph)+ if (issues.length > 0) result.issues = issues++ if (depth > 0 && node.childIds.length > 0) {+ const kids: ChildDescription[] = []+ for (const childId of node.childIds) {+ const child = graph.getNode(childId)+ if (!child || !child.visible) continue+ kids.push(describeChild(child, graph, depth - 1, gridSize))+ }+ if (kids.length > 0) result.children = kids+ }+ return result+}++export function describeOneNode(+ figma: { graph: SceneGraph },+ nodeId: string,+ depth: number,+ gridSize: number,+): Record<string, unknown> {+ const raw = figma.graph.getNode(nodeId)+ if (!raw) return { id: nodeId, error: `Node "${nodeId}" not found` }++ const role = detectRole(raw)+ const visual = describeVisual(raw)+ const layout = describeLayout(raw)+ const issues = detectIssues(raw, gridSize, figma.graph)++ const children: ChildDescription[] = []+ for (const childId of raw.childIds) {+ const child = figma.graph.getNode(childId)+ if (!child || !child.visible) continue+ children.push(describeChild(child, figma.graph, depth - 1, gridSize))+ }++ const result: Record<string, unknown> = {+ id: raw.id,+ name: raw.name,+ type: raw.type,+ role,+ size: `${raw.width}×${raw.height}`,+ visual,+ }+ if (layout) result.layout = layout+ if (children.length > 0) result.children = children+ if (issues.length > 0) result.issues = issues+ return result+}++function countDescendants(graph: SceneGraph, nodeId: string): number {+ const node = graph.getNode(nodeId)+ if (!node) return 0+ let count = 0+ for (const childId of node.childIds) {+ count += 1 + countDescendants(graph, childId)+ }+ return count+}++export function autoDepth(graph: SceneGraph, nodeId: string): number {+ const size = countDescendants(graph, nodeId)+ if (size <= 15) return 4+ if (size <= 40) return 3+ if (size <= 100) return 2+ return 1+}diff --git a/packages/core/src/tools/index.ts b/packages/core/src/tools/index.tsindex 4104b93cc..f0db6dcd2 100644--- a/packages/core/src/tools/index.ts+++ b/packages/core/src/tools/index.ts@@ -1,7 +1,9 @@export { ALL_TOOLS, CORE_TOOLS, EXTENDED_TOOLS } from './registry'+export { default as CODEGEN_PROMPT } from './prompts/codegen.md'export { exportImage } from './vector'export { defineTool, nodeToResult, nodeSummary, requireNode, NodeNotFoundError } from './schema'export type { ToolDef, ParamDef, ParamType } from './schema'export { toolsToAI, buildDebugLog } from './ai-adapter'export type { ToolLogEntry, ToolDebugLog, AIAdapterOptions, StepBudget } from './ai-adapter'export { calcClusterConfidence } from './analyze'+export { setPexelsApiKey, setUnsplashAccessKey } from './stock-photo'diff --git a/packages/core/src/tools/modify.ts b/packages/core/src/tools/modify.tsindex fffafa4c4..ffb48756f 100644--- a/packages/core/src/tools/modify.ts+++ b/packages/core/src/tools/modify.ts@@ -1,778 +1,7 @@-/* eslint-disable max-lines -- property setters share common patterns, splitting would scatter related tools */-import { parseColor } from '../color'-import { DEFAULT_SHADOW_COLOR } from '../constants'-import { styleToWeight } from '../text/fonts'-import { applyStyleToRange } from '../text/style-runs'-import { defineTool } from './schema'--import type { CharacterStyleOverride, Effect, SceneNode } from '../scene-graph'-import type { Matrix } from '../types'--export const setFill = defineTool({- name: 'set_fill',- mutates: true,- description:- 'Set fill on a node. Solid: color="#ff0000". Linear gradient: gradient="top-bottom" or "left-right" with color (start) and color_end (end).',- params: {- id: { type: 'string', description: 'Node ID', required: true },- color: {- type: 'color',- description: 'Color (hex). For gradient: start color.',- required: true- },- color_end: { type: 'color', description: 'End color for gradient (if omitted, solid fill)' },- gradient: {- type: 'string',- description: 'Gradient direction',- enum: ['top-bottom', 'bottom-top', 'left-right', 'right-left']- }- },- execute: (figma, { id, color, color_end, gradient }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }-- const c = parseColor(color)-- if (gradient && color_end) {- const cEnd = parseColor(color_end)- const transforms: Record<string, Matrix> = {- 'top-bottom': { m00: 0, m01: 1, m02: 0, m10: -1, m11: 0, m12: 1 },- 'bottom-top': { m00: 0, m01: -1, m02: 1, m10: 1, m11: 0, m12: 0 },- 'left-right': { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 },- 'right-left': { m00: -1, m01: 0, m02: 1, m10: 0, m11: -1, m12: 1 }- }- node.fills = [- {- type: 'GRADIENT_LINEAR',- color: c,- opacity: 1,- visible: true,- gradientStops: [- { position: 0, color: c },- { position: 1, color: cEnd }- ],- gradientTransform: transforms[gradient] ?? transforms['top-bottom']- }- ]- return { id, gradient, start: c, end: cEnd }- }-- node.fills = [{ type: 'SOLID', color: c, opacity: 1, visible: true }]- return { id, color: c }- }-})--export const setStroke = defineTool({- name: 'set_stroke',- mutates: true,- description: 'Set the stroke (border) of a node.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- color: { type: 'color', description: 'Stroke color (hex)', required: true },- weight: { type: 'number', description: 'Stroke weight', default: 1, min: 0.1 },- align: {- type: 'string',- description: 'Stroke alignment',- default: 'INSIDE',- enum: ['INSIDE', 'CENTER', 'OUTSIDE']- }- },- execute: (figma, { id, color, weight, align }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }-- const c = parseColor(color)- node.strokes = [- {- color: c,- weight: weight ?? 1,- opacity: 1,- visible: true,- align: (align ?? 'INSIDE') as 'INSIDE' | 'CENTER' | 'OUTSIDE'- }- ]- return { id, color: c, weight: weight ?? 1 }- }-})--export const setEffects = defineTool({- name: 'set_effects',- mutates: true,- description:- 'Set effects on a node (drop shadow, inner shadow, blur). Pass an array or a single effect.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- type: {- type: 'string',- description: 'Effect type',- required: true,- enum: ['DROP_SHADOW', 'INNER_SHADOW', 'FOREGROUND_BLUR', 'BACKGROUND_BLUR']- },- color: { type: 'color', description: 'Shadow color (hex). Ignored for blur.' },- offset_x: { type: 'number', description: 'Shadow X offset', default: 0 },- offset_y: { type: 'number', description: 'Shadow Y offset', default: 4 },- radius: { type: 'number', description: 'Blur radius', default: 4, min: 0 },- spread: { type: 'number', description: 'Shadow spread', default: 0 }- },- execute: (figma, args) => {- const node = figma.getNodeById(args.id)- if (!node) return { error: `Node "${args.id}" not found` }-- const isBlur = args.type === 'FOREGROUND_BLUR' || args.type === 'BACKGROUND_BLUR'- let color = { ...DEFAULT_SHADOW_COLOR }- if (isBlur) color = { r: 0, g: 0, b: 0, a: 0 }- else if (args.color) color = parseColor(args.color)- const effect: Effect = {- type: args.type as Effect['type'],- visible: true,- radius: args.radius ?? 4,- color,- offset: { x: isBlur ? 0 : (args.offset_x ?? 0), y: isBlur ? 0 : (args.offset_y ?? 4) },- spread: isBlur ? 0 : (args.spread ?? 0)- }-- node.effects = [...node.effects, effect]- return { id: args.id, effects: node.effects.length }- }-})--export const updateNode = defineTool({- name: 'update_node',- mutates: true,- description:- 'Update properties of an existing node: position, size, opacity, corner radius, visibility, text, font.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- x: { type: 'number', description: 'X position' },- y: { type: 'number', description: 'Y position' },- width: { type: 'number', description: 'Width', min: 1 },- height: { type: 'number', description: 'Height', min: 1 },- opacity: { type: 'number', description: 'Opacity (0-1)', min: 0, max: 1 },- corner_radius: { type: 'number', description: 'Corner radius', min: 0 },- visible: { type: 'boolean', description: 'Visibility' },- text: { type: 'string', description: 'Text content (TEXT nodes)' },- text_direction: {- type: 'string',- description: 'Text direction for TEXT nodes',- enum: ['AUTO', 'LTR', 'RTL']- },- flow_direction: {- type: 'string',- description: 'Auto-layout flow direction for FRAME nodes',- enum: ['AUTO', 'LTR', 'RTL']- },- font_size: { type: 'number', description: 'Font size', min: 1 },- font_weight: { type: 'number', description: 'Font weight (100-900)' },- name: { type: 'string', description: 'Layer name' }- },- execute: (figma, args) => {- const node = figma.getNodeById(args.id)- if (!node) return { error: `Node "${args.id}" not found` }- const updated: string[] = []- if (args.x !== undefined) {- node.x = args.x- updated.push('x')- }- if (args.y !== undefined) {- node.y = args.y- updated.push('y')- }- if (args.width !== undefined || args.height !== undefined) {- node.resize(args.width ?? node.width, args.height ?? node.height)- updated.push('size')- }- if (args.opacity !== undefined) {- node.opacity = args.opacity- updated.push('opacity')- }- if (args.corner_radius !== undefined) {- node.cornerRadius = args.corner_radius- updated.push('cornerRadius')- }- if (args.visible !== undefined) {- node.visible = args.visible- updated.push('visible')- }- if (args.name !== undefined) {- node.name = args.name- updated.push('name')- }- if (args.text !== undefined) {- figma.graph.updateNode(node.id, { text: args.text })- updated.push('text')- }- if (args.text_direction !== undefined) {- figma.graph.updateNode(node.id, {- textDirection: args.text_direction as SceneNode['textDirection']- })- updated.push('textDirection')- }- if (args.flow_direction !== undefined) {- figma.graph.updateNode(node.id, {- layoutDirection: args.flow_direction as SceneNode['layoutDirection']- })- updated.push('layoutDirection')- }- if (args.font_size !== undefined) {- figma.graph.updateNode(node.id, { fontSize: args.font_size })- updated.push('fontSize')- }- if (args.font_weight !== undefined) {- figma.graph.updateNode(node.id, { fontWeight: args.font_weight })- updated.push('fontWeight')- }- return { id: args.id, updated }- }-})--export const setLayout = defineTool({- name: 'set_layout',- mutates: true,- description: 'Set auto-layout (flexbox) on a frame. Direction, alignment, spacing, padding.',- params: {- id: { type: 'string', description: 'Frame node ID', required: true },- direction: {- type: 'string',- description: 'Layout direction (keeps current if omitted)',- enum: ['HORIZONTAL', 'VERTICAL']- },- spacing: {- type: 'number',- description: 'Gap between items (only changes if provided)',- min: 0- },- padding: {- type: 'number',- description: 'Equal padding on all sides (only changes if provided)',- min: 0- },- padding_horizontal: { type: 'number', description: 'Horizontal padding', min: 0 },- padding_vertical: { type: 'number', description: 'Vertical padding', min: 0 },- align: {- type: 'string',- description: 'Primary axis alignment (only changes if provided)',- enum: ['MIN', 'CENTER', 'MAX', 'SPACE_BETWEEN']- },- counter_align: {- type: 'string',- description: 'Cross axis alignment (only changes if provided)',- enum: ['MIN', 'CENTER', 'MAX', 'STRETCH']- },- flow_direction: {- type: 'string',- description: 'Child flow direction for auto-layout. AUTO inherits from parent.',- enum: ['AUTO', 'LTR', 'RTL']- }- },- execute: (figma, args) => {- const node = figma.getNodeById(args.id)- if (!node) return { error: `Node "${args.id}" not found` }-- const raw = figma.graph.getNode(args.id)- if (!args.direction && raw?.layoutMode === 'NONE') {- return {- error: 'Frame has no auto-layout. Pass direction ("HORIZONTAL" or "VERTICAL") to enable it.'- }- }-- const wasNone = raw?.layoutMode === 'NONE'- if (args.direction) node.layoutMode = args.direction as 'HORIZONTAL' | 'VERTICAL'- if (wasNone) {- node.primaryAxisSizingMode = 'AUTO'- node.counterAxisSizingMode = 'AUTO'- }- if (args.spacing !== undefined) node.itemSpacing = args.spacing- if (args.align !== undefined) node.primaryAxisAlignItems = args.align- if (args.counter_align !== undefined) node.counterAxisAlignItems = args.counter_align- if (args.flow_direction !== undefined)- node.layoutDirection = args.flow_direction as SceneNode['layoutDirection']-- if (args.padding !== undefined) {- node.paddingTop = args.padding- node.paddingRight = args.padding- node.paddingBottom = args.padding- node.paddingLeft = args.padding- }- if (args.padding_horizontal !== undefined) {- node.paddingLeft = args.padding_horizontal- node.paddingRight = args.padding_horizontal- }- if (args.padding_vertical !== undefined) {- node.paddingTop = args.padding_vertical- node.paddingBottom = args.padding_vertical- }-- return { id: args.id, spacing: node.itemSpacing }- }-})--export const setConstraints = defineTool({- name: 'set_constraints',- mutates: true,- description: 'Set resize constraints for a node within its parent.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- horizontal: {- type: 'string',- description: 'Horizontal constraint',- enum: ['MIN', 'CENTER', 'MAX', 'STRETCH', 'SCALE']- },- vertical: {- type: 'string',- description: 'Vertical constraint',- enum: ['MIN', 'CENTER', 'MAX', 'STRETCH', 'SCALE']- }- },- execute: (figma, args) => {- const node = figma.getNodeById(args.id)- if (!node) return { error: `Node "${args.id}" not found` }- if (args.horizontal || args.vertical) {- node.constraints = {- horizontal: args.horizontal ?? node.constraints.horizontal,- vertical: args.vertical ?? node.constraints.vertical- }- }- return { id: args.id, constraints: node.constraints }- }-})--export const setRotation = defineTool({- name: 'set_rotation',- mutates: true,- description: 'Set rotation angle of a node in degrees.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- angle: { type: 'number', description: 'Rotation angle in degrees', required: true }- },- execute: (figma, { id, angle }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- node.rotation = angle- return { id, rotation: angle }- }-})--export const setOpacity = defineTool({- name: 'set_opacity',- mutates: true,- description: 'Set opacity of a node (0-1).',- params: {- id: { type: 'string', description: 'Node ID', required: true },- value: { type: 'number', description: 'Opacity (0-1)', required: true, min: 0, max: 1 }- },- execute: (figma, { id, value }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- node.opacity = value- return { id, opacity: value }- }-})--export const setRadius = defineTool({- name: 'set_radius',- mutates: true,- description: 'Set corner radius. Use individual corners for independent values.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- radius: { type: 'number', description: 'Corner radius for all corners', min: 0 },- top_left: { type: 'number', description: 'Top-left radius', min: 0 },- top_right: { type: 'number', description: 'Top-right radius', min: 0 },- bottom_right: { type: 'number', description: 'Bottom-right radius', min: 0 },- bottom_left: { type: 'number', description: 'Bottom-left radius', min: 0 }- },- execute: (figma, args) => {- const node = figma.getNodeById(args.id)- if (!node) return { error: `Node "${args.id}" not found` }- if (args.radius !== undefined) {- node.cornerRadius = args.radius- }- if (args.top_left !== undefined) node.topLeftRadius = args.top_left- if (args.top_right !== undefined) node.topRightRadius = args.top_right- if (args.bottom_right !== undefined) node.bottomRightRadius = args.bottom_right- if (args.bottom_left !== undefined) node.bottomLeftRadius = args.bottom_left- const cr = node.cornerRadius- if (typeof cr === 'number') {- return { id: args.id, cornerRadius: cr }- }- return {- id: args.id,- topLeftRadius: node.topLeftRadius,- topRightRadius: node.topRightRadius,- bottomRightRadius: node.bottomRightRadius,- bottomLeftRadius: node.bottomLeftRadius- }- }-})--export const setMinMax = defineTool({- name: 'set_minmax',- mutates: true,- description: 'Set min/max width and height constraints on a node.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- min_width: { type: 'number', description: 'Minimum width', min: 0 },- max_width: { type: 'number', description: 'Maximum width', min: 0 },- min_height: { type: 'number', description: 'Minimum height', min: 0 },- max_height: { type: 'number', description: 'Maximum height', min: 0 }- },- execute: (figma, args) => {- const node = figma.getNodeById(args.id)- if (!node) return { error: `Node "${args.id}" not found` }- if (args.min_width !== undefined) node.minWidth = args.min_width- if (args.max_width !== undefined) node.maxWidth = args.max_width- if (args.min_height !== undefined) node.minHeight = args.min_height- if (args.max_height !== undefined) node.maxHeight = args.max_height- return {- id: args.id,- minWidth: node.minWidth,- maxWidth: node.maxWidth,- minHeight: node.minHeight,- maxHeight: node.maxHeight- }- }-})--export const setText = defineTool({- name: 'set_text',- mutates: true,- description: 'Set text content of a text node.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- text: { type: 'string', description: 'Text content', required: true }- },- execute: (figma, { id, text }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- node.characters = text- return { id, text }- }-})--export const setFont = defineTool({- name: 'set_font',- mutates: true,- description: 'Set font properties of a text node.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- family: { type: 'string', description: 'Font family name' },- size: { type: 'number', description: 'Font size', min: 1 },- style: { type: 'string', description: 'Font style (e.g. "Bold", "Regular", "Bold Italic")' }- },- execute: (figma, args) => {- const node = figma.getNodeById(args.id)- if (!node) return { error: `Node "${args.id}" not found` }- if (args.size !== undefined) node.fontSize = args.size- if (args.family || args.style) {- const current = node.fontName- node.fontName = {- family: args.family ?? current.family,- style: args.style ?? current.style- }- }- return { id: args.id, fontName: node.fontName, fontSize: node.fontSize }- }-})--export const setFontRange = defineTool({- name: 'set_font_range',- mutates: true,- description: 'Set font properties for a text range.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- start: { type: 'number', description: 'Start character index', required: true, min: 0 },- end: { type: 'number', description: 'End character index', required: true, min: 0 },- family: { type: 'string', description: 'Font family name' },- size: { type: 'number', description: 'Font size', min: 1 },- style: { type: 'string', description: 'Font style' },- color: { type: 'color', description: 'Text color (hex)' }- },- execute: (figma, args) => {- const node = figma.getNodeById(args.id)- if (!node) return { error: `Node "${args.id}" not found` }- const override: CharacterStyleOverride = {}- if (args.family) override.fontFamily = args.family- if (args.size) override.fontSize = args.size- if (args.style) {- const s = args.style.toLowerCase()- if (s.includes('italic')) override.italic = true- override.fontWeight = styleToWeight(args.style)- }- if (args.color) {- override.fills = [{ type: 'SOLID', color: parseColor(args.color), opacity: 1, visible: true }]- }- const raw = figma.graph.getNode(node.id)- if (!raw) return { error: `Node "${args.id}" not found` }- const runs = applyStyleToRange(raw.styleRuns, args.start, args.end, override, raw.text.length)- figma.graph.updateNode(node.id, { styleRuns: runs })- return { id: args.id, range: { start: args.start, end: args.end } }- }-})--export const setTextResize = defineTool({- name: 'set_text_resize',- mutates: true,- description: 'Set text auto-resize mode.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- mode: {- type: 'string',- description: 'Resize mode',- required: true,- enum: ['NONE', 'WIDTH_AND_HEIGHT', 'HEIGHT', 'TRUNCATE']- }- },- execute: (figma, { id, mode }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- node.textAutoResize = mode- return { id, textAutoResize: mode }- }-})--export const setVisible = defineTool({- name: 'set_visible',- mutates: true,- description: 'Set visibility of a node.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- value: { type: 'boolean', description: 'Visible (true/false)', required: true }- },- execute: (figma, { id, value }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- node.visible = value- return { id, visible: value }- }-})--export const setBlend = defineTool({- name: 'set_blend',- mutates: true,- description: 'Set blend mode of a node.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- mode: {- type: 'string',- description: 'Blend mode',- required: true,- enum: [- 'NORMAL',- 'DARKEN',- 'MULTIPLY',- 'COLOR_BURN',- 'LIGHTEN',- 'SCREEN',- 'COLOR_DODGE',- 'OVERLAY',- 'SOFT_LIGHT',- 'HARD_LIGHT',- 'DIFFERENCE',- 'EXCLUSION',- 'HUE',- 'SATURATION',- 'COLOR',- 'LUMINOSITY'- ]- }- },- execute: (figma, { id, mode }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- node.blendMode = mode- return { id, blendMode: mode }- }-})--export const setLocked = defineTool({- name: 'set_locked',- mutates: true,- description: 'Set locked state of a node.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- value: { type: 'boolean', description: 'Locked (true/false)', required: true }- },- execute: (figma, { id, value }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- node.locked = value- return { id, locked: value }- }-})--export const setStrokeAlign = defineTool({- name: 'set_stroke_align',- mutates: true,- description: 'Set stroke alignment of a node.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- align: {- type: 'string',- description: 'Stroke alignment',- required: true,- enum: ['INSIDE', 'CENTER', 'OUTSIDE']- }- },- execute: (figma, { id, align }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- node.strokeAlign = align- return { id, strokeAlign: align }- }-})--export const setTextProperties = defineTool({- name: 'set_text_properties',- mutates: true,- description:- 'Set text layout properties: alignment, auto-resize, text case, decoration, truncation.',- params: {- id: { type: 'string', description: 'Text node ID', required: true },- align_horizontal: {- type: 'string',- description: 'Horizontal text alignment',- enum: ['LEFT', 'CENTER', 'RIGHT', 'JUSTIFIED']- },- align_vertical: {- type: 'string',- description: 'Vertical text alignment',- enum: ['TOP', 'CENTER', 'BOTTOM']- },- auto_resize: {- type: 'string',- description: 'Text auto-resize mode',- enum: ['NONE', 'WIDTH_AND_HEIGHT', 'HEIGHT', 'TRUNCATE']- },- direction: {- type: 'string',- description: 'Text direction',- enum: ['AUTO', 'LTR', 'RTL']- },- text_decoration: {- type: 'string',- description: 'Text decoration',- enum: ['NONE', 'UNDERLINE', 'STRIKETHROUGH']- }- },- execute: (figma, args) => {- const node = figma.getNodeById(args.id)- if (!node) return { error: `Node "${args.id}" not found` }- if (node.type !== 'TEXT') return { error: `Node "${args.id}" is not a TEXT node` }- const updated: string[] = []- if (args.align_horizontal !== undefined) {- node.textAlignHorizontal = args.align_horizontal- updated.push('textAlignHorizontal')- }- if (args.align_vertical !== undefined) {- node.textAlignVertical = args.align_vertical- updated.push('textAlignVertical')- }- if (args.auto_resize !== undefined) {- node.textAutoResize = args.auto_resize- updated.push('textAutoResize')- }- if (args.direction !== undefined) {- node.textDirection = args.direction as SceneNode['textDirection']- updated.push('textDirection')- }- if (args.text_decoration !== undefined) {- node.textDecoration = args.text_decoration- updated.push('textDecoration')- }- return { id: args.id, updated }- }-})--export const setLayoutChild = defineTool({- name: 'set_layout_child',- mutates: true,- description:- 'Configure auto-layout child: sizing (FIXED/HUG/FILL), grow, alignment, absolute positioning.',- params: {- id: { type: 'string', description: 'Child node ID', required: true },- sizing_horizontal: {- type: 'string',- description: 'Horizontal sizing mode',- enum: ['FIXED', 'HUG', 'FILL']- },- sizing_vertical: {- type: 'string',- description: 'Vertical sizing mode',- enum: ['FIXED', 'HUG', 'FILL']- },- grow: { type: 'number', description: 'Flex grow factor (0 = fixed, 1 = grow)', min: 0 },- align_self: {- type: 'string',- description: 'Self alignment override (cross-axis)',- enum: ['INHERIT', 'MIN', 'CENTER', 'MAX', 'STRETCH', 'BASELINE']- },- positioning: {- type: 'string',- description: 'ABSOLUTE to take node out of auto-layout flow',- enum: ['AUTO', 'ABSOLUTE']- }- },- execute: (figma, args) => {- const node = figma.getNodeById(args.id)- if (!node) return { error: `Node "${args.id}" not found` }- const updated: string[] = []- if (args.sizing_horizontal !== undefined) {- node.layoutSizingHorizontal = args.sizing_horizontal- updated.push('layoutSizingHorizontal')- }- if (args.sizing_vertical !== undefined) {- node.layoutSizingVertical = args.sizing_vertical- updated.push('layoutSizingVertical')- }- if (args.grow !== undefined) {- node.layoutGrow = args.grow- updated.push('layoutGrow')- }- if (args.align_self !== undefined) {- node.layoutAlign = args.align_self- updated.push('layoutAlign')- }- if (args.positioning !== undefined) {- node.layoutPositioning = args.positioning- updated.push('layoutPositioning')- }- return { id: args.id, updated }- }-})--export const setImageFill = defineTool({- name: 'set_image_fill',- mutates: true,- description: 'Set an image fill on a node from base64-encoded image data.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- image_data: {- type: 'string',- description: 'Base64-encoded image bytes (PNG, JPEG, or WEBP)',- required: true- },- scale_mode: {- type: 'string',- description: 'Image scale mode',- default: 'FILL',- enum: ['FILL', 'FIT', 'CROP', 'TILE']- }- },- execute: (figma, { id, image_data, scale_mode }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- const bytes = Uint8Array.fromBase64(image_data)- const image = figma.createImage(bytes)- const mode = (scale_mode ?? 'FILL') as 'FILL' | 'FIT' | 'CROP' | 'TILE'- node.fills = [- {- type: 'IMAGE',- color: { r: 0, g: 0, b: 0, a: 1 },- opacity: 1,- visible: true,- imageHash: image.hash,- imageScaleMode: mode- }- ]- return { id, imageHash: image.hash, scaleMode: mode }- }-})+export { setEffects } from './modify/effects'+export { setMinMax, setOpacity, setRadius, setRotation } from './modify/geometry'+export { setConstraints, setLayout, setLayoutChild } from './modify/layout'+export { setFill, setImageFill, setStroke } from './modify/paint'+export { setBlend, setLocked, setStrokeAlign, setVisible } from './modify/state'+export { setFont, setFontRange, setText, setTextProperties, setTextResize } from './modify/text'+export { updateNode } from './modify/update'diff --git a/packages/core/src/tools/modify/effects.ts b/packages/core/src/tools/modify/effects.tsnew file mode 100644index 000000000..3ea496ca1--- /dev/null+++ b/packages/core/src/tools/modify/effects.ts@@ -0,0 +1,47 @@+import { parseColor } from '#core/color'+import { DEFAULT_SHADOW_COLOR } from '#core/constants'+import { defineTool, nodeNotFound } from '#core/tools/schema'++import type { Effect } from '#core/scene-graph'++export const setEffects = defineTool({+ name: 'set_effects',+ mutates: true,+ description:+ 'Set effects on a node (drop shadow, inner shadow, blur). Pass an array or a single effect.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ type: {+ type: 'string',+ description: 'Effect type',+ required: true,+ enum: ['DROP_SHADOW', 'INNER_SHADOW', 'FOREGROUND_BLUR', 'BACKGROUND_BLUR']+ },+ color: { type: 'color', description: 'Shadow color (hex). Ignored for blur.' },+ offset_x: { type: 'number', description: 'Shadow X offset', default: 0 },+ offset_y: { type: 'number', description: 'Shadow Y offset', default: 4 },+ radius: { type: 'number', description: 'Blur radius', default: 4, min: 0 },+ spread: { type: 'number', description: 'Shadow spread', default: 0 }+ },+ execute: (figma, args) => {+ const node = figma.getNodeById(args.id)+ if (!node) return nodeNotFound(args.id)++ const isBlur = args.type === 'FOREGROUND_BLUR' || args.type === 'BACKGROUND_BLUR'+ let color = { ...DEFAULT_SHADOW_COLOR }+ if (isBlur) color = { r: 0, g: 0, b: 0, a: 0 }+ else if (args.color) color = parseColor(args.color)+ const effect: Effect = {+ type: args.type as Effect['type'],+ visible: true,+ radius: args.radius ?? 4,+ color,+ offset: { x: isBlur ? 0 : (args.offset_x ?? 0), y: isBlur ? 0 : (args.offset_y ?? 4) },+ spread: isBlur ? 0 : (args.spread ?? 0)+ }++ node.effects = [...node.effects, effect]+ return { id: args.id, effects: node.effects.length }+ }+})+diff --git a/packages/core/src/tools/modify/geometry.ts b/packages/core/src/tools/modify/geometry.tsnew file mode 100644index 000000000..5d7f0753b--- /dev/null+++ b/packages/core/src/tools/modify/geometry.ts@@ -0,0 +1,98 @@+import { defineTool, nodeNotFound } from '#core/tools/schema'++export const setRotation = defineTool({+ name: 'set_rotation',+ mutates: true,+ description: 'Set rotation angle of a node in degrees.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ angle: { type: 'number', description: 'Rotation angle in degrees', required: true }+ },+ execute: (figma, { id, angle }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ node.rotation = angle+ return { id, rotation: angle }+ }+})++export const setOpacity = defineTool({+ name: 'set_opacity',+ mutates: true,+ description: 'Set opacity of a node (0-1).',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ value: { type: 'number', description: 'Opacity (0-1)', required: true, min: 0, max: 1 }+ },+ execute: (figma, { id, value }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ node.opacity = value+ return { id, opacity: value }+ }+})++export const setRadius = defineTool({+ name: 'set_radius',+ mutates: true,+ description: 'Set corner radius. Use individual corners for independent values.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ radius: { type: 'number', description: 'Corner radius for all corners', min: 0 },+ top_left: { type: 'number', description: 'Top-left radius', min: 0 },+ top_right: { type: 'number', description: 'Top-right radius', min: 0 },+ bottom_right: { type: 'number', description: 'Bottom-right radius', min: 0 },+ bottom_left: { type: 'number', description: 'Bottom-left radius', min: 0 }+ },+ execute: (figma, args) => {+ const node = figma.getNodeById(args.id)+ if (!node) return nodeNotFound(args.id)+ if (args.radius !== undefined) {+ node.cornerRadius = args.radius+ }+ if (args.top_left !== undefined) node.topLeftRadius = args.top_left+ if (args.top_right !== undefined) node.topRightRadius = args.top_right+ if (args.bottom_right !== undefined) node.bottomRightRadius = args.bottom_right+ if (args.bottom_left !== undefined) node.bottomLeftRadius = args.bottom_left+ const cr = node.cornerRadius+ if (typeof cr === 'number') {+ return { id: args.id, cornerRadius: cr }+ }+ return {+ id: args.id,+ topLeftRadius: node.topLeftRadius,+ topRightRadius: node.topRightRadius,+ bottomRightRadius: node.bottomRightRadius,+ bottomLeftRadius: node.bottomLeftRadius+ }+ }+})++export const setMinMax = defineTool({+ name: 'set_minmax',+ mutates: true,+ description: 'Set min/max width and height constraints on a node.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ min_width: { type: 'number', description: 'Minimum width', min: 0 },+ max_width: { type: 'number', description: 'Maximum width', min: 0 },+ min_height: { type: 'number', description: 'Minimum height', min: 0 },+ max_height: { type: 'number', description: 'Maximum height', min: 0 }+ },+ execute: (figma, args) => {+ const node = figma.getNodeById(args.id)+ if (!node) return nodeNotFound(args.id)+ if (args.min_width !== undefined) node.minWidth = args.min_width+ if (args.max_width !== undefined) node.maxWidth = args.max_width+ if (args.min_height !== undefined) node.minHeight = args.min_height+ if (args.max_height !== undefined) node.maxHeight = args.max_height+ return {+ id: args.id,+ minWidth: node.minWidth,+ maxWidth: node.maxWidth,+ minHeight: node.minHeight,+ maxHeight: node.maxHeight+ }+ }+})+diff --git a/packages/core/src/tools/modify/layout.ts b/packages/core/src/tools/modify/layout.tsnew file mode 100644index 000000000..39c5ab34b--- /dev/null+++ b/packages/core/src/tools/modify/layout.ts@@ -0,0 +1,172 @@+import { defineTool, nodeNotFound } from '#core/tools/schema'++import type { SceneNode } from '#core/scene-graph'++export const setLayout = defineTool({+ name: 'set_layout',+ mutates: true,+ description: 'Set auto-layout (flexbox) on a frame. Direction, alignment, spacing, padding.',+ params: {+ id: { type: 'string', description: 'Frame node ID', required: true },+ direction: {+ type: 'string',+ description: 'Layout direction (keeps current if omitted)',+ enum: ['HORIZONTAL', 'VERTICAL']+ },+ spacing: {+ type: 'number',+ description: 'Gap between items (only changes if provided)',+ min: 0+ },+ padding: {+ type: 'number',+ description: 'Equal padding on all sides (only changes if provided)',+ min: 0+ },+ padding_horizontal: { type: 'number', description: 'Horizontal padding', min: 0 },+ padding_vertical: { type: 'number', description: 'Vertical padding', min: 0 },+ align: {+ type: 'string',+ description: 'Primary axis alignment (only changes if provided)',+ enum: ['MIN', 'CENTER', 'MAX', 'SPACE_BETWEEN']+ },+ counter_align: {+ type: 'string',+ description: 'Cross axis alignment (only changes if provided)',+ enum: ['MIN', 'CENTER', 'MAX', 'STRETCH']+ },+ flow_direction: {+ type: 'string',+ description: 'Child flow direction for auto-layout. AUTO inherits from parent.',+ enum: ['AUTO', 'LTR', 'RTL']+ }+ },+ execute: (figma, args) => {+ const node = figma.getNodeById(args.id)+ if (!node) return nodeNotFound(args.id)++ const raw = figma.graph.getNode(args.id)+ if (!args.direction && raw?.layoutMode === 'NONE') {+ return {+ error: 'Frame has no auto-layout. Pass direction ("HORIZONTAL" or "VERTICAL") to enable it.'+ }+ }++ const wasNone = raw?.layoutMode === 'NONE'+ if (args.direction) node.layoutMode = args.direction as 'HORIZONTAL' | 'VERTICAL'+ if (wasNone) {+ node.primaryAxisSizingMode = 'AUTO'+ node.counterAxisSizingMode = 'AUTO'+ }+ if (args.spacing !== undefined) node.itemSpacing = args.spacing+ if (args.align !== undefined) node.primaryAxisAlignItems = args.align+ if (args.counter_align !== undefined) node.counterAxisAlignItems = args.counter_align+ if (args.flow_direction !== undefined)+ node.layoutDirection = args.flow_direction as SceneNode['layoutDirection']++ if (args.padding !== undefined) {+ node.paddingTop = args.padding+ node.paddingRight = args.padding+ node.paddingBottom = args.padding+ node.paddingLeft = args.padding+ }+ if (args.padding_horizontal !== undefined) {+ node.paddingLeft = args.padding_horizontal+ node.paddingRight = args.padding_horizontal+ }+ if (args.padding_vertical !== undefined) {+ node.paddingTop = args.padding_vertical+ node.paddingBottom = args.padding_vertical+ }++ return { id: args.id, spacing: node.itemSpacing }+ }+})++export const setConstraints = defineTool({+ name: 'set_constraints',+ mutates: true,+ description: 'Set resize constraints for a node within its parent.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ horizontal: {+ type: 'string',+ description: 'Horizontal constraint',+ enum: ['MIN', 'CENTER', 'MAX', 'STRETCH', 'SCALE']+ },+ vertical: {+ type: 'string',+ description: 'Vertical constraint',+ enum: ['MIN', 'CENTER', 'MAX', 'STRETCH', 'SCALE']+ }+ },+ execute: (figma, args) => {+ const node = figma.getNodeById(args.id)+ if (!node) return nodeNotFound(args.id)+ if (args.horizontal || args.vertical) {+ node.constraints = {+ horizontal: args.horizontal ?? node.constraints.horizontal,+ vertical: args.vertical ?? node.constraints.vertical+ }+ }+ return { id: args.id, constraints: node.constraints }+ }+})++export const setLayoutChild = defineTool({+ name: 'set_layout_child',+ mutates: true,+ description:+ 'Configure auto-layout child: sizing (FIXED/HUG/FILL), grow, alignment, absolute positioning.',+ params: {+ id: { type: 'string', description: 'Child node ID', required: true },+ sizing_horizontal: {+ type: 'string',+ description: 'Horizontal sizing mode',+ enum: ['FIXED', 'HUG', 'FILL']+ },+ sizing_vertical: {+ type: 'string',+ description: 'Vertical sizing mode',+ enum: ['FIXED', 'HUG', 'FILL']+ },+ grow: { type: 'number', description: 'Flex grow factor (0 = fixed, 1 = grow)', min: 0 },+ align_self: {+ type: 'string',+ description: 'Self alignment override (cross-axis)',+ enum: ['INHERIT', 'MIN', 'CENTER', 'MAX', 'STRETCH', 'BASELINE']+ },+ positioning: {+ type: 'string',+ description: 'ABSOLUTE to take node out of auto-layout flow',+ enum: ['AUTO', 'ABSOLUTE']+ }+ },+ execute: (figma, args) => {+ const node = figma.getNodeById(args.id)+ if (!node) return nodeNotFound(args.id)+ const updated: string[] = []+ if (args.sizing_horizontal !== undefined) {+ node.layoutSizingHorizontal = args.sizing_horizontal+ updated.push('layoutSizingHorizontal')+ }+ if (args.sizing_vertical !== undefined) {+ node.layoutSizingVertical = args.sizing_vertical+ updated.push('layoutSizingVertical')+ }+ if (args.grow !== undefined) {+ node.layoutGrow = args.grow+ updated.push('layoutGrow')+ }+ if (args.align_self !== undefined) {+ node.layoutAlign = args.align_self+ updated.push('layoutAlign')+ }+ if (args.positioning !== undefined) {+ node.layoutPositioning = args.positioning+ updated.push('layoutPositioning')+ }+ return { id: args.id, updated }+ }+})+diff --git a/packages/core/src/tools/modify/paint.ts b/packages/core/src/tools/modify/paint.tsnew file mode 100644index 000000000..11b1e54ed--- /dev/null+++ b/packages/core/src/tools/modify/paint.ts@@ -0,0 +1,129 @@+import { parseColor } from '#core/color'+import { defineTool } from '#core/tools/schema'++import type { Matrix } from '#core/types'++export const setFill = defineTool({+ name: 'set_fill',+ mutates: true,+ description:+ 'Set fill on a node. Solid: color="#ff0000". Linear gradient: gradient="top-bottom" or "left-right" with color (start) and color_end (end).',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ color: {+ type: 'color',+ description: 'Color (hex). For gradient: start color.',+ required: true+ },+ color_end: { type: 'color', description: 'End color for gradient (if omitted, solid fill)' },+ gradient: {+ type: 'string',+ description: 'Gradient direction',+ enum: ['top-bottom', 'bottom-top', 'left-right', 'right-left']+ }+ },+ execute: (figma, { id, color, color_end, gradient }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }++ const c = parseColor(color)++ if (gradient && color_end) {+ const cEnd = parseColor(color_end)+ const transforms: Record<string, Matrix> = {+ 'top-bottom': { m00: 0, m01: 1, m02: 0, m10: -1, m11: 0, m12: 1 },+ 'bottom-top': { m00: 0, m01: -1, m02: 1, m10: 1, m11: 0, m12: 0 },+ 'left-right': { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 },+ 'right-left': { m00: -1, m01: 0, m02: 1, m10: 0, m11: -1, m12: 1 }+ }+ node.fills = [+ {+ type: 'GRADIENT_LINEAR',+ color: c,+ opacity: 1,+ visible: true,+ gradientStops: [+ { position: 0, color: c },+ { position: 1, color: cEnd }+ ],+ gradientTransform: transforms[gradient] ?? transforms['top-bottom']+ }+ ]+ return { id, gradient, start: c, end: cEnd }+ }++ node.fills = [{ type: 'SOLID', color: c, opacity: 1, visible: true }]+ return { id, color: c }+ }+})++export const setStroke = defineTool({+ name: 'set_stroke',+ mutates: true,+ description: 'Set the stroke (border) of a node.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ color: { type: 'color', description: 'Stroke color (hex)', required: true },+ weight: { type: 'number', description: 'Stroke weight', default: 1, min: 0.1 },+ align: {+ type: 'string',+ description: 'Stroke alignment',+ default: 'INSIDE',+ enum: ['INSIDE', 'CENTER', 'OUTSIDE']+ }+ },+ execute: (figma, { id, color, weight, align }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }++ const c = parseColor(color)+ node.strokes = [+ {+ color: c,+ weight: weight ?? 1,+ opacity: 1,+ visible: true,+ align: (align ?? 'INSIDE') as 'INSIDE' | 'CENTER' | 'OUTSIDE'+ }+ ]+ return { id, color: c, weight: weight ?? 1 }+ }+})++export const setImageFill = defineTool({+ name: 'set_image_fill',+ mutates: true,+ description: 'Set an image fill on a node from base64-encoded image data.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ image_data: {+ type: 'string',+ description: 'Base64-encoded image bytes (PNG, JPEG, or WEBP)',+ required: true+ },+ scale_mode: {+ type: 'string',+ description: 'Image scale mode',+ default: 'FILL',+ enum: ['FILL', 'FIT', 'CROP', 'TILE']+ }+ },+ execute: (figma, { id, image_data, scale_mode }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ const bytes = Uint8Array.fromBase64(image_data)+ const image = figma.createImage(bytes)+ const mode = (scale_mode ?? 'FILL') as 'FILL' | 'FIT' | 'CROP' | 'TILE'+ node.fills = [+ {+ type: 'IMAGE',+ color: { r: 0, g: 0, b: 0, a: 1 },+ opacity: 1,+ visible: true,+ imageHash: image.hash,+ imageScaleMode: mode+ }+ ]+ return { id, imageHash: image.hash, scaleMode: mode }+ }+})diff --git a/packages/core/src/tools/modify/state.ts b/packages/core/src/tools/modify/state.tsnew file mode 100644index 000000000..8fa709039--- /dev/null+++ b/packages/core/src/tools/modify/state.ts@@ -0,0 +1,93 @@+import { defineTool } from '#core/tools/schema'++export const setVisible = defineTool({+ name: 'set_visible',+ mutates: true,+ description: 'Set visibility of a node.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ value: { type: 'boolean', description: 'Visible (true/false)', required: true }+ },+ execute: (figma, { id, value }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ node.visible = value+ return { id, visible: value }+ }+})++export const setBlend = defineTool({+ name: 'set_blend',+ mutates: true,+ description: 'Set blend mode of a node.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ mode: {+ type: 'string',+ description: 'Blend mode',+ required: true,+ enum: [+ 'NORMAL',+ 'DARKEN',+ 'MULTIPLY',+ 'COLOR_BURN',+ 'LIGHTEN',+ 'SCREEN',+ 'COLOR_DODGE',+ 'OVERLAY',+ 'SOFT_LIGHT',+ 'HARD_LIGHT',+ 'DIFFERENCE',+ 'EXCLUSION',+ 'HUE',+ 'SATURATION',+ 'COLOR',+ 'LUMINOSITY'+ ]+ }+ },+ execute: (figma, { id, mode }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ node.blendMode = mode+ return { id, blendMode: mode }+ }+})++export const setLocked = defineTool({+ name: 'set_locked',+ mutates: true,+ description: 'Set locked state of a node.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ value: { type: 'boolean', description: 'Locked (true/false)', required: true }+ },+ execute: (figma, { id, value }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ node.locked = value+ return { id, locked: value }+ }+})++export const setStrokeAlign = defineTool({+ name: 'set_stroke_align',+ mutates: true,+ description: 'Set stroke alignment of a node.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ align: {+ type: 'string',+ description: 'Stroke alignment',+ required: true,+ enum: ['INSIDE', 'CENTER', 'OUTSIDE']+ }+ },+ execute: (figma, { id, align }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ node.strokeAlign = align+ return { id, strokeAlign: align }+ }+})+diff --git a/packages/core/src/tools/modify/text.ts b/packages/core/src/tools/modify/text.tsnew file mode 100644index 000000000..e429e0fae--- /dev/null+++ b/packages/core/src/tools/modify/text.ts@@ -0,0 +1,166 @@+import { parseColor } from '#core/color'+import { styleToWeight } from '#core/text/fonts'+import { applyStyleToRange } from '#core/text/style-runs'+import { defineTool, nodeNotFound } from '#core/tools/schema'++import type { CharacterStyleOverride, SceneNode } from '#core/scene-graph'++export const setText = defineTool({+ name: 'set_text',+ mutates: true,+ description: 'Set text content of a text node.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ text: { type: 'string', description: 'Text content', required: true }+ },+ execute: (figma, { id, text }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ node.characters = text+ return { id, text }+ }+})++export const setFont = defineTool({+ name: 'set_font',+ mutates: true,+ description: 'Set font properties of a text node.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ family: { type: 'string', description: 'Font family name' },+ size: { type: 'number', description: 'Font size', min: 1 },+ style: { type: 'string', description: 'Font style (e.g. "Bold", "Regular", "Bold Italic")' }+ },+ execute: (figma, args) => {+ const node = figma.getNodeById(args.id)+ if (!node) return nodeNotFound(args.id)+ if (args.size !== undefined) node.fontSize = args.size+ if (args.family || args.style) {+ const current = node.fontName+ node.fontName = {+ family: args.family ?? current.family,+ style: args.style ?? current.style+ }+ }+ return { id: args.id, fontName: node.fontName, fontSize: node.fontSize }+ }+})++export const setFontRange = defineTool({+ name: 'set_font_range',+ mutates: true,+ description: 'Set font properties for a text range.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ start: { type: 'number', description: 'Start character index', required: true, min: 0 },+ end: { type: 'number', description: 'End character index', required: true, min: 0 },+ family: { type: 'string', description: 'Font family name' },+ size: { type: 'number', description: 'Font size', min: 1 },+ style: { type: 'string', description: 'Font style' },+ color: { type: 'color', description: 'Text color (hex)' }+ },+ execute: (figma, args) => {+ const node = figma.getNodeById(args.id)+ if (!node) return nodeNotFound(args.id)+ const override: CharacterStyleOverride = {}+ if (args.family) override.fontFamily = args.family+ if (args.size) override.fontSize = args.size+ if (args.style) {+ const s = args.style.toLowerCase()+ if (s.includes('italic')) override.italic = true+ override.fontWeight = styleToWeight(args.style)+ }+ if (args.color) {+ override.fills = [{ type: 'SOLID', color: parseColor(args.color), opacity: 1, visible: true }]+ }+ const raw = figma.graph.getNode(node.id)+ if (!raw) return { error: `Node "${args.id}" not found` }+ const runs = applyStyleToRange(raw.styleRuns, args.start, args.end, override, raw.text.length)+ figma.graph.updateNode(node.id, { styleRuns: runs })+ return { id: args.id, range: { start: args.start, end: args.end } }+ }+})++export const setTextResize = defineTool({+ name: 'set_text_resize',+ mutates: true,+ description: 'Set text auto-resize mode.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ mode: {+ type: 'string',+ description: 'Resize mode',+ required: true,+ enum: ['NONE', 'WIDTH_AND_HEIGHT', 'HEIGHT', 'TRUNCATE']+ }+ },+ execute: (figma, { id, mode }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ node.textAutoResize = mode+ return { id, textAutoResize: mode }+ }+})++export const setTextProperties = defineTool({+ name: 'set_text_properties',+ mutates: true,+ description:+ 'Set text layout properties: alignment, auto-resize, text case, decoration, truncation.',+ params: {+ id: { type: 'string', description: 'Text node ID', required: true },+ align_horizontal: {+ type: 'string',+ description: 'Horizontal text alignment',+ enum: ['LEFT', 'CENTER', 'RIGHT', 'JUSTIFIED']+ },+ align_vertical: {+ type: 'string',+ description: 'Vertical text alignment',+ enum: ['TOP', 'CENTER', 'BOTTOM']+ },+ auto_resize: {+ type: 'string',+ description: 'Text auto-resize mode',+ enum: ['NONE', 'WIDTH_AND_HEIGHT', 'HEIGHT', 'TRUNCATE']+ },+ direction: {+ type: 'string',+ description: 'Text direction',+ enum: ['AUTO', 'LTR', 'RTL']+ },+ text_decoration: {+ type: 'string',+ description: 'Text decoration',+ enum: ['NONE', 'UNDERLINE', 'STRIKETHROUGH']+ }+ },+ execute: (figma, args) => {+ const node = figma.getNodeById(args.id)+ if (!node) return nodeNotFound(args.id)+ if (node.type !== 'TEXT') return { error: `Node "${args.id}" is not a TEXT node` }+ const updated: string[] = []+ if (args.align_horizontal !== undefined) {+ node.textAlignHorizontal = args.align_horizontal+ updated.push('textAlignHorizontal')+ }+ if (args.align_vertical !== undefined) {+ node.textAlignVertical = args.align_vertical+ updated.push('textAlignVertical')+ }+ if (args.auto_resize !== undefined) {+ node.textAutoResize = args.auto_resize+ updated.push('textAutoResize')+ }+ if (args.direction !== undefined) {+ node.textDirection = args.direction as SceneNode['textDirection']+ updated.push('textDirection')+ }+ if (args.text_decoration !== undefined) {+ node.textDecoration = args.text_decoration+ updated.push('textDecoration')+ }+ return { id: args.id, updated }+ }+})+diff --git a/packages/core/src/tools/modify/update.ts b/packages/core/src/tools/modify/update.tsnew file mode 100644index 000000000..b370c342e--- /dev/null+++ b/packages/core/src/tools/modify/update.ts@@ -0,0 +1,92 @@+import { defineTool, nodeNotFound } from '#core/tools/schema'++import type { SceneNode } from '#core/scene-graph'++export const updateNode = defineTool({+ name: 'update_node',+ mutates: true,+ description:+ 'Update properties of an existing node: position, size, opacity, corner radius, visibility, text, font.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ x: { type: 'number', description: 'X position' },+ y: { type: 'number', description: 'Y position' },+ width: { type: 'number', description: 'Width', min: 1 },+ height: { type: 'number', description: 'Height', min: 1 },+ opacity: { type: 'number', description: 'Opacity (0-1)', min: 0, max: 1 },+ corner_radius: { type: 'number', description: 'Corner radius', min: 0 },+ visible: { type: 'boolean', description: 'Visibility' },+ text: { type: 'string', description: 'Text content (TEXT nodes)' },+ text_direction: {+ type: 'string',+ description: 'Text direction for TEXT nodes',+ enum: ['AUTO', 'LTR', 'RTL'],+ },+ flow_direction: {+ type: 'string',+ description: 'Auto-layout flow direction for FRAME nodes',+ enum: ['AUTO', 'LTR', 'RTL'],+ },+ font_size: { type: 'number', description: 'Font size', min: 1 },+ font_weight: { type: 'number', description: 'Font weight (100-900)' },+ name: { type: 'string', description: 'Layer name' },+ },+ execute: (figma, args) => {+ const node = figma.getNodeById(args.id)+ if (!node) return nodeNotFound(args.id)+ const updated: string[] = []+ if (args.x !== undefined) {+ node.x = args.x+ updated.push('x')+ }+ if (args.y !== undefined) {+ node.y = args.y+ updated.push('y')+ }+ if (args.width !== undefined || args.height !== undefined) {+ node.resize(args.width ?? node.width, args.height ?? node.height)+ updated.push('size')+ }+ if (args.opacity !== undefined) {+ node.opacity = args.opacity+ updated.push('opacity')+ }+ if (args.corner_radius !== undefined) {+ node.cornerRadius = args.corner_radius+ updated.push('cornerRadius')+ }+ if (args.visible !== undefined) {+ node.visible = args.visible+ updated.push('visible')+ }+ if (args.name !== undefined) {+ node.name = args.name+ updated.push('name')+ }+ if (args.text !== undefined) {+ figma.graph.updateNode(node.id, { text: args.text })+ updated.push('text')+ }+ if (args.text_direction !== undefined) {+ figma.graph.updateNode(node.id, {+ textDirection: args.text_direction as SceneNode['textDirection'],+ })+ updated.push('textDirection')+ }+ if (args.flow_direction !== undefined) {+ figma.graph.updateNode(node.id, {+ layoutDirection: args.flow_direction as SceneNode['layoutDirection'],+ })+ updated.push('layoutDirection')+ }+ if (args.font_size !== undefined) {+ figma.graph.updateNode(node.id, { fontSize: args.font_size })+ updated.push('fontSize')+ }+ if (args.font_weight !== undefined) {+ figma.graph.updateNode(node.id, { fontWeight: args.font_weight })+ updated.push('fontWeight')+ }+ return { id: args.id, updated }+ },+})diff --git a/packages/core/src/tools/read.ts b/packages/core/src/tools/read.tsindex 6b05081ea..c3443a59d 100644--- a/packages/core/src/tools/read.ts+++ b/packages/core/src/tools/read.ts@@ -1,344 +1,7 @@-import { createTwoFilesPatch } from 'diff'--import { computeBounds } from '../geometry'-import { sceneNodeToJSX } from '../io/formats/jsx'-import { queryByXPath } from '../xpath'-import { defineTool, nodeSummary, nodeToResult } from './schema'--import type { FigmaNodeProxy } from '../figma-api'--export const getSelection = defineTool({- name: 'get_selection',- description: 'Get details about currently selected nodes.',- params: {},- execute: (figma) => {- const sel = figma.currentPage.selection- return { selection: sel.map(nodeToResult) }- }-})--interface TreeEntry {- id: string- type: string- name: string- w: number- h: number- children?: TreeEntry[]-}--function nodeToTreeEntry(node: FigmaNodeProxy): TreeEntry {- const entry: TreeEntry = {- id: node.id,- type: node.type,- name: node.name,- w: node.width,- h: node.height- }- if (node.children.length > 0) {- entry.children = node.children.map(nodeToTreeEntry)- }- return entry-}--export const getPageTree = defineTool({- name: 'get_page_tree',- description:- 'Get the node tree of the current page. Returns lightweight hierarchy: id, type, name, size. Use get_node for full properties of a specific node.',- params: {},- execute: (figma) => {- const page = figma.currentPage- return {- page: page.name,- children: page.children.map(nodeToTreeEntry)- }- }-})--export const getNode = defineTool({- name: 'get_node',- description:- 'Get detailed properties of a node by ID. Use depth to limit child recursion (0 = node only, 1 = direct children, etc). Default: unlimited.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- depth: {- type: 'number',- description: 'Max depth of children to include (0 = no children). Default: unlimited'- }- },- execute: (figma, { id, depth }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- return nodeToResult(node, depth)- }-})--export const findNodes = defineTool({- name: 'find_nodes',- description: 'Find nodes by name pattern and/or type.',- params: {- name: { type: 'string', description: 'Name substring to match (case-insensitive)' },- type: {- type: 'string',- description: 'Node type filter',- enum: [- 'FRAME',- 'RECTANGLE',- 'ELLIPSE',- 'TEXT',- 'LINE',- 'STAR',- 'POLYGON',- 'SECTION',- 'GROUP',- 'COMPONENT',- 'INSTANCE',- 'VECTOR'- ]- }- },- execute: (figma, args) => {- const page = figma.currentPage- const matches = page.findAll((node) => {- if (args.type && node.type !== args.type) return false- if (args.name && !node.name.toLowerCase().includes(args.name.toLowerCase())) return false- return true- })- return { count: matches.length, nodes: matches.map(nodeSummary) }- }-})--export const getComponents = defineTool({- name: 'get_components',- description: 'List all components in the document, optionally filtered by name.',- params: {- name: { type: 'string', description: 'Filter by name (case-insensitive substring)' },- limit: { type: 'number', description: 'Max results (default: 50)' }- },- execute: (figma, args) => {- const limit = args.limit ?? 50- const nameFilter = args.name?.toLowerCase()- const components: { id: string; name: string; type: string; page: string }[] = []-- for (const page of figma.root.children) {- if (components.length >= limit) break- page.findAll((node) => {- if (components.length >= limit) return false- if (node.type !== 'COMPONENT' && node.type !== 'COMPONENT_SET') return false- if (nameFilter && !node.name.toLowerCase().includes(nameFilter)) return false- components.push({ id: node.id, name: node.name, type: node.type, page: page.name })- return false- })- }-- return { count: components.length, components }- }-})--export const listPages = defineTool({- name: 'list_pages',- description: 'List all pages in the document.',- params: {},- execute: (figma) => {- const pages = figma.root.children- return {- current: figma.currentPage.name,- pages: pages.map((p) => ({ id: p.id, name: p.name }))- }- }-})--export const switchPage = defineTool({- name: 'switch_page',- mutates: true,- description: 'Switch to a different page by name or ID.',- params: {- page: { type: 'string', description: 'Page name or ID', required: true }- },- execute: (figma, { page }) => {- const target = figma.root.children.find((p) => p.name === page) ?? figma.getNodeById(page)- if (!target) return { error: `Page "${page}" not found` }- figma.currentPage = target- return { page: target.name, id: target.id }- }-})--export const getCurrentPage = defineTool({- name: 'get_current_page',- description: 'Get the current page name and ID.',- params: {},- execute: (figma) => {- return { id: figma.currentPage.id, name: figma.currentPage.name }- }-})--export const pageBounds = defineTool({- name: 'page_bounds',- description: 'Get bounding box of all objects on the current page.',- params: {},- execute: (figma) => {- return computeBounds(figma.currentPage.children.map((c) => c.absoluteBoundingBox))- }-})--export const selectNodes = defineTool({- name: 'select_nodes',- mutates: true,- description: 'Select one or more nodes by ID.',- params: {- ids: { type: 'string[]', description: 'Node IDs to select', required: true }- },- execute: (figma, { ids }) => {- figma.currentPage.selection = ids- .map((id) => figma.getNodeById(id))- .filter((n): n is FigmaNodeProxy => n !== null)- return { selected: ids }- }-})--export const listFonts = defineTool({- name: 'list_fonts',- description: 'List fonts used in the current page.',- params: {- family: { type: 'string', description: 'Filter by family name (substring)' }- },- execute: (figma, args) => {- const fonts = new Map<string, Set<number>>()- const page = figma.currentPage- page.findAll((node) => {- if (node.type === 'TEXT') {- const raw = figma.graph.getNode(node.id)- if (raw) {- const key = raw.fontFamily- if (!fonts.has(key)) fonts.set(key, new Set())- fonts.get(key)?.add(raw.fontWeight)- }- }- return false- })- let result = [...fonts.entries()].map(([family, weights]) => ({- family,- weights: [...weights].sort((a, b) => a - b)- }))- if (args.family) {- const q = args.family.toLowerCase()- result = result.filter((f) => f.family.toLowerCase().includes(q))- }- return { count: result.length, fonts: result }- }-})--export const listAvailableFonts = defineTool({- name: 'list_available_fonts',- description:- 'List font families the host can render (system fonts on desktop plus any bundled fonts). ' +- 'Use this to discover what fonts are available to set on a text node — distinct from list_fonts ' +- 'which only reports families currently used in the page.',- params: {- family: { type: 'string', description: 'Filter by family name (substring, case-insensitive)' }- },- execute: async (figma, args) => {- const fonts = await figma.listAvailableFontsAsync()- let families = Array.from(new Set(fonts.map((f) => f.fontName.family)))- if (args.family) {- const q = args.family.toLowerCase()- families = families.filter((f) => f.toLowerCase().includes(q))- }- families.sort((a, b) => a.localeCompare(b))- return { count: families.length, fonts: families }- }-})--export const queryNodes = defineTool({- name: 'query_nodes',- description: `Query nodes using XPath selectors. Node types are element names (FRAME, TEXT, RECTANGLE, ELLIPSE, etc.). Attributes: name, width, height, x, y, visible, opacity, cornerRadius, fontSize, fontFamily, fontWeight, layoutMode, itemSpacing, paddingTop/Right/Bottom/Left, strokeWeight, rotation, locked, blendMode, text, lineHeight, letterSpacing.--Examples:- //FRAME — all frames- //FRAME[@width < 300] — frames narrower than 300px- //COMPONENT[starts-with(@name, 'Button')] — components starting with "Button"- //SECTION/FRAME — direct frame children of sections- //SECTION//TEXT — all text nodes inside sections- //*[@cornerRadius > 0] — any node with corner radius- //TEXT[contains(@text, 'Hello')] — text nodes containing "Hello"`,- params: {- selector: { type: 'string', description: 'XPath selector', required: true },- page: { type: 'string', description: 'Page name (default: current page)' },- limit: { type: 'number', description: 'Max results (default: 1000)' }- },- execute: async (figma, args) => {- try {- const nodes = await queryByXPath(figma.graph, args.selector, {- page: args.page ?? figma.currentPage.name,- limit: args.limit- })- return {- count: nodes.length,- nodes: nodes.map((n) => ({ id: n.id, name: n.name, type: n.type }))- }- } catch (err) {- return { error: `XPath error: ${err instanceof Error ? err.message : String(err)}` }- }- }-})--const MAX_JSX_LENGTH = 12_000--export const getJsx = defineTool({- name: 'get_jsx',- description:- 'Get JSX representation of a node and its children. Compact round-trip format — same syntax as the render tool.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- path: {- type: 'string',- description: 'Write JSX to this path instead of returning it (requires OPENPENCIL_MCP_ROOT)'- }- },- execute: (figma, { id }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- const jsx = sceneNodeToJSX(id, figma.graph)- if (jsx.length > MAX_JSX_LENGTH) {- return {- id,- name: node.name,- jsx: jsx.slice(0, MAX_JSX_LENGTH),- truncated: true,- totalLength: jsx.length- }- }- return { id, name: node.name, jsx }- }-})--export const diffJsx = defineTool({- name: 'diff_jsx',- description:- 'Structural diff between two nodes in JSX format. Shows added/removed children, changed props.',- params: {- from: { type: 'string', description: 'Source node ID', required: true },- to: { type: 'string', description: 'Target node ID', required: true }- },- execute: (figma, { from, to }) => {- const fromNode = figma.getNodeById(from)- if (!fromNode) return { error: `Node "${from}" not found` }- const toNode = figma.getNodeById(to)- if (!toNode) return { error: `Node "${to}" not found` }-- const fromJsx = sceneNodeToJSX(from, figma.graph)- const toJsx = sceneNodeToJSX(to, figma.graph)-- if (fromJsx === toJsx) return { diff: null, message: 'No differences' }-- const patch = createTwoFilesPatch(- fromNode.name,- toNode.name,- fromJsx,- toJsx,- 'source',- 'target',- { context: 3 }- )- return { diff: patch }- }-})+export { getComponents } from './read/components'+export { listAvailableFonts, listFonts } from './read/fonts'+export { diffJsx, getJsx } from './read/jsx'+export { findNodes, getNode, getPageTree } from './read/nodes'+export { getCurrentPage, listPages, pageBounds, switchPage } from './read/pages'+export { queryNodes } from './read/query'+export { getSelection, selectNodes } from './read/selection'diff --git a/packages/core/src/tools/read/components.ts b/packages/core/src/tools/read/components.tsnew file mode 100644index 000000000..7fc474039--- /dev/null+++ b/packages/core/src/tools/read/components.ts@@ -0,0 +1,28 @@+import { defineTool } from '#core/tools/schema'++export const getComponents = defineTool({+ name: 'get_components',+ description: 'List all components in the document, optionally filtered by name.',+ params: {+ name: { type: 'string', description: 'Filter by name (case-insensitive substring)' },+ limit: { type: 'number', description: 'Max results (default: 50)' },+ },+ execute: (figma, args) => {+ const limit = args.limit ?? 50+ const nameFilter = args.name?.toLowerCase()+ const components: { id: string; name: string; type: string; page: string }[] = []++ for (const page of figma.root.children) {+ if (components.length >= limit) break+ page.findAll((node) => {+ if (components.length >= limit) return false+ if (node.type !== 'COMPONENT' && node.type !== 'COMPONENT_SET') return false+ if (nameFilter && !node.name.toLowerCase().includes(nameFilter)) return false+ components.push({ id: node.id, name: node.name, type: node.type, page: page.name })+ return false+ })+ }++ return { count: components.length, components }+ },+})diff --git a/packages/core/src/tools/read/fonts.ts b/packages/core/src/tools/read/fonts.tsnew file mode 100644index 000000000..62675f00f--- /dev/null+++ b/packages/core/src/tools/read/fonts.ts@@ -0,0 +1,54 @@+import { defineTool } from '#core/tools/schema'++export const listFonts = defineTool({+ name: 'list_fonts',+ description: 'List fonts used in the current page.',+ params: {+ family: { type: 'string', description: 'Filter by family name (substring)' },+ },+ execute: (figma, args) => {+ const fonts = new Map<string, Set<number>>()+ const page = figma.currentPage+ page.findAll((node) => {+ if (node.type === 'TEXT') {+ const raw = figma.graph.getNode(node.id)+ if (raw) {+ const key = raw.fontFamily+ if (!fonts.has(key)) fonts.set(key, new Set())+ fonts.get(key)?.add(raw.fontWeight)+ }+ }+ return false+ })+ let result = [...fonts.entries()].map(([family, weights]) => ({+ family,+ weights: [...weights].sort((a, b) => a - b),+ }))+ if (args.family) {+ const q = args.family.toLowerCase()+ result = result.filter((font) => font.family.toLowerCase().includes(q))+ }+ return { count: result.length, fonts: result }+ },+})++export const listAvailableFonts = defineTool({+ name: 'list_available_fonts',+ description:+ 'List font families the host can render (system fonts on desktop plus any bundled fonts). ' ++ 'Use this to discover what fonts are available to set on a text node — distinct from list_fonts ' ++ 'which only reports families currently used in the page.',+ params: {+ family: { type: 'string', description: 'Filter by family name (substring, case-insensitive)' },+ },+ execute: async (figma, args) => {+ const fonts = await figma.listAvailableFontsAsync()+ let families = Array.from(new Set(fonts.map((font) => font.fontName.family)))+ if (args.family) {+ const q = args.family.toLowerCase()+ families = families.filter((family) => family.toLowerCase().includes(q))+ }+ families.sort((a, b) => a.localeCompare(b))+ return { count: families.length, fonts: families }+ },+})diff --git a/packages/core/src/tools/read/jsx.ts b/packages/core/src/tools/read/jsx.tsnew file mode 100644index 000000000..9e7cff722--- /dev/null+++ b/packages/core/src/tools/read/jsx.ts@@ -0,0 +1,66 @@+import { createTwoFilesPatch } from 'diff'++import { sceneNodeToJSX } from '#core/io/formats/jsx'+import { defineTool } from '#core/tools/schema'++const MAX_JSX_LENGTH = 12_000++export const getJsx = defineTool({+ name: 'get_jsx',+ description:+ 'Get JSX representation of a node and its children. Compact round-trip format — same syntax as the render tool.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ path: {+ type: 'string',+ description: 'Write JSX to this path instead of returning it (requires OPENPENCIL_MCP_ROOT)',+ },+ },+ execute: (figma, { id }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ const jsx = sceneNodeToJSX(id, figma.graph)+ if (jsx.length > MAX_JSX_LENGTH) {+ return {+ id,+ name: node.name,+ jsx: jsx.slice(0, MAX_JSX_LENGTH),+ truncated: true,+ totalLength: jsx.length,+ }+ }+ return { id, name: node.name, jsx }+ },+})++export const diffJsx = defineTool({+ name: 'diff_jsx',+ description:+ 'Structural diff between two nodes in JSX format. Shows added/removed children, changed props.',+ params: {+ from: { type: 'string', description: 'Source node ID', required: true },+ to: { type: 'string', description: 'Target node ID', required: true },+ },+ execute: (figma, { from, to }) => {+ const fromNode = figma.getNodeById(from)+ if (!fromNode) return { error: `Node "${from}" not found` }+ const toNode = figma.getNodeById(to)+ if (!toNode) return { error: `Node "${to}" not found` }++ const fromJsx = sceneNodeToJSX(from, figma.graph)+ const toJsx = sceneNodeToJSX(to, figma.graph)++ if (fromJsx === toJsx) return { diff: null, message: 'No differences' }++ const patch = createTwoFilesPatch(+ fromNode.name,+ toNode.name,+ fromJsx,+ toJsx,+ 'source',+ 'target',+ { context: 3 }+ )+ return { diff: patch }+ },+})diff --git a/packages/core/src/tools/read/nodes.ts b/packages/core/src/tools/read/nodes.tsnew file mode 100644index 000000000..cc545daa6--- /dev/null+++ b/packages/core/src/tools/read/nodes.ts@@ -0,0 +1,93 @@+import { defineTool, nodeSummary, nodeToResult } from '#core/tools/schema'++import type { FigmaNodeProxy } from '#core/figma-api'++interface TreeEntry {+ id: string+ type: string+ name: string+ w: number+ h: number+ children?: TreeEntry[]+}++function nodeToTreeEntry(node: FigmaNodeProxy): TreeEntry {+ const entry: TreeEntry = {+ id: node.id,+ type: node.type,+ name: node.name,+ w: node.width,+ h: node.height,+ }+ if (node.children.length > 0) {+ entry.children = node.children.map(nodeToTreeEntry)+ }+ return entry+}++export const getPageTree = defineTool({+ name: 'get_page_tree',+ description:+ 'Get the node tree of the current page. Returns lightweight hierarchy: id, type, name, size. Use get_node for full properties of a specific node.',+ params: {},+ execute: (figma) => {+ const page = figma.currentPage+ return {+ page: page.name,+ children: page.children.map(nodeToTreeEntry),+ }+ },+})++export const getNode = defineTool({+ name: 'get_node',+ description:+ 'Get detailed properties of a node by ID. Use depth to limit child recursion (0 = node only, 1 = direct children, etc). Default: unlimited.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ depth: {+ type: 'number',+ description: 'Max depth of children to include (0 = no children). Default: unlimited',+ },+ },+ execute: (figma, { id, depth }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ return nodeToResult(node, depth)+ },+})++export const findNodes = defineTool({+ name: 'find_nodes',+ description: 'Find nodes by name pattern and/or type.',+ params: {+ name: { type: 'string', description: 'Name substring to match (case-insensitive)' },+ type: {+ type: 'string',+ description: 'Node type filter',+ enum: [+ 'FRAME',+ 'RECTANGLE',+ 'ELLIPSE',+ 'TEXT',+ 'LINE',+ 'STAR',+ 'POLYGON',+ 'SECTION',+ 'GROUP',+ 'COMPONENT',+ 'INSTANCE',+ 'VECTOR',+ ],+ },+ },+ execute: (figma, args) => {+ const page = figma.currentPage+ const matches = page.findAll((node) => {+ if (args.type && node.type !== args.type) return false+ if (args.name && !node.name.toLowerCase().includes(args.name.toLowerCase())) return false+ return true+ })+ return { count: matches.length, nodes: matches.map(nodeSummary) }+ },+})diff --git a/packages/core/src/tools/read/pages.ts b/packages/core/src/tools/read/pages.tsnew file mode 100644index 000000000..f0f3c3960--- /dev/null+++ b/packages/core/src/tools/read/pages.ts@@ -0,0 +1,48 @@+import { computeBounds } from '#core/geometry'+import { defineTool } from '#core/tools/schema'++export const listPages = defineTool({+ name: 'list_pages',+ description: 'List all pages in the document.',+ params: {},+ execute: (figma) => {+ const pages = figma.root.children+ return {+ current: figma.currentPage.name,+ pages: pages.map((page) => ({ id: page.id, name: page.name })),+ }+ },+})++export const switchPage = defineTool({+ name: 'switch_page',+ mutates: true,+ description: 'Switch to a different page by name or ID.',+ params: {+ page: { type: 'string', description: 'Page name or ID', required: true },+ },+ execute: (figma, { page }) => {+ const target = figma.root.children.find((candidate) => candidate.name === page) ?? figma.getNodeById(page)+ if (!target) return { error: `Page "${page}" not found` }+ figma.currentPage = target+ return { page: target.name, id: target.id }+ },+})++export const getCurrentPage = defineTool({+ name: 'get_current_page',+ description: 'Get the current page name and ID.',+ params: {},+ execute: (figma) => {+ return { id: figma.currentPage.id, name: figma.currentPage.name }+ },+})++export const pageBounds = defineTool({+ name: 'page_bounds',+ description: 'Get bounding box of all objects on the current page.',+ params: {},+ execute: (figma) => {+ return computeBounds(figma.currentPage.children.map((child) => child.absoluteBoundingBox))+ },+})diff --git a/packages/core/src/tools/read/query.ts b/packages/core/src/tools/read/query.tsnew file mode 100644index 000000000..c283aca6c--- /dev/null+++ b/packages/core/src/tools/read/query.ts@@ -0,0 +1,35 @@+import { queryByXPath } from '#core/xpath'+import { defineTool } from '#core/tools/schema'++export const queryNodes = defineTool({+ name: 'query_nodes',+ description: `Query nodes using XPath selectors. Node types are element names (FRAME, TEXT, RECTANGLE, ELLIPSE, etc.). Attributes: name, width, height, x, y, visible, opacity, cornerRadius, fontSize, fontFamily, fontWeight, layoutMode, itemSpacing, paddingTop/Right/Bottom/Left, strokeWeight, rotation, locked, blendMode, text, lineHeight, letterSpacing.++Examples:+ //FRAME — all frames+ //FRAME[@width < 300] — frames narrower than 300px+ //COMPONENT[starts-with(@name, 'Button')] — components starting with "Button"+ //SECTION/FRAME — direct frame children of sections+ //SECTION//TEXT — all text nodes inside sections+ //*[@cornerRadius > 0] — any node with corner radius+ //TEXT[contains(@text, 'Hello')] — text nodes containing "Hello"`,+ params: {+ selector: { type: 'string', description: 'XPath selector', required: true },+ page: { type: 'string', description: 'Page name (default: current page)' },+ limit: { type: 'number', description: 'Max results (default: 1000)' },+ },+ execute: async (figma, args) => {+ try {+ const nodes = await queryByXPath(figma.graph, args.selector, {+ page: args.page ?? figma.currentPage.name,+ limit: args.limit,+ })+ return {+ count: nodes.length,+ nodes: nodes.map((node) => ({ id: node.id, name: node.name, type: node.type })),+ }+ } catch (err) {+ return { error: `XPath error: ${err instanceof Error ? err.message : String(err)}` }+ }+ },+})diff --git a/packages/core/src/tools/read/selection.ts b/packages/core/src/tools/read/selection.tsnew file mode 100644index 000000000..d6c81d21c--- /dev/null+++ b/packages/core/src/tools/read/selection.ts@@ -0,0 +1,28 @@+import { defineTool, nodeToResult } from '#core/tools/schema'++import type { FigmaNodeProxy } from '#core/figma-api'++export const getSelection = defineTool({+ name: 'get_selection',+ description: 'Get details about currently selected nodes.',+ params: {},+ execute: (figma) => {+ const selection = figma.currentPage.selection+ return { selection: selection.map(nodeToResult) }+ },+})++export const selectNodes = defineTool({+ name: 'select_nodes',+ mutates: true,+ description: 'Select one or more nodes by ID.',+ params: {+ ids: { type: 'string[]', description: 'Node IDs to select', required: true },+ },+ execute: (figma, { ids }) => {+ figma.currentPage.selection = ids+ .map((id) => figma.getNodeById(id))+ .filter((node): node is FigmaNodeProxy => node !== null)+ return { selected: ids }+ },+})diff --git a/packages/core/src/tools/registry-core.ts b/packages/core/src/tools/registry-core.tsnew file mode 100644index 000000000..4feb13880--- /dev/null+++ b/packages/core/src/tools/registry-core.ts@@ -0,0 +1,55 @@+import { evalCode } from './analyze'+import { calc } from './calc'+import { render } from './create'+import { describe } from './describe'+import {+ setFill,+ setLayout,+ setLayoutChild,+ setRadius,+ setStroke,+ setText,+ setTextProperties,+ updateNode,+} from './modify'+import { findNodes, getJsx, getNode, getSelection } from './read'+import { stockPhoto } from './stock-photo'+import { batchUpdate, deleteNode, nodeResize, reparentNode } from './structure'+import { viewportZoomToFit } from './vector'++import type { ToolDef } from './schema'++/**+ * Core tools registered by default in AI chat (~30 tools, ~3K schema tokens).+ * Covers 90%+ of design sessions: render, describe, modify, structure, icons.+ */+export const CORE_TOOLS: ToolDef[] = [+ // Read+ getSelection,+ getNode,+ findNodes,+ getJsx,+ // Create+ render,+ // Modify+ updateNode,+ setLayout,+ setLayoutChild,+ setRadius,+ setFill,+ setStroke,+ setText,+ setTextProperties,+ // Structure+ deleteNode,+ reparentNode,+ nodeResize,+ batchUpdate,+ // Stock photos+ stockPhoto,+ // Inspect & utility+ describe,+ calc,+ evalCode,+ viewportZoomToFit,+]diff --git a/packages/core/src/tools/registry-extended.ts b/packages/core/src/tools/registry-extended.tsnew file mode 100644index 000000000..4876fd13a--- /dev/null+++ b/packages/core/src/tools/registry-extended.ts@@ -0,0 +1,188 @@+import {+ analyzeClusters,+ analyzeColors,+ analyzeSpacing,+ analyzeTypography,+ diffCreate,+ diffShow,+} from './analyze'+import { designToComponentMap, designToTokens } from './codegen'+import {+ createComponent,+ createInstance,+ createPage,+ createShape,+ createSlice,+ createVector,+ fetchIconsTool,+ insertIcon,+ searchIconsTool,+} from './create'+import {+ setBlend,+ setConstraints,+ setEffects,+ setFont,+ setFontRange,+ setImageFill,+ setLocked,+ setMinMax,+ setOpacity,+ setRotation,+ setStrokeAlign,+ setTextResize,+ setVisible,+} from './modify'+import {+ diffJsx,+ getComponents,+ getCurrentPage,+ getPageTree,+ listAvailableFonts,+ listFonts,+ listPages,+ pageBounds,+ queryNodes,+ selectNodes,+ switchPage,+} from './read'+import {+ arrangeNodes,+ cloneNode,+ flattenNodes,+ groupNodes,+ nodeAncestors,+ nodeBindings,+ nodeBounds,+ nodeChildren,+ nodeMove,+ nodeReplaceWith,+ nodeToComponent,+ nodeTree,+ renameNode,+ ungroupNode,+} from './structure'+import {+ bindVariable,+ createCollection,+ createVariable,+ deleteCollection,+ deleteVariable,+ findVariables,+ getCollection,+ getVariable,+ listCollections,+ listVariables,+ setVariable,+} from './variables'+import {+ booleanExclude,+ booleanIntersect,+ booleanSubtract,+ booleanUnion,+ exportImage,+ exportSvg,+ pathFlip,+ pathGet,+ pathMove,+ pathScale,+ pathSet,+ viewportGet,+ viewportSet,+} from './vector'++import type { ToolDef } from './schema'++/**+ * Extended tools not in CORE_TOOLS — variables, vector ops, analysis,+ * codegen, advanced structure, path manipulation, etc.+ */+export const EXTENDED_TOOLS: ToolDef[] = [+ // Read (advanced)+ getPageTree,+ getCurrentPage,+ listPages,+ selectNodes,+ queryNodes,+ getComponents,+ switchPage,+ pageBounds,+ listFonts,+ listAvailableFonts,+ diffJsx,+ // Create (advanced)+ createShape,+ searchIconsTool,+ insertIcon,+ fetchIconsTool,+ createComponent,+ createInstance,+ createPage,+ createVector,+ createSlice,+ // Modify (advanced)+ setEffects,+ setOpacity,+ setFont,+ setVisible,+ setConstraints,+ setRotation,+ setMinMax,+ setFontRange,+ setTextResize,+ setBlend,+ setLocked,+ setStrokeAlign,+ setImageFill,+ // Structure (advanced)+ cloneNode,+ nodeMove,+ renameNode,+ groupNodes,+ ungroupNode,+ flattenNodes,+ nodeToComponent,+ nodeBounds,+ nodeAncestors,+ nodeChildren,+ nodeTree,+ nodeBindings,+ nodeReplaceWith,+ arrangeNodes,+ // Variables+ listVariables,+ listCollections,+ getVariable,+ findVariables,+ createVariable,+ setVariable,+ deleteVariable,+ bindVariable,+ getCollection,+ createCollection,+ deleteCollection,+ // Vector & export+ booleanUnion,+ booleanSubtract,+ booleanIntersect,+ booleanExclude,+ pathGet,+ pathSet,+ pathScale,+ pathFlip,+ pathMove,+ viewportGet,+ viewportSet,+ exportSvg,+ exportImage,+ // Analyze & diff+ analyzeColors,+ analyzeTypography,+ analyzeSpacing,+ analyzeClusters,+ diffCreate,+ diffShow,+ // Codegen+ designToTokens,+ designToComponentMap,+]diff --git a/packages/core/src/tools/registry.ts b/packages/core/src/tools/registry.tsindex 3bf3ddcc8..5cbcc78dc 100644--- a/packages/core/src/tools/registry.ts+++ b/packages/core/src/tools/registry.ts@@ -1,248 +1,10 @@-import {- analyzeColors,- analyzeTypography,- analyzeSpacing,- analyzeClusters,- diffCreate,- diffShow,- evalCode-} from './analyze'-import { calc } from './calc'-import { designToTokens, designToComponentMap } from './codegen'-import {- createShape,- render,- createComponent,- createInstance,- createPage,- createVector,- createSlice,- fetchIconsTool,- insertIcon,- searchIconsTool-} from './create'-import { describe } from './describe'-import {- setFill,- setStroke,- setEffects,- updateNode,- setLayout,- setConstraints,- setRotation,- setOpacity,- setRadius,- setMinMax,- setText,- setFont,- setFontRange,- setTextResize,- setVisible,- setBlend,- setLocked,- setStrokeAlign,- setTextProperties,- setLayoutChild,- setImageFill-} from './modify'-import {- getSelection,- getPageTree,- getNode,- findNodes,- queryNodes,- getComponents,- listPages,- switchPage,- getCurrentPage,- pageBounds,- selectNodes,- listFonts,- listAvailableFonts,- getJsx,- diffJsx-} from './read'-import { stockPhoto } from './stock-photo'-import {- deleteNode,- cloneNode,- renameNode,- reparentNode,- groupNodes,- ungroupNode,- flattenNodes,- nodeToComponent,- nodeBounds,- nodeMove,- nodeResize,- nodeAncestors,- nodeChildren,- nodeTree,- nodeBindings,- nodeReplaceWith,- arrangeNodes,- batchUpdate-} from './structure'-import {- listVariables,- listCollections,- getVariable,- findVariables,- createVariable,- setVariable,- deleteVariable,- bindVariable,- getCollection,- createCollection,- deleteCollection-} from './variables'-import {- booleanUnion,- booleanSubtract,- booleanIntersect,- booleanExclude,- pathGet,- pathSet,- pathScale,- pathFlip,- pathMove,- viewportGet,- viewportSet,- viewportZoomToFit,- exportSvg,- exportImage-} from './vector'+import { CORE_TOOLS } from './registry-core'+import { EXTENDED_TOOLS } from './registry-extended'import type { ToolDef } from './schema'-/**- * Core tools registered by default in AI chat (~30 tools, ~3K schema tokens).- * Covers 90%+ of design sessions: render, describe, modify, structure, icons.- */-export const CORE_TOOLS: ToolDef[] = [- // Read- getSelection,- getNode,- findNodes,- getJsx,- // Create- render,- // Modify- updateNode,- setLayout,- setLayoutChild,- setRadius,- setFill,- setStroke,- setText,- setTextProperties,- // Structure- deleteNode,- reparentNode,- nodeResize,- batchUpdate,- // Stock photos- stockPhoto,- // Inspect & utility- describe,- calc,- evalCode,- viewportZoomToFit-]--/**- * Extended tools not in CORE_TOOLS — variables, vector ops, analysis,- * codegen, advanced structure, path manipulation, etc.- */-export const EXTENDED_TOOLS: ToolDef[] = [- // Read (advanced)- getPageTree,- getCurrentPage,- listPages,- selectNodes,- queryNodes,- getComponents,- switchPage,- pageBounds,- listFonts,- listAvailableFonts,- diffJsx,- // Create (advanced)- createShape,- searchIconsTool,- insertIcon,- fetchIconsTool,- createComponent,- createInstance,- createPage,- createVector,- createSlice,- // Modify (advanced)- setEffects,- setOpacity,- setFont,- setVisible,- setConstraints,- setRotation,- setMinMax,- setFontRange,- setTextResize,- setBlend,- setLocked,- setStrokeAlign,- setImageFill,- // Structure (advanced)- cloneNode,- nodeMove,- renameNode,- groupNodes,- ungroupNode,- flattenNodes,- nodeToComponent,- nodeBounds,- nodeAncestors,- nodeChildren,- nodeTree,- nodeBindings,- nodeReplaceWith,- arrangeNodes,- // Variables- listVariables,- listCollections,- getVariable,- findVariables,- createVariable,- setVariable,- deleteVariable,- bindVariable,- getCollection,- createCollection,- deleteCollection,- // Vector & export- booleanUnion,- booleanSubtract,- booleanIntersect,- booleanExclude,- pathGet,- pathSet,- pathScale,- pathFlip,- pathMove,- viewportGet,- viewportSet,- exportSvg,- exportImage,- // Analyze & diff- analyzeColors,- analyzeTypography,- analyzeSpacing,- analyzeClusters,- diffCreate,- diffShow,- // Codegen- designToTokens,- designToComponentMap-]+export { CORE_TOOLS } from './registry-core'+export { EXTENDED_TOOLS } from './registry-extended'/** All tools combined — used by MCP server and CLI. */export const ALL_TOOLS: ToolDef[] = [...CORE_TOOLS, ...EXTENDED_TOOLS]diff --git a/packages/core/src/tools/schema.ts b/packages/core/src/tools/schema.tsindex 83933971c..700f0e246 100644--- a/packages/core/src/tools/schema.ts+++ b/packages/core/src/tools/schema.ts@@ -6,7 +6,8 @@* and MCP (JSON Schema) are generated from these definitions.*/-import type { FigmaAPI, FigmaNodeProxy } from '../figma-api'+import type { FigmaAPI, FigmaNodeProxy } from '#core/figma-api'+import type { SceneNode } from '#core/scene-graph'export type ParamType = 'string' | 'number' | 'boolean' | 'color' | 'string[]'@@ -69,6 +70,18 @@ export function requireNode(figma: FigmaAPI, id: string): ReturnType<FigmaAPI['greturn node}+export function nodeNotFound(id: string): { error: string } {+ return { error: `Node "${id}" not found` }+}++export function getRawNodeOrError(+ figma: FigmaAPI,+ id: string+): { node: SceneNode } | { error: string } {+ const node = figma.graph.getNode(id)+ return node ? { node } : nodeNotFound(id)+}+export function nodeToResult(node: FigmaNodeProxy, maxDepth?: number): Record<string, unknown> {return node.toJSON(maxDepth)}diff --git a/packages/core/src/tools/stock-photo.ts b/packages/core/src/tools/stock-photo.tsindex 282bc58e7..262e6ccb2 100644--- a/packages/core/src/tools/stock-photo.ts+++ b/packages/core/src/tools/stock-photo.ts@@ -1,232 +1,19 @@import { defineTool } from './schema'--import type { FigmaAPI } from '../figma-api'--export interface StockPhotoResult {- url: string- width: number- height: number- photographer: string- sourceId: string-}--export interface StockPhotoProvider {- name: string- search(- query: string,- options: {- perPage: number- orientation: 'landscape' | 'portrait' | 'square'- targetDim: number- }- ): Promise<StockPhotoResult[]>-}--const providers = new Map<string, StockPhotoProvider>()-let activeProviderId: string | null = null--export function registerStockPhotoProvider(provider: StockPhotoProvider): void {- providers.set(provider.name, provider)- if (!activeProviderId) activeProviderId = provider.name-}--export function setActiveStockPhotoProvider(name: string | null): void {- activeProviderId = name-}--export function getStockPhotoProviders(): string[] {- return [...providers.keys()]-}--function getActiveProvider(): StockPhotoProvider | null {- if (!activeProviderId) return null- return providers.get(activeProviderId) ?? null-}--// --- Pexels provider -----interface PexelsPhoto {- id: number- width: number- height: number- photographer: string- src: {- original: string- large2x: string- large: string- medium: string- small: string- landscape: string- }-}--function pickPexelsSize(src: PexelsPhoto['src'], targetDim: number): string {- if (targetDim <= 200) return src.small- if (targetDim <= 400) return src.medium- if (targetDim <= 800) return src.large- if (targetDim <= 1600) return src.large2x- return src.original-}--let pexelsApiKey: string | null = null--export function setPexelsApiKey(key: string | null): void {- pexelsApiKey = key- if (key) {- registerStockPhotoProvider(pexelsProvider)- setActiveStockPhotoProvider('pexels')- }-}--const pexelsProvider: StockPhotoProvider = {- name: 'pexels',- async search(query, { perPage, orientation, targetDim }) {- if (!pexelsApiKey) throw new Error('Pexels API key not configured')- const url = `https://api.pexels.com/v1/search?query=${encodeURIComponent(query)}&per_page=${perPage}&orientation=${orientation}`- const resp = await fetch(url, { headers: { Authorization: pexelsApiKey } })- if (!resp.ok) throw new Error(`Pexels ${resp.status}`)- const data = (await resp.json()) as { photos: PexelsPhoto[] }- return data.photos.map((p) => ({- url: pickPexelsSize(p.src, targetDim),- width: p.width,- height: p.height,- photographer: p.photographer,- sourceId: String(p.id)- }))- }-}--// --- Unsplash provider -----let unsplashAccessKey: string | null = null--export function setUnsplashAccessKey(key: string | null): void {- unsplashAccessKey = key- if (key) {- registerStockPhotoProvider(unsplashProvider)- }-}--interface UnsplashPhoto {- id: string- width: number- height: number- urls: { raw: string; full: string; regular: string; small: string; thumb: string }- user: { name: string }- links: { download_location: string }-}--function pickUnsplashSize(urls: UnsplashPhoto['urls'], targetDim: number): string {- if (targetDim <= 200) return urls.thumb- if (targetDim <= 400) return urls.small- if (targetDim <= 1080) return urls.regular- return urls.full-}--const unsplashProvider: StockPhotoProvider = {- name: 'unsplash',- async search(query, { perPage, orientation }) {- if (!unsplashAccessKey) throw new Error('Unsplash access key not configured')- const orient = orientation === 'square' ? 'squarish' : orientation- const url = `https://api.unsplash.com/search/photos?query=${encodeURIComponent(query)}&per_page=${perPage}&orientation=${orient}`- const resp = await fetch(url, {- headers: {- Authorization: `Client-ID ${unsplashAccessKey}`,- 'Accept-Version': 'v1'- }- })- if (!resp.ok) throw new Error(`Unsplash ${resp.status}`)- const data = (await resp.json()) as { results: UnsplashPhoto[] }- return data.results.map((p) => ({- url: pickUnsplashSize(p.urls, 1080),- width: p.width,- height: p.height,- photographer: p.user.name,- sourceId: p.id- }))- }-}--// --- Tool -----interface PhotoRequest {- id: string- query: string- index?: number- orientation?: 'landscape' | 'portrait' | 'square'-}--interface PhotoResult {- id: string- photo?: {- sourceId: string- photographer: string- width: number- height: number- provider: string- }- error?: string-}--async function applyPhoto(- figma: FigmaAPI,- provider: StockPhotoProvider,- req: PhotoRequest-): Promise<PhotoResult> {- const node = figma.getNodeById(req.id)- if (!node) return { id: req.id, error: 'Not found' }-- const children = 'children' in node ? (node as { children: unknown[] }).children : []- if (children.length > 0) {- return { id: req.id, error: `"${node.name}" has children — use a leaf shape` }- }-- const perPage = Math.min((req.index ?? 0) + 3, 15)- const orientation = req.orientation ?? 'landscape'- const targetDim = Math.max(node.width, node.height)-- let results: StockPhotoResult[]- try {- results = await provider.search(req.query, { perPage, orientation, targetDim })- } catch (err) {- return { id: req.id, error: err instanceof Error ? err.message : String(err) }- }-- if (results.length === 0) return { id: req.id, error: `No photos for "${req.query}"` }- const photo = results[Math.min(req.index ?? 0, results.length - 1)]-- let imageBytes: Uint8Array- try {- const imgResp = await fetch(photo.url)- if (!imgResp.ok) return { id: req.id, error: `Download ${imgResp.status}` }- imageBytes = new Uint8Array(await imgResp.arrayBuffer())- } catch (err) {- return { id: req.id, error: `Download: ${err instanceof Error ? err.message : String(err)}` }- }-- const image = figma.createImage(imageBytes)- node.fills = [- {- type: 'IMAGE',- color: { r: 1, g: 1, b: 1, a: 1 },- imageHash: image.hash,- imageScaleMode: 'FILL',- visible: true,- opacity: 1- }- ]-- return {- id: node.id,- photo: {- sourceId: photo.sourceId,- photographer: photo.photographer,- width: photo.width,- height: photo.height,- provider: provider.name- }- }-}+import { applyPhoto } from './stock-photo/apply'+import { getActiveProvider } from './stock-photo/providers'+import { parsePhotoRequests } from './stock-photo/requests'++export { applyPhoto, type PhotoRequest, type PhotoResult } from './stock-photo/apply'+export { parsePhotoRequests } from './stock-photo/requests'+export {+ getStockPhotoProviders,+ registerStockPhotoProvider,+ setActiveStockPhotoProvider,+ setPexelsApiKey,+ setUnsplashAccessKey,+ type StockPhotoProvider,+ type StockPhotoResult,+} from './stock-photo/providers'export const stockPhoto = defineTool({name: 'stock_photo',@@ -239,30 +26,23 @@ export const stockPhoto = defineTool({type: 'string',description:'JSON array: [{"id":"0:5","query":"mountain sunset"},{"id":"0:8","query":"business team","orientation":"square"}]',- required: true- }+ required: true,+ },},execute: async (figma, { requests }) => {const provider = getActiveProvider()if (!provider) {return {- error: `No stock photo provider configured. Ask the user to add an API key in AI chat settings. Available providers: Pexels, Unsplash.`+ error: `No stock photo provider configured. Ask the user to add an API key in AI chat settings. Available providers: Pexels, Unsplash.`,}}- let reqs: PhotoRequest[]- try {- const parsed = JSON.parse(String(requests))- reqs = Array.isArray(parsed) ? parsed : [parsed]- } catch {- return { error: 'Invalid JSON in requests' }- }-- if (reqs.length === 0) return { error: 'Empty requests array' }+ const reqs = parsePhotoRequests(requests)+ if ('error' in reqs) return reqs- const results = await Promise.all(reqs.map((r) => applyPhoto(figma, provider, r)))- const ok = results.filter((r) => r.photo).length+ const results = await Promise.all(reqs.map((request) => applyPhoto(figma, provider, request)))+ const ok = results.filter((result) => result.photo).lengthreturn { applied: ok, failed: results.length - ok, provider: provider.name, results }- }+ },})diff --git a/packages/core/src/tools/stock-photo/apply.ts b/packages/core/src/tools/stock-photo/apply.tsnew file mode 100644index 000000000..83181a33b--- /dev/null+++ b/packages/core/src/tools/stock-photo/apply.ts@@ -0,0 +1,81 @@+import type { FigmaAPI } from '#core/figma-api'+import type { StockPhotoProvider, StockPhotoResult } from './providers'++export interface PhotoRequest {+ id: string+ query: string+ index?: number+ orientation?: 'landscape' | 'portrait' | 'square'+}++export interface PhotoResult {+ id: string+ photo?: {+ sourceId: string+ photographer: string+ width: number+ height: number+ provider: string+ }+ error?: string+}++export async function applyPhoto(+ figma: FigmaAPI,+ provider: StockPhotoProvider,+ req: PhotoRequest+): Promise<PhotoResult> {+ const node = figma.getNodeById(req.id)+ if (!node) return { id: req.id, error: 'Not found' }++ const children = 'children' in node ? (node as { children: unknown[] }).children : []+ if (children.length > 0) {+ return { id: req.id, error: `"${node.name}" has children — use a leaf shape` }+ }++ const perPage = Math.min((req.index ?? 0) + 3, 15)+ const orientation = req.orientation ?? 'landscape'+ const targetDim = Math.max(node.width, node.height)++ let results: StockPhotoResult[]+ try {+ results = await provider.search(req.query, { perPage, orientation, targetDim })+ } catch (err) {+ return { id: req.id, error: err instanceof Error ? err.message : String(err) }+ }++ if (results.length === 0) return { id: req.id, error: `No photos for "${req.query}"` }+ const photo = results[Math.min(req.index ?? 0, results.length - 1)]++ let imageBytes: Uint8Array+ try {+ const response = await fetch(photo.url)+ if (!response.ok) return { id: req.id, error: `Download ${response.status}` }+ imageBytes = new Uint8Array(await response.arrayBuffer())+ } catch (err) {+ return { id: req.id, error: `Download: ${err instanceof Error ? err.message : String(err)}` }+ }++ const image = figma.createImage(imageBytes)+ node.fills = [+ {+ type: 'IMAGE',+ color: { r: 1, g: 1, b: 1, a: 1 },+ imageHash: image.hash,+ imageScaleMode: 'FILL',+ visible: true,+ opacity: 1,+ },+ ]++ return {+ id: node.id,+ photo: {+ sourceId: photo.sourceId,+ photographer: photo.photographer,+ width: photo.width,+ height: photo.height,+ provider: provider.name,+ },+ }+}diff --git a/packages/core/src/tools/stock-photo/providers.ts b/packages/core/src/tools/stock-photo/providers.tsnew file mode 100644index 000000000..74aedcbff--- /dev/null+++ b/packages/core/src/tools/stock-photo/providers.ts@@ -0,0 +1,140 @@+export interface StockPhotoResult {+ url: string+ width: number+ height: number+ photographer: string+ sourceId: string+}++export interface StockPhotoProvider {+ name: string+ search(+ query: string,+ options: {+ perPage: number+ orientation: 'landscape' | 'portrait' | 'square'+ targetDim: number+ }+ ): Promise<StockPhotoResult[]>+}++const providers = new Map<string, StockPhotoProvider>()+let activeProviderId: string | null = null++export function registerStockPhotoProvider(provider: StockPhotoProvider): void {+ providers.set(provider.name, provider)+ if (!activeProviderId) activeProviderId = provider.name+}++export function setActiveStockPhotoProvider(name: string | null): void {+ activeProviderId = name+}++export function getStockPhotoProviders(): string[] {+ return [...providers.keys()]+}++export function getActiveProvider(): StockPhotoProvider | null {+ if (!activeProviderId) return null+ return providers.get(activeProviderId) ?? null+}++interface PexelsPhoto {+ id: number+ width: number+ height: number+ photographer: string+ src: {+ original: string+ large2x: string+ large: string+ medium: string+ small: string+ landscape: string+ }+}++function pickPexelsSize(src: PexelsPhoto['src'], targetDim: number): string {+ if (targetDim <= 200) return src.small+ if (targetDim <= 400) return src.medium+ if (targetDim <= 800) return src.large+ if (targetDim <= 1600) return src.large2x+ return src.original+}++let pexelsApiKey: string | null = null++export function setPexelsApiKey(key: string | null): void {+ pexelsApiKey = key+ if (key) {+ registerStockPhotoProvider(pexelsProvider)+ setActiveStockPhotoProvider('pexels')+ }+}++const pexelsProvider: StockPhotoProvider = {+ name: 'pexels',+ async search(query, { perPage, orientation, targetDim }) {+ if (!pexelsApiKey) throw new Error('Pexels API key not configured')+ const url = `https://api.pexels.com/v1/search?query=${encodeURIComponent(query)}&per_page=${perPage}&orientation=${orientation}`+ const resp = await fetch(url, { headers: { Authorization: pexelsApiKey } })+ if (!resp.ok) throw new Error(`Pexels ${resp.status}`)+ const data = (await resp.json()) as { photos: PexelsPhoto[] }+ return data.photos.map((photo) => ({+ url: pickPexelsSize(photo.src, targetDim),+ width: photo.width,+ height: photo.height,+ photographer: photo.photographer,+ sourceId: String(photo.id),+ }))+ },+}++let unsplashAccessKey: string | null = null++export function setUnsplashAccessKey(key: string | null): void {+ unsplashAccessKey = key+ if (key) {+ registerStockPhotoProvider(unsplashProvider)+ }+}++interface UnsplashPhoto {+ id: string+ width: number+ height: number+ urls: { raw: string; full: string; regular: string; small: string; thumb: string }+ user: { name: string }+ links: { download_location: string }+}++function pickUnsplashSize(urls: UnsplashPhoto['urls'], targetDim: number): string {+ if (targetDim <= 200) return urls.thumb+ if (targetDim <= 400) return urls.small+ if (targetDim <= 1080) return urls.regular+ return urls.full+}++const unsplashProvider: StockPhotoProvider = {+ name: 'unsplash',+ async search(query, { perPage, orientation }) {+ if (!unsplashAccessKey) throw new Error('Unsplash access key not configured')+ const orient = orientation === 'square' ? 'squarish' : orientation+ const url = `https://api.unsplash.com/search/photos?query=${encodeURIComponent(query)}&per_page=${perPage}&orientation=${orient}`+ const resp = await fetch(url, {+ headers: {+ Authorization: `Client-ID ${unsplashAccessKey}`,+ 'Accept-Version': 'v1',+ },+ })+ if (!resp.ok) throw new Error(`Unsplash ${resp.status}`)+ const data = (await resp.json()) as { results: UnsplashPhoto[] }+ return data.results.map((photo) => ({+ url: pickUnsplashSize(photo.urls, 1080),+ width: photo.width,+ height: photo.height,+ photographer: photo.user.name,+ sourceId: photo.id,+ }))+ },+}diff --git a/packages/core/src/tools/stock-photo/requests.ts b/packages/core/src/tools/stock-photo/requests.tsnew file mode 100644index 000000000..ca6763732--- /dev/null+++ b/packages/core/src/tools/stock-photo/requests.ts@@ -0,0 +1,14 @@+import type { PhotoRequest } from './apply'++export function parsePhotoRequests(value: unknown): PhotoRequest[] | { error: string } {+ let parsed: unknown+ try {+ parsed = JSON.parse(String(value))+ } catch {+ return { error: 'Invalid JSON in requests' }+ }++ const requests = Array.isArray(parsed) ? parsed : [parsed]+ if (requests.length === 0) return { error: 'Empty requests array' }+ return requests as PhotoRequest[]+}diff --git a/packages/core/src/tools/structure.ts b/packages/core/src/tools/structure.tsindex 0f73aa654..574f77345 100644--- a/packages/core/src/tools/structure.ts+++ b/packages/core/src/tools/structure.ts@@ -1,481 +1,10 @@-import { defineTool, nodeSummary } from './schema'+export { cloneNode, deleteNode, nodeBounds, nodeMove, nodeResize, renameNode } from './structure/basic'+export { flattenNodes, groupNodes, nodeToComponent, reparentNode, ungroupNode } from './structure/hierarchy'-import type { FigmaNodeProxy } from '../figma-api'+export { nodeAncestors, nodeBindings, nodeChildren, nodeTree } from './structure/tree'-export const deleteNode = defineTool({- name: 'delete_node',- mutates: true,- description: 'Delete a node by ID.',- params: {- id: { type: 'string', description: 'Node ID to delete', required: true }- },- execute: (figma, { id }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- node.remove()- return { deleted: id }- }-})+export { nodeReplaceWith } from './structure/replace'-export const cloneNode = defineTool({- name: 'clone_node',- mutates: true,- description: 'Clone (duplicate) a node.',- params: {- id: { type: 'string', description: 'Node ID to clone', required: true }- },- execute: (figma, { id }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- const clone = node.clone()- return nodeSummary(clone)- }-})+export { arrangeNodes } from './structure/arrange'-export const renameNode = defineTool({- name: 'rename_node',- mutates: true,- description: 'Rename a node in the layers panel.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- name: { type: 'string', description: 'New name', required: true }- },- execute: (figma, { id, name }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- node.name = name- return { id, name }- }-})--export const reparentNode = defineTool({- name: 'reparent_node',- mutates: true,- description: 'Move a node into a different parent.',- params: {- id: { type: 'string', description: 'Node ID to move', required: true },- parent_id: { type: 'string', description: 'New parent node ID', required: true }- },- execute: (figma, { id, parent_id }) => {- const node = figma.getNodeById(id)- const parent = figma.getNodeById(parent_id)- if (!node) return { error: `Node "${id}" not found` }- if (!parent) return { error: `Parent "${parent_id}" not found` }- parent.appendChild(node)- return { id, parent_id }- }-})--export const groupNodes = defineTool({- name: 'group_nodes',- mutates: true,- description: 'Group selected nodes.',- params: {- ids: { type: 'string[]', description: 'Node IDs to group', required: true }- },- execute: (figma, { ids }) => {- const nodes = ids- .map((id) => figma.getNodeById(id))- .filter((n): n is FigmaNodeProxy => n !== null)- if (nodes.length < 2) return { error: 'Need at least 2 nodes to group' }- const parent = nodes[0].parent ?? figma.currentPage- const group = figma.group(nodes, parent)- return nodeSummary(group)- }-})--export const ungroupNode = defineTool({- name: 'ungroup_node',- mutates: true,- description: 'Ungroup a group node.',- params: {- id: { type: 'string', description: 'Group node ID', required: true }- },- execute: (figma, { id }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- figma.ungroup(node)- return { ungrouped: id }- }-})--export const flattenNodes = defineTool({- name: 'flatten_nodes',- mutates: true,- description: 'Flatten nodes into a single vector.',- params: {- ids: { type: 'string[]', description: 'Node IDs to flatten', required: true }- },- execute: (figma, { ids }) => {- const result = figma.flattenNode(ids)- return nodeSummary(result)- }-})--export const nodeToComponent = defineTool({- name: 'node_to_component',- mutates: true,- description: 'Convert one or more frames/groups into components.',- params: {- ids: { type: 'string[]', description: 'Node IDs to convert', required: true }- },- execute: (figma, { ids }) => {- const results: { id: string; name: string; originalId: string }[] = []- for (const id of ids) {- const node = figma.getNodeById(id)- if (!node) continue- const comp = figma.createComponentFromNode(node)- results.push({ id: comp.id, name: comp.name, originalId: id })- }- return { converted: results }- }-})--export const nodeBounds = defineTool({- name: 'node_bounds',- description: 'Get absolute bounding box of a node.',- params: {- id: { type: 'string', description: 'Node ID', required: true }- },- execute: (figma, { id }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- return { id, bounds: node.absoluteBoundingBox }- }-})--export const nodeMove = defineTool({- name: 'node_move',- mutates: true,- description: 'Move a node to new coordinates.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- x: { type: 'number', description: 'X position', required: true },- y: { type: 'number', description: 'Y position', required: true }- },- execute: (figma, { id, x, y }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- node.x = x- node.y = y- return { id, x, y }- }-})--export const nodeResize = defineTool({- name: 'node_resize',- mutates: true,- description: 'Resize a node.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- width: { type: 'number', description: 'Width', required: true, min: 1 },- height: { type: 'number', description: 'Height', required: true, min: 1 }- },- execute: (figma, { id, width, height }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- node.resize(width, height)- return { id, width, height }- }-})--export const nodeAncestors = defineTool({- name: 'node_ancestors',- description: 'Get the ancestor chain from a node to the page root.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- depth: { type: 'number', description: 'Max depth to traverse' }- },- execute: (figma, args) => {- const node = figma.getNodeById(args.id)- if (!node) return { error: `Node "${args.id}" not found` }- const ancestors: { id: string; name: string; type: string }[] = []- let current = node.parent- let d = 0- while (current && (!args.depth || d < args.depth)) {- ancestors.push(nodeSummary(current))- current = current.parent- d++- }- return { id: args.id, ancestors }- }-})--export const nodeChildren = defineTool({- name: 'node_children',- description: 'Get direct children of a node.',- params: {- id: { type: 'string', description: 'Node ID', required: true }- },- execute: (figma, { id }) => {- const node = figma.getNodeById(id)- if (!node) return { error: `Node "${id}" not found` }- return {- id,- children: node.children.map(nodeSummary)- }- }-})--export const nodeTree = defineTool({- name: 'node_tree',- description: 'Get a node tree with types and hierarchy.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- depth: { type: 'number', description: 'Max depth (default: unlimited)' }- },- execute: (figma, args) => {- const node = figma.getNodeById(args.id)- if (!node) return { error: `Node "${args.id}" not found` }- function buildTree(n: FigmaNodeProxy, d: number): Record<string, unknown> {- const result: Record<string, unknown> = { id: n.id, name: n.name, type: n.type }- if (args.depth === undefined || d < args.depth) {- const kids = n.children- if (kids.length > 0) result.children = kids.map((c) => buildTree(c, d + 1))- }- return result- }- return buildTree(node, 0)- }-})--export const nodeBindings = defineTool({- name: 'node_bindings',- description: 'Get variable bindings for a node.',- params: {- id: { type: 'string', description: 'Node ID', required: true }- },- execute: (figma, { id }) => {- const raw = figma.graph.getNode(id)- if (!raw) return { error: `Node "${id}" not found` }- return { id, bindings: raw.boundVariables }- }-})--export const nodeReplaceWith = defineTool({- name: 'node_replace_with',- mutates: true,- description: 'Replace a node with JSX content.',- params: {- id: { type: 'string', description: 'Node ID to replace', required: true },- jsx: { type: 'string', description: 'JSX string for the replacement', required: true }- },- execute: async (figma, args) => {- const node = figma.getNodeById(args.id)- if (!node) return { error: `Node "${args.id}" not found` }- const parentId = node.parent?.id ?? figma.currentPageId- const x = node.x- const y = node.y- node.remove()- const { renderJSX } = await import('../design-jsx/render.js')- const results = await renderJSX(figma.graph, args.jsx, { parentId, x, y })- const result = results[0]- return {- id: result.id,- name: result.name,- type: result.type,- children: results.slice(1).map((r) => ({ id: r.id, name: r.name, type: r.type }))- }- }-})--export const arrangeNodes = defineTool({- name: 'arrange',- mutates: true,- description:- 'Arrange top-level nodes on the canvas in a grid, row, or column layout. Useful after batch creation to tidy up overlapping frames.',- params: {- ids: { type: 'string[]', description: 'Node IDs to arrange (default: all top-level children)' },- mode: {- type: 'string',- description: 'Layout mode',- enum: ['grid', 'row', 'column'],- default: 'grid'- },- gap: { type: 'number', description: 'Spacing between nodes (default: 40)' },- cols: { type: 'number', description: 'Column count for grid mode (default: auto)' }- },- execute: (figma, args) => {- const gap = args.gap ?? 40- const mode = args.mode ?? 'grid'- const page = figma.currentPage-- let nodes: FigmaNodeProxy[]- if (args.ids && args.ids.length > 0) {- nodes = args.ids- .map((id) => figma.getNodeById(id))- .filter((n): n is FigmaNodeProxy => n !== null)- } else {- nodes = [...page.children]- }-- if (nodes.length === 0) return { error: 'No nodes to arrange' }- const first = nodes[0]-- if (mode === 'row') {- let x = first.x- const y = first.y- for (const node of nodes) {- node.x = x- node.y = y- x += node.width + gap- }- } else if (mode === 'column') {- const x = first.x- let y = first.y- for (const node of nodes) {- node.x = x- node.y = y- y += node.height + gap- }- } else {- const cols = args.cols ?? Math.ceil(Math.sqrt(nodes.length))- const startX = first.x- let x = startX- let y = first.y- let rowHeight = 0-- for (let i = 0; i < nodes.length; i++) {- const node = nodes[i]- if (i > 0 && i % cols === 0) {- x = startX- y += rowHeight + gap- rowHeight = 0- }- node.x = x- node.y = y- x += node.width + gap- rowHeight = Math.max(rowHeight, node.height)- }- }-- return { arranged: nodes.length, mode }- }-})--interface BatchOp {- id: string- props: Record<string, unknown>-}--function str(v: unknown): string {- return typeof v === 'string' ? v : ''-}-function num(v: unknown): number {- return typeof v === 'number' ? v : 0-}--function applyBatchProps(node: FigmaNodeProxy, p: Record<string, unknown>): string[] {- const updated: string[] = []-- if (p.spacing !== undefined) {- node.itemSpacing = num(p.spacing)- updated.push('spacing')- }- if (p.padding !== undefined) {- const v = num(p.padding)- node.paddingTop = v- node.paddingRight = v- node.paddingBottom = v- node.paddingLeft = v- updated.push('padding')- }- if (p.padding_horizontal !== undefined) {- node.paddingLeft = num(p.padding_horizontal)- node.paddingRight = num(p.padding_horizontal)- updated.push('padding_horizontal')- }- if (p.padding_vertical !== undefined) {- node.paddingTop = num(p.padding_vertical)- node.paddingBottom = num(p.padding_vertical)- updated.push('padding_vertical')- }- if (p.counter_align !== undefined) {- node.counterAxisAlignItems = str(p.counter_align)- updated.push('counter_align')- }- if (p.align !== undefined) {- node.primaryAxisAlignItems = str(p.align)- updated.push('align')- }- if (p.sizing_horizontal !== undefined) {- node.layoutSizingHorizontal = str(p.sizing_horizontal)- updated.push('sizing_horizontal')- }- if (p.sizing_vertical !== undefined) {- node.layoutSizingVertical = str(p.sizing_vertical)- updated.push('sizing_vertical')- }- if (p.grow !== undefined) {- node.layoutGrow = num(p.grow)- updated.push('grow')- }- if (p.name !== undefined) {- node.name = str(p.name)- updated.push('name')- }- if (p.visible !== undefined) {- node.visible = Boolean(p.visible)- updated.push('visible')- }- if (p.corner_radius !== undefined) {- node.cornerRadius = num(p.corner_radius)- updated.push('corner_radius')- }- if (p.opacity !== undefined) {- node.opacity = num(p.opacity)- updated.push('opacity')- }- if (p.auto_resize !== undefined) {- node.textAutoResize = str(p.auto_resize)- updated.push('auto_resize')- }- if (p.direction !== undefined) {- node.layoutMode = str(p.direction) as 'HORIZONTAL' | 'VERTICAL'- updated.push('direction')- }-- return updated-}--export const batchUpdate = defineTool({- name: 'batch_update',- mutates: true,- description:- 'Execute multiple modifications in one call. Each operation is {id, props} where props can include: spacing, padding, padding_horizontal, padding_vertical, counter_align, sizing_horizontal, sizing_vertical, grow, name, visible, corner_radius, auto_resize (for text), direction. Runs all updates with one layout recompute.',- params: {- operations: {- type: 'string',- description:- 'JSON array: [{"id":"0:5","props":{"spacing":8}},{"id":"0:6","props":{"sizing_horizontal":"FILL","grow":1}}]',- required: true- }- },- execute: (figma, { operations }) => {- let ops: BatchOp[]- try {- ops = JSON.parse(String(operations))- } catch {- return { error: 'Invalid JSON in operations' }- }- if (!Array.isArray(ops)) return { error: 'operations must be a JSON array' }-- const results: Array<{ id: string; updated: string[] }> = []- const errors: string[] = []-- for (const op of ops) {- const node = figma.getNodeById(op.id)- if (!node) {- errors.push(`Node "${op.id}" not found`)- continue- }- const updated = applyBatchProps(node, op.props)- if (updated.length > 0) results.push({ id: op.id, updated })- }-- const out: Record<string, unknown> = { updated: results.length }- if (results.length > 0) out.results = results- if (errors.length > 0) out.errors = errors- return out- }-})+export { batchUpdate } from './structure/batch'diff --git a/packages/core/src/tools/structure/arrange.ts b/packages/core/src/tools/structure/arrange.tsnew file mode 100644index 000000000..10a075be0--- /dev/null+++ b/packages/core/src/tools/structure/arrange.ts@@ -0,0 +1,85 @@+import { defineTool } from '#core/tools/schema'++import type { FigmaNodeProxy } from '#core/figma-api'++export const arrangeNodes = defineTool({+ name: 'arrange',+ mutates: true,+ description:+ 'Arrange top-level nodes on the canvas in a grid, row, or column layout. Useful after batch creation to tidy up overlapping frames.',+ params: {+ ids: { type: 'string[]', description: 'Node IDs to arrange (default: all top-level children)' },+ mode: {+ type: 'string',+ description: 'Layout mode',+ enum: ['grid', 'row', 'column'],+ default: 'grid',+ },+ gap: { type: 'number', description: 'Spacing between nodes (default: 40)' },+ cols: { type: 'number', description: 'Column count for grid mode (default: auto)' },+ },+ execute: (figma, args) => {+ const gap = args.gap ?? 40+ const mode = args.mode ?? 'grid'+ const page = figma.currentPage++ let nodes: FigmaNodeProxy[]+ if (args.ids && args.ids.length > 0) {+ nodes = args.ids+ .map((id) => figma.getNodeById(id))+ .filter((node): node is FigmaNodeProxy => node !== null)+ } else {+ nodes = [...page.children]+ }++ if (nodes.length === 0) return { error: 'No nodes to arrange' }+ const first = nodes[0]++ if (mode === 'row') {+ arrangeRow(nodes, first.x, first.y, gap)+ } else if (mode === 'column') {+ arrangeColumn(nodes, first.x, first.y, gap)+ } else {+ arrangeGrid(nodes, first.x, first.y, args.cols ?? Math.ceil(Math.sqrt(nodes.length)), gap)+ }++ return { arranged: nodes.length, mode }+ },+})++function arrangeRow(nodes: FigmaNodeProxy[], startX: number, y: number, gap: number) {+ let x = startX+ for (const node of nodes) {+ node.x = x+ node.y = y+ x += node.width + gap+ }+}++function arrangeColumn(nodes: FigmaNodeProxy[], x: number, startY: number, gap: number) {+ let y = startY+ for (const node of nodes) {+ node.x = x+ node.y = y+ y += node.height + gap+ }+}++function arrangeGrid(nodes: FigmaNodeProxy[], startX: number, startY: number, cols: number, gap: number) {+ let x = startX+ let y = startY+ let rowHeight = 0++ for (let index = 0; index < nodes.length; index++) {+ const node = nodes[index]+ if (index > 0 && index % cols === 0) {+ x = startX+ y += rowHeight + gap+ rowHeight = 0+ }+ node.x = x+ node.y = y+ x += node.width + gap+ rowHeight = Math.max(rowHeight, node.height)+ }+}diff --git a/packages/core/src/tools/structure/basic.ts b/packages/core/src/tools/structure/basic.tsnew file mode 100644index 000000000..6baec7c34--- /dev/null+++ b/packages/core/src/tools/structure/basic.ts@@ -0,0 +1,95 @@+import { defineTool, nodeNotFound, nodeSummary } from '#core/tools/schema'++export const deleteNode = defineTool({+ name: 'delete_node',+ mutates: true,+ description: 'Delete a node by ID.',+ params: {+ id: { type: 'string', description: 'Node ID to delete', required: true },+ },+ execute: (figma, { id }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ node.remove()+ return { deleted: id }+ },+})++export const cloneNode = defineTool({+ name: 'clone_node',+ mutates: true,+ description: 'Clone (duplicate) a node.',+ params: {+ id: { type: 'string', description: 'Node ID to clone', required: true },+ },+ execute: (figma, { id }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ const clone = node.clone()+ return nodeSummary(clone)+ },+})++export const renameNode = defineTool({+ name: 'rename_node',+ mutates: true,+ description: 'Rename a node in the layers panel.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ name: { type: 'string', description: 'New name', required: true },+ },+ execute: (figma, { id, name }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ node.name = name+ return { id, name }+ },+})++export const nodeBounds = defineTool({+ name: 'node_bounds',+ description: 'Get absolute bounding box of a node.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ },+ execute: (figma, { id }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ return { id, bounds: node.absoluteBoundingBox }+ },+})++export const nodeMove = defineTool({+ name: 'node_move',+ mutates: true,+ description: 'Move a node to new coordinates.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ x: { type: 'number', description: 'X position', required: true },+ y: { type: 'number', description: 'Y position', required: true },+ },+ execute: (figma, { id, x, y }) => {+ const node = figma.getNodeById(id)+ if (!node) return nodeNotFound(id)+ node.x = x+ node.y = y+ return { id, x, y }+ },+})++export const nodeResize = defineTool({+ name: 'node_resize',+ mutates: true,+ description: 'Resize a node.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ width: { type: 'number', description: 'Width', required: true, min: 1 },+ height: { type: 'number', description: 'Height', required: true, min: 1 },+ },+ execute: (figma, { id, width, height }) => {+ const node = figma.getNodeById(id)+ if (!node) return nodeNotFound(id)+ node.resize(width, height)+ return { id, width, height }+ },+})diff --git a/packages/core/src/tools/structure/batch.ts b/packages/core/src/tools/structure/batch.tsnew file mode 100644index 000000000..d625dc8ae--- /dev/null+++ b/packages/core/src/tools/structure/batch.ts@@ -0,0 +1,131 @@+import { defineTool } from '#core/tools/schema'++import type { FigmaNodeProxy } from '#core/figma-api'++interface BatchOp {+ id: string+ props: Record<string, unknown>+}++function str(value: unknown): string {+ return typeof value === 'string' ? value : ''+}++function num(value: unknown): number {+ return typeof value === 'number' ? value : 0+}++function applyBatchProps(node: FigmaNodeProxy, props: Record<string, unknown>): string[] {+ const updated: string[] = []++ if (props.spacing !== undefined) {+ node.itemSpacing = num(props.spacing)+ updated.push('spacing')+ }+ if (props.padding !== undefined) {+ const value = num(props.padding)+ node.paddingTop = value+ node.paddingRight = value+ node.paddingBottom = value+ node.paddingLeft = value+ updated.push('padding')+ }+ if (props.padding_horizontal !== undefined) {+ node.paddingLeft = num(props.padding_horizontal)+ node.paddingRight = num(props.padding_horizontal)+ updated.push('padding_horizontal')+ }+ if (props.padding_vertical !== undefined) {+ node.paddingTop = num(props.padding_vertical)+ node.paddingBottom = num(props.padding_vertical)+ updated.push('padding_vertical')+ }+ if (props.counter_align !== undefined) {+ node.counterAxisAlignItems = str(props.counter_align)+ updated.push('counter_align')+ }+ if (props.align !== undefined) {+ node.primaryAxisAlignItems = str(props.align)+ updated.push('align')+ }+ if (props.sizing_horizontal !== undefined) {+ node.layoutSizingHorizontal = str(props.sizing_horizontal)+ updated.push('sizing_horizontal')+ }+ if (props.sizing_vertical !== undefined) {+ node.layoutSizingVertical = str(props.sizing_vertical)+ updated.push('sizing_vertical')+ }+ if (props.grow !== undefined) {+ node.layoutGrow = num(props.grow)+ updated.push('grow')+ }+ if (props.name !== undefined) {+ node.name = str(props.name)+ updated.push('name')+ }+ if (props.visible !== undefined) {+ node.visible = Boolean(props.visible)+ updated.push('visible')+ }+ if (props.corner_radius !== undefined) {+ node.cornerRadius = num(props.corner_radius)+ updated.push('corner_radius')+ }+ if (props.opacity !== undefined) {+ node.opacity = num(props.opacity)+ updated.push('opacity')+ }+ if (props.auto_resize !== undefined) {+ node.textAutoResize = str(props.auto_resize)+ updated.push('auto_resize')+ }+ if (props.direction !== undefined) {+ node.layoutMode = str(props.direction) as 'HORIZONTAL' | 'VERTICAL'+ updated.push('direction')+ }++ return updated+}++export const batchUpdate = defineTool({+ name: 'batch_update',+ mutates: true,+ description:+ 'Execute multiple modifications in one call. Each operation is {id, props} where props can include: spacing, padding, padding_horizontal, padding_vertical, counter_align, sizing_horizontal, sizing_vertical, grow, name, visible, corner_radius, auto_resize (for text), direction. Runs all updates with one layout recompute.',+ params: {+ operations: {+ type: 'string',+ description:+ 'JSON array: [{"id":"0:5","props":{"spacing":8}},{"id":"0:6","props":{"sizing_horizontal":"FILL","grow":1}}]',+ required: true,+ },+ },+ execute: (figma, { operations }) => {+ let ops: BatchOp[]+ try {+ ops = JSON.parse(String(operations))+ } catch {+ return { error: 'Invalid JSON in operations' }+ }+ if (!Array.isArray(ops)) return { error: 'operations must be a JSON array' }++ const results: Array<{ id: string; updated: string[] }> = []+ const errors: string[] = []++ for (const op of ops) {+ const node = figma.getNodeById(op.id)+ if (!node) {+ errors.push(`Node "${op.id}" not found`)+ continue+ }+ const updated = applyBatchProps(node, op.props)+ if (updated.length > 0) results.push({ id: op.id, updated })+ }++ const out: Record<string, unknown> = { updated: results.length }+ if (results.length > 0) out.results = results+ if (errors.length > 0) out.errors = errors+ return out+ },+})diff --git a/packages/core/src/tools/structure/hierarchy.ts b/packages/core/src/tools/structure/hierarchy.tsnew file mode 100644index 000000000..45e2a4daa--- /dev/null+++ b/packages/core/src/tools/structure/hierarchy.ts@@ -0,0 +1,86 @@+import { defineTool, nodeSummary } from '#core/tools/schema'++import type { FigmaNodeProxy } from '#core/figma-api'++export const reparentNode = defineTool({+ name: 'reparent_node',+ mutates: true,+ description: 'Move a node into a different parent.',+ params: {+ id: { type: 'string', description: 'Node ID to move', required: true },+ parent_id: { type: 'string', description: 'New parent node ID', required: true },+ },+ execute: (figma, { id, parent_id }) => {+ const node = figma.getNodeById(id)+ const parent = figma.getNodeById(parent_id)+ if (!node) return { error: `Node "${id}" not found` }+ if (!parent) return { error: `Parent "${parent_id}" not found` }+ parent.appendChild(node)+ return { id, parent_id }+ },+})++export const groupNodes = defineTool({+ name: 'group_nodes',+ mutates: true,+ description: 'Group selected nodes.',+ params: {+ ids: { type: 'string[]', description: 'Node IDs to group', required: true },+ },+ execute: (figma, { ids }) => {+ const nodes = ids+ .map((id) => figma.getNodeById(id))+ .filter((node): node is FigmaNodeProxy => node !== null)+ if (nodes.length < 2) return { error: 'Need at least 2 nodes to group' }+ const parent = nodes[0].parent ?? figma.currentPage+ const group = figma.group(nodes, parent)+ return nodeSummary(group)+ },+})++export const ungroupNode = defineTool({+ name: 'ungroup_node',+ mutates: true,+ description: 'Ungroup a group node.',+ params: {+ id: { type: 'string', description: 'Group node ID', required: true },+ },+ execute: (figma, { id }) => {+ const node = figma.getNodeById(id)+ if (!node) return { error: `Node "${id}" not found` }+ figma.ungroup(node)+ return { ungrouped: id }+ },+})++export const flattenNodes = defineTool({+ name: 'flatten_nodes',+ mutates: true,+ description: 'Flatten nodes into a single vector.',+ params: {+ ids: { type: 'string[]', description: 'Node IDs to flatten', required: true },+ },+ execute: (figma, { ids }) => {+ const result = figma.flattenNode(ids)+ return nodeSummary(result)+ },+})++export const nodeToComponent = defineTool({+ name: 'node_to_component',+ mutates: true,+ description: 'Convert one or more frames/groups into components.',+ params: {+ ids: { type: 'string[]', description: 'Node IDs to convert', required: true },+ },+ execute: (figma, { ids }) => {+ const results: { id: string; name: string; originalId: string }[] = []+ for (const id of ids) {+ const node = figma.getNodeById(id)+ if (!node) continue+ const comp = figma.createComponentFromNode(node)+ results.push({ id: comp.id, name: comp.name, originalId: id })+ }+ return { converted: results }+ },+})diff --git a/packages/core/src/tools/structure/replace.ts b/packages/core/src/tools/structure/replace.tsnew file mode 100644index 000000000..d00e4282e--- /dev/null+++ b/packages/core/src/tools/structure/replace.ts@@ -0,0 +1,28 @@+import { defineTool } from '#core/tools/schema'++export const nodeReplaceWith = defineTool({+ name: 'node_replace_with',+ mutates: true,+ description: 'Replace a node with JSX content.',+ params: {+ id: { type: 'string', description: 'Node ID to replace', required: true },+ jsx: { type: 'string', description: 'JSX string for the replacement', required: true },+ },+ execute: async (figma, args) => {+ const node = figma.getNodeById(args.id)+ if (!node) return { error: `Node "${args.id}" not found` }+ const parentId = node.parent?.id ?? figma.currentPageId+ const x = node.x+ const y = node.y+ node.remove()+ const { renderJSX } = await import('#core/design-jsx/render.js')+ const results = await renderJSX(figma.graph, args.jsx, { parentId, x, y })+ const result = results[0]+ return {+ id: result.id,+ name: result.name,+ type: result.type,+ children: results.slice(1).map((child) => ({ id: child.id, name: child.name, type: child.type })),+ }+ },+})diff --git a/packages/core/src/tools/structure/tree.ts b/packages/core/src/tools/structure/tree.tsnew file mode 100644index 000000000..6ef9c294f--- /dev/null+++ b/packages/core/src/tools/structure/tree.ts@@ -0,0 +1,77 @@+import { defineTool, getRawNodeOrError, nodeNotFound, nodeSummary } from '#core/tools/schema'++import type { FigmaNodeProxy } from '#core/figma-api'++export const nodeAncestors = defineTool({+ name: 'node_ancestors',+ description: 'Get the ancestor chain from a node to the page root.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ depth: { type: 'number', description: 'Max depth to traverse' },+ },+ execute: (figma, args) => {+ const node = figma.getNodeById(args.id)+ if (!node) return { error: `Node "${args.id}" not found` }+ const ancestors: { id: string; name: string; type: string }[] = []+ let current = node.parent+ let depth = 0+ while (current && (!args.depth || depth < args.depth)) {+ ancestors.push(nodeSummary(current))+ current = current.parent+ depth+++ }+ return { id: args.id, ancestors }+ },+})++export const nodeChildren = defineTool({+ name: 'node_children',+ description: 'Get direct children of a node.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ },+ execute: (figma, { id }) => {+ const node = figma.getNodeById(id)+ if (!node) return nodeNotFound(id)+ return { id, children: node.children.map(nodeSummary) }+ },+})++export const nodeTree = defineTool({+ name: 'node_tree',+ description: 'Get a node tree with types and hierarchy.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ depth: { type: 'number', description: 'Max depth (default: unlimited)' },+ },+ execute: (figma, args) => {+ const node = figma.getNodeById(args.id)+ if (!node) return { error: `Node "${args.id}" not found` }+ function buildTree(current: FigmaNodeProxy, depth: number): Record<string, unknown> {+ const result: Record<string, unknown> = {+ id: current.id,+ name: current.name,+ type: current.type,+ }+ if (args.depth === undefined || depth < args.depth) {+ const children = current.children+ if (children.length > 0) result.children = children.map((child) => buildTree(child, depth + 1))+ }+ return result+ }+ return buildTree(node, 0)+ },+})++export const nodeBindings = defineTool({+ name: 'node_bindings',+ description: 'Get variable bindings for a node.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ },+ execute: (figma, { id }) => {+ const result = getRawNodeOrError(figma, id)+ if ('error' in result) return result+ return { id, bindings: result.node.boundVariables }+ },+})diff --git a/packages/core/src/tools/variables.ts b/packages/core/src/tools/variables.tsindex 691369765..3d0aa99f1 100644--- a/packages/core/src/tools/variables.ts+++ b/packages/core/src/tools/variables.ts@@ -1,194 +1,4 @@-import { parseColor } from '../color'-import { defineTool } from './schema'--import type { VariableType, VariableValue } from '../scene-graph'--export const listVariables = defineTool({- name: 'list_variables',- description: 'List all design variables (colors, numbers, strings, booleans).',- params: {- type: {- type: 'string',- description: 'Filter by variable type',- enum: ['COLOR', 'FLOAT', 'STRING', 'BOOLEAN']- }- },- execute: (figma, args) => {- const vars = figma.getLocalVariables(args.type)- return { count: vars.length, variables: vars }- }-})--export const listCollections = defineTool({- name: 'list_collections',- description: 'List all variable collections.',- params: {},- execute: (figma) => {- const cols = figma.getLocalVariableCollections()- return { count: cols.length, collections: cols }- }-})--export const getVariable = defineTool({- name: 'get_variable',- description: 'Get a variable by ID.',- params: {- id: { type: 'string', description: 'Variable ID', required: true }- },- execute: (figma, { id }) => {- const v = figma.getVariableById(id)- if (!v) return { error: `Variable "${id}" not found` }- return v- }-})--export const findVariables = defineTool({- name: 'find_variables',- description: 'Find variables by name pattern.',- params: {- query: { type: 'string', description: 'Name substring (case-insensitive)', required: true },- type: {- type: 'string',- description: 'Filter by type',- enum: ['COLOR', 'FLOAT', 'STRING', 'BOOLEAN']- }- },- execute: (figma, args) => {- let vars = figma.getLocalVariables(args.type)- vars = vars.filter((v) => v.name.toLowerCase().includes(args.query.toLowerCase()))- return { count: vars.length, variables: vars }- }-})--export const createVariable = defineTool({- name: 'create_variable',- mutates: true,- description: 'Create a new variable in a collection.',- params: {- name: { type: 'string', description: 'Variable name', required: true },- type: {- type: 'string',- description: 'Variable type',- required: true,- enum: ['COLOR', 'FLOAT', 'STRING', 'BOOLEAN']- },- collection_id: { type: 'string', description: 'Collection ID', required: true },- value: { type: 'string', description: 'Initial value (hex for COLOR, number for FLOAT, etc.)' }- },- execute: (figma, args) => {- let parsedValue: unknown- if (args.value !== undefined) {- if (args.type === 'COLOR') parsedValue = parseColor(args.value)- else if (args.type === 'FLOAT') parsedValue = Number(args.value)- else if (args.type === 'BOOLEAN') parsedValue = args.value === 'true'- else parsedValue = args.value- }- const v = figma.createVariable(- args.name,- args.type as VariableType,- args.collection_id,- parsedValue as VariableValue- )- return v- }-})--export const setVariable = defineTool({- name: 'set_variable',- mutates: true,- description: 'Set the value of a variable for a specific mode.',- params: {- id: { type: 'string', description: 'Variable ID', required: true },- mode: { type: 'string', description: 'Mode ID', required: true },- value: {- type: 'string',- description: 'Value (hex for COLOR, number for FLOAT, etc.)',- required: true- }- },- execute: (figma, args) => {- const v = figma.getVariableById(args.id)- if (!v) return { error: `Variable "${args.id}" not found` }- let parsedValue: unknown- if (v.type === 'COLOR') parsedValue = parseColor(args.value)- else if (v.type === 'FLOAT') parsedValue = Number(args.value)- else if (v.type === 'BOOLEAN') parsedValue = args.value === 'true'- else parsedValue = args.value- figma.setVariableValue(args.id, args.mode, parsedValue as VariableValue)- return { id: args.id, mode: args.mode, value: parsedValue }- }-})--export const deleteVariable = defineTool({- name: 'delete_variable',- mutates: true,- description: 'Delete a variable.',- params: {- id: { type: 'string', description: 'Variable ID', required: true }- },- execute: (figma, { id }) => {- figma.deleteVariable(id)- return { deleted: id }- }-})--export const bindVariable = defineTool({- name: 'bind_variable',- mutates: true,- description: 'Bind a variable to a node property (fills, strokes, opacity, width, height, etc.).',- params: {- node_id: { type: 'string', description: 'Node ID', required: true },- field: {- type: 'string',- description: 'Property field (fills, strokes, opacity, width, height, etc.)',- required: true- },- variable_id: { type: 'string', description: 'Variable ID', required: true }- },- execute: (figma, args) => {- const node = figma.getNodeById(args.node_id)- if (!node) return { error: `Node "${args.node_id}" not found` }- const v = figma.getVariableById(args.variable_id)- if (!v) return { error: `Variable "${args.variable_id}" not found` }- figma.bindVariable(args.node_id, args.field, args.variable_id)- return { node_id: args.node_id, field: args.field, variable_id: args.variable_id }- }-})--export const getCollection = defineTool({- name: 'get_collection',- description: 'Get a variable collection by ID.',- params: {- id: { type: 'string', description: 'Collection ID', required: true }- },- execute: (figma, { id }) => {- const c = figma.getVariableCollectionById(id)- if (!c) return { error: `Collection "${id}" not found` }- return c- }-})--export const createCollection = defineTool({- name: 'create_collection',- mutates: true,- description: 'Create a new variable collection.',- params: {- name: { type: 'string', description: 'Collection name', required: true }- },- execute: (figma, { name }) => {- return figma.createVariableCollection(name)- }-})--export const deleteCollection = defineTool({- name: 'delete_collection',- mutates: true,- description: 'Delete a variable collection and all its variables.',- params: {- id: { type: 'string', description: 'Collection ID', required: true }- },- execute: (figma, { id }) => {- figma.deleteVariableCollection(id)- return { deleted: id }- }-})+export { bindVariable } from './variables/bindings'+export { createCollection, deleteCollection, getCollection, listCollections } from './variables/collections'+export { findVariables, getVariable, listVariables } from './variables/read'+export { createVariable, deleteVariable, setVariable } from './variables/values'diff --git a/packages/core/src/tools/variables/bindings.ts b/packages/core/src/tools/variables/bindings.tsnew file mode 100644index 000000000..d4c36e322--- /dev/null+++ b/packages/core/src/tools/variables/bindings.ts@@ -0,0 +1,24 @@+import { defineTool } from '#core/tools/schema'++export const bindVariable = defineTool({+ name: 'bind_variable',+ mutates: true,+ description: 'Bind a variable to a node property (fills, strokes, opacity, width, height, etc.).',+ params: {+ node_id: { type: 'string', description: 'Node ID', required: true },+ field: {+ type: 'string',+ description: 'Property field (fills, strokes, opacity, width, height, etc.)',+ required: true,+ },+ variable_id: { type: 'string', description: 'Variable ID', required: true },+ },+ execute: (figma, args) => {+ const node = figma.getNodeById(args.node_id)+ if (!node) return { error: `Node "${args.node_id}" not found` }+ const variable = figma.getVariableById(args.variable_id)+ if (!variable) return { error: `Variable "${args.variable_id}" not found` }+ figma.bindVariable(args.node_id, args.field, args.variable_id)+ return { node_id: args.node_id, field: args.field, variable_id: args.variable_id }+ },+})diff --git a/packages/core/src/tools/variables/collections.ts b/packages/core/src/tools/variables/collections.tsnew file mode 100644index 000000000..f2c6e0822--- /dev/null+++ b/packages/core/src/tools/variables/collections.ts@@ -0,0 +1,49 @@+import { defineTool } from '#core/tools/schema'++export const listCollections = defineTool({+ name: 'list_collections',+ description: 'List all variable collections.',+ params: {},+ execute: (figma) => {+ const collections = figma.getLocalVariableCollections()+ return { count: collections.length, collections }+ },+})++export const getCollection = defineTool({+ name: 'get_collection',+ description: 'Get a variable collection by ID.',+ params: {+ id: { type: 'string', description: 'Collection ID', required: true },+ },+ execute: (figma, { id }) => {+ const collection = figma.getVariableCollectionById(id)+ if (!collection) return { error: `Collection "${id}" not found` }+ return collection+ },+})++export const createCollection = defineTool({+ name: 'create_collection',+ mutates: true,+ description: 'Create a new variable collection.',+ params: {+ name: { type: 'string', description: 'Collection name', required: true },+ },+ execute: (figma, { name }) => {+ return figma.createVariableCollection(name)+ },+})++export const deleteCollection = defineTool({+ name: 'delete_collection',+ mutates: true,+ description: 'Delete a variable collection and all its variables.',+ params: {+ id: { type: 'string', description: 'Collection ID', required: true },+ },+ execute: (figma, { id }) => {+ figma.deleteVariableCollection(id)+ return { deleted: id }+ },+})diff --git a/packages/core/src/tools/variables/read.ts b/packages/core/src/tools/variables/read.tsnew file mode 100644index 000000000..a0e674312--- /dev/null+++ b/packages/core/src/tools/variables/read.ts@@ -0,0 +1,50 @@+import { defineTool } from '#core/tools/schema'++export const listVariables = defineTool({+ name: 'list_variables',+ description: 'List all design variables (colors, numbers, strings, booleans).',+ params: {+ type: {+ type: 'string',+ description: 'Filter by variable type',+ enum: ['COLOR', 'FLOAT', 'STRING', 'BOOLEAN'],+ },+ },+ execute: (figma, args) => {+ const variables = figma.getLocalVariables(args.type)+ return { count: variables.length, variables }+ },+})++export const getVariable = defineTool({+ name: 'get_variable',+ description: 'Get a variable by ID.',+ params: {+ id: { type: 'string', description: 'Variable ID', required: true },+ },+ execute: (figma, { id }) => {+ const variable = figma.getVariableById(id)+ if (!variable) return { error: `Variable "${id}" not found` }+ return variable+ },+})++export const findVariables = defineTool({+ name: 'find_variables',+ description: 'Find variables by name pattern.',+ params: {+ query: { type: 'string', description: 'Name substring (case-insensitive)', required: true },+ type: {+ type: 'string',+ description: 'Filter by type',+ enum: ['COLOR', 'FLOAT', 'STRING', 'BOOLEAN'],+ },+ },+ execute: (figma, args) => {+ let variables = figma.getLocalVariables(args.type)+ variables = variables.filter((variable) =>+ variable.name.toLowerCase().includes(args.query.toLowerCase())+ )+ return { count: variables.length, variables }+ },+})diff --git a/packages/core/src/tools/variables/values.ts b/packages/core/src/tools/variables/values.tsnew file mode 100644index 000000000..988c1f6e2--- /dev/null+++ b/packages/core/src/tools/variables/values.ts@@ -0,0 +1,68 @@+import { parseColor } from '#core/color'+import { defineTool } from '#core/tools/schema'++import type { VariableType, VariableValue } from '#core/scene-graph'++function parseVariableValue(type: VariableType, value: string): VariableValue {+ if (type === 'COLOR') return parseColor(value)+ if (type === 'FLOAT') return Number(value)+ if (type === 'BOOLEAN') return value === 'true'+ return value+}++export const createVariable = defineTool({+ name: 'create_variable',+ mutates: true,+ description: 'Create a new variable in a collection.',+ params: {+ name: { type: 'string', description: 'Variable name', required: true },+ type: {+ type: 'string',+ description: 'Variable type',+ required: true,+ enum: ['COLOR', 'FLOAT', 'STRING', 'BOOLEAN'],+ },+ collection_id: { type: 'string', description: 'Collection ID', required: true },+ value: { type: 'string', description: 'Initial value (hex for COLOR, number for FLOAT, etc.)' },+ },+ execute: (figma, args) => {+ const type = args.type as VariableType+ const parsedValue = args.value === undefined ? undefined : parseVariableValue(type, args.value)+ return figma.createVariable(args.name, type, args.collection_id, parsedValue)+ },+})++export const setVariable = defineTool({+ name: 'set_variable',+ mutates: true,+ description: 'Set the value of a variable for a specific mode.',+ params: {+ id: { type: 'string', description: 'Variable ID', required: true },+ mode: { type: 'string', description: 'Mode ID', required: true },+ value: {+ type: 'string',+ description: 'Value (hex for COLOR, number for FLOAT, etc.)',+ required: true,+ },+ },+ execute: (figma, args) => {+ const variable = figma.getVariableById(args.id)+ if (!variable) return { error: `Variable "${args.id}" not found` }+ const parsedValue = parseVariableValue(variable.type, args.value)+ figma.setVariableValue(args.id, args.mode, parsedValue)+ return { id: args.id, mode: args.mode, value: parsedValue }+ },+})++export const deleteVariable = defineTool({+ name: 'delete_variable',+ mutates: true,+ description: 'Delete a variable.',+ params: {+ id: { type: 'string', description: 'Variable ID', required: true },+ },+ execute: (figma, { id }) => {+ figma.deleteVariable(id)+ return { deleted: id }+ },+})diff --git a/packages/core/src/tools/vector.ts b/packages/core/src/tools/vector.tsindex 506e47687..43dd4299f 100644--- a/packages/core/src/tools/vector.ts+++ b/packages/core/src/tools/vector.ts@@ -1,331 +1,8 @@-import { cloneVectorNetwork } from '../scene-graph'-import { defineTool, nodeSummary } from './schema'-import type { FigmaAPI } from '../figma-api'-import type { RasterExportFormat } from '../io/formats/raster'-import type { SceneNode, VectorNetwork } from '../scene-graph'+export { booleanExclude, booleanIntersect, booleanSubtract, booleanUnion } from './vector/boolean'-function getVectorNode(- figma: FigmaAPI,- id: string-): { node: SceneNode; vn: VectorNetwork } | { error: string } {- const node = figma.graph.getNode(id)- if (!node) return { error: `Node "${id}" not found` }- if (!node.vectorNetwork) return { error: `Node "${id}" has no vector data` }- return { node, vn: cloneVectorNetwork(node.vectorNetwork) }-}+export { pathFlip, pathGet, pathMove, pathScale, pathSet } from './vector/path'-const CHUNK_SIZE = 0x8000+export { viewportGet, viewportSet, viewportZoomToFit } from './vector/viewport'-function uint8ArrayToBase64(bytes: Uint8Array): string {- if (typeof Buffer !== 'undefined') {- return Buffer.from(bytes).toString('base64')- }- let binary = ''- for (let i = 0; i < bytes.length; i += CHUNK_SIZE) {- const chunk = bytes.subarray(i, i + CHUNK_SIZE)- binary += String.fromCharCode.apply(null, chunk as unknown as number[])- }- return btoa(binary)-}--export const booleanUnion = defineTool({- name: 'boolean_union',- mutates: true,- description: 'Union (combine) multiple nodes.',- params: {- ids: { type: 'string[]', description: 'Node IDs to union', required: true }- },- execute: (figma, { ids }) => {- const result = figma.booleanOperation('UNION', ids)- return nodeSummary(result)- }-})--export const booleanSubtract = defineTool({- name: 'boolean_subtract',- mutates: true,- description: 'Subtract the second node from the first.',- params: {- ids: { type: 'string[]', description: 'Node IDs (first minus rest)', required: true }- },- execute: (figma, { ids }) => {- const result = figma.booleanOperation('SUBTRACT', ids)- return nodeSummary(result)- }-})--export const booleanIntersect = defineTool({- name: 'boolean_intersect',- mutates: true,- description: 'Intersect multiple nodes.',- params: {- ids: { type: 'string[]', description: 'Node IDs to intersect', required: true }- },- execute: (figma, { ids }) => {- const result = figma.booleanOperation('INTERSECT', ids)- return nodeSummary(result)- }-})--export const booleanExclude = defineTool({- name: 'boolean_exclude',- mutates: true,- description: 'Exclude (XOR) multiple nodes.',- params: {- ids: { type: 'string[]', description: 'Node IDs to exclude', required: true }- },- execute: (figma, { ids }) => {- const result = figma.booleanOperation('EXCLUDE', ids)- return nodeSummary(result)- }-})--export const pathGet = defineTool({- name: 'path_get',- description: 'Get vector path data of a node.',- params: {- id: { type: 'string', description: 'Node ID', required: true }- },- execute: (figma, { id }) => {- const raw = figma.graph.getNode(id)- if (!raw) return { error: `Node "${id}" not found` }- if (!raw.vectorNetwork) return { error: `Node "${id}" has no vector data` }- return { id, vectorNetwork: raw.vectorNetwork }- }-})--export const pathSet = defineTool({- name: 'path_set',- mutates: true,- description: 'Set vector path data on a node. Provide a VectorNetwork JSON.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- path: { type: 'string', description: 'VectorNetwork JSON', required: true }- },- execute: (figma, args) => {- const raw = figma.graph.getNode(args.id)- if (!raw) return { error: `Node "${args.id}" not found` }- const network = JSON.parse(args.path)- figma.graph.updateNode(args.id, { vectorNetwork: network })- return { id: args.id }- }-})--export const pathScale = defineTool({- name: 'path_scale',- mutates: true,- description: 'Scale vector path from center.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- factor: { type: 'number', description: 'Scale factor (e.g. 2 for double)', required: true }- },- execute: (figma, { id, factor }) => {- const result = getVectorNode(figma, id)- if ('error' in result) return result- const { node: raw, vn } = result- const cx = raw.width / 2- const cy = raw.height / 2- for (const v of vn.vertices) {- v.x = cx + (v.x - cx) * factor- v.y = cy + (v.y - cy) * factor- }- for (const s of vn.segments) {- s.tangentStart.x *= factor- s.tangentStart.y *= factor- s.tangentEnd.x *= factor- s.tangentEnd.y *= factor- }-- figma.graph.updateNode(id, { vectorNetwork: vn })- return { id, factor }- }-})--export const pathFlip = defineTool({- name: 'path_flip',- mutates: true,- description: 'Flip vector path horizontally or vertically.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- axis: {- type: 'string',- description: 'Flip axis',- required: true,- enum: ['horizontal', 'vertical']- }- },- execute: (figma, { id, axis }) => {- const result = getVectorNode(figma, id)- if ('error' in result) return result- const { node: raw, vn } = result- const w = raw.width- const h = raw.height- for (const v of vn.vertices) {- if (axis === 'horizontal') v.x = w - v.x- else v.y = h - v.y- }- for (const s of vn.segments) {- if (axis === 'horizontal') s.tangentStart.x = -s.tangentStart.x- else s.tangentStart.y = -s.tangentStart.y- if (axis === 'horizontal') s.tangentEnd.x = -s.tangentEnd.x- else s.tangentEnd.y = -s.tangentEnd.y- }-- figma.graph.updateNode(id, { vectorNetwork: vn })- return { id, axis }- }-})--export const pathMove = defineTool({- name: 'path_move',- mutates: true,- description: 'Move all path points by an offset.',- params: {- id: { type: 'string', description: 'Node ID', required: true },- dx: { type: 'number', description: 'X offset', required: true },- dy: { type: 'number', description: 'Y offset', required: true }- },- execute: (figma, { id, dx, dy }) => {- const result = getVectorNode(figma, id)- if ('error' in result) return result- const { vn } = result- for (const v of vn.vertices) {- v.x += dx- v.y += dy- }-- figma.graph.updateNode(id, { vectorNetwork: vn })- return { id, dx, dy }- }-})--export const viewportGet = defineTool({- name: 'viewport_get',- description: 'Get current viewport position and zoom level.',- params: {},- execute: (figma) => {- return figma.viewport- }-})--export const viewportSet = defineTool({- name: 'viewport_set',- mutates: true,- description: 'Set viewport position and zoom.',- params: {- x: { type: 'number', description: 'Center X', required: true },- y: { type: 'number', description: 'Center Y', required: true },- zoom: { type: 'number', description: 'Zoom level', required: true, min: 0.01 }- },- execute: (figma, { x, y, zoom }) => {- figma.viewport = { center: { x, y }, zoom }- return { x, y, zoom }- }-})--export const viewportZoomToFit = defineTool({- name: 'viewport_zoom_to_fit',- mutates: true,- description: 'Zoom viewport to fit specified nodes.',- params: {- ids: { type: 'string[]', description: 'Node IDs to fit in view', required: true }- },- execute: (figma, { ids }) => {- let minX = Infinity- let minY = Infinity- let maxX = -Infinity- let maxY = -Infinity- for (const id of ids) {- const node = figma.getNodeById(id)- if (!node) continue- const bounds = node.absoluteBoundingBox- minX = Math.min(minX, bounds.x)- minY = Math.min(minY, bounds.y)- maxX = Math.max(maxX, bounds.x + bounds.width)- maxY = Math.max(maxY, bounds.y + bounds.height)- }- if (minX === Infinity) return { error: 'No valid nodes found' }- const cx = (minX + maxX) / 2- const cy = (minY + maxY) / 2- figma.viewport = { center: { x: cx, y: cy }, zoom: 1 }- return {- center: { x: cx, y: cy },- bounds: { x: minX, y: minY, width: maxX - minX, height: maxY - minY }- }- }-})--export const exportSvg = defineTool({- name: 'export_svg',- description: 'Export nodes as SVG markup. Returns the SVG string.',- params: {- ids: {- type: 'string[]',- description: 'Node IDs to export. Omit to export all top-level nodes on the current page.'- },- path: {- type: 'string',- description: 'Write SVG to this path instead of returning it (requires OPENPENCIL_MCP_ROOT)'- }- },- execute: async (figma, args) => {- const { renderNodesToSVG } = await import('../io/formats/svg/index.js')- const pageId = figma.currentPageId- const ids =- args.ids && args.ids.length > 0 ? args.ids : figma.currentPage.children.map((n) => n.id)- const svg = renderNodesToSVG(figma.graph, pageId, ids)- if (!svg) return { error: 'No visible nodes to export' }- return { svg }- }-})--export const exportImage = defineTool({- name: 'export_image',- description:- 'Export nodes as a raster image (PNG, JPG, or WEBP). Returns base64-encoded image data. Use to visually verify designs.',- params: {- ids: {- type: 'string[]',- description: 'Node IDs to export. Omit to export all top-level nodes on the current page.'- },- format: {- type: 'string',- description: 'Image format',- enum: ['PNG', 'JPG', 'WEBP'],- default: 'PNG'- },- scale: {- type: 'number',- description: 'Export scale multiplier (default: 1)',- default: 1,- min: 0.1,- max: 4- },- path: {- type: 'string',- description:- 'Write image to this path instead of returning base64 (requires OPENPENCIL_MCP_ROOT)'- }- },- execute: async (figma, args) => {- if (!figma.exportImage) {- return { error: 'Image export is not available in this environment' }- }- const ids =- args.ids && args.ids.length > 0 ? args.ids : figma.currentPage.children.map((n) => n.id)- const format = (args.format ?? 'PNG').toUpperCase() as RasterExportFormat- const data = await figma.exportImage(ids, {- scale: args.scale ?? 1,- format- })- if (!data || data.length === 0) return { error: 'No visible nodes to export' }- const base64 = uint8ArrayToBase64(data)- const mimeMap = { PNG: 'image/png', JPG: 'image/jpeg', WEBP: 'image/webp' } as const- return {- mimeType: mimeMap[format],- base64,- byteLength: data.length- }- }-})+export { exportImage, exportSvg } from './vector/export'diff --git a/packages/core/src/tools/vector/boolean.ts b/packages/core/src/tools/vector/boolean.tsnew file mode 100644index 000000000..7a7e43516--- /dev/null+++ b/packages/core/src/tools/vector/boolean.ts@@ -0,0 +1,53 @@+import { defineTool, nodeSummary } from '#core/tools/schema'++export const booleanUnion = defineTool({+ name: 'boolean_union',+ mutates: true,+ description: 'Union (combine) multiple nodes.',+ params: {+ ids: { type: 'string[]', description: 'Node IDs to union', required: true },+ },+ execute: (figma, { ids }) => {+ const result = figma.booleanOperation('UNION', ids)+ return nodeSummary(result)+ },+})++export const booleanSubtract = defineTool({+ name: 'boolean_subtract',+ mutates: true,+ description: 'Subtract the second node from the first.',+ params: {+ ids: { type: 'string[]', description: 'Node IDs (first minus rest)', required: true },+ },+ execute: (figma, { ids }) => {+ const result = figma.booleanOperation('SUBTRACT', ids)+ return nodeSummary(result)+ },+})++export const booleanIntersect = defineTool({+ name: 'boolean_intersect',+ mutates: true,+ description: 'Intersect multiple nodes.',+ params: {+ ids: { type: 'string[]', description: 'Node IDs to intersect', required: true },+ },+ execute: (figma, { ids }) => {+ const result = figma.booleanOperation('INTERSECT', ids)+ return nodeSummary(result)+ },+})++export const booleanExclude = defineTool({+ name: 'boolean_exclude',+ mutates: true,+ description: 'Exclude (XOR) multiple nodes.',+ params: {+ ids: { type: 'string[]', description: 'Node IDs to exclude', required: true },+ },+ execute: (figma, { ids }) => {+ const result = figma.booleanOperation('EXCLUDE', ids)+ return nodeSummary(result)+ },+})diff --git a/packages/core/src/tools/vector/export.ts b/packages/core/src/tools/vector/export.tsnew file mode 100644index 000000000..e05d89a85--- /dev/null+++ b/packages/core/src/tools/vector/export.ts@@ -0,0 +1,91 @@+import { defineTool } from '#core/tools/schema'++import type { RasterExportFormat } from '#core/io/formats/raster'++const CHUNK_SIZE = 0x8000++function uint8ArrayToBase64(bytes: Uint8Array): string {+ if (typeof Buffer !== 'undefined') {+ return Buffer.from(bytes).toString('base64')+ }+ let binary = ''+ for (let index = 0; index < bytes.length; index += CHUNK_SIZE) {+ const chunk = bytes.subarray(index, index + CHUNK_SIZE)+ binary += String.fromCharCode.apply(null, chunk as unknown as number[])+ }+ return btoa(binary)+}++export const exportSvg = defineTool({+ name: 'export_svg',+ description: 'Export nodes as SVG markup. Returns the SVG string.',+ params: {+ ids: {+ type: 'string[]',+ description: 'Node IDs to export. Omit to export all top-level nodes on the current page.',+ },+ path: {+ type: 'string',+ description: 'Write SVG to this path instead of returning it (requires OPENPENCIL_MCP_ROOT)',+ },+ },+ execute: async (figma, args) => {+ const { renderNodesToSVG } = await import('#core/io/formats/svg')+ const pageId = figma.currentPageId+ const ids =+ args.ids && args.ids.length > 0 ? args.ids : figma.currentPage.children.map((node) => node.id)+ const svg = renderNodesToSVG(figma.graph, pageId, ids)+ if (!svg) return { error: 'No visible nodes to export' }+ return { svg }+ },+})++export const exportImage = defineTool({+ name: 'export_image',+ description:+ 'Export nodes as a raster image (PNG, JPG, or WEBP). Returns base64-encoded image data. Use to visually verify designs.',+ params: {+ ids: {+ type: 'string[]',+ description: 'Node IDs to export. Omit to export all top-level nodes on the current page.',+ },+ format: {+ type: 'string',+ description: 'Image format',+ enum: ['PNG', 'JPG', 'WEBP'],+ default: 'PNG',+ },+ scale: {+ type: 'number',+ description: 'Export scale multiplier (default: 1)',+ default: 1,+ min: 0.1,+ max: 4,+ },+ path: {+ type: 'string',+ description:+ 'Write image to this path instead of returning base64 (requires OPENPENCIL_MCP_ROOT)',+ },+ },+ execute: async (figma, args) => {+ if (!figma.exportImage) {+ return { error: 'Image export is not available in this environment' }+ }+ const ids =+ args.ids && args.ids.length > 0 ? args.ids : figma.currentPage.children.map((node) => node.id)+ const format = (args.format ?? 'PNG').toUpperCase() as RasterExportFormat+ const data = await figma.exportImage(ids, {+ scale: args.scale ?? 1,+ format,+ })+ if (!data || data.length === 0) return { error: 'No visible nodes to export' }+ const base64 = uint8ArrayToBase64(data)+ const mimeMap = { PNG: 'image/png', JPG: 'image/jpeg', WEBP: 'image/webp' } as const+ return {+ mimeType: mimeMap[format],+ base64,+ byteLength: data.length,+ }+ },+})diff --git a/packages/core/src/tools/vector/path.ts b/packages/core/src/tools/vector/path.tsnew file mode 100644index 000000000..16aa95943--- /dev/null+++ b/packages/core/src/tools/vector/path.ts@@ -0,0 +1,134 @@+import { cloneVectorNetwork } from '#core/scene-graph'+import { defineTool } from '#core/tools/schema'++import type { FigmaAPI } from '#core/figma-api'+import type { SceneNode, VectorNetwork } from '#core/scene-graph'++function getVectorNode(+ figma: FigmaAPI,+ id: string+): { node: SceneNode; vn: VectorNetwork } | { error: string } {+ const node = figma.graph.getNode(id)+ if (!node) return { error: `Node "${id}" not found` }+ if (!node.vectorNetwork) return { error: `Node "${id}" has no vector data` }+ return { node, vn: cloneVectorNetwork(node.vectorNetwork) }+}++export const pathGet = defineTool({+ name: 'path_get',+ description: 'Get vector path data of a node.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ },+ execute: (figma, { id }) => {+ const raw = figma.graph.getNode(id)+ if (!raw) return { error: `Node "${id}" not found` }+ const vectorNetwork = raw.vectorNetwork+ return vectorNetwork ? { id, vectorNetwork } : { error: `Node "${id}" has no vector data` }+ },+})++export const pathSet = defineTool({+ name: 'path_set',+ mutates: true,+ description: 'Set vector path data on a node. Provide a VectorNetwork JSON.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ path: { type: 'string', description: 'VectorNetwork JSON', required: true },+ },+ execute: (figma, args) => {+ const raw = figma.graph.getNode(args.id)+ if (!raw) return { error: `Node "${args.id}" not found` }+ const network = JSON.parse(args.path)+ figma.graph.updateNode(args.id, { vectorNetwork: network })+ return { id: args.id }+ },+})++export const pathScale = defineTool({+ name: 'path_scale',+ mutates: true,+ description: 'Scale vector path from center.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ factor: { type: 'number', description: 'Scale factor (e.g. 2 for double)', required: true },+ },+ execute: (figma, { id, factor }) => {+ const result = getVectorNode(figma, id)+ if ('error' in result) return result+ const { node: raw, vn } = result+ const centerX = raw.width / 2+ const centerY = raw.height / 2+ for (const vertex of vn.vertices) {+ vertex.x = centerX + (vertex.x - centerX) * factor+ vertex.y = centerY + (vertex.y - centerY) * factor+ }+ for (const segment of vn.segments) {+ segment.tangentStart.x *= factor+ segment.tangentStart.y *= factor+ segment.tangentEnd.x *= factor+ segment.tangentEnd.y *= factor+ }++ figma.graph.updateNode(id, { vectorNetwork: vn })+ return { id, factor }+ },+})++export const pathFlip = defineTool({+ name: 'path_flip',+ mutates: true,+ description: 'Flip vector path horizontally or vertically.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ axis: {+ type: 'string',+ description: 'Flip axis',+ required: true,+ enum: ['horizontal', 'vertical'],+ },+ },+ execute: (figma, { id, axis }) => {+ const result = getVectorNode(figma, id)+ if ('error' in result) return result+ const { node: raw, vn } = result+ const width = raw.width+ const height = raw.height+ for (const vertex of vn.vertices) {+ if (axis === 'horizontal') vertex.x = width - vertex.x+ else vertex.y = height - vertex.y+ }+ for (const segment of vn.segments) {+ if (axis === 'horizontal') segment.tangentStart.x = -segment.tangentStart.x+ else segment.tangentStart.y = -segment.tangentStart.y+ if (axis === 'horizontal') segment.tangentEnd.x = -segment.tangentEnd.x+ else segment.tangentEnd.y = -segment.tangentEnd.y+ }++ figma.graph.updateNode(id, { vectorNetwork: vn })+ return { id, axis }+ },+})++export const pathMove = defineTool({+ name: 'path_move',+ mutates: true,+ description: 'Move all path points by an offset.',+ params: {+ id: { type: 'string', description: 'Node ID', required: true },+ dx: { type: 'number', description: 'X offset', required: true },+ dy: { type: 'number', description: 'Y offset', required: true },+ },+ execute: (figma, { id, dx, dy }) => {+ const result = getVectorNode(figma, id)+ if ('error' in result) return result+ const { vn } = result+ for (const vertex of vn.vertices) {+ vertex.x += dx+ vertex.y += dy+ }++ figma.graph.updateNode(id, { vectorNetwork: vn })+ return { id, dx, dy }+ },+})diff --git a/packages/core/src/tools/vector/viewport.ts b/packages/core/src/tools/vector/viewport.tsnew file mode 100644index 000000000..316db8718--- /dev/null+++ b/packages/core/src/tools/vector/viewport.ts@@ -0,0 +1,57 @@+import { defineTool } from '#core/tools/schema'++export const viewportGet = defineTool({+ name: 'viewport_get',+ description: 'Get current viewport position and zoom level.',+ params: {},+ execute: (figma) => {+ return figma.viewport+ },+})++export const viewportSet = defineTool({+ name: 'viewport_set',+ mutates: true,+ description: 'Set viewport position and zoom.',+ params: {+ x: { type: 'number', description: 'Center X', required: true },+ y: { type: 'number', description: 'Center Y', required: true },+ zoom: { type: 'number', description: 'Zoom level', required: true, min: 0.01 },+ },+ execute: (figma, { x, y, zoom }) => {+ figma.viewport = { center: { x, y }, zoom }+ return { x, y, zoom }+ },+})++export const viewportZoomToFit = defineTool({+ name: 'viewport_zoom_to_fit',+ mutates: true,+ description: 'Zoom viewport to fit specified nodes.',+ params: {+ ids: { type: 'string[]', description: 'Node IDs to fit in view', required: true },+ },+ execute: (figma, { ids }) => {+ let minX = Infinity+ let minY = Infinity+ let maxX = -Infinity+ let maxY = -Infinity+ for (const id of ids) {+ const node = figma.getNodeById(id)+ if (!node) continue+ const bounds = node.absoluteBoundingBox+ minX = Math.min(minX, bounds.x)+ minY = Math.min(minY, bounds.y)+ maxX = Math.max(maxX, bounds.x + bounds.width)+ maxY = Math.max(maxY, bounds.y + bounds.height)+ }+ if (minX === Infinity) return { error: 'No valid nodes found' }+ const centerX = (minX + maxX) / 2+ const centerY = (minY + maxY) / 2+ figma.viewport = { center: { x: centerX, y: centerY }, zoom: 1 }+ return {+ center: { x: centerX, y: centerY },+ bounds: { x: minX, y: minY, width: maxX - minX, height: maxY - minY },+ }+ },+})diff --git a/packages/core/src/vector/bezier.ts b/packages/core/src/vector/bezier.tsindex e413e1048..3aa5e9745 100644--- a/packages/core/src/vector/bezier.ts+++ b/packages/core/src/vector/bezier.ts@@ -1,340 +1,48 @@-import type { VectorNetwork, VectorSegment, VectorVertex, VectorRegion } from '../scene-graph'-/* eslint-disable max-lines -- Bezier/network utilities kept together for shared geometry math */-/**- * Pure-JS bezier math utilities for VectorNetwork manipulation.- * Replaces Paper.js dependency from the reference implementation.- */-import type { Vector, Rect } from '../types'--// ----------------------------------------------------------------------------// Types-// -----------------------------------------------------------------------------export interface CubicPoints {- p0: Vector- cp1: Vector- cp2: Vector- p3: Vector-}--export interface NearestResult {- t: number- x: number- y: number- distance: number-}--export interface NetworkNearestResult extends NearestResult {- segmentIndex: number-}--// ----------------------------------------------------------------------------// De Casteljau evaluation-// -----------------------------------------------------------------------------/** Evaluate a cubic bezier at parameter t (0..1). */-export function evalCubic(- p0x: number,- p0y: number,- p1x: number,- p1y: number,- p2x: number,- p2y: number,- p3x: number,- p3y: number,- t: number-): Vector {- const mt = 1 - t- const mt2 = mt * mt- const t2 = t * t- const a = mt2 * mt- const b = 3 * mt2 * t- const c = 3 * mt * t2- const d = t2 * t- return {- x: a * p0x + b * p1x + c * p2x + d * p3x,- y: a * p0y + b * p1y + c * p2y + d * p3y- }-}--// ----------------------------------------------------------------------------// Curve splitting (De Casteljau subdivision)-// -----------------------------------------------------------------------------/** Split a cubic bezier at parameter t, returning two sub-curves. */-export function splitCubicAt(- p0: Vector,- cp1: Vector,- cp2: Vector,- p3: Vector,- t: number-): { left: CubicPoints; right: CubicPoints } {- const mt = 1 - t-- // Level 1- const m01x = mt * p0.x + t * cp1.x- const m01y = mt * p0.y + t * cp1.y- const m12x = mt * cp1.x + t * cp2.x- const m12y = mt * cp1.y + t * cp2.y- const m23x = mt * cp2.x + t * p3.x- const m23y = mt * cp2.y + t * p3.y-- // Level 2- const m012x = mt * m01x + t * m12x- const m012y = mt * m01y + t * m12y- const m123x = mt * m12x + t * m23x- const m123y = mt * m12y + t * m23y-- // Level 3 — the split point- const mx = mt * m012x + t * m123x- const my = mt * m012y + t * m123y-- return {- left: {- p0: { x: p0.x, y: p0.y },- cp1: { x: m01x, y: m01y },- cp2: { x: m012x, y: m012y },- p3: { x: mx, y: my }- },- right: {- p0: { x: mx, y: my },- cp1: { x: m123x, y: m123y },- cp2: { x: m23x, y: m23y },- p3: { x: p3.x, y: p3.y }- }- }-}--// ----------------------------------------------------------------------------// Segment ↔ absolute control points conversion-// -----------------------------------------------------------------------------/** Convert a VectorSegment's relative tangents to absolute control points. */-export function segmentToAbsolute(network: VectorNetwork, segmentIndex: number): CubicPoints {- const seg = network.segments[segmentIndex]- const v0 = network.vertices[seg.start]- const v1 = network.vertices[seg.end]- return {- p0: { x: v0.x, y: v0.y },- cp1: { x: v0.x + seg.tangentStart.x, y: v0.y + seg.tangentStart.y },- cp2: { x: v1.x + seg.tangentEnd.x, y: v1.y + seg.tangentEnd.y },- p3: { x: v1.x, y: v1.y }- }-}--/** Check if a segment is a straight line (both tangents zero). */-export function isLineSegment(seg: VectorSegment): boolean {- return (- seg.tangentStart.x === 0 &&- seg.tangentStart.y === 0 &&- seg.tangentEnd.x === 0 &&- seg.tangentEnd.y === 0- )-}--// ----------------------------------------------------------------------------// Accurate bezier bounds via cubic extrema-// -----------------------------------------------------------------------------/**- * Find parameter values where the cubic derivative is zero (extrema) in one axis.- * Given cubic coefficients for one axis: B(t) = (1-t)^3*p0 + 3(1-t)^2*t*p1 + 3(1-t)*t^2*p2 + t^3*p3- * Derivative: B'(t) = 3[(1-t)^2(p1-p0) + 2(1-t)t(p2-p1) + t^2(p3-p2)]- * Expanding: at^2 + bt + c = 0 where:- * a = -p0 + 3p1 - 3p2 + p3- * b = 2(p0 - 2p1 + p2)- * c = -p0 + p1- */-export function cubicExtrema(p0: number, p1: number, p2: number, p3: number): number[] {- const a = -p0 + 3 * p1 - 3 * p2 + p3- const b = 2 * (p0 - 2 * p1 + p2)- const c = -p0 + p1-- const results: number[] = []- const EPS = 1e-12-- if (Math.abs(a) < EPS) {- // Linear: bt + c = 0- if (Math.abs(b) > EPS) {- const t = -c / b- if (t > 0 && t < 1) results.push(t)- }- } else {- const disc = b * b - 4 * a * c- if (disc >= 0) {- const sq = Math.sqrt(disc)- const t1 = (-b + sq) / (2 * a)- const t2 = (-b - sq) / (2 * a)- if (t1 > 0 && t1 < 1) results.push(t1)- if (t2 > 0 && t2 < 1 && Math.abs(t2 - t1) > EPS) results.push(t2)- }- }-- return results-}--/** Compute tight axis-aligned bounding box for a VectorNetwork. */-export function computeAccurateBounds(network: VectorNetwork): Rect {- const { vertices, segments } = network- if (vertices.length === 0) return { x: 0, y: 0, width: 0, height: 0 }-- let minX = Infinity,- minY = Infinity,- maxX = -Infinity,- maxY = -Infinity-- const update = (x: number, y: number) => {- if (x < minX) minX = x- if (y < minY) minY = y- if (x > maxX) maxX = x- if (y > maxY) maxY = y- }-- // Include all vertex positions- for (const v of vertices) update(v.x, v.y)-- // For each segment, find curve extrema- for (let i = 0; i < segments.length; i++) {- const { p0, cp1, cp2, p3 } = segmentToAbsolute(network, i)-- // X extrema- for (const t of cubicExtrema(p0.x, cp1.x, cp2.x, p3.x)) {- const pt = evalCubic(p0.x, p0.y, cp1.x, cp1.y, cp2.x, cp2.y, p3.x, p3.y, t)- update(pt.x, pt.y)- }-- // Y extrema- for (const t of cubicExtrema(p0.y, cp1.y, cp2.y, p3.y)) {- const pt = evalCubic(p0.x, p0.y, cp1.x, cp1.y, cp2.x, cp2.y, p3.x, p3.y, t)- update(pt.x, pt.y)- }- }-- return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }-}--// ----------------------------------------------------------------------------// Nearest point on cubic bezier-// -----------------------------------------------------------------------------/**- * Find the nearest point on a cubic bezier to a given point (px, py).- * Uses coarse sampling + iterative refinement.- */-export function nearestPointOnCubic(- px: number,- py: number,- p0: Vector,- cp1: Vector,- cp2: Vector,- p3: Vector,- coarseSamples: number = 64-): NearestResult {- let bestT = 0- let bestDist = Infinity-- // Coarse sampling- for (let i = 0; i <= coarseSamples; i++) {- const t = i / coarseSamples- const pt = evalCubic(p0.x, p0.y, cp1.x, cp1.y, cp2.x, cp2.y, p3.x, p3.y, t)- const dx = pt.x - px- const dy = pt.y - py- const d = dx * dx + dy * dy- if (d < bestDist) {- bestDist = d- bestT = t- }- }-- // Refinement — bisect around best sample, 5 iterations- let lo = Math.max(0, bestT - 1 / coarseSamples)- let hi = Math.min(1, bestT + 1 / coarseSamples)-- for (let iter = 0; iter < 5; iter++) {- const step = (hi - lo) / 4- let localBestT = lo- let localBestDist = Infinity-- for (let i = 0; i <= 4; i++) {- const t = lo + step * i- const pt = evalCubic(p0.x, p0.y, cp1.x, cp1.y, cp2.x, cp2.y, p3.x, p3.y, t)- const dx = pt.x - px- const dy = pt.y - py- const d = dx * dx + dy * dy- if (d < localBestDist) {- localBestDist = d- localBestT = t- }- }-- bestT = localBestT- bestDist = localBestDist- lo = Math.max(0, bestT - step)- hi = Math.min(1, bestT + step)- }-- const pt = evalCubic(p0.x, p0.y, cp1.x, cp1.y, cp2.x, cp2.y, p3.x, p3.y, bestT)- return { t: bestT, x: pt.x, y: pt.y, distance: Math.sqrt(bestDist) }-}--/** Find nearest point on a straight line segment. */-function nearestPointOnLine(px: number, py: number, p0: Vector, p1: Vector): NearestResult {- const dx = p1.x - p0.x- const dy = p1.y - p0.y- const lenSq = dx * dx + dy * dy-- let t: number- if (lenSq < 1e-12) {- t = 0- } else {- t = Math.max(0, Math.min(1, ((px - p0.x) * dx + (py - p0.y) * dy) / lenSq))- }-- const x = p0.x + t * dx- const y = p0.y + t * dy- const ddx = x - px- const ddy = y - py- return { t, x, y, distance: Math.sqrt(ddx * ddx + ddy * ddy) }-}--/** Find nearest point across all segments in a VectorNetwork. */-export function nearestPointOnNetwork(- px: number,- py: number,+import { evalCubic, isLineSegment, segmentToAbsolute, splitCubicAt } from './curve-math'+import { reindexRegionLoops, remapRegions } from './regions'+export {+ computeAccurateBounds,+ cubicExtrema,+ evalCubic,+ isLineSegment,+ nearestPointOnCubic,+ nearestPointOnNetwork,+ segmentToAbsolute,+ splitCubicAt,+ type CubicPoints,+ type NearestResult,+ type NetworkNearestResult+} from './curve-math'++import type { VectorNetwork, VectorSegment, VectorVertex } from '#core/scene-graph'+import type { Vector } from '#core/types'++function finishSplitSegment(network: VectorNetwork,- threshold: number-): NetworkNearestResult | null {- let best: NetworkNearestResult | null = null+ newVertices: VectorVertex[],+ newSegments: VectorSegment[],+ segmentIndex: number,+ seg1: VectorSegment,+ seg2: VectorSegment,+ newVertexIndex: number+): { network: VectorNetwork; newVertexIndex: number } {+ const newSegIdx2 = newSegments.length+ newSegments[segmentIndex] = seg1+ newSegments.push(seg2)- for (let i = 0; i < network.segments.length; i++) {- const seg = network.segments[i]- let result: NearestResult-- if (isLineSegment(seg)) {- const v0 = network.vertices[seg.start]- const v1 = network.vertices[seg.end]- result = nearestPointOnLine(px, py, v0, v1)- } else {- const { p0, cp1, cp2, p3 } = segmentToAbsolute(network, i)- result = nearestPointOnCubic(px, py, p0, cp1, cp2, p3)- }+ const regions = reindexRegionLoops(+ network.regions,+ segmentIndex,+ [segmentIndex, newSegIdx2],+ network.segments+ )- if (result.distance <= threshold && (!best || result.distance < best.distance)) {- best = { ...result, segmentIndex: i }- }+ return {+ network: { vertices: newVertices, segments: newSegments, regions },+ newVertexIndex}-- return best}-// ----------------------------------------------------------------------------// Split segment within a VectorNetwork-// -----------------------------------------------------------------------------/**- * Split a segment in a VectorNetwork at parameter t, inserting a new vertex.- * Returns a new VectorNetwork with updated vertices, segments, and regions.- */export function splitSegmentAt(network: VectorNetwork,segmentIndex: number,@@ -371,22 +79,7 @@ export function splitSegmentAt(tangentEnd: { x: 0, y: 0 }}- // Replace original segment with first; insert second after- const newSegIdx2 = newSegments.length- newSegments[segmentIndex] = seg1- newSegments.push(seg2)-- const regions = reindexRegionLoops(- network.regions,- segmentIndex,- [segmentIndex, newSegIdx2],- network.segments- )-- return {- network: { vertices: newVertices, segments: newSegments, regions },- newVertexIndex- }+ return finishSplitSegment(network, newVertices, newSegments, segmentIndex, seg1, seg2, newVertexIndex)}// Cubic split via De Casteljau@@ -410,21 +103,7 @@ export function splitSegmentAt(tangentEnd: { x: right.cp2.x - v1.x, y: right.cp2.y - v1.y }}- const newSegIdx2 = newSegments.length- newSegments[segmentIndex] = seg1- newSegments.push(seg2)-- const regions = reindexRegionLoops(- network.regions,- segmentIndex,- [segmentIndex, newSegIdx2],- network.segments- )-- return {- network: { vertices: newVertices, segments: newSegments, regions },- newVertexIndex- }+ return finishSplitSegment(network, newVertices, newSegments, segmentIndex, seg1, seg2, newVertexIndex)}function buildMergedSegmentForRemovedVertex(@@ -706,89 +385,6 @@ export function breakAtVertex(network: VectorNetwork, vertexIndex: number): Vect* Remap segment indices in all region loops.* Map value of null means the segment was removed — the loop entry is dropped.*/-function remapRegions(- regions: VectorRegion[],- indexMap: Map<number, number | null>-): VectorRegion[] {- const result: VectorRegion[] = []-- for (const region of regions) {- const newLoops: number[][] = []- for (const loop of region.loops) {- const newLoop: number[] = []- for (const idx of loop) {- const mapped = indexMap.get(idx)- if (mapped == null) continue- // Deduplicate: when two merged segments both map to the same index,- // only include it once (skip consecutive duplicates)- if (newLoop.length > 0 && newLoop[newLoop.length - 1] === mapped) continue- newLoop.push(mapped)- }- // Also check wrap-around: if last equals first, remove the trailing duplicate- if (newLoop.length > 1 && newLoop[0] === newLoop[newLoop.length - 1]) {- newLoop.pop()- }- if (newLoop.length >= 2) newLoops.push(newLoop)- }- if (newLoops.length > 0) {- result.push({ ...region, loops: newLoops })- }- }-- return result-}-/**- * Replace a single segment index in all region loops with one or more new indices.- * Used after splitting a segment.- *- * When a segment is split into [seg1, seg2], seg1 goes original.start→mid and- * seg2 goes mid→original.end. If the loop traverses the original segment backward- * (end→start), the replacement must be [seg2, seg1] (reversed).- */-function reindexRegionLoops(- regions: VectorRegion[],- oldSegIndex: number,- newSegIndices: number[],- segments?: VectorSegment[]-): VectorRegion[] {- return regions.map((region) => ({- ...region,- loops: region.loops.map((loop) => {- const result: number[] = []- for (let i = 0; i < loop.length; i++) {- if (loop[i] !== oldSegIndex) {- result.push(loop[i])- continue- }-- // Determine traversal direction by checking the adjacent segment- if (!segments || newSegIndices.length < 2) {- result.push(...newSegIndices)- continue- }-- const origSeg = segments[oldSegIndex]- // Look at the NEXT segment in the loop to determine direction- const nextIdx = loop[(i + 1) % loop.length]- const nextSeg = segments[nextIdx]-- // If the original segment's end connects to the next segment,- // the loop traverses forward → [seg1, seg2]- // Otherwise backward → [seg2, seg1]- const endConnectsToNext = origSeg.end === nextSeg.start || origSeg.end === nextSeg.end-- if (endConnectsToNext) {- result.push(...newSegIndices)- } else {- // Backward traversal — reverse the replacement order- result.push(...[...newSegIndices].reverse())- }- }- return result- })- }))-}-// ---------------------------------------------------------------------------// Handle mirroring// ---------------------------------------------------------------------------@@ -870,91 +466,4 @@ export function findAllHandles(* Find connected components in a VectorNetwork.* Returns arrays of vertex indices for each component.*/-export function findConnectedComponents(network: VectorNetwork): number[][] {- const n = network.vertices.length- if (n === 0) return []-- const adj = new Map<number, Set<number>>()- for (const seg of network.segments) {- if (!adj.has(seg.start)) adj.set(seg.start, new Set())- if (!adj.has(seg.end)) adj.set(seg.end, new Set())- const from = adj.get(seg.start)- const to = adj.get(seg.end)- if (!from || !to) continue- from.add(seg.end)- to.add(seg.start)- }-- const visited = new Set<number>()- const components: number[][] = []-- for (let i = 0; i < n; i++) {- if (visited.has(i)) continue- const component: number[] = []- const stack = [i]- while (stack.length > 0) {- const v = stack.pop()- if (v === undefined) continue- if (visited.has(v)) continue- visited.add(v)- component.push(v)- const neighbors = adj.get(v)- if (neighbors) {- for (const nb of neighbors) {- if (!visited.has(nb)) stack.push(nb)- }- }- }- components.push(component)- }-- return components-}--/**- * Extract a sub-network from a VectorNetwork given a set of vertex indices.- */-export function extractSubNetwork(network: VectorNetwork, vertexIndices: number[]): VectorNetwork {- const indexSet = new Set(vertexIndices)- const oldToNew = new Map<number, number>()- const newVertices: VectorVertex[] = []-- for (const idx of vertexIndices) {- oldToNew.set(idx, newVertices.length)- newVertices.push({ ...network.vertices[idx] })- }-- const newSegments: VectorSegment[] = []- const segOldToNew = new Map<number, number>()-- for (let i = 0; i < network.segments.length; i++) {- const s = network.segments[i]- if (indexSet.has(s.start) && indexSet.has(s.end)) {- segOldToNew.set(i, newSegments.length)- const start = oldToNew.get(s.start)- const end = oldToNew.get(s.end)- if (start === undefined || end === undefined) continue- newSegments.push({- start,- end,- tangentStart: { ...s.tangentStart },- tangentEnd: { ...s.tangentEnd }- })- }- }-- // Remap regions- const newRegions: VectorRegion[] = []- for (const region of network.regions) {- const newLoops: number[][] = []- for (const loop of region.loops) {- const newLoop = loop- .map((i) => segOldToNew.get(i))- .filter((i): i is number => i !== undefined)- if (newLoop.length >= 2) newLoops.push(newLoop)- }- if (newLoops.length > 0) newRegions.push({ ...region, loops: newLoops })- }-- return { vertices: newVertices, segments: newSegments, regions: newRegions }-}+export { extractSubNetwork, findConnectedComponents } from './connectivity'diff --git a/packages/core/src/vector/connectivity.ts b/packages/core/src/vector/connectivity.tsnew file mode 100644index 000000000..1736a59a2--- /dev/null+++ b/packages/core/src/vector/connectivity.ts@@ -0,0 +1,90 @@+import type { VectorNetwork, VectorRegion, VectorSegment, VectorVertex } from '#core/scene-graph'++export function findConnectedComponents(network: VectorNetwork): number[][] {+ const n = network.vertices.length+ if (n === 0) return []++ const adj = new Map<number, Set<number>>()+ for (const seg of network.segments) {+ if (!adj.has(seg.start)) adj.set(seg.start, new Set())+ if (!adj.has(seg.end)) adj.set(seg.end, new Set())+ const from = adj.get(seg.start)+ const to = adj.get(seg.end)+ if (!from || !to) continue+ from.add(seg.end)+ to.add(seg.start)+ }++ const visited = new Set<number>()+ const components: number[][] = []++ for (let i = 0; i < n; i++) {+ if (visited.has(i)) continue+ const component: number[] = []+ const stack = [i]+ while (stack.length > 0) {+ const v = stack.pop()+ if (v === undefined) continue+ if (visited.has(v)) continue+ visited.add(v)+ component.push(v)+ const neighbors = adj.get(v)+ if (neighbors) {+ for (const nb of neighbors) {+ if (!visited.has(nb)) stack.push(nb)+ }+ }+ }+ components.push(component)+ }++ return components+}++/**+ * Extract a sub-network from a VectorNetwork given a set of vertex indices.+ */+export function extractSubNetwork(network: VectorNetwork, vertexIndices: number[]): VectorNetwork {+ const indexSet = new Set(vertexIndices)+ const oldToNew = new Map<number, number>()+ const newVertices: VectorVertex[] = []++ for (const idx of vertexIndices) {+ oldToNew.set(idx, newVertices.length)+ newVertices.push({ ...network.vertices[idx] })+ }++ const newSegments: VectorSegment[] = []+ const segOldToNew = new Map<number, number>()++ for (let i = 0; i < network.segments.length; i++) {+ const s = network.segments[i]+ if (indexSet.has(s.start) && indexSet.has(s.end)) {+ segOldToNew.set(i, newSegments.length)+ const start = oldToNew.get(s.start)+ const end = oldToNew.get(s.end)+ if (start === undefined || end === undefined) continue+ newSegments.push({+ start,+ end,+ tangentStart: { ...s.tangentStart },+ tangentEnd: { ...s.tangentEnd }+ })+ }+ }++ // Remap regions+ const newRegions: VectorRegion[] = []+ for (const region of network.regions) {+ const newLoops: number[][] = []+ for (const loop of region.loops) {+ const newLoop = loop+ .map((i) => segOldToNew.get(i))+ .filter((i): i is number => i !== undefined)+ if (newLoop.length >= 2) newLoops.push(newLoop)+ }+ if (newLoops.length > 0) newRegions.push({ ...region, loops: newLoops })+ }++ return { vertices: newVertices, segments: newSegments, regions: newRegions }+}diff --git a/packages/core/src/vector/curve-math.ts b/packages/core/src/vector/curve-math.tsnew file mode 100644index 000000000..94e6d094c--- /dev/null+++ b/packages/core/src/vector/curve-math.ts@@ -0,0 +1,328 @@+import type { VectorNetwork, VectorSegment } from '#core/scene-graph'+import type { Vector, Rect } from '#core/types'++export interface CubicPoints {+ p0: Vector+ cp1: Vector+ cp2: Vector+ p3: Vector+}++export interface NearestResult {+ t: number+ x: number+ y: number+ distance: number+}++export interface NetworkNearestResult extends NearestResult {+ segmentIndex: number+}++// ---------------------------------------------------------------------------+// De Casteljau evaluation+// ---------------------------------------------------------------------------++/** Evaluate a cubic bezier at parameter t (0..1). */+export function evalCubic(+ p0x: number,+ p0y: number,+ p1x: number,+ p1y: number,+ p2x: number,+ p2y: number,+ p3x: number,+ p3y: number,+ t: number+): Vector {+ const mt = 1 - t+ const mt2 = mt * mt+ const t2 = t * t+ const a = mt2 * mt+ const b = 3 * mt2 * t+ const c = 3 * mt * t2+ const d = t2 * t+ return {+ x: a * p0x + b * p1x + c * p2x + d * p3x,+ y: a * p0y + b * p1y + c * p2y + d * p3y+ }+}++// ---------------------------------------------------------------------------+// Curve splitting (De Casteljau subdivision)+// ---------------------------------------------------------------------------++/** Split a cubic bezier at parameter t, returning two sub-curves. */+export function splitCubicAt(+ p0: Vector,+ cp1: Vector,+ cp2: Vector,+ p3: Vector,+ t: number+): { left: CubicPoints; right: CubicPoints } {+ const mt = 1 - t++ // Level 1+ const m01x = mt * p0.x + t * cp1.x+ const m01y = mt * p0.y + t * cp1.y+ const m12x = mt * cp1.x + t * cp2.x+ const m12y = mt * cp1.y + t * cp2.y+ const m23x = mt * cp2.x + t * p3.x+ const m23y = mt * cp2.y + t * p3.y++ // Level 2+ const m012x = mt * m01x + t * m12x+ const m012y = mt * m01y + t * m12y+ const m123x = mt * m12x + t * m23x+ const m123y = mt * m12y + t * m23y++ // Level 3 — the split point+ const mx = mt * m012x + t * m123x+ const my = mt * m012y + t * m123y++ return {+ left: {+ p0: { x: p0.x, y: p0.y },+ cp1: { x: m01x, y: m01y },+ cp2: { x: m012x, y: m012y },+ p3: { x: mx, y: my }+ },+ right: {+ p0: { x: mx, y: my },+ cp1: { x: m123x, y: m123y },+ cp2: { x: m23x, y: m23y },+ p3: { x: p3.x, y: p3.y }+ }+ }+}++// ---------------------------------------------------------------------------+// Segment ↔ absolute control points conversion+// ---------------------------------------------------------------------------++/** Convert a VectorSegment's relative tangents to absolute control points. */+export function segmentToAbsolute(network: VectorNetwork, segmentIndex: number): CubicPoints {+ const seg = network.segments[segmentIndex]+ const v0 = network.vertices[seg.start]+ const v1 = network.vertices[seg.end]+ return {+ p0: { x: v0.x, y: v0.y },+ cp1: { x: v0.x + seg.tangentStart.x, y: v0.y + seg.tangentStart.y },+ cp2: { x: v1.x + seg.tangentEnd.x, y: v1.y + seg.tangentEnd.y },+ p3: { x: v1.x, y: v1.y }+ }+}++/** Check if a segment is a straight line (both tangents zero). */+export function isLineSegment(seg: VectorSegment): boolean {+ return (+ seg.tangentStart.x === 0 &&+ seg.tangentStart.y === 0 &&+ seg.tangentEnd.x === 0 &&+ seg.tangentEnd.y === 0+ )+}++// ---------------------------------------------------------------------------+// Accurate bezier bounds via cubic extrema+// ---------------------------------------------------------------------------++/**+ * Find parameter values where the cubic derivative is zero (extrema) in one axis.+ * Given cubic coefficients for one axis: B(t) = (1-t)^3*p0 + 3(1-t)^2*t*p1 + 3(1-t)*t^2*p2 + t^3*p3+ * Derivative: B'(t) = 3[(1-t)^2(p1-p0) + 2(1-t)t(p2-p1) + t^2(p3-p2)]+ * Expanding: at^2 + bt + c = 0 where:+ * a = -p0 + 3p1 - 3p2 + p3+ * b = 2(p0 - 2p1 + p2)+ * c = -p0 + p1+ */+export function cubicExtrema(p0: number, p1: number, p2: number, p3: number): number[] {+ const a = -p0 + 3 * p1 - 3 * p2 + p3+ const b = 2 * (p0 - 2 * p1 + p2)+ const c = -p0 + p1++ const results: number[] = []+ const EPS = 1e-12++ if (Math.abs(a) < EPS) {+ // Linear: bt + c = 0+ if (Math.abs(b) > EPS) {+ const t = -c / b+ if (t > 0 && t < 1) results.push(t)+ }+ } else {+ const disc = b * b - 4 * a * c+ if (disc >= 0) {+ const sq = Math.sqrt(disc)+ const t1 = (-b + sq) / (2 * a)+ const t2 = (-b - sq) / (2 * a)+ if (t1 > 0 && t1 < 1) results.push(t1)+ if (t2 > 0 && t2 < 1 && Math.abs(t2 - t1) > EPS) results.push(t2)+ }+ }++ return results+}++/** Compute tight axis-aligned bounding box for a VectorNetwork. */+export function computeAccurateBounds(network: VectorNetwork): Rect {+ const { vertices, segments } = network+ if (vertices.length === 0) return { x: 0, y: 0, width: 0, height: 0 }++ let minX = Infinity,+ minY = Infinity,+ maxX = -Infinity,+ maxY = -Infinity++ const update = (x: number, y: number) => {+ if (x < minX) minX = x+ if (y < minY) minY = y+ if (x > maxX) maxX = x+ if (y > maxY) maxY = y+ }++ // Include all vertex positions+ for (const v of vertices) update(v.x, v.y)++ // For each segment, find curve extrema+ for (let i = 0; i < segments.length; i++) {+ const { p0, cp1, cp2, p3 } = segmentToAbsolute(network, i)++ // X extrema+ for (const t of cubicExtrema(p0.x, cp1.x, cp2.x, p3.x)) {+ const pt = evalCubic(p0.x, p0.y, cp1.x, cp1.y, cp2.x, cp2.y, p3.x, p3.y, t)+ update(pt.x, pt.y)+ }++ // Y extrema+ for (const t of cubicExtrema(p0.y, cp1.y, cp2.y, p3.y)) {+ const pt = evalCubic(p0.x, p0.y, cp1.x, cp1.y, cp2.x, cp2.y, p3.x, p3.y, t)+ update(pt.x, pt.y)+ }+ }++ return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }+}++// ---------------------------------------------------------------------------+// Nearest point on cubic bezier+// ---------------------------------------------------------------------------++/**+ * Find the nearest point on a cubic bezier to a given point (px, py).+ * Uses coarse sampling + iterative refinement.+ */+export function nearestPointOnCubic(+ px: number,+ py: number,+ p0: Vector,+ cp1: Vector,+ cp2: Vector,+ p3: Vector,+ coarseSamples: number = 64+): NearestResult {+ let bestT = 0+ let bestDist = Infinity++ // Coarse sampling+ for (let i = 0; i <= coarseSamples; i++) {+ const t = i / coarseSamples+ const pt = evalCubic(p0.x, p0.y, cp1.x, cp1.y, cp2.x, cp2.y, p3.x, p3.y, t)+ const dx = pt.x - px+ const dy = pt.y - py+ const d = dx * dx + dy * dy+ if (d < bestDist) {+ bestDist = d+ bestT = t+ }+ }++ // Refinement — bisect around best sample, 5 iterations+ let lo = Math.max(0, bestT - 1 / coarseSamples)+ let hi = Math.min(1, bestT + 1 / coarseSamples)++ for (let iter = 0; iter < 5; iter++) {+ const step = (hi - lo) / 4+ let localBestT = lo+ let localBestDist = Infinity++ for (let i = 0; i <= 4; i++) {+ const t = lo + step * i+ const pt = evalCubic(p0.x, p0.y, cp1.x, cp1.y, cp2.x, cp2.y, p3.x, p3.y, t)+ const dx = pt.x - px+ const dy = pt.y - py+ const d = dx * dx + dy * dy+ if (d < localBestDist) {+ localBestDist = d+ localBestT = t+ }+ }++ bestT = localBestT+ bestDist = localBestDist+ lo = Math.max(0, bestT - step)+ hi = Math.min(1, bestT + step)+ }++ const pt = evalCubic(p0.x, p0.y, cp1.x, cp1.y, cp2.x, cp2.y, p3.x, p3.y, bestT)+ return { t: bestT, x: pt.x, y: pt.y, distance: Math.sqrt(bestDist) }+}++/** Find nearest point on a straight line segment. */+function nearestPointOnLine(px: number, py: number, p0: Vector, p1: Vector): NearestResult {+ const dx = p1.x - p0.x+ const dy = p1.y - p0.y+ const lenSq = dx * dx + dy * dy++ let t: number+ if (lenSq < 1e-12) {+ t = 0+ } else {+ t = Math.max(0, Math.min(1, ((px - p0.x) * dx + (py - p0.y) * dy) / lenSq))+ }++ const x = p0.x + t * dx+ const y = p0.y + t * dy+ const ddx = x - px+ const ddy = y - py+ return { t, x, y, distance: Math.sqrt(ddx * ddx + ddy * ddy) }+}++/** Find nearest point across all segments in a VectorNetwork. */+export function nearestPointOnNetwork(+ px: number,+ py: number,+ network: VectorNetwork,+ threshold: number+): NetworkNearestResult | null {+ let best: NetworkNearestResult | null = null++ for (let i = 0; i < network.segments.length; i++) {+ const seg = network.segments[i]+ let result: NearestResult++ if (isLineSegment(seg)) {+ const v0 = network.vertices[seg.start]+ const v1 = network.vertices[seg.end]+ result = nearestPointOnLine(px, py, v0, v1)+ } else {+ const { p0, cp1, cp2, p3 } = segmentToAbsolute(network, i)+ result = nearestPointOnCubic(px, py, p0, cp1, cp2, p3)+ }++ if (result.distance <= threshold && (!best || result.distance < best.distance)) {+ best = { ...result, segmentIndex: i }+ }+ }++ return best+}++// ---------------------------------------------------------------------------+// Split segment within a VectorNetwork+// ---------------------------------------------------------------------------++/**+ * Split a segment in a VectorNetwork at parameter t, inserting a new vertex.+ * Returns a new VectorNetwork with updated vertices, segments, and regions.+ */\ No newline at end of filediff --git a/packages/core/src/vector/index.ts b/packages/core/src/vector/index.tsindex 6a376180d..463139e0e 100644--- a/packages/core/src/vector/index.ts+++ b/packages/core/src/vector/index.ts@@ -1,3 +1,15 @@+export {+ breakAtVertex,+ computeAccurateBounds,+ deleteVertex,+ findAllHandles,+ findOppositeHandle,+ mirrorHandle,+ nearestPointOnNetwork,+ removeVertex,+ splitSegmentAt+} from './bezier'+import { computeAccurateBounds } from './bezier'import type {@@ -7,8 +19,8 @@ import type {VectorSegment,VectorVertex,WindingRule-} from '../scene-graph'-import type { Rect } from '../types'+} from '#core/scene-graph'+import type { Rect } from '#core/types'import type { CanvasKit, Path } from 'canvaskit-wasm'// --- vectorNetworkBlob binary format ---diff --git a/packages/core/src/vector/regions.ts b/packages/core/src/vector/regions.tsnew file mode 100644index 000000000..07699e792--- /dev/null+++ b/packages/core/src/vector/regions.ts@@ -0,0 +1,67 @@+import type { VectorRegion, VectorSegment } from '#core/scene-graph'++export function remapRegions(+ regions: VectorRegion[],+ indexMap: Map<number, number | null>+): VectorRegion[] {+ const result: VectorRegion[] = []++ for (const region of regions) {+ const newLoops: number[][] = []+ for (const loop of region.loops) {+ const newLoop: number[] = []+ for (const idx of loop) {+ const mapped = indexMap.get(idx)+ if (mapped == null) continue+ if (newLoop.length > 0 && newLoop[newLoop.length - 1] === mapped) continue+ newLoop.push(mapped)+ }+ if (newLoop.length > 1 && newLoop[0] === newLoop[newLoop.length - 1]) {+ newLoop.pop()+ }+ if (newLoop.length >= 2) newLoops.push(newLoop)+ }+ if (newLoops.length > 0) {+ result.push({ ...region, loops: newLoops })+ }+ }++ return result+}++export function reindexRegionLoops(+ regions: VectorRegion[],+ oldSegIndex: number,+ newSegIndices: number[],+ segments?: VectorSegment[]+): VectorRegion[] {+ return regions.map((region) => ({+ ...region,+ loops: region.loops.map((loop) => {+ const result: number[] = []+ for (let i = 0; i < loop.length; i++) {+ if (loop[i] !== oldSegIndex) {+ result.push(loop[i])+ continue+ }++ if (!segments || newSegIndices.length < 2) {+ result.push(...newSegIndices)+ continue+ }++ const origSeg = segments[oldSegIndex]+ const nextIdx = loop[(i + 1) % loop.length]+ const nextSeg = segments[nextIdx]+ const endConnectsToNext = origSeg.end === nextSeg.start || origSeg.end === nextSeg.end++ if (endConnectsToNext) {+ result.push(...newSegIndices)+ } else {+ result.push(...[...newSegIndices].reverse())+ }+ }+ return result+ })+ }))+}diff --git a/packages/core/src/xpath.ts b/packages/core/src/xpath.tsindex 7939f76c3..a2d5c94fc 100644--- a/packages/core/src/xpath.ts+++ b/packages/core/src/xpath.ts@@ -143,6 +143,20 @@ function isDocument(node: unknown): node is XPathDocument {return (node as XPathDocument).nodeType === NODE_TYPES.DOCUMENT_NODE}+function siblingNode(+ graph: SceneGraph,+ node: XPathNode | XPathDocument,+ offset: -1 | 1+): XPathNode | null {+ if (isDocument(node)) return null+ const parent = node._parent+ if (!parent) return null+ const siblings = getChildren(graph, parent)+ const index = siblings.indexOf(node)+ if (index === -1) return null+ return siblings[index + offset] ?? null+}+function createDomFacade(graph: SceneGraph) {return {getAllAttributes(node: XPathNode | XPathDocument): XPathAttr[] {@@ -185,12 +199,7 @@ function createDomFacade(graph: SceneGraph) {},getNextSibling(node: XPathNode | XPathDocument): XPathNode | null {- if (isDocument(node)) return null- const parent = node._parent- if (!parent) return null- const siblings = getChildren(graph, parent)- const idx = siblings.indexOf(node)- return siblings[idx + 1] ?? null+ return siblingNode(graph, node, 1)},getParentNode(node: XPathNode | XPathDocument): XPathNode | XPathDocument | null {@@ -199,12 +208,7 @@ function createDomFacade(graph: SceneGraph) {},getPreviousSibling(node: XPathNode | XPathDocument): XPathNode | null {- if (isDocument(node)) return null- const parent = node._parent- if (!parent) return null- const siblings = getChildren(graph, parent)- const idx = siblings.indexOf(node)- return idx > 0 ? siblings[idx - 1] : null+ return siblingNode(graph, node, -1)}}}diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.jsonindex 11da7de6c..716238992 100644--- a/packages/core/tsconfig.json+++ b/packages/core/tsconfig.json@@ -14,6 +14,7 @@"outDir": "dist","rootDir": "src","paths": {+ "#core/*": ["./src/*"],"@open-pencil/core": ["./src/index.ts"],"@open-pencil/core/*": ["./src/*"]}diff --git a/packages/core/tsdown.config.ts b/packages/core/tsdown.config.tsindex 5da13f67a..5f54ce3da 100644--- a/packages/core/tsdown.config.ts+++ b/packages/core/tsdown.config.ts@@ -22,20 +22,23 @@ export default defineConfig({sourcemap: true,clean: true,outDir: './dist',- external: [- '@iconify/utils',- 'canvaskit-wasm',- 'culori',- 'diff',- 'expr-eval',- 'fflate',- 'fontoxpath',- 'fzstd',- 'nanoevents',- 'opentype.js',- 'sucrase',- 'svgpath',- 'yoga-layout',- /^node:/- ]+ deps: {+ neverBundle: [+ '@iconify/utils',+ 'canvaskit-wasm',+ 'culori',+ 'diff',+ 'expr-eval',+ 'fflate',+ 'fontoxpath',+ 'fzstd',+ 'nanoevents',+ 'opentype.js',+ 'sucrase',+ 'svgpath',+ 'yoga-layout',+ /^node:/+ ],+ onlyBundle: false+ }})diff --git a/packages/docs/.vitepress/config.ts b/packages/docs/.vitepress/config.tsindex a211d8268..c5a0f8416 100644--- a/packages/docs/.vitepress/config.ts+++ b/packages/docs/.vitepress/config.ts@@ -1,514 +1,27 @@-import { defineConfig, type DefaultTheme } from 'vitepress'+import { defineConfig } from 'vitepress'-interface SidebarLabels {- gettingAround: string- creatingContent: string- organizing: string- advanced: string- canvasNav: string- selection: string- shapes: string- text: string- pen: string- layers: string- contextMenu: string- exporting: string- autoLayout: string- components: string- variables: string- guide: string- gettingStarted: string- features: string- architecture: string- techStack: string- comparison: string- figmaMatrix: string-}--interface ProgrammableLabels {- overview: string- cli: string- inspecting: string- exporting: string- analyzing: string- scripting: string- jsxRenderer: string- mcpServer: string- aiChat: string- collaboration: string-}--interface NavLabels {- guide: string- userGuide: string- programmable: string- sdk: string- reference: string- development: string- openApp: string-}--const SDK_COMPONENT_PAGES = [- { text: 'CanvasRoot', slug: 'canvas-root' },- { text: 'CanvasSurface', slug: 'canvas-surface' },- { text: 'LayerTreeRoot', slug: 'layer-tree-root' },- { text: 'LayerTreeItem', slug: 'layer-tree-item' },- { text: 'ToolbarRoot', slug: 'toolbar-root' },- { text: 'ToolbarItem', slug: 'toolbar-item' },- { text: 'PageListRoot', slug: 'page-list-root' },- { text: 'PropertyListRoot', slug: 'property-list-root' },- { text: 'PropertyListItem', slug: 'property-list-item' },- { text: 'ColorPickerRoot', slug: 'color-picker-root' },- { text: 'ColorInputRoot', slug: 'color-input-root' },- { text: 'FillPickerRoot', slug: 'fill-picker-root' },- { text: 'FontPickerRoot', slug: 'font-picker-root' },- { text: 'GradientEditorRoot', slug: 'gradient-editor-root' },- { text: 'GradientEditorBar', slug: 'gradient-editor-bar' },- { text: 'GradientEditorStop', slug: 'gradient-editor-stop' },- { text: 'ScrubInputRoot', slug: 'scrub-input-root' },- { text: 'ScrubInputField', slug: 'scrub-input-field' },- { text: 'ScrubInputDisplay', slug: 'scrub-input-display' },- { text: 'LayoutControlsRoot', slug: 'layout-controls-root' },- { text: 'AppearanceControlsRoot', slug: 'appearance-controls-root' },- { text: 'PositionControlsRoot', slug: 'position-controls-root' },- { text: 'TypographyControlsRoot', slug: 'typography-controls-root' },-] as const--const SDK_COMPOSABLE_PAGES = [- { text: 'provideEditor', slug: 'provide-editor' },- { text: 'useEditor', slug: 'use-editor' },- { text: 'useCanvas', slug: 'use-canvas' },- { text: 'useCanvasInput', slug: 'use-canvas-input' },- { text: 'useTextEdit', slug: 'use-text-edit' },- { text: 'useSelectionState', slug: 'use-selection-state' },- { text: 'useSelectionCapabilities', slug: 'use-selection-capabilities' },- { text: 'useEditorCommands', slug: 'use-editor-commands' },- { text: 'useMenuModel', slug: 'use-menu-model' },- { text: 'usePosition', slug: 'use-position' },- { text: 'useLayout', slug: 'use-layout' },- { text: 'useAppearance', slug: 'use-appearance' },- { text: 'useTypography', slug: 'use-typography' },- { text: 'useExport', slug: 'use-export' },- { text: 'useFillControls', slug: 'use-fill-controls' },- { text: 'useStrokeControls', slug: 'use-stroke-controls' },- { text: 'useEffectsControls', slug: 'use-effects-controls' },- { text: 'useVariablesEditor', slug: 'use-variables-editor' },- { text: 'usePageList', slug: 'use-page-list' },-] as const--const SDK_ADVANCED_PAGES = [- { text: 'useNodeProps', slug: 'use-node-props' },- { text: 'useSceneComputed', slug: 'use-scene-computed' },- { text: 'useFillVariableBinding', slug: 'use-fill-variable-binding' },- { text: 'useFillPicker', slug: 'use-fill-picker' },- { text: 'useGradientStops', slug: 'use-gradient-stops' },- { text: 'useFontPicker', slug: 'use-font-picker' },- { text: 'usePropScrub', slug: 'use-prop-scrub' },- { text: 'useLayerDrag', slug: 'use-layer-drag' },- { text: 'useInlineRename', slug: 'use-inline-rename' },- { text: 'useToolbarState', slug: 'use-toolbar-state' },- { text: 'useNodeFontStatus', slug: 'use-node-font-status' },- { text: 'useCanvasDrop', slug: 'use-canvas-drop' },- { text: 'extractImageFilesFromClipboard', slug: 'extract-image-files-from-clipboard' },- { text: 'toolCursor', slug: 'tool-cursor' },- { text: 'useCanvasContext', slug: 'use-canvas-context' },- { text: 'useLayerTree', slug: 'use-layer-tree' },- { text: 'useToolbar', slug: 'use-toolbar' },- { text: 'usePropertyList', slug: 'use-property-list' },- { text: 'useScrubInput', slug: 'use-scrub-input' },-] as const--const userGuideSidebar = (prefix: string, l: SidebarLabels): DefaultTheme.SidebarItem[] => [- {- text: l.gettingAround,- items: [- { text: l.canvasNav, link: `${prefix}/user-guide/canvas-navigation` },- { text: l.selection, link: `${prefix}/user-guide/selection-and-manipulation` },- ],- },- {- text: l.creatingContent,- items: [- { text: l.shapes, link: `${prefix}/user-guide/drawing-shapes` },- { text: l.text, link: `${prefix}/user-guide/text-editing` },- { text: l.pen, link: `${prefix}/user-guide/pen-tool` },- ],- },- {- text: l.organizing,- items: [- { text: l.layers, link: `${prefix}/user-guide/layers-and-pages` },- { text: l.exporting, link: `${prefix}/user-guide/exporting` },- ],- },- {- text: l.advanced,- items: [- { text: l.autoLayout, link: `${prefix}/user-guide/auto-layout` },- { text: l.components, link: `${prefix}/user-guide/components` },- { text: l.variables, link: `${prefix}/user-guide/variables` },- ],- },-]--const programmableSidebar = (- prefix: string,- p: ProgrammableLabels,-): DefaultTheme.SidebarItem[] => [- {- text: p.overview,- link: `${prefix}/programmable/`,- },- {- text: p.aiChat,- link: `${prefix}/programmable/ai-chat`,- },- {- text: p.collaboration,- link: `${prefix}/programmable/collaboration`,- },- {- text: p.jsxRenderer,- link: `${prefix}/programmable/jsx-renderer`,- },- {- text: p.cli,- items: [- { text: p.inspecting, link: `${prefix}/programmable/cli/inspecting` },- { text: p.exporting, link: `${prefix}/programmable/cli/exporting` },- { text: p.analyzing, link: `${prefix}/programmable/cli/analyzing` },- { text: p.scripting, link: `${prefix}/programmable/cli/scripting` },- ],- },- {- text: p.mcpServer,- link: `${prefix}/programmable/mcp-server`,- },-]---const sdkSidebar = (prefix: string): DefaultTheme.SidebarItem[] => [- {- text: 'Vue SDK',- items: [- { text: 'Overview', link: `${prefix}/programmable/sdk/` },- { text: 'Getting Started', link: `${prefix}/programmable/sdk/getting-started` },- { text: 'Architecture', link: `${prefix}/programmable/sdk/architecture` },- { text: 'Custom Shell', link: `${prefix}/programmable/sdk/guides/custom-editor-shell` },- { text: 'Property Panels', link: `${prefix}/programmable/sdk/guides/property-panels` },- { text: 'Navigation Panels', link: `${prefix}/programmable/sdk/guides/navigation-panels` },- {- text: 'API Reference',- items: [- { text: 'Overview', link: `${prefix}/programmable/sdk/api/` },- {- text: 'Components',- items: [- { text: 'Overview', link: `${prefix}/programmable/sdk/api/components/` },- ...SDK_COMPONENT_PAGES.map((page) => ({- text: page.text,- link: `${prefix}/programmable/sdk/api/components/${page.slug}`,- })),- ],- },- {- text: 'Composables',- items: [- { text: 'Overview', link: `${prefix}/programmable/sdk/api/composables/` },- ...SDK_COMPOSABLE_PAGES.map((page) => ({- text: page.text,- link: `${prefix}/programmable/sdk/api/composables/${page.slug}`,- })),- ],- },- {- text: 'Advanced',- items: [- { text: 'Overview', link: `${prefix}/programmable/sdk/api/advanced/` },- ...SDK_ADVANCED_PAGES.map((page) => ({- text: page.text,- link: `${prefix}/programmable/sdk/api/advanced/${page.slug}`,- })),- ],- },- ],- },- ],- },-]--const guideSidebar = (prefix: string, l: SidebarLabels): DefaultTheme.SidebarItem[] => [- {- text: l.guide,- items: [- { text: l.gettingStarted, link: `${prefix}/guide/getting-started` },- { text: l.features, link: `${prefix}/guide/features` },- { text: l.architecture, link: `${prefix}/guide/architecture` },- { text: l.techStack, link: `${prefix}/guide/tech-stack` },- { text: l.comparison, link: `${prefix}/guide/comparison` },- { text: l.figmaMatrix, link: `${prefix}/guide/figma-comparison` },- ],- },-]--const referenceSidebar = (prefix: string, label: string): DefaultTheme.SidebarItem[] => [- {- text: label,- items: [- { text: 'Keyboard Shortcuts', link: `${prefix}/reference/keyboard-shortcuts` },- { text: 'CLI', link: `${prefix}/reference/cli` },- { text: 'Node Types', link: `${prefix}/reference/node-types` },- { text: 'Scene Graph', link: `${prefix}/reference/scene-graph` },- { text: 'File Format', link: `${prefix}/reference/file-format` },- ],- },-]--const developmentSidebar = (prefix: string, label: string): DefaultTheme.SidebarItem[] => [- {- text: label,- items: [- { text: 'Contributing', link: `${prefix}/development/contributing` },- { text: 'Testing', link: `${prefix}/development/testing` },- { text: 'OpenSpec', link: `${prefix}/development/openspec` },- { text: 'Roadmap', link: `${prefix}/development/roadmap` },- ],- },-]--const EN_PROG: ProgrammableLabels = { overview: 'Overview', cli: 'CLI', inspecting: 'Inspecting Files', exporting: 'Exporting', analyzing: 'Analyzing Designs', scripting: 'Scripting', jsxRenderer: 'JSX Renderer', mcpServer: 'MCP Server', aiChat: 'AI Chat', collaboration: 'Collaboration' }-const DE_PROG: ProgrammableLabels = { overview: 'Überblick', cli: 'CLI', inspecting: 'Dateien inspizieren', exporting: 'Exportieren', analyzing: 'Designs analysieren', scripting: 'Skripte', jsxRenderer: 'JSX-Renderer', mcpServer: 'MCP-Server', aiChat: 'KI-Chat', collaboration: 'Zusammenarbeit' }-const IT_PROG: ProgrammableLabels = { overview: 'Panoramica', cli: 'CLI', inspecting: 'Ispezione file', exporting: 'Esportazione', analyzing: 'Analisi design', scripting: 'Scripting', jsxRenderer: 'Renderer JSX', mcpServer: 'Server MCP', aiChat: 'Chat IA', collaboration: 'Collaborazione' }-const FR_PROG: ProgrammableLabels = { overview: 'Vue d’ensemble', cli: 'CLI', inspecting: 'Inspecter les fichiers', exporting: 'Exporter', analyzing: 'Analyser les designs', scripting: 'Scripts', jsxRenderer: 'Moteur JSX', mcpServer: 'Serveur MCP', aiChat: 'Chat IA', collaboration: 'Collaboration' }-const ES_PROG: ProgrammableLabels = { overview: 'Resumen', cli: 'CLI', inspecting: 'Inspeccionar archivos', exporting: 'Exportar', analyzing: 'Analizar diseños', scripting: 'Scripts', jsxRenderer: 'Renderizador JSX', mcpServer: 'Servidor MCP', aiChat: 'Chat IA', collaboration: 'Colaboración' }-const PL_PROG: ProgrammableLabels = { overview: 'Przegląd', cli: 'CLI', inspecting: 'Inspekcja plików', exporting: 'Eksportowanie', analyzing: 'Analiza projektów', scripting: 'Skrypty', jsxRenderer: 'Renderer JSX', mcpServer: 'Serwer MCP', aiChat: 'Czat AI', collaboration: 'Współpraca' }-const RU_PROG: ProgrammableLabels = { overview: 'Обзор', cli: 'CLI', inspecting: 'Инспекция файлов', exporting: 'Экспорт', analyzing: 'Анализ дизайна', scripting: 'Скрипты', jsxRenderer: 'JSX-рендерер', mcpServer: 'MCP-сервер', aiChat: 'ИИ-чат', collaboration: 'Совместная работа' }--const localeThemeConfig = (- prefix: string,- nav: NavLabels,- sidebar: SidebarLabels,- prog: ProgrammableLabels,-): DefaultTheme.Config => ({- nav: [- { text: nav.guide, link: `${prefix}/guide/getting-started` },- { text: nav.userGuide, link: `${prefix}/user-guide/` },- { text: nav.programmable, link: `${prefix}/programmable/` },- { text: nav.sdk, link: `${prefix}/programmable/sdk/` },- { text: nav.reference, link: `${prefix}/reference/keyboard-shortcuts` },- { text: nav.development, link: `${prefix}/development/contributing` },- { text: nav.openApp, link: 'https://app.openpencil.dev' },- ],- sidebar: {- [`${prefix}/user-guide/`]: userGuideSidebar(prefix, sidebar),- [`${prefix}/programmable/sdk/`]: sdkSidebar(prefix),- [`${prefix}/programmable/`]: programmableSidebar(prefix, prog),- [`${prefix}/reference/`]: referenceSidebar(prefix, nav.reference),- [`${prefix}/`]: [- ...guideSidebar(prefix, sidebar),- ...developmentSidebar(prefix, nav.development),- ],- },-})--const EN: SidebarLabels = { gettingAround: 'Getting Around', creatingContent: 'Creating Content', organizing: 'Organizing & Managing', advanced: 'Advanced Features', canvasNav: 'Canvas Navigation', selection: 'Selection & Manipulation', shapes: 'Drawing Shapes', text: 'Text Editing', pen: 'Pen Tool', layers: 'Layers & Pages', contextMenu: 'Context Menu', exporting: 'Exporting', autoLayout: 'Auto Layout', components: 'Components', variables: 'Variables', guide: 'Guide', gettingStarted: 'Getting Started', features: 'Features', architecture: 'Architecture', techStack: 'Tech Stack', comparison: 'Comparison', figmaMatrix: 'Figma Feature Matrix' }--const DE: SidebarLabels = { gettingAround: 'Erste Schritte', creatingContent: 'Inhalte erstellen', organizing: 'Organisieren', advanced: 'Erweitert', canvasNav: 'Canvas-Navigation', selection: 'Auswahl & Bearbeitung', shapes: 'Formen zeichnen', text: 'Textbearbeitung', pen: 'Stiftwerkzeug', layers: 'Ebenen & Seiten', contextMenu: 'Kontextmenü', exporting: 'Exportieren', autoLayout: 'Auto-Layout', components: 'Komponenten', variables: 'Variablen', guide: 'Anleitung', gettingStarted: 'Erste Schritte', features: 'Funktionen', architecture: 'Architektur', techStack: 'Tech-Stack', comparison: 'Vergleich', figmaMatrix: 'Figma-Funktionsmatrix' }--const IT: SidebarLabels = { gettingAround: 'Orientamento', creatingContent: 'Creazione contenuti', organizing: 'Organizzazione', advanced: 'Avanzate', canvasNav: 'Navigazione canvas', selection: 'Selezione e manipolazione', shapes: 'Disegno forme', text: 'Modifica testo', pen: 'Strumento penna', layers: 'Livelli e pagine', contextMenu: 'Menu contestuale', exporting: 'Esportazione', autoLayout: 'Auto-layout', components: 'Componenti', variables: 'Variabili', guide: 'Guida', gettingStarted: 'Per iniziare', features: 'Funzionalità', architecture: 'Architettura', techStack: 'Stack tecnologico', comparison: 'Confronto', figmaMatrix: 'Matrice funzionalità Figma' }--const FR: SidebarLabels = { gettingAround: 'Prise en main', creatingContent: 'Création de contenu', organizing: 'Organisation', advanced: 'Avancé', canvasNav: 'Navigation sur le canevas', selection: 'Sélection et manipulation', shapes: 'Dessiner des formes', text: 'Édition de texte', pen: 'Outil plume', layers: 'Calques et pages', contextMenu: 'Menu contextuel', exporting: 'Exportation', autoLayout: 'Mise en page auto', components: 'Composants', variables: 'Variables', guide: 'Guide', gettingStarted: 'Premiers pas', features: 'Fonctionnalités', architecture: 'Architecture', techStack: 'Stack technique', comparison: 'Comparaison', figmaMatrix: 'Matrice des fonctionnalités Figma' }--const ES: SidebarLabels = { gettingAround: 'Orientación', creatingContent: 'Crear contenido', organizing: 'Organizar', advanced: 'Avanzado', canvasNav: 'Navegación del lienzo', selection: 'Selección y manipulación', shapes: 'Dibujar formas', text: 'Edición de texto', pen: 'Herramienta pluma', layers: 'Capas y páginas', contextMenu: 'Menú contextual', exporting: 'Exportar', autoLayout: 'Auto-layout', components: 'Componentes', variables: 'Variables', guide: 'Guía', gettingStarted: 'Primeros pasos', features: 'Características', architecture: 'Arquitectura', techStack: 'Stack tecnológico', comparison: 'Comparación', figmaMatrix: 'Matriz de funcionalidades Figma' }--const PL: SidebarLabels = { gettingAround: 'Nawigacja', creatingContent: 'Tworzenie treści', organizing: 'Organizacja', advanced: 'Zaawansowane', canvasNav: 'Nawigacja po płótnie', selection: 'Zaznaczanie i edycja', shapes: 'Rysowanie kształtów', text: 'Edycja tekstu', pen: 'Narzędzie pióro', layers: 'Warstwy i strony', contextMenu: 'Menu kontekstowe', exporting: 'Eksportowanie', autoLayout: 'Auto-layout', components: 'Komponenty', variables: 'Zmienne', guide: 'Przewodnik', gettingStarted: 'Rozpoczęcie pracy', features: 'Funkcje', architecture: 'Architektura', techStack: 'Stack technologiczny', comparison: 'Porównanie', figmaMatrix: 'Matryca funkcji Figma' }--const RU: SidebarLabels = { gettingAround: 'Навигация', creatingContent: 'Создание контента', organizing: 'Организация', advanced: 'Продвинутые функции', canvasNav: 'Навигация по холсту', selection: 'Выделение и редактирование', shapes: 'Рисование фигур', text: 'Редактирование текста', pen: 'Инструмент «Перо»', layers: 'Слои и страницы', contextMenu: 'Контекстное меню', exporting: 'Экспорт', autoLayout: 'Авто-раскладка', components: 'Компоненты', variables: 'Переменные', guide: 'Руководство', gettingStarted: 'Начало работы', features: 'Возможности', architecture: 'Архитектура', techStack: 'Технологии', comparison: 'Сравнение', figmaMatrix: 'Матрица функций Figma' }--const BASE = 'https://openpencil.dev'--const LOCALE_PREFIXES = ['de', 'fr', 'es', 'it', 'pl', 'ru'] as const--const LOCALES: Record<string, { hreflang: string; ogLocale: string; prefix: string }> = {- en: { hreflang: 'en', ogLocale: 'en_US', prefix: '' },- de: { hreflang: 'de', ogLocale: 'de_DE', prefix: '/de' },- fr: { hreflang: 'fr', ogLocale: 'fr_FR', prefix: '/fr' },- es: { hreflang: 'es', ogLocale: 'es_ES', prefix: '/es' },- it: { hreflang: 'it', ogLocale: 'it_IT', prefix: '/it' },- pl: { hreflang: 'pl', ogLocale: 'pl_PL', prefix: '/pl' },- ru: { hreflang: 'ru', ogLocale: 'ru_RU', prefix: '/ru' },-}+import { docsLocales } from './locales'+import { rootThemeConfig } from './root-theme'+import { BASE, applyPageSeo, siteHead, withAlternateSitemapLinks } from './seo'export default defineConfig({title: 'OpenPencil',- description: 'Open-source, AI-native design editor. Figma alternative built from scratch with full .fig file compatibility.',+ description:+ 'Open-source, AI-native design editor. Figma alternative built from scratch with full .fig file compatibility.',cleanUrls: true,lastUpdated: true,appearance: 'dark',sitemap: {hostname: BASE,- transformItems(items) {- return items.map((item) => {- const localeKey = LOCALE_PREFIXES.find((p) => item.url.startsWith(p + '/')) ?? 'en'- const slug = item.url- .replace(new RegExp(`^(${LOCALE_PREFIXES.join('|')})/`), '')- .replace(/\/$/, '')-- return {- ...item,- links: Object.entries(LOCALES).map(([, loc]) => {- const url = slug ? `${BASE}${loc.prefix}/${slug}` : `${BASE}${loc.prefix || '/'}`- return { lang: loc.hreflang, url }- }),- }- })- },+ transformItems: withAlternateSitemapLinks,},- head: [- ['link', { rel: 'icon', type: 'image/png', href: '/favicon.png' }],- ['meta', { property: 'og:type', content: 'website' }],- ['meta', { property: 'og:site_name', content: 'OpenPencil' }],- ['meta', { property: 'og:image', content: `${BASE}/screenshot.png` }],- ['meta', { property: 'og:image:width', content: '2784' }],- ['meta', { property: 'og:image:height', content: '1824' }],- ['meta', { property: 'og:image:alt', content: 'OpenPencil — AI-Native Design Editor' }],- ['meta', { name: 'twitter:card', content: 'summary_large_image' }],- ['meta', { name: 'twitter:site', content: '@openpencildev' }],- ['meta', { name: 'twitter:image', content: `${BASE}/screenshot.png` }],- ],-- transformPageData(pageData) {- const rel = pageData.relativePath-- const localeKey = (LOCALE_PREFIXES.find((p) => rel.startsWith(p + '/')) as string) ?? 'en'- const locale = LOCALES[localeKey]-- const slug = rel- .replace(new RegExp(`^(${LOCALE_PREFIXES.join('|')})/`), '')- .replace(/\.md$/, '')- .replace(/\/index$/, '')- .replace(/^index$/, '')+ head: siteHead,- const pageUrl = slug ? `${BASE}${locale.prefix}/${slug}` : `${BASE}${locale.prefix || ''}`- const enSlug = slug ? `${BASE}/${slug}` : BASE+ transformPageData: applyPageSeo,- pageData.frontmatter.head ??= []- const h = pageData.frontmatter.head as [string, Record<string, string>][]+ locales: docsLocales,- h.push(['link', { rel: 'canonical', href: pageUrl }])- h.push(['meta', { property: 'og:url', content: pageUrl }])- h.push(['meta', { property: 'og:locale', content: locale.ogLocale }])-- for (const [key, loc] of Object.entries(LOCALES)) {- if (key !== localeKey) {- h.push(['meta', { property: 'og:locale:alternate', content: loc.ogLocale }])- }- }-- for (const [, loc] of Object.entries(LOCALES)) {- const altUrl = slug ? `${BASE}${loc.prefix}/${slug}` : `${BASE}${loc.prefix || ''}`- h.push(['link', { rel: 'alternate', hreflang: loc.hreflang, href: altUrl }])- }- h.push(['link', { rel: 'alternate', hreflang: 'x-default', href: enSlug }])-- if (pageData.title) {- const ogTitle = `${pageData.title} — OpenPencil`- h.push(['meta', { property: 'og:title', content: ogTitle }])- h.push(['meta', { name: 'twitter:title', content: ogTitle }])- }-- if (pageData.description) {- h.push(['meta', { property: 'og:description', content: pageData.description }])- h.push(['meta', { name: 'twitter:description', content: pageData.description }])- h.push(['meta', { name: 'description', content: pageData.description }])- }- },-- locales: {- root: {- label: 'English',- lang: 'en',- },- de: {- label: 'Deutsch',- lang: 'de',- description: 'Open-Source, KI-nativer Design-Editor. Figma-Alternative.',- themeConfig: localeThemeConfig('/de', { guide: 'Guide', userGuide: 'Benutzerhandbuch', programmable: 'Automation', sdk: 'SDK', reference: 'Referenz', development: 'Entwicklung', openApp: 'App öffnen' }, DE, DE_PROG),- },- it: {- label: 'Italiano',- lang: 'it',- description: 'Editor di design open-source, IA-nativo. Alternativa a Figma.',- themeConfig: localeThemeConfig('/it', { guide: 'Guida', userGuide: 'Guida utente', programmable: 'Automation', sdk: 'SDK', reference: 'Riferimento', development: 'Sviluppo', openApp: 'Apri app' }, IT, IT_PROG),- },- fr: {- label: 'Français',- lang: 'fr',- description: 'Éditeur de design open-source, IA-natif. Alternative à Figma.',- themeConfig: localeThemeConfig('/fr', { guide: 'Guide', userGuide: 'Guide utilisateur', programmable: 'Automation', sdk: 'SDK', reference: 'Référence', development: 'Développement', openApp: "Ouvrir l'app" }, FR, FR_PROG),- },- es: {- label: 'Español',- lang: 'es',- description: 'Editor de diseño open-source, IA-nativo. Alternativa a Figma.',- themeConfig: localeThemeConfig('/es', { guide: 'Guía', userGuide: 'Guía del usuario', programmable: 'Automation', sdk: 'SDK', reference: 'Referencia', development: 'Desarrollo', openApp: 'Abrir app' }, ES, ES_PROG),- },- pl: {- label: 'Polski',- lang: 'pl',- description: "Open-source'owy edytor graficzny z natywnym AI. Alternatywa dla Figmy.",- themeConfig: localeThemeConfig('/pl', { guide: 'Przewodnik', userGuide: 'Podręcznik', programmable: 'Automation', sdk: 'SDK', reference: 'Referencja', development: 'Rozwój', openApp: 'Otwórz app' }, PL, PL_PROG),- },- ru: {- label: 'Русский',- lang: 'ru',- description: 'Дизайн-редактор с открытым исходным кодом. Альтернатива Figma с встроенным ИИ.',- themeConfig: localeThemeConfig('/ru', { guide: 'Руководство', userGuide: 'Руководство', programmable: 'Automation', sdk: 'SDK', reference: 'Справочник', development: 'Разработка', openApp: 'Открыть приложение' }, RU, RU_PROG),- },- },-- themeConfig: {- search: { provider: 'local' },-- nav: [- { text: 'Guide', link: '/guide/getting-started' },- { text: 'User Guide', link: '/user-guide/' },- { text: 'Automation', link: '/programmable/' },- { text: 'SDK', link: '/programmable/sdk/' },- { text: 'Reference', link: '/reference/keyboard-shortcuts' },- { text: 'Development', link: '/development/contributing' },- { text: 'Open App', link: 'https://app.openpencil.dev' },- ],-- sidebar: {- '/user-guide/': userGuideSidebar('', EN),- '/programmable/sdk/': sdkSidebar(''),- '/programmable/': programmableSidebar('', EN_PROG),- '/reference/': referenceSidebar('', 'Reference'),- '/': [- ...guideSidebar('', EN),- {- text: 'Development',- items: [- { text: 'Contributing', link: '/development/contributing' },- { text: 'Testing', link: '/development/testing' },- { text: 'OpenSpec Workflow', link: '/development/openspec' },- { text: 'Roadmap', link: '/development/roadmap' },- ],- },- ],- },-- socialLinks: [{ icon: 'github', link: 'https://github.com/open-pencil/open-pencil' }],-- editLink: {- pattern: 'https://github.com/open-pencil/open-pencil/edit/main/packages/docs/:path',- },-- footer: {- message: 'Released under the MIT License.',- },- },+ themeConfig: rootThemeConfig(),})diff --git a/packages/docs/.vitepress/labels.ts b/packages/docs/.vitepress/labels.tsnew file mode 100644index 000000000..9f7de2e68--- /dev/null+++ b/packages/docs/.vitepress/labels.ts@@ -0,0 +1,301 @@+export interface SidebarLabels {+ gettingAround: string+ creatingContent: string+ organizing: string+ advanced: string+ canvasNav: string+ selection: string+ shapes: string+ text: string+ pen: string+ layers: string+ contextMenu: string+ exporting: string+ autoLayout: string+ components: string+ variables: string+ guide: string+ gettingStarted: string+ features: string+ architecture: string+ techStack: string+ comparison: string+ figmaMatrix: string+}++export interface ProgrammableLabels {+ overview: string+ cli: string+ inspecting: string+ exporting: string+ analyzing: string+ scripting: string+ jsxRenderer: string+ mcpServer: string+ aiChat: string+ collaboration: string+}++export interface NavLabels {+ guide: string+ userGuide: string+ programmable: string+ sdk: string+ reference: string+ development: string+ openApp: string+}++export const EN_PROG: ProgrammableLabels = {+ overview: 'Overview',+ cli: 'CLI',+ inspecting: 'Inspecting Files',+ exporting: 'Exporting',+ analyzing: 'Analyzing Designs',+ scripting: 'Scripting',+ jsxRenderer: 'JSX Renderer',+ mcpServer: 'MCP Server',+ aiChat: 'AI Chat',+ collaboration: 'Collaboration'+}+export const DE_PROG: ProgrammableLabels = {+ overview: 'Überblick',+ cli: 'CLI',+ inspecting: 'Dateien inspizieren',+ exporting: 'Exportieren',+ analyzing: 'Designs analysieren',+ scripting: 'Skripte',+ jsxRenderer: 'JSX-Renderer',+ mcpServer: 'MCP-Server',+ aiChat: 'KI-Chat',+ collaboration: 'Zusammenarbeit'+}+export const IT_PROG: ProgrammableLabels = {+ overview: 'Panoramica',+ cli: 'CLI',+ inspecting: 'Ispezione file',+ exporting: 'Esportazione',+ analyzing: 'Analisi design',+ scripting: 'Scripting',+ jsxRenderer: 'Renderer JSX',+ mcpServer: 'Server MCP',+ aiChat: 'Chat IA',+ collaboration: 'Collaborazione'+}+export const FR_PROG: ProgrammableLabels = {+ overview: 'Vue d’ensemble',+ cli: 'CLI',+ inspecting: 'Inspecter les fichiers',+ exporting: 'Exporter',+ analyzing: 'Analyser les designs',+ scripting: 'Scripts',+ jsxRenderer: 'Moteur JSX',+ mcpServer: 'Serveur MCP',+ aiChat: 'Chat IA',+ collaboration: 'Collaboration'+}+export const ES_PROG: ProgrammableLabels = {+ overview: 'Resumen',+ cli: 'CLI',+ inspecting: 'Inspeccionar archivos',+ exporting: 'Exportar',+ analyzing: 'Analizar diseños',+ scripting: 'Scripts',+ jsxRenderer: 'Renderizador JSX',+ mcpServer: 'Servidor MCP',+ aiChat: 'Chat IA',+ collaboration: 'Colaboración'+}+export const PL_PROG: ProgrammableLabels = {+ overview: 'Przegląd',+ cli: 'CLI',+ inspecting: 'Inspekcja plików',+ exporting: 'Eksportowanie',+ analyzing: 'Analiza projektów',+ scripting: 'Skrypty',+ jsxRenderer: 'Renderer JSX',+ mcpServer: 'Serwer MCP',+ aiChat: 'Czat AI',+ collaboration: 'Współpraca'+}+export const RU_PROG: ProgrammableLabels = {+ overview: 'Обзор',+ cli: 'CLI',+ inspecting: 'Инспекция файлов',+ exporting: 'Экспорт',+ analyzing: 'Анализ дизайна',+ scripting: 'Скрипты',+ jsxRenderer: 'JSX-рендерер',+ mcpServer: 'MCP-сервер',+ aiChat: 'ИИ-чат',+ collaboration: 'Совместная работа'+}++export const EN: SidebarLabels = {+ gettingAround: 'Getting Around',+ creatingContent: 'Creating Content',+ organizing: 'Organizing & Managing',+ advanced: 'Advanced Features',+ canvasNav: 'Canvas Navigation',+ selection: 'Selection & Manipulation',+ shapes: 'Drawing Shapes',+ text: 'Text Editing',+ pen: 'Pen Tool',+ layers: 'Layers & Pages',+ contextMenu: 'Context Menu',+ exporting: 'Exporting',+ autoLayout: 'Auto Layout',+ components: 'Components',+ variables: 'Variables',+ guide: 'Guide',+ gettingStarted: 'Getting Started',+ features: 'Features',+ architecture: 'Architecture',+ techStack: 'Tech Stack',+ comparison: 'Comparison',+ figmaMatrix: 'Figma Feature Matrix'+}+export const DE: SidebarLabels = {+ gettingAround: 'Erste Schritte',+ creatingContent: 'Inhalte erstellen',+ organizing: 'Organisieren',+ advanced: 'Erweitert',+ canvasNav: 'Canvas-Navigation',+ selection: 'Auswahl & Bearbeitung',+ shapes: 'Formen zeichnen',+ text: 'Textbearbeitung',+ pen: 'Stiftwerkzeug',+ layers: 'Ebenen & Seiten',+ contextMenu: 'Kontextmenü',+ exporting: 'Exportieren',+ autoLayout: 'Auto-Layout',+ components: 'Komponenten',+ variables: 'Variablen',+ guide: 'Anleitung',+ gettingStarted: 'Erste Schritte',+ features: 'Funktionen',+ architecture: 'Architektur',+ techStack: 'Tech-Stack',+ comparison: 'Vergleich',+ figmaMatrix: 'Figma-Funktionsmatrix'+}+export const IT: SidebarLabels = {+ gettingAround: 'Orientamento',+ creatingContent: 'Creazione contenuti',+ organizing: 'Organizzazione',+ advanced: 'Avanzate',+ canvasNav: 'Navigazione canvas',+ selection: 'Selezione e manipolazione',+ shapes: 'Disegno forme',+ text: 'Modifica testo',+ pen: 'Strumento penna',+ layers: 'Livelli e pagine',+ contextMenu: 'Menu contestuale',+ exporting: 'Esportazione',+ autoLayout: 'Auto-layout',+ components: 'Componenti',+ variables: 'Variabili',+ guide: 'Guida',+ gettingStarted: 'Per iniziare',+ features: 'Funzionalità',+ architecture: 'Architettura',+ techStack: 'Stack tecnologico',+ comparison: 'Confronto',+ figmaMatrix: 'Matrice funzionalità Figma'+}+export const FR: SidebarLabels = {+ gettingAround: 'Prise en main',+ creatingContent: 'Création de contenu',+ organizing: 'Organisation',+ advanced: 'Avancé',+ canvasNav: 'Navigation sur le canevas',+ selection: 'Sélection et manipulation',+ shapes: 'Dessiner des formes',+ text: 'Édition de texte',+ pen: 'Outil plume',+ layers: 'Calques et pages',+ contextMenu: 'Menu contextuel',+ exporting: 'Exportation',+ autoLayout: 'Mise en page auto',+ components: 'Composants',+ variables: 'Variables',+ guide: 'Guide',+ gettingStarted: 'Premiers pas',+ features: 'Fonctionnalités',+ architecture: 'Architecture',+ techStack: 'Stack technique',+ comparison: 'Comparaison',+ figmaMatrix: 'Matrice des fonctionnalités Figma'+}+export const ES: SidebarLabels = {+ gettingAround: 'Orientación',+ creatingContent: 'Crear contenido',+ organizing: 'Organizar',+ advanced: 'Avanzado',+ canvasNav: 'Navegación del lienzo',+ selection: 'Selección y manipulación',+ shapes: 'Dibujar formas',+ text: 'Edición de texto',+ pen: 'Herramienta pluma',+ layers: 'Capas y páginas',+ contextMenu: 'Menú contextual',+ exporting: 'Exportar',+ autoLayout: 'Auto-layout',+ components: 'Componentes',+ variables: 'Variables',+ guide: 'Guía',+ gettingStarted: 'Primeros pasos',+ features: 'Características',+ architecture: 'Arquitectura',+ techStack: 'Stack tecnológico',+ comparison: 'Comparación',+ figmaMatrix: 'Matriz de funcionalidades Figma'+}+export const PL: SidebarLabels = {+ gettingAround: 'Nawigacja',+ creatingContent: 'Tworzenie treści',+ organizing: 'Organizacja',+ advanced: 'Zaawansowane',+ canvasNav: 'Nawigacja po płótnie',+ selection: 'Zaznaczanie i edycja',+ shapes: 'Rysowanie kształtów',+ text: 'Edycja tekstu',+ pen: 'Narzędzie pióro',+ layers: 'Warstwy i strony',+ contextMenu: 'Menu kontekstowe',+ exporting: 'Eksportowanie',+ autoLayout: 'Auto-layout',+ components: 'Komponenty',+ variables: 'Zmienne',+ guide: 'Przewodnik',+ gettingStarted: 'Rozpoczęcie pracy',+ features: 'Funkcje',+ architecture: 'Architektura',+ techStack: 'Stack technologiczny',+ comparison: 'Porównanie',+ figmaMatrix: 'Matryca funkcji Figma'+}+export const RU: SidebarLabels = {+ gettingAround: 'Навигация',+ creatingContent: 'Создание контента',+ organizing: 'Организация',+ advanced: 'Продвинутые функции',+ canvasNav: 'Навигация по холсту',+ selection: 'Выделение и редактирование',+ shapes: 'Рисование фигур',+ text: 'Редактирование текста',+ pen: 'Инструмент «Перо»',+ layers: 'Слои и страницы',+ contextMenu: 'Контекстное меню',+ exporting: 'Экспорт',+ autoLayout: 'Авто-раскладка',+ components: 'Компоненты',+ variables: 'Переменные',+ guide: 'Руководство',+ gettingStarted: 'Начало работы',+ features: 'Возможности',+ architecture: 'Архитектура',+ techStack: 'Технологии',+ comparison: 'Сравнение',+ figmaMatrix: 'Матрица функций Figma'+}diff --git a/packages/docs/.vitepress/locale-theme.ts b/packages/docs/.vitepress/locale-theme.tsnew file mode 100644index 000000000..f2e44b76d--- /dev/null+++ b/packages/docs/.vitepress/locale-theme.ts@@ -0,0 +1,38 @@+import { sdkSidebar } from './sdk-sidebar'+import {+ developmentSidebar,+ guideSidebar,+ programmableSidebar,+ referenceSidebar,+ userGuideSidebar,+} from './sidebars'++import type { NavLabels, ProgrammableLabels, SidebarLabels } from './labels'+import type { DefaultTheme } from 'vitepress'++export const localeThemeConfig = (+ prefix: string,+ nav: NavLabels,+ sidebar: SidebarLabels,+ prog: ProgrammableLabels,+): DefaultTheme.Config => ({+ nav: [+ { text: nav.guide, link: `${prefix}/guide/getting-started` },+ { text: nav.userGuide, link: `${prefix}/user-guide/` },+ { text: nav.programmable, link: `${prefix}/programmable/` },+ { text: nav.sdk, link: `${prefix}/programmable/sdk/` },+ { text: nav.reference, link: `${prefix}/reference/keyboard-shortcuts` },+ { text: nav.development, link: `${prefix}/development/contributing` },+ { text: nav.openApp, link: 'https://app.openpencil.dev' },+ ],+ sidebar: {+ [`${prefix}/user-guide/`]: userGuideSidebar(prefix, sidebar),+ [`${prefix}/programmable/sdk/`]: sdkSidebar(prefix),+ [`${prefix}/programmable/`]: programmableSidebar(prefix, prog),+ [`${prefix}/reference/`]: referenceSidebar(prefix, nav.reference),+ [`${prefix}/`]: [+ ...guideSidebar(prefix, sidebar),+ ...developmentSidebar(prefix, nav.development),+ ],+ },+})diff --git a/packages/docs/.vitepress/locales.ts b/packages/docs/.vitepress/locales.tsnew file mode 100644index 000000000..97fc5698d--- /dev/null+++ b/packages/docs/.vitepress/locales.ts@@ -0,0 +1,136 @@+import {+ DE,+ DE_PROG,+ ES,+ ES_PROG,+ FR,+ FR_PROG,+ IT,+ IT_PROG,+ PL,+ PL_PROG,+ RU,+ RU_PROG,+} from './labels'+import { localeThemeConfig } from './locale-theme'++export const docsLocales = {+ root: {+ label: 'English',+ lang: 'en',+ },+ de: {+ label: 'Deutsch',+ lang: 'de',+ description: 'Open-Source, KI-nativer Design-Editor. Figma-Alternative.',+ themeConfig: localeThemeConfig(+ '/de',+ {+ guide: 'Guide',+ userGuide: 'Benutzerhandbuch',+ programmable: 'Automation',+ sdk: 'SDK',+ reference: 'Referenz',+ development: 'Entwicklung',+ openApp: 'App öffnen',+ },+ DE,+ DE_PROG,+ ),+ },+ it: {+ label: 'Italiano',+ lang: 'it',+ description: 'Editor di design open-source, IA-nativo. Alternativa a Figma.',+ themeConfig: localeThemeConfig(+ '/it',+ {+ guide: 'Guida',+ userGuide: 'Guida utente',+ programmable: 'Automation',+ sdk: 'SDK',+ reference: 'Riferimento',+ development: 'Sviluppo',+ openApp: 'Apri app',+ },+ IT,+ IT_PROG,+ ),+ },+ fr: {+ label: 'Français',+ lang: 'fr',+ description: 'Éditeur de design open-source, IA-natif. Alternative à Figma.',+ themeConfig: localeThemeConfig(+ '/fr',+ {+ guide: 'Guide',+ userGuide: 'Guide utilisateur',+ programmable: 'Automation',+ sdk: 'SDK',+ reference: 'Référence',+ development: 'Développement',+ openApp: "Ouvrir l'app",+ },+ FR,+ FR_PROG,+ ),+ },+ es: {+ label: 'Español',+ lang: 'es',+ description: 'Editor de diseño open-source, IA-nativo. Alternativa a Figma.',+ themeConfig: localeThemeConfig(+ '/es',+ {+ guide: 'Guía',+ userGuide: 'Guía del usuario',+ programmable: 'Automation',+ sdk: 'SDK',+ reference: 'Referencia',+ development: 'Desarrollo',+ openApp: 'Abrir app',+ },+ ES,+ ES_PROG,+ ),+ },+ pl: {+ label: 'Polski',+ lang: 'pl',+ description: "Open-source'owy edytor graficzny z natywnym AI. Alternatywa dla Figmy.",+ themeConfig: localeThemeConfig(+ '/pl',+ {+ guide: 'Przewodnik',+ userGuide: 'Podręcznik',+ programmable: 'Automation',+ sdk: 'SDK',+ reference: 'Referencja',+ development: 'Rozwój',+ openApp: 'Otwórz app',+ },+ PL,+ PL_PROG,+ ),+ },+ ru: {+ label: 'Русский',+ lang: 'ru',+ description: 'Дизайн-редактор с открытым исходным кодом. Альтернатива Figma с встроенным ИИ.',+ themeConfig: localeThemeConfig(+ '/ru',+ {+ guide: 'Руководство',+ userGuide: 'Руководство',+ programmable: 'Automation',+ sdk: 'SDK',+ reference: 'Справочник',+ development: 'Разработка',+ openApp: 'Открыть приложение',+ },+ RU,+ RU_PROG,+ ),+ },+}diff --git a/packages/docs/.vitepress/root-theme.ts b/packages/docs/.vitepress/root-theme.tsnew file mode 100644index 000000000..30ab2f8de--- /dev/null+++ b/packages/docs/.vitepress/root-theme.ts@@ -0,0 +1,53 @@+import { EN, EN_PROG } from './labels'+import { sdkSidebar } from './sdk-sidebar'+import {+ guideSidebar,+ programmableSidebar,+ referenceSidebar,+ userGuideSidebar,+} from './sidebars'++import type { DefaultTheme } from 'vitepress'++export const rootThemeConfig = (): DefaultTheme.Config => ({+ search: { provider: 'local' },++ nav: [+ { text: 'Guide', link: '/guide/getting-started' },+ { text: 'User Guide', link: '/user-guide/' },+ { text: 'Automation', link: '/programmable/' },+ { text: 'SDK', link: '/programmable/sdk/' },+ { text: 'Reference', link: '/reference/keyboard-shortcuts' },+ { text: 'Development', link: '/development/contributing' },+ { text: 'Open App', link: 'https://app.openpencil.dev' },+ ],++ sidebar: {+ '/user-guide/': userGuideSidebar('', EN),+ '/programmable/sdk/': sdkSidebar(''),+ '/programmable/': programmableSidebar('', EN_PROG),+ '/reference/': referenceSidebar('', 'Reference'),+ '/': [+ ...guideSidebar('', EN),+ {+ text: 'Development',+ items: [+ { text: 'Contributing', link: '/development/contributing' },+ { text: 'Testing', link: '/development/testing' },+ { text: 'OpenSpec Workflow', link: '/development/openspec' },+ { text: 'Roadmap', link: '/development/roadmap' },+ ],+ },+ ],+ },++ socialLinks: [{ icon: 'github', link: 'https://github.com/open-pencil/open-pencil' }],++ editLink: {+ pattern: 'https://github.com/open-pencil/open-pencil/edit/main/packages/docs/:path',+ },++ footer: {+ message: 'Released under the MIT License.',+ },+})diff --git a/packages/docs/.vitepress/sdk-sidebar.ts b/packages/docs/.vitepress/sdk-sidebar.tsnew file mode 100644index 000000000..835e0fe36--- /dev/null+++ b/packages/docs/.vitepress/sdk-sidebar.ts@@ -0,0 +1,121 @@+import type { DefaultTheme } from 'vitepress'++const SDK_COMPONENT_PAGES = [+ { text: 'CanvasRoot', slug: 'canvas-root' },+ { text: 'CanvasSurface', slug: 'canvas-surface' },+ { text: 'LayerTreeRoot', slug: 'layer-tree-root' },+ { text: 'LayerTreeItem', slug: 'layer-tree-item' },+ { text: 'ToolbarRoot', slug: 'toolbar-root' },+ { text: 'ToolbarItem', slug: 'toolbar-item' },+ { text: 'PageListRoot', slug: 'page-list-root' },+ { text: 'PropertyListRoot', slug: 'property-list-root' },+ { text: 'PropertyListItem', slug: 'property-list-item' },+ { text: 'ColorPickerRoot', slug: 'color-picker-root' },+ { text: 'ColorInputRoot', slug: 'color-input-root' },+ { text: 'FillPickerRoot', slug: 'fill-picker-root' },+ { text: 'FontPickerRoot', slug: 'font-picker-root' },+ { text: 'GradientEditorRoot', slug: 'gradient-editor-root' },+ { text: 'GradientEditorBar', slug: 'gradient-editor-bar' },+ { text: 'GradientEditorStop', slug: 'gradient-editor-stop' },+ { text: 'ScrubInputRoot', slug: 'scrub-input-root' },+ { text: 'ScrubInputField', slug: 'scrub-input-field' },+ { text: 'ScrubInputDisplay', slug: 'scrub-input-display' },+ { text: 'LayoutControlsRoot', slug: 'layout-controls-root' },+ { text: 'AppearanceControlsRoot', slug: 'appearance-controls-root' },+ { text: 'PositionControlsRoot', slug: 'position-controls-root' },+ { text: 'TypographyControlsRoot', slug: 'typography-controls-root' }+] as const++const SDK_COMPOSABLE_PAGES = [+ { text: 'provideEditor', slug: 'provide-editor' },+ { text: 'useEditor', slug: 'use-editor' },+ { text: 'useCanvas', slug: 'use-canvas' },+ { text: 'useCanvasInput', slug: 'use-canvas-input' },+ { text: 'useTextEdit', slug: 'use-text-edit' },+ { text: 'useSelectionState', slug: 'use-selection-state' },+ { text: 'useSelectionCapabilities', slug: 'use-selection-capabilities' },+ { text: 'useEditorCommands', slug: 'use-editor-commands' },+ { text: 'useMenuModel', slug: 'use-menu-model' },+ { text: 'usePosition', slug: 'use-position' },+ { text: 'useLayout', slug: 'use-layout' },+ { text: 'useAppearance', slug: 'use-appearance' },+ { text: 'useTypography', slug: 'use-typography' },+ { text: 'useExport', slug: 'use-export' },+ { text: 'useFillControls', slug: 'use-fill-controls' },+ { text: 'useStrokeControls', slug: 'use-stroke-controls' },+ { text: 'useEffectsControls', slug: 'use-effects-controls' },+ { text: 'useVariablesEditor', slug: 'use-variables-editor' },+ { text: 'usePageList', slug: 'use-page-list' }+] as const++const SDK_ADVANCED_PAGES = [+ { text: 'useNodeProps', slug: 'use-node-props' },+ { text: 'useSceneComputed', slug: 'use-scene-computed' },+ { text: 'useFillVariableBinding', slug: 'use-fill-variable-binding' },+ { text: 'useFillPicker', slug: 'use-fill-picker' },+ { text: 'useGradientStops', slug: 'use-gradient-stops' },+ { text: 'useFontPicker', slug: 'use-font-picker' },+ { text: 'usePropScrub', slug: 'use-prop-scrub' },+ { text: 'useLayerDrag', slug: 'use-layer-drag' },+ { text: 'useInlineRename', slug: 'use-inline-rename' },+ { text: 'useToolbarState', slug: 'use-toolbar-state' },+ { text: 'useNodeFontStatus', slug: 'use-node-font-status' },+ { text: 'useCanvasDrop', slug: 'use-canvas-drop' },+ { text: 'extractImageFilesFromClipboard', slug: 'extract-image-files-from-clipboard' },+ { text: 'toolCursor', slug: 'tool-cursor' },+ { text: 'useCanvasContext', slug: 'use-canvas-context' },+ { text: 'useLayerTree', slug: 'use-layer-tree' },+ { text: 'useToolbar', slug: 'use-toolbar' },+ { text: 'usePropertyList', slug: 'use-property-list' },+ { text: 'useScrubInput', slug: 'use-scrub-input' }+] as const++export const sdkSidebar = (prefix: string): DefaultTheme.SidebarItem[] => [+ {+ text: 'Vue SDK',+ items: [+ { text: 'Overview', link: `${prefix}/programmable/sdk/` },+ { text: 'Getting Started', link: `${prefix}/programmable/sdk/getting-started` },+ { text: 'Architecture', link: `${prefix}/programmable/sdk/architecture` },+ { text: 'Custom Shell', link: `${prefix}/programmable/sdk/guides/custom-editor-shell` },+ { text: 'Property Panels', link: `${prefix}/programmable/sdk/guides/property-panels` },+ { text: 'Navigation Panels', link: `${prefix}/programmable/sdk/guides/navigation-panels` },+ {+ text: 'API Reference',+ items: [+ { text: 'Overview', link: `${prefix}/programmable/sdk/api/` },+ {+ text: 'Components',+ items: [+ { text: 'Overview', link: `${prefix}/programmable/sdk/api/components/` },+ ...SDK_COMPONENT_PAGES.map((page) => ({+ text: page.text,+ link: `${prefix}/programmable/sdk/api/components/${page.slug}`+ }))+ ]+ },+ {+ text: 'Composables',+ items: [+ { text: 'Overview', link: `${prefix}/programmable/sdk/api/composables/` },+ ...SDK_COMPOSABLE_PAGES.map((page) => ({+ text: page.text,+ link: `${prefix}/programmable/sdk/api/composables/${page.slug}`+ }))+ ]+ },+ {+ text: 'Advanced',+ items: [+ { text: 'Overview', link: `${prefix}/programmable/sdk/api/advanced/` },+ ...SDK_ADVANCED_PAGES.map((page) => ({+ text: page.text,+ link: `${prefix}/programmable/sdk/api/advanced/${page.slug}`+ }))+ ]+ }+ ]+ }+ ]+ }+]diff --git a/packages/docs/.vitepress/seo.ts b/packages/docs/.vitepress/seo.tsnew file mode 100644index 000000000..441094a5b--- /dev/null+++ b/packages/docs/.vitepress/seo.ts@@ -0,0 +1,119 @@+export const BASE = 'https://openpencil.dev'++export const LOCALE_PREFIXES = ['de', 'fr', 'es', 'it', 'pl', 'ru'] as const++export const LOCALES: Record<string, { hreflang: string; ogLocale: string; prefix: string }> = {+ en: { hreflang: 'en', ogLocale: 'en_US', prefix: '' },+ de: { hreflang: 'de', ogLocale: 'de_DE', prefix: '/de' },+ fr: { hreflang: 'fr', ogLocale: 'fr_FR', prefix: '/fr' },+ es: { hreflang: 'es', ogLocale: 'es_ES', prefix: '/es' },+ it: { hreflang: 'it', ogLocale: 'it_IT', prefix: '/it' },+ pl: { hreflang: 'pl', ogLocale: 'pl_PL', prefix: '/pl' },+ ru: { hreflang: 'ru', ogLocale: 'ru_RU', prefix: '/ru' }+}++export const siteHead: [string, Record<string, string>][] = [+ ['link', { rel: 'icon', type: 'image/png', href: '/favicon.png' }],+ ['meta', { property: 'og:type', content: 'website' }],+ ['meta', { property: 'og:site_name', content: 'OpenPencil' }],+ ['meta', { property: 'og:image', content: `${BASE}/screenshot.png` }],+ ['meta', { property: 'og:image:width', content: '2784' }],+ ['meta', { property: 'og:image:height', content: '1824' }],+ ['meta', { property: 'og:image:alt', content: 'OpenPencil — AI-Native Design Editor' }],+ ['meta', { name: 'twitter:card', content: 'summary_large_image' }],+ ['meta', { name: 'twitter:site', content: '@openpencildev' }],+ ['meta', { name: 'twitter:image', content: `${BASE}/screenshot.png` }]+]++type SitemapItem = {+ url: string+ links?: Array<{ lang: string; url: string }>+}++type PageDataLike = {+ relativePath: string+ title?: string+ description?: string+ frontmatter: {+ head?: [string, Record<string, string>][]+ }+}++function stripLocalePrefix(path: string): string {+ return path.replace(new RegExp(`^(${LOCALE_PREFIXES.join('|')})/`), '')+}++function localeKeyForPath(path: string): string {+ return LOCALE_PREFIXES.find((prefix) => path.startsWith(`${prefix}/`)) ?? 'en'+}++function slugForPath(path: string): string {+ return stripLocalePrefix(path)+ .replace(/\.md$/, '')+ .replace(/\/index$/, '')+ .replace(/^index$/, '')+ .replace(/\/$/, '')+}++function localizedUrl(slug: string, prefix: string): string {+ if (slug) return `${BASE}${prefix}/${slug}`+ return `${BASE}${prefix || ''}`+}++export function withAlternateSitemapLinks<T extends SitemapItem>(items: T[]): T[] {+ return items.map((item) => {+ const slug = slugForPath(item.url)+ return {+ ...item,+ links: Object.values(LOCALES).map((locale) => {+ const url = slug ? `${BASE}${locale.prefix}/${slug}` : `${BASE}${locale.prefix || '/'}`+ return { lang: locale.hreflang, url }+ })+ }+ })+}++export function applyPageSeo(pageData: PageDataLike): void {+ const localeKey = localeKeyForPath(pageData.relativePath)+ const locale = LOCALES[localeKey]+ const slug = slugForPath(pageData.relativePath)+ const pageUrl = localizedUrl(slug, locale.prefix)+ const enSlug = slug ? `${BASE}/${slug}` : BASE++ pageData.frontmatter.head ??= []+ const head = pageData.frontmatter.head++ head.push(['link', { rel: 'canonical', href: pageUrl }])+ head.push(['meta', { property: 'og:url', content: pageUrl }])+ head.push(['meta', { property: 'og:locale', content: locale.ogLocale }])++ for (const [key, loc] of Object.entries(LOCALES)) {+ if (key !== localeKey) {+ head.push(['meta', { property: 'og:locale:alternate', content: loc.ogLocale }])+ }+ }++ for (const localeOption of Object.values(LOCALES)) {+ head.push([+ 'link',+ {+ rel: 'alternate',+ hreflang: localeOption.hreflang,+ href: localizedUrl(slug, localeOption.prefix)+ }+ ])+ }+ head.push(['link', { rel: 'alternate', hreflang: 'x-default', href: enSlug }])++ if (pageData.title) {+ const ogTitle = `${pageData.title} — OpenPencil`+ head.push(['meta', { property: 'og:title', content: ogTitle }])+ head.push(['meta', { name: 'twitter:title', content: ogTitle }])+ }++ if (pageData.description) {+ head.push(['meta', { property: 'og:description', content: pageData.description }])+ head.push(['meta', { name: 'twitter:description', content: pageData.description }])+ head.push(['meta', { name: 'description', content: pageData.description }])+ }+}diff --git a/packages/docs/.vitepress/sidebars.ts b/packages/docs/.vitepress/sidebars.tsnew file mode 100644index 000000000..1fea4c2b1--- /dev/null+++ b/packages/docs/.vitepress/sidebars.ts@@ -0,0 +1,99 @@+import type { ProgrammableLabels, SidebarLabels } from './labels'+import type { DefaultTheme } from 'vitepress'++export const guideSidebar = (prefix: string, labels: SidebarLabels): DefaultTheme.SidebarItem[] => [+ {+ text: labels.guide,+ items: [+ { text: labels.gettingStarted, link: `${prefix}/guide/getting-started` },+ { text: labels.features, link: `${prefix}/guide/features` },+ { text: labels.architecture, link: `${prefix}/guide/architecture` },+ { text: labels.techStack, link: `${prefix}/guide/tech-stack` },+ { text: labels.comparison, link: `${prefix}/guide/comparison` },+ { text: labels.figmaMatrix, link: `${prefix}/guide/figma-comparison` },+ ],+ },+]++export const userGuideSidebar = (+ prefix: string,+ labels: SidebarLabels,+): DefaultTheme.SidebarItem[] => [+ {+ text: labels.gettingAround,+ items: [+ { text: labels.canvasNav, link: `${prefix}/user-guide/canvas-navigation` },+ { text: labels.selection, link: `${prefix}/user-guide/selection-and-manipulation` },+ { text: labels.contextMenu, link: `${prefix}/user-guide/context-menu` },+ ],+ },+ {+ text: labels.creatingContent,+ items: [+ { text: labels.shapes, link: `${prefix}/user-guide/drawing-shapes` },+ { text: labels.text, link: `${prefix}/user-guide/text-editing` },+ { text: labels.pen, link: `${prefix}/user-guide/pen-tool` },+ ],+ },+ {+ text: labels.organizing,+ items: [+ { text: labels.layers, link: `${prefix}/user-guide/layers-and-pages` },+ { text: labels.exporting, link: `${prefix}/user-guide/exporting` },+ ],+ },+ {+ text: labels.advanced,+ items: [+ { text: labels.autoLayout, link: `${prefix}/user-guide/auto-layout` },+ { text: labels.components, link: `${prefix}/user-guide/components` },+ { text: labels.variables, link: `${prefix}/user-guide/variables` },+ ],+ },+]++export const programmableSidebar = (+ prefix: string,+ labels: ProgrammableLabels,+): DefaultTheme.SidebarItem[] => [+ {+ text: labels.overview,+ items: [+ { text: labels.overview, link: `${prefix}/programmable/` },+ { text: labels.cli, link: `${prefix}/programmable/cli` },+ { text: labels.inspecting, link: `${prefix}/programmable/inspecting` },+ { text: labels.exporting, link: `${prefix}/programmable/exporting` },+ { text: labels.analyzing, link: `${prefix}/programmable/analyzing` },+ { text: labels.scripting, link: `${prefix}/programmable/scripting` },+ { text: labels.jsxRenderer, link: `${prefix}/programmable/jsx-renderer` },+ { text: labels.mcpServer, link: `${prefix}/programmable/mcp-server` },+ { text: labels.aiChat, link: `${prefix}/programmable/ai-chat` },+ { text: labels.collaboration, link: `${prefix}/programmable/collaboration` },+ ],+ },+]++export const referenceSidebar = (prefix: string, label: string): DefaultTheme.SidebarItem[] => [+ {+ text: label,+ items: [+ { text: 'Keyboard Shortcuts', link: `${prefix}/reference/keyboard-shortcuts` },+ { text: 'CLI', link: `${prefix}/reference/cli` },+ { text: 'Node Types', link: `${prefix}/reference/node-types` },+ { text: 'Scene Graph', link: `${prefix}/reference/scene-graph` },+ { text: 'File Format', link: `${prefix}/reference/file-format` },+ ],+ },+]++export const developmentSidebar = (prefix: string, label: string): DefaultTheme.SidebarItem[] => [+ {+ text: label,+ items: [+ { text: 'Contributing', link: `${prefix}/development/contributing` },+ { text: 'Testing', link: `${prefix}/development/testing` },+ { text: 'OpenSpec', link: `${prefix}/development/openspec` },+ { text: 'Roadmap', link: `${prefix}/development/roadmap` },+ ],+ },+]diff --git a/packages/docs/.vitepress/theme/components/SdkDataTable.vue b/packages/docs/.vitepress/theme/components/SdkDataTable.vuenew file mode 100644index 000000000..e05399087--- /dev/null+++ b/packages/docs/.vitepress/theme/components/SdkDataTable.vue@@ -0,0 +1,122 @@+<script setup lang="ts">+export type SdkDataTableColumn = {+ key: string+ label: string+ kind?: 'code' | 'chip' | 'text' | 'description'+}++export type SdkDataTableRow = Record<string, string | boolean | undefined>++defineProps<{+ columns: SdkDataTableColumn[]+ rows: SdkDataTableRow[]+ rowKey?: string+}>()++function cellValue(row: SdkDataTableRow, key: string) {+ const value = row[key]+ return typeof value === 'string' ? value : ''+}++function isRequired(row: SdkDataTableRow) {+ return row.required === true+}+</script>++<template>+ <div class="sdk-table-wrap">+ <table class="sdk-table">+ <thead>+ <tr>+ <th v-for="column in columns" :key="column.key">{{ column.label }}</th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="row in rows" :key="cellValue(row, rowKey ?? 'name')">+ <td v-for="column in columns" :key="column.key">+ <template v-if="column.kind === 'code'">+ <code class="sdk-table__code">+ {{ cellValue(row, column.key) }}<span v-if="column.key === 'name' && isRequired(row)">*</span>+ </code>+ <div v-if="row.description" class="sdk-table__description">+ {{ row.description }}+ </div>+ </template>+ <template v-else-if="column.kind === 'chip'">+ <code v-if="cellValue(row, column.key)" class="sdk-table__chip">+ {{ cellValue(row, column.key) }}+ </code>+ <span v-else>—</span>+ </template>+ <template v-else-if="column.kind === 'description'">+ <span class="sdk-table__description-cell">{{ cellValue(row, column.key) }}</span>+ </template>+ <template v-else>+ {{ cellValue(row, column.key) || '—' }}+ </template>+ </td>+ </tr>+ </tbody>+ </table>+ </div>+</template>++<style scoped>+.sdk-table-wrap {+ overflow-x: auto;+}++.sdk-table {+ width: 100%;+ border-collapse: separate;+ border-spacing: 0;+ font-size: 14px;+}++.sdk-table th,+.sdk-table td {+ padding: 16px;+ vertical-align: top;+ border: 1px solid var(--vp-c-divider);+}++.sdk-table thead th {+ background: var(--vp-c-bg-soft);+ color: var(--vp-c-text-2);+ font-weight: 600;+ text-align: left;+}++.sdk-table thead th:first-child {+ border-top-left-radius: 14px;+}++.sdk-table thead th:last-child {+ border-top-right-radius: 14px;+}++.sdk-table__code {+ color: var(--vp-c-brand-1);+}++.sdk-table__chip {+ display: inline-block;+ padding: 4px 10px;+ border: 1px solid var(--vp-c-divider);+ border-radius: 10px;+ background: var(--vp-c-bg-soft);+ color: var(--vp-c-text-1);+ white-space: nowrap;+}++.sdk-table__description {+ margin-top: 8px;+ color: var(--vp-c-text-2);+ line-height: 1.6;+}++.sdk-table__description-cell {+ color: var(--vp-c-text-2);+ line-height: 1.6;+}+</style>diff --git a/packages/docs/.vitepress/theme/components/SdkEventsTable.vue b/packages/docs/.vitepress/theme/components/SdkEventsTable.vueindex 0a31370ef..48edbae5c 100644--- a/packages/docs/.vitepress/theme/components/SdkEventsTable.vue+++ b/packages/docs/.vitepress/theme/components/SdkEventsTable.vue@@ -1,4 +1,6 @@<script setup lang="ts">+import SdkDataTable from './SdkDataTable.vue'+interface Row {name: stringpayload?: string@@ -8,82 +10,14 @@ interface Row {defineProps<{rows: Row[]}>()++const columns = [+ { key: 'name', label: 'Event', kind: 'code' },+ { key: 'payload', label: 'Payload', kind: 'chip' },+ { key: 'description', label: 'Description', kind: 'description' },+] as const</script><template>- <div class="sdk-table-wrap">- <table class="sdk-table">- <thead>- <tr>- <th>Event</th>- <th>Payload</th>- <th>Description</th>- </tr>- </thead>- <tbody>- <tr v-for="row in rows" :key="row.name">- <td><code class="sdk-table__code">{{ row.name }}</code></td>- <td>- <code v-if="row.payload" class="sdk-table__chip">{{ row.payload }}</code>- <span v-else>—</span>- </td>- <td class="sdk-table__description-cell">{{ row.description }}</td>- </tr>- </tbody>- </table>- </div>+ <SdkDataTable :columns="columns" :rows="rows" /></template>--<style scoped>-.sdk-table-wrap {- overflow-x: auto;-}--.sdk-table {- width: 100%;- border-collapse: separate;- border-spacing: 0;- font-size: 14px;-}--.sdk-table th,-.sdk-table td {- padding: 16px;- vertical-align: top;- border: 1px solid var(--vp-c-divider);-}--.sdk-table thead th {- background: var(--vp-c-bg-soft);- color: var(--vp-c-text-2);- font-weight: 600;- text-align: left;-}--.sdk-table thead th:first-child {- border-top-left-radius: 14px;-}--.sdk-table thead th:last-child {- border-top-right-radius: 14px;-}--.sdk-table__code {- color: var(--vp-c-brand-1);-}--.sdk-table__chip {- display: inline-block;- padding: 4px 10px;- border: 1px solid var(--vp-c-divider);- border-radius: 10px;- background: var(--vp-c-bg-soft);- color: var(--vp-c-text-1);- white-space: nowrap;-}--.sdk-table__description-cell {- color: var(--vp-c-text-2);- line-height: 1.6;-}-</style>diff --git a/packages/docs/.vitepress/theme/components/SdkPropsTable.vue b/packages/docs/.vitepress/theme/components/SdkPropsTable.vueindex eaae6032e..c3b5950be 100644--- a/packages/docs/.vitepress/theme/components/SdkPropsTable.vue+++ b/packages/docs/.vitepress/theme/components/SdkPropsTable.vue@@ -1,4 +1,6 @@<script setup lang="ts">+import SdkDataTable from './SdkDataTable.vue'+interface Row {name: stringtype?: string@@ -10,89 +12,14 @@ interface Row {defineProps<{rows: Row[]}>()++const columns = [+ { key: 'name', label: 'Prop', kind: 'code' },+ { key: 'default', label: 'Default', kind: 'chip' },+ { key: 'type', label: 'Type', kind: 'chip' },+] as const</script><template>- <div class="sdk-table-wrap">- <table class="sdk-table">- <thead>- <tr>- <th>Prop</th>- <th>Default</th>- <th>Type</th>- </tr>- </thead>- <tbody>- <tr v-for="row in rows" :key="row.name">- <td>- <code class="sdk-table__code">{{ row.name }}<span v-if="row.required">*</span></code>- <div class="sdk-table__description">{{ row.description }}</div>- </td>- <td>- <code v-if="row.default" class="sdk-table__chip">{{ row.default }}</code>- <span v-else>—</span>- </td>- <td>- <code v-if="row.type" class="sdk-table__chip">{{ row.type }}</code>- <span v-else>—</span>- </td>- </tr>- </tbody>- </table>- </div>+ <SdkDataTable :columns="columns" :rows="rows" /></template>--<style scoped>-.sdk-table-wrap {- overflow-x: auto;-}--.sdk-table {- width: 100%;- border-collapse: separate;- border-spacing: 0;- font-size: 14px;-}--.sdk-table th,-.sdk-table td {- padding: 16px;- vertical-align: top;- border: 1px solid var(--vp-c-divider);-}--.sdk-table thead th {- background: var(--vp-c-bg-soft);- color: var(--vp-c-text-2);- font-weight: 600;- text-align: left;-}--.sdk-table thead th:first-child {- border-top-left-radius: 14px;-}--.sdk-table thead th:last-child {- border-top-right-radius: 14px;-}--.sdk-table__code {- color: var(--vp-c-brand-1);-}--.sdk-table__chip {- display: inline-block;- padding: 4px 10px;- border: 1px solid var(--vp-c-divider);- border-radius: 10px;- background: var(--vp-c-bg-soft);- color: var(--vp-c-text-1);- white-space: nowrap;-}--.sdk-table__description {- margin-top: 8px;- color: var(--vp-c-text-2);- line-height: 1.6;-}-</style>diff --git a/packages/docs/.vitepress/theme/components/SdkSlotsTable.vue b/packages/docs/.vitepress/theme/components/SdkSlotsTable.vueindex 51ee2c0da..309c588de 100644--- a/packages/docs/.vitepress/theme/components/SdkSlotsTable.vue+++ b/packages/docs/.vitepress/theme/components/SdkSlotsTable.vue@@ -1,4 +1,6 @@<script setup lang="ts">+import SdkDataTable from './SdkDataTable.vue'+interface Row {name: stringprops?: string@@ -8,81 +10,14 @@ interface Row {defineProps<{rows: Row[]}>()++const columns = [+ { key: 'name', label: 'Slot', kind: 'code' },+ { key: 'props', label: 'Props', kind: 'chip' },+ { key: 'description', label: 'Description', kind: 'description' },+] as const</script><template>- <div class="sdk-table-wrap">- <table class="sdk-table">- <thead>- <tr>- <th>Slot</th>- <th>Props</th>- <th>Description</th>- </tr>- </thead>- <tbody>- <tr v-for="row in rows" :key="row.name">- <td><code class="sdk-table__code">{{ row.name }}</code></td>- <td>- <code v-if="row.props" class="sdk-table__chip">{{ row.props }}</code>- <span v-else>—</span>- </td>- <td class="sdk-table__description-cell">{{ row.description }}</td>- </tr>- </tbody>- </table>- </div>+ <SdkDataTable :columns="columns" :rows="rows" /></template>--<style scoped>-.sdk-table-wrap {- overflow-x: auto;-}--.sdk-table {- width: 100%;- border-collapse: separate;- border-spacing: 0;- font-size: 14px;-}--.sdk-table th,-.sdk-table td {- padding: 16px;- vertical-align: top;- border: 1px solid var(--vp-c-divider);-}--.sdk-table thead th {- background: var(--vp-c-bg-soft);- color: var(--vp-c-text-2);- font-weight: 600;- text-align: left;-}--.sdk-table thead th:first-child {- border-top-left-radius: 14px;-}--.sdk-table thead th:last-child {- border-top-right-radius: 14px;-}--.sdk-table__code {- color: var(--vp-c-brand-1);-}--.sdk-table__chip {- display: inline-block;- padding: 4px 10px;- border: 1px solid var(--vp-c-divider);- border-radius: 10px;- background: var(--vp-c-bg-soft);- color: var(--vp-c-text-1);-}--.sdk-table__description-cell {- color: var(--vp-c-text-2);- line-height: 1.6;-}-</style>diff --git a/packages/docs/.vitepress/theme/index.ts b/packages/docs/.vitepress/theme/index.tsindex 4fa466cbc..294703632 100644--- a/packages/docs/.vitepress/theme/index.ts+++ b/packages/docs/.vitepress/theme/index.ts@@ -3,6 +3,7 @@ import DefaultTheme from 'vitepress/theme'import HomeLayout from './HomeLayout.vue'import SdkCard from './components/SdkCard.vue'import SdkCardGroup from './components/SdkCardGroup.vue'+import SdkDataTable from './components/SdkDataTable.vue'import SdkEventsTable from './components/SdkEventsTable.vue'import SdkField from './components/SdkField.vue'import SdkFieldGroup from './components/SdkFieldGroup.vue'@@ -16,6 +17,7 @@ export default {enhanceApp({ app }) {app.component('SdkCard', SdkCard)app.component('SdkCardGroup', SdkCardGroup)+ app.component('SdkDataTable', SdkDataTable)app.component('SdkEventsTable', SdkEventsTable)app.component('SdkField', SdkField)app.component('SdkFieldGroup', SdkFieldGroup)diff --git a/packages/docs/de/development/contributing.md b/packages/docs/de/development/contributing.mdindex 3e1918df7..94d77cda7 100644--- a/packages/docs/de/development/contributing.md+++ b/packages/docs/de/development/contributing.md@@ -69,22 +69,22 @@ Entwickler und KI-Agenten sollten `AGENTS.md` im Repo-Root lesen ([auf GitHub an## Schlüsseldateien-Engine-Quellcode lebt in `packages/core/src/`. Die `src/engine/`- und `src/kiwi/`-Dateien der App sind Re-Export-Shims — bearbeiten Sie das Core-Paket, nicht die Shims.+Der Core-Engine-Quellcode lebt in `packages/core/src/`. App-spezifischer Editor-, Dokument-, KI-, Kollaborations-, Shell-, Demo- und Automatisierungscode liegt unter `src/app/*`; das Vue SDK verwaltet wiederverwendbaren Canvas- und Composable-Code unter `packages/vue/src/`.| Datei | Zweck ||-------|-------|-| `packages/core/src/scene-graph.ts` | Szenengraph: Knoten, Variablen, Instanzen, Hit-Testing |-| `packages/core/src/renderer.ts` | CanvasKit-Rendering-Pipeline |+| `packages/core/src/scene-graph/` | Szenengraph: Knoten, Variablen, Instanzen, Hit-Testing |+| `packages/core/src/canvas/renderer.ts` | CanvasKit-Rendering-Pipeline || `packages/core/src/layout.ts` | Yoga-Layout-Adapter |-| `packages/core/src/undo.ts` | Rückgängig/Wiederherstellen-Manager |+| `packages/core/src/scene-graph/undo.ts` | Rückgängig/Wiederherstellen-Manager || `packages/core/src/clipboard.ts` | Figma-kompatible Zwischenablage |-| `packages/core/src/vector.ts` | Vektornetzwerk-Modell |-| `packages/core/src/kiwi/codec.ts` | Kiwi-Binär-Encoder/Decoder |+| `packages/core/src/vector/` | Vektornetzwerk-Modell |+| `packages/core/src/kiwi/binary/codec.ts` | Kiwi-Binär-Encoder/Decoder || `packages/core/src/kiwi/fig-import.ts` | .fig-Datei-Import-Logik || `packages/core/src/tools/` | Vereinheitlichte Werkzeugdefinitionen (KI, MCP, CLI) |-| `packages/core/src/figma-api.ts` | Figma Plugin API-Implementierung |+| `packages/core/src/figma-api/` | Figma Plugin API-Implementierung || `packages/mcp/src/server.ts` | MCP-Server-Factory || `packages/cli/src/index.ts` | CLI-Einstiegspunkt |-| `src/stores/editor.ts` | Globaler Editor-Zustand |-| `src/composables/use-canvas.ts` | Canvas-Rendering-Composable |-| `src/composables/use-keyboard.ts` | Tastenkürzel-Behandlung |+| `src/app/editor/session/create.ts` | Editor session assembly |+| `packages/vue/src/canvas/CanvasRoot.vue` | Canvas-Rendering-Composable |+| `src/app/shell/keyboard/use.ts` | Tastenkürzel-Behandlung |diff --git a/packages/docs/development/contributing.md b/packages/docs/development/contributing.mdindex fc94c90e5..078dc9822 100644--- a/packages/docs/development/contributing.md+++ b/packages/docs/development/contributing.md@@ -70,25 +70,25 @@ Developers and AI agents working on the codebase should read `AGENTS.md` in the## Key Files-Engine source lives in `packages/core/src/`. The app's `src/engine/` and `src/kiwi/` are re-export shims — edit the core package, not the shims.+Core engine source lives in `packages/core/src/`. App-specific editor, document, AI, collaboration, shell, demo, and automation code lives under `src/app/*`; the Vue SDK owns reusable canvas/composable code under `packages/vue/src/`.| File | Purpose ||------|---------|-| `packages/core/src/scene-graph.ts` | Scene graph: nodes, variables, instances, hit testing |-| `packages/core/src/renderer.ts` | CanvasKit rendering pipeline |+| `packages/core/src/scene-graph/` | Scene graph: nodes, variables, instances, hit testing |+| `packages/core/src/canvas/renderer.ts` | CanvasKit rendering pipeline || `packages/core/src/layout.ts` | Yoga layout adapter |-| `packages/core/src/undo.ts` | Undo/redo manager |+| `packages/core/src/scene-graph/undo.ts` | Undo/redo manager || `packages/core/src/clipboard.ts` | Figma-compatible clipboard |-| `packages/core/src/vector.ts` | Vector network model |-| `packages/core/src/render-image.ts` | Offscreen image export (PNG/JPG/WEBP) |-| `packages/core/src/kiwi/codec.ts` | Kiwi binary encoder/decoder |+| `packages/core/src/vector/` | Vector network model |+| `packages/core/src/io/formats/raster/render.ts` | Offscreen image export (PNG/JPG/WEBP) |+| `packages/core/src/kiwi/binary/codec.ts` | Kiwi binary encoder/decoder || `packages/core/src/kiwi/fig-import.ts` | .fig file import logic || `packages/cli/src/index.ts` | CLI entry point || `packages/core/src/tools/` | Unified tool definitions split by domain (read, create, modify, structure, variables, vector, analyze) |-| `packages/core/src/figma-api.ts` | Figma Plugin API implementation |+| `packages/core/src/figma-api/` | Figma Plugin API implementation || `packages/mcp/src/server.ts` | MCP server factory || `packages/cli/src/commands/` | CLI commands (info, tree, find, export, eval, analyze) |-| `src/stores/editor.ts` | Global editor state |-| `src/composables/use-canvas.ts` | Canvas rendering composable |-| `src/composables/use-canvas-input.ts` | Mouse/touch input handling |-| `src/composables/use-keyboard.ts` | Keyboard shortcut handling |+| `src/app/editor/session/create.ts` | Editor session assembly |+| `packages/vue/src/canvas/CanvasRoot.vue` | Canvas rendering composable |+| `packages/vue/src/canvas/useCanvasInput.ts` | Mouse/touch input handling |+| `src/app/shell/keyboard/use.ts` | Keyboard shortcut handling |diff --git a/packages/docs/development/testing.md b/packages/docs/development/testing.mdindex efecd9257..dd83a9d60 100644--- a/packages/docs/development/testing.md+++ b/packages/docs/development/testing.md@@ -57,7 +57,7 @@ Tests cover:```typescriptimport { describe, expect, it } from 'bun:test'-import { SceneGraph } from '../../src/engine/scene-graph'+import { SceneGraph } from '@open-pencil/core/scene-graph'describe('SceneGraph', () => {it('creates and retrieves a node', () => {diff --git a/packages/docs/es/development/contributing.md b/packages/docs/es/development/contributing.mdindex f6f028056..9b56dab2a 100644--- a/packages/docs/es/development/contributing.md+++ b/packages/docs/es/development/contributing.md@@ -72,25 +72,25 @@ Desarrolladores y agentes IA deben leer `AGENTS.md` en la raíz del repo ([ver e## Archivos clave-El código fuente del motor vive en `packages/core/src/`. Los directorios `src/engine/` y `src/kiwi/` de la app son shims de re-exportación — edita el paquete core, no los shims.+El código fuente del motor core vive en `packages/core/src/`. El código específico de la app para editor, documentos, IA, colaboración, shell, demo y automatización vive en `src/app/*`; el SDK Vue contiene el código reutilizable de canvas y composables en `packages/vue/src/`.| Archivo | Propósito ||---------|-----------|-| `packages/core/src/scene-graph.ts` | Grafo de escena: nodos, variables, instancias, hit testing |-| `packages/core/src/renderer.ts` | Pipeline de renderizado CanvasKit |+| `packages/core/src/scene-graph/` | Grafo de escena: nodos, variables, instancias, hit testing |+| `packages/core/src/canvas/renderer.ts` | Pipeline de renderizado CanvasKit || `packages/core/src/layout.ts` | Adaptador de layout Yoga |-| `packages/core/src/undo.ts` | Gestor de deshacer/rehacer |+| `packages/core/src/scene-graph/undo.ts` | Gestor de deshacer/rehacer || `packages/core/src/clipboard.ts` | Portapapeles compatible con Figma |-| `packages/core/src/vector.ts` | Modelo de red vectorial |-| `packages/core/src/render-image.ts` | Exportación de imagen offscreen (PNG/JPG/WEBP) |-| `packages/core/src/kiwi/codec.ts` | Codificador/decodificador binario Kiwi |+| `packages/core/src/vector/` | Modelo de red vectorial |+| `packages/core/src/io/formats/raster/render.ts` | Exportación de imagen offscreen (PNG/JPG/WEBP) |+| `packages/core/src/kiwi/binary/codec.ts` | Codificador/decodificador binario Kiwi || `packages/core/src/kiwi/fig-import.ts` | Lógica de importación de archivos .fig || `packages/cli/src/index.ts` | Punto de entrada del CLI || `packages/core/src/tools/` | Definiciones unificadas de herramientas (IA, MCP, CLI) |-| `packages/core/src/figma-api.ts` | Implementación de Figma Plugin API |+| `packages/core/src/figma-api/` | Implementación de Figma Plugin API || `packages/mcp/src/server.ts` | Factory del servidor MCP || `packages/cli/src/commands/` | Comandos CLI (info, tree, find, export, eval, analyze) |-| `src/stores/editor.ts` | Estado global del editor |-| `src/composables/use-canvas.ts` | Composable de renderizado del canvas |-| `src/composables/use-canvas-input.ts` | Manejo de entrada ratón/touch |-| `src/composables/use-keyboard.ts` | Manejo de atajos de teclado |+| `src/app/editor/session/create.ts` | Editor session assembly |+| `packages/vue/src/canvas/CanvasRoot.vue` | Composable de renderizado del canvas |+| `packages/vue/src/canvas/useCanvasInput.ts` | Manejo de entrada ratón/touch |+| `src/app/shell/keyboard/use.ts` | Manejo de atajos de teclado |diff --git a/packages/docs/fr/development/contributing.md b/packages/docs/fr/development/contributing.mdindex 3cda26f70..626eb3377 100644--- a/packages/docs/fr/development/contributing.md+++ b/packages/docs/fr/development/contributing.md@@ -72,25 +72,25 @@ Les développeurs et agents IA doivent lire `AGENTS.md` à la racine du repo ([v## Fichiers clés-Le code source du moteur se trouve dans `packages/core/src/`. Les répertoires `src/engine/` et `src/kiwi/` de l'app sont des shims de ré-exportation — éditez le package core, pas les shims.+Le code source du moteur core se trouve dans `packages/core/src/`. Le code propre à l'app pour l'éditeur, les documents, l'IA, la collaboration, le shell, les démos et l'automatisation vit sous `src/app/*`; le SDK Vue contient le code canvas et composable réutilisable dans `packages/vue/src/`.| Fichier | Objectif ||---------|----------|-| `packages/core/src/scene-graph.ts` | Graphe de scène : nœuds, variables, instances, hit testing |-| `packages/core/src/renderer.ts` | Pipeline de rendu CanvasKit |+| `packages/core/src/scene-graph/` | Graphe de scène : nœuds, variables, instances, hit testing |+| `packages/core/src/canvas/renderer.ts` | Pipeline de rendu CanvasKit || `packages/core/src/layout.ts` | Adaptateur layout Yoga |-| `packages/core/src/undo.ts` | Gestionnaire annuler/rétablir |+| `packages/core/src/scene-graph/undo.ts` | Gestionnaire annuler/rétablir || `packages/core/src/clipboard.ts` | Presse-papiers compatible Figma |-| `packages/core/src/vector.ts` | Modèle de réseau vectoriel |-| `packages/core/src/render-image.ts` | Export d'image hors-écran (PNG/JPG/WEBP) |-| `packages/core/src/kiwi/codec.ts` | Encodeur/décodeur binaire Kiwi |+| `packages/core/src/vector/` | Modèle de réseau vectoriel |+| `packages/core/src/io/formats/raster/render.ts` | Export d'image hors-écran (PNG/JPG/WEBP) |+| `packages/core/src/kiwi/binary/codec.ts` | Encodeur/décodeur binaire Kiwi || `packages/core/src/kiwi/fig-import.ts` | Logique d'import de fichiers .fig || `packages/cli/src/index.ts` | Point d'entrée du CLI || `packages/core/src/tools/` | Définitions d'outils unifiées (IA, MCP, CLI) |-| `packages/core/src/figma-api.ts` | Implémentation de Figma Plugin API |+| `packages/core/src/figma-api/` | Implémentation de Figma Plugin API || `packages/mcp/src/server.ts` | Factory du serveur MCP || `packages/cli/src/commands/` | Commandes CLI (info, tree, find, export, eval, analyze) |-| `src/stores/editor.ts` | État global de l'éditeur |-| `src/composables/use-canvas.ts` | Composable de rendu du canevas |-| `src/composables/use-canvas-input.ts` | Gestion des entrées souris/touch |-| `src/composables/use-keyboard.ts` | Gestion des raccourcis clavier |+| `src/app/editor/session/create.ts` | Editor session assembly |+| `packages/vue/src/canvas/CanvasRoot.vue` | Composable de rendu du canevas |+| `packages/vue/src/canvas/useCanvasInput.ts` | Gestion des entrées souris/touch |+| `src/app/shell/keyboard/use.ts` | Gestion des raccourcis clavier |diff --git a/packages/docs/it/development/contributing.md b/packages/docs/it/development/contributing.mdindex b56462bc9..4bdcec7d5 100644--- a/packages/docs/it/development/contributing.md+++ b/packages/docs/it/development/contributing.md@@ -72,25 +72,25 @@ Sviluppatori e agenti IA dovrebbero leggere `AGENTS.md` nella root del repo ([ve## File chiave-Il codice sorgente del motore si trova in `packages/core/src/`. I directory `src/engine/` e `src/kiwi/` dell'app sono shim di ri-esportazione — modificare il pacchetto core, non gli shim.+Il codice sorgente del motore core si trova in `packages/core/src/`. Il codice specifico dell'app per editor, documenti, IA, collaborazione, shell, demo e automazione vive in `src/app/*`; l'SDK Vue contiene il codice canvas e composable riutilizzabile in `packages/vue/src/`.| File | Scopo ||------|-------|-| `packages/core/src/scene-graph.ts` | Grafo scena: nodi, variabili, istanze, hit testing |-| `packages/core/src/renderer.ts` | Pipeline di rendering CanvasKit |+| `packages/core/src/scene-graph/` | Grafo scena: nodi, variabili, istanze, hit testing |+| `packages/core/src/canvas/renderer.ts` | Pipeline di rendering CanvasKit || `packages/core/src/layout.ts` | Adattatore layout Yoga |-| `packages/core/src/undo.ts` | Gestore annulla/ripristina |+| `packages/core/src/scene-graph/undo.ts` | Gestore annulla/ripristina || `packages/core/src/clipboard.ts` | Appunti compatibili con Figma |-| `packages/core/src/vector.ts` | Modello rete vettoriale |-| `packages/core/src/render-image.ts` | Export immagine offscreen (PNG/JPG/WEBP) |-| `packages/core/src/kiwi/codec.ts` | Encoder/decoder binario Kiwi |+| `packages/core/src/vector/` | Modello rete vettoriale |+| `packages/core/src/io/formats/raster/render.ts` | Export immagine offscreen (PNG/JPG/WEBP) |+| `packages/core/src/kiwi/binary/codec.ts` | Encoder/decoder binario Kiwi || `packages/core/src/kiwi/fig-import.ts` | Logica import file .fig || `packages/cli/src/index.ts` | Punto di ingresso CLI || `packages/core/src/tools/` | Definizioni strumenti unificate (IA, MCP, CLI) |-| `packages/core/src/figma-api.ts` | Implementazione Figma Plugin API |+| `packages/core/src/figma-api/` | Implementazione Figma Plugin API || `packages/mcp/src/server.ts` | Factory del server MCP || `packages/cli/src/commands/` | Comandi CLI (info, tree, find, export, eval, analyze) |-| `src/stores/editor.ts` | Stato globale dell'editor |-| `src/composables/use-canvas.ts` | Composable rendering canvas |-| `src/composables/use-canvas-input.ts` | Gestione input mouse/touch |-| `src/composables/use-keyboard.ts` | Gestione scorciatoie tastiera |+| `src/app/editor/session/create.ts` | Editor session assembly |+| `packages/vue/src/canvas/CanvasRoot.vue` | Composable rendering canvas |+| `packages/vue/src/canvas/useCanvasInput.ts` | Gestione input mouse/touch |+| `src/app/shell/keyboard/use.ts` | Gestione scorciatoie tastiera |diff --git a/packages/docs/pl/development/contributing.md b/packages/docs/pl/development/contributing.mdindex 90728c41d..598060ba2 100644--- a/packages/docs/pl/development/contributing.md+++ b/packages/docs/pl/development/contributing.md@@ -72,25 +72,25 @@ Deweloperzy i agenci AI powinni przeczytać `AGENTS.md` w katalogu głównym rep## Kluczowe pliki-Kod źródłowy silnika znajduje się w `packages/core/src/`. Katalogi `src/engine/` i `src/kiwi/` aplikacji to shimy re-eksportu — edytuj pakiet core, nie shimy.+Kod źródłowy silnika core znajduje się w `packages/core/src/`. Kod aplikacyjny edytora, dokumentów, AI, współpracy, shella, demo i automatyzacji znajduje się w `src/app/*`; SDK Vue zawiera wielokrotnego użytku kod canvasu i composable w `packages/vue/src/`.| Plik | Cel ||------|-----|-| `packages/core/src/scene-graph.ts` | Graf sceny: węzły, zmienne, instancje, hit testing |-| `packages/core/src/renderer.ts` | Pipeline renderowania CanvasKit |+| `packages/core/src/scene-graph/` | Graf sceny: węzły, zmienne, instancje, hit testing |+| `packages/core/src/canvas/renderer.ts` | Pipeline renderowania CanvasKit || `packages/core/src/layout.ts` | Adapter layoutu Yoga |-| `packages/core/src/undo.ts` | Menedżer cofnij/ponów |+| `packages/core/src/scene-graph/undo.ts` | Menedżer cofnij/ponów || `packages/core/src/clipboard.ts` | Schowek kompatybilny z Figmą |-| `packages/core/src/vector.ts` | Model sieci wektorowej |-| `packages/core/src/render-image.ts` | Eksport obrazu offscreen (PNG/JPG/WEBP) |-| `packages/core/src/kiwi/codec.ts` | Koder/dekoder binarny Kiwi |+| `packages/core/src/vector/` | Model sieci wektorowej |+| `packages/core/src/io/formats/raster/render.ts` | Eksport obrazu offscreen (PNG/JPG/WEBP) |+| `packages/core/src/kiwi/binary/codec.ts` | Koder/dekoder binarny Kiwi || `packages/core/src/kiwi/fig-import.ts` | Logika importu plików .fig || `packages/cli/src/index.ts` | Punkt wejścia CLI || `packages/core/src/tools/` | Ujednolicone definicje narzędzi (AI, MCP, CLI) |-| `packages/core/src/figma-api.ts` | Implementacja Figma Plugin API |+| `packages/core/src/figma-api/` | Implementacja Figma Plugin API || `packages/mcp/src/server.ts` | Fabryka serwera MCP || `packages/cli/src/commands/` | Polecenia CLI (info, tree, find, export, eval, analyze) |-| `src/stores/editor.ts` | Globalny stan edytora |-| `src/composables/use-canvas.ts` | Composable renderowania canvasu |-| `src/composables/use-canvas-input.ts` | Obsługa wejścia mysz/dotyk |-| `src/composables/use-keyboard.ts` | Obsługa skrótów klawiszowych |+| `src/app/editor/session/create.ts` | Editor session assembly |+| `packages/vue/src/canvas/CanvasRoot.vue` | Composable renderowania canvasu |+| `packages/vue/src/canvas/useCanvasInput.ts` | Obsługa wejścia mysz/dotyk |+| `src/app/shell/keyboard/use.ts` | Obsługa skrótów klawiszowych |diff --git a/packages/docs/ru/development/contributing.md b/packages/docs/ru/development/contributing.mdindex 8383b4a77..246943bc7 100644--- a/packages/docs/ru/development/contributing.md+++ b/packages/docs/ru/development/contributing.md@@ -72,25 +72,25 @@ bun run check## Ключевые файлы-Исходники движка находятся в `packages/core/src/`. Файлы `src/engine/` и `src/kiwi/` приложения — это шимы реэкспорта. Редактируйте пакет core, а не шимы.+Исходники core-движка находятся в `packages/core/src/`. Код приложения для редактора, документов, AI, коллаборации, shell, демо и автоматизации живёт в `src/app/*`; Vue SDK содержит переиспользуемый canvas/composable-код в `packages/vue/src/`.| Файл | Назначение ||------|------------|-| `packages/core/src/scene-graph.ts` | Граф сцены: узлы, переменные, экземпляры, проверка попадания |-| `packages/core/src/renderer.ts` | Конвейер отрисовки CanvasKit |+| `packages/core/src/scene-graph/` | Граф сцены: узлы, переменные, экземпляры, проверка попадания |+| `packages/core/src/canvas/renderer.ts` | Конвейер отрисовки CanvasKit || `packages/core/src/layout.ts` | Адаптер компоновки Yoga |-| `packages/core/src/undo.ts` | Менеджер отмены/повтора |+| `packages/core/src/scene-graph/undo.ts` | Менеджер отмены/повтора || `packages/core/src/clipboard.ts` | Figma-совместимый буфер обмена |-| `packages/core/src/vector.ts` | Модель векторных сетей |-| `packages/core/src/render-image.ts` | Внеэкранный экспорт изображений (PNG/JPG/WEBP) |-| `packages/core/src/kiwi/codec.ts` | Бинарный кодировщик/декодировщик Kiwi |+| `packages/core/src/vector/` | Модель векторных сетей |+| `packages/core/src/io/formats/raster/render.ts` | Внеэкранный экспорт изображений (PNG/JPG/WEBP) |+| `packages/core/src/kiwi/binary/codec.ts` | Бинарный кодировщик/декодировщик Kiwi || `packages/core/src/kiwi/fig-import.ts` | Логика импорта .fig файлов || `packages/cli/src/index.ts` | Точка входа CLI || `packages/core/src/tools/` | Унифицированные определения инструментов по доменам (read, create, modify, structure, variables, vector, analyze) |-| `packages/core/src/figma-api.ts` | Реализация Figma Plugin API |+| `packages/core/src/figma-api/` | Реализация Figma Plugin API || `packages/mcp/src/server.ts` | Фабрика MCP-сервера || `packages/cli/src/commands/` | Команды CLI (info, tree, find, export, eval, analyze) |-| `src/stores/editor.ts` | Глобальное состояние редактора |-| `src/composables/use-canvas.ts` | Composable отрисовки холста |-| `src/composables/use-canvas-input.ts` | Обработка ввода мышью/тачем |-| `src/composables/use-keyboard.ts` | Обработка сочетаний клавиш |+| `src/app/editor/session/create.ts` | Editor session assembly |+| `packages/vue/src/canvas/CanvasRoot.vue` | Composable отрисовки холста |+| `packages/vue/src/canvas/useCanvasInput.ts` | Обработка ввода мышью/тачем |+| `src/app/shell/keyboard/use.ts` | Обработка сочетаний клавиш |diff --git a/packages/docs/ru/development/testing.md b/packages/docs/ru/development/testing.mdindex 9eb421a17..cd8d09e52 100644--- a/packages/docs/ru/development/testing.md+++ b/packages/docs/ru/development/testing.md@@ -57,7 +57,7 @@ bun run test:unit```typescriptimport { describe, expect, it } from 'bun:test'-import { SceneGraph } from '../../src/engine/scene-graph'+import { SceneGraph } from '@open-pencil/core/scene-graph'describe('SceneGraph', () => {it('creates and retrieves a node', () => {diff --git a/packages/mcp/package.json b/packages/mcp/package.jsonindex cd73e2946..2981a2dc5 100644--- a/packages/mcp/package.json+++ b/packages/mcp/package.json@@ -3,6 +3,13 @@"version": "0.11.8","license": "MIT","type": "module",+ "imports": {+ "#mcp/*": {+ "types": "./src/*.ts",+ "bun": "./src/*.ts",+ "default": "./dist/*.js"+ }+ },"main": "./dist/server.js","bin": {"openpencil-mcp": "./dist/stdio.js",diff --git a/packages/mcp/src/auth.ts b/packages/mcp/src/auth.tsnew file mode 100644index 000000000..79d4c100e--- /dev/null+++ b/packages/mcp/src/auth.ts@@ -0,0 +1,14 @@+export function bearerToken(header: string | undefined | null): string | null {+ return header?.startsWith('Bearer ') ? header.slice('Bearer '.length) : null+}++export function mcpRequestToken(+ authorization: string | undefined | null,+ headerToken: string | undefined | null,+): string | null {+ return bearerToken(authorization) ?? headerToken ?? null+}++export function isAuthorized(provided: string | null, expected: string | null): boolean {+ return expected === null || provided === expected+}diff --git a/packages/mcp/src/browser-rpc.ts b/packages/mcp/src/browser-rpc.tsnew file mode 100644index 000000000..a77416bc4--- /dev/null+++ b/packages/mcp/src/browser-rpc.ts@@ -0,0 +1,114 @@+import { randomUUID } from 'node:crypto'++import type { WebSocket } from 'ws'++const RPC_TIMEOUT = 30_000++type PendingRequest = {+ resolve: (value: unknown) => void+ reject: (error: Error) => void+ timer: ReturnType<typeof setTimeout>+}++type BrowserRpcBridgeOptions = {+ authToken: string | null+ onConnectionChange: () => void+}++type BrowserMessage = {+ type: string+ id?: string+ token?: string+ result?: unknown+ error?: string+ ok?: boolean+}++export function createBrowserRpcBridge({ authToken, onConnectionChange }: BrowserRpcBridgeOptions) {+ const pending = new Map<string, PendingRequest>()+ let browserWs: WebSocket | null = null+ let browserToken: string | null = null+ let browserRegistered = false++ function currentRpcToken(): string | null {+ return authToken ?? browserToken+ }++ function isConnected(): boolean {+ return Boolean(browserWs && browserRegistered)+ }++ function rejectAllPending(reason: string) {+ for (const [id, req] of pending) {+ clearTimeout(req.timer)+ req.reject(new Error(reason))+ pending.delete(id)+ }+ }++ function sendRpc(body: Record<string, unknown>): Promise<unknown> {+ return new Promise((resolve, reject) => {+ if (!browserWs || browserWs.readyState !== browserWs.OPEN || !browserRegistered) {+ reject(new Error('OpenPencil app is not connected'))+ return+ }+ const id = randomUUID()+ const timer = setTimeout(() => {+ pending.delete(id)+ reject(new Error('RPC timeout (30s)'))+ }, RPC_TIMEOUT)+ pending.set(id, { resolve, reject, timer })+ browserWs.send(JSON.stringify({ type: 'request', id, ...body }))+ })+ }++ function handleMessage(data: string, ws: WebSocket) {+ try {+ const msg = JSON.parse(data) as BrowserMessage+ if (msg.type === 'register' && msg.token) {+ if (authToken && msg.token !== authToken) {+ ws.close()+ return+ }+ if (browserWs && browserWs !== ws && browserWs.readyState === ws.OPEN) {+ browserWs.close()+ rejectAllPending('Browser reconnected')+ }+ browserWs = ws+ browserToken = msg.token+ browserRegistered = true+ onConnectionChange()+ return+ }+ if (!browserRegistered || browserWs !== ws) return+ if (msg.type === 'response' && msg.id) {+ const req = pending.get(msg.id)+ if (!req) return+ pending.delete(msg.id)+ clearTimeout(req.timer)+ if (msg.ok === false) req.reject(new Error(msg.error ?? 'RPC failed'))+ else {+ const { type: _, id: __, ...payload } = msg+ req.resolve(payload)+ }+ }+ } catch (e) {+ console.warn('Malformed automation message:', e)+ }+ }++ function handleClose(ws: WebSocket) {+ if (browserWs !== ws) return+ browserWs = null+ browserToken = null+ browserRegistered = false+ rejectAllPending('Browser disconnected')+ onConnectionChange()+ }++ function close() {+ rejectAllPending('Server shutting down')+ }++ return { close, currentRpcToken, handleClose, handleMessage, isConnected, sendRpc }+}diff --git a/packages/mcp/src/http-options.ts b/packages/mcp/src/http-options.tsnew file mode 100644index 000000000..aadf8cf9f--- /dev/null+++ b/packages/mcp/src/http-options.ts@@ -0,0 +1,12 @@+export const MCP_CORS_METHODS = ['GET', 'POST', 'DELETE', 'OPTIONS']++export const MCP_CORS_HEADERS = [+ 'Content-Type',+ 'Authorization',+ 'x-mcp-token',+ 'mcp-session-id',+ 'Last-Event-ID',+ 'mcp-protocol-version',+]++export const MCP_EXPOSED_HEADERS = ['mcp-session-id', 'mcp-protocol-version']diff --git a/packages/mcp/src/jsx-preprocess.ts b/packages/mcp/src/jsx-preprocess.tsnew file mode 100644index 000000000..7ac1feb95--- /dev/null+++ b/packages/mcp/src/jsx-preprocess.ts@@ -0,0 +1,19 @@+import { buildComponent, createElement, resolveToTree } from '@open-pencil/core/design-jsx'++export function preprocessRpc(body: Record<string, unknown>): Record<string, unknown> {+ if (body.command !== 'tool') return body+ const args = body.args as { name?: string; args?: Record<string, unknown> } | undefined+ if (args?.name !== 'render' || !args.args?.jsx) return body+ try {+ const Component = buildComponent(args.args.jsx as string)+ const element = createElement(Component, null)+ const tree = resolveToTree(element)+ return {+ ...body,+ args: { ...args, args: { ...args.args, jsx: undefined, tree } },+ }+ } catch (e) {+ console.warn('JSX preprocessing failed, passing raw:', e instanceof Error ? e.message : e)+ return body+ }+}diff --git a/packages/mcp/src/mcp-sessions.ts b/packages/mcp/src/mcp-sessions.tsnew file mode 100644index 000000000..29267723b--- /dev/null+++ b/packages/mcp/src/mcp-sessions.ts@@ -0,0 +1,82 @@+import { randomUUID } from 'node:crypto'++import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'+import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js'++export type MCPTransport = { handleRequest: (request: Request) => Promise<Response> }++type MCPSession = {+ transport: MCPTransport+ server: McpServer+ lastSeen: number+}++type McpSessionManagerOptions = {+ serverVersion: string+ registerTools: (server: McpServer) => void+}++const MAX_MCP_SESSIONS = 10+const MCP_SESSION_TTL_MS = 15 * 60_000++export function createMcpSessionManager({ serverVersion, registerTools }: McpSessionManagerOptions) {+ const sessions = new Map<string, MCPSession>()++ function notifyToolsChanged() {+ for (const session of sessions.values()) {+ try {+ session.server.sendToolListChanged()+ } catch {+ continue+ }+ }+ }++ function cleanupExpired() {+ const now = Date.now()+ for (const [id, session] of sessions) {+ if (now - session.lastSeen > MCP_SESSION_TTL_MS) {+ sessions.delete(id)+ }+ }+ }++ function createSession(id: string): MCPTransport {+ const server = new McpServer({ name: 'open-pencil', version: serverVersion })+ registerTools(server)++ const transport = new WebStandardStreamableHTTPServerTransport({+ sessionIdGenerator: () => id,+ })+ void server.connect(transport)+ sessions.set(id, { transport, server, lastSeen: Date.now() })+ return transport+ }++ function resolveTransport(sessionId: string | undefined): MCPTransport | { error: 'too_many' } {+ cleanupExpired()+ const existing = sessionId ? sessions.get(sessionId) : undefined+ if (!existing && sessions.size >= MAX_MCP_SESSIONS) {+ return { error: 'too_many' }+ }+ return existing?.transport ?? createSession(sessionId ?? randomUUID())+ }++ function touch(sessionId: string | undefined, transport: MCPTransport) {+ const resolvedSessionId =+ sessionId ?? [...sessions.entries()].find(([, entry]) => entry.transport === transport)?.[0]+ if (!resolvedSessionId) return+ const session = sessions.get(resolvedSessionId)+ if (session) session.lastSeen = Date.now()+ }++ function deleteSession(sessionId: string | undefined) {+ if (sessionId) sessions.delete(sessionId)+ }++ function clear() {+ sessions.clear()+ }++ return { clear, deleteSession, notifyToolsChanged, resolveTransport, touch }+}diff --git a/packages/mcp/src/result.ts b/packages/mcp/src/result.tsnew file mode 100644index 000000000..f811cd8e6--- /dev/null+++ b/packages/mcp/src/result.ts@@ -0,0 +1,14 @@+export type MCPContent =+ | { type: 'text'; text: string }+ | { type: 'image'; data: string; mimeType: string }++export type MCPResult = { content: MCPContent[]; isError?: boolean }++export function ok(data: unknown): MCPResult {+ return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] }+}++export function fail(e: unknown): MCPResult {+ const msg = e instanceof Error ? e.message : String(e)+ return { content: [{ type: 'text', text: JSON.stringify({ error: msg }) }], isError: true }+}diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.tsindex d6585e223..1d006ecee 100644--- a/packages/mcp/src/server.ts+++ b/packages/mcp/src/server.ts@@ -1,228 +1,23 @@-import { randomUUID } from 'node:crypto'-import { writeFile, mkdir } from 'node:fs/promises'import { createRequire } from 'node:module'-import { resolve, dirname, sep as osSep } from 'node:path'--import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'-import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js'import { Hono } from 'hono'import { cors } from 'hono/cors'-import { WebSocketServer, type WebSocket } from 'ws'-import { z } from 'zod'--import {- ALL_TOOLS,- CODEGEN_PROMPT,- buildComponent,- createElement,- resolveToTree-} from '@open-pencil/core'+import { WebSocketServer } from 'ws'+import { bearerToken, isAuthorized, mcpRequestToken } from './auth'+import { createBrowserRpcBridge } from './browser-rpc'+import { MCP_CORS_HEADERS, MCP_CORS_METHODS, MCP_EXPOSED_HEADERS } from './http-options'+import { preprocessRpc } from './jsx-preprocess'+import { createMcpSessionManager } from './mcp-sessions'+import { registerTools } from './tool/registration'-import type { ParamDef, ParamType } from '@open-pencil/core'+import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'const require = createRequire(import.meta.url)export const MCP_VERSION: string = (require('../package.json') as { version: string }).version-export type MCPContent =- | { type: 'text'; text: string }- | { type: 'image'; data: string; mimeType: string }-export type MCPResult = { content: MCPContent[]; isError?: boolean }--const RPC_TIMEOUT = 30_000--interface PendingRequest {- resolve: (value: unknown) => void- reject: (error: Error) => void- timer: ReturnType<typeof setTimeout>-}--export function ok(data: unknown): MCPResult {- return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] }-}--export function fail(e: unknown): MCPResult {- const msg = e instanceof Error ? e.message : String(e)- return { content: [{ type: 'text', text: JSON.stringify({ error: msg }) }], isError: true }-}--export type RpcSender = (body: Record<string, unknown>) => Promise<unknown>--export interface RegisterToolsOptions {- enableEval: boolean- mcpRoot?: string | null- sendRpc: RpcSender-}--function resolveSafePath(filePath: string, root: string): string {- const resolved = resolve(filePath)- const sep = root.endsWith('/') || root.endsWith('\\') ? '' : osSep- if (!resolved.startsWith(root + sep) && resolved !== root) {- throw new Error(`Path is outside the allowed root: ${root}`)- }- return resolved-}+export { fail, ok, type MCPContent, type MCPResult } from './result'-export function registerTools(mcpServer: McpServer, options: RegisterToolsOptions) {- const { enableEval, sendRpc } = options- const resolvedRoot = options.mcpRoot ? resolve(options.mcpRoot) : null- const register = mcpServer.registerTool.bind(mcpServer) as (...a: unknown[]) => void-- async function writeToolOutput(- toolName: string,- r: Record<string, unknown>,- filePath: string,- root: string- ): Promise<MCPResult | null> {- const resolved = resolveSafePath(filePath, root)- await mkdir(dirname(resolved), { recursive: true })- if (toolName === 'export_svg' && typeof r.svg === 'string') {- await writeFile(resolved, r.svg, 'utf8')- return ok({ written: resolved, byteLength: Buffer.byteLength(r.svg, 'utf8') })- }- if (toolName === 'export_image' && typeof r.base64 === 'string') {- await writeFile(resolved, Buffer.from(r.base64, 'base64'))- return ok({ written: resolved, byteLength: r.byteLength ?? null })- }- if (toolName === 'get_jsx' && typeof r.jsx === 'string') {- await writeFile(resolved, r.jsx, 'utf8')- return ok({ written: resolved, byteLength: Buffer.byteLength(r.jsx, 'utf8') })- }- return null- }-- for (const def of ALL_TOOLS) {- if (!enableEval && def.name === 'eval') continue- const shape: Record<string, z.ZodType> = {}- for (const [key, param] of Object.entries(def.params)) {- shape[key] = paramToZod(param)- }- register(- def.name,- { description: def.description, inputSchema: z.object(shape) },- async (args: Record<string, unknown>) => {- try {- const result = await sendRpc({ command: 'tool', args: { name: def.name, args } })- const res = result as { ok?: boolean; result?: unknown; error?: string }- if (res.ok === false) return fail(new Error(res.error))- const r = res.result as Record<string, unknown> | undefined- const filePath = typeof args.path === 'string' ? args.path : null- if (r && filePath && resolvedRoot) {- const written = await writeToolOutput(def.name, r, filePath, resolvedRoot)- if (written) return written- }- if (r && 'base64' in r && 'mimeType' in r) {- return {- content: [- {- type: 'image' as const,- data: r.base64 as string,- mimeType: r.mimeType as string- }- ]- }- }- return ok(r)- } catch (e) {- return fail(e)- }- }- )- }-- register(- 'save_file',- {- description:- 'Save the current document to disk. Uses the existing file path if available, otherwise prompts for a location.',- inputSchema: z.object({})- },- async () => {- try {- const result = await sendRpc({ command: 'save_file' })- const res = result as { ok?: boolean; error?: string }- if (res.ok === false) return fail(new Error(res.error))- return ok({ saved: true })- } catch (e) {- return fail(e)- }- }- )-- if (resolvedRoot) {- register(- 'open_file',- {- description: `Open a .fig or .pen file from disk into a new tab. Path must be inside ${resolvedRoot}.`,- inputSchema: z.object({- path: z.string().describe('Absolute path to the design file')- })- },- async (args: { path: string }) => {- try {- const safe = resolveSafePath(args.path, resolvedRoot)- const result = await sendRpc({ command: 'open_file', args: { path: safe } })- const res = result as { ok?: boolean; error?: string }- if (res.ok === false) return fail(new Error(res.error))- return ok({ opened: true })- } catch (e) {- return fail(e)- }- }- )-- register(- 'new_document',- {- description: `Create a new empty document. Optionally set a save path inside ${resolvedRoot}.`,- inputSchema: z.object({- path: z.string().describe('Optional absolute path for the new file').optional()- })- },- async (args: { path?: string }) => {- try {- const safePath = args.path ? resolveSafePath(args.path, resolvedRoot) : undefined- const result = await sendRpc({ command: 'new_document', args: { path: safePath } })- const res = result as { ok?: boolean; error?: string }- if (res.ok === false) return fail(new Error(res.error))- return ok({ created: true })- } catch (e) {- return fail(e)- }- }- )- }-- register(- 'get_codegen_prompt',- {- description:- 'Get design-to-code generation guidelines. Call before generating frontend code.',- inputSchema: z.object({})- },- async () => ok({ prompt: CODEGEN_PROMPT })- )-}--export function paramToZod(param: ParamDef): z.ZodType {- const typeMap: Record<ParamType, () => z.ZodType> = {- string: () =>- param.enum- ? z.enum(param.enum as [string, ...string[]]).describe(param.description)- : z.string().describe(param.description),- number: () => {- let s = z.coerce.number()- if (param.min !== undefined) s = s.min(param.min)- if (param.max !== undefined) s = s.max(param.max)- return s.describe(param.description)- },- boolean: () => z.boolean().describe(param.description),- color: () => z.string().describe(param.description),- 'string[]': () => z.array(z.string()).min(1).describe(param.description)- }-- const schema = typeMap[param.type]()- return param.required ? schema : schema.optional()-}+export { registerTools, type RegisterToolsOptions, type RpcSender } from './tool/registration'+export { paramToZod } from './tool/schema'export interface ServerOptions {httpPort?: number@@ -241,124 +36,34 @@ export function startServer(options: ServerOptions = {}) {const authToken = options.authToken ?? nullconst corsOrigin = options.corsOrigin ?? null- const pending = new Map<string, PendingRequest>()- let browserWs: WebSocket | null = null- let browserToken: string | null = null- let browserRegistered = false-- function currentRpcToken(): string | null {- return authToken ?? browserToken- }+ const mcpSessions = createMcpSessionManager({+ serverVersion: MCP_VERSION,+ registerTools: (mcpServer: McpServer) =>+ registerTools(mcpServer, { enableEval, mcpRoot, sendRpc: sendToBrowser })+ })+ const browserRpc = createBrowserRpcBridge({+ authToken,+ onConnectionChange: mcpSessions.notifyToolsChanged+ })+ const sendToBrowser = browserRpc.sendRpc// --- WebSocket: browser connects here ---- function sendToBrowser(body: Record<string, unknown>): Promise<unknown> {- return new Promise((resolve, reject) => {- if (!browserWs || browserWs.readyState !== browserWs.OPEN || !browserRegistered) {- reject(new Error('OpenPencil app is not connected'))- return- }- const id = randomUUID()- const timer = setTimeout(() => {- pending.delete(id)- reject(new Error('RPC timeout (30s)'))- }, RPC_TIMEOUT)- pending.set(id, { resolve, reject, timer })- browserWs.send(JSON.stringify({ type: 'request', id, ...body }))- })- }-- function handleBrowserMessage(data: string, ws: WebSocket) {- try {- const msg = JSON.parse(data) as {- type: string- id?: string- token?: string- result?: unknown- error?: string- ok?: boolean- }- if (msg.type === 'register' && msg.token) {- if (authToken && msg.token !== authToken) {- ws.close()- return- }- if (browserWs && browserWs !== ws && browserWs.readyState === WebSocket.OPEN) {- browserWs.close()- rejectAllPending('Browser reconnected')- }- browserWs = ws- browserToken = msg.token- browserRegistered = true- notifyToolsChanged()- return- }- if (!browserRegistered || browserWs !== ws) return- if (msg.type === 'response' && msg.id) {- const req = pending.get(msg.id)- if (!req) return- pending.delete(msg.id)- clearTimeout(req.timer)- if (msg.ok === false) req.reject(new Error(msg.error ?? 'RPC failed'))- else {- const { type: _, id: __, ...payload } = msg- req.resolve(payload)- }- }- } catch (e) {- console.warn('Malformed automation message:', e)- }- }-- function rejectAllPending(reason: string) {- for (const [id, req] of pending) {- clearTimeout(req.timer)- req.reject(new Error(reason))- pending.delete(id)- }- }-const wss = new WebSocketServer({ port: wsPort, host: '127.0.0.1' })wss.on('connection', (ws) => {ws.on('message', (raw) => {- handleBrowserMessage(+ browserRpc.handleMessage(typeof raw === 'string' ? raw : Buffer.from(raw as Buffer).toString('utf-8'),ws)})ws.on('close', () => {- if (browserWs === ws) {- browserWs = null- browserToken = null- browserRegistered = false- rejectAllPending('Browser disconnected')- notifyToolsChanged()- }+ browserRpc.handleClose(ws)})})- // --- JSX preprocessing ----- function preprocessRpc(body: Record<string, unknown>): Record<string, unknown> {- if (body.command !== 'tool') return body- const args = body.args as { name?: string; args?: Record<string, unknown> } | undefined- if (args?.name !== 'render' || !args.args?.jsx) return body- try {- const Component = buildComponent(args.args.jsx as string)- const element = createElement(Component, null)- const tree = resolveToTree(element)- return {- ...body,- args: { ...args, args: { ...args.args, jsx: undefined, tree } }- }- } catch (e) {- console.warn('JSX preprocessing failed, passing raw:', e instanceof Error ? e.message : e)- return body- }- }-// --- HTTP server ---const app = new Hono()@@ -368,36 +73,28 @@ export function startServer(options: ServerOptions = {}) {'*',cors({origin: corsOrigin,- allowMethods: ['GET', 'POST', 'DELETE', 'OPTIONS'],- allowHeaders: [- 'Content-Type',- 'Authorization',- 'x-mcp-token',- 'mcp-session-id',- 'Last-Event-ID',- 'mcp-protocol-version'- ],- exposeHeaders: ['mcp-session-id', 'mcp-protocol-version']+ allowMethods: MCP_CORS_METHODS,+ allowHeaders: MCP_CORS_HEADERS,+ exposeHeaders: MCP_EXPOSED_HEADERS}))}app.get('/health', (c) =>c.json({- status: browserWs && browserRegistered ? 'ok' : 'no_app',+ status: browserRpc.isConnected() ? 'ok' : 'no_app',authRequired: authToken !== null,- ...(currentRpcToken() ? { token: currentRpcToken() } : {})+ ...(browserRpc.currentRpcToken() ? { token: browserRpc.currentRpcToken() } : {})}))app.use('/rpc', async (c, next) => {- const rpcToken = currentRpcToken()- if (!browserWs || !browserRegistered || !rpcToken) {+ const rpcToken = browserRpc.currentRpcToken()+ if (!browserRpc.isConnected() || !rpcToken) {return c.json({ error: 'OpenPencil app is not connected. Is a document open?' }, 503)}- const auth = c.req.header('authorization')- const provided = auth?.startsWith('Bearer ') ? auth.slice(7) : null- if (provided !== rpcToken) {+ const provided = bearerToken(c.req.header('authorization'))+ if (!isAuthorized(provided, rpcToken)) {return c.json({ error: 'Unauthorized' }, 401)}return next()@@ -420,79 +117,31 @@ export function startServer(options: ServerOptions = {}) {// --- MCP Streamable HTTP ---- type MCPTransport = { handleRequest: (r: Request) => Promise<Response> }- interface MCPSession {- transport: MCPTransport- server: McpServer- lastSeen: number- }- const mcpSessions = new Map<string, MCPSession>()-- function notifyToolsChanged() {- for (const session of mcpSessions.values()) {- session.server.sendToolListChanged().catch(() => undefined)- }- }- const MAX_MCP_SESSIONS = 10- const MCP_SESSION_TTL_MS = 15 * 60_000-- function cleanupExpiredMCPSessions() {- const now = Date.now()- for (const [id, session] of mcpSessions) {- if (now - session.lastSeen > MCP_SESSION_TTL_MS) {- mcpSessions.delete(id)- }- }- }-- function createMCPSession(id: string): MCPTransport {- const mcpServer = new McpServer({ name: 'open-pencil', version: MCP_VERSION })- registerTools(mcpServer, { enableEval, mcpRoot, sendRpc: sendToBrowser })-- const transport = new WebStandardStreamableHTTPServerTransport({- sessionIdGenerator: () => id- })- void mcpServer.connect(transport)- mcpSessions.set(id, { transport, server: mcpServer, lastSeen: Date.now() })- return transport- }-app.all('/mcp', async (c) => {if (authToken) {- const auth = c.req.header('authorization')- const token = auth?.startsWith('Bearer ')- ? auth.slice('Bearer '.length)- : c.req.header('x-mcp-token')- if (token !== authToken) {+ const token = mcpRequestToken(c.req.header('authorization'), c.req.header('x-mcp-token'))+ if (!isAuthorized(token, authToken)) {return c.json({ error: 'Unauthorized' }, 401)}}- cleanupExpiredMCPSessions()const sessionId = c.req.header('mcp-session-id') ?? undefined- const existing = sessionId ? mcpSessions.get(sessionId) : undefined- if (!existing && mcpSessions.size >= MAX_MCP_SESSIONS) {+ const transport = mcpSessions.resolveTransport(sessionId)+ if ('error' in transport) {return c.json({ error: 'Too many active MCP sessions' },{ status: 503, headers: { 'Retry-After': '5' } })}- const transport = existing?.transport ?? createMCPSession(sessionId ?? randomUUID())- const resolvedSessionId =- sessionId ??- [...mcpSessions.entries()].find(([, entry]) => entry.transport === transport)?.[0]- if (resolvedSessionId) {- const session = mcpSessions.get(resolvedSessionId)- if (session) session.lastSeen = Date.now()- }+ mcpSessions.touch(sessionId, transport)const response = await transport.handleRequest(c.req.raw)- if (c.req.method === 'DELETE' && sessionId) {- mcpSessions.delete(sessionId)+ if (c.req.method === 'DELETE') {+ mcpSessions.deleteSession(sessionId)}return response})function close() {- rejectAllPending('Server shutting down')+ browserRpc.close()mcpSessions.clear()wss.close()}diff --git a/packages/mcp/src/stdio-bridge.ts b/packages/mcp/src/stdio-bridge.tsnew file mode 100644index 000000000..f564465b4--- /dev/null+++ b/packages/mcp/src/stdio-bridge.ts@@ -0,0 +1,112 @@+import { WebSocket } from 'ws'++type PendingRequest = {+ resolve: (value: unknown) => void+ reject: (error: Error) => void+ timer: ReturnType<typeof setTimeout>+}++type StdioRpcBridgeOptions = {+ wsUrl: string+ reconnectDelayMs?: number+ onOpen?: () => void+ onMalformedMessage?: () => void+}++const RPC_TIMEOUT = 30_000+const DISCONNECTED_MESSAGE =+ 'OpenPencil app is not connected. ' ++ 'STOP and tell the user: "The OpenPencil desktop app is not running or no document is open. ' ++ 'Please start the app and open a document, then try again." ' ++ 'Do NOT attempt to start the app yourself or retry automatically.'++function wsMessageToString(raw: WebSocket.RawData): string {+ if (Buffer.isBuffer(raw)) return raw.toString('utf8')+ if (Array.isArray(raw)) return Buffer.concat(raw).toString('utf8')+ return Buffer.from(raw).toString('utf8')+}++export function createStdioRpcBridge({+ wsUrl,+ reconnectDelayMs = 2000,+ onOpen,+ onMalformedMessage,+}: StdioRpcBridgeOptions) {+ const pending = new Map<string, PendingRequest>()+ let ws: WebSocket | null = null+ let registered = false++ function rejectAllPending(reason: string) {+ for (const [id, req] of pending) {+ clearTimeout(req.timer)+ req.reject(new Error(reason))+ pending.delete(id)+ }+ }++ function connect() {+ ws = new WebSocket(wsUrl)++ ws.on('open', () => {+ onOpen?.()+ })++ ws.on('message', (raw) => {+ try {+ const msg = JSON.parse(wsMessageToString(raw)) as {+ type: string+ id?: string+ token?: string+ result?: unknown+ error?: string+ ok?: boolean+ }+ if (msg.type === 'register' && msg.token) {+ registered = true+ return+ }+ if (msg.type === 'response' && msg.id) {+ const req = pending.get(msg.id)+ if (!req) return+ pending.delete(msg.id)+ clearTimeout(req.timer)+ if (msg.ok === false) req.reject(new Error(msg.error ?? 'RPC failed'))+ else {+ const { type: _, id: __, ...payload } = msg+ req.resolve(payload)+ }+ }+ } catch {+ onMalformedMessage?.()+ }+ })++ ws.on('close', () => {+ registered = false+ rejectAllPending('WebSocket closed')+ setTimeout(connect, reconnectDelayMs)+ })++ ws.on('error', () => {+ ws?.close()+ })+ }++ function sendRpc(body: Record<string, unknown>): Promise<unknown> {+ return new Promise((resolve, reject) => {+ if (!ws || ws.readyState !== WebSocket.OPEN || !registered) {+ reject(new Error(DISCONNECTED_MESSAGE))+ return+ }+ const id = crypto.randomUUID()+ const timer = setTimeout(() => {+ pending.delete(id)+ reject(new Error('RPC timeout (30s)'))+ }, RPC_TIMEOUT)+ pending.set(id, { resolve, reject, timer })+ ws.send(JSON.stringify({ type: 'request', id, ...body }))+ })+ }++ return { connect, sendRpc }+}diff --git a/packages/mcp/src/stdio.ts b/packages/mcp/src/stdio.tsindex b3598d9ab..6f0351ed3 100644--- a/packages/mcp/src/stdio.ts+++ b/packages/mcp/src/stdio.ts@@ -1,8 +1,8 @@#!/usr/bin/env nodeimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'-import { WebSocket } from 'ws'+import { createStdioRpcBridge } from './stdio-bridge.js'import { MCP_VERSION, registerTools } from './server.js'const wsPort = parseInt(process.env.WS_PORT ?? '7601', 10)@@ -11,101 +11,20 @@ const enableEval = process.env.OPENPENCIL_MCP_EVAL === '1'const mcpRoot = process.env.OPENPENCIL_MCP_ROOT?.trim() || process.cwd()const wsUrl = `ws://${wsHost}:${wsPort}`-let ws: WebSocket | null = null-let registered = false--const pending = new Map<- string,- {- resolve: (v: unknown) => void- reject: (e: Error) => void- timer: ReturnType<typeof setTimeout>- }->()--function connect() {- ws = new WebSocket(wsUrl)-- ws.on('open', () => {+const bridge = createStdioRpcBridge({+ wsUrl,+ onOpen: () => {process.stderr.write(`Connected to OpenPencil app at ${wsUrl}\n`)- })-- ws.on('message', (raw) => {- try {- let text: string- if (Buffer.isBuffer(raw)) text = raw.toString('utf8')- else if (Array.isArray(raw)) text = Buffer.concat(raw).toString('utf8')- else text = Buffer.from(raw).toString('utf8')- const msg = JSON.parse(text) as {- type: string- id?: string- token?: string- result?: unknown- error?: string- ok?: boolean- }- if (msg.type === 'register' && msg.token) {- registered = true- return- }- if (msg.type === 'response' && msg.id) {- const req = pending.get(msg.id)- if (!req) return- pending.delete(msg.id)- clearTimeout(req.timer)- if (msg.ok === false) req.reject(new Error(msg.error ?? 'RPC failed'))- else {- const { type: _, id: __, ...payload } = msg- req.resolve(payload)- }- }- } catch {- process.stderr.write('Malformed WS message\n')- }- })-- ws.on('close', () => {- registered = false- for (const [id, req] of pending) {- clearTimeout(req.timer)- req.reject(new Error('WebSocket closed'))- pending.delete(id)- }- setTimeout(connect, 2000)- })-- ws.on('error', () => {- ws?.close()- })-}--function sendRpc(body: Record<string, unknown>): Promise<unknown> {- return new Promise((resolve, reject) => {- if (!ws || ws.readyState !== WebSocket.OPEN || !registered) {- reject(- new Error(- 'OpenPencil app is not connected. ' +- 'STOP and tell the user: "The OpenPencil desktop app is not running or no document is open. ' +- 'Please start the app and open a document, then try again." ' +- 'Do NOT attempt to start the app yourself or retry automatically.'- )- )- return- }- const id = crypto.randomUUID()- const timer = setTimeout(() => {- pending.delete(id)- reject(new Error('RPC timeout (30s)'))- }, 30_000)- pending.set(id, { resolve, reject, timer })- ws.send(JSON.stringify({ type: 'request', id, ...body }))- })-}+ },+ onMalformedMessage: () => {+ process.stderr.write('Malformed WS message\n')+ },+})-connect()+bridge.connect()const mcpServer = new McpServer({ name: 'open-pencil', version: MCP_VERSION })-registerTools(mcpServer, { enableEval, mcpRoot, sendRpc })+registerTools(mcpServer, { enableEval, mcpRoot, sendRpc: bridge.sendRpc })const transport = new StdioServerTransport()void mcpServer.connect(transport)diff --git a/packages/mcp/src/tool/output.ts b/packages/mcp/src/tool/output.tsnew file mode 100644index 000000000..3199a3743--- /dev/null+++ b/packages/mcp/src/tool/output.ts@@ -0,0 +1,38 @@+import { mkdir, writeFile } from 'node:fs/promises'+import { dirname, resolve, sep as osSep } from 'node:path'++import { ok } from '#mcp/result'++import type { MCPResult } from '#mcp/result'++export function resolveSafePath(filePath: string, root: string): string {+ const resolved = resolve(filePath)+ const sep = root.endsWith('/') || root.endsWith('\\') ? '' : osSep+ if (!resolved.startsWith(root + sep) && resolved !== root) {+ throw new Error(`Path is outside the allowed root: ${root}`)+ }+ return resolved+}++export async function writeToolOutput(+ toolName: string,+ result: Record<string, unknown>,+ filePath: string,+ root: string,+): Promise<MCPResult | null> {+ const resolved = resolveSafePath(filePath, root)+ await mkdir(dirname(resolved), { recursive: true })+ if (toolName === 'export_svg' && typeof result.svg === 'string') {+ await writeFile(resolved, result.svg, 'utf8')+ return ok({ written: resolved, byteLength: Buffer.byteLength(result.svg, 'utf8') })+ }+ if (toolName === 'export_image' && typeof result.base64 === 'string') {+ await writeFile(resolved, Buffer.from(result.base64, 'base64'))+ return ok({ written: resolved, byteLength: result.byteLength ?? null })+ }+ if (toolName === 'get_jsx' && typeof result.jsx === 'string') {+ await writeFile(resolved, result.jsx, 'utf8')+ return ok({ written: resolved, byteLength: Buffer.byteLength(result.jsx, 'utf8') })+ }+ return null+}diff --git a/packages/mcp/src/tool/registration.ts b/packages/mcp/src/tool/registration.tsnew file mode 100644index 000000000..196ff752f--- /dev/null+++ b/packages/mcp/src/tool/registration.ts@@ -0,0 +1,136 @@+import { resolve } from 'node:path'++import { z } from 'zod'++import { ALL_TOOLS, CODEGEN_PROMPT } from '@open-pencil/core/tools'++import { fail, ok } from '#mcp/result'+import { resolveSafePath, writeToolOutput } from './output'+import { paramToZod } from './schema'++import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'++export type RpcSender = (body: Record<string, unknown>) => Promise<unknown>++export interface RegisterToolsOptions {+ enableEval: boolean+ mcpRoot?: string | null+ sendRpc: RpcSender+}++export function registerTools(mcpServer: McpServer, options: RegisterToolsOptions) {+ const { enableEval, sendRpc } = options+ const resolvedRoot = options.mcpRoot ? resolve(options.mcpRoot) : null+ const register = mcpServer.registerTool.bind(mcpServer) as (...a: unknown[]) => void++ for (const def of ALL_TOOLS) {+ if (!enableEval && def.name === 'eval') continue+ const shape: Record<string, z.ZodType> = {}+ for (const [key, param] of Object.entries(def.params)) {+ shape[key] = paramToZod(param)+ }+ register(+ def.name,+ { description: def.description, inputSchema: z.object(shape) },+ async (args: Record<string, unknown>) => {+ try {+ const result = await sendRpc({ command: 'tool', args: { name: def.name, args } })+ const res = result as { ok?: boolean; result?: unknown; error?: string }+ if (res.ok === false) return fail(new Error(res.error))+ const r = res.result as Record<string, unknown> | undefined+ const filePath = typeof args.path === 'string' ? args.path : null+ if (r && filePath && resolvedRoot) {+ const written = await writeToolOutput(def.name, r, filePath, resolvedRoot)+ if (written) return written+ }+ if (r && 'base64' in r && 'mimeType' in r) {+ return {+ content: [+ {+ type: 'image' as const,+ data: r.base64 as string,+ mimeType: r.mimeType as string,+ },+ ],+ }+ }+ return ok(r)+ } catch (e) {+ return fail(e)+ }+ },+ )+ }++ register(+ 'save_file',+ {+ description:+ 'Save the current document to disk. Uses the existing file path if available, otherwise prompts for a location.',+ inputSchema: z.object({}),+ },+ async () => {+ try {+ const result = await sendRpc({ command: 'save_file' })+ const res = result as { ok?: boolean; error?: string }+ if (res.ok === false) return fail(new Error(res.error))+ return ok({ saved: true })+ } catch (e) {+ return fail(e)+ }+ },+ )++ if (resolvedRoot) {+ register(+ 'open_file',+ {+ description: `Open a .fig or .pen file from disk into a new tab. Path must be inside ${resolvedRoot}.`,+ inputSchema: z.object({+ path: z.string().describe('Absolute path to the design file'),+ }),+ },+ async (args: { path: string }) => {+ try {+ const safe = resolveSafePath(args.path, resolvedRoot)+ const result = await sendRpc({ command: 'open_file', args: { path: safe } })+ const res = result as { ok?: boolean; error?: string }+ if (res.ok === false) return fail(new Error(res.error))+ return ok({ opened: true })+ } catch (e) {+ return fail(e)+ }+ },+ )++ register(+ 'new_document',+ {+ description: `Create a new empty document. Optionally set a save path inside ${resolvedRoot}.`,+ inputSchema: z.object({+ path: z.string().describe('Optional absolute path for the new file').optional(),+ }),+ },+ async (args: { path?: string }) => {+ try {+ const safePath = args.path ? resolveSafePath(args.path, resolvedRoot) : undefined+ const result = await sendRpc({ command: 'new_document', args: { path: safePath } })+ const res = result as { ok?: boolean; error?: string }+ if (res.ok === false) return fail(new Error(res.error))+ return ok({ created: true })+ } catch (e) {+ return fail(e)+ }+ },+ )+ }++ register(+ 'get_codegen_prompt',+ {+ description: 'Get design-to-code generation guidelines. Call before generating frontend code.',+ inputSchema: z.object({}),+ },+ async () => ok({ prompt: CODEGEN_PROMPT }),+ )+}diff --git a/packages/mcp/src/tool/schema.ts b/packages/mcp/src/tool/schema.tsnew file mode 100644index 000000000..796fc6559--- /dev/null+++ b/packages/mcp/src/tool/schema.ts@@ -0,0 +1,24 @@+import { z } from 'zod'++import type { ParamDef, ParamType } from '@open-pencil/core/tools'++export function paramToZod(param: ParamDef): z.ZodType {+ const typeMap: Record<ParamType, () => z.ZodType> = {+ string: () =>+ param.enum+ ? z.enum(param.enum as [string, ...string[]]).describe(param.description)+ : z.string().describe(param.description),+ number: () => {+ let schema = z.coerce.number()+ if (param.min !== undefined) schema = schema.min(param.min)+ if (param.max !== undefined) schema = schema.max(param.max)+ return schema.describe(param.description)+ },+ boolean: () => z.boolean().describe(param.description),+ color: () => z.string().describe(param.description),+ 'string[]': () => z.array(z.string()).min(1).describe(param.description),+ }++ const schema = typeMap[param.type]()+ return param.required ? schema : schema.optional()+}diff --git a/packages/mcp/tsconfig.json b/packages/mcp/tsconfig.jsonindex d349b91c2..554efaa5d 100644--- a/packages/mcp/tsconfig.json+++ b/packages/mcp/tsconfig.json@@ -5,6 +5,9 @@"moduleResolution": "bundler","strict": true,"skipLibCheck": true,+ "paths": {+ "#mcp/*": ["./src/*"]+ },"noCheck": true,"outDir": "dist","rootDir": "src"diff --git a/packages/vue/package.json b/packages/vue/package.jsonindex 6bc647f47..459ce87e3 100644--- a/packages/vue/package.json+++ b/packages/vue/package.json@@ -3,6 +3,13 @@"version": "0.11.8","license": "MIT","type": "module",+ "imports": {+ "#vue/*": {+ "types": "./src/*",+ "bun": "./src/*",+ "default": "./dist/*"+ }+ },"exports": {".": {"types": "./dist/index.d.ts",@@ -40,6 +47,7 @@"dependencies": {"@nanostores/i18n": "^1.2.2","@nanostores/vue": "^1.1.0",+ "@use-gesture/vanilla": "^10.3.1","@vueuse/core": "^14.2.1","nanostores": "^1.2.0"},diff --git a/packages/vue/src/AppearanceControls/index.ts b/packages/vue/src/AppearanceControls/index.tsdeleted file mode 100644index 0a795c6ab..000000000--- a/packages/vue/src/AppearanceControls/index.ts+++ /dev/null@@ -1 +0,0 @@-export { default as AppearanceControlsRoot } from './AppearanceControlsRoot.vue'diff --git a/packages/vue/src/Canvas/index.ts b/packages/vue/src/Canvas/index.tsdeleted file mode 100644index 778981191..000000000--- a/packages/vue/src/Canvas/index.ts+++ /dev/null@@ -1,4 +0,0 @@-export { default as CanvasRoot } from './CanvasRoot.vue'-export { default as CanvasSurface } from './CanvasSurface.vue'-export { useCanvasContext } from './context'-export type { CanvasContext } from './context'diff --git a/packages/vue/src/Canvas/useCanvasInput.ts b/packages/vue/src/Canvas/useCanvasInput.tsdeleted file mode 100644index e5f61553c..000000000--- a/packages/vue/src/Canvas/useCanvasInput.ts+++ /dev/null@@ -1,821 +0,0 @@-import { useEventListener } from '@vueuse/core'-import { ref, type Ref } from 'vue'--import {- PEN_CLOSE_THRESHOLD,- ROTATION_SNAP_DEGREES,- DEFAULT_TEXT_WIDTH,- DEFAULT_TEXT_HEIGHT,- degToRad-} from '@open-pencil/core'-import { getAbsolutePositionFull } from '@open-pencil/core/canvas'-import { handleDrawMove, handleDrawUp } from '@open-pencil/vue/shared/input/draw'-import { hitTestCornerRotationByMatrix } from '@open-pencil/vue/shared/input/geometry'-import { handleMoveMove, handleMoveUp } from '@open-pencil/vue/shared/input/move'-import { setupPanZoom } from '@open-pencil/vue/shared/input/pan-zoom'-import { applyResize } from '@open-pencil/vue/shared/input/resize'-import {- handlePenNodeEditDown,- handleNodeEditMove,- handleSelectDown,- updateHoverCursor,- hitTestEditHandle,- isEndpoint,- NODE_HIT_THRESHOLD,- type HitTestFns-} from '@open-pencil/vue/shared/input/select'-import { TOOL_TO_NODE } from '@open-pencil/vue/shared/input/types'--import type { SceneNode, Vector, VectorSegment } from '@open-pencil/core'-import type { Editor } from '@open-pencil/core/editor'-import type {- DragMarquee,- DragPan,- DragRotate,- DragState-} from '@open-pencil/vue/shared/input/types'--type NodeEditState = {- segments: VectorSegment[]- vertices: Vector[]- hoveredHandleInfo: {- segmentIndex: number- tangentField: 'tangentStart' | 'tangentEnd'- } | null-}--type NodeEditMethods = Partial<{- nodeEditBendHandle: (- vertexIndex: number,- dx: number,- dy: number,- independent: boolean,- targetSegmentIndex: number | null,- targetTangentField: 'tangentStart' | 'tangentEnd' | null- ) => void- nodeEditZeroVertexHandles: (vertexIndex: number) => void- nodeEditConnectEndpoints: (a: number, b: number) => void- enterNodeEditMode: (nodeId: string) => void-}>--/**- * Wires pointer and mouse interaction to an OpenPencil canvas.- *- * This composable coordinates selection, dragging, resizing, rotation,- * panning, drawing tools, scoped hit testing, and text-edit interaction.- * It is primarily intended for editor shell components that own the canvas.- */-export function useCanvasInput(- canvasRef: Ref<HTMLCanvasElement | null>,- editor: Editor,- hitTestSectionTitle: (cx: number, cy: number) => SceneNode | null,- hitTestComponentLabel: (cx: number, cy: number) => SceneNode | null,- hitTestFrameTitle: (cx: number, cy: number) => SceneNode | null,- onCursorMove?: (cx: number, cy: number) => void-) {- const drag = ref<DragState | null>(null)- const cursorOverride = ref<string | null>(null)- const spaceHeld = ref(false)- useEventListener(window, 'keydown', (e: KeyboardEvent) => {- if (e.code === 'Space') spaceHeld.value = true- })- useEventListener(window, 'keyup', (e: KeyboardEvent) => {- if (e.code === 'Space') spaceHeld.value = false- })- let lastClickTime = 0- let lastClickX = 0- let lastClickY = 0- let clickCount = 0- const MULTI_CLICK_DELAY = 500- const MULTI_CLICK_RADIUS = 5-- function getCoords(e: MouseEvent) {- const canvas = canvasRef.value- if (!canvas) return { sx: 0, sy: 0, cx: 0, cy: 0 }- const rect = canvas.getBoundingClientRect()- const sx = e.clientX - rect.left- const sy = e.clientY - rect.top- const { x: cx, y: cy } = editor.screenToCanvas(sx, sy)- return { sx, sy, cx, cy }- }-- function canvasToLocal(cx: number, cy: number, scopeId: string): { lx: number; ly: number } {- const node = editor.graph.getNode(scopeId)- if (!node) return { lx: cx, ly: cy }- const abs = editor.graph.getAbsolutePosition(scopeId)- let dx = cx - abs.x- let dy = cy - abs.y- if (node.rotation !== 0) {- const hw = node.width / 2- const hh = node.height / 2- const rad = degToRad(-node.rotation)- const cos = Math.cos(rad)- const sin = Math.sin(rad)- const rx = dx - hw- const ry = dy - hh- dx = rx * cos - ry * sin + hw- dy = rx * sin + ry * cos + hh- }- return { lx: dx, ly: dy }- }-- function hitTestInScope(cx: number, cy: number, deep: boolean): SceneNode | null {- const scopeId = editor.state.enteredContainerId-- const renderer = editor.renderer- if (!renderer) return null- if (scopeId) {- if (!editor.graph.getNode(scopeId)) {- editor.state.enteredContainerId = null- } else {- const { lx, ly } = canvasToLocal(cx, cy, scopeId)- return deep- ? editor.graph.hitTestDeep(lx, ly, scopeId)- : editor.graph.hitTest(lx, ly, scopeId)- }- }- return deep- ? editor.graph.hitTestDeep(cx, cy, editor.state.currentPageId)- : editor.graph.hitTest(cx, cy, editor.state.currentPageId)- }-- function isInsideContainerBounds(cx: number, cy: number, containerId: string): boolean {- const container = editor.graph.getNode(containerId)- if (!container) return false- const { lx, ly } = canvasToLocal(cx, cy, containerId)- return lx >= 0 && lx <= container.width && ly >= 0 && ly <= container.height- }-- const hitFns: HitTestFns = {- hitTestInScope,- isInsideContainerBounds,- hitTestSectionTitle,- hitTestComponentLabel,- hitTestFrameTitle- }-- function setDrag(d: DragState) {- drag.value = d- }-- function startPanDrag(e: MouseEvent) {- drag.value = {- type: 'pan',- startScreenX: e.clientX,- startScreenY: e.clientY,- startPanX: editor.state.panX,- startPanY: editor.state.panY- }- }-- function handleTextEditClick(cx: number, cy: number, shiftKey: boolean): boolean {- const textEd = editor.textEditor- const editNode = editor.state.editingTextId- ? editor.graph.getNode(editor.state.editingTextId)- : null- if (!textEd || !editNode) {- editor.commitTextEdit()- return false- }- const abs = editor.graph.getAbsolutePosition(editNode.id)- const localX = cx - abs.x- const localY = cy - abs.y- if (localX < 0 || localY < 0 || localX > editNode.width || localY > editNode.height) {- editor.commitTextEdit()- return false- }- if (clickCount >= 3) {- textEd.selectAll()- } else if (clickCount === 2) {- textEd.selectWordAt(localX, localY)- } else {- textEd.setCursorAt(localX, localY, shiftKey)- drag.value = { type: 'text-select', startX: cx, startY: cy } as DragState- }- editor.requestRender()- return true- }-- function tryStartRotation(cx: number, cy: number): boolean {- if (editor.state.selectedIds.size !== 1) return false- const id = [...editor.state.selectedIds][0]- const node = editor.graph.getNode(id)- if (!node || node.locked) return false-- if (editor.state.selectedIds.size > 1) {- return false- }- const abs = getAbsolutePositionFull(node, editor.graph)-- if (!hitTestCornerRotationByMatrix(cx, cy, node, editor.graph, editor.renderer?.zoom ?? 1)) {- return false- }- const startAngle = Math.atan2(cy - abs.centerY, cx - abs.centerX) * (180 / Math.PI)- drag.value = {- type: 'rotate',- nodeId: id,- centerX: abs.centerX,- centerY: abs.centerY,- startAngle: startAngle,- origRotation: node.rotation- }- return true- }-- function handlePanMove(d: DragPan, e: MouseEvent) {- const dx = e.clientX - d.startScreenX- const dy = e.clientY - d.startScreenY- editor.state.panX = d.startPanX + dx- editor.state.panY = d.startPanY + dy- editor.requestRepaint()- }-- function handleRotateMove(d: DragRotate, sx: number, sy: number, shiftKey: boolean) {- const currentAngle = Math.atan2(sy - d.centerY, sx - d.centerX) * (180 / Math.PI)-- let delta = currentAngle - d.startAngle-- delta = ((((delta + 180) % 360) + 360) % 360) - 180- let rotation = d.origRotation + delta-- if (shiftKey) {- rotation = Math.round(rotation / ROTATION_SNAP_DEGREES) * ROTATION_SNAP_DEGREES- }-- rotation = ((((rotation + 180) % 360) + 360) % 360) - 180- editor.setRotationPreview({ nodeId: d.nodeId, angle: rotation })- }-- function handleTextSelectMove(cx: number, cy: number) {- const textEd = editor.textEditor- const editNode = editor.state.editingTextId- ? editor.graph.getNode(editor.state.editingTextId)- : null- if (textEd && editNode) {- const abs = editor.graph.getAbsolutePosition(editNode.id)- textEd.setCursorAt(cx - abs.x, cy - abs.y, true)- editor.requestRender()- }- }-- function handleMarqueeMove(d: DragMarquee, cx: number, cy: number) {- const minX = Math.min(d.startX, cx)- const minY = Math.min(d.startY, cy)- const maxX = Math.max(d.startX, cx)- const maxY = Math.max(d.startY, cy)-- const scopeId = editor.state.enteredContainerId- const parentId = scopeId ?? editor.state.currentPageId- const localMin = scopeId ? canvasToLocal(minX, minY, scopeId) : { lx: minX, ly: minY }- const localMax = scopeId ? canvasToLocal(maxX, maxY, scopeId) : { lx: maxX, ly: maxY }- const localMinX = Math.min(localMin.lx, localMax.lx)- const localMinY = Math.min(localMin.ly, localMax.ly)- const localMaxX = Math.max(localMin.lx, localMax.lx)- const localMaxY = Math.max(localMin.ly, localMax.ly)-- const hits: string[] = []- for (const node of editor.graph.getChildren(parentId)) {- if (!node.visible || node.locked) continue- if (- node.x + node.width > localMinX &&- node.x < localMaxX &&- node.y + node.height > localMinY &&- node.y < localMaxY- ) {- hits.push(node.id)- }- }- editor.select(hits)- editor.setMarquee({ x: minX, y: minY, width: maxX - minX, height: maxY - minY })- }-- function resolveBendTargetHandle(- es: NodeEditState | null | undefined,- vertexIndex: number,- samples: Vector[]- ): { segmentIndex: number; tangentField: 'tangentStart' | 'tangentEnd' } | null {- if (!es || samples.length === 0) return null- const vx = es.vertices[vertexIndex]?.x- const vy = es.vertices[vertexIndex]?.y- if (vx == null || vy == null) return null-- const sampleVector = samples.reduce(- (acc, p) => ({ x: acc.x + (p.x - vx), y: acc.y + (p.y - vy) }),- { x: 0, y: 0 }- )- const sampleLen = Math.hypot(sampleVector.x, sampleVector.y)- if (sampleLen < 1e-6) return null- const sampleDir = { x: sampleVector.x / sampleLen, y: sampleVector.y / sampleLen }-- let best: { segmentIndex: number; tangentField: 'tangentStart' | 'tangentEnd' } | null = null- let bestDot = -Infinity- for (let i = 0; i < es.segments.length; i++) {- const seg = es.segments[i]- let tangentField: 'tangentStart' | 'tangentEnd'- let neighborIndex: number- let tangent: Vector- if (seg.start === vertexIndex) {- tangentField = 'tangentStart'- neighborIndex = seg.end- tangent = seg.tangentStart- } else if (seg.end === vertexIndex) {- tangentField = 'tangentEnd'- neighborIndex = seg.start- tangent = seg.tangentEnd- } else {- continue- }-- const neighbor = es.vertices[neighborIndex]- if (!neighbor) continue-- const tangentLen = Math.hypot(tangent.x, tangent.y)- const base =- tangentLen > 1e-6- ? tangent- : {- x: neighbor.x - vx,- y: neighbor.y - vy- }- const baseLen = Math.hypot(base.x, base.y)- if (baseLen < 1e-6) continue- const dir = { x: base.x / baseLen, y: base.y / baseLen }- const dot = dir.x * sampleDir.x + dir.y * sampleDir.y- if (dot > bestDot) {- bestDot = dot- best = { segmentIndex: i, tangentField }- }- }- return best- }-- function onMouseDown(e: MouseEvent) {- if (!editor.state.editingTextId) canvasRef.value?.focus()- editor.setHoveredNode(null)- const { sx, sy, cx, cy } = getCoords(e)-- const now = performance.now()- if (- now - lastClickTime < MULTI_CLICK_DELAY &&- Math.abs(sx - lastClickX) < MULTI_CLICK_RADIUS &&- Math.abs(sy - lastClickY) < MULTI_CLICK_RADIUS- ) {- clickCount++- } else {- clickCount = 1- }- lastClickTime = now- lastClickX = sx- lastClickY = sy- const tool = editor.state.activeTool-- if (e.button === 1 || tool === 'HAND') {- startPanDrag(e)- return- }-- if (tool === 'SELECT') {- handleSelectDown(e, cx, cy, editor, hitFns, tryStartRotation, handleTextEditClick, setDrag)- return- }-- if (tool === 'PEN') {- // Hide draft segment during drag- editor.state.penCursorX = null- editor.state.penCursorY = null-- // In node edit mode with pen tool: click curve to add point, click vertex to remove- const nodeEditState = (- editor.state as Editor['state'] & { nodeEditState?: NodeEditState | null }- ).nodeEditState- if (nodeEditState) {- handlePenNodeEditDown(e, cx, cy, editor)- return- }-- const penState = editor.state.penState- if (penState && penState.vertices.length > 2) {- const first = penState.vertices[0]- const dist = Math.hypot(cx - first.x, cy - first.y)- if (dist < PEN_CLOSE_THRESHOLD) {- editor.penSetPendingClose(true)- editor.penSetClosingToFirst(true)- drag.value = {- type: 'pen-drag',- startX: first.x,- startY: first.y,- modifierMode: 'default',- frozenOppositeTangent: null,- spaceDown: false,- spaceStartX: 0,- spaceStartY: 0,- knotStartX: first.x,- knotStartY: first.y- } as DragState- cursorOverride.value = 'crosshair'- return- }- }-- editor.penSetPendingClose(false)- editor.penAddVertex(cx, cy)- drag.value = {- type: 'pen-drag',- startX: cx,- startY: cy,- modifierMode: 'default',- frozenOppositeTangent: null,- spaceDown: false,- spaceStartX: 0,- spaceStartY: 0,- knotStartX: cx,- knotStartY: cy- } as DragState- cursorOverride.value = 'crosshair'- return- }-- if (tool === 'TEXT') {- const nodeId = editor.createShape('TEXT', cx, cy, DEFAULT_TEXT_WIDTH, DEFAULT_TEXT_HEIGHT)- editor.graph.updateNode(nodeId, { text: '' })- editor.select([nodeId])- editor.startTextEditing(nodeId)- editor.setTool('SELECT')- editor.requestRender()- return- }-- const nodeType = TOOL_TO_NODE[tool]- if (!nodeType) return-- editor.undo.beginBatch('Create shape')- const nodeId = editor.createShape(nodeType, cx, cy, 0, 0)- editor.select([nodeId])-- drag.value = { type: 'draw', startX: cx, startY: cy, nodeId }- }-- function onMouseMove(e: MouseEvent) {- const nodeEditEditor = editor as Editor & NodeEditMethods- if (onCursorMove) {- const { cx, cy } = getCoords(e)- onCursorMove(cx, cy)- }-- if (editor.state.activeTool === 'PEN' && editor.state.penState && !drag.value) {- const { cx, cy } = getCoords(e)- editor.state.penCursorX = cx- editor.state.penCursorY = cy-- if (!drag.value) {- const first = editor.state.penState.vertices[0]- if (editor.state.penState.vertices.length > 2) {- const dist = Math.hypot(cx - first.x, cy - first.y)- editor.penSetClosingToFirst(dist < PEN_CLOSE_THRESHOLD)- }- }- editor.requestRepaint()- }-- // Track hovered handle in node edit mode- const nodeEditState = (- editor.state as Editor['state'] & { nodeEditState?: NodeEditState | null }- ).nodeEditState- if (!drag.value && nodeEditState) {- const { cx, cy } = getCoords(e)- const hit = hitTestEditHandle(editor, cx, cy)- const es = nodeEditState- const prev = es.hoveredHandleInfo- if (hit) {- if (- !prev ||- prev.segmentIndex !== hit.segmentIndex ||- prev.tangentField !== hit.tangentField- ) {- es.hoveredHandleInfo = { segmentIndex: hit.segmentIndex, tangentField: hit.tangentField }- editor.requestRepaint()- }- } else if (prev) {- es.hoveredHandleInfo = null- editor.requestRepaint()- }- }-- if (!drag.value && editor.state.activeTool === 'SELECT') {- const { cx, cy } = getCoords(e)- cursorOverride.value = updateHoverCursor(cx, cy, editor, hitFns)- }-- if (!drag.value) return- const d = drag.value-- if (d.type === 'pan') {- handlePanMove(d, e)- return- }-- const { cx, cy } = getCoords(e)-- if (d.type === 'rotate') {- handleRotateMove(d, cx, cy, e.shiftKey)- return- }- if (d.type === 'move') {- handleMoveMove(d, cx, cy, editor)- return- }- if (d.type === 'text-select') {- handleTextSelectMove(cx, cy)- return- }- if (d.type === 'resize') {- applyResize(d, cx, cy, e.shiftKey, editor)- return- }-- if (d.type === 'pen-drag') {- const isSpace = spaceHeld.value- const penState = editor.state.penState-- if (!penState) return- const isClosing = !!penState.pendingClose && penState.vertices.length > 2- const anchorIndex = isClosing ? 0 : penState.vertices.length - 1- const anchor = penState.vertices[anchorIndex]-- if (isSpace) {- if (!d.spaceDown) {- d.spaceDown = true- d.spaceStartX = cx- d.spaceStartY = cy- d.knotStartX = anchor.x- d.knotStartY = anchor.y- }-- const dx = cx - d.spaceStartX- const dy = cy - d.spaceStartY- editor.penSetKnotPosition?.(d.knotStartX + dx, d.knotStartY + dy)- } else {- if (d.spaceDown) {- d.spaceDown = false- // Adjust startX/startY so the tangent pull is relative to the new knot position- const dx = anchor.x - d.knotStartX- const dy = anchor.y - d.knotStartY- d.startX += dx- d.startY += dy- }-- const tx = cx - d.startX- const ty = cy - d.startY- if (Math.hypot(tx, ty) > 2) {- const firstSeg = penState.segments[0]- const closingOpposite =- penState.pendingClose && firstSeg- ? firstSeg.start === 0- ? firstSeg.tangentStart- : firstSeg.end === 0- ? firstSeg.tangentEnd- : null- : null- const mode = e.metaKey || e.ctrlKey ? 'continuous' : e.altKey ? 'independent' : 'default'- if (mode !== d.modifierMode) {- if (mode === 'default') {- d.frozenOppositeTangent = null- } else if (!d.frozenOppositeTangent) {- const lastSeg = penState.segments[penState.segments.length - 1]- d.frozenOppositeTangent = lastSeg- ? closingOpposite- ? { ...closingOpposite }- : { ...lastSeg.tangentEnd }- : penState.dragTangent- ? { x: -penState.dragTangent.x, y: -penState.dragTangent.y }- : { x: 0, y: 0 }- }- d.modifierMode = mode- }-- if (mode === 'continuous') {- editor.penSetDragTangent(tx, ty, {- keepOpposite: true,- constrainToOpposite: true,- oppositeTangent: d.frozenOppositeTangent- })- } else if (mode === 'independent') {- editor.penSetDragTangent(tx, ty, {- keepOpposite: true,- oppositeTangent: d.frozenOppositeTangent- })- } else {- editor.penSetDragTangent(- tx,- ty,- penState.pendingClose- ? {- keepOpposite: true,- oppositeTangent: closingOpposite- }- : undefined- )- }- }- }- return- }-- if (d.type === 'edit-node' || d.type === 'edit-handle') {- handleNodeEditMove(d, cx, cy, editor, e.altKey, e.metaKey || e.ctrlKey, e.shiftKey)- return- }-- if (d.type === 'bend-handle') {- const dx = cx - d.startX- const dy = cy - d.startY- if (Math.hypot(dx, dy) < 2) return- // Lock mode on first meaningful move — persists for the rest of the drag- if (d.lockedMode === null) {- d.lockedMode = e.altKey ? 'independent' : 'symmetric'- }- if (d.dragSamples.length < 3) {- d.dragSamples.push({ x: cx, y: cy })- }- if (d.targetSegmentIndex === null && d.dragSamples.length >= 3) {- const target = resolveBendTargetHandle(nodeEditState, d.vertexIndex, d.dragSamples)- if (target) {- d.targetSegmentIndex = target.segmentIndex- d.targetTangentField = target.tangentField- }- }- if (d.targetSegmentIndex === null || d.targetTangentField === null) {- return- }- nodeEditEditor.nodeEditBendHandle?.(- d.vertexIndex,- dx,- dy,- d.lockedMode === 'independent',- d.targetSegmentIndex,- d.targetTangentField- )- return- }-- if (d.type === 'draw') {- handleDrawMove(d, cx, cy, e.shiftKey, editor)- return- }-- handleMarqueeMove(d, cx, cy)- }-- function onMouseUp() {- const nodeEditEditor = editor as Editor & NodeEditMethods- if (!drag.value) return- const d = drag.value-- if (d.type === 'bend-handle') {- // If no drag happened (lockedMode never set), zero all handles on this vertex- if (d.lockedMode === null) {- nodeEditEditor.nodeEditZeroVertexHandles?.(d.vertexIndex)- }- drag.value = null- return- }- if (d.type === 'edit-node') {- // Check if a single endpoint was dragged onto another endpoint → connect- const es = (editor.state as Editor['state'] & { nodeEditState?: NodeEditState | null })- .nodeEditState- if (es && d.origPositions.size === 1) {- const [draggedIdx] = d.origPositions.keys()- if (isEndpoint(draggedIdx, es.segments)) {- const v = es.vertices[draggedIdx]- const iz = 1 / editor.state.zoom- for (let i = 0; i < es.vertices.length; i++) {- if (i === draggedIdx) continue- if (!isEndpoint(i, es.segments)) continue- const t = es.vertices[i]- if (Math.hypot(v.x - t.x, v.y - t.y) < NODE_HIT_THRESHOLD * iz) {- nodeEditEditor.nodeEditConnectEndpoints?.(draggedIdx, i)- drag.value = null- return- }- }- }- }- drag.value = null- return- }- if (d.type === 'edit-handle') {- drag.value = null- return- }- if (d.type === 'move') handleMoveUp(d, editor)- else if (d.type === 'text-select') {- drag.value = null- return- } else if (d.type === 'resize') editor.commitResize(d.nodeId, d.origRect)- else if (d.type === 'pen-drag') {- const penState = editor.state.penState as- | (typeof editor.state.penState & {- pendingClose?: boolean- })- | null- if (penState?.pendingClose) {- editor.penCommit(true)- }- drag.value = null- return- } else if (d.type === 'rotate') {- const preview = editor.state.rotationPreview- if (preview) {- editor.updateNode(d.nodeId, { rotation: preview.angle })- editor.commitRotation(d.nodeId, d.origRotation)- }- editor.setRotationPreview(null)- } else if (d.type === 'draw') handleDrawUp(d, editor)- else if (d.type === 'marquee') editor.setMarquee(null)-- drag.value = null- cursorOverride.value = null- }-- function startTextEditingAt(hit: SceneNode, cx: number, cy: number) {- editor.select([hit.id])- editor.startTextEditing(hit.id)- const textEd = editor.textEditor- if (textEd) {- const abs = editor.graph.getAbsolutePosition(hit.id)- textEd.selectWordAt(cx - abs.x, cy - abs.y)- editor.requestRender()- }- }-- function getContainerDescendantHit(containerId: string, cx: number, cy: number): SceneNode | null {- const hit = editor.graph.hitTestDeep(cx, cy, editor.state.currentPageId)- if (!hit) return null- if (hit.id === containerId || editor.graph.isDescendant(hit.id, containerId)) return hit- return null- }-- function onDblClick(e: MouseEvent) {- const nodeEditEditor = editor as Editor & NodeEditMethods- if (editor.state.editingTextId) return-- const { cx, cy } = getCoords(e)-- const selectedId =- editor.state.selectedIds.size === 1 ? [...editor.state.selectedIds][0] : undefined- const selectedNode = selectedId ? editor.graph.getNode(selectedId) : undefined- const canEnter =- selectedNode && selectedId && editor.graph.isContainer(selectedId) && !selectedNode.locked-- if (canEnter) {- const useDeep = selectedNode.type === 'COMPONENT' || selectedNode.type === 'INSTANCE'- const hit = useDeep- ? getContainerDescendantHit(selectedId, cx, cy)- : hitTestInScope(cx, cy, false)- editor.enterContainer(selectedId)- if (hit?.type === 'TEXT') {- startTextEditingAt(hit, cx, cy)- } else if (hit) {- editor.select([hit.id])- } else {- editor.clearSelection()- }- return- }-- const hit =- hitTestSectionTitle(cx, cy) ?? hitTestComponentLabel(cx, cy) ?? hitTestInScope(cx, cy, true)- if (!hit) return-- if (hit.type === 'TEXT') {- startTextEditingAt(hit, cx, cy)- return- }-- if (hit.type === 'VECTOR') {- nodeEditEditor.enterNodeEditMode?.(hit.id)- return- }-- editor.select([hit.id])- }-- useEventListener(canvasRef, 'dblclick', onDblClick)- useEventListener(canvasRef, 'mousedown', onMouseDown)- useEventListener(canvasRef, 'mousemove', onMouseMove)- useEventListener(canvasRef, 'mouseup', onMouseUp)- useEventListener(canvasRef, 'mouseleave', () => {- if (!drag.value) {- editor.setHoveredNode(null)- }- })- useEventListener(window, 'mouseup', () => {- if (drag.value) onMouseUp()- })-- setupPanZoom(canvasRef, editor, drag, onMouseDown, onMouseMove, onMouseUp)- return {- drag,- cursorOverride- }-}diff --git a/packages/vue/src/Canvas/useTextEdit.ts b/packages/vue/src/Canvas/useTextEdit.tsdeleted file mode 100644index 0d487d7e6..000000000--- a/packages/vue/src/Canvas/useTextEdit.ts+++ /dev/null@@ -1,347 +0,0 @@-import { useEventListener } from '@vueuse/core'-import { shallowRef, watch, type Ref } from 'vue'--import {- adjustRunsForDelete,- adjustRunsForInsert,- toggleBoldInRange,- toggleDecorationInRange,- toggleItalicInRange-} from '@open-pencil/core'--import type { SceneNode } from '@open-pencil/core'-import type { Editor } from '@open-pencil/core/editor'--const CARET_BLINK_MS = 530--/**- * Bridges DOM text input and the editor's canvas text-editing model.- *- * This composable manages textarea-backed input, IME composition, caret- * blinking, keyboard editing behavior, text formatting shortcuts, and syncing- * text/style-run updates back into the scene graph.- */-export function useTextEdit(canvasRef: Ref<HTMLCanvasElement | null>, store: Editor) {- const textareaRef = shallowRef<HTMLTextAreaElement | null>(null)- let isComposing = false- let blinkTimer = 0-- function getEditingNode() {- const id = store.state.editingTextId- if (!id) return null- return store.graph.getNode(id) ?? null- }-- function resetBlink() {- if (store.textEditor) store.textEditor.caretVisible = true- clearInterval(blinkTimer)- blinkTimer = window.setInterval(() => {- if (!store.textEditor) return- store.textEditor.caretVisible = !store.textEditor.caretVisible- store.requestRepaint()- }, CARET_BLINK_MS)- store.requestRepaint()- }-- function syncText(nodeId: string, text: string, runs?: SceneNode['styleRuns']) {- const changes: Partial<SceneNode> = { text }- if (runs !== undefined) changes.styleRuns = runs- store.graph.updateNode(nodeId, changes)- store.requestRender()- }-- function insertText(text: string, node: SceneNode) {- const editor = store.textEditor- if (!editor) return- const range = editor.getSelectionRange()- let runs = node.styleRuns- if (range) {- runs = adjustRunsForDelete(runs, range[0], range[1] - range[0])- runs = adjustRunsForInsert(runs, range[0], text.length)- } else {- runs = adjustRunsForInsert(runs, editor.state?.cursor ?? 0, text.length)- }- editor.insert(text, node)- syncText(node.id, editor.state?.text ?? '', runs)- }-- function deleteText(node: SceneNode, forward: boolean) {- const editor = store.textEditor- if (!editor) return- const range = editor.getSelectionRange()- let runs = node.styleRuns- if (range) {- runs = adjustRunsForDelete(runs, range[0], range[1] - range[0])- } else if (forward && editor.state && editor.state.cursor < node.text.length) {- runs = adjustRunsForDelete(runs, editor.state.cursor, 1)- } else if (!forward && editor.state && editor.state.cursor > 0) {- runs = adjustRunsForDelete(runs, editor.state.cursor - 1, 1)- }- if (forward) {- editor.delete(node)- } else {- editor.backspace(node)- }- syncText(node.id, editor.state?.text ?? '', runs)- }-- function onCompositionStart() {- isComposing = true- }-- function onCompositionEnd(e: CompositionEvent) {- isComposing = false- if (!e.data) return- const node = getEditingNode()- if (!node) return- insertText(e.data, node)- if (textareaRef.value) textareaRef.value.value = ''- resetBlink()- }-- function onInput() {- const el = textareaRef.value- if (isComposing || !el) return- const text = el.value- if (!text) return- el.value = ''-- const node = getEditingNode()- if (!node) return- insertText(text, node)- resetBlink()- }-- function handleHorizontalArrow(e: KeyboardEvent, editor: NonNullable<typeof store.textEditor>) {- const select = e.shiftKey- const isMeta = e.metaKey || e.ctrlKey- if (e.code === 'ArrowLeft') {- if (isMeta) editor.moveToLineStart(select)- else if (e.altKey) editor.moveWordLeft(select)- else editor.moveLeft(select)- } else if (e.code === 'ArrowRight') {- if (isMeta) editor.moveToLineEnd(select)- else if (e.altKey) editor.moveWordRight(select)- else editor.moveRight(select)- }- }-- function handleDeletion(- e: KeyboardEvent,- editor: NonNullable<typeof store.textEditor>,- node: SceneNode- ) {- const isMeta = e.metaKey || e.ctrlKey- const forward = e.code === 'Delete'- if (forward) {- if (isMeta) editor.moveToLineEnd(true)- else if (e.altKey) editor.moveWordRight(true)- } else {- if (isMeta) editor.moveToLineStart(true)- else if (e.altKey) editor.moveWordLeft(true)- }- deleteText(node, forward)- }-- type MetaAction = (node: SceneNode) => void- const metaKeyActions: Partial<Record<string, MetaAction>> = {- KeyA: () => store.textEditor?.selectAll(),- KeyC: () => handleCopy(),- KeyX: (node) => handleCut(node),- KeyV: (node) => void handlePaste(node),- KeyB: (node) => toggleBold(node),- KeyI: (node) => toggleItalic(node),- KeyU: (node) => toggleUnderline(node)- }-- function onKeyDown(e: KeyboardEvent) {- if (isComposing) return- const editor = store.textEditor- const node = getEditingNode()- if (!editor || !node) return-- const isMeta = e.metaKey || e.ctrlKey- let textChanged = false-- switch (e.code) {- case 'Escape':- store.commitTextEdit()- canvasRef.value?.focus()- e.preventDefault()- return- case 'Enter':- insertText('\n', node)- textChanged = true- break- case 'Backspace':- case 'Delete':- handleDeletion(e, editor, node)- textChanged = true- break- case 'ArrowLeft':- case 'ArrowRight':- handleHorizontalArrow(e, editor)- break- case 'ArrowUp':- editor.moveUp(e.shiftKey)- break- case 'ArrowDown':- editor.moveDown(e.shiftKey)- break- case 'Home':- editor.moveToLineStart(e.shiftKey)- break- case 'End':- editor.moveToLineEnd(e.shiftKey)- break- default: {- if (!isMeta) return- const action = metaKeyActions[e.code]- if (!action) return- action(node)- e.preventDefault()- return- }- }-- if (!textChanged) {- store.requestRender()- }- resetBlink()- e.preventDefault()- }-- function applyFormatting(nodeId: string, changes: Partial<SceneNode>, label: string) {- store.updateNodeWithUndo(nodeId, changes, label)- const updated = store.graph.getNode(nodeId)- if (updated) store.textEditor?.rebuildParagraph(updated)- store.requestRender()- }-- function toggleBold(node: SceneNode) {- const editor = store.textEditor- const range = editor?.getSelectionRange()- if (range) {- const { runs } = toggleBoldInRange(- node.styleRuns,- range[0],- range[1],- node.fontWeight,- node.text.length- )- applyFormatting(node.id, { styleRuns: runs }, 'Toggle bold')- } else {- applyFormatting(node.id, { fontWeight: node.fontWeight >= 700 ? 400 : 700 }, 'Toggle bold')- }- }-- function toggleItalic(node: SceneNode) {- const editor = store.textEditor- const range = editor?.getSelectionRange()- if (range) {- const { runs } = toggleItalicInRange(- node.styleRuns,- range[0],- range[1],- node.italic,- node.text.length- )- applyFormatting(node.id, { styleRuns: runs }, 'Toggle italic')- } else {- applyFormatting(node.id, { italic: !node.italic }, 'Toggle italic')- }- }-- function toggleUnderline(node: SceneNode) {- const editor = store.textEditor- const range = editor?.getSelectionRange()- if (range) {- const { runs } = toggleDecorationInRange(- node.styleRuns,- range[0],- range[1],- 'UNDERLINE',- node.textDecoration,- node.text.length- )- applyFormatting(node.id, { styleRuns: runs }, 'Toggle underline')- } else {- applyFormatting(- node.id,- { textDecoration: node.textDecoration === 'UNDERLINE' ? 'NONE' : 'UNDERLINE' },- 'Toggle underline'- )- }- }-- function handleCopy() {- const editor = store.textEditor- if (!editor) return- const text = editor.getSelectedText()- if (text) void navigator.clipboard.writeText(text)- }-- function handleCut(node: ReturnType<typeof getEditingNode>) {- const editor = store.textEditor- if (!editor || !node) return- const text = editor.getSelectedText()- if (text) {- void navigator.clipboard.writeText(text)- deleteText(node, false)- resetBlink()- }- }-- async function handlePaste(node: ReturnType<typeof getEditingNode>) {- const editor = store.textEditor- if (!editor || !node) return- try {- const text = await navigator.clipboard.readText()- if (text) {- insertText(text, node)- resetBlink()- }- } catch (e) {- console.warn('Clipboard access denied:', e)- }- }-- useEventListener(textareaRef, 'input', onInput)- useEventListener(textareaRef, 'compositionstart', onCompositionStart)- useEventListener(textareaRef, 'compositionend', onCompositionEnd)- useEventListener(textareaRef, 'keydown', onKeyDown)-- useEventListener(canvasRef, 'mousedown', () => {- if (store.state.editingTextId && textareaRef.value) {- requestAnimationFrame(() => textareaRef.value?.focus())- }- })-- watch(- () => store.state.editingTextId,- (id, _, onCleanup) => {- if (id) {- const el = document.createElement('textarea')- el.style.cssText =- 'position:fixed;opacity:0;width:1px;height:1px;padding:0;border:0;top:50%;left:50%;overflow:hidden;resize:none;'- el.autocomplete = 'off'- el.setAttribute('autocorrect', 'off')- el.setAttribute('autocapitalize', 'none')- el.spellcheck = false- el.tabIndex = -1- el.setAttribute('aria-hidden', 'true')- document.body.appendChild(el)- textareaRef.value = el- el.focus()- resetBlink()-- onCleanup(() => {- clearInterval(blinkTimer)- el.remove()- textareaRef.value = null- isComposing = false- })- }- }- )-}diff --git a/packages/vue/src/ColorPicker/index.ts b/packages/vue/src/ColorPicker/index.tsdeleted file mode 100644index dadd45068..000000000--- a/packages/vue/src/ColorPicker/index.ts+++ /dev/null@@ -1,18 +0,0 @@-export { default as ColorInputRoot } from './ColorInputRoot.vue'-export { default as ColorPickerRoot } from './ColorPickerRoot.vue'-export {- createColorPickerModel,- createOkHCLSliderGradientModel,- createOkHCLSliderPreviewModel,- createSliderGradientModel,- createSliderPreviewModel,- fromPercent,- rekaToAppColor,- toPercent,- updateAlpha,- updateHSBChannel,- updateHSLChannel,- updateHue,- updateRGBChannel-} from './model'-export { applySolidFillColor, applySolidStrokeColor } from './solid-color'diff --git a/packages/vue/src/ColorPicker/solid-color.ts b/packages/vue/src/ColorPicker/solid-color.tsdeleted file mode 100644index dc293cdf8..000000000--- a/packages/vue/src/ColorPicker/solid-color.ts+++ /dev/null@@ -1,16 +0,0 @@-import type { Color, Fill, Stroke } from '@open-pencil/core'--export function applySolidFillColor(fill: Fill, color: Color): Fill {- return {- ...fill,- color,- opacity: color.a- }-}--export function applySolidStrokeColor(color: Color): Partial<Stroke> {- return {- color,- opacity: color.a- }-}diff --git a/packages/vue/src/FillPicker/index.ts b/packages/vue/src/FillPicker/index.tsdeleted file mode 100644index 554f42ad9..000000000--- a/packages/vue/src/FillPicker/index.ts+++ /dev/null@@ -1 +0,0 @@-export { default as FillPickerRoot } from './FillPickerRoot.vue'diff --git a/packages/vue/src/FontPicker/index.ts b/packages/vue/src/FontPicker/index.tsdeleted file mode 100644index 1195a355f..000000000--- a/packages/vue/src/FontPicker/index.ts+++ /dev/null@@ -1 +0,0 @@-export { default as FontPickerRoot } from './FontPickerRoot.vue'diff --git a/packages/vue/src/GradientEditor/GradientEditorRoot.vue b/packages/vue/src/GradientEditor/GradientEditorRoot.vuedeleted file mode 100644index aff84d8f3..000000000--- a/packages/vue/src/GradientEditor/GradientEditorRoot.vue+++ /dev/null@@ -1,129 +0,0 @@-<script setup lang="ts">-import { computed, ref } from 'vue'-import { colorToCSS, parseColor } from '@open-pencil/core'--import type { Fill, GradientStop, GradientTransform } from '@open-pencil/core'--type GradientSubtype =- | 'GRADIENT_LINEAR'- | 'GRADIENT_RADIAL'- | 'GRADIENT_ANGULAR'- | 'GRADIENT_DIAMOND'--const SUBTYPES: { value: GradientSubtype; label: string }[] = [- { value: 'GRADIENT_LINEAR', label: 'Linear' },- { value: 'GRADIENT_RADIAL', label: 'Radial' },- { value: 'GRADIENT_ANGULAR', label: 'Angular' },- { value: 'GRADIENT_DIAMOND', label: 'Diamond' }-]--const DEFAULT_TRANSFORMS: Record<GradientSubtype, GradientTransform> = {- GRADIENT_LINEAR: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 0, m12: 0.5 },- GRADIENT_RADIAL: { m00: 0.5, m01: 0, m02: 0.5, m10: 0, m11: 0.5, m12: 0.5 },- GRADIENT_ANGULAR: { m00: 0.5, m01: 0, m02: 0.5, m10: 0, m11: 0.5, m12: 0.5 },- GRADIENT_DIAMOND: { m00: 0.5, m01: 0, m02: 0.5, m10: 0, m11: 0.5, m12: 0.5 }-}--const { fill } = defineProps<{ fill: Fill }>()-const emit = defineEmits<{ update: [fill: Fill] }>()--const activeStopIndex = ref(0)-const stops = computed(() => fill.gradientStops ?? [])-const subtype = computed(() => fill.type as GradientSubtype)--const activeColor = computed(() => {- const s = stops.value- if (!s.length) return fill.color- return s[Math.min(activeStopIndex.value, s.length - 1)].color-})--const barBackground = computed(() =>- stops.value.length- ? `linear-gradient(to right, ${stops.value.map((s) => `${colorToCSS(s.color)} ${s.position * 100}%`).join(', ')})`- : ''-)--function emitStops(newStops: GradientStop[]) {- emit('update', { ...fill, gradientStops: newStops })-}--function setSubtype(type: GradientSubtype) {- if (type === fill.type) return- emit('update', { ...fill, type, gradientTransform: DEFAULT_TRANSFORMS[type] })-}--function selectStop(index: number) {- activeStopIndex.value = index-}--function addStop() {- const s = [...stops.value]- const pos = s.length >= 2 ? (s[s.length - 2].position + s[s.length - 1].position) / 2 : 0.5- s.push({ color: { ...activeColor.value }, position: pos })- s.sort((a, b) => a.position - b.position)- activeStopIndex.value = s.findIndex((stop) => stop.position === pos)- emitStops(s)-}--function removeStop(index: number) {- if (stops.value.length <= 2) return- emitStops(stops.value.filter((_, i) => i !== index))- activeStopIndex.value = Math.min(activeStopIndex.value, stops.value.length - 2)-}--function updateStopPosition(index: number, position: number) {- const s = [...stops.value]- s[index] = { ...s[index], position: Math.max(0, Math.min(1, position / 100)) }- emitStops(s)-}--function updateStopColor(index: number, hex: string) {- const color = parseColor(hex.startsWith('#') ? hex : `#${hex}`)- if (!color) return- const s = [...stops.value]- s[index] = { ...s[index], color: { ...color, a: s[index].color.a } }- emitStops(s)-}--function updateStopOpacity(index: number, opacity: number) {- const s = [...stops.value]- s[index] = {- ...s[index],- color: { ...s[index].color, a: Math.max(0, Math.min(1, opacity / 100)) }- }- emitStops(s)-}--function onActiveColorUpdate(color: { r: number; g: number; b: number; a: number }) {- const s = [...stops.value]- const idx = Math.min(activeStopIndex.value, s.length - 1)- s[idx] = { ...s[idx], color }- emitStops(s)-}--function onStopDrag(index: number, position: number) {- const s = [...stops.value]- s[index] = { ...s[index], position }- emitStops(s)-}-</script>--<template>- <slot- :stops="stops"- :subtype="subtype"- :subtypes="SUBTYPES"- :active-stop-index="activeStopIndex"- :active-color="activeColor"- :bar-background="barBackground"- :set-subtype="setSubtype"- :select-stop="selectStop"- :add-stop="addStop"- :remove-stop="removeStop"- :update-stop-position="updateStopPosition"- :update-stop-color="updateStopColor"- :update-stop-opacity="updateStopOpacity"- :update-active-color="onActiveColorUpdate"- :drag-stop="onStopDrag"- />-</template>diff --git a/packages/vue/src/GradientEditor/index.ts b/packages/vue/src/GradientEditor/index.tsdeleted file mode 100644index 748fd39ee..000000000--- a/packages/vue/src/GradientEditor/index.ts+++ /dev/null@@ -1,3 +0,0 @@-export { default as GradientEditorRoot } from './GradientEditorRoot.vue'-export { default as GradientEditorBar } from './GradientEditorBar.vue'-export { default as GradientEditorStop } from './GradientEditorStop.vue'diff --git a/packages/vue/src/LayerTree/index.ts b/packages/vue/src/LayerTree/index.tsdeleted file mode 100644index 9024f61a7..000000000--- a/packages/vue/src/LayerTree/index.ts+++ /dev/null@@ -1,4 +0,0 @@-export { default as LayerTreeRoot } from './LayerTreeRoot.vue'-export { default as LayerTreeItem } from './LayerTreeItem.vue'-export { useLayerTree } from './context'-export type { LayerTreeContext, LayerNode } from './context'diff --git a/packages/vue/src/LayoutControls/index.ts b/packages/vue/src/LayoutControls/index.tsdeleted file mode 100644index b6899b659..000000000--- a/packages/vue/src/LayoutControls/index.ts+++ /dev/null@@ -1 +0,0 @@-export { default as LayoutControlsRoot } from './LayoutControlsRoot.vue'diff --git a/packages/vue/src/PageList/index.ts b/packages/vue/src/PageList/index.tsdeleted file mode 100644index abb1df0a1..000000000--- a/packages/vue/src/PageList/index.ts+++ /dev/null@@ -1 +0,0 @@-export { default as PageListRoot } from './PageListRoot.vue'diff --git a/packages/vue/src/PositionControls/index.ts b/packages/vue/src/PositionControls/index.tsdeleted file mode 100644index 9fb0f748a..000000000--- a/packages/vue/src/PositionControls/index.ts+++ /dev/null@@ -1 +0,0 @@-export { default as PositionControlsRoot } from './PositionControlsRoot.vue'diff --git a/packages/vue/src/PropertyList/index.ts b/packages/vue/src/PropertyList/index.tsdeleted file mode 100644index f089cbd75..000000000--- a/packages/vue/src/PropertyList/index.ts+++ /dev/null@@ -1,4 +0,0 @@-export { default as PropertyListRoot } from './PropertyListRoot.vue'-export { default as PropertyListItem } from './PropertyListItem.vue'-export { usePropertyList } from './context'-export type { PropertyListContext } from './context'diff --git a/packages/vue/src/ScrubInput/index.ts b/packages/vue/src/ScrubInput/index.tsdeleted file mode 100644index 0ab973311..000000000--- a/packages/vue/src/ScrubInput/index.ts+++ /dev/null@@ -1,5 +0,0 @@-export { default as ScrubInputRoot } from './ScrubInputRoot.vue'-export { default as ScrubInputField } from './ScrubInputField.vue'-export { default as ScrubInputDisplay } from './ScrubInputDisplay.vue'-export { useScrubInput } from './context'-export type { ScrubInputContext } from './context'diff --git a/packages/vue/src/Toolbar/index.ts b/packages/vue/src/Toolbar/index.tsdeleted file mode 100644index c73aae9da..000000000--- a/packages/vue/src/Toolbar/index.ts+++ /dev/null@@ -1,4 +0,0 @@-export { default as ToolbarRoot } from './ToolbarRoot.vue'-export { default as ToolbarItem } from './ToolbarItem.vue'-export { useToolbar } from './context'-export type { ToolbarContext } from './context'diff --git a/packages/vue/src/TypographyControls/index.ts b/packages/vue/src/TypographyControls/index.tsdeleted file mode 100644index 1c2ea0745..000000000--- a/packages/vue/src/TypographyControls/index.ts+++ /dev/null@@ -1 +0,0 @@-export { default as TypographyControlsRoot } from './TypographyControlsRoot.vue'diff --git a/packages/vue/src/VariablesEditor/index.ts b/packages/vue/src/VariablesEditor/index.tsdeleted file mode 100644index e69de29bb..000000000diff --git a/packages/vue/src/VariablesEditor/useVariablesTable.ts b/packages/vue/src/VariablesEditor/useVariablesTable.tsdeleted file mode 100644index d5056c506..000000000--- a/packages/vue/src/VariablesEditor/useVariablesTable.ts+++ /dev/null@@ -1,138 +0,0 @@-import { EditableArea, EditableInput, EditablePreview, EditableRoot } from 'reka-ui'-import { computed, h, type Component } from 'vue'--import type { Color, Variable, VariableValue } from '@open-pencil/core'-import type { ColumnDef } from '@tanstack/vue-table'-import type { ComputedRef } from 'vue'--interface VariablesTableOptions {- activeModes: ComputedRef<{ modeId: string; name: string }[]>- formatModeValue: (variable: Variable, modeId: string) => string- parseVariableValue: (variable: Variable, raw: string) => VariableValue | undefined- shortName: (variable: Variable) => string- renameVariable: (id: string, newName: string) => void- updateVariableValue: (id: string, modeId: string, value: VariableValue) => void- removeVariable: (id: string) => void- ColorInput: Component- icons: Record<string, Component>- fallbackIcon: Component- deleteIcon: Component-}--export function useVariablesTable(options: VariablesTableOptions) {- function commitNameEdit(variable: Variable, newName: string) {- if (newName && newName !== variable.name) {- options.renameVariable(variable.id, newName)- }- }-- function commitValueEdit(variable: Variable, modeId: string, newValue: string) {- const parsed = options.parseVariableValue(variable, newValue)- if (parsed !== undefined) {- options.updateVariableValue(variable.id, modeId, parsed)- }- }-- const columns = computed<ColumnDef<Variable>[]>(() => {- const nameCol: ColumnDef<Variable> = {- id: 'name',- header: 'Name',- size: 200,- minSize: 120,- maxSize: 400,- cell: ({ row }) => {- const variable = row.original- const iconClass = 'size-3.5 shrink-0 text-muted'- const iconComponent = options.icons[variable.type] ?? options.fallbackIcon- const icon = h(iconComponent, { class: iconClass })-- return h('div', { class: 'flex items-center gap-2' }, [- icon,- h(- EditableRoot,- {- defaultValue: options.shortName(variable),- class: 'min-w-0 flex-1',- onSubmit: (value: string | null | undefined) =>- value && commitNameEdit(variable, value)- },- () =>- h(EditableArea, { class: 'flex' }, () => [- h(EditablePreview, {- class: 'min-w-0 flex-1 cursor-text truncate text-xs text-surface'- }),- h(EditableInput, {- class:- 'min-w-0 flex-1 rounded border border-border bg-surface/10 px-1 py-0.5 text-xs text-surface outline-none'- })- ])- )- ])- }- }-- const modeCols: ColumnDef<Variable>[] = options.activeModes.value.map((mode) => ({- id: `mode-${mode.modeId}`,- header: mode.name,- size: 200,- minSize: 120,- maxSize: 500,- cell: ({ row }) => {- const variable = row.original- const value = variable.valuesByMode[mode.modeId]-- if (variable.type === 'COLOR' && value && typeof value === 'object' && 'r' in value) {- return h(options.ColorInput, {- color: value as Color,- onUpdate: (color: Color) => options.updateVariableValue(variable.id, mode.modeId, color)- })- }-- return h(- EditableRoot,- {- defaultValue: options.formatModeValue(variable, mode.modeId),- class: 'min-w-0 flex-1',- onSubmit: (value: string | null | undefined) =>- value && commitValueEdit(variable, mode.modeId, value)- },- () =>- h(EditableArea, { class: 'flex' }, () => [- h(EditablePreview, {- class: 'min-w-0 flex-1 cursor-text truncate font-mono text-xs text-muted'- }),- h(EditableInput, {- class:- 'min-w-0 flex-1 rounded border border-border bg-surface/10 px-1 py-0.5 font-mono text-xs text-surface outline-none'- })- ])- )- }- }))-- const deleteCol: ColumnDef<Variable> = {- id: 'actions',- header: '',- size: 36,- minSize: 36,- maxSize: 36,- enableResizing: false,- cell: ({ row }) =>- h(- 'button',- {- class:- 'flex size-5 cursor-pointer items-center justify-center rounded border-none bg-transparent text-muted opacity-0 transition-opacity group-hover:opacity-100 hover:text-surface',- onClick: () => options.removeVariable(row.original.id)- },- h(options.deleteIcon, { class: 'size-3' })- )- }-- return [nameCol, ...modeCols, deleteCol]- })-- return {- columns- }-}diff --git a/packages/vue/src/Canvas/CanvasRoot.vue b/packages/vue/src/canvas/CanvasRoot.vuesimilarity index 65%rename from packages/vue/src/Canvas/CanvasRoot.vuerename to packages/vue/src/canvas/CanvasRoot.vueindex b4ccfdb9a..dc006b8da 100644--- a/packages/vue/src/Canvas/CanvasRoot.vue+++ b/packages/vue/src/canvas/CanvasRoot.vue@@ -1,13 +1,11 @@<script setup lang="ts">import { ref } from 'vue'-import { useEditor } from '@open-pencil/vue/context/editorContext'-import { useCanvas, type UseCanvasOptions } from '@open-pencil/vue'-import { provideCanvas } from './context'+import { useEditor } from '#vue/editor/context'+import { useCanvas, type UseCanvasOptions } from '#vue/canvas/surface/use'+import { provideCanvas } from '#vue/canvas/context'-const props = withDefaults(defineProps<UseCanvasOptions>(), {- showRulers: undefined-})+const { showRulers, preserveDrawingBuffer } = defineProps<UseCanvasOptions>()const editor = useEditor()const canvasRef = ref<HTMLCanvasElement | null>(null)@@ -17,7 +15,8 @@ const { renderNow, hitTestSectionTitle, hitTestComponentLabel, hitTestFrameTitlecanvasRef,editor,{- ...props,+ showRulers,+ preserveDrawingBuffer,onReady: () => {ready.value = true}diff --git a/packages/vue/src/Canvas/CanvasSurface.vue b/packages/vue/src/canvas/CanvasSurface.vuesimilarity index 84%rename from packages/vue/src/Canvas/CanvasSurface.vuerename to packages/vue/src/canvas/CanvasSurface.vueindex a18281c55..5a95b1d7a 100644--- a/packages/vue/src/Canvas/CanvasSurface.vue+++ b/packages/vue/src/canvas/CanvasSurface.vue@@ -1,5 +1,5 @@<script setup lang="ts">-import { useCanvasContext } from './context'+import { useCanvasContext } from '#vue/canvas/context'const { canvasRef } = useCanvasContext()</script>diff --git a/packages/vue/src/Canvas/context.ts b/packages/vue/src/canvas/context/index.tssimilarity index 82%rename from packages/vue/src/Canvas/context.tsrename to packages/vue/src/canvas/context/index.tsindex cfa47e04d..8686d2a15 100644--- a/packages/vue/src/Canvas/context.ts+++ b/packages/vue/src/canvas/context/index.ts@@ -1,7 +1,6 @@-import { type InjectionKey, inject, provide } from 'vue'+import { type InjectionKey, type Ref, inject, provide } from 'vue'-import type { SceneNode } from '@open-pencil/core'-import type { Ref } from 'vue'+import type { SceneNode } from '@open-pencil/core/scene-graph'export interface CanvasContext {canvasRef: Ref<HTMLCanvasElement | null>diff --git a/packages/vue/src/Canvas/useCanvasDrop.ts b/packages/vue/src/canvas/drop/use.tssimilarity index 100%rename from packages/vue/src/Canvas/useCanvasDrop.tsrename to packages/vue/src/canvas/drop/use.tsdiff --git a/packages/vue/src/canvas/index.ts b/packages/vue/src/canvas/index.tsnew file mode 100644index 000000000..c87e7e471--- /dev/null+++ b/packages/vue/src/canvas/index.ts@@ -0,0 +1,4 @@+export { default as CanvasRoot } from '#vue/canvas/CanvasRoot.vue'+export { default as CanvasSurface } from '#vue/canvas/CanvasSurface.vue'+export { useCanvasContext } from '#vue/canvas/context'+export type { CanvasContext } from '#vue/canvas/context'diff --git a/packages/vue/src/canvas/node-edit-input/bend.ts b/packages/vue/src/canvas/node-edit-input/bend.tsnew file mode 100644index 000000000..4bef73ead--- /dev/null+++ b/packages/vue/src/canvas/node-edit-input/bend.ts@@ -0,0 +1,122 @@+import type { DragState } from '#vue/shared/input/types'+import type { VectorSegment } from '@open-pencil/core/scene-graph'+import type { Vector } from '@open-pencil/core/types'+import type { Editor } from '@open-pencil/core/editor'++export type CanvasNodeEditState = {+ segments: VectorSegment[]+ vertices: Vector[]+ hoveredHandleInfo: {+ segmentIndex: number+ tangentField: 'tangentStart' | 'tangentEnd'+ } | null+}++export type CanvasNodeEditMethods = Partial<{+ nodeEditBendHandle: (+ vertexIndex: number,+ dx: number,+ dy: number,+ independent: boolean,+ targetSegmentIndex: number | null,+ targetTangentField: 'tangentStart' | 'tangentEnd' | null+ ) => void+ nodeEditZeroVertexHandles: (vertexIndex: number) => void+ nodeEditConnectEndpoints: (a: number, b: number) => void+ enterNodeEditMode: (nodeId: string) => void+}>++export function getCanvasNodeEditState(editor: Editor): CanvasNodeEditState | null | undefined {+ return (editor.state as Editor['state'] & { nodeEditState?: CanvasNodeEditState | null })+ .nodeEditState+}++export function resolveBendTargetHandle(+ es: CanvasNodeEditState | null | undefined,+ vertexIndex: number,+ samples: Vector[]+): { segmentIndex: number; tangentField: 'tangentStart' | 'tangentEnd' } | null {+ if (!es || samples.length === 0) return null+ const vertex = es.vertices.at(vertexIndex)+ if (!vertex) return null+ const vx = vertex.x+ const vy = vertex.y++ const sampleVector = samples.reduce(+ (acc, p) => ({ x: acc.x + (p.x - vx), y: acc.y + (p.y - vy) }),+ { x: 0, y: 0 }+ )+ const sampleLen = Math.hypot(sampleVector.x, sampleVector.y)+ if (sampleLen < 1e-6) return null+ const sampleDir = { x: sampleVector.x / sampleLen, y: sampleVector.y / sampleLen }++ let best: { segmentIndex: number; tangentField: 'tangentStart' | 'tangentEnd' } | null = null+ let bestDot = -Infinity+ for (let i = 0; i < es.segments.length; i++) {+ const seg = es.segments[i]+ let tangentField: 'tangentStart' | 'tangentEnd'+ let neighborIndex: number+ let tangent: Vector+ if (seg.start === vertexIndex) {+ tangentField = 'tangentStart'+ neighborIndex = seg.end+ tangent = seg.tangentStart+ } else if (seg.end === vertexIndex) {+ tangentField = 'tangentEnd'+ neighborIndex = seg.start+ tangent = seg.tangentEnd+ } else {+ continue+ }++ const neighbor = es.vertices[neighborIndex]++ const tangentLen = Math.hypot(tangent.x, tangent.y)+ const base = tangentLen > 1e-6 ? tangent : { x: neighbor.x - vx, y: neighbor.y - vy }+ const baseLen = Math.hypot(base.x, base.y)+ if (baseLen < 1e-6) continue+ const dir = { x: base.x / baseLen, y: base.y / baseLen }+ const dot = dir.x * sampleDir.x + dir.y * sampleDir.y+ if (dot > bestDot) {+ bestDot = dot+ best = { segmentIndex: i, tangentField }+ }+ }+ return best+}++export function handleBendHandleMove(+ d: Extract<DragState, { type: 'bend-handle' }>,+ cx: number,+ cy: number,+ event: MouseEvent,+ editor: Editor+): void {+ const nodeEditEditor = editor as Editor & CanvasNodeEditMethods+ const nodeEditState = getCanvasNodeEditState(editor)+ const dx = cx - d.startX+ const dy = cy - d.startY+ if (Math.hypot(dx, dy) < 2) return+ if (d.lockedMode === null) {+ d.lockedMode = event.altKey ? 'independent' : 'symmetric'+ }+ if (d.dragSamples.length < 3) {+ d.dragSamples.push({ x: cx, y: cy })+ }+ if (d.targetSegmentIndex === null && d.dragSamples.length >= 3) {+ const target = resolveBendTargetHandle(nodeEditState, d.vertexIndex, d.dragSamples)+ if (target) {+ d.targetSegmentIndex = target.segmentIndex+ d.targetTangentField = target.tangentField+ }+ }+ if (d.targetSegmentIndex === null || d.targetTangentField === null) return+ nodeEditEditor.nodeEditBendHandle?.(+ d.vertexIndex,+ dx,+ dy,+ d.lockedMode === 'independent',+ d.targetSegmentIndex,+ d.targetTangentField+ )+}diff --git a/packages/vue/src/canvas/node-edit-input/use.ts b/packages/vue/src/canvas/node-edit-input/use.tsnew file mode 100644index 000000000..a5a32022e--- /dev/null+++ b/packages/vue/src/canvas/node-edit-input/use.ts@@ -0,0 +1,77 @@+import {+ getCanvasNodeEditState,+ handleBendHandleMove,+ resolveBendTargetHandle,+ type CanvasNodeEditMethods+} from '#vue/canvas/node-edit-input/bend'+import { hitTestEditHandle, isEndpoint, NODE_HIT_THRESHOLD } from '#vue/shared/input/node-edit'++import type { DragState } from '#vue/shared/input/types'+import type { Editor } from '@open-pencil/core/editor'+import type { Ref } from 'vue'++export function updateNodeEditHover(editor: Editor, cx: number, cy: number): boolean {+ const nodeEditState = getCanvasNodeEditState(editor)+ if (!nodeEditState) return false+ const hit = hitTestEditHandle(editor, cx, cy)+ const prev = nodeEditState.hoveredHandleInfo+ if (hit) {+ if (!prev || prev.segmentIndex !== hit.segmentIndex || prev.tangentField !== hit.tangentField) {+ nodeEditState.hoveredHandleInfo = {+ segmentIndex: hit.segmentIndex,+ tangentField: hit.tangentField+ }+ editor.requestRepaint()+ }+ } else if (prev) {+ nodeEditState.hoveredHandleInfo = null+ editor.requestRepaint()+ }+ return true+}++export { handleBendHandleMove, resolveBendTargetHandle }++export function handleNodeEditMouseUp(drag: Ref<DragState | null>, editor: Editor): boolean {+ const nodeEditEditor = editor as Editor & CanvasNodeEditMethods+ const d = drag.value+ if (!d) return false++ if (d.type === 'bend-handle') {+ if (d.lockedMode === null) {+ nodeEditEditor.nodeEditZeroVertexHandles?.(d.vertexIndex)+ }+ drag.value = null+ return true+ }++ if (d.type === 'edit-node') {+ const es = getCanvasNodeEditState(editor)+ if (es && d.origPositions.size === 1) {+ const [draggedIdx] = d.origPositions.keys()+ if (isEndpoint(draggedIdx, es.segments)) {+ const v = es.vertices[draggedIdx]+ const iz = 1 / editor.state.zoom+ for (let i = 0; i < es.vertices.length; i++) {+ if (i === draggedIdx) continue+ if (!isEndpoint(i, es.segments)) continue+ const t = es.vertices[i]+ if (Math.hypot(v.x - t.x, v.y - t.y) < NODE_HIT_THRESHOLD * iz) {+ nodeEditEditor.nodeEditConnectEndpoints?.(draggedIdx, i)+ drag.value = null+ return true+ }+ }+ }+ }+ drag.value = null+ return true+ }++ if (d.type === 'edit-handle') {+ drag.value = null+ return true+ }++ return false+}diff --git a/packages/vue/src/canvas/pen-input/drag.ts b/packages/vue/src/canvas/pen-input/drag.tsnew file mode 100644index 000000000..fa14d1559--- /dev/null+++ b/packages/vue/src/canvas/pen-input/drag.ts@@ -0,0 +1,145 @@+import type { DragState } from '#vue/shared/input/types'+import type { Vector } from '@open-pencil/core/types'+import type { Editor } from '@open-pencil/core/editor'++type PenDragState = Extract<DragState, { type: 'pen-drag' }>+type PenState = NonNullable<Editor['state']['penState']>+type PenModifierMode = PenDragState['modifierMode']++export function createPenDrag(startX: number, startY: number): DragState {+ return {+ type: 'pen-drag',+ startX,+ startY,+ modifierMode: 'default',+ frozenOppositeTangent: null,+ spaceDown: false,+ spaceStartX: 0,+ spaceStartY: 0,+ knotStartX: startX,+ knotStartY: startY+ } as DragState+}++function getPenAnchor(penState: PenState): Vector {+ const isClosing = !!penState.pendingClose && penState.vertices.length > 2+ const anchorIndex = isClosing ? 0 : penState.vertices.length - 1+ return penState.vertices[anchorIndex]+}++function handleSpaceDrag(+ d: PenDragState,+ cx: number,+ cy: number,+ isSpace: boolean,+ anchor: Vector,+ editor: Editor+): boolean {+ if (!isSpace) return false+ if (!d.spaceDown) {+ d.spaceDown = true+ d.spaceStartX = cx+ d.spaceStartY = cy+ d.knotStartX = anchor.x+ d.knotStartY = anchor.y+ }++ const dx = cx - d.spaceStartX+ const dy = cy - d.spaceStartY+ editor.penSetKnotPosition(d.knotStartX + dx, d.knotStartY + dy)+ return true+}++function applySpaceDragOffset(d: PenDragState, anchor: Vector) {+ if (!d.spaceDown) return+ d.spaceDown = false+ d.startX += anchor.x - d.knotStartX+ d.startY += anchor.y - d.knotStartY+}++function getClosingOpposite(penState: PenState): Vector | null {+ const firstSeg = penState.segments[0]+ if (!penState.pendingClose) return null+ if (firstSeg.start === 0) return firstSeg.tangentStart+ if (firstSeg.end === 0) return firstSeg.tangentEnd+ return null+}++function getModifierMode(event: MouseEvent): PenModifierMode {+ if (event.metaKey || event.ctrlKey) return 'continuous'+ if (event.altKey) return 'independent'+ return 'default'+}++function freezeOppositeTangent(penState: PenState, closingOpposite: Vector | null): Vector {+ const lastSeg = penState.segments[penState.segments.length - 1]+ if (closingOpposite) return { ...closingOpposite }+ return { ...lastSeg.tangentEnd }+}++function updateModifierMode(d: PenDragState, mode: PenModifierMode, penState: PenState) {+ if (mode === d.modifierMode) return+ if (mode === 'default') {+ d.frozenOppositeTangent = null+ } else if (!d.frozenOppositeTangent) {+ d.frozenOppositeTangent = freezeOppositeTangent(penState, getClosingOpposite(penState))+ }+ d.modifierMode = mode+}++function applyPenDragTangent(+ editor: Editor,+ penState: PenState,+ d: PenDragState,+ tx: number,+ ty: number,+ mode: PenModifierMode,+ closingOpposite: Vector | null+) {+ if (mode === 'continuous') {+ editor.penSetDragTangent(tx, ty, {+ keepOpposite: true,+ constrainToOpposite: true,+ oppositeTangent: d.frozenOppositeTangent+ })+ return+ }++ if (mode === 'independent') {+ editor.penSetDragTangent(tx, ty, {+ keepOpposite: true,+ oppositeTangent: d.frozenOppositeTangent+ })+ return+ }++ const options = penState.pendingClose+ ? { keepOpposite: true, oppositeTangent: closingOpposite }+ : undefined+ editor.penSetDragTangent(tx, ty, options)+}++export function handlePenDragMove(+ d: PenDragState,+ cx: number,+ cy: number,+ isSpace: boolean,+ event: MouseEvent,+ editor: Editor+): void {+ const penState = editor.state.penState+ if (!penState) return++ const anchor = getPenAnchor(penState)+ if (handleSpaceDrag(d, cx, cy, isSpace, anchor, editor)) return++ applySpaceDragOffset(d, anchor)++ const tx = cx - d.startX+ const ty = cy - d.startY+ if (Math.hypot(tx, ty) <= 2) return++ const mode = getModifierMode(event)+ updateModifierMode(d, mode, penState)+ applyPenDragTangent(editor, penState, d, tx, ty, mode, getClosingOpposite(penState))+}diff --git a/packages/vue/src/canvas/pen-input/use.ts b/packages/vue/src/canvas/pen-input/use.tsnew file mode 100644index 000000000..2b9303577--- /dev/null+++ b/packages/vue/src/canvas/pen-input/use.ts@@ -0,0 +1,65 @@+import { createPenDrag, handlePenDragMove } from '#vue/canvas/pen-input/drag'+import { handlePenNodeEditDown } from '#vue/shared/input/node-edit'++import { PEN_CLOSE_THRESHOLD } from '@open-pencil/core/constants'++import type { DragState } from '#vue/shared/input/types'+import type { Editor } from '@open-pencil/core/editor'+import type { Ref } from 'vue'++type NodeEditState = NonNullable<Editor['state']> & { nodeEditState?: object | null }++type SetDrag = (drag: DragState) => void++export function startPenInput(+ e: MouseEvent,+ cx: number,+ cy: number,+ editor: Editor,+ setDrag: SetDrag,+ cursorOverride: Ref<string | null>+): boolean {+ editor.state.penCursorX = null+ editor.state.penCursorY = null++ const nodeEditState = (editor.state as NodeEditState).nodeEditState+ if (nodeEditState) {+ handlePenNodeEditDown(e, cx, cy, editor)+ return true+ }++ const penState = editor.state.penState+ if (penState && penState.vertices.length > 2) {+ const first = penState.vertices[0]+ const dist = Math.hypot(cx - first.x, cy - first.y)+ if (dist < PEN_CLOSE_THRESHOLD) {+ editor.penSetPendingClose(true)+ editor.penSetClosingToFirst(true)+ setDrag(createPenDrag(first.x, first.y))+ cursorOverride.value = 'crosshair'+ return true+ }+ }++ editor.penSetPendingClose(false)+ editor.penAddVertex(cx, cy)+ setDrag(createPenDrag(cx, cy))+ cursorOverride.value = 'crosshair'+ return true+}++export function updatePenHover(cx: number, cy: number, editor: Editor): boolean {+ if (editor.state.activeTool !== 'PEN' || !editor.state.penState) return false+ editor.state.penCursorX = cx+ editor.state.penCursorY = cy++ const first = editor.state.penState.vertices[0]+ if (editor.state.penState.vertices.length > 2) {+ const dist = Math.hypot(cx - first.x, cy - first.y)+ editor.penSetClosingToFirst(dist < PEN_CLOSE_THRESHOLD)+ }+ editor.requestRepaint()+ return true+}++export { handlePenDragMove }diff --git a/packages/vue/src/canvas/pointer/use.ts b/packages/vue/src/canvas/pointer/use.tsnew file mode 100644index 000000000..8b95e5ed4--- /dev/null+++ b/packages/vue/src/canvas/pointer/use.ts@@ -0,0 +1,42 @@+import {+ canvasToLocalPoint,+ getPointerCoords,+ hitTestInEditorScope,+ isInsideEditorContainerBounds+} from '#vue/shared/input/geometry'++import type { HitTestFns } from '#vue/shared/input/select'+import type { SceneNode } from '@open-pencil/core/scene-graph'+import type { Editor } from '@open-pencil/core/editor'+import type { Ref } from 'vue'++export function createCanvasPointer(+ canvasRef: Ref<HTMLCanvasElement | null>,+ editor: Editor,+ hitTestSectionTitle: (cx: number, cy: number) => SceneNode | null,+ hitTestComponentLabel: (cx: number, cy: number) => SceneNode | null,+ hitTestFrameTitle: (cx: number, cy: number) => SceneNode | null+) {+ const canvasToLocal = (cx: number, cy: number, scopeId: string) =>+ canvasToLocalPoint(cx, cy, scopeId, editor)+ const hitTestInScope = (cx: number, cy: number, deep: boolean) =>+ hitTestInEditorScope(cx, cy, deep, editor, canvasToLocal)+ const isInsideContainerBounds = (cx: number, cy: number, containerId: string) =>+ isInsideEditorContainerBounds(cx, cy, containerId, editor, canvasToLocal)++ const hitFns: HitTestFns = {+ hitTestInScope,+ isInsideContainerBounds,+ hitTestSectionTitle,+ hitTestComponentLabel,+ hitTestFrameTitle+ }++ return {+ getCoords: (e: MouseEvent) => getPointerCoords(e, canvasRef.value, editor),+ canvasToLocal,+ hitTestInScope,+ isInsideContainerBounds,+ hitFns+ }+}diff --git a/packages/vue/src/canvas/surface/gl-surface.ts b/packages/vue/src/canvas/surface/gl-surface.tsnew file mode 100644index 000000000..f35667bfa--- /dev/null+++ b/packages/vue/src/canvas/surface/gl-surface.ts@@ -0,0 +1,47 @@+import type { UseCanvasOptions } from '#vue/canvas/surface/types'+import type { Editor } from '@open-pencil/core/editor'+import type { CanvasKit, Surface } from 'canvaskit-wasm'++type GLContext = ReturnType<CanvasKit['MakeGrContext']>++export type CanvasGLContext = GLContext++export function sizeCanvas(canvas: HTMLCanvasElement, editor: Editor) {+ const dpr = window.devicePixelRatio || 1+ canvas.width = canvas.clientWidth * dpr+ canvas.height = canvas.clientHeight * dpr+ const maybeSizedEditor = editor as Editor & {+ setViewportSize?: (width: number, height: number) => void+ }+ maybeSizedEditor.setViewportSize?.(canvas.clientWidth, canvas.clientHeight)+}++export function makeGLSurface(+ ck: CanvasKit,+ canvas: HTMLCanvasElement,+ editor: Editor,+ options: UseCanvasOptions | undefined,+ glContext: GLContext | null+): { surface: Surface | null; glContext: GLContext | null } {+ let context = glContext+ if (!context) {+ const glAttrs = options?.preserveDrawingBuffer ? { preserveDrawingBuffer: 1 } : undefined+ const handle = ck.GetWebGLContext(canvas, glAttrs)+ if (!handle) return { surface: null, glContext: context }+ context = ck.MakeGrContext(handle)+ }+ if (!context) return { surface: null, glContext: context }++ const preferredSpace = editor.graph.documentColorSpace+ const colorSpaces =+ preferredSpace === 'display-p3'+ ? [ck.ColorSpace.DISPLAY_P3, ck.ColorSpace.SRGB]+ : [ck.ColorSpace.SRGB]++ for (const colorSpace of colorSpaces) {+ const surface = ck.MakeOnScreenGLSurface(context, canvas.width, canvas.height, colorSpace)+ if (surface) return { surface, glContext: context }+ }++ return { surface: null, glContext: context }+}diff --git a/packages/vue/src/canvas/surface/kit-loader.ts b/packages/vue/src/canvas/surface/kit-loader.tsnew file mode 100644index 000000000..333f4a427--- /dev/null+++ b/packages/vue/src/canvas/surface/kit-loader.ts@@ -0,0 +1,51 @@+import { onMounted, onScopeDispose } from 'vue'++import { getCanvasKit } from '@open-pencil/core/canvaskit'++import type { CanvasKit } from 'canvaskit-wasm'+import type { Ref } from 'vue'++type CanvasKitLoaderOptions = {+ canvasRef: Ref<HTMLCanvasElement | null>+ lifecycle: { destroyed: boolean }+ setCanvasKit: (ck: CanvasKit | null) => void+ createSurface: (canvas: HTMLCanvasElement) => void+ loadFonts: () => Promise<unknown> | undefined+ renderNow: () => void+ onReady?: () => void+}++export function useCanvasKitLoader({+ canvasRef,+ lifecycle,+ setCanvasKit,+ createSurface,+ loadFonts,+ renderNow,+ onReady+}: CanvasKitLoaderOptions) {+ const isDestroyed = () => lifecycle.destroyed++ async function init() {+ const canvas = canvasRef.value+ if (!canvas || isDestroyed()) return++ setCanvasKit(await getCanvasKit())+ if (isDestroyed()) return++ await new Promise((resolve) => requestAnimationFrame(resolve))+ createSurface(canvas)+ await loadFonts()+ if (isDestroyed()) return+ renderNow()+ onReady?.()+ }++ onMounted(() => {+ void init()+ })++ onScopeDispose(() => {+ lifecycle.destroyed = true+ })+}diff --git a/packages/vue/src/canvas/surface/lifecycle.ts b/packages/vue/src/canvas/surface/lifecycle.tsnew file mode 100644index 000000000..17caa18b1--- /dev/null+++ b/packages/vue/src/canvas/surface/lifecycle.ts@@ -0,0 +1,152 @@+import { onScopeDispose } from 'vue'++import { SkiaRenderer } from '@open-pencil/core/canvas'+import { makeGLSurface, sizeCanvas, type CanvasGLContext } from '#vue/canvas/surface/gl-surface'+import { useCanvasKitLoader } from '#vue/canvas/surface/kit-loader'+import { createCanvasRenderLoop } from '#vue/canvas/surface/render-loop'+import { useCanvasResizeObserver } from '#vue/canvas/surface/resize-observer'++import type { UseCanvasOptions } from '#vue/canvas/surface/types'+import type { Editor } from '@open-pencil/core/editor'+import type { CanvasKit } from 'canvaskit-wasm'+import type { Ref } from 'vue'++type SurfaceManagerState = {+ renderer: SkiaRenderer | null+ glContext: CanvasGLContext | null+}++export function createCanvasSurfaceManager({+ editor,+ canvasRef,+ options,+ getCanvasKit,+ isDestroyed,+ shouldShowRulers+}: {+ editor: Editor+ canvasRef: { value: HTMLCanvasElement | null }+ options: UseCanvasOptions | undefined+ getCanvasKit: () => CanvasKit | null+ isDestroyed: () => boolean+ shouldShowRulers: () => boolean+}) {+ const state: SurfaceManagerState = { renderer: null, glContext: null }++ function createSurface(canvas: HTMLCanvasElement) {+ const ck = getCanvasKit()+ if (!ck) return++ if (state.renderer) editor.removeCanvasRenderer(state.renderer)+ state.renderer?.destroy()+ state.renderer = null+ state.glContext?.delete()+ state.glContext = null++ sizeCanvas(canvas, editor)++ const result = makeGLSurface(ck, canvas, editor, options, state.glContext)+ state.glContext = result.glContext+ const surface = result.surface+ if (!surface) {+ canvas.dataset.surfaceError = 'webgl'+ return+ }++ const glCtx = canvas.getContext('webgl2') ?? null+ state.renderer = new SkiaRenderer(ck, surface, glCtx)+ editor.setCanvasKit(ck, state.renderer)+ canvas.dataset.ready = '1'+ }++ function renderNow() {+ if (!state.renderer || isDestroyed()) return+ state.renderer.renderFromEditorState(+ editor.state,+ editor.graph,+ editor.textEditor,+ canvasRef.value?.clientWidth ?? 0,+ canvasRef.value?.clientHeight ?? 0,+ shouldShowRulers(),+ options?.layer ?? 'full'+ )+ renderLoop.markRendered()+ }++ const renderLoop = createCanvasRenderLoop(editor, renderNow)++ function resizeCanvas(canvas: HTMLCanvasElement) {+ const ck = getCanvasKit()+ if (!ck || !state.renderer) {+ createSurface(canvas)+ return+ }++ sizeCanvas(canvas, editor)++ const result = makeGLSurface(ck, canvas, editor, options, state.glContext)+ state.glContext = result.glContext+ const surface = result.surface+ if (!surface) {+ console.warn('Falling back to full surface recreation after resize')+ createSurface(canvas)+ return+ }+ state.renderer.replaceSurface(surface)+ renderNow()+ }++ function destroy() {+ renderLoop.pause()+ if (state.renderer) editor.removeCanvasRenderer(state.renderer)+ state.renderer?.destroy()+ state.glContext?.delete()+ }++ return {+ createSurface,+ resizeCanvas,+ renderNow,+ destroy,+ markDirty: renderLoop.markDirty,+ getRenderer: () => state.renderer+ }+}++export function useCanvasSurfaceLifecycle({+ canvasRef,+ surface,+ setCanvasKit,+ getCanvasKitValue,+ lifecycle,+ onReady+}: {+ canvasRef: Ref<HTMLCanvasElement | null>+ surface: ReturnType<typeof createCanvasSurfaceManager>+ setCanvasKit: (ck: CanvasKit | null) => void+ getCanvasKitValue: () => CanvasKit | null+ lifecycle: { destroyed: boolean }+ onReady?: () => void+}) {+ useCanvasKitLoader({+ canvasRef,+ lifecycle,+ setCanvasKit,+ createSurface: surface.createSurface,+ loadFonts: () => surface.getRenderer()?.loadFonts(),+ renderNow: surface.renderNow,+ onReady+ })++ const { cancelResize } = useCanvasResizeObserver({+ canvasRef,+ getCanvasKitValue,+ resizeCanvas: surface.resizeCanvas+ })++ onScopeDispose(() => {+ lifecycle.destroyed = true+ cancelResize()+ surface.destroy()+ })+}diff --git a/packages/vue/src/canvas/surface/overlays.ts b/packages/vue/src/canvas/surface/overlays.tsnew file mode 100644index 000000000..632e91ea7--- /dev/null+++ b/packages/vue/src/canvas/surface/overlays.ts@@ -0,0 +1,40 @@+import { useViewportKind } from '#vue/editor/viewport-kind/use'++import { IS_BROWSER } from '@open-pencil/core/constants'++import type { SkiaRenderer } from '@open-pencil/core/canvas'+import type { Editor } from '@open-pencil/core/editor'++export type RulerVisibilityOptions = {+ showRulers?: boolean+}++export function createRulerVisibility(options?: RulerVisibilityOptions) {+ const params = IS_BROWSER ? new URLSearchParams(window.location.search) : new URLSearchParams()+ const noRulersParam = params.has('no-rulers')+ const { isMobile } = useViewportKind()++ return function shouldShowRulers() {+ if (options?.showRulers === false) return false+ return !noRulersParam && !isMobile.value+ }+}++export function createCanvasHitTests(editor: Editor, getRenderer: () => SkiaRenderer | null) {+ function hitTestSectionTitle(canvasX: number, canvasY: number) {+ return getRenderer()?.hitTestSectionTitle(editor.graph, canvasX, canvasY) ?? null+ }++ function hitTestComponentLabel(canvasX: number, canvasY: number) {+ return getRenderer()?.hitTestComponentLabel(editor.graph, canvasX, canvasY) ?? null+ }++ function hitTestFrameTitle(canvasX: number, canvasY: number) {+ return (+ getRenderer()?.hitTestFrameTitle(editor.graph, canvasX, canvasY, editor.state.selectedIds) ??+ null+ )+ }++ return { hitTestSectionTitle, hitTestComponentLabel, hitTestFrameTitle }+}diff --git a/packages/vue/src/canvas/surface/render-loop.ts b/packages/vue/src/canvas/surface/render-loop.tsnew file mode 100644index 000000000..264b5a32a--- /dev/null+++ b/packages/vue/src/canvas/surface/render-loop.ts@@ -0,0 +1,32 @@+import { useRafFn } from '@vueuse/core'++import type { Editor } from '@open-pencil/core/editor'++export function createCanvasRenderLoop(editor: Editor, renderNow: () => void) {+ let dirty = true+ let lastRenderVersion = -1+ let lastSelectedIds: Set<string> | null = null++ function markRendered() {+ lastRenderVersion = editor.state.renderVersion+ lastSelectedIds = editor.state.selectedIds+ }++ const { pause } = useRafFn(() => {+ if (editor.state.loading) return+ const versionChanged = editor.state.renderVersion !== lastRenderVersion+ const selectionChanged = editor.state.selectedIds !== lastSelectedIds+ if (dirty || versionChanged || selectionChanged) {+ dirty = false+ renderNow()+ }+ })++ return {+ pause,+ markRendered,+ markDirty: () => {+ dirty = true+ }+ }+}diff --git a/packages/vue/src/canvas/surface/resize-observer.ts b/packages/vue/src/canvas/surface/resize-observer.tsnew file mode 100644index 000000000..48665f939--- /dev/null+++ b/packages/vue/src/canvas/surface/resize-observer.ts@@ -0,0 +1,33 @@+import { useResizeObserver } from '@vueuse/core'++import type { CanvasKit } from 'canvaskit-wasm'+import type { Ref } from 'vue'++type ResizeObserverOptions = {+ canvasRef: Ref<HTMLCanvasElement | null>+ getCanvasKitValue: () => CanvasKit | null+ resizeCanvas: (canvas: HTMLCanvasElement) => void+}++export function useCanvasResizeObserver({+ canvasRef,+ getCanvasKitValue,+ resizeCanvas+}: ResizeObserverOptions) {+ let resizeRaf = 0++ function cancelResize() {+ cancelAnimationFrame(resizeRaf)+ }++ useResizeObserver(canvasRef, () => {+ const canvas = canvasRef.value+ if (!canvas || !getCanvasKitValue() || resizeRaf) return+ resizeRaf = requestAnimationFrame(() => {+ resizeRaf = 0+ resizeCanvas(canvas)+ })+ })++ return { cancelResize }+}diff --git a/packages/vue/src/canvas/surface/types.ts b/packages/vue/src/canvas/surface/types.tsnew file mode 100644index 000000000..bd724e83a--- /dev/null+++ b/packages/vue/src/canvas/surface/types.ts@@ -0,0 +1,28 @@+/**+ * Options for {@link useCanvas}.+ */+export type CanvasRenderLayer = 'full' | 'scene' | 'overlays'++export interface UseCanvasOptions {+ /**+ * Selects which render layer this canvas owns.+ */+ layer?: CanvasRenderLayer+ /**+ * Forces ruler visibility on or off for this canvas.+ *+ * When omitted, the composable falls back to viewport and URL-param logic.+ */+ showRulers?: boolean+ /**+ * Keeps the drawing buffer after presenting frames.+ *+ * Useful for screenshot or pixel-readback workflows, but may increase memory+ * usage depending on the browser and GPU backend.+ */+ preserveDrawingBuffer?: boolean+ /**+ * Called once the rendering surface is ready.+ */+ onReady?: () => void+}diff --git a/packages/vue/src/canvas/surface/use.ts b/packages/vue/src/canvas/surface/use.tsnew file mode 100644index 000000000..cd6bdbd17--- /dev/null+++ b/packages/vue/src/canvas/surface/use.ts@@ -0,0 +1,63 @@+import {+ createCanvasSurfaceManager,+ useCanvasSurfaceLifecycle+} from '#vue/canvas/surface/lifecycle'+import { createCanvasHitTests, createRulerVisibility } from '#vue/canvas/surface/overlays'++import type { UseCanvasOptions } from '#vue/canvas/surface/types'+import type { Editor } from '@open-pencil/core/editor'+import type { CanvasKit } from 'canvaskit-wasm'+import type { Ref } from 'vue'++export type { UseCanvasOptions } from '#vue/canvas/surface/types'++/**+ * Connects an OpenPencil editor to a real canvas element using CanvasKit.+ *+ * This composable owns renderer creation, surface recreation on resize,+ * render scheduling, and renderer-backed hit testing helpers used by higher-+ * level canvas interaction code.+ */+export function useCanvas(+ canvasRef: Ref<HTMLCanvasElement | null>,+ editor: Editor,+ options?: UseCanvasOptions+) {+ let ck: CanvasKit | null = null+ const lifecycle: { destroyed: boolean } = { destroyed: false }+ const isDestroyed = () => lifecycle.destroyed+ const shouldShowRulers = createRulerVisibility(options)++ const surface = createCanvasSurfaceManager({+ editor,+ canvasRef,+ options,+ getCanvasKit: () => ck,+ isDestroyed,+ shouldShowRulers+ })++ useCanvasSurfaceLifecycle({+ canvasRef,+ surface,+ lifecycle,+ getCanvasKitValue: () => ck,+ setCanvasKit: (value) => {+ ck = value+ },+ onReady: options?.onReady+ })++ const { hitTestSectionTitle, hitTestComponentLabel, hitTestFrameTitle } = createCanvasHitTests(+ editor,+ surface.getRenderer+ )++ return {+ render: surface.markDirty,+ renderNow: surface.renderNow,+ hitTestSectionTitle,+ hitTestComponentLabel,+ hitTestFrameTitle+ }+}diff --git a/packages/vue/src/canvas/text-edit/clipboard.ts b/packages/vue/src/canvas/text-edit/clipboard.tsnew file mode 100644index 000000000..3d924cc0c--- /dev/null+++ b/packages/vue/src/canvas/text-edit/clipboard.ts@@ -0,0 +1,50 @@+import type { Editor } from '@open-pencil/core/editor'+import type { SceneNode } from '@open-pencil/core/scene-graph'++type TextClipboardOptions = {+ store: Editor+ insertText: (text: string, node: SceneNode) => void+ deleteText: (node: SceneNode, forward: boolean) => void+ resetBlink: () => void+}++export function createTextClipboardActions({+ store,+ insertText,+ deleteText,+ resetBlink+}: TextClipboardOptions) {+ function handleCopy() {+ const editor = store.textEditor+ if (!editor) return+ const text = editor.getSelectedText()+ if (text) void navigator.clipboard.writeText(text)+ }++ function handleCut(node: SceneNode | null) {+ const editor = store.textEditor+ if (!editor || !node) return+ const text = editor.getSelectedText()+ if (text) {+ void navigator.clipboard.writeText(text)+ deleteText(node, false)+ resetBlink()+ }+ }++ async function handlePaste(node: SceneNode | null) {+ const editor = store.textEditor+ if (!editor || !node) return+ try {+ const text = await navigator.clipboard.readText()+ if (text) {+ insertText(text, node)+ resetBlink()+ }+ } catch (error) {+ console.warn('Clipboard access denied:', error)+ }+ }++ return { handleCopy, handleCut, handlePaste }+}diff --git a/packages/vue/src/canvas/text-edit/editing.ts b/packages/vue/src/canvas/text-edit/editing.tsnew file mode 100644index 000000000..0cce45647--- /dev/null+++ b/packages/vue/src/canvas/text-edit/editing.ts@@ -0,0 +1,131 @@+import { useIntervalFn } from '@vueuse/core'++import { adjustRunsForDelete, adjustRunsForInsert } from '@open-pencil/core/text'++import type { Editor } from '@open-pencil/core/editor'+import type { SceneNode } from '@open-pencil/core/scene-graph'+import type { ShallowRef } from 'vue'++const CARET_BLINK_MS = 530++export function createCaretBlink(store: Editor) {+ const { pause, resume } = useIntervalFn(+ () => {+ if (!store.textEditor) return+ store.textEditor.caretVisible = !store.textEditor.caretVisible+ store.requestRepaint()+ },+ CARET_BLINK_MS,+ { immediate: false }+ )++ function resetBlink() {+ if (store.textEditor) store.textEditor.caretVisible = true+ pause()+ resume()+ store.requestRepaint()+ }++ return { resetBlink, stopBlink: pause }+}++type TextCompositionOptions = {+ textareaRef: ShallowRef<HTMLTextAreaElement | null>+ getEditingNode: () => SceneNode | null+ insertText: (text: string, node: SceneNode) => void+ resetBlink: () => void+}++export function createTextCompositionHandlers({+ textareaRef,+ getEditingNode,+ insertText,+ resetBlink+}: TextCompositionOptions) {+ let isComposing = false++ function onCompositionStart() {+ isComposing = true+ }++ function onCompositionEnd(e: CompositionEvent) {+ isComposing = false+ if (!e.data) return+ const node = getEditingNode()+ if (!node) return+ insertText(e.data, node)+ if (textareaRef.value) textareaRef.value.value = ''+ resetBlink()+ }++ function onInput() {+ const el = textareaRef.value+ if (isComposing || !el) return+ const text = el.value+ if (!text) return+ el.value = ''++ const node = getEditingNode()+ if (!node) return+ insertText(text, node)+ resetBlink()+ }++ function resetComposition() {+ isComposing = false+ }++ return { isComposing: () => isComposing, onCompositionStart, onCompositionEnd, onInput, resetComposition }+}++export function createTextEditActions(store: Editor) {+ function getEditingNode() {+ const id = store.state.editingTextId+ if (!id) return null+ return store.graph.getNode(id) ?? null+ }++ function syncText(nodeId: string, text: string, runs?: SceneNode['styleRuns']) {+ const changes: Partial<SceneNode> = { text }+ if (runs !== undefined) changes.styleRuns = runs+ store.graph.updateNode(nodeId, changes)+ store.requestRender()+ }++ function insertText(text: string, node: SceneNode) {+ const editor = store.textEditor+ if (!editor) return+ const range = editor.getSelectionRange()+ let runs = node.styleRuns+ if (range) {+ runs = adjustRunsForDelete(runs, range[0], range[1] - range[0])+ runs = adjustRunsForInsert(runs, range[0], text.length)+ } else {+ runs = adjustRunsForInsert(runs, editor.state?.cursor ?? 0, text.length)+ }+ editor.insert(text, node)+ syncText(node.id, editor.state?.text ?? '', runs)+ }++ function deleteText(node: SceneNode, forward: boolean) {+ const editor = store.textEditor+ if (!editor) return+ const range = editor.getSelectionRange()+ let runs = node.styleRuns+ if (range) {+ runs = adjustRunsForDelete(runs, range[0], range[1] - range[0])+ } else if (forward && editor.state && editor.state.cursor < node.text.length) {+ runs = adjustRunsForDelete(runs, editor.state.cursor, 1)+ } else if (!forward && editor.state && editor.state.cursor > 0) {+ runs = adjustRunsForDelete(runs, editor.state.cursor - 1, 1)+ }+ if (forward) {+ editor.delete(node)+ } else {+ editor.backspace(node)+ }+ syncText(node.id, editor.state?.text ?? '', runs)+ }++ return { getEditingNode, insertText, deleteText }+}diff --git a/packages/vue/src/canvas/text-edit/formatting.ts b/packages/vue/src/canvas/text-edit/formatting.tsnew file mode 100644index 000000000..6ed36c0a0--- /dev/null+++ b/packages/vue/src/canvas/text-edit/formatting.ts@@ -0,0 +1,75 @@+import {+ toggleBoldInRange,+ toggleDecorationInRange,+ toggleItalicInRange+} from '@open-pencil/core/text'++import type { Editor } from '@open-pencil/core/editor'+import type { SceneNode } from '@open-pencil/core/scene-graph'++export function createTextFormattingActions(store: Editor) {+ function applyFormatting(nodeId: string, changes: Partial<SceneNode>, label: string) {+ store.updateNodeWithUndo(nodeId, changes, label)+ const updated = store.graph.getNode(nodeId)+ if (updated) store.textEditor?.rebuildParagraph(updated)+ store.requestRender()+ }++ function toggleBold(node: SceneNode) {+ const editor = store.textEditor+ const range = editor?.getSelectionRange()+ if (range) {+ const { runs } = toggleBoldInRange(+ node.styleRuns,+ range[0],+ range[1],+ node.fontWeight,+ node.text.length+ )+ applyFormatting(node.id, { styleRuns: runs }, 'Toggle bold')+ } else {+ applyFormatting(node.id, { fontWeight: node.fontWeight >= 700 ? 400 : 700 }, 'Toggle bold')+ }+ }++ function toggleItalic(node: SceneNode) {+ const editor = store.textEditor+ const range = editor?.getSelectionRange()+ if (range) {+ const { runs } = toggleItalicInRange(+ node.styleRuns,+ range[0],+ range[1],+ node.italic,+ node.text.length+ )+ applyFormatting(node.id, { styleRuns: runs }, 'Toggle italic')+ } else {+ applyFormatting(node.id, { italic: !node.italic }, 'Toggle italic')+ }+ }++ function toggleUnderline(node: SceneNode) {+ const editor = store.textEditor+ const range = editor?.getSelectionRange()+ if (range) {+ const { runs } = toggleDecorationInRange(+ node.styleRuns,+ range[0],+ range[1],+ 'UNDERLINE',+ node.textDecoration,+ node.text.length+ )+ applyFormatting(node.id, { styleRuns: runs }, 'Toggle underline')+ } else {+ applyFormatting(+ node.id,+ { textDecoration: node.textDecoration === 'UNDERLINE' ? 'NONE' : 'UNDERLINE' },+ 'Toggle underline'+ )+ }+ }++ return { toggleBold, toggleItalic, toggleUnderline }+}diff --git a/packages/vue/src/canvas/text-edit/input.ts b/packages/vue/src/canvas/text-edit/input.tsnew file mode 100644index 000000000..30c3b2063--- /dev/null+++ b/packages/vue/src/canvas/text-edit/input.ts@@ -0,0 +1,127 @@+import type { DragState } from '#vue/shared/input/types'+import type { SceneNode } from '@open-pencil/core/scene-graph'+import type { Editor } from '@open-pencil/core/editor'++type NodeEditMethods = Partial<{ enterNodeEditMode: (nodeId: string) => void }>+type GetCoords = (e: MouseEvent) => { cx: number; cy: number }+type HitTest = (cx: number, cy: number, deep: boolean) => SceneNode | null+type SetDrag = (drag: DragState) => void++type TextEditInputOptions = {+ editor: Editor+ getCoords: GetCoords+ hitTestInScope: HitTest+ hitTestSectionTitle: (cx: number, cy: number) => SceneNode | null+ hitTestComponentLabel: (cx: number, cy: number) => SceneNode | null+ getClickCount: () => number+ setDrag: SetDrag+}++export function createTextEditInput(options: TextEditInputOptions) {+ const {+ editor,+ getCoords,+ hitTestInScope,+ hitTestSectionTitle,+ hitTestComponentLabel,+ getClickCount,+ setDrag+ } = options++ function handleTextEditClick(cx: number, cy: number, shiftKey: boolean): boolean {+ const textEd = editor.textEditor+ const editNode = editor.state.editingTextId+ ? editor.graph.getNode(editor.state.editingTextId)+ : null+ if (!textEd || !editNode) {+ editor.commitTextEdit()+ return false+ }+ const abs = editor.graph.getAbsolutePosition(editNode.id)+ const localX = cx - abs.x+ const localY = cy - abs.y+ if (localX < 0 || localY < 0 || localX > editNode.width || localY > editNode.height) {+ editor.commitTextEdit()+ return false+ }+ if (getClickCount() >= 3) {+ textEd.selectAll()+ } else if (getClickCount() === 2) {+ textEd.selectWordAt(localX, localY)+ } else {+ textEd.setCursorAt(localX, localY, shiftKey)+ setDrag({ type: 'text-select', startX: cx, startY: cy })+ }+ editor.requestRender()+ return true+ }++ function startTextEditingAt(hit: SceneNode, cx: number, cy: number) {+ editor.select([hit.id])+ editor.startTextEditing(hit.id)+ const textEd = editor.textEditor+ if (textEd) {+ const abs = editor.graph.getAbsolutePosition(hit.id)+ textEd.selectWordAt(cx - abs.x, cy - abs.y)+ editor.requestRender()+ }+ }++ function getContainerDescendantHit(+ containerId: string,+ cx: number,+ cy: number+ ): SceneNode | null {+ const hit = editor.graph.hitTestDeep(cx, cy, editor.state.currentPageId)+ if (!hit) return null+ if (hit.id === containerId || editor.graph.isDescendant(hit.id, containerId)) return hit+ return null+ }++ function onDblClick(e: MouseEvent) {+ const nodeEditEditor = editor as Editor & NodeEditMethods+ if (editor.state.editingTextId) return++ const { cx, cy } = getCoords(e)++ const selectedId =+ editor.state.selectedIds.size === 1 ? [...editor.state.selectedIds][0] : undefined+ const selectedNode = selectedId ? editor.graph.getNode(selectedId) : undefined+ const canEnter =+ selectedNode && selectedId && editor.graph.isContainer(selectedId) && !selectedNode.locked++ if (canEnter) {+ const useDeep = selectedNode.type === 'COMPONENT' || selectedNode.type === 'INSTANCE'+ const hit = useDeep+ ? getContainerDescendantHit(selectedId, cx, cy)+ : hitTestInScope(cx, cy, false)+ editor.enterContainer(selectedId)+ if (hit?.type === 'TEXT') {+ startTextEditingAt(hit, cx, cy)+ } else if (hit) {+ editor.select([hit.id])+ } else {+ editor.clearSelection()+ }+ return+ }++ const hit =+ hitTestSectionTitle(cx, cy) ?? hitTestComponentLabel(cx, cy) ?? hitTestInScope(cx, cy, true)+ if (!hit) return++ if (hit.type === 'TEXT') {+ startTextEditingAt(hit, cx, cy)+ return+ }++ if (hit.type === 'VECTOR') {+ nodeEditEditor.enterNodeEditMode?.(hit.id)+ return+ }++ editor.select([hit.id])+ }++ return { handleTextEditClick, onDblClick }+}diff --git a/packages/vue/src/canvas/text-edit/keyboard.ts b/packages/vue/src/canvas/text-edit/keyboard.tsnew file mode 100644index 000000000..15ecc4cba--- /dev/null+++ b/packages/vue/src/canvas/text-edit/keyboard.ts@@ -0,0 +1,74 @@+import { extendSelectionForDeletion, handleNavigationKey } from './navigation'++import type { SceneNode } from '@open-pencil/core/scene-graph'+import type { Editor } from '@open-pencil/core/editor'++type TextKeyboardOptions = {+ store: Editor+ canvasRef: { value: HTMLCanvasElement | null }+ getEditingNode: () => SceneNode | null+ isComposing: () => boolean+ insertText: (text: string, node: SceneNode) => void+ deleteText: (node: SceneNode, forward: boolean) => void+ resetBlink: () => void+ handleCopy: () => void+ handleCut: (node: SceneNode) => void+ handlePaste: (node: SceneNode) => Promise<void>+ toggleBold: (node: SceneNode) => void+ toggleItalic: (node: SceneNode) => void+ toggleUnderline: (node: SceneNode) => void+}++export function createTextKeyDownHandler(options: TextKeyboardOptions) {+ type MetaAction = (node: SceneNode) => void+ const metaKeyActions: Partial<Record<string, MetaAction>> = {+ KeyA: () => options.store.textEditor?.selectAll(),+ KeyC: () => options.handleCopy(),+ KeyX: (node) => options.handleCut(node),+ KeyV: (node) => void options.handlePaste(node),+ KeyB: (node) => options.toggleBold(node),+ KeyI: (node) => options.toggleItalic(node),+ KeyU: (node) => options.toggleUnderline(node)+ }++ function handleMetaKey(e: KeyboardEvent, node: SceneNode) {+ const action = metaKeyActions[e.code]+ if (!action) return false+ action(node)+ e.preventDefault()+ return true+ }++ return function onKeyDown(e: KeyboardEvent) {+ if (options.isComposing()) return+ const editor = options.store.textEditor+ const node = options.getEditingNode()+ if (!editor || !node) return++ const isMeta = e.metaKey || e.ctrlKey+ let textChanged = false++ if (e.code === 'Escape') {+ options.store.commitTextEdit()+ options.canvasRef.value?.focus()+ e.preventDefault()+ return+ }++ if (e.code === 'Enter') {+ options.insertText('\n', node)+ textChanged = true+ } else if (e.code === 'Backspace' || e.code === 'Delete') {+ extendSelectionForDeletion(e, editor)+ options.deleteText(node, e.code === 'Delete')+ textChanged = true+ } else if (!handleNavigationKey(e, editor)) {+ if (!isMeta || !handleMetaKey(e, node)) return+ return+ }++ if (!textChanged) options.store.requestRender()+ options.resetBlink()+ e.preventDefault()+ }+}diff --git a/packages/vue/src/canvas/text-edit/navigation.ts b/packages/vue/src/canvas/text-edit/navigation.tsnew file mode 100644index 000000000..54d1a4ed3--- /dev/null+++ b/packages/vue/src/canvas/text-edit/navigation.ts@@ -0,0 +1,52 @@+import type { Editor } from '@open-pencil/core/editor'++type TextEditor = NonNullable<Editor['textEditor']>++function handleHorizontalArrow(event: KeyboardEvent, editor: TextEditor) {+ const select = event.shiftKey+ const isMeta = event.metaKey || event.ctrlKey+ if (event.code === 'ArrowLeft') {+ if (isMeta) editor.moveToLineStart(select)+ else if (event.altKey) editor.moveWordLeft(select)+ else editor.moveLeft(select)+ } else if (event.code === 'ArrowRight') {+ if (isMeta) editor.moveToLineEnd(select)+ else if (event.altKey) editor.moveWordRight(select)+ else editor.moveRight(select)+ }+}++export function extendSelectionForDeletion(event: KeyboardEvent, editor: TextEditor) {+ const isMeta = event.metaKey || event.ctrlKey+ const forward = event.code === 'Delete'+ if (forward) {+ if (isMeta) editor.moveToLineEnd(true)+ else if (event.altKey) editor.moveWordRight(true)+ } else {+ if (isMeta) editor.moveToLineStart(true)+ else if (event.altKey) editor.moveWordLeft(true)+ }+}++export function handleNavigationKey(event: KeyboardEvent, editor: TextEditor) {+ switch (event.code) {+ case 'ArrowLeft':+ case 'ArrowRight':+ handleHorizontalArrow(event, editor)+ return true+ case 'ArrowUp':+ editor.moveUp(event.shiftKey)+ return true+ case 'ArrowDown':+ editor.moveDown(event.shiftKey)+ return true+ case 'Home':+ editor.moveToLineStart(event.shiftKey)+ return true+ case 'End':+ editor.moveToLineEnd(event.shiftKey)+ return true+ default:+ return false+ }+}diff --git a/packages/vue/src/canvas/text-edit/textarea.ts b/packages/vue/src/canvas/text-edit/textarea.tsnew file mode 100644index 000000000..ae8fceaf7--- /dev/null+++ b/packages/vue/src/canvas/text-edit/textarea.ts@@ -0,0 +1,55 @@+import { watch } from 'vue'++import type { Editor } from '@open-pencil/core/editor'+import type { ShallowRef } from 'vue'++export function createHiddenTextArea() {+ const textarea = document.createElement('textarea')+ textarea.setAttribute('aria-hidden', 'true')+ textarea.tabIndex = -1+ textarea.className = 'fixed left-0 top-0 h-px w-px opacity-0'+ document.body.appendChild(textarea)+ return textarea+}++export function focusTextAreaOnCanvasPointerDown(+ textareaRef: ShallowRef<HTMLTextAreaElement | null>,+ store: Editor+) {+ if (store.state.editingTextId && textareaRef.value) {+ requestAnimationFrame(() => textareaRef.value?.focus())+ }+}++export function useTextEditingSession({+ store,+ textareaRef,+ resetBlink,+ stopBlink,+ resetComposition+}: {+ store: Editor+ textareaRef: ShallowRef<HTMLTextAreaElement | null>+ resetBlink: () => void+ stopBlink: () => void+ resetComposition: () => void+}) {+ watch(+ () => store.state.editingTextId,+ (id, _, onCleanup) => {+ if (id) {+ const el = createHiddenTextArea()+ textareaRef.value = el+ el.focus()+ resetBlink()++ onCleanup(() => {+ stopBlink()+ el.remove()+ textareaRef.value = null+ resetComposition()+ })+ }+ }+ )+}diff --git a/packages/vue/src/canvas/text-edit/use.ts b/packages/vue/src/canvas/text-edit/use.tsnew file mode 100644index 000000000..bd02ca256--- /dev/null+++ b/packages/vue/src/canvas/text-edit/use.ts@@ -0,0 +1,63 @@+import { useEventListener } from '@vueuse/core'+import { shallowRef, type Ref } from 'vue'++import { createTextClipboardActions } from './clipboard'+import {+ createCaretBlink,+ createTextCompositionHandlers,+ createTextEditActions+} from './editing'+import { focusTextAreaOnCanvasPointerDown, useTextEditingSession } from './textarea'+import { createTextFormattingActions } from './formatting'+import { createTextKeyDownHandler } from './keyboard'++import type { Editor } from '@open-pencil/core/editor'++/**+ * Bridges DOM text input and the editor's canvas text-editing model.+ *+ * This composable manages textarea-backed input, IME composition, caret+ * blinking, keyboard editing behavior, text formatting shortcuts, and syncing+ * text/style-run updates back into the scene graph.+ */+export function useTextEdit(canvasRef: Ref<HTMLCanvasElement | null>, store: Editor) {+ const textareaRef = shallowRef<HTMLTextAreaElement | null>(null)+ const { resetBlink, stopBlink } = createCaretBlink(store)+ const { getEditingNode, insertText, deleteText } = createTextEditActions(store)+ const { toggleBold, toggleItalic, toggleUnderline } = createTextFormattingActions(store)++ const { handleCopy, handleCut, handlePaste } = createTextClipboardActions({+ store,+ insertText,+ deleteText,+ resetBlink+ })+ const { isComposing, onCompositionStart, onCompositionEnd, onInput, resetComposition } =+ createTextCompositionHandlers({ textareaRef, getEditingNode, insertText, resetBlink })++ const onKeyDown = createTextKeyDownHandler({+ store,+ canvasRef,+ getEditingNode,+ isComposing,+ insertText,+ deleteText,+ resetBlink,+ handleCopy,+ handleCut,+ handlePaste,+ toggleBold,+ toggleItalic,+ toggleUnderline+ })++ useEventListener(textareaRef, 'input', onInput)+ useEventListener(textareaRef, 'compositionstart', onCompositionStart)+ useEventListener(textareaRef, 'compositionend', onCompositionEnd)+ useEventListener(textareaRef, 'keydown', onKeyDown)+ useEventListener(canvasRef, 'mousedown', () =>+ focusTextAreaOnCanvasPointerDown(textareaRef, store)+ )++ useTextEditingSession({ store, textareaRef, resetBlink, stopBlink, resetComposition })+}diff --git a/packages/vue/src/canvas/tool-input/index.ts b/packages/vue/src/canvas/tool-input/index.tsnew file mode 100644index 000000000..b05b352fb--- /dev/null+++ b/packages/vue/src/canvas/tool-input/index.ts@@ -0,0 +1 @@+export { handleToolMouseDown, startPanDrag } from './use'diff --git a/packages/vue/src/canvas/tool-input/use.ts b/packages/vue/src/canvas/tool-input/use.tsnew file mode 100644index 000000000..ca9164a9f--- /dev/null+++ b/packages/vue/src/canvas/tool-input/use.ts@@ -0,0 +1,68 @@+import { startPenInput } from '#vue/canvas/pen-input/use'+import { startShapeDraw, startTextTool } from '#vue/shared/input/draw'+import { startPanDrag } from '#vue/shared/input/pan'+import { handleSelectDown } from '#vue/shared/input/select'++import type { HitTestFns } from '#vue/shared/input/select'+import type { DragState } from '#vue/shared/input/types'+import type { Editor } from '@open-pencil/core/editor'+import type { Ref } from 'vue'++type ToolMouseDownOptions = {+ event: MouseEvent+ cx: number+ cy: number+ editor: Editor+ hitFns: HitTestFns+ cursorOverride: Ref<string | null>+ setDrag: (d: DragState) => void+ tryStartRotation: (cx: number, cy: number) => boolean+ handleTextEditClick: (cx: number, cy: number, shiftKey: boolean) => boolean+}++export { startPanDrag }++export function handleToolMouseDown({+ event,+ cx,+ cy,+ editor,+ hitFns,+ cursorOverride,+ setDrag,+ tryStartRotation,+ handleTextEditClick+}: ToolMouseDownOptions) {+ const tool = editor.state.activeTool++ if (event.button === 1 || tool === 'HAND') {+ startPanDrag(event, setDrag, editor)+ return+ }++ if (tool === 'SELECT') {+ handleSelectDown(+ event,+ cx,+ cy,+ editor,+ hitFns,+ tryStartRotation,+ handleTextEditClick,+ setDrag+ )+ return+ }++ if (tool === 'PEN') {+ startPenInput(event, cx, cy, editor, setDrag, cursorOverride)+ return+ }++ if (tool === 'TEXT') {+ startTextTool(cx, cy, editor)+ return+ }++ startShapeDraw(cx, cy, editor, setDrag)+}diff --git a/packages/vue/src/canvas/transform-input/actions.ts b/packages/vue/src/canvas/transform-input/actions.tsnew file mode 100644index 000000000..5c09af862--- /dev/null+++ b/packages/vue/src/canvas/transform-input/actions.ts@@ -0,0 +1,47 @@+import { handleMarqueeMove as handleMarqueeMoveAction } from '#vue/canvas/transform-input/marquee'+import { handlePanMove as handlePanMoveAction } from '#vue/canvas/transform-input/pan'+import {+ handleRotateMove as handleRotateMoveAction,+ tryStartRotation as tryStartRotationAction+} from '#vue/canvas/transform-input/rotation'+import { handleTextSelectMove as handleTextSelectMoveAction } from '#vue/canvas/transform-input/text-selection'++import type { DragMarquee, DragPan, DragRotate, DragState } from '#vue/shared/input/types'+import type { Editor } from '@open-pencil/core/editor'++type CanvasToLocal = (cx: number, cy: number, scopeId: string) => { lx: number; ly: number }+type SetDrag = (drag: DragState) => void++export function createTransformInputActions(+ editor: Editor,+ canvasToLocal: CanvasToLocal,+ setDrag: SetDrag+) {+ function tryStartRotation(cx: number, cy: number): boolean {+ return tryStartRotationAction(editor, setDrag, cx, cy)+ }++ function handlePanMove(d: DragPan, e: MouseEvent) {+ handlePanMoveAction(editor, d, e)+ }++ function handleRotateMove(d: DragRotate, sx: number, sy: number, shiftKey: boolean) {+ handleRotateMoveAction(editor, d, sx, sy, shiftKey)+ }++ function handleTextSelectMove(cx: number, cy: number) {+ handleTextSelectMoveAction(editor, cx, cy)+ }++ function handleMarqueeMove(d: DragMarquee, cx: number, cy: number) {+ handleMarqueeMoveAction(editor, canvasToLocal, d, cx, cy)+ }++ return {+ tryStartRotation,+ handlePanMove,+ handleRotateMove,+ handleTextSelectMove,+ handleMarqueeMove+ }+}diff --git a/packages/vue/src/canvas/transform-input/marquee.ts b/packages/vue/src/canvas/transform-input/marquee.tsnew file mode 100644index 000000000..cf56f559c--- /dev/null+++ b/packages/vue/src/canvas/transform-input/marquee.ts@@ -0,0 +1,42 @@+import type { DragMarquee } from '#vue/shared/input/types'+import type { Editor } from '@open-pencil/core/editor'++type CanvasToLocal = (cx: number, cy: number, scopeId: string) => { lx: number; ly: number }++export function handleMarqueeMove(+ editor: Editor,+ canvasToLocal: CanvasToLocal,+ d: DragMarquee,+ cx: number,+ cy: number+) {+ const minX = Math.min(d.startX, cx)+ const minY = Math.min(d.startY, cy)+ const maxX = Math.max(d.startX, cx)+ const maxY = Math.max(d.startY, cy)++ const scopeId = editor.state.enteredContainerId+ const parentId = scopeId ?? editor.state.currentPageId+ const localMin = scopeId ? canvasToLocal(minX, minY, scopeId) : { lx: minX, ly: minY }+ const localMax = scopeId ? canvasToLocal(maxX, maxY, scopeId) : { lx: maxX, ly: maxY }+ const localMinX = Math.min(localMin.lx, localMax.lx)+ const localMinY = Math.min(localMin.ly, localMax.ly)+ const localMaxX = Math.max(localMin.lx, localMax.lx)+ const localMaxY = Math.max(localMin.ly, localMax.ly)++ const hits: string[] = []+ for (const node of editor.graph.getChildren(parentId)) {+ if (!node.visible || node.locked) continue+ if (+ node.x + node.width > localMinX &&+ node.x < localMaxX &&+ node.y + node.height > localMinY &&+ node.y < localMaxY+ ) {+ hits.push(node.id)+ }+ }++ editor.select(hits)+ editor.setMarquee({ x: minX, y: minY, width: maxX - minX, height: maxY - minY })+}diff --git a/packages/vue/src/canvas/transform-input/pan.ts b/packages/vue/src/canvas/transform-input/pan.tsnew file mode 100644index 000000000..420b1d461--- /dev/null+++ b/packages/vue/src/canvas/transform-input/pan.ts@@ -0,0 +1,10 @@+import type { DragPan } from '#vue/shared/input/types'+import type { Editor } from '@open-pencil/core/editor'++export function handlePanMove(editor: Editor, d: DragPan, event: MouseEvent) {+ const dx = event.clientX - d.startScreenX+ const dy = event.clientY - d.startScreenY+ editor.state.panX = d.startPanX + dx+ editor.state.panY = d.startPanY + dy+ editor.requestRepaint()+}diff --git a/packages/vue/src/canvas/transform-input/rotation.ts b/packages/vue/src/canvas/transform-input/rotation.tsnew file mode 100644index 000000000..d0b094316--- /dev/null+++ b/packages/vue/src/canvas/transform-input/rotation.ts@@ -0,0 +1,64 @@+import {+ hitTestCornerRotationByMatrix,+ hitTestTopRotationHandleByMatrix+} from '#vue/shared/input/geometry'++import { getAbsolutePositionFull } from '@open-pencil/core/canvas'+import { ROTATION_SNAP_DEGREES } from '@open-pencil/core/constants'++import type { DragRotate, DragState } from '#vue/shared/input/types'+import type { Editor } from '@open-pencil/core/editor'++type SetDrag = (drag: DragState) => void++function normalizeRotation(angle: number) {+ return ((((angle + 180) % 360) + 360) % 360) - 180+}++export function tryStartRotation(+ editor: Editor,+ setDrag: SetDrag,+ cx: number,+ cy: number+): boolean {+ if (editor.state.selectedIds.size !== 1) return false+ const id = [...editor.state.selectedIds][0]+ const node = editor.graph.getNode(id)+ if (!node || node.locked) return false++ const abs = getAbsolutePositionFull(node, editor.graph)++ const zoom = editor.renderer?.zoom ?? 1+ const hitsRotationHandle =+ hitTestTopRotationHandleByMatrix(cx, cy, node, editor.graph, zoom) ||+ hitTestCornerRotationByMatrix(cx, cy, node, editor.graph, zoom)+ if (!hitsRotationHandle) return false+ const startAngle = Math.atan2(cy - abs.centerY, cx - abs.centerX) * (180 / Math.PI)+ setDrag({+ type: 'rotate',+ nodeId: id,+ centerX: abs.centerX,+ centerY: abs.centerY,+ startAngle,+ origRotation: node.rotation+ })+ return true+}++export function handleRotateMove(+ editor: Editor,+ d: DragRotate,+ sx: number,+ sy: number,+ shiftKey: boolean+) {+ const currentAngle = Math.atan2(sy - d.centerY, sx - d.centerX) * (180 / Math.PI)+ const delta = normalizeRotation(currentAngle - d.startAngle)+ let rotation = d.origRotation + delta++ if (shiftKey) {+ rotation = Math.round(rotation / ROTATION_SNAP_DEGREES) * ROTATION_SNAP_DEGREES+ }++ editor.setRotationPreview({ nodeId: d.nodeId, angle: normalizeRotation(rotation) })+}diff --git a/packages/vue/src/canvas/transform-input/text-selection.ts b/packages/vue/src/canvas/transform-input/text-selection.tsnew file mode 100644index 000000000..1bb6baa1a--- /dev/null+++ b/packages/vue/src/canvas/transform-input/text-selection.ts@@ -0,0 +1,13 @@+import type { Editor } from '@open-pencil/core/editor'++export function handleTextSelectMove(editor: Editor, cx: number, cy: number) {+ const textEditor = editor.textEditor+ const editNode = editor.state.editingTextId+ ? editor.graph.getNode(editor.state.editingTextId)+ : null+ if (textEditor && editNode) {+ const abs = editor.graph.getAbsolutePosition(editNode.id)+ textEditor.setCursorAt(cx - abs.x, cy - abs.y, true)+ editor.requestRender()+ }+}diff --git a/packages/vue/src/canvas/transform-input/use.ts b/packages/vue/src/canvas/transform-input/use.tsnew file mode 100644index 000000000..2d90cba67--- /dev/null+++ b/packages/vue/src/canvas/transform-input/use.ts@@ -0,0 +1,15 @@+import { createTransformInputActions } from '#vue/canvas/transform-input/actions'++import type { DragState } from '#vue/shared/input/types'+import type { Editor } from '@open-pencil/core/editor'++type CanvasToLocal = (cx: number, cy: number, scopeId: string) => { lx: number; ly: number }+type SetDrag = (drag: DragState) => void++export function createCanvasTransformInput(+ editor: Editor,+ canvasToLocal: CanvasToLocal,+ setDrag: SetDrag+) {+ return createTransformInputActions(editor, canvasToLocal, setDrag)+}diff --git a/packages/vue/src/canvas/useCanvasInput.ts b/packages/vue/src/canvas/useCanvasInput.tsnew file mode 100644index 000000000..1da797681--- /dev/null+++ b/packages/vue/src/canvas/useCanvasInput.ts@@ -0,0 +1,220 @@+import {+ handleBendHandleMove,+ handleNodeEditMouseUp,+ updateNodeEditHover+} from '#vue/canvas/node-edit-input/use'+import { handlePenDragMove, updatePenHover } from '#vue/canvas/pen-input/use'+import { createCanvasPointer } from '#vue/canvas/pointer/use'+import { createTextEditInput } from '#vue/canvas/text-edit/input'+import { createCanvasTransformInput } from '#vue/canvas/transform-input/use'+import { handleToolMouseDown } from '#vue/canvas/tool-input/use'+import { createClickCounter } from '#vue/shared/input/click-count'+import { handleDrawMove, handleDrawUp } from '#vue/shared/input/draw'+import { useSpaceHeld } from '#vue/shared/input/space-key'+import { handleMoveMove, handleMoveUp } from '#vue/shared/input/move'+import { handleNodeEditMove } from '#vue/shared/input/node-edit'+import { setupPanZoom } from '#vue/shared/input/pan-zoom'+import { applyResize } from '#vue/shared/input/resize'+import { updateHoverCursor } from '#vue/shared/input/select'+import { useEventListener } from '@vueuse/core'+import { ref, type Ref } from 'vue'++import type { DragState } from '#vue/shared/input/types'+import type { SceneNode } from '@open-pencil/core/scene-graph'+import type { Editor } from '@open-pencil/core/editor'++/**+ * Wires pointer and mouse interaction to an OpenPencil canvas.+ *+ * This composable coordinates selection, dragging, resizing, rotation,+ * panning, drawing tools, scoped hit testing, and text-edit interaction.+ * It is primarily intended for editor shell components that own the canvas.+ */+export function useCanvasInput(+ canvasRef: Ref<HTMLCanvasElement | null>,+ editor: Editor,+ hitTestSectionTitle: (cx: number, cy: number) => SceneNode | null,+ hitTestComponentLabel: (cx: number, cy: number) => SceneNode | null,+ hitTestFrameTitle: (cx: number, cy: number) => SceneNode | null,+ onCursorMove?: (cx: number, cy: number) => void+) {+ const drag = ref<DragState | null>(null)+ const cursorOverride = ref<string | null>(null)+ const spaceHeld = useSpaceHeld()+ const { recordClick, getClickCount } = createClickCounter()++ const { getCoords, canvasToLocal, hitTestInScope, hitFns } = createCanvasPointer(+ canvasRef,+ editor,+ hitTestSectionTitle,+ hitTestComponentLabel,+ hitTestFrameTitle+ )++ function setDrag(d: DragState) {+ drag.value = d+ }++ const { handleTextEditClick, onDblClick } = createTextEditInput({+ editor,+ getCoords,+ hitTestInScope,+ hitTestSectionTitle,+ hitTestComponentLabel,+ getClickCount,+ setDrag+ })++ const {+ tryStartRotation,+ handlePanMove,+ handleRotateMove,+ handleTextSelectMove,+ handleMarqueeMove+ } = createCanvasTransformInput(editor, canvasToLocal, setDrag)++ function onMouseDown(e: MouseEvent) {+ if (!editor.state.editingTextId) canvasRef.value?.focus()+ editor.setHoveredNode(null)+ const { sx, sy, cx, cy } = getCoords(e)++ recordClick(sx, sy)+ handleToolMouseDown({+ event: e,+ cx,+ cy,+ editor,+ hitFns,+ cursorOverride,+ setDrag,+ tryStartRotation,+ handleTextEditClick+ })+ }++ function onMouseMove(e: MouseEvent) {+ if (onCursorMove) {+ const { cx, cy } = getCoords(e)+ onCursorMove(cx, cy)+ }++ if (!drag.value) {+ const { cx, cy } = getCoords(e)+ updatePenHover(cx, cy, editor)+ }++ if (!drag.value) {+ const { cx, cy } = getCoords(e)+ updateNodeEditHover(editor, cx, cy)+ }++ if (!drag.value && editor.state.activeTool === 'SELECT') {+ const { cx, cy } = getCoords(e)+ cursorOverride.value = updateHoverCursor(cx, cy, editor, hitFns)+ }++ if (!drag.value) return+ const d = drag.value++ if (d.type === 'pan') {+ handlePanMove(d, e)+ return+ }++ const { cx, cy } = getCoords(e)++ if (d.type === 'rotate') {+ handleRotateMove(d, cx, cy, e.shiftKey)+ return+ }+ if (d.type === 'move') {+ handleMoveMove(d, cx, cy, editor)+ return+ }+ if (d.type === 'text-select') {+ handleTextSelectMove(cx, cy)+ return+ }+ if (d.type === 'resize') {+ applyResize(d, cx, cy, e.shiftKey, editor)+ return+ }++ if (d.type === 'pen-drag') {+ handlePenDragMove(d, cx, cy, spaceHeld.value, e, editor)+ return+ }++ if (d.type === 'edit-node' || d.type === 'edit-handle') {+ handleNodeEditMove(d, cx, cy, editor, e.altKey, e.metaKey || e.ctrlKey, e.shiftKey)+ return+ }++ if (d.type === 'bend-handle') {+ handleBendHandleMove(d, cx, cy, e, editor)+ return+ }++ if (d.type === 'draw') {+ handleDrawMove(d, cx, cy, e.shiftKey, editor)+ return+ }++ handleMarqueeMove(d, cx, cy)+ }++ function onMouseUp() {+ if (!drag.value) return+ const d = drag.value++ if (handleNodeEditMouseUp(drag, editor)) return++ if (d.type === 'move') handleMoveUp(d, editor)+ else if (d.type === 'text-select') {+ drag.value = null+ return+ } else if (d.type === 'resize') editor.commitResize(d.nodeId, d.origRect)+ else if (d.type === 'pen-drag') {+ const penState = editor.state.penState as+ | (typeof editor.state.penState & {+ pendingClose?: boolean+ })+ | null+ if (penState?.pendingClose) {+ editor.penCommit(true)+ }+ drag.value = null+ return+ } else if (d.type === 'rotate') {+ const preview = editor.state.rotationPreview+ if (preview) {+ editor.updateNode(d.nodeId, { rotation: preview.angle })+ editor.commitRotation(d.nodeId, d.origRotation)+ }+ editor.setRotationPreview(null)+ } else if (d.type === 'draw') handleDrawUp(d, editor)+ else if (d.type === 'marquee') editor.setMarquee(null)++ drag.value = null+ cursorOverride.value = null+ }++ useEventListener(canvasRef, 'dblclick', onDblClick)+ useEventListener(canvasRef, 'mousedown', onMouseDown)+ useEventListener(canvasRef, 'mousemove', onMouseMove)+ useEventListener(canvasRef, 'mouseup', onMouseUp)+ useEventListener(canvasRef, 'mouseleave', () => {+ if (!drag.value) {+ editor.setHoveredNode(null)+ }+ })+ useEventListener(window, 'mouseup', () => {+ if (drag.value) onMouseUp()+ })++ setupPanZoom(canvasRef, editor, drag, onMouseDown, onMouseMove, onMouseUp)+ return {+ drag,+ cursorOverride+ }+}diff --git a/packages/vue/src/commands/useEditorCommands.ts b/packages/vue/src/commands/useEditorCommands.tsdeleted file mode 100644index 0c64597c1..000000000--- a/packages/vue/src/commands/useEditorCommands.ts+++ /dev/null@@ -1,298 +0,0 @@-import { useStore } from '@nanostores/vue'-import { computed } from 'vue'--import { useEditor } from '@open-pencil/vue/context/editorContext'-import { commandMessages } from '@open-pencil/vue/i18n'-import { usePageList } from '@open-pencil/vue/PageList/usePageList'-import { useSelectionCapabilities } from '@open-pencil/vue/selection/useSelectionCapabilities'-import { useSelectionState } from '@open-pencil/vue/selection/useSelectionState'--import type { Component, ComputedRef } from 'vue'--/**- * Stable command identifiers exposed by {@link useEditorCommands}.- */-export type EditorCommandId =- | 'edit.undo'- | 'edit.redo'- | 'selection.selectAll'- | 'selection.duplicate'- | 'selection.delete'- | 'selection.group'- | 'selection.ungroup'- | 'selection.createComponent'- | 'selection.createComponentSet'- | 'selection.createInstance'- | 'selection.detachInstance'- | 'selection.goToMainComponent'- | 'selection.wrapInAutoLayout'- | 'selection.bringToFront'- | 'selection.sendToBack'- | 'selection.toggleVisibility'- | 'selection.toggleLock'- | 'selection.moveToPage'- | 'view.zoom100'- | 'view.zoomFit'- | 'view.zoomSelection'--/**- * Reactive editor command descriptor.- */-export interface EditorCommand {- /** Stable command id. */- id: EditorCommandId- /** Human-readable label for UI. */- label: string- /** Whether the command can currently run. */- enabled: ComputedRef<boolean>- /** Executes the command. */- run: () => void-}--export interface EditorCommandMenuItem {- label: string- shortcut?: string- action?: () => void- disabled?: boolean- checked?: boolean- onCheckedChange?: (checked: boolean) => void- icon?: Component-}--export interface EditorCommandMenuSeparator {- separator: true-}--export type EditorCommandMenuEntry = EditorCommandMenuItem | EditorCommandMenuSeparator--/**- * Builds a command-oriented interface on top of the current editor.- *- * Use this composable when building menus, toolbars, keyboard handlers, or- * any other UI that should talk in terms of commands instead of raw editor- * method calls.- */-export function useEditorCommands() {- const editor = useEditor()- const selection = useSelectionState()- const capabilities = useSelectionCapabilities()- const { pages } = usePageList()-- const t = useStore(commandMessages)-- const commands: Record<EditorCommandId, EditorCommand> = {- 'edit.undo': {- id: 'edit.undo',- get label() {- return t.value.undo- },- enabled: capabilities.canUndo,- run: () => editor.undoAction()- },- 'edit.redo': {- id: 'edit.redo',- get label() {- return t.value.redo- },- enabled: capabilities.canRedo,- run: () => editor.redoAction()- },- 'selection.selectAll': {- id: 'selection.selectAll',- get label() {- return t.value.selectAll- },- enabled: capabilities.canSelectAll,- run: () => editor.selectAll()- },- 'selection.duplicate': {- id: 'selection.duplicate',- get label() {- return t.value.duplicate- },- enabled: capabilities.canDuplicate,- run: () => editor.duplicateSelected()- },- 'selection.delete': {- id: 'selection.delete',- get label() {- return t.value.delete- },- enabled: capabilities.canDelete,- run: () => editor.deleteSelected()- },- 'selection.group': {- id: 'selection.group',- get label() {- return t.value.group- },- enabled: capabilities.canGroup,- run: () => editor.groupSelected()- },- 'selection.ungroup': {- id: 'selection.ungroup',- get label() {- return t.value.ungroup- },- enabled: capabilities.canUngroup,- run: () => editor.ungroupSelected()- },- 'selection.createComponent': {- id: 'selection.createComponent',- get label() {- return t.value.createComponent- },- enabled: capabilities.canCreateComponent,- run: () => editor.createComponentFromSelection()- },- 'selection.createComponentSet': {- id: 'selection.createComponentSet',- get label() {- return t.value.createComponentSet- },- enabled: capabilities.canCreateComponentSet,- run: () => editor.createComponentSetFromComponents()- },- 'selection.createInstance': {- id: 'selection.createInstance',- get label() {- return t.value.createInstance- },- enabled: capabilities.canCreateInstance,- run: () => {- const node = selection.selectedNode.value- if (node?.type === 'COMPONENT') editor.createInstanceFromComponent(node.id)- }- },- 'selection.detachInstance': {- id: 'selection.detachInstance',- get label() {- return t.value.detachInstance- },- enabled: capabilities.canDetachInstance,- run: () => editor.detachInstance()- },- 'selection.goToMainComponent': {- id: 'selection.goToMainComponent',- get label() {- return t.value.goToMainComponent- },- enabled: capabilities.canGoToMainComponent,- run: () => editor.goToMainComponent()- },- 'selection.wrapInAutoLayout': {- id: 'selection.wrapInAutoLayout',- get label() {- return t.value.addAutoLayout- },- enabled: capabilities.canWrapInAutoLayout,- run: () => editor.wrapInAutoLayout()- },- 'selection.bringToFront': {- id: 'selection.bringToFront',- get label() {- return t.value.bringToFront- },- enabled: capabilities.canBringToFront,- run: () => editor.bringToFront()- },- 'selection.sendToBack': {- id: 'selection.sendToBack',- get label() {- return t.value.sendToBack- },- enabled: capabilities.canSendToBack,- run: () => editor.sendToBack()- },- 'selection.toggleVisibility': {- id: 'selection.toggleVisibility',- get label() {- return t.value.toggleVisibility- },- enabled: capabilities.canToggleVisibility,- run: () => editor.toggleVisibility()- },- 'selection.toggleLock': {- id: 'selection.toggleLock',- get label() {- return t.value.toggleLock- },- enabled: capabilities.canToggleLock,- run: () => editor.toggleLock()- },- 'selection.moveToPage': {- id: 'selection.moveToPage',- get label() {- return t.value.moveToPage- },- enabled: capabilities.canMoveToPage,- run: () => {- const targetPage = otherPages.value[0]- if (targetPage) moveSelectionToPage(targetPage.id)- }- },- 'view.zoom100': {- id: 'view.zoom100',- get label() {- return t.value.zoomTo100- },- enabled: computed(() => true),- run: () => editor.zoomTo100()- },- 'view.zoomFit': {- id: 'view.zoomFit',- get label() {- return t.value.zoomToFit- },- enabled: computed(() => true),- run: () => editor.zoomToFit()- },- 'view.zoomSelection': {- id: 'view.zoomSelection',- get label() {- return t.value.zoomToSelection- },- enabled: capabilities.canZoomToSelection,- run: () => editor.zoomToSelection()- }- }-- const otherPages = computed(() =>- pages.value.filter((page) => page.id !== editor.state.currentPageId)- )-- function getCommand(id: EditorCommandId) {- return commands[id]- }-- function runCommand(id: EditorCommandId) {- const command = commands[id]- if (command.enabled.value) command.run()- }-- function moveSelectionToPage(pageId: string) {- if (!capabilities.canMoveToPage.value) return- editor.moveToPage(pageId)- }-- function menuItem(id: EditorCommandId, shortcut?: string): EditorCommandMenuItem {- const command = getCommand(id)- return {- label: command.label,- shortcut,- get disabled() {- return !command.enabled.value- },- action: () => runCommand(id)- }- }-- return {- commands,- otherPages,- getCommand,- runCommand,- moveSelectionToPage,- menuItem- }-}diff --git a/packages/vue/src/commands/useMenuModel.ts b/packages/vue/src/commands/useMenuModel.tsdeleted file mode 100644index 8081bf44a..000000000--- a/packages/vue/src/commands/useMenuModel.ts+++ /dev/null@@ -1,129 +0,0 @@-import { useStore } from '@nanostores/vue'-import { computed } from 'vue'--import { useEditorCommands } from '@open-pencil/vue/commands/useEditorCommands'-import { useEditor } from '@open-pencil/vue/context/editorContext'-import { menuMessages } from '@open-pencil/vue/i18n'-import { useSelectionState } from '@open-pencil/vue/selection/useSelectionState'--/**- * Action entry used by menu models returned from {@link useMenuModel}.- */-export interface MenuActionNode {- separator?: false- label: string- shortcut?: string- action?: () => void- disabled?: boolean- checked?: boolean- onCheckedChange?: (checked: boolean) => void- sub?: MenuEntry[]-}--export interface MenuSeparatorNode {- separator: true-}--export type MenuEntry = MenuActionNode | MenuSeparatorNode--/**- * Returns ready-to-render menu models derived from the current editor state.- *- * This is a higher-level API than {@link useEditorCommands}: it groups- * commands into app and canvas menu structures and computes context-sensitive- * labels like Hide/Show and Lock/Unlock.- */-export function useMenuModel() {- const editor = useEditor()- const { menuItem: commandMenuItem, otherPages, moveSelectionToPage } = useEditorCommands()- const { hasSelection, isGroup, isInstance, isComponent, canCreateComponentSet } =- useSelectionState()-- const t = useStore(menuMessages)-- const editMenu = computed<MenuEntry[]>(() => [- commandMenuItem('edit.undo'),- commandMenuItem('edit.redo'),- { separator: true },- commandMenuItem('selection.duplicate'),- commandMenuItem('selection.delete'),- { separator: true },- commandMenuItem('selection.selectAll')- ])-- const viewMenu = computed<MenuEntry[]>(() => [- commandMenuItem('view.zoom100'),- commandMenuItem('view.zoomFit'),- commandMenuItem('view.zoomSelection')- ])-- const objectMenu = computed<MenuEntry[]>(() => [- commandMenuItem('selection.group'),- commandMenuItem('selection.ungroup'),- { separator: true },- commandMenuItem('selection.createComponent'),- commandMenuItem('selection.createComponentSet'),- commandMenuItem('selection.detachInstance'),- { separator: true },- commandMenuItem('selection.bringToFront'),- commandMenuItem('selection.sendToBack')- ])-- const arrangeMenu = computed<MenuEntry[]>(() => [commandMenuItem('selection.wrapInAutoLayout')])-- const appMenu = computed(() => [- { label: t.value.edit, items: editMenu.value },- { label: t.value.view, items: viewMenu.value },- { label: t.value.object, items: objectMenu.value },- { label: t.value.arrange, items: arrangeMenu.value }- ])-- const canvasMenu = computed<MenuEntry[]>(() => {- const moveToPageSubmenu: MenuEntry[] = otherPages.value.map((page) => ({- label: page.name,- action: () => moveSelectionToPage(page.id)- }))-- return [- commandMenuItem('selection.duplicate', '⌘D'),- commandMenuItem('selection.delete', '⌫'),- { separator: true },- ...(moveToPageSubmenu.length > 0 && hasSelection.value- ? [{ label: t.value.moveToPage, sub: moveToPageSubmenu } satisfies MenuActionNode]- : []),- commandMenuItem('selection.bringToFront', ']'),- commandMenuItem('selection.sendToBack', '['),- { separator: true },- commandMenuItem('selection.group', '⌘G'),- ...(isGroup.value ? [commandMenuItem('selection.ungroup', '⇧⌘G')] : []),- ...(hasSelection.value ? [commandMenuItem('selection.wrapInAutoLayout', '⇧A')] : []),- { separator: true },- ...(isComponent.value- ? [commandMenuItem('selection.createInstance')]- : [commandMenuItem('selection.createComponent', '⌥⌘K')]),- ...(canCreateComponentSet.value- ? [commandMenuItem('selection.createComponentSet', '⇧⌘K')]- : []),- ...(isInstance.value ? [commandMenuItem('selection.goToMainComponent')] : []),- ...(isInstance.value ? [commandMenuItem('selection.detachInstance', '⌥⌘B')] : []),- ...(hasSelection.value- ? [- { separator: true } as MenuSeparatorNode,- commandMenuItem('selection.toggleVisibility', '⇧⌘H'),- commandMenuItem('selection.toggleLock', '⇧⌘L')- ]- : [])- ]- })-- const selectionLabelMenu = computed(() => ({- visibility: (editor.getSelectedNode()?.visible ?? true) ? t.value.hide : t.value.show,- lock: (editor.getSelectedNode()?.locked ?? false) ? t.value.unlock : t.value.lock- }))-- return {- appMenu,- canvasMenu,- selectionLabelMenu- }-}diff --git a/packages/vue/src/controls/useAppearance.ts b/packages/vue/src/controls/appearance/helpers.tssimilarity index 69%rename from packages/vue/src/controls/useAppearance.tsrename to packages/vue/src/controls/appearance/helpers.tsindex 31ec2b4bd..b8d0556c5 100644--- a/packages/vue/src/controls/useAppearance.ts+++ b/packages/vue/src/controls/appearance/helpers.ts@@ -1,9 +1,9 @@+import { MIXED, type MixedValue } from '#vue/controls/node-props/use'import { computed } from 'vue'-import { useEditor } from '@open-pencil/vue/context/editorContext'-import { MIXED, useNodeProps } from '@open-pencil/vue/controls/useNodeProps'--import type { SceneNode } from '@open-pencil/core'+import type { Editor } from '@open-pencil/core/editor'+import type { SceneNode } from '@open-pencil/core/scene-graph'+import type { ComputedRef } from 'vue'const CORNER_RADIUS_TYPES = new Set(['RECTANGLE',@@ -13,16 +13,18 @@ const CORNER_RADIUS_TYPES = new Set(['INSTANCE'])-/**- * Returns appearance-related state and actions for the current selection.- *- * Use this composable for visibility, opacity, and corner-radius controls in- * property panels.- */-export function useAppearance() {- const editor = useEditor()- const { nodes, node, active, isMulti, merged, updateProp, commitProp } = useNodeProps()+type AppearanceStateOptions = {+ node: ComputedRef<SceneNode | null>+ nodes: ComputedRef<SceneNode[]>+ isMulti: ComputedRef<boolean>+ merged: <K extends keyof SceneNode>(key: K) => MixedValue<SceneNode[K]>+}+type AppearanceActionOptions = AppearanceStateOptions & {+ editor: Editor+}++export function createAppearanceState({ node, nodes, isMulti, merged }: AppearanceStateOptions) {const hasCornerRadius = computed(() => {if (isMulti.value) return nodes.value.every((n) => CORNER_RADIUS_TYPES.has(n.type))return node.value ? CORNER_RADIUS_TYPES.has(node.value.type) : false@@ -40,7 +42,7 @@ export function useAppearance() {const opacityPercent = computed(() => {const v = merged('opacity')- return v === MIXED ? MIXED : Math.round((v as number) * 100)+ return v === MIXED ? MIXED : Math.round(v * 100)})const visibilityState = computed<'visible' | 'hidden' | 'mixed'>(() => {@@ -49,6 +51,10 @@ export function useAppearance() {return v ? 'visible' : 'hidden'})+ return { hasCornerRadius, independentCorners, cornerRadiusValue, opacityPercent, visibilityState }+}++export function createAppearanceActions({ editor, node, nodes, isMulti }: AppearanceActionOptions) {function toggleVisibility() {if (isMulti.value) {const liveNodes = nodes.value@@ -56,11 +62,11 @@ export function useAppearance() {.filter((n): n is SceneNode => n != null)if (liveNodes.length === 0) returnconst allVisible = liveNodes.every((n) => n.visible)- editor.undo.beginBatch('Toggle visibility')- for (const n of liveNodes) {- editor.updateNodeWithUndo(n.id, { visible: !allVisible }, 'Toggle visibility')- }- editor.undo.commitBatch()+ editor.undo.runBatch('Toggle visibility', () => {+ for (const n of liveNodes) {+ editor.updateNodeWithUndo(n.id, { visible: !allVisible }, 'Toggle visibility')+ }+ })return}@@ -72,7 +78,9 @@ export function useAppearance() {}function toggleIndependentCorners() {- const targets = isMulti.value ? nodes.value : node.value ? [node.value] : []+ const selected = node.value+ const singleTarget = selected ? [selected] : []+ const targets = isMulti.value ? nodes.value : singleTargetfor (const n of targets) {if (n.independentCorners) {const uniform = n.topLeftRadius@@ -120,27 +128,11 @@ export function useAppearance() {}} else {const n = node.value- if (n)+ if (n) {editor.commitNodeUpdate(n.id, { [key]: previous } as Partial<SceneNode>, `Change ${key}`)+ }}}- return {- editor,- nodes,- node,- active,- isMulti,- hasCornerRadius,- independentCorners,- cornerRadiusValue,- opacityPercent,- visibilityState,- updateProp,- commitProp,- toggleVisibility,- toggleIndependentCorners,- updateCornerProp,- commitCornerProp- }+ return { toggleVisibility, toggleIndependentCorners, updateCornerProp, commitCornerProp }}diff --git a/packages/vue/src/controls/appearance/use.ts b/packages/vue/src/controls/appearance/use.tsnew file mode 100644index 000000000..2611370a1--- /dev/null+++ b/packages/vue/src/controls/appearance/use.ts@@ -0,0 +1,32 @@+import {+ createAppearanceActions,+ createAppearanceState+} from '#vue/controls/appearance/helpers'+import { useNodeProps } from '#vue/controls/node-props/use'+import { useEditor } from '#vue/editor/context'++/**+ * Returns appearance-related state and actions for the current selection.+ *+ * Use this composable for visibility, opacity, and corner-radius controls in+ * property panels.+ */+export function useAppearance() {+ const editor = useEditor()+ const { nodes, node, active, isMulti, merged, updateProp, commitProp } = useNodeProps()++ const appearanceState = createAppearanceState({ node, nodes, isMulti, merged })+ const appearanceActions = createAppearanceActions({ editor, node, nodes, isMulti, merged })++ return {+ editor,+ nodes,+ node,+ active,+ isMulti,+ ...appearanceState,+ updateProp,+ commitProp,+ ...appearanceActions+ }+}diff --git a/packages/vue/src/controls/useColorVariableBinding.ts b/packages/vue/src/controls/color-variable-binding/use.tssimilarity index 91%rename from packages/vue/src/controls/useColorVariableBinding.tsrename to packages/vue/src/controls/color-variable-binding/use.tsindex 27071e893..7e72dbc7e 100644--- a/packages/vue/src/controls/useColorVariableBinding.ts+++ b/packages/vue/src/controls/color-variable-binding/use.ts@@ -1,9 +1,8 @@+import { useEditor } from '#vue/editor/context'import { useFilter } from 'reka-ui'import { computed, ref } from 'vue'-import { useEditor } from '@open-pencil/vue/context/editorContext'--import type { Variable } from '@open-pencil/core'+import type { Variable } from '@open-pencil/core/scene-graph'type ColorBindingKind = 'fills' | 'strokes'diff --git a/packages/vue/src/controls/useEffectsControls.ts b/packages/vue/src/controls/effects/helpers.tssimilarity index 65%rename from packages/vue/src/controls/useEffectsControls.tsrename to packages/vue/src/controls/effects/helpers.tsindex 75f483ffe..094a052ff 100644--- a/packages/vue/src/controls/useEffectsControls.ts+++ b/packages/vue/src/controls/effects/helpers.ts@@ -1,8 +1,7 @@-import { ref } from 'vue'--import { useEditor } from '@open-pencil/vue/context/editorContext'--import type { Color, Effect, SceneNode } from '@open-pencil/core'+import type { Effect, SceneNode } from '@open-pencil/core/scene-graph'+import type { Color } from '@open-pencil/core/types'+import type { Editor } from '@open-pencil/core/editor'+import type { Ref } from 'vue'type EffectType = Effect['type']@@ -14,36 +13,25 @@ const EFFECT_LABELS: Record<string, string> = {FOREGROUND_BLUR: 'Foreground blur'}-const EFFECT_TYPES = Object.keys(EFFECT_LABELS) as EffectType[]--/**- * Returns effect-editing helpers for property panels.- *- * This composable manages default effect creation, expanded-row state,- * scrub-preview behavior, and effect type/color updates.- */-export function useEffectsControls() {- const editor = useEditor()-- const expandedIndex = ref<number | null>(null)- const effectsBeforeScrub = ref<Effect[] | null>(null)- const effectOptions = EFFECT_TYPES.map((t) => ({ value: t, label: EFFECT_LABELS[t] }))+export const EFFECT_TYPES = Object.keys(EFFECT_LABELS) as EffectType[]+export const EFFECT_OPTIONS = EFFECT_TYPES.map((t) => ({ value: t, label: EFFECT_LABELS[t] }))- function isShadow(type: string) {- return type === 'DROP_SHADOW' || type === 'INNER_SHADOW'- }+export function isShadow(type: string) {+ return type === 'DROP_SHADOW' || type === 'INNER_SHADOW'+}- function createDefaultEffect(): Effect {- return {- type: 'DROP_SHADOW',- color: { r: 0, g: 0, b: 0, a: 0.25 },- offset: { x: 0, y: 4 },- radius: 4,- spread: 0,- visible: true- }+export function createDefaultEffect(): Effect {+ return {+ type: 'DROP_SHADOW',+ color: { r: 0, g: 0, b: 0, a: 0.25 },+ offset: { x: 0, y: 4 },+ radius: 4,+ spread: 0,+ visible: true}+}+export function createEffectEditActions(editor: Editor, effectsBeforeScrub: Ref<Effect[] | null>) {function scrubEffect(node: SceneNode | null, index: number, changes: Partial<Effect>) {if (!node) returnif (!effectsBeforeScrub.value) {@@ -72,6 +60,10 @@ export function useEffectsControls() {}}+ return { scrubEffect, commitEffect }+}++export function createEffectControlActions(expandedIndex: Ref<number | null>) {function updateType(patch: (index: number, changes: Partial<Effect>) => void,node: SceneNode | null,@@ -108,16 +100,5 @@ export function useEffectsControls() {expandedIndex.value = expandedIndex.value === index ? null : index}- return {- expandedIndex,- effectOptions,- createDefaultEffect,- isShadow,- scrubEffect,- commitEffect,- updateType,- updateColor,- handleRemove,- toggleExpand- }+ return { updateType, updateColor, handleRemove, toggleExpand }}diff --git a/packages/vue/src/controls/effects/use.ts b/packages/vue/src/controls/effects/use.tsnew file mode 100644index 000000000..939fd27ea--- /dev/null+++ b/packages/vue/src/controls/effects/use.ts@@ -0,0 +1,36 @@+import { useEditor } from '#vue/editor/context'+import { ref } from 'vue'++import {+ EFFECT_OPTIONS,+ createDefaultEffect,+ createEffectControlActions,+ createEffectEditActions,+ isShadow+} from '#vue/controls/effects/helpers'++import type { Effect } from '@open-pencil/core/scene-graph'++/**+ * Returns effect-editing helpers for property panels.+ *+ * This composable manages default effect creation, expanded-row state,+ * scrub-preview behavior, and effect type/color updates.+ */+export function useEffectsControls() {+ const editor = useEditor()++ const expandedIndex = ref<number | null>(null)+ const effectsBeforeScrub = ref<Effect[] | null>(null)+ const editActions = createEffectEditActions(editor, effectsBeforeScrub)+ const controlActions = createEffectControlActions(expandedIndex)++ return {+ expandedIndex,+ effectOptions: EFFECT_OPTIONS,+ createDefaultEffect,+ isShadow,+ ...editActions,+ ...controlActions+ }+}diff --git a/packages/vue/src/controls/useFillControls.ts b/packages/vue/src/controls/fill/use.tssimilarity index 69%rename from packages/vue/src/controls/useFillControls.tsrename to packages/vue/src/controls/fill/use.tsindex a5e3b814e..918312a3b 100644--- a/packages/vue/src/controls/useFillControls.ts+++ b/packages/vue/src/controls/fill/use.ts@@ -1,6 +1,6 @@-import { DEFAULT_SHAPE_FILL } from '@open-pencil/core'+import { useColorVariableBinding } from '#vue/controls/color-variable-binding/use'-import { useColorVariableBinding } from './useColorVariableBinding'+import { DEFAULT_SHAPE_FILL } from '@open-pencil/core/constants'/*** Returns fill-related panel helpers and a reusable default fill value.diff --git a/packages/vue/src/controls/useLayout.ts b/packages/vue/src/controls/layout/helpers.tssimilarity index 73%rename from packages/vue/src/controls/useLayout.tsrename to packages/vue/src/controls/layout/helpers.tsindex 06bdb0394..249aafe21 100644--- a/packages/vue/src/controls/useLayout.ts+++ b/packages/vue/src/controls/layout/helpers.ts@@ -1,20 +1,30 @@+import { useSceneComputed } from '#vue/internal/scene-computed/use'import { computed, ref } from 'vue'-import { useEditor } from '@open-pencil/vue/context/editorContext'-import { useI18n } from '@open-pencil/vue/i18n'-import { useSceneComputed } from '@open-pencil/vue/internal/useSceneComputed'-+import type { useI18n } from '#vue/i18n'import type {- SceneNode,- LayoutSizing,+ GridTrack,LayoutAlign,LayoutCounterAlign,- GridTrack-} from '@open-pencil/core'+ LayoutSizing,+ SceneNode+} from '@open-pencil/core/scene-graph'+import type { Editor } from '@open-pencil/core/editor'+import type { ComputedRef } from 'vue'++export type AlignCell = { primary: LayoutAlign; counter: LayoutCounterAlign }++type GridTrackProp = 'gridTemplateColumns' | 'gridTemplateRows'++type LayoutPanelStrings = {+ sizingFixed: string+ sizingHug: string+ sizingFill: string+}-type AlignCell = { primary: LayoutAlign; counter: LayoutCounterAlign }+type ValueRef<T> = { readonly value: T }-const ALIGN_HORIZONTAL: AlignCell[] = [+export const ALIGN_HORIZONTAL: AlignCell[] = [{ primary: 'MIN', counter: 'MIN' },{ primary: 'CENTER', counter: 'MIN' },{ primary: 'MAX', counter: 'MIN' },@@ -26,7 +36,7 @@ const ALIGN_HORIZONTAL: AlignCell[] = [{ primary: 'MAX', counter: 'MAX' }]-const ALIGN_VERTICAL: AlignCell[] = [+export const ALIGN_VERTICAL: AlignCell[] = [{ primary: 'MIN', counter: 'MIN' },{ primary: 'MIN', counter: 'CENTER' },{ primary: 'MIN', counter: 'MAX' },@@ -38,82 +48,66 @@ const ALIGN_VERTICAL: AlignCell[] = [{ primary: 'MAX', counter: 'MAX' }]-function createTrackSizingOptions(panels: ReturnType<typeof useI18n>['panels']['value']) {- return [- { value: 'FR' as const, label: panels.sizingFillFr },- { value: 'FIXED' as const, label: panels.sizingFixedPx },- { value: 'AUTO' as const, label: panels.auto }- ]-}--/**- * Returns layout-related state and actions for the current selection.- *- * Use this composable to build auto-layout and grid panels that need sizing,- * padding, alignment, and track editing behavior.- */-export function useLayout() {- const editor = useEditor()- const { panels } = useI18n()-+export function createLayoutSelectionState(+ editor: Editor,+ panels: ReturnType<typeof useI18n>['panels']+) {const node = useSceneComputed<SceneNode | null>(() => editor.getSelectedNode() ?? null)const layoutDirection = computed<SceneNode['layoutDirection']>(() => node.value?.layoutDirection ?? 'AUTO')+ const sizingState = createLayoutSizingState(editor, node, panels)+ const alignGrid = computed(() =>+ node.value?.layoutMode === 'VERTICAL' ? ALIGN_VERTICAL : ALIGN_HORIZONTAL+ )- const isInAutoLayout = computed(() => {- const n = node.value- if (!n?.parentId) return false- const parent = editor.getNode(n.parentId)- return parent ? parent.layoutMode !== 'NONE' : false- })+ return { node, layoutDirection, alignGrid, ...sizingState }+}- const isGrid = computed(() => node.value?.layoutMode === 'GRID')- const isFlex = computed(- () => node.value?.layoutMode === 'HORIZONTAL' || node.value?.layoutMode === 'VERTICAL'- )+export function createTrackSizingOptions(panels: ReturnType<typeof useI18n>['panels']['value']) {+ return [+ { value: 'FR' as const, label: panels.sizingFillFr },+ { value: 'FIXED' as const, label: panels.sizingFixedPx },+ { value: 'AUTO' as const, label: panels.auto }+ ]+}- const widthSizing = computed<LayoutSizing>(() => {- const n = node.value- if (!n) return 'FIXED'- if (isFlex.value)- return n.layoutMode === 'HORIZONTAL' ? n.primaryAxisSizing : n.counterAxisSizing- if (isInAutoLayout.value && n.layoutGrow > 0) return 'FILL'- return 'FIXED'- })+export function trackLabel(track: GridTrack): string {+ if (track.sizing === 'FR') return `${track.value}fr`+ if (track.sizing === 'FIXED') return `${track.value}px`+ return 'Auto'+}- const heightSizing = computed<LayoutSizing>(() => {- const n = node.value- if (!n) return 'FIXED'- if (isFlex.value) return n.layoutMode === 'VERTICAL' ? n.primaryAxisSizing : n.counterAxisSizing- if (isInAutoLayout.value && n.layoutAlignSelf === 'STRETCH') return 'FILL'- return 'FIXED'- })+export function createGridTrackActions(editor: Editor, node: ComputedRef<SceneNode | null>) {+ function updateGridTrack(prop: GridTrackProp, index: number, updates: Partial<GridTrack>) {+ if (!node.value) return+ const tracks = [...node.value[prop]]+ tracks[index] = { ...tracks[index], ...updates }+ editor.updateNodeWithUndo(node.value.id, { [prop]: tracks }, 'Change grid track')+ }- const widthSizingOptions = computed(() => {- const options: { value: LayoutSizing; label: string }[] = [- { value: 'FIXED', label: panels.value.sizingFixed }- ]- if (isFlex.value) options.push({ value: 'HUG', label: panels.value.sizingHug })- if (isInAutoLayout.value || isFlex.value)- options.push({ value: 'FILL', label: panels.value.sizingFill })- return options- })+ function addTrack(prop: GridTrackProp) {+ if (!node.value) return+ editor.updateNodeWithUndo(+ node.value.id,+ { [prop]: [...node.value[prop], { sizing: 'FR' as const, value: 1 }] },+ 'Add grid track'+ )+ }- const heightSizingOptions = computed(() => {- const options: { value: LayoutSizing; label: string }[] = [- { value: 'FIXED', label: panels.value.sizingFixed }- ]- if (isFlex.value) options.push({ value: 'HUG', label: panels.value.sizingHug })- if (isInAutoLayout.value || isFlex.value)- options.push({ value: 'FILL', label: panels.value.sizingFill })- return options- })+ function removeTrack(prop: GridTrackProp, index: number) {+ if (!node.value) return+ editor.updateNodeWithUndo(+ node.value.id,+ { [prop]: node.value[prop].filter((_: GridTrack, i: number) => i !== index) },+ 'Remove grid track'+ )+ }- const alignGrid = computed(() =>- node.value?.layoutMode === 'VERTICAL' ? ALIGN_VERTICAL : ALIGN_HORIZONTAL- )+ return { updateGridTrack, addTrack, removeTrack }+}+export function createPaddingActions(editor: Editor, node: ComputedRef<SceneNode | null>) {const showIndividualPadding = ref(false)const hasUniformPadding = computed(() => {@@ -126,17 +120,66 @@ export function useLayout() {)})+ function setUniformPadding(v: number) {+ if (!node.value) return+ editor.updateNode(node.value.id, {+ paddingTop: v,+ paddingRight: v,+ paddingBottom: v,+ paddingLeft: v+ })+ }++ function commitUniformPadding(_value: number, previous: number) {+ if (!node.value) return+ editor.commitNodeUpdate(+ node.value.id,+ {+ paddingTop: previous,+ paddingRight: previous,+ paddingBottom: previous,+ paddingLeft: previous+ } satisfies Partial<SceneNode>,+ 'Change padding'+ )+ }++ function toggleIndividualPadding() {+ showIndividualPadding.value = !showIndividualPadding.value+ }++ return {+ showIndividualPadding,+ hasUniformPadding,+ setUniformPadding,+ commitUniformPadding,+ toggleIndividualPadding+ }+}++export function createLayoutActions({+ editor,+ node,+ isFlex,+ isInAutoLayout+}: {+ editor: Editor+ node: ComputedRef<SceneNode | null>+ isFlex: ComputedRef<boolean>+ isInAutoLayout: ComputedRef<boolean>+}) {function updateProp(key: string, value: number | string) {if (node.value) editor.updateNode(node.value.id, { [key]: value })}function commitProp(key: string, _value: number | string, previous: number | string) {- if (node.value)+ if (node.value) {editor.commitNodeUpdate(node.value.id,{ [key]: previous } as Partial<SceneNode>,`Change ${key}`)+ }}function setWidthSizing(sizing: LayoutSizing) {@@ -159,30 +202,6 @@ export function useLayout() {}}- function setUniformPadding(v: number) {- if (!node.value) return- editor.updateNode(node.value.id, {- paddingTop: v,- paddingRight: v,- paddingBottom: v,- paddingLeft: v- })- }-- function commitUniformPadding(_value: number, previous: number) {- if (!node.value) return- editor.commitNodeUpdate(- node.value.id,- {- paddingTop: previous,- paddingRight: previous,- paddingBottom: previous,- paddingLeft: previous- } as unknown as Partial<SceneNode>,- 'Change padding'- )- }-function setAlignment(primary: LayoutAlign, counter: LayoutCounterAlign) {if (!node.value) returneditor.updateNodeWithUndo(@@ -201,72 +220,70 @@ export function useLayout() {)}- function updateGridTrack(- prop: 'gridTemplateColumns' | 'gridTemplateRows',- index: number,- updates: Partial<GridTrack>- ) {- if (!node.value) return- const tracks = [...node.value[prop]]- tracks[index] = { ...tracks[index], ...updates }- editor.updateNodeWithUndo(node.value.id, { [prop]: tracks }, 'Change grid track')+ return {+ updateProp,+ commitProp,+ setWidthSizing,+ setHeightSizing,+ setAlignment,+ setLayoutDirection}+}- function addTrack(prop: 'gridTemplateColumns' | 'gridTemplateRows') {- if (!node.value) return- editor.updateNodeWithUndo(- node.value.id,- { [prop]: [...node.value[prop], { sizing: 'FR' as const, value: 1 }] },- 'Add grid track'- )- }+export function createLayoutSizingState(+ editor: Editor,+ node: ComputedRef<SceneNode | null>,+ panels: ValueRef<LayoutPanelStrings>+) {+ const isInAutoLayout = computed(() => {+ const n = node.value+ if (!n?.parentId) return false+ const parent = editor.getNode(n.parentId)+ return parent ? parent.layoutMode !== 'NONE' : false+ })- function removeTrack(prop: 'gridTemplateColumns' | 'gridTemplateRows', index: number) {- if (!node.value) return- editor.updateNodeWithUndo(- node.value.id,- { [prop]: node.value[prop].filter((_: GridTrack, i: number) => i !== index) },- 'Remove grid track'- )- }+ const isGrid = computed(() => node.value?.layoutMode === 'GRID')+ const isFlex = computed(+ () => node.value?.layoutMode === 'HORIZONTAL' || node.value?.layoutMode === 'VERTICAL'+ )- function trackLabel(track: GridTrack): string {- if (track.sizing === 'FR') return `${track.value}fr`- if (track.sizing === 'FIXED') return `${track.value}px`- return 'Auto'- }+ const widthSizing = computed<LayoutSizing>(() => {+ const n = node.value+ if (!n) return 'FIXED'+ if (isFlex.value)+ return n.layoutMode === 'HORIZONTAL' ? n.primaryAxisSizing : n.counterAxisSizing+ if (isInAutoLayout.value && n.layoutGrow > 0) return 'FILL'+ return 'FIXED'+ })- function toggleIndividualPadding() {- showIndividualPadding.value = !showIndividualPadding.value+ const heightSizing = computed<LayoutSizing>(() => {+ const n = node.value+ if (!n) return 'FIXED'+ if (isFlex.value) return n.layoutMode === 'VERTICAL' ? n.primaryAxisSizing : n.counterAxisSizing+ if (isInAutoLayout.value && n.layoutAlignSelf === 'STRETCH') return 'FILL'+ return 'FIXED'+ })++ function sizingOptions() {+ const options: { value: LayoutSizing; label: string }[] = [+ { value: 'FIXED', label: panels.value.sizingFixed }+ ]+ if (isFlex.value) options.push({ value: 'HUG', label: panels.value.sizingHug })+ if (isInAutoLayout.value || isFlex.value)+ options.push({ value: 'FILL', label: panels.value.sizingFill })+ return options}+ const widthSizingOptions = computed(sizingOptions)+ const heightSizingOptions = computed(sizingOptions)+return {- editor,- node,- layoutDirection,isInAutoLayout,isGrid,isFlex,widthSizing,heightSizing,widthSizingOptions,- heightSizingOptions,- alignGrid,- showIndividualPadding,- hasUniformPadding,- trackSizingOptions: createTrackSizingOptions(panels.value),- updateProp,- commitProp,- setWidthSizing,- setHeightSizing,- setUniformPadding,- commitUniformPadding,- setAlignment,- setLayoutDirection,- updateGridTrack,- addTrack,- removeTrack,- trackLabel,- toggleIndividualPadding+ heightSizingOptions}}diff --git a/packages/vue/src/controls/layout/use.ts b/packages/vue/src/controls/layout/use.tsnew file mode 100644index 000000000..4deb84580--- /dev/null+++ b/packages/vue/src/controls/layout/use.ts@@ -0,0 +1,76 @@+import {+ createGridTrackActions,+ createLayoutActions,+ createLayoutSelectionState,+ createPaddingActions,+ createTrackSizingOptions,+ trackLabel+} from '#vue/controls/layout/helpers'+import { useEditor } from '#vue/editor/context'+import { useI18n } from '#vue/i18n'++/**+ * Returns layout-related state and actions for the current selection.+ *+ * Use this composable to build auto-layout and grid panels that need sizing,+ * padding, alignment, and track editing behavior.+ */+export function useLayout() {+ const editor = useEditor()+ const { panels } = useI18n()++ const {+ node,+ layoutDirection,+ alignGrid,+ isInAutoLayout,+ isGrid,+ isFlex,+ widthSizing,+ heightSizing,+ widthSizingOptions,+ heightSizingOptions+ } = createLayoutSelectionState(editor, panels)++ const {+ showIndividualPadding,+ hasUniformPadding,+ setUniformPadding,+ commitUniformPadding,+ toggleIndividualPadding+ } = createPaddingActions(editor, node)++ const layoutActions = createLayoutActions({ editor, node, isFlex, isInAutoLayout })++ const { updateGridTrack, addTrack, removeTrack } = createGridTrackActions(editor, node)++ return {+ editor,+ node,+ layoutDirection,+ isInAutoLayout,+ isGrid,+ isFlex,+ widthSizing,+ heightSizing,+ widthSizingOptions,+ heightSizingOptions,+ alignGrid,+ showIndividualPadding,+ hasUniformPadding,+ trackSizingOptions: createTrackSizingOptions(panels.value),+ updateProp: layoutActions.updateProp,+ commitProp: layoutActions.commitProp,+ setWidthSizing: layoutActions.setWidthSizing,+ setHeightSizing: layoutActions.setHeightSizing,+ setUniformPadding,+ commitUniformPadding,+ setAlignment: layoutActions.setAlignment,+ setLayoutDirection: layoutActions.setLayoutDirection,+ updateGridTrack,+ addTrack,+ removeTrack,+ trackLabel,+ toggleIndividualPadding+ }+}diff --git a/packages/vue/src/controls/useNodeProps.ts b/packages/vue/src/controls/node-props/helpers.tssimilarity index 59%rename from packages/vue/src/controls/useNodeProps.tsrename to packages/vue/src/controls/node-props/helpers.tsindex 69cb38c02..a2d0227bc 100644--- a/packages/vue/src/controls/useNodeProps.ts+++ b/packages/vue/src/controls/node-props/helpers.ts@@ -1,26 +1,58 @@+import { useSceneComputed } from '#vue/internal/scene-computed/use'import { computed } from 'vue'-import { useEditor } from '@open-pencil/vue/context/editorContext'-import { useSceneComputed } from '@open-pencil/vue/internal/useSceneComputed'+import type { ComputedRef } from 'vue'+import type { Effect, Fill, SceneNode, Stroke } from '@open-pencil/core/scene-graph'+import type { Editor } from '@open-pencil/core/editor'-import type { Effect, Fill, SceneNode, Stroke } from '@open-pencil/core'--/** Sentinel value returned when a property differs across multiple selected nodes. */export const MIXED = Symbol('mixed')--/** Property value that may either be concrete or mixed across the selection. */export type MixedValue<T> = T | typeof MIXED-type ArrayItem = Fill | Stroke | Effect | Record<string, unknown>+export type ArrayItem = Fill | Stroke | Effect | Record<string, unknown>++export function areArrayItemsEqual(a: ArrayItem, b: ArrayItem): boolean {+ if (a === b) return true+ const aKeys = Object.keys(a)+ const bKeys = Object.keys(b)+ if (aKeys.length !== bKeys.length) return false+ for (const key of aKeys) {+ const aValue = a[key as keyof typeof a]+ const bValue = b[key as keyof typeof b]+ if (Array.isArray(aValue) && Array.isArray(bValue)) {+ if (aValue.length !== bValue.length) return false+ for (let i = 0; i < aValue.length; i++) {+ const left = aValue[i]+ const right = bValue[i]+ if (+ typeof left === 'object' &&+ left != null &&+ typeof right === 'object' &&+ right != null+ ) {+ if (!areArrayItemsEqual(left as ArrayItem, right as ArrayItem)) return false+ } else if (left !== right) {+ return false+ }+ }+ continue+ }+ if (+ typeof aValue === 'object' &&+ aValue != null &&+ typeof bValue === 'object' &&+ bValue != null+ ) {+ if (!areArrayItemsEqual(aValue as ArrayItem, bValue as ArrayItem)) return false+ continue+ }+ if (aValue !== bValue) return false+ }+ return true+}++type ArrayPropKey = 'fills' | 'strokes' | 'effects'-/**- * Returns shared property-panel helpers for the current selection.- *- * This composable centralizes mixed-value detection, multi-selection updates,- * array-item editing, and commit semantics used by higher-level controls.- */-export function useNodeProps() {- const store = useEditor()+export function createNodePropSelectionState(store: Editor) {const node = useSceneComputed(() => {void store.state.sceneVersionreturn store.getSelectedNode() ?? null@@ -43,46 +75,6 @@ export function useNodeProps() {return first}- function areArrayItemsEqual(a: ArrayItem, b: ArrayItem): boolean {- if (a === b) return true- const aKeys = Object.keys(a)- const bKeys = Object.keys(b)- if (aKeys.length !== bKeys.length) return false- for (const key of aKeys) {- const aValue = a[key as keyof typeof a]- const bValue = b[key as keyof typeof b]- if (Array.isArray(aValue) && Array.isArray(bValue)) {- if (aValue.length !== bValue.length) return false- for (let i = 0; i < aValue.length; i++) {- const left = aValue[i]- const right = bValue[i]- if (- typeof left === 'object' &&- left != null &&- typeof right === 'object' &&- right != null- ) {- if (!areArrayItemsEqual(left as ArrayItem, right as ArrayItem)) return false- } else if (left !== right) {- return false- }- }- continue- }- if (- typeof aValue === 'object' &&- aValue != null &&- typeof bValue === 'object' &&- bValue != null- ) {- if (!areArrayItemsEqual(aValue as ArrayItem, bValue as ArrayItem)) return false- continue- }- if (aValue !== bValue) return false- }- return true- }-function prop<K extends keyof SceneNode>(key: K) {return computed(() => merged(key))}@@ -93,34 +85,40 @@ export function useNodeProps() {}}- function isArrayMixed(key: keyof SceneNode): boolean {- const all = nodes.value- if (all.length <= 1) return false- const first = all[0][key]- if (!Array.isArray(first)) return all.some((n) => n[key] !== first)- for (let i = 1; i < all.length; i++) {- const current = all[i][key]- if (!Array.isArray(current) || current.length !== first.length) return true- for (let j = 0; j < first.length; j++) {- const left = first[j]- const right = current[j]- if (- typeof left === 'object' &&- left != null &&- typeof right === 'object' &&- right != null- ) {- if (!areArrayItemsEqual(left as ArrayItem, right as ArrayItem)) return true- } else if (left !== right) {- return true- }+ return { node, nodes, isMulti, active, activeNode, merged, prop, updateAllWithUndo }+}++export function isNodeArrayMixed(nodes: SceneNode[], key: keyof SceneNode): boolean {+ if (nodes.length <= 1) return false+ const first = nodes[0][key]+ if (!Array.isArray(first)) return nodes.some((n) => n[key] !== first)+ for (let i = 1; i < nodes.length; i++) {+ const current = nodes[i][key]+ if (!Array.isArray(current) || current.length !== first.length) return true+ for (let j = 0; j < first.length; j++) {+ const left = first[j]+ const right = current[j]+ if (typeof left === 'object' && typeof right === 'object') {+ if (!areArrayItemsEqual(left as ArrayItem, right as ArrayItem)) return true+ } else if (left !== right) {+ return true}}- return false}+ return false+}- type ArrayPropKey = 'fills' | 'strokes' | 'effects'-+export function createNodePropArrayActions({+ store,+ nodes,+ activeNode,+ isMulti+}: {+ store: Editor+ nodes: ComputedRef<SceneNode[]>+ activeNode: ComputedRef<SceneNode | null>+ isMulti: ComputedRef<boolean>+}) {function targetNodes(): SceneNode[] {if (isMulti.value) return nodes.valuereturn activeNode.value ? [activeNode.value] : []@@ -163,6 +161,10 @@ export function useNodeProps() {}}+ return { targetNodes, updateArrayItem, removeArrayItem, toggleArrayVisibility }+}++export function createNodePropScrubActions(store: Editor) {const previousValues = new Map<string, Record<string, number | string>>()function storePreviousValues(key: string) {@@ -205,22 +207,5 @@ export function useNodeProps() {}}- return {- store,- node,- nodes,- isMulti,- active,- activeNode,- targetNodes,- prop,- merged,- updateAllWithUndo,- updateArrayItem,- removeArrayItem,- toggleArrayVisibility,- isArrayMixed,- updateProp,- commitProp- }+ return { updateProp, commitProp }}diff --git a/packages/vue/src/controls/node-props/use.ts b/packages/vue/src/controls/node-props/use.tsnew file mode 100644index 000000000..5a1037a97--- /dev/null+++ b/packages/vue/src/controls/node-props/use.ts@@ -0,0 +1,54 @@+import { useEditor } from '#vue/editor/context'+import {+ MIXED,+ createNodePropArrayActions,+ createNodePropScrubActions,+ createNodePropSelectionState,+ isNodeArrayMixed+} from '#vue/controls/node-props/helpers'++/** Sentinel value returned when a property differs across multiple selected nodes. */+export { MIXED }++/** Property value that may either be concrete or mixed across the selection. */+export type { MixedValue } from '#vue/controls/node-props/helpers'++/**+ * Returns shared property-panel helpers for the current selection.+ *+ * This composable centralizes mixed-value detection, multi-selection updates,+ * array-item editing, and commit semantics used by higher-level controls.+ */+export function useNodeProps() {+ const store = useEditor()+ const { node, nodes, isMulti, active, activeNode, prop, merged, updateAllWithUndo } =+ createNodePropSelectionState(store)++ function isArrayMixed(key: Parameters<typeof isNodeArrayMixed>[1]): boolean {+ return isNodeArrayMixed(nodes.value, key)+ }++ const { targetNodes, updateArrayItem, removeArrayItem, toggleArrayVisibility } =+ createNodePropArrayActions({ store, nodes, activeNode, isMulti })++ const { updateProp, commitProp } = createNodePropScrubActions(store)++ return {+ store,+ node,+ nodes,+ isMulti,+ active,+ activeNode,+ targetNodes,+ prop,+ merged,+ updateAllWithUndo,+ updateArrayItem,+ removeArrayItem,+ toggleArrayVisibility,+ isArrayMixed,+ updateProp,+ commitProp+ }+}diff --git a/packages/vue/src/controls/okhcl/helpers.ts b/packages/vue/src/controls/okhcl/helpers.tsnew file mode 100644index 000000000..53506612b--- /dev/null+++ b/packages/vue/src/controls/okhcl/helpers.ts@@ -0,0 +1,128 @@+import {+ getFillOkHCL,+ getStrokeOkHCL,+ resolveOkHCLForPreview,+ rgbaToOkHCL,+ setNodeFillOkHCL,+ setNodeStrokeOkHCL+} from '@open-pencil/core/color'++import type { ColorFieldFormat } from '#vue/primitives/ColorPicker/types'+import type { OkHCLColor } from '@open-pencil/core/color'+import type { SceneNode } from '@open-pencil/core/scene-graph'+import type { Editor } from '@open-pencil/core/editor'+import type { Ref } from 'vue'++type ColorKind = 'fill' | 'stroke'++function fieldKey(kind: ColorKind, nodeId: string, index: number) {+ return `${kind}:${nodeId}:${index}`+}++export function getFillOkHCLColor(node: SceneNode | null, index: number): OkHCLColor | null {+ return node ? (getFillOkHCL(node, index)?.color ?? null) : null+}++export function getStrokeOkHCLColor(node: SceneNode | null, index: number): OkHCLColor | null {+ return node ? (getStrokeOkHCL(node, index)?.color ?? null) : null+}++function fallbackFillOkHCL(node: SceneNode, index: number) {+ return getFillOkHCLColor(node, index) ?? rgbaToOkHCL(node.fills[index]?.color ?? { r: 0, g: 0, b: 0, a: 1 })+}++function fallbackStrokeOkHCL(node: SceneNode, index: number) {+ return getStrokeOkHCLColor(node, index) ?? rgbaToOkHCL(node.strokes[index]?.color ?? { r: 0, g: 0, b: 0, a: 1 })+}++export function createOkHCLActions(editor: Editor) {+ function ensureFillOkHCL(node: SceneNode, index: number) {+ editor.updateNodeWithUndo(+ node.id,+ setNodeFillOkHCL(node, index, fallbackFillOkHCL(node, index)),+ 'Update fill color model'+ )+ }++ function ensureStrokeOkHCL(node: SceneNode, index: number) {+ editor.updateNodeWithUndo(+ node.id,+ setNodeStrokeOkHCL(node, index, fallbackStrokeOkHCL(node, index)),+ 'Update stroke color model'+ )+ }++ function updateFillOkHCL(node: SceneNode, index: number, patch: Partial<OkHCLColor>) {+ const current = fallbackFillOkHCL(node, index)+ editor.updateNodeWithUndo(+ node.id,+ setNodeFillOkHCL(node, index, { ...current, ...patch }),+ 'Change fill OkHCL'+ )+ }++ function updateStrokeOkHCL(node: SceneNode, index: number, patch: Partial<OkHCLColor>) {+ const current = fallbackStrokeOkHCL(node, index)+ editor.updateNodeWithUndo(+ node.id,+ setNodeStrokeOkHCL(node, index, { ...current, ...patch }),+ 'Change stroke OkHCL'+ )+ }++ return { ensureFillOkHCL, ensureStrokeOkHCL, updateFillOkHCL, updateStrokeOkHCL }+}++export function createOkHCLPreviewHelpers(editor: Editor) {+ function getPreviewInfo(okhcl: OkHCLColor | null) {+ const documentColorSpace = editor.graph.documentColorSpace+ if (!okhcl) return { previewColorSpace: documentColorSpace, clipped: false }+ const resolved = resolveOkHCLForPreview(okhcl, { documentColorSpace })+ return { previewColorSpace: resolved.targetSpace, clipped: resolved.clipped }+ }++ function getFillPreviewInfo(node: SceneNode | null, index: number) {+ return getPreviewInfo(getFillOkHCLColor(node, index))+ }++ function getStrokePreviewInfo(node: SceneNode | null, index: number) {+ return getPreviewInfo(getStrokeOkHCLColor(node, index))+ }++ return { getFillPreviewInfo, getStrokePreviewInfo }+}++export function createOkHCLFieldFormats(+ fieldFormats: Ref<Map<string, ColorFieldFormat>>,+ ensureFillOkHCL: (node: SceneNode, index: number) => void,+ ensureStrokeOkHCL: (node: SceneNode, index: number) => void+) {+ function getFieldFormat(node: SceneNode | null, index: number, kind: ColorKind) {+ if (!node) return 'rgb' as const+ const key = fieldKey(kind, node.id, index)+ const stored = fieldFormats.value.get(key)+ if (stored) return stored+ return (kind === 'fill' ? getFillOkHCL(node, index) : getStrokeOkHCL(node, index))+ ? 'okhcl'+ : 'rgb'+ }++ function setFillFieldFormat(node: SceneNode, index: number, format: ColorFieldFormat) {+ fieldFormats.value.set(fieldKey('fill', node.id, index), format)+ if (format === 'okhcl') ensureFillOkHCL(node, index)+ }++ function setStrokeFieldFormat(node: SceneNode, index: number, format: ColorFieldFormat) {+ fieldFormats.value.set(fieldKey('stroke', node.id, index), format)+ if (format === 'okhcl') ensureStrokeOkHCL(node, index)+ }++ return { getFieldFormat, setFillFieldFormat, setStrokeFieldFormat }+}++export const OKHCL_FIELD_OPTIONS = [+ { value: 'rgb' as const, label: 'RGB' },+ { value: 'hsl' as const, label: 'HSL' },+ { value: 'hsb' as const, label: 'HSB' },+ { value: 'okhcl' as const, label: 'OkHCL' }+]diff --git a/packages/vue/src/controls/okhcl/use.ts b/packages/vue/src/controls/okhcl/use.tsnew file mode 100644index 000000000..8220b44ab--- /dev/null+++ b/packages/vue/src/controls/okhcl/use.ts@@ -0,0 +1,40 @@+import { useEditor } from '#vue/editor/context'+import { ref } from 'vue'++import {+ OKHCL_FIELD_OPTIONS,+ createOkHCLActions,+ createOkHCLFieldFormats,+ createOkHCLPreviewHelpers,+ getFillOkHCLColor,+ getStrokeOkHCLColor+} from '#vue/controls/okhcl/helpers'++import type { ColorFieldFormat } from '#vue/primitives/ColorPicker/types'++export function useOkHCL() {+ const editor = useEditor()+ const fieldFormats = ref(new Map<string, ColorFieldFormat>())++ const { ensureFillOkHCL, ensureStrokeOkHCL, updateFillOkHCL, updateStrokeOkHCL } =+ createOkHCLActions(editor)+ const { getFillPreviewInfo, getStrokePreviewInfo } = createOkHCLPreviewHelpers(editor)+ const { getFieldFormat, setFillFieldFormat, setStrokeFieldFormat } = createOkHCLFieldFormats(+ fieldFormats,+ ensureFillOkHCL,+ ensureStrokeOkHCL+ )++ return {+ getFillOkHCLColor,+ getStrokeOkHCLColor,+ getFillPreviewInfo,+ getStrokePreviewInfo,+ getFieldFormat,+ setFillFieldFormat,+ setStrokeFieldFormat,+ updateFillOkHCL,+ updateStrokeOkHCL,+ fieldOptions: OKHCL_FIELD_OPTIONS+ }+}diff --git a/packages/vue/src/controls/usePosition.ts b/packages/vue/src/controls/position/use.tssimilarity index 86%rename from packages/vue/src/controls/usePosition.tsrename to packages/vue/src/controls/position/use.tsindex 7662d2812..7914c870a 100644--- a/packages/vue/src/controls/usePosition.ts+++ b/packages/vue/src/controls/position/use.ts@@ -1,10 +1,9 @@+import { usePropScrub } from '#vue/controls/prop-scrub/use'+import { useEditor } from '#vue/editor/context'+import { useSceneComputed } from '#vue/internal/scene-computed/use'import { computed } from 'vue'-import { useEditor } from '@open-pencil/vue/context/editorContext'-import { usePropScrub } from '@open-pencil/vue/controls/usePropScrub'-import { useSceneComputed } from '@open-pencil/vue/internal/useSceneComputed'--import type { SceneNode } from '@open-pencil/core'+import type { SceneNode } from '@open-pencil/core/scene-graph'/*** Returns position-related state and actions for the current selection.diff --git a/packages/vue/src/controls/usePropScrub.ts b/packages/vue/src/controls/prop-scrub/use.tssimilarity index 84%rename from packages/vue/src/controls/usePropScrub.tsrename to packages/vue/src/controls/prop-scrub/use.tsindex f3dfdc432..339389328 100644--- a/packages/vue/src/controls/usePropScrub.ts+++ b/packages/vue/src/controls/prop-scrub/use.ts@@ -1,4 +1,5 @@-import type { Editor, SceneNode } from '@open-pencil/core'+import type { Editor } from '@open-pencil/core/editor'+import type { SceneNode } from '@open-pencil/core/scene-graph'export function usePropScrub(editor: Editor) {const previousValues = new Map<string, Record<string, number | string>>()@@ -39,8 +40,7 @@ export function usePropScrub(editor: Editor) {previousValues.clear()} else {const n = nodes[0]- if (n)- editor.commitNodeUpdate(n.id, { [key]: previous } as Partial<SceneNode>, `Change ${key}`)+ editor.commitNodeUpdate(n.id, { [key]: previous } as Partial<SceneNode>, `Change ${key}`)}}diff --git a/packages/vue/src/controls/stroke/helpers.ts b/packages/vue/src/controls/stroke/helpers.tsnew file mode 100644index 000000000..792cd8f85--- /dev/null+++ b/packages/vue/src/controls/stroke/helpers.ts@@ -0,0 +1,107 @@+import type { SceneNode, Stroke } from '@open-pencil/core/scene-graph'+import type { Editor } from '@open-pencil/core/editor'+import type { Ref } from 'vue'++export type StrokeSides = 'ALL' | 'TOP' | 'BOTTOM' | 'LEFT' | 'RIGHT' | 'CUSTOM'++export const SIDE_OPTIONS: { value: StrokeSides; label: string }[] = [+ { value: 'ALL', label: 'All' },+ { value: 'TOP', label: 'Top' },+ { value: 'BOTTOM', label: 'Bottom' },+ { value: 'LEFT', label: 'Left' },+ { value: 'RIGHT', label: 'Right' },+ { value: 'CUSTOM', label: 'Custom' }+]++export const BORDER_SIDES = ['top', 'right', 'bottom', 'left'] as const+export const DEFAULT_STROKE: Stroke = {+ color: { r: 0, g: 0, b: 0, a: 1 },+ weight: 1,+ opacity: 1,+ visible: true,+ align: 'CENTER'+}++export function updateAlign(editor: Editor, align: Stroke['align'], activeNode: SceneNode) {+ const strokes = activeNode.strokes.map((s) => ({ ...s, align }))+ editor.updateNodeWithUndo(activeNode.id, { strokes }, 'Change stroke align')+}++export function currentAlign(activeNode: SceneNode | null): Stroke['align'] {+ if (!activeNode || activeNode.strokes.length === 0) return 'CENTER'+ return activeNode.strokes[0].align+}++export function currentSides(activeNode: SceneNode | null): StrokeSides {+ if (!activeNode?.independentStrokeWeights) return 'ALL'+ const { borderTopWeight: t, borderRightWeight: r, borderBottomWeight: b, borderLeftWeight: l } = activeNode+ const active = [t > 0, r > 0, b > 0, l > 0]+ const count = active.filter(Boolean).length+ if (count === 4 && t === r && r === b && b === l) return 'ALL'+ if (count === 1) {+ if (t > 0) return 'TOP'+ if (b > 0) return 'BOTTOM'+ if (l > 0) return 'LEFT'+ if (r > 0) return 'RIGHT'+ }+ return 'CUSTOM'+}++export function createStrokeSideActions(editor: Editor, sideMenuOpen: Ref<boolean>) {+ function selectSide(side: StrokeSides, activeNode: SceneNode) {+ const weight = activeNode.strokes.length > 0 ? activeNode.strokes[0].weight : 1+ if (side === 'ALL') {+ editor.updateNodeWithUndo(+ activeNode.id,+ {+ independentStrokeWeights: false,+ borderTopWeight: 0,+ borderRightWeight: 0,+ borderBottomWeight: 0,+ borderLeftWeight: 0+ } as Partial<SceneNode>,+ 'Stroke all sides'+ )+ } else if (side === 'CUSTOM') {+ const w = activeNode.independentStrokeWeights+ ? {+ top: activeNode.borderTopWeight,+ right: activeNode.borderRightWeight,+ bottom: activeNode.borderBottomWeight,+ left: activeNode.borderLeftWeight+ }+ : { top: weight, right: weight, bottom: weight, left: weight }+ editor.updateNodeWithUndo(+ activeNode.id,+ {+ independentStrokeWeights: true,+ borderTopWeight: w.top,+ borderRightWeight: w.right,+ borderBottomWeight: w.bottom,+ borderLeftWeight: w.left+ } as Partial<SceneNode>,+ 'Custom stroke sides'+ )+ } else {+ editor.updateNodeWithUndo(+ activeNode.id,+ {+ independentStrokeWeights: true,+ borderTopWeight: side === 'TOP' ? weight : 0,+ borderRightWeight: side === 'RIGHT' ? weight : 0,+ borderBottomWeight: side === 'BOTTOM' ? weight : 0,+ borderLeftWeight: side === 'LEFT' ? weight : 0+ } as Partial<SceneNode>,+ `Stroke ${side.toLowerCase()} only`+ )+ }+ sideMenuOpen.value = false+ }++ function updateBorderWeight(side: (typeof BORDER_SIDES)[number], value: number, activeNode: SceneNode) {+ const key = `border${side[0].toUpperCase()}${side.slice(1)}Weight` as keyof SceneNode+ editor.updateNodeWithUndo(activeNode.id, { [key]: value } as Partial<SceneNode>, 'Change stroke weight')+ }++ return { selectSide, updateBorderWeight }+}diff --git a/packages/vue/src/controls/stroke/use.ts b/packages/vue/src/controls/stroke/use.tsnew file mode 100644index 000000000..d1e7f7d28--- /dev/null+++ b/packages/vue/src/controls/stroke/use.ts@@ -0,0 +1,44 @@+import { useEditor } from '#vue/editor/context'+import { useI18n } from '#vue/i18n'+import { ref } from 'vue'++import {+ BORDER_SIDES,+ DEFAULT_STROKE,+ SIDE_OPTIONS,+ createStrokeSideActions,+ currentAlign,+ currentSides,+ updateAlign+} from '#vue/controls/stroke/helpers'++/**+ * Returns stroke-related helpers for property panels.+ *+ * This composable provides alignment options, side presets, a default stroke,+ * and helpers for per-side border weight editing.+ */+export function useStrokeControls() {+ const store = useEditor()+ const { panels } = useI18n()+ const sideMenuOpen = ref(false)+ const alignOptions = [+ { value: 'INSIDE' as const, label: panels.value.strokeAlignInside },+ { value: 'CENTER' as const, label: panels.value.strokeAlignCenter },+ { value: 'OUTSIDE' as const, label: panels.value.strokeAlignOutside }+ ]+ const { selectSide, updateBorderWeight } = createStrokeSideActions(store, sideMenuOpen)++ return {+ alignOptions,+ sideOptions: SIDE_OPTIONS,+ borderSides: BORDER_SIDES,+ sideMenuOpen,+ defaultStroke: DEFAULT_STROKE,+ updateAlign: updateAlign.bind(null, store),+ currentAlign,+ currentSides,+ selectSide,+ updateBorderWeight+ }+}diff --git a/packages/vue/src/controls/useTypography.ts b/packages/vue/src/controls/typography/actions.tssimilarity index 77%rename from packages/vue/src/controls/useTypography.tsrename to packages/vue/src/controls/typography/actions.tsindex 0c0833f57..3719391e2 100644--- a/packages/vue/src/controls/useTypography.ts+++ b/packages/vue/src/controls/typography/actions.ts@@ -1,50 +1,31 @@+import { useSceneComputed } from '#vue/internal/scene-computed/use'+import { useNodeFontStatus } from '#vue/shared/font-status/use'import { computed } from 'vue'-import { FONT_WEIGHT_NAMES, weightToStyle } from '@open-pencil/core'-import { useEditor } from '@open-pencil/vue/context/editorContext'-import { useSceneComputed } from '@open-pencil/vue/internal/useSceneComputed'-import { useNodeFontStatus } from '@open-pencil/vue/shared/useFontStatus'+import { FONT_WEIGHT_NAMES, weightToStyle } from '@open-pencil/core/text'-import type { SceneNode, TextDecoration } from '@open-pencil/core'+import type { UseTypographyOptions } from '#vue/controls/typography/use'+import type { Editor } from '@open-pencil/core/editor'+import type { SceneNode, TextDecoration } from '@open-pencil/core/scene-graph'+import type { ComputedRef } from 'vue'type TextAlign = 'LEFT' | 'CENTER' | 'RIGHT'type TextDirection = SceneNode['textDirection']-const WEIGHTS = Object.entries(FONT_WEIGHT_NAMES).map(([value, label]) => ({+export const TYPOGRAPHY_WEIGHTS = Object.entries(FONT_WEIGHT_NAMES).map(([value, label]) => ({value: Number(value),label}))-/**- * Options for {@link useTypography}.- */-export interface UseTypographyOptions {- /**- * Optional font loader invoked before changing family or weight.- */- loadFont?: (family: string, style: string) => Promise<unknown>-}--/**- * Returns typography-related state and actions for the current text selection.- *- * This composable is designed for text property panels and formatting controls.- */-export function useTypography(options: UseTypographyOptions = {}) {- const editor = useEditor()-+export function createTypographyState(editor: Editor) {const node = useSceneComputed<SceneNode | null>(() => editor.getSelectedNode() ?? null)-const { missingFonts, hasMissingFonts } = useNodeFontStatus(() => node.value)-const fontFamily = computed(() => node.value?.fontFamily ?? '')const fontWeight = computed(() => node.value?.fontWeight ?? 400)const fontSize = computed(() => node.value?.fontSize ?? 16)-const currentWeightLabel = computed(() => FONT_WEIGHT_NAMES[node.value?.fontWeight ?? 400] ?? 'Regular')-const activeFormatting = computed(() => {const n = node.valueif (!n) return []@@ -56,6 +37,33 @@ export function useTypography(options: UseTypographyOptions = {}) {return result})+ return {+ node,+ fontFamily,+ fontWeight,+ fontSize,+ currentWeightLabel,+ activeFormatting,+ missingFonts,+ hasMissingFonts+ }+}++type TypographyActionOptions = {+ editor: Editor+ node: ComputedRef<SceneNode | null>+ currentWeightLabel: ComputedRef<string>+ activeFormatting: ComputedRef<string[]>+ options: UseTypographyOptions+}++export function createTypographyActions({+ editor,+ node,+ currentWeightLabel,+ activeFormatting,+ options+}: TypographyActionOptions) {async function doLoadFont(family: string, style: string) {if (options.loadFont) await options.loadFont(family, style)}@@ -68,9 +76,10 @@ export function useTypography(options: UseTypographyOptions = {}) {async function setWeight(weight: number) {if (!node.value) return+ const { id, fontFamily } = node.valueconst style = weightToStyle(weight)- await doLoadFont(node.value.fontFamily, style)- editor.updateNodeWithUndo(node.value.id, { fontWeight: weight }, 'Change font weight')+ editor.updateNodeWithUndo(id, { fontWeight: weight }, 'Change font weight')+ await doLoadFont(fontFamily, style)}function setAlign(align: TextAlign) {@@ -89,7 +98,7 @@ export function useTypography(options: UseTypographyOptions = {}) {function toggleBold() {if (!node.value) return- setWeight(node.value.fontWeight >= 700 ? 400 : 700)+ void setWeight(node.value.fontWeight >= 700 ? 400 : 700)}function toggleItalic() {@@ -135,16 +144,6 @@ export function useTypography(options: UseTypographyOptions = {}) {}return {- editor,- node,- fontFamily,- fontWeight,- fontSize,- weights: WEIGHTS,- currentWeightLabel,- activeFormatting,- missingFonts,- hasMissingFonts,setFamily,setWeight,setAlign,diff --git a/packages/vue/src/controls/typography/use.ts b/packages/vue/src/controls/typography/use.tsnew file mode 100644index 000000000..e94ee4593--- /dev/null+++ b/packages/vue/src/controls/typography/use.ts@@ -0,0 +1,34 @@+import {+ TYPOGRAPHY_WEIGHTS,+ createTypographyActions,+ createTypographyState+} from '#vue/controls/typography/actions'+import { useEditor } from '#vue/editor/context'++/**+ * Options for {@link useTypography}.+ */+export interface UseTypographyOptions {+ /**+ * Optional font loader invoked before changing family or weight.+ */+ loadFont?: (family: string, style: string) => Promise<unknown>+}++/**+ * Returns typography-related state and actions for the current text selection.+ *+ * This composable is designed for text property panels and formatting controls.+ */+export function useTypography(options: UseTypographyOptions = {}) {+ const editor = useEditor()+ const typographyState = createTypographyState(editor)+ const actions = createTypographyActions({ editor, ...typographyState, options })++ return {+ editor,+ ...typographyState,+ weights: TYPOGRAPHY_WEIGHTS,+ ...actions+ }+}diff --git a/packages/vue/src/controls/useUndoBatch.ts b/packages/vue/src/controls/undo-batch/use.tssimilarity index 50%rename from packages/vue/src/controls/useUndoBatch.tsrename to packages/vue/src/controls/undo-batch/use.tsindex c9aef9a66..631f47037 100644--- a/packages/vue/src/controls/useUndoBatch.ts+++ b/packages/vue/src/controls/undo-batch/use.ts@@ -1,35 +1,40 @@-import { onBeforeUnmount } from 'vue'+import { tryOnScopeDispose, useTimeoutFn } from '@vueuse/core'-import type { UndoManager } from '@open-pencil/core'+import type { UndoManager } from '@open-pencil/core/scene-graph'const BATCH_IDLE_MS = 300export function useUndoBatch(undo: UndoManager) {let batchKey: string | null = null- let batchTimer: ReturnType<typeof setTimeout> | null = null- function flush() {- if (batchTimer !== null) {- clearTimeout(batchTimer)- batchTimer = null- }+ function commitActiveBatch() {if (batchKey !== null) {undo.commitBatch()batchKey = null}}+ const { start: scheduleFlush, stop: cancelFlush } = useTimeoutFn(+ commitActiveBatch,+ BATCH_IDLE_MS,+ { immediate: false }+ )++ function flush() {+ cancelFlush()+ commitActiveBatch()+ }+function ensure(key: string, label: string) {if (batchKey !== key) {flush()undo.beginBatch(label)batchKey = key}- if (batchTimer !== null) clearTimeout(batchTimer)- batchTimer = setTimeout(flush, BATCH_IDLE_MS)+ scheduleFlush()}- onBeforeUnmount(flush)+ tryOnScopeDispose(flush)return { ensure, flush }}diff --git a/packages/vue/src/controls/useExport.ts b/packages/vue/src/controls/useExport.tsdeleted file mode 100644index 31cff1c9b..000000000--- a/packages/vue/src/controls/useExport.ts+++ /dev/null@@ -1,121 +0,0 @@-import { computed, ref } from 'vue'--import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core'-import { useEditor } from '@open-pencil/vue/context/editorContext'-import { useSceneComputed } from '@open-pencil/vue/internal/useSceneComputed'--export type ExportFormatId = 'png' | 'jpg' | 'webp' | 'svg' | 'fig'-export type ExportPanelTarget = 'selection' | 'page'--interface ExportSetting {- scale: number- format: ExportFormatId-}--const SCALES = [0.5, 0.75, 1, 1.5, 2, 3, 4] as const-const FORMATS: ExportFormatId[] = ['png', 'jpg', 'webp', 'svg', 'fig']-const io = new IORegistry(BUILTIN_IO_FORMATS)--function createDefaultSetting(): ExportSetting {- return { scale: 1, format: 'png' }-}--export function useExport() {- const editor = useEditor()-- const selectionSettings = ref<ExportSetting[]>([createDefaultSetting()])- const pageSettings = ref<ExportSetting[]>([createDefaultSetting()])-- const selectedIds = useSceneComputed(() => [...editor.state.selectedIds])-- const formatSupportsScale = (format: ExportFormatId) =>- io.getFormat(format)?.exportOptions?.scale ?? false-- const selectedNodeName = useSceneComputed(() => {- const ids = editor.state.selectedIds- if (ids.size === 1) {- const id = [...ids][0]- return editor.graph.getNode(id)?.name ?? 'Export'- }- if (ids.size > 1) return `${ids.size} layers`- return null- })-- const currentPageName = useSceneComputed(() => {- const page = editor.graph.getNode(editor.state.currentPageId)- return page?.name ?? 'Page'- })-- const hasSelection = computed(() => selectedIds.value.length > 0)- const activeTarget = computed<ExportPanelTarget>(() =>- hasSelection.value ? 'selection' : 'page'- )- const activeName = computed(() =>- activeTarget.value === 'selection'- ? (selectedNodeName.value ?? 'Export')- : currentPageName.value- )- const activeSettings = computed(() =>- activeTarget.value === 'selection' ? selectionSettings.value : pageSettings.value- )-- function addSelectionSetting() {- const last = selectionSettings.value[selectionSettings.value.length - 1]- const nextScale = SCALES.find((s) => s > (last?.scale ?? 1)) ?? 2- selectionSettings.value.push({ scale: nextScale, format: last?.format ?? 'png' })- }-- function addPageSetting() {- const last = pageSettings.value[pageSettings.value.length - 1]- const nextScale = SCALES.find((s) => s > (last?.scale ?? 1)) ?? 2- pageSettings.value.push({ scale: nextScale, format: last?.format ?? 'png' })- }-- function removeSelectionSetting(index: number) {- selectionSettings.value.splice(index, 1)- }-- function removePageSetting(index: number) {- pageSettings.value.splice(index, 1)- }-- function updateSelectionScale(index: number, scale: number) {- selectionSettings.value[index] = { ...selectionSettings.value[index], scale }- }-- function updatePageScale(index: number, scale: number) {- pageSettings.value[index] = { ...pageSettings.value[index], scale }- }-- function updateSelectionFormat(index: number, format: ExportFormatId) {- selectionSettings.value[index] = { ...selectionSettings.value[index], format }- }-- function updatePageFormat(index: number, format: ExportFormatId) {- pageSettings.value[index] = { ...pageSettings.value[index], format }- }-- return {- editor,- selectedIds,- scales: SCALES,- formats: FORMATS,- formatSupportsScale,- hasSelection,- activeTarget,- activeName,- activeSettings,- selectedNodeName,- currentPageName,- selectionSettings,- pageSettings,- addSelectionSetting,- addPageSetting,- removeSelectionSetting,- removePageSetting,- updateSelectionScale,- updatePageScale,- updateSelectionFormat,- updatePageFormat- }-}diff --git a/packages/vue/src/controls/useOkHCL.ts b/packages/vue/src/controls/useOkHCL.tsdeleted file mode 100644index a7c82db30..000000000--- a/packages/vue/src/controls/useOkHCL.ts+++ /dev/null@@ -1,129 +0,0 @@-import { ref } from 'vue'--import {- getFillOkHCL,- getStrokeOkHCL,- resolveOkHCLForPreview,- rgbaToOkHCL,- setNodeFillOkHCL,- setNodeStrokeOkHCL-} from '@open-pencil/core'-import { useEditor } from '@open-pencil/vue/context/editorContext'--import type { OkHCLColor, SceneNode } from '@open-pencil/core'-import type { ColorFieldFormat } from '@open-pencil/vue/ColorPicker/types'--export function useOkHCL() {- const editor = useEditor()- const fieldFormats = ref(new Map<string, ColorFieldFormat>())-- function fieldKey(kind: 'fill' | 'stroke', nodeId: string, index: number) {- return `${kind}:${nodeId}:${index}`- }-- function getFillOkHCLColor(node: SceneNode | null, index: number): OkHCLColor | null {- return node ? (getFillOkHCL(node, index)?.color ?? null) : null- }-- function getStrokeOkHCLColor(node: SceneNode | null, index: number): OkHCLColor | null {- return node ? (getStrokeOkHCL(node, index)?.color ?? null) : null- }-- function ensureFillOkHCL(node: SceneNode, index: number) {- const color =- getFillOkHCLColor(node, index) ??- rgbaToOkHCL(node.fills[index]?.color ?? { r: 0, g: 0, b: 0, a: 1 })- editor.updateNodeWithUndo(- node.id,- setNodeFillOkHCL(node, index, color),- 'Update fill color model'- )- }-- function ensureStrokeOkHCL(node: SceneNode, index: number) {- const color =- getStrokeOkHCLColor(node, index) ??- rgbaToOkHCL(node.strokes[index]?.color ?? { r: 0, g: 0, b: 0, a: 1 })- editor.updateNodeWithUndo(- node.id,- setNodeStrokeOkHCL(node, index, color),- 'Update stroke color model'- )- }-- function updateFillOkHCL(node: SceneNode, index: number, patch: Partial<OkHCLColor>) {- const current =- getFillOkHCLColor(node, index) ??- rgbaToOkHCL(node.fills[index]?.color ?? { r: 0, g: 0, b: 0, a: 1 })- editor.updateNodeWithUndo(- node.id,- setNodeFillOkHCL(node, index, { ...current, ...patch }),- 'Change fill OkHCL'- )- }-- function updateStrokeOkHCL(node: SceneNode, index: number, patch: Partial<OkHCLColor>) {- const current =- getStrokeOkHCLColor(node, index) ??- rgbaToOkHCL(node.strokes[index]?.color ?? { r: 0, g: 0, b: 0, a: 1 })- editor.updateNodeWithUndo(- node.id,- setNodeStrokeOkHCL(node, index, { ...current, ...patch }),- 'Change stroke OkHCL'- )- }-- function getFillPreviewInfo(node: SceneNode | null, index: number) {- const documentColorSpace = editor.graph.documentColorSpace- const okhcl = getFillOkHCLColor(node, index)- if (!okhcl) return { previewColorSpace: documentColorSpace, clipped: false }- const resolved = resolveOkHCLForPreview(okhcl, { documentColorSpace })- return { previewColorSpace: resolved.targetSpace, clipped: resolved.clipped }- }-- function getStrokePreviewInfo(node: SceneNode | null, index: number) {- const documentColorSpace = editor.graph.documentColorSpace- const okhcl = getStrokeOkHCLColor(node, index)- if (!okhcl) return { previewColorSpace: documentColorSpace, clipped: false }- const resolved = resolveOkHCLForPreview(okhcl, { documentColorSpace })- return { previewColorSpace: resolved.targetSpace, clipped: resolved.clipped }- }-- function getFieldFormat(node: SceneNode | null, index: number, kind: 'fill' | 'stroke') {- if (!node) return 'rgb' as const- const key = fieldKey(kind, node.id, index)- const stored = fieldFormats.value.get(key)- if (stored) return stored- return (kind === 'fill' ? getFillOkHCL(node, index) : getStrokeOkHCL(node, index))- ? 'okhcl'- : 'rgb'- }-- function setFillFieldFormat(node: SceneNode, index: number, format: ColorFieldFormat) {- fieldFormats.value.set(fieldKey('fill', node.id, index), format)- if (format === 'okhcl') ensureFillOkHCL(node, index)- }-- function setStrokeFieldFormat(node: SceneNode, index: number, format: ColorFieldFormat) {- fieldFormats.value.set(fieldKey('stroke', node.id, index), format)- if (format === 'okhcl') ensureStrokeOkHCL(node, index)- }-- return {- getFillOkHCLColor,- getStrokeOkHCLColor,- getFillPreviewInfo,- getStrokePreviewInfo,- getFieldFormat,- setFillFieldFormat,- setStrokeFieldFormat,- updateFillOkHCL,- updateStrokeOkHCL,- fieldOptions: [- { value: 'rgb' as const, label: 'RGB' },- { value: 'hsl' as const, label: 'HSL' },- { value: 'hsb' as const, label: 'HSB' },- { value: 'okhcl' as const, label: 'OkHCL' }- ]- }-}diff --git a/packages/vue/src/controls/useStrokeControls.ts b/packages/vue/src/controls/useStrokeControls.tsdeleted file mode 100644index 2ca29220d..000000000--- a/packages/vue/src/controls/useStrokeControls.ts+++ /dev/null@@ -1,149 +0,0 @@-import { ref } from 'vue'--import { useEditor } from '@open-pencil/vue/context/editorContext'-import { useI18n } from '@open-pencil/vue/i18n'--import type { SceneNode, Stroke } from '@open-pencil/core'--type StrokeSides = 'ALL' | 'TOP' | 'BOTTOM' | 'LEFT' | 'RIGHT' | 'CUSTOM'--const SIDE_OPTIONS: { value: StrokeSides; label: string }[] = [- { value: 'ALL', label: 'All' },- { value: 'TOP', label: 'Top' },- { value: 'BOTTOM', label: 'Bottom' },- { value: 'LEFT', label: 'Left' },- { value: 'RIGHT', label: 'Right' },- { value: 'CUSTOM', label: 'Custom' }-]--const BORDER_SIDES = ['top', 'right', 'bottom', 'left'] as const-const DEFAULT_STROKE: Stroke = {- color: { r: 0, g: 0, b: 0, a: 1 },- weight: 1,- opacity: 1,- visible: true,- align: 'CENTER'-}--/**- * Returns stroke-related helpers for property panels.- *- * This composable provides alignment options, side presets, a default stroke,- * and helpers for per-side border weight editing.- */-export function useStrokeControls() {- const store = useEditor()- const { panels } = useI18n()- const sideMenuOpen = ref(false)- const alignOptions = [- { value: 'INSIDE' as const, label: panels.value.strokeAlignInside },- { value: 'CENTER' as const, label: panels.value.strokeAlignCenter },- { value: 'OUTSIDE' as const, label: panels.value.strokeAlignOutside }- ]-- function updateAlign(align: Stroke['align'], activeNode: SceneNode) {- const strokes = activeNode.strokes.map((s) => ({ ...s, align }))- store.updateNodeWithUndo(activeNode.id, { strokes }, 'Change stroke align')- }-- function currentAlign(activeNode: SceneNode | null): Stroke['align'] {- if (!activeNode || activeNode.strokes.length === 0) return 'CENTER'- return activeNode.strokes[0].align- }-- function currentSides(activeNode: SceneNode | null): StrokeSides {- if (!activeNode?.independentStrokeWeights) return 'ALL'- const {- borderTopWeight: t,- borderRightWeight: r,- borderBottomWeight: b,- borderLeftWeight: l- } = activeNode- const active = [t > 0, r > 0, b > 0, l > 0]- const count = active.filter(Boolean).length- if (count === 4 && t === r && r === b && b === l) return 'ALL'- if (count === 1) {- if (t > 0) return 'TOP'- if (b > 0) return 'BOTTOM'- if (l > 0) return 'LEFT'- if (r > 0) return 'RIGHT'- }- return 'CUSTOM'- }-- function selectSide(side: StrokeSides, activeNode: SceneNode) {- const weight = activeNode.strokes.length > 0 ? activeNode.strokes[0].weight : 1- if (side === 'ALL') {- store.updateNodeWithUndo(- activeNode.id,- {- independentStrokeWeights: false,- borderTopWeight: 0,- borderRightWeight: 0,- borderBottomWeight: 0,- borderLeftWeight: 0- } as Partial<SceneNode>,- 'Stroke all sides'- )- } else if (side === 'CUSTOM') {- const w = activeNode.independentStrokeWeights- ? {- top: activeNode.borderTopWeight,- right: activeNode.borderRightWeight,- bottom: activeNode.borderBottomWeight,- left: activeNode.borderLeftWeight- }- : { top: weight, right: weight, bottom: weight, left: weight }- store.updateNodeWithUndo(- activeNode.id,- {- independentStrokeWeights: true,- borderTopWeight: w.top,- borderRightWeight: w.right,- borderBottomWeight: w.bottom,- borderLeftWeight: w.left- } as Partial<SceneNode>,- 'Custom stroke sides'- )- } else {- store.updateNodeWithUndo(- activeNode.id,- {- independentStrokeWeights: true,- borderTopWeight: side === 'TOP' ? weight : 0,- borderRightWeight: side === 'RIGHT' ? weight : 0,- borderBottomWeight: side === 'BOTTOM' ? weight : 0,- borderLeftWeight: side === 'LEFT' ? weight : 0- } as Partial<SceneNode>,- `Stroke ${side.toLowerCase()} only`- )- }- sideMenuOpen.value = false- }-- function updateBorderWeight(- side: (typeof BORDER_SIDES)[number],- value: number,- activeNode: SceneNode- ) {- const key = `border${side[0].toUpperCase()}${side.slice(1)}Weight` as keyof SceneNode- store.updateNodeWithUndo(- activeNode.id,- { [key]: value } as Partial<SceneNode>,- 'Change stroke weight'- )- }-- return {- alignOptions,- sideOptions: SIDE_OPTIONS,- borderSides: BORDER_SIDES,- sideMenuOpen,- defaultStroke: DEFAULT_STROKE,- updateAlign,- currentAlign,- currentSides,- selectSide,- updateBorderWeight- }-}diff --git a/packages/vue/src/document/export/helpers.ts b/packages/vue/src/document/export/helpers.tsnew file mode 100644index 000000000..d09962391--- /dev/null+++ b/packages/vue/src/document/export/helpers.ts@@ -0,0 +1,90 @@+import { computed } from 'vue'++import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'++import type { ExportFormatId, ExportPanelTarget, ExportSetting } from '#vue/document/export/use'+import type { Editor } from '@open-pencil/core/editor'+import type { Ref } from 'vue'++export const EXPORT_SCALES = [0.5, 0.75, 1, 1.5, 2, 3, 4] as const+export const EXPORT_FORMATS: ExportFormatId[] = ['png', 'jpg', 'webp', 'svg', 'fig']++const io = new IORegistry(BUILTIN_IO_FORMATS)++export function createDefaultExportSetting(): ExportSetting {+ return { scale: 1, format: 'png' }+}++export function formatSupportsScale(format: ExportFormatId) {+ return io.getFormat(format)?.exportOptions?.scale ?? false+}++export function createExportTargetState(+ editor: Editor,+ selectedIds: Ref<string[]>,+ selectionSettings: Ref<ExportSetting[]>,+ pageSettings: Ref<ExportSetting[]>+) {+ const hasSelection = computed(() => selectedIds.value.length > 0)+ const activeTarget = computed<ExportPanelTarget>(() =>+ hasSelection.value ? 'selection' : 'page'+ )++ const selectedNodeName = computed(() => {+ const ids = editor.state.selectedIds+ if (ids.size === 1) {+ const id = [...ids][0]+ return editor.graph.getNode(id)?.name ?? 'Export'+ }+ if (ids.size > 1) return `${ids.size} layers`+ return null+ })++ const currentPageName = computed(() => {+ const page = editor.graph.getNode(editor.state.currentPageId)+ return page?.name ?? 'Page'+ })++ const activeName = computed(() =>+ activeTarget.value === 'selection'+ ? (selectedNodeName.value ?? 'Export')+ : currentPageName.value+ )+ const activeSettings = computed(() =>+ activeTarget.value === 'selection' ? selectionSettings.value : pageSettings.value+ )++ return { hasSelection, activeTarget, selectedNodeName, currentPageName, activeName, activeSettings }+}++export function createExportSettingActions(+ selectionSettings: Ref<ExportSetting[]>,+ pageSettings: Ref<ExportSetting[]>+) {+ function addSetting(settings: Ref<ExportSetting[]>) {+ const last = settings.value[settings.value.length - 1]+ const nextScale = EXPORT_SCALES.find((s) => s > last.scale) ?? 2+ settings.value.push({ scale: nextScale, format: last.format })+ }++ function updateScale(settings: Ref<ExportSetting[]>, index: number, scale: number) {+ settings.value[index] = { ...settings.value[index], scale }+ }++ function updateFormat(settings: Ref<ExportSetting[]>, index: number, format: ExportFormatId) {+ settings.value[index] = { ...settings.value[index], format }+ }++ return {+ addSelectionSetting: () => addSetting(selectionSettings),+ addPageSetting: () => addSetting(pageSettings),+ removeSelectionSetting: (index: number) => selectionSettings.value.splice(index, 1),+ removePageSetting: (index: number) => pageSettings.value.splice(index, 1),+ updateSelectionScale: (index: number, scale: number) => updateScale(selectionSettings, index, scale),+ updatePageScale: (index: number, scale: number) => updateScale(pageSettings, index, scale),+ updateSelectionFormat: (index: number, format: ExportFormatId) =>+ updateFormat(selectionSettings, index, format),+ updatePageFormat: (index: number, format: ExportFormatId) =>+ updateFormat(pageSettings, index, format)+ }+}diff --git a/packages/vue/src/document/export/use.ts b/packages/vue/src/document/export/use.tsnew file mode 100644index 000000000..62ce72fc9--- /dev/null+++ b/packages/vue/src/document/export/use.ts@@ -0,0 +1,42 @@+import { useEditor } from '#vue/editor/context'+import { useSceneComputed } from '#vue/internal/scene-computed/use'+import {+ EXPORT_FORMATS,+ EXPORT_SCALES,+ createDefaultExportSetting,+ createExportSettingActions,+ createExportTargetState,+ formatSupportsScale+} from '#vue/document/export/helpers'+import { ref } from 'vue'++export type ExportFormatId = 'png' | 'jpg' | 'webp' | 'svg' | 'fig'+export type ExportPanelTarget = 'selection' | 'page'++export interface ExportSetting {+ scale: number+ format: ExportFormatId+}++export function useExport() {+ const editor = useEditor()++ const selectionSettings = ref<ExportSetting[]>([createDefaultExportSetting()])+ const pageSettings = ref<ExportSetting[]>([createDefaultExportSetting()])+ const selectedIds = useSceneComputed(() => [...editor.state.selectedIds])++ const targetState = createExportTargetState(editor, selectedIds, selectionSettings, pageSettings)+ const settingActions = createExportSettingActions(selectionSettings, pageSettings)++ return {+ editor,+ selectedIds,+ scales: EXPORT_SCALES,+ formats: EXPORT_FORMATS,+ formatSupportsScale,+ selectionSettings,+ pageSettings,+ ...targetState,+ ...settingActions+ }+}diff --git a/packages/vue/src/editor/commands/actions.ts b/packages/vue/src/editor/commands/actions.tsnew file mode 100644index 000000000..05c46d781--- /dev/null+++ b/packages/vue/src/editor/commands/actions.ts@@ -0,0 +1,32 @@+import { EDITOR_COMMAND_SHORTCUTS } from './metadata'++import type { EditorCommand, EditorCommandId, EditorCommandMenuItem } from './types'++export function createEditorCommandActions(commands: Record<EditorCommandId, EditorCommand>) {+ function getCommand(id: EditorCommandId) {+ return commands[id]+ }++ function runCommand(id: EditorCommandId) {+ const command = commands[id]+ if (command.enabled.value) command.run()+ }++ function menuItem(+ id: EditorCommandId,+ shortcut = EDITOR_COMMAND_SHORTCUTS[id]+ ): EditorCommandMenuItem {+ const command = getCommand(id)+ return {+ id,+ label: command.label,+ shortcut,+ get disabled() {+ return !command.enabled.value+ },+ action: () => runCommand(id)+ }+ }++ return { getCommand, runCommand, menuItem }+}diff --git a/packages/vue/src/editor/commands/context.ts b/packages/vue/src/editor/commands/context.tsnew file mode 100644index 000000000..46e6aa30c--- /dev/null+++ b/packages/vue/src/editor/commands/context.ts@@ -0,0 +1,17 @@+import type { useSelectionCapabilities } from '#vue/editor/selection-capabilities/use'+import type { useSelectionState } from '#vue/editor/selection-state/use'+import type { Editor } from '@open-pencil/core/editor'+import type { ComputedRef } from 'vue'++export type CommandMessagesStore = { value: Record<string, string> }+export type SelectionState = ReturnType<typeof useSelectionState>+export type SelectionCapabilities = ReturnType<typeof useSelectionCapabilities>++export type EditorCommandMapOptions = {+ editor: Editor+ selection: SelectionState+ capabilities: SelectionCapabilities+ messages: CommandMessagesStore+ otherPages: ComputedRef<Array<{ id: string }>>+ moveSelectionToPage: (pageId: string) => void+}diff --git a/packages/vue/src/editor/commands/definitions.ts b/packages/vue/src/editor/commands/definitions.tsnew file mode 100644index 000000000..07e3a08d5--- /dev/null+++ b/packages/vue/src/editor/commands/definitions.ts@@ -0,0 +1,16 @@+import { createEditCommands } from './edit'+import { createSelectionCommands } from './selection'+import { createViewCommands } from './view'++import type { EditorCommand, EditorCommandId } from './types'+import type { EditorCommandMapOptions } from './context'++export function createEditorCommandMap(+ options: EditorCommandMapOptions+): Record<EditorCommandId, EditorCommand> {+ return {+ ...createEditCommands(options),+ ...createSelectionCommands(options),+ ...createViewCommands(options),+ }+}diff --git a/packages/vue/src/editor/commands/edit.ts b/packages/vue/src/editor/commands/edit.tsnew file mode 100644index 000000000..803eefc1e--- /dev/null+++ b/packages/vue/src/editor/commands/edit.ts@@ -0,0 +1,29 @@+import type { EditorCommand } from './types'+import type { EditorCommandMapOptions } from './context'++type EditCommandId = 'edit.undo' | 'edit.redo'++export function createEditCommands({+ editor,+ capabilities,+ messages: t,+}: EditorCommandMapOptions): Record<EditCommandId, EditorCommand> {+ return {+ 'edit.undo': {+ id: 'edit.undo',+ get label() {+ return t.value.undo+ },+ enabled: capabilities.canUndo,+ run: () => editor.undoAction(),+ },+ 'edit.redo': {+ id: 'edit.redo',+ get label() {+ return t.value.redo+ },+ enabled: capabilities.canRedo,+ run: () => editor.redoAction(),+ },+ }+}diff --git a/packages/vue/src/editor/commands/metadata.ts b/packages/vue/src/editor/commands/metadata.tsnew file mode 100644index 000000000..6b4494fad--- /dev/null+++ b/packages/vue/src/editor/commands/metadata.ts@@ -0,0 +1,19 @@+import type { EditorCommandId } from './types'++export const EDITOR_COMMAND_SHORTCUTS: Partial<Record<EditorCommandId, string>> = {+ 'edit.undo': '⌘Z',+ 'edit.redo': '⇧⌘Z',+ 'selection.selectAll': '⌘A',+ 'selection.duplicate': '⌘D',+ 'selection.delete': '⌫',+ 'selection.group': '⌘G',+ 'selection.ungroup': '⇧⌘G',+ 'selection.createComponent': '⌥⌘K',+ 'selection.createComponentSet': '⇧⌘K',+ 'selection.detachInstance': '⌥⌘B',+ 'selection.wrapInAutoLayout': '⇧A',+ 'selection.bringToFront': ']',+ 'selection.sendToBack': '[',+ 'selection.toggleVisibility': '⇧⌘H',+ 'selection.toggleLock': '⇧⌘L',+}diff --git a/packages/vue/src/editor/commands/selection.ts b/packages/vue/src/editor/commands/selection.tsnew file mode 100644index 000000000..766d1a908--- /dev/null+++ b/packages/vue/src/editor/commands/selection.ts@@ -0,0 +1,149 @@+import type { EditorCommand, EditorCommandId } from './types'+import type { EditorCommandMapOptions } from './context'++type SelectionCommandId = Extract<EditorCommandId, `selection.${string}`>++export function createSelectionCommands({+ editor,+ selection,+ capabilities,+ messages: t,+ otherPages,+ moveSelectionToPage,+}: EditorCommandMapOptions): Record<SelectionCommandId, EditorCommand> {+ return {+ 'selection.selectAll': {+ id: 'selection.selectAll',+ get label() {+ return t.value.selectAll+ },+ enabled: capabilities.canSelectAll,+ run: () => editor.selectAll(),+ },+ 'selection.duplicate': {+ id: 'selection.duplicate',+ get label() {+ return t.value.duplicate+ },+ enabled: capabilities.canDuplicate,+ run: () => editor.duplicateSelected(),+ },+ 'selection.delete': {+ id: 'selection.delete',+ get label() {+ return t.value.delete+ },+ enabled: capabilities.canDelete,+ run: () => editor.deleteSelected(),+ },+ 'selection.group': {+ id: 'selection.group',+ get label() {+ return t.value.group+ },+ enabled: capabilities.canGroup,+ run: () => editor.groupSelected(),+ },+ 'selection.ungroup': {+ id: 'selection.ungroup',+ get label() {+ return t.value.ungroup+ },+ enabled: capabilities.canUngroup,+ run: () => editor.ungroupSelected(),+ },+ 'selection.createComponent': {+ id: 'selection.createComponent',+ get label() {+ return t.value.createComponent+ },+ enabled: capabilities.canCreateComponent,+ run: () => editor.createComponentFromSelection(),+ },+ 'selection.createComponentSet': {+ id: 'selection.createComponentSet',+ get label() {+ return t.value.createComponentSet+ },+ enabled: capabilities.canCreateComponentSet,+ run: () => editor.createComponentSetFromComponents(),+ },+ 'selection.createInstance': {+ id: 'selection.createInstance',+ get label() {+ return t.value.createInstance+ },+ enabled: capabilities.canCreateInstance,+ run: () => {+ const node = selection.selectedNode.value+ if (node?.type === 'COMPONENT') editor.createInstanceFromComponent(node.id)+ },+ },+ 'selection.detachInstance': {+ id: 'selection.detachInstance',+ get label() {+ return t.value.detachInstance+ },+ enabled: capabilities.canDetachInstance,+ run: () => editor.detachInstance(),+ },+ 'selection.goToMainComponent': {+ id: 'selection.goToMainComponent',+ get label() {+ return t.value.goToMainComponent+ },+ enabled: capabilities.canGoToMainComponent,+ run: () => editor.goToMainComponent(),+ },+ 'selection.wrapInAutoLayout': {+ id: 'selection.wrapInAutoLayout',+ get label() {+ return t.value.addAutoLayout+ },+ enabled: capabilities.canWrapInAutoLayout,+ run: () => editor.wrapInAutoLayout(),+ },+ 'selection.bringToFront': {+ id: 'selection.bringToFront',+ get label() {+ return t.value.bringToFront+ },+ enabled: capabilities.canBringToFront,+ run: () => editor.bringToFront(),+ },+ 'selection.sendToBack': {+ id: 'selection.sendToBack',+ get label() {+ return t.value.sendToBack+ },+ enabled: capabilities.canSendToBack,+ run: () => editor.sendToBack(),+ },+ 'selection.toggleVisibility': {+ id: 'selection.toggleVisibility',+ get label() {+ return t.value.toggleVisibility+ },+ enabled: capabilities.canToggleVisibility,+ run: () => editor.toggleVisibility(),+ },+ 'selection.toggleLock': {+ id: 'selection.toggleLock',+ get label() {+ return t.value.toggleLock+ },+ enabled: capabilities.canToggleLock,+ run: () => editor.toggleLock(),+ },+ 'selection.moveToPage': {+ id: 'selection.moveToPage',+ get label() {+ return t.value.moveToPage+ },+ enabled: capabilities.canMoveToPage,+ run: () => {+ moveSelectionToPage(otherPages.value[0].id)+ },+ },+ }+}diff --git a/packages/vue/src/editor/commands/types.ts b/packages/vue/src/editor/commands/types.tsnew file mode 100644index 000000000..5d2f3a8a1--- /dev/null+++ b/packages/vue/src/editor/commands/types.ts@@ -0,0 +1,48 @@+import type { Component, ComputedRef } from 'vue'++export type EditorCommandId =+ | 'edit.undo'+ | 'edit.redo'+ | 'selection.selectAll'+ | 'selection.duplicate'+ | 'selection.delete'+ | 'selection.group'+ | 'selection.ungroup'+ | 'selection.createComponent'+ | 'selection.createComponentSet'+ | 'selection.createInstance'+ | 'selection.detachInstance'+ | 'selection.goToMainComponent'+ | 'selection.wrapInAutoLayout'+ | 'selection.bringToFront'+ | 'selection.sendToBack'+ | 'selection.toggleVisibility'+ | 'selection.toggleLock'+ | 'selection.moveToPage'+ | 'view.zoom100'+ | 'view.zoomFit'+ | 'view.zoomSelection'++export interface EditorCommand {+ id: EditorCommandId+ label: string+ enabled: ComputedRef<boolean>+ run: () => void+}++export interface EditorCommandMenuItem {+ id?: EditorCommandId+ label: string+ shortcut?: string+ action?: () => void+ disabled?: boolean+ checked?: boolean+ onCheckedChange?: (checked: boolean) => void+ icon?: Component+}++export interface EditorCommandMenuSeparator {+ separator: true+}++export type EditorCommandMenuEntry = EditorCommandMenuItem | EditorCommandMenuSeparatordiff --git a/packages/vue/src/editor/commands/use.ts b/packages/vue/src/editor/commands/use.tsnew file mode 100644index 000000000..83b3afa6f--- /dev/null+++ b/packages/vue/src/editor/commands/use.ts@@ -0,0 +1,58 @@+import { createEditorCommandActions } from '#vue/editor/commands/actions'+import { createEditorCommandMap } from '#vue/editor/commands/definitions'+import { useEditor } from '#vue/editor/context'+import { useSelectionCapabilities } from '#vue/editor/selection-capabilities/use'+import { useSelectionState } from '#vue/editor/selection-state/use'+import { commandMessages } from '#vue/i18n'+import { usePageList } from '#vue/primitives/PageList/usePageList'+import { useStore } from '@nanostores/vue'+import { computed } from 'vue'++export type {+ EditorCommand,+ EditorCommandId,+ EditorCommandMenuEntry,+ EditorCommandMenuItem,+ EditorCommandMenuSeparator+} from './types'++/**+ * Builds a command-oriented interface on top of the current editor.+ *+ * Use this composable when building menus, toolbars, keyboard handlers, or+ * any other UI that should talk in terms of commands instead of raw editor+ * method calls.+ */+export function useEditorCommands() {+ const editor = useEditor()+ const selection = useSelectionState()+ const capabilities = useSelectionCapabilities()+ const { pages } = usePageList()++ const t = useStore(commandMessages)++ const otherPages = computed(() =>+ pages.value.filter((page) => page.id !== editor.state.currentPageId)+ )++ function moveSelectionToPage(pageId: string) {+ if (!capabilities.canMoveToPage.value) return+ editor.moveToPage(pageId)+ }++ const commands = createEditorCommandMap({+ editor,+ selection,+ capabilities,+ messages: t,+ otherPages,+ moveSelectionToPage+ })++ return {+ commands,+ otherPages,+ moveSelectionToPage,+ ...createEditorCommandActions(commands)+ }+}diff --git a/packages/vue/src/editor/commands/view.ts b/packages/vue/src/editor/commands/view.tsnew file mode 100644index 000000000..2098c6fb3--- /dev/null+++ b/packages/vue/src/editor/commands/view.ts@@ -0,0 +1,40 @@+import { computed } from 'vue'++import type { EditorCommand } from './types'+import type { EditorCommandMapOptions } from './context'++export function createViewCommands({+ editor,+ capabilities,+ messages: t,+}: EditorCommandMapOptions): Pick<+ Record<'view.zoom100' | 'view.zoomFit' | 'view.zoomSelection', EditorCommand>,+ 'view.zoom100' | 'view.zoomFit' | 'view.zoomSelection'+> {+ return {+ 'view.zoom100': {+ id: 'view.zoom100',+ get label() {+ return t.value.zoomTo100+ },+ enabled: computed(() => true),+ run: () => editor.zoomTo100(),+ },+ 'view.zoomFit': {+ id: 'view.zoomFit',+ get label() {+ return t.value.zoomToFit+ },+ enabled: computed(() => true),+ run: () => editor.zoomToFit(),+ },+ 'view.zoomSelection': {+ id: 'view.zoomSelection',+ get label() {+ return t.value.zoomToSelection+ },+ enabled: capabilities.canZoomToSelection,+ run: () => editor.zoomToSelection(),+ },+ }+}diff --git a/packages/vue/src/context/editorContext.ts b/packages/vue/src/editor/context/index.tssimilarity index 100%rename from packages/vue/src/context/editorContext.tsrename to packages/vue/src/editor/context/index.tsdiff --git a/packages/vue/src/shared/useInlineRename.ts b/packages/vue/src/editor/inline-rename/use.tssimilarity index 100%rename from packages/vue/src/shared/useInlineRename.tsrename to packages/vue/src/editor/inline-rename/use.tsdiff --git a/packages/vue/src/editor/menu-model/builders.ts b/packages/vue/src/editor/menu-model/builders.tsnew file mode 100644index 000000000..1b393b311--- /dev/null+++ b/packages/vue/src/editor/menu-model/builders.ts@@ -0,0 +1,93 @@+import {+ EDIT_MENU_COMMAND_GROUPS,+ OBJECT_MENU_COMMAND_GROUPS,+ VIEW_MENU_COMMANDS+} from '#vue/editor/menu-model/command-groups'++import type { EditorCommandId } from '#vue/editor/commands/types'+import type { useEditorCommands } from '#vue/editor/commands/use'+import type { MenuActionNode, MenuEntry, MenuSeparatorNode } from '#vue/editor/menu-model/types'+import type { useSelectionState } from '#vue/editor/selection-state/use'++type CommandMenuItem = ReturnType<typeof useEditorCommands>['menuItem']+type SelectionState = ReturnType<typeof useSelectionState>++type MenuTranslations = {+ moveToPage: string+}++type CanvasMenuOptions = {+ commandMenuItem: CommandMenuItem+ otherPages: ReturnType<typeof useEditorCommands>['otherPages']['value']+ moveSelectionToPage: ReturnType<typeof useEditorCommands>['moveSelectionToPage']+ selection: SelectionState+ t: MenuTranslations+}++function commandGroupEntries(+ commandMenuItem: CommandMenuItem,+ groups: ReadonlyArray<ReadonlyArray<EditorCommandId>>+): MenuEntry[] {+ const entries: MenuEntry[] = []+ for (const [index, group] of groups.entries()) {+ if (index > 0) entries.push({ separator: true })+ entries.push(...group.map((id) => commandMenuItem(id)))+ }+ return entries+}++export function buildEditMenu(commandMenuItem: CommandMenuItem): MenuEntry[] {+ return commandGroupEntries(commandMenuItem, EDIT_MENU_COMMAND_GROUPS)+}++export function buildViewMenu(commandMenuItem: CommandMenuItem): MenuEntry[] {+ return VIEW_MENU_COMMANDS.map((id) => commandMenuItem(id))+}++export function buildObjectMenu(commandMenuItem: CommandMenuItem): MenuEntry[] {+ return commandGroupEntries(commandMenuItem, OBJECT_MENU_COMMAND_GROUPS)+}++export function buildCanvasMenu({+ commandMenuItem,+ otherPages,+ moveSelectionToPage,+ selection,+ t+}: CanvasMenuOptions): MenuEntry[] {+ const moveToPageSubmenu: MenuEntry[] = otherPages.map((page) => ({+ label: page.name,+ action: () => moveSelectionToPage(page.id)+ }))++ return [+ commandMenuItem('selection.duplicate'),+ commandMenuItem('selection.delete'),+ { separator: true },+ ...(moveToPageSubmenu.length > 0 && selection.hasSelection.value+ ? [{ label: t.moveToPage, sub: moveToPageSubmenu } satisfies MenuActionNode]+ : []),+ commandMenuItem('selection.bringToFront'),+ commandMenuItem('selection.sendToBack'),+ { separator: true },+ commandMenuItem('selection.group'),+ ...(selection.isGroup.value ? [commandMenuItem('selection.ungroup')] : []),+ ...(selection.hasSelection.value ? [commandMenuItem('selection.wrapInAutoLayout')] : []),+ { separator: true },+ ...(selection.isComponent.value+ ? [commandMenuItem('selection.createInstance')]+ : [commandMenuItem('selection.createComponent')]),+ ...(selection.canCreateComponentSet.value+ ? [commandMenuItem('selection.createComponentSet')]+ : []),+ ...(selection.isInstance.value ? [commandMenuItem('selection.goToMainComponent')] : []),+ ...(selection.isInstance.value ? [commandMenuItem('selection.detachInstance')] : []),+ ...(selection.hasSelection.value+ ? [+ { separator: true } as MenuSeparatorNode,+ commandMenuItem('selection.toggleVisibility'),+ commandMenuItem('selection.toggleLock')+ ]+ : [])+ ]+}diff --git a/packages/vue/src/editor/menu-model/command-groups.ts b/packages/vue/src/editor/menu-model/command-groups.tsnew file mode 100644index 000000000..caef19746--- /dev/null+++ b/packages/vue/src/editor/menu-model/command-groups.ts@@ -0,0 +1,19 @@+import type { EditorCommandId } from '#vue/editor/commands/types'++export const EDIT_MENU_COMMAND_GROUPS = [+ ['edit.undo', 'edit.redo'],+ ['selection.duplicate', 'selection.delete'],+ ['selection.selectAll'],+] satisfies ReadonlyArray<ReadonlyArray<EditorCommandId>>++export const VIEW_MENU_COMMANDS = [+ 'view.zoom100',+ 'view.zoomFit',+ 'view.zoomSelection',+] satisfies ReadonlyArray<EditorCommandId>++export const OBJECT_MENU_COMMAND_GROUPS = [+ ['selection.group', 'selection.ungroup'],+ ['selection.createComponent', 'selection.createComponentSet', 'selection.detachInstance'],+ ['selection.bringToFront', 'selection.sendToBack'],+] satisfies ReadonlyArray<ReadonlyArray<EditorCommandId>>diff --git a/packages/vue/src/editor/menu-model/types.ts b/packages/vue/src/editor/menu-model/types.tsnew file mode 100644index 000000000..c2c274c11--- /dev/null+++ b/packages/vue/src/editor/menu-model/types.ts@@ -0,0 +1,19 @@+import type { EditorCommandId } from '#vue/editor/commands/types'++export interface MenuActionNode {+ separator?: false+ id?: EditorCommandId+ label: string+ shortcut?: string+ action?: () => void+ disabled?: boolean+ checked?: boolean+ onCheckedChange?: (checked: boolean) => void+ sub?: MenuEntry[]+}++export interface MenuSeparatorNode {+ separator: true+}++export type MenuEntry = MenuActionNode | MenuSeparatorNodediff --git a/packages/vue/src/editor/menu-model/use.ts b/packages/vue/src/editor/menu-model/use.tsnew file mode 100644index 000000000..df8397384--- /dev/null+++ b/packages/vue/src/editor/menu-model/use.ts@@ -0,0 +1,67 @@+import {+ buildCanvasMenu,+ buildEditMenu,+ buildObjectMenu,+ buildViewMenu+} from '#vue/editor/menu-model/builders'+import { useEditorCommands } from '#vue/editor/commands/use'+import { useEditor } from '#vue/editor/context'+import { useSelectionState } from '#vue/editor/selection-state/use'+import { menuMessages } from '#vue/i18n'+import { useStore } from '@nanostores/vue'+import { computed } from 'vue'++export type { MenuActionNode, MenuEntry, MenuSeparatorNode } from '#vue/editor/menu-model/types'++import type { MenuEntry } from '#vue/editor/menu-model/types'++/**+ * Returns ready-to-render menu models derived from the current editor state.+ *+ * This is a higher-level API than {@link useEditorCommands}: it groups+ * commands into app and canvas menu structures and computes context-sensitive+ * labels like Hide/Show and Lock/Unlock.+ */+export function useMenuModel() {+ const editor = useEditor()+ const { menuItem: commandMenuItem, otherPages, moveSelectionToPage } = useEditorCommands()+ const selection = useSelectionState()++ const t = useStore(menuMessages)++ const editMenu = computed<MenuEntry[]>(() => buildEditMenu(commandMenuItem))++ const viewMenu = computed<MenuEntry[]>(() => buildViewMenu(commandMenuItem))++ const objectMenu = computed<MenuEntry[]>(() => buildObjectMenu(commandMenuItem))++ const arrangeMenu = computed<MenuEntry[]>(() => [commandMenuItem('selection.wrapInAutoLayout')])++ const appMenu = computed(() => [+ { label: t.value.edit, items: editMenu.value },+ { label: t.value.view, items: viewMenu.value },+ { label: t.value.object, items: objectMenu.value },+ { label: t.value.arrange, items: arrangeMenu.value }+ ])++ const canvasMenu = computed<MenuEntry[]>(() =>+ buildCanvasMenu({+ commandMenuItem,+ otherPages: otherPages.value,+ moveSelectionToPage,+ selection,+ t: t.value+ })+ )++ const selectionLabelMenu = computed(() => ({+ visibility: (editor.getSelectedNode()?.visible ?? true) ? t.value.hide : t.value.show,+ lock: (editor.getSelectedNode()?.locked ?? false) ? t.value.unlock : t.value.lock+ }))++ return {+ appMenu,+ canvasMenu,+ selectionLabelMenu+ }+}diff --git a/packages/vue/src/editor/selection-capabilities/use.ts b/packages/vue/src/editor/selection-capabilities/use.tsnew file mode 100644index 000000000..0e069b94c--- /dev/null+++ b/packages/vue/src/editor/selection-capabilities/use.ts@@ -0,0 +1,45 @@+import { useSelectionState } from '#vue/editor/selection-state/use'+import { useSceneComputed } from '#vue/internal/scene-computed/use'+import { computed } from 'vue'++/**+ * Returns reactive booleans describing which selection-dependent actions are+ * currently available.+ *+ * This is useful for menus, toolbars, shortcuts, and action buttons that need+ * command-friendly capability checks.+ */+export function useSelectionCapabilities() {+ const selection = useSelectionState()+ const { editor, selectedIds, selectedNode, selectedCount, hasSelection } = selection++ return {+ selectedIds,+ selectedNode,+ canCopy: computed(() => hasSelection.value),+ canCut: computed(() => hasSelection.value),+ canPaste: computed(() => true),+ canDelete: computed(() => hasSelection.value),+ canDuplicate: computed(() => hasSelection.value),+ canExportSelection: computed(() => hasSelection.value),+ canGroup: computed(() => selectedCount.value >= 2),+ canUngroup: computed(() => selection.isGroup.value),+ canCreateComponent: computed(() => hasSelection.value),+ canCreateComponentSet: selection.canCreateComponentSet,+ canDetachInstance: computed(() => selection.isInstance.value),+ canWrapInAutoLayout: computed(() => hasSelection.value),+ canBringToFront: computed(() => hasSelection.value),+ canSendToBack: computed(() => hasSelection.value),+ canToggleVisibility: computed(() => hasSelection.value),+ canToggleLock: computed(() => hasSelection.value),+ canGoToMainComponent: computed(() => selection.isInstance.value),+ canCreateInstance: computed(() => selectedNode.value?.type === 'COMPONENT'),+ canMoveToPage: useSceneComputed(() => hasSelection.value && editor.graph.getPages().length > 1),+ canSelectAll: useSceneComputed(+ () => editor.graph.getChildren(editor.state.currentPageId).length > 0+ ),+ canUndo: useSceneComputed(() => editor.undo.canUndo),+ canRedo: useSceneComputed(() => editor.undo.canRedo),+ canZoomToSelection: computed(() => hasSelection.value)+ }+}diff --git a/packages/vue/src/selection/useSelectionState.ts b/packages/vue/src/editor/selection-state/use.tssimilarity index 87%rename from packages/vue/src/selection/useSelectionState.tsrename to packages/vue/src/editor/selection-state/use.tsindex 6ba6711a0..c6599a374 100644--- a/packages/vue/src/selection/useSelectionState.ts+++ b/packages/vue/src/editor/selection-state/use.ts@@ -1,9 +1,8 @@+import { useEditor } from '#vue/editor/context'+import { useSceneComputed } from '#vue/internal/scene-computed/use'import { computed } from 'vue'-import { useEditor } from '@open-pencil/vue/context/editorContext'-import { useSceneComputed } from '@open-pencil/vue/internal/useSceneComputed'--import type { SceneNode } from '@open-pencil/core'+import type { SceneNode } from '@open-pencil/core/scene-graph'/*** Returns reactive selection-derived state for the current editor.diff --git a/packages/vue/src/internal/toolCursor.ts b/packages/vue/src/editor/tool-cursor/index.tssimilarity index 100%rename from packages/vue/src/internal/toolCursor.tsrename to packages/vue/src/editor/tool-cursor/index.tsdiff --git a/packages/vue/src/viewport/useViewportKind.ts b/packages/vue/src/editor/viewport-kind/use.tssimilarity index 100%rename from packages/vue/src/viewport/useViewportKind.tsrename to packages/vue/src/editor/viewport-kind/use.tsdiff --git a/packages/vue/src/global.d.ts b/packages/vue/src/global.d.tsindex 9ebba9189..0ded8a35f 100644--- a/packages/vue/src/global.d.ts+++ b/packages/vue/src/global.d.ts@@ -21,3 +21,10 @@ declare module '*?raw' {const content: stringexport default content}++declare module '*.vue' {+ import type { DefineComponent } from 'vue'++ const component: DefineComponent<Record<string, unknown>, Record<string, unknown>, unknown>+ export default component+}diff --git a/packages/vue/src/i18n/i18n.ts b/packages/vue/src/i18n/i18n.tsdeleted file mode 100644index 338eb6541..000000000--- a/packages/vue/src/i18n/i18n.ts+++ /dev/null@@ -1,25 +0,0 @@-import { createI18n } from '@nanostores/i18n'--import { locale } from './locale'--import type { Locale } from './locale'-import type { ComponentsJSON } from '@nanostores/i18n'--const localeLoaders: Record<Exclude<Locale, 'en'>, () => Promise<{ default: ComponentsJSON }>> = {- de: () => import('../locales/de.json'),- es: () => import('../locales/es.json'),- fr: () => import('../locales/fr.json'),- it: () => import('../locales/it.json'),- pl: () => import('../locales/pl.json'),- ru: () => import('../locales/ru.json'),- 'zh-CN': () => import('../locales/zh-CN.json')-}--export const i18n = createI18n<Locale, 'en'>(locale, {- baseLocale: 'en',- async get(code) {- if (code === 'en') return {}- const mod = await localeLoaders[code]()- return mod.default- }-})diff --git a/packages/vue/src/i18n/index.ts b/packages/vue/src/i18n/index.tsindex f87f43b0a..6c6c099aa 100644--- a/packages/vue/src/i18n/index.ts+++ b/packages/vue/src/i18n/index.ts@@ -1,6 +1,12 @@-export { useI18n } from './useI18n'-export { locale, localeSetting, setLocale, AVAILABLE_LOCALES, LOCALE_LABELS } from './locale'-export type { Locale } from './locale'+export { useI18n } from '#vue/i18n/useI18n'+export {+ locale,+ localeSetting,+ setLocale,+ AVAILABLE_LOCALES,+ LOCALE_LABELS+} from '#vue/i18n/locale'+export type { Locale } from '#vue/i18n/locale'export {menuMessages,commandMessages,@@ -8,4 +14,4 @@ export {panelMessages,pageMessages,dialogMessages-} from './messages'+} from '#vue/i18n/messages'diff --git a/packages/vue/src/i18n/messages.ts b/packages/vue/src/i18n/messages.tsindex d988fc840..509a52938 100644--- a/packages/vue/src/i18n/messages.ts+++ b/packages/vue/src/i18n/messages.ts@@ -1,6 +1,27 @@-import { params } from '@nanostores/i18n'--import { i18n } from './i18n'+import { locale } from '#vue/i18n/locale'+import { createI18n, params } from '@nanostores/i18n'++import type { Locale } from '#vue/i18n/locale'+import type { ComponentsJSON } from '@nanostores/i18n'++const localeLoaders: Record<Exclude<Locale, 'en'>, () => Promise<{ default: ComponentsJSON }>> = {+ de: () => import('#vue/locales/de.json'),+ es: () => import('#vue/locales/es.json'),+ fr: () => import('#vue/locales/fr.json'),+ it: () => import('#vue/locales/it.json'),+ pl: () => import('#vue/locales/pl.json'),+ ru: () => import('#vue/locales/ru.json'),+ 'zh-CN': () => import('#vue/locales/zh-CN.json')+}++const i18n = createI18n<Locale, 'en'>(locale, {+ baseLocale: 'en',+ async get(code) {+ if (code === 'en') return {}+ const mod = await localeLoaders[code]()+ return mod.default+ }+})export const menuMessages = i18n('menu', {file: 'File',diff --git a/packages/vue/src/i18n/useI18n.ts b/packages/vue/src/i18n/useI18n.tsindex 7d238771b..f2e07461b 100644--- a/packages/vue/src/i18n/useI18n.ts+++ b/packages/vue/src/i18n/useI18n.ts@@ -1,6 +1,4 @@-import { useStore } from '@nanostores/vue'--import { locale, setLocale, AVAILABLE_LOCALES, LOCALE_LABELS } from './locale'+import { locale, setLocale, AVAILABLE_LOCALES, LOCALE_LABELS } from '#vue/i18n/locale'import {menuMessages,commandMessages,@@ -8,9 +6,10 @@ import {panelMessages,pageMessages,dialogMessages-} from './messages'+} from '#vue/i18n/messages'+import { useStore } from '@nanostores/vue'-import type { Locale } from './locale'+import type { Locale } from '#vue/i18n/locale'import type { Ref } from 'vue'/**diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.tsindex 6903cbc74..07ff5ca3b 100644--- a/packages/vue/src/index.ts+++ b/packages/vue/src/index.ts@@ -13,63 +13,64 @@ export { createEditor, EDITOR_TOOLS, TOOL_SHORTCUTS } from '@open-pencil/core/ed* These are the primary entry points for making an editor available to a Vue* subtree and reading it back inside composables and headless primitives.*/-export { provideEditor, useEditor, EDITOR_KEY } from './context/editorContext'+export { provideEditor, useEditor, EDITOR_KEY } from '#vue/editor/context'/** Canvas and input integration composables. */-export { useCanvas } from './shared/useCanvas'-export type { UseCanvasOptions } from './shared/useCanvas'-export { useCanvasInput } from './Canvas/useCanvasInput'-export { useTextEdit } from './Canvas/useTextEdit'-export { useCanvasDrop, extractImageFilesFromClipboard } from './Canvas/useCanvasDrop'+export { useCanvas } from '#vue/canvas/surface/use'+export type { UseCanvasOptions } from '#vue/canvas/surface/use'+export { useCanvasInput } from '#vue/canvas/useCanvasInput'+export { useTextEdit } from '#vue/canvas/text-edit/use'+export { useCanvasDrop, extractImageFilesFromClipboard } from '#vue/canvas/drop/use'/** Low-level selection, graph, and derived-state helpers. */-export { useNodeProps, MIXED } from './controls/useNodeProps'-export type { MixedValue } from './controls/useNodeProps'-export { useSceneComputed } from './internal/useSceneComputed'-export { useSelectionState } from './selection/useSelectionState'-export { useSelectionCapabilities } from './selection/useSelectionCapabilities'+export { useNodeProps, MIXED } from '#vue/controls/node-props/use'+export type { MixedValue } from '#vue/controls/node-props/use'+export { useSceneComputed } from '#vue/internal/scene-computed/use'+export { useSelectionState } from '#vue/editor/selection-state/use'+export { useSelectionCapabilities } from '#vue/editor/selection-capabilities/use'/** Command and menu composition helpers. */-export { useEditorCommands } from './commands/useEditorCommands'-export type { EditorCommand, EditorCommandId } from './commands/useEditorCommands'-export { useMenuModel } from './commands/useMenuModel'-export type { MenuEntry } from './commands/useMenuModel'+export { useEditorCommands } from '#vue/editor/commands/use'+export type { EditorCommand, EditorCommandId } from '#vue/editor/commands/use'+export { useMenuModel } from '#vue/editor/menu-model/use'+export type { MenuActionNode, MenuEntry, MenuSeparatorNode } from '#vue/editor/menu-model/use'/** Miscellaneous editor-shell helpers. */-export { useViewportKind } from './viewport/useViewportKind'-export { useLayerDrag } from './LayerTree/useLayerDrag'-export { useInlineRename } from './shared/useInlineRename'-export { useToolbarState } from './Toolbar/useToolbarState'-export { useNodeFontStatus } from './shared/useFontStatus'-export { usePropScrub } from './controls/usePropScrub'-export { toolCursor } from './internal/toolCursor'+export { useViewportKind } from '#vue/editor/viewport-kind/use'+export { useLayerDrag } from '#vue/primitives/LayerTree/useLayerDrag'+export { useInlineRename } from '#vue/editor/inline-rename/use'+export { useToolbarState } from '#vue/primitives/Toolbar/useToolbarState'+export { useNodeFontStatus } from '#vue/shared/font-status/use'+export { usePropScrub } from '#vue/controls/prop-scrub/use'+export { toolCursor } from '#vue/editor/tool-cursor'/** Property-panel composables. */-export { usePosition } from './controls/usePosition'-export { useLayout } from './controls/useLayout'-export { useAppearance } from './controls/useAppearance'-export { useTypography } from './controls/useTypography'-export type { UseTypographyOptions } from './controls/useTypography'-export { useExport } from './controls/useExport'-export { useFillControls } from './controls/useFillControls'-export { useColorVariableBinding } from './controls/useColorVariableBinding'-export { useEffectsControls } from './controls/useEffectsControls'-export { useStrokeControls } from './controls/useStrokeControls'-export { useOkHCL } from './controls/useOkHCL'+export { usePosition } from '#vue/controls/position/use'+export { useLayout } from '#vue/controls/layout/use'+export { useAppearance } from '#vue/controls/appearance/use'+export { useTypography } from '#vue/controls/typography/use'+export type { UseTypographyOptions } from '#vue/controls/typography/use'+export { useExport } from '#vue/document/export/use'+export type { ExportFormatId } from '#vue/document/export/use'+export { useFillControls } from '#vue/controls/fill/use'+export { useColorVariableBinding } from '#vue/controls/color-variable-binding/use'+export { useEffectsControls } from '#vue/controls/effects/use'+export { useStrokeControls } from '#vue/controls/stroke/use'+export { useOkHCL } from '#vue/controls/okhcl/use'/** Variables, page navigation, and picker helpers. */-export { useVariables } from './VariablesEditor/useVariables'-export { useVariablesDialogState } from './VariablesEditor/useVariablesDialogState'-export { useVariablesEditor } from './VariablesEditor/useVariablesEditor'-export { useVariablesTable } from './VariablesEditor/useVariablesTable'-export { usePageList } from './PageList/usePageList'-export { useFillPicker } from './FillPicker/useFillPicker'-export { useGradientStops } from './GradientEditor/useGradientStops'-export { useFontPicker } from './FontPicker/useFontPicker'+export { useVariables } from '#vue/variables/use'+export { useVariablesDialogState } from '#vue/variables/dialog/use'+export { useVariablesEditor } from '#vue/variables/editor/use'+export { useVariablesTable } from '#vue/variables/table/use'+export { usePageList } from '#vue/primitives/PageList/usePageList'+export { useFillPicker } from '#vue/primitives/FillPicker/useFillPicker'+export { useGradientStops } from '#vue/primitives/GradientEditor/useGradientStops'+export { useFontPicker } from '#vue/primitives/FontPicker/useFontPicker'/** Headless structural primitives and their local contexts. */-export { CanvasRoot, CanvasSurface, useCanvasContext } from './Canvas'-export type { CanvasContext } from './Canvas'+export { CanvasRoot, CanvasSurface, useCanvasContext } from '#vue/canvas'+export type { CanvasContext } from '#vue/canvas'export {ColorInputRoot,ColorPickerRoot,@@ -88,28 +89,39 @@ export {updateRGBChannel,applySolidFillColor,applySolidStrokeColor-} from './ColorPicker'-export { FillPickerRoot } from './FillPicker'-export { FontPickerRoot } from './FontPicker'-export { GradientEditorRoot, GradientEditorBar, GradientEditorStop } from './GradientEditor'-export { LayerTreeRoot, LayerTreeItem, useLayerTree } from './LayerTree'-export type { LayerTreeContext, LayerNode } from './LayerTree'-export { LayoutControlsRoot } from './LayoutControls'-export { AppearanceControlsRoot } from './AppearanceControls'-export { PageListRoot } from './PageList'-export { PositionControlsRoot } from './PositionControls'-export { PropertyListRoot, PropertyListItem, usePropertyList } from './PropertyList'-export type { PropertyListContext } from './PropertyList'-export { ScrubInputRoot, ScrubInputField, ScrubInputDisplay, useScrubInput } from './ScrubInput'-export type { ScrubInputContext } from './ScrubInput'-export { TypographyControlsRoot } from './TypographyControls'-export { ToolbarRoot, ToolbarItem, useToolbar } from './Toolbar'-export type { ToolbarContext } from './Toolbar'+} from '#vue/primitives/ColorPicker'+export type { ColorFieldFormat, OkHCLControls } from '#vue/primitives/ColorPicker'+export { FillPickerRoot } from '#vue/primitives/FillPicker'+export { FontPickerRoot } from '#vue/primitives/FontPicker'+export {+ GradientEditorRoot,+ GradientEditorBar,+ GradientEditorStop+} from '#vue/primitives/GradientEditor'+export { LayerTreeRoot, LayerTreeItem, useLayerTree } from '#vue/primitives/LayerTree'+export type { LayerTreeContext, LayerNode } from '#vue/primitives/LayerTree'+export { LayoutControlsRoot, useLayoutControlsContext } from '#vue/primitives/LayoutControls'+export type { LayoutControlsContext } from '#vue/primitives/LayoutControls'+export { AppearanceControlsRoot } from '#vue/primitives/AppearanceControls'+export { PageListRoot } from '#vue/primitives/PageList'+export { PositionControlsRoot } from '#vue/primitives/PositionControls'+export { PropertyListRoot, PropertyListItem, usePropertyList } from '#vue/primitives/PropertyList'+export type { PropertyListContext } from '#vue/primitives/PropertyList'+export {+ ScrubInputRoot,+ ScrubInputField,+ ScrubInputDisplay,+ useScrubInput+} from '#vue/primitives/ScrubInput'+export type { ScrubInputContext } from '#vue/primitives/ScrubInput'+export { TypographyControlsRoot } from '#vue/primitives/TypographyControls'+export { ToolbarRoot, ToolbarItem, useToolbar } from '#vue/primitives/Toolbar'+export type { ToolbarContext } from '#vue/primitives/Toolbar'/** Internationalization. */-export { useI18n } from './i18n'-export { locale, localeSetting, setLocale, AVAILABLE_LOCALES, LOCALE_LABELS } from './i18n'-export type { Locale } from './i18n'+export { useI18n } from '#vue/i18n'+export { locale, localeSetting, setLocale, AVAILABLE_LOCALES, LOCALE_LABELS } from '#vue/i18n'+export type { Locale } from '#vue/i18n'export {menuMessages,commandMessages,@@ -117,4 +129,4 @@ export {panelMessages,pageMessages,dialogMessages-} from './i18n'+} from '#vue/i18n'diff --git a/packages/vue/src/context/createContext.ts b/packages/vue/src/internal/create-context.tssimilarity index 100%rename from packages/vue/src/context/createContext.tsrename to packages/vue/src/internal/create-context.tsdiff --git a/packages/vue/src/internal/useSceneComputed.ts b/packages/vue/src/internal/scene-computed/use.tssimilarity index 87%rename from packages/vue/src/internal/useSceneComputed.tsrename to packages/vue/src/internal/scene-computed/use.tsindex 36c460e8b..c69c34d81 100644--- a/packages/vue/src/internal/useSceneComputed.ts+++ b/packages/vue/src/internal/scene-computed/use.ts@@ -1,7 +1,6 @@+import { useEditor } from '#vue/editor/context'import { computed, type ComputedRef } from 'vue'-import { useEditor } from '@open-pencil/vue/context/editorContext'-/*** Convenience wrapper for scene-derived computed state.*diff --git a/packages/vue/src/AppearanceControls/AppearanceControlsRoot.vue b/packages/vue/src/primitives/AppearanceControls/AppearanceControlsRoot.vuesimilarity index 90%rename from packages/vue/src/AppearanceControls/AppearanceControlsRoot.vuerename to packages/vue/src/primitives/AppearanceControls/AppearanceControlsRoot.vueindex a50cbe333..443866726 100644--- a/packages/vue/src/AppearanceControls/AppearanceControlsRoot.vue+++ b/packages/vue/src/primitives/AppearanceControls/AppearanceControlsRoot.vue@@ -1,5 +1,5 @@<script setup lang="ts">-import { useAppearance } from '@open-pencil/vue/controls/useAppearance'+import { useAppearance } from '#vue/controls/appearance/use'const ctx = useAppearance()</script>diff --git a/packages/vue/src/primitives/AppearanceControls/index.ts b/packages/vue/src/primitives/AppearanceControls/index.tsnew file mode 100644index 000000000..72baadca7--- /dev/null+++ b/packages/vue/src/primitives/AppearanceControls/index.ts@@ -0,0 +1 @@+export { default as AppearanceControlsRoot } from '#vue/primitives/AppearanceControls/AppearanceControlsRoot.vue'diff --git a/packages/vue/src/ColorPicker/ColorInputRoot.vue b/packages/vue/src/primitives/ColorPicker/ColorInputRoot.vuesimilarity index 55%rename from packages/vue/src/ColorPicker/ColorInputRoot.vuerename to packages/vue/src/primitives/ColorPicker/ColorInputRoot.vueindex df2e9e9b7..7303f321e 100644--- a/packages/vue/src/ColorPicker/ColorInputRoot.vue+++ b/packages/vue/src/primitives/ColorPicker/ColorInputRoot.vue@@ -1,11 +1,11 @@<script setup lang="ts">import { computed } from 'vue'-import { colorToHexRaw, parseColor } from '@open-pencil/core'+import { colorToHexRaw, parseColor } from '@open-pencil/core/color'-import type { Color } from '@open-pencil/core'-import type { OkHCLControls } from './types'+import type { Color } from '@open-pencil/core/types'+import type { OkHCLControls } from '#vue/primitives/ColorPicker/types'-const props = defineProps<{+const { color, editable = false, okhcl = null } = defineProps<{color: Coloreditable?: booleanokhcl?: OkHCLControls | null@@ -13,21 +13,21 @@ const props = defineProps<{const emit = defineEmits<{ update: [color: Color] }>()-const hex = computed(() => colorToHexRaw(props.color))+const hex = computed(() => colorToHexRaw(color))function updateFromHex(value: string) {const parsed = parseColor(value.startsWith('#') ? value : `#${value}`)- emit('update', { ...parsed, a: props.color.a })+ emit('update', { ...parsed, a: color.a })}</script><template><slot:color="color"- :editable="editable ?? false"+ :editable="editable":hex="hex":update-from-hex="updateFromHex":update-color="(nextColor: Color) => emit('update', nextColor)"- :okhcl="props.okhcl ?? null"+ :okhcl="okhcl"/></template>diff --git a/packages/vue/src/ColorPicker/ColorPickerRoot.vue b/packages/vue/src/primitives/ColorPicker/ColorPickerRoot.vuesimilarity index 67%rename from packages/vue/src/ColorPicker/ColorPickerRoot.vuerename to packages/vue/src/primitives/ColorPicker/ColorPickerRoot.vueindex b77401b50..f9b67f5f1 100644--- a/packages/vue/src/ColorPicker/ColorPickerRoot.vue+++ b/packages/vue/src/primitives/ColorPicker/ColorPickerRoot.vue@@ -1,11 +1,11 @@<script setup lang="ts">import { computed } from 'vue'import { PopoverContent, PopoverPortal, PopoverRoot, PopoverTrigger } from 'reka-ui'-import { colorToCSS } from '@open-pencil/core'+import { colorToCSS } from '@open-pencil/core/color'-import type { Color } from '@open-pencil/core'+import type { Color } from '@open-pencil/core/types'-const props = defineProps<{+const { color, contentClass, swatchClass } = defineProps<{color: ColorcontentClass?: stringswatchClass?: string@@ -13,14 +13,18 @@ const props = defineProps<{const emit = defineEmits<{ update: [color: Color] }>()-const swatchBg = computed(() => colorToCSS(props.color))+const swatchBg = computed(() => colorToCSS(color))</script><template><PopoverRoot><PopoverTrigger as-child><slot name="trigger" :style="{ background: swatchBg }">- <button :class="swatchClass" :style="{ background: swatchBg }" />+ <button+ data-test-id="color-picker-swatch"+ :class="swatchClass"+ :style="{ background: swatchBg }"+ /></slot></PopoverTrigger>diff --git a/packages/vue/src/primitives/ColorPicker/index.ts b/packages/vue/src/primitives/ColorPicker/index.tsnew file mode 100644index 000000000..f29d15091--- /dev/null+++ b/packages/vue/src/primitives/ColorPicker/index.ts@@ -0,0 +1,20 @@+export { default as ColorInputRoot } from '#vue/primitives/ColorPicker/ColorInputRoot.vue'+export { default as ColorPickerRoot } from '#vue/primitives/ColorPicker/ColorPickerRoot.vue'+export {+ createColorPickerModel,+ createOkHCLSliderGradientModel,+ createOkHCLSliderPreviewModel,+ createSliderGradientModel,+ createSliderPreviewModel,+ fromPercent,+ rekaToAppColor,+ toPercent,+ updateAlpha,+ updateHSBChannel,+ updateHSLChannel,+ updateHue,+ updateRGBChannel,+ applySolidFillColor,+ applySolidStrokeColor+} from '#vue/primitives/ColorPicker/model'+export type { ColorFieldFormat, OkHCLControls } from '#vue/primitives/ColorPicker/types'diff --git a/packages/vue/src/ColorPicker/model.ts b/packages/vue/src/primitives/ColorPicker/model.tssimilarity index 92%rename from packages/vue/src/ColorPicker/model.tsrename to packages/vue/src/primitives/ColorPicker/model.tsindex 8b19b47fd..b3161f5a8 100644--- a/packages/vue/src/ColorPicker/model.ts+++ b/packages/vue/src/primitives/ColorPicker/model.ts@@ -1,8 +1,10 @@import { convertToHsb, convertToHsl, convertToRgb } from 'reka-ui'-import { colorToCSS, okhclToRGBA, rgba255ToColor } from '@open-pencil/core'+import { colorToCSS, okhclToRGBA, rgba255ToColor } from '@open-pencil/core/color'-import type { Color, OkHCLColor } from '@open-pencil/core'+import type { OkHCLColor } from '@open-pencil/core/color'+import type { Fill, Stroke } from '@open-pencil/core/scene-graph'+import type { Color } from '@open-pencil/core/types'import type { Color as RekaColor, HSBColor, HSLColor, RGBColor } from 'reka-ui'export interface ColorPickerModel {@@ -221,3 +223,18 @@ function clampUnit(value: number): number {function clampPercent(value: number): number {return Math.max(0, Math.min(100, value))}++export function applySolidFillColor(fill: Fill, color: Color): Fill {+ return {+ ...fill,+ color,+ opacity: color.a+ }+}++export function applySolidStrokeColor(color: Color): Partial<Stroke> {+ return {+ color,+ opacity: color.a+ }+}diff --git a/packages/vue/src/ColorPicker/types.ts b/packages/vue/src/primitives/ColorPicker/types.tssimilarity index 97%rename from packages/vue/src/ColorPicker/types.tsrename to packages/vue/src/primitives/ColorPicker/types.tsindex f5cab5cb7..4375edab8 100644--- a/packages/vue/src/ColorPicker/types.ts+++ b/packages/vue/src/primitives/ColorPicker/types.ts@@ -1,4 +1,4 @@-import type { OkHCLColor, RenderColorSpace } from '@open-pencil/core'+import type { OkHCLColor, RenderColorSpace } from '@open-pencil/core/color'export type ColorFieldFormat = 'rgb' | 'hsl' | 'hsb' | 'okhcl'diff --git a/packages/vue/src/FillPicker/FillPickerRoot.vue b/packages/vue/src/primitives/FillPicker/FillPickerRoot.vuesimilarity index 82%rename from packages/vue/src/FillPicker/FillPickerRoot.vuerename to packages/vue/src/primitives/FillPicker/FillPickerRoot.vueindex e8a020426..3036c00c5 100644--- a/packages/vue/src/FillPicker/FillPickerRoot.vue+++ b/packages/vue/src/primitives/FillPicker/FillPickerRoot.vue@@ -2,11 +2,11 @@import { computed } from 'vue'import { PopoverContent, PopoverPortal, PopoverRoot, PopoverTrigger } from 'reka-ui'-import { useFillPicker } from '@open-pencil/vue/FillPicker/useFillPicker'+import { useFillPicker } from '#vue/primitives/FillPicker/useFillPicker'-import type { Fill } from '@open-pencil/core'+import type { Fill } from '@open-pencil/core/scene-graph'-const props = defineProps<{+const { fill, contentClass, swatchClass } = defineProps<{fill: FillcontentClass?: stringswatchClass?: string@@ -15,7 +15,7 @@ const props = defineProps<{const emit = defineEmits<{ update: [fill: Fill] }>()const { category, swatchBg, toSolid, toGradient, toImage } = useFillPicker(- computed(() => props.fill),+ computed(() => fill),(updated) => emit('update', updated))</script>diff --git a/packages/vue/src/primitives/FillPicker/index.ts b/packages/vue/src/primitives/FillPicker/index.tsnew file mode 100644index 000000000..136ead9df--- /dev/null+++ b/packages/vue/src/primitives/FillPicker/index.ts@@ -0,0 +1 @@+export { default as FillPickerRoot } from '#vue/primitives/FillPicker/FillPickerRoot.vue'diff --git a/packages/vue/src/FillPicker/useFillPicker.ts b/packages/vue/src/primitives/FillPicker/useFillPicker.tssimilarity index 94%rename from packages/vue/src/FillPicker/useFillPicker.tsrename to packages/vue/src/primitives/FillPicker/useFillPicker.tsindex e0b0255ac..652934df3 100644--- a/packages/vue/src/FillPicker/useFillPicker.ts+++ b/packages/vue/src/primitives/FillPicker/useFillPicker.ts@@ -1,8 +1,8 @@import { computed, type Ref } from 'vue'-import { colorToCSS } from '@open-pencil/core'+import { colorToCSS } from '@open-pencil/core/color'-import type { Fill, GradientStop } from '@open-pencil/core'+import type { Fill, GradientStop } from '@open-pencil/core/scene-graph'type FillCategory = 'SOLID' | 'GRADIENT' | 'IMAGE'diff --git a/packages/vue/src/FontPicker/FontPickerRoot.vue b/packages/vue/src/primitives/FontPicker/FontPickerRoot.vuesimilarity index 92%rename from packages/vue/src/FontPicker/FontPickerRoot.vuerename to packages/vue/src/primitives/FontPicker/FontPickerRoot.vueindex c05af7f51..15c8ed8c7 100644--- a/packages/vue/src/FontPicker/FontPickerRoot.vue+++ b/packages/vue/src/primitives/FontPicker/FontPickerRoot.vue@@ -13,9 +13,20 @@ import {type AcceptableValue} from 'reka-ui'-import { useFontPicker } from '@open-pencil/vue/FontPicker/useFontPicker'+import { useFontPicker } from '#vue/primitives/FontPicker/useFontPicker'-const props = defineProps<{+const {+ listFamilies,+ triggerClass,+ contentClass,+ itemClass,+ searchClass,+ viewportClass,+ emptyClass,+ emptySearchText,+ emptyFontsText,+ emptyFontsHint+} = defineProps<{listFamilies: () => Promise<string[]>triggerClass?: stringcontentClass?: string@@ -39,7 +50,7 @@ function setInputRef(el: HTMLInputElement | null) {const { searchTerm, open, filtered, select } = useFontPicker({modelValue,- listFamilies: props.listFamilies,+ listFamilies,onSelect: (family) => emit('select', family)})</script>diff --git a/packages/vue/src/primitives/FontPicker/index.ts b/packages/vue/src/primitives/FontPicker/index.tsnew file mode 100644index 000000000..cb7d14a79--- /dev/null+++ b/packages/vue/src/primitives/FontPicker/index.ts@@ -0,0 +1 @@+export { default as FontPickerRoot } from '#vue/primitives/FontPicker/FontPickerRoot.vue'diff --git a/packages/vue/src/FontPicker/useFontPicker.ts b/packages/vue/src/primitives/FontPicker/useFontPicker.tssimilarity index 100%rename from packages/vue/src/FontPicker/useFontPicker.tsrename to packages/vue/src/primitives/FontPicker/useFontPicker.tsdiff --git a/packages/vue/src/GradientEditor/GradientEditorBar.vue b/packages/vue/src/primitives/GradientEditor/GradientEditorBar.vuesimilarity index 95%rename from packages/vue/src/GradientEditor/GradientEditorBar.vuerename to packages/vue/src/primitives/GradientEditor/GradientEditorBar.vueindex 68e30d071..4e6a3d32e 100644--- a/packages/vue/src/GradientEditor/GradientEditorBar.vue+++ b/packages/vue/src/primitives/GradientEditor/GradientEditorBar.vue@@ -1,7 +1,7 @@<script setup lang="ts">import { ref } from 'vue'-import type { GradientStop } from '@open-pencil/core'+import type { GradientStop } from '@open-pencil/core/scene-graph'const { stops } = defineProps<{stops: GradientStop[]diff --git a/packages/vue/src/primitives/GradientEditor/GradientEditorRoot.vue b/packages/vue/src/primitives/GradientEditor/GradientEditorRoot.vuenew file mode 100644index 000000000..50372e3d1--- /dev/null+++ b/packages/vue/src/primitives/GradientEditor/GradientEditorRoot.vue@@ -0,0 +1,51 @@+<script setup lang="ts">+import { computed } from 'vue'++import { useGradientStops } from '#vue/primitives/GradientEditor/useGradientStops'++import type { Fill } from '@open-pencil/core/scene-graph'++const { fill } = defineProps<{ fill: Fill }>()+const emit = defineEmits<{ update: [fill: Fill] }>()++const {+ activeStopIndex,+ stops,+ subtype,+ subtypes,+ activeColor,+ barBackground,+ setSubtype,+ selectStop,+ addStop,+ removeStop,+ updateStopPosition,+ updateStopColor,+ updateStopOpacity,+ updateActiveColor,+ dragStop+} = useGradientStops(+ computed(() => fill),+ (updated) => emit('update', updated)+)+</script>++<template>+ <slot+ :stops="stops"+ :subtype="subtype"+ :subtypes="subtypes"+ :active-stop-index="activeStopIndex"+ :active-color="activeColor"+ :bar-background="barBackground"+ :set-subtype="setSubtype"+ :select-stop="selectStop"+ :add-stop="addStop"+ :remove-stop="removeStop"+ :update-stop-position="updateStopPosition"+ :update-stop-color="updateStopColor"+ :update-stop-opacity="updateStopOpacity"+ :update-active-color="updateActiveColor"+ :drag-stop="dragStop"+ />+</template>diff --git a/packages/vue/src/GradientEditor/GradientEditorStop.vue b/packages/vue/src/primitives/GradientEditor/GradientEditorStop.vuesimilarity index 66%rename from packages/vue/src/GradientEditor/GradientEditorStop.vuerename to packages/vue/src/primitives/GradientEditor/GradientEditorStop.vueindex dee41c25e..4aa2716d8 100644--- a/packages/vue/src/GradientEditor/GradientEditorStop.vue+++ b/packages/vue/src/primitives/GradientEditor/GradientEditorStop.vue@@ -1,10 +1,10 @@<script setup lang="ts">import { computed } from 'vue'-import { colorToCSS, colorToHexRaw } from '@open-pencil/core'+import { colorToCSS, colorToHexRaw } from '@open-pencil/core/color'-import type { GradientStop } from '@open-pencil/core'+import type { GradientStop } from '@open-pencil/core/scene-graph'-const props = defineProps<{+const { stop, index, active } = defineProps<{stop: GradientStopindex: numberactive: boolean@@ -18,10 +18,10 @@ const emit = defineEmits<{remove: [index: number]}>()-const positionPercent = computed(() => Math.round(props.stop.position * 100))-const opacityPercent = computed(() => Math.round(props.stop.color.a * 100))-const hex = computed(() => colorToHexRaw(props.stop.color))-const css = computed(() => colorToCSS(props.stop.color))+const positionPercent = computed(() => Math.round(stop.position * 100))+const opacityPercent = computed(() => Math.round(stop.color.a * 100))+const hex = computed(() => colorToHexRaw(stop.color))+const css = computed(() => colorToCSS(stop.color))</script><template>diff --git a/packages/vue/src/primitives/GradientEditor/index.ts b/packages/vue/src/primitives/GradientEditor/index.tsnew file mode 100644index 000000000..d6d89e505--- /dev/null+++ b/packages/vue/src/primitives/GradientEditor/index.ts@@ -0,0 +1,3 @@+export { default as GradientEditorRoot } from '#vue/primitives/GradientEditor/GradientEditorRoot.vue'+export { default as GradientEditorBar } from '#vue/primitives/GradientEditor/GradientEditorBar.vue'+export { default as GradientEditorStop } from '#vue/primitives/GradientEditor/GradientEditorStop.vue'diff --git a/packages/vue/src/GradientEditor/useGradientStops.ts b/packages/vue/src/primitives/GradientEditor/useGradientStops.tssimilarity index 94%rename from packages/vue/src/GradientEditor/useGradientStops.tsrename to packages/vue/src/primitives/GradientEditor/useGradientStops.tsindex 1c50101a3..5c9531522 100644--- a/packages/vue/src/GradientEditor/useGradientStops.ts+++ b/packages/vue/src/primitives/GradientEditor/useGradientStops.ts@@ -1,8 +1,9 @@import { computed, ref, type Ref } from 'vue'-import { colorToCSS, parseColor } from '@open-pencil/core'+import { colorToCSS, parseColor } from '@open-pencil/core/color'-import type { Color, Fill, GradientStop, GradientTransform } from '@open-pencil/core'+import type { Fill, GradientStop, GradientTransform } from '@open-pencil/core/scene-graph'+import type { Color } from '@open-pencil/core/types'type GradientSubtype =| 'GRADIENT_LINEAR'@@ -83,7 +84,6 @@ export function useGradientStops(fill: Ref<Fill>, onUpdate: (fill: Fill) => voidfunction updateStopColor(index: number, hex: string) {const color = parseColor(hex.startsWith('#') ? hex : `#${hex}`)- if (!color) returnconst s = [...stops.value]s[index] = { ...s[index], color: { ...color, a: s[index].color.a } }emitStops(s)diff --git a/packages/vue/src/LayerTree/LayerTreeItem.vue b/packages/vue/src/primitives/LayerTree/LayerTreeItem.vuesimilarity index 93%rename from packages/vue/src/LayerTree/LayerTreeItem.vuerename to packages/vue/src/primitives/LayerTree/LayerTreeItem.vueindex ebb59021b..018d9f750 100644--- a/packages/vue/src/LayerTree/LayerTreeItem.vue+++ b/packages/vue/src/primitives/LayerTree/LayerTreeItem.vue@@ -1,9 +1,9 @@<script setup lang="ts">import { computed, ref } from 'vue'-import { useLayerTree } from './context'+import { useLayerTree } from '#vue/primitives/LayerTree/context'-import type { LayerNode } from './context'+import type { LayerNode } from '#vue/primitives/LayerTree/context'const { node, level, hasChildren } = defineProps<{node: LayerNodediff --git a/packages/vue/src/LayerTree/LayerTreeRoot.vue b/packages/vue/src/primitives/LayerTree/LayerTreeRoot.vuesimilarity index 95%rename from packages/vue/src/LayerTree/LayerTreeRoot.vuerename to packages/vue/src/primitives/LayerTree/LayerTreeRoot.vueindex 53e96b503..33361ddee 100644--- a/packages/vue/src/LayerTree/LayerTreeRoot.vue+++ b/packages/vue/src/primitives/LayerTree/LayerTreeRoot.vue@@ -1,10 +1,10 @@<script setup lang="ts">import { computed, nextTick, ref, watch } from 'vue'-import { useEditor } from '@open-pencil/vue/context/editorContext'-import { provideLayerTree } from './context'+import { useEditor } from '#vue/editor/context'+import { provideLayerTree } from '#vue/primitives/LayerTree/context'-import type { LayerNode } from './context'+import type { LayerNode } from '#vue/primitives/LayerTree/context'const { indentPerLevel = 16 } = defineProps<{indentPerLevel?: numberdiff --git a/packages/vue/src/LayerTree/context.ts b/packages/vue/src/primitives/LayerTree/context.tssimilarity index 91%rename from packages/vue/src/LayerTree/context.tsrename to packages/vue/src/primitives/LayerTree/context.tsindex e4995632c..6054d0cd4 100644--- a/packages/vue/src/LayerTree/context.ts+++ b/packages/vue/src/primitives/LayerTree/context.ts@@ -1,7 +1,6 @@-import { type InjectionKey, inject, provide } from 'vue'+import { type ComputedRef, type InjectionKey, type Ref, inject, provide } from 'vue'import type { Editor } from '@open-pencil/core/editor'-import type { ComputedRef, Ref } from 'vue'export interface LayerNode {id: stringdiff --git a/packages/vue/src/primitives/LayerTree/index.ts b/packages/vue/src/primitives/LayerTree/index.tsnew file mode 100644index 000000000..3285bd2f5--- /dev/null+++ b/packages/vue/src/primitives/LayerTree/index.ts@@ -0,0 +1,4 @@+export { default as LayerTreeRoot } from '#vue/primitives/LayerTree/LayerTreeRoot.vue'+export { default as LayerTreeItem } from '#vue/primitives/LayerTree/LayerTreeItem.vue'+export { useLayerTree } from '#vue/primitives/LayerTree/context'+export type { LayerTreeContext, LayerNode } from '#vue/primitives/LayerTree/context'diff --git a/packages/vue/src/LayerTree/useLayerDrag.ts b/packages/vue/src/primitives/LayerTree/useLayerDrag.tssimilarity index 94%rename from packages/vue/src/LayerTree/useLayerDrag.tsrename to packages/vue/src/primitives/LayerTree/useLayerDrag.tsindex 7e7d53d7f..2156ccf99 100644--- a/packages/vue/src/LayerTree/useLayerDrag.ts+++ b/packages/vue/src/primitives/LayerTree/useLayerDrag.ts@@ -1,7 +1,6 @@import {attachInstruction,extractInstruction,- type Instruction,type ItemMode} from '@atlaskit/pragmatic-drag-and-drop-hitbox/tree-item'import { combine } from '@atlaskit/pragmatic-drag-and-drop/combine'@@ -21,10 +20,7 @@ interface DragItem {parentId: string | null}-type TreeInstruction = Extract<- Instruction,- { type: 'reorder-above' | 'reorder-below' | 'make-child' }->+type TreeInstruction = { type: 'reorder-above' | 'reorder-below' | 'make-child' }export function useLayerDrag(editor: Editor, indentPerLevel = 16) {const draggingId = ref<string | null>(null)@@ -89,7 +85,7 @@ export function useLayerDrag(editor: Editor, indentPerLevel = 16) {const cleanupMonitor = monitorForElements({onDrop: ({ source, location }) => {- const target = location.current.dropTargets[0]+ const target = location.current.dropTargets.at(0)if (!target) returnconst sourceId = source.data.id as string@@ -110,7 +106,7 @@ export function useLayerDrag(editor: Editor, indentPerLevel = 16) {editor.reorderChildWithUndo(sourceId, targetParentId, targetIndex)} else if (inst.type === 'reorder-below') {editor.reorderChildWithUndo(sourceId, targetParentId, targetIndex + 1)- } else if (inst.type === 'make-child') {+ } else {const container = editor.graph.getNode(targetId)editor.reorderChildWithUndo(sourceId, targetId, container?.childIds.length ?? 0)}diff --git a/packages/vue/src/LayoutControls/LayoutControlsRoot.vue b/packages/vue/src/primitives/LayoutControls/LayoutControlsRoot.vuesimilarity index 81%rename from packages/vue/src/LayoutControls/LayoutControlsRoot.vuerename to packages/vue/src/primitives/LayoutControls/LayoutControlsRoot.vueindex bc8e5cc68..cd4bc4b7a 100644--- a/packages/vue/src/LayoutControls/LayoutControlsRoot.vue+++ b/packages/vue/src/primitives/LayoutControls/LayoutControlsRoot.vue@@ -1,7 +1,10 @@<script setup lang="ts">-import { useLayout } from '@open-pencil/vue/controls/useLayout'+import { useLayout } from '#vue/controls/layout/use'+import { provideLayoutControls } from '#vue/primitives/LayoutControls/context'+import { proxyRefs } from 'vue'const ctx = useLayout()+provideLayoutControls(proxyRefs(ctx) as ReturnType<typeof proxyRefs<typeof ctx>> & { node: NonNullable<typeof ctx.node.value> })</script><template>diff --git a/packages/vue/src/primitives/LayoutControls/context.ts b/packages/vue/src/primitives/LayoutControls/context.tsnew file mode 100644index 000000000..dbb6f1ae2--- /dev/null+++ b/packages/vue/src/primitives/LayoutControls/context.ts@@ -0,0 +1,20 @@+import { inject, provide } from 'vue'++import type { SceneNode } from '@open-pencil/core/scene-graph'+import type { useLayout } from '#vue/controls/layout/use'+import type { InjectionKey, ShallowUnwrapRef } from 'vue'++type RawLayoutControlsContext = ShallowUnwrapRef<ReturnType<typeof useLayout>>+export type LayoutControlsContext = Omit<RawLayoutControlsContext, 'node'> & { node: SceneNode }++const LAYOUT_CONTROLS_KEY: InjectionKey<LayoutControlsContext> = Symbol('LayoutControlsContext')++export function provideLayoutControls(ctx: LayoutControlsContext) {+ provide(LAYOUT_CONTROLS_KEY, ctx)+}++export function useLayoutControlsContext(): LayoutControlsContext {+ const ctx = inject(LAYOUT_CONTROLS_KEY)+ if (!ctx) throw new Error('Layout controls must be used within LayoutControlsRoot')+ return ctx+}diff --git a/packages/vue/src/primitives/LayoutControls/index.ts b/packages/vue/src/primitives/LayoutControls/index.tsnew file mode 100644index 000000000..3bd5edbb0--- /dev/null+++ b/packages/vue/src/primitives/LayoutControls/index.ts@@ -0,0 +1,3 @@+export { default as LayoutControlsRoot } from '#vue/primitives/LayoutControls/LayoutControlsRoot.vue'+export { useLayoutControlsContext } from '#vue/primitives/LayoutControls/context'+export type { LayoutControlsContext } from '#vue/primitives/LayoutControls/context'diff --git a/packages/vue/src/PageList/PageListRoot.vue b/packages/vue/src/primitives/PageList/PageListRoot.vuesimilarity index 84%rename from packages/vue/src/PageList/PageListRoot.vuerename to packages/vue/src/primitives/PageList/PageListRoot.vueindex c2605c7b6..4e848fcb0 100644--- a/packages/vue/src/PageList/PageListRoot.vue+++ b/packages/vue/src/primitives/PageList/PageListRoot.vue@@ -1,9 +1,9 @@<script setup lang="ts">import { computed } from 'vue'-import { usePageList } from '@open-pencil/vue/PageList/usePageList'+import { usePageList } from '#vue/primitives/PageList/usePageList'-const props = defineProps<{+const { dividerPattern: customDividerPattern } = defineProps<{dividerPattern?: RegExp}>()@@ -16,7 +16,7 @@ const emit = defineEmits<{const { pages, currentPageId, switchPage, addPage, renamePage, deletePage } = usePageList()-const dividerPattern = computed(() => props.dividerPattern ?? /^[-–—*\s]+$/)+const dividerPattern = computed(() => customDividerPattern ?? /^[-–—*\s]+$/)function isDivider(page: { name: string; childIds: string[] }) {return page.childIds.length === 0 && dividerPattern.value.test(page.name)diff --git a/packages/vue/src/primitives/PageList/index.ts b/packages/vue/src/primitives/PageList/index.tsnew file mode 100644index 000000000..8e042f3a4--- /dev/null+++ b/packages/vue/src/primitives/PageList/index.ts@@ -0,0 +1 @@+export { default as PageListRoot } from '#vue/primitives/PageList/PageListRoot.vue'diff --git a/packages/vue/src/PageList/usePageList.ts b/packages/vue/src/primitives/PageList/usePageList.tssimilarity index 81%rename from packages/vue/src/PageList/usePageList.tsrename to packages/vue/src/primitives/PageList/usePageList.tsindex 2143ad352..ebdec212e 100644--- a/packages/vue/src/PageList/usePageList.ts+++ b/packages/vue/src/primitives/PageList/usePageList.ts@@ -1,8 +1,7 @@+import { useEditor } from '#vue/editor/context'+import { useSceneComputed } from '#vue/internal/scene-computed/use'import { computed } from 'vue'-import { useEditor } from '@open-pencil/vue/context/editorContext'-import { useSceneComputed } from '@open-pencil/vue/internal/useSceneComputed'-/*** Returns reactive page state and page-management actions.*diff --git a/packages/vue/src/PositionControls/PositionControlsRoot.vue b/packages/vue/src/primitives/PositionControls/PositionControlsRoot.vuesimilarity index 94%rename from packages/vue/src/PositionControls/PositionControlsRoot.vuerename to packages/vue/src/primitives/PositionControls/PositionControlsRoot.vueindex 446085e86..02f3f0608 100644--- a/packages/vue/src/PositionControls/PositionControlsRoot.vue+++ b/packages/vue/src/primitives/PositionControls/PositionControlsRoot.vue@@ -1,7 +1,7 @@<script setup lang="ts">import { computed } from 'vue'-import { MIXED, useNodeProps } from '@open-pencil/vue/controls/useNodeProps'+import { MIXED, useNodeProps } from '#vue/controls/node-props/use'const {updateProp,diff --git a/packages/vue/src/primitives/PositionControls/index.ts b/packages/vue/src/primitives/PositionControls/index.tsnew file mode 100644index 000000000..d3022fcb9--- /dev/null+++ b/packages/vue/src/primitives/PositionControls/index.ts@@ -0,0 +1 @@+export { default as PositionControlsRoot } from '#vue/primitives/PositionControls/PositionControlsRoot.vue'diff --git a/packages/vue/src/PropertyList/PropertyListItem.vue b/packages/vue/src/primitives/PropertyList/PropertyListItem.vuesimilarity index 92%rename from packages/vue/src/PropertyList/PropertyListItem.vuerename to packages/vue/src/primitives/PropertyList/PropertyListItem.vueindex 98a417789..52ddcb66e 100644--- a/packages/vue/src/PropertyList/PropertyListItem.vue+++ b/packages/vue/src/primitives/PropertyList/PropertyListItem.vue@@ -1,5 +1,5 @@<script setup lang="ts">-import { usePropertyList } from './context'+import { usePropertyList } from '#vue/primitives/PropertyList/context'const { index } = defineProps<{index: numberdiff --git a/packages/vue/src/PropertyList/PropertyListRoot.vue b/packages/vue/src/primitives/PropertyList/PropertyListRoot.vuesimilarity index 77%rename from packages/vue/src/PropertyList/PropertyListRoot.vuerename to packages/vue/src/primitives/PropertyList/PropertyListRoot.vueindex c43c9c032..167b3d2a0 100644--- a/packages/vue/src/PropertyList/PropertyListRoot.vue+++ b/packages/vue/src/primitives/PropertyList/PropertyListRoot.vue@@ -1,13 +1,13 @@<script setup lang="ts">import { computed } from 'vue'-import { useEditor } from '@open-pencil/vue/context/editorContext'-import { useNodeProps } from '@open-pencil/vue/controls/useNodeProps'-import { useUndoBatch } from '@open-pencil/vue/controls/useUndoBatch'-import { useSceneComputed } from '@open-pencil/vue/internal/useSceneComputed'-import { providePropertyList } from './context'+import { useEditor } from '#vue/editor/context'+import { useNodeProps } from '#vue/controls/node-props/use'+import { useUndoBatch } from '#vue/controls/undo-batch/use'+import { useSceneComputed } from '#vue/internal/scene-computed/use'+import { providePropertyList } from '#vue/primitives/PropertyList/context'-import type { Fill, Stroke, Effect, SceneNode } from '@open-pencil/core'+import type { Effect, Fill, SceneNode, Stroke } from '@open-pencil/core/scene-graph'type ArrayPropKey = 'fills' | 'strokes' | 'effects'type ArrayItemType = Fill | Stroke | Effect@@ -111,25 +111,23 @@ function toggleVisibility(index: number) {emit('toggleVisibility', index)const nodes = targetNodes()if (nodes.length === 0) return- if (nodes.length > 1) {- editor.undo.beginBatch(`Toggle ${propKey} visibility`)- }- for (const n of nodes) {- const liveNode = editor.getNode(n.id)- if (!liveNode) continue- const arr = liveNode[propKey] as Array<{ visible: boolean }>- if (!arr[index]) continue- const newArr = [...liveNode[propKey]] as Array<{ visible: boolean }>- newArr[index] = { ...newArr[index], visible: !arr[index].visible }- editor.updateNodeWithUndo(- n.id,- { [propKey]: newArr } as Partial<SceneNode>,- `Toggle ${propKey} visibility`- )- }- if (nodes.length > 1) {- editor.undo.commitBatch()+ const updateVisibility = () => {+ for (const n of nodes) {+ const liveNode = editor.getNode(n.id)+ if (!liveNode) continue+ const arr = liveNode[propKey] as Array<{ visible: boolean }>+ if (!arr[index]) continue+ const newArr = [...liveNode[propKey]] as Array<{ visible: boolean }>+ newArr[index] = { ...newArr[index], visible: !arr[index].visible }+ editor.updateNodeWithUndo(+ n.id,+ { [propKey]: newArr } as Partial<SceneNode>,+ `Toggle ${propKey} visibility`+ )+ }}+ if (nodes.length > 1) editor.undo.runBatch(`Toggle ${propKey} visibility`, updateVisibility)+ else updateVisibility()}providePropertyList({diff --git a/packages/vue/src/PropertyList/context.ts b/packages/vue/src/primitives/PropertyList/context.tssimilarity index 87%rename from packages/vue/src/PropertyList/context.tsrename to packages/vue/src/primitives/PropertyList/context.tsindex ac4fef4da..a2bf9bfdd 100644--- a/packages/vue/src/PropertyList/context.ts+++ b/packages/vue/src/primitives/PropertyList/context.ts@@ -1,8 +1,7 @@-import { type InjectionKey, inject, provide } from 'vue'+import { type ComputedRef, type InjectionKey, inject, provide } from 'vue'-import type { SceneNode } from '@open-pencil/core'+import type { SceneNode } from '@open-pencil/core/scene-graph'import type { Editor } from '@open-pencil/core/editor'-import type { ComputedRef } from 'vue'type ArrayPropKey = 'fills' | 'strokes' | 'effects'diff --git a/packages/vue/src/primitives/PropertyList/index.ts b/packages/vue/src/primitives/PropertyList/index.tsnew file mode 100644index 000000000..68bd746a6--- /dev/null+++ b/packages/vue/src/primitives/PropertyList/index.ts@@ -0,0 +1,4 @@+export { default as PropertyListRoot } from '#vue/primitives/PropertyList/PropertyListRoot.vue'+export { default as PropertyListItem } from '#vue/primitives/PropertyList/PropertyListItem.vue'+export { usePropertyList } from '#vue/primitives/PropertyList/context'+export type { PropertyListContext } from '#vue/primitives/PropertyList/context'diff --git a/packages/vue/src/ScrubInput/ScrubInputDisplay.vue b/packages/vue/src/primitives/ScrubInput/ScrubInputDisplay.vuesimilarity index 85%rename from packages/vue/src/ScrubInput/ScrubInputDisplay.vuerename to packages/vue/src/primitives/ScrubInput/ScrubInputDisplay.vueindex fc8cf6c94..02097bf69 100644--- a/packages/vue/src/ScrubInput/ScrubInputDisplay.vue+++ b/packages/vue/src/primitives/ScrubInput/ScrubInputDisplay.vue@@ -1,5 +1,5 @@<script setup lang="ts">-import { useScrubInput } from './context'+import { useScrubInput } from '#vue/primitives/ScrubInput/context'const ctx = useScrubInput()</script>diff --git a/packages/vue/src/ScrubInput/ScrubInputField.vue b/packages/vue/src/primitives/ScrubInput/ScrubInputField.vuesimilarity index 87%rename from packages/vue/src/ScrubInput/ScrubInputField.vuerename to packages/vue/src/primitives/ScrubInput/ScrubInputField.vueindex 621cdfea1..baaf235da 100644--- a/packages/vue/src/ScrubInput/ScrubInputField.vue+++ b/packages/vue/src/primitives/ScrubInput/ScrubInputField.vue@@ -1,5 +1,5 @@<script setup lang="ts">-import { useScrubInput } from './context'+import { useScrubInput } from '#vue/primitives/ScrubInput/context'const ctx = useScrubInput()</script>diff --git a/packages/vue/src/ScrubInput/ScrubInputRoot.vue b/packages/vue/src/primitives/ScrubInput/ScrubInputRoot.vuesimilarity index 70%rename from packages/vue/src/ScrubInput/ScrubInputRoot.vuerename to packages/vue/src/primitives/ScrubInput/ScrubInputRoot.vueindex 53b2cca5d..25d6404ae 100644--- a/packages/vue/src/ScrubInput/ScrubInputRoot.vue+++ b/packages/vue/src/primitives/ScrubInput/ScrubInputRoot.vue@@ -2,25 +2,23 @@import { ref, computed, toRef, watch } from 'vue'import { useEventListener } from '@vueuse/core'-import { provideScrubInput } from './context'--const props = withDefaults(- defineProps<{- modelValue: number | symbol- min?: number- max?: number- step?: number- sensitivity?: number- placeholder?: string- }>(),- {- min: -Infinity,- max: Infinity,- step: 1,- sensitivity: 1,- placeholder: 'Mixed'- }-)+import { provideScrubInput } from '#vue/primitives/ScrubInput/context'++const {+ modelValue,+ min = -Infinity,+ max = Infinity,+ step = 1,+ sensitivity = 1,+ placeholder = 'Mixed'+} = defineProps<{+ modelValue: number | symbol+ min?: number+ max?: number+ step?: number+ sensitivity?: number+ placeholder?: string+}>()const emit = defineEmits<{'update:modelValue': [value: number]@@ -32,8 +30,8 @@ const editing = ref(false)const scrubbing = ref(false)const inputRef = ref<HTMLInputElement | null>(null)-const isMixed = computed(() => typeof props.modelValue === 'symbol')-const numericValue = computed(() => (isMixed.value ? 0 : (props.modelValue as number)))+const isMixed = computed(() => typeof modelValue === 'symbol')+const numericValue = computed(() => (isMixed.value ? 0 : (modelValue as number)))const displayValue = computed(() => (isMixed.value ? '' : String(Math.round(numericValue.value))))let stopMove: (() => void) | undefined@@ -56,9 +54,9 @@ function startScrub(e: PointerEvent) {document.body.style.cursor = 'ew-resize'}if (hasMoved) {- accumulated += dx * props.step * props.sensitivity- const clamped = Math.round(Math.min(props.max, Math.max(props.min, accumulated)))- if (clamped !== props.modelValue) emit('update:modelValue', clamped)+ accumulated += dx * step * sensitivity+ const clamped = Math.round(Math.min(max, Math.max(min, accumulated)))+ if (clamped !== modelValue) emit('update:modelValue', clamped)}})@@ -68,8 +66,8 @@ function startScrub(e: PointerEvent) {stopMove?.()stopUp?.()if (hasMoved) {- if (typeof props.modelValue === 'number' && props.modelValue !== valueBeforeScrub) {- emit('commit', props.modelValue, valueBeforeScrub)+ if (typeof modelValue === 'number' && modelValue !== valueBeforeScrub) {+ emit('commit', modelValue, valueBeforeScrub)}} else {startEdit()@@ -94,7 +92,7 @@ function commitEdit(e: Event) {const previous = numericValue.valueediting.value = falseif (!Number.isNaN(val)) {- const clamped = Math.min(props.max, Math.max(props.min, val))+ const clamped = Math.min(max, Math.max(min, val))emit('update:modelValue', clamped)if (clamped !== previous) emit('commit', clamped, previous)}@@ -103,7 +101,7 @@ function commitEdit(e: Event) {function liveUpdate(e: Event) {const val = +(e.target as HTMLInputElement).valueif (!Number.isNaN(val)) {- const clamped = Math.min(props.max, Math.max(props.min, val))+ const clamped = Math.min(max, Math.max(min, val))emit('update:modelValue', clamped)}}@@ -114,7 +112,7 @@ function onKeydown(e: KeyboardEvent) {}const ctx = {- modelValue: toRef(props, 'modelValue'),+ modelValue: toRef(() => modelValue),displayValue,isMixed,editing,@@ -134,7 +132,7 @@ watch(editing, (v) => emit('editing-change', v))<template><slot- :model-value="props.modelValue"+ :model-value="modelValue":display-value="displayValue":is-mixed="isMixed":editing="editing"@@ -143,6 +141,6 @@ watch(editing, (v) => emit('editing-change', v)):start-edit="startEdit":commit-edit="commitEdit":keydown="onKeydown"- :placeholder="props.placeholder"+ :placeholder="placeholder"/></template>diff --git a/packages/vue/src/ScrubInput/context.ts b/packages/vue/src/primitives/ScrubInput/context.tssimilarity index 89%rename from packages/vue/src/ScrubInput/context.tsrename to packages/vue/src/primitives/ScrubInput/context.tsindex d93b8a943..5d1aff0c8 100644--- a/packages/vue/src/ScrubInput/context.ts+++ b/packages/vue/src/primitives/ScrubInput/context.ts@@ -1,6 +1,4 @@-import { type InjectionKey, inject, provide } from 'vue'--import type { Ref } from 'vue'+import { type InjectionKey, type Ref, inject, provide } from 'vue'export interface ScrubInputContext {modelValue: Ref<number | symbol>diff --git a/packages/vue/src/primitives/ScrubInput/index.ts b/packages/vue/src/primitives/ScrubInput/index.tsnew file mode 100644index 000000000..e9db2c06b--- /dev/null+++ b/packages/vue/src/primitives/ScrubInput/index.ts@@ -0,0 +1,5 @@+export { default as ScrubInputRoot } from '#vue/primitives/ScrubInput/ScrubInputRoot.vue'+export { default as ScrubInputField } from '#vue/primitives/ScrubInput/ScrubInputField.vue'+export { default as ScrubInputDisplay } from '#vue/primitives/ScrubInput/ScrubInputDisplay.vue'+export { useScrubInput } from '#vue/primitives/ScrubInput/context'+export type { ScrubInputContext } from '#vue/primitives/ScrubInput/context'diff --git a/packages/vue/src/Toolbar/ToolbarItem.vue b/packages/vue/src/primitives/Toolbar/ToolbarItem.vuesimilarity index 85%rename from packages/vue/src/Toolbar/ToolbarItem.vuerename to packages/vue/src/primitives/Toolbar/ToolbarItem.vueindex fe57effe0..90f7e6013 100644--- a/packages/vue/src/Toolbar/ToolbarItem.vue+++ b/packages/vue/src/primitives/Toolbar/ToolbarItem.vue@@ -1,7 +1,7 @@<script setup lang="ts">import { computed } from 'vue'-import { useToolbar } from './context'+import { useToolbar } from '#vue/primitives/Toolbar/context'import type { Tool } from '@open-pencil/core/editor'diff --git a/packages/vue/src/Toolbar/ToolbarRoot.vue b/packages/vue/src/primitives/Toolbar/ToolbarRoot.vuesimilarity index 89%rename from packages/vue/src/Toolbar/ToolbarRoot.vuerename to packages/vue/src/primitives/Toolbar/ToolbarRoot.vueindex c33b49797..6fdc56df7 100644--- a/packages/vue/src/Toolbar/ToolbarRoot.vue+++ b/packages/vue/src/primitives/Toolbar/ToolbarRoot.vue@@ -2,8 +2,8 @@import { ref, computed } from 'vue'import { EDITOR_TOOLS } from '@open-pencil/core/editor'-import { useEditor } from '@open-pencil/vue/context/editorContext'-import { provideToolbar } from './context'+import { useEditor } from '#vue/editor/context'+import { provideToolbar } from '#vue/primitives/Toolbar/context'import type { EditorToolDef, Tool } from '@open-pencil/core/editor'diff --git a/packages/vue/src/Toolbar/context.ts b/packages/vue/src/primitives/Toolbar/context.tssimilarity index 86%rename from packages/vue/src/Toolbar/context.tsrename to packages/vue/src/primitives/Toolbar/context.tsindex 4a30bc25f..ca5feaef1 100644--- a/packages/vue/src/Toolbar/context.ts+++ b/packages/vue/src/primitives/Toolbar/context.ts@@ -1,7 +1,6 @@-import { type InjectionKey, inject, provide } from 'vue'+import { type ComputedRef, type InjectionKey, type Ref, inject, provide } from 'vue'import type { Editor, EditorToolDef, Tool } from '@open-pencil/core/editor'-import type { ComputedRef, Ref } from 'vue'export interface ToolbarContext {editor: Editordiff --git a/packages/vue/src/primitives/Toolbar/index.ts b/packages/vue/src/primitives/Toolbar/index.tsnew file mode 100644index 000000000..92be543f9--- /dev/null+++ b/packages/vue/src/primitives/Toolbar/index.ts@@ -0,0 +1,4 @@+export { default as ToolbarRoot } from '#vue/primitives/Toolbar/ToolbarRoot.vue'+export { default as ToolbarItem } from '#vue/primitives/Toolbar/ToolbarItem.vue'+export { useToolbar } from '#vue/primitives/Toolbar/context'+export type { ToolbarContext } from '#vue/primitives/Toolbar/context'diff --git a/packages/vue/src/Toolbar/useToolbarState.ts b/packages/vue/src/primitives/Toolbar/useToolbarState.tssimilarity index 100%rename from packages/vue/src/Toolbar/useToolbarState.tsrename to packages/vue/src/primitives/Toolbar/useToolbarState.tsdiff --git a/packages/vue/src/TypographyControls/TypographyControlsRoot.vue b/packages/vue/src/primitives/TypographyControls/TypographyControlsRoot.vuesimilarity index 77%rename from packages/vue/src/TypographyControls/TypographyControlsRoot.vuerename to packages/vue/src/primitives/TypographyControls/TypographyControlsRoot.vueindex 7a77577ce..1ecb19865 100644--- a/packages/vue/src/TypographyControls/TypographyControlsRoot.vue+++ b/packages/vue/src/primitives/TypographyControls/TypographyControlsRoot.vue@@ -1,13 +1,13 @@<script setup lang="ts">-import { useTypography } from '@open-pencil/vue/controls/useTypography'+import { useTypography } from '#vue/controls/typography/use'import type { AcceptableValue } from 'reka-ui'-const props = defineProps<{+const { loadFont } = defineProps<{loadFont?: (family: string, style: string) => Promise<unknown>}>()-const ctx = useTypography({ loadFont: props.loadFont })+const ctx = useTypography({ loadFont })function onAlignChange(val: AcceptableValue) {if (val) ctx.setAlign(val as 'LEFT' | 'CENTER' | 'RIGHT')@@ -32,5 +32,8 @@ function onFormattingChange(val: AcceptableValue | AcceptableValue[]) {:commit-prop="ctx.commitProp":on-align-change="onAlignChange":on-formatting-change="onFormattingChange"+ :toggle-bold="ctx.toggleBold"+ :toggle-italic="ctx.toggleItalic"+ :toggle-decoration="ctx.toggleDecoration"/></template>diff --git a/packages/vue/src/primitives/TypographyControls/index.ts b/packages/vue/src/primitives/TypographyControls/index.tsnew file mode 100644index 000000000..d46cfb81b--- /dev/null+++ b/packages/vue/src/primitives/TypographyControls/index.ts@@ -0,0 +1 @@+export { default as TypographyControlsRoot } from '#vue/primitives/TypographyControls/TypographyControlsRoot.vue'diff --git a/packages/vue/src/selection/useSelectionCapabilities.ts b/packages/vue/src/selection/useSelectionCapabilities.tsdeleted file mode 100644index fac4514aa..000000000--- a/packages/vue/src/selection/useSelectionCapabilities.ts+++ /dev/null@@ -1,79 +0,0 @@-import { computed } from 'vue'--import { useSceneComputed } from '@open-pencil/vue/internal/useSceneComputed'-import { useSelectionState } from '@open-pencil/vue/selection/useSelectionState'--/**- * Returns reactive booleans describing which selection-dependent actions are- * currently available.- *- * This is useful for menus, toolbars, shortcuts, and action buttons that need- * command-friendly capability checks.- */-export function useSelectionCapabilities() {- const {- editor,- selectedIds,- selectedNode,- selectedCount,- hasSelection,- isInstance,- isGroup,- canCreateComponentSet- } = useSelectionState()-- const canCopy = computed(() => hasSelection.value)- const canCut = computed(() => hasSelection.value)- const canDelete = computed(() => hasSelection.value)- const canDuplicate = computed(() => hasSelection.value)- const canExportSelection = computed(() => hasSelection.value)- const canGroup = computed(() => selectedCount.value >= 2)- const canUngroup = computed(() => isGroup.value)- const canCreateComponent = computed(() => hasSelection.value)- const canDetachInstance = computed(() => isInstance.value)- const canWrapInAutoLayout = computed(() => hasSelection.value)- const canBringToFront = computed(() => hasSelection.value)- const canSendToBack = computed(() => hasSelection.value)- const canToggleVisibility = computed(() => hasSelection.value)- const canToggleLock = computed(() => hasSelection.value)- const canGoToMainComponent = computed(() => isInstance.value)- const canCreateInstance = computed(() => selectedNode.value?.type === 'COMPONENT')- const canMoveToPage = useSceneComputed(- () => hasSelection.value && editor.graph.getPages().length > 1- )- const canPaste = computed(() => true)- const canSelectAll = useSceneComputed(- () => editor.graph.getChildren(editor.state.currentPageId).length > 0- )- const canUndo = computed(() => editor.undo.canUndo)- const canRedo = computed(() => editor.undo.canRedo)- const canZoomToSelection = computed(() => hasSelection.value)-- return {- selectedIds,- selectedNode,- canCopy,- canCut,- canPaste,- canDelete,- canDuplicate,- canExportSelection,- canGroup,- canUngroup,- canCreateComponent,- canCreateComponentSet,- canDetachInstance,- canWrapInAutoLayout,- canBringToFront,- canSendToBack,- canToggleVisibility,- canToggleLock,- canGoToMainComponent,- canCreateInstance,- canMoveToPage,- canSelectAll,- canUndo,- canRedo,- canZoomToSelection- }-}diff --git a/packages/vue/src/shared/useFontStatus.ts b/packages/vue/src/shared/font-status/use.tssimilarity index 78%rename from packages/vue/src/shared/useFontStatus.tsrename to packages/vue/src/shared/font-status/use.tsindex aea91eb5b..4ef5f2615 100644--- a/packages/vue/src/shared/useFontStatus.ts+++ b/packages/vue/src/shared/font-status/use.ts@@ -1,8 +1,9 @@import { computed } from 'vue'-import { isFontLoaded, DEFAULT_FONT_FAMILY } from '@open-pencil/core'+import { DEFAULT_FONT_FAMILY } from '@open-pencil/core/constants'+import { isFontLoaded } from '@open-pencil/core/text'-import type { SceneNode } from '@open-pencil/core'+import type { SceneNode } from '@open-pencil/core/scene-graph'/*** Returns missing-font information for a text node getter.@@ -13,7 +14,7 @@ import type { SceneNode } from '@open-pencil/core'export function useNodeFontStatus(node: () => SceneNode | null | undefined) {const missingFonts = computed(() => {const n = node()- if (!n || n.type !== 'TEXT') return []+ if (n?.type !== 'TEXT') return []const families = new Set<string>()families.add(n.fontFamily || DEFAULT_FONT_FAMILY)diff --git a/packages/vue/src/shared/gesture/wheel.ts b/packages/vue/src/shared/gesture/wheel.tsnew file mode 100644index 000000000..f6f3303fc--- /dev/null+++ b/packages/vue/src/shared/gesture/wheel.ts@@ -0,0 +1,30 @@+import { WheelGesture } from '@use-gesture/vanilla'+import { watch, shallowRef, onScopeDispose } from 'vue'++import type { EventTypes, Handler, UserWheelConfig } from '@use-gesture/vanilla'+import type { Ref } from 'vue'++export function useWheelGesture(+ target: Ref<EventTarget | null>,+ handler: Handler<'wheel', EventTypes['wheel']>,+ config?: UserWheelConfig+) {+ const gesture = shallowRef<WheelGesture | null>(null)++ const stop = watch(+ target,+ (element) => {+ gesture.value?.destroy()+ gesture.value = element ? new WheelGesture(element, handler, config) : null+ },+ { immediate: true }+ )++ onScopeDispose(() => {+ stop()+ gesture.value?.destroy()+ gesture.value = null+ })++ return gesture+}diff --git a/packages/vue/src/shared/input/auto-layout.ts b/packages/vue/src/shared/input/auto-layout.tsindex e98e02744..624b65ec5 100644--- a/packages/vue/src/shared/input/auto-layout.ts+++ b/packages/vue/src/shared/input/auto-layout.ts@@ -1,8 +1,9 @@-import { resolveNodeLayoutDirection } from '@open-pencil/core'+import { resolveNodeLayoutDirection } from '@open-pencil/core/text'-import type { DragMove } from './types'-import type { SceneNode, Vector } from '@open-pencil/core'+import type { DragMove } from '#vue/shared/input/types'import type { Editor } from '@open-pencil/core/editor'+import type { SceneNode } from '@open-pencil/core/scene-graph'+import type { Vector } from '@open-pencil/core/types'function resolveLayoutDirection(parent: SceneNode, editor: Editor): 'LTR' | 'RTL' {const ancestor = parent.parentId ? editor.graph.getNode(parent.parentId) : nulldiff --git a/packages/vue/src/shared/input/click-count.ts b/packages/vue/src/shared/input/click-count.tsnew file mode 100644index 000000000..826251aee--- /dev/null+++ b/packages/vue/src/shared/input/click-count.ts@@ -0,0 +1,32 @@+const MULTI_CLICK_DELAY = 500+const MULTI_CLICK_RADIUS = 5++export function createClickCounter() {+ let lastClickTime = 0+ let lastClickX = 0+ let lastClickY = 0+ let clickCount = 0++ function recordClick(sx: number, sy: number) {+ const now = performance.now()+ if (+ now - lastClickTime < MULTI_CLICK_DELAY &&+ Math.abs(sx - lastClickX) < MULTI_CLICK_RADIUS &&+ Math.abs(sy - lastClickY) < MULTI_CLICK_RADIUS+ ) {+ clickCount+++ } else {+ clickCount = 1+ }+ lastClickTime = now+ lastClickX = sx+ lastClickY = sy+ return clickCount+ }++ function getClickCount() {+ return clickCount+ }++ return { recordClick, getClickCount }+}diff --git a/packages/vue/src/shared/input/draw.ts b/packages/vue/src/shared/input/draw.tsindex 6249b315e..217f3916d 100644--- a/packages/vue/src/shared/input/draw.ts+++ b/packages/vue/src/shared/input/draw.ts@@ -1,6 +1,34 @@-import type { DragDraw } from './types'+import { DEFAULT_TEXT_HEIGHT, DEFAULT_TEXT_WIDTH } from '@open-pencil/core/constants'++import { TOOL_TO_NODE } from '#vue/shared/input/types'++import type { DragDraw, DragState } from '#vue/shared/input/types'import type { Editor } from '@open-pencil/core/editor'+export function startTextTool(cx: number, cy: number, editor: Editor) {+ const nodeId = editor.createShape('TEXT', cx, cy, DEFAULT_TEXT_WIDTH, DEFAULT_TEXT_HEIGHT)+ editor.graph.updateNode(nodeId, { text: '' })+ editor.select([nodeId])+ editor.startTextEditing(nodeId)+ editor.setTool('SELECT')+ editor.requestRender()+}++export function startShapeDraw(+ cx: number,+ cy: number,+ editor: Editor,+ setDrag: (d: DragState) => void+) {+ const nodeType = TOOL_TO_NODE[editor.state.activeTool]+ if (!nodeType) return++ editor.undo.beginBatch('Create shape')+ const nodeId = editor.createShape(nodeType, cx, cy, 0, 0)+ editor.select([nodeId])+ setDrag({ type: 'draw', startX: cx, startY: cy, nodeId })+}+export function handleDrawMove(d: DragDraw,cx: number,diff --git a/packages/vue/src/shared/input/drop-target.ts b/packages/vue/src/shared/input/drop-target.tsnew file mode 100644index 000000000..18e5833cf--- /dev/null+++ b/packages/vue/src/shared/input/drop-target.ts@@ -0,0 +1,38 @@+import type { Editor } from '@open-pencil/core/editor'+import type { SceneNode } from '@open-pencil/core/scene-graph'++export function findMoveDropTarget(cx: number, cy: number, editor: Editor): SceneNode | null {+ let dropTarget = editor.graph.hitTestFrame(+ cx,+ cy,+ editor.state.selectedIds,+ editor.state.currentPageId+ )+ const movingSection = [...editor.state.selectedIds].some(+ (id) => editor.graph.getNode(id)?.type === 'SECTION'+ )+ if (+ movingSection &&+ dropTarget &&+ dropTarget.type !== 'SECTION' &&+ dropTarget.type !== 'CANVAS'+ ) {+ dropTarget = null+ }+ return dropTarget+}++export function reparentOutsideNodes(editor: Editor) {+ for (const id of editor.state.selectedIds) {+ const node = editor.graph.getNode(id)+ if (!node?.parentId || editor.isTopLevel(node.parentId)) continue+ const parent = editor.graph.getNode(node.parentId)+ if (!parent || (parent.type !== 'FRAME' && parent.type !== 'SECTION')) continue+ const outsideX = node.x + node.width < 0 || node.x > parent.width+ const outsideY = node.y + node.height < 0 || node.y > parent.height+ if (outsideX || outsideY) {+ const grandparentId = parent.parentId ?? editor.state.currentPageId+ editor.graph.reparentNode(id, grandparentId)+ }+ }+}diff --git a/packages/vue/src/shared/input/duplicate-drag.ts b/packages/vue/src/shared/input/duplicate-drag.tsnew file mode 100644index 000000000..72d10c51a--- /dev/null+++ b/packages/vue/src/shared/input/duplicate-drag.ts@@ -0,0 +1,42 @@+import type { DragState } from '#vue/shared/input/types'+import type { Editor } from '@open-pencil/core/editor'++type DragOriginal = { x: number; y: number; parentId: string }++export function duplicateAndDrag(+ cx: number,+ cy: number,+ editor: Editor+): { originals: Map<string, DragOriginal>; drag: DragState } {+ const previousSelection = new Set(editor.state.selectedIds)+ const newIds: string[] = []+ const newOriginals = new Map<string, DragOriginal>()+ for (const id of previousSelection) {+ const source = editor.graph.getNode(id)+ if (!source) continue+ const parentId = source.parentId ?? editor.state.currentPageId+ const clone = editor.graph.cloneTree(id, parentId, { name: source.name + ' copy' })+ if (!clone) continue+ newIds.push(clone.id)+ newOriginals.set(clone.id, {+ x: source.x,+ y: source.y,+ parentId+ })+ }+ editor.select(newIds)+ editor.requestRender()+ return {+ originals: newOriginals,+ drag: {+ type: 'move',+ startX: cx,+ startY: cy,+ currentX: cx,+ currentY: cy,+ originals: newOriginals,+ duplicated: true,+ duplicatedPreviousSelection: previousSelection+ }+ }+}diff --git a/packages/vue/src/shared/input/geometry.ts b/packages/vue/src/shared/input/geometry.tsindex 502ba8ab5..9e3b9cc7f 100644--- a/packages/vue/src/shared/input/geometry.ts+++ b/packages/vue/src/shared/input/geometry.ts@@ -1,15 +1,87 @@-import {- CORNER_ROTATE_ZONE,- getAbsoluteRotation,- getWorldHandles,- HANDLE_HIT_RADIUS-} from '@open-pencil/core'+import resizeCursorSvg from '#vue/shared/assets/resize-cursor.svg?raw'+import rotateCursorSvg from '#vue/shared/assets/rotate-cursor.svg?raw'-import resizeCursorSvg from '../assets/resize-cursor.svg?raw'-import rotateCursorSvg from '../assets/rotate-cursor.svg?raw'+import { getAbsoluteRotation, getWorldHandles } from '@open-pencil/core/canvas'+import { CORNER_ROTATE_ZONE, HANDLE_HIT_RADIUS } from '@open-pencil/core/constants'+import { degToRad } from '@open-pencil/core/geometry'-import type { CornerPosition, HandlePosition } from './types'-import type { Vector, SceneGraph, SceneNode } from '@open-pencil/core'+import type { CornerPosition, HandlePosition } from '#vue/shared/input/types'+import type { Editor } from '@open-pencil/core/editor'+import type { SceneGraph, SceneNode } from '@open-pencil/core/scene-graph'+import type { Vector } from '@open-pencil/core/types'++export function getPointerCoords(e: MouseEvent, canvas: HTMLCanvasElement | null, editor: Editor) {+ if (!canvas) return { sx: 0, sy: 0, cx: 0, cy: 0 }+ const rect = canvas.getBoundingClientRect()+ const sx = e.clientX - rect.left+ const sy = e.clientY - rect.top+ const { x: cx, y: cy } = editor.screenToCanvas(sx, sy)+ return { sx, sy, cx, cy }+}++export function canvasToLocalPoint(+ cx: number,+ cy: number,+ scopeId: string,+ editor: Editor+): { lx: number; ly: number } {+ const node = editor.graph.getNode(scopeId)+ if (!node) return { lx: cx, ly: cy }+ const abs = editor.graph.getAbsolutePosition(scopeId)+ let dx = cx - abs.x+ let dy = cy - abs.y+ if (node.rotation !== 0) {+ const hw = node.width / 2+ const hh = node.height / 2+ const rad = degToRad(-node.rotation)+ const cos = Math.cos(rad)+ const sin = Math.sin(rad)+ const rx = dx - hw+ const ry = dy - hh+ dx = rx * cos - ry * sin + hw+ dy = rx * sin + ry * cos + hh+ }+ return { lx: dx, ly: dy }+}++export function hitTestInEditorScope(+ cx: number,+ cy: number,+ deep: boolean,+ editor: Editor,+ canvasToLocal: (cx: number, cy: number, scopeId: string) => { lx: number; ly: number }+): SceneNode | null {+ const scopeId = editor.state.enteredContainerId++ const renderer = editor.renderer+ if (!renderer) return null+ if (scopeId) {+ if (!editor.graph.getNode(scopeId)) {+ editor.state.enteredContainerId = null+ } else {+ const { lx, ly } = canvasToLocal(cx, cy, scopeId)+ return deep+ ? editor.graph.hitTestDeep(lx, ly, scopeId)+ : editor.graph.hitTest(lx, ly, scopeId)+ }+ }+ return deep+ ? editor.graph.hitTestDeep(cx, cy, editor.state.currentPageId)+ : editor.graph.hitTest(cx, cy, editor.state.currentPageId)+}++export function isInsideEditorContainerBounds(+ cx: number,+ cy: number,+ containerId: string,+ editor: Editor,+ canvasToLocal: (cx: number, cy: number, scopeId: string) => { lx: number; ly: number }+): boolean {+ const container = editor.graph.getNode(containerId)+ if (!container) return false+ const { lx, ly } = canvasToLocal(cx, cy, containerId)+ return lx >= 0 && lx <= container.width && ly >= 0 && ly <= container.height+}export function getScreenRect(absX: number,@@ -113,8 +185,6 @@ export function getHitHandleByMatrix(const handleKey = key as HandlePositionconst p = handles[handleKey]- if (!p) continue-const dx = cx - p.xconst dy = cy - p.y@@ -130,6 +200,29 @@ export function getHitHandleByMatrix(return null}+export function hitTestTopRotationHandleByMatrix(+ cx: number,+ cy: number,+ node: SceneNode,+ graph: SceneGraph,+ zoom: number = 1+): boolean {+ const handles = getWorldHandles(node, graph)+ const rotation = getAbsoluteRotation(node, graph)+ const topMidX = (handles.nw.x + handles.ne.x) / 2+ const topMidY = (handles.nw.y + handles.ne.y) / 2+ const distance = 24 / zoom+ const rad = degToRad(rotation - 90)+ const handle = {+ x: topMidX + Math.cos(rad) * distance,+ y: topMidY + Math.sin(rad) * distance+ }+ const radius = HANDLE_HIT_RADIUS / zoom+ const dx = cx - handle.x+ const dy = cy - handle.y+ return dx * dx + dy * dy <= radius * radius+}+export function hitTestCornerRotationByMatrix(cx: number,cy: number,@@ -142,7 +235,7 @@ export function hitTestCornerRotationByMatrix(const HANDLE_R = HANDLE_HIT_RADIUS / zoomconst ROTATE_R = CORNER_ROTATE_ZONE / zoom- const corners: Array<{ key: CornerPosition; p: { x: number; y: number } }> = [+ const corners: Array<{ key: CornerPosition; p: Vector }> = [{ key: 'nw', p: handles.nw },{ key: 'ne', p: handles.ne },{ key: 'se', p: handles.se },@@ -206,7 +299,7 @@ export function cornerRotationCursor(corner: CornerPosition, nodeRotation = 0):export function buildResizeCursor(angleDeg: number): string {const normalized = ((Math.round(angleDeg) % 360) + 360) % 360- let svg = resizeCursorSvg+ const svg = resizeCursorSvg.replace('<path',`<g transform='translate(512 512) rotate(${normalized}) translate(-512 -512)'><path`diff --git a/packages/vue/src/shared/input/gesture.ts b/packages/vue/src/shared/input/gesture.tsnew file mode 100644index 000000000..fd710e514--- /dev/null+++ b/packages/vue/src/shared/input/gesture.ts@@ -0,0 +1,57 @@+import { useEventListener } from '@vueuse/core'++import { createRafScheduler } from '#vue/shared/input/raf-scheduler'++import type { Editor } from '@open-pencil/core/editor'+import type { Ref } from 'vue'++export function setupSafariGestureZoom(canvasRef: Ref<HTMLCanvasElement | null>, editor: Editor) {+ let gestureStartZoom = 1+ let pendingGesture: { scale: number; sx: number; sy: number } | null = null++ function flushGesture() {+ if (!pendingGesture) return+ editor.setHoveredNode(null)+ const { scale, sx, sy } = pendingGesture+ pendingGesture = null+ editor.setZoomAroundPoint(gestureStartZoom * scale, sx, sy)+ }++ const gestureScheduler = createRafScheduler(flushGesture)++ useEventListener(+ canvasRef,+ 'gesturestart' as keyof HTMLElementEventMap,+ (e: Event) => {+ e.preventDefault()+ gestureStartZoom = editor.state.zoom+ },+ { passive: false }+ )+ useEventListener(+ canvasRef,+ 'gesturechange' as keyof HTMLElementEventMap,+ (e: Event) => {+ e.preventDefault()+ const ge = e as GestureEvent+ const canvas = canvasRef.value+ if (!canvas) return+ const rect = canvas.getBoundingClientRect()+ pendingGesture = {+ scale: ge.scale,+ sx: ge.clientX - rect.left,+ sy: ge.clientY - rect.top+ }+ gestureScheduler.schedule()+ },+ { passive: false }+ )+ useEventListener(+ canvasRef,+ 'gestureend' as keyof HTMLElementEventMap,+ (e: Event) => {+ e.preventDefault()+ },+ { passive: false }+ )+}diff --git a/packages/vue/src/shared/input/move-snap.ts b/packages/vue/src/shared/input/move-snap.tsnew file mode 100644index 000000000..d6426c036--- /dev/null+++ b/packages/vue/src/shared/input/move-snap.ts@@ -0,0 +1,53 @@+import { computeSelectionBounds, computeSnap } from '@open-pencil/core/scene-graph'++import type { DragMove } from '#vue/shared/input/types'+import type { Editor } from '@open-pencil/core/editor'+import type { SceneNode } from '@open-pencil/core/scene-graph'++export function applyMoveSnap(+ d: DragMove,+ dx: number,+ dy: number,+ editor: Editor+): { dx: number; dy: number } {+ const selectedNodes: SceneNode[] = []+ for (const [id, orig] of d.originals) {+ const node = editor.graph.getNode(id)+ if (node) {+ const abs = editor.graph.getAbsolutePosition(id)+ const parentAbs = node.parentId+ ? editor.graph.getAbsolutePosition(node.parentId)+ : { x: 0, y: 0 }+ selectedNodes.push({+ ...node,+ x: abs.x - parentAbs.x - node.x + orig.x + dx,+ y: abs.y - parentAbs.y - node.y + orig.y + dy+ })+ }+ }++ const bounds = computeSelectionBounds(selectedNodes)+ if (!bounds) return { dx, dy }++ const firstId = [...d.originals.keys()][0]+ const firstNode = editor.graph.getNode(firstId)+ const parentId = firstNode?.parentId ?? editor.state.currentPageId+ const siblings = editor.graph.getChildren(parentId)+ const parentAbs = !editor.isTopLevel(parentId)+ ? editor.graph.getAbsolutePosition(parentId)+ : { x: 0, y: 0 }+ const absTargets = siblings.map((node) => ({+ ...node,+ x: node.x + parentAbs.x,+ y: node.y + parentAbs.y+ }))+ const absBounds = {+ x: bounds.x + parentAbs.x,+ y: bounds.y + parentAbs.y,+ width: bounds.width,+ height: bounds.height+ }+ const snap = computeSnap(editor.state.selectedIds, absBounds, absTargets)+ editor.setSnapGuides(snap.guides)+ return { dx: dx + snap.dx, dy: dy + snap.dy }+}diff --git a/packages/vue/src/shared/input/move.ts b/packages/vue/src/shared/input/move.tsindex 12d8bf3ad..f7129450c 100644--- a/packages/vue/src/shared/input/move.ts+++ b/packages/vue/src/shared/input/move.ts@@ -1,9 +1,14 @@-import { AUTO_LAYOUT_BREAK_THRESHOLD, computeSelectionBounds, computeSnap } from '@open-pencil/core'+import {+ computeAutoLayoutIndicator,+ computeAutoLayoutIndicatorForFrame+} from '#vue/shared/input/auto-layout'+import { findMoveDropTarget, reparentOutsideNodes } from '#vue/shared/input/drop-target'+export { duplicateAndDrag } from '#vue/shared/input/duplicate-drag'+import { applyMoveSnap } from '#vue/shared/input/move-snap'-import { computeAutoLayoutIndicator, computeAutoLayoutIndicatorForFrame } from './auto-layout'+import { AUTO_LAYOUT_BREAK_THRESHOLD } from '@open-pencil/core/constants'-import type { DragMove, DragState } from './types'-import type { SceneNode } from '@open-pencil/core'+import type { DragMove } from '#vue/shared/input/types'import type { Editor } from '@open-pencil/core/editor'const AUTO_LAYOUT_REORDER_CLICK_SLOP = 3@@ -20,109 +25,6 @@ export function detectAutoLayoutParent(editor: Editor): string | undefined {return undefined}-export function duplicateAndDrag(- cx: number,- cy: number,- editor: Editor-): { originals: Map<string, { x: number; y: number; parentId: string }>; drag: DragState } {- const newIds: string[] = []- const newOriginals = new Map<string, { x: number; y: number; parentId: string }>()- for (const id of editor.state.selectedIds) {- const src = editor.graph.getNode(id)- if (!src) continue- const parentId = src.parentId ?? editor.state.currentPageId- const clone = editor.graph.cloneTree(id, parentId, { name: src.name + ' copy' })- if (!clone) continue- newIds.push(clone.id)- newOriginals.set(clone.id, {- x: src.x,- y: src.y,- parentId- })- }- editor.select(newIds)- editor.requestRender()- return {- originals: newOriginals,- drag: {- type: 'move',- startX: cx,- startY: cy,- currentX: cx,- currentY: cy,- originals: newOriginals,- duplicated: true- }- }-}--function findDropTarget(cx: number, cy: number, editor: Editor): SceneNode | null {- let dropTarget = editor.graph.hitTestFrame(- cx,- cy,- editor.state.selectedIds,- editor.state.currentPageId- )- const movingSection = [...editor.state.selectedIds].some(- (id) => editor.graph.getNode(id)?.type === 'SECTION'- )- if (- movingSection &&- dropTarget &&- dropTarget.type !== 'SECTION' &&- dropTarget.type !== 'CANVAS'- ) {- dropTarget = null- }- return dropTarget-}--function applyMoveSnap(- d: DragMove,- dx: number,- dy: number,- editor: Editor-): { dx: number; dy: number } {- const selectedNodes: SceneNode[] = []- for (const [id, orig] of d.originals) {- const n = editor.graph.getNode(id)- if (n) {- const abs = editor.graph.getAbsolutePosition(id)- const parentAbs = n.parentId ? editor.graph.getAbsolutePosition(n.parentId) : { x: 0, y: 0 }- selectedNodes.push({- ...n,- x: abs.x - parentAbs.x - n.x + orig.x + dx,- y: abs.y - parentAbs.y - n.y + orig.y + dy- })- }- }-- const bounds = computeSelectionBounds(selectedNodes)- if (!bounds) return { dx, dy }-- const firstId = [...d.originals.keys()][0]- const firstNode = editor.graph.getNode(firstId)- const parentId = firstNode?.parentId ?? editor.state.currentPageId- const siblings = editor.graph.getChildren(parentId)- const parentAbs = !editor.isTopLevel(parentId)- ? editor.graph.getAbsolutePosition(parentId)- : { x: 0, y: 0 }- const absTargets = siblings.map((n) => ({- ...n,- x: n.x + parentAbs.x,- y: n.y + parentAbs.y- }))- const absBounds = {- x: bounds.x + parentAbs.x,- y: bounds.y + parentAbs.y,- width: bounds.width,- height: bounds.height- }- const snap = computeSnap(editor.state.selectedIds, absBounds, absTargets)- editor.setSnapGuides(snap.guides)- return { dx: dx + snap.dx, dy: dy + snap.dy }-}-export function handleMoveMove(d: DragMove, cx: number, cy: number, editor: Editor) {d.currentX = cxd.currentY = cy@@ -140,7 +42,7 @@ export function handleMoveMove(d: DragMove, cx: number, cy: number, editor: Editeditor.setLayoutInsertIndicator(null)}- const dropTarget = findDropTarget(cx, cy, editor)+ const dropTarget = findMoveDropTarget(cx, cy, editor)const dropParent = dropTarget ? editor.graph.getNode(dropTarget.id) : nullif (dropParent && dropParent.layoutMode !== 'NONE') {@@ -173,21 +75,6 @@ function getMoveDistance(d: DragMove) {return Math.hypot(d.currentX - d.startX, d.currentY - d.startY)}-function reparentOutsideNodes(editor: Editor) {- for (const id of editor.state.selectedIds) {- const node = editor.graph.getNode(id)- if (!node?.parentId || editor.isTopLevel(node.parentId)) continue- const parent = editor.graph.getNode(node.parentId)- if (!parent || (parent.type !== 'FRAME' && parent.type !== 'SECTION')) continue- const outsideX = node.x + node.width < 0 || node.x > parent.width- const outsideY = node.y + node.height < 0 || node.y > parent.height- if (outsideX || outsideY) {- const grandparentId = parent.parentId ?? editor.state.currentPageId- editor.graph.reparentNode(id, grandparentId)- }- }-}-export function handleMoveUp(d: DragMove, editor: Editor) {const indicator = editor.state.layoutInsertIndicatoreditor.setLayoutInsertIndicator(null)@@ -217,6 +104,11 @@ export function handleMoveUp(d: DragMove, editor: Editor) {} else {reparentOutsideNodes(editor)}+ }++ if (d.duplicated) {+ editor.commitDuplicateMove([...d.originals.keys()], d.duplicatedPreviousSelection ?? new Set())+ } else if (moved) {editor.commitMoveWithReparent(d.originals)}editor.setDropTarget(null)diff --git a/packages/vue/src/shared/input/node-edit/hit-test.ts b/packages/vue/src/shared/input/node-edit/hit-test.tsnew file mode 100644index 000000000..26033c432--- /dev/null+++ b/packages/vue/src/shared/input/node-edit/hit-test.ts@@ -0,0 +1,102 @@+import type { VectorSegment, VectorVertex } from '@open-pencil/core/scene-graph'+import type { Editor } from '@open-pencil/core/editor'++export type NodeEditState = {+ nodeId: string+ vertices: VectorVertex[]+ segments: VectorSegment[]+ selectedVertexIndices: Set<number>+ selectedHandles: Set<string>+ hoveredHandleInfo: {+ segmentIndex: number+ tangentField: 'tangentStart' | 'tangentEnd'+ } | null+}++export function getNodeEditState(editor: Editor): NodeEditState | null {+ return (+ (editor.state as Editor['state'] & { nodeEditState?: NodeEditState | null }).nodeEditState ??+ null+ )+}++export const NODE_HIT_THRESHOLD = 8+const HANDLE_HIT_THRESHOLD_NE = 6++export function isEndpoint(vertexIndex: number, segments: VectorSegment[]): boolean {+ let count = 0+ for (const seg of segments) {+ if (seg.start === vertexIndex || seg.end === vertexIndex) count+++ }+ return count === 1+}++export function hitTestEditVertex(editor: Editor, cx: number, cy: number): number | null {+ const es = getNodeEditState(editor)+ if (!es) return null+ const iz = 1 / editor.state.zoom+ for (let i = 0; i < es.vertices.length; i++) {+ const v = es.vertices[i]+ if (Math.hypot(cx - v.x, cy - v.y) < NODE_HIT_THRESHOLD * iz) return i+ }+ return null+}++function getHandleVisibleVertices(editor: Editor): Set<number> {+ const es = getNodeEditState(editor)+ if (!es) return new Set()+ const seed = new Set(es.selectedVertexIndices)+ for (const key of es.selectedHandles) {+ const [siStr, tf] = key.split(':')+ const seg = es.segments[Number(siStr)]+ seed.add(tf === 'tangentStart' ? seg.start : seg.end)+ }+ const visible = new Set(seed)+ for (const seg of es.segments) {+ if (seed.has(seg.start)) visible.add(seg.end)+ if (seed.has(seg.end)) visible.add(seg.start)+ }+ return visible+}++export function hitTestEditHandle(+ editor: Editor,+ cx: number,+ cy: number+): {+ segmentIndex: number+ tangentField: 'tangentStart' | 'tangentEnd'+ vertexIndex: number+} | null {+ const es = getNodeEditState(editor)+ if (!es) return null+ const iz = 1 / editor.state.zoom+ const visible = getHandleVisibleVertices(editor)++ for (let si = 0; si < es.segments.length; si++) {+ const seg = es.segments[si]++ if (visible.has(seg.start)) {+ const ts = seg.tangentStart+ if (ts.x !== 0 || ts.y !== 0) {+ const hx = es.vertices[seg.start].x + ts.x+ const hy = es.vertices[seg.start].y + ts.y+ if (Math.hypot(cx - hx, cy - hy) < HANDLE_HIT_THRESHOLD_NE * iz) {+ return { segmentIndex: si, tangentField: 'tangentStart', vertexIndex: seg.start }+ }+ }+ }++ if (visible.has(seg.end)) {+ const te = seg.tangentEnd+ if (te.x !== 0 || te.y !== 0) {+ const hx = es.vertices[seg.end].x + te.x+ const hy = es.vertices[seg.end].y + te.y+ if (Math.hypot(cx - hx, cy - hy) < HANDLE_HIT_THRESHOLD_NE * iz) {+ return { segmentIndex: si, tangentField: 'tangentEnd', vertexIndex: seg.end }+ }+ }+ }+ }+ return null+}diff --git a/packages/vue/src/shared/input/node-edit/index.ts b/packages/vue/src/shared/input/node-edit/index.tsnew file mode 100644index 000000000..7c638fadc--- /dev/null+++ b/packages/vue/src/shared/input/node-edit/index.ts@@ -0,0 +1,188 @@+import {+ getNodeEditState,+ hitTestEditHandle,+ hitTestEditVertex,+ isEndpoint+} from '#vue/shared/input/node-edit/hit-test'++import type { DragEditHandle, DragEditNode, DragState } from '#vue/shared/input/types'++export {+ getNodeEditState,+ hitTestEditHandle,+ isEndpoint,+ NODE_HIT_THRESHOLD+} from '#vue/shared/input/node-edit/hit-test'+import type { Vector } from '@open-pencil/core/types'+import type { Editor } from '@open-pencil/core/editor'++type NodeEditEditor = Partial<{+ nodeEditSelectVertex: (vertexIndex: number, addToSelection: boolean) => void+ exitNodeEditMode: (commit: boolean) => void+ nodeEditRemoveVertex: (vertexIndex: number) => void+ penResumeFromEndpoint: (nodeId: string, endpointVertexIndex: number) => void+ nodeEditAddVertex: (cx: number, cy: number) => void+ nodeEditSetHandle: (+ segmentIndex: number,+ tangentField: 'tangentStart' | 'tangentEnd',+ newTangent: Vector,+ options?: {+ breakMirroring?: boolean+ continuous?: boolean+ lockDirection?: boolean+ }+ ) => void+}>++export function handleNodeEditDown(+ e: MouseEvent,+ cx: number,+ cy: number,+ editor: Editor,+ setDrag: (d: DragState) => void+) {+ const es = getNodeEditState(editor)+ if (!es) return+ const nodeEditEditor = editor as Editor & NodeEditEditor++ const handleHit = hitTestEditHandle(editor, cx, cy)+ if (handleHit) {+ const key = `${handleHit.segmentIndex}:${handleHit.tangentField}`+ if (e.shiftKey) {+ const next = new Set(es.selectedHandles)+ if (next.has(key)) next.delete(key)+ else next.add(key)+ es.selectedHandles = next+ } else {+ es.selectedVertexIndices = new Set()+ es.selectedHandles = new Set([key])+ }+ setDrag({+ type: 'edit-handle',+ segmentIndex: handleHit.segmentIndex,+ tangentField: handleHit.tangentField,+ vertexIndex: handleHit.vertexIndex,+ startX: cx,+ startY: cy,+ initialTangent: (() => {+ const seg = es.segments[handleHit.segmentIndex]+ const tangent =+ handleHit.tangentField === 'tangentStart' ? seg.tangentStart : seg.tangentEnd+ return { x: tangent.x, y: tangent.y }+ })()+ })+ return+ }++ const vi = hitTestEditVertex(editor, cx, cy)+ if (vi !== null) {+ if (!e.shiftKey) es.selectedHandles = new Set()++ if (e.metaKey || e.ctrlKey) {+ nodeEditEditor.nodeEditSelectVertex?.(vi, false)+ setDrag({+ type: 'bend-handle',+ vertexIndex: vi,+ startX: es.vertices[vi].x,+ startY: es.vertices[vi].y,+ lockedMode: null,+ dragSamples: [],+ targetSegmentIndex: null,+ targetTangentField: null+ })+ return+ }++ if (!(es.selectedVertexIndices.has(vi) && !e.shiftKey)) {+ nodeEditEditor.nodeEditSelectVertex?.(vi, e.shiftKey)+ }++ const origPositions = new Map<number, Vector>()+ for (const idx of es.selectedVertexIndices) {+ origPositions.set(idx, { x: es.vertices[idx].x, y: es.vertices[idx].y })+ }+ if (!origPositions.has(vi)) {+ origPositions.set(vi, { x: es.vertices[vi].x, y: es.vertices[vi].y })+ }++ setDrag({+ type: 'edit-node',+ startX: cx,+ startY: cy,+ origPositions+ })+ return+ }++ nodeEditEditor.exitNodeEditMode?.(true)+}++export function handlePenNodeEditDown(e: MouseEvent, cx: number, cy: number, editor: Editor) {+ const es = getNodeEditState(editor)+ if (!es) return+ const nodeEditEditor = editor as Editor & NodeEditEditor++ const vi = hitTestEditVertex(editor, cx, cy)+ if (vi !== null) {+ if (e.altKey) {+ nodeEditEditor.nodeEditRemoveVertex?.(vi)+ return+ }+ if (isEndpoint(vi, es.segments)) {+ const nodeId = es.nodeId+ nodeEditEditor.exitNodeEditMode?.(true)+ nodeEditEditor.penResumeFromEndpoint?.(nodeId, vi)+ }+ return+ }++ nodeEditEditor.nodeEditAddVertex?.(cx, cy)+}++export function handleNodeEditMove(+ d: DragEditNode | DragEditHandle,+ cx: number,+ cy: number,+ editor: Editor,+ breakMirroring?: boolean,+ continuous?: boolean,+ lockDirection?: boolean+) {+ const nodeEditEditor = editor as Editor & NodeEditEditor+ if (d.type === 'edit-node') {+ const dx = cx - d.startX+ const dy = cy - d.startY+ const es = getNodeEditState(editor)+ if (!es) return++ for (const [idx, orig] of d.origPositions) {+ es.vertices[idx] = {+ ...es.vertices[idx],+ x: orig.x + dx,+ y: orig.y + dy+ }+ }+ editor.requestRepaint()+ return+ }+ const es = getNodeEditState(editor)+ if (!es) return+ const vertex = es.vertices[d.vertexIndex]+ let newTangent = { x: cx - vertex.x, y: cy - vertex.y }+ const canLockDirection =+ lockDirection &&+ (vertex.handleMirroring === 'ANGLE' || vertex.handleMirroring === 'ANGLE_AND_LENGTH')+ if (canLockDirection && d.initialTangent) {+ const len = Math.hypot(d.initialTangent.x, d.initialTangent.y)+ if (len > 1e-6) {+ const dir = { x: d.initialTangent.x / len, y: d.initialTangent.y / len }+ const projectedLen = Math.max(0, newTangent.x * dir.x + newTangent.y * dir.y)+ newTangent = { x: dir.x * projectedLen, y: dir.y * projectedLen }+ }+ }+ nodeEditEditor.nodeEditSetHandle?.(d.segmentIndex, d.tangentField, newTangent, {+ breakMirroring,+ continuous,+ lockDirection+ })+}diff --git a/packages/vue/src/shared/input/pan-zoom.ts b/packages/vue/src/shared/input/pan-zoom.tsindex 02102ec38..4adb0ee2c 100644--- a/packages/vue/src/shared/input/pan-zoom.ts+++ b/packages/vue/src/shared/input/pan-zoom.ts@@ -1,6 +1,8 @@+import { setupSafariGestureZoom } from '#vue/shared/input/gesture'+import { setupWheelPanZoom } from '#vue/shared/input/wheel'import { useEventListener } from '@vueuse/core'-import type { DragState } from './types'+import type { DragState } from '#vue/shared/input/types'import type { Editor } from '@open-pencil/core/editor'import type { Ref } from 'vue'@@ -12,63 +14,6 @@ export function setupPanZoom(onMouseMove: (e: MouseEvent) => void,onMouseUp: () => void) {- const wheelAccum = {- deltaX: 0,- deltaY: 0,- zoomDelta: 0,- zoomCenterX: 0,- zoomCenterY: 0,- hasZoom: false,- rafId: 0- }-- function flushWheel() {- wheelAccum.rafId = 0- editor.setHoveredNode(null)- if (wheelAccum.hasZoom) {- editor.applyZoom(wheelAccum.zoomDelta, wheelAccum.zoomCenterX, wheelAccum.zoomCenterY)- } else {- editor.pan(wheelAccum.deltaX, wheelAccum.deltaY)- }- wheelAccum.deltaX = 0- wheelAccum.deltaY = 0- wheelAccum.zoomDelta = 0- wheelAccum.hasZoom = false- }-- function normalizeWheelDelta(e: WheelEvent): { dx: number; dy: number } {- let { deltaX, deltaY } = e- if (e.deltaMode === WheelEvent.DOM_DELTA_LINE) {- deltaX *= 40- deltaY *= 40- } else if (e.deltaMode === WheelEvent.DOM_DELTA_PAGE) {- deltaX *= 800- deltaY *= 800- }- return { dx: deltaX, dy: deltaY }- }-- function onWheel(e: WheelEvent) {- e.preventDefault()- const canvas = canvasRef.value- if (!canvas) return- const { dx, dy } = normalizeWheelDelta(e)-- if (e.ctrlKey || e.metaKey) {- const rect = canvas.getBoundingClientRect()- wheelAccum.zoomCenterX = e.clientX - rect.left- wheelAccum.zoomCenterY = e.clientY - rect.top- wheelAccum.zoomDelta += dy- wheelAccum.hasZoom = true- } else {- wheelAccum.deltaX -= dx- wheelAccum.deltaY -= dy- }- if (!wheelAccum.rafId) {- wheelAccum.rafId = requestAnimationFrame(flushWheel)- }- }-let activeTouches: Touch[] = []let pinchStartDist = 0let pinchStartZoom = 0@@ -146,15 +91,12 @@ export function setupPanZoom(const newDist = touchDist(a, b)if (pinchStartDist > 0) {const scale = newDist / pinchStartDist- const newZoom = Math.max(0.02, Math.min(256, pinchStartZoom * scale))- const zoomRatio = newZoom / editor.state.zoom-+ const newZoom = pinchStartZoom * scaleconst panDx = newMidX - pinchMidXconst panDy = newMidY - pinchMidY- editor.state.panX = pinchMidX - (pinchMidX - editor.state.panX) * zoomRatio + panDx- editor.state.panY = pinchMidY - (pinchMidY - editor.state.panY) * zoomRatio + panDy- editor.state.zoom = newZoom+ editor.setZoomAroundPoint(newZoom, pinchMidX, pinchMidY)+ editor.pan(panDx, panDy)}pinchMidX = newMidX@@ -200,65 +142,11 @@ export function setupPanZoom(}}- useEventListener(canvasRef, 'wheel', onWheel, { passive: false })+ setupWheelPanZoom(canvasRef, editor)useEventListener(canvasRef, 'touchstart', onTouchStart, { passive: false })useEventListener(canvasRef, 'touchmove', onTouchMove, { passive: false })useEventListener(canvasRef, 'touchend', onTouchEnd, { passive: false })useEventListener(canvasRef, 'touchcancel', onTouchEnd, { passive: false })- let gestureStartZoom = 1- let gestureRafId = 0- let pendingGesture: { scale: number; sx: number; sy: number } | null = null-- function flushGesture() {- gestureRafId = 0- if (!pendingGesture) return- editor.setHoveredNode(null)- const { scale, sx, sy } = pendingGesture- pendingGesture = null- const newZoom = Math.max(0.02, Math.min(256, gestureStartZoom * scale))- const zoomRatio = newZoom / editor.state.zoom- editor.state.panX = sx - (sx - editor.state.panX) * zoomRatio- editor.state.panY = sy - (sy - editor.state.panY) * zoomRatio- editor.state.zoom = newZoom- editor.requestRepaint()- }-- useEventListener(- canvasRef,- 'gesturestart' as keyof HTMLElementEventMap,- (e: Event) => {- e.preventDefault()- gestureStartZoom = editor.state.zoom- },- { passive: false }- )- useEventListener(- canvasRef,- 'gesturechange' as keyof HTMLElementEventMap,- (e: Event) => {- e.preventDefault()- const ge = e as GestureEvent- const canvas = canvasRef.value- if (!canvas) return- const rect = canvas.getBoundingClientRect()- pendingGesture = {- scale: ge.scale,- sx: ge.clientX - rect.left,- sy: ge.clientY - rect.top- }- if (!gestureRafId) {- gestureRafId = requestAnimationFrame(flushGesture)- }- },- { passive: false }- )- useEventListener(- canvasRef,- 'gestureend' as keyof HTMLElementEventMap,- (e: Event) => {- e.preventDefault()- },- { passive: false }- )+ setupSafariGestureZoom(canvasRef, editor)}diff --git a/packages/vue/src/shared/input/pan.ts b/packages/vue/src/shared/input/pan.tsnew file mode 100644index 000000000..41f092044--- /dev/null+++ b/packages/vue/src/shared/input/pan.ts@@ -0,0 +1,12 @@+import type { DragState } from '#vue/shared/input/types'+import type { Editor } from '@open-pencil/core/editor'++export function startPanDrag(event: MouseEvent, setDrag: (d: DragState) => void, editor: Editor) {+ setDrag({+ type: 'pan',+ startScreenX: event.clientX,+ startScreenY: event.clientY,+ startPanX: editor.state.panX,+ startPanY: editor.state.panY+ })+}diff --git a/packages/vue/src/shared/input/raf-scheduler.ts b/packages/vue/src/shared/input/raf-scheduler.tsnew file mode 100644index 000000000..58148ee5f--- /dev/null+++ b/packages/vue/src/shared/input/raf-scheduler.ts@@ -0,0 +1,19 @@+export function createRafScheduler(flush: () => void) {+ let rafId = 0++ function schedule() {+ if (rafId) return+ rafId = requestAnimationFrame(() => {+ rafId = 0+ flush()+ })+ }++ function cancel() {+ if (!rafId) return+ cancelAnimationFrame(rafId)+ rafId = 0+ }++ return { schedule, cancel }+}diff --git a/packages/vue/src/shared/input/resize.ts b/packages/vue/src/shared/input/resize.tsindex 74b51af68..cc8f7da44 100644--- a/packages/vue/src/shared/input/resize.ts+++ b/packages/vue/src/shared/input/resize.ts@@ -1,39 +1,11 @@-import { cloneVectorNetwork } from '@open-pencil/core'-import { getHitHandleByMatrix } from '@open-pencil/vue/shared/input/geometry'+export { constrainToAspectRatio } from '#vue/shared/input/resize/rect'+export { tryStartResize } from '#vue/shared/input/resize/start'+import { calculateResizeRect } from '#vue/shared/input/resize/rect'+import { scaleVectorNetworkForResize } from '#vue/shared/input/resize/vector'-import type { DragResize, HandlePosition } from './types'-import type { Rect, SceneNode } from '@open-pencil/core'+import type { DragResize } from '#vue/shared/input/types'import type { Editor } from '@open-pencil/core/editor'--export function constrainToAspectRatio(- handle: HandlePosition,- origRect: Rect,- width: number,- height: number,- dx: number,- dy: number-): Rect {- let x = handle.includes('w') ? origRect.x + origRect.width - Math.abs(width) : origRect.x- const isTop = handle === 'nw' || handle === 'n' || handle === 'ne'- let y = isTop ? origRect.y + origRect.height - Math.abs(height) : origRect.y- const aspect = origRect.width / origRect.height-- if (handle === 'n' || handle === 's') {- width = Math.abs(height) * aspect- x = origRect.x + (origRect.width - width) / 2- } else if (handle === 'e' || handle === 'w') {- height = Math.abs(width) / aspect- y = origRect.y + (origRect.height - height) / 2- } else if (Math.abs(dx) > Math.abs(dy)) {- height = (Math.abs(width) / aspect) * Math.sign(height || 1)- if (isTop) y = origRect.y + origRect.height - Math.abs(height)- } else {- width = Math.abs(height) * aspect * Math.sign(width || 1)- if (handle.includes('w')) x = origRect.x + origRect.width - Math.abs(width)- }-- return { x, y, width, height }-}+import type { SceneNode } from '@open-pencil/core/scene-graph'export function applyResize(d: DragResize,@@ -42,93 +14,25 @@ export function applyResize(constrain: boolean,editor: Editor) {- const { handle, origRect } = d- let { x, y, width, height } = origRect-- const dx = cx - d.startX- const dy = cy - d.startY-- const origX = origRect.x- const origY = origRect.y- const origW = origRect.width- const origH = origRect.height-- const moveLeft = handle.includes('w')- const moveRight = handle.includes('e')- const moveTop = handle === 'nw' || handle === 'n' || handle === 'ne'- const moveBottom = handle === 'sw' || handle === 's' || handle === 'se'-- if (moveRight) width = origW + dx- if (moveLeft) {- x = origX + dx- width = origW - dx- }- if (moveBottom) height = origH + dy- if (moveTop) {- y = origY + dy- height = origH - dy- }-- if (constrain && origW > 0 && origH > 0) {- ;({ x, y, width, height } = constrainToAspectRatio(handle, origRect, width, height, dx, dy))- }-- if (width < 0) {- x += width- width = -width- }- if (height < 0) {- y += height- height = -height- }-- const newW = Math.round(Math.max(1, width))- const newH = Math.round(Math.max(1, height))- const newX = Math.round(x)- const newY = Math.round(y)-- const changes: Partial<SceneNode> = {- x: newX,- y: newY,- width: newW,- height: newH- }-- if (d.origVectorNetwork && origW > 0 && origH > 0) {- const sx = newW / origW- const sy = newH / origH- if (sx !== 1 || sy !== 1) {- const vn = d.origVectorNetwork- changes.vectorNetwork = {- vertices: vn.vertices.map((v) => ({ ...v, x: v.x * sx, y: v.y * sy })),- segments: vn.segments.map((s) => ({- ...s,- tangentStart: { x: s.tangentStart.x * sx, y: s.tangentStart.y * sy },- tangentEnd: { x: s.tangentEnd.x * sx, y: s.tangentEnd.y * sy }- })),- regions: vn.regions- }- }- }+ const { origRect } = d+ const newRect = calculateResizeRect(+ d.handle,+ origRect,+ cx - d.startX,+ cy - d.startY,+ constrain+ )++ const changes: Partial<SceneNode> = { ...newRect }++ const resizedVectorNetwork = scaleVectorNetworkForResize(+ d.origVectorNetwork,+ origRect.width,+ origRect.height,+ newRect.width,+ newRect.height+ )+ if (resizedVectorNetwork) changes.vectorNetwork = resizedVectorNetworkeditor.updateNode(d.nodeId, changes)-}-export function tryStartResize(cx: number, cy: number, editor: Editor): DragResize | null {- for (const id of editor.state.selectedIds) {- const node = editor.graph.getNode(id)- if (!node || node.locked) continue- const handleResult = getHitHandleByMatrix(cx, cy, node, editor.graph, editor?.renderer?.zoom)- if (handleResult?.handle) {- return {- type: 'resize',- handle: handleResult?.handle,- startX: cx,- startY: cy,- origRect: { x: node.x, y: node.y, width: node.width, height: node.height },- nodeId: id,- origVectorNetwork: node.vectorNetwork ? cloneVectorNetwork(node.vectorNetwork) : null- }- }- }- return null-}+}\ No newline at end of filediff --git a/packages/vue/src/shared/input/resize/rect.ts b/packages/vue/src/shared/input/resize/rect.tsnew file mode 100644index 000000000..fefc31451--- /dev/null+++ b/packages/vue/src/shared/input/resize/rect.ts@@ -0,0 +1,78 @@+import type { HandlePosition } from '#vue/shared/input/types'+import type { Rect } from '@open-pencil/core/types'++export function constrainToAspectRatio(+ handle: HandlePosition,+ origRect: Rect,+ width: number,+ height: number,+ dx: number,+ dy: number+): Rect {+ let x = handle.includes('w') ? origRect.x + origRect.width - Math.abs(width) : origRect.x+ const isTop = handle === 'nw' || handle === 'n' || handle === 'ne'+ let y = isTop ? origRect.y + origRect.height - Math.abs(height) : origRect.y+ const aspect = origRect.width / origRect.height++ if (handle === 'n' || handle === 's') {+ width = Math.abs(height) * aspect+ x = origRect.x + (origRect.width - width) / 2+ } else if (handle === 'e' || handle === 'w') {+ height = Math.abs(width) / aspect+ y = origRect.y + (origRect.height - height) / 2+ } else if (Math.abs(dx) > Math.abs(dy)) {+ height = (Math.abs(width) / aspect) * Math.sign(height || 1)+ if (isTop) y = origRect.y + origRect.height - Math.abs(height)+ } else {+ width = Math.abs(height) * aspect * Math.sign(width || 1)+ if (handle.includes('w')) x = origRect.x + origRect.width - Math.abs(width)+ }++ return { x, y, width, height }+}++export function calculateResizeRect(+ handle: HandlePosition,+ origRect: Rect,+ dx: number,+ dy: number,+ constrain: boolean+): Rect {+ let { x, y, width, height } = origRect++ const moveLeft = handle.includes('w')+ const moveRight = handle.includes('e')+ const moveTop = handle === 'nw' || handle === 'n' || handle === 'ne'+ const moveBottom = handle === 'sw' || handle === 's' || handle === 'se'++ if (moveRight) width = origRect.width + dx+ if (moveLeft) {+ x = origRect.x + dx+ width = origRect.width - dx+ }+ if (moveBottom) height = origRect.height + dy+ if (moveTop) {+ y = origRect.y + dy+ height = origRect.height - dy+ }++ if (constrain && origRect.width > 0 && origRect.height > 0) {+ ;({ x, y, width, height } = constrainToAspectRatio(handle, origRect, width, height, dx, dy))+ }++ if (width < 0) {+ x += width+ width = -width+ }+ if (height < 0) {+ y += height+ height = -height+ }++ return {+ x: Math.round(x),+ y: Math.round(y),+ width: Math.round(Math.max(1, width)),+ height: Math.round(Math.max(1, height))+ }+}diff --git a/packages/vue/src/shared/input/resize/start.ts b/packages/vue/src/shared/input/resize/start.tsnew file mode 100644index 000000000..2c55a4f36--- /dev/null+++ b/packages/vue/src/shared/input/resize/start.ts@@ -0,0 +1,26 @@+import { getHitHandleByMatrix } from '#vue/shared/input/geometry'++import { cloneVectorNetwork } from '@open-pencil/core/scene-graph'++import type { DragResize } from '#vue/shared/input/types'+import type { Editor } from '@open-pencil/core/editor'++export function tryStartResize(cx: number, cy: number, editor: Editor): DragResize | null {+ for (const id of editor.state.selectedIds) {+ const node = editor.graph.getNode(id)+ if (!node || node.locked) continue+ const handleResult = getHitHandleByMatrix(cx, cy, node, editor.graph, editor.renderer?.zoom)+ if (handleResult) {+ return {+ type: 'resize',+ handle: handleResult.handle,+ startX: cx,+ startY: cy,+ origRect: { x: node.x, y: node.y, width: node.width, height: node.height },+ nodeId: id,+ origVectorNetwork: node.vectorNetwork ? cloneVectorNetwork(node.vectorNetwork) : null+ }+ }+ }+ return null+}diff --git a/packages/vue/src/shared/input/resize/vector.ts b/packages/vue/src/shared/input/resize/vector.tsnew file mode 100644index 000000000..24a3869fd--- /dev/null+++ b/packages/vue/src/shared/input/resize/vector.ts@@ -0,0 +1,37 @@+import type { SceneNode } from '@open-pencil/core/scene-graph'++type VectorNetwork = NonNullable<SceneNode['vectorNetwork']>++export function scaleVectorNetworkForResize(+ vectorNetwork: VectorNetwork | null,+ origWidth: number,+ origHeight: number,+ width: number,+ height: number+): VectorNetwork | null {+ if (!vectorNetwork || origWidth <= 0 || origHeight <= 0) return null++ const sx = width / origWidth+ const sy = height / origHeight+ if (sx === 1 && sy === 1) return null++ return {+ vertices: vectorNetwork.vertices.map((vertex) => ({+ ...vertex,+ x: vertex.x * sx,+ y: vertex.y * sy+ })),+ segments: vectorNetwork.segments.map((segment) => ({+ ...segment,+ tangentStart: {+ x: segment.tangentStart.x * sx,+ y: segment.tangentStart.y * sy+ },+ tangentEnd: {+ x: segment.tangentEnd.x * sx,+ y: segment.tangentEnd.y * sy+ }+ })),+ regions: vectorNetwork.regions+ }+}diff --git a/packages/vue/src/shared/input/select.ts b/packages/vue/src/shared/input/select.tsindex b8e1c5886..684769342 100644--- a/packages/vue/src/shared/input/select.ts+++ b/packages/vue/src/shared/input/select.ts@@ -1,59 +1,13 @@-import {- getAbsoluteRotation,- SceneNode,- Vector,- VectorSegment,- VectorVertex-} from '@open-pencil/core'--import {- cornerRotationCursor,- getHitHandleByMatrix,- hitTestCornerRotationByMatrix,- buildResizeCursor-} from './geometry'-import { duplicateAndDrag, detectAutoLayoutParent } from './move'-import { tryStartResize } from './resize'--import type { DragEditHandle, DragEditNode, DragState } from './types'+import { getNodeEditState, handleNodeEditDown } from '#vue/shared/input/node-edit'+export { resolveHit } from '#vue/shared/input/select/hit'+import { resolveHit } from '#vue/shared/input/select/hit'+export { updateHoverCursor } from '#vue/shared/input/select/hover'+import { createSelectionMoveDrag, selectionIsLocked } from '#vue/shared/input/select/move'+import { tryStartResize } from '#vue/shared/input/resize'++import type { DragState } from '#vue/shared/input/types'import type { Editor } from '@open-pencil/core/editor'--type NodeEditState = {- nodeId: string- vertices: VectorVertex[]- segments: VectorSegment[]- selectedVertexIndices: Set<number>- selectedHandles: Set<string>- hoveredHandleInfo: {- segmentIndex: number- tangentField: 'tangentStart' | 'tangentEnd'- } | null-}--type NodeEditEditor = Partial<{- nodeEditSelectVertex: (vertexIndex: number, addToSelection: boolean) => void- exitNodeEditMode: (commit: boolean) => void- nodeEditRemoveVertex: (vertexIndex: number) => void- penResumeFromEndpoint: (nodeId: string, endpointVertexIndex: number) => void- nodeEditAddVertex: (cx: number, cy: number) => void- nodeEditSetHandle: (- segmentIndex: number,- tangentField: 'tangentStart' | 'tangentEnd',- newTangent: Vector,- options?: {- breakMirroring?: boolean- continuous?: boolean- lockDirection?: boolean- }- ) => void-}>--function getNodeEditState(editor: Editor): NodeEditState | null {- return (- (editor.state as Editor['state'] & { nodeEditState?: NodeEditState | null }).nodeEditState ??- null- )-}+import type { SceneNode } from '@open-pencil/core/scene-graph'export interface HitTestFns {hitTestInScope: (cx: number, cy: number, deep: boolean) => SceneNode | null@@ -63,296 +17,6 @@ export interface HitTestFns {hitTestFrameTitle: (cx: number, cy: number) => SceneNode | null}-export function resolveHit(- cx: number,- cy: number,- editor: Editor,- fns: HitTestFns-): SceneNode | null {- const titleHit =- fns.hitTestFrameTitle(cx, cy) ??- fns.hitTestSectionTitle(cx, cy) ??- fns.hitTestComponentLabel(cx, cy)- if (titleHit) return titleHit-- const hit = fns.hitTestInScope(cx, cy, false)- if (hit) return hit-- const scopeId = editor.state.enteredContainerId- if (!scopeId) return null-- if (fns.isInsideContainerBounds(cx, cy, scopeId)) {- editor.clearSelection()- return null- }-- editor.exitContainer()- const afterExit = fns.hitTestInScope(cx, cy, false)- if (afterExit) return afterExit-- if (editor.state.enteredContainerId) {- editor.exitContainer()- }- return null-}--// ----------------------------------------------------------------------------// Node edit mode handlers-// -----------------------------------------------------------------------------export const NODE_HIT_THRESHOLD = 8-const HANDLE_HIT_THRESHOLD_NE = 6--/** Check if vertex is an endpoint (connected to exactly 1 segment) */-export function isEndpoint(vertexIndex: number, segments: VectorSegment[]): boolean {- let count = 0- for (const seg of segments) {- if (seg.start === vertexIndex || seg.end === vertexIndex) count++- }- return count === 1-}--function hitTestEditVertex(editor: Editor, cx: number, cy: number): number | null {- const es = getNodeEditState(editor)- if (!es) return null- const iz = 1 / editor.state.zoom- for (let i = 0; i < es.vertices.length; i++) {- const v = es.vertices[i]- if (Math.hypot(cx - v.x, cy - v.y) < NODE_HIT_THRESHOLD * iz) return i- }- return null-}--/** Vertices whose handles are visible: selected vertices + vertices with selected handles + their direct neighbors */-function getHandleVisibleVertices(editor: Editor): Set<number> {- const es = getNodeEditState(editor)- if (!es) return new Set()- // Seed: selected vertices + vertices that own a selected handle- const seed = new Set(es.selectedVertexIndices)- for (const key of es.selectedHandles) {- const [siStr, tf] = key.split(':')- const seg = es.segments[Number(siStr)]- seed.add(tf === 'tangentStart' ? seg.start : seg.end)- }- // Expand: add only direct neighbors of seed vertices (no cascading)- const visible = new Set(seed)- for (const seg of es.segments) {- if (seed.has(seg.start)) visible.add(seg.end)- if (seed.has(seg.end)) visible.add(seg.start)- }- return visible-}--export function hitTestEditHandle(- editor: Editor,- cx: number,- cy: number-): {- segmentIndex: number- tangentField: 'tangentStart' | 'tangentEnd'- vertexIndex: number-} | null {- const es = getNodeEditState(editor)- if (!es) return null- const iz = 1 / editor.state.zoom- const visible = getHandleVisibleVertices(editor)-- for (let si = 0; si < es.segments.length; si++) {- const seg = es.segments[si]-- if (visible.has(seg.start)) {- const ts = seg.tangentStart- if (ts.x !== 0 || ts.y !== 0) {- const hx = es.vertices[seg.start].x + ts.x- const hy = es.vertices[seg.start].y + ts.y- if (Math.hypot(cx - hx, cy - hy) < HANDLE_HIT_THRESHOLD_NE * iz) {- return { segmentIndex: si, tangentField: 'tangentStart', vertexIndex: seg.start }- }- }- }-- if (visible.has(seg.end)) {- const te = seg.tangentEnd- if (te.x !== 0 || te.y !== 0) {- const hx = es.vertices[seg.end].x + te.x- const hy = es.vertices[seg.end].y + te.y- if (Math.hypot(cx - hx, cy - hy) < HANDLE_HIT_THRESHOLD_NE * iz) {- return { segmentIndex: si, tangentField: 'tangentEnd', vertexIndex: seg.end }- }- }- }- }- return null-}--function handleNodeEditDown(- e: MouseEvent,- cx: number,- cy: number,- editor: Editor,- setDrag: (d: DragState) => void-) {- const es = getNodeEditState(editor)- if (!es) return- const nodeEditEditor = editor as Editor & NodeEditEditor-- // Check handle hit first (only for vertices with visible handles)- const handleHit = hitTestEditHandle(editor, cx, cy)- if (handleHit) {- const key = `${handleHit.segmentIndex}:${handleHit.tangentField}`- if (e.shiftKey) {- // Shift+click: toggle handle in multi-selection- const next = new Set(es.selectedHandles)- if (next.has(key)) next.delete(key)- else next.add(key)- es.selectedHandles = next- } else {- // Click on handle: select only this handle, deselect everything else- es.selectedVertexIndices = new Set()- es.selectedHandles = new Set([key])- }- setDrag({- type: 'edit-handle',- segmentIndex: handleHit.segmentIndex,- tangentField: handleHit.tangentField,- vertexIndex: handleHit.vertexIndex,- startX: cx,- startY: cy,- initialTangent: (() => {- const seg = es.segments[handleHit.segmentIndex]- const tangent =- handleHit.tangentField === 'tangentStart' ? seg.tangentStart : seg.tangentEnd- return { x: tangent.x, y: tangent.y }- })()- })- return- }-- // Check vertex hit- const vi = hitTestEditVertex(editor, cx, cy)- if (vi !== null) {- if (!e.shiftKey) es.selectedHandles = new Set()-- // Cmd/Ctrl + vertex click → Bend mode (recreate handles from scratch)- if (e.metaKey || e.ctrlKey) {- nodeEditEditor.nodeEditSelectVertex?.(vi, false)- setDrag({- type: 'bend-handle',- vertexIndex: vi,- startX: es.vertices[vi].x,- startY: es.vertices[vi].y,- lockedMode: null,- dragSamples: [],- targetSegmentIndex: null,- targetTangentField: null- })- return- }-- // If vertex is already selected and not Shift — keep selection, just start drag- if (es.selectedVertexIndices.has(vi) && !e.shiftKey) {- // Don't re-select — preserve multi-selection for dragging- } else {- nodeEditEditor.nodeEditSelectVertex?.(vi, e.shiftKey)- }-- // Start drag- const origPositions = new Map<number, Vector>()- for (const idx of es.selectedVertexIndices) {- origPositions.set(idx, { x: es.vertices[idx].x, y: es.vertices[idx].y })- }- if (!origPositions.has(vi)) {- origPositions.set(vi, { x: es.vertices[vi].x, y: es.vertices[vi].y })- }-- setDrag({- type: 'edit-node',- startX: cx,- startY: cy,- origPositions- })- return- }-- // Click on empty space: exit node edit mode- nodeEditEditor.exitNodeEditMode?.(true)-}--export function handlePenNodeEditDown(e: MouseEvent, cx: number, cy: number, editor: Editor) {- const es = getNodeEditState(editor)- if (!es) return- const nodeEditEditor = editor as Editor & NodeEditEditor-- const vi = hitTestEditVertex(editor, cx, cy)- if (vi !== null) {- // Alt+click on vertex → remove it (smooth merge of adjacent segments)- if (e.altKey) {- nodeEditEditor.nodeEditRemoveVertex?.(vi)- return- }- // Click on endpoint → continue drawing from this endpoint- if (isEndpoint(vi, es.segments)) {- const nodeId = es.nodeId- nodeEditEditor.exitNodeEditMode?.(true)- nodeEditEditor.penResumeFromEndpoint?.(nodeId, vi)- return- }- // Click on non-endpoint vertex → no action- return- }-- // Click on curve contour → add new anchor point- nodeEditEditor.nodeEditAddVertex?.(cx, cy)-}--export function handleNodeEditMove(- d: DragEditNode | DragEditHandle,- cx: number,- cy: number,- editor: Editor,- breakMirroring?: boolean,- continuous?: boolean,- lockDirection?: boolean-) {- const nodeEditEditor = editor as Editor & NodeEditEditor- if (d.type === 'edit-node') {- const dx = cx - d.startX- const dy = cy - d.startY- const es = getNodeEditState(editor)- if (!es) return-- for (const [idx, orig] of d.origPositions) {- es.vertices[idx] = {- ...es.vertices[idx],- x: orig.x + dx,- y: orig.y + dy- }- }- editor.requestRepaint()- return- }- const es = getNodeEditState(editor)- if (!es) return- const vertex = es.vertices[d.vertexIndex]- let newTangent = { x: cx - vertex.x, y: cy - vertex.y }- const canLockDirection =- lockDirection &&- (vertex.handleMirroring === 'ANGLE' || vertex.handleMirroring === 'ANGLE_AND_LENGTH')- if (canLockDirection && d.initialTangent) {- const len = Math.hypot(d.initialTangent.x, d.initialTangent.y)- if (len > 1e-6) {- const dir = { x: d.initialTangent.x / len, y: d.initialTangent.y / len }- const projectedLen = Math.max(0, newTangent.x * dir.x + newTangent.y * dir.y)- newTangent = { x: dir.x * projectedLen, y: dir.y * projectedLen }- }- }- nodeEditEditor.nodeEditSetHandle?.(d.segmentIndex, d.tangentField, newTangent, {- breakMirroring,- continuous,- lockDirection- })-}-export function handleSelectDown(e: MouseEvent,cx: number,@@ -396,81 +60,8 @@ export function handleSelectDown(editor.select([hit.id], true)}- const allLocked = [...editor.state.selectedIds].every((id) => editor.graph.getNode(id)?.locked)- if (allLocked) return+ if (selectionIsLocked(editor)) return- const originals = new Map<string, { x: number; y: number; parentId: string }>()- for (const id of editor.state.selectedIds) {- const n = editor.graph.getNode(id)- if (n) originals.set(id, { x: n.x, y: n.y, parentId: n.parentId ?? editor.state.currentPageId })- }-- if (e.altKey && editor.state.selectedIds.size > 0) {- const result = duplicateAndDrag(cx, cy, editor)- setDrag(result.drag)- return- }- setDrag({- type: 'move',- startX: cx,- startY: cy,- currentX: cx,- currentY: cy,- originals,- autoLayoutParentId: detectAutoLayoutParent(editor)- })+ setDrag(createSelectionMoveDrag(cx, cy, editor, e.altKey))}-export function updateHoverCursor(- cx: number,- cy: number,- editor: Editor,- fns: Pick<HitTestFns, 'hitTestInScope' | 'hitTestSectionTitle' | 'hitTestComponentLabel'>-): string | null {- if (getNodeEditState(editor)) {- editor.setHoveredNode(null)- return null- }-- let cursor: string | null = null-- for (const id of editor.state.selectedIds) {- const node = editor.graph.getNode(id)- if (!node) continue-- const handHit = getHitHandleByMatrix(cx, cy, node, editor.graph, editor.renderer?.zoom ?? 1)- if (handHit?.handle) {- cursor = buildResizeCursor(handHit?.rotation)- break- }- }-- if (!cursor && editor.state.selectedIds.size === 1) {- const id = [...editor.state.selectedIds][0]- const node = editor.graph.getNode(id)- if (node) {- const corner = hitTestCornerRotationByMatrix(- cx,- cy,- node,- editor.graph,- editor.renderer?.zoom ?? 1- )- if (corner) {- const abRotation = getAbsoluteRotation(node, editor.graph)- cursor = cornerRotationCursor(corner, abRotation)- }- }- }-- const hit =- fns.hitTestSectionTitle(cx, cy) ??- fns.hitTestComponentLabel(cx, cy) ??- fns.hitTestInScope(cx, cy, false)- const editNodeId = getNodeEditState(editor)?.nodeId- editor.setHoveredNode(- hit && !editor.state.selectedIds.has(hit.id) && hit.id !== editNodeId ? hit.id : null- )-- return cursor-}diff --git a/packages/vue/src/shared/input/select/hit.ts b/packages/vue/src/shared/input/select/hit.tsnew file mode 100644index 000000000..0cda42f35--- /dev/null+++ b/packages/vue/src/shared/input/select/hit.ts@@ -0,0 +1,36 @@+import type { HitTestFns } from '#vue/shared/input/select'+import type { Editor } from '@open-pencil/core/editor'+import type { SceneNode } from '@open-pencil/core/scene-graph'++export function resolveHit(+ cx: number,+ cy: number,+ editor: Editor,+ fns: HitTestFns+): SceneNode | null {+ const titleHit =+ fns.hitTestFrameTitle(cx, cy) ??+ fns.hitTestSectionTitle(cx, cy) ??+ fns.hitTestComponentLabel(cx, cy)+ if (titleHit) return titleHit++ const hit = fns.hitTestInScope(cx, cy, false)+ if (hit) return hit++ const scopeId = editor.state.enteredContainerId+ if (!scopeId) return null++ if (fns.isInsideContainerBounds(cx, cy, scopeId)) {+ editor.clearSelection()+ return null+ }++ editor.exitContainer()+ const afterExit = fns.hitTestInScope(cx, cy, false)+ if (afterExit) return afterExit++ if (editor.state.enteredContainerId) {+ editor.exitContainer()+ }+ return null+}diff --git a/packages/vue/src/shared/input/select/hover.ts b/packages/vue/src/shared/input/select/hover.tsnew file mode 100644index 000000000..e3863a2c8--- /dev/null+++ b/packages/vue/src/shared/input/select/hover.ts@@ -0,0 +1,70 @@+import {+ buildResizeCursor,+ cornerRotationCursor,+ getHitHandleByMatrix,+ hitTestCornerRotationByMatrix+} from '#vue/shared/input/geometry'+import { getNodeEditState } from '#vue/shared/input/node-edit'++import { getAbsoluteRotation } from '@open-pencil/core/canvas'++import type { HitTestFns } from '#vue/shared/input/select'+import type { Editor } from '@open-pencil/core/editor'++function getResizeCursorForSelection(cx: number, cy: number, editor: Editor): string | null {+ for (const id of editor.state.selectedIds) {+ const node = editor.graph.getNode(id)+ if (!node) continue++ const handleHit = getHitHandleByMatrix(cx, cy, node, editor.graph, editor.renderer?.zoom ?? 1)+ if (handleHit?.handle) return buildResizeCursor(handleHit.rotation)+ }+ return null+}++function getRotationCursorForSelection(cx: number, cy: number, editor: Editor): string | null {+ if (editor.state.selectedIds.size !== 1) return null++ const id = [...editor.state.selectedIds][0]+ const node = editor.graph.getNode(id)+ if (!node) return null++ const corner = hitTestCornerRotationByMatrix(cx, cy, node, editor.graph, editor.renderer?.zoom ?? 1)+ if (!corner) return null++ const absoluteRotation = getAbsoluteRotation(node, editor.graph)+ return cornerRotationCursor(corner, absoluteRotation)+}++function updateHoveredNode(+ cx: number,+ cy: number,+ editor: Editor,+ fns: Pick<HitTestFns, 'hitTestInScope' | 'hitTestSectionTitle' | 'hitTestComponentLabel'>+) {+ const hit =+ fns.hitTestSectionTitle(cx, cy) ??+ fns.hitTestComponentLabel(cx, cy) ??+ fns.hitTestInScope(cx, cy, false)+ const editNodeId = getNodeEditState(editor)?.nodeId+ editor.setHoveredNode(+ hit && !editor.state.selectedIds.has(hit.id) && hit.id !== editNodeId ? hit.id : null+ )+}++export function updateHoverCursor(+ cx: number,+ cy: number,+ editor: Editor,+ fns: Pick<HitTestFns, 'hitTestInScope' | 'hitTestSectionTitle' | 'hitTestComponentLabel'>+): string | null {+ if (getNodeEditState(editor)) {+ editor.setHoveredNode(null)+ return null+ }++ const cursor =+ getResizeCursorForSelection(cx, cy, editor) ?? getRotationCursorForSelection(cx, cy, editor)+ updateHoveredNode(cx, cy, editor, fns)+ return cursor+}diff --git a/packages/vue/src/shared/input/select/move.ts b/packages/vue/src/shared/input/select/move.tsnew file mode 100644index 000000000..e8bae86bd--- /dev/null+++ b/packages/vue/src/shared/input/select/move.ts@@ -0,0 +1,45 @@+import { detectAutoLayoutParent } from '#vue/shared/input/move'+import { duplicateAndDrag } from '#vue/shared/input/duplicate-drag'++import type { DragState } from '#vue/shared/input/types'+import type { Editor } from '@open-pencil/core/editor'++type MoveOriginal = { x: number; y: number; parentId: string }++export function selectionIsLocked(editor: Editor) {+ return [...editor.state.selectedIds].every((id) => editor.graph.getNode(id)?.locked)+}++function collectMoveOriginals(editor: Editor) {+ const originals = new Map<string, MoveOriginal>()+ for (const id of editor.state.selectedIds) {+ const node = editor.graph.getNode(id)+ if (node) {+ originals.set(id, {+ x: node.x,+ y: node.y,+ parentId: node.parentId ?? editor.state.currentPageId+ })+ }+ }+ return originals+}++export function createSelectionMoveDrag(+ cx: number,+ cy: number,+ editor: Editor,+ duplicate: boolean+): DragState {+ if (duplicate && editor.state.selectedIds.size > 0) return duplicateAndDrag(cx, cy, editor).drag++ return {+ type: 'move',+ startX: cx,+ startY: cy,+ currentX: cx,+ currentY: cy,+ originals: collectMoveOriginals(editor),+ autoLayoutParentId: detectAutoLayoutParent(editor)+ }+}diff --git a/packages/vue/src/shared/input/space-key.ts b/packages/vue/src/shared/input/space-key.tsnew file mode 100644index 000000000..aa732c6f0--- /dev/null+++ b/packages/vue/src/shared/input/space-key.ts@@ -0,0 +1,13 @@+import { useEventListener } from '@vueuse/core'+import { ref } from 'vue'++export function useSpaceHeld() {+ const spaceHeld = ref(false)+ useEventListener(window, 'keydown', (event: KeyboardEvent) => {+ if (event.code === 'Space') spaceHeld.value = true+ })+ useEventListener(window, 'keyup', (event: KeyboardEvent) => {+ if (event.code === 'Space') spaceHeld.value = false+ })+ return spaceHeld+}diff --git a/packages/vue/src/shared/input/types.ts b/packages/vue/src/shared/input/types.tsindex 0aa953e91..b548a26dc 100644--- a/packages/vue/src/shared/input/types.ts+++ b/packages/vue/src/shared/input/types.ts@@ -1,5 +1,5 @@-import type { NodeType, Rect, VectorNetwork } from '@open-pencil/core'-import type { Vector } from '@open-pencil/core'+import type { NodeType, VectorNetwork } from '@open-pencil/core/scene-graph'+import type { Rect, Vector } from '@open-pencil/core/types'import type { Tool } from '@open-pencil/core/editor'export type HandlePosition = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w'@@ -21,6 +21,7 @@ export interface DragMove {currentY: numberoriginals: Map<string, { x: number; y: number; parentId: string }>duplicated?: boolean+ duplicatedPreviousSelection?: Set<string>autoLayoutParentId?: stringbrokeFromAutoLayout?: boolean}@@ -81,7 +82,7 @@ export interface DragEditNode {type: 'edit-node'startX: numberstartY: number- origPositions: Map<number, { x: number; y: number }>+ origPositions: Map<number, Vector>}export interface DragEditHandle {diff --git a/packages/vue/src/shared/input/wheel.ts b/packages/vue/src/shared/input/wheel.tsnew file mode 100644index 000000000..d1a5d2c9f--- /dev/null+++ b/packages/vue/src/shared/input/wheel.ts@@ -0,0 +1,83 @@+import { useWheelGesture } from '#vue/shared/gesture/wheel'+import { createRafScheduler } from '#vue/shared/input/raf-scheduler'++import type { Editor } from '@open-pencil/core/editor'+import type { Ref } from 'vue'++const TRACKPAD_ZOOM_DELTA_MULTIPLIER = 1.5++type WheelAccum = {+ deltaX: number+ deltaY: number+ zoomDelta: number+ zoomCenterX: number+ zoomCenterY: number+ hasZoom: boolean+}++function normalizeWheelDelta(e: WheelEvent): { dx: number; dy: number } {+ let { deltaX, deltaY } = e+ if (e.deltaMode === WheelEvent.DOM_DELTA_LINE) {+ deltaX *= 40+ deltaY *= 40+ } else if (e.deltaMode === WheelEvent.DOM_DELTA_PAGE) {+ deltaX *= 800+ deltaY *= 800+ }+ return { dx: deltaX, dy: deltaY }+}++export function setupWheelPanZoom(canvasRef: Ref<HTMLCanvasElement | null>, editor: Editor) {+ const wheelAccum: WheelAccum = {+ deltaX: 0,+ deltaY: 0,+ zoomDelta: 0,+ zoomCenterX: 0,+ zoomCenterY: 0,+ hasZoom: false+ }++ function flushWheel() {+ editor.setHoveredNode(null)+ if (wheelAccum.hasZoom) {+ editor.applyZoom(wheelAccum.zoomDelta, wheelAccum.zoomCenterX, wheelAccum.zoomCenterY)+ } else {+ editor.pan(wheelAccum.deltaX, wheelAccum.deltaY)+ }+ wheelAccum.deltaX = 0+ wheelAccum.deltaY = 0+ wheelAccum.zoomDelta = 0+ wheelAccum.hasZoom = false+ }++ const wheelScheduler = createRafScheduler(flushWheel)++ function onWheel(e: WheelEvent) {+ const canvas = canvasRef.value+ if (!canvas) return+ const { dx, dy } = normalizeWheelDelta(e)++ if (e.ctrlKey || e.metaKey) {+ const rect = canvas.getBoundingClientRect()+ wheelAccum.zoomCenterX = e.clientX - rect.left+ wheelAccum.zoomCenterY = e.clientY - rect.top+ wheelAccum.zoomDelta += dy * TRACKPAD_ZOOM_DELTA_MULTIPLIER+ wheelAccum.hasZoom = true+ } else {+ wheelAccum.deltaX -= dx+ wheelAccum.deltaY -= dy+ }+ wheelScheduler.schedule()+ }++ useWheelGesture(+ canvasRef,+ ({ event, last }) => {+ if (!last) onWheel(event)+ },+ {+ eventOptions: { passive: false },+ preventDefault: true+ }+ )+}diff --git a/packages/vue/src/shared/useCanvas.ts b/packages/vue/src/shared/useCanvas.tsdeleted file mode 100644index 673be5846..000000000--- a/packages/vue/src/shared/useCanvas.ts+++ /dev/null@@ -1,223 +0,0 @@-import { useRafFn, useResizeObserver } from '@vueuse/core'-import { onMounted, onScopeDispose, type Ref } from 'vue'--import { getCanvasKit, SkiaRenderer } from '@open-pencil/core'--import { useViewportKind } from '../viewport/useViewportKind'--import type { Editor } from '@open-pencil/core/editor'-import type { CanvasKit } from 'canvaskit-wasm'--/**- * Options for {@link useCanvas}.- */-export interface UseCanvasOptions {- /**- * Forces ruler visibility on or off for this canvas.- *- * When omitted, the composable falls back to viewport and URL-param logic.- */- showRulers?: boolean- /**- * Keeps the drawing buffer after presenting frames.- *- * Useful for screenshot or pixel-readback workflows, but may increase memory- * usage depending on the browser and GPU backend.- */- preserveDrawingBuffer?: boolean- /**- * Called once the rendering surface is ready.- */- onReady?: () => void-}--/**- * Connects an OpenPencil editor to a real canvas element using CanvasKit.- *- * This composable owns renderer creation, surface recreation on resize,- * render scheduling, and renderer-backed hit testing helpers used by higher-- * level canvas interaction code.- */-export function useCanvas(- canvasRef: Ref<HTMLCanvasElement | null>,- editor: Editor,- options?: UseCanvasOptions-) {- let renderer: SkiaRenderer | null = null- let ck: CanvasKit | null = null- let glContext: ReturnType<CanvasKit['MakeGrContext']> | null = null- let destroyed = false- let dirty = true- let lastRenderVersion = -1- let lastSelectedIds: Set<string> | null = null-- async function init() {- const canvas = canvasRef.value- if (!canvas || destroyed) return-- ck = await getCanvasKit()- if (destroyed) return-- await new Promise((r) => requestAnimationFrame(r))- createSurface(canvas)- await renderer?.loadFonts()- if (!destroyed) renderNow()- }-- function sizeCanvas(canvas: HTMLCanvasElement) {- const dpr = window.devicePixelRatio || 1- canvas.width = canvas.clientWidth * dpr- canvas.height = canvas.clientHeight * dpr- const maybeSizedEditor = editor as Editor & {- setViewportSize?: (width: number, height: number) => void- }- maybeSizedEditor.setViewportSize?.(canvas.clientWidth, canvas.clientHeight)- }-- function makeGLSurface(canvas: HTMLCanvasElement) {- if (!ck) return null- if (!glContext) {- const glAttrs = options?.preserveDrawingBuffer ? { preserveDrawingBuffer: 1 } : undefined- const handle = ck.GetWebGLContext(canvas, glAttrs)- if (!handle) return null- glContext = ck.MakeGrContext(handle)- }- if (!glContext) return null-- const preferredSpace = editor.graph.documentColorSpace- const colorSpaces =- preferredSpace === 'display-p3'- ? [ck.ColorSpace.DISPLAY_P3, ck.ColorSpace.SRGB]- : [ck.ColorSpace.SRGB]-- for (const colorSpace of colorSpaces) {- const surface = ck.MakeOnScreenGLSurface(glContext, canvas.width, canvas.height, colorSpace)- if (surface) return surface- }-- return null- }-- function createSurface(canvas: HTMLCanvasElement) {- if (!ck) return-- renderer?.destroy()- renderer = null- glContext?.delete()- glContext = null-- sizeCanvas(canvas)-- const surface = makeGLSurface(canvas)- if (!surface) {- console.error('Failed to create WebGL surface')- return- }-- const glCtx = canvas.getContext('webgl2') ?? null- renderer = new SkiaRenderer(ck, surface, glCtx)- editor.setCanvasKit(ck, renderer)- canvas.dataset.ready = '1'- options?.onReady?.()- }-- const params =- typeof window !== 'undefined'- ? new URLSearchParams(window.location.search)- : new URLSearchParams()- const noRulersParam = params.has('no-rulers')- const { isMobile } = useViewportKind()-- function shouldShowRulers() {- if (options?.showRulers === false) return false- return !noRulersParam && !isMobile.value- }-- function renderNow() {- if (!renderer || destroyed) return- renderer.renderFromEditorState(- editor.state,- editor.graph,- editor.textEditor,- canvasRef.value?.clientWidth ?? 0,- canvasRef.value?.clientHeight ?? 0,- shouldShowRulers()- )- lastRenderVersion = editor.state.renderVersion- lastSelectedIds = editor.state.selectedIds- }-- const { pause } = useRafFn(() => {- if (editor.state.loading) return- const versionChanged = editor.state.renderVersion !== lastRenderVersion- const selectionChanged = editor.state.selectedIds !== lastSelectedIds- if (dirty || versionChanged || selectionChanged) {- dirty = false- renderNow()- }- })-- onMounted(() => {- void init()- })-- onScopeDispose(() => {- destroyed = true- pause()- cancelAnimationFrame(resizeRaf)- renderer?.destroy()- glContext?.delete()- })-- let resizeRaf = 0- useResizeObserver(canvasRef, () => {- const canvas = canvasRef.value- if (!canvas || !ck || resizeRaf) return- resizeRaf = requestAnimationFrame(() => {- resizeRaf = 0- resizeCanvas(canvas)- })- })-- function resizeCanvas(canvas: HTMLCanvasElement) {- if (!ck || !renderer) {- createSurface(canvas)- return- }-- sizeCanvas(canvas)-- const surface = makeGLSurface(canvas)- if (!surface) {- console.warn('Falling back to full surface recreation after resize')- createSurface(canvas)- return- }- renderer.replaceSurface(surface)- renderNow()- }-- function hitTestSectionTitle(canvasX: number, canvasY: number) {- return renderer?.hitTestSectionTitle(editor.graph, canvasX, canvasY) ?? null- }-- function hitTestComponentLabel(canvasX: number, canvasY: number) {- return renderer?.hitTestComponentLabel(editor.graph, canvasX, canvasY) ?? null- }-- function hitTestFrameTitle(canvasX: number, canvasY: number) {- return (- renderer?.hitTestFrameTitle(editor.graph, canvasX, canvasY, editor.state.selectedIds) ?? null- )- }-- return {- render: () => {- dirty = true- },- renderNow,- hitTestSectionTitle,- hitTestComponentLabel,- hitTestFrameTitle- }-}diff --git a/packages/vue/src/VariablesEditor/useVariablesDialogState.ts b/packages/vue/src/variables/dialog/use.tssimilarity index 96%rename from packages/vue/src/VariablesEditor/useVariablesDialogState.tsrename to packages/vue/src/variables/dialog/use.tsindex ee8662056..30c8309ff 100644--- a/packages/vue/src/VariablesEditor/useVariablesDialogState.ts+++ b/packages/vue/src/variables/dialog/use.ts@@ -1,7 +1,6 @@+import { useVariables } from '#vue/variables/use'import { nextTick, ref } from 'vue'-import { useVariables } from './useVariables'-export function useVariablesDialogState() {const variables = useVariables()diff --git a/packages/vue/src/VariablesEditor/useVariablesEditor.ts b/packages/vue/src/variables/editor/use.tssimilarity index 92%rename from packages/vue/src/VariablesEditor/useVariablesEditor.tsrename to packages/vue/src/variables/editor/use.tsindex c09347aa5..ba85351b7 100644--- a/packages/vue/src/VariablesEditor/useVariablesEditor.ts+++ b/packages/vue/src/variables/editor/use.ts@@ -1,9 +1,8 @@+import { useVariablesDialogState } from '#vue/variables/dialog/use'+import { useVariablesTable } from '#vue/variables/table/use'import { useVueTable, getCoreRowModel } from '@tanstack/vue-table'import { computed, type Component } from 'vue'-import { useVariablesDialogState } from './useVariablesDialogState'-import { useVariablesTable } from './useVariablesTable'-/*** Composes variables dialog state, table columns, and TanStack table wiring* into a single higher-level variables editor API.diff --git a/packages/vue/src/VariablesEditor/useVariables.ts b/packages/vue/src/variables/helpers.tssimilarity index 57%rename from packages/vue/src/VariablesEditor/useVariables.tsrename to packages/vue/src/variables/helpers.tsindex 30ed5af19..1d8ccdc53 100644--- a/packages/vue/src/VariablesEditor/useVariables.ts+++ b/packages/vue/src/variables/helpers.ts@@ -1,37 +1,14 @@-import { ref, computed, watch } from 'vue'+import { colorToHexRaw, parseColor } from '@open-pencil/core/color'+import { randomHex } from '@open-pencil/core/random'-import { colorToHexRaw, parseColor, randomHex } from '@open-pencil/core'-import { useEditor } from '@open-pencil/vue/context/editorContext'-import { useSceneComputed } from '@open-pencil/vue/internal/useSceneComputed'--import type { Color, Variable, VariableCollection, VariableValue } from '@open-pencil/core'--export function useVariables() {- const editor = useEditor()- const searchTerm = ref('')-- function setSearchTerm(term: string) {- searchTerm.value = term- }-- const collections = useSceneComputed(() => editor.getCollections())-- const activeCollectionId = ref(collections.value[0]?.id ?? '')- watch(collections, (cols) => {- if (!activeCollectionId.value && cols[0]) activeCollectionId.value = cols[0].id- })-- const activeCollection = computed(() => editor.getCollection(activeCollectionId.value) ?? null)- const activeModes = computed(() => activeCollection.value?.modes ?? [])-- const variables = useSceneComputed(() => {- if (!activeCollectionId.value) return [] as Variable[]- const all = editor.getVariablesForCollection(activeCollectionId.value)- if (!searchTerm.value) return all- const q = searchTerm.value.toLowerCase()- return all.filter((v) => v.name.toLowerCase().includes(q))- })+import type { Variable, VariableCollection, VariableValue } from '@open-pencil/core/scene-graph'+import type { Editor } from '@open-pencil/core/editor'+import type { Ref } from 'vue'+export function createVariableCollectionActions(+ editor: Editor,+ activeCollectionId: Ref<string>+) {function setActiveCollection(id: string) {activeCollectionId.value = id}@@ -53,8 +30,15 @@ export function useVariables() {editor.renameCollection(id, newName)}+ return { setActiveCollection, addCollection, renameCollection }+}++export function createVariableValueActions(+ editor: Editor,+ getActiveCollection: () => VariableCollection | null+) {function addVariable() {- const col = activeCollection.value+ const col = getActiveCollection()if (!col) returnconst id = `var:${randomHex(8)}`@@ -88,8 +72,7 @@ export function useVariables() {function formatModeValue(variable: Variable, modeId: string): string {const value = variable.valuesByMode[modeId]- if (value === undefined) return '—'- if (typeof value === 'object' && 'r' in value) return colorToHexRaw(value as Color)+ if (typeof value === 'object' && 'r' in value) return colorToHexRaw(value)if (typeof value === 'object' && 'aliasId' in value) {const aliased = editor.getVariable(value.aliasId)return aliased ? `→ ${aliased.name}` : '→ ?'@@ -98,9 +81,7 @@ export function useVariables() {}function parseVariableValue(variable: Variable, raw: string): VariableValue | undefined {- if (variable.type === 'COLOR') {- return parseColor(raw.startsWith('#') ? raw : `#${raw}`) ?? undefined- }+ if (variable.type === 'COLOR') return parseColor(raw.startsWith('#') ? raw : `#${raw}`)if (variable.type === 'FLOAT') {const num = parseFloat(raw)return isNaN(num) ? undefined : num@@ -115,17 +96,6 @@ export function useVariables() {}return {- editor,- collections,- activeCollectionId,- activeCollection,- activeModes,- variables,- searchTerm,- setSearchTerm,- setActiveCollection,- addCollection,- renameCollection,addVariable,removeVariable,renameVariable,diff --git a/packages/vue/src/variables/table/helpers.ts b/packages/vue/src/variables/table/helpers.tsnew file mode 100644index 000000000..29cbb5719--- /dev/null+++ b/packages/vue/src/variables/table/helpers.ts@@ -0,0 +1,147 @@+import { EditableArea, EditableInput, EditablePreview, EditableRoot } from 'reka-ui'+import { h, type Component, type ComputedRef } from 'vue'++import type { Variable, VariableValue } from '@open-pencil/core/scene-graph'+import type { Color } from '@open-pencil/core/types'+import type { ColumnDef } from '@tanstack/vue-table'++export interface VariablesTableOptions {+ activeModes: ComputedRef<{ modeId: string; name: string }[]>+ formatModeValue: (variable: Variable, modeId: string) => string+ parseVariableValue: (variable: Variable, raw: string) => VariableValue | undefined+ shortName: (variable: Variable) => string+ renameVariable: (id: string, newName: string) => void+ updateVariableValue: (id: string, modeId: string, value: VariableValue) => void+ removeVariable: (id: string) => void+ ColorInput: Component+ icons: Record<string, Component>+ fallbackIcon: Component+ deleteIcon: Component+}++function commitNameEdit(options: VariablesTableOptions, variable: Variable, newName: string) {+ if (newName && newName !== variable.name) {+ options.renameVariable(variable.id, newName)+ }+}++function commitValueEdit(+ options: VariablesTableOptions,+ variable: Variable,+ modeId: string,+ newValue: string+) {+ const parsed = options.parseVariableValue(variable, newValue)+ if (parsed !== undefined) {+ options.updateVariableValue(variable.id, modeId, parsed)+ }+}++function createVariableNameColumn(options: VariablesTableOptions): ColumnDef<Variable> {+ return {+ id: 'name',+ header: 'Name',+ size: 200,+ minSize: 120,+ maxSize: 400,+ cell: ({ row }) => {+ const variable = row.original+ const iconClass = 'size-3.5 shrink-0 text-muted'+ const iconComponent = options.icons[variable.type] ?? options.fallbackIcon+ const icon = h(iconComponent, { class: iconClass })++ return h('div', { class: 'flex items-center gap-2' }, [+ icon,+ h(+ EditableRoot,+ {+ defaultValue: options.shortName(variable),+ class: 'min-w-0 flex-1',+ onSubmit: (value: string | null | undefined) =>+ value && commitNameEdit(options, variable, value)+ },+ () =>+ h(EditableArea, { class: 'flex' }, () => [+ h(EditablePreview, {+ class: 'min-w-0 flex-1 cursor-text truncate text-xs text-surface'+ }),+ h(EditableInput, {+ class:+ 'min-w-0 flex-1 rounded border border-border bg-surface/10 px-1 py-0.5 text-xs text-surface outline-none'+ })+ ])+ )+ ])+ }+ }+}++function createVariableModeColumns(options: VariablesTableOptions): ColumnDef<Variable>[] {+ return options.activeModes.value.map((mode) => ({+ id: `mode-${mode.modeId}`,+ header: mode.name,+ size: 200,+ minSize: 120,+ maxSize: 500,+ cell: ({ row }) => {+ const variable = row.original+ const value = variable.valuesByMode[mode.modeId]++ if (variable.type === 'COLOR' && value && typeof value === 'object' && 'r' in value) {+ return h(options.ColorInput, {+ color: value,+ onUpdate: (color: Color) => options.updateVariableValue(variable.id, mode.modeId, color)+ })+ }++ return h(+ EditableRoot,+ {+ defaultValue: options.formatModeValue(variable, mode.modeId),+ class: 'min-w-0 flex-1',+ onSubmit: (submitted: string | null | undefined) =>+ submitted && commitValueEdit(options, variable, mode.modeId, submitted)+ },+ () =>+ h(EditableArea, { class: 'flex' }, () => [+ h(EditablePreview, {+ class: 'min-w-0 flex-1 cursor-text truncate font-mono text-xs text-muted'+ }),+ h(EditableInput, {+ class:+ 'min-w-0 flex-1 rounded border border-border bg-surface/10 px-1 py-0.5 font-mono text-xs text-surface outline-none'+ })+ ])+ )+ }+ }))+}++function createDeleteColumn(options: VariablesTableOptions): ColumnDef<Variable> {+ return {+ id: 'actions',+ header: '',+ size: 36,+ minSize: 36,+ maxSize: 36,+ enableResizing: false,+ cell: ({ row }) =>+ h(+ 'button',+ {+ class:+ 'flex size-5 cursor-pointer items-center justify-center rounded border-none bg-transparent text-muted opacity-0 transition-opacity group-hover:opacity-100 hover:text-surface',+ onClick: () => options.removeVariable(row.original.id)+ },+ h(options.deleteIcon, { class: 'size-3' })+ )+ }+}++export function createVariableColumns(options: VariablesTableOptions): ColumnDef<Variable>[] {+ return [+ createVariableNameColumn(options),+ ...createVariableModeColumns(options),+ createDeleteColumn(options)+ ]+}diff --git a/packages/vue/src/variables/table/use.ts b/packages/vue/src/variables/table/use.tsnew file mode 100644index 000000000..87b3d4e5e--- /dev/null+++ b/packages/vue/src/variables/table/use.ts@@ -0,0 +1,8 @@+import { createVariableColumns, type VariablesTableOptions } from '#vue/variables/table/helpers'+import { computed } from 'vue'++export function useVariablesTable(options: VariablesTableOptions) {+ const columns = computed(() => createVariableColumns(options))++ return { columns }+}diff --git a/packages/vue/src/variables/use.ts b/packages/vue/src/variables/use.tsnew file mode 100644index 000000000..36d0e26aa--- /dev/null+++ b/packages/vue/src/variables/use.ts@@ -0,0 +1,52 @@+import { useEditor } from '#vue/editor/context'+import { useSceneComputed } from '#vue/internal/scene-computed/use'+import {+ createVariableCollectionActions,+ createVariableValueActions+} from '#vue/variables/helpers'+import { ref, computed, watch } from 'vue'++import type { Variable } from '@open-pencil/core/scene-graph'++export function useVariables() {+ const editor = useEditor()+ const searchTerm = ref('')++ function setSearchTerm(term: string) {+ searchTerm.value = term+ }++ const collections = useSceneComputed(() => editor.getCollections())++ const activeCollectionId = ref(collections.value[0]?.id ?? '')+ watch(collections, (cols) => {+ if (!activeCollectionId.value && cols[0]) activeCollectionId.value = cols[0].id+ })++ const activeCollection = computed(() => editor.getCollection(activeCollectionId.value) ?? null)+ const activeModes = computed(() => activeCollection.value?.modes ?? [])++ const variables = useSceneComputed(() => {+ if (!activeCollectionId.value) return [] as Variable[]+ const all = editor.getVariablesForCollection(activeCollectionId.value)+ if (!searchTerm.value) return all+ const q = searchTerm.value.toLowerCase()+ return all.filter((v) => v.name.toLowerCase().includes(q))+ })++ const collectionActions = createVariableCollectionActions(editor, activeCollectionId)+ const variableActions = createVariableValueActions(editor, () => activeCollection.value)++ return {+ editor,+ collections,+ activeCollectionId,+ activeCollection,+ activeModes,+ variables,+ searchTerm,+ setSearchTerm,+ ...collectionActions,+ ...variableActions+ }+}diff --git a/packages/vue/tsconfig.json b/packages/vue/tsconfig.jsonindex 58b806a82..23d81539b 100644--- a/packages/vue/tsconfig.json+++ b/packages/vue/tsconfig.json@@ -13,10 +13,10 @@"skipLibCheck": true,"esModuleInterop": true,"resolveJsonModule": true,- "baseUrl": ".","paths": {+ "#vue/*": ["./src/*", "./src/*.vue"],+ "#core/*": ["../core/src/*"],"@open-pencil/vue": ["./src/index.ts"],- "@open-pencil/vue/*": ["./src/*"],"@open-pencil/core": ["../core/src/index.ts"],"@open-pencil/core/*": ["../core/src/*"],"@open-pencil/core/editor": ["../core/src/editor/index.ts"],diff --git a/packages/vue/tsdown.config.ts b/packages/vue/tsdown.config.tsindex e41017342..b2dbd6d59 100644--- a/packages/vue/tsdown.config.ts+++ b/packages/vue/tsdown.config.ts@@ -10,7 +10,8 @@ export default defineConfig({format: ['esm'],dts: {vue: true,- sourcemap: true+ sourcemap: true,+ resolver: 'tsc'},sourcemap: true,hash: false,@@ -19,30 +20,38 @@ export default defineConfig({treeshake: {moduleSideEffects: false},- external: [- 'vue',- /^vue\//,- '@open-pencil/core',- /^@open-pencil\/core\//,- 'canvaskit-wasm',- '@vueuse/core',- '@nanostores/vue',- '@nanostores/i18n',- 'nanostores',- '@tanstack/vue-table',- 'reka-ui',- '@atlaskit/pragmatic-drag-and-drop',- /^@atlaskit\/pragmatic-drag-and-drop\//,- '@atlaskit/pragmatic-drag-and-drop-hitbox',- /^@atlaskit\/pragmatic-drag-and-drop-hitbox\//- ],+ deps: {+ neverBundle: [+ 'vue',+ /^vue\//,+ '@open-pencil/core',+ /^@open-pencil\/core\//,+ 'canvaskit-wasm',+ 'opentype.js',+ '@vueuse/core',+ '@use-gesture/vanilla',+ '@nanostores/vue',+ '@nanostores/i18n',+ 'nanostores',+ '@tanstack/vue-table',+ 'reka-ui',+ '@atlaskit/pragmatic-drag-and-drop',+ /^@atlaskit\/pragmatic-drag-and-drop\//,+ '@atlaskit/pragmatic-drag-and-drop-hitbox',+ /^@atlaskit\/pragmatic-drag-and-drop-hitbox\//+ ],+ onlyBundle: false+ },plugins: [raw(), vue()],inputOptions: {- preserveEntrySignatures: 'allow-extension'+ preserveEntrySignatures: 'allow-extension',+ checks: {+ pluginTimings: false+ }},outputOptions: {minifyInternalExports: false,- advancedChunks: {+ codeSplitting: {groups: [{test: /(?<!\.d\.c?ts)$/,diff --git a/plan-refactor.md b/plan-refactor.mddeleted file mode 100644index ed90603d2..000000000--- a/plan-refactor.md+++ /dev/null@@ -1,54 +0,0 @@-# Refactor Plan — Architecture Cleanup--## Status: DONE ✓--## 1. tools/schema.ts cleanup [P0] ✓-- Deleted all duplicate tool definitions from schema.ts: 1831 → 65 lines-- Fixed tools/index.ts to export ALL_TOOLS from registry-- Fixed renderJsx → renderJSX typo in create.ts and structure.ts--## 2. geometry.ts extraction [P0] ✓-- Created packages/core/src/geometry.ts with degToRad, radToDeg, rotatePoint, rotatedCorners, rotatedBBox-- Exported from core index.ts-- Consumer refactoring (snap.ts, kiwi-serialize.ts, use-canvas-input.ts) deferred — functions available for new code--## 3. renderer/ directory split [P1] ✓-- Split 3206-line renderer.ts into renderer/ directory (10 files)-- renderer.ts (1144) — class with delegations, constructor, render(), loadFonts(), surface mgmt-- overlays.ts (760) — selection, hover, snap, marquee, flashes, pen, remote cursors, text edit overlay-- scene.ts (490) — node rendering pipeline, effects, text-- rulers.ts (235) — ruler drawing and badges-- fills.ts (233) — fill application, gradients, images, arcs-- strokes.ts (221) — stroke drawing with alignment-- labels.ts (212) — section titles and component labels-- shapes.ts (193) — path/shape creation and geometry caching-- effects.ts (64) — image/mask filter caching--## 4. isMixed() helper [P1] ✓-- Added isArrayMixed() to use-multi-props.ts-- Deduplicated FillSection, StrokeSection, EffectsSection (each lost 4 lines of boilerplate)--## 5. Test imports cleanup ✓-- All tests now use `@open-pencil/core` instead of relative paths into packages/core/src/-- Merged duplicate import statements across all test files-- Fixed 3 broken test imports (stale paths to src/engine/ and src/kiwi/)-- Exported profiler internals and style-run helpers from core index.ts--## 6. Test coverage [P0-P1] ✓-New test files (98 new tests, 683 total → all green):-- color.test.ts — parseColor, colorToHex, colorToCSS (14 tests)-- undo.test.ts — UndoManager apply/push/undo/redo/batch/clear (12 tests)-- snap.test.ts — computeSnap, computeSelectionBounds (9 tests)-- vector.test.ts — vectorNetworkBlob round-trip, computeVectorBounds (10 tests)-- style-runs.test.ts — toggleBold/Italic/Decoration, adjustRuns, applyStyle (18 tests)-- text-editor.test.ts — insert/delete/cursor/selection/word ops (25 tests)--## 7. Bug fixes (found during audit) ✓-- renderJsx → renderJSX typo in tools/create.ts and tools/structure.ts-- 3 broken test file imports (stale paths after monorepo reorganization)--## Future work (not in this batch)-- Refactor consumers to use geometry.ts (snap.ts, kiwi-serialize.ts, use-canvas-input.ts)-- Split editor.ts store into sub-composables (~2184 lines, 91 functions)-- Split use-canvas-input.ts drag handlers (~1298 lines)-- Unify decompress utilities (kiwi-serialize.ts vs kiwi/codec.ts)diff --git a/scripts/visual-compare.ts b/scripts/visual-compare.tsindex 0d22bc55f..a5a8add75 100644--- a/scripts/visual-compare.ts+++ b/scripts/visual-compare.ts@@ -18,16 +18,12 @@ import { parseArgs } from 'node:util'import { existsSync, mkdirSync } from 'node:fs'import { $ } from 'bun'-import {- parseFigmaClipboard,- importClipboardNodes,- computeAllLayouts,- SceneGraph,- loadFont,- SkiaRenderer,- renderNodesToImage-} from '@open-pencil/core'-import { initCanvasKit } from '../packages/cli/src/headless'+import { parseFigmaClipboard, importClipboardNodes } from '#core/clipboard'+import { SkiaRenderer } from '@open-pencil/core/canvas'+import { renderNodesToImage, initCanvasKit } from '@open-pencil/core/io'+import { computeAllLayouts } from '@open-pencil/core/layout'+import { SceneGraph } from '@open-pencil/core/scene-graph'+import { loadFont } from '@open-pencil/core/text'const { values: opts } = parseArgs({options: {@@ -143,9 +139,7 @@ async function renderOurs(html: string) {async function renderFigmaViaPaste() {// Create temp page so we don't pollute the user's work- const createPage =- await $`figma-use eval ${'(() => { const p = figma.createPage(); p.name = "__visual_compare__"; figma.currentPage = p; return p.id; })()'} --json`.quiet()- const tmpPageId = JSON.parse(createPage.text().trim())+ await $`figma-use eval ${'(() => { const p = figma.createPage(); p.name = "__visual_compare__"; figma.currentPage = p; return p.id; })()'} --json`.quiet()try {// Activate Figma and pastediff --git a/src/App.vue b/src/App.vueindex 0467c1562..406959b6e 100644--- a/src/App.vue+++ b/src/App.vue@@ -5,8 +5,8 @@ import { TooltipProvider } from 'reka-ui'import { provideEditor } from '@open-pencil/vue'import AppToast from '@/components/AppToast.vue'-import { useEditorStore } from '@/stores/editor'-import { toast } from '@/utils/toast'+import { useEditorStore } from '@/app/editor/active-store'+import { toast } from '@/app/shell/ui'useHead({ titleTemplate: (title) => (title ? `${title} — OpenPencil` : 'OpenPencil') })diff --git a/src/app/ai/acp/design-context.md b/src/app/ai/acp/design-context.mdnew file mode 100644index 000000000..d8ed74794--- /dev/null+++ b/src/app/ai/acp/design-context.md@@ -0,0 +1 @@+You are inside OpenPencil, an open-source design editor (like Figma). Use the open-pencil MCP tools to create and modify designs on the live canvas. Key tools: render (JSX to design), create_shape, set_fill, set_layout, find_nodes, get_page_tree, export_image. The render tool accepts JSX with components: Frame, Text, Rectangle, Ellipse, Icon, Group, Section. Props: w, h, bg, flex, gap, p, rounded, color, size, weight, items, justify, stroke, opacity, shadow. Do NOT write HTML files or use terminal commands — draw directly on the canvas using the MCP tools.diff --git a/src/ai/acp-map-update.ts b/src/app/ai/acp/map-update.tssimilarity index 100%rename from src/ai/acp-map-update.tsrename to src/app/ai/acp/map-update.tsdiff --git a/src/ai/acp-permission.ts b/src/app/ai/acp/permission.tssimilarity index 100%rename from src/ai/acp-permission.tsrename to src/app/ai/acp/permission.tsdiff --git a/src/app/ai/acp/process.ts b/src/app/ai/acp/process.tsnew file mode 100644index 000000000..f013760f9--- /dev/null+++ b/src/app/ai/acp/process.ts@@ -0,0 +1,92 @@+import { decodeTauriStderr } from '@/app/shell/ui'++export type TauriChild = {+ write(data: number[]): Promise<void>+ kill(): Promise<void>+}++type AcpProcessOptions = {+ command: string+ args: string[]+ logId: string+ destroying: () => boolean+ onUnexpectedClose: () => void+}++export async function spawnAcpProcess({+ command: commandName,+ args,+ logId,+ destroying,+ onUnexpectedClose+}: AcpProcessOptions) {+ const { Command } = await import('@tauri-apps/plugin-shell')+ const command = Command.create(commandName, args, { encoding: 'raw' })++ const stdoutChunks: Uint8Array[] = []+ let stdoutResolver: ((chunk: Uint8Array | null) => void) | null = null+ let stdoutClosed = false+ let stdoutClosedError: Error | null = null++ command.stdout.on('data', (raw: Uint8Array | number[]) => {+ const chunk = raw instanceof Uint8Array ? raw : new Uint8Array(raw)+ if (stdoutResolver) {+ const resolve = stdoutResolver+ stdoutResolver = null+ resolve(chunk)+ } else {+ stdoutChunks.push(chunk)+ }+ })++ command.stderr.on('data', (raw: Uint8Array | number[] | string) => {+ console.error(`[ACP ${logId}]`, decodeTauriStderr(raw))+ })++ command.on('close', () => {+ stdoutClosed = true+ stdoutClosedError = destroying() ? null : new Error('Agent process exited unexpectedly.')+ if (stdoutResolver) {+ const resolve = stdoutResolver+ stdoutResolver = null+ resolve(null)+ }+ if (!destroying()) {+ onUnexpectedClose()+ }+ })++ const child = await command.spawn()++ const output = new ReadableStream<Uint8Array>({+ async pull(controller) {+ const buffered = stdoutChunks.shift()+ if (buffered) {+ controller.enqueue(buffered)+ return+ }+ if (stdoutClosed) {+ if (stdoutClosedError) controller.error(stdoutClosedError)+ else controller.close()+ return+ }+ const chunk = await new Promise<Uint8Array | null>((resolve) => {+ stdoutResolver = resolve+ })+ if (chunk) {+ controller.enqueue(chunk)+ return+ }+ if (stdoutClosedError) controller.error(stdoutClosedError)+ else controller.close()+ }+ })++ const input = new WritableStream<Uint8Array>({+ async write(chunk) {+ await child.write(Array.from(chunk))+ }+ })++ return { child, input, output }+}diff --git a/src/ai/acp-transport.ts b/src/app/ai/acp/transport.tssimilarity index 74%rename from src/ai/acp-transport.tsrename to src/app/ai/acp/transport.tsindex 61c7dca2d..f637f667e 100644--- a/src/ai/acp-transport.ts+++ b/src/app/ai/acp/transport.ts@@ -1,9 +1,9 @@import { ClientSideConnection, ndJsonStream, PROTOCOL_VERSION } from '@agentclientprotocol/sdk'-import SYSTEM_PROMPT from '@/ai/system-prompt.md?raw'-import { decodeTauriStderr } from '@/utils/tauri'+import SYSTEM_PROMPT from '@/app/ai/chat/system-prompt.md?raw'-import { mapUpdate } from './acp-map-update'+import { mapUpdate } from './map-update'+import { spawnAcpProcess } from './process'import type {Client,@@ -12,12 +12,15 @@ import type {RequestPermissionRequest,RequestPermissionResponse} from '@agentclientprotocol/sdk'-import type { ACPAgentDef } from '@open-pencil/core'+import type { ACPAgentDef } from '@open-pencil/core/constants'import type { ChatTransport, UIMessage, UIMessageChunk } from 'ai'-type TauriChild = {- write(data: number[]): Promise<void>- kill(): Promise<void>+type TauriChild = Awaited<ReturnType<typeof spawnAcpProcess>>['child']++interface ACPDebugEntry {+ ts: number+ type: string+ data: unknown}interface ACPSession {@@ -28,6 +31,34 @@ interface ACPSession {dead: boolean}+const MAX_LOG_AGE_MS = 5 * 60 * 1000+const IS_DEV = import.meta.env.DEV++const acpDebugLog: ACPDebugEntry[] = []++function pruneOldEntries() {+ const cutoff = Date.now() - MAX_LOG_AGE_MS+ while (acpDebugLog.length > 0 && acpDebugLog[0].ts < cutoff) {+ acpDebugLog.shift()+ }+}++export function getAcpDebugText(): string {+ pruneOldEntries()+ return acpDebugLog+ .map((e) => `[${new Date(e.ts).toISOString()}] ${e.type}\n${JSON.stringify(e.data, null, 2)}`)+ .join('\n\n---\n\n')+}++export function clearAcpDebugLog() {+ acpDebugLog.length = 0+}++export function hasAcpDebugEntries(): boolean {+ pruneOldEntries()+ return acpDebugLog.length > 0+}+function isMissingCommandError(message: string): boolean {const normalized = message.toLowerCase()return normalized.includes('enoent') || normalized.includes('program not found')@@ -73,40 +104,6 @@ export function buildCrashChunks(return { chunks, shouldNullSession: true }}-interface ACPDebugEntry {- ts: number- type: string- data: unknown-}--const MAX_LOG_AGE_MS = 5 * 60 * 1000-const IS_DEV = import.meta.env.DEV--export const acpDebugLog: ACPDebugEntry[] = []--function pruneOldEntries() {- const cutoff = Date.now() - MAX_LOG_AGE_MS- while (acpDebugLog.length > 0 && acpDebugLog[0].ts < cutoff) {- acpDebugLog.shift()- }-}--export function getAcpDebugText(): string {- pruneOldEntries()- return acpDebugLog- .map((e) => `[${new Date(e.ts).toISOString()}] ${e.type}\n${JSON.stringify(e.data, null, 2)}`)- .join('\n\n---\n\n')-}--export function clearAcpDebugLog() {- acpDebugLog.length = 0-}--export function hasAcpDebugEntries(): boolean {- pruneOldEntries()- return acpDebugLog.length > 0-}-export class ACPChatTransport implements ChatTransport<UIMessage> {private session: ACPSession | null = nullprivate agentDef: ACPAgentDef@@ -215,82 +212,24 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {}private async spawnAgent(): Promise<ACPSession> {- const { Command } = await import('@tauri-apps/plugin-shell')-- const command = Command.create(this.agentDef.command, this.agentDef.args, {- encoding: 'raw'- })-- const stdoutChunks: Uint8Array[] = []- let stdoutResolver: ((chunk: Uint8Array | null) => void) | null = null- let stdoutClosed = false- let stdoutClosedError: Error | null = null-- command.stdout.on('data', (raw: Uint8Array | number[]) => {- const chunk = raw instanceof Uint8Array ? raw : new Uint8Array(raw)- if (stdoutResolver) {- const resolve = stdoutResolver- stdoutResolver = null- resolve(chunk)- } else {- stdoutChunks.push(chunk)- }- })-- command.stderr.on('data', (raw: Uint8Array | number[] | string) => {- console.error(`[ACP ${this.agentDef.id}]`, decodeTauriStderr(raw))- })-- command.on('close', () => {- stdoutClosed = true- stdoutClosedError = this.destroying ? null : new Error('Agent process exited unexpectedly.')- if (stdoutResolver) {- const resolve = stdoutResolver- stdoutResolver = null- resolve(null)- }- if (this.destroying || !this.session) return- this.session.dead = true- this.session = null- })-- let child: TauriChild+ let process: Awaited<ReturnType<typeof spawnAcpProcess>>try {- child = await command.spawn()+ process = await spawnAcpProcess({+ command: this.agentDef.command,+ args: this.agentDef.args,+ logId: this.agentDef.id,+ destroying: () => this.destroying,+ onUnexpectedClose: () => {+ if (!this.session) return+ this.session.dead = true+ this.session = null+ }+ })} catch (e) {throw new Error(formatConnectionError(e, this.agentDef))}- const output = new ReadableStream<Uint8Array>({- async pull(controller) {- const buffered = stdoutChunks.shift()- if (buffered) {- controller.enqueue(buffered)- return- }- if (stdoutClosed) {- if (stdoutClosedError) controller.error(stdoutClosedError)- else controller.close()- return- }- const chunk = await new Promise<Uint8Array | null>((resolve) => {- stdoutResolver = resolve- })- if (chunk) {- controller.enqueue(chunk)- return- }- if (stdoutClosedError) controller.error(stdoutClosedError)- else controller.close()- }- })-- const input = new WritableStream<Uint8Array>({- async write(chunk) {- await child.write(Array.from(chunk))- }- })-+ const { child, input, output } = processconst stream = ndJsonStream(input, output)let onUpdate: ACPSession['onUpdate'] = null@@ -298,7 +237,7 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {async requestPermission(params: RequestPermissionRequest): Promise<RequestPermissionResponse> {- const { requestPermissionFromUser } = await import('@/ai/acp-permission')+ const { requestPermissionFromUser } = await import('@/app/ai/acp/permission')return requestPermissionFromUser(params)},@@ -308,7 +247,7 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {}const connection = new ClientSideConnection((_agent: Agent) => clientImpl, stream)- const { getAutomationAuthToken } = await import('@/automation/spawn-mcp')+ const { getAutomationAuthToken } = await import('@/app/automation/mcp/spawn')const automationAuthToken = await getAutomationAuthToken()await connection.initialize({diff --git a/src/app/ai/chat/model.ts b/src/app/ai/chat/model.tsnew file mode 100644index 000000000..2f22dc6c7--- /dev/null+++ b/src/app/ai/chat/model.ts@@ -0,0 +1,83 @@+import { createAnthropic } from '@ai-sdk/anthropic'+import { createGoogleGenerativeAI } from '@ai-sdk/google'+import { createOpenAI } from '@ai-sdk/openai'+import { createOpenRouter } from '@openrouter/ai-sdk-provider'++import type { AIProviderID } from '@open-pencil/core/constants'+import type { LanguageModel } from 'ai'++export type ModelConfig = {+ providerID: AIProviderID+ apiKey: string+ modelID: string+ customModelID: string+ customBaseURL: string+ customAPIType: 'completions' | 'responses'+}++export function createLanguageModel(config: ModelConfig): LanguageModel {+ const needsCustomModel =+ config.providerID === 'openai-compatible' || config.providerID === 'anthropic-compatible'+ const effectiveModelID = needsCustomModel ? config.customModelID : config.modelID++ switch (config.providerID) {+ case 'openrouter': {+ const openrouter = createOpenRouter({+ apiKey: config.apiKey,+ headers: {+ 'X-OpenRouter-Title': 'OpenPencil',+ 'HTTP-Referer': 'https://github.com/open-pencil/open-pencil'+ }+ })+ return openrouter(effectiveModelID)+ }+ case 'anthropic': {+ const anthropic = createAnthropic({ apiKey: config.apiKey })+ return anthropic(effectiveModelID)+ }+ case 'openai': {+ const openai = createOpenAI({ apiKey: config.apiKey })+ return openai(effectiveModelID)+ }+ case 'google': {+ const google = createGoogleGenerativeAI({ apiKey: config.apiKey })+ return google(effectiveModelID)+ }+ case 'zai': {+ const zai = createAnthropic({+ apiKey: config.apiKey,+ baseURL: 'https://api.z.ai/api/anthropic'+ })+ return zai(effectiveModelID)+ }+ case 'minimax': {+ const minimax = createOpenAI({+ apiKey: config.apiKey,+ baseURL: 'https://api.minimax.io/v1'+ })+ return minimax.chat(effectiveModelID)+ }+ case 'openai-compatible': {+ const custom = createOpenAI({+ apiKey: config.apiKey,+ baseURL: config.customBaseURL+ })+ return config.customAPIType === 'responses'+ ? custom.responses(effectiveModelID)+ : custom.chat(effectiveModelID)+ }+ case 'anthropic-compatible': {+ const custom = createAnthropic({+ apiKey: config.apiKey,+ baseURL: config.customBaseURL+ })+ return custom(effectiveModelID)+ }+ default: {+ if (config.providerID.startsWith('acp:')) {+ throw new Error('ACP providers do not use direct API models')+ }+ throw new Error(`Unknown provider: ${config.providerID}`)+ }+ }+}diff --git a/src/app/ai/chat/storage.ts b/src/app/ai/chat/storage.tsnew file mode 100644index 000000000..ac2eefc12--- /dev/null+++ b/src/app/ai/chat/storage.ts@@ -0,0 +1,101 @@+import { useLocalStorage } from '@vueuse/core'+import { computed, watch } from 'vue'++import {+ AI_PROVIDERS,+ DEFAULT_AI_MODEL,+ DEFAULT_AI_PROVIDER,+ IS_BROWSER,+ IS_TAURI,+} from '@open-pencil/core/constants'+import { setPexelsApiKey, setUnsplashAccessKey } from '@open-pencil/core/tools'++import type { AIProviderID } from '@open-pencil/core/constants'++const STORAGE_PREFIX = 'open-pencil:'+const LEGACY_KEY_STORAGE = `${STORAGE_PREFIX}openrouter-api-key`++export function keyStorageKey(id: string) {+ return `${STORAGE_PREFIX}ai-key:${id}`+}++function migrateLegacyStorage() {+ const legacyKey = localStorage.getItem(LEGACY_KEY_STORAGE)+ if (legacyKey) {+ localStorage.setItem(keyStorageKey('openrouter'), legacyKey)+ localStorage.removeItem(LEGACY_KEY_STORAGE)+ if (!localStorage.getItem(`${STORAGE_PREFIX}ai-provider`)) {+ localStorage.setItem(`${STORAGE_PREFIX}ai-provider`, 'openrouter')+ }+ }+}++if (IS_BROWSER) migrateLegacyStorage()++export const providerID = useLocalStorage<AIProviderID>(+ `${STORAGE_PREFIX}ai-provider`,+ DEFAULT_AI_PROVIDER+)+const apiKeyStorageKey = computed(() => keyStorageKey(providerID.value))+export const apiKey = useLocalStorage(apiKeyStorageKey, '')+export const modelID = useLocalStorage(`${STORAGE_PREFIX}ai-model`, DEFAULT_AI_MODEL)+export const customBaseURL = useLocalStorage(`${STORAGE_PREFIX}ai-base-url`, '')+export const customModelID = useLocalStorage(`${STORAGE_PREFIX}ai-custom-model`, '')+export const customAPIType = useLocalStorage<'completions' | 'responses'>(+ `${STORAGE_PREFIX}ai-api-type`,+ 'completions'+)+export const maxOutputTokens = useLocalStorage(`${STORAGE_PREFIX}ai-max-output-tokens`, 16384)+export const pexelsApiKey = useLocalStorage(`${STORAGE_PREFIX}pexels-api-key`, '')+export const unsplashAccessKey = useLocalStorage(`${STORAGE_PREFIX}unsplash-access-key`, '')++export const providerDef = computed(+ () => AI_PROVIDERS.find((p) => p.id === providerID.value) ?? AI_PROVIDERS[0]+)++export const isACPProvider = computed(() => providerID.value.startsWith('acp:'))++export const isConfigured = computed(() => {+ if (isACPProvider.value) return IS_TAURI+ if (!apiKey.value) return false+ const needsBaseURL =+ providerID.value === 'openai-compatible' || providerID.value === 'anthropic-compatible'+ if (needsBaseURL && !customBaseURL.value) return false+ return true+})++export function setAPIKey(key: string) {+ apiKey.value = key+}++export function registerAIChatEffects(markTransportDirty: () => void) {+ watch(+ pexelsApiKey,+ (key) => {+ setPexelsApiKey(key || null)+ },+ { immediate: true }+ )++ watch(+ unsplashAccessKey,+ (key) => {+ setUnsplashAccessKey(key || null)+ },+ { immediate: true }+ )++ watch(providerID, (id) => {+ const def = AI_PROVIDERS.find((p) => p.id === id)+ if (def?.defaultModel) {+ modelID.value = def.defaultModel+ }+ markTransportDirty()+ })++ watch(modelID, markTransportDirty)+ watch(customModelID, markTransportDirty)+ watch(customAPIType, markTransportDirty)+ watch(apiKey, markTransportDirty)+ watch(customBaseURL, markTransportDirty)+}diff --git a/src/ai/system-prompt.md b/src/app/ai/chat/system-prompt.mdsimilarity index 100%rename from src/ai/system-prompt.mdrename to src/app/ai/chat/system-prompt.mddiff --git a/src/app/ai/chat/transports.ts b/src/app/ai/chat/transports.tsnew file mode 100644index 000000000..e02257e8d--- /dev/null+++ b/src/app/ai/chat/transports.ts@@ -0,0 +1,200 @@+import { Chat } from '@ai-sdk/vue'+import { DirectChatTransport, stepCountIs, ToolLoopAgent } from 'ai'++import { createLanguageModel } from '@/app/ai/chat/model'+import SYSTEM_PROMPT from '@/app/ai/chat/system-prompt.md?raw'+import { MAX_AGENT_STEPS, createAITools, recordStepUsage, resetRunSteps } from '@/app/ai/tools'+import { ACP_AGENTS } from '@open-pencil/core/constants'++import type { getActiveEditorStore } from '@/app/editor/active-store'+import type { ACPAgentID, AIProviderID } from '@open-pencil/core/constants'+import type { UIMessage } from 'ai'+import type { ComputedRef, Ref } from 'vue'++type EditorStore = ReturnType<typeof getActiveEditorStore>++type ChatSessionOptions = {+ isConfigured: ComputedRef<boolean>+ isACPProvider: ComputedRef<boolean>+ providerID: Ref<AIProviderID>+ apiKey: Ref<string>+ modelID: Ref<string>+ customModelID: Ref<string>+ customBaseURL: Ref<string>+ customAPIType: Ref<'completions' | 'responses'>+ maxOutputTokens: Ref<number>+ getActiveEditorStore: () => EditorStore+}++type ToolLoopTransportOptions = {+ store: EditorStore+ providerID: AIProviderID+ apiKey: string+ modelID: string+ customModelID: string+ customBaseURL: string+ customAPIType: 'completions' | 'responses'+ maxOutputTokens: number+}++const ANTHROPIC_CACHE_CONTROL = {+ anthropic: { cacheControl: { type: 'ephemeral' } }+} as const++function supportsAnthropicCaching(providerID: AIProviderID, modelID: string): boolean {+ return (+ providerID === 'anthropic' ||+ providerID === 'anthropic-compatible' ||+ (providerID === 'openrouter' && modelID.startsWith('anthropic/'))+ )+}++export async function createACPTransport(providerID: AIProviderID) {+ const agentId = providerID.replace('acp:', '') as ACPAgentID+ const agentDef = ACP_AGENTS.find((a) => a.id === agentId)+ if (!agentDef) throw new Error(`Unknown ACP agent: ${agentId}`)++ const { ACPChatTransport } = await import('@/app/ai/acp/transport')+ const { homeDir } = await import('@tauri-apps/api/path')+ return new ACPChatTransport({ agentDef, cwd: await homeDir() })+}++export function createToolLoopTransport({+ store,+ providerID,+ apiKey,+ modelID,+ customModelID,+ customBaseURL,+ customAPIType,+ maxOutputTokens+}: ToolLoopTransportOptions) {+ const tools = createAITools(store)+ const cacheProviderOptions = supportsAnthropicCaching(providerID, modelID)+ ? ANTHROPIC_CACHE_CONTROL+ : undefined++ const agent = new ToolLoopAgent({+ model: createLanguageModel({+ providerID,+ apiKey,+ modelID,+ customModelID,+ customBaseURL,+ customAPIType+ }),+ instructions: SYSTEM_PROMPT,+ tools,+ stopWhen: stepCountIs(MAX_AGENT_STEPS),+ maxOutputTokens,+ providerOptions: cacheProviderOptions,+ prepareCall: (options) => {+ resetRunSteps(store)+ return {+ ...options,+ maxOutputTokens,+ providerOptions: cacheProviderOptions+ }+ },+ onStepFinish: ({ usage }) => {+ recordStepUsage(+ {+ inputTokens: usage.inputTokens ?? 0,+ outputTokens: usage.outputTokens ?? 0,+ cacheReadTokens: usage.inputTokenDetails.cacheReadTokens ?? 0,+ cacheWriteTokens: usage.inputTokenDetails.cacheWriteTokens ?? 0,+ timestamp: Date.now()+ },+ store+ )+ }+ })++ return new DirectChatTransport({ agent })+}++export function createChatSessionManager({+ isConfigured,+ isACPProvider,+ providerID,+ apiKey,+ modelID,+ customModelID,+ customBaseURL,+ customAPIType,+ maxOutputTokens,+ getActiveEditorStore+}: ChatSessionOptions) {+ let transportDirty = false+ let currentChatStore: EditorStore | null = null+ let currentChatMessages = new WeakMap<EditorStore, UIMessage[]>()+ let chat: Chat<UIMessage> | null = null+ let acpTransportInstance: { destroy(): Promise<void> } | null = null+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- test-only mock transports don't implement full generics+ let overrideTransport: (() => any) | null = null++ function markTransportDirty() {+ transportDirty = true+ currentChatStore = null+ currentChatMessages = new WeakMap()+ }++ async function createActiveACPTransport() {+ await acpTransportInstance?.destroy()+ const transport = await createACPTransport(providerID.value)+ acpTransportInstance = transport+ return transport+ }++ function createTransport(store: EditorStore) {+ if (overrideTransport) return overrideTransport()++ void acpTransportInstance?.destroy()+ acpTransportInstance = null++ return createToolLoopTransport({+ store,+ providerID: providerID.value,+ apiKey: apiKey.value,+ modelID: modelID.value,+ customModelID: customModelID.value,+ customBaseURL: customBaseURL.value,+ customAPIType: customAPIType.value,+ maxOutputTokens: maxOutputTokens.value+ })+ }++ async function ensureChat(): Promise<Chat<UIMessage> | null> {+ if (!isConfigured.value) return null++ const store = getActiveEditorStore()+ if (currentChatStore && chat) {+ currentChatMessages.set(currentChatStore, chat.messages)+ }++ if (!chat || transportDirty || currentChatStore !== store) {+ const messages = currentChatMessages.get(store)+ const transport = isACPProvider.value+ ? await createActiveACPTransport()+ : createTransport(store)+ chat = new Chat<UIMessage>({ transport, messages })+ currentChatStore = store+ transportDirty = false+ }+ return chat+ }++ function resetChat() {+ if (currentChatStore) currentChatMessages.delete(currentChatStore)+ chat = null+ currentChatStore = null+ transportDirty = false+ }++ function setOverrideTransport(factory: (() => unknown) | null) {+ overrideTransport = factory+ markTransportDirty()+ }++ return { ensureChat, resetChat, markTransportDirty, setOverrideTransport }+}diff --git a/src/app/ai/chat/use.ts b/src/app/ai/chat/use.tsnew file mode 100644index 000000000..32c3ea9da--- /dev/null+++ b/src/app/ai/chat/use.ts@@ -0,0 +1,64 @@+import { ref } from 'vue'++import {+ apiKey,+ customAPIType,+ customBaseURL,+ customModelID,+ isACPProvider,+ isConfigured,+ maxOutputTokens,+ modelID,+ pexelsApiKey,+ providerDef,+ providerID,+ registerAIChatEffects,+ setAPIKey,+ unsplashAccessKey+} from '@/app/ai/chat/storage'+import { createChatSessionManager } from '@/app/ai/chat/transports'+import { getActiveEditorStore } from '@/app/editor/active-store'+import { IS_BROWSER } from '@open-pencil/core/constants'++const activeTab = ref<'design' | 'code' | 'ai'>('design')++const chatSession = createChatSessionManager({+ isConfigured,+ isACPProvider,+ providerID,+ apiKey,+ modelID,+ customModelID,+ customBaseURL,+ customAPIType,+ maxOutputTokens,+ getActiveEditorStore+})++registerAIChatEffects(chatSession.markTransportDirty)++if (IS_BROWSER) {+ window.__OPEN_PENCIL_SET_TRANSPORT__ = (factory) => {+ chatSession.setOverrideTransport(factory)+ }+}++export function useAIChat() {+ return {+ providerID,+ providerDef,+ apiKey,+ setAPIKey,+ modelID,+ customBaseURL,+ customModelID,+ customAPIType,+ maxOutputTokens,+ pexelsApiKey,+ unsplashAccessKey,+ activeTab,+ isConfigured,+ ensureChat: chatSession.ensureChat,+ resetChat: chatSession.resetChat+ }+}diff --git a/src/ai/chat-debug.ts b/src/app/ai/debug/index.tssimilarity index 96%rename from src/ai/chat-debug.tsrename to src/app/ai/debug/index.tsindex 1de759f29..46c6e76d1 100644--- a/src/ai/chat-debug.ts+++ b/src/app/ai/debug/index.ts@@ -1,28 +1,52 @@-import { getStepUsages, getToolLogEntries } from '@/ai/tools'+import { getStepUsages, getToolLogEntries } from '@/app/ai/tools'import { buildDebugLog } from '@open-pencil/core/tools'import type { ToolDebugLog, ToolLogEntry } from '@open-pencil/core/tools'import type { UIMessage } from 'ai'-function formatToolPart(part: Record<string, unknown>): string {- const inv = part.toolInvocation as Record<string, unknown> | undefined- if (inv) {- const lines = [` [tool] ${String(inv.toolName)} (${String(inv.state)})`]- if (inv.args) lines.push(` args: ${JSON.stringify(inv.args)}`)- if (inv.result !== undefined) lines.push(` result: ${JSON.stringify(inv.result)}`)- return lines.join('\n')++export function formatTokenUsage(): string {+ const steps = getStepUsages()+ if (steps.length === 0) return ' (no usage data — provider may not report it)'++ let totalInput = 0+ let totalOutput = 0+ let totalCacheRead = 0+ let totalCacheWrite = 0++ const lines: string[] = []+ for (let i = 0; i < steps.length; i++) {+ const s = steps[i]+ totalInput += s.inputTokens+ totalOutput += s.outputTokens+ totalCacheRead += s.cacheReadTokens+ totalCacheWrite += s.cacheWriteTokens++ let cacheInfo = ' NO CACHE'+ if (s.cacheReadTokens > 0) {+ cacheInfo = ` cache_read=${s.cacheReadTokens}`+ } else if (s.cacheWriteTokens > 0) {+ cacheInfo = ` cache_write=${s.cacheWriteTokens}`+ }+ lines.push(` Step ${i + 1}: in=${s.inputTokens} out=${s.outputTokens}${cacheInfo}`)}- const name = (typeof part.type === 'string' ? part.type : 'unknown').replace(/^tool-/, '')- const state = typeof part.state === 'string' ? part.state : '?'- const lines = [` [tool] ${name} (${state})`]- if (part.input) lines.push(` input: ${JSON.stringify(part.input)}`)- if (part.output !== undefined) lines.push(` output: ${JSON.stringify(part.output)}`)- if (part.errorText) lines.push(` error: ${part.errorText as string}`)- return lines.join('\n')+ const cacheHitRate = totalInput > 0 ? ((totalCacheRead / totalInput) * 100).toFixed(1) : '0.0'+ const savedTokens = totalCacheRead > 0 ? totalCacheRead - Math.round(totalCacheRead * 0.1) : 0++ lines.unshift(+ `Total: in=${totalInput} out=${totalOutput} cache_read=${totalCacheRead} cache_write=${totalCacheWrite}`,+ `Cache hit rate: ${cacheHitRate}% (saved ~${savedTokens} uncached input tokens, 90% cost reduction on cached)`,+ `Steps: ${steps.length}`,+ totalCacheRead === 0 && totalCacheWrite === 0+ ? '⚠ NO CACHING DETECTED — system prompt + tools are re-processed every step'+ : ''+ )++ return lines.filter(Boolean).join('\n')}-function formatLogEntry(entry: ToolLogEntry, index: number): string {+export function formatLogEntry(entry: ToolLogEntry, index: number): string {const time = new Date(entry.timestamp).toISOString().slice(11, 23)const lines = [` #${index + 1} [${time}] ${entry.tool} (${entry.durationMs}ms)`]lines.push(` args: ${JSON.stringify(entry.args)}`)@@ -63,11 +87,11 @@ function diffNodeSnapshots(before: Record<string, unknown>,after: Record<string, unknown>): Array<{ prop: string; before: unknown; after: unknown }> {- const SKIP = new Set(['childIds', 'parentId', 'id'])+ const skip = new Set(['childIds', 'parentId', 'id'])const changed: Array<{ prop: string; before: unknown; after: unknown }> = []const allKeys = new Set([...Object.keys(before), ...Object.keys(after)])for (const key of allKeys) {- if (SKIP.has(key)) continue+ if (skip.has(key)) continueconst bStr = JSON.stringify(before[key])const aStr = JSON.stringify(after[key])if (bStr !== aStr) {@@ -77,7 +101,7 @@ function diffNodeSnapshots(return changed}-function formatDiagnostics(log: ToolDebugLog): string {+export function formatDiagnostics(log: ToolDebugLog): string {const sections: string[] = []sections.push(`Total tool calls: ${log.entries.length}`)@@ -129,6 +153,24 @@ function formatDiagnostics(log: ToolDebugLog): string {return sections.join('\n')}+function formatToolPart(part: Record<string, unknown>): string {+ const inv = part.toolInvocation as Record<string, unknown> | undefined+ if (inv) {+ const lines = [` [tool] ${String(inv.toolName)} (${String(inv.state)})`]+ if (inv.args) lines.push(` args: ${JSON.stringify(inv.args)}`)+ if (inv.result !== undefined) lines.push(` result: ${JSON.stringify(inv.result)}`)+ return lines.join('\n')+ }++ const name = (typeof part.type === 'string' ? part.type : 'unknown').replace(/^tool-/, '')+ const state = typeof part.state === 'string' ? part.state : '?'+ const lines = [` [tool] ${name} (${state})`]+ if (part.input) lines.push(` input: ${JSON.stringify(part.input)}`)+ if (part.output !== undefined) lines.push(` output: ${JSON.stringify(part.output)}`)+ if (part.errorText) lines.push(` error: ${part.errorText as string}`)+ return lines.join('\n')+}+function formatMessageStats(messages: UIMessage[]): string {let userMessages = 0let assistantMessages = 0@@ -162,47 +204,6 @@ function formatMessageStats(messages: UIMessage[]): string {return lines.join('\n')}-function formatTokenUsage(): string {- const steps = getStepUsages()- if (steps.length === 0) return ' (no usage data — provider may not report it)'-- let totalInput = 0- let totalOutput = 0- let totalCacheRead = 0- let totalCacheWrite = 0-- const lines: string[] = []- for (let i = 0; i < steps.length; i++) {- const s = steps[i]- totalInput += s.inputTokens- totalOutput += s.outputTokens- totalCacheRead += s.cacheReadTokens- totalCacheWrite += s.cacheWriteTokens-- let cacheInfo = ' NO CACHE'- if (s.cacheReadTokens > 0) {- cacheInfo = ` cache_read=${s.cacheReadTokens}`- } else if (s.cacheWriteTokens > 0) {- cacheInfo = ` cache_write=${s.cacheWriteTokens}`- }- lines.push(` Step ${i + 1}: in=${s.inputTokens} out=${s.outputTokens}${cacheInfo}`)- }-- const cacheHitRate = totalInput > 0 ? ((totalCacheRead / totalInput) * 100).toFixed(1) : '0.0'- const savedTokens = totalCacheRead > 0 ? totalCacheRead - Math.round(totalCacheRead * 0.1) : 0-- lines.unshift(- `Total: in=${totalInput} out=${totalOutput} cache_read=${totalCacheRead} cache_write=${totalCacheWrite}`,- `Cache hit rate: ${cacheHitRate}% (saved ~${savedTokens} uncached input tokens, 90% cost reduction on cached)`,- `Steps: ${steps.length}`,- totalCacheRead === 0 && totalCacheWrite === 0- ? '⚠ NO CACHING DETECTED — system prompt + tools are re-processed every step'- : ''- )-- return lines.filter(Boolean).join('\n')-}-export function serializeChatLog(messages: UIMessage[]): string {const sections: string[] = []diff --git a/src/ai/tools.ts b/src/app/ai/tools/index.tssimilarity index 87%rename from src/ai/tools.tsrename to src/app/ai/tools/index.tsindex ea95d62cb..8e9f54358 100644--- a/src/ai/tools.ts+++ b/src/app/ai/tools/index.ts@@ -2,19 +2,15 @@ import { valibotSchema } from '@ai-sdk/valibot'import { tool } from 'ai'import * as v from 'valibot'-import { makeFigmaFromStore } from '@/automation/figma-factory'-import { getActiveEditorStore } from '@/stores/editor'-import {- CORE_TOOLS,- collectFontKeys,- computeAllLayouts,- isFontLoaded,- loadFont,- toolsToAI-} from '@open-pencil/core'--import type { EditorStore } from '@/stores/editor'-import type { SceneNode, StepBudget, ToolLogEntry } from '@open-pencil/core'+import { makeFigmaFromStore } from '@/app/automation/bridge/figma-factory'+import { getActiveEditorStore } from '@/app/editor/active-store'+import { computeAllLayouts } from '@open-pencil/core/layout'+import { collectFontKeys, isFontLoaded, loadFont } from '@open-pencil/core/text'+import { CORE_TOOLS, toolsToAI } from '@open-pencil/core/tools'++import type { EditorStore } from '@/app/editor/active-store'+import type { SceneNode } from '@open-pencil/core/scene-graph'+import type { StepBudget, ToolLogEntry } from '@open-pencil/core/tools'export const MAX_AGENT_STEPS = 50diff --git a/src/app/automation/bridge/eval-handler.ts b/src/app/automation/bridge/eval-handler.tsnew file mode 100644index 000000000..e4df7d70c--- /dev/null+++ b/src/app/automation/bridge/eval-handler.ts@@ -0,0 +1,22 @@+import type { EditorStore } from '@/app/editor/active-store'+import type { FigmaAPI } from '@open-pencil/core/figma-api'++type FigmaFactory = () => FigmaAPI++export function createAutomationEvalHandler(makeFigma: FigmaFactory) {+ return async function handleEval(store: EditorStore, args: unknown): Promise<unknown> {+ const code = (args as { code?: string }).code+ if (!code) throw new Error('Missing "code" in args')+ const figma = makeFigma()+ const AsyncFunction = Object.getPrototypeOf(async function () {+ /* noop */+ }).constructor+ const wrappedCode = code.trim().startsWith('return')+ ? code+ : `return (async () => { ${code} })()`+ const fn = new AsyncFunction('figma', wrappedCode)+ const result = await fn(figma)+ store.requestRender()+ return { ok: true, result: result ?? null }+ }+}diff --git a/src/app/automation/bridge/export-handlers.ts b/src/app/automation/bridge/export-handlers.tsnew file mode 100644index 000000000..9a26c775c--- /dev/null+++ b/src/app/automation/bridge/export-handlers.ts@@ -0,0 +1,34 @@+import { selectionToJSX, sceneNodeToJSX, type RasterExportFormat } from '@open-pencil/core/io'++import type { EditorStore } from '@/app/editor/active-store'++export async function handleExport(store: EditorStore, args: unknown): Promise<unknown> {+ const exportArgs = args as { nodeIds?: string[]; scale?: number; format?: string } | undefined+ const nodeIds = exportArgs?.nodeIds ?? [...store.state.selectedIds]+ if (nodeIds.length === 0) throw new Error('No nodes to export')+ const data = await store.renderExportImage(+ nodeIds,+ exportArgs?.scale ?? 1,+ (exportArgs?.format ?? 'PNG') as RasterExportFormat+ )+ if (!data) throw new Error('Export failed')+ let binary = ''+ for (const byte of data) binary += String.fromCharCode(byte)+ const base64 = btoa(binary)+ return {+ ok: true,+ result: { base64, mimeType: `image/${(exportArgs?.format ?? 'png').toLowerCase()}` }+ }+}++export async function handleExportJsx(store: EditorStore, args: unknown): Promise<unknown> {+ const jsxArgs = args as { nodeIds?: string[]; style?: string } | undefined+ const style = (jsxArgs?.style ?? 'openpencil') as 'openpencil' | 'tailwind'+ const currentPage = store.graph.getNode(store.state.currentPageId)+ const nodeIds = jsxArgs?.nodeIds ?? currentPage?.childIds ?? []+ const jsx =+ nodeIds.length === 1+ ? sceneNodeToJSX(nodeIds[0], store.graph, style)+ : selectionToJSX(nodeIds, store.graph, style)+ return { ok: true, result: { jsx } }+}diff --git a/src/automation/figma-factory.ts b/src/app/automation/bridge/figma-factory.tssimilarity index 84%rename from src/automation/figma-factory.tsrename to src/app/automation/bridge/figma-factory.tsindex 862d1bd1c..28ec9dcd9 100644--- a/src/automation/figma-factory.ts+++ b/src/app/automation/bridge/figma-factory.ts@@ -1,7 +1,7 @@-import { listFonts } from '@/engine/fonts'-import { FigmaAPI } from '@open-pencil/core'+import { listFonts } from '@/app/editor/fonts'+import { FigmaAPI } from '@open-pencil/core/figma-api'-import type { EditorStore } from '@/stores/editor'+import type { EditorStore } from '@/app/editor/active-store'export function makeFigmaFromStore(store: EditorStore): FigmaAPI {const api = new FigmaAPI(store.graph)diff --git a/src/app/automation/bridge/file-handlers.ts b/src/app/automation/bridge/file-handlers.tsnew file mode 100644index 000000000..29a68fb5c--- /dev/null+++ b/src/app/automation/bridge/file-handlers.ts@@ -0,0 +1,41 @@+import { openFileFromPath } from '@/app/shell/menu/use'+import { createTab, openFileInNewTab } from '@/app/tabs'+import { IS_TAURI } from '@open-pencil/core/constants'++import type { EditorStore } from '@/app/editor/active-store'++export async function handleSaveFile(store: EditorStore): Promise<unknown> {+ await store.saveFigFile()+ return { ok: true }+}++export async function handleNewDocument(_store: EditorStore, args: unknown): Promise<unknown> {+ const path = (args as { path?: string }).path+ const tab = createTab()+ if (path) {+ tab.store.setPlannedFilePath(path)+ if (IS_TAURI) {+ const { mkdir } = await import('@tauri-apps/plugin-fs')+ const dir = path.replace(/[\\/][^\\/]+$/, '')+ await mkdir(dir, { recursive: true })+ }+ await tab.store.saveFigFile()+ tab.store.startWatchingCurrentFile()+ }+ return { ok: true }+}++export async function handleOpenFile(_store: EditorStore, args: unknown): Promise<unknown> {+ const path = (args as { path?: string }).path+ if (!path) throw new Error('Missing "path" in args')+ if (IS_TAURI) {+ await openFileFromPath(path)+ } else {+ const response = await fetch(path)+ if (!response.ok) throw new Error(`Failed to fetch file: ${response.statusText}`)+ const name = path.split(/[\\/]/).pop() ?? 'file.fig'+ const file = new File([await response.blob()], name)+ await openFileInNewTab(file, undefined, path)+ }+ return { ok: true }+}diff --git a/src/app/automation/bridge/handlers.ts b/src/app/automation/bridge/handlers.tsnew file mode 100644index 000000000..6f90f73c5--- /dev/null+++ b/src/app/automation/bridge/handlers.ts@@ -0,0 +1,46 @@+import { createAutomationEvalHandler } from '@/app/automation/bridge/eval-handler'+import { handleExport, handleExportJsx } from '@/app/automation/bridge/export-handlers'+import {+ handleNewDocument,+ handleOpenFile,+ handleSaveFile+} from '@/app/automation/bridge/file-handlers'+import { handleRpcFallback } from '@/app/automation/bridge/rpc-handler'+import { handleSelection } from '@/app/automation/bridge/selection-handler'+import { createAutomationToolHandler } from '@/app/automation/bridge/tool-handlers'++import type { EditorStore } from '@/app/editor/active-store'+import type { FigmaAPI } from '@open-pencil/core/figma-api'++type FigmaFactory = () => FigmaAPI++type CommandHandler = (store: EditorStore, args: unknown) => Promise<unknown>++export function createAutomationCommandHandlers(makeFigma: FigmaFactory) {+ const handleEval = createAutomationEvalHandler(makeFigma)+ const handleTool = createAutomationToolHandler(makeFigma)++ const commandHandlers: Partial<Record<string, CommandHandler>> = {+ eval: handleEval,+ tool: handleTool,+ export: handleExport,+ export_jsx: handleExportJsx,+ selection: handleSelection,+ save_file: handleSaveFile,+ new_document: handleNewDocument,+ open_file: handleOpenFile+ }++ async function handleRequest(+ store: EditorStore,+ command: string,+ args: unknown+ ): Promise<unknown> {+ const handler = commandHandlers[command]+ if (handler) return handler(store, args)+ return handleRpcFallback(store, command, args)+ }++ return { handleRequest }+}+diff --git a/src/app/automation/bridge/rpc-handler.ts b/src/app/automation/bridge/rpc-handler.tsnew file mode 100644index 000000000..6dde621a6--- /dev/null+++ b/src/app/automation/bridge/rpc-handler.ts@@ -0,0 +1,12 @@+import { executeRpcCommand } from '@open-pencil/core/rpc'++import type { EditorStore } from '@/app/editor/active-store'++export async function handleRpcFallback(+ store: EditorStore,+ command: string,+ args: unknown+): Promise<unknown> {+ const result = executeRpcCommand(store.graph, command, args ?? {})+ return { ok: true, result }+}diff --git a/src/app/automation/bridge/selection-handler.ts b/src/app/automation/bridge/selection-handler.tsnew file mode 100644index 000000000..8e446a5f7--- /dev/null+++ b/src/app/automation/bridge/selection-handler.ts@@ -0,0 +1,19 @@+import { nodeToXPath } from '@open-pencil/core/xpath'++import type { EditorStore } from '@/app/editor/active-store'++export async function handleSelection(store: EditorStore): Promise<unknown> {+ const ids = [...store.state.selectedIds]+ const nodes = ids+ .map((id) => store.graph.getNode(id))+ .filter((node): node is NonNullable<typeof node> => node !== undefined)+ .map((node) => ({+ id: node.id,+ name: node.name,+ type: node.type,+ width: Math.round(node.width),+ height: Math.round(node.height),+ xpath: nodeToXPath(store.graph, node.id)+ }))+ return { ok: true, result: nodes }+}diff --git a/src/app/automation/bridge/server.ts b/src/app/automation/bridge/server.tsnew file mode 100644index 000000000..8c626973c--- /dev/null+++ b/src/app/automation/bridge/server.ts@@ -0,0 +1,100 @@+import { makeFigmaFromStore } from '@/app/automation/bridge/figma-factory'+import { createAutomationCommandHandlers } from '@/app/automation/bridge/handlers'+/**+ * Browser-side automation handler.+ *+ * Connects to the bridge via WebSocket, receives RPC requests,+ * executes them against the live EditorStore, and sends results back.+ */+import { AUTOMATION_WS_PORT } from '@open-pencil/core/constants'+import { randomHex } from '@open-pencil/core/random'++import type { EditorStore } from '@/app/editor/active-store'+export function connectAutomation(getStore: () => EditorStore, authToken: string | null = null) {+ const token = authToken ?? randomHex(32)+ let ws: WebSocket | null = null+ let reconnectTimer: ReturnType<typeof setTimeout> | undefined+ let intentionalDisconnect = false++ function makeFigma() {+ return makeFigmaFromStore(getStore())+ }++ const { handleRequest: handleAutomationRequest } = createAutomationCommandHandlers(makeFigma)++ async function handleRequest(_id: string, command: string, args: unknown): Promise<unknown> {+ return handleAutomationRequest(getStore(), command, args)+ }++ function connect() {+ try {+ ws = new WebSocket(`ws://127.0.0.1:${AUTOMATION_WS_PORT}`)+ } catch (e) {+ console.error(+ '[Automation] WebSocket constructor failed:',+ e instanceof Error ? e.message : e+ )+ scheduleReconnect()+ return+ }++ ws.onopen = () => {+ console.debug('[Automation] WebSocket connected to MCP server')+ ws?.send(JSON.stringify({ type: 'register', token }))+ }++ ws.onmessage = async (event) => {+ try {+ const msg = JSON.parse(event.data) as {+ type: string+ id: string+ command: string+ args?: unknown+ }+ if (msg.type !== 'request' || !msg.id) return+ try {+ const result = await handleRequest(msg.id, msg.command, msg.args)+ ws?.send(JSON.stringify({ type: 'response', id: msg.id, ...(result as object) }))+ } catch (e) {+ ws?.send(+ JSON.stringify({+ type: 'response',+ id: msg.id,+ ok: false,+ error: e instanceof Error ? e.message : String(e)+ })+ )+ }+ } catch (e) {+ console.warn('Failed to parse WebSocket message:', e)+ }+ }++ ws.onclose = (event) => {+ ws = null+ if (intentionalDisconnect || event.code === 1000) return+ console.error('[Automation] WebSocket closed:', `code=${event.code} reason=${event.reason}`)+ scheduleReconnect()+ }++ ws.onerror = (event) => {+ console.error('[Automation] WebSocket error:', event)+ ws?.close()+ }+ }++ function scheduleReconnect() {+ clearTimeout(reconnectTimer)+ reconnectTimer = setTimeout(connect, 2000)+ }++ function disconnect() {+ intentionalDisconnect = true+ clearTimeout(reconnectTimer)+ ws?.close()+ ws = null+ }++ connect()+ return { disconnect, token }+}diff --git a/src/app/automation/bridge/tool-handlers.ts b/src/app/automation/bridge/tool-handlers.tsnew file mode 100644index 000000000..b0227806a--- /dev/null+++ b/src/app/automation/bridge/tool-handlers.ts@@ -0,0 +1,74 @@+import { renderTreeNode } from '@open-pencil/core/design-jsx'+import { computeAllLayouts } from '@open-pencil/core/layout'+import { ALL_TOOLS } from '@open-pencil/core/tools'++import type { EditorStore } from '@/app/editor/active-store'+import type { FigmaAPI } from '@open-pencil/core/figma-api'++type FigmaFactory = () => FigmaAPI++export function createAutomationToolHandler(makeFigma: FigmaFactory) {+ async function handleToolRender(+ store: EditorStore,+ toolArgs: Record<string, unknown>+ ): Promise<unknown> {+ const tree = toolArgs.tree as Parameters<typeof renderTreeNode>[1]+ const result = await renderTreeNode(store.graph, tree, {+ parentId: (toolArgs.parent_id as string | undefined) ?? store.state.currentPageId,+ x: toolArgs.x as number | undefined,+ y: toolArgs.y as number | undefined+ })+ computeAllLayouts(store.graph, store.state.currentPageId)+ store.requestRender()+ store.flashNodes([result.id])+ return {+ ok: true,+ result: { id: result.id, name: result.name, type: result.type, children: result.childIds }+ }+ }++ return async function handleTool(store: EditorStore, args: unknown): Promise<unknown> {+ const toolName = (args as { name?: string }).name+ const toolArgs = (args as { args?: Record<string, unknown> }).args ?? {}+ if (!toolName) throw new Error('Missing "name" in args')++ if (toolName === 'render' && toolArgs.tree) {+ return handleToolRender(store, toolArgs)+ }++ const def = ALL_TOOLS.find((t) => t.name === toolName)+ if (!def) throw new Error(`Unknown tool: ${toolName}`)+ const figma = makeFigma()+ const result = await def.execute(figma, toolArgs)++ if (figma.currentPageId !== store.state.currentPageId) {+ void store.switchPage(figma.currentPageId)+ }++ if (def.mutates) {+ computeAllLayouts(store.graph, store.state.currentPageId)+ store.requestRender()+ store.flashNodes(extractNodeIds(result))+ }+ return { ok: true, result }+ }+}++function extractNodeIds(result: unknown): string[] {+ if (!result || typeof result !== 'object') return []+ const obj = result as Record<string, unknown>+ if (typeof obj.deleted === 'string') return []+ const ids: string[] = []+ if (typeof obj.id === 'string') ids.push(obj.id)+ if (Array.isArray(obj.results)) {+ for (const item of obj.results) {+ if (+ item &&+ typeof item === 'object' &&+ typeof (item as Record<string, unknown>).id === 'string'+ )+ ids.push((item as Record<string, unknown>).id as string)+ }+ }+ return ids+}diff --git a/src/automation/vite-plugin.ts b/src/app/automation/bridge/vite-plugin.tssimilarity index 100%rename from src/automation/vite-plugin.tsrename to src/app/automation/bridge/vite-plugin.tsdiff --git a/src/automation/spawn-mcp.ts b/src/app/automation/mcp/spawn.tssimilarity index 92%rename from src/automation/spawn-mcp.tsrename to src/app/automation/mcp/spawn.tsindex a5ebbb581..c5c889f8a 100644--- a/src/automation/spawn-mcp.ts+++ b/src/app/automation/mcp/spawn.ts@@ -1,5 +1,8 @@-import { decodeTauriStderr } from '@/utils/tauri'-import { AUTOMATION_HTTP_PORT, IS_BROWSER, randomHex } from '@open-pencil/core'+import { promiseTimeout } from '@vueuse/core'++import { decodeTauriStderr } from '@/app/shell/ui'+import { AUTOMATION_HTTP_PORT, IS_BROWSER } from '@open-pencil/core/constants'+import { randomHex } from '@open-pencil/core/random'interface AutomationHealth {status: 'ok' | 'no_app'@@ -32,7 +35,7 @@ async function readHealth(): Promise<AutomationHealth | null> {async function pollHealth(retries: number, delayMs: number): Promise<AutomationHealth | null> {for (let i = 0; i < retries; i++) {- await new Promise((r) => setTimeout(r, delayMs))+ await promiseTimeout(delayMs)const health = await readHealth()if (health) return health}diff --git a/src/app/collab/awareness.ts b/src/app/collab/awareness.tsnew file mode 100644index 000000000..4fafefbe6--- /dev/null+++ b/src/app/collab/awareness.ts@@ -0,0 +1,103 @@+import { ref } from 'vue'++import { PEER_COLORS, ROOM_ID_CHARS, ROOM_ID_LENGTH } from '@/constants'+import { randomIndex } from '@open-pencil/core/random'++import type { EditorStore } from '@/app/editor/active-store'+import type { RemotePeer } from './types'+import type { Color } from '@open-pencil/core/types'+import type * as awarenessProtocol from 'y-protocols/awareness'++type Awareness = awarenessProtocol.Awareness++type CursorState = {+ x: number+ y: number+ pageId: string+ zoom?: number+}++export function buildRemotePeers(+ states: Map<number, Record<string, unknown>>,+ localClientId: number+): RemotePeer[] {+ const peers: RemotePeer[] = []++ states.forEach((peerState, clientId) => {+ if (clientId === localClientId) return+ const user = peerState.user as { name?: string; color?: Color } | undefined+ if (!user) return+ peers.push({+ clientId,+ name: user.name || 'Anonymous',+ color: user.color || PEER_COLORS[clientId % PEER_COLORS.length],+ cursor: peerState.cursor as RemotePeer['cursor'],+ selection: peerState.selection as string[]+ })+ })++ return peers+}++export function remotePeersToCursors(peers: RemotePeer[], currentPageId: string) {+ return peers+ .filter((p) => p.cursor && p.cursor.pageId === currentPageId)+ .map((p) => {+ const cursor = p.cursor as NonNullable<RemotePeer['cursor']>+ return {+ name: p.name,+ color: p.color,+ x: cursor.x,+ y: cursor.y,+ selection: p.selection+ }+ })+}++export function createFollowActions(+ getStore: () => EditorStore,+ getAwareness: () => Awareness | null+) {+ const followingPeer = ref<number | null>(null)++ function followPeer(clientId: number | null) {+ followingPeer.value = clientId+ }++ function resetFollow() {+ followingPeer.value = null+ }++ function tickFollow() {+ const store = getStore()+ const awareness = getAwareness()+ if (!followingPeer.value || !awareness) return+ const peerState = awareness.getStates().get(followingPeer.value)+ if (!peerState?.cursor) {+ followingPeer.value = null+ return+ }+ const cursor = peerState.cursor as CursorState+ if (cursor.pageId !== store.state.currentPageId) {+ void store.switchPage(cursor.pageId)+ }+ const canvas = document.querySelector('canvas')+ if (!canvas) return+ if (cursor.zoom) store.state.zoom = cursor.zoom+ const cw = canvas.width / devicePixelRatio+ const ch = canvas.height / devicePixelRatio+ store.state.panX = cw / 2 - cursor.x * store.state.zoom+ store.state.panY = ch / 2 - cursor.y * store.state.zoom+ store.requestRender()+ }++ return { followingPeer, followPeer, resetFollow, tickFollow }+}++export function generateRoomId(): string {+ let result = ''+ for (let i = 0; i < ROOM_ID_LENGTH; i++) {+ result += ROOM_ID_CHARS[randomIndex(ROOM_ID_CHARS.length)]+ }+ return result+}diff --git a/src/app/collab/context.ts b/src/app/collab/context.tsnew file mode 100644index 000000000..e39cf1ff1--- /dev/null+++ b/src/app/collab/context.ts@@ -0,0 +1,10 @@+import { inject, type InjectionKey } from 'vue'++import type { useCollab } from '@/app/collab/use'++export type CollabReturn = ReturnType<typeof useCollab>+export const COLLAB_KEY = Symbol('collab') as InjectionKey<CollabReturn>++export function useCollabInjected() {+ return inject(COLLAB_KEY)+}diff --git a/src/app/collab/local-awareness.ts b/src/app/collab/local-awareness.tsnew file mode 100644index 000000000..2ee047673--- /dev/null+++ b/src/app/collab/local-awareness.ts@@ -0,0 +1,64 @@+import { buildRemotePeers, remotePeersToCursors } from '@/app/collab/awareness'++import type { CollabState } from '@/app/collab/types'+import type { EditorStore } from '@/app/editor/active-store'+import type { Ref } from 'vue'+import type { Awareness } from 'y-protocols/awareness'++type LocalAwarenessOptions = {+ state: Ref<CollabState>+ storedName: Ref<string>+ getStore: () => EditorStore+ getAwareness: () => Awareness | null+}++export function createLocalAwarenessActions({+ state,+ storedName,+ getStore,+ getAwareness+}: LocalAwarenessOptions) {+ function broadcastAwareness() {+ const awareness = getAwareness()+ if (!awareness) return+ awareness.setLocalStateField('user', {+ name: state.value.localName,+ color: state.value.localColor+ })+ }++ function updateCursor(x: number, y: number, pageId: string) {+ const awareness = getAwareness()+ if (!awareness) return+ awareness.setLocalStateField('cursor', { x, y, pageId, zoom: getStore().state.zoom })+ }++ function updateSelection(ids: string[]) {+ const awareness = getAwareness()+ if (!awareness) return+ awareness.setLocalStateField('selection', ids)+ }++ function updatePeersList() {+ const awareness = getAwareness()+ if (!awareness) return++ const store = getStore()+ const peers = buildRemotePeers(+ awareness.getStates() as Map<number, Record<string, unknown>>,+ awareness.clientID+ )++ state.value.peers = peers+ store.state.remoteCursors = remotePeersToCursors(peers, store.state.currentPageId)+ store.requestRender()+ }++ function setLocalName(name: string) {+ state.value.localName = name+ storedName.value = name+ broadcastAwareness()+ }++ return { broadcastAwareness, updateCursor, updateSelection, updatePeersList, setLocalName }+}diff --git a/src/app/collab/room.ts b/src/app/collab/room.tsnew file mode 100644index 000000000..c514f6709--- /dev/null+++ b/src/app/collab/room.ts@@ -0,0 +1,116 @@+import { joinRoom as joinTrysteroRoom } from 'trystero/mqtt'+import * as awarenessProtocol from 'y-protocols/awareness'+import * as Y from 'yjs'++import { TRYSTERO_APP_ID } from '@/constants'++import type { Room } from 'trystero'++type CollabRoomOptions = {+ roomId: string+ ydoc: Y.Doc+ awareness: awarenessProtocol.Awareness+ setConnected: () => void+ updatePeersList: () => void+}++export type CollabRoomConnection = {+ room: Room+ sendYjsUpdate: (data: Uint8Array, peerId?: string) => void+ sendAwareness: (data: Uint8Array, peerId?: string) => void+ sendSyncStep1: (data: Uint8Array, peerId?: string) => void+}++export function connectCollabRoom({+ roomId,+ ydoc,+ awareness,+ setConnected,+ updatePeersList+}: CollabRoomOptions): CollabRoomConnection {+ const room = joinTrysteroRoom(+ {+ appId: TRYSTERO_APP_ID,+ rtcConfig: {+ iceServers: [+ { urls: 'stun:stun.l.google.com:19302' },+ { urls: 'stun:stun.cloudflare.com:3478' },+ {+ urls: 'turn:openrelay.metered.ca:443',+ username: 'openrelayproject',+ credential: 'openrelayproject'+ },+ {+ urls: 'turn:openrelay.metered.ca:443?transport=tcp',+ username: 'openrelayproject',+ credential: 'openrelayproject'+ }+ ]+ }+ },+ roomId+ )++ const [sendUpdate, getUpdate] = room.makeAction<Uint8Array>('yjs-update')+ const [sendAw, getAw] = room.makeAction<Uint8Array>('awareness')+ const [sendSync, getSync] = room.makeAction<Uint8Array>('sync-step1')+ const [sendSyncReply, getSyncReply] = room.makeAction<Uint8Array>('sync-reply')++ const sendYjsUpdate = (data: Uint8Array, peerId?: string) =>+ void (peerId ? sendUpdate(data, peerId) : sendUpdate(data))+ const sendAwareness = (data: Uint8Array, peerId?: string) =>+ void (peerId ? sendAw(data, peerId) : sendAw(data))+ const sendSyncStep1 = (data: Uint8Array, peerId?: string) =>+ void (peerId ? sendSync(data, peerId) : sendSync(data))++ getUpdate((data) => {+ Y.applyUpdate(ydoc, new Uint8Array(data), 'remote')+ })++ getAw((data) => {+ awarenessProtocol.applyAwarenessUpdate(awareness, new Uint8Array(data), null)+ })++ getSync((data, peerId) => {+ const sv = new Uint8Array(data)+ const update = Y.encodeStateAsUpdate(ydoc, sv)+ void sendSyncReply(update, peerId)+ })++ getSyncReply((data) => {+ Y.applyUpdate(ydoc, new Uint8Array(data), 'remote')+ })++ ydoc.on('update', (update: Uint8Array, origin: unknown) => {+ if (origin === 'remote') return+ sendYjsUpdate(update)+ })++ awareness.on(+ 'update',+ ({ added, updated, removed }: { added: number[]; updated: number[]; removed: number[] }) => {+ const changedClients = [...added, ...updated, ...removed]+ const encodedUpdate = awarenessProtocol.encodeAwarenessUpdate(awareness, changedClients)+ sendAwareness(encodedUpdate)+ }+ )++ room.onPeerJoin((peerId) => {+ setConnected()+ const sv = Y.encodeStateVector(ydoc)+ sendSyncStep1(sv, peerId)++ const encodedUpdate = awarenessProtocol.encodeAwarenessUpdate(awareness, [awareness.clientID])+ sendAwareness(encodedUpdate, peerId)+ })++ room.onPeerLeave(() => {+ const remoteClients = [...awareness.getStates().keys()].filter(+ (id) => id !== awareness.clientID+ )+ awarenessProtocol.removeAwarenessStates(awareness, remoteClients, 'peer-left')+ updatePeersList()+ })++ return { room, sendYjsUpdate, sendAwareness, sendSyncStep1 }+}diff --git a/src/app/collab/session.ts b/src/app/collab/session.tsnew file mode 100644index 000000000..1926171ff--- /dev/null+++ b/src/app/collab/session.ts@@ -0,0 +1,249 @@+import { watch } from 'vue'+import { IndexeddbPersistence } from 'y-indexeddb'+import * as awarenessProtocol from 'y-protocols/awareness'+import * as Y from 'yjs'++import { connectCollabRoom } from '@/app/collab/room'+import { bindCollabGraphEvents, registerYjsObservers } from '@/app/collab/yjs-sync'+import { PEER_COLORS } from '@/constants'+import { randomIndex } from '@open-pencil/core/random'++import type { CollabState } from '@/app/collab/types'+import type { EditorStore } from '@/app/editor/active-store'+import type { Ref } from 'vue'+import type { Room } from 'trystero'+import type { Awareness } from 'y-protocols/awareness'++export type CollabRuntime = {+ ydoc: Y.Doc | null+ awareness: awarenessProtocol.Awareness | null+ ynodes: Y.Map<Y.Map<unknown>> | null+ yimages: Y.Map<Uint8Array> | null+ room: Room | null+ persistence: IndexeddbPersistence | null+ connectedStore: EditorStore | null+ suppressGraphSync: boolean+ suppressYjsEvents: boolean+ unbindGraphEvents: (() => void) | null+ stopZoomWatch: (() => void) | null+}++type ConnectCollabSessionOptions = {+ roomId: string+ runtime: CollabRuntime+ state: Ref<CollabState>+ store: EditorStore+ disconnect: () => void+ updatePeersList: () => void+ tickFollow: () => void+ broadcastAwareness: () => void+ applyYjsToGraph: (events: Y.YEvent<Y.Map<unknown>>[]) => void+ syncNodeToYjs: (nodeId: string) => void+}++type CollabConnectionActionsOptions = {+ runtime: CollabRuntime+ state: Ref<CollabState>+ getStore: () => EditorStore+ updatePeersList: () => void+ tickFollow: () => void+ broadcastAwareness: () => void+ applyYjsToGraph: (events: Y.YEvent<Y.Map<unknown>>[]) => void+ syncNodeToYjs: (nodeId: string) => void+ resetFollow: () => void+}++type CollabSessionResources = {+ store: EditorStore+ room: Room | null+ awareness: awarenessProtocol.Awareness | null+ persistence: IndexeddbPersistence | null+ ydoc: Y.Doc | null+ unbindGraphEvents: (() => void) | null+ stopZoomWatch: (() => void) | null+ resetFollow: () => void+}++export function createCollabRuntime(): CollabRuntime {+ return {+ ydoc: null,+ awareness: null,+ ynodes: null,+ yimages: null,+ room: null,+ persistence: null,+ connectedStore: null,+ suppressGraphSync: false,+ suppressYjsEvents: false,+ unbindGraphEvents: null,+ stopZoomWatch: null+ }+}++export function createInitialCollabState(localName: string): CollabState {+ return {+ connected: false,+ roomId: null,+ peers: [],+ localName,+ localColor: PEER_COLORS[randomIndex(PEER_COLORS.length)]+ }+}++export function createCollabConnectionActions({+ runtime,+ state,+ getStore,+ updatePeersList,+ tickFollow,+ broadcastAwareness,+ applyYjsToGraph,+ syncNodeToYjs,+ resetFollow+}: CollabConnectionActionsOptions) {+ function connect(roomId: string) {+ connectCollabSession({+ roomId,+ runtime,+ state,+ store: getStore(),+ disconnect,+ updatePeersList,+ tickFollow,+ broadcastAwareness,+ applyYjsToGraph,+ syncNodeToYjs+ })+ }++ function disconnect() {+ const store = runtime.connectedStore ?? getStore()+ disposeCollabSessionResources({+ store,+ room: runtime.room,+ awareness: runtime.awareness,+ persistence: runtime.persistence,+ ydoc: runtime.ydoc,+ unbindGraphEvents: runtime.unbindGraphEvents,+ stopZoomWatch: runtime.stopZoomWatch,+ resetFollow+ })+ resetCollabRuntime(runtime)+ resetCollabConnectionState(state)+ }++ return { connect, disconnect }+}++export function watchAwarenessZoom(store: EditorStore, getAwareness: () => Awareness | null) {+ return watch(+ () => store.state.zoom,+ (zoom) => {+ const awareness = getAwareness()+ if (!awareness) return+ const prev = awareness.getLocalState()?.cursor as+ | { x: number; y: number; pageId: string; zoom: number }+ | undefined+ if (prev) {+ awareness.setLocalStateField('cursor', { ...prev, zoom })+ }+ }+ )+}++export function connectCollabSession({+ roomId,+ runtime,+ state,+ store,+ disconnect,+ updatePeersList,+ tickFollow,+ broadcastAwareness,+ applyYjsToGraph,+ syncNodeToYjs+}: ConnectCollabSessionOptions) {+ if (runtime.room) disconnect()++ runtime.connectedStore = store+ state.value.roomId = roomId+ runtime.ydoc = new Y.Doc()+ runtime.awareness = new awarenessProtocol.Awareness(runtime.ydoc)+ runtime.ynodes = runtime.ydoc.getMap('nodes')+ runtime.yimages = runtime.ydoc.getMap('images')+ runtime.persistence = new IndexeddbPersistence(`op-room-${roomId}`, runtime.ydoc)++ runtime.awareness.on('change', () => {+ updatePeersList()+ tickFollow()+ })++ registerYjsObservers({+ store,+ ynodes: runtime.ynodes,+ yimages: runtime.yimages,+ getSuppressYjsEvents: () => runtime.suppressYjsEvents,+ setSuppressGraphSync: (value) => {+ runtime.suppressGraphSync = value+ },+ applyYjsToGraph+ })++ const roomConnection = connectCollabRoom({+ roomId,+ ydoc: runtime.ydoc,+ awareness: runtime.awareness,+ setConnected: () => {+ state.value.connected = true+ },+ updatePeersList+ })+ runtime.room = roomConnection.room+ state.value.connected = true+ broadcastAwareness()++ runtime.stopZoomWatch = watchAwarenessZoom(store, () => runtime.awareness)++ runtime.unbindGraphEvents = bindCollabGraphEvents({+ store,+ getYdoc: () => runtime.ydoc,+ getYnodes: () => runtime.ynodes,+ getSuppressGraphSync: () => runtime.suppressGraphSync,+ setSuppressYjsEvents: (value) => {+ runtime.suppressYjsEvents = value+ },+ syncNodeToYjs+ })+}++export function resetCollabRuntime(runtime: CollabRuntime) {+ runtime.unbindGraphEvents = null+ runtime.stopZoomWatch = null+ runtime.room = null+ runtime.awareness = null+ runtime.persistence = null+ runtime.ydoc = null+ runtime.ynodes = null+ runtime.yimages = null+ runtime.connectedStore = null+}++export function resetCollabConnectionState(state: Ref<CollabState>) {+ state.value.connected = false+ state.value.roomId = null+ state.value.peers = []+}++export function disposeCollabSessionResources(resources: CollabSessionResources) {+ resources.unbindGraphEvents?.()+ resources.stopZoomWatch?.()+ void resources.room?.leave()+ resources.awareness?.destroy()+ if (resources.persistence) {+ void resources.persistence.destroy()+ }+ resources.ydoc?.destroy()+ resources.resetFollow()+ resources.store.state.remoteCursors = []+ resources.store.requestRender()+}diff --git a/src/app/collab/types.ts b/src/app/collab/types.tsnew file mode 100644index 000000000..5be403c47--- /dev/null+++ b/src/app/collab/types.ts@@ -0,0 +1,25 @@+import type { Color } from '@open-pencil/core/types'++export interface RemotePeer {+ clientId: number+ name: string+ color: Color+ cursor?: { x: number; y: number; pageId: string }+ selection?: string[]+}++export interface CollabState {+ connected: boolean+ roomId: string | null+ peers: RemotePeer[]+ localName: string+ localColor: Color+}++export const DEFAULT_COLLAB_STATE: CollabState = {+ connected: false,+ roomId: null,+ peers: [],+ localName: '',+ localColor: { r: 0.5, g: 0.5, b: 0.5, a: 1 }+}diff --git a/src/app/collab/use.ts b/src/app/collab/use.tsnew file mode 100644index 000000000..ce92dadc0--- /dev/null+++ b/src/app/collab/use.ts@@ -0,0 +1,83 @@+import { tryOnScopeDispose, useLocalStorage } from '@vueuse/core'+import { computed, ref } from 'vue'++import { createFollowActions, generateRoomId } from '@/app/collab/awareness'+import { createLocalAwarenessActions } from '@/app/collab/local-awareness'+import {+ createCollabConnectionActions,+ createCollabRuntime,+ createInitialCollabState+} from '@/app/collab/session'+import { DEFAULT_COLLAB_STATE, type CollabState, type RemotePeer } from '@/app/collab/types'+import { createYjsGraphSync } from '@/app/collab/yjs-sync'+import type { EditorStore } from '@/app/editor/active-store'++export { COLLAB_KEY, useCollabInjected } from '@/app/collab/context'+export { DEFAULT_COLLAB_STATE }+export type { CollabState, RemotePeer }++export function useCollab(storeOrGetter: EditorStore | (() => EditorStore)) {+ const getStore = () =>+ typeof storeOrGetter === 'function' ? (storeOrGetter as () => EditorStore)() : storeOrGetter+ const storedName = useLocalStorage('op-collab-name', '')+ const state = ref<CollabState>(createInitialCollabState(storedName.value))+ const runtime = createCollabRuntime()+ const remotePeers = computed(() => state.value.peers)+ const getActiveStore = () => runtime.connectedStore ?? getStore()++ const { followingPeer, followPeer, resetFollow, tickFollow } = createFollowActions(+ getActiveStore,+ () => runtime.awareness+ )+ const { broadcastAwareness, updateCursor, updateSelection, updatePeersList, setLocalName } =+ createLocalAwarenessActions({+ state,+ storedName,+ getStore: getActiveStore,+ getAwareness: () => runtime.awareness+ })++ const { syncNodeToYjs, syncAllNodesToYjs, applyYjsToGraph } = createYjsGraphSync({+ getStore: getActiveStore,+ getYdoc: () => runtime.ydoc,+ getYnodes: () => runtime.ynodes,+ getYimages: () => runtime.yimages,+ setSuppressYjsEvents: (value) => {+ runtime.suppressYjsEvents = value+ }+ })+ const { connect, disconnect } = createCollabConnectionActions({+ runtime,+ state,+ getStore,+ updatePeersList,+ tickFollow,+ broadcastAwareness,+ applyYjsToGraph,+ syncNodeToYjs,+ resetFollow+ })++ function shareCurrentDoc(): string {+ const roomId = generateRoomId()+ connect(roomId)+ syncAllNodesToYjs()+ return roomId+ }++ tryOnScopeDispose(disconnect)++ return {+ state,+ remotePeers,+ followingPeer,+ connect,+ disconnect,+ shareCurrentDoc,+ updateCursor,+ updateSelection,+ setLocalName,+ followPeer,+ tickFollow+ }+}diff --git a/src/app/collab/yjs-sync.ts b/src/app/collab/yjs-sync.tsnew file mode 100644index 000000000..f1c911ccf--- /dev/null+++ b/src/app/collab/yjs-sync.ts@@ -0,0 +1,251 @@+import * as Y from 'yjs'++import { YJS_JSON_FIELDS } from '@/constants'++import type { EditorStore } from '@/app/editor/active-store'+import type { SceneNode } from '@open-pencil/core/scene-graph'++type YNodes = Y.Map<Y.Map<unknown>>+type YImages = Y.Map<Uint8Array>++type GraphBindingOptions = {+ store: EditorStore+ getYdoc: () => Y.Doc | null+ getYnodes: () => YNodes | null+ getSuppressGraphSync: () => boolean+ setSuppressYjsEvents: (value: boolean) => void+ syncNodeToYjs: (nodeId: string) => void+}++type YjsObserverOptions = {+ store: EditorStore+ ynodes: Y.Map<Y.Map<unknown>>+ yimages: Y.Map<Uint8Array>+ getSuppressYjsEvents: () => boolean+ setSuppressGraphSync: (value: boolean) => void+ applyYjsToGraph: (events: Y.YEvent<Y.Map<unknown>>[]) => void+}++type YjsGraphSyncOptions = {+ getStore: () => EditorStore+ getYdoc: () => Y.Doc | null+ getYnodes: () => YNodes | null+ getYimages: () => YImages | null+ setSuppressYjsEvents: (value: boolean) => void+}++export function syncNodePropsToYMap(node: SceneNode, ynode: Y.Map<unknown>) {+ for (const [key, value] of Object.entries(node)) {+ if (typeof value === 'object' && value !== null) {+ ynode.set(key, JSON.stringify(value))+ } else {+ ynode.set(key, value)+ }+ }+}++export function yNodeToProps(ynode: Y.Map<unknown>): Record<string, unknown> {+ const props: Record<string, unknown> = {}++ for (const [key, value] of ynode.entries()) {+ if (YJS_JSON_FIELDS.has(key)) {+ try {+ props[key] = typeof value === 'string' ? JSON.parse(value) : value+ } catch {+ props[key] = value+ }+ } else {+ props[key] = value+ }+ }++ return props+}++export function bindCollabGraphEvents({+ store,+ getYdoc,+ getYnodes,+ getSuppressGraphSync,+ setSuppressYjsEvents,+ syncNodeToYjs+}: GraphBindingOptions) {+ function onGraphMutation(nodeId: string) {+ if (!getSuppressGraphSync() && getYdoc() && getYnodes()) {+ syncNodeToYjs(nodeId)+ }+ }++ return store.graph.onNodeEvents({+ updated: (id) => onGraphMutation(id),+ created: (node) => onGraphMutation(node.id),+ reparented: (nodeId) => onGraphMutation(nodeId),+ reordered: (nodeId) => onGraphMutation(nodeId),+ deleted: (id) => {+ const ydoc = getYdoc()+ const ynodes = getYnodes()+ if (!getSuppressGraphSync() && ydoc && ynodes) {+ setSuppressYjsEvents(true)+ ydoc.transact(() => {+ ynodes.delete(id)+ })+ setSuppressYjsEvents(false)+ }+ }+ })+}++export function registerYjsObservers({+ store,+ ynodes,+ yimages,+ getSuppressYjsEvents,+ setSuppressGraphSync,+ applyYjsToGraph+}: YjsObserverOptions) {+ ynodes.observeDeep((events) => {+ if (getSuppressYjsEvents()) return+ setSuppressGraphSync(true)+ try {+ applyYjsToGraph(events)+ } finally {+ setSuppressGraphSync(false)+ }+ store.requestRender()+ })++ yimages.observe((event) => {+ if (getSuppressYjsEvents()) return+ for (const [key, change] of event.changes.keys) {+ if (change.action === 'add' || change.action === 'update') {+ const data = yimages.get(key)+ if (data) store.graph.images.set(key, new Uint8Array(data))+ } else {+ store.graph.images.delete(key)+ }+ }+ store.requestRender()+ })+}++export function createYjsGraphSync({+ getStore,+ getYdoc,+ getYnodes,+ getYimages,+ setSuppressYjsEvents+}: YjsGraphSyncOptions) {+ function syncNodeToYjs(nodeId: string) {+ const store = getStore()+ const ydoc = getYdoc()+ const ynodes = getYnodes()+ if (!ydoc || !ynodes) return+ const node = store.graph.getNode(nodeId)+ if (!node) return++ const localYimages = getYimages()+ setSuppressYjsEvents(true)+ ydoc.transact(() => {+ let ynode = ynodes.get(nodeId)+ if (!ynode) {+ ynode = new Y.Map()+ ynodes.set(nodeId, ynode)+ }+ syncNodePropsToYMap(node, ynode)++ if (localYimages) {+ for (const fill of node.fills) {+ if (fill.imageHash && !localYimages.has(fill.imageHash)) {+ const data = store.graph.images.get(fill.imageHash)+ if (data) localYimages.set(fill.imageHash, data)+ }+ }+ }+ })+ setSuppressYjsEvents(false)+ }++ function syncAllNodesToYjs() {+ const store = getStore()+ const ydoc = getYdoc()+ const ynodes = getYnodes()+ if (!ydoc || !ynodes) return+ const localYimages = getYimages()+ setSuppressYjsEvents(true)+ ydoc.transact(() => {+ for (const node of store.graph.getAllNodes()) {+ let ynode = ynodes.get(node.id)+ if (!ynode) {+ ynode = new Y.Map()+ ynodes.set(node.id, ynode)+ }+ syncNodePropsToYMap(node, ynode)+ }+ })+ if (localYimages) {+ ydoc.transact(() => {+ for (const [hash, data] of store.graph.images) {+ if (!localYimages.has(hash)) {+ localYimages.set(hash, data)+ }+ }+ })+ }+ setSuppressYjsEvents(false)+ }++ function applyYjsToGraph(events: Y.YEvent<Y.Map<unknown>>[]) {+ const store = getStore()+ const ynodes = getYnodes()+ if (!ynodes) return+ for (const event of events) {+ if (event.target === ynodes) {+ for (const [key, change] of event.changes.keys) {+ if (change.action === 'add') {+ const ynode = ynodes.get(key)+ if (ynode) applyYnodeToGraph(key, ynode)+ } else if (change.action === 'delete') {+ store.graph.deleteNode(key)+ }+ }+ } else if (event.target.parent === ynodes) {+ const nodeId = findNodeIdForYMap(event.target)+ if (nodeId) {+ const ynode = ynodes.get(nodeId)+ if (ynode) applyYnodeToGraph(nodeId, ynode)+ }+ }+ }+ }++ function findNodeIdForYMap(ymap: Y.Map<unknown>): string | null {+ const ynodes = getYnodes()+ if (!ynodes) return null+ for (const [key, value] of ynodes.entries()) {+ if (value === ymap) return key+ }+ return null+ }++ function applyYnodeToGraph(nodeId: string, ynode: Y.Map<unknown>) {+ const store = getStore()+ const existing = store.graph.getNode(nodeId)+ const props = yNodeToProps(ynode)++ if (existing) {+ store.graph.updateNode(nodeId, props as Partial<SceneNode>)+ return+ }++ const parentId = props.parentId as string+ if (parentId && store.graph.getNode(parentId)) {+ const type = props.type as SceneNode['type']+ const node = store.graph.createNode(type, parentId, props as Partial<SceneNode>)+ store.graph.nodes.delete(node.id)+ node.id = nodeId+ store.graph.nodes.set(nodeId, node)+ }+ }++ return { syncNodeToYjs, syncAllNodesToYjs, applyYjsToGraph }+}diff --git a/src/app/demo/colors.ts b/src/app/demo/colors.tsnew file mode 100644index 000000000..999213029--- /dev/null+++ b/src/app/demo/colors.ts@@ -0,0 +1,34 @@+import type { Color, Fill, GradientStop, Stroke } from '@open-pencil/core/scene-graph'++export const WHITE: Color = { r: 1, g: 1, b: 1, a: 1 }+export const BLACK: Color = { r: 0, g: 0, b: 0, a: 1 }+export const GRAY_50: Color = { r: 0.98, g: 0.98, b: 0.98, a: 1 }+export const GRAY_100: Color = { r: 0.96, g: 0.96, b: 0.97, a: 1 }+export const GRAY_200: Color = { r: 0.9, g: 0.9, b: 0.92, a: 1 }+export const GRAY_500: Color = { r: 0.55, g: 0.55, b: 0.58, a: 1 }+export const BLUE: Color = { r: 0.23, g: 0.51, b: 0.96, a: 1 }+export const INDIGO: Color = { r: 0.38, g: 0.35, b: 0.95, a: 1 }+export const PURPLE: Color = { r: 0.59, g: 0.28, b: 0.96, a: 1 }+export const GREEN: Color = { r: 0.13, g: 0.77, b: 0.42, a: 1 }+export const ORANGE: Color = { r: 0.96, g: 0.52, b: 0.13, a: 1 }+export const RED: Color = { r: 0.91, g: 0.22, b: 0.22, a: 1 }+export const TEAL: Color = { r: 0.08, g: 0.73, b: 0.73, a: 1 }++export function solid(color: Color, opacity = 1): Fill {+ return { type: 'SOLID', color, opacity, visible: true }+}++export function gradient(stops: GradientStop[]): Fill {+ return {+ type: 'GRADIENT_LINEAR',+ color: stops[0].color,+ opacity: 1,+ visible: true,+ gradientStops: stops,+ gradientTransform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }+ }+}++export function thinStroke(color: Color): Stroke[] {+ return [{ color, weight: 1, opacity: 1, visible: true, align: 'INSIDE' as const }]+}diff --git a/src/app/demo/document.ts b/src/app/demo/document.tsnew file mode 100644index 000000000..0e98b4629--- /dev/null+++ b/src/app/demo/document.ts@@ -0,0 +1,33 @@+import { createAppPreviewSection } from '@/app/demo/sections/app-preview'+import { createComponentsSection } from '@/app/demo/sections/components'+import { createEffectsSection } from '@/app/demo/sections/effects'+import { createStandaloneShapes } from '@/app/demo/sections/standalone'+import { createDemoVariables } from '@/app/demo/sections/variables'+import { computeAllLayouts } from '@open-pencil/core/layout'++import type { EditorStore } from '@/app/editor/session'++export function createDemoShapes(store: EditorStore) {+ const { graph } = store++ const { btnCompId, badgeCompId } = createComponentsSection(store)+ computeAllLayouts(store.graph)+ const { sidebarId, headerId, frameId, headerTitle, chartTitle } = createAppPreviewSection(+ store,+ btnCompId,+ badgeCompId+ )++ createStandaloneShapes(store)+ createDemoVariables(store)+ createEffectsSection(store)++ graph.bindVariable(sidebarId, 'fills/0/color', 'var-bg')+ graph.bindVariable(headerId, 'fills/0/color', 'var-bg')+ graph.bindVariable(frameId, 'fills/0/color', 'var-bg-secondary')+ graph.bindVariable(headerTitle, 'fills/0/color', 'var-text-primary')+ graph.bindVariable(chartTitle, 'fills/0/color', 'var-text-primary')++ computeAllLayouts(store.graph)+ store.clearSelection()+}diff --git a/src/app/demo/effects.ts b/src/app/demo/effects.tsnew file mode 100644index 000000000..ffead691d--- /dev/null+++ b/src/app/demo/effects.ts@@ -0,0 +1,46 @@+import type { Color, Effect } from '@open-pencil/core/scene-graph'++export function dropShadow(+ ox = 0,+ oy = 4,+ radius = 8,+ spread = 0,+ color: Color = { r: 0, g: 0, b: 0, a: 0.25 }+): Effect {+ return {+ type: 'DROP_SHADOW',+ color,+ offset: { x: ox, y: oy },+ radius,+ spread,+ visible: true+ }+}++export function innerShadow(+ ox = 0,+ oy = 2,+ radius = 4,+ spread = 0,+ color: Color = { r: 0, g: 0, b: 0, a: 0.2 }+): Effect {+ return {+ type: 'INNER_SHADOW',+ color,+ offset: { x: ox, y: oy },+ radius,+ spread,+ visible: true+ }+}++export function blurEffect(type: Effect['type'], radius: number): Effect {+ return {+ type,+ color: { r: 0, g: 0, b: 0, a: 0 },+ offset: { x: 0, y: 0 },+ radius,+ spread: 0,+ visible: true+ }+}diff --git a/src/app/demo/helpers.ts b/src/app/demo/helpers.tsnew file mode 100644index 000000000..a9cf14d96--- /dev/null+++ b/src/app/demo/helpers.ts@@ -0,0 +1,7 @@+import type { EditorStore } from '@/app/editor/session'++export function makeComponent(store: EditorStore, ids: string[]): string {+ store.select(ids)+ store.createComponentFromSelection()+ return [...store.state.selectedIds][0]+}diff --git a/src/app/demo/sections/app-preview.ts b/src/app/demo/sections/app-preview.tsnew file mode 100644index 000000000..5be05a4c6--- /dev/null+++ b/src/app/demo/sections/app-preview.ts@@ -0,0 +1,190 @@+import {+ BLACK,+ BLUE,+ GRAY_200,+ GRAY_50,+ GRAY_500,+ GREEN,+ INDIGO,+ RED,+ WHITE,+ gradient,+ solid,+ thinStroke+} from '@/app/demo/colors'++import type { EditorStore } from '@/app/editor/session'++export function createAppPreviewSection(+ store: EditorStore,+ btnCompId: string,+ badgeCompId: string+) {+ const { graph } = store++ const appSectionId = store.createShape('SECTION', 1040, 60, 560, 540)+ graph.updateNode(appSectionId, { name: 'App Preview' })++ const frameId = store.createShape('FRAME', 20, 48, 520, 460, appSectionId)+ graph.updateNode(frameId, {+ name: 'Dashboard',+ fills: [solid(GRAY_50)],+ strokes: thinStroke(GRAY_200),+ clipsContent: true+ })++ const sidebarId = store.createShape('RECTANGLE', 0, 0, 56, 460, frameId)+ graph.updateNode(sidebarId, {+ name: 'Sidebar',+ fills: [solid(WHITE)],+ strokes: thinStroke(GRAY_200)+ })++ for (let i = 0; i < 5; i++) {+ const dotId = store.createShape('ELLIPSE', 18, 20 + i * 40, 20, 20, frameId)+ graph.updateNode(dotId, {+ name: `Nav ${i + 1}`,+ fills: [solid(i === 0 ? BLUE : GRAY_200)]+ })+ }++ const headerId = store.createShape('RECTANGLE', 56, 0, 464, 52, frameId)+ graph.updateNode(headerId, {+ name: 'Header',+ fills: [solid(WHITE)],+ strokes: thinStroke(GRAY_200)+ })+ const headerTitle = store.createShape('TEXT', 76, 16, 120, 20, frameId)+ graph.updateNode(headerTitle, {+ name: 'Page Title',+ text: 'Dashboard',+ fontSize: 16,+ fontWeight: 600,+ fills: [solid(BLACK)]+ })++ const headerBtn = graph.createInstance(btnCompId, frameId, { x: 400, y: 8 })+ if (headerBtn) graph.updateNode(headerBtn.id, { x: 400, y: 8 })++ const headerBadge = graph.createInstance(badgeCompId, frameId, { x: 200, y: 18 })+ if (headerBadge) graph.updateNode(headerBadge.id, { x: 200, y: 18 })++ const stats = [+ { title: 'Revenue', value: '$12,480', badge: '+14%', color: GREEN },+ { title: 'Users', value: '3,842', badge: '+8%', color: BLUE },+ { title: 'Orders', value: '1,249', badge: '-3%', color: RED }+ ]++ for (let i = 0; i < stats.length; i++) {+ const s = stats[i]+ const cx = 76 + i * 152+ const cId = store.createShape('FRAME', cx, 72, 140, 88, frameId)+ graph.updateNode(cId, {+ name: s.title,+ cornerRadius: 10,+ fills: [solid(WHITE)],+ strokes: thinStroke(GRAY_200),+ layoutMode: 'VERTICAL',+ primaryAxisSizing: 'FIXED',+ counterAxisSizing: 'FIXED',+ itemSpacing: 4,+ paddingTop: 14,+ paddingBottom: 14,+ paddingLeft: 16,+ paddingRight: 16+ })+ const labelId = store.createShape('TEXT', 0, 0, 108, 14, cId)+ graph.updateNode(labelId, {+ name: 'Label',+ text: s.title,+ fontSize: 11,+ fontWeight: 500,+ fills: [solid(GRAY_500)]+ })+ const valId = store.createShape('TEXT', 0, 0, 108, 24, cId)+ graph.updateNode(valId, {+ name: 'Value',+ text: s.value,+ fontSize: 22,+ fontWeight: 700,+ fills: [solid(BLACK)]+ })+ const bId = store.createShape('TEXT', 0, 0, 108, 14, cId)+ graph.updateNode(bId, {+ name: 'Badge',+ text: s.badge,+ fontSize: 11,+ fontWeight: 600,+ fills: [solid(s.color)]+ })+ }++ const chartBg = store.createShape('FRAME', 76, 180, 424, 200, frameId)+ graph.updateNode(chartBg, {+ name: 'Chart',+ cornerRadius: 10,+ fills: [solid(WHITE)],+ strokes: thinStroke(GRAY_200)+ })+ const chartTitle = store.createShape('TEXT', 16, 16, 120, 18, chartBg)+ graph.updateNode(chartTitle, {+ name: 'Chart Title',+ text: 'Revenue over time',+ fontSize: 13,+ fontWeight: 600,+ fills: [solid(BLACK)]+ })++ const barHeights = [60, 90, 72, 110, 95, 130, 100, 80, 120, 140, 115, 88]+ const barW = 24+ const barGap = 10+ const barStartX = 16+ const barBaseY = 180++ for (let i = 0; i < barHeights.length; i++) {+ const h = barHeights[i]+ const bx = barStartX + i * (barW + barGap)+ const by = barBaseY - h+ const barId = store.createShape('RECTANGLE', bx, by, barW, h, chartBg)+ graph.updateNode(barId, {+ name: `Bar ${i + 1}`,+ cornerRadius: 4,+ fills: [+ gradient([+ { color: BLUE, position: 0 },+ { color: INDIGO, position: 1 }+ ])+ ]+ })+ }++ const tableId = store.createShape('FRAME', 76, 400, 424, 40, frameId)+ graph.updateNode(tableId, {+ name: 'Table Header',+ fills: [solid(WHITE)],+ strokes: thinStroke(GRAY_200),+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: 'FIXED',+ counterAxisSizing: 'HUG',+ primaryAxisAlign: 'SPACE_BETWEEN',+ counterAxisAlign: 'CENTER',+ paddingTop: 10,+ paddingBottom: 10,+ paddingLeft: 16,+ paddingRight: 16,+ itemSpacing: 16+ })+ const cols = ['Name', 'Status', 'Amount', 'Date']+ for (const col of cols) {+ const colId = store.createShape('TEXT', 0, 0, 80, 16, tableId)+ graph.updateNode(colId, {+ name: col,+ text: col,+ fontSize: 12,+ fontWeight: 600,+ fills: [solid(GRAY_500)]+ })+ }++ return { sidebarId, headerId, frameId, headerTitle, chartTitle }+}diff --git a/src/app/demo/sections/components.ts b/src/app/demo/sections/components.tsnew file mode 100644index 000000000..ebbc420ee--- /dev/null+++ b/src/app/demo/sections/components.ts@@ -0,0 +1,238 @@+import {+ BLACK,+ BLUE,+ GRAY_100,+ GRAY_200,+ GRAY_500,+ GREEN,+ INDIGO,+ ORANGE,+ PURPLE,+ RED,+ TEAL,+ WHITE,+ gradient,+ solid,+ thinStroke+} from '@/app/demo/colors'+import { makeComponent } from '@/app/demo/helpers'++import type { EditorStore } from '@/app/editor/session'++export function createComponentsSection(store: EditorStore) {+ const { graph } = store++ const compSectionId = store.createShape('SECTION', 60, 60, 920, 540)+ graph.updateNode(compSectionId, { name: 'Components' })++ const btnId = store.createShape('FRAME', 32, 48, 120, 40, compSectionId)+ graph.updateNode(btnId, {+ name: 'Button/Primary',+ cornerRadius: 8,+ fills: [solid(BLUE)],+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: 'HUG',+ counterAxisSizing: 'HUG',+ primaryAxisAlign: 'CENTER',+ counterAxisAlign: 'CENTER',+ paddingTop: 10,+ paddingBottom: 10,+ paddingLeft: 20,+ paddingRight: 20+ })+ const btnTextId = store.createShape('TEXT', 0, 0, 80, 20, btnId)+ graph.updateNode(btnTextId, {+ name: 'Label',+ text: 'Get Started',+ fontSize: 14,+ fontWeight: 600,+ fills: [solid(WHITE)]+ })+ const btnCompId = makeComponent(store, [btnId])++ const btn2Id = store.createShape('FRAME', 176, 48, 100, 40, compSectionId)+ graph.updateNode(btn2Id, {+ name: 'Button/Secondary',+ cornerRadius: 8,+ fills: [solid(WHITE)],+ strokes: thinStroke(GRAY_200),+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: 'HUG',+ counterAxisSizing: 'HUG',+ primaryAxisAlign: 'CENTER',+ counterAxisAlign: 'CENTER',+ paddingTop: 10,+ paddingBottom: 10,+ paddingLeft: 20,+ paddingRight: 20+ })+ const btn2TextId = store.createShape('TEXT', 0, 0, 60, 20, btn2Id)+ graph.updateNode(btn2TextId, {+ name: 'Label',+ text: 'Cancel',+ fontSize: 14,+ fontWeight: 500,+ fills: [solid(BLACK)]+ })+ makeComponent(store, [btn2Id])++ const chipId = store.createShape('FRAME', 304, 52, 80, 28, compSectionId)+ graph.updateNode(chipId, {+ name: 'Tag',+ cornerRadius: 14,+ fills: [solid({ r: 0.93, g: 0.94, b: 1, a: 1 })],+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: 'HUG',+ counterAxisSizing: 'HUG',+ primaryAxisAlign: 'CENTER',+ counterAxisAlign: 'CENTER',+ paddingTop: 4,+ paddingBottom: 4,+ paddingLeft: 12,+ paddingRight: 12+ })+ const chipTextId = store.createShape('TEXT', 0, 0, 56, 16, chipId)+ graph.updateNode(chipTextId, {+ name: 'Label',+ text: 'Design',+ fontSize: 12,+ fontWeight: 500,+ fills: [solid(INDIGO)]+ })+ makeComponent(store, [chipId])++ const avatarId = store.createShape('ELLIPSE', 416, 48, 40, 40, compSectionId)+ graph.updateNode(avatarId, {+ name: 'Avatar',+ fills: [+ gradient([+ { color: PURPLE, position: 0 },+ { color: BLUE, position: 1 }+ ])+ ]+ })+ makeComponent(store, [avatarId])++ const cardId = store.createShape('FRAME', 32, 128, 280, 160, compSectionId)+ graph.updateNode(cardId, {+ name: 'Card',+ cornerRadius: 12,+ fills: [solid(WHITE)],+ strokes: thinStroke(GRAY_200),+ layoutMode: 'VERTICAL',+ primaryAxisSizing: 'FIXED',+ counterAxisSizing: 'FIXED',+ itemSpacing: 8,+ paddingTop: 20,+ paddingBottom: 20,+ paddingLeft: 20,+ paddingRight: 20+ })+ const cardTitleId = store.createShape('TEXT', 0, 0, 240, 22, cardId)+ graph.updateNode(cardTitleId, {+ name: 'Title',+ text: 'Analytics Overview',+ fontSize: 16,+ fontWeight: 600,+ fills: [solid(BLACK)]+ })+ const cardDescId = store.createShape('TEXT', 0, 0, 240, 36, cardId)+ graph.updateNode(cardDescId, {+ name: 'Description',+ text: 'Track your key metrics and performance indicators in real time.',+ fontSize: 13,+ fontWeight: 400,+ fills: [solid(GRAY_500)]+ })+ const cardBarBg = store.createShape('RECTANGLE', 0, 0, 240, 8, cardId)+ graph.updateNode(cardBarBg, {+ name: 'Progress BG',+ cornerRadius: 4,+ fills: [solid(GRAY_100)]+ })+ const cardBar = store.createShape('RECTANGLE', 0, 0, 168, 8, cardId)+ graph.updateNode(cardBar, {+ name: 'Progress',+ cornerRadius: 4,+ fills: [+ gradient([+ { color: BLUE, position: 0 },+ { color: TEAL, position: 1 }+ ])+ ]+ })+ makeComponent(store, [cardId])++ const inputId = store.createShape('FRAME', 344, 128, 240, 40, compSectionId)+ graph.updateNode(inputId, {+ name: 'Input',+ cornerRadius: 8,+ fills: [solid(WHITE)],+ strokes: thinStroke(GRAY_200),+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: 'FIXED',+ counterAxisSizing: 'HUG',+ primaryAxisAlign: 'MIN',+ counterAxisAlign: 'CENTER',+ paddingTop: 10,+ paddingBottom: 10,+ paddingLeft: 12,+ paddingRight: 12+ })+ const inputPlaceholder = store.createShape('TEXT', 0, 0, 200, 18, inputId)+ graph.updateNode(inputPlaceholder, {+ name: 'Placeholder',+ text: 'Search...',+ fontSize: 14,+ fontWeight: 400,+ fills: [solid(GRAY_500)]+ })+ makeComponent(store, [inputId])++ const badgeId = store.createShape('FRAME', 344, 196, 48, 24, compSectionId)+ graph.updateNode(badgeId, {+ name: 'Badge',+ cornerRadius: 12,+ fills: [solid({ r: 0.93, g: 1, b: 0.95, a: 1 })],+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: 'HUG',+ counterAxisSizing: 'HUG',+ primaryAxisAlign: 'CENTER',+ counterAxisAlign: 'CENTER',+ itemSpacing: 4,+ paddingTop: 4,+ paddingBottom: 4,+ paddingLeft: 8,+ paddingRight: 8+ })+ const badgeDot = store.createShape('ELLIPSE', 0, 0, 6, 6, badgeId)+ graph.updateNode(badgeDot, {+ name: 'Dot',+ fills: [solid(GREEN)]+ })+ const badgeText = store.createShape('TEXT', 0, 0, 28, 14, badgeId)+ graph.updateNode(badgeText, {+ name: 'Label',+ text: 'Live',+ fontSize: 11,+ fontWeight: 600,+ fills: [solid(GREEN)]+ })+ const badgeCompId = makeComponent(store, [badgeId])++ const swatches = [+ { name: 'Blue', color: BLUE, x: 32 },+ { name: 'Indigo', color: INDIGO, x: 88 },+ { name: 'Purple', color: PURPLE, x: 144 },+ { name: 'Green', color: GREEN, x: 200 },+ { name: 'Teal', color: TEAL, x: 256 },+ { name: 'Orange', color: ORANGE, x: 312 },+ { name: 'Red', color: RED, x: 368 }+ ]+ for (const swatch of swatches) {+ const id = store.createShape('ELLIPSE', swatch.x, 460, 44, 44, compSectionId)+ graph.updateNode(id, { name: swatch.name, fills: [solid(swatch.color)] })+ }++ return { btnCompId, badgeCompId }+}diff --git a/src/app/demo/sections/effects.ts b/src/app/demo/sections/effects.tsnew file mode 100644index 000000000..8e13eb0ba--- /dev/null+++ b/src/app/demo/sections/effects.ts@@ -0,0 +1,229 @@+import {+ BLACK,+ BLUE,+ GRAY_100,+ GRAY_500,+ INDIGO,+ PURPLE,+ WHITE,+ gradient,+ solid,+ thinStroke+} from '@/app/demo/colors'+import { blurEffect, dropShadow, innerShadow } from '@/app/demo/effects'++import type { EditorStore } from '@/app/editor/session'++export function createEffectsSection(store: EditorStore) {+ const { graph } = store++ const effectsSectionId = store.createShape('SECTION', 60, 840, 920, 480)+ graph.updateNode(effectsSectionId, {+ name: 'Effects',+ fills: [{ type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 }, visible: true, opacity: 1 }]+ })++ const shadowLabel = store.createShape('TEXT', 32, 48, 200, 20, effectsSectionId)+ graph.updateNode(shadowLabel, {+ name: 'Label',+ text: 'Drop Shadow',+ fontSize: 13,+ fontWeight: 600,+ fills: [solid(GRAY_500)]+ })++ const shadowCard1 = store.createShape('FRAME', 32, 76, 160, 100, effectsSectionId)+ graph.updateNode(shadowCard1, {+ name: 'Subtle Shadow',+ cornerRadius: 12,+ fills: [solid(WHITE)],+ effects: [dropShadow(0, 2, 8, 0, { r: 0, g: 0, b: 0, a: 0.08 })]+ })+ const s1Text = store.createShape('TEXT', 16, 40, 128, 20, shadowCard1)+ graph.updateNode(s1Text, {+ name: 'Label',+ text: 'Subtle',+ fontSize: 13,+ fontWeight: 500,+ fills: [solid(GRAY_500)]+ })++ const shadowCard2 = store.createShape('FRAME', 220, 76, 160, 100, effectsSectionId)+ graph.updateNode(shadowCard2, {+ name: 'Medium Shadow',+ cornerRadius: 12,+ fills: [solid(WHITE)],+ effects: [dropShadow(0, 4, 16, 0, { r: 0, g: 0, b: 0, a: 0.15 })]+ })+ const s2Text = store.createShape('TEXT', 16, 40, 128, 20, shadowCard2)+ graph.updateNode(s2Text, {+ name: 'Label',+ text: 'Medium',+ fontSize: 13,+ fontWeight: 500,+ fills: [solid(GRAY_500)]+ })++ const shadowCard3 = store.createShape('FRAME', 408, 76, 160, 100, effectsSectionId)+ graph.updateNode(shadowCard3, {+ name: 'Heavy Shadow',+ cornerRadius: 12,+ fills: [solid(WHITE)],+ effects: [dropShadow(0, 8, 24, 0, { r: 0, g: 0, b: 0, a: 0.2 })]+ })+ const s3Text = store.createShape('TEXT', 16, 40, 128, 20, shadowCard3)+ graph.updateNode(s3Text, {+ name: 'Label',+ text: 'Heavy',+ fontSize: 13,+ fontWeight: 500,+ fills: [solid(GRAY_500)]+ })++ const shadowCard4 = store.createShape('FRAME', 596, 76, 160, 100, effectsSectionId)+ graph.updateNode(shadowCard4, {+ name: 'Spread Shadow',+ cornerRadius: 12,+ fills: [solid(WHITE)],+ effects: [dropShadow(0, 4, 12, 8, { r: 0.23, g: 0.51, b: 0.96, a: 0.3 })]+ })+ const s4Text = store.createShape('TEXT', 16, 40, 128, 20, shadowCard4)+ graph.updateNode(s4Text, {+ name: 'Label',+ text: 'With Spread',+ fontSize: 13,+ fontWeight: 500,+ fills: [solid(BLUE)]+ })++ const innerLabel = store.createShape('TEXT', 32, 208, 200, 20, effectsSectionId)+ graph.updateNode(innerLabel, {+ name: 'Label',+ text: 'Inner Shadow',+ fontSize: 13,+ fontWeight: 600,+ fills: [solid(GRAY_500)]+ })++ const innerCard1 = store.createShape('FRAME', 32, 236, 160, 100, effectsSectionId)+ graph.updateNode(innerCard1, {+ name: 'Inset Light',+ cornerRadius: 12,+ fills: [solid(GRAY_100)],+ effects: [innerShadow(0, 2, 6, 0, { r: 0, g: 0, b: 0, a: 0.12 })]+ })+ const i1Text = store.createShape('TEXT', 16, 40, 128, 20, innerCard1)+ graph.updateNode(i1Text, {+ name: 'Label',+ text: 'Inset',+ fontSize: 13,+ fontWeight: 500,+ fills: [solid(GRAY_500)]+ })++ const innerCard2 = store.createShape('FRAME', 220, 236, 160, 100, effectsSectionId)+ graph.updateNode(innerCard2, {+ name: 'Inset with Spread',+ cornerRadius: 12,+ fills: [solid(GRAY_100)],+ effects: [innerShadow(0, 2, 8, 4, { r: 0, g: 0, b: 0, a: 0.15 })]+ })+ const i2Text = store.createShape('TEXT', 16, 40, 128, 20, innerCard2)+ graph.updateNode(i2Text, {+ name: 'Label',+ text: 'Inset + Spread',+ fontSize: 13,+ fontWeight: 500,+ fills: [solid(GRAY_500)]+ })++ const innerEllipse = store.createShape('ELLIPSE', 408, 236, 100, 100, effectsSectionId)+ graph.updateNode(innerEllipse, {+ name: 'Inset Circle',+ fills: [+ gradient([+ { color: { r: 0.93, g: 0.94, b: 1, a: 1 }, position: 0 },+ { color: { r: 0.85, g: 0.86, b: 0.95, a: 1 }, position: 1 }+ ])+ ],+ effects: [innerShadow(0, 4, 12, 0, { r: 0.38, g: 0.35, b: 0.95, a: 0.3 })]+ })++ const comboCard = store.createShape('FRAME', 536, 236, 160, 100, effectsSectionId)+ graph.updateNode(comboCard, {+ name: 'Combined',+ cornerRadius: 12,+ fills: [solid(WHITE)],+ effects: [+ dropShadow(0, 4, 16, 0, { r: 0, g: 0, b: 0, a: 0.12 }),+ innerShadow(0, 1, 2, 0, { r: 0, g: 0, b: 0, a: 0.06 })+ ]+ })+ const comboText = store.createShape('TEXT', 16, 40, 128, 20, comboCard)+ graph.updateNode(comboText, {+ name: 'Label',+ text: 'Drop + Inner',+ fontSize: 13,+ fontWeight: 500,+ fills: [solid(GRAY_500)]+ })++ const textFxLabel = store.createShape('TEXT', 32, 368, 200, 20, effectsSectionId)+ graph.updateNode(textFxLabel, {+ name: 'Label',+ text: 'Text Shadow & Blur',+ fontSize: 13,+ fontWeight: 600,+ fills: [solid(GRAY_500)]+ })++ const textShadow = store.createShape('TEXT', 32, 400, 200, 36, effectsSectionId)+ graph.updateNode(textShadow, {+ name: 'Text Shadow',+ text: 'Glyph Shadow',+ fontSize: 28,+ fontWeight: 700,+ fills: [solid(BLACK)],+ effects: [dropShadow(2, 2, 4, 0, { r: 0.23, g: 0.51, b: 0.96, a: 0.5 })]+ })++ const textInner = store.createShape('TEXT', 260, 400, 200, 36, effectsSectionId)+ graph.updateNode(textInner, {+ name: 'Text Inner',+ text: 'Inner Glow',+ fontSize: 28,+ fontWeight: 700,+ fills: [solid(INDIGO)],+ effects: [innerShadow(0, -1, 3, 0, { r: 1, g: 1, b: 1, a: 0.6 })]+ })++ const blurRect = store.createShape('RECTANGLE', 500, 392, 120, 50, effectsSectionId)+ graph.updateNode(blurRect, {+ name: 'Layer Blur',+ cornerRadius: 10,+ fills: [+ gradient([+ { color: PURPLE, position: 0 },+ { color: BLUE, position: 1 }+ ])+ ],+ effects: [blurEffect('LAYER_BLUR', 4)]+ })++ const glassBg = store.createShape('FRAME', 652, 368, 200, 80, effectsSectionId)+ graph.updateNode(glassBg, {+ name: 'Glass Card',+ cornerRadius: 16,+ fills: [solid({ r: 1, g: 1, b: 1, a: 0.3 })],+ strokes: thinStroke({ r: 1, g: 1, b: 1, a: 0.4 }),+ effects: [blurEffect('BACKGROUND_BLUR', 16)]+ })+ const glassText = store.createShape('TEXT', 20, 30, 160, 20, glassBg)+ graph.updateNode(glassText, {+ name: 'Label',+ text: 'Glassmorphism',+ fontSize: 14,+ fontWeight: 600,+ fills: [solid(BLACK)]+ })+}diff --git a/src/app/demo/sections/standalone.ts b/src/app/demo/sections/standalone.tsnew file mode 100644index 000000000..7865dc216--- /dev/null+++ b/src/app/demo/sections/standalone.ts@@ -0,0 +1,148 @@+import {+ BLACK,+ BLUE,+ GRAY_200,+ GREEN,+ ORANGE,+ PURPLE,+ RED,+ TEAL,+ WHITE,+ gradient,+ solid,+ thinStroke+} from '@/app/demo/colors'++import type { EditorStore } from '@/app/editor/session'++export function createStandaloneShapes(store: EditorStore) {+ const { graph } = store++ const grad1 = store.createShape('FRAME', 60, 660, 180, 120)+ graph.updateNode(grad1, {+ name: 'Gradient Card',+ cornerRadius: 16,+ fills: [+ gradient([+ { color: { r: 0.99, g: 0.37, b: 0.33, a: 1 }, position: 0 },+ { color: { r: 0.93, g: 0.18, b: 0.65, a: 1 }, position: 0.5 },+ { color: { r: 0.55, g: 0.28, b: 0.96, a: 1 }, position: 1 }+ ])+ ]+ })+ const gradText = store.createShape('TEXT', 20, 80, 140, 20, grad1)+ graph.updateNode(gradText, {+ name: 'Label',+ text: 'Linear Gradient',+ fontSize: 14,+ fontWeight: 600,+ fills: [solid(WHITE)]+ })++ const grad2 = store.createShape('FRAME', 260, 660, 180, 120)+ graph.updateNode(grad2, {+ name: 'Ocean',+ cornerRadius: 16,+ fills: [+ gradient([+ { color: { r: 0.04, g: 0.82, b: 0.67, a: 1 }, position: 0 },+ { color: { r: 0.13, g: 0.45, b: 0.96, a: 1 }, position: 1 }+ ])+ ]+ })+ const grad2Text = store.createShape('TEXT', 20, 80, 140, 20, grad2)+ graph.updateNode(grad2Text, {+ name: 'Label',+ text: 'Ocean Breeze',+ fontSize: 14,+ fontWeight: 600,+ fills: [solid(WHITE)]+ })++ const grad3 = store.createShape('FRAME', 460, 660, 180, 120)+ graph.updateNode(grad3, {+ name: 'Sunset',+ cornerRadius: 16,+ fills: [+ gradient([+ { color: { r: 1, g: 0.6, b: 0.2, a: 1 }, position: 0 },+ { color: { r: 0.96, g: 0.26, b: 0.21, a: 1 }, position: 1 }+ ])+ ]+ })+ const grad3Text = store.createShape('TEXT', 20, 80, 140, 20, grad3)+ graph.updateNode(grad3Text, {+ name: 'Label',+ text: 'Warm Sunset',+ fontSize: 14,+ fontWeight: 600,+ fills: [solid(WHITE)]+ })++ const typoFrame = store.createShape('FRAME', 700, 660, 300, 120)+ graph.updateNode(typoFrame, {+ name: 'Typography',+ cornerRadius: 12,+ fills: [solid(WHITE)],+ strokes: thinStroke(GRAY_200),+ layoutMode: 'VERTICAL',+ primaryAxisSizing: 'FIXED',+ counterAxisSizing: 'FIXED',+ itemSpacing: 6,+ paddingTop: 16,+ paddingBottom: 16,+ paddingLeft: 20,+ paddingRight: 20+ })+ const typoItems = [+ { text: 'Heading', size: 24, weight: 700 },+ { text: 'Subheading', size: 16, weight: 600 },+ { text: 'Body text — The quick brown fox jumps.', size: 13, weight: 400 },+ { text: 'CAPTION · OVERLINE', size: 10, weight: 500 }+ ]+ for (const t of typoItems) {+ const tid = store.createShape('TEXT', 0, 0, 260, t.size + 4, typoFrame)+ graph.updateNode(tid, {+ name: t.text.split(' ')[0],+ text: t.text,+ fontSize: t.size,+ fontWeight: t.weight,+ fills: [solid(BLACK)]+ })+ }++ const shapes = [+ {+ type: 'ELLIPSE' as const,+ x: 1060,+ fill: gradient([+ { color: PURPLE, position: 0 },+ { color: BLUE, position: 1 }+ ])+ },+ {+ type: 'RECTANGLE' as const,+ x: 1160,+ fill: gradient([+ { color: GREEN, position: 0 },+ { color: TEAL, position: 1 }+ ])+ },+ {+ type: 'ELLIPSE' as const,+ x: 1260,+ fill: gradient([+ { color: ORANGE, position: 0 },+ { color: RED, position: 1 }+ ])+ }+ ]+ for (const s of shapes) {+ const id = store.createShape(s.type, s.x, 680, 80, 80)+ graph.updateNode(id, {+ name: s.type === 'ELLIPSE' ? 'Circle' : 'Square',+ cornerRadius: s.type === 'RECTANGLE' ? 16 : 0,+ fills: [s.fill]+ })+ }+}diff --git a/src/app/demo/sections/variables.ts b/src/app/demo/sections/variables.tsnew file mode 100644index 000000000..c33d87861--- /dev/null+++ b/src/app/demo/sections/variables.ts@@ -0,0 +1,148 @@+import {+ BLACK,+ BLUE,+ GRAY_100,+ GRAY_200,+ GRAY_50,+ GRAY_500,+ GREEN,+ RED,+ WHITE+} from '@/app/demo/colors'++import type { EditorStore } from '@/app/editor/session'+import type { Color } from '@open-pencil/core/scene-graph'++export function createDemoVariables(store: EditorStore) {+ const { graph } = store++ graph.addCollection({+ id: 'col-primitives',+ name: 'Primitives',+ modes: [+ { modeId: 'light', name: 'Light' },+ { modeId: 'dark', name: 'Dark' }+ ],+ defaultModeId: 'light',+ variableIds: []+ })++ const primitiveColors: Array<{+ id: string+ name: string+ light: Color+ dark: Color+ }> = [+ { id: 'var-white', name: 'White', light: WHITE, dark: { r: 0.12, g: 0.12, b: 0.13, a: 1 } },+ { id: 'var-black', name: 'Black', light: BLACK, dark: WHITE },+ {+ id: 'var-gray-50',+ name: 'Gray/50',+ light: GRAY_50,+ dark: { r: 0.1, g: 0.1, b: 0.11, a: 1 }+ },+ {+ id: 'var-gray-100',+ name: 'Gray/100',+ light: GRAY_100,+ dark: { r: 0.14, g: 0.14, b: 0.16, a: 1 }+ },+ {+ id: 'var-gray-200',+ name: 'Gray/200',+ light: GRAY_200,+ dark: { r: 0.22, g: 0.22, b: 0.24, a: 1 }+ },+ {+ id: 'var-gray-500',+ name: 'Gray/500',+ light: GRAY_500,+ dark: { r: 0.65, g: 0.65, b: 0.68, a: 1 }+ },+ { id: 'var-blue', name: 'Blue', light: BLUE, dark: { r: 0.33, g: 0.61, b: 1, a: 1 } },+ {+ id: 'var-green',+ name: 'Green',+ light: GREEN,+ dark: { r: 0.23, g: 0.87, b: 0.52, a: 1 }+ },+ { id: 'var-red', name: 'Red', light: RED, dark: { r: 1, g: 0.32, b: 0.32, a: 1 } }+ ]++ for (const c of primitiveColors) {+ graph.addVariable({+ id: c.id,+ name: c.name,+ type: 'COLOR',+ collectionId: 'col-primitives',+ valuesByMode: { light: c.light, dark: c.dark },+ description: '',+ hiddenFromPublishing: false+ })+ }++ graph.addCollection({+ id: 'col-semantic',+ name: 'Semantic',+ modes: [{ modeId: 'default', name: 'Default' }],+ defaultModeId: 'default',+ variableIds: []+ })++ const semanticVars: Array<{ id: string; name: string; aliasId: string }> = [+ { id: 'var-bg', name: 'Background', aliasId: 'var-white' },+ { id: 'var-bg-secondary', name: 'Background/Secondary', aliasId: 'var-gray-50' },+ { id: 'var-text-primary', name: 'Text/Primary', aliasId: 'var-black' },+ { id: 'var-text-secondary', name: 'Text/Secondary', aliasId: 'var-gray-500' },+ { id: 'var-border', name: 'Border', aliasId: 'var-gray-200' },+ { id: 'var-accent', name: 'Accent', aliasId: 'var-blue' },+ { id: 'var-success', name: 'Success', aliasId: 'var-green' },+ { id: 'var-error', name: 'Error', aliasId: 'var-red' }+ ]++ for (const s of semanticVars) {+ graph.addVariable({+ id: s.id,+ name: s.name,+ type: 'COLOR',+ collectionId: 'col-semantic',+ valuesByMode: { default: { aliasId: s.aliasId } },+ description: '',+ hiddenFromPublishing: false+ })+ }++ graph.addCollection({+ id: 'col-spacing',+ name: 'Spacing',+ modes: [+ { modeId: 'default', name: 'Default' },+ { modeId: 'compact', name: 'Compact' }+ ],+ defaultModeId: 'default',+ variableIds: []+ })++ const spacingVars: Array<{ id: string; name: string; default: number; compact: number }> = [+ { id: 'var-space-xs', name: 'Space/XS', default: 4, compact: 2 },+ { id: 'var-space-sm', name: 'Space/SM', default: 8, compact: 4 },+ { id: 'var-space-md', name: 'Space/MD', default: 16, compact: 12 },+ { id: 'var-space-lg', name: 'Space/LG', default: 24, compact: 16 },+ { id: 'var-space-xl', name: 'Space/XL', default: 32, compact: 24 },+ { id: 'var-radius-sm', name: 'Radius/SM', default: 4, compact: 2 },+ { id: 'var-radius-md', name: 'Radius/MD', default: 8, compact: 6 },+ { id: 'var-radius-lg', name: 'Radius/LG', default: 16, compact: 12 }+ ]++ for (const s of spacingVars) {+ graph.addVariable({+ id: s.id,+ name: s.name,+ type: 'FLOAT',+ collectionId: 'col-spacing',+ valuesByMode: { default: s.default, compact: s.compact },+ description: '',+ hiddenFromPublishing: false+ })+ }+}diff --git a/src/app/document/autosave/create.ts b/src/app/document/autosave/create.tsnew file mode 100644index 000000000..bcb422d07--- /dev/null+++ b/src/app/document/autosave/create.ts@@ -0,0 +1,46 @@+import { useDebounceFn } from '@vueuse/core'+import { watch } from 'vue'++import type { EditorState } from '@open-pencil/core/editor'++type AutosaveState = EditorState & { autosaveEnabled: boolean }++type AutosaveOptions = {+ state: AutosaveState+ getSavedVersion: () => number+ hasWritableSource: () => boolean+ saveCurrentDocument: () => Promise<void>+}++export function createAutosave({+ state,+ getSavedVersion,+ hasWritableSource,+ saveCurrentDocument+}: AutosaveOptions) {+ const debouncedAutosave = useDebounceFn(async () => {+ if (state.sceneVersion === getSavedVersion()) return+ if (!state.autosaveEnabled) return+ try {+ await saveCurrentDocument()+ } catch (e) {+ console.warn('Autosave failed:', e)+ }+ }, 3000)++ watch(+ () => state.sceneVersion,+ (version) => {+ if (version === getSavedVersion()) return+ if (!state.autosaveEnabled) return+ if (!hasWritableSource()) return+ void debouncedAutosave()+ }+ )++ function disposeAutosave() {+ ;(debouncedAutosave as typeof debouncedAutosave & { cancel?: () => void }).cancel?.()+ }++ return { disposeAutosave }+}diff --git a/src/app/document/autosave/index.ts b/src/app/document/autosave/index.tsnew file mode 100644index 000000000..e56d81ba3--- /dev/null+++ b/src/app/document/autosave/index.ts@@ -0,0 +1 @@+export { createAutosave } from './create'diff --git a/src/app/document/export/create.ts b/src/app/document/export/create.tsnew file mode 100644index 000000000..4691f06f9--- /dev/null+++ b/src/app/document/export/create.ts@@ -0,0 +1,71 @@+import {+ createExportTargetActions,+ getExportBaseName,+ getExportBytes,+ getExportFileName,+ getExportOptions,+ saveExportedFile+} from '@/app/document/export/files'++import type { Editor, EditorState } from '@open-pencil/core/editor'+import type { ExportRequest, IORegistry } from '@open-pencil/core/io'++type ExportOptions = {+ scale?: number+ quality?: number+ jsxFormat?: 'openpencil' | 'tailwind'+}++type DownloadBlob = (data: Uint8Array, filename: string, mime: string) => void++export function createDocumentExportActions(+ editor: Editor,+ state: EditorState,+ io: IORegistry,+ downloadBlob: DownloadBlob+) {+ const { renderExportImage, getSelectionExportTarget, listSelectionExportFormats } =+ createExportTargetActions(editor, state, io)++ async function exportTarget(+ target: ExportRequest['target'],+ formatId: string,+ options?: ExportOptions+ ) {+ const format = io.getFormat(formatId)+ if (!format) throw new Error(`Unknown export format: ${formatId}`)++ const exportOptions = getExportOptions(formatId, options)++ const result = await io.exportContent(+ formatId,+ { graph: editor.graph, target },+ exportOptions,+ editor.renderer ? { canvasKit: editor.renderer.ck, renderer: editor.renderer } : undefined+ )++ const baseName = getExportBaseName(editor.graph, target)+ const fileName = getExportFileName(baseName, formatId, result.extension, options)+ const bytes = getExportBytes(result.data)++ await saveExportedFile(+ bytes,+ fileName,+ format.label,+ `.${result.extension}`,+ result.mimeType,+ downloadBlob+ )+ }++ async function exportSelection(scale: number, formatId: 'png' | 'jpg' | 'webp' | 'svg' | 'fig') {+ await exportTarget(getSelectionExportTarget(), formatId, { scale })+ }++ return {+ renderExportImage,+ listSelectionExportFormats,+ exportTarget,+ exportSelection+ }+}diff --git a/src/app/document/export/files.ts b/src/app/document/export/files.tsnew file mode 100644index 000000000..07dd39015--- /dev/null+++ b/src/app/document/export/files.ts@@ -0,0 +1,125 @@+import { IS_TAURI } from '@/constants'+import { renderNodesToImage } from '@open-pencil/core/io/formats/raster'++import type { Editor, EditorState } from '@open-pencil/core/editor'+import type { ExportRequest, IOFormatAdapter, IORegistry, RasterExportFormat } from '@open-pencil/core/io'+import type { SceneGraph } from '@open-pencil/core/scene-graph'++type ExportOptions = {+ scale?: number+ quality?: number+ jsxFormat?: 'openpencil' | 'tailwind'+}++type ExportData = string | ArrayBuffer | Uint8Array++type DownloadBlob = (data: Uint8Array, filename: string, mime: string) => void++export function getExportBaseName(graph: SceneGraph, target: ExportRequest['target']): string {+ if (target.scope === 'node') return graph.getNode(target.nodeId)?.name ?? 'Export'+ if (target.scope === 'selection' && target.nodeIds.length === 1) {+ return graph.getNode(target.nodeIds[0])?.name ?? 'Export'+ }+ if (target.scope === 'page') return graph.getNode(target.pageId)?.name ?? 'Page'+ return 'Export'+}++export function getExportOptions(formatId: string, options?: ExportOptions): unknown {+ if (formatId === 'png' || formatId === 'jpg' || formatId === 'webp') {+ return {+ format: formatId.toUpperCase(),+ scale: options?.scale ?? 1,+ quality: options?.quality+ }+ }+ if (formatId === 'jsx') return { format: options?.jsxFormat ?? 'openpencil' }+ return undefined+}++export function getExportFileName(+ baseName: string,+ formatId: string,+ extension: string,+ options?: ExportOptions+): string {+ return formatId === 'png' || formatId === 'jpg' || formatId === 'webp'+ ? `${baseName}@${options?.scale ?? 1}x.${extension}`+ : `${baseName}.${extension}`+}++export function getExportBytes(data: ExportData): Uint8Array {+ return typeof data === 'string' ? new TextEncoder().encode(data) : new Uint8Array(data)+}++export function createExportTargetActions(editor: Editor, state: EditorState, io: IORegistry) {+ async function renderExportImage(+ nodeIds: string[],+ scale: number,+ format: RasterExportFormat+ ): Promise<Uint8Array | null> {+ const renderer = editor.renderer+ if (!renderer) return null+ const ids =+ nodeIds.length > 0 ? nodeIds : editor.graph.getChildren(state.currentPageId).map((n) => n.id)+ if (ids.length === 0) return null+ return renderNodesToImage(renderer.ck, renderer, editor.graph, state.currentPageId, ids, {+ scale,+ format+ })+ }++ function getSelectionExportTarget(): ExportRequest['target'] {+ const ids = [...state.selectedIds]+ if (ids.length > 0) return { scope: 'selection', nodeIds: ids }+ return { scope: 'page', pageId: state.currentPageId }+ }++ function listSelectionExportFormats(): IOFormatAdapter[] {+ return io.listExportFormats(state.selectedIds.size > 0 ? 'selection' : 'page')+ }++ return { renderExportImage, getSelectionExportTarget, listSelectionExportFormats }+}++export async function saveExportedFile(+ data: Uint8Array,+ fileName: string,+ format: string,+ ext: string,+ mime: string,+ downloadBlob: DownloadBlob+) {+ if (IS_TAURI) {+ const { save } = await import('@tauri-apps/plugin-dialog')+ const path = await save({+ defaultPath: fileName,+ filters: [{ name: format, extensions: [ext.slice(1)] }]+ })+ if (!path) return+ const { writeFile: tauriWrite } = await import('@tauri-apps/plugin-fs')+ await tauriWrite(path, data)+ return+ }++ if (window.showSaveFilePicker) {+ try {+ const handle = await window.showSaveFilePicker({+ suggestedName: fileName,+ types: [+ {+ description: `${format} file`,+ accept: { [mime]: [ext] }+ }+ ]+ })+ const writable = await handle.createWritable()+ await writable.write(new Uint8Array(data))+ await writable.close()+ return+ } catch (e) {+ if ((e as Error).name === 'AbortError') return+ }+ }++ downloadBlob(data, fileName, mime)+}diff --git a/src/app/document/export/index.ts b/src/app/document/export/index.tsnew file mode 100644index 000000000..0cb7bdcd9--- /dev/null+++ b/src/app/document/export/index.ts@@ -0,0 +1 @@+export { createDocumentExportActions } from './create'diff --git a/src/app/document/io/browser.ts b/src/app/document/io/browser.tsnew file mode 100644index 000000000..d89f0504d--- /dev/null+++ b/src/app/document/io/browser.ts@@ -0,0 +1,38 @@+export function yieldToUI(): Promise<void> {+ return new Promise((resolve) => requestAnimationFrame(() => resolve()))+}++type ViewportSize = { width: number; height: number }++type ViewportEditor = {+ zoomToFit: () => void+}++export function createDocumentViewportActions(editor: ViewportEditor, viewportSize: ViewportSize) {+ function setViewportSize(width: number, height: number) {+ viewportSize.width = width+ viewportSize.height = height+ }++ async function fitCurrentPageToViewport() {+ await yieldToUI()+ editor.zoomToFit()+ }++ return { setViewportSize, fitCurrentPageToViewport }+}++export function downloadBlob(data: Uint8Array, filename: string, mime: string) {+ const blob = new Blob([data.buffer as ArrayBuffer], { type: mime })+ const url = URL.createObjectURL(blob)+ const a = document.createElement('a')+ a.href = url+ a.download = filename+ a.style.display = 'none'+ document.body.appendChild(a)+ a.click()+ setTimeout(() => {+ document.body.removeChild(a)+ URL.revokeObjectURL(url)+ }, 100)+}diff --git a/src/app/document/io/create.ts b/src/app/document/io/create.tsnew file mode 100644index 000000000..81f5bee53--- /dev/null+++ b/src/app/document/io/create.ts@@ -0,0 +1,75 @@+import { createDocumentViewportActions, downloadBlob } from '@/app/document/io/browser'+import { createOpenActions, createReloadActions } from '@/app/document/io/read'+import { createDocumentSourceActions, createDocumentSourceState } from '@/app/document/io/source'+import { createFileWatcher } from '@/app/document/io/watch'+import { prefetchFigmaSchema } from '@open-pencil/core/kiwi'++import type { Editor, EditorState } from '@open-pencil/core/editor'++type DocumentIOState = EditorState & {+ documentName: string+ loading: boolean+ autosaveEnabled: boolean+}++type ViewportSize = {+ width: number+ height: number+}++export function createDocumentIOActions(+ editor: Editor,+ state: DocumentIOState,+ viewportSize: ViewportSize+) {+ const sourceState = createDocumentSourceState()++ void prefetchFigmaSchema()++ const { reloadFromDisk } = createReloadActions({+ editor,+ state,+ getFilePath: sourceState.getFilePath,+ getFileHandle: sourceState.getFileHandle,+ setSavedVersion: sourceState.setSavedVersion+ })+ const { startWatchingFile, stopWatchingFile } = createFileWatcher({+ getFilePath: sourceState.getFilePath,+ getFileHandle: sourceState.getFileHandle,+ getLastWriteTime: sourceState.getLastWriteTime,+ reloadFromDisk: () => {+ void reloadFromDisk()+ }+ })+ const { setViewportSize, fitCurrentPageToViewport } = createDocumentViewportActions(+ editor,+ viewportSize+ )+ const sourceActions = createDocumentSourceActions({+ editor,+ state,+ stopWatchingFile,+ startWatchingFile,+ getRenderer: () => editor.renderer,+ ...sourceState+ })+ const { openFigFile } = createOpenActions({+ editor,+ state,+ setDocumentSource: sourceActions.setDocumentSource,+ fitCurrentPageToViewport+ })++ return {+ downloadBlob,+ setViewportSize,+ fitCurrentPageToViewport,+ setDocumentSource: sourceActions.setDocumentSource,+ setPlannedFilePath: sourceActions.setPlannedFilePath,+ startWatchingCurrentFile: sourceActions.startWatchingCurrentFile,+ disposeDocumentIO: sourceActions.disposeDocumentIO,+ openFigFile,+ saveFigFile: sourceActions.saveFigFile,+ saveFigFileAs: sourceActions.saveFigFileAs+ }+}diff --git a/src/app/document/io/imported-document.ts b/src/app/document/io/imported-document.tsnew file mode 100644index 000000000..42ef5cec7--- /dev/null+++ b/src/app/document/io/imported-document.ts@@ -0,0 +1,11 @@+import type { Editor } from '@open-pencil/core/editor'+import type { SceneGraph, SceneNode } from '@open-pencil/core/scene-graph'++export async function applyImportedDocument(editor: Editor, imported: SceneGraph) {+ editor.replaceGraph(imported)+ editor.undo.clear()+ editor.state.selectedIds = new Set()+ const firstPage = editor.graph.getPages()[0] as SceneNode | undefined+ const pageId = firstPage?.id ?? editor.graph.rootId+ await editor.switchPage(pageId)+}diff --git a/src/app/document/io/index.ts b/src/app/document/io/index.tsnew file mode 100644index 000000000..9355bde86--- /dev/null+++ b/src/app/document/io/index.ts@@ -0,0 +1 @@+export { createDocumentIOActions } from './create'diff --git a/src/app/document/io/names.ts b/src/app/document/io/names.tsnew file mode 100644index 000000000..364c4c11d--- /dev/null+++ b/src/app/document/io/names.ts@@ -0,0 +1,14 @@+export function documentNameFromFigPath(path: string): string {+ return path+ .split(/[\\/]/)+ .pop()+ ?.replace(/\.fig$/i, '') ?? 'Untitled'+}++export function downloadNameFromPath(path: string): string {+ return path.split(/[\\/]/).pop() ?? 'Untitled.fig'+}++export function figDownloadName(fileName: string, sourceFormat: string): string {+ return sourceFormat === 'fig' ? fileName : fileName.replace(/\.[^.]+$/i, '.fig')+}diff --git a/src/app/document/io/read.ts b/src/app/document/io/read.tsnew file mode 100644index 000000000..c5e0d5045--- /dev/null+++ b/src/app/document/io/read.ts@@ -0,0 +1,88 @@+import { yieldToUI } from '@/app/document/io/browser'+import { applyImportedDocument } from '@/app/document/io/imported-document'+import { readReloadSource } from '@/app/document/io/reload-source'+import { captureReloadState, restoreReloadState } from '@/app/document/io/reload-state'+import { toast } from '@/app/shell/ui'+import { readFigFile } from '@open-pencil/core/io/formats/fig'++import type { Editor, EditorState } from '@open-pencil/core/editor'++type OpenDocumentState = EditorState & {+ documentName: string+ loading: boolean+}++type ReloadDocumentState = EditorState & { documentName: string }++type OpenFigFileOptions = {+ editor: Editor+ state: OpenDocumentState+ setDocumentSource: (+ fileName: string,+ sourceFormat: string,+ handle?: FileSystemFileHandle,+ path?: string+ ) => void+ fitCurrentPageToViewport: () => Promise<void>+}++type ReloadActionsOptions = {+ editor: Editor+ state: ReloadDocumentState+ getFilePath: () => string | null+ getFileHandle: () => FileSystemFileHandle | null+ setSavedVersion: (version: number) => void+}++export function createOpenActions({+ editor,+ state,+ setDocumentSource,+ fitCurrentPageToViewport+}: OpenFigFileOptions) {+ async function openFigFile(file: File, handle?: FileSystemFileHandle, path?: string) {+ try {+ state.loading = true+ await yieldToUI()+ const imported = await readFigFile(file, { populate: 'first-page' })+ await yieldToUI()+ await applyImportedDocument(editor, imported)+ state.documentName = file.name.replace(/\.fig$/i, '')+ setDocumentSource(file.name, 'fig', handle, path)+ await fitCurrentPageToViewport()+ editor.requestRender()+ } catch (e) {+ console.error('Failed to open .fig file:', e)+ toast.error(`Failed to open file: ${e instanceof Error ? e.message : String(e)}`)+ } finally {+ state.loading = false+ }+ }++ return { openFigFile }+}++export function createReloadActions({+ editor,+ state,+ getFilePath,+ getFileHandle,+ setSavedVersion+}: ReloadActionsOptions) {+ async function reloadFromDisk() {+ const snapshot = captureReloadState(state)+ const filePath = getFilePath()+ const fileHandle = getFileHandle()++ const imported = await readReloadSource({ documentName: state.documentName, filePath, fileHandle })+ if (!imported) return+ editor.replaceGraph(imported)++ editor.undo.clear()+ setSavedVersion(state.sceneVersion)+ restoreReloadState(editor, state, snapshot)+ editor.requestRender()+ }++ return { reloadFromDisk }+}diff --git a/src/app/document/io/reload-source.ts b/src/app/document/io/reload-source.tsnew file mode 100644index 000000000..45ed34ca0--- /dev/null+++ b/src/app/document/io/reload-source.ts@@ -0,0 +1,29 @@+import { IS_TAURI } from '@/constants'+import { readFigFile } from '@open-pencil/core/io/formats/fig'++export type ReloadSourceOptions = {+ documentName: string+ filePath: string | null+ fileHandle: FileSystemFileHandle | null+}++export async function readReloadSource({+ documentName,+ filePath,+ fileHandle+}: ReloadSourceOptions) {+ if (filePath && IS_TAURI) {+ const { readFile: tauriRead } = await import('@tauri-apps/plugin-fs')+ const bytes = await tauriRead(filePath)+ const blob = new Blob([bytes])+ const file = new File([blob], `${documentName}.fig`)+ return readFigFile(file, { populate: 'first-page' })+ }++ if (fileHandle) {+ const file = await fileHandle.getFile()+ return readFigFile(file, { populate: 'first-page' })+ }++ return null+}diff --git a/src/app/document/io/reload-state.ts b/src/app/document/io/reload-state.tsnew file mode 100644index 000000000..b8101cdfe--- /dev/null+++ b/src/app/document/io/reload-state.ts@@ -0,0 +1,31 @@+import type { Editor, EditorState } from '@open-pencil/core/editor'++type ReloadViewport = {+ panX: number+ panY: number+ zoom: number+}++export type ReloadStateSnapshot = {+ viewport: ReloadViewport+ pageId: string+}++export function captureReloadState(state: EditorState): ReloadStateSnapshot {+ return {+ viewport: { panX: state.panX, panY: state.panY, zoom: state.zoom },+ pageId: state.currentPageId+ }+}++export function restoreReloadState(editor: Editor, state: EditorState, snapshot: ReloadStateSnapshot) {+ state.selectedIds = new Set()+ if (editor.graph.getNode(snapshot.pageId)) {+ state.currentPageId = snapshot.pageId+ } else {+ state.currentPageId = editor.graph.getPages()[0]?.id ?? editor.graph.rootId+ }+ state.panX = snapshot.viewport.panX+ state.panY = snapshot.viewport.panY+ state.zoom = snapshot.viewport.zoom+}diff --git a/src/app/document/io/save-targets.ts b/src/app/document/io/save-targets.tsnew file mode 100644index 000000000..643109d94--- /dev/null+++ b/src/app/document/io/save-targets.ts@@ -0,0 +1,25 @@+export async function chooseTauriFigSavePath() {+ const { save } = await import('@tauri-apps/plugin-dialog')+ return save({+ defaultPath: 'Untitled.fig',+ filters: [{ name: 'Figma file', extensions: ['fig'] }]+ })+}++export async function chooseBrowserFigSaveHandle() {+ if (!window.showSaveFilePicker) return null+ try {+ return await window.showSaveFilePicker({+ suggestedName: 'Untitled.fig',+ types: [+ {+ description: 'Figma file',+ accept: { 'application/octet-stream': ['.fig'] }+ }+ ]+ })+ } catch (error) {+ if ((error as Error).name === 'AbortError') return null+ throw error+ }+}diff --git a/src/app/document/io/save.ts b/src/app/document/io/save.tsnew file mode 100644index 000000000..679f97091--- /dev/null+++ b/src/app/document/io/save.ts@@ -0,0 +1,92 @@+import { downloadBlob } from '@/app/document/io/browser'+import { documentNameFromFigPath } from '@/app/document/io/names'+import { chooseBrowserFigSaveHandle, chooseTauriFigSavePath } from '@/app/document/io/save-targets'+import { createDocumentWriter } from '@/app/document/io/write'+import { IS_TAURI } from '@/constants'++import type { EditorState } from '@open-pencil/core/editor'++type SaveDocumentState = EditorState & { documentName: string }++type SaveActionsOptions = {+ state: SaveDocumentState+ buildFigFile: () => Uint8Array | Promise<Uint8Array>+ getFilePath: () => string | null+ setFilePath: (path: string | null) => void+ getFileHandle: () => FileSystemFileHandle | null+ setFileHandle: (handle: FileSystemFileHandle | null) => void+ getDownloadName: () => string | null+ setDownloadName: (name: string | null) => void+ setSavedVersion: (version: number) => void+ setLastWriteTime: (time: number) => void+ startWatchingFile: () => void+}++export function createSaveActions({+ state,+ buildFigFile,+ getFilePath,+ setFilePath,+ getFileHandle,+ setFileHandle,+ getDownloadName,+ setDownloadName,+ setSavedVersion,+ setLastWriteTime,+ startWatchingFile+}: SaveActionsOptions) {+ const writeFile = createDocumentWriter({+ state,+ getFilePath,+ getFileHandle,+ setSavedVersion,+ setLastWriteTime+ })++ async function saveFigFile() {+ const filePath = getFilePath()+ const fileHandle = getFileHandle()+ const downloadName = getDownloadName()+ if (filePath || fileHandle) {+ await writeFile(await buildFigFile())+ } else if (downloadName) {+ downloadBlob(new Uint8Array(await buildFigFile()), downloadName, 'application/octet-stream')+ } else {+ await saveFigFileAs()+ }+ }++ async function saveFigFileAs() {+ const data = await buildFigFile()++ if (IS_TAURI) {+ const path = await chooseTauriFigSavePath()+ if (!path) return+ setFilePath(path)+ setFileHandle(null)+ state.documentName = documentNameFromFigPath(path)+ await writeFile(data)+ startWatchingFile()+ return+ }++ if (window.showSaveFilePicker) {+ const handle = await chooseBrowserFigSaveHandle()+ if (!handle) return+ setFileHandle(handle)+ setFilePath(null)+ state.documentName = documentNameFromFigPath(handle.name)+ await writeFile(data)+ startWatchingFile()+ return+ }++ const filename = prompt('Save as:', getDownloadName() ?? 'Untitled.fig')+ if (!filename) return+ setDownloadName(filename)+ state.documentName = documentNameFromFigPath(filename)+ downloadBlob(new Uint8Array(data), filename, 'application/octet-stream')+ }++ return { saveFigFile, saveFigFileAs, writeFile }+}diff --git a/src/app/document/io/source-state.ts b/src/app/document/io/source-state.tsnew file mode 100644index 000000000..8efe78f57--- /dev/null+++ b/src/app/document/io/source-state.ts@@ -0,0 +1,30 @@+export function createDocumentSourceState() {+ let fileHandle: FileSystemFileHandle | null = null+ let filePath: string | null = null+ let downloadName: string | null = null+ let savedVersion = 0+ let lastWriteTime = 0++ return {+ getFileHandle: () => fileHandle,+ setFileHandle: (handle: FileSystemFileHandle | null) => {+ fileHandle = handle+ },+ getFilePath: () => filePath,+ setFilePath: (path: string | null) => {+ filePath = path+ },+ getDownloadName: () => downloadName,+ setDownloadName: (name: string | null) => {+ downloadName = name+ },+ getSavedVersion: () => savedVersion,+ setSavedVersion: (version: number) => {+ savedVersion = version+ },+ getLastWriteTime: () => lastWriteTime,+ setLastWriteTime: (time: number) => {+ lastWriteTime = time+ }+ }+}diff --git a/src/app/document/io/source.ts b/src/app/document/io/source.tsnew file mode 100644index 000000000..5703babc7--- /dev/null+++ b/src/app/document/io/source.ts@@ -0,0 +1,119 @@+import { createAutosave } from '@/app/document/autosave'+import { createSaveActions } from '@/app/document/io/save'+import { documentNameFromFigPath, downloadNameFromPath, figDownloadName } from '@/app/document/io/names'+import { createDocumentSourceState } from '@/app/document/io/source-state'+import { exportFigFile } from '@open-pencil/core/io/formats/fig'++import type { Editor, EditorState } from '@open-pencil/core/editor'++type DocumentSourceState = EditorState & {+ documentName: string+ autosaveEnabled: boolean+}++export { createDocumentSourceState }++type DocumentSourceOptions = {+ editor: Editor+ state: DocumentSourceState+ stopWatchingFile: () => void+ startWatchingFile: () => Promise<void>+ getFileHandle: () => FileSystemFileHandle | null+ setFileHandle: (handle: FileSystemFileHandle | null) => void+ getFilePath: () => string | null+ setFilePath: (path: string | null) => void+ getDownloadName: () => string | null+ setDownloadName: (name: string | null) => void+ getSavedVersion: () => number+ setSavedVersion: (version: number) => void+ setLastWriteTime: (time: number) => void+ getRenderer: () => Editor['renderer']+}++export function createDocumentSourceActions({+ editor,+ state,+ stopWatchingFile,+ startWatchingFile,+ getFileHandle,+ setFileHandle,+ getFilePath,+ setFilePath,+ getDownloadName,+ setDownloadName,+ getSavedVersion,+ setSavedVersion,+ setLastWriteTime,+ getRenderer+}: DocumentSourceOptions) {+ function buildFigFile() {+ return exportFigFile(editor.graph, undefined, getRenderer() ?? undefined, state.currentPageId)+ }++ const { saveFigFile, saveFigFileAs, writeFile } = createSaveActions({+ state,+ buildFigFile,+ getFilePath,+ setFilePath,+ getFileHandle,+ setFileHandle,+ getDownloadName,+ setDownloadName,+ setSavedVersion,+ setLastWriteTime,+ startWatchingFile: () => {+ void startWatchingFile()+ }+ })++ const { disposeAutosave } = createAutosave({+ state,+ getSavedVersion,+ hasWritableSource: () => !!getFileHandle() || !!getFilePath(),+ saveCurrentDocument: async () => writeFile(await buildFigFile())+ })++ function setDocumentSource(+ fileName: string,+ sourceFormat: string,+ handle?: FileSystemFileHandle,+ path?: string+ ) {+ stopWatchingFile()+ const isFig = sourceFormat === 'fig'+ setFileHandle(isFig ? (handle ?? null) : null)+ setFilePath(isFig ? (path ?? null) : null)+ setDownloadName(figDownloadName(fileName, sourceFormat))+ setSavedVersion(state.sceneVersion)+ if (isFig && (handle || path)) {+ void startWatchingFile()+ }+ }++ function setPlannedFilePath(path: string) {+ stopWatchingFile()+ setFileHandle(null)+ setFilePath(path)+ const downloadName = downloadNameFromPath(path)+ setDownloadName(downloadName)+ state.documentName = documentNameFromFigPath(downloadName)+ }++ function startWatchingCurrentFile() {+ void startWatchingFile()+ }++ function disposeDocumentIO() {+ stopWatchingFile()+ disposeAutosave()+ }++ return {+ setDocumentSource,+ setPlannedFilePath,+ startWatchingCurrentFile,+ disposeDocumentIO,+ saveFigFile,+ saveFigFileAs+ }+}diff --git a/src/app/document/io/watch-targets.ts b/src/app/document/io/watch-targets.tsnew file mode 100644index 000000000..0d4cd25c8--- /dev/null+++ b/src/app/document/io/watch-targets.ts@@ -0,0 +1,60 @@+import { useIntervalFn } from '@vueuse/core'++const RECENT_WRITE_MS = 1000+const BROWSER_POLL_MS = 2000+const TAURI_WATCH_DELAY_MS = 500++export async function watchTauriFile(+ filePath: string,+ getLastWriteTime: () => number,+ reloadFromDisk: () => void+) {+ const { watch: tauriWatch } = await import('@tauri-apps/plugin-fs')+ const unwatch = await tauriWatch(+ filePath,+ (event) => {+ if (typeof event.type !== 'object' || !('modify' in event.type)) return+ if (Date.now() - getLastWriteTime() < RECENT_WRITE_MS) return+ reloadFromDisk()+ },+ { delayMs: TAURI_WATCH_DELAY_MS }+ )+ return () => unwatch()+}++export async function watchBrowserFile(+ fileHandle: FileSystemFileHandle,+ getActiveFileHandle: () => FileSystemFileHandle | null,+ getLastWriteTime: () => number,+ reloadFromDisk: () => void,+ stopWatchingFile: () => void+) {+ let lastModified = (await fileHandle.getFile()).lastModified+ const { pause, resume } = useIntervalFn(+ () => {+ void checkBrowserFileModified(fileHandle)+ },+ BROWSER_POLL_MS,+ { immediate: false }+ )+ resume()++ async function checkBrowserFileModified(handle: FileSystemFileHandle) {+ if (getActiveFileHandle() !== handle) {+ stopWatchingFile()+ return+ }+ try {+ const file = await handle.getFile()+ if (file.lastModified > lastModified) {+ lastModified = file.lastModified+ if (Date.now() - getLastWriteTime() < RECENT_WRITE_MS) return+ reloadFromDisk()+ }+ } catch {+ stopWatchingFile()+ }+ }++ return pause+}diff --git a/src/app/document/io/watch.ts b/src/app/document/io/watch.tsnew file mode 100644index 000000000..e0cad25ea--- /dev/null+++ b/src/app/document/io/watch.ts@@ -0,0 +1,45 @@+import { watchBrowserFile, watchTauriFile } from '@/app/document/io/watch-targets'+import { IS_TAURI } from '@/constants'++type FileWatchOptions = {+ getFilePath: () => string | null+ getFileHandle: () => FileSystemFileHandle | null+ getLastWriteTime: () => number+ reloadFromDisk: () => void+}++export function createFileWatcher({+ getFilePath,+ getFileHandle,+ getLastWriteTime,+ reloadFromDisk+}: FileWatchOptions) {+ let unwatchFile: (() => void) | null = null++ function stopWatchingFile() {+ if (unwatchFile) {+ unwatchFile()+ unwatchFile = null+ }+ }++ async function startWatchingFile() {+ stopWatchingFile()+ const filePath = getFilePath()+ const fileHandle = getFileHandle()++ if (filePath && IS_TAURI) {+ unwatchFile = await watchTauriFile(filePath, getLastWriteTime, reloadFromDisk)+ } else if (fileHandle) {+ unwatchFile = await watchBrowserFile(+ fileHandle,+ getFileHandle,+ getLastWriteTime,+ reloadFromDisk,+ stopWatchingFile+ )+ }+ }++ return { startWatchingFile, stopWatchingFile }+}diff --git a/src/app/document/io/write.ts b/src/app/document/io/write.tsnew file mode 100644index 000000000..865493e3b--- /dev/null+++ b/src/app/document/io/write.ts@@ -0,0 +1,39 @@+import { IS_TAURI } from '@/constants'++import type { EditorState } from '@open-pencil/core/editor'++type WriteDocumentState = EditorState++type DocumentWriterOptions = {+ state: WriteDocumentState+ getFilePath: () => string | null+ getFileHandle: () => FileSystemFileHandle | null+ setSavedVersion: (version: number) => void+ setLastWriteTime: (time: number) => void+}++export function createDocumentWriter({+ state,+ getFilePath,+ getFileHandle,+ setSavedVersion,+ setLastWriteTime+}: DocumentWriterOptions) {+ return async function writeFile(data: Uint8Array) {+ setLastWriteTime(Date.now())+ const filePath = getFilePath()+ const fileHandle = getFileHandle()+ if (filePath && IS_TAURI) {+ const { writeFile: tauriWrite } = await import('@tauri-apps/plugin-fs')+ await tauriWrite(filePath, data)+ setSavedVersion(state.sceneVersion)+ return+ }+ if (fileHandle) {+ const writable = await fileHandle.createWritable()+ await writable.write(new Uint8Array(data))+ await writable.close()+ setSavedVersion(state.sceneVersion)+ }+ }+}diff --git a/src/app/editor/active-store/index.ts b/src/app/editor/active-store/index.tsnew file mode 100644index 000000000..4ed713fbb--- /dev/null+++ b/src/app/editor/active-store/index.ts@@ -0,0 +1,27 @@+import { shallowRef, triggerRef } from 'vue'++import type { EditorStore } from '@/app/editor/session'++export type { EditorStore }++const storeRef = shallowRef<EditorStore>()++export function setActiveEditorStore(store: EditorStore) {+ storeRef.value = store+ triggerRef(storeRef)+}++export function getActiveEditorStore(): EditorStore {+ if (!storeRef.value) throw new Error('Editor store not provided')+ return storeRef.value+}++const storeProxy = new Proxy({} as EditorStore, {+ get(_, prop) {+ return Reflect.get(getActiveEditorStore(), prop)+ }+})++export function useEditorStore(): EditorStore {+ return storeProxy+}diff --git a/src/app/editor/canvas/collaboration-awareness.ts b/src/app/editor/canvas/collaboration-awareness.tsnew file mode 100644index 000000000..0cc1d79c9--- /dev/null+++ b/src/app/editor/canvas/collaboration-awareness.ts@@ -0,0 +1,21 @@+import { watch } from 'vue'++import type { useCollabInjected } from '@/app/collab/use'+import type { EditorStore } from '@/app/editor/active-store'++type Collaboration = ReturnType<typeof useCollabInjected>++export function useCanvasCollaborationAwareness(store: EditorStore, collab: Collaboration) {+ function updateCursor(cx: number, cy: number) {+ store.state.cursorCanvasX = cx+ store.state.cursorCanvasY = cy+ collab?.updateCursor(cx, cy, store.state.currentPageId)+ }++ watch(+ () => [...store.state.selectedIds],+ (ids) => collab?.updateSelection(ids)+ )++ return { updateCursor }+}diff --git a/src/app/editor/canvas/context-selection.ts b/src/app/editor/canvas/context-selection.tsnew file mode 100644index 000000000..3d198b521--- /dev/null+++ b/src/app/editor/canvas/context-selection.ts@@ -0,0 +1,20 @@+import type { EditorStore } from '@/app/editor/active-store'+import type { Ref } from 'vue'++export function createCanvasContextSelection(+ canvasRef: Ref<HTMLCanvasElement | null>,+ store: EditorStore+) {+ function selectAtContextPoint(event: MouseEvent) {+ const canvas = canvasRef.value+ if (!canvas) return+ const rect = canvas.getBoundingClientRect()+ const { x: cx, y: cy } = store.screenToCanvas(+ event.clientX - rect.left,+ event.clientY - rect.top+ )+ store.selectAtPoint(cx, cy)+ }++ return { selectAtContextPoint }+}diff --git a/src/app/editor/canvas/loader-overlay.ts b/src/app/editor/canvas/loader-overlay.tsnew file mode 100644index 000000000..ac72a10f4--- /dev/null+++ b/src/app/editor/canvas/loader-overlay.ts@@ -0,0 +1,8 @@+const LOADER_FADE_OUT_MS = 300++export function fadeOutGlobalLoader() {+ const loader = document.getElementById('loader')+ if (!loader) return+ loader.classList.add('fade-out')+ setTimeout(() => loader.remove(), LOADER_FADE_OUT_MS)+}diff --git a/src/app/editor/canvas/menu-actions.ts b/src/app/editor/canvas/menu-actions.tsnew file mode 100644index 000000000..968b78db9--- /dev/null+++ b/src/app/editor/canvas/menu-actions.ts@@ -0,0 +1,69 @@+import { useClipboard } from '@vueuse/core'+import { nodeToXPath } from '@open-pencil/core/xpath'++import { toast } from '@/app/shell/ui'++import type { EditorStore } from '@/app/editor/active-store'+import type { Ref } from 'vue'++function toArrayBuffer(data: Uint8Array): ArrayBuffer {+ const bytes = new Uint8Array(data.length)+ bytes.set(data)+ return bytes.buffer+}++export function createCanvasMenuActions(store: EditorStore, selectedIds: Ref<Set<string>>) {+ const { copy } = useClipboard()++ function ids() {+ return [...selectedIds.value]+ }++ function execCommand(cmd: 'copy' | 'cut' | 'paste') {+ try {+ if (window.document.execCommand(cmd)) return+ } catch (error) {+ console.warn(`Clipboard command ${cmd} failed`, error)+ }++ toast.error('Clipboard access is blocked in this browser context')+ }++ async function clipboardWrite(text: string | null, label: string) {+ if (!text) return+ await copy(text)+ toast.info(`Copied as ${label}`)+ }++ async function copyNodeId() {+ const nodeIds = ids()+ if (nodeIds.length === 0) return+ await copy(nodeIds.join(', '))+ toast.info(`Copied node ID${nodeIds.length > 1 ? 's' : ''}`)+ }++ async function copyXPath() {+ const nodeIds = ids()+ if (nodeIds.length === 0) return+ const xpaths = nodeIds+ .map((id) => nodeToXPath(store.graph, id))+ .filter((xpath): xpath is string => xpath !== null)+ if (xpaths.length === 0) return+ await copy(xpaths.join('\n'))+ toast.info(`Copied XPath${xpaths.length > 1 ? 's' : ''}`)+ }++ async function copyAsPNG() {+ if (typeof ClipboardItem === 'undefined') {+ toast.error('PNG clipboard export is not available in this browser')+ return+ }+ const data = await store.renderExportImage(ids(), 2, 'PNG')+ if (!data) return+ const blob = new Blob([toArrayBuffer(data)], { type: 'image/png' })+ await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })])+ toast.info('Copied as PNG')+ }++ return { ids, execCommand, clipboardWrite, copyNodeId, copyXPath, copyAsPNG }+}diff --git a/src/app/editor/canvas/menu-model.ts b/src/app/editor/canvas/menu-model.tsnew file mode 100644index 000000000..d409343ad--- /dev/null+++ b/src/app/editor/canvas/menu-model.ts@@ -0,0 +1,14 @@+const COMPONENT_MENU_LABEL_PARTS = ['component', 'instance']++export function isComponentMenuItem(label: string) {+ const normalized = label.toLowerCase()+ return COMPONENT_MENU_LABEL_PARTS.some((part) => normalized.includes(part))+}++export function canvasMenuItemClass(label: string, classes: { item: string; component: string }) {+ return isComponentMenuItem(label) ? classes.component : classes.item+}++export function canvasMenuShortcutClass(label: string) {+ return isComponentMenuItem(label) ? 'text-component/60' : 'text-muted'+}diff --git a/src/app/editor/flash/create.ts b/src/app/editor/flash/create.tsnew file mode 100644index 000000000..c92bb00e2--- /dev/null+++ b/src/app/editor/flash/create.ts@@ -0,0 +1,51 @@+import type { Editor, EditorState } from '@open-pencil/core/editor'++export function createFlashActions(editor: Editor, state: EditorState) {+ let flashRafId = 0++ function pumpFlashes() {+ if (!editor.renderer?.hasActiveFlashes) {+ flashRafId = 0+ return+ }+ state.renderVersion+++ flashRafId = requestAnimationFrame(pumpFlashes)+ }++ function flashNodes(nodeIds: string[]) {+ const renderer = editor.renderer+ if (!renderer) return+ for (const id of nodeIds) renderer.flashNode(id)+ if (!flashRafId) pumpFlashes()+ }++ function aiMarkActive(nodeIds: string[]) {+ if (!editor.renderer) return+ editor.renderer.aiMarkActive(nodeIds)+ if (!flashRafId) pumpFlashes()+ }++ function aiMarkDone(nodeIds: string[]) {+ if (!editor.renderer) return+ editor.renderer.aiMarkDone(nodeIds)+ if (!flashRafId) pumpFlashes()+ }++ function aiFlashDone(nodeIds: string[]) {+ if (!editor.renderer) return+ editor.renderer.aiFlashDone(nodeIds)+ if (!flashRafId) pumpFlashes()+ }++ function aiClearAll() {+ editor.renderer?.aiClearAll()+ }++ return {+ flashNodes,+ aiMarkActive,+ aiMarkDone,+ aiFlashDone,+ aiClearAll+ }+}diff --git a/src/app/editor/flash/index.ts b/src/app/editor/flash/index.tsnew file mode 100644index 000000000..4f3d2a949--- /dev/null+++ b/src/app/editor/flash/index.ts@@ -0,0 +1 @@+export { createFlashActions } from './create'diff --git a/src/engine/fonts.ts b/src/app/editor/fonts.tssimilarity index 92%rename from src/engine/fonts.tsrename to src/app/editor/fonts.tsindex 2ebdb8599..5a938957e 100644--- a/src/engine/fonts.ts+++ b/src/app/editor/fonts.ts@@ -1,9 +1,5 @@-import {- IS_TAURI,- loadFont as loadFontCore,- markFontLoaded,- styleToWeight-} from '@open-pencil/core'+import { IS_TAURI } from '@open-pencil/core/constants'+import { loadFont as loadFontCore, markFontLoaded, styleToWeight } from '@open-pencil/core/text'interface TauriFontFamily {family: string@@ -48,7 +44,7 @@ export async function listFamilies(): Promise<string[]> {return fonts.map((f) => f.family)}- const { listFamilies: coreList } = await import('@open-pencil/core')+ const { listFamilies: coreList } = await import('@open-pencil/core/text')return coreList()}diff --git a/src/utils/layer-icons.ts b/src/app/editor/icons.tssimilarity index 71%rename from src/utils/layer-icons.tsrename to src/app/editor/icons.tsindex 4603ee951..4b4b55fa3 100644--- a/src/utils/layer-icons.ts+++ b/src/app/editor/icons.ts@@ -5,13 +5,34 @@ import IconComponent from '~icons/lucide/diamond'import IconFrame from '~icons/lucide/frame'import IconGrid from '~icons/lucide/grid-3x3'import IconGroup from '~icons/lucide/group'+import IconHand from '~icons/lucide/hand'import IconSection from '~icons/lucide/layout-grid'import IconMinus from '~icons/lucide/minus'+import IconMousePointer from '~icons/lucide/mouse-pointer'import IconPenTool from '~icons/lucide/pen-tool'import IconRows from '~icons/lucide/rows-3'import IconSquare from '~icons/lucide/square'+import IconStar from '~icons/lucide/star'+import IconTriangle from '~icons/lucide/triangle'import IconType from '~icons/lucide/type'+import type { Tool } from '@/app/editor/session'+import type { Component } from 'vue'++export const toolIcons: Record<Tool, Component> = {+ SELECT: IconMousePointer,+ FRAME: IconFrame,+ SECTION: IconSection,+ RECTANGLE: IconSquare,+ ELLIPSE: IconCircle,+ LINE: IconMinus,+ POLYGON: IconTriangle,+ STAR: IconStar,+ PEN: IconPenTool,+ TEXT: IconType,+ HAND: IconHand+}+export const NODE_ICONS: Partial<Record<string, typeof IconSquare>> = {SECTION: IconSection,ELLIPSE: IconCircle,diff --git a/src/app/editor/mobile-clipboard/index.ts b/src/app/editor/mobile-clipboard/index.tsnew file mode 100644index 000000000..f7c1ae85e--- /dev/null+++ b/src/app/editor/mobile-clipboard/index.ts@@ -0,0 +1,24 @@+import type { Editor, EditorState } from '@open-pencil/core/editor'++type MobileClipboardState = EditorState & { clipboardHtml: string }++export function createMobileClipboardActions(editor: Editor, state: MobileClipboardState) {+ async function mobileCopy() {+ const transfer = new DataTransfer()+ await editor.writeCopyData(transfer)+ state.clipboardHtml = transfer.getData('text/html')+ }++ async function mobileCut() {+ await mobileCopy()+ editor.deleteSelected()+ }++ function mobilePaste() {+ if (state.clipboardHtml) {+ editor.pasteFromHTML(state.clipboardHtml)+ }+ }++ return { mobileCopy, mobileCut, mobilePaste }+}diff --git a/src/app/editor/pen/create.ts b/src/app/editor/pen/create.tsnew file mode 100644index 000000000..cc4e5a4f1--- /dev/null+++ b/src/app/editor/pen/create.ts@@ -0,0 +1,58 @@+import {+ absoluteVertices,+ cloneSegments,+ createResumedPenState,+ walkChainOrdered,+ walkChainToEnd,+ type PenState+} from '@/app/editor/pen/resume'++import type { Editor, Tool } from '@open-pencil/core/editor'+import type { SceneGraph } from '@open-pencil/core/scene-graph'++export function createPenActions(editor: Editor, graph: SceneGraph, state: PenState) {+ function setTool(tool: Tool) {+ if (state.penState && tool !== 'PEN' && tool !== 'HAND') {+ editor.penCommit(false)+ }+ state.activeTool = tool+ }++ function penResumeOnPath(nodeId: string) {+ const node = graph.getNode(nodeId)+ if (node?.type !== 'VECTOR' || !node.vectorNetwork) return++ state.penState = createResumedPenState(+ node,+ absoluteVertices(node, node.vectorNetwork.vertices),+ cloneSegments(node.vectorNetwork.segments)+ )++ graph.deleteNode(nodeId)+ state.selectedIds = new Set()+ state.activeTool = 'PEN'+ editor.requestRender()+ }++ function penResumeFromEndpoint(nodeId: string, endpointVertexIndex: number) {+ const node = graph.getNode(nodeId)+ if (node?.type !== 'VECTOR' || !node.vectorNetwork) return++ const absVertices = absoluteVertices(node, node.vectorNetwork.vertices)+ const absSegments = cloneSegments(node.vectorNetwork.segments)+ const otherEnd = walkChainToEnd(absSegments, endpointVertexIndex)+ const { orderedVertices, orderedSegments } = walkChainOrdered(+ absVertices,+ absSegments,+ otherEnd+ )++ state.penState = createResumedPenState(node, orderedVertices, orderedSegments)+ graph.deleteNode(nodeId)+ state.selectedIds = new Set()+ state.activeTool = 'PEN'+ editor.requestRender()+ }++ return { setTool, penResumeOnPath, penResumeFromEndpoint }+}diff --git a/src/app/editor/pen/index.ts b/src/app/editor/pen/index.tsnew file mode 100644index 000000000..27e11577d--- /dev/null+++ b/src/app/editor/pen/index.ts@@ -0,0 +1 @@+export { createPenActions } from './create'diff --git a/src/app/editor/pen/resume.ts b/src/app/editor/pen/resume.tsnew file mode 100644index 000000000..32dae20cc--- /dev/null+++ b/src/app/editor/pen/resume.ts@@ -0,0 +1,113 @@+import type { EditorState } from '@open-pencil/core/editor'+import type { Fill, SceneNode, VectorSegment, VectorVertex } from '@open-pencil/core/scene-graph'++type ResumablePenState = NonNullable<EditorState['penState']> & {+ resumingNodeId?: string+ resumedFills?: Fill[]+ resumedStrokes?: SceneNode['strokes']+}++export type PenState = Omit<EditorState, 'penState'> & {+ penState: ResumablePenState | null+}++export function absoluteVertices(node: SceneNode, vertices: VectorVertex[]): VectorVertex[] {+ return vertices.map((v) => ({+ ...v,+ x: v.x + node.x,+ y: v.y + node.y+ }))+}++export function cloneSegments(segments: VectorSegment[]): VectorSegment[] {+ return segments.map((s) => ({+ ...s,+ tangentStart: { ...s.tangentStart },+ tangentEnd: { ...s.tangentEnd }+ }))+}++export function createResumedPenState(+ node: SceneNode,+ vertices: VectorVertex[],+ segments: VectorSegment[]+): ResumablePenState {+ return {+ vertices,+ segments,+ dragTangent: null,+ oppositeDragTangent: null,+ closingToFirst: false,+ pendingClose: false,+ resumingNodeId: node.id,+ resumedFills: [...node.fills],+ resumedStrokes: [...node.strokes]+ }+}++export function walkChainToEnd(segments: { start: number; end: number }[], start: number): number {+ let current = start+ const visited = new Set<number>([start])+ for (;;) {+ let found = false+ for (const seg of segments) {+ let next = -1+ if (seg.start === current && !visited.has(seg.end)) next = seg.end+ else if (seg.end === current && !visited.has(seg.start)) next = seg.start+ if (next === -1) continue+ visited.add(next)+ current = next+ found = true+ break+ }+ if (!found) break+ }+ return current+}++export function walkChainOrdered(+ absVertices: VectorVertex[],+ absSegments: VectorSegment[],+ start: number+): { orderedVertices: VectorVertex[]; orderedSegments: VectorSegment[] } {+ const orderedVertices: VectorVertex[] = []+ const orderedSegments: VectorSegment[] = []+ const visited = new Set<number>()+ let current = start++ orderedVertices.push(absVertices[current])+ visited.add(current)++ for (;;) {+ let foundSeg = false+ for (const seg of absSegments) {+ let next = -1+ let isForward = false+ if (seg.start === current && !visited.has(seg.end)) {+ next = seg.end+ isForward = true+ } else if (seg.end === current && !visited.has(seg.start)) {+ next = seg.start+ }+ if (next === -1) continue++ const fromIdx = orderedVertices.length - 1+ orderedVertices.push(absVertices[next])+ const toIdx = orderedVertices.length - 1++ orderedSegments.push({+ start: fromIdx,+ end: toIdx,+ tangentStart: isForward ? { ...seg.tangentStart } : { ...seg.tangentEnd },+ tangentEnd: isForward ? { ...seg.tangentEnd } : { ...seg.tangentStart }+ })++ visited.add(next)+ current = next+ foundSeg = true+ break+ }+ if (!foundSeg) break+ }+ return { orderedVertices, orderedSegments }+}diff --git a/src/app/editor/profiler/index.ts b/src/app/editor/profiler/index.tsnew file mode 100644index 000000000..722bfcb09--- /dev/null+++ b/src/app/editor/profiler/index.ts@@ -0,0 +1,19 @@+import type { Editor } from '@open-pencil/core/editor'++export function createProfilerActions(editor: Editor) {+ function viewportScreenCenter() {+ const canvas = document.querySelector<HTMLCanvasElement>('[data-test-id="canvas-element"]')+ if (canvas) {+ const rect = canvas.getBoundingClientRect()+ return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }+ }+ return { x: window.innerWidth / 2, y: window.innerHeight / 2 }+ }++ function toggleProfiler() {+ editor.renderer?.profiler.toggle()+ editor.requestRepaint()+ }++ return { viewportScreenCenter, toggleProfiler }+}diff --git a/src/app/editor/session/create.ts b/src/app/editor/session/create.tsnew file mode 100644index 000000000..4eac5c98a--- /dev/null+++ b/src/app/editor/session/create.ts@@ -0,0 +1,69 @@+import { shallowReactive } from 'vue'++import {+ getActiveEditorStore,+ setActiveEditorStore,+ useEditorStore+} from '@/app/editor/active-store'+import { loadFont } from '@/app/editor/fonts'+import {+ createEditorComputedRefs,+ createEditorStoreModules,+ defineEditorStoreAccessors+} from '@/app/editor/session/modules'+import { createInitialAppEditorState, type AppEditorState } from '@/app/editor/session/types'+import { createEditor } from '@open-pencil/core/editor'+import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'+import { SceneGraph } from '@open-pencil/core/scene-graph'++export { EDITOR_TOOLS as TOOLS, TOOL_SHORTCUTS } from '@open-pencil/core/editor'+export type { EditorToolDef as ToolDef, Tool } from '@open-pencil/core/editor'++export function createEditorStore(initialGraph?: SceneGraph) {+ const graph = initialGraph ?? new SceneGraph()++ const state = shallowReactive<AppEditorState>(createInitialAppEditorState(graph.getPages()[0].id))++ const viewportSize = { width: 0, height: 0 }+ const editor = createEditor({+ graph,+ state,+ loadFont,+ skipInitialGraphSetup: !!initialGraph,+ getViewportSize: () =>+ viewportSize.width > 0 && viewportSize.height > 0+ ? viewportSize+ : { width: window.innerWidth, height: window.innerHeight }+ })+ const io = new IORegistry(BUILTIN_IO_FORMATS)++ if (initialGraph) {+ editor.subscribeToGraph()+ }++ const { selectedNodes, selectedNode, layerTree } = createEditorComputedRefs(editor, state)++ const modules = createEditorStoreModules(editor, graph, state, io, viewportSize)++ // ─── Public API ───────────────────────────────────────────────+ // Spread all core Editor methods, then override getters and add app-specific.++ const store = {+ ...editor,+ state,+ selectedNodes,+ selectedNode,+ layerTree,++ // App-specific overrides and additions+ ...modules+ }++ defineEditorStoreAccessors(store, editor)++ return store+}++export type EditorStore = ReturnType<typeof createEditorStore>++export { getActiveEditorStore, setActiveEditorStore, useEditorStore }diff --git a/src/app/editor/session/index.ts b/src/app/editor/session/index.tsnew file mode 100644index 000000000..45585fb1d--- /dev/null+++ b/src/app/editor/session/index.ts@@ -0,0 +1,3 @@+export { createEditorStore } from './create'+export type { EditorStore, Tool, ToolDef } from './create'+export { TOOLS, TOOL_SHORTCUTS } from './create'diff --git a/src/app/editor/session/modules.ts b/src/app/editor/session/modules.tsnew file mode 100644index 000000000..a40aa00bb--- /dev/null+++ b/src/app/editor/session/modules.ts@@ -0,0 +1,90 @@+import { computed } from 'vue'++import { createDocumentExportActions } from '@/app/document/export'+import { createDocumentIOActions } from '@/app/document/io'+import { createFlashActions } from '@/app/editor/flash'+import { createMobileClipboardActions } from '@/app/editor/mobile-clipboard'+import { createPenActions } from '@/app/editor/pen'+import { createProfilerActions } from '@/app/editor/profiler'+import { createVectorEditActions } from '@/app/editor/vector-edit'++import type { AppEditorState } from '@/app/editor/session/types'+import type { Editor } from '@open-pencil/core/editor'+import type { IORegistry } from '@open-pencil/core/io'+import type { SceneGraph } from '@open-pencil/core/scene-graph'++type ViewportSize = { width: number; height: number }++export function defineEditorStoreAccessors(store: object, editor: Editor) {+ Object.defineProperties(store, {+ graph: {+ enumerable: true,+ get: () => editor.graph+ },+ renderer: {+ enumerable: true,+ get: () => editor.renderer+ },+ textEditor: {+ enumerable: true,+ get: () => editor.textEditor+ }+ })+}++export function createEditorComputedRefs(editor: Editor, state: AppEditorState) {+ const selectedNodes = computed(() => {+ void state.sceneVersion+ return editor.getSelectedNodes()+ })++ const selectedNode = computed(() =>+ selectedNodes.value.length === 1 ? selectedNodes.value[0] : undefined+ )++ const layerTree = computed(() => {+ void state.sceneVersion+ return editor.getLayerTree()+ })++ return { selectedNodes, selectedNode, layerTree }+}++export function createEditorStoreModules(+ editor: Editor,+ graph: SceneGraph,+ state: AppEditorState,+ io: IORegistry,+ viewportSize: ViewportSize+) {+ const flash = createFlashActions(editor, state)+ const pen = createPenActions(editor, graph, state)+ const vectorEdit = createVectorEditActions(editor, graph, state)+ const documentIO = createDocumentIOActions(editor, state, viewportSize)+ const documentExport = createDocumentExportActions(+ editor,+ state,+ io,+ documentIO.downloadBlob+ )+ const mobileClipboard = createMobileClipboardActions(editor, state)+ const profiler = createProfilerActions(editor)++ return {+ ...flash,+ ...pen,+ ...vectorEdit,+ openFigFile: documentIO.openFigFile,+ setViewportSize: documentIO.setViewportSize,+ fitCurrentPageToViewport: documentIO.fitCurrentPageToViewport,+ saveFigFile: documentIO.saveFigFile,+ saveFigFileAs: documentIO.saveFigFileAs,+ setDocumentSource: documentIO.setDocumentSource,+ setPlannedFilePath: documentIO.setPlannedFilePath,+ startWatchingCurrentFile: documentIO.startWatchingCurrentFile,+ dispose: documentIO.disposeDocumentIO,+ ...documentExport,+ ...mobileClipboard,+ ...profiler+ }+}diff --git a/src/app/editor/session/types.ts b/src/app/editor/session/types.tsnew file mode 100644index 000000000..f22e52024--- /dev/null+++ b/src/app/editor/session/types.ts@@ -0,0 +1,50 @@+import type { NodeEditState } from '@/app/editor/vector-edit/types'+import { createDefaultEditorState, type EditorState } from '@open-pencil/core/editor'+import type { Fill, SceneNode, VectorSegment, VectorVertex } from '@open-pencil/core/scene-graph'+import type { Vector } from '@open-pencil/core/types'++export function createInitialAppEditorState(pageId: string): AppEditorState {+ return {+ ...createDefaultEditorState(pageId),+ showUI: true,+ showRulers: true,+ showRemoteCursors: true,+ activeRibbonTab: 'panels',+ panelMode: 'design',+ actionToast: null,+ mobileDrawerSnap: 'closed',+ clipboardHtml: '',+ autosaveEnabled: false,+ cursorCanvasX: null,+ cursorCanvasY: null,+ nodeEditState: null,+ scrubInputFocused: false+ }+}++export type AppEditorState = Omit<EditorState, 'penState'> & {+ penState: {+ vertices: VectorVertex[]+ segments: VectorSegment[]+ dragTangent: Vector | null+ oppositeDragTangent: Vector | null+ closingToFirst: boolean+ pendingClose?: boolean+ resumingNodeId?: string+ resumedFills?: Fill[]+ resumedStrokes?: SceneNode['strokes']+ } | null+ showUI: boolean+ showRulers: boolean+ showRemoteCursors: boolean+ activeRibbonTab: 'panels' | 'code' | 'ai'+ panelMode: 'layers' | 'design'+ actionToast: string | null+ mobileDrawerSnap: 'closed' | 'half' | 'full'+ clipboardHtml: string+ autosaveEnabled: boolean+ cursorCanvasX: number | null+ cursorCanvasY: number | null+ nodeEditState: NodeEditState | null+ scrubInputFocused: boolean+}diff --git a/src/app/editor/vector-edit/create.ts b/src/app/editor/vector-edit/create.tsnew file mode 100644index 000000000..6c048ea0e--- /dev/null+++ b/src/app/editor/vector-edit/create.ts@@ -0,0 +1,43 @@+import { createVectorEditHandleActions } from './handle-actions'+import { createVectorEditLifecycle } from './lifecycle'+import { createVectorEditNetworkActions, getLiveNetwork, setNodeEditNetwork } from './network'+import { createVectorEditSelectionActions } from './selection'++import type { VectorEditState } from './types'+import type { Editor } from '@open-pencil/core/editor'+import type { SceneGraph } from '@open-pencil/core/scene-graph'++export function createVectorEditActions(editor: Editor, graph: SceneGraph, state: VectorEditState) {+ const { getNodeEditState, applyNodeEditToNode, enterNodeEditMode, exitNodeEditMode } =+ createVectorEditLifecycle(editor, graph, state)+ const {+ nodeEditSelectVertex,+ nodeEditAlignVertices,+ nodeEditDeleteSelected,+ nodeEditBreakAtVertex+ } = createVectorEditSelectionActions(editor, state)++ const { nodeEditSetHandle, nodeEditBendHandle, nodeEditZeroVertexHandles } =+ createVectorEditHandleActions(editor, getNodeEditState)+ const { nodeEditConnectEndpoints, nodeEditAddVertex, nodeEditRemoveVertex } =+ createVectorEditNetworkActions(editor, state, getNodeEditState)++ return {+ getNodeEditState,+ setNodeEditNetwork,+ getLiveNetwork,+ applyNodeEditToNode,+ enterNodeEditMode,+ exitNodeEditMode,+ nodeEditSelectVertex,+ nodeEditSetHandle,+ nodeEditBendHandle,+ nodeEditZeroVertexHandles,+ nodeEditConnectEndpoints,+ nodeEditAddVertex,+ nodeEditRemoveVertex,+ nodeEditAlignVertices,+ nodeEditDeleteSelected,+ nodeEditBreakAtVertex+ }+}diff --git a/src/app/editor/vector-edit/handle-actions.ts b/src/app/editor/vector-edit/handle-actions.tsnew file mode 100644index 000000000..6b75938d8--- /dev/null+++ b/src/app/editor/vector-edit/handle-actions.ts@@ -0,0 +1,141 @@+import { findAllHandles, findOppositeHandle, mirrorHandle } from '@open-pencil/core/vector'++import { constrainContinuousTangent } from './handles'+import { getLiveNetwork } from './network'++import type { NodeEditState } from './types'+import type { Editor } from '@open-pencil/core/editor'+import type { Vector } from '@open-pencil/core/types'++type GetNodeEditState = () => NodeEditState | null++export function createVectorEditHandleActions(editor: Editor, getNodeEditState: GetNodeEditState) {+ function nodeEditSetHandle(+ segmentIndex: number,+ tangentField: 'tangentStart' | 'tangentEnd',+ newTangent: Vector,+ options?: {+ breakMirroring?: boolean+ continuous?: boolean+ lockDirection?: boolean+ }+ ) {+ const es = getNodeEditState()+ if (!es) return+ const seg = es.segments[segmentIndex]++ const breakMirroring = options?.breakMirroring ?? false+ const continuous = options?.continuous ?? false+ const lockDirection = options?.lockDirection ?? false+ const vertexIndex = tangentField === 'tangentStart' ? seg.start : seg.end+ const vertex = es.vertices[vertexIndex]+ const live = getLiveNetwork(es)++ const all = findAllHandles(live, vertexIndex)+ const active = all.find(+ (h) => h.segmentIndex === segmentIndex && h.tangentField === tangentField+ )++ let applied = { x: newTangent.x, y: newTangent.y }+ if (continuous && active) {+ applied =+ constrainContinuousTangent(+ es,+ newTangent,+ active,+ all,+ seg,+ tangentField,+ vertexIndex,+ vertex+ ) ?? applied+ }++ seg[tangentField] = applied+ const mode = vertex.handleMirroring ?? 'NONE'+ if (lockDirection && mode === 'NONE') {+ seg[tangentField] = { x: newTangent.x, y: newTangent.y }+ editor.requestRepaint()+ return+ }+ if (breakMirroring) {+ vertex.handleMirroring = 'NONE'+ editor.requestRepaint()+ return+ }+ if (mode === 'NONE') {+ editor.requestRepaint()+ return+ }++ const opposite = findOppositeHandle(live, vertexIndex, segmentIndex)+ if (!opposite) {+ editor.requestRepaint()+ return+ }++ const oppositeSeg = es.segments[opposite.segmentIndex]+ const oppositeCurrent = oppositeSeg[opposite.tangentField]+ const oppositeLength =+ mode === 'ANGLE' ? Math.hypot(oppositeCurrent.x, oppositeCurrent.y) : undefined+ const mirrored = mirrorHandle(applied, mode, oppositeLength)+ if (mirrored) {+ oppositeSeg[opposite.tangentField] = mirrored+ }+ editor.requestRepaint()+ }++ function nodeEditBendHandle(+ vertexIndex: number,+ dx: number,+ dy: number,+ independent: boolean,+ targetSegmentIndex: number | null,+ targetTangentField: 'tangentStart' | 'tangentEnd' | null+ ) {+ const es = getNodeEditState()+ if (!es) return+ if (targetSegmentIndex == null || targetTangentField == null) return+ const live = getLiveNetwork(es)+ const handles = findAllHandles(live, vertexIndex)+ if (handles.length === 0) return++ const effectiveTargets = handles.filter(+ (h) => h.segmentIndex === targetSegmentIndex && h.tangentField === targetTangentField+ )+ if (effectiveTargets.length === 0) return++ const primary = { x: dx, y: dy }+ const opposite = independent ? { x: dx, y: dy } : { x: -dx, y: -dy }++ const first = effectiveTargets[0]+ es.segments[first.segmentIndex][first.tangentField] = primary+ for (let i = 1; i < effectiveTargets.length; i++) {+ const h = effectiveTargets[i]+ es.segments[h.segmentIndex][h.tangentField] = primary+ }+ if (!independent) {+ for (const h of handles) {+ if (effectiveTargets.includes(h)) continue+ es.segments[h.segmentIndex][h.tangentField] = opposite+ }+ }++ es.vertices[vertexIndex].handleMirroring = independent ? 'NONE' : 'ANGLE_AND_LENGTH'+ editor.requestRepaint()+ }++ function nodeEditZeroVertexHandles(vertexIndex: number) {+ const es = getNodeEditState()+ if (!es) return+ const live = getLiveNetwork(es)+ const handles = findAllHandles(live, vertexIndex)+ for (const h of handles) {+ es.segments[h.segmentIndex][h.tangentField] = { x: 0, y: 0 }+ }+ es.vertices[vertexIndex].handleMirroring = 'NONE'+ editor.requestRepaint()+ }++ return { nodeEditSetHandle, nodeEditBendHandle, nodeEditZeroVertexHandles }+}diff --git a/src/app/editor/vector-edit/handles.ts b/src/app/editor/vector-edit/handles.tsnew file mode 100644index 000000000..9e3d9c3e6--- /dev/null+++ b/src/app/editor/vector-edit/handles.ts@@ -0,0 +1,69 @@+import type { HandleInfo, NodeEditState } from './types'+import type { VectorSegment, VectorVertex } from '@open-pencil/core/scene-graph'+import type { Vector } from '@open-pencil/core/types'++function handleBaseVector(tangent: Vector, neighbor: Vector, origin: Vector): Vector {+ return Math.hypot(tangent.x, tangent.y) > 1e-6+ ? tangent+ : { x: neighbor.x - origin.x, y: neighbor.y - origin.y }+}++function findSisterHandle(+ es: NodeEditState,+ siblings: HandleInfo[],+ activeBase: Vector,+ vertexIndex: number+): HandleInfo {+ let sister = siblings[0]+ const activeBaseLen = Math.hypot(activeBase.x, activeBase.y)+ if (activeBaseLen <= 1e-6) return sister++ const activeDir = { x: activeBase.x / activeBaseLen, y: activeBase.y / activeBaseLen }+ let bestDot = Infinity+ for (const s of siblings) {+ const sSeg = es.segments[s.segmentIndex]+ const sVertex = es.vertices[vertexIndex]+ const sNeighbor = es.vertices[s.neighborIndex]+ const sBase = handleBaseVector(sSeg[s.tangentField], sNeighbor, sVertex)+ const sLen = Math.hypot(sBase.x, sBase.y)+ if (sLen < 1e-6) continue+ const sDir = { x: sBase.x / sLen, y: sBase.y / sLen }+ const dot = activeDir.x * sDir.x + activeDir.y * sDir.y+ if (dot < bestDot) {+ bestDot = dot+ sister = s+ }+ }+ return sister+}++export function constrainContinuousTangent(+ es: NodeEditState,+ newTangent: Vector,+ active: HandleInfo,+ all: HandleInfo[],+ seg: VectorSegment,+ tangentField: 'tangentStart' | 'tangentEnd',+ vertexIndex: number,+ vertex: VectorVertex+): Vector | null {+ const siblings = all.filter(+ (h) => !(h.segmentIndex === active.segmentIndex && h.tangentField === active.tangentField)+ )+ if (siblings.length === 0) return null++ const activeNeighbor = es.vertices[active.neighborIndex]+ const activeBase = handleBaseVector(seg[tangentField], activeNeighbor, vertex)+ const sister = findSisterHandle(es, siblings, activeBase, vertexIndex)++ const sisterSeg = es.segments[sister.segmentIndex]+ const sisterNeighbor = es.vertices[sister.neighborIndex]+ const sisterBase = handleBaseVector(sisterSeg[sister.tangentField], sisterNeighbor, vertex)+ const sisterLen = Math.hypot(sisterBase.x, sisterBase.y)+ if (sisterLen <= 1e-6) return null++ const desiredDir = { x: -sisterBase.x / sisterLen, y: -sisterBase.y / sisterLen }+ const len = Math.max(0, newTangent.x * desiredDir.x + newTangent.y * desiredDir.y)+ vertex.handleMirroring = 'ANGLE'+ return { x: desiredDir.x * len, y: desiredDir.y * len }+}diff --git a/src/app/editor/vector-edit/index.ts b/src/app/editor/vector-edit/index.tsnew file mode 100644index 000000000..339ede3ee--- /dev/null+++ b/src/app/editor/vector-edit/index.ts@@ -0,0 +1 @@+export { createVectorEditActions } from './create'diff --git a/src/app/editor/vector-edit/lifecycle.ts b/src/app/editor/vector-edit/lifecycle.tsnew file mode 100644index 000000000..ed2123eca--- /dev/null+++ b/src/app/editor/vector-edit/lifecycle.ts@@ -0,0 +1,107 @@+import { cloneVectorNetwork } from '@open-pencil/core/scene-graph'+import { computeAccurateBounds } from '@open-pencil/core/vector'++import { getLiveNetwork } from './network'++import type { VectorEditState } from './types'+import type { Editor } from '@open-pencil/core/editor'+import type { SceneGraph, VectorNetwork } from '@open-pencil/core/scene-graph'++export function createVectorEditLifecycle(+ editor: Editor,+ graph: SceneGraph,+ state: VectorEditState+) {+ function getNodeEditState() {+ return state.nodeEditState+ }++ function applyNodeEditToNode(es: NonNullable<typeof state.nodeEditState>) {+ const node = graph.getNode(es.nodeId)+ if (node?.type !== 'VECTOR') return++ const live = getLiveNetwork(es)+ const bounds = computeAccurateBounds(live)+ const relativeNetwork: VectorNetwork = {+ vertices: live.vertices.map((v) => ({+ ...v,+ x: v.x - bounds.x,+ y: v.y - bounds.y+ })),+ segments: live.segments,+ regions: live.regions+ }++ graph.updateNode(node.id, {+ x: bounds.x,+ y: bounds.y,+ width: bounds.width,+ height: bounds.height,+ vectorNetwork: relativeNetwork+ })+ editor.requestRender()+ }++ function enterNodeEditMode(nodeId: string) {+ const node = graph.getNode(nodeId)+ if (node?.type !== 'VECTOR' || !node.vectorNetwork) return++ const absVertices = node.vectorNetwork.vertices.map((v) => ({+ ...v,+ x: v.x + node.x,+ y: v.y + node.y+ }))++ state.nodeEditState = {+ nodeId,+ origNetwork: cloneVectorNetwork(node.vectorNetwork),+ origBounds: { x: node.x, y: node.y, width: node.width, height: node.height },+ vertices: absVertices,+ segments: node.vectorNetwork.segments.map((s) => ({+ ...s,+ tangentStart: { ...s.tangentStart },+ tangentEnd: { ...s.tangentEnd }+ })),+ regions: node.vectorNetwork.regions.map((r) => ({+ windingRule: r.windingRule,+ loops: r.loops.map((l) => [...l])+ })),+ selectedVertexIndices: new Set(),+ draggedHandleInfo: null,+ selectedHandles: new Set(),+ hoveredHandleInfo: null+ }++ state.selectedIds = new Set([nodeId])+ editor.requestRender()+ }++ function exitNodeEditMode(commit: boolean) {+ const es = getNodeEditState()+ if (!es) return++ const node = graph.getNode(es.nodeId)+ if (node?.type !== 'VECTOR') {+ state.nodeEditState = null+ editor.requestRender()+ return+ }++ if (commit) {+ applyNodeEditToNode(es)+ } else {+ graph.updateNode(es.nodeId, {+ x: es.origBounds.x,+ y: es.origBounds.y,+ width: es.origBounds.width,+ height: es.origBounds.height,+ vectorNetwork: cloneVectorNetwork(es.origNetwork)+ })+ editor.requestRender()+ }++ state.nodeEditState = null+ }++ return { getNodeEditState, applyNodeEditToNode, enterNodeEditMode, exitNodeEditMode }+}diff --git a/src/app/editor/vector-edit/network.ts b/src/app/editor/vector-edit/network.tsnew file mode 100644index 000000000..f7eb0186d--- /dev/null+++ b/src/app/editor/vector-edit/network.ts@@ -0,0 +1,97 @@+import { nearestPointOnNetwork, removeVertex, splitSegmentAt } from '@open-pencil/core/vector'++import type { NodeEditState, VectorEditState } from './types'+import type { Editor } from '@open-pencil/core/editor'+import type { VectorNetwork } from '@open-pencil/core/scene-graph'++export function setNodeEditNetwork(es: NodeEditState, network: VectorNetwork) {+ es.vertices = network.vertices.map((v) => ({ ...v }))+ es.segments = network.segments.map((s) => ({+ ...s,+ tangentStart: { ...s.tangentStart },+ tangentEnd: { ...s.tangentEnd }+ }))+ es.regions = network.regions.map((r) => ({+ windingRule: r.windingRule,+ loops: r.loops.map((l) => [...l])+ }))+}++export function getLiveNetwork(es: NodeEditState): VectorNetwork {+ return {+ vertices: es.vertices.map((v) => ({ ...v })),+ segments: es.segments.map((s) => ({+ ...s,+ tangentStart: { ...s.tangentStart },+ tangentEnd: { ...s.tangentEnd }+ })),+ regions: es.regions.map((r) => ({+ windingRule: r.windingRule,+ loops: r.loops.map((l) => [...l])+ }))+ }+}++export function createVectorEditNetworkActions(+ editor: Editor,+ state: VectorEditState,+ getNodeEditState: () => NodeEditState | null+) {+ const nodeEditHitThreshold = 8++ function nodeEditConnectEndpoints(a: number, b: number) {+ const es = getNodeEditState()+ if (!es || a === b) return+ if (a < 0 || b < 0 || a >= es.vertices.length || b >= es.vertices.length) return++ const removeIndex = a+ const keepIndex = b+ const remap = (idx: number): number => {+ if (idx === removeIndex) return keepIndex+ return idx > removeIndex ? idx - 1 : idx+ }++ const nextVertices = es.vertices.filter((_, idx) => idx !== removeIndex)+ const nextSegments = es.segments+ .map((seg) => ({+ ...seg,+ tangentStart: { ...seg.tangentStart },+ tangentEnd: { ...seg.tangentEnd },+ start: remap(seg.start),+ end: remap(seg.end)+ }))+ .filter((seg) => seg.start !== seg.end)++ setNodeEditNetwork(es, { vertices: nextVertices, segments: nextSegments, regions: [] })+ es.selectedVertexIndices = new Set([remap(keepIndex)])+ es.selectedHandles = new Set()+ editor.requestRender()+ }++ function nodeEditAddVertex(cx: number, cy: number) {+ const es = getNodeEditState()+ if (!es) return+ const live = getLiveNetwork(es)+ const nearest = nearestPointOnNetwork(cx, cy, live, nodeEditHitThreshold / state.zoom)+ if (!nearest) return+ const split = splitSegmentAt(live, nearest.segmentIndex, nearest.t)+ setNodeEditNetwork(es, split.network)+ es.selectedVertexIndices = new Set([split.newVertexIndex])+ es.selectedHandles = new Set()+ editor.requestRender()+ }++ function nodeEditRemoveVertex(vertexIndex: number) {+ const es = getNodeEditState()+ if (!es) return+ const live = getLiveNetwork(es)+ const next = removeVertex(live, vertexIndex)+ if (!next) return+ setNodeEditNetwork(es, next)+ es.selectedVertexIndices = new Set()+ es.selectedHandles = new Set()+ editor.requestRender()+ }++ return { nodeEditConnectEndpoints, nodeEditAddVertex, nodeEditRemoveVertex }+}diff --git a/src/app/editor/vector-edit/selection.ts b/src/app/editor/vector-edit/selection.tsnew file mode 100644index 000000000..b13cc4a48--- /dev/null+++ b/src/app/editor/vector-edit/selection.ts@@ -0,0 +1,95 @@+import { breakAtVertex, deleteVertex } from '@open-pencil/core/vector'++import { getLiveNetwork, setNodeEditNetwork } from './network'++import type { VectorEditState } from './types'+import type { Editor } from '@open-pencil/core/editor'++export function createVectorEditSelectionActions(editor: Editor, state: VectorEditState) {+ function getNodeEditState() {+ return state.nodeEditState+ }++ function nodeEditSelectVertex(vertexIndex: number, addToSelection: boolean) {+ const es = getNodeEditState()+ if (!es) return+ if (addToSelection) {+ const next = new Set(es.selectedVertexIndices)+ if (next.has(vertexIndex)) next.delete(vertexIndex)+ else next.add(vertexIndex)+ es.selectedVertexIndices = next+ } else {+ es.selectedVertexIndices = new Set([vertexIndex])+ }+ editor.requestRepaint()+ }++ function nodeEditAlignVertices(axis: 'horizontal' | 'vertical', align: 'min' | 'center' | 'max') {+ const es = getNodeEditState()+ if (!es || es.selectedVertexIndices.size < 2) return++ const indices = [...es.selectedVertexIndices]+ const prop = axis === 'horizontal' ? 'x' : 'y'++ let lo = Infinity+ let hi = -Infinity+ for (const i of indices) {+ const v = es.vertices[i][prop]+ if (v < lo) lo = v+ if (v > hi) hi = v+ }++ let target = (lo + hi) / 2+ if (align === 'min') target = lo+ else if (align === 'max') target = hi+ for (const i of indices) {+ es.vertices[i] = { ...es.vertices[i], [prop]: target }+ }+ editor.requestRepaint()+ }++ function nodeEditDeleteSelected() {+ const es = getNodeEditState()+ if (!es) return+ let live = getLiveNetwork(es)++ for (const key of es.selectedHandles) {+ const [siStr, tf] = key.split(':')+ const si = Number(siStr)+ const seg = live.segments[si]+ if (tf === 'tangentStart') seg.tangentStart = { x: 0, y: 0 }+ else seg.tangentEnd = { x: 0, y: 0 }+ }++ const verticesToDelete = [...es.selectedVertexIndices].sort((a, b) => b - a)+ for (const vi of verticesToDelete) {+ const next = deleteVertex(live, vi)+ if (!next) break+ live = next+ }++ setNodeEditNetwork(es, live)+ es.selectedVertexIndices = new Set()+ es.selectedHandles = new Set()+ editor.requestRender()+ }++ function nodeEditBreakAtVertex() {+ const es = getNodeEditState()+ if (!es || es.selectedVertexIndices.size === 0) return+ const [vertexIndex] = es.selectedVertexIndices+ const live = getLiveNetwork(es)+ const next = breakAtVertex(live, vertexIndex)+ setNodeEditNetwork(es, next)+ es.selectedHandles = new Set()+ es.selectedVertexIndices = new Set([vertexIndex])+ editor.requestRender()+ }++ return {+ nodeEditSelectVertex,+ nodeEditAlignVertices,+ nodeEditDeleteSelected,+ nodeEditBreakAtVertex+ }+}diff --git a/src/app/editor/vector-edit/types.ts b/src/app/editor/vector-edit/types.tsnew file mode 100644index 000000000..cd9298112--- /dev/null+++ b/src/app/editor/vector-edit/types.ts@@ -0,0 +1,31 @@+import type { EditorState } from '@open-pencil/core/editor'+import type { VectorNetwork, VectorRegion, VectorSegment, VectorVertex } from '@open-pencil/core/scene-graph'+import type { Rect } from '@open-pencil/core/types'++export type NodeEditState = {+ nodeId: string+ origNetwork: VectorNetwork+ origBounds: Rect+ vertices: VectorVertex[]+ segments: VectorSegment[]+ regions: VectorRegion[]+ selectedVertexIndices: Set<number>+ draggedHandleInfo: {+ vertexIndex: number+ handleType: 'tangentStart' | 'tangentEnd'+ segmentIndex: number+ } | null+ selectedHandles: Set<string>+ hoveredHandleInfo: {+ segmentIndex: number+ tangentField: 'tangentStart' | 'tangentEnd'+ } | null+}++export type VectorEditState = EditorState & { nodeEditState: NodeEditState | null }++export type HandleInfo = {+ segmentIndex: number+ tangentField: 'tangentStart' | 'tangentEnd'+ neighborIndex: number+}diff --git a/src/app/shell/keyboard/actions.ts b/src/app/shell/keyboard/actions.tsnew file mode 100644index 000000000..222c2f0cf--- /dev/null+++ b/src/app/shell/keyboard/actions.ts@@ -0,0 +1,108 @@+import type { EditorStore } from '@/app/editor/active-store'+import type { useEditorCommands, useViewportKind } from '@open-pencil/vue'+import type { Ref } from 'vue'++type KeyboardActionsOptions = {+ store: EditorStore+ activeTab: Ref<'design' | 'code' | 'ai'>+ isMobile: ReturnType<typeof useViewportKind>['isMobile']+ runCommand: ReturnType<typeof useEditorCommands>['runCommand']+}++export function createKeyboardActions({+ store,+ activeTab,+ isMobile,+ runCommand+}: KeyboardActionsOptions) {+ function hasNodeEditSelection() {+ return (+ store.state.nodeEditState &&+ (store.state.nodeEditState.selectedVertexIndices.size > 0 ||+ store.state.nodeEditState.selectedHandles.size > 0)+ )+ }++ function smartDelete(altKey: boolean) {+ if (hasNodeEditSelection()) {+ if (altKey) store.nodeEditBreakAtVertex()+ else store.nodeEditDeleteSelected()+ return+ }+ runCommand('selection.delete')+ }++ function confirmOrEnterText() {+ if (store.state.nodeEditState) {+ store.exitNodeEditMode(true)+ return+ }+ if (store.state.penState) {+ store.penCommit(false)+ return+ }+ const node = store.selectedNode.value+ if (node?.type === 'TEXT') {+ requestAnimationFrame(() => {+ store.startTextEditing(node.id)+ store.textEditor?.selectAll()+ store.requestRender()+ })+ }+ }++ function escapeOrDeselect() {+ if (store.state.nodeEditState) {+ store.exitNodeEditMode(true)+ return+ }+ if (store.state.penState) {+ store.penCancel()+ return+ }+ if (store.state.enteredContainerId) {+ store.exitContainer()+ return+ }+ store.clearSelection()+ store.setTool('SELECT')+ }++ function toggleAutoLayout() {+ const node = store.selectedNode.value+ if (node?.type === 'FRAME' && store.selectedNodes.value.length === 1) {+ store.setLayoutMode(node.id, node.layoutMode === 'NONE' ? 'VERTICAL' : 'NONE')+ } else if (store.selectedNodes.value.length > 0) {+ runCommand('selection.wrapInAutoLayout')+ }+ }++ function toggleUI() {+ store.state.showUI = !store.state.showUI+ }++ function toggleAI() {+ if (isMobile.value) {+ store.state.activeRibbonTab = store.state.activeRibbonTab === 'ai' ? 'panels' : 'ai'+ if (store.state.mobileDrawerSnap === 'closed') {+ store.state.mobileDrawerSnap = 'half'+ }+ } else {+ activeTab.value = activeTab.value === 'ai' ? 'design' : 'ai'+ }+ }++ function exportSelectionPng() {+ if (store.state.selectedIds.size > 0) void store.exportSelection(1, 'png')+ }++ return {+ smartDelete,+ confirmOrEnterText,+ escapeOrDeselect,+ toggleAutoLayout,+ toggleUI,+ toggleAI,+ exportSelectionPng+ }+}diff --git a/src/app/shell/keyboard/clipboard.ts b/src/app/shell/keyboard/clipboard.tsnew file mode 100644index 000000000..91e9bf65d--- /dev/null+++ b/src/app/shell/keyboard/clipboard.ts@@ -0,0 +1,40 @@+import { useEventListener } from '@vueuse/core'++import { isEditing } from '@/app/shell/keyboard/focus'+import { extractImageFilesFromClipboard } from '@open-pencil/vue'++import type { EditorStore } from '@/app/editor/active-store'++export function bindEditorClipboard(store: EditorStore) {+ useEventListener(window, 'copy', (e: ClipboardEvent) => {+ if (isEditing(e)) return+ e.preventDefault()+ if (e.clipboardData) void store.writeCopyData(e.clipboardData)+ })++ useEventListener(window, 'cut', (e: ClipboardEvent) => {+ if (isEditing(e)) return+ e.preventDefault()+ if (e.clipboardData) void store.writeCopyData(e.clipboardData)+ store.deleteSelected()+ })++ useEventListener(window, 'paste', (e: ClipboardEvent) => {+ if (isEditing(e)) return+ e.preventDefault()++ const { cursorCanvasX: ccx, cursorCanvasY: ccy } = store.state+ const cursorPos = ccx != null && ccy != null ? { x: ccx, y: ccy } : undefined++ const imageFiles = extractImageFilesFromClipboard(e)+ if (imageFiles.length) {+ const cx = cursorPos?.x ?? (-store.state.panX + window.innerWidth / 2) / store.state.zoom+ const cy = cursorPos?.y ?? (-store.state.panY + window.innerHeight / 2) / store.state.zoom+ void store.placeImageFiles(imageFiles, cx, cy)+ return+ }++ const html = e.clipboardData?.getData('text/html') ?? ''+ if (html) store.pasteFromHTML(html, cursorPos)+ })+}diff --git a/src/app/shell/keyboard/focus.ts b/src/app/shell/keyboard/focus.tsnew file mode 100644index 000000000..ac7526ffe--- /dev/null+++ b/src/app/shell/keyboard/focus.ts@@ -0,0 +1,7 @@+export function isEditing(e: Event) {+ return e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement+}++export function isInputElement(el: EventTarget | null | undefined): boolean {+ return el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement+}diff --git a/src/app/shell/keyboard/nudging.ts b/src/app/shell/keyboard/nudging.tsnew file mode 100644index 000000000..238649b47--- /dev/null+++ b/src/app/shell/keyboard/nudging.ts@@ -0,0 +1,28 @@+import { useEventListener } from '@vueuse/core'++import { isEditing } from '@/app/shell/keyboard/focus'+import { isReservedModShortcut } from '@/app/shell/keyboard/reserved'++import type { EditorStore } from '@/app/editor/active-store'++const NUDGE_DELTAS: Partial<Record<string, [number, number]>> = {+ ArrowUp: [0, -1],+ ArrowDown: [0, 1],+ ArrowLeft: [-1, 0],+ ArrowRight: [1, 0]+}++export function bindNudgeKeys(store: EditorStore) {+ useEventListener(window, 'keydown', (e: KeyboardEvent) => {+ if (isEditing(e) || store.state.editingTextId) return+ if (isReservedModShortcut(e)) e.preventDefault()+ if (e.metaKey || e.ctrlKey || e.altKey) return++ const delta = NUDGE_DELTAS[e.code]+ if (!delta || store.state.selectedIds.size === 0) return++ const step = e.shiftKey ? 10 : 1+ store.nudgeSelected(delta[0] * step, delta[1] * step)+ e.preventDefault()+ })+}diff --git a/src/app/shell/keyboard/registry.ts b/src/app/shell/keyboard/registry.tsnew file mode 100644index 000000000..864afe4d8--- /dev/null+++ b/src/app/shell/keyboard/registry.ts@@ -0,0 +1,123 @@+import { onScopeDispose } from 'vue'+import { tinykeys } from 'tinykeys'++import { TOOL_SHORTCUTS } from '@/app/editor/session'+import { isEditing } from '@/app/shell/keyboard/focus'+import { bindSpaceHandTool } from '@/app/shell/keyboard/space-tool'++import type { KeyBindingMap } from 'tinykeys'+import type {+ KeyboardShortcutOptions,+ KeyboardShortcutRunOptions+} from '@/app/shell/keyboard/types'++type ShortcutAction = (options: KeyboardShortcutRunOptions) => void++type ShortcutDefinition = {+ id: string+ keys: string | string[]+ run: ShortcutAction+}++function commandShortcut(+ id: string,+ keys: string | string[],+ command: Parameters<KeyboardShortcutOptions['runCommand']>[0]+): ShortcutDefinition {+ return { id, keys, run: ({ runCommand }) => runCommand(command) }+}++function shouldIgnoreShortcut(event: KeyboardEvent, options: KeyboardShortcutOptions) {+ return (+ isEditing(event) ||+ options.inputFocused.value ||+ !!options.store.state.editingTextId ||+ !!options.store.state.scrubInputFocused+ )+}++function bindShortcut(+ bindings: KeyBindingMap,+ keys: string | string[],+ run: (event: KeyboardEvent) => void+) {+ for (const key of Array.isArray(keys) ? keys : [keys]) bindings[key] = run+}++function bindToolShortcuts(bindings: KeyBindingMap, options: KeyboardShortcutRunOptions) {+ for (const [code, tool] of Object.entries(TOOL_SHORTCUTS)) {+ if (!tool) continue+ bindings[code] = (event) => {+ event.preventDefault()+ options.spaceTool.resetToolBeforeSpace()+ options.store.setTool(tool)+ }+ }+}++export function registerKeyboardShortcuts(options: KeyboardShortcutOptions) {+ const spaceTool = bindSpaceHandTool(options.inputFocused, options.store)+ const runOptions = (event: KeyboardEvent): KeyboardShortcutRunOptions => ({+ ...options,+ keyEvent: event,+ spaceTool+ })++ const shortcuts: ShortcutDefinition[] = [+ commandShortcut('create-component', '$mod+Alt+KeyK', 'selection.createComponent'),+ commandShortcut('detach-instance', '$mod+Alt+KeyB', 'selection.detachInstance'),+ commandShortcut('create-component-set', '$mod+Shift+KeyK', 'selection.createComponentSet'),+ commandShortcut('toggle-visibility', '$mod+Shift+KeyH', 'selection.toggleVisibility'),+ commandShortcut('toggle-lock', '$mod+Shift+KeyL', 'selection.toggleLock'),+ { id: 'export-selection-png', keys: '$mod+Shift+KeyE', run: ({ actions }) => actions.exportSelectionPng() },+ { id: 'save-as', keys: '$mod+Shift+KeyS', run: ({ store }) => void store.saveFigFileAs() },+ commandShortcut('ungroup', '$mod+Shift+KeyG', 'selection.ungroup'),+ commandShortcut('redo-shift', '$mod+Shift+KeyZ', 'edit.redo'),+ { id: 'toggle-ui', keys: '$mod+Backslash', run: ({ actions }) => actions.toggleUI() },+ { id: 'toggle-ai', keys: '$mod+KeyJ', run: ({ actions }) => actions.toggleAI() },+ { id: 'close-tab', keys: '$mod+KeyW', run: ({ closeActiveTab }) => closeActiveTab() },+ { id: 'new-tab', keys: ['$mod+KeyN', '$mod+KeyT'], run: ({ createTab }) => createTab() },+ commandShortcut('undo', '$mod+KeyZ', 'edit.undo'),+ commandShortcut('redo', '$mod+KeyY', 'edit.redo'),+ commandShortcut('zoom-100', '$mod+Digit0', 'view.zoom100'),+ commandShortcut('zoom-fit', '$mod+Digit1', 'view.zoomFit'),+ commandShortcut('zoom-selection', '$mod+Digit2', 'view.zoomSelection'),+ commandShortcut('duplicate', '$mod+KeyD', 'selection.duplicate'),+ commandShortcut('select-all', '$mod+KeyA', 'selection.selectAll'),+ { id: 'save', keys: '$mod+KeyS', run: ({ store }) => void store.saveFigFile() },+ { id: 'open-file', keys: '$mod+KeyO', run: ({ openFileDialog }) => openFileDialog() },+ commandShortcut('group', '$mod+KeyG', 'selection.group'),+ commandShortcut('zoom-fit-shift', 'Shift+Digit1', 'view.zoomFit'),+ commandShortcut('zoom-selection-shift', 'Shift+Digit2', 'view.zoomSelection'),+ { id: 'toggle-auto-layout', keys: 'Shift+KeyA', run: ({ actions }) => actions.toggleAutoLayout() },+ commandShortcut('bring-to-front', 'BracketRight', 'selection.bringToFront'),+ commandShortcut('send-to-back', 'BracketLeft', 'selection.sendToBack'),+ { id: 'delete-backspace', keys: 'Backspace', run: ({ actions }) => actions.smartDelete(false) },+ { id: 'delete', keys: 'Delete', run: ({ actions }) => actions.smartDelete(false) },+ { id: 'delete-alt', keys: 'Alt+Delete', run: ({ actions }) => actions.smartDelete(true) },+ { id: 'enter', keys: 'Enter', run: ({ actions }) => actions.confirmOrEnterText() },+ { id: 'escape', keys: 'Escape', run: ({ actions }) => actions.escapeOrDeselect() }+ ]++ const bindings: KeyBindingMap = {}+ bindToolShortcuts(bindings, runOptions(new KeyboardEvent('keydown')))++ for (const shortcut of shortcuts) {+ bindShortcut(bindings, shortcut.keys, (event) => {+ event.preventDefault()+ shortcut.run(runOptions(event))+ })+ }++ const unsubscribe = tinykeys(window, Object.fromEntries(+ Object.entries(bindings).map(([keys, handler]) => [+ keys,+ (event: KeyboardEvent) => {+ if (shouldIgnoreShortcut(event, options)) return+ handler(event)+ }+ ])+ ))++ onScopeDispose(unsubscribe)+}diff --git a/src/app/shell/keyboard/reserved.ts b/src/app/shell/keyboard/reserved.tsnew file mode 100644index 000000000..4b557fda7--- /dev/null+++ b/src/app/shell/keyboard/reserved.ts@@ -0,0 +1,37 @@+const RESERVED_MOD_CODES = new Set([+ 'Backslash',+ 'BracketLeft',+ 'BracketRight',+ 'Digit0',+ 'Digit1',+ 'Digit2',+ 'KeyA',+ 'KeyB',+ 'KeyD',+ 'KeyE',+ 'KeyG',+ 'KeyH',+ 'KeyJ',+ 'KeyK',+ 'KeyL',+ 'KeyN',+ 'KeyO',+ 'KeyS',+ 'KeyT',+ 'KeyW',+ 'KeyY',+ 'KeyZ'+])++export function isReservedModShortcut(e: KeyboardEvent): boolean {+ if (!(e.metaKey || e.ctrlKey)) return false+ if (e.altKey) return e.code === 'KeyB' || e.code === 'KeyK'+ return RESERVED_MOD_CODES.has(e.code)+}++export function preventReservedKeyboardDefaults(e: KeyboardEvent) {+ if (isReservedModShortcut(e)) e.preventDefault()+ if (e.code === 'Backspace' || e.code === 'Delete') e.preventDefault()+ if (e.code === 'BracketLeft' || e.code === 'BracketRight') e.preventDefault()+ if (e.code === 'Space') e.preventDefault()+}diff --git a/src/app/shell/keyboard/space-tool.ts b/src/app/shell/keyboard/space-tool.tsnew file mode 100644index 000000000..efded90f4--- /dev/null+++ b/src/app/shell/keyboard/space-tool.ts@@ -0,0 +1,36 @@+import { useEventListener } from '@vueuse/core'++import type { EditorStore } from '@/app/editor/active-store'+import type { ComputedRef } from 'vue'++export function bindSpaceHandTool(inputFocused: ComputedRef<boolean>, store: EditorStore) {+ let toolBeforeSpace: typeof store.state.activeTool | null = null++ function restoreTool() {+ if (toolBeforeSpace === null) return+ store.setTool(toolBeforeSpace)+ toolBeforeSpace = null+ }++ useEventListener(window, 'keydown', (event: KeyboardEvent) => {+ if (event.code !== 'Space') return+ if (inputFocused.value || store.state.editingTextId) return+ if (event.metaKey || event.ctrlKey || event.altKey) return+ event.preventDefault()+ if (toolBeforeSpace !== null || store.state.activeTool === 'HAND') return+ toolBeforeSpace = store.state.activeTool+ store.setTool('HAND')+ })++ useEventListener(window, 'keyup', (event: KeyboardEvent) => {+ if (event.code === 'Space') restoreTool()+ })++ useEventListener(window, 'blur', restoreTool)++ return {+ resetToolBeforeSpace() {+ toolBeforeSpace = null+ }+ }+}diff --git a/src/app/shell/keyboard/types.ts b/src/app/shell/keyboard/types.tsnew file mode 100644index 000000000..e2252f58e--- /dev/null+++ b/src/app/shell/keyboard/types.ts@@ -0,0 +1,28 @@+import type { EditorStore } from '@/app/editor/active-store'+import type { useEditorCommands } from '@open-pencil/vue'+import type { ComputedRef } from 'vue'++export type KeyboardShortcutActions = {+ smartDelete: (altKey: boolean) => void+ confirmOrEnterText: () => void+ escapeOrDeselect: () => void+ toggleAutoLayout: () => void+ toggleUI: () => void+ toggleAI: () => void+ exportSelectionPng: () => void+}++export type KeyboardShortcutOptions = {+ inputFocused: ComputedRef<boolean>+ store: EditorStore+ runCommand: ReturnType<typeof useEditorCommands>['runCommand']+ actions: KeyboardShortcutActions+ openFileDialog: () => void+ closeActiveTab: () => void+ createTab: () => void+}++export type KeyboardShortcutRunOptions = KeyboardShortcutOptions & {+ keyEvent: KeyboardEvent+ spaceTool: { resetToolBeforeSpace: () => void }+}diff --git a/src/app/shell/keyboard/use.ts b/src/app/shell/keyboard/use.tsnew file mode 100644index 000000000..f5743f95e--- /dev/null+++ b/src/app/shell/keyboard/use.ts@@ -0,0 +1,41 @@+import { useActiveElement } from '@vueuse/core'+import { computed } from 'vue'++import { useAIChat } from '@/app/ai/chat/use'+import { useEditorStore } from '@/app/editor/active-store'+import { createKeyboardActions } from '@/app/shell/keyboard/actions'+import { bindEditorClipboard } from '@/app/shell/keyboard/clipboard'+import { isInputElement } from '@/app/shell/keyboard/focus'+import { bindNudgeKeys } from '@/app/shell/keyboard/nudging'+import { registerKeyboardShortcuts } from '@/app/shell/keyboard/registry'+import { openFileDialog } from '@/app/shell/menu/use'+import { closeTab, createTab, activeTab as activeTabRef } from '@/app/tabs'+import { useEditorCommands, useViewportKind } from '@open-pencil/vue'++export function useKeyboard() {+ const { activeTab } = useAIChat()+ const store = useEditorStore()+ const { isMobile } = useViewportKind()+ const { runCommand } = useEditorCommands()+ const activeElement = useActiveElement()+ const inputFocused = computed(() => isInputElement(activeElement.value))++ const actions = createKeyboardActions({ store, activeTab, isMobile, runCommand })++ bindEditorClipboard(store)+ bindNudgeKeys(store)++ registerKeyboardShortcuts({+ inputFocused,+ store,+ runCommand,+ actions,+ openFileDialog: () => {+ void openFileDialog()+ },+ closeActiveTab: () => {+ if (activeTabRef.value) closeTab(activeTabRef.value.id)+ },+ createTab: () => createTab()+ })+}diff --git a/src/app/shell/layout-storage.ts b/src/app/shell/layout-storage.tsnew file mode 100644index 000000000..f5308442d--- /dev/null+++ b/src/app/shell/layout-storage.ts@@ -0,0 +1,25 @@+import { IS_BROWSER } from '@open-pencil/core/constants'++const EDITOR_LAYOUT_KEY = 'open-pencil:editor-layout'+const DEFAULT_EDITOR_LAYOUT = [18, 64, 18]++export function loadEditorLayout(): number[] {+ if (!IS_BROWSER) return DEFAULT_EDITOR_LAYOUT+ try {+ const raw = window.localStorage.getItem(EDITOR_LAYOUT_KEY)+ if (!raw) return DEFAULT_EDITOR_LAYOUT+ const parsed = JSON.parse(raw)+ return Array.isArray(parsed) &&+ parsed.length === 3 &&+ parsed.every((v) => typeof v === 'number')+ ? parsed+ : DEFAULT_EDITOR_LAYOUT+ } catch {+ return DEFAULT_EDITOR_LAYOUT+ }+}++export function saveEditorLayout(layout: number[]): void {+ if (!IS_BROWSER) return+ window.localStorage.setItem(EDITOR_LAYOUT_KEY, JSON.stringify(layout))+}diff --git a/src/shims/mermaid.ts b/src/app/shell/markdown/index.tssimilarity index 100%rename from src/shims/mermaid.tsrename to src/app/shell/markdown/index.tsdiff --git a/src/composables/use-app-menu.ts b/src/app/shell/menu/app-menu.tssimilarity index 96%rename from src/composables/use-app-menu.tsrename to src/app/shell/menu/app-menu.tsindex d01ea792d..54dc58e0b 100644--- a/src/composables/use-app-menu.ts+++ b/src/app/shell/menu/app-menu.ts@@ -1,7 +1,7 @@import { computed } from 'vue'-import { openFileDialog } from '@/composables/use-menu'-import { useEditorStore } from '@/stores/editor'+import { useEditorStore } from '@/app/editor/active-store'+import { openFileDialog } from '@/app/shell/menu/use'import { useEditorCommands, useI18n } from '@open-pencil/vue'import type { MenuEntry } from '@open-pencil/vue'@@ -34,7 +34,7 @@ export function useAppMenu(mod: string) {label: t.value.new,shortcut: `${mod}N`,action: () => {- void import('@/stores/tabs').then((m) => m.createTab())+ void import('@/app/tabs').then((m) => m.createTab())}},{ label: t.value.open, shortcut: `${mod}O`, action: () => void openFileDialog() },@@ -143,6 +143,14 @@ export function useAppMenu(mod: string) {commandMenuItem('selection.sendToBack', '[')]},+ {+ label: t.value.text,+ items: [+ { label: t.value.bold, shortcut: `${mod}B` },+ { label: t.value.italic, shortcut: `${mod}I` },+ { label: t.value.underline, shortcut: `${mod}U` }+ ]+ },{label: t.value.arrange,items: [@@ -156,14 +164,6 @@ export function useAppMenu(mod: string) {{ label: p.value.alignMiddle, shortcut: '⌥V' },{ label: p.value.alignBottom, shortcut: '⌥S' }]- },- {- label: t.value.text,- items: [- { label: t.value.bold, shortcut: `${mod}B` },- { label: t.value.italic, shortcut: `${mod}I` },- { label: t.value.underline, shortcut: `${mod}U` }- ]}])diff --git a/src/app/shell/menu/document-name.ts b/src/app/shell/menu/document-name.tsnew file mode 100644index 000000000..a18620852--- /dev/null+++ b/src/app/shell/menu/document-name.ts@@ -0,0 +1,27 @@+import { computed } from 'vue'+import { useInlineRename } from '@open-pencil/vue'++import type { EditorStore } from '@/app/editor/active-store'++const DOCUMENT_NAME_ID = 'document-name'++export function useDocumentNameRename(store: EditorStore) {+ const rename = useInlineRename<'document-name'>((_id, name) => {+ store.state.documentName = name+ })+ const editingName = computed(() => rename.editingId.value === DOCUMENT_NAME_ID)++ function setNameInputRef(el: HTMLInputElement | null) {+ if (el) void rename.focusInput(el)+ }++ function startRename() {+ rename.start(DOCUMENT_NAME_ID, store.state.documentName)+ }++ function commitRename(input: HTMLInputElement) {+ rename.commit(DOCUMENT_NAME_ID, input)+ }++ return { rename, editingName, setNameInputRef, startRename, commitRename }+}diff --git a/src/app/shell/menu/entry.ts b/src/app/shell/menu/entry.tsnew file mode 100644index 000000000..d59ebc070--- /dev/null+++ b/src/app/shell/menu/entry.ts@@ -0,0 +1,45 @@+import type { MenuActionNode, MenuEntry } from '@open-pencil/vue'++export function isMenuSeparator(entry: MenuEntry) {+ return 'separator' in entry && entry.separator+}++export function isMenuAction(entry: MenuEntry): entry is MenuActionNode {+ return !isMenuSeparator(entry)+}++export function menuLabel(entry: MenuEntry) {+ return isMenuAction(entry) ? entry.label : ''+}++export function menuShortcut(entry: MenuEntry) {+ return isMenuAction(entry) ? entry.shortcut : undefined+}++export function menuDisabled(entry: MenuEntry) {+ return isMenuAction(entry) ? entry.disabled : undefined+}++export function menuSubItems(entry: MenuEntry) {+ return isMenuAction(entry) ? (entry.sub ?? []) : []+}++export function hasMenuSubItems(entry: MenuEntry) {+ return menuSubItems(entry).length > 0+}++export function isMenuCheckbox(entry: MenuEntry) {+ return isMenuAction(entry) && Boolean(entry.onCheckedChange)+}++export function menuChecked(entry: MenuEntry) {+ return isMenuAction(entry) ? entry.checked : undefined+}++export function updateMenuChecked(entry: MenuEntry, checked: boolean) {+ if (isMenuAction(entry)) entry.onCheckedChange?.(checked)+}++export function runMenuAction(entry: MenuEntry) {+ if (isMenuAction(entry)) entry.action?.()+}diff --git a/src/composables/use-menu.ts b/src/app/shell/menu/files.tssimilarity index 57%rename from src/composables/use-menu.tsrename to src/app/shell/menu/files.tsindex 17b0c749f..a37f0ec3e 100644--- a/src/composables/use-menu.ts+++ b/src/app/shell/menu/files.ts@@ -1,11 +1,10 @@import { useFileDialog } from '@vueuse/core'-import { onUnmounted } from 'vue'+import { openFileInNewTab } from '@/app/tabs'import { IS_BROWSER, IS_TAURI } from '@/constants'-import { useEditorStore } from '@/stores/editor'-import { openFileInNewTab, createTab, closeTab, activeTab } from '@/stores/tabs'const fileDialog = useFileDialog({ accept: '.fig,.pen', multiple: false, reset: true })+fileDialog.onChange((files) => {const file = files?.[0]if (file) void openFileInNewTab(file)@@ -71,46 +70,3 @@ export async function openFileDialog() {export async function importFileDialog() {await openFileDialog()}--const store = useEditorStore()--const MENU_ACTIONS: Partial<Record<string, () => void>> = {- new: () => createTab(),- open: () => void openFileDialog(),- import: () => void importFileDialog(),- close: () => {- if (activeTab.value) closeTab(activeTab.value.id)- },- save: () => void store.saveFigFile(),- 'save-as': () => void store.saveFigFileAs(),- duplicate: () => store.duplicateSelected(),- delete: () => store.deleteSelected(),- group: () => store.groupSelected(),- ungroup: () => store.ungroupSelected(),- 'create-component': () => store.createComponentFromSelection(),- 'create-component-set': () => store.createComponentSetFromComponents(),- 'detach-instance': () => store.detachInstance(),- 'zoom-100': () => store.zoomTo100(),- 'zoom-fit': () => store.zoomToFit(),- 'zoom-selection': () => store.zoomToSelection(),- export: () => {- if (store.state.selectedIds.size > 0) void store.exportSelection(1, 'png')- }-}--export function useMenu() {- if (!IS_TAURI) return-- let unlisten: (() => void) | undefined-- void import('@tauri-apps/api/event').then(({ listen }) => {- void listen<string>('menu-event', (event) => {- const action = MENU_ACTIONS[event.payload]- if (action) action()- }).then((fn) => {- unlisten = fn- })- })-- onUnmounted(() => unlisten?.())-}diff --git a/src/app/shell/menu/use.ts b/src/app/shell/menu/use.tsnew file mode 100644index 000000000..7b399d4de--- /dev/null+++ b/src/app/shell/menu/use.ts@@ -0,0 +1,52 @@+import { tryOnScopeDispose } from '@vueuse/core'++import { useEditorStore } from '@/app/editor/active-store'+import { importFileDialog, openFileDialog } from '@/app/shell/menu/files'+import { createTab, closeTab, activeTab } from '@/app/tabs'+import { IS_TAURI } from '@/constants'++const store = useEditorStore()++const MENU_ACTIONS: Partial<Record<string, () => void>> = {+ new: () => createTab(),+ open: () => void openFileDialog(),+ import: () => void importFileDialog(),+ close: () => {+ if (activeTab.value) closeTab(activeTab.value.id)+ },+ save: () => void store.saveFigFile(),+ 'save-as': () => void store.saveFigFileAs(),+ duplicate: () => store.duplicateSelected(),+ delete: () => store.deleteSelected(),+ group: () => store.groupSelected(),+ ungroup: () => store.ungroupSelected(),+ 'create-component': () => store.createComponentFromSelection(),+ 'create-component-set': () => store.createComponentSetFromComponents(),+ 'detach-instance': () => store.detachInstance(),+ 'zoom-100': () => store.zoomTo100(),+ 'zoom-fit': () => store.zoomToFit(),+ 'zoom-selection': () => store.zoomToSelection(),+ export: () => {+ if (store.state.selectedIds.size > 0) void store.exportSelection(1, 'png')+ }+}++export { importFileDialog, openFileDialog }+export { openFileFromPath } from '@/app/shell/menu/files'++export function useMenu() {+ if (!IS_TAURI) return++ let unlisten: (() => void) | undefined++ void import('@tauri-apps/api/event').then(({ listen }) => {+ void listen<string>('menu-event', (event) => {+ const action = MENU_ACTIONS[event.payload]+ if (action) action()+ }).then((fn) => {+ unlisten = fn+ })+ })++ tryOnScopeDispose(() => unlisten?.())+}diff --git a/src/app/shell/toast/action.ts b/src/app/shell/toast/action.tsnew file mode 100644index 000000000..37782d01c--- /dev/null+++ b/src/app/shell/toast/action.ts@@ -0,0 +1,25 @@+import { useTimeoutFn } from '@vueuse/core'++import { useEditorStore } from '@/app/editor/active-store'+import { ACTION_TOAST_DURATION } from '@/constants'++export function useActionToast() {+ const store = useEditorStore()+ const { start: scheduleHideToast, stop: cancelHideToast } = useTimeoutFn(+ () => {+ store.state.actionToast = null+ },+ ACTION_TOAST_DURATION,+ { immediate: false }+ )++ function showActionToast(label: string) {+ store.state.actionToast = label+ cancelHideToast()+ scheduleHideToast()+ }++ return {+ showActionToast+ }+}diff --git a/src/utils/toast.ts b/src/app/shell/ui.tssimilarity index 77%rename from src/utils/toast.tsrename to src/app/shell/ui.tsindex b4557a76f..0a8357c40 100644--- a/src/utils/toast.ts+++ b/src/app/shell/ui.ts@@ -1,5 +1,6 @@import { useEventListener } from '@vueuse/core'import { ref } from 'vue'+import { IS_TAURI } from '@open-pencil/core/constants'export type ToastVariant = 'default' | 'warning' | 'error'@@ -79,3 +80,26 @@ export const toast = {TOAST_DURATION,ERROR_TOAST_DURATION}++export async function openExternalLink(url: string) {+ if (IS_TAURI) {+ const { openUrl } = await import('@tauri-apps/plugin-opener')+ await openUrl(url)+ } else {+ window.open(url, '_blank')+ }+}+export function initials(name: string): string {+ return (+ name+ .split(' ')+ .map((w) => w[0])+ .join('')+ .toUpperCase()+ .slice(0, 2) || '?'+ )+}+export function decodeTauriStderr(raw: Uint8Array | number[] | string): string {+ if (typeof raw === 'string') return raw+ return new TextDecoder().decode(raw instanceof Uint8Array ? raw : new Uint8Array(raw))+}diff --git a/src/stores/tabs.ts b/src/app/tabs/index.tssimilarity index 90%rename from src/stores/tabs.tsrename to src/app/tabs/index.tsindex 0afe51bf1..60ca3c7a0 100644--- a/src/stores/tabs.ts+++ b/src/app/tabs/index.ts@@ -1,11 +1,12 @@import { shallowRef, computed, triggerRef } from 'vue'-import { BUILTIN_IO_FORMATS, IORegistry, readFigFile } from '@open-pencil/core'+import { setActiveEditorStore } from '@/app/editor/active-store'+import { createEditorStore } from '@/app/editor/session'+import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'+import { readFigFile } from '@open-pencil/core/io/formats/fig'-import { createEditorStore, setActiveEditorStore } from './editor'--import type { EditorStore } from './editor'-import type { SceneGraph } from '@open-pencil/core'+import type { EditorStore } from '@/app/editor/session'+import type { SceneGraph } from '@open-pencil/core/scene-graph'export interface Tab {id: stringdiff --git a/src/automation/server.ts b/src/automation/server.tsdeleted file mode 100644index 547ecb168..000000000--- a/src/automation/server.ts+++ /dev/null@@ -1,289 +0,0 @@-import { makeFigmaFromStore } from '@/automation/figma-factory'-import { openFileFromPath } from '@/composables/use-menu'-import { createTab, openFileInNewTab } from '@/stores/tabs'-/**- * Browser-side automation handler.- *- * Connects to the bridge via WebSocket, receives RPC requests,- * executes them against the live EditorStore, and sends results back.- */-import {- ALL_TOOLS,- AUTOMATION_WS_PORT,- IS_TAURI,- executeRpcCommand,- renderTreeNode,- computeAllLayouts,- selectionToJSX,- sceneNodeToJSX,- nodeToXPath,- randomHex-} from '@open-pencil/core'--import type { EditorStore } from '@/stores/editor'-import type { RasterExportFormat } from '@open-pencil/core'--export function connectAutomation(getStore: () => EditorStore, authToken: string | null = null) {- const token = authToken ?? randomHex(32)- let ws: WebSocket | null = null- let reconnectTimer: ReturnType<typeof setTimeout> | undefined-- function makeFigma() {- return makeFigmaFromStore(getStore())- }-- async function handleEval(store: EditorStore, args: unknown): Promise<unknown> {- const code = (args as { code?: string }).code- if (!code) throw new Error('Missing "code" in args')- const figma = makeFigma()- const AsyncFunction = Object.getPrototypeOf(async function () {- /* noop */- }).constructor- const wrappedCode = code.trim().startsWith('return')- ? code- : `return (async () => { ${code} })()`- const fn = new AsyncFunction('figma', wrappedCode)- const result = await fn(figma)- store.requestRender()- return { ok: true, result: result ?? null }- }-- async function handleToolRender(- store: EditorStore,- toolArgs: Record<string, unknown>- ): Promise<unknown> {- const tree = toolArgs.tree as Parameters<typeof renderTreeNode>[1]- const result = await renderTreeNode(store.graph, tree, {- parentId: (toolArgs.parent_id as string | undefined) ?? store.state.currentPageId,- x: toolArgs.x as number | undefined,- y: toolArgs.y as number | undefined- })- computeAllLayouts(store.graph, store.state.currentPageId)- store.requestRender()- store.flashNodes([result.id])- return {- ok: true,- result: { id: result.id, name: result.name, type: result.type, children: result.childIds }- }- }-- async function handleTool(store: EditorStore, args: unknown): Promise<unknown> {- const toolName = (args as { name?: string }).name- const toolArgs = (args as { args?: Record<string, unknown> }).args ?? {}- if (!toolName) throw new Error('Missing "name" in args')-- if (toolName === 'render' && toolArgs.tree) {- return handleToolRender(store, toolArgs)- }-- const def = ALL_TOOLS.find((t) => t.name === toolName)- if (!def) throw new Error(`Unknown tool: ${toolName}`)- const figma = makeFigma()- const result = await def.execute(figma, toolArgs)-- if (figma.currentPageId !== store.state.currentPageId) {- void store.switchPage(figma.currentPageId)- }-- if (def.mutates) {- computeAllLayouts(store.graph, store.state.currentPageId)- store.requestRender()- store.flashNodes(extractNodeIds(result))- }- return { ok: true, result }- }-- async function handleExport(store: EditorStore, args: unknown): Promise<unknown> {- const exportArgs = args as { nodeIds?: string[]; scale?: number; format?: string } | undefined- const nodeIds = exportArgs?.nodeIds ?? [...store.state.selectedIds]- if (nodeIds.length === 0) throw new Error('No nodes to export')- const data = await store.renderExportImage(- nodeIds,- exportArgs?.scale ?? 1,- (exportArgs?.format ?? 'PNG') as RasterExportFormat- )- if (!data) throw new Error('Export failed')- let binary = ''- for (const byte of data) binary += String.fromCharCode(byte)- const base64 = btoa(binary)- return {- ok: true,- result: { base64, mimeType: `image/${(exportArgs?.format ?? 'png').toLowerCase()}` }- }- }-- async function handleExportJsx(store: EditorStore, args: unknown): Promise<unknown> {- const jsxArgs = args as { nodeIds?: string[]; style?: string } | undefined- const style = (jsxArgs?.style ?? 'openpencil') as 'openpencil' | 'tailwind'- const currentPage = store.graph.getNode(store.state.currentPageId)- const nodeIds = jsxArgs?.nodeIds ?? currentPage?.childIds ?? []- const jsx =- nodeIds.length === 1- ? sceneNodeToJSX(nodeIds[0], store.graph, style)- : selectionToJSX(nodeIds, store.graph, style)- return { ok: true, result: { jsx } }- }-- async function handleSaveFile(store: EditorStore): Promise<unknown> {- await store.saveFigFile()- return { ok: true }- }-- async function handleNewDocument(_store: EditorStore, args: unknown): Promise<unknown> {- const path = (args as { path?: string }).path- const tab = createTab()- if (path) {- tab.store.setPlannedFilePath(path)- if (IS_TAURI) {- const { mkdir } = await import('@tauri-apps/plugin-fs')- const dir = path.replace(/[\\/][^\\/]+$/, '')- await mkdir(dir, { recursive: true })- }- await tab.store.saveFigFile()- tab.store.startWatchingCurrentFile()- }- return { ok: true }- }-- async function handleOpenFile(_store: EditorStore, args: unknown): Promise<unknown> {- const path = (args as { path?: string }).path- if (!path) throw new Error('Missing "path" in args')- if (IS_TAURI) {- await openFileFromPath(path)- } else {- const response = await fetch(path)- if (!response.ok) throw new Error(`Failed to fetch file: ${response.statusText}`)- const name = path.split(/[\\/]/).pop() ?? 'file.fig'- const file = new File([await response.blob()], name)- await openFileInNewTab(file, undefined, path)- }- return { ok: true }- }-- async function handleSelection(store: EditorStore): Promise<unknown> {- const ids = [...store.state.selectedIds]- const nodes = ids- .map((id) => store.graph.getNode(id))- .filter((n): n is NonNullable<typeof n> => n !== undefined)- .map((n) => ({- id: n.id,- name: n.name,- type: n.type,- width: Math.round(n.width),- height: Math.round(n.height),- xpath: nodeToXPath(store.graph, n.id)- }))- return { ok: true, result: nodes }- }-- const commandHandlers: Partial<- Record<string, (store: EditorStore, args: unknown) => Promise<unknown>>- > = {- eval: handleEval,- tool: handleTool,- export: handleExport,- export_jsx: handleExportJsx,- selection: handleSelection,-- save_file: handleSaveFile,- new_document: handleNewDocument,- open_file: handleOpenFile- }-- async function handleRequest(_id: string, command: string, args: unknown): Promise<unknown> {- const store = getStore()- const handler = commandHandlers[command]- if (handler) return handler(store, args)- const result = executeRpcCommand(store.graph, command, args ?? {})- return { ok: true, result }- }-- function connect() {- try {- ws = new WebSocket(`ws://127.0.0.1:${AUTOMATION_WS_PORT}`)- } catch (e) {- console.error(- '[Automation] WebSocket constructor failed:',- e instanceof Error ? e.message : e- )- scheduleReconnect()- return- }-- ws.onopen = () => {- console.debug('[Automation] WebSocket connected to MCP server')- ws?.send(JSON.stringify({ type: 'register', token }))- }-- ws.onmessage = async (event) => {- try {- const msg = JSON.parse(event.data) as {- type: string- id: string- command: string- args?: unknown- }- if (msg.type !== 'request' || !msg.id) return- try {- const result = await handleRequest(msg.id, msg.command, msg.args)- ws?.send(JSON.stringify({ type: 'response', id: msg.id, ...(result as object) }))- } catch (e) {- ws?.send(- JSON.stringify({- type: 'response',- id: msg.id,- ok: false,- error: e instanceof Error ? e.message : String(e)- })- )- }- } catch (e) {- console.warn('Failed to parse WebSocket message:', e)- }- }-- ws.onclose = (event) => {- console.error('[Automation] WebSocket closed:', `code=${event.code} reason=${event.reason}`)- ws = null- scheduleReconnect()- }-- ws.onerror = (event) => {- console.error('[Automation] WebSocket error:', event)- ws?.close()- }- }-- function scheduleReconnect() {- clearTimeout(reconnectTimer)- reconnectTimer = setTimeout(connect, 2000)- }-- function disconnect() {- clearTimeout(reconnectTimer)- ws?.close()- ws = null- }-- connect()- return { disconnect, token }-}--function extractNodeIds(result: unknown): string[] {- if (!result || typeof result !== 'object') return []- const obj = result as Record<string, unknown>- if (typeof obj.deleted === 'string') return []- const ids: string[] = []- if (typeof obj.id === 'string') ids.push(obj.id)- if (Array.isArray(obj.results)) {- for (const item of obj.results) {- if (- item &&- typeof item === 'object' &&- typeof (item as Record<string, unknown>).id === 'string'- )- ids.push((item as Record<string, unknown>).id as string)- }- }- return ids-}diff --git a/src/components/AppMenu.vue b/src/components/AppMenu.vueindex 2f6e5d621..98d4e4f80 100644--- a/src/components/AppMenu.vue+++ b/src/components/AppMenu.vue@@ -16,55 +16,34 @@ import {import IconChevronRight from '~icons/lucide/chevron-right'-import { computed } from 'vue'--import { useI18n, useInlineRename } from '@open-pencil/vue'+import { useI18n } from '@open-pencil/vue'import { useMenuUI } from '@/components/ui/menu'import { IS_TAURI } from '@/constants'-import { useAppMenu } from '@/composables/use-app-menu'-import { useEditorStore } from '@/stores/editor'+import { useAppMenu } from '@/app/shell/menu/app-menu'+import { useDocumentNameRename } from '@/app/shell/menu/document-name'+import {+ hasMenuSubItems,+ isMenuCheckbox,+ isMenuSeparator,+ menuChecked,+ menuDisabled,+ menuLabel,+ menuShortcut,+ menuSubItems,+ runMenuAction,+ updateMenuChecked+} from '@/app/shell/menu/entry'+import { useEditorStore } from '@/app/editor/active-store'const store = useEditorStore()-const DOCUMENT_NAME_ID = 'document-name'-const rename = useInlineRename<'document-name'>((_id, name) => {- store.state.documentName = name-})-const editingName = computed(() => rename.editingId.value === DOCUMENT_NAME_ID)--function setNameInputRef(el: HTMLInputElement | null) {- if (el) void rename.focusInput(el)-}--function startRename() {- rename.start(DOCUMENT_NAME_ID, store.state.documentName)-}--function commitRename(input: HTMLInputElement) {- rename.commit(DOCUMENT_NAME_ID, input)-}+const { rename, editingName, setNameInputRef, startRename, commitRename } =+ useDocumentNameRename(store)const isMac = navigator.platform.includes('Mac')const mod = isMac ? '⌘' : 'Ctrl+'const { menu: t } = useI18n()-interface MenuAction {- separator?: false- label: string- shortcut?: string- action?: () => void- disabled?: boolean- checked?: boolean- onCheckedChange?: (checked: boolean) => void- sub?: MenuEntry[]-}--interface MenuSeparator {- separator: true-}--type MenuEntry = MenuAction | MenuSeparator-const { topMenus } = useAppMenu(mod)const menuCls = useMenuUI()const mainMenuCls = useMenuUI({ content: 'min-w-52' })@@ -115,32 +94,23 @@ const subMenuCls = useMenuUI({ content: 'min-w-44' })<MenubarPortal><MenubarContent :side-offset="4" align="start" :class="mainMenuCls.content"><template v-for="(item, i) in menu.items" :key="i">- <MenubarSeparator- v-if="'separator' in item && item.separator"- :class="menuCls.separator"- />- <MenubarSub v-else-if="'sub' in item && item.sub">+ <MenubarSeparator v-if="isMenuSeparator(item)" :class="menuCls.separator" />+ <MenubarSub v-else-if="hasMenuSubItems(item)"><MenubarSubTrigger :class="menuCls.item">- <span class="flex-1">{{ 'label' in item ? item.label : '' }}</span>+ <span class="flex-1">{{ menuLabel(item) }}</span><IconChevronRight class="size-3 text-muted" /></MenubarSubTrigger><MenubarPortal><MenubarSubContent :side-offset="4" :class="subMenuCls.content">- <template- v-for="(sub, j) in 'sub' in item && item.sub ? item.sub : []"- :key="j"- >- <MenubarSeparator- v-if="'separator' in sub && sub.separator"- :class="menuCls.separator"- />+ <template v-for="(sub, j) in menuSubItems(item)" :key="j">+ <MenubarSeparator v-if="isMenuSeparator(sub)" :class="menuCls.separator" /><MenubarCheckboxItem- v-else-if="'onCheckedChange' in sub && sub.onCheckedChange"- :model-value="'checked' in sub ? sub.checked : undefined"+ v-else-if="isMenuCheckbox(sub)"+ :model-value="menuChecked(sub)":class="menuCls.item"- @update:model-value="sub.onCheckedChange?.($event as boolean)"+ @update:model-value="updateMenuChecked(sub, $event as boolean)">- <span class="flex-1">{{ 'label' in sub ? sub.label : '' }}</span>+ <span class="flex-1">{{ menuLabel(sub) }}</span><MenubarItemIndicator class="text-surface"><icon-lucide-check class="size-3.5" /></MenubarItemIndicator>@@ -148,27 +118,25 @@ const subMenuCls = useMenuUI({ content: 'min-w-44' })<MenubarItemv-else:class="menuCls.item"- :disabled="'disabled' in sub ? sub.disabled : undefined"- @select="'action' in sub ? sub.action?.() : undefined"+ :disabled="menuDisabled(sub)"+ @select="runMenuAction(sub)">- <span class="flex-1">{{ 'label' in sub ? sub.label : '' }}</span>- <span- v-if="'shortcut' in sub && sub.shortcut"- class="text-[11px] text-muted"- >{{ sub.shortcut }}</span- >+ <span class="flex-1">{{ menuLabel(sub) }}</span>+ <span v-if="menuShortcut(sub)" class="text-[11px] text-muted">{{+ menuShortcut(sub)+ }}</span></MenubarItem></template></MenubarSubContent></MenubarPortal></MenubarSub><MenubarCheckboxItem- v-else-if="'onCheckedChange' in item && item.onCheckedChange"- :model-value="'checked' in item ? item.checked : undefined"+ v-else-if="isMenuCheckbox(item)"+ :model-value="menuChecked(item)":class="menuCls.item"- @update:model-value="item.onCheckedChange?.($event as boolean)"+ @update:model-value="updateMenuChecked(item, $event as boolean)">- <span class="flex-1">{{ 'label' in item ? item.label : '' }}</span>+ <span class="flex-1">{{ menuLabel(item) }}</span><MenubarItemIndicator class="text-surface"><icon-lucide-check class="size-3.5" /></MenubarItemIndicator>@@ -176,12 +144,12 @@ const subMenuCls = useMenuUI({ content: 'min-w-44' })<MenubarItemv-else:class="menuCls.item"- :disabled="'disabled' in item ? item.disabled : undefined"- @select="'action' in item ? item.action?.() : undefined"+ :disabled="menuDisabled(item)"+ @select="runMenuAction(item)">- <span class="flex-1">{{ 'label' in item ? item.label : '' }}</span>- <span v-if="'shortcut' in item && item.shortcut" class="text-[11px] text-muted">{{- item.shortcut+ <span class="flex-1">{{ menuLabel(item) }}</span>+ <span v-if="menuShortcut(item)" class="text-[11px] text-muted">{{+ menuShortcut(item)}}</span></MenubarItem></template>diff --git a/src/components/AppToast.vue b/src/components/AppToast.vueindex 7c0c403db..7dbd6a745 100644--- a/src/components/AppToast.vue+++ b/src/components/AppToast.vue@@ -4,7 +4,7 @@ import { ToastProvider, ToastRoot, ToastDescription, ToastViewport, ToastClose }import { useClipboard } from '@vueuse/core'import Tip from '@/components/ui/Tip.vue'-import { toast } from '@/utils/toast'+import { toast } from '@/app/shell/ui'import { useToastUI } from '@/components/ui/toast'const { copy, copied } = useClipboard({ copiedDuring: 1500 })diff --git a/src/components/CanvasMenu.vue b/src/components/CanvasMenu.vueindex f8a3e4e43..869d47ae3 100644--- a/src/components/CanvasMenu.vue+++ b/src/components/CanvasMenu.vue@@ -8,71 +8,22 @@ import {ContextMenuSubContent,ContextMenuPortal} from 'reka-ui'-import { useClipboard } from '@vueuse/core'-import { nodeToXPath } from '@open-pencil/core'import { useEditorCommands, useI18n, useMenuModel, useSelectionState } from '@open-pencil/vue'-import { toast } from '@/utils/toast'-import { useEditorStore } from '@/stores/editor'+import { useEditorStore } from '@/app/editor/active-store'+import { createCanvasMenuActions } from '@/app/editor/canvas/menu-actions'+import { canvasMenuItemClass, canvasMenuShortcutClass } from '@/app/editor/canvas/menu-model'import { menu, useMenuUI } from '@/components/ui/menu'const store = useEditorStore()-const { copy } = useClipboard()const { editor, selectedIds, hasSelection } = useSelectionState()const { getCommand } = useEditorCommands()const { canvasMenu } = useMenuModel()const { menu: t } = useI18n()-function ids() {- return [...selectedIds.value]-}--function execCommand(cmd: 'copy' | 'cut' | 'paste') {- try {- if (window.document.execCommand(cmd)) return- } catch (error) {- console.warn(`Clipboard command ${cmd} failed`, error)- }-- toast.error('Clipboard access is blocked in this browser context')-}--async function clipboardWrite(text: string | null, label: string) {- if (!text) return- copy(text)- toast.info(`Copied as ${label}`)-}--function copyNodeId() {- const nodeIds = ids()- if (nodeIds.length === 0) return- copy(nodeIds.join(', '))- toast.info(`Copied node ID${nodeIds.length > 1 ? 's' : ''}`)-}--function copyXPath() {- const nodeIds = ids()- if (nodeIds.length === 0) return- const xpaths = nodeIds- .map((id) => nodeToXPath(store.graph, id))- .filter((x): x is string => x !== null)- if (xpaths.length === 0) return- copy(xpaths.join('\n'))- toast.info(`Copied XPath${xpaths.length > 1 ? 's' : ''}`)-}--async function copyAsPNG() {- if (!navigator.clipboard?.write || typeof ClipboardItem === 'undefined') {- toast.error('PNG clipboard export is not available in this browser')- return- }- const data = await store.renderExportImage([...selectedIds.value], 2, 'PNG')- if (!data) return- const blob = new Blob([data], { type: 'image/png' })- await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })])- toast.info('Copied as PNG')-}+const { ids, execCommand, clipboardWrite, copyNodeId, copyXPath, copyAsPNG } =+ createCanvasMenuActions(store, selectedIds)const menuCls = useMenuUI({content: 'min-w-56 shadow-[0_8px_30px_rgb(0_0_0/0.4)] animate-in fade-in zoom-in-95',@@ -86,23 +37,47 @@ const cls = {component: componentMenu.item(),sep: menuCls.separator}++const staticContextCommandIds = new Set(['selection.duplicate', 'selection.delete'])++const contextCommandTestIds: Record<string, string> = {+ 'selection.duplicate': 'context-duplicate',+ 'selection.delete': 'context-delete',+ 'selection.bringToFront': 'context-bring-to-front',+ 'selection.sendToBack': 'context-send-to-back',+ 'selection.group': 'context-group',+ 'selection.createComponent': 'context-create-component',+ 'selection.toggleVisibility': 'context-toggle-visibility',+ 'selection.toggleLock': 'context-toggle-lock'+}</script><template><ContextMenuContent :class="cls.menu" :side-offset="2" align="start">- <ContextMenuItem :class="cls.item" :disabled="!hasSelection" @select="execCommand('copy')">+ <ContextMenuItem+ data-test-id="context-copy"+ :class="cls.item"+ :disabled="!hasSelection"+ @select="execCommand('copy')"+ ><span>{{ t.copy }}</span><span class="text-[11px] text-muted">⌘C</span></ContextMenuItem>- <ContextMenuItem :class="cls.item" :disabled="!hasSelection" @select="execCommand('cut')">+ <ContextMenuItem+ data-test-id="context-cut"+ :class="cls.item"+ :disabled="!hasSelection"+ @select="execCommand('cut')"+ ><span>{{ t.cut }}</span><span class="text-[11px] text-muted">⌘X</span></ContextMenuItem>- <ContextMenuItem :class="cls.item" @select="execCommand('paste')">+ <ContextMenuItem data-test-id="context-paste" :class="cls.item" @select="execCommand('paste')"><span>{{ t.pasteHere }}</span><span class="text-[11px] text-muted">⌘V</span></ContextMenuItem><ContextMenuItem+ data-test-id="context-duplicate":class="cls.item":disabled="!hasSelection"@select="getCommand('selection.duplicate').run()"@@ -110,6 +85,7 @@ const cls = {<span>Duplicate</span><span class="text-[11px] text-muted">⌘D</span></ContextMenuItem><ContextMenuItem+ data-test-id="context-delete":class="cls.item":disabled="!hasSelection"@select="getCommand('selection.delete').run()"@@ -118,7 +94,8 @@ const cls = {</ContextMenuItem><template v-for="(item, i) in canvasMenu" :key="`menu-${i}`">- <ContextMenuSeparator v-if="item.separator" :class="cls.sep" />+ <template v-if="!item.separator && item.id && staticContextCommandIds.has(item.id)" />+ <ContextMenuSeparator v-else-if="item.separator" :class="cls.sep" /><ContextMenuSub v-else-if="item.sub"><ContextMenuSubTrigger :class="cls.item"><span>{{ item.label }}</span@@ -143,11 +120,8 @@ const cls = {</ContextMenuSub><ContextMenuItemv-else- :class="- item.label.includes('component') || item.label.includes('instance')- ? cls.component- : cls.item- "+ :data-test-id="item.id ? contextCommandTestIds[item.id] : undefined"+ :class="canvasMenuItemClass(item.label, cls)":disabled="item.disabled"@select="item.action?.()">@@ -155,11 +129,7 @@ const cls = {<spanv-if="item.shortcut"class="text-[11px]"- :class="- item.label.includes('component') || item.label.includes('instance')- ? 'text-component/60'- : 'text-muted'- "+ :class="canvasMenuShortcutClass(item.label)">{{ item.shortcut }}</span></ContextMenuItem>@@ -169,7 +139,7 @@ const cls = {<ContextMenuSeparator :class="cls.sep" /><ContextMenuSub>- <ContextMenuSubTrigger :class="cls.item">+ <ContextMenuSubTrigger data-test-id="context-copy-paste-as" :class="cls.item"><span>{{ t.copyPasteAs }}</span><span class="text-sm text-muted">›</span></ContextMenuSubTrigger>@@ -181,6 +151,7 @@ const cls = {>{{ t.copyAsText }}</ContextMenuItem><ContextMenuItem+ data-test-id="context-copy-as-svg":class="cls.item"@select="clipboardWrite(editor.copySelectionAsSVG(ids()), 'SVG')">{{ t.copyAsSVG }}</ContextMenuItem@@ -190,6 +161,7 @@ const cls = {><span class="text-[11px] text-muted">⇧⌘C</span></ContextMenuItem><ContextMenuItem+ data-test-id="context-copy-as-jsx":class="cls.item"@select="clipboardWrite(editor.copySelectionAsJSX(ids()), 'JSX')">{{ t.copyAsJSX }}</ContextMenuItemdiff --git a/src/components/ChatPanel.vue b/src/components/ChatPanel.vueindex e21cfb370..d17d821ef 100644--- a/src/components/ChatPanel.vue+++ b/src/components/ChatPanel.vue@@ -1,17 +1,18 @@<script setup lang="ts">import { ScrollAreaRoot, ScrollAreaScrollbar, ScrollAreaThumb, ScrollAreaViewport } from 'reka-ui'+import { refAutoReset } from '@vueuse/core'import { computed, markRaw, nextTick, ref, watch } from 'vue'-import { getAcpDebugText, clearAcpDebugLog, hasAcpDebugEntries } from '@/ai/acp-transport'-import { copyChatLog } from '@/ai/chat-debug'-import { clearToolLogEntries, didHitStepLimit } from '@/ai/tools'-import { activeTab } from '@/stores/tabs'-import ACPPermissionDialog from '@/components/chat/ACPPermissionDialog.vue'+import { getAcpDebugText, clearAcpDebugLog, hasAcpDebugEntries } from '@/app/ai/acp/transport'+import { copyChatLog } from '@/app/ai/debug'+import { clearToolLogEntries, didHitStepLimit } from '@/app/ai/tools'+import { activeTab } from '@/app/tabs'+import AcpPermissionDialog from '@/components/chat/AcpPermissionDialog.vue'import ChatInput from '@/components/chat/ChatInput.vue'import ChatMessage from '@/components/chat/ChatMessage.vue'import ProviderSetup from '@/components/chat/ProviderSetup.vue'-import { useAIChat } from '@/composables/use-chat'-import { toast } from '@/utils/toast'+import { useAIChat } from '@/app/ai/chat/use'+import { toast } from '@/app/shell/ui'import { useI18n } from '@open-pencil/vue'import type { Chat } from '@ai-sdk/vue'@@ -28,8 +29,8 @@ ensureChat().then((c) => {if (c) chat.value = markRaw(c)})const messagesEnd = ref<HTMLDivElement>()-const debugCopied = ref(false)-const acpLogCopied = ref(false)+const debugCopied = refAutoReset(false, 1500)+const acpLogCopied = refAutoReset(false, 1500)const messages = computed(() => chat.value?.messages ?? [])const status = computed(() => chat.value?.status ?? 'ready')@@ -62,6 +63,12 @@ function scrollToBottom() {}watch(messages, scrollToBottom, { deep: true })+watch(+ () => chat.value?.error,+ (error) => {+ if (error) toast.error(error.message)+ }+)watch(() => activeTab.value?.id,async () => {@@ -93,9 +100,6 @@ function handleStop() {async function handleCopyDebug() {await copyChatLog(messages.value)debugCopied.value = true- setTimeout(() => {- debugCopied.value = false- }, 1500)}async function handleCopyAcpLog() {@@ -103,9 +107,6 @@ async function handleCopyAcpLog() {if (!text) returnawait navigator.clipboard.writeText(text)acpLogCopied.value = true- setTimeout(() => {- acpLogCopied.value = false- }, 1500)}function handleClearChat() {@@ -213,7 +214,7 @@ function handleClearChat() {<ChatInput :status="status" @submit="handleSubmit" @stop="handleStop" />- <ACPPermissionDialog />+ <AcpPermissionDialog /></template></div></template>diff --git a/src/components/CodePanel.vue b/src/components/CodePanel.vueindex 1e3e332ba..d35717e76 100644--- a/src/components/CodePanel.vue+++ b/src/components/CodePanel.vue@@ -5,12 +5,12 @@ import { ScrollAreaRoot, ScrollAreaScrollbar, ScrollAreaThumb, ScrollAreaViewporimport { useClipboard } from '@vueuse/core'import { computed, ref } from 'vue'-import { selectionToJSX, JSX_REFERENCE } from '@open-pencil/core'+import { JSX_REFERENCE, selectionToJSX } from '@open-pencil/core/design-jsx'import { useI18n, useSceneComputed } from '@open-pencil/vue'-import { useEditorStore } from '@/stores/editor'+import { useEditorStore } from '@/app/editor/active-store'-import type { JSXFormat } from '@open-pencil/core'+import type { JSXFormat } from '@open-pencil/core/design-jsx'const store = useEditorStore()const { copy, copied } = useClipboard({ copiedDuring: 2000 })diff --git a/src/components/CollabPanel.vue b/src/components/CollabPanel.vuedeleted file mode 100644index 5a9418773..000000000--- a/src/components/CollabPanel.vue+++ /dev/null@@ -1,266 +0,0 @@-<script setup lang="ts">-import { useClipboard } from '@vueuse/core'-import { computed, ref, watch } from 'vue'-import { useRoute, useRouter } from 'vue-router'-import { PopoverRoot, PopoverTrigger, PopoverPortal, PopoverContent } from 'reka-ui'--import { colorToCSS } from '@open-pencil/core'-import Tip from '@/components/ui/Tip.vue'-import { usePopoverUI } from '@/components/ui/popover'-import { DEFAULT_COLLAB_STATE, useCollabInjected } from '@/composables/use-collab'-import { toast } from '@/utils/toast'-import { initials } from '@/utils/text'-import { useI18n } from '@open-pencil/vue'--const route = useRoute()-const router = useRouter()-const cls = usePopoverUI({ content: 'z-50 w-72 p-3' })-const collab = useCollabInjected()-const { copy, copied } = useClipboard({ copiedDuring: 2000 })-const { dialogs } = useI18n()--const joinInput = ref('')-const nameDraft = ref(collab?.state.value.localName ?? '')-const pendingRoomId = computed(() =>- typeof route.params.roomId === 'string' ? route.params.roomId : null-)-const popoverOpen = ref(!!pendingRoomId.value)--const state = computed(() => collab?.state.value ?? DEFAULT_COLLAB_STATE)-const peers = computed(() => collab?.remotePeers.value ?? [])-const followingPeer = computed(() => collab?.followingPeer.value ?? null)--const shareUrl = computed(() => {- if (!state.value.roomId) return ''- return `${window.location.origin}/share/${state.value.roomId}`-})--const isJoining = computed(() => !!pendingRoomId.value && !state.value.connected)--watch(- pendingRoomId,- (roomId) => {- if (!state.value.connected) {- popoverOpen.value = !!roomId- }- },- { immediate: true }-)--function copyLink() {- if (!shareUrl.value) return- copy(shareUrl.value)- toast.info('Link copied to clipboard')-}--function onShare() {- if (!collab || !nameDraft.value.trim()) return- collab.setLocalName(nameDraft.value.trim())- const roomId = collab.shareCurrentDoc()- router.push(`/share/${roomId}`)- copy(`${window.location.origin}/share/${roomId}`)- toast.info('Link copied to clipboard')- popoverOpen.value = false-}--function onJoin() {- if (!collab) return- const roomId = pendingRoomId.value || joinInput.value.trim().replace(/.*\/share\//, '')- if (!roomId || !nameDraft.value.trim()) return- collab.setLocalName(nameDraft.value.trim())- collab.connect(roomId)- router.push(`/share/${roomId}`)- popoverOpen.value = false-}--function onDisconnect() {- if (!collab) return- collab.disconnect()- popoverOpen.value = false- router.push('/')-}-</script>--<template>- <div class="flex w-full items-center justify-end gap-2">- <!-- Avatar stack -->- <div class="flex -space-x-1.5">- <Tip :label="`${state.localName || 'You'} (you)`">- <div- data-test-id="collab-local-avatar"- class="flex size-6 items-center justify-center rounded-full border-2 border-panel text-[10px] font-semibold text-white"- :style="{ background: colorToCSS(state.localColor) }"- >- {{ initials(state.localName || 'You') }}- </div>- </Tip>-- <Tip- v-for="peer in peers"- :key="peer.clientId"- :label="- followingPeer === peer.clientId- ? `Following ${peer.name} (click to stop)`- : `Click to follow ${peer.name}`- "- >- <div- data-test-id="collab-peer-avatar"- class="flex size-6 cursor-pointer items-center justify-center rounded-full border-2 text-[10px] font-semibold text-white transition-all"- :class="- followingPeer === peer.clientId ? 'border-white ring-2 ring-white/40' : 'border-panel'- "- :style="{ background: colorToCSS(peer.color) }"- @click="collab?.followPeer(followingPeer === peer.clientId ? null : peer.clientId)"- >- {{ initials(peer.name) }}- </div>- </Tip>- </div>-- <div class="flex-1" />-- <!-- Share button / popover -->- <PopoverRoot v-model:open="popoverOpen">- <PopoverTrigger as-child>- <button- data-test-id="collab-share-button"- class="flex h-7 cursor-pointer items-center gap-1.5 rounded-md border-none px-3 text-xs font-medium transition-colors"- :class="- state.connected- ? 'bg-green-600 text-white hover:bg-green-700'- : isJoining- ? 'animate-pulse bg-amber-600 text-white'- : 'bg-accent text-white hover:bg-accent/90'- "- >- <icon-lucide-share-2 class="size-3.5" />- {{ state.connected ? dialogs.connected : isJoining ? dialogs.joinRoom : dialogs.share }}- </button>- </PopoverTrigger>-- <PopoverPortal>- <PopoverContent- data-test-id="collab-popover"- :class="cls.content"- :side-offset="8"- side="bottom"- align="end"- >- <!-- Connected state -->- <template v-if="state.connected">- <div class="mb-3 text-xs font-medium text-surface">{{ dialogs.roomLink }}</div>- <div class="mb-3 flex items-center gap-1.5">- <input- :value="shareUrl"- readonly- data-test-id="collab-room-link"- class="min-w-0 flex-1 rounded border border-border bg-input px-2 py-1 text-xs text-surface"- @focus="($event.target as HTMLInputElement).select()"- />- <button- data-test-id="collab-copy-link"- class="flex h-7 cursor-pointer items-center gap-1 rounded border-none bg-accent px-2 text-xs text-white hover:bg-accent/90"- @click="copyLink"- >- <icon-lucide-check v-if="copied" class="size-3" />- <icon-lucide-copy v-else class="size-3" />- {{ copied ? 'Copied' : 'Copy' }}- </button>- </div>-- <div class="mb-2 text-xs font-medium text-surface">- {{ peers.length + 1 }} {{ peers.length === 0 ? 'person' : 'people' }} in this room- </div>-- <button- data-test-id="collab-disconnect"- class="flex h-7 w-full cursor-pointer items-center justify-center rounded border border-border bg-transparent text-xs text-muted hover:bg-hover hover:text-surface"- @click="onDisconnect"- >- Disconnect- </button>- </template>-- <!-- Joining via /share/ link -->- <template v-else-if="isJoining">- <div class="mb-1 text-xs font-medium text-surface">{{ dialogs.joinCollaboration }}</div>- <div class="mb-3 text-[11px] text-muted">- Someone shared this file with you. Enter your name to join.- </div>-- <div class="mb-3">- <label class="mb-1 block text-xs text-muted">{{ dialogs.yourName }}</label>- <input- v-model="nameDraft"- data-test-id="collab-name-input"- class="w-full rounded border border-border bg-input px-2 py-1 text-xs text-surface"- :placeholder="dialogs.enterYourName"- autofocus- @keydown.enter="onJoin"- />- </div>-- <button- data-test-id="collab-join-button"- class="flex h-8 w-full cursor-pointer items-center justify-center gap-1.5 rounded border-none bg-accent text-xs font-medium text-white hover:bg-accent/90 disabled:opacity-50"- :disabled="!nameDraft.trim()"- @click="onJoin"- >- <icon-lucide-users class="size-3.5" />- Join room- </button>- </template>-- <!-- Not connected: share or join -->- <template v-else>- <div class="mb-3">- <label class="mb-1 block text-xs text-muted">{{ dialogs.yourName }}</label>- <input- v-model="nameDraft"- data-test-id="collab-name-input"- class="w-full rounded border border-border bg-input px-2 py-1 text-xs text-surface"- :placeholder="dialogs.enterYourName"- @keydown.enter="onShare"- />- </div>-- <button- data-test-id="collab-share-file"- class="mb-3 flex h-8 w-full cursor-pointer items-center justify-center gap-1.5 rounded border-none bg-accent text-xs font-medium text-white hover:bg-accent/90 disabled:opacity-50"- :disabled="!nameDraft.trim()"- @click="onShare"- >- <icon-lucide-share-2 class="size-3.5" />- {{ dialogs.shareThisFile }}- </button>-- <div class="mb-2 flex items-center gap-2">- <div class="h-px flex-1 bg-border" />- <span class="text-[11px] text-muted">{{ dialogs.orJoinRoom }}</span>- <div class="h-px flex-1 bg-border" />- </div>-- <div class="flex items-center gap-1.5">- <input- v-model="joinInput"- data-test-id="collab-join-input"- class="min-w-0 flex-1 rounded border border-border bg-input px-2 py-1 text-xs text-surface"- :placeholder="dialogs.pasteRoomLinkOrId"- @keydown.enter="onJoin"- />- <button- data-test-id="collab-join-room-button"- class="flex h-7 cursor-pointer items-center rounded border-none bg-accent px-3 text-xs text-white hover:bg-accent/90 disabled:opacity-50"- :disabled="!joinInput.trim() || !nameDraft.trim()"- @click="onJoin"- >- Join- </button>- </div>- </template>- </PopoverContent>- </PopoverPortal>- </PopoverRoot>- </div>-</template>diff --git a/src/components/CollabPanel/CollabAvatarStack.vue b/src/components/CollabPanel/CollabAvatarStack.vuenew file mode 100644index 000000000..dda522253--- /dev/null+++ b/src/components/CollabPanel/CollabAvatarStack.vue@@ -0,0 +1,47 @@+<script setup lang="ts">+import { colorToCSS } from '@open-pencil/core/color'++import Tip from '@/components/ui/Tip.vue'+import { initials } from '@/app/shell/ui'+import { useCollabPanelContext } from '@/components/CollabPanel/context'++const collab = useCollabPanelContext()+</script>++<template>+ <div class="flex -space-x-1.5">+ <Tip :label="`${collab.state.localName || 'You'} (you)`">+ <div+ data-test-id="collab-local-avatar"+ class="flex size-6 items-center justify-center rounded-full border-2 border-panel text-[10px] font-semibold text-white"+ :style="{ background: colorToCSS(collab.state.localColor) }"+ >+ {{ initials(collab.state.localName || 'You') }}+ </div>+ </Tip>++ <Tip+ v-for="peer in collab.peers"+ :key="peer.clientId"+ :label="+ collab.followingPeer === peer.clientId+ ? `Following ${peer.name} (click to stop)`+ : `Click to follow ${peer.name}`+ "+ >+ <div+ data-test-id="collab-peer-avatar"+ class="flex size-6 cursor-pointer items-center justify-center rounded-full border-2 text-[10px] font-semibold text-white transition-all"+ :class="+ collab.followingPeer === peer.clientId+ ? 'border-white ring-2 ring-white/40'+ : 'border-panel'+ "+ :style="{ background: colorToCSS(peer.color) }"+ @click="collab.toggleFollowPeer(peer.clientId)"+ >+ {{ initials(peer.name) }}+ </div>+ </Tip>+ </div>+</template>diff --git a/src/components/CollabPanel/CollabPanel.vue b/src/components/CollabPanel/CollabPanel.vuenew file mode 100644index 000000000..2b3998055--- /dev/null+++ b/src/components/CollabPanel/CollabPanel.vue@@ -0,0 +1,15 @@+<script setup lang="ts">+import CollabAvatarStack from '@/components/CollabPanel/CollabAvatarStack.vue'+import CollabSharePopover from '@/components/CollabPanel/CollabSharePopover.vue'+import { provideCollabPanel } from '@/components/CollabPanel/context'++provideCollabPanel()+</script>++<template>+ <div class="flex w-full items-center justify-end gap-2">+ <CollabAvatarStack />+ <div class="flex-1" />+ <CollabSharePopover />+ </div>+</template>diff --git a/src/components/CollabPanel/CollabSharePopover.vue b/src/components/CollabPanel/CollabSharePopover.vuenew file mode 100644index 000000000..5768eeb09--- /dev/null+++ b/src/components/CollabPanel/CollabSharePopover.vue@@ -0,0 +1,53 @@+<script setup lang="ts">+import { PopoverContent, PopoverPortal, PopoverRoot, PopoverTrigger } from 'reka-ui'++import ConnectedRoom from '@/components/CollabPanel/ConnectedRoom.vue'+import JoinRoomPrompt from '@/components/CollabPanel/JoinRoomPrompt.vue'+import ShareOrJoinRoom from '@/components/CollabPanel/ShareOrJoinRoom.vue'+import { useCollabPanelContext } from '@/components/CollabPanel/context'+import { usePopoverUI } from '@/components/ui/popover'++const collab = useCollabPanelContext()+const cls = usePopoverUI({ content: 'z-50 w-72 p-3' })+</script>++<template>+ <PopoverRoot v-model:open="collab.popoverOpen">+ <PopoverTrigger as-child>+ <button+ data-test-id="collab-share-button"+ class="flex h-7 cursor-pointer items-center gap-1.5 rounded-md border-none px-3 text-xs font-medium transition-colors"+ :class="+ collab.state.connected+ ? 'bg-green-600 text-white hover:bg-green-700'+ : collab.isJoining+ ? 'animate-pulse bg-amber-600 text-white'+ : 'bg-accent text-white hover:bg-accent/90'+ "+ >+ <icon-lucide-share-2 class="size-3.5" />+ {{+ collab.state.connected+ ? collab.dialogs.connected+ : collab.isJoining+ ? collab.dialogs.joinRoom+ : collab.dialogs.share+ }}+ </button>+ </PopoverTrigger>++ <PopoverPortal>+ <PopoverContent+ data-test-id="collab-popover"+ :class="cls.content"+ :side-offset="8"+ side="bottom"+ align="end"+ >+ <ConnectedRoom v-if="collab.state.connected" />+ <JoinRoomPrompt v-else-if="collab.isJoining" />+ <ShareOrJoinRoom v-else />+ </PopoverContent>+ </PopoverPortal>+ </PopoverRoot>+</template>diff --git a/src/components/CollabPanel/ConnectedRoom.vue b/src/components/CollabPanel/ConnectedRoom.vuenew file mode 100644index 000000000..ada2d76b1--- /dev/null+++ b/src/components/CollabPanel/ConnectedRoom.vue@@ -0,0 +1,39 @@+<script setup lang="ts">+import { useCollabPanelContext } from '@/components/CollabPanel/context'++const collab = useCollabPanelContext()+</script>++<template>+ <div class="mb-3 text-xs font-medium text-surface">{{ collab.dialogs.roomLink }}</div>+ <div class="mb-3 flex items-center gap-1.5">+ <input+ :value="collab.shareUrl"+ readonly+ data-test-id="collab-room-link"+ class="min-w-0 flex-1 rounded border border-border bg-input px-2 py-1 text-xs text-surface"+ @focus="($event.target as HTMLInputElement).select()"+ />+ <button+ data-test-id="collab-copy-link"+ class="flex h-7 cursor-pointer items-center gap-1 rounded border-none bg-accent px-2 text-xs text-white hover:bg-accent/90"+ @click="collab.copyLink"+ >+ <icon-lucide-check v-if="collab.copied" class="size-3" />+ <icon-lucide-copy v-else class="size-3" />+ {{ collab.copied ? 'Copied' : 'Copy' }}+ </button>+ </div>++ <div class="mb-2 text-xs font-medium text-surface">+ {{ collab.peers.length + 1 }} {{ collab.peers.length === 0 ? 'person' : 'people' }} in this room+ </div>++ <button+ data-test-id="collab-disconnect"+ class="flex h-7 w-full cursor-pointer items-center justify-center rounded border border-border bg-transparent text-xs text-muted hover:bg-hover hover:text-surface"+ @click="collab.disconnect"+ >+ Disconnect+ </button>+</template>diff --git a/src/components/CollabPanel/JoinRoomPrompt.vue b/src/components/CollabPanel/JoinRoomPrompt.vuenew file mode 100644index 000000000..de1df659a--- /dev/null+++ b/src/components/CollabPanel/JoinRoomPrompt.vue@@ -0,0 +1,34 @@+<script setup lang="ts">+import { useCollabPanelContext } from '@/components/CollabPanel/context'++const collab = useCollabPanelContext()+</script>++<template>+ <div class="mb-1 text-xs font-medium text-surface">{{ collab.dialogs.joinCollaboration }}</div>+ <div class="mb-3 text-[11px] text-muted">+ Someone shared this file with you. Enter your name to join.+ </div>++ <div class="mb-3">+ <label class="mb-1 block text-xs text-muted">{{ collab.dialogs.yourName }}</label>+ <input+ v-model="collab.nameDraft"+ data-test-id="collab-name-input"+ class="w-full rounded border border-border bg-input px-2 py-1 text-xs text-surface"+ :placeholder="collab.dialogs.enterYourName"+ autofocus+ @keydown.enter="collab.join"+ />+ </div>++ <button+ data-test-id="collab-join-button"+ class="flex h-8 w-full cursor-pointer items-center justify-center gap-1.5 rounded border-none bg-accent text-xs font-medium text-white hover:bg-accent/90 disabled:opacity-50"+ :disabled="!collab.nameDraft.trim()"+ @click="collab.join"+ >+ <icon-lucide-users class="size-3.5" />+ Join room+ </button>+</template>diff --git a/src/components/CollabPanel/ShareOrJoinRoom.vue b/src/components/CollabPanel/ShareOrJoinRoom.vuenew file mode 100644index 000000000..338d0d5ee--- /dev/null+++ b/src/components/CollabPanel/ShareOrJoinRoom.vue@@ -0,0 +1,52 @@+<script setup lang="ts">+import { useCollabPanelContext } from '@/components/CollabPanel/context'++const collab = useCollabPanelContext()+</script>++<template>+ <div class="mb-3">+ <label class="mb-1 block text-xs text-muted">{{ collab.dialogs.yourName }}</label>+ <input+ v-model="collab.nameDraft"+ data-test-id="collab-name-input"+ class="w-full rounded border border-border bg-input px-2 py-1 text-xs text-surface"+ :placeholder="collab.dialogs.enterYourName"+ @keydown.enter="collab.share"+ />+ </div>++ <button+ data-test-id="collab-share-file"+ class="mb-3 flex h-8 w-full cursor-pointer items-center justify-center gap-1.5 rounded border-none bg-accent text-xs font-medium text-white hover:bg-accent/90 disabled:opacity-50"+ :disabled="!collab.nameDraft.trim()"+ @click="collab.share"+ >+ <icon-lucide-share-2 class="size-3.5" />+ {{ collab.dialogs.shareThisFile }}+ </button>++ <div class="mb-2 flex items-center gap-2">+ <div class="h-px flex-1 bg-border" />+ <span class="text-[11px] text-muted">{{ collab.dialogs.orJoinRoom }}</span>+ <div class="h-px flex-1 bg-border" />+ </div>++ <div class="flex items-center gap-1.5">+ <input+ v-model="collab.joinInput"+ data-test-id="collab-join-input"+ class="min-w-0 flex-1 rounded border border-border bg-input px-2 py-1 text-xs text-surface"+ :placeholder="collab.dialogs.pasteRoomLinkOrId"+ @keydown.enter="collab.join"+ />+ <button+ data-test-id="collab-join-room-button"+ class="flex h-7 cursor-pointer items-center rounded border-none bg-accent px-3 text-xs text-white hover:bg-accent/90 disabled:opacity-50"+ :disabled="!collab.joinInput.trim() || !collab.nameDraft.trim()"+ @click="collab.join"+ >+ Join+ </button>+ </div>+</template>diff --git a/src/components/CollabPanel/context.ts b/src/components/CollabPanel/context.tsnew file mode 100644index 000000000..b9aad8f15--- /dev/null+++ b/src/components/CollabPanel/context.ts@@ -0,0 +1,111 @@+import { useClipboard } from '@vueuse/core'+import { computed, inject, provide, proxyRefs, ref, watch } from 'vue'+import { useRoute, useRouter } from 'vue-router'++import { DEFAULT_COLLAB_STATE, useCollabInjected } from '@/app/collab/use'+import { toast } from '@/app/shell/ui'+import { useI18n } from '@open-pencil/vue'++import type { InjectionKey, ShallowUnwrapRef } from 'vue'++function createCollabPanelContext() {+ const route = useRoute()+ const router = useRouter()+ const collab = useCollabInjected()+ const { copy, copied } = useClipboard({ copiedDuring: 2000 })+ const { dialogs } = useI18n()++ const joinInput = ref('')+ const nameDraft = ref(collab?.state.value.localName ?? '')+ const pendingRoomId = computed(() =>+ typeof route.params.roomId === 'string' ? route.params.roomId : null+ )+ const popoverOpen = ref(!!pendingRoomId.value)+ const state = computed(() => collab?.state.value ?? DEFAULT_COLLAB_STATE)+ const peers = computed(() => collab?.remotePeers.value ?? [])+ const followingPeer = computed(() => collab?.followingPeer.value ?? null)+ const shareUrl = computed(() => {+ if (!state.value.roomId) return ''+ return `${window.location.origin}/share/${state.value.roomId}`+ })+ const isJoining = computed(() => !!pendingRoomId.value && !state.value.connected)++ watch(+ pendingRoomId,+ (roomId) => {+ if (!state.value.connected) popoverOpen.value = !!roomId+ },+ { immediate: true }+ )++ function copyLink() {+ if (!shareUrl.value) return+ void copy(shareUrl.value)+ toast.info('Link copied to clipboard')+ }++ function share() {+ if (!collab || !nameDraft.value.trim()) return+ collab.setLocalName(nameDraft.value.trim())+ const roomId = collab.shareCurrentDoc()+ void router.push(`/share/${roomId}`)+ void copy(`${window.location.origin}/share/${roomId}`)+ toast.info('Link copied to clipboard')+ popoverOpen.value = false+ }++ function join() {+ if (!collab) return+ const roomId = pendingRoomId.value || joinInput.value.trim().replace(/.*\/share\//, '')+ if (!roomId || !nameDraft.value.trim()) return+ collab.setLocalName(nameDraft.value.trim())+ collab.connect(roomId)+ void router.push(`/share/${roomId}`)+ popoverOpen.value = false+ }++ function disconnect() {+ if (!collab) return+ collab.disconnect()+ popoverOpen.value = false+ void router.push('/')+ }++ function toggleFollowPeer(clientId: number) {+ collab?.followPeer(followingPeer.value === clientId ? null : clientId)+ }++ return {+ dialogs,+ copied,+ joinInput,+ nameDraft,+ popoverOpen,+ state,+ peers,+ followingPeer,+ shareUrl,+ isJoining,+ copyLink,+ share,+ join,+ disconnect,+ toggleFollowPeer+ }+}++export type CollabPanelContext = ShallowUnwrapRef<ReturnType<typeof createCollabPanelContext>>++const COLLAB_PANEL_KEY: InjectionKey<CollabPanelContext> = Symbol('CollabPanelContext')++export function provideCollabPanel() {+ const ctx = proxyRefs(createCollabPanelContext())+ provide(COLLAB_PANEL_KEY, ctx)+ return ctx+}++export function useCollabPanelContext(): CollabPanelContext {+ const ctx = inject(COLLAB_PANEL_KEY)+ if (!ctx) throw new Error('Collab panel controls must be used within CollabPanel')+ return ctx+}diff --git a/src/components/ColorInput.vue b/src/components/ColorPicker/ColorInput.vuesimilarity index 77%rename from src/components/ColorInput.vuerename to src/components/ColorPicker/ColorInput.vueindex b3377bb70..df4ac3ad2 100644--- a/src/components/ColorInput.vue+++ b/src/components/ColorPicker/ColorInput.vue@@ -1,10 +1,16 @@<script setup lang="ts">+import { useAttrs } from 'vue'+import { ColorInputRoot } from '@open-pencil/vue'-import ColorPicker from './ColorPicker.vue'+import ColorPicker from '@/components/ColorPicker/ColorPicker.vue'++import type { Color } from '@open-pencil/core/types'+import type { OkHCLControls } from '@open-pencil/vue'++defineOptions({ inheritAttrs: false })-import type { Color } from '@open-pencil/core'-import type { OkHCLControls } from '@open-pencil/vue/ColorPicker/types'+const attrs = useAttrs()const {editable = false,@@ -28,7 +34,7 @@ const emit = defineEmits<{ update: [color: Color] }>()<template#default="{ editable: isEditable, hex, updateFromHex, updateColor, okhcl: okhclControls }">- <div class="flex items-center gap-1.5">+ <div v-bind="attrs" class="flex items-center gap-1.5"><ColorPicker :color="color" :okhcl="okhclControls" @update="updateColor($event)" /><inputv-if="isEditable"diff --git a/src/components/ColorPicker.vue b/src/components/ColorPicker/ColorPicker.vuesimilarity index 73%rename from src/components/ColorPicker.vuerename to src/components/ColorPicker/ColorPicker.vueindex 5782819ba..9a41dffb5 100644--- a/src/components/ColorPicker.vue+++ b/src/components/ColorPicker/ColorPicker.vue@@ -1,11 +1,11 @@<script setup lang="ts">import { ColorPickerRoot } from '@open-pencil/vue'-import ColorPickerPanel from './ColorPickerPanel.vue'-import { usePopoverUI } from './ui/popover'+import ColorPickerPanel from '@/components/ColorPickerPanel/ColorPickerPanel.vue'+import { usePopoverUI } from '@/components/ui/popover'-import type { Color } from '@open-pencil/core'-import type { OkHCLControls } from '@open-pencil/vue/ColorPicker/types'+import type { Color } from '@open-pencil/core/types'+import type { OkHCLControls } from '@open-pencil/vue'const { color, okhcl = null } = defineProps<{ color: Color; okhcl?: OkHCLControls | null }>()const emit = defineEmits<{ update: [color: Color] }>()diff --git a/src/components/ColorPickerPanel.vue b/src/components/ColorPickerPanel.vuedeleted file mode 100644index 07bd4c0bb..000000000--- a/src/components/ColorPickerPanel.vue+++ /dev/null@@ -1,399 +0,0 @@-<script setup lang="ts">-import { computed } from 'vue'-import { ColorAreaRoot, ColorAreaArea, ColorAreaThumb } from 'reka-ui'--import type { Color } from '@open-pencil/core'-import { colorToCSS } from '@open-pencil/core'-import type { OkHCLControls } from '@open-pencil/vue/ColorPicker/types'-import {- createColorPickerModel,- createOkHCLSliderGradientModel,- createOkHCLSliderPreviewModel,- createSliderGradientModel,- createSliderPreviewModel,- fromPercent,- rekaToAppColor,- toPercent,- updateAlpha,- updateHSBChannel,- updateHSLChannel,- updateHue,- updateRGBChannel,- useI18n-} from '@open-pencil/vue'-import PickerSlider from './PickerSlider.vue'-import AppSelect from './ui/AppSelect.vue'--const { color, okhcl = null } = defineProps<{- color: Color- okhcl?: OkHCLControls | null-}>()--const emit = defineEmits<{- update: [color: Color]-}>()--const { panels } = useI18n()--const pickerModel = computed(() => createColorPickerModel(color))-const rekaColor = computed(() => pickerModel.value.rekaColor)-const hslColor = computed(() => pickerModel.value.hsl)-const hsbColor = computed(() => pickerModel.value.hsb)-const rgbColor = computed(() => pickerModel.value.rgb)-const sliderPreview = computed(() => createSliderPreviewModel(pickerModel.value))-const sliderGradient = computed(() => createSliderGradientModel(pickerModel.value))-const okhclSliderPreview = computed(() =>- okhcl?.okhcl ? createOkHCLSliderPreviewModel(okhcl.okhcl) : null-)-const okhclSliderGradient = computed(() =>- okhcl?.okhcl ? createOkHCLSliderGradientModel(okhcl.okhcl) : null-)-const fieldOptions = computed(- () =>- okhcl?.fieldOptions ?? [- { value: 'rgb', label: panels.value.colorFormatRgb },- { value: 'hsl', label: panels.value.colorFormatHsl },- { value: 'hsb', label: panels.value.colorFormatHsb }- ]-)-const fieldFormat = computed(() => okhcl?.fieldFormat ?? 'rgb')-const isOkHCLFormat = computed(() => fieldFormat.value === 'okhcl' && okhcl)--function onRekaColorUpdate(colorValue: ReturnType<typeof createColorPickerModel>['rekaColor']) {- emit('update', rekaToAppColor(colorValue))-}--function setFieldFormat(value: string) {- okhcl?.setFieldFormat(value as NonNullable<OkHCLControls>['fieldFormat'])-}--function updateRGBAHue(value: number) {- emit('update', updateHue(pickerModel.value, value))-}--function updateRGBAAlpha(value: number) {- emit('update', updateAlpha(color, value))-}--function updateRGBChannelValue(channel: 'r' | 'g' | 'b', value: number) {- emit('update', updateRGBChannel(color, channel, value))-}--function updateHSLChannelValue(channel: 'h' | 's' | 'l', value: number) {- emit('update', updateHSLChannel(pickerModel.value, channel, value))-}--function updateHSBChannelValue(channel: 'h' | 's' | 'b', value: number) {- emit('update', updateHSBChannel(pickerModel.value, channel, value))-}--function updateOkHCLChannel(channel: 'h' | 'c' | 'l' | 'a', value: number) {- okhcl?.updateOkHCL({ [channel]: value })-}-</script>--<template>- <div class="flex flex-col gap-2">- <ColorAreaRoot- v-slot="{ style }"- :model-value="rekaColor"- color-space="hsb"- x-channel="saturation"- y-channel="brightness"- @update:color="onRekaColorUpdate"- >- <ColorAreaArea- class="relative h-[140px] w-full cursor-crosshair overflow-hidden rounded"- :style="style"- >- <ColorAreaThumb- class="pointer-events-none absolute size-2.5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-sm"- />- </ColorAreaArea>- </ColorAreaRoot>-- <template v-if="fieldFormat !== 'okhcl'">- <PickerSlider- label="H"- :model-value="hslColor.h ?? 0"- :min="0"- :max="360"- :step="1"- gradient-style="background: linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000);"- :thumb-fill="colorToCSS(sliderPreview.hue)"- :ui="{ root: 'gap-0', label: 'hidden', input: 'hidden' }"- test-id="color-slider-hue"- @update:model-value="updateRGBAHue"- />-- <PickerSlider- label="A"- :model-value="color.a"- :min="0"- :max="1"- :step="0.001"- checkerboard- :gradient-style="`background: linear-gradient(to right, transparent, ${colorToCSS({ ...color, a: 1 })})`"- :thumb-fill="colorToCSS(color)"- :ui="{ root: 'gap-0', label: 'hidden', input: 'hidden' }"- test-id="color-slider-alpha"- @update:model-value="updateRGBAAlpha"- />- </template>-- <div class="flex flex-col gap-2">- <AppSelect- class="w-[120px]"- test-id="color-format-select"- :model-value="fieldFormat"- :options="fieldOptions"- @update:model-value="setFieldFormat"- />-- <div class="min-w-0 flex flex-col gap-2">- <div- v-if="fieldFormat === 'rgb'"- class="grid grid-cols-[repeat(3,minmax(0,1fr))] gap-px overflow-hidden rounded border border-border bg-border"- >- <input- type="number"- class="bg-input px-2 py-1 text-xs text-surface outline-none"- :value="Math.round(rgbColor.r)"- min="0"- max="255"- @change="updateRGBChannelValue('r', +($event.target as HTMLInputElement).value)"- />- <input- type="number"- class="bg-input px-2 py-1 text-xs text-surface outline-none"- :value="Math.round(rgbColor.g)"- min="0"- max="255"- @change="updateRGBChannelValue('g', +($event.target as HTMLInputElement).value)"- />- <input- type="number"- class="bg-input px-2 py-1 text-xs text-surface outline-none"- :value="Math.round(rgbColor.b)"- min="0"- max="255"- @change="updateRGBChannelValue('b', +($event.target as HTMLInputElement).value)"- />- </div>-- <template v-else-if="fieldFormat === 'hsl'">- <div- class="grid grid-cols-[repeat(3,minmax(0,1fr))] gap-px overflow-hidden rounded border border-border bg-border"- >- <input- type="number"- class="bg-input px-2 py-1 text-xs text-surface outline-none"- :value="Math.round(hslColor.h ?? 0)"- min="0"- max="360"- @change="updateHSLChannelValue('h', +($event.target as HTMLInputElement).value)"- />- <input- type="number"- class="bg-input px-2 py-1 text-xs text-surface outline-none"- :value="Math.round(hslColor.s ?? 0)"- min="0"- max="100"- @change="updateHSLChannelValue('s', +($event.target as HTMLInputElement).value)"- />- <input- type="number"- class="bg-input px-2 py-1 text-xs text-surface outline-none"- :value="Math.round(hslColor.l ?? 0)"- min="0"- max="100"- @change="updateHSLChannelValue('l', +($event.target as HTMLInputElement).value)"- />- </div>-- <PickerSlider- label="S"- :model-value="hslColor.s ?? 0"- :min="0"- :max="100"- :step="0.1"- :display-value="Math.round(hslColor.s ?? 0)"- :display-min="0"- :display-max="100"- :display-step="1"- :gradient-style="sliderGradient.hslSaturation"- :thumb-fill="colorToCSS(sliderPreview.hslSaturation)"- test-id="color-slider-hsl-s"- @update:model-value="updateHSLChannelValue('s', $event)"- />-- <PickerSlider- label="L"- :model-value="hslColor.l ?? 0"- :min="0"- :max="100"- :step="0.1"- :display-value="Math.round(hslColor.l ?? 0)"- :display-min="0"- :display-max="100"- :display-step="1"- :gradient-style="sliderGradient.hslLightness"- :thumb-fill="colorToCSS(sliderPreview.hslLightness)"- test-id="color-slider-hsl-l"- @update:model-value="updateHSLChannelValue('l', $event)"- />-- <p class="text-[10px] leading-4 text-muted">{{ panels.colorHintHsl }}</p>- </template>-- <template v-else-if="fieldFormat === 'hsb'">- <div- class="grid grid-cols-[repeat(3,minmax(0,1fr))] gap-px overflow-hidden rounded border border-border bg-border"- >- <input- type="number"- class="bg-input px-2 py-1 text-xs text-surface outline-none"- :value="Math.round(hsbColor.h)"- min="0"- max="360"- @change="updateHSBChannelValue('h', +($event.target as HTMLInputElement).value)"- />- <input- type="number"- class="bg-input px-2 py-1 text-xs text-surface outline-none"- :value="Math.round(hsbColor.s)"- min="0"- max="100"- @change="updateHSBChannelValue('s', +($event.target as HTMLInputElement).value)"- />- <input- type="number"- class="bg-input px-2 py-1 text-xs text-surface outline-none"- :value="Math.round(hsbColor.b)"- min="0"- max="100"- @change="updateHSBChannelValue('b', +($event.target as HTMLInputElement).value)"- />- </div>-- <PickerSlider- label="S"- :model-value="hsbColor.s"- :min="0"- :max="100"- :step="0.1"- :display-value="Math.round(hsbColor.s)"- :display-min="0"- :display-max="100"- :display-step="1"- :gradient-style="sliderGradient.hsbSaturation"- :thumb-fill="colorToCSS(sliderPreview.hsbSaturation)"- test-id="color-slider-hsb-s"- @update:model-value="updateHSBChannelValue('s', $event)"- />-- <PickerSlider- label="B"- :model-value="hsbColor.b"- :min="0"- :max="100"- :step="0.1"- :display-value="Math.round(hsbColor.b)"- :display-min="0"- :display-max="100"- :display-step="1"- :gradient-style="sliderGradient.hsbBrightness"- :thumb-fill="colorToCSS(sliderPreview.hsbBrightness)"- test-id="color-slider-hsb-b"- @update:model-value="updateHSBChannelValue('b', $event)"- />-- <p class="text-[10px] leading-4 text-muted">{{ panels.colorHintHsb }}</p>- </template>-- <div v-else-if="isOkHCLFormat && okhcl?.okhcl" class="flex flex-col gap-2">- <PickerSlider- label="H"- :model-value="okhcl.okhcl.h"- :min="0"- :max="360"- :step="1"- :display-value="Math.round(okhcl.okhcl.h)"- :display-min="0"- :display-max="360"- :display-step="1"- gradient-style="background: linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000);"- :thumb-fill="colorToCSS(okhclSliderPreview?.okhclHue ?? color)"- test-id="color-slider-okhcl-h"- @update:model-value="updateOkHCLChannel('h', $event)"- />-- <PickerSlider- label="C"- :model-value="okhcl.okhcl.c"- :min="0"- :max="0.4"- :step="0.001"- :display-value="toPercent(okhcl.okhcl.c)"- :display-min="0"- :display-max="40"- :display-step="1"- :parse-display="fromPercent"- :gradient-style="okhclSliderGradient?.okhclChroma ?? undefined"- :thumb-fill="colorToCSS(okhclSliderPreview?.okhclChroma ?? color)"- test-id="color-slider-okhcl-c"- @update:model-value="updateOkHCLChannel('c', $event)"- />-- <PickerSlider- label="L"- :model-value="okhcl.okhcl.l"- :min="0"- :max="1"- :step="0.001"- :display-value="toPercent(okhcl.okhcl.l)"- :display-min="0"- :display-max="100"- :display-step="1"- :parse-display="fromPercent"- :gradient-style="okhclSliderGradient?.okhclLightness ?? undefined"- :thumb-fill="colorToCSS(okhclSliderPreview?.okhclLightness ?? color)"- test-id="color-slider-okhcl-l"- @update:model-value="updateOkHCLChannel('l', $event)"- />-- <PickerSlider- label="A"- :model-value="okhcl.okhcl.a ?? 1"- :min="0"- :max="1"- :step="0.001"- :display-value="toPercent(okhcl.okhcl.a ?? 1)"- :display-min="0"- :display-max="100"- :display-step="1"- :parse-display="fromPercent"- checkerboard- :gradient-style="`background: linear-gradient(to right, transparent, ${colorToCSS(color)})`"- :thumb-fill="colorToCSS(color)"- test-id="color-slider-okhcl-a"- @update:model-value="updateOkHCLChannel('a', $event)"- />-- <div class="flex items-start justify-between gap-2 text-[10px] text-muted">- <p class="min-w-0 flex-1 leading-4 break-words">{{ panels.colorHintOkhcl }}</p>- <span- v-if="okhcl.previewColorSpace"- class="shrink-0 rounded border border-border px-1 py-0.5 text-[10px] uppercase"- >- {{ okhcl.previewColorSpace }}- </span>- </div>- <p v-if="okhcl.clipped" class="text-[10px] leading-4 text-amber-400">- {{ panels.colorPreviewClipped({ space: okhcl.previewColorSpace ?? 'display-p3' }) }}- </p>- </div>- </div>- </div>- </div>-</template>diff --git a/src/components/ColorPickerPanel/ColorAreaControl.vue b/src/components/ColorPickerPanel/ColorAreaControl.vuenew file mode 100644index 000000000..3f1cccfd6--- /dev/null+++ b/src/components/ColorPickerPanel/ColorAreaControl.vue@@ -0,0 +1,27 @@+<script setup lang="ts">+import { ColorAreaArea, ColorAreaRoot, ColorAreaThumb } from 'reka-ui'++import { useColorPickerPanelContext } from '@/components/ColorPickerPanel/context'++const ctx = useColorPickerPanelContext()+</script>++<template>+ <ColorAreaRoot+ v-slot="{ style }"+ :model-value="ctx.rekaColor"+ color-space="hsb"+ x-channel="saturation"+ y-channel="brightness"+ @update:color="ctx.onRekaColorUpdate"+ >+ <ColorAreaArea+ class="relative h-[140px] w-full cursor-crosshair overflow-hidden rounded"+ :style="style"+ >+ <ColorAreaThumb+ class="pointer-events-none absolute size-2.5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-sm"+ />+ </ColorAreaArea>+ </ColorAreaRoot>+</template>diff --git a/src/components/ColorPickerPanel/ColorPickerPanel.vue b/src/components/ColorPickerPanel/ColorPickerPanel.vuenew file mode 100644index 000000000..d2573f600--- /dev/null+++ b/src/components/ColorPickerPanel/ColorPickerPanel.vue@@ -0,0 +1,38 @@+<script setup lang="ts">+import type { Color } from '@open-pencil/core/types'+import type { OkHCLControls } from '@open-pencil/vue'++import ColorAreaControl from '@/components/ColorPickerPanel/ColorAreaControl.vue'+import FormatControls from '@/components/ColorPickerPanel/FormatControls.vue'+import HueAlphaSliders from '@/components/ColorPickerPanel/HueAlphaSliders.vue'+import { provideColorPickerPanel } from '@/components/ColorPickerPanel/context'++const { color, okhcl = null } = defineProps<{+ color: Color+ okhcl?: OkHCLControls | null+}>()++const emit = defineEmits<{+ update: [color: Color]+}>()++provideColorPickerPanel(+ {+ get color() {+ return color+ },+ get okhcl() {+ return okhcl+ }+ },+ emit+)+</script>++<template>+ <div class="flex flex-col gap-2">+ <ColorAreaControl />+ <HueAlphaSliders />+ <FormatControls />+ </div>+</template>diff --git a/src/components/ColorPickerPanel/FormatControls.vue b/src/components/ColorPickerPanel/FormatControls.vuenew file mode 100644index 000000000..ee9787407--- /dev/null+++ b/src/components/ColorPickerPanel/FormatControls.vue@@ -0,0 +1,29 @@+<script setup lang="ts">+import AppSelect from '@/components/ui/AppSelect.vue'+import HsbFields from '@/components/ColorPickerPanel/HsbFields.vue'+import HslFields from '@/components/ColorPickerPanel/HslFields.vue'+import OkhclFields from '@/components/ColorPickerPanel/OkhclFields.vue'+import RgbFields from '@/components/ColorPickerPanel/RgbFields.vue'+import { useColorPickerPanelContext } from '@/components/ColorPickerPanel/context'++const ctx = useColorPickerPanelContext()+</script>++<template>+ <div class="flex flex-col gap-2">+ <AppSelect+ class="w-[120px]"+ test-id="color-format-select"+ :model-value="ctx.fieldFormat"+ :options="ctx.fieldOptions"+ @update:model-value="ctx.setFieldFormat"+ />++ <div class="min-w-0 flex flex-col gap-2">+ <RgbFields v-if="ctx.fieldFormat === 'rgb'" />+ <HslFields v-else-if="ctx.fieldFormat === 'hsl'" />+ <HsbFields v-else-if="ctx.fieldFormat === 'hsb'" />+ <OkhclFields v-else />+ </div>+ </div>+</template>diff --git a/src/components/ColorPickerPanel/HsbFields.vue b/src/components/ColorPickerPanel/HsbFields.vuenew file mode 100644index 000000000..be2e3984f--- /dev/null+++ b/src/components/ColorPickerPanel/HsbFields.vue@@ -0,0 +1,73 @@+<script setup lang="ts">+import { colorToCSS } from '@open-pencil/core/color'++import PickerSlider from '@/components/PickerSlider.vue'+import { useColorPickerPanelContext } from '@/components/ColorPickerPanel/context'++const ctx = useColorPickerPanelContext()+</script>++<template>+ <div+ class="grid grid-cols-[repeat(3,minmax(0,1fr))] gap-px overflow-hidden rounded border border-border bg-border"+ >+ <input+ type="number"+ class="bg-input px-2 py-1 text-xs text-surface outline-none"+ :value="Math.round(ctx.hsbColor.h)"+ min="0"+ max="360"+ @change="ctx.updateHSBChannelValue('h', +($event.target as HTMLInputElement).value)"+ />+ <input+ type="number"+ class="bg-input px-2 py-1 text-xs text-surface outline-none"+ :value="Math.round(ctx.hsbColor.s)"+ min="0"+ max="100"+ @change="ctx.updateHSBChannelValue('s', +($event.target as HTMLInputElement).value)"+ />+ <input+ type="number"+ class="bg-input px-2 py-1 text-xs text-surface outline-none"+ :value="Math.round(ctx.hsbColor.b)"+ min="0"+ max="100"+ @change="ctx.updateHSBChannelValue('b', +($event.target as HTMLInputElement).value)"+ />+ </div>++ <PickerSlider+ label="S"+ :model-value="ctx.hsbColor.s"+ :min="0"+ :max="100"+ :step="0.1"+ :display-value="Math.round(ctx.hsbColor.s)"+ :display-min="0"+ :display-max="100"+ :display-step="1"+ :gradient-style="ctx.sliderGradient.hsbSaturation"+ :thumb-fill="colorToCSS(ctx.sliderPreview.hsbSaturation)"+ test-id="color-slider-hsb-s"+ @update:model-value="ctx.updateHSBChannelValue('s', $event)"+ />++ <PickerSlider+ label="B"+ :model-value="ctx.hsbColor.b"+ :min="0"+ :max="100"+ :step="0.1"+ :display-value="Math.round(ctx.hsbColor.b)"+ :display-min="0"+ :display-max="100"+ :display-step="1"+ :gradient-style="ctx.sliderGradient.hsbBrightness"+ :thumb-fill="colorToCSS(ctx.sliderPreview.hsbBrightness)"+ test-id="color-slider-hsb-b"+ @update:model-value="ctx.updateHSBChannelValue('b', $event)"+ />++ <p class="text-[10px] leading-4 text-muted">{{ ctx.panels.colorHintHsb }}</p>+</template>diff --git a/src/components/ColorPickerPanel/HslFields.vue b/src/components/ColorPickerPanel/HslFields.vuenew file mode 100644index 000000000..7a0dec651--- /dev/null+++ b/src/components/ColorPickerPanel/HslFields.vue@@ -0,0 +1,73 @@+<script setup lang="ts">+import { colorToCSS } from '@open-pencil/core/color'++import PickerSlider from '@/components/PickerSlider.vue'+import { useColorPickerPanelContext } from '@/components/ColorPickerPanel/context'++const ctx = useColorPickerPanelContext()+</script>++<template>+ <div+ class="grid grid-cols-[repeat(3,minmax(0,1fr))] gap-px overflow-hidden rounded border border-border bg-border"+ >+ <input+ type="number"+ class="bg-input px-2 py-1 text-xs text-surface outline-none"+ :value="Math.round(ctx.hslColor.h ?? 0)"+ min="0"+ max="360"+ @change="ctx.updateHSLChannelValue('h', +($event.target as HTMLInputElement).value)"+ />+ <input+ type="number"+ class="bg-input px-2 py-1 text-xs text-surface outline-none"+ :value="Math.round(ctx.hslColor.s ?? 0)"+ min="0"+ max="100"+ @change="ctx.updateHSLChannelValue('s', +($event.target as HTMLInputElement).value)"+ />+ <input+ type="number"+ class="bg-input px-2 py-1 text-xs text-surface outline-none"+ :value="Math.round(ctx.hslColor.l ?? 0)"+ min="0"+ max="100"+ @change="ctx.updateHSLChannelValue('l', +($event.target as HTMLInputElement).value)"+ />+ </div>++ <PickerSlider+ label="S"+ :model-value="ctx.hslColor.s ?? 0"+ :min="0"+ :max="100"+ :step="0.1"+ :display-value="Math.round(ctx.hslColor.s ?? 0)"+ :display-min="0"+ :display-max="100"+ :display-step="1"+ :gradient-style="ctx.sliderGradient.hslSaturation"+ :thumb-fill="colorToCSS(ctx.sliderPreview.hslSaturation)"+ test-id="color-slider-hsl-s"+ @update:model-value="ctx.updateHSLChannelValue('s', $event)"+ />++ <PickerSlider+ label="L"+ :model-value="ctx.hslColor.l ?? 0"+ :min="0"+ :max="100"+ :step="0.1"+ :display-value="Math.round(ctx.hslColor.l ?? 0)"+ :display-min="0"+ :display-max="100"+ :display-step="1"+ :gradient-style="ctx.sliderGradient.hslLightness"+ :thumb-fill="colorToCSS(ctx.sliderPreview.hslLightness)"+ test-id="color-slider-hsl-l"+ @update:model-value="ctx.updateHSLChannelValue('l', $event)"+ />++ <p class="text-[10px] leading-4 text-muted">{{ ctx.panels.colorHintHsl }}</p>+</template>diff --git a/src/components/ColorPickerPanel/HueAlphaSliders.vue b/src/components/ColorPickerPanel/HueAlphaSliders.vuenew file mode 100644index 000000000..bdad174c5--- /dev/null+++ b/src/components/ColorPickerPanel/HueAlphaSliders.vue@@ -0,0 +1,39 @@+<script setup lang="ts">+import { colorToCSS } from '@open-pencil/core/color'++import PickerSlider from '@/components/PickerSlider.vue'+import { useColorPickerPanelContext } from '@/components/ColorPickerPanel/context'++const ctx = useColorPickerPanelContext()+</script>++<template>+ <template v-if="ctx.fieldFormat !== 'okhcl'">+ <PickerSlider+ label="H"+ :model-value="ctx.hslColor.h ?? 0"+ :min="0"+ :max="360"+ :step="1"+ gradient-style="background: linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000);"+ :thumb-fill="colorToCSS(ctx.sliderPreview.hue)"+ :ui="{ root: 'gap-0', label: 'hidden', input: 'hidden' }"+ test-id="color-slider-hue"+ @update:model-value="ctx.updateRGBAHue"+ />++ <PickerSlider+ label="A"+ :model-value="ctx.color.a"+ :min="0"+ :max="1"+ :step="0.001"+ checkerboard+ :gradient-style="`background: linear-gradient(to right, transparent, ${colorToCSS({ ...ctx.color, a: 1 })})`"+ :thumb-fill="colorToCSS(ctx.color)"+ :ui="{ root: 'gap-0', label: 'hidden', input: 'hidden' }"+ test-id="color-slider-alpha"+ @update:model-value="ctx.updateRGBAAlpha"+ />+ </template>+</template>diff --git a/src/components/ColorPickerPanel/OkhclFields.vue b/src/components/ColorPickerPanel/OkhclFields.vuenew file mode 100644index 000000000..70dee1be0--- /dev/null+++ b/src/components/ColorPickerPanel/OkhclFields.vue@@ -0,0 +1,94 @@+<script setup lang="ts">+import { colorToCSS } from '@open-pencil/core/color'+import { fromPercent, toPercent } from '@open-pencil/vue'++import PickerSlider from '@/components/PickerSlider.vue'+import { useColorPickerPanelContext } from '@/components/ColorPickerPanel/context'++const ctx = useColorPickerPanelContext()+</script>++<template>+ <div v-if="ctx.isOkHCLFormat && ctx.okhcl?.okhcl" class="flex flex-col gap-2">+ <PickerSlider+ label="H"+ :model-value="ctx.okhcl.okhcl.h"+ :min="0"+ :max="360"+ :step="1"+ :display-value="Math.round(ctx.okhcl.okhcl.h)"+ :display-min="0"+ :display-max="360"+ :display-step="1"+ gradient-style="background: linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000);"+ :thumb-fill="colorToCSS(ctx.okhclSliderPreview?.okhclHue ?? ctx.color)"+ test-id="color-slider-okhcl-h"+ @update:model-value="ctx.updateOkHCLChannel('h', $event)"+ />++ <PickerSlider+ label="C"+ :model-value="ctx.okhcl.okhcl.c"+ :min="0"+ :max="0.4"+ :step="0.001"+ :display-value="toPercent(ctx.okhcl.okhcl.c)"+ :display-min="0"+ :display-max="40"+ :display-step="1"+ :parse-display="fromPercent"+ :gradient-style="ctx.okhclSliderGradient?.okhclChroma ?? undefined"+ :thumb-fill="colorToCSS(ctx.okhclSliderPreview?.okhclChroma ?? ctx.color)"+ test-id="color-slider-okhcl-c"+ @update:model-value="ctx.updateOkHCLChannel('c', $event)"+ />++ <PickerSlider+ label="L"+ :model-value="ctx.okhcl.okhcl.l"+ :min="0"+ :max="1"+ :step="0.001"+ :display-value="toPercent(ctx.okhcl.okhcl.l)"+ :display-min="0"+ :display-max="100"+ :display-step="1"+ :parse-display="fromPercent"+ :gradient-style="ctx.okhclSliderGradient?.okhclLightness ?? undefined"+ :thumb-fill="colorToCSS(ctx.okhclSliderPreview?.okhclLightness ?? ctx.color)"+ test-id="color-slider-okhcl-l"+ @update:model-value="ctx.updateOkHCLChannel('l', $event)"+ />++ <PickerSlider+ label="A"+ :model-value="ctx.okhcl.okhcl.a ?? 1"+ :min="0"+ :max="1"+ :step="0.001"+ :display-value="toPercent(ctx.okhcl.okhcl.a ?? 1)"+ :display-min="0"+ :display-max="100"+ :display-step="1"+ :parse-display="fromPercent"+ checkerboard+ :gradient-style="`background: linear-gradient(to right, transparent, ${colorToCSS(ctx.color)})`"+ :thumb-fill="colorToCSS(ctx.color)"+ test-id="color-slider-okhcl-a"+ @update:model-value="ctx.updateOkHCLChannel('a', $event)"+ />++ <div class="flex items-start justify-between gap-2 text-[10px] text-muted">+ <p class="min-w-0 flex-1 leading-4 break-words">{{ ctx.panels.colorHintOkhcl }}</p>+ <span+ v-if="ctx.okhcl.previewColorSpace"+ class="shrink-0 rounded border border-border px-1 py-0.5 text-[10px] uppercase"+ >+ {{ ctx.okhcl.previewColorSpace }}+ </span>+ </div>+ <p v-if="ctx.okhcl.clipped" class="text-[10px] leading-4 text-amber-400">+ {{ ctx.panels.colorPreviewClipped({ space: ctx.okhcl.previewColorSpace ?? 'display-p3' }) }}+ </p>+ </div>+</template>diff --git a/src/components/ColorPickerPanel/RgbFields.vue b/src/components/ColorPickerPanel/RgbFields.vuenew file mode 100644index 000000000..ca5d44c66--- /dev/null+++ b/src/components/ColorPickerPanel/RgbFields.vue@@ -0,0 +1,36 @@+<script setup lang="ts">+import { useColorPickerPanelContext } from '@/components/ColorPickerPanel/context'++const ctx = useColorPickerPanelContext()+</script>++<template>+ <div+ class="grid grid-cols-[repeat(3,minmax(0,1fr))] gap-px overflow-hidden rounded border border-border bg-border"+ >+ <input+ type="number"+ class="bg-input px-2 py-1 text-xs text-surface outline-none"+ :value="Math.round(ctx.rgbColor.r)"+ min="0"+ max="255"+ @change="ctx.updateRGBChannelValue('r', +($event.target as HTMLInputElement).value)"+ />+ <input+ type="number"+ class="bg-input px-2 py-1 text-xs text-surface outline-none"+ :value="Math.round(ctx.rgbColor.g)"+ min="0"+ max="255"+ @change="ctx.updateRGBChannelValue('g', +($event.target as HTMLInputElement).value)"+ />+ <input+ type="number"+ class="bg-input px-2 py-1 text-xs text-surface outline-none"+ :value="Math.round(ctx.rgbColor.b)"+ min="0"+ max="255"+ @change="ctx.updateRGBChannelValue('b', +($event.target as HTMLInputElement).value)"+ />+ </div>+</template>diff --git a/src/components/ColorPickerPanel/context.ts b/src/components/ColorPickerPanel/context.tsnew file mode 100644index 000000000..7bc5c9ba4--- /dev/null+++ b/src/components/ColorPickerPanel/context.ts@@ -0,0 +1,137 @@+import { computed, inject, provide, proxyRefs } from 'vue'++import {+ createColorPickerModel,+ createOkHCLSliderGradientModel,+ createOkHCLSliderPreviewModel,+ createSliderGradientModel,+ createSliderPreviewModel,+ rekaToAppColor,+ updateAlpha,+ updateHSBChannel,+ updateHSLChannel,+ updateHue,+ updateRGBChannel,+ useI18n+} from '@open-pencil/vue'++import type { Color } from '@open-pencil/core/types'+import type { OkHCLControls } from '@open-pencil/vue'+import type { InjectionKey, ShallowUnwrapRef } from 'vue'++type ColorPanelProps = {+ color: Color+ okhcl?: OkHCLControls | null+}++type ColorPanelEmit = (event: 'update', color: Color) => void++type RekaColor = ReturnType<typeof createColorPickerModel>['rekaColor']++function createColorPickerPanelContext(props: ColorPanelProps, emit: ColorPanelEmit) {+ const { panels } = useI18n()+ const color = computed(() => props.color)+ const okhcl = computed(() => props.okhcl ?? null)+ const pickerModel = computed(() => createColorPickerModel(color.value))+ const rekaColor = computed(() => pickerModel.value.rekaColor)+ const hslColor = computed(() => pickerModel.value.hsl)+ const hsbColor = computed(() => pickerModel.value.hsb)+ const rgbColor = computed(() => pickerModel.value.rgb)+ const sliderPreview = computed(() => createSliderPreviewModel(pickerModel.value))+ const sliderGradient = computed(() => createSliderGradientModel(pickerModel.value))+ const okhclSliderPreview = computed(() =>+ okhcl.value?.okhcl ? createOkHCLSliderPreviewModel(okhcl.value.okhcl) : null+ )+ const okhclSliderGradient = computed(() =>+ okhcl.value?.okhcl ? createOkHCLSliderGradientModel(okhcl.value.okhcl) : null+ )+ const fieldOptions = computed(+ () =>+ okhcl.value?.fieldOptions ?? [+ { value: 'rgb', label: panels.value.colorFormatRgb },+ { value: 'hsl', label: panels.value.colorFormatHsl },+ { value: 'hsb', label: panels.value.colorFormatHsb }+ ]+ )+ const fieldFormat = computed(() => okhcl.value?.fieldFormat ?? 'rgb')+ const isOkHCLFormat = computed(() => fieldFormat.value === 'okhcl' && okhcl.value)++ function updateColor(nextColor: Color) {+ emit('update', nextColor)+ }++ function onRekaColorUpdate(colorValue: RekaColor) {+ updateColor(rekaToAppColor(colorValue))+ }++ function setFieldFormat(value: string) {+ okhcl.value?.setFieldFormat(value as NonNullable<OkHCLControls>['fieldFormat'])+ }++ function updateRGBAHue(value: number) {+ updateColor(updateHue(pickerModel.value, value))+ }++ function updateRGBAAlpha(value: number) {+ updateColor(updateAlpha(color.value, value))+ }++ function updateRGBChannelValue(channel: 'r' | 'g' | 'b', value: number) {+ updateColor(updateRGBChannel(color.value, channel, value))+ }++ function updateHSLChannelValue(channel: 'h' | 's' | 'l', value: number) {+ updateColor(updateHSLChannel(pickerModel.value, channel, value))+ }++ function updateHSBChannelValue(channel: 'h' | 's' | 'b', value: number) {+ updateColor(updateHSBChannel(pickerModel.value, channel, value))+ }++ function updateOkHCLChannel(channel: 'h' | 'c' | 'l' | 'a', value: number) {+ okhcl.value?.updateOkHCL({ [channel]: value })+ }++ return {+ panels,+ color,+ okhcl,+ pickerModel,+ rekaColor,+ hslColor,+ hsbColor,+ rgbColor,+ sliderPreview,+ sliderGradient,+ okhclSliderPreview,+ okhclSliderGradient,+ fieldOptions,+ fieldFormat,+ isOkHCLFormat,+ onRekaColorUpdate,+ setFieldFormat,+ updateRGBAHue,+ updateRGBAAlpha,+ updateRGBChannelValue,+ updateHSLChannelValue,+ updateHSBChannelValue,+ updateOkHCLChannel+ }+}++export type ColorPickerPanelContext = ShallowUnwrapRef<+ ReturnType<typeof createColorPickerPanelContext>+>++const COLOR_PICKER_PANEL_KEY: InjectionKey<ColorPickerPanelContext> =+ Symbol('ColorPickerPanelContext')++export function provideColorPickerPanel(props: ColorPanelProps, emit: ColorPanelEmit) {+ provide(COLOR_PICKER_PANEL_KEY, proxyRefs(createColorPickerPanelContext(props, emit)))+}++export function useColorPickerPanelContext(): ColorPickerPanelContext {+ const ctx = inject(COLOR_PICKER_PANEL_KEY)+ if (!ctx) throw new Error('Color picker panel controls must be used within ColorPickerPanel')+ return ctx+}diff --git a/src/components/DesignPanel.vue b/src/components/DesignPanel.vueindex 7d7aa7575..df8c08d41 100644--- a/src/components/DesignPanel.vue+++ b/src/components/DesignPanel.vue@@ -8,7 +8,7 @@ import AppearanceSection from './properties/AppearanceSection.vue'import EffectsSection from './properties/EffectsSection.vue'import ExportSection from './properties/ExportSection.vue'import FillSection from './properties/FillSection.vue'-import LayoutSection from './properties/LayoutSection.vue'+import LayoutSection from './properties/LayoutSection/LayoutSection.vue'import PageSection from './properties/PageSection.vue'import PositionSection from './properties/PositionSection.vue'import StrokeSection from './properties/StrokeSection.vue'diff --git a/src/components/EditorCanvas.vue b/src/components/EditorCanvas.vueindex 51d7199dc..7c560d3a5 100644--- a/src/components/EditorCanvas.vue+++ b/src/components/EditorCanvas.vue@@ -1,27 +1,33 @@<script setup lang="ts">-import { ref, computed, watch } from 'vue'+import { ref, computed } from 'vue'import { ContextMenuRoot, ContextMenuTrigger, ContextMenuPortal } from 'reka-ui'import { toolCursor, useCanvas, useCanvasDrop, useCanvasInput, useTextEdit } from '@open-pencil/vue'-import { useCollabInjected } from '@/composables/use-collab'-import { useEditorStore } from '@/stores/editor'+import { useCollabInjected } from '@/app/collab/use'+import { useEditorStore } from '@/app/editor/active-store'+import { useCanvasCollaborationAwareness } from '@/app/editor/canvas/collaboration-awareness'+import { createCanvasContextSelection } from '@/app/editor/canvas/context-selection'+import { fadeOutGlobalLoader } from '@/app/editor/canvas/loader-overlay'import CanvasMenu from './CanvasMenu.vue'const store = useEditorStore()const collab = useCollabInjected()+const sceneCanvasRef = ref<HTMLCanvasElement | null>(null)const canvasRef = ref<HTMLCanvasElement | null>(null)+const { updateCursor } = useCanvasCollaborationAwareness(store, collab)+const { selectAtContextPoint } = createCanvasContextSelection(canvasRef, store)++useCanvas(sceneCanvasRef, store, {+ layer: 'scene',+ showRulers: false,+ onReady: fadeOutGlobalLoader+})const { hitTestSectionTitle, hitTestComponentLabel, hitTestFrameTitle } = useCanvas(canvasRef,store,{- onReady() {- const loader = document.getElementById('loader')- if (loader) {- loader.classList.add('fade-out')- setTimeout(() => loader.remove(), 300)- }- }+ layer: 'overlays'})const { cursorOverride } = useCanvasInput(@@ -30,45 +36,34 @@ const { cursorOverride } = useCanvasInput(hitTestSectionTitle,hitTestComponentLabel,hitTestFrameTitle,- (cx, cy) => {- store.state.cursorCanvasX = cx- store.state.cursorCanvasY = cy- collab?.updateCursor(cx, cy, store.state.currentPageId)- }+ updateCursor)useTextEdit(canvasRef, store)const { isDraggingOver } = useCanvasDrop(canvasRef, store)-watch(- () => [...store.state.selectedIds],- (ids) => collab?.updateSelection(ids)-)-const cursor = computed(() => toolCursor(store.state.activeTool, cursorOverride.value))--function onContextMenu(e: MouseEvent) {- const canvas = canvasRef.value- if (!canvas) return- const rect = canvas.getBoundingClientRect()- const { x: cx, y: cy } = store.screenToCanvas(e.clientX - rect.left, e.clientY - rect.top)- store.selectAtPoint(cx, cy)-}</script><template><ContextMenuRoot :modal="false">- <ContextMenuTrigger as-child @contextmenu="onContextMenu">+ <ContextMenuTrigger as-child @contextmenu="selectAtContextPoint"><divdata-test-id="canvas-area"class="canvas-area relative min-h-0 min-w-0 flex-1 overflow-hidden">+ <canvas+ ref="sceneCanvasRef"+ data-test-id="scene-canvas-element"+ aria-hidden="true"+ class="pointer-events-none absolute inset-0 size-full outline-none"+ /><canvasref="canvasRef"data-test-id="canvas-element"tabindex="-1":style="{ cursor }"- class="block size-full touch-none outline-none"+ class="absolute inset-0 block size-full touch-none outline-none"/><Transitionenter-active-class="transition-opacity duration-150"diff --git a/src/components/FillPicker.vue b/src/components/FillPicker.vueindex 4ee7245a4..3ccbc23a4 100644--- a/src/components/FillPicker.vue+++ b/src/components/FillPicker.vue@@ -4,13 +4,13 @@ import { twMerge } from 'tailwind-merge'import { applySolidFillColor, FillPickerRoot, useI18n } from '@open-pencil/vue'import GradientEditor from './GradientEditor.vue'-import ColorPickerPanel from './ColorPickerPanel.vue'+import ColorPickerPanel from '@/components/ColorPickerPanel/ColorPickerPanel.vue'import ImageFillPicker from './ImageFillPicker.vue'import Tip from './ui/Tip.vue'import { usePopoverUI } from './ui/popover'-import type { Fill } from '@open-pencil/core'-import type { OkHCLControls } from '@open-pencil/vue/ColorPicker/types'+import type { Fill } from '@open-pencil/core/scene-graph'+import type { OkHCLControls } from '@open-pencil/vue'const TAB_BASE ='flex size-6 cursor-pointer items-center justify-center rounded border-none p-0 transition-colors'diff --git a/src/components/FontPicker.vue b/src/components/FontPicker.vueindex 56e02b43a..8657b4ba2 100644--- a/src/components/FontPicker.vue+++ b/src/components/FontPicker.vue@@ -3,7 +3,7 @@ import { FontPickerRoot } from '@open-pencil/vue'import { useSelectUI } from '@/components/ui/select'import { usePopoverUI } from '@/components/ui/popover'-import { listFamilies } from '@/engine/fonts'+import { listFamilies } from '@/app/editor/fonts'const modelValue = defineModel<string>({ required: true })const emit = defineEmits<{ select: [family: string] }>()diff --git a/src/components/GradientEditor.vue b/src/components/GradientEditor.vueindex af6f00c70..d9e86e295 100644--- a/src/components/GradientEditor.vue+++ b/src/components/GradientEditor.vue@@ -1,9 +1,9 @@<script setup lang="ts">import AppSelect from './ui/AppSelect.vue'import Tip from './ui/Tip.vue'-import ColorPickerPanel from './ColorPickerPanel.vue'+import ColorPickerPanel from '@/components/ColorPickerPanel/ColorPickerPanel.vue'import ScrubInput from './ScrubInput.vue'-import { colorToCSS } from '@open-pencil/core'+import { colorToCSS } from '@open-pencil/core/color'import {GradientEditorRoot,GradientEditorBar,@@ -11,7 +11,7 @@ import {useI18n} from '@open-pencil/vue'-import type { Fill } from '@open-pencil/core'+import type { Fill } from '@open-pencil/core/scene-graph'const { fill } = defineProps<{ fill: Fill }>()const emit = defineEmits<{ update: [fill: Fill] }>()diff --git a/src/components/ImageFillPicker.vue b/src/components/ImageFillPicker.vueindex 350c0bfed..161dfc9b9 100644--- a/src/components/ImageFillPicker.vue+++ b/src/components/ImageFillPicker.vue@@ -4,9 +4,9 @@ import { useFileDialog, useObjectUrl } from '@vueuse/core'import AppSelect from './ui/AppSelect.vue'-import { useEditorStore } from '@/stores/editor'+import { useEditorStore } from '@/app/editor/active-store'-import type { Fill, ImageScaleMode } from '@open-pencil/core'+import type { Fill, ImageScaleMode } from '@open-pencil/core/scene-graph'const IMAGE_SCALE_MODES: { value: ImageScaleMode; label: string }[] = [{ value: 'FILL', label: 'Fill' },diff --git a/src/components/LayerTree.vue b/src/components/LayerTree.vueindex e870efaeb..db7b514a0 100644--- a/src/components/LayerTree.vue+++ b/src/components/LayerTree.vue@@ -1,4 +1,5 @@<script setup lang="ts">+import { useAttrs } from 'vue'import { TreeRoot, TreeItem, ContextMenuRoot, ContextMenuTrigger, ContextMenuPortal } from 'reka-ui'import {@@ -8,12 +9,15 @@ import {useInlineRename,useLayerDrag} from '@open-pencil/vue'-import { useEditorStore } from '@/stores/editor'-import { nodeIcon, COMPONENT_TYPES } from '@/utils/layer-icons'+import { useEditorStore } from '@/app/editor/active-store'+import { nodeIcon, COMPONENT_TYPES } from '@/app/editor/icons'import CanvasMenu from './CanvasMenu.vue'import Tip from './ui/Tip.vue'+defineOptions({ inheritAttrs: false })+const INDENT = 16+const attrs = useAttrs()const store = useEditorStore()const rename = useInlineRename((id, name) => store.renameNode(id, name))const { menu: t } = useI18n()@@ -43,7 +47,7 @@ function onTreeSelect(e: CustomEvent, select: (additive: boolean) => void) {><ContextMenuRoot :modal="false"><ContextMenuTrigger as-child @contextmenu="onLayerRightClick">- <div class="relative scrollbar-thin flex-1 overflow-y-auto px-1">+ <div v-bind="attrs" class="relative scrollbar-thin flex-1 overflow-y-auto px-1"><TreeRoot:key="treeKey"v-slot="{ flattenItems }"diff --git a/src/components/MobileDrawer.vue b/src/components/MobileDrawer.vueindex 1537630fe..e894422fb 100644--- a/src/components/MobileDrawer.vue+++ b/src/components/MobileDrawer.vue@@ -18,7 +18,7 @@ import {SWIPE_THRESHOLD,SWIPE_VELOCITY_THRESHOLD} from '@/constants'-import { useEditorStore } from '@/stores/editor'+import { useEditorStore } from '@/app/editor/active-store'type Snap = 'closed' | 'half' | 'full'type DrawerTab = 'layers' | 'design' | 'code' | 'ai'diff --git a/src/components/MobileHud.vue b/src/components/MobileHud.vuedeleted file mode 100644index 729b79b97..000000000--- a/src/components/MobileHud.vue+++ /dev/null@@ -1,248 +0,0 @@-<script setup lang="ts">-import { useClipboard } from '@vueuse/core'-import { computed } from 'vue'-import { useRouter } from 'vue-router'-import {- PopoverRoot,- PopoverTrigger,- PopoverPortal,- PopoverContent,- DropdownMenuRoot,- DropdownMenuTrigger,- DropdownMenuPortal,- DropdownMenuContent,- DropdownMenuItem-} from 'reka-ui'--import IconFilePlus from '~icons/lucide/file-plus'-import IconFolderOpen from '~icons/lucide/folder-open'-import IconImageDown from '~icons/lucide/image-down'-import IconSave from '~icons/lucide/save'-import IconZoomIn from '~icons/lucide/zoom-in'--import { menu, useMenuUI } from '@/components/ui/menu'-import { openFileDialog } from '@/composables/use-menu'-import { DEFAULT_COLLAB_STATE, useCollabInjected } from '@/composables/use-collab'-import { toast } from '@/utils/toast'-import { useEditorStore } from '@/stores/editor'-import Tip from '@/components/ui/Tip.vue'-import { colorToCSS } from '@open-pencil/core'-import { useEditorCommands, useI18n } from '@open-pencil/vue'-import { toolIcons } from '@/utils/tools'-import { initials } from '@/utils/text'--import type { Component } from 'vue'--const router = useRouter()-const collab = useCollabInjected()-const store = useEditorStore()-const { copy } = useClipboard()-const { dialogs } = useI18n()--const collabState = computed(() => collab?.state.value ?? DEFAULT_COLLAB_STATE)-const collabPeers = computed(() => collab?.remotePeers.value ?? [])-const followingPeer = computed(() => collab?.followingPeer.value ?? null)-const { getCommand } = useEditorCommands()--function onShare() {- if (!collab) return- const roomId = collab.shareCurrentDoc()- router.push(`/share/${roomId}`)- copy(`${window.location.origin}/share/${roomId}`)- toast.info('Link copied to clipboard')-}--function onDisconnect() {- if (!collab) return- collab.disconnect()- router.push('/')-}--const activeToolIcon = computed(() => toolIcons[store.state.activeTool])-const menuCls = useMenuUI({- content: 'w-48 rounded-xl p-1.5 shadow-xl',- item: 'w-full gap-2.5 rounded-lg border-none bg-transparent px-2.5 py-2 active:bg-hover'-})--interface MenuAction {- icon: Component- label: string- action: () => void-}--const menuItems: MenuAction[] = [- {- icon: IconFilePlus,- label: 'New',- action: () => import('@/stores/tabs').then((m) => m.createTab())- },- { icon: IconFolderOpen, label: 'Open…', action: () => openFileDialog() },- { icon: IconSave, label: 'Save', action: () => store.saveFigFile() },- {- icon: IconImageDown,- label: 'Export…',- action: () => store.exportSelection(1, 'png')- },- { icon: IconZoomIn, label: 'Zoom to fit', action: () => getCommand('view.zoomFit').run() }-]--const onlineCount = computed(() => collabPeers.value.length + 1)-</script>--<template>- <div- class="pointer-events-none absolute inset-x-0 top-0 z-10 flex items-start px-3 pt-3"- @touchstart.stop- >- <!-- Undo / Redo + active tool indicator -->- <div class="pointer-events-auto flex flex-col items-start gap-1.5">- <div class="flex gap-1.5">- <Tip label="Undo">- <button- class="flex size-8 cursor-pointer items-center justify-center rounded-full border border-white/10 bg-panel/70 shadow-md backdrop-blur-xl select-none active:bg-hover"- @click="getCommand('edit.undo').run()"- >- <icon-lucide-undo-2 class="size-3.5 text-surface" />- </button>- </Tip>- <Tip label="Redo">- <button- class="flex size-8 cursor-pointer items-center justify-center rounded-full border border-white/10 bg-panel/70 shadow-md backdrop-blur-xl select-none active:bg-hover"- @click="getCommand('edit.redo').run()"- >- <icon-lucide-redo-2 class="size-3.5 text-surface" />- </button>- </Tip>- </div>- <div- class="flex size-8 items-center justify-center rounded-full border border-accent/20 bg-panel/70 shadow-md backdrop-blur-xl transition-colors duration-200"- >- <Transition- mode="out-in"- enter-active-class="animate-in fade-in zoom-in-75 duration-150"- leave-active-class="animate-out fade-out zoom-out-75 duration-150"- >- <component- :is="activeToolIcon"- :key="store.state.activeTool"- class="size-3.5 text-accent"- />- </Transition>- </div>- </div>-- <!-- Center: Online badge + action toast -->- <div class="pointer-events-auto relative mx-auto flex flex-col items-center gap-1.5">- <!-- Online badge with peers popover -->- <PopoverRoot v-if="collabState.connected">- <PopoverTrigger as-child>- <button- class="flex h-8 cursor-pointer items-center gap-1.5 rounded-full border border-white/10 bg-panel/70 px-3 shadow-md backdrop-blur-xl select-none active:bg-hover"- >- <span class="size-2 rounded-full bg-green-500" />- <span class="text-xs text-surface">Online: {{ onlineCount }}</span>- </button>- </PopoverTrigger>- <PopoverPortal>- <PopoverContent- :modal="false"- :side-offset="8"- side="bottom"- align="center"- class="z-50 w-56 rounded-xl border border-border bg-panel p-3 shadow-xl"- >- <div class="mb-2 text-[11px] tracking-wider text-muted uppercase">In this room</div>- <div class="flex flex-col gap-2">- <div class="flex items-center gap-2">- <div- class="flex size-7 shrink-0 items-center justify-center rounded-full text-[10px] font-semibold text-white"- :style="{ background: colorToCSS(collabState.localColor) }"- >- {{ initials(collabState.localName || 'You') }}- </div>- <span class="min-w-0 flex-1 truncate text-xs text-surface">- {{ collabState.localName || 'You' }}- </span>- <span class="text-[10px] text-muted">you</span>- </div>-- <div- v-for="peer in collabPeers"- :key="peer.clientId"- class="flex cursor-pointer items-center gap-2 rounded-md px-0.5 py-0.5 select-none active:bg-hover"- @click="collab?.followPeer(followingPeer === peer.clientId ? null : peer.clientId)"- >- <div- class="flex size-7 shrink-0 items-center justify-center rounded-full text-[10px] font-semibold text-white"- :class="followingPeer === peer.clientId ? 'ring-2 ring-white/40' : ''"- :style="{ background: colorToCSS(peer.color) }"- >- {{ initials(peer.name) }}- </div>- <span class="min-w-0 flex-1 truncate text-xs text-surface">{{ peer.name }}</span>- <span v-if="followingPeer === peer.clientId" class="text-[10px] text-accent"- >following</span- >- </div>- </div>-- <button- class="mt-3 flex h-7 w-full cursor-pointer items-center justify-center rounded border border-border bg-transparent text-xs text-muted select-none active:bg-hover"- @click="onDisconnect"- >- Disconnect- </button>- </PopoverContent>- </PopoverPortal>- </PopoverRoot>-- <!-- Action toast -->- <Transition- enter-active-class="animate-in fade-in duration-150"- leave-active-class="animate-out fade-out duration-200"- >- <div- v-if="store.state.actionToast"- :key="store.state.actionToast"- class="flex h-8 items-center rounded-full border border-accent/20 bg-panel/70 px-3 shadow-md backdrop-blur-xl"- >- <span class="text-xs whitespace-nowrap text-accent">{{ store.state.actionToast }}</span>- </div>- </Transition>- </div>-- <!-- Share + Menu -->- <div class="pointer-events-auto flex items-center gap-1.5">- <button- class="flex h-8 cursor-pointer items-center gap-1.5 rounded-full border border-white/10 bg-panel/70 px-3 shadow-md backdrop-blur-xl select-none active:bg-hover"- @click="onShare"- >- <icon-lucide-share-2 class="size-3.5 text-surface" />- <span class="text-xs text-surface">{{ dialogs.share }}</span>- </button>-- <DropdownMenuRoot>- <DropdownMenuTrigger as-child>- <button- class="flex size-8 cursor-pointer items-center justify-center rounded-full border border-white/10 bg-panel/70 shadow-md backdrop-blur-xl select-none active:bg-hover"- >- <icon-lucide-menu class="size-3.5 text-surface" />- </button>- </DropdownMenuTrigger>- <DropdownMenuPortal>- <DropdownMenuContent :side-offset="8" side="bottom" align="end" :class="menuCls.content">- <DropdownMenuItem- v-for="item in menuItems"- :key="item.label"- :class="menu({ justify: 'start' }).item({ class: menuCls.item })"- @click="item.action()"- >- <component :is="item.icon" class="size-4 text-muted" />- <span>{{ item.label }}</span>- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenuPortal>- </DropdownMenuRoot>- </div>- </div>-</template>diff --git a/src/components/MobileHud/MobileActionToast.vue b/src/components/MobileHud/MobileActionToast.vuenew file mode 100644index 000000000..9baa3ca79--- /dev/null+++ b/src/components/MobileHud/MobileActionToast.vue@@ -0,0 +1,20 @@+<script setup lang="ts">+import { useMobileHudContext } from '@/components/MobileHud/context'++const hud = useMobileHudContext()+</script>++<template>+ <Transition+ enter-active-class="animate-in fade-in duration-150"+ leave-active-class="animate-out fade-out duration-200"+ >+ <div+ v-if="hud.actionToast"+ :key="hud.actionToast"+ class="flex h-8 items-center rounded-full border border-accent/20 bg-panel/70 px-3 shadow-md backdrop-blur-xl"+ >+ <span class="text-xs whitespace-nowrap text-accent">{{ hud.actionToast }}</span>+ </div>+ </Transition>+</template>diff --git a/src/components/MobileHud/MobileActiveToolBadge.vue b/src/components/MobileHud/MobileActiveToolBadge.vuenew file mode 100644index 000000000..770375851--- /dev/null+++ b/src/components/MobileHud/MobileActiveToolBadge.vue@@ -0,0 +1,23 @@+<script setup lang="ts">+import { useMobileHudContext } from '@/components/MobileHud/context'++const hud = useMobileHudContext()+</script>++<template>+ <div+ class="flex size-8 items-center justify-center rounded-full border border-accent/20 bg-panel/70 shadow-md backdrop-blur-xl transition-colors duration-200"+ >+ <Transition+ mode="out-in"+ enter-active-class="animate-in fade-in zoom-in-75 duration-150"+ leave-active-class="animate-out fade-out zoom-out-75 duration-150"+ >+ <component+ :is="hud.activeToolIcon"+ :key="hud.store.state.activeTool"+ class="size-3.5 text-accent"+ />+ </Transition>+ </div>+</template>diff --git a/src/components/MobileHud/MobileFileMenu.vue b/src/components/MobileHud/MobileFileMenu.vuenew file mode 100644index 000000000..e279c37ac--- /dev/null+++ b/src/components/MobileHud/MobileFileMenu.vue@@ -0,0 +1,43 @@+<script setup lang="ts">+import {+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuPortal,+ DropdownMenuRoot,+ DropdownMenuTrigger+} from 'reka-ui'++import { menu, useMenuUI } from '@/components/ui/menu'+import { useMobileHudContext } from '@/components/MobileHud/context'++const hud = useMobileHudContext()+const menuCls = useMenuUI({+ content: 'w-48 rounded-xl p-1.5 shadow-xl',+ item: 'w-full gap-2.5 rounded-lg border-none bg-transparent px-2.5 py-2 active:bg-hover'+})+</script>++<template>+ <DropdownMenuRoot>+ <DropdownMenuTrigger as-child>+ <button+ class="flex size-8 cursor-pointer items-center justify-center rounded-full border border-white/10 bg-panel/70 shadow-md backdrop-blur-xl select-none active:bg-hover"+ >+ <icon-lucide-menu class="size-3.5 text-surface" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuPortal>+ <DropdownMenuContent :side-offset="8" side="bottom" align="end" :class="menuCls.content">+ <DropdownMenuItem+ v-for="item in hud.menuItems"+ :key="item.label"+ :class="menu({ justify: 'start' }).item({ class: menuCls.item })"+ @click="item.action()"+ >+ <component :is="item.icon" class="size-4 text-muted" />+ <span>{{ item.label }}</span>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenuPortal>+ </DropdownMenuRoot>+</template>diff --git a/src/components/MobileHud/MobileHud.vue b/src/components/MobileHud/MobileHud.vuenew file mode 100644index 000000000..a10899bd9--- /dev/null+++ b/src/components/MobileHud/MobileHud.vue@@ -0,0 +1,33 @@+<script setup lang="ts">+import MobileActionToast from '@/components/MobileHud/MobileActionToast.vue'+import MobileActiveToolBadge from '@/components/MobileHud/MobileActiveToolBadge.vue'+import MobileFileMenu from '@/components/MobileHud/MobileFileMenu.vue'+import MobilePresencePopover from '@/components/MobileHud/MobilePresencePopover.vue'+import MobileShareButton from '@/components/MobileHud/MobileShareButton.vue'+import MobileUndoRedo from '@/components/MobileHud/MobileUndoRedo.vue'+import { provideMobileHud } from '@/components/MobileHud/context'++provideMobileHud()+</script>++<template>+ <div+ class="pointer-events-none absolute inset-x-0 top-0 z-10 flex items-start px-3 pt-3"+ @touchstart.stop+ >+ <div class="pointer-events-auto flex flex-col items-start gap-1.5">+ <MobileUndoRedo />+ <MobileActiveToolBadge />+ </div>++ <div class="pointer-events-auto relative mx-auto flex flex-col items-center gap-1.5">+ <MobilePresencePopover />+ <MobileActionToast />+ </div>++ <div class="pointer-events-auto flex items-center gap-1.5">+ <MobileShareButton />+ <MobileFileMenu />+ </div>+ </div>+</template>diff --git a/src/components/MobileHud/MobilePresencePopover.vue b/src/components/MobileHud/MobilePresencePopover.vuenew file mode 100644index 000000000..979d71888--- /dev/null+++ b/src/components/MobileHud/MobilePresencePopover.vue@@ -0,0 +1,73 @@+<script setup lang="ts">+import { PopoverContent, PopoverPortal, PopoverRoot, PopoverTrigger } from 'reka-ui'++import { initials } from '@/app/shell/ui'+import { colorToCSS } from '@open-pencil/core/color'+import { useMobileHudContext } from '@/components/MobileHud/context'++const hud = useMobileHudContext()+</script>++<template>+ <PopoverRoot v-if="hud.collabState.connected">+ <PopoverTrigger as-child>+ <button+ class="flex h-8 cursor-pointer items-center gap-1.5 rounded-full border border-white/10 bg-panel/70 px-3 shadow-md backdrop-blur-xl select-none active:bg-hover"+ >+ <span class="size-2 rounded-full bg-green-500" />+ <span class="text-xs text-surface">Online: {{ hud.onlineCount }}</span>+ </button>+ </PopoverTrigger>+ <PopoverPortal>+ <PopoverContent+ :modal="false"+ :side-offset="8"+ side="bottom"+ align="center"+ class="z-50 w-56 rounded-xl border border-border bg-panel p-3 shadow-xl"+ >+ <div class="mb-2 text-[11px] tracking-wider text-muted uppercase">In this room</div>+ <div class="flex flex-col gap-2">+ <div class="flex items-center gap-2">+ <div+ class="flex size-7 shrink-0 items-center justify-center rounded-full text-[10px] font-semibold text-white"+ :style="{ background: colorToCSS(hud.collabState.localColor) }"+ >+ {{ initials(hud.collabState.localName || 'You') }}+ </div>+ <span class="min-w-0 flex-1 truncate text-xs text-surface">+ {{ hud.collabState.localName || 'You' }}+ </span>+ <span class="text-[10px] text-muted">you</span>+ </div>++ <div+ v-for="peer in hud.collabPeers"+ :key="peer.clientId"+ class="flex cursor-pointer items-center gap-2 rounded-md px-0.5 py-0.5 select-none active:bg-hover"+ @click="hud.toggleFollowPeer(peer.clientId)"+ >+ <div+ class="flex size-7 shrink-0 items-center justify-center rounded-full text-[10px] font-semibold text-white"+ :class="hud.followingPeer === peer.clientId ? 'ring-2 ring-white/40' : ''"+ :style="{ background: colorToCSS(peer.color) }"+ >+ {{ initials(peer.name) }}+ </div>+ <span class="min-w-0 flex-1 truncate text-xs text-surface">{{ peer.name }}</span>+ <span v-if="hud.followingPeer === peer.clientId" class="text-[10px] text-accent">+ following+ </span>+ </div>+ </div>++ <button+ class="mt-3 flex h-7 w-full cursor-pointer items-center justify-center rounded border border-border bg-transparent text-xs text-muted select-none active:bg-hover"+ @click="hud.disconnect"+ >+ Disconnect+ </button>+ </PopoverContent>+ </PopoverPortal>+ </PopoverRoot>+</template>diff --git a/src/components/MobileHud/MobileShareButton.vue b/src/components/MobileHud/MobileShareButton.vuenew file mode 100644index 000000000..a2bfbf289--- /dev/null+++ b/src/components/MobileHud/MobileShareButton.vue@@ -0,0 +1,15 @@+<script setup lang="ts">+import { useMobileHudContext } from '@/components/MobileHud/context'++const hud = useMobileHudContext()+</script>++<template>+ <button+ class="flex h-8 cursor-pointer items-center gap-1.5 rounded-full border border-white/10 bg-panel/70 px-3 shadow-md backdrop-blur-xl select-none active:bg-hover"+ @click="hud.share"+ >+ <icon-lucide-share-2 class="size-3.5 text-surface" />+ <span class="text-xs text-surface">{{ hud.dialogs.share }}</span>+ </button>+</template>diff --git a/src/components/MobileHud/MobileUndoRedo.vue b/src/components/MobileHud/MobileUndoRedo.vuenew file mode 100644index 000000000..e66dd10d5--- /dev/null+++ b/src/components/MobileHud/MobileUndoRedo.vue@@ -0,0 +1,27 @@+<script setup lang="ts">+import Tip from '@/components/ui/Tip.vue'+import { useMobileHudContext } from '@/components/MobileHud/context'++const hud = useMobileHudContext()+</script>++<template>+ <div class="flex gap-1.5">+ <Tip label="Undo">+ <button+ class="flex size-8 cursor-pointer items-center justify-center rounded-full border border-white/10 bg-panel/70 shadow-md backdrop-blur-xl select-none active:bg-hover"+ @click="hud.undo"+ >+ <icon-lucide-undo-2 class="size-3.5 text-surface" />+ </button>+ </Tip>+ <Tip label="Redo">+ <button+ class="flex size-8 cursor-pointer items-center justify-center rounded-full border border-white/10 bg-panel/70 shadow-md backdrop-blur-xl select-none active:bg-hover"+ @click="hud.redo"+ >+ <icon-lucide-redo-2 class="size-3.5 text-surface" />+ </button>+ </Tip>+ </div>+</template>diff --git a/src/components/MobileHud/context.ts b/src/components/MobileHud/context.tsnew file mode 100644index 000000000..c59412adc--- /dev/null+++ b/src/components/MobileHud/context.ts@@ -0,0 +1,110 @@+import { useClipboard } from '@vueuse/core'+import { computed, inject, provide, proxyRefs } from 'vue'+import { useRouter } from 'vue-router'+import IconFilePlus from '~icons/lucide/file-plus'+import IconFolderOpen from '~icons/lucide/folder-open'+import IconImageDown from '~icons/lucide/image-down'+import IconSave from '~icons/lucide/save'+import IconZoomIn from '~icons/lucide/zoom-in'++import { DEFAULT_COLLAB_STATE, useCollabInjected } from '@/app/collab/use'+import { useEditorStore } from '@/app/editor/active-store'+import { toolIcons } from '@/app/editor/icons'+import { openFileDialog } from '@/app/shell/menu/use'+import { toast } from '@/app/shell/ui'+import { useEditorCommands, useI18n } from '@open-pencil/vue'++import type { Component, InjectionKey, ShallowUnwrapRef } from 'vue'++interface MenuAction {+ icon: Component+ label: string+ action: () => void+}++function createMobileHudContext() {+ const router = useRouter()+ const collab = useCollabInjected()+ const store = useEditorStore()+ const { copy } = useClipboard()+ const { dialogs } = useI18n()+ const { getCommand } = useEditorCommands()++ const collabState = computed(() => collab?.state.value ?? DEFAULT_COLLAB_STATE)+ const collabPeers = computed(() => collab?.remotePeers.value ?? [])+ const followingPeer = computed(() => collab?.followingPeer.value ?? null)+ const onlineCount = computed(() => collabPeers.value.length + 1)+ const activeToolIcon = computed(() => toolIcons[store.state.activeTool])+ const actionToast = computed(() => store.state.actionToast)++ const menuItems: MenuAction[] = [+ {+ icon: IconFilePlus,+ label: 'New',+ action: () => void import('@/app/tabs').then((m) => m.createTab())+ },+ { icon: IconFolderOpen, label: 'Open…', action: () => void openFileDialog() },+ { icon: IconSave, label: 'Save', action: () => void store.saveFigFile() },+ { icon: IconImageDown, label: 'Export…', action: () => void store.exportSelection(1, 'png') },+ { icon: IconZoomIn, label: 'Zoom to fit', action: () => getCommand('view.zoomFit').run() }+ ]++ function undo() {+ getCommand('edit.undo').run()+ }++ function redo() {+ getCommand('edit.redo').run()+ }++ function share() {+ if (!collab) return+ const roomId = collab.shareCurrentDoc()+ void router.push(`/share/${roomId}`)+ void copy(`${window.location.origin}/share/${roomId}`)+ toast.info('Link copied to clipboard')+ }++ function disconnect() {+ if (!collab) return+ collab.disconnect()+ void router.push('/')+ }++ function toggleFollowPeer(clientId: number) {+ collab?.followPeer(followingPeer.value === clientId ? null : clientId)+ }++ return {+ store,+ dialogs,+ collabState,+ collabPeers,+ followingPeer,+ onlineCount,+ activeToolIcon,+ actionToast,+ menuItems,+ undo,+ redo,+ share,+ disconnect,+ toggleFollowPeer+ }+}++export type MobileHudContext = ShallowUnwrapRef<ReturnType<typeof createMobileHudContext>>++const MOBILE_HUD_KEY: InjectionKey<MobileHudContext> = Symbol('MobileHudContext')++export function provideMobileHud() {+ const ctx = proxyRefs(createMobileHudContext())+ provide(MOBILE_HUD_KEY, ctx)+ return ctx+}++export function useMobileHudContext(): MobileHudContext {+ const ctx = inject(MOBILE_HUD_KEY)+ if (!ctx) throw new Error('Mobile HUD controls must be used within MobileHud')+ return ctx+}diff --git a/src/components/PropertiesPanel.vue b/src/components/PropertiesPanel.vueindex bf5a15aea..bf4c6d502 100644--- a/src/components/PropertiesPanel.vue+++ b/src/components/PropertiesPanel.vue@@ -2,7 +2,7 @@import { TabsContent, TabsList, TabsRoot, TabsTrigger } from 'reka-ui'import { useI18n } from '@open-pencil/vue'-import { useAIChat } from '@/composables/use-chat'+import { useAIChat } from '@/app/ai/chat/use'import ChatPanel from './ChatPanel.vue'import CodePanel from './CodePanel.vue'diff --git a/src/components/ScrubInput.vue b/src/components/ScrubInput.vueindex c51890a5c..1a6ce2c15 100644--- a/src/components/ScrubInput.vue+++ b/src/components/ScrubInput.vue@@ -1,6 +1,9 @@<script setup lang="ts">+import { useAttrs } from 'vue'import { ScrubInputRoot, ScrubInputField, ScrubInputDisplay } from '@open-pencil/vue'-import { useEditorStore } from '@/stores/editor'+import { useEditorStore } from '@/app/editor/active-store'++const attrs = useAttrs()const store = useEditorStore()@@ -20,6 +23,8 @@ const emit = defineEmits<{'update:modelValue': [value: number]commit: [value: number, previous: number]}>()++defineOptions({ inheritAttrs: false })</script><template>@@ -36,13 +41,18 @@ const emit = defineEmits<{@editing-change="store.state.scrubInputFocused = $event"><div- data-test-id="scrub-input"+ v-bind="attrs"+ :data-test-id="(attrs['data-test-id'] as string | undefined) ?? 'scrub-input'":tabindex="editing ? undefined : 0"- class="group flex h-[26px] min-w-0 flex-1 items-center rounded border border-border bg-input focus-within:border-accent focus:border-accent"+ :class="[+ attrs.class,+ 'group flex h-[26px] min-w-0 flex-1 items-center rounded border border-border bg-input focus-within:border-accent focus:border-accent'+ ]":style="{ cursor: editing ? 'auto' : 'ew-resize' }"@pointerdown="!editing && startScrub($event)"@focus="!editing && startEdit()">+ <span v-if="attrs['data-test-id']" data-test-id="scrub-input" class="hidden" /><spanclass="flex shrink-0 items-center justify-center self-stretch px-[5px] text-muted select-none [&>*]:pointer-events-none">diff --git a/src/components/TabBar.vue b/src/components/TabBar.vueindex daeec133c..609be7bde 100644--- a/src/components/TabBar.vue+++ b/src/components/TabBar.vue@@ -3,7 +3,7 @@ import { computed } from 'vue'import { TabsList, TabsRoot, TabsTrigger } from 'reka-ui'import Tip from '@/components/ui/Tip.vue'-import { useTabsStore, createTab } from '@/stores/tabs'+import { useTabsStore, createTab } from '@/app/tabs'const { tabs, activeTabId, switchTab, closeTab } = useTabsStore()diff --git a/src/components/Toolbar.vue b/src/components/Toolbar.vuedeleted file mode 100644index 55565b13b..000000000--- a/src/components/Toolbar.vue+++ /dev/null@@ -1,417 +0,0 @@-<script setup lang="ts">-import {- DropdownMenuRoot,- DropdownMenuTrigger,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuPortal-} from 'reka-ui'-import { AnimatePresence, motion } from 'motion-v'--import IconChevronDown from '~icons/lucide/chevron-down'-import IconChevronLeft from '~icons/lucide/chevron-left'-import IconChevronRight from '~icons/lucide/chevron-right'-import IconCopy from '~icons/lucide/copy'-import IconClipboard from '~icons/lucide/clipboard'-import IconScissors from '~icons/lucide/scissors'-import IconCopyPlus from '~icons/lucide/copy-plus'-import IconTrash2 from '~icons/lucide/trash-2'-import IconArrowUpToLine from '~icons/lucide/arrow-up-to-line'-import IconArrowDownToLine from '~icons/lucide/arrow-down-to-line'-import IconGroup from '~icons/lucide/group'-import IconUngroup from '~icons/lucide/ungroup'-import IconLock from '~icons/lucide/lock'--import { menu, useMenuUI } from '@/components/ui/menu'-import Tip from '@/components/ui/Tip.vue'-import { useActionToast } from '@/composables/use-action-toast'-import { useEditorStore } from '@/stores/editor'-import { toolIcons } from '@/utils/tools'-import {- ToolbarRoot,- ToolbarItem,- useEditorCommands,- useI18n,- useToolbarState,- useViewportKind-} from '@open-pencil/vue'-import { computed } from 'vue'--import type { Component } from 'vue'-import type { Tool } from '@open-pencil/vue'--const store = useEditorStore()-const { isMobile } = useViewportKind()-const { getCommand } = useEditorCommands()-const { showActionToast } = useActionToast()-const { menu: t, tools: toolTexts } = useI18n()--const toolLabels = computed<Record<Tool, string>>(() => ({- SELECT: toolTexts.value.move,- FRAME: toolTexts.value.frame,- SECTION: toolTexts.value.section,- RECTANGLE: toolTexts.value.rectangle,- ELLIPSE: toolTexts.value.ellipse,- LINE: toolTexts.value.line,- POLYGON: toolTexts.value.polygon,- STAR: toolTexts.value.star,- PEN: toolTexts.value.pen,- TEXT: toolTexts.value.text,- HAND: toolTexts.value.hand-}))--const toolShortcuts: Record<Tool, string> = {- SELECT: 'V',- FRAME: 'F',- SECTION: 'S',- RECTANGLE: 'R',- ELLIPSE: 'O',- LINE: 'L',- POLYGON: '',- STAR: '',- PEN: 'P',- TEXT: 'T',- HAND: 'H'-}--interface ActionItem {- icon: Component- label: string- action: () => void-}--const flyoutMenuCls = useMenuUI({ content: 'min-w-32' })--const editActions = computed<ActionItem[]>(() => [- { icon: IconCopy, label: t.value.copy, action: () => store.mobileCopy() },- { icon: IconClipboard, label: t.value.paste, action: () => store.mobilePaste() },- { icon: IconScissors, label: t.value.cut, action: () => store.mobileCut() },- {- icon: IconCopyPlus,- label: getCommand('selection.duplicate').label,- action: () => getCommand('selection.duplicate').run()- },- {- icon: IconTrash2,- label: getCommand('selection.delete').label,- action: () => getCommand('selection.delete').run()- }-])--const arrangeActions = computed<ActionItem[]>(() => [- {- icon: IconArrowUpToLine,- label: t.value.front,- action: () => getCommand('selection.bringToFront').run()- },- {- icon: IconArrowDownToLine,- label: t.value.back,- action: () => getCommand('selection.sendToBack').run()- },- {- icon: IconGroup,- label: getCommand('selection.group').label,- action: () => getCommand('selection.group').run()- },- {- icon: IconUngroup,- label: getCommand('selection.ungroup').label,- action: () => getCommand('selection.ungroup').run()- },- {- icon: IconLock,- label: t.value.lock,- action: () => getCommand('selection.toggleLock').run()- }-])--const {- mobileCategory,- slideDirection,- hasPrev,- hasNext,- isActive,- activeKeyForTool,- goPrev,- goNext-} = useToolbarState()--function onActionTap(item: ActionItem) {- item.action()- showActionToast(item.label)-}--const slideVariants = {- initial: (dir: unknown) => ({ opacity: 0, x: (dir as number) * 20 }),- animate: { opacity: 1, x: 0 },- exit: (dir: unknown) => ({ opacity: 0, x: (dir as number) * -20 })-}-</script>--<template>- <ToolbarRoot v-slot="{ tools, activeTool, setTool }">- <div- v-if="!isMobile"- class="absolute bottom-4 left-1/2 z-10 flex -translate-x-1/2 items-center"- >- <div- data-test-id="toolbar"- class="flex gap-0.5 rounded-xl border border-border bg-panel p-1 shadow-lg"- >- <template v-for="tool in tools" :key="tool.key">- <div v-if="tool.flyout && tool.flyout.length > 1" class="flex items-center">- <Tip :label="`${toolLabels[activeKeyForTool(tool, activeTool)]} (${tool.shortcut})`">- <button- :data-test-id="`toolbar-tool-${activeKeyForTool(tool, activeTool).toLowerCase()}`"- class="flex size-8 cursor-pointer items-center justify-center rounded-lg border-none transition-colors"- :class="- isActive(tool, activeTool)- ? 'bg-accent text-white'- : 'bg-transparent text-muted hover:bg-hover hover:text-surface'- "- @click="setTool(activeKeyForTool(tool, activeTool))"- >- <component :is="toolIcons[activeKeyForTool(tool, activeTool)]" class="size-4" />- </button>- </Tip>-- <DropdownMenuRoot>- <DropdownMenuTrigger as-child>- <button- :data-test-id="`toolbar-flyout-${tool.key.toLowerCase()}`"- class="flex h-8 w-3 cursor-pointer items-center justify-center rounded-lg border-none transition-colors"- :class="- isActive(tool, activeTool)- ? 'bg-accent text-white'- : 'bg-transparent text-muted hover:bg-hover hover:text-surface'- "- >- <IconChevronDown class="size-2.5" />- </button>- </DropdownMenuTrigger>-- <DropdownMenuPortal>- <DropdownMenuContent- side="top"- :side-offset="8"- align="start"- :class="flyoutMenuCls.content"- >- <ToolbarItem- v-for="sub in tool.flyout"- :key="sub"- v-slot="{ active: subActive, select: selectSub }"- :tool="sub"- >- <DropdownMenuItem- :data-test-id="`toolbar-flyout-item-${sub.toLowerCase()}`"- :class="- menu().item({ class: subActive ? 'bg-accent text-white' : undefined })- "- @select="selectSub"- >- <component :is="toolIcons[sub]" class="size-3.5" />- <span class="flex-1">{{ toolLabels[sub] }}</span>- <span v-if="toolShortcuts[sub]" class="text-[11px] text-muted">{{- toolShortcuts[sub]- }}</span>- </DropdownMenuItem>- </ToolbarItem>- </DropdownMenuContent>- </DropdownMenuPortal>- </DropdownMenuRoot>- </div>-- <ToolbarItem v-else v-slot="{ active, select: selectTool }" :tool="tool.key">- <Tip :label="`${toolLabels[tool.key]} (${tool.shortcut})`">- <button- :data-test-id="`toolbar-tool-${tool.key.toLowerCase()}`"- class="flex size-8 cursor-pointer items-center justify-center rounded-lg border-none transition-colors"- :class="- active- ? 'bg-accent text-white'- : 'bg-transparent text-muted hover:bg-hover hover:text-surface'- "- @click="selectTool"- >- <component :is="toolIcons[tool.key]" class="size-4" />- </button>- </Tip>- </ToolbarItem>- </template>- </div>- </div>-- <!-- Mobile toolbar -->- <div- v-else- data-test-id="mobile-toolbar"- class="fixed left-1/2 z-20 flex -translate-x-1/2 items-center gap-1.5"- :style="{- maxWidth: 'calc(100vw - 2rem)',- bottom: `calc(56px + env(safe-area-inset-bottom) + 0.75rem)`- }"- >- <motion.button- data-test-id="mobile-toolbar-prev"- class="flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-full border border-border bg-panel shadow-sm select-none"- :class="hasPrev ? 'text-muted' : 'pointer-events-none'"- :animate="{ opacity: hasPrev ? 1 : 0 }"- :transition="{ duration: 0.15 }"- @click="goPrev"- >- <IconChevronLeft class="size-3.5" />- </motion.button>-- <motion.div- layout- data-test-id="mobile-toolbar-container"- class="relative flex h-11 items-center overflow-hidden rounded-[8px] border border-border bg-panel px-2 shadow-lg"- :transition="{ layout: { type: 'spring', damping: 30, stiffness: 500 } }"- >- <AnimatePresence mode="popLayout" :custom="slideDirection">- <motion.div- v-if="mobileCategory === 0"- key="tools"- data-test-id="mobile-toolbar-tools"- class="flex gap-0.5"- :variants="slideVariants"- initial="initial"- animate="animate"- exit="exit"- :transition="{ duration: 0.15 }"- >- <template v-for="tool in tools" :key="tool.key">- <div v-if="tool.flyout && tool.flyout.length > 1" class="flex items-center">- <button- :data-test-id="`mobile-toolbar-tool-${activeKeyForTool(tool, activeTool).toLowerCase()}`"- class="flex size-8 cursor-pointer items-center justify-center rounded-[6px] border-none transition-colors select-none"- :class="- isActive(tool, activeTool)- ? 'bg-accent text-white'- : 'bg-transparent text-muted active:bg-hover'- "- @click="setTool(activeKeyForTool(tool, activeTool))"- >- <component :is="toolIcons[activeKeyForTool(tool, activeTool)]" class="size-4" />- </button>-- <DropdownMenuRoot>- <DropdownMenuTrigger as-child>- <button- :data-test-id="`mobile-toolbar-flyout-${tool.key.toLowerCase()}`"- class="flex h-8 w-3 cursor-pointer items-center justify-center rounded-[6px] border-none transition-colors select-none"- :class="- isActive(tool, activeTool)- ? 'bg-accent text-white'- : 'bg-transparent text-muted active:bg-hover'- "- >- <IconChevronDown class="size-2.5" />- </button>- </DropdownMenuTrigger>-- <DropdownMenuPortal>- <DropdownMenuContent- side="top"- :side-offset="8"- align="start"- :class="flyoutMenuCls.content"- >- <ToolbarItem- v-for="sub in tool.flyout"- :key="sub"- v-slot="{ active: subActive, select: selectSub }"- :tool="sub"- >- <DropdownMenuItem- :data-test-id="`mobile-toolbar-flyout-item-${sub.toLowerCase()}`"- :class="- menu().item({ class: subActive ? 'bg-accent text-white' : undefined })- "- @select="selectSub"- >- <component :is="toolIcons[sub]" class="size-3.5" />- <span class="flex-1">{{ toolLabels[sub] }}</span>- </DropdownMenuItem>- </ToolbarItem>- </DropdownMenuContent>- </DropdownMenuPortal>- </DropdownMenuRoot>- </div>-- <ToolbarItem v-else v-slot="{ active, select: selectTool }" :tool="tool.key">- <button- :data-test-id="`mobile-toolbar-tool-${tool.key.toLowerCase()}`"- class="flex size-8 cursor-pointer items-center justify-center rounded-[6px] border-none transition-colors select-none"- :class="- active ? 'bg-accent text-white' : 'bg-transparent text-muted active:bg-hover'- "- @click="selectTool"- >- <component :is="toolIcons[tool.key]" class="size-4" />- </button>- </ToolbarItem>- </template>- </motion.div>-- <motion.div- v-else-if="mobileCategory === 1"- key="edit"- data-test-id="mobile-toolbar-edit"- class="flex gap-0.5"- :variants="slideVariants"- initial="initial"- animate="animate"- exit="exit"- :transition="{ duration: 0.15 }"- >- <button- v-for="item in editActions"- :key="item.label"- :data-test-id="`mobile-toolbar-${item.label.toLowerCase()}`"- class="flex size-8 cursor-pointer items-center justify-center rounded-[6px] border-none bg-transparent text-muted transition-colors select-none active:bg-hover active:text-surface"- @click="onActionTap(item)"- >- <component :is="item.icon" class="size-4" />- </button>- </motion.div>-- <motion.div- v-else- key="arrange"- data-test-id="mobile-toolbar-arrange"- class="flex gap-0.5"- :variants="slideVariants"- initial="initial"- animate="animate"- exit="exit"- :transition="{ duration: 0.15 }"- >- <button- v-for="item in arrangeActions"- :key="item.label"- :data-test-id="`mobile-toolbar-${item.label.toLowerCase()}`"- class="flex size-8 cursor-pointer items-center justify-center rounded-[6px] border-none bg-transparent text-muted transition-colors select-none active:bg-hover active:text-surface"- @click="onActionTap(item)"- >- <component :is="item.icon" class="size-4" />- </button>- </motion.div>- </AnimatePresence>- </motion.div>-- <motion.button- data-test-id="mobile-toolbar-next"- class="flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-full border border-border bg-panel shadow-sm select-none"- :class="hasNext ? 'text-muted' : 'pointer-events-none'"- :animate="{ opacity: hasNext ? 1 : 0 }"- :transition="{ duration: 0.15 }"- @click="goNext"- >- <IconChevronRight class="size-3.5" />- </motion.button>- </div>- </ToolbarRoot>-</template>diff --git a/src/components/Toolbar/DesktopToolbar.vue b/src/components/Toolbar/DesktopToolbar.vuenew file mode 100644index 000000000..3818c1448--- /dev/null+++ b/src/components/Toolbar/DesktopToolbar.vue@@ -0,0 +1,69 @@+<script setup lang="ts">+import Tip from '@/components/ui/Tip.vue'+import ToolButton from '@/components/Toolbar/ToolButton.vue'+import ToolFlyout from '@/components/Toolbar/ToolFlyout.vue'+import { ToolbarItem } from '@open-pencil/vue'++import type { Tool } from '@open-pencil/vue'+import type { EditorToolDef } from '@open-pencil/core/editor'+import type { ToolIconMap, ToolLabels } from '@/components/Toolbar/types'++const { tools, activeTool, toolIcons, toolLabels, toolShortcuts, flyoutContentClass } =+ defineProps<{+ tools: EditorToolDef[]+ activeTool: Tool+ toolIcons: ToolIconMap+ toolLabels: ToolLabels+ toolShortcuts: Record<Tool, string>+ flyoutContentClass: string+ }>()++const emit = defineEmits<{+ setTool: [tool: Tool]+}>()++function isActive(tool: EditorToolDef) {+ return tool.key === activeTool || (tool.flyout?.includes(activeTool) ?? false)+}++function activeKeyForTool(tool: EditorToolDef) {+ return tool.flyout?.includes(activeTool) ? activeTool : tool.key+}+</script>++<template>+ <div class="absolute bottom-4 left-1/2 z-10 flex -translate-x-1/2 items-center">+ <div+ data-test-id="toolbar"+ class="flex gap-0.5 rounded-xl border border-border bg-panel p-1 shadow-lg"+ >+ <template v-for="tool in tools" :key="tool.key">+ <Tip+ v-if="tool.flyout && tool.flyout.length > 1"+ :label="`${toolLabels[activeKeyForTool(tool)]} (${tool.shortcut})`"+ >+ <ToolFlyout+ :tool="tool"+ :active-tool="activeTool"+ :tool-icons="toolIcons"+ :tool-labels="toolLabels"+ :tool-shortcuts="toolShortcuts"+ :content-class="flyoutContentClass"+ @select="emit('setTool', $event)"+ />+ </Tip>++ <ToolbarItem v-else v-slot="{ active, select: selectTool }" :tool="tool.key">+ <Tip :label="`${toolLabels[tool.key]} (${tool.shortcut})`">+ <ToolButton+ :test-id="`toolbar-tool-${tool.key.toLowerCase()}`"+ :icon="toolIcons[tool.key]"+ :active="active || isActive(tool)"+ @click="selectTool"+ />+ </Tip>+ </ToolbarItem>+ </template>+ </div>+ </div>+</template>diff --git a/src/components/Toolbar/MobileToolbar.vue b/src/components/Toolbar/MobileToolbar.vuenew file mode 100644index 000000000..e7abe8b8b--- /dev/null+++ b/src/components/Toolbar/MobileToolbar.vue@@ -0,0 +1,174 @@+<script setup lang="ts">+import { AnimatePresence, motion } from 'motion-v'++import IconChevronLeft from '~icons/lucide/chevron-left'+import IconChevronRight from '~icons/lucide/chevron-right'++import ToolButton from '@/components/Toolbar/ToolButton.vue'+import ToolFlyout from '@/components/Toolbar/ToolFlyout.vue'+import ToolbarActionGroup from '@/components/Toolbar/ToolbarActionGroup.vue'+import { ToolbarItem } from '@open-pencil/vue'++import type { Tool } from '@open-pencil/vue'+import type { EditorToolDef } from '@open-pencil/core/editor'+import type { ToolbarActionItem, ToolIconMap, ToolLabels } from '@/components/Toolbar/types'++const {+ tools,+ activeTool,+ toolIcons,+ toolLabels,+ toolShortcuts,+ flyoutContentClass,+ mobileCategory,+ slideDirection,+ hasPrev,+ hasNext,+ editActions,+ arrangeActions+} = defineProps<{+ tools: EditorToolDef[]+ activeTool: Tool+ toolIcons: ToolIconMap+ toolLabels: ToolLabels+ toolShortcuts: Record<Tool, string>+ flyoutContentClass: string+ mobileCategory: number+ slideDirection: number+ hasPrev: boolean+ hasNext: boolean+ editActions: ToolbarActionItem[]+ arrangeActions: ToolbarActionItem[]+}>()++const emit = defineEmits<{+ setTool: [tool: Tool]+ prev: []+ next: []+ action: [item: ToolbarActionItem]+}>()++const slideVariants = {+ initial: (dir: unknown) => ({ opacity: 0, x: (dir as number) * 20 }),+ animate: { opacity: 1, x: 0 },+ exit: (dir: unknown) => ({ opacity: 0, x: (dir as number) * -20 })+}++function activeKeyForTool(tool: EditorToolDef) {+ return tool.flyout?.includes(activeTool) ? activeTool : tool.key+}+</script>++<template>+ <div+ data-test-id="mobile-toolbar"+ class="fixed left-1/2 z-20 flex -translate-x-1/2 items-center gap-1.5"+ :style="{+ maxWidth: 'calc(100vw - 2rem)',+ bottom: `calc(56px + env(safe-area-inset-bottom) + 0.75rem)`+ }"+ >+ <motion.button+ data-test-id="mobile-toolbar-prev"+ class="flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-full border border-border bg-panel shadow-sm select-none"+ :class="hasPrev ? 'text-muted' : 'pointer-events-none'"+ :animate="{ opacity: hasPrev ? 1 : 0 }"+ :transition="{ duration: 0.15 }"+ @click="emit('prev')"+ >+ <IconChevronLeft class="size-3.5" />+ </motion.button>++ <motion.div+ layout+ data-test-id="mobile-toolbar-container"+ class="relative flex h-11 items-center overflow-hidden rounded-[8px] border border-border bg-panel px-2 shadow-lg"+ :transition="{ layout: { type: 'spring', damping: 30, stiffness: 500 } }"+ >+ <AnimatePresence mode="popLayout" :custom="slideDirection">+ <motion.div+ v-if="mobileCategory === 0"+ key="tools"+ data-test-id="mobile-toolbar-tools"+ class="flex gap-0.5"+ :variants="slideVariants"+ initial="initial"+ animate="animate"+ exit="exit"+ :transition="{ duration: 0.15 }"+ >+ <template v-for="tool in tools" :key="tool.key">+ <ToolFlyout+ v-if="tool.flyout && tool.flyout.length > 1"+ mobile+ :tool="tool"+ :active-tool="activeTool"+ :tool-icons="toolIcons"+ :tool-labels="toolLabels"+ :tool-shortcuts="toolShortcuts"+ :content-class="flyoutContentClass"+ @select="emit('setTool', $event)"+ />++ <ToolbarItem v-else v-slot="{ active, select: selectTool }" :tool="tool.key">+ <ToolButton+ mobile+ :test-id="`mobile-toolbar-tool-${tool.key.toLowerCase()}`"+ :icon="toolIcons[tool.key]"+ :active="active || activeKeyForTool(tool) === activeTool"+ @click="selectTool"+ />+ </ToolbarItem>+ </template>+ </motion.div>++ <motion.div+ v-else-if="mobileCategory === 1"+ key="edit"+ data-test-id="mobile-toolbar-edit"+ class="flex gap-0.5"+ :variants="slideVariants"+ initial="initial"+ animate="animate"+ exit="exit"+ :transition="{ duration: 0.15 }"+ >+ <ToolbarActionGroup+ :actions="editActions"+ test-prefix="mobile-toolbar"+ @action="emit('action', $event)"+ />+ </motion.div>++ <motion.div+ v-else+ key="arrange"+ data-test-id="mobile-toolbar-arrange"+ class="flex gap-0.5"+ :variants="slideVariants"+ initial="initial"+ animate="animate"+ exit="exit"+ :transition="{ duration: 0.15 }"+ >+ <ToolbarActionGroup+ :actions="arrangeActions"+ test-prefix="mobile-toolbar"+ @action="emit('action', $event)"+ />+ </motion.div>+ </AnimatePresence>+ </motion.div>++ <motion.button+ data-test-id="mobile-toolbar-next"+ class="flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-full border border-border bg-panel shadow-sm select-none"+ :class="hasNext ? 'text-muted' : 'pointer-events-none'"+ :animate="{ opacity: hasNext ? 1 : 0 }"+ :transition="{ duration: 0.15 }"+ @click="emit('next')"+ >+ <IconChevronRight class="size-3.5" />+ </motion.button>+ </div>+</template>diff --git a/src/components/Toolbar/ToolButton.vue b/src/components/Toolbar/ToolButton.vuenew file mode 100644index 000000000..a7d4d4d27--- /dev/null+++ b/src/components/Toolbar/ToolButton.vue@@ -0,0 +1,37 @@+<script setup lang="ts">+import type { Component } from 'vue'++const {+ icon,+ active = false,+ mobile = false,+ testId+} = defineProps<{+ icon: Component+ active?: boolean+ mobile?: boolean+ testId: string+}>()++const emit = defineEmits<{+ click: []+}>()+</script>++<template>+ <button+ :data-test-id="testId"+ class="flex size-8 cursor-pointer items-center justify-center border-none transition-colors"+ :class="[+ mobile ? 'rounded-[6px] select-none' : 'rounded-lg',+ active+ ? 'bg-accent text-white'+ : mobile+ ? 'bg-transparent text-muted active:bg-hover'+ : 'bg-transparent text-muted hover:bg-hover hover:text-surface'+ ]"+ @click="emit('click')"+ >+ <component :is="icon" class="size-4" />+ </button>+</template>diff --git a/src/components/Toolbar/ToolFlyout.vue b/src/components/Toolbar/ToolFlyout.vuenew file mode 100644index 000000000..d765d8c2d--- /dev/null+++ b/src/components/Toolbar/ToolFlyout.vue@@ -0,0 +1,111 @@+<script setup lang="ts">+import {+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuPortal,+ DropdownMenuRoot,+ DropdownMenuTrigger+} from 'reka-ui'++import IconChevronDown from '~icons/lucide/chevron-down'++import { menu } from '@/components/ui/menu'+import ToolButton from '@/components/Toolbar/ToolButton.vue'+import { ToolbarItem } from '@open-pencil/vue'++import type { Tool } from '@open-pencil/vue'+import type { EditorToolDef } from '@open-pencil/core/editor'+import type { ToolIconMap, ToolLabels } from '@/components/Toolbar/types'++const {+ tool,+ activeTool,+ toolIcons,+ toolLabels,+ toolShortcuts,+ contentClass,+ mobile = false+} = defineProps<{+ tool: EditorToolDef+ activeTool: Tool+ toolIcons: ToolIconMap+ toolLabels: ToolLabels+ toolShortcuts: Record<Tool, string>+ contentClass: string+ mobile?: boolean+}>()++const emit = defineEmits<{+ select: [tool: Tool]+}>()++defineSlots<{+ default(props: { label: string }): unknown+}>()++function isActiveTool(key: Tool) {+ return (+ tool.key === activeTool || (tool.flyout?.includes(activeTool) ?? false) || key === activeTool+ )+}++function activeKeyForTool() {+ return tool.flyout?.includes(activeTool) ? activeTool : tool.key+}+</script>++<template>+ <div class="flex items-center">+ <slot :label="`${toolLabels[activeKeyForTool()]} (${tool.shortcut})`">+ <ToolButton+ :test-id="`${mobile ? 'mobile-' : ''}toolbar-tool-${activeKeyForTool().toLowerCase()}`"+ :icon="toolIcons[activeKeyForTool()]"+ :active="isActiveTool(activeKeyForTool())"+ :mobile="mobile"+ @click="emit('select', activeKeyForTool())"+ />+ </slot>++ <DropdownMenuRoot>+ <DropdownMenuTrigger as-child>+ <button+ :data-test-id="`${mobile ? 'mobile-' : ''}toolbar-flyout-${tool.key.toLowerCase()}`"+ class="flex h-8 w-3 cursor-pointer items-center justify-center border-none transition-colors"+ :class="[+ mobile ? 'rounded-[6px] select-none' : 'rounded-lg',+ isActiveTool(activeKeyForTool())+ ? 'bg-accent text-white'+ : mobile+ ? 'bg-transparent text-muted active:bg-hover'+ : 'bg-transparent text-muted hover:bg-hover hover:text-surface'+ ]"+ >+ <IconChevronDown class="size-2.5" />+ </button>+ </DropdownMenuTrigger>++ <DropdownMenuPortal>+ <DropdownMenuContent side="top" :side-offset="8" align="start" :class="contentClass">+ <ToolbarItem+ v-for="sub in tool.flyout"+ :key="sub"+ v-slot="{ active: subActive, select: selectSub }"+ :tool="sub"+ >+ <DropdownMenuItem+ :data-test-id="`${mobile ? 'mobile-' : ''}toolbar-flyout-item-${sub.toLowerCase()}`"+ :class="menu().item({ class: subActive ? 'bg-accent text-white' : undefined })"+ @select="selectSub"+ >+ <component :is="toolIcons[sub]" class="size-3.5" />+ <span class="flex-1">{{ toolLabels[sub] }}</span>+ <span v-if="!mobile && toolShortcuts[sub]" class="text-[11px] text-muted">+ {{ toolShortcuts[sub] }}+ </span>+ </DropdownMenuItem>+ </ToolbarItem>+ </DropdownMenuContent>+ </DropdownMenuPortal>+ </DropdownMenuRoot>+ </div>+</template>diff --git a/src/components/Toolbar/Toolbar.vue b/src/components/Toolbar/Toolbar.vuenew file mode 100644index 000000000..48039d8f0--- /dev/null+++ b/src/components/Toolbar/Toolbar.vue@@ -0,0 +1,100 @@+<script setup lang="ts">+import { computed } from 'vue'++import DesktopToolbar from '@/components/Toolbar/DesktopToolbar.vue'+import MobileToolbar from '@/components/Toolbar/MobileToolbar.vue'+import { useToolbarActions } from '@/components/Toolbar/actions'+import { useActionToast } from '@/app/shell/toast/action'+import { useEditorStore } from '@/app/editor/active-store'+import { toolIcons } from '@/app/editor/icons'+import { useMenuUI } from '@/components/ui/menu'+import {+ ToolbarRoot,+ useEditorCommands,+ useI18n,+ useToolbarState,+ useViewportKind+} from '@open-pencil/vue'++import type { Tool } from '@open-pencil/vue'+import type { ToolbarActionItem } from '@/components/Toolbar/types'++const store = useEditorStore()+const { isMobile } = useViewportKind()+const { getCommand } = useEditorCommands()+const { showActionToast } = useActionToast()+const { menu, tools: toolTexts } = useI18n()++const toolLabels = computed<Record<Tool, string>>(() => ({+ SELECT: toolTexts.value.move,+ FRAME: toolTexts.value.frame,+ SECTION: toolTexts.value.section,+ RECTANGLE: toolTexts.value.rectangle,+ ELLIPSE: toolTexts.value.ellipse,+ LINE: toolTexts.value.line,+ POLYGON: toolTexts.value.polygon,+ STAR: toolTexts.value.star,+ PEN: toolTexts.value.pen,+ TEXT: toolTexts.value.text,+ HAND: toolTexts.value.hand+}))++const toolShortcuts: Record<Tool, string> = {+ SELECT: 'V',+ FRAME: 'F',+ SECTION: 'S',+ RECTANGLE: 'R',+ ELLIPSE: 'O',+ LINE: 'L',+ POLYGON: '',+ STAR: '',+ PEN: 'P',+ TEXT: 'T',+ HAND: 'H'+}++const flyoutMenuCls = useMenuUI({ content: 'min-w-32' })+const { editActions, arrangeActions } = useToolbarActions({ store, getCommand, menu })++const { mobileCategory, slideDirection, hasPrev, hasNext, goPrev, goNext } = useToolbarState()++function onActionTap(item: ToolbarActionItem) {+ item.action()+ showActionToast(item.label)+}+</script>++<template>+ <ToolbarRoot v-slot="{ tools, activeTool, setTool }">+ <DesktopToolbar+ v-if="!isMobile"+ :tools="tools"+ :active-tool="activeTool"+ :tool-icons="toolIcons"+ :tool-labels="toolLabels"+ :tool-shortcuts="toolShortcuts"+ :flyout-content-class="flyoutMenuCls.content"+ @set-tool="setTool"+ />++ <MobileToolbar+ v-else+ :tools="tools"+ :active-tool="activeTool"+ :tool-icons="toolIcons"+ :tool-labels="toolLabels"+ :tool-shortcuts="toolShortcuts"+ :flyout-content-class="flyoutMenuCls.content"+ :mobile-category="mobileCategory"+ :slide-direction="slideDirection"+ :has-prev="hasPrev"+ :has-next="hasNext"+ :edit-actions="editActions"+ :arrange-actions="arrangeActions"+ @set-tool="setTool"+ @prev="goPrev"+ @next="goNext"+ @action="onActionTap"+ />+ </ToolbarRoot>+</template>diff --git a/src/components/Toolbar/ToolbarActionGroup.vue b/src/components/Toolbar/ToolbarActionGroup.vuenew file mode 100644index 000000000..1a9bb83c1--- /dev/null+++ b/src/components/Toolbar/ToolbarActionGroup.vue@@ -0,0 +1,24 @@+<script setup lang="ts">+import type { ToolbarActionItem } from '@/components/Toolbar/types'++const { actions, testPrefix } = defineProps<{+ actions: ToolbarActionItem[]+ testPrefix: string+}>()++const emit = defineEmits<{+ action: [item: ToolbarActionItem]+}>()+</script>++<template>+ <button+ v-for="item in actions"+ :key="item.label"+ :data-test-id="`${testPrefix}-${item.label.toLowerCase()}`"+ class="flex size-8 cursor-pointer items-center justify-center rounded-[6px] border-none bg-transparent text-muted transition-colors select-none active:bg-hover active:text-surface"+ @click="emit('action', item)"+ >+ <component :is="item.icon" class="size-4" />+ </button>+</template>diff --git a/src/components/Toolbar/actions.ts b/src/components/Toolbar/actions.tsnew file mode 100644index 000000000..436541f2c--- /dev/null+++ b/src/components/Toolbar/actions.ts@@ -0,0 +1,70 @@+import { computed } from 'vue'+import IconArrowDownToLine from '~icons/lucide/arrow-down-to-line'+import IconArrowUpToLine from '~icons/lucide/arrow-up-to-line'+import IconClipboard from '~icons/lucide/clipboard'+import IconCopy from '~icons/lucide/copy'+import IconCopyPlus from '~icons/lucide/copy-plus'+import IconGroup from '~icons/lucide/group'+import IconLock from '~icons/lucide/lock'+import IconScissors from '~icons/lucide/scissors'+import IconTrash2 from '~icons/lucide/trash-2'+import IconUngroup from '~icons/lucide/ungroup'++import type { EditorStore } from '@/app/editor/active-store'+import type { ToolbarActionItem } from '@/components/Toolbar/types'+import type { useEditorCommands } from '@open-pencil/vue'+import type { Ref } from 'vue'++type ToolbarActionOptions = {+ store: EditorStore+ getCommand: ReturnType<typeof useEditorCommands>['getCommand']+ menu: Ref<{ copy: string; paste: string; cut: string; front: string; back: string; lock: string }>+}++export function useToolbarActions({ store, getCommand, menu }: ToolbarActionOptions) {+ const editActions = computed<ToolbarActionItem[]>(() => [+ { icon: IconCopy, label: menu.value.copy, action: () => void store.mobileCopy() },+ { icon: IconClipboard, label: menu.value.paste, action: () => store.mobilePaste() },+ { icon: IconScissors, label: menu.value.cut, action: () => void store.mobileCut() },+ {+ icon: IconCopyPlus,+ label: getCommand('selection.duplicate').label,+ action: () => getCommand('selection.duplicate').run()+ },+ {+ icon: IconTrash2,+ label: getCommand('selection.delete').label,+ action: () => getCommand('selection.delete').run()+ }+ ])++ const arrangeActions = computed<ToolbarActionItem[]>(() => [+ {+ icon: IconArrowUpToLine,+ label: menu.value.front,+ action: () => getCommand('selection.bringToFront').run()+ },+ {+ icon: IconArrowDownToLine,+ label: menu.value.back,+ action: () => getCommand('selection.sendToBack').run()+ },+ {+ icon: IconGroup,+ label: getCommand('selection.group').label,+ action: () => getCommand('selection.group').run()+ },+ {+ icon: IconUngroup,+ label: getCommand('selection.ungroup').label,+ action: () => getCommand('selection.ungroup').run()+ },+ {+ icon: IconLock,+ label: menu.value.lock,+ action: () => getCommand('selection.toggleLock').run()+ }+ ])++ return { editActions, arrangeActions }+}diff --git a/src/components/Toolbar/types.ts b/src/components/Toolbar/types.tsnew file mode 100644index 000000000..03a93e547--- /dev/null+++ b/src/components/Toolbar/types.ts@@ -0,0 +1,11 @@+import type { Tool } from '@open-pencil/vue'+import type { Component } from 'vue'++export interface ToolbarActionItem {+ icon: Component+ label: string+ action: () => void+}++export type ToolLabels = Record<Tool, string>+export type ToolIconMap = Record<Tool, Component>diff --git a/src/components/VariablesDialog.vue b/src/components/VariablesDialog.vueindex 6c484dcda..d29c1d059 100644--- a/src/components/VariablesDialog.vue+++ b/src/components/VariablesDialog.vue@@ -21,7 +21,7 @@ import IconPalette from '~icons/lucide/palette'import IconToggleLeft from '~icons/lucide/toggle-left'import IconType from '~icons/lucide/type'import IconX from '~icons/lucide/x'-import ColorInput from './ColorInput.vue'+import ColorInput from '@/components/ColorPicker/ColorInput.vue'import Tip from './ui/Tip.vue'import { useDialogUI } from '@/components/ui/dialog'diff --git a/src/components/ZoomDropdown.vue b/src/components/ZoomDropdown.vueindex 9fa51f8c9..ffbc1386c 100644--- a/src/components/ZoomDropdown.vue+++ b/src/components/ZoomDropdown.vue@@ -11,7 +11,7 @@ import { nextTick, ref, watch } from 'vue'import { useEditorCommands, useI18n } from '@open-pencil/vue'import { menuItem, useMenuUI } from '@/components/ui/menu'-import { useEditorStore } from '@/stores/editor'+import { useEditorStore } from '@/app/editor/active-store'const store = useEditorStore()const { getCommand } = useEditorCommands()diff --git a/src/components/chat/ACPPermissionDialog.vue b/src/components/chat/AcpPermissionDialog.vuesimilarity index 98%rename from src/components/chat/ACPPermissionDialog.vuerename to src/components/chat/AcpPermissionDialog.vueindex 02e872a23..7bca1033d 100644--- a/src/components/chat/ACPPermissionDialog.vue+++ b/src/components/chat/AcpPermissionDialog.vue@@ -15,7 +15,7 @@ import {currentPermission,rejectCurrentPermission,respondToPermission-} from '@/ai/acp-permission'+} from '@/app/ai/acp/permission'import { useDialogUI } from '@/components/ui/dialog'const open = computed(() => currentPermission.value !== null)diff --git a/src/components/chat/ChatInput.vue b/src/components/chat/ChatInput.vueindex 5fe1e0104..b31e800ef 100644--- a/src/components/chat/ChatInput.vue+++ b/src/components/chat/ChatInput.vue@@ -3,14 +3,14 @@ import { TooltipProvider } from 'reka-ui'import { computed, ref } from 'vue'import ProviderModelSelect from '@/components/chat/ProviderModelSelect.vue'-import ProviderSettings from '@/components/chat/ProviderSettings.vue'+import ProviderSettings from '@/components/chat/ProviderSettings/ProviderSettings.vue'import Tip from '@/components/ui/Tip.vue'import { useButtonUI } from '@/components/ui/button'import { useInputUI } from '@/components/ui/input'-import { useAIChat } from '@/composables/use-chat'+import { useAIChat } from '@/app/ai/chat/use'import { useI18n } from '@open-pencil/vue'-import { ACP_AGENTS } from '@open-pencil/core'+import { ACP_AGENTS } from '@open-pencil/core/constants'const { providerID, providerDef, modelID, customModelID } = useAIChat()const { dialogs } = useI18n()diff --git a/src/components/chat/ProviderModelSelect.vue b/src/components/chat/ProviderModelSelect.vueindex c7a5944c0..7b9f54b7f 100644--- a/src/components/chat/ProviderModelSelect.vue+++ b/src/components/chat/ProviderModelSelect.vue@@ -10,7 +10,7 @@ import {} from 'reka-ui'import { useSelectUI } from '@/components/ui/select'-import { useAIChat } from '@/composables/use-chat'+import { useAIChat } from '@/app/ai/chat/use'const { modelID, providerDef } = useAIChat()const selectCls = useSelectUI({diff --git a/src/components/chat/ProviderSelect.vue b/src/components/chat/ProviderSelect/ProviderSelect.vuesimilarity index 88%rename from src/components/chat/ProviderSelect.vuerename to src/components/chat/ProviderSelect/ProviderSelect.vueindex 9928382a1..a0660de21 100644--- a/src/components/chat/ProviderSelect.vue+++ b/src/components/chat/ProviderSelect/ProviderSelect.vue@@ -1,9 +1,15 @@<script setup lang="ts">+import { promiseTimeout } from '@vueuse/core'import { computed, onMounted, ref } from 'vue'import AppGroupedSelect from '@/components/ui/AppGroupedSelect.vue'-import { ACP_AGENTS, AI_PROVIDERS, AUTOMATION_HTTP_PORT, IS_TAURI } from '@open-pencil/core'-import { useAIChat } from '@/composables/use-chat'+import {+ ACP_AGENTS,+ AI_PROVIDERS,+ AUTOMATION_HTTP_PORT,+ IS_TAURI+} from '@open-pencil/core/constants'+import { useAIChat } from '@/app/ai/chat/use'const { providerID, providerDef } = useAIChat()@@ -26,7 +32,7 @@ async function checkMCPHealth(retries = 3, delayMs = 1000) {'):',e instanceof Error ? e.message : e)- if (i < retries - 1) await new Promise((r) => setTimeout(r, delayMs))+ if (i < retries - 1) await promiseTimeout(delayMs)}}}diff --git a/src/components/chat/ProviderSelectField.vue b/src/components/chat/ProviderSelect/ProviderSelectField.vuesimilarity index 82%rename from src/components/chat/ProviderSelectField.vuerename to src/components/chat/ProviderSelect/ProviderSelectField.vueindex 26f11da16..2b2d14773 100644--- a/src/components/chat/ProviderSelectField.vue+++ b/src/components/chat/ProviderSelect/ProviderSelectField.vue@@ -1,5 +1,5 @@<script setup lang="ts">-import ProviderSelect from '@/components/chat/ProviderSelect.vue'+import ProviderSelect from '@/components/chat/ProviderSelect/ProviderSelect.vue'const { testId = 'provider-selector' } = defineProps<{testId?: stringdiff --git a/src/components/chat/ProviderSettings.vue b/src/components/chat/ProviderSettings.vuedeleted file mode 100644index c073cdcd7..000000000--- a/src/components/chat/ProviderSettings.vue+++ /dev/null@@ -1,319 +0,0 @@-<script setup lang="ts">-import {- PopoverClose,- PopoverContent,- PopoverPortal,- PopoverRoot,- PopoverTrigger,- TabsContent,- TabsList,- TabsRoot,- TabsTrigger-} from 'reka-ui'-import { computed, ref, watch } from 'vue'--import ProviderSelectField from '@/components/chat/ProviderSelectField.vue'-import { useInputUI } from '@/components/ui/input'-import { usePopoverUI } from '@/components/ui/popover'-import { useAIChat } from '@/composables/use-chat'-import { openExternalLink } from '@/utils/external-link'--const cls = usePopoverUI({ content: 'isolate z-[51] w-64 p-3' })-const popoverOpen = ref(false)--const {- providerID,- providerDef,- apiKey,- setAPIKey,- customBaseURL,- customModelID,- customAPIType,- maxOutputTokens,- pexelsApiKey,- unsplashAccessKey-} = useAIChat()--const isACP = computed(() => providerID.value.startsWith('acp:'))--const keyInput = ref('')-const pexelsKeyInput = ref('')-const unsplashKeyInput = ref('')-const baseURLInput = ref(customBaseURL.value)-const customModelInput = ref(customModelID.value)-const hasExistingKey = ref(!!apiKey.value)-const hasExistingPexelsKey = ref(!!pexelsApiKey.value)-const hasExistingUnsplashKey = ref(!!unsplashAccessKey.value)--watch(providerID, () => {- keyInput.value = ''- hasExistingKey.value = !!apiKey.value- baseURLInput.value = customBaseURL.value- customModelInput.value = customModelID.value-})--function save() {- if (keyInput.value.trim()) {- setAPIKey(keyInput.value.trim())- hasExistingKey.value = true- keyInput.value = ''- }- if (pexelsKeyInput.value.trim()) {- pexelsApiKey.value = pexelsKeyInput.value.trim()- hasExistingPexelsKey.value = true- pexelsKeyInput.value = ''- }- if (unsplashKeyInput.value.trim()) {- unsplashAccessKey.value = unsplashKeyInput.value.trim()- hasExistingUnsplashKey.value = true- unsplashKeyInput.value = ''- }- if (providerDef.value.supportsCustomBaseURL) {- customBaseURL.value = baseURLInput.value.trim()- }- if (providerDef.value.supportsCustomModel) {- customModelID.value = customModelInput.value.trim()- }-}--function clearKey() {- setAPIKey('')- keyInput.value = ''- hasExistingKey.value = false-}--function clearPexelsKey() {- pexelsApiKey.value = ''- pexelsKeyInput.value = ''- hasExistingPexelsKey.value = false-}--function clearUnsplashKey() {- unsplashAccessKey.value = ''- unsplashKeyInput.value = ''- hasExistingUnsplashKey.value = false-}-</script>--<template>- <PopoverRoot @update:open="popoverOpen = $event">- <PopoverTrigger- data-test-id="provider-settings-trigger"- class="rounded p-0.5 text-muted hover:bg-hover hover:text-surface"- :title="popoverOpen ? undefined : 'Provider settings'"- >- <icon-lucide-settings class="size-3" />- </PopoverTrigger>-- <PopoverPortal>- <PopoverContent- side="top"- :side-offset="8"- align="end"- :collision-padding="16"- :avoid-collisions="true"- :class="cls.content"- @interact-outside="- (e: Event) => {- const target = e.target as HTMLElement | null- if (target?.closest('[role=listbox], [data-reka-popper-content-wrapper]')) {- e.preventDefault()- return- }- save()- }- "- >- <div class="flex flex-col gap-2.5">- <h3 class="text-[11px] font-semibold text-surface">AI Provider</h3>-- <ProviderSelectField test-id="provider-settings-provider" />-- <!-- Max output tokens -->- <div v-if="!isACP" class="flex flex-col gap-1">- <label class="text-[10px] text-muted">Max output tokens</label>- <input- v-model.number="maxOutputTokens"- type="number"- data-test-id="provider-settings-max-tokens"- :min="1024"- :max="128000"- :step="1024"- :class="useInputUI({ size: 'sm' }).base"- />- </div>-- <!-- Pexels stock photos -->- <div class="flex flex-col gap-1">- <div class="flex items-center justify-between">- <label class="text-[10px] text-muted">Pexels API Key (stock photos)</label>- <button- v-if="pexelsApiKey"- class="cursor-pointer text-[10px] text-muted hover:text-surface"- data-test-id="provider-settings-clear-pexels-key"- @click="clearPexelsKey"- >- Clear- </button>- </div>- <input- v-model="pexelsKeyInput"- type="password"- data-test-id="provider-settings-pexels-key"- :placeholder="- hasExistingPexelsKey- ? 'Key saved — enter new to replace'- : 'Optional — for stock_photo tool'- "- :class="useInputUI({ size: 'sm' }).base"- @change="save"- />- <button- type="button"- class="cursor-pointer text-[9px] text-muted underline hover:text-surface"- @click="openExternalLink('https://www.pexels.com/api/')"- >- Get free Pexels API key →- </button>- </div>-- <!-- Unsplash stock photos -->- <div class="flex flex-col gap-1">- <div class="flex items-center justify-between">- <label class="text-[10px] text-muted">Unsplash Access Key</label>- <button- v-if="unsplashAccessKey"- class="cursor-pointer text-[10px] text-muted hover:text-surface"- data-test-id="provider-settings-clear-unsplash-key"- @click="clearUnsplashKey"- >- Clear- </button>- </div>- <input- v-model="unsplashKeyInput"- type="password"- data-test-id="provider-settings-unsplash-key"- :placeholder="- hasExistingUnsplashKey- ? 'Key saved — enter new to replace'- : 'Optional — alternative to Pexels'- "- :class="useInputUI({ size: 'sm' }).base"- @change="save"- />- <button- type="button"- class="cursor-pointer text-[9px] text-muted underline hover:text-surface"- @click="openExternalLink('https://unsplash.com/oauth/applications')"- >- Get free Unsplash access key →- </button>- </div>-- <template v-if="!isACP">- <!-- Base URL (OpenAI-compatible only) -->- <div v-if="providerDef.supportsCustomBaseURL" class="flex flex-col gap-1">- <label class="text-[10px] text-muted">Base URL</label>- <input- v-model="baseURLInput"- type="text"- data-test-id="provider-settings-base-url"- placeholder="http://localhost:11434/v1"- :class="useInputUI({ size: 'sm' }).base"- @change="save"- />- </div>-- <!-- Custom model ID (OpenAI-compatible only) -->- <div v-if="providerDef.supportsCustomModel" class="flex flex-col gap-1">- <label class="text-[10px] text-muted">Model ID</label>- <input- v-model="customModelInput"- type="text"- data-test-id="provider-settings-custom-model"- placeholder="e.g. llama-3.3-70b"- :class="useInputUI({ size: 'sm' }).base"- @change="save"- />- </div>-- <!-- API type (OpenAI-compatible only) -->- <div v-if="providerID === 'openai-compatible'" class="flex flex-col gap-1">- <label class="text-[10px] text-muted">API Type</label>- <TabsRoot- :model-value="customAPIType"- data-test-id="provider-settings-api-type"- class="flex flex-col"- @update:model-value="- (v: string) => {- customAPIType = v as 'completions' | 'responses'- save()- }- "- >- <TabsList class="flex rounded bg-canvas">- <TabsTrigger- value="completions"- class="flex-1 rounded px-2 py-1 text-[10px] text-muted data-[state=active]:bg-hover data-[state=active]:text-surface"- >- Completions- </TabsTrigger>- <TabsTrigger- value="responses"- class="flex-1 rounded px-2 py-1 text-[10px] text-muted data-[state=active]:bg-hover data-[state=active]:text-surface"- >- Responses- </TabsTrigger>- </TabsList>- <TabsContent value="completions" />- <TabsContent value="responses" />- </TabsRoot>- </div>-- <!-- API key -->- <div class="flex flex-col gap-1">- <div class="flex items-center justify-between">- <label class="text-[10px] text-muted">API Key</label>- <button- v-if="apiKey"- class="cursor-pointer text-[10px] text-muted hover:text-surface"- data-test-id="provider-settings-clear-key"- @click="clearKey"- >- Clear- </button>- </div>- <input- v-model="keyInput"- type="password"- data-test-id="provider-settings-api-key"- :placeholder="- hasExistingKey ? 'Key saved — enter new to replace' : providerDef.keyPlaceholder- "- :class="useInputUI({ size: 'sm' }).base"- @change="save"- />- <button- v-if="providerDef.keyURL"- type="button"- class="cursor-pointer text-[9px] text-muted underline hover:text-surface"- @click="openExternalLink(providerDef.keyURL as string)"- >- Get API key →- </button>- </div>- </template>-- <PopoverClose- class="mt-1 w-full rounded bg-accent px-2 py-1 text-center text-[11px] font-medium text-white hover:bg-accent/90"- data-test-id="provider-settings-done"- @click="save"- >- Done- </PopoverClose>- </div>- </PopoverContent>- </PopoverPortal>- </PopoverRoot>-</template>diff --git a/src/components/chat/ProviderSettings/ApiKeySection.vue b/src/components/chat/ProviderSettings/ApiKeySection.vuenew file mode 100644index 000000000..87e93d7ac--- /dev/null+++ b/src/components/chat/ProviderSettings/ApiKeySection.vue@@ -0,0 +1,41 @@+<script setup lang="ts">+import { openExternalLink } from '@/app/shell/ui'+import { useInputUI } from '@/components/ui/input'+import { useProviderSettingsContext } from '@/components/chat/ProviderSettings/context'++const ctx = useProviderSettingsContext()+</script>++<template>+ <div v-if="!ctx.isACP" class="flex flex-col gap-1">+ <div class="flex items-center justify-between">+ <label class="text-[10px] text-muted">API Key</label>+ <button+ v-if="ctx.apiKey"+ class="cursor-pointer text-[10px] text-muted hover:text-surface"+ data-test-id="provider-settings-clear-key"+ @click="ctx.clearKey"+ >+ Clear+ </button>+ </div>+ <input+ v-model="ctx.keyInput"+ type="password"+ data-test-id="provider-settings-api-key"+ :placeholder="+ ctx.hasExistingKey ? 'Key saved — enter new to replace' : ctx.providerDef.keyPlaceholder+ "+ :class="useInputUI({ size: 'sm' }).base"+ @change="ctx.save"+ />+ <button+ v-if="ctx.providerDef.keyURL"+ type="button"+ class="cursor-pointer text-[9px] text-muted underline hover:text-surface"+ @click="openExternalLink(ctx.providerDef.keyURL as string)"+ >+ Get API key →+ </button>+ </div>+</template>diff --git a/src/components/chat/ProviderSettings/ApiTypeSection.vue b/src/components/chat/ProviderSettings/ApiTypeSection.vuenew file mode 100644index 000000000..67a5f13ce--- /dev/null+++ b/src/components/chat/ProviderSettings/ApiTypeSection.vue@@ -0,0 +1,36 @@+<script setup lang="ts">+import { TabsContent, TabsList, TabsRoot, TabsTrigger } from 'reka-ui'++import { useProviderSettingsContext } from '@/components/chat/ProviderSettings/context'++const ctx = useProviderSettingsContext()+</script>++<template>+ <div v-if="!ctx.isACP && ctx.providerID === 'openai-compatible'" class="flex flex-col gap-1">+ <label class="text-[10px] text-muted">API Type</label>+ <TabsRoot+ :model-value="ctx.customAPIType"+ data-test-id="provider-settings-api-type"+ class="flex flex-col"+ @update:model-value="ctx.setCustomAPIType"+ >+ <TabsList class="flex rounded bg-canvas">+ <TabsTrigger+ value="completions"+ class="flex-1 rounded px-2 py-1 text-[10px] text-muted data-[state=active]:bg-hover data-[state=active]:text-surface"+ >+ Completions+ </TabsTrigger>+ <TabsTrigger+ value="responses"+ class="flex-1 rounded px-2 py-1 text-[10px] text-muted data-[state=active]:bg-hover data-[state=active]:text-surface"+ >+ Responses+ </TabsTrigger>+ </TabsList>+ <TabsContent value="completions" />+ <TabsContent value="responses" />+ </TabsRoot>+ </div>+</template>diff --git a/src/components/chat/ProviderSettings/CustomEndpointSection.vue b/src/components/chat/ProviderSettings/CustomEndpointSection.vuenew file mode 100644index 000000000..f8fd1eafb--- /dev/null+++ b/src/components/chat/ProviderSettings/CustomEndpointSection.vue@@ -0,0 +1,34 @@+<script setup lang="ts">+import { useInputUI } from '@/components/ui/input'+import { useProviderSettingsContext } from '@/components/chat/ProviderSettings/context'++const ctx = useProviderSettingsContext()+</script>++<template>+ <template v-if="!ctx.isACP">+ <div v-if="ctx.providerDef.supportsCustomBaseURL" class="flex flex-col gap-1">+ <label class="text-[10px] text-muted">Base URL</label>+ <input+ v-model="ctx.baseURLInput"+ type="text"+ data-test-id="provider-settings-base-url"+ placeholder="http://localhost:11434/v1"+ :class="useInputUI({ size: 'sm' }).base"+ @change="ctx.save"+ />+ </div>++ <div v-if="ctx.providerDef.supportsCustomModel" class="flex flex-col gap-1">+ <label class="text-[10px] text-muted">Model ID</label>+ <input+ v-model="ctx.customModelInput"+ type="text"+ data-test-id="provider-settings-custom-model"+ placeholder="e.g. llama-3.3-70b"+ :class="useInputUI({ size: 'sm' }).base"+ @change="ctx.save"+ />+ </div>+ </template>+</template>diff --git a/src/components/chat/ProviderSettings/MaxTokensSection.vue b/src/components/chat/ProviderSettings/MaxTokensSection.vuenew file mode 100644index 000000000..18c9bc195--- /dev/null+++ b/src/components/chat/ProviderSettings/MaxTokensSection.vue@@ -0,0 +1,21 @@+<script setup lang="ts">+import { useInputUI } from '@/components/ui/input'+import { useProviderSettingsContext } from '@/components/chat/ProviderSettings/context'++const ctx = useProviderSettingsContext()+</script>++<template>+ <div v-if="!ctx.isACP" class="flex flex-col gap-1">+ <label class="text-[10px] text-muted">Max output tokens</label>+ <input+ v-model.number="ctx.maxOutputTokens"+ type="number"+ data-test-id="provider-settings-max-tokens"+ :min="1024"+ :max="128000"+ :step="1024"+ :class="useInputUI({ size: 'sm' }).base"+ />+ </div>+</template>diff --git a/src/components/chat/ProviderSettings/ProviderSettings.vue b/src/components/chat/ProviderSettings/ProviderSettings.vuenew file mode 100644index 000000000..7f5e1c2a6--- /dev/null+++ b/src/components/chat/ProviderSettings/ProviderSettings.vue@@ -0,0 +1,68 @@+<script setup lang="ts">+import { PopoverClose, PopoverContent, PopoverPortal, PopoverRoot, PopoverTrigger } from 'reka-ui'+import { ref } from 'vue'++import ApiKeySection from '@/components/chat/ProviderSettings/ApiKeySection.vue'+import ApiTypeSection from '@/components/chat/ProviderSettings/ApiTypeSection.vue'+import CustomEndpointSection from '@/components/chat/ProviderSettings/CustomEndpointSection.vue'+import MaxTokensSection from '@/components/chat/ProviderSettings/MaxTokensSection.vue'+import ProviderSelectField from '@/components/chat/ProviderSelect/ProviderSelectField.vue'+import StockPhotoKeysSection from '@/components/chat/ProviderSettings/StockPhotoKeysSection.vue'+import { provideProviderSettings } from '@/components/chat/ProviderSettings/context'+import { usePopoverUI } from '@/components/ui/popover'++const cls = usePopoverUI({ content: 'isolate z-[51] w-64 p-3' })+const popoverOpen = ref(false)+const providerSettings = provideProviderSettings()++function onInteractOutside(e: Event) {+ const target = e.target as HTMLElement | null+ if (target?.closest('[role=listbox], [data-reka-popper-content-wrapper]')) {+ e.preventDefault()+ return+ }+ providerSettings.save()+}+</script>++<template>+ <PopoverRoot @update:open="popoverOpen = $event">+ <PopoverTrigger+ data-test-id="provider-settings-trigger"+ class="rounded p-0.5 text-muted hover:bg-hover hover:text-surface"+ :title="popoverOpen ? undefined : 'Provider settings'"+ >+ <icon-lucide-settings class="size-3" />+ </PopoverTrigger>++ <PopoverPortal>+ <PopoverContent+ side="top"+ :side-offset="8"+ align="end"+ :collision-padding="16"+ :avoid-collisions="true"+ :class="cls.content"+ @interact-outside="onInteractOutside"+ >+ <div class="flex flex-col gap-2.5">+ <h3 class="text-[11px] font-semibold text-surface">AI Provider</h3>+ <ProviderSelectField test-id="provider-settings-provider" />+ <MaxTokensSection />+ <StockPhotoKeysSection />+ <CustomEndpointSection />+ <ApiTypeSection />+ <ApiKeySection />++ <PopoverClose+ class="mt-1 w-full rounded bg-accent px-2 py-1 text-center text-[11px] font-medium text-white hover:bg-accent/90"+ data-test-id="provider-settings-done"+ @click="providerSettings.save"+ >+ Done+ </PopoverClose>+ </div>+ </PopoverContent>+ </PopoverPortal>+ </PopoverRoot>+</template>diff --git a/src/components/chat/ProviderSettings/StockPhotoKeysSection.vue b/src/components/chat/ProviderSettings/StockPhotoKeysSection.vuenew file mode 100644index 000000000..94a980784--- /dev/null+++ b/src/components/chat/ProviderSettings/StockPhotoKeysSection.vue@@ -0,0 +1,75 @@+<script setup lang="ts">+import { openExternalLink } from '@/app/shell/ui'+import { useInputUI } from '@/components/ui/input'+import { useProviderSettingsContext } from '@/components/chat/ProviderSettings/context'++const ctx = useProviderSettingsContext()+</script>++<template>+ <div class="flex flex-col gap-1">+ <div class="flex items-center justify-between">+ <label class="text-[10px] text-muted">Pexels API Key (stock photos)</label>+ <button+ v-if="ctx.pexelsApiKey"+ class="cursor-pointer text-[10px] text-muted hover:text-surface"+ data-test-id="provider-settings-clear-pexels-key"+ @click="ctx.clearPexelsKey"+ >+ Clear+ </button>+ </div>+ <input+ v-model="ctx.pexelsKeyInput"+ type="password"+ data-test-id="provider-settings-pexels-key"+ :placeholder="+ ctx.hasExistingPexelsKey+ ? 'Key saved — enter new to replace'+ : 'Optional — for stock_photo tool'+ "+ :class="useInputUI({ size: 'sm' }).base"+ @change="ctx.save"+ />+ <button+ type="button"+ class="cursor-pointer text-[9px] text-muted underline hover:text-surface"+ @click="openExternalLink('https://www.pexels.com/api/')"+ >+ Get free Pexels API key →+ </button>+ </div>++ <div class="flex flex-col gap-1">+ <div class="flex items-center justify-between">+ <label class="text-[10px] text-muted">Unsplash Access Key</label>+ <button+ v-if="ctx.unsplashAccessKey"+ class="cursor-pointer text-[10px] text-muted hover:text-surface"+ data-test-id="provider-settings-clear-unsplash-key"+ @click="ctx.clearUnsplashKey"+ >+ Clear+ </button>+ </div>+ <input+ v-model="ctx.unsplashKeyInput"+ type="password"+ data-test-id="provider-settings-unsplash-key"+ :placeholder="+ ctx.hasExistingUnsplashKey+ ? 'Key saved — enter new to replace'+ : 'Optional — alternative to Pexels'+ "+ :class="useInputUI({ size: 'sm' }).base"+ @change="ctx.save"+ />+ <button+ type="button"+ class="cursor-pointer text-[9px] text-muted underline hover:text-surface"+ @click="openExternalLink('https://unsplash.com/oauth/applications')"+ >+ Get free Unsplash access key →+ </button>+ </div>+</template>diff --git a/src/components/chat/ProviderSettings/context.ts b/src/components/chat/ProviderSettings/context.tsnew file mode 100644index 000000000..33849b9ec--- /dev/null+++ b/src/components/chat/ProviderSettings/context.ts@@ -0,0 +1,129 @@+import { computed, inject, provide, proxyRefs, ref, watch } from 'vue'++import { useAIChat } from '@/app/ai/chat/use'++import type { InjectionKey, ShallowUnwrapRef } from 'vue'++function createProviderSettingsContext() {+ const {+ providerID,+ providerDef,+ apiKey,+ setAPIKey,+ customBaseURL,+ customModelID,+ customAPIType,+ maxOutputTokens,+ pexelsApiKey,+ unsplashAccessKey+ } = useAIChat()++ const isACP = computed(() => providerID.value.startsWith('acp:'))+ const keyInput = ref('')+ const pexelsKeyInput = ref('')+ const unsplashKeyInput = ref('')+ const baseURLInput = ref(customBaseURL.value)+ const customModelInput = ref(customModelID.value)+ const hasExistingKey = ref(!!apiKey.value)+ const hasExistingPexelsKey = ref(!!pexelsApiKey.value)+ const hasExistingUnsplashKey = ref(!!unsplashAccessKey.value)++ watch(providerID, () => {+ keyInput.value = ''+ hasExistingKey.value = !!apiKey.value+ baseURLInput.value = customBaseURL.value+ customModelInput.value = customModelID.value+ })++ function save() {+ if (keyInput.value.trim()) {+ setAPIKey(keyInput.value.trim())+ hasExistingKey.value = true+ keyInput.value = ''+ }+ if (pexelsKeyInput.value.trim()) {+ pexelsApiKey.value = pexelsKeyInput.value.trim()+ hasExistingPexelsKey.value = true+ pexelsKeyInput.value = ''+ }+ if (unsplashKeyInput.value.trim()) {+ unsplashAccessKey.value = unsplashKeyInput.value.trim()+ hasExistingUnsplashKey.value = true+ unsplashKeyInput.value = ''+ }+ if (providerDef.value.supportsCustomBaseURL) {+ customBaseURL.value = baseURLInput.value.trim()+ }+ if (providerDef.value.supportsCustomModel) {+ customModelID.value = customModelInput.value.trim()+ }+ }++ function clearKey() {+ setAPIKey('')+ keyInput.value = ''+ hasExistingKey.value = false+ }++ function clearPexelsKey() {+ pexelsApiKey.value = ''+ pexelsKeyInput.value = ''+ hasExistingPexelsKey.value = false+ }++ function clearUnsplashKey() {+ unsplashAccessKey.value = ''+ unsplashKeyInput.value = ''+ hasExistingUnsplashKey.value = false+ }++ function setCustomAPIType(value: string) {+ customAPIType.value = value as 'completions' | 'responses'+ save()+ }++ return {+ providerID,+ providerDef,+ apiKey,+ customAPIType,+ customBaseURL,+ customModelID,+ maxOutputTokens,+ pexelsApiKey,+ unsplashAccessKey,+ isACP,+ keyInput,+ pexelsKeyInput,+ unsplashKeyInput,+ baseURLInput,+ customModelInput,+ hasExistingKey,+ hasExistingPexelsKey,+ hasExistingUnsplashKey,+ save,+ clearKey,+ clearPexelsKey,+ clearUnsplashKey,+ setCustomAPIType+ }+}++export type ProviderSettingsContext = ShallowUnwrapRef<+ ReturnType<typeof createProviderSettingsContext>+>++const PROVIDER_SETTINGS_KEY: InjectionKey<ProviderSettingsContext> =+ Symbol('ProviderSettingsContext')++export function provideProviderSettings() {+ const ctx = proxyRefs(createProviderSettingsContext())+ provide(PROVIDER_SETTINGS_KEY, ctx)+ return ctx+}++export function useProviderSettingsContext(): ProviderSettingsContext {+ const ctx = inject(PROVIDER_SETTINGS_KEY)+ if (!ctx) throw new Error('Provider settings controls must be used within ProviderSettings')+ return ctx+}diff --git a/src/components/chat/ProviderSetup.vue b/src/components/chat/ProviderSetup.vueindex 3418efb17..4a238b456 100644--- a/src/components/chat/ProviderSetup.vue+++ b/src/components/chat/ProviderSetup.vue@@ -1,11 +1,11 @@<script setup lang="ts">import { computed, ref } from 'vue'-import ProviderSelectField from '@/components/chat/ProviderSelectField.vue'+import ProviderSelectField from '@/components/chat/ProviderSelect/ProviderSelectField.vue'import { useInputUI } from '@/components/ui/input'-import { useAIChat } from '@/composables/use-chat'-import { ACP_AGENTS } from '@open-pencil/core'-import { openExternalLink } from '@/utils/external-link'+import { useAIChat } from '@/app/ai/chat/use'+import { ACP_AGENTS } from '@open-pencil/core/constants'+import { openExternalLink } from '@/app/shell/ui'import { useI18n } from '@open-pencil/vue'const { providerID, providerDef, setAPIKey, customBaseURL, customModelID } = useAIChat()diff --git a/src/components/properties/AppearanceSection.vue b/src/components/properties/AppearanceSection.vueindex 0edcfee06..df3bd796b 100644--- a/src/components/properties/AppearanceSection.vue+++ b/src/components/properties/AppearanceSection.vue@@ -81,6 +81,7 @@ function onToggleCorners() {<template v-if="hasCornerRadius"><ScrubInputv-if="!showIndependentCorners"+ data-test-id="corner-radius-input":model-value="cornerRadiusValue":min="0"@update:model-value="updateProp('cornerRadius', $event)"@@ -121,6 +122,7 @@ function onToggleCorners() {class="mt-1.5 grid grid-cols-2 gap-1.5"><ScrubInput+ data-test-id="corner-tl-input":model-value="node.topLeftRadius":min="0"@update:model-value="updateCornerProp('topLeftRadius', $event)"@@ -139,6 +141,7 @@ function onToggleCorners() {</template></ScrubInput><ScrubInput+ data-test-id="corner-tr-input":model-value="node.topRightRadius":min="0"@update:model-value="updateCornerProp('topRightRadius', $event)"@@ -157,6 +160,7 @@ function onToggleCorners() {</template></ScrubInput><ScrubInput+ data-test-id="corner-bl-input":model-value="node.bottomLeftRadius":min="0"@update:model-value="updateCornerProp('bottomLeftRadius', $event)"@@ -175,6 +179,7 @@ function onToggleCorners() {</template></ScrubInput><ScrubInput+ data-test-id="corner-br-input":model-value="node.bottomRightRadius":min="0"@update:model-value="updateCornerProp('bottomRightRadius', $event)"diff --git a/src/components/properties/ColorStyleRow.vue b/src/components/properties/ColorStyleRow.vueindex e241a3ea5..b61800eee 100644--- a/src/components/properties/ColorStyleRow.vue+++ b/src/components/properties/ColorStyleRow.vue@@ -16,28 +16,22 @@ import Tip from '@/components/ui/Tip.vue'import { useIconButtonUI } from '@/components/ui/icon-button'import { ref } from 'vue'-import { colorToCSS } from '@open-pencil/core'import { useI18n } from '@open-pencil/vue'-import type { Variable } from '@open-pencil/core'+import {+ opacityFromPercent,+ opacityPercent,+ variableSwatchBackground+} from '@/components/properties/color-style-row'-type BindingApi = {- store: {- resolveColorVariable: (id: string) => unknown- }- colorVariables: { value: Variable[] }- filteredVariables: { value: Variable[] }- searchTerm: { value: string }- getBoundVariable: (nodeId: string, index: number) => Variable | undefined- bindVariable: (nodeId: string, index: number, variableId: string) => void- unbindVariable: (nodeId: string, index: number) => void-}+import type { ColorVariableBindingApi } from '@/components/properties/color-style-row'+import type { Variable } from '@open-pencil/core/scene-graph'const { item, index, activeNodeId, bindingApi, visibilityTestId, unbindTestId } = defineProps<{item: { opacity: number; visible: boolean }index: numberactiveNodeId?: string | null- bindingApi: BindingApi+ bindingApi: ColorVariableBindingApivisibilityTestId: stringunbindTestId?: string}>()@@ -61,10 +55,10 @@ const varPopoverOpen = ref(false)<ScrubInputclass="w-12 shrink-0"suffix="%"- :model-value="Math.round(item.opacity * 100)"+ :model-value="opacityPercent(item.opacity)":min="0":max="100"- @update:model-value="emit('patch', { opacity: Math.max(0, Math.min(1, $event / 100)) })"+ @update:model-value="emit('patch', { opacity: opacityFromPercent($event) })"/><PopoverRoot@@ -111,11 +105,7 @@ const varPopoverOpen = ref(false)><divclass="size-3 shrink-0 rounded-sm border border-border"- :style="{- background: bindingApi.store.resolveColorVariable(v.id)- ? colorToCSS(bindingApi.store.resolveColorVariable(v.id) as never)- : '#000'- }"+ :style="{ background: variableSwatchBackground(bindingApi, v.id) }"/><span class="min-w-0 flex-1 truncate">{{ v.name }}</span></ComboboxItem>@@ -140,6 +130,7 @@ const varPopoverOpen = ref(false)<button:data-test-id="visibilityTestId"+ :data-visible="item.visible ? 'true' : 'false'"class="shrink-0 cursor-pointer border-none bg-transparent p-0 text-muted hover:text-surface"@click="emit('toggleVisibility')">diff --git a/src/components/properties/EffectsSection.vue b/src/components/properties/EffectsSection.vueindex ad8069194..0db857573 100644--- a/src/components/properties/EffectsSection.vue+++ b/src/components/properties/EffectsSection.vue@@ -1,14 +1,14 @@<script setup lang="ts">import AppSelect from '@/components/ui/AppSelect.vue'-import ColorInput from '@/components/ColorInput.vue'+import ColorInput from '@/components/ColorPicker/ColorInput.vue'import ScrubInput from '@/components/ScrubInput.vue'import { useIconButtonUI } from '@/components/ui/icon-button'import { useSectionUI } from '@/components/ui/section'import { PropertyListRoot, useEffectsControls, useI18n } from '@open-pencil/vue'-import { colorToCSS } from '@open-pencil/core'+import { colorToCSS } from '@open-pencil/core/color'-import type { Effect } from '@open-pencil/core'+import type { Effect } from '@open-pencil/core/scene-graph'const effectsCtx = useEffectsControls()const { panels } = useI18n()@@ -66,6 +66,7 @@ const sectionCls = useSectionUI()<button:data-test-id="`effect-visibility-${i}`"+ :data-visible="effect.visible ? 'true' : 'false'"class="cursor-pointer border-none bg-transparent p-0 text-muted hover:text-surface"@click="toggleVisibility(i)">diff --git a/src/components/properties/ExportSection.vue b/src/components/properties/ExportSection.vueindex 44db4ea60..27b93acf3 100644--- a/src/components/properties/ExportSection.vue+++ b/src/components/properties/ExportSection.vue@@ -4,10 +4,10 @@ import { ref, computed, watch, onScopeDispose } from 'vue'import AppSelect from '@/components/ui/AppSelect.vue'import { useIconButtonUI } from '@/components/ui/icon-button'import { useSectionUI } from '@/components/ui/section'-import { useEditorStore } from '@/stores/editor'+import { useEditorStore } from '@/app/editor/active-store'import { useExport, useI18n } from '@open-pencil/vue'-import type { ExportFormatId } from '@open-pencil/vue/controls/useExport'+import type { ExportFormatId } from '@open-pencil/vue'const editorStore = useEditorStore()const { panels } = useI18n()@@ -144,9 +144,9 @@ onScopeDispose(() => {class="flex items-center gap-1.5 py-0.5"><AppSelect+ v-if="formatSupportsScale(setting.format)":model-value="setting.scale":options="SCALE_OPTIONS"- :disabled="!formatSupportsScale(setting.format)"@update:model-value="updateScale(i, Number($event))"/><AppSelectdiff --git a/src/components/properties/FillSection.vue b/src/components/properties/FillSection.vueindex dcc0492a6..149d3ca83 100644--- a/src/components/properties/FillSection.vue+++ b/src/components/properties/FillSection.vue@@ -1,13 +1,14 @@<script setup lang="ts">-import { colorToHexRaw } from '@open-pencil/core'import { PropertyListRoot, useFillControls, useOkHCL, useI18n } from '@open-pencil/vue'import FillPicker from '@/components/FillPicker.vue'import ColorStyleRow from '@/components/properties/ColorStyleRow.vue'+import { fillLabel } from '@/components/properties/fill-label'+import { createFillOkhclAdapter } from '@/components/properties/fill-okhcl'import { useIconButtonUI } from '@/components/ui/icon-button'import { useSectionUI } from '@/components/ui/section'-import type { Fill } from '@open-pencil/core'+import type { Fill } from '@open-pencil/core/scene-graph'const fillCtx = useFillControls()const okhcl = useOkHCL()@@ -50,37 +51,20 @@ const sectionCls = useSectionUI()><FillPicker:fill="fill"- :okhcl="- activeNode- ? {- fieldFormat: okhcl.getFieldFormat(activeNode, i, 'fill'),- fieldOptions: okhcl.fieldOptions,- okhcl: okhcl.getFillOkHCLColor(activeNode, i),- ...okhcl.getFillPreviewInfo(activeNode, i),- setFieldFormat: ($event) => okhcl.setFillFieldFormat(activeNode, i, $event),- updateOkHCL: ($event) => okhcl.updateFillOkHCL(activeNode, i, $event)- }- : null- "+ :okhcl="createFillOkhclAdapter(okhcl, activeNode, i)"@update="update(i, $event)"/>- <template v-if="activeNode && fillCtx.getBoundVariable(activeNode.id, i)">- <span- class="min-w-0 flex-1 truncate rounded bg-violet-500/10 px-1 font-mono text-xs text-violet-400"- >- {{ fillCtx.getBoundVariable(activeNode.id, i)!.name }}- </span>- </template>- <template v-else>- <span class="min-w-0 flex-1 font-mono text-xs text-surface">- <template v-if="fill.type === 'SOLID'">{{ colorToHexRaw(fill.color) }}</template>- <template v-else-if="fill.type.startsWith('GRADIENT')">{{- fill.type.replace('GRADIENT_', '')- }}</template>- <template v-else>{{ fill.type }}</template>- </span>- </template>+ <span+ class="min-w-0 flex-1 truncate font-mono text-xs"+ :class="+ activeNode && fillCtx.getBoundVariable(activeNode.id, i)+ ? 'rounded bg-violet-500/10 px-1 text-violet-400'+ : 'text-surface'+ "+ >+ {{ fillLabel(fill, activeNode ? fillCtx.getBoundVariable(activeNode.id, i) : undefined) }}+ </span></ColorStyleRow></div></PropertyListRoot>diff --git a/src/components/properties/LayoutSection.vue b/src/components/properties/LayoutSection.vuedeleted file mode 100644index 311fc185b..000000000--- a/src/components/properties/LayoutSection.vue+++ /dev/null@@ -1,389 +0,0 @@-<script setup lang="ts">-import {- SelectContent,- SelectItem,- SelectItemIndicator,- SelectItemText,- SelectPortal,- SelectRoot,- SelectTrigger,- SelectViewport-} from 'reka-ui'--import { LayoutControlsRoot, useI18n } from '@open-pencil/vue'--import AppSelect from '@/components/ui/AppSelect.vue'-import ScrubInput from '@/components/ScrubInput.vue'-import Tip from '@/components/ui/Tip.vue'-import { useSelectUI } from '@/components/ui/select'-import { useSectionUI } from '@/components/ui/section'--import type { LayoutSizing } from '@open-pencil/core'--const { panels } = useI18n()-const sectionCls = useSectionUI()--const CONTAINER_TYPES = ['FRAME', 'COMPONENT', 'COMPONENT_SET', 'INSTANCE']--const sizingSelect = useSelectUI({- item: 'rounded py-1.5 pr-2 pl-6 text-xs'-})--function sizingShortLabel(sizing: LayoutSizing): string | null {- if (sizing === 'HUG') return panels.value.sizingHugShort- if (sizing === 'FILL') return panels.value.sizingFillShort- return null-}-</script>--<template>- <LayoutControlsRoot v-slot="ctx">- <template v-if="ctx.node">- <div data-test-id="layout-section" :class="sectionCls.wrapper">- <label class="mb-1.5 block text-[11px] text-muted">{{ panels.layout }}</label>- <div class="flex gap-1.5">- <ScrubInput- icon="W"- :model-value="Math.round(ctx.node.width)"- :min="0"- @update:model-value="ctx.updateProp('width', $event)"- @commit="(v: number, p: number) => ctx.commitProp('width', v, p)"- >- <template v-if="ctx.isFlex || ctx.isInAutoLayout" #suffix>- <SelectRoot- :model-value="ctx.widthSizing"- @update:model-value="ctx.setWidthSizing($event as LayoutSizing)"- >- <SelectTrigger- class="flex shrink-0 cursor-pointer items-center self-stretch border-none bg-transparent px-1 text-[11px] text-muted outline-none"- @pointerdown.stop- >- <span class="group-hover:hidden">{{ sizingShortLabel(ctx.widthSizing) }}</span>- <icon-lucide-chevron-down class="hidden size-3 group-hover:block" />- </SelectTrigger>- <SelectPortal>- <SelectContent- position="popper"- align="start"- :side-offset="2"- :class="sizingSelect.content"- >- <SelectViewport class="p-0.5">- <SelectItem- v-for="opt in ctx.widthSizingOptions"- :key="opt.value"- :value="opt.value"- :class="sizingSelect.item"- >- <SelectItemIndicator- class="absolute left-1.5 inline-flex items-center justify-center"- >- <icon-lucide-check class="size-3 text-accent" />- </SelectItemIndicator>- <SelectItemText>{{ opt.label }}</SelectItemText>- </SelectItem>- </SelectViewport>- </SelectContent>- </SelectPortal>- </SelectRoot>- </template>- </ScrubInput>- <ScrubInput- icon="H"- :model-value="Math.round(ctx.node.height)"- :min="0"- @update:model-value="ctx.updateProp('height', $event)"- @commit="(v: number, p: number) => ctx.commitProp('height', v, p)"- >- <template v-if="ctx.isFlex || ctx.isInAutoLayout" #suffix>- <SelectRoot- :model-value="ctx.heightSizing"- @update:model-value="ctx.setHeightSizing($event as LayoutSizing)"- >- <SelectTrigger- class="flex shrink-0 cursor-pointer items-center self-stretch border-none bg-transparent px-1 text-[11px] text-muted outline-none"- @pointerdown.stop- >- <span class="group-hover:hidden">{{ sizingShortLabel(ctx.heightSizing) }}</span>- <icon-lucide-chevron-down class="hidden size-3 group-hover:block" />- </SelectTrigger>- <SelectPortal>- <SelectContent- position="popper"- align="start"- :side-offset="2"- :class="sizingSelect.content"- >- <SelectViewport class="p-0.5">- <SelectItem- v-for="opt in ctx.heightSizingOptions"- :key="opt.value"- :value="opt.value"- :class="sizingSelect.item"- >- <SelectItemIndicator- class="absolute left-1.5 inline-flex items-center justify-center"- >- <icon-lucide-check class="size-3 text-accent" />- </SelectItemIndicator>- <SelectItemText>{{ opt.label }}</SelectItemText>- </SelectItem>- </SelectViewport>- </SelectContent>- </SelectPortal>- </SelectRoot>- </template>- </ScrubInput>- </div>- </div>-- <template v-if="CONTAINER_TYPES.includes(ctx.node.type)">- <div :class="sectionCls.wrapper">- <div class="flex items-center justify-between">- <label class="mb-1.5 block text-[11px] text-muted">{{ panels.autoLayout }}</label>- <Tip v-if="ctx.node.layoutMode === 'NONE'" :label="panels.addAutoLayout">- <button- class="cursor-pointer rounded border-none bg-transparent px-1 text-base leading-none text-muted hover:bg-hover hover:text-surface"- data-test-id="layout-add-auto"- @click="ctx.editor.setLayoutMode(ctx.node.id, 'VERTICAL')"- >- +- </button>- </Tip>- <Tip v-else :label="panels.removeAutoLayout">- <button- class="cursor-pointer rounded border-none bg-transparent px-1 text-base leading-none text-muted hover:bg-hover hover:text-surface"- data-test-id="layout-remove-auto"- @click="ctx.editor.setLayoutMode(ctx.node.id, 'NONE')"- >- −- </button>- </Tip>- </div>-- <template v-if="ctx.node.layoutMode !== 'NONE'">- <div class="mt-1.5 flex gap-0.5">- <button- v-for="dir in [- { mode: 'HORIZONTAL', test: 'horizontal' },- { mode: 'VERTICAL', test: 'vertical' },- { mode: 'GRID', test: 'grid' }- ] as const"- :key="dir.mode"- :data-test-id="`layout-direction-${dir.test}`"- class="flex cursor-pointer items-center justify-center rounded border px-2 py-1"- :class="- (dir.mode === 'GRID' ? ctx.isGrid : ctx.node.layoutMode === dir.mode)- ? 'border-accent bg-accent/10 text-accent'- : 'border-border text-muted hover:bg-hover hover:text-surface'- "- @click="ctx.editor.setLayoutMode(ctx.node.id, dir.mode)"- >- <icon-lucide-arrow-right v-if="dir.mode === 'HORIZONTAL'" class="size-3.5" />- <icon-lucide-arrow-down v-else-if="dir.mode === 'VERTICAL'" class="size-3.5" />- <icon-lucide-layout-grid v-else class="size-3.5" />- </button>- <button- v-if="ctx.isFlex"- data-test-id="layout-direction-wrap"- class="flex cursor-pointer items-center justify-center rounded border px-2 py-1"- :class="- ctx.node.layoutWrap === 'WRAP'- ? 'border-accent bg-accent/10 text-accent'- : 'border-border text-muted hover:bg-hover hover:text-surface'- "- @click="- ctx.updateProp('layoutWrap', ctx.node.layoutWrap === 'WRAP' ? 'NO_WRAP' : 'WRAP')- "- >- <icon-lucide-wrap-text class="size-3.5" />- </button>- </div>-- <div v-if="ctx.isFlex" class="mt-2">- <label class="mb-1 block text-[11px] text-muted">{{ panels.flow }}</label>- <AppSelect- :model-value="ctx.layoutDirection"- :options="[- { value: 'AUTO', label: panels.auto },- { value: 'LTR', label: 'LTR' },- { value: 'RTL', label: 'RTL' }- ]"- @update:model-value="ctx.setLayoutDirection($event as 'AUTO' | 'LTR' | 'RTL')"- />- </div>-- <template v-if="ctx.isGrid">- <div- v-for="trackProp in ['gridTemplateColumns', 'gridTemplateRows'] as const"- :key="trackProp"- class="mt-2"- >- <div class="mb-1 flex items-center justify-between">- <label class="text-[11px] text-muted">{{- trackProp === 'gridTemplateColumns' ? panels.columns : panels.rows- }}</label>- <button- class="cursor-pointer rounded border-none bg-transparent px-1 text-xs leading-none text-muted hover:bg-hover hover:text-surface"- @click="ctx.addTrack(trackProp)"- >- +- </button>- </div>- <div class="flex flex-col gap-1">- <div- v-for="(track, i) in ctx.node[trackProp]"- :key="i"- class="flex items-center gap-1"- >- <ScrubInput- v-if="track.sizing !== 'AUTO'"- class="flex-1"- :icon="`${trackProp === 'gridTemplateColumns' ? 'C' : 'R'}${i + 1}`"- :model-value="track.value"- :min="track.sizing === 'FR' ? 1 : 0"- :suffix="track.sizing === 'FR' ? 'fr' : 'px'"- @update:model-value="ctx.updateGridTrack(trackProp, i, { value: $event })"- />- <span v-else class="flex-1 px-1 text-xs text-muted">{{- ctx.trackLabel(track)- }}</span>- <AppSelect- :model-value="track.sizing"- :options="ctx.trackSizingOptions"- @update:model-value="- ctx.updateGridTrack(trackProp, i, {- sizing: $event,- value: $event === 'FR' ? 1 : $event === 'FIXED' ? 100 : 0- })- "- />- <button- v-if="ctx.node[trackProp].length > 1"- class="cursor-pointer rounded border-none bg-transparent px-0.5 text-xs text-muted hover:text-surface"- @click="ctx.removeTrack(trackProp, i)"- >- ×- </button>- </div>- </div>- </div>- <div class="mt-2 grid grid-cols-2 gap-1.5">- <ScrubInput- icon="↔"- :model-value="Math.round(ctx.node.gridColumnGap)"- :min="0"- @update:model-value="ctx.updateProp('gridColumnGap', $event)"- @commit="(v: number, p: number) => ctx.commitProp('gridColumnGap', v, p)"- />- <ScrubInput- icon="↕"- :model-value="Math.round(ctx.node.gridRowGap)"- :min="0"- @update:model-value="ctx.updateProp('gridRowGap', $event)"- @commit="(v: number, p: number) => ctx.commitProp('gridRowGap', v, p)"- />- </div>- </template>-- <template v-if="ctx.isFlex">- <div class="mt-2 flex items-center gap-1.5">- <ScrubInput- data-test-id="layout-gap-input"- class="flex-1"- :icon="ctx.node.layoutMode === 'VERTICAL' ? '↕' : '↔'"- :model-value="Math.round(ctx.node.itemSpacing)"- :min="0"- @update:model-value="ctx.updateProp('itemSpacing', $event)"- @commit="(v: number, p: number) => ctx.commitProp('itemSpacing', v, p)"- />- <button- class="flex size-7 shrink-0 cursor-pointer items-center justify-center rounded border border-border bg-transparent text-muted hover:bg-hover hover:text-surface"- @click="ctx.toggleIndividualPadding"- >- <icon-lucide-minus- v-if="ctx.showIndividualPadding || !ctx.hasUniformPadding"- class="size-3"- />- <icon-lucide-plus v-else class="size-3" />- </button>- </div>- <div v-if="!ctx.showIndividualPadding && ctx.hasUniformPadding" class="mt-1.5">- <ScrubInput- data-test-id="layout-uniform-padding-input"- icon="☐"- :model-value="Math.round(ctx.node.paddingTop)"- :min="0"- @update:model-value="ctx.setUniformPadding"- @commit="ctx.commitUniformPadding"- />- </div>- </template>-- <template- v-if="- ctx.isGrid || (ctx.isFlex && (ctx.showIndividualPadding || !ctx.hasUniformPadding))- "- >- <div class="mt-1.5 grid grid-cols-2 gap-1.5">- <ScrubInput- v-for="side in [- 'paddingTop',- 'paddingRight',- 'paddingBottom',- 'paddingLeft'- ] as const"- :key="side"- :icon="side[7]"- :model-value="Math.round(ctx.node[side])"- :min="0"- @update:model-value="ctx.updateProp(side, $event)"- @commit="(v: number, p: number) => ctx.commitProp(side, v, p)"- />- </div>- </template>-- <div v-if="ctx.isFlex" class="mt-2">- <label class="mb-1 block text-[11px] text-muted">{{ panels.alignment }}</label>- <div data-test-id="layout-alignment-grid" class="grid w-fit grid-cols-3 gap-0.5">- <button- v-for="cell in ctx.alignGrid"- :key="`${cell.primary}-${cell.counter}`"- class="flex size-6 cursor-pointer items-center justify-center rounded border text-[11px]"- :class="- ctx.node.primaryAxisAlign === cell.primary &&- ctx.node.counterAxisAlign === cell.counter- ? 'border-accent bg-accent/10 text-accent'- : 'border-border text-muted hover:bg-hover hover:text-surface'- "- @click="ctx.setAlignment(cell.primary, cell.counter)"- >- <span class="size-1.5 rounded-full bg-current" />- </button>- </div>- </div>- </template>- </div>-- <div :class="sectionCls.wrapper">- <label class="flex cursor-pointer items-center gap-2 text-xs text-surface">- <input- type="checkbox"- data-test-id="clip-content-checkbox"- class="accent-accent"- :checked="ctx.node.clipsContent"- @change="- ctx.editor.updateNodeWithUndo(- ctx.node.id,- { clipsContent: !ctx.node.clipsContent },- 'Toggle clip content'- )- "- />- {{ panels.clipContent }}- </label>- </div>- </template>- </template>- </LayoutControlsRoot>-</template>diff --git a/src/components/properties/LayoutSection/AutoLayoutControls.vue b/src/components/properties/LayoutSection/AutoLayoutControls.vuenew file mode 100644index 000000000..f988db3b1--- /dev/null+++ b/src/components/properties/LayoutSection/AutoLayoutControls.vue@@ -0,0 +1,72 @@+<script setup lang="ts">+import Tip from '@/components/ui/Tip.vue'+import { useI18n, useLayoutControlsContext } from '@open-pencil/vue'++import type { LayoutMode } from '@open-pencil/core/scene-graph'++const ctx = useLayoutControlsContext()++const { panels } = useI18n()++const layoutModes: { mode: LayoutMode; test: string }[] = [+ { mode: 'HORIZONTAL', test: 'horizontal' },+ { mode: 'VERTICAL', test: 'vertical' },+ { mode: 'GRID', test: 'grid' }+]+</script>++<template>+ <div class="flex items-center justify-between">+ <label class="mb-1.5 block text-[11px] text-muted">{{ panels.autoLayout }}</label>+ <Tip v-if="ctx.node.layoutMode === 'NONE'" :label="panels.addAutoLayout">+ <button+ class="cursor-pointer rounded border-none bg-transparent px-1 text-base leading-none text-muted hover:bg-hover hover:text-surface"+ data-test-id="layout-add-auto"+ @click="ctx.editor.setLayoutMode(ctx.node.id, 'VERTICAL')"+ >+ ++ </button>+ </Tip>+ <Tip v-else :label="panels.removeAutoLayout">+ <button+ class="cursor-pointer rounded border-none bg-transparent px-1 text-base leading-none text-muted hover:bg-hover hover:text-surface"+ data-test-id="layout-remove-auto"+ @click="ctx.editor.setLayoutMode(ctx.node.id, 'NONE')"+ >+ −+ </button>+ </Tip>+ </div>++ <div v-if="ctx.node.layoutMode !== 'NONE'" class="mt-1.5 flex gap-0.5">+ <button+ v-for="dir in layoutModes"+ :key="dir.mode"+ :data-test-id="`layout-direction-${dir.test}`"+ class="flex cursor-pointer items-center justify-center rounded border px-2 py-1"+ :class="+ (dir.mode === 'GRID' ? ctx.isGrid : ctx.node.layoutMode === dir.mode)+ ? 'border-accent bg-accent/10 text-accent'+ : 'border-border text-muted hover:bg-hover hover:text-surface'+ "+ @click="ctx.editor.setLayoutMode(ctx.node.id, dir.mode)"+ >+ <icon-lucide-arrow-right v-if="dir.mode === 'HORIZONTAL'" class="size-3.5" />+ <icon-lucide-arrow-down v-else-if="dir.mode === 'VERTICAL'" class="size-3.5" />+ <icon-lucide-layout-grid v-else class="size-3.5" />+ </button>+ <button+ v-if="ctx.isFlex"+ data-test-id="layout-direction-wrap"+ class="flex cursor-pointer items-center justify-center rounded border px-2 py-1"+ :class="+ ctx.node.layoutWrap === 'WRAP'+ ? 'border-accent bg-accent/10 text-accent'+ : 'border-border text-muted hover:bg-hover hover:text-surface'+ "+ @click="ctx.updateProp('layoutWrap', ctx.node.layoutWrap === 'WRAP' ? 'NO_WRAP' : 'WRAP')"+ >+ <icon-lucide-wrap-text class="size-3.5" />+ </button>+ </div>+</template>diff --git a/src/components/properties/LayoutSection/ClipContentControl.vue b/src/components/properties/LayoutSection/ClipContentControl.vuenew file mode 100644index 000000000..d0bde21d2--- /dev/null+++ b/src/components/properties/LayoutSection/ClipContentControl.vue@@ -0,0 +1,26 @@+<script setup lang="ts">+import { useI18n, useLayoutControlsContext } from '@open-pencil/vue'++const ctx = useLayoutControlsContext()++const { panels } = useI18n()+</script>++<template>+ <label class="flex cursor-pointer items-center gap-2 text-xs text-surface">+ <input+ type="checkbox"+ data-test-id="clip-content-checkbox"+ class="accent-accent"+ :checked="ctx.node.clipsContent"+ @change="+ ctx.editor.updateNodeWithUndo(+ ctx.node.id,+ { clipsContent: !ctx.node.clipsContent },+ 'Toggle clip content'+ )+ "+ />+ {{ panels.clipContent }}+ </label>+</template>diff --git a/src/components/properties/LayoutSection/FlexControls.vue b/src/components/properties/LayoutSection/FlexControls.vuenew file mode 100644index 000000000..e4db64357--- /dev/null+++ b/src/components/properties/LayoutSection/FlexControls.vue@@ -0,0 +1,70 @@+<script setup lang="ts">+import AppSelect from '@/components/ui/AppSelect.vue'+import ScrubInput from '@/components/ScrubInput.vue'+import PaddingControls from '@/components/properties/LayoutSection/PaddingControls.vue'+import { useI18n, useLayoutControlsContext } from '@open-pencil/vue'++import type { LayoutDirection } from '@open-pencil/core/scene-graph'++const ctx = useLayoutControlsContext()++const { panels } = useI18n()+</script>++<template>+ <div class="mt-2">+ <label class="mb-1 block text-[11px] text-muted">{{ panels.flow }}</label>+ <AppSelect+ :model-value="ctx.layoutDirection"+ :options="[+ { value: 'AUTO', label: panels.auto },+ { value: 'LTR', label: 'LTR' },+ { value: 'RTL', label: 'RTL' }+ ]"+ @update:model-value="ctx.setLayoutDirection($event as LayoutDirection)"+ />+ </div>++ <div class="mt-2 flex items-center gap-1.5">+ <ScrubInput+ data-test-id="layout-gap-input"+ class="flex-1"+ :icon="ctx.node.layoutMode === 'VERTICAL' ? '↕' : '↔'"+ :model-value="Math.round(ctx.node.itemSpacing)"+ :min="0"+ @update:model-value="ctx.updateProp('itemSpacing', $event)"+ @commit="(v: number, p: number) => ctx.commitProp('itemSpacing', v, p)"+ />+ <button+ class="flex size-7 shrink-0 cursor-pointer items-center justify-center rounded border border-border bg-transparent text-muted hover:bg-hover hover:text-surface"+ @click="ctx.toggleIndividualPadding"+ >+ <icon-lucide-minus+ v-if="ctx.showIndividualPadding || !ctx.hasUniformPadding"+ class="size-3"+ />+ <icon-lucide-plus v-else class="size-3" />+ </button>+ </div>++ <PaddingControls />++ <div class="mt-2">+ <label class="mb-1 block text-[11px] text-muted">{{ panels.alignment }}</label>+ <div data-test-id="layout-alignment-grid" class="grid w-fit grid-cols-3 gap-0.5">+ <button+ v-for="cell in ctx.alignGrid"+ :key="`${cell.primary}-${cell.counter}`"+ class="flex size-6 cursor-pointer items-center justify-center rounded border text-[11px]"+ :class="+ ctx.node.primaryAxisAlign === cell.primary && ctx.node.counterAxisAlign === cell.counter+ ? 'border-accent bg-accent/10 text-accent'+ : 'border-border text-muted hover:bg-hover hover:text-surface'+ "+ @click="ctx.setAlignment(cell.primary, cell.counter)"+ >+ <span class="size-1.5 rounded-full bg-current" />+ </button>+ </div>+ </div>+</template>diff --git a/src/components/properties/LayoutSection/GridControls.vue b/src/components/properties/LayoutSection/GridControls.vuenew file mode 100644index 000000000..e382c240b--- /dev/null+++ b/src/components/properties/LayoutSection/GridControls.vue@@ -0,0 +1,85 @@+<script setup lang="ts">+import AppSelect from '@/components/ui/AppSelect.vue'+import ScrubInput from '@/components/ScrubInput.vue'+import { useI18n, useLayoutControlsContext } from '@open-pencil/vue'++import type { GridTrackProp } from '@/components/properties/LayoutSection/types'+import type { GridTrackSizing } from '@open-pencil/core/scene-graph'++const ctx = useLayoutControlsContext()++const { panels } = useI18n()+const trackProps: GridTrackProp[] = ['gridTemplateColumns', 'gridTemplateRows']++function defaultTrackValue(sizing: GridTrackSizing): number {+ if (sizing === 'FR') return 1+ if (sizing === 'FIXED') return 100+ return 0+}+</script>++<template>+ <template v-for="trackProp in trackProps" :key="trackProp">+ <div class="mt-2">+ <div class="mb-1 flex items-center justify-between">+ <label class="text-[11px] text-muted">+ {{ trackProp === 'gridTemplateColumns' ? panels.columns : panels.rows }}+ </label>+ <button+ class="cursor-pointer rounded border-none bg-transparent px-1 text-xs leading-none text-muted hover:bg-hover hover:text-surface"+ @click="ctx.addTrack(trackProp)"+ >+ ++ </button>+ </div>+ <div class="flex flex-col gap-1">+ <div v-for="(track, i) in ctx.node[trackProp]" :key="i" class="flex items-center gap-1">+ <ScrubInput+ v-if="track.sizing !== 'AUTO'"+ class="flex-1"+ :icon="`${trackProp === 'gridTemplateColumns' ? 'C' : 'R'}${i + 1}`"+ :model-value="track.value"+ :min="track.sizing === 'FR' ? 1 : 0"+ :suffix="track.sizing === 'FR' ? 'fr' : 'px'"+ @update:model-value="ctx.updateGridTrack(trackProp, i, { value: $event })"+ />+ <span v-else class="flex-1 px-1 text-xs text-muted">{{ ctx.trackLabel(track) }}</span>+ <AppSelect+ :model-value="track.sizing"+ :options="ctx.trackSizingOptions"+ @update:model-value="+ ctx.updateGridTrack(trackProp, i, {+ sizing: $event as GridTrackSizing,+ value: defaultTrackValue($event as GridTrackSizing)+ })+ "+ />+ <button+ v-if="ctx.node[trackProp].length > 1"+ class="cursor-pointer rounded border-none bg-transparent px-0.5 text-xs text-muted hover:text-surface"+ @click="ctx.removeTrack(trackProp, i)"+ >+ ×+ </button>+ </div>+ </div>+ </div>+ </template>++ <div class="mt-2 grid grid-cols-2 gap-1.5">+ <ScrubInput+ icon="↔"+ :model-value="Math.round(ctx.node.gridColumnGap)"+ :min="0"+ @update:model-value="ctx.updateProp('gridColumnGap', $event)"+ @commit="(v: number, p: number) => ctx.commitProp('gridColumnGap', v, p)"+ />+ <ScrubInput+ icon="↕"+ :model-value="Math.round(ctx.node.gridRowGap)"+ :min="0"+ @update:model-value="ctx.updateProp('gridRowGap', $event)"+ @commit="(v: number, p: number) => ctx.commitProp('gridRowGap', v, p)"+ />+ </div>+</template>diff --git a/src/components/properties/LayoutSection/LayoutSection.vue b/src/components/properties/LayoutSection/LayoutSection.vuenew file mode 100644index 000000000..d013c8ea6--- /dev/null+++ b/src/components/properties/LayoutSection/LayoutSection.vue@@ -0,0 +1,45 @@+<script setup lang="ts">+import { LayoutControlsRoot, useI18n } from '@open-pencil/vue'++import AutoLayoutControls from '@/components/properties/LayoutSection/AutoLayoutControls.vue'+import ClipContentControl from '@/components/properties/LayoutSection/ClipContentControl.vue'+import FlexControls from '@/components/properties/LayoutSection/FlexControls.vue'+import GridControls from '@/components/properties/LayoutSection/GridControls.vue'+import PaddingControls from '@/components/properties/LayoutSection/PaddingControls.vue'+import SizeControls from '@/components/properties/LayoutSection/SizeControls.vue'+import { useSectionUI } from '@/components/ui/section'++const { panels } = useI18n()+const sectionCls = useSectionUI()++const CONTAINER_TYPES = ['FRAME', 'COMPONENT', 'COMPONENT_SET', 'INSTANCE']+</script>++<template>+ <LayoutControlsRoot v-slot="ctx">+ <template v-if="ctx.node">+ <div data-test-id="layout-section" :class="sectionCls.wrapper">+ <label class="mb-1.5 block text-[11px] text-muted">{{ panels.layout }}</label>+ <SizeControls />+ </div>++ <template v-if="CONTAINER_TYPES.includes(ctx.node.type)">+ <div :class="sectionCls.wrapper">+ <AutoLayoutControls />++ <template v-if="ctx.node.layoutMode !== 'NONE'">+ <FlexControls v-if="ctx.isFlex" />+ <template v-if="ctx.isGrid">+ <GridControls />+ <PaddingControls />+ </template>+ </template>+ </div>++ <div :class="sectionCls.wrapper">+ <ClipContentControl />+ </div>+ </template>+ </template>+ </LayoutControlsRoot>+</template>diff --git a/src/components/properties/LayoutSection/PaddingControls.vue b/src/components/properties/LayoutSection/PaddingControls.vuenew file mode 100644index 000000000..72c4cef2c--- /dev/null+++ b/src/components/properties/LayoutSection/PaddingControls.vue@@ -0,0 +1,38 @@+<script setup lang="ts">+import ScrubInput from '@/components/ScrubInput.vue'+import { useLayoutControlsContext } from '@open-pencil/vue'++import type { PaddingProp } from '@/components/properties/LayoutSection/types'++const ctx = useLayoutControlsContext()++const paddingSides: PaddingProp[] = ['paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft']+</script>++<template>+ <div v-if="!ctx.showIndividualPadding && ctx.hasUniformPadding" class="mt-1.5">+ <ScrubInput+ data-test-id="layout-uniform-padding-input"+ icon="☐"+ :model-value="Math.round(ctx.node.paddingTop)"+ :min="0"+ @update:model-value="ctx.setUniformPadding"+ @commit="ctx.commitUniformPadding"+ />+ </div>++ <div+ v-if="ctx.isGrid || (ctx.isFlex && (ctx.showIndividualPadding || !ctx.hasUniformPadding))"+ class="mt-1.5 grid grid-cols-2 gap-1.5"+ >+ <ScrubInput+ v-for="side in paddingSides"+ :key="side"+ :icon="side[7]"+ :model-value="Math.round(ctx.node[side])"+ :min="0"+ @update:model-value="ctx.updateProp(side, $event)"+ @commit="(v: number, p: number) => ctx.commitProp(side, v, p)"+ />+ </div>+</template>diff --git a/src/components/properties/LayoutSection/SizeControls.vue b/src/components/properties/LayoutSection/SizeControls.vuenew file mode 100644index 000000000..e30c02cd7--- /dev/null+++ b/src/components/properties/LayoutSection/SizeControls.vue@@ -0,0 +1,127 @@+<script setup lang="ts">+import {+ SelectContent,+ SelectItem,+ SelectItemIndicator,+ SelectItemText,+ SelectPortal,+ SelectRoot,+ SelectTrigger,+ SelectViewport+} from 'reka-ui'++import ScrubInput from '@/components/ScrubInput.vue'+import { useSelectUI } from '@/components/ui/select'+import { useI18n, useLayoutControlsContext } from '@open-pencil/vue'++import type { LayoutSizing } from '@open-pencil/core/scene-graph'++const ctx = useLayoutControlsContext()++const { panels } = useI18n()+const sizingSelect = useSelectUI({ item: 'rounded py-1.5 pr-2 pl-6 text-xs' })++function sizingShortLabel(sizing: LayoutSizing): string | null {+ if (sizing === 'HUG') return panels.value.sizingHugShort+ if (sizing === 'FILL') return panels.value.sizingFillShort+ return null+}+</script>++<template>+ <div class="flex gap-1.5">+ <ScrubInput+ icon="W"+ :model-value="Math.round(ctx.node.width)"+ :min="0"+ @update:model-value="ctx.updateProp('width', $event)"+ @commit="(v: number, p: number) => ctx.commitProp('width', v, p)"+ >+ <template v-if="ctx.isFlex || ctx.isInAutoLayout" #suffix>+ <SelectRoot+ :model-value="ctx.widthSizing"+ @update:model-value="ctx.setWidthSizing($event as LayoutSizing)"+ >+ <SelectTrigger+ class="flex shrink-0 cursor-pointer items-center self-stretch border-none bg-transparent px-1 text-[11px] text-muted outline-none"+ @pointerdown.stop+ >+ <span class="group-hover:hidden">{{ sizingShortLabel(ctx.widthSizing) }}</span>+ <icon-lucide-chevron-down class="hidden size-3 group-hover:block" />+ </SelectTrigger>+ <SelectPortal>+ <SelectContent+ position="popper"+ align="start"+ :side-offset="2"+ :class="sizingSelect.content"+ >+ <SelectViewport class="p-0.5">+ <SelectItem+ v-for="opt in ctx.widthSizingOptions"+ :key="opt.value"+ :value="opt.value"+ :class="sizingSelect.item"+ >+ <SelectItemIndicator+ class="absolute left-1.5 inline-flex items-center justify-center"+ >+ <icon-lucide-check class="size-3 text-accent" />+ </SelectItemIndicator>+ <SelectItemText>{{ opt.label }}</SelectItemText>+ </SelectItem>+ </SelectViewport>+ </SelectContent>+ </SelectPortal>+ </SelectRoot>+ </template>+ </ScrubInput>++ <ScrubInput+ icon="H"+ :model-value="Math.round(ctx.node.height)"+ :min="0"+ @update:model-value="ctx.updateProp('height', $event)"+ @commit="(v: number, p: number) => ctx.commitProp('height', v, p)"+ >+ <template v-if="ctx.isFlex || ctx.isInAutoLayout" #suffix>+ <SelectRoot+ :model-value="ctx.heightSizing"+ @update:model-value="ctx.setHeightSizing($event as LayoutSizing)"+ >+ <SelectTrigger+ class="flex shrink-0 cursor-pointer items-center self-stretch border-none bg-transparent px-1 text-[11px] text-muted outline-none"+ @pointerdown.stop+ >+ <span class="group-hover:hidden">{{ sizingShortLabel(ctx.heightSizing) }}</span>+ <icon-lucide-chevron-down class="hidden size-3 group-hover:block" />+ </SelectTrigger>+ <SelectPortal>+ <SelectContent+ position="popper"+ align="start"+ :side-offset="2"+ :class="sizingSelect.content"+ >+ <SelectViewport class="p-0.5">+ <SelectItem+ v-for="opt in ctx.heightSizingOptions"+ :key="opt.value"+ :value="opt.value"+ :class="sizingSelect.item"+ >+ <SelectItemIndicator+ class="absolute left-1.5 inline-flex items-center justify-center"+ >+ <icon-lucide-check class="size-3 text-accent" />+ </SelectItemIndicator>+ <SelectItemText>{{ opt.label }}</SelectItemText>+ </SelectItem>+ </SelectViewport>+ </SelectContent>+ </SelectPortal>+ </SelectRoot>+ </template>+ </ScrubInput>+ </div>+</template>diff --git a/src/components/properties/LayoutSection/types.ts b/src/components/properties/LayoutSection/types.tsnew file mode 100644index 000000000..753bcea64--- /dev/null+++ b/src/components/properties/LayoutSection/types.ts@@ -0,0 +1,2 @@+export type GridTrackProp = 'gridTemplateColumns' | 'gridTemplateRows'+export type PaddingProp = 'paddingTop' | 'paddingRight' | 'paddingBottom' | 'paddingLeft'diff --git a/src/components/properties/PageSection.vue b/src/components/properties/PageSection.vueindex 3d5d46141..6bda96474 100644--- a/src/components/properties/PageSection.vue+++ b/src/components/properties/PageSection.vue@@ -2,10 +2,10 @@import { computed } from 'vue'import { useI18n } from '@open-pencil/vue'-import ColorInput from '@/components/ColorInput.vue'+import ColorInput from '@/components/ColorPicker/ColorInput.vue'import { useSectionUI } from '@/components/ui/section'-import { useEditorStore } from '@/stores/editor'+import { useEditorStore } from '@/app/editor/active-store'const editor = useEditorStore()const pageColor = computed(() => editor.state.pageColor)diff --git a/src/components/properties/PositionSection.vue b/src/components/properties/PositionSection.vueindex 4a07c5ab4..2e3e8001e 100644--- a/src/components/properties/PositionSection.vue+++ b/src/components/properties/PositionSection.vue@@ -3,7 +3,7 @@ import ScrubInput from '@/components/ScrubInput.vue'import Tip from '@/components/ui/Tip.vue'import { useIconButtonUI } from '@/components/ui/icon-button'import { useSectionUI } from '@/components/ui/section'-import { useEditorStore } from '@/stores/editor'+import { useEditorStore } from '@/app/editor/active-store'import { PositionControlsRoot, useI18n } from '@open-pencil/vue'const { panels } = useI18n()diff --git a/src/components/properties/StrokeSection.vue b/src/components/properties/StrokeSection.vueindex 9e33f62a7..4722b17aa 100644--- a/src/components/properties/StrokeSection.vue+++ b/src/components/properties/StrokeSection.vue@@ -12,13 +12,13 @@ import {import ColorStyleRow from '@/components/properties/ColorStyleRow.vue'import AppSelect from '@/components/ui/AppSelect.vue'-import ColorInput from '@/components/ColorInput.vue'+import ColorInput from '@/components/ColorPicker/ColorInput.vue'import ScrubInput from '@/components/ScrubInput.vue'import Tip from '@/components/ui/Tip.vue'import { useIconButtonUI } from '@/components/ui/icon-button'import { useSectionUI } from '@/components/ui/section'-import type { SceneNode, Stroke } from '@open-pencil/core'+import type { SceneNode, Stroke } from '@open-pencil/core/scene-graph'const strokeCtx = useStrokeControls()const strokeVarCtx = useColorVariableBinding('strokes')diff --git a/src/components/properties/TypographySection.vue b/src/components/properties/TypographySection.vueindex 9e165eca9..acc4329e9 100644--- a/src/components/properties/TypographySection.vue+++ b/src/components/properties/TypographySection.vue@@ -8,7 +8,7 @@ import ScrubInput from '@/components/ScrubInput.vue'import AppSelect from '@/components/ui/AppSelect.vue'import Tip from '@/components/ui/Tip.vue'import { useSectionUI } from '@/components/ui/section'-import { loadFont } from '@/engine/fonts'+import { loadFont } from '@/app/editor/fonts'const { panels } = useI18n()const sectionCls = useSectionUI()@@ -115,46 +115,45 @@ const sectionCls = useSectionUI()<icon-lucide-align-right v-else class="size-3.5" /></ToggleGroupItem></ToggleGroupRoot>- <ToggleGroupRoot- type="multiple"- class="flex gap-0.5"- :model-value="ctx.activeFormatting.value"- @update:model-value="ctx.onFormattingChange"- >+ <div class="flex gap-0.5"><Tip label="Bold (⌘B)">- <ToggleGroupItem- value="bold"+ <buttondata-test-id="typography-bold-button"class="flex cursor-pointer items-center justify-center rounded border border-border bg-input px-2 py-1 font-bold text-muted hover:bg-hover hover:text-surface data-[state=on]:border-accent data-[state=on]:bg-accent data-[state=on]:text-white"+ :data-state="ctx.activeFormatting.value.includes('bold') ? 'on' : 'off'"+ @click="ctx.toggleBold"><icon-lucide-bold class="size-3.5" />- </ToggleGroupItem>+ </button></Tip><Tip label="Italic (⌘I)">- <ToggleGroupItem- value="italic"+ <buttonclass="flex cursor-pointer items-center justify-center rounded border border-border bg-input px-2 py-1 text-muted hover:bg-hover hover:text-surface data-[state=on]:border-accent data-[state=on]:bg-accent data-[state=on]:text-white"+ :data-state="ctx.activeFormatting.value.includes('italic') ? 'on' : 'off'"+ @click="ctx.toggleItalic"><icon-lucide-italic class="size-3.5" />- </ToggleGroupItem>+ </button></Tip><Tip label="Underline (⌘U)">- <ToggleGroupItem- value="underline"+ <buttonclass="flex cursor-pointer items-center justify-center rounded border border-border bg-input px-2 py-1 text-muted hover:bg-hover hover:text-surface data-[state=on]:border-accent data-[state=on]:bg-accent data-[state=on]:text-white"+ :data-state="ctx.activeFormatting.value.includes('underline') ? 'on' : 'off'"+ @click="ctx.toggleDecoration('UNDERLINE')"><icon-lucide-underline class="size-3.5" />- </ToggleGroupItem>+ </button></Tip><Tip label="Strikethrough">- <ToggleGroupItem- value="strikethrough"+ <buttonclass="flex cursor-pointer items-center justify-center rounded border border-border bg-input px-2 py-1 text-muted hover:bg-hover hover:text-surface data-[state=on]:border-accent data-[state=on]:bg-accent data-[state=on]:text-white"+ :data-state="ctx.activeFormatting.value.includes('strikethrough') ? 'on' : 'off'"+ @click="ctx.toggleDecoration('STRIKETHROUGH')"><icon-lucide-strikethrough class="size-3.5" />- </ToggleGroupItem>+ </button></Tip>- </ToggleGroupRoot>+ </div></div></div></TypographyControlsRoot>diff --git a/src/components/properties/VariablesSection.vue b/src/components/properties/VariablesSection.vueindex bd0619d44..c9c4c3b43 100644--- a/src/components/properties/VariablesSection.vue+++ b/src/components/properties/VariablesSection.vue@@ -5,7 +5,7 @@ import Tip from '@/components/ui/Tip.vue'import { useSectionUI } from '@/components/ui/section'import { useI18n, useSceneComputed } from '@open-pencil/vue'-import { useEditorStore } from '@/stores/editor'+import { useEditorStore } from '@/app/editor/active-store'const emit = defineEmits<{ openDialog: [] }>()diff --git a/src/components/properties/color-style-row.ts b/src/components/properties/color-style-row.tsnew file mode 100644index 000000000..3bff80482--- /dev/null+++ b/src/components/properties/color-style-row.ts@@ -0,0 +1,28 @@+import { colorToCSS } from '@open-pencil/core/color'++import type { Color, Variable } from '@open-pencil/core/scene-graph'++export type ColorVariableBindingApi = {+ store: {+ resolveColorVariable: (id: string) => unknown+ }+ colorVariables: { value: Variable[] }+ filteredVariables: { value: Variable[] }+ searchTerm: { value: string }+ getBoundVariable: (nodeId: string, index: number) => Variable | undefined+ bindVariable: (nodeId: string, index: number, variableId: string) => void+ unbindVariable: (nodeId: string, index: number) => void+}++export function opacityPercent(opacity: number) {+ return Math.round(opacity * 100)+}++export function opacityFromPercent(percent: number) {+ return Math.max(0, Math.min(1, percent / 100))+}++export function variableSwatchBackground(bindingApi: ColorVariableBindingApi, variableId: string) {+ const color = bindingApi.store.resolveColorVariable(variableId) as Color | null+ return color ? colorToCSS(color) : '#000'+}diff --git a/src/components/properties/fill-label.ts b/src/components/properties/fill-label.tsnew file mode 100644index 000000000..e94f698e0--- /dev/null+++ b/src/components/properties/fill-label.ts@@ -0,0 +1,10 @@+import { colorToHexRaw } from '@open-pencil/core/color'++import type { Fill, Variable } from '@open-pencil/core/scene-graph'++export function fillLabel(fill: Fill, boundVariable?: Variable): string {+ if (boundVariable) return boundVariable.name+ if (fill.type === 'SOLID') return colorToHexRaw(fill.color)+ if (fill.type.startsWith('GRADIENT')) return fill.type.replace('GRADIENT_', '')+ return fill.type+}diff --git a/src/components/properties/fill-okhcl.ts b/src/components/properties/fill-okhcl.tsnew file mode 100644index 000000000..7a46e1944--- /dev/null+++ b/src/components/properties/fill-okhcl.ts@@ -0,0 +1,22 @@+import type { SceneNode } from '@open-pencil/core/scene-graph'+import type { useOkHCL } from '@open-pencil/vue'++type OkhclControls = ReturnType<typeof useOkHCL>+type FillFieldFormat = Parameters<OkhclControls['setFillFieldFormat']>[2]+type OkhclValue = Parameters<OkhclControls['updateFillOkHCL']>[2]++export function createFillOkhclAdapter(+ okhcl: OkhclControls,+ activeNode: SceneNode | null | undefined,+ index: number+) {+ if (!activeNode) return null+ return {+ fieldFormat: okhcl.getFieldFormat(activeNode, index, 'fill'),+ fieldOptions: okhcl.fieldOptions,+ okhcl: okhcl.getFillOkHCLColor(activeNode, index),+ ...okhcl.getFillPreviewInfo(activeNode, index),+ setFieldFormat: (format: FillFieldFormat) => okhcl.setFillFieldFormat(activeNode, index, format),+ updateOkHCL: (value: OkhclValue) => okhcl.updateFillOkHCL(activeNode, index, value)+ }+}diff --git a/src/components/ui/toast.ts b/src/components/ui/toast.tsindex bdf14e10c..f36dc773f 100644--- a/src/components/ui/toast.ts+++ b/src/components/ui/toast.ts@@ -1,7 +1,7 @@import { twMerge } from 'tailwind-merge'import { tv } from 'tailwind-variants'-import type { ToastVariant } from '@/utils/toast'+import type { ToastVariant } from '@/app/shell/ui'const toast = tv({base: 'flex max-w-sm items-start gap-1.5 rounded-md px-2.5 py-1.5 text-xs text-white shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out data-[state=closed]:slide-out-to-top-1 data-[state=open]:animate-in data-[state=open]:fade-in data-[state=open]:slide-in-from-top-1 data-[swipe=cancel]:translate-y-0 data-[swipe=cancel]:transition-transform data-[swipe=move]:translate-y-[var(--reka-toast-swipe-move-y)]',diff --git a/src/composables/use-action-toast.ts b/src/composables/use-action-toast.tsdeleted file mode 100644index 75b3be8fc..000000000--- a/src/composables/use-action-toast.ts+++ /dev/null@@ -1,20 +0,0 @@-import { ACTION_TOAST_DURATION } from '@/constants'-import { useEditorStore } from '@/stores/editor'--let toastTimer: ReturnType<typeof setTimeout> | undefined--export function useActionToast() {- const store = useEditorStore()-- function showActionToast(label: string) {- store.state.actionToast = label- clearTimeout(toastTimer)- toastTimer = setTimeout(() => {- store.state.actionToast = null- }, ACTION_TOAST_DURATION)- }-- return {- showActionToast- }-}diff --git a/src/composables/use-chat.ts b/src/composables/use-chat.tsdeleted file mode 100644index eecb8c403..000000000--- a/src/composables/use-chat.ts+++ /dev/null@@ -1,316 +0,0 @@-import { createAnthropic } from '@ai-sdk/anthropic'-import { createGoogleGenerativeAI } from '@ai-sdk/google'-import { createOpenAI } from '@ai-sdk/openai'-import { Chat } from '@ai-sdk/vue'-import { createOpenRouter } from '@openrouter/ai-sdk-provider'-import { useLocalStorage } from '@vueuse/core'-import { DirectChatTransport, stepCountIs, ToolLoopAgent } from 'ai'-import { computed, ref, watch } from 'vue'--import SYSTEM_PROMPT from '@/ai/system-prompt.md?raw'-import { MAX_AGENT_STEPS, createAITools, recordStepUsage, resetRunSteps } from '@/ai/tools'-import { getActiveEditorStore } from '@/stores/editor'-import {- ACP_AGENTS,- AI_PROVIDERS,- DEFAULT_AI_MODEL,- DEFAULT_AI_PROVIDER,- IS_BROWSER,- IS_TAURI,- setPexelsApiKey,- setUnsplashAccessKey-} from '@open-pencil/core'--import type { ACPAgentID, AIProviderID } from '@open-pencil/core'-import type { LanguageModel, UIMessage } from 'ai'--const STORAGE_PREFIX = 'open-pencil:'-const LEGACY_KEY_STORAGE = `${STORAGE_PREFIX}openrouter-api-key`--function keyStorageKey(id: string) {- return `${STORAGE_PREFIX}ai-key:${id}`-}--function migrateLegacyStorage() {- const legacyKey = localStorage.getItem(LEGACY_KEY_STORAGE)- if (legacyKey) {- localStorage.setItem(keyStorageKey('openrouter'), legacyKey)- localStorage.removeItem(LEGACY_KEY_STORAGE)- if (!localStorage.getItem(`${STORAGE_PREFIX}ai-provider`)) {- localStorage.setItem(`${STORAGE_PREFIX}ai-provider`, 'openrouter')- }- }-}--if (IS_BROWSER) migrateLegacyStorage()--const providerID = useLocalStorage<AIProviderID>(- `${STORAGE_PREFIX}ai-provider`,- DEFAULT_AI_PROVIDER-)-const apiKeyStorageKey = computed(() => keyStorageKey(providerID.value))-const apiKey = useLocalStorage(apiKeyStorageKey, '')-const modelID = useLocalStorage(`${STORAGE_PREFIX}ai-model`, DEFAULT_AI_MODEL)-const customBaseURL = useLocalStorage(`${STORAGE_PREFIX}ai-base-url`, '')-const customModelID = useLocalStorage(`${STORAGE_PREFIX}ai-custom-model`, '')-const customAPIType = useLocalStorage<'completions' | 'responses'>(- `${STORAGE_PREFIX}ai-api-type`,- 'completions'-)-const maxOutputTokens = useLocalStorage(`${STORAGE_PREFIX}ai-max-output-tokens`, 16384)-const pexelsApiKey = useLocalStorage(`${STORAGE_PREFIX}pexels-api-key`, '')-const unsplashAccessKey = useLocalStorage(`${STORAGE_PREFIX}unsplash-access-key`, '')-const activeTab = ref<'design' | 'code' | 'ai'>('design')--const providerDef = computed(- () => AI_PROVIDERS.find((p) => p.id === providerID.value) ?? AI_PROVIDERS[0]-)--const isACPProvider = computed(() => providerID.value.startsWith('acp:'))--const isConfigured = computed(() => {- if (isACPProvider.value) return IS_TAURI- if (!apiKey.value) return false- const needsBaseURL =- providerID.value === 'openai-compatible' || providerID.value === 'anthropic-compatible'- if (needsBaseURL && !customBaseURL.value) return false- return true-})--let transportDirty = false-let currentChatStore: ReturnType<typeof getActiveEditorStore> | null = null-let currentChatMessages = new WeakMap<ReturnType<typeof getActiveEditorStore>, UIMessage[]>()--function markTransportDirty() {- transportDirty = true- currentChatStore = null- currentChatMessages = new WeakMap()-}--watch(- pexelsApiKey,- (key) => {- setPexelsApiKey(key || null)- },- { immediate: true }-)--watch(- unsplashAccessKey,- (key) => {- setUnsplashAccessKey(key || null)- },- { immediate: true }-)--watch(providerID, (id) => {- const def = AI_PROVIDERS.find((p) => p.id === id)- if (def?.defaultModel) {- modelID.value = def.defaultModel- }- markTransportDirty()-})--watch(modelID, markTransportDirty)-watch(customModelID, markTransportDirty)-watch(customAPIType, markTransportDirty)-watch(apiKey, markTransportDirty)-watch(customBaseURL, markTransportDirty)--function setAPIKey(key: string) {- apiKey.value = key-}--function createModel(): LanguageModel {- const key = apiKey.value- const needsCustomModel =- providerID.value === 'openai-compatible' || providerID.value === 'anthropic-compatible'- const effectiveModelID = needsCustomModel ? customModelID.value : modelID.value-- switch (providerID.value) {- case 'openrouter': {- const openrouter = createOpenRouter({- apiKey: key,- headers: {- 'X-OpenRouter-Title': 'OpenPencil',- 'HTTP-Referer': 'https://github.com/open-pencil/open-pencil'- }- })- return openrouter(effectiveModelID)- }- case 'anthropic': {- const anthropic = createAnthropic({ apiKey: key })- return anthropic(effectiveModelID)- }- case 'openai': {- const openai = createOpenAI({ apiKey: key })- return openai(effectiveModelID)- }- case 'google': {- const google = createGoogleGenerativeAI({ apiKey: key })- return google(effectiveModelID)- }- case 'zai': {- const zai = createAnthropic({- apiKey: key,- baseURL: 'https://api.z.ai/api/anthropic'- })- return zai(effectiveModelID)- }- case 'minimax': {- const minimax = createOpenAI({- apiKey: key,- baseURL: 'https://api.minimax.io/v1'- })- return minimax.chat(effectiveModelID)- }- case 'openai-compatible': {- const custom = createOpenAI({- apiKey: key,- baseURL: customBaseURL.value- })- return customAPIType.value === 'responses'- ? custom.responses(effectiveModelID)- : custom.chat(effectiveModelID)- }- case 'anthropic-compatible': {- const custom = createAnthropic({- apiKey: key,- baseURL: customBaseURL.value- })- return custom(effectiveModelID)- }- default: {- if (providerID.value.startsWith('acp:')) {- throw new Error('ACP providers do not use direct API models')- }- throw new Error(`Unknown provider: ${providerID.value}`)- }- }-}--// eslint-disable-next-line @typescript-eslint/no-explicit-any -- test-only mock transports don't implement full generics-let overrideTransport: (() => any) | null = null--let chat: Chat<UIMessage> | null = null--const ANTHROPIC_CACHE_CONTROL = {- anthropic: { cacheControl: { type: 'ephemeral' } }-} as const--function supportsAnthropicCaching(): boolean {- return (- providerID.value === 'anthropic' ||- providerID.value === 'anthropic-compatible' ||- (providerID.value === 'openrouter' && modelID.value.startsWith('anthropic/'))- )-}--let acpTransportInstance: { destroy(): Promise<void> } | null = null--async function createACPTransport() {- const agentId = providerID.value.replace('acp:', '') as ACPAgentID- const agentDef = ACP_AGENTS.find((a) => a.id === agentId)- if (!agentDef) throw new Error(`Unknown ACP agent: ${agentId}`)-- const { ACPChatTransport } = await import('@/ai/acp-transport')- const { homeDir } = await import('@tauri-apps/api/path')- await acpTransportInstance?.destroy()- const transport = new ACPChatTransport({ agentDef, cwd: await homeDir() })- acpTransportInstance = transport- return transport-}--function createTransport(store: ReturnType<typeof getActiveEditorStore>) {- if (overrideTransport) return overrideTransport()-- void acpTransportInstance?.destroy()- acpTransportInstance = null-- const tools = createAITools(store)- const cacheProviderOptions = supportsAnthropicCaching() ? ANTHROPIC_CACHE_CONTROL : undefined-- const agent = new ToolLoopAgent({- model: createModel(),- instructions: SYSTEM_PROMPT,- tools,- stopWhen: stepCountIs(MAX_AGENT_STEPS),- maxOutputTokens: maxOutputTokens.value,- providerOptions: cacheProviderOptions,- prepareCall: (options) => {- resetRunSteps(store)- return {- ...options,- maxOutputTokens: maxOutputTokens.value,- providerOptions: cacheProviderOptions- }- },- onStepFinish: ({ usage }) => {- recordStepUsage(- {- inputTokens: usage.inputTokens ?? 0,- outputTokens: usage.outputTokens ?? 0,- cacheReadTokens: usage.inputTokenDetails.cacheReadTokens ?? 0,- cacheWriteTokens: usage.inputTokenDetails.cacheWriteTokens ?? 0,- timestamp: Date.now()- },- store- )- }- })-- return new DirectChatTransport({ agent })-}--async function ensureChat(): Promise<Chat<UIMessage> | null> {- if (!isConfigured.value) return null-- const store = getActiveEditorStore()- if (currentChatStore && chat) {- currentChatMessages.set(currentChatStore, chat.messages)- }-- if (!chat || transportDirty || currentChatStore !== store) {- const messages = currentChatMessages.get(store)- const transport = isACPProvider.value ? await createACPTransport() : createTransport(store)- chat = new Chat<UIMessage>({ transport, messages })- currentChatStore = store- transportDirty = false- }- return chat-}--function resetChat() {- if (currentChatStore) {- currentChatMessages.delete(currentChatStore)- }- chat = null- currentChatStore = null- transportDirty = false-}--if (IS_BROWSER) {- window.__OPEN_PENCIL_SET_TRANSPORT__ = (factory) => {- overrideTransport = factory- }-}--export function useAIChat() {- return {- providerID,- providerDef,- apiKey,- setAPIKey,- modelID,- customBaseURL,- customModelID,- customAPIType,- maxOutputTokens,- pexelsApiKey,- unsplashAccessKey,- activeTab,- isConfigured,- ensureChat,- resetChat- }-}diff --git a/src/composables/use-collab.ts b/src/composables/use-collab.tsdeleted file mode 100644index 08bd1ea15..000000000--- a/src/composables/use-collab.ts+++ /dev/null@@ -1,556 +0,0 @@-import { useLocalStorage } from '@vueuse/core'-import { joinRoom as joinTrysteroRoom } from 'trystero/mqtt'-import { ref, watch, onUnmounted, computed, type InjectionKey, inject } from 'vue'-import { IndexeddbPersistence } from 'y-indexeddb'-import * as awarenessProtocol from 'y-protocols/awareness'-import * as Y from 'yjs'--import {- TRYSTERO_APP_ID,- PEER_COLORS,- ROOM_ID_LENGTH,- ROOM_ID_CHARS,- YJS_JSON_FIELDS-} from '@/constants'-import { randomIndex } from '@open-pencil/core'--import type { EditorStore } from '@/stores/editor'-import type { Color, SceneNode } from '@open-pencil/core'-import type { Room } from 'trystero'--export interface RemotePeer {- clientId: number- name: string- color: Color- cursor?: { x: number; y: number; pageId: string }- selection?: string[]-}--export interface CollabState {- connected: boolean- roomId: string | null- peers: RemotePeer[]- localName: string- localColor: Color-}--export const DEFAULT_COLLAB_STATE: CollabState = {- connected: false,- roomId: null,- peers: [],- localName: '',- localColor: { r: 0.5, g: 0.5, b: 0.5, a: 1 }-}--export function useCollab(storeOrGetter: EditorStore | (() => EditorStore)) {- const getStore = () =>- typeof storeOrGetter === 'function' ? (storeOrGetter as () => EditorStore)() : storeOrGetter- const storedName = useLocalStorage('op-collab-name', '')- const state = ref<CollabState>({- connected: false,- roomId: null,- peers: [],- localName: storedName.value,- localColor: PEER_COLORS[randomIndex(PEER_COLORS.length)]- })-- let ydoc: Y.Doc | null = null- let awareness: awarenessProtocol.Awareness | null = null- let ynodes: Y.Map<Y.Map<unknown>> | null = null- let yimages: Y.Map<Uint8Array> | null = null- let room: Room | null = null- let persistence: IndexeddbPersistence | null = null- let connectedStore: EditorStore | null = null- let suppressGraphSync = false- let suppressYjsEvents = false- let unbindGraphEvents: (() => void) | null = null- let stopZoomWatch: (() => void) | null = null- let sendYjsUpdate: ((data: Uint8Array, peerId?: string) => void) | null = null- let sendAwareness: ((data: Uint8Array, peerId?: string) => void) | null = null- let sendSyncStep1: ((data: Uint8Array, peerId?: string) => void) | null = null-- const remotePeers = computed(() => state.value.peers)-- function connect(roomId: string) {- if (room) disconnect()-- const store = getStore()- connectedStore = store- state.value.roomId = roomId- ydoc = new Y.Doc()- awareness = new awarenessProtocol.Awareness(ydoc)- ynodes = ydoc.getMap('nodes')- yimages = ydoc.getMap('images')-- persistence = new IndexeddbPersistence(`op-room-${roomId}`, ydoc)-- awareness.on('change', () => {- updatePeersList()- tickFollow()- })-- ynodes.observeDeep((events) => {- if (suppressYjsEvents) return- suppressGraphSync = true- try {- applyYjsToGraph(events)- } finally {- suppressGraphSync = false- }- store.requestRender()- })-- yimages.observe((event) => {- if (suppressYjsEvents) return- for (const [key, change] of event.changes.keys) {- if (change.action === 'add' || change.action === 'update') {- const data = yimages?.get(key)- if (data) store.graph.images.set(key, new Uint8Array(data))- } else {- store.graph.images.delete(key)- }- }- store.requestRender()- })-- room = joinTrysteroRoom(- {- appId: TRYSTERO_APP_ID,- rtcConfig: {- iceServers: [- { urls: 'stun:stun.l.google.com:19302' },- { urls: 'stun:stun.cloudflare.com:3478' },- {- urls: 'turn:openrelay.metered.ca:443',- username: 'openrelayproject',- credential: 'openrelayproject'- },- {- urls: 'turn:openrelay.metered.ca:443?transport=tcp',- username: 'openrelayproject',- credential: 'openrelayproject'- }- ]- }- },- roomId- )-- const [sendUpdate, getUpdate] = room.makeAction<Uint8Array>('yjs-update')- const [sendAw, getAw] = room.makeAction<Uint8Array>('awareness')- const [sendSync, getSync] = room.makeAction<Uint8Array>('sync-step1')- const [sendSyncReply, getSyncReply] = room.makeAction<Uint8Array>('sync-reply')-- sendYjsUpdate = (data, peerId) => void (peerId ? sendUpdate(data, peerId) : sendUpdate(data))- sendAwareness = (data, peerId) => void (peerId ? sendAw(data, peerId) : sendAw(data))- sendSyncStep1 = (data, peerId) => void (peerId ? sendSync(data, peerId) : sendSync(data))-- getUpdate((data) => {- if (!ydoc) return- Y.applyUpdate(ydoc, new Uint8Array(data), 'remote')- })-- getAw((data) => {- if (!awareness) return- awarenessProtocol.applyAwarenessUpdate(awareness, new Uint8Array(data), null)- })-- getSync((data, peerId) => {- if (!ydoc) return- const sv = new Uint8Array(data)- const update = Y.encodeStateAsUpdate(ydoc, sv)- void sendSyncReply(update, peerId)- })-- getSyncReply((data) => {- if (!ydoc) return- Y.applyUpdate(ydoc, new Uint8Array(data), 'remote')- })-- ydoc.on('update', (update: Uint8Array, origin: unknown) => {- if (origin === 'remote') return- sendYjsUpdate?.(update)- })-- const localAwareness = awareness- const localYdoc = ydoc-- localAwareness.on(- 'update',- ({ added, updated, removed }: { added: number[]; updated: number[]; removed: number[] }) => {- const changedClients = [...added, ...updated, ...removed]- const encodedUpdate = awarenessProtocol.encodeAwarenessUpdate(- localAwareness,- changedClients- )- sendAwareness?.(encodedUpdate)- }- )-- room.onPeerJoin((peerId) => {- state.value.connected = true- const sv = Y.encodeStateVector(localYdoc)- sendSyncStep1?.(sv, peerId)-- const encodedUpdate = awarenessProtocol.encodeAwarenessUpdate(localAwareness, [- localAwareness.clientID- ])- sendAwareness?.(encodedUpdate, peerId)- })-- room.onPeerLeave(() => {- const remoteClients = [...localAwareness.getStates().keys()].filter(- (id) => id !== localAwareness.clientID- )- awarenessProtocol.removeAwarenessStates(localAwareness, remoteClients, 'peer-left')- updatePeersList()- })-- state.value.connected = true- broadcastAwareness()-- stopZoomWatch = watch(- () => store.state.zoom,- (zoom) => {- if (!awareness) return- const prev = awareness.getLocalState()?.cursor as- | { x: number; y: number; pageId: string; zoom: number }- | undefined- if (prev) {- awareness.setLocalStateField('cursor', { ...prev, zoom })- }- }- )-- function onGraphMutation(nodeId: string) {- if (!suppressGraphSync && ydoc && ynodes) {- syncNodeToYjs(nodeId)- }- }-- const unbindUpdated = store.graph.emitter.on('node:updated', (id) => onGraphMutation(id))- const unbindCreated = store.graph.emitter.on('node:created', (node) => onGraphMutation(node.id))- const unbindReparented = store.graph.emitter.on('node:reparented', (nodeId) =>- onGraphMutation(nodeId)- )- const unbindReordered = store.graph.emitter.on('node:reordered', (nodeId) =>- onGraphMutation(nodeId)- )- const unbindDeleted = store.graph.emitter.on('node:deleted', (id) => {- if (!suppressGraphSync && ydoc && ynodes) {- suppressYjsEvents = true- const map = ynodes- ydoc.transact(() => {- map.delete(id)- })- suppressYjsEvents = false- }- })-- unbindGraphEvents = () => {- unbindUpdated()- unbindCreated()- unbindReparented()- unbindReordered()- unbindDeleted()- }- }-- function disconnect() {- const store = connectedStore ?? getStore()- unbindGraphEvents?.()- unbindGraphEvents = null- stopZoomWatch?.()- stopZoomWatch = null- void room?.leave()- room = null- sendYjsUpdate = null- sendAwareness = null- sendSyncStep1 = null-- if (awareness) {- awareness.destroy()- awareness = null- }- if (persistence) {- void persistence.destroy()- persistence = null- }- if (ydoc) {- ydoc.destroy()- ydoc = null- }- ynodes = null- yimages = null- state.value.connected = false- state.value.roomId = null- state.value.peers = []- followingPeer.value = null- store.state.remoteCursors = []- store.requestRender()- connectedStore = null- }-- function syncNodeToYjs(nodeId: string) {- const store = connectedStore ?? getStore()- if (!ydoc || !ynodes) return- const node = store.graph.getNode(nodeId)- if (!node) return-- const localYnodes = ynodes- const localYimages = yimages- suppressYjsEvents = true- ydoc.transact(() => {- let ynode = localYnodes.get(nodeId)- if (!ynode) {- ynode = new Y.Map()- localYnodes.set(nodeId, ynode)- }- syncNodePropsToYMap(node, ynode)-- if (localYimages) {- for (const fill of node.fills) {- if (fill.imageHash && !localYimages.has(fill.imageHash)) {- const data = store.graph.images.get(fill.imageHash)- if (data) localYimages.set(fill.imageHash, data)- }- }- }- })- suppressYjsEvents = false- }-- function syncNodePropsToYMap(node: SceneNode, ynode: Y.Map<unknown>) {- for (const [key, value] of Object.entries(node)) {- if (typeof value === 'object' && value !== null) {- ynode.set(key, JSON.stringify(value))- } else {- ynode.set(key, value)- }- }- }-- function syncAllNodesToYjs() {- const store = connectedStore ?? getStore()- if (!ydoc || !ynodes) return- const localYnodes = ynodes- const localYimages = yimages- suppressYjsEvents = true- ydoc.transact(() => {- for (const node of store.graph.getAllNodes()) {- let ynode = localYnodes.get(node.id)- if (!ynode) {- ynode = new Y.Map()- localYnodes.set(node.id, ynode)- }- syncNodePropsToYMap(node, ynode)- }- })- if (localYimages) {- ydoc.transact(() => {- for (const [hash, data] of store.graph.images) {- if (!localYimages.has(hash)) {- localYimages.set(hash, data)- }- }- })- }- suppressYjsEvents = false- }-- function applyYjsToGraph(events: Y.YEvent<Y.Map<unknown>>[]) {- const store = connectedStore ?? getStore()- if (!ynodes) return- const localYnodes = ynodes- for (const event of events) {- if (event.target === localYnodes) {- for (const [key, change] of event.changes.keys) {- if (change.action === 'add') {- const ynode = localYnodes.get(key)- if (ynode) applyYnodeToGraph(key, ynode)- } else if (change.action === 'delete') {- store.graph.deleteNode(key)- }- }- } else if (event.target.parent === localYnodes) {- const nodeId = findNodeIdForYMap(event.target)- if (nodeId) {- const ynode = localYnodes.get(nodeId)- if (ynode) applyYnodeToGraph(nodeId, ynode)- }- }- }- }-- function findNodeIdForYMap(ymap: Y.Map<unknown>): string | null {- if (!ynodes) return null- for (const [key, value] of ynodes.entries()) {- if (value === ymap) return key- }- return null- }-- function applyYnodeToGraph(nodeId: string, ynode: Y.Map<unknown>) {- const store = connectedStore ?? getStore()- const existing = store.graph.getNode(nodeId)- const props: Record<string, unknown> = {}-- for (const [key, value] of ynode.entries()) {- if (YJS_JSON_FIELDS.has(key)) {- try {- props[key] = typeof value === 'string' ? JSON.parse(value) : value- } catch {- props[key] = value- }- } else {- props[key] = value- }- }-- if (existing) {- store.graph.updateNode(nodeId, props as Partial<SceneNode>)- } else {- const parentId = props.parentId as string- if (parentId && store.graph.getNode(parentId)) {- const type = props.type as SceneNode['type']- const node = store.graph.createNode(type, parentId, props as Partial<SceneNode>)- store.graph.nodes.delete(node.id)- node.id = nodeId- store.graph.nodes.set(nodeId, node)- }- }- }-- function broadcastAwareness() {- if (!awareness) return- awareness.setLocalStateField('user', {- name: state.value.localName,- color: state.value.localColor- })- }-- function updateCursor(x: number, y: number, pageId: string) {- const store = connectedStore ?? getStore()- if (!awareness) return- awareness.setLocalStateField('cursor', { x, y, pageId, zoom: store.state.zoom })- }-- function updateSelection(ids: string[]) {- if (!awareness) return- awareness.setLocalStateField('selection', ids)- }-- function updatePeersList() {- const store = connectedStore ?? getStore()- if (!awareness) return- const states = awareness.getStates()- const peers: RemotePeer[] = []- const localClientId = awareness.clientID- const currentPageId = store.state.currentPageId-- states.forEach((peerState, clientId) => {- if (clientId === localClientId) return- const user = peerState.user as { name?: string; color?: Color } | undefined- if (!user) return- peers.push({- clientId,- name: user.name || 'Anonymous',- color: user.color || PEER_COLORS[clientId % PEER_COLORS.length],- cursor: peerState.cursor as RemotePeer['cursor'],- selection: peerState.selection as string[]- })- })-- state.value.peers = peers- store.state.remoteCursors = peers- .filter((p) => p.cursor && p.cursor.pageId === currentPageId)- .map((p) => {- const cursor = p.cursor as NonNullable<RemotePeer['cursor']>- return {- name: p.name,- color: p.color,- x: cursor.x,- y: cursor.y,- selection: p.selection- }- })- store.requestRender()- }-- function setLocalName(name: string) {- state.value.localName = name- storedName.value = name- broadcastAwareness()- }-- function generateRoomId(): string {- let result = ''- for (let i = 0; i < ROOM_ID_LENGTH; i++) {- result += ROOM_ID_CHARS[randomIndex(ROOM_ID_CHARS.length)]- }- return result- }-- function shareCurrentDoc(): string {- const roomId = generateRoomId()- connect(roomId)- syncAllNodesToYjs()- return roomId- }-- function joinRoom(roomId: string) {- connect(roomId)- }-- const followingPeer = ref<number | null>(null)-- function followPeer(clientId: number | null) {- followingPeer.value = clientId- }-- function tickFollow() {- const store = connectedStore ?? getStore()- if (!followingPeer.value || !awareness) return- const peerState = awareness.getStates().get(followingPeer.value)- if (!peerState?.cursor) {- followingPeer.value = null- return- }- const cursor = peerState.cursor as { x: number; y: number; pageId: string; zoom?: number }- if (cursor.pageId !== store.state.currentPageId) {- void store.switchPage(cursor.pageId)- }- const canvas = document.querySelector('canvas')- if (!canvas) return- if (cursor.zoom) store.state.zoom = cursor.zoom- const cw = canvas.width / devicePixelRatio- const ch = canvas.height / devicePixelRatio- store.state.panX = cw / 2 - cursor.x * store.state.zoom- store.state.panY = ch / 2 - cursor.y * store.state.zoom- store.requestRender()- }-- onUnmounted(() => {- disconnect()- })-- return {- state,- remotePeers,- followingPeer,- connect: joinRoom,- disconnect,- shareCurrentDoc,- updateCursor,- updateSelection,- setLocalName,- followPeer,- tickFollow- }-}--export type CollabReturn = ReturnType<typeof useCollab>-export const COLLAB_KEY = Symbol('collab') as InjectionKey<CollabReturn>-export function useCollabInjected() {- return inject(COLLAB_KEY)-}diff --git a/src/composables/use-keyboard.ts b/src/composables/use-keyboard.tsdeleted file mode 100644index f35d6efb2..000000000--- a/src/composables/use-keyboard.ts+++ /dev/null@@ -1,333 +0,0 @@-import { useActiveElement, useEventListener, useMagicKeys, whenever } from '@vueuse/core'-import { computed, watch } from 'vue'--import { useAIChat } from '@/composables/use-chat'-import { TOOL_SHORTCUTS, useEditorStore } from '@/stores/editor'-import { closeTab, createTab, activeTab as activeTabRef } from '@/stores/tabs'-import {- extractImageFilesFromClipboard,- useEditorCommands,- useViewportKind-} from '@open-pencil/vue'--import { openFileDialog } from './use-menu'--import type { ComputedRef } from 'vue'--function isEditing(e: Event) {- return e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement-}--function isInputElement(el: EventTarget | null | undefined): boolean {- return el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement-}--const NUDGE_DELTAS: Partial<Record<string, [number, number]>> = {- ArrowUp: [0, -1],- ArrowDown: [0, 1],- ArrowLeft: [-1, 0],- ArrowRight: [1, 0]-}--const RESERVED_MOD_CODES = new Set([- 'Backslash',- 'BracketLeft',- 'BracketRight',- 'Digit0',- 'Digit1',- 'Digit2',- 'KeyA',- 'KeyB',- 'KeyD',- 'KeyE',- 'KeyG',- 'KeyH',- 'KeyJ',- 'KeyK',- 'KeyL',- 'KeyN',- 'KeyO',- 'KeyS',- 'KeyT',- 'KeyW',- 'KeyY',- 'KeyZ'-])--function isReservedModShortcut(e: KeyboardEvent): boolean {- if (!(e.metaKey || e.ctrlKey)) return false- if (e.altKey) return e.code === 'KeyB' || e.code === 'KeyK'- return RESERVED_MOD_CODES.has(e.code)-}--export function useKeyboard() {- const { activeTab } = useAIChat()- const store = useEditorStore()- const { isMobile } = useViewportKind()- const { runCommand } = useEditorCommands()- const activeElement = useActiveElement()- const inputFocused = computed(() => isInputElement(activeElement.value))-- // ─── App-level actions ─────────────────────────────────────-- function hasNodeEditSelection() {- return (- store.state.nodeEditState &&- (store.state.nodeEditState.selectedVertexIndices.size > 0 ||- store.state.nodeEditState.selectedHandles.size > 0)- )- }-- function smartDelete(altKey: boolean) {- if (hasNodeEditSelection()) {- if (altKey) store.nodeEditBreakAtVertex()- else store.nodeEditDeleteSelected()- return- }- runCommand('selection.delete')- }-- function confirmOrEnterText() {- if (store.state.nodeEditState) {- store.exitNodeEditMode(true)- return- }- if (store.state.penState) {- store.penCommit(false)- return- }- const node = store.selectedNode.value- if (node?.type === 'TEXT') {- requestAnimationFrame(() => {- store.startTextEditing(node.id)- store.textEditor?.selectAll()- store.requestRender()- })- }- }-- function escapeOrDeselect() {- if (store.state.nodeEditState) {- store.exitNodeEditMode(true)- return- }- if (store.state.penState) {- store.penCommit(false)- return- }- if (store.state.enteredContainerId) {- store.exitContainer()- return- }- store.clearSelection()- store.setTool('SELECT')- }-- function toggleAutoLayout() {- const node = store.selectedNode.value- if (node?.type === 'FRAME' && store.selectedNodes.value.length === 1) {- store.setLayoutMode(node.id, node.layoutMode === 'NONE' ? 'VERTICAL' : 'NONE')- } else if (store.selectedNodes.value.length > 0) {- runCommand('selection.wrapInAutoLayout')- }- }-- function toggleUI() {- store.state.showUI = !store.state.showUI- }-- function toggleAI() {- if (isMobile.value) {- store.state.activeRibbonTab = store.state.activeRibbonTab === 'ai' ? 'panels' : 'ai'- if (store.state.mobileDrawerSnap === 'closed') {- store.state.mobileDrawerSnap = 'half'- }- } else {- activeTab.value = activeTab.value === 'ai' ? 'design' : 'ai'- }- }-- function exportSelectionPng() {- if (store.state.selectedIds.size > 0) void store.exportSelection(1, 'png')- }-- // ─── Clipboard ──────────────────────────────────────────────-- useEventListener(window, 'copy', (e: ClipboardEvent) => {- if (isEditing(e)) return- e.preventDefault()- if (e.clipboardData) void store.writeCopyData(e.clipboardData)- })-- useEventListener(window, 'cut', (e: ClipboardEvent) => {- if (isEditing(e)) return- e.preventDefault()- if (e.clipboardData) void store.writeCopyData(e.clipboardData)- store.deleteSelected()- })-- useEventListener(window, 'paste', (e: ClipboardEvent) => {- if (isEditing(e)) return- e.preventDefault()-- const { cursorCanvasX: ccx, cursorCanvasY: ccy } = store.state- const cursorPos = ccx != null && ccy != null ? { x: ccx, y: ccy } : undefined-- const imageFiles = extractImageFilesFromClipboard(e)- if (imageFiles.length) {- const cx = cursorPos?.x ?? (-store.state.panX + window.innerWidth / 2) / store.state.zoom- const cy = cursorPos?.y ?? (-store.state.panY + window.innerHeight / 2) / store.state.zoom- void store.placeImageFiles(imageFiles, cx, cy)- return- }-- const html = e.clipboardData?.getData('text/html') ?? ''- if (html) store.pasteFromHTML(html, cursorPos)- })-- // ─── Raw keydown handlers ─────────────────────────────────-- useEventListener(window, 'keydown', (e: KeyboardEvent) => {- if (isEditing(e) || store.state.editingTextId) return- if (isReservedModShortcut(e)) e.preventDefault()- if (e.metaKey || e.ctrlKey || e.altKey) return- const delta = NUDGE_DELTAS[e.code]- if (delta && store.state.selectedIds.size > 0) {- const step = e.shiftKey ? 10 : 1- store.nudgeSelected(delta[0] * step, delta[1] * step)- e.preventDefault()- }- })-- // ─── useMagicKeys ──────────────────────────────────────────-- const keys = useMagicKeys({- passive: false,- onEventFired(e) {- if (e.type !== 'keydown') return- if (isEditing(e) || store.state.editingTextId) return- if (isReservedModShortcut(e)) e.preventDefault()- if (e.code === 'Backspace' || e.code === 'Delete') e.preventDefault()- if (e.code === 'BracketLeft' || e.code === 'BracketRight') e.preventDefault()- if (e.code === 'Enter' && store.state.penState) e.preventDefault()- if (e.code === 'Space') e.preventDefault()- }- })-- // ─── Helpers ───────────────────────────────────────────────-- function mod(combo: string): ComputedRef<boolean> {- const hasShift = combo.includes('shift')- const hasAlt = combo.includes('alt')- const base = computed(() => keys[`meta+${combo}`].value || keys[`control+${combo}`].value)- if (hasShift && hasAlt) return base- if (hasShift) return computed(() => base.value && !keys['alt'].value)- if (hasAlt) return computed(() => base.value && !keys['shift'].value)- return computed(() => base.value && !keys['shift'].value && !keys['alt'].value)- }-- function shift(key: string): ComputedRef<boolean> {- return computed(- () =>- !inputFocused.value &&- keys[`shift+${key}`].value &&- !keys['meta'].value &&- !keys['control'].value- )- }-- function plain(key: string, options?: { allowAlt?: boolean }): ComputedRef<boolean> {- const allowAlt = options?.allowAlt ?? false- return computed(- () =>- !inputFocused.value &&- keys[key].value &&- !keys['meta'].value &&- !keys['control'].value &&- !keys['shift'].value &&- (allowAlt || !keys['alt'].value) &&- !store.state.editingTextId &&- !store.state.scrubInputFocused- )- }-- // ─── Space hold → temporary Hand tool ──────────────────────-- let toolBeforeSpace: typeof store.state.activeTool | null = null-- const spaceHeld = computed(- () =>- !inputFocused.value &&- keys['Space'].value &&- !keys['meta'].value &&- !keys['control'].value &&- !keys['alt'].value- )-- watch(spaceHeld, (held) => {- if (held && toolBeforeSpace === null && store.state.activeTool !== 'HAND') {- toolBeforeSpace = store.state.activeTool- store.setTool('HAND')- } else if (!held && toolBeforeSpace !== null) {- store.setTool(toolBeforeSpace)- toolBeforeSpace = null- }- })-- // ─── Tool shortcuts (plain single keys) ────────────────────-- for (const [code, tool] of Object.entries(TOOL_SHORTCUTS)) {- if (!tool) continue- whenever(plain(code), () => {- toolBeforeSpace = null- store.setTool(tool)- })- }-- // ─── Shortcut → action mapping ─────────────────────────────-- // Mod + Alt- whenever(mod('alt+keyk'), () => runCommand('selection.createComponent'))- whenever(mod('alt+keyb'), () => runCommand('selection.detachInstance'))-- // Mod + Shift- whenever(mod('shift+keyk'), () => runCommand('selection.createComponentSet'))- whenever(mod('shift+keyh'), () => runCommand('selection.toggleVisibility'))- whenever(mod('shift+keyl'), () => runCommand('selection.toggleLock'))- whenever(mod('shift+keye'), exportSelectionPng)- whenever(mod('shift+keys'), () => store.saveFigFileAs())- whenever(mod('shift+keyg'), () => runCommand('selection.ungroup'))- whenever(mod('shift+keyz'), () => runCommand('edit.redo'))-- // Mod- whenever(mod('backslash'), toggleUI)- whenever(mod('keyj'), toggleAI)- whenever(mod('keyw'), () => {- if (activeTabRef.value) closeTab(activeTabRef.value.id)- })- whenever(mod('keyn'), () => createTab())- whenever(mod('keyt'), () => createTab())- whenever(mod('keyz'), () => runCommand('edit.undo'))- whenever(mod('keyy'), () => runCommand('edit.redo'))- whenever(mod('digit0'), () => runCommand('view.zoom100'))- whenever(mod('digit1'), () => runCommand('view.zoomFit'))- whenever(mod('digit2'), () => runCommand('view.zoomSelection'))- whenever(mod('keyd'), () => runCommand('selection.duplicate'))- whenever(mod('keya'), () => runCommand('selection.selectAll'))- whenever(mod('keys'), () => store.saveFigFile())- whenever(mod('keyo'), () => openFileDialog())- whenever(mod('keyg'), () => runCommand('selection.group'))-- // Shift (no mod)- whenever(shift('digit1'), () => runCommand('view.zoomFit'))- whenever(shift('digit2'), () => runCommand('view.zoomSelection'))- whenever(shift('keya'), toggleAutoLayout)-- // Plain keys- whenever(plain('BracketRight'), () => runCommand('selection.bringToFront'))- whenever(plain('BracketLeft'), () => runCommand('selection.sendToBack'))- whenever(plain('Backspace'), () => smartDelete(false))- whenever(plain('Delete', { allowAlt: true }), () => smartDelete(keys['alt'].value))- whenever(plain('Enter'), confirmOrEnterText)- whenever(plain('Escape'), escapeOrDeselect)-}diff --git a/src/constants.ts b/src/constants.tsindex 4d7aecb29..d33e37c56 100644--- a/src/constants.ts+++ b/src/constants.ts@@ -1,3 +1,5 @@+import ACP_DESIGN_CONTEXT from '@/app/ai/acp/design-context.md'+export {IS_BROWSER,IS_TAURI,@@ -55,9 +57,9 @@ export {COMPONENT_LABEL_ICON_GAP,RULER_TARGET_PIXEL_SPACING,RULER_MAJOR_TOLERANCE-} from '@open-pencil/core'+} from '@open-pencil/core/constants'-import type { Color } from '@open-pencil/core'+import type { Color } from '@open-pencil/core/types'export const TRYSTERO_APP_ID = 'openpencil'export const ROOM_ID_LENGTH = 8@@ -92,7 +94,7 @@ export {ZOOM_DIVISOR,ZOOM_SCALE_MIN,ZOOM_SCALE_MAX-} from '@open-pencil/core'+} from '@open-pencil/core/constants'export const HANDLE_SIZE = 6@@ -116,9 +118,4 @@ export const HANDLE_HIT_RADIUS = 6export const ACP_PERMISSION_TIMEOUT_MS = 60_000-export const ACP_DESIGN_CONTEXT = `You are inside OpenPencil, an open-source design editor (like Figma). \-Use the open-pencil MCP tools to create and modify designs on the live canvas. \-Key tools: render (JSX to design), create_shape, set_fill, set_layout, find_nodes, get_page_tree, export_image. \-The render tool accepts JSX with components: Frame, Text, Rectangle, Ellipse, Icon, Group, Section. \-Props: w, h, bg, flex, gap, p, rounded, color, size, weight, items, justify, stroke, opacity, shadow. \-Do NOT write HTML files or use terminal commands — draw directly on the canvas using the MCP tools.`+export { ACP_DESIGN_CONTEXT }diff --git a/src/demo.ts b/src/demo.tsdeleted file mode 100644index 78364edf1..000000000--- a/src/demo.ts+++ /dev/null@@ -1,980 +0,0 @@-import { computeAllLayouts } from '@open-pencil/core'--import type { EditorStore } from './stores/editor'-import type { Color, Effect, Fill, GradientStop } from '@open-pencil/core'--const WHITE: Color = { r: 1, g: 1, b: 1, a: 1 }-const BLACK: Color = { r: 0, g: 0, b: 0, a: 1 }-const GRAY_50: Color = { r: 0.98, g: 0.98, b: 0.98, a: 1 }-const GRAY_100: Color = { r: 0.96, g: 0.96, b: 0.97, a: 1 }-const GRAY_200: Color = { r: 0.9, g: 0.9, b: 0.92, a: 1 }-const GRAY_500: Color = { r: 0.55, g: 0.55, b: 0.58, a: 1 }-const BLUE: Color = { r: 0.23, g: 0.51, b: 0.96, a: 1 }-const INDIGO: Color = { r: 0.38, g: 0.35, b: 0.95, a: 1 }-const PURPLE: Color = { r: 0.59, g: 0.28, b: 0.96, a: 1 }-const GREEN: Color = { r: 0.13, g: 0.77, b: 0.42, a: 1 }-const ORANGE: Color = { r: 0.96, g: 0.52, b: 0.13, a: 1 }-const RED: Color = { r: 0.91, g: 0.22, b: 0.22, a: 1 }-const TEAL: Color = { r: 0.08, g: 0.73, b: 0.73, a: 1 }--function solid(color: Color, opacity = 1): Fill {- return { type: 'SOLID', color, opacity, visible: true }-}--function gradient(stops: GradientStop[]): Fill {- return {- type: 'GRADIENT_LINEAR',- color: stops[0].color,- opacity: 1,- visible: true,- gradientStops: stops,- gradientTransform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }- }-}--function thinStroke(color: Color) {- return [{ color, weight: 1, opacity: 1, visible: true, align: 'INSIDE' as const }]-}--function makeComponent(store: EditorStore, ids: string[]): string {- store.select(ids)- store.createComponentFromSelection()- return [...store.state.selectedIds][0]-}--export function createDemoShapes(store: EditorStore) {- const { graph } = store-- // ─── Section: Components ──────────────────────────────────────- const compSectionId = store.createShape('SECTION', 60, 60, 920, 540)- graph.updateNode(compSectionId, { name: 'Components' })-- // Button component- const btnId = store.createShape('FRAME', 32, 48, 120, 40, compSectionId)- graph.updateNode(btnId, {- name: 'Button/Primary',- cornerRadius: 8,- fills: [solid(BLUE)],- layoutMode: 'HORIZONTAL',- primaryAxisSizing: 'HUG',- counterAxisSizing: 'HUG',- primaryAxisAlign: 'CENTER',- counterAxisAlign: 'CENTER',- paddingTop: 10,- paddingBottom: 10,- paddingLeft: 20,- paddingRight: 20- })- const btnTextId = store.createShape('TEXT', 0, 0, 80, 20, btnId)- graph.updateNode(btnTextId, {- name: 'Label',- text: 'Get Started',- fontSize: 14,- fontWeight: 600,- fills: [solid(WHITE)]- })- const btnCompId = makeComponent(store, [btnId])-- // Secondary button- const btn2Id = store.createShape('FRAME', 176, 48, 100, 40, compSectionId)- graph.updateNode(btn2Id, {- name: 'Button/Secondary',- cornerRadius: 8,- fills: [solid(WHITE)],- strokes: thinStroke(GRAY_200),- layoutMode: 'HORIZONTAL',- primaryAxisSizing: 'HUG',- counterAxisSizing: 'HUG',- primaryAxisAlign: 'CENTER',- counterAxisAlign: 'CENTER',- paddingTop: 10,- paddingBottom: 10,- paddingLeft: 20,- paddingRight: 20- })- const btn2TextId = store.createShape('TEXT', 0, 0, 60, 20, btn2Id)- graph.updateNode(btn2TextId, {- name: 'Label',- text: 'Cancel',- fontSize: 14,- fontWeight: 500,- fills: [solid(BLACK)]- })- makeComponent(store, [btn2Id])-- // Chip / Tag component- const chipId = store.createShape('FRAME', 304, 52, 80, 28, compSectionId)- graph.updateNode(chipId, {- name: 'Tag',- cornerRadius: 14,- fills: [solid({ r: 0.93, g: 0.94, b: 1, a: 1 })],- layoutMode: 'HORIZONTAL',- primaryAxisSizing: 'HUG',- counterAxisSizing: 'HUG',- primaryAxisAlign: 'CENTER',- counterAxisAlign: 'CENTER',- paddingTop: 4,- paddingBottom: 4,- paddingLeft: 12,- paddingRight: 12- })- const chipTextId = store.createShape('TEXT', 0, 0, 56, 16, chipId)- graph.updateNode(chipTextId, {- name: 'Label',- text: 'Design',- fontSize: 12,- fontWeight: 500,- fills: [solid(INDIGO)]- })- makeComponent(store, [chipId])-- // Avatar component- const avatarId = store.createShape('ELLIPSE', 416, 48, 40, 40, compSectionId)- graph.updateNode(avatarId, {- name: 'Avatar',- fills: [- gradient([- { color: PURPLE, position: 0 },- { color: BLUE, position: 1 }- ])- ]- })- makeComponent(store, [avatarId])-- // Card component (auto layout)- const cardId = store.createShape('FRAME', 32, 128, 280, 160, compSectionId)- graph.updateNode(cardId, {- name: 'Card',- cornerRadius: 12,- fills: [solid(WHITE)],- strokes: thinStroke(GRAY_200),- layoutMode: 'VERTICAL',- primaryAxisSizing: 'FIXED',- counterAxisSizing: 'FIXED',- itemSpacing: 8,- paddingTop: 20,- paddingBottom: 20,- paddingLeft: 20,- paddingRight: 20- })- const cardTitleId = store.createShape('TEXT', 0, 0, 240, 22, cardId)- graph.updateNode(cardTitleId, {- name: 'Title',- text: 'Analytics Overview',- fontSize: 16,- fontWeight: 600,- fills: [solid(BLACK)]- })- const cardDescId = store.createShape('TEXT', 0, 0, 240, 36, cardId)- graph.updateNode(cardDescId, {- name: 'Description',- text: 'Track your key metrics and performance indicators in real time.',- fontSize: 13,- fontWeight: 400,- fills: [solid(GRAY_500)]- })- const cardBarBg = store.createShape('RECTANGLE', 0, 0, 240, 8, cardId)- graph.updateNode(cardBarBg, {- name: 'Progress BG',- cornerRadius: 4,- fills: [solid(GRAY_100)]- })- const cardBar = store.createShape('RECTANGLE', 0, 0, 168, 8, cardId)- graph.updateNode(cardBar, {- name: 'Progress',- cornerRadius: 4,- fills: [- gradient([- { color: BLUE, position: 0 },- { color: TEAL, position: 1 }- ])- ]- })- makeComponent(store, [cardId])-- // Input component- const inputId = store.createShape('FRAME', 344, 128, 240, 40, compSectionId)- graph.updateNode(inputId, {- name: 'Input',- cornerRadius: 8,- fills: [solid(WHITE)],- strokes: thinStroke(GRAY_200),- layoutMode: 'HORIZONTAL',- primaryAxisSizing: 'FIXED',- counterAxisSizing: 'HUG',- primaryAxisAlign: 'MIN',- counterAxisAlign: 'CENTER',- paddingTop: 10,- paddingBottom: 10,- paddingLeft: 12,- paddingRight: 12- })- const inputPlaceholder = store.createShape('TEXT', 0, 0, 200, 18, inputId)- graph.updateNode(inputPlaceholder, {- name: 'Placeholder',- text: 'Search...',- fontSize: 14,- fontWeight: 400,- fills: [solid(GRAY_500)]- })- makeComponent(store, [inputId])-- // Badge component- const badgeId = store.createShape('FRAME', 344, 196, 48, 24, compSectionId)- graph.updateNode(badgeId, {- name: 'Badge',- cornerRadius: 12,- fills: [solid({ r: 0.93, g: 1, b: 0.95, a: 1 })],- layoutMode: 'HORIZONTAL',- primaryAxisSizing: 'HUG',- counterAxisSizing: 'HUG',- primaryAxisAlign: 'CENTER',- counterAxisAlign: 'CENTER',- paddingTop: 4,- paddingBottom: 4,- paddingLeft: 8,- paddingRight: 8- })- const badgeDot = store.createShape('ELLIPSE', 0, 0, 6, 6, badgeId)- graph.updateNode(badgeDot, {- name: 'Dot',- fills: [solid(GREEN)]- })- const badgeText = store.createShape('TEXT', 0, 0, 28, 14, badgeId)- graph.updateNode(badgeText, {- name: 'Label',- text: 'Live',- fontSize: 11,- fontWeight: 600,- fills: [solid(GREEN)]- })- const badgeCompId = makeComponent(store, [badgeId])-- // Color swatches row- const swatches = [- { name: 'Blue', color: BLUE, x: 32 },- { name: 'Indigo', color: INDIGO, x: 88 },- { name: 'Purple', color: PURPLE, x: 144 },- { name: 'Green', color: GREEN, x: 200 },- { name: 'Teal', color: TEAL, x: 256 },- { name: 'Orange', color: ORANGE, x: 312 },- { name: 'Red', color: RED, x: 368 }- ]- for (const s of swatches) {- const id = store.createShape('ELLIPSE', s.x, 460, 44, 44, compSectionId)- graph.updateNode(id, { name: s.name, fills: [solid(s.color)] })- }-- // ─── Section: App Preview ─────────────────────────────────────- const appSectionId = store.createShape('SECTION', 1040, 60, 560, 540)- graph.updateNode(appSectionId, { name: 'App Preview' })-- // Desktop frame- const frameId = store.createShape('FRAME', 20, 48, 520, 460, appSectionId)- graph.updateNode(frameId, {- name: 'Dashboard',- fills: [solid(GRAY_50)],- strokes: thinStroke(GRAY_200),- clipsContent: true- })-- // Sidebar- const sidebarId = store.createShape('RECTANGLE', 0, 0, 56, 460, frameId)- graph.updateNode(sidebarId, {- name: 'Sidebar',- fills: [solid(WHITE)],- strokes: thinStroke(GRAY_200)- })-- // Sidebar dots- for (let i = 0; i < 5; i++) {- const dotId = store.createShape('ELLIPSE', 18, 20 + i * 40, 20, 20, frameId)- graph.updateNode(dotId, {- name: `Nav ${i + 1}`,- fills: [solid(i === 0 ? BLUE : GRAY_200)]- })- }-- // Header bar- const headerId = store.createShape('RECTANGLE', 56, 0, 464, 52, frameId)- graph.updateNode(headerId, {- name: 'Header',- fills: [solid(WHITE)],- strokes: thinStroke(GRAY_200)- })- const headerTitle = store.createShape('TEXT', 76, 16, 120, 20, frameId)- graph.updateNode(headerTitle, {- name: 'Page Title',- text: 'Dashboard',- fontSize: 16,- fontWeight: 600,- fills: [solid(BLACK)]- })-- // Button instance in the header- const headerBtn = graph.createInstance(btnCompId, frameId, { x: 400, y: 8 })- if (headerBtn) graph.updateNode(headerBtn.id, { x: 400, y: 8 })-- // Badge instance next to title- const headerBadge = graph.createInstance(badgeCompId, frameId, { x: 200, y: 18 })- if (headerBadge) graph.updateNode(headerBadge.id, { x: 200, y: 18 })-- // Stat cards row (instances from Card component, simulated as frames)- const stats = [- { title: 'Revenue', value: '$12,480', badge: '+14%', color: GREEN },- { title: 'Users', value: '3,842', badge: '+8%', color: BLUE },- { title: 'Orders', value: '1,249', badge: '-3%', color: RED }- ]-- for (let i = 0; i < stats.length; i++) {- const s = stats[i]- const cx = 76 + i * 152- const cId = store.createShape('FRAME', cx, 72, 140, 88, frameId)- graph.updateNode(cId, {- name: s.title,- cornerRadius: 10,- fills: [solid(WHITE)],- strokes: thinStroke(GRAY_200),- layoutMode: 'VERTICAL',- primaryAxisSizing: 'FIXED',- counterAxisSizing: 'FIXED',- itemSpacing: 4,- paddingTop: 14,- paddingBottom: 14,- paddingLeft: 16,- paddingRight: 16- })- const labelId = store.createShape('TEXT', 0, 0, 108, 14, cId)- graph.updateNode(labelId, {- name: 'Label',- text: s.title,- fontSize: 11,- fontWeight: 500,- fills: [solid(GRAY_500)]- })- const valId = store.createShape('TEXT', 0, 0, 108, 24, cId)- graph.updateNode(valId, {- name: 'Value',- text: s.value,- fontSize: 22,- fontWeight: 700,- fills: [solid(BLACK)]- })- const bId = store.createShape('TEXT', 0, 0, 108, 14, cId)- graph.updateNode(bId, {- name: 'Badge',- text: s.badge,- fontSize: 11,- fontWeight: 600,- fills: [solid(s.color)]- })- }-- // Chart area- const chartBg = store.createShape('FRAME', 76, 180, 424, 200, frameId)- graph.updateNode(chartBg, {- name: 'Chart',- cornerRadius: 10,- fills: [solid(WHITE)],- strokes: thinStroke(GRAY_200)- })- const chartTitle = store.createShape('TEXT', 16, 16, 120, 18, chartBg)- graph.updateNode(chartTitle, {- name: 'Chart Title',- text: 'Revenue over time',- fontSize: 13,- fontWeight: 600,- fills: [solid(BLACK)]- })-- // Chart bars- const barHeights = [60, 90, 72, 110, 95, 130, 100, 80, 120, 140, 115, 88]- const barW = 24- const barGap = 10- const barStartX = 16- const barBaseY = 180-- for (let i = 0; i < barHeights.length; i++) {- const h = barHeights[i]- const bx = barStartX + i * (barW + barGap)- const by = barBaseY - h- const barId = store.createShape('RECTANGLE', bx, by, barW, h, chartBg)- graph.updateNode(barId, {- name: `Bar ${i + 1}`,- cornerRadius: 4,- fills: [- gradient([- { color: BLUE, position: 0 },- { color: INDIGO, position: 1 }- ])- ]- })- }-- // Table section- const tableId = store.createShape('FRAME', 76, 400, 424, 40, frameId)- graph.updateNode(tableId, {- name: 'Table Header',- fills: [solid(WHITE)],- strokes: thinStroke(GRAY_200),- layoutMode: 'HORIZONTAL',- primaryAxisSizing: 'FIXED',- counterAxisSizing: 'HUG',- primaryAxisAlign: 'SPACE_BETWEEN',- counterAxisAlign: 'CENTER',- paddingTop: 10,- paddingBottom: 10,- paddingLeft: 16,- paddingRight: 16,- itemSpacing: 16- })- const cols = ['Name', 'Status', 'Amount', 'Date']- for (const col of cols) {- const colId = store.createShape('TEXT', 0, 0, 80, 16, tableId)- graph.updateNode(colId, {- name: col,- text: col,- fontSize: 12,- fontWeight: 600,- fills: [solid(GRAY_500)]- })- }-- // ─── Standalone shapes (bottom) ───────────────────────────────- // Gradient showcase- const grad1 = store.createShape('FRAME', 60, 660, 180, 120)- graph.updateNode(grad1, {- name: 'Gradient Card',- cornerRadius: 16,- fills: [- gradient([- { color: { r: 0.99, g: 0.37, b: 0.33, a: 1 }, position: 0 },- { color: { r: 0.93, g: 0.18, b: 0.65, a: 1 }, position: 0.5 },- { color: { r: 0.55, g: 0.28, b: 0.96, a: 1 }, position: 1 }- ])- ]- })- const gradText = store.createShape('TEXT', 20, 80, 140, 20, grad1)- graph.updateNode(gradText, {- name: 'Label',- text: 'Linear Gradient',- fontSize: 14,- fontWeight: 600,- fills: [solid(WHITE)]- })-- const grad2 = store.createShape('FRAME', 260, 660, 180, 120)- graph.updateNode(grad2, {- name: 'Ocean',- cornerRadius: 16,- fills: [- gradient([- { color: { r: 0.04, g: 0.82, b: 0.67, a: 1 }, position: 0 },- { color: { r: 0.13, g: 0.45, b: 0.96, a: 1 }, position: 1 }- ])- ]- })- const grad2Text = store.createShape('TEXT', 20, 80, 140, 20, grad2)- graph.updateNode(grad2Text, {- name: 'Label',- text: 'Ocean Breeze',- fontSize: 14,- fontWeight: 600,- fills: [solid(WHITE)]- })-- const grad3 = store.createShape('FRAME', 460, 660, 180, 120)- graph.updateNode(grad3, {- name: 'Sunset',- cornerRadius: 16,- fills: [- gradient([- { color: { r: 1, g: 0.6, b: 0.2, a: 1 }, position: 0 },- { color: { r: 0.96, g: 0.26, b: 0.21, a: 1 }, position: 1 }- ])- ]- })- const grad3Text = store.createShape('TEXT', 20, 80, 140, 20, grad3)- graph.updateNode(grad3Text, {- name: 'Label',- text: 'Warm Sunset',- fontSize: 14,- fontWeight: 600,- fills: [solid(WHITE)]- })-- // Typography showcase- const typoFrame = store.createShape('FRAME', 700, 660, 300, 120)- graph.updateNode(typoFrame, {- name: 'Typography',- cornerRadius: 12,- fills: [solid(WHITE)],- strokes: thinStroke(GRAY_200),- layoutMode: 'VERTICAL',- primaryAxisSizing: 'FIXED',- counterAxisSizing: 'FIXED',- itemSpacing: 6,- paddingTop: 16,- paddingBottom: 16,- paddingLeft: 20,- paddingRight: 20- })- const typoItems = [- { text: 'Heading', size: 24, weight: 700 },- { text: 'Subheading', size: 16, weight: 600 },- { text: 'Body text — The quick brown fox jumps.', size: 13, weight: 400 },- { text: 'CAPTION · OVERLINE', size: 10, weight: 500 }- ]- for (const t of typoItems) {- const tid = store.createShape('TEXT', 0, 0, 260, t.size + 4, typoFrame)- graph.updateNode(tid, {- name: t.text.split(' ')[0],- text: t.text,- fontSize: t.size,- fontWeight: t.weight,- fills: [solid(BLACK)]- })- }-- // Mixed shapes row- const shapes = [- {- type: 'ELLIPSE' as const,- x: 1060,- fill: gradient([- { color: PURPLE, position: 0 },- { color: BLUE, position: 1 }- ])- },- {- type: 'RECTANGLE' as const,- x: 1160,- fill: gradient([- { color: GREEN, position: 0 },- { color: TEAL, position: 1 }- ])- },- {- type: 'ELLIPSE' as const,- x: 1260,- fill: gradient([- { color: ORANGE, position: 0 },- { color: RED, position: 1 }- ])- }- ]- for (const s of shapes) {- const id = store.createShape(s.type, s.x, 680, 80, 80)- graph.updateNode(id, {- name: s.type === 'ELLIPSE' ? 'Circle' : 'Square',- cornerRadius: s.type === 'RECTANGLE' ? 16 : 0,- fills: [s.fill]- })- }-- // ─── Variable Collections ──────────────────────────────────────- graph.addCollection({- id: 'col-primitives',- name: 'Primitives',- modes: [- { modeId: 'light', name: 'Light' },- { modeId: 'dark', name: 'Dark' }- ],- defaultModeId: 'light',- variableIds: []- })-- const primitiveColors: Array<{- id: string- name: string- light: Color- dark: Color- }> = [- { id: 'var-white', name: 'White', light: WHITE, dark: { r: 0.12, g: 0.12, b: 0.13, a: 1 } },- { id: 'var-black', name: 'Black', light: BLACK, dark: WHITE },- {- id: 'var-gray-50',- name: 'Gray/50',- light: GRAY_50,- dark: { r: 0.1, g: 0.1, b: 0.11, a: 1 }- },- {- id: 'var-gray-100',- name: 'Gray/100',- light: GRAY_100,- dark: { r: 0.14, g: 0.14, b: 0.16, a: 1 }- },- {- id: 'var-gray-200',- name: 'Gray/200',- light: GRAY_200,- dark: { r: 0.22, g: 0.22, b: 0.24, a: 1 }- },- {- id: 'var-gray-500',- name: 'Gray/500',- light: GRAY_500,- dark: { r: 0.65, g: 0.65, b: 0.68, a: 1 }- },- { id: 'var-blue', name: 'Blue', light: BLUE, dark: { r: 0.33, g: 0.61, b: 1, a: 1 } },- {- id: 'var-green',- name: 'Green',- light: GREEN,- dark: { r: 0.23, g: 0.87, b: 0.52, a: 1 }- },- { id: 'var-red', name: 'Red', light: RED, dark: { r: 1, g: 0.32, b: 0.32, a: 1 } }- ]-- for (const c of primitiveColors) {- graph.addVariable({- id: c.id,- name: c.name,- type: 'COLOR',- collectionId: 'col-primitives',- valuesByMode: { light: c.light, dark: c.dark },- description: '',- hiddenFromPublishing: false- })- }-- graph.addCollection({- id: 'col-semantic',- name: 'Semantic',- modes: [{ modeId: 'default', name: 'Default' }],- defaultModeId: 'default',- variableIds: []- })-- const semanticVars: Array<{ id: string; name: string; aliasId: string }> = [- { id: 'var-bg', name: 'Background', aliasId: 'var-white' },- { id: 'var-bg-secondary', name: 'Background/Secondary', aliasId: 'var-gray-50' },- { id: 'var-text-primary', name: 'Text/Primary', aliasId: 'var-black' },- { id: 'var-text-secondary', name: 'Text/Secondary', aliasId: 'var-gray-500' },- { id: 'var-border', name: 'Border', aliasId: 'var-gray-200' },- { id: 'var-accent', name: 'Accent', aliasId: 'var-blue' },- { id: 'var-success', name: 'Success', aliasId: 'var-green' },- { id: 'var-error', name: 'Error', aliasId: 'var-red' }- ]-- for (const s of semanticVars) {- graph.addVariable({- id: s.id,- name: s.name,- type: 'COLOR',- collectionId: 'col-semantic',- valuesByMode: { default: { aliasId: s.aliasId } },- description: '',- hiddenFromPublishing: false- })- }-- graph.addCollection({- id: 'col-spacing',- name: 'Spacing',- modes: [- { modeId: 'default', name: 'Default' },- { modeId: 'compact', name: 'Compact' }- ],- defaultModeId: 'default',- variableIds: []- })-- const spacingVars: Array<{ id: string; name: string; default: number; compact: number }> = [- { id: 'var-space-xs', name: 'Space/XS', default: 4, compact: 2 },- { id: 'var-space-sm', name: 'Space/SM', default: 8, compact: 4 },- { id: 'var-space-md', name: 'Space/MD', default: 16, compact: 12 },- { id: 'var-space-lg', name: 'Space/LG', default: 24, compact: 16 },- { id: 'var-space-xl', name: 'Space/XL', default: 32, compact: 24 },- { id: 'var-radius-sm', name: 'Radius/SM', default: 4, compact: 2 },- { id: 'var-radius-md', name: 'Radius/MD', default: 8, compact: 6 },- { id: 'var-radius-lg', name: 'Radius/LG', default: 16, compact: 12 }- ]-- for (const s of spacingVars) {- graph.addVariable({- id: s.id,- name: s.name,- type: 'FLOAT',- collectionId: 'col-spacing',- valuesByMode: { default: s.default, compact: s.compact },- description: '',- hiddenFromPublishing: false- })- }-- // ─── Section: Effects Showcase ──────────────────────────────────- const effectsSectionId = store.createShape('SECTION', 60, 840, 920, 480)- graph.updateNode(effectsSectionId, {- name: 'Effects',- fills: [{ type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 }, visible: true, opacity: 1 }]- })-- function dropShadow(- ox = 0,- oy = 4,- radius = 8,- spread = 0,- color: Color = { r: 0, g: 0, b: 0, a: 0.25 }- ): Effect {- return {- type: 'DROP_SHADOW',- color,- offset: { x: ox, y: oy },- radius,- spread,- visible: true- }- }-- function innerShadow(- ox = 0,- oy = 2,- radius = 4,- spread = 0,- color: Color = { r: 0, g: 0, b: 0, a: 0.2 }- ): Effect {- return {- type: 'INNER_SHADOW',- color,- offset: { x: ox, y: oy },- radius,- spread,- visible: true- }- }-- function blurEffect(type: Effect['type'], radius: number): Effect {- return {- type,- color: { r: 0, g: 0, b: 0, a: 0 },- offset: { x: 0, y: 0 },- radius,- spread: 0,- visible: true- }- }-- // Row 1: Drop shadows- const shadowLabel = store.createShape('TEXT', 32, 48, 200, 20, effectsSectionId)- graph.updateNode(shadowLabel, {- name: 'Label',- text: 'Drop Shadow',- fontSize: 13,- fontWeight: 600,- fills: [solid(GRAY_500)]- })-- const shadowCard1 = store.createShape('FRAME', 32, 76, 160, 100, effectsSectionId)- graph.updateNode(shadowCard1, {- name: 'Subtle Shadow',- cornerRadius: 12,- fills: [solid(WHITE)],- effects: [dropShadow(0, 2, 8, 0, { r: 0, g: 0, b: 0, a: 0.08 })]- })- const s1Text = store.createShape('TEXT', 16, 40, 128, 20, shadowCard1)- graph.updateNode(s1Text, {- name: 'Label',- text: 'Subtle',- fontSize: 13,- fontWeight: 500,- fills: [solid(GRAY_500)]- })-- const shadowCard2 = store.createShape('FRAME', 220, 76, 160, 100, effectsSectionId)- graph.updateNode(shadowCard2, {- name: 'Medium Shadow',- cornerRadius: 12,- fills: [solid(WHITE)],- effects: [dropShadow(0, 4, 16, 0, { r: 0, g: 0, b: 0, a: 0.15 })]- })- const s2Text = store.createShape('TEXT', 16, 40, 128, 20, shadowCard2)- graph.updateNode(s2Text, {- name: 'Label',- text: 'Medium',- fontSize: 13,- fontWeight: 500,- fills: [solid(GRAY_500)]- })-- const shadowCard3 = store.createShape('FRAME', 408, 76, 160, 100, effectsSectionId)- graph.updateNode(shadowCard3, {- name: 'Heavy Shadow',- cornerRadius: 12,- fills: [solid(WHITE)],- effects: [dropShadow(0, 8, 24, 0, { r: 0, g: 0, b: 0, a: 0.2 })]- })- const s3Text = store.createShape('TEXT', 16, 40, 128, 20, shadowCard3)- graph.updateNode(s3Text, {- name: 'Label',- text: 'Heavy',- fontSize: 13,- fontWeight: 500,- fills: [solid(GRAY_500)]- })-- const shadowCard4 = store.createShape('FRAME', 596, 76, 160, 100, effectsSectionId)- graph.updateNode(shadowCard4, {- name: 'Spread Shadow',- cornerRadius: 12,- fills: [solid(WHITE)],- effects: [dropShadow(0, 4, 12, 8, { r: 0.23, g: 0.51, b: 0.96, a: 0.3 })]- })- const s4Text = store.createShape('TEXT', 16, 40, 128, 20, shadowCard4)- graph.updateNode(s4Text, {- name: 'Label',- text: 'With Spread',- fontSize: 13,- fontWeight: 500,- fills: [solid(BLUE)]- })-- // Row 2: Inner shadows- const innerLabel = store.createShape('TEXT', 32, 208, 200, 20, effectsSectionId)- graph.updateNode(innerLabel, {- name: 'Label',- text: 'Inner Shadow',- fontSize: 13,- fontWeight: 600,- fills: [solid(GRAY_500)]- })-- const innerCard1 = store.createShape('FRAME', 32, 236, 160, 100, effectsSectionId)- graph.updateNode(innerCard1, {- name: 'Inset Light',- cornerRadius: 12,- fills: [solid(GRAY_100)],- effects: [innerShadow(0, 2, 6, 0, { r: 0, g: 0, b: 0, a: 0.12 })]- })- const i1Text = store.createShape('TEXT', 16, 40, 128, 20, innerCard1)- graph.updateNode(i1Text, {- name: 'Label',- text: 'Inset',- fontSize: 13,- fontWeight: 500,- fills: [solid(GRAY_500)]- })-- const innerCard2 = store.createShape('FRAME', 220, 236, 160, 100, effectsSectionId)- graph.updateNode(innerCard2, {- name: 'Inset with Spread',- cornerRadius: 12,- fills: [solid(GRAY_100)],- effects: [innerShadow(0, 2, 8, 4, { r: 0, g: 0, b: 0, a: 0.15 })]- })- const i2Text = store.createShape('TEXT', 16, 40, 128, 20, innerCard2)- graph.updateNode(i2Text, {- name: 'Label',- text: 'Inset + Spread',- fontSize: 13,- fontWeight: 500,- fills: [solid(GRAY_500)]- })-- // Ellipse with inner shadow- const innerEllipse = store.createShape('ELLIPSE', 408, 236, 100, 100, effectsSectionId)- graph.updateNode(innerEllipse, {- name: 'Inset Circle',- fills: [- gradient([- { color: { r: 0.93, g: 0.94, b: 1, a: 1 }, position: 0 },- { color: { r: 0.85, g: 0.86, b: 0.95, a: 1 }, position: 1 }- ])- ],- effects: [innerShadow(0, 4, 12, 0, { r: 0.38, g: 0.35, b: 0.95, a: 0.3 })]- })-- // Combined drop + inner shadow- const comboCard = store.createShape('FRAME', 536, 236, 160, 100, effectsSectionId)- graph.updateNode(comboCard, {- name: 'Combined',- cornerRadius: 12,- fills: [solid(WHITE)],- effects: [- dropShadow(0, 4, 16, 0, { r: 0, g: 0, b: 0, a: 0.12 }),- innerShadow(0, 1, 2, 0, { r: 0, g: 0, b: 0, a: 0.06 })- ]- })- const comboText = store.createShape('TEXT', 16, 40, 128, 20, comboCard)- graph.updateNode(comboText, {- name: 'Label',- text: 'Drop + Inner',- fontSize: 13,- fontWeight: 500,- fills: [solid(GRAY_500)]- })-- // Row 3: Text shadows & blurs- const textFxLabel = store.createShape('TEXT', 32, 368, 200, 20, effectsSectionId)- graph.updateNode(textFxLabel, {- name: 'Label',- text: 'Text Shadow & Blur',- fontSize: 13,- fontWeight: 600,- fills: [solid(GRAY_500)]- })-- // Text with drop shadow (renders on glyphs, not bounding box)- const textShadow = store.createShape('TEXT', 32, 400, 200, 36, effectsSectionId)- graph.updateNode(textShadow, {- name: 'Text Shadow',- text: 'Glyph Shadow',- fontSize: 28,- fontWeight: 700,- fills: [solid(BLACK)],- effects: [dropShadow(2, 2, 4, 0, { r: 0.23, g: 0.51, b: 0.96, a: 0.5 })]- })-- // Text with inner shadow- const textInner = store.createShape('TEXT', 260, 400, 200, 36, effectsSectionId)- graph.updateNode(textInner, {- name: 'Text Inner',- text: 'Inner Glow',- fontSize: 28,- fontWeight: 700,- fills: [solid(INDIGO)],- effects: [innerShadow(0, -1, 3, 0, { r: 1, g: 1, b: 1, a: 0.6 })]- })-- // Layer blur- const blurRect = store.createShape('RECTANGLE', 500, 392, 120, 50, effectsSectionId)- graph.updateNode(blurRect, {- name: 'Layer Blur',- cornerRadius: 10,- fills: [- gradient([- { color: PURPLE, position: 0 },- { color: BLUE, position: 1 }- ])- ],- effects: [blurEffect('LAYER_BLUR', 4)]- })-- // Background blur (glassmorphism card)- const glassBg = store.createShape('FRAME', 652, 368, 200, 80, effectsSectionId)- graph.updateNode(glassBg, {- name: 'Glass Card',- cornerRadius: 16,- fills: [solid({ r: 1, g: 1, b: 1, a: 0.3 })],- strokes: thinStroke({ r: 1, g: 1, b: 1, a: 0.4 }),- effects: [blurEffect('BACKGROUND_BLUR', 16)]- })- const glassText = store.createShape('TEXT', 20, 30, 160, 20, glassBg)- graph.updateNode(glassText, {- name: 'Label',- text: 'Glassmorphism',- fontSize: 14,- fontWeight: 600,- fills: [solid(BLACK)]- })-- // Bind variables to some demo nodes- graph.bindVariable(sidebarId, 'fills/0/color', 'var-bg')- graph.bindVariable(headerId, 'fills/0/color', 'var-bg')- graph.bindVariable(frameId, 'fills/0/color', 'var-bg-secondary')- graph.bindVariable(headerTitle, 'fills/0/color', 'var-text-primary')- graph.bindVariable(chartTitle, 'fills/0/color', 'var-text-primary')-- computeAllLayouts(store.graph)- store.clearSelection()-}diff --git a/src/main.ts b/src/main.tsindex b4c804e27..1fd918562 100644--- a/src/main.ts+++ b/src/main.ts@@ -3,7 +3,7 @@ import { createApp } from 'vue'import './app.css'import { IS_TAURI } from '@/constants'-import { preloadFonts } from '@/engine/fonts'+import { preloadFonts } from '@/app/editor/fonts'import App from './App.vue'import router from './router'diff --git a/src/stores/editor.ts b/src/stores/editor.tsdeleted file mode 100644index 2f70f1376..000000000--- a/src/stores/editor.ts+++ /dev/null@@ -1,1348 +0,0 @@-import { useDebounceFn } from '@vueuse/core'-import { shallowReactive, shallowRef, computed, watch, triggerRef } from 'vue'--import { IS_TAURI } from '@/constants'-import { loadFont } from '@/engine/fonts'-import { toast } from '@/utils/toast'-import {- breakAtVertex,- BUILTIN_IO_FORMATS,- cloneVectorNetwork,- computeAccurateBounds,- createDefaultEditorState,- createEditor,- deleteVertex,- exportFigFile,- findAllHandles,- findOppositeHandle,- IORegistry,- mirrorHandle,- nearestPointOnNetwork,- readFigFile,- removeVertex,- renderNodesToImage,- SceneGraph,- splitSegmentAt,- prefetchFigmaSchema-} from '@open-pencil/core'--import type {- EditorState,- ExportRequest,- Fill,- IOFormatAdapter,- RasterExportFormat,- Rect,- SceneNode,- Vector,- VectorNetwork,- VectorRegion,- VectorSegment,- VectorVertex,- Tool-} from '@open-pencil/core'--export type { Tool } from '@open-pencil/core'-export type { EditorToolDef as ToolDef } from '@open-pencil/core'-export { EDITOR_TOOLS as TOOLS, TOOL_SHORTCUTS } from '@open-pencil/core'--export function createEditorStore(initialGraph?: SceneGraph) {- const graph = initialGraph ?? new SceneGraph()-- const state = shallowReactive<- Omit<EditorState, 'penState'> & {- penState: {- vertices: VectorVertex[]- segments: VectorSegment[]- dragTangent: Vector | null- oppositeDragTangent: Vector | null- closingToFirst: boolean- pendingClose?: boolean- resumingNodeId?: string- resumedFills?: Fill[]- resumedStrokes?: SceneNode['strokes']- } | null- showUI: boolean- showRulers: boolean- showRemoteCursors: boolean- activeRibbonTab: 'panels' | 'code' | 'ai'- panelMode: 'layers' | 'design'- actionToast: string | null- mobileDrawerSnap: 'closed' | 'half' | 'full'- clipboardHtml: string- autosaveEnabled: boolean- cursorCanvasX: number | null- cursorCanvasY: number | null- nodeEditState: {- nodeId: string- origNetwork: VectorNetwork- origBounds: Rect- vertices: VectorVertex[]- segments: VectorSegment[]- regions: VectorRegion[]- selectedVertexIndices: Set<number>- draggedHandleInfo: {- vertexIndex: number- handleType: 'tangentStart' | 'tangentEnd'- segmentIndex: number- } | null- /** Set of selected handles as "segIdx:tangentField" strings */- selectedHandles: Set<string>- hoveredHandleInfo: {- segmentIndex: number- tangentField: 'tangentStart' | 'tangentEnd'- } | null- } | null- scrubInputFocused: boolean- }- >({- ...createDefaultEditorState(graph.getPages()[0].id),- showUI: true,- showRulers: true,- showRemoteCursors: true,- activeRibbonTab: 'panels',- panelMode: 'design',- actionToast: null,- mobileDrawerSnap: 'closed',- clipboardHtml: '',- autosaveEnabled: false,- cursorCanvasX: null,- cursorCanvasY: null,- nodeEditState: null,- scrubInputFocused: false- })-- const viewportSize = { width: 0, height: 0 }- const editor = createEditor({- graph,- state,- loadFont,- skipInitialGraphSetup: !!initialGraph,- getViewportSize: () =>- viewportSize.width > 0 && viewportSize.height > 0- ? viewportSize- : { width: window.innerWidth, height: window.innerHeight }- })- const io = new IORegistry(BUILTIN_IO_FORMATS)-- if (initialGraph) {- editor.subscribeToGraph()- }-- // ─── Vue computed refs ────────────────────────────────────────-- const selectedNodes = computed(() => {- void state.sceneVersion- return editor.getSelectedNodes()- })-- const selectedNode = computed(() =>- selectedNodes.value.length === 1 ? selectedNodes.value[0] : undefined- )-- const layerTree = computed(() => {- void state.sceneVersion- return editor.getLayerTree()- })-- // ─── File I/O state ───────────────────────────────────────────-- let fileHandle: FileSystemFileHandle | null = null- let filePath: string | null = null- let downloadName: string | null = null- let savedVersion = 0- let lastWriteTime = 0- let unwatchFile: (() => void) | null = null-- void prefetchFigmaSchema()-- function downloadBlob(data: Uint8Array, filename: string, mime: string) {- const blob = new Blob([data.buffer as ArrayBuffer], { type: mime })- const url = URL.createObjectURL(blob)- const a = document.createElement('a')- a.href = url- a.download = filename- a.style.display = 'none'- document.body.appendChild(a)- a.click()- setTimeout(() => {- document.body.removeChild(a)- URL.revokeObjectURL(url)- }, 100)- }-- const AUTOSAVE_DELAY = 3000-- const debouncedAutosave = useDebounceFn(async () => {- if (state.sceneVersion === savedVersion) return- if (!state.autosaveEnabled) return- try {- await writeFile(await buildFigFile())- } catch (e) {- console.warn('Autosave failed:', e)- }- }, AUTOSAVE_DELAY)-- watch(- () => state.sceneVersion,- (version) => {- if (version === savedVersion) return- if (!state.autosaveEnabled) return- if (!fileHandle && !filePath) return- void debouncedAutosave()- }- )-- // ─── Flash nodes (renderer-specific) ─────────────────────────-- let flashRafId = 0- function flashNodes(nodeIds: string[]) {- const renderer = editor.renderer- if (!renderer) return- for (const id of nodeIds) renderer.flashNode(id)- if (!flashRafId) pumpFlashes()- }-- function aiMarkActive(nodeIds: string[]) {- if (!editor.renderer) return- editor.renderer.aiMarkActive(nodeIds)- if (!flashRafId) pumpFlashes()- }-- function aiMarkDone(nodeIds: string[]) {- if (!editor.renderer) return- editor.renderer.aiMarkDone(nodeIds)- if (!flashRafId) pumpFlashes()- }-- function aiFlashDone(nodeIds: string[]) {- if (!editor.renderer) return- editor.renderer.aiFlashDone(nodeIds)- if (!flashRafId) pumpFlashes()- }-- function aiClearAll() {- editor.renderer?.aiClearAll()- }-- function pumpFlashes() {- if (!editor.renderer?.hasActiveFlashes) {- flashRafId = 0- return- }- state.renderVersion++- flashRafId = requestAnimationFrame(pumpFlashes)- }-- // ─── Tool override (commit pen on tool switch) ────────────────-- function setTool(tool: Tool) {- // If switching away from PEN while drawing, commit the open path- // except when switching to HAND (e.g. holding Space to pan)- if (state.penState && tool !== 'PEN' && tool !== 'HAND') {- editor.penCommit(false)- }- state.activeTool = tool- }-- // ─── Pen resume (vector editor) ────────────────────────────────-- function penResumeOnPath(nodeId: string) {- const node = graph.getNode(nodeId)- if (node?.type !== 'VECTOR' || !node.vectorNetwork) return-- const vn = node.vectorNetwork-- // Convert to absolute coords- const absVertices: VectorVertex[] = vn.vertices.map((v) => ({- ...v,- x: v.x + node.x,- y: v.y + node.y- }))-- state.penState = {- vertices: absVertices,- segments: vn.segments.map((s) => ({- ...s,- tangentStart: { ...s.tangentStart },- tangentEnd: { ...s.tangentEnd }- })),- dragTangent: null,- oppositeDragTangent: null,- closingToFirst: false,- pendingClose: false,- resumingNodeId: nodeId,- resumedFills: [...node.fills],- resumedStrokes: [...node.strokes]- }-- // Remove the original node (will be recreated on commit)- graph.deleteNode(nodeId)- state.selectedIds = new Set()- state.activeTool = 'PEN'- editor.requestRender()- }-- /** Walk a chain from `start` and return the last vertex reached. */- function walkChainToEnd(segments: { start: number; end: number }[], start: number): number {- let current = start- const visited = new Set<number>([start])- for (;;) {- let found = false- for (const seg of segments) {- let next = -1- if (seg.start === current && !visited.has(seg.end)) next = seg.end- else if (seg.end === current && !visited.has(seg.start)) next = seg.start- if (next === -1) continue- visited.add(next)- current = next- found = true- break- }- if (!found) break- }- return current- }-- /** Walk from `start` and return ordered vertices/segments (remapped to 0-based indices). */- function walkChainOrdered(- absVertices: VectorVertex[],- absSegments: VectorSegment[],- start: number- ): { orderedVertices: VectorVertex[]; orderedSegments: VectorSegment[] } {- const orderedVertices: VectorVertex[] = []- const orderedSegments: VectorSegment[] = []- const visited = new Set<number>()- let current = start-- orderedVertices.push(absVertices[current])- visited.add(current)-- for (;;) {- let foundSeg = false- for (const seg of absSegments) {- let next = -1- let isForward = false- if (seg.start === current && !visited.has(seg.end)) {- next = seg.end- isForward = true- } else if (seg.end === current && !visited.has(seg.start)) {- next = seg.start- isForward = false- }- if (next === -1) continue-- const fromIdx = orderedVertices.length - 1- orderedVertices.push(absVertices[next])- const toIdx = orderedVertices.length - 1-- orderedSegments.push({- start: fromIdx,- end: toIdx,- tangentStart: isForward ? { ...seg.tangentStart } : { ...seg.tangentEnd },- tangentEnd: isForward ? { ...seg.tangentEnd } : { ...seg.tangentStart }- })-- visited.add(next)- current = next- foundSeg = true- break- }- if (!foundSeg) break- }- return { orderedVertices, orderedSegments }- }-- /**- * Resume pen drawing from an endpoint of an existing VECTOR node.- * Reorders vertices/segments so the endpoint is the last vertex,- * then sets up penState for continuing the drawing.- */- function penResumeFromEndpoint(nodeId: string, endpointVertexIndex: number) {- const node = graph.getNode(nodeId)- if (node?.type !== 'VECTOR' || !node.vectorNetwork) return-- const vn = node.vectorNetwork-- // Convert to absolute coords- const absVertices: VectorVertex[] = vn.vertices.map((v) => ({- ...v,- x: v.x + node.x,- y: v.y + node.y- }))- const absSegments: VectorSegment[] = vn.segments.map((s) => ({- ...s,- tangentStart: { ...s.tangentStart },- tangentEnd: { ...s.tangentEnd }- }))-- // Find the OTHER endpoint, then walk from it so the clicked one ends up last.- const otherEnd = walkChainToEnd(absSegments, endpointVertexIndex)- const { orderedVertices, orderedSegments } = walkChainOrdered(- absVertices,- absSegments,- otherEnd- )-- state.penState = {- vertices: orderedVertices,- segments: orderedSegments,- dragTangent: null,- oppositeDragTangent: null,- closingToFirst: false,- pendingClose: false,- resumingNodeId: nodeId,- resumedFills: [...node.fills],- resumedStrokes: [...node.strokes]- }-- graph.deleteNode(nodeId)- state.selectedIds = new Set()- state.activeTool = 'PEN'- editor.requestRender()- }-- // ─── Node edit mode (vector geometry) ──────────────────────────-- const NODE_EDIT_HIT_THRESHOLD = 8-- function getNodeEditState() {- return state.nodeEditState- }-- function setNodeEditNetwork(es: NonNullable<typeof state.nodeEditState>, network: VectorNetwork) {- es.vertices = network.vertices.map((v) => ({ ...v }))- es.segments = network.segments.map((s) => ({- ...s,- tangentStart: { ...s.tangentStart },- tangentEnd: { ...s.tangentEnd }- }))- es.regions = network.regions.map((r) => ({- windingRule: r.windingRule,- loops: r.loops.map((l) => [...l])- }))- }-- function getLiveNetwork(es: NonNullable<typeof state.nodeEditState>): VectorNetwork {- return {- vertices: es.vertices.map((v) => ({ ...v })),- segments: es.segments.map((s) => ({- ...s,- tangentStart: { ...s.tangentStart },- tangentEnd: { ...s.tangentEnd }- })),- regions: es.regions.map((r) => ({- windingRule: r.windingRule,- loops: r.loops.map((l) => [...l])- }))- }- }-- function applyNodeEditToNode(es: NonNullable<typeof state.nodeEditState>) {- const node = graph.getNode(es.nodeId)- if (node?.type !== 'VECTOR') return-- const live = getLiveNetwork(es)- const bounds = computeAccurateBounds(live)- const relativeNetwork: VectorNetwork = {- vertices: live.vertices.map((v) => ({- ...v,- x: v.x - bounds.x,- y: v.y - bounds.y- })),- segments: live.segments,- regions: live.regions- }-- graph.updateNode(node.id, {- x: bounds.x,- y: bounds.y,- width: bounds.width,- height: bounds.height,- vectorNetwork: relativeNetwork- })- editor.requestRender()- }-- function enterNodeEditMode(nodeId: string) {- const node = graph.getNode(nodeId)- if (node?.type !== 'VECTOR' || !node.vectorNetwork) return-- const absVertices = node.vectorNetwork.vertices.map((v) => ({- ...v,- x: v.x + node.x,- y: v.y + node.y- }))-- state.nodeEditState = {- nodeId,- origNetwork: cloneVectorNetwork(node.vectorNetwork),- origBounds: { x: node.x, y: node.y, width: node.width, height: node.height },- vertices: absVertices,- segments: node.vectorNetwork.segments.map((s) => ({- ...s,- tangentStart: { ...s.tangentStart },- tangentEnd: { ...s.tangentEnd }- })),- regions: node.vectorNetwork.regions.map((r) => ({- windingRule: r.windingRule,- loops: r.loops.map((l) => [...l])- })),- selectedVertexIndices: new Set(),- draggedHandleInfo: null,- selectedHandles: new Set(),- hoveredHandleInfo: null- }-- state.selectedIds = new Set([nodeId])- editor.requestRender()- }-- function exitNodeEditMode(commit: boolean) {- const es = getNodeEditState()- if (!es) return-- const node = graph.getNode(es.nodeId)- if (node?.type !== 'VECTOR') {- state.nodeEditState = null- editor.requestRender()- return- }-- if (commit) {- applyNodeEditToNode(es)- } else {- graph.updateNode(es.nodeId, {- x: es.origBounds.x,- y: es.origBounds.y,- width: es.origBounds.width,- height: es.origBounds.height,- vectorNetwork: cloneVectorNetwork(es.origNetwork)- })- editor.requestRender()- }-- state.nodeEditState = null- }-- function nodeEditSelectVertex(vertexIndex: number, addToSelection: boolean) {- const es = getNodeEditState()- if (!es) return- if (addToSelection) {- const next = new Set(es.selectedVertexIndices)- if (next.has(vertexIndex)) next.delete(vertexIndex)- else next.add(vertexIndex)- es.selectedVertexIndices = next- } else {- es.selectedVertexIndices = new Set([vertexIndex])- }- editor.requestRepaint()- }-- type HandleInfo = {- segmentIndex: number- tangentField: 'tangentStart' | 'tangentEnd'- neighborIndex: number- }-- /** Resolve the base direction vector for a handle, falling back to neighbor direction. */- function handleBaseVector(tangent: Vector, neighbor: Vector, origin: Vector): Vector {- return Math.hypot(tangent.x, tangent.y) > 1e-6- ? tangent- : { x: neighbor.x - origin.x, y: neighbor.y - origin.y }- }-- /** Among sibling handles, find the one most opposite to the active handle direction. */- function findSisterHandle(- es: NonNullable<typeof state.nodeEditState>,- siblings: HandleInfo[],- activeBase: Vector,- vertexIndex: number- ): HandleInfo {- let sister = siblings[0]- const activeBaseLen = Math.hypot(activeBase.x, activeBase.y)- if (activeBaseLen <= 1e-6) return sister-- const activeDir = { x: activeBase.x / activeBaseLen, y: activeBase.y / activeBaseLen }- let bestDot = Infinity- for (const s of siblings) {- const sSeg = es.segments[s.segmentIndex]- const sVertex = es.vertices[vertexIndex]- const sNeighbor = es.vertices[s.neighborIndex]- const sBase = handleBaseVector(sSeg[s.tangentField], sNeighbor, sVertex)- const sLen = Math.hypot(sBase.x, sBase.y)- if (sLen < 1e-6) continue- const sDir = { x: sBase.x / sLen, y: sBase.y / sLen }- const dot = activeDir.x * sDir.x + activeDir.y * sDir.y- if (dot < bestDot) {- bestDot = dot- sister = s- }- }- return sister- }-- /** Constrain a tangent to be continuous with the sister handle. Returns the constrained vector, or null if no constraint applied. */- function constrainContinuousTangent(- es: NonNullable<typeof state.nodeEditState>,- newTangent: Vector,- active: HandleInfo,- all: HandleInfo[],- seg: VectorSegment,- tangentField: 'tangentStart' | 'tangentEnd',- vertexIndex: number,- vertex: VectorVertex- ): Vector | null {- const siblings = all.filter(- (h) => !(h.segmentIndex === active.segmentIndex && h.tangentField === active.tangentField)- )- if (siblings.length === 0) return null-- const activeNeighbor = es.vertices[active.neighborIndex]- const activeBase = handleBaseVector(seg[tangentField], activeNeighbor, vertex)- const sister = findSisterHandle(es, siblings, activeBase, vertexIndex)-- const sisterSeg = es.segments[sister.segmentIndex]- const sisterNeighbor = es.vertices[sister.neighborIndex]- const sisterBase = handleBaseVector(sisterSeg[sister.tangentField], sisterNeighbor, vertex)- const sisterLen = Math.hypot(sisterBase.x, sisterBase.y)- if (sisterLen <= 1e-6) return null-- const desiredDir = { x: -sisterBase.x / sisterLen, y: -sisterBase.y / sisterLen }- const len = Math.max(0, newTangent.x * desiredDir.x + newTangent.y * desiredDir.y)- vertex.handleMirroring = 'ANGLE'- return { x: desiredDir.x * len, y: desiredDir.y * len }- }-- function nodeEditSetHandle(- segmentIndex: number,- tangentField: 'tangentStart' | 'tangentEnd',- newTangent: Vector,- options?: {- breakMirroring?: boolean- continuous?: boolean- lockDirection?: boolean- }- ) {- const es = getNodeEditState()- if (!es) return- const seg = es.segments[segmentIndex]-- const breakMirroring = options?.breakMirroring ?? false- const continuous = options?.continuous ?? false- const lockDirection = options?.lockDirection ?? false- const vertexIndex = tangentField === 'tangentStart' ? seg.start : seg.end- const vertex = es.vertices[vertexIndex]- const live = getLiveNetwork(es)-- const all = findAllHandles(live, vertexIndex)- const active = all.find(- (h) => h.segmentIndex === segmentIndex && h.tangentField === tangentField- )-- let applied = { x: newTangent.x, y: newTangent.y }- if (continuous && active) {- applied =- constrainContinuousTangent(- es,- newTangent,- active,- all,- seg,- tangentField,- vertexIndex,- vertex- ) ?? applied- }-- seg[tangentField] = applied- const mode = vertex.handleMirroring ?? 'NONE'- if (lockDirection && mode === 'NONE') {- seg[tangentField] = { x: newTangent.x, y: newTangent.y }- editor.requestRepaint()- return- }- if (breakMirroring) {- vertex.handleMirroring = 'NONE'- editor.requestRepaint()- return- }- if (mode === 'NONE') {- editor.requestRepaint()- return- }-- const opposite = findOppositeHandle(live, vertexIndex, segmentIndex)- if (!opposite) {- editor.requestRepaint()- return- }-- const oppositeSeg = es.segments[opposite.segmentIndex]- const oppositeCurrent = oppositeSeg[opposite.tangentField]- const oppositeLength =- mode === 'ANGLE' ? Math.hypot(oppositeCurrent.x, oppositeCurrent.y) : undefined- const mirrored = mirrorHandle(applied, mode, oppositeLength)- if (mirrored) {- oppositeSeg[opposite.tangentField] = mirrored- }- editor.requestRepaint()- }-- function nodeEditBendHandle(- vertexIndex: number,- dx: number,- dy: number,- independent: boolean,- targetSegmentIndex: number | null,- targetTangentField: 'tangentStart' | 'tangentEnd' | null- ) {- const es = getNodeEditState()- if (!es) return- if (targetSegmentIndex == null || targetTangentField == null) return- const live = getLiveNetwork(es)- const handles = findAllHandles(live, vertexIndex)- if (handles.length === 0) return-- const effectiveTargets = handles.filter(- (h) => h.segmentIndex === targetSegmentIndex && h.tangentField === targetTangentField- )- if (effectiveTargets.length === 0) return-- const primary = { x: dx, y: dy }- const opposite = independent ? { x: dx, y: dy } : { x: -dx, y: -dy }-- const first = effectiveTargets[0]- es.segments[first.segmentIndex][first.tangentField] = primary- for (let i = 1; i < effectiveTargets.length; i++) {- const h = effectiveTargets[i]- es.segments[h.segmentIndex][h.tangentField] = primary- }- if (!independent) {- for (const h of handles) {- if (effectiveTargets.includes(h)) continue- es.segments[h.segmentIndex][h.tangentField] = opposite- }- }-- es.vertices[vertexIndex].handleMirroring = independent ? 'NONE' : 'ANGLE_AND_LENGTH'- editor.requestRepaint()- }-- function nodeEditZeroVertexHandles(vertexIndex: number) {- const es = getNodeEditState()- if (!es) return- const live = getLiveNetwork(es)- const handles = findAllHandles(live, vertexIndex)- for (const h of handles) {- es.segments[h.segmentIndex][h.tangentField] = { x: 0, y: 0 }- }- es.vertices[vertexIndex].handleMirroring = 'NONE'- editor.requestRepaint()- }-- function nodeEditConnectEndpoints(a: number, b: number) {- const es = getNodeEditState()- if (!es || a === b) return- if (a < 0 || b < 0 || a >= es.vertices.length || b >= es.vertices.length) return-- const removeIndex = a- const keepIndex = b- const remap = (idx: number): number => {- if (idx === removeIndex) return keepIndex- return idx > removeIndex ? idx - 1 : idx- }-- const nextVertices = es.vertices.filter((_, idx) => idx !== removeIndex)- const nextSegments = es.segments- .map((seg) => ({- ...seg,- tangentStart: { ...seg.tangentStart },- tangentEnd: { ...seg.tangentEnd },- start: remap(seg.start),- end: remap(seg.end)- }))- .filter((seg) => seg.start !== seg.end)-- setNodeEditNetwork(es, { vertices: nextVertices, segments: nextSegments, regions: [] })- es.selectedVertexIndices = new Set([remap(keepIndex)])- es.selectedHandles = new Set()- editor.requestRender()- }-- function nodeEditAddVertex(cx: number, cy: number) {- const es = getNodeEditState()- if (!es) return- const live = getLiveNetwork(es)- const nearest = nearestPointOnNetwork(cx, cy, live, NODE_EDIT_HIT_THRESHOLD / state.zoom)- if (!nearest) return- const split = splitSegmentAt(live, nearest.segmentIndex, nearest.t)- setNodeEditNetwork(es, split.network)- es.selectedVertexIndices = new Set([split.newVertexIndex])- es.selectedHandles = new Set()- editor.requestRender()- }-- function nodeEditRemoveVertex(vertexIndex: number) {- const es = getNodeEditState()- if (!es) return- const live = getLiveNetwork(es)- const next = removeVertex(live, vertexIndex)- if (!next) return- setNodeEditNetwork(es, next)- es.selectedVertexIndices = new Set()- es.selectedHandles = new Set()- editor.requestRender()- }-- function nodeEditAlignVertices(axis: 'horizontal' | 'vertical', align: 'min' | 'center' | 'max') {- const es = getNodeEditState()- if (!es || es.selectedVertexIndices.size < 2) return-- const indices = [...es.selectedVertexIndices]- const prop = axis === 'horizontal' ? 'x' : 'y'-- let lo = Infinity- let hi = -Infinity- for (const i of indices) {- const v = es.vertices[i][prop]- if (v < lo) lo = v- if (v > hi) hi = v- }-- let target = (lo + hi) / 2- if (align === 'min') target = lo- else if (align === 'max') target = hi- for (const i of indices) {- es.vertices[i] = { ...es.vertices[i], [prop]: target }- }- editor.requestRepaint()- }-- function nodeEditDeleteSelected() {- const es = getNodeEditState()- if (!es) return- let live = getLiveNetwork(es)-- for (const key of es.selectedHandles) {- const [siStr, tf] = key.split(':')- const si = Number(siStr)- const seg = live.segments[si]- if (tf === 'tangentStart') seg.tangentStart = { x: 0, y: 0 }- else seg.tangentEnd = { x: 0, y: 0 }- }-- const verticesToDelete = [...es.selectedVertexIndices].sort((a, b) => b - a)- for (const vi of verticesToDelete) {- const next = deleteVertex(live, vi)- if (!next) break- live = next- }-- setNodeEditNetwork(es, live)- es.selectedVertexIndices = new Set()- es.selectedHandles = new Set()- editor.requestRender()- }-- function nodeEditBreakAtVertex() {- const es = getNodeEditState()- if (!es || es.selectedVertexIndices.size === 0) return- const [vertexIndex] = es.selectedVertexIndices- const live = getLiveNetwork(es)- const next = breakAtVertex(live, vertexIndex)- setNodeEditNetwork(es, next)- es.selectedHandles = new Set()- es.selectedVertexIndices = new Set([vertexIndex])- editor.requestRender()- }-- // ─── File I/O ──────────────────────────────────────────────────-- function yieldToUI(): Promise<void> {- return new Promise((r) => requestAnimationFrame(() => r()))- }-- function setViewportSize(width: number, height: number) {- viewportSize.width = width- viewportSize.height = height- }-- async function fitCurrentPageToViewport() {- await yieldToUI()- editor.zoomToFit()- }-- function setDocumentSource(- fileName: string,- sourceFormat: string,- handle?: FileSystemFileHandle,- path?: string- ) {- stopWatchingFile()- fileHandle = sourceFormat === 'fig' ? (handle ?? null) : null- filePath = sourceFormat === 'fig' ? (path ?? null) : null- downloadName = sourceFormat === 'fig' ? fileName : fileName.replace(/\.[^.]+$/i, '.fig')- savedVersion = state.sceneVersion- if (sourceFormat === 'fig' && (fileHandle || filePath)) {- void startWatchingFile()- }- }-- function setPlannedFilePath(path: string) {- stopWatchingFile()- fileHandle = null- filePath = path- downloadName = path.split(/[\\/]/).pop() ?? 'Untitled.fig'- state.documentName = downloadName.replace(/\.fig$/i, '')- }-- function startWatchingCurrentFile() {- void startWatchingFile()- }-- function dispose() {- stopWatchingFile()- ;(debouncedAutosave as typeof debouncedAutosave & { cancel?: () => void }).cancel?.()- }-- async function openFigFile(file: File, handle?: FileSystemFileHandle, path?: string) {- try {- state.loading = true- await yieldToUI()- const imported = await readFigFile(file, { populate: 'first-page' })- await yieldToUI()- editor.replaceGraph(imported)- editor.undo.clear()- state.documentName = file.name.replace(/\.fig$/i, '')- setDocumentSource(file.name, 'fig', handle, path)- state.selectedIds = new Set()- const firstPage = editor.graph.getPages()[0] as SceneNode | undefined- const pageId = firstPage?.id ?? editor.graph.rootId- await editor.switchPage(pageId)- await fitCurrentPageToViewport()- editor.requestRender()- } catch (e) {- console.error('Failed to open .fig file:', e)- toast.error(`Failed to open file: ${e instanceof Error ? e.message : String(e)}`)- } finally {- state.loading = false- }- }-- function buildFigFile() {- return exportFigFile(editor.graph, undefined, editor.renderer ?? undefined, state.currentPageId)- }-- async function saveFigFile() {- if (filePath || fileHandle) {- await writeFile(await buildFigFile())- } else if (downloadName) {- downloadBlob(new Uint8Array(await buildFigFile()), downloadName, 'application/octet-stream')- } else {- await saveFigFileAs()- }- }-- async function saveFigFileAs() {- const data = await buildFigFile()-- if (IS_TAURI) {- const { save } = await import('@tauri-apps/plugin-dialog')- const path = await save({- defaultPath: 'Untitled.fig',- filters: [{ name: 'Figma file', extensions: ['fig'] }]- })- if (!path) return- filePath = path- fileHandle = null- state.documentName =- path- .split('/')- .pop()- ?.replace(/\.fig$/i, '') ?? 'Untitled'- await writeFile(data)- void startWatchingFile()- return- }-- if (window.showSaveFilePicker) {- try {- const handle = await window.showSaveFilePicker({- suggestedName: 'Untitled.fig',- types: [- {- description: 'Figma file',- accept: { 'application/octet-stream': ['.fig'] }- }- ]- })- fileHandle = handle- filePath = null- state.documentName = handle.name.replace(/\.fig$/i, '')- await writeFile(data)- void startWatchingFile()- return- } catch (e) {- if ((e as Error).name === 'AbortError') return- }- }-- const filename = prompt('Save as:', downloadName ?? 'Untitled.fig')- if (!filename) return- downloadName = filename- state.documentName = filename.replace(/\.fig$/i, '')- downloadBlob(new Uint8Array(data), filename, 'application/octet-stream')- }-- async function writeFile(data: Uint8Array) {- lastWriteTime = Date.now()- if (filePath && IS_TAURI) {- const { writeFile: tauriWrite } = await import('@tauri-apps/plugin-fs')- await tauriWrite(filePath, data)- savedVersion = state.sceneVersion- return- }- if (fileHandle) {- const writable = await fileHandle.createWritable()- await writable.write(new Uint8Array(data))- await writable.close()- savedVersion = state.sceneVersion- }- }-- const WATCH_DEBOUNCE_MS = 1000-- async function reloadFromDisk() {- const viewport = { panX: state.panX, panY: state.panY, zoom: state.zoom }- const pageId = state.currentPageId-- if (filePath && IS_TAURI) {- const { readFile: tauriRead } = await import('@tauri-apps/plugin-fs')- const bytes = await tauriRead(filePath)- const blob = new Blob([bytes])- const file = new File([blob], state.documentName + '.fig')- const imported = await readFigFile(file, { populate: 'first-page' })- editor.replaceGraph(imported)- } else if (fileHandle) {- const file = await fileHandle.getFile()- const imported = await readFigFile(file, { populate: 'first-page' })- editor.replaceGraph(imported)- } else {- return- }-- editor.undo.clear()- savedVersion = state.sceneVersion- state.selectedIds = new Set()- if (editor.graph.getNode(pageId)) {- state.currentPageId = pageId- } else {- state.currentPageId = editor.graph.getPages()[0]?.id ?? editor.graph.rootId- }- state.panX = viewport.panX- state.panY = viewport.panY- state.zoom = viewport.zoom- editor.requestRender()- }-- function stopWatchingFile() {- if (unwatchFile) {- unwatchFile()- unwatchFile = null- }- }-- async function startWatchingFile() {- stopWatchingFile()-- if (filePath && IS_TAURI) {- const { watch: tauriWatch } = await import('@tauri-apps/plugin-fs')- const path = filePath- const unwatch = await tauriWatch(- path,- (event) => {- if (typeof event.type !== 'object' || !('modify' in event.type)) return- if (Date.now() - lastWriteTime < WATCH_DEBOUNCE_MS) return- void reloadFromDisk()- },- { delayMs: 500 }- )- unwatchFile = () => unwatch()- } else if (fileHandle) {- let lastModified = (await fileHandle.getFile()).lastModified- // oxlint-disable-next-line typescript/no-misused-promises- const interval = setInterval(async () => {- if (!fileHandle) {- clearInterval(interval)- return- }- try {- const file = await fileHandle.getFile()- if (file.lastModified > lastModified) {- lastModified = file.lastModified- if (Date.now() - lastWriteTime < WATCH_DEBOUNCE_MS) return- void reloadFromDisk()- }- } catch {- clearInterval(interval)- }- }, 2000)- unwatchFile = () => clearInterval(interval)- }- }-- // ─── Export ───────────────────────────────────────────────────-- async function renderExportImage(- nodeIds: string[],- scale: number,- format: RasterExportFormat- ): Promise<Uint8Array | null> {- const renderer = editor.renderer- if (!renderer) return null- const ids =- nodeIds.length > 0 ? nodeIds : editor.graph.getChildren(state.currentPageId).map((n) => n.id)- if (ids.length === 0) return null- return renderNodesToImage(renderer.ck, renderer, editor.graph, state.currentPageId, ids, {- scale,- format- })- }-- function getExportBaseName(target: ExportRequest['target']): string {- if (target.scope === 'node') {- return editor.graph.getNode(target.nodeId)?.name ?? 'Export'- }- if (target.scope === 'selection' && target.nodeIds.length === 1) {- return editor.graph.getNode(target.nodeIds[0])?.name ?? 'Export'- }- if (target.scope === 'page') {- return editor.graph.getNode(target.pageId)?.name ?? 'Page'- }- return 'Export'- }-- function getSelectionExportTarget(): ExportRequest['target'] {- const ids = [...state.selectedIds]- if (ids.length > 0) return { scope: 'selection', nodeIds: ids }- return { scope: 'page', pageId: state.currentPageId }- }-- function listSelectionExportFormats(): IOFormatAdapter[] {- return io.listExportFormats(state.selectedIds.size > 0 ? 'selection' : 'page')- }-- async function exportTarget(- target: ExportRequest['target'],- formatId: string,- options?: { scale?: number; quality?: number; jsxFormat?: 'openpencil' | 'tailwind' }- ) {- const format = io.getFormat(formatId)- if (!format) throw new Error(`Unknown export format: ${formatId}`)-- let exportOptions: unknown- if (formatId === 'png' || formatId === 'jpg' || formatId === 'webp') {- exportOptions = {- format: formatId.toUpperCase(),- scale: options?.scale ?? 1,- quality: options?.quality- }- } else if (formatId === 'jsx') {- exportOptions = { format: options?.jsxFormat ?? 'openpencil' }- }-- const result = await io.exportContent(- formatId,- { graph: editor.graph, target },- exportOptions,- editor.renderer ? { canvasKit: editor.renderer.ck, renderer: editor.renderer } : undefined- )-- const baseName = getExportBaseName(target)- const fileName =- formatId === 'png' || formatId === 'jpg' || formatId === 'webp'- ? `${baseName}@${options?.scale ?? 1}x.${result.extension}`- : `${baseName}.${result.extension}`-- const bytes =- typeof result.data === 'string'- ? new TextEncoder().encode(result.data)- : new Uint8Array(result.data)-- await saveExportedFile(bytes, fileName, format.label, `.${result.extension}`, result.mimeType)- }-- async function exportSelection(scale: number, formatId: 'png' | 'jpg' | 'webp' | 'svg' | 'fig') {- await exportTarget(getSelectionExportTarget(), formatId, { scale })- }-- async function saveExportedFile(- data: Uint8Array,- fileName: string,- format: string,- ext: string,- mime: string- ) {- if (IS_TAURI) {- const { save } = await import('@tauri-apps/plugin-dialog')- const path = await save({- defaultPath: fileName,- filters: [{ name: format, extensions: [ext.slice(1)] }]- })- if (!path) return- const { writeFile: tauriWrite } = await import('@tauri-apps/plugin-fs')- await tauriWrite(path, data)- return- }-- if (window.showSaveFilePicker) {- try {- const handle = await window.showSaveFilePicker({- suggestedName: fileName,- types: [- {- description: `${format} file`,- accept: { [mime]: [ext] }- }- ]- })- const writable = await handle.createWritable()- await writable.write(new Uint8Array(data))- await writable.close()- return- } catch (e) {- if ((e as Error).name === 'AbortError') return- }- }-- downloadBlob(data, fileName, mime)- }-- // ─── Mobile clipboard ─────────────────────────────────────────-- async function mobileCopy() {- const transfer = new DataTransfer()- await editor.writeCopyData(transfer)- state.clipboardHtml = transfer.getData('text/html')- }-- async function mobileCut() {- await mobileCopy()- editor.deleteSelected()- }-- function mobilePaste() {- if (state.clipboardHtml) {- editor.pasteFromHTML(state.clipboardHtml)- }- }-- // ─── Profiler toggle ─────────────────────────────────────────-- function viewportScreenCenter() {- const canvas = document.querySelector<HTMLCanvasElement>('[data-test-id="canvas-element"]')- if (canvas) {- const rect = canvas.getBoundingClientRect()- return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }- }- return { x: window.innerWidth / 2, y: window.innerHeight / 2 }- }-- function toggleProfiler() {- editor.renderer?.profiler.toggle()- editor.requestRepaint()- }-- // ─── Public API ───────────────────────────────────────────────- // Spread all core Editor methods, then override getters and add app-specific.-- const store = {- ...editor,- state,- selectedNodes,- selectedNode,- layerTree,-- // App-specific overrides and additions- flashNodes,- aiMarkActive,- aiMarkDone,- aiFlashDone,- aiClearAll,- setTool,- penResumeOnPath,- penResumeFromEndpoint,- enterNodeEditMode,- exitNodeEditMode,- nodeEditSelectVertex,- nodeEditSetHandle,- nodeEditBendHandle,- nodeEditZeroVertexHandles,- nodeEditConnectEndpoints,- nodeEditAddVertex,- nodeEditRemoveVertex,- nodeEditAlignVertices,- nodeEditDeleteSelected,- nodeEditBreakAtVertex,- openFigFile,- setViewportSize,- fitCurrentPageToViewport,- saveFigFile,- saveFigFileAs,- setDocumentSource,- setPlannedFilePath,- startWatchingCurrentFile,- dispose,- renderExportImage,- listSelectionExportFormats,- exportTarget,- exportSelection,- mobileCopy,- mobileCut,- mobilePaste,- viewportScreenCenter,- toggleProfiler- }-- Object.defineProperties(store, {- graph: {- enumerable: true,- get: () => editor.graph- },- renderer: {- enumerable: true,- get: () => editor.renderer- },- textEditor: {- enumerable: true,- get: () => editor.textEditor- }- })-- return store-}--export type EditorStore = ReturnType<typeof createEditorStore>--const storeRef = shallowRef<EditorStore>()--export function setActiveEditorStore(store: EditorStore) {- storeRef.value = store- triggerRef(storeRef)-}--export function getActiveEditorStore(): EditorStore {- if (!storeRef.value) throw new Error('Editor store not provided')- return storeRef.value-}--const storeProxy = new Proxy({} as EditorStore, {- get(_, prop) {- return Reflect.get(getActiveEditorStore(), prop)- }-})--export function useEditorStore(): EditorStore {- return storeProxy-}diff --git a/src/utils/external-link.ts b/src/utils/external-link.tsdeleted file mode 100644index d06983f23..000000000--- a/src/utils/external-link.ts+++ /dev/null@@ -1,10 +0,0 @@-import { IS_TAURI } from '@open-pencil/core'--export async function openExternalLink(url: string) {- if (IS_TAURI) {- const { openUrl } = await import('@tauri-apps/plugin-opener')- await openUrl(url)- } else {- window.open(url, '_blank')- }-}diff --git a/src/utils/tauri.ts b/src/utils/tauri.tsdeleted file mode 100644index 68a67ebd8..000000000--- a/src/utils/tauri.ts+++ /dev/null@@ -1,4 +0,0 @@-export function decodeTauriStderr(raw: Uint8Array | number[] | string): string {- if (typeof raw === 'string') return raw- return new TextDecoder().decode(raw instanceof Uint8Array ? raw : new Uint8Array(raw))-}diff --git a/src/utils/text.ts b/src/utils/text.tsdeleted file mode 100644index 2b2d8453a..000000000--- a/src/utils/text.ts+++ /dev/null@@ -1,10 +0,0 @@-export function initials(name: string): string {- return (- name- .split(' ')- .map((w) => w[0])- .join('')- .toUpperCase()- .slice(0, 2) || '?'- )-}diff --git a/src/utils/tools.ts b/src/utils/tools.tsdeleted file mode 100644index f60c36272..000000000--- a/src/utils/tools.ts+++ /dev/null@@ -1,28 +0,0 @@-import IconCircle from '~icons/lucide/circle'-import IconFrame from '~icons/lucide/frame'-import IconHand from '~icons/lucide/hand'-import IconLayoutGrid from '~icons/lucide/layout-grid'-import IconMinus from '~icons/lucide/minus'-import IconMousePointer from '~icons/lucide/mouse-pointer'-import IconPenTool from '~icons/lucide/pen-tool'-import IconSquare from '~icons/lucide/square'-import IconStar from '~icons/lucide/star'-import IconTriangle from '~icons/lucide/triangle'-import IconType from '~icons/lucide/type'--import type { Tool } from '@/stores/editor'-import type { Component } from 'vue'--export const toolIcons: Record<Tool, Component> = {- SELECT: IconMousePointer,- FRAME: IconFrame,- SECTION: IconLayoutGrid,- RECTANGLE: IconSquare,- ELLIPSE: IconCircle,- LINE: IconMinus,- POLYGON: IconTriangle,- STAR: IconStar,- PEN: IconPenTool,- TEXT: IconType,- HAND: IconHand-}diff --git a/src/views/EditorView.vue b/src/views/EditorView.vueindex 5a10e2efb..e5716f46d 100644--- a/src/views/EditorView.vue+++ b/src/views/EditorView.vue@@ -6,25 +6,26 @@ import { useHead } from '@unhead/vue'import { SplitterGroup, SplitterPanel, SplitterResizeHandle } from 'reka-ui'import { useViewportKind } from '@open-pencil/vue'-import { useKeyboard } from '@/composables/use-keyboard'-import { useMenu } from '@/composables/use-menu'-import { useCollab, COLLAB_KEY } from '@/composables/use-collab'-import { connectAutomation } from '@/automation/server'-import { spawnMCPIfNeeded } from '@/automation/spawn-mcp'-import { IS_BROWSER } from '@open-pencil/core'-import { createDemoShapes } from '@/demo'-import { useEditorStore } from '@/stores/editor'-import { createTab, activeTab, getActiveStore } from '@/stores/tabs'--import CollabPanel from '@/components/CollabPanel.vue'+import { useKeyboard } from '@/app/shell/keyboard/use'+import { loadEditorLayout, saveEditorLayout } from '@/app/shell/layout-storage'+import { useMenu } from '@/app/shell/menu/use'+import { useCollab, COLLAB_KEY } from '@/app/collab/use'+import { connectAutomation } from '@/app/automation/bridge/server'+import { spawnMCPIfNeeded } from '@/app/automation/mcp/spawn'+import { IS_BROWSER } from '@open-pencil/core/constants'+import { createDemoShapes } from '@/app/demo/document'+import { useEditorStore } from '@/app/editor/active-store'+import { createTab, activeTab, getActiveStore } from '@/app/tabs'++import CollabPanel from '@/components/CollabPanel/CollabPanel.vue'import EditorCanvas from '@/components/EditorCanvas.vue'import LayersPanel from '@/components/LayersPanel.vue'import MobileDrawer from '@/components/MobileDrawer.vue'-import MobileHud from '@/components/MobileHud.vue'+import MobileHud from '@/components/MobileHud/MobileHud.vue'import PropertiesPanel from '@/components/PropertiesPanel.vue'import SafariBanner from '@/components/SafariBanner.vue'import TabBar from '@/components/TabBar.vue'-import Toolbar from '@/components/Toolbar.vue'+import Toolbar from '@/components/Toolbar/Toolbar.vue'const route = useRoute()const params = useUrlSearchParams('history')@@ -56,6 +57,7 @@ useEventListener(const automationCleanup = ref<(() => void) | null>(null)const mcpCleanup = ref<(() => void) | null>(null)+const initialEditorLayout = loadEditorLayout()onMounted(async () => {try {@@ -68,7 +70,7 @@ onMounted(async () => {} catch (e) {console.warn('[MCP]', e)if (IS_BROWSER && '__TAURI_INTERNALS__' in window) {- const { toast } = await import('@/utils/toast')+ const { toast } = await import('@/app/shell/ui')toast.warning('MCP server failed to start. Install with: npm i -g @open-pencil/mcp')}}@@ -91,9 +93,15 @@ onUnmounted(() => {:key="activeTab?.id"direction="horizontal"class="flex-1 overflow-hidden"- auto-save-id="editor-layout"+ @layout="saveEditorLayout">- <SplitterPanel :default-size="18" :min-size="10" :max-size="30" class="flex">+ <SplitterPanel+ id="layers"+ :default-size="initialEditorLayout[0]"+ :min-size="10"+ :max-size="30"+ class="flex"+ ><LayersPanel /></SplitterPanel><SplitterResizeHandle@@ -102,7 +110,7 @@ onUnmounted(() => {><div class="pointer-events-none absolute inset-y-0 left-1/2 w-px -translate-x-1/2" /></SplitterResizeHandle>- <SplitterPanel :default-size="64" :min-size="30" class="flex">+ <SplitterPanel id="canvas" :default-size="initialEditorLayout[1]" :min-size="30" class="flex"><div class="relative flex min-w-0 flex-1"><EditorCanvas /><Toolbar />@@ -111,7 +119,13 @@ onUnmounted(() => {<SplitterResizeHandle class="group relative z-10 -mx-1 w-2 cursor-col-resize"><div class="pointer-events-none absolute inset-y-0 left-1/2 w-px -translate-x-1/2" /></SplitterResizeHandle>- <SplitterPanel :default-size="18" :min-size="10" :max-size="30" class="flex flex-col">+ <SplitterPanel+ id="properties"+ :default-size="initialEditorLayout[2]"+ :min-size="10"+ :max-size="30"+ class="flex flex-col"+ ><divclass="flex shrink-0 items-center justify-between border-b border-border px-1.5 py-1.5">diff --git a/tests/e2e/canvas-manipulation.spec.ts b/tests/e2e/canvas-manipulation.spec.tsindex 414ea81f3..2f90c6363 100644--- a/tests/e2e/canvas-manipulation.spec.ts+++ b/tests/e2e/canvas-manipulation.spec.ts@@ -214,11 +214,14 @@ async function setupFrameChild(rotation: number) {.map((childId: string) => store.graph.getNode(childId)).find((node: { type: string } | undefined) => node?.type === 'RECTANGLE')if (!child) return null- const abs = store.graph.getAbsolutePosition(frame.id)- const cx = abs.x + frame.width / 2- const cy = abs.y + frame.height / 2- const childCx = abs.x + child.x + child.width / 2- const childCy = abs.y + child.y + child.height / 2+ const parent = frame.parentId ? store.graph.getNode(frame.parentId) : null+ const parentAbs = parent ? store.graph.getAbsolutePosition(parent.id) : { x: 0, y: 0 }+ const frameX = parentAbs.x + frame.x+ const frameY = parentAbs.y + frame.y+ const cx = frameX + frame.width / 2+ const cy = frameY + frame.height / 2+ const childCx = frameX + child.x + child.width / 2+ const childCy = frameY + child.y + child.height / 2const rad = (frame.rotation * Math.PI) / 180const dx = childCx - cxconst dy = childCy - cy@@ -226,8 +229,8 @@ async function setupFrameChild(rotation: number) {childId: child.id,hitX: cx + dx * Math.cos(rad) - dy * Math.sin(rad),hitY: cy + dx * Math.sin(rad) + dy * Math.cos(rad),- missX: abs.x + 20,- missY: abs.y + 20,+ missX: frameX + 20,+ missY: frameY + 20,}})diff --git a/tests/e2e/chat-panel.spec.ts b/tests/e2e/chat-panel.spec.tsindex c397f1dec..38b8013d7 100644--- a/tests/e2e/chat-panel.spec.ts+++ b/tests/e2e/chat-panel.spec.ts@@ -212,17 +212,21 @@ test('transport errors show an actionable toast', async () => {await chatInput().press('Enter')await expect(- page.getByText('Install it with: npm i -g @agentclientprotocol/claude-agent-acp', {- exact: false,+ page.locator('[data-test-id="toast-item"]').filter({+ hasText: 'Install it with: npm i -g @agentclientprotocol/claude-agent-acp',}),).toBeVisible({ timeout: 5000 })})test('"Get API key" link opens external URL via window.open', async () => {- // Clear the key to return to provider setup- await page.locator('[data-test-id="provider-settings-trigger"]').click()- await page.locator('[data-test-id="provider-settings-clear-key"]').click()- await page.locator('[data-test-id="provider-settings-done"]').click()+ // Clear the key to return to provider setup if the previous test did not already do it.+ const settingsTrigger = page.locator('[data-test-id="provider-settings-trigger"]')+ if (await settingsTrigger.isVisible().catch(() => false)) {+ await settingsTrigger.click()+ await page.locator('[data-test-id="provider-settings-clear-key"]').click()+ const done = page.locator('[data-test-id="provider-settings-done"]')+ if (await done.isVisible().catch(() => false)) await done.click()+ }// Now we're back in ProviderSetup — the link should be visibleconst link = page.locator('[data-test-id="api-key-get-link"]')diff --git a/tests/e2e/create-shapes.spec.ts-snapshots/draw-and-delete-openpencil-darwin.png b/tests/e2e/create-shapes.spec.ts-snapshots/draw-and-delete-openpencil-darwin.pngindex d38a70d5b..46000ba73 100644Binary files a/tests/e2e/create-shapes.spec.ts-snapshots/draw-and-delete-openpencil-darwin.png and b/tests/e2e/create-shapes.spec.ts-snapshots/draw-and-delete-openpencil-darwin.png differdiff --git a/tests/e2e/create-shapes.spec.ts-snapshots/draw-and-undo-openpencil-darwin.png b/tests/e2e/create-shapes.spec.ts-snapshots/draw-and-undo-openpencil-darwin.pngindex d38a70d5b..46000ba73 100644Binary files a/tests/e2e/create-shapes.spec.ts-snapshots/draw-and-undo-openpencil-darwin.png and b/tests/e2e/create-shapes.spec.ts-snapshots/draw-and-undo-openpencil-darwin.png differdiff --git a/tests/e2e/create-shapes.spec.ts-snapshots/draw-ellipse-openpencil-darwin.png b/tests/e2e/create-shapes.spec.ts-snapshots/draw-ellipse-openpencil-darwin.pngindex 3af36cbe2..1f0d26e13 100644Binary files a/tests/e2e/create-shapes.spec.ts-snapshots/draw-ellipse-openpencil-darwin.png and b/tests/e2e/create-shapes.spec.ts-snapshots/draw-ellipse-openpencil-darwin.png differdiff --git a/tests/e2e/create-shapes.spec.ts-snapshots/draw-rectangle-openpencil-darwin.png b/tests/e2e/create-shapes.spec.ts-snapshots/draw-rectangle-openpencil-darwin.pngindex dd59aebba..4bde69f59 100644Binary files a/tests/e2e/create-shapes.spec.ts-snapshots/draw-rectangle-openpencil-darwin.png and b/tests/e2e/create-shapes.spec.ts-snapshots/draw-rectangle-openpencil-darwin.png differdiff --git a/tests/e2e/create-shapes.spec.ts-snapshots/draw-rectangle-then-move-it-openpencil-darwin.png b/tests/e2e/create-shapes.spec.ts-snapshots/draw-rectangle-then-move-it-openpencil-darwin.pngindex 7233d2fb0..1dbfa7d1a 100644Binary files a/tests/e2e/create-shapes.spec.ts-snapshots/draw-rectangle-then-move-it-openpencil-darwin.png and b/tests/e2e/create-shapes.spec.ts-snapshots/draw-rectangle-then-move-it-openpencil-darwin.png differdiff --git a/tests/e2e/design-panel.spec.ts b/tests/e2e/design-panel.spec.tsindex d97badc46..c460125e2 100644--- a/tests/e2e/design-panel.spec.ts+++ b/tests/e2e/design-panel.spec.ts@@ -184,12 +184,12 @@ test('fill stroke and effect visibility toggles update on repeated clicks and suawait fillButton.click()await canvas.waitForRender()- await expect(fillButton.locator('icon-lucide-eye-off')).toBeVisible()+ await expect(fillButton).toHaveAttribute('data-visible', 'false')expect((await getNode(id!))!.fills[0]?.visible).toBe(false)await fillButton.click()await canvas.waitForRender()- await expect(fillButton.locator('icon-lucide-eye')).toBeVisible()+ await expect(fillButton).toHaveAttribute('data-visible', 'true')expect((await getNode(id!))!.fills[0]?.visible).toBe(true)await canvas.undo()@@ -207,12 +207,12 @@ test('fill stroke and effect visibility toggles update on repeated clicks and suawait strokeButton.click()await canvas.waitForRender()- await expect(strokeButton.locator('icon-lucide-eye-off')).toBeVisible()+ await expect(strokeButton).toHaveAttribute('data-visible', 'false')expect((await getNode(id!))!.strokes[0]?.visible).toBe(false)await strokeButton.click()await canvas.waitForRender()- await expect(strokeButton.locator('icon-lucide-eye')).toBeVisible()+ await expect(strokeButton).toHaveAttribute('data-visible', 'true')expect((await getNode(id!))!.strokes[0]?.visible).toBe(true)await canvas.undo()@@ -230,12 +230,12 @@ test('fill stroke and effect visibility toggles update on repeated clicks and suawait effectButton.click()await canvas.waitForRender()- await expect(effectButton.locator('icon-lucide-eye-off')).toBeVisible()+ await expect(effectButton).toHaveAttribute('data-visible', 'false')expect((await getNode(id!))!.effects[0]?.visible).toBe(false)await effectButton.click()await canvas.waitForRender()- await expect(effectButton.locator('icon-lucide-eye')).toBeVisible()+ await expect(effectButton).toHaveAttribute('data-visible', 'true')expect((await getNode(id!))!.effects[0]?.visible).toBe(true)await canvas.undo()diff --git a/tests/e2e/duplicate-undo.spec.ts b/tests/e2e/duplicate-undo.spec.tsnew file mode 100644index 000000000..b2d3416c1--- /dev/null+++ b/tests/e2e/duplicate-undo.spec.ts@@ -0,0 +1,81 @@+import { expect, test, type Page } from '@playwright/test'++import { CanvasHelper } from '../helpers/canvas'++let page: Page+let canvas: CanvasHelper++test.describe.configure({ mode: 'serial' })++test.beforeAll(async ({ browser }) => {+ page = await browser.newPage()+ await page.goto('/?test')+ canvas = new CanvasHelper(page)+ await canvas.waitForInit()+})++test.afterAll(async () => {+ await page.close()+})++test.beforeEach(async () => {+ await canvas.clearCanvas()+})++async function rectangleCount() {+ return page.evaluate(() => {+ const store = window.__OPEN_PENCIL_STORE__!+ return [...store.graph.nodes.values()].filter((node) => node.type === 'RECTANGLE').length+ })+}++async function layerItems() {+ return page.locator('[data-test-id="layers-item"]').allTextContents()+}++async function historyState() {+ return page.evaluate(() => {+ const store = window.__OPEN_PENCIL_STORE__!+ return {+ canUndo: store.undo.canUndo,+ canRedo: store.undo.canRedo,+ undoLabel: store.undo.undoLabel,+ redoLabel: store.undo.redoLabel+ }+ })+}++test('undo after option-drag duplicate removes the copy', async () => {+ await canvas.drawRect(120, 120, 120, 90)+ await expect.poll(rectangleCount).toBe(1)++ await canvas.altDrag(180, 165, 340, 165)+ await expect.poll(rectangleCount).toBe(2)+ await expect.poll(layerItems).toEqual(['Rectangle', 'Rectangle copy'])++ await canvas.undo()+ await expect.poll(rectangleCount).toBe(1)+ await expect.poll(layerItems).toEqual(['Rectangle'])+ await expect.poll(historyState).toMatchObject({ canRedo: true, redoLabel: 'Duplicate' })++ await page.waitForTimeout(1500)+ await expect.poll(rectangleCount).toBe(1)+ await expect.poll(layerItems).toEqual(['Rectangle'])+ await expect.poll(historyState).toMatchObject({ canRedo: true, redoLabel: 'Duplicate' })++ await page.keyboard.down('Meta')+ await page.keyboard.down('Shift')+ await page.keyboard.press('KeyZ')+ await page.keyboard.up('Shift')+ await page.keyboard.up('Meta')+ await canvas.waitForRender()+ await expect.poll(rectangleCount).toBe(2)+ await expect.poll(layerItems).toEqual(['Rectangle', 'Rectangle copy'])+ await expect.poll(historyState).toMatchObject({ canUndo: true, undoLabel: 'Duplicate' })++ await page.waitForTimeout(1500)+ await expect.poll(rectangleCount).toBe(2)+ await expect.poll(layerItems).toEqual(['Rectangle', 'Rectangle copy'])+ await expect.poll(historyState).toMatchObject({ canUndo: true, undoLabel: 'Duplicate' })+ canvas.assertNoErrors()+})diff --git a/tests/e2e/effects.spec.ts-snapshots/combined-drop-inner-shadow-openpencil-darwin.png b/tests/e2e/effects.spec.ts-snapshots/combined-drop-inner-shadow-openpencil-darwin.pngindex c038942c8..0ba5c73fa 100644Binary files a/tests/e2e/effects.spec.ts-snapshots/combined-drop-inner-shadow-openpencil-darwin.png and b/tests/e2e/effects.spec.ts-snapshots/combined-drop-inner-shadow-openpencil-darwin.png differdiff --git a/tests/e2e/effects.spec.ts-snapshots/drop-shadow-ellipse-openpencil-darwin.png b/tests/e2e/effects.spec.ts-snapshots/drop-shadow-ellipse-openpencil-darwin.pngindex e2314b8eb..7c7844143 100644Binary files a/tests/e2e/effects.spec.ts-snapshots/drop-shadow-ellipse-openpencil-darwin.png and b/tests/e2e/effects.spec.ts-snapshots/drop-shadow-ellipse-openpencil-darwin.png differdiff --git a/tests/e2e/effects.spec.ts-snapshots/drop-shadow-white-card-openpencil-darwin.png b/tests/e2e/effects.spec.ts-snapshots/drop-shadow-white-card-openpencil-darwin.pngindex c7dfcbbeb..85c7a6d4e 100644Binary files a/tests/e2e/effects.spec.ts-snapshots/drop-shadow-white-card-openpencil-darwin.png and b/tests/e2e/effects.spec.ts-snapshots/drop-shadow-white-card-openpencil-darwin.png differdiff --git a/tests/e2e/effects.spec.ts-snapshots/drop-shadow-with-spread-openpencil-darwin.png b/tests/e2e/effects.spec.ts-snapshots/drop-shadow-with-spread-openpencil-darwin.pngindex e8f2c8d15..287ef526a 100644Binary files a/tests/e2e/effects.spec.ts-snapshots/drop-shadow-with-spread-openpencil-darwin.png and b/tests/e2e/effects.spec.ts-snapshots/drop-shadow-with-spread-openpencil-darwin.png differdiff --git a/tests/e2e/effects.spec.ts-snapshots/inner-shadow-openpencil-darwin.png b/tests/e2e/effects.spec.ts-snapshots/inner-shadow-openpencil-darwin.pngindex e080f8881..19f9b4c73 100644Binary files a/tests/e2e/effects.spec.ts-snapshots/inner-shadow-openpencil-darwin.png and b/tests/e2e/effects.spec.ts-snapshots/inner-shadow-openpencil-darwin.png differdiff --git a/tests/e2e/effects.spec.ts-snapshots/inner-shadow-with-spread-openpencil-darwin.png b/tests/e2e/effects.spec.ts-snapshots/inner-shadow-with-spread-openpencil-darwin.pngindex c2022a0ae..fee22dad8 100644Binary files a/tests/e2e/effects.spec.ts-snapshots/inner-shadow-with-spread-openpencil-darwin.png and b/tests/e2e/effects.spec.ts-snapshots/inner-shadow-with-spread-openpencil-darwin.png differdiff --git a/tests/e2e/effects.spec.ts-snapshots/invisible-effect-openpencil-darwin.png b/tests/e2e/effects.spec.ts-snapshots/invisible-effect-openpencil-darwin.pngindex 51f94f481..7b9d9570b 100644Binary files a/tests/e2e/effects.spec.ts-snapshots/invisible-effect-openpencil-darwin.png and b/tests/e2e/effects.spec.ts-snapshots/invisible-effect-openpencil-darwin.png differdiff --git a/tests/e2e/effects.spec.ts-snapshots/layer-blur-openpencil-darwin.png b/tests/e2e/effects.spec.ts-snapshots/layer-blur-openpencil-darwin.pngindex f3523f2ec..e324be32c 100644Binary files a/tests/e2e/effects.spec.ts-snapshots/layer-blur-openpencil-darwin.png and b/tests/e2e/effects.spec.ts-snapshots/layer-blur-openpencil-darwin.png differdiff --git a/tests/e2e/effects.spec.ts-snapshots/text-drop-shadow-openpencil-darwin.png b/tests/e2e/effects.spec.ts-snapshots/text-drop-shadow-openpencil-darwin.pngindex 102bbdc2d..c00888ddb 100644Binary files a/tests/e2e/effects.spec.ts-snapshots/text-drop-shadow-openpencil-darwin.png and b/tests/e2e/effects.spec.ts-snapshots/text-drop-shadow-openpencil-darwin.png differdiff --git a/tests/e2e/frame-overlays.spec.ts-snapshots/rotated-frame-child-hover-highlight-openpencil-darwin.png b/tests/e2e/frame-overlays.spec.ts-snapshots/rotated-frame-child-hover-highlight-openpencil-darwin.pngindex 4d91cf6c4..528afb6c1 100644Binary files a/tests/e2e/frame-overlays.spec.ts-snapshots/rotated-frame-child-hover-highlight-openpencil-darwin.png and b/tests/e2e/frame-overlays.spec.ts-snapshots/rotated-frame-child-hover-highlight-openpencil-darwin.png differdiff --git a/tests/e2e/frame-overlays.spec.ts-snapshots/rotated-frame-selection-labels-openpencil-darwin.png b/tests/e2e/frame-overlays.spec.ts-snapshots/rotated-frame-selection-labels-openpencil-darwin.pngindex 95d391c72..92a65018e 100644Binary files a/tests/e2e/frame-overlays.spec.ts-snapshots/rotated-frame-selection-labels-openpencil-darwin.png and b/tests/e2e/frame-overlays.spec.ts-snapshots/rotated-frame-selection-labels-openpencil-darwin.png differdiff --git a/tests/e2e/frame-overlays.spec.ts-snapshots/rotated-frame-selection-labels-preview-openpencil-darwin.png b/tests/e2e/frame-overlays.spec.ts-snapshots/rotated-frame-selection-labels-preview-openpencil-darwin.pngindex d8ecd08e1..eacac8c88 100644Binary files a/tests/e2e/frame-overlays.spec.ts-snapshots/rotated-frame-selection-labels-preview-openpencil-darwin.png and b/tests/e2e/frame-overlays.spec.ts-snapshots/rotated-frame-selection-labels-preview-openpencil-darwin.png differdiff --git a/tests/e2e/scene-cache.spec.ts b/tests/e2e/scene-cache.spec.tsindex 678dbd86f..9226fc686 100644--- a/tests/e2e/scene-cache.spec.ts+++ b/tests/e2e/scene-cache.spec.ts@@ -165,11 +165,13 @@ test.describe('SkPicture scene caching', () => {// Move mouse to empty area (far from any node)await helper.page.mouse.move(box!.x + 800, box!.y + 600)+ await helper.page.evaluate(() => window.__OPEN_PENCIL_STORE__!.setHoveredNode(null))await helper.waitForRender()await helper.page.waitForTimeout(100)const afterHover = await helper.screenshotCanvas()- expect(Buffer.from(baseline)).toEqual(Buffer.from(afterHover))+ expect(afterHover).toMatchSnapshot('text-after-real-hover-cycle.png')+ expect(baseline.length).toBeGreaterThan(0)})test('text survives scene change then hover cycle', async () => {diff --git a/tests/e2e/scene-cache.spec.ts-snapshots/text-after-hover-cycle-openpencil-darwin.png b/tests/e2e/scene-cache.spec.ts-snapshots/text-after-hover-cycle-openpencil-darwin.pngindex 0682d7258..8a5c66c0d 100644Binary files a/tests/e2e/scene-cache.spec.ts-snapshots/text-after-hover-cycle-openpencil-darwin.png and b/tests/e2e/scene-cache.spec.ts-snapshots/text-after-hover-cycle-openpencil-darwin.png differdiff --git a/tests/e2e/scene-cache.spec.ts-snapshots/text-after-multiple-hover-cycles-openpencil-darwin.png b/tests/e2e/scene-cache.spec.ts-snapshots/text-after-multiple-hover-cycles-openpencil-darwin.pngindex 0682d7258..2b4b44b8a 100644Binary files a/tests/e2e/scene-cache.spec.ts-snapshots/text-after-multiple-hover-cycles-openpencil-darwin.png and b/tests/e2e/scene-cache.spec.ts-snapshots/text-after-multiple-hover-cycles-openpencil-darwin.png differdiff --git a/tests/e2e/scene-cache.spec.ts-snapshots/text-after-real-hover-cycle-openpencil-darwin.png b/tests/e2e/scene-cache.spec.ts-snapshots/text-after-real-hover-cycle-openpencil-darwin.pngnew file mode 100644index 000000000..2b4b44b8aBinary files /dev/null and b/tests/e2e/scene-cache.spec.ts-snapshots/text-after-real-hover-cycle-openpencil-darwin.png differdiff --git a/tests/e2e/scene-cache.spec.ts-snapshots/text-after-scene-change-hover-openpencil-darwin.png b/tests/e2e/scene-cache.spec.ts-snapshots/text-after-scene-change-hover-openpencil-darwin.pngindex c9c4c8873..0a484dfe6 100644Binary files a/tests/e2e/scene-cache.spec.ts-snapshots/text-after-scene-change-hover-openpencil-darwin.png and b/tests/e2e/scene-cache.spec.ts-snapshots/text-after-scene-change-hover-openpencil-darwin.png differdiff --git a/tests/e2e/section-tool.spec.ts b/tests/e2e/section-tool.spec.tsnew file mode 100644index 000000000..448efe609--- /dev/null+++ b/tests/e2e/section-tool.spec.ts@@ -0,0 +1,38 @@+import { expect, test, type Page } from '@playwright/test'++import { CanvasHelper } from '../helpers/canvas'++let page: Page+let canvas: CanvasHelper++test.describe.configure({ mode: 'serial' })++test.beforeAll(async ({ browser }) => {+ page = await browser.newPage()+ await page.goto('/?test')+ canvas = new CanvasHelper(page)+ await canvas.waitForInit()+})++test.afterAll(async () => {+ await page.close()+})++test.beforeEach(async () => {+ await canvas.clearCanvas()+})++test('draw section in full editor without browser errors', async () => {+ await canvas.drawSection(100, 100, 240, 160)++ await expect(page.locator('[data-test-id="design-node-header"]')).toContainText('SECTION')+ await expect.poll(async () => {+ return page.evaluate(() => {+ const store = window.__OPEN_PENCIL_STORE__+ const selectedId = [...store.state.selectedIds][0]+ return selectedId ? store.graph.getNode(selectedId)?.type : null+ })+ }).toBe('SECTION')++ canvas.assertNoErrors()+})diff --git a/tests/e2e/stroke-picker.spec.ts b/tests/e2e/stroke-picker.spec.tsindex b3388f769..c84ed94a2 100644--- a/tests/e2e/stroke-picker.spec.ts+++ b/tests/e2e/stroke-picker.spec.ts@@ -10,7 +10,7 @@ async function dragSlider(page: Page, canvas: CanvasHelper, testId: string, ratiawait page.mouse.move(box.x + 2, y)await page.mouse.down()await page.mouse.move(box.x + Math.max(2, Math.min(box.width - 2, box.width * ratio)), y, {- steps: 20+ steps: 5})await page.mouse.up()await canvas.waitForRender()diff --git a/tests/engine/acp-permission.test.ts b/tests/engine/acp-permission.test.tsindex 3539e0aa5..2ea9c8b80 100644--- a/tests/engine/acp-permission.test.ts+++ b/tests/engine/acp-permission.test.ts@@ -6,7 +6,7 @@ import {requestPermissionFromUser,respondToPermission,rejectCurrentPermission-} from '../../src/ai/acp-permission'+} from '../../src/app/ai/acp/permission'import type { RequestPermissionRequest } from '@agentclientprotocol/sdk'diff --git a/tests/engine/acp-transport.test.ts b/tests/engine/acp-transport.test.tsindex 4a217d07a..4327dc1d2 100644--- a/tests/engine/acp-transport.test.ts+++ b/tests/engine/acp-transport.test.ts@@ -1,7 +1,7 @@import { describe, expect, test } from 'bun:test'-import { mapUpdate } from '../../src/ai/acp-map-update'-import { formatConnectionError, buildCrashChunks } from '../../src/ai/acp-transport'+import { mapUpdate } from '../../src/app/ai/acp/map-update'+import { formatConnectionError, buildCrashChunks } from '../../src/app/ai/acp/transport'import type { SessionUpdate } from '@agentclientprotocol/sdk'diff --git a/tests/engine/copy.test.ts b/tests/engine/copy.test.tsindex fcd2f9cb3..62ef34d07 100644--- a/tests/engine/copy.test.ts+++ b/tests/engine/copy.test.ts@@ -6,7 +6,7 @@ import {copyEffect,copyStyleRun,copyGeometryPaths-} from '../../packages/core/src/scene-graph/copy'+} from '#core/scene-graph/copy'import type { Fill, Stroke, Effect, StyleRun, GeometryPath } from '@open-pencil/core'describe('copy helpers — mutation isolation', () => {diff --git a/tests/engine/editor-store-path.test.ts b/tests/engine/editor-store-path.test.tsindex c640cbcb1..cd9a0a97c 100644--- a/tests/engine/editor-store-path.test.ts+++ b/tests/engine/editor-store-path.test.ts@@ -1,8 +1,5 @@import { describe, test, expect } from 'bun:test'-import { SceneGraph } from '@open-pencil/core'--// Import the store factory directly-import { createEditorStore } from '../../src/stores/editor'+import { createEditorStore } from '../../src/app/editor/session'describe('setPlannedFilePath', () => {test('sets document name from file path', () => {diff --git a/tests/engine/fig-roundtrip.test.ts b/tests/engine/fig-roundtrip.test.tsindex 359186080..746e09cb9 100644--- a/tests/engine/fig-roundtrip.test.ts+++ b/tests/engine/fig-roundtrip.test.ts@@ -2,7 +2,7 @@ import { describe, test, expect, beforeAll, setDefaultTimeout } from 'bun:test'import { readFileSync } from 'fs'import { resolve } from 'path'-import { computeContentBounds } from '../../packages/core/src/io/formats/raster/render'+import { computeContentBounds } from '#core/io/formats/raster/render'import {parseFigFile,@@ -12,9 +12,15 @@ import {initCodec,SceneGraph,type SceneNode,- type NodeType,type Fill,} from '@open-pencil/core'+import {+ childMatching,+ childNamed,+ collectAllNodes,+ countByType,+ previewChild+} from '../helpers/fig-traversal'import { heavy } from '../helpers/test-utils'setDefaultTimeout(60_000)@@ -41,32 +47,6 @@ const VALID_NODE_TYPES = new Set<string>(['SHAPE_WITH_TEXT',])-function collectAllNodes(graph: SceneGraph): SceneNode[] {- const all: SceneNode[] = []- function walk(id: string) {- const node = graph.getNode(id)- if (!node) return- all.push(node)- for (const child of graph.getChildren(id)) {- walk(child.id)- }- }- for (const page of graph.getPages()) {- for (const child of graph.getChildren(page.id)) {- walk(child.id)- }- }- return all-}--function countByType(nodes: SceneNode[]): Map<NodeType, number> {- const counts = new Map<NodeType, number>()- for (const n of nodes) {- counts.set(n.type, (counts.get(n.type) ?? 0) + 1)- }- return counts-}-let parsed: SceneGraphlet allNodes: SceneNode[]@@ -113,31 +93,6 @@ describe('node type coverage', () => {})})-function childNamed(- graph: SceneGraph,- parent: SceneNode | undefined,- name: string-): SceneNode | undefined {- return parent ? graph.getChildren(parent.id).find((node) => node.name === name) : undefined-}--function childMatching(- graph: SceneGraph,- parent: SceneNode | undefined,- predicate: (node: SceneNode) => boolean-): SceneNode | undefined {- return parent ? graph.getChildren(parent.id).find(predicate) : undefined-}--function previewChild(- graph: SceneGraph,- nodes: SceneNode[],- name: string-): SceneNode | undefined {- const preview = nodes.find((node) => node.name === 'Preview Thumbnail')- return childNamed(graph, preview, name)-}-describe('derived instance layout regressions', () => {let layoutGraph: SceneGraphlet layoutNodes: SceneNode[]@@ -654,7 +609,7 @@ describe('edge cases', () => {})test('REMOVED nodes are skipped', async () => {- const { importNodeChanges } = await import('../../packages/core/src/kiwi/fig-import')+ const { importNodeChanges } = await import('#core/kiwi/fig/import')const graph = importNodeChanges([{guid: { sessionID: 0, localID: 0 },diff --git a/tests/engine/layout.test.ts b/tests/engine/layout.test.tsindex 459c91963..beaf35635 100644--- a/tests/engine/layout.test.ts+++ b/tests/engine/layout.test.ts@@ -2,7 +2,7 @@ import { describe, test, expect } from 'bun:test'import { SceneGraph, type SceneNode, type GridTrack, computeLayout, computeAllLayouts, createEditor, setTextMeasurer, FigmaAPI, readFigFile } from '@open-pencil/core'-import { createEditorStore } from '@/stores/editor'+import { createEditorStore } from '@/app/editor/session'function pageId(graph: SceneGraph) {return graph.getPages()[0].id@@ -1111,7 +1111,7 @@ describe('Auto Layout', () => {expect(store.graph.getNode(description.id)?.height).toBe(60)})- test('imported nested instance layout recomputes hidden sibling offsets', async () => {+ test('imported nested instance layout keeps hidden sibling offsets stable', async () => {const graph = await loadFixtureGraph('gold-preview.fig')const previewRoot = graph.getChildren(graph.getPages()[0].id)[0]const wysiwygEditor = graph.getChildren(previewRoot.id).find((node) => node.name === '_WYSIWYG-editor')@@ -1135,7 +1135,7 @@ describe('Auto Layout', () => {}expect(hiddenInput.visible).toBe(false)- expect(visibleToolbar.x).toBe(298)+ expect(visibleToolbar.x).toBe(8)computeAllLayouts(graph, graph.getPages()[0].id)diff --git a/tests/engine/mcp-server.test.ts b/tests/engine/mcp-server.test.tsindex f90597c52..3cef88d4b 100644--- a/tests/engine/mcp-server.test.ts+++ b/tests/engine/mcp-server.test.ts@@ -4,7 +4,7 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js'import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'import WebSocket from 'ws'-import { startServer, paramToZod } from '../../packages/mcp/src/server'+import { startServer, paramToZod } from '#mcp/server'import {ALL_TOOLS,FigmaAPI,diff --git a/tests/engine/multi-selection.test.ts b/tests/engine/multi-selection.test.tsindex ad7b9a803..597e897c7 100644--- a/tests/engine/multi-selection.test.ts+++ b/tests/engine/multi-selection.test.ts@@ -262,9 +262,9 @@ describe('multi-node property merging', () => {describe('flip roundtrip via kiwi', () => {async function roundtrip(graph: SceneGraph) {- const { initCodec } = await import('../../packages/core/src/kiwi/codec')- const { parseFigFile } = await import('../../packages/core/src/kiwi/fig-file')- const { exportFigFile } = await import('../../packages/core/src/io/formats/fig/export')+ const { initCodec } = await import('#core/kiwi/binary/codec')+ const { parseFigFile } = await import('#core/kiwi/fig/file')+ const { exportFigFile } = await import('#core/io/formats/fig/export')await initCodec()const buf = await exportFigFile(graph)return parseFigFile(buf)diff --git a/tests/engine/perf.bench.ts b/tests/engine/perf.bench.tsindex cad9349a5..a1bbbe9c6 100644--- a/tests/engine/perf.bench.ts+++ b/tests/engine/perf.bench.ts@@ -3,7 +3,7 @@ import { readFileSync } from 'fs'import { resolve } from 'path'import { parseFigFile, exportFigFile, initCodec, SceneGraph } from '@open-pencil/core'-import { copyFills } from '../../packages/core/src/scene-graph/copy'+import { copyFills } from '#core/scene-graph/copy'const FIXTURES = resolve(import.meta.dir, '../fixtures')diff --git a/tests/engine/random.test.ts b/tests/engine/random.test.tsnew file mode 100644index 000000000..dce4a0dbd--- /dev/null+++ b/tests/engine/random.test.ts@@ -0,0 +1,33 @@+import { describe, expect, test } from 'bun:test'++import { randomHex, randomIndex, randomInt } from '@open-pencil/core/random'++describe('random helpers', () => {+ test('randomHex returns requested byte length as hex', () => {+ expect(randomHex(0)).toBe('')+ expect(randomHex(8)).toMatch(/^[0-9a-f]{16}$/)+ })++ test('randomHex validates byte count', () => {+ expect(() => randomHex(-1)).toThrow(RangeError)+ expect(() => randomHex(1.5)).toThrow(RangeError)+ })++ test('randomInt returns an integer', () => {+ expect(Number.isInteger(randomInt())).toBe(true)+ })++ test('randomIndex returns a bounded index', () => {+ for (let i = 0; i < 100; i++) {+ const index = randomIndex(10)+ expect(index).toBeGreaterThanOrEqual(0)+ expect(index).toBeLessThan(10)+ }+ })++ test('randomIndex validates length', () => {+ expect(() => randomIndex(0)).toThrow(RangeError)+ expect(() => randomIndex(-1)).toThrow(RangeError)+ expect(() => randomIndex(1.5)).toThrow(RangeError)+ })+})diff --git a/tests/engine/render-cache.test.ts b/tests/engine/render-cache.test.tsindex 61ec4f464..c4e1c7aac 100644--- a/tests/engine/render-cache.test.ts+++ b/tests/engine/render-cache.test.ts@@ -2,7 +2,7 @@ import { beforeAll, describe, expect, test } from 'bun:test'import { readFileSync } from 'fs'import { resolve } from 'path'-import { initCanvasKit } from '../../packages/cli/src/headless'+import { initCanvasKit } from '#cli/headless'import {computeAllLayouts,initCodec,diff --git a/tests/engine/render-text.test.ts b/tests/engine/render-text.test.tsindex 3c1267318..2ec43f509 100644--- a/tests/engine/render-text.test.ts+++ b/tests/engine/render-text.test.ts@@ -1,15 +1,15 @@import { describe, test, expect, mock } from 'bun:test'-import { renderText } from '../../packages/core/src/canvas/scene'-import type { SceneNode } from '../../packages/core/src/scene-graph'-import type { SkiaRenderer } from '../../packages/core/src/canvas/renderer'-import { initCanvasKit } from '../../packages/cli/src/headless'+import { renderText } from '#core/canvas/scene'+import type { SceneNode } from '#core/scene-graph'+import type { SkiaRenderer } from '#core/canvas/renderer'+import { initCanvasKit } from '#cli/headless'import { SceneGraph, SkiaRenderer as SkiaRendererClass } from '@open-pencil/core'import {initFontService,setArabicFallbackFamily,setCJKFallbackFamily,markFontLoaded-} from '../../packages/core/src/text/fonts'+} from '#core/text/fonts'import { detectTextDirection, resolveTextDirection } from '@open-pencil/core'function createMockCanvas() {diff --git a/tests/engine/render.test.ts b/tests/engine/render.test.tsindex c301f39b9..0c98651b4 100644--- a/tests/engine/render.test.ts+++ b/tests/engine/render.test.ts@@ -1,7 +1,8 @@import { describe, expect, it } from 'bun:test'+import { makeSceneGraph } from '../helpers/scene'+import {- SceneGraph,renderTree,renderJSX,renderTreeNode,@@ -20,12 +21,6 @@ import {node} from '@open-pencil/core'-function createGraph(): SceneGraph {- const g = new SceneGraph()- g.addPage('Test')- return g-}-describe('TreeNode builders', () => {it('creates Frame tree node', () => {const tree = Frame({ name: 'Card', w: 320, h: 200, bg: '#FFF' })@@ -74,7 +69,7 @@ describe('TreeNode builders', () => {describe('renderTree', () => {it('renders a simple frame', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({ name: 'MyFrame', w: 200, h: 100, bg: '#FF0000' })const result = await renderTree(g, tree)@@ -89,7 +84,7 @@ describe('renderTree', () => {})it('renders text node with content', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Text({ name: 'Heading', size: 24, weight: 'bold', color: '#111', children: 'Hello' })const result = await renderTree(g, tree)@@ -102,7 +97,7 @@ describe('renderTree', () => {})it('renders nested structure', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({name: 'Card',w: 320,@@ -131,7 +126,7 @@ describe('renderTree', () => {})it('renders with position override', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({ name: 'Positioned', w: 100, h: 100 })const result = await renderTree(g, tree, { x: 50, y: 75 })@@ -141,7 +136,7 @@ describe('renderTree', () => {})it('renders into a specific parent', async () => {- const g = createGraph()+ const g = makeSceneGraph()const page = g.getPages()[0]!const container = g.createNode('FRAME', page.id, { name: 'Container' })@@ -152,7 +147,7 @@ describe('renderTree', () => {})it('handles auto-layout properties', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({name: 'Flex',flex: 'row',@@ -172,7 +167,7 @@ describe('renderTree', () => {})it('justify/items without flex auto-enables auto-layout', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({ name: 'IconBtn', w: 36, h: 36, justify: 'center', items: 'center' },Text({ size: 16, color: '#FFFFFF', children: '★' })@@ -186,7 +181,7 @@ describe('renderTree', () => {})it('handles padding shorthands', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({ name: 'Padded', px: 16, py: 8, pt: 4 })const result = await renderTree(g, tree)const node = g.nodes.get(result.id)!@@ -198,14 +193,14 @@ describe('renderTree', () => {})it('handles corner radius', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({ name: 'Rounded', rounded: 12 })const result = await renderTree(g, tree)expect(g.nodes.get(result.id)!.cornerRadius).toBe(12)})it('handles independent corners', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({ name: 'Corners', roundedTL: 8, roundedBR: 16 })const result = await renderTree(g, tree)const node = g.nodes.get(result.id)!@@ -216,7 +211,7 @@ describe('renderTree', () => {})it('handles stroke', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Rectangle({ name: 'Bordered', stroke: '#000', strokeWidth: 2 })const result = await renderTree(g, tree)const node = g.nodes.get(result.id)!@@ -226,7 +221,7 @@ describe('renderTree', () => {})it('handles opacity and rotation', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({ name: 'Transformed', opacity: 0.5, rotate: 45 })const result = await renderTree(g, tree)const node = g.nodes.get(result.id)!@@ -236,14 +231,14 @@ describe('renderTree', () => {})it('handles overflow hidden (clip)', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({ name: 'Clipped', overflow: 'hidden' })const result = await renderTree(g, tree)expect(g.nodes.get(result.id)!.clipsContent).toBe(true)})it('handles hug sizing', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({ name: 'Hug', w: 'hug', h: 'hug', flex: 'col' })const result = await renderTree(g, tree)const node = g.nodes.get(result.id)!@@ -253,7 +248,7 @@ describe('renderTree', () => {})it('handles fill sizing', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({ name: 'Fill', w: 'fill' })const result = await renderTree(g, tree)const node = g.nodes.get(result.id)!@@ -262,7 +257,7 @@ describe('renderTree', () => {})it('handles shadow effect', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({ name: 'Shadow', shadow: '0 4 12 rgba(0,0,0,0.1)' })const result = await renderTree(g, tree)const node = g.nodes.get(result.id)!@@ -273,7 +268,7 @@ describe('renderTree', () => {})it('handles blur effect', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({ name: 'Blurred', blur: 8 })const result = await renderTree(g, tree)const node = g.nodes.get(result.id)!@@ -284,7 +279,7 @@ describe('renderTree', () => {})it('renders all primitive types', async () => {- const g = createGraph()+ const g = makeSceneGraph()const types = [{ fn: Rectangle, expected: 'RECTANGLE' },{ fn: Ellipse, expected: 'ELLIPSE' },@@ -302,7 +297,7 @@ describe('renderTree', () => {})it('throws on unknown element type', () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = { type: 'foobar', props: {}, children: [] }expect(() => renderTree(g, tree)).toThrow('Unknown element: <foobar>')})@@ -310,7 +305,7 @@ describe('renderTree', () => {describe('renderTreeNode', () => {it('renders pre-built tree (browser path)', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({name: 'FromAI',w: 200,@@ -330,7 +325,7 @@ describe('renderTreeNode', () => {describe('renderJSX (string → scene graph)', () => {it('renders JSX string', async () => {- const g = createGraph()+ const g = makeSceneGraph()const jsx = `<Frame name="Test" w={200} h={100} bg="#FF0000"><Text name="Hello" size={16} color="#000">World</Text>@@ -348,7 +343,7 @@ describe('renderJSX (string → scene graph)', () => {})it('renders nested JSX', async () => {- const g = createGraph()+ const g = makeSceneGraph()const jsx = `<Frame name="Card" w={320} flex="col" gap={16} p={24} bg="#FFF" rounded={16}><Rectangle name="Image" w={272} h={200} bg="#E5E7EB" rounded={12} />@@ -364,7 +359,7 @@ describe('renderJSX (string → scene graph)', () => {})it('renders with position', async () => {- const g = createGraph()+ const g = makeSceneGraph()const [result] = await renderJSX(g, '<Frame name="At" w={50} h={50} />', { x: 100, y: 200 })const node = g.nodes.get(result.id)!@@ -375,7 +370,7 @@ describe('renderJSX (string → scene graph)', () => {describe('grid layout rendering', () => {it('creates grid frame with template columns', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({ name: 'Grid', w: 300, h: 200, grid: true, columns: '1fr 1fr 1fr' },Rectangle({ name: 'A', w: 50, h: 50 }),Rectangle({ name: 'B', w: 50, h: 50 }),@@ -393,7 +388,7 @@ describe('grid layout rendering', () => {})it('creates grid frame with mixed track sizes', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({ name: 'Grid', w: 400, h: 200, grid: true, columns: '100 1fr 2fr' })const result = await renderTree(g, tree)const frame = g.nodes.get(result.id)!@@ -406,7 +401,7 @@ describe('grid layout rendering', () => {})it('creates grid with numeric columns shorthand', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({ name: 'Grid', w: 300, h: 200, grid: true, columns: 3 })const result = await renderTree(g, tree)const frame = g.nodes.get(result.id)!@@ -419,7 +414,7 @@ describe('grid layout rendering', () => {})it('sets grid gaps', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({ name: 'Grid', w: 300, h: 200, grid: true, columns: '1fr 1fr', columnGap: 10, rowGap: 20 })const result = await renderTree(g, tree)const frame = g.nodes.get(result.id)!@@ -429,7 +424,7 @@ describe('grid layout rendering', () => {})it('sets grid gap shorthand', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({ name: 'Grid', w: 300, h: 200, grid: true, columns: '1fr 1fr', gap: 16 })const result = await renderTree(g, tree)const frame = g.nodes.get(result.id)!@@ -439,7 +434,7 @@ describe('grid layout rendering', () => {})it('applies grid padding', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({ name: 'Grid', w: 300, h: 200, grid: true, columns: '1fr 1fr', p: 10 })const result = await renderTree(g, tree)const frame = g.nodes.get(result.id)!@@ -451,7 +446,7 @@ describe('grid layout rendering', () => {})it('sets grid rows', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({ name: 'Grid', w: 300, h: 200, grid: true, columns: '1fr', rows: '100 1fr' })const result = await renderTree(g, tree)const frame = g.nodes.get(result.id)!@@ -463,7 +458,7 @@ describe('grid layout rendering', () => {})it('sets grid child position', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({ name: 'Grid', w: 300, h: 200, grid: true, columns: '1fr 1fr 1fr', rows: '1fr 1fr' },Rectangle({ name: 'A', w: 50, h: 50, colStart: 2, rowStart: 1 }))@@ -474,7 +469,7 @@ describe('grid layout rendering', () => {})it('sets grid child span', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({ name: 'Grid', w: 300, h: 200, grid: true, columns: '1fr 1fr 1fr', rows: '1fr 1fr' },Rectangle({ name: 'A', w: 50, h: 50, colStart: 1, colSpan: 2, rowStart: 1, rowSpan: 2 }))@@ -485,7 +480,7 @@ describe('grid layout rendering', () => {})it('grid + computeLayout positions children in cells', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({ name: 'Grid', w: 300, h: 200, grid: true, columns: '1fr 1fr 1fr', rows: '1fr' },Rectangle({ name: 'A', w: 50, h: 50 }),Rectangle({ name: 'B', w: 50, h: 50 }),@@ -501,7 +496,7 @@ describe('grid layout rendering', () => {})it('grid 2x2 with gap positions correctly', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({ name: 'Grid', w: 210, h: 210, grid: true, columns: '1fr 1fr', rows: '1fr 1fr', gap: 10 },Rectangle({ name: 'A', w: 30, h: 30 }),Rectangle({ name: 'B', w: 30, h: 30 }),@@ -523,7 +518,7 @@ describe('grid layout rendering', () => {})it('renders grid from JSX string', async () => {- const g = createGraph()+ const g = makeSceneGraph()const jsx = `<Frame name="Grid" w={300} h={100} grid columns="1fr 1fr" gap={10}><Rectangle name="A" w={50} h={50} />@@ -548,7 +543,7 @@ describe('grid layout rendering', () => {})it('grid auto-height (no rows) grows to fit content', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({ name: 'Grid', w: 300, grid: true, columns: '1fr 1fr', gap: 10 },Rectangle({ name: 'A', w: 50, h: 80 }),Rectangle({ name: 'B', w: 50, h: 80 }),@@ -565,7 +560,7 @@ describe('grid layout rendering', () => {})it('grid children with flex stretch to cell width', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({ name: 'Grid', w: 200, grid: true, columns: '1fr 1fr', gap: 0 },Frame({ name: 'A', flex: 'col', gap: 4, p: 8, children: [Rectangle({ name: 'R1', w: 10, h: 20 })@@ -585,7 +580,7 @@ describe('grid layout rendering', () => {})it('grid prop takes precedence over padding-triggered auto-layout', async () => {- const g = createGraph()+ const g = makeSceneGraph()const tree = Frame({ name: 'Grid', w: 300, grid: true, columns: '1fr 1fr', p: 20 },Rectangle({ name: 'A', w: 50, h: 50 }),Rectangle({ name: 'B', w: 50, h: 50 })@@ -596,7 +591,7 @@ describe('grid layout rendering', () => {})it('grid w=fill stretches in flex-col parent', async () => {- const g = createGraph()+ const g = makeSceneGraph()const jsx = `<Frame name="P" flex="col" w={400} p={20}><Frame name="G" grid columns="1fr 1fr" gap={10} w="fill">@@ -613,7 +608,7 @@ describe('grid layout rendering', () => {})it('grid grow=1 fills remaining space in flex-row', async () => {- const g = createGraph()+ const g = makeSceneGraph()const jsx = `<Frame name="P" flex="row" w={500} p={20} gap={10}><Rectangle w={100} h={50} />@@ -630,7 +625,7 @@ describe('grid layout rendering', () => {})it('nested flex > flex > grid: grid stretches to correct width', async () => {- const g = createGraph()+ const g = makeSceneGraph()const jsx = `<Frame name="Card" flex="col" w={780}><Frame name="Content" flex="col" w="fill" p={28}>@@ -651,7 +646,7 @@ describe('grid layout rendering', () => {})it('grid h=fill grows in flex-col parent', async () => {- const g = createGraph()+ const g = makeSceneGraph()const jsx = `<Frame name="P" flex="col" w={400} h={600} p={20}><Rectangle w={360} h={100} />@@ -670,7 +665,7 @@ describe('grid layout rendering', () => {describe('text props round-trip', () => {it('lineHeight renders and exports', async () => {- const g = createGraph()+ const g = makeSceneGraph()const [result] = await renderJSX(g, '<Text color="#000" lineHeight={24}>Hello</Text>')const n = g.getNode(result.id)!expect(n.lineHeight).toBe(24)@@ -679,7 +674,7 @@ describe('text props round-trip', () => {})it('letterSpacing renders and exports', async () => {- const g = createGraph()+ const g = makeSceneGraph()const [result] = await renderJSX(g, '<Text color="#000" letterSpacing={2}>Spaced</Text>')const n = g.getNode(result.id)!expect(n.letterSpacing).toBe(2)@@ -688,7 +683,7 @@ describe('text props round-trip', () => {})it('textDecoration renders and exports', async () => {- const g = createGraph()+ const g = makeSceneGraph()const [result] = await renderJSX(g, '<Text color="#000" textDecoration="underline">Link</Text>')const n = g.getNode(result.id)!expect(n.textDecoration).toBe('UNDERLINE')@@ -697,7 +692,7 @@ describe('text props round-trip', () => {})it('textCase renders and exports', async () => {- const g = createGraph()+ const g = makeSceneGraph()const [result] = await renderJSX(g, '<Text color="#000" textCase="upper">label</Text>')const n = g.getNode(result.id)!expect(n.textCase).toBe('UPPER')@@ -706,7 +701,7 @@ describe('text props round-trip', () => {})it('maxLines renders with truncation', async () => {- const g = createGraph()+ const g = makeSceneGraph()const [result] = await renderJSX(g, '<Text color="#000" maxLines={2}>Long text here</Text>')const n = g.getNode(result.id)!expect(n.maxLines).toBe(2)@@ -716,7 +711,7 @@ describe('text props round-trip', () => {})it('truncate without maxLines', async () => {- const g = createGraph()+ const g = makeSceneGraph()const [result] = await renderJSX(g, '<Text color="#000" truncate>Overflow</Text>')const n = g.getNode(result.id)!expect(n.textTruncation).toBe('ENDING')@@ -725,7 +720,7 @@ describe('text props round-trip', () => {})it('defaults omit text props', async () => {- const g = createGraph()+ const g = makeSceneGraph()const [result] = await renderJSX(g, '<Text color="#000">Plain</Text>')const n = g.getNode(result.id)!expect(n.lineHeight).toBeNull()@@ -743,7 +738,7 @@ describe('text props round-trip', () => {})it('text w="fill" in flex="col" exports as w="fill" not w={computed}', async () => {- const g = createGraph()+ const g = makeSceneGraph()const [result] = await renderJSX(g, `<Frame name="Card" flex="col" w={300} p={20}><Text name="Title" size={22} weight="bold" color="#111" w="fill">Hello World</Text>@@ -759,7 +754,7 @@ describe('text props round-trip', () => {})it('text grow={1} in flex="row" exports as grow not w={computed}', async () => {- const g = createGraph()+ const g = makeSceneGraph()const [result] = await renderJSX(g, `<Frame name="Row" flex="row" w={300}><Text name="Label" color="#999" w={60}>Label</Text>diff --git a/tests/engine/renderer-effects.test.ts b/tests/engine/renderer-effects.test.tsindex f5a304526..04ff3edaa 100644--- a/tests/engine/renderer-effects.test.ts+++ b/tests/engine/renderer-effects.test.ts@@ -3,11 +3,21 @@ import { readdir } from 'node:fs/promises'import { join } from 'node:path'const rendererDir = new URL('../../packages/core/src/canvas/', import.meta.url).pathname-const files = await readdir(rendererDir)-const parts = await Promise.all(- files.filter((f) => f.endsWith('.ts')).map((f) => Bun.file(join(rendererDir, f)).text())-)-const rendererSource = parts.join('\n')++async function readTypescriptFiles(dir: string): Promise<string[]> {+ const entries = await readdir(dir, { withFileTypes: true })+ const parts = await Promise.all(+ entries.map((entry) => {+ const path = join(dir, entry.name)+ if (entry.isDirectory()) return readTypescriptFiles(path)+ if (entry.isFile() && entry.name.endsWith('.ts')) return Bun.file(path).text()+ return []+ })+ )+ return parts.flat()+}++const rendererSource = (await readTypescriptFiles(rendererDir)).join('\n')describe('Renderer effect ordering', () => {test('drop shadow renders before fills', () => {@@ -51,13 +61,11 @@ describe('Renderer handles all effect types', () => {describe('Shadow spread support', () => {test('drop shadow uses spread for shape expansion', () => {- const dropShadowSection = rendererSource.slice(- rendererSource.indexOf("effect.type === 'DROP_SHADOW'"),- rendererSource.indexOf("effect.type === 'DROP_SHADOW'") + 2000- )+ const dropShadowStart = rendererSource.indexOf('function drawShapeDropShadow')+ const dropShadowSection = rendererSource.slice(dropShadowStart, dropShadowStart + 1800)expect(dropShadowSection).toContain('effect.spread')expect(dropShadowSection).toContain('makeRRectWithSpread')- expect(dropShadowSection).toContain('getCachedDropShadow')+ expect(dropShadowSection).toContain('getCachedMaskBlur')})test('inner shadow uses spread for cutout contraction', () => {@@ -79,10 +87,8 @@ describe('Shadow spread support', () => {describe('Text shadow renders on glyphs, not bounding box', () => {test('drop shadow has TEXT-specific branch', () => {- const dropShadowBlock = rendererSource.slice(- rendererSource.indexOf("effect.type === 'DROP_SHADOW'"),- rendererSource.indexOf("effect.type === 'DROP_SHADOW'") + 2000- )+ const dropShadowStart = rendererSource.indexOf('function renderDropShadow')+ const dropShadowBlock = rendererSource.slice(dropShadowStart, dropShadowStart + 2500)expect(dropShadowBlock).toContain("node.type === 'TEXT'")expect(dropShadowBlock).toContain('renderText')expect(dropShadowBlock).toContain('getCachedDropShadow')diff --git a/tests/engine/rtl-auto-layout-input.test.ts b/tests/engine/rtl-auto-layout-input.test.tsindex a78036e2e..29444c2ac 100644--- a/tests/engine/rtl-auto-layout-input.test.ts+++ b/tests/engine/rtl-auto-layout-input.test.ts@@ -3,9 +3,9 @@ import { describe, expect, test } from 'bun:test'import { SceneGraph, computeLayout } from '@open-pencil/core'import { createEditor } from '@open-pencil/core/editor'-import { computeAutoLayoutIndicatorForFrame } from '../../packages/vue/src/shared/input/auto-layout'-import { handleMoveUp } from '../../packages/vue/src/shared/input/move'-import type { DragMove } from '../../packages/vue/src/shared/input/types'+import { computeAutoLayoutIndicatorForFrame } from '#vue/shared/input/auto-layout'+import { handleMoveUp } from '#vue/shared/input/move'+import type { DragMove } from '#vue/shared/input/types'function pageId(graph: SceneGraph) {return graph.getPages()[0].iddiff --git a/tests/engine/undo-batch-idle.test.ts b/tests/engine/undo-batch-idle.test.tsindex 0a5a23dc7..64d11e036 100644--- a/tests/engine/undo-batch-idle.test.ts+++ b/tests/engine/undo-batch-idle.test.ts@@ -1,22 +1,17 @@import { describe, test, expect } from 'bun:test'-import { UndoManager } from '@open-pencil/core'+import { createUndoManager, noop, undoEntry } from '../helpers/undo'describe('UndoManager idle-timer batching', () => {- function noop() {}- function entry(label: string, forward = noop, inverse = noop) {- return { label, forward, inverse }- }-test('rapid pushes inside a batch produce a single undo entry', () => {- const undo = new UndoManager()+ const undo = createUndoManager()let value = 0undo.beginBatch('drag color')for (let i = 1; i <= 10; i++) {const prev = valueconst next = i- undo.push({ label: `step ${i}`, forward: () => { value = next }, inverse: () => { value = prev } })+ undo.push(undoEntry(`step ${i}`, () => { value = next }, () => { value = prev }))value = next}undo.commitBatch()@@ -30,19 +25,19 @@ describe('UndoManager idle-timer batching', () => {})test('changing batch key flushes the previous batch', () => {- const undo = new UndoManager()+ const undo = createUndoManager()let a = 0let b = 0undo.beginBatch('batch A')- undo.push(entry('a1', () => { a = 1 }, () => { a = 0 }))+ undo.push(undoEntry('a1', () => { a = 1 }, () => { a = 0 }))a = 1- undo.push(entry('a2', () => { a = 2 }, () => { a = 1 }))+ undo.push(undoEntry('a2', () => { a = 2 }, () => { a = 1 }))a = 2undo.commitBatch()undo.beginBatch('batch B')- undo.push(entry('b1', () => { b = 10 }, () => { b = 0 }))+ undo.push(undoEntry('b1', () => { b = 10 }, () => { b = 0 }))b = 10undo.commitBatch()@@ -56,17 +51,17 @@ describe('UndoManager idle-timer batching', () => {})test('discrete action between batches is separate undo entry', () => {- const undo = new UndoManager()+ const undo = createUndoManager()let v = 0undo.beginBatch('drag')- undo.push(entry('d1', () => { v = 1 }, () => { v = 0 }))+ undo.push(undoEntry('d1', () => { v = 1 }, () => { v = 0 }))v = 1- undo.push(entry('d2', () => { v = 2 }, () => { v = 1 }))+ undo.push(undoEntry('d2', () => { v = 2 }, () => { v = 1 }))v = 2undo.commitBatch()- undo.push(entry('add fill', () => { v = 100 }, () => { v = 2 }))+ undo.push(undoEntry('add fill', () => { v = 100 }, () => { v = 2 }))v = 100undo.undo()@@ -77,13 +72,13 @@ describe('UndoManager idle-timer batching', () => {})test('batch redo replays all steps in order', () => {- const undo = new UndoManager()+ const undo = createUndoManager()const log: number[] = []undo.beginBatch('batch')- undo.apply(entry('s1', () => log.push(1), () => log.pop()))- undo.apply(entry('s2', () => log.push(2), () => log.pop()))- undo.apply(entry('s3', () => log.push(3), () => log.pop()))+ undo.apply(undoEntry('s1', () => log.push(1), () => log.pop()))+ undo.apply(undoEntry('s2', () => log.push(2), () => log.pop()))+ undo.apply(undoEntry('s3', () => log.push(3), () => log.pop()))undo.commitBatch()expect(log).toEqual([1, 2, 3])@@ -96,8 +91,8 @@ describe('UndoManager idle-timer batching', () => {})test('commitBatch with no entries is a no-op', () => {- const undo = new UndoManager()- undo.push(entry('existing', noop, noop))+ const undo = createUndoManager()+ undo.push(undoEntry('existing', noop, noop))undo.beginBatch('empty')undo.commitBatch()diff --git a/tests/engine/undo-redo-sequence.test.ts b/tests/engine/undo-redo-sequence.test.tsindex 97aa830f2..0b9fa0ea4 100644--- a/tests/engine/undo-redo-sequence.test.ts+++ b/tests/engine/undo-redo-sequence.test.ts@@ -1,24 +1,12 @@import { describe, test, expect } from 'bun:test'-import { createEditor } from '@open-pencil/core/editor'+import { createHistoryFrame, setupEditorPage } from '../helpers/editor-history'describe('undo/redo multi-step sequences', () => {- function setup() {- const editor = createEditor()- const pageId = editor.graph.getPages()[0].id- return { editor, pageId }- }-test('create → move → duplicate → move copy → undo all → redo all', () => {- const { editor, pageId } = setup()+ const { editor, pageId } = setupEditorPage()- const frame = editor.graph.createNode('FRAME', pageId, {- name: 'Card',- x: 100,- y: 100,- width: 200,- height: 150,- })+ const frame = createHistoryFrame(editor, pageId, { x: 100, y: 100 })editor.select([frame.id])const createSnapshot = structuredClone(editor.graph.getNode(frame.id)!)editor.pushUndoEntry({@@ -81,15 +69,9 @@ describe('undo/redo multi-step sequences', () => {})test('duplicate with children preserves subtree on redo', () => {- const { editor, pageId } = setup()+ const { editor, pageId } = setupEditorPage()- const frame = editor.graph.createNode('FRAME', pageId, {- name: 'Card',- x: 50,- y: 50,- width: 200,- height: 150,- })+ const frame = createHistoryFrame(editor, pageId, { x: 50, y: 50 })editor.graph.createNode('TEXT', frame.id, {name: 'Title',text: 'Hello',@@ -121,16 +103,28 @@ describe('undo/redo multi-step sequences', () => {expect(editor.graph.getNode(dupTextId)!.text).toBe('Hello')})- test('delete frame with children → undo restores subtree', () => {- const { editor, pageId } = setup()-- const frame = editor.graph.createNode('FRAME', pageId, {- name: 'Card',- x: 0,- y: 0,+ test('page snapshot restore preserves node IDs', () => {+ const { editor, pageId } = setupEditorPage()+ const frame = createHistoryFrame(editor, pageId)+ const child = editor.graph.createNode('RECTANGLE', frame.id, {+ name: 'Bg',width: 200,height: 150,})++ const snapshot = editor.snapshotPage()+ editor.graph.deleteNode(frame.id)+ editor.restorePageFromSnapshot(snapshot)++ expect(editor.graph.getNode(frame.id)).not.toBeUndefined()+ expect(editor.graph.getNode(child.id)).not.toBeUndefined()+ expect(editor.graph.getNode(frame.id)!.childIds).toEqual([child.id])+ })++ test('delete frame with children → undo restores subtree', () => {+ const { editor, pageId } = setupEditorPage()++ const frame = createHistoryFrame(editor, pageId)const child = editor.graph.createNode('RECTANGLE', frame.id, {name: 'Bg',x: 0,diff --git a/tests/engine/undo.test.ts b/tests/engine/undo.test.tsindex c3c5e849e..18d2e0cc8 100644--- a/tests/engine/undo.test.ts+++ b/tests/engine/undo.test.ts@@ -1,10 +1,10 @@import { describe, test, expect } from 'bun:test'-import { UndoManager } from '@open-pencil/core'+import { createUndoManager, undoEntry } from '../helpers/undo'describe('UndoManager', () => {test('initial state', () => {- const undo = new UndoManager()+ const undo = createUndoManager()expect(undo.canUndo).toBe(false)expect(undo.canRedo).toBe(false)expect(undo.undoLabel).toBeNull()@@ -12,38 +12,26 @@ describe('UndoManager', () => {})test('apply executes forward and enables undo', () => {- const undo = new UndoManager()+ const undo = createUndoManager()let value = 0- undo.apply({- label: 'increment',- forward: () => { value = 1 },- inverse: () => { value = 0 }- })+ undo.apply(undoEntry('increment', () => { value = 1 }, () => { value = 0 }))expect(value).toBe(1)expect(undo.canUndo).toBe(true)expect(undo.undoLabel).toBe('increment')})test('push does not execute forward', () => {- const undo = new UndoManager()+ const undo = createUndoManager()let value = 0- undo.push({- label: 'set',- forward: () => { value = 1 },- inverse: () => { value = 0 }- })+ undo.push(undoEntry('set', () => { value = 1 }, () => { value = 0 }))expect(value).toBe(0)expect(undo.canUndo).toBe(true)})test('undo calls inverse and returns label', () => {- const undo = new UndoManager()+ const undo = createUndoManager()let value = 0- undo.apply({- label: 'set',- forward: () => { value = 1 },- inverse: () => { value = 0 }- })+ undo.apply(undoEntry('set', () => { value = 1 }, () => { value = 0 }))const label = undo.undo()expect(label).toBe('set')expect(value).toBe(0)@@ -52,13 +40,9 @@ describe('UndoManager', () => {})test('redo calls forward and returns label', () => {- const undo = new UndoManager()+ const undo = createUndoManager()let value = 0- undo.apply({- label: 'set',- forward: () => { value = 1 },- inverse: () => { value = 0 }- })+ undo.apply(undoEntry('set', () => { value = 1 }, () => { value = 0 }))undo.undo()const label = undo.redo()expect(label).toBe('set')@@ -67,39 +51,53 @@ describe('UndoManager', () => {})test('new action clears redo stack', () => {- const undo = new UndoManager()- undo.apply({ label: 'a', forward: () => {}, inverse: () => {} })+ const undo = createUndoManager()+ undo.apply(undoEntry('a'))undo.undo()expect(undo.canRedo).toBe(true)- undo.apply({ label: 'b', forward: () => {}, inverse: () => {} })+ undo.apply(undoEntry('b'))expect(undo.canRedo).toBe(false)})test('undo on empty returns null', () => {- const undo = new UndoManager()+ const undo = createUndoManager()expect(undo.undo()).toBeNull()})test('redo on empty returns null', () => {- const undo = new UndoManager()+ const undo = createUndoManager()expect(undo.redo()).toBeNull()})test('clear empties both stacks', () => {- const undo = new UndoManager()- undo.apply({ label: 'a', forward: () => {}, inverse: () => {} })+ const undo = createUndoManager()+ undo.apply(undoEntry('a'))undo.undo()undo.clear()expect(undo.canUndo).toBe(false)expect(undo.canRedo).toBe(false)})+ test('history limit drops oldest entries', () => {+ const undo = createUndoManager({ limit: 2 })+ let val = 0+ undo.apply(undoEntry('to1', () => { val = 1 }, () => { val = 0 }))+ undo.apply(undoEntry('to2', () => { val = 2 }, () => { val = 1 }))+ undo.apply(undoEntry('to3', () => { val = 3 }, () => { val = 2 }))++ expect(undo.undoLabel).toBe('to3')+ undo.undo()+ undo.undo()+ expect(val).toBe(1)+ expect(undo.undo()).toBeNull()+ })+test('batch combines into single entry', () => {- const undo = new UndoManager()+ const undo = createUndoManager()const log: number[] = []undo.beginBatch('batch')- undo.apply({ label: 'a', forward: () => log.push(1), inverse: () => log.push(-1) })- undo.apply({ label: 'b', forward: () => log.push(2), inverse: () => log.push(-2) })+ undo.apply(undoEntry('a', () => log.push(1), () => log.push(-1)))+ undo.apply(undoEntry('b', () => log.push(2), () => log.push(-2)))undo.commitBatch()expect(log).toEqual([1, 2])expect(undo.undoLabel).toBe('batch')@@ -108,19 +106,65 @@ describe('UndoManager', () => {expect(log).toEqual([1, 2, -2, -1])})+ test('runBatch commits on success', () => {+ const undo = createUndoManager()+ const log: number[] = []++ undo.runBatch('batch', () => {+ undo.apply(undoEntry('a', () => log.push(1), () => log.push(-1)))+ undo.apply(undoEntry('b', () => log.push(2), () => log.push(-2)))+ })++ expect(log).toEqual([1, 2])+ expect(undo.undoLabel).toBe('batch')+ undo.undo()+ expect(log).toEqual([1, 2, -2, -1])+ })++ test('runBatch rolls back on throw', () => {+ const undo = createUndoManager()+ const log: number[] = []++ expect(() =>+ undo.runBatch('batch', () => {+ undo.apply(undoEntry('a', () => log.push(1), () => log.push(-1)))+ throw new Error('boom')+ })+ ).toThrow('boom')++ expect(log).toEqual([1, -1])+ expect(undo.canUndo).toBe(false)+ })++ test('nested batches commit as a single outer entry', () => {+ const undo = createUndoManager()+ const log: number[] = []++ undo.runBatch('outer', () => {+ undo.apply(undoEntry('a', () => log.push(1), () => log.push(-1)))+ undo.runBatch('inner', () => {+ undo.apply(undoEntry('b', () => log.push(2), () => log.push(-2)))+ })+ })++ expect(undo.undoLabel).toBe('outer')+ undo.undo()+ expect(log).toEqual([1, 2, -2, -1])+ })+test('empty batch commits nothing', () => {- const undo = new UndoManager()+ const undo = createUndoManager()undo.beginBatch('empty')undo.commitBatch()expect(undo.canUndo).toBe(false)})test('multiple undo/redo', () => {- const undo = new UndoManager()+ const undo = createUndoManager()let val = 0- undo.apply({ label: 'to1', forward: () => { val = 1 }, inverse: () => { val = 0 } })- undo.apply({ label: 'to2', forward: () => { val = 2 }, inverse: () => { val = 1 } })- undo.apply({ label: 'to3', forward: () => { val = 3 }, inverse: () => { val = 2 } })+ undo.apply(undoEntry('to1', () => { val = 1 }, () => { val = 0 }))+ undo.apply(undoEntry('to2', () => { val = 2 }, () => { val = 1 }))+ undo.apply(undoEntry('to3', () => { val = 3 }, () => { val = 2 }))undo.undo()expect(val).toBe(2)diff --git a/tests/engine/vector.test.ts b/tests/engine/vector.test.tsindex ba275522f..1393bb6ce 100644--- a/tests/engine/vector.test.ts+++ b/tests/engine/vector.test.ts@@ -1,5 +1,13 @@import { describe, test, expect } from 'bun:test'+import {+ lineNetwork,+ triangleNetwork,+ vectorNetwork,+ vectorSegment,+ vectorVertex+} from '../helpers/vector-network'+import {encodeVectorNetworkBlob,decodeVectorNetworkBlob,@@ -20,16 +28,7 @@ describe('vectorNetworkBlob round-trip', () => {})test('single line segment', () => {- const network: VectorNetwork = {- vertices: [- { x: 0, y: 0, handleMirroring: 'NONE' },- { x: 100, y: 50, handleMirroring: 'NONE' }- ],- segments: [- { start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }- ],- regions: []- }+ const network = lineNetwork()const blob = encodeVectorNetworkBlob(network)const decoded = decodeVectorNetworkBlob(blob)expect(decoded.vertices).toHaveLength(2)@@ -42,16 +41,13 @@ describe('vectorNetworkBlob round-trip', () => {})test('cubic bezier segment', () => {- const network: VectorNetwork = {- vertices: [- { x: 0, y: 0, handleMirroring: 'ANGLE' },- { x: 100, y: 100, handleMirroring: 'ANGLE' }- ],- segments: [- { start: 0, end: 1, tangentStart: { x: 30, y: 0 }, tangentEnd: { x: -30, y: 0 } }+ const network = vectorNetwork(+ [+ { ...vectorVertex(0, 0), handleMirroring: 'ANGLE' },+ { ...vectorVertex(100, 100), handleMirroring: 'ANGLE' }],- regions: []- }+ [vectorSegment(0, 1, { x: 30, y: 0 }, { x: -30, y: 0 })]+ )const blob = encodeVectorNetworkBlob(network)const decoded = decodeVectorNetworkBlob(blob)expect(decoded.segments[0].tangentStart.x).toBeCloseTo(30)@@ -59,21 +55,7 @@ describe('vectorNetworkBlob round-trip', () => {})test('network with region', () => {- const network: VectorNetwork = {- vertices: [- { x: 0, y: 0, handleMirroring: 'NONE' },- { x: 100, y: 0, handleMirroring: 'NONE' },- { x: 50, y: 100, handleMirroring: 'NONE' }- ],- segments: [- { start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },- { start: 1, end: 2, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },- { start: 2, end: 0, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }- ],- regions: [- { windingRule: 'NONZERO', loops: [[0, 1, 2]] }- ]- }+ const network = triangleNetwork()const blob = encodeVectorNetworkBlob(network)const decoded = decodeVectorNetworkBlob(blob)expect(decoded.regions).toHaveLength(1)diff --git a/tests/helpers/canvas.ts b/tests/helpers/canvas.tsindex 450a0694f..0a9e28132 100644--- a/tests/helpers/canvas.ts+++ b/tests/helpers/canvas.ts@@ -7,7 +7,7 @@ export class CanvasHelper {constructor(page: Page) {this.page = page- this.canvas = page.locator('canvas')+ this.canvas = page.locator('[data-test-id="canvas-area"]')page.on('pageerror', (err) => this.errors.push(err.message))page.on('console', (msg) => {if (msg.type() === 'error') this.errors.push(msg.text())@@ -29,6 +29,7 @@ export class CanvasHelper {async waitForInit() {await this.page.locator('canvas[data-ready="1"]').waitFor({ timeout: 30000 })await this.page.locator('[data-test-id="canvas-loading"]').waitFor({ state: 'hidden', timeout: 30000 })+ await this.page.locator('#loader').waitFor({ state: 'detached', timeout: 30000 })}async clearCanvas() {@@ -82,10 +83,19 @@ export class CanvasHelper {await this.waitForRender()}- async selectTool(tool: 'select' | 'frame' | 'rectangle' | 'ellipse' | 'text' | 'pen' | 'hand') {+ async drawSection(x: number, y: number, width: number, height: number) {+ await this.pressKey('s')+ await this.drag(x, y, x + width, y + height)+ await this.waitForRender()+ }++ async selectTool(+ tool: 'select' | 'frame' | 'section' | 'rectangle' | 'ellipse' | 'text' | 'pen' | 'hand'+ ) {const keys: Record<string, string> = {select: 'v',frame: 'f',+ section: 's',rectangle: 'r',ellipse: 'o',text: 't',diff --git a/tests/helpers/editor-history.ts b/tests/helpers/editor-history.tsnew file mode 100644index 000000000..c5b757ee4--- /dev/null+++ b/tests/helpers/editor-history.ts@@ -0,0 +1,24 @@+import { createEditor } from '@open-pencil/core/editor'++import type { Editor } from '@open-pencil/core/editor'++export function setupEditorPage() {+ const editor = createEditor()+ const pageId = editor.graph.getPages()[0].id+ return { editor, pageId }+}++export function createHistoryFrame(+ editor: Editor,+ parentId: string,+ overrides: Partial<{ name: string; x: number; y: number; width: number; height: number }> = {}+) {+ return editor.graph.createNode('FRAME', parentId, {+ name: 'Card',+ x: 0,+ y: 0,+ width: 200,+ height: 150,+ ...overrides,+ })+}diff --git a/tests/helpers/fig-traversal.ts b/tests/helpers/fig-traversal.tsnew file mode 100644index 000000000..53bfe8fd9--- /dev/null+++ b/tests/helpers/fig-traversal.ts@@ -0,0 +1,52 @@+import type { NodeType, SceneGraph, SceneNode } from '@open-pencil/core'++export function collectAllNodes(graph: SceneGraph): SceneNode[] {+ const all: SceneNode[] = []+ function walk(id: string) {+ const node = graph.getNode(id)+ if (!node) return+ all.push(node)+ for (const child of graph.getChildren(id)) {+ walk(child.id)+ }+ }+ for (const page of graph.getPages()) {+ for (const child of graph.getChildren(page.id)) {+ walk(child.id)+ }+ }+ return all+}++export function countByType(nodes: SceneNode[]): Map<NodeType, number> {+ const counts = new Map<NodeType, number>()+ for (const node of nodes) {+ counts.set(node.type, (counts.get(node.type) ?? 0) + 1)+ }+ return counts+}++export function childNamed(+ graph: SceneGraph,+ parent: SceneNode | undefined,+ name: string+): SceneNode | undefined {+ return parent ? graph.getChildren(parent.id).find((node) => node.name === name) : undefined+}++export function childMatching(+ graph: SceneGraph,+ parent: SceneNode | undefined,+ predicate: (node: SceneNode) => boolean+): SceneNode | undefined {+ return parent ? graph.getChildren(parent.id).find(predicate) : undefined+}++export function previewChild(+ graph: SceneGraph,+ nodes: SceneNode[],+ name: string+): SceneNode | undefined {+ const preview = nodes.find((node) => node.name === 'Preview Thumbnail')+ return childNamed(graph, preview, name)+}diff --git a/tests/helpers/scene.ts b/tests/helpers/scene.tsnew file mode 100644index 000000000..f35f65f8e--- /dev/null+++ b/tests/helpers/scene.ts@@ -0,0 +1,7 @@+import { SceneGraph } from '@open-pencil/core'++export function makeSceneGraph(pageName = 'Test'): SceneGraph {+ const graph = new SceneGraph()+ graph.addPage(pageName)+ return graph+}diff --git a/tests/helpers/undo.ts b/tests/helpers/undo.tsnew file mode 100644index 000000000..49bd828e1--- /dev/null+++ b/tests/helpers/undo.ts@@ -0,0 +1,11 @@+import { UndoManager } from '@open-pencil/core'++export function noop() {}++export function createUndoManager(options?: ConstructorParameters<typeof UndoManager>[0]) {+ return new UndoManager(options)+}++export function undoEntry(label: string, forward = noop, inverse = noop) {+ return { label, forward, inverse }+}diff --git a/tests/helpers/vector-network.ts b/tests/helpers/vector-network.tsnew file mode 100644index 000000000..4947ed041--- /dev/null+++ b/tests/helpers/vector-network.ts@@ -0,0 +1,34 @@+import type { VectorNetwork, VectorSegment, VectorVertex } from '@open-pencil/core'++export function vectorVertex(x: number, y: number): VectorVertex {+ return { x, y, handleMirroring: 'NONE' }+}++export function vectorSegment(+ start: number,+ end: number,+ tangentStart = { x: 0, y: 0 },+ tangentEnd = { x: 0, y: 0 }+): VectorSegment {+ return { start, end, tangentStart, tangentEnd }+}++export function vectorNetwork(+ vertices: VectorVertex[],+ segments: VectorSegment[],+ regions: VectorNetwork['regions'] = []+): VectorNetwork {+ return { vertices, segments, regions }+}++export function lineNetwork(): VectorNetwork {+ return vectorNetwork([vectorVertex(0, 0), vectorVertex(100, 50)], [vectorSegment(0, 1)])+}++export function triangleNetwork(): VectorNetwork {+ return vectorNetwork(+ [vectorVertex(0, 0), vectorVertex(100, 0), vectorVertex(50, 100)],+ [vectorSegment(0, 1), vectorSegment(1, 2), vectorSegment(2, 0)],+ [{ windingRule: 'NONZERO', loops: [[0, 1, 2]] }]+ )+}diff --git a/tsconfig.json b/tsconfig.jsonindex a10106f91..126f7f58a 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -17,13 +17,16 @@"noFallthroughCasesInSwitch": true,"paths": {"@/*": ["./src/*"],+ "#vue/*": ["./packages/vue/src/*", "./packages/vue/src/*.vue"],+ "#core/*": ["./packages/core/src/*"],+ "#cli/*": ["./packages/cli/src/*"],+ "#mcp/*": ["./packages/mcp/src/*"],+ "tinykeys": ["./node_modules/tinykeys/dist/tinykeys.d.ts"],"@open-pencil/vue": ["./packages/vue/src/index.ts"],- "@open-pencil/vue/*": ["./packages/vue/src/*"],"@open-pencil/core": ["./packages/core/src/index.ts"],"@open-pencil/core/*": ["./packages/core/src/*"]}},"include": ["src/**/*.ts", "src/**/*.vue"],- "exclude": ["src/kiwi/index.ts", "src/kiwi/client.ts"],"references": [{ "path": "./tsconfig.node.json" }]}diff --git a/vite.config.ts b/vite.config.tsindex d28acfaf9..3c84b69f0 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -1,130 +1,39 @@-import { randomUUID } from 'crypto'-import { resolve } from 'path'-import { defineConfig } from 'vite'import vue from '@vitejs/plugin-vue'import tailwindcss from '@tailwindcss/vite'import Icons from 'unplugin-icons/vite'import IconsResolver from 'unplugin-icons/resolver'import Components from 'unplugin-vue-components/vite'-import { VitePWA } from 'vite-plugin-pwa'-import { copyFileSync, existsSync, mkdirSync } from 'fs'--import { automationPlugin } from './src/automation/vite-plugin'--const devAutomationAuthToken = randomUUID()+import { createOpenPencilAliases } from './vite/aliases'+import { localAutomationToken, openPencilAutomationPlugin } from './vite/automation'+import { copyCanvasKitAssetsPlugin } from './vite/canvaskit-assets'+import { openPencilPwaPlugin } from './vite/pwa'+import { rawMarkdownPlugin } from './vite/raw-markdown'+import { createDevServerOptions } from './vite/server'// @ts-expect-error process is a nodejs globalconst host = process.env.TAURI_DEV_HOST-const devAutomationCorsOrigin = host ? `http://${host}:1420` : 'http://localhost:1420'export default defineConfig(async ({ command }) => ({resolve: {- alias: {- '@': resolve(__dirname, 'src'),- '@open-pencil/vue': resolve(__dirname, 'packages/vue/src'),- '@open-pencil/core': resolve(__dirname, 'packages/core/src'),- 'opentype.js': resolve(__dirname, 'node_modules/opentype.js/dist/opentype.module.js'),- // vue-stream-markdown eagerly loads mermaid/beautiful-mermaid as optional peer deps.- // Alias to empty shims to avoid runtime errors and reduce bundle size.- mermaid: resolve(__dirname, 'src/shims/mermaid.ts'),- 'beautiful-mermaid': resolve(__dirname, 'src/shims/mermaid.ts')- }+ alias: createOpenPencilAliases(__dirname)},define: {- __OPENPENCIL_LOCAL_AUTOMATION_TOKEN__: JSON.stringify(- command === 'serve' ? devAutomationAuthToken : null- )+ __OPENPENCIL_LOCAL_AUTOMATION_TOKEN__: JSON.stringify(localAutomationToken(command))},plugins: [- {- name: 'raw-md',- transform(code: string, id: string) {- if (id.endsWith('.md')) {- return { code: `export default ${JSON.stringify(code)}`, map: null }- }- }- },- {- name: 'copy-canvaskit-wasm',- buildStart() {- const src = 'node_modules/canvaskit-wasm/bin/canvaskit.wasm'- const dest = 'public/canvaskit.wasm'- if (existsSync(src) && !existsSync(dest)) {- copyFileSync(src, dest)- }-- const webgpuSrc = 'packages/core/vendor/canvaskit-webgpu/canvaskit.wasm'- const webgpuDir = 'public/canvaskit-webgpu'- const webgpuDest = `${webgpuDir}/canvaskit.wasm`- if (existsSync(webgpuSrc) && !existsSync(webgpuDest)) {- mkdirSync(webgpuDir, { recursive: true })- copyFileSync(webgpuSrc, webgpuDest)- }-- const webgpuJsSrc = 'packages/core/vendor/canvaskit-webgpu/canvaskit.js'- const webgpuJsDest = `${webgpuDir}/canvaskit.js`- if (existsSync(webgpuJsSrc) && !existsSync(webgpuJsDest)) {- mkdirSync(webgpuDir, { recursive: true })- copyFileSync(webgpuJsSrc, webgpuJsDest)- }- }- },+ rawMarkdownPlugin(),+ copyCanvasKitAssetsPlugin(),tailwindcss(),Icons({ compiler: 'vue3' }),Components({ resolvers: [IconsResolver({ prefix: 'icon' })] }),- automationPlugin(command === 'serve' ? devAutomationAuthToken : null, devAutomationCorsOrigin),+ openPencilAutomationPlugin(command, host),vue(),- VitePWA({- registerType: 'autoUpdate',- devOptions: { enabled: false },- workbox: {- maximumFileSizeToCacheInBytes: 12 * 1024 * 1024,- globPatterns: ['**/*.{js,css,html,wasm,png,ico,ttf,webmanifest}'],- navigateFallback: '/index.html'- },- manifest: {- name: 'OpenPencil',- short_name: 'OpenPencil',- description: 'Open-source design editor',- display: 'standalone',- orientation: 'any',- start_url: '/',- scope: '/',- theme_color: '#1e1e1e',- background_color: '#1e1e1e',- categories: ['design', 'productivity'],- icons: [- { src: '/pwa-192.png', sizes: '192x192', type: 'image/png', purpose: 'any' },- { src: '/pwa-512.png', sizes: '512x512', type: 'image/png', purpose: 'any' },- { src: '/pwa-maskable-512.png', sizes: '512x512', type: 'image/png', purpose: 'maskable' }- ]- }- })+ openPencilPwaPlugin()],clearScreen: false,- server: {- port: 1420,- strictPort: true,- host: host || false,- hmr: host- ? {- protocol: 'ws',- host,- port: 1421- }- : undefined,- watch: {- ignored: [- '**/desktop/**',- '**/packages/cli/**',- '**/packages/mcp/**',- '**/packages/docs/**',- '**/tests/**',- '**/.worktrees/**',- '**/.github/**',- '**/.pi/**'- ]- }- }+ build: {+ chunkSizeWarningLimit: 2500+ },+ server: createDevServerOptions(host)}))diff --git a/vite/aliases.ts b/vite/aliases.tsnew file mode 100644index 000000000..83d7cf331--- /dev/null+++ b/vite/aliases.ts@@ -0,0 +1,18 @@+import { resolve } from 'path'++export function createOpenPencilAliases(rootDir: string) {+ const emptyNodeModule = resolve(rootDir, 'vite/empty-node-module.ts')++ return {+ fs: emptyNodeModule,+ path: emptyNodeModule,+ '@': resolve(rootDir, 'src'),+ '#vue': resolve(rootDir, 'packages/vue/src'),+ '#core': resolve(rootDir, 'packages/core/src'),+ '@open-pencil/vue': resolve(rootDir, 'packages/vue/src'),+ '@open-pencil/core': resolve(rootDir, 'packages/core/src'),+ 'opentype.js': resolve(rootDir, 'node_modules/opentype.js/dist/opentype.module.js'),+ mermaid: resolve(rootDir, 'src/app/shell/markdown/index.ts'),+ 'beautiful-mermaid': resolve(rootDir, 'src/app/shell/markdown/index.ts'),+ }+}diff --git a/vite/automation.ts b/vite/automation.tsnew file mode 100644index 000000000..54e28492f--- /dev/null+++ b/vite/automation.ts@@ -0,0 +1,17 @@+import { randomUUID } from 'crypto'++import { automationPlugin } from '../src/app/automation/bridge/vite-plugin'++const devAutomationAuthToken = randomUUID()++export function localAutomationToken(command: string): string | null {+ return command === 'serve' ? devAutomationAuthToken : null+}++export function automationCorsOrigin(host: string | undefined): string {+ return host ? `http://${host}:1420` : 'http://localhost:1420'+}++export function openPencilAutomationPlugin(command: string, host: string | undefined) {+ return automationPlugin(localAutomationToken(command), automationCorsOrigin(host))+}diff --git a/vite/canvaskit-assets.ts b/vite/canvaskit-assets.tsnew file mode 100644index 000000000..d69d2fb73--- /dev/null+++ b/vite/canvaskit-assets.ts@@ -0,0 +1,27 @@+import { copyFileSync, existsSync, mkdirSync } from 'fs'++import type { Plugin } from 'vite'++function copyIfMissing(source: string, destination: string) {+ if (!existsSync(source) || existsSync(destination)) return+ const directory = destination.slice(0, destination.lastIndexOf('/'))+ if (directory) mkdirSync(directory, { recursive: true })+ copyFileSync(source, destination)+}++export function copyCanvasKitAssetsPlugin(): Plugin {+ return {+ name: 'copy-canvaskit-wasm',+ buildStart() {+ copyIfMissing('node_modules/canvaskit-wasm/bin/canvaskit.wasm', 'public/canvaskit.wasm')+ copyIfMissing(+ 'packages/core/vendor/canvaskit-webgpu/canvaskit.wasm',+ 'public/canvaskit-webgpu/canvaskit.wasm',+ )+ copyIfMissing(+ 'packages/core/vendor/canvaskit-webgpu/canvaskit.js',+ 'public/canvaskit-webgpu/canvaskit.js',+ )+ },+ }+}diff --git a/vite/empty-node-module.ts b/vite/empty-node-module.tsnew file mode 100644index 000000000..b1c6ea436--- /dev/null+++ b/vite/empty-node-module.ts@@ -0,0 +1 @@+export default {}diff --git a/vite/pwa.ts b/vite/pwa.tsnew file mode 100644index 000000000..deba26465--- /dev/null+++ b/vite/pwa.ts@@ -0,0 +1,30 @@+import { VitePWA } from 'vite-plugin-pwa'++export function openPencilPwaPlugin() {+ return VitePWA({+ registerType: 'autoUpdate',+ devOptions: { enabled: false },+ workbox: {+ maximumFileSizeToCacheInBytes: 12 * 1024 * 1024,+ globPatterns: ['**/*.{js,css,html,wasm,png,ico,ttf,webmanifest}'],+ navigateFallback: '/index.html',+ },+ manifest: {+ name: 'OpenPencil',+ short_name: 'OpenPencil',+ description: 'Open-source design editor',+ display: 'standalone',+ orientation: 'any',+ start_url: '/',+ scope: '/',+ theme_color: '#1e1e1e',+ background_color: '#1e1e1e',+ categories: ['design', 'productivity'],+ icons: [+ { src: '/pwa-192.png', sizes: '192x192', type: 'image/png', purpose: 'any' },+ { src: '/pwa-512.png', sizes: '512x512', type: 'image/png', purpose: 'any' },+ { src: '/pwa-maskable-512.png', sizes: '512x512', type: 'image/png', purpose: 'maskable' },+ ],+ },+ })+}diff --git a/vite/raw-markdown.ts b/vite/raw-markdown.tsnew file mode 100644index 000000000..0c55ef1ff--- /dev/null+++ b/vite/raw-markdown.ts@@ -0,0 +1,12 @@+import type { Plugin } from 'vite'++export function rawMarkdownPlugin(): Plugin {+ return {+ name: 'raw-md',+ transform(code: string, id: string) {+ if (id.endsWith('.md')) {+ return { code: `export default ${JSON.stringify(code)}`, map: null }+ }+ },+ }+}diff --git a/vite/server.ts b/vite/server.tsnew file mode 100644index 000000000..c0601a030--- /dev/null+++ b/vite/server.ts@@ -0,0 +1,30 @@+import type { ServerOptions } from 'vite'++export const WATCH_IGNORED = [+ '**/desktop/**',+ '**/packages/cli/**',+ '**/packages/mcp/**',+ '**/packages/docs/**',+ '**/tests/**',+ '**/.worktrees/**',+ '**/.github/**',+ '**/.pi/**',+]++export function createDevServerOptions(host: string | undefined): ServerOptions {+ return {+ port: 1420,+ strictPort: true,+ host: host || false,+ hmr: host+ ? {+ protocol: 'ws',+ host,+ port: 1421,+ }+ : undefined,+ watch: {+ ignored: WATCH_IGNORED,+ },+ }+}