From c714feb44abca5623013651b4d62cb87e7df3857 Mon Sep 17 00:00:00 2001 From: Danila Poyarkov Date: Sun, 8 Mar 2026 18:30:40 +0300 Subject: [PATCH] Add "AI & Automation" docs section, CLI reference, formatting fixes (#75) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add AI & Automation docs section, CLI reference, formatting fixes New 'AI & Automation' top-level nav section with 9 pages: - AI Chat: setup, 87 tools, example prompts - Collaboration: room sharing, cursors, follow mode - JSX Renderer: elements, style props, visual diffing - CLI (4 pages): inspecting, exporting, analyzing, scripting - MCP Server: moved from Reference, setup + 90 tools New CLI reference page in Reference with all 12 commands, every option, alias, and default value. Formatting fixes across all 7 locales: - Wrap enum values in backticks (FRAME, SOLID, ROUND, etc.) - Fix single-backtick code blocks → triple backticks - Use for all keyboard shortcuts - Remove implementation details from user guide - Delete stale eval-command.md and mcp-tools.md (14 files) - Update dead links to new locations * Translate AI & Automation + CLI reference to all 6 locales 48 translated pages (de, es, fr, it, pl, ru) for the Programmable section: overview, AI Chat, Collaboration, JSX Renderer, CLI (inspecting, exporting, analyzing, scripting). CLI reference and MCP server pages copied as-is (mostly code/tables). * Update README and docs for CSS Grid support - Add 'Auto layout & CSS Grid' to README features - Update architecture, tech-stack, features, figma-comparison, comparison - Mark grid as ✅ in all 7 locales - Replace 'blocked on upstream' with Yoga fork links --- README.md | 1 + packages/docs/.vitepress/config.ts | 89 +++- packages/docs/de/development/roadmap.md | 10 +- packages/docs/de/eval-command.md | 140 ------ packages/docs/de/guide/architecture.md | 8 +- packages/docs/de/guide/features.md | 2 +- packages/docs/de/guide/figma-comparison.md | 36 +- packages/docs/de/guide/tech-stack.md | 2 +- packages/docs/de/programmable/ai-chat.md | 47 ++ .../docs/de/programmable/cli/analyzing.md | 65 +++ .../docs/de/programmable/cli/exporting.md | 59 +++ .../docs/de/programmable/cli/inspecting.md | 98 ++++ .../docs/de/programmable/cli/scripting.md | 70 +++ .../docs/de/programmable/collaboration.md | 38 ++ packages/docs/de/programmable/index.md | 51 ++ packages/docs/de/programmable/jsx-renderer.md | 116 +++++ .../programmable/mcp-server.md} | 4 +- packages/docs/de/reference/cli.md | 184 ++++++++ packages/docs/de/reference/file-format.md | 79 ++-- packages/docs/de/reference/mcp-tools.md | 150 ------ packages/docs/de/reference/node-types.md | 74 +-- packages/docs/de/reference/scene-graph.md | 14 +- packages/docs/de/user-guide/auto-layout.md | 8 +- .../docs/de/user-guide/canvas-navigation.md | 16 +- packages/docs/de/user-guide/components.md | 18 +- packages/docs/de/user-guide/context-menu.md | 28 +- packages/docs/de/user-guide/drawing-shapes.md | 24 +- packages/docs/de/user-guide/exporting.md | 24 +- packages/docs/de/user-guide/index.md | 4 +- .../docs/de/user-guide/layers-and-pages.md | 8 +- packages/docs/de/user-guide/pen-tool.md | 10 +- .../user-guide/selection-and-manipulation.md | 34 +- packages/docs/de/user-guide/text-editing.md | 32 +- packages/docs/development/openspec.md | 2 +- packages/docs/development/roadmap.md | 28 +- packages/docs/es/development/roadmap.md | 10 +- packages/docs/es/eval-command.md | 77 --- packages/docs/es/guide/architecture.md | 8 +- packages/docs/es/guide/comparison.md | 2 +- packages/docs/es/guide/features.md | 2 +- packages/docs/es/guide/figma-comparison.md | 30 +- packages/docs/es/guide/tech-stack.md | 2 +- packages/docs/es/programmable/ai-chat.md | 47 ++ .../docs/es/programmable/cli/analyzing.md | 65 +++ .../docs/es/programmable/cli/exporting.md | 59 +++ .../docs/es/programmable/cli/inspecting.md | 98 ++++ .../docs/es/programmable/cli/scripting.md | 70 +++ .../docs/es/programmable/collaboration.md | 38 ++ packages/docs/es/programmable/index.md | 51 ++ packages/docs/es/programmable/jsx-renderer.md | 116 +++++ packages/docs/es/programmable/mcp-server.md | 251 ++++++++++ packages/docs/es/reference/cli.md | 184 ++++++++ packages/docs/es/reference/file-format.md | 79 ++-- packages/docs/es/reference/mcp-tools.md | 150 ------ packages/docs/es/reference/node-types.md | 74 +-- packages/docs/es/reference/scene-graph.md | 14 +- packages/docs/es/user-guide/auto-layout.md | 7 +- .../docs/es/user-guide/canvas-navigation.md | 16 +- packages/docs/es/user-guide/components.md | 46 +- packages/docs/es/user-guide/context-menu.md | 10 +- packages/docs/es/user-guide/drawing-shapes.md | 12 +- packages/docs/es/user-guide/exporting.md | 18 +- packages/docs/es/user-guide/index.md | 4 +- .../docs/es/user-guide/layers-and-pages.md | 4 +- packages/docs/es/user-guide/pen-tool.md | 29 +- .../user-guide/selection-and-manipulation.md | 14 +- packages/docs/es/user-guide/text-editing.md | 45 +- packages/docs/eval-command.md | 437 ------------------ packages/docs/fr/development/roadmap.md | 10 +- packages/docs/fr/eval-command.md | 77 --- packages/docs/fr/guide/architecture.md | 8 +- packages/docs/fr/guide/comparison.md | 2 +- packages/docs/fr/guide/features.md | 2 +- packages/docs/fr/guide/figma-comparison.md | 28 +- packages/docs/fr/guide/tech-stack.md | 2 +- packages/docs/fr/programmable/ai-chat.md | 47 ++ .../docs/fr/programmable/cli/analyzing.md | 65 +++ .../docs/fr/programmable/cli/exporting.md | 59 +++ .../docs/fr/programmable/cli/inspecting.md | 98 ++++ .../docs/fr/programmable/cli/scripting.md | 70 +++ .../docs/fr/programmable/collaboration.md | 38 ++ packages/docs/fr/programmable/index.md | 51 ++ packages/docs/fr/programmable/jsx-renderer.md | 116 +++++ packages/docs/fr/programmable/mcp-server.md | 251 ++++++++++ packages/docs/fr/reference/cli.md | 184 ++++++++ packages/docs/fr/reference/file-format.md | 79 ++-- packages/docs/fr/reference/mcp-tools.md | 150 ------ packages/docs/fr/reference/node-types.md | 74 +-- packages/docs/fr/reference/scene-graph.md | 14 +- packages/docs/fr/user-guide/auto-layout.md | 4 +- .../docs/fr/user-guide/canvas-navigation.md | 16 +- packages/docs/fr/user-guide/components.md | 16 +- packages/docs/fr/user-guide/context-menu.md | 10 +- packages/docs/fr/user-guide/drawing-shapes.md | 12 +- packages/docs/fr/user-guide/exporting.md | 14 +- packages/docs/fr/user-guide/index.md | 2 +- .../docs/fr/user-guide/layers-and-pages.md | 2 +- packages/docs/fr/user-guide/pen-tool.md | 8 +- .../user-guide/selection-and-manipulation.md | 14 +- packages/docs/fr/user-guide/text-editing.md | 20 +- packages/docs/guide/architecture.md | 8 +- packages/docs/guide/comparison.md | 4 +- packages/docs/guide/features.md | 4 +- packages/docs/guide/figma-comparison.md | 34 +- packages/docs/guide/tech-stack.md | 4 +- packages/docs/it/development/roadmap.md | 10 +- packages/docs/it/eval-command.md | 77 --- packages/docs/it/guide/architecture.md | 8 +- packages/docs/it/guide/comparison.md | 2 +- packages/docs/it/guide/features.md | 2 +- packages/docs/it/guide/figma-comparison.md | 30 +- packages/docs/it/guide/tech-stack.md | 2 +- packages/docs/it/programmable/ai-chat.md | 47 ++ .../docs/it/programmable/cli/analyzing.md | 65 +++ .../docs/it/programmable/cli/exporting.md | 59 +++ .../docs/it/programmable/cli/inspecting.md | 98 ++++ .../docs/it/programmable/cli/scripting.md | 70 +++ .../docs/it/programmable/collaboration.md | 38 ++ packages/docs/it/programmable/index.md | 51 ++ packages/docs/it/programmable/jsx-renderer.md | 116 +++++ packages/docs/it/programmable/mcp-server.md | 251 ++++++++++ packages/docs/it/reference/cli.md | 184 ++++++++ packages/docs/it/reference/file-format.md | 79 ++-- packages/docs/it/reference/mcp-tools.md | 150 ------ packages/docs/it/reference/node-types.md | 74 +-- packages/docs/it/reference/scene-graph.md | 14 +- packages/docs/it/user-guide/auto-layout.md | 4 +- .../docs/it/user-guide/canvas-navigation.md | 16 +- packages/docs/it/user-guide/components.md | 12 +- packages/docs/it/user-guide/context-menu.md | 10 +- packages/docs/it/user-guide/drawing-shapes.md | 12 +- packages/docs/it/user-guide/exporting.md | 14 +- packages/docs/it/user-guide/index.md | 2 +- .../docs/it/user-guide/layers-and-pages.md | 2 +- packages/docs/it/user-guide/pen-tool.md | 16 +- .../user-guide/selection-and-manipulation.md | 16 +- packages/docs/it/user-guide/text-editing.md | 24 +- packages/docs/pl/development/roadmap.md | 10 +- packages/docs/pl/eval-command.md | 77 --- packages/docs/pl/guide/architecture.md | 8 +- packages/docs/pl/guide/comparison.md | 2 +- packages/docs/pl/guide/features.md | 2 +- packages/docs/pl/guide/figma-comparison.md | 30 +- packages/docs/pl/guide/tech-stack.md | 2 +- packages/docs/pl/programmable/ai-chat.md | 47 ++ .../docs/pl/programmable/cli/analyzing.md | 65 +++ .../docs/pl/programmable/cli/exporting.md | 59 +++ .../docs/pl/programmable/cli/inspecting.md | 98 ++++ .../docs/pl/programmable/cli/scripting.md | 70 +++ .../docs/pl/programmable/collaboration.md | 38 ++ packages/docs/pl/programmable/index.md | 51 ++ packages/docs/pl/programmable/jsx-renderer.md | 116 +++++ packages/docs/pl/programmable/mcp-server.md | 251 ++++++++++ packages/docs/pl/reference/cli.md | 184 ++++++++ packages/docs/pl/reference/file-format.md | 79 ++-- packages/docs/pl/reference/mcp-tools.md | 150 ------ packages/docs/pl/reference/node-types.md | 74 +-- packages/docs/pl/reference/scene-graph.md | 14 +- packages/docs/pl/user-guide/auto-layout.md | 4 +- .../docs/pl/user-guide/canvas-navigation.md | 16 +- packages/docs/pl/user-guide/components.md | 24 +- packages/docs/pl/user-guide/context-menu.md | 10 +- packages/docs/pl/user-guide/drawing-shapes.md | 12 +- packages/docs/pl/user-guide/exporting.md | 14 +- packages/docs/pl/user-guide/index.md | 4 +- .../docs/pl/user-guide/layers-and-pages.md | 6 +- packages/docs/pl/user-guide/pen-tool.md | 14 +- .../user-guide/selection-and-manipulation.md | 16 +- packages/docs/pl/user-guide/text-editing.md | 30 +- packages/docs/programmable/ai-chat.md | 47 ++ packages/docs/programmable/cli/analyzing.md | 65 +++ packages/docs/programmable/cli/exporting.md | 59 +++ packages/docs/programmable/cli/inspecting.md | 98 ++++ packages/docs/programmable/cli/scripting.md | 70 +++ packages/docs/programmable/collaboration.md | 38 ++ packages/docs/programmable/index.md | 51 ++ packages/docs/programmable/jsx-renderer.md | 116 +++++ packages/docs/programmable/mcp-server.md | 251 ++++++++++ packages/docs/reference/cli.md | 184 ++++++++ packages/docs/reference/file-format.md | 69 +-- packages/docs/reference/node-types.md | 72 +-- packages/docs/reference/scene-graph.md | 10 +- packages/docs/ru/development/openspec.md | 2 +- packages/docs/ru/development/roadmap.md | 28 +- packages/docs/ru/eval-command.md | 437 ------------------ packages/docs/ru/guide/architecture.md | 8 +- packages/docs/ru/guide/comparison.md | 2 +- packages/docs/ru/guide/features.md | 2 +- packages/docs/ru/guide/figma-comparison.md | 34 +- packages/docs/ru/guide/tech-stack.md | 2 +- packages/docs/ru/programmable/ai-chat.md | 47 ++ .../docs/ru/programmable/cli/analyzing.md | 65 +++ .../docs/ru/programmable/cli/exporting.md | 59 +++ .../docs/ru/programmable/cli/inspecting.md | 98 ++++ .../docs/ru/programmable/cli/scripting.md | 70 +++ .../docs/ru/programmable/collaboration.md | 38 ++ packages/docs/ru/programmable/index.md | 51 ++ packages/docs/ru/programmable/jsx-renderer.md | 116 +++++ packages/docs/ru/programmable/mcp-server.md | 251 ++++++++++ packages/docs/ru/reference/cli.md | 184 ++++++++ packages/docs/ru/reference/file-format.md | 97 ++-- packages/docs/ru/reference/mcp-tools.md | 251 ---------- packages/docs/ru/reference/node-types.md | 166 +++---- packages/docs/ru/reference/scene-graph.md | 72 +-- packages/docs/ru/user-guide/auto-layout.md | 8 +- .../docs/ru/user-guide/canvas-navigation.md | 14 +- packages/docs/ru/user-guide/components.md | 22 +- packages/docs/ru/user-guide/context-menu.md | 28 +- packages/docs/ru/user-guide/drawing-shapes.md | 24 +- packages/docs/ru/user-guide/exporting.md | 24 +- packages/docs/ru/user-guide/index.md | 4 +- .../docs/ru/user-guide/layers-and-pages.md | 8 +- packages/docs/ru/user-guide/pen-tool.md | 10 +- .../user-guide/selection-and-manipulation.md | 34 +- packages/docs/ru/user-guide/text-editing.md | 44 +- packages/docs/user-guide/auto-layout.md | 8 +- packages/docs/user-guide/canvas-navigation.md | 16 +- packages/docs/user-guide/components.md | 22 +- packages/docs/user-guide/context-menu.md | 28 +- packages/docs/user-guide/drawing-shapes.md | 24 +- packages/docs/user-guide/exporting.md | 24 +- packages/docs/user-guide/index.md | 4 +- packages/docs/user-guide/layers-and-pages.md | 10 +- packages/docs/user-guide/pen-tool.md | 10 +- .../user-guide/selection-and-manipulation.md | 36 +- packages/docs/user-guide/text-editing.md | 44 +- 226 files changed, 8226 insertions(+), 3801 deletions(-) delete mode 100644 packages/docs/de/eval-command.md create mode 100644 packages/docs/de/programmable/ai-chat.md create mode 100644 packages/docs/de/programmable/cli/analyzing.md create mode 100644 packages/docs/de/programmable/cli/exporting.md create mode 100644 packages/docs/de/programmable/cli/inspecting.md create mode 100644 packages/docs/de/programmable/cli/scripting.md create mode 100644 packages/docs/de/programmable/collaboration.md create mode 100644 packages/docs/de/programmable/index.md create mode 100644 packages/docs/de/programmable/jsx-renderer.md rename packages/docs/{reference/mcp-tools.md => de/programmable/mcp-server.md} (98%) create mode 100644 packages/docs/de/reference/cli.md delete mode 100644 packages/docs/de/reference/mcp-tools.md delete mode 100644 packages/docs/es/eval-command.md create mode 100644 packages/docs/es/programmable/ai-chat.md create mode 100644 packages/docs/es/programmable/cli/analyzing.md create mode 100644 packages/docs/es/programmable/cli/exporting.md create mode 100644 packages/docs/es/programmable/cli/inspecting.md create mode 100644 packages/docs/es/programmable/cli/scripting.md create mode 100644 packages/docs/es/programmable/collaboration.md create mode 100644 packages/docs/es/programmable/index.md create mode 100644 packages/docs/es/programmable/jsx-renderer.md create mode 100644 packages/docs/es/programmable/mcp-server.md create mode 100644 packages/docs/es/reference/cli.md delete mode 100644 packages/docs/es/reference/mcp-tools.md delete mode 100644 packages/docs/eval-command.md delete mode 100644 packages/docs/fr/eval-command.md create mode 100644 packages/docs/fr/programmable/ai-chat.md create mode 100644 packages/docs/fr/programmable/cli/analyzing.md create mode 100644 packages/docs/fr/programmable/cli/exporting.md create mode 100644 packages/docs/fr/programmable/cli/inspecting.md create mode 100644 packages/docs/fr/programmable/cli/scripting.md create mode 100644 packages/docs/fr/programmable/collaboration.md create mode 100644 packages/docs/fr/programmable/index.md create mode 100644 packages/docs/fr/programmable/jsx-renderer.md create mode 100644 packages/docs/fr/programmable/mcp-server.md create mode 100644 packages/docs/fr/reference/cli.md delete mode 100644 packages/docs/fr/reference/mcp-tools.md delete mode 100644 packages/docs/it/eval-command.md create mode 100644 packages/docs/it/programmable/ai-chat.md create mode 100644 packages/docs/it/programmable/cli/analyzing.md create mode 100644 packages/docs/it/programmable/cli/exporting.md create mode 100644 packages/docs/it/programmable/cli/inspecting.md create mode 100644 packages/docs/it/programmable/cli/scripting.md create mode 100644 packages/docs/it/programmable/collaboration.md create mode 100644 packages/docs/it/programmable/index.md create mode 100644 packages/docs/it/programmable/jsx-renderer.md create mode 100644 packages/docs/it/programmable/mcp-server.md create mode 100644 packages/docs/it/reference/cli.md delete mode 100644 packages/docs/it/reference/mcp-tools.md delete mode 100644 packages/docs/pl/eval-command.md create mode 100644 packages/docs/pl/programmable/ai-chat.md create mode 100644 packages/docs/pl/programmable/cli/analyzing.md create mode 100644 packages/docs/pl/programmable/cli/exporting.md create mode 100644 packages/docs/pl/programmable/cli/inspecting.md create mode 100644 packages/docs/pl/programmable/cli/scripting.md create mode 100644 packages/docs/pl/programmable/collaboration.md create mode 100644 packages/docs/pl/programmable/index.md create mode 100644 packages/docs/pl/programmable/jsx-renderer.md create mode 100644 packages/docs/pl/programmable/mcp-server.md create mode 100644 packages/docs/pl/reference/cli.md delete mode 100644 packages/docs/pl/reference/mcp-tools.md create mode 100644 packages/docs/programmable/ai-chat.md create mode 100644 packages/docs/programmable/cli/analyzing.md create mode 100644 packages/docs/programmable/cli/exporting.md create mode 100644 packages/docs/programmable/cli/inspecting.md create mode 100644 packages/docs/programmable/cli/scripting.md create mode 100644 packages/docs/programmable/collaboration.md create mode 100644 packages/docs/programmable/index.md create mode 100644 packages/docs/programmable/jsx-renderer.md create mode 100644 packages/docs/programmable/mcp-server.md create mode 100644 packages/docs/reference/cli.md delete mode 100644 packages/docs/ru/eval-command.md create mode 100644 packages/docs/ru/programmable/ai-chat.md create mode 100644 packages/docs/ru/programmable/cli/analyzing.md create mode 100644 packages/docs/ru/programmable/cli/exporting.md create mode 100644 packages/docs/ru/programmable/cli/inspecting.md create mode 100644 packages/docs/ru/programmable/cli/scripting.md create mode 100644 packages/docs/ru/programmable/collaboration.md create mode 100644 packages/docs/ru/programmable/index.md create mode 100644 packages/docs/ru/programmable/jsx-renderer.md create mode 100644 packages/docs/ru/programmable/mcp-server.md create mode 100644 packages/docs/ru/reference/cli.md delete mode 100644 packages/docs/ru/reference/mcp-tools.md diff --git a/README.md b/README.md index 003e955d4..1b395cfac 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ Or download from the [releases page](https://github.com/open-pencil/open-pencil/ - **AI builds designs** — describe what you want in chat, 90 tools create and modify nodes. Bring your own API key - **Fully programmable** — headless CLI, Figma Plugin API via `eval`, MCP server for AI agents - **Real-time collaboration** — P2P via WebRTC, no server, no account. Cursors, presence, follow mode +- **Auto layout & CSS Grid** — flex and grid layout via Yoga WASM, with gap, padding, alignment, track sizing - **Tailwind CSS export** — export any selection as HTML with Tailwind v4 utility classes - **~7 MB desktop app** — Tauri v2 for macOS, Windows, Linux. Also runs in the browser as a PWA diff --git a/packages/docs/.vitepress/config.ts b/packages/docs/.vitepress/config.ts index 1bb9fd202..e947d27cc 100644 --- a/packages/docs/.vitepress/config.ts +++ b/packages/docs/.vitepress/config.ts @@ -25,8 +25,21 @@ interface SidebarLabels { figmaMatrix: string } +interface ProgrammableLabels { + cli: string + inspecting: string + exporting: string + analyzing: string + scripting: string + jsxRenderer: string + mcpServer: string + aiChat: string + collaboration: string +} + interface NavLabels { userGuide: string + programmable: string reference: string development: string openApp: string @@ -52,7 +65,6 @@ const userGuideSidebar = (prefix: string, l: SidebarLabels): DefaultTheme.Sideba text: l.organizing, items: [ { text: l.layers, link: `${prefix}/user-guide/layers-and-pages` }, - { text: l.contextMenu, link: `${prefix}/user-guide/context-menu` }, { text: l.exporting, link: `${prefix}/user-guide/exporting` }, ], }, @@ -66,6 +78,34 @@ const userGuideSidebar = (prefix: string, l: SidebarLabels): DefaultTheme.Sideba }, ] +const programmableSidebar = (prefix: string, p: ProgrammableLabels): DefaultTheme.SidebarItem[] => [ + { + text: p.aiChat, + link: `${prefix}/programmable/ai-chat`, + }, + { + text: p.collaboration, + link: `${prefix}/programmable/collaboration`, + }, + { + text: p.jsxRenderer, + link: `${prefix}/programmable/jsx-renderer`, + }, + { + text: p.cli, + items: [ + { text: p.inspecting, link: `${prefix}/programmable/cli/inspecting` }, + { text: p.exporting, link: `${prefix}/programmable/cli/exporting` }, + { text: p.analyzing, link: `${prefix}/programmable/cli/analyzing` }, + { text: p.scripting, link: `${prefix}/programmable/cli/scripting` }, + ], + }, + { + text: p.mcpServer, + link: `${prefix}/programmable/mcp-server`, + }, +] + const guideSidebar = (prefix: string, l: SidebarLabels): DefaultTheme.SidebarItem[] => [ { text: l.guide, @@ -80,16 +120,16 @@ const guideSidebar = (prefix: string, l: SidebarLabels): DefaultTheme.SidebarIte }, ] -const referenceSidebar = (prefix: string, label: string): DefaultTheme.SidebarItem[] => [ +const referenceSidebar = (prefix: string, label: string, l: SidebarLabels): DefaultTheme.SidebarItem[] => [ { text: label, items: [ { text: 'Keyboard Shortcuts', link: `${prefix}/reference/keyboard-shortcuts` }, + { text: l.contextMenu, link: `${prefix}/user-guide/context-menu` }, + { text: 'CLI', link: `${prefix}/reference/cli` }, { 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` }, ], }, ] @@ -106,20 +146,31 @@ const developmentSidebar = (prefix: string, label: string): DefaultTheme.Sidebar }, ] +const EN_PROG: ProgrammableLabels = { cli: 'CLI', inspecting: 'Inspecting Files', exporting: 'Exporting', analyzing: 'Analyzing Designs', scripting: 'Scripting', jsxRenderer: 'JSX Renderer', mcpServer: 'MCP Server', aiChat: 'AI Chat', collaboration: 'Collaboration' } +const DE_PROG: ProgrammableLabels = { cli: 'CLI', inspecting: 'Dateien inspizieren', exporting: 'Exportieren', analyzing: 'Designs analysieren', scripting: 'Skripte', jsxRenderer: 'JSX-Renderer', mcpServer: 'MCP-Server', aiChat: 'KI-Chat', collaboration: 'Zusammenarbeit' } +const IT_PROG: ProgrammableLabels = { cli: 'CLI', inspecting: 'Ispezione file', exporting: 'Esportazione', analyzing: 'Analisi design', scripting: 'Scripting', jsxRenderer: 'Renderer JSX', mcpServer: 'Server MCP', aiChat: 'Chat IA', collaboration: 'Collaborazione' } +const FR_PROG: ProgrammableLabels = { cli: 'CLI', inspecting: 'Inspecter les fichiers', exporting: 'Exporter', analyzing: 'Analyser les designs', scripting: 'Scripts', jsxRenderer: 'Moteur JSX', mcpServer: 'Serveur MCP', aiChat: 'Chat IA', collaboration: 'Collaboration' } +const ES_PROG: ProgrammableLabels = { cli: 'CLI', inspecting: 'Inspeccionar archivos', exporting: 'Exportar', analyzing: 'Analizar diseños', scripting: 'Scripts', jsxRenderer: 'Renderizador JSX', mcpServer: 'Servidor MCP', aiChat: 'Chat IA', collaboration: 'Colaboración' } +const PL_PROG: ProgrammableLabels = { cli: 'CLI', inspecting: 'Inspekcja plików', exporting: 'Eksportowanie', analyzing: 'Analiza projektów', scripting: 'Skrypty', jsxRenderer: 'Renderer JSX', mcpServer: 'Serwer MCP', aiChat: 'Czat AI', collaboration: 'Współpraca' } +const RU_PROG: ProgrammableLabels = { cli: 'CLI', inspecting: 'Инспекция файлов', exporting: 'Экспорт', analyzing: 'Анализ дизайна', scripting: 'Скрипты', jsxRenderer: 'JSX-рендерер', mcpServer: 'MCP-сервер', aiChat: 'ИИ-чат', collaboration: 'Совместная работа' } + const localeThemeConfig = ( prefix: string, nav: NavLabels, sidebar: SidebarLabels, + prog: ProgrammableLabels, ): DefaultTheme.Config => ({ nav: [ { text: nav.userGuide, link: `${prefix}/user-guide/` }, + { text: nav.programmable, link: `${prefix}/programmable/` }, { 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}/reference/`]: referenceSidebar(prefix, nav.reference), + [`${prefix}/programmable/`]: programmableSidebar(prefix, prog), + [`${prefix}/reference/`]: referenceSidebar(prefix, nav.reference, sidebar), [`${prefix}/`]: [ ...guideSidebar(prefix, sidebar), ...developmentSidebar(prefix, nav.development), @@ -251,37 +302,37 @@ export default defineConfig({ label: 'Deutsch', lang: 'de', description: 'Open-Source, KI-nativer Design-Editor. Figma-Alternative.', - themeConfig: localeThemeConfig('/de', { userGuide: 'Benutzerhandbuch', reference: 'Referenz', development: 'Entwicklung', openApp: 'App öffnen' }, DE), + themeConfig: localeThemeConfig('/de', { userGuide: 'Benutzerhandbuch', programmable: 'KI & Automatisierung', reference: 'Referenz', development: 'Entwicklung', openApp: 'App öffnen' }, DE, DE_PROG), }, it: { label: 'Italiano', lang: 'it', description: 'Editor di design open-source, IA-nativo. Alternativa a Figma.', - themeConfig: localeThemeConfig('/it', { userGuide: 'Guida utente', reference: 'Riferimento', development: 'Sviluppo', openApp: 'Apri app' }, IT), + themeConfig: localeThemeConfig('/it', { userGuide: 'Guida utente', programmable: 'IA & Automazione', reference: 'Riferimento', development: 'Sviluppo', openApp: 'Apri app' }, IT, IT_PROG), }, fr: { label: 'Français', lang: 'fr', description: 'Éditeur de design open-source, IA-natif. Alternative à Figma.', - themeConfig: localeThemeConfig('/fr', { userGuide: 'Guide utilisateur', reference: 'Référence', development: 'Développement', openApp: "Ouvrir l'app" }, FR), + themeConfig: localeThemeConfig('/fr', { userGuide: 'Guide utilisateur', programmable: 'IA & Automatisation', reference: 'Référence', development: 'Développement', openApp: "Ouvrir l'app" }, FR, FR_PROG), }, es: { label: 'Español', lang: 'es', description: 'Editor de diseño open-source, IA-nativo. Alternativa a Figma.', - themeConfig: localeThemeConfig('/es', { userGuide: 'Guía del usuario', reference: 'Referencia', development: 'Desarrollo', openApp: 'Abrir app' }, ES), + themeConfig: localeThemeConfig('/es', { userGuide: 'Guía del usuario', programmable: 'IA & Automatización', reference: 'Referencia', development: 'Desarrollo', openApp: 'Abrir app' }, ES, ES_PROG), }, pl: { label: 'Polski', lang: 'pl', description: "Open-source'owy edytor graficzny z natywnym AI. Alternatywa dla Figmy.", - themeConfig: localeThemeConfig('/pl', { userGuide: 'Podręcznik', reference: 'Referencja', development: 'Rozwój', openApp: 'Otwórz app' }, PL), + themeConfig: localeThemeConfig('/pl', { userGuide: 'Podręcznik', programmable: 'AI i automatyzacja', reference: 'Referencja', development: 'Rozwój', openApp: 'Otwórz app' }, PL, PL_PROG), }, ru: { label: 'Русский', lang: 'ru', description: 'Дизайн-редактор с открытым исходным кодом. Альтернатива Figma с встроенным ИИ.', - themeConfig: localeThemeConfig('/ru', { userGuide: 'Руководство', reference: 'Справочник', development: 'Разработка', openApp: 'Открыть приложение' }, RU), + themeConfig: localeThemeConfig('/ru', { userGuide: 'Руководство', programmable: 'ИИ и автоматизация', reference: 'Справочник', development: 'Разработка', openApp: 'Открыть приложение' }, RU, RU_PROG), }, }, @@ -290,6 +341,7 @@ export default defineConfig({ nav: [ { text: 'User Guide', link: '/user-guide/' }, + { text: 'AI & Automation', link: '/programmable/' }, { text: 'Reference', link: '/reference/keyboard-shortcuts' }, { text: 'Development', link: '/development/contributing' }, { text: 'Open App', link: 'https://app.openpencil.dev' }, @@ -297,19 +349,8 @@ export default defineConfig({ sidebar: { '/user-guide/': userGuideSidebar('', EN), - '/reference/': [ - { - text: 'Reference', - items: [ - { text: 'Keyboard Shortcuts', link: '/reference/keyboard-shortcuts' }, - { text: 'Node Types', link: '/reference/node-types' }, - { text: 'MCP Tools', link: '/reference/mcp-tools' }, - { text: 'Scene Graph', link: '/reference/scene-graph' }, - { text: 'File Format', link: '/reference/file-format' }, - { text: 'Eval Command', link: '/eval-command' }, - ], - }, - ], + '/programmable/': programmableSidebar('', EN_PROG), + '/reference/': referenceSidebar('', 'Reference', EN), '/': [ ...guideSidebar('', EN), { diff --git a/packages/docs/de/development/roadmap.md b/packages/docs/de/development/roadmap.md index 5086e8792..a8f28b1d2 100644 --- a/packages/docs/de/development/roadmap.md +++ b/packages/docs/de/development/roadmap.md @@ -4,7 +4,7 @@ ### Phase 1: Core-Engine ✅ -SceneGraph, Skia-Rendering, Grundformen, Auswahl, Zoom/Pan, Rückgängig/Wiederherstellen, Fanglinien. +`SceneGraph`, Skia-Rendering, Grundformen, Auswahl, Zoom/Pan, Rückgängig/Wiederherstellen, Fanglinien. ### Phase 2: Editor-UI + Layout ✅ @@ -16,7 +16,7 @@ Vue 3 + Reka UI Panels, Eigenschaften, Ebenen, Werkzeugleiste, Yoga Auto-Layout, ### Phase 4: Komponenten + Variablen ✅ -Komponenten, Instanzen, Overrides, Komponenten-Sets, Variablen (COLOR/FLOAT/STRING/BOOLEAN), Sammlungen, Modi, Bildexport, Kontextmenü, Rich-Text-Formatierung. +Komponenten, Instanzen, Overrides, Komponenten-Sets, Variablen (`COLOR`/FLOAT/STRING/BOOLEAN), Sammlungen, Modi, Bildexport, Kontextmenü, Rich-Text-Formatierung. ### Phase 5: KI-Integration & Werkzeuge ✅ @@ -24,7 +24,7 @@ Komponenten, Instanzen, Overrides, Komponenten-Sets, Variablen (COLOR/FLOAT/STRI - @open-pencil/core extrahiert in packages/core/ (keine DOM-Abhängigkeiten) - @open-pencil/cli mit headless .fig-Operationen (info, tree, find, export, analyze, node, pages, variables, eval) - `eval`-Befehl mit Figma-kompatibler Plugin API für Headless-Skripting -- KI-Chat: OpenRouter-Direktverbindung, 87 Werkzeuge in `packages/core/src/tools/`, Modellauswahl, ⌘J +- KI-Chat: OpenRouter-Direktverbindung, 87 Werkzeuge in `packages/core/src/tools/`, Modellauswahl, ⌘J - 49 zusätzliche KI/MCP-Werkzeuge portiert von figma-use (75 gesamt) - MCP-Server (@open-pencil/mcp): stdio + HTTP, 87 Core-Tools + 3 Dateiverwaltungs-Tools - Vereinheitlichte Werkzeugdefinitionen: einmal in `packages/core/src/tools/` definieren, für KI-Chat (valibot), MCP (zod), CLI (eval) adaptieren @@ -46,7 +46,7 @@ Komponenten, Instanzen, Overrides, Komponenten-Sets, Variablen (COLOR/FLOAT/STRI - Folgemodus: Klick auf Peer-Avatar zum Viewport-Folgen - Lokale Persistenz über y-indexeddb - Effekt-Rendering: Schlagschatten, innerer Schatten, Ebenen-/Hintergrund-/Vordergrund-Unschärfe -- Multi-Datei-Tabs: ⌘N/⌘T neuer Tab, ⌘W schließen, ⌘O öffnen +- Multi-Datei-Tabs: ⌘N/⌘T neuer Tab, ⌘W schließen, ⌘O öffnen - Apple Code-Signierung und Notarisierung für macOS - Linux-Builds (x64) in CI hinzugefügt - VitePress-Dokumentationsseite mit i18n (6 Sprachen) @@ -55,7 +55,7 @@ Komponenten, Instanzen, Overrides, Komponenten-Sets, Variablen (COLOR/FLOAT/STRI - Prototyping (Frame-Verbindungen, Übergänge, Animationen) - Kommentare (Pin, Threads, Auflösen) - PWA-Unterstützung -- Varianten-Switching, FLOAT/STRING/BOOLEAN Variable UI, variablengesteuertes Theming +- Varianten-Switching, `FLOAT`/STRING/BOOLEAN Variable UI, variablengesteuertes Theming ## Zeitplan diff --git a/packages/docs/de/eval-command.md b/packages/docs/de/eval-command.md deleted file mode 100644 index 5c4ef3d70..000000000 --- a/packages/docs/de/eval-command.md +++ /dev/null @@ -1,140 +0,0 @@ -# `open-pencil eval` — Figma-ähnliche Plugin-API für Headless-Skripting - -## Übersicht - -`bun open-pencil eval --code ''` führt JavaScript gegen eine `.fig`-Datei mit einem Figma-kompatiblen `figma`-Globalobjekt aus. Dies ermöglicht Headless-Skripting, Batch-Operationen, KI-Werkzeug-Ausführung und Tests — alles ohne die GUI. - -Das `figma`-Objekt spiegelt Figmas Plugin-API-Oberfläche so nah wie möglich, sodass vorhandenes Figma-Plugin-Wissen und Code-Snippets direkt übertragbar sind. - -```bash -# Frame erstellen, Auto-Layout setzen, Kinder hinzufügen -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 } -' - -# Knoten abfragen -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 })) -' - -# Von stdin lesen (für mehrzeilige Skripte / Piping) -cat transform.js | bun open-pencil eval design.fig --stdin - -# Änderungen zurückschreiben -bun open-pencil eval design.fig --code '...' --write -bun open-pencil eval design.fig --code '...' -o modified.fig -``` - -## Architektur - -``` -┌──────────────────────────────────────────────────────┐ -│ CLI: `open-pencil eval --code '...'` │ -│ ↓ │ -│ loadDocument(file) → SceneGraph │ -│ ↓ │ -│ FigmaAPI(sceneGraph) → `figma` Proxy-Objekt │ -│ ↓ │ -│ AsyncFunction('figma', wrappedCode)(figmaProxy) │ -│ ↓ │ -│ Ergebnis als JSON / agentfmt ausgeben │ -│ optional: saveDocument(file) bei --write │ -└──────────────────────────────────────────────────────┘ -``` - -### Schlüsselklassen - -| Klasse | Ort | Rolle | -|--------|-----|-------| -| `FigmaAPI` | `packages/core/src/figma-api.ts` | Proxy-Objekt, das `figma.*`-Methoden gegen `SceneGraph` implementiert | -| `FigmaNode` | `packages/core/src/figma-api.ts` | Proxy, der `SceneNode` mit Figma-ähnlichem Eigenschaftszugriff umhüllt | -| `eval`-Befehl | `packages/cli/src/commands/eval.ts` | CLI-Befehl: Dokument laden, API erstellen, Code ausführen | - -### Warum in `@open-pencil/core`? - -Die `FigmaAPI`-Klasse lebt in core (nicht CLI), weil: -- **KI-Werkzeuge nutzen sie wieder** — das Chat-Panels `render`-Werkzeug kann JSX über dieselbe API ausführen -- **Testskripte** — Unit-Tests können die API für Fixture-Setup verwenden -- **Keine DOM-Abhängigkeiten** — läuft headless in Bun - -## CLI-Befehl - -``` -bun open-pencil eval [optionen] - -Argumente: - file .fig-Datei zum Bearbeiten - -Optionen: - --code, -c Auszuführender JavaScript-Code (hat Zugriff auf `figma`-Global) - --stdin Code von stdin statt --code lesen - --write, -w Änderungen in die Eingabedatei zurückschreiben - -o, --output In eine andere Datei schreiben - --json Ergebnis als JSON ausgeben (Standard für Nicht-TTY) - --quiet, -q Ausgabe unterdrücken, nur Datei schreiben -``` - -### Ausführungsmodell - -1. `.fig` laden → `SceneGraph` -2. `FigmaAPI(graph)` erstellen → `figma`-Proxy -3. Benutzercode in async-Funktion verpacken: `return (async () => { })()` -4. Mit `figma` als einzigem Argument ausführen -5. Rückgabewert ausgeben (JSON oder agentfmt) -6. Bei `--write` oder `-o`: `SceneGraph` zurück in `.fig` serialisieren - -### Rückgabewert-Formatierung - -- `undefined` / `void` → keine Ausgabe -- Primitive → direkt ausgeben -- Objekte/Arrays → `JSON.stringify(result, null, 2)` oder agentfmt-Tabellen -- `FigmaNode` → serialisiert als `{ id, type, name, x, y, width, height, fills, ... }` -- Arrays von `FigmaNode` → als Liste serialisiert - -## `FigmaAPI` — Phasenweise Implementierung - -Die vollständige API-Referenz mit Phasen (Core, Komponenten, Variablen, Stile) und Eigenschafts-Mapping finden Sie in der [englischen Version](/eval-command). - -### Phase 1: Core - -Deckt ~80% realer Plugin-Skripte ab. Enthält: Dokument & Seite, Knotenerstellung, Knoteneigenschaften, Baumoperationen, Auto-Layout, Text, Kontur und Export. - -### Phase 2: Komponenten & Instanzen - -`figma.createComponent()`, `combineAsVariants()`, `createInstance()`, `detachInstance()`, `mainComponent`. - -### Phase 3: Variablen - -`figma.variables.getLocalVariables()`, `createVariable()`, `createVariableCollection()`, `setBoundVariable()`. - -### Phase 4: Stile & Erweitert - -Paint/Text/Effekt-Stile, Boolesche Operationen, JSX-Renderer. - -## Gemeinsam mit KI-Werkzeugen - -Die `FigmaAPI`-Klasse ist **dieselbe API-Oberfläche**, die KI-Werkzeuge verwenden. Dies stellt sicher, dass CLI-Skripte und KI-Werkzeuge identisch funktionieren. - -## Dateilayout - -``` -packages/core/src/ - figma-api.ts # FigmaAPI-Klasse + FigmaNode-Proxy -packages/cli/src/commands/ - eval.ts # CLI-Befehl -``` diff --git a/packages/docs/de/guide/architecture.md b/packages/docs/de/guide/architecture.md index b0ed27a9b..9883cf7ea 100644 --- a/packages/docs/de/guide/architecture.md +++ b/packages/docs/de/guide/architecture.md @@ -2,7 +2,7 @@ ## Systemübersicht -```mermaid +`mermaid graph TB subgraph Tauri["Tauri v2 Shell"] subgraph Editor["Editor (Web)"] @@ -22,7 +22,7 @@ graph TB MCP["MCP Server (90 tools, stdio+HTTP)"] Collab["P2P Collab (Trystero + Yjs)"] end -``` +` ## Editor-Layout @@ -62,7 +62,7 @@ Metas Yoga bietet CSS-Flexbox-Layout-Berechnung. Ein dünner Adapter mappt Figma ### Dateiformat (Kiwi-Binär) -Verwendet Figmas Kiwi-Binär-Codec mit 194 Message-/Enum-/Struct-Definitionen. Import: Header parsen → Zstd-Dekompression → Kiwi-Dekodierung → NodeChange[] → Szenengraph. Export kehrt den Prozess um, inklusive Thumbnail-Generierung. +Verwendet Figmas Kiwi-Binär-Codec mit 194 Message-/Enum-/Struct-Definitionen. Import: Header parsen → Zstd-Dekompression → Kiwi-Dekodierung → `NodeChange`[] → Szenengraph. Export kehrt den Prozess um, inklusive Thumbnail-Generierung. Siehe [Dateiformat-Referenz](/reference/file-format) für Details. @@ -108,7 +108,7 @@ Frame-zu-Frame-Übergänge, Interaktions-Trigger (Klick, Hover, Ziehen), Overlay ### CSS Grid Layout -Yoga WASM unterstützt derzeit nur Flexbox. CSS Grid ist upstream in [facebook/yoga#1893](https://github.com/facebook/yoga/pull/1893). OpenPencil wird es übernehmen, sobald das Yoga-Release erscheint. +CSS Grid wird über einen [Yoga-Fork](https://github.com/open-pencil/yoga/tree/grid) mit Cherry-Picked Grid-PRs aus dem Upstream unterstützt. Wählen Sie einen Frame aus und klicken Sie auf das Grid-Symbol, um von Flex zu Grid zu wechseln. Konfigurieren Sie Spalten-/Zeilen-Tracks (fr, feste px, auto), Spalten- und Zeilenabstände und Padding pro Seite. ### Windows Code Signing diff --git a/packages/docs/de/guide/features.md b/packages/docs/de/guide/features.md index 5422aec6c..a8491aeef 100644 --- a/packages/docs/de/guide/features.md +++ b/packages/docs/de/guide/features.md @@ -87,7 +87,7 @@ bun add -g @open-pencil/mcp } ``` -Siehe [MCP-Tools-Referenz](/reference/mcp-tools) für die vollständige Werkzeugliste. +Siehe [MCP-Tools-Referenz](/programmable/mcp-server) für die vollständige Werkzeugliste. ## CLI diff --git a/packages/docs/de/guide/figma-comparison.md b/packages/docs/de/guide/figma-comparison.md index e08975a8f..af6edaf7c 100644 --- a/packages/docs/de/guide/figma-comparison.md +++ b/packages/docs/de/guide/figma-comparison.md @@ -16,7 +16,7 @@ Feature-für-Feature-Vergleich der Figma-Design-Funktionen mit dem aktuellen Imp | Ebenen-Panel (linke Seitenleiste) | ✅ | Baumansicht mit Auf-/Zuklappen, Drag-Neuordnung, Sichtbarkeits-Toggle; skalierbare Breite | | Seiten-Panel | ✅ | Seiten hinzufügen, löschen, umbenennen; Viewport-Zustand pro Seite | | Eigenschafts-Panel (rechte Seitenleiste) | ✅ | Abschnitte: Darstellung, Füllung, Kontur, Effekte, Typografie, Layout, Position; skalierbare Breite | -| Zoom & Schwenken | ✅ | Strg+Scroll, Pinch, ⌘+/⌘−/⌘0, Leertaste+Ziehen, mittlere Maustaste, Hand-Werkzeug (H) | +| Zoom & Schwenken | ✅ | Strg+Scroll, Pinch, ⌘+ / ⌘− / ⌘0, Leertaste+Ziehen, mittlere Maustaste, Hand-Werkzeug (H) | | Canvas-Lineale | ✅ | Oben/links Lineale mit Auswahl-Bändern und Koordinaten-Badges | | Canvas-Hintergrundfarbe | ✅ | Pro-Seite-Hintergrund über Eigenschafts-Panel | | Canvas-Hilfslinien | 🔲 | Figma unterstützt ziehbare Hilfslinien von Linealen | @@ -36,7 +36,7 @@ Feature-für-Feature-Vergleich der Figma-Design-Funktionen mit dem aktuellen Imp |----------|--------|-------------| | Formwerkzeuge (Rechteck, Ellipse, Linie, Polygon, Stern) | ✅ | Alle Grundformtypen; Polygonseitenzahl und Stern-Innenradius konfigurierbar | | Frames | ✅ | Inhalt beschneiden, unabhängiges Koordinatensystem | -| Gruppen | ✅ | ⌘G zum Gruppieren, ⇧⌘G zum Entgruppieren | +| Gruppen | ✅ | ⌘G zum Gruppieren, ⇧⌘G zum Entgruppieren | | Sektionen | ✅ | Titel-Pills, automatische Übernahme überlappender Knoten, luminanzadaptiver Text | | Bogen-Werkzeug (Bögen, Halbkreise, Ringe) | ✅ | arcData mit Start-/Endwinkel und Innenradius | | Bleistift (Freihand-Werkzeug) | 🔲 | Figmas Freihand-Zeichenwerkzeug | @@ -46,9 +46,9 @@ Feature-für-Feature-Vergleich der Figma-Design-Funktionen mit dem aktuellen Imp | Ausrichtung & Position | ✅ | Position, Drehung, Abmessungen im Panel | | Objekte kopieren & einfügen | ✅ | Standard-Zwischenablage + Figma-Kiwi-Binärformat | | Ebenen proportional skalieren | 🟡 | Umschalt-Resize hält Proportionen; kein dediziertes Scale-Werkzeug (K) | -| Ebenen sperren/entsperren | ✅ | ⇧⌘L schaltet Sperre um | -| Ebenensichtbarkeit umschalten | ✅ | Augen-Icon im Panel + ⇧⌘H-Kürzel | -| Ebenen umbenennen | ✅ | Doppelklick-Inline-Umbenennen; Enter/Escape/Blur zum Bestätigen | +| Ebenen sperren/entsperren | ✅ | ⇧⌘L schaltet Sperre um | +| Ebenensichtbarkeit umschalten | ✅ | Augen-Icon im Panel + ⇧⌘H-Kürzel | +| Ebenen umbenennen | ✅ | Doppelklick-Inline-Umbenennen; Enter/Escape/Blur zum Bestätigen | | Nach vorne / Nach hinten | ✅ | ] und [ Tastaturkürzel; auch im Kontextmenü | | Auf Seite verschieben | ✅ | Knoten zwischen Seiten verschieben via Kontextmenü | | Einschränkungen (responsives Resize) | 🔲 | Kanten/Mitte fixieren für Eltern-Resize-Verhalten | @@ -79,7 +79,7 @@ Feature-für-Feature-Vergleich der Figma-Design-Funktionen mit dem aktuellen Imp | Funktion | Status | Anmerkungen | |----------|--------|-------------| -| Textwerkzeug & Inline-Bearbeitung | ✅ | Canvas-native Bearbeitung, Phantom-Textarea, Style-Runs (⌘B/I/U, S-Button) | +| Textwerkzeug & Inline-Bearbeitung | ✅ | Canvas-native Bearbeitung, Phantom-Textarea, Style-Runs (⌘B / I / U, S-Button) | | Textrendering (Paragraph API) | ✅ | CanvasKit Paragraph für Formgebung, Zeilenumbrüche, Metriken | | Schriftladung (Systemschriften) | ✅ | Inter Standard, font-kit in Tauri mit OnceLock-Cache, queryLocalFonts im Browser | | Schriftfamilie & -stärke | ✅ | FontPicker mit virtuellem Scrollen, Suche, CSS-Vorschau | @@ -126,7 +126,7 @@ Feature-für-Feature-Vergleich der Figma-Design-Funktionen mit dem aktuellen Imp | Hintergrund-Unschärfe | ✅ | Inhalt hinter der Ebene unscharf | | Vordergrund-Unschärfe | ✅ | Unschärfe im Vordergrund | | Konturstärke | ✅ | Konfigurierbar im Eigenschafts-Panel | -| Kontur-Endung (Rund, Quadrat, Pfeil) | ✅ | NONE, ROUND, SQUARE, ARROW_LINES, ARROW_EQUILATERAL | +| Kontur-Endung (Rund, Quadrat, Pfeil) | ✅ | `NONE`, `ROUND`, `SQUARE`, `ARROW_LINES`, `ARROW_EQUILATERAL` | | Kontur-Verbindung (Gehrung, Abschrägung, Rund) | ✅ | Alle drei Verbindungstypen | | Strichmuster | ✅ | Strich-An/Strich-Aus-Muster | | Eckenradius | ✅ | Einheitlicher und pro-Ecke-Radius mit unabhängigem Toggle | @@ -138,14 +138,14 @@ Feature-für-Feature-Vergleich der Figma-Design-Funktionen mit dem aktuellen Imp | Funktion | Status | Anmerkungen | |----------|--------|-------------| | Horizontaler & vertikaler Fluss | ✅ | Yoga-WASM-Flexbox-Engine | -| Auto Layout umschalten (⇧A) | ✅ | Auf Frame umschalten oder Auswahl umhüllen | +| Auto Layout umschalten (⇧A) | ✅ | Auf Frame umschalten oder Auswahl umhüllen | | Gap (Abstand zwischen Kindern) | ✅ | Konfigurierbar im Panel | | Padding (einheitlich & pro Seite) | ✅ | Alle vier Seiten unabhängig | -| Justify Content | ✅ | Start, Center, End, Space-Between | -| Align Items | ✅ | Start, Center, End, Stretch | +| Justify Content | ✅ | Start, Center, End, Space-Between | +| Align Items | ✅ | Start, Center, End, Stretch | | Kindgröße (fix, füllen, anpassen) | ✅ | Größenmodi pro Kind | | Wrap | ✅ | Flex-Wrap für mehrzeiliges Layout | -| Grid-Auto-Layout-Fluss | 🔲 | Figmas rasterbasiertes Auto-Layout | +| Grid-Auto-Layout-Fluss | ✅ | CSS Grid über Yoga-Fork — Spalten-/Zeilen-Tracks, Gaps, Spans | | Kombinierte Flüsse (verschachtelt) | ✅ | Verschachtelte Auto-Layout-Frames mit verschiedenen Richtungen | | Drag-Neuordnung in Auto Layout | ✅ | Visueller Einfügeindikator | | Min/Max Breite und Höhe | 🔲 | Figma unterstützt Min/Max-Einschränkungen | @@ -154,17 +154,17 @@ Feature-für-Feature-Vergleich der Figma-Design-Funktionen mit dem aktuellen Imp | Funktion | Status | Anmerkungen | |----------|--------|-------------| -| Komponenten erstellen | 🟡 | ⌥⌘K erstellt aus Frame/Gruppe; noch kein Komponenten-Eigenschafts-UI | -| Komponenten-Sets | 🟡 | ⇧⌘K kombiniert Komponenten; gestrichelter violetter Rand; keine Varianten-Eigenschaftsbearbeitung | +| Komponenten erstellen | 🟡 | ⌥⌘K erstellt aus Frame/Gruppe; noch kein Komponenten-Eigenschafts-UI | +| Komponenten-Sets | 🟡 | ⇧⌘K kombiniert Komponenten; gestrichelter violetter Rand; keine Varianten-Eigenschaftsbearbeitung | | Komponenteninstanzen | 🟡 | Instanz aus Kontextmenü erstellen; Live-Sync; kein Override-Bearbeitungs-UI | | Varianten | 🔲 | Variantenwechsel und eigenschaftsbasierte Auswahl | | Komponenteneigenschaften | 🔲 | Boolesche, Text-, Instanztausch-Eigenschaften | | Override-Propagation | ✅ | Änderungen an Hauptkomponente werden propagiert; Overrides erhalten | -| Variablen (Farbe, Zahl, String, Boolean) | 🟡 | COLOR mit vollem UI; FLOAT/STRING/BOOLEAN definiert ohne Bearbeitungs-UI | +| Variablen (Farbe, Zahl, String, Boolean) | 🟡 | `COLOR` mit vollem UI; `FLOAT`/STRING/BOOLEAN definiert ohne Bearbeitungs-UI | | Variablensammlungen & Modi | 🟡 | Sammlungen, Modi, activeMode-Wechsel funktionieren; kein Variablen-Theming-UI | | Stile (Farbe, Text, Effekt, Layout) | 🔲 | Wiederverwendbare benannte Stil-Presets | | Bibliotheken (veröffentlichen, teilen, aktualisieren) | 🔲 | Geteilte Komponenten-/Stil-Bibliotheken | -| Instanz ablösen | ✅ | ⌥⌘B wandelt Instanz in Frame um | +| Instanz ablösen | ✅ | ⌥⌘B wandelt Instanz in Frame um | | Zur Hauptkomponente navigieren | ✅ | Zur Quellkomponente navigieren, seitenübergreifend | ## Prototyping @@ -187,9 +187,9 @@ Feature-für-Feature-Vergleich der Figma-Design-Funktionen mit dem aktuellen Imp | Funktion | Status | Anmerkungen | |----------|--------|-------------| -| .fig-Datei-Import | ✅ | Vollständiger Kiwi-Codec: 194 Definitionen, ~390 Felder pro NodeChange | +| .fig-Datei-Import | ✅ | Vollständiger Kiwi-Codec: 194 Definitionen, ~390 Felder pro `NodeChange` | | .fig-Datei-Export | ✅ | Kiwi-Encoding + Zstd-Kompression + Miniatur-Generierung | -| Speichern / Speichern unter | ✅ | ⌘S / ⇧⌘S; native Dialoge (Tauri), File System Access API (Chrome/Edge), Download-Fallback (Safari) | +| Speichern / Speichern unter | ✅ | ⌘S / ⇧⌘S; native Dialoge (Tauri), File System Access API (Chrome/Edge), Download-Fallback (Safari) | | Figma-Zwischenablage (Einfügen) | ✅ | Kiwi-Binär aus Figma-Zwischenablage dekodieren | | Figma-Zwischenablage (Kopieren) | ✅ | Kiwi-Binär kodieren, das Figma lesen kann | | Sketch-Datei-Import | 🔲 | .sketch-Datei-Parsing | @@ -211,7 +211,7 @@ Feature-für-Feature-Vergleich der Figma-Design-Funktionen mit dem aktuellen Imp | Echtzeit-Multiplayer | ✅ | P2P via Trystero + Yjs CRDT, Cursor, Folgemodus; kein Server | | Cursor-Chat | 🔲 | Inline-Chat-Blasen am Cursor | | Branching & Merging | 🔲 | Versions-Branches für Design-Dateien | -| Entwicklermodus (Inspizieren) | 🟡 | Code-Tab zeigt JSX; keine CSS-Eigenschaften oder Handoff-Specs | +| Entwicklermodus (Inspizieren) | 🟡 | Code-Tab zeigt JSX; keine CSS-Eigenschaften oder Handoff-Specs | | Code Connect | 🔲 | Design-Komponenten mit Code verknüpfen | | Code-Snippets | 🟡 | JSX-Export mit Hervorhebung und Kopieren; keine CSS/Swift/Kotlin-Snippets | | Figma für VS Code | 🔲 | Editor-Plugin-Integration | diff --git a/packages/docs/de/guide/tech-stack.md b/packages/docs/de/guide/tech-stack.md index 164d63ee4..1ead8b31c 100644 --- a/packages/docs/de/guide/tech-stack.md +++ b/packages/docs/de/guide/tech-stack.md @@ -60,4 +60,4 @@ Yoga wird von Meta gepflegt, ist auf Milliarden von React-Native-Geräten getest | Technologie | Zweck | Phase | |-----------|---------|-------| -| CSS Grid in Yoga | Grid-basiertes Auto-Layout | Blockiert durch Upstream (facebook/yoga#1893) | +| CSS Grid in Yoga | Grid-basiertes Auto-Layout | ✅ Unterstützt über [Yoga-Fork](https://github.com/open-pencil/yoga/tree/grid) | diff --git a/packages/docs/de/programmable/ai-chat.md b/packages/docs/de/programmable/ai-chat.md new file mode 100644 index 000000000..bad21c464 --- /dev/null +++ b/packages/docs/de/programmable/ai-chat.md @@ -0,0 +1,47 @@ +--- +title: KI-Chat +description: Integrierter KI-Assistent mit 87 Werkzeugen zum Erstellen und Bearbeiten von Designs. +--- + +# KI-Chat + +Drücke ⌘J (Ctrl + J), um den KI-Assistenten zu öffnen. Beschreibe, was du möchtest — er erstellt Formen, setzt Stile, verwaltet Layout, arbeitet mit Komponenten und analysiert dein Design. + +## Einrichtung + +1. Öffne das KI-Chat-Panel (⌘J) +2. Klicke auf das Einstellungssymbol +3. Gib deinen OpenRouter API-Schlüssel ein +4. Wähle ein Modell (Claude, GPT-4, Gemini, etc.) + +Kein Backend, kein Abonnement — dein Schlüssel kommuniziert direkt mit OpenRouter. + +## Was er kann + +Der Assistent hat 87 Werkzeuge in diesen Kategorien: + +- **Erstellen** — Frames, Formen, Text, Komponenten, Seiten. Rendert JSX für komplexe Layouts. +- **Gestalten** — Füllungen, Konturen, Effekte, Deckkraft, Eckenradius, Mischmodi. +- **Layout** — Auto-Layout, Ausrichtung, Abstände, Größenanpassung. +- **Komponenten** — Komponenten, Instanzen, Komponentensets erstellen. Überschreibungen verwalten. +- **Variablen** — Variablen, Sammlungen, Modi erstellen/bearbeiten. An Füllungen binden. +- **Abfragen** — Knoten finden, Eigenschaften lesen, Seiten, Schriften, Auswahl auflisten. +- **Analysieren** — Farbpalette, Typografie-Audit, Abstandskonsistenz, Cluster-Erkennung. +- **Exportieren** — PNG, SVG, JSX mit Tailwind-Klassen. +- **Vektor** — Boolesche Operationen, Pfadbearbeitung. + +## Beispiel-Prompts + +- „Erstelle eine Karte mit Titel, Beschreibung und einem blauen Button" +- „Gib allen Buttons auf dieser Seite den gleichen Eckenradius" +- „Welche Schriften werden in dieser Datei verwendet?" +- „Ändere den Hintergrund des ausgewählten Frames in einen Verlauf von Blau nach Lila" +- „Exportiere den ausgewählten Frame als SVG" +- „Finde alle Textknoten mit einer Schriftgröße kleiner als 12" + +## Tipps + +- Wähle Knoten aus, bevor du fragst — der Assistent weiß, was ausgewählt ist. +- Sei spezifisch bei Farben, Größen und Positionen für präzise Ergebnisse. +- Der Assistent kann mehrere Knoten in einer Nachricht bearbeiten. +- Verwende „Rückgängig" im Editor, wenn dir das Ergebnis nicht gefällt. diff --git a/packages/docs/de/programmable/cli/analyzing.md b/packages/docs/de/programmable/cli/analyzing.md new file mode 100644 index 000000000..e5952c4ed --- /dev/null +++ b/packages/docs/de/programmable/cli/analyzing.md @@ -0,0 +1,65 @@ +--- +title: Designs analysieren +description: Farben, Typografie, Abstände und wiederkehrende Muster in .fig-Dateien auditieren. +--- + +# Designs analysieren + +Die `analyze`-Befehle prüfen ein gesamtes Designsystem vom Terminal aus — Inkonsistenzen finden, die tatsächliche Palette extrahieren, Komponenten erkennen, die noch extrahiert werden sollten. + +## Farben + +```sh +open-pencil analyze colors design.fig +``` + +Findet jede Farbe in der Datei, zählt die Verwendung und zeigt ein visuelles Histogramm: + +``` +#1d1b20 ██████████████████████████████ 17155× +#49454f ██████████████████████████████ 9814× +#ffffff ██████████████████████████████ 8620× +#6750a4 ██████████████████████████████ 3967× +``` + +## Typografie + +```sh +open-pencil analyze typography design.fig +``` + +Listet jede Kombination aus Schriftfamilie, -größe und -gewicht mit Nutzungszahlen auf. Nützlich, um einmalige Textstile zu erkennen, die konsolidiert werden sollten. + +## Abstände + +```sh +open-pencil analyze spacing design.fig +``` + +Prüft Gap- und Padding-Werte über alle Auto-Layout-Frames hinweg. Hilft, Inkonsistenzen in der Abstandsskala zu identifizieren — z.B. ein einzelner `13px`-Gap zwischen ansonsten `8/16/24`-Werten. + +## Cluster + +```sh +open-pencil analyze clusters design.fig +``` + +Findet wiederkehrende Knotenmuster, die in Komponenten extrahiert werden könnten: + +``` +3771× frame "container" (100% match) + size: 40×40, structure: Frame > [Frame] + +2982× instance "Checkboxes" (100% match) + size: 48×48, structure: Instance > [Frame] +``` + +## JSON-Ausgabe + +Alle Analyse-Befehle unterstützen `--json` für maschinenlesbare Ausgabe: + +```sh +open-pencil analyze colors design.fig --json +``` + +Weiterleiten an `jq`, in CI-Prüfungen einspeisen oder in Skripten verwenden, die Design-Token-Budgets durchsetzen. diff --git a/packages/docs/de/programmable/cli/exporting.md b/packages/docs/de/programmable/cli/exporting.md new file mode 100644 index 000000000..6f9af3bb7 --- /dev/null +++ b/packages/docs/de/programmable/cli/exporting.md @@ -0,0 +1,59 @@ +--- +title: Exportieren +description: .fig-Dateien als PNG, JPG, WEBP, SVG oder JSX mit Tailwind-Klassen rendern. +--- + +# Exportieren + +Designs vom Terminal aus exportieren — Rasterbilder, Vektoren oder JSX-Code. + +## Bildexport + +```sh +open-pencil export design.fig # PNG (Standard) +open-pencil export design.fig -f jpg -s 2 -q 90 # JPG in 2×, Qualität 90 +open-pencil export design.fig -f webp -s 3 # WEBP in 3× +open-pencil export design.fig -f svg # SVG-Vektor +``` + +Optionen: + +- `-f` — Format: `png`, `jpg`, `webp`, `svg`, `jsx` +- `-s` — Skalierung: `1`–`4` +- `-q` — Qualität: `0`–`100` (nur JPG/WEBP) +- `-o` — Ausgabepfad +- `--page` — Seitenname +- `--node` — bestimmte Knoten-ID + +## JSX-Export + +Als JSX mit Tailwind-Utility-Klassen exportieren: + +```sh +open-pencil export design.fig -f jsx --style tailwind +``` + +Ausgabe: + +```html +
+

Card Title

+

Description text

+
+``` + +Unterstützt auch `--style openpencil` für das native JSX-Format (siehe [JSX-Renderer](../jsx-renderer)). + +## Vorschaubilder + +```sh +open-pencil export design.fig --thumbnail --width 1920 --height 1080 +``` + +## Live-App-Modus + +Lass die Datei weg, um aus der laufenden App zu exportieren: + +```sh +open-pencil export -f png # Screenshot der aktuellen Zeichenfläche +``` diff --git a/packages/docs/de/programmable/cli/inspecting.md b/packages/docs/de/programmable/cli/inspecting.md new file mode 100644 index 000000000..1adcfd525 --- /dev/null +++ b/packages/docs/de/programmable/cli/inspecting.md @@ -0,0 +1,98 @@ +--- +title: Dateien inspizieren +description: Knotenbäume durchsuchen, nach Name oder Typ suchen und Eigenschaften im Terminal untersuchen. +--- + +# Dateien inspizieren + +Das CLI ermöglicht es, `.fig`-Dateien zu erkunden, ohne den Editor zu öffnen. Jeder Befehl funktioniert auch mit der laufenden App — lass einfach das Dateiargument weg. + +::: tip Installation +```sh +bun add -g @open-pencil/cli +# oder +brew install open-pencil/tap/open-pencil +``` +::: + +## Dokumentinformationen + +Erhalte einen schnellen Überblick — Seitenanzahl, Gesamtknoten, verwendete Schriften, Dateigröße: + +```sh +open-pencil info design.fig +``` + +## Knotenbaum + +Gibt die vollständige Knotenhierarchie aus: + +```sh +open-pencil tree design.fig +``` + +``` +[0] [page] "Getting started" (0:46566) + [0] [section] "" (0:46567) + [0] [frame] "Body" (0:46568) + [0] [frame] "Introduction" (0:46569) + [0] [frame] "Introduction Card" (0:46570) + [0] [frame] "Guidance" (0:46571) +``` + +## Knoten finden + +Nach Typ suchen: + +```sh +open-pencil find design.fig --type TEXT +``` + +Nach Name suchen: + +```sh +open-pencil find design.fig --name "Button" +``` + +Beide Flags können kombiniert werden, um Ergebnisse weiter einzugrenzen. + +## Knotendetails + +Alle Eigenschaften eines bestimmten Knotens anhand seiner ID inspizieren: + +```sh +open-pencil node design.fig --id 1:23 +``` + +## Seiten + +Alle Seiten im Dokument auflisten: + +```sh +open-pencil pages design.fig +``` + +## Variablen + +Designvariablen und ihre Sammlungen auflisten: + +```sh +open-pencil variables design.fig +``` + +## Live-App-Modus + +Wenn die Desktop-App läuft, lass das Dateiargument weg — das CLI verbindet sich über RPC und arbeitet auf der Live-Zeichenfläche: + +```sh +open-pencil tree # das Live-Dokument inspizieren +open-pencil eval -c "..." # den Editor abfragen +``` + +## JSON-Ausgabe + +Alle Befehle unterstützen `--json` für maschinenlesbare Ausgabe — weiterleiten an `jq`, in CI-Skripte einspeisen oder mit anderen Werkzeugen verarbeiten: + +```sh +open-pencil tree design.fig --json | jq '.[] | .name' +``` diff --git a/packages/docs/de/programmable/cli/scripting.md b/packages/docs/de/programmable/cli/scripting.md new file mode 100644 index 000000000..2550c0162 --- /dev/null +++ b/packages/docs/de/programmable/cli/scripting.md @@ -0,0 +1,70 @@ +--- +title: Skripting +description: JavaScript mit der Figma Plugin API ausführen — Knoten abfragen, Designs im Stapel bearbeiten, Frames erstellen. +--- + +# Skripting + +`open-pencil eval` bietet dir die vollständige Figma Plugin API im Terminal. Knoten lesen, Eigenschaften ändern, Formen erstellen — und Änderungen zurück in die Datei schreiben. + +## Grundlegende Verwendung + +```sh +open-pencil eval design.fig -c "figma.currentPage.children.length" +``` + +Das `-c`-Flag nimmt JavaScript entgegen. Das `figma`-Global funktioniert wie die Figma Plugin API. + +## Knoten abfragen + +```sh +open-pencil eval design.fig -c " + figma.currentPage.findAll(n => n.type === 'FRAME' && n.name.includes('Button')) + .map(b => ({ id: b.id, name: b.name, w: b.width, h: b.height })) +" +``` + +## Bearbeiten und speichern + +```sh +open-pencil eval design.fig -c " + figma.currentPage.children.forEach(n => n.opacity = 0.5) +" -w +``` + +`-w` schreibt die Änderungen zurück in die Eingabedatei. Verwende `-o output.fig`, um stattdessen in eine andere Datei zu schreiben. + +## Von Stdin lesen + +Für längere Skripte: + +```sh +cat transform.js | open-pencil eval design.fig --stdin -w +``` + +## Live-App-Modus + +Lass die Datei weg, um gegen die laufende Desktop-App auszuführen: + +```sh +open-pencil eval -c "figma.currentPage.name" +``` + +## Verfügbare API + +Das `figma`-Objekt unterstützt: + +- `figma.currentPage` — die aktive Seite +- `figma.root` — das Dokumentwurzel-Element +- `figma.createFrame()`, `figma.createRectangle()`, `figma.createEllipse()`, `figma.createText()`, etc. +- `.findAll()`, `.findOne()` — Nachkommen durchsuchen +- `.appendChild()`, `.insertChild()` — Baummanipulation +- Alle Eigenschafts-Setter: `.fills`, `.strokes`, `.effects`, `.opacity`, `.cornerRadius`, `.layoutMode`, `.itemSpacing`, etc. + +Dies ist dieselbe API, die Figma-Plugins verwenden, sodass bestehendes Wissen und Code-Snippets direkt übertragbar sind. + +## JSON-Ausgabe + +```sh +open-pencil eval design.fig -c "..." --json +``` diff --git a/packages/docs/de/programmable/collaboration.md b/packages/docs/de/programmable/collaboration.md new file mode 100644 index 000000000..fcdb8a52a --- /dev/null +++ b/packages/docs/de/programmable/collaboration.md @@ -0,0 +1,38 @@ +--- +title: Zusammenarbeit +description: Echtzeit-Zusammenarbeit über P2P WebRTC — kein Server, kein Konto. +--- + +# Zusammenarbeit + +Bearbeite Designs gemeinsam in Echtzeit. Peers verbinden sich direkt — kein Server leitet deine Daten weiter, kein Konto erforderlich. + +## Einen Raum teilen + +1. Klicke auf den Teilen-Button in der oberen rechten Ecke +2. Kopiere den generierten Link (`app.openpencil.dev/share/`) +3. Sende ihn an deine Mitarbeiter + +Jeder mit dem Link kann beitreten. Der Raum bleibt aktiv, solange mindestens ein Teilnehmer die Seite geöffnet hat. + +## Was synchronisiert wird + +- **Dokumentänderungen** — jede Bearbeitung (Formen, Text, Eigenschaften, Layout) wird sofort synchronisiert +- **Cursor** — sieh, wo jeder Mitarbeiter zeigt, mit Name und Farbe +- **Auswahlen** — markierte Auswahlen sind für alle sichtbar + +## Folgemodus + +Klicke auf den Avatar eines Mitarbeiters in der oberen Leiste, um seinem Viewport zu folgen. Deine Zeichenfläche schwenkt und zoomt passend zu seiner Ansicht. Klicke erneut, um das Folgen zu beenden. + +## So funktioniert es + +Peers verbinden sich direkt über WebRTC — deine Designdaten gehen direkt von Browser zu Browser, nie über einen zentralen Server. Der Dokumentzustand verwendet einen CRDT (Conflict-free Replicated Data Type), sodass gleichzeitige Bearbeitungen automatisch ohne Konflikte zusammengeführt werden. + +Der Raum bleibt lokal bestehen — wenn du die Seite aktualisierst, trittst du mit dem gleichen Zustand wieder bei. + +## Tipps + +- Funktioniert im Browser und in der Desktop-App +- Raum-IDs sind kryptografisch zufällig — nur Personen mit dem Link können beitreten +- Veraltete Cursor werden automatisch bereinigt, wenn jemand die Verbindung trennt diff --git a/packages/docs/de/programmable/index.md b/packages/docs/de/programmable/index.md new file mode 100644 index 000000000..aab66641a --- /dev/null +++ b/packages/docs/de/programmable/index.md @@ -0,0 +1,51 @@ +--- +layout: doc +title: KI & Automatisierung +description: Jede Operation in OpenPencil ist skriptfähig — KI-Chat, CLI, JSX-Renderer, MCP-Server, Echtzeit-Zusammenarbeit. +--- + +# KI & Automatisierung + +OpenPencil behandelt Designdateien als Daten. Jede im Editor verfügbare Operation — Formen erstellen, Füllungen setzen, Auto-Layout verwalten, Assets exportieren — ist auch über das Terminal, über KI-Agenten und aus Code heraus verfügbar. Keine Plugins zu installieren, keine API-Schlüssel, keine Warteliste. + +Die Editor-Oberfläche und die Automatisierungsschnittstellen verwenden dieselbe Engine. Was du per Klick machen kannst, kannst du auch per Skript machen. + +## KI-Chat + +Der integrierte Assistent hat Zugriff auf 87 Werkzeuge, die die gesamte Oberfläche des Editors abdecken. Beschreibe in natürlicher Sprache, was du möchtest — „füge allen Buttons einen 16px Schlagschatten hinzu", „erstelle eine Kartenkomponente mit Dark-Mode-Variante", „exportiere jeden Frame auf dieser Seite in 2×". + +[KI-Chat →](./ai-chat) + +## Zusammenarbeit + +Echtzeit-Multiplayer-Bearbeitung über Peer-to-Peer WebRTC. Kein Server, kein Konto. Teile einen Raum-Link und bearbeite gemeinsam mit Live-Cursorn und Folgemodus. Der Dokumentzustand wird über CRDT synchronisiert, sodass Bearbeitungen auch bei instabilen Verbindungen automatisch zusammengeführt werden. + +[Zusammenarbeit →](./collaboration) + +## JSX-Renderer + +Beschreibe UI als JSX — die gleiche Syntax, die LLMs bereits von React kennen. Ein einziger Aufruf kann einen ganzen Komponentenbaum mit Frames, Text, Auto-Layout, Füllungen und Konturen erstellen. Kompakt, deklarativ und diff-fähig. + +In die andere Richtung kannst du jede Auswahl als JSX mit Tailwind-Klassen exportieren — nützlich für die Übergabe an die Entwicklung oder um Designs zurück in ein LLM einzuspeisen. + +[JSX-Renderer →](./jsx-renderer) + +## CLI + +`.fig`-Dateien inspizieren, exportieren und analysieren, ohne den Editor zu öffnen. Seiten auflisten, Knoten suchen, Design-Tokens extrahieren, als PNG rendern — alles vom Terminal aus mit maschinenlesbarer JSON-Ausgabe. + +Das CLI verbindet sich auch über RPC mit der laufenden Desktop-App, sodass du den Editor skripten kannst, während du ihn benutzt. + +[Dateien inspizieren](./cli/inspecting) · [Exportieren](./cli/exporting) · [Designs analysieren](./cli/analyzing) · [Skripting](./cli/scripting) + +## MCP-Server + +Verbinde Claude Code, Cursor, Windsurf oder jeden MCP-kompatiblen Client mit OpenPencil. Der Server stellt 90 Werkzeuge zum Lesen, Erstellen und Bearbeiten von Designs bereit — dieselben Werkzeuge, die der integrierte KI-Chat verwendet. Läuft über stdio oder HTTP mit Session-Unterstützung. + +[MCP-Server →](./mcp-server) + +## Warum offen? + +Figma ist eine geschlossene Plattform. Ihr MCP-Server ist schreibgeschützt. Der CDP-Browserzugang wurde in Version 126 abgeschafft. Designdateien liegen in einem proprietären Format auf fremden Servern. Plugin-Entwicklung erfordert eine eigene Laufzeitumgebung mit eingeschränkten APIs. + +OpenPencil ist die Alternative: Open Source, MIT-lizenziert, jede Operation skriptfähig, Daten lokal gespeichert. Deine Designdateien gehören dir — inspiziere sie, transformiere sie, leite sie in die CI weiter, speise sie in ein LLM ein. Keine Erlaubnis nötig. diff --git a/packages/docs/de/programmable/jsx-renderer.md b/packages/docs/de/programmable/jsx-renderer.md new file mode 100644 index 000000000..1aa1e5252 --- /dev/null +++ b/packages/docs/de/programmable/jsx-renderer.md @@ -0,0 +1,116 @@ +--- +title: JSX-Renderer +description: Designs mit JSX erstellen — die Syntax, die LLMs bereits von Millionen von React-Komponenten kennen. +--- + +# JSX-Renderer + +OpenPencil verwendet JSX als Sprache zur Designerstellung. LLMs haben Millionen von React-Komponenten gesehen — ein Layout als `` zu beschreiben ist natürlich, kein spezielles Training nötig. Jedes Token zählt, wenn ein KI-Agent Dutzende von Operationen durchführt, und JSX ist die kompakteste deklarative Darstellung. + +JSX ist auch diff-fähig. Wenn eine KI ein Design ändert, ist die Änderung ein JSX-Diff — lesbar, überprüfbar, versionierbar. + +## Designs erstellen + +Das `render`-Werkzeug (verfügbar im KI-Chat, MCP und CLI eval) akzeptiert JSX: + +```jsx + + Card Title + Description text + +``` + +Im MCP-Server und KI-Chat akzeptiert das `render`-Werkzeug JSX-Strings direkt. Im CLI verwendest du den `export`-Befehl für die umgekehrte Richtung — [Designs als JSX exportieren](./cli/exporting). + +## Elemente + +Alle Knotentypen sind als JSX-Elemente verfügbar: + +| Element | Erstellt | Aliasse | +|---------|----------|---------| +| `` | Frame (Container, unterstützt Auto-Layout) | `` | +| `` | Rechteck | `` | +| `` | Ellipse / Kreis | | +| `` | Textknoten (Kinder werden zum Textinhalt) | | +| `` | Linie | | +| `` | Stern | | +| `` | Polygon | | +| `` | Vektorpfad | | +| `` | Gruppe | | +| `
` | Abschnitt | | + +## Stil-Props + +Kompakte Kurzschreibweisen, inspiriert von Tailwinds Benennung. + +### Layout + +| Prop | Beschreibung | +|------|--------------| +| `flex` | `"row"` oder `"col"` — aktiviert Auto-Layout | +| `gap` | Abstand zwischen Kindern | +| `wrap` | Kinder in nächste Zeile umbrechen | +| `rowGap` | Gegenachsen-Abstand beim Umbrechen | +| `justify` | `"start"`, `"end"`, `"center"`, `"between"` | +| `items` | `"start"`, `"end"`, `"center"`, `"stretch"` | +| `p`, `px`, `py`, `pt`, `pr`, `pb`, `pl` | Innenabstand | + +### Größe & Position + +| Prop | Beschreibung | +|------|--------------| +| `w`, `h` | Breite/Höhe — Zahl, `"fill"` oder `"hug"` | +| `minW`, `maxW`, `minH`, `maxH` | Größenbeschränkungen | +| `x`, `y` | Position | + +### Erscheinungsbild + +| Prop | Beschreibung | +|------|--------------| +| `bg` | Hintergrundfüllung (Hex-Farbe) | +| `fill` | Alias für `bg` | +| `stroke` | Konturfarbe | +| `strokeWidth` | Konturbreite (Standard: 1) | +| `rounded` | Eckenradius (oder `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`) | +| `cornerSmoothing` | iOS-artig abgerundete Ecken (0–1) | +| `opacity` | 0–1 | +| `shadow` | Schlagschatten (z.B. `"0 4 8 #00000040"`) | +| `blur` | Ebenen-Unschärferadius | +| `rotate` | Rotation in Grad | +| `blendMode` | Mischmodus | +| `overflow` | `"hidden"` oder `"visible"` | + +### Typografie + +| Prop | Beschreibung | +|------|--------------| +| `size` / `fontSize` | Schriftgröße | +| `font` / `fontFamily` | Schriftfamilie | +| `weight` / `fontWeight` | `"bold"`, `"medium"`, `"normal"` oder Zahl | +| `color` | Textfarbe | +| `textAlign` | `"left"`, `"center"`, `"right"`, `"justified"` | + +## Als JSX exportieren + +Bestehende Designs zurück in JSX konvertieren: + +```sh +open-pencil export design.fig -f jsx # OpenPencil-Format +open-pencil export design.fig -f jsx --style tailwind # Tailwind-Klassen +``` + +Der Roundtrip funktioniert: Exportiere ein Design als JSX, bearbeite den Code, rendere es zurück. + +## Visuelles Diffing + +Da Designs als JSX darstellbar sind, werden Änderungen zu Code-Diffs: + +```diff + +- Old Title ++ New Title + Description + +``` + +Das macht Designänderungen in Pull Requests überprüfbar, in der Versionskontrolle nachverfolgbar und in der CI auditierbar. diff --git a/packages/docs/reference/mcp-tools.md b/packages/docs/de/programmable/mcp-server.md similarity index 98% rename from packages/docs/reference/mcp-tools.md rename to packages/docs/de/programmable/mcp-server.md index 634725bf1..e296a6447 100644 --- a/packages/docs/reference/mcp-tools.md +++ b/packages/docs/de/programmable/mcp-server.md @@ -126,7 +126,7 @@ Works with Claude Code, Cursor, Windsurf, Codex, and any agent that supports [sk | Tool | Description | |------|-------------| -| `create_shape` | Create a shape (FRAME, RECTANGLE, ELLIPSE, TEXT, LINE, STAR, POLYGON, SECTION) | +| `create_shape` | Create a shape (`FRAME`, `RECTANGLE`, `ELLIPSE`, `TEXT`, `LINE`, `STAR`, `POLYGON`, `SECTION`) | | `create_vector` | Create a vector node from a path string | | `create_slice` | Create an export slice | | `create_page` | Create a new page | @@ -149,7 +149,7 @@ Works with Claude Code, Cursor, Windsurf, Codex, and any agent that supports [sk | `set_opacity` | Set opacity (0–1) | | `set_radius` | Set corner radius (uniform or per-corner) | | `set_minmax` | Set min/max width and height constraints | -| `set_text` | Set text content of a TEXT node | +| `set_text` | Set text content of a `TEXT` node | | `set_font` | Set font family and weight | | `set_font_range` | Set font properties on a character range | | `set_text_resize` | Set text auto-resize mode (fixed/auto-width/auto-height) | diff --git a/packages/docs/de/reference/cli.md b/packages/docs/de/reference/cli.md new file mode 100644 index 000000000..6f83df440 --- /dev/null +++ b/packages/docs/de/reference/cli.md @@ -0,0 +1,184 @@ +--- +title: CLI Reference +description: Complete reference for all open-pencil commands, options, and flags. +--- + +# CLI Reference + +All commands accept a `.fig` file as a positional argument. When omitted, the CLI connects to the running desktop app via RPC. + +## info + +Show document info — pages, node counts, fonts, file size. + +```sh +open-pencil info [file] [--json] +``` + +| Option | Description | +|--------|-------------| +| `--json` | Output as JSON | + +## tree + +Print the node hierarchy. + +```sh +open-pencil tree [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--page` | Page name (default: first page) | +| `--depth` | Max depth (default: unlimited) | +| `--json` | Output as JSON | + +## find + +Search nodes by name or type. + +```sh +open-pencil find [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--name` | Node name (partial match, case-insensitive) | +| `--type` | Node type: `FRAME`, `TEXT`, `RECTANGLE`, `INSTANCE`, etc. | +| `--page` | Page name (default: all pages) | +| `--limit` | Max results (default: 100) | +| `--json` | Output as JSON | + +## node + +Show detailed properties of a node. + +```sh +open-pencil node [file] --id [--json] +``` + +| Option | Description | +|--------|-------------| +| `--id` | **Required.** Node ID (e.g. `1:23`) | +| `--json` | Output as JSON | + +## pages + +List all pages in the document. + +```sh +open-pencil pages [file] [--json] +``` + +| Option | Description | +|--------|-------------| +| `--json` | Output as JSON | + +## variables + +List design variables and collections. + +```sh +open-pencil variables [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--collection` | Filter by collection name | +| `--type` | Filter by type: `COLOR`, `FLOAT`, `STRING`, `BOOLEAN` | +| `--json` | Output as JSON | + +## export + +Export to PNG, JPG, WEBP, SVG, or JSX. + +```sh +open-pencil export [file] [options] +``` + +| Option | Alias | Description | +|--------|-------|-------------| +| `--format` | `-f` | `png` (default), `jpg`, `webp`, `svg`, `jsx` | +| `--output` | `-o` | Output file path (default: `.`) | +| `--scale` | `-s` | Export scale (default: 1) | +| `--quality` | `-q` | Quality 0–100, JPG/WEBP only (default: 90) | +| `--page` | | Page name (default: first page) | +| `--node` | | Node ID to export (default: all top-level nodes) | +| `--style` | | JSX style: `openpencil` (default), `tailwind` | +| `--thumbnail` | | Export page thumbnail instead of full render | +| `--width` | | Thumbnail width (default: 1920) | +| `--height` | | Thumbnail height (default: 1080) | + +## eval + +Execute JavaScript with the Figma Plugin API. + +```sh +open-pencil eval [file] [options] +``` + +| Option | Alias | Description | +|--------|-------|-------------| +| `--code` | `-c` | JavaScript code to execute | +| `--stdin` | | Read code from stdin | +| `--write` | `-w` | Write changes back to the input file | +| `--output` | `-o` | Write to a different file | +| `--json` | | Output as JSON | +| `--quiet` | `-q` | Suppress output | + +## analyze colors + +Analyze color palette usage across the document. + +```sh +open-pencil analyze colors [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--limit` | Max colors to show (default: 30) | +| `--threshold` | Distance threshold for clustering similar colors, 0–50 (default: 15) | +| `--similar` | Show similar color clusters | +| `--json` | Output as JSON | + +## analyze typography + +Analyze font family, size, and weight distribution. + +```sh +open-pencil analyze typography [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--group-by` | Group by: `family`, `size`, `weight` (default: show all styles) | +| `--limit` | Max styles to show (default: 30) | +| `--json` | Output as JSON | + +## analyze spacing + +Analyze gap and padding values across auto-layout frames. + +```sh +open-pencil analyze spacing [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--grid` | Base grid size to check against (default: 8) | +| `--json` | Output as JSON | + +## analyze clusters + +Find repeated node patterns — potential components. + +```sh +open-pencil analyze clusters [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--limit` | Max clusters to show (default: 20) | +| `--min-size` | Min node size in px (default: 30) | +| `--min-count` | Min instances to form a cluster (default: 2) | +| `--json` | Output as JSON | diff --git a/packages/docs/de/reference/file-format.md b/packages/docs/de/reference/file-format.md index 73becf3b8..ea94b8fb6 100644 --- a/packages/docs/de/reference/file-format.md +++ b/packages/docs/de/reference/file-format.md @@ -1,71 +1,72 @@ -# Dateiformat +# File Format -## .fig-Dateistruktur +## .fig File Structure + +A `.fig` file is a ZIP archive containing a Kiwi-encoded binary message: + +| Offset | Content | +|--------|---------| +| 0 | Magic header `fig-kiwi` (8 bytes) | +| 8 | Version (4 bytes, uint32 LE) | +| 12 | Schema length (4 bytes, uint32 LE) | +| 16 | Compressed Kiwi schema | +| … | Message length (4 bytes, uint32 LE) | +| … | Compressed Kiwi message — `NodeChange[]` (entire document) | +| … | Blob data — images, vector networks, fonts | + +## Import Pipeline ``` -┌─────────────────────────────────┐ -│ 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 -└─────────────────────────────────┘ +.fig file → parse header → decompress Zstd → decode Kiwi schema + → decode message → NodeChange[] → build SceneGraph + → resolve blob refs → render on canvas ``` -## Import-Pipeline +## Export Pipeline ``` -.fig file → Parse header → Decompress Zstd → Decode Kiwi schema - → Decode Message → NodeChange[] → Build SceneGraph - → Resolve blob refs → Render on canvas +SceneGraph → NodeChange[] → Kiwi encode → compress (Zstd/deflate) + → build ZIP (header + schema + message + thumbnail.png) + → write .fig file ``` -## Export-Pipeline +Export uses ⌘S (Save) and ⇧⌘S (Save As) with native OS dialogs on the desktop app. The exported file includes a `thumbnail.png` required by Figma for file preview. -``` -SceneGraph → NodeChange[] → Kiwi encode → Compress (Zstd/deflate) - → Build ZIP (header + schema + message + thumbnail.png) - → Write .fig file -``` - -Export uses ⌘S (Save) and ⇧⌘S (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). +Compression uses Zstd via Tauri Rust command on desktop, with deflate fallback in the browser. ## Kiwi Binary Codec -The codec handles Figma's 194-definition Kiwi schema with NodeChange as the central type (~390 fields). Key components: +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 +| Module | Purpose | +|--------|---------| +| `kiwi-schema` | Kiwi parser (from [evanw/kiwi](https://github.com/nicolo-ribaudo/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. +Figma's schema uses non-contiguous field IDs (e.g. 1, 2, 5, 10 with gaps). The kiwi-schema parser handles 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`. +`.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. ## Supported Formats | Format | Import | Export | |--------|--------|--------| -| .fig (Figma) | ✅ | ✅ | -| .svg | Planned | Planned | -| .png | Planned | Planned | -| .pdf | — | Planned | - -See [Roadmap](/development/roadmap) for planned format support timeline. +| `.fig` (Figma) | ✅ | ✅ | +| `.svg` | Planned | Planned | +| `.png` | Planned | Planned | +| `.pdf` | — | Planned | ## 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 +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. +Encoding happens synchronously in the copy event handler (not async Clipboard API) for browser compatibility. This enables bidirectional clipboard between OpenPencil and Figma. diff --git a/packages/docs/de/reference/mcp-tools.md b/packages/docs/de/reference/mcp-tools.md deleted file mode 100644 index f05541772..000000000 --- a/packages/docs/de/reference/mcp-tools.md +++ /dev/null @@ -1,150 +0,0 @@ -# MCP-Server - -OpenPencil enthält einen MCP-Server (Model Context Protocol), der KI-Coding-Tools — Claude Code, Cursor, Windsurf usw. — ermöglicht, .fig-Dateien headless zu lesen und zu bearbeiten. - -Zwei Transporte - -## **stdio** für MCP-Clients, **HTTP** für alles andere. - -```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" - } - } -} -``` - -Oder aus dem Quellcode ausführen: - -::: 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` - -## AI Agent Skill - -Install the OpenPencil skill for your AI coding agent: - -```sh -npx skills add open-pencil/skills@open-pencil -``` - -Works with Claude Code, Cursor, Windsurf, Codex, and any agent that supports [skills](https://skills.sh). - -## Tools (75) - -### 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.md index 8bb08fcd6..f6024302d 100644 --- a/packages/docs/de/reference/node-types.md +++ b/packages/docs/de/reference/node-types.md @@ -1,4 +1,4 @@ -# Knotentypen +# Node Types 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. @@ -8,41 +8,41 @@ The scene graph supports 28 node types from Figma's Kiwi schema. Each node is id | 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) | ✅ | +| `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) +- `COMPONENT_SET` → variant group container (no dedicated Kiwi ID, mapped from `SYMBOL` with variants) - `POLYGON` → Kiwi `REGULAR_POLYGON` (ID 11) ```typescript @@ -81,14 +81,14 @@ Document ## Core Properties -Every node carries these fields (subset of NodeChange): +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 +- `phase` — `CREATED` or `REMOVED` - `parentIndex` — parent GUID + position string for z-ordering ### Transform @@ -103,14 +103,14 @@ Every node carries these fields (subset of NodeChange): - `strokePaints[]` — stroke colors - `effects[]` — shadows, blurs - `opacity` — 0–1 -- `blendMode` — NORMAL, MULTIPLY, SCREEN, etc. +- `blendMode` — `NORMAL`, `MULTIPLY`, `SCREEN`, etc. ### Stroke - `strokeWeight` — stroke thickness -- `strokeAlign` — inside / center / outside -- `strokeCap` — butt / round / square -- `strokeJoin` — miter / bevel / round +- `strokeAlign` — `INSIDE` / `CENTER` / `OUTSIDE` +- `strokeCap` — `NONE` / `ROUND` / `SQUARE` / `ARROW_LINES` / `ARROW_EQUILATERAL` +- `strokeJoin` — `MITER` / `BEVEL` / `ROUND` - `dashPattern[]` — dash/gap lengths ### Corners diff --git a/packages/docs/de/reference/scene-graph.md b/packages/docs/de/reference/scene-graph.md index 6b33b7283..0d445d189 100644 --- a/packages/docs/de/reference/scene-graph.md +++ b/packages/docs/de/reference/scene-graph.md @@ -1,8 +1,8 @@ -# Szenengraph +# Scene Graph -## In-Memory-Darstellung +## In-Memory Representation -Knoten leben in einer flachen `Map` keyed by GUID string. Baumstruktur wird über `parentIndex` references. This gives O(1)-Lookup by ID and efficient traversal. +Nodes live in a flat `Map` 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 { @@ -31,11 +31,11 @@ interface SceneGraph { ## 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. +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. +`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 @@ -86,11 +86,11 @@ For marquee selection, `getNodesInRect` returns all nodes whose bounds intersect ## 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). +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. +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 diff --git a/packages/docs/de/user-guide/auto-layout.md b/packages/docs/de/user-guide/auto-layout.md index 19e87610f..9f78370e7 100644 --- a/packages/docs/de/user-guide/auto-layout.md +++ b/packages/docs/de/user-guide/auto-layout.md @@ -5,12 +5,12 @@ description: Flexbox-basiertes Auto-Layout in OpenPencil — Richtung, Abstand, # Auto-Layout -Auto-Layout verwendet Yoga (Flexbox-Engine), um Kinder automatisch innerhalb eines Frames zu positionieren. Es verwaltet Richtung, Abstände, Ausrichtung und responsive Größenanpassung. +Auto-Layout positioniert Kinder automatisch innerhalb eines Frames nach Flexbox-Regeln. Es verwaltet Richtung, Abstände, Ausrichtung und responsive Größenanpassung. ## Auto-Layout aktivieren -- Wählen Sie einen Frame und drücken Sie **⇧ A** (Shift + A), um Auto-Layout ein-/auszuschalten -- Wählen Sie lose Knoten und drücken Sie **⇧ A**, um sie in einen neuen Auto-Layout-Frame zu wickeln +- Wählen Sie einen Frame und drücken Sie ⇧A (Shift + A), um Auto-Layout ein-/auszuschalten +- Wählen Sie lose Knoten und drücken Sie ⇧A, um sie in einen neuen Auto-Layout-Frame zu wickeln Beim Umschließen werden Knoten nach visueller Position sortiert. @@ -60,7 +60,7 @@ Innerhalb eines Auto-Layout-Frames können Sie ein Kind ziehen, um es unter Gesc | Aktion | Mac | Windows / Linux | |--------|-----|-----------------| -| Auto-Layout umschalten | ⇧ A | Shift + A | +| Auto-Layout umschalten | ⇧A | Shift + A | ## Tipps diff --git a/packages/docs/de/user-guide/canvas-navigation.md b/packages/docs/de/user-guide/canvas-navigation.md index beb19bc7a..7a00027f7 100644 --- a/packages/docs/de/user-guide/canvas-navigation.md +++ b/packages/docs/de/user-guide/canvas-navigation.md @@ -11,19 +11,19 @@ Der Canvas ist Ihr unendlicher Arbeitsbereich. Sie können frei schwenken und zo Verschieben Sie den sichtbaren Bereich des Canvas, ohne Objekte zu beeinflussen. -- **Leertaste + Ziehen** — Leertaste halten und irgendwo auf dem Canvas ziehen +- Leertaste + Ziehen — Leertaste halten und irgendwo auf dem Canvas ziehen - **Mittlere Maustaste ziehen** — mittlere Maustaste drücken und ziehen - **Zwei-Finger-Trackpad** — mit zwei Fingern auf dem Trackpad wischen ## Handwerkzeug -Drücken Sie **H**, um das Handwerkzeug für kontinuierliches Schwenken zu aktivieren. Jedes Ziehen auf dem Canvas schwenkt den Viewport, ohne die Leertaste halten zu müssen. Wechseln Sie zu einem anderen Werkzeug (z.B. **V** für Auswahl), um zu deaktivieren. +Drücken Sie H, um das Handwerkzeug für kontinuierliches Schwenken zu aktivieren. Jedes Ziehen auf dem Canvas schwenkt den Viewport, ohne die Leertaste halten zu müssen. Wechseln Sie zu einem anderen Werkzeug (z.B. V für Auswahl), um zu deaktivieren. ## Zoomen Hinein- und Herauszoomen, zentriert auf Ihre Cursorposition. -- **Strg + Scrollen** (oder **⌘ + Scrollen** auf Mac) — nach oben scrollen zum Hineinzoomen, nach unten zum Herauszoomen +- Strg + Scrollen (oder ⌘ + Scrollen auf Mac) — nach oben scrollen zum Hineinzoomen, nach unten zum Herauszoomen - **Pinch-Geste** — auf dem Trackpad zusammenziehen zum Zoomen - **Tastenkürzel** — siehe Tabelle unten @@ -31,11 +31,11 @@ Hinein- und Herauszoomen, zentriert auf Ihre Cursorposition. | Aktion | Mac | Windows / Linux | |--------|-----|-----------------| -| Schwenken | Leertaste + Ziehen | Leertaste + Ziehen | -| Handwerkzeug | H | H | -| Hineinzoomen | ⌘ + | Strg + + | -| Herauszoomen | ⌘ - | Strg + - | -| Zoom auf 100% | ⌘ 0 | Strg + 0 | +| Schwenken | Leertaste + Ziehen | Leertaste + Ziehen | +| Handwerkzeug | H | H | +| Hineinzoomen | ⌘+ | Strg + + | +| Herauszoomen | ⌘− | Strg + − | +| Zoom auf 100% | ⌘0 | Strg + 0 | ## Tipps diff --git a/packages/docs/de/user-guide/components.md b/packages/docs/de/user-guide/components.md index 14dc8eeb6..6bd933014 100644 --- a/packages/docs/de/user-guide/components.md +++ b/packages/docs/de/user-guide/components.md @@ -9,13 +9,13 @@ Komponenten sind wiederverwendbare Design-Elemente. Bearbeiten Sie die Hauptkomp ## Komponente erstellen -Wählen Sie einen Frame oder eine Gruppe und drücken Sie **⌥ ⌘ K** (Strg + Alt + K). Der Knoten wird an Ort und Stelle in einen COMPONENT-Typ umgewandelt. +Wählen Sie einen Frame oder eine Gruppe und drücken Sie ⌥⌘K (Strg + Alt + K). Der Knoten wird zu einer wiederverwendbaren Komponente. Komponenten zeigen ein lila Label mit Diamant-Symbol. ## Komponenten-Sets -Wählen Sie zwei oder mehr Komponenten und drücken Sie **⇧ ⌘ K** (Shift + Strg + K), um sie zu einem Komponenten-Set zu kombinieren — ein Container mit gestricheltem lila Rand. +Wählen Sie zwei oder mehr Komponenten und drücken Sie ⇧⌘K (Shift + Strg + K), um sie zu einem Komponenten-Set zu kombinieren — ein Container mit gestricheltem lila Rand. ## Instanzen erstellen @@ -23,7 +23,7 @@ Rechtsklick auf eine Komponente → **Instanz erstellen**. Die Instanz erscheint ## Instanz lösen -Wählen Sie eine Instanz und drücken Sie **⌥ ⌘ B** (Strg + Alt + B). Die Instanz wird zu einem regulären Frame ohne Verbindung zur Komponente. +Wählen Sie eine Instanz und drücken Sie ⌥⌘B (Strg + Alt + B). Die Instanz wird zu einem regulären Frame ohne Verbindung zur Komponente. ## Zur Hauptkomponente @@ -45,7 +45,7 @@ Instanzen können bestimmte Eigenschaften überschreiben, ohne die Synchronisati ### Überschreibbare Eigenschaften -Name, Text, fontSize, fontWeight, fontFamily sowie alle visuellen und Layout-Eigenschaften. +Name, Text, Schriftgröße, Schriftstärke, Schriftfamilie sowie alle visuellen und Layout-Eigenschaften. ### Neue Kinder @@ -59,17 +59,17 @@ Komponenten und Instanzen sind opake Container — Klicken wählt die Komponente | Element | Darstellung | |---------|------------| -| Komponenten-Label | Lila (#9747ff) mit Diamant-Symbol | -| Instanz-Label | Lila (#9747ff) mit Diamant-Symbol | +| Komponenten-Label | Lila mit Diamant-Symbol | +| Instanz-Label | Lila mit Diamant-Symbol | | Komponenten-Set-Rand | Gestrichelt lila | ## Tastenkürzel | Aktion | Mac | Windows / Linux | |--------|-----|-----------------| -| Komponente erstellen | ⌥ ⌘ K | Strg + Alt + K | -| Komponenten-Set erstellen | ⇧ ⌘ K | Shift + Strg + K | -| Instanz lösen | ⌥ ⌘ B | Strg + Alt + B | +| Komponente erstellen | ⌥⌘K | Strg + Alt + K | +| Komponenten-Set erstellen | ⇧⌘K | Shift + Strg + K | +| Instanz lösen | ⌥⌘B | Strg + Alt + B | ## Tipps diff --git a/packages/docs/de/user-guide/context-menu.md b/packages/docs/de/user-guide/context-menu.md index 3ce257a10..bca83db65 100644 --- a/packages/docs/de/user-guide/context-menu.md +++ b/packages/docs/de/user-guide/context-menu.md @@ -15,18 +15,18 @@ Das Untermenü **Als kopieren** bietet folgende Zwischenablage-Formate: |--------|--------------|---------------------| | Als Text kopieren | — | — | | Als SVG kopieren | — | — | -| Als PNG kopieren | ⇧ ⌘ C | Shift + Strg + C | +| Als PNG kopieren | ⇧⌘C | Shift + Strg + C | | Als JSX kopieren | — | — | ## Zwischenablage | Aktion | Kürzel (Mac) | Kürzel (Win/Linux) | |--------|--------------|---------------------| -| Kopieren | ⌘ C | Strg + C | -| Ausschneiden | ⌘ X | Strg + X | -| Hier einfügen | ⌘ V | Strg + V | -| Duplizieren | ⌘ D | Strg + D | -| Löschen | ⌫ | Rücktaste / Entf | +| Kopieren | ⌘C | Strg + C | +| Ausschneiden | ⌘X | Strg + X | +| Hier einfügen | ⌘V | Strg + V | +| Duplizieren | ⌘D | Strg + D | +| Löschen | ⌫ | Rücktaste / Entf | ## Z-Reihenfolge @@ -39,9 +39,9 @@ Das Untermenü **Als kopieren** bietet folgende Zwischenablage-Formate: | Aktion | Kürzel (Mac) | Kürzel (Win/Linux) | |--------|--------------|---------------------| -| Gruppieren | ⌘ G | Strg + G | -| Entgruppieren | ⇧ ⌘ G | Shift + Strg + G | -| Auto-Layout hinzufügen | ⇧ A | Shift + A | +| Gruppieren | ⌘G | Strg + G | +| Entgruppieren | ⇧⌘G | Shift + Strg + G | +| Auto-Layout hinzufügen | ⇧A | Shift + A | ## Komponenten-Aktionen @@ -49,18 +49,18 @@ Komponenten-Aktionen werden in Lila dargestellt. | Aktion | Kürzel (Mac) | Kürzel (Win/Linux) | Verfügbar bei | |--------|--------------|---------------------|---------------| -| Komponente erstellen | ⌥ ⌘ K | Strg + Alt + K | Frames, Gruppen | -| Komponenten-Set erstellen | ⇧ ⌘ K | Shift + Strg + K | 2+ Komponenten | +| Komponente erstellen | ⌥⌘K | Strg + Alt + K | Frames, Gruppen | +| Komponenten-Set erstellen | ⇧⌘K | Shift + Strg + K | 2+ Komponenten | | Instanz erstellen | — | — | Komponenten | | Zur Hauptkomponente | — | — | Instanzen | -| Instanz lösen | ⌥ ⌘ B | Strg + Alt + B | Instanzen | +| Instanz lösen | ⌥⌘B | Strg + Alt + B | Instanzen | ## Sichtbarkeit & Sperre | Aktion | Kürzel (Mac) | Kürzel (Win/Linux) | |--------|--------------|---------------------| -| Ausblenden / Einblenden | ⇧ ⌘ H | Shift + Strg + H | -| Sperren / Entsperren | ⇧ ⌘ L | Shift + Strg + L | +| Ausblenden / Einblenden | ⇧⌘H | Shift + Strg + H | +| Sperren / Entsperren | ⇧⌘L | Shift + Strg + L | ## Auf Seite verschieben diff --git a/packages/docs/de/user-guide/drawing-shapes.md b/packages/docs/de/user-guide/drawing-shapes.md index d79ff4bcf..3ec59794d 100644 --- a/packages/docs/de/user-guide/drawing-shapes.md +++ b/packages/docs/de/user-guide/drawing-shapes.md @@ -11,11 +11,11 @@ Die untere Werkzeugleiste bietet Werkzeuge zum Erstellen von Formen, Frames und | Werkzeug | Kürzel | Beschreibung | |----------|--------|--------------| -| Rechteck | R | Zeichnet ein Rechteck | -| Ellipse | O | Zeichnet eine Ellipse | -| Linie | L | Zeichnet eine Linie | -| Frame | F | Zeichnet einen Frame (Container) | -| Sektion | S | Zeichnet eine Sektion (übernimmt überlappende Geschwister) | +| Rechteck | R | Zeichnet ein Rechteck | +| Ellipse | O | Zeichnet eine Ellipse | +| Linie | L | Zeichnet eine Linie | +| Frame | F | Zeichnet einen Frame (Container) | +| Sektion | S | Zeichnet eine Sektion (übernimmt überlappende Geschwister) | ## Formen-Flyout @@ -26,7 +26,7 @@ Das Formen-Flyout enthält zusätzliche Formen: ## Proportionales Zeichnen -Halten Sie **Shift** beim Ziehen: +Halten Sie Shift beim Ziehen: - Rechteck → Quadrat - Ellipse → Kreis @@ -71,9 +71,9 @@ Verfügbar für Rechtecke, Frames, Komponenten und Instanzen. Jede Ecke einzeln | Aktion | Mac | Windows / Linux | |--------|-----|-----------------| -| Rechteck | R | R | -| Ellipse | O | O | -| Linie | L | L | -| Frame | F | F | -| Sektion | S | S | -| Quadrat/Kreis erzwingen | Shift + Ziehen | Shift + Ziehen | +| Rechteck | R | R | +| Ellipse | O | O | +| Linie | L | L | +| Frame | F | F | +| Sektion | S | S | +| Quadrat/Kreis erzwingen | Shift + Ziehen | Shift + Ziehen | diff --git a/packages/docs/de/user-guide/exporting.md b/packages/docs/de/user-guide/exporting.md index ffb9fad1f..bf21147c2 100644 --- a/packages/docs/de/user-guide/exporting.md +++ b/packages/docs/de/user-guide/exporting.md @@ -23,8 +23,8 @@ Sie können mehrere Export-Einstellungen hinzufügen. Eine Live-Vorschau mit Sch | Methode | Mac | Windows / Linux | |---------|-----|-----------------| -| Tastenkürzel | ⇧ ⌘ E | Shift + Strg + E | -| Kontextmenü | Rechtsklick → Exportieren… | Rechtsklick → Exportieren… | +| Tastenkürzel | ⇧⌘E | Shift + Strg + E | +| Kontextmenü | Rechtsklick → Exportieren… | Rechtsklick → Exportieren… | | Eigenschaftspanel | Klick auf „Exportieren" | Klick auf „Exportieren" | ## Als kopieren @@ -35,25 +35,25 @@ Das Kontextmenü bietet **Als kopieren** mit mehreren Zwischenablage-Formaten: |--------|-----|-----------------| | Als Text kopieren | — | — | | Als SVG kopieren | — | — | -| Als PNG kopieren | ⇧ ⌘ C | Shift + Strg + C | +| Als PNG kopieren | ⇧⌘C | Shift + Strg + C | | Als JSX kopieren | — | — | ## .fig-Dateioperationen -OpenPencil verwendet das .fig-Format — dasselbe Binärformat wie Figma. +OpenPencil verwendet das .fig-Format — kompatibel mit Figma. Gespeicherte Dateien werden komprimiert und enthalten ein Vorschaubild. ### Dateien öffnen | Aktion | Mac | Windows / Linux | |--------|-----|-----------------| -| Datei öffnen | ⌘ O | Strg + O | +| Datei öffnen | ⌘O | Strg + O | ### Dateien speichern | Aktion | Mac | Windows / Linux | |--------|-----|-----------------| -| Speichern | ⌘ S | Strg + S | -| Speichern unter | ⇧ ⌘ S | Shift + Strg + S | +| Speichern | ⌘S | Strg + S | +| Speichern unter | ⇧⌘S | Shift + Strg + S | - **Speichern** überschreibt die aktuelle Datei ohne Dialog - **Speichern unter** öffnet einen Speicherdialog @@ -66,11 +66,11 @@ Aus OpenPencil exportierte Dateien können in Figma geöffnet werden und umgekeh | Aktion | Mac | Windows / Linux | |--------|-----|-----------------| -| Auswahl exportieren | ⇧ ⌘ E | Shift + Strg + E | -| Als PNG kopieren | ⇧ ⌘ C | Shift + Strg + C | -| Datei öffnen | ⌘ O | Strg + O | -| Speichern | ⌘ S | Strg + S | -| Speichern unter | ⇧ ⌘ S | Shift + Strg + S | +| Auswahl exportieren | ⇧⌘E | Shift + Strg + E | +| Als PNG kopieren | ⇧⌘C | Shift + Strg + C | +| Datei öffnen | ⌘O | Strg + O | +| Speichern | ⌘S | Strg + S | +| Speichern unter | ⇧⌘S | Shift + Strg + S | ## Tipps diff --git a/packages/docs/de/user-guide/index.md b/packages/docs/de/user-guide/index.md index 50f3c4c5f..a4e0141a8 100644 --- a/packages/docs/de/user-guide/index.md +++ b/packages/docs/de/user-guide/index.md @@ -9,7 +9,7 @@ description: Lernen Sie OpenPencil kennen — Canvas-Navigation, Zeichnen, Text, OpenPencil ist ein Open-Source, Figma-kompatibler Design-Editor — vollständig lokal, KI-nativ und programmierbar. Dieses Handbuch behandelt alles, was Sie für die effektive Nutzung des Editors wissen müssen. ::: tip Plattformübergreifende Tastenkürzel -In diesem Handbuch verwenden Tastenkürzel Mac-Notation: **⌘** = Command (Strg unter Windows/Linux), **⌥** = Option (Alt), **⇧** = Shift. +In diesem Handbuch verwenden Tastenkürzel Mac-Notation: ⌘ = Command (Strg unter Windows/Linux), ⌥ = Option (Alt), ⇧ = Shift. ::: ## Erste Schritte @@ -31,6 +31,6 @@ In diesem Handbuch verwenden Tastenkürzel Mac-Notation: **⌘** = Command (Strg ## Erweiterte Funktionen -- [Auto-Layout](./auto-layout) — Flexbox-basierte automatische Positionierung mit Yoga +- [Auto-Layout](./auto-layout) — Flexbox-basierte automatische Positionierung - [Komponenten](./components) — Wiederverwendbare Komponenten, Instanzen und Overrides - [Variablen](./variables) — Design-Variablen, Sammlungen, Modi und Füllbindungen diff --git a/packages/docs/de/user-guide/layers-and-pages.md b/packages/docs/de/user-guide/layers-and-pages.md index fcc19467a..ec3284dcd 100644 --- a/packages/docs/de/user-guide/layers-and-pages.md +++ b/packages/docs/de/user-guide/layers-and-pages.md @@ -17,7 +17,7 @@ Knoten werden in einem zusammenklappbaren Baum angezeigt. Klicken Sie auf den Pf ### Ziehen zum Umordnen -Ziehen Sie Ebenen, um sie umzuordnen. Dies ändert die Z-Reihenfolge im Szenengraphen. +Ziehen Sie Ebenen, um sie umzuordnen. Ebenen weiter oben in der Liste werden über den anderen gerendert. ### Sichtbarkeit umschalten @@ -25,7 +25,7 @@ Klicken Sie auf das Auge-Symbol neben einer Ebene, um sie auf dem Canvas ein- od ### Umbenennen -Doppelklicken Sie auf einen Ebenennamen, um ihn inline umzubenennen. **Enter** oder Klick außerhalb bestätigt, **Escape** bricht ab. +Doppelklicken Sie auf einen Ebenennamen, um ihn inline umzubenennen. Enter oder Klick außerhalb bestätigt, Escape bricht ab. ### Auswahl-Synchronisation @@ -64,10 +64,10 @@ Zeigt den ausgewählten Knoten als JSX-Code mit Syntaxhervorhebung. ### KI-Tab -KI-Chat-Interface (auch mit **⌘ J** umschaltbar). +KI-Chat-Interface (auch mit ⌘J umschaltbar). ## Tastenkürzel | Aktion | Mac | Windows / Linux | |--------|-----|-----------------| -| KI-Chat umschalten | ⌘ J | Strg + J | +| KI-Chat umschalten | ⌘J | Strg + J | diff --git a/packages/docs/de/user-guide/pen-tool.md b/packages/docs/de/user-guide/pen-tool.md index 8c443a126..c46a09830 100644 --- a/packages/docs/de/user-guide/pen-tool.md +++ b/packages/docs/de/user-guide/pen-tool.md @@ -9,7 +9,7 @@ Das Stiftwerkzeug erstellt Vektorpfade mit einem Vektornetzwerk-Datenmodell, kom ## Aktivieren -Drücken Sie **P**, um das Stiftwerkzeug zu aktivieren. +Drücken Sie P, um das Stiftwerkzeug zu aktivieren. ## Punkte setzen @@ -24,18 +24,18 @@ Klicken Sie auf den **ersten Punkt** des Pfades, um ihn zu einer Schleife zu sch ## Offene Pfade -Drücken Sie **Escape**, um den aktuellen Pfad als offenen Pfad zu bestätigen. Offene Pfade werden nur als Konturen gerendert. +Drücken Sie Escape, um den aktuellen Pfad als offenen Pfad zu bestätigen. Offene Pfade werden nur als Konturen gerendert. ## Vektornetzwerke -Pfade verwenden das Vektornetzwerk-Datenmodell statt einfacher Punktlisten. Vektornetzwerke ermöglichen flexiblere Topologien und werden in Figmas `vectorNetworkBlob`-Binärformat für .fig-Kompatibilität kodiert. +Pfade verwenden das Vektornetzwerk-Datenmodell statt einfacher Punktlisten. Vektornetzwerke ermöglichen flexiblere Topologien und sind vollständig mit dem .fig-Format kompatibel. ## Tastenkürzel | Aktion | Mac | Windows / Linux | |--------|-----|-----------------| -| Stiftwerkzeug | P | P | -| Offenen Pfad bestätigen | Escape | Escape | +| Stiftwerkzeug | P | P | +| Offenen Pfad bestätigen | Escape | Escape | ## Tipps diff --git a/packages/docs/de/user-guide/selection-and-manipulation.md b/packages/docs/de/user-guide/selection-and-manipulation.md index c55c8ae12..e35fd21fe 100644 --- a/packages/docs/de/user-guide/selection-and-manipulation.md +++ b/packages/docs/de/user-guide/selection-and-manipulation.md @@ -10,33 +10,33 @@ Wählen Sie Objekte aus, um sie zu bewegen, skalieren, drehen, duplizieren und a ## Auswählen - **Klicken** auf einen Knoten zur Auswahl (hebt alle anderen auf) -- **Shift + Klicken** zum Hinzufügen oder Entfernen aus der aktuellen Auswahl +- Shift + Klicken zum Hinzufügen oder Entfernen aus der aktuellen Auswahl - **Auswahlrechteck ziehen** — auf leeren Canvas ziehen; alle schneidenden Knoten werden ausgewählt -- **⌘ A** — alle Knoten auf der aktuellen Seite auswählen +- ⌘A — alle Knoten auf der aktuellen Seite auswählen - **Auf leeren Canvas klicken** — alles abwählen ## Bewegen - **Ziehen** eines ausgewählten Knotens zum Bewegen - **Pfeiltasten** — um 1 px verschieben -- **Shift + Pfeiltasten** — um 10 px verschieben +- Shift + Pfeiltasten — um 10 px verschieben ## Skalieren Ausgewählte Knoten zeigen 8 Skalierungsgriffe (4 Ecken + 4 Kantenmittelpunkte). Ziehen Sie einen Griff zum Skalieren. -- **Shift + Ziehen** einer Ecke, um Proportionen beizubehalten +- Shift + Ziehen einer Ecke, um Proportionen beizubehalten ## Drehen Fahren Sie knapp außerhalb eines Eckgriffs, um den Drehungscursor zu sehen. Ziehen zum Drehen. -- **Shift + Ziehen** rastet auf 15°-Schritte ein +- Shift + Ziehen rastet auf 15°-Schritte ein ## Duplizieren -- **Alt + Ziehen** (⌥ + Ziehen auf Mac) — ausgewählten Knoten duplizieren und Kopie verschieben -- **⌘ D** — an Ort und Stelle duplizieren +- Alt + Ziehen (⌥ + Ziehen auf Mac) — ausgewählten Knoten duplizieren und Kopie verschieben +- ⌘D — an Ort und Stelle duplizieren ## Löschen @@ -49,20 +49,20 @@ Fahren Sie knapp außerhalb eines Eckgriffs, um den Drehungscursor zu sehen. Zie ## Sichtbarkeit & Sperre -- **⇧ ⌘ H** — Sichtbarkeit umschalten -- **⇧ ⌘ L** — Sperre umschalten +- ⇧⌘H — Sichtbarkeit umschalten +- ⇧⌘L — Sperre umschalten ## Tastenkürzel | Aktion | Mac | Windows / Linux | |--------|-----|-----------------| -| Alles auswählen | ⌘ A | Strg + A | -| Duplizieren | ⌘ D | Strg + D | -| Duplizieren + bewegen | ⌥ + Ziehen | Alt + Ziehen | -| Löschen | ⌫ / Entf | Rücktaste / Entf | -| 1 px verschieben | Pfeiltasten | Pfeiltasten | -| 10 px verschieben | ⇧ + Pfeiltasten | Shift + Pfeiltasten | +| Alles auswählen | ⌘A | Strg + A | +| Duplizieren | ⌘D | Strg + D | +| Duplizieren + bewegen | ⌥ + Ziehen | Alt + Ziehen | +| Löschen | ⌫ / Entf | Rücktaste / Entf | +| 1 px verschieben | Pfeiltasten | Pfeiltasten | +| 10 px verschieben | ⇧ + Pfeiltasten | Shift + Pfeiltasten | | Nach vorne | ] | ] | | Nach hinten | [ | [ | -| Sichtbarkeit | ⇧ ⌘ H | Shift + Strg + H | -| Sperre | ⇧ ⌘ L | Shift + Strg + L | +| Sichtbarkeit | ⇧⌘H | Shift + Strg + H | +| Sperre | ⇧⌘L | Shift + Strg + L | diff --git a/packages/docs/de/user-guide/text-editing.md b/packages/docs/de/user-guide/text-editing.md index 601307f79..85705ac46 100644 --- a/packages/docs/de/user-guide/text-editing.md +++ b/packages/docs/de/user-guide/text-editing.md @@ -9,7 +9,7 @@ Erstellen Sie Textknoten und bearbeiten Sie sie direkt auf dem Canvas mit voller ## Text erstellen -Drücken Sie **T**, um das Textwerkzeug zu aktivieren, dann klicken Sie auf den Canvas. Ein leerer Textknoten erscheint mit blinkendem Cursor — tippen Sie sofort los. +Drücken Sie T, um das Textwerkzeug zu aktivieren, dann klicken Sie auf den Canvas. Ein leerer Textknoten erscheint mit blinkendem Cursor — tippen Sie sofort los. ## Inline-Bearbeitung @@ -19,12 +19,12 @@ Doppelklicken Sie auf einen vorhandenen Textknoten, um den Inline-Bearbeitungsmo | Aktion | Mac | Windows / Linux | |--------|-----|-----------------| -| Links/rechts | ← / → | ← / → | -| Hoch/runter | ↑ / ↓ | ↑ / ↓ | -| Wortweise | ⌥ ← / ⌥ → | Strg + ← / Strg + → | -| Zeilenanfang/-ende | ⌘ ← / ⌘ → | Pos1 / Ende | +| Links/rechts | ← / → | ← / → | +| Hoch/runter | ↑ / ↓ | ↑ / ↓ | +| Wortweise | ⌥← / ⌥→ | Strg + ← / Strg + → | +| Zeilenanfang/-ende | ⌘← / ⌘→ | Pos1 / Ende | -Halten Sie **Shift** mit jeder Bewegungstaste, um die Auswahl zu erweitern. +Halten Sie Shift mit jeder Bewegungstaste, um die Auswahl zu erweitern. ## Textauswahl @@ -37,9 +37,9 @@ Halten Sie **Shift** mit jeder Bewegungstaste, um die Auswahl zu erweitern. | Aktion | Mac | Windows / Linux | |--------|-----|-----------------| -| Fett | ⌘ B | Strg + B | -| Kursiv | ⌘ I | Strg + I | -| Unterstrichen | ⌘ U | Strg + U | +| Fett | ⌘B | Strg + B | +| Kursiv | ⌘I | Strg + I | +| Unterstrichen | ⌘U | Strg + U | Durchgestrichen ist über den **S**-Schalter im Typografie-Bereich verfügbar. @@ -47,11 +47,11 @@ Durchgestrichen ist über den **S**-Schalter im Typografie-Bereich verfügbar. | Aktion | Mac | Windows / Linux | |--------|-----|-----------------| -| Wort vor Cursor löschen | ⌥ ⌫ | Strg + Rücktaste | -| Bis Zeilenanfang löschen | ⌘ ⌫ | — | -| Ausschneiden | ⌘ X | Strg + X | -| Kopieren | ⌘ C | Strg + C | -| Einfügen | ⌘ V | Strg + V | +| Wort vor Cursor löschen | ⌥⌫ | Strg + Rücktaste | +| Bis Zeilenanfang löschen | ⌘⌫ | — | +| Ausschneiden | ⌘X | Strg + X | +| Kopieren | ⌘C | Strg + C | +| Einfügen | ⌘V | Strg + V | ## Schriftauswahl @@ -60,8 +60,8 @@ Die Schriftauswahl im Typografie-Bereich bietet Suchfilter, Schriftvorschau und ## Schriftquellen - **Standardschrift** — Inter wird automatisch geladen -- **Desktop (Tauri)** — Systemschriften via Rust font-kit -- **Browser** — via Local Font Access API (Chrome/Edge) +- **Desktop** — Systemschriften werden automatisch erkannt +- **Browser** — Systemschriften werden in Chrome und Edge unterstützt ## Tipps diff --git a/packages/docs/development/openspec.md b/packages/docs/development/openspec.md index a9eb48b9f..4c3f20939 100644 --- a/packages/docs/development/openspec.md +++ b/packages/docs/development/openspec.md @@ -37,7 +37,7 @@ openspec/ | 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 | +| 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 | diff --git a/packages/docs/development/roadmap.md b/packages/docs/development/roadmap.md index fc2ab9373..563e1b63a 100644 --- a/packages/docs/development/roadmap.md +++ b/packages/docs/development/roadmap.md @@ -4,7 +4,7 @@ ### Phase 1: Core Engine ✅ -SceneGraph, Skia rendering, basic shapes, selection, zoom/pan, undo/redo. +`SceneGraph`, Skia rendering, basic shapes, selection, zoom/pan, undo/redo. **Delivered:** - Scene graph with flat Map storage and parent-child tree @@ -36,13 +36,13 @@ Properties panel, layers panel, toolbar, Yoga layout integration, text editing. **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 +- 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) +- 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 @@ -57,17 +57,17 @@ Properties panel, layers panel, toolbar, Yoga layout integration, text editing. 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 +- 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) +- 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) +- 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) @@ -77,22 +77,22 @@ Components, instances, overrides, variables, collections, modes, image export. - 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: `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 +- 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 +- 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 types: `FLOAT`, `STRING`, `BOOLEAN` editing UI - Variable-driven theming ### Phase 5: AI Integration & Tooling ✅ @@ -107,7 +107,7 @@ Core extraction, CLI, MCP server, AI tools, eval command. - 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 -- AI chat: OpenRouter direct (no backend), Stronghold key storage, 87 tools split across domain files in `tools/`, model selector, ⌘J toggle, streaming markdown, Playwright tests with mock transport +- AI chat: OpenRouter direct (no backend), Stronghold key storage, 87 tools split across domain files in `tools/`, model selector, ⌘J toggle, streaming markdown, Playwright tests with mock transport - 49 additional AI/MCP tools ported from figma-use (87 total): granular set tools, node operations, variable CRUD, boolean operations, vector path tools, viewport control - MCP server (@open-pencil/mcp): stdio + HTTP (Hono + Streamable HTTP with sessions), 87 core tools + 3 file management tools (90 total), runs on Bun and Node.js - Unified tool definitions: define once in `packages/core/src/tools/` (split by domain), adapt for AI chat (valibot), MCP (zod), CLI (eval) @@ -135,7 +135,7 @@ Real-time collaboration, prototyping, comments, desktop distribution. - Share link at `/share/` with secure room IDs - Effects rendering: drop shadow, inner shadow, shadow spread, layer blur, background blur, foreground blur - Per-node SkPicture cache for effects (zero re-computation for static effects) -- Multi-file tabs: ⌘N/⌘T new tab, ⌘W close, ⌘O open in new tab +- Multi-file tabs: ⌘N/⌘T new tab, ⌘W close, ⌘O open in new tab - Apple code signing and notarization for macOS builds - Linux builds (x64) added to CI - Git LFS moved to Cloudflare R2 @@ -146,7 +146,7 @@ Real-time collaboration, prototyping, comments, desktop distribution. - Prototyping (frame connections, transitions, animations) - Comments (pin, threads, resolve) - PWA support -- Variant switching, FLOAT/STRING/BOOLEAN variable UI, variable-driven theming +- Variant switching, `FLOAT`/STRING/BOOLEAN variable UI, variable-driven theming - Full Figma compatibility test suite ## Timeline diff --git a/packages/docs/es/development/roadmap.md b/packages/docs/es/development/roadmap.md index 399775d7d..ca17a8833 100644 --- a/packages/docs/es/development/roadmap.md +++ b/packages/docs/es/development/roadmap.md @@ -4,7 +4,7 @@ ### Fase 1: Motor Core ✅ -SceneGraph, renderizado Skia, formas básicas, selección, zoom/pan, deshacer/rehacer, guías de ajuste. +`SceneGraph`, renderizado Skia, formas básicas, selección, zoom/pan, deshacer/rehacer, guías de ajuste. ### Fase 2: UI del Editor + Layout ✅ @@ -16,7 +16,7 @@ Importación/exportación .fig, codec Kiwi, portapapeles, herramienta de pluma, ### Fase 4: Componentes + Variables ✅ -Componentes, instancias, overrides, conjuntos de componentes, variables (COLOR/FLOAT/STRING/BOOLEAN), colecciones, modos, exportación de imágenes, menú contextual, formateo de texto enriquecido. +Componentes, instancias, overrides, conjuntos de componentes, variables (`COLOR`/FLOAT/STRING/BOOLEAN), colecciones, modos, exportación de imágenes, menú contextual, formateo de texto enriquecido. ### Fase 5: Integración IA & Herramientas ✅ @@ -24,7 +24,7 @@ Componentes, instancias, overrides, conjuntos de componentes, variables (COLOR/F - @open-pencil/core extraído a packages/core/ (sin dependencias DOM) - @open-pencil/cli con operaciones headless .fig (info, tree, find, export, analyze, eval) - Comando `eval` con API Plugin compatible con Figma -- Chat IA: conexión directa OpenRouter, 87 herramientas en `packages/core/src/tools/`, ⌘J +- Chat IA: conexión directa OpenRouter, 87 herramientas en `packages/core/src/tools/`, ⌘J - 49 herramientas IA/MCP adicionales portadas de figma-use (75 en total) - Servidor MCP (@open-pencil/mcp): stdio + HTTP, 87 herramientas core + 3 de gestión de archivos - Definiciones de herramientas unificadas: definir una vez en `packages/core/src/tools/` (por dominio), adaptar para chat IA (valibot), MCP (zod), CLI (eval) @@ -44,7 +44,7 @@ Componentes, instancias, overrides, conjuntos de componentes, variables (COLOR/F - Modo seguimiento: clic en avatar del par para seguir su viewport - Persistencia local vía y-indexeddb - Renderizado de efectos: sombra paralela, sombra interior, desenfoque de capa/fondo/primer plano -- Pestañas multi-archivo: ⌘N/⌘T nueva pestaña, ⌘W cerrar, ⌘O abrir +- Pestañas multi-archivo: ⌘N/⌘T nueva pestaña, ⌘W cerrar, ⌘O abrir - Firma de código Apple y notarización para macOS - Builds Linux (x64) añadidos al CI - Sitio de documentación VitePress con i18n (6 idiomas) @@ -53,7 +53,7 @@ Componentes, instancias, overrides, conjuntos de componentes, variables (COLOR/F - Prototipado (conexiones de frames, transiciones, animaciones) - Comentarios (pin, hilos, resolver) - Soporte PWA -- Cambio de variantes, UI de variables FLOAT/STRING/BOOLEAN, theming por variables +- Cambio de variantes, UI de variables `FLOAT`/STRING/BOOLEAN, theming por variables ## Cronograma diff --git a/packages/docs/es/eval-command.md b/packages/docs/es/eval-command.md deleted file mode 100644 index f4d484cdd..000000000 --- a/packages/docs/es/eval-command.md +++ /dev/null @@ -1,77 +0,0 @@ -# `open-pencil eval` — API de Plugin compatible con Figma para scripting headless - -## Visión general - -`bun open-pencil eval --code ''` ejecuta JavaScript contra un archivo `.fig` con un objeto global `figma` compatible con Figma. Esto permite scripting headless, operaciones por lotes, ejecución de herramientas IA y pruebas — todo sin interfaz gráfica. - -El objeto `figma` refleja la superficie de la API de Plugin de Figma lo más fielmente posible, por lo que el conocimiento existente sobre plugins de Figma y los fragmentos de código son directamente transferibles. - -```bash -# Crear un marco, configurar auto-layout, añadir hijos -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.fills = [{ type: "SOLID", color: { r: 1, g: 1, b: 1 } }] - return { id: frame.id, name: frame.name } -' - -# Consultar nodos -bun open-pencil eval design.fig --code ' - const buttons = figma.currentPage.findAll(n => n.name.includes("Button")) - return buttons.map(b => ({ id: b.id, name: b.name })) -' - -# Escribir los cambios -bun open-pencil eval design.fig --code '...' --write -``` - -## Arquitectura - -``` -CLI: open-pencil eval --code '...' - → loadDocument(file) → SceneGraph - → FigmaAPI(sceneGraph) → proxy `figma` - → AsyncFunction('figma', code)(figmaProxy) - → imprimir resultado / guardar con --write -``` - -### Clases principales - -| Clase | Ubicación | Rol | -|-------|-----------|-----| -| `FigmaAPI` | `packages/core/src/figma-api.ts` | Objeto proxy que implementa métodos `figma.*` | -| `FigmaNode` | `packages/core/src/figma-api.ts` | Proxy que envuelve `SceneNode` con acceso a propiedades estilo Figma | -| Comando `eval` | `packages/cli/src/commands/eval.ts` | Carga documento, crea API, ejecuta código | - -### ¿Por qué en `@open-pencil/core`? - -La clase `FigmaAPI` vive en core porque: las herramientas IA la reutilizan, los tests la usan y no tiene dependencias DOM. - -## Comando CLI - -``` -bun open-pencil eval [opciones] - -Argumentos: - file Archivo .fig sobre el que operar - -Opciones: - --code, -c Código JavaScript a ejecutar - --stdin Leer código desde stdin - --write, -w Escribir cambios en el archivo de entrada - -o, --output Escribir en un archivo diferente - --json Salida como JSON - --quiet, -q Suprimir la salida -``` - -## Implementación por fases - -- **Fase 1: Core** — creación de nodos, propiedades, operaciones de árbol, auto-layout, texto (~80% de scripts reales) -- **Fase 2: Componentes e Instancias** — createComponent, createInstance, detachInstance -- **Fase 3: Variables** — getLocalVariables, createVariable, setBoundVariable -- **Fase 4: Estilos y Avanzado** — estilos paint/texto/efectos, operaciones booleanas - -[Referencia API completa en inglés](/eval-command) diff --git a/packages/docs/es/guide/architecture.md b/packages/docs/es/guide/architecture.md index f13a388d0..969bbd308 100644 --- a/packages/docs/es/guide/architecture.md +++ b/packages/docs/es/guide/architecture.md @@ -2,7 +2,7 @@ ## Vista general del sistema -```mermaid +`mermaid graph TB subgraph Tauri["Tauri v2 Shell"] subgraph Editor["Editor (Web)"] @@ -22,7 +22,7 @@ graph TB MCP["MCP Server (90 tools, stdio+HTTP)"] Collab["P2P Collab (Trystero + Yjs)"] end -``` +` ## Diseño del editor @@ -62,7 +62,7 @@ Yoga de Meta proporciona cálculo de layout CSS flexbox. Un adaptador delgado ma ### Formato de archivo (Kiwi binario) -Reutiliza el códec binario Kiwi de Figma con 194 definiciones de mensaje/enum/struct. Importación: parsear cabecera → descomprimir Zstd → decodificar Kiwi → NodeChange[] → grafo de escena. La exportación invierte el proceso con generación de miniatura. +Reutiliza el códec binario Kiwi de Figma con 194 definiciones de mensaje/enum/struct. Importación: parsear cabecera → descomprimir Zstd → decodificar Kiwi → `NodeChange`[] → grafo de escena. La exportación invierte el proceso con generación de miniatura. Véase [Referencia del formato de archivo](/reference/file-format) para más detalles. @@ -108,7 +108,7 @@ Transiciones entre frames, triggers de interacción (clic, hover, arrastre), ges ### Layout CSS Grid -Yoga WASM actualmente solo soporta flexbox. CSS Grid está en upstream en [facebook/yoga#1893](https://github.com/facebook/yoga/pull/1893). OpenPencil lo adoptará cuando se publique la versión de Yoga. +CSS Grid está soportado a través de un [fork de Yoga](https://github.com/open-pencil/yoga/tree/grid) con PRs de grid cherry-picked del upstream. Selecciona un frame, haz clic en el icono de grid para cambiar de flex a grid. Configura tracks de columnas/filas (fr, px fijos, auto), gaps de columna y fila, y padding por lado. ### Firma de código en Windows diff --git a/packages/docs/es/guide/comparison.md b/packages/docs/es/guide/comparison.md index e515c790e..8ecd2583f 100644 --- a/packages/docs/es/guide/comparison.md +++ b/packages/docs/es/guide/comparison.md @@ -242,7 +242,7 @@ El enfoque de Open Pencil es más simple y con menos overhead. ## 11. Scripting y extensibilidad -OpenPencil incluye un [comando `eval`](/eval-command) que proporciona una API de Plugin compatible con Figma para scripting headless. Además, 90 herramientas AI disponibles vía chat integrado, servidor MCP (stdio + HTTP) y CLI. Penpot tiene sistema de plugins con ejecución sandboxed pero sin API de scripting headless ni integración MCP. +OpenPencil incluye un [comando `eval`](/programmable/cli/scripting) que proporciona una API de Plugin compatible con Figma para scripting headless. Además, 90 herramientas AI disponibles vía chat integrado, servidor MCP (stdio + HTTP) y CLI. Penpot tiene sistema de plugins con ejecución sandboxed pero sin API de scripting headless ni integración MCP. ## Resumen diff --git a/packages/docs/es/guide/features.md b/packages/docs/es/guide/features.md index 6a1c56697..b435d8989 100644 --- a/packages/docs/es/guide/features.md +++ b/packages/docs/es/guide/features.md @@ -87,7 +87,7 @@ bun add -g @open-pencil/mcp } ``` -Consulta la [referencia de herramientas MCP](/reference/mcp-tools) para la lista completa. +Consulta la [referencia de herramientas MCP](/programmable/mcp-server) para la lista completa. ## CLI diff --git a/packages/docs/es/guide/figma-comparison.md b/packages/docs/es/guide/figma-comparison.md index 3cb44adc1..167ad74b2 100644 --- a/packages/docs/es/guide/figma-comparison.md +++ b/packages/docs/es/guide/figma-comparison.md @@ -16,7 +16,7 @@ Comparación característica por característica de las capacidades de Figma Des | Panel de capas (barra lateral izquierda) | ✅ | Vista de árbol con expandir/colapsar, reordenamiento por arrastre, toggle de visibilidad; ancho redimensionable | | Panel de páginas | ✅ | Añadir, eliminar, renombrar páginas; estado de viewport por página | | Panel de propiedades (barra lateral derecha) | ✅ | Secciones: Apariencia, Relleno, Trazo, Efectos, Tipografía, Layout, Posición; ancho redimensionable | -| Zoom y pan | ✅ | Ctrl+scroll, pinch, ⌘+/⌘−/⌘0, espacio+arrastrar, ratón medio, herramienta mano (H) | +| Zoom y pan | ✅ | Ctrl + scroll, pinch, ⌘+ / ⌘− / ⌘0, espacio+arrastrar, ratón medio, herramienta mano (H) | | Reglas del canvas | ✅ | Reglas superior/izquierda con bandas de selección y badges de coordenadas | | Color de fondo del canvas | ✅ | Fondo por página vía panel de propiedades | | Guías del canvas | 🔲 | Figma soporta guías arrastrables desde las reglas | @@ -36,7 +36,7 @@ Comparación característica por característica de las capacidades de Figma Des |---------------|--------|-------| | Herramientas de forma (Rectángulo, Elipse, Línea, Polígono, Estrella) | ✅ | Todos los tipos de forma básicos; lados del polígono y radio interior de estrella configurables | | Frames | ✅ | Recorte de contenido, sistema de coordenadas independiente | -| Grupos | ✅ | ⌘G para agrupar, ⇧⌘G para desagrupar | +| Grupos | ✅ | ⌘G para agrupar, ⇧⌘G para desagrupar | | Secciones | ✅ | Píldoras de título, auto-adopción de nodos superpuestos, texto adaptativo a luminancia | | Herramienta de arco (arcos, semicírculos, anillos) | ✅ | arcData con ángulo inicio/fin y radio interior | | Herramienta de lápiz (mano alzada) | 🔲 | Herramienta de dibujo a mano alzada de Figma | @@ -46,9 +46,9 @@ Comparación característica por característica de las capacidades de Figma Des | Alineación y posición | ✅ | Posición, rotación, dimensiones en el panel de propiedades | | Copiar y pegar objetos | ✅ | Portapapeles estándar + formato binario Kiwi de Figma | | Escalar capas proporcionalmente | 🟡 | Shift-redimensionar mantiene proporciones; sin herramienta Scale dedicada (K) | -| Bloquear y desbloquear capas | ✅ | ⇧⌘L alterna bloqueo; nodos bloqueados no se pueden seleccionar/mover | -| Alternar visibilidad de capa | ✅ | Icono de ojo en panel de capas + atajo ⇧⌘H | -| Renombrar capas | ✅ | Doble clic para renombrar inline; Enter/Escape/clic para confirmar | +| Bloquear y desbloquear capas | ✅ | ⇧⌘L alterna bloqueo; nodos bloqueados no se pueden seleccionar/mover | +| Alternar visibilidad de capa | ✅ | Icono de ojo en panel de capas + atajo ⇧⌘H | +| Renombrar capas | ✅ | Doble clic para renombrar inline; Enter/Escape/clic para confirmar | | Traer al frente / Enviar al fondo | ✅ | Atajos ] y [; también en menú contextual | | Mover a página | ✅ | Mover nodos entre páginas vía menú contextual | | Restricciones (redimensionamiento responsivo) | 🔲 | Fijar bordes/centro para comportamiento de resize del padre | @@ -79,7 +79,7 @@ Comparación característica por característica de las capacidades de Figma Des | Característica | Estado | Notas | |---------------|--------|-------| -| Herramienta de texto y edición inline | ✅ | Edición nativa en canvas, textarea fantasma, cursor/selección/selección de palabra, arrastre, doble/triple clic, style runs (⌘B/I/U, botón S) | +| Herramienta de texto y edición inline | ✅ | Edición nativa en canvas, textarea fantasma, cursor/selección/selección de palabra, arrastre, doble/triple clic, style runs (⌘B / I / U, botón S) | | Renderizado de texto (Paragraph API) | ✅ | CanvasKit Paragraph para shaping, saltos de línea, métricas | | Carga de fuentes (fuentes del sistema) | ✅ | Inter por defecto, font-kit en Tauri con cache OnceLock, queryLocalFonts en navegador | | Familia y peso de fuente | ✅ | FontPicker con scroll virtual, búsqueda, vista previa CSS | @@ -126,7 +126,7 @@ Comparación característica por característica de las capacidades de Figma Des | Desenfoque de fondo | ✅ | Desenfocar contenido detrás de la capa | | Desenfoque de primer plano | ✅ | Desenfoque en primer plano | | Grosor de trazo | ✅ | Configurable en panel de propiedades | -| Cap de trazo (round, square, arrow) | ✅ | NONE, ROUND, SQUARE, ARROW_LINES, ARROW_EQUILATERAL | +| Cap de trazo (round, square, arrow) | ✅ | `NONE`, `ROUND`, `SQUARE`, `ARROW_LINES`, `ARROW_EQUILATERAL` | | Join de trazo (miter, bevel, round) | ✅ | Los tres tipos de join | | Patrones de guiones | ✅ | Patrón de trazo dash-on/dash-off | | Radio de esquina | ✅ | Radio uniforme y por esquina con toggle independiente | @@ -138,14 +138,14 @@ Comparación característica por característica de las capacidades de Figma Des | Característica | Estado | Notas | |---------------|--------|-------| | Flujo horizontal y vertical | ✅ | Motor flexbox Yoga WASM | -| Alternar auto layout (⇧A) | ✅ | Alternar en frame o envolver selección | +| Alternar auto layout (⇧A) | ✅ | Alternar en frame o envolver selección | | Gap (espaciado entre hijos) | ✅ | Configurable en panel de propiedades | | Padding (uniforme y por lado) | ✅ | Los cuatro lados independientemente | | Justify content | ✅ | Start, center, end, space-between | | Align items | ✅ | Start, center, end, stretch | | Dimensionado de hijos (fijo, rellenar, ajustar) | ✅ | Modos de dimensionado por hijo | | Wrap | ✅ | Flex wrap para layout multi-línea | -| Flujo auto layout grid | 🔲 | Auto layout basado en grid de Figma | +| Flujo auto layout grid | ✅ | CSS Grid vía fork de Yoga — tracks de columna/fila, gaps, spans | | Flujos combinados (anidados) | ✅ | Frames auto-layout anidados con diferentes direcciones | | Reordenar arrastrando en auto layout | ✅ | Indicador visual de inserción | | Ancho/alto mínimo y máximo | 🔲 | Figma soporta restricciones min/max en hijos de auto-layout | @@ -154,17 +154,17 @@ Comparación característica por característica de las capacidades de Figma Des | Característica | Estado | Notas | |---------------|--------|-------| -| Crear componentes | 🟡 | ⌥⌘K crea desde frame/grupo o envuelve selección; sin UI de propiedades de componente aún | -| Conjuntos de componentes | 🟡 | ⇧⌘K combina componentes; borde punteado púrpura; sin edición de propiedades de variante | +| Crear componentes | 🟡 | ⌥⌘K crea desde frame/grupo o envuelve selección; sin UI de propiedades de componente aún | +| Conjuntos de componentes | 🟡 | ⇧⌘K combina componentes; borde punteado púrpura; sin edición de propiedades de variante | | Instancias de componentes | 🟡 | Crear instancia desde menú contextual con clonación de hijos y mapeo componentId; sync en vivo; sin UI de edición de overrides | | Variantes | 🔲 | Cambio de variante y selección por propiedades | | Propiedades de componente | 🔲 | Propiedades booleanas, texto, intercambio de instancia | | Propagación de overrides | ✅ | Cambios en componente principal se propagan; overrides preservados | -| Variables (color, número, string, booleano) | 🟡 | COLOR con UI completa; FLOAT/STRING/BOOLEAN definidos sin UI de edición | +| Variables (color, número, string, booleano) | 🟡 | `COLOR` con UI completa; `FLOAT`/STRING/BOOLEAN definidos sin UI de edición | | Colecciones y modos de variables | 🟡 | Colecciones, modos, cambio activeMode funcionan; sin UI de theming por variable | | Estilos (color, texto, efecto, layout) | 🔲 | Presets de estilo reutilizables con nombre | | Bibliotecas (publicar, compartir, actualizar) | 🔲 | Bibliotecas compartidas de componentes/estilos | -| Desacoplar instancia | ✅ | ⌥⌘B convierte instancia en frame | +| Desacoplar instancia | ✅ | ⌥⌘B convierte instancia en frame | | Ir al componente principal | ✅ | Navegar al componente fuente, cross-page | ## Prototipado @@ -187,9 +187,9 @@ Comparación característica por característica de las capacidades de Figma Des | Característica | Estado | Notas | |---------------|--------|-------| -| Import de archivo .fig | ✅ | Codec Kiwi completo: 194 definiciones, ~390 campos por NodeChange | +| Import de archivo .fig | ✅ | Codec Kiwi completo: 194 definiciones, ~390 campos por `NodeChange` | | Export de archivo .fig | ✅ | Codificación Kiwi + compresión Zstd + generación de miniatura | -| Guardar / Guardar como | ✅ | ⌘S / ⇧⌘S; diálogos nativos (Tauri), File System Access API (Chrome/Edge), fallback de descarga (Safari) | +| Guardar / Guardar como | ✅ | ⌘S / ⇧⌘S; diálogos nativos (Tauri), File System Access API (Chrome/Edge), fallback de descarga (Safari) | | Portapapeles de Figma (pegar) | ✅ | Decodificar binario Kiwi del portapapeles de Figma | | Portapapeles de Figma (copiar) | ✅ | Codificar binario Kiwi que Figma puede leer | | Import de archivo Sketch | 🔲 | Parseo de archivos .sketch | diff --git a/packages/docs/es/guide/tech-stack.md b/packages/docs/es/guide/tech-stack.md index e9f6eecfe..0cb11c8bc 100644 --- a/packages/docs/es/guide/tech-stack.md +++ b/packages/docs/es/guide/tech-stack.md @@ -60,4 +60,4 @@ Yoga es mantenido por Meta, probado en miles de millones de dispositivos React N | Tecnología | Propósito | Fase | |-----------|---------|-------| -| CSS Grid en Yoga | Auto layout basado en grid | Bloqueado por upstream (facebook/yoga#1893) | +| CSS Grid en Yoga | Auto layout basado en grid | ✅ Soportado vía [fork de Yoga](https://github.com/open-pencil/yoga/tree/grid) | diff --git a/packages/docs/es/programmable/ai-chat.md b/packages/docs/es/programmable/ai-chat.md new file mode 100644 index 000000000..433ca6fbb --- /dev/null +++ b/packages/docs/es/programmable/ai-chat.md @@ -0,0 +1,47 @@ +--- +title: Chat con IA +description: Asistente de IA integrado con 87 herramientas para crear y modificar diseños. +--- + +# Chat con IA + +Pulsa ⌘J (Ctrl + J) para abrir el asistente de IA. Describe lo que quieres — crea formas, establece estilos, gestiona el layout, trabaja con componentes y analiza tu diseño. + +## Configuración + +1. Abre el panel de chat con IA (⌘J) +2. Haz clic en el icono de ajustes +3. Introduce tu clave de API de OpenRouter +4. Elige un modelo (Claude, GPT-4, Gemini, etc.) + +Sin backend, sin suscripción — tu clave se comunica directamente con OpenRouter. + +## Qué Puede Hacer + +El asistente tiene 87 herramientas en estas categorías: + +- **Crear** — frames, formas, texto, componentes, páginas. Renderiza JSX para layouts complejos. +- **Estilo** — rellenos, bordes, efectos, opacidad, radio de esquina, modos de fusión. +- **Layout** — auto-layout, alineación, espaciado, dimensionamiento. +- **Componentes** — crear componentes, instancias, conjuntos de componentes. Gestionar sobrecargas. +- **Variables** — crear/editar variables, colecciones, modos. Vincular a rellenos. +- **Consultar** — buscar nodos, leer propiedades, listar páginas, fuentes, selección. +- **Analizar** — paleta de colores, auditoría tipográfica, consistencia de espaciado, detección de clusters. +- **Exportar** — PNG, SVG, JSX con clases Tailwind. +- **Vector** — operaciones booleanas, manipulación de trazados. + +## Prompts de Ejemplo + +- "Crea una tarjeta con un título, descripción y un botón azul" +- "Haz que todos los botones de esta página usen el mismo radio de borde" +- "¿Qué fuentes se usan en este archivo?" +- "Cambia el fondo del frame seleccionado a un degradado de azul a púrpura" +- "Exporta el frame seleccionado como SVG" +- "Encuentra todos los nodos de texto con tamaño de fuente menor a 12" + +## Consejos + +- Selecciona nodos antes de preguntar — el asistente sabe qué está seleccionado. +- Sé específico con colores, tamaños y posiciones para resultados precisos. +- El asistente puede modificar múltiples nodos en un solo mensaje. +- Usa "deshacer" en el editor si no te gusta el resultado. diff --git a/packages/docs/es/programmable/cli/analyzing.md b/packages/docs/es/programmable/cli/analyzing.md new file mode 100644 index 000000000..15eade463 --- /dev/null +++ b/packages/docs/es/programmable/cli/analyzing.md @@ -0,0 +1,65 @@ +--- +title: Analizar Diseños +description: Audita colores, tipografía, espaciado y patrones repetidos en archivos .fig. +--- + +# Analizar Diseños + +Los comandos `analyze` auditan un sistema de diseño completo desde la terminal — encuentra inconsistencias, extrae la paleta real, detecta componentes que esperan ser extraídos. + +## Colores + +```sh +open-pencil analyze colors design.fig +``` + +Encuentra cada color en el archivo, cuenta el uso y muestra un histograma visual: + +``` +#1d1b20 ██████████████████████████████ 17155× +#49454f ██████████████████████████████ 9814× +#ffffff ██████████████████████████████ 8620× +#6750a4 ██████████████████████████████ 3967× +``` + +## Tipografía + +```sh +open-pencil analyze typography design.fig +``` + +Lista cada combinación de familia tipográfica, tamaño y peso con conteos de uso. Útil para detectar estilos de texto aislados que deberían consolidarse. + +## Espaciado + +```sh +open-pencil analyze spacing design.fig +``` + +Audita los valores de gap y padding en los frames con auto-layout. Ayuda a identificar inconsistencias en la escala de espaciado — por ejemplo, un gap de `13px` suelto entre valores de `8/16/24`. + +## Clusters + +```sh +open-pencil analyze clusters design.fig +``` + +Encuentra patrones de nodos repetidos que podrían extraerse como componentes: + +``` +3771× frame "container" (100% match) + size: 40×40, structure: Frame > [Frame] + +2982× instance "Checkboxes" (100% match) + size: 48×48, structure: Instance > [Frame] +``` + +## Salida JSON + +Todos los comandos de análisis soportan `--json` para salida legible por máquinas: + +```sh +open-pencil analyze colors design.fig --json +``` + +Envía a `jq`, alimenta verificaciones de CI, o úsalo en scripts que controlen presupuestos de tokens de diseño. diff --git a/packages/docs/es/programmable/cli/exporting.md b/packages/docs/es/programmable/cli/exporting.md new file mode 100644 index 000000000..c15237da9 --- /dev/null +++ b/packages/docs/es/programmable/cli/exporting.md @@ -0,0 +1,59 @@ +--- +title: Exportar +description: Renderiza archivos .fig a PNG, JPG, WEBP, SVG o JSX con clases Tailwind. +--- + +# Exportar + +Exporta diseños desde la terminal — imágenes rasterizadas, vectores o código JSX. + +## Exportar Imágenes + +```sh +open-pencil export design.fig # PNG (predeterminado) +open-pencil export design.fig -f jpg -s 2 -q 90 # JPG a 2×, calidad 90 +open-pencil export design.fig -f webp -s 3 # WEBP a 3× +open-pencil export design.fig -f svg # SVG vectorial +``` + +Opciones: + +- `-f` — formato: `png`, `jpg`, `webp`, `svg`, `jsx` +- `-s` — escala: `1`–`4` +- `-q` — calidad: `0`–`100` (solo JPG/WEBP) +- `-o` — ruta de salida +- `--page` — nombre de página +- `--node` — ID de nodo específico + +## Exportar JSX + +Exporta como JSX con clases de utilidad Tailwind: + +```sh +open-pencil export design.fig -f jsx --style tailwind +``` + +Salida: + +```html +
+

Card Title

+

Description text

+
+``` + +También soporta `--style openpencil` para el formato JSX nativo (ver [Renderizador JSX](../jsx-renderer)). + +## Miniaturas + +```sh +open-pencil export design.fig --thumbnail --width 1920 --height 1080 +``` + +## Modo Aplicación en Vivo + +Omite el archivo para exportar desde la aplicación en ejecución: + +```sh +open-pencil export -f png # captura de pantalla del lienzo actual +``` diff --git a/packages/docs/es/programmable/cli/inspecting.md b/packages/docs/es/programmable/cli/inspecting.md new file mode 100644 index 000000000..c576a1831 --- /dev/null +++ b/packages/docs/es/programmable/cli/inspecting.md @@ -0,0 +1,98 @@ +--- +title: Inspeccionar Archivos +description: Navega árboles de nodos, busca por nombre o tipo, y examina propiedades desde la terminal. +--- + +# Inspeccionar Archivos + +El CLI te permite explorar archivos `.fig` sin abrir el editor. Cada comando también funciona con la aplicación en vivo — simplemente omite el argumento de archivo. + +::: tip Instalar +```sh +bun add -g @open-pencil/cli +# o +brew install open-pencil/tap/open-pencil +``` +::: + +## Información del Documento + +Obtén un resumen rápido — cantidad de páginas, nodos totales, fuentes utilizadas, tamaño del archivo: + +```sh +open-pencil info design.fig +``` + +## Árbol de Nodos + +Imprime la jerarquía completa de nodos: + +```sh +open-pencil tree design.fig +``` + +``` +[0] [page] "Getting started" (0:46566) + [0] [section] "" (0:46567) + [0] [frame] "Body" (0:46568) + [0] [frame] "Introduction" (0:46569) + [0] [frame] "Introduction Card" (0:46570) + [0] [frame] "Guidance" (0:46571) +``` + +## Buscar Nodos + +Buscar por tipo: + +```sh +open-pencil find design.fig --type TEXT +``` + +Buscar por nombre: + +```sh +open-pencil find design.fig --name "Button" +``` + +Ambos flags se pueden combinar para refinar aún más los resultados. + +## Detalles del Nodo + +Inspecciona todas las propiedades de un nodo específico por su ID: + +```sh +open-pencil node design.fig --id 1:23 +``` + +## Páginas + +Lista todas las páginas del documento: + +```sh +open-pencil pages design.fig +``` + +## Variables + +Lista las variables de diseño y sus colecciones: + +```sh +open-pencil variables design.fig +``` + +## Modo Aplicación en Vivo + +Cuando la aplicación de escritorio está en ejecución, omite el argumento de archivo — el CLI se conecta vía RPC y opera sobre el lienzo en vivo: + +```sh +open-pencil tree # inspeccionar el documento en vivo +open-pencil eval -c "..." # consultar el editor +``` + +## Salida JSON + +Todos los comandos soportan `--json` para salida legible por máquinas — envía a `jq`, alimenta scripts de CI, o procesa con otras herramientas: + +```sh +open-pencil tree design.fig --json | jq '.[] | .name' +``` diff --git a/packages/docs/es/programmable/cli/scripting.md b/packages/docs/es/programmable/cli/scripting.md new file mode 100644 index 000000000..4e36d606f --- /dev/null +++ b/packages/docs/es/programmable/cli/scripting.md @@ -0,0 +1,70 @@ +--- +title: Scripting +description: Ejecuta JavaScript con la API de Plugins de Figma — consulta nodos, modifica diseños por lotes, crea frames. +--- + +# Scripting + +`open-pencil eval` te da acceso a la API completa de Plugins de Figma en la terminal. Lee nodos, modifica propiedades, crea formas — y luego guarda los cambios en el archivo. + +## Uso Básico + +```sh +open-pencil eval design.fig -c "figma.currentPage.children.length" +``` + +El flag `-c` recibe JavaScript. El global `figma` funciona como la API de Plugins de Figma. + +## Consultar Nodos + +```sh +open-pencil eval design.fig -c " + figma.currentPage.findAll(n => n.type === 'FRAME' && n.name.includes('Button')) + .map(b => ({ id: b.id, name: b.name, w: b.width, h: b.height })) +" +``` + +## Modificar y Guardar + +```sh +open-pencil eval design.fig -c " + figma.currentPage.children.forEach(n => n.opacity = 0.5) +" -w +``` + +`-w` escribe los cambios de vuelta al archivo de entrada. Usa `-o output.fig` para escribir en un archivo diferente. + +## Leer desde Stdin + +Para scripts más largos: + +```sh +cat transform.js | open-pencil eval design.fig --stdin -w +``` + +## Modo Aplicación en Vivo + +Omite el archivo para ejecutar contra la aplicación de escritorio en ejecución: + +```sh +open-pencil eval -c "figma.currentPage.name" +``` + +## API Disponible + +El objeto `figma` soporta: + +- `figma.currentPage` — la página activa +- `figma.root` — la raíz del documento +- `figma.createFrame()`, `figma.createRectangle()`, `figma.createEllipse()`, `figma.createText()`, etc. +- `.findAll()`, `.findOne()` — buscar descendientes +- `.appendChild()`, `.insertChild()` — manipulación del árbol +- Todos los setters de propiedades: `.fills`, `.strokes`, `.effects`, `.opacity`, `.cornerRadius`, `.layoutMode`, `.itemSpacing`, etc. + +Esta es la misma API que usan los plugins de Figma, por lo que el conocimiento existente y los fragmentos de código se transfieren directamente. + +## Salida JSON + +```sh +open-pencil eval design.fig -c "..." --json +``` diff --git a/packages/docs/es/programmable/collaboration.md b/packages/docs/es/programmable/collaboration.md new file mode 100644 index 000000000..4fc7c3cbf --- /dev/null +++ b/packages/docs/es/programmable/collaboration.md @@ -0,0 +1,38 @@ +--- +title: Colaboración +description: Edición colaborativa en tiempo real vía P2P WebRTC — sin servidor, sin cuenta. +--- + +# Colaboración + +Edita diseños juntos en tiempo real. Los pares se conectan directamente — ningún servidor retransmite tus datos, no se requiere cuenta. + +## Compartir una Sala + +1. Haz clic en el botón de compartir en la esquina superior derecha +2. Copia el enlace generado (`app.openpencil.dev/share/`) +3. Envíalo a tus colaboradores + +Cualquiera con el enlace puede unirse. La sala permanece activa mientras al menos un participante tenga la página abierta. + +## Qué se Sincroniza + +- **Cambios en el documento** — cada edición (formas, texto, propiedades, layout) se sincroniza instantáneamente +- **Cursores** — ve dónde apunta cada colaborador, con su nombre y color +- **Selecciones** — las selecciones resaltadas son visibles para todos + +## Modo de Seguimiento + +Haz clic en el avatar de un colaborador en la barra superior para seguir su vista. Tu lienzo se desplaza y hace zoom para coincidir con su vista. Haz clic de nuevo para dejar de seguir. + +## Cómo Funciona + +Los pares se conectan directamente vía WebRTC — tus datos de diseño van directamente de navegador a navegador, nunca a través de un servidor central. El estado del documento usa un CRDT (tipo de datos replicado libre de conflictos), así que las ediciones concurrentes se fusionan automáticamente sin conflictos. + +La sala persiste localmente — si refrescas la página, te reconectas con el mismo estado. + +## Consejos + +- Funciona en el navegador y en la aplicación de escritorio +- Los IDs de sala son criptográficamente aleatorios — solo las personas con el enlace pueden unirse +- Los cursores inactivos se limpian automáticamente cuando alguien se desconecta diff --git a/packages/docs/es/programmable/index.md b/packages/docs/es/programmable/index.md new file mode 100644 index 000000000..9fa928c0d --- /dev/null +++ b/packages/docs/es/programmable/index.md @@ -0,0 +1,51 @@ +--- +layout: doc +title: IA y Automatización +description: Cada operación en OpenPencil es scriptable — chat con IA, CLI, renderizador JSX, servidor MCP, colaboración en tiempo real. +--- + +# IA y Automatización + +OpenPencil trata los archivos de diseño como datos. Cada operación disponible en el editor — crear formas, establecer rellenos, gestionar auto-layout, exportar recursos — también está disponible desde la terminal, desde agentes de IA y desde código. Sin plugins que instalar, sin claves de API, sin lista de espera. + +La interfaz del editor y las interfaces de automatización usan el mismo motor. Si puedes hacerlo con un clic, puedes hacerlo con un script. + +## Chat con IA + +El asistente integrado tiene acceso a 87 herramientas que cubren toda la superficie del editor. Describe lo que quieres en lenguaje natural — "añade una sombra de 16px a todos los botones", "crea un componente de tarjeta con variante para modo oscuro", "exporta cada frame de esta página a 2×". + +[Chat con IA →](./ai-chat) + +## Colaboración + +Edición multijugador en tiempo real mediante WebRTC peer-to-peer. Sin servidor, sin cuenta. Comparte un enlace de sala y edita junto con cursores en vivo y modo de seguimiento. El estado del documento se sincroniza mediante CRDT, así que las ediciones se fusionan automáticamente incluso con conexiones inestables. + +[Colaboración →](./collaboration) + +## Renderizador JSX + +Describe la interfaz como JSX — la misma sintaxis que los LLMs ya conocen de React. Una sola llamada puede crear un árbol completo de componentes con frames, texto, auto-layout, rellenos y bordes. Compacto, declarativo y diferenciable. + +En la dirección opuesta, exporta cualquier selección de vuelta a JSX con clases Tailwind — útil para entregar a desarrollo o alimentar diseños de vuelta a un LLM. + +[Renderizador JSX →](./jsx-renderer) + +## CLI + +Inspecciona, exporta y analiza archivos `.fig` sin abrir el editor. Lista páginas, busca nodos, extrae tokens de diseño, renderiza a PNG — todo desde la terminal con salida JSON legible por máquinas. + +El CLI también se conecta a la aplicación de escritorio en ejecución vía RPC, para que puedas crear scripts del editor mientras lo usas. + +[Inspeccionar Archivos](./cli/inspecting) · [Exportar](./cli/exporting) · [Analizar Diseños](./cli/analyzing) · [Scripting](./cli/scripting) + +## Servidor MCP + +Conecta Claude Code, Cursor, Windsurf o cualquier cliente compatible con MCP a OpenPencil. El servidor expone 90 herramientas para leer, crear y modificar diseños — las mismas herramientas que usa el chat con IA integrado. Funciona sobre stdio o HTTP con soporte de sesiones. + +[Servidor MCP →](./mcp-server) + +## ¿Por Qué Abierto? + +Figma es una plataforma cerrada. Su servidor MCP es de solo lectura. El acceso CDP por navegador fue eliminado en la versión 126. Los archivos de diseño viven en un formato propietario en los servidores de otra empresa. El desarrollo de plugins requiere un runtime personalizado con APIs limitadas. + +OpenPencil es la alternativa: código abierto, licencia MIT, cada operación scriptable, datos almacenados localmente. Tus archivos de diseño son tuyos — inspecciónalos, transfórmalos, envíalos a CI, aliméntalos a un LLM. Sin necesidad de permiso. diff --git a/packages/docs/es/programmable/jsx-renderer.md b/packages/docs/es/programmable/jsx-renderer.md new file mode 100644 index 000000000..256b6e67b --- /dev/null +++ b/packages/docs/es/programmable/jsx-renderer.md @@ -0,0 +1,116 @@ +--- +title: Renderizador JSX +description: Crea diseños con JSX — la sintaxis que los LLMs ya conocen de millones de componentes React. +--- + +# Renderizador JSX + +OpenPencil usa JSX como su lenguaje de creación de diseños. Los LLMs han visto millones de componentes React — describir un layout como `` es natural, sin necesidad de entrenamiento especial. Cada token importa cuando un agente de IA realiza docenas de operaciones, y JSX es la representación declarativa más compacta. + +JSX también es diferenciable. Cuando una IA modifica un diseño, el cambio es un diff de JSX — legible, revisable, versionable. + +## Crear Diseños + +La herramienta `render` (disponible en el chat con IA, MCP y CLI eval) acepta JSX: + +```jsx + + Card Title + Description text + +``` + +En el servidor MCP y el chat con IA, la herramienta `render` acepta cadenas JSX directamente. En el CLI, usa el comando `export` para ir en la dirección opuesta — [exportar diseños como JSX](./cli/exporting). + +## Elementos + +Todos los tipos de nodos están disponibles como elementos JSX: + +| Elemento | Crea | Alias | +|----------|------|-------| +| `` | Frame (contenedor, soporta auto-layout) | `` | +| `` | Rectángulo | `` | +| `` | Elipse / círculo | | +| `` | Nodo de texto (los hijos se convierten en contenido de texto) | | +| `` | Línea | | +| `` | Estrella | | +| `` | Polígono | | +| `` | Trazado vectorial | | +| `` | Grupo | | +| `
` | Sección | | + +## Props de Estilo + +Props abreviados compactos inspirados en la nomenclatura de Tailwind. + +### Layout + +| Prop | Descripción | +|------|-------------| +| `flex` | `"row"` o `"col"` — activa auto-layout | +| `gap` | Espacio entre hijos | +| `wrap` | Ajustar hijos a la siguiente línea | +| `rowGap` | Espaciado en el eje transversal al ajustar | +| `justify` | `"start"`, `"end"`, `"center"`, `"between"` | +| `items` | `"start"`, `"end"`, `"center"`, `"stretch"` | +| `p`, `px`, `py`, `pt`, `pr`, `pb`, `pl` | Padding | + +### Tamaño y Posición + +| Prop | Descripción | +|------|-------------| +| `w`, `h` | Ancho/alto — número, `"fill"` o `"hug"` | +| `minW`, `maxW`, `minH`, `maxH` | Restricciones de tamaño | +| `x`, `y` | Posición | + +### Apariencia + +| Prop | Descripción | +|------|-------------| +| `bg` | Relleno de fondo (color hexadecimal) | +| `fill` | Alias de `bg` | +| `stroke` | Color de borde | +| `strokeWidth` | Ancho del borde (predeterminado: 1) | +| `rounded` | Radio de esquina (o `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`) | +| `cornerSmoothing` | Esquinas suaves estilo iOS (0–1) | +| `opacity` | 0–1 | +| `shadow` | Sombra proyectada (ej. `"0 4 8 #00000040"`) | +| `blur` | Radio de desenfoque de capa | +| `rotate` | Rotación en grados | +| `blendMode` | Modo de fusión | +| `overflow` | `"hidden"` o `"visible"` | + +### Tipografía + +| Prop | Descripción | +|------|-------------| +| `size` / `fontSize` | Tamaño de fuente | +| `font` / `fontFamily` | Familia tipográfica | +| `weight` / `fontWeight` | `"bold"`, `"medium"`, `"normal"` o número | +| `color` | Color del texto | +| `textAlign` | `"left"`, `"center"`, `"right"`, `"justified"` | + +## Exportar a JSX + +Convierte diseños existentes de vuelta a JSX: + +```sh +open-pencil export design.fig -f jsx # formato OpenPencil +open-pencil export design.fig -f jsx --style tailwind # clases Tailwind +``` + +El viaje de ida y vuelta funciona: exporta un diseño como JSX, modifica el código, renderízalo de nuevo. + +## Diferencias Visuales + +Como los diseños son representables como JSX, los cambios se convierten en diffs de código: + +```diff + +- Old Title ++ New Title + Description + +``` + +Esto hace que los cambios de diseño sean revisables en pull requests, rastreables en control de versiones y auditables en CI. diff --git a/packages/docs/es/programmable/mcp-server.md b/packages/docs/es/programmable/mcp-server.md new file mode 100644 index 000000000..e296a6447 --- /dev/null +++ b/packages/docs/es/programmable/mcp-server.md @@ -0,0 +1,251 @@ +# 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` + +Security defaults (HTTP transport): + +- Binds to `127.0.0.1` by default (`HOST` to override) +- `eval` tool is disabled +- File operations are limited to `OPENPENCIL_MCP_ROOT` (defaults to current working directory) +- CORS is disabled by default; set `OPENPENCIL_MCP_CORS_ORIGIN` to allow one origin +- Optional auth token: `OPENPENCIL_MCP_AUTH_TOKEN` (client sends `Authorization: Bearer ` or `x-mcp-token`) + +Server 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` + +## AI Agent Skill + +Teach your AI coding agent to use OpenPencil tools: + +```sh +npx skills add open-pencil/skills@open-pencil +``` + +Works with Claude Code, Cursor, Windsurf, Codex, and any agent that supports [skills](https://skills.sh). The skill covers the CLI, MCP tools, JSX rendering, eval, and the running app's automation bridge. + +## Tools (90) + +### 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_current_page` | Get the current page name and ID | +| `get_node` | Get detailed properties of a node by ID | +| `find_nodes` | Find nodes by name pattern and/or type | +| `get_components` | List all components in the document | +| `list_pages` | List all pages | +| `list_variables` | List design variables | +| `list_collections` | List variable collections | +| `list_fonts` | List fonts used in the current page | +| `page_bounds` | Get bounding box of all objects on the current page | +| `node_bounds` | Get bounding box of a node | +| `node_ancestors` | Get ancestor chain of a node | +| `node_children` | Get direct children of a node | +| `node_tree` | Get the subtree rooted at a node | +| `node_bindings` | Get variable bindings on a node | + +### Create + +| Tool | Description | +|------|-------------| +| `create_shape` | Create a shape (`FRAME`, `RECTANGLE`, `ELLIPSE`, `TEXT`, `LINE`, `STAR`, `POLYGON`, `SECTION`) | +| `create_vector` | Create a vector node from a path string | +| `create_slice` | Create an export slice | +| `create_page` | Create a new page | +| `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 | +| `node_to_component` | Convert an existing node into a component in-place | + +### 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 | +| `set_rotation` | Set rotation angle in degrees | +| `set_opacity` | Set opacity (0–1) | +| `set_radius` | Set corner radius (uniform or per-corner) | +| `set_minmax` | Set min/max width and height constraints | +| `set_text` | Set text content of a `TEXT` node | +| `set_font` | Set font family and weight | +| `set_font_range` | Set font properties on a character range | +| `set_text_resize` | Set text auto-resize mode (fixed/auto-width/auto-height) | +| `set_visible` | Show or hide a node | +| `set_blend` | Set blend mode | +| `set_locked` | Lock or unlock a node | +| `set_stroke_align` | Set stroke alignment (inside/center/outside) | +| `set_text_properties` | Set text layout: alignment, auto-resize, text case, decoration, truncation | +| `set_layout_child` | Configure auto-layout child: sizing, grow, alignment, absolute positioning | +| `node_move` | Move a node to a new position | +| `node_resize` | Resize a node | +| `node_replace_with` | Replace a node with another node | +| `arrange` | Align or distribute selected nodes | + +### 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 | +| `flatten_nodes` | Flatten nodes into a single vector | +| `boolean_union` | Boolean union of two or more nodes | +| `boolean_subtract` | Boolean subtraction | +| `boolean_intersect` | Boolean intersection | +| `boolean_exclude` | Boolean exclusion | + +### Vector Path + +| Tool | Description | +|------|-------------| +| `path_get` | Get the path data of a vector node | +| `path_set` | Set the path data of a vector node | +| `path_scale` | Scale a vector path | +| `path_flip` | Flip a vector path horizontally or vertically | +| `path_move` | Translate a vector path | + +### Export + +| Tool | Description | +|------|-------------| +| `export_image` | Export nodes as PNG, JPG, or WEBP. Returns base64-encoded image data | +| `export_svg` | Export nodes as SVG markup | + +### Viewport + +| Tool | Description | +|------|-------------| +| `viewport_get` | Get current viewport position and zoom level | +| `viewport_set` | Set viewport position and zoom | +| `viewport_zoom_to_fit` | Zoom viewport to fit specified nodes | + +### Variables + +| Tool | Description | +|------|-------------| +| `get_variable` | Get a variable by ID or name | +| `find_variables` | Find variables by name pattern or type | +| `create_variable` | Create a new variable in a collection | +| `set_variable` | Set a variable value in a mode | +| `delete_variable` | Delete a variable | +| `bind_variable` | Bind a variable to a node property | +| `get_collection` | Get a variable collection by ID or name | +| `create_collection` | Create a new variable collection | +| `delete_collection` | Delete a variable collection | + +### Analyze + +| Tool | Description | +|------|-------------| +| `analyze_colors` | Analyze color palette usage across the document | +| `analyze_typography` | Analyze font/size/weight distribution | +| `analyze_spacing` | Analyze gap and padding values | +| `analyze_clusters` | Detect repeated patterns (potential components) | + +### Diff + +| Tool | Description | +|------|-------------| +| `diff_create` | Create a snapshot of the current document state | +| `diff_show` | Show differences between the current state and a snapshot | + +### 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 | + +Note: `eval` is available over stdio, but disabled in HTTP mode for security. diff --git a/packages/docs/es/reference/cli.md b/packages/docs/es/reference/cli.md new file mode 100644 index 000000000..6f83df440 --- /dev/null +++ b/packages/docs/es/reference/cli.md @@ -0,0 +1,184 @@ +--- +title: CLI Reference +description: Complete reference for all open-pencil commands, options, and flags. +--- + +# CLI Reference + +All commands accept a `.fig` file as a positional argument. When omitted, the CLI connects to the running desktop app via RPC. + +## info + +Show document info — pages, node counts, fonts, file size. + +```sh +open-pencil info [file] [--json] +``` + +| Option | Description | +|--------|-------------| +| `--json` | Output as JSON | + +## tree + +Print the node hierarchy. + +```sh +open-pencil tree [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--page` | Page name (default: first page) | +| `--depth` | Max depth (default: unlimited) | +| `--json` | Output as JSON | + +## find + +Search nodes by name or type. + +```sh +open-pencil find [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--name` | Node name (partial match, case-insensitive) | +| `--type` | Node type: `FRAME`, `TEXT`, `RECTANGLE`, `INSTANCE`, etc. | +| `--page` | Page name (default: all pages) | +| `--limit` | Max results (default: 100) | +| `--json` | Output as JSON | + +## node + +Show detailed properties of a node. + +```sh +open-pencil node [file] --id [--json] +``` + +| Option | Description | +|--------|-------------| +| `--id` | **Required.** Node ID (e.g. `1:23`) | +| `--json` | Output as JSON | + +## pages + +List all pages in the document. + +```sh +open-pencil pages [file] [--json] +``` + +| Option | Description | +|--------|-------------| +| `--json` | Output as JSON | + +## variables + +List design variables and collections. + +```sh +open-pencil variables [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--collection` | Filter by collection name | +| `--type` | Filter by type: `COLOR`, `FLOAT`, `STRING`, `BOOLEAN` | +| `--json` | Output as JSON | + +## export + +Export to PNG, JPG, WEBP, SVG, or JSX. + +```sh +open-pencil export [file] [options] +``` + +| Option | Alias | Description | +|--------|-------|-------------| +| `--format` | `-f` | `png` (default), `jpg`, `webp`, `svg`, `jsx` | +| `--output` | `-o` | Output file path (default: `.`) | +| `--scale` | `-s` | Export scale (default: 1) | +| `--quality` | `-q` | Quality 0–100, JPG/WEBP only (default: 90) | +| `--page` | | Page name (default: first page) | +| `--node` | | Node ID to export (default: all top-level nodes) | +| `--style` | | JSX style: `openpencil` (default), `tailwind` | +| `--thumbnail` | | Export page thumbnail instead of full render | +| `--width` | | Thumbnail width (default: 1920) | +| `--height` | | Thumbnail height (default: 1080) | + +## eval + +Execute JavaScript with the Figma Plugin API. + +```sh +open-pencil eval [file] [options] +``` + +| Option | Alias | Description | +|--------|-------|-------------| +| `--code` | `-c` | JavaScript code to execute | +| `--stdin` | | Read code from stdin | +| `--write` | `-w` | Write changes back to the input file | +| `--output` | `-o` | Write to a different file | +| `--json` | | Output as JSON | +| `--quiet` | `-q` | Suppress output | + +## analyze colors + +Analyze color palette usage across the document. + +```sh +open-pencil analyze colors [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--limit` | Max colors to show (default: 30) | +| `--threshold` | Distance threshold for clustering similar colors, 0–50 (default: 15) | +| `--similar` | Show similar color clusters | +| `--json` | Output as JSON | + +## analyze typography + +Analyze font family, size, and weight distribution. + +```sh +open-pencil analyze typography [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--group-by` | Group by: `family`, `size`, `weight` (default: show all styles) | +| `--limit` | Max styles to show (default: 30) | +| `--json` | Output as JSON | + +## analyze spacing + +Analyze gap and padding values across auto-layout frames. + +```sh +open-pencil analyze spacing [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--grid` | Base grid size to check against (default: 8) | +| `--json` | Output as JSON | + +## analyze clusters + +Find repeated node patterns — potential components. + +```sh +open-pencil analyze clusters [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--limit` | Max clusters to show (default: 20) | +| `--min-size` | Min node size in px (default: 30) | +| `--min-count` | Min instances to form a cluster (default: 2) | +| `--json` | Output as JSON | diff --git a/packages/docs/es/reference/file-format.md b/packages/docs/es/reference/file-format.md index fe3594464..ea94b8fb6 100644 --- a/packages/docs/es/reference/file-format.md +++ b/packages/docs/es/reference/file-format.md @@ -1,71 +1,72 @@ -# Formato de archivo +# File Format -## Estructura de archivos .fig +## .fig File Structure + +A `.fig` file is a ZIP archive containing a Kiwi-encoded binary message: + +| Offset | Content | +|--------|---------| +| 0 | Magic header `fig-kiwi` (8 bytes) | +| 8 | Version (4 bytes, uint32 LE) | +| 12 | Schema length (4 bytes, uint32 LE) | +| 16 | Compressed Kiwi schema | +| … | Message length (4 bytes, uint32 LE) | +| … | Compressed Kiwi message — `NodeChange[]` (entire document) | +| … | Blob data — images, vector networks, fonts | + +## Import Pipeline ``` -┌─────────────────────────────────┐ -│ 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 -└─────────────────────────────────┘ +.fig file → parse header → decompress Zstd → decode Kiwi schema + → decode message → NodeChange[] → build SceneGraph + → resolve blob refs → render on canvas ``` -## Pipeline de importación +## Export Pipeline ``` -.fig file → Parse header → Decompress Zstd → Decode Kiwi schema - → Decode Message → NodeChange[] → Build SceneGraph - → Resolve blob refs → Render on canvas +SceneGraph → NodeChange[] → Kiwi encode → compress (Zstd/deflate) + → build ZIP (header + schema + message + thumbnail.png) + → write .fig file ``` -## Pipeline de exportación +Export uses ⌘S (Save) and ⇧⌘S (Save As) with native OS dialogs on the desktop app. The exported file includes a `thumbnail.png` required by Figma for file preview. -``` -SceneGraph → NodeChange[] → Kiwi encode → Compress (Zstd/deflate) - → Build ZIP (header + schema + message + thumbnail.png) - → Write .fig file -``` - -Export uses ⌘S (Save) and ⇧⌘S (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). +Compression uses Zstd via Tauri Rust command on desktop, with deflate fallback in the browser. ## Kiwi Binary Codec -The codec handles Figma's 194-definition Kiwi schema with NodeChange as the central type (~390 fields). Key components: +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 +| Module | Purpose | +|--------|---------| +| `kiwi-schema` | Kiwi parser (from [evanw/kiwi](https://github.com/nicolo-ribaudo/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. +Figma's schema uses non-contiguous field IDs (e.g. 1, 2, 5, 10 with gaps). The kiwi-schema parser handles 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`. +`.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. ## Supported Formats | Format | Import | Export | |--------|--------|--------| -| .fig (Figma) | ✅ | ✅ | -| .svg | Planned | Planned | -| .png | Planned | Planned | -| .pdf | — | Planned | - -See [Roadmap](/development/roadmap) for planned format support timeline. +| `.fig` (Figma) | ✅ | ✅ | +| `.svg` | Planned | Planned | +| `.png` | Planned | Planned | +| `.pdf` | — | Planned | ## 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 +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. +Encoding happens synchronously in the copy event handler (not async Clipboard API) for browser compatibility. This enables bidirectional clipboard between OpenPencil and Figma. diff --git a/packages/docs/es/reference/mcp-tools.md b/packages/docs/es/reference/mcp-tools.md deleted file mode 100644 index c2ef12c5d..000000000 --- a/packages/docs/es/reference/mcp-tools.md +++ /dev/null @@ -1,150 +0,0 @@ -# Servidor MCP - -OpenPencil incluye un servidor MCP (Model Context Protocol) que permite a las herramientas de coding IA — Claude Code, Cursor, Windsurf etc. — leer y modificar archivos .fig headless. - -Dos transportes - -## **stdio** para clientes MCP, **HTTP** para todo lo demás. - -```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" - } - } -} -``` - -O ejecutar desde el código fuente: - -::: 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` - -## AI Agent Skill - -Install the OpenPencil skill for your AI coding agent: - -```sh -npx skills add open-pencil/skills@open-pencil -``` - -Works with Claude Code, Cursor, Windsurf, Codex, and any agent that supports [skills](https://skills.sh). - -## Tools (75) - -### 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.md index e7447724e..f6024302d 100644 --- a/packages/docs/es/reference/node-types.md +++ b/packages/docs/es/reference/node-types.md @@ -1,4 +1,4 @@ -# Tipos de nodo +# Node Types 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. @@ -8,41 +8,41 @@ The scene graph supports 28 node types from Figma's Kiwi schema. Each node is id | 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) | ✅ | +| `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) +- `COMPONENT_SET` → variant group container (no dedicated Kiwi ID, mapped from `SYMBOL` with variants) - `POLYGON` → Kiwi `REGULAR_POLYGON` (ID 11) ```typescript @@ -81,14 +81,14 @@ Document ## Core Properties -Every node carries these fields (subset of NodeChange): +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 +- `phase` — `CREATED` or `REMOVED` - `parentIndex` — parent GUID + position string for z-ordering ### Transform @@ -103,14 +103,14 @@ Every node carries these fields (subset of NodeChange): - `strokePaints[]` — stroke colors - `effects[]` — shadows, blurs - `opacity` — 0–1 -- `blendMode` — NORMAL, MULTIPLY, SCREEN, etc. +- `blendMode` — `NORMAL`, `MULTIPLY`, `SCREEN`, etc. ### Stroke - `strokeWeight` — stroke thickness -- `strokeAlign` — inside / center / outside -- `strokeCap` — butt / round / square -- `strokeJoin` — miter / bevel / round +- `strokeAlign` — `INSIDE` / `CENTER` / `OUTSIDE` +- `strokeCap` — `NONE` / `ROUND` / `SQUARE` / `ARROW_LINES` / `ARROW_EQUILATERAL` +- `strokeJoin` — `MITER` / `BEVEL` / `ROUND` - `dashPattern[]` — dash/gap lengths ### Corners diff --git a/packages/docs/es/reference/scene-graph.md b/packages/docs/es/reference/scene-graph.md index 2f0f06eef..0d445d189 100644 --- a/packages/docs/es/reference/scene-graph.md +++ b/packages/docs/es/reference/scene-graph.md @@ -1,8 +1,8 @@ -# Grafo de escena +# Scene Graph -## Representación en memoria +## In-Memory Representation -Los nodos viven en un Map plano `Map` keyed by GUID string. La estructura de árbol se mantiene via `parentIndex` references. This gives Búsqueda O(1) by ID and efficient traversal. +Nodes live in a flat `Map` 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 { @@ -31,11 +31,11 @@ interface SceneGraph { ## 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. +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. +`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 @@ -86,11 +86,11 @@ For marquee selection, `getNodesInRect` returns all nodes whose bounds intersect ## 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). +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. +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 diff --git a/packages/docs/es/user-guide/auto-layout.md b/packages/docs/es/user-guide/auto-layout.md index 51a001111..a809a8655 100644 --- a/packages/docs/es/user-guide/auto-layout.md +++ b/packages/docs/es/user-guide/auto-layout.md @@ -4,7 +4,12 @@ description: Auto-layout basado en flexbox en OpenPencil. --- # Auto-layout -**⇧ A** para activar/desactivar o envolver la selección. +El auto-layout posiciona los hijos automáticamente dentro de un marco usando reglas de flexbox. Controla la dirección, el espaciado, la alineación y el dimensionamiento responsivo. + +## Activar auto-layout + +- Selecciona un marco y pulsa ⇧A (Shift + A) para activar o desactivar el auto-layout +- Selecciona nodos sueltos (sin marco padre) y pulsa ⇧A para envolverlos en un nuevo marco con auto-layout ## Dirección - **Horizontal** — de izquierda a derecha diff --git a/packages/docs/es/user-guide/canvas-navigation.md b/packages/docs/es/user-guide/canvas-navigation.md index 2070d0edf..65ca44cf9 100644 --- a/packages/docs/es/user-guide/canvas-navigation.md +++ b/packages/docs/es/user-guide/canvas-navigation.md @@ -9,23 +9,23 @@ El lienzo es tu espacio de trabajo infinito. ## Panorámica -- **Espacio + arrastrar** — mantén Espacio y arrastra +- Espacio + arrastrar — mantén Espacio y arrastra - **Botón central del ratón** — pulsa y arrastra - **Trackpad con dos dedos** — desliza con dos dedos ## Herramienta mano -Pulsa **H** para activar la herramienta mano. Cambia a otra herramienta (ej. **V**) para desactivar. +Pulsa H para activar la herramienta mano. Cambia a otra herramienta (ej. **V**) para desactivar. ## Zoom -- **Ctrl + scroll** (o **⌘ + scroll** en Mac) — zoom adelante/atrás +- Ctrl + scroll (o ⌘ + scroll en Mac) — zoom adelante/atrás - **Gesto de pellizco** — pellizca en el trackpad | Acción | Mac | Windows / Linux | |--------|-----|-----------------| -| Panorámica | Espacio + arrastrar | Espacio + arrastrar | -| Herramienta mano | H | H | -| Zoom adelante | ⌘ + | Ctrl + + | -| Zoom atrás | ⌘ - | Ctrl + - | -| Zoom 100% | ⌘ 0 | Ctrl + 0 | +| Panorámica | Espacio + arrastrar | Espacio + arrastrar | +| Herramienta mano | H | H | +| Zoom adelante | ⌘+ | Ctrl + + | +| Zoom atrás | ⌘− | Ctrl + − | +| Zoom 100% | ⌘0 | Ctrl + 0 | diff --git a/packages/docs/es/user-guide/components.md b/packages/docs/es/user-guide/components.md index 36488d8d0..a59bf7234 100644 --- a/packages/docs/es/user-guide/components.md +++ b/packages/docs/es/user-guide/components.md @@ -4,29 +4,55 @@ description: Componentes reutilizables, instancias, overrides y sincronización --- # Componentes +Los componentes son elementos de diseño reutilizables. Edita el componente principal y todas sus instancias se actualizan automáticamente. + ## Crear un componente -**⌥ ⌘ K** (Ctrl+Alt+K) — convierte marco/grupo en COMPONENT. Etiqueta morada con diamante. + +Selecciona un marco o grupo y pulsa ⌥⌘K (Ctrl + Alt + K). La selección se convierte en un componente reutilizable. + +Los componentes muestran una etiqueta morada con icono de diamante. ## Conjuntos de componentes -**⇧ ⌘ K** — combina 2+ componentes con borde morado punteado. + +Selecciona dos o más componentes y pulsa ⇧⌘K (Shift + Ctrl + K) para combinarlos en un conjunto de componentes — un contenedor con borde morado punteado. Los conjuntos son útiles para agrupar variantes (ej. estados de botón). ## Crear instancias -Clic derecho → **Crear instancia**. Aparece 40 px a la derecha. + +Clic derecho → **Crear instancia**. La instancia aparece a la derecha del componente original. ## Desenlazar una instancia -**⌥ ⌘ B** — se convierte en marco sin enlace. + +Selecciona una instancia y pulsa ⌥⌘B (Ctrl + Alt + B). La instancia se convierte en un marco regular sin enlace al componente original. ## Sincronización en vivo -Editar un componente actualiza todas sus instancias. Propiedades sincronizadas: dimensiones, rellenos, trazos, efectos, opacidad, radios de esquinas, layout. + +Editar un componente actualiza todas sus instancias automáticamente. Propiedades sincronizadas: + +- Ancho y alto +- Rellenos, trazos y efectos +- Opacidad y radios de esquinas +- Propiedades de layout ## Overrides -Las instancias pueden sobreescribir propiedades sin romper el enlace. -## Hit testing +Las instancias pueden sobreescribir propiedades específicas sin romper el enlace de sincronización. Cuando se sobreescribe una propiedad en una instancia, esa propiedad se omite durante la sincronización — las demás propiedades continúan actualizándose desde el componente principal. + +## Selección + Clic selecciona el componente. **Doble clic** para entrar y seleccionar hijos. +## Tratamiento visual + +| Elemento | Apariencia | +|----------|------------| +| Etiqueta de componente | Morada con icono de diamante, siempre visible | +| Etiqueta de instancia | Morada con icono de diamante, siempre visible | +| Borde de conjunto | Contorno morado punteado | + +## Atajos de teclado + | Acción | Mac | Windows / Linux | |--------|-----|-----------------| -| Crear componente | ⌥ ⌘ K | Ctrl + Alt + K | -| Crear conjunto | ⇧ ⌘ K | Shift + Ctrl + K | -| Desenlazar instancia | ⌥ ⌘ B | Ctrl + Alt + B | +| Crear componente | ⌥⌘K | Ctrl + Alt + K | +| Crear conjunto | ⇧⌘K | Shift + Ctrl + K | +| Desenlazar instancia | ⌥⌘B | Ctrl + Alt + B | diff --git a/packages/docs/es/user-guide/context-menu.md b/packages/docs/es/user-guide/context-menu.md index 734713af7..c492cfb85 100644 --- a/packages/docs/es/user-guide/context-menu.md +++ b/packages/docs/es/user-guide/context-menu.md @@ -14,23 +14,23 @@ El submenú **Copiar como** ofrece estos formatos: |--------|-----|-----------------| | Copiar como texto | — | — | | Copiar como SVG | — | — | -| Copiar como PNG | ⇧ ⌘ C | Shift + Ctrl + C | +| Copiar como PNG | ⇧⌘C | Shift + Ctrl + C | | Copiar como JSX | — | — | ## Portapapeles -Copiar (⌘C), Cortar (⌘X), Pegar (⌘V), Duplicar (⌘D), Eliminar (⌫) +Copiar (⌘C), Cortar (⌘X), Pegar (⌘V), Duplicar (⌘D), Eliminar (⌫) ## Orden Z **]** al frente · **[** al fondo ## Agrupación -Agrupar (⌘G), Desagrupar (⇧⌘G), Añadir auto-layout (⇧A) +Agrupar (⌘G), Desagrupar (⇧⌘G), Añadir auto-layout (⇧A) ## Componentes -Crear componente (⌥⌘K), Crear conjunto (⇧⌘K), Crear instancia, Ir al componente principal, Desenlazar instancia (⌥⌘B). Acciones en morado. +Crear componente (⌥⌘K), Crear conjunto (⇧⌘K), Crear instancia, Ir al componente principal, Desenlazar instancia (⌥⌘B). Acciones en morado. ## Visibilidad y bloqueo -Ocultar/Mostrar (⇧⌘H), Bloquear/Desbloquear (⇧⌘L) +Ocultar/Mostrar (⇧⌘H), Bloquear/Desbloquear (⇧⌘L) ## Mover a página Submenú con todas las páginas excepto la actual. diff --git a/packages/docs/es/user-guide/drawing-shapes.md b/packages/docs/es/user-guide/drawing-shapes.md index 2d2a7e2a3..b0581ee8a 100644 --- a/packages/docs/es/user-guide/drawing-shapes.md +++ b/packages/docs/es/user-guide/drawing-shapes.md @@ -6,17 +6,17 @@ description: Crear rectángulos, elipses, líneas, marcos y secciones en OpenPen | Herramienta | Atajo | Descripción | |-------------|-------|-------------| -| Rectángulo | R | Dibuja un rectángulo | -| Elipse | O | Dibuja una elipse | -| Línea | L | Dibuja una línea | -| Marco | F | Dibuja un marco (contenedor) | -| Sección | S | Dibuja una sección | +| Rectángulo | R | Dibuja un rectángulo | +| Elipse | O | Dibuja una elipse | +| Línea | L | Dibuja una línea | +| Marco | F | Dibuja un marco (contenedor) | +| Sección | S | Dibuja una sección | ## Formas adicionales **Polígono** y **Estrella** en el menú desplegable de formas. ## Dibujo restringido -**Shift** al arrastrar: rectángulo → cuadrado, elipse → círculo, línea → 0°/45°/90°. +Shift al arrastrar: rectángulo → cuadrado, elipse → círculo, línea → 0°/45°/90°. ## Propiedades - **Relleno** — color sólido, gradiente (lineal, radial, angular, diamante), imagen diff --git a/packages/docs/es/user-guide/exporting.md b/packages/docs/es/user-guide/exporting.md index 3c2522e9a..03b3a081f 100644 --- a/packages/docs/es/user-guide/exporting.md +++ b/packages/docs/es/user-guide/exporting.md @@ -17,8 +17,8 @@ Selecciona un nodo y usa la sección Export en el panel de propiedades. | Método | Mac | Windows / Linux | |--------|-----|-----------------| -| Atajo de teclado | ⇧ ⌘ E | Shift + Ctrl + E | -| Menú contextual | Clic derecho → Exportar… | Clic derecho → Exportar… | +| Atajo de teclado | ⇧⌘E | Shift + Ctrl + E | +| Menú contextual | Clic derecho → Exportar… | Clic derecho → Exportar… | | Panel de propiedades | Botón "Exportar" | Botón "Exportar" | ## Copiar como @@ -29,18 +29,22 @@ El menú contextual **Copiar como** ofrece formatos adicionales: |--------|-----|-----------------| | Copiar como texto | — | — | | Copiar como SVG | — | — | -| Copiar como PNG | ⇧ ⌘ C | Shift + Ctrl + C | +| Copiar como PNG | ⇧⌘C | Shift + Ctrl + C | | Copiar como JSX | — | — | ## Operaciones de archivo .fig | Acción | Mac | Windows / Linux | |--------|-----|-----------------| -| Abrir | ⌘ O | Ctrl + O | -| Guardar | ⌘ S | Ctrl + S | -| Guardar como | ⇧ ⌘ S | Shift + Ctrl + S | +| Abrir | ⌘O | Ctrl + O | +| Guardar | ⌘S | Ctrl + S | +| Guardar como | ⇧⌘S | Shift + Ctrl + S | -Compatibilidad de ida y vuelta con Figma. +Los archivos guardados se comprimen e incluyen una imagen en miniatura para vista previa. + +### Compatibilidad de ida y vuelta + +Los archivos exportados desde OpenPencil se pueden abrir en Figma, y viceversa. El formato .fig preserva todos los tipos de nodos, propiedades, rellenos, trazos, efectos, datos vectoriales y configuración de layout. ## Consejos diff --git a/packages/docs/es/user-guide/index.md b/packages/docs/es/user-guide/index.md index 698fcb289..44ec67c45 100644 --- a/packages/docs/es/user-guide/index.md +++ b/packages/docs/es/user-guide/index.md @@ -9,7 +9,7 @@ description: Aprende a usar OpenPencil — navegación del lienzo, dibujo, texto OpenPencil es un editor de diseño open-source, compatible con Figma — completamente local, IA-nativo y programable. ::: tip Atajos multiplataforma -**⌘** = Command (Ctrl en Windows/Linux), **⌥** = Option (Alt), **⇧** = Shift. +⌘ = Command (Ctrl en Windows/Linux), ⌥ = Option (Alt), ⇧ = Shift. ::: ## Orientación @@ -31,6 +31,6 @@ OpenPencil es un editor de diseño open-source, compatible con Figma — complet ## Funciones avanzadas -- [Auto-layout](./auto-layout) — posicionamiento automático basado en flexbox +- [Auto-layout](./auto-layout) — posicionamiento automático de hijos usando reglas de flexbox - [Componentes](./components) — componentes reutilizables, instancias y overrides - [Variables](./variables) — variables de diseño, colecciones, modos diff --git a/packages/docs/es/user-guide/layers-and-pages.md b/packages/docs/es/user-guide/layers-and-pages.md index fd904f98e..5f9904f17 100644 --- a/packages/docs/es/user-guide/layers-and-pages.md +++ b/packages/docs/es/user-guide/layers-and-pages.md @@ -11,12 +11,12 @@ description: Gestionar capas, páginas y panel de propiedades en OpenPencil. - **Cambiar página** — clic en una pestaña - **Añadir** — botón añadir - **Eliminar** — eliminar página actual -- **Renombrar** — doble clic en el nombre; Enter o clic fuera para confirmar, Escape para cancelar +- **Renombrar** — doble clic en el nombre; Enter o clic fuera para confirmar, Escape para cancelar Cada página tiene su propio estado de viewport. ## Panel de propiedades -Tres pestañas: **Diseño** (propiedades contextuales), **Código** (JSX / Tailwind CSS v4), **IA** (chat ⌘ J). +Tres pestañas: **Diseño** (propiedades contextuales), **Código** (JSX / Tailwind CSS v4), **IA** (chat ⌘J). Diseño: apariencia, relleno, trazo, efectos, tipografía, layout, exportación. diff --git a/packages/docs/es/user-guide/pen-tool.md b/packages/docs/es/user-guide/pen-tool.md index a006dca20..55919fe1c 100644 --- a/packages/docs/es/user-guide/pen-tool.md +++ b/packages/docs/es/user-guide/pen-tool.md @@ -1,26 +1,35 @@ --- title: Herramienta pluma -description: Trazados vectoriales con curvas de Bézier in OpenPencil. +description: Trazados vectoriales con curvas de Bézier en OpenPencil. --- # Herramienta pluma +La herramienta pluma crea trazados vectoriales usando un modelo de redes vectoriales, compatible con el formato .fig de Figma. + ## Activación -**P** + +Pulsa P para activar la herramienta pluma. ## Colocar puntos -- **Click** — corner point -- **Click + drag** — curve point with Bézier tangent handles + +- **Clic** — punto de esquina (segmento recto) +- **Clic + arrastrar** — punto de curva con manejadores de tangente Bézier — la dirección y longitud del arrastre controlan la forma de la curva ## Cerrar un trazado -Click the first point to close into a loop. + +Haz clic en el **primer punto** del trazado para cerrarlo en un bucle. Los trazados cerrados se pueden rellenar. ## Trazados abiertos -**Escape** to commit as open path. + +Pulsa Escape para confirmar el trazado actual como trazado abierto. Los trazados abiertos se renderizan solo como trazos — no se rellenan. ## Redes vectoriales -Vector network data model, compatible with Figma `vectorNetworkBlob`. -| Action | Mac | Windows / Linux | +Los trazados en OpenPencil usan redes vectoriales — un modelo más flexible que las listas simples de puntos que soporta trazados ramificados y topología compleja. Es el mismo modelo que usa Figma, así que los trazados se mantienen perfectamente al abrir y guardar archivos .fig. + +## Atajos de teclado + +| Acción | Mac | Windows / Linux | |--------|-----|-----------------| -| Pen tool | P | P | -| Commit | Escape | Escape | +| Herramienta pluma | P | P | +| Confirmar trazado abierto | Escape | Escape | diff --git a/packages/docs/es/user-guide/selection-and-manipulation.md b/packages/docs/es/user-guide/selection-and-manipulation.md index e13c946f4..43baa5ed4 100644 --- a/packages/docs/es/user-guide/selection-and-manipulation.md +++ b/packages/docs/es/user-guide/selection-and-manipulation.md @@ -6,23 +6,23 @@ description: Seleccionar, mover, redimensionar, rotar y organizar nodos en OpenP ## Seleccionar - **Clic** en un nodo para seleccionarlo -- **Shift + clic** para añadir/quitar de la selección +- Shift + clic para añadir/quitar de la selección - **Arrastre de marquesina** — arrastra en el lienzo vacío -- **⌘ A** — seleccionar todo +- ⌘A — seleccionar todo - **Clic en lienzo vacío** — deseleccionar todo ## Mover - **Arrastrar** el nodo seleccionado -- **Flechas** — mover 1 px · **Shift + flechas** — 10 px +- **Flechas** — mover 1 px · Shift + flechas — 10 px ## Redimensionar -8 controles. **Shift + arrastrar** mantiene proporciones. +8 controles. Shift + arrastrar mantiene proporciones. ## Rotar -Pasa cerca de una esquina. **Shift** ajusta a 15°. +Pasa cerca de una esquina. Shift ajusta a 15°. ## Duplicar -- **Alt + arrastrar** — duplicar y mover · **⌘ D** — duplicar en su lugar +- Alt + arrastrar — duplicar y mover · ⌘D — duplicar en su lugar ## Eliminar **Retroceso** o **Supr** @@ -31,4 +31,4 @@ Pasa cerca de una esquina. **Shift** ajusta a 15°. **]** traer al frente · **[** enviar al fondo ## Visibilidad y bloqueo -**⇧ ⌘ H** visibilidad · **⇧ ⌘ L** bloqueo +⇧⌘H visibilidad · ⇧⌘L bloqueo diff --git a/packages/docs/es/user-guide/text-editing.md b/packages/docs/es/user-guide/text-editing.md index d29e39ef9..72ecfed96 100644 --- a/packages/docs/es/user-guide/text-editing.md +++ b/packages/docs/es/user-guide/text-editing.md @@ -4,28 +4,51 @@ description: Crear y editar texto con formato enriquecido en OpenPencil. --- # Edición de texto +Crea nodos de texto y edítalos directamente en el lienzo con soporte completo de texto enriquecido. + ## Crear texto -Pulsa **T**, luego haz clic en el lienzo. Empieza a escribir inmediatamente. + +Pulsa T para activar la herramienta de texto, luego haz clic en el lienzo. Aparece un nodo de texto vacío con un cursor parpadeante — empieza a escribir inmediatamente. ## Edición inline -Doble clic en un nodo de texto para entrar en modo edición. Clic fuera para confirmar. + +Doble clic en un nodo de texto para entrar en modo edición. Un contorno azul rodea el texto para indicar el modo edición. Clic fuera para confirmar y salir. + +El texto se renderiza directamente en el lienzo — no hay una capa de entrada de texto separada. ## Navegación del cursor + | Acción | Mac | Windows / Linux | |--------|-----|-----------------| -| Izquierda/derecha | ← / → | ← / → | -| Arriba/abajo | ↑ / ↓ | ↑ / ↓ | -| Por palabra | ⌥ ← / ⌥ → | Ctrl + ← / Ctrl + → | -| Inicio/fin de línea | ⌘ ← / ⌘ → | Inicio / Fin | +| Izquierda/derecha | ← / → | ← / → | +| Arriba/abajo | ↑ / ↓ | ↑ / ↓ | +| Por palabra | ⌥← / ⌥→ | Ctrl + ← / Ctrl + → | +| Inicio/fin de línea | ⌘← / ⌘→ | Home / End | -**Shift** extiende la selección. +Mantén Shift con cualquier tecla de movimiento para extender la selección. ## Formato enriquecido + +Aplica formato al texto seleccionado, o alterna el estilo para todo el nodo cuando no hay selección. + | Acción | Mac | Windows / Linux | |--------|-----|-----------------| -| Negrita | ⌘ B | Ctrl + B | -| Cursiva | ⌘ I | Ctrl + I | -| Subrayado | ⌘ U | Ctrl + U | +| Negrita | ⌘B | Ctrl + B | +| Cursiva | ⌘I | Ctrl + I | +| Subrayado | ⌘U | Ctrl + U | + +El formato se aplica por carácter. Cuando escribes entre un segmento en negrita y uno regular, el nuevo texto hereda el estilo del segmento anterior. ## Selector de fuentes -Búsqueda, vista previa y scroll virtual. Fuentes del sistema en desktop (Tauri), Local Font Access API en el navegador. + +Abre el selector de fuentes en la sección Tipografía del panel de propiedades para cambiar la familia tipográfica. Incluye: + +- **Filtro de búsqueda** — escribe para filtrar la lista de fuentes +- **Vista previa** — cada nombre de fuente se muestra con su propia tipografía +- **Scroll virtual** — maneja listas largas de fuentes eficientemente + +## Fuentes disponibles + +- **Fuente predeterminada** — Inter se carga automáticamente +- **App de escritorio** — todas las fuentes del sistema están disponibles +- **Navegador** — las fuentes del sistema están disponibles en Chrome y Edge diff --git a/packages/docs/eval-command.md b/packages/docs/eval-command.md deleted file mode 100644 index 9f7c45018..000000000 --- a/packages/docs/eval-command.md +++ /dev/null @@ -1,437 +0,0 @@ -# `open-pencil eval` — Figma-like Plugin API for Headless Scripting - -## Overview - -`bun open-pencil eval --code ''` 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 --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 = { - // 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 - - // Components (Phase 2) - createInstance(): FigmaNode - detachInstance(): void - get mainComponent(): FigmaNode | null -} -``` - -## CLI Command - -``` -bun open-pencil eval [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 () => { })()` -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/development/roadmap.md b/packages/docs/fr/development/roadmap.md index 0152d6a15..bd291099d 100644 --- a/packages/docs/fr/development/roadmap.md +++ b/packages/docs/fr/development/roadmap.md @@ -4,7 +4,7 @@ ### Phase 1 : Moteur Core ✅ -SceneGraph, rendu Skia, formes de base, sélection, zoom/pan, annuler/rétablir, guides d'alignement. +`SceneGraph`, rendu Skia, formes de base, sélection, zoom/pan, annuler/rétablir, guides d'alignement. ### Phase 2 : UI Éditeur + Layout ✅ @@ -16,7 +16,7 @@ Import/export .fig, codec Kiwi, presse-papiers, outil plume, réseaux vectoriels ### Phase 4 : Composants + Variables ✅ -Composants, instances, surcharges, jeux de composants, variables (COLOR/FLOAT/STRING/BOOLEAN), collections, modes, export d'images, menu contextuel, formatage de texte riche. +Composants, instances, surcharges, jeux de composants, variables (`COLOR`/FLOAT/STRING/BOOLEAN), collections, modes, export d'images, menu contextuel, formatage de texte riche. ### Phase 5 : Intégration IA & Outils ✅ @@ -24,7 +24,7 @@ Composants, instances, surcharges, jeux de composants, variables (COLOR/FLOAT/ST - @open-pencil/core extrait dans packages/core/ (aucune dépendance DOM) - @open-pencil/cli avec opérations headless .fig (info, tree, find, export, analyze, eval) - Commande `eval` avec API Plugin compatible Figma -- Chat IA : connexion directe OpenRouter, 87 outils dans `packages/core/src/tools/`, ⌘J +- Chat IA : connexion directe OpenRouter, 87 outils dans `packages/core/src/tools/`, ⌘J - 49 outils IA/MCP additionnels portés depuis figma-use (75 au total) - Serveur MCP (@open-pencil/mcp) : stdio + HTTP, 87 outils core + 3 gestion de fichiers - Définitions d'outils unifiées : définir une fois dans `packages/core/src/tools/`, adapter pour chat IA (valibot), MCP (zod), CLI (eval) @@ -44,7 +44,7 @@ Composants, instances, surcharges, jeux de composants, variables (COLOR/FLOAT/ST - Mode suivi : clic sur l'avatar d'un pair pour suivre son viewport - Persistance locale via y-indexeddb - Rendu des effets : ombre portée, ombre intérieure, flou de calque/arrière-plan/premier plan -- Onglets multi-fichiers : ⌘N/⌘T nouvel onglet, ⌘W fermer, ⌘O ouvrir +- Onglets multi-fichiers : ⌘N/⌘T nouvel onglet, ⌘W fermer, ⌘O ouvrir - Signature de code Apple et notarisation pour macOS - Builds Linux (x64) ajoutés au CI - Site de documentation VitePress avec i18n (6 langues) @@ -53,7 +53,7 @@ Composants, instances, surcharges, jeux de composants, variables (COLOR/FLOAT/ST - Prototypage (connexions de frames, transitions, animations) - Commentaires (pin, fils, résoudre) - Support PWA -- Changement de variantes, UI variables FLOAT/STRING/BOOLEAN, theming par variables +- Changement de variantes, UI variables `FLOAT`/STRING/BOOLEAN, theming par variables ## Calendrier diff --git a/packages/docs/fr/eval-command.md b/packages/docs/fr/eval-command.md deleted file mode 100644 index af7f3deb4..000000000 --- a/packages/docs/fr/eval-command.md +++ /dev/null @@ -1,77 +0,0 @@ -# `open-pencil eval` — API Plugin compatible Figma pour le scripting headless - -## Vue d'ensemble - -`bun open-pencil eval --code ''` exécute du JavaScript sur un fichier `.fig` avec un objet global `figma` compatible Figma. Cela permet le scripting headless, les opérations par lots, l'exécution d'outils IA et les tests — le tout sans interface graphique. - -L'objet `figma` reflète la surface de l'API Plugin de Figma aussi fidèlement que possible, de sorte que les connaissances existantes sur les plugins Figma et les extraits de code sont directement transférables. - -```bash -# Créer un cadre, définir l'auto-layout, ajouter des enfants -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.fills = [{ type: "SOLID", color: { r: 1, g: 1, b: 1 } }] - return { id: frame.id, name: frame.name } -' - -# Interroger les nœuds -bun open-pencil eval design.fig --code ' - const buttons = figma.currentPage.findAll(n => n.name.includes("Button")) - return buttons.map(b => ({ id: b.id, name: b.name })) -' - -# Écrire les modifications -bun open-pencil eval design.fig --code '...' --write -``` - -## Architecture - -``` -CLI: open-pencil eval --code '...' - → loadDocument(file) → SceneGraph - → FigmaAPI(sceneGraph) → proxy `figma` - → AsyncFunction('figma', code)(figmaProxy) - → afficher résultat / sauvegarder avec --write -``` - -### Classes principales - -| Classe | Emplacement | Rôle | -|--------|-------------|------| -| `FigmaAPI` | `packages/core/src/figma-api.ts` | Objet proxy implémentant les méthodes `figma.*` | -| `FigmaNode` | `packages/core/src/figma-api.ts` | Proxy enveloppant `SceneNode` avec accès propriétés style Figma | -| Commande `eval` | `packages/cli/src/commands/eval.ts` | Charge le document, crée l'API, exécute le code | - -### Pourquoi dans `@open-pencil/core` ? - -La classe `FigmaAPI` vit dans core car : les outils IA la réutilisent, les tests l'utilisent et elle n'a pas de dépendances DOM. - -## Commande CLI - -``` -bun open-pencil eval [options] - -Arguments : - file Fichier .fig sur lequel opérer - -Options : - --code, -c Code JavaScript à exécuter - --stdin Lire le code depuis stdin - --write, -w Écrire les modifications dans le fichier d'entrée - -o, --output Écrire dans un fichier différent - --json Sortie en JSON - --quiet, -q Supprimer la sortie -``` - -## Implémentation par phases - -- **Phase 1 : Core** — création de nœuds, propriétés, opérations d'arbre, auto-layout, texte (~80% des scripts réels) -- **Phase 2 : Composants & Instances** — createComponent, createInstance, detachInstance -- **Phase 3 : Variables** — getLocalVariables, createVariable, setBoundVariable -- **Phase 4 : Styles & Avancé** — styles paint/texte/effets, opérations booléennes - -[Référence API complète en anglais](/eval-command) diff --git a/packages/docs/fr/guide/architecture.md b/packages/docs/fr/guide/architecture.md index 5bcd19c4a..8e1ddee4e 100644 --- a/packages/docs/fr/guide/architecture.md +++ b/packages/docs/fr/guide/architecture.md @@ -2,7 +2,7 @@ ## Vue d'ensemble du système -```mermaid +`mermaid graph TB subgraph Tauri["Tauri v2 Shell"] subgraph Editor["Editor (Web)"] @@ -22,7 +22,7 @@ graph TB MCP["MCP Server (90 tools, stdio+HTTP)"] Collab["P2P Collab (Trystero + Yjs)"] end -``` +` ## Disposition de l'éditeur @@ -62,7 +62,7 @@ Yoga de Meta fournit le calcul de layout CSS flexbox. Un adaptateur fin mappe le ### Format de fichier (Kiwi binaire) -Réutilise le codec binaire Kiwi de Figma avec 194 définitions de message/enum/struct. Import : analyser l'en-tête → décompresser Zstd → décoder Kiwi → NodeChange[] → graphe de scène. L'export inverse le processus avec génération de miniature. +Réutilise le codec binaire Kiwi de Figma avec 194 définitions de message/enum/struct. Import : analyser l'en-tête → décompresser Zstd → décoder Kiwi → `NodeChange`[] → graphe de scène. L'export inverse le processus avec génération de miniature. Voir la [Référence du format de fichier](/reference/file-format) pour plus de détails. @@ -108,7 +108,7 @@ Transitions frame-à-frame, déclencheurs d'interaction (clic, survol, glissemen ### Layout CSS Grid -Yoga WASM ne supporte actuellement que le flexbox. CSS Grid est en développement en amont dans [facebook/yoga#1893](https://github.com/facebook/yoga/pull/1893). OpenPencil l'adoptera dès la sortie de la version Yoga correspondante. +CSS Grid est supporté via un [fork de Yoga](https://github.com/open-pencil/yoga/tree/grid) avec des PRs grid cherry-picked de l'upstream. Sélectionnez un frame, cliquez sur l'icône grille pour passer de flex à grid. Configurez les tracks colonnes/lignes (fr, px fixes, auto), les gaps colonnes et lignes, et le padding par côté. ### Signature de code Windows diff --git a/packages/docs/fr/guide/comparison.md b/packages/docs/fr/guide/comparison.md index 55fbfa330..cf09ff79e 100644 --- a/packages/docs/fr/guide/comparison.md +++ b/packages/docs/fr/guide/comparison.md @@ -229,7 +229,7 @@ Gestion d'état via Potok (bibliothèque Redux-like pour atomes ClojureScript). ## 11. Scripting et extensibilité -OpenPencil inclut une [commande `eval`](/eval-command) offrant une API Plugin compatible Figma pour le scripting headless. De plus, 90 outils IA sont disponibles via le chat intégré, le serveur MCP (stdio + HTTP) et le CLI. Penpot a un système de plugins avec exécution sandboxée mais pas d'API de scripting headless ni d'intégration MCP. +OpenPencil inclut une [commande `eval`](/programmable/cli/scripting) offrant une API Plugin compatible Figma pour le scripting headless. De plus, 90 outils IA sont disponibles via le chat intégré, le serveur MCP (stdio + HTTP) et le CLI. Penpot a un système de plugins avec exécution sandboxée mais pas d'API de scripting headless ni d'intégration MCP. ## Résumé diff --git a/packages/docs/fr/guide/features.md b/packages/docs/fr/guide/features.md index 819160621..df9392240 100644 --- a/packages/docs/fr/guide/features.md +++ b/packages/docs/fr/guide/features.md @@ -87,7 +87,7 @@ bun add -g @open-pencil/mcp } ``` -Voir la [référence des outils MCP](/reference/mcp-tools) pour la liste complète. +Voir la [référence des outils MCP](/programmable/mcp-server) pour la liste complète. ## CLI diff --git a/packages/docs/fr/guide/figma-comparison.md b/packages/docs/fr/guide/figma-comparison.md index 82140a757..20aa911ea 100644 --- a/packages/docs/fr/guide/figma-comparison.md +++ b/packages/docs/fr/guide/figma-comparison.md @@ -16,7 +16,7 @@ Comparaison fonctionnalité par fonctionnalité des capacités de Figma Design a | Panneau des calques (barre latérale gauche) | ✅ | Vue en arbre avec expansion/réduction, réordonnancement par glissement, toggle de visibilité ; largeur redimensionnable | | Panneau des pages | ✅ | Ajouter, supprimer, renommer des pages ; état viewport par page | | Panneau de propriétés (barre latérale droite) | ✅ | Sections : Apparence, Remplissage, Contour, Effets, Typographie, Layout, Position ; largeur redimensionnable | -| Zoom et défilement | ✅ | Ctrl+scroll, pinch, ⌘+/⌘−/⌘0, espace+glisser, souris milieu, outil main (H) | +| Zoom et défilement | ✅ | Ctrl + scroll, pinch, ⌘+ / ⌘− / ⌘0, espace+glisser, souris milieu, outil main (H) | | Règles du canevas | ✅ | Règles haut/gauche avec bandes de sélection et badges de coordonnées | | Couleur de fond du canevas | ✅ | Fond par page via le panneau de propriétés | | Guides du canevas | 🔲 | Figma supporte des guides glissables depuis les règles | @@ -36,7 +36,7 @@ Comparaison fonctionnalité par fonctionnalité des capacités de Figma Design a |---------------|--------|-------| | Outils de forme (Rectangle, Ellipse, Ligne, Polygone, Étoile) | ✅ | Tous les types de forme de base ; côtés du polygone et rayon intérieur de l'étoile configurables | | Frames | ✅ | Découpe du contenu, système de coordonnées indépendant | -| Groupes | ✅ | ⌘G pour grouper, ⇧⌘G pour dégrouper | +| Groupes | ✅ | ⌘G pour grouper, ⇧⌘G pour dégrouper | | Sections | ✅ | Pilules de titre, auto-adoption des nœuds superposés, texte adaptatif à la luminance | | Outil arc (arcs, demi-cercles, anneaux) | ✅ | arcData avec angle début/fin et rayon intérieur | | Outil crayon (main levée) | 🔲 | Outil de dessin à main levée de Figma | @@ -46,8 +46,8 @@ Comparaison fonctionnalité par fonctionnalité des capacités de Figma Design a | Alignement et position | ✅ | Position, rotation, dimensions dans le panneau | | Copier et coller des objets | ✅ | Presse-papiers standard + format binaire Kiwi de Figma | | Mettre à l'échelle proportionnellement | 🟡 | Shift-redimensionner contraint les proportions ; pas d'outil Scale dédié (K) | -| Verrouiller et déverrouiller des calques | ✅ | ⇧⌘L toggle le verrouillage | -| Basculer la visibilité | ✅ | Icône œil dans le panneau + raccourci ⇧⌘H | +| Verrouiller et déverrouiller des calques | ✅ | ⇧⌘L toggle le verrouillage | +| Basculer la visibilité | ✅ | Icône œil dans le panneau + raccourci ⇧⌘H | | Renommer des calques | ✅ | Double-clic renommage inline ; Entrée/Échap/clic pour valider | | Mettre au premier plan / Envoyer en arrière | ✅ | Raccourcis ] et [ ; aussi dans le menu contextuel | | Déplacer vers une page | ✅ | Déplacer les nœuds entre pages via menu contextuel | @@ -79,7 +79,7 @@ Comparaison fonctionnalité par fonctionnalité des capacités de Figma Design a | Fonctionnalité | Statut | Notes | |---------------|--------|-------| -| Outil texte et édition en ligne | ✅ | Édition native sur canevas, textarea phantom, style runs (⌘B/I/U, bouton S) | +| Outil texte et édition en ligne | ✅ | Édition native sur canevas, textarea phantom, style runs (⌘B / I / U, bouton S) | | Rendu de texte (Paragraph API) | ✅ | CanvasKit Paragraph pour le façonnage, les sauts de ligne, les métriques | | Chargement de polices (polices système) | ✅ | Inter par défaut, font-kit dans Tauri avec cache OnceLock, queryLocalFonts dans le navigateur | | Famille et graisse de police | ✅ | FontPicker avec défilement virtuel, recherche, aperçu CSS | @@ -126,7 +126,7 @@ Comparaison fonctionnalité par fonctionnalité des capacités de Figma Design a | Flou d'arrière-plan | ✅ | Flouter le contenu derrière le calque | | Flou de premier plan | ✅ | Flou au premier plan | | Épaisseur du contour | ✅ | Configurable dans le panneau de propriétés | -| Extrémité du contour (round, square, arrow) | ✅ | NONE, ROUND, SQUARE, ARROW_LINES, ARROW_EQUILATERAL | +| Extrémité du contour (round, square, arrow) | ✅ | `NONE`, `ROUND`, `SQUARE`, `ARROW_LINES`, `ARROW_EQUILATERAL` | | Jointure du contour (miter, bevel, round) | ✅ | Les trois types de jointure | | Motifs de tirets | ✅ | Motif de contour dash-on/dash-off | | Rayon de coin | ✅ | Rayon uniforme et par coin avec toggle indépendant | @@ -138,14 +138,14 @@ Comparaison fonctionnalité par fonctionnalité des capacités de Figma Design a | Fonctionnalité | Statut | Notes | |---------------|--------|-------| | Flux horizontal et vertical | ✅ | Moteur flexbox Yoga WASM | -| Basculer auto layout (⇧A) | ✅ | Basculer sur un frame ou envelopper la sélection | +| Basculer auto layout (⇧A) | ✅ | Basculer sur un frame ou envelopper la sélection | | Gap (espacement entre enfants) | ✅ | Configurable dans le panneau de propriétés | | Padding (uniforme et par côté) | ✅ | Les quatre côtés indépendamment | | Justify content | ✅ | Start, center, end, space-between | | Align items | ✅ | Start, center, end, stretch | | Dimensionnement des enfants (fixe, remplir, ajuster) | ✅ | Modes de dimensionnement par enfant | | Wrap | ✅ | Flex wrap pour layout multi-ligne | -| Flux auto layout en grille | 🔲 | Auto layout basé sur grille de Figma | +| Flux auto layout en grille | ✅ | CSS Grid via fork Yoga — tracks colonnes/lignes, gaps, spans | | Flux combinés (imbriqués) | ✅ | Frames auto-layout imbriqués avec directions différentes | | Réordonnancer par glissement dans auto layout | ✅ | Indicateur visuel d'insertion | | Largeur/hauteur min et max | 🔲 | Figma supporte les contraintes min/max | @@ -154,17 +154,17 @@ Comparaison fonctionnalité par fonctionnalité des capacités de Figma Design a | Fonctionnalité | Statut | Notes | |---------------|--------|-------| -| Créer des composants | 🟡 | ⌥⌘K crée depuis frame/groupe ; pas d'UI de propriétés de composant encore | -| Ensembles de composants | 🟡 | ⇧⌘K combine des composants ; bordure pointillée violette ; pas d'édition de propriétés de variante | +| Créer des composants | 🟡 | ⌥⌘K crée depuis frame/groupe ; pas d'UI de propriétés de composant encore | +| Ensembles de composants | 🟡 | ⇧⌘K combine des composants ; bordure pointillée violette ; pas d'édition de propriétés de variante | | Instances de composants | 🟡 | Créer instance depuis menu contextuel ; sync en direct ; pas d'UI d'édition de surcharges | | Variantes | 🔲 | Changement de variante et sélection par propriétés | | Propriétés de composant | 🔲 | Propriétés booléennes, texte, échange d'instance | | Propagation des surcharges | ✅ | Changements du composant principal propagés ; surcharges préservées | -| Variables (couleur, nombre, chaîne, booléen) | 🟡 | COLOR avec UI complète ; FLOAT/STRING/BOOLEAN définis sans UI d'édition | +| Variables (couleur, nombre, chaîne, booléen) | 🟡 | `COLOR` avec UI complète ; `FLOAT`/STRING/BOOLEAN définis sans UI d'édition | | Collections et modes de variables | 🟡 | Collections, modes, changement activeMode fonctionnent ; pas d'UI de thématisation | | Styles (couleur, texte, effet, layout) | 🔲 | Presets de style réutilisables nommés | | Bibliothèques (publier, partager, mettre à jour) | 🔲 | Bibliothèques partagées de composants/styles | -| Détacher une instance | ✅ | ⌥⌘B convertit une instance en frame | +| Détacher une instance | ✅ | ⌥⌘B convertit une instance en frame | | Aller au composant principal | ✅ | Naviguer vers le composant source, cross-page | ## Prototypage @@ -187,9 +187,9 @@ Comparaison fonctionnalité par fonctionnalité des capacités de Figma Design a | Fonctionnalité | Statut | Notes | |---------------|--------|-------| -| Import de fichier .fig | ✅ | Codec Kiwi complet : 194 définitions, ~390 champs par NodeChange | +| Import de fichier .fig | ✅ | Codec Kiwi complet : 194 définitions, ~390 champs par `NodeChange` | | Export de fichier .fig | ✅ | Encodage Kiwi + compression Zstd + génération de miniature | -| Enregistrer / Enregistrer sous | ✅ | ⌘S / ⇧⌘S ; dialogues natifs (Tauri), File System Access API (Chrome/Edge), téléchargement (Safari) | +| Enregistrer / Enregistrer sous | ✅ | ⌘S / ⇧⌘S ; dialogues natifs (Tauri), File System Access API (Chrome/Edge), téléchargement (Safari) | | Presse-papiers Figma (coller) | ✅ | Décoder binaire Kiwi du presse-papiers Figma | | Presse-papiers Figma (copier) | ✅ | Encoder binaire Kiwi lisible par Figma | | Import de fichier Sketch | 🔲 | Analyse de fichiers .sketch | diff --git a/packages/docs/fr/guide/tech-stack.md b/packages/docs/fr/guide/tech-stack.md index 234a0b71c..b5eb40041 100644 --- a/packages/docs/fr/guide/tech-stack.md +++ b/packages/docs/fr/guide/tech-stack.md @@ -60,4 +60,4 @@ Yoga est maintenu par Meta, éprouvé sur des milliards d'appareils React Native | Technologie | Objectif | Phase | |-----------|---------|-------| -| CSS Grid dans Yoga | Auto layout basé sur une grille | Bloqué en amont (facebook/yoga#1893) | +| CSS Grid dans Yoga | Auto layout basé sur une grille | ✅ Supporté via [fork Yoga](https://github.com/open-pencil/yoga/tree/grid) | diff --git a/packages/docs/fr/programmable/ai-chat.md b/packages/docs/fr/programmable/ai-chat.md new file mode 100644 index 000000000..ccaea411b --- /dev/null +++ b/packages/docs/fr/programmable/ai-chat.md @@ -0,0 +1,47 @@ +--- +title: Chat IA +description: Assistant IA intégré avec 87 outils pour créer et modifier des designs. +--- + +# Chat IA + +Appuyez sur ⌘J (Ctrl + J) pour ouvrir l'assistant IA. Décrivez ce que vous voulez — il crée des formes, définit des styles, gère la mise en page, travaille avec les composants et analyse votre design. + +## Configuration + +1. Ouvrez le panneau de chat IA (⌘J) +2. Cliquez sur l'icône de paramètres +3. Entrez votre clé API OpenRouter +4. Choisissez un modèle (Claude, GPT-4, Gemini, etc.) + +Pas de backend, pas d'abonnement — votre clé communique directement avec OpenRouter. + +## Ce qu'il peut faire + +L'assistant dispose de 87 outils répartis dans ces catégories : + +- **Créer** — frames, formes, texte, composants, pages. Rendu JSX pour les mises en page complexes. +- **Styliser** — remplissages, contours, effets, opacité, rayon d'arrondi, modes de fusion. +- **Mise en page** — auto-layout, alignement, espacement, dimensionnement. +- **Composants** — créer des composants, des instances, des ensembles de composants. Gérer les surcharges. +- **Variables** — créer/modifier des variables, des collections, des modes. Lier aux remplissages. +- **Requêter** — trouver des nœuds, lire des propriétés, lister les pages, les polices, la sélection. +- **Analyser** — palette de couleurs, audit typographique, cohérence de l'espacement, détection de motifs récurrents. +- **Exporter** — PNG, SVG, JSX avec classes Tailwind. +- **Vectoriel** — opérations booléennes, manipulation de chemins. + +## Exemples de prompts + +- « Créer une carte avec un titre, une description et un bouton bleu » +- « Faire en sorte que tous les boutons de cette page utilisent le même rayon d'arrondi » +- « Quelles polices sont utilisées dans ce fichier ? » +- « Changer l'arrière-plan du frame sélectionné en un dégradé du bleu au violet » +- « Exporter le frame sélectionné en SVG » +- « Trouver tous les nœuds de texte avec une taille de police inférieure à 12 » + +## Conseils + +- Sélectionnez des nœuds avant de poser votre question — l'assistant sait ce qui est sélectionné. +- Soyez précis sur les couleurs, tailles et positions pour des résultats exacts. +- L'assistant peut modifier plusieurs nœuds en un seul message. +- Utilisez « annuler » dans l'éditeur si le résultat ne vous convient pas. diff --git a/packages/docs/fr/programmable/cli/analyzing.md b/packages/docs/fr/programmable/cli/analyzing.md new file mode 100644 index 000000000..7c17eed6e --- /dev/null +++ b/packages/docs/fr/programmable/cli/analyzing.md @@ -0,0 +1,65 @@ +--- +title: Analyser des designs +description: Auditez les couleurs, la typographie, l'espacement et les motifs récurrents dans les fichiers .fig. +--- + +# Analyser des designs + +Les commandes `analyze` permettent d'auditer un système de design entier depuis le terminal — trouvez les incohérences, extrayez la vraie palette, repérez les composants qui attendent d'être extraits. + +## Couleurs + +```sh +open-pencil analyze colors design.fig +``` + +Trouve chaque couleur dans le fichier, compte les utilisations et affiche un histogramme visuel : + +``` +#1d1b20 ██████████████████████████████ 17155× +#49454f ██████████████████████████████ 9814× +#ffffff ██████████████████████████████ 8620× +#6750a4 ██████████████████████████████ 3967× +``` + +## Typographie + +```sh +open-pencil analyze typography design.fig +``` + +Liste chaque combinaison de famille de polices, taille et graisse avec le nombre d'utilisations. Utile pour repérer les styles de texte ponctuels qui devraient être consolidés. + +## Espacement + +```sh +open-pencil analyze spacing design.fig +``` + +Audite les valeurs de gap et de padding à travers les frames avec auto-layout. Aide à identifier les incohérences d'échelle d'espacement — par exemple, un gap de `13px` isolé parmi des valeurs de `8/16/24`. + +## Motifs récurrents + +```sh +open-pencil analyze clusters design.fig +``` + +Trouve les motifs de nœuds répétés qui pourraient être extraits en composants : + +``` +3771× frame "container" (100% match) + size: 40×40, structure: Frame > [Frame] + +2982× instance "Checkboxes" (100% match) + size: 48×48, structure: Instance > [Frame] +``` + +## Sortie JSON + +Toutes les commandes d'analyse supportent `--json` pour une sortie lisible par machine : + +```sh +open-pencil analyze colors design.fig --json +``` + +Redirigez vers `jq`, alimentez des vérifications CI, ou utilisez dans des scripts qui contrôlent les budgets de tokens de design. diff --git a/packages/docs/fr/programmable/cli/exporting.md b/packages/docs/fr/programmable/cli/exporting.md new file mode 100644 index 000000000..b8e95db39 --- /dev/null +++ b/packages/docs/fr/programmable/cli/exporting.md @@ -0,0 +1,59 @@ +--- +title: Exporter +description: Rendez des fichiers .fig en PNG, JPG, WEBP, SVG ou JSX avec classes Tailwind. +--- + +# Exporter + +Exportez des designs depuis le terminal — images raster, vecteurs ou code JSX. + +## Export d'images + +```sh +open-pencil export design.fig # PNG (par défaut) +open-pencil export design.fig -f jpg -s 2 -q 90 # JPG en 2×, qualité 90 +open-pencil export design.fig -f webp -s 3 # WEBP en 3× +open-pencil export design.fig -f svg # SVG vectoriel +``` + +Options : + +- `-f` — format : `png`, `jpg`, `webp`, `svg`, `jsx` +- `-s` — échelle : `1`–`4` +- `-q` — qualité : `0`–`100` (JPG/WEBP uniquement) +- `-o` — chemin de sortie +- `--page` — nom de la page +- `--node` — identifiant de nœud spécifique + +## Export JSX + +Exportez en JSX avec des classes utilitaires Tailwind : + +```sh +open-pencil export design.fig -f jsx --style tailwind +``` + +Résultat : + +```html +
+

Card Title

+

Description text

+
+``` + +Supporte aussi `--style openpencil` pour le format JSX natif (voir [Moteur de rendu JSX](../jsx-renderer)). + +## Miniatures + +```sh +open-pencil export design.fig --thumbnail --width 1920 --height 1080 +``` + +## Mode application en direct + +Omettez le fichier pour exporter depuis l'application en cours d'exécution : + +```sh +open-pencil export -f png # capture du canevas actuel +``` diff --git a/packages/docs/fr/programmable/cli/inspecting.md b/packages/docs/fr/programmable/cli/inspecting.md new file mode 100644 index 000000000..2236c0cd1 --- /dev/null +++ b/packages/docs/fr/programmable/cli/inspecting.md @@ -0,0 +1,98 @@ +--- +title: Inspecter des fichiers +description: Parcourez les arborescences de nœuds, recherchez par nom ou type, et examinez les propriétés depuis le terminal. +--- + +# Inspecter des fichiers + +Le CLI vous permet d'explorer des fichiers `.fig` sans ouvrir l'éditeur. Chaque commande fonctionne aussi sur l'application en cours d'exécution — il suffit d'omettre l'argument fichier. + +::: tip Installation +```sh +bun add -g @open-pencil/cli +# ou +brew install open-pencil/tap/open-pencil +``` +::: + +## Informations sur le document + +Obtenez un aperçu rapide — nombre de pages, nombre total de nœuds, polices utilisées, taille du fichier : + +```sh +open-pencil info design.fig +``` + +## Arborescence des nœuds + +Affichez la hiérarchie complète des nœuds : + +```sh +open-pencil tree design.fig +``` + +``` +[0] [page] "Getting started" (0:46566) + [0] [section] "" (0:46567) + [0] [frame] "Body" (0:46568) + [0] [frame] "Introduction" (0:46569) + [0] [frame] "Introduction Card" (0:46570) + [0] [frame] "Guidance" (0:46571) +``` + +## Trouver des nœuds + +Rechercher par type : + +```sh +open-pencil find design.fig --type TEXT +``` + +Rechercher par nom : + +```sh +open-pencil find design.fig --name "Button" +``` + +Les deux options peuvent être combinées pour affiner les résultats. + +## Détails d'un nœud + +Inspectez toutes les propriétés d'un nœud spécifique par son identifiant : + +```sh +open-pencil node design.fig --id 1:23 +``` + +## Pages + +Listez toutes les pages du document : + +```sh +open-pencil pages design.fig +``` + +## Variables + +Listez les variables de design et leurs collections : + +```sh +open-pencil variables design.fig +``` + +## Mode application en direct + +Quand l'application de bureau est en cours d'exécution, omettez l'argument fichier — le CLI se connecte via RPC et opère sur le canevas en direct : + +```sh +open-pencil tree # inspecter le document en direct +open-pencil eval -c "..." # interroger l'éditeur +``` + +## Sortie JSON + +Toutes les commandes supportent `--json` pour une sortie lisible par machine — redirigez vers `jq`, alimentez des scripts CI, ou traitez avec d'autres outils : + +```sh +open-pencil tree design.fig --json | jq '.[] | .name' +``` diff --git a/packages/docs/fr/programmable/cli/scripting.md b/packages/docs/fr/programmable/cli/scripting.md new file mode 100644 index 000000000..01862d3d1 --- /dev/null +++ b/packages/docs/fr/programmable/cli/scripting.md @@ -0,0 +1,70 @@ +--- +title: Scripter +description: Exécutez du JavaScript avec l'API Figma Plugin — interrogez des nœuds, modifiez des designs en lot, créez des frames. +--- + +# Scripter + +`open-pencil eval` vous donne accès à l'API complète Figma Plugin dans le terminal. Lisez des nœuds, modifiez des propriétés, créez des formes — puis écrivez les changements dans le fichier. + +## Utilisation de base + +```sh +open-pencil eval design.fig -c "figma.currentPage.children.length" +``` + +L'option `-c` prend du JavaScript. Le global `figma` fonctionne comme l'API Figma Plugin. + +## Interroger des nœuds + +```sh +open-pencil eval design.fig -c " + figma.currentPage.findAll(n => n.type === 'FRAME' && n.name.includes('Button')) + .map(b => ({ id: b.id, name: b.name, w: b.width, h: b.height })) +" +``` + +## Modifier et sauvegarder + +```sh +open-pencil eval design.fig -c " + figma.currentPage.children.forEach(n => n.opacity = 0.5) +" -w +``` + +`-w` écrit les changements dans le fichier d'entrée. Utilisez `-o output.fig` pour écrire dans un fichier différent. + +## Lire depuis l'entrée standard + +Pour des scripts plus longs : + +```sh +cat transform.js | open-pencil eval design.fig --stdin -w +``` + +## Mode application en direct + +Omettez le fichier pour exécuter sur l'application de bureau en cours d'exécution : + +```sh +open-pencil eval -c "figma.currentPage.name" +``` + +## API disponible + +L'objet `figma` supporte : + +- `figma.currentPage` — la page active +- `figma.root` — la racine du document +- `figma.createFrame()`, `figma.createRectangle()`, `figma.createEllipse()`, `figma.createText()`, etc. +- `.findAll()`, `.findOne()` — rechercher dans les descendants +- `.appendChild()`, `.insertChild()` — manipulation de l'arborescence +- Tous les setters de propriétés : `.fills`, `.strokes`, `.effects`, `.opacity`, `.cornerRadius`, `.layoutMode`, `.itemSpacing`, etc. + +C'est la même API que celle utilisée par les plugins Figma, donc les connaissances et les extraits de code existants sont directement transférables. + +## Sortie JSON + +```sh +open-pencil eval design.fig -c "..." --json +``` diff --git a/packages/docs/fr/programmable/collaboration.md b/packages/docs/fr/programmable/collaboration.md new file mode 100644 index 000000000..a6f6494f0 --- /dev/null +++ b/packages/docs/fr/programmable/collaboration.md @@ -0,0 +1,38 @@ +--- +title: Collaboration +description: Édition collaborative en temps réel via P2P WebRTC — sans serveur, sans compte. +--- + +# Collaboration + +Éditez des designs ensemble en temps réel. Les pairs se connectent directement — aucun serveur ne relaie vos données, aucun compte n'est requis. + +## Partager une salle + +1. Cliquez sur le bouton de partage dans le coin supérieur droit +2. Copiez le lien généré (`app.openpencil.dev/share/`) +3. Envoyez-le à vos collaborateurs + +Toute personne ayant le lien peut rejoindre la salle. La salle reste active tant qu'au moins un participant a la page ouverte. + +## Ce qui se synchronise + +- **Modifications du document** — chaque modification (formes, texte, propriétés, mise en page) se synchronise instantanément +- **Curseurs** — voyez où chaque collaborateur pointe, avec son nom et sa couleur +- **Sélections** — les sélections en surbrillance sont visibles par tous + +## Mode suivi + +Cliquez sur l'avatar d'un collaborateur dans la barre supérieure pour suivre son viewport. Votre canevas se déplace et zoome pour correspondre à sa vue. Cliquez à nouveau pour arrêter de suivre. + +## Comment ça fonctionne + +Les pairs se connectent directement via WebRTC — vos données de design passent directement d'un navigateur à l'autre, jamais par un serveur central. L'état du document utilise un CRDT (type de données répliqué sans conflit), donc les modifications concurrentes fusionnent automatiquement sans conflits. + +La salle persiste localement — si vous rafraîchissez la page, vous rejoignez avec le même état. + +## Conseils + +- Fonctionne dans le navigateur et l'application de bureau +- Les identifiants de salle sont cryptographiquement aléatoires — seules les personnes ayant le lien peuvent rejoindre +- Les curseurs obsolètes sont nettoyés automatiquement lorsqu'un participant se déconnecte diff --git a/packages/docs/fr/programmable/index.md b/packages/docs/fr/programmable/index.md new file mode 100644 index 000000000..337ac8731 --- /dev/null +++ b/packages/docs/fr/programmable/index.md @@ -0,0 +1,51 @@ +--- +layout: doc +title: IA et automatisation +description: Chaque opération dans OpenPencil est scriptable — chat IA, CLI, moteur de rendu JSX, serveur MCP, collaboration en temps réel. +--- + +# IA et automatisation + +OpenPencil traite les fichiers de design comme des données. Chaque opération disponible dans l'éditeur — créer des formes, définir des remplissages, gérer l'auto-layout, exporter des assets — est aussi disponible depuis le terminal, depuis des agents IA, et depuis du code. Pas de plugins à installer, pas de clés API, pas de liste d'attente. + +L'interface de l'éditeur et les interfaces d'automatisation utilisent le même moteur. Si vous pouvez le faire en cliquant, vous pouvez le faire en scriptant. + +## Chat IA + +L'assistant intégré a accès à 87 outils qui couvrent l'ensemble des fonctionnalités de l'éditeur. Décrivez ce que vous voulez en langage naturel — « ajouter une ombre portée de 16px à tous les boutons », « créer un composant carte avec une variante mode sombre », « exporter chaque frame de cette page en 2× ». + +[Chat IA →](./ai-chat) + +## Collaboration + +Édition multijoueur en temps réel via WebRTC pair-à-pair. Pas de serveur, pas de compte. Partagez un lien de salle et éditez ensemble avec des curseurs en direct et le mode suivi. L'état du document se synchronise via CRDT, donc les modifications fusionnent automatiquement même avec des connexions instables. + +[Collaboration →](./collaboration) + +## Moteur de rendu JSX + +Décrivez une interface en JSX — la même syntaxe que les LLMs connaissent déjà grâce à React. Un seul appel peut créer un arbre de composants complet avec des frames, du texte, de l'auto-layout, des remplissages et des contours. Compact, déclaratif et diffable. + +Dans l'autre sens, exportez n'importe quelle sélection en JSX avec des classes Tailwind — utile pour le transfert au développement ou pour renvoyer des designs dans un LLM. + +[Moteur de rendu JSX →](./jsx-renderer) + +## CLI + +Inspectez, exportez et analysez des fichiers `.fig` sans ouvrir l'éditeur. Listez les pages, recherchez des nœuds, extrayez des tokens de design, rendez en PNG — le tout depuis le terminal avec une sortie JSON lisible par machine. + +Le CLI se connecte aussi à l'application de bureau en cours d'exécution via RPC, ce qui permet de scripter l'éditeur pendant que vous l'utilisez. + +[Inspecter des fichiers](./cli/inspecting) · [Exporter](./cli/exporting) · [Analyser des designs](./cli/analyzing) · [Scripter](./cli/scripting) + +## Serveur MCP + +Connectez Claude Code, Cursor, Windsurf ou tout client compatible MCP à OpenPencil. Le serveur expose 90 outils pour lire, créer et modifier des designs — les mêmes outils que le chat IA intégré utilise. Fonctionne via stdio ou HTTP avec support de sessions. + +[Serveur MCP →](./mcp-server) + +## Pourquoi ouvert ? + +Figma est une plateforme fermée. Leur serveur MCP est en lecture seule. L'accès via CDP au navigateur a été supprimé dans la version 126. Les fichiers de design sont stockés dans un format propriétaire sur les serveurs de quelqu'un d'autre. Le développement de plugins nécessite un runtime personnalisé avec des API limitées. + +OpenPencil est l'alternative : open source, sous licence MIT, chaque opération scriptable, données stockées localement. Vos fichiers de design vous appartiennent — inspectez-les, transformez-les, intégrez-les dans votre CI, envoyez-les à un LLM. Aucune permission nécessaire. diff --git a/packages/docs/fr/programmable/jsx-renderer.md b/packages/docs/fr/programmable/jsx-renderer.md new file mode 100644 index 000000000..1a78b0227 --- /dev/null +++ b/packages/docs/fr/programmable/jsx-renderer.md @@ -0,0 +1,116 @@ +--- +title: Moteur de rendu JSX +description: Créez des designs avec JSX — la syntaxe que les LLMs connaissent déjà grâce à des millions de composants React. +--- + +# Moteur de rendu JSX + +OpenPencil utilise JSX comme langage de création de design. Les LLMs ont vu des millions de composants React — décrire une mise en page avec `` est naturel, aucun entraînement spécial nécessaire. Chaque token compte quand un agent IA effectue des dizaines d'opérations, et JSX est la représentation déclarative la plus compacte. + +JSX est aussi diffable. Quand une IA modifie un design, le changement est un diff JSX — lisible, vérifiable, versionnable. + +## Créer des designs + +L'outil `render` (disponible dans le chat IA, MCP et l'eval du CLI) accepte du JSX : + +```jsx + + Card Title + Description text + +``` + +Dans le serveur MCP et le chat IA, l'outil `render` accepte des chaînes JSX directement. Dans le CLI, utilisez la commande `export` pour aller dans l'autre sens — [exporter des designs en JSX](./cli/exporting). + +## Éléments + +Tous les types de nœuds sont disponibles en tant qu'éléments JSX : + +| Élément | Crée | Alias | +|---------|------|-------| +| `` | Frame (conteneur, supporte l'auto-layout) | `` | +| `` | Rectangle | `` | +| `` | Ellipse / cercle | | +| `` | Nœud texte (les enfants deviennent le contenu textuel) | | +| `` | Ligne | | +| `` | Étoile | | +| `` | Polygone | | +| `` | Chemin vectoriel | | +| `` | Groupe | | +| `
` | Section | | + +## Props de style + +Props raccourcies compactes inspirées des conventions de nommage de Tailwind. + +### Mise en page + +| Prop | Description | +|------|-------------| +| `flex` | `"row"` ou `"col"` — active l'auto-layout | +| `gap` | Espace entre les enfants | +| `wrap` | Retour à la ligne des enfants | +| `rowGap` | Espacement sur l'axe transversal lors du retour à la ligne | +| `justify` | `"start"`, `"end"`, `"center"`, `"between"` | +| `items` | `"start"`, `"end"`, `"center"`, `"stretch"` | +| `p`, `px`, `py`, `pt`, `pr`, `pb`, `pl` | Marges internes (padding) | + +### Taille et position + +| Prop | Description | +|------|-------------| +| `w`, `h` | Largeur/hauteur — nombre, `"fill"` ou `"hug"` | +| `minW`, `maxW`, `minH`, `maxH` | Contraintes de taille | +| `x`, `y` | Position | + +### Apparence + +| Prop | Description | +|------|-------------| +| `bg` | Remplissage d'arrière-plan (couleur hexadécimale) | +| `fill` | Alias pour `bg` | +| `stroke` | Couleur de contour | +| `strokeWidth` | Épaisseur du contour (par défaut : 1) | +| `rounded` | Rayon d'arrondi (ou `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`) | +| `cornerSmoothing` | Coins lisses style iOS (0–1) | +| `opacity` | 0–1 | +| `shadow` | Ombre portée (ex. `"0 4 8 #00000040"`) | +| `blur` | Rayon de flou du calque | +| `rotate` | Rotation en degrés | +| `blendMode` | Mode de fusion | +| `overflow` | `"hidden"` ou `"visible"` | + +### Typographie + +| Prop | Description | +|------|-------------| +| `size` / `fontSize` | Taille de police | +| `font` / `fontFamily` | Famille de polices | +| `weight` / `fontWeight` | `"bold"`, `"medium"`, `"normal"` ou nombre | +| `color` | Couleur du texte | +| `textAlign` | `"left"`, `"center"`, `"right"`, `"justified"` | + +## Exporter en JSX + +Convertissez des designs existants en JSX : + +```sh +open-pencil export design.fig -f jsx # Format OpenPencil +open-pencil export design.fig -f jsx --style tailwind # Classes Tailwind +``` + +L'aller-retour fonctionne : exportez un design en JSX, modifiez le code, rendez-le à nouveau. + +## Diff visuel + +Comme les designs sont représentables en JSX, les changements deviennent des diffs de code : + +```diff + +- Old Title ++ New Title + Description + +``` + +Cela rend les changements de design vérifiables dans les pull requests, traçables dans le contrôle de version, et auditables dans la CI. diff --git a/packages/docs/fr/programmable/mcp-server.md b/packages/docs/fr/programmable/mcp-server.md new file mode 100644 index 000000000..e296a6447 --- /dev/null +++ b/packages/docs/fr/programmable/mcp-server.md @@ -0,0 +1,251 @@ +# 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` + +Security defaults (HTTP transport): + +- Binds to `127.0.0.1` by default (`HOST` to override) +- `eval` tool is disabled +- File operations are limited to `OPENPENCIL_MCP_ROOT` (defaults to current working directory) +- CORS is disabled by default; set `OPENPENCIL_MCP_CORS_ORIGIN` to allow one origin +- Optional auth token: `OPENPENCIL_MCP_AUTH_TOKEN` (client sends `Authorization: Bearer ` or `x-mcp-token`) + +Server 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` + +## AI Agent Skill + +Teach your AI coding agent to use OpenPencil tools: + +```sh +npx skills add open-pencil/skills@open-pencil +``` + +Works with Claude Code, Cursor, Windsurf, Codex, and any agent that supports [skills](https://skills.sh). The skill covers the CLI, MCP tools, JSX rendering, eval, and the running app's automation bridge. + +## Tools (90) + +### 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_current_page` | Get the current page name and ID | +| `get_node` | Get detailed properties of a node by ID | +| `find_nodes` | Find nodes by name pattern and/or type | +| `get_components` | List all components in the document | +| `list_pages` | List all pages | +| `list_variables` | List design variables | +| `list_collections` | List variable collections | +| `list_fonts` | List fonts used in the current page | +| `page_bounds` | Get bounding box of all objects on the current page | +| `node_bounds` | Get bounding box of a node | +| `node_ancestors` | Get ancestor chain of a node | +| `node_children` | Get direct children of a node | +| `node_tree` | Get the subtree rooted at a node | +| `node_bindings` | Get variable bindings on a node | + +### Create + +| Tool | Description | +|------|-------------| +| `create_shape` | Create a shape (`FRAME`, `RECTANGLE`, `ELLIPSE`, `TEXT`, `LINE`, `STAR`, `POLYGON`, `SECTION`) | +| `create_vector` | Create a vector node from a path string | +| `create_slice` | Create an export slice | +| `create_page` | Create a new page | +| `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 | +| `node_to_component` | Convert an existing node into a component in-place | + +### 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 | +| `set_rotation` | Set rotation angle in degrees | +| `set_opacity` | Set opacity (0–1) | +| `set_radius` | Set corner radius (uniform or per-corner) | +| `set_minmax` | Set min/max width and height constraints | +| `set_text` | Set text content of a `TEXT` node | +| `set_font` | Set font family and weight | +| `set_font_range` | Set font properties on a character range | +| `set_text_resize` | Set text auto-resize mode (fixed/auto-width/auto-height) | +| `set_visible` | Show or hide a node | +| `set_blend` | Set blend mode | +| `set_locked` | Lock or unlock a node | +| `set_stroke_align` | Set stroke alignment (inside/center/outside) | +| `set_text_properties` | Set text layout: alignment, auto-resize, text case, decoration, truncation | +| `set_layout_child` | Configure auto-layout child: sizing, grow, alignment, absolute positioning | +| `node_move` | Move a node to a new position | +| `node_resize` | Resize a node | +| `node_replace_with` | Replace a node with another node | +| `arrange` | Align or distribute selected nodes | + +### 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 | +| `flatten_nodes` | Flatten nodes into a single vector | +| `boolean_union` | Boolean union of two or more nodes | +| `boolean_subtract` | Boolean subtraction | +| `boolean_intersect` | Boolean intersection | +| `boolean_exclude` | Boolean exclusion | + +### Vector Path + +| Tool | Description | +|------|-------------| +| `path_get` | Get the path data of a vector node | +| `path_set` | Set the path data of a vector node | +| `path_scale` | Scale a vector path | +| `path_flip` | Flip a vector path horizontally or vertically | +| `path_move` | Translate a vector path | + +### Export + +| Tool | Description | +|------|-------------| +| `export_image` | Export nodes as PNG, JPG, or WEBP. Returns base64-encoded image data | +| `export_svg` | Export nodes as SVG markup | + +### Viewport + +| Tool | Description | +|------|-------------| +| `viewport_get` | Get current viewport position and zoom level | +| `viewport_set` | Set viewport position and zoom | +| `viewport_zoom_to_fit` | Zoom viewport to fit specified nodes | + +### Variables + +| Tool | Description | +|------|-------------| +| `get_variable` | Get a variable by ID or name | +| `find_variables` | Find variables by name pattern or type | +| `create_variable` | Create a new variable in a collection | +| `set_variable` | Set a variable value in a mode | +| `delete_variable` | Delete a variable | +| `bind_variable` | Bind a variable to a node property | +| `get_collection` | Get a variable collection by ID or name | +| `create_collection` | Create a new variable collection | +| `delete_collection` | Delete a variable collection | + +### Analyze + +| Tool | Description | +|------|-------------| +| `analyze_colors` | Analyze color palette usage across the document | +| `analyze_typography` | Analyze font/size/weight distribution | +| `analyze_spacing` | Analyze gap and padding values | +| `analyze_clusters` | Detect repeated patterns (potential components) | + +### Diff + +| Tool | Description | +|------|-------------| +| `diff_create` | Create a snapshot of the current document state | +| `diff_show` | Show differences between the current state and a snapshot | + +### 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 | + +Note: `eval` is available over stdio, but disabled in HTTP mode for security. diff --git a/packages/docs/fr/reference/cli.md b/packages/docs/fr/reference/cli.md new file mode 100644 index 000000000..6f83df440 --- /dev/null +++ b/packages/docs/fr/reference/cli.md @@ -0,0 +1,184 @@ +--- +title: CLI Reference +description: Complete reference for all open-pencil commands, options, and flags. +--- + +# CLI Reference + +All commands accept a `.fig` file as a positional argument. When omitted, the CLI connects to the running desktop app via RPC. + +## info + +Show document info — pages, node counts, fonts, file size. + +```sh +open-pencil info [file] [--json] +``` + +| Option | Description | +|--------|-------------| +| `--json` | Output as JSON | + +## tree + +Print the node hierarchy. + +```sh +open-pencil tree [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--page` | Page name (default: first page) | +| `--depth` | Max depth (default: unlimited) | +| `--json` | Output as JSON | + +## find + +Search nodes by name or type. + +```sh +open-pencil find [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--name` | Node name (partial match, case-insensitive) | +| `--type` | Node type: `FRAME`, `TEXT`, `RECTANGLE`, `INSTANCE`, etc. | +| `--page` | Page name (default: all pages) | +| `--limit` | Max results (default: 100) | +| `--json` | Output as JSON | + +## node + +Show detailed properties of a node. + +```sh +open-pencil node [file] --id [--json] +``` + +| Option | Description | +|--------|-------------| +| `--id` | **Required.** Node ID (e.g. `1:23`) | +| `--json` | Output as JSON | + +## pages + +List all pages in the document. + +```sh +open-pencil pages [file] [--json] +``` + +| Option | Description | +|--------|-------------| +| `--json` | Output as JSON | + +## variables + +List design variables and collections. + +```sh +open-pencil variables [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--collection` | Filter by collection name | +| `--type` | Filter by type: `COLOR`, `FLOAT`, `STRING`, `BOOLEAN` | +| `--json` | Output as JSON | + +## export + +Export to PNG, JPG, WEBP, SVG, or JSX. + +```sh +open-pencil export [file] [options] +``` + +| Option | Alias | Description | +|--------|-------|-------------| +| `--format` | `-f` | `png` (default), `jpg`, `webp`, `svg`, `jsx` | +| `--output` | `-o` | Output file path (default: `.`) | +| `--scale` | `-s` | Export scale (default: 1) | +| `--quality` | `-q` | Quality 0–100, JPG/WEBP only (default: 90) | +| `--page` | | Page name (default: first page) | +| `--node` | | Node ID to export (default: all top-level nodes) | +| `--style` | | JSX style: `openpencil` (default), `tailwind` | +| `--thumbnail` | | Export page thumbnail instead of full render | +| `--width` | | Thumbnail width (default: 1920) | +| `--height` | | Thumbnail height (default: 1080) | + +## eval + +Execute JavaScript with the Figma Plugin API. + +```sh +open-pencil eval [file] [options] +``` + +| Option | Alias | Description | +|--------|-------|-------------| +| `--code` | `-c` | JavaScript code to execute | +| `--stdin` | | Read code from stdin | +| `--write` | `-w` | Write changes back to the input file | +| `--output` | `-o` | Write to a different file | +| `--json` | | Output as JSON | +| `--quiet` | `-q` | Suppress output | + +## analyze colors + +Analyze color palette usage across the document. + +```sh +open-pencil analyze colors [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--limit` | Max colors to show (default: 30) | +| `--threshold` | Distance threshold for clustering similar colors, 0–50 (default: 15) | +| `--similar` | Show similar color clusters | +| `--json` | Output as JSON | + +## analyze typography + +Analyze font family, size, and weight distribution. + +```sh +open-pencil analyze typography [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--group-by` | Group by: `family`, `size`, `weight` (default: show all styles) | +| `--limit` | Max styles to show (default: 30) | +| `--json` | Output as JSON | + +## analyze spacing + +Analyze gap and padding values across auto-layout frames. + +```sh +open-pencil analyze spacing [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--grid` | Base grid size to check against (default: 8) | +| `--json` | Output as JSON | + +## analyze clusters + +Find repeated node patterns — potential components. + +```sh +open-pencil analyze clusters [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--limit` | Max clusters to show (default: 20) | +| `--min-size` | Min node size in px (default: 30) | +| `--min-count` | Min instances to form a cluster (default: 2) | +| `--json` | Output as JSON | diff --git a/packages/docs/fr/reference/file-format.md b/packages/docs/fr/reference/file-format.md index 2b34f6680..ea94b8fb6 100644 --- a/packages/docs/fr/reference/file-format.md +++ b/packages/docs/fr/reference/file-format.md @@ -1,71 +1,72 @@ -# Format de fichier +# File Format -## Structure des fichiers .fig +## .fig File Structure + +A `.fig` file is a ZIP archive containing a Kiwi-encoded binary message: + +| Offset | Content | +|--------|---------| +| 0 | Magic header `fig-kiwi` (8 bytes) | +| 8 | Version (4 bytes, uint32 LE) | +| 12 | Schema length (4 bytes, uint32 LE) | +| 16 | Compressed Kiwi schema | +| … | Message length (4 bytes, uint32 LE) | +| … | Compressed Kiwi message — `NodeChange[]` (entire document) | +| … | Blob data — images, vector networks, fonts | + +## Import Pipeline ``` -┌─────────────────────────────────┐ -│ 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 -└─────────────────────────────────┘ +.fig file → parse header → decompress Zstd → decode Kiwi schema + → decode message → NodeChange[] → build SceneGraph + → resolve blob refs → render on canvas ``` -## Pipeline d'importation +## Export Pipeline ``` -.fig file → Parse header → Decompress Zstd → Decode Kiwi schema - → Decode Message → NodeChange[] → Build SceneGraph - → Resolve blob refs → Render on canvas +SceneGraph → NodeChange[] → Kiwi encode → compress (Zstd/deflate) + → build ZIP (header + schema + message + thumbnail.png) + → write .fig file ``` -## Pipeline d'exportation +Export uses ⌘S (Save) and ⇧⌘S (Save As) with native OS dialogs on the desktop app. The exported file includes a `thumbnail.png` required by Figma for file preview. -``` -SceneGraph → NodeChange[] → Kiwi encode → Compress (Zstd/deflate) - → Build ZIP (header + schema + message + thumbnail.png) - → Write .fig file -``` - -Export uses ⌘S (Save) and ⇧⌘S (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). +Compression uses Zstd via Tauri Rust command on desktop, with deflate fallback in the browser. ## Kiwi Binary Codec -The codec handles Figma's 194-definition Kiwi schema with NodeChange as the central type (~390 fields). Key components: +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 +| Module | Purpose | +|--------|---------| +| `kiwi-schema` | Kiwi parser (from [evanw/kiwi](https://github.com/nicolo-ribaudo/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. +Figma's schema uses non-contiguous field IDs (e.g. 1, 2, 5, 10 with gaps). The kiwi-schema parser handles 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`. +`.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. ## Supported Formats | Format | Import | Export | |--------|--------|--------| -| .fig (Figma) | ✅ | ✅ | -| .svg | Planned | Planned | -| .png | Planned | Planned | -| .pdf | — | Planned | - -See [Roadmap](/development/roadmap) for planned format support timeline. +| `.fig` (Figma) | ✅ | ✅ | +| `.svg` | Planned | Planned | +| `.png` | Planned | Planned | +| `.pdf` | — | Planned | ## 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 +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. +Encoding happens synchronously in the copy event handler (not async Clipboard API) for browser compatibility. This enables bidirectional clipboard between OpenPencil and Figma. diff --git a/packages/docs/fr/reference/mcp-tools.md b/packages/docs/fr/reference/mcp-tools.md deleted file mode 100644 index 1fa75b008..000000000 --- a/packages/docs/fr/reference/mcp-tools.md +++ /dev/null @@ -1,150 +0,0 @@ -# Serveur MCP - -OpenPencil inclut un serveur MCP (Model Context Protocol) qui permet aux outils de coding IA — Claude Code, Cursor, Windsurf etc. — de lire et modifier des fichiers .fig en headless. - -Deux transports - -## **stdio** pour les clients MCP, **HTTP** pour tout le reste. - -```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" - } - } -} -``` - -Ou exécuter depuis les sources : - -::: 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` - -## AI Agent Skill - -Install the OpenPencil skill for your AI coding agent: - -```sh -npx skills add open-pencil/skills@open-pencil -``` - -Works with Claude Code, Cursor, Windsurf, Codex, and any agent that supports [skills](https://skills.sh). - -## Tools (75) - -### 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.md index 3b4b57fee..f6024302d 100644 --- a/packages/docs/fr/reference/node-types.md +++ b/packages/docs/fr/reference/node-types.md @@ -1,4 +1,4 @@ -# Types de nœuds +# Node Types 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. @@ -8,41 +8,41 @@ The scene graph supports 28 node types from Figma's Kiwi schema. Each node is id | 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) | ✅ | +| `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) +- `COMPONENT_SET` → variant group container (no dedicated Kiwi ID, mapped from `SYMBOL` with variants) - `POLYGON` → Kiwi `REGULAR_POLYGON` (ID 11) ```typescript @@ -81,14 +81,14 @@ Document ## Core Properties -Every node carries these fields (subset of NodeChange): +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 +- `phase` — `CREATED` or `REMOVED` - `parentIndex` — parent GUID + position string for z-ordering ### Transform @@ -103,14 +103,14 @@ Every node carries these fields (subset of NodeChange): - `strokePaints[]` — stroke colors - `effects[]` — shadows, blurs - `opacity` — 0–1 -- `blendMode` — NORMAL, MULTIPLY, SCREEN, etc. +- `blendMode` — `NORMAL`, `MULTIPLY`, `SCREEN`, etc. ### Stroke - `strokeWeight` — stroke thickness -- `strokeAlign` — inside / center / outside -- `strokeCap` — butt / round / square -- `strokeJoin` — miter / bevel / round +- `strokeAlign` — `INSIDE` / `CENTER` / `OUTSIDE` +- `strokeCap` — `NONE` / `ROUND` / `SQUARE` / `ARROW_LINES` / `ARROW_EQUILATERAL` +- `strokeJoin` — `MITER` / `BEVEL` / `ROUND` - `dashPattern[]` — dash/gap lengths ### Corners diff --git a/packages/docs/fr/reference/scene-graph.md b/packages/docs/fr/reference/scene-graph.md index 17c302c4e..0d445d189 100644 --- a/packages/docs/fr/reference/scene-graph.md +++ b/packages/docs/fr/reference/scene-graph.md @@ -1,8 +1,8 @@ -# Graphe de scène +# Scene Graph -## Représentation en mémoire +## In-Memory Representation -Les nœuds vivent dans une Map plate `Map` keyed by GUID string. La structure arborescente est maintenue via `parentIndex` references. This gives Recherche O(1) by ID and efficient traversal. +Nodes live in a flat `Map` 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 { @@ -31,11 +31,11 @@ interface SceneGraph { ## 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. +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. +`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 @@ -86,11 +86,11 @@ For marquee selection, `getNodesInRect` returns all nodes whose bounds intersect ## 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). +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. +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 diff --git a/packages/docs/fr/user-guide/auto-layout.md b/packages/docs/fr/user-guide/auto-layout.md index 1347b837b..66077c52a 100644 --- a/packages/docs/fr/user-guide/auto-layout.md +++ b/packages/docs/fr/user-guide/auto-layout.md @@ -4,7 +4,9 @@ description: Mise en page auto basée sur flexbox dans OpenPencil. --- # Mise en page auto -**⇧ A** pour activer/désactiver ou envelopper la sélection. +La mise en page auto positionne automatiquement les enfants dans un cadre selon les règles flexbox. Elle gère la direction, l'espacement, l'alignement et le dimensionnement adaptatif. + +⇧A pour activer/désactiver ou envelopper la sélection. ## Direction - **Horizontale** — de gauche à droite diff --git a/packages/docs/fr/user-guide/canvas-navigation.md b/packages/docs/fr/user-guide/canvas-navigation.md index 92f3696d1..f7e98361d 100644 --- a/packages/docs/fr/user-guide/canvas-navigation.md +++ b/packages/docs/fr/user-guide/canvas-navigation.md @@ -9,23 +9,23 @@ Le canevas est votre espace de travail infini. ## Panoramique -- **Espace + glisser** — maintenez Espace et glissez +- Espace + glisser — maintenez Espace et glissez - **Bouton central de la souris** — cliquez et glissez - **Trackpad à deux doigts** — glissez avec deux doigts ## Outil main -Appuyez sur **H** pour activer l'outil main. Changez d'outil (ex. **V**) pour désactiver. +Appuyez sur H pour activer l'outil main. Changez d'outil (ex. **V**) pour désactiver. ## Zoom -- **Ctrl + molette** (ou **⌘ + molette** sur Mac) — zoom avant/arrière +- Ctrl + molette (ou ⌘ + molette sur Mac) — zoom avant/arrière - **Geste de pincement** — pincez sur le trackpad | Action | Mac | Windows / Linux | |--------|-----|-----------------| -| Panoramique | Espace + glisser | Espace + glisser | -| Outil main | H | H | -| Zoom avant | ⌘ + | Ctrl + + | -| Zoom arrière | ⌘ - | Ctrl + - | -| Zoom 100% | ⌘ 0 | Ctrl + 0 | +| Panoramique | Espace + glisser | Espace + glisser | +| Outil main | H | H | +| Zoom avant | ⌘+ | Ctrl + + | +| Zoom arrière | ⌘− | Ctrl + − | +| Zoom 100% | ⌘0 | Ctrl + 0 | diff --git a/packages/docs/fr/user-guide/components.md b/packages/docs/fr/user-guide/components.md index 4e1f574e3..e0b6734a1 100644 --- a/packages/docs/fr/user-guide/components.md +++ b/packages/docs/fr/user-guide/components.md @@ -5,19 +5,19 @@ description: Composants réutilisables, instances, surcharges et synchronisation # Composants ## Créer un composant -**⌥ ⌘ K** (Ctrl+Alt+K) — convertit cadre/groupe en COMPONENT. Étiquette violette avec diamant. +⌥⌘K (Ctrl + Alt + K) — convertit un cadre ou un groupe en composant réutilisable. Une étiquette violette avec un losange apparaît au-dessus. ## Jeux de composants -**⇧ ⌘ K** — combine 2+ composants avec bordure violette en pointillés. +⇧⌘K — combine deux composants ou plus dans un conteneur avec une bordure violette en pointillés. ## Créer des instances -Clic droit → **Créer une instance**. Apparaît 40 px à droite. +Clic droit → **Créer une instance**. L'instance apparaît à droite du composant source. ## Détacher une instance -**⌥ ⌘ B** — devient un cadre sans lien. +⌥⌘B — devient un cadre sans lien. ## Synchronisation live -Modifier un composant met à jour toutes ses instances. Propriétés synchronisées : dimensions, remplissages, contours, effets, opacité, rayons des coins, mise en page. +Modifier un composant met à jour automatiquement toutes ses instances. Les propriétés synchronisées incluent les dimensions, les couleurs, les contours, les effets, l'opacité, les coins arrondis et la mise en page. ## Surcharges Les instances peuvent surcharger des propriétés sans rompre le lien. @@ -27,6 +27,6 @@ Clic sélectionne le composant. **Double-clic** pour entrer et sélectionner les | Action | Mac | Windows / Linux | |--------|-----|-----------------| -| Créer composant | ⌥ ⌘ K | Ctrl + Alt + K | -| Créer jeu | ⇧ ⌘ K | Shift + Ctrl + K | -| Détacher instance | ⌥ ⌘ B | Ctrl + Alt + B | +| Créer composant | ⌥⌘K | Ctrl + Alt + K | +| Créer jeu | ⇧⌘K | Shift + Ctrl + K | +| Détacher instance | ⌥⌘B | Ctrl + Alt + B | diff --git a/packages/docs/fr/user-guide/context-menu.md b/packages/docs/fr/user-guide/context-menu.md index 856f3e006..ea2a735c0 100644 --- a/packages/docs/fr/user-guide/context-menu.md +++ b/packages/docs/fr/user-guide/context-menu.md @@ -14,23 +14,23 @@ Le sous-menu **Copier en tant que** offre ces formats : |--------|-----|-----------------| | Copier en tant que texte | — | — | | Copier en tant que SVG | — | — | -| Copier en tant que PNG | ⇧ ⌘ C | Shift + Ctrl + C | +| Copier en tant que PNG | ⇧⌘C | Shift + Ctrl + C | | Copier en tant que JSX | — | — | ## Presse-papiers -Copier (⌘C), Couper (⌘X), Coller (⌘V), Dupliquer (⌘D), Supprimer (⌫) +Copier (⌘C), Couper (⌘X), Coller (⌘V), Dupliquer (⌘D), Supprimer (⌫) ## Ordre Z **]** au premier plan · **[** à l'arrière-plan ## Groupement -Grouper (⌘G), Dégrouper (⇧⌘G), Ajouter mise en page auto (⇧A) +Grouper (⌘G), Dégrouper (⇧⌘G), Ajouter mise en page auto (⇧A) ## Composants -Créer composant (⌥⌘K), Créer jeu de composants (⇧⌘K), Créer instance, Aller au composant principal, Détacher instance (⌥⌘B). Actions en violet. +Créer composant (⌥⌘K), Créer jeu de composants (⇧⌘K), Créer instance, Aller au composant principal, Détacher instance (⌥⌘B). Actions en violet. ## Visibilité et verrouillage -Masquer/Afficher (⇧⌘H), Verrouiller/Déverrouiller (⇧⌘L) +Masquer/Afficher (⇧⌘H), Verrouiller/Déverrouiller (⇧⌘L) ## Déplacer vers la page Sous-menu avec toutes les pages sauf la page courante. diff --git a/packages/docs/fr/user-guide/drawing-shapes.md b/packages/docs/fr/user-guide/drawing-shapes.md index 922cea1ca..7b27a3765 100644 --- a/packages/docs/fr/user-guide/drawing-shapes.md +++ b/packages/docs/fr/user-guide/drawing-shapes.md @@ -6,17 +6,17 @@ description: Créer des rectangles, ellipses, lignes, cadres et sections dans Op | Outil | Raccourci | Description | |-------|-----------|-------------| -| Rectangle | R | Dessine un rectangle | -| Ellipse | O | Dessine une ellipse | -| Ligne | L | Dessine une ligne | -| Cadre | F | Dessine un cadre (conteneur) | -| Section | S | Dessine une section | +| Rectangle | R | Dessine un rectangle | +| Ellipse | O | Dessine une ellipse | +| Ligne | L | Dessine une ligne | +| Cadre | F | Dessine un cadre (conteneur) | +| Section | S | Dessine une section | ## Formes supplémentaires **Polygone** et **Étoile** dans le menu déroulant des formes. ## Dessin contraint -**Shift** pendant le glissement : rectangle → carré, ellipse → cercle, ligne → 0°/45°/90°. +Shift pendant le glissement : rectangle → carré, ellipse → cercle, ligne → 0°/45°/90°. ## Propriétés - **Remplissage** — couleur unie, dégradé (linéaire, radial, angulaire, diamant), image diff --git a/packages/docs/fr/user-guide/exporting.md b/packages/docs/fr/user-guide/exporting.md index 98679907c..acd9fd87c 100644 --- a/packages/docs/fr/user-guide/exporting.md +++ b/packages/docs/fr/user-guide/exporting.md @@ -17,8 +17,8 @@ Sélectionnez un nœud et utilisez la section Export dans le panneau de proprié | Méthode | Mac | Windows / Linux | |--------|-----|-----------------| -| Raccourci clavier | ⇧ ⌘ E | Shift + Ctrl + E | -| Menu contextuel | Clic droit → Exporter… | Clic droit → Exporter… | +| Raccourci clavier | ⇧⌘E | Shift + Ctrl + E | +| Menu contextuel | Clic droit → Exporter… | Clic droit → Exporter… | | Panneau propriétés | Bouton "Exporter" | Bouton "Exporter" | ## Copier en tant que @@ -29,18 +29,18 @@ Le menu contextuel **Copier en tant que** offre des formats supplémentaires : |--------|-----|-----------------| | Copier en tant que texte | — | — | | Copier en tant que SVG | — | — | -| Copier en tant que PNG | ⇧ ⌘ C | Shift + Ctrl + C | +| Copier en tant que PNG | ⇧⌘C | Shift + Ctrl + C | | Copier en tant que JSX | — | — | ## Opérations de fichier .fig | Action | Mac | Windows / Linux | |--------|-----|-----------------| -| Ouvrir | ⌘ O | Ctrl + O | -| Enregistrer | ⌘ S | Ctrl + S | -| Enregistrer sous | ⇧ ⌘ S | Shift + Ctrl + S | +| Ouvrir | ⌘O | Ctrl + O | +| Enregistrer | ⌘S | Ctrl + S | +| Enregistrer sous | ⇧⌘S | Shift + Ctrl + S | -Compatibilité aller-retour avec Figma. +Les fichiers sauvegardés sont compressés et incluent une miniature pour l'aperçu. Compatibilité aller-retour avec Figma. ## Conseils diff --git a/packages/docs/fr/user-guide/index.md b/packages/docs/fr/user-guide/index.md index 504d61e52..5543e8998 100644 --- a/packages/docs/fr/user-guide/index.md +++ b/packages/docs/fr/user-guide/index.md @@ -9,7 +9,7 @@ description: Apprenez à utiliser OpenPencil — navigation canvas, dessin, text OpenPencil est un éditeur de design open-source, compatible Figma — entièrement local, IA-natif et programmable. ::: tip Raccourcis multiplateforme -**⌘** = Command (Ctrl sur Windows/Linux), **⌥** = Option (Alt), **⇧** = Shift. +⌘ = Command (Ctrl sur Windows/Linux), ⌥ = Option (Alt), ⇧ = Shift. ::: ## Prise en main diff --git a/packages/docs/fr/user-guide/layers-and-pages.md b/packages/docs/fr/user-guide/layers-and-pages.md index e5801c872..143a54143 100644 --- a/packages/docs/fr/user-guide/layers-and-pages.md +++ b/packages/docs/fr/user-guide/layers-and-pages.md @@ -16,7 +16,7 @@ Arborescence hiérarchique à gauche. Déplier/replier, glisser pour réordonner Chaque page a son propre état de viewport. ## Panneau propriétés -Trois onglets : **Design** (propriétés contextuelles), **Code** (JSX / Tailwind CSS v4), **IA** (chat ⌘ J). +Trois onglets : **Design** (propriétés contextuelles), **Code** (JSX / Tailwind CSS v4), **IA** (chat ⌘J). Design : apparence, remplissage, contour, effets, typographie, mise en page, exportation. diff --git a/packages/docs/fr/user-guide/pen-tool.md b/packages/docs/fr/user-guide/pen-tool.md index 48ddd764b..6f873000d 100644 --- a/packages/docs/fr/user-guide/pen-tool.md +++ b/packages/docs/fr/user-guide/pen-tool.md @@ -15,12 +15,12 @@ description: Tracés vectoriels avec courbes de Bézier in OpenPencil. Click the first point to close into a loop. ## Tracés ouverts -**Escape** to commit as open path. +Escape to commit as open path. ## Réseaux vectoriels -Vector network data model, compatible with Figma `vectorNetworkBlob`. +Les tracés dans OpenPencil utilisent des réseaux vectoriels — un modèle plus flexible que les listes de points simples, qui prend en charge les tracés ramifiés et les topologies complexes. C'est le même modèle que Figma, les tracés sont donc parfaitement conservés dans les fichiers .fig. | Action | Mac | Windows / Linux | |--------|-----|-----------------| -| Pen tool | P | P | -| Commit | Escape | Escape | +| Pen tool | P | P | +| Commit | Escape | Escape | diff --git a/packages/docs/fr/user-guide/selection-and-manipulation.md b/packages/docs/fr/user-guide/selection-and-manipulation.md index 3a3b5497b..7198e62fd 100644 --- a/packages/docs/fr/user-guide/selection-and-manipulation.md +++ b/packages/docs/fr/user-guide/selection-and-manipulation.md @@ -6,23 +6,23 @@ description: Sélectionner, déplacer, redimensionner, tourner et organiser les ## Sélectionner - **Clic** sur un nœud pour le sélectionner -- **Shift + clic** pour ajouter/retirer de la sélection +- Shift + clic pour ajouter/retirer de la sélection - **Glissement de sélection** — glissez sur le canevas vide pour la sélection rectangulaire -- **⌘ A** — tout sélectionner +- ⌘A — tout sélectionner - **Clic sur le canevas vide** — tout désélectionner ## Déplacer - **Glisser** le nœud sélectionné -- **Flèches** — décaler de 1 px · **Shift + flèches** — 10 px +- **Flèches** — décaler de 1 px · Shift + flèches — 10 px ## Redimensionner -8 poignées. **Shift + glisser** contraint les proportions. +8 poignées. Shift + glisser contraint les proportions. ## Tourner -Survolez juste à l'extérieur d'un coin. **Shift** accroche à 15°. +Survolez juste à l'extérieur d'un coin. Shift accroche à 15°. ## Dupliquer -- **Alt + glisser** — dupliquer et déplacer · **⌘ D** — dupliquer sur place +- Alt + glisser — dupliquer et déplacer · ⌘D — dupliquer sur place ## Supprimer **Retour arrière** ou **Suppr** @@ -31,4 +31,4 @@ Survolez juste à l'extérieur d'un coin. **Shift** accroche à 15°. **]** au premier plan · **[** à l'arrière-plan ## Visibilité et verrouillage -**⇧ ⌘ H** visibilité · **⇧ ⌘ L** verrouillage +⇧⌘H visibilité · ⇧⌘L verrouillage diff --git a/packages/docs/fr/user-guide/text-editing.md b/packages/docs/fr/user-guide/text-editing.md index 6c75acb34..d7d91be22 100644 --- a/packages/docs/fr/user-guide/text-editing.md +++ b/packages/docs/fr/user-guide/text-editing.md @@ -5,7 +5,7 @@ description: Créer et modifier du texte avec formatage riche dans OpenPencil. # Édition de texte ## Créer du texte -Appuyez sur **T**, puis cliquez sur le canevas. Commencez à taper immédiatement. +Appuyez sur T, puis cliquez sur le canevas. Commencez à taper immédiatement. ## Édition en ligne Double-cliquez sur un nœud texte pour entrer en mode édition. Cliquez à l'extérieur pour confirmer. @@ -13,19 +13,19 @@ Double-cliquez sur un nœud texte pour entrer en mode édition. Cliquez à l'ext ## Navigation du curseur | Action | Mac | Windows / Linux | |--------|-----|-----------------| -| Gauche/droite | ← / → | ← / → | -| Haut/bas | ↑ / ↓ | ↑ / ↓ | -| Par mot | ⌥ ← / ⌥ → | Ctrl + ← / Ctrl + → | -| Début/fin de ligne | ⌘ ← / ⌘ → | Début / Fin | +| Gauche/droite | ← / → | ← / → | +| Haut/bas | ↑ / ↓ | ↑ / ↓ | +| Par mot | ⌥← / ⌥→ | Ctrl + ← / Ctrl + → | +| Début/fin de ligne | ⌘← / ⌘→ | Début / Fin | -**Shift** étend la sélection. +Shift étend la sélection. ## Formatage riche | Action | Mac | Windows / Linux | |--------|-----|-----------------| -| Gras | ⌘ B | Ctrl + B | -| Italique | ⌘ I | Ctrl + I | -| Souligné | ⌘ U | Ctrl + U | +| Gras | ⌘B | Ctrl + B | +| Italique | ⌘I | Ctrl + I | +| Souligné | ⌘U | Ctrl + U | ## Sélecteur de police -Recherche, aperçu et défilement virtuel. Polices système sur desktop (Tauri), Local Font Access API dans le navigateur. +Recherche, aperçu et défilement virtuel. Les polices système sont disponibles sur l'application de bureau, ainsi que dans Chrome et Edge. diff --git a/packages/docs/guide/architecture.md b/packages/docs/guide/architecture.md index 2c8cca9ff..24f4020cf 100644 --- a/packages/docs/guide/architecture.md +++ b/packages/docs/guide/architecture.md @@ -2,7 +2,7 @@ ## System Overview -```mermaid +`mermaid graph TB subgraph Tauri["Tauri v2 Shell"] subgraph Editor["Editor (Web)"] @@ -22,7 +22,7 @@ graph TB MCP["MCP Server (90 tools, stdio+HTTP)"] Collab["P2P Collab (Trystero + Yjs)"] end -``` +` ## Editor Layout @@ -62,7 +62,7 @@ Meta's Yoga provides CSS flexbox layout computation. A thin adapter maps Figma p ### File Format (Kiwi Binary) -Reuses Figma's Kiwi binary codec with 194 message/enum/struct definitions. Import: parse header → Zstd decompress → Kiwi decode → NodeChange[] → scene graph. Export reverses the process with thumbnail generation. +Reuses Figma's Kiwi binary codec with 194 message/enum/struct definitions. Import: parse header → Zstd decompress → Kiwi decode → `NodeChange`[] → scene graph. Export reverses the process with thumbnail generation. See [File Format Reference](/reference/file-format) for details. @@ -108,7 +108,7 @@ Frame-to-frame transitions, interaction triggers (click, hover, drag), overlay m ### CSS Grid Layout -Yoga WASM currently supports flexbox only. CSS Grid is upstream in [facebook/yoga#1893](https://github.com/facebook/yoga/pull/1893). OpenPencil will adopt it once the Yoga release ships. +CSS Grid is supported via a [Yoga fork](https://github.com/open-pencil/yoga/tree/grid) with cherry-picked grid PRs from upstream. Select a frame, click the grid icon to switch from flex to grid. Configure column/row tracks (fr, fixed px, auto), column and row gaps, and per-side padding. ### Windows Code Signing diff --git a/packages/docs/guide/comparison.md b/packages/docs/guide/comparison.md index 9277f32e5..f297074ba 100644 --- a/packages/docs/guide/comparison.md +++ b/packages/docs/guide/comparison.md @@ -266,13 +266,13 @@ Open Pencil's approach is simpler and lower overhead. Penpot's approach is more 2. **PDF export** — headless Chromium export service for PDF rendering (OpenPencil exports SVG but not PDF yet) 3. **Plugin system** — full plugin API with sandboxed execution 4. **Design tokens** — native design token support -5. **CSS Grid layout** — custom implementation (Open Pencil waiting for Yoga Grid) +5. **CSS Grid layout** — custom implementation (Open Pencil uses Yoga fork with grid support) 6. **Self-hosting** — Docker-based deployment for teams 7. **Maturity** — years of production usage, battle-tested at scale ## 11. Scripting & Extensibility -OpenPencil ships with an [`eval` command](/eval-command) that provides a Figma-compatible Plugin API for headless scripting — batch operations, automated testing, and AI-driven modifications all run without the GUI. On top of that, **90 AI tools** are available via built-in chat, MCP server (stdio + HTTP), and the CLI — covering read, create, modify, structure, variables, vector path, analyze (color/typography/spacing/clusters), diff, boolean operations, and arrangement. Penpot has a plugin system with sandboxed execution but no headless scripting API or MCP integration. +OpenPencil ships with an [`eval` command](/programmable/cli/scripting) that provides a Figma-compatible Plugin API for headless scripting — batch operations, automated testing, and AI-driven modifications all run without the GUI. On top of that, **90 AI tools** are available via built-in chat, MCP server (stdio + HTTP), and the CLI — covering read, create, modify, structure, variables, vector path, analyze (color/typography/spacing/clusters), diff, boolean operations, and arrangement. Penpot has a plugin system with sandboxed execution but no headless scripting API or MCP integration. ## Summary diff --git a/packages/docs/guide/features.md b/packages/docs/guide/features.md index dc3a75fe8..4bf6ad4cf 100644 --- a/packages/docs/guide/features.md +++ b/packages/docs/guide/features.md @@ -12,7 +12,7 @@ Open and save native Figma files directly. The import/export pipeline uses the s - **Pen tool** — vector networks (not simple paths), bezier curves with tangent handles - **Text** — canvas-native editing with IME support, double-click to enter edit mode - **Rich text** — per-character bold (⌘B), italic (⌘I), underline (⌘U), strikethrough -- **Auto-layout** — flexbox via Yoga WASM: direction, gap, padding, justify, align, child sizing. ⇧A to toggle +- **Auto-layout** — flexbox and CSS Grid via Yoga WASM: direction, gap, padding, justify, align, child sizing, grid tracks. ⇧A to toggle - **Components** — create (⌥⌘K), component sets (⇧⌘K), instances with override support, live sync - **Variables** — design tokens with collections, modes (Light/Dark), color/float/string/boolean types, variable binding - **Sections** — organizational containers with auto-adopting children and title pills @@ -87,7 +87,7 @@ bun add -g @open-pencil/mcp } ``` -See [MCP Tools reference](/reference/mcp-tools) for the full tool list. +See [MCP Tools reference](/programmable/mcp-server) for the full tool list. ## CLI diff --git a/packages/docs/guide/figma-comparison.md b/packages/docs/guide/figma-comparison.md index a5d2f7598..7f06b98fd 100644 --- a/packages/docs/guide/figma-comparison.md +++ b/packages/docs/guide/figma-comparison.md @@ -16,7 +16,7 @@ Feature-by-feature comparison of Figma Design capabilities with Open Pencil's cu | Layers panel (left sidebar) | ✅ | Tree view with expand/collapse, drag reorder, visibility toggle; resizable width | | Pages panel | ✅ | Add, delete, rename pages; per-page viewport state | | Properties panel (right sidebar) | ✅ | Sections: Appearance, Fill, Stroke, Effects, Typography, Layout, Position; resizable width | -| Zoom & pan | ✅ | Ctrl+scroll, pinch, ⌘+/⌘−/⌘0, space+drag, middle mouse, hand tool (H) | +| Zoom & pan | ✅ | Ctrl + scroll, pinch, ⌘+ / ⌘− / ⌘0, Space + drag, middle mouse, hand tool (H) | | Canvas rulers | ✅ | Top/left rulers with selection highlight bands and coordinate badges | | Canvas background color | ✅ | Per-page background via properties panel | | Canvas guides | 🔲 | Figma supports draggable guides from rulers | @@ -36,7 +36,7 @@ Feature-by-feature comparison of Figma Design capabilities with Open Pencil's cu |---------|--------|-------| | Shape tools (Rectangle, Ellipse, Line, Polygon, Star) | ✅ | All basic shape types; polygon side count and star inner radius configurable | | Frames | ✅ | Clip content, independent coordinate system | -| Groups | ✅ | ⌘G to group, ⇧⌘G to ungroup | +| Groups | ✅ | ⌘G to group, ⇧⌘G to ungroup | | Sections | ✅ | Title pills, auto-adopt overlapping nodes, luminance-adaptive text | | Arc tool (arcs, semi-circles, rings) | ✅ | arcData with start/end angle and inner radius | | Pencil (freehand) tool | 🔲 | Figma's freehand drawing tool | @@ -46,9 +46,9 @@ Feature-by-feature comparison of Figma Design capabilities with Open Pencil's cu | Alignment & position | ✅ | Position, rotation, dimensions in properties panel | | Copy & paste objects | ✅ | Standard clipboard + Figma Kiwi binary format; Copy as text/SVG/PNG/JSX | | Scale layers proportionally | 🟡 | Shift-resize constrains proportions; no dedicated Scale tool (K) | -| Lock & unlock layers | ✅ | ⇧⌘L toggles lock; locked nodes can't be selected/moved from canvas | -| Toggle layer visibility | ✅ | Eye icon in layers panel + ⇧⌘H keyboard shortcut | -| Rename layers | ✅ | Double-click inline rename in layers panel; Enter/Escape/blur to commit | +| Lock & unlock layers | ✅ | ⇧⌘L toggles lock; locked nodes can't be selected/moved from canvas | +| Toggle layer visibility | ✅ | Eye icon in layers panel + ⇧⌘H keyboard shortcut | +| Rename layers | ✅ | Double-click inline rename in layers panel; Enter/Escape/blur to commit | | Bring to front / Send to back | ✅ | ] and [ keyboard shortcuts; also in context menu | | Move to page | ✅ | Move selected nodes between pages via context menu | | Constraints (responsive resize) | 🔲 | Pin edges/center for parent resize behavior | @@ -79,13 +79,13 @@ Feature-by-feature comparison of Figma Design capabilities with Open Pencil's cu | Feature | Status | Notes | |---------|--------|-------| -| Text tool & inline editing | ✅ | Canvas-native editing, phantom textarea, cursor/selection/word select, drag to select, double/triple-click, rich text style runs (⌘B/I/U, S button) | +| Text tool & inline editing | ✅ | Canvas-native editing, phantom textarea, cursor/selection/word select, drag to select, double/triple-click, rich text style runs (⌘B / I / U, **S** button) | | Text rendering (Paragraph API) | ✅ | CanvasKit Paragraph for shaping, line-breaking, metrics | | Font loading (system fonts) | ✅ | Inter default, font-kit in Tauri with OnceLock cache + preloading, queryLocalFonts in browser | | Font family & weight | ✅ | FontPicker with virtual scroll, search, CSS preview; weight selection in properties panel | | Font size & line height | ✅ | Editable in typography section | | Text alignment | 🟡 | Basic alignment; Figma has vertical alignment and auto-width/height modes | -| Text styles | 🟡 | Per-selection bold/italic/underline/strikethrough (⌘B/I/U, S button); not yet reusable named text style presets | +| Text styles | 🟡 | Per-selection bold/italic/underline/strikethrough (⌘B / I / U, **S** button); not yet reusable named text style presets | | Text resizing modes (auto, fixed, hug) | 🔲 | Figma's auto-width, auto-height, fixed-size text modes | | Bulleted & numbered lists | 🔲 | List formatting in text | | Links in text | 🔲 | Hyperlinks within text content | @@ -126,7 +126,7 @@ Feature-by-feature comparison of Figma Design capabilities with Open Pencil's cu | Background blur | ✅ | Blur content behind layer | | Foreground blur | ✅ | Blur in foreground | | Stroke weight | ✅ | Configurable in properties panel | -| Stroke cap (round, square, arrow) | ✅ | NONE, ROUND, SQUARE, ARROW_LINES, ARROW_EQUILATERAL | +| Stroke cap (round, square, arrow) | ✅ | `NONE`, `ROUND`, `SQUARE`, `ARROW_LINES`, `ARROW_EQUILATERAL` | | Stroke join (miter, bevel, round) | ✅ | All three join types | | Dash patterns | ✅ | Dash-on/dash-off stroke pattern | | Stroke alignment | ✅ | Inside/Center/Outside with clip-based rendering matching Figma behavior | @@ -140,14 +140,14 @@ Feature-by-feature comparison of Figma Design capabilities with Open Pencil's cu | Feature | Status | Notes | |---------|--------|-------| | Horizontal & vertical flow | ✅ | Yoga WASM flexbox engine | -| Toggle auto layout (⇧A) | ✅ | Toggle on frame or wrap selection | +| Toggle auto layout (⇧A) | ✅ | Toggle on frame or wrap selection | | Gap (spacing between children) | ✅ | Configurable in properties panel | | Padding (uniform & per-side) | ✅ | All four sides independently | | Justify content | ✅ | Start, center, end, space-between | | Align items | ✅ | Start, center, end, stretch | | Child sizing (fixed, fill, hug) | ✅ | Per-child sizing modes | | Wrap | ✅ | Flex wrap for multi-line layout | -| Grid auto layout flow | 🔲 | Figma's grid-based auto layout (rows × columns) | +| Grid auto layout flow | ✅ | CSS Grid via Yoga fork — column/row tracks, gaps, spans | | Combined flows (nested) | ✅ | Nested auto-layout frames with different directions | | Drag reorder within auto layout | ✅ | Visual insertion indicator | | Min/max width and height | 🔲 | Figma supports min/max constraints on auto-layout children | @@ -156,17 +156,17 @@ Feature-by-feature comparison of Figma Design capabilities with Open Pencil's cu | Feature | Status | Notes | |---------|--------|-------| -| Create components | 🟡 | ⌥⌘K creates from frame/group or wraps selection; no component properties UI yet | -| Component sets | 🟡 | ⇧⌘K combines components; dashed purple border; no variant property editing | +| Create components | 🟡 | ⌥⌘K creates from frame/group or wraps selection; no component properties UI yet | +| Component sets | 🟡 | ⇧⌘K combines components; dashed purple border; no variant property editing | | Component instances | 🟡 | Create instance from context menu with child cloning and componentId mapping; live sync from component; no override editing UI | | Variants | 🔲 | Variant switching and property-based selection | | Component properties | 🔲 | Boolean, text, instance swap properties | | Override propagation | ✅ | Changes to main component propagate to all instances; overrides preserved | -| Variables (color, number, string, boolean) | 🟡 | COLOR full UI (dialog, TanStack Table, inline editing, undo/redo, demo collections); FLOAT/STRING/BOOLEAN defined but no editing UI | +| Variables (color, number, string, boolean) | 🟡 | `COLOR` full UI (dialog, TanStack Table, inline editing, undo/redo, demo collections); `FLOAT`/STRING/BOOLEAN defined but no editing UI | | Variable collections & modes | 🟡 | Collections, modes, activeMode switching work; no variable-driven theming UI yet | | Styles (color, text, effect, layout) | 🔲 | Reusable named style presets | | Libraries (publish, share, update) | 🔲 | Shared component/style libraries | -| Detach instance | ✅ | ⌥⌘B converts instance back to frame | +| Detach instance | ✅ | ⌥⌘B converts instance back to frame | | Go to main component | ✅ | Navigate to source component, cross-page | ## Prototyping @@ -189,9 +189,9 @@ Feature-by-feature comparison of Figma Design capabilities with Open Pencil's cu | Feature | Status | Notes | |---------|--------|-------| -| .fig file import | ✅ | Full Kiwi codec: 194 definitions, ~390 fields per NodeChange | -| .fig file export | ✅ | Kiwi encoding + Zstd compression + thumbnail generation; COMPONENT/COMPONENT_SET mapped to SYMBOL for round-trip | -| Save / Save As | ✅ | ⌘S / ⇧⌘S; native dialogs (Tauri), File System Access API (Chrome/Edge), download fallback (Safari) | +| .fig file import | ✅ | Full Kiwi codec: 194 definitions, ~390 fields per `NodeChange` | +| .fig file export | ✅ | Kiwi encoding + Zstd compression + thumbnail generation; `COMPONENT`/COMPONENT_SET mapped to `SYMBOL` for round-trip | +| Save / Save As | ✅ | ⌘S / ⇧⌘S; native dialogs (Tauri), File System Access API (Chrome/Edge), download fallback (Safari) | | Figma clipboard (paste) | ✅ | Decode Kiwi binary from Figma clipboard | | Figma clipboard (copy) | ✅ | Encode Kiwi binary that Figma can read | | Sketch file import | 🔲 | .sketch file parsing | diff --git a/packages/docs/guide/tech-stack.md b/packages/docs/guide/tech-stack.md index 44d3bda7b..3f66e5118 100644 --- a/packages/docs/guide/tech-stack.md +++ b/packages/docs/guide/tech-stack.md @@ -8,7 +8,7 @@ | **UI Framework** | Vue 3 + VueUse | Reactive composition API, excellent TypeScript support | | **Components** | Reka UI | Headless, accessible UI primitives (tree, slider, etc.) | | **Styling** | Tailwind CSS 4 | Utility-first, fast iteration, dark theme | -| **Layout** | Yoga WASM | CSS flexbox engine from Meta, battle-tested in React Native | +| **Layout** | Yoga WASM | CSS flexbox and grid engine from Meta, battle-tested in React Native | | **File Format** | Kiwi binary + Zstd | Figma's own format — compact, fast parsing, .fig compatible | | **Collaboration** | Trystero + Yjs | P2P WebRTC via MQTT signaling, CRDT sync, y-indexeddb persistence | | **Color** | culori | Color space conversions (HSV, RGB, hex) | @@ -60,4 +60,4 @@ Yoga is maintained by Meta, battle-tested across billions of React Native device | Technology | Purpose | Phase | |-----------|---------|-------| -| CSS Grid in Yoga | Grid-based auto layout | Blocked on upstream (facebook/yoga#1893) | +| CSS Grid in Yoga | Grid-based auto layout | ✅ Supported via [Yoga fork](https://github.com/open-pencil/yoga/tree/grid) | diff --git a/packages/docs/it/development/roadmap.md b/packages/docs/it/development/roadmap.md index a147ca740..4d130b0b6 100644 --- a/packages/docs/it/development/roadmap.md +++ b/packages/docs/it/development/roadmap.md @@ -4,7 +4,7 @@ ### Fase 1: Motore Core ✅ -SceneGraph, rendering Skia, forme base, selezione, zoom/pan, annulla/ripristina, guide di snap. +`SceneGraph`, rendering Skia, forme base, selezione, zoom/pan, annulla/ripristina, guide di snap. ### Fase 2: UI Editor + Layout ✅ @@ -16,7 +16,7 @@ Import/export .fig, codec Kiwi, appunti, strumento penna, reti vettoriali, grupp ### Fase 4: Componenti + Variabili ✅ -Componenti, istanze, override, set di componenti, variabili (COLOR/FLOAT/STRING/BOOLEAN), collezioni, modalità, export immagini, menu contestuale, formattazione testo ricco. +Componenti, istanze, override, set di componenti, variabili (`COLOR`/FLOAT/STRING/BOOLEAN), collezioni, modalità, export immagini, menu contestuale, formattazione testo ricco. ### Fase 5: Integrazione IA & Strumenti ✅ @@ -24,7 +24,7 @@ Componenti, istanze, override, set di componenti, variabili (COLOR/FLOAT/STRING/ - @open-pencil/core estratto in packages/core/ (nessuna dipendenza DOM) - @open-pencil/cli con operazioni headless .fig (info, tree, find, export, analyze, eval) - Comando `eval` con API Plugin compatibile Figma -- Chat IA: connessione diretta OpenRouter, 87 strumenti in `packages/core/src/tools/`, ⌘J +- Chat IA: connessione diretta OpenRouter, 87 strumenti in `packages/core/src/tools/`, ⌘J - 49 strumenti IA/MCP aggiuntivi portati da figma-use (75 in totale) - Server MCP (@open-pencil/mcp): stdio + HTTP, 87 strumenti core + 3 gestione file - Definizioni strumenti unificate: definire una volta in `packages/core/src/tools/`, adattare per chat IA (valibot), MCP (zod), CLI (eval) @@ -44,7 +44,7 @@ Componenti, istanze, override, set di componenti, variabili (COLOR/FLOAT/STRING/ - Modalità segui: clic sull'avatar di un peer per seguire il suo viewport - Persistenza locale via y-indexeddb - Rendering effetti: ombra portata, ombra interna, sfocatura livello/sfondo/primo piano -- Schede multi-file: ⌘N/⌘T nuova scheda, ⌘W chiudi, ⌘O apri +- Schede multi-file: ⌘N/⌘T nuova scheda, ⌘W chiudi, ⌘O apri - Firma codice Apple e notarizzazione per macOS - Build Linux (x64) aggiunti al CI - Sito documentazione VitePress con i18n (6 lingue) @@ -53,7 +53,7 @@ Componenti, istanze, override, set di componenti, variabili (COLOR/FLOAT/STRING/ - Prototipazione (connessioni frame, transizioni, animazioni) - Commenti (pin, thread, risolvere) - Supporto PWA -- Cambio varianti, UI variabili FLOAT/STRING/BOOLEAN, theming tramite variabili +- Cambio varianti, UI variabili `FLOAT`/STRING/BOOLEAN, theming tramite variabili ## Tempistica diff --git a/packages/docs/it/eval-command.md b/packages/docs/it/eval-command.md deleted file mode 100644 index 732cd6a35..000000000 --- a/packages/docs/it/eval-command.md +++ /dev/null @@ -1,77 +0,0 @@ -# `open-pencil eval` — API Plugin Figma-compatibile per scripting headless - -## Panoramica - -`bun open-pencil eval --code ''` esegue JavaScript su un file `.fig` con un oggetto globale `figma` compatibile con Figma. Questo abilita scripting headless, operazioni batch, esecuzione di strumenti IA e test — tutto senza la GUI. - -L'oggetto `figma` rispecchia la superficie dell'API Plugin di Figma il più fedelmente possibile, così le conoscenze esistenti sui plugin Figma e gli snippet di codice sono direttamente trasferibili. - -```bash -# Creare un frame, impostare auto-layout, aggiungere figli -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.fills = [{ type: "SOLID", color: { r: 1, g: 1, b: 1 } }] - return { id: frame.id, name: frame.name } -' - -# Interrogare nodi -bun open-pencil eval design.fig --code ' - const buttons = figma.currentPage.findAll(n => n.name.includes("Button")) - return buttons.map(b => ({ id: b.id, name: b.name })) -' - -# Scrivere le modifiche -bun open-pencil eval design.fig --code '...' --write -``` - -## Architettura - -``` -CLI: open-pencil eval --code '...' - → loadDocument(file) → SceneGraph - → FigmaAPI(sceneGraph) → proxy `figma` - → AsyncFunction('figma', code)(figmaProxy) - → stampa risultato / salva file con --write -``` - -### Classi principali - -| Classe | Posizione | Ruolo | -|--------|-----------|-------| -| `FigmaAPI` | `packages/core/src/figma-api.ts` | Oggetto proxy che implementa metodi `figma.*` | -| `FigmaNode` | `packages/core/src/figma-api.ts` | Proxy che avvolge `SceneNode` con accesso proprietà stile Figma | -| Comando `eval` | `packages/cli/src/commands/eval.ts` | Carica documento, crea API, esegue codice | - -### Perché in `@open-pencil/core`? - -La classe `FigmaAPI` è nel core perché: gli strumenti IA la riutilizzano, i test possono usarla e non ha dipendenze DOM. - -## Comando CLI - -``` -bun open-pencil eval [opzioni] - -Argomenti: - file File .fig su cui operare - -Opzioni: - --code, -c Codice JavaScript da eseguire - --stdin Leggere codice da stdin - --write, -w Scrivere le modifiche nel file di input - -o, --output Scrivere in un file diverso - --json Output come JSON - --quiet, -q Sopprimere l'output -``` - -## Implementazione a fasi - -- **Fase 1: Core** — creazione nodi, proprietà, operazioni albero, auto-layout, testo (~80% degli script reali) -- **Fase 2: Componenti & Istanze** — createComponent, createInstance, detachInstance -- **Fase 3: Variabili** — getLocalVariables, createVariable, setBoundVariable -- **Fase 4: Stili & Avanzato** — stili paint/testo/effetti, operazioni booleane - -[Riferimento API completo in inglese](/eval-command) diff --git a/packages/docs/it/guide/architecture.md b/packages/docs/it/guide/architecture.md index ec0399519..da8fb4cc3 100644 --- a/packages/docs/it/guide/architecture.md +++ b/packages/docs/it/guide/architecture.md @@ -2,7 +2,7 @@ ## Panoramica del Sistema -```mermaid +`mermaid graph TB subgraph Tauri["Tauri v2 Shell"] subgraph Editor["Editor (Web)"] @@ -22,7 +22,7 @@ graph TB MCP["MCP Server (90 tools, stdio+HTTP)"] Collab["P2P Collab (Trystero + Yjs)"] end -``` +` ## Layout dell'Editor @@ -62,7 +62,7 @@ Yoga di Meta fornisce il calcolo del layout CSS flexbox. Un adattatore sottile m ### Formato File (Kiwi Binary) -Riutilizza il codec binario Kiwi di Figma con 194 definizioni di messaggio/enum/struct. Importazione: analizza l'header → decompressione Zstd → decodifica Kiwi → NodeChange[] → scene graph. L'esportazione inverte il processo con generazione di miniature. +Riutilizza il codec binario Kiwi di Figma con 194 definizioni di messaggio/enum/struct. Importazione: analizza l'header → decompressione Zstd → decodifica Kiwi → `NodeChange`[] → scene graph. L'esportazione inverte il processo con generazione di miniature. Consulta il [riferimento Formato File](/it/reference/file-format) per i dettagli. @@ -108,7 +108,7 @@ Transizioni frame-to-frame, trigger di interazione (clic, hover, trascinamento), ### Layout CSS Grid -Yoga WASM attualmente supporta solo flexbox. CSS Grid è in fase di sviluppo upstream in [facebook/yoga#1893](https://github.com/facebook/yoga/pull/1893). OpenPencil lo adotterà non appena la release di Yoga sarà disponibile. +CSS Grid è supportato tramite un [fork di Yoga](https://github.com/open-pencil/yoga/tree/grid) con PR grid cherry-picked dall'upstream. Seleziona un frame, clicca sull'icona griglia per passare da flex a grid. Configura track colonne/righe (fr, px fissi, auto), gap colonne e righe, e padding per lato. ### Firma del Codice per Windows diff --git a/packages/docs/it/guide/comparison.md b/packages/docs/it/guide/comparison.md index b02215c9a..03fd2860c 100644 --- a/packages/docs/it/guide/comparison.md +++ b/packages/docs/it/guide/comparison.md @@ -215,7 +215,7 @@ Gestione stato via Potok. Undo con vettori di cambiamenti inversi (max 50 voci), ## 11. Scripting ed estensibilità -OpenPencil include un [comando `eval`](/eval-command) che fornisce un'API Plugin compatibile Figma per scripting headless. Inoltre, 90 strumenti AI disponibili via chat integrata, server MCP (stdio + HTTP) e CLI. Penpot ha un sistema plugin con esecuzione sandboxed ma senza API di scripting headless né integrazione MCP. +OpenPencil include un [comando `eval`](/programmable/cli/scripting) che fornisce un'API Plugin compatibile Figma per scripting headless. Inoltre, 90 strumenti AI disponibili via chat integrata, server MCP (stdio + HTTP) e CLI. Penpot ha un sistema plugin con esecuzione sandboxed ma senza API di scripting headless né integrazione MCP. ## Riepilogo diff --git a/packages/docs/it/guide/features.md b/packages/docs/it/guide/features.md index 40c4ab6ca..1d765e262 100644 --- a/packages/docs/it/guide/features.md +++ b/packages/docs/it/guide/features.md @@ -87,7 +87,7 @@ bun add -g @open-pencil/mcp } ``` -Consulta il [riferimento strumenti MCP](/it/reference/mcp-tools) per l'elenco completo degli strumenti. +Consulta il [riferimento strumenti MCP](/programmable/mcp-server) per l'elenco completo degli strumenti. ## CLI diff --git a/packages/docs/it/guide/figma-comparison.md b/packages/docs/it/guide/figma-comparison.md index e3198cafe..beb5cd4ee 100644 --- a/packages/docs/it/guide/figma-comparison.md +++ b/packages/docs/it/guide/figma-comparison.md @@ -16,7 +16,7 @@ Confronto funzionalità per funzionalità delle capacità di Figma Design con lo | Pannello livelli (barra laterale sinistra) | ✅ | Vista ad albero con espansione/compressione, riordinamento per trascinamento, toggle visibilità; larghezza ridimensionabile | | Pannello pagine | ✅ | Aggiungere, eliminare, rinominare pagine; stato viewport per pagina | | Pannello proprietà (barra laterale destra) | ✅ | Sezioni: Aspetto, Riempimento, Contorno, Effetti, Tipografia, Layout, Posizione; larghezza ridimensionabile | -| Zoom e panoramica | ✅ | Ctrl+scroll, pinch, ⌘+/⌘−/⌘0, spazio+trascinamento, mouse centrale, strumento mano (H) | +| Zoom e panoramica | ✅ | Ctrl + scroll, pinch, ⌘+ / ⌘− / ⌘0, spazio+trascinamento, mouse centrale, strumento mano (H) | | Righelli canvas | ✅ | Righelli superiore/sinistro con bande di selezione e badge di coordinate | | Colore di sfondo del canvas | ✅ | Sfondo per pagina tramite pannello proprietà | | Guide del canvas | 🔲 | Figma supporta guide trascinabili dai righelli | @@ -36,7 +36,7 @@ Confronto funzionalità per funzionalità delle capacità di Figma Design con lo |-------------|-------|------| | Strumenti forma (Rettangolo, Ellisse, Linea, Poligono, Stella) | ✅ | Tutti i tipi di forma base; lati poligono e raggio interno stella configurabili | | Frame | ✅ | Ritaglio contenuto, sistema di coordinate indipendente | -| Gruppi | ✅ | ⌘G per raggruppare, ⇧⌘G per separare | +| Gruppi | ✅ | ⌘G per raggruppare, ⇧⌘G per separare | | Sezioni | ✅ | Pillole titolo, auto-adozione nodi sovrapposti, testo adattivo alla luminanza | | Strumento arco (archi, semicerchi, anelli) | ✅ | arcData con angolo inizio/fine e raggio interno | | Strumento matita (mano libera) | 🔲 | Strumento di disegno a mano libera di Figma | @@ -46,8 +46,8 @@ Confronto funzionalità per funzionalità delle capacità di Figma Design con lo | Allineamento e posizione | ✅ | Posizione, rotazione, dimensioni nel pannello | | Copiare e incollare oggetti | ✅ | Appunti standard + formato binario Kiwi di Figma | | Scalare livelli proporzionalmente | 🟡 | Shift-ridimensiona mantiene proporzioni; nessuno strumento Scale dedicato (K) | -| Bloccare e sbloccare livelli | ✅ | ⇧⌘L alterna blocco | -| Toggle visibilità livello | ✅ | Icona occhio nel pannello + scorciatoia ⇧⌘H | +| Bloccare e sbloccare livelli | ✅ | ⇧⌘L alterna blocco | +| Toggle visibilità livello | ✅ | Icona occhio nel pannello + scorciatoia ⇧⌘H | | Rinominare livelli | ✅ | Doppio clic per rinomina inline; Invio/Esc/clic per confermare | | Porta in primo piano / Invia in fondo | ✅ | Scorciatoie ] e [; anche nel menu contestuale | | Sposta a pagina | ✅ | Spostare nodi tra pagine tramite menu contestuale | @@ -79,7 +79,7 @@ Confronto funzionalità per funzionalità delle capacità di Figma Design con lo | Funzionalità | Stato | Note | |-------------|-------|------| -| Strumento testo e modifica inline | ✅ | Modifica nativa sul canvas, textarea phantom, style run (⌘B/I/U, pulsante S) | +| Strumento testo e modifica inline | ✅ | Modifica nativa sul canvas, textarea phantom, style run (⌘B / I / U, pulsante S) | | Rendering testo (Paragraph API) | ✅ | CanvasKit Paragraph per shaping, interruzione riga, metriche | | Caricamento font (font di sistema) | ✅ | Inter default, font-kit in Tauri con cache OnceLock, queryLocalFonts nel browser | | Famiglia e peso font | ✅ | FontPicker con scroll virtuale, ricerca, anteprima CSS | @@ -126,7 +126,7 @@ Confronto funzionalità per funzionalità delle capacità di Figma Design con lo | Sfocatura sfondo | ✅ | Sfocare contenuto dietro il livello | | Sfocatura primo piano | ✅ | Sfocatura in primo piano | | Spessore contorno | ✅ | Configurabile nel pannello proprietà | -| Estremità contorno (round, square, arrow) | ✅ | NONE, ROUND, SQUARE, ARROW_LINES, ARROW_EQUILATERAL | +| Estremità contorno (round, square, arrow) | ✅ | `NONE`, `ROUND`, `SQUARE`, `ARROW_LINES`, `ARROW_EQUILATERAL` | | Giunzione contorno (miter, bevel, round) | ✅ | Tutti e tre i tipi di giunzione | | Pattern tratteggio | ✅ | Pattern contorno dash-on/dash-off | | Raggio angolo | ✅ | Raggio uniforme e per angolo con toggle indipendente | @@ -138,14 +138,14 @@ Confronto funzionalità per funzionalità delle capacità di Figma Design con lo | Funzionalità | Stato | Note | |-------------|-------|------| | Flusso orizzontale e verticale | ✅ | Motore flexbox Yoga WASM | -| Toggle auto layout (⇧A) | ✅ | Toggle su frame o avvolgi selezione | +| Toggle auto layout (⇧A) | ✅ | Toggle su frame o avvolgi selezione | | Gap (spaziatura tra figli) | ✅ | Configurabile nel pannello proprietà | | Padding (uniforme e per lato) | ✅ | Tutti e quattro i lati indipendentemente | | Justify content | ✅ | Start, center, end, space-between | | Align items | ✅ | Start, center, end, stretch | | Dimensionamento figli (fisso, riempimento, adatta) | ✅ | Modi dimensionamento per figlio | | Wrap | ✅ | Flex wrap per layout multi-riga | -| Flusso auto layout griglia | 🔲 | Auto layout basato su griglia di Figma | +| Flusso auto layout griglia | ✅ | CSS Grid tramite fork Yoga — track colonne/righe, gap, span | | Flussi combinati (annidati) | ✅ | Frame auto-layout annidati con direzioni diverse | | Riordinare trascinando in auto layout | ✅ | Indicatore visivo di inserimento | | Larghezza/altezza min e max | 🔲 | Figma supporta vincoli min/max | @@ -154,17 +154,17 @@ Confronto funzionalità per funzionalità delle capacità di Figma Design con lo | Funzionalità | Stato | Note | |-------------|-------|------| -| Creare componenti | 🟡 | ⌥⌘K crea da frame/gruppo; nessuna UI proprietà componente ancora | -| Set di componenti | 🟡 | ⇧⌘K combina componenti; bordo tratteggiato viola; nessuna modifica proprietà variante | +| Creare componenti | 🟡 | ⌥⌘K crea da frame/gruppo; nessuna UI proprietà componente ancora | +| Set di componenti | 🟡 | ⇧⌘K combina componenti; bordo tratteggiato viola; nessuna modifica proprietà variante | | Istanze di componenti | 🟡 | Creare istanza dal menu contestuale; sync in tempo reale; nessuna UI modifica override | | Varianti | 🔲 | Cambio variante e selezione per proprietà | | Proprietà componente | 🔲 | Proprietà booleane, testo, scambio istanza | | Propagazione override | ✅ | Modifiche al componente principale propagate; override preservati | -| Variabili (colore, numero, stringa, booleano) | 🟡 | COLOR con UI completa; FLOAT/STRING/BOOLEAN definiti senza UI di modifica | +| Variabili (colore, numero, stringa, booleano) | 🟡 | `COLOR` con UI completa; `FLOAT`/STRING/BOOLEAN definiti senza UI di modifica | | Collezioni e modi variabili | 🟡 | Collezioni, modi, cambio activeMode funzionano; nessuna UI tematizzazione | | Stili (colore, testo, effetto, layout) | 🔲 | Preset stile riutilizzabili nominati | | Librerie (pubblicare, condividere, aggiornare) | 🔲 | Librerie condivise componenti/stili | -| Staccare istanza | ✅ | ⌥⌘B converte istanza in frame | +| Staccare istanza | ✅ | ⌥⌘B converte istanza in frame | | Vai al componente principale | ✅ | Navigare al componente sorgente, cross-page | ## Prototipazione @@ -187,9 +187,9 @@ Confronto funzionalità per funzionalità delle capacità di Figma Design con lo | Funzionalità | Stato | Note | |-------------|-------|------| -| Import file .fig | ✅ | Codec Kiwi completo: 194 definizioni, ~390 campi per NodeChange | +| Import file .fig | ✅ | Codec Kiwi completo: 194 definizioni, ~390 campi per `NodeChange` | | Export file .fig | ✅ | Codifica Kiwi + compressione Zstd + generazione miniatura | -| Salva / Salva con nome | ✅ | ⌘S / ⇧⌘S; dialoghi nativi (Tauri), File System Access API (Chrome/Edge), download fallback (Safari) | +| Salva / Salva con nome | ✅ | ⌘S / ⇧⌘S; dialoghi nativi (Tauri), File System Access API (Chrome/Edge), download fallback (Safari) | | Appunti Figma (incolla) | ✅ | Decodificare binario Kiwi dagli appunti Figma | | Appunti Figma (copia) | ✅ | Codificare binario Kiwi leggibile da Figma | | Import file Sketch | 🔲 | Parsing file .sketch | @@ -211,7 +211,7 @@ Confronto funzionalità per funzionalità delle capacità di Figma Design con lo | Multiplayer in tempo reale | ✅ | P2P via Trystero + Yjs CRDT, cursori, modalità segui; senza server | | Chat al cursore | 🔲 | Bolle chat inline al cursore | | Branching e merging | 🔲 | Branch di versione per file di design | -| Modalità sviluppatore (ispezione) | 🟡 | Tab Codice mostra JSX; nessuna proprietà CSS né spec di handoff | +| Modalità sviluppatore (ispezione) | 🟡 | Tab Codice mostra JSX; nessuna proprietà CSS né spec di handoff | | Code Connect | 🔲 | Collegare componenti design al codice | | Frammenti di codice | 🟡 | Export JSX con evidenziazione e copia; nessun frammento CSS/Swift/Kotlin | | Figma for VS Code | 🔲 | Integrazione plugin editor | diff --git a/packages/docs/it/guide/tech-stack.md b/packages/docs/it/guide/tech-stack.md index 299a23912..80bdf5d3f 100644 --- a/packages/docs/it/guide/tech-stack.md +++ b/packages/docs/it/guide/tech-stack.md @@ -60,4 +60,4 @@ Yoga è mantenuto da Meta, collaudato su miliardi di dispositivi React Native e | Tecnologia | Scopo | Fase | |-----------|---------|-------| -| CSS Grid in Yoga | Auto layout basato su griglia | Bloccato da upstream (facebook/yoga#1893) | +| CSS Grid in Yoga | Auto layout basato su griglia | ✅ Supportato tramite [fork Yoga](https://github.com/open-pencil/yoga/tree/grid) | diff --git a/packages/docs/it/programmable/ai-chat.md b/packages/docs/it/programmable/ai-chat.md new file mode 100644 index 000000000..92d7643de --- /dev/null +++ b/packages/docs/it/programmable/ai-chat.md @@ -0,0 +1,47 @@ +--- +title: Chat IA +description: Assistente IA integrato con 87 strumenti per creare e modificare design. +--- + +# Chat IA + +Premi ⌘J (Ctrl + J) per aprire l'assistente IA. Descrivi ciò che vuoi — crea forme, imposta stili, gestisce il layout, lavora con i componenti e analizza il tuo design. + +## Configurazione + +1. Apri il pannello chat IA (⌘J) +2. Clicca l'icona delle impostazioni +3. Inserisci la tua chiave API OpenRouter +4. Scegli un modello (Claude, GPT-4, Gemini, ecc.) + +Nessun backend, nessun abbonamento — la tua chiave comunica direttamente con OpenRouter. + +## Cosa Può Fare + +L'assistente ha 87 strumenti suddivisi in queste categorie: + +- **Creazione** — frame, forme, testo, componenti, pagine. Renderizza JSX per layout complessi. +- **Stile** — riempimenti, bordi, effetti, opacità, raggio degli angoli, metodi di fusione. +- **Layout** — auto-layout, allineamento, spaziatura, dimensionamento. +- **Componenti** — crea componenti, istanze, set di componenti. Gestisci le sovrascritture. +- **Variabili** — crea/modifica variabili, collezioni, modalità. Associa ai riempimenti. +- **Query** — trova nodi, leggi proprietà, elenca pagine, font, selezione. +- **Analisi** — palette colori, audit tipografico, coerenza della spaziatura, rilevamento cluster. +- **Esportazione** — PNG, SVG, JSX con classi Tailwind. +- **Vettoriale** — operazioni booleane, manipolazione dei tracciati. + +## Esempi di Prompt + +- "Crea una card con un titolo, una descrizione e un pulsante blu" +- "Fai in modo che tutti i pulsanti di questa pagina usino lo stesso raggio dei bordi" +- "Quali font sono usati in questo file?" +- "Cambia lo sfondo del frame selezionato con un gradiente dal blu al viola" +- "Esporta il frame selezionato come SVG" +- "Trova tutti i nodi di testo con dimensione font inferiore a 12" + +## Suggerimenti + +- Seleziona i nodi prima di chiedere — l'assistente sa cosa è selezionato. +- Sii specifico su colori, dimensioni e posizioni per risultati precisi. +- L'assistente può modificare più nodi in un singolo messaggio. +- Usa "annulla" nell'editor se il risultato non ti piace. diff --git a/packages/docs/it/programmable/cli/analyzing.md b/packages/docs/it/programmable/cli/analyzing.md new file mode 100644 index 000000000..407d5a4a1 --- /dev/null +++ b/packages/docs/it/programmable/cli/analyzing.md @@ -0,0 +1,65 @@ +--- +title: Analisi dei Design +description: Audita colori, tipografia, spaziatura e pattern ripetuti nei file .fig. +--- + +# Analisi dei Design + +I comandi `analyze` auditano un intero design system dal terminale — trova incongruenze, estrai la palette reale, individua componenti in attesa di essere estratti. + +## Colori + +```sh +open-pencil analyze colors design.fig +``` + +Trova ogni colore nel file, conta l'utilizzo e mostra un istogramma visuale: + +``` +#1d1b20 ██████████████████████████████ 17155× +#49454f ██████████████████████████████ 9814× +#ffffff ██████████████████████████████ 8620× +#6750a4 ██████████████████████████████ 3967× +``` + +## Tipografia + +```sh +open-pencil analyze typography design.fig +``` + +Elenca ogni combinazione di famiglia di font, dimensione e peso con conteggi di utilizzo. Utile per individuare stili di testo isolati che dovrebbero essere consolidati. + +## Spaziatura + +```sh +open-pencil analyze spacing design.fig +``` + +Audita i valori di gap e padding nei frame con auto-layout. Aiuta a identificare incongruenze nella scala di spaziatura — ad esempio un gap di `13px` isolato tra valori altrimenti di `8/16/24`. + +## Cluster + +```sh +open-pencil analyze clusters design.fig +``` + +Trova pattern di nodi ripetuti che potrebbero essere estratti come componenti: + +``` +3771× frame "container" (100% match) + size: 40×40, structure: Frame > [Frame] + +2982× instance "Checkboxes" (100% match) + size: 48×48, structure: Instance > [Frame] +``` + +## Output JSON + +Tutti i comandi analyze supportano `--json` per output leggibile dalle macchine: + +```sh +open-pencil analyze colors design.fig --json +``` + +Invia tramite pipe a `jq`, usa nei controlli CI o utilizza negli script che verificano i budget dei token di design. diff --git a/packages/docs/it/programmable/cli/exporting.md b/packages/docs/it/programmable/cli/exporting.md new file mode 100644 index 000000000..548aba53d --- /dev/null +++ b/packages/docs/it/programmable/cli/exporting.md @@ -0,0 +1,59 @@ +--- +title: Esportazione +description: Renderizza file .fig in PNG, JPG, WEBP, SVG o JSX con classi Tailwind. +--- + +# Esportazione + +Esporta i design dal terminale — immagini raster, vettoriali o codice JSX. + +## Esportazione Immagini + +```sh +open-pencil export design.fig # PNG (predefinito) +open-pencil export design.fig -f jpg -s 2 -q 90 # JPG a 2×, qualità 90 +open-pencil export design.fig -f webp -s 3 # WEBP a 3× +open-pencil export design.fig -f svg # SVG vettoriale +``` + +Opzioni: + +- `-f` — formato: `png`, `jpg`, `webp`, `svg`, `jsx` +- `-s` — scala: `1`–`4` +- `-q` — qualità: `0`–`100` (solo JPG/WEBP) +- `-o` — percorso di output +- `--page` — nome della pagina +- `--node` — ID di un nodo specifico + +## Esportazione JSX + +Esporta come JSX con classi utility Tailwind: + +```sh +open-pencil export design.fig -f jsx --style tailwind +``` + +Output: + +```html +
+

Card Title

+

Description text

+
+``` + +Supporta anche `--style openpencil` per il formato JSX nativo (vedi [Renderer JSX](../jsx-renderer)). + +## Miniature + +```sh +open-pencil export design.fig --thumbnail --width 1920 --height 1080 +``` + +## Modalità App in Esecuzione + +Ometti il file per esportare dall'app in esecuzione: + +```sh +open-pencil export -f png # screenshot del canvas corrente +``` diff --git a/packages/docs/it/programmable/cli/inspecting.md b/packages/docs/it/programmable/cli/inspecting.md new file mode 100644 index 000000000..877a96369 --- /dev/null +++ b/packages/docs/it/programmable/cli/inspecting.md @@ -0,0 +1,98 @@ +--- +title: Ispezione dei File +description: Esplora alberi di nodi, cerca per nome o tipo e analizza le proprietà dal terminale. +--- + +# Ispezione dei File + +La CLI ti permette di esplorare file `.fig` senza aprire l'editor. Ogni comando funziona anche con l'app in esecuzione — basta omettere l'argomento del file. + +::: tip Installazione +```sh +bun add -g @open-pencil/cli +# oppure +brew install open-pencil/tap/open-pencil +``` +::: + +## Informazioni sul Documento + +Ottieni una panoramica rapida — conteggio pagine, nodi totali, font utilizzati, dimensione del file: + +```sh +open-pencil info design.fig +``` + +## Albero dei Nodi + +Stampa l'intera gerarchia dei nodi: + +```sh +open-pencil tree design.fig +``` + +``` +[0] [page] "Getting started" (0:46566) + [0] [section] "" (0:46567) + [0] [frame] "Body" (0:46568) + [0] [frame] "Introduction" (0:46569) + [0] [frame] "Introduction Card" (0:46570) + [0] [frame] "Guidance" (0:46571) +``` + +## Trova Nodi + +Cerca per tipo: + +```sh +open-pencil find design.fig --type TEXT +``` + +Cerca per nome: + +```sh +open-pencil find design.fig --name "Button" +``` + +Entrambi i flag possono essere combinati per restringere ulteriormente i risultati. + +## Dettagli del Nodo + +Ispeziona tutte le proprietà di un nodo specifico tramite il suo ID: + +```sh +open-pencil node design.fig --id 1:23 +``` + +## Pagine + +Elenca tutte le pagine del documento: + +```sh +open-pencil pages design.fig +``` + +## Variabili + +Elenca le variabili di design e le relative collezioni: + +```sh +open-pencil variables design.fig +``` + +## Modalità App in Esecuzione + +Quando l'app desktop è in esecuzione, ometti l'argomento del file — la CLI si connette tramite RPC e opera sul canvas attivo: + +```sh +open-pencil tree # ispeziona il documento attivo +open-pencil eval -c "..." # interroga l'editor +``` + +## Output JSON + +Tutti i comandi supportano `--json` per output leggibile dalle macchine — invia tramite pipe a `jq`, usa negli script CI o elabora con altri strumenti: + +```sh +open-pencil tree design.fig --json | jq '.[] | .name' +``` diff --git a/packages/docs/it/programmable/cli/scripting.md b/packages/docs/it/programmable/cli/scripting.md new file mode 100644 index 000000000..dfd30793e --- /dev/null +++ b/packages/docs/it/programmable/cli/scripting.md @@ -0,0 +1,70 @@ +--- +title: Scripting +description: Esegui JavaScript con la Figma Plugin API — interroga nodi, modifica design in batch, crea frame. +--- + +# Scripting + +`open-pencil eval` ti dà accesso alla Figma Plugin API completa dal terminale. Leggi nodi, modifica proprietà, crea forme — poi scrivi le modifiche nel file. + +## Utilizzo Base + +```sh +open-pencil eval design.fig -c "figma.currentPage.children.length" +``` + +Il flag `-c` accetta JavaScript. La variabile globale `figma` funziona come la Figma Plugin API. + +## Interrogazione dei Nodi + +```sh +open-pencil eval design.fig -c " + figma.currentPage.findAll(n => n.type === 'FRAME' && n.name.includes('Button')) + .map(b => ({ id: b.id, name: b.name, w: b.width, h: b.height })) +" +``` + +## Modifica e Salvataggio + +```sh +open-pencil eval design.fig -c " + figma.currentPage.children.forEach(n => n.opacity = 0.5) +" -w +``` + +`-w` scrive le modifiche nel file di input. Usa `-o output.fig` per scrivere in un file diverso. + +## Lettura da Stdin + +Per script più lunghi: + +```sh +cat transform.js | open-pencil eval design.fig --stdin -w +``` + +## Modalità App in Esecuzione + +Ometti il file per eseguire sull'app desktop in esecuzione: + +```sh +open-pencil eval -c "figma.currentPage.name" +``` + +## API Disponibili + +L'oggetto `figma` supporta: + +- `figma.currentPage` — la pagina attiva +- `figma.root` — la radice del documento +- `figma.createFrame()`, `figma.createRectangle()`, `figma.createEllipse()`, `figma.createText()`, ecc. +- `.findAll()`, `.findOne()` — cerca tra i discendenti +- `.appendChild()`, `.insertChild()` — manipolazione dell'albero +- Tutti i setter di proprietà: `.fills`, `.strokes`, `.effects`, `.opacity`, `.cornerRadius`, `.layoutMode`, `.itemSpacing`, ecc. + +Questa è la stessa API utilizzata dai plugin Figma, quindi le conoscenze esistenti e gli snippet di codice si trasferiscono direttamente. + +## Output JSON + +```sh +open-pencil eval design.fig -c "..." --json +``` diff --git a/packages/docs/it/programmable/collaboration.md b/packages/docs/it/programmable/collaboration.md new file mode 100644 index 000000000..41b2b8506 --- /dev/null +++ b/packages/docs/it/programmable/collaboration.md @@ -0,0 +1,38 @@ +--- +title: Collaborazione +description: Editing collaborativo in tempo reale tramite P2P WebRTC — nessun server, nessun account. +--- + +# Collaborazione + +Modifica i design insieme in tempo reale. I peer si connettono direttamente — nessun server trasmette i tuoi dati, nessun account richiesto. + +## Condivisione di una Stanza + +1. Clicca il pulsante di condivisione nell'angolo in alto a destra +2. Copia il link generato (`app.openpencil.dev/share/`) +3. Invialo ai tuoi collaboratori + +Chiunque abbia il link può partecipare. La stanza rimane attiva finché almeno un partecipante ha la pagina aperta. + +## Cosa si Sincronizza + +- **Modifiche al documento** — ogni modifica (forme, testo, proprietà, layout) si sincronizza istantaneamente +- **Cursori** — vedi dove sta puntando ciascun collaboratore, con il suo nome e colore +- **Selezioni** — le selezioni evidenziate sono visibili a tutti + +## Modalità Follow + +Clicca l'avatar di un collaboratore nella barra superiore per seguire il suo viewport. Il tuo canvas si sposta e zooma per corrispondere alla sua vista. Clicca di nuovo per smettere di seguire. + +## Come Funziona + +I peer si connettono direttamente tramite WebRTC — i dati del tuo design vanno dritti da browser a browser, senza mai passare per un server centrale. Lo stato del documento usa un CRDT (tipo di dato replicato senza conflitti), quindi le modifiche concorrenti si uniscono automaticamente senza conflitti. + +La stanza persiste localmente — se aggiorni la pagina, ti riconnetti con lo stesso stato. + +## Suggerimenti + +- Funziona nel browser e nell'app desktop +- Gli ID delle stanze sono crittograficamente casuali — solo chi ha il link può partecipare +- I cursori inattivi vengono rimossi automaticamente quando qualcuno si disconnette diff --git a/packages/docs/it/programmable/index.md b/packages/docs/it/programmable/index.md new file mode 100644 index 000000000..a8db4351e --- /dev/null +++ b/packages/docs/it/programmable/index.md @@ -0,0 +1,51 @@ +--- +layout: doc +title: IA e Automazione +description: Ogni operazione in OpenPencil è scriptabile — chat IA, CLI, renderer JSX, server MCP, collaborazione in tempo reale. +--- + +# IA e Automazione + +OpenPencil tratta i file di design come dati. Ogni operazione disponibile nell'editor — creare forme, impostare riempimenti, gestire l'auto-layout, esportare risorse — è disponibile anche dal terminale, dagli agenti IA e dal codice. Nessun plugin da installare, nessuna chiave API, nessuna lista d'attesa. + +L'interfaccia dell'editor e le interfacce di automazione utilizzano lo stesso motore. Se puoi farlo cliccando, puoi farlo con uno script. + +## Chat IA + +L'assistente integrato ha accesso a 87 strumenti che coprono l'intera superficie dell'editor. Descrivi ciò che vuoi in linguaggio naturale — "aggiungi un'ombra esterna di 16px a tutti i pulsanti", "crea un componente card con variante dark mode", "esporta ogni frame di questa pagina a 2×". + +[Chat IA →](./ai-chat) + +## Collaborazione + +Editing multiplayer in tempo reale tramite WebRTC peer-to-peer. Nessun server, nessun account. Condividi un link della stanza e modifica insieme con cursori live e modalità di follow. Lo stato del documento si sincronizza tramite CRDT, quindi le modifiche si uniscono automaticamente anche con connessioni instabili. + +[Collaborazione →](./collaboration) + +## Renderer JSX + +Descrivi l'interfaccia come JSX — la stessa sintassi che gli LLM già conoscono da React. Una singola chiamata può creare un intero albero di componenti con frame, testo, auto-layout, riempimenti e bordi. Compatto, dichiarativo e confrontabile con diff. + +Nella direzione opposta, esporta qualsiasi selezione in JSX con classi Tailwind — utile per il passaggio allo sviluppo o per fornire i design a un LLM. + +[Renderer JSX →](./jsx-renderer) + +## CLI + +Ispeziona, esporta e analizza file `.fig` senza aprire l'editor. Elenca le pagine, cerca i nodi, estrai i token di design, renderizza in PNG — tutto dal terminale con output JSON leggibile dalle macchine. + +La CLI si connette anche all'app desktop in esecuzione tramite RPC, così puoi scriptare l'editor mentre lo stai usando. + +[Ispezione dei File](./cli/inspecting) · [Esportazione](./cli/exporting) · [Analisi dei Design](./cli/analyzing) · [Scripting](./cli/scripting) + +## Server MCP + +Connetti Claude Code, Cursor, Windsurf o qualsiasi client compatibile con MCP a OpenPencil. Il server espone 90 strumenti per leggere, creare e modificare design — gli stessi strumenti che usa la chat IA integrata. Funziona tramite stdio o HTTP con supporto alle sessioni. + +[Server MCP →](./mcp-server) + +## Perché Open? + +Figma è una piattaforma chiusa. Il loro server MCP è in sola lettura. L'accesso CDP via browser è stato eliminato nella versione 126. I file di design risiedono in un formato proprietario sui server di qualcun altro. Lo sviluppo di plugin richiede un runtime personalizzato con API limitate. + +OpenPencil è l'alternativa: open source, licenza MIT, ogni operazione scriptabile, dati archiviati localmente. I tuoi file di design sono tuoi — ispezionali, trasformali, inviali alla CI, dalli in pasto a un LLM. Nessun permesso necessario. diff --git a/packages/docs/it/programmable/jsx-renderer.md b/packages/docs/it/programmable/jsx-renderer.md new file mode 100644 index 000000000..a2d0b4616 --- /dev/null +++ b/packages/docs/it/programmable/jsx-renderer.md @@ -0,0 +1,116 @@ +--- +title: Renderer JSX +description: Crea design con JSX — la sintassi che gli LLM già conoscono da milioni di componenti React. +--- + +# Renderer JSX + +OpenPencil usa JSX come linguaggio di creazione dei design. Gli LLM hanno visto milioni di componenti React — descrivere un layout come `` è naturale, nessun addestramento speciale necessario. Ogni token conta quando un agente IA esegue decine di operazioni, e JSX è la rappresentazione dichiarativa più compatta. + +JSX è anche confrontabile con diff. Quando un'IA modifica un design, la modifica è un diff JSX — leggibile, revisionabile, versionabile. + +## Creazione dei Design + +Lo strumento `render` (disponibile nella chat IA, MCP e CLI eval) accetta JSX: + +```jsx + + Card Title + Description text + +``` + +Nel server MCP e nella chat IA, lo strumento `render` accetta direttamente stringhe JSX. Nella CLI, usa il comando `export` per andare nella direzione opposta — [esportare design come JSX](./cli/exporting). + +## Elementi + +Tutti i tipi di nodo sono disponibili come elementi JSX: + +| Elemento | Crea | Alias | +|----------|------|-------| +| `` | Frame (contenitore, supporta auto-layout) | `` | +| `` | Rettangolo | `` | +| `` | Ellisse / cerchio | | +| `` | Nodo di testo (i figli diventano contenuto testuale) | | +| `` | Linea | | +| `` | Stella | | +| `` | Poligono | | +| `` | Tracciato vettoriale | | +| `` | Gruppo | | +| `
` | Sezione | | + +## Proprietà di Stile + +Proprietà abbreviate compatte ispirate alla nomenclatura di Tailwind. + +### Layout + +| Proprietà | Descrizione | +|-----------|-------------| +| `flex` | `"row"` o `"col"` — attiva l'auto-layout | +| `gap` | Spazio tra i figli | +| `wrap` | Manda a capo i figli alla riga successiva | +| `rowGap` | Spaziatura sull'asse trasversale durante il wrapping | +| `justify` | `"start"`, `"end"`, `"center"`, `"between"` | +| `items` | `"start"`, `"end"`, `"center"`, `"stretch"` | +| `p`, `px`, `py`, `pt`, `pr`, `pb`, `pl` | Padding | + +### Dimensione e Posizione + +| Proprietà | Descrizione | +|-----------|-------------| +| `w`, `h` | Larghezza/altezza — numero, `"fill"` o `"hug"` | +| `minW`, `maxW`, `minH`, `maxH` | Vincoli di dimensione | +| `x`, `y` | Posizione | + +### Aspetto + +| Proprietà | Descrizione | +|-----------|-------------| +| `bg` | Riempimento di sfondo (colore esadecimale) | +| `fill` | Alias per `bg` | +| `stroke` | Colore del bordo | +| `strokeWidth` | Larghezza del bordo (predefinito: 1) | +| `rounded` | Raggio degli angoli (o `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`) | +| `cornerSmoothing` | Angoli arrotondati stile iOS (0–1) | +| `opacity` | 0–1 | +| `shadow` | Ombra esterna (es. `"0 4 8 #00000040"`) | +| `blur` | Raggio sfocatura del livello | +| `rotate` | Rotazione in gradi | +| `blendMode` | Metodo di fusione | +| `overflow` | `"hidden"` o `"visible"` | + +### Tipografia + +| Proprietà | Descrizione | +|-----------|-------------| +| `size` / `fontSize` | Dimensione del font | +| `font` / `fontFamily` | Famiglia di font | +| `weight` / `fontWeight` | `"bold"`, `"medium"`, `"normal"` o numero | +| `color` | Colore del testo | +| `textAlign` | `"left"`, `"center"`, `"right"`, `"justified"` | + +## Esportazione in JSX + +Converti design esistenti in JSX: + +```sh +open-pencil export design.fig -f jsx # formato OpenPencil +open-pencil export design.fig -f jsx --style tailwind # classi Tailwind +``` + +Il ciclo completo funziona: esporta un design come JSX, modifica il codice, renderizzalo di nuovo. + +## Confronto Visuale con Diff + +Poiché i design sono rappresentabili come JSX, le modifiche diventano diff del codice: + +```diff + +- Old Title ++ New Title + Description + +``` + +Questo rende le modifiche ai design revisionabili nelle pull request, tracciabili nel controllo di versione e verificabili nella CI. diff --git a/packages/docs/it/programmable/mcp-server.md b/packages/docs/it/programmable/mcp-server.md new file mode 100644 index 000000000..e296a6447 --- /dev/null +++ b/packages/docs/it/programmable/mcp-server.md @@ -0,0 +1,251 @@ +# 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` + +Security defaults (HTTP transport): + +- Binds to `127.0.0.1` by default (`HOST` to override) +- `eval` tool is disabled +- File operations are limited to `OPENPENCIL_MCP_ROOT` (defaults to current working directory) +- CORS is disabled by default; set `OPENPENCIL_MCP_CORS_ORIGIN` to allow one origin +- Optional auth token: `OPENPENCIL_MCP_AUTH_TOKEN` (client sends `Authorization: Bearer ` or `x-mcp-token`) + +Server 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` + +## AI Agent Skill + +Teach your AI coding agent to use OpenPencil tools: + +```sh +npx skills add open-pencil/skills@open-pencil +``` + +Works with Claude Code, Cursor, Windsurf, Codex, and any agent that supports [skills](https://skills.sh). The skill covers the CLI, MCP tools, JSX rendering, eval, and the running app's automation bridge. + +## Tools (90) + +### 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_current_page` | Get the current page name and ID | +| `get_node` | Get detailed properties of a node by ID | +| `find_nodes` | Find nodes by name pattern and/or type | +| `get_components` | List all components in the document | +| `list_pages` | List all pages | +| `list_variables` | List design variables | +| `list_collections` | List variable collections | +| `list_fonts` | List fonts used in the current page | +| `page_bounds` | Get bounding box of all objects on the current page | +| `node_bounds` | Get bounding box of a node | +| `node_ancestors` | Get ancestor chain of a node | +| `node_children` | Get direct children of a node | +| `node_tree` | Get the subtree rooted at a node | +| `node_bindings` | Get variable bindings on a node | + +### Create + +| Tool | Description | +|------|-------------| +| `create_shape` | Create a shape (`FRAME`, `RECTANGLE`, `ELLIPSE`, `TEXT`, `LINE`, `STAR`, `POLYGON`, `SECTION`) | +| `create_vector` | Create a vector node from a path string | +| `create_slice` | Create an export slice | +| `create_page` | Create a new page | +| `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 | +| `node_to_component` | Convert an existing node into a component in-place | + +### 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 | +| `set_rotation` | Set rotation angle in degrees | +| `set_opacity` | Set opacity (0–1) | +| `set_radius` | Set corner radius (uniform or per-corner) | +| `set_minmax` | Set min/max width and height constraints | +| `set_text` | Set text content of a `TEXT` node | +| `set_font` | Set font family and weight | +| `set_font_range` | Set font properties on a character range | +| `set_text_resize` | Set text auto-resize mode (fixed/auto-width/auto-height) | +| `set_visible` | Show or hide a node | +| `set_blend` | Set blend mode | +| `set_locked` | Lock or unlock a node | +| `set_stroke_align` | Set stroke alignment (inside/center/outside) | +| `set_text_properties` | Set text layout: alignment, auto-resize, text case, decoration, truncation | +| `set_layout_child` | Configure auto-layout child: sizing, grow, alignment, absolute positioning | +| `node_move` | Move a node to a new position | +| `node_resize` | Resize a node | +| `node_replace_with` | Replace a node with another node | +| `arrange` | Align or distribute selected nodes | + +### 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 | +| `flatten_nodes` | Flatten nodes into a single vector | +| `boolean_union` | Boolean union of two or more nodes | +| `boolean_subtract` | Boolean subtraction | +| `boolean_intersect` | Boolean intersection | +| `boolean_exclude` | Boolean exclusion | + +### Vector Path + +| Tool | Description | +|------|-------------| +| `path_get` | Get the path data of a vector node | +| `path_set` | Set the path data of a vector node | +| `path_scale` | Scale a vector path | +| `path_flip` | Flip a vector path horizontally or vertically | +| `path_move` | Translate a vector path | + +### Export + +| Tool | Description | +|------|-------------| +| `export_image` | Export nodes as PNG, JPG, or WEBP. Returns base64-encoded image data | +| `export_svg` | Export nodes as SVG markup | + +### Viewport + +| Tool | Description | +|------|-------------| +| `viewport_get` | Get current viewport position and zoom level | +| `viewport_set` | Set viewport position and zoom | +| `viewport_zoom_to_fit` | Zoom viewport to fit specified nodes | + +### Variables + +| Tool | Description | +|------|-------------| +| `get_variable` | Get a variable by ID or name | +| `find_variables` | Find variables by name pattern or type | +| `create_variable` | Create a new variable in a collection | +| `set_variable` | Set a variable value in a mode | +| `delete_variable` | Delete a variable | +| `bind_variable` | Bind a variable to a node property | +| `get_collection` | Get a variable collection by ID or name | +| `create_collection` | Create a new variable collection | +| `delete_collection` | Delete a variable collection | + +### Analyze + +| Tool | Description | +|------|-------------| +| `analyze_colors` | Analyze color palette usage across the document | +| `analyze_typography` | Analyze font/size/weight distribution | +| `analyze_spacing` | Analyze gap and padding values | +| `analyze_clusters` | Detect repeated patterns (potential components) | + +### Diff + +| Tool | Description | +|------|-------------| +| `diff_create` | Create a snapshot of the current document state | +| `diff_show` | Show differences between the current state and a snapshot | + +### 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 | + +Note: `eval` is available over stdio, but disabled in HTTP mode for security. diff --git a/packages/docs/it/reference/cli.md b/packages/docs/it/reference/cli.md new file mode 100644 index 000000000..6f83df440 --- /dev/null +++ b/packages/docs/it/reference/cli.md @@ -0,0 +1,184 @@ +--- +title: CLI Reference +description: Complete reference for all open-pencil commands, options, and flags. +--- + +# CLI Reference + +All commands accept a `.fig` file as a positional argument. When omitted, the CLI connects to the running desktop app via RPC. + +## info + +Show document info — pages, node counts, fonts, file size. + +```sh +open-pencil info [file] [--json] +``` + +| Option | Description | +|--------|-------------| +| `--json` | Output as JSON | + +## tree + +Print the node hierarchy. + +```sh +open-pencil tree [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--page` | Page name (default: first page) | +| `--depth` | Max depth (default: unlimited) | +| `--json` | Output as JSON | + +## find + +Search nodes by name or type. + +```sh +open-pencil find [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--name` | Node name (partial match, case-insensitive) | +| `--type` | Node type: `FRAME`, `TEXT`, `RECTANGLE`, `INSTANCE`, etc. | +| `--page` | Page name (default: all pages) | +| `--limit` | Max results (default: 100) | +| `--json` | Output as JSON | + +## node + +Show detailed properties of a node. + +```sh +open-pencil node [file] --id [--json] +``` + +| Option | Description | +|--------|-------------| +| `--id` | **Required.** Node ID (e.g. `1:23`) | +| `--json` | Output as JSON | + +## pages + +List all pages in the document. + +```sh +open-pencil pages [file] [--json] +``` + +| Option | Description | +|--------|-------------| +| `--json` | Output as JSON | + +## variables + +List design variables and collections. + +```sh +open-pencil variables [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--collection` | Filter by collection name | +| `--type` | Filter by type: `COLOR`, `FLOAT`, `STRING`, `BOOLEAN` | +| `--json` | Output as JSON | + +## export + +Export to PNG, JPG, WEBP, SVG, or JSX. + +```sh +open-pencil export [file] [options] +``` + +| Option | Alias | Description | +|--------|-------|-------------| +| `--format` | `-f` | `png` (default), `jpg`, `webp`, `svg`, `jsx` | +| `--output` | `-o` | Output file path (default: `.`) | +| `--scale` | `-s` | Export scale (default: 1) | +| `--quality` | `-q` | Quality 0–100, JPG/WEBP only (default: 90) | +| `--page` | | Page name (default: first page) | +| `--node` | | Node ID to export (default: all top-level nodes) | +| `--style` | | JSX style: `openpencil` (default), `tailwind` | +| `--thumbnail` | | Export page thumbnail instead of full render | +| `--width` | | Thumbnail width (default: 1920) | +| `--height` | | Thumbnail height (default: 1080) | + +## eval + +Execute JavaScript with the Figma Plugin API. + +```sh +open-pencil eval [file] [options] +``` + +| Option | Alias | Description | +|--------|-------|-------------| +| `--code` | `-c` | JavaScript code to execute | +| `--stdin` | | Read code from stdin | +| `--write` | `-w` | Write changes back to the input file | +| `--output` | `-o` | Write to a different file | +| `--json` | | Output as JSON | +| `--quiet` | `-q` | Suppress output | + +## analyze colors + +Analyze color palette usage across the document. + +```sh +open-pencil analyze colors [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--limit` | Max colors to show (default: 30) | +| `--threshold` | Distance threshold for clustering similar colors, 0–50 (default: 15) | +| `--similar` | Show similar color clusters | +| `--json` | Output as JSON | + +## analyze typography + +Analyze font family, size, and weight distribution. + +```sh +open-pencil analyze typography [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--group-by` | Group by: `family`, `size`, `weight` (default: show all styles) | +| `--limit` | Max styles to show (default: 30) | +| `--json` | Output as JSON | + +## analyze spacing + +Analyze gap and padding values across auto-layout frames. + +```sh +open-pencil analyze spacing [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--grid` | Base grid size to check against (default: 8) | +| `--json` | Output as JSON | + +## analyze clusters + +Find repeated node patterns — potential components. + +```sh +open-pencil analyze clusters [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--limit` | Max clusters to show (default: 20) | +| `--min-size` | Min node size in px (default: 30) | +| `--min-count` | Min instances to form a cluster (default: 2) | +| `--json` | Output as JSON | diff --git a/packages/docs/it/reference/file-format.md b/packages/docs/it/reference/file-format.md index b49d41784..ea94b8fb6 100644 --- a/packages/docs/it/reference/file-format.md +++ b/packages/docs/it/reference/file-format.md @@ -1,71 +1,72 @@ -# Formato file +# File Format -## Struttura file .fig +## .fig File Structure + +A `.fig` file is a ZIP archive containing a Kiwi-encoded binary message: + +| Offset | Content | +|--------|---------| +| 0 | Magic header `fig-kiwi` (8 bytes) | +| 8 | Version (4 bytes, uint32 LE) | +| 12 | Schema length (4 bytes, uint32 LE) | +| 16 | Compressed Kiwi schema | +| … | Message length (4 bytes, uint32 LE) | +| … | Compressed Kiwi message — `NodeChange[]` (entire document) | +| … | Blob data — images, vector networks, fonts | + +## Import Pipeline ``` -┌─────────────────────────────────┐ -│ 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 -└─────────────────────────────────┘ +.fig file → parse header → decompress Zstd → decode Kiwi schema + → decode message → NodeChange[] → build SceneGraph + → resolve blob refs → render on canvas ``` -## Pipeline di importazione +## Export Pipeline ``` -.fig file → Parse header → Decompress Zstd → Decode Kiwi schema - → Decode Message → NodeChange[] → Build SceneGraph - → Resolve blob refs → Render on canvas +SceneGraph → NodeChange[] → Kiwi encode → compress (Zstd/deflate) + → build ZIP (header + schema + message + thumbnail.png) + → write .fig file ``` -## Pipeline di esportazione +Export uses ⌘S (Save) and ⇧⌘S (Save As) with native OS dialogs on the desktop app. The exported file includes a `thumbnail.png` required by Figma for file preview. -``` -SceneGraph → NodeChange[] → Kiwi encode → Compress (Zstd/deflate) - → Build ZIP (header + schema + message + thumbnail.png) - → Write .fig file -``` - -Export uses ⌘S (Save) and ⇧⌘S (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). +Compression uses Zstd via Tauri Rust command on desktop, with deflate fallback in the browser. ## Kiwi Binary Codec -The codec handles Figma's 194-definition Kiwi schema with NodeChange as the central type (~390 fields). Key components: +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 +| Module | Purpose | +|--------|---------| +| `kiwi-schema` | Kiwi parser (from [evanw/kiwi](https://github.com/nicolo-ribaudo/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. +Figma's schema uses non-contiguous field IDs (e.g. 1, 2, 5, 10 with gaps). The kiwi-schema parser handles 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`. +`.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. ## Supported Formats | Format | Import | Export | |--------|--------|--------| -| .fig (Figma) | ✅ | ✅ | -| .svg | Planned | Planned | -| .png | Planned | Planned | -| .pdf | — | Planned | - -See [Roadmap](/development/roadmap) for planned format support timeline. +| `.fig` (Figma) | ✅ | ✅ | +| `.svg` | Planned | Planned | +| `.png` | Planned | Planned | +| `.pdf` | — | Planned | ## 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 +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. +Encoding happens synchronously in the copy event handler (not async Clipboard API) for browser compatibility. This enables bidirectional clipboard between OpenPencil and Figma. diff --git a/packages/docs/it/reference/mcp-tools.md b/packages/docs/it/reference/mcp-tools.md deleted file mode 100644 index de4376d18..000000000 --- a/packages/docs/it/reference/mcp-tools.md +++ /dev/null @@ -1,150 +0,0 @@ -# Server MCP - -OpenPencil include un server MCP (Model Context Protocol) che permette agli strumenti di coding IA — Claude Code, Cursor, Windsurf ecc. — di leggere e modificare file .fig headless. - -Due trasporti - -## **stdio** per client MCP, **HTTP** per tutto il resto. - -```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" - } - } -} -``` - -O eseguire dal codice sorgente: - -::: 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` - -## AI Agent Skill - -Install the OpenPencil skill for your AI coding agent: - -```sh -npx skills add open-pencil/skills@open-pencil -``` - -Works with Claude Code, Cursor, Windsurf, Codex, and any agent that supports [skills](https://skills.sh). - -## Tools (75) - -### 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.md index d1247a45a..f6024302d 100644 --- a/packages/docs/it/reference/node-types.md +++ b/packages/docs/it/reference/node-types.md @@ -1,4 +1,4 @@ -# Tipi di nodo +# Node Types 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. @@ -8,41 +8,41 @@ The scene graph supports 28 node types from Figma's Kiwi schema. Each node is id | 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) | ✅ | +| `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) +- `COMPONENT_SET` → variant group container (no dedicated Kiwi ID, mapped from `SYMBOL` with variants) - `POLYGON` → Kiwi `REGULAR_POLYGON` (ID 11) ```typescript @@ -81,14 +81,14 @@ Document ## Core Properties -Every node carries these fields (subset of NodeChange): +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 +- `phase` — `CREATED` or `REMOVED` - `parentIndex` — parent GUID + position string for z-ordering ### Transform @@ -103,14 +103,14 @@ Every node carries these fields (subset of NodeChange): - `strokePaints[]` — stroke colors - `effects[]` — shadows, blurs - `opacity` — 0–1 -- `blendMode` — NORMAL, MULTIPLY, SCREEN, etc. +- `blendMode` — `NORMAL`, `MULTIPLY`, `SCREEN`, etc. ### Stroke - `strokeWeight` — stroke thickness -- `strokeAlign` — inside / center / outside -- `strokeCap` — butt / round / square -- `strokeJoin` — miter / bevel / round +- `strokeAlign` — `INSIDE` / `CENTER` / `OUTSIDE` +- `strokeCap` — `NONE` / `ROUND` / `SQUARE` / `ARROW_LINES` / `ARROW_EQUILATERAL` +- `strokeJoin` — `MITER` / `BEVEL` / `ROUND` - `dashPattern[]` — dash/gap lengths ### Corners diff --git a/packages/docs/it/reference/scene-graph.md b/packages/docs/it/reference/scene-graph.md index a72146525..0d445d189 100644 --- a/packages/docs/it/reference/scene-graph.md +++ b/packages/docs/it/reference/scene-graph.md @@ -1,8 +1,8 @@ -# Grafo della scena +# Scene Graph -## Rappresentazione in memoria +## In-Memory Representation -I nodi vivono in una mappa piatta `Map` keyed by GUID string. La struttura ad albero è mantenuta via `parentIndex` references. This gives Lookup O(1) by ID and efficient traversal. +Nodes live in a flat `Map` 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 { @@ -31,11 +31,11 @@ interface SceneGraph { ## 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. +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. +`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 @@ -86,11 +86,11 @@ For marquee selection, `getNodesInRect` returns all nodes whose bounds intersect ## 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). +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. +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 diff --git a/packages/docs/it/user-guide/auto-layout.md b/packages/docs/it/user-guide/auto-layout.md index 7e3dbc96d..d21c2358c 100644 --- a/packages/docs/it/user-guide/auto-layout.md +++ b/packages/docs/it/user-guide/auto-layout.md @@ -4,7 +4,9 @@ description: Auto-layout basato su flexbox in OpenPencil. --- # Auto-layout -**⇧ A** per attivare/disattivare o avvolgere la selezione in un frame auto-layout. +L'auto-layout posiziona i figli automaticamente all'interno di un frame usando regole flexbox. Gestisce direzione, spaziatura, allineamento e dimensionamento responsivo. + +⇧A per attivare/disattivare o avvolgere la selezione in un frame auto-layout. ## Direzione - **Orizzontale** — da sinistra a destra diff --git a/packages/docs/it/user-guide/canvas-navigation.md b/packages/docs/it/user-guide/canvas-navigation.md index 7026e88c2..0793ae9d1 100644 --- a/packages/docs/it/user-guide/canvas-navigation.md +++ b/packages/docs/it/user-guide/canvas-navigation.md @@ -9,24 +9,24 @@ Il canvas è il tuo spazio di lavoro infinito. ## Panoramica -- **Spazio + trascinamento** — tieni Spazio e trascina +- Spazio + trascinamento — tieni Spazio e trascina - **Pulsante centrale del mouse** — premi e trascina - **Trackpad a due dita** — scorri con due dita ## Strumento mano -Premi **H** per attivare lo strumento mano. Passa a un altro strumento (es. **V**) per disattivare. +Premi H per attivare lo strumento mano. Passa a un altro strumento (es. **V**) per disattivare. ## Zoom -- **Ctrl + scroll** (o **⌘ + scroll** su Mac) — zoom avanti/indietro +- Ctrl + scroll (o ⌘ + scroll su Mac) — zoom avanti/indietro - **Gesto pinch** — pinch sul trackpad - Scorciatoie da tastiera — vedi tabella | Azione | Mac | Windows / Linux | |--------|-----|-----------------| -| Panoramica | Spazio + trascinamento | Spazio + trascinamento | -| Strumento mano | H | H | -| Zoom avanti | ⌘ + | Ctrl + + | -| Zoom indietro | ⌘ - | Ctrl + - | -| Zoom 100% | ⌘ 0 | Ctrl + 0 | +| Panoramica | Spazio + trascinamento | Spazio + trascinamento | +| Strumento mano | H | H | +| Zoom avanti | ⌘+ | Ctrl + + | +| Zoom indietro | ⌘− | Ctrl + − | +| Zoom 100% | ⌘0 | Ctrl + 0 | diff --git a/packages/docs/it/user-guide/components.md b/packages/docs/it/user-guide/components.md index e683c8f7a..9b7654f11 100644 --- a/packages/docs/it/user-guide/components.md +++ b/packages/docs/it/user-guide/components.md @@ -5,16 +5,16 @@ description: Componenti riutilizzabili, istanze, override e sincronizzazione liv # Componenti ## Creare un componente -**⌥ ⌘ K** (Ctrl+Alt+K) — converte frame/gruppo in COMPONENT. Etichetta viola con diamante. +⌥⌘K (Ctrl + Alt + K) — converte la selezione in un componente riutilizzabile. I componenti mostrano un'etichetta viola con icona a diamante. ## Set di componenti -**⇧ ⌘ K** — combina 2+ componenti in un set con bordo tratteggiato viola. +⇧⌘K — combina 2+ componenti in un set con bordo tratteggiato viola. ## Creare istanze Click destro → **Crea istanza**. Appare 40 px a destra. ## Separare un'istanza -**⌥ ⌘ B** — diventa un frame senza collegamento. +⌥⌘B — diventa un frame senza collegamento. ## Sincronizzazione live Modificare un componente aggiorna tutte le istanze. Proprietà sincronizzate: dimensioni, riempimenti, contorni, effetti, opacità, raggi angoli, layout. @@ -27,6 +27,6 @@ Click seleziona il componente. **Doppio click** per entrare e selezionare i figl | Azione | Mac | Windows / Linux | |--------|-----|-----------------| -| Crea componente | ⌥ ⌘ K | Ctrl + Alt + K | -| Crea set | ⇧ ⌘ K | Shift + Ctrl + K | -| Separa istanza | ⌥ ⌘ B | Ctrl + Alt + B | +| Crea componente | ⌥⌘K | Ctrl + Alt + K | +| Crea set | ⇧⌘K | Shift + Ctrl + K | +| Separa istanza | ⌥⌘B | Ctrl + Alt + B | diff --git a/packages/docs/it/user-guide/context-menu.md b/packages/docs/it/user-guide/context-menu.md index e2d90b100..1122fbecd 100644 --- a/packages/docs/it/user-guide/context-menu.md +++ b/packages/docs/it/user-guide/context-menu.md @@ -14,23 +14,23 @@ Il sottomenu **Copia come** offre questi formati: |--------|-----|-----------------| | Copia come testo | — | — | | Copia come SVG | — | — | -| Copia come PNG | ⇧ ⌘ C | Shift + Ctrl + C | +| Copia come PNG | ⇧⌘C | Shift + Ctrl + C | | Copia come JSX | — | — | ## Appunti -Copia (⌘C), Taglia (⌘X), Incolla (⌘V), Duplica (⌘D), Elimina (⌫) +Copia (⌘C), Taglia (⌘X), Incolla (⌘V), Duplica (⌘D), Elimina (⌫) ## Ordine Z **]** porta in primo piano · **[** manda in fondo ## Raggruppamento -Raggruppa (⌘G), Separa (⇧⌘G), Aggiungi auto-layout (⇧A) +Raggruppa (⌘G), Separa (⇧⌘G), Aggiungi auto-layout (⇧A) ## Componenti -Crea componente (⌥⌘K), Crea set componenti (⇧⌘K), Crea istanza, Vai al componente principale, Separa istanza (⌥⌘B). Azioni in viola. +Crea componente (⌥⌘K), Crea set componenti (⇧⌘K), Crea istanza, Vai al componente principale, Separa istanza (⌥⌘B). Azioni in viola. ## Visibilità e blocco -Nascondi/Mostra (⇧⌘H), Blocca/Sblocca (⇧⌘L) +Nascondi/Mostra (⇧⌘H), Blocca/Sblocca (⇧⌘L) ## Sposta in pagina Sottomenu con tutte le pagine tranne quella corrente. diff --git a/packages/docs/it/user-guide/drawing-shapes.md b/packages/docs/it/user-guide/drawing-shapes.md index c8084fe16..efc9252c5 100644 --- a/packages/docs/it/user-guide/drawing-shapes.md +++ b/packages/docs/it/user-guide/drawing-shapes.md @@ -6,17 +6,17 @@ description: Creare rettangoli, ellissi, linee, frame e sezioni in OpenPencil. | Strumento | Scorciatoia | Descrizione | |-----------|-------------|-------------| -| Rettangolo | R | Disegna un rettangolo | -| Ellisse | O | Disegna un'ellisse | -| Linea | L | Disegna una linea | -| Frame | F | Disegna un frame (contenitore) | -| Sezione | S | Disegna una sezione | +| Rettangolo | R | Disegna un rettangolo | +| Ellisse | O | Disegna un'ellisse | +| Linea | L | Disegna una linea | +| Frame | F | Disegna un frame (contenitore) | +| Sezione | S | Disegna una sezione | ## Forme aggiuntive **Poligono** e **Stella** nel flyout delle forme. ## Disegno vincolato -**Shift** durante il trascinamento: rettangolo → quadrato, ellisse → cerchio, linea → 0°/45°/90°. +Shift durante il trascinamento: rettangolo → quadrato, ellisse → cerchio, linea → 0°/45°/90°. ## Proprietà - **Riempimento** — colore solido, gradiente (lineare, radiale, angolare, diamante), immagine diff --git a/packages/docs/it/user-guide/exporting.md b/packages/docs/it/user-guide/exporting.md index 3fe0d4e88..451754f7c 100644 --- a/packages/docs/it/user-guide/exporting.md +++ b/packages/docs/it/user-guide/exporting.md @@ -17,8 +17,8 @@ Seleziona un nodo e usa la sezione Export nel pannello proprietà. | Metodo | Mac | Windows / Linux | |--------|-----|-----------------| -| Scorciatoia tastiera | ⇧ ⌘ E | Shift + Ctrl + E | -| Menu contestuale | Tasto destro → Esporta… | Tasto destro → Esporta… | +| Scorciatoia tastiera | ⇧⌘E | Shift + Ctrl + E | +| Menu contestuale | Tasto destro → Esporta… | Tasto destro → Esporta… | | Pannello proprietà | Pulsante "Esporta" | Pulsante "Esporta" | ## Copia come @@ -29,16 +29,18 @@ Il menu contestuale **Copia come** offre formati aggiuntivi: |--------|-----|-----------------| | Copia come testo | — | — | | Copia come SVG | — | — | -| Copia come PNG | ⇧ ⌘ C | Shift + Ctrl + C | +| Copia come PNG | ⇧⌘C | Shift + Ctrl + C | | Copia come JSX | — | — | ## Operazioni file .fig | Action | Mac | Windows / Linux | |--------|-----|-----------------| -| Apri | ⌘ O | Ctrl + O | -| Salva | ⌘ S | Ctrl + S | -| Salva come | ⇧ ⌘ S | Shift + Ctrl + S | +| Apri | ⌘O | Ctrl + O | +| Salva | ⌘S | Ctrl + S | +| Salva come | ⇧⌘S | Shift + Ctrl + S | + +I file salvati sono compressi e includono una miniatura per l'anteprima nel file manager. Compatibilità round-trip con Figma. diff --git a/packages/docs/it/user-guide/index.md b/packages/docs/it/user-guide/index.md index a7b1c701f..e95244e0b 100644 --- a/packages/docs/it/user-guide/index.md +++ b/packages/docs/it/user-guide/index.md @@ -9,7 +9,7 @@ description: Impara a usare OpenPencil — navigazione canvas, disegno, testo, c OpenPencil è un editor di design open-source, compatibile con Figma — completamente locale, IA-nativo e programmabile. ::: tip Scorciatoie multipiattaforma -**⌘** = Command (Ctrl su Windows/Linux), **⌥** = Option (Alt), **⇧** = Shift. +⌘ = Command (Ctrl su Windows/Linux), ⌥ = Option (Alt), ⇧ = Shift. ::: ## Orientamento diff --git a/packages/docs/it/user-guide/layers-and-pages.md b/packages/docs/it/user-guide/layers-and-pages.md index 09f384381..39943824b 100644 --- a/packages/docs/it/user-guide/layers-and-pages.md +++ b/packages/docs/it/user-guide/layers-and-pages.md @@ -16,7 +16,7 @@ Albero gerarchico sulla sinistra. Espandi/comprimi, trascina per riordinare, att Ogni pagina ha il suo viewport indipendente. ## Pannello proprietà -Tre tab: **Design** (proprietà contestuali), **Codice** (JSX / Tailwind CSS v4), **IA** (chat ⌘ J). +Tre tab: **Design** (proprietà contestuali), **Codice** (JSX / Tailwind CSS v4), **IA** (chat ⌘J). Design: aspetto, riempimento, contorno, effetti, tipografia, layout, esportazione. diff --git a/packages/docs/it/user-guide/pen-tool.md b/packages/docs/it/user-guide/pen-tool.md index a8e9e5e2d..7d99cf553 100644 --- a/packages/docs/it/user-guide/pen-tool.md +++ b/packages/docs/it/user-guide/pen-tool.md @@ -8,19 +8,19 @@ description: Percorsi vettoriali con curve di Bézier in OpenPencil. **P** ## Posizionare punti -- **Click** — corner point -- **Click + drag** — curve point with Bézier tangent handles +- **Click** — punto angolare (segmento rettilineo) +- **Click + trascina** — punto curvo con maniglie tangenti di Bézier ## Chiudere un percorso -Click the first point to close into a loop. +Clicca sul primo punto del percorso per chiuderlo in un anello. I percorsi chiusi possono essere riempiti. ## Percorsi aperti -**Escape** to commit as open path. +Premi Escape per confermare il percorso corrente come percorso aperto. ## Reti vettoriali -Vector network data model, compatible with Figma `vectorNetworkBlob`. +I percorsi in OpenPencil usano reti vettoriali — un modello più flessibile delle semplici liste di punti, che supporta percorsi ramificati e topologie complesse. Questo è lo stesso modello usato da Figma, quindi i percorsi si preservano perfettamente nei file .fig. -| Action | Mac | Windows / Linux | +| Azione | Mac | Windows / Linux | |--------|-----|-----------------| -| Pen tool | P | P | -| Commit | Escape | Escape | +| Strumento penna | P | P | +| Conferma percorso | Escape | Escape | diff --git a/packages/docs/it/user-guide/selection-and-manipulation.md b/packages/docs/it/user-guide/selection-and-manipulation.md index b455af48f..bd2078c7a 100644 --- a/packages/docs/it/user-guide/selection-and-manipulation.md +++ b/packages/docs/it/user-guide/selection-and-manipulation.md @@ -6,29 +6,29 @@ description: Selezionare, spostare, ridimensionare, ruotare e organizzare nodi i ## Selezionare - **Click** su un nodo per selezionarlo -- **Shift + click** per aggiungere/rimuovere dalla selezione +- Shift + click per aggiungere/rimuovere dalla selezione - **Trascinamento marquee** — trascina sul canvas vuoto per la selezione rettangolare -- **⌘ A** — seleziona tutto +- ⌘A — seleziona tutto - **Click su canvas vuoto** — deseleziona tutto ## Spostare - **Trascinamento** del nodo selezionato -- **Frecce** — sposta di 1 px · **Shift + frecce** — 10 px +- **Frecce** — sposta di 1 px · Shift + frecce — 10 px ## Ridimensionare -8 maniglie (4 angoli + 4 punti medi). **Shift + trascinamento** mantiene le proporzioni. +8 maniglie (4 angoli + 4 punti medi). Shift + trascinamento mantiene le proporzioni. ## Ruotare -Passa vicino a un angolo per il cursore di rotazione. **Shift** scatta a incrementi di 15°. +Passa vicino a un angolo per il cursore di rotazione. Shift scatta a incrementi di 15°. ## Duplicare -- **Alt + trascinamento** — duplica e sposta · **⌘ D** — duplica sul posto +- Alt + trascinamento — duplica e sposta · ⌘D — duplica sul posto ## Eliminare -**Backspace** o **Canc** +Backspace o **Canc** ## Ordine Z **]** porta in primo piano · **[** manda in fondo ## Visibilità e blocco -**⇧ ⌘ H** visibilità · **⇧ ⌘ L** blocco +⇧⌘H visibilità · ⇧⌘L blocco diff --git a/packages/docs/it/user-guide/text-editing.md b/packages/docs/it/user-guide/text-editing.md index ef97abaaf..07fb2b38f 100644 --- a/packages/docs/it/user-guide/text-editing.md +++ b/packages/docs/it/user-guide/text-editing.md @@ -5,7 +5,7 @@ description: Creare e modificare testo con formattazione rich in OpenPencil. # Modifica testo ## Creare testo -Premi **T**, poi clicca sul canvas. Inizia a digitare immediatamente. +Premi T, poi clicca sul canvas. Inizia a digitare immediatamente. ## Modifica inline Doppio click su un nodo testo per entrare in modalità modifica. Clicca fuori per confermare. @@ -13,22 +13,26 @@ Doppio click su un nodo testo per entrare in modalità modifica. Clicca fuori pe ## Navigazione cursore | Azione | Mac | Windows / Linux | |--------|-----|-----------------| -| Sinistra/destra | ← / → | ← / → | -| Su/giù | ↑ / ↓ | ↑ / ↓ | -| Per parola | ⌥ ← / ⌥ → | Ctrl + ← / Ctrl + → | -| Inizio/fine riga | ⌘ ← / ⌘ → | Home / End | +| Sinistra/destra | ← / → | ← / → | +| Su/giù | ↑ / ↓ | ↑ / ↓ | +| Per parola | ⌥← / ⌥→ | Ctrl + ← / Ctrl + → | +| Inizio/fine riga | ⌘← / ⌘→ | Home / End | -**Shift** estende la selezione. +Shift estende la selezione. ## Formattazione rich text | Azione | Mac | Windows / Linux | |--------|-----|-----------------| -| Grassetto | ⌘ B | Ctrl + B | -| Corsivo | ⌘ I | Ctrl + I | -| Sottolineato | ⌘ U | Ctrl + U | +| Grassetto | ⌘B | Ctrl + B | +| Corsivo | ⌘I | Ctrl + I | +| Sottolineato | ⌘U | Ctrl + U | ## Selettore font -Ricerca, anteprima e scroll virtuale. Font di sistema su desktop (Tauri), Local Font Access API nel browser. +Ricerca, anteprima e scroll virtuale. + +## Fonti dei font +- **App desktop** — tutti i font di sistema disponibili +- **Browser** — font di sistema disponibili in Chrome e Edge ## Suggerimenti - Input IME (cinese, giapponese, coreano) completamente supportato. diff --git a/packages/docs/pl/development/roadmap.md b/packages/docs/pl/development/roadmap.md index 92dede833..ccced2262 100644 --- a/packages/docs/pl/development/roadmap.md +++ b/packages/docs/pl/development/roadmap.md @@ -4,7 +4,7 @@ ### Faza 1: Silnik Core ✅ -SceneGraph, renderowanie Skia, podstawowe kształty, selekcja, zoom/pan, cofnij/ponów, linie wyrównania. +`SceneGraph`, renderowanie Skia, podstawowe kształty, selekcja, zoom/pan, cofnij/ponów, linie wyrównania. ### Faza 2: UI Edytora + Layout ✅ @@ -16,7 +16,7 @@ Import/eksport .fig, kodek Kiwi, schowek, narzędzie pióra, sieci wektorowe, gr ### Faza 4: Komponenty + Zmienne ✅ -Komponenty, instancje, nadpisania, zestawy komponentów, zmienne (COLOR/FLOAT/STRING/BOOLEAN), kolekcje, tryby, eksport obrazów, menu kontekstowe, formatowanie tekstu bogatego. +Komponenty, instancje, nadpisania, zestawy komponentów, zmienne (`COLOR`/FLOAT/STRING/BOOLEAN), kolekcje, tryby, eksport obrazów, menu kontekstowe, formatowanie tekstu bogatego. ### Faza 5: Integracja AI i Narzędzia ✅ @@ -24,7 +24,7 @@ Komponenty, instancje, nadpisania, zestawy komponentów, zmienne (COLOR/FLOAT/ST - @open-pencil/core wyodrębniony do packages/core/ (zero zależności DOM) - @open-pencil/cli z headless operacjami .fig (info, tree, find, export, analyze, eval) - Polecenie `eval` z API Plugin kompatybilnym z Figmą -- Chat AI: bezpośrednie połączenie OpenRouter, 87 narzędzi w `packages/core/src/tools/`, ⌘J +- Chat AI: bezpośrednie połączenie OpenRouter, 87 narzędzi w `packages/core/src/tools/`, ⌘J - 49 dodatkowych narzędzi AI/MCP przeniesionych z figma-use (75 łącznie) - Serwer MCP (@open-pencil/mcp): stdio + HTTP, 87 narzędzi core + 3 zarządzanie plikami - Ujednolicone definicje narzędzi: zdefiniuj raz w `packages/core/src/tools/`, adaptuj dla chatu AI (valibot), MCP (zod), CLI (eval) @@ -44,7 +44,7 @@ Komponenty, instancje, nadpisania, zestawy komponentów, zmienne (COLOR/FLOAT/ST - Tryb śledzenia: klik na avatar peera aby śledzić viewport - Lokalna persystencja przez y-indexeddb - Renderowanie efektów: cień rzucany, cień wewnętrzny, rozmycie warstwy/tła/pierwszego planu -- Karty multi-plikowe: ⌘N/⌘T nowa karta, ⌘W zamknij, ⌘O otwórz +- Karty multi-plikowe: ⌘N/⌘T nowa karta, ⌘W zamknij, ⌘O otwórz - Podpisywanie kodu Apple i notaryzacja dla macOS - Buildy Linux (x64) dodane do CI - Strona dokumentacji VitePress z i18n (6 języków) @@ -53,7 +53,7 @@ Komponenty, instancje, nadpisania, zestawy komponentów, zmienne (COLOR/FLOAT/ST - Prototypowanie (połączenia ramek, przejścia, animacje) - Komentarze (pin, wątki, rozwiązywanie) - Wsparcie PWA -- Przełączanie wariantów, UI zmiennych FLOAT/STRING/BOOLEAN, theming przez zmienne +- Przełączanie wariantów, UI zmiennych `FLOAT`/STRING/BOOLEAN, theming przez zmienne ## Harmonogram diff --git a/packages/docs/pl/eval-command.md b/packages/docs/pl/eval-command.md deleted file mode 100644 index 749d17feb..000000000 --- a/packages/docs/pl/eval-command.md +++ /dev/null @@ -1,77 +0,0 @@ -# `open-pencil eval` — API Pluginów kompatybilne z Figmą do skryptowania headless - -## Przegląd - -`bun open-pencil eval --code ''` wykonuje JavaScript na pliku `.fig` z globalnym obiektem `figma` kompatybilnym z Figmą. Umożliwia to skryptowanie headless, operacje wsadowe, wykonywanie narzędzi AI i testy — wszystko bez GUI. - -Obiekt `figma` odzwierciedla powierzchnię API Pluginów Figmy jak najdokładniej, więc istniejąca wiedza o pluginach Figmy i fragmenty kodu są bezpośrednio przenośne. - -```bash -# Utworzenie ramki, ustawienie auto-layout, dodanie dzieci -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.fills = [{ type: "SOLID", color: { r: 1, g: 1, b: 1 } }] - return { id: frame.id, name: frame.name } -' - -# Zapytanie o węzły -bun open-pencil eval design.fig --code ' - const buttons = figma.currentPage.findAll(n => n.name.includes("Button")) - return buttons.map(b => ({ id: b.id, name: b.name })) -' - -# Zapis zmian -bun open-pencil eval design.fig --code '...' --write -``` - -## Architektura - -``` -CLI: open-pencil eval --code '...' - → loadDocument(file) → SceneGraph - → FigmaAPI(sceneGraph) → proxy `figma` - → AsyncFunction('figma', code)(figmaProxy) - → wydruk wyniku / zapis pliku z --write -``` - -### Główne klasy - -| Klasa | Lokalizacja | Rola | -|-------|-------------|------| -| `FigmaAPI` | `packages/core/src/figma-api.ts` | Obiekt proxy implementujący metody `figma.*` | -| `FigmaNode` | `packages/core/src/figma-api.ts` | Proxy opakowujący `SceneNode` z dostępem do właściwości w stylu Figmy | -| Polecenie `eval` | `packages/cli/src/commands/eval.ts` | Ładuje dokument, tworzy API, wykonuje kod | - -### Dlaczego w `@open-pencil/core`? - -Klasa `FigmaAPI` żyje w core, ponieważ: narzędzia AI ją reużywają, testy mogą jej używać i nie ma zależności DOM. - -## Polecenie CLI - -``` -bun open-pencil eval [opcje] - -Argumenty: - file Plik .fig do przetworzenia - -Opcje: - --code, -c Kod JavaScript do wykonania - --stdin Odczyt kodu ze stdin - --write, -w Zapis zmian do pliku wejściowego - -o, --output Zapis do innego pliku - --json Wynik jako JSON - --quiet, -q Pomiń wydruk -``` - -## Implementacja fazowa - -- **Faza 1: Core** — tworzenie węzłów, właściwości, operacje na drzewie, auto-layout, tekst (~80% realnych skryptów) -- **Faza 2: Komponenty i Instancje** — createComponent, createInstance, detachInstance -- **Faza 3: Zmienne** — getLocalVariables, createVariable, setBoundVariable -- **Faza 4: Style i Zaawansowane** — style paint/tekst/efekty, operacje boolowskie - -[Pełna referencja API po angielsku](/eval-command) diff --git a/packages/docs/pl/guide/architecture.md b/packages/docs/pl/guide/architecture.md index 6960e88e8..d20a0b420 100644 --- a/packages/docs/pl/guide/architecture.md +++ b/packages/docs/pl/guide/architecture.md @@ -2,7 +2,7 @@ ## Przegląd systemu -```mermaid +`mermaid graph TB subgraph Tauri["Tauri v2 Shell"] subgraph Editor["Editor (Web)"] @@ -22,7 +22,7 @@ graph TB MCP["MCP Server (90 tools, stdio+HTTP)"] Collab["P2P Collab (Trystero + Yjs)"] end -``` +` ## Układ edytora @@ -62,7 +62,7 @@ Yoga od Mety zapewnia obliczanie layoutu CSS flexbox. Cienki adapter mapuje nazw ### Format pliku (Kiwi binarny) -Wykorzystuje binarny kodek Kiwi Figmy z 194 definicjami wiadomości/enum/struct. Import: parsowanie nagłówka → dekompresja Zstd → dekodowanie Kiwi → NodeChange[] → graf sceny. Eksport odwraca proces z generowaniem miniatur. +Wykorzystuje binarny kodek Kiwi Figmy z 194 definicjami wiadomości/enum/struct. Import: parsowanie nagłówka → dekompresja Zstd → dekodowanie Kiwi → `NodeChange`[] → graf sceny. Eksport odwraca proces z generowaniem miniatur. Zobacz [Referencja formatu pliku](/reference/file-format) dla szczegółów. @@ -108,7 +108,7 @@ Przejścia między ramkami, wyzwalacze interakcji (kliknięcie, najechanie, prze ### CSS Grid Layout -Yoga WASM obecnie obsługuje tylko flexbox. CSS Grid jest upstream w [facebook/yoga#1893](https://github.com/facebook/yoga/pull/1893). OpenPencil adoptuje go po wydaniu nowej wersji Yoga. +CSS Grid jest obsługiwany przez [fork Yoga](https://github.com/open-pencil/yoga/tree/grid) z cherry-picked PR-ami grid z upstream. Wybierz ramkę, kliknij ikonę siatki, aby przełączyć z flex na grid. Konfiguruj ścieżki kolumn/wierszy (fr, stałe px, auto), odstępy kolumn i wierszy oraz padding po każdej stronie. ### Podpisywanie kodu Windows diff --git a/packages/docs/pl/guide/comparison.md b/packages/docs/pl/guide/comparison.md index 1c8e6e4fb..d17256383 100644 --- a/packages/docs/pl/guide/comparison.md +++ b/packages/docs/pl/guide/comparison.md @@ -215,7 +215,7 @@ Zarządzanie stanem przez Potok. Cofanie z wektorami zmian odwrotnych (max 50 wp ## 11. Scripting i rozszerzalność -OpenPencil zawiera [komendę `eval`](/eval-command) oferującą API Plugin kompatybilne z Figmą do skryptowania headless. Ponadto 90 narzędzi AI dostępnych przez wbudowany chat, serwer MCP (stdio + HTTP) i CLI. Penpot ma system pluginów z sandboxem, ale bez API skryptowania headless ani integracji MCP. +OpenPencil zawiera [komendę `eval`](/programmable/cli/scripting) oferującą API Plugin kompatybilne z Figmą do skryptowania headless. Ponadto 90 narzędzi AI dostępnych przez wbudowany chat, serwer MCP (stdio + HTTP) i CLI. Penpot ma system pluginów z sandboxem, ale bez API skryptowania headless ani integracji MCP. ## Podsumowanie diff --git a/packages/docs/pl/guide/features.md b/packages/docs/pl/guide/features.md index 5bff3abaf..2e104e15d 100644 --- a/packages/docs/pl/guide/features.md +++ b/packages/docs/pl/guide/features.md @@ -87,7 +87,7 @@ bun add -g @open-pencil/mcp } ``` -Zobacz [Referencja narzędzi MCP](/reference/mcp-tools) dla pełnej listy narzędzi. +Zobacz [Referencja narzędzi MCP](/programmable/mcp-server) dla pełnej listy narzędzi. ## CLI diff --git a/packages/docs/pl/guide/figma-comparison.md b/packages/docs/pl/guide/figma-comparison.md index 7e161c828..916df6ec5 100644 --- a/packages/docs/pl/guide/figma-comparison.md +++ b/packages/docs/pl/guide/figma-comparison.md @@ -16,7 +16,7 @@ Porównanie funkcja po funkcji możliwości Figma Design z aktualnym stanem impl | Panel warstw (lewy panel boczny) | ✅ | Widok drzewa z rozwijaniem/zwijaniem, zmianą kolejności, przełącznikiem widoczności; zmienna szerokość | | Panel stron | ✅ | Dodaj, usuń, zmień nazwę stron; stan viewportu per strona | | Panel właściwości (prawy panel boczny) | ✅ | Sekcje: Wygląd, Wypełnienie, Obrys, Efekty, Typografia, Layout, Pozycja; zmienna szerokość | -| Zoom i panorama | ✅ | Ctrl+scroll, pinch, ⌘+/⌘−/⌘0, spacja+przeciągnij, środkowy przycisk myszy, narzędzie ręki (H) | +| Zoom i panorama | ✅ | Ctrl + scroll, pinch, ⌘+ / ⌘− / ⌘0, spacja+przeciągnij, środkowy przycisk myszy, narzędzie ręki (H) | | Linijki canvasu | ✅ | Linijki góra/lewo z pasmami zaznaczenia i badge'ami współrzędnych | | Kolor tła canvasu | ✅ | Tło per strona przez panel właściwości | | Prowadnice canvasu | 🔲 | Figma obsługuje przeciągane prowadnice z linijek | @@ -36,7 +36,7 @@ Porównanie funkcja po funkcji możliwości Figma Design z aktualnym stanem impl |---------|--------|-------| | Narzędzia kształtów (Prostokąt, Elipsa, Linia, Wielokąt, Gwiazda) | ✅ | Wszystkie podstawowe typy kształtów; boki wielokąta i promień wewnętrzny gwiazdy konfigurowalne | | Ramki | ✅ | Przycinanie zawartości, niezależny układ współrzędnych | -| Grupy | ✅ | ⌘G grupowanie, ⇧⌘G rozgrupowanie | +| Grupy | ✅ | ⌘G grupowanie, ⇧⌘G rozgrupowanie | | Sekcje | ✅ | Pigułki tytułu, auto-adopcja nakładających się węzłów, tekst adaptacyjny do luminancji | | Narzędzie łuku (łuki, półkola, pierścienie) | ✅ | arcData z kątem początkowym/końcowym i promieniem wewnętrznym | | Narzędzie ołówka (odręczne) | 🔲 | Narzędzie rysowania odręcznego Figmy | @@ -46,9 +46,9 @@ Porównanie funkcja po funkcji możliwości Figma Design z aktualnym stanem impl | Wyrównanie i pozycja | ✅ | Pozycja, rotacja, wymiary w panelu | | Kopiuj i wklej obiekty | ✅ | Standardowy schowek + format binarny Kiwi Figmy | | Skaluj warstwy proporcjonalnie | 🟡 | Shift-zmiana rozmiaru utrzymuje proporcje; brak dedykowanego narzędzia Scale (K) | -| Zablokuj i odblokuj warstwy | ✅ | ⇧⌘L przełącza blokadę | -| Przełącz widoczność warstwy | ✅ | Ikona oka w panelu + skrót ⇧⌘H | -| Zmień nazwę warstw | ✅ | Dwuklik - zmiana nazwy inline; Enter/Escape/blur aby zatwierdzić | +| Zablokuj i odblokuj warstwy | ✅ | ⇧⌘L przełącza blokadę | +| Przełącz widoczność warstwy | ✅ | Ikona oka w panelu + skrót ⇧⌘H | +| Zmień nazwę warstw | ✅ | Dwuklik - zmiana nazwy inline; Enter/Escape/blur aby zatwierdzić | | Przenieś na wierzch / Wyślij na spód | ✅ | Skróty ] i [; też w menu kontekstowym | | Przenieś na stronę | ✅ | Przenoszenie węzłów między stronami przez menu kontekstowe | | Ograniczenia (responsywna zmiana rozmiaru) | 🔲 | Przypięcie krawędzi/centrum dla zachowania resize rodzica | @@ -79,7 +79,7 @@ Porównanie funkcja po funkcji możliwości Figma Design z aktualnym stanem impl | Funkcja | Status | Uwagi | |---------|--------|-------| -| Narzędzie tekstowe i edycja inline | ✅ | Natywna edycja na canvasie, phantom textarea, style run (⌘B/I/U, przycisk S) | +| Narzędzie tekstowe i edycja inline | ✅ | Natywna edycja na canvasie, phantom textarea, style run (⌘B / I / U, przycisk S) | | Renderowanie tekstu (Paragraph API) | ✅ | CanvasKit Paragraph do kształtowania, łamania linii, metryk | | Ładowanie czcionek (czcionki systemowe) | ✅ | Inter domyślny, font-kit w Tauri z cache OnceLock, queryLocalFonts w przeglądarce | | Rodzina i grubość czcionki | ✅ | FontPicker z wirtualnym scrollem, wyszukiwaniem, podglądem CSS | @@ -126,7 +126,7 @@ Porównanie funkcja po funkcji możliwości Figma Design z aktualnym stanem impl | Rozmycie tła | ✅ | Rozmycie zawartości za warstwą | | Rozmycie pierwszego planu | ✅ | Rozmycie na pierwszym planie | | Grubość obrysu | ✅ | Konfigurowalny w panelu właściwości | -| Zakończenie obrysu (round, square, arrow) | ✅ | NONE, ROUND, SQUARE, ARROW_LINES, ARROW_EQUILATERAL | +| Zakończenie obrysu (round, square, arrow) | ✅ | `NONE`, `ROUND`, `SQUARE`, `ARROW_LINES`, `ARROW_EQUILATERAL` | | Złączenie obrysu (miter, bevel, round) | ✅ | Wszystkie trzy typy złączeń | | Wzory przerywane | ✅ | Wzór obrysu dash-on/dash-off | | Promień narożnika | ✅ | Jednolity i per narożnik z niezależnym przełącznikiem | @@ -138,14 +138,14 @@ Porównanie funkcja po funkcji możliwości Figma Design z aktualnym stanem impl | Funkcja | Status | Uwagi | |---------|--------|-------| | Przepływ poziomy i pionowy | ✅ | Silnik flexbox Yoga WASM | -| Przełącz auto layout (⇧A) | ✅ | Przełącz na ramce lub owijaj zaznaczenie | +| Przełącz auto layout (⇧A) | ✅ | Przełącz na ramce lub owijaj zaznaczenie | | Gap (odstęp między dziećmi) | ✅ | Konfigurowalny w panelu właściwości | | Padding (jednolity i per strona) | ✅ | Wszystkie cztery strony niezależnie | | Justify content | ✅ | Start, center, end, space-between | | Align items | ✅ | Start, center, end, stretch | | Wymiarowanie dzieci (stałe, wypełnij, dopasuj) | ✅ | Tryby wymiarowania per dziecko | | Wrap | ✅ | Flex wrap dla layoutu wieloliniowego | -| Przepływ auto layout siatka | 🔲 | Auto layout oparty na siatce Figmy | +| Przepływ auto layout siatka | ✅ | CSS Grid przez fork Yoga — ścieżki kolumn/wierszy, odstępy, spany | | Przepływy połączone (zagnieżdżone) | ✅ | Zagnieżdżone ramki auto-layout z różnymi kierunkami | | Zmiana kolejności przeciąganiem w auto layout | ✅ | Wizualny wskaźnik wstawiania | | Min/max szerokość i wysokość | 🔲 | Figma obsługuje ograniczenia min/max | @@ -154,17 +154,17 @@ Porównanie funkcja po funkcji możliwości Figma Design z aktualnym stanem impl | Funkcja | Status | Uwagi | |---------|--------|-------| -| Tworzenie komponentów | 🟡 | ⌥⌘K tworzy z ramki/grupy; brak UI właściwości komponentu jeszcze | -| Zestawy komponentów | 🟡 | ⇧⌘K łączy komponenty; przerywana fioletowa ramka; brak edycji właściwości wariantów | +| Tworzenie komponentów | 🟡 | ⌥⌘K tworzy z ramki/grupy; brak UI właściwości komponentu jeszcze | +| Zestawy komponentów | 🟡 | ⇧⌘K łączy komponenty; przerywana fioletowa ramka; brak edycji właściwości wariantów | | Instancje komponentów | 🟡 | Tworzenie instancji z menu kontekstowego; sync na żywo; brak UI edycji nadpisań | | Warianty | 🔲 | Przełączanie wariantów i selekcja po właściwościach | | Właściwości komponentu | 🔲 | Właściwości boolean, tekst, zamiana instancji | | Propagacja nadpisań | ✅ | Zmiany w głównym komponencie propagowane; nadpisania zachowane | -| Zmienne (kolor, liczba, string, boolean) | 🟡 | COLOR z pełnym UI; FLOAT/STRING/BOOLEAN zdefiniowane bez UI edycji | +| Zmienne (kolor, liczba, string, boolean) | 🟡 | `COLOR` z pełnym UI; `FLOAT`/STRING/BOOLEAN zdefiniowane bez UI edycji | | Kolekcje i tryby zmiennych | 🟡 | Kolekcje, tryby, zmiana activeMode działają; brak UI tematyzacji | | Style (kolor, tekst, efekt, layout) | 🔲 | Presety stylów wielokrotnego użytku | | Biblioteki (publikuj, udostępniaj, aktualizuj) | 🔲 | Współdzielone biblioteki komponentów/stylów | -| Odłącz instancję | ✅ | ⌥⌘B konwertuje instancję na ramkę | +| Odłącz instancję | ✅ | ⌥⌘B konwertuje instancję na ramkę | | Przejdź do głównego komponentu | ✅ | Nawigacja do komponentu źródłowego, cross-page | ## Prototypowanie @@ -187,9 +187,9 @@ Porównanie funkcja po funkcji możliwości Figma Design z aktualnym stanem impl | Funkcja | Status | Uwagi | |---------|--------|-------| -| Import pliku .fig | ✅ | Pełny kodek Kiwi: 194 definicje, ~390 pól per NodeChange | +| Import pliku .fig | ✅ | Pełny kodek Kiwi: 194 definicje, ~390 pól per `NodeChange` | | Eksport pliku .fig | ✅ | Kodowanie Kiwi + kompresja Zstd + generowanie miniatur | -| Zapisz / Zapisz jako | ✅ | ⌘S / ⇧⌘S; natywne dialogi (Tauri), File System Access API (Chrome/Edge), fallback pobierania (Safari) | +| Zapisz / Zapisz jako | ✅ | ⌘S / ⇧⌘S; natywne dialogi (Tauri), File System Access API (Chrome/Edge), fallback pobierania (Safari) | | Schowek Figmy (wklej) | ✅ | Dekodowanie binarnego Kiwi ze schowka Figmy | | Schowek Figmy (kopiuj) | ✅ | Kodowanie binarnego Kiwi czytelnego przez Figmę | | Import pliku Sketch | 🔲 | Parsowanie plików .sketch | diff --git a/packages/docs/pl/guide/tech-stack.md b/packages/docs/pl/guide/tech-stack.md index f26edf144..f65f64af6 100644 --- a/packages/docs/pl/guide/tech-stack.md +++ b/packages/docs/pl/guide/tech-stack.md @@ -60,4 +60,4 @@ Yoga jest utrzymywana przez Metę, przetestowana na miliardach urządzeń React | Technologia | Cel | Faza | |-----------|---------|-------| -| CSS Grid w Yoga | Auto layout oparty na siatce | Zablokowane przez upstream (facebook/yoga#1893) | +| CSS Grid w Yoga | Auto layout oparty na siatce | ✅ Obsługiwane przez [fork Yoga](https://github.com/open-pencil/yoga/tree/grid) | diff --git a/packages/docs/pl/programmable/ai-chat.md b/packages/docs/pl/programmable/ai-chat.md new file mode 100644 index 000000000..71df14d1d --- /dev/null +++ b/packages/docs/pl/programmable/ai-chat.md @@ -0,0 +1,47 @@ +--- +title: Czat AI +description: Wbudowany asystent AI z 87 narzędziami do tworzenia i modyfikowania projektów. +--- + +# Czat AI + +Naciśnij ⌘J (Ctrl + J), aby otworzyć asystenta AI. Opisz czego chcesz — tworzy kształty, ustawia style, zarządza layoutem, pracuje z komponentami i analizuje Twój projekt. + +## Konfiguracja + +1. Otwórz panel czatu AI (⌘J) +2. Kliknij ikonę ustawień +3. Wprowadź swój klucz API OpenRouter +4. Wybierz model (Claude, GPT-4, Gemini itp.) + +Bez backendu, bez subskrypcji — Twój klucz komunikuje się bezpośrednio z OpenRouter. + +## Możliwości + +Asystent dysponuje 87 narzędziami w następujących kategoriach: + +- **Tworzenie** — ramki, kształty, tekst, komponenty, strony. Renderuje JSX dla złożonych layoutów. +- **Stylowanie** — wypełnienia, obrysy, efekty, przezroczystość, zaokrąglenie narożników, tryby mieszania. +- **Layout** — auto-layout, wyrównanie, odstępy, wymiarowanie. +- **Komponenty** — tworzenie komponentów, instancji, zestawów komponentów. Zarządzanie nadpisaniami. +- **Zmienne** — tworzenie/edycja zmiennych, kolekcji, trybów. Wiązanie z wypełnieniami. +- **Zapytania** — wyszukiwanie węzłów, odczyt właściwości, listowanie stron, czcionek, zaznaczenia. +- **Analiza** — paleta kolorów, audyt typografii, spójność odstępów, wykrywanie klastrów. +- **Eksport** — PNG, SVG, JSX z klasami Tailwind. +- **Wektory** — operacje boolowskie, manipulacja ścieżkami. + +## Przykładowe polecenia + +- „Utwórz kartę z tytułem, opisem i niebieskim przyciskiem" +- „Ustaw taki sam border radius dla wszystkich przycisków na tej stronie" +- „Jakie czcionki są używane w tym pliku?" +- „Zmień tło wybranej ramki na gradient od niebieskiego do fioletowego" +- „Wyeksportuj wybraną ramkę jako SVG" +- „Znajdź wszystkie węzły tekstowe z rozmiarem czcionki mniejszym niż 12" + +## Wskazówki + +- Zaznacz węzły przed zapytaniem — asystent wie, co jest zaznaczone. +- Podawaj konkretne kolory, rozmiary i pozycje dla precyzyjnych rezultatów. +- Asystent może modyfikować wiele węzłów w jednej wiadomości. +- Użyj „cofnij" w edytorze, jeśli nie podoba Ci się wynik. diff --git a/packages/docs/pl/programmable/cli/analyzing.md b/packages/docs/pl/programmable/cli/analyzing.md new file mode 100644 index 000000000..a9ebd5a60 --- /dev/null +++ b/packages/docs/pl/programmable/cli/analyzing.md @@ -0,0 +1,65 @@ +--- +title: Analiza projektów +description: Audytuj kolory, typografię, odstępy i powtarzające się wzorce w plikach .fig. +--- + +# Analiza projektów + +Polecenia `analyze` audytują cały system projektowy z terminala — znajdują niespójności, wyodrębniają rzeczywistą paletę i wykrywają komponenty czekające na wydzielenie. + +## Kolory + +```sh +open-pencil analyze colors design.fig +``` + +Znajduje każdy kolor w pliku, zlicza użycie i wyświetla wizualny histogram: + +``` +#1d1b20 ██████████████████████████████ 17155× +#49454f ██████████████████████████████ 9814× +#ffffff ██████████████████████████████ 8620× +#6750a4 ██████████████████████████████ 3967× +``` + +## Typografia + +```sh +open-pencil analyze typography design.fig +``` + +Listuje każdą kombinację rodziny czcionek, rozmiaru i grubości wraz z liczbą użyć. Przydatne do wykrywania jednorazowych stylów tekstowych, które powinny zostać ujednolicone. + +## Odstępy + +```sh +open-pencil analyze spacing design.fig +``` + +Audytuje wartości gap i padding w ramkach z auto-layoutem. Pomaga zidentyfikować niespójności w skali odstępów — np. przypadkowy `13px` gap wśród wartości `8/16/24`. + +## Klastry + +```sh +open-pencil analyze clusters design.fig +``` + +Znajduje powtarzające się wzorce węzłów, które mogłyby zostać wydzielone jako komponenty: + +``` +3771× frame "container" (100% match) + size: 40×40, structure: Frame > [Frame] + +2982× instance "Checkboxes" (100% match) + size: 48×48, structure: Instance > [Frame] +``` + +## Wyjście JSON + +Wszystkie polecenia analyze obsługują `--json` dla wyjścia w formacie do odczytu maszynowego: + +```sh +open-pencil analyze colors design.fig --json +``` + +Przekieruj do `jq`, zasilaj kontrole CI lub używaj w skryptach egzekwujących budżety tokenów projektowych. diff --git a/packages/docs/pl/programmable/cli/exporting.md b/packages/docs/pl/programmable/cli/exporting.md new file mode 100644 index 000000000..1bc978912 --- /dev/null +++ b/packages/docs/pl/programmable/cli/exporting.md @@ -0,0 +1,59 @@ +--- +title: Eksportowanie +description: Renderuj pliki .fig do PNG, JPG, WEBP, SVG lub JSX z klasami Tailwind. +--- + +# Eksportowanie + +Eksportuj projekty z terminala — obrazy rastrowe, wektory lub kod JSX. + +## Eksport obrazów + +```sh +open-pencil export design.fig # PNG (domyślnie) +open-pencil export design.fig -f jpg -s 2 -q 90 # JPG w 2×, jakość 90 +open-pencil export design.fig -f webp -s 3 # WEBP w 3× +open-pencil export design.fig -f svg # SVG wektor +``` + +Opcje: + +- `-f` — format: `png`, `jpg`, `webp`, `svg`, `jsx` +- `-s` — skala: `1`–`4` +- `-q` — jakość: `0`–`100` (tylko JPG/WEBP) +- `-o` — ścieżka wyjściowa +- `--page` — nazwa strony +- `--node` — ID konkretnego węzła + +## Eksport JSX + +Eksportuj jako JSX z klasami narzędziowymi Tailwind: + +```sh +open-pencil export design.fig -f jsx --style tailwind +``` + +Wynik: + +```html +
+

Card Title

+

Description text

+
+``` + +Obsługuje również `--style openpencil` dla natywnego formatu JSX (zobacz [Renderer JSX](../jsx-renderer)). + +## Miniatury + +```sh +open-pencil export design.fig --thumbnail --width 1920 --height 1080 +``` + +## Tryb żywej aplikacji + +Pomiń plik, aby eksportować z uruchomionej aplikacji: + +```sh +open-pencil export -f png # zrzut ekranu bieżącego płótna +``` diff --git a/packages/docs/pl/programmable/cli/inspecting.md b/packages/docs/pl/programmable/cli/inspecting.md new file mode 100644 index 000000000..c5c8f24ed --- /dev/null +++ b/packages/docs/pl/programmable/cli/inspecting.md @@ -0,0 +1,98 @@ +--- +title: Przeglądanie plików +description: Przeglądaj drzewa węzłów, szukaj po nazwie lub typie i sprawdzaj właściwości z terminala. +--- + +# Przeglądanie plików + +CLI pozwala eksplorować pliki `.fig` bez otwierania edytora. Każde polecenie działa również na żywej aplikacji — wystarczy pominąć argument pliku. + +::: tip Instalacja +```sh +bun add -g @open-pencil/cli +# lub +brew install open-pencil/tap/open-pencil +``` +::: + +## Informacje o dokumencie + +Szybki przegląd — liczba stron, łączna liczba węzłów, użyte czcionki, rozmiar pliku: + +```sh +open-pencil info design.fig +``` + +## Drzewo węzłów + +Wyświetl pełną hierarchię węzłów: + +```sh +open-pencil tree design.fig +``` + +``` +[0] [page] "Getting started" (0:46566) + [0] [section] "" (0:46567) + [0] [frame] "Body" (0:46568) + [0] [frame] "Introduction" (0:46569) + [0] [frame] "Introduction Card" (0:46570) + [0] [frame] "Guidance" (0:46571) +``` + +## Wyszukiwanie węzłów + +Szukaj po typie: + +```sh +open-pencil find design.fig --type TEXT +``` + +Szukaj po nazwie: + +```sh +open-pencil find design.fig --name "Button" +``` + +Obie flagi można łączyć, aby zawęzić wyniki. + +## Szczegóły węzła + +Sprawdź wszystkie właściwości konkretnego węzła po jego ID: + +```sh +open-pencil node design.fig --id 1:23 +``` + +## Strony + +Wylistuj wszystkie strony w dokumencie: + +```sh +open-pencil pages design.fig +``` + +## Zmienne + +Wylistuj zmienne projektowe i ich kolekcje: + +```sh +open-pencil variables design.fig +``` + +## Tryb żywej aplikacji + +Gdy aplikacja desktopowa jest uruchomiona, pomiń argument pliku — CLI łączy się przez RPC i operuje na żywym płótnie: + +```sh +open-pencil tree # przeglądaj żywy dokument +open-pencil eval -c "..." # odpytuj edytor +``` + +## Wyjście JSON + +Wszystkie polecenia obsługują `--json` dla wyjścia w formacie do odczytu maszynowego — przekieruj do `jq`, zasilaj skrypty CI lub przetwarzaj innymi narzędziami: + +```sh +open-pencil tree design.fig --json | jq '.[] | .name' +``` diff --git a/packages/docs/pl/programmable/cli/scripting.md b/packages/docs/pl/programmable/cli/scripting.md new file mode 100644 index 000000000..210e21a5e --- /dev/null +++ b/packages/docs/pl/programmable/cli/scripting.md @@ -0,0 +1,70 @@ +--- +title: Skryptowanie +description: Wykonuj JavaScript z Figma Plugin API — odpytuj węzły, modyfikuj projekty wsadowo, twórz ramki. +--- + +# Skryptowanie + +`open-pencil eval` daje Ci pełne Figma Plugin API w terminalu. Odczytuj węzły, modyfikuj właściwości, twórz kształty — a następnie zapisz zmiany z powrotem do pliku. + +## Podstawowe użycie + +```sh +open-pencil eval design.fig -c "figma.currentPage.children.length" +``` + +Flaga `-c` przyjmuje JavaScript. Globalny obiekt `figma` działa jak Figma Plugin API. + +## Odpytywanie węzłów + +```sh +open-pencil eval design.fig -c " + figma.currentPage.findAll(n => n.type === 'FRAME' && n.name.includes('Button')) + .map(b => ({ id: b.id, name: b.name, w: b.width, h: b.height })) +" +``` + +## Modyfikacja i zapis + +```sh +open-pencil eval design.fig -c " + figma.currentPage.children.forEach(n => n.opacity = 0.5) +" -w +``` + +`-w` zapisuje zmiany z powrotem do pliku wejściowego. Użyj `-o output.fig`, aby zapisać do innego pliku. + +## Odczyt ze stdin + +Dla dłuższych skryptów: + +```sh +cat transform.js | open-pencil eval design.fig --stdin -w +``` + +## Tryb żywej aplikacji + +Pomiń plik, aby uruchomić na działającej aplikacji desktopowej: + +```sh +open-pencil eval -c "figma.currentPage.name" +``` + +## Dostępne API + +Obiekt `figma` obsługuje: + +- `figma.currentPage` — aktywna strona +- `figma.root` — korzeń dokumentu +- `figma.createFrame()`, `figma.createRectangle()`, `figma.createEllipse()`, `figma.createText()` itp. +- `.findAll()`, `.findOne()` — wyszukiwanie potomków +- `.appendChild()`, `.insertChild()` — manipulacja drzewem +- Wszystkie settery właściwości: `.fills`, `.strokes`, `.effects`, `.opacity`, `.cornerRadius`, `.layoutMode`, `.itemSpacing` itp. + +To jest to samo API, którego używają wtyczki Figma, więc istniejąca wiedza i fragmenty kodu można zastosować bezpośrednio. + +## Wyjście JSON + +```sh +open-pencil eval design.fig -c "..." --json +``` diff --git a/packages/docs/pl/programmable/collaboration.md b/packages/docs/pl/programmable/collaboration.md new file mode 100644 index 000000000..2a58d0a96 --- /dev/null +++ b/packages/docs/pl/programmable/collaboration.md @@ -0,0 +1,38 @@ +--- +title: Współpraca +description: Wspólna edycja w czasie rzeczywistym przez P2P WebRTC — bez serwera, bez konta. +--- + +# Współpraca + +Edytujcie projekty razem w czasie rzeczywistym. Uczestnicy łączą się bezpośrednio — żaden serwer nie przekazuje Twoich danych, konto nie jest wymagane. + +## Udostępnianie pokoju + +1. Kliknij przycisk udostępniania w prawym górnym rogu +2. Skopiuj wygenerowany link (`app.openpencil.dev/share/`) +3. Wyślij go swoim współpracownikom + +Każdy z linkiem może dołączyć. Pokój pozostaje aktywny, dopóki przynajmniej jeden uczestnik ma otwartą stronę. + +## Co się synchronizuje + +- **Zmiany w dokumencie** — każda edycja (kształty, tekst, właściwości, layout) synchronizuje się natychmiast +- **Kursory** — widzisz, gdzie wskazuje każdy współpracownik, wraz z imieniem i kolorem +- **Zaznaczenia** — podświetlone zaznaczenia są widoczne dla wszystkich + +## Tryb śledzenia + +Kliknij awatar współpracownika na górnym pasku, aby śledzić jego widok. Twoje płótno przesuwa się i przybliża zgodnie z jego widokiem. Kliknij ponownie, aby przestać śledzić. + +## Jak to działa + +Uczestnicy łączą się bezpośrednio przez WebRTC — Twoje dane projektowe trafiają prosto z przeglądarki do przeglądarki, nigdy przez centralny serwer. Stan dokumentu wykorzystuje CRDT (bezkonfliktowy replikowany typ danych), więc równoczesne edycje łączą się automatycznie bez konfliktów. + +Pokój jest przechowywany lokalnie — jeśli odświeżysz stronę, dołączysz ponownie z tym samym stanem. + +## Wskazówki + +- Działa w przeglądarce i w aplikacji desktopowej +- Identyfikatory pokojów są kryptograficznie losowe — tylko osoby z linkiem mogą dołączyć +- Nieaktywne kursory są automatycznie usuwane po rozłączeniu uczestnika diff --git a/packages/docs/pl/programmable/index.md b/packages/docs/pl/programmable/index.md new file mode 100644 index 000000000..827f59ffc --- /dev/null +++ b/packages/docs/pl/programmable/index.md @@ -0,0 +1,51 @@ +--- +layout: doc +title: AI i automatyzacja +description: Każda operacja w OpenPencil jest skryptowalna — czat AI, CLI, renderer JSX, serwer MCP, współpraca w czasie rzeczywistym. +--- + +# AI i automatyzacja + +OpenPencil traktuje pliki projektowe jako dane. Każda operacja dostępna w edytorze — tworzenie kształtów, ustawianie wypełnień, zarządzanie auto-layoutem, eksportowanie zasobów — jest również dostępna z terminala, z agentów AI i z kodu. Bez wtyczek do instalowania, bez kluczy API, bez listy oczekujących. + +Interfejs edytora i interfejsy automatyzacji korzystają z tego samego silnika. Jeśli możesz coś zrobić kliknięciem, możesz to zrobić skryptem. + +## Czat AI + +Wbudowany asystent ma dostęp do 87 narzędzi, które obejmują całą powierzchnię edytora. Opisz czego chcesz w języku naturalnym — „dodaj cień 16px do wszystkich przycisków", „utwórz komponent karty z wariantem ciemnego motywu", „wyeksportuj każdą ramkę na tej stronie w 2×". + +[Czat AI →](./ai-chat) + +## Współpraca + +Edycja wieloosobowa w czasie rzeczywistym przez peer-to-peer WebRTC. Bez serwera, bez konta. Udostępnij link do pokoju i edytujcie wspólnie z kursorami na żywo i trybem śledzenia. Stan dokumentu synchronizuje się przez CRDT, więc edycje łączą się automatycznie nawet przy niestabilnym połączeniu. + +[Współpraca →](./collaboration) + +## Renderer JSX + +Opisz UI jako JSX — tę samą składnię, którą LLM-y już znają z Reacta. Jedno wywołanie może stworzyć całe drzewo komponentów z ramkami, tekstem, auto-layoutem, wypełnieniami i obrysami. Zwięzłe, deklaratywne i porównywalne w diffach. + +W drugą stronę — wyeksportuj dowolne zaznaczenie z powrotem do JSX z klasami Tailwind — przydatne do przekazywania do rozwoju lub do zasilania projektami z powrotem do LLM-a. + +[Renderer JSX →](./jsx-renderer) + +## CLI + +Przeglądaj, eksportuj i analizuj pliki `.fig` bez otwierania edytora. Listuj strony, szukaj węzłów, wyodrębniaj tokeny projektowe, renderuj do PNG — wszystko z terminala z wyjściem JSON do odczytu maszynowego. + +CLI łączy się również z uruchomioną aplikacją desktopową przez RPC, więc możesz skryptować edytor podczas pracy z nim. + +[Przeglądanie plików](./cli/inspecting) · [Eksportowanie](./cli/exporting) · [Analiza projektów](./cli/analyzing) · [Skryptowanie](./cli/scripting) + +## Serwer MCP + +Połącz Claude Code, Cursor, Windsurf lub dowolnego klienta kompatybilnego z MCP z OpenPencil. Serwer udostępnia 90 narzędzi do odczytywania, tworzenia i modyfikowania projektów — te same narzędzia, z których korzysta wbudowany czat AI. Działa przez stdio lub HTTP z obsługą sesji. + +[Serwer MCP →](./mcp-server) + +## Dlaczego otwarte? + +Figma to zamknięta platforma. Ich serwer MCP jest tylko do odczytu. Dostęp przez CDP w przeglądarce został usunięty w wersji 126. Pliki projektowe żyją w zastrzeżonym formacie na cudzych serwerach. Rozwój wtyczek wymaga niestandardowego środowiska uruchomieniowego z ograniczonymi API. + +OpenPencil to alternatywa: open source, licencja MIT, każda operacja skryptowalna, dane przechowywane lokalnie. Twoje pliki projektowe są Twoje — przeglądaj je, przekształcaj, przesyłaj do CI, zasilaj nimi LLM. Bez potrzeby pozwolenia. diff --git a/packages/docs/pl/programmable/jsx-renderer.md b/packages/docs/pl/programmable/jsx-renderer.md new file mode 100644 index 000000000..3fc94c4fb --- /dev/null +++ b/packages/docs/pl/programmable/jsx-renderer.md @@ -0,0 +1,116 @@ +--- +title: Renderer JSX +description: Twórz projekty za pomocą JSX — składni, którą LLM-y już znają z milionów komponentów React. +--- + +# Renderer JSX + +OpenPencil używa JSX jako języka tworzenia projektów. LLM-y widziały miliony komponentów React — opisanie layoutu jako `` jest naturalne, bez potrzeby specjalnego trenowania. Każdy token ma znaczenie, gdy agent AI wykonuje dziesiątki operacji, a JSX jest najbardziej zwięzłą deklaratywną reprezentacją. + +JSX jest również porównywalny w diffach. Gdy AI modyfikuje projekt, zmiana jest diffem JSX — czytelnym, weryfikowalnym, kontrolowalnym wersyjnie. + +## Tworzenie projektów + +Narzędzie `render` (dostępne w czacie AI, MCP i CLI eval) przyjmuje JSX: + +```jsx + + Card Title + Description text + +``` + +W serwerze MCP i czacie AI narzędzie `render` przyjmuje ciągi JSX bezpośrednio. W CLI użyj polecenia `export`, aby pójść w drugą stronę — [eksportowanie projektów jako JSX](./cli/exporting). + +## Elementy + +Wszystkie typy węzłów są dostępne jako elementy JSX: + +| Element | Tworzy | Aliasy | +|---------|--------|--------| +| `` | Ramka (kontener, obsługuje auto-layout) | `` | +| `` | Prostokąt | `` | +| `` | Elipsa / koło | | +| `` | Węzeł tekstowy (dzieci stają się treścią tekstu) | | +| `` | Linia | | +| `` | Gwiazda | | +| `` | Wielokąt | | +| `` | Ścieżka wektorowa | | +| `` | Grupa | | +| `
` | Sekcja | | + +## Właściwości stylów + +Zwięzłe skrócone właściwości inspirowane nazewnictwem Tailwind. + +### Layout + +| Właściwość | Opis | +|------------|------| +| `flex` | `"row"` lub `"col"` — włącza auto-layout | +| `gap` | Odstęp między dziećmi | +| `wrap` | Zawijanie dzieci do następnej linii | +| `rowGap` | Odstęp na osi poprzecznej przy zawijaniu | +| `justify` | `"start"`, `"end"`, `"center"`, `"between"` | +| `items` | `"start"`, `"end"`, `"center"`, `"stretch"` | +| `p`, `px`, `py`, `pt`, `pr`, `pb`, `pl` | Padding | + +### Rozmiar i pozycja + +| Właściwość | Opis | +|------------|------| +| `w`, `h` | Szerokość/wysokość — liczba, `"fill"` lub `"hug"` | +| `minW`, `maxW`, `minH`, `maxH` | Ograniczenia rozmiaru | +| `x`, `y` | Pozycja | + +### Wygląd + +| Właściwość | Opis | +|------------|------| +| `bg` | Wypełnienie tła (kolor hex) | +| `fill` | Alias dla `bg` | +| `stroke` | Kolor obrysu | +| `strokeWidth` | Szerokość obrysu (domyślnie: 1) | +| `rounded` | Zaokrąglenie narożników (lub `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`) | +| `cornerSmoothing` | Gładkie narożniki w stylu iOS (0–1) | +| `opacity` | 0–1 | +| `shadow` | Cień (np. `"0 4 8 #00000040"`) | +| `blur` | Promień rozmycia warstwy | +| `rotate` | Obrót w stopniach | +| `blendMode` | Tryb mieszania | +| `overflow` | `"hidden"` lub `"visible"` | + +### Typografia + +| Właściwość | Opis | +|------------|------| +| `size` / `fontSize` | Rozmiar czcionki | +| `font` / `fontFamily` | Rodzina czcionki | +| `weight` / `fontWeight` | `"bold"`, `"medium"`, `"normal"` lub liczba | +| `color` | Kolor tekstu | +| `textAlign` | `"left"`, `"center"`, `"right"`, `"justified"` | + +## Eksport do JSX + +Konwertuj istniejące projekty z powrotem do JSX: + +```sh +open-pencil export design.fig -f jsx # format OpenPencil +open-pencil export design.fig -f jsx --style tailwind # klasy Tailwind +``` + +Pełen cykl działa: wyeksportuj projekt jako JSX, zmodyfikuj kod, wyrenderuj z powrotem. + +## Wizualne porównywanie + +Ponieważ projekty są reprezentowalne jako JSX, zmiany stają się diffami kodu: + +```diff + +- Old Title ++ New Title + Description + +``` + +Dzięki temu zmiany projektowe są weryfikowalne w pull requestach, śledzone w systemie kontroli wersji i audytowalne w CI. diff --git a/packages/docs/pl/programmable/mcp-server.md b/packages/docs/pl/programmable/mcp-server.md new file mode 100644 index 000000000..e296a6447 --- /dev/null +++ b/packages/docs/pl/programmable/mcp-server.md @@ -0,0 +1,251 @@ +# 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` + +Security defaults (HTTP transport): + +- Binds to `127.0.0.1` by default (`HOST` to override) +- `eval` tool is disabled +- File operations are limited to `OPENPENCIL_MCP_ROOT` (defaults to current working directory) +- CORS is disabled by default; set `OPENPENCIL_MCP_CORS_ORIGIN` to allow one origin +- Optional auth token: `OPENPENCIL_MCP_AUTH_TOKEN` (client sends `Authorization: Bearer ` or `x-mcp-token`) + +Server 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` + +## AI Agent Skill + +Teach your AI coding agent to use OpenPencil tools: + +```sh +npx skills add open-pencil/skills@open-pencil +``` + +Works with Claude Code, Cursor, Windsurf, Codex, and any agent that supports [skills](https://skills.sh). The skill covers the CLI, MCP tools, JSX rendering, eval, and the running app's automation bridge. + +## Tools (90) + +### 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_current_page` | Get the current page name and ID | +| `get_node` | Get detailed properties of a node by ID | +| `find_nodes` | Find nodes by name pattern and/or type | +| `get_components` | List all components in the document | +| `list_pages` | List all pages | +| `list_variables` | List design variables | +| `list_collections` | List variable collections | +| `list_fonts` | List fonts used in the current page | +| `page_bounds` | Get bounding box of all objects on the current page | +| `node_bounds` | Get bounding box of a node | +| `node_ancestors` | Get ancestor chain of a node | +| `node_children` | Get direct children of a node | +| `node_tree` | Get the subtree rooted at a node | +| `node_bindings` | Get variable bindings on a node | + +### Create + +| Tool | Description | +|------|-------------| +| `create_shape` | Create a shape (`FRAME`, `RECTANGLE`, `ELLIPSE`, `TEXT`, `LINE`, `STAR`, `POLYGON`, `SECTION`) | +| `create_vector` | Create a vector node from a path string | +| `create_slice` | Create an export slice | +| `create_page` | Create a new page | +| `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 | +| `node_to_component` | Convert an existing node into a component in-place | + +### 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 | +| `set_rotation` | Set rotation angle in degrees | +| `set_opacity` | Set opacity (0–1) | +| `set_radius` | Set corner radius (uniform or per-corner) | +| `set_minmax` | Set min/max width and height constraints | +| `set_text` | Set text content of a `TEXT` node | +| `set_font` | Set font family and weight | +| `set_font_range` | Set font properties on a character range | +| `set_text_resize` | Set text auto-resize mode (fixed/auto-width/auto-height) | +| `set_visible` | Show or hide a node | +| `set_blend` | Set blend mode | +| `set_locked` | Lock or unlock a node | +| `set_stroke_align` | Set stroke alignment (inside/center/outside) | +| `set_text_properties` | Set text layout: alignment, auto-resize, text case, decoration, truncation | +| `set_layout_child` | Configure auto-layout child: sizing, grow, alignment, absolute positioning | +| `node_move` | Move a node to a new position | +| `node_resize` | Resize a node | +| `node_replace_with` | Replace a node with another node | +| `arrange` | Align or distribute selected nodes | + +### 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 | +| `flatten_nodes` | Flatten nodes into a single vector | +| `boolean_union` | Boolean union of two or more nodes | +| `boolean_subtract` | Boolean subtraction | +| `boolean_intersect` | Boolean intersection | +| `boolean_exclude` | Boolean exclusion | + +### Vector Path + +| Tool | Description | +|------|-------------| +| `path_get` | Get the path data of a vector node | +| `path_set` | Set the path data of a vector node | +| `path_scale` | Scale a vector path | +| `path_flip` | Flip a vector path horizontally or vertically | +| `path_move` | Translate a vector path | + +### Export + +| Tool | Description | +|------|-------------| +| `export_image` | Export nodes as PNG, JPG, or WEBP. Returns base64-encoded image data | +| `export_svg` | Export nodes as SVG markup | + +### Viewport + +| Tool | Description | +|------|-------------| +| `viewport_get` | Get current viewport position and zoom level | +| `viewport_set` | Set viewport position and zoom | +| `viewport_zoom_to_fit` | Zoom viewport to fit specified nodes | + +### Variables + +| Tool | Description | +|------|-------------| +| `get_variable` | Get a variable by ID or name | +| `find_variables` | Find variables by name pattern or type | +| `create_variable` | Create a new variable in a collection | +| `set_variable` | Set a variable value in a mode | +| `delete_variable` | Delete a variable | +| `bind_variable` | Bind a variable to a node property | +| `get_collection` | Get a variable collection by ID or name | +| `create_collection` | Create a new variable collection | +| `delete_collection` | Delete a variable collection | + +### Analyze + +| Tool | Description | +|------|-------------| +| `analyze_colors` | Analyze color palette usage across the document | +| `analyze_typography` | Analyze font/size/weight distribution | +| `analyze_spacing` | Analyze gap and padding values | +| `analyze_clusters` | Detect repeated patterns (potential components) | + +### Diff + +| Tool | Description | +|------|-------------| +| `diff_create` | Create a snapshot of the current document state | +| `diff_show` | Show differences between the current state and a snapshot | + +### 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 | + +Note: `eval` is available over stdio, but disabled in HTTP mode for security. diff --git a/packages/docs/pl/reference/cli.md b/packages/docs/pl/reference/cli.md new file mode 100644 index 000000000..6f83df440 --- /dev/null +++ b/packages/docs/pl/reference/cli.md @@ -0,0 +1,184 @@ +--- +title: CLI Reference +description: Complete reference for all open-pencil commands, options, and flags. +--- + +# CLI Reference + +All commands accept a `.fig` file as a positional argument. When omitted, the CLI connects to the running desktop app via RPC. + +## info + +Show document info — pages, node counts, fonts, file size. + +```sh +open-pencil info [file] [--json] +``` + +| Option | Description | +|--------|-------------| +| `--json` | Output as JSON | + +## tree + +Print the node hierarchy. + +```sh +open-pencil tree [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--page` | Page name (default: first page) | +| `--depth` | Max depth (default: unlimited) | +| `--json` | Output as JSON | + +## find + +Search nodes by name or type. + +```sh +open-pencil find [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--name` | Node name (partial match, case-insensitive) | +| `--type` | Node type: `FRAME`, `TEXT`, `RECTANGLE`, `INSTANCE`, etc. | +| `--page` | Page name (default: all pages) | +| `--limit` | Max results (default: 100) | +| `--json` | Output as JSON | + +## node + +Show detailed properties of a node. + +```sh +open-pencil node [file] --id [--json] +``` + +| Option | Description | +|--------|-------------| +| `--id` | **Required.** Node ID (e.g. `1:23`) | +| `--json` | Output as JSON | + +## pages + +List all pages in the document. + +```sh +open-pencil pages [file] [--json] +``` + +| Option | Description | +|--------|-------------| +| `--json` | Output as JSON | + +## variables + +List design variables and collections. + +```sh +open-pencil variables [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--collection` | Filter by collection name | +| `--type` | Filter by type: `COLOR`, `FLOAT`, `STRING`, `BOOLEAN` | +| `--json` | Output as JSON | + +## export + +Export to PNG, JPG, WEBP, SVG, or JSX. + +```sh +open-pencil export [file] [options] +``` + +| Option | Alias | Description | +|--------|-------|-------------| +| `--format` | `-f` | `png` (default), `jpg`, `webp`, `svg`, `jsx` | +| `--output` | `-o` | Output file path (default: `.`) | +| `--scale` | `-s` | Export scale (default: 1) | +| `--quality` | `-q` | Quality 0–100, JPG/WEBP only (default: 90) | +| `--page` | | Page name (default: first page) | +| `--node` | | Node ID to export (default: all top-level nodes) | +| `--style` | | JSX style: `openpencil` (default), `tailwind` | +| `--thumbnail` | | Export page thumbnail instead of full render | +| `--width` | | Thumbnail width (default: 1920) | +| `--height` | | Thumbnail height (default: 1080) | + +## eval + +Execute JavaScript with the Figma Plugin API. + +```sh +open-pencil eval [file] [options] +``` + +| Option | Alias | Description | +|--------|-------|-------------| +| `--code` | `-c` | JavaScript code to execute | +| `--stdin` | | Read code from stdin | +| `--write` | `-w` | Write changes back to the input file | +| `--output` | `-o` | Write to a different file | +| `--json` | | Output as JSON | +| `--quiet` | `-q` | Suppress output | + +## analyze colors + +Analyze color palette usage across the document. + +```sh +open-pencil analyze colors [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--limit` | Max colors to show (default: 30) | +| `--threshold` | Distance threshold for clustering similar colors, 0–50 (default: 15) | +| `--similar` | Show similar color clusters | +| `--json` | Output as JSON | + +## analyze typography + +Analyze font family, size, and weight distribution. + +```sh +open-pencil analyze typography [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--group-by` | Group by: `family`, `size`, `weight` (default: show all styles) | +| `--limit` | Max styles to show (default: 30) | +| `--json` | Output as JSON | + +## analyze spacing + +Analyze gap and padding values across auto-layout frames. + +```sh +open-pencil analyze spacing [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--grid` | Base grid size to check against (default: 8) | +| `--json` | Output as JSON | + +## analyze clusters + +Find repeated node patterns — potential components. + +```sh +open-pencil analyze clusters [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--limit` | Max clusters to show (default: 20) | +| `--min-size` | Min node size in px (default: 30) | +| `--min-count` | Min instances to form a cluster (default: 2) | +| `--json` | Output as JSON | diff --git a/packages/docs/pl/reference/file-format.md b/packages/docs/pl/reference/file-format.md index cb9dad7af..ea94b8fb6 100644 --- a/packages/docs/pl/reference/file-format.md +++ b/packages/docs/pl/reference/file-format.md @@ -1,71 +1,72 @@ -# Format pliku +# File Format -## Struktura pliku .fig +## .fig File Structure + +A `.fig` file is a ZIP archive containing a Kiwi-encoded binary message: + +| Offset | Content | +|--------|---------| +| 0 | Magic header `fig-kiwi` (8 bytes) | +| 8 | Version (4 bytes, uint32 LE) | +| 12 | Schema length (4 bytes, uint32 LE) | +| 16 | Compressed Kiwi schema | +| … | Message length (4 bytes, uint32 LE) | +| … | Compressed Kiwi message — `NodeChange[]` (entire document) | +| … | Blob data — images, vector networks, fonts | + +## Import Pipeline ``` -┌─────────────────────────────────┐ -│ 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 -└─────────────────────────────────┘ +.fig file → parse header → decompress Zstd → decode Kiwi schema + → decode message → NodeChange[] → build SceneGraph + → resolve blob refs → render on canvas ``` -## Pipeline importu +## Export Pipeline ``` -.fig file → Parse header → Decompress Zstd → Decode Kiwi schema - → Decode Message → NodeChange[] → Build SceneGraph - → Resolve blob refs → Render on canvas +SceneGraph → NodeChange[] → Kiwi encode → compress (Zstd/deflate) + → build ZIP (header + schema + message + thumbnail.png) + → write .fig file ``` -## Pipeline eksportu +Export uses ⌘S (Save) and ⇧⌘S (Save As) with native OS dialogs on the desktop app. The exported file includes a `thumbnail.png` required by Figma for file preview. -``` -SceneGraph → NodeChange[] → Kiwi encode → Compress (Zstd/deflate) - → Build ZIP (header + schema + message + thumbnail.png) - → Write .fig file -``` - -Export uses ⌘S (Save) and ⇧⌘S (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). +Compression uses Zstd via Tauri Rust command on desktop, with deflate fallback in the browser. ## Kiwi Binary Codec -The codec handles Figma's 194-definition Kiwi schema with NodeChange as the central type (~390 fields). Key components: +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 +| Module | Purpose | +|--------|---------| +| `kiwi-schema` | Kiwi parser (from [evanw/kiwi](https://github.com/nicolo-ribaudo/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. +Figma's schema uses non-contiguous field IDs (e.g. 1, 2, 5, 10 with gaps). The kiwi-schema parser handles 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`. +`.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. ## Supported Formats | Format | Import | Export | |--------|--------|--------| -| .fig (Figma) | ✅ | ✅ | -| .svg | Planned | Planned | -| .png | Planned | Planned | -| .pdf | — | Planned | - -See [Roadmap](/development/roadmap) for planned format support timeline. +| `.fig` (Figma) | ✅ | ✅ | +| `.svg` | Planned | Planned | +| `.png` | Planned | Planned | +| `.pdf` | — | Planned | ## 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 +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. +Encoding happens synchronously in the copy event handler (not async Clipboard API) for browser compatibility. This enables bidirectional clipboard between OpenPencil and Figma. diff --git a/packages/docs/pl/reference/mcp-tools.md b/packages/docs/pl/reference/mcp-tools.md deleted file mode 100644 index 6258add4d..000000000 --- a/packages/docs/pl/reference/mcp-tools.md +++ /dev/null @@ -1,150 +0,0 @@ -# Serwer MCP - -OpenPencil zawiera serwer MCP (Model Context Protocol), który umożliwia narzędziom kodowania AI — Claude Code, Cursor, Windsurf itp. — odczyt i modyfikację plików .fig headless. - -Dwa transporty - -## **stdio** dla klientów MCP, **HTTP** dla reszty. - -```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" - } - } -} -``` - -Lub uruchom ze źródeł: - -::: 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` - -## AI Agent Skill - -Install the OpenPencil skill for your AI coding agent: - -```sh -npx skills add open-pencil/skills@open-pencil -``` - -Works with Claude Code, Cursor, Windsurf, Codex, and any agent that supports [skills](https://skills.sh). - -## Tools (75) - -### 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.md index f5e27b1d6..f6024302d 100644 --- a/packages/docs/pl/reference/node-types.md +++ b/packages/docs/pl/reference/node-types.md @@ -1,4 +1,4 @@ -# Typy węzłów +# Node Types 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. @@ -8,41 +8,41 @@ The scene graph supports 28 node types from Figma's Kiwi schema. Each node is id | 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) | ✅ | +| `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) +- `COMPONENT_SET` → variant group container (no dedicated Kiwi ID, mapped from `SYMBOL` with variants) - `POLYGON` → Kiwi `REGULAR_POLYGON` (ID 11) ```typescript @@ -81,14 +81,14 @@ Document ## Core Properties -Every node carries these fields (subset of NodeChange): +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 +- `phase` — `CREATED` or `REMOVED` - `parentIndex` — parent GUID + position string for z-ordering ### Transform @@ -103,14 +103,14 @@ Every node carries these fields (subset of NodeChange): - `strokePaints[]` — stroke colors - `effects[]` — shadows, blurs - `opacity` — 0–1 -- `blendMode` — NORMAL, MULTIPLY, SCREEN, etc. +- `blendMode` — `NORMAL`, `MULTIPLY`, `SCREEN`, etc. ### Stroke - `strokeWeight` — stroke thickness -- `strokeAlign` — inside / center / outside -- `strokeCap` — butt / round / square -- `strokeJoin` — miter / bevel / round +- `strokeAlign` — `INSIDE` / `CENTER` / `OUTSIDE` +- `strokeCap` — `NONE` / `ROUND` / `SQUARE` / `ARROW_LINES` / `ARROW_EQUILATERAL` +- `strokeJoin` — `MITER` / `BEVEL` / `ROUND` - `dashPattern[]` — dash/gap lengths ### Corners diff --git a/packages/docs/pl/reference/scene-graph.md b/packages/docs/pl/reference/scene-graph.md index 119b9849f..0d445d189 100644 --- a/packages/docs/pl/reference/scene-graph.md +++ b/packages/docs/pl/reference/scene-graph.md @@ -1,8 +1,8 @@ -# Graf sceny +# Scene Graph -## Reprezentacja w pamięci +## In-Memory Representation -Węzły żyją w płaskiej mapie `Map` keyed by GUID string. Struktura drzewa utrzymywana przez `parentIndex` references. This gives Wyszukiwanie O(1) by ID and efficient traversal. +Nodes live in a flat `Map` 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 { @@ -31,11 +31,11 @@ interface SceneGraph { ## 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. +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. +`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 @@ -86,11 +86,11 @@ For marquee selection, `getNodesInRect` returns all nodes whose bounds intersect ## 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). +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. +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 diff --git a/packages/docs/pl/user-guide/auto-layout.md b/packages/docs/pl/user-guide/auto-layout.md index 96480b543..97c964133 100644 --- a/packages/docs/pl/user-guide/auto-layout.md +++ b/packages/docs/pl/user-guide/auto-layout.md @@ -4,7 +4,9 @@ description: Auto-layout oparty na flexbox w OpenPencil. --- # Auto-layout -**⇧ A** aby włączyć/wyłączyć lub opakować zaznaczenie. +Auto-layout automatycznie pozycjonuje dzieci wewnątrz ramki, stosując reguły flexbox. Obsługuje kierunek, odstępy, wyrównanie i responsywne rozmiary. + +⇧A aby włączyć/wyłączyć lub opakować zaznaczenie. ## Kierunek - **Poziomy** — od lewej do prawej diff --git a/packages/docs/pl/user-guide/canvas-navigation.md b/packages/docs/pl/user-guide/canvas-navigation.md index 2f835c756..9ba820482 100644 --- a/packages/docs/pl/user-guide/canvas-navigation.md +++ b/packages/docs/pl/user-guide/canvas-navigation.md @@ -9,23 +9,23 @@ Płótno to Twoja nieskończona przestrzeń robocza. ## Przesuwanie -- **Spacja + przeciąganie** — przytrzymaj Spację i przeciągnij +- Spacja + przeciąganie — przytrzymaj Spację i przeciągnij - **Środkowy przycisk myszy** — naciśnij i przeciągnij - **Trackpad dwoma palcami** — przesuń dwoma palcami ## Narzędzie rączka -Naciśnij **H**, aby aktywować narzędzie rączka. Przełącz na inne narzędzie (np. **V**), aby dezaktywować. +Naciśnij H, aby aktywować narzędzie rączka. Przełącz na inne narzędzie (np. **V**), aby dezaktywować. ## Powiększanie -- **Ctrl + scroll** (lub **⌘ + scroll** na Mac) — powiększanie/pomniejszanie +- Ctrl + scroll (lub ⌘ + scroll na Mac) — powiększanie/pomniejszanie - **Gest szczypania** — szczyp na trackpadzie | Akcja | Mac | Windows / Linux | |-------|-----|-----------------| -| Przesuwanie | Spacja + przeciąganie | Spacja + przeciąganie | -| Narzędzie rączka | H | H | -| Powiększ | ⌘ + | Ctrl + + | -| Pomniejsz | ⌘ - | Ctrl + - | -| Zoom 100% | ⌘ 0 | Ctrl + 0 | +| Przesuwanie | Spacja + przeciąganie | Spacja + przeciąganie | +| Narzędzie rączka | H | H | +| Powiększ | ⌘+ | Ctrl + + | +| Pomniejsz | ⌘− | Ctrl + − | +| Zoom 100% | ⌘0 | Ctrl + 0 | diff --git a/packages/docs/pl/user-guide/components.md b/packages/docs/pl/user-guide/components.md index 3dc85e02f..e8dee5c2e 100644 --- a/packages/docs/pl/user-guide/components.md +++ b/packages/docs/pl/user-guide/components.md @@ -5,28 +5,38 @@ description: Komponenty wielokrotnego użytku, instancje, nadpisania i synchroni # Komponenty ## Tworzenie komponentu -**⌥ ⌘ K** (Ctrl+Alt+K) — konwertuje ramkę/grupę na COMPONENT. Fioletowa etykieta z diamentem. +Zaznacz ramkę lub grupę i naciśnij ⌥⌘K (Ctrl + Alt + K). Zaznaczenie staje się komponentem wielokrotnego użytku z fioletową etykietą i ikoną diamentu. ## Zestawy komponentów -**⇧ ⌘ K** — łączy 2+ komponenty z fioletową przerywaną ramką. +⇧⌘K — łączy 2+ komponenty z fioletową przerywaną ramką. ## Tworzenie instancji Prawy przycisk → **Utwórz instancję**. Pojawia się 40 px na prawo. ## Odłączanie instancji -**⌥ ⌘ B** — staje się ramką bez powiązania. +⌥⌘B — staje się ramką bez powiązania. ## Synchronizacja na żywo Edycja komponentu aktualizuje wszystkie instancje. Synchronizowane: wymiary, wypełnienia, obrysy, efekty, przezroczystość, promienie narożników, layout. ## Nadpisania -Instancje mogą nadpisywać właściwości bez zrywania powiązania. +Instancje mogą nadpisywać wybrane właściwości bez zrywania powiązania z komponentem głównym. Nadpisana właściwość jest pomijana podczas synchronizacji — pozostałe właściwości nadal aktualizują się z komponentu. ## Hit testing Kliknięcie zaznacza komponent. **Dwuklik** aby wejść i zaznaczyć dzieci. +## Wygląd + +| Element | Wygląd | +|---------|--------| +| Etykieta komponentu | Fioletowa z ikoną diamentu | +| Etykieta instancji | Fioletowa z ikoną diamentu | +| Ramka zestawu | Fioletowa przerywana ramka | + +## Skróty klawiszowe + | Akcja | Mac | Windows / Linux | |-------|-----|-----------------| -| Utwórz komponent | ⌥ ⌘ K | Ctrl + Alt + K | -| Utwórz zestaw | ⇧ ⌘ K | Shift + Ctrl + K | -| Odłącz instancję | ⌥ ⌘ B | Ctrl + Alt + B | +| Utwórz komponent | ⌥⌘K | Ctrl + Alt + K | +| Utwórz zestaw | ⇧⌘K | Shift + Ctrl + K | +| Odłącz instancję | ⌥⌘B | Ctrl + Alt + B | diff --git a/packages/docs/pl/user-guide/context-menu.md b/packages/docs/pl/user-guide/context-menu.md index 0cdc9c1c2..3273ca186 100644 --- a/packages/docs/pl/user-guide/context-menu.md +++ b/packages/docs/pl/user-guide/context-menu.md @@ -14,23 +14,23 @@ Podmenu **Kopiuj jako** oferuje następujące formaty: |-------|-----|-----------------| | Kopiuj jako tekst | — | — | | Kopiuj jako SVG | — | — | -| Kopiuj jako PNG | ⇧ ⌘ C | Shift + Ctrl + C | +| Kopiuj jako PNG | ⇧⌘C | Shift + Ctrl + C | | Kopiuj jako JSX | — | — | ## Schowek -Kopiuj (⌘C), Wytnij (⌘X), Wklej (⌘V), Duplikuj (⌘D), Usuń (⌫) +Kopiuj (⌘C), Wytnij (⌘X), Wklej (⌘V), Duplikuj (⌘D), Usuń (⌫) ## Kolejność Z **]** na wierzch · **[** na spód ## Grupowanie -Grupuj (⌘G), Rozgrupuj (⇧⌘G), Dodaj auto-layout (⇧A) +Grupuj (⌘G), Rozgrupuj (⇧⌘G), Dodaj auto-layout (⇧A) ## Komponenty -Utwórz komponent (⌥⌘K), Utwórz zestaw (⇧⌘K), Utwórz instancję, Przejdź do głównego komponentu, Odłącz instancję (⌥⌘B). Akcje w kolorze fioletowym. +Utwórz komponent (⌥⌘K), Utwórz zestaw (⇧⌘K), Utwórz instancję, Przejdź do głównego komponentu, Odłącz instancję (⌥⌘B). Akcje w kolorze fioletowym. ## Widoczność i blokada -Ukryj/Pokaż (⇧⌘H), Zablokuj/Odblokuj (⇧⌘L) +Ukryj/Pokaż (⇧⌘H), Zablokuj/Odblokuj (⇧⌘L) ## Przenieś na stronę Podmenu ze wszystkimi stronami oprócz bieżącej. diff --git a/packages/docs/pl/user-guide/drawing-shapes.md b/packages/docs/pl/user-guide/drawing-shapes.md index 8d2984c72..871c21622 100644 --- a/packages/docs/pl/user-guide/drawing-shapes.md +++ b/packages/docs/pl/user-guide/drawing-shapes.md @@ -6,17 +6,17 @@ description: Tworzenie prostokątów, elips, linii, ramek i sekcji w OpenPencil. | Narzędzie | Skrót | Opis | |-----------|-------|------| -| Prostokąt | R | Rysuje prostokąt | -| Elipsa | O | Rysuje elipsę | -| Linia | L | Rysuje linię | -| Ramka | F | Rysuje ramkę (kontener) | -| Sekcja | S | Rysuje sekcję | +| Prostokąt | R | Rysuje prostokąt | +| Elipsa | O | Rysuje elipsę | +| Linia | L | Rysuje linię | +| Ramka | F | Rysuje ramkę (kontener) | +| Sekcja | S | Rysuje sekcję | ## Dodatkowe kształty **Wielokąt** i **Gwiazda** w menu rozwijanym kształtów. ## Rysowanie z ograniczeniami -**Shift** podczas przeciągania: prostokąt → kwadrat, elipsa → koło, linia → 0°/45°/90°. +Shift podczas przeciągania: prostokąt → kwadrat, elipsa → koło, linia → 0°/45°/90°. ## Właściwości - **Wypełnienie** — kolor, gradient (liniowy, radialny, kątowy, diamentowy), obraz diff --git a/packages/docs/pl/user-guide/exporting.md b/packages/docs/pl/user-guide/exporting.md index a5e83d279..3ff32830b 100644 --- a/packages/docs/pl/user-guide/exporting.md +++ b/packages/docs/pl/user-guide/exporting.md @@ -17,8 +17,8 @@ Wybierz węzeł i użyj sekcji Eksport w panelu właściwości. | Metoda | Mac | Windows / Linux | |--------|-----|-----------------| -| Skrót klawiszowy | ⇧ ⌘ E | Shift + Ctrl + E | -| Menu kontekstowe | Prawy klik → Eksportuj… | Prawy klik → Eksportuj… | +| Skrót klawiszowy | ⇧⌘E | Shift + Ctrl + E | +| Menu kontekstowe | Prawy klik → Eksportuj… | Prawy klik → Eksportuj… | | Panel właściwości | Przycisk "Eksportuj" | Przycisk "Eksportuj" | ## Kopiuj jako @@ -29,18 +29,18 @@ Menu kontekstowe **Kopiuj jako** oferuje dodatkowe formaty: |--------|-----|-----------------| | Kopiuj jako tekst | — | — | | Kopiuj jako SVG | — | — | -| Kopiuj jako PNG | ⇧ ⌘ C | Shift + Ctrl + C | +| Kopiuj jako PNG | ⇧⌘C | Shift + Ctrl + C | | Kopiuj jako JSX | — | — | ## Operacje na plikach .fig | Action | Mac | Windows / Linux | |--------|-----|-----------------| -| Otwórz | ⌘ O | Ctrl + O | -| Zapisz | ⌘ S | Ctrl + S | -| Zapisz jako | ⇧ ⌘ S | Shift + Ctrl + S | +| Otwórz | ⌘O | Ctrl + O | +| Zapisz | ⌘S | Ctrl + S | +| Zapisz jako | ⇧⌘S | Shift + Ctrl + S | -Kompatybilność round-trip z Figmą. +Pliki eksportowane z OpenPencil można otwierać w Figmie i odwrotnie. ## Wskazówki diff --git a/packages/docs/pl/user-guide/index.md b/packages/docs/pl/user-guide/index.md index 54082685b..0c87ffc03 100644 --- a/packages/docs/pl/user-guide/index.md +++ b/packages/docs/pl/user-guide/index.md @@ -9,7 +9,7 @@ description: Naucz się korzystać z OpenPencil — nawigacja po płótnie, ryso OpenPencil to open-source'owy edytor graficzny, kompatybilny z Figmą — w pełni lokalny, natywnie AI i programowalny. ::: tip Skróty klawiszowe -**⌘** = Command (Ctrl na Windows/Linux), **⌥** = Option (Alt), **⇧** = Shift. +⌘ = Command (Ctrl na Windows/Linux), ⌥ = Option (Alt), ⇧ = Shift. ::: ## Nawigacja @@ -31,6 +31,6 @@ OpenPencil to open-source'owy edytor graficzny, kompatybilny z Figmą — w peł ## Zaawansowane -- [Auto-layout](./auto-layout) — automatyczne pozycjonowanie oparte na flexbox +- [Auto-layout](./auto-layout) — automatyczne pozycjonowanie dzieci w ramce - [Komponenty](./components) — komponenty wielokrotnego użytku, instancje i nadpisania - [Zmienne](./variables) — zmienne projektowe, kolekcje, tryby diff --git a/packages/docs/pl/user-guide/layers-and-pages.md b/packages/docs/pl/user-guide/layers-and-pages.md index de276105a..688430227 100644 --- a/packages/docs/pl/user-guide/layers-and-pages.md +++ b/packages/docs/pl/user-guide/layers-and-pages.md @@ -5,18 +5,18 @@ description: Zarządzanie warstwami, stronami i panelem właściwości w OpenPen # Warstwy i strony ## Panel warstw -Drzewo hierarchii po lewej. Rozwijanie/zwijanie, przeciąganie aby zmienić kolejność, przełączanie widoczności ikoną oka, **dwuklik aby zmienić nazwę** (Enter lub klik poza polem zatwierdza, Escape anuluje). Zaznaczenie synchronizuje się z płótnem. +Drzewo hierarchii po lewej. Rozwijanie/zwijanie, przeciąganie aby zmienić kolejność, przełączanie widoczności ikoną oka, **dwuklik aby zmienić nazwę** (Enter lub klik poza polem zatwierdza, Escape anuluje). Zaznaczenie synchronizuje się z płótnem. ## Panel stron - **Zmiana strony** — kliknij na zakładkę - **Dodaj** — przycisk dodaj - **Usuń** — usuń bieżącą stronę -- **Zmień nazwę** — dwuklik na nazwie (Enter lub klik poza polem zatwierdza, Escape anuluje) +- **Zmień nazwę** — dwuklik na nazwie (Enter lub klik poza polem zatwierdza, Escape anuluje) Każda strona ma własny niezależny stan widoku. ## Panel właściwości -Trzy zakładki: **Design** (właściwości kontekstowe), **Kod** (JSX / Tailwind CSS v4), **AI** (chat ⌘ J). +Trzy zakładki: **Design** (właściwości kontekstowe), **Kod** (JSX / Tailwind CSS v4), **AI** (chat ⌘J). Design: wygląd, wypełnienie, obrys, efekty, typografia, layout, eksport. diff --git a/packages/docs/pl/user-guide/pen-tool.md b/packages/docs/pl/user-guide/pen-tool.md index 240a38901..084842e1a 100644 --- a/packages/docs/pl/user-guide/pen-tool.md +++ b/packages/docs/pl/user-guide/pen-tool.md @@ -15,12 +15,14 @@ description: Ścieżki wektorowe z krzywymi Béziera in OpenPencil. Click the first point to close into a loop. ## Otwarte ścieżki -**Escape** to commit as open path. +Escape to commit as open path. ## Sieci wektorowe -Vector network data model, compatible with Figma `vectorNetworkBlob`. +Ścieżki w OpenPencil korzystają z sieci wektorowych — elastycznego modelu obsługującego rozgałęzione ścieżki i złożoną topologię. Jest to ten sam model, co w Figmie, więc ścieżki zachowują pełną kompatybilność z plikami .fig. -| Action | Mac | Windows / Linux | -|--------|-----|-----------------| -| Pen tool | P | P | -| Commit | Escape | Escape | +## Skróty klawiszowe + +| Akcja | Mac | Windows / Linux | +|-------|-----|-----------------| +| Narzędzie pióro | P | P | +| Zatwierdź | Escape | Escape | diff --git a/packages/docs/pl/user-guide/selection-and-manipulation.md b/packages/docs/pl/user-guide/selection-and-manipulation.md index b49576f7f..8691400aa 100644 --- a/packages/docs/pl/user-guide/selection-and-manipulation.md +++ b/packages/docs/pl/user-guide/selection-and-manipulation.md @@ -6,29 +6,29 @@ description: Zaznaczanie, przesuwanie, skalowanie, obracanie i organizowanie wę ## Zaznaczanie - **Kliknięcie** na węzeł, aby go zaznaczyć -- **Shift + kliknięcie** aby dodać/usunąć z zaznaczenia +- Shift + kliknięcie aby dodać/usunąć z zaznaczenia - **Przeciąganie prostokąta** — przeciągnij na pustym płótnie -- **⌘ A** — zaznacz wszystko +- ⌘A — zaznacz wszystko - **Kliknięcie na puste płótno** — odznacz wszystko ## Przesuwanie - **Przeciąganie** zaznaczonego węzła -- **Strzałki** — przesuń o 1 px · **Shift + strzałki** — 10 px +- **Strzałki** — przesuń o 1 px · Shift + strzałki — 10 px ## Skalowanie -8 uchwytów. **Shift + przeciąganie** zachowuje proporcje. +8 uchwytów. Shift + przeciąganie zachowuje proporcje. ## Obracanie -Najedź blisko rogu. **Shift** przyciąga do 15°. +Najedź blisko rogu. Shift przyciąga do 15°. ## Duplikowanie -- **Alt + przeciąganie** — duplikuj i przesuń · **⌘ D** — duplikuj w miejscu +- Alt + przeciąganie — duplikuj i przesuń · ⌘D — duplikuj w miejscu ## Usuwanie -**Backspace** lub **Delete** +Backspace lub Delete ## Kolejność Z **]** na wierzch · **[** na spód ## Widoczność i blokada -**⇧ ⌘ H** widoczność · **⇧ ⌘ L** blokada +⇧⌘H widoczność · ⇧⌘L blokada diff --git a/packages/docs/pl/user-guide/text-editing.md b/packages/docs/pl/user-guide/text-editing.md index 1ce5bb20b..8bba76f98 100644 --- a/packages/docs/pl/user-guide/text-editing.md +++ b/packages/docs/pl/user-guide/text-editing.md @@ -5,7 +5,7 @@ description: Tworzenie i edycja tekstu z formatowaniem w OpenPencil. # Edycja tekstu ## Tworzenie tekstu -Naciśnij **T**, kliknij na płótnie. Zacznij pisać natychmiast. +Naciśnij T, kliknij na płótnie. Zacznij pisać natychmiast. ## Edycja inline Dwuklik na węźle tekstowym, aby wejść w tryb edycji. Kliknij poza, aby zatwierdzić. @@ -13,19 +13,29 @@ Dwuklik na węźle tekstowym, aby wejść w tryb edycji. Kliknij poza, aby zatwi ## Nawigacja kursora | Akcja | Mac | Windows / Linux | |-------|-----|-----------------| -| Lewo/prawo | ← / → | ← / → | -| Góra/dół | ↑ / ↓ | ↑ / ↓ | -| Po słowie | ⌥ ← / ⌥ → | Ctrl + ← / Ctrl + → | -| Początek/koniec linii | ⌘ ← / ⌘ → | Home / End | +| Lewo/prawo | ← / → | ← / → | +| Góra/dół | ↑ / ↓ | ↑ / ↓ | +| Po słowie | ⌥← / ⌥→ | Ctrl + ← / Ctrl + → | +| Początek/koniec linii | ⌘← / ⌘→ | Home / End | -**Shift** rozszerza zaznaczenie. +Shift rozszerza zaznaczenie. ## Formatowanie tekstu | Akcja | Mac | Windows / Linux | |-------|-----|-----------------| -| Pogrubienie | ⌘ B | Ctrl + B | -| Kursywa | ⌘ I | Ctrl + I | -| Podkreślenie | ⌘ U | Ctrl + U | +| Pogrubienie | ⌘B | Ctrl + B | +| Kursywa | ⌘I | Ctrl + I | +| Podkreślenie | ⌘U | Ctrl + U | ## Wybór czcionki -Wyszukiwanie, podgląd i wirtualne przewijanie. Czcionki systemowe na desktopie (Tauri), Local Font Access API w przeglądarce. +Otwórz selektor czcionek w sekcji Typografia panelu właściwości. Dostępne funkcje: + +- **Wyszukiwanie** — wpisz, aby przefiltrować listę +- **Podgląd** — każda nazwa czcionki renderowana jest własnym krojem +- **Przewijanie do aktualnej** — bieżąca czcionka jest podświetlona po otwarciu + +## Źródła czcionek + +- **Czcionka domyślna** — Inter jest ładowany automatycznie +- **Aplikacja desktopowa** — dostępne wszystkie czcionki systemowe +- **Przeglądarka** — czcionki systemowe dostępne w Chrome i Edge diff --git a/packages/docs/programmable/ai-chat.md b/packages/docs/programmable/ai-chat.md new file mode 100644 index 000000000..864480015 --- /dev/null +++ b/packages/docs/programmable/ai-chat.md @@ -0,0 +1,47 @@ +--- +title: AI Chat +description: Built-in AI assistant with 87 tools for creating and modifying designs. +--- + +# AI Chat + +Press ⌘J (Ctrl + J) to open the AI assistant. Describe what you want — it creates shapes, sets styles, manages layout, works with components, and analyzes your design. + +## Setup + +1. Open the AI chat panel (⌘J) +2. Click the settings icon +3. Enter your OpenRouter API key +4. Choose a model (Claude, GPT-4, Gemini, etc.) + +No backend, no subscription — your key talks directly to OpenRouter. + +## What It Can Do + +The assistant has 87 tools across these categories: + +- **Create** — frames, shapes, text, components, pages. Renders JSX for complex layouts. +- **Style** — fills, strokes, effects, opacity, corner radius, blend modes. +- **Layout** — auto-layout, alignment, spacing, sizing. +- **Components** — create components, instances, component sets. Manage overrides. +- **Variables** — create/edit variables, collections, modes. Bind to fills. +- **Query** — find nodes, read properties, list pages, fonts, selection. +- **Analyze** — color palette, typography audit, spacing consistency, cluster detection. +- **Export** — PNG, SVG, JSX with Tailwind classes. +- **Vector** — boolean operations, path manipulation. + +## Example Prompts + +- "Create a card with a title, description, and a blue button" +- "Make all buttons on this page use the same border radius" +- "What fonts are used in this file?" +- "Change the background of the selected frame to a gradient from blue to purple" +- "Export the selected frame as SVG" +- "Find all text nodes with font size less than 12" + +## Tips + +- Select nodes before asking — the assistant knows what's selected. +- Be specific about colors, sizes, and positions for precise results. +- The assistant can modify multiple nodes in one message. +- Use "undo" in the editor if you don't like the result. diff --git a/packages/docs/programmable/cli/analyzing.md b/packages/docs/programmable/cli/analyzing.md new file mode 100644 index 000000000..da8ab307b --- /dev/null +++ b/packages/docs/programmable/cli/analyzing.md @@ -0,0 +1,65 @@ +--- +title: Analyzing Designs +description: Audit colors, typography, spacing, and repeated patterns in .fig files. +--- + +# Analyzing Designs + +The `analyze` commands audit an entire design system from the terminal — find inconsistencies, extract the real palette, spot components waiting to be extracted. + +## Colors + +```sh +open-pencil analyze colors design.fig +``` + +Finds every color in the file, counts usage, and shows a visual histogram: + +``` +#1d1b20 ██████████████████████████████ 17155× +#49454f ██████████████████████████████ 9814× +#ffffff ██████████████████████████████ 8620× +#6750a4 ██████████████████████████████ 3967× +``` + +## Typography + +```sh +open-pencil analyze typography design.fig +``` + +Lists every font family, size, and weight combination with usage counts. Useful for spotting one-off text styles that should be consolidated. + +## Spacing + +```sh +open-pencil analyze spacing design.fig +``` + +Audits gap and padding values across auto-layout frames. Helps identify spacing scale inconsistencies — e.g. a stray `13px` gap among otherwise `8/16/24` values. + +## Clusters + +```sh +open-pencil analyze clusters design.fig +``` + +Finds repeated node patterns that could be extracted into components: + +``` +3771× frame "container" (100% match) + size: 40×40, structure: Frame > [Frame] + +2982× instance "Checkboxes" (100% match) + size: 48×48, structure: Instance > [Frame] +``` + +## JSON Output + +All analyze commands support `--json` for machine-readable output: + +```sh +open-pencil analyze colors design.fig --json +``` + +Pipe into `jq`, feed into CI checks, or use in scripts that enforce design token budgets. diff --git a/packages/docs/programmable/cli/exporting.md b/packages/docs/programmable/cli/exporting.md new file mode 100644 index 000000000..058bb6988 --- /dev/null +++ b/packages/docs/programmable/cli/exporting.md @@ -0,0 +1,59 @@ +--- +title: Exporting +description: Render .fig files to PNG, JPG, WEBP, SVG, or JSX with Tailwind classes. +--- + +# Exporting + +Export designs from the terminal — raster images, vectors, or JSX code. + +## Image Export + +```sh +open-pencil export design.fig # PNG (default) +open-pencil export design.fig -f jpg -s 2 -q 90 # JPG at 2×, quality 90 +open-pencil export design.fig -f webp -s 3 # WEBP at 3× +open-pencil export design.fig -f svg # SVG vector +``` + +Options: + +- `-f` — format: `png`, `jpg`, `webp`, `svg`, `jsx` +- `-s` — scale: `1`–`4` +- `-q` — quality: `0`–`100` (JPG/WEBP only) +- `-o` — output path +- `--page` — page name +- `--node` — specific node ID + +## JSX Export + +Export as JSX with Tailwind utility classes: + +```sh +open-pencil export design.fig -f jsx --style tailwind +``` + +Output: + +```html +
+

Card Title

+

Description text

+
+``` + +Also supports `--style openpencil` for the native JSX format (see [JSX Renderer](../jsx-renderer)). + +## Thumbnails + +```sh +open-pencil export design.fig --thumbnail --width 1920 --height 1080 +``` + +## Live App Mode + +Omit the file to export from the running app: + +```sh +open-pencil export -f png # screenshot the current canvas +``` diff --git a/packages/docs/programmable/cli/inspecting.md b/packages/docs/programmable/cli/inspecting.md new file mode 100644 index 000000000..0cb2e7f5f --- /dev/null +++ b/packages/docs/programmable/cli/inspecting.md @@ -0,0 +1,98 @@ +--- +title: Inspecting Files +description: Browse node trees, search by name or type, and dig into properties from the terminal. +--- + +# Inspecting Files + +The CLI lets you explore `.fig` files without opening the editor. Every command also works on the live app — just omit the file argument. + +::: tip Install +```sh +bun add -g @open-pencil/cli +# or +brew install open-pencil/tap/open-pencil +``` +::: + +## Document Info + +Get a quick overview — page count, total nodes, fonts used, file size: + +```sh +open-pencil info design.fig +``` + +## Node Tree + +Print the full node hierarchy: + +```sh +open-pencil tree design.fig +``` + +``` +[0] [page] "Getting started" (0:46566) + [0] [section] "" (0:46567) + [0] [frame] "Body" (0:46568) + [0] [frame] "Introduction" (0:46569) + [0] [frame] "Introduction Card" (0:46570) + [0] [frame] "Guidance" (0:46571) +``` + +## Find Nodes + +Search by type: + +```sh +open-pencil find design.fig --type TEXT +``` + +Search by name: + +```sh +open-pencil find design.fig --name "Button" +``` + +Both flags can be combined to narrow results further. + +## Node Details + +Inspect all properties of a specific node by its ID: + +```sh +open-pencil node design.fig --id 1:23 +``` + +## Pages + +List all pages in the document: + +```sh +open-pencil pages design.fig +``` + +## Variables + +List design variables and their collections: + +```sh +open-pencil variables design.fig +``` + +## Live App Mode + +When the desktop app is running, omit the file argument — the CLI connects via RPC and operates on the live canvas: + +```sh +open-pencil tree # inspect the live document +open-pencil eval -c "..." # query the editor +``` + +## JSON Output + +All commands support `--json` for machine-readable output — pipe into `jq`, feed to CI scripts, or process with other tools: + +```sh +open-pencil tree design.fig --json | jq '.[] | .name' +``` diff --git a/packages/docs/programmable/cli/scripting.md b/packages/docs/programmable/cli/scripting.md new file mode 100644 index 000000000..8c668bc5f --- /dev/null +++ b/packages/docs/programmable/cli/scripting.md @@ -0,0 +1,70 @@ +--- +title: Scripting +description: Execute JavaScript with the Figma Plugin API — query nodes, batch-modify designs, create frames. +--- + +# Scripting + +`open-pencil eval` gives you the full Figma Plugin API in the terminal. Read nodes, modify properties, create shapes — then write changes back to the file. + +## Basic Usage + +```sh +open-pencil eval design.fig -c "figma.currentPage.children.length" +``` + +The `-c` flag takes JavaScript. The `figma` global works like the Figma Plugin API. + +## Query Nodes + +```sh +open-pencil eval design.fig -c " + figma.currentPage.findAll(n => n.type === 'FRAME' && n.name.includes('Button')) + .map(b => ({ id: b.id, name: b.name, w: b.width, h: b.height })) +" +``` + +## Modify and Save + +```sh +open-pencil eval design.fig -c " + figma.currentPage.children.forEach(n => n.opacity = 0.5) +" -w +``` + +`-w` writes changes back to the input file. Use `-o output.fig` to write to a different file instead. + +## Read from Stdin + +For longer scripts: + +```sh +cat transform.js | open-pencil eval design.fig --stdin -w +``` + +## Live App Mode + +Omit the file to run against the running desktop app: + +```sh +open-pencil eval -c "figma.currentPage.name" +``` + +## Available API + +The `figma` object supports: + +- `figma.currentPage` — the active page +- `figma.root` — the document root +- `figma.createFrame()`, `figma.createRectangle()`, `figma.createEllipse()`, `figma.createText()`, etc. +- `.findAll()`, `.findOne()` — search descendants +- `.appendChild()`, `.insertChild()` — tree manipulation +- All property setters: `.fills`, `.strokes`, `.effects`, `.opacity`, `.cornerRadius`, `.layoutMode`, `.itemSpacing`, etc. + +This is the same API Figma plugins use, so existing knowledge and code snippets transfer directly. + +## JSON Output + +```sh +open-pencil eval design.fig -c "..." --json +``` diff --git a/packages/docs/programmable/collaboration.md b/packages/docs/programmable/collaboration.md new file mode 100644 index 000000000..b7e2b1de1 --- /dev/null +++ b/packages/docs/programmable/collaboration.md @@ -0,0 +1,38 @@ +--- +title: Collaboration +description: Real-time collaborative editing via P2P WebRTC — no server, no account. +--- + +# Collaboration + +Edit designs together in real time. Peers connect directly — no server relays your data, no account required. + +## Sharing a Room + +1. Click the share button in the top-right corner +2. Copy the generated link (`app.openpencil.dev/share/`) +3. Send it to your collaborators + +Anyone with the link can join. The room stays active as long as at least one participant has the page open. + +## What Syncs + +- **Document changes** — every edit (shapes, text, properties, layout) syncs instantly +- **Cursors** — see where each collaborator is pointing, with their name and color +- **Selections** — highlighted selections are visible to everyone + +## Follow Mode + +Click a collaborator's avatar in the top bar to follow their viewport. Your canvas pans and zooms to match their view. Click again to stop following. + +## How It Works + +Peers connect directly via WebRTC — your design data goes straight from browser to browser, never through a central server. The document state uses a CRDT (conflict-free replicated data type), so concurrent edits merge automatically without conflicts. + +The room persists locally — if you refresh the page, you rejoin with the same state. + +## Tips + +- Works in the browser and the desktop app +- Room IDs are cryptographically random — only people with the link can join +- Stale cursors are cleaned up automatically when someone disconnects diff --git a/packages/docs/programmable/index.md b/packages/docs/programmable/index.md new file mode 100644 index 000000000..497182146 --- /dev/null +++ b/packages/docs/programmable/index.md @@ -0,0 +1,51 @@ +--- +layout: doc +title: AI & Automation +description: Every operation in OpenPencil is scriptable — AI chat, CLI, JSX renderer, MCP server, real-time collaboration. +--- + +# AI & Automation + +OpenPencil treats design files as data. Every operation available in the editor — creating shapes, setting fills, managing auto-layout, exporting assets — is also available from the terminal, from AI agents, and from code. No plugins to install, no API keys, no waiting list. + +The editor UI and the automation interfaces use the same engine. If you can do it by clicking, you can do it by scripting. + +## AI Chat + +The built-in assistant has access to 87 tools that cover the full surface of the editor. Describe what you want in natural language — "add a 16px drop shadow to all buttons", "create a card component with dark mode variant", "export every frame on this page at 2×". + +[AI Chat →](./ai-chat) + +## Collaboration + +Real-time multiplayer editing over peer-to-peer WebRTC. No server, no account. Share a room link and edit together with live cursors and follow mode. Document state syncs via CRDT, so edits merge automatically even on flaky connections. + +[Collaboration →](./collaboration) + +## JSX Renderer + +Describe UI as JSX — the same syntax LLMs already know from React. A single call can create an entire component tree with frames, text, auto-layout, fills, and strokes. Compact, declarative, and diffable. + +Going the other direction, export any selection back to JSX with Tailwind classes — useful for handing off to development or feeding designs back into an LLM. + +[JSX Renderer →](./jsx-renderer) + +## CLI + +Inspect, export, and analyze `.fig` files without opening the editor. List pages, search nodes, extract design tokens, render to PNG — all from the terminal with machine-readable JSON output. + +The CLI also connects to the running desktop app via RPC, so you can script the editor while you're using it. + +[Inspecting Files](./cli/inspecting) · [Exporting](./cli/exporting) · [Analyzing Designs](./cli/analyzing) · [Scripting](./cli/scripting) + +## MCP Server + +Connect Claude Code, Cursor, Windsurf, or any MCP-compatible client to OpenPencil. The server exposes 90 tools for reading, creating, and modifying designs — the same tools the built-in AI chat uses. Runs over stdio or HTTP with session support. + +[MCP Server →](./mcp-server) + +## Why Open? + +Figma is a closed platform. Their MCP server is read-only. CDP browser access was killed in version 126. Design files live in a proprietary format on someone else's servers. Plugin development requires a custom runtime with limited APIs. + +OpenPencil is the alternative: open source, MIT licensed, every operation scriptable, data stored locally. Your design files are yours — inspect them, transform them, pipe them into CI, feed them to an LLM. No permission needed. diff --git a/packages/docs/programmable/jsx-renderer.md b/packages/docs/programmable/jsx-renderer.md new file mode 100644 index 000000000..baa1ecf9a --- /dev/null +++ b/packages/docs/programmable/jsx-renderer.md @@ -0,0 +1,116 @@ +--- +title: JSX Renderer +description: Create designs with JSX — the syntax LLMs already know from millions of React components. +--- + +# JSX Renderer + +OpenPencil uses JSX as its design creation language. LLMs have seen millions of React components — describing a layout as `` is natural, no special training needed. Every token matters when an AI agent performs dozens of operations, and JSX is the most compact declarative representation. + +JSX is also diffable. When an AI modifies a design, the change is a JSX diff — readable, reviewable, version-controllable. + +## Creating Designs + +The `render` tool (available in AI chat, MCP, and CLI eval) accepts JSX: + +```jsx + + Card Title + Description text + +``` + +In the MCP server and AI chat, the `render` tool accepts JSX strings directly. In the CLI, use the `export` command to go the other direction — [exporting designs as JSX](./cli/exporting). + +## Elements + +All node types are available as JSX elements: + +| Element | Creates | Aliases | +|---------|---------|---------| +| `` | Frame (container, supports auto-layout) | `` | +| `` | Rectangle | `` | +| `` | Ellipse / circle | | +| `` | Text node (children become text content) | | +| `` | Line | | +| `` | Star | | +| `` | Polygon | | +| `` | Vector path | | +| `` | Group | | +| `
` | Section | | + +## Style Props + +Compact shorthand props inspired by Tailwind's naming. + +### Layout + +| Prop | Description | +|------|-------------| +| `flex` | `"row"` or `"col"` — enables auto-layout | +| `gap` | Space between children | +| `wrap` | Wrap children to next line | +| `rowGap` | Counter-axis spacing when wrapping | +| `justify` | `"start"`, `"end"`, `"center"`, `"between"` | +| `items` | `"start"`, `"end"`, `"center"`, `"stretch"` | +| `p`, `px`, `py`, `pt`, `pr`, `pb`, `pl` | Padding | + +### Size & Position + +| Prop | Description | +|------|-------------| +| `w`, `h` | Width/height — number, `"fill"`, or `"hug"` | +| `minW`, `maxW`, `minH`, `maxH` | Size constraints | +| `x`, `y` | Position | + +### Appearance + +| Prop | Description | +|------|-------------| +| `bg` | Background fill (hex color) | +| `fill` | Alias for `bg` | +| `stroke` | Stroke color | +| `strokeWidth` | Stroke width (default: 1) | +| `rounded` | Corner radius (or `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`) | +| `cornerSmoothing` | iOS-style smooth corners (0–1) | +| `opacity` | 0–1 | +| `shadow` | Drop shadow (e.g. `"0 4 8 #00000040"`) | +| `blur` | Layer blur radius | +| `rotate` | Rotation in degrees | +| `blendMode` | Blend mode | +| `overflow` | `"hidden"` or `"visible"` | + +### Typography + +| Prop | Description | +|------|-------------| +| `size` / `fontSize` | Font size | +| `font` / `fontFamily` | Font family | +| `weight` / `fontWeight` | `"bold"`, `"medium"`, `"normal"`, or number | +| `color` | Text color | +| `textAlign` | `"left"`, `"center"`, `"right"`, `"justified"` | + +## Exporting to JSX + +Convert existing designs back to JSX: + +```sh +open-pencil export design.fig -f jsx # OpenPencil format +open-pencil export design.fig -f jsx --style tailwind # Tailwind classes +``` + +The round-trip works: export a design as JSX, modify the code, render it back. + +## Visual Diffing + +Because designs are representable as JSX, changes become code diffs: + +```diff + +- Old Title ++ New Title + Description + +``` + +This makes design changes reviewable in pull requests, trackable in version control, and auditable in CI. diff --git a/packages/docs/programmable/mcp-server.md b/packages/docs/programmable/mcp-server.md new file mode 100644 index 000000000..e296a6447 --- /dev/null +++ b/packages/docs/programmable/mcp-server.md @@ -0,0 +1,251 @@ +# 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` + +Security defaults (HTTP transport): + +- Binds to `127.0.0.1` by default (`HOST` to override) +- `eval` tool is disabled +- File operations are limited to `OPENPENCIL_MCP_ROOT` (defaults to current working directory) +- CORS is disabled by default; set `OPENPENCIL_MCP_CORS_ORIGIN` to allow one origin +- Optional auth token: `OPENPENCIL_MCP_AUTH_TOKEN` (client sends `Authorization: Bearer ` or `x-mcp-token`) + +Server 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` + +## AI Agent Skill + +Teach your AI coding agent to use OpenPencil tools: + +```sh +npx skills add open-pencil/skills@open-pencil +``` + +Works with Claude Code, Cursor, Windsurf, Codex, and any agent that supports [skills](https://skills.sh). The skill covers the CLI, MCP tools, JSX rendering, eval, and the running app's automation bridge. + +## Tools (90) + +### 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_current_page` | Get the current page name and ID | +| `get_node` | Get detailed properties of a node by ID | +| `find_nodes` | Find nodes by name pattern and/or type | +| `get_components` | List all components in the document | +| `list_pages` | List all pages | +| `list_variables` | List design variables | +| `list_collections` | List variable collections | +| `list_fonts` | List fonts used in the current page | +| `page_bounds` | Get bounding box of all objects on the current page | +| `node_bounds` | Get bounding box of a node | +| `node_ancestors` | Get ancestor chain of a node | +| `node_children` | Get direct children of a node | +| `node_tree` | Get the subtree rooted at a node | +| `node_bindings` | Get variable bindings on a node | + +### Create + +| Tool | Description | +|------|-------------| +| `create_shape` | Create a shape (`FRAME`, `RECTANGLE`, `ELLIPSE`, `TEXT`, `LINE`, `STAR`, `POLYGON`, `SECTION`) | +| `create_vector` | Create a vector node from a path string | +| `create_slice` | Create an export slice | +| `create_page` | Create a new page | +| `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 | +| `node_to_component` | Convert an existing node into a component in-place | + +### 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 | +| `set_rotation` | Set rotation angle in degrees | +| `set_opacity` | Set opacity (0–1) | +| `set_radius` | Set corner radius (uniform or per-corner) | +| `set_minmax` | Set min/max width and height constraints | +| `set_text` | Set text content of a `TEXT` node | +| `set_font` | Set font family and weight | +| `set_font_range` | Set font properties on a character range | +| `set_text_resize` | Set text auto-resize mode (fixed/auto-width/auto-height) | +| `set_visible` | Show or hide a node | +| `set_blend` | Set blend mode | +| `set_locked` | Lock or unlock a node | +| `set_stroke_align` | Set stroke alignment (inside/center/outside) | +| `set_text_properties` | Set text layout: alignment, auto-resize, text case, decoration, truncation | +| `set_layout_child` | Configure auto-layout child: sizing, grow, alignment, absolute positioning | +| `node_move` | Move a node to a new position | +| `node_resize` | Resize a node | +| `node_replace_with` | Replace a node with another node | +| `arrange` | Align or distribute selected nodes | + +### 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 | +| `flatten_nodes` | Flatten nodes into a single vector | +| `boolean_union` | Boolean union of two or more nodes | +| `boolean_subtract` | Boolean subtraction | +| `boolean_intersect` | Boolean intersection | +| `boolean_exclude` | Boolean exclusion | + +### Vector Path + +| Tool | Description | +|------|-------------| +| `path_get` | Get the path data of a vector node | +| `path_set` | Set the path data of a vector node | +| `path_scale` | Scale a vector path | +| `path_flip` | Flip a vector path horizontally or vertically | +| `path_move` | Translate a vector path | + +### Export + +| Tool | Description | +|------|-------------| +| `export_image` | Export nodes as PNG, JPG, or WEBP. Returns base64-encoded image data | +| `export_svg` | Export nodes as SVG markup | + +### Viewport + +| Tool | Description | +|------|-------------| +| `viewport_get` | Get current viewport position and zoom level | +| `viewport_set` | Set viewport position and zoom | +| `viewport_zoom_to_fit` | Zoom viewport to fit specified nodes | + +### Variables + +| Tool | Description | +|------|-------------| +| `get_variable` | Get a variable by ID or name | +| `find_variables` | Find variables by name pattern or type | +| `create_variable` | Create a new variable in a collection | +| `set_variable` | Set a variable value in a mode | +| `delete_variable` | Delete a variable | +| `bind_variable` | Bind a variable to a node property | +| `get_collection` | Get a variable collection by ID or name | +| `create_collection` | Create a new variable collection | +| `delete_collection` | Delete a variable collection | + +### Analyze + +| Tool | Description | +|------|-------------| +| `analyze_colors` | Analyze color palette usage across the document | +| `analyze_typography` | Analyze font/size/weight distribution | +| `analyze_spacing` | Analyze gap and padding values | +| `analyze_clusters` | Detect repeated patterns (potential components) | + +### Diff + +| Tool | Description | +|------|-------------| +| `diff_create` | Create a snapshot of the current document state | +| `diff_show` | Show differences between the current state and a snapshot | + +### 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 | + +Note: `eval` is available over stdio, but disabled in HTTP mode for security. diff --git a/packages/docs/reference/cli.md b/packages/docs/reference/cli.md new file mode 100644 index 000000000..6f83df440 --- /dev/null +++ b/packages/docs/reference/cli.md @@ -0,0 +1,184 @@ +--- +title: CLI Reference +description: Complete reference for all open-pencil commands, options, and flags. +--- + +# CLI Reference + +All commands accept a `.fig` file as a positional argument. When omitted, the CLI connects to the running desktop app via RPC. + +## info + +Show document info — pages, node counts, fonts, file size. + +```sh +open-pencil info [file] [--json] +``` + +| Option | Description | +|--------|-------------| +| `--json` | Output as JSON | + +## tree + +Print the node hierarchy. + +```sh +open-pencil tree [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--page` | Page name (default: first page) | +| `--depth` | Max depth (default: unlimited) | +| `--json` | Output as JSON | + +## find + +Search nodes by name or type. + +```sh +open-pencil find [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--name` | Node name (partial match, case-insensitive) | +| `--type` | Node type: `FRAME`, `TEXT`, `RECTANGLE`, `INSTANCE`, etc. | +| `--page` | Page name (default: all pages) | +| `--limit` | Max results (default: 100) | +| `--json` | Output as JSON | + +## node + +Show detailed properties of a node. + +```sh +open-pencil node [file] --id [--json] +``` + +| Option | Description | +|--------|-------------| +| `--id` | **Required.** Node ID (e.g. `1:23`) | +| `--json` | Output as JSON | + +## pages + +List all pages in the document. + +```sh +open-pencil pages [file] [--json] +``` + +| Option | Description | +|--------|-------------| +| `--json` | Output as JSON | + +## variables + +List design variables and collections. + +```sh +open-pencil variables [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--collection` | Filter by collection name | +| `--type` | Filter by type: `COLOR`, `FLOAT`, `STRING`, `BOOLEAN` | +| `--json` | Output as JSON | + +## export + +Export to PNG, JPG, WEBP, SVG, or JSX. + +```sh +open-pencil export [file] [options] +``` + +| Option | Alias | Description | +|--------|-------|-------------| +| `--format` | `-f` | `png` (default), `jpg`, `webp`, `svg`, `jsx` | +| `--output` | `-o` | Output file path (default: `.`) | +| `--scale` | `-s` | Export scale (default: 1) | +| `--quality` | `-q` | Quality 0–100, JPG/WEBP only (default: 90) | +| `--page` | | Page name (default: first page) | +| `--node` | | Node ID to export (default: all top-level nodes) | +| `--style` | | JSX style: `openpencil` (default), `tailwind` | +| `--thumbnail` | | Export page thumbnail instead of full render | +| `--width` | | Thumbnail width (default: 1920) | +| `--height` | | Thumbnail height (default: 1080) | + +## eval + +Execute JavaScript with the Figma Plugin API. + +```sh +open-pencil eval [file] [options] +``` + +| Option | Alias | Description | +|--------|-------|-------------| +| `--code` | `-c` | JavaScript code to execute | +| `--stdin` | | Read code from stdin | +| `--write` | `-w` | Write changes back to the input file | +| `--output` | `-o` | Write to a different file | +| `--json` | | Output as JSON | +| `--quiet` | `-q` | Suppress output | + +## analyze colors + +Analyze color palette usage across the document. + +```sh +open-pencil analyze colors [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--limit` | Max colors to show (default: 30) | +| `--threshold` | Distance threshold for clustering similar colors, 0–50 (default: 15) | +| `--similar` | Show similar color clusters | +| `--json` | Output as JSON | + +## analyze typography + +Analyze font family, size, and weight distribution. + +```sh +open-pencil analyze typography [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--group-by` | Group by: `family`, `size`, `weight` (default: show all styles) | +| `--limit` | Max styles to show (default: 30) | +| `--json` | Output as JSON | + +## analyze spacing + +Analyze gap and padding values across auto-layout frames. + +```sh +open-pencil analyze spacing [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--grid` | Base grid size to check against (default: 8) | +| `--json` | Output as JSON | + +## analyze clusters + +Find repeated node patterns — potential components. + +```sh +open-pencil analyze clusters [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--limit` | Max clusters to show (default: 20) | +| `--min-size` | Min node size in px (default: 30) | +| `--min-count` | Min instances to form a cluster (default: 2) | +| `--json` | Output as JSON | diff --git a/packages/docs/reference/file-format.md b/packages/docs/reference/file-format.md index b1d880894..ea94b8fb6 100644 --- a/packages/docs/reference/file-format.md +++ b/packages/docs/reference/file-format.md @@ -2,70 +2,71 @@ ## .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 -└─────────────────────────────────┘ -``` +A `.fig` file is a ZIP archive containing a Kiwi-encoded binary message: + +| Offset | Content | +|--------|---------| +| 0 | Magic header `fig-kiwi` (8 bytes) | +| 8 | Version (4 bytes, uint32 LE) | +| 12 | Schema length (4 bytes, uint32 LE) | +| 16 | Compressed Kiwi schema | +| … | Message length (4 bytes, 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 +.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 +SceneGraph → NodeChange[] → Kiwi encode → compress (Zstd/deflate) + → build ZIP (header + schema + message + thumbnail.png) + → write .fig file ``` -Export uses ⌘S (Save) and ⇧⌘S (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). +Export uses ⌘S (Save) and ⇧⌘S (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. ## Kiwi Binary Codec -The codec handles Figma's 194-definition Kiwi schema with NodeChange as the central type (~390 fields). Key components: +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 +| Module | Purpose | +|--------|---------| +| `kiwi-schema` | Kiwi parser (from [evanw/kiwi](https://github.com/nicolo-ribaudo/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. +Figma's schema uses non-contiguous field IDs (e.g. 1, 2, 5, 10 with gaps). The kiwi-schema parser handles 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`. +`.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. ## Supported Formats | Format | Import | Export | |--------|--------|--------| -| .fig (Figma) | ✅ | ✅ | -| .svg | Planned | Planned | -| .png | Planned | Planned | -| .pdf | — | Planned | - -See [Roadmap](/development/roadmap) for planned format support timeline. +| `.fig` (Figma) | ✅ | ✅ | +| `.svg` | Planned | Planned | +| `.png` | Planned | Planned | +| `.pdf` | — | Planned | ## 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 +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. +Encoding happens synchronously in the copy event handler (not async Clipboard API) for browser compatibility. This enables bidirectional clipboard between OpenPencil and Figma. diff --git a/packages/docs/reference/node-types.md b/packages/docs/reference/node-types.md index 961ab3b02..f6024302d 100644 --- a/packages/docs/reference/node-types.md +++ b/packages/docs/reference/node-types.md @@ -8,41 +8,41 @@ The scene graph supports 28 node types from Figma's Kiwi schema. Each node is id | 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) | ✅ | +| `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) +- `COMPONENT_SET` → variant group container (no dedicated Kiwi ID, mapped from `SYMBOL` with variants) - `POLYGON` → Kiwi `REGULAR_POLYGON` (ID 11) ```typescript @@ -81,14 +81,14 @@ Document ## Core Properties -Every node carries these fields (subset of NodeChange): +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 +- `phase` — `CREATED` or `REMOVED` - `parentIndex` — parent GUID + position string for z-ordering ### Transform @@ -103,14 +103,14 @@ Every node carries these fields (subset of NodeChange): - `strokePaints[]` — stroke colors - `effects[]` — shadows, blurs - `opacity` — 0–1 -- `blendMode` — NORMAL, MULTIPLY, SCREEN, etc. +- `blendMode` — `NORMAL`, `MULTIPLY`, `SCREEN`, etc. ### Stroke - `strokeWeight` — stroke thickness -- `strokeAlign` — inside / center / outside -- `strokeCap` — butt / round / square -- `strokeJoin` — miter / bevel / round +- `strokeAlign` — `INSIDE` / `CENTER` / `OUTSIDE` +- `strokeCap` — `NONE` / `ROUND` / `SQUARE` / `ARROW_LINES` / `ARROW_EQUILATERAL` +- `strokeJoin` — `MITER` / `BEVEL` / `ROUND` - `dashPattern[]` — dash/gap lengths ### Corners diff --git a/packages/docs/reference/scene-graph.md b/packages/docs/reference/scene-graph.md index 2c60c9b51..0d445d189 100644 --- a/packages/docs/reference/scene-graph.md +++ b/packages/docs/reference/scene-graph.md @@ -2,7 +2,7 @@ ## In-Memory Representation -Nodes live in a flat `Map` keyed by GUID string. The tree structure is maintained via `parentIndex` references. This gives O(1) lookup by ID and efficient traversal. +Nodes live in a flat `Map` 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 { @@ -31,11 +31,11 @@ interface SceneGraph { ## 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. +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. +`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 @@ -86,11 +86,11 @@ For marquee selection, `getNodesInRect` returns all nodes whose bounds intersect ## 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). +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. +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 diff --git a/packages/docs/ru/development/openspec.md b/packages/docs/ru/development/openspec.md index aff87fafc..2ed87d6af 100644 --- a/packages/docs/ru/development/openspec.md +++ b/packages/docs/ru/development/openspec.md @@ -37,7 +37,7 @@ openspec/ | editor-ui | Панели Vue 3, панель инструментов, палитра цветов | | snap-guides | Привязка к краям/центрам, с учётом поворота | | rulers | Линейки на холсте, подсветка выделения | -| group-ungroup | ⌘G/⇧⌘G, сортировка по позиции | +| group-ungroup | ⌘G / ⇧⌘G, сортировка по позиции | | desktop-app | Tauri v2, строка меню macOS | | testing | Playwright E2E, юнит-тесты bun:test | | scrub-input | Ввод чисел перетаскиванием | diff --git a/packages/docs/ru/development/roadmap.md b/packages/docs/ru/development/roadmap.md index 2102b789a..122fa1c3e 100644 --- a/packages/docs/ru/development/roadmap.md +++ b/packages/docs/ru/development/roadmap.md @@ -4,7 +4,7 @@ ### Фаза 1: Ядро движка ✅ -SceneGraph, отрисовка Skia, базовые фигуры, выделение, масштабирование/панорамирование, отмена/повтор. +`SceneGraph`, отрисовка Skia, базовые фигуры, выделение, масштабирование/панорамирование, отмена/повтор. **Реализовано:** - Граф сцены с хранением в плоском Map и древовидной структурой родитель-потомок @@ -36,13 +36,13 @@ SceneGraph, отрисовка Skia, базовые фигуры, выделен **Реализовано:** - Импорт .fig файлов через бинарный кодек Kiwi - Экспорт .fig файлов с Kiwi-кодированием, Zstd-сжатием, генерацией миниатюры -- Сохранение (⌘S) и Сохранить как (⇧⌘S) с нативными диалогами ОС +- Сохранение (⌘S) и Сохранить как (⇧⌘S) с нативными диалогами ОС - Zstd-сжатие через Tauri Rust-команду (fallback на deflate в браузере) - Вендорённый kiwi-schema с патчами для ESM + разреженных ID полей - Figma-совместимый буфер обмена (двусторонний бинарный Kiwi) - Инструмент «Перо» с моделью векторных сетей - Бинарное кодирование/декодирование vectorNetworkBlob -- Группировка/разгруппировка (⌘G/⇧⌘G) +- Группировка/разгруппировка (⌘G/⇧⌘G) - Десктопное приложение Tauri v2 с нативной строкой меню (macOS/Windows/Linux) - Секции (клавиша S) с плашками заголовков, авто-захватом, адаптивным цветом текста - Многостраничные документы с панелью страниц, отдельной областью просмотра для каждой страницы @@ -57,17 +57,17 @@ SceneGraph, отрисовка Skia, базовые фигуры, выделен Компоненты, экземпляры, переопределения, переменные, коллекции, режимы, экспорт изображений. **Реализовано:** -- Создание компонентов из фрейма/группы или мульти-выделения (⌥⌘K) -- Наборы компонентов из нескольких компонентов (⇧⌘K) с пунктирной фиолетовой рамкой +- Создание компонентов из фрейма/группы или мульти-выделения (⌥⌘K) +- Наборы компонентов из нескольких компонентов (⇧⌘K) с пунктирной фиолетовой рамкой - Создание экземпляров из компонентов с клонированием потомков и маппингом componentId - Синхронизация компонент-экземпляр в реальном времени с сохранением переопределений -- Открепление экземпляра обратно во фрейм (⌥⌘B) +- Открепление экземпляра обратно во фрейм (⌥⌘B) - Переход к основному компоненту (навигация между страницами) - Постоянно видимые фиолетовые метки компонентов/экземпляров с иконкой ромба - Проверка попадания в непрозрачный контейнер (клик выделяет компонент, двойной клик — входит внутрь) - Контекстное меню по правому клику с действиями: буфер обмена, z-порядок, группировка, компонент, видимость, блокировка, перемещение на другую страницу - Управление z-порядком (] на передний план, [ на задний план) -- Переключение видимости (⇧⌘H) и блокировки (⇧⌘L) +- Переключение видимости (⇧⌘H) и блокировки (⇧⌘L) - Перемещение узлов между страницами через контекстное меню - Culling области просмотра, повторное использование Paint, объединение RAF-отрисовок - UI панели эффектов (тень, внутренняя тень, размытие слоя/фона/переднего плана) @@ -77,22 +77,22 @@ SceneGraph, отрисовка Skia, базовые фигуры, выделен - Изменяемые размеры левой/правой панелей через reka-ui Splitter (сохраняемый макет) - Алиас импорта @/, модуль общих типов (src/types.ts, src/global.d.ts) - Чистый код: 0 предупреждений oxlint, 0 ошибок типов tsgo -- Переменные: тип COLOR с коллекциями, режимами, привязками, выбор переменных в FillSection, импорт из .fig +- Переменные: тип `COLOR` с коллекциями, режимами, привязками, выбор переменных в FillSection, импорт из .fig - Диалог переменных: TanStack Table с изменяемой шириной столбцов, столбцы режимов, вкладки коллекций с переименованием, поиск, демо-коллекции (Primitives/Semantic/Spacing), отмена/повтор для всех операций с переменными -- Экспорт изображений: PNG/JPG/WEBP с ExportSection (масштаб, формат, предпросмотр), сочетание ⇧⌘E, контекстное меню +- Экспорт изображений: PNG/JPG/WEBP с ExportSection (масштаб, формат, предпросмотр), сочетание ⇧⌘E, контекстное меню - Нативное редактирование текста на холсте: класс TextEditor в core, phantom textarea, курсор/выделение/границы слов на холсте, мерцание каретки, подсветка выделения - Перечисление системных шрифтов через Rust-крейт font-kit, кеш OnceLock, предзагрузка при старте - Выбор шрифтов: виртуальный скролл (reka-ui ListboxVirtualizer), поисковый фильтр, CSS-предпросмотр шрифта - Извлечение компонента ColorInput, исправление шахматного фона ползунка прозрачности ColorPicker - Идентичность приложения: иконка-карандаш, Cargo crate open_pencil, macOS Dock «OpenPencil» - Заставка во время инициализации WASM -- Стилевые серии в тексте: ⌘B/I/U для выделения, модель StyleRun, ParagraphBuilder pushStyle/pop, roundtrip .fig +- Стилевые серии в тексте: ⌘B/I/U для выделения, модель StyleRun, ParagraphBuilder pushStyle/pop, roundtrip .fig - Кнопки B/I/U/S в секции типографики - Выделение текста двойным кликом (слово), тройным кликом (всё) **Оставшееся (перенесено в Фазу 6):** - Переключение вариантов -- UI для типов переменных: FLOAT, STRING, BOOLEAN +- UI для типов переменных: `FLOAT`, `STRING`, `BOOLEAN` - Тематизация на основе переменных ### Фаза 5: AI-интеграция и инструментарий ✅ @@ -107,7 +107,7 @@ SceneGraph, отрисовка Skia, базовые фигуры, выделен - Обнаружение копипасты jscpd (15.6% → 0.62%), консолидация kiwi-serialize.ts - Тесты roundtrip .fig с LFS-фикстурами (material3.fig 87K узлов, nuxtui.fig 314K узлов) - Исправление O(n²) → O(n) в импорте .fig (37с → 535мс на 87K узлов), оптимизация ByteBuffer -- AI-чат: OpenRouter напрямую (без бэкенда), хранение ключей в Stronghold, 87 инструментов, разделённых по доменным файлам в `tools/`, селектор моделей, ⌘J, потоковый markdown, тесты Playwright с mock-транспортом +- AI-чат: OpenRouter напрямую (без бэкенда), хранение ключей в Stronghold, 87 инструментов, разделённых по доменным файлам в `tools/`, селектор моделей, ⌘J, потоковый markdown, тесты Playwright с mock-транспортом - 49 дополнительных AI/MCP инструментов, портированных из figma-use (87 всего): гранулярные set-инструменты, операции с узлами, CRUD переменных, булевы операции, инструменты векторных путей, управление областью просмотра - MCP-сервер (@open-pencil/mcp): stdio + HTTP (Hono + Streamable HTTP с сессиями), 87 core-инструментов + 3 инструмента управления файлами (90 всего), работает на Bun и Node.js - Унифицированные определения инструментов: определяются один раз в `packages/core/src/tools/` (по доменам), адаптируются для AI-чата (valibot), MCP (zod), CLI (eval) @@ -135,7 +135,7 @@ SceneGraph, отрисовка Skia, базовые фигуры, выделен - Ссылка для совместного доступа по адресу `/share/` с безопасными ID комнат - Отрисовка эффектов: тень, внутренняя тень, разброс тени, размытие слоя, размытие фона, размытие переднего плана - Кеш SkPicture для каждого узла для эффектов (нулевой пересчёт для статических эффектов) -- Мульти-файловые вкладки: ⌘N/⌘T новая вкладка, ⌘W закрыть, ⌘O открыть в новой вкладке +- Мульти-файловые вкладки: ⌘N/⌘T новая вкладка, ⌘W закрыть, ⌘O открыть в новой вкладке - Подписание кода Apple и нотаризация для сборок macOS - Сборки Linux (x64) добавлены в CI - Git LFS перемещён на Cloudflare R2 @@ -146,7 +146,7 @@ SceneGraph, отрисовка Skia, базовые фигуры, выделен - Прототипирование (связи фреймов, переходы, анимации) - Комментарии (закрепление, треды, разрешение) - Поддержка PWA -- Переключение вариантов, UI для FLOAT/STRING/BOOLEAN переменных, тематизация на основе переменных +- Переключение вариантов, UI для `FLOAT`/STRING/BOOLEAN переменных, тематизация на основе переменных - Полный набор тестов совместимости с Figma ## Сроки diff --git a/packages/docs/ru/eval-command.md b/packages/docs/ru/eval-command.md deleted file mode 100644 index a7f82550f..000000000 --- a/packages/docs/ru/eval-command.md +++ /dev/null @@ -1,437 +0,0 @@ -# `open-pencil eval` — Figma-совместимый Plugin API для скриптинга без GUI - -## Обзор - -`bun open-pencil eval --code ''` выполняет JavaScript-код над `.fig`-файлом с глобальным объектом `figma`, совместимым с Figma. Это позволяет автоматизировать пакетные операции, запускать AI-инструменты и тесты — всё без графического интерфейса. - -Объект `figma` максимально точно повторяет API плагинов Figma, поэтому существующие знания и фрагменты кода для плагинов Figma можно использовать напрямую. - -```bash -# Создать фрейм, настроить автораскладку, добавить дочерние элементы -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 } -' - -# Поиск узлов -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 })) -' - -# Чтение из stdin (для многострочных скриптов / пайплайнов) -cat transform.js | bun open-pencil eval design.fig --stdin - -# Сохранить изменения обратно в файл -bun open-pencil eval design.fig --code '...' --write -bun open-pencil eval design.fig --code '...' -o modified.fig -``` - -## Архитектура - -``` -┌──────────────────────────────────────────────────────┐ -│ CLI: `open-pencil eval --code '...'` │ -│ ↓ │ -│ loadDocument(file) → SceneGraph │ -│ ↓ │ -│ FigmaAPI(sceneGraph) → прокси-объект `figma` │ -│ ↓ │ -│ AsyncFunction('figma', wrappedCode)(figmaProxy) │ -│ ↓ │ -│ вывод результата в JSON / agentfmt │ -│ опционально: saveDocument(file) при --write │ -└──────────────────────────────────────────────────────┘ -``` - -### Основные классы - -| Класс | Расположение | Роль | -|-------|--------------|------| -| `FigmaAPI` | `packages/core/src/figma-api.ts` | Прокси-объект, реализующий методы `figma.*` поверх `SceneGraph` | -| `FigmaNode` | `packages/core/src/figma-api.ts` | Прокси-обёртка над `SceneNode` с доступом к свойствам в стиле Figma (`.fills`, `.resize()`, `.appendChild()` и т.д.) | -| Команда `eval` | `packages/cli/src/commands/eval.ts` | CLI-команда, загружающая документ, создающая API и выполняющая код | - -### Почему в `@open-pencil/core`? - -Класс `FigmaAPI` находится в core (а не в CLI), потому что: -- **AI-инструменты используют его** — инструмент `render` в панели чата выполняет JSX через тот же API -- **Тестовые скрипты** — модульные тесты могут использовать API для подготовки фикстур -- **Нет зависимостей от DOM** — работает в headless-режиме в Bun, без браузерных API - -## `FigmaAPI` — поэтапная реализация - -### Фаза 1: Базовый функционал (MVP для команды eval) - -Покрывает ~80% реальных скриптов для плагинов: - -#### Документ и страницы - -| Figma API | Наша реализация | Примечания | -|-----------|-----------------|------------| -| `figma.root` | Геттер → прокси для корневого узла | `.children` возвращает прокси страниц | -| `figma.currentPage` | Геттер/сеттер → первая страница по умолчанию | Можно установить на любой прокси страницы | -| `figma.currentPage.selection` | Чтение/запись → отслеживаемый массив выделения | | -| `figma.getNodeById(id)` | `graph.getNode(id)`, обёрнутый в прокси | Синхронный, как устаревшая версия Figma | - -#### Создание узлов - -| Figma API | Соответствие | -|-----------|--------------| -| `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', ...)` | - -#### Свойства узлов (через прокси `FigmaNode`) - -Чтение и запись на любом прокси-узле. Обращение к свойствам транслируется в поля `SceneNode`: - -```ts -// Геометрия -node.x, node.y // прямое соответствие -node.width, node.height // только чтение, используйте node.resize(w, h) -node.rotation // прямое соответствие -node.resize(w, h) // обновляет width и height -node.resizeWithoutConstraints(w, h) // аналогично (движка ограничений пока нет) - -// Визуальные свойства -node.fills // чтение/запись Fill[] -node.strokes // чтение/запись Stroke[] -node.effects // чтение/запись Effect[] -node.opacity // чтение/запись number -node.visible // чтение/запись boolean -node.locked // чтение/запись boolean -node.blendMode // чтение/запись BlendMode -node.clipsContent // чтение/запись boolean - -// Скругление углов -node.cornerRadius // чтение/запись (number или figma.mixed) -node.topLeftRadius // чтение/запись -node.topRightRadius // чтение/запись -node.bottomLeftRadius // чтение/запись -node.bottomRightRadius // чтение/запись -node.cornerSmoothing // чтение/запись - -// Идентификация -node.id // только чтение -node.name // чтение/запись -node.type // только чтение -node.parent // только чтение → FigmaNode | null -node.removed // только чтение boolean -``` - -#### Операции с деревом - -```ts -node.children // только чтение FigmaNode[] -node.appendChild(child) // перемещает в конец -node.insertChild(index, child) // перемещает на позицию index -node.remove() // graph.deleteNode(id) - -// Обход дерева -node.findAll(callback?) // рекурсивный поиск -node.findOne(callback) // первое совпадение -node.findChild(callback) // только среди прямых потомков -node.findChildren(callback?) // только среди прямых потомков -``` - -#### Автораскладка - -```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' - -// Размеры дочерних элементов -node.layoutPositioning // 'AUTO' | 'ABSOLUTE' -node.layoutGrow // 0 | 1 -node.layoutSizingHorizontal // 'FIXED' | 'HUG' | 'FILL' -node.layoutSizingVertical // 'FIXED' | 'HUG' | 'FILL' -``` - -#### Текст - -```ts -node.characters // чтение/запись (соответствует node.text) -node.fontSize // чтение/запись -node.fontName // чтение/запись { family, style } -node.fontWeight // чтение/запись -node.textAlignHorizontal // чтение/запись -node.textAlignVertical // чтение/запись -node.textAutoResize // чтение/запись -node.letterSpacing // чтение/запись -node.lineHeight // чтение/запись -node.maxLines // чтение/запись -node.textCase // чтение/запись -node.textDecoration // чтение/запись -``` - -#### Параметры обводки - -```ts -node.strokeWeight // чтение/запись (соответствует strokes[0].weight) -node.strokeAlign // чтение/запись (соответствует strokes[0].align) -node.dashPattern // чтение/запись -``` - -#### Прочее - -```ts -figma.mixed // Symbol-маркер для смешанных значений -figma.group(nodes, parent) // создаёт GROUP с указанными дочерними элементами -figma.ungroup(node) // разгруппировывает, перемещает потомков к родителю -figma.flatten(nodes) // ПОКА НЕ РЕАЛИЗОВАНО — возвращает первый узел -``` - -#### Экспорт - -```ts -node.exportAsync(settings?) // работает только при загруженном CanvasKit - // settings: { format: 'PNG'|'JPG'|'SVG', constraint? } -``` - -### Фаза 2: Компоненты и экземпляры - -| API | Соответствие | -|-----|--------------| -| `figma.createComponent()` | `graph.createNode('COMPONENT', ...)` | -| `figma.createComponentFromNode(node)` | Преобразование существующего фрейма в компонент | -| `figma.combineAsVariants(components, parent)` | Создание COMPONENT_SET | -| Узел: `node.createInstance()` | `graph.createInstance(componentId, parentId)` | -| Узел: `node.detachInstance()` | `graph.detachInstance(id)` | -| `figma.getNodeById(id).mainComponent` | `graph.getMainComponent(id)` | - -### Фаза 3: Переменные - -| API | Соответствие | -|-----|--------------| -| `figma.variables.getLocalVariables(type?)` | `graph.variables` с фильтрацией | -| `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` | Геттер из SceneNode | - -### Фаза 4: Стили и расширенные возможности - -| API | Примечания | -|-----|------------| -| `figma.createPaintStyle()` | Требует хранилища стилей в SceneGraph | -| `figma.createTextStyle()` | Требует хранилища стилей в SceneGraph | -| `figma.createEffectStyle()` | Требует хранилища стилей в SceneGraph | -| `figma.loadFontAsync(fontName)` | No-op (у нас нет ограничений на загрузку шрифтов) | -| `figma.listAvailableFontsAsync()` | Возвращает системные шрифты, если доступны | -| Булевы операции (`union`, `subtract`, `intersect`, `exclude`) | Требует движка булевых операций над путями | -| `figma.createNodeFromJSXAsync(jsx)` | Портирование JSX-рендерера из figma-use | - -## Устройство прокси `FigmaNode` - -Прокси оборачивает `SceneNode` и транслирует имена свойств Figma во внутренние имена. Основные соответствия: - -```ts -const PROPERTY_MAP: Record = { - // Имя Figma → поле SceneNode (только при различиях) - 'characters': 'text', - 'strokeWeight': → вычисляется из strokes[0].weight, - 'strokeAlign': → вычисляется из strokes[0].align, - 'fontName': → вычисляется из { family: fontFamily, style: ... }, - 'primaryAxisAlignItems': 'primaryAxisAlign', - 'counterAxisAlignItems': 'counterAxisAlign', - 'primaryAxisSizingMode': 'primaryAxisSizing', // маппинг значений: 'AUTO' → 'HUG', 'FIXED' → 'FIXED' - 'counterAxisSizingMode': 'counterAxisSizing', - 'layoutSizingHorizontal': → вычисляется из primaryAxisSizing / counterAxisSizing в зависимости от layoutMode - 'layoutSizingVertical': → вычисляется -} -``` - -Методы прокси: - -```ts -class FigmaNode { - // Прокси создаётся через: new Proxy(target, handler) - // handler.get перехватывает чтение свойств, handler.set — запись - - 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 - - // Компоненты (Фаза 2) - createInstance(): FigmaNode - detachInstance(): void - get mainComponent(): FigmaNode | null -} -``` - -## CLI-команда - -``` -bun open-pencil eval [options] - -Аргументы: - file .fig-файл для обработки - -Опции: - --code, -c JavaScript-код для выполнения (имеет доступ к глобальному объекту `figma`) - --stdin Читать код из stdin вместо --code - --write, -w Записать изменения обратно в исходный файл - -o, --output Записать в другой файл - --json Вывести результат в формате JSON (по умолчанию для не-TTY) - --quiet, -q Подавить вывод, только записать файл -``` - -### Модель выполнения - -1. Загрузка `.fig` → `SceneGraph` -2. Создание `FigmaAPI(graph)` → прокси `figma` -3. Обёртка пользовательского кода в асинхронную функцию: `return (async () => { <код> })()` -4. Выполнение с `figma` в качестве единственного аргумента -5. Вывод возвращённого значения (JSON или agentfmt) -6. Если указан `--write` или `-o`: сериализация `SceneGraph` обратно в `.fig` - -### Форматирование возвращаемого значения - -- `undefined` / `void` → без вывода -- Примитивы → выводятся напрямую -- Объекты/массивы → `JSON.stringify(result, null, 2)` или таблицы agentfmt -- `FigmaNode` → сериализуется как `{ id, type, name, x, y, width, height, fills, ... }` -- Массивы `FigmaNode` → сериализуются как список - -## Общий код с AI-инструментами - -Класс `FigmaAPI` — это **та же поверхность API**, которую используют AI-инструменты. Сейчас `src/ai/tools.ts` вызывает `store.createShape()`, `store.updateNodeWithUndo()` и т.д. — их следует рефакторить для работы через `FigmaAPI`: - -```ts -// До (текущие AI-инструменты) -execute: async ({ type, x, y, width, height }) => { - const id = store.createShape(type, x, y, width, height) - return { id } -} - -// После (с использованием 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 } -} -``` - -Это гарантирует идентичное поведение CLI-скриптов и AI-инструментов. - -## Структура файлов - -``` -packages/core/src/ - figma-api.ts # Класс FigmaAPI + прокси FigmaNode (Фазы 1–4) - figma-api.test.ts # Модульные тесты на headless SceneGraph - -packages/cli/src/commands/ - eval.ts # CLI-команда - -packages/cli/src/commands/eval.test.ts # Интеграционные тесты -``` - -## План тестирования - -### Модульные тесты (`packages/core/src/figma-api.test.ts`) - -1. **Создание узлов** — каждый `createX()` создаёт узел правильного типа, добавленный на текущую страницу -2. **Доступ к свойствам** — `.fills`, `.x`, `.width`, `.name`, `.characters` корректно читаются и записываются -3. **Изменение размера** — `.resize(w, h)` обновляет width/height -4. **Операции с деревом** — `.appendChild()`, `.insertChild()`, `.remove()`, `.parent`, `.children` -5. **Обход дерева** — `.findAll()`, `.findOne()`, `.findChild()`, `.findChildren()` с колбэками -6. **Автораскладка** — `.layoutMode`, `.itemSpacing`, `.paddingTop` и т.д. -7. **Текст** — `.characters` соответствует `.text`, `.fontName` соответствует `{ family, style }` -8. **Смешанные значения** — `.cornerRadius` возвращает `figma.mixed`, когда углы различаются -9. **Выделение** — `figma.currentPage.selection` чтение/запись -10. **Переключение страниц** — `figma.currentPage = page2` работает -11. **Группировка/разгруппировка** — `figma.group()` создаёт группу, `figma.ungroup()` расформировывает её -12. **Клонирование** — создание узлов порождает независимые копии - -### Интеграционные тесты CLI (`packages/cli/src/commands/eval.test.ts`) - -1. **Базовый eval** — `eval test.fig --code 'return figma.currentPage.name'` → имя страницы -2. **Создание + чтение** — создать фрейм, вернуть его свойства -3. **Поиск узлов** — `findAll` возвращает правильные узлы -4. **Сохранение** — `--write` сохраняет изменения, при повторной загрузке они видны -5. **Stdin** — `echo 'return 42' | bun open-pencil eval test.fig --stdin` → `42` -6. **JSON-вывод** — `--json` возвращает валидный JSON -7. **Обработка ошибок** — синтаксические и ошибки времени выполнения корректно выводятся - -## Порядок реализации - -1. **Прокси `FigmaNode`** — маппинг свойств, `.resize()`, `.remove()`, методы работы с деревом -2. **Класс `FigmaAPI`** — `createFrame/Rectangle/...`, `.root`, `.currentPage`, `.getNodeById()`, `.mixed`, `.group()` -3. **CLI-команда `eval`** — разбор аргументов, обёртка кода, форматирование вывода -4. **Модульные тесты** — все 12 групп тестов выше -5. **Интеграционные тесты CLI** — все 7 групп тестов выше -6. **Интеграция с AI-инструментами** — рефакторинг `src/ai/tools.ts` для использования `FigmaAPI` где возможно -7. **Фаза 2** — компоненты и экземпляры -8. **Фаза 3** — переменные -9. **Фаза 4** — стили, булевы операции, JSX-рендерер - -## Справочник соответствий свойств - -| Свойство Figma | Поле SceneNode | Тип | Примечания | -|----------------|----------------|-----|------------| -| `characters` | `text` | `string` | | -| `fontName` | `fontFamily` + `fontWeight` + `italic` | `{ family, style }` | Вычисляется: `style` = "Bold Italic" и т.д. | -| `strokeWeight` | `strokes[0].weight` | `number` | Вычисляется | -| `strokeAlign` | `strokes[0].align` | `string` | Вычисляется | -| `primaryAxisAlignItems` | `primaryAxisAlign` | `string` | | -| `counterAxisAlignItems` | `counterAxisAlign` | `string` | | -| `layoutSizingHorizontal` | `primaryAxisSizing` или `counterAxisSizing` | `string` | Зависит от `layoutMode` | -| `layoutSizingVertical` | (противоположное horizontal) | `string` | | -| `absoluteTransform` | вычисляется из `x`, `y`, `rotation` | `Transform` | Только чтение | -| `absoluteBoundingBox` | `getAbsoluteBounds(id)` | `Rect` | Только чтение | -| Все остальные | Совпадающее имя | Тот же тип | Прямая передача | - -## Открытые вопросы - -1. **Загрузка шрифтов**: `figma.loadFontAsync()` — должно ли быть no-op (у нас нет ограничений на шрифты) или нужно отслеживать загруженные шрифты? - → **Решение: No-op, возвращающий resolved Promise.** Мы не блокируем редактирование текста загрузкой шрифтов. - -2. **Экспорт в headless-режиме**: `node.exportAsync()` требует CanvasKit. Должен ли eval загружать CanvasKit? - → **Решение: Опционально.** Если CanvasKit доступен (через флаг `--with-canvaskit` или переменную окружения), экспорт включается. Иначе выбрасывается ошибка "Export requires CanvasKit". - -3. **Символ `figma.mixed`**: Использовать настоящий символ Figma или собственный? - → **Решение: Собственный `Symbol('mixed')`.** Доступен как `figma.mixed`. - -4. **Отмена действий**: `figma.commitUndo()` / `figma.triggerUndo()` — актуально ли в headless-режиме? - → **Решение: No-op в CLI.** Отмена имеет значение только в интерактивном редакторе. AI-инструменты могут добавить поддержку отмены отдельно через EditorStore. - -5. **Формат записи**: Должен ли `--write` создавать `.fig` (бинарный Kiwi) или также поддерживать `.json`? - → **Решение: Только `.fig` на данный момент.** Экспорт в JSON — отдельная функциональность. diff --git a/packages/docs/ru/guide/architecture.md b/packages/docs/ru/guide/architecture.md index 6b676ee53..ade455cd4 100644 --- a/packages/docs/ru/guide/architecture.md +++ b/packages/docs/ru/guide/architecture.md @@ -2,7 +2,7 @@ ## Обзор системы -```mermaid +`mermaid graph TB subgraph Tauri["Tauri v2 Shell"] subgraph Editor["Editor (Web)"] @@ -22,7 +22,7 @@ graph TB MCP["MCP Server (90 tools, stdio+HTTP)"] Collab["P2P Collab (Trystero + Yjs)"] end -``` +` ## Макет редактора @@ -62,7 +62,7 @@ Yoga от Meta обеспечивает вычисление макета CSS fl ### Формат файлов (Kiwi Binary) -Использует бинарный кодек Kiwi от Figma с 194 определениями message/enum/struct. Импорт: разбор заголовка → декомпрессия Zstd → декодирование Kiwi → NodeChange[] → граф сцены. Экспорт выполняет обратный процесс с генерацией миниатюры. +Использует бинарный кодек Kiwi от Figma с 194 определениями message/enum/struct. Импорт: разбор заголовка → декомпрессия Zstd → декодирование Kiwi → `NodeChange`[] → граф сцены. Экспорт выполняет обратный процесс с генерацией миниатюры. См. [справочник формата файлов](/reference/file-format) для подробностей. @@ -108,7 +108,7 @@ Headless CLI уже поддерживает `analyze colors/typography/spacing/ ### Макет CSS Grid -Yoga WASM пока поддерживает только flexbox. CSS Grid находится в разработке в [facebook/yoga#1893](https://github.com/facebook/yoga/pull/1893). OpenPencil адаптирует его после выхода релиза Yoga. +CSS Grid поддерживается через [форк Yoga](https://github.com/open-pencil/yoga/tree/grid). Выберите фрейм, нажмите на иконку сетки для переключения с flex на grid. Настройте колонки и строки (fr, фиксированные px, auto), зазоры между ними и отступы с каждой стороны. ### Подпись кода для Windows diff --git a/packages/docs/ru/guide/comparison.md b/packages/docs/ru/guide/comparison.md index 71b7cc733..11c6eb533 100644 --- a/packages/docs/ru/guide/comparison.md +++ b/packages/docs/ru/guide/comparison.md @@ -272,7 +272,7 @@ class UndoManager { ## 11. Скриптинг и расширяемость -OpenPencil поставляется с [командой `eval`](/eval-command), предоставляющей Figma-совместимый Plugin API для headless-скриптинга — пакетные операции, автоматизированное тестирование и ИИ-модификации работают без GUI. Кроме того, **90 ИИ-инструментов** доступны через встроенный чат, MCP-сервер (stdio + HTTP) и CLI — охватывающие чтение, создание, модификацию, структуру, переменные, векторные пути, анализ (цвета/типографика/отступы/кластеры), сравнение, булевые операции и упорядочивание. Penpot имеет систему плагинов с изолированным выполнением, но без headless-скриптинга или интеграции MCP. +OpenPencil поставляется с [командой `eval`](/programmable/cli/scripting), предоставляющей Figma-совместимый Plugin API для headless-скриптинга — пакетные операции, автоматизированное тестирование и ИИ-модификации работают без GUI. Кроме того, **90 ИИ-инструментов** доступны через встроенный чат, MCP-сервер (stdio + HTTP) и CLI — охватывающие чтение, создание, модификацию, структуру, переменные, векторные пути, анализ (цвета/типографика/отступы/кластеры), сравнение, булевые операции и упорядочивание. Penpot имеет систему плагинов с изолированным выполнением, но без headless-скриптинга или интеграции MCP. ## Итоги diff --git a/packages/docs/ru/guide/features.md b/packages/docs/ru/guide/features.md index df7fa7484..2bb3cda3c 100644 --- a/packages/docs/ru/guide/features.md +++ b/packages/docs/ru/guide/features.md @@ -87,7 +87,7 @@ bun add -g @open-pencil/mcp } ``` -См. [справочник инструментов MCP](/reference/mcp-tools) для полного списка. +См. [справочник инструментов MCP](/programmable/mcp-server) для полного списка. ## CLI diff --git a/packages/docs/ru/guide/figma-comparison.md b/packages/docs/ru/guide/figma-comparison.md index c5b2147c3..401799b47 100644 --- a/packages/docs/ru/guide/figma-comparison.md +++ b/packages/docs/ru/guide/figma-comparison.md @@ -16,7 +16,7 @@ | Панель слоёв (левая боковая) | ✅ | Древовидное представление со сворачиванием, перетаскиванием, переключением видимости; изменяемая ширина | | Панель страниц | ✅ | Добавление, удаление, переименование страниц; состояние области видимости для каждой страницы | | Панель свойств (правая боковая) | ✅ | Секции: Внешний вид, Заливка, Обводка, Эффекты, Типографика, Макет, Позиция; изменяемая ширина | -| Масштабирование и панорамирование | ✅ | Ctrl+scroll, pinch, ⌘+/⌘−/⌘0, space+drag, средняя кнопка мыши, инструмент «Рука» (H) | +| Масштабирование и панорамирование | ✅ | Ctrl + scroll, pinch, ⌘+ / ⌘− / ⌘0, space+drag, средняя кнопка мыши, инструмент «Рука» (H) | | Линейки канваса | ✅ | Верхняя/левая линейки с полосами выделения и координатными метками | | Цвет фона канваса | ✅ | Настройка фона для каждой страницы через панель свойств | | Направляющие канваса | 🔲 | Figma поддерживает перетаскиваемые направляющие с линеек | @@ -36,7 +36,7 @@ |---------|--------|-------| | Инструменты фигур (Прямоугольник, Эллипс, Линия, Многоугольник, Звезда) | ✅ | Все базовые типы; настраиваемое количество сторон многоугольника и внутренний радиус звезды | | Фреймы | ✅ | Обрезка содержимого, независимая система координат | -| Группы | ✅ | ⌘G для группировки, ⇧⌘G для разгруппировки | +| Группы | ✅ | ⌘G для группировки, ⇧⌘G для разгруппировки | | Секции | ✅ | Заголовки, автоматическое включение перекрывающих узлов, адаптивный текст по яркости | | Инструмент дуги (дуги, полукруги, кольца) | ✅ | arcData с начальным/конечным углом и внутренним радиусом | | Инструмент «Карандаш» (рисование от руки) | 🔲 | Инструмент свободного рисования Figma | @@ -46,9 +46,9 @@ | Выравнивание и позиция | ✅ | Позиция, поворот, размеры в панели свойств | | Копирование и вставка объектов | ✅ | Стандартный буфер обмена + бинарный формат Figma Kiwi; Копировать как текст/SVG/PNG/JSX | | Пропорциональное масштабирование | 🟡 | Shift-resize сохраняет пропорции; нет отдельного инструмента Scale (K) | -| Блокировка/разблокировка слоёв | ✅ | ⇧⌘L переключает блокировку; заблокированные узлы нельзя выделить/переместить с канваса | -| Переключение видимости слоя | ✅ | Иконка глаза в панели слоёв + горячая клавиша ⇧⌘H | -| Переименование слоёв | ✅ | Двойной клик для переименования в панели слоёв; Enter/Escape/blur для подтверждения | +| Блокировка/разблокировка слоёв | ✅ | ⇧⌘L переключает блокировку; заблокированные узлы нельзя выделить/переместить с канваса | +| Переключение видимости слоя | ✅ | Иконка глаза в панели слоёв + горячая клавиша ⇧⌘H | +| Переименование слоёв | ✅ | Двойной клик для переименования в панели слоёв; Enter/Escape/blur для подтверждения | | На передний/задний план | ✅ | Горячие клавиши ] и [; также в контекстном меню | | Переместить на страницу | ✅ | Перемещение выделенных узлов между страницами через контекстное меню | | Ограничения (адаптивное изменение размера) | 🔲 | Привязка краёв/центра при изменении размера родителя | @@ -79,13 +79,13 @@ | Функция | Статус | Примечания | |---------|--------|-------| -| Текстовый инструмент и редактирование | ✅ | Нативное редактирование на канвасе, phantom textarea, курсор/выделение/выделение слова, перетаскивание для выделения, двойной/тройной клик, стили (⌘B/I/U, кнопка S) | +| Текстовый инструмент и редактирование | ✅ | Нативное редактирование на канвасе, phantom textarea, курсор/выделение/выделение слова, перетаскивание для выделения, двойной/тройной клик, стили (⌘B / I / U, кнопка S) | | Рендеринг текста (Paragraph API) | ✅ | CanvasKit Paragraph для формирования, переноса строк, метрик | | Загрузка шрифтов (системные) | ✅ | Inter по умолчанию, font-kit в Tauri с кешем OnceLock + предзагрузка, queryLocalFonts в браузере | | Семейство и начертание шрифта | ✅ | FontPicker с виртуальной прокруткой, поиском, CSS-превью; выбор начертания в панели свойств | | Размер шрифта и межстрочный интервал | ✅ | Редактируемые в секции типографики | | Выравнивание текста | 🟡 | Базовое выравнивание; Figma имеет вертикальное выравнивание и режимы auto-width/height | -| Стили текста | 🟡 | Посимвольное жирный/курсив/подчёркивание/зачёркивание (⌘B/I/U, кнопка S); нет переиспользуемых именованных пресетов | +| Стили текста | 🟡 | Посимвольное жирный/курсив/подчёркивание/зачёркивание (⌘B / I / U, кнопка S); нет переиспользуемых именованных пресетов | | Режимы размера текста (auto, fixed, hug) | 🔲 | Режимы auto-width, auto-height, fixed-size Figma | | Маркированные и нумерованные списки | 🔲 | Форматирование списков в тексте | | Ссылки в тексте | 🔲 | Гиперссылки в текстовом содержимом | @@ -126,7 +126,7 @@ | Размытие фона | ✅ | Размытие содержимого за слоем | | Размытие переднего плана | ✅ | Размытие на переднем плане | | Толщина обводки | ✅ | Настраиваемая в панели свойств | -| Наконечник обводки (круглый, квадратный, стрелка) | ✅ | NONE, ROUND, SQUARE, ARROW_LINES, ARROW_EQUILATERAL | +| Наконечник обводки (круглый, квадратный, стрелка) | ✅ | `NONE`, `ROUND`, `SQUARE`, `ARROW_LINES`, `ARROW_EQUILATERAL` | | Соединение обводки (miter, bevel, round) | ✅ | Все три типа соединений | | Штриховые паттерны | ✅ | Паттерн dash-on/dash-off | | Выравнивание обводки | ✅ | Inside/Center/Outside с clip-рендерингом, соответствующим поведению Figma | @@ -140,14 +140,14 @@ | Функция | Статус | Примечания | |---------|--------|-------| | Горизонтальный и вертикальный поток | ✅ | Движок Yoga WASM flexbox | -| Переключение авто-макета (⇧A) | ✅ | Включение на фрейме или оборачивание выделения | +| Переключение авто-макета (⇧A) | ✅ | Включение на фрейме или оборачивание выделения | | Отступ (расстояние между дочерними) | ✅ | Настраиваемый в панели свойств | | Паддинг (единый и по сторонам) | ✅ | Все четыре стороны независимо | | Выравнивание содержимого (justify) | ✅ | Start, center, end, space-between | | Выравнивание элементов (align) | ✅ | Start, center, end, stretch | | Размеры дочерних (fixed, fill, hug) | ✅ | Режимы размера для каждого элемента | | Перенос (wrap) | ✅ | Flex wrap для многострочного макета | -| Grid-поток авто-макета | 🔲 | Grid-макет Figma (строки × столбцы) | +| Grid-поток авто-макета | ✅ | CSS Grid через форк Yoga — настройка колонок/строк, зазоры, объединение ячеек | | Комбинированные потоки (вложенные) | ✅ | Вложенные авто-макеты с разными направлениями | | Перетаскивание для переупорядочивания в авто-макете | ✅ | Визуальный индикатор вставки | | Min/max ширина и высота | 🔲 | Figma поддерживает min/max ограничения для дочерних авто-макета | @@ -156,17 +156,17 @@ | Функция | Статус | Примечания | |---------|--------|-------| -| Создание компонентов | 🟡 | ⌥⌘K создаёт из фрейма/группы или оборачивает выделение; нет UI свойств компонентов | -| Наборы компонентов | 🟡 | ⇧⌘K объединяет компоненты; пунктирная фиолетовая рамка; нет редактирования свойств вариантов | +| Создание компонентов | 🟡 | ⌥⌘K создаёт из фрейма/группы или оборачивает выделение; нет UI свойств компонентов | +| Наборы компонентов | 🟡 | ⇧⌘K объединяет компоненты; пунктирная фиолетовая рамка; нет редактирования свойств вариантов | | Экземпляры компонентов | 🟡 | Создание экземпляра через контекстное меню с клонированием и сопоставлением componentId; живая синхронизация; нет UI редактирования переопределений | | Варианты | 🔲 | Переключение вариантов и выбор по свойствам | | Свойства компонентов | 🔲 | Boolean, text, instance swap свойства | | Распространение переопределений | ✅ | Изменения главного компонента распространяются на все экземпляры; переопределения сохраняются | -| Переменные (color, number, string, boolean) | 🟡 | COLOR полный UI (диалог, TanStack Table, инлайн-редактирование, отмена/повтор, демо-коллекции); FLOAT/STRING/BOOLEAN определены, но без UI редактирования | +| Переменные (color, number, string, boolean) | 🟡 | `COLOR` полный UI (диалог, TanStack Table, инлайн-редактирование, отмена/повтор, демо-коллекции); `FLOAT`/STRING/BOOLEAN определены, но без UI редактирования | | Коллекции и режимы переменных | 🟡 | Коллекции, режимы, переключение activeMode работают; нет UI тем на переменных | | Стили (цвет, текст, эффект, макет) | 🔲 | Переиспользуемые именованные пресеты стилей | | Библиотеки (публикация, обмен, обновление) | 🔲 | Общие библиотеки компонентов/стилей | -| Отсоединение экземпляра | ✅ | ⌥⌘B преобразует экземпляр обратно во фрейм | +| Отсоединение экземпляра | ✅ | ⌥⌘B преобразует экземпляр обратно во фрейм | | Переход к главному компоненту | ✅ | Навигация к исходному компоненту, в том числе на другую страницу | ## Прототипирование @@ -189,9 +189,9 @@ | Функция | Статус | Примечания | |---------|--------|-------| -| Импорт файлов .fig | ✅ | Полный Kiwi-кодек: 194 определения, ~390 полей на NodeChange | -| Экспорт файлов .fig | ✅ | Кодирование Kiwi + сжатие Zstd + генерация миниатюры; COMPONENT/COMPONENT_SET маппятся в SYMBOL для round-trip | -| Сохранить / Сохранить как | ✅ | ⌘S / ⇧⌘S; нативные диалоги (Tauri), File System Access API (Chrome/Edge), скачивание (Safari) | +| Импорт файлов .fig | ✅ | Полный Kiwi-кодек: 194 определения, ~390 полей на `NodeChange` | +| Экспорт файлов .fig | ✅ | Кодирование Kiwi + сжатие Zstd + генерация миниатюры; `COMPONENT`/COMPONENT_SET маппятся в `SYMBOL` для round-trip | +| Сохранить / Сохранить как | ✅ | ⌘S / ⇧⌘S; нативные диалоги (Tauri), File System Access API (Chrome/Edge), скачивание (Safari) | | Буфер обмена Figma (вставка) | ✅ | Декодирование бинарного Kiwi из буфера обмена Figma | | Буфер обмена Figma (копирование) | ✅ | Кодирование бинарного Kiwi, читаемого Figma | | Импорт файлов Sketch | 🔲 | Парсинг файлов .sketch | diff --git a/packages/docs/ru/guide/tech-stack.md b/packages/docs/ru/guide/tech-stack.md index 38bc5a06a..941bd144c 100644 --- a/packages/docs/ru/guide/tech-stack.md +++ b/packages/docs/ru/guide/tech-stack.md @@ -60,4 +60,4 @@ Yoga поддерживается Meta, проверен на миллиарда | Технология | Назначение | Этап | |-----------|---------|-------| -| CSS Grid в Yoga | Макет на основе сетки | Зависит от апстрима (facebook/yoga#1893) | +| CSS Grid в Yoga | Макет на основе сетки | ✅ Поддерживается через [форк Yoga](https://github.com/open-pencil/yoga/tree/grid) | diff --git a/packages/docs/ru/programmable/ai-chat.md b/packages/docs/ru/programmable/ai-chat.md new file mode 100644 index 000000000..026481385 --- /dev/null +++ b/packages/docs/ru/programmable/ai-chat.md @@ -0,0 +1,47 @@ +--- +title: ИИ-чат +description: Встроенный ИИ-ассистент с 87 инструментами для создания и модификации дизайна. +--- + +# ИИ-чат + +Нажмите ⌘J (Ctrl + J), чтобы открыть ИИ-ассистент. Опишите, что вам нужно — он создаёт фигуры, настраивает стили, управляет лейаутом, работает с компонентами и анализирует ваш дизайн. + +## Настройка + +1. Откройте панель ИИ-чата (⌘J) +2. Нажмите значок настроек +3. Введите ваш API-ключ OpenRouter +4. Выберите модель (Claude, GPT-4, Gemini и др.) + +Без бэкенда, без подписки — ваш ключ обращается напрямую к OpenRouter. + +## Возможности + +Ассистент имеет 87 инструментов в следующих категориях: + +- **Создание** — фреймы, фигуры, текст, компоненты, страницы. Рендер JSX для сложных макетов. +- **Стилизация** — заливки, обводки, эффекты, прозрачность, скругление углов, режимы наложения. +- **Лейаут** — автолейаут, выравнивание, отступы, размеры. +- **Компоненты** — создание компонентов, экземпляров, наборов компонентов. Управление переопределениями. +- **Переменные** — создание и редактирование переменных, коллекций, режимов. Привязка к заливкам. +- **Запросы** — поиск узлов, чтение свойств, список страниц, шрифтов, выделение. +- **Анализ** — цветовая палитра, аудит типографики, проверка консистентности отступов, обнаружение кластеров. +- **Экспорт** — PNG, SVG, JSX с классами Tailwind. +- **Вектор** — булевы операции, работа с контурами. + +## Примеры запросов + +- «Создай карточку с заголовком, описанием и синей кнопкой» +- «Сделай одинаковое скругление углов для всех кнопок на этой странице» +- «Какие шрифты используются в этом файле?» +- «Измени фон выделенного фрейма на градиент от синего к фиолетовому» +- «Экспортируй выделенный фрейм как SVG» +- «Найди все текстовые узлы с размером шрифта меньше 12» + +## Советы + +- Выделите узлы перед запросом — ассистент знает, что выделено. +- Указывайте конкретные цвета, размеры и позиции для точных результатов. +- Ассистент может модифицировать несколько узлов в одном сообщении. +- Используйте «Отменить» в редакторе, если результат вам не подходит. diff --git a/packages/docs/ru/programmable/cli/analyzing.md b/packages/docs/ru/programmable/cli/analyzing.md new file mode 100644 index 000000000..7659055ff --- /dev/null +++ b/packages/docs/ru/programmable/cli/analyzing.md @@ -0,0 +1,65 @@ +--- +title: Анализ дизайна +description: Аудит цветов, типографики, отступов и повторяющихся паттернов в .fig-файлах. +--- + +# Анализ дизайна + +Команды `analyze` проводят аудит всей дизайн-системы из терминала — находят несоответствия, извлекают реальную палитру, обнаруживают компоненты, которые стоит выделить. + +## Цвета + +```sh +open-pencil analyze colors design.fig +``` + +Находит каждый цвет в файле, подсчитывает использование и показывает визуальную гистограмму: + +``` +#1d1b20 ██████████████████████████████ 17155× +#49454f ██████████████████████████████ 9814× +#ffffff ██████████████████████████████ 8620× +#6750a4 ██████████████████████████████ 3967× +``` + +## Типографика + +```sh +open-pencil analyze typography design.fig +``` + +Выводит список всех комбинаций шрифтов, размеров и начертаний с количеством использований. Помогает обнаружить единичные стили текста, которые следует унифицировать. + +## Отступы + +```sh +open-pencil analyze spacing design.fig +``` + +Анализирует значения gap и padding во фреймах с автолейаутом. Помогает выявить несоответствия в шкале отступов — например, случайный `13px` среди стандартных значений `8/16/24`. + +## Кластеры + +```sh +open-pencil analyze clusters design.fig +``` + +Находит повторяющиеся паттерны узлов, которые можно выделить в компоненты: + +``` +3771× frame "container" (100% match) + size: 40×40, structure: Frame > [Frame] + +2982× instance "Checkboxes" (100% match) + size: 48×48, structure: Instance > [Frame] +``` + +## JSON-вывод + +Все команды анализа поддерживают `--json` для машиночитаемого вывода: + +```sh +open-pencil analyze colors design.fig --json +``` + +Передавайте в `jq`, используйте в CI-проверках или в скриптах, контролирующих бюджет дизайн-токенов. diff --git a/packages/docs/ru/programmable/cli/exporting.md b/packages/docs/ru/programmable/cli/exporting.md new file mode 100644 index 000000000..14d2bdd04 --- /dev/null +++ b/packages/docs/ru/programmable/cli/exporting.md @@ -0,0 +1,59 @@ +--- +title: Экспорт +description: Рендер .fig-файлов в PNG, JPG, WEBP, SVG или JSX с классами Tailwind. +--- + +# Экспорт + +Экспортируйте дизайн из терминала — растровые изображения, вектор или JSX-код. + +## Экспорт изображений + +```sh +open-pencil export design.fig # PNG (по умолчанию) +open-pencil export design.fig -f jpg -s 2 -q 90 # JPG в 2×, качество 90 +open-pencil export design.fig -f webp -s 3 # WEBP в 3× +open-pencil export design.fig -f svg # SVG-вектор +``` + +Параметры: + +- `-f` — формат: `png`, `jpg`, `webp`, `svg`, `jsx` +- `-s` — масштаб: `1`–`4` +- `-q` — качество: `0`–`100` (только JPG/WEBP) +- `-o` — путь для сохранения +- `--page` — имя страницы +- `--node` — ID конкретного узла + +## Экспорт в JSX + +Экспорт в JSX с утилитарными классами Tailwind: + +```sh +open-pencil export design.fig -f jsx --style tailwind +``` + +Результат: + +```html +
+

Card Title

+

Description text

+
+``` + +Также поддерживается `--style openpencil` для нативного JSX-формата (см. [JSX-рендерер](../jsx-renderer)). + +## Миниатюры + +```sh +open-pencil export design.fig --thumbnail --width 1920 --height 1080 +``` + +## Режим работы с приложением + +Опустите файл для экспорта из запущенного приложения: + +```sh +open-pencil export -f png # снимок текущего холста +``` diff --git a/packages/docs/ru/programmable/cli/inspecting.md b/packages/docs/ru/programmable/cli/inspecting.md new file mode 100644 index 000000000..28de791eb --- /dev/null +++ b/packages/docs/ru/programmable/cli/inspecting.md @@ -0,0 +1,98 @@ +--- +title: Просмотр файлов +description: Просматривайте деревья узлов, ищите по имени или типу и изучайте свойства из терминала. +--- + +# Просмотр файлов + +CLI позволяет исследовать файлы `.fig` без открытия редактора. Каждая команда также работает с запущенным приложением — просто опустите аргумент файла. + +::: tip Установка +```sh +bun add -g @open-pencil/cli +# или +brew install open-pencil/tap/open-pencil +``` +::: + +## Информация о документе + +Краткий обзор — количество страниц, общее число узлов, используемые шрифты, размер файла: + +```sh +open-pencil info design.fig +``` + +## Дерево узлов + +Вывод полной иерархии узлов: + +```sh +open-pencil tree design.fig +``` + +``` +[0] [page] "Getting started" (0:46566) + [0] [section] "" (0:46567) + [0] [frame] "Body" (0:46568) + [0] [frame] "Introduction" (0:46569) + [0] [frame] "Introduction Card" (0:46570) + [0] [frame] "Guidance" (0:46571) +``` + +## Поиск узлов + +Поиск по типу: + +```sh +open-pencil find design.fig --type TEXT +``` + +Поиск по имени: + +```sh +open-pencil find design.fig --name "Button" +``` + +Оба флага можно комбинировать для более точных результатов. + +## Свойства узла + +Просмотр всех свойств конкретного узла по его ID: + +```sh +open-pencil node design.fig --id 1:23 +``` + +## Страницы + +Список всех страниц в документе: + +```sh +open-pencil pages design.fig +``` + +## Переменные + +Список дизайн-переменных и их коллекций: + +```sh +open-pencil variables design.fig +``` + +## Режим работы с приложением + +Когда настольное приложение запущено, опустите аргумент файла — CLI подключится по RPC и будет работать с активным холстом: + +```sh +open-pencil tree # просмотр текущего документа +open-pencil eval -c "..." # запрос к редактору +``` + +## JSON-вывод + +Все команды поддерживают `--json` для машиночитаемого вывода — передавайте в `jq`, используйте в CI-скриптах или обрабатывайте другими инструментами: + +```sh +open-pencil tree design.fig --json | jq '.[] | .name' +``` diff --git a/packages/docs/ru/programmable/cli/scripting.md b/packages/docs/ru/programmable/cli/scripting.md new file mode 100644 index 000000000..b6f001201 --- /dev/null +++ b/packages/docs/ru/programmable/cli/scripting.md @@ -0,0 +1,70 @@ +--- +title: Скрипты +description: Выполняйте JavaScript с Figma Plugin API — запрашивайте узлы, массово изменяйте дизайн, создавайте фреймы. +--- + +# Скрипты + +`open-pencil eval` предоставляет полный Figma Plugin API в терминале. Читайте узлы, изменяйте свойства, создавайте фигуры — и сохраняйте изменения обратно в файл. + +## Базовое использование + +```sh +open-pencil eval design.fig -c "figma.currentPage.children.length" +``` + +Флаг `-c` принимает JavaScript. Глобальный объект `figma` работает как Figma Plugin API. + +## Запрос узлов + +```sh +open-pencil eval design.fig -c " + figma.currentPage.findAll(n => n.type === 'FRAME' && n.name.includes('Button')) + .map(b => ({ id: b.id, name: b.name, w: b.width, h: b.height })) +" +``` + +## Изменение и сохранение + +```sh +open-pencil eval design.fig -c " + figma.currentPage.children.forEach(n => n.opacity = 0.5) +" -w +``` + +`-w` записывает изменения обратно во входной файл. Используйте `-o output.fig`, чтобы записать в другой файл. + +## Чтение из stdin + +Для длинных скриптов: + +```sh +cat transform.js | open-pencil eval design.fig --stdin -w +``` + +## Режим работы с приложением + +Опустите файл для выполнения команд в запущенном настольном приложении: + +```sh +open-pencil eval -c "figma.currentPage.name" +``` + +## Доступный API + +Объект `figma` поддерживает: + +- `figma.currentPage` — активная страница +- `figma.root` — корень документа +- `figma.createFrame()`, `figma.createRectangle()`, `figma.createEllipse()`, `figma.createText()` и др. +- `.findAll()`, `.findOne()` — поиск по потомкам +- `.appendChild()`, `.insertChild()` — манипуляции с деревом +- Все сеттеры свойств: `.fills`, `.strokes`, `.effects`, `.opacity`, `.cornerRadius`, `.layoutMode`, `.itemSpacing` и др. + +Это тот же API, который используют плагины Figma, поэтому существующие знания и фрагменты кода применимы напрямую. + +## JSON-вывод + +```sh +open-pencil eval design.fig -c "..." --json +``` diff --git a/packages/docs/ru/programmable/collaboration.md b/packages/docs/ru/programmable/collaboration.md new file mode 100644 index 000000000..bb558c0a7 --- /dev/null +++ b/packages/docs/ru/programmable/collaboration.md @@ -0,0 +1,38 @@ +--- +title: Совместная работа +description: Совместное редактирование в реальном времени через P2P WebRTC — без сервера, без аккаунта. +--- + +# Совместная работа + +Редактируйте дизайн вместе в реальном времени. Участники соединяются напрямую — никакой сервер не передаёт ваши данные, аккаунт не требуется. + +## Создание комнаты + +1. Нажмите кнопку «Поделиться» в правом верхнем углу +2. Скопируйте сгенерированную ссылку (`app.openpencil.dev/share/`) +3. Отправьте её коллегам + +Присоединиться может любой, у кого есть ссылка. Комната остаётся активной, пока хотя бы один участник держит страницу открытой. + +## Что синхронизируется + +- **Изменения документа** — каждая правка (фигуры, текст, свойства, лейаут) синхронизируется мгновенно +- **Курсоры** — видно, куда указывает каждый участник, с именем и цветом +- **Выделения** — выделенные объекты видны всем + +## Режим следования + +Нажмите на аватар коллеги в верхней панели, чтобы следовать за его областью просмотра. Ваш холст панорамируется и масштабируется, повторяя его вид. Нажмите снова, чтобы прекратить следование. + +## Как это работает + +Участники соединяются напрямую через WebRTC — дизайн-данные передаются напрямую из браузера в браузер, минуя центральный сервер. Состояние документа использует CRDT (бесконфликтный реплицируемый тип данных), поэтому одновременные правки объединяются автоматически без конфликтов. + +Комната сохраняется локально — если вы обновите страницу, вы вернётесь с тем же состоянием. + +## Советы + +- Работает в браузере и в настольном приложении +- Идентификаторы комнат генерируются криптографически — присоединиться могут только те, у кого есть ссылка +- Неактивные курсоры автоматически удаляются при отключении участника diff --git a/packages/docs/ru/programmable/index.md b/packages/docs/ru/programmable/index.md new file mode 100644 index 000000000..a27fdd4c6 --- /dev/null +++ b/packages/docs/ru/programmable/index.md @@ -0,0 +1,51 @@ +--- +layout: doc +title: ИИ и автоматизация +description: Каждая операция в OpenPencil доступна из скриптов — ИИ-чат, CLI, JSX-рендерер, MCP-сервер, совместная работа в реальном времени. +--- + +# ИИ и автоматизация + +OpenPencil работает с дизайн-файлами как с данными. Каждая операция, доступная в редакторе — создание фигур, настройка заливок, управление автолейаутом, экспорт ассетов — также доступна из терминала, ИИ-агентов и кода. Без плагинов, без API-ключей, без листов ожидания. + +Интерфейс редактора и инструменты автоматизации используют один и тот же движок. Если что-то можно сделать кликом — это можно сделать скриптом. + +## ИИ-чат + +Встроенный ассистент имеет доступ к 87 инструментам, покрывающим все возможности редактора. Опишите, что вам нужно, на естественном языке — «добавь тень 16px ко всем кнопкам», «создай компонент карточки с вариантом для тёмной темы», «экспортируй каждый фрейм на этой странице в 2×». + +[ИИ-чат →](./ai-chat) + +## Совместная работа + +Совместное редактирование в реальном времени через peer-to-peer WebRTC. Без сервера, без аккаунта. Поделитесь ссылкой на комнату и редактируйте вместе с курсорами в реальном времени и режимом следования. Состояние документа синхронизируется через CRDT, поэтому правки объединяются автоматически даже при нестабильном соединении. + +[Совместная работа →](./collaboration) + +## JSX-рендерер + +Описывайте интерфейс как JSX — тот же синтаксис, который LLM уже знают из React. Один вызов может создать целое дерево компонентов с фреймами, текстом, автолейаутом, заливками и обводками. Компактно, декларативно и поддаётся сравнению. + +В обратном направлении — экспортируйте любое выделение обратно в JSX с классами Tailwind, что удобно для передачи в разработку или для повторной загрузки дизайна в LLM. + +[JSX-рендерер →](./jsx-renderer) + +## CLI + +Просматривайте, экспортируйте и анализируйте файлы `.fig` без открытия редактора. Список страниц, поиск узлов, извлечение дизайн-токенов, рендер в PNG — всё из терминала с машиночитаемым JSON-выводом. + +CLI также подключается к запущенному настольному приложению по RPC, позволяя управлять редактором скриптами прямо во время работы. + +[Просмотр файлов](./cli/inspecting) · [Экспорт](./cli/exporting) · [Анализ дизайна](./cli/analyzing) · [Скрипты](./cli/scripting) + +## MCP-сервер + +Подключите Claude Code, Cursor, Windsurf или любой MCP-совместимый клиент к OpenPencil. Сервер предоставляет 90 инструментов для чтения, создания и изменения дизайна — те же инструменты, которые использует встроенный ИИ-чат. Работает через stdio или HTTP с поддержкой сессий. + +[MCP-сервер →](./mcp-server) + +## Почему открытый? + +Figma — закрытая платформа. Их MCP-сервер работает только на чтение. Доступ через CDP был заблокирован в версии 126. Дизайн-файлы хранятся в проприетарном формате на чужих серверах. Разработка плагинов требует специального рантайма с ограниченными API. + +OpenPencil — альтернатива: открытый исходный код, лицензия MIT, каждая операция доступна из скриптов, данные хранятся локально. Ваши дизайн-файлы — ваши: просматривайте, трансформируйте, отправляйте в CI, загружайте в LLM. Без чьего-либо разрешения. diff --git a/packages/docs/ru/programmable/jsx-renderer.md b/packages/docs/ru/programmable/jsx-renderer.md new file mode 100644 index 000000000..8ace2f729 --- /dev/null +++ b/packages/docs/ru/programmable/jsx-renderer.md @@ -0,0 +1,116 @@ +--- +title: JSX-рендерер +description: Создавайте дизайн с помощью JSX — синтаксиса, который LLM уже знают из миллионов React-компонентов. +--- + +# JSX-рендерер + +OpenPencil использует JSX как язык создания дизайна. LLM видели миллионы React-компонентов — описание макета через `` естественно и не требует специального обучения. Каждый токен важен, когда ИИ-агент выполняет десятки операций, а JSX — это самое компактное декларативное представление. + +JSX также поддаётся сравнению. Когда ИИ изменяет дизайн, изменение представлено как JSX-дифф — читаемый, проверяемый, пригодный для контроля версий. + +## Создание дизайна + +Инструмент `render` (доступен в ИИ-чате, MCP и CLI eval) принимает JSX: + +```jsx + + Card Title + Description text + +``` + +В MCP-сервере и ИИ-чате инструмент `render` принимает JSX-строки напрямую. В CLI используйте команду `export` для обратного направления — [экспорт дизайна в JSX](./cli/exporting). + +## Элементы + +Все типы узлов доступны как JSX-элементы: + +| Элемент | Создаёт | Псевдонимы | +|---------|---------|------------| +| `` | Фрейм (контейнер, поддерживает автолейаут) | `` | +| `` | Прямоугольник | `` | +| `` | Эллипс / круг | | +| `` | Текстовый узел (дочерние элементы становятся текстовым содержимым) | | +| `` | Линия | | +| `` | Звезда | | +| `` | Многоугольник | | +| `` | Векторный контур | | +| `` | Группа | | +| `
` | Секция | | + +## Свойства стиля + +Компактные сокращённые свойства, вдохновлённые именованием Tailwind. + +### Лейаут + +| Свойство | Описание | +|----------|----------| +| `flex` | `"row"` или `"col"` — включает автолейаут | +| `gap` | Расстояние между дочерними элементами | +| `wrap` | Перенос дочерних элементов на следующую строку | +| `rowGap` | Межстрочный интервал при переносе | +| `justify` | `"start"`, `"end"`, `"center"`, `"between"` | +| `items` | `"start"`, `"end"`, `"center"`, `"stretch"` | +| `p`, `px`, `py`, `pt`, `pr`, `pb`, `pl` | Отступы | + +### Размер и позиция + +| Свойство | Описание | +|----------|----------| +| `w`, `h` | Ширина/высота — число, `"fill"` или `"hug"` | +| `minW`, `maxW`, `minH`, `maxH` | Ограничения размера | +| `x`, `y` | Позиция | + +### Внешний вид + +| Свойство | Описание | +|----------|----------| +| `bg` | Заливка фона (HEX-цвет) | +| `fill` | Псевдоним для `bg` | +| `stroke` | Цвет обводки | +| `strokeWidth` | Толщина обводки (по умолчанию: 1) | +| `rounded` | Скругление углов (или `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`) | +| `cornerSmoothing` | Плавное скругление в стиле iOS (0–1) | +| `opacity` | 0–1 | +| `shadow` | Тень (напр. `"0 4 8 #00000040"`) | +| `blur` | Радиус размытия слоя | +| `rotate` | Поворот в градусах | +| `blendMode` | Режим наложения | +| `overflow` | `"hidden"` или `"visible"` | + +### Типографика + +| Свойство | Описание | +|----------|----------| +| `size` / `fontSize` | Размер шрифта | +| `font` / `fontFamily` | Семейство шрифта | +| `weight` / `fontWeight` | `"bold"`, `"medium"`, `"normal"` или число | +| `color` | Цвет текста | +| `textAlign` | `"left"`, `"center"`, `"right"`, `"justified"` | + +## Экспорт в JSX + +Конвертируйте существующий дизайн обратно в JSX: + +```sh +open-pencil export design.fig -f jsx # формат OpenPencil +open-pencil export design.fig -f jsx --style tailwind # классы Tailwind +``` + +Круговой цикл работает: экспортируйте дизайн как JSX, измените код, отрендерьте обратно. + +## Визуальное сравнение + +Поскольку дизайн можно представить как JSX, изменения становятся диффами кода: + +```diff + +- Old Title ++ New Title + Description + +``` + +Это делает изменения дизайна доступными для ревью в пулл-реквестах, отслеживаемыми в системе контроля версий и проверяемыми в CI. diff --git a/packages/docs/ru/programmable/mcp-server.md b/packages/docs/ru/programmable/mcp-server.md new file mode 100644 index 000000000..e296a6447 --- /dev/null +++ b/packages/docs/ru/programmable/mcp-server.md @@ -0,0 +1,251 @@ +# 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` + +Security defaults (HTTP transport): + +- Binds to `127.0.0.1` by default (`HOST` to override) +- `eval` tool is disabled +- File operations are limited to `OPENPENCIL_MCP_ROOT` (defaults to current working directory) +- CORS is disabled by default; set `OPENPENCIL_MCP_CORS_ORIGIN` to allow one origin +- Optional auth token: `OPENPENCIL_MCP_AUTH_TOKEN` (client sends `Authorization: Bearer ` or `x-mcp-token`) + +Server 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` + +## AI Agent Skill + +Teach your AI coding agent to use OpenPencil tools: + +```sh +npx skills add open-pencil/skills@open-pencil +``` + +Works with Claude Code, Cursor, Windsurf, Codex, and any agent that supports [skills](https://skills.sh). The skill covers the CLI, MCP tools, JSX rendering, eval, and the running app's automation bridge. + +## Tools (90) + +### 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_current_page` | Get the current page name and ID | +| `get_node` | Get detailed properties of a node by ID | +| `find_nodes` | Find nodes by name pattern and/or type | +| `get_components` | List all components in the document | +| `list_pages` | List all pages | +| `list_variables` | List design variables | +| `list_collections` | List variable collections | +| `list_fonts` | List fonts used in the current page | +| `page_bounds` | Get bounding box of all objects on the current page | +| `node_bounds` | Get bounding box of a node | +| `node_ancestors` | Get ancestor chain of a node | +| `node_children` | Get direct children of a node | +| `node_tree` | Get the subtree rooted at a node | +| `node_bindings` | Get variable bindings on a node | + +### Create + +| Tool | Description | +|------|-------------| +| `create_shape` | Create a shape (`FRAME`, `RECTANGLE`, `ELLIPSE`, `TEXT`, `LINE`, `STAR`, `POLYGON`, `SECTION`) | +| `create_vector` | Create a vector node from a path string | +| `create_slice` | Create an export slice | +| `create_page` | Create a new page | +| `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 | +| `node_to_component` | Convert an existing node into a component in-place | + +### 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 | +| `set_rotation` | Set rotation angle in degrees | +| `set_opacity` | Set opacity (0–1) | +| `set_radius` | Set corner radius (uniform or per-corner) | +| `set_minmax` | Set min/max width and height constraints | +| `set_text` | Set text content of a `TEXT` node | +| `set_font` | Set font family and weight | +| `set_font_range` | Set font properties on a character range | +| `set_text_resize` | Set text auto-resize mode (fixed/auto-width/auto-height) | +| `set_visible` | Show or hide a node | +| `set_blend` | Set blend mode | +| `set_locked` | Lock or unlock a node | +| `set_stroke_align` | Set stroke alignment (inside/center/outside) | +| `set_text_properties` | Set text layout: alignment, auto-resize, text case, decoration, truncation | +| `set_layout_child` | Configure auto-layout child: sizing, grow, alignment, absolute positioning | +| `node_move` | Move a node to a new position | +| `node_resize` | Resize a node | +| `node_replace_with` | Replace a node with another node | +| `arrange` | Align or distribute selected nodes | + +### 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 | +| `flatten_nodes` | Flatten nodes into a single vector | +| `boolean_union` | Boolean union of two or more nodes | +| `boolean_subtract` | Boolean subtraction | +| `boolean_intersect` | Boolean intersection | +| `boolean_exclude` | Boolean exclusion | + +### Vector Path + +| Tool | Description | +|------|-------------| +| `path_get` | Get the path data of a vector node | +| `path_set` | Set the path data of a vector node | +| `path_scale` | Scale a vector path | +| `path_flip` | Flip a vector path horizontally or vertically | +| `path_move` | Translate a vector path | + +### Export + +| Tool | Description | +|------|-------------| +| `export_image` | Export nodes as PNG, JPG, or WEBP. Returns base64-encoded image data | +| `export_svg` | Export nodes as SVG markup | + +### Viewport + +| Tool | Description | +|------|-------------| +| `viewport_get` | Get current viewport position and zoom level | +| `viewport_set` | Set viewport position and zoom | +| `viewport_zoom_to_fit` | Zoom viewport to fit specified nodes | + +### Variables + +| Tool | Description | +|------|-------------| +| `get_variable` | Get a variable by ID or name | +| `find_variables` | Find variables by name pattern or type | +| `create_variable` | Create a new variable in a collection | +| `set_variable` | Set a variable value in a mode | +| `delete_variable` | Delete a variable | +| `bind_variable` | Bind a variable to a node property | +| `get_collection` | Get a variable collection by ID or name | +| `create_collection` | Create a new variable collection | +| `delete_collection` | Delete a variable collection | + +### Analyze + +| Tool | Description | +|------|-------------| +| `analyze_colors` | Analyze color palette usage across the document | +| `analyze_typography` | Analyze font/size/weight distribution | +| `analyze_spacing` | Analyze gap and padding values | +| `analyze_clusters` | Detect repeated patterns (potential components) | + +### Diff + +| Tool | Description | +|------|-------------| +| `diff_create` | Create a snapshot of the current document state | +| `diff_show` | Show differences between the current state and a snapshot | + +### 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 | + +Note: `eval` is available over stdio, but disabled in HTTP mode for security. diff --git a/packages/docs/ru/reference/cli.md b/packages/docs/ru/reference/cli.md new file mode 100644 index 000000000..6f83df440 --- /dev/null +++ b/packages/docs/ru/reference/cli.md @@ -0,0 +1,184 @@ +--- +title: CLI Reference +description: Complete reference for all open-pencil commands, options, and flags. +--- + +# CLI Reference + +All commands accept a `.fig` file as a positional argument. When omitted, the CLI connects to the running desktop app via RPC. + +## info + +Show document info — pages, node counts, fonts, file size. + +```sh +open-pencil info [file] [--json] +``` + +| Option | Description | +|--------|-------------| +| `--json` | Output as JSON | + +## tree + +Print the node hierarchy. + +```sh +open-pencil tree [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--page` | Page name (default: first page) | +| `--depth` | Max depth (default: unlimited) | +| `--json` | Output as JSON | + +## find + +Search nodes by name or type. + +```sh +open-pencil find [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--name` | Node name (partial match, case-insensitive) | +| `--type` | Node type: `FRAME`, `TEXT`, `RECTANGLE`, `INSTANCE`, etc. | +| `--page` | Page name (default: all pages) | +| `--limit` | Max results (default: 100) | +| `--json` | Output as JSON | + +## node + +Show detailed properties of a node. + +```sh +open-pencil node [file] --id [--json] +``` + +| Option | Description | +|--------|-------------| +| `--id` | **Required.** Node ID (e.g. `1:23`) | +| `--json` | Output as JSON | + +## pages + +List all pages in the document. + +```sh +open-pencil pages [file] [--json] +``` + +| Option | Description | +|--------|-------------| +| `--json` | Output as JSON | + +## variables + +List design variables and collections. + +```sh +open-pencil variables [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--collection` | Filter by collection name | +| `--type` | Filter by type: `COLOR`, `FLOAT`, `STRING`, `BOOLEAN` | +| `--json` | Output as JSON | + +## export + +Export to PNG, JPG, WEBP, SVG, or JSX. + +```sh +open-pencil export [file] [options] +``` + +| Option | Alias | Description | +|--------|-------|-------------| +| `--format` | `-f` | `png` (default), `jpg`, `webp`, `svg`, `jsx` | +| `--output` | `-o` | Output file path (default: `.`) | +| `--scale` | `-s` | Export scale (default: 1) | +| `--quality` | `-q` | Quality 0–100, JPG/WEBP only (default: 90) | +| `--page` | | Page name (default: first page) | +| `--node` | | Node ID to export (default: all top-level nodes) | +| `--style` | | JSX style: `openpencil` (default), `tailwind` | +| `--thumbnail` | | Export page thumbnail instead of full render | +| `--width` | | Thumbnail width (default: 1920) | +| `--height` | | Thumbnail height (default: 1080) | + +## eval + +Execute JavaScript with the Figma Plugin API. + +```sh +open-pencil eval [file] [options] +``` + +| Option | Alias | Description | +|--------|-------|-------------| +| `--code` | `-c` | JavaScript code to execute | +| `--stdin` | | Read code from stdin | +| `--write` | `-w` | Write changes back to the input file | +| `--output` | `-o` | Write to a different file | +| `--json` | | Output as JSON | +| `--quiet` | `-q` | Suppress output | + +## analyze colors + +Analyze color palette usage across the document. + +```sh +open-pencil analyze colors [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--limit` | Max colors to show (default: 30) | +| `--threshold` | Distance threshold for clustering similar colors, 0–50 (default: 15) | +| `--similar` | Show similar color clusters | +| `--json` | Output as JSON | + +## analyze typography + +Analyze font family, size, and weight distribution. + +```sh +open-pencil analyze typography [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--group-by` | Group by: `family`, `size`, `weight` (default: show all styles) | +| `--limit` | Max styles to show (default: 30) | +| `--json` | Output as JSON | + +## analyze spacing + +Analyze gap and padding values across auto-layout frames. + +```sh +open-pencil analyze spacing [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--grid` | Base grid size to check against (default: 8) | +| `--json` | Output as JSON | + +## analyze clusters + +Find repeated node patterns — potential components. + +```sh +open-pencil analyze clusters [file] [options] +``` + +| Option | Description | +|--------|-------------| +| `--limit` | Max clusters to show (default: 20) | +| `--min-size` | Min node size in px (default: 30) | +| `--min-count` | Min instances to form a cluster (default: 2) | +| `--json` | Output as JSON | diff --git a/packages/docs/ru/reference/file-format.md b/packages/docs/ru/reference/file-format.md index 299b35612..ea94b8fb6 100644 --- a/packages/docs/ru/reference/file-format.md +++ b/packages/docs/ru/reference/file-format.md @@ -1,71 +1,72 @@ -# Формат файлов +# File Format -## Структура .fig файла +## .fig File Structure + +A `.fig` file is a ZIP archive containing a Kiwi-encoded binary message: + +| Offset | Content | +|--------|---------| +| 0 | Magic header `fig-kiwi` (8 bytes) | +| 8 | Version (4 bytes, uint32 LE) | +| 12 | Schema length (4 bytes, uint32 LE) | +| 16 | Compressed Kiwi schema | +| … | Message length (4 bytes, uint32 LE) | +| … | Compressed Kiwi message — `NodeChange[]` (entire document) | +| … | Blob data — images, vector networks, fonts | + +## Import Pipeline ``` -┌─────────────────────────────────┐ -│ Магический заголовок: "fig-kiwi" (8Б) │ -│ Версия (4Б uint32 LE) │ -│ Длина схемы (4Б uint32 LE) │ -│ Сжатая Kiwi-схема │ -│ Длина сообщения (4Б uint32 LE) │ -│ Сжатое Kiwi-сообщение │ ← NodeChange[] (весь документ) -│ Бинарные данные │ ← Изображения, векторные сети, шрифты -└─────────────────────────────────┘ +.fig file → parse header → decompress Zstd → decode Kiwi schema + → decode message → NodeChange[] → build SceneGraph + → resolve blob refs → render on canvas ``` -## Конвейер импорта +## Export Pipeline ``` -.fig файл → Парсинг заголовка → Декомпрессия Zstd → Декодирование Kiwi-схемы - → Декодирование сообщения → NodeChange[] → Построение SceneGraph - → Разрешение ссылок на блобы → Отрисовка на холсте +SceneGraph → NodeChange[] → Kiwi encode → compress (Zstd/deflate) + → build ZIP (header + schema + message + thumbnail.png) + → write .fig file ``` -## Конвейер экспорта +Export uses ⌘S (Save) and ⇧⌘S (Save As) with native OS dialogs on the desktop app. The exported file includes a `thumbnail.png` required by Figma for file preview. -``` -SceneGraph → NodeChange[] → Kiwi-кодирование → Сжатие (Zstd/deflate) - → Сборка ZIP (заголовок + схема + сообщение + thumbnail.png) - → Запись .fig файла -``` +Compression uses Zstd via Tauri Rust command on desktop, with deflate fallback in the browser. -Экспорт выполняется через ⌘S (Сохранить) и ⇧⌘S (Сохранить как) с нативными диалоговыми окнами ОС в десктопном приложении. Экспортированный файл включает `thumbnail.png`, необходимый Figma для предпросмотра. Сжатие использует Zstd через Tauri Rust-команду на десктопе, с fallback на deflate в браузере. ZIP-архив собирается на Rust в десктопном варианте для корректных заголовков Zstd-фреймов (с указанием размера содержимого). +## Kiwi Binary Codec -## Бинарный кодек Kiwi +The codec handles Figma's 194-definition Kiwi schema with `NodeChange` as the central type (~390 fields). Key components: -Кодек обрабатывает 194-определённую Kiwi-схему Figma с NodeChange в качестве центрального типа (~390 полей). Основные компоненты: +| Module | Purpose | +|--------|---------| +| `kiwi-schema` | Kiwi parser (from [evanw/kiwi](https://github.com/nicolo-ribaudo/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 | -- **kiwi-schema** — вендорённый из evanw/kiwi, с патчем для ESM и разреженных ID полей -- **codec.ts** — кодирование/декодирование сообщений с использованием Kiwi-схемы -- **protocol.ts** — парсинг проводного формата и определение типа сообщения -- **schema.ts** — 194 определения message/enum/struct +### Sparse Field IDs -### Разреженные ID полей +Figma's schema uses non-contiguous field IDs (e.g. 1, 2, 5, 10 with gaps). The kiwi-schema parser handles this correctly. -Схема Figma использует непоследовательные ID полей (например, 1, 2, 5, 10 с пропусками). Вендорённый парсер kiwi-schema пропатчен для корректной обработки этого случая. +### 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. -Файлы .fig используют Zstd-сжатие для полезных данных схемы и сообщения. Декомпрессия выполняется библиотекой `fzstd`. При экспорте Zstd-сжатие делегируется Tauri Rust-команде в десктопном приложении (лучшая производительность, корректные заголовки фреймов). В браузере в качестве fallback используется deflate через `fflate`. Кодирование буфера обмена также использует `fflate`. +## Supported Formats -## Поддерживаемые форматы +| Format | Import | Export | +|--------|--------|--------| +| `.fig` (Figma) | ✅ | ✅ | +| `.svg` | Planned | Planned | +| `.png` | Planned | Planned | +| `.pdf` | — | Planned | -| Формат | Импорт | Экспорт | -|--------|--------|---------| -| .fig (Figma) | ✅ | ✅ | -| .svg | Планируется | Планируется | -| .png | Планируется | Планируется | -| .pdf | — | Планируется | +## Clipboard Format -Подробнее о сроках поддержки форматов см. [Дорожная карта](/ru/development/roadmap). +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 -Копирование/вставка использует то же бинарное Kiwi-кодирование: - -1. **Копирование** — кодирование выбранных NodeChange[] в бинарный Kiwi, сжатие, запись в буфер обмена с MIME-типом `application/x-figma-design` -2. **Вставка** — чтение буфера обмена, декомпрессия, декодирование бинарного Kiwi, создание узлов в графе сцены -3. **Синхронность** — кодирование происходит в обработчике события копирования (не через асинхронный Clipboard API) для совместимости с браузерами - -Это обеспечивает двусторонний обмен через буфер обмена между OpenPencil и Figma. +Encoding happens synchronously in the copy event handler (not async Clipboard API) for browser compatibility. This enables bidirectional clipboard between OpenPencil and Figma. diff --git a/packages/docs/ru/reference/mcp-tools.md b/packages/docs/ru/reference/mcp-tools.md deleted file mode 100644 index bd2b31964..000000000 --- a/packages/docs/ru/reference/mcp-tools.md +++ /dev/null @@ -1,251 +0,0 @@ -# MCP-сервер - -OpenPencil включает MCP-сервер (Model Context Protocol), который позволяет AI-инструментам — Claude Code, Cursor, Windsurf и др. — читать и редактировать `.fig` файлы в headless-режиме. - -Два транспорта: **stdio** для MCP-клиентов, **HTTP** для всего остального. - -## Установка - -```sh -bun add -g @open-pencil/mcp -``` - -## Stdio (Claude Code, Cursor и др.) - -Добавьте в конфигурацию MCP (например, `~/.claude/settings.json` или `.cursor/mcp.json`): - -```json -{ - "mcpServers": { - "open-pencil": { - "command": "openpencil-mcp" - } - } -} -``` - -Или запустите из исходников без установки: - -::: 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 - -Для браузерных расширений, скриптов, CI или любого HTTP-клиента: - -```sh -openpencil-mcp-http -``` - -Или из исходников: `bun packages/mcp/src/http.ts` / `npx tsx packages/mcp/src/http.ts` - -Настройки безопасности (HTTP-транспорт): - -- По умолчанию привязка к `127.0.0.1` (переопределяется через `HOST`) -- Инструмент `eval` отключён -- Файловые операции ограничены `OPENPENCIL_MCP_ROOT` (по умолчанию — текущий рабочий каталог) -- CORS отключён по умолчанию; установите `OPENPENCIL_MCP_CORS_ORIGIN` для разрешения одного origin -- Опциональный токен аутентификации: `OPENPENCIL_MCP_AUTH_TOKEN` (клиент отправляет `Authorization: Bearer ` или `x-mcp-token`) - -Сервер запускается на порту 3100 (переопределяется через переменную окружения `PORT`). Эндпоинты: - -- `GET /health` — статус сервера -- `POST /mcp` — MCP Streamable HTTP (SSE). Сессии через заголовок `mcp-session-id`. - -## Рабочий процесс - -1. **Открытие** — `open_file` для загрузки существующего `.fig`, или `new_document` для чистого холста -2. **Чтение** — `get_page_tree`, `find_nodes`, `get_node`, `list_pages` -3. **Создание** — `create_shape`, `render` (JSX) -4. **Изменение** — `set_fill`, `set_stroke`, `set_layout`, `update_node`, `set_effects` -5. **Структура** — `reparent_node`, `group_nodes`, `clone_node`, `delete_node` -6. **Сохранение** — `save_file` для записи обратно в `.fig` - -## Навык для AI-агента - -Научите вашего AI-агента использовать инструменты OpenPencil: - -```sh -npx skills add open-pencil/skills@open-pencil -``` - -Работает с Claude Code, Cursor, Windsurf, Codex и любым агентом, поддерживающим [skills](https://skills.sh). Навык охватывает CLI, MCP-инструменты, JSX-рендеринг, eval и мост автоматизации запущенного приложения. - -## Инструменты (90) - -### Документ - -| Инструмент | Описание | -|------------|----------| -| `open_file` | Открыть `.fig` файл для редактирования | -| `save_file` | Сохранить текущий документ в `.fig` файл | -| `new_document` | Создать новый пустой документ | - -### Чтение - -| Инструмент | Описание | -|------------|----------| -| `get_selection` | Получить выделенные узлы | -| `get_page_tree` | Получить полное дерево узлов текущей страницы | -| `get_current_page` | Получить имя и ID текущей страницы | -| `get_node` | Получить свойства узла по ID | -| `find_nodes` | Найти узлы по шаблону имени и/или типу | -| `get_components` | Список всех компонентов в документе | -| `list_pages` | Список всех страниц | -| `list_variables` | Список дизайн-переменных | -| `list_collections` | Список коллекций переменных | -| `list_fonts` | Список шрифтов на текущей странице | -| `page_bounds` | Получить ограничивающий прямоугольник всех объектов на странице | -| `node_bounds` | Получить ограничивающий прямоугольник узла | -| `node_ancestors` | Получить цепочку предков узла | -| `node_children` | Получить прямых потомков узла | -| `node_tree` | Получить поддерево с корнем в узле | -| `node_bindings` | Получить привязки переменных к узлу | - -### Создание - -| Инструмент | Описание | -|------------|----------| -| `create_shape` | Создать фигуру (FRAME, RECTANGLE, ELLIPSE, TEXT, LINE, STAR, POLYGON, SECTION) | -| `create_vector` | Создать векторный узел из строки пути | -| `create_slice` | Создать экспортную область | -| `create_page` | Создать новую страницу | -| `render` | Рендеринг JSX в узлы дизайна — создание целых деревьев компонентов за один вызов | -| `create_component` | Преобразовать фрейм/группу в компонент | -| `create_instance` | Создать экземпляр компонента | -| `node_to_component` | Преобразовать существующий узел в компонент на месте | - -### Изменение - -| Инструмент | Описание | -|------------|----------| -| `set_fill` | Установить цвет заливки (hex) | -| `set_stroke` | Установить цвет, толщину и выравнивание обводки | -| `set_effects` | Добавить тень или размытие | -| `update_node` | Обновить позицию, размер, непрозрачность, радиус скругления, текст, шрифт | -| `set_layout` | Установить auto-layout (flexbox) — направление, отступы, выравнивание | -| `set_constraints` | Установить ограничения масштабирования | -| `set_rotation` | Установить угол поворота в градусах | -| `set_opacity` | Установить непрозрачность (0–1) | -| `set_radius` | Установить радиус скругления (единый или для каждого угла) | -| `set_minmax` | Установить ограничения мин./макс. ширины и высоты | -| `set_text` | Установить текстовое содержимое узла TEXT | -| `set_font` | Установить семейство и начертание шрифта | -| `set_font_range` | Установить свойства шрифта для диапазона символов | -| `set_text_resize` | Установить режим авторазмера текста (fixed/auto-width/auto-height) | -| `set_visible` | Показать или скрыть узел | -| `set_blend` | Установить режим наложения | -| `set_locked` | Заблокировать или разблокировать узел | -| `set_stroke_align` | Установить выравнивание обводки (inside/center/outside) | -| `set_text_properties` | Установить свойства текста: выравнивание, авторазмер, регистр, декор, обрезка | -| `set_layout_child` | Настроить дочерний элемент auto-layout: размер, grow, выравнивание, абсолютное позиционирование | -| `node_move` | Переместить узел на новую позицию | -| `node_resize` | Изменить размер узла | -| `node_replace_with` | Заменить узел другим узлом | -| `arrange` | Выровнять или распределить выделенные узлы | - -### Структура - -| Инструмент | Описание | -|------------|----------| -| `delete_node` | Удалить узел | -| `clone_node` | Дублировать узел | -| `rename_node` | Переименовать узел | -| `reparent_node` | Переместить узел в другой родительский элемент | -| `select_nodes` | Выделить узлы по ID | -| `group_nodes` | Сгруппировать узлы | -| `ungroup_node` | Разгруппировать группу | -| `flatten_nodes` | Объединить узлы в один вектор | -| `boolean_union` | Булево объединение двух и более узлов | -| `boolean_subtract` | Булево вычитание | -| `boolean_intersect` | Булево пересечение | -| `boolean_exclude` | Булево исключение | - -### Векторный путь - -| Инструмент | Описание | -|------------|----------| -| `path_get` | Получить данные пути векторного узла | -| `path_set` | Установить данные пути векторного узла | -| `path_scale` | Масштабировать векторный путь | -| `path_flip` | Отразить векторный путь по горизонтали или вертикали | -| `path_move` | Сдвинуть векторный путь | - -### Экспорт - -| Инструмент | Описание | -|------------|----------| -| `export_image` | Экспортировать узлы в PNG, JPG или WEBP. Возвращает base64-кодированные данные | -| `export_svg` | Экспортировать узлы как SVG-разметку | - -### Область просмотра - -| Инструмент | Описание | -|------------|----------| -| `viewport_get` | Получить текущую позицию и масштаб области просмотра | -| `viewport_set` | Установить позицию и масштаб области просмотра | -| `viewport_zoom_to_fit` | Масштабировать область просмотра по указанным узлам | - -### Переменные - -| Инструмент | Описание | -|------------|----------| -| `get_variable` | Получить переменную по ID или имени | -| `find_variables` | Найти переменные по шаблону имени или типу | -| `create_variable` | Создать новую переменную в коллекции | -| `set_variable` | Установить значение переменной в режиме | -| `delete_variable` | Удалить переменную | -| `bind_variable` | Привязать переменную к свойству узла | -| `get_collection` | Получить коллекцию переменных по ID или имени | -| `create_collection` | Создать новую коллекцию переменных | -| `delete_collection` | Удалить коллекцию переменных | - -### Анализ - -| Инструмент | Описание | -|------------|----------| -| `analyze_colors` | Анализ использования цветовой палитры в документе | -| `analyze_typography` | Анализ распределения шрифтов/размеров/начертаний | -| `analyze_spacing` | Анализ значений gap и padding | -| `analyze_clusters` | Обнаружение повторяющихся паттернов (потенциальных компонентов) | - -### Сравнение - -| Инструмент | Описание | -|------------|----------| -| `diff_create` | Создать снимок текущего состояния документа | -| `diff_show` | Показать различия между текущим состоянием и снимком | - -### Навигация - -| Инструмент | Описание | -|------------|----------| -| `switch_page` | Переключиться на страницу по имени или ID | - -### Произвольный код - -| Инструмент | Описание | -|------------|----------| -| `eval` | Выполнить JavaScript с полным доступом к Figma Plugin API | - -Примечание: `eval` доступен через stdio, но отключён в HTTP-режиме из соображений безопасности. diff --git a/packages/docs/ru/reference/node-types.md b/packages/docs/ru/reference/node-types.md index 6f4d331cc..f6024302d 100644 --- a/packages/docs/ru/reference/node-types.md +++ b/packages/docs/ru/reference/node-types.md @@ -1,48 +1,48 @@ -# Типы узлов +# Node Types -Граф сцены поддерживает 28 типов узлов из Kiwi-схемы Figma. Каждый узел идентифицируется GUID (`sessionID:localID`) и содержит ссылку на родителя через `parentIndex`. Объединение `NodeType` движка OpenPencil использует 17 из этих типов. +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 + 1 синтетический тип движка. Типы, отмеченные ✅, входят в объединение `NodeType` движка (всего 17). +28 Figma schema types + 1 synthetic engine type. Types marked ✅ are in the engine's `NodeType` union (17 total). -| Тип | ID | Описание | Движок | -|-----|----|----------|--------| -| DOCUMENT | 1 | Корневой узел, один на файл | — | -| CANVAS | 2 | Страница | ✅ | -| GROUP | 3 | Контейнер-группа | ✅ | -| FRAME | 4 | Основной контейнер (артборд), поддерживает auto-layout | ✅ | -| BOOLEAN_OPERATION | 5 | Результат union/subtract/intersect/exclude | | -| VECTOR | 6 | Свободный векторный путь | ✅ | -| STAR | 7 | Звезда | ✅ | -| LINE | 8 | Линия | ✅ | -| ELLIPSE | 9 | Эллипс/круг, поддерживает данные дуги | ✅ | -| RECTANGLE | 10 | Прямоугольник | ✅ | -| REGULAR_POLYGON | 11 | Правильный многоугольник (3–12 сторон, в движке используется `POLYGON`) | ✅ | -| ROUNDED_RECTANGLE | 12 | Прямоугольник со сглаженными углами | ✅ | -| TEXT | 13 | Текст с форматированием | ✅ | -| SLICE | 14 | Область экспорта | | -| SYMBOL | 15 | Компонент (основной, в движке используется `COMPONENT`) | ✅ | -| INSTANCE | 16 | Экземпляр компонента | ✅ | -| STICKY | 17 | Стикер FigJam | | -| SHAPE_WITH_TEXT | 18 | Фигура FigJam | ✅ | -| CONNECTOR | 19 | Соединительная линия между узлами | ✅ | -| CODE_BLOCK | 20 | Блок кода FigJam | | -| WIDGET | 21 | Виджет плагина | | -| STAMP | 22 | Штамп FigJam | | -| MEDIA | 23 | Видео/GIF | | -| HIGHLIGHT | 24 | Выделение FigJam | | -| SECTION | 25 | Секция холста (организационная, только верхний уровень) | ✅ | -| SECTION_OVERLAY | 26 | Оверлей секции | | -| WASHI_TAPE | 27 | Васи-тейп FigJam | | -| VARIABLE | 28 | Узел определения переменной | | -| COMPONENT_SET | — | Контейнер группы вариантов (синтетический, отображается из SYMBOL) | ✅ | +| 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`) | ✅ | -### Объединение NodeType движка (17 типов) +### Engine NodeType Union (17 types) -Движок использует упрощённые имена. Некоторые отличаются от Kiwi-схемы: +The engine's `NodeType` uses simplified names. Some differ from the Kiwi schema: - `COMPONENT` → Kiwi `SYMBOL` (ID 15) -- `COMPONENT_SET` → контейнер группы вариантов (нет выделенного Kiwi ID, отображается из SYMBOL с вариантами) +- `COMPONENT_SET` → variant group container (no dedicated Kiwi ID, mapped from `SYMBOL` with variants) - `POLYGON` → Kiwi `REGULAR_POLYGON` (ID 11) ```typescript @@ -54,81 +54,81 @@ type NodeType = | 'CONNECTOR' | 'SHAPE_WITH_TEXT' ``` -## Иерархия узлов +## Node Hierarchy ``` Document -├── Canvas (Страница 1) -│ ├── Section (только верхний уровень, плашка с названием, авто-захват соседей) +├── Canvas (Page 1) +│ ├── Section (top-level only, title pill, auto-adopts siblings) │ │ ├── Frame -│ │ │ └── ...дочерние элементы +│ │ │ └── ...children │ │ └── Rectangle │ ├── Frame │ │ ├── Rectangle │ │ ├── Text -│ │ └── Frame (вложенный) +│ │ └── Frame (nested) │ │ ├── Ellipse -│ │ └── Instance (→ ссылается на Component) +│ │ └── Instance (→ references Component) │ ├── Component -│ │ └── ...дочерние элементы +│ │ └── ...children │ ├── Group -│ │ └── ...дочерние элементы +│ │ └── ...children │ └── BooleanOperation -│ └── ...операнды -└── Canvas (Страница 2) +│ └── ...operand shapes +└── Canvas (Page 2) └── ... ``` -## Основные свойства +## Core Properties -Каждый узел содержит следующие поля (подмножество NodeChange): +Every node carries these fields (subset of `NodeChange`): -### Идентификация и дерево +### Identity & Tree -- `guid` — уникальный идентификатор (`sessionID:localID`) -- `type` — перечисление типа узла -- `name` — отображаемое имя -- `phase` — CREATED или REMOVED -- `parentIndex` — GUID родителя + строка позиции для z-упорядочивания +- `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` — вектор ширины/высоты -- `transform` — аффинная матрица 2×3 -- `rotation` — градусы +- `size` — width/height vector +- `transform` — 2×3 affine matrix +- `rotation` — degrees -### Внешний вид +### Appearance -- `fillPaints[]` — заливки цветом/градиентом/изображением -- `strokePaints[]` — цвета обводки -- `effects[]` — тени, размытия +- `fillPaints[]` — fill colors/gradients/images +- `strokePaints[]` — stroke colors +- `effects[]` — shadows, blurs - `opacity` — 0–1 -- `blendMode` — NORMAL, MULTIPLY, SCREEN и др. +- `blendMode` — `NORMAL`, `MULTIPLY`, `SCREEN`, etc. -### Обводка +### Stroke -- `strokeWeight` — толщина обводки -- `strokeAlign` — inside / center / outside -- `strokeCap` — butt / round / square -- `strokeJoin` — miter / bevel / round -- `dashPattern[]` — длины штрихов/промежутков +- `strokeWeight` — stroke thickness +- `strokeAlign` — `INSIDE` / `CENTER` / `OUTSIDE` +- `strokeCap` — `NONE` / `ROUND` / `SQUARE` / `ARROW_LINES` / `ARROW_EQUILATERAL` +- `strokeJoin` — `MITER` / `BEVEL` / `ROUND` +- `dashPattern[]` — dash/gap lengths -### Углы +### Corners -- `cornerRadius` — единый радиус -- `cornerSmoothing` — степень сквиркла (0–1) -- Индивидуальные радиусы углов, когда `rectangleCornerRadiiIndependent` равно true +- `cornerRadius` — uniform radius +- `cornerSmoothing` — squircle amount (0–1) +- Per-corner radii when `rectangleCornerRadiiIndependent` is true -### Видимость +### Visibility -- `visible` — показать/скрыть -- `locked` — предотвратить редактирование +- `visible` — show/hide +- `locked` — prevent editing -## Свойства отдельных типов +## Type-Specific Properties ### Text -`fontSize`, `fontName`, `lineHeight`, `letterSpacing`, `textAlignHorizontal`, `textAlignVertical`, `textAutoResize`, `textData` (символы, переопределения стилей, базовые линии, глифы) +`fontSize`, `fontName`, `lineHeight`, `letterSpacing`, `textAlignHorizontal`, `textAlignVertical`, `textAutoResize`, `textData` (characters, style overrides, baselines, glyphs) ### Vector @@ -156,9 +156,9 @@ interface Fill { opacity: number // 0–1 visible: boolean blendMode?: BlendMode - gradientStops?: GradientStop[] // для градиентов - gradientTransform?: GradientTransform // матрица 2×3 - imageHash?: string // для заливок изображением + gradientStops?: GradientStop[] // for gradients + gradientTransform?: GradientTransform // 2×3 matrix + imageHash?: string // for image fills imageScaleMode?: 'FILL' | 'FIT' | 'CROP' | 'TILE' imageTransform?: GradientTransform } diff --git a/packages/docs/ru/reference/scene-graph.md b/packages/docs/ru/reference/scene-graph.md index ae78d4039..0d445d189 100644 --- a/packages/docs/ru/reference/scene-graph.md +++ b/packages/docs/ru/reference/scene-graph.md @@ -1,8 +1,8 @@ -# Граф сцены +# Scene Graph -## Представление в памяти +## In-Memory Representation -Узлы хранятся в плоском `Map` с ключами-GUID. Древовидная структура поддерживается через ссылки `parentIndex`. Это обеспечивает O(1) поиск по ID и эффективный обход. +Nodes live in a flat `Map` 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 { @@ -29,38 +29,38 @@ interface SceneGraph { } ``` -## Страницы +## Pages -Документы поддерживают несколько страниц (узлы CANVAS как прямые потомки корня DOCUMENT). Каждая страница имеет собственное дерево дочерних элементов и независимое состояние области просмотра (panX, panY, zoom, pageColor). Редактор отслеживает `currentPageId` и отрисовывает только дочерние элементы активной страницы. +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 — это организационные контейнеры верхнего уровня (только прямые потомки CANVAS). Они не могут вкладываться во фреймы или группы. Создание секции автоматически захватывает перекрывающихся соседей. Секции отображают плашку с заголовком, цвет текста которой адаптируется в зависимости от яркости фона. +`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 -Состояние редактора отслеживает `hoveredNodeId` — узел, находящийся под курсором. Отрисовщик рисует контур наведения, повторяющий форму объекта (по фактической геометрии для эллипсов, скруглённых прямоугольников, векторов), для визуальной обратной связи перед выделением. +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 -Система использует паттерн **обратных команд** Figma. Каждая запись отмены содержит прямые изменения и их автоматически вычисленную инверсию: +The system uses Figma's **inverse command** pattern. Each undo entry contains the forward changes and their automatically-computed inverse: -| Операция | Прямое действие | Обратное действие | -|----------|-----------------|-------------------| -| Создание узла | `{guid, phase: CREATED, ...props}` | `{guid, phase: REMOVED}` | -| Удаление узла | `{guid, phase: REMOVED}` | `{guid, phase: CREATED, ...allProps}` | -| Изменение свойства | `{guid, fill: "#F00"}` | `{guid, fill: "#00F"}` | -| Перемещение узла | `{guid, parentIndex: newParent}` | `{guid, parentIndex: oldParent}` | +| 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. -**Группировка** — такие операции, как перетаскивание, генерируют сотни изменений позиции в секунду. Они объединяются в одну запись отмены с помощью дебаунса. `beginBatch`/`commitBatch` оборачивает многоступенчатые операции. +**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. -## Движок компоновки (Yoga) +## Layout Engine (Yoga) -Свойства auto-layout Figma отображаются на Yoga flexbox: +Figma's auto-layout properties map to Yoga flexbox: -| Свойство Figma | Эквивалент Yoga | +| Figma Property | Yoga Equivalent | |---|---| | `stackMode: HORIZONTAL` | `flexDirection: row` | | `stackMode: VERTICAL` | `flexDirection: column` | @@ -73,27 +73,27 @@ interface SceneGraph { | `stackChildAlignSelf` | `alignSelf` | | `stackPositioning: ABSOLUTE` | `position: absolute` | -## Проверка попадания (Hit Testing) +## Hit Testing -Для заданной точки в координатах холста граф сцены возвращает самый верхний видимый узел в этой позиции. Алгоритм: +Given a point in canvas coordinates, the scene graph returns the topmost visible node at that position. The algorithm: -1. Обход видимых узлов в обратном z-порядке (сверху вниз) -2. Преобразование точки проверки в локальную систему координат каждого узла -3. Проверка, находится ли точка в пределах границ узла (с учётом поворота) -4. Возврат первого совпадения +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 -Для выделения рамкой `getNodesInRect` возвращает все узлы, чьи границы пересекаются с заданным прямоугольником. +For marquee selection, `getNodesInRect` returns all nodes whose bounds intersect the given rectangle. -## Расширенные типы заливок +## Extended Fill Types -Заливки поддерживают шесть типов: SOLID, GRADIENT_LINEAR, GRADIENT_RADIAL, GRADIENT_ANGULAR, GRADIENT_DIAMOND и IMAGE. Градиентные заливки содержат `gradientStops` (пары цвет + позиция) и `gradientTransform` (матрица 2×3). Заливки изображением ссылаются на бинарные данные через `imageHash` с режимами масштабирования (FILL, FIT, CROP, TILE). +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 -Обводки поддерживают `cap` (NONE, ROUND, SQUARE, ARROW_LINES, ARROW_EQUILATERAL), `join` (MITER, BEVEL, ROUND) и `dashPattern` (массив длин штрихов/промежутков) в дополнение к базовым свойствам color, weight, opacity, visible и align. +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. -Поворот хранится в градусах и применяется как часть аффинной матрицы 2×3. Направляющие привязки и проверка попадания учитывают поворот при вычислении визуальных границ. +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/ru/user-guide/auto-layout.md b/packages/docs/ru/user-guide/auto-layout.md index b7b6e58de..492750799 100644 --- a/packages/docs/ru/user-guide/auto-layout.md +++ b/packages/docs/ru/user-guide/auto-layout.md @@ -5,12 +5,12 @@ description: Авто-раскладка на основе flexbox в OpenPencil # Авто-раскладка -Авто-раскладка использует Yoga (движок flexbox) для автоматического позиционирования дочерних элементов внутри фрейма. Она управляет направлением, отступами, выравниванием и адаптивными размерами. +Авто-раскладка автоматически позиционирует дочерние элементы внутри фрейма по правилам flexbox. Она управляет направлением, отступами, выравниванием и адаптивными размерами. ## Включение авто-раскладки -- Выделите фрейм и нажмите **⇧ A** (Shift + A), чтобы включить или выключить авто-раскладку -- Выделите свободные узлы (без родительского фрейма) и нажмите **⇧ A**, чтобы обернуть их в новый фрейм с авто-раскладкой +- Выделите фрейм и нажмите ⇧A (Shift + A), чтобы включить или выключить авто-раскладку +- Выделите свободные узлы (без родительского фрейма) и нажмите ⇧A, чтобы обернуть их в новый фрейм с авто-раскладкой При оборачивании выделения узлы сортируются по визуальному положению: слева направо для горизонтальной раскладки, сверху вниз для вертикальной. @@ -72,7 +72,7 @@ description: Авто-раскладка на основе flexbox в OpenPencil | Действие | Mac | Windows / Linux | |----------|-----|-----------------| -| Переключить авто-раскладку | ⇧ A | Shift + A | +| Переключить авто-раскладку | ⇧A | Shift + A | ## Советы diff --git a/packages/docs/ru/user-guide/canvas-navigation.md b/packages/docs/ru/user-guide/canvas-navigation.md index 60ae2eccd..85cfc8620 100644 --- a/packages/docs/ru/user-guide/canvas-navigation.md +++ b/packages/docs/ru/user-guide/canvas-navigation.md @@ -17,13 +17,13 @@ description: Перемещение, масштабирование и инст ## Инструмент «Рука» -Нажмите **H**, чтобы активировать инструмент «Рука» для непрерывного перемещения. Любое перетаскивание на холсте сдвигает область просмотра без необходимости удерживать Space. Переключитесь на другой инструмент (например, **V** для выделения), чтобы деактивировать. +Нажмите H, чтобы активировать инструмент «Рука» для непрерывного перемещения. Любое перетаскивание на холсте сдвигает область просмотра без необходимости удерживать Space. Переключитесь на другой инструмент (например, V для выделения), чтобы деактивировать. ## Масштабирование Увеличение и уменьшение масштаба относительно позиции курсора. -- **Ctrl + прокрутка** (или **⌘ + прокрутка** на Mac) — прокрутка вверх для увеличения, вниз для уменьшения +- Ctrl + прокрутка (или ⌘ + прокрутка на Mac) — прокрутка вверх для увеличения, вниз для уменьшения - **Жест сведения пальцев** — сведите пальцы на трекпаде для масштабирования - **Сочетания клавиш** — см. таблицу ниже @@ -33,11 +33,11 @@ description: Перемещение, масштабирование и инст | Действие | Mac | Windows / Linux | |----------|-----|-----------------| -| Перемещение | Space + перетаскивание | Space + перетаскивание | -| Инструмент «Рука» | H | H | -| Увеличить | ⌘ + | Ctrl + + | -| Уменьшить | ⌘ - | Ctrl + - | -| Масштаб 100% | ⌘ 0 | Ctrl + 0 | +| Перемещение | Space + перетаскивание | Space + перетаскивание | +| Инструмент «Рука» | H | H | +| Увеличить | ⌘+ | Ctrl + + | +| Уменьшить | ⌘− | Ctrl + − | +| Масштаб 100% | ⌘0 | Ctrl + 0 | ## Советы diff --git a/packages/docs/ru/user-guide/components.md b/packages/docs/ru/user-guide/components.md index 13b4d4952..2213aea6f 100644 --- a/packages/docs/ru/user-guide/components.md +++ b/packages/docs/ru/user-guide/components.md @@ -9,7 +9,7 @@ description: Создание переиспользуемых компонен ## Создание компонента -Выделите фрейм или группу и нажмите **⌥ ⌘ K** (Ctrl + Alt + K). Узел преобразуется в тип COMPONENT на месте. +Выделите фрейм или группу и нажмите ⌥⌘K (Ctrl + Alt + K). Выделение становится многоразовым компонентом. Если выделено несколько узлов, они оборачиваются в новый компонент, позиционированный по их ограничивающей рамке. @@ -17,7 +17,7 @@ description: Создание переиспользуемых компонен ## Наборы компонентов -Выделите два или более компонента и нажмите **⇧ ⌘ K** (Shift + Ctrl + K), чтобы объединить их в набор компонентов — контейнер с пунктирной фиолетовой рамкой и отступом 40 px вокруг дочерних элементов. Наборы компонентов полезны для группировки вариантов (например, состояний кнопки). +Выделите два или более компонента и нажмите ⇧⌘K (Shift + Ctrl + K), чтобы объединить их в набор компонентов — контейнер с пунктирной фиолетовой рамкой и отступом 40 px вокруг дочерних элементов. Наборы компонентов полезны для группировки вариантов (например, состояний кнопки). ## Создание экземпляров @@ -27,7 +27,7 @@ description: Создание переиспользуемых компонен ## Отсоединение экземпляра -Выделите экземпляр и нажмите **⌥ ⌘ B** (Ctrl + Alt + B), чтобы отсоединить его. Экземпляр становится обычным фреймом без связи с оригинальным компонентом. Все переопределения сохраняются. +Выделите экземпляр и нажмите ⌥⌘B (Ctrl + Alt + B), чтобы отсоединить его. Экземпляр становится обычным фреймом без связи с оригинальным компонентом. Все переопределения сохраняются. ## Перейти к основному компоненту @@ -51,9 +51,7 @@ description: Создание переиспользуемых компонен ### Переопределяемые свойства -Переопределения на уровне дочерних элементов поддерживают: имя, текст, fontSize, fontWeight, fontFamily, а также все визуальные свойства и свойства раскладки (заливки, обводки, эффекты, прозрачность, скругление углов, размеры). - -Ключи переопределений используют формат `childId:propertyName` в записи переопределений экземпляра. +Переопределения на уровне дочерних элементов поддерживают: имя, текст, размер шрифта, насыщенность шрифта, семейство шрифта, а также все визуальные свойства и свойства раскладки (заливки, обводки, эффекты, прозрачность, скругление углов, размеры). ### Новые дочерние элементы @@ -67,17 +65,17 @@ description: Создание переиспользуемых компонен | Элемент | Внешний вид | |---------|-------------| -| Метка компонента | Фиолетовая (#9747ff) с значком ромба, всегда видна | -| Метка экземпляра | Фиолетовая (#9747ff) с значком ромба, всегда видна | -| Рамка набора компонентов | Пунктирная фиолетовая (штрих 6 px, промежуток 4 px, толщина 1.5 px) | +| Метка компонента | Фиолетовая с значком ромба, всегда видна | +| Метка экземпляра | Фиолетовая с значком ромба, всегда видна | +| Рамка набора компонентов | Пунктирная фиолетовая рамка | ## Сочетания клавиш | Действие | Mac | Windows / Linux | |----------|-----|-----------------| -| Создать компонент | ⌥ ⌘ K | Ctrl + Alt + K | -| Создать набор компонентов | ⇧ ⌘ K | Shift + Ctrl + K | -| Отсоединить экземпляр | ⌥ ⌘ B | Ctrl + Alt + B | +| Создать компонент | ⌥⌘K | Ctrl + Alt + K | +| Создать набор компонентов | ⇧⌘K | Shift + Ctrl + K | +| Отсоединить экземпляр | ⌥⌘B | Ctrl + Alt + B | ## Советы diff --git a/packages/docs/ru/user-guide/context-menu.md b/packages/docs/ru/user-guide/context-menu.md index 5b9fa58bb..763cc1366 100644 --- a/packages/docs/ru/user-guide/context-menu.md +++ b/packages/docs/ru/user-guide/context-menu.md @@ -15,7 +15,7 @@ description: Действия контекстного меню по право |----------|-----------------|----------------------| | Копировать как текст | — | — | | Копировать как SVG | — | — | -| Копировать как PNG | ⇧ ⌘ C | Shift + Ctrl + C | +| Копировать как PNG | ⇧⌘C | Shift + Ctrl + C | | Копировать как JSX | — | — | - **Копировать как текст** — копирует видимое текстовое содержимое из выделения @@ -27,11 +27,11 @@ description: Действия контекстного меню по право | Действие | Сочетание (Mac) | Сочетание (Win/Linux) | |----------|-----------------|----------------------| -| Копировать | ⌘ C | Ctrl + C | -| Вырезать | ⌘ X | Ctrl + X | -| Вставить сюда | ⌘ V | Ctrl + V | -| Дублировать | ⌘ D | Ctrl + D | -| Удалить | ⌫ | Backspace / Delete | +| Копировать | ⌘C | Ctrl + C | +| Вырезать | ⌘X | Ctrl + X | +| Вставить сюда | ⌘V | Ctrl + V | +| Дублировать | ⌘D | Ctrl + D | +| Удалить | ⌫ | Backspace / Delete | Действия с буфером обмена недоступны, когда ничего не выделено (кроме «Вставить», которое доступно при наличии содержимого в буфере обмена). @@ -48,9 +48,9 @@ description: Действия контекстного меню по право | Действие | Сочетание (Mac) | Сочетание (Win/Linux) | |----------|-----------------|----------------------| -| Сгруппировать | ⌘ G | Ctrl + G | -| Разгруппировать | ⇧ ⌘ G | Shift + Ctrl + G | -| Добавить авто-раскладку | ⇧ A | Shift + A | +| Сгруппировать | ⌘G | Ctrl + G | +| Разгруппировать | ⇧⌘G | Shift + Ctrl + G | +| Добавить авто-раскладку | ⇧A | Shift + A | - **Сгруппировать** требует 2 или более выделенных узла - **Разгруппировать** появляется при выделении группы — дочерние элементы перемещаются к родителю группы @@ -62,11 +62,11 @@ description: Действия контекстного меню по право | Действие | Сочетание (Mac) | Сочетание (Win/Linux) | Доступно для | |----------|-----------------|----------------------|--------------| -| Создать компонент | ⌥ ⌘ K | Ctrl + Alt + K | Фреймы, группы, множественное выделение | -| Создать набор компонентов | ⇧ ⌘ K | Shift + Ctrl + K | 2+ выделенных компонента | +| Создать компонент | ⌥⌘K | Ctrl + Alt + K | Фреймы, группы, множественное выделение | +| Создать набор компонентов | ⇧⌘K | Shift + Ctrl + K | 2+ выделенных компонента | | Создать экземпляр | — | — | Компоненты (без сочетания клавиш) | | Перейти к основному компоненту | — | — | Экземпляры | -| Отсоединить экземпляр | ⌥ ⌘ B | Ctrl + Alt + B | Экземпляры | +| Отсоединить экземпляр | ⌥⌘B | Ctrl + Alt + B | Экземпляры | См. [Компоненты](./components) для подробностей о работе с компонентами. @@ -74,8 +74,8 @@ description: Действия контекстного меню по право | Действие | Сочетание (Mac) | Сочетание (Win/Linux) | |----------|-----------------|----------------------| -| Скрыть / Показать | ⇧ ⌘ H | Shift + Ctrl + H | -| Заблокировать / Разблокировать | ⇧ ⌘ L | Shift + Ctrl + L | +| Скрыть / Показать | ⇧⌘H | Shift + Ctrl + H | +| Заблокировать / Разблокировать | ⇧⌘L | Shift + Ctrl + L | Метка переключается в зависимости от текущего состояния узла (например, «Скрыть» для видимого узла, «Показать» для скрытого). diff --git a/packages/docs/ru/user-guide/drawing-shapes.md b/packages/docs/ru/user-guide/drawing-shapes.md index 367af2686..6e4f3527a 100644 --- a/packages/docs/ru/user-guide/drawing-shapes.md +++ b/packages/docs/ru/user-guide/drawing-shapes.md @@ -11,11 +11,11 @@ description: Создание прямоугольников, эллипсов, | Инструмент | Сочетание | Описание | |------------|-----------|----------| -| Прямоугольник | R | Рисует прямоугольник | -| Эллипс | O | Рисует эллипс | -| Линия | L | Рисует линию | -| Фрейм | F | Рисует фрейм (контейнер для других узлов) | -| Секция | S | Рисует секцию (автоматически включает перекрывающиеся соседние элементы) | +| Прямоугольник | R | Рисует прямоугольник | +| Эллипс | O | Рисует эллипс | +| Линия | L | Рисует линию | +| Фрейм | F | Рисует фрейм (контейнер для других узлов) | +| Секция | S | Рисует секцию (автоматически включает перекрывающиеся соседние элементы) | ## Выпадающее меню фигур @@ -28,7 +28,7 @@ description: Создание прямоугольников, эллипсов, ## Пропорциональное рисование -Удерживайте **Shift** при перетаскивании, чтобы ограничить пропорции фигуры: +Удерживайте Shift при перетаскивании, чтобы ограничить пропорции фигуры: - Прямоугольник → квадрат (одинаковая ширина и высота) - Эллипс → круг @@ -83,12 +83,12 @@ description: Создание прямоугольников, эллипсов, | Действие | Mac | Windows / Linux | |----------|-----|-----------------| -| Прямоугольник | R | R | -| Эллипс | O | O | -| Линия | L | L | -| Фрейм | F | F | -| Секция | S | S | -| Ограничить до квадрата/круга | Shift + перетаскивание | Shift + перетаскивание | +| Прямоугольник | R | R | +| Эллипс | O | O | +| Линия | L | L | +| Фрейм | F | F | +| Секция | S | S | +| Ограничить до квадрата/круга | Shift + перетаскивание | Shift + перетаскивание | ## Советы diff --git a/packages/docs/ru/user-guide/exporting.md b/packages/docs/ru/user-guide/exporting.md index 55ebc700d..0723c722b 100644 --- a/packages/docs/ru/user-guide/exporting.md +++ b/packages/docs/ru/user-guide/exporting.md @@ -22,8 +22,8 @@ description: Экспорт изображений (PNG, JPG, WEBP) и сохр | Метод | Mac | Windows / Linux | |-------|-----|-----------------| -| Сочетание клавиш | ⇧ ⌘ E | Shift + Ctrl + E | -| Контекстное меню | Правый клик → Экспорт… | Правый клик → Экспорт… | +| Сочетание клавиш | ⇧⌘E | Shift + Ctrl + E | +| Контекстное меню | Правый клик → Экспорт… | Правый клик → Экспорт… | | Панель свойств | Нажать кнопку «Экспорт» | Нажать кнопку «Экспорт» | Экспортированный файл сохраняется через нативный диалог (настольное приложение) или скачивание в браузере. @@ -36,7 +36,7 @@ description: Экспорт изображений (PNG, JPG, WEBP) и сохр |----------|-----------------|----------------------| | Копировать как текст | — | — | | Копировать как SVG | — | — | -| Копировать как PNG | ⇧ ⌘ C | Shift + Ctrl + C | +| Копировать как PNG | ⇧⌘C | Shift + Ctrl + C | | Копировать как JSX | — | — | - **Копировать как текст** — копирует видимое текстовое содержимое из выделения @@ -52,7 +52,7 @@ OpenPencil использует формат .fig для полных докум | Действие | Mac | Windows / Linux | |----------|-----|-----------------| -| Открыть файл | ⌘ O | Ctrl + O | +| Открыть файл | ⌘O | Ctrl + O | Открывается диалог выбора файла с фильтром по файлам .fig. В настольном приложении используется нативный диалог ОС. @@ -60,13 +60,13 @@ OpenPencil использует формат .fig для полных докум | Действие | Mac | Windows / Linux | |----------|-----|-----------------| -| Сохранить | ⌘ S | Ctrl + S | -| Сохранить как | ⇧ ⌘ S | Shift + Ctrl + S | +| Сохранить | ⌘S | Ctrl + S | +| Сохранить как | ⇧⌘S | Shift + Ctrl + S | - **Сохранить** — перезаписывает текущий открытый файл без диалога - **Сохранить как** — открывает диалог сохранения для выбора нового местоположения -Конвейер экспорта кодирует граф сцены в бинарный формат Kiwi, сжимает его и записывает ZIP-архив с данными и миниатюрой. +Сохранённые файлы сжимаются и включают миниатюру для предпросмотра. ### Совместимость двустороннего обмена @@ -76,11 +76,11 @@ OpenPencil использует формат .fig для полных докум | Действие | Mac | Windows / Linux | |----------|-----|-----------------| -| Экспорт выделения | ⇧ ⌘ E | Shift + Ctrl + E | -| Копировать как PNG | ⇧ ⌘ C | Shift + Ctrl + C | -| Открыть файл | ⌘ O | Ctrl + O | -| Сохранить | ⌘ S | Ctrl + S | -| Сохранить как | ⇧ ⌘ S | Shift + Ctrl + S | +| Экспорт выделения | ⇧⌘E | Shift + Ctrl + E | +| Копировать как PNG | ⇧⌘C | Shift + Ctrl + C | +| Открыть файл | ⌘O | Ctrl + O | +| Сохранить | ⌘S | Ctrl + S | +| Сохранить как | ⇧⌘S | Shift + Ctrl + S | ## Советы diff --git a/packages/docs/ru/user-guide/index.md b/packages/docs/ru/user-guide/index.md index cdb4fcc63..caba492a0 100644 --- a/packages/docs/ru/user-guide/index.md +++ b/packages/docs/ru/user-guide/index.md @@ -9,7 +9,7 @@ description: Узнайте, как использовать OpenPencil — на OpenPencil — это редактор дизайна с открытым исходным кодом, совместимый с Figma. Полностью локальный, с нативной поддержкой ИИ и возможностью программирования. Это руководство охватывает всё, что нужно знать для эффективной работы с редактором. ::: tip Кроссплатформенные сочетания клавиш -В этом руководстве сочетания клавиш приведены в нотации Mac: **⌘** = Command (Ctrl на Windows/Linux), **⌥** = Option (Alt), **⇧** = Shift. +В этом руководстве сочетания клавиш приведены в нотации Mac: ⌘ = Command (Ctrl на Windows/Linux), ⌥ = Option (Alt), ⇧ = Shift. ::: ## Навигация @@ -31,6 +31,6 @@ OpenPencil — это редактор дизайна с открытым исх ## Продвинутые возможности -- [Авто-раскладка](./auto-layout) — автоматическое позиционирование на основе flexbox с помощью Yoga +- [Авто-раскладка](./auto-layout) — автоматическое позиционирование на основе flexbox - [Компоненты](./components) — переиспользуемые компоненты, экземпляры и переопределения - [Переменные](./variables) — дизайн-переменные, коллекции, режимы и привязка заливок diff --git a/packages/docs/ru/user-guide/layers-and-pages.md b/packages/docs/ru/user-guide/layers-and-pages.md index b71adc1e0..066576551 100644 --- a/packages/docs/ru/user-guide/layers-and-pages.md +++ b/packages/docs/ru/user-guide/layers-and-pages.md @@ -25,7 +25,7 @@ description: Управление слоями, страницами и пане ### Переименование -Дважды кликните по имени слоя, чтобы переименовать его встроенным редактированием. Нажмите **Enter** или кликните в другом месте для подтверждения, **Escape** — для отмены. +Дважды кликните по имени слоя, чтобы переименовать его встроенным редактированием. Нажмите Enter или кликните в другом месте для подтверждения, Escape — для отмены. ### Синхронизация выделения @@ -38,7 +38,7 @@ description: Управление слоями, страницами и пане - **Переключение страницы** — кликните по вкладке страницы, чтобы сделать её активной. Холст переключается на эту страницу и восстанавливает её позицию просмотра. - **Добавить страницу** — нажмите кнопку добавления для создания новой страницы - **Удалить страницу** — удаляет текущую страницу -- **Переименовать страницу** — дважды кликните по имени страницы для встроенного редактирования. Нажатие Enter или Escape, или клик в другом месте подтверждает переименование. +- **Переименовать страницу** — дважды кликните по имени страницы для встроенного редактирования. Нажатие Enter или Escape, или клик в другом месте подтверждает переименование. У каждой страницы свой холст и состояние области просмотра. @@ -69,13 +69,13 @@ description: Управление слоями, страницами и пане ### Вкладка «ИИ» -Интерфейс ИИ-чата (также переключается через **⌘ J**), который может создавать и изменять элементы дизайна на естественном языке. Поддерживает несколько моделей ИИ через OpenRouter. +Интерфейс ИИ-чата (также переключается через ⌘J), который может создавать и изменять элементы дизайна на естественном языке. Поддерживает несколько моделей ИИ через OpenRouter. ## Сочетания клавиш | Действие | Mac | Windows / Linux | |----------|-----|-----------------| -| Переключить ИИ-чат | ⌘ J | Ctrl + J | +| Переключить ИИ-чат | ⌘J | Ctrl + J | ## Мобильная раскладка diff --git a/packages/docs/ru/user-guide/pen-tool.md b/packages/docs/ru/user-guide/pen-tool.md index 71555ab3e..31e5af2ad 100644 --- a/packages/docs/ru/user-guide/pen-tool.md +++ b/packages/docs/ru/user-guide/pen-tool.md @@ -9,7 +9,7 @@ description: Рисование векторных контуров с крив ## Активация -Нажмите **P**, чтобы активировать инструмент «Перо». +Нажмите P, чтобы активировать инструмент «Перо». ## Расстановка точек @@ -24,18 +24,18 @@ description: Рисование векторных контуров с крив ## Открытые контуры -Нажмите **Escape**, чтобы зафиксировать текущий контур как открытый. Открытые контуры отображаются только обводкой — заливка не применяется. +Нажмите Escape, чтобы зафиксировать текущий контур как открытый. Открытые контуры отображаются только обводкой — заливка не применяется. ## Векторные сети -Под капотом контуры используют модель данных векторной сети вместо простых списков точек. Векторные сети позволяют создавать более гибкую топологию (например, ветвящиеся контуры) и кодируются в бинарном формате `vectorNetworkBlob` Figma для совместимости с файлами .fig. +Контуры используют модель данных векторной сети вместо простых списков точек. Векторные сети позволяют создавать более гибкую топологию — например, ветвящиеся контуры — и полностью совместимы с форматом .fig. ## Сочетания клавиш | Действие | Mac | Windows / Linux | |----------|-----|-----------------| -| Инструмент «Перо» | P | P | -| Зафиксировать открытый контур | Escape | Escape | +| Инструмент «Перо» | P | P | +| Зафиксировать открытый контур | Escape | Escape | ## Советы diff --git a/packages/docs/ru/user-guide/selection-and-manipulation.md b/packages/docs/ru/user-guide/selection-and-manipulation.md index c238c31a9..d9d962346 100644 --- a/packages/docs/ru/user-guide/selection-and-manipulation.md +++ b/packages/docs/ru/user-guide/selection-and-manipulation.md @@ -10,37 +10,37 @@ description: Выделение, перемещение, изменение ра ## Выделение - **Клик** по узлу — выделяет его (снимает выделение со всего остального) -- **Shift + клик** — добавляет или убирает узел из текущего выделения +- Shift + клик — добавляет или убирает узел из текущего выделения - **Перетаскивание рамкой** — перетащите по пустому холсту, чтобы нарисовать прямоугольник выделения; все пересекающиеся узлы выделяются при отпускании кнопки -- **⌘ A** — выделить все узлы на текущей странице +- ⌘A — выделить все узлы на текущей странице - **Клик по пустому холсту** — снять выделение со всех ## Перемещение - **Перетаскивание** выделенного узла перемещает его (все выделенные узлы двигаются вместе) - **Клавиши-стрелки** — сдвиг выделенных узлов на 1 px -- **Shift + стрелки** — сдвиг на 10 px +- Shift + стрелки — сдвиг на 10 px ## Изменение размеров У выделенных узлов отображаются 8 маркеров изменения размера (4 угловых + 4 серединных). Перетащите любой маркер для изменения размера. -- **Shift + перетаскивание** углового маркера сохраняет пропорции +- Shift + перетаскивание углового маркера сохраняет пропорции ## Вращение Наведите курсор чуть за пределы углового маркера, чтобы увидеть курсор вращения. Перетаскивайте для поворота. -- **Shift + перетаскивание** фиксирует вращение с шагом 15° +- Shift + перетаскивание фиксирует вращение с шагом 15° ## Дублирование -- **Alt + перетаскивание** (⌥ + перетаскивание на Mac) — дублирует выделенный узел и перемещает копию -- **⌘ D** — дублировать на месте +- Alt + перетаскивание (⌥ + перетаскивание на Mac) — дублирует выделенный узел и перемещает копию +- ⌘D — дублировать на месте ## Удаление -Нажмите **Backspace** или **Delete**, чтобы удалить все выделенные узлы. +Нажмите Backspace или Delete, чтобы удалить все выделенные узлы. ## Z-порядок @@ -51,8 +51,8 @@ description: Выделение, перемещение, изменение ра ## Видимость и блокировка -- **⇧ ⌘ H** — переключить видимость. Скрытые узлы не отображаются, но остаются в панели слоёв. -- **⇧ ⌘ L** — переключить блокировку. Заблокированные узлы нельзя выделить или переместить на холсте. +- ⇧⌘H — переключить видимость. Скрытые узлы не отображаются, но остаются в панели слоёв. +- ⇧⌘L — переключить блокировку. Заблокированные узлы нельзя выделить или переместить на холсте. ## Перемещение на страницу @@ -66,16 +66,16 @@ description: Выделение, перемещение, изменение ра | Действие | Mac | Windows / Linux | |----------|-----|-----------------| -| Выделить всё | ⌘ A | Ctrl + A | -| Дублировать | ⌘ D | Ctrl + D | -| Дублировать + переместить | ⌥ + перетаскивание | Alt + перетаскивание | -| Удалить | ⌫ / Delete | Backspace / Delete | +| Выделить всё | ⌘A | Ctrl + A | +| Дублировать | ⌘D | Ctrl + D | +| Дублировать + переместить | ⌥ + перетаскивание | Alt + перетаскивание | +| Удалить | ⌫ / Delete | Backspace / Delete | | Сдвиг на 1 px | Клавиши-стрелки | Клавиши-стрелки | -| Сдвиг на 10 px | ⇧ + стрелки | Shift + стрелки | +| Сдвиг на 10 px | ⇧ + стрелки | Shift + стрелки | | На передний план | ] | ] | | На задний план | [ | [ | -| Переключить видимость | ⇧ ⌘ H | Shift + Ctrl + H | -| Переключить блокировку | ⇧ ⌘ L | Shift + Ctrl + L | +| Переключить видимость | ⇧⌘H | Shift + Ctrl + H | +| Переключить блокировку | ⇧⌘L | Shift + Ctrl + L | ## Советы diff --git a/packages/docs/ru/user-guide/text-editing.md b/packages/docs/ru/user-guide/text-editing.md index a9b098810..8b9e7a317 100644 --- a/packages/docs/ru/user-guide/text-editing.md +++ b/packages/docs/ru/user-guide/text-editing.md @@ -9,24 +9,24 @@ description: Создание и редактирование текста с р ## Создание текста -Нажмите **T**, чтобы активировать текстовый инструмент, затем кликните по холсту. Появится пустой текстовый узел с мигающим курсором — начинайте вводить текст. +Нажмите T, чтобы активировать текстовый инструмент, затем кликните по холсту. Появится пустой текстовый узел с мигающим курсором — начинайте вводить текст. ## Встроенное редактирование Дважды кликните по существующему текстовому узлу, чтобы войти в режим встроенного редактирования. Вокруг текста появляется синяя рамка, указывающая на режим редактирования. Кликните за пределами текстового узла, чтобы применить изменения и выйти из редактирования. -Текст отображается непосредственно на холсте через Paragraph API CanvasKit — видимого наложения текстового поля ввода нет. +Текст отображается непосредственно на холсте — видимого наложения текстового поля ввода нет. ## Навигация курсором | Действие | Mac | Windows / Linux | |----------|-----|-----------------| -| Переместить влево/вправо | ← / → | ← / → | -| Переместить вверх/вниз | ↑ / ↓ | ↑ / ↓ | -| Переместить по словам | ⌥ ← / ⌥ → | Ctrl + ← / Ctrl + → | -| В начало/конец строки | ⌘ ← / ⌘ → | Home / End | +| Переместить влево/вправо | ← / → | ← / → | +| Переместить вверх/вниз | ↑ / ↓ | ↑ / ↓ | +| Переместить по словам | ⌥← / ⌥→ | Ctrl + ← / Ctrl + → | +| В начало/конец строки | ⌘← / ⌘→ | Home / End | -Удерживайте **Shift** с любой клавишей перемещения, чтобы расширить выделение. +Удерживайте Shift с любой клавишей перемещения, чтобы расширить выделение. ## Выделение текста @@ -41,13 +41,13 @@ description: Создание и редактирование текста с р | Действие | Mac | Windows / Linux | |----------|-----|-----------------| -| Полужирный | ⌘ B | Ctrl + B | -| Курсив | ⌘ I | Ctrl + I | -| Подчёркивание | ⌘ U | Ctrl + U | +| Полужирный | ⌘B | Ctrl + B | +| Курсив | ⌘I | Ctrl + I | +| Подчёркивание | ⌘U | Ctrl + U | -Зачёркивание доступно через кнопку-переключатель **S** в разделе «Типографика» панели свойств (сочетания клавиш нет — ⌘ S используется для сохранения). +Зачёркивание доступно через кнопку-переключатель **S** в разделе «Типографика» панели свойств (сочетания клавиш нет — ⌘S используется для сохранения). -Форматирование хранится в виде стилевых последовательностей (стили для каждого символа). Когда вы набираете текст между жирным и обычным сегментами, новый текст наследует стиль предыдущего сегмента. +Форматирование применяется к каждому символу. Когда вы набираете текст между жирным и обычным сегментами, новый текст наследует стиль предыдущего сегмента. Кнопки-переключатели **B / I / U / S** в разделе «Типографика» панели свойств также применяют форматирование. @@ -55,11 +55,11 @@ description: Создание и редактирование текста с р | Действие | Mac | Windows / Linux | |----------|-----|-----------------| -| Удалить слово перед курсором | ⌥ ⌫ | Ctrl + Backspace | -| Удалить до начала строки | ⌘ ⌫ | — | -| Вырезать | ⌘ X | Ctrl + X | -| Копировать | ⌘ C | Ctrl + C | -| Вставить | ⌘ V | Ctrl + V | +| Удалить слово перед курсором | ⌥⌫ | Ctrl + Backspace | +| Удалить до начала строки | ⌘⌫ | — | +| Вырезать | ⌘X | Ctrl + X | +| Копировать | ⌘C | Ctrl + C | +| Вставить | ⌘V | Ctrl + V | ## Выбор шрифта @@ -72,17 +72,17 @@ description: Создание и редактирование текста с р ## Начертание шрифта -Измените начертание шрифта в разделе «Типографика» панели свойств. Доступные начертания зависят от выбранного семейства шрифта (например, Regular, Medium, Bold, Black). Начертание применяется к узлу и отображается через текстовые стили CanvasKit. +Измените начертание шрифта в разделе «Типографика» панели свойств. Доступные начертания зависят от выбранного семейства шрифта (например, Regular, Medium, Bold, Black). ## Источники шрифтов - **Шрифт по умолчанию** — Inter загружается автоматически -- **Настольное приложение (Tauri)** — системные шрифты перечисляются через Rust-бэкенд font-kit и предзагружаются при запуске -- **Браузер** — системные шрифты доступны через Local Font Access API (Chrome/Edge) +- **Настольное приложение** — системные шрифты обнаруживаются и предзагружаются при запуске +- **Браузер** — системные шрифты доступны в поддерживаемых браузерах (Chrome/Edge) ## Советы - Список шрифтов предзагружается при запуске, поэтому панель выбора открывается без задержки. -- Ввод через IME (китайский, японский, корейский) полностью поддерживается через скрытое текстовое поле. -- Расширенное форматирование сохраняется при импорте/экспорте .fig — стилевые последовательности соответствуют `characterStyleIDs` Figma. +- Ввод через IME (китайский, японский, корейский) полностью поддерживается. +- Расширенное форматирование сохраняется при импорте/экспорте .fig. - См. [Компоненты](./components) для информации о текстовых переопределениях в экземплярах компонентов. diff --git a/packages/docs/user-guide/auto-layout.md b/packages/docs/user-guide/auto-layout.md index d7c153115..f7f7267fc 100644 --- a/packages/docs/user-guide/auto-layout.md +++ b/packages/docs/user-guide/auto-layout.md @@ -5,11 +5,11 @@ description: Flexbox-based auto layout in OpenPencil — direction, gap, padding # Auto Layout -Auto layout uses Yoga (flexbox engine) to position children automatically within a frame. It handles direction, spacing, alignment, and responsive sizing. +Auto layout positions children automatically within a frame using flexbox rules. It handles direction, spacing, alignment, and responsive sizing. ## Enabling Auto Layout -- Select a frame and press **⇧ A** (Shift + A) to toggle auto layout on or off -- Select loose nodes (without a parent frame) and press **⇧ A** to wrap them in a new auto-layout frame +- Select a frame and press ⇧A (Shift + A) to toggle auto layout on or off +- Select loose nodes (without a parent frame) and press ⇧A to wrap them in a new auto-layout frame When wrapping a selection, nodes are sorted by visual position: left-to-right for horizontal layout, top-to-bottom for vertical. @@ -71,7 +71,7 @@ When an auto-layout frame is selected, the Layout section in the properties pane | Action | Mac | Windows / Linux | |--------|-----|-----------------| -| Toggle auto layout | ⇧ A | Shift + A | +| Toggle auto layout | ⇧A | Shift + A | ## Tips diff --git a/packages/docs/user-guide/canvas-navigation.md b/packages/docs/user-guide/canvas-navigation.md index 8b5e37061..61e96d291 100644 --- a/packages/docs/user-guide/canvas-navigation.md +++ b/packages/docs/user-guide/canvas-navigation.md @@ -10,19 +10,19 @@ The canvas is your infinite workspace. You can pan and zoom freely to navigate y Move the visible area of the canvas without affecting any objects. -- **Space + drag** — hold Space and drag anywhere on the canvas +- Space + drag — hold Space and drag anywhere on the canvas - **Middle mouse drag** — press and drag the middle mouse button - **Two-finger trackpad** — swipe with two fingers on a trackpad ## Hand Tool -Press **H** to activate the hand tool for continuous panning. Any drag on the canvas pans the viewport without needing to hold Space. Switch to another tool (e.g., **V** for Select) to deactivate. +Press H to activate the hand tool for continuous panning. Any drag on the canvas pans the viewport without needing to hold Space. Switch to another tool (e.g., **V** for Select) to deactivate. ## Zooming Zoom in and out centered on your cursor position. -- **Ctrl + scroll** (or **⌘ + scroll** on Mac) — scroll up to zoom in, scroll down to zoom out +- Ctrl + scroll (or ⌘ + scroll on Mac) — scroll up to zoom in, scroll down to zoom out - **Pinch gesture** — pinch on a trackpad to zoom in/out - **Keyboard shortcuts** — see table below @@ -32,11 +32,11 @@ Pinch-to-zoom on UI panels (layers, properties) is prevented so it doesn't accid | Action | Mac | Windows / Linux | |--------|-----|-----------------| -| Pan | Space + drag | Space + drag | -| Hand tool | H | H | -| Zoom in | ⌘ + | Ctrl + + | -| Zoom out | ⌘ - | Ctrl + - | -| Zoom to 100% | ⌘ 0 | Ctrl + 0 | +| Pan | Space + drag | Space + drag | +| Hand tool | H | H | +| Zoom in | ⌘+ | Ctrl + + | +| Zoom out | ⌘− | Ctrl + − | +| Zoom to 100% | ⌘0 | Ctrl + 0 | ## Tips diff --git a/packages/docs/user-guide/components.md b/packages/docs/user-guide/components.md index bf5cf568b..594a709a9 100644 --- a/packages/docs/user-guide/components.md +++ b/packages/docs/user-guide/components.md @@ -8,7 +8,7 @@ description: Creating reusable components, instances, component sets, overrides, Components are reusable design elements. Edit the main component and all its instances update automatically. ## Creating a Component -Select a frame or group and press **⌥ ⌘ K** (Ctrl + Alt + K). The node converts to a COMPONENT type in place. +Select a frame or group and press ⌥⌘K (Ctrl + Alt + K). The selection becomes a reusable component. If you select multiple nodes, they're wrapped in a new component positioned at their bounding box. @@ -16,7 +16,7 @@ Components display a purple label with a diamond icon above them. ## Component Sets -Select two or more components and press **⇧ ⌘ K** (Shift + Ctrl + K) to combine them into a component set — a container with a dashed purple border and 40 px padding around its children. Component sets are useful for grouping variants (e.g., button states). +Select two or more components and press ⇧⌘K (Shift + Ctrl + K) to combine them into a component set — a container with a dashed purple border and 40 px padding around its children. Component sets are useful for grouping variants (e.g., button states). ## Creating Instances @@ -26,7 +26,7 @@ Instance creation is available only through the context menu — there's no tool ## Detaching an Instance -Select an instance and press **⌥ ⌘ B** (Ctrl + Alt + B) to detach it. The instance becomes a regular frame with no link to the original component. All overrides are baked in. +Select an instance and press ⌥⌘B (Ctrl + Alt + B) to detach it. The instance becomes a regular frame with no link to the original component. All overrides are baked in. ## Go to Main Component @@ -50,9 +50,7 @@ Instances can override specific properties without breaking the sync link. When ### Overridable Properties -Child-level overrides support: name, text, fontSize, fontWeight, fontFamily, plus all visual and layout properties (fills, strokes, effects, opacity, corner radii, size). - -Override keys use the format `childId:propertyName` in the instance's overrides record. +Child-level overrides support: name, text, font size, font weight, font family, plus all visual and layout properties (fills, strokes, effects, opacity, corner radii, size). ### New Children @@ -66,17 +64,17 @@ Components and instances are opaque containers — clicking on a child selects t | Element | Appearance | |---------|------------| -| Component label | Purple (#9747ff) with diamond icon, always visible | -| Instance label | Purple (#9747ff) with diamond icon, always visible | -| Component set border | Dashed purple (6 px dash, 4 px gap, 1.5 px width) | +| Component label | Purple with diamond icon, always visible | +| Instance label | Purple with diamond icon, always visible | +| Component set border | Dashed purple outline | ## Keyboard Shortcuts | Action | Mac | Windows / Linux | |--------|-----|-----------------| -| Create component | ⌥ ⌘ K | Ctrl + Alt + K | -| Create component set | ⇧ ⌘ K | Shift + Ctrl + K | -| Detach instance | ⌥ ⌘ B | Ctrl + Alt + B | +| Create component | ⌥⌘K | Ctrl + Alt + K | +| Create component set | ⇧⌘K | Shift + Ctrl + K | +| Detach instance | ⌥⌘B | Ctrl + Alt + B | ## Tips diff --git a/packages/docs/user-guide/context-menu.md b/packages/docs/user-guide/context-menu.md index 78e5aa88a..5960a0607 100644 --- a/packages/docs/user-guide/context-menu.md +++ b/packages/docs/user-guide/context-menu.md @@ -14,7 +14,7 @@ The **Copy/Paste as** submenu offers additional clipboard formats for the select |--------|----------------|----------------------| | Copy as text | — | — | | Copy as SVG | — | — | -| Copy as PNG | ⇧ ⌘ C | Shift + Ctrl + C | +| Copy as PNG | ⇧⌘C | Shift + Ctrl + C | | Copy as JSX | — | — | - **Copy as text** — copies visible text content from the selection @@ -26,11 +26,11 @@ The **Copy/Paste as** submenu offers additional clipboard formats for the select | Action | Shortcut (Mac) | Shortcut (Win/Linux) | |--------|----------------|----------------------| -| Copy | ⌘ C | Ctrl + C | -| Cut | ⌘ X | Ctrl + X | -| Paste here | ⌘ V | Ctrl + V | -| Duplicate | ⌘ D | Ctrl + D | -| Delete | ⌫ | Backspace / Delete | +| Copy | ⌘C | Ctrl + C | +| Cut | ⌘X | Ctrl + X | +| Paste here | ⌘V | Ctrl + V | +| Duplicate | ⌘D | Ctrl + D | +| Delete | ⌫ | Backspace / Delete | Clipboard actions are disabled when nothing is selected (except Paste, which is available when the clipboard has content). @@ -47,9 +47,9 @@ Moves the selected node to the top or bottom of its parent's child list. | Action | Shortcut (Mac) | Shortcut (Win/Linux) | |--------|----------------|----------------------| -| Group | ⌘ G | Ctrl + G | -| Ungroup | ⇧ ⌘ G | Shift + Ctrl + G | -| Add auto layout | ⇧ A | Shift + A | +| Group | ⌘G | Ctrl + G | +| Ungroup | ⇧⌘G | Shift + Ctrl + G | +| Add auto layout | ⇧A | Shift + A | - **Group** requires 2 or more selected nodes - **Ungroup** appears when a group is selected — children are reparented to the group's parent @@ -61,11 +61,11 @@ Component actions are displayed in purple to match the component color theme. | Action | Shortcut (Mac) | Shortcut (Win/Linux) | Available on | |--------|----------------|----------------------|--------------| -| Create component | ⌥ ⌘ K | Ctrl + Alt + K | Frames, groups, multi-selection | -| Create component set | ⇧ ⌘ K | Shift + Ctrl + K | 2+ selected components | +| Create component | ⌥⌘K | Ctrl + Alt + K | Frames, groups, multi-selection | +| Create component set | ⇧⌘K | Shift + Ctrl + K | 2+ selected components | | Create instance | — | — | Components (no shortcut) | | Go to main component | — | — | Instances | -| Detach instance | ⌥ ⌘ B | Ctrl + Alt + B | Instances | +| Detach instance | ⌥⌘B | Ctrl + Alt + B | Instances | See [Components](./components) for details on the component workflow. @@ -73,8 +73,8 @@ See [Components](./components) for details on the component workflow. | Action | Shortcut (Mac) | Shortcut (Win/Linux) | |--------|----------------|----------------------| -| Hide / Show | ⇧ ⌘ H | Shift + Ctrl + H | -| Lock / Unlock | ⇧ ⌘ L | Shift + Ctrl + L | +| Hide / Show | ⇧⌘H | Shift + Ctrl + H | +| Lock / Unlock | ⇧⌘L | Shift + Ctrl + L | The label toggles based on the node's current state (e.g., "Hide" for a visible node, "Show" for a hidden one). diff --git a/packages/docs/user-guide/drawing-shapes.md b/packages/docs/user-guide/drawing-shapes.md index e88d35445..4abf1663d 100644 --- a/packages/docs/user-guide/drawing-shapes.md +++ b/packages/docs/user-guide/drawing-shapes.md @@ -10,11 +10,11 @@ The bottom toolbar provides tools for creating shapes, frames, and sections. Sel | Tool | Shortcut | Description | |------|----------|-------------| -| Rectangle | R | Draws a rectangle | -| Ellipse | O | Draws an ellipse | -| Line | L | Draws a line | -| Frame | F | Draws a frame (container for other nodes) | -| Section | S | Draws a section (auto-adopts overlapping siblings) | +| Rectangle | R | Draws a rectangle | +| Ellipse | O | Draws an ellipse | +| Line | L | Draws a line | +| Frame | F | Draws a frame (container for other nodes) | +| Section | S | Draws a section (auto-adopts overlapping siblings) | ## Shapes Flyout @@ -27,7 +27,7 @@ Polygon and Star have no keyboard shortcut — access them from the shapes flyou ## Constrained Drawing -Hold **Shift** while dragging to constrain the shape: +Hold Shift while dragging to constrain the shape: - Rectangle → square (equal width and height) - Ellipse → circle @@ -82,12 +82,12 @@ Click **+** to add an effect. Each effect row is collapsible with inline control | Action | Mac | Windows / Linux | |--------|-----|-----------------| -| Rectangle tool | R | R | -| Ellipse tool | O | O | -| Line tool | L | L | -| Frame tool | F | F | -| Section tool | S | S | -| Constrain to square/circle | Shift + drag | Shift + drag | +| Rectangle tool | R | R | +| Ellipse tool | O | O | +| Line tool | L | L | +| Frame tool | F | F | +| Section tool | S | S | +| Constrain to square/circle | Shift + drag | Shift + drag | ## Tips diff --git a/packages/docs/user-guide/exporting.md b/packages/docs/user-guide/exporting.md index 47120df79..7d35a83de 100644 --- a/packages/docs/user-guide/exporting.md +++ b/packages/docs/user-guide/exporting.md @@ -21,8 +21,8 @@ You can add multiple export settings to export the same node at different scales | Method | Mac | Windows / Linux | |--------|-----|-----------------| -| Keyboard shortcut | ⇧ ⌘ E | Shift + Ctrl + E | -| Context menu | Right-click → Export… | Right-click → Export… | +| Keyboard shortcut | ⇧⌘E | Shift + Ctrl + E | +| Context menu | Right-click → Export… | Right-click → Export… | | Properties panel | Click "Export" button | Click "Export" button | The exported file is saved via a native dialog (desktop) or browser download. @@ -35,7 +35,7 @@ In addition to file export, you can copy the selection to the clipboard in multi |--------|----------------|----------------------| | Copy as text | — | — | | Copy as SVG | — | — | -| Copy as PNG | ⇧ ⌘ C | Shift + Ctrl + C | +| Copy as PNG | ⇧⌘C | Shift + Ctrl + C | | Copy as JSX | — | — | - **Copy as text** — copies visible text content from the selection @@ -51,7 +51,7 @@ OpenPencil uses the .fig format for full documents — the same binary format as | Action | Mac | Windows / Linux | |--------|-----|-----------------| -| Open file | ⌘ O | Ctrl + O | +| Open file | ⌘O | Ctrl + O | A file picker dialog opens, filtered for .fig files. On the desktop app, this uses the native OS dialog. @@ -59,13 +59,13 @@ A file picker dialog opens, filtered for .fig files. On the desktop app, this us | Action | Mac | Windows / Linux | |--------|-----|-----------------| -| Save | ⌘ S | Ctrl + S | -| Save As | ⇧ ⌘ S | Shift + Ctrl + S | +| Save | ⌘S | Ctrl + S | +| Save As | ⇧⌘S | Shift + Ctrl + S | - **Save** overwrites the currently open file without a dialog - **Save As** opens a save dialog to choose a new location -The export pipeline encodes the scene graph to Kiwi binary format, compresses it, and writes a ZIP archive with the payload and a thumbnail image. +Saved files are compressed and include a thumbnail image for preview in file browsers. ### Round-trip Compatibility @@ -75,11 +75,11 @@ Files exported from OpenPencil can be opened in Figma, and vice versa. The .fig | Action | Mac | Windows / Linux | |--------|-----|-----------------| -| Export selection | ⇧ ⌘ E | Shift + Ctrl + E | -| Copy as PNG | ⇧ ⌘ C | Shift + Ctrl + C | -| Open file | ⌘ O | Ctrl + O | -| Save | ⌘ S | Ctrl + S | -| Save As | ⇧ ⌘ S | Shift + Ctrl + S | +| Export selection | ⇧⌘E | Shift + Ctrl + E | +| Copy as PNG | ⇧⌘C | Shift + Ctrl + C | +| Open file | ⌘O | Ctrl + O | +| Save | ⌘S | Ctrl + S | +| Save As | ⇧⌘S | Shift + Ctrl + S | ## Tips diff --git a/packages/docs/user-guide/index.md b/packages/docs/user-guide/index.md index 07b78f101..7bfae94d5 100644 --- a/packages/docs/user-guide/index.md +++ b/packages/docs/user-guide/index.md @@ -9,7 +9,7 @@ description: Learn how to use OpenPencil — canvas navigation, drawing, text, c OpenPencil is an open-source, Figma-compatible design editor — fully local, AI-native, and programmable. This guide covers everything you need to know to use the editor effectively. ::: tip Cross-platform shortcuts -Throughout this guide, keyboard shortcuts use Mac notation: **⌘** = Command (Ctrl on Windows/Linux), **⌥** = Option (Alt), **⇧** = Shift. +Throughout this guide, keyboard shortcuts use Mac notation: ⌘ = Command (Ctrl on Windows/Linux), ⌥ = Option (Alt), ⇧ = Shift. ::: ## Getting Around @@ -31,6 +31,6 @@ Throughout this guide, keyboard shortcuts use Mac notation: **⌘** = Command (C ## Advanced Features -- [Auto Layout](./auto-layout) — flexbox-based automatic positioning with Yoga +- [Auto Layout](./auto-layout) — flexbox-based automatic positioning - [Components](./components) — reusable components, instances, and overrides - [Variables](./variables) — design variables, collections, modes, and fill bindings diff --git a/packages/docs/user-guide/layers-and-pages.md b/packages/docs/user-guide/layers-and-pages.md index 76619f2ec..a9a510854 100644 --- a/packages/docs/user-guide/layers-and-pages.md +++ b/packages/docs/user-guide/layers-and-pages.md @@ -16,7 +16,7 @@ Nodes are shown in a collapsible tree. Click the chevron next to a frame, group, ### Drag Reorder -Drag layers to reorder them. This changes the node's z-order in the scene graph — nodes higher in the list render on top. +Drag layers to reorder them. Nodes higher in the list render on top. ### Visibility Toggle @@ -24,7 +24,7 @@ Click the eye icon next to any layer to hide or show it on the canvas. Hidden no ### Rename -Double-click a layer name to rename it inline. Press **Enter** or click away to commit, **Escape** to cancel. +Double-click a layer name to rename it inline. Press Enter or click away to commit, Escape to cancel. ### Selection Sync @@ -37,7 +37,7 @@ The pages panel shows all pages in the document. - **Switch page** — click a page tab to make it active. The canvas switches to that page and restores its viewport position. - **Add page** — click the add button to create a new page - **Delete page** — remove the current page -- **Rename page** — double-click the page name for inline editing. Pressing Enter or Escape, or clicking away, commits the rename. +- **Rename page** — double-click the page name for inline editing. Pressing Enter or Escape, or clicking away, commits the rename. Each page has its own canvas and viewport state. @@ -68,13 +68,13 @@ Displays the selected node as code with syntax highlighting, line numbers, and a ### AI Tab -An AI chat interface (also toggled with **⌘ J**) that can create and modify design elements via natural language. Supports multiple AI models through OpenRouter. +An AI chat interface (also toggled with ⌘J) that can create and modify design elements via natural language. Supports multiple AI models through OpenRouter. ## Keyboard Shortcuts | Action | Mac | Windows / Linux | |--------|-----|-----------------| -| Toggle AI chat | ⌘ J | Ctrl + J | +| Toggle AI chat | ⌘J | Ctrl + J | ## Mobile Layout diff --git a/packages/docs/user-guide/pen-tool.md b/packages/docs/user-guide/pen-tool.md index cc6f9adda..4ede68534 100644 --- a/packages/docs/user-guide/pen-tool.md +++ b/packages/docs/user-guide/pen-tool.md @@ -8,7 +8,7 @@ description: Drawing vector paths with bezier curves using the pen tool in OpenP The pen tool creates vector paths using a vector network data model, compatible with Figma's .fig format. ## Activating -Press **P** to activate the pen tool. +Press P to activate the pen tool. ## Placing Points @@ -23,18 +23,18 @@ Click on the **first point** of the path to close it into a loop. Closed paths c ## Open Paths -Press **Escape** to commit the current path as an open path. Open paths render as strokes only — they're not filled. +Press Escape to commit the current path as an open path. Open paths render as strokes only — they're not filled. ## Vector Networks -Under the hood, paths use the vector network data model instead of simple point lists. Vector networks allow more flexible topology (e.g., branching paths) and are encoded in Figma's `vectorNetworkBlob` binary format for .fig file compatibility. +Paths in OpenPencil use vector networks — a more flexible model than simple point lists that supports branching paths and complex topology. This is the same model Figma uses, so paths round-trip perfectly in .fig files. ## Keyboard Shortcuts | Action | Mac | Windows / Linux | |--------|-----|-----------------| -| Pen tool | P | P | -| Commit open path | Escape | Escape | +| Pen tool | P | P | +| Commit open path | Escape | Escape | ## Tips diff --git a/packages/docs/user-guide/selection-and-manipulation.md b/packages/docs/user-guide/selection-and-manipulation.md index 4081c0ea8..61e2f4010 100644 --- a/packages/docs/user-guide/selection-and-manipulation.md +++ b/packages/docs/user-guide/selection-and-manipulation.md @@ -9,37 +9,37 @@ Select objects to move, resize, rotate, duplicate, and organize them on the canv ## Selecting - **Click** a node to select it (deselects everything else) -- **Shift + click** to add or remove a node from the current selection +- Shift + click to add or remove a node from the current selection - **Marquee drag** — drag on empty canvas to draw a selection rectangle; all intersecting nodes are selected on release -- **⌘ A** — select all nodes on the current page +- ⌘A — select all nodes on the current page - **Click empty canvas** — deselect all ## Moving - **Drag** a selected node to move it (all selected nodes move together) - **Arrow keys** — nudge selected nodes by 1 px -- **Shift + arrow keys** — nudge by 10 px +- Shift + arrow keys — nudge by 10 px ## Resizing Selected nodes show 8 resize handles (4 corners + 4 edge midpoints). Drag any handle to resize. -- **Shift + drag** a corner handle to constrain proportions +- Shift + drag a corner handle to constrain proportions ## Rotating Hover just outside a corner handle to see the rotation cursor. Drag to rotate. -- **Shift + drag** snaps rotation to 15° increments +- Shift + drag snaps rotation to 15° increments ## Duplicating -- **Alt + drag** (⌥ + drag on Mac) — duplicate the selected node and move the copy -- **⌘ D** — duplicate in place +- Alt + drag (⌥ + drag on Mac) — duplicate the selected node and move the copy +- ⌘D — duplicate in place ## Deleting -Press **Backspace** or **Delete** to remove all selected nodes. +Press Backspace or Delete to remove all selected nodes. ## Z-Order @@ -50,8 +50,8 @@ Change the stacking order of nodes within their parent: ## Visibility & Lock -- **⇧ ⌘ H** — toggle visibility. Hidden nodes don't render but stay in the layers panel. -- **⇧ ⌘ L** — toggle lock. Locked nodes can't be selected or moved on canvas. +- ⇧⌘H — toggle visibility. Hidden nodes don't render but stay in the layers panel. +- ⇧⌘L — toggle lock. Locked nodes can't be selected or moved on canvas. ## Move to Page @@ -65,16 +65,16 @@ Drawing a section on the canvas automatically adopts overlapping sibling nodes a | Action | Mac | Windows / Linux | |--------|-----|-----------------| -| Select all | ⌘ A | Ctrl + A | -| Duplicate | ⌘ D | Ctrl + D | -| Duplicate + move | ⌥ + drag | Alt + drag | -| Delete | ⌫ / Delete | Backspace / Delete | -| Nudge 1 px | Arrow keys | Arrow keys | -| Nudge 10 px | ⇧ + Arrow keys | Shift + Arrow keys | +| Select all | ⌘A | Ctrl + A | +| Duplicate | ⌘D | Ctrl + D | +| Duplicate + move | ⌥ + drag | Alt + drag | +| Delete | ⌫ / Delete | Backspace / Delete | +| Nudge 1 px | Arrow keys | Arrow keys | +| Nudge 10 px | ⇧ + Arrow keys | Shift + Arrow keys | | Bring to front | ] | ] | | Send to back | [ | [ | -| Toggle visibility | ⇧ ⌘ H | Shift + Ctrl + H | -| Toggle lock | ⇧ ⌘ L | Shift + Ctrl + L | +| Toggle visibility | ⇧⌘H | Shift + Ctrl + H | +| Toggle lock | ⇧⌘L | Shift + Ctrl + L | ## Tips diff --git a/packages/docs/user-guide/text-editing.md b/packages/docs/user-guide/text-editing.md index 048aa6916..aab0e2099 100644 --- a/packages/docs/user-guide/text-editing.md +++ b/packages/docs/user-guide/text-editing.md @@ -8,24 +8,24 @@ description: Creating and editing text with rich formatting, fonts, and inline e Create text nodes and edit them directly on the canvas with full rich text support. ## Creating Text -Press **T** to activate the text tool, then click on the canvas. An empty text node appears with a blinking cursor — start typing immediately. +Press T to activate the text tool, then click on the canvas. An empty text node appears with a blinking cursor — start typing immediately. ## Inline Editing Double-click any existing text node to enter inline editing mode. A blue outline appears around the text to indicate edit mode. Click outside the text node to commit and exit editing. -Text is rendered directly on the canvas using CanvasKit's Paragraph API — there's no visible text input overlay. +Text is rendered directly on the canvas — there's no separate text input overlay. ## Cursor Navigation | Action | Mac | Windows / Linux | |--------|-----|-----------------| -| Move left/right | ← / → | ← / → | -| Move up/down | ↑ / ↓ | ↑ / ↓ | -| Move by word | ⌥ ← / ⌥ → | Ctrl + ← / Ctrl + → | -| Move to line start/end | ⌘ ← / ⌘ → | Home / End | +| Move left/right | ← / → | ← / → | +| Move up/down | ↑ / ↓ | ↑ / ↓ | +| Move by word | ⌥← / ⌥→ | Ctrl + ← / Ctrl + → | +| Move to line start/end | ⌘← / ⌘→ | Home / End | -Hold **Shift** with any movement key to extend the selection. +Hold Shift with any movement key to extend the selection. ## Text Selection @@ -40,13 +40,13 @@ Apply formatting to selected text, or toggle the style for the entire node when | Action | Mac | Windows / Linux | |--------|-----|-----------------| -| Bold | ⌘ B | Ctrl + B | -| Italic | ⌘ I | Ctrl + I | -| Underline | ⌘ U | Ctrl + U | +| Bold | ⌘B | Ctrl + B | +| Italic | ⌘I | Ctrl + I | +| Underline | ⌘U | Ctrl + U | -Strikethrough is available via the **S** toggle button in the Typography section of the properties panel (no keyboard shortcut — ⌘ S is used for Save). +Strikethrough is available via the **S** toggle button in the Typography section of the properties panel (no keyboard shortcut — ⌘S is used for Save). -Formatting is stored as style runs (per-character styles). When you type between a bold and regular segment, the new text inherits the style of the preceding segment. +Formatting is applied per character. When you type between a bold and regular segment, the new text inherits the style of the preceding segment. The **B / I / U / S** toggle buttons in the Typography section of the properties panel also apply formatting. @@ -54,11 +54,11 @@ The **B / I / U / S** toggle buttons in the Typography section of the properties | Action | Mac | Windows / Linux | |--------|-----|-----------------| -| Delete word before cursor | ⌥ ⌫ | Ctrl + Backspace | -| Delete to line start | ⌘ ⌫ | — | -| Cut | ⌘ X | Ctrl + X | -| Copy | ⌘ C | Ctrl + C | -| Paste | ⌘ V | Ctrl + V | +| Delete word before cursor | ⌥⌫ | Ctrl + Backspace | +| Delete to line start | ⌘⌫ | — | +| Cut | ⌘X | Ctrl + X | +| Copy | ⌘C | Ctrl + C | +| Paste | ⌘V | Ctrl + V | ## Font Picker @@ -71,17 +71,17 @@ Open the font picker in the Typography section of the properties panel to change ## Font Weight -Change the font weight in the Typography section of the properties panel. Available weights depend on the selected font family (e.g., Regular, Medium, Bold, Black). The weight is applied per-node and renders via CanvasKit text styles. +Change the font weight in the Typography section of the properties panel. Available weights depend on the selected font family (e.g., Regular, Medium, Bold, Black). ## Font Sources - **Default font** — Inter is loaded automatically -- **Desktop (Tauri)** — system fonts are enumerated via the font-kit Rust backend and preloaded on startup -- **Browser** — system fonts are available via the Local Font Access API (Chrome/Edge) +- **Desktop app** — all system fonts are available +- **Browser** — system fonts are available in Chrome and Edge ## Tips - The font list is preloaded at startup so the picker opens without delay. -- IME input (Chinese, Japanese, Korean) is fully supported through the phantom textarea. -- Rich text formatting survives .fig import/export — style runs map to Figma's `characterStyleIDs`. +- IME input (Chinese, Japanese, Korean) is fully supported. +- Rich text formatting is preserved when opening and saving .fig files. - See [Components](./components) for how text overrides work in component instances.