AI-native design editor. Open-source Figma alternative.
Add reference & development pages for all locales, fix nav missing menu items
Anton A S8ca1bc790f8c
diff --git a/packages/docs/.vitepress/config.ts b/packages/docs/.vitepress/config.tsindex 1dd78ff60..aafbc2943 100644--- a/packages/docs/.vitepress/config.ts+++ b/packages/docs/.vitepress/config.ts@@ -27,6 +27,8 @@ interface SidebarLabels {interface NavLabels {userGuide: string+ reference: string+ development: stringopenApp: string}@@ -78,6 +80,32 @@ const guideSidebar = (prefix: string, l: SidebarLabels): DefaultTheme.SidebarIte},]+const referenceSidebar = (prefix: string, label: string): DefaultTheme.SidebarItem[] => [+ {+ text: label,+ items: [+ { text: 'Keyboard Shortcuts', link: `${prefix}/reference/keyboard-shortcuts` },+ { text: 'Node Types', link: `${prefix}/reference/node-types` },+ { text: 'MCP Tools', link: `${prefix}/reference/mcp-tools` },+ { text: 'Scene Graph', link: `${prefix}/reference/scene-graph` },+ { text: 'File Format', link: `${prefix}/reference/file-format` },+ { text: 'Eval Command', link: `${prefix}/eval-command` },+ ],+ },+]++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 localeThemeConfig = (prefix: string,nav: NavLabels,@@ -85,11 +113,17 @@ const localeThemeConfig = (): DefaultTheme.Config => ({nav: [{ text: nav.userGuide, link: `${prefix}/user-guide/` },+ { 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}/`]: guideSidebar(prefix, sidebar),+ [`${prefix}/reference/`]: referenceSidebar(prefix, nav.reference),+ [`${prefix}/`]: [+ ...guideSidebar(prefix, sidebar),+ ...developmentSidebar(prefix, nav.development),+ ],},})@@ -128,31 +162,31 @@ export default defineConfig({label: 'Deutsch',lang: 'de',description: 'Open-Source, KI-nativer Design-Editor. Figma-Alternative.',- themeConfig: localeThemeConfig('/de', { userGuide: 'Benutzerhandbuch', openApp: 'App öffnen' }, DE),+ themeConfig: localeThemeConfig('/de', { userGuide: 'Benutzerhandbuch', reference: 'Referenz', development: 'Entwicklung', openApp: 'App öffnen' }, DE),},it: {label: 'Italiano',lang: 'it',description: 'Editor di design open-source, IA-nativo. Alternativa a Figma.',- themeConfig: localeThemeConfig('/it', { userGuide: 'Guida utente', openApp: 'Apri app' }, IT),+ themeConfig: localeThemeConfig('/it', { userGuide: 'Guida utente', reference: 'Riferimento', development: 'Sviluppo', openApp: 'Apri app' }, IT),},fr: {label: 'Français',lang: 'fr',description: 'Éditeur de design open-source, IA-natif. Alternative à Figma.',- themeConfig: localeThemeConfig('/fr', { userGuide: 'Guide utilisateur', openApp: 'Ouvrir l\'app' }, FR),+ themeConfig: localeThemeConfig('/fr', { userGuide: 'Guide utilisateur', reference: 'Référence', development: 'Développement', openApp: 'Ouvrir l\'app' }, FR),},es: {label: 'Español',lang: 'es',description: 'Editor de diseño open-source, IA-nativo. Alternativa a Figma.',- themeConfig: localeThemeConfig('/es', { userGuide: 'Guía del usuario', openApp: 'Abrir app' }, ES),+ themeConfig: localeThemeConfig('/es', { userGuide: 'Guía del usuario', reference: 'Referencia', development: 'Desarrollo', openApp: 'Abrir app' }, ES),},pl: {label: 'Polski',lang: 'pl',description: 'Open-source\'owy edytor graficzny z natywnym AI. Alternatywa dla Figmy.',- themeConfig: localeThemeConfig('/pl', { userGuide: 'Podręcznik', openApp: 'Otwórz app' }, PL),+ themeConfig: localeThemeConfig('/pl', { userGuide: 'Podręcznik', reference: 'Referencja', development: 'Rozwój', openApp: 'Otwórz app' }, PL),},},diff --git a/packages/docs/de/development/contributing.md b/packages/docs/de/development/contributing.mdnew file mode 100644index 000000000..c6c5a15d9--- /dev/null+++ b/packages/docs/de/development/contributing.md@@ -0,0 +1,94 @@+# Mitwirken++## Project Structure++```+packages/+ core/ @open-pencil/core — engine (zero DOM deps)+ src/ Scene graph, renderer, layout, codec, kiwi, types+ cli/ @open-pencil/cli — headless CLI for .fig operations+ src/commands/ info, tree, find, export+src/+ components/ Vue SFCs (canvas, panels, toolbar, color picker)+ properties/ Property panel sections (Appearance, Fill, Stroke, etc.)+ composables/ Canvas input, keyboard shortcuts, rendering hooks+ stores/ Editor state (Vue reactivity)+ engine/ Re-export shims from @open-pencil/core+ kiwi/ Re-export shims from @open-pencil/core+ types.ts Shared types (re-exported from core)+ constants.ts UI colors, defaults, thresholds+desktop/ Tauri v2 (Rust + config)+tests/+ e2e/ Playwright visual regression+ engine/ Unit tests (bun:test)+docs/ VitePress documentation site+openspec/+ specs/ Capability specifications (source of truth)+ changes/ Active and archived changes+```++## Development Setup++```sh+bun install+bun run dev # Editor at localhost:1420+bun run docs:dev # Docs at localhost:5173+```++## Code Style++### Tooling++| Tool | Command | Purpose |+|------|---------|---------|+| oxlint | `bun run lint` | Linting (Rust-based, fast) |+| oxfmt | `bun run format` | Code formatting |+| tsgo | `bun run typecheck` | Type checking (Go-based TypeScript checker) |++Run all checks:++```sh+bun run check+```++### Conventions++- **File names** — kebab-case (`scene-graph.ts`, `use-canvas-input.ts`)+- **Components** — PascalCase Vue SFCs (`EditorCanvas.vue`, `ScrubInput.vue`)+- **Constants** — SCREAMING_SNAKE_CASE+- **Functions/variables** — camelCase+- **Types/interfaces** — PascalCase++### AI Agent Conventions++Developers and AI agents working on the codebase should read `AGENTS.md` in the repo root ([view on GitHub](https://github.com/open-pencil/open-pencil/blob/master/AGENTS.md)). Covers rendering, scene graph, components & instances, layout, UI, file format, Tauri conventions, and known issues.++## Making Changes++1. Check existing [openspec specs](/development/openspec) for the capability you're modifying+2. Create an openspec change if adding new behavior: `openspec new change "my-change"`+3. Implement the change+4. Run `bun run check` and `bun run test`+5. Submit a pull request++## 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.++| 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/layout.ts` | Yoga layout adapter |+| `packages/core/src/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/kiwi/fig-import.ts` | .fig file import logic |+| `packages/cli/src/index.ts` | CLI entry point |+| `packages/cli/src/commands/` | CLI commands (info, tree, find, export) |+| `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 |diff --git a/packages/docs/de/development/openspec.md b/packages/docs/de/development/openspec.mdnew file mode 100644index 000000000..697b6fc17--- /dev/null+++ b/packages/docs/de/development/openspec.md@@ -0,0 +1,107 @@+# OpenSpec-Workflow++OpenPencil uses [OpenSpec](https://github.com/Fission-AI/OpenSpec) for spec-driven development. Specifications are the source of truth for what the system does.++## Structure++```+openspec/+├── specs/ # Source of truth: how the system works now+│ ├── scene-graph/+│ │ └── spec.md+│ ├── canvas-rendering/+│ │ └── spec.md+│ ├── auto-layout/+│ │ └── spec.md+│ └── ... # 19 capability specs total+├── changes/ # Proposed changes (one directory per change)+│ └── archive/ # Completed changes+└── config.yaml # Optional configuration+```++## Current Specs++| Capability | Description |+|-----------|-------------|+| scene-graph | Flat Map storage, CRUD, hit testing |+| canvas-rendering | CanvasKit WASM rendering pipeline |+| canvas-navigation | Pan, zoom, hand tool |+| selection-manipulation | Click/marquee select, move, resize, rotate |+| undo-redo | Inverse-command pattern |+| text-editing | Text tool, Paragraph API, font loading |+| pen-tool | Vector network model, bezier curves |+| auto-layout | Yoga WASM flexbox, Shift+A toggle |+| figma-clipboard | Bidirectional Kiwi binary clipboard |+| fig-import | .fig file import pipeline |+| kiwi-codec | Kiwi binary codec, sparse field IDs |+| editor-ui | Vue 3 panels, toolbar, color picker |+| snap-guides | Edge/center snapping, rotation-aware |+| rulers | Canvas rulers, selection highlight |+| group-ungroup | ⌘G/⇧⌘G, position-based sort |+| desktop-app | Tauri v2, macOS menu bar |+| testing | Playwright E2E, bun:test unit |+| scrub-input | Drag-to-scrub numeric inputs |+| tooling | Vite 7, oxlint, oxfmt, tsgo, VitePress |++## Workflow++### 1. Propose a Change++```+/opsx:propose add-dark-mode+```++Creates `openspec/changes/add-dark-mode/` with:+- `proposal.md` — why and what changes+- `design.md` — technical approach+- `specs/` — delta specifications (ADDED/MODIFIED/REMOVED requirements)+- `tasks.md` — implementation checklist++### 2. Implement++```+/opsx:apply+```++Execute tasks from tasks.md, checking off items as they're completed.++### 3. Archive++```+/opsx:archive+```++- Merges delta specs into `openspec/specs/` (the baseline)+- Moves the change to `openspec/changes/archive/`++## Spec Format++Each spec file follows a consistent structure:++```markdown+# capability-name Specification++## Purpose+One-line description of what this capability does.++## Requirements++### Requirement: Name+Description using SHALL/MUST for normative requirements.++#### Scenario: Name+- **WHEN** condition+- **THEN** expected outcome+```++Every requirement has at least one scenario. Scenarios are potential test cases.++## CLI Commands++```sh+openspec list # List active changes+openspec show <name> # Show change details+openspec status --change <name> # Artifact status+openspec archive <name> # Archive completed change+openspec update # Regenerate skills/prompts+```diff --git a/packages/docs/de/development/roadmap.md b/packages/docs/de/development/roadmap.mdnew file mode 100644index 000000000..9355b5198--- /dev/null+++ b/packages/docs/de/development/roadmap.md@@ -0,0 +1,145 @@+# Fahrplan++## Phases++### Phase 1: Core Engine ✅++SceneGraph, Skia rendering, basic shapes, selection, zoom/pan, undo/redo.++**Delivered:**+- Scene graph with flat Map storage and parent-child tree+- CanvasKit WASM rendering for all shape types+- Click/shift/marquee selection with resize handles and rotation+- Zoom/pan with keyboard shortcuts and trackpad gestures+- Undo/redo wired into all operations+- Snap guides with edge and center snapping++### Phase 2: Editor UI + Layout ✅++Properties panel, layers panel, toolbar, Yoga layout integration, text editing.++**Delivered:**+- Vue 3 + Reka UI panels (properties, layers, toolbar)+- Properties panel split into sections (Appearance, Fill, Stroke, Typography, Layout, Position)+- ScrubInput component for all numeric inputs+- Color picker (HSV, hex, opacity)+- Layers panel with tree view, drag reorder, visibility toggle+- Auto-layout with Yoga WASM (direction, gap, padding, justify, align)+- Inline text editing with CanvasKit Paragraph API+- System font loading via Local Font Access API+- Canvas rulers with selection highlight++### Phase 3: File I/O + Visual Features ✅++.fig import/export, Kiwi codec, clipboard, sections, pages, advanced rendering.++**Delivered:**+- .fig file import via Kiwi binary codec+- .fig file export with Kiwi encoding, Zstd compression, thumbnail generation+- Save (⌘S) and Save As (⇧⌘S) with native OS dialogs+- Zstd compression via Tauri Rust command (deflate fallback in browser)+- Vendored kiwi-schema with ESM + sparse field ID patches+- Figma-compatible clipboard (bidirectional Kiwi binary)+- Pen tool with vector network model+- vectorNetworkBlob binary encode/decode+- Group/ungroup (⌘G/⇧⌘G)+- Tauri v2 desktop app with native menu bar (macOS/Windows/Linux)+- Sections (S key) with title pills, auto-adopt, luminance-adaptive text+- Multi-page documents with pages panel, per-page viewport+- Hover highlight with shape-aware outlines+- Tier 1 rendering: gradients, image fills, effects, strokes (cap/join/dash), arcs+- Fill type picker with solid/gradient/image tabs and gradient stop editing+- Canvas background color per page+- Fig-import unit tests, layout unit tests, layers-panel E2E tests++### Phase 4: Components + Variables ✅++Components, instances, overrides, variables, collections, modes, image export.++**Delivered:**+- Component creation from frame/group or multi-selection (⌥⌘K)+- Component sets from multiple components (⇧⌘K) with dashed purple border+- Instance creation from components with child cloning and componentId mapping+- Live component-instance sync with override preservation+- Detach instance back to frame (⌥⌘B)+- Go to main component (cross-page navigation)+- Always-visible purple component/instance labels with diamond icon+- Opaque container hit testing (click selects component, double-click enters)+- Right-click context menu with clipboard, z-order, grouping, component, visibility, lock, move-to-page actions+- Z-order manipulation (] bring to front, [ send to back)+- Toggle visibility (⇧⌘H) and lock (⇧⌘L)+- Move nodes between pages via context menu+- Viewport culling, Paint reuse, RAF render coalescing+- Effects panel UI (drop shadow, inner shadow, layer/background/foreground blur)+- Independent corner radius controls (per-corner toggle in Appearance section)+- GitHub Actions CI/CD for Windows (x64, arm64) and macOS (x64, arm64) builds+- Polygon and Star drawing tools with pointCount and starInnerRadius+- Resizable left/right panels via reka-ui Splitter (persistent layout)+- @/ import alias, shared types module (src/types.ts, src/global.d.ts)+- Codebase lint-clean: 0 oxlint warnings, 0 tsgo type errors+- Variables: COLOR type with collections, modes, bindings, FillSection variable picker, .fig import+- Variables dialog: TanStack Table with resizable columns, mode columns, collection tabs with rename, search, demo collections (Primitives/Semantic/Spacing), undo/redo for all variable operations+- Image export: PNG/JPG/WEBP with ExportSection (scale, format, live preview), ⇧⌘E shortcut, context menu+- Canvas-native text editing: TextEditor class in core, phantom textarea, cursor/selection/word boundaries on canvas, caret blinking, selection highlights+- System font enumeration via font-kit Rust crate, OnceLock cache, preload on startup+- Font picker: virtual scroll (reka-ui ListboxVirtualizer), search filter, CSS font preview+- ColorInput component extraction, ColorPicker alpha slider checkerboard fix+- App identity: pencil icon, Cargo crate open_pencil, macOS Dock "OpenPencil"+- Splash loader during WASM initialization+- Rich text style runs: per-selection ⌘B/I/U, StyleRun model, ParagraphBuilder pushStyle/pop, .fig roundtrip+- B/I/U/S toggle buttons in TypographySection+- Double-click (word), triple-click (select all) text selection++**Remaining (deferred to Phase 6):**+- Variant switching+- Variable types: FLOAT, STRING, BOOLEAN editing UI+- Variable-driven theming++### Phase 5: AI Integration & Tooling 🟡++Core extraction, CLI, MCP server, design guidelines, screenshot verification loop.++**Delivered:**+- @open-pencil/core extracted to packages/core/ (zero DOM deps, Bun workspace)+- @open-pencil/cli with headless .fig operations (info, tree, find, export, analyze, node, pages, variables), CanvasKit CPU rasterization, --json output+- JSX renderer: TreeNode builders (Frame, Text, Rectangle, etc.), renderTreeNode/renderJsx, Tailwind-like shorthand props, 27 tests+- jscpd copy-paste detection (15.6% → 0.62%), kiwi-serialize.ts consolidation+- .fig roundtrip tests with LFS fixtures (material3.fig 87K nodes, nuxtui.fig 314K nodes)+- .fig import O(n²) → O(n) fix (37s → 535ms on 87K nodes), ByteBuffer optimization+- test:coverage script+- AI chat: OpenRouter direct (no backend), Stronghold key storage, 26 tools (create_shape, set_fill, set_effects, set_constraints, components, groups, pages, variables, eval_code, etc.), model selector, ⌘J toggle, streaming markdown, Playwright tests with mock transport+- Code panel: sceneNodeToJsx() export, Prism.js highlighting, line numbers, copy button, 14 tests+- Properties panel restructured: Design | Code | AI tabs+- npm publishing preparation for core and cli packages++**Planned:**+- Port remaining figma-use tools (118 total, 26 currently implemented)+- Attached mode: WebSocket to running editor for eval, create, export, screenshot+- Design guidelines system+- AI-driven design workflow via MCP+- Screenshot verification loop++### Phase 6: Polish + Distribution 🔲++Prototyping, comments, desktop distribution, documentation, public launch.++**Planned:**+- Prototyping (frame connections, transitions)+- Comments (pin, threads, resolve)+- Linux Tauri builds (macOS and Windows already covered by CI)+- PWA support+- Documentation site (VitePress)+- Performance optimization (Lighthouse > 90)+- Full Figma compatibility test suite+- Deferred from Phase 4: variant switching, FLOAT/STRING/BOOLEAN variable UI, variable-driven theming++## Timeline++| Phase | Estimated Duration | Status |+|-------|-------------------|--------|+| Phase 1: Core Engine | 3 months | ✅ Complete |+| Phase 2: Editor UI + Layout | 3 months | ✅ Complete |+| Phase 3: File I/O + Visual Features | 2 months | ✅ Complete |+| Phase 4: Components + Variables | 2 months | ✅ Complete |+| Phase 5: AI Integration & Tooling | 2 months | 🟡 In Progress |+| Phase 6: Polish + Distribution | 2 months | 🔲 Planned |diff --git a/packages/docs/de/development/testing.md b/packages/docs/de/development/testing.mdnew file mode 100644index 000000000..3c6871d2c--- /dev/null+++ b/packages/docs/de/development/testing.md@@ -0,0 +1,91 @@+# Testen++## Overview++| Type | Framework | Command | Location |+|------|-----------|---------|----------|+| E2E visual regression | Playwright | `bun run test` | `tests/e2e/` |+| Figma CDP reference | Playwright | `bun run test:figma` | `tests/figma/` |+| Unit tests | bun:test | `bun run test:unit` | `tests/engine/` |++## E2E Visual Regression++Playwright creates shapes on the canvas and compares screenshots against baseline PNGs.++```sh+bun run test # Run tests, compare against baselines+bun run test:update # Regenerate baseline screenshots+```++### How It Works++1. Tests load the editor in a headless browser+2. The editor signals readiness via a `data-ready` HTML attribute+3. Tests create shapes via the editor's API+4. Screenshots are taken and compared against baselines using `toMatchSnapshot`+5. Page is reused across test cases for speed (~2s total)++### No-Chrome Test Mode++The editor supports a test mode that hides UI chrome (toolbar, panels) for clean screenshot capture. Activated via URL parameter.++## Figma CDP Reference Tests++A separate Playwright project connects to Figma via Chrome DevTools Protocol to capture reference screenshots for pixel-perfect comparison.++```sh+bun run figma:debug # Launch Figma with debugging port+bun run test:figma # Connect to Figma, capture references+```++Requires Figma desktop app running with `--remote-debugging-port=9222`.++## Unit Tests++Engine unit tests use bun:test and target < 50ms execution:++```sh+bun run test:unit+```++Tests cover:+- Scene graph CRUD operations, parent-child relationships, z-ordering, hit testing+- **Fig-import pipeline** — node type mapping, transforms, fills/strokes/effects, gradients, images, arcs, nested hierarchies (`tests/engine/fig-import.test.ts`)+- **Layout computation** — Yoga auto-layout: direction, gap, padding, justify, align, child sizing (fixed/fill/hug), cross-axis sizing, wrap, nested layouts (`tests/engine/layout.test.ts`)++### Writing Unit Tests++```typescript+import { describe, expect, it } from 'bun:test'+import { SceneGraph } from '../../src/engine/scene-graph'++describe('SceneGraph', () => {+ it('creates and retrieves a node', () => {+ const sg = new SceneGraph()+ const node = sg.createNode('RECTANGLE', sg.root, { name: 'Test' })+ expect(sg.getNode(node.guid)).toBeDefined()+ })+})+```++## E2E Test Coverage++| Test file | Scope |+|-----------|-------|+| `tests/e2e/layers-panel.spec.ts` | Layers panel tree structure, visibility toggles, selection sync |+| `tests/e2e/visual.spec.ts` | Visual regression screenshots for shapes and rendering |++## Test Helpers++| File | Purpose |+|------|---------|+| `tests/helpers/canvas.ts` | Canvas setup and interaction utilities |+| `tests/helpers/figma.ts` | Figma CDP connection helpers |++## Performance Targets++| Metric | Target |+|--------|--------|+| E2E suite total | < 3s |+| Unit test suite total | < 50ms |+| Screenshot comparison | toMatchSnapshot (pixel-level) |diff --git a/packages/docs/de/eval-command.md b/packages/docs/de/eval-command.mdnew file mode 100644index 000000000..9f7c45018--- /dev/null+++ b/packages/docs/de/eval-command.md@@ -0,0 +1,437 @@+# `open-pencil eval` — Figma-like Plugin API for Headless Scripting++## Overview++`bun open-pencil eval <file> --code '<js>'` executes JavaScript against a `.fig` file with a Figma-compatible `figma` global object. This enables headless scripting, batch operations, AI tool execution, and testing — all without the GUI.++The `figma` object mirrors Figma's Plugin API surface as closely as possible, so existing Figma plugin knowledge and code snippets transfer directly.++```bash+# Create a frame, set auto-layout, add children+bun open-pencil eval design.fig --code '+ const frame = figma.createFrame()+ frame.name = "Card"+ frame.resize(300, 200)+ frame.layoutMode = "VERTICAL"+ frame.itemSpacing = 12+ frame.paddingTop = frame.paddingBottom = 16+ frame.paddingLeft = frame.paddingRight = 16+ frame.fills = [{ type: "SOLID", color: { r: 1, g: 1, b: 1 } }]++ const title = figma.createText()+ title.characters = "Hello World"+ title.fontSize = 24+ frame.appendChild(title)++ return { id: frame.id, name: frame.name }+'++# Query nodes+bun open-pencil eval design.fig --code '+ const buttons = figma.currentPage.findAll(n => n.type === "FRAME" && n.name.includes("Button"))+ return buttons.map(b => ({ id: b.id, name: b.name, w: b.width, h: b.height }))+'++# Read from stdin (for multiline scripts / piping)+cat transform.js | bun open-pencil eval design.fig --stdin++# Write changes back+bun open-pencil eval design.fig --code '...' --write+bun open-pencil eval design.fig --code '...' -o modified.fig+```++## Architecture++```+┌──────────────────────────────────────────────────────┐+│ CLI: `open-pencil eval <file> --code '...'` │+│ ↓ │+│ loadDocument(file) → SceneGraph │+│ ↓ │+│ FigmaAPI(sceneGraph) → `figma` proxy object │+│ ↓ │+│ AsyncFunction('figma', wrappedCode)(figmaProxy) │+│ ↓ │+│ print result as JSON / agentfmt │+│ optionally: saveDocument(file) if --write │+└──────────────────────────────────────────────────────┘+```++### Key classes++| 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.) |+| `eval` command | `packages/cli/src/commands/eval.ts` | CLI command that loads doc, creates API, executes code |++### Why in `@open-pencil/core`?++The `FigmaAPI` class lives in core (not CLI) because:+- **AI tools reuse it** — the chat panel's `render` tool can execute JSX through the same API+- **Test scripts** — unit tests can use the API to set up fixtures+- **No DOM deps** — runs headless in Bun, no browser APIs needed++## `FigmaAPI` — Phased Implementation++### Phase 1: Core (MVP for eval command)++These cover ~80% of real plugin scripts:++#### Document & Page++| Figma API | Our implementation | Notes |+|-----------|--------------------|-------|+| `figma.root` | Getter → proxy for root node | `.children` returns page proxies |+| `figma.currentPage` | Getter/setter → first page by default | Settable to any page proxy |+| `figma.currentPage.selection` | Get/set → tracked selection array | |+| `figma.getNodeById(id)` | `graph.getNode(id)` wrapped in proxy | Sync, like Figma's deprecated version |++#### Node Creation++| Figma API | Maps to |+|-----------|---------|+| `figma.createFrame()` | `graph.createNode('FRAME', currentPageId)` |+| `figma.createRectangle()` | `graph.createNode('RECTANGLE', ...)` |+| `figma.createEllipse()` | `graph.createNode('ELLIPSE', ...)` |+| `figma.createText()` | `graph.createNode('TEXT', ...)` |+| `figma.createLine()` | `graph.createNode('LINE', ...)` |+| `figma.createPolygon()` | `graph.createNode('POLYGON', ...)` |+| `figma.createStar()` | `graph.createNode('STAR', ...)` |+| `figma.createComponent()` | `graph.createNode('COMPONENT', ...)` |+| `figma.createPage()` | `graph.addPage(name)` |+| `figma.createSection()` | `graph.createNode('SECTION', ...)` |++#### Node Properties (via `FigmaNode` proxy)++Read/write on any node proxy. Property access maps to `SceneNode` fields:++```ts+// Geometry+node.x, node.y // direct+node.width, node.height // read-only, use node.resize(w, h)+node.rotation // direct+node.resize(w, h) // updates width + height+node.resizeWithoutConstraints(w, h) // same (no constraint engine yet)++// Visual+node.fills // get/set Fill[]+node.strokes // get/set Stroke[]+node.effects // get/set Effect[]+node.opacity // get/set number+node.visible // get/set boolean+node.locked // get/set boolean+node.blendMode // get/set BlendMode+node.clipsContent // get/set boolean++// Corner radius+node.cornerRadius // get/set (number or figma.mixed)+node.topLeftRadius // get/set+node.topRightRadius // get/set+node.bottomLeftRadius // get/set+node.bottomRightRadius // get/set+node.cornerSmoothing // get/set++// Identity+node.id // read-only+node.name // get/set+node.type // read-only+node.parent // read-only → FigmaNode | null+node.removed // read-only boolean+```++#### Tree Operations++```ts+node.children // read-only FigmaNode[]+node.appendChild(child) // reparent to end+node.insertChild(index, child) // reparent at index+node.remove() // graph.deleteNode(id)++// Traversal+node.findAll(callback?) // recursive find+node.findOne(callback) // first match+node.findChild(callback) // direct children only+node.findChildren(callback?) // direct children only+```++#### Auto-layout++```ts+node.layoutMode // 'NONE' | 'HORIZONTAL' | 'VERTICAL'+node.primaryAxisAlignItems // 'MIN' | 'CENTER' | 'MAX' | 'SPACE_BETWEEN'+node.counterAxisAlignItems // 'MIN' | 'CENTER' | 'MAX' | 'BASELINE'+node.itemSpacing // number+node.counterAxisSpacing // number | null+node.paddingTop / Right / Bottom / Left // number+node.layoutWrap // 'NO_WRAP' | 'WRAP'++// Child sizing+node.layoutPositioning // 'AUTO' | 'ABSOLUTE'+node.layoutGrow // 0 | 1+node.layoutSizingHorizontal // 'FIXED' | 'HUG' | 'FILL'+node.layoutSizingVertical // 'FIXED' | 'HUG' | 'FILL'+```++#### Text++```ts+node.characters // get/set (maps to node.text)+node.fontSize // get/set+node.fontName // get/set { family, style }+node.fontWeight // get/set+node.textAlignHorizontal // get/set+node.textAlignVertical // get/set+node.textAutoResize // get/set+node.letterSpacing // get/set+node.lineHeight // get/set+node.maxLines // get/set+node.textCase // get/set+node.textDecoration // get/set+```++#### Stroke details++```ts+node.strokeWeight // get/set (maps to strokes[0].weight)+node.strokeAlign // get/set (maps to strokes[0].align)+node.dashPattern // get/set+```++#### Misc++```ts+figma.mixed // Symbol sentinel for mixed values+figma.group(nodes, parent) // creates GROUP with given children+figma.ungroup(node) // ungroups, reparents children+figma.flatten(nodes) // NOT IMPLEMENTED YET — returns first node+```++#### Export++```ts+node.exportAsync(settings?) // only works if CanvasKit is loaded+ // settings: { format: 'PNG'|'JPG'|'SVG', constraint? }+```++### Phase 2: Components & Instances++| API | Maps to |+|-----|---------|+| `figma.createComponent()` | `graph.createNode('COMPONENT', ...)` |+| `figma.createComponentFromNode(node)` | Convert existing frame to component |+| `figma.combineAsVariants(components, parent)` | Create COMPONENT_SET |+| Node: `node.createInstance()` | `graph.createInstance(componentId, parentId)` |+| Node: `node.detachInstance()` | `graph.detachInstance(id)` |+| `figma.getNodeById(id).mainComponent` | `graph.getMainComponent(id)` |++### Phase 3: Variables++| API | Maps to |+|-----|---------|+| `figma.variables.getLocalVariables(type?)` | `graph.variables` filtered |+| `figma.variables.getLocalVariableCollections()` | `graph.variableCollections` |+| `figma.variables.createVariable(name, collection, type)` | `graph.addVariable(...)` |+| `figma.variables.createVariableCollection(name)` | `graph.addCollection(...)` |+| `figma.variables.getVariableById(id)` | `graph.variables.get(id)` |+| `node.setBoundVariable(field, variable)` | `graph.bindVariable(...)` |+| `node.boundVariables` | getter from SceneNode |++### Phase 4: Styles & Advanced++| API | Notes |+|-----|-------|+| `figma.createPaintStyle()` | Requires style storage in SceneGraph |+| `figma.createTextStyle()` | Requires style storage in SceneGraph |+| `figma.createEffectStyle()` | Requires style storage in SceneGraph |+| `figma.loadFontAsync(fontName)` | No-op (we don't have font loading constraints) |+| `figma.listAvailableFontsAsync()` | Return system fonts if available |+| Boolean operations (`union`, `subtract`, `intersect`, `exclude`) | Requires path boolean engine |+| `figma.createNodeFromJSXAsync(jsx)` | Port figma-use's JSX renderer |++## `FigmaNode` Proxy Design++The proxy wraps a `SceneNode` and translates Figma property names to our internal names. Key mappings:++```ts+const PROPERTY_MAP: Record<string, string> = {+ // Figma name → SceneNode field name (only where they differ)+ 'characters': 'text',+ 'strokeWeight': → computed from strokes[0].weight,+ 'strokeAlign': → computed from strokes[0].align,+ 'fontName': → computed from { family: fontFamily, style: ... },+ 'primaryAxisAlignItems': 'primaryAxisAlign',+ 'counterAxisAlignItems': 'counterAxisAlign',+ 'primaryAxisSizingMode': 'primaryAxisSizing', // value mapping: 'AUTO' → 'HUG', 'FIXED' → 'FIXED'+ 'counterAxisSizingMode': 'counterAxisSizing',+ 'layoutSizingHorizontal': → computed from primaryAxisSizing / counterAxisSizing depending on layoutMode+ 'layoutSizingVertical': → computed+}+```++Methods on the proxy:++```ts+class FigmaNode {+ // The proxy is created via: new Proxy(target, handler)+ // where handler.get intercepts property reads and handler.set intercepts writes++ resize(width: number, height: number): void+ resizeWithoutConstraints(width: number, height: number): void+ remove(): void+ appendChild(child: FigmaNode): void+ insertChild(index: number, child: FigmaNode): void+ findAll(callback?: (node: FigmaNode) => boolean): FigmaNode[]+ findOne(callback: (node: FigmaNode) => boolean): FigmaNode | null+ findChild(callback: (node: FigmaNode) => boolean): FigmaNode | null+ findChildren(callback?: (node: FigmaNode) => boolean): FigmaNode[]+ exportAsync(settings?: ExportSettings): Promise<Uint8Array>++ // Components (Phase 2)+ createInstance(): FigmaNode+ detachInstance(): void+ get mainComponent(): FigmaNode | null+}+```++## CLI Command++```+bun open-pencil eval <file> [options]++Arguments:+ file .fig file to operate on++Options:+ --code, -c JavaScript code to execute (has access to `figma` global)+ --stdin Read code from stdin instead of --code+ --write, -w Write changes back to the input file+ -o, --output Write to a different file+ --json Output result as JSON (default for non-TTY)+ --quiet, -q Suppress output, only write file+```++### Execution model++1. Load `.fig` → `SceneGraph`+2. Create `FigmaAPI(graph)` → `figma` proxy+3. Wrap user code in async function: `return (async () => { <code> })()`+4. Execute with `figma` as sole argument+5. Print return value (JSON or agentfmt)+6. If `--write` or `-o`: serialize `SceneGraph` back to `.fig`++### Return value formatting++- `undefined` / `void` → no output+- Primitives → printed directly+- Objects/arrays → `JSON.stringify(result, null, 2)` or agentfmt tables+- `FigmaNode` → serialized as `{ id, type, name, x, y, width, height, fills, ... }`+- Arrays of `FigmaNode` → serialized as list++## 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`:++```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)+execute: async ({ type, x, y, width, height }) => {+ const frame = figma.createFrame()+ frame.resize(width, height)+ frame.x = x+ frame.y = y+ return { id: frame.id }+}+```++This ensures CLI scripts and AI tools behave identically.++## File Layout++```+packages/core/src/+ figma-api.ts # FigmaAPI class + FigmaNode proxy (Phase 1–4)+ figma-api.test.ts # Unit tests against headless SceneGraph++packages/cli/src/commands/+ eval.ts # CLI command++packages/cli/src/commands/eval.test.ts # Integration tests+```++## Test Plan++### Unit tests (`packages/core/src/figma-api.test.ts`)++1. **Node creation** — each `createX()` creates correct type, added to current page+2. **Property access** — `.fills`, `.x`, `.width`, `.name`, `.characters` read/write correctly+3. **Resize** — `.resize(w, h)` updates width/height+4. **Tree operations** — `.appendChild()`, `.insertChild()`, `.remove()`, `.parent`, `.children`+5. **Traversal** — `.findAll()`, `.findOne()`, `.findChild()`, `.findChildren()` with callbacks+6. **Auto-layout** — `.layoutMode`, `.itemSpacing`, `.paddingTop`, etc.+7. **Text** — `.characters` maps to `.text`, `.fontName` maps to `{ family, style }`+8. **Mixed values** — `.cornerRadius` returns `figma.mixed` when corners differ+9. **Selection** — `figma.currentPage.selection` get/set+10. **Page switching** — `figma.currentPage = page2` works+11. **Group/ungroup** — `figma.group()` creates group, `figma.ungroup()` dissolves it+12. **Clone** — node creation produces independent copies++### CLI integration tests (`packages/cli/src/commands/eval.test.ts`)++1. **Basic eval** — `eval test.fig --code 'return figma.currentPage.name'` → page name+2. **Create + read** — create a frame, return its properties+3. **Query nodes** — `findAll` returns correct nodes+4. **Write back** — `--write` saves changes, reloading shows them+5. **Stdin** — `echo 'return 42' | bun open-pencil eval test.fig --stdin` → `42`+6. **JSON output** — `--json` returns valid JSON+7. **Error handling** — syntax errors, runtime errors reported cleanly++## Implementation Order++1. **`FigmaNode` proxy** — property mapping, `.resize()`, `.remove()`, tree methods+2. **`FigmaAPI` class** — `createFrame/Rectangle/...`, `.root`, `.currentPage`, `.getNodeById()`, `.mixed`, `.group()`+3. **CLI `eval` command** — argument parsing, code wrapping, output formatting+4. **Unit tests** — all 12 test groups above+5. **CLI integration tests** — all 7 test groups above+6. **Wire to AI tools** — refactor `src/ai/tools.ts` to use `FigmaAPI` where possible+7. **Phase 2** — components & instances+8. **Phase 3** — variables+9. **Phase 4** — styles, boolean ops, JSX renderer++## Property Mapping Reference++| Figma Property | SceneNode Field | Type | Notes |+|---------------|-----------------|------|-------|+| `characters` | `text` | `string` | |+| `fontName` | `fontFamily` + `fontWeight` + `italic` | `{ family, style }` | Computed: `style` = "Bold Italic" etc. |+| `strokeWeight` | `strokes[0].weight` | `number` | Computed |+| `strokeAlign` | `strokes[0].align` | `string` | Computed |+| `primaryAxisAlignItems` | `primaryAxisAlign` | `string` | |+| `counterAxisAlignItems` | `counterAxisAlign` | `string` | |+| `layoutSizingHorizontal` | `primaryAxisSizing` or `counterAxisSizing` | `string` | Depends on `layoutMode` |+| `layoutSizingVertical` | (opposite of horizontal) | `string` | |+| `absoluteTransform` | computed from `x`, `y`, `rotation` | `Transform` | Read-only |+| `absoluteBoundingBox` | `getAbsoluteBounds(id)` | `Rect` | Read-only |+| All others | Same name | Same type | Direct passthrough |++## Open Questions++1. **Font loading**: `figma.loadFontAsync()` — should it be a no-op (we don't have font gating) or should we track loaded fonts?+ → **Decision: No-op that returns resolved Promise.** We don't gate text editing on font loading.++2. **Export in headless mode**: `node.exportAsync()` requires CanvasKit. Should eval load CanvasKit?+ → **Decision: Optional.** If CanvasKit is available (via `--with-canvaskit` flag or env), enable export. Otherwise, throw "Export requires CanvasKit" error.++3. **`figma.mixed` symbol**: Should we use the actual Figma symbol or our own?+ → **Decision: Our own `Symbol('mixed')`.** Exposed as `figma.mixed`.++4. **Undo**: `figma.commitUndo()` / `figma.triggerUndo()` — relevant in headless?+ → **Decision: No-op in CLI.** Undo only matters in the live editor. The AI tools can add undo support separately via EditorStore.++5. **Write format**: Should `--write` produce `.fig` (Kiwi binary) or also support `.json`?+ → **Decision: `.fig` only for now.** JSON export is a separate feature.diff --git a/packages/docs/de/reference/file-format.md b/packages/docs/de/reference/file-format.mdnew file mode 100644index 000000000..0bd57ce9c--- /dev/null+++ b/packages/docs/de/reference/file-format.md@@ -0,0 +1,71 @@+# Dateiformat++## .fig File Structure++```+┌─────────────────────────────────┐+│ Magic header: "fig-kiwi" (8B) │+│ Version (4B uint32 LE) │+│ Schema length (4B uint32 LE) │+│ Compressed Kiwi schema │+│ Message length (4B uint32 LE) │+│ Compressed Kiwi message │ ← NodeChange[] (entire document)+│ Blob data │ ← Images, vector networks, fonts+└─────────────────────────────────┘+```++## Import Pipeline++```+.fig file → Parse header → Decompress Zstd → Decode Kiwi schema+ → Decode Message → NodeChange[] → Build SceneGraph+ → Resolve blob refs → Render on canvas+```++## Export Pipeline++```+SceneGraph → NodeChange[] → Kiwi encode → Compress (Zstd/deflate)+ → Build ZIP (header + schema + message + thumbnail.png)+ → Write .fig file+```++Export uses <kbd>⌘</kbd><kbd>S</kbd> (Save) and <kbd>⇧</kbd><kbd>⌘</kbd><kbd>S</kbd> (Save As) with native OS dialogs on the desktop app. The exported file includes a `thumbnail.png` required by Figma for file preview. Compression uses Zstd via Tauri Rust command on desktop, with deflate fallback in the browser. The ZIP archive is assembled in Rust on desktop for correct Zstd frame headers (content size included).++## Kiwi Binary Codec++The codec handles Figma's 194-definition Kiwi schema with NodeChange as the central type (~390 fields). Key components:++- **kiwi-schema** — vendored from evanw/kiwi, patched for ESM and sparse field IDs+- **codec.ts** — encode/decode Messages using the Kiwi schema+- **protocol.ts** — wire format parsing and message type detection+- **schema.ts** — 194 message/enum/struct definitions++### Sparse Field IDs++Figma's schema uses non-contiguous field IDs (e.g., 1, 2, 5, 10 with gaps). The vendored kiwi-schema parser is patched to handle this correctly.++### Compression++.fig files use Zstd compression for both the schema and message payloads. Decompression uses the `fzstd` library. For export, Zstd compression is offloaded to a Tauri Rust command on the desktop app (better performance, correct frame headers). In the browser, deflate via `fflate` is used as a fallback. Clipboard encoding also uses `fflate`.++## Supported Formats++| Format | Import | Export |+|--------|--------|--------|+| .fig (Figma) | ✅ | ✅ |+| .svg | Planned | Planned |+| .png | Planned | Planned |+| .pdf | — | Planned |++See [Roadmap](/development/roadmap) for planned format support timeline.++## Clipboard Format++Copy/paste uses the same Kiwi binary encoding:++1. **Copy** — encode selected NodeChange[] to Kiwi binary, compress, write to clipboard as `application/x-figma-design` MIME type+2. **Paste** — read clipboard, decompress, decode Kiwi binary, create nodes in scene graph+3. **Synchronous** — encoding happens in the copy event handler (not async Clipboard API) to ensure browser compatibility++This enables bidirectional clipboard between OpenPencil and Figma.diff --git a/packages/docs/de/reference/keyboard-shortcuts.md b/packages/docs/de/reference/keyboard-shortcuts.mdnew file mode 100644index 000000000..69e9d4a62--- /dev/null+++ b/packages/docs/de/reference/keyboard-shortcuts.md@@ -0,0 +1,120 @@+# Tastenkürzel++Vollständige Figma-kompatible Tastenkürzel-Übersicht.++::: tip Symbol Legend+⌘ = Cmd (Mac) / Ctrl (Win/Linux) · ⇧ = Shift · ⌥ = Alt/Option · ⌃ = Ctrl · ⌫ = Backspace+:::++## Tools++| Key | Tool | Status |+|-----|------|--------|+| <kbd>V</kbd> | Move/Select | ✅ |+| <kbd>K</kbd> | Scale | 🔲 |+| <kbd>H</kbd> | Hand | ✅ |+| <kbd>F</kbd> | Frame | ✅ |+| <kbd>S</kbd> | Section | ✅ |+| <kbd>R</kbd> | Rectangle | ✅ |+| <kbd>O</kbd> | Ellipse | ✅ |+| <kbd>L</kbd> | Line | ✅ |+| — | Polygon | ✅ (flyout only) |+| — | Star | ✅ (flyout only) |+| <kbd>⇧</kbd><kbd>L</kbd> | Arrow | 🔲 |+| <kbd>P</kbd> | Pen | ✅ |+| <kbd>⇧</kbd><kbd>P</kbd> | Pencil | 🔲 |+| <kbd>T</kbd> | Text | ✅ |+| <kbd>C</kbd> | Comment | 🔲 |+| <kbd>I</kbd> | Eyedropper | 🔲 |++## File++| Shortcut | Action | Status |+|----------|--------|--------|+| <kbd>⌘</kbd><kbd>N</kbd> | New Window | 🔲 |+| <kbd>⌘</kbd><kbd>O</kbd> | Open File | ✅ |+| <kbd>⌘</kbd><kbd>W</kbd> | Close Tab | 🔲 |+| <kbd>⌘</kbd><kbd>S</kbd> | Save | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>S</kbd> | Save As | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>E</kbd> | Export… | ✅ |++## Edit++| Shortcut | Action | Status |+|----------|--------|--------|+| <kbd>⌘</kbd><kbd>Z</kbd> | Undo | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>Z</kbd> | Redo | ✅ |+| <kbd>⌘</kbd><kbd>X</kbd> | Cut | ✅ |+| <kbd>⌘</kbd><kbd>C</kbd> | Copy | ✅ |+| <kbd>⌘</kbd><kbd>V</kbd> | Paste | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>V</kbd> | Paste Over Selection | 🔲 |+| <kbd>⌘</kbd><kbd>D</kbd> | Duplicate | ✅ |+| <kbd>⌫</kbd> | Delete | ✅ |+| <kbd>⌘</kbd><kbd>A</kbd> | Select All | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>A</kbd> | Select Inverse | 🔲 |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>C</kbd> | Copy Properties | 🔲 |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>V</kbd> | Paste Properties | 🔲 |++## View++| Shortcut | Action | Status |+|----------|--------|--------|+| <kbd>⌘</kbd><kbd>'</kbd> | Pixel Grid | 🔲 |+| <kbd>⌃</kbd><kbd>G</kbd> | Layout Guides | 🔲 |+| <kbd>⇧</kbd><kbd>R</kbd> | Rulers | 🔲 |+| <kbd>⌘</kbd><kbd>\\</kbd> | Show/Hide UI | 🔲 |+| <kbd>⌘</kbd><kbd>=</kbd> | Zoom In | ✅ |+| <kbd>⌘</kbd><kbd>-</kbd> | Zoom Out | ✅ |+| <kbd>⌘</kbd><kbd>0</kbd> | Zoom to 100% | ✅ |+| <kbd>⌘</kbd><kbd>1</kbd> | Zoom to Fit | 🔲 |+| <kbd>⌘</kbd><kbd>2</kbd> | Zoom to Selection | 🔲 |+| <kbd>⌘</kbd><kbd>J</kbd> | Toggle AI Chat | ✅ |++## Object++| Shortcut | Action | Status |+|----------|--------|--------|+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>G</kbd> | Frame Selection | 🔲 |+| <kbd>⌘</kbd><kbd>G</kbd> | Group Selection | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>G</kbd> | Ungroup | ✅ |+| <kbd>⇧</kbd><kbd>A</kbd> | Add Auto Layout | ✅ |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>K</kbd> | Create Component | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>K</kbd> | Create Component Set | ✅ |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>B</kbd> | Detach Instance | ✅ |+| <kbd>⌘</kbd><kbd>]</kbd> | Bring Forward | 🔲 |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>]</kbd> | Bring to Front | 🔲 |+| <kbd>]</kbd> | Bring to Front | ✅ |+| <kbd>⌘</kbd><kbd>[</kbd> | Send Backward | 🔲 |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>[</kbd> | Send to Back | 🔲 |+| <kbd>[</kbd> | Send to Back | ✅ |+| <kbd>⇧</kbd><kbd>H</kbd> | Flip Horizontal | 🔲 |+| <kbd>⇧</kbd><kbd>V</kbd> | Flip Vertical | 🔲 |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>H</kbd> | Toggle Visibility | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>L</kbd> | Toggle Lock | ✅ |+| <kbd>⌘</kbd><kbd>E</kbd> | Flatten | 🔲 |++## Text++| Shortcut | Action | Status |+|----------|--------|--------|+| <kbd>⌘</kbd><kbd>B</kbd> | Bold | ✅ |+| <kbd>⌘</kbd><kbd>I</kbd> | Italic | ✅ |+| <kbd>⌘</kbd><kbd>U</kbd> | Underline | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>X</kbd> | Strikethrough | 🔲 |++## Canvas Interaction++| Input | Action | Status |+|-------|--------|--------|+| Click | Select node | ✅ |+| <kbd>Shift</kbd>+Click | Add/remove from selection | ✅ |+| <kbd>Alt</kbd>+Drag | Duplicate and move | ✅ |+| <kbd>Shift</kbd>+Drag (draw) | Constrain to square/circle | ✅ |+| <kbd>Shift</kbd>+Drag (resize) | Maintain aspect ratio | ✅ |+| <kbd>Shift</kbd>+Drag (rotate) | Snap to 15° | ✅ |+| Middle mouse drag | Pan | ✅ |+| Scroll | Pan | ✅ |+| <kbd>Ctrl</kbd>+Scroll / Pinch | Zoom | ✅ |+| Double-click text | Edit text inline | ✅ |+| Drag onto frame | Reparent into frame | ✅ |+| <kbd>Escape</kbd> | Deselect / Cancel | ✅ |diff --git a/packages/docs/de/reference/mcp-tools.md b/packages/docs/de/reference/mcp-tools.mdnew file mode 100644index 000000000..b1f0fbcae--- /dev/null+++ b/packages/docs/de/reference/mcp-tools.md@@ -0,0 +1,140 @@+# MCP-Server++OpenPencil includes an MCP (Model Context Protocol) server that lets AI coding tools — Claude Code, Cursor, Windsurf, etc. — read and modify `.fig` files headlessly.++Two transports: **stdio** for MCP clients, **HTTP** for everything else.++## Install++```sh+bun add -g @open-pencil/mcp+```++## Stdio (Claude Code, Cursor, etc.)++Add to your MCP config (e.g. `~/.claude/settings.json` or `.cursor/mcp.json`):++```json+{+ "mcpServers": {+ "open-pencil": {+ "command": "openpencil-mcp"+ }+ }+}+```++Or run from source without installing:++::: code-group+```json [Bun]+{+ "mcpServers": {+ "open-pencil": {+ "command": "bun",+ "args": ["/path/to/open-pencil/packages/mcp/src/index.ts"]+ }+ }+}+```+```json [Node.js]+{+ "mcpServers": {+ "open-pencil": {+ "command": "npx",+ "args": ["tsx", "/path/to/open-pencil/packages/mcp/src/index.ts"]+ }+ }+}+```+:::++## HTTP++For browser extensions, scripts, CI, or any HTTP client:++```sh+openpencil-mcp-http+```++Or from source: `bun packages/mcp/src/http.ts` / `npx tsx packages/mcp/src/http.ts`++Starts on port 3100 (override with `PORT` env var). Endpoints:++- `GET /health` — server status+- `POST /mcp` — MCP Streamable HTTP (SSE). Sessions via `mcp-session-id` header.++## Workflow++1. **Open** — `open_file` to load an existing `.fig`, or `new_document` for a blank canvas+2. **Read** — `get_page_tree`, `find_nodes`, `get_node`, `list_pages`+3. **Create** — `create_shape`, `render` (JSX)+4. **Modify** — `set_fill`, `set_stroke`, `set_layout`, `update_node`, `set_effects`+5. **Structure** — `reparent_node`, `group_nodes`, `clone_node`, `delete_node`+6. **Save** — `save_file` to write back to `.fig`++## Tools (29)++### Document++| Tool | Description |+|------|-------------|+| `open_file` | Open a `.fig` file for editing |+| `save_file` | Save the current document to a `.fig` file |+| `new_document` | Create a new empty document |++### Read++| Tool | Description |+|------|-------------|+| `get_selection` | Get currently selected nodes |+| `get_page_tree` | Get the full node tree of the current page |+| `get_node` | Get detailed properties of a node by ID |+| `find_nodes` | Find nodes by name pattern and/or type |+| `list_pages` | List all pages |+| `list_variables` | List design variables |+| `list_collections` | List variable collections |++### Create++| Tool | Description |+|------|-------------|+| `create_shape` | Create a shape (FRAME, RECTANGLE, ELLIPSE, TEXT, LINE, STAR, POLYGON, SECTION) |+| `render` | Render JSX to design nodes — create entire component trees in one call |+| `create_component` | Convert a frame/group into a component |+| `create_instance` | Create an instance of a component |++### Modify++| Tool | Description |+|------|-------------|+| `set_fill` | Set fill color (hex) |+| `set_stroke` | Set stroke color, weight, alignment |+| `set_effects` | Add shadow or blur effects |+| `update_node` | Update position, size, opacity, corner radius, text, font |+| `set_layout` | Set auto-layout (flexbox) — direction, spacing, padding, alignment |+| `set_constraints` | Set resize constraints |++### Structure++| Tool | Description |+|------|-------------|+| `delete_node` | Delete a node |+| `clone_node` | Duplicate a node |+| `rename_node` | Rename a node |+| `reparent_node` | Move a node into a different parent |+| `select_nodes` | Select nodes by ID |+| `group_nodes` | Group nodes |+| `ungroup_node` | Ungroup a group |++### Navigation++| Tool | Description |+|------|-------------|+| `switch_page` | Switch to a page by name or ID |++### Escape Hatch++| Tool | Description |+|------|-------------|+| `eval` | Execute JavaScript with full Figma Plugin API access |diff --git a/packages/docs/de/reference/node-types.md b/packages/docs/de/reference/node-types.mdnew file mode 100644index 000000000..8bb08fcd6--- /dev/null+++ b/packages/docs/de/reference/node-types.md@@ -0,0 +1,194 @@+# Knotentypen++The scene graph supports 28 node types from Figma's Kiwi schema. Each node is identified by a GUID (`sessionID:localID`) and has a parent reference via `parentIndex`. The OpenPencil engine's `NodeType` union currently uses 17 of these types.++## Type Table++28 Figma schema types + 1 synthetic engine type. Types marked ✅ are in the engine's `NodeType` union (17 total).++| Type | ID | Description | Engine |+|------|----|-------------|--------|+| DOCUMENT | 1 | Root node, one per file | — |+| CANVAS | 2 | Page | ✅ |+| GROUP | 3 | Group container | ✅ |+| FRAME | 4 | Primary container (artboard), supports auto-layout | ✅ |+| BOOLEAN_OPERATION | 5 | Union/subtract/intersect/exclude result | |+| VECTOR | 6 | Freeform vector path | ✅ |+| STAR | 7 | Star shape | ✅ |+| LINE | 8 | Line | ✅ |+| ELLIPSE | 9 | Ellipse/circle, supports arc data | ✅ |+| RECTANGLE | 10 | Rectangle | ✅ |+| REGULAR_POLYGON | 11 | Regular polygon (3–12 sides, engine uses `POLYGON`) | ✅ |+| ROUNDED_RECTANGLE | 12 | Rectangle with smooth corners | ✅ |+| TEXT | 13 | Text with rich formatting | ✅ |+| SLICE | 14 | Export region | |+| SYMBOL | 15 | Component (main, engine uses `COMPONENT`) | ✅ |+| INSTANCE | 16 | Component instance | ✅ |+| STICKY | 17 | FigJam sticky note | |+| SHAPE_WITH_TEXT | 18 | FigJam shape | ✅ |+| CONNECTOR | 19 | Connector line between nodes | ✅ |+| CODE_BLOCK | 20 | FigJam code block | |+| WIDGET | 21 | Plugin widget | |+| STAMP | 22 | FigJam stamp | |+| MEDIA | 23 | Video/GIF | |+| HIGHLIGHT | 24 | FigJam highlight | |+| SECTION | 25 | Canvas section (organizational, top-level only) | ✅ |+| SECTION_OVERLAY | 26 | Section overlay | |+| WASHI_TAPE | 27 | FigJam washi tape | |+| VARIABLE | 28 | Variable definition node | |+| COMPONENT_SET | — | Variant group container (synthetic, mapped from SYMBOL) | ✅ |++### Engine NodeType Union (17 types)++The engine's `NodeType` uses simplified names. Some differ from the Kiwi schema:+- `COMPONENT` → Kiwi `SYMBOL` (ID 15)+- `COMPONENT_SET` → variant group container (no dedicated Kiwi ID, mapped from SYMBOL with variants)+- `POLYGON` → Kiwi `REGULAR_POLYGON` (ID 11)++```typescript+type NodeType =+ | 'CANVAS' | 'FRAME' | 'RECTANGLE' | 'ROUNDED_RECTANGLE'+ | 'ELLIPSE' | 'TEXT' | 'LINE' | 'STAR' | 'POLYGON'+ | 'VECTOR' | 'GROUP' | 'SECTION'+ | 'COMPONENT' | 'COMPONENT_SET' | 'INSTANCE'+ | 'CONNECTOR' | 'SHAPE_WITH_TEXT'+```++## Node Hierarchy++```+Document+├── Canvas (Page 1)+│ ├── Section (top-level only, title pill, auto-adopts siblings)+│ │ ├── Frame+│ │ │ └── ...children+│ │ └── Rectangle+│ ├── Frame+│ │ ├── Rectangle+│ │ ├── Text+│ │ └── Frame (nested)+│ │ ├── Ellipse+│ │ └── Instance (→ references Component)+│ ├── Component+│ │ └── ...children+│ ├── Group+│ │ └── ...children+│ └── BooleanOperation+│ └── ...operand shapes+└── Canvas (Page 2)+ └── ...+```++## Core Properties++Every node carries these fields (subset of NodeChange):++### Identity & Tree++- `guid` — unique identifier (`sessionID:localID`)+- `type` — node type enum+- `name` — display name+- `phase` — CREATED or REMOVED+- `parentIndex` — parent GUID + position string for z-ordering++### Transform++- `size` — width/height vector+- `transform` — 2×3 affine matrix+- `rotation` — degrees++### Appearance++- `fillPaints[]` — fill colors/gradients/images+- `strokePaints[]` — stroke colors+- `effects[]` — shadows, blurs+- `opacity` — 0–1+- `blendMode` — NORMAL, MULTIPLY, SCREEN, etc.++### Stroke++- `strokeWeight` — stroke thickness+- `strokeAlign` — inside / center / outside+- `strokeCap` — butt / round / square+- `strokeJoin` — miter / bevel / round+- `dashPattern[]` — dash/gap lengths++### Corners++- `cornerRadius` — uniform radius+- `cornerSmoothing` — squircle amount (0–1)+- Per-corner radii when `rectangleCornerRadiiIndependent` is true++### Visibility++- `visible` — show/hide+- `locked` — prevent editing++## Type-Specific Properties++### Text++`fontSize`, `fontName`, `lineHeight`, `letterSpacing`, `textAlignHorizontal`, `textAlignVertical`, `textAutoResize`, `textData` (characters, style overrides, baselines, glyphs)++### Vector++`vectorData` (vectorNetworkBlob, normalizedSize), `fillGeometry[]`, `strokeGeometry[]`, `handleMirroring`, `arcData`++### Layout (Frame)++`stackMode`, `stackSpacing`, `stackPadding`, `stackJustify`, `stackCounterAlign`, `stackPrimarySizing`, `stackCounterSizing`, `stackChildPrimaryGrow`, `stackChildAlignSelf`++### Component++`symbolData`, `componentKey`, `componentPropDefs[]`, `symbolDescription`++### Instance++`overriddenSymbolID`, `symbolData.symbolOverrides[]`, `componentPropRefs[]`, `componentPropAssignments[]`++## Paint++```typescript+interface Fill {+ type: 'SOLID' | 'GRADIENT_LINEAR' | 'GRADIENT_RADIAL' |+ 'GRADIENT_ANGULAR' | 'GRADIENT_DIAMOND' | 'IMAGE'+ color: Color // {r, g, b, a} 0–1 floats+ opacity: number // 0–1+ visible: boolean+ blendMode?: BlendMode+ gradientStops?: GradientStop[] // for gradients+ gradientTransform?: GradientTransform // 2×3 matrix+ imageHash?: string // for image fills+ imageScaleMode?: 'FILL' | 'FIT' | 'CROP' | 'TILE'+ imageTransform?: GradientTransform+}+```++## Effect++```typescript+interface Effect {+ type: 'DROP_SHADOW' | 'INNER_SHADOW' | 'LAYER_BLUR' |+ 'BACKGROUND_BLUR' | 'FOREGROUND_BLUR'+ color: Color+ offset: { x: number; y: number }+ radius: number+ spread: number+ visible: boolean+}+```++## Stroke++```typescript+interface Stroke {+ color: Color+ weight: number+ opacity: number+ visible: boolean+ align: 'INSIDE' | 'CENTER' | 'OUTSIDE'+ cap?: 'NONE' | 'ROUND' | 'SQUARE' | 'ARROW_LINES' | 'ARROW_EQUILATERAL'+ join?: 'MITER' | 'BEVEL' | 'ROUND'+ dashPattern?: number[]+}+```diff --git a/packages/docs/de/reference/scene-graph.md b/packages/docs/de/reference/scene-graph.mdnew file mode 100644index 000000000..c3aee6777--- /dev/null+++ b/packages/docs/de/reference/scene-graph.md@@ -0,0 +1,99 @@+# Szenengraph++## In-Memory Representation++Nodes live in a flat `Map<string, Node>` keyed by GUID string. The tree structure is maintained via `parentIndex` references. This gives O(1) lookup by ID and efficient traversal.++```typescript+interface SceneGraph {+ nodes: Map<string, Node>+ root: string++ getNode(id: string): Node+ getChildren(id: string): Node[]+ getParent(id: string): Node | null+ getPages(): Node[]++ createNode(type: NodeType, parent: string, props: Partial<NodeChange>): Node+ updateNode(id: string, changes: Partial<NodeChange>): void+ deleteNode(id: string): void+ moveNode(id: string, newParent: string, position: string): void+ addPage(name: string): Node+ deletePage(id: string): void+ renamePage(id: string, name: string): void++ findByType(type: NodeType): Node[]+ findByName(pattern: string): Node[]+ hitTest(point: Vector, canvas: string): Node | null+ getNodesInRect(rect: Rect, canvas: string): Node[]+}+```++## Pages++Documents support multiple pages (CANVAS nodes as direct children of the DOCUMENT root). Each page has its own child tree and independent viewport state (panX, panY, zoom, pageColor). The editor tracks `currentPageId` and renders only the active page's children.++## Sections++SECTION nodes are top-level organizational containers (direct children of CANVAS only). They cannot nest inside frames or groups. Creating a section auto-adopts overlapping siblings. Sections display a title pill with luminance-adaptive text color.++## Hover State++The editor state tracks `hoveredNodeId` — the node currently under the cursor. The renderer draws a shape-aware hover outline (following actual geometry for ellipses, rounded rects, vectors) for visual feedback before selection.++## Undo/Redo++The system uses Figma's **inverse command** pattern. Each undo entry contains the forward changes and their automatically-computed inverse:++| Operation | Forward | Inverse |+|-----------|---------|---------|+| Create node | `{guid, phase: CREATED, ...props}` | `{guid, phase: REMOVED}` |+| Delete node | `{guid, phase: REMOVED}` | `{guid, phase: CREATED, ...allProps}` |+| Change prop | `{guid, fill: "#F00"}` | `{guid, fill: "#00F"}` |+| Move node | `{guid, parentIndex: newParent}` | `{guid, parentIndex: oldParent}` |++Before applying any change, affected fields are snapshotted. The snapshot becomes the inverse.++**Batching** — operations like drag-to-move produce hundreds of position changes per second. These are debounced into a single undo entry. `beginBatch`/`commitBatch` wraps multi-step operations.++## Layout Engine (Yoga)++Figma's auto-layout properties map to Yoga flexbox:++| Figma Property | Yoga Equivalent |+|---|---|+| `stackMode: HORIZONTAL` | `flexDirection: row` |+| `stackMode: VERTICAL` | `flexDirection: column` |+| `stackSpacing` | `gap` |+| `stackPadding` | `padding` |+| `stackJustify: MIN/CENTER/MAX/SPACE_BETWEEN` | `justifyContent` |+| `stackCounterAlign` | `alignItems` |+| `stackPrimarySizing: FIXED/HUG/FILL` | width/height + flex-grow |+| `stackChildPrimaryGrow` | `flexGrow` |+| `stackChildAlignSelf` | `alignSelf` |+| `stackPositioning: ABSOLUTE` | `position: absolute` |++## Hit Testing++Given a point in canvas coordinates, the scene graph returns the topmost visible node at that position. The algorithm:++1. Traverse visible nodes in reverse z-order (top to bottom)+2. Transform the test point into each node's local coordinate system+3. Check if the point is within the node's bounds (including rotation)+4. Return the first match++For marquee selection, `getNodesInRect` returns all nodes whose bounds intersect the given rectangle.++## Extended Fill Types++Fills support six types: SOLID, GRADIENT_LINEAR, GRADIENT_RADIAL, GRADIENT_ANGULAR, GRADIENT_DIAMOND, and IMAGE. Gradient fills carry `gradientStops` (color + position pairs) and a `gradientTransform` (2×3 matrix). Image fills reference blob data via `imageHash` with scale modes (FILL, FIT, CROP, TILE).++## Extended Stroke Properties++Strokes support `cap` (NONE, ROUND, SQUARE, ARROW_LINES, ARROW_EQUILATERAL), `join` (MITER, BEVEL, ROUND), and `dashPattern` (array of dash/gap lengths) in addition to the base color, weight, opacity, visible, and align properties.++## Coordinate System++Nodes store position and size relative to their parent. To get absolute (canvas) coordinates, walk up the parent chain applying transforms. The renderer uses this to draw nested frames with correct positioning.++Rotation is stored in degrees and applied as part of the 2×3 transform matrix. Snap guides and hit testing account for rotation when computing visual bounds.diff --git a/packages/docs/es/development/contributing.md b/packages/docs/es/development/contributing.mdnew file mode 100644index 000000000..08ca85e2d--- /dev/null+++ b/packages/docs/es/development/contributing.md@@ -0,0 +1,94 @@+# Contribuir++## Project Structure++```+packages/+ core/ @open-pencil/core — engine (zero DOM deps)+ src/ Scene graph, renderer, layout, codec, kiwi, types+ cli/ @open-pencil/cli — headless CLI for .fig operations+ src/commands/ info, tree, find, export+src/+ components/ Vue SFCs (canvas, panels, toolbar, color picker)+ properties/ Property panel sections (Appearance, Fill, Stroke, etc.)+ composables/ Canvas input, keyboard shortcuts, rendering hooks+ stores/ Editor state (Vue reactivity)+ engine/ Re-export shims from @open-pencil/core+ kiwi/ Re-export shims from @open-pencil/core+ types.ts Shared types (re-exported from core)+ constants.ts UI colors, defaults, thresholds+desktop/ Tauri v2 (Rust + config)+tests/+ e2e/ Playwright visual regression+ engine/ Unit tests (bun:test)+docs/ VitePress documentation site+openspec/+ specs/ Capability specifications (source of truth)+ changes/ Active and archived changes+```++## Development Setup++```sh+bun install+bun run dev # Editor at localhost:1420+bun run docs:dev # Docs at localhost:5173+```++## Code Style++### Tooling++| Tool | Command | Purpose |+|------|---------|---------|+| oxlint | `bun run lint` | Linting (Rust-based, fast) |+| oxfmt | `bun run format` | Code formatting |+| tsgo | `bun run typecheck` | Type checking (Go-based TypeScript checker) |++Run all checks:++```sh+bun run check+```++### Conventions++- **File names** — kebab-case (`scene-graph.ts`, `use-canvas-input.ts`)+- **Components** — PascalCase Vue SFCs (`EditorCanvas.vue`, `ScrubInput.vue`)+- **Constants** — SCREAMING_SNAKE_CASE+- **Functions/variables** — camelCase+- **Types/interfaces** — PascalCase++### AI Agent Conventions++Developers and AI agents working on the codebase should read `AGENTS.md` in the repo root ([view on GitHub](https://github.com/open-pencil/open-pencil/blob/master/AGENTS.md)). Covers rendering, scene graph, components & instances, layout, UI, file format, Tauri conventions, and known issues.++## Making Changes++1. Check existing [openspec specs](/development/openspec) for the capability you're modifying+2. Create an openspec change if adding new behavior: `openspec new change "my-change"`+3. Implement the change+4. Run `bun run check` and `bun run test`+5. Submit a pull request++## 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.++| 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/layout.ts` | Yoga layout adapter |+| `packages/core/src/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/kiwi/fig-import.ts` | .fig file import logic |+| `packages/cli/src/index.ts` | CLI entry point |+| `packages/cli/src/commands/` | CLI commands (info, tree, find, export) |+| `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 |diff --git a/packages/docs/es/development/openspec.md b/packages/docs/es/development/openspec.mdnew file mode 100644index 000000000..de2d4da98--- /dev/null+++ b/packages/docs/es/development/openspec.md@@ -0,0 +1,107 @@+# Flujo OpenSpec++OpenPencil uses [OpenSpec](https://github.com/Fission-AI/OpenSpec) for spec-driven development. Specifications are the source of truth for what the system does.++## Structure++```+openspec/+├── specs/ # Source of truth: how the system works now+│ ├── scene-graph/+│ │ └── spec.md+│ ├── canvas-rendering/+│ │ └── spec.md+│ ├── auto-layout/+│ │ └── spec.md+│ └── ... # 19 capability specs total+├── changes/ # Proposed changes (one directory per change)+│ └── archive/ # Completed changes+└── config.yaml # Optional configuration+```++## Current Specs++| Capability | Description |+|-----------|-------------|+| scene-graph | Flat Map storage, CRUD, hit testing |+| canvas-rendering | CanvasKit WASM rendering pipeline |+| canvas-navigation | Pan, zoom, hand tool |+| selection-manipulation | Click/marquee select, move, resize, rotate |+| undo-redo | Inverse-command pattern |+| text-editing | Text tool, Paragraph API, font loading |+| pen-tool | Vector network model, bezier curves |+| auto-layout | Yoga WASM flexbox, Shift+A toggle |+| figma-clipboard | Bidirectional Kiwi binary clipboard |+| fig-import | .fig file import pipeline |+| kiwi-codec | Kiwi binary codec, sparse field IDs |+| editor-ui | Vue 3 panels, toolbar, color picker |+| snap-guides | Edge/center snapping, rotation-aware |+| rulers | Canvas rulers, selection highlight |+| group-ungroup | ⌘G/⇧⌘G, position-based sort |+| desktop-app | Tauri v2, macOS menu bar |+| testing | Playwright E2E, bun:test unit |+| scrub-input | Drag-to-scrub numeric inputs |+| tooling | Vite 7, oxlint, oxfmt, tsgo, VitePress |++## Workflow++### 1. Propose a Change++```+/opsx:propose add-dark-mode+```++Creates `openspec/changes/add-dark-mode/` with:+- `proposal.md` — why and what changes+- `design.md` — technical approach+- `specs/` — delta specifications (ADDED/MODIFIED/REMOVED requirements)+- `tasks.md` — implementation checklist++### 2. Implement++```+/opsx:apply+```++Execute tasks from tasks.md, checking off items as they're completed.++### 3. Archive++```+/opsx:archive+```++- Merges delta specs into `openspec/specs/` (the baseline)+- Moves the change to `openspec/changes/archive/`++## Spec Format++Each spec file follows a consistent structure:++```markdown+# capability-name Specification++## Purpose+One-line description of what this capability does.++## Requirements++### Requirement: Name+Description using SHALL/MUST for normative requirements.++#### Scenario: Name+- **WHEN** condition+- **THEN** expected outcome+```++Every requirement has at least one scenario. Scenarios are potential test cases.++## CLI Commands++```sh+openspec list # List active changes+openspec show <name> # Show change details+openspec status --change <name> # Artifact status+openspec archive <name> # Archive completed change+openspec update # Regenerate skills/prompts+```diff --git a/packages/docs/es/development/roadmap.md b/packages/docs/es/development/roadmap.mdnew file mode 100644index 000000000..372b9c142--- /dev/null+++ b/packages/docs/es/development/roadmap.md@@ -0,0 +1,145 @@+# Hoja de ruta++## Phases++### Phase 1: Core Engine ✅++SceneGraph, Skia rendering, basic shapes, selection, zoom/pan, undo/redo.++**Delivered:**+- Scene graph with flat Map storage and parent-child tree+- CanvasKit WASM rendering for all shape types+- Click/shift/marquee selection with resize handles and rotation+- Zoom/pan with keyboard shortcuts and trackpad gestures+- Undo/redo wired into all operations+- Snap guides with edge and center snapping++### Phase 2: Editor UI + Layout ✅++Properties panel, layers panel, toolbar, Yoga layout integration, text editing.++**Delivered:**+- Vue 3 + Reka UI panels (properties, layers, toolbar)+- Properties panel split into sections (Appearance, Fill, Stroke, Typography, Layout, Position)+- ScrubInput component for all numeric inputs+- Color picker (HSV, hex, opacity)+- Layers panel with tree view, drag reorder, visibility toggle+- Auto-layout with Yoga WASM (direction, gap, padding, justify, align)+- Inline text editing with CanvasKit Paragraph API+- System font loading via Local Font Access API+- Canvas rulers with selection highlight++### Phase 3: File I/O + Visual Features ✅++.fig import/export, Kiwi codec, clipboard, sections, pages, advanced rendering.++**Delivered:**+- .fig file import via Kiwi binary codec+- .fig file export with Kiwi encoding, Zstd compression, thumbnail generation+- Save (⌘S) and Save As (⇧⌘S) with native OS dialogs+- Zstd compression via Tauri Rust command (deflate fallback in browser)+- Vendored kiwi-schema with ESM + sparse field ID patches+- Figma-compatible clipboard (bidirectional Kiwi binary)+- Pen tool with vector network model+- vectorNetworkBlob binary encode/decode+- Group/ungroup (⌘G/⇧⌘G)+- Tauri v2 desktop app with native menu bar (macOS/Windows/Linux)+- Sections (S key) with title pills, auto-adopt, luminance-adaptive text+- Multi-page documents with pages panel, per-page viewport+- Hover highlight with shape-aware outlines+- Tier 1 rendering: gradients, image fills, effects, strokes (cap/join/dash), arcs+- Fill type picker with solid/gradient/image tabs and gradient stop editing+- Canvas background color per page+- Fig-import unit tests, layout unit tests, layers-panel E2E tests++### Phase 4: Components + Variables ✅++Components, instances, overrides, variables, collections, modes, image export.++**Delivered:**+- Component creation from frame/group or multi-selection (⌥⌘K)+- Component sets from multiple components (⇧⌘K) with dashed purple border+- Instance creation from components with child cloning and componentId mapping+- Live component-instance sync with override preservation+- Detach instance back to frame (⌥⌘B)+- Go to main component (cross-page navigation)+- Always-visible purple component/instance labels with diamond icon+- Opaque container hit testing (click selects component, double-click enters)+- Right-click context menu with clipboard, z-order, grouping, component, visibility, lock, move-to-page actions+- Z-order manipulation (] bring to front, [ send to back)+- Toggle visibility (⇧⌘H) and lock (⇧⌘L)+- Move nodes between pages via context menu+- Viewport culling, Paint reuse, RAF render coalescing+- Effects panel UI (drop shadow, inner shadow, layer/background/foreground blur)+- Independent corner radius controls (per-corner toggle in Appearance section)+- GitHub Actions CI/CD for Windows (x64, arm64) and macOS (x64, arm64) builds+- Polygon and Star drawing tools with pointCount and starInnerRadius+- Resizable left/right panels via reka-ui Splitter (persistent layout)+- @/ import alias, shared types module (src/types.ts, src/global.d.ts)+- Codebase lint-clean: 0 oxlint warnings, 0 tsgo type errors+- Variables: COLOR type with collections, modes, bindings, FillSection variable picker, .fig import+- Variables dialog: TanStack Table with resizable columns, mode columns, collection tabs with rename, search, demo collections (Primitives/Semantic/Spacing), undo/redo for all variable operations+- Image export: PNG/JPG/WEBP with ExportSection (scale, format, live preview), ⇧⌘E shortcut, context menu+- Canvas-native text editing: TextEditor class in core, phantom textarea, cursor/selection/word boundaries on canvas, caret blinking, selection highlights+- System font enumeration via font-kit Rust crate, OnceLock cache, preload on startup+- Font picker: virtual scroll (reka-ui ListboxVirtualizer), search filter, CSS font preview+- ColorInput component extraction, ColorPicker alpha slider checkerboard fix+- App identity: pencil icon, Cargo crate open_pencil, macOS Dock "OpenPencil"+- Splash loader during WASM initialization+- Rich text style runs: per-selection ⌘B/I/U, StyleRun model, ParagraphBuilder pushStyle/pop, .fig roundtrip+- B/I/U/S toggle buttons in TypographySection+- Double-click (word), triple-click (select all) text selection++**Remaining (deferred to Phase 6):**+- Variant switching+- Variable types: FLOAT, STRING, BOOLEAN editing UI+- Variable-driven theming++### Phase 5: AI Integration & Tooling 🟡++Core extraction, CLI, MCP server, design guidelines, screenshot verification loop.++**Delivered:**+- @open-pencil/core extracted to packages/core/ (zero DOM deps, Bun workspace)+- @open-pencil/cli with headless .fig operations (info, tree, find, export, analyze, node, pages, variables), CanvasKit CPU rasterization, --json output+- JSX renderer: TreeNode builders (Frame, Text, Rectangle, etc.), renderTreeNode/renderJsx, Tailwind-like shorthand props, 27 tests+- jscpd copy-paste detection (15.6% → 0.62%), kiwi-serialize.ts consolidation+- .fig roundtrip tests with LFS fixtures (material3.fig 87K nodes, nuxtui.fig 314K nodes)+- .fig import O(n²) → O(n) fix (37s → 535ms on 87K nodes), ByteBuffer optimization+- test:coverage script+- AI chat: OpenRouter direct (no backend), Stronghold key storage, 26 tools (create_shape, set_fill, set_effects, set_constraints, components, groups, pages, variables, eval_code, etc.), model selector, ⌘J toggle, streaming markdown, Playwright tests with mock transport+- Code panel: sceneNodeToJsx() export, Prism.js highlighting, line numbers, copy button, 14 tests+- Properties panel restructured: Design | Code | AI tabs+- npm publishing preparation for core and cli packages++**Planned:**+- Port remaining figma-use tools (118 total, 26 currently implemented)+- Attached mode: WebSocket to running editor for eval, create, export, screenshot+- Design guidelines system+- AI-driven design workflow via MCP+- Screenshot verification loop++### Phase 6: Polish + Distribution 🔲++Prototyping, comments, desktop distribution, documentation, public launch.++**Planned:**+- Prototyping (frame connections, transitions)+- Comments (pin, threads, resolve)+- Linux Tauri builds (macOS and Windows already covered by CI)+- PWA support+- Documentation site (VitePress)+- Performance optimization (Lighthouse > 90)+- Full Figma compatibility test suite+- Deferred from Phase 4: variant switching, FLOAT/STRING/BOOLEAN variable UI, variable-driven theming++## Timeline++| Phase | Estimated Duration | Status |+|-------|-------------------|--------|+| Phase 1: Core Engine | 3 months | ✅ Complete |+| Phase 2: Editor UI + Layout | 3 months | ✅ Complete |+| Phase 3: File I/O + Visual Features | 2 months | ✅ Complete |+| Phase 4: Components + Variables | 2 months | ✅ Complete |+| Phase 5: AI Integration & Tooling | 2 months | 🟡 In Progress |+| Phase 6: Polish + Distribution | 2 months | 🔲 Planned |diff --git a/packages/docs/es/development/testing.md b/packages/docs/es/development/testing.mdnew file mode 100644index 000000000..3e7cd945c--- /dev/null+++ b/packages/docs/es/development/testing.md@@ -0,0 +1,91 @@+# Pruebas++## Overview++| Type | Framework | Command | Location |+|------|-----------|---------|----------|+| E2E visual regression | Playwright | `bun run test` | `tests/e2e/` |+| Figma CDP reference | Playwright | `bun run test:figma` | `tests/figma/` |+| Unit tests | bun:test | `bun run test:unit` | `tests/engine/` |++## E2E Visual Regression++Playwright creates shapes on the canvas and compares screenshots against baseline PNGs.++```sh+bun run test # Run tests, compare against baselines+bun run test:update # Regenerate baseline screenshots+```++### How It Works++1. Tests load the editor in a headless browser+2. The editor signals readiness via a `data-ready` HTML attribute+3. Tests create shapes via the editor's API+4. Screenshots are taken and compared against baselines using `toMatchSnapshot`+5. Page is reused across test cases for speed (~2s total)++### No-Chrome Test Mode++The editor supports a test mode that hides UI chrome (toolbar, panels) for clean screenshot capture. Activated via URL parameter.++## Figma CDP Reference Tests++A separate Playwright project connects to Figma via Chrome DevTools Protocol to capture reference screenshots for pixel-perfect comparison.++```sh+bun run figma:debug # Launch Figma with debugging port+bun run test:figma # Connect to Figma, capture references+```++Requires Figma desktop app running with `--remote-debugging-port=9222`.++## Unit Tests++Engine unit tests use bun:test and target < 50ms execution:++```sh+bun run test:unit+```++Tests cover:+- Scene graph CRUD operations, parent-child relationships, z-ordering, hit testing+- **Fig-import pipeline** — node type mapping, transforms, fills/strokes/effects, gradients, images, arcs, nested hierarchies (`tests/engine/fig-import.test.ts`)+- **Layout computation** — Yoga auto-layout: direction, gap, padding, justify, align, child sizing (fixed/fill/hug), cross-axis sizing, wrap, nested layouts (`tests/engine/layout.test.ts`)++### Writing Unit Tests++```typescript+import { describe, expect, it } from 'bun:test'+import { SceneGraph } from '../../src/engine/scene-graph'++describe('SceneGraph', () => {+ it('creates and retrieves a node', () => {+ const sg = new SceneGraph()+ const node = sg.createNode('RECTANGLE', sg.root, { name: 'Test' })+ expect(sg.getNode(node.guid)).toBeDefined()+ })+})+```++## E2E Test Coverage++| Test file | Scope |+|-----------|-------|+| `tests/e2e/layers-panel.spec.ts` | Layers panel tree structure, visibility toggles, selection sync |+| `tests/e2e/visual.spec.ts` | Visual regression screenshots for shapes and rendering |++## Test Helpers++| File | Purpose |+|------|---------|+| `tests/helpers/canvas.ts` | Canvas setup and interaction utilities |+| `tests/helpers/figma.ts` | Figma CDP connection helpers |++## Performance Targets++| Metric | Target |+|--------|--------|+| E2E suite total | < 3s |+| Unit test suite total | < 50ms |+| Screenshot comparison | toMatchSnapshot (pixel-level) |diff --git a/packages/docs/es/eval-command.md b/packages/docs/es/eval-command.mdnew file mode 100644index 000000000..9f7c45018--- /dev/null+++ b/packages/docs/es/eval-command.md@@ -0,0 +1,437 @@+# `open-pencil eval` — Figma-like Plugin API for Headless Scripting++## Overview++`bun open-pencil eval <file> --code '<js>'` executes JavaScript against a `.fig` file with a Figma-compatible `figma` global object. This enables headless scripting, batch operations, AI tool execution, and testing — all without the GUI.++The `figma` object mirrors Figma's Plugin API surface as closely as possible, so existing Figma plugin knowledge and code snippets transfer directly.++```bash+# Create a frame, set auto-layout, add children+bun open-pencil eval design.fig --code '+ const frame = figma.createFrame()+ frame.name = "Card"+ frame.resize(300, 200)+ frame.layoutMode = "VERTICAL"+ frame.itemSpacing = 12+ frame.paddingTop = frame.paddingBottom = 16+ frame.paddingLeft = frame.paddingRight = 16+ frame.fills = [{ type: "SOLID", color: { r: 1, g: 1, b: 1 } }]++ const title = figma.createText()+ title.characters = "Hello World"+ title.fontSize = 24+ frame.appendChild(title)++ return { id: frame.id, name: frame.name }+'++# Query nodes+bun open-pencil eval design.fig --code '+ const buttons = figma.currentPage.findAll(n => n.type === "FRAME" && n.name.includes("Button"))+ return buttons.map(b => ({ id: b.id, name: b.name, w: b.width, h: b.height }))+'++# Read from stdin (for multiline scripts / piping)+cat transform.js | bun open-pencil eval design.fig --stdin++# Write changes back+bun open-pencil eval design.fig --code '...' --write+bun open-pencil eval design.fig --code '...' -o modified.fig+```++## Architecture++```+┌──────────────────────────────────────────────────────┐+│ CLI: `open-pencil eval <file> --code '...'` │+│ ↓ │+│ loadDocument(file) → SceneGraph │+│ ↓ │+│ FigmaAPI(sceneGraph) → `figma` proxy object │+│ ↓ │+│ AsyncFunction('figma', wrappedCode)(figmaProxy) │+│ ↓ │+│ print result as JSON / agentfmt │+│ optionally: saveDocument(file) if --write │+└──────────────────────────────────────────────────────┘+```++### Key classes++| 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.) |+| `eval` command | `packages/cli/src/commands/eval.ts` | CLI command that loads doc, creates API, executes code |++### Why in `@open-pencil/core`?++The `FigmaAPI` class lives in core (not CLI) because:+- **AI tools reuse it** — the chat panel's `render` tool can execute JSX through the same API+- **Test scripts** — unit tests can use the API to set up fixtures+- **No DOM deps** — runs headless in Bun, no browser APIs needed++## `FigmaAPI` — Phased Implementation++### Phase 1: Core (MVP for eval command)++These cover ~80% of real plugin scripts:++#### Document & Page++| Figma API | Our implementation | Notes |+|-----------|--------------------|-------|+| `figma.root` | Getter → proxy for root node | `.children` returns page proxies |+| `figma.currentPage` | Getter/setter → first page by default | Settable to any page proxy |+| `figma.currentPage.selection` | Get/set → tracked selection array | |+| `figma.getNodeById(id)` | `graph.getNode(id)` wrapped in proxy | Sync, like Figma's deprecated version |++#### Node Creation++| Figma API | Maps to |+|-----------|---------|+| `figma.createFrame()` | `graph.createNode('FRAME', currentPageId)` |+| `figma.createRectangle()` | `graph.createNode('RECTANGLE', ...)` |+| `figma.createEllipse()` | `graph.createNode('ELLIPSE', ...)` |+| `figma.createText()` | `graph.createNode('TEXT', ...)` |+| `figma.createLine()` | `graph.createNode('LINE', ...)` |+| `figma.createPolygon()` | `graph.createNode('POLYGON', ...)` |+| `figma.createStar()` | `graph.createNode('STAR', ...)` |+| `figma.createComponent()` | `graph.createNode('COMPONENT', ...)` |+| `figma.createPage()` | `graph.addPage(name)` |+| `figma.createSection()` | `graph.createNode('SECTION', ...)` |++#### Node Properties (via `FigmaNode` proxy)++Read/write on any node proxy. Property access maps to `SceneNode` fields:++```ts+// Geometry+node.x, node.y // direct+node.width, node.height // read-only, use node.resize(w, h)+node.rotation // direct+node.resize(w, h) // updates width + height+node.resizeWithoutConstraints(w, h) // same (no constraint engine yet)++// Visual+node.fills // get/set Fill[]+node.strokes // get/set Stroke[]+node.effects // get/set Effect[]+node.opacity // get/set number+node.visible // get/set boolean+node.locked // get/set boolean+node.blendMode // get/set BlendMode+node.clipsContent // get/set boolean++// Corner radius+node.cornerRadius // get/set (number or figma.mixed)+node.topLeftRadius // get/set+node.topRightRadius // get/set+node.bottomLeftRadius // get/set+node.bottomRightRadius // get/set+node.cornerSmoothing // get/set++// Identity+node.id // read-only+node.name // get/set+node.type // read-only+node.parent // read-only → FigmaNode | null+node.removed // read-only boolean+```++#### Tree Operations++```ts+node.children // read-only FigmaNode[]+node.appendChild(child) // reparent to end+node.insertChild(index, child) // reparent at index+node.remove() // graph.deleteNode(id)++// Traversal+node.findAll(callback?) // recursive find+node.findOne(callback) // first match+node.findChild(callback) // direct children only+node.findChildren(callback?) // direct children only+```++#### Auto-layout++```ts+node.layoutMode // 'NONE' | 'HORIZONTAL' | 'VERTICAL'+node.primaryAxisAlignItems // 'MIN' | 'CENTER' | 'MAX' | 'SPACE_BETWEEN'+node.counterAxisAlignItems // 'MIN' | 'CENTER' | 'MAX' | 'BASELINE'+node.itemSpacing // number+node.counterAxisSpacing // number | null+node.paddingTop / Right / Bottom / Left // number+node.layoutWrap // 'NO_WRAP' | 'WRAP'++// Child sizing+node.layoutPositioning // 'AUTO' | 'ABSOLUTE'+node.layoutGrow // 0 | 1+node.layoutSizingHorizontal // 'FIXED' | 'HUG' | 'FILL'+node.layoutSizingVertical // 'FIXED' | 'HUG' | 'FILL'+```++#### Text++```ts+node.characters // get/set (maps to node.text)+node.fontSize // get/set+node.fontName // get/set { family, style }+node.fontWeight // get/set+node.textAlignHorizontal // get/set+node.textAlignVertical // get/set+node.textAutoResize // get/set+node.letterSpacing // get/set+node.lineHeight // get/set+node.maxLines // get/set+node.textCase // get/set+node.textDecoration // get/set+```++#### Stroke details++```ts+node.strokeWeight // get/set (maps to strokes[0].weight)+node.strokeAlign // get/set (maps to strokes[0].align)+node.dashPattern // get/set+```++#### Misc++```ts+figma.mixed // Symbol sentinel for mixed values+figma.group(nodes, parent) // creates GROUP with given children+figma.ungroup(node) // ungroups, reparents children+figma.flatten(nodes) // NOT IMPLEMENTED YET — returns first node+```++#### Export++```ts+node.exportAsync(settings?) // only works if CanvasKit is loaded+ // settings: { format: 'PNG'|'JPG'|'SVG', constraint? }+```++### Phase 2: Components & Instances++| API | Maps to |+|-----|---------|+| `figma.createComponent()` | `graph.createNode('COMPONENT', ...)` |+| `figma.createComponentFromNode(node)` | Convert existing frame to component |+| `figma.combineAsVariants(components, parent)` | Create COMPONENT_SET |+| Node: `node.createInstance()` | `graph.createInstance(componentId, parentId)` |+| Node: `node.detachInstance()` | `graph.detachInstance(id)` |+| `figma.getNodeById(id).mainComponent` | `graph.getMainComponent(id)` |++### Phase 3: Variables++| API | Maps to |+|-----|---------|+| `figma.variables.getLocalVariables(type?)` | `graph.variables` filtered |+| `figma.variables.getLocalVariableCollections()` | `graph.variableCollections` |+| `figma.variables.createVariable(name, collection, type)` | `graph.addVariable(...)` |+| `figma.variables.createVariableCollection(name)` | `graph.addCollection(...)` |+| `figma.variables.getVariableById(id)` | `graph.variables.get(id)` |+| `node.setBoundVariable(field, variable)` | `graph.bindVariable(...)` |+| `node.boundVariables` | getter from SceneNode |++### Phase 4: Styles & Advanced++| API | Notes |+|-----|-------|+| `figma.createPaintStyle()` | Requires style storage in SceneGraph |+| `figma.createTextStyle()` | Requires style storage in SceneGraph |+| `figma.createEffectStyle()` | Requires style storage in SceneGraph |+| `figma.loadFontAsync(fontName)` | No-op (we don't have font loading constraints) |+| `figma.listAvailableFontsAsync()` | Return system fonts if available |+| Boolean operations (`union`, `subtract`, `intersect`, `exclude`) | Requires path boolean engine |+| `figma.createNodeFromJSXAsync(jsx)` | Port figma-use's JSX renderer |++## `FigmaNode` Proxy Design++The proxy wraps a `SceneNode` and translates Figma property names to our internal names. Key mappings:++```ts+const PROPERTY_MAP: Record<string, string> = {+ // Figma name → SceneNode field name (only where they differ)+ 'characters': 'text',+ 'strokeWeight': → computed from strokes[0].weight,+ 'strokeAlign': → computed from strokes[0].align,+ 'fontName': → computed from { family: fontFamily, style: ... },+ 'primaryAxisAlignItems': 'primaryAxisAlign',+ 'counterAxisAlignItems': 'counterAxisAlign',+ 'primaryAxisSizingMode': 'primaryAxisSizing', // value mapping: 'AUTO' → 'HUG', 'FIXED' → 'FIXED'+ 'counterAxisSizingMode': 'counterAxisSizing',+ 'layoutSizingHorizontal': → computed from primaryAxisSizing / counterAxisSizing depending on layoutMode+ 'layoutSizingVertical': → computed+}+```++Methods on the proxy:++```ts+class FigmaNode {+ // The proxy is created via: new Proxy(target, handler)+ // where handler.get intercepts property reads and handler.set intercepts writes++ resize(width: number, height: number): void+ resizeWithoutConstraints(width: number, height: number): void+ remove(): void+ appendChild(child: FigmaNode): void+ insertChild(index: number, child: FigmaNode): void+ findAll(callback?: (node: FigmaNode) => boolean): FigmaNode[]+ findOne(callback: (node: FigmaNode) => boolean): FigmaNode | null+ findChild(callback: (node: FigmaNode) => boolean): FigmaNode | null+ findChildren(callback?: (node: FigmaNode) => boolean): FigmaNode[]+ exportAsync(settings?: ExportSettings): Promise<Uint8Array>++ // Components (Phase 2)+ createInstance(): FigmaNode+ detachInstance(): void+ get mainComponent(): FigmaNode | null+}+```++## CLI Command++```+bun open-pencil eval <file> [options]++Arguments:+ file .fig file to operate on++Options:+ --code, -c JavaScript code to execute (has access to `figma` global)+ --stdin Read code from stdin instead of --code+ --write, -w Write changes back to the input file+ -o, --output Write to a different file+ --json Output result as JSON (default for non-TTY)+ --quiet, -q Suppress output, only write file+```++### Execution model++1. Load `.fig` → `SceneGraph`+2. Create `FigmaAPI(graph)` → `figma` proxy+3. Wrap user code in async function: `return (async () => { <code> })()`+4. Execute with `figma` as sole argument+5. Print return value (JSON or agentfmt)+6. If `--write` or `-o`: serialize `SceneGraph` back to `.fig`++### Return value formatting++- `undefined` / `void` → no output+- Primitives → printed directly+- Objects/arrays → `JSON.stringify(result, null, 2)` or agentfmt tables+- `FigmaNode` → serialized as `{ id, type, name, x, y, width, height, fills, ... }`+- Arrays of `FigmaNode` → serialized as list++## 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`:++```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)+execute: async ({ type, x, y, width, height }) => {+ const frame = figma.createFrame()+ frame.resize(width, height)+ frame.x = x+ frame.y = y+ return { id: frame.id }+}+```++This ensures CLI scripts and AI tools behave identically.++## File Layout++```+packages/core/src/+ figma-api.ts # FigmaAPI class + FigmaNode proxy (Phase 1–4)+ figma-api.test.ts # Unit tests against headless SceneGraph++packages/cli/src/commands/+ eval.ts # CLI command++packages/cli/src/commands/eval.test.ts # Integration tests+```++## Test Plan++### Unit tests (`packages/core/src/figma-api.test.ts`)++1. **Node creation** — each `createX()` creates correct type, added to current page+2. **Property access** — `.fills`, `.x`, `.width`, `.name`, `.characters` read/write correctly+3. **Resize** — `.resize(w, h)` updates width/height+4. **Tree operations** — `.appendChild()`, `.insertChild()`, `.remove()`, `.parent`, `.children`+5. **Traversal** — `.findAll()`, `.findOne()`, `.findChild()`, `.findChildren()` with callbacks+6. **Auto-layout** — `.layoutMode`, `.itemSpacing`, `.paddingTop`, etc.+7. **Text** — `.characters` maps to `.text`, `.fontName` maps to `{ family, style }`+8. **Mixed values** — `.cornerRadius` returns `figma.mixed` when corners differ+9. **Selection** — `figma.currentPage.selection` get/set+10. **Page switching** — `figma.currentPage = page2` works+11. **Group/ungroup** — `figma.group()` creates group, `figma.ungroup()` dissolves it+12. **Clone** — node creation produces independent copies++### CLI integration tests (`packages/cli/src/commands/eval.test.ts`)++1. **Basic eval** — `eval test.fig --code 'return figma.currentPage.name'` → page name+2. **Create + read** — create a frame, return its properties+3. **Query nodes** — `findAll` returns correct nodes+4. **Write back** — `--write` saves changes, reloading shows them+5. **Stdin** — `echo 'return 42' | bun open-pencil eval test.fig --stdin` → `42`+6. **JSON output** — `--json` returns valid JSON+7. **Error handling** — syntax errors, runtime errors reported cleanly++## Implementation Order++1. **`FigmaNode` proxy** — property mapping, `.resize()`, `.remove()`, tree methods+2. **`FigmaAPI` class** — `createFrame/Rectangle/...`, `.root`, `.currentPage`, `.getNodeById()`, `.mixed`, `.group()`+3. **CLI `eval` command** — argument parsing, code wrapping, output formatting+4. **Unit tests** — all 12 test groups above+5. **CLI integration tests** — all 7 test groups above+6. **Wire to AI tools** — refactor `src/ai/tools.ts` to use `FigmaAPI` where possible+7. **Phase 2** — components & instances+8. **Phase 3** — variables+9. **Phase 4** — styles, boolean ops, JSX renderer++## Property Mapping Reference++| Figma Property | SceneNode Field | Type | Notes |+|---------------|-----------------|------|-------|+| `characters` | `text` | `string` | |+| `fontName` | `fontFamily` + `fontWeight` + `italic` | `{ family, style }` | Computed: `style` = "Bold Italic" etc. |+| `strokeWeight` | `strokes[0].weight` | `number` | Computed |+| `strokeAlign` | `strokes[0].align` | `string` | Computed |+| `primaryAxisAlignItems` | `primaryAxisAlign` | `string` | |+| `counterAxisAlignItems` | `counterAxisAlign` | `string` | |+| `layoutSizingHorizontal` | `primaryAxisSizing` or `counterAxisSizing` | `string` | Depends on `layoutMode` |+| `layoutSizingVertical` | (opposite of horizontal) | `string` | |+| `absoluteTransform` | computed from `x`, `y`, `rotation` | `Transform` | Read-only |+| `absoluteBoundingBox` | `getAbsoluteBounds(id)` | `Rect` | Read-only |+| All others | Same name | Same type | Direct passthrough |++## Open Questions++1. **Font loading**: `figma.loadFontAsync()` — should it be a no-op (we don't have font gating) or should we track loaded fonts?+ → **Decision: No-op that returns resolved Promise.** We don't gate text editing on font loading.++2. **Export in headless mode**: `node.exportAsync()` requires CanvasKit. Should eval load CanvasKit?+ → **Decision: Optional.** If CanvasKit is available (via `--with-canvaskit` flag or env), enable export. Otherwise, throw "Export requires CanvasKit" error.++3. **`figma.mixed` symbol**: Should we use the actual Figma symbol or our own?+ → **Decision: Our own `Symbol('mixed')`.** Exposed as `figma.mixed`.++4. **Undo**: `figma.commitUndo()` / `figma.triggerUndo()` — relevant in headless?+ → **Decision: No-op in CLI.** Undo only matters in the live editor. The AI tools can add undo support separately via EditorStore.++5. **Write format**: Should `--write` produce `.fig` (Kiwi binary) or also support `.json`?+ → **Decision: `.fig` only for now.** JSON export is a separate feature.diff --git a/packages/docs/es/reference/file-format.md b/packages/docs/es/reference/file-format.mdnew file mode 100644index 000000000..5fd8620d3--- /dev/null+++ b/packages/docs/es/reference/file-format.md@@ -0,0 +1,71 @@+# Formato de archivo++## .fig File Structure++```+┌─────────────────────────────────┐+│ Magic header: "fig-kiwi" (8B) │+│ Version (4B uint32 LE) │+│ Schema length (4B uint32 LE) │+│ Compressed Kiwi schema │+│ Message length (4B uint32 LE) │+│ Compressed Kiwi message │ ← NodeChange[] (entire document)+│ Blob data │ ← Images, vector networks, fonts+└─────────────────────────────────┘+```++## Import Pipeline++```+.fig file → Parse header → Decompress Zstd → Decode Kiwi schema+ → Decode Message → NodeChange[] → Build SceneGraph+ → Resolve blob refs → Render on canvas+```++## Export Pipeline++```+SceneGraph → NodeChange[] → Kiwi encode → Compress (Zstd/deflate)+ → Build ZIP (header + schema + message + thumbnail.png)+ → Write .fig file+```++Export uses <kbd>⌘</kbd><kbd>S</kbd> (Save) and <kbd>⇧</kbd><kbd>⌘</kbd><kbd>S</kbd> (Save As) with native OS dialogs on the desktop app. The exported file includes a `thumbnail.png` required by Figma for file preview. Compression uses Zstd via Tauri Rust command on desktop, with deflate fallback in the browser. The ZIP archive is assembled in Rust on desktop for correct Zstd frame headers (content size included).++## Kiwi Binary Codec++The codec handles Figma's 194-definition Kiwi schema with NodeChange as the central type (~390 fields). Key components:++- **kiwi-schema** — vendored from evanw/kiwi, patched for ESM and sparse field IDs+- **codec.ts** — encode/decode Messages using the Kiwi schema+- **protocol.ts** — wire format parsing and message type detection+- **schema.ts** — 194 message/enum/struct definitions++### Sparse Field IDs++Figma's schema uses non-contiguous field IDs (e.g., 1, 2, 5, 10 with gaps). The vendored kiwi-schema parser is patched to handle this correctly.++### Compression++.fig files use Zstd compression for both the schema and message payloads. Decompression uses the `fzstd` library. For export, Zstd compression is offloaded to a Tauri Rust command on the desktop app (better performance, correct frame headers). In the browser, deflate via `fflate` is used as a fallback. Clipboard encoding also uses `fflate`.++## Supported Formats++| Format | Import | Export |+|--------|--------|--------|+| .fig (Figma) | ✅ | ✅ |+| .svg | Planned | Planned |+| .png | Planned | Planned |+| .pdf | — | Planned |++See [Roadmap](/development/roadmap) for planned format support timeline.++## Clipboard Format++Copy/paste uses the same Kiwi binary encoding:++1. **Copy** — encode selected NodeChange[] to Kiwi binary, compress, write to clipboard as `application/x-figma-design` MIME type+2. **Paste** — read clipboard, decompress, decode Kiwi binary, create nodes in scene graph+3. **Synchronous** — encoding happens in the copy event handler (not async Clipboard API) to ensure browser compatibility++This enables bidirectional clipboard between OpenPencil and Figma.diff --git a/packages/docs/es/reference/keyboard-shortcuts.md b/packages/docs/es/reference/keyboard-shortcuts.mdnew file mode 100644index 000000000..2c9aa2621--- /dev/null+++ b/packages/docs/es/reference/keyboard-shortcuts.md@@ -0,0 +1,120 @@+# Atajos de teclado++Mapa completo de atajos compatibles con Figma.++::: tip Symbol Legend+⌘ = Cmd (Mac) / Ctrl (Win/Linux) · ⇧ = Shift · ⌥ = Alt/Option · ⌃ = Ctrl · ⌫ = Backspace+:::++## Tools++| Key | Tool | Status |+|-----|------|--------|+| <kbd>V</kbd> | Move/Select | ✅ |+| <kbd>K</kbd> | Scale | 🔲 |+| <kbd>H</kbd> | Hand | ✅ |+| <kbd>F</kbd> | Frame | ✅ |+| <kbd>S</kbd> | Section | ✅ |+| <kbd>R</kbd> | Rectangle | ✅ |+| <kbd>O</kbd> | Ellipse | ✅ |+| <kbd>L</kbd> | Line | ✅ |+| — | Polygon | ✅ (flyout only) |+| — | Star | ✅ (flyout only) |+| <kbd>⇧</kbd><kbd>L</kbd> | Arrow | 🔲 |+| <kbd>P</kbd> | Pen | ✅ |+| <kbd>⇧</kbd><kbd>P</kbd> | Pencil | 🔲 |+| <kbd>T</kbd> | Text | ✅ |+| <kbd>C</kbd> | Comment | 🔲 |+| <kbd>I</kbd> | Eyedropper | 🔲 |++## File++| Shortcut | Action | Status |+|----------|--------|--------|+| <kbd>⌘</kbd><kbd>N</kbd> | New Window | 🔲 |+| <kbd>⌘</kbd><kbd>O</kbd> | Open File | ✅ |+| <kbd>⌘</kbd><kbd>W</kbd> | Close Tab | 🔲 |+| <kbd>⌘</kbd><kbd>S</kbd> | Save | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>S</kbd> | Save As | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>E</kbd> | Export… | ✅ |++## Edit++| Shortcut | Action | Status |+|----------|--------|--------|+| <kbd>⌘</kbd><kbd>Z</kbd> | Undo | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>Z</kbd> | Redo | ✅ |+| <kbd>⌘</kbd><kbd>X</kbd> | Cut | ✅ |+| <kbd>⌘</kbd><kbd>C</kbd> | Copy | ✅ |+| <kbd>⌘</kbd><kbd>V</kbd> | Paste | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>V</kbd> | Paste Over Selection | 🔲 |+| <kbd>⌘</kbd><kbd>D</kbd> | Duplicate | ✅ |+| <kbd>⌫</kbd> | Delete | ✅ |+| <kbd>⌘</kbd><kbd>A</kbd> | Select All | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>A</kbd> | Select Inverse | 🔲 |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>C</kbd> | Copy Properties | 🔲 |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>V</kbd> | Paste Properties | 🔲 |++## View++| Shortcut | Action | Status |+|----------|--------|--------|+| <kbd>⌘</kbd><kbd>'</kbd> | Pixel Grid | 🔲 |+| <kbd>⌃</kbd><kbd>G</kbd> | Layout Guides | 🔲 |+| <kbd>⇧</kbd><kbd>R</kbd> | Rulers | 🔲 |+| <kbd>⌘</kbd><kbd>\\</kbd> | Show/Hide UI | 🔲 |+| <kbd>⌘</kbd><kbd>=</kbd> | Zoom In | ✅ |+| <kbd>⌘</kbd><kbd>-</kbd> | Zoom Out | ✅ |+| <kbd>⌘</kbd><kbd>0</kbd> | Zoom to 100% | ✅ |+| <kbd>⌘</kbd><kbd>1</kbd> | Zoom to Fit | 🔲 |+| <kbd>⌘</kbd><kbd>2</kbd> | Zoom to Selection | 🔲 |+| <kbd>⌘</kbd><kbd>J</kbd> | Toggle AI Chat | ✅ |++## Object++| Shortcut | Action | Status |+|----------|--------|--------|+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>G</kbd> | Frame Selection | 🔲 |+| <kbd>⌘</kbd><kbd>G</kbd> | Group Selection | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>G</kbd> | Ungroup | ✅ |+| <kbd>⇧</kbd><kbd>A</kbd> | Add Auto Layout | ✅ |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>K</kbd> | Create Component | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>K</kbd> | Create Component Set | ✅ |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>B</kbd> | Detach Instance | ✅ |+| <kbd>⌘</kbd><kbd>]</kbd> | Bring Forward | 🔲 |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>]</kbd> | Bring to Front | 🔲 |+| <kbd>]</kbd> | Bring to Front | ✅ |+| <kbd>⌘</kbd><kbd>[</kbd> | Send Backward | 🔲 |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>[</kbd> | Send to Back | 🔲 |+| <kbd>[</kbd> | Send to Back | ✅ |+| <kbd>⇧</kbd><kbd>H</kbd> | Flip Horizontal | 🔲 |+| <kbd>⇧</kbd><kbd>V</kbd> | Flip Vertical | 🔲 |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>H</kbd> | Toggle Visibility | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>L</kbd> | Toggle Lock | ✅ |+| <kbd>⌘</kbd><kbd>E</kbd> | Flatten | 🔲 |++## Text++| Shortcut | Action | Status |+|----------|--------|--------|+| <kbd>⌘</kbd><kbd>B</kbd> | Bold | ✅ |+| <kbd>⌘</kbd><kbd>I</kbd> | Italic | ✅ |+| <kbd>⌘</kbd><kbd>U</kbd> | Underline | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>X</kbd> | Strikethrough | 🔲 |++## Canvas Interaction++| Input | Action | Status |+|-------|--------|--------|+| Click | Select node | ✅ |+| <kbd>Shift</kbd>+Click | Add/remove from selection | ✅ |+| <kbd>Alt</kbd>+Drag | Duplicate and move | ✅ |+| <kbd>Shift</kbd>+Drag (draw) | Constrain to square/circle | ✅ |+| <kbd>Shift</kbd>+Drag (resize) | Maintain aspect ratio | ✅ |+| <kbd>Shift</kbd>+Drag (rotate) | Snap to 15° | ✅ |+| Middle mouse drag | Pan | ✅ |+| Scroll | Pan | ✅ |+| <kbd>Ctrl</kbd>+Scroll / Pinch | Zoom | ✅ |+| Double-click text | Edit text inline | ✅ |+| Drag onto frame | Reparent into frame | ✅ |+| <kbd>Escape</kbd> | Deselect / Cancel | ✅ |diff --git a/packages/docs/es/reference/mcp-tools.md b/packages/docs/es/reference/mcp-tools.mdnew file mode 100644index 000000000..21f06a4e8--- /dev/null+++ b/packages/docs/es/reference/mcp-tools.md@@ -0,0 +1,140 @@+# Servidor MCP++OpenPencil includes an MCP (Model Context Protocol) server that lets AI coding tools — Claude Code, Cursor, Windsurf, etc. — read and modify `.fig` files headlessly.++Two transports: **stdio** for MCP clients, **HTTP** for everything else.++## Install++```sh+bun add -g @open-pencil/mcp+```++## Stdio (Claude Code, Cursor, etc.)++Add to your MCP config (e.g. `~/.claude/settings.json` or `.cursor/mcp.json`):++```json+{+ "mcpServers": {+ "open-pencil": {+ "command": "openpencil-mcp"+ }+ }+}+```++Or run from source without installing:++::: code-group+```json [Bun]+{+ "mcpServers": {+ "open-pencil": {+ "command": "bun",+ "args": ["/path/to/open-pencil/packages/mcp/src/index.ts"]+ }+ }+}+```+```json [Node.js]+{+ "mcpServers": {+ "open-pencil": {+ "command": "npx",+ "args": ["tsx", "/path/to/open-pencil/packages/mcp/src/index.ts"]+ }+ }+}+```+:::++## HTTP++For browser extensions, scripts, CI, or any HTTP client:++```sh+openpencil-mcp-http+```++Or from source: `bun packages/mcp/src/http.ts` / `npx tsx packages/mcp/src/http.ts`++Starts on port 3100 (override with `PORT` env var). Endpoints:++- `GET /health` — server status+- `POST /mcp` — MCP Streamable HTTP (SSE). Sessions via `mcp-session-id` header.++## Workflow++1. **Open** — `open_file` to load an existing `.fig`, or `new_document` for a blank canvas+2. **Read** — `get_page_tree`, `find_nodes`, `get_node`, `list_pages`+3. **Create** — `create_shape`, `render` (JSX)+4. **Modify** — `set_fill`, `set_stroke`, `set_layout`, `update_node`, `set_effects`+5. **Structure** — `reparent_node`, `group_nodes`, `clone_node`, `delete_node`+6. **Save** — `save_file` to write back to `.fig`++## Tools (29)++### Document++| Tool | Description |+|------|-------------|+| `open_file` | Open a `.fig` file for editing |+| `save_file` | Save the current document to a `.fig` file |+| `new_document` | Create a new empty document |++### Read++| Tool | Description |+|------|-------------|+| `get_selection` | Get currently selected nodes |+| `get_page_tree` | Get the full node tree of the current page |+| `get_node` | Get detailed properties of a node by ID |+| `find_nodes` | Find nodes by name pattern and/or type |+| `list_pages` | List all pages |+| `list_variables` | List design variables |+| `list_collections` | List variable collections |++### Create++| Tool | Description |+|------|-------------|+| `create_shape` | Create a shape (FRAME, RECTANGLE, ELLIPSE, TEXT, LINE, STAR, POLYGON, SECTION) |+| `render` | Render JSX to design nodes — create entire component trees in one call |+| `create_component` | Convert a frame/group into a component |+| `create_instance` | Create an instance of a component |++### Modify++| Tool | Description |+|------|-------------|+| `set_fill` | Set fill color (hex) |+| `set_stroke` | Set stroke color, weight, alignment |+| `set_effects` | Add shadow or blur effects |+| `update_node` | Update position, size, opacity, corner radius, text, font |+| `set_layout` | Set auto-layout (flexbox) — direction, spacing, padding, alignment |+| `set_constraints` | Set resize constraints |++### Structure++| Tool | Description |+|------|-------------|+| `delete_node` | Delete a node |+| `clone_node` | Duplicate a node |+| `rename_node` | Rename a node |+| `reparent_node` | Move a node into a different parent |+| `select_nodes` | Select nodes by ID |+| `group_nodes` | Group nodes |+| `ungroup_node` | Ungroup a group |++### Navigation++| Tool | Description |+|------|-------------|+| `switch_page` | Switch to a page by name or ID |++### Escape Hatch++| Tool | Description |+|------|-------------|+| `eval` | Execute JavaScript with full Figma Plugin API access |diff --git a/packages/docs/es/reference/node-types.md b/packages/docs/es/reference/node-types.mdnew file mode 100644index 000000000..e7447724e--- /dev/null+++ b/packages/docs/es/reference/node-types.md@@ -0,0 +1,194 @@+# Tipos de nodo++The scene graph supports 28 node types from Figma's Kiwi schema. Each node is identified by a GUID (`sessionID:localID`) and has a parent reference via `parentIndex`. The OpenPencil engine's `NodeType` union currently uses 17 of these types.++## Type Table++28 Figma schema types + 1 synthetic engine type. Types marked ✅ are in the engine's `NodeType` union (17 total).++| Type | ID | Description | Engine |+|------|----|-------------|--------|+| DOCUMENT | 1 | Root node, one per file | — |+| CANVAS | 2 | Page | ✅ |+| GROUP | 3 | Group container | ✅ |+| FRAME | 4 | Primary container (artboard), supports auto-layout | ✅ |+| BOOLEAN_OPERATION | 5 | Union/subtract/intersect/exclude result | |+| VECTOR | 6 | Freeform vector path | ✅ |+| STAR | 7 | Star shape | ✅ |+| LINE | 8 | Line | ✅ |+| ELLIPSE | 9 | Ellipse/circle, supports arc data | ✅ |+| RECTANGLE | 10 | Rectangle | ✅ |+| REGULAR_POLYGON | 11 | Regular polygon (3–12 sides, engine uses `POLYGON`) | ✅ |+| ROUNDED_RECTANGLE | 12 | Rectangle with smooth corners | ✅ |+| TEXT | 13 | Text with rich formatting | ✅ |+| SLICE | 14 | Export region | |+| SYMBOL | 15 | Component (main, engine uses `COMPONENT`) | ✅ |+| INSTANCE | 16 | Component instance | ✅ |+| STICKY | 17 | FigJam sticky note | |+| SHAPE_WITH_TEXT | 18 | FigJam shape | ✅ |+| CONNECTOR | 19 | Connector line between nodes | ✅ |+| CODE_BLOCK | 20 | FigJam code block | |+| WIDGET | 21 | Plugin widget | |+| STAMP | 22 | FigJam stamp | |+| MEDIA | 23 | Video/GIF | |+| HIGHLIGHT | 24 | FigJam highlight | |+| SECTION | 25 | Canvas section (organizational, top-level only) | ✅ |+| SECTION_OVERLAY | 26 | Section overlay | |+| WASHI_TAPE | 27 | FigJam washi tape | |+| VARIABLE | 28 | Variable definition node | |+| COMPONENT_SET | — | Variant group container (synthetic, mapped from SYMBOL) | ✅ |++### Engine NodeType Union (17 types)++The engine's `NodeType` uses simplified names. Some differ from the Kiwi schema:+- `COMPONENT` → Kiwi `SYMBOL` (ID 15)+- `COMPONENT_SET` → variant group container (no dedicated Kiwi ID, mapped from SYMBOL with variants)+- `POLYGON` → Kiwi `REGULAR_POLYGON` (ID 11)++```typescript+type NodeType =+ | 'CANVAS' | 'FRAME' | 'RECTANGLE' | 'ROUNDED_RECTANGLE'+ | 'ELLIPSE' | 'TEXT' | 'LINE' | 'STAR' | 'POLYGON'+ | 'VECTOR' | 'GROUP' | 'SECTION'+ | 'COMPONENT' | 'COMPONENT_SET' | 'INSTANCE'+ | 'CONNECTOR' | 'SHAPE_WITH_TEXT'+```++## Node Hierarchy++```+Document+├── Canvas (Page 1)+│ ├── Section (top-level only, title pill, auto-adopts siblings)+│ │ ├── Frame+│ │ │ └── ...children+│ │ └── Rectangle+│ ├── Frame+│ │ ├── Rectangle+│ │ ├── Text+│ │ └── Frame (nested)+│ │ ├── Ellipse+│ │ └── Instance (→ references Component)+│ ├── Component+│ │ └── ...children+│ ├── Group+│ │ └── ...children+│ └── BooleanOperation+│ └── ...operand shapes+└── Canvas (Page 2)+ └── ...+```++## Core Properties++Every node carries these fields (subset of NodeChange):++### Identity & Tree++- `guid` — unique identifier (`sessionID:localID`)+- `type` — node type enum+- `name` — display name+- `phase` — CREATED or REMOVED+- `parentIndex` — parent GUID + position string for z-ordering++### Transform++- `size` — width/height vector+- `transform` — 2×3 affine matrix+- `rotation` — degrees++### Appearance++- `fillPaints[]` — fill colors/gradients/images+- `strokePaints[]` — stroke colors+- `effects[]` — shadows, blurs+- `opacity` — 0–1+- `blendMode` — NORMAL, MULTIPLY, SCREEN, etc.++### Stroke++- `strokeWeight` — stroke thickness+- `strokeAlign` — inside / center / outside+- `strokeCap` — butt / round / square+- `strokeJoin` — miter / bevel / round+- `dashPattern[]` — dash/gap lengths++### Corners++- `cornerRadius` — uniform radius+- `cornerSmoothing` — squircle amount (0–1)+- Per-corner radii when `rectangleCornerRadiiIndependent` is true++### Visibility++- `visible` — show/hide+- `locked` — prevent editing++## Type-Specific Properties++### Text++`fontSize`, `fontName`, `lineHeight`, `letterSpacing`, `textAlignHorizontal`, `textAlignVertical`, `textAutoResize`, `textData` (characters, style overrides, baselines, glyphs)++### Vector++`vectorData` (vectorNetworkBlob, normalizedSize), `fillGeometry[]`, `strokeGeometry[]`, `handleMirroring`, `arcData`++### Layout (Frame)++`stackMode`, `stackSpacing`, `stackPadding`, `stackJustify`, `stackCounterAlign`, `stackPrimarySizing`, `stackCounterSizing`, `stackChildPrimaryGrow`, `stackChildAlignSelf`++### Component++`symbolData`, `componentKey`, `componentPropDefs[]`, `symbolDescription`++### Instance++`overriddenSymbolID`, `symbolData.symbolOverrides[]`, `componentPropRefs[]`, `componentPropAssignments[]`++## Paint++```typescript+interface Fill {+ type: 'SOLID' | 'GRADIENT_LINEAR' | 'GRADIENT_RADIAL' |+ 'GRADIENT_ANGULAR' | 'GRADIENT_DIAMOND' | 'IMAGE'+ color: Color // {r, g, b, a} 0–1 floats+ opacity: number // 0–1+ visible: boolean+ blendMode?: BlendMode+ gradientStops?: GradientStop[] // for gradients+ gradientTransform?: GradientTransform // 2×3 matrix+ imageHash?: string // for image fills+ imageScaleMode?: 'FILL' | 'FIT' | 'CROP' | 'TILE'+ imageTransform?: GradientTransform+}+```++## Effect++```typescript+interface Effect {+ type: 'DROP_SHADOW' | 'INNER_SHADOW' | 'LAYER_BLUR' |+ 'BACKGROUND_BLUR' | 'FOREGROUND_BLUR'+ color: Color+ offset: { x: number; y: number }+ radius: number+ spread: number+ visible: boolean+}+```++## Stroke++```typescript+interface Stroke {+ color: Color+ weight: number+ opacity: number+ visible: boolean+ align: 'INSIDE' | 'CENTER' | 'OUTSIDE'+ cap?: 'NONE' | 'ROUND' | 'SQUARE' | 'ARROW_LINES' | 'ARROW_EQUILATERAL'+ join?: 'MITER' | 'BEVEL' | 'ROUND'+ dashPattern?: number[]+}+```diff --git a/packages/docs/es/reference/scene-graph.md b/packages/docs/es/reference/scene-graph.mdnew file mode 100644index 000000000..e4b5b9dfe--- /dev/null+++ b/packages/docs/es/reference/scene-graph.md@@ -0,0 +1,99 @@+# Grafo de escena++## In-Memory Representation++Nodes live in a flat `Map<string, Node>` keyed by GUID string. The tree structure is maintained via `parentIndex` references. This gives O(1) lookup by ID and efficient traversal.++```typescript+interface SceneGraph {+ nodes: Map<string, Node>+ root: string++ getNode(id: string): Node+ getChildren(id: string): Node[]+ getParent(id: string): Node | null+ getPages(): Node[]++ createNode(type: NodeType, parent: string, props: Partial<NodeChange>): Node+ updateNode(id: string, changes: Partial<NodeChange>): void+ deleteNode(id: string): void+ moveNode(id: string, newParent: string, position: string): void+ addPage(name: string): Node+ deletePage(id: string): void+ renamePage(id: string, name: string): void++ findByType(type: NodeType): Node[]+ findByName(pattern: string): Node[]+ hitTest(point: Vector, canvas: string): Node | null+ getNodesInRect(rect: Rect, canvas: string): Node[]+}+```++## Pages++Documents support multiple pages (CANVAS nodes as direct children of the DOCUMENT root). Each page has its own child tree and independent viewport state (panX, panY, zoom, pageColor). The editor tracks `currentPageId` and renders only the active page's children.++## Sections++SECTION nodes are top-level organizational containers (direct children of CANVAS only). They cannot nest inside frames or groups. Creating a section auto-adopts overlapping siblings. Sections display a title pill with luminance-adaptive text color.++## Hover State++The editor state tracks `hoveredNodeId` — the node currently under the cursor. The renderer draws a shape-aware hover outline (following actual geometry for ellipses, rounded rects, vectors) for visual feedback before selection.++## Undo/Redo++The system uses Figma's **inverse command** pattern. Each undo entry contains the forward changes and their automatically-computed inverse:++| Operation | Forward | Inverse |+|-----------|---------|---------|+| Create node | `{guid, phase: CREATED, ...props}` | `{guid, phase: REMOVED}` |+| Delete node | `{guid, phase: REMOVED}` | `{guid, phase: CREATED, ...allProps}` |+| Change prop | `{guid, fill: "#F00"}` | `{guid, fill: "#00F"}` |+| Move node | `{guid, parentIndex: newParent}` | `{guid, parentIndex: oldParent}` |++Before applying any change, affected fields are snapshotted. The snapshot becomes the inverse.++**Batching** — operations like drag-to-move produce hundreds of position changes per second. These are debounced into a single undo entry. `beginBatch`/`commitBatch` wraps multi-step operations.++## Layout Engine (Yoga)++Figma's auto-layout properties map to Yoga flexbox:++| Figma Property | Yoga Equivalent |+|---|---|+| `stackMode: HORIZONTAL` | `flexDirection: row` |+| `stackMode: VERTICAL` | `flexDirection: column` |+| `stackSpacing` | `gap` |+| `stackPadding` | `padding` |+| `stackJustify: MIN/CENTER/MAX/SPACE_BETWEEN` | `justifyContent` |+| `stackCounterAlign` | `alignItems` |+| `stackPrimarySizing: FIXED/HUG/FILL` | width/height + flex-grow |+| `stackChildPrimaryGrow` | `flexGrow` |+| `stackChildAlignSelf` | `alignSelf` |+| `stackPositioning: ABSOLUTE` | `position: absolute` |++## Hit Testing++Given a point in canvas coordinates, the scene graph returns the topmost visible node at that position. The algorithm:++1. Traverse visible nodes in reverse z-order (top to bottom)+2. Transform the test point into each node's local coordinate system+3. Check if the point is within the node's bounds (including rotation)+4. Return the first match++For marquee selection, `getNodesInRect` returns all nodes whose bounds intersect the given rectangle.++## Extended Fill Types++Fills support six types: SOLID, GRADIENT_LINEAR, GRADIENT_RADIAL, GRADIENT_ANGULAR, GRADIENT_DIAMOND, and IMAGE. Gradient fills carry `gradientStops` (color + position pairs) and a `gradientTransform` (2×3 matrix). Image fills reference blob data via `imageHash` with scale modes (FILL, FIT, CROP, TILE).++## Extended Stroke Properties++Strokes support `cap` (NONE, ROUND, SQUARE, ARROW_LINES, ARROW_EQUILATERAL), `join` (MITER, BEVEL, ROUND), and `dashPattern` (array of dash/gap lengths) in addition to the base color, weight, opacity, visible, and align properties.++## Coordinate System++Nodes store position and size relative to their parent. To get absolute (canvas) coordinates, walk up the parent chain applying transforms. The renderer uses this to draw nested frames with correct positioning.++Rotation is stored in degrees and applied as part of the 2×3 transform matrix. Snap guides and hit testing account for rotation when computing visual bounds.diff --git a/packages/docs/fr/development/contributing.md b/packages/docs/fr/development/contributing.mdnew file mode 100644index 000000000..772a05e5c--- /dev/null+++ b/packages/docs/fr/development/contributing.md@@ -0,0 +1,94 @@+# Contribuer++## Project Structure++```+packages/+ core/ @open-pencil/core — engine (zero DOM deps)+ src/ Scene graph, renderer, layout, codec, kiwi, types+ cli/ @open-pencil/cli — headless CLI for .fig operations+ src/commands/ info, tree, find, export+src/+ components/ Vue SFCs (canvas, panels, toolbar, color picker)+ properties/ Property panel sections (Appearance, Fill, Stroke, etc.)+ composables/ Canvas input, keyboard shortcuts, rendering hooks+ stores/ Editor state (Vue reactivity)+ engine/ Re-export shims from @open-pencil/core+ kiwi/ Re-export shims from @open-pencil/core+ types.ts Shared types (re-exported from core)+ constants.ts UI colors, defaults, thresholds+desktop/ Tauri v2 (Rust + config)+tests/+ e2e/ Playwright visual regression+ engine/ Unit tests (bun:test)+docs/ VitePress documentation site+openspec/+ specs/ Capability specifications (source of truth)+ changes/ Active and archived changes+```++## Development Setup++```sh+bun install+bun run dev # Editor at localhost:1420+bun run docs:dev # Docs at localhost:5173+```++## Code Style++### Tooling++| Tool | Command | Purpose |+|------|---------|---------|+| oxlint | `bun run lint` | Linting (Rust-based, fast) |+| oxfmt | `bun run format` | Code formatting |+| tsgo | `bun run typecheck` | Type checking (Go-based TypeScript checker) |++Run all checks:++```sh+bun run check+```++### Conventions++- **File names** — kebab-case (`scene-graph.ts`, `use-canvas-input.ts`)+- **Components** — PascalCase Vue SFCs (`EditorCanvas.vue`, `ScrubInput.vue`)+- **Constants** — SCREAMING_SNAKE_CASE+- **Functions/variables** — camelCase+- **Types/interfaces** — PascalCase++### AI Agent Conventions++Developers and AI agents working on the codebase should read `AGENTS.md` in the repo root ([view on GitHub](https://github.com/open-pencil/open-pencil/blob/master/AGENTS.md)). Covers rendering, scene graph, components & instances, layout, UI, file format, Tauri conventions, and known issues.++## Making Changes++1. Check existing [openspec specs](/development/openspec) for the capability you're modifying+2. Create an openspec change if adding new behavior: `openspec new change "my-change"`+3. Implement the change+4. Run `bun run check` and `bun run test`+5. Submit a pull request++## 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.++| 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/layout.ts` | Yoga layout adapter |+| `packages/core/src/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/kiwi/fig-import.ts` | .fig file import logic |+| `packages/cli/src/index.ts` | CLI entry point |+| `packages/cli/src/commands/` | CLI commands (info, tree, find, export) |+| `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 |diff --git a/packages/docs/fr/development/openspec.md b/packages/docs/fr/development/openspec.mdnew file mode 100644index 000000000..4907fe432--- /dev/null+++ b/packages/docs/fr/development/openspec.md@@ -0,0 +1,107 @@+# Workflow OpenSpec++OpenPencil uses [OpenSpec](https://github.com/Fission-AI/OpenSpec) for spec-driven development. Specifications are the source of truth for what the system does.++## Structure++```+openspec/+├── specs/ # Source of truth: how the system works now+│ ├── scene-graph/+│ │ └── spec.md+│ ├── canvas-rendering/+│ │ └── spec.md+│ ├── auto-layout/+│ │ └── spec.md+│ └── ... # 19 capability specs total+├── changes/ # Proposed changes (one directory per change)+│ └── archive/ # Completed changes+└── config.yaml # Optional configuration+```++## Current Specs++| Capability | Description |+|-----------|-------------|+| scene-graph | Flat Map storage, CRUD, hit testing |+| canvas-rendering | CanvasKit WASM rendering pipeline |+| canvas-navigation | Pan, zoom, hand tool |+| selection-manipulation | Click/marquee select, move, resize, rotate |+| undo-redo | Inverse-command pattern |+| text-editing | Text tool, Paragraph API, font loading |+| pen-tool | Vector network model, bezier curves |+| auto-layout | Yoga WASM flexbox, Shift+A toggle |+| figma-clipboard | Bidirectional Kiwi binary clipboard |+| fig-import | .fig file import pipeline |+| kiwi-codec | Kiwi binary codec, sparse field IDs |+| editor-ui | Vue 3 panels, toolbar, color picker |+| snap-guides | Edge/center snapping, rotation-aware |+| rulers | Canvas rulers, selection highlight |+| group-ungroup | ⌘G/⇧⌘G, position-based sort |+| desktop-app | Tauri v2, macOS menu bar |+| testing | Playwright E2E, bun:test unit |+| scrub-input | Drag-to-scrub numeric inputs |+| tooling | Vite 7, oxlint, oxfmt, tsgo, VitePress |++## Workflow++### 1. Propose a Change++```+/opsx:propose add-dark-mode+```++Creates `openspec/changes/add-dark-mode/` with:+- `proposal.md` — why and what changes+- `design.md` — technical approach+- `specs/` — delta specifications (ADDED/MODIFIED/REMOVED requirements)+- `tasks.md` — implementation checklist++### 2. Implement++```+/opsx:apply+```++Execute tasks from tasks.md, checking off items as they're completed.++### 3. Archive++```+/opsx:archive+```++- Merges delta specs into `openspec/specs/` (the baseline)+- Moves the change to `openspec/changes/archive/`++## Spec Format++Each spec file follows a consistent structure:++```markdown+# capability-name Specification++## Purpose+One-line description of what this capability does.++## Requirements++### Requirement: Name+Description using SHALL/MUST for normative requirements.++#### Scenario: Name+- **WHEN** condition+- **THEN** expected outcome+```++Every requirement has at least one scenario. Scenarios are potential test cases.++## CLI Commands++```sh+openspec list # List active changes+openspec show <name> # Show change details+openspec status --change <name> # Artifact status+openspec archive <name> # Archive completed change+openspec update # Regenerate skills/prompts+```diff --git a/packages/docs/fr/development/roadmap.md b/packages/docs/fr/development/roadmap.mdnew file mode 100644index 000000000..9d224ec36--- /dev/null+++ b/packages/docs/fr/development/roadmap.md@@ -0,0 +1,145 @@+# Feuille de route++## Phases++### Phase 1: Core Engine ✅++SceneGraph, Skia rendering, basic shapes, selection, zoom/pan, undo/redo.++**Delivered:**+- Scene graph with flat Map storage and parent-child tree+- CanvasKit WASM rendering for all shape types+- Click/shift/marquee selection with resize handles and rotation+- Zoom/pan with keyboard shortcuts and trackpad gestures+- Undo/redo wired into all operations+- Snap guides with edge and center snapping++### Phase 2: Editor UI + Layout ✅++Properties panel, layers panel, toolbar, Yoga layout integration, text editing.++**Delivered:**+- Vue 3 + Reka UI panels (properties, layers, toolbar)+- Properties panel split into sections (Appearance, Fill, Stroke, Typography, Layout, Position)+- ScrubInput component for all numeric inputs+- Color picker (HSV, hex, opacity)+- Layers panel with tree view, drag reorder, visibility toggle+- Auto-layout with Yoga WASM (direction, gap, padding, justify, align)+- Inline text editing with CanvasKit Paragraph API+- System font loading via Local Font Access API+- Canvas rulers with selection highlight++### Phase 3: File I/O + Visual Features ✅++.fig import/export, Kiwi codec, clipboard, sections, pages, advanced rendering.++**Delivered:**+- .fig file import via Kiwi binary codec+- .fig file export with Kiwi encoding, Zstd compression, thumbnail generation+- Save (⌘S) and Save As (⇧⌘S) with native OS dialogs+- Zstd compression via Tauri Rust command (deflate fallback in browser)+- Vendored kiwi-schema with ESM + sparse field ID patches+- Figma-compatible clipboard (bidirectional Kiwi binary)+- Pen tool with vector network model+- vectorNetworkBlob binary encode/decode+- Group/ungroup (⌘G/⇧⌘G)+- Tauri v2 desktop app with native menu bar (macOS/Windows/Linux)+- Sections (S key) with title pills, auto-adopt, luminance-adaptive text+- Multi-page documents with pages panel, per-page viewport+- Hover highlight with shape-aware outlines+- Tier 1 rendering: gradients, image fills, effects, strokes (cap/join/dash), arcs+- Fill type picker with solid/gradient/image tabs and gradient stop editing+- Canvas background color per page+- Fig-import unit tests, layout unit tests, layers-panel E2E tests++### Phase 4: Components + Variables ✅++Components, instances, overrides, variables, collections, modes, image export.++**Delivered:**+- Component creation from frame/group or multi-selection (⌥⌘K)+- Component sets from multiple components (⇧⌘K) with dashed purple border+- Instance creation from components with child cloning and componentId mapping+- Live component-instance sync with override preservation+- Detach instance back to frame (⌥⌘B)+- Go to main component (cross-page navigation)+- Always-visible purple component/instance labels with diamond icon+- Opaque container hit testing (click selects component, double-click enters)+- Right-click context menu with clipboard, z-order, grouping, component, visibility, lock, move-to-page actions+- Z-order manipulation (] bring to front, [ send to back)+- Toggle visibility (⇧⌘H) and lock (⇧⌘L)+- Move nodes between pages via context menu+- Viewport culling, Paint reuse, RAF render coalescing+- Effects panel UI (drop shadow, inner shadow, layer/background/foreground blur)+- Independent corner radius controls (per-corner toggle in Appearance section)+- GitHub Actions CI/CD for Windows (x64, arm64) and macOS (x64, arm64) builds+- Polygon and Star drawing tools with pointCount and starInnerRadius+- Resizable left/right panels via reka-ui Splitter (persistent layout)+- @/ import alias, shared types module (src/types.ts, src/global.d.ts)+- Codebase lint-clean: 0 oxlint warnings, 0 tsgo type errors+- Variables: COLOR type with collections, modes, bindings, FillSection variable picker, .fig import+- Variables dialog: TanStack Table with resizable columns, mode columns, collection tabs with rename, search, demo collections (Primitives/Semantic/Spacing), undo/redo for all variable operations+- Image export: PNG/JPG/WEBP with ExportSection (scale, format, live preview), ⇧⌘E shortcut, context menu+- Canvas-native text editing: TextEditor class in core, phantom textarea, cursor/selection/word boundaries on canvas, caret blinking, selection highlights+- System font enumeration via font-kit Rust crate, OnceLock cache, preload on startup+- Font picker: virtual scroll (reka-ui ListboxVirtualizer), search filter, CSS font preview+- ColorInput component extraction, ColorPicker alpha slider checkerboard fix+- App identity: pencil icon, Cargo crate open_pencil, macOS Dock "OpenPencil"+- Splash loader during WASM initialization+- Rich text style runs: per-selection ⌘B/I/U, StyleRun model, ParagraphBuilder pushStyle/pop, .fig roundtrip+- B/I/U/S toggle buttons in TypographySection+- Double-click (word), triple-click (select all) text selection++**Remaining (deferred to Phase 6):**+- Variant switching+- Variable types: FLOAT, STRING, BOOLEAN editing UI+- Variable-driven theming++### Phase 5: AI Integration & Tooling 🟡++Core extraction, CLI, MCP server, design guidelines, screenshot verification loop.++**Delivered:**+- @open-pencil/core extracted to packages/core/ (zero DOM deps, Bun workspace)+- @open-pencil/cli with headless .fig operations (info, tree, find, export, analyze, node, pages, variables), CanvasKit CPU rasterization, --json output+- JSX renderer: TreeNode builders (Frame, Text, Rectangle, etc.), renderTreeNode/renderJsx, Tailwind-like shorthand props, 27 tests+- jscpd copy-paste detection (15.6% → 0.62%), kiwi-serialize.ts consolidation+- .fig roundtrip tests with LFS fixtures (material3.fig 87K nodes, nuxtui.fig 314K nodes)+- .fig import O(n²) → O(n) fix (37s → 535ms on 87K nodes), ByteBuffer optimization+- test:coverage script+- AI chat: OpenRouter direct (no backend), Stronghold key storage, 26 tools (create_shape, set_fill, set_effects, set_constraints, components, groups, pages, variables, eval_code, etc.), model selector, ⌘J toggle, streaming markdown, Playwright tests with mock transport+- Code panel: sceneNodeToJsx() export, Prism.js highlighting, line numbers, copy button, 14 tests+- Properties panel restructured: Design | Code | AI tabs+- npm publishing preparation for core and cli packages++**Planned:**+- Port remaining figma-use tools (118 total, 26 currently implemented)+- Attached mode: WebSocket to running editor for eval, create, export, screenshot+- Design guidelines system+- AI-driven design workflow via MCP+- Screenshot verification loop++### Phase 6: Polish + Distribution 🔲++Prototyping, comments, desktop distribution, documentation, public launch.++**Planned:**+- Prototyping (frame connections, transitions)+- Comments (pin, threads, resolve)+- Linux Tauri builds (macOS and Windows already covered by CI)+- PWA support+- Documentation site (VitePress)+- Performance optimization (Lighthouse > 90)+- Full Figma compatibility test suite+- Deferred from Phase 4: variant switching, FLOAT/STRING/BOOLEAN variable UI, variable-driven theming++## Timeline++| Phase | Estimated Duration | Status |+|-------|-------------------|--------|+| Phase 1: Core Engine | 3 months | ✅ Complete |+| Phase 2: Editor UI + Layout | 3 months | ✅ Complete |+| Phase 3: File I/O + Visual Features | 2 months | ✅ Complete |+| Phase 4: Components + Variables | 2 months | ✅ Complete |+| Phase 5: AI Integration & Tooling | 2 months | 🟡 In Progress |+| Phase 6: Polish + Distribution | 2 months | 🔲 Planned |diff --git a/packages/docs/fr/development/testing.md b/packages/docs/fr/development/testing.mdnew file mode 100644index 000000000..9e0d7ce81--- /dev/null+++ b/packages/docs/fr/development/testing.md@@ -0,0 +1,91 @@+# Tests++## Overview++| Type | Framework | Command | Location |+|------|-----------|---------|----------|+| E2E visual regression | Playwright | `bun run test` | `tests/e2e/` |+| Figma CDP reference | Playwright | `bun run test:figma` | `tests/figma/` |+| Unit tests | bun:test | `bun run test:unit` | `tests/engine/` |++## E2E Visual Regression++Playwright creates shapes on the canvas and compares screenshots against baseline PNGs.++```sh+bun run test # Run tests, compare against baselines+bun run test:update # Regenerate baseline screenshots+```++### How It Works++1. Tests load the editor in a headless browser+2. The editor signals readiness via a `data-ready` HTML attribute+3. Tests create shapes via the editor's API+4. Screenshots are taken and compared against baselines using `toMatchSnapshot`+5. Page is reused across test cases for speed (~2s total)++### No-Chrome Test Mode++The editor supports a test mode that hides UI chrome (toolbar, panels) for clean screenshot capture. Activated via URL parameter.++## Figma CDP Reference Tests++A separate Playwright project connects to Figma via Chrome DevTools Protocol to capture reference screenshots for pixel-perfect comparison.++```sh+bun run figma:debug # Launch Figma with debugging port+bun run test:figma # Connect to Figma, capture references+```++Requires Figma desktop app running with `--remote-debugging-port=9222`.++## Unit Tests++Engine unit tests use bun:test and target < 50ms execution:++```sh+bun run test:unit+```++Tests cover:+- Scene graph CRUD operations, parent-child relationships, z-ordering, hit testing+- **Fig-import pipeline** — node type mapping, transforms, fills/strokes/effects, gradients, images, arcs, nested hierarchies (`tests/engine/fig-import.test.ts`)+- **Layout computation** — Yoga auto-layout: direction, gap, padding, justify, align, child sizing (fixed/fill/hug), cross-axis sizing, wrap, nested layouts (`tests/engine/layout.test.ts`)++### Writing Unit Tests++```typescript+import { describe, expect, it } from 'bun:test'+import { SceneGraph } from '../../src/engine/scene-graph'++describe('SceneGraph', () => {+ it('creates and retrieves a node', () => {+ const sg = new SceneGraph()+ const node = sg.createNode('RECTANGLE', sg.root, { name: 'Test' })+ expect(sg.getNode(node.guid)).toBeDefined()+ })+})+```++## E2E Test Coverage++| Test file | Scope |+|-----------|-------|+| `tests/e2e/layers-panel.spec.ts` | Layers panel tree structure, visibility toggles, selection sync |+| `tests/e2e/visual.spec.ts` | Visual regression screenshots for shapes and rendering |++## Test Helpers++| File | Purpose |+|------|---------|+| `tests/helpers/canvas.ts` | Canvas setup and interaction utilities |+| `tests/helpers/figma.ts` | Figma CDP connection helpers |++## Performance Targets++| Metric | Target |+|--------|--------|+| E2E suite total | < 3s |+| Unit test suite total | < 50ms |+| Screenshot comparison | toMatchSnapshot (pixel-level) |diff --git a/packages/docs/fr/eval-command.md b/packages/docs/fr/eval-command.mdnew file mode 100644index 000000000..9f7c45018--- /dev/null+++ b/packages/docs/fr/eval-command.md@@ -0,0 +1,437 @@+# `open-pencil eval` — Figma-like Plugin API for Headless Scripting++## Overview++`bun open-pencil eval <file> --code '<js>'` executes JavaScript against a `.fig` file with a Figma-compatible `figma` global object. This enables headless scripting, batch operations, AI tool execution, and testing — all without the GUI.++The `figma` object mirrors Figma's Plugin API surface as closely as possible, so existing Figma plugin knowledge and code snippets transfer directly.++```bash+# Create a frame, set auto-layout, add children+bun open-pencil eval design.fig --code '+ const frame = figma.createFrame()+ frame.name = "Card"+ frame.resize(300, 200)+ frame.layoutMode = "VERTICAL"+ frame.itemSpacing = 12+ frame.paddingTop = frame.paddingBottom = 16+ frame.paddingLeft = frame.paddingRight = 16+ frame.fills = [{ type: "SOLID", color: { r: 1, g: 1, b: 1 } }]++ const title = figma.createText()+ title.characters = "Hello World"+ title.fontSize = 24+ frame.appendChild(title)++ return { id: frame.id, name: frame.name }+'++# Query nodes+bun open-pencil eval design.fig --code '+ const buttons = figma.currentPage.findAll(n => n.type === "FRAME" && n.name.includes("Button"))+ return buttons.map(b => ({ id: b.id, name: b.name, w: b.width, h: b.height }))+'++# Read from stdin (for multiline scripts / piping)+cat transform.js | bun open-pencil eval design.fig --stdin++# Write changes back+bun open-pencil eval design.fig --code '...' --write+bun open-pencil eval design.fig --code '...' -o modified.fig+```++## Architecture++```+┌──────────────────────────────────────────────────────┐+│ CLI: `open-pencil eval <file> --code '...'` │+│ ↓ │+│ loadDocument(file) → SceneGraph │+│ ↓ │+│ FigmaAPI(sceneGraph) → `figma` proxy object │+│ ↓ │+│ AsyncFunction('figma', wrappedCode)(figmaProxy) │+│ ↓ │+│ print result as JSON / agentfmt │+│ optionally: saveDocument(file) if --write │+└──────────────────────────────────────────────────────┘+```++### Key classes++| 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.) |+| `eval` command | `packages/cli/src/commands/eval.ts` | CLI command that loads doc, creates API, executes code |++### Why in `@open-pencil/core`?++The `FigmaAPI` class lives in core (not CLI) because:+- **AI tools reuse it** — the chat panel's `render` tool can execute JSX through the same API+- **Test scripts** — unit tests can use the API to set up fixtures+- **No DOM deps** — runs headless in Bun, no browser APIs needed++## `FigmaAPI` — Phased Implementation++### Phase 1: Core (MVP for eval command)++These cover ~80% of real plugin scripts:++#### Document & Page++| Figma API | Our implementation | Notes |+|-----------|--------------------|-------|+| `figma.root` | Getter → proxy for root node | `.children` returns page proxies |+| `figma.currentPage` | Getter/setter → first page by default | Settable to any page proxy |+| `figma.currentPage.selection` | Get/set → tracked selection array | |+| `figma.getNodeById(id)` | `graph.getNode(id)` wrapped in proxy | Sync, like Figma's deprecated version |++#### Node Creation++| Figma API | Maps to |+|-----------|---------|+| `figma.createFrame()` | `graph.createNode('FRAME', currentPageId)` |+| `figma.createRectangle()` | `graph.createNode('RECTANGLE', ...)` |+| `figma.createEllipse()` | `graph.createNode('ELLIPSE', ...)` |+| `figma.createText()` | `graph.createNode('TEXT', ...)` |+| `figma.createLine()` | `graph.createNode('LINE', ...)` |+| `figma.createPolygon()` | `graph.createNode('POLYGON', ...)` |+| `figma.createStar()` | `graph.createNode('STAR', ...)` |+| `figma.createComponent()` | `graph.createNode('COMPONENT', ...)` |+| `figma.createPage()` | `graph.addPage(name)` |+| `figma.createSection()` | `graph.createNode('SECTION', ...)` |++#### Node Properties (via `FigmaNode` proxy)++Read/write on any node proxy. Property access maps to `SceneNode` fields:++```ts+// Geometry+node.x, node.y // direct+node.width, node.height // read-only, use node.resize(w, h)+node.rotation // direct+node.resize(w, h) // updates width + height+node.resizeWithoutConstraints(w, h) // same (no constraint engine yet)++// Visual+node.fills // get/set Fill[]+node.strokes // get/set Stroke[]+node.effects // get/set Effect[]+node.opacity // get/set number+node.visible // get/set boolean+node.locked // get/set boolean+node.blendMode // get/set BlendMode+node.clipsContent // get/set boolean++// Corner radius+node.cornerRadius // get/set (number or figma.mixed)+node.topLeftRadius // get/set+node.topRightRadius // get/set+node.bottomLeftRadius // get/set+node.bottomRightRadius // get/set+node.cornerSmoothing // get/set++// Identity+node.id // read-only+node.name // get/set+node.type // read-only+node.parent // read-only → FigmaNode | null+node.removed // read-only boolean+```++#### Tree Operations++```ts+node.children // read-only FigmaNode[]+node.appendChild(child) // reparent to end+node.insertChild(index, child) // reparent at index+node.remove() // graph.deleteNode(id)++// Traversal+node.findAll(callback?) // recursive find+node.findOne(callback) // first match+node.findChild(callback) // direct children only+node.findChildren(callback?) // direct children only+```++#### Auto-layout++```ts+node.layoutMode // 'NONE' | 'HORIZONTAL' | 'VERTICAL'+node.primaryAxisAlignItems // 'MIN' | 'CENTER' | 'MAX' | 'SPACE_BETWEEN'+node.counterAxisAlignItems // 'MIN' | 'CENTER' | 'MAX' | 'BASELINE'+node.itemSpacing // number+node.counterAxisSpacing // number | null+node.paddingTop / Right / Bottom / Left // number+node.layoutWrap // 'NO_WRAP' | 'WRAP'++// Child sizing+node.layoutPositioning // 'AUTO' | 'ABSOLUTE'+node.layoutGrow // 0 | 1+node.layoutSizingHorizontal // 'FIXED' | 'HUG' | 'FILL'+node.layoutSizingVertical // 'FIXED' | 'HUG' | 'FILL'+```++#### Text++```ts+node.characters // get/set (maps to node.text)+node.fontSize // get/set+node.fontName // get/set { family, style }+node.fontWeight // get/set+node.textAlignHorizontal // get/set+node.textAlignVertical // get/set+node.textAutoResize // get/set+node.letterSpacing // get/set+node.lineHeight // get/set+node.maxLines // get/set+node.textCase // get/set+node.textDecoration // get/set+```++#### Stroke details++```ts+node.strokeWeight // get/set (maps to strokes[0].weight)+node.strokeAlign // get/set (maps to strokes[0].align)+node.dashPattern // get/set+```++#### Misc++```ts+figma.mixed // Symbol sentinel for mixed values+figma.group(nodes, parent) // creates GROUP with given children+figma.ungroup(node) // ungroups, reparents children+figma.flatten(nodes) // NOT IMPLEMENTED YET — returns first node+```++#### Export++```ts+node.exportAsync(settings?) // only works if CanvasKit is loaded+ // settings: { format: 'PNG'|'JPG'|'SVG', constraint? }+```++### Phase 2: Components & Instances++| API | Maps to |+|-----|---------|+| `figma.createComponent()` | `graph.createNode('COMPONENT', ...)` |+| `figma.createComponentFromNode(node)` | Convert existing frame to component |+| `figma.combineAsVariants(components, parent)` | Create COMPONENT_SET |+| Node: `node.createInstance()` | `graph.createInstance(componentId, parentId)` |+| Node: `node.detachInstance()` | `graph.detachInstance(id)` |+| `figma.getNodeById(id).mainComponent` | `graph.getMainComponent(id)` |++### Phase 3: Variables++| API | Maps to |+|-----|---------|+| `figma.variables.getLocalVariables(type?)` | `graph.variables` filtered |+| `figma.variables.getLocalVariableCollections()` | `graph.variableCollections` |+| `figma.variables.createVariable(name, collection, type)` | `graph.addVariable(...)` |+| `figma.variables.createVariableCollection(name)` | `graph.addCollection(...)` |+| `figma.variables.getVariableById(id)` | `graph.variables.get(id)` |+| `node.setBoundVariable(field, variable)` | `graph.bindVariable(...)` |+| `node.boundVariables` | getter from SceneNode |++### Phase 4: Styles & Advanced++| API | Notes |+|-----|-------|+| `figma.createPaintStyle()` | Requires style storage in SceneGraph |+| `figma.createTextStyle()` | Requires style storage in SceneGraph |+| `figma.createEffectStyle()` | Requires style storage in SceneGraph |+| `figma.loadFontAsync(fontName)` | No-op (we don't have font loading constraints) |+| `figma.listAvailableFontsAsync()` | Return system fonts if available |+| Boolean operations (`union`, `subtract`, `intersect`, `exclude`) | Requires path boolean engine |+| `figma.createNodeFromJSXAsync(jsx)` | Port figma-use's JSX renderer |++## `FigmaNode` Proxy Design++The proxy wraps a `SceneNode` and translates Figma property names to our internal names. Key mappings:++```ts+const PROPERTY_MAP: Record<string, string> = {+ // Figma name → SceneNode field name (only where they differ)+ 'characters': 'text',+ 'strokeWeight': → computed from strokes[0].weight,+ 'strokeAlign': → computed from strokes[0].align,+ 'fontName': → computed from { family: fontFamily, style: ... },+ 'primaryAxisAlignItems': 'primaryAxisAlign',+ 'counterAxisAlignItems': 'counterAxisAlign',+ 'primaryAxisSizingMode': 'primaryAxisSizing', // value mapping: 'AUTO' → 'HUG', 'FIXED' → 'FIXED'+ 'counterAxisSizingMode': 'counterAxisSizing',+ 'layoutSizingHorizontal': → computed from primaryAxisSizing / counterAxisSizing depending on layoutMode+ 'layoutSizingVertical': → computed+}+```++Methods on the proxy:++```ts+class FigmaNode {+ // The proxy is created via: new Proxy(target, handler)+ // where handler.get intercepts property reads and handler.set intercepts writes++ resize(width: number, height: number): void+ resizeWithoutConstraints(width: number, height: number): void+ remove(): void+ appendChild(child: FigmaNode): void+ insertChild(index: number, child: FigmaNode): void+ findAll(callback?: (node: FigmaNode) => boolean): FigmaNode[]+ findOne(callback: (node: FigmaNode) => boolean): FigmaNode | null+ findChild(callback: (node: FigmaNode) => boolean): FigmaNode | null+ findChildren(callback?: (node: FigmaNode) => boolean): FigmaNode[]+ exportAsync(settings?: ExportSettings): Promise<Uint8Array>++ // Components (Phase 2)+ createInstance(): FigmaNode+ detachInstance(): void+ get mainComponent(): FigmaNode | null+}+```++## CLI Command++```+bun open-pencil eval <file> [options]++Arguments:+ file .fig file to operate on++Options:+ --code, -c JavaScript code to execute (has access to `figma` global)+ --stdin Read code from stdin instead of --code+ --write, -w Write changes back to the input file+ -o, --output Write to a different file+ --json Output result as JSON (default for non-TTY)+ --quiet, -q Suppress output, only write file+```++### Execution model++1. Load `.fig` → `SceneGraph`+2. Create `FigmaAPI(graph)` → `figma` proxy+3. Wrap user code in async function: `return (async () => { <code> })()`+4. Execute with `figma` as sole argument+5. Print return value (JSON or agentfmt)+6. If `--write` or `-o`: serialize `SceneGraph` back to `.fig`++### Return value formatting++- `undefined` / `void` → no output+- Primitives → printed directly+- Objects/arrays → `JSON.stringify(result, null, 2)` or agentfmt tables+- `FigmaNode` → serialized as `{ id, type, name, x, y, width, height, fills, ... }`+- Arrays of `FigmaNode` → serialized as list++## 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`:++```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)+execute: async ({ type, x, y, width, height }) => {+ const frame = figma.createFrame()+ frame.resize(width, height)+ frame.x = x+ frame.y = y+ return { id: frame.id }+}+```++This ensures CLI scripts and AI tools behave identically.++## File Layout++```+packages/core/src/+ figma-api.ts # FigmaAPI class + FigmaNode proxy (Phase 1–4)+ figma-api.test.ts # Unit tests against headless SceneGraph++packages/cli/src/commands/+ eval.ts # CLI command++packages/cli/src/commands/eval.test.ts # Integration tests+```++## Test Plan++### Unit tests (`packages/core/src/figma-api.test.ts`)++1. **Node creation** — each `createX()` creates correct type, added to current page+2. **Property access** — `.fills`, `.x`, `.width`, `.name`, `.characters` read/write correctly+3. **Resize** — `.resize(w, h)` updates width/height+4. **Tree operations** — `.appendChild()`, `.insertChild()`, `.remove()`, `.parent`, `.children`+5. **Traversal** — `.findAll()`, `.findOne()`, `.findChild()`, `.findChildren()` with callbacks+6. **Auto-layout** — `.layoutMode`, `.itemSpacing`, `.paddingTop`, etc.+7. **Text** — `.characters` maps to `.text`, `.fontName` maps to `{ family, style }`+8. **Mixed values** — `.cornerRadius` returns `figma.mixed` when corners differ+9. **Selection** — `figma.currentPage.selection` get/set+10. **Page switching** — `figma.currentPage = page2` works+11. **Group/ungroup** — `figma.group()` creates group, `figma.ungroup()` dissolves it+12. **Clone** — node creation produces independent copies++### CLI integration tests (`packages/cli/src/commands/eval.test.ts`)++1. **Basic eval** — `eval test.fig --code 'return figma.currentPage.name'` → page name+2. **Create + read** — create a frame, return its properties+3. **Query nodes** — `findAll` returns correct nodes+4. **Write back** — `--write` saves changes, reloading shows them+5. **Stdin** — `echo 'return 42' | bun open-pencil eval test.fig --stdin` → `42`+6. **JSON output** — `--json` returns valid JSON+7. **Error handling** — syntax errors, runtime errors reported cleanly++## Implementation Order++1. **`FigmaNode` proxy** — property mapping, `.resize()`, `.remove()`, tree methods+2. **`FigmaAPI` class** — `createFrame/Rectangle/...`, `.root`, `.currentPage`, `.getNodeById()`, `.mixed`, `.group()`+3. **CLI `eval` command** — argument parsing, code wrapping, output formatting+4. **Unit tests** — all 12 test groups above+5. **CLI integration tests** — all 7 test groups above+6. **Wire to AI tools** — refactor `src/ai/tools.ts` to use `FigmaAPI` where possible+7. **Phase 2** — components & instances+8. **Phase 3** — variables+9. **Phase 4** — styles, boolean ops, JSX renderer++## Property Mapping Reference++| Figma Property | SceneNode Field | Type | Notes |+|---------------|-----------------|------|-------|+| `characters` | `text` | `string` | |+| `fontName` | `fontFamily` + `fontWeight` + `italic` | `{ family, style }` | Computed: `style` = "Bold Italic" etc. |+| `strokeWeight` | `strokes[0].weight` | `number` | Computed |+| `strokeAlign` | `strokes[0].align` | `string` | Computed |+| `primaryAxisAlignItems` | `primaryAxisAlign` | `string` | |+| `counterAxisAlignItems` | `counterAxisAlign` | `string` | |+| `layoutSizingHorizontal` | `primaryAxisSizing` or `counterAxisSizing` | `string` | Depends on `layoutMode` |+| `layoutSizingVertical` | (opposite of horizontal) | `string` | |+| `absoluteTransform` | computed from `x`, `y`, `rotation` | `Transform` | Read-only |+| `absoluteBoundingBox` | `getAbsoluteBounds(id)` | `Rect` | Read-only |+| All others | Same name | Same type | Direct passthrough |++## Open Questions++1. **Font loading**: `figma.loadFontAsync()` — should it be a no-op (we don't have font gating) or should we track loaded fonts?+ → **Decision: No-op that returns resolved Promise.** We don't gate text editing on font loading.++2. **Export in headless mode**: `node.exportAsync()` requires CanvasKit. Should eval load CanvasKit?+ → **Decision: Optional.** If CanvasKit is available (via `--with-canvaskit` flag or env), enable export. Otherwise, throw "Export requires CanvasKit" error.++3. **`figma.mixed` symbol**: Should we use the actual Figma symbol or our own?+ → **Decision: Our own `Symbol('mixed')`.** Exposed as `figma.mixed`.++4. **Undo**: `figma.commitUndo()` / `figma.triggerUndo()` — relevant in headless?+ → **Decision: No-op in CLI.** Undo only matters in the live editor. The AI tools can add undo support separately via EditorStore.++5. **Write format**: Should `--write` produce `.fig` (Kiwi binary) or also support `.json`?+ → **Decision: `.fig` only for now.** JSON export is a separate feature.diff --git a/packages/docs/fr/reference/file-format.md b/packages/docs/fr/reference/file-format.mdnew file mode 100644index 000000000..eff84db84--- /dev/null+++ b/packages/docs/fr/reference/file-format.md@@ -0,0 +1,71 @@+# Format de fichier++## .fig File Structure++```+┌─────────────────────────────────┐+│ Magic header: "fig-kiwi" (8B) │+│ Version (4B uint32 LE) │+│ Schema length (4B uint32 LE) │+│ Compressed Kiwi schema │+│ Message length (4B uint32 LE) │+│ Compressed Kiwi message │ ← NodeChange[] (entire document)+│ Blob data │ ← Images, vector networks, fonts+└─────────────────────────────────┘+```++## Import Pipeline++```+.fig file → Parse header → Decompress Zstd → Decode Kiwi schema+ → Decode Message → NodeChange[] → Build SceneGraph+ → Resolve blob refs → Render on canvas+```++## Export Pipeline++```+SceneGraph → NodeChange[] → Kiwi encode → Compress (Zstd/deflate)+ → Build ZIP (header + schema + message + thumbnail.png)+ → Write .fig file+```++Export uses <kbd>⌘</kbd><kbd>S</kbd> (Save) and <kbd>⇧</kbd><kbd>⌘</kbd><kbd>S</kbd> (Save As) with native OS dialogs on the desktop app. The exported file includes a `thumbnail.png` required by Figma for file preview. Compression uses Zstd via Tauri Rust command on desktop, with deflate fallback in the browser. The ZIP archive is assembled in Rust on desktop for correct Zstd frame headers (content size included).++## Kiwi Binary Codec++The codec handles Figma's 194-definition Kiwi schema with NodeChange as the central type (~390 fields). Key components:++- **kiwi-schema** — vendored from evanw/kiwi, patched for ESM and sparse field IDs+- **codec.ts** — encode/decode Messages using the Kiwi schema+- **protocol.ts** — wire format parsing and message type detection+- **schema.ts** — 194 message/enum/struct definitions++### Sparse Field IDs++Figma's schema uses non-contiguous field IDs (e.g., 1, 2, 5, 10 with gaps). The vendored kiwi-schema parser is patched to handle this correctly.++### Compression++.fig files use Zstd compression for both the schema and message payloads. Decompression uses the `fzstd` library. For export, Zstd compression is offloaded to a Tauri Rust command on the desktop app (better performance, correct frame headers). In the browser, deflate via `fflate` is used as a fallback. Clipboard encoding also uses `fflate`.++## Supported Formats++| Format | Import | Export |+|--------|--------|--------|+| .fig (Figma) | ✅ | ✅ |+| .svg | Planned | Planned |+| .png | Planned | Planned |+| .pdf | — | Planned |++See [Roadmap](/development/roadmap) for planned format support timeline.++## Clipboard Format++Copy/paste uses the same Kiwi binary encoding:++1. **Copy** — encode selected NodeChange[] to Kiwi binary, compress, write to clipboard as `application/x-figma-design` MIME type+2. **Paste** — read clipboard, decompress, decode Kiwi binary, create nodes in scene graph+3. **Synchronous** — encoding happens in the copy event handler (not async Clipboard API) to ensure browser compatibility++This enables bidirectional clipboard between OpenPencil and Figma.diff --git a/packages/docs/fr/reference/keyboard-shortcuts.md b/packages/docs/fr/reference/keyboard-shortcuts.mdnew file mode 100644index 000000000..46b11065a--- /dev/null+++ b/packages/docs/fr/reference/keyboard-shortcuts.md@@ -0,0 +1,120 @@+# Raccourcis clavier++Carte complète des raccourcis compatibles Figma.++::: tip Symbol Legend+⌘ = Cmd (Mac) / Ctrl (Win/Linux) · ⇧ = Shift · ⌥ = Alt/Option · ⌃ = Ctrl · ⌫ = Backspace+:::++## Tools++| Key | Tool | Status |+|-----|------|--------|+| <kbd>V</kbd> | Move/Select | ✅ |+| <kbd>K</kbd> | Scale | 🔲 |+| <kbd>H</kbd> | Hand | ✅ |+| <kbd>F</kbd> | Frame | ✅ |+| <kbd>S</kbd> | Section | ✅ |+| <kbd>R</kbd> | Rectangle | ✅ |+| <kbd>O</kbd> | Ellipse | ✅ |+| <kbd>L</kbd> | Line | ✅ |+| — | Polygon | ✅ (flyout only) |+| — | Star | ✅ (flyout only) |+| <kbd>⇧</kbd><kbd>L</kbd> | Arrow | 🔲 |+| <kbd>P</kbd> | Pen | ✅ |+| <kbd>⇧</kbd><kbd>P</kbd> | Pencil | 🔲 |+| <kbd>T</kbd> | Text | ✅ |+| <kbd>C</kbd> | Comment | 🔲 |+| <kbd>I</kbd> | Eyedropper | 🔲 |++## File++| Shortcut | Action | Status |+|----------|--------|--------|+| <kbd>⌘</kbd><kbd>N</kbd> | New Window | 🔲 |+| <kbd>⌘</kbd><kbd>O</kbd> | Open File | ✅ |+| <kbd>⌘</kbd><kbd>W</kbd> | Close Tab | 🔲 |+| <kbd>⌘</kbd><kbd>S</kbd> | Save | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>S</kbd> | Save As | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>E</kbd> | Export… | ✅ |++## Edit++| Shortcut | Action | Status |+|----------|--------|--------|+| <kbd>⌘</kbd><kbd>Z</kbd> | Undo | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>Z</kbd> | Redo | ✅ |+| <kbd>⌘</kbd><kbd>X</kbd> | Cut | ✅ |+| <kbd>⌘</kbd><kbd>C</kbd> | Copy | ✅ |+| <kbd>⌘</kbd><kbd>V</kbd> | Paste | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>V</kbd> | Paste Over Selection | 🔲 |+| <kbd>⌘</kbd><kbd>D</kbd> | Duplicate | ✅ |+| <kbd>⌫</kbd> | Delete | ✅ |+| <kbd>⌘</kbd><kbd>A</kbd> | Select All | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>A</kbd> | Select Inverse | 🔲 |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>C</kbd> | Copy Properties | 🔲 |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>V</kbd> | Paste Properties | 🔲 |++## View++| Shortcut | Action | Status |+|----------|--------|--------|+| <kbd>⌘</kbd><kbd>'</kbd> | Pixel Grid | 🔲 |+| <kbd>⌃</kbd><kbd>G</kbd> | Layout Guides | 🔲 |+| <kbd>⇧</kbd><kbd>R</kbd> | Rulers | 🔲 |+| <kbd>⌘</kbd><kbd>\\</kbd> | Show/Hide UI | 🔲 |+| <kbd>⌘</kbd><kbd>=</kbd> | Zoom In | ✅ |+| <kbd>⌘</kbd><kbd>-</kbd> | Zoom Out | ✅ |+| <kbd>⌘</kbd><kbd>0</kbd> | Zoom to 100% | ✅ |+| <kbd>⌘</kbd><kbd>1</kbd> | Zoom to Fit | 🔲 |+| <kbd>⌘</kbd><kbd>2</kbd> | Zoom to Selection | 🔲 |+| <kbd>⌘</kbd><kbd>J</kbd> | Toggle AI Chat | ✅ |++## Object++| Shortcut | Action | Status |+|----------|--------|--------|+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>G</kbd> | Frame Selection | 🔲 |+| <kbd>⌘</kbd><kbd>G</kbd> | Group Selection | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>G</kbd> | Ungroup | ✅ |+| <kbd>⇧</kbd><kbd>A</kbd> | Add Auto Layout | ✅ |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>K</kbd> | Create Component | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>K</kbd> | Create Component Set | ✅ |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>B</kbd> | Detach Instance | ✅ |+| <kbd>⌘</kbd><kbd>]</kbd> | Bring Forward | 🔲 |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>]</kbd> | Bring to Front | 🔲 |+| <kbd>]</kbd> | Bring to Front | ✅ |+| <kbd>⌘</kbd><kbd>[</kbd> | Send Backward | 🔲 |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>[</kbd> | Send to Back | 🔲 |+| <kbd>[</kbd> | Send to Back | ✅ |+| <kbd>⇧</kbd><kbd>H</kbd> | Flip Horizontal | 🔲 |+| <kbd>⇧</kbd><kbd>V</kbd> | Flip Vertical | 🔲 |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>H</kbd> | Toggle Visibility | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>L</kbd> | Toggle Lock | ✅ |+| <kbd>⌘</kbd><kbd>E</kbd> | Flatten | 🔲 |++## Text++| Shortcut | Action | Status |+|----------|--------|--------|+| <kbd>⌘</kbd><kbd>B</kbd> | Bold | ✅ |+| <kbd>⌘</kbd><kbd>I</kbd> | Italic | ✅ |+| <kbd>⌘</kbd><kbd>U</kbd> | Underline | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>X</kbd> | Strikethrough | 🔲 |++## Canvas Interaction++| Input | Action | Status |+|-------|--------|--------|+| Click | Select node | ✅ |+| <kbd>Shift</kbd>+Click | Add/remove from selection | ✅ |+| <kbd>Alt</kbd>+Drag | Duplicate and move | ✅ |+| <kbd>Shift</kbd>+Drag (draw) | Constrain to square/circle | ✅ |+| <kbd>Shift</kbd>+Drag (resize) | Maintain aspect ratio | ✅ |+| <kbd>Shift</kbd>+Drag (rotate) | Snap to 15° | ✅ |+| Middle mouse drag | Pan | ✅ |+| Scroll | Pan | ✅ |+| <kbd>Ctrl</kbd>+Scroll / Pinch | Zoom | ✅ |+| Double-click text | Edit text inline | ✅ |+| Drag onto frame | Reparent into frame | ✅ |+| <kbd>Escape</kbd> | Deselect / Cancel | ✅ |diff --git a/packages/docs/fr/reference/mcp-tools.md b/packages/docs/fr/reference/mcp-tools.mdnew file mode 100644index 000000000..372872cb4--- /dev/null+++ b/packages/docs/fr/reference/mcp-tools.md@@ -0,0 +1,140 @@+# Serveur MCP++OpenPencil includes an MCP (Model Context Protocol) server that lets AI coding tools — Claude Code, Cursor, Windsurf, etc. — read and modify `.fig` files headlessly.++Two transports: **stdio** for MCP clients, **HTTP** for everything else.++## Install++```sh+bun add -g @open-pencil/mcp+```++## Stdio (Claude Code, Cursor, etc.)++Add to your MCP config (e.g. `~/.claude/settings.json` or `.cursor/mcp.json`):++```json+{+ "mcpServers": {+ "open-pencil": {+ "command": "openpencil-mcp"+ }+ }+}+```++Or run from source without installing:++::: code-group+```json [Bun]+{+ "mcpServers": {+ "open-pencil": {+ "command": "bun",+ "args": ["/path/to/open-pencil/packages/mcp/src/index.ts"]+ }+ }+}+```+```json [Node.js]+{+ "mcpServers": {+ "open-pencil": {+ "command": "npx",+ "args": ["tsx", "/path/to/open-pencil/packages/mcp/src/index.ts"]+ }+ }+}+```+:::++## HTTP++For browser extensions, scripts, CI, or any HTTP client:++```sh+openpencil-mcp-http+```++Or from source: `bun packages/mcp/src/http.ts` / `npx tsx packages/mcp/src/http.ts`++Starts on port 3100 (override with `PORT` env var). Endpoints:++- `GET /health` — server status+- `POST /mcp` — MCP Streamable HTTP (SSE). Sessions via `mcp-session-id` header.++## Workflow++1. **Open** — `open_file` to load an existing `.fig`, or `new_document` for a blank canvas+2. **Read** — `get_page_tree`, `find_nodes`, `get_node`, `list_pages`+3. **Create** — `create_shape`, `render` (JSX)+4. **Modify** — `set_fill`, `set_stroke`, `set_layout`, `update_node`, `set_effects`+5. **Structure** — `reparent_node`, `group_nodes`, `clone_node`, `delete_node`+6. **Save** — `save_file` to write back to `.fig`++## Tools (29)++### Document++| Tool | Description |+|------|-------------|+| `open_file` | Open a `.fig` file for editing |+| `save_file` | Save the current document to a `.fig` file |+| `new_document` | Create a new empty document |++### Read++| Tool | Description |+|------|-------------|+| `get_selection` | Get currently selected nodes |+| `get_page_tree` | Get the full node tree of the current page |+| `get_node` | Get detailed properties of a node by ID |+| `find_nodes` | Find nodes by name pattern and/or type |+| `list_pages` | List all pages |+| `list_variables` | List design variables |+| `list_collections` | List variable collections |++### Create++| Tool | Description |+|------|-------------|+| `create_shape` | Create a shape (FRAME, RECTANGLE, ELLIPSE, TEXT, LINE, STAR, POLYGON, SECTION) |+| `render` | Render JSX to design nodes — create entire component trees in one call |+| `create_component` | Convert a frame/group into a component |+| `create_instance` | Create an instance of a component |++### Modify++| Tool | Description |+|------|-------------|+| `set_fill` | Set fill color (hex) |+| `set_stroke` | Set stroke color, weight, alignment |+| `set_effects` | Add shadow or blur effects |+| `update_node` | Update position, size, opacity, corner radius, text, font |+| `set_layout` | Set auto-layout (flexbox) — direction, spacing, padding, alignment |+| `set_constraints` | Set resize constraints |++### Structure++| Tool | Description |+|------|-------------|+| `delete_node` | Delete a node |+| `clone_node` | Duplicate a node |+| `rename_node` | Rename a node |+| `reparent_node` | Move a node into a different parent |+| `select_nodes` | Select nodes by ID |+| `group_nodes` | Group nodes |+| `ungroup_node` | Ungroup a group |++### Navigation++| Tool | Description |+|------|-------------|+| `switch_page` | Switch to a page by name or ID |++### Escape Hatch++| Tool | Description |+|------|-------------|+| `eval` | Execute JavaScript with full Figma Plugin API access |diff --git a/packages/docs/fr/reference/node-types.md b/packages/docs/fr/reference/node-types.mdnew file mode 100644index 000000000..3b4b57fee--- /dev/null+++ b/packages/docs/fr/reference/node-types.md@@ -0,0 +1,194 @@+# Types de nœuds++The scene graph supports 28 node types from Figma's Kiwi schema. Each node is identified by a GUID (`sessionID:localID`) and has a parent reference via `parentIndex`. The OpenPencil engine's `NodeType` union currently uses 17 of these types.++## Type Table++28 Figma schema types + 1 synthetic engine type. Types marked ✅ are in the engine's `NodeType` union (17 total).++| Type | ID | Description | Engine |+|------|----|-------------|--------|+| DOCUMENT | 1 | Root node, one per file | — |+| CANVAS | 2 | Page | ✅ |+| GROUP | 3 | Group container | ✅ |+| FRAME | 4 | Primary container (artboard), supports auto-layout | ✅ |+| BOOLEAN_OPERATION | 5 | Union/subtract/intersect/exclude result | |+| VECTOR | 6 | Freeform vector path | ✅ |+| STAR | 7 | Star shape | ✅ |+| LINE | 8 | Line | ✅ |+| ELLIPSE | 9 | Ellipse/circle, supports arc data | ✅ |+| RECTANGLE | 10 | Rectangle | ✅ |+| REGULAR_POLYGON | 11 | Regular polygon (3–12 sides, engine uses `POLYGON`) | ✅ |+| ROUNDED_RECTANGLE | 12 | Rectangle with smooth corners | ✅ |+| TEXT | 13 | Text with rich formatting | ✅ |+| SLICE | 14 | Export region | |+| SYMBOL | 15 | Component (main, engine uses `COMPONENT`) | ✅ |+| INSTANCE | 16 | Component instance | ✅ |+| STICKY | 17 | FigJam sticky note | |+| SHAPE_WITH_TEXT | 18 | FigJam shape | ✅ |+| CONNECTOR | 19 | Connector line between nodes | ✅ |+| CODE_BLOCK | 20 | FigJam code block | |+| WIDGET | 21 | Plugin widget | |+| STAMP | 22 | FigJam stamp | |+| MEDIA | 23 | Video/GIF | |+| HIGHLIGHT | 24 | FigJam highlight | |+| SECTION | 25 | Canvas section (organizational, top-level only) | ✅ |+| SECTION_OVERLAY | 26 | Section overlay | |+| WASHI_TAPE | 27 | FigJam washi tape | |+| VARIABLE | 28 | Variable definition node | |+| COMPONENT_SET | — | Variant group container (synthetic, mapped from SYMBOL) | ✅ |++### Engine NodeType Union (17 types)++The engine's `NodeType` uses simplified names. Some differ from the Kiwi schema:+- `COMPONENT` → Kiwi `SYMBOL` (ID 15)+- `COMPONENT_SET` → variant group container (no dedicated Kiwi ID, mapped from SYMBOL with variants)+- `POLYGON` → Kiwi `REGULAR_POLYGON` (ID 11)++```typescript+type NodeType =+ | 'CANVAS' | 'FRAME' | 'RECTANGLE' | 'ROUNDED_RECTANGLE'+ | 'ELLIPSE' | 'TEXT' | 'LINE' | 'STAR' | 'POLYGON'+ | 'VECTOR' | 'GROUP' | 'SECTION'+ | 'COMPONENT' | 'COMPONENT_SET' | 'INSTANCE'+ | 'CONNECTOR' | 'SHAPE_WITH_TEXT'+```++## Node Hierarchy++```+Document+├── Canvas (Page 1)+│ ├── Section (top-level only, title pill, auto-adopts siblings)+│ │ ├── Frame+│ │ │ └── ...children+│ │ └── Rectangle+│ ├── Frame+│ │ ├── Rectangle+│ │ ├── Text+│ │ └── Frame (nested)+│ │ ├── Ellipse+│ │ └── Instance (→ references Component)+│ ├── Component+│ │ └── ...children+│ ├── Group+│ │ └── ...children+│ └── BooleanOperation+│ └── ...operand shapes+└── Canvas (Page 2)+ └── ...+```++## Core Properties++Every node carries these fields (subset of NodeChange):++### Identity & Tree++- `guid` — unique identifier (`sessionID:localID`)+- `type` — node type enum+- `name` — display name+- `phase` — CREATED or REMOVED+- `parentIndex` — parent GUID + position string for z-ordering++### Transform++- `size` — width/height vector+- `transform` — 2×3 affine matrix+- `rotation` — degrees++### Appearance++- `fillPaints[]` — fill colors/gradients/images+- `strokePaints[]` — stroke colors+- `effects[]` — shadows, blurs+- `opacity` — 0–1+- `blendMode` — NORMAL, MULTIPLY, SCREEN, etc.++### Stroke++- `strokeWeight` — stroke thickness+- `strokeAlign` — inside / center / outside+- `strokeCap` — butt / round / square+- `strokeJoin` — miter / bevel / round+- `dashPattern[]` — dash/gap lengths++### Corners++- `cornerRadius` — uniform radius+- `cornerSmoothing` — squircle amount (0–1)+- Per-corner radii when `rectangleCornerRadiiIndependent` is true++### Visibility++- `visible` — show/hide+- `locked` — prevent editing++## Type-Specific Properties++### Text++`fontSize`, `fontName`, `lineHeight`, `letterSpacing`, `textAlignHorizontal`, `textAlignVertical`, `textAutoResize`, `textData` (characters, style overrides, baselines, glyphs)++### Vector++`vectorData` (vectorNetworkBlob, normalizedSize), `fillGeometry[]`, `strokeGeometry[]`, `handleMirroring`, `arcData`++### Layout (Frame)++`stackMode`, `stackSpacing`, `stackPadding`, `stackJustify`, `stackCounterAlign`, `stackPrimarySizing`, `stackCounterSizing`, `stackChildPrimaryGrow`, `stackChildAlignSelf`++### Component++`symbolData`, `componentKey`, `componentPropDefs[]`, `symbolDescription`++### Instance++`overriddenSymbolID`, `symbolData.symbolOverrides[]`, `componentPropRefs[]`, `componentPropAssignments[]`++## Paint++```typescript+interface Fill {+ type: 'SOLID' | 'GRADIENT_LINEAR' | 'GRADIENT_RADIAL' |+ 'GRADIENT_ANGULAR' | 'GRADIENT_DIAMOND' | 'IMAGE'+ color: Color // {r, g, b, a} 0–1 floats+ opacity: number // 0–1+ visible: boolean+ blendMode?: BlendMode+ gradientStops?: GradientStop[] // for gradients+ gradientTransform?: GradientTransform // 2×3 matrix+ imageHash?: string // for image fills+ imageScaleMode?: 'FILL' | 'FIT' | 'CROP' | 'TILE'+ imageTransform?: GradientTransform+}+```++## Effect++```typescript+interface Effect {+ type: 'DROP_SHADOW' | 'INNER_SHADOW' | 'LAYER_BLUR' |+ 'BACKGROUND_BLUR' | 'FOREGROUND_BLUR'+ color: Color+ offset: { x: number; y: number }+ radius: number+ spread: number+ visible: boolean+}+```++## Stroke++```typescript+interface Stroke {+ color: Color+ weight: number+ opacity: number+ visible: boolean+ align: 'INSIDE' | 'CENTER' | 'OUTSIDE'+ cap?: 'NONE' | 'ROUND' | 'SQUARE' | 'ARROW_LINES' | 'ARROW_EQUILATERAL'+ join?: 'MITER' | 'BEVEL' | 'ROUND'+ dashPattern?: number[]+}+```diff --git a/packages/docs/fr/reference/scene-graph.md b/packages/docs/fr/reference/scene-graph.mdnew file mode 100644index 000000000..667d41c56--- /dev/null+++ b/packages/docs/fr/reference/scene-graph.md@@ -0,0 +1,99 @@+# Graphe de scène++## In-Memory Representation++Nodes live in a flat `Map<string, Node>` keyed by GUID string. The tree structure is maintained via `parentIndex` references. This gives O(1) lookup by ID and efficient traversal.++```typescript+interface SceneGraph {+ nodes: Map<string, Node>+ root: string++ getNode(id: string): Node+ getChildren(id: string): Node[]+ getParent(id: string): Node | null+ getPages(): Node[]++ createNode(type: NodeType, parent: string, props: Partial<NodeChange>): Node+ updateNode(id: string, changes: Partial<NodeChange>): void+ deleteNode(id: string): void+ moveNode(id: string, newParent: string, position: string): void+ addPage(name: string): Node+ deletePage(id: string): void+ renamePage(id: string, name: string): void++ findByType(type: NodeType): Node[]+ findByName(pattern: string): Node[]+ hitTest(point: Vector, canvas: string): Node | null+ getNodesInRect(rect: Rect, canvas: string): Node[]+}+```++## Pages++Documents support multiple pages (CANVAS nodes as direct children of the DOCUMENT root). Each page has its own child tree and independent viewport state (panX, panY, zoom, pageColor). The editor tracks `currentPageId` and renders only the active page's children.++## Sections++SECTION nodes are top-level organizational containers (direct children of CANVAS only). They cannot nest inside frames or groups. Creating a section auto-adopts overlapping siblings. Sections display a title pill with luminance-adaptive text color.++## Hover State++The editor state tracks `hoveredNodeId` — the node currently under the cursor. The renderer draws a shape-aware hover outline (following actual geometry for ellipses, rounded rects, vectors) for visual feedback before selection.++## Undo/Redo++The system uses Figma's **inverse command** pattern. Each undo entry contains the forward changes and their automatically-computed inverse:++| Operation | Forward | Inverse |+|-----------|---------|---------|+| Create node | `{guid, phase: CREATED, ...props}` | `{guid, phase: REMOVED}` |+| Delete node | `{guid, phase: REMOVED}` | `{guid, phase: CREATED, ...allProps}` |+| Change prop | `{guid, fill: "#F00"}` | `{guid, fill: "#00F"}` |+| Move node | `{guid, parentIndex: newParent}` | `{guid, parentIndex: oldParent}` |++Before applying any change, affected fields are snapshotted. The snapshot becomes the inverse.++**Batching** — operations like drag-to-move produce hundreds of position changes per second. These are debounced into a single undo entry. `beginBatch`/`commitBatch` wraps multi-step operations.++## Layout Engine (Yoga)++Figma's auto-layout properties map to Yoga flexbox:++| Figma Property | Yoga Equivalent |+|---|---|+| `stackMode: HORIZONTAL` | `flexDirection: row` |+| `stackMode: VERTICAL` | `flexDirection: column` |+| `stackSpacing` | `gap` |+| `stackPadding` | `padding` |+| `stackJustify: MIN/CENTER/MAX/SPACE_BETWEEN` | `justifyContent` |+| `stackCounterAlign` | `alignItems` |+| `stackPrimarySizing: FIXED/HUG/FILL` | width/height + flex-grow |+| `stackChildPrimaryGrow` | `flexGrow` |+| `stackChildAlignSelf` | `alignSelf` |+| `stackPositioning: ABSOLUTE` | `position: absolute` |++## Hit Testing++Given a point in canvas coordinates, the scene graph returns the topmost visible node at that position. The algorithm:++1. Traverse visible nodes in reverse z-order (top to bottom)+2. Transform the test point into each node's local coordinate system+3. Check if the point is within the node's bounds (including rotation)+4. Return the first match++For marquee selection, `getNodesInRect` returns all nodes whose bounds intersect the given rectangle.++## Extended Fill Types++Fills support six types: SOLID, GRADIENT_LINEAR, GRADIENT_RADIAL, GRADIENT_ANGULAR, GRADIENT_DIAMOND, and IMAGE. Gradient fills carry `gradientStops` (color + position pairs) and a `gradientTransform` (2×3 matrix). Image fills reference blob data via `imageHash` with scale modes (FILL, FIT, CROP, TILE).++## Extended Stroke Properties++Strokes support `cap` (NONE, ROUND, SQUARE, ARROW_LINES, ARROW_EQUILATERAL), `join` (MITER, BEVEL, ROUND), and `dashPattern` (array of dash/gap lengths) in addition to the base color, weight, opacity, visible, and align properties.++## Coordinate System++Nodes store position and size relative to their parent. To get absolute (canvas) coordinates, walk up the parent chain applying transforms. The renderer uses this to draw nested frames with correct positioning.++Rotation is stored in degrees and applied as part of the 2×3 transform matrix. Snap guides and hit testing account for rotation when computing visual bounds.diff --git a/packages/docs/it/development/contributing.md b/packages/docs/it/development/contributing.mdnew file mode 100644index 000000000..5e26dfd1a--- /dev/null+++ b/packages/docs/it/development/contributing.md@@ -0,0 +1,94 @@+# Contribuire++## Project Structure++```+packages/+ core/ @open-pencil/core — engine (zero DOM deps)+ src/ Scene graph, renderer, layout, codec, kiwi, types+ cli/ @open-pencil/cli — headless CLI for .fig operations+ src/commands/ info, tree, find, export+src/+ components/ Vue SFCs (canvas, panels, toolbar, color picker)+ properties/ Property panel sections (Appearance, Fill, Stroke, etc.)+ composables/ Canvas input, keyboard shortcuts, rendering hooks+ stores/ Editor state (Vue reactivity)+ engine/ Re-export shims from @open-pencil/core+ kiwi/ Re-export shims from @open-pencil/core+ types.ts Shared types (re-exported from core)+ constants.ts UI colors, defaults, thresholds+desktop/ Tauri v2 (Rust + config)+tests/+ e2e/ Playwright visual regression+ engine/ Unit tests (bun:test)+docs/ VitePress documentation site+openspec/+ specs/ Capability specifications (source of truth)+ changes/ Active and archived changes+```++## Development Setup++```sh+bun install+bun run dev # Editor at localhost:1420+bun run docs:dev # Docs at localhost:5173+```++## Code Style++### Tooling++| Tool | Command | Purpose |+|------|---------|---------|+| oxlint | `bun run lint` | Linting (Rust-based, fast) |+| oxfmt | `bun run format` | Code formatting |+| tsgo | `bun run typecheck` | Type checking (Go-based TypeScript checker) |++Run all checks:++```sh+bun run check+```++### Conventions++- **File names** — kebab-case (`scene-graph.ts`, `use-canvas-input.ts`)+- **Components** — PascalCase Vue SFCs (`EditorCanvas.vue`, `ScrubInput.vue`)+- **Constants** — SCREAMING_SNAKE_CASE+- **Functions/variables** — camelCase+- **Types/interfaces** — PascalCase++### AI Agent Conventions++Developers and AI agents working on the codebase should read `AGENTS.md` in the repo root ([view on GitHub](https://github.com/open-pencil/open-pencil/blob/master/AGENTS.md)). Covers rendering, scene graph, components & instances, layout, UI, file format, Tauri conventions, and known issues.++## Making Changes++1. Check existing [openspec specs](/development/openspec) for the capability you're modifying+2. Create an openspec change if adding new behavior: `openspec new change "my-change"`+3. Implement the change+4. Run `bun run check` and `bun run test`+5. Submit a pull request++## 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.++| 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/layout.ts` | Yoga layout adapter |+| `packages/core/src/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/kiwi/fig-import.ts` | .fig file import logic |+| `packages/cli/src/index.ts` | CLI entry point |+| `packages/cli/src/commands/` | CLI commands (info, tree, find, export) |+| `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 |diff --git a/packages/docs/it/development/openspec.md b/packages/docs/it/development/openspec.mdnew file mode 100644index 000000000..4907fe432--- /dev/null+++ b/packages/docs/it/development/openspec.md@@ -0,0 +1,107 @@+# Workflow OpenSpec++OpenPencil uses [OpenSpec](https://github.com/Fission-AI/OpenSpec) for spec-driven development. Specifications are the source of truth for what the system does.++## Structure++```+openspec/+├── specs/ # Source of truth: how the system works now+│ ├── scene-graph/+│ │ └── spec.md+│ ├── canvas-rendering/+│ │ └── spec.md+│ ├── auto-layout/+│ │ └── spec.md+│ └── ... # 19 capability specs total+├── changes/ # Proposed changes (one directory per change)+│ └── archive/ # Completed changes+└── config.yaml # Optional configuration+```++## Current Specs++| Capability | Description |+|-----------|-------------|+| scene-graph | Flat Map storage, CRUD, hit testing |+| canvas-rendering | CanvasKit WASM rendering pipeline |+| canvas-navigation | Pan, zoom, hand tool |+| selection-manipulation | Click/marquee select, move, resize, rotate |+| undo-redo | Inverse-command pattern |+| text-editing | Text tool, Paragraph API, font loading |+| pen-tool | Vector network model, bezier curves |+| auto-layout | Yoga WASM flexbox, Shift+A toggle |+| figma-clipboard | Bidirectional Kiwi binary clipboard |+| fig-import | .fig file import pipeline |+| kiwi-codec | Kiwi binary codec, sparse field IDs |+| editor-ui | Vue 3 panels, toolbar, color picker |+| snap-guides | Edge/center snapping, rotation-aware |+| rulers | Canvas rulers, selection highlight |+| group-ungroup | ⌘G/⇧⌘G, position-based sort |+| desktop-app | Tauri v2, macOS menu bar |+| testing | Playwright E2E, bun:test unit |+| scrub-input | Drag-to-scrub numeric inputs |+| tooling | Vite 7, oxlint, oxfmt, tsgo, VitePress |++## Workflow++### 1. Propose a Change++```+/opsx:propose add-dark-mode+```++Creates `openspec/changes/add-dark-mode/` with:+- `proposal.md` — why and what changes+- `design.md` — technical approach+- `specs/` — delta specifications (ADDED/MODIFIED/REMOVED requirements)+- `tasks.md` — implementation checklist++### 2. Implement++```+/opsx:apply+```++Execute tasks from tasks.md, checking off items as they're completed.++### 3. Archive++```+/opsx:archive+```++- Merges delta specs into `openspec/specs/` (the baseline)+- Moves the change to `openspec/changes/archive/`++## Spec Format++Each spec file follows a consistent structure:++```markdown+# capability-name Specification++## Purpose+One-line description of what this capability does.++## Requirements++### Requirement: Name+Description using SHALL/MUST for normative requirements.++#### Scenario: Name+- **WHEN** condition+- **THEN** expected outcome+```++Every requirement has at least one scenario. Scenarios are potential test cases.++## CLI Commands++```sh+openspec list # List active changes+openspec show <name> # Show change details+openspec status --change <name> # Artifact status+openspec archive <name> # Archive completed change+openspec update # Regenerate skills/prompts+```diff --git a/packages/docs/it/development/roadmap.md b/packages/docs/it/development/roadmap.mdnew file mode 100644index 000000000..5c9d3753f--- /dev/null+++ b/packages/docs/it/development/roadmap.md@@ -0,0 +1,145 @@+# Roadmap++## Phases++### Phase 1: Core Engine ✅++SceneGraph, Skia rendering, basic shapes, selection, zoom/pan, undo/redo.++**Delivered:**+- Scene graph with flat Map storage and parent-child tree+- CanvasKit WASM rendering for all shape types+- Click/shift/marquee selection with resize handles and rotation+- Zoom/pan with keyboard shortcuts and trackpad gestures+- Undo/redo wired into all operations+- Snap guides with edge and center snapping++### Phase 2: Editor UI + Layout ✅++Properties panel, layers panel, toolbar, Yoga layout integration, text editing.++**Delivered:**+- Vue 3 + Reka UI panels (properties, layers, toolbar)+- Properties panel split into sections (Appearance, Fill, Stroke, Typography, Layout, Position)+- ScrubInput component for all numeric inputs+- Color picker (HSV, hex, opacity)+- Layers panel with tree view, drag reorder, visibility toggle+- Auto-layout with Yoga WASM (direction, gap, padding, justify, align)+- Inline text editing with CanvasKit Paragraph API+- System font loading via Local Font Access API+- Canvas rulers with selection highlight++### Phase 3: File I/O + Visual Features ✅++.fig import/export, Kiwi codec, clipboard, sections, pages, advanced rendering.++**Delivered:**+- .fig file import via Kiwi binary codec+- .fig file export with Kiwi encoding, Zstd compression, thumbnail generation+- Save (⌘S) and Save As (⇧⌘S) with native OS dialogs+- Zstd compression via Tauri Rust command (deflate fallback in browser)+- Vendored kiwi-schema with ESM + sparse field ID patches+- Figma-compatible clipboard (bidirectional Kiwi binary)+- Pen tool with vector network model+- vectorNetworkBlob binary encode/decode+- Group/ungroup (⌘G/⇧⌘G)+- Tauri v2 desktop app with native menu bar (macOS/Windows/Linux)+- Sections (S key) with title pills, auto-adopt, luminance-adaptive text+- Multi-page documents with pages panel, per-page viewport+- Hover highlight with shape-aware outlines+- Tier 1 rendering: gradients, image fills, effects, strokes (cap/join/dash), arcs+- Fill type picker with solid/gradient/image tabs and gradient stop editing+- Canvas background color per page+- Fig-import unit tests, layout unit tests, layers-panel E2E tests++### Phase 4: Components + Variables ✅++Components, instances, overrides, variables, collections, modes, image export.++**Delivered:**+- Component creation from frame/group or multi-selection (⌥⌘K)+- Component sets from multiple components (⇧⌘K) with dashed purple border+- Instance creation from components with child cloning and componentId mapping+- Live component-instance sync with override preservation+- Detach instance back to frame (⌥⌘B)+- Go to main component (cross-page navigation)+- Always-visible purple component/instance labels with diamond icon+- Opaque container hit testing (click selects component, double-click enters)+- Right-click context menu with clipboard, z-order, grouping, component, visibility, lock, move-to-page actions+- Z-order manipulation (] bring to front, [ send to back)+- Toggle visibility (⇧⌘H) and lock (⇧⌘L)+- Move nodes between pages via context menu+- Viewport culling, Paint reuse, RAF render coalescing+- Effects panel UI (drop shadow, inner shadow, layer/background/foreground blur)+- Independent corner radius controls (per-corner toggle in Appearance section)+- GitHub Actions CI/CD for Windows (x64, arm64) and macOS (x64, arm64) builds+- Polygon and Star drawing tools with pointCount and starInnerRadius+- Resizable left/right panels via reka-ui Splitter (persistent layout)+- @/ import alias, shared types module (src/types.ts, src/global.d.ts)+- Codebase lint-clean: 0 oxlint warnings, 0 tsgo type errors+- Variables: COLOR type with collections, modes, bindings, FillSection variable picker, .fig import+- Variables dialog: TanStack Table with resizable columns, mode columns, collection tabs with rename, search, demo collections (Primitives/Semantic/Spacing), undo/redo for all variable operations+- Image export: PNG/JPG/WEBP with ExportSection (scale, format, live preview), ⇧⌘E shortcut, context menu+- Canvas-native text editing: TextEditor class in core, phantom textarea, cursor/selection/word boundaries on canvas, caret blinking, selection highlights+- System font enumeration via font-kit Rust crate, OnceLock cache, preload on startup+- Font picker: virtual scroll (reka-ui ListboxVirtualizer), search filter, CSS font preview+- ColorInput component extraction, ColorPicker alpha slider checkerboard fix+- App identity: pencil icon, Cargo crate open_pencil, macOS Dock "OpenPencil"+- Splash loader during WASM initialization+- Rich text style runs: per-selection ⌘B/I/U, StyleRun model, ParagraphBuilder pushStyle/pop, .fig roundtrip+- B/I/U/S toggle buttons in TypographySection+- Double-click (word), triple-click (select all) text selection++**Remaining (deferred to Phase 6):**+- Variant switching+- Variable types: FLOAT, STRING, BOOLEAN editing UI+- Variable-driven theming++### Phase 5: AI Integration & Tooling 🟡++Core extraction, CLI, MCP server, design guidelines, screenshot verification loop.++**Delivered:**+- @open-pencil/core extracted to packages/core/ (zero DOM deps, Bun workspace)+- @open-pencil/cli with headless .fig operations (info, tree, find, export, analyze, node, pages, variables), CanvasKit CPU rasterization, --json output+- JSX renderer: TreeNode builders (Frame, Text, Rectangle, etc.), renderTreeNode/renderJsx, Tailwind-like shorthand props, 27 tests+- jscpd copy-paste detection (15.6% → 0.62%), kiwi-serialize.ts consolidation+- .fig roundtrip tests with LFS fixtures (material3.fig 87K nodes, nuxtui.fig 314K nodes)+- .fig import O(n²) → O(n) fix (37s → 535ms on 87K nodes), ByteBuffer optimization+- test:coverage script+- AI chat: OpenRouter direct (no backend), Stronghold key storage, 26 tools (create_shape, set_fill, set_effects, set_constraints, components, groups, pages, variables, eval_code, etc.), model selector, ⌘J toggle, streaming markdown, Playwright tests with mock transport+- Code panel: sceneNodeToJsx() export, Prism.js highlighting, line numbers, copy button, 14 tests+- Properties panel restructured: Design | Code | AI tabs+- npm publishing preparation for core and cli packages++**Planned:**+- Port remaining figma-use tools (118 total, 26 currently implemented)+- Attached mode: WebSocket to running editor for eval, create, export, screenshot+- Design guidelines system+- AI-driven design workflow via MCP+- Screenshot verification loop++### Phase 6: Polish + Distribution 🔲++Prototyping, comments, desktop distribution, documentation, public launch.++**Planned:**+- Prototyping (frame connections, transitions)+- Comments (pin, threads, resolve)+- Linux Tauri builds (macOS and Windows already covered by CI)+- PWA support+- Documentation site (VitePress)+- Performance optimization (Lighthouse > 90)+- Full Figma compatibility test suite+- Deferred from Phase 4: variant switching, FLOAT/STRING/BOOLEAN variable UI, variable-driven theming++## Timeline++| Phase | Estimated Duration | Status |+|-------|-------------------|--------|+| Phase 1: Core Engine | 3 months | ✅ Complete |+| Phase 2: Editor UI + Layout | 3 months | ✅ Complete |+| Phase 3: File I/O + Visual Features | 2 months | ✅ Complete |+| Phase 4: Components + Variables | 2 months | ✅ Complete |+| Phase 5: AI Integration & Tooling | 2 months | 🟡 In Progress |+| Phase 6: Polish + Distribution | 2 months | 🔲 Planned |diff --git a/packages/docs/it/development/testing.md b/packages/docs/it/development/testing.mdnew file mode 100644index 000000000..efecd9257--- /dev/null+++ b/packages/docs/it/development/testing.md@@ -0,0 +1,91 @@+# Testing++## Overview++| Type | Framework | Command | Location |+|------|-----------|---------|----------|+| E2E visual regression | Playwright | `bun run test` | `tests/e2e/` |+| Figma CDP reference | Playwright | `bun run test:figma` | `tests/figma/` |+| Unit tests | bun:test | `bun run test:unit` | `tests/engine/` |++## E2E Visual Regression++Playwright creates shapes on the canvas and compares screenshots against baseline PNGs.++```sh+bun run test # Run tests, compare against baselines+bun run test:update # Regenerate baseline screenshots+```++### How It Works++1. Tests load the editor in a headless browser+2. The editor signals readiness via a `data-ready` HTML attribute+3. Tests create shapes via the editor's API+4. Screenshots are taken and compared against baselines using `toMatchSnapshot`+5. Page is reused across test cases for speed (~2s total)++### No-Chrome Test Mode++The editor supports a test mode that hides UI chrome (toolbar, panels) for clean screenshot capture. Activated via URL parameter.++## Figma CDP Reference Tests++A separate Playwright project connects to Figma via Chrome DevTools Protocol to capture reference screenshots for pixel-perfect comparison.++```sh+bun run figma:debug # Launch Figma with debugging port+bun run test:figma # Connect to Figma, capture references+```++Requires Figma desktop app running with `--remote-debugging-port=9222`.++## Unit Tests++Engine unit tests use bun:test and target < 50ms execution:++```sh+bun run test:unit+```++Tests cover:+- Scene graph CRUD operations, parent-child relationships, z-ordering, hit testing+- **Fig-import pipeline** — node type mapping, transforms, fills/strokes/effects, gradients, images, arcs, nested hierarchies (`tests/engine/fig-import.test.ts`)+- **Layout computation** — Yoga auto-layout: direction, gap, padding, justify, align, child sizing (fixed/fill/hug), cross-axis sizing, wrap, nested layouts (`tests/engine/layout.test.ts`)++### Writing Unit Tests++```typescript+import { describe, expect, it } from 'bun:test'+import { SceneGraph } from '../../src/engine/scene-graph'++describe('SceneGraph', () => {+ it('creates and retrieves a node', () => {+ const sg = new SceneGraph()+ const node = sg.createNode('RECTANGLE', sg.root, { name: 'Test' })+ expect(sg.getNode(node.guid)).toBeDefined()+ })+})+```++## E2E Test Coverage++| Test file | Scope |+|-----------|-------|+| `tests/e2e/layers-panel.spec.ts` | Layers panel tree structure, visibility toggles, selection sync |+| `tests/e2e/visual.spec.ts` | Visual regression screenshots for shapes and rendering |++## Test Helpers++| File | Purpose |+|------|---------|+| `tests/helpers/canvas.ts` | Canvas setup and interaction utilities |+| `tests/helpers/figma.ts` | Figma CDP connection helpers |++## Performance Targets++| Metric | Target |+|--------|--------|+| E2E suite total | < 3s |+| Unit test suite total | < 50ms |+| Screenshot comparison | toMatchSnapshot (pixel-level) |diff --git a/packages/docs/it/eval-command.md b/packages/docs/it/eval-command.mdnew file mode 100644index 000000000..9f7c45018--- /dev/null+++ b/packages/docs/it/eval-command.md@@ -0,0 +1,437 @@+# `open-pencil eval` — Figma-like Plugin API for Headless Scripting++## Overview++`bun open-pencil eval <file> --code '<js>'` executes JavaScript against a `.fig` file with a Figma-compatible `figma` global object. This enables headless scripting, batch operations, AI tool execution, and testing — all without the GUI.++The `figma` object mirrors Figma's Plugin API surface as closely as possible, so existing Figma plugin knowledge and code snippets transfer directly.++```bash+# Create a frame, set auto-layout, add children+bun open-pencil eval design.fig --code '+ const frame = figma.createFrame()+ frame.name = "Card"+ frame.resize(300, 200)+ frame.layoutMode = "VERTICAL"+ frame.itemSpacing = 12+ frame.paddingTop = frame.paddingBottom = 16+ frame.paddingLeft = frame.paddingRight = 16+ frame.fills = [{ type: "SOLID", color: { r: 1, g: 1, b: 1 } }]++ const title = figma.createText()+ title.characters = "Hello World"+ title.fontSize = 24+ frame.appendChild(title)++ return { id: frame.id, name: frame.name }+'++# Query nodes+bun open-pencil eval design.fig --code '+ const buttons = figma.currentPage.findAll(n => n.type === "FRAME" && n.name.includes("Button"))+ return buttons.map(b => ({ id: b.id, name: b.name, w: b.width, h: b.height }))+'++# Read from stdin (for multiline scripts / piping)+cat transform.js | bun open-pencil eval design.fig --stdin++# Write changes back+bun open-pencil eval design.fig --code '...' --write+bun open-pencil eval design.fig --code '...' -o modified.fig+```++## Architecture++```+┌──────────────────────────────────────────────────────┐+│ CLI: `open-pencil eval <file> --code '...'` │+│ ↓ │+│ loadDocument(file) → SceneGraph │+│ ↓ │+│ FigmaAPI(sceneGraph) → `figma` proxy object │+│ ↓ │+│ AsyncFunction('figma', wrappedCode)(figmaProxy) │+│ ↓ │+│ print result as JSON / agentfmt │+│ optionally: saveDocument(file) if --write │+└──────────────────────────────────────────────────────┘+```++### Key classes++| 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.) |+| `eval` command | `packages/cli/src/commands/eval.ts` | CLI command that loads doc, creates API, executes code |++### Why in `@open-pencil/core`?++The `FigmaAPI` class lives in core (not CLI) because:+- **AI tools reuse it** — the chat panel's `render` tool can execute JSX through the same API+- **Test scripts** — unit tests can use the API to set up fixtures+- **No DOM deps** — runs headless in Bun, no browser APIs needed++## `FigmaAPI` — Phased Implementation++### Phase 1: Core (MVP for eval command)++These cover ~80% of real plugin scripts:++#### Document & Page++| Figma API | Our implementation | Notes |+|-----------|--------------------|-------|+| `figma.root` | Getter → proxy for root node | `.children` returns page proxies |+| `figma.currentPage` | Getter/setter → first page by default | Settable to any page proxy |+| `figma.currentPage.selection` | Get/set → tracked selection array | |+| `figma.getNodeById(id)` | `graph.getNode(id)` wrapped in proxy | Sync, like Figma's deprecated version |++#### Node Creation++| Figma API | Maps to |+|-----------|---------|+| `figma.createFrame()` | `graph.createNode('FRAME', currentPageId)` |+| `figma.createRectangle()` | `graph.createNode('RECTANGLE', ...)` |+| `figma.createEllipse()` | `graph.createNode('ELLIPSE', ...)` |+| `figma.createText()` | `graph.createNode('TEXT', ...)` |+| `figma.createLine()` | `graph.createNode('LINE', ...)` |+| `figma.createPolygon()` | `graph.createNode('POLYGON', ...)` |+| `figma.createStar()` | `graph.createNode('STAR', ...)` |+| `figma.createComponent()` | `graph.createNode('COMPONENT', ...)` |+| `figma.createPage()` | `graph.addPage(name)` |+| `figma.createSection()` | `graph.createNode('SECTION', ...)` |++#### Node Properties (via `FigmaNode` proxy)++Read/write on any node proxy. Property access maps to `SceneNode` fields:++```ts+// Geometry+node.x, node.y // direct+node.width, node.height // read-only, use node.resize(w, h)+node.rotation // direct+node.resize(w, h) // updates width + height+node.resizeWithoutConstraints(w, h) // same (no constraint engine yet)++// Visual+node.fills // get/set Fill[]+node.strokes // get/set Stroke[]+node.effects // get/set Effect[]+node.opacity // get/set number+node.visible // get/set boolean+node.locked // get/set boolean+node.blendMode // get/set BlendMode+node.clipsContent // get/set boolean++// Corner radius+node.cornerRadius // get/set (number or figma.mixed)+node.topLeftRadius // get/set+node.topRightRadius // get/set+node.bottomLeftRadius // get/set+node.bottomRightRadius // get/set+node.cornerSmoothing // get/set++// Identity+node.id // read-only+node.name // get/set+node.type // read-only+node.parent // read-only → FigmaNode | null+node.removed // read-only boolean+```++#### Tree Operations++```ts+node.children // read-only FigmaNode[]+node.appendChild(child) // reparent to end+node.insertChild(index, child) // reparent at index+node.remove() // graph.deleteNode(id)++// Traversal+node.findAll(callback?) // recursive find+node.findOne(callback) // first match+node.findChild(callback) // direct children only+node.findChildren(callback?) // direct children only+```++#### Auto-layout++```ts+node.layoutMode // 'NONE' | 'HORIZONTAL' | 'VERTICAL'+node.primaryAxisAlignItems // 'MIN' | 'CENTER' | 'MAX' | 'SPACE_BETWEEN'+node.counterAxisAlignItems // 'MIN' | 'CENTER' | 'MAX' | 'BASELINE'+node.itemSpacing // number+node.counterAxisSpacing // number | null+node.paddingTop / Right / Bottom / Left // number+node.layoutWrap // 'NO_WRAP' | 'WRAP'++// Child sizing+node.layoutPositioning // 'AUTO' | 'ABSOLUTE'+node.layoutGrow // 0 | 1+node.layoutSizingHorizontal // 'FIXED' | 'HUG' | 'FILL'+node.layoutSizingVertical // 'FIXED' | 'HUG' | 'FILL'+```++#### Text++```ts+node.characters // get/set (maps to node.text)+node.fontSize // get/set+node.fontName // get/set { family, style }+node.fontWeight // get/set+node.textAlignHorizontal // get/set+node.textAlignVertical // get/set+node.textAutoResize // get/set+node.letterSpacing // get/set+node.lineHeight // get/set+node.maxLines // get/set+node.textCase // get/set+node.textDecoration // get/set+```++#### Stroke details++```ts+node.strokeWeight // get/set (maps to strokes[0].weight)+node.strokeAlign // get/set (maps to strokes[0].align)+node.dashPattern // get/set+```++#### Misc++```ts+figma.mixed // Symbol sentinel for mixed values+figma.group(nodes, parent) // creates GROUP with given children+figma.ungroup(node) // ungroups, reparents children+figma.flatten(nodes) // NOT IMPLEMENTED YET — returns first node+```++#### Export++```ts+node.exportAsync(settings?) // only works if CanvasKit is loaded+ // settings: { format: 'PNG'|'JPG'|'SVG', constraint? }+```++### Phase 2: Components & Instances++| API | Maps to |+|-----|---------|+| `figma.createComponent()` | `graph.createNode('COMPONENT', ...)` |+| `figma.createComponentFromNode(node)` | Convert existing frame to component |+| `figma.combineAsVariants(components, parent)` | Create COMPONENT_SET |+| Node: `node.createInstance()` | `graph.createInstance(componentId, parentId)` |+| Node: `node.detachInstance()` | `graph.detachInstance(id)` |+| `figma.getNodeById(id).mainComponent` | `graph.getMainComponent(id)` |++### Phase 3: Variables++| API | Maps to |+|-----|---------|+| `figma.variables.getLocalVariables(type?)` | `graph.variables` filtered |+| `figma.variables.getLocalVariableCollections()` | `graph.variableCollections` |+| `figma.variables.createVariable(name, collection, type)` | `graph.addVariable(...)` |+| `figma.variables.createVariableCollection(name)` | `graph.addCollection(...)` |+| `figma.variables.getVariableById(id)` | `graph.variables.get(id)` |+| `node.setBoundVariable(field, variable)` | `graph.bindVariable(...)` |+| `node.boundVariables` | getter from SceneNode |++### Phase 4: Styles & Advanced++| API | Notes |+|-----|-------|+| `figma.createPaintStyle()` | Requires style storage in SceneGraph |+| `figma.createTextStyle()` | Requires style storage in SceneGraph |+| `figma.createEffectStyle()` | Requires style storage in SceneGraph |+| `figma.loadFontAsync(fontName)` | No-op (we don't have font loading constraints) |+| `figma.listAvailableFontsAsync()` | Return system fonts if available |+| Boolean operations (`union`, `subtract`, `intersect`, `exclude`) | Requires path boolean engine |+| `figma.createNodeFromJSXAsync(jsx)` | Port figma-use's JSX renderer |++## `FigmaNode` Proxy Design++The proxy wraps a `SceneNode` and translates Figma property names to our internal names. Key mappings:++```ts+const PROPERTY_MAP: Record<string, string> = {+ // Figma name → SceneNode field name (only where they differ)+ 'characters': 'text',+ 'strokeWeight': → computed from strokes[0].weight,+ 'strokeAlign': → computed from strokes[0].align,+ 'fontName': → computed from { family: fontFamily, style: ... },+ 'primaryAxisAlignItems': 'primaryAxisAlign',+ 'counterAxisAlignItems': 'counterAxisAlign',+ 'primaryAxisSizingMode': 'primaryAxisSizing', // value mapping: 'AUTO' → 'HUG', 'FIXED' → 'FIXED'+ 'counterAxisSizingMode': 'counterAxisSizing',+ 'layoutSizingHorizontal': → computed from primaryAxisSizing / counterAxisSizing depending on layoutMode+ 'layoutSizingVertical': → computed+}+```++Methods on the proxy:++```ts+class FigmaNode {+ // The proxy is created via: new Proxy(target, handler)+ // where handler.get intercepts property reads and handler.set intercepts writes++ resize(width: number, height: number): void+ resizeWithoutConstraints(width: number, height: number): void+ remove(): void+ appendChild(child: FigmaNode): void+ insertChild(index: number, child: FigmaNode): void+ findAll(callback?: (node: FigmaNode) => boolean): FigmaNode[]+ findOne(callback: (node: FigmaNode) => boolean): FigmaNode | null+ findChild(callback: (node: FigmaNode) => boolean): FigmaNode | null+ findChildren(callback?: (node: FigmaNode) => boolean): FigmaNode[]+ exportAsync(settings?: ExportSettings): Promise<Uint8Array>++ // Components (Phase 2)+ createInstance(): FigmaNode+ detachInstance(): void+ get mainComponent(): FigmaNode | null+}+```++## CLI Command++```+bun open-pencil eval <file> [options]++Arguments:+ file .fig file to operate on++Options:+ --code, -c JavaScript code to execute (has access to `figma` global)+ --stdin Read code from stdin instead of --code+ --write, -w Write changes back to the input file+ -o, --output Write to a different file+ --json Output result as JSON (default for non-TTY)+ --quiet, -q Suppress output, only write file+```++### Execution model++1. Load `.fig` → `SceneGraph`+2. Create `FigmaAPI(graph)` → `figma` proxy+3. Wrap user code in async function: `return (async () => { <code> })()`+4. Execute with `figma` as sole argument+5. Print return value (JSON or agentfmt)+6. If `--write` or `-o`: serialize `SceneGraph` back to `.fig`++### Return value formatting++- `undefined` / `void` → no output+- Primitives → printed directly+- Objects/arrays → `JSON.stringify(result, null, 2)` or agentfmt tables+- `FigmaNode` → serialized as `{ id, type, name, x, y, width, height, fills, ... }`+- Arrays of `FigmaNode` → serialized as list++## 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`:++```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)+execute: async ({ type, x, y, width, height }) => {+ const frame = figma.createFrame()+ frame.resize(width, height)+ frame.x = x+ frame.y = y+ return { id: frame.id }+}+```++This ensures CLI scripts and AI tools behave identically.++## File Layout++```+packages/core/src/+ figma-api.ts # FigmaAPI class + FigmaNode proxy (Phase 1–4)+ figma-api.test.ts # Unit tests against headless SceneGraph++packages/cli/src/commands/+ eval.ts # CLI command++packages/cli/src/commands/eval.test.ts # Integration tests+```++## Test Plan++### Unit tests (`packages/core/src/figma-api.test.ts`)++1. **Node creation** — each `createX()` creates correct type, added to current page+2. **Property access** — `.fills`, `.x`, `.width`, `.name`, `.characters` read/write correctly+3. **Resize** — `.resize(w, h)` updates width/height+4. **Tree operations** — `.appendChild()`, `.insertChild()`, `.remove()`, `.parent`, `.children`+5. **Traversal** — `.findAll()`, `.findOne()`, `.findChild()`, `.findChildren()` with callbacks+6. **Auto-layout** — `.layoutMode`, `.itemSpacing`, `.paddingTop`, etc.+7. **Text** — `.characters` maps to `.text`, `.fontName` maps to `{ family, style }`+8. **Mixed values** — `.cornerRadius` returns `figma.mixed` when corners differ+9. **Selection** — `figma.currentPage.selection` get/set+10. **Page switching** — `figma.currentPage = page2` works+11. **Group/ungroup** — `figma.group()` creates group, `figma.ungroup()` dissolves it+12. **Clone** — node creation produces independent copies++### CLI integration tests (`packages/cli/src/commands/eval.test.ts`)++1. **Basic eval** — `eval test.fig --code 'return figma.currentPage.name'` → page name+2. **Create + read** — create a frame, return its properties+3. **Query nodes** — `findAll` returns correct nodes+4. **Write back** — `--write` saves changes, reloading shows them+5. **Stdin** — `echo 'return 42' | bun open-pencil eval test.fig --stdin` → `42`+6. **JSON output** — `--json` returns valid JSON+7. **Error handling** — syntax errors, runtime errors reported cleanly++## Implementation Order++1. **`FigmaNode` proxy** — property mapping, `.resize()`, `.remove()`, tree methods+2. **`FigmaAPI` class** — `createFrame/Rectangle/...`, `.root`, `.currentPage`, `.getNodeById()`, `.mixed`, `.group()`+3. **CLI `eval` command** — argument parsing, code wrapping, output formatting+4. **Unit tests** — all 12 test groups above+5. **CLI integration tests** — all 7 test groups above+6. **Wire to AI tools** — refactor `src/ai/tools.ts` to use `FigmaAPI` where possible+7. **Phase 2** — components & instances+8. **Phase 3** — variables+9. **Phase 4** — styles, boolean ops, JSX renderer++## Property Mapping Reference++| Figma Property | SceneNode Field | Type | Notes |+|---------------|-----------------|------|-------|+| `characters` | `text` | `string` | |+| `fontName` | `fontFamily` + `fontWeight` + `italic` | `{ family, style }` | Computed: `style` = "Bold Italic" etc. |+| `strokeWeight` | `strokes[0].weight` | `number` | Computed |+| `strokeAlign` | `strokes[0].align` | `string` | Computed |+| `primaryAxisAlignItems` | `primaryAxisAlign` | `string` | |+| `counterAxisAlignItems` | `counterAxisAlign` | `string` | |+| `layoutSizingHorizontal` | `primaryAxisSizing` or `counterAxisSizing` | `string` | Depends on `layoutMode` |+| `layoutSizingVertical` | (opposite of horizontal) | `string` | |+| `absoluteTransform` | computed from `x`, `y`, `rotation` | `Transform` | Read-only |+| `absoluteBoundingBox` | `getAbsoluteBounds(id)` | `Rect` | Read-only |+| All others | Same name | Same type | Direct passthrough |++## Open Questions++1. **Font loading**: `figma.loadFontAsync()` — should it be a no-op (we don't have font gating) or should we track loaded fonts?+ → **Decision: No-op that returns resolved Promise.** We don't gate text editing on font loading.++2. **Export in headless mode**: `node.exportAsync()` requires CanvasKit. Should eval load CanvasKit?+ → **Decision: Optional.** If CanvasKit is available (via `--with-canvaskit` flag or env), enable export. Otherwise, throw "Export requires CanvasKit" error.++3. **`figma.mixed` symbol**: Should we use the actual Figma symbol or our own?+ → **Decision: Our own `Symbol('mixed')`.** Exposed as `figma.mixed`.++4. **Undo**: `figma.commitUndo()` / `figma.triggerUndo()` — relevant in headless?+ → **Decision: No-op in CLI.** Undo only matters in the live editor. The AI tools can add undo support separately via EditorStore.++5. **Write format**: Should `--write` produce `.fig` (Kiwi binary) or also support `.json`?+ → **Decision: `.fig` only for now.** JSON export is a separate feature.diff --git a/packages/docs/it/reference/file-format.md b/packages/docs/it/reference/file-format.mdnew file mode 100644index 000000000..1318032e3--- /dev/null+++ b/packages/docs/it/reference/file-format.md@@ -0,0 +1,71 @@+# Formato file++## .fig File Structure++```+┌─────────────────────────────────┐+│ Magic header: "fig-kiwi" (8B) │+│ Version (4B uint32 LE) │+│ Schema length (4B uint32 LE) │+│ Compressed Kiwi schema │+│ Message length (4B uint32 LE) │+│ Compressed Kiwi message │ ← NodeChange[] (entire document)+│ Blob data │ ← Images, vector networks, fonts+└─────────────────────────────────┘+```++## Import Pipeline++```+.fig file → Parse header → Decompress Zstd → Decode Kiwi schema+ → Decode Message → NodeChange[] → Build SceneGraph+ → Resolve blob refs → Render on canvas+```++## Export Pipeline++```+SceneGraph → NodeChange[] → Kiwi encode → Compress (Zstd/deflate)+ → Build ZIP (header + schema + message + thumbnail.png)+ → Write .fig file+```++Export uses <kbd>⌘</kbd><kbd>S</kbd> (Save) and <kbd>⇧</kbd><kbd>⌘</kbd><kbd>S</kbd> (Save As) with native OS dialogs on the desktop app. The exported file includes a `thumbnail.png` required by Figma for file preview. Compression uses Zstd via Tauri Rust command on desktop, with deflate fallback in the browser. The ZIP archive is assembled in Rust on desktop for correct Zstd frame headers (content size included).++## Kiwi Binary Codec++The codec handles Figma's 194-definition Kiwi schema with NodeChange as the central type (~390 fields). Key components:++- **kiwi-schema** — vendored from evanw/kiwi, patched for ESM and sparse field IDs+- **codec.ts** — encode/decode Messages using the Kiwi schema+- **protocol.ts** — wire format parsing and message type detection+- **schema.ts** — 194 message/enum/struct definitions++### Sparse Field IDs++Figma's schema uses non-contiguous field IDs (e.g., 1, 2, 5, 10 with gaps). The vendored kiwi-schema parser is patched to handle this correctly.++### Compression++.fig files use Zstd compression for both the schema and message payloads. Decompression uses the `fzstd` library. For export, Zstd compression is offloaded to a Tauri Rust command on the desktop app (better performance, correct frame headers). In the browser, deflate via `fflate` is used as a fallback. Clipboard encoding also uses `fflate`.++## Supported Formats++| Format | Import | Export |+|--------|--------|--------|+| .fig (Figma) | ✅ | ✅ |+| .svg | Planned | Planned |+| .png | Planned | Planned |+| .pdf | — | Planned |++See [Roadmap](/development/roadmap) for planned format support timeline.++## Clipboard Format++Copy/paste uses the same Kiwi binary encoding:++1. **Copy** — encode selected NodeChange[] to Kiwi binary, compress, write to clipboard as `application/x-figma-design` MIME type+2. **Paste** — read clipboard, decompress, decode Kiwi binary, create nodes in scene graph+3. **Synchronous** — encoding happens in the copy event handler (not async Clipboard API) to ensure browser compatibility++This enables bidirectional clipboard between OpenPencil and Figma.diff --git a/packages/docs/it/reference/keyboard-shortcuts.md b/packages/docs/it/reference/keyboard-shortcuts.mdnew file mode 100644index 000000000..72f03ef1a--- /dev/null+++ b/packages/docs/it/reference/keyboard-shortcuts.md@@ -0,0 +1,120 @@+# Scorciatoie da tastiera++Mappa completa delle scorciatoie compatibili con Figma.++::: tip Symbol Legend+⌘ = Cmd (Mac) / Ctrl (Win/Linux) · ⇧ = Shift · ⌥ = Alt/Option · ⌃ = Ctrl · ⌫ = Backspace+:::++## Tools++| Key | Tool | Status |+|-----|------|--------|+| <kbd>V</kbd> | Move/Select | ✅ |+| <kbd>K</kbd> | Scale | 🔲 |+| <kbd>H</kbd> | Hand | ✅ |+| <kbd>F</kbd> | Frame | ✅ |+| <kbd>S</kbd> | Section | ✅ |+| <kbd>R</kbd> | Rectangle | ✅ |+| <kbd>O</kbd> | Ellipse | ✅ |+| <kbd>L</kbd> | Line | ✅ |+| — | Polygon | ✅ (flyout only) |+| — | Star | ✅ (flyout only) |+| <kbd>⇧</kbd><kbd>L</kbd> | Arrow | 🔲 |+| <kbd>P</kbd> | Pen | ✅ |+| <kbd>⇧</kbd><kbd>P</kbd> | Pencil | 🔲 |+| <kbd>T</kbd> | Text | ✅ |+| <kbd>C</kbd> | Comment | 🔲 |+| <kbd>I</kbd> | Eyedropper | 🔲 |++## File++| Shortcut | Action | Status |+|----------|--------|--------|+| <kbd>⌘</kbd><kbd>N</kbd> | New Window | 🔲 |+| <kbd>⌘</kbd><kbd>O</kbd> | Open File | ✅ |+| <kbd>⌘</kbd><kbd>W</kbd> | Close Tab | 🔲 |+| <kbd>⌘</kbd><kbd>S</kbd> | Save | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>S</kbd> | Save As | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>E</kbd> | Export… | ✅ |++## Edit++| Shortcut | Action | Status |+|----------|--------|--------|+| <kbd>⌘</kbd><kbd>Z</kbd> | Undo | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>Z</kbd> | Redo | ✅ |+| <kbd>⌘</kbd><kbd>X</kbd> | Cut | ✅ |+| <kbd>⌘</kbd><kbd>C</kbd> | Copy | ✅ |+| <kbd>⌘</kbd><kbd>V</kbd> | Paste | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>V</kbd> | Paste Over Selection | 🔲 |+| <kbd>⌘</kbd><kbd>D</kbd> | Duplicate | ✅ |+| <kbd>⌫</kbd> | Delete | ✅ |+| <kbd>⌘</kbd><kbd>A</kbd> | Select All | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>A</kbd> | Select Inverse | 🔲 |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>C</kbd> | Copy Properties | 🔲 |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>V</kbd> | Paste Properties | 🔲 |++## View++| Shortcut | Action | Status |+|----------|--------|--------|+| <kbd>⌘</kbd><kbd>'</kbd> | Pixel Grid | 🔲 |+| <kbd>⌃</kbd><kbd>G</kbd> | Layout Guides | 🔲 |+| <kbd>⇧</kbd><kbd>R</kbd> | Rulers | 🔲 |+| <kbd>⌘</kbd><kbd>\\</kbd> | Show/Hide UI | 🔲 |+| <kbd>⌘</kbd><kbd>=</kbd> | Zoom In | ✅ |+| <kbd>⌘</kbd><kbd>-</kbd> | Zoom Out | ✅ |+| <kbd>⌘</kbd><kbd>0</kbd> | Zoom to 100% | ✅ |+| <kbd>⌘</kbd><kbd>1</kbd> | Zoom to Fit | 🔲 |+| <kbd>⌘</kbd><kbd>2</kbd> | Zoom to Selection | 🔲 |+| <kbd>⌘</kbd><kbd>J</kbd> | Toggle AI Chat | ✅ |++## Object++| Shortcut | Action | Status |+|----------|--------|--------|+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>G</kbd> | Frame Selection | 🔲 |+| <kbd>⌘</kbd><kbd>G</kbd> | Group Selection | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>G</kbd> | Ungroup | ✅ |+| <kbd>⇧</kbd><kbd>A</kbd> | Add Auto Layout | ✅ |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>K</kbd> | Create Component | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>K</kbd> | Create Component Set | ✅ |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>B</kbd> | Detach Instance | ✅ |+| <kbd>⌘</kbd><kbd>]</kbd> | Bring Forward | 🔲 |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>]</kbd> | Bring to Front | 🔲 |+| <kbd>]</kbd> | Bring to Front | ✅ |+| <kbd>⌘</kbd><kbd>[</kbd> | Send Backward | 🔲 |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>[</kbd> | Send to Back | 🔲 |+| <kbd>[</kbd> | Send to Back | ✅ |+| <kbd>⇧</kbd><kbd>H</kbd> | Flip Horizontal | 🔲 |+| <kbd>⇧</kbd><kbd>V</kbd> | Flip Vertical | 🔲 |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>H</kbd> | Toggle Visibility | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>L</kbd> | Toggle Lock | ✅ |+| <kbd>⌘</kbd><kbd>E</kbd> | Flatten | 🔲 |++## Text++| Shortcut | Action | Status |+|----------|--------|--------|+| <kbd>⌘</kbd><kbd>B</kbd> | Bold | ✅ |+| <kbd>⌘</kbd><kbd>I</kbd> | Italic | ✅ |+| <kbd>⌘</kbd><kbd>U</kbd> | Underline | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>X</kbd> | Strikethrough | 🔲 |++## Canvas Interaction++| Input | Action | Status |+|-------|--------|--------|+| Click | Select node | ✅ |+| <kbd>Shift</kbd>+Click | Add/remove from selection | ✅ |+| <kbd>Alt</kbd>+Drag | Duplicate and move | ✅ |+| <kbd>Shift</kbd>+Drag (draw) | Constrain to square/circle | ✅ |+| <kbd>Shift</kbd>+Drag (resize) | Maintain aspect ratio | ✅ |+| <kbd>Shift</kbd>+Drag (rotate) | Snap to 15° | ✅ |+| Middle mouse drag | Pan | ✅ |+| Scroll | Pan | ✅ |+| <kbd>Ctrl</kbd>+Scroll / Pinch | Zoom | ✅ |+| Double-click text | Edit text inline | ✅ |+| Drag onto frame | Reparent into frame | ✅ |+| <kbd>Escape</kbd> | Deselect / Cancel | ✅ |diff --git a/packages/docs/it/reference/mcp-tools.md b/packages/docs/it/reference/mcp-tools.mdnew file mode 100644index 000000000..56f059449--- /dev/null+++ b/packages/docs/it/reference/mcp-tools.md@@ -0,0 +1,140 @@+# Server MCP++OpenPencil includes an MCP (Model Context Protocol) server that lets AI coding tools — Claude Code, Cursor, Windsurf, etc. — read and modify `.fig` files headlessly.++Two transports: **stdio** for MCP clients, **HTTP** for everything else.++## Install++```sh+bun add -g @open-pencil/mcp+```++## Stdio (Claude Code, Cursor, etc.)++Add to your MCP config (e.g. `~/.claude/settings.json` or `.cursor/mcp.json`):++```json+{+ "mcpServers": {+ "open-pencil": {+ "command": "openpencil-mcp"+ }+ }+}+```++Or run from source without installing:++::: code-group+```json [Bun]+{+ "mcpServers": {+ "open-pencil": {+ "command": "bun",+ "args": ["/path/to/open-pencil/packages/mcp/src/index.ts"]+ }+ }+}+```+```json [Node.js]+{+ "mcpServers": {+ "open-pencil": {+ "command": "npx",+ "args": ["tsx", "/path/to/open-pencil/packages/mcp/src/index.ts"]+ }+ }+}+```+:::++## HTTP++For browser extensions, scripts, CI, or any HTTP client:++```sh+openpencil-mcp-http+```++Or from source: `bun packages/mcp/src/http.ts` / `npx tsx packages/mcp/src/http.ts`++Starts on port 3100 (override with `PORT` env var). Endpoints:++- `GET /health` — server status+- `POST /mcp` — MCP Streamable HTTP (SSE). Sessions via `mcp-session-id` header.++## Workflow++1. **Open** — `open_file` to load an existing `.fig`, or `new_document` for a blank canvas+2. **Read** — `get_page_tree`, `find_nodes`, `get_node`, `list_pages`+3. **Create** — `create_shape`, `render` (JSX)+4. **Modify** — `set_fill`, `set_stroke`, `set_layout`, `update_node`, `set_effects`+5. **Structure** — `reparent_node`, `group_nodes`, `clone_node`, `delete_node`+6. **Save** — `save_file` to write back to `.fig`++## Tools (29)++### Document++| Tool | Description |+|------|-------------|+| `open_file` | Open a `.fig` file for editing |+| `save_file` | Save the current document to a `.fig` file |+| `new_document` | Create a new empty document |++### Read++| Tool | Description |+|------|-------------|+| `get_selection` | Get currently selected nodes |+| `get_page_tree` | Get the full node tree of the current page |+| `get_node` | Get detailed properties of a node by ID |+| `find_nodes` | Find nodes by name pattern and/or type |+| `list_pages` | List all pages |+| `list_variables` | List design variables |+| `list_collections` | List variable collections |++### Create++| Tool | Description |+|------|-------------|+| `create_shape` | Create a shape (FRAME, RECTANGLE, ELLIPSE, TEXT, LINE, STAR, POLYGON, SECTION) |+| `render` | Render JSX to design nodes — create entire component trees in one call |+| `create_component` | Convert a frame/group into a component |+| `create_instance` | Create an instance of a component |++### Modify++| Tool | Description |+|------|-------------|+| `set_fill` | Set fill color (hex) |+| `set_stroke` | Set stroke color, weight, alignment |+| `set_effects` | Add shadow or blur effects |+| `update_node` | Update position, size, opacity, corner radius, text, font |+| `set_layout` | Set auto-layout (flexbox) — direction, spacing, padding, alignment |+| `set_constraints` | Set resize constraints |++### Structure++| Tool | Description |+|------|-------------|+| `delete_node` | Delete a node |+| `clone_node` | Duplicate a node |+| `rename_node` | Rename a node |+| `reparent_node` | Move a node into a different parent |+| `select_nodes` | Select nodes by ID |+| `group_nodes` | Group nodes |+| `ungroup_node` | Ungroup a group |++### Navigation++| Tool | Description |+|------|-------------|+| `switch_page` | Switch to a page by name or ID |++### Escape Hatch++| Tool | Description |+|------|-------------|+| `eval` | Execute JavaScript with full Figma Plugin API access |diff --git a/packages/docs/it/reference/node-types.md b/packages/docs/it/reference/node-types.mdnew file mode 100644index 000000000..d1247a45a--- /dev/null+++ b/packages/docs/it/reference/node-types.md@@ -0,0 +1,194 @@+# Tipi di nodo++The scene graph supports 28 node types from Figma's Kiwi schema. Each node is identified by a GUID (`sessionID:localID`) and has a parent reference via `parentIndex`. The OpenPencil engine's `NodeType` union currently uses 17 of these types.++## Type Table++28 Figma schema types + 1 synthetic engine type. Types marked ✅ are in the engine's `NodeType` union (17 total).++| Type | ID | Description | Engine |+|------|----|-------------|--------|+| DOCUMENT | 1 | Root node, one per file | — |+| CANVAS | 2 | Page | ✅ |+| GROUP | 3 | Group container | ✅ |+| FRAME | 4 | Primary container (artboard), supports auto-layout | ✅ |+| BOOLEAN_OPERATION | 5 | Union/subtract/intersect/exclude result | |+| VECTOR | 6 | Freeform vector path | ✅ |+| STAR | 7 | Star shape | ✅ |+| LINE | 8 | Line | ✅ |+| ELLIPSE | 9 | Ellipse/circle, supports arc data | ✅ |+| RECTANGLE | 10 | Rectangle | ✅ |+| REGULAR_POLYGON | 11 | Regular polygon (3–12 sides, engine uses `POLYGON`) | ✅ |+| ROUNDED_RECTANGLE | 12 | Rectangle with smooth corners | ✅ |+| TEXT | 13 | Text with rich formatting | ✅ |+| SLICE | 14 | Export region | |+| SYMBOL | 15 | Component (main, engine uses `COMPONENT`) | ✅ |+| INSTANCE | 16 | Component instance | ✅ |+| STICKY | 17 | FigJam sticky note | |+| SHAPE_WITH_TEXT | 18 | FigJam shape | ✅ |+| CONNECTOR | 19 | Connector line between nodes | ✅ |+| CODE_BLOCK | 20 | FigJam code block | |+| WIDGET | 21 | Plugin widget | |+| STAMP | 22 | FigJam stamp | |+| MEDIA | 23 | Video/GIF | |+| HIGHLIGHT | 24 | FigJam highlight | |+| SECTION | 25 | Canvas section (organizational, top-level only) | ✅ |+| SECTION_OVERLAY | 26 | Section overlay | |+| WASHI_TAPE | 27 | FigJam washi tape | |+| VARIABLE | 28 | Variable definition node | |+| COMPONENT_SET | — | Variant group container (synthetic, mapped from SYMBOL) | ✅ |++### Engine NodeType Union (17 types)++The engine's `NodeType` uses simplified names. Some differ from the Kiwi schema:+- `COMPONENT` → Kiwi `SYMBOL` (ID 15)+- `COMPONENT_SET` → variant group container (no dedicated Kiwi ID, mapped from SYMBOL with variants)+- `POLYGON` → Kiwi `REGULAR_POLYGON` (ID 11)++```typescript+type NodeType =+ | 'CANVAS' | 'FRAME' | 'RECTANGLE' | 'ROUNDED_RECTANGLE'+ | 'ELLIPSE' | 'TEXT' | 'LINE' | 'STAR' | 'POLYGON'+ | 'VECTOR' | 'GROUP' | 'SECTION'+ | 'COMPONENT' | 'COMPONENT_SET' | 'INSTANCE'+ | 'CONNECTOR' | 'SHAPE_WITH_TEXT'+```++## Node Hierarchy++```+Document+├── Canvas (Page 1)+│ ├── Section (top-level only, title pill, auto-adopts siblings)+│ │ ├── Frame+│ │ │ └── ...children+│ │ └── Rectangle+│ ├── Frame+│ │ ├── Rectangle+│ │ ├── Text+│ │ └── Frame (nested)+│ │ ├── Ellipse+│ │ └── Instance (→ references Component)+│ ├── Component+│ │ └── ...children+│ ├── Group+│ │ └── ...children+│ └── BooleanOperation+│ └── ...operand shapes+└── Canvas (Page 2)+ └── ...+```++## Core Properties++Every node carries these fields (subset of NodeChange):++### Identity & Tree++- `guid` — unique identifier (`sessionID:localID`)+- `type` — node type enum+- `name` — display name+- `phase` — CREATED or REMOVED+- `parentIndex` — parent GUID + position string for z-ordering++### Transform++- `size` — width/height vector+- `transform` — 2×3 affine matrix+- `rotation` — degrees++### Appearance++- `fillPaints[]` — fill colors/gradients/images+- `strokePaints[]` — stroke colors+- `effects[]` — shadows, blurs+- `opacity` — 0–1+- `blendMode` — NORMAL, MULTIPLY, SCREEN, etc.++### Stroke++- `strokeWeight` — stroke thickness+- `strokeAlign` — inside / center / outside+- `strokeCap` — butt / round / square+- `strokeJoin` — miter / bevel / round+- `dashPattern[]` — dash/gap lengths++### Corners++- `cornerRadius` — uniform radius+- `cornerSmoothing` — squircle amount (0–1)+- Per-corner radii when `rectangleCornerRadiiIndependent` is true++### Visibility++- `visible` — show/hide+- `locked` — prevent editing++## Type-Specific Properties++### Text++`fontSize`, `fontName`, `lineHeight`, `letterSpacing`, `textAlignHorizontal`, `textAlignVertical`, `textAutoResize`, `textData` (characters, style overrides, baselines, glyphs)++### Vector++`vectorData` (vectorNetworkBlob, normalizedSize), `fillGeometry[]`, `strokeGeometry[]`, `handleMirroring`, `arcData`++### Layout (Frame)++`stackMode`, `stackSpacing`, `stackPadding`, `stackJustify`, `stackCounterAlign`, `stackPrimarySizing`, `stackCounterSizing`, `stackChildPrimaryGrow`, `stackChildAlignSelf`++### Component++`symbolData`, `componentKey`, `componentPropDefs[]`, `symbolDescription`++### Instance++`overriddenSymbolID`, `symbolData.symbolOverrides[]`, `componentPropRefs[]`, `componentPropAssignments[]`++## Paint++```typescript+interface Fill {+ type: 'SOLID' | 'GRADIENT_LINEAR' | 'GRADIENT_RADIAL' |+ 'GRADIENT_ANGULAR' | 'GRADIENT_DIAMOND' | 'IMAGE'+ color: Color // {r, g, b, a} 0–1 floats+ opacity: number // 0–1+ visible: boolean+ blendMode?: BlendMode+ gradientStops?: GradientStop[] // for gradients+ gradientTransform?: GradientTransform // 2×3 matrix+ imageHash?: string // for image fills+ imageScaleMode?: 'FILL' | 'FIT' | 'CROP' | 'TILE'+ imageTransform?: GradientTransform+}+```++## Effect++```typescript+interface Effect {+ type: 'DROP_SHADOW' | 'INNER_SHADOW' | 'LAYER_BLUR' |+ 'BACKGROUND_BLUR' | 'FOREGROUND_BLUR'+ color: Color+ offset: { x: number; y: number }+ radius: number+ spread: number+ visible: boolean+}+```++## Stroke++```typescript+interface Stroke {+ color: Color+ weight: number+ opacity: number+ visible: boolean+ align: 'INSIDE' | 'CENTER' | 'OUTSIDE'+ cap?: 'NONE' | 'ROUND' | 'SQUARE' | 'ARROW_LINES' | 'ARROW_EQUILATERAL'+ join?: 'MITER' | 'BEVEL' | 'ROUND'+ dashPattern?: number[]+}+```diff --git a/packages/docs/it/reference/scene-graph.md b/packages/docs/it/reference/scene-graph.mdnew file mode 100644index 000000000..ea9778529--- /dev/null+++ b/packages/docs/it/reference/scene-graph.md@@ -0,0 +1,99 @@+# Grafo della scena++## In-Memory Representation++Nodes live in a flat `Map<string, Node>` keyed by GUID string. The tree structure is maintained via `parentIndex` references. This gives O(1) lookup by ID and efficient traversal.++```typescript+interface SceneGraph {+ nodes: Map<string, Node>+ root: string++ getNode(id: string): Node+ getChildren(id: string): Node[]+ getParent(id: string): Node | null+ getPages(): Node[]++ createNode(type: NodeType, parent: string, props: Partial<NodeChange>): Node+ updateNode(id: string, changes: Partial<NodeChange>): void+ deleteNode(id: string): void+ moveNode(id: string, newParent: string, position: string): void+ addPage(name: string): Node+ deletePage(id: string): void+ renamePage(id: string, name: string): void++ findByType(type: NodeType): Node[]+ findByName(pattern: string): Node[]+ hitTest(point: Vector, canvas: string): Node | null+ getNodesInRect(rect: Rect, canvas: string): Node[]+}+```++## Pages++Documents support multiple pages (CANVAS nodes as direct children of the DOCUMENT root). Each page has its own child tree and independent viewport state (panX, panY, zoom, pageColor). The editor tracks `currentPageId` and renders only the active page's children.++## Sections++SECTION nodes are top-level organizational containers (direct children of CANVAS only). They cannot nest inside frames or groups. Creating a section auto-adopts overlapping siblings. Sections display a title pill with luminance-adaptive text color.++## Hover State++The editor state tracks `hoveredNodeId` — the node currently under the cursor. The renderer draws a shape-aware hover outline (following actual geometry for ellipses, rounded rects, vectors) for visual feedback before selection.++## Undo/Redo++The system uses Figma's **inverse command** pattern. Each undo entry contains the forward changes and their automatically-computed inverse:++| Operation | Forward | Inverse |+|-----------|---------|---------|+| Create node | `{guid, phase: CREATED, ...props}` | `{guid, phase: REMOVED}` |+| Delete node | `{guid, phase: REMOVED}` | `{guid, phase: CREATED, ...allProps}` |+| Change prop | `{guid, fill: "#F00"}` | `{guid, fill: "#00F"}` |+| Move node | `{guid, parentIndex: newParent}` | `{guid, parentIndex: oldParent}` |++Before applying any change, affected fields are snapshotted. The snapshot becomes the inverse.++**Batching** — operations like drag-to-move produce hundreds of position changes per second. These are debounced into a single undo entry. `beginBatch`/`commitBatch` wraps multi-step operations.++## Layout Engine (Yoga)++Figma's auto-layout properties map to Yoga flexbox:++| Figma Property | Yoga Equivalent |+|---|---|+| `stackMode: HORIZONTAL` | `flexDirection: row` |+| `stackMode: VERTICAL` | `flexDirection: column` |+| `stackSpacing` | `gap` |+| `stackPadding` | `padding` |+| `stackJustify: MIN/CENTER/MAX/SPACE_BETWEEN` | `justifyContent` |+| `stackCounterAlign` | `alignItems` |+| `stackPrimarySizing: FIXED/HUG/FILL` | width/height + flex-grow |+| `stackChildPrimaryGrow` | `flexGrow` |+| `stackChildAlignSelf` | `alignSelf` |+| `stackPositioning: ABSOLUTE` | `position: absolute` |++## Hit Testing++Given a point in canvas coordinates, the scene graph returns the topmost visible node at that position. The algorithm:++1. Traverse visible nodes in reverse z-order (top to bottom)+2. Transform the test point into each node's local coordinate system+3. Check if the point is within the node's bounds (including rotation)+4. Return the first match++For marquee selection, `getNodesInRect` returns all nodes whose bounds intersect the given rectangle.++## Extended Fill Types++Fills support six types: SOLID, GRADIENT_LINEAR, GRADIENT_RADIAL, GRADIENT_ANGULAR, GRADIENT_DIAMOND, and IMAGE. Gradient fills carry `gradientStops` (color + position pairs) and a `gradientTransform` (2×3 matrix). Image fills reference blob data via `imageHash` with scale modes (FILL, FIT, CROP, TILE).++## Extended Stroke Properties++Strokes support `cap` (NONE, ROUND, SQUARE, ARROW_LINES, ARROW_EQUILATERAL), `join` (MITER, BEVEL, ROUND), and `dashPattern` (array of dash/gap lengths) in addition to the base color, weight, opacity, visible, and align properties.++## Coordinate System++Nodes store position and size relative to their parent. To get absolute (canvas) coordinates, walk up the parent chain applying transforms. The renderer uses this to draw nested frames with correct positioning.++Rotation is stored in degrees and applied as part of the 2×3 transform matrix. Snap guides and hit testing account for rotation when computing visual bounds.diff --git a/packages/docs/pl/development/contributing.md b/packages/docs/pl/development/contributing.mdnew file mode 100644index 000000000..973ee6628--- /dev/null+++ b/packages/docs/pl/development/contributing.md@@ -0,0 +1,94 @@+# Współpraca++## Project Structure++```+packages/+ core/ @open-pencil/core — engine (zero DOM deps)+ src/ Scene graph, renderer, layout, codec, kiwi, types+ cli/ @open-pencil/cli — headless CLI for .fig operations+ src/commands/ info, tree, find, export+src/+ components/ Vue SFCs (canvas, panels, toolbar, color picker)+ properties/ Property panel sections (Appearance, Fill, Stroke, etc.)+ composables/ Canvas input, keyboard shortcuts, rendering hooks+ stores/ Editor state (Vue reactivity)+ engine/ Re-export shims from @open-pencil/core+ kiwi/ Re-export shims from @open-pencil/core+ types.ts Shared types (re-exported from core)+ constants.ts UI colors, defaults, thresholds+desktop/ Tauri v2 (Rust + config)+tests/+ e2e/ Playwright visual regression+ engine/ Unit tests (bun:test)+docs/ VitePress documentation site+openspec/+ specs/ Capability specifications (source of truth)+ changes/ Active and archived changes+```++## Development Setup++```sh+bun install+bun run dev # Editor at localhost:1420+bun run docs:dev # Docs at localhost:5173+```++## Code Style++### Tooling++| Tool | Command | Purpose |+|------|---------|---------|+| oxlint | `bun run lint` | Linting (Rust-based, fast) |+| oxfmt | `bun run format` | Code formatting |+| tsgo | `bun run typecheck` | Type checking (Go-based TypeScript checker) |++Run all checks:++```sh+bun run check+```++### Conventions++- **File names** — kebab-case (`scene-graph.ts`, `use-canvas-input.ts`)+- **Components** — PascalCase Vue SFCs (`EditorCanvas.vue`, `ScrubInput.vue`)+- **Constants** — SCREAMING_SNAKE_CASE+- **Functions/variables** — camelCase+- **Types/interfaces** — PascalCase++### AI Agent Conventions++Developers and AI agents working on the codebase should read `AGENTS.md` in the repo root ([view on GitHub](https://github.com/open-pencil/open-pencil/blob/master/AGENTS.md)). Covers rendering, scene graph, components & instances, layout, UI, file format, Tauri conventions, and known issues.++## Making Changes++1. Check existing [openspec specs](/development/openspec) for the capability you're modifying+2. Create an openspec change if adding new behavior: `openspec new change "my-change"`+3. Implement the change+4. Run `bun run check` and `bun run test`+5. Submit a pull request++## 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.++| 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/layout.ts` | Yoga layout adapter |+| `packages/core/src/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/kiwi/fig-import.ts` | .fig file import logic |+| `packages/cli/src/index.ts` | CLI entry point |+| `packages/cli/src/commands/` | CLI commands (info, tree, find, export) |+| `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 |diff --git a/packages/docs/pl/development/openspec.md b/packages/docs/pl/development/openspec.mdnew file mode 100644index 000000000..4907fe432--- /dev/null+++ b/packages/docs/pl/development/openspec.md@@ -0,0 +1,107 @@+# Workflow OpenSpec++OpenPencil uses [OpenSpec](https://github.com/Fission-AI/OpenSpec) for spec-driven development. Specifications are the source of truth for what the system does.++## Structure++```+openspec/+├── specs/ # Source of truth: how the system works now+│ ├── scene-graph/+│ │ └── spec.md+│ ├── canvas-rendering/+│ │ └── spec.md+│ ├── auto-layout/+│ │ └── spec.md+│ └── ... # 19 capability specs total+├── changes/ # Proposed changes (one directory per change)+│ └── archive/ # Completed changes+└── config.yaml # Optional configuration+```++## Current Specs++| Capability | Description |+|-----------|-------------|+| scene-graph | Flat Map storage, CRUD, hit testing |+| canvas-rendering | CanvasKit WASM rendering pipeline |+| canvas-navigation | Pan, zoom, hand tool |+| selection-manipulation | Click/marquee select, move, resize, rotate |+| undo-redo | Inverse-command pattern |+| text-editing | Text tool, Paragraph API, font loading |+| pen-tool | Vector network model, bezier curves |+| auto-layout | Yoga WASM flexbox, Shift+A toggle |+| figma-clipboard | Bidirectional Kiwi binary clipboard |+| fig-import | .fig file import pipeline |+| kiwi-codec | Kiwi binary codec, sparse field IDs |+| editor-ui | Vue 3 panels, toolbar, color picker |+| snap-guides | Edge/center snapping, rotation-aware |+| rulers | Canvas rulers, selection highlight |+| group-ungroup | ⌘G/⇧⌘G, position-based sort |+| desktop-app | Tauri v2, macOS menu bar |+| testing | Playwright E2E, bun:test unit |+| scrub-input | Drag-to-scrub numeric inputs |+| tooling | Vite 7, oxlint, oxfmt, tsgo, VitePress |++## Workflow++### 1. Propose a Change++```+/opsx:propose add-dark-mode+```++Creates `openspec/changes/add-dark-mode/` with:+- `proposal.md` — why and what changes+- `design.md` — technical approach+- `specs/` — delta specifications (ADDED/MODIFIED/REMOVED requirements)+- `tasks.md` — implementation checklist++### 2. Implement++```+/opsx:apply+```++Execute tasks from tasks.md, checking off items as they're completed.++### 3. Archive++```+/opsx:archive+```++- Merges delta specs into `openspec/specs/` (the baseline)+- Moves the change to `openspec/changes/archive/`++## Spec Format++Each spec file follows a consistent structure:++```markdown+# capability-name Specification++## Purpose+One-line description of what this capability does.++## Requirements++### Requirement: Name+Description using SHALL/MUST for normative requirements.++#### Scenario: Name+- **WHEN** condition+- **THEN** expected outcome+```++Every requirement has at least one scenario. Scenarios are potential test cases.++## CLI Commands++```sh+openspec list # List active changes+openspec show <name> # Show change details+openspec status --change <name> # Artifact status+openspec archive <name> # Archive completed change+openspec update # Regenerate skills/prompts+```diff --git a/packages/docs/pl/development/roadmap.md b/packages/docs/pl/development/roadmap.mdnew file mode 100644index 000000000..59a244531--- /dev/null+++ b/packages/docs/pl/development/roadmap.md@@ -0,0 +1,145 @@+# Plan rozwoju++## Phases++### Phase 1: Core Engine ✅++SceneGraph, Skia rendering, basic shapes, selection, zoom/pan, undo/redo.++**Delivered:**+- Scene graph with flat Map storage and parent-child tree+- CanvasKit WASM rendering for all shape types+- Click/shift/marquee selection with resize handles and rotation+- Zoom/pan with keyboard shortcuts and trackpad gestures+- Undo/redo wired into all operations+- Snap guides with edge and center snapping++### Phase 2: Editor UI + Layout ✅++Properties panel, layers panel, toolbar, Yoga layout integration, text editing.++**Delivered:**+- Vue 3 + Reka UI panels (properties, layers, toolbar)+- Properties panel split into sections (Appearance, Fill, Stroke, Typography, Layout, Position)+- ScrubInput component for all numeric inputs+- Color picker (HSV, hex, opacity)+- Layers panel with tree view, drag reorder, visibility toggle+- Auto-layout with Yoga WASM (direction, gap, padding, justify, align)+- Inline text editing with CanvasKit Paragraph API+- System font loading via Local Font Access API+- Canvas rulers with selection highlight++### Phase 3: File I/O + Visual Features ✅++.fig import/export, Kiwi codec, clipboard, sections, pages, advanced rendering.++**Delivered:**+- .fig file import via Kiwi binary codec+- .fig file export with Kiwi encoding, Zstd compression, thumbnail generation+- Save (⌘S) and Save As (⇧⌘S) with native OS dialogs+- Zstd compression via Tauri Rust command (deflate fallback in browser)+- Vendored kiwi-schema with ESM + sparse field ID patches+- Figma-compatible clipboard (bidirectional Kiwi binary)+- Pen tool with vector network model+- vectorNetworkBlob binary encode/decode+- Group/ungroup (⌘G/⇧⌘G)+- Tauri v2 desktop app with native menu bar (macOS/Windows/Linux)+- Sections (S key) with title pills, auto-adopt, luminance-adaptive text+- Multi-page documents with pages panel, per-page viewport+- Hover highlight with shape-aware outlines+- Tier 1 rendering: gradients, image fills, effects, strokes (cap/join/dash), arcs+- Fill type picker with solid/gradient/image tabs and gradient stop editing+- Canvas background color per page+- Fig-import unit tests, layout unit tests, layers-panel E2E tests++### Phase 4: Components + Variables ✅++Components, instances, overrides, variables, collections, modes, image export.++**Delivered:**+- Component creation from frame/group or multi-selection (⌥⌘K)+- Component sets from multiple components (⇧⌘K) with dashed purple border+- Instance creation from components with child cloning and componentId mapping+- Live component-instance sync with override preservation+- Detach instance back to frame (⌥⌘B)+- Go to main component (cross-page navigation)+- Always-visible purple component/instance labels with diamond icon+- Opaque container hit testing (click selects component, double-click enters)+- Right-click context menu with clipboard, z-order, grouping, component, visibility, lock, move-to-page actions+- Z-order manipulation (] bring to front, [ send to back)+- Toggle visibility (⇧⌘H) and lock (⇧⌘L)+- Move nodes between pages via context menu+- Viewport culling, Paint reuse, RAF render coalescing+- Effects panel UI (drop shadow, inner shadow, layer/background/foreground blur)+- Independent corner radius controls (per-corner toggle in Appearance section)+- GitHub Actions CI/CD for Windows (x64, arm64) and macOS (x64, arm64) builds+- Polygon and Star drawing tools with pointCount and starInnerRadius+- Resizable left/right panels via reka-ui Splitter (persistent layout)+- @/ import alias, shared types module (src/types.ts, src/global.d.ts)+- Codebase lint-clean: 0 oxlint warnings, 0 tsgo type errors+- Variables: COLOR type with collections, modes, bindings, FillSection variable picker, .fig import+- Variables dialog: TanStack Table with resizable columns, mode columns, collection tabs with rename, search, demo collections (Primitives/Semantic/Spacing), undo/redo for all variable operations+- Image export: PNG/JPG/WEBP with ExportSection (scale, format, live preview), ⇧⌘E shortcut, context menu+- Canvas-native text editing: TextEditor class in core, phantom textarea, cursor/selection/word boundaries on canvas, caret blinking, selection highlights+- System font enumeration via font-kit Rust crate, OnceLock cache, preload on startup+- Font picker: virtual scroll (reka-ui ListboxVirtualizer), search filter, CSS font preview+- ColorInput component extraction, ColorPicker alpha slider checkerboard fix+- App identity: pencil icon, Cargo crate open_pencil, macOS Dock "OpenPencil"+- Splash loader during WASM initialization+- Rich text style runs: per-selection ⌘B/I/U, StyleRun model, ParagraphBuilder pushStyle/pop, .fig roundtrip+- B/I/U/S toggle buttons in TypographySection+- Double-click (word), triple-click (select all) text selection++**Remaining (deferred to Phase 6):**+- Variant switching+- Variable types: FLOAT, STRING, BOOLEAN editing UI+- Variable-driven theming++### Phase 5: AI Integration & Tooling 🟡++Core extraction, CLI, MCP server, design guidelines, screenshot verification loop.++**Delivered:**+- @open-pencil/core extracted to packages/core/ (zero DOM deps, Bun workspace)+- @open-pencil/cli with headless .fig operations (info, tree, find, export, analyze, node, pages, variables), CanvasKit CPU rasterization, --json output+- JSX renderer: TreeNode builders (Frame, Text, Rectangle, etc.), renderTreeNode/renderJsx, Tailwind-like shorthand props, 27 tests+- jscpd copy-paste detection (15.6% → 0.62%), kiwi-serialize.ts consolidation+- .fig roundtrip tests with LFS fixtures (material3.fig 87K nodes, nuxtui.fig 314K nodes)+- .fig import O(n²) → O(n) fix (37s → 535ms on 87K nodes), ByteBuffer optimization+- test:coverage script+- AI chat: OpenRouter direct (no backend), Stronghold key storage, 26 tools (create_shape, set_fill, set_effects, set_constraints, components, groups, pages, variables, eval_code, etc.), model selector, ⌘J toggle, streaming markdown, Playwright tests with mock transport+- Code panel: sceneNodeToJsx() export, Prism.js highlighting, line numbers, copy button, 14 tests+- Properties panel restructured: Design | Code | AI tabs+- npm publishing preparation for core and cli packages++**Planned:**+- Port remaining figma-use tools (118 total, 26 currently implemented)+- Attached mode: WebSocket to running editor for eval, create, export, screenshot+- Design guidelines system+- AI-driven design workflow via MCP+- Screenshot verification loop++### Phase 6: Polish + Distribution 🔲++Prototyping, comments, desktop distribution, documentation, public launch.++**Planned:**+- Prototyping (frame connections, transitions)+- Comments (pin, threads, resolve)+- Linux Tauri builds (macOS and Windows already covered by CI)+- PWA support+- Documentation site (VitePress)+- Performance optimization (Lighthouse > 90)+- Full Figma compatibility test suite+- Deferred from Phase 4: variant switching, FLOAT/STRING/BOOLEAN variable UI, variable-driven theming++## Timeline++| Phase | Estimated Duration | Status |+|-------|-------------------|--------|+| Phase 1: Core Engine | 3 months | ✅ Complete |+| Phase 2: Editor UI + Layout | 3 months | ✅ Complete |+| Phase 3: File I/O + Visual Features | 2 months | ✅ Complete |+| Phase 4: Components + Variables | 2 months | ✅ Complete |+| Phase 5: AI Integration & Tooling | 2 months | 🟡 In Progress |+| Phase 6: Polish + Distribution | 2 months | 🔲 Planned |diff --git a/packages/docs/pl/development/testing.md b/packages/docs/pl/development/testing.mdnew file mode 100644index 000000000..342a5c2a1--- /dev/null+++ b/packages/docs/pl/development/testing.md@@ -0,0 +1,91 @@+# Testowanie++## Overview++| Type | Framework | Command | Location |+|------|-----------|---------|----------|+| E2E visual regression | Playwright | `bun run test` | `tests/e2e/` |+| Figma CDP reference | Playwright | `bun run test:figma` | `tests/figma/` |+| Unit tests | bun:test | `bun run test:unit` | `tests/engine/` |++## E2E Visual Regression++Playwright creates shapes on the canvas and compares screenshots against baseline PNGs.++```sh+bun run test # Run tests, compare against baselines+bun run test:update # Regenerate baseline screenshots+```++### How It Works++1. Tests load the editor in a headless browser+2. The editor signals readiness via a `data-ready` HTML attribute+3. Tests create shapes via the editor's API+4. Screenshots are taken and compared against baselines using `toMatchSnapshot`+5. Page is reused across test cases for speed (~2s total)++### No-Chrome Test Mode++The editor supports a test mode that hides UI chrome (toolbar, panels) for clean screenshot capture. Activated via URL parameter.++## Figma CDP Reference Tests++A separate Playwright project connects to Figma via Chrome DevTools Protocol to capture reference screenshots for pixel-perfect comparison.++```sh+bun run figma:debug # Launch Figma with debugging port+bun run test:figma # Connect to Figma, capture references+```++Requires Figma desktop app running with `--remote-debugging-port=9222`.++## Unit Tests++Engine unit tests use bun:test and target < 50ms execution:++```sh+bun run test:unit+```++Tests cover:+- Scene graph CRUD operations, parent-child relationships, z-ordering, hit testing+- **Fig-import pipeline** — node type mapping, transforms, fills/strokes/effects, gradients, images, arcs, nested hierarchies (`tests/engine/fig-import.test.ts`)+- **Layout computation** — Yoga auto-layout: direction, gap, padding, justify, align, child sizing (fixed/fill/hug), cross-axis sizing, wrap, nested layouts (`tests/engine/layout.test.ts`)++### Writing Unit Tests++```typescript+import { describe, expect, it } from 'bun:test'+import { SceneGraph } from '../../src/engine/scene-graph'++describe('SceneGraph', () => {+ it('creates and retrieves a node', () => {+ const sg = new SceneGraph()+ const node = sg.createNode('RECTANGLE', sg.root, { name: 'Test' })+ expect(sg.getNode(node.guid)).toBeDefined()+ })+})+```++## E2E Test Coverage++| Test file | Scope |+|-----------|-------|+| `tests/e2e/layers-panel.spec.ts` | Layers panel tree structure, visibility toggles, selection sync |+| `tests/e2e/visual.spec.ts` | Visual regression screenshots for shapes and rendering |++## Test Helpers++| File | Purpose |+|------|---------|+| `tests/helpers/canvas.ts` | Canvas setup and interaction utilities |+| `tests/helpers/figma.ts` | Figma CDP connection helpers |++## Performance Targets++| Metric | Target |+|--------|--------|+| E2E suite total | < 3s |+| Unit test suite total | < 50ms |+| Screenshot comparison | toMatchSnapshot (pixel-level) |diff --git a/packages/docs/pl/eval-command.md b/packages/docs/pl/eval-command.mdnew file mode 100644index 000000000..9f7c45018--- /dev/null+++ b/packages/docs/pl/eval-command.md@@ -0,0 +1,437 @@+# `open-pencil eval` — Figma-like Plugin API for Headless Scripting++## Overview++`bun open-pencil eval <file> --code '<js>'` executes JavaScript against a `.fig` file with a Figma-compatible `figma` global object. This enables headless scripting, batch operations, AI tool execution, and testing — all without the GUI.++The `figma` object mirrors Figma's Plugin API surface as closely as possible, so existing Figma plugin knowledge and code snippets transfer directly.++```bash+# Create a frame, set auto-layout, add children+bun open-pencil eval design.fig --code '+ const frame = figma.createFrame()+ frame.name = "Card"+ frame.resize(300, 200)+ frame.layoutMode = "VERTICAL"+ frame.itemSpacing = 12+ frame.paddingTop = frame.paddingBottom = 16+ frame.paddingLeft = frame.paddingRight = 16+ frame.fills = [{ type: "SOLID", color: { r: 1, g: 1, b: 1 } }]++ const title = figma.createText()+ title.characters = "Hello World"+ title.fontSize = 24+ frame.appendChild(title)++ return { id: frame.id, name: frame.name }+'++# Query nodes+bun open-pencil eval design.fig --code '+ const buttons = figma.currentPage.findAll(n => n.type === "FRAME" && n.name.includes("Button"))+ return buttons.map(b => ({ id: b.id, name: b.name, w: b.width, h: b.height }))+'++# Read from stdin (for multiline scripts / piping)+cat transform.js | bun open-pencil eval design.fig --stdin++# Write changes back+bun open-pencil eval design.fig --code '...' --write+bun open-pencil eval design.fig --code '...' -o modified.fig+```++## Architecture++```+┌──────────────────────────────────────────────────────┐+│ CLI: `open-pencil eval <file> --code '...'` │+│ ↓ │+│ loadDocument(file) → SceneGraph │+│ ↓ │+│ FigmaAPI(sceneGraph) → `figma` proxy object │+│ ↓ │+│ AsyncFunction('figma', wrappedCode)(figmaProxy) │+│ ↓ │+│ print result as JSON / agentfmt │+│ optionally: saveDocument(file) if --write │+└──────────────────────────────────────────────────────┘+```++### Key classes++| 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.) |+| `eval` command | `packages/cli/src/commands/eval.ts` | CLI command that loads doc, creates API, executes code |++### Why in `@open-pencil/core`?++The `FigmaAPI` class lives in core (not CLI) because:+- **AI tools reuse it** — the chat panel's `render` tool can execute JSX through the same API+- **Test scripts** — unit tests can use the API to set up fixtures+- **No DOM deps** — runs headless in Bun, no browser APIs needed++## `FigmaAPI` — Phased Implementation++### Phase 1: Core (MVP for eval command)++These cover ~80% of real plugin scripts:++#### Document & Page++| Figma API | Our implementation | Notes |+|-----------|--------------------|-------|+| `figma.root` | Getter → proxy for root node | `.children` returns page proxies |+| `figma.currentPage` | Getter/setter → first page by default | Settable to any page proxy |+| `figma.currentPage.selection` | Get/set → tracked selection array | |+| `figma.getNodeById(id)` | `graph.getNode(id)` wrapped in proxy | Sync, like Figma's deprecated version |++#### Node Creation++| Figma API | Maps to |+|-----------|---------|+| `figma.createFrame()` | `graph.createNode('FRAME', currentPageId)` |+| `figma.createRectangle()` | `graph.createNode('RECTANGLE', ...)` |+| `figma.createEllipse()` | `graph.createNode('ELLIPSE', ...)` |+| `figma.createText()` | `graph.createNode('TEXT', ...)` |+| `figma.createLine()` | `graph.createNode('LINE', ...)` |+| `figma.createPolygon()` | `graph.createNode('POLYGON', ...)` |+| `figma.createStar()` | `graph.createNode('STAR', ...)` |+| `figma.createComponent()` | `graph.createNode('COMPONENT', ...)` |+| `figma.createPage()` | `graph.addPage(name)` |+| `figma.createSection()` | `graph.createNode('SECTION', ...)` |++#### Node Properties (via `FigmaNode` proxy)++Read/write on any node proxy. Property access maps to `SceneNode` fields:++```ts+// Geometry+node.x, node.y // direct+node.width, node.height // read-only, use node.resize(w, h)+node.rotation // direct+node.resize(w, h) // updates width + height+node.resizeWithoutConstraints(w, h) // same (no constraint engine yet)++// Visual+node.fills // get/set Fill[]+node.strokes // get/set Stroke[]+node.effects // get/set Effect[]+node.opacity // get/set number+node.visible // get/set boolean+node.locked // get/set boolean+node.blendMode // get/set BlendMode+node.clipsContent // get/set boolean++// Corner radius+node.cornerRadius // get/set (number or figma.mixed)+node.topLeftRadius // get/set+node.topRightRadius // get/set+node.bottomLeftRadius // get/set+node.bottomRightRadius // get/set+node.cornerSmoothing // get/set++// Identity+node.id // read-only+node.name // get/set+node.type // read-only+node.parent // read-only → FigmaNode | null+node.removed // read-only boolean+```++#### Tree Operations++```ts+node.children // read-only FigmaNode[]+node.appendChild(child) // reparent to end+node.insertChild(index, child) // reparent at index+node.remove() // graph.deleteNode(id)++// Traversal+node.findAll(callback?) // recursive find+node.findOne(callback) // first match+node.findChild(callback) // direct children only+node.findChildren(callback?) // direct children only+```++#### Auto-layout++```ts+node.layoutMode // 'NONE' | 'HORIZONTAL' | 'VERTICAL'+node.primaryAxisAlignItems // 'MIN' | 'CENTER' | 'MAX' | 'SPACE_BETWEEN'+node.counterAxisAlignItems // 'MIN' | 'CENTER' | 'MAX' | 'BASELINE'+node.itemSpacing // number+node.counterAxisSpacing // number | null+node.paddingTop / Right / Bottom / Left // number+node.layoutWrap // 'NO_WRAP' | 'WRAP'++// Child sizing+node.layoutPositioning // 'AUTO' | 'ABSOLUTE'+node.layoutGrow // 0 | 1+node.layoutSizingHorizontal // 'FIXED' | 'HUG' | 'FILL'+node.layoutSizingVertical // 'FIXED' | 'HUG' | 'FILL'+```++#### Text++```ts+node.characters // get/set (maps to node.text)+node.fontSize // get/set+node.fontName // get/set { family, style }+node.fontWeight // get/set+node.textAlignHorizontal // get/set+node.textAlignVertical // get/set+node.textAutoResize // get/set+node.letterSpacing // get/set+node.lineHeight // get/set+node.maxLines // get/set+node.textCase // get/set+node.textDecoration // get/set+```++#### Stroke details++```ts+node.strokeWeight // get/set (maps to strokes[0].weight)+node.strokeAlign // get/set (maps to strokes[0].align)+node.dashPattern // get/set+```++#### Misc++```ts+figma.mixed // Symbol sentinel for mixed values+figma.group(nodes, parent) // creates GROUP with given children+figma.ungroup(node) // ungroups, reparents children+figma.flatten(nodes) // NOT IMPLEMENTED YET — returns first node+```++#### Export++```ts+node.exportAsync(settings?) // only works if CanvasKit is loaded+ // settings: { format: 'PNG'|'JPG'|'SVG', constraint? }+```++### Phase 2: Components & Instances++| API | Maps to |+|-----|---------|+| `figma.createComponent()` | `graph.createNode('COMPONENT', ...)` |+| `figma.createComponentFromNode(node)` | Convert existing frame to component |+| `figma.combineAsVariants(components, parent)` | Create COMPONENT_SET |+| Node: `node.createInstance()` | `graph.createInstance(componentId, parentId)` |+| Node: `node.detachInstance()` | `graph.detachInstance(id)` |+| `figma.getNodeById(id).mainComponent` | `graph.getMainComponent(id)` |++### Phase 3: Variables++| API | Maps to |+|-----|---------|+| `figma.variables.getLocalVariables(type?)` | `graph.variables` filtered |+| `figma.variables.getLocalVariableCollections()` | `graph.variableCollections` |+| `figma.variables.createVariable(name, collection, type)` | `graph.addVariable(...)` |+| `figma.variables.createVariableCollection(name)` | `graph.addCollection(...)` |+| `figma.variables.getVariableById(id)` | `graph.variables.get(id)` |+| `node.setBoundVariable(field, variable)` | `graph.bindVariable(...)` |+| `node.boundVariables` | getter from SceneNode |++### Phase 4: Styles & Advanced++| API | Notes |+|-----|-------|+| `figma.createPaintStyle()` | Requires style storage in SceneGraph |+| `figma.createTextStyle()` | Requires style storage in SceneGraph |+| `figma.createEffectStyle()` | Requires style storage in SceneGraph |+| `figma.loadFontAsync(fontName)` | No-op (we don't have font loading constraints) |+| `figma.listAvailableFontsAsync()` | Return system fonts if available |+| Boolean operations (`union`, `subtract`, `intersect`, `exclude`) | Requires path boolean engine |+| `figma.createNodeFromJSXAsync(jsx)` | Port figma-use's JSX renderer |++## `FigmaNode` Proxy Design++The proxy wraps a `SceneNode` and translates Figma property names to our internal names. Key mappings:++```ts+const PROPERTY_MAP: Record<string, string> = {+ // Figma name → SceneNode field name (only where they differ)+ 'characters': 'text',+ 'strokeWeight': → computed from strokes[0].weight,+ 'strokeAlign': → computed from strokes[0].align,+ 'fontName': → computed from { family: fontFamily, style: ... },+ 'primaryAxisAlignItems': 'primaryAxisAlign',+ 'counterAxisAlignItems': 'counterAxisAlign',+ 'primaryAxisSizingMode': 'primaryAxisSizing', // value mapping: 'AUTO' → 'HUG', 'FIXED' → 'FIXED'+ 'counterAxisSizingMode': 'counterAxisSizing',+ 'layoutSizingHorizontal': → computed from primaryAxisSizing / counterAxisSizing depending on layoutMode+ 'layoutSizingVertical': → computed+}+```++Methods on the proxy:++```ts+class FigmaNode {+ // The proxy is created via: new Proxy(target, handler)+ // where handler.get intercepts property reads and handler.set intercepts writes++ resize(width: number, height: number): void+ resizeWithoutConstraints(width: number, height: number): void+ remove(): void+ appendChild(child: FigmaNode): void+ insertChild(index: number, child: FigmaNode): void+ findAll(callback?: (node: FigmaNode) => boolean): FigmaNode[]+ findOne(callback: (node: FigmaNode) => boolean): FigmaNode | null+ findChild(callback: (node: FigmaNode) => boolean): FigmaNode | null+ findChildren(callback?: (node: FigmaNode) => boolean): FigmaNode[]+ exportAsync(settings?: ExportSettings): Promise<Uint8Array>++ // Components (Phase 2)+ createInstance(): FigmaNode+ detachInstance(): void+ get mainComponent(): FigmaNode | null+}+```++## CLI Command++```+bun open-pencil eval <file> [options]++Arguments:+ file .fig file to operate on++Options:+ --code, -c JavaScript code to execute (has access to `figma` global)+ --stdin Read code from stdin instead of --code+ --write, -w Write changes back to the input file+ -o, --output Write to a different file+ --json Output result as JSON (default for non-TTY)+ --quiet, -q Suppress output, only write file+```++### Execution model++1. Load `.fig` → `SceneGraph`+2. Create `FigmaAPI(graph)` → `figma` proxy+3. Wrap user code in async function: `return (async () => { <code> })()`+4. Execute with `figma` as sole argument+5. Print return value (JSON or agentfmt)+6. If `--write` or `-o`: serialize `SceneGraph` back to `.fig`++### Return value formatting++- `undefined` / `void` → no output+- Primitives → printed directly+- Objects/arrays → `JSON.stringify(result, null, 2)` or agentfmt tables+- `FigmaNode` → serialized as `{ id, type, name, x, y, width, height, fills, ... }`+- Arrays of `FigmaNode` → serialized as list++## 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`:++```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)+execute: async ({ type, x, y, width, height }) => {+ const frame = figma.createFrame()+ frame.resize(width, height)+ frame.x = x+ frame.y = y+ return { id: frame.id }+}+```++This ensures CLI scripts and AI tools behave identically.++## File Layout++```+packages/core/src/+ figma-api.ts # FigmaAPI class + FigmaNode proxy (Phase 1–4)+ figma-api.test.ts # Unit tests against headless SceneGraph++packages/cli/src/commands/+ eval.ts # CLI command++packages/cli/src/commands/eval.test.ts # Integration tests+```++## Test Plan++### Unit tests (`packages/core/src/figma-api.test.ts`)++1. **Node creation** — each `createX()` creates correct type, added to current page+2. **Property access** — `.fills`, `.x`, `.width`, `.name`, `.characters` read/write correctly+3. **Resize** — `.resize(w, h)` updates width/height+4. **Tree operations** — `.appendChild()`, `.insertChild()`, `.remove()`, `.parent`, `.children`+5. **Traversal** — `.findAll()`, `.findOne()`, `.findChild()`, `.findChildren()` with callbacks+6. **Auto-layout** — `.layoutMode`, `.itemSpacing`, `.paddingTop`, etc.+7. **Text** — `.characters` maps to `.text`, `.fontName` maps to `{ family, style }`+8. **Mixed values** — `.cornerRadius` returns `figma.mixed` when corners differ+9. **Selection** — `figma.currentPage.selection` get/set+10. **Page switching** — `figma.currentPage = page2` works+11. **Group/ungroup** — `figma.group()` creates group, `figma.ungroup()` dissolves it+12. **Clone** — node creation produces independent copies++### CLI integration tests (`packages/cli/src/commands/eval.test.ts`)++1. **Basic eval** — `eval test.fig --code 'return figma.currentPage.name'` → page name+2. **Create + read** — create a frame, return its properties+3. **Query nodes** — `findAll` returns correct nodes+4. **Write back** — `--write` saves changes, reloading shows them+5. **Stdin** — `echo 'return 42' | bun open-pencil eval test.fig --stdin` → `42`+6. **JSON output** — `--json` returns valid JSON+7. **Error handling** — syntax errors, runtime errors reported cleanly++## Implementation Order++1. **`FigmaNode` proxy** — property mapping, `.resize()`, `.remove()`, tree methods+2. **`FigmaAPI` class** — `createFrame/Rectangle/...`, `.root`, `.currentPage`, `.getNodeById()`, `.mixed`, `.group()`+3. **CLI `eval` command** — argument parsing, code wrapping, output formatting+4. **Unit tests** — all 12 test groups above+5. **CLI integration tests** — all 7 test groups above+6. **Wire to AI tools** — refactor `src/ai/tools.ts` to use `FigmaAPI` where possible+7. **Phase 2** — components & instances+8. **Phase 3** — variables+9. **Phase 4** — styles, boolean ops, JSX renderer++## Property Mapping Reference++| Figma Property | SceneNode Field | Type | Notes |+|---------------|-----------------|------|-------|+| `characters` | `text` | `string` | |+| `fontName` | `fontFamily` + `fontWeight` + `italic` | `{ family, style }` | Computed: `style` = "Bold Italic" etc. |+| `strokeWeight` | `strokes[0].weight` | `number` | Computed |+| `strokeAlign` | `strokes[0].align` | `string` | Computed |+| `primaryAxisAlignItems` | `primaryAxisAlign` | `string` | |+| `counterAxisAlignItems` | `counterAxisAlign` | `string` | |+| `layoutSizingHorizontal` | `primaryAxisSizing` or `counterAxisSizing` | `string` | Depends on `layoutMode` |+| `layoutSizingVertical` | (opposite of horizontal) | `string` | |+| `absoluteTransform` | computed from `x`, `y`, `rotation` | `Transform` | Read-only |+| `absoluteBoundingBox` | `getAbsoluteBounds(id)` | `Rect` | Read-only |+| All others | Same name | Same type | Direct passthrough |++## Open Questions++1. **Font loading**: `figma.loadFontAsync()` — should it be a no-op (we don't have font gating) or should we track loaded fonts?+ → **Decision: No-op that returns resolved Promise.** We don't gate text editing on font loading.++2. **Export in headless mode**: `node.exportAsync()` requires CanvasKit. Should eval load CanvasKit?+ → **Decision: Optional.** If CanvasKit is available (via `--with-canvaskit` flag or env), enable export. Otherwise, throw "Export requires CanvasKit" error.++3. **`figma.mixed` symbol**: Should we use the actual Figma symbol or our own?+ → **Decision: Our own `Symbol('mixed')`.** Exposed as `figma.mixed`.++4. **Undo**: `figma.commitUndo()` / `figma.triggerUndo()` — relevant in headless?+ → **Decision: No-op in CLI.** Undo only matters in the live editor. The AI tools can add undo support separately via EditorStore.++5. **Write format**: Should `--write` produce `.fig` (Kiwi binary) or also support `.json`?+ → **Decision: `.fig` only for now.** JSON export is a separate feature.diff --git a/packages/docs/pl/reference/file-format.md b/packages/docs/pl/reference/file-format.mdnew file mode 100644index 000000000..220856b20--- /dev/null+++ b/packages/docs/pl/reference/file-format.md@@ -0,0 +1,71 @@+# Format pliku++## .fig File Structure++```+┌─────────────────────────────────┐+│ Magic header: "fig-kiwi" (8B) │+│ Version (4B uint32 LE) │+│ Schema length (4B uint32 LE) │+│ Compressed Kiwi schema │+│ Message length (4B uint32 LE) │+│ Compressed Kiwi message │ ← NodeChange[] (entire document)+│ Blob data │ ← Images, vector networks, fonts+└─────────────────────────────────┘+```++## Import Pipeline++```+.fig file → Parse header → Decompress Zstd → Decode Kiwi schema+ → Decode Message → NodeChange[] → Build SceneGraph+ → Resolve blob refs → Render on canvas+```++## Export Pipeline++```+SceneGraph → NodeChange[] → Kiwi encode → Compress (Zstd/deflate)+ → Build ZIP (header + schema + message + thumbnail.png)+ → Write .fig file+```++Export uses <kbd>⌘</kbd><kbd>S</kbd> (Save) and <kbd>⇧</kbd><kbd>⌘</kbd><kbd>S</kbd> (Save As) with native OS dialogs on the desktop app. The exported file includes a `thumbnail.png` required by Figma for file preview. Compression uses Zstd via Tauri Rust command on desktop, with deflate fallback in the browser. The ZIP archive is assembled in Rust on desktop for correct Zstd frame headers (content size included).++## Kiwi Binary Codec++The codec handles Figma's 194-definition Kiwi schema with NodeChange as the central type (~390 fields). Key components:++- **kiwi-schema** — vendored from evanw/kiwi, patched for ESM and sparse field IDs+- **codec.ts** — encode/decode Messages using the Kiwi schema+- **protocol.ts** — wire format parsing and message type detection+- **schema.ts** — 194 message/enum/struct definitions++### Sparse Field IDs++Figma's schema uses non-contiguous field IDs (e.g., 1, 2, 5, 10 with gaps). The vendored kiwi-schema parser is patched to handle this correctly.++### Compression++.fig files use Zstd compression for both the schema and message payloads. Decompression uses the `fzstd` library. For export, Zstd compression is offloaded to a Tauri Rust command on the desktop app (better performance, correct frame headers). In the browser, deflate via `fflate` is used as a fallback. Clipboard encoding also uses `fflate`.++## Supported Formats++| Format | Import | Export |+|--------|--------|--------|+| .fig (Figma) | ✅ | ✅ |+| .svg | Planned | Planned |+| .png | Planned | Planned |+| .pdf | — | Planned |++See [Roadmap](/development/roadmap) for planned format support timeline.++## Clipboard Format++Copy/paste uses the same Kiwi binary encoding:++1. **Copy** — encode selected NodeChange[] to Kiwi binary, compress, write to clipboard as `application/x-figma-design` MIME type+2. **Paste** — read clipboard, decompress, decode Kiwi binary, create nodes in scene graph+3. **Synchronous** — encoding happens in the copy event handler (not async Clipboard API) to ensure browser compatibility++This enables bidirectional clipboard between OpenPencil and Figma.diff --git a/packages/docs/pl/reference/keyboard-shortcuts.md b/packages/docs/pl/reference/keyboard-shortcuts.mdnew file mode 100644index 000000000..a8839772f--- /dev/null+++ b/packages/docs/pl/reference/keyboard-shortcuts.md@@ -0,0 +1,120 @@+# Skróty klawiszowe++Pełna mapa skrótów kompatybilnych z Figmą.++::: tip Symbol Legend+⌘ = Cmd (Mac) / Ctrl (Win/Linux) · ⇧ = Shift · ⌥ = Alt/Option · ⌃ = Ctrl · ⌫ = Backspace+:::++## Tools++| Key | Tool | Status |+|-----|------|--------|+| <kbd>V</kbd> | Move/Select | ✅ |+| <kbd>K</kbd> | Scale | 🔲 |+| <kbd>H</kbd> | Hand | ✅ |+| <kbd>F</kbd> | Frame | ✅ |+| <kbd>S</kbd> | Section | ✅ |+| <kbd>R</kbd> | Rectangle | ✅ |+| <kbd>O</kbd> | Ellipse | ✅ |+| <kbd>L</kbd> | Line | ✅ |+| — | Polygon | ✅ (flyout only) |+| — | Star | ✅ (flyout only) |+| <kbd>⇧</kbd><kbd>L</kbd> | Arrow | 🔲 |+| <kbd>P</kbd> | Pen | ✅ |+| <kbd>⇧</kbd><kbd>P</kbd> | Pencil | 🔲 |+| <kbd>T</kbd> | Text | ✅ |+| <kbd>C</kbd> | Comment | 🔲 |+| <kbd>I</kbd> | Eyedropper | 🔲 |++## File++| Shortcut | Action | Status |+|----------|--------|--------|+| <kbd>⌘</kbd><kbd>N</kbd> | New Window | 🔲 |+| <kbd>⌘</kbd><kbd>O</kbd> | Open File | ✅ |+| <kbd>⌘</kbd><kbd>W</kbd> | Close Tab | 🔲 |+| <kbd>⌘</kbd><kbd>S</kbd> | Save | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>S</kbd> | Save As | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>E</kbd> | Export… | ✅ |++## Edit++| Shortcut | Action | Status |+|----------|--------|--------|+| <kbd>⌘</kbd><kbd>Z</kbd> | Undo | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>Z</kbd> | Redo | ✅ |+| <kbd>⌘</kbd><kbd>X</kbd> | Cut | ✅ |+| <kbd>⌘</kbd><kbd>C</kbd> | Copy | ✅ |+| <kbd>⌘</kbd><kbd>V</kbd> | Paste | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>V</kbd> | Paste Over Selection | 🔲 |+| <kbd>⌘</kbd><kbd>D</kbd> | Duplicate | ✅ |+| <kbd>⌫</kbd> | Delete | ✅ |+| <kbd>⌘</kbd><kbd>A</kbd> | Select All | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>A</kbd> | Select Inverse | 🔲 |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>C</kbd> | Copy Properties | 🔲 |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>V</kbd> | Paste Properties | 🔲 |++## View++| Shortcut | Action | Status |+|----------|--------|--------|+| <kbd>⌘</kbd><kbd>'</kbd> | Pixel Grid | 🔲 |+| <kbd>⌃</kbd><kbd>G</kbd> | Layout Guides | 🔲 |+| <kbd>⇧</kbd><kbd>R</kbd> | Rulers | 🔲 |+| <kbd>⌘</kbd><kbd>\\</kbd> | Show/Hide UI | 🔲 |+| <kbd>⌘</kbd><kbd>=</kbd> | Zoom In | ✅ |+| <kbd>⌘</kbd><kbd>-</kbd> | Zoom Out | ✅ |+| <kbd>⌘</kbd><kbd>0</kbd> | Zoom to 100% | ✅ |+| <kbd>⌘</kbd><kbd>1</kbd> | Zoom to Fit | 🔲 |+| <kbd>⌘</kbd><kbd>2</kbd> | Zoom to Selection | 🔲 |+| <kbd>⌘</kbd><kbd>J</kbd> | Toggle AI Chat | ✅ |++## Object++| Shortcut | Action | Status |+|----------|--------|--------|+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>G</kbd> | Frame Selection | 🔲 |+| <kbd>⌘</kbd><kbd>G</kbd> | Group Selection | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>G</kbd> | Ungroup | ✅ |+| <kbd>⇧</kbd><kbd>A</kbd> | Add Auto Layout | ✅ |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>K</kbd> | Create Component | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>K</kbd> | Create Component Set | ✅ |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>B</kbd> | Detach Instance | ✅ |+| <kbd>⌘</kbd><kbd>]</kbd> | Bring Forward | 🔲 |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>]</kbd> | Bring to Front | 🔲 |+| <kbd>]</kbd> | Bring to Front | ✅ |+| <kbd>⌘</kbd><kbd>[</kbd> | Send Backward | 🔲 |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>[</kbd> | Send to Back | 🔲 |+| <kbd>[</kbd> | Send to Back | ✅ |+| <kbd>⇧</kbd><kbd>H</kbd> | Flip Horizontal | 🔲 |+| <kbd>⇧</kbd><kbd>V</kbd> | Flip Vertical | 🔲 |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>H</kbd> | Toggle Visibility | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>L</kbd> | Toggle Lock | ✅ |+| <kbd>⌘</kbd><kbd>E</kbd> | Flatten | 🔲 |++## Text++| Shortcut | Action | Status |+|----------|--------|--------|+| <kbd>⌘</kbd><kbd>B</kbd> | Bold | ✅ |+| <kbd>⌘</kbd><kbd>I</kbd> | Italic | ✅ |+| <kbd>⌘</kbd><kbd>U</kbd> | Underline | ✅ |+| <kbd>⇧</kbd><kbd>⌘</kbd><kbd>X</kbd> | Strikethrough | 🔲 |++## Canvas Interaction++| Input | Action | Status |+|-------|--------|--------|+| Click | Select node | ✅ |+| <kbd>Shift</kbd>+Click | Add/remove from selection | ✅ |+| <kbd>Alt</kbd>+Drag | Duplicate and move | ✅ |+| <kbd>Shift</kbd>+Drag (draw) | Constrain to square/circle | ✅ |+| <kbd>Shift</kbd>+Drag (resize) | Maintain aspect ratio | ✅ |+| <kbd>Shift</kbd>+Drag (rotate) | Snap to 15° | ✅ |+| Middle mouse drag | Pan | ✅ |+| Scroll | Pan | ✅ |+| <kbd>Ctrl</kbd>+Scroll / Pinch | Zoom | ✅ |+| Double-click text | Edit text inline | ✅ |+| Drag onto frame | Reparent into frame | ✅ |+| <kbd>Escape</kbd> | Deselect / Cancel | ✅ |diff --git a/packages/docs/pl/reference/mcp-tools.md b/packages/docs/pl/reference/mcp-tools.mdnew file mode 100644index 000000000..c0241f09a--- /dev/null+++ b/packages/docs/pl/reference/mcp-tools.md@@ -0,0 +1,140 @@+# Serwer MCP++OpenPencil includes an MCP (Model Context Protocol) server that lets AI coding tools — Claude Code, Cursor, Windsurf, etc. — read and modify `.fig` files headlessly.++Two transports: **stdio** for MCP clients, **HTTP** for everything else.++## Install++```sh+bun add -g @open-pencil/mcp+```++## Stdio (Claude Code, Cursor, etc.)++Add to your MCP config (e.g. `~/.claude/settings.json` or `.cursor/mcp.json`):++```json+{+ "mcpServers": {+ "open-pencil": {+ "command": "openpencil-mcp"+ }+ }+}+```++Or run from source without installing:++::: code-group+```json [Bun]+{+ "mcpServers": {+ "open-pencil": {+ "command": "bun",+ "args": ["/path/to/open-pencil/packages/mcp/src/index.ts"]+ }+ }+}+```+```json [Node.js]+{+ "mcpServers": {+ "open-pencil": {+ "command": "npx",+ "args": ["tsx", "/path/to/open-pencil/packages/mcp/src/index.ts"]+ }+ }+}+```+:::++## HTTP++For browser extensions, scripts, CI, or any HTTP client:++```sh+openpencil-mcp-http+```++Or from source: `bun packages/mcp/src/http.ts` / `npx tsx packages/mcp/src/http.ts`++Starts on port 3100 (override with `PORT` env var). Endpoints:++- `GET /health` — server status+- `POST /mcp` — MCP Streamable HTTP (SSE). Sessions via `mcp-session-id` header.++## Workflow++1. **Open** — `open_file` to load an existing `.fig`, or `new_document` for a blank canvas+2. **Read** — `get_page_tree`, `find_nodes`, `get_node`, `list_pages`+3. **Create** — `create_shape`, `render` (JSX)+4. **Modify** — `set_fill`, `set_stroke`, `set_layout`, `update_node`, `set_effects`+5. **Structure** — `reparent_node`, `group_nodes`, `clone_node`, `delete_node`+6. **Save** — `save_file` to write back to `.fig`++## Tools (29)++### Document++| Tool | Description |+|------|-------------|+| `open_file` | Open a `.fig` file for editing |+| `save_file` | Save the current document to a `.fig` file |+| `new_document` | Create a new empty document |++### Read++| Tool | Description |+|------|-------------|+| `get_selection` | Get currently selected nodes |+| `get_page_tree` | Get the full node tree of the current page |+| `get_node` | Get detailed properties of a node by ID |+| `find_nodes` | Find nodes by name pattern and/or type |+| `list_pages` | List all pages |+| `list_variables` | List design variables |+| `list_collections` | List variable collections |++### Create++| Tool | Description |+|------|-------------|+| `create_shape` | Create a shape (FRAME, RECTANGLE, ELLIPSE, TEXT, LINE, STAR, POLYGON, SECTION) |+| `render` | Render JSX to design nodes — create entire component trees in one call |+| `create_component` | Convert a frame/group into a component |+| `create_instance` | Create an instance of a component |++### Modify++| Tool | Description |+|------|-------------|+| `set_fill` | Set fill color (hex) |+| `set_stroke` | Set stroke color, weight, alignment |+| `set_effects` | Add shadow or blur effects |+| `update_node` | Update position, size, opacity, corner radius, text, font |+| `set_layout` | Set auto-layout (flexbox) — direction, spacing, padding, alignment |+| `set_constraints` | Set resize constraints |++### Structure++| Tool | Description |+|------|-------------|+| `delete_node` | Delete a node |+| `clone_node` | Duplicate a node |+| `rename_node` | Rename a node |+| `reparent_node` | Move a node into a different parent |+| `select_nodes` | Select nodes by ID |+| `group_nodes` | Group nodes |+| `ungroup_node` | Ungroup a group |++### Navigation++| Tool | Description |+|------|-------------|+| `switch_page` | Switch to a page by name or ID |++### Escape Hatch++| Tool | Description |+|------|-------------|+| `eval` | Execute JavaScript with full Figma Plugin API access |diff --git a/packages/docs/pl/reference/node-types.md b/packages/docs/pl/reference/node-types.mdnew file mode 100644index 000000000..f5e27b1d6--- /dev/null+++ b/packages/docs/pl/reference/node-types.md@@ -0,0 +1,194 @@+# Typy węzłów++The scene graph supports 28 node types from Figma's Kiwi schema. Each node is identified by a GUID (`sessionID:localID`) and has a parent reference via `parentIndex`. The OpenPencil engine's `NodeType` union currently uses 17 of these types.++## Type Table++28 Figma schema types + 1 synthetic engine type. Types marked ✅ are in the engine's `NodeType` union (17 total).++| Type | ID | Description | Engine |+|------|----|-------------|--------|+| DOCUMENT | 1 | Root node, one per file | — |+| CANVAS | 2 | Page | ✅ |+| GROUP | 3 | Group container | ✅ |+| FRAME | 4 | Primary container (artboard), supports auto-layout | ✅ |+| BOOLEAN_OPERATION | 5 | Union/subtract/intersect/exclude result | |+| VECTOR | 6 | Freeform vector path | ✅ |+| STAR | 7 | Star shape | ✅ |+| LINE | 8 | Line | ✅ |+| ELLIPSE | 9 | Ellipse/circle, supports arc data | ✅ |+| RECTANGLE | 10 | Rectangle | ✅ |+| REGULAR_POLYGON | 11 | Regular polygon (3–12 sides, engine uses `POLYGON`) | ✅ |+| ROUNDED_RECTANGLE | 12 | Rectangle with smooth corners | ✅ |+| TEXT | 13 | Text with rich formatting | ✅ |+| SLICE | 14 | Export region | |+| SYMBOL | 15 | Component (main, engine uses `COMPONENT`) | ✅ |+| INSTANCE | 16 | Component instance | ✅ |+| STICKY | 17 | FigJam sticky note | |+| SHAPE_WITH_TEXT | 18 | FigJam shape | ✅ |+| CONNECTOR | 19 | Connector line between nodes | ✅ |+| CODE_BLOCK | 20 | FigJam code block | |+| WIDGET | 21 | Plugin widget | |+| STAMP | 22 | FigJam stamp | |+| MEDIA | 23 | Video/GIF | |+| HIGHLIGHT | 24 | FigJam highlight | |+| SECTION | 25 | Canvas section (organizational, top-level only) | ✅ |+| SECTION_OVERLAY | 26 | Section overlay | |+| WASHI_TAPE | 27 | FigJam washi tape | |+| VARIABLE | 28 | Variable definition node | |+| COMPONENT_SET | — | Variant group container (synthetic, mapped from SYMBOL) | ✅ |++### Engine NodeType Union (17 types)++The engine's `NodeType` uses simplified names. Some differ from the Kiwi schema:+- `COMPONENT` → Kiwi `SYMBOL` (ID 15)+- `COMPONENT_SET` → variant group container (no dedicated Kiwi ID, mapped from SYMBOL with variants)+- `POLYGON` → Kiwi `REGULAR_POLYGON` (ID 11)++```typescript+type NodeType =+ | 'CANVAS' | 'FRAME' | 'RECTANGLE' | 'ROUNDED_RECTANGLE'+ | 'ELLIPSE' | 'TEXT' | 'LINE' | 'STAR' | 'POLYGON'+ | 'VECTOR' | 'GROUP' | 'SECTION'+ | 'COMPONENT' | 'COMPONENT_SET' | 'INSTANCE'+ | 'CONNECTOR' | 'SHAPE_WITH_TEXT'+```++## Node Hierarchy++```+Document+├── Canvas (Page 1)+│ ├── Section (top-level only, title pill, auto-adopts siblings)+│ │ ├── Frame+│ │ │ └── ...children+│ │ └── Rectangle+│ ├── Frame+│ │ ├── Rectangle+│ │ ├── Text+│ │ └── Frame (nested)+│ │ ├── Ellipse+│ │ └── Instance (→ references Component)+│ ├── Component+│ │ └── ...children+│ ├── Group+│ │ └── ...children+│ └── BooleanOperation+│ └── ...operand shapes+└── Canvas (Page 2)+ └── ...+```++## Core Properties++Every node carries these fields (subset of NodeChange):++### Identity & Tree++- `guid` — unique identifier (`sessionID:localID`)+- `type` — node type enum+- `name` — display name+- `phase` — CREATED or REMOVED+- `parentIndex` — parent GUID + position string for z-ordering++### Transform++- `size` — width/height vector+- `transform` — 2×3 affine matrix+- `rotation` — degrees++### Appearance++- `fillPaints[]` — fill colors/gradients/images+- `strokePaints[]` — stroke colors+- `effects[]` — shadows, blurs+- `opacity` — 0–1+- `blendMode` — NORMAL, MULTIPLY, SCREEN, etc.++### Stroke++- `strokeWeight` — stroke thickness+- `strokeAlign` — inside / center / outside+- `strokeCap` — butt / round / square+- `strokeJoin` — miter / bevel / round+- `dashPattern[]` — dash/gap lengths++### Corners++- `cornerRadius` — uniform radius+- `cornerSmoothing` — squircle amount (0–1)+- Per-corner radii when `rectangleCornerRadiiIndependent` is true++### Visibility++- `visible` — show/hide+- `locked` — prevent editing++## Type-Specific Properties++### Text++`fontSize`, `fontName`, `lineHeight`, `letterSpacing`, `textAlignHorizontal`, `textAlignVertical`, `textAutoResize`, `textData` (characters, style overrides, baselines, glyphs)++### Vector++`vectorData` (vectorNetworkBlob, normalizedSize), `fillGeometry[]`, `strokeGeometry[]`, `handleMirroring`, `arcData`++### Layout (Frame)++`stackMode`, `stackSpacing`, `stackPadding`, `stackJustify`, `stackCounterAlign`, `stackPrimarySizing`, `stackCounterSizing`, `stackChildPrimaryGrow`, `stackChildAlignSelf`++### Component++`symbolData`, `componentKey`, `componentPropDefs[]`, `symbolDescription`++### Instance++`overriddenSymbolID`, `symbolData.symbolOverrides[]`, `componentPropRefs[]`, `componentPropAssignments[]`++## Paint++```typescript+interface Fill {+ type: 'SOLID' | 'GRADIENT_LINEAR' | 'GRADIENT_RADIAL' |+ 'GRADIENT_ANGULAR' | 'GRADIENT_DIAMOND' | 'IMAGE'+ color: Color // {r, g, b, a} 0–1 floats+ opacity: number // 0–1+ visible: boolean+ blendMode?: BlendMode+ gradientStops?: GradientStop[] // for gradients+ gradientTransform?: GradientTransform // 2×3 matrix+ imageHash?: string // for image fills+ imageScaleMode?: 'FILL' | 'FIT' | 'CROP' | 'TILE'+ imageTransform?: GradientTransform+}+```++## Effect++```typescript+interface Effect {+ type: 'DROP_SHADOW' | 'INNER_SHADOW' | 'LAYER_BLUR' |+ 'BACKGROUND_BLUR' | 'FOREGROUND_BLUR'+ color: Color+ offset: { x: number; y: number }+ radius: number+ spread: number+ visible: boolean+}+```++## Stroke++```typescript+interface Stroke {+ color: Color+ weight: number+ opacity: number+ visible: boolean+ align: 'INSIDE' | 'CENTER' | 'OUTSIDE'+ cap?: 'NONE' | 'ROUND' | 'SQUARE' | 'ARROW_LINES' | 'ARROW_EQUILATERAL'+ join?: 'MITER' | 'BEVEL' | 'ROUND'+ dashPattern?: number[]+}+```diff --git a/packages/docs/pl/reference/scene-graph.md b/packages/docs/pl/reference/scene-graph.mdnew file mode 100644index 000000000..c80d6a193--- /dev/null+++ b/packages/docs/pl/reference/scene-graph.md@@ -0,0 +1,99 @@+# Graf sceny++## In-Memory Representation++Nodes live in a flat `Map<string, Node>` keyed by GUID string. The tree structure is maintained via `parentIndex` references. This gives O(1) lookup by ID and efficient traversal.++```typescript+interface SceneGraph {+ nodes: Map<string, Node>+ root: string++ getNode(id: string): Node+ getChildren(id: string): Node[]+ getParent(id: string): Node | null+ getPages(): Node[]++ createNode(type: NodeType, parent: string, props: Partial<NodeChange>): Node+ updateNode(id: string, changes: Partial<NodeChange>): void+ deleteNode(id: string): void+ moveNode(id: string, newParent: string, position: string): void+ addPage(name: string): Node+ deletePage(id: string): void+ renamePage(id: string, name: string): void++ findByType(type: NodeType): Node[]+ findByName(pattern: string): Node[]+ hitTest(point: Vector, canvas: string): Node | null+ getNodesInRect(rect: Rect, canvas: string): Node[]+}+```++## Pages++Documents support multiple pages (CANVAS nodes as direct children of the DOCUMENT root). Each page has its own child tree and independent viewport state (panX, panY, zoom, pageColor). The editor tracks `currentPageId` and renders only the active page's children.++## Sections++SECTION nodes are top-level organizational containers (direct children of CANVAS only). They cannot nest inside frames or groups. Creating a section auto-adopts overlapping siblings. Sections display a title pill with luminance-adaptive text color.++## Hover State++The editor state tracks `hoveredNodeId` — the node currently under the cursor. The renderer draws a shape-aware hover outline (following actual geometry for ellipses, rounded rects, vectors) for visual feedback before selection.++## Undo/Redo++The system uses Figma's **inverse command** pattern. Each undo entry contains the forward changes and their automatically-computed inverse:++| Operation | Forward | Inverse |+|-----------|---------|---------|+| Create node | `{guid, phase: CREATED, ...props}` | `{guid, phase: REMOVED}` |+| Delete node | `{guid, phase: REMOVED}` | `{guid, phase: CREATED, ...allProps}` |+| Change prop | `{guid, fill: "#F00"}` | `{guid, fill: "#00F"}` |+| Move node | `{guid, parentIndex: newParent}` | `{guid, parentIndex: oldParent}` |++Before applying any change, affected fields are snapshotted. The snapshot becomes the inverse.++**Batching** — operations like drag-to-move produce hundreds of position changes per second. These are debounced into a single undo entry. `beginBatch`/`commitBatch` wraps multi-step operations.++## Layout Engine (Yoga)++Figma's auto-layout properties map to Yoga flexbox:++| Figma Property | Yoga Equivalent |+|---|---|+| `stackMode: HORIZONTAL` | `flexDirection: row` |+| `stackMode: VERTICAL` | `flexDirection: column` |+| `stackSpacing` | `gap` |+| `stackPadding` | `padding` |+| `stackJustify: MIN/CENTER/MAX/SPACE_BETWEEN` | `justifyContent` |+| `stackCounterAlign` | `alignItems` |+| `stackPrimarySizing: FIXED/HUG/FILL` | width/height + flex-grow |+| `stackChildPrimaryGrow` | `flexGrow` |+| `stackChildAlignSelf` | `alignSelf` |+| `stackPositioning: ABSOLUTE` | `position: absolute` |++## Hit Testing++Given a point in canvas coordinates, the scene graph returns the topmost visible node at that position. The algorithm:++1. Traverse visible nodes in reverse z-order (top to bottom)+2. Transform the test point into each node's local coordinate system+3. Check if the point is within the node's bounds (including rotation)+4. Return the first match++For marquee selection, `getNodesInRect` returns all nodes whose bounds intersect the given rectangle.++## Extended Fill Types++Fills support six types: SOLID, GRADIENT_LINEAR, GRADIENT_RADIAL, GRADIENT_ANGULAR, GRADIENT_DIAMOND, and IMAGE. Gradient fills carry `gradientStops` (color + position pairs) and a `gradientTransform` (2×3 matrix). Image fills reference blob data via `imageHash` with scale modes (FILL, FIT, CROP, TILE).++## Extended Stroke Properties++Strokes support `cap` (NONE, ROUND, SQUARE, ARROW_LINES, ARROW_EQUILATERAL), `join` (MITER, BEVEL, ROUND), and `dashPattern` (array of dash/gap lengths) in addition to the base color, weight, opacity, visible, and align properties.++## Coordinate System++Nodes store position and size relative to their parent. To get absolute (canvas) coordinates, walk up the parent chain applying transforms. The renderer uses this to draw nested frames with correct positioning.++Rotation is stored in degrees and applied as part of the 2×3 transform matrix. Snap guides and hit testing account for rotation when computing visual bounds.