From e67dd3fbd9510b307c1fe6c554c38cda33e0272c Mon Sep 17 00:00:00 2001 From: Danila Poyarkov Date: Sun, 8 Mar 2026 11:04:26 +0300 Subject: [PATCH] =?UTF-8?q?Rewrite=20docs:=20landing=20page,=20features,?= =?UTF-8?q?=20architecture=20=E2=80=94=20all=206=20locales?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Landing page: reorder features (Figma-compatible first), add collaboration card, fix app size - Features: cut implementation details, group into clear sections, add MCP/CLI/Homebrew - Architecture: replace ASCII diagram with mermaid, add RPC bridge, update tool counts - Remove ~500 lines of internal implementation prose from user-facing docs --- packages/docs/de/guide/architecture.md | 103 ++++--- packages/docs/de/guide/features.md | 290 ++++++------------ packages/docs/de/index.md | 35 ++- packages/docs/es/guide/architecture.md | 103 ++++--- packages/docs/es/guide/features.md | 257 ++++++---------- packages/docs/es/index.md | 35 ++- packages/docs/fr/guide/architecture.md | 107 ++++--- packages/docs/fr/guide/features.md | 245 ++++++--------- packages/docs/fr/index.md | 35 ++- packages/docs/guide/architecture.md | 107 +++---- packages/docs/guide/features.md | 407 ++++++------------------- packages/docs/index.md | 33 +- packages/docs/it/guide/architecture.md | 131 ++++---- packages/docs/it/guide/features.md | 247 ++++++--------- packages/docs/it/index.md | 37 +-- packages/docs/pl/guide/architecture.md | 103 ++++--- packages/docs/pl/guide/features.md | 261 ++++++---------- packages/docs/pl/index.md | 35 ++- 18 files changed, 1037 insertions(+), 1534 deletions(-) diff --git a/packages/docs/de/guide/architecture.md b/packages/docs/de/guide/architecture.md index ed4e0e1ab..b0ed27a9b 100644 --- a/packages/docs/de/guide/architecture.md +++ b/packages/docs/de/guide/architecture.md @@ -2,42 +2,33 @@ ## Systemübersicht -``` -┌──────────────────────────────────────────────────────────────────┐ -│ Tauri v2 Shell │ -│ │ -│ ┌────────────────────────────────────────────────────────────┐ │ -│ │ Editor (Web) │ │ -│ │ │ │ -│ │ Vue 3 UI Skia CanvasKit (WASM, 7MB) │ │ -│ │ - Werkzeugleiste - Vektordarstellung │ │ -│ │ - Panels - Textgestaltung │ │ -│ │ - Eigenschaften - Bildverarbeitung │ │ -│ │ - Ebenen - Effekte (Unschärfe, Schatten)│ │ -│ │ - Farbauswahl - Export (PNG, SVG, PDF) │ │ -│ │ │ │ -│ │ ┌──────────────────────────────────────────────────────┐ │ │ -│ │ │ Core Engine (TS) │ │ │ -│ │ │ SceneGraph ─── Layout (Yoga) ─── Selection │ │ │ -│ │ │ │ │ │ │ │ -│ │ │ Undo/Redo ─── Constraints ─── Hit Testing │ │ │ -│ │ └──────────────────────────────────────────────────────┘ │ │ -│ │ │ │ -│ │ ┌──────────────────────────────────────────────────────┐ │ │ -│ │ │ Dateiformatschicht │ │ │ -│ │ │ .fig Import/Export ── Kiwi-Codec ── .svg (geplant) │ │ │ -│ │ └──────────────────────────────────────────────────────┘ │ │ -│ └────────────────────────────────────────────────────────────┘ │ -│ │ -│ MCP-Server (75+ Tools, stdio+HTTP) P2P-Kollab. (Trystero + Yjs) │ -└──────────────────────────────────────────────────────────────────┘ +```mermaid +graph TB + subgraph Tauri["Tauri v2 Shell"] + subgraph Editor["Editor (Web)"] + UI["Vue 3 UI
Toolbar · Panels · Properties
Layers · Color Picker"] + Skia["Skia CanvasKit (WASM, 7MB)
Vector rendering · Text shaping
Effects · Export"] + subgraph Core["Core Engine (TS)"] + SG[SceneGraph] --- Layout[Layout - Yoga] + SG --- Selection + Undo[Undo/Redo] --- Constraints + Constraints --- HitTest[Hit Testing] + end + subgraph FileFormat["File Format Layer"] + FigIO[".fig import/export"] --- Kiwi[Kiwi codec] + Kiwi --- SVG[SVG export] + end + end + MCP["MCP Server (90 tools, stdio+HTTP)"] + Collab["P2P Collab (Trystero + Yjs)"] + end ``` ## Editor-Layout Die Oberfläche folgt Figmas UI3-Layout — Werkzeugleiste unten, Navigation links, Eigenschaften rechts: -- **Navigationspanel (links)** — Ebenenbaum, Seitenpanel, Asset-Bibliothek (geplant) +- **Navigationspanel (links)** — Ebenenbaum, Seitenpanel - **Canvas (Mitte)** — Unendlicher Canvas mit CanvasKit-Rendering, Zoom/Pan - **Eigenschaftspanel (rechts)** — Kontextsensitive Abschnitte: Darstellung, Füllung, Kontur, Typografie, Layout, Position - **Werkzeugleiste (unten)** — Werkzeugauswahl: Auswahl, Frame, Sektion, Rechteck, Ellipse, Linie, Text, Stift, Hand @@ -46,13 +37,13 @@ Die Oberfläche folgt Figmas UI3-Layout — Werkzeugleiste unten, Navigation lin ### Rendering (CanvasKit WASM) -Dieselbe Rendering-Engine wie Figma. CanvasKit bietet GPU-beschleunigte 2D-Zeichnung mit Vektorformen, Textgestaltung, Effekten und Export. +Dieselbe Rendering-Engine wie Figma. CanvasKit bietet GPU-beschleunigte 2D-Zeichnung mit Vektorformen, Textgestaltung via Paragraph API, Effekten (Schatten, Unschärfe, Mischmodi) und Export (PNG, SVG). Das 7 MB große WASM-Binary wird beim Start geladen und erstellt eine GPU-Oberfläche auf dem HTML-Canvas. -Das 7 MB große WASM-Binary wird beim Start geladen und erstellt eine GPU-Oberfläche auf dem HTML-Canvas. +Der Renderer ist in fokussierte Module in `packages/core/src/renderer/` aufgeteilt: Szenentraversierung, Overlays, Füllungen, Konturen, Formen, Effekte, Lineale, Labels und Remote-Cursor. ### Szenengraph -Flache `Map` mit GUID-Strings als Schlüssel. Baumstruktur über `parentIndex`-Referenzen. Bietet O(1)-Lookup, effiziente Traversierung und Hit-Testing. +Flache `Map` mit GUID-Strings als Schlüssel. Baumstruktur über `parentIndex`-Referenzen. Bietet O(1)-Lookup, effiziente Traversierung, Hit-Testing und rechteckige Bereichsabfragen für Marquee-Selektion. Siehe [Szenengraph-Referenz](/reference/scene-graph) für Interna. @@ -71,7 +62,19 @@ Metas Yoga bietet CSS-Flexbox-Layout-Berechnung. Ein dünner Adapter mappt Figma ### Dateiformat (Kiwi-Binär) -Verwendet Figmas bewährten Kiwi-Binär-Codec mit 194 Nachrichten-/Enum-/Strukturdefinitionen. Siehe [Dateiformat-Referenz](/reference/file-format) für Details. +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. + +### KI & Werkzeuge + +Werkzeuge werden einmal in `packages/core/src/tools/` definiert, aufgeteilt nach Domäne: read, create, modify, structure, variables, vector, analyze. Jedes Werkzeug hat typisierte Parameter und eine `execute(figma, args)`-Funktion. Adapter konvertieren sie für: + +- **KI-Chat** — valibot-Schemas, verbunden mit OpenRouter +- **MCP-Server** — zod-Schemas, stdio + HTTP-Transporte +- **CLI** — verfügbar über den `eval`-Befehl + +87 Core-Werkzeuge + 3 MCP-Dateiverwaltungswerkzeuge = 90 insgesamt. ### Rückgängig/Wiederherstellen @@ -79,12 +82,34 @@ Inverse-Command-Muster. Vor jeder Änderung werden betroffene Felder als Snapsho ### Zwischenablage -Figma-kompatible bidirektionale Zwischenablage. Kodiert/dekodiert Kiwi-Binär (gleiches Format wie .fig-Dateien) über native Browser-Kopier/Einfüge-Events. Paste verarbeitet Vektorpfad-Skalierung, Instanz-Kind-Population aus Komponenten, Component-Set-Erkennung und Override-Anwendung. - -### MCP-Server - -`@open-pencil/mcp` stellt 87 Core-Tools + 3 Dateiverwaltungs-Tools für KI-Coding-Werkzeuge bereit. Zwei Transporte: stdio für Claude Code/Cursor/Windsurf, HTTP mit Hono + Streamable HTTP für Skripte und CI. Tools werden einmal in `packages/core/src/tools/` definiert und für AI-Chat (valibot), MCP (zod) und CLI (eval-Befehl) adaptiert. +Figma-kompatible bidirektionale Zwischenablage. Kodiert/dekodiert Kiwi-Binär (gleiches Format wie .fig-Dateien) über native Browser-Kopier/Einfüge-Events. Verarbeitet Vektorpfad-Skalierung, Instanz-Kinder, Component-Set-Erkennung und Override-Anwendung. ### P2P-Kollaboration Echtzeit-Peer-to-Peer-Kollaboration über Trystero (WebRTC) + Yjs CRDT. Kein Server-Relay — Signalisierung über öffentliche MQTT-Broker, STUN/TURN für NAT-Traversal. Das Awareness-Protokoll bietet Live-Cursor, Auswahlen und Präsenz. Lokale Persistenz über y-indexeddb. + +### CLI-zu-App RPC-Bridge + +Wenn die Desktop-App läuft, verbinden sich CLI-Befehle über WebSocket statt eine .fig-Datei zu benötigen. Der Automatisierungsserver läuft auf `127.0.0.1:7600` (HTTP) und `127.0.0.1:7601` (WebSocket). Befehle werden gegen den Live-Editor-Zustand ausgeführt, sodass Automatisierungsskripte und KI-Agenten mit der laufenden App interagieren können. + +## Ausblick + +### Vollständiges figma-use-Werkzeugset + +Der MCP-Server bietet derzeit 90 Werkzeuge. Die Referenzimplementierung in [figma-use](https://github.com/dannote/figma-use) hat 118. Die verbleibenden Werkzeuge decken erweiterte Layout-Constraints, Prototyp-Verbindungen, erweiterte Komponenteneigenschafts-Bearbeitung und Massen-Dokumentoperationen ab. + +### CI-Design-Werkzeuge + +Die headless CLI unterstützt bereits `analyze colors/typography/spacing/clusters`. Nächster Schritt: GitHub Actions-Integration für automatisiertes Design-Linting und visuelle Regression in PRs. + +### Prototyping + +Frame-zu-Frame-Übergänge, Interaktions-Trigger (Klick, Hover, Ziehen), Overlay-Verwaltung und Vollbild-Vorschaumodus. + +### 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. + +### Windows Code Signing + +macOS-Binaries sind seit v0.6.0 signiert und notarisiert. Windows Authenticode-Signierung über Azure Code Signing ist geplant, um die SmartScreen-Warnung zu entfernen. diff --git a/packages/docs/de/guide/features.md b/packages/docs/de/guide/features.md index 38587ba79..5422aec6c 100644 --- a/packages/docs/de/guide/features.md +++ b/packages/docs/de/guide/features.md @@ -1,254 +1,138 @@ # Funktionen -## Warum OpenPencil +## Figma .fig-Dateien -Design-Tools sind ein Lieferkettenproblem. Wenn Ihr Tool proprietär ist, bestimmt der Anbieter, was möglich ist — er kann Ihre Automatisierung über Nacht brechen. OpenPencil ist eine Open-Source-Alternative: MIT-lizenziert, Figma-kompatibel, vollständig lokal und programmierbar. +Öffnen und speichern Sie native Figma-Dateien direkt. Die Import/Export-Pipeline verwendet denselben Kiwi-Binär-Codec wie Figma — 194 Schema-Definitionen, ~390 Felder pro Knoten. Speichern mit S, Speichern unter mit S. -## Figma .fig-Datei Import & Export +**Kopieren & Einfügen mit Figma** — Knoten in Figma auswählen, C, zu OpenPencil wechseln, V. Füllungen, Konturen, Auto-Layout, Text, Effekte, Eckenradien und Vektornetzwerke bleiben erhalten. Funktioniert in beide Richtungen. -Öffnen und speichern Sie native Figma-Dateien direkt. Der Import dekodiert das vollständige 194-Definitionen-Kiwi-Schema einschließlich NodeChange-Nachrichten mit ~390 Feldern. Der Export kodiert den Szenengraphen zurück in Kiwi-Binärformat mit Zstd-Kompression und Thumbnail-Generierung. Speichern (S) und Speichern unter (S) verwenden native OS-Dialoge in der Desktop-App. Die Import/Export-Pipeline unterstützt Round-Trip-Treue. +## Zeichnen & Bearbeiten -## Kopieren & Einfügen mit Figma - -Knoten in Figma auswählen, C, zu OpenPencil wechseln, V — sie erscheinen mit Füllungen, Konturen, Auto-Layout, Text, Eckenradien, Effekten und Vektornetzwerken. Funktioniert auch umgekehrt. - -Paste verarbeitet komplexe Szenarien: Vektorpfade werden von Figmas `normalizedSize` auf die tatsächlichen Knotenmaße skaliert, Instanz-Kinder werden aus den `symbolData` ihrer Komponente gefüllt, Component-Sets werden erkannt und `symbolOverrides` für Text, Füllungen, Sichtbarkeit und Layout-Eigenschaften angewendet. Schriften, die von eingefügten Textknoten referenziert werden, werden automatisch geladen. - -## Vektornetzwerke - -Das Stiftwerkzeug verwendet Figmas Vektornetzwerk-Modell — keine einfachen Pfade. Klicken für Eckpunkte, Klicken+Ziehen für Bézier-Kurven mit Tangentengriffen. Offene und geschlossene Pfade werden unterstützt. - -## Formwerkzeuge - -Die Werkzeugleiste bietet alle grundlegenden Figma-Formwerkzeuge: Rechteck (R), Ellipse (O), Linie (L), Polygon und Stern. Alle Formen unterstützen Füllung, Kontur, Hover-Hervorhebung und Auswahlumriss. - -## Auto-Layout - -Yoga WASM bietet CSS-Flexbox-Layout. Frames unterstützen: - -- **Richtung** — horizontal, vertikal, Umbruch -- **Abstand** — Zwischenraum zwischen Kindern -- **Polsterung** — einheitlich oder pro Seite -- **Ausrichtung** — Start, Mitte, Ende, Zwischenraum -- **Querachse** — Start, Mitte, Ende, Dehnen -- **Kindgröße** — fest, füllen, anpassen - -Shift+A schaltet Auto-Layout um oder umschließt ausgewählte Knoten. - -## Inline-Textbearbeitung - -Canvas-native Textbearbeitung — kein DOM-Textarea-Overlay. Doppelklicken Sie auf einen Textknoten, um den Bearbeitungsmodus zu betreten. Der Canvas rendert einen blinkenden Cursor, blaue Auswahlrechtecke und einen blauen Umriss. - -**Schriftart-Auswahl** mit virtuellem Scrollen, Suchfilter und CSS-Schriftvorschau. In Tauri werden Systemschriften über Rusts `font-kit`-Crate aufgelistet. - -## Rich-Text-Formatierung - -Zeichenweise Formatierung innerhalb eines Textknotens. B für fett, I für kursiv, U für unterstrichen. Rich-Text-Formatierung bleibt bei .fig-Import/Export erhalten. - -## Rückgängig/Wiederherstellen - -Jede Operation ist rückgängig machbar. Das System verwendet ein Inverse-Command-Muster. Z macht rückgängig, Z stellt wieder her. - -## Fanglinien - -Kanten- und Mittenfang mit roten Führungslinien bei ausgerichteten Knoten. Rotationsbewusst. - -## Canvas-Lineale - -Lineale an den oberen und linken Kanten zeigen Koordinatenskalen. Bei Auswahl eines Knotens werden Position und Koordinaten-Badges angezeigt. - -## Farbauswahl & Fülltypen - -HSV-Farbauswahl mit Farbton-Schieberegler, Alpha-Schieberegler, Hex-Eingabe und Deckkraftsteuerung. Fülltypen: Vollfarbe, Verlauf (Linear, Radial, Winkel, Diamant) und Bild. - -## Ebenen-Panel - -Baumansicht der Dokumenthierarchie mit Reka UI Tree-Komponente. Aufklappen/Zuklappen, Ziehen zum Umordnen, Sichtbarkeit pro Knoten umschalten. +- **Formen** — Rechteck (R), Ellipse (O), Linie (L), Polygon, Stern +- **Stiftwerkzeug** — Vektornetzwerke (keine einfachen Pfade), Bézier-Kurven mit Tangentengriffen +- **Text** — Canvas-native Bearbeitung mit IME-Unterstützung, Doppelklick zum Betreten des Bearbeitungsmodus +- **Rich Text** — Zeichenweise Fett (B), Kursiv (I), Unterstrichen (U), Durchgestrichen +- **Auto-Layout** — Flexbox via Yoga WASM: Richtung, Abstand, Polsterung, Ausrichtung, Kindgröße. A zum Umschalten +- **Komponenten** — Erstellen (K), Component Sets (K), Instanzen mit Override-Unterstützung, Live-Synchronisation +- **Variablen** — Design-Tokens mit Sammlungen, Modi (Hell/Dunkel), Farb-/Float-/String-/Boolean-Typen, Variablenbindung +- **Sektionen** — Organisatorische Container mit automatischer Kindübernahme und Titel-Pills ## Eigenschafts-Panel -Registerkarten-Oberfläche mit **Design** | **Code** | **KI**-Tabs. +Kontextsensitive Design | Code | KI-Tabs: -Der **Design**-Tab zeigt kontextsensitive Abschnitte: Darstellung, Füllung, Kontur, Effekte, Typografie, Layout, Position, Export und Seite. +- **Darstellung** — Deckkraft, Eckenradius (einheitlich oder pro Ecke), Sichtbarkeit +- **Füllung** — Vollfarbe, Verlauf (Linear/Radial/Angular/Diamant), Bild +- **Kontur** — Farbe, Breite, Ausrichtung (Innen/Mitte/Außen), Pro-Seite-Breiten, Cap, Join, Dash +- **Effekte** — Schlagschatten, Innerer Schatten, Ebenen-Unschärfe, Hintergrund-Unschärfe, Vordergrund-Unschärfe +- **Typografie** — Schriftart-Auswahl mit virtuellem Scrollen und Suche, Gewicht, Größe, Ausrichtung, Stil-Buttons +- **Layout** — Auto-Layout-Steuerungen (wenn aktiviert) +- **Export** — Skalierung, Format (PNG/JPG/WEBP/SVG), Live-Vorschau -Der **Code**-Tab zeigt JSX-Export der Auswahl. Der **KI**-Tab bietet eine KI-Chat-Oberfläche. +## Rendering -## Gruppieren/Entgruppieren +Skia (CanvasKit WASM) — dieselbe Rendering-Engine wie Figma: -⌘G gruppiert ausgewählte Knoten. ⇧⌘G entgruppiert. +- Verlaufsfüllungen (Linear, Radial, Angular, Diamant) +- Bildfüllungen mit Skalierungsmodi +- Effekte mit Pro-Knoten-Caching +- Bogendaten (partielle Ellipsen, Donuts) +- Viewport-Culling und Paint-Wiederverwendung +- Fanglinien mit rotationsbewusster Ausrichtung +- Canvas-Lineale mit Auswahl-Badges +- Hover-Hervorhebung entlang der tatsächlichen Geometrie -## Sektionen +## Rückgängig/Wiederherstellen -Sektionen (S) sind organisatorische Container auf der obersten Ebene des Canvas. +Jede Operation ist rückgängig machbar — Erstellen, Löschen, Verschieben, Größenänderungen, Eigenschaftsänderungen, Umordnung, Layout-Änderungen, Variablen-Operationen. Verwendet ein Inverse-Command-Muster. Z / Z. ## Mehrseitige Dokumente -Dokumente unterstützen mehrere Seiten wie Figma. Jede Seite hat einen unabhängigen Viewport-Zustand. - -## Hover-Hervorhebung - -Knoten werden beim Überfahren mit einem formgerechten Umriss hervorgehoben. - -## Erweitertes Rendering (Tier 1) - -Der CanvasKit-Renderer unterstützt vollständige Tier-1-Visualfunktionen: Gradientenfüllungen (linear, radial, angular, diamant), Bildfüllungen, Effekte (Schatten, Unschärfe), Kontureigenschaften (Cap, Join, Dash), Bogendaten, Viewport-Culling, Paint-Wiederverwendung und RAF-Zusammenfassung. - -## Komponenten & Instanzen - -Erstellen Sie wiederverwendbare Komponenten aus Frames oder Auswahlen (K). Live-Synchronisation, Override-Unterstützung und Komponenten-Sets (K). - -## Variablen - -Design-Token als Variablen mit Sammlungen und Modi. Unterstützt COLOR-Typ mit vollständiger UI, FLOAT/STRING/BOOLEAN definiert. Organisieren Sie Variablen in Sammlungen, definieren Sie Modi (z.B. Hell/Dunkel). - -## Bildexport - -Ausgewählte Knoten als PNG, JPG oder WEBP exportieren. Skalierung von 0,5× bis 4×, Formatauswahl und Live-Vorschau. - -## Kontextmenü - -Rechtsklick auf dem Canvas öffnet ein Figma-ähnliches Kontextmenü mit Zwischenablage, Z-Reihenfolge, Gruppierung, Komponenten- und Sichtbarkeitsaktionen. - -## Z-Ordnung, Sichtbarkeit & Sperre - -] bringt ausgewählte Knoten nach vorne, [ sendet nach hinten. H schaltet Sichtbarkeit um. L schaltet die Sperre um — gesperrte Knoten können nicht vom Canvas aus ausgewählt oder verschoben werden. Knoten zwischen Seiten verschieben über das Kontextmenü „Auf Seite verschieben". - -## Web- & Desktop-App - -OpenPencil läuft im Browser unter [app.openpencil.dev](https://app.openpencil.dev). Die Desktop-App verwendet eine Tauri v2-Shell (~5 MB). - -## App-Menü (Browser) - -Im Browser-Modus bietet eine mit reka-ui Menubar erstellte Menüleiste Zugriff auf alle wichtigen Editor-Aktionen. Sechs Menüs: **Datei**, **Bearbeiten**, **Ansicht**, **Objekt**, **Text**, **Anordnen**. - -## Automatisches Speichern - -Dateien werden 3 Sekunden nach der letzten Szenenänderung automatisch gespeichert. - -## P2P-Kollaboration - -Echtzeit-Peer-to-Peer-Kollaboration — kein Server erforderlich. Teilen Sie einen Link und bearbeiten Sie gemeinsam. Basiert auf Trystero (WebRTC) für direkte Peer-Verbindungen und Yjs (CRDT) für konfliktfreie Dokumentensynchronisation. - -- **Keine Hosting-Kosten** — Signalisierung über öffentliche MQTT-Broker, Daten fließen direkt zwischen Peers -- **NAT-Traversal** — Google STUN, Cloudflare STUN und Open Relay TURN-Server -- **Live-Cursor** — Figma-ähnliche farbige Cursor-Pfeile mit weißem Rand und Namens-Pills, im Bildschirmraum gerendert -- **Präsenz** — sehen Sie, wer im Raum ist, mit farbigen Avataren -- **Folgemodus** — klicken Sie auf den Avatar eines Peers, um seinem Viewport in Echtzeit zu folgen -- **Lokale Persistenz** — y-indexeddb hält den Raum über Seitenaktualisierungen hinweg am Leben -- **Sichere Räume** — IDs werden mit `crypto.getRandomValues()` generiert +Seiten hinzufügen, löschen, umbenennen. Jede Seite hat einen unabhängigen Viewport-Zustand. Doppelklick zum Inline-Umbenennen. ## Multi-Datei-Tabs -Öffnen Sie mehrere Dokumente in Tabs innerhalb eines einzigen Fensters. Tab-Leiste mit Schließen-Buttons. Mittelklick zum Schließen eines Tabs. +Mehrere Dokumente in Tabs öffnen. T neuer Tab, W schließen, O Datei öffnen. -- N oder T — neuer Tab -- W — aktuellen Tab schließen -- O — Datei in neuem Tab öffnen +## Export -Jeder Tab pflegt seinen eigenen Dokumentzustand, Undo-Verlauf und Viewport. +- **Bild** — PNG, JPG, WEBP in konfigurierbarer Skalierung (0,5×–4×). Über Panel, Kontextmenü oder E +- **SVG** — Formen, Text mit Stil-Runs, Verläufe, Effekte, Mischmodi +- **Tailwind JSX** — HTML mit Tailwind v4 Utility-Klassen, bereit für React oder Vue +- **Als kopieren** — Text, SVG, PNG (C) oder JSX über das Kontextmenü -## Effekt-Rendering +CLI: `open-pencil export design.fig -f jsx --style tailwind` -Vollständiges Rendering von Figma-Effekten über CanvasKit: +## KI-Chat -- **Schlagschatten** — Versatz, Unschärferadius, Ausdehnung, Farbe -- **Innerer Schatten** — eingefügter Schatten mit Versatz, Unschärfe und Farbe -- **Ebenen-Unschärfe** — Gaußsche Unschärfe auf der gesamten Ebene -- **Hintergrund-Unschärfe** — Unschärfe des Inhalts hinter der Ebene (Glas-/Matteffekt) -- **Vordergrund-Unschärfe** — Unschärfe im Vordergrund +J öffnet den KI-Assistenten. 87 Werkzeuge zum Erstellen von Formen, Setzen von Stilen, Verwalten von Layout, Arbeiten mit Komponenten und Variablen, Ausführen boolescher Operationen, Analysieren von Design-Tokens und Exportieren von Assets. Eigener OpenRouter-API-Key. -Per-Knoten `SkPicture`-Cache bedeutet, dass unveränderte Schatten-/Unschärfe-Knoten aus dem Cache wiedergegeben werden. +Tool-Aufrufe werden als einklappbare Timeline-Einträge angezeigt. Modellauswahl mit Claude, Gemini, GPT, DeepSeek und weiteren. -## Multi-Selektion-Eigenschaften +## MCP-Server -Wählen Sie mehrere Knoten aus und bearbeiten Sie gemeinsame Eigenschaften gleichzeitig: +Claude Code, Cursor, Windsurf oder jeden MCP-Client verbinden, um `.fig`-Dateien headless zu lesen und zu schreiben. 90 Werkzeuge (87 Core + 3 Dateiverwaltung). Zwei Transporte: stdio und HTTP. -- Gemeinsame Werte werden in allen Abschnitten normal angezeigt (Position, Größe, Darstellung, Füllung, Kontur, Effekte) -- Unterschiedliche Werte zeigen „Mixed" -- Breiten- und Höheneingaben funktionieren über die Auswahl -- Horizontal/vertikal spiegeln gilt für alle ausgewählten Knoten +```sh +bun add -g @open-pencil/mcp +``` -## ScrubInput +```json +{ + "mcpServers": { + "open-pencil": { + "command": "openpencil-mcp" + } + } +} +``` -Alle numerischen Eingaben im Eigenschafts-Panel verwenden eine Zieh-zum-Ändern-Interaktion — horizontal ziehen zum Anpassen des Wertes, oder klicken zum direkten Eingeben. Unterstützt Suffix-Anzeige (°, px, %). +Siehe [MCP-Tools-Referenz](/reference/mcp-tools) für die vollständige Werkzeugliste. -## CI/CD-Builds +## CLI -GitHub Actions baut native Tauri-Desktop-Apps bei Versions-Tags. Die Build-Matrix umfasst macOS (arm64, x64), Windows (x64, arm64) und Linux (x64). macOS-Builds sind mit Apple-Developer-Zertifikaten signiert und notarisiert. Release-Notes werden automatisch aus CHANGELOG.md befüllt. +`.fig`-Dateien vom Terminal aus inspizieren, exportieren und analysieren: -## Bild- & SVG-Export +```sh +open-pencil tree design.fig # Knotenbaum +open-pencil find design.fig --type TEXT # Suche +open-pencil export design.fig -f png # Rendern +open-pencil analyze colors design.fig # Farbanalyse +open-pencil analyze clusters design.fig # Wiederholte Muster +open-pencil eval design.fig -c "..." # Figma Plugin API +``` -Exportieren Sie ausgewählte Knoten als PNG, JPG, WEBP oder SVG. SVG-Export unterstützt Rechtecke, Ellipsen, Linien, Sterne, Polygone, Vektoren, Text, Verläufe, Bildausfüllungen, Effekte und verschachtelte Gruppen. +Wenn die Desktop-App läuft, kann die Datei weggelassen werden, um den Live-Editor via RPC zu steuern: -CLI: `bun open-pencil export --format svg file.fig`. MCP/KI-Tool: `export_svg`. +```sh +open-pencil tree # Live-Dokument +open-pencil export -f png # Canvas-Screenshot +``` -## Als kopieren +Alle Befehle unterstützen `--json`. Installation: `bun add -g @open-pencil/cli` -Das **Als kopieren**-Untermenü im Kontextmenü bietet: +## Echtzeit-Kollaboration -- **Als Text kopieren** — sichtbarer Textinhalt -- **Als SVG kopieren** — SVG-Markup der Auswahl -- **Als PNG kopieren** — rendert bei 2× in die Zwischenablage (C) -- **Als JSX kopieren** — OpenPencil JSX +P2P via WebRTC — kein Server erforderlich. Link teilen und gemeinsam bearbeiten. -## Konturausrichtung & Pro-Seite-Breiten +- Live-Cursor mit farbigen Pfeilen und Namens-Pills +- Präsenz-Avatare +- Folgemodus — auf einen Peer klicken, um seinem Viewport zu folgen +- Lokale Persistenz via IndexedDB +- Sichere Raum-IDs via `crypto.getRandomValues()` -Konturausrichtung: **Innen**, **Mitte** oder **Außen** (beschneidungsbasiertes Rendering wie in Figma). Individuelle Konturbreiten pro Seite (Oben/Rechts/Unten/Links) über das Seitenauswahl-Dropdown. +## Desktop & Web -## Mobile Layout & PWA +**Desktop** — Tauri v2, ~7 MB. macOS (signiert & notarisiert), Windows, Linux. Native Menüs, Offline-Betrieb, automatisches Speichern. -OpenPencil ist als Progressive Web App auf Mobilgeräten installierbar. Das Layout passt sich kleinen Bildschirmen an — Seitenpanels werden durch ein wischbares unteres Drawer mit Tabs ersetzt: Ebenen, Eigenschaften, Design, Code. +**Web** — läuft unter [app.openpencil.dev](https://app.openpencil.dev), als PWA auf Mobilgeräten installierbar mit touch-optimierter Oberfläche. -## Tailwind CSS v4 JSX-Export - -Der Code-Tab bietet einen Formatschalter zwischen **OpenPencil JSX** und **Tailwind CSS v4** (HTML mit Utility-Klassen). CLI: `bun open-pencil export --format jsx --style tailwind file.fig` - -## Google Fonts Fallback - -Wenn eine Schriftart lokal nicht verfügbar ist, lädt OpenPencil sie automatisch von der Google Fonts API. - -## Homebrew-Tap - -macOS-Nutzer können die Desktop-App über Homebrew installieren: +**Homebrew:** ```sh brew install open-pencil/tap/open-pencil ``` -## Ebenen-Inline-Umbenennen +## Google Fonts Fallback -Doppelklick auf einen Ebenennamen zum Inline-Umbenennen. Enter oder Klick außerhalb bestätigt, Escape bricht ab. - -## Renderer-Profiler - -Ein HUD-Overlay zeigt Frame-Timing, GPU-Phasen und Frame-Budget. Zugänglich über das Ansichtsmenü. - -## KI-Chat - -Integrierter KI-Assistent über den KI-Tab oder J. Kommuniziert direkt mit OpenRouter. **87 Werkzeuge** für Lesen, Erstellen, Ändern und Organisieren von Design-Elementen. **MCP-Server** für externe KI-Coding-Tools. - -**AI agent skill** — `npx skills add open-pencil/skills@open-pencil` — teaches AI coding agents to use the CLI, MCP tools, and automation bridge. Source: [open-pencil/skills](https://github.com/open-pencil/skills). - -## @open-pencil/core & CLI - -Die Engine ist in `packages/core/` extrahiert. CLI bietet headless .fig-Dateioperationen: - -- `open-pencil info ` — Dokumentstatistiken -- `open-pencil tree ` — visueller Knotenbaum -- `open-pencil find ` — Suche nach Name/Typ -- `open-pencil export ` — Rendern als PNG/JPG/WEBP -- `open-pencil eval ` — JavaScript mit Figma Plugin API ausführen - -Alle Befehle unterstützen `--json` für maschinenlesbare Ausgabe. - -## JSX-Renderer - -Programmatische Design-Erstellung über TreeNode-Builder-Funktionen aus `@open-pencil/core`. Unterstützt Tailwind-ähnliche Kurzform-Props — `w`, `h`, `bg`, `rounded`, `flex`, `gap`, `p`/`px`/`py`. - -## Code-Panel - -Der Code-Tab im Eigenschafts-Panel zeigt die Code-Darstellung der aktuellen Auswahl mit Syntaxhervorhebung und einem Kopieren-Button. Ein Formatschalter wechselt zwischen OpenPencil JSX und Tailwind CSS v4. - -## Codequalität - -Copy-Paste-Erkennung via jscpd — projektweite Duplikation von 15,6% auf 0,62% reduziert. +Wenn eine Schriftart lokal nicht verfügbar ist, lädt OpenPencil sie automatisch von Google Fonts. Keine manuelle Installation nötig beim Öffnen von .fig-Dateien mit unbekannten Schriften. diff --git a/packages/docs/de/index.md b/packages/docs/de/index.md index 1a44d2f9d..5986befee 100644 --- a/packages/docs/de/index.md +++ b/packages/docs/de/index.md @@ -1,16 +1,16 @@ --- layout: home -title: OpenPencil — KI-nativer Design-Editor -description: Open-Source Figma-Alternative. Vollständig lokal, KI-nativ, programmierbar. +title: OpenPencil — Open-Source Design-Editor +description: Open-Source Figma-Alternative. Öffnet .fig-Dateien, integrierte KI, vollständig programmierbar. hero: name: OpenPencil - text: KI-nativer Design-Editor - tagline: Open-Source Figma-Alternative. Vollständig lokal, KI-nativ, programmierbar. + text: Open-Source Design-Editor + tagline: Öffnet Figma-Dateien. Integrierte KI. Vollständig programmierbar. Für immer kostenlos. actions: - theme: brand text: Online testen - link: https://app.openpencil.dev + link: https://app.openpencil.dev/demo - theme: alt text: Herunterladen link: https://github.com/open-pencil/open-pencil/releases/latest @@ -19,19 +19,22 @@ hero: link: https://github.com/open-pencil/open-pencil features: - - icon: 📖 - title: Open Source - details: MIT-Lizenz. Alles lesen und ändern — Editor, Engine, Datei-Codec. - icon: 📂 title: Figma-kompatibel - details: Öffnet .fig-Dateien nativ. Kopieren/Einfügen zwischen Apps. Kiwi-Codec mit Round-Trip-Treue. - - icon: 🤖 - title: KI-nativ - details: Integrierter Chat mit Tool-Nutzung. Eigener API-Key — kein Abo, kein Vendor-Lock-in. - - icon: 🖥️ - title: Kein Abonnement - details: Kein Konto, kein Server, kein Internet nötig. Für immer kostenlos. ~5 MB Desktop-App. + details: Öffnet .fig-Dateien nativ. Kopieren & Einfügen zwischen Figma und OpenPencil. Kiwi-Binär-Codec mit Round-Trip-Treue. - icon: ⚡ title: Programmierbar - details: Headless-CLI für .fig-Inspektion und Export. Jede Operation ist skriptfähig. JSX-Renderer. + details: Headless-CLI zum Inspizieren, Exportieren und Analysieren von .fig-Dateien. Figma Plugin API via eval. Tailwind CSS-Export. JSON-Ausgabe für CI. + - icon: 🤖 + title: KI-nativ + details: Integrierter Chat mit 90 Werkzeugen — Formen erstellen, Stile setzen, Layout verwalten, Tokens analysieren. MCP-Server für Claude Code, Cursor, Windsurf. + - icon: 📖 + title: Open Source + details: MIT-Lizenz. Alles lesen und ändern — den Editor, die Engine, den Datei-Codec, die CLI. + - icon: 🖥️ + title: Kostenlos & lokal + details: Kein Konto, kein Server, kein Internet nötig. ~7 MB Desktop-App via Homebrew oder die Web-App nutzen. + - icon: 👥 + title: Echtzeit-Kollaboration + details: P2P via WebRTC — kein Server. Link teilen, gemeinsam bearbeiten mit Live-Cursorn und Folgemodus. --- diff --git a/packages/docs/es/guide/architecture.md b/packages/docs/es/guide/architecture.md index 48da9905e..f13a388d0 100644 --- a/packages/docs/es/guide/architecture.md +++ b/packages/docs/es/guide/architecture.md @@ -2,42 +2,33 @@ ## Vista general del sistema -``` -┌──────────────────────────────────────────────────────────────────┐ -│ Tauri v2 Shell │ -│ │ -│ ┌────────────────────────────────────────────────────────────┐ │ -│ │ Editor (Web) │ │ -│ │ │ │ -│ │ Vue 3 UI Skia CanvasKit (WASM, 7MB) │ │ -│ │ - Barra de herramientas - Renderizado vectorial │ │ -│ │ - Paneles - Modelado de texto │ │ -│ │ - Propiedades - Procesamiento de imágenes │ │ -│ │ - Capas - Efectos (desenfoque, sombra) │ │ -│ │ - Selector de color - Exportación (PNG, SVG, PDF) │ │ -│ │ │ │ -│ │ ┌──────────────────────────────────────────────────────┐ │ │ -│ │ │ Core Engine (TS) │ │ │ -│ │ │ SceneGraph ─── Layout (Yoga) ─── Selection │ │ │ -│ │ │ │ │ │ │ │ -│ │ │ Undo/Redo ─── Constraints ─── Hit Testing │ │ │ -│ │ └──────────────────────────────────────────────────────┘ │ │ -│ │ │ │ -│ │ ┌──────────────────────────────────────────────────────┐ │ │ -│ │ │ Capa de formato de archivo │ │ │ -│ │ │ .fig import/export ── Kiwi codec ── .svg (previsto) │ │ │ -│ │ └──────────────────────────────────────────────────────┘ │ │ -│ └────────────────────────────────────────────────────────────┘ │ -│ │ -│ MCP Server (75+ tools, stdio+HTTP) P2P Collab (Trystero + Yjs) │ -└──────────────────────────────────────────────────────────────────┘ +```mermaid +graph TB + subgraph Tauri["Tauri v2 Shell"] + subgraph Editor["Editor (Web)"] + UI["Vue 3 UI
Toolbar · Panels · Properties
Layers · Color Picker"] + Skia["Skia CanvasKit (WASM, 7MB)
Vector rendering · Text shaping
Effects · Export"] + subgraph Core["Core Engine (TS)"] + SG[SceneGraph] --- Layout[Layout - Yoga] + SG --- Selection + Undo[Undo/Redo] --- Constraints + Constraints --- HitTest[Hit Testing] + end + subgraph FileFormat["File Format Layer"] + FigIO[".fig import/export"] --- Kiwi[Kiwi codec] + Kiwi --- SVG[SVG export] + end + end + MCP["MCP Server (90 tools, stdio+HTTP)"] + Collab["P2P Collab (Trystero + Yjs)"] + end ``` ## Diseño del editor La interfaz sigue el layout UI3 de Figma — barra de herramientas abajo, navegación a la izquierda, propiedades a la derecha: -- **Panel de navegación (izquierda)** — Árbol de capas, panel de páginas, biblioteca de assets (previsto) +- **Panel de navegación (izquierda)** — Árbol de capas, panel de páginas - **Canvas (centro)** — Canvas infinito con renderizado CanvasKit, zoom/pan - **Panel de propiedades (derecha)** — Secciones contextuales: Apariencia, Relleno, Trazo, Tipografía, Layout, Posición - **Barra de herramientas (abajo)** — Selección de herramienta: Seleccionar, Frame, Sección, Rectángulo, Elipse, Línea, Texto, Pluma, Mano @@ -46,13 +37,9 @@ La interfaz sigue el layout UI3 de Figma — barra de herramientas abajo, navega ### Renderizado (CanvasKit WASM) -El mismo motor de renderizado que Figma. CanvasKit proporciona dibujo 2D acelerado por GPU con: -- Formas vectoriales (rectángulo, elipse, ruta, línea, estrella, polígono) -- Modelado de texto vía Paragraph API -- Efectos (sombras, desenfoques, modos de mezcla) -- Exportación (PNG, SVG, PDF) +El mismo motor de renderizado que Figma. CanvasKit proporciona dibujo 2D acelerado por GPU con formas vectoriales, modelado de texto vía Paragraph API, efectos (sombras, desenfoques, modos de mezcla) y exportación (PNG, SVG). El binario WASM de 7 MB se carga al inicio y crea una superficie GPU en el canvas HTML. -El binario WASM de 7 MB se carga al inicio y crea una superficie GPU en el canvas HTML. +El renderer está dividido en módulos enfocados en `packages/core/src/renderer/`: recorrido de escena, overlays, rellenos, trazos, formas, efectos, reglas, etiquetas y cursores remotos. ### Grafo de escena @@ -75,22 +62,54 @@ Yoga de Meta proporciona cálculo de layout CSS flexbox. Un adaptador delgado ma ### Formato de archivo (Kiwi binario) -Reutiliza el probado codec binario Kiwi de Figma con 194 definiciones de mensaje/enum/struct. Pipeline de importación `.fig`: parsear cabecera → descomprimir Zstd → decodificar Kiwi → NodeChange[] → grafo de escena. El pipeline de exportación invierte el proceso: grafo de escena → NodeChange[] → codificar Kiwi → comprimir Zstd → ZIP con 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. +### IA y herramientas + +Las herramientas se definen una vez en `packages/core/src/tools/`, divididas por dominio: read, create, modify, structure, variables, vector, analyze. Cada herramienta tiene parámetros tipados y una función `execute(figma, args)`. Los adaptadores las convierten para: + +- **Chat IA** — schemas valibot, conectados a OpenRouter +- **Servidor MCP** — schemas zod, transportes stdio + HTTP +- **CLI** — disponibles vía el comando `eval` + +87 herramientas core + 3 herramientas de gestión de archivos MCP = 90 en total. + ### Deshacer/Rehacer Patrón de comando inverso. Antes de aplicar cualquier cambio, se captura un snapshot de los campos afectados. El snapshot se convierte en la operación inversa. El batching agrupa cambios rápidos (como arrastre) en entradas de deshacer únicas. ### Portapapeles -Portapapeles bidireccional compatible con Figma. Codifica/decodifica binario Kiwi (mismo formato que archivos .fig) usando eventos nativos de copiar/pegar del navegador (síncronos, no la API asíncrona del Clipboard). El pegado gestiona escalado de rutas vectoriales, población de hijos de instancia, detección de conjuntos de componentes y aplicación de overrides. - -### Servidor MCP - -`@open-pencil/mcp` expone 87 herramientas core + 3 herramientas de gestión de archivos para herramientas de codificación IA. Dos transportes: stdio para Claude Code/Cursor/Windsurf, HTTP con Hono + Streamable HTTP para scripts y CI. Las herramientas se definen una vez en `packages/core/src/tools/` y se adaptan para chat IA (valibot), MCP (zod) y CLI (comando eval). +Portapapeles bidireccional compatible con Figma. Codifica/decodifica binario Kiwi (mismo formato que archivos .fig) usando eventos nativos de copiar/pegar del navegador. Gestiona escalado de rutas vectoriales, hijos de instancia, detección de conjuntos de componentes y aplicación de overrides. ### Colaboración P2P Colaboración peer-to-peer en tiempo real vía Trystero (WebRTC) + Yjs CRDT. Sin servidor relay — señalización a través de brokers MQTT públicos, STUN/TURN para traversal NAT. El protocolo de awareness proporciona cursores en vivo, selecciones y presencia. Persistencia local vía y-indexeddb. + +### Puente RPC CLI-a-App + +Cuando la app de escritorio está en ejecución, los comandos CLI se conectan a ella vía WebSocket en lugar de requerir un archivo .fig. El servidor de automatización corre en `127.0.0.1:7600` (HTTP) y `127.0.0.1:7601` (WebSocket). Los comandos se ejecutan contra el estado del editor en vivo, permitiendo que scripts de automatización y agentes IA interactúen con la app en ejecución. + +## Próximos pasos + +### Conjunto completo de herramientas figma-use + +El servidor MCP actualmente expone 90 herramientas. La implementación de referencia en [figma-use](https://github.com/dannote/figma-use) tiene 118. Las herramientas restantes cubren restricciones de layout avanzadas, conexiones de prototipos, edición avanzada de propiedades de componentes y operaciones masivas de documentos. + +### Herramientas de diseño para CI + +El CLI headless ya soporta `analyze colors/typography/spacing/clusters`. Próximo: integración con GitHub Actions para linting de diseño automatizado y regresión visual en PRs. + +### Prototipado + +Transiciones entre frames, triggers de interacción (clic, hover, arrastre), gestión de overlays y modo de vista previa a pantalla completa. + +### 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. + +### Firma de código en Windows + +Los binarios de macOS están firmados y notarizados desde la v0.6.0. La firma Authenticode de Windows vía Azure Code Signing está planificada para eliminar la advertencia de SmartScreen. diff --git a/packages/docs/es/guide/features.md b/packages/docs/es/guide/features.md index 8ae33ecf5..6a1c56697 100644 --- a/packages/docs/es/guide/features.md +++ b/packages/docs/es/guide/features.md @@ -1,217 +1,138 @@ # Características -## Por qué OpenPencil +## Archivos .fig de Figma -Las herramientas de diseño son un problema de cadena de suministro. Cuando tu herramienta es de código cerrado, el proveedor controla lo que es posible — pueden romper tu automatización de la noche a la mañana. OpenPencil es una alternativa open-source: licencia MIT, compatible con Figma, completamente local y programable. +Abre y guarda archivos nativos de Figma directamente. El pipeline de importación/exportación usa el mismo códec binario Kiwi que Figma — 194 definiciones de esquema, ~390 campos por nodo. Guardar con S, Guardar como con S. -## Import & export de archivos .fig de Figma +**Copiar y pegar con Figma** — selecciona nodos en Figma, C, cambia a OpenPencil, V. Rellenos, trazos, auto-layout, texto, efectos, radios de esquina y redes vectoriales se preservan. Funciona en ambas direcciones. -Abre y guarda archivos nativos de Figma directamente. El import decodifica el esquema Kiwi completo de 194 definiciones incluyendo mensajes NodeChange con ~390 campos. El export codifica el grafo de escena de vuelta a binario Kiwi con compresión Zstd y generación de miniatura. Guardar (S) y Guardar como (S) usan diálogos nativos del SO en la app de escritorio. El pipeline de import/export soporta fidelidad round-trip. +## Dibujo y edición -## Copiar y pegar con Figma - -Selecciona nodos en Figma, C, cambia a OpenPencil, V — aparecen con rellenos, trazos, auto-layout, texto, radios de esquina, efectos y redes vectoriales preservados. Funciona también en la otra dirección: copia desde OpenPencil, pega en Figma. - -Internamente, ambas direcciones usan el mismo formato binario Kiwi que los archivos .fig. OpenPencil decodifica el esquema completo al pegar (194 definiciones, ~390 campos por NodeChange) y lo codifica al copiar. Los datos vectoriales se transportan ida y vuelta a través del formato binario `vectorNetworkBlob`. También funciona entre instancias de OpenPencil via un formato de portapapeles nativo separado. - -El pegado gestiona escenarios complejos: las rutas vectoriales se escalan desde `normalizedSize` de Figma a los límites reales del nodo, los hijos de instancia se pueblan desde el `symbolData` de su componente, los conjuntos de componentes se detectan promoviendo frames con `componentPropDefs` de variante, los nodos del canvas interno se omiten, y los `symbolOverrides` se aplican para texto, rellenos, visibilidad y propiedades de layout. Las fuentes referenciadas por nodos de texto pegados se cargan automáticamente. - -## Redes vectoriales - -La herramienta pluma usa el modelo de red vectorial de Figma — no rutas simples. Clic para puntos de esquina, clic+arrastrar para curvas de Bézier con asas de tangente. Soporta rutas abiertas y cerradas. Los datos vectoriales usan el mismo formato binario `vectorNetworkBlob` que Figma. - -## Herramientas de forma - -La barra de herramientas proporciona todas las herramientas de forma básicas de Figma: Rectángulo (R), Elipse (O), Línea (L), Polígono y Estrella. Polígono dibuja polígonos regulares (por defecto 3 lados). Estrella dibuja estrellas puntiagudas (por defecto 5 puntas) con `starInnerRadius` configurable. Todas las formas soportan relleno, trazo, resaltado al pasar el ratón y contorno de selección. - -## Auto-Layout - -Yoga WASM proporciona layout CSS flexbox. Los frames soportan: dirección (horizontal, vertical, wrap), gap, padding (uniforme o por lado), justify (start, center, end, space-between), align (start, center, end, stretch) y dimensionado de hijos (fijo, rellenar, ajustar). Shift+A alterna auto-layout en un frame o envuelve los nodos seleccionados. - -## Edición de texto inline - -Edición de texto nativa en el canvas — sin overlay de textarea DOM. Doble clic en un nodo de texto para entrar en modo de edición. El canvas renderiza un cursor parpadeante, rectángulos de selección azules translúcidos y un contorno azul alrededor del nodo. Navegación con teclado con soporte de modificadores: / para movimiento por palabra, / para inicio/fin de línea. - -**Selector de fuentes** con scroll virtual, filtro de búsqueda y vista previa CSS de fuentes. En Tauri, las fuentes del sistema se enumeran vía el crate Rust `font-kit`. En el navegador, se usa la API Local Font Access cuando está disponible. - -## Formateo de texto enriquecido - -Formateo por carácter dentro de un nodo de texto. B para negrita, I para cursiva, U para subrayado, o usa los botones B/I/U/S en la sección Tipografía. Implementado vía un modelo StyleRun. El formateo de texto enriquecido se preserva durante import/export .fig. - -## Deshacer/Rehacer - -Toda operación es deshacible — creación/eliminación de nodos, movimientos, redimensionamientos, cambios de propiedades, cambios de padre, cambios de layout y todas las operaciones de variables. Z deshace, Z rehace. - -## Guías de snap - -Snap de bordes y centros con líneas guía rojas cuando los nodos se alinean. Consciente de la rotación — los cálculos de snap usan los límites visuales reales de nodos rotados. - -## Reglas del canvas - -Reglas en los bordes superior e izquierdo muestran escalas de coordenadas. Al seleccionar un nodo, las reglas resaltan su posición con una banda translúcida y muestran badges de coordenadas. - -## Selector de color y tipos de relleno - -Selección de color HSV con slider de tono, slider alfa, entrada hex y control de opacidad. El selector de tipo de relleno proporciona pestañas para Sólido, Gradiente (Lineal, Radial, Angular, Diamante) e Imagen. - -## Panel de capas - -Vista de árbol de la jerarquía del documento usando el componente Reka UI Tree. Expandir/colapsar frames, arrastrar para reordenar (cambia z-order), alternar visibilidad por nodo. Ambos paneles son redimensionables. +- **Formas** — Rectángulo (R), Elipse (O), Línea (L), Polígono, Estrella +- **Herramienta pluma** — redes vectoriales (no rutas simples), curvas de Bézier con asas de tangente +- **Texto** — edición nativa en el canvas con soporte IME, doble clic para entrar en modo de edición +- **Texto enriquecido** — negrita por carácter (B), cursiva (I), subrayado (U), tachado +- **Auto-layout** — flexbox vía Yoga WASM: dirección, gap, padding, justify, align, dimensionado de hijos. A para alternar +- **Componentes** — crear (K), conjuntos de componentes (K), instancias con soporte de overrides, sincronización en vivo +- **Variables** — tokens de diseño con colecciones, modos (Claro/Oscuro), tipos color/float/string/boolean, vinculación de variables +- **Secciones** — contenedores organizacionales con adopción automática de hijos y píldoras de título ## Panel de propiedades -Interfaz con pestañas **Diseño** | **Código** | **IA** (reka-ui Tabs). +Pestañas contextuales Diseño | Código | IA: -La pestaña **Diseño** es contextual con secciones: Apariencia (opacidad, radio de esquina, visibilidad), Relleno, Trazo, Efectos, Tipografía, Layout, Posición, Exportación y Página. +- **Apariencia** — opacidad, radio de esquina (uniforme o por esquina), visibilidad +- **Relleno** — sólido, gradiente (lineal/radial/angular/diamante), imagen +- **Trazo** — color, grosor, alineación (interior/centro/exterior), grosores por lado, cap, join, dash +- **Efectos** — sombra paralela, sombra interior, desenfoque de capa, desenfoque de fondo, desenfoque de primer plano +- **Tipografía** — selector de fuentes con scroll virtual y búsqueda, peso, tamaño, alineación, botones de estilo +- **Layout** — controles de auto-layout cuando está habilitado +- **Exportación** — escala, formato (PNG/JPG/WEBP/SVG), vista previa en vivo -La pestaña **Código** muestra export JSX de la selección. La pestaña **IA** proporciona una interfaz de chat IA. +## Renderizado -## Agrupar/Desagrupar +Skia (CanvasKit WASM) — el mismo motor de renderizado que Figma: -⌘G agrupa nodos seleccionados. ⇧⌘G desagrupa. Los nodos se ordenan por posición visual al agrupar. +- Rellenos de gradiente (lineal, radial, angular, diamante) +- Rellenos de imagen con modos de escala +- Efectos con caché por nodo +- Datos de arco (elipses parciales, donuts) +- Culling de viewport y reutilización de Paint +- Guías de snap con alineación consciente de rotación +- Reglas del canvas con badges de selección +- Resaltado al pasar que sigue la geometría real -## Secciones +## Deshacer/Rehacer -Las secciones (S) son contenedores organizacionales de nivel superior en el canvas. Cada sección muestra una píldora de título. El color del texto se invierte automáticamente según la luminancia del fondo. +Toda operación es deshacible — creación, eliminación, movimientos, redimensionamientos, cambios de propiedades, cambios de padre, cambios de layout, operaciones de variables. Usa un patrón de comando inverso. Z / Z. ## Documentos multi-página -Los documentos soportan múltiples páginas como Figma. El panel de páginas permite añadir, eliminar y renombrar páginas. Cada página mantiene un estado de viewport independiente. - -## Resaltado al pasar - -Los nodos se resaltan al pasar con un contorno que sigue la geometría real — las elipses obtienen contornos elípticos, los rectángulos redondeados obtienen contornos redondeados, los vectores obtienen contornos de ruta. - -## Renderizado avanzado (Tier 1) - -El renderer CanvasKit soporta las características visuales completas de Tier 1: rellenos de gradiente (lineal, radial, angular, diamante), rellenos de imagen, efectos (sombra, desenfoque), propiedades de trazo (cap, join, dash), datos de arco, culling de viewport, reutilización de Paint y coalescencia RAF. - -## Componentes e instancias - -Crea componentes reutilizables desde frames o selecciones (K). Combina componentes en un COMPONENT_SET (K). Crea instancias desde componentes vía menú contextual. Desacopla una instancia de vuelta a un frame con B. "Ir al componente principal" navega al componente fuente. - -**Sincronización en vivo:** Editar un componente principal propaga cambios a todas sus instancias automáticamente. **Soporte de overrides:** Las instancias mantienen un registro de overrides que se preservan durante la sincronización. Los componentes muestran etiquetas púrpura siempre visibles con icono de diamante. - -## Variables - -Tokens de diseño como variables con colecciones y modos. Diálogo con TanStack Table con columnas redimensionables. Soporta tipo COLOR con UI completa, tipos FLOAT/STRING/BOOLEAN definidos. Organiza variables en colecciones, define modos (ej: Claro/Oscuro). Vincula variables a colores de relleno. Cadenas de alias con detección de ciclos. Todas las operaciones de variables son deshacibles. - -## Exportación de imágenes - -Exporta nodos seleccionados como PNG, JPG o WEBP. Selección de escala (0,5×–4×), selector de formato, soporte multi-exportación y vista previa en vivo. Disponible vía menú contextual y E. - -## Menú contextual - -Clic derecho en el canvas abre un menú contextual estilo Figma con acciones de: Portapapeles, Orden Z, Agrupación, Componentes (ítems púrpura), Visibilidad y Mover a página. - -## Orden Z, visibilidad y bloqueo - -] trae nodos al frente, [ envía al fondo. H alterna visibilidad. L alterna bloqueo. Mover nodos entre páginas vía submenú "Mover a página". - -## App web y de escritorio - -OpenPencil funciona en el navegador en [app.openpencil.dev](https://app.openpencil.dev) — sin instalación requerida. La app de escritorio usa Tauri v2 (~5 MB vs ~100 MB de Electron). Funciona completamente offline. Menú nativo en todas las plataformas. Herramientas de desarrollador accesibles vía I. - -## Menú de app (navegador) - -En modo navegador, una barra de menú con reka-ui Menubar proporciona acceso a todas las acciones principales del editor. Seis menús: **Archivo**, **Editar**, **Ver**, **Objeto**, **Texto**, **Organizar**. Los atajos de teclado se muestran junto a cada ítem con etiquetas de modificador según la plataforma. Oculto en Tauri, que proporciona sus propios menús nativos. - -## Autoguardado - -Los archivos se guardan automáticamente 3 segundos después del último cambio de escena. Un watcher con debounce monitorea `sceneVersion`. Usa el plugin fs de Tauri en escritorio o la API File System Access en navegadores compatibles. El autoguardado está deshabilitado para documentos nuevos sin título hasta que el usuario realice un Guardar como explícito. - -## Colaboración P2P - -Colaboración peer-to-peer en tiempo real — sin servidor requerido. Comparte un enlace y edita junto. Basado en Trystero (WebRTC) para conexiones directas entre pares y Yjs (CRDT) para sincronización de documentos sin conflictos. - -- **Zero costes de hosting** — señalización vía brokers MQTT públicos, datos fluyen directamente entre pares -- **Traversal NAT** — servidores Google STUN, Cloudflare STUN y Open Relay TURN -- **Cursores en vivo** — flechas de cursor coloreadas estilo Figma con borde blanco y píldoras de nombre -- **Presencia** — ve quién está en la sala con avatares coloreados -- **Modo seguimiento** — clic en el avatar de un par para seguir su viewport en tiempo real -- **Persistencia local** — y-indexeddb mantiene la sala entre recargas de página -- **Salas seguras** — IDs generados con `crypto.getRandomValues()` +Añadir, eliminar, renombrar páginas. Cada página tiene estado de viewport independiente. Doble clic para renombrar en línea. ## Pestañas multi-archivo -Abre múltiples documentos en pestañas dentro de una sola ventana. La barra de pestañas muestra archivos abiertos con botones de cierre. Clic medio en una pestaña para cerrarla. N o T — nueva pestaña, W — cerrar pestaña actual, O — abrir archivo en nueva pestaña. +Abre múltiples documentos en pestañas. T nueva pestaña, W cerrar, O abrir archivo. -## Renderizado de efectos +## Exportación -Renderizado completo de efectos Figma vía CanvasKit: **Sombra paralela** (offset, radio de desenfoque, extensión, color), **Sombra interior**, **Desenfoque de capa** (Gaussiano), **Desenfoque de fondo** (efecto cristal/esmerilado), **Desenfoque de primer plano**. Las sombras de texto se renderizan en glifos individuales. Cache SkPicture por nodo para rendimiento. +- **Imagen** — PNG, JPG, WEBP a escala configurable (0,5×–4×). Vía panel, menú contextual, o E +- **SVG** — formas, texto con style runs, gradientes, efectos, modos de mezcla +- **Tailwind JSX** — HTML con clases de utilidad Tailwind v4, listo para React o Vue +- **Copiar como** — texto, SVG, PNG (C), o JSX vía menú contextual -## Propiedades multi-selección - -Selecciona múltiples nodos y edita propiedades compartidas a la vez. Los valores compartidos se muestran normalmente, los valores diferentes muestran "Mixed". Las entradas de ancho y alto funcionan a través de la selección. Voltear H/V se aplica a todos los nodos seleccionados. - -## ScrubInput - -Todas las entradas numéricas en el panel de propiedades usan interacción de arrastre para ajustar — arrastra horizontalmente para ajustar el valor, o haz clic para escribir directamente. Soporta sufijos (°, px, %). - -## Builds CI/CD - -GitHub Actions construye apps Tauri nativas en tags de versión. La matriz cubre macOS (arm64, x64), Windows (x64, arm64) y Linux (x64). Los builds de macOS están firmados y notarizados vía certificados Apple Developer. Las notas de release se auto-rellenan desde CHANGELOG.md. - -## @open-pencil/core y CLI - -El motor está extraído en `packages/core/` (@open-pencil/core) — sin dependencias DOM. El CLI (`packages/cli/`) proporciona operaciones headless .fig: info, tree, find, export, analyze (colors, typography, spacing, clusters), node, pages, variables, eval. Todos los comandos soportan `--json`. - -El comando `eval` ejecuta JavaScript contra un archivo `.fig` con un objeto `figma` global compatible con Figma. Véase [Comando Eval](/eval-command) para la referencia completa. - -## Renderizador JSX - -Creación programática de diseño vía funciones TreeNode builder exportadas desde `@open-pencil/core`. Soporta props shorthand estilo Tailwind — `w`, `h`, `bg`, `rounded`, `flex`, `gap`, `p`/`px`/`py`. +CLI: `open-pencil export design.fig -f jsx --style tailwind` ## Chat IA -Asistente IA integrado accesible vía la pestaña IA o J. Comunica directamente con OpenRouter — sin servidor backend requerido. +Pulsa J para abrir el asistente IA. 87 herramientas que pueden crear formas, aplicar estilos, gestionar layout, trabajar con componentes y variables, ejecutar operaciones booleanas, analizar tokens de diseño y exportar assets. Trae tu propia clave API de OpenRouter. -**87 herramientas** definidas en `packages/core/src/tools/`, cubriendo: operaciones de lectura, creación, modificación, manipulación de nodos, CRUD de variables, herramientas de rutas vectoriales, control de viewport y un escape hatch `eval`. Las herramientas están conectadas al chat IA (schemas valibot), servidor MCP (schemas zod) y CLI (comando `eval`). +Las llamadas a herramientas se muestran como entradas colapsables en una línea de tiempo. Selector de modelo con Claude, Gemini, GPT, DeepSeek y otros. -**AI agent skill** — `npx skills add open-pencil/skills@open-pencil` — teaches AI coding agents to use the CLI, MCP tools, and automation bridge. Source: [open-pencil/skills](https://github.com/open-pencil/skills). +## Servidor MCP -**Servidor MCP** (`packages/mcp/`) expone todas las herramientas para herramientas de codificación IA externas. Dos transportes: stdio y HTTP con Hono. Añade 3 herramientas de gestión de archivos sobre las 87 herramientas core (= 90 en total). +Conecta Claude Code, Cursor, Windsurf, o cualquier cliente MCP para leer y escribir archivos `.fig` de forma headless. 90 herramientas (87 core + 3 de gestión de archivos). Dos transportes: stdio y HTTP. -## Exportación SVG +```sh +bun add -g @open-pencil/mcp +``` -Exporta nodos seleccionados como PNG, JPG, WEBP o SVG. CLI: `bun open-pencil export --format svg file.fig`. +```json +{ + "mcpServers": { + "open-pencil": { + "command": "openpencil-mcp" + } + } +} +``` -## Copiar como +Consulta la [referencia de herramientas MCP](/reference/mcp-tools) para la lista completa. -El submenú **Copiar como** del menú contextual ofrece: Copiar como texto, SVG, PNG (C), JSX. +## CLI -## Alineación de trazo y pesos por lado +Inspecciona, exporta y analiza archivos `.fig` desde el terminal: -Alineación: **Interior**, **Centro** o **Exterior**. Pesos individuales por lado (Arriba/Derecha/Abajo/Izquierda) mediante el selector de lados. +```sh +open-pencil tree design.fig # Árbol de nodos +open-pencil find design.fig --type TEXT # Buscar +open-pencil export design.fig -f png # Renderizar +open-pencil analyze colors design.fig # Auditoría de colores +open-pencil analyze clusters design.fig # Patrones repetidos +open-pencil eval design.fig -c "..." # Figma Plugin API +``` -## Layout móvil & PWA +Cuando la app de escritorio está en ejecución, omite el archivo para controlar el editor en vivo vía RPC: -Instalable como PWA. En móvil, paneles laterales reemplazados por cajón inferior deslizable con pestañas. +```sh +open-pencil tree # Documento en vivo +open-pencil export -f png # Captura del canvas +``` -## Exportación Tailwind CSS v4 +Todos los comandos soportan `--json`. Instalar: `bun add -g @open-pencil/cli` -La pestaña Código ofrece alternancia entre **OpenPencil JSX** y **Tailwind CSS v4** (HTML con clases de utilidad). +## Colaboración en tiempo real -## Google Fonts Fallback +P2P vía WebRTC — sin servidor requerido. Comparte un enlace y edita junto. -Cuando una fuente no está disponible localmente, OpenPencil la carga automáticamente de Google Fonts API. +- Cursores en vivo con flechas de colores y píldoras de nombre +- Avatares de presencia +- Modo seguimiento — clic en un par para seguir su viewport +- Persistencia local vía IndexedDB +- IDs de sala seguros vía `crypto.getRandomValues()` -## Homebrew Tap +## Escritorio y web -En macOS: `brew install open-pencil/tap/open-pencil` +**Escritorio** — Tauri v2, ~7 MB. macOS (firmado y notarizado), Windows, Linux. Menús nativos, offline, autoguardado. -## Renombrar capas inline +**Web** — funciona en [app.openpencil.dev](https://app.openpencil.dev), instalable como PWA en móvil con interfaz optimizada para táctil. -Doble clic en el nombre de una capa para renombrarla. Enter o clic fuera confirma, Escape cancela. +**Homebrew:** -## Profiler de renderizado +```sh +brew install open-pencil/tap/open-pencil +``` -Superposición HUD con métricas de tiempo de renderizado. Accesible desde el menú Vista. +## Fallback de Google Fonts -## Panel de código - -La pestaña Código muestra la representación JSX de la selección actual con resaltado de sintaxis Prism.js y botón de copia al portapapeles. - -## Calidad de código - -Detección de copia-pega vía jscpd — duplicación reducida de 15,6% a 0,62%. Pipeline de importación .fig optimizado de O(n²) a O(n). +Cuando una fuente no está disponible localmente, OpenPencil la carga automáticamente desde Google Fonts. No requiere instalación manual al abrir archivos .fig con fuentes desconocidas. diff --git a/packages/docs/es/index.md b/packages/docs/es/index.md index a26041ec3..996380c46 100644 --- a/packages/docs/es/index.md +++ b/packages/docs/es/index.md @@ -1,16 +1,16 @@ --- layout: home -title: OpenPencil — Editor de Diseño IA-Nativo -description: Alternativa open-source a Figma. Completamente local, IA-nativa, programable. +title: OpenPencil — Editor de Diseño Open-Source +description: Alternativa open-source a Figma. Abre archivos .fig, IA integrada, completamente programable. hero: name: OpenPencil - text: Editor de diseño IA-nativo - tagline: Alternativa open-source a Figma. Completamente local, IA-nativa, programable. + text: Editor de Diseño Open-Source + tagline: Abre archivos de Figma. IA integrada. Completamente programable. Gratis para siempre. actions: - theme: brand text: Probar en línea - link: https://app.openpencil.dev + link: https://app.openpencil.dev/demo - theme: alt text: Descargar link: https://github.com/open-pencil/open-pencil/releases/latest @@ -19,19 +19,22 @@ hero: link: https://github.com/open-pencil/open-pencil features: - - icon: 📖 - title: Código abierto - details: Licencia MIT. Lee y modifica todo — el editor, el motor, el códec de archivos. - icon: 📂 title: Compatible con Figma - details: Abre archivos .fig nativamente. Copiar/pegar entre aplicaciones. Códec Kiwi con fidelidad de ida y vuelta. - - icon: 🤖 - title: IA-nativo - details: Chat integrado con uso de herramientas. Trae tu propia clave API — sin suscripción, sin dependencia de proveedor. - - icon: 🖥️ - title: Sin suscripción - details: Sin cuenta, sin servidor, sin internet. Gratis para siempre. Aplicación de escritorio ~5 MB. + details: Abre archivos .fig nativamente. Copiar y pegar entre Figma y OpenPencil. Códec binario Kiwi con fidelidad de ida y vuelta. - icon: ⚡ title: Programable - details: CLI headless para inspección y exportación de .fig. Cada operación es scriptable. Renderer JSX. + details: CLI headless para inspeccionar, exportar y analizar archivos .fig. Figma Plugin API vía eval. Exportación Tailwind CSS. Salida JSON para CI. + - icon: 🤖 + title: IA-Nativo + details: Chat integrado con 90 herramientas — crear formas, aplicar estilos, gestionar layout, analizar tokens. Servidor MCP para Claude Code, Cursor, Windsurf. + - icon: 📖 + title: Código Abierto + details: Licencia MIT. Lee y modifica todo — el editor, el motor, el códec de archivos, el CLI. + - icon: 🖥️ + title: Gratis y Local + details: Sin cuenta, sin servidor, sin internet. App de escritorio de ~7 MB vía Homebrew, o usa la app web. + - icon: 👥 + title: Colaboración en Tiempo Real + details: P2P vía WebRTC — sin servidor. Comparte un enlace, edita junto con cursores en vivo y modo seguimiento. --- diff --git a/packages/docs/fr/guide/architecture.md b/packages/docs/fr/guide/architecture.md index 59f479458..5bcd19c4a 100644 --- a/packages/docs/fr/guide/architecture.md +++ b/packages/docs/fr/guide/architecture.md @@ -2,42 +2,33 @@ ## Vue d'ensemble du système -``` -┌──────────────────────────────────────────────────────────────────┐ -│ Tauri v2 Shell │ -│ │ -│ ┌────────────────────────────────────────────────────────────┐ │ -│ │ Éditeur (Web) │ │ -│ │ │ │ -│ │ Vue 3 UI Skia CanvasKit (WASM, 7MB) │ │ -│ │ - Barre d'outils - Rendu vectoriel │ │ -│ │ - Panneaux - Mise en forme du texte │ │ -│ │ - Propriétés - Traitement d'images │ │ -│ │ - Calques - Effets (flou, ombre) │ │ -│ │ - Sélecteur de couleur - Export (PNG, SVG, PDF) │ │ -│ │ │ │ -│ │ ┌──────────────────────────────────────────────────────┐ │ │ -│ │ │ Core Engine (TS) │ │ │ -│ │ │ SceneGraph ─── Layout (Yoga) ─── Selection │ │ │ -│ │ │ │ │ │ │ │ -│ │ │ Undo/Redo ─── Constraints ─── Hit Testing │ │ │ -│ │ └──────────────────────────────────────────────────────┘ │ │ -│ │ │ │ -│ │ ┌──────────────────────────────────────────────────────┐ │ │ -│ │ │ Couche de format de fichier │ │ │ -│ │ │ .fig import/export ── Kiwi codec ── .svg (prévu) │ │ │ -│ │ └──────────────────────────────────────────────────────┘ │ │ -│ └────────────────────────────────────────────────────────────┘ │ -│ │ -│ MCP Server (75+ tools, stdio+HTTP) P2P Collab (Trystero + Yjs) │ -└──────────────────────────────────────────────────────────────────┘ +```mermaid +graph TB + subgraph Tauri["Tauri v2 Shell"] + subgraph Editor["Editor (Web)"] + UI["Vue 3 UI
Toolbar · Panels · Properties
Layers · Color Picker"] + Skia["Skia CanvasKit (WASM, 7MB)
Vector rendering · Text shaping
Effects · Export"] + subgraph Core["Core Engine (TS)"] + SG[SceneGraph] --- Layout[Layout - Yoga] + SG --- Selection + Undo[Undo/Redo] --- Constraints + Constraints --- HitTest[Hit Testing] + end + subgraph FileFormat["File Format Layer"] + FigIO[".fig import/export"] --- Kiwi[Kiwi codec] + Kiwi --- SVG[SVG export] + end + end + MCP["MCP Server (90 tools, stdio+HTTP)"] + Collab["P2P Collab (Trystero + Yjs)"] + end ``` ## Disposition de l'éditeur L'interface suit le layout UI3 de Figma — barre d'outils en bas, navigation à gauche, propriétés à droite : -- **Panneau de navigation (gauche)** — Arbre des calques, panneau des pages, bibliothèque d'assets (prévu) +- **Panneau de navigation (gauche)** — Arbre des calques, panneau des pages - **Canvas (centre)** — Canvas infini avec rendu CanvasKit, zoom/pan - **Panneau de propriétés (droite)** — Sections contextuelles : Apparence, Remplissage, Contour, Typographie, Layout, Position - **Barre d'outils (bas)** — Sélection d'outil : Sélectionner, Frame, Section, Rectangle, Ellipse, Ligne, Texte, Plume, Main @@ -46,19 +37,15 @@ L'interface suit le layout UI3 de Figma — barre d'outils en bas, navigation à ### Rendu (CanvasKit WASM) -Le même moteur de rendu que Figma. CanvasKit fournit un dessin 2D accéléré par GPU avec : -- Formes vectorielles (rectangle, ellipse, chemin, ligne, étoile, polygone) -- Mise en forme du texte via Paragraph API -- Effets (ombres, flous, modes de fusion) -- Export (PNG, SVG, PDF) +Le même moteur de rendu que Figma. CanvasKit fournit un dessin 2D accéléré par GPU avec formes vectorielles, mise en forme du texte via Paragraph API, effets (ombres, flous, modes de fusion) et export (PNG, SVG). Le binaire WASM de 7 Mo se charge au démarrage et crée une surface GPU sur le canvas HTML. -Le binaire WASM de 7 Mo se charge au démarrage et crée une surface GPU sur le canvas HTML. +Le renderer est découpé en modules spécialisés dans `packages/core/src/renderer/` : parcours de scène, overlays, remplissages, contours, formes, effets, règles, étiquettes et curseurs distants. ### Graphe de scène `Map` plat indexé par des chaînes GUID. Structure en arbre via des références `parentIndex`. Fournit une recherche O(1), un parcours efficace, du hit testing et des requêtes par zone rectangulaire pour la sélection par marquise. -Voir [Référence du graphe de scène](/reference/scene-graph) pour les détails internes. +Voir la [Référence du graphe de scène](/reference/scene-graph) pour les détails internes. ### Moteur de layout (Yoga WASM) @@ -75,9 +62,19 @@ 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 éprouvé de Figma avec 194 définitions de message/enum/struct. Pipeline d'importation `.fig` : analyser l'en-tête → décompresser Zstd → décoder Kiwi → NodeChange[] → graphe de scène. Le pipeline d'exportation inverse le processus : graphe de scène → NodeChange[] → encoder Kiwi → compresser Zstd → ZIP avec 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 [Référence du format de fichier](/reference/file-format) pour plus de détails. +Voir la [Référence du format de fichier](/reference/file-format) pour plus de détails. + +### IA et outils + +Les outils sont définis une seule fois dans `packages/core/src/tools/`, découpés par domaine : read, create, modify, structure, variables, vector, analyze. Chaque outil a des paramètres typés et une fonction `execute(figma, args)`. Les adaptateurs les convertissent pour : + +- **Chat IA** — schémas valibot, connecté à OpenRouter +- **Serveur MCP** — schémas zod, transports stdio + HTTP +- **CLI** — accessible via la commande `eval` + +87 outils core + 3 outils de gestion de fichiers MCP = 90 au total. ### Annuler/Rétablir @@ -85,12 +82,34 @@ Patron de commande inverse. Avant d'appliquer tout changement, les champs concer ### Presse-papiers -Presse-papiers bidirectionnel compatible Figma. Encode/décode le binaire Kiwi (même format que les fichiers .fig) en utilisant les événements natifs copier/coller du navigateur (synchrones, pas l'API asynchrone du Clipboard). Le collage gère le redimensionnement des chemins vectoriels, le peuplement des enfants d'instances, la détection des ensembles de composants et l'application des surcharges. - -### Serveur MCP - -`@open-pencil/mcp` expose 87 outils core + 3 outils de gestion de fichiers pour les outils de codage IA. Deux transports : stdio pour Claude Code/Cursor/Windsurf, HTTP avec Hono + Streamable HTTP pour les scripts et le CI. Les outils sont définis une fois dans `packages/core/src/tools/` et adaptés pour le chat IA (valibot), MCP (zod) et CLI (commande eval). +Presse-papiers bidirectionnel compatible Figma. Encode/décode le binaire Kiwi (même format que les fichiers .fig) via les événements natifs copier/coller du navigateur. Gère le redimensionnement des chemins vectoriels, les enfants d'instances, la détection des ensembles de composants et l'application des surcharges. ### Collaboration P2P Collaboration peer-to-peer en temps réel via Trystero (WebRTC) + Yjs CRDT. Sans serveur relais — signalisation via des brokers MQTT publics, STUN/TURN pour le traversal NAT. Le protocole d'awareness fournit des curseurs en direct, des sélections et de la présence. Persistance locale via y-indexeddb. + +### Pont RPC CLI-vers-application + +Lorsque l'application de bureau est lancée, les commandes CLI s'y connectent via WebSocket au lieu de nécessiter un fichier .fig. Le serveur d'automatisation tourne sur `127.0.0.1:7600` (HTTP) et `127.0.0.1:7601` (WebSocket). Les commandes s'exécutent sur l'état en direct de l'éditeur, permettant aux scripts d'automatisation et aux agents IA d'interagir avec l'application en cours d'exécution. + +## Prochaines étapes + +### Ensemble complet d'outils figma-use + +Le serveur MCP expose actuellement 90 outils. L'implémentation de référence dans [figma-use](https://github.com/dannote/figma-use) en compte 118. Les outils restants couvrent les contraintes de layout avancées, les connexions de prototype, l'édition avancée des propriétés de composants et les opérations en masse sur les documents. + +### Outillage de design pour la CI + +Le CLI headless supporte déjà `analyze colors/typography/spacing/clusters`. Prochaine étape : intégration GitHub Actions pour le linting de design automatisé et la régression visuelle dans les PRs. + +### Prototypage + +Transitions frame-à-frame, déclencheurs d'interaction (clic, survol, glissement), gestion des overlays et mode aperçu plein écran. + +### 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. + +### Signature de code Windows + +Les binaires macOS sont signés et notarisés depuis la v0.6.0. La signature Authenticode Windows via Azure Code Signing est prévue pour supprimer l'avertissement SmartScreen. diff --git a/packages/docs/fr/guide/features.md b/packages/docs/fr/guide/features.md index 570507fb9..819160621 100644 --- a/packages/docs/fr/guide/features.md +++ b/packages/docs/fr/guide/features.md @@ -1,201 +1,138 @@ # Fonctionnalités -## Pourquoi OpenPencil +## Fichiers .fig Figma -Les outils de design sont un problème de chaîne d'approvisionnement. Quand votre outil est propriétaire, l'éditeur contrôle ce qui est possible — il peut casser votre automatisation du jour au lendemain. OpenPencil est une alternative open-source : licence MIT, compatible Figma, entièrement local et programmable. +Ouvrez et enregistrez les fichiers natifs Figma directement. Le pipeline d'import/export utilise le même codec binaire Kiwi que Figma — 194 définitions de schéma, ~390 champs par nœud. Enregistrer avec S, Enregistrer sous avec S. -## Import & export de fichiers .fig Figma +**Copier-coller avec Figma** — sélectionnez des nœuds dans Figma, C, passez à OpenPencil, V. Les remplissages, contours, auto-layout, texte, effets, rayons de coins et réseaux vectoriels sont préservés. Fonctionne dans les deux sens. -Ouvrez et enregistrez les fichiers natifs Figma directement. L'import décode le schéma Kiwi complet à 194 définitions incluant les messages NodeChange avec ~390 champs. L'export encode le graphe de scène en binaire Kiwi avec compression Zstd et génération de miniature. Enregistrer (S) et Enregistrer sous (S) utilisent les dialogues natifs de l'OS sur l'app bureau. +## Dessin et édition -## Copier-coller avec Figma - -Sélectionnez des nœuds dans Figma, C, passez à OpenPencil, V — ils apparaissent avec remplissages, contours, auto-layout, texte, rayons de coins, effets et réseaux vectoriels préservés. Fonctionne aussi dans l'autre sens. - -Le collage gère les scénarios complexes : les chemins vectoriels sont redimensionnés depuis la `normalizedSize` de Figma vers les limites réelles du nœud, les enfants d'instance sont peuplés depuis le `symbolData` de leur composant, les ensembles de composants sont détectés et les `symbolOverrides` sont appliqués. Les polices sont chargées automatiquement. - -## Réseaux vectoriels - -L'outil plume utilise le modèle de réseau vectoriel de Figma — pas de chemins simples. Clic pour les points d'angle, clic+glisser pour les courbes de Bézier. Chemins ouverts et fermés supportés. - -## Outils de forme - -La barre d'outils fournit tous les outils de forme de base de Figma : Rectangle (R), Ellipse (O), Ligne (L), Polygone et Étoile. Toutes les formes supportent remplissage, contour, surbrillance au survol et contour de sélection. - -## Auto-Layout - -Yoga WASM fournit le layout CSS flexbox. Les frames supportent : direction, gap, padding, justify, align et dimensionnement des enfants. Shift+A active/désactive l'auto-layout. - -## Édition de texte en ligne - -Édition de texte native sur le canevas. Double-clic sur un nœud texte pour entrer en mode édition. **Sélecteur de polices** avec défilement virtuel, filtre de recherche et aperçu CSS. Dans Tauri, les polices système sont énumérées via le crate Rust `font-kit`. - -## Formatage de texte riche - -Formatage par caractère : B gras, I italique, U souligné, ou boutons B/I/U/S. Implémenté via un modèle StyleRun. Préservé lors de l'import/export .fig. - -## Annuler/Rétablir - -Toute opération est annulable. Patron de commande inverse. Z annule, Z rétablit. - -## Guides d'alignement - -Accrochage aux bords et centres avec lignes guides rouges. Conscient de la rotation. - -## Règles du canevas - -Règles en haut et à gauche montrant les échelles de coordonnées avec badges de coordonnées lors de la sélection. - -## Sélecteur de couleur et types de remplissage - -Sélection HSV avec curseur de teinte, curseur alpha, entrée hex et contrôle d'opacité. Types : Solide, Dégradé (Linéaire, Radial, Angulaire, Diamant) et Image. - -## Panneau des calques - -Vue en arbre de la hiérarchie du document avec le composant Reka UI Tree. Panneaux redimensionnables. +- **Formes** — Rectangle (R), Ellipse (O), Ligne (L), Polygone, Étoile +- **Outil plume** — réseaux vectoriels (pas de simples chemins), courbes de Bézier avec poignées de tangente +- **Texte** — édition native sur le canevas avec support IME, double-clic pour entrer en mode édition +- **Texte riche** — gras (B), italique (I), souligné (U), barré par caractère +- **Auto-layout** — flexbox via Yoga WASM : direction, gap, padding, justify, align, dimensionnement des enfants. A pour activer/désactiver +- **Composants** — créer (K), ensembles de composants (K), instances avec support des surcharges, synchronisation en direct +- **Variables** — tokens de design avec collections, modes (Clair/Sombre), types couleur/nombre/chaîne/booléen, liaison de variables +- **Sections** — conteneurs organisationnels avec adoption automatique des enfants et pilules de titre ## Panneau de propriétés -Interface à onglets **Design** | **Code** | **IA**. L'onglet Design montre des sections contextuelles : Apparence, Remplissage, Contour, Effets, Typographie, Layout, Position, Export et Page. +Onglets contextuels Design | Code | IA : -## Grouper/Dégrouper +- **Apparence** — opacité, rayon de coin (uniforme ou par coin), visibilité +- **Remplissage** — solide, dégradé (linéaire/radial/angulaire/diamant), image +- **Contour** — couleur, épaisseur, alignement (intérieur/centre/extérieur), épaisseurs par côté, extrémité, jointure, tirets +- **Effets** — ombre portée, ombre intérieure, flou de calque, flou d'arrière-plan, flou de premier plan +- **Typographie** — sélecteur de polices avec défilement virtuel et recherche, graisse, taille, alignement, boutons de style +- **Layout** — contrôles d'auto-layout lorsqu'activé +- **Export** — échelle, format (PNG/JPG/WEBP/SVG), aperçu en direct -⌘G groupe. ⇧⌘G dégroupe. Les nœuds sont triés par position visuelle. +## Rendu -## Sections +Skia (CanvasKit WASM) — le même moteur de rendu que Figma : -Les sections (S) sont des conteneurs organisationnels de niveau supérieur sur le canevas avec des pilules de titre et inversion automatique de la couleur du texte. +- Remplissages dégradés (linéaire, radial, angulaire, diamant) +- Remplissages d'images avec modes de mise à l'échelle +- Effets avec cache par nœud +- Données d'arc (ellipses partielles, anneaux) +- Culling de viewport et réutilisation de Paint +- Guides d'accrochage avec alignement tenant compte de la rotation +- Règles du canevas avec badges de sélection +- Surbrillance au survol suivant la géométrie réelle + +## Annuler/Rétablir + +Chaque opération est annulable — création, suppression, déplacements, redimensionnements, changements de propriétés, re-parentage, changements de layout, opérations sur les variables. Utilise un patron de commande inverse. Z / Z. ## Documents multi-pages -Les documents supportent plusieurs pages. Chaque page maintient un état de viewport indépendant. - -## Surbrillance au survol - -Les nœuds se mettent en surbrillance avec un contour qui suit la géométrie réelle. - -## Rendu avancé (Tier 1) - -Le renderer CanvasKit supporte les fonctionnalités visuelles Tier 1 complètes : dégradés, remplissages d'images, effets, propriétés de contour, données d'arc, culling de viewport, réutilisation de Paint et coalescence RAF. - -## Composants et instances - -Composants réutilisables (K), ensembles (K), instances via menu contextuel, détacher (B). **Sync en direct** et **support des surcharges**. Étiquettes violettes avec icône diamant. - -## Variables - -Jetons de design avec collections et modes. Dialogue TanStack Table. Supporte COLOR avec UI complète, FLOAT/STRING/BOOLEAN définis. Toutes les opérations sont annulables. - -## Export d'images - -PNG, JPG, WEBP avec échelle 0,5×–4×, aperçu en direct et E. - -## Menu contextuel - -Clic droit pour : Presse-papiers, Ordre Z, Groupement, Composants (items violets), Visibilité, Déplacer vers page. - -## Ordre Z, visibilité et verrouillage - -] amène au premier plan, [ envoie en arrière. H visibilité. L verrouillage. - -## App web et bureau - -OpenPencil fonctionne dans le navigateur sur [app.openpencil.dev](https://app.openpencil.dev). L'app bureau utilise Tauri v2 (~5 Mo). Fonctionne entièrement hors ligne. - -## Menu de l'app (navigateur) - -Barre de menus avec reka-ui : **Fichier**, **Édition**, **Affichage**, **Objet**, **Texte**, **Disposition**. Raccourcis clavier adaptés à la plateforme. Caché dans Tauri. - -## Sauvegarde automatique - -Fichiers sauvegardés 3 secondes après le dernier changement. Debounce sur `sceneVersion`. Désactivé pour les nouveaux documents sans titre. - -## Collaboration P2P - -Collaboration peer-to-peer en temps réel — aucun serveur requis. Basé sur Trystero (WebRTC) + Yjs (CRDT). - -- **Zéro coût d'hébergement** — signalisation via brokers MQTT publics -- **Traversal NAT** — serveurs Google STUN, Cloudflare STUN et Open Relay TURN -- **Curseurs en direct** — flèches colorées style Figma avec pilules de nom -- **Présence** — avatars colorés -- **Mode suivi** — cliquez sur l'avatar d'un pair pour suivre son viewport -- **Persistance locale** — y-indexeddb maintient la salle entre les rechargements -- **Salles sécurisées** — IDs via `crypto.getRandomValues()` +Ajouter, supprimer, renommer des pages. Chaque page a un état de viewport indépendant. Double-clic pour renommer en ligne. ## Onglets multi-fichiers -Ouvrez plusieurs documents en onglets. N/T nouvel onglet, W fermer, O ouvrir dans un nouvel onglet. Chaque onglet maintient son propre état de document. +Ouvrez plusieurs documents en onglets. T nouvel onglet, W fermer, O ouvrir un fichier. -## Rendu des effets +## Export -Rendu complet des effets Figma : **Ombre portée**, **Ombre intérieure**, **Flou de calque** (Gaussien), **Flou d'arrière-plan** (effet verre/givre), **Flou de premier plan**. Cache SkPicture par nœud pour la performance. +- **Image** — PNG, JPG, WEBP à échelle configurable (0,5×–4×). Via le panneau, le menu contextuel ou E +- **SVG** — formes, texte avec style runs, dégradés, effets, modes de fusion +- **Tailwind JSX** — HTML avec classes utilitaires Tailwind v4, prêt pour React ou Vue +- **Copier en tant que** — texte, SVG, PNG (C), ou JSX via le menu contextuel -## Propriétés multi-sélection - -Sélectionnez plusieurs nœuds et éditez les propriétés partagées. Valeurs communes affichées normalement, valeurs différentes montrent « Mixed ». Retournement H/V s'applique à tous les nœuds. - -## ScrubInput - -Toutes les entrées numériques utilisent une interaction glisser-pour-ajuster. Supporte les suffixes (°, px, %). - -## Builds CI/CD - -GitHub Actions construit les apps Tauri sur les tags de version. macOS signé et notarisé. Notes de release auto-remplies depuis CHANGELOG.md. - -## @open-pencil/core et CLI - -Le moteur est extrait dans `packages/core/`. Le CLI fournit : info, tree, find, export, analyze, node, pages, variables, eval. Tous supportent `--json`. Le commande `eval` exécute JavaScript avec l'API Plugin Figma. Voir [Commande Eval](/eval-command). - -## Rendereur JSX - -Création programmable via TreeNode builders. Props shorthand style Tailwind. +CLI : `open-pencil export design.fig -f jsx --style tailwind` ## Chat IA -Assistant IA intégré via J. **87 outils** dans `packages/core/src/tools/` couvrant lecture, création, modification, manipulation de nœuds, CRUD variables, outils vectoriels, contrôle viewport et `eval`. **Serveur MCP** expose 90 outils au total (87 core + 3 gestion fichiers) pour les outils de codage IA externes. +Appuyez sur J pour ouvrir l'assistant IA. 87 outils qui peuvent créer des formes, définir des styles, gérer le layout, travailler avec les composants et variables, exécuter des opérations booléennes, analyser les tokens de design et exporter des assets. Apportez votre propre clé API OpenRouter. -**AI agent skill** — `npx skills add open-pencil/skills@open-pencil` — teaches AI coding agents to use the CLI, MCP tools, and automation bridge. Source: [open-pencil/skills](https://github.com/open-pencil/skills). +Les appels d'outils s'affichent comme des entrées de chronologie dépliables. Sélecteur de modèle avec Claude, Gemini, GPT, DeepSeek et d'autres. -## Export SVG +## Serveur MCP -Exporte les nœuds sélectionnés en PNG, JPG, WEBP ou SVG. CLI : `bun open-pencil export --format svg file.fig`. +Connectez Claude Code, Cursor, Windsurf ou tout client MCP pour lire et écrire des fichiers `.fig` en mode headless. 90 outils (87 core + 3 gestion de fichiers). Deux transports : stdio et HTTP. -## Copier en tant que +```sh +bun add -g @open-pencil/mcp +``` -Le sous-menu **Copier en tant que** du menu contextuel propose : Copier en tant que texte, SVG, PNG (C), JSX. +```json +{ + "mcpServers": { + "open-pencil": { + "command": "openpencil-mcp" + } + } +} +``` -## Alignement du contour & épaisseurs par côté +Voir la [référence des outils MCP](/reference/mcp-tools) pour la liste complète. -Alignement : **Intérieur**, **Centre** ou **Extérieur**. Épaisseurs individuelles par côté (Haut/Droite/Bas/Gauche). +## CLI -## Layout mobile & PWA +Inspectez, exportez et analysez les fichiers `.fig` depuis le terminal : -Installable en PWA. Sur mobile, panneaux latéraux remplacés par un tiroir inférieur glissable avec onglets. +```sh +open-pencil tree design.fig # Arbre de nœuds +open-pencil find design.fig --type TEXT # Recherche +open-pencil export design.fig -f png # Rendu +open-pencil analyze colors design.fig # Audit des couleurs +open-pencil analyze clusters design.fig # Motifs répétés +open-pencil eval design.fig -c "..." # API Plugin Figma +``` -## Export Tailwind CSS v4 +Lorsque l'application de bureau est lancée, omettez le fichier pour contrôler l'éditeur en direct via RPC : -L'onglet Code propose un basculement entre **OpenPencil JSX** et **Tailwind CSS v4** (HTML avec classes utilitaires). +```sh +open-pencil tree # Document en direct +open-pencil export -f png # Capture du canevas +``` -## Google Fonts Fallback +Toutes les commandes supportent `--json`. Installation : `bun add -g @open-pencil/cli` -Si une police n'est pas disponible localement, OpenPencil la charge automatiquement depuis Google Fonts API. +## Collaboration en temps réel -## Homebrew Tap +P2P via WebRTC — aucun serveur requis. Partagez un lien et éditez ensemble. -Sur macOS : `brew install open-pencil/tap/open-pencil` +- Curseurs en direct avec flèches colorées et pilules de nom +- Avatars de présence +- Mode suivi — cliquez sur un pair pour suivre son viewport +- Persistance locale via IndexedDB +- IDs de salle sécurisés via `crypto.getRandomValues()` -## Renommage inline des calques +## Bureau et web -Double-clic sur le nom d'un calque pour le renommer. Entrée ou clic ailleurs valide, Échap annule. +**Bureau** — Tauri v2, ~7 Mo. macOS (signé et notarisé), Windows, Linux. Menus natifs, hors ligne, sauvegarde automatique. -## Profileur de rendu +**Web** — disponible sur [app.openpencil.dev](https://app.openpencil.dev), installable en PWA sur mobile avec interface tactile optimisée. -Superposition HUD avec métriques de timing. Accessible via le menu Affichage. +**Homebrew :** -## Panneau de code +```sh +brew install open-pencil/tap/open-pencil +``` -L'onglet Code montre le JSX de la sélection avec coloration syntaxique Prism.js et copie. +## Polices Google Fonts en secours -## Qualité de code - -Détection de copier-coller via jscpd — duplication réduite de 15,6% à 0,62%. Pipeline d'import optimisé de O(n²) à O(n). +Lorsqu'une police n'est pas disponible localement, OpenPencil la récupère automatiquement depuis Google Fonts. Aucune installation manuelle nécessaire lors de l'ouverture de fichiers .fig avec des polices inconnues. diff --git a/packages/docs/fr/index.md b/packages/docs/fr/index.md index 3f5827ec5..2f5033ae3 100644 --- a/packages/docs/fr/index.md +++ b/packages/docs/fr/index.md @@ -1,16 +1,16 @@ --- layout: home -title: OpenPencil — Éditeur de Design IA-Natif -description: Alternative open-source à Figma. Entièrement local, IA-native, programmable. +title: OpenPencil — Éditeur de Design Open Source +description: Alternative open-source à Figma. Ouvre les fichiers .fig, IA intégrée, entièrement programmable. hero: name: OpenPencil - text: Éditeur de design IA-natif - tagline: Alternative open-source à Figma. Entièrement local, IA-native, programmable. + text: Éditeur de Design Open Source + tagline: Ouvre les fichiers Figma. IA intégrée. Entièrement programmable. Gratuit pour toujours. actions: - theme: brand text: Essayer en ligne - link: https://app.openpencil.dev + link: https://app.openpencil.dev/demo - theme: alt text: Télécharger link: https://github.com/open-pencil/open-pencil/releases/latest @@ -19,19 +19,22 @@ hero: link: https://github.com/open-pencil/open-pencil features: - - icon: 📖 - title: Open Source - details: Licence MIT. Lisez et modifiez tout — l'éditeur, le moteur, le codec de fichiers. - icon: 📂 title: Compatible Figma - details: Ouvre les fichiers .fig nativement. Copier/coller entre les applications. Codec Kiwi avec fidélité aller-retour. - - icon: 🤖 - title: IA-natif - details: Chat intégré avec utilisation d'outils. Apportez votre propre clé API — pas d'abonnement, pas de dépendance fournisseur. - - icon: 🖥️ - title: Sans abonnement - details: Pas de compte, pas de serveur, pas d'internet requis. Gratuit pour toujours. Application de bureau ~5 Mo. + details: Ouvre les fichiers .fig nativement. Copier-coller entre Figma et OpenPencil. Codec binaire Kiwi avec fidélité aller-retour. - icon: ⚡ title: Programmable - details: CLI headless pour l'inspection et l'export .fig. Chaque opération est scriptable. Renderer JSX. + details: CLI headless pour inspecter, exporter et analyser les fichiers .fig. API Plugin Figma via eval. Export Tailwind CSS. Sortie JSON pour la CI. + - icon: 🤖 + title: IA-natif + details: Chat intégré avec 90 outils — créer des formes, définir des styles, gérer le layout, analyser les tokens. Serveur MCP pour Claude Code, Cursor, Windsurf. + - icon: 📖 + title: Open Source + details: Licence MIT. Lisez et modifiez tout — l'éditeur, le moteur, le codec de fichiers, le CLI. + - icon: 🖥️ + title: Gratuit et local + details: Pas de compte, pas de serveur, pas d'internet requis. Application de bureau ~7 Mo via Homebrew, ou utilisez l'app web. + - icon: 👥 + title: Collaboration en temps réel + details: P2P via WebRTC — aucun serveur. Partagez un lien, éditez ensemble avec curseurs en direct et mode suivi. --- diff --git a/packages/docs/guide/architecture.md b/packages/docs/guide/architecture.md index ddf755d48..2c8cca9ff 100644 --- a/packages/docs/guide/architecture.md +++ b/packages/docs/guide/architecture.md @@ -2,42 +2,33 @@ ## System Overview -``` -┌──────────────────────────────────────────────────────────────────┐ -│ Tauri v2 Shell │ -│ │ -│ ┌────────────────────────────────────────────────────────────┐ │ -│ │ Editor (Web) │ │ -│ │ │ │ -│ │ Vue 3 UI Skia CanvasKit (WASM, 7MB) │ │ -│ │ - Toolbar - Vector rendering │ │ -│ │ - Panels - Text shaping │ │ -│ │ - Properties - Image processing │ │ -│ │ - Layers - Effects (blur, shadow) │ │ -│ │ - Color Picker - Export (PNG, SVG, PDF) │ │ -│ │ │ │ -│ │ ┌──────────────────────────────────────────────────────┐ │ │ -│ │ │ Core Engine (TS) │ │ │ -│ │ │ SceneGraph ─── Layout (Yoga) ─── Selection │ │ │ -│ │ │ │ │ │ │ │ -│ │ │ Undo/Redo ─── Constraints ─── Hit Testing │ │ │ -│ │ └──────────────────────────────────────────────────────┘ │ │ -│ │ │ │ -│ │ ┌──────────────────────────────────────────────────────┐ │ │ -│ │ │ File Format Layer │ │ │ -│ │ │ .fig import/export ── Kiwi codec ── .svg (planned) │ │ │ -│ │ └──────────────────────────────────────────────────────┘ │ │ -│ └────────────────────────────────────────────────────────────┘ │ -│ │ -│ MCP Server (75+ tools, stdio+HTTP) P2P Collab (Trystero + Yjs) │ -└──────────────────────────────────────────────────────────────────┘ +```mermaid +graph TB + subgraph Tauri["Tauri v2 Shell"] + subgraph Editor["Editor (Web)"] + UI["Vue 3 UI
Toolbar · Panels · Properties
Layers · Color Picker"] + Skia["Skia CanvasKit (WASM, 7MB)
Vector rendering · Text shaping
Effects · Export"] + subgraph Core["Core Engine (TS)"] + SG[SceneGraph] --- Layout[Layout - Yoga] + SG --- Selection + Undo[Undo/Redo] --- Constraints + Constraints --- HitTest[Hit Testing] + end + subgraph FileFormat["File Format Layer"] + FigIO[".fig import/export"] --- Kiwi[Kiwi codec] + Kiwi --- SVG[SVG export] + end + end + MCP["MCP Server (90 tools, stdio+HTTP)"] + Collab["P2P Collab (Trystero + Yjs)"] + end ``` ## Editor Layout The UI follows Figma's UI3 layout — toolbar at the bottom, navigation on the left, properties on the right: -- **Navigation panel (left)** — Layers tree, pages panel, asset library (planned) +- **Navigation panel (left)** — Layers tree, pages panel - **Canvas (center)** — Infinite canvas with CanvasKit rendering, zoom/pan - **Properties panel (right)** — Context-sensitive sections: Appearance, Fill, Stroke, Typography, Layout, Position - **Toolbar (bottom)** — Tool selection: Select, Frame, Section, Rectangle, Ellipse, Line, Text, Pen, Hand @@ -46,13 +37,9 @@ The UI follows Figma's UI3 layout — toolbar at the bottom, navigation on the l ### Rendering (CanvasKit WASM) -The same rendering engine as Figma. CanvasKit provides GPU-accelerated 2D drawing with: -- Vector shapes (rect, ellipse, path, line, star, polygon) -- Text shaping via Paragraph API -- Effects (shadows, blurs, blend modes) -- Export (PNG, SVG, PDF) +The same rendering engine as Figma. CanvasKit provides GPU-accelerated 2D drawing with vector shapes, text shaping via Paragraph API, effects (shadows, blurs, blend modes), and export (PNG, SVG). The 7MB WASM binary loads at startup and creates a GPU surface on the HTML canvas. -The 7MB WASM binary loads at startup and creates a GPU surface on the HTML canvas. +The renderer is split into focused modules in `packages/core/src/renderer/`: scene traversal, overlays, fills, strokes, shapes, effects, rulers, labels, and remote cursors. ### Scene Graph @@ -75,58 +62,54 @@ Meta's Yoga provides CSS flexbox layout computation. A thin adapter maps Figma p ### File Format (Kiwi Binary) -Reuses Figma's proven Kiwi binary codec with 194 message/enum/struct definitions. The `.fig` import pipeline: parse header → Zstd decompress → Kiwi decode → NodeChange[] → scene graph. The export pipeline reverses the process: scene graph → NodeChange[] → Kiwi encode → Zstd compress → ZIP with thumbnail. +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. +### AI & Tools + +Tools are defined once in `packages/core/src/tools/`, split by domain: read, create, modify, structure, variables, vector, analyze. Each tool has typed params and an `execute(figma, args)` function. Adapters convert them for: + +- **AI chat** — valibot schemas, wired to OpenRouter +- **MCP server** — zod schemas, stdio + HTTP transports +- **CLI** — available via the `eval` command + +87 core tools + 3 MCP file management tools = 90 total. + ### Undo/Redo Inverse-command pattern. Before applying any change, affected fields are snapshotted. The snapshot becomes the inverse operation. Batching groups rapid changes (like drag) into single undo entries. ### Clipboard -Figma-compatible bidirectional clipboard. Encodes/decodes Kiwi binary (same format as .fig files) using native browser copy/paste events (synchronous, not async Clipboard API). Paste handles vector path scaling, instance child population from components, component set detection, and override application. - -### MCP Server - -`@open-pencil/mcp` exposes 87 core tools + 3 file management tools (90 total) for AI coding tools. Two transports: stdio for Claude Code/Cursor/Windsurf, HTTP with Hono + Streamable HTTP for scripts and CI. Tools are defined once in `packages/core/src/tools/` (split by domain: read, create, modify, structure, variables, vector, analyze) and adapted for AI chat (valibot), MCP (zod), and CLI (eval command). +Figma-compatible bidirectional clipboard. Encodes/decodes Kiwi binary (same format as .fig files) via native browser copy/paste events. Handles vector path scaling, instance children, component set detection, and override application. ### P2P Collaboration Real-time peer-to-peer collaboration via Trystero (WebRTC) + Yjs CRDT. No server relay — signaling over MQTT public brokers, STUN/TURN for NAT traversal. Awareness protocol provides live cursors, selections, and presence. Local persistence via y-indexeddb. +### CLI-to-App RPC Bridge + +When the desktop app is running, CLI commands connect to it via WebSocket instead of requiring a .fig file. The automation server runs on `127.0.0.1:7600` (HTTP) and `127.0.0.1:7601` (WebSocket). Commands execute against the live editor state, enabling automation scripts and AI agents to interact with the running app. + ## What's Next -Current priorities and planned work, in rough order: - -### More AI Providers - -The AI chat currently routes through OpenRouter. Direct integrations planned: Anthropic API key (skip OpenRouter), Google Gemini, and local models via Ollama. This removes the OpenRouter dependency for users who already have API keys with individual providers. - ### Full figma-use Tool Set -The MCP server currently exposes 90 tools. The reference implementation in [figma-use](https://github.com/dannote/figma-use) has 118. The remaining tools cover advanced layout constraints, prototype connections, advanced component property editing, and bulk document operations — all will be ported. +The MCP server currently exposes 90 tools. The reference implementation in [figma-use](https://github.com/dannote/figma-use) has 118. The remaining tools cover advanced layout constraints, prototype connections, advanced component property editing, and bulk document operations. ### CI Design Tooling -The headless CLI already supports `analyze colors/typography/spacing/clusters`. Next: integrate these into GitHub Actions workflows for automated design linting (naming conventions, spacing consistency, accessibility contrast ratios) and visual regression in PRs via the headless PNG exporter. +The headless CLI already supports `analyze colors/typography/spacing/clusters`. Next: GitHub Actions integration for automated design linting and visual regression in PRs. ### Prototyping -Frame-to-frame transitions, interaction triggers (click, hover, drag), overlay management, and a fullscreen preview mode. This is a large feature set — tracked as Phase 6 in the original roadmap. +Frame-to-frame transitions, interaction triggers (click, hover, drag), overlay management, and fullscreen preview mode. ### CSS Grid Layout -Yoga WASM currently supports flexbox only. CSS Grid support is upstream in [facebook/yoga#1893](https://github.com/facebook/yoga/pull/1893) (9 PRs merged). OpenPencil will adopt it once the Yoga release ships — no custom grid engine needed. +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. -### PDF Export +### Windows Code Signing -SVG export shipped in v0.7.0. PDF export requires either a server-side headless renderer or CanvasKit's PDF canvas backend — the latter is being investigated for a client-side implementation. - -### .fig Fidelity - -Ongoing improvement of import/export round-trip accuracy for complex real-world files: advanced prototype connections, complex component property assignments, interaction effects, and rare node types not yet in the codec. - -### Code Signing - -macOS binaries are signed and notarized since v0.6.0. Windows Authenticode signing via Azure Code Signing is planned to remove the "unknown publisher" SmartScreen warning on Windows installers. +macOS binaries are signed and notarized since v0.6.0. Windows Authenticode signing via Azure Code Signing is planned to remove the SmartScreen warning. diff --git a/packages/docs/guide/features.md b/packages/docs/guide/features.md index 12d31fc02..dc3a75fe8 100644 --- a/packages/docs/guide/features.md +++ b/packages/docs/guide/features.md @@ -1,353 +1,138 @@ # Features -## Why OpenPencil +## Figma .fig Files -Design tools are a supply chain problem. When your tool is closed-source, the vendor controls what's possible — they can break your automation overnight. OpenPencil is an open-source alternative: MIT-licensed, Figma-compatible, fully local, and programmable. +Open and save native Figma files directly. The import/export pipeline uses the same Kiwi binary codec as Figma — 194 schema definitions, ~390 fields per node. Save with S, Save As with S. -## Figma .fig File Import & Export +**Copy & paste with Figma** — select nodes in Figma, C, switch to OpenPencil, V. Fills, strokes, auto-layout, text, effects, corner radii, and vector networks are preserved. Works both ways. -Open and save native Figma files directly. Import decodes the full 194-definition Kiwi schema including NodeChange messages with ~390 fields. Export encodes the scene graph back to Kiwi binary with Zstd compression and thumbnail generation. Save (S) and Save As (S) use native OS dialogs on the desktop app. The import/export pipeline supports round-trip fidelity. +## Drawing & Editing -## Copy & Paste with Figma - -Select nodes in Figma, C, switch to OpenPencil, V — they appear with fills, strokes, auto-layout, text, corner radii, effects, and vector networks preserved. Works the other way too: copy from OpenPencil, paste into Figma. - -Under the hood, both directions use the same Kiwi binary format as .fig files — Figma base64-encodes it into HTML on the clipboard. OpenPencil decodes the full schema on paste (194 definitions, ~390 fields per NodeChange) and encodes it on copy. Vector data round-trips through the `vectorNetworkBlob` binary format. Also works between OpenPencil instances via a separate native clipboard format. - -Paste handles complex scenarios: vector paths are scaled from Figma's `normalizedSize` to actual node bounds, instance children are populated from their component's `symbolData`, component sets are detected by promoting frames with variant `componentPropDefs`, internal canvas nodes are skipped, and `symbolOverrides` are applied for text, fills, visibility, and layout properties. Fonts referenced by pasted text nodes are automatically loaded. - -## Vector Networks - -The pen tool uses Figma's vector network model — not simple paths. Click to place corner points, click+drag for bezier curves with tangent handles. Supports open and closed paths. Vector data uses the same `vectorNetworkBlob` binary format as Figma. - -## Shape Tools - -The toolbar provides all basic Figma shape tools: Rectangle (R), Ellipse (O), Line (L), Polygon, and Star. Polygon and Star are in the shapes flyout — click and hold the Rectangle tool to access them. Polygon draws regular polygons (default 3 sides) using a `pointCount` property. Star draws pointed stars (default 5 points) with a configurable `starInnerRadius` (default 0.38). All shapes support fill, stroke, hover highlight, and selection outline. - -## Auto-Layout - -Yoga WASM provides CSS flexbox layout. Frames support: - -- **Direction** — horizontal, vertical, wrap -- **Gap** — spacing between children -- **Padding** — uniform or per-side -- **Justify** — start, center, end, space-between -- **Align** — start, center, end, stretch -- **Child sizing** — fixed, fill, hug - -Shift+A toggles auto-layout on a frame or wraps selected nodes. - -## Inline Text Editing - -Canvas-native text editing — no DOM textarea overlay on screen. A `TextEditor` class in `@open-pencil/core` handles cursor positioning, text selection, word boundary detection, and line navigation using the CanvasKit Paragraph API (`getGlyphPositionAtCoordinate`, `getRectsForRange`, `getLineMetrics`). A hidden phantom textarea captures keyboard input, IME composition, and clipboard events. - -Double-click a text node to enter edit mode. The canvas renders a blinking caret, translucent blue selection rectangles, and a blue outline around the node. Click and drag to select text, double-click a word to select it, triple-click to select all. Keyboard navigation with modifier support: / for word movement, / for line start/end, for word delete, for line delete. Shift extends selection. Esc or clicking outside commits the edit. - -**Font picker** with virtual scroll (reka-ui ListboxVirtualizer), search filter, and CSS font preview — each font name renders in its own typeface. In Tauri, system fonts are enumerated via Rust `font-kit` crate (`list_system_fonts`/`load_system_font` commands) with OnceLock caching for instant picker access. In browser, the Local Font Access API is used when available. - -## Rich Text Formatting - -Per-character formatting within a single text node. Select text and press B for bold, I for italic, U for underline, or use the B/I/U/S buttons in the Typography section. With no selection, the shortcut toggles the whole-node style. - -Implemented via a StyleRun model — an array of `{start, length, style}` segments where style includes fontWeight, italic, and textDecoration. The renderer uses CanvasKit ParagraphBuilder.pushStyle/pop to render mixed formatting in a single paragraph. Style runs adjust automatically on insert and delete to preserve formatting boundaries. - -Rich text formatting is preserved during .fig import/export — `characterStyleIDs` and `styleOverrideTable` from Figma's TextData are imported as StyleRun arrays and exported back with a deduped style table. - -## Undo/Redo - -Every operation is undoable — node creation/deletion, moves, resizes, property changes, reparenting, layout changes, and all variable operations (create/delete/rename variables, create/rename collections, color and value changes). The system uses an inverse-command pattern — before applying any change, it snapshots affected fields. The snapshot becomes the inverse. Z undoes, Z redoes. - -## Snap Guides - -Edge and center snapping with red guide lines when nodes align. Rotation-aware — snap calculations use actual visual bounds of rotated nodes. Coordinates are computed in absolute canvas space. - -## Canvas Rulers - -Rulers at the top and left edges show coordinate scales. When you select a node, rulers highlight its position with a translucent band and show coordinate badges at the start/end points. - -## Color Picker & Fill Types - -HSV color selection with hue slider, alpha slider, hex input, and opacity control. The fill type picker provides tabs for Solid, Gradient (Linear, Radial, Angular, Diamond), and Image. Switching to a gradient type shows an editable gradient stop bar. Gradient transforms position the gradient within the shape. Connected to fill and stroke sections in the properties panel. - -## Layers Panel - -Tree view of the document hierarchy using Reka UI Tree component. Expand/collapse frames, drag to reorder (changes z-order), toggle visibility per node. - -Both the layers panel and properties panel are resizable — drag the edge between panels and canvas to adjust width (default 15%, range 10–30%). Layout persists across reloads. +- **Shapes** — Rectangle (R), Ellipse (O), Line (L), Polygon, Star +- **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 +- **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 ## Properties Panel -Tabbed interface with **Design** | **Code** | **AI** tabs (reka-ui Tabs). +Context-sensitive Design | Code | AI tabs: -The **Design** tab is context-sensitive with sections: - -- **Appearance** — opacity, corner radius (uniform or per-corner with independent toggle), visibility -- **Fill** — solid/gradient/image type picker, gradient stop editor, hex input, opacity -- **Stroke** — color, weight, opacity, cap, join, dash pattern -- **Effects** — add/remove effects, type picker (drop shadow, inner shadow, layer blur, background blur, foreground blur), inline expanded controls (offset, blur, spread, color for shadows; blur radius for blurs), per-effect visibility toggle -- **Typography** — font family (FontPicker with virtual scroll and search), weight, size, alignment, B/I/U/S buttons +- **Appearance** — opacity, corner radius (uniform or per-corner), visibility +- **Fill** — solid, gradient (linear/radial/angular/diamond), image +- **Stroke** — color, weight, align (inside/center/outside), per-side weights, cap, join, dash +- **Effects** — drop shadow, inner shadow, layer blur, background blur, foreground blur +- **Typography** — font picker with virtual scroll and search, weight, size, alignment, style buttons - **Layout** — auto-layout controls when enabled -- **Position** — alignment buttons, rotation, flip -- **Export** — scale, format (PNG/JPG/WEBP), live preview, multi-export -- **Page** — canvas background color (shown when no nodes selected) +- **Export** — scale, format (PNG/JPG/WEBP/SVG), live preview -The **Code** tab shows JSX export of the selection (see [Code Panel](#code-panel)). The **AI** tab provides an AI chat interface (see [AI Chat](#ai-chat)). +## Rendering -## Group/Ungroup +Skia (CanvasKit WASM) — the same rendering engine as Figma: -⌘G groups selected nodes. ⇧⌘G ungroups. Nodes are sorted by visual position when grouping to preserve reading order. +- Gradient fills (linear, radial, angular, diamond) +- Image fills with scale modes +- Effects with per-node caching +- Arc data (partial ellipses, donuts) +- Viewport culling and paint reuse +- Snap guides with rotation-aware alignment +- Canvas rulers with selection badges +- Hover highlight that follows actual geometry -## Sections +## Undo/Redo -Sections (S) are top-level organizational containers on the canvas. Each section displays a title pill with the section name. Title text color automatically inverts based on the pill's background luminance for readability. Creating a section auto-adopts overlapping sibling nodes. Frame name labels are shown for direct children of sections. +Every operation is undoable — creation, deletion, moves, resizes, property changes, reparenting, layout changes, variable operations. Uses an inverse-command pattern. Z / Z. ## Multi-Page Documents -Documents support multiple pages like Figma. The pages panel lets you add, delete, and rename pages. Each page maintains independent viewport state (pan, zoom, background color). Double-click a page name to rename inline. - -## Hover Highlight - -Nodes highlight on hover with a shape-aware outline that follows the actual geometry — ellipses get elliptical outlines, rounded rectangles get rounded outlines, vectors get path outlines. This provides visual feedback before clicking to select. - -## Advanced Rendering (Tier 1) - -The CanvasKit renderer supports full Tier 1 visual features for Figma rendering parity: - -- **Gradient fills** — linear, radial, angular, diamond with gradient stops and transforms -- **Image fills** — decoded from blob data with scale modes (fill, fit, crop, tile) -- **Effects** — drop shadow, inner shadow, layer blur, background blur, foreground blur -- **Stroke properties** — cap (none, round, square, arrow), join (miter, bevel, round), dash patterns -- **Arc data** — partial ellipses with start/end angle and inner radius (donuts) -- **Viewport culling** — off-screen nodes are skipped during rendering -- **Paint reuse** — Skia Paint objects are recycled across frames instead of reallocated -- **RAF coalescing** — multiple render requests within one frame are batched into a single `requestAnimationFrame` call - -## Components & Instances - -Create reusable components from frames or selections (K). A single frame converts in-place to a COMPONENT; multiple nodes wrap in a new component. Combine multiple components into a COMPONENT_SET (K) with a dashed purple border. Create instances from components via context menu — instances copy the component's visual properties and deep-clone children with `componentId` mapping. Detach an instance back to a frame with B. "Go to main component" navigates to and selects the source component, switching pages if needed. - -**Live sync:** Editing a main component propagates changes to all its instances automatically. The store triggers sync after property updates, moves, and resizes. Synced properties include size, fills, strokes, effects, opacity, corner radii, layout, and clipsContent. Instance children are matched to component children via `componentId`. - -**Override support:** Instances maintain an overrides record. Properties marked as overridden are preserved during sync — if you customize an instance child's text, it won't be overwritten when the component changes. New children added to a component appear in all existing instances. - -Components and instances display always-visible purple labels with a diamond icon showing the node name. They act as opaque containers for selection — clicking selects the component itself, double-clicking enters it to select children. - -## Variables - -Design tokens as variables with collections and modes. Open the variables dialog from the Variables section in page properties (settings icon). The dialog uses TanStack Table (`@tanstack/vue-table`) with resizable columns — Name | Mode 1 | Mode 2 | ... — matching Figma's table layout. Collection tabs with double-click to rename, search bar, and "+ Create variable" button. Color variables show inline ColorInput with picker. - -Supports COLOR type with full UI, FLOAT/STRING/BOOLEAN types defined. Organize variables in collections (e.g., "Primitives", "Semantic"), define modes (e.g., Light/Dark), switch active mode. Bind variables to fill colors via the variable picker in Fill — bound fills show a purple badge with the variable name and a detach button. Alias chains (one variable references another) with cycle detection. All variable operations are undoable: create/delete variable, create collection, rename, color change. - -The demo document includes three collections: Primitives (9 colors with Light/Dark modes), Semantic (aliases to Primitives), and Spacing (8 number tokens with Default/Compact modes). Variables are bound to demo nodes for live preview. - -## Image & SVG Export - -Export selected nodes as PNG, JPG, WEBP, or SVG. The Export section in the properties panel provides scale selection (0.5×–4×, hidden for SVG), format picker, multi-export support, and a live preview with checkerboard background. Also available via context menu "Export…" and E. SVG export supports rectangles, ellipses, lines, stars, polygons, vectors, text with style runs, gradients, image fills, effects, blend modes, and nested groups. - -CLI: `bun open-pencil export --format svg file.fig`. MCP/AI tool: `export_svg`. - -## Copy/Paste as - -The context menu **Copy/Paste as** submenu exposes multiple clipboard formats: - -- **Copy as text** — visible text content from the selection -- **Copy as SVG** — full SVG markup of the selection -- **Copy as PNG** — renders at 2× to the system clipboard (C) -- **Copy as JSX** — OpenPencil JSX compatible with `renderJsx()` - -## Stroke Align & Per-Side Weights - -Stroke alignment controls where the stroke is drawn relative to the shape boundary: **Inside** (stroke painted inside, clip path trims overlap with fill), **Center**, or **Outside**. Rendering matches Figma's behavior exactly. - -Individual stroke weights per side let you set different widths for Top, Right, Bottom, and Left independently via the side selector dropdown in the Stroke section. - -## Context Menu - -Right-click on the canvas opens a Figma-style context menu. Actions adapt to the current selection: - -- **Clipboard** — Copy, Cut, Paste here, Duplicate, Delete -- **Copy/Paste as** — Copy as text, SVG, PNG (C), JSX -- **Z-order** — Bring to front, Send to back -- **Grouping** — Group, Ungroup, Add auto layout -- **Components** — Create component, Create component set, Create instance, Go to main component, Detach instance (purple-styled items) -- **Visibility** — Hide/Show, Lock/Unlock -- **Move to page** — submenu with all other pages - -Right-clicking a node selects it first. Right-clicking empty canvas clears selection. - -## Z-Order, Visibility & Lock - -] brings selected nodes to front, [ sends to back within their parent. H toggles visibility — hidden nodes stay in the layers panel but don't render. L toggles lock — locked nodes can't be selected or moved from the canvas. Move nodes between pages via the context menu's "Move to page" submenu. - -## Web & Desktop App - -OpenPencil runs in the browser at [app.openpencil.dev](https://app.openpencil.dev) — no installation required. - -The desktop app uses a Tauri v2 shell (~5MB vs Electron's ~100MB). Works fully offline — no account, no server, no internet required. Native menu bar with File/Edit/View/Object/Window/Help menus on all platforms. macOS gets an app-level submenu. Native Save/Open dialogs via Tauri plugin-dialog. Zstd compression offloaded to Rust for .fig export performance. Developer Tools accessible via I. - -## App Menu (Browser) - -In browser mode, a menu bar built with reka-ui Menubar provides access to all major editor actions. Six menus: **File** (Open, Save, Save As, Export selection), **Edit** (Undo, Redo, Copy, Paste, Duplicate, Delete, Select all), **View** (Zoom to fit, Zoom in/out, Toggle rulers), **Object** (Group, Ungroup, Frame selection, Create component, Create component set), **Text** (Font size adjustment, Bold, Italic, Underline, Strikethrough, Align submenu), **Arrange** (Bring to front, Send to back, Bring forward, Send backward). Keyboard shortcuts are displayed next to each menu item with platform-aware modifier labels (⌘ on Mac, Ctrl+ on Windows/Linux). Hidden when running in Tauri, which provides its own native menus. - -## Autosave - -Files are automatically saved 3 seconds after the last scene change. A debounced watcher monitors `sceneVersion` — multiple rapid edits only trigger a single write after activity settles. Uses the Tauri fs plugin on desktop or the File System Access API in supported browsers. Autosave is disabled for new untitled documents until the user performs an explicit Save As. Errors are handled silently — the user can always trigger a manual save with S. - -**Auto-save toggle** — File → Auto-save disables automatic writes when you want full manual control (useful during exploratory edits you may not want to persist). - -## Mobile Layout & PWA - -OpenPencil is installable as a Progressive Web App on mobile devices. The responsive layout adapts to small screens: - -- Side panels replaced by a **swipeable bottom drawer** with tabs: Layers, Properties, Design, Code -- Toolbar collapses to a compact strip with animated category switching -- Spring-animated drawer with pan gesture control -- PWA manifest with icons and service worker for offline capability (disabled in dev mode) - -## Tailwind CSS v4 JSX Export - -The Code panel's format toggle switches between two output modes: - -- **OpenPencil** — custom component tree (`Frame`, `Text`, `Rect`, etc.) compatible with `renderJsx()` -- **Tailwind CSS v4** — HTML with utility classes (`
`) ready to drop into any React or Vue project - -Tailwind output supports layout, sizing, colors, border radius, opacity, rotation, overflow, shadows, blur, and typography. Uses v4 spacing semantics (px/4 multiplier) with automatic fallback to arbitrary values for non-standard sizes. - -CLI: `bun open-pencil export --format jsx --style tailwind file.fig` - -## Google Fonts Fallback - -When a font is not available locally, OpenPencil automatically fetches it from Google Fonts API. This ensures text renders correctly when opening .fig files that reference fonts not installed on the system — no manual font installation required. - -## Layer Inline Rename - -Double-click any layer name in the layers panel to rename it inline. Press **Enter** or click away to commit, **Escape** to cancel. Works for all node types. - -## Renderer Profiler - -A developer HUD overlay shows per-frame render timing, GPU phase breakdown, and frame budget. Accessible via the View menu. Useful for diagnosing performance issues on complex documents. - -## P2P Collaboration - -Real-time peer-to-peer collaboration — no server required. Share a link and edit together. Built on Trystero (WebRTC) for direct peer connections and Yjs (CRDT) for conflict-free document sync. - -- **Zero hosting cost** — signaling via MQTT public brokers, data flows directly between peers -- **NAT traversal** — Google STUN, Cloudflare STUN, and Open Relay TURN servers -- **Live cursors** — Figma-style colored cursor arrows with white border and name pills, rendered in screen space -- **Presence** — see who's in the room with colored avatars -- **Follow mode** — click a peer's avatar to follow their viewport in real time, click again to stop -- **Local persistence** — y-indexeddb keeps the room alive across page refreshes -- **Secure rooms** — IDs generated with `crypto.getRandomValues()`, shared via `/share/` URL - -Stale cursors are cleaned up automatically when a peer disconnects. +Add, delete, rename pages. Each page has independent viewport state. Double-click to rename inline. ## Multi-File Tabs -Open multiple documents in tabs within a single window. Tab bar shows open files with close buttons. Middle-click a tab to close it. +Open multiple documents in tabs. T new tab, W close, O open file. -- N or T — new tab -- W — close current tab -- O — open file in new tab -- + button in tab bar — new tab +## Export -Each tab maintains its own document state, undo history, and viewport. +- **Image** — PNG, JPG, WEBP at configurable scale (0.5×–4×). Via panel, context menu, or E +- **SVG** — shapes, text with style runs, gradients, effects, blend modes +- **Tailwind JSX** — HTML with Tailwind v4 utility classes, ready for React or Vue +- **Copy as** — text, SVG, PNG (C), or JSX via context menu -## Effects Rendering +CLI: `open-pencil export design.fig -f jsx --style tailwind` -Full rendering of Figma effects via CanvasKit: +## AI Chat -- **Drop shadow** — offset, blur radius, spread, color; draws behind opaque content using `MaskFilter` direct draw (no `saveLayer` overhead) -- **Inner shadow** — inset shadow with offset, blur, and color -- **Layer blur** — Gaussian blur on the entire layer -- **Background blur** — blur content behind the layer (glass/frosted effect) -- **Foreground blur** — blur in the foreground +Press J to open the AI assistant. 87 tools that can create shapes, set styles, manage layout, work with components and variables, run boolean operations, analyze design tokens, and export assets. Bring your own OpenRouter API key. -Text shadows render on individual glyphs instead of the bounding box. Each effect has an independent visibility toggle. Per-node `SkPicture` caching means unchanged shadow/blur nodes replay from cache on scene redraws — zero re-computation for static effects. +Tool calls display as collapsible timeline entries. Model selector with Claude, Gemini, GPT, DeepSeek, and others. -## Multi-Selection Properties +## MCP Server -Select multiple nodes and edit shared properties at once. The properties panel adapts: +Connect Claude Code, Cursor, Windsurf, or any MCP client to read and write `.fig` files headlessly. 90 tools (87 core + 3 file management). Two transports: stdio and HTTP. -- Shared values display normally in all sections (position, size, appearance, fill, stroke, effects) -- Differing values show "Mixed" -- Width and height inputs work across the selection -- Flip horizontal/vertical applies to all selected nodes +```sh +bun add -g @open-pencil/mcp +``` -Single-node alignment aligns to parent frame bounds. Multi-selection uses the selection bounding box. +```json +{ + "mcpServers": { + "open-pencil": { + "command": "openpencil-mcp" + } + } +} +``` -## ScrubInput +See [MCP Tools reference](/reference/mcp-tools) for the full tool list. -All numeric inputs in the properties panel use a drag-to-scrub interaction — drag horizontally to adjust the value, or click to type directly. Supports suffix display (°, px, %). +## CLI -## Homebrew Tap +Inspect, export, and analyze `.fig` files from the terminal: -macOS users can install the desktop app via Homebrew: +```sh +open-pencil tree design.fig # Node tree +open-pencil find design.fig --type TEXT # Search +open-pencil export design.fig -f png # Render +open-pencil analyze colors design.fig # Color audit +open-pencil analyze clusters design.fig # Repeated patterns +open-pencil eval design.fig -c "..." # Figma Plugin API +``` + +When the desktop app is running, omit the file to control the live editor via RPC: + +```sh +open-pencil tree # Live document +open-pencil export -f png # Screenshot canvas +``` + +All commands support `--json`. Install: `bun add -g @open-pencil/cli` + +## Real-Time Collaboration + +P2P via WebRTC — no server required. Share a link and edit together. + +- Live cursors with colored arrows and name pills +- Presence avatars +- Follow mode — click a peer to follow their viewport +- Local persistence via IndexedDB +- Secure room IDs via `crypto.getRandomValues()` + +## Desktop & Web + +**Desktop** — Tauri v2, ~7 MB. macOS (signed & notarized), Windows, Linux. Native menus, offline, autosave. + +**Web** — runs at [app.openpencil.dev](https://app.openpencil.dev), installable as a PWA on mobile with touch-optimized UI. + +**Homebrew:** ```sh brew install open-pencil/tap/open-pencil ``` -Supports Apple Silicon (arm64) and Intel (x64). The tap is auto-updated on each release via GitHub Actions. +## Google Fonts Fallback -## CI/CD Builds - -GitHub Actions workflow builds native Tauri desktop apps on version tags. The build matrix covers macOS (arm64, x64), Windows (x64, arm64), and Linux (x64). Builds use `tauri-apps/tauri-action` and produce draft GitHub releases with platform-specific binaries. macOS builds are code-signed and notarized via Apple Developer certificates. Release notes are auto-populated from CHANGELOG.md. - -## @open-pencil/core & CLI - -The engine is extracted to `packages/core/` (@open-pencil/core) — scene-graph, renderer, layout, codec, kiwi, types — with zero DOM dependencies. The app re-exports from core via thin shims. - -`packages/cli/` (@open-pencil/cli) provides headless .fig file operations using CanvasKit CPU rasterization: - -- `open-pencil info ` — document stats, node types, fonts -- `open-pencil tree ` — visual node tree -- `open-pencil find ` — search by name/type -- `open-pencil export ` — render to PNG/JPG/WEBP at any scale -- `open-pencil analyze colors ` — color palette usage with clustering -- `open-pencil analyze typography ` — font/size/weight distribution -- `open-pencil analyze spacing ` — gap/padding values with grid check -- `open-pencil analyze clusters ` — repeated patterns (potential components) -- `open-pencil node ` — detailed properties of a node by ID -- `open-pencil pages ` — list pages with node counts -- `open-pencil variables ` — list design variables and collections -- `open-pencil eval ` — execute JavaScript with Figma Plugin API - -All commands support `--json` for machine-readable output. Runnable via `bun open-pencil` in the workspace. See [Project Structure](/development/contributing#project-structure) for the full monorepo layout. - -The `eval` command deserves special mention: `bun open-pencil eval --code ''` executes JavaScript against a `.fig` file with a Figma-compatible `figma` global object. Enables headless scripting, batch operations, AI tool execution, and testing — all without the GUI. See [Eval Command](/eval-command) for the full reference. - -## JSX Renderer - -Programmatic design creation via TreeNode builder functions exported from `@open-pencil/core`: Frame, Text, Rectangle, Ellipse, and others. Supports Tailwind-like shorthand props — `w`, `h`, `bg`, `rounded`, `flex`, `gap`, `p`/`px`/`py`, `justify`, `items`, `shadow`, `blur`. - -Two rendering paths: -- `renderTreeNode()` — tree → scene graph (any runtime, no external deps) -- `renderJsx()` — JSX string → esbuild → tree → scene graph (CLI/headless) - - - -## AI Chat - -Built-in AI assistant accessible via the AI tab in the properties panel or J. Communicates directly with OpenRouter from the browser — no backend server required. API key stored securely in Tauri Stronghold (localStorage fallback in browser). - -**Model selector** with curated models: Claude, Gemini, GPT, DeepSeek, Qwen, Kimi, Llama — stored in `@open-pencil/core` constants with benchmark-ranked tags. Responses stream as markdown (vue-stream-markdown). - -**87 tools** defined in `packages/core/src/tools/` across domain files (read, create, modify, structure, variables, vector, analyze), covering: read operations (selection, page tree, node details, search, components, fonts), create operations (shapes, frames, vectors, slices, pages, components, instances, JSX render), modify operations (fill, stroke, effects, layout, constraints, text, font, opacity, rotation, radius, visibility, blend mode, lock, stroke align), node manipulation (move, resize, reparent, clone, delete, flatten, boolean operations, arrange), variable CRUD (get, find, create, set, delete, bind, collections), vector path tools (get, set, scale, flip, move), analyze (colors, typography, spacing, clusters), diff (create/show snapshots), and an `eval` escape hatch. Tools are wired to AI chat (valibot schemas), MCP server (zod schemas), and CLI (`eval` command). Tool calls display as collapsible timeline entries in the chat (Reka UI Collapsible). - -**MCP server** (`packages/mcp/`) exposes all tools for external AI coding tools. Two transports: stdio for Claude Code/Cursor/Windsurf (`openpencil-mcp`), HTTP with Hono + Streamable HTTP for scripts and CI (`openpencil-mcp-http`). Adds 3 file management tools (`open_file`, `save_file`, `new_document`) on top of the 87 core tools, for 90 total. Runs on Bun and Node.js. See [MCP Tools reference](/reference/mcp-tools). - -**AI agent skill** — install with `npx skills add open-pencil/skills@open-pencil`. Teaches AI coding agents (Claude Code, Cursor, Windsurf, Codex) to use the CLI, MCP tools, JSX rendering, eval, and the app's automation bridge. Source: [open-pencil/skills](https://github.com/open-pencil/skills). - -**CLI-to-app RPC bridge** — when the desktop app is running, CLI commands automatically connect to it via WebSocket instead of requiring a .fig file. Run `bun open-pencil tree` to inspect the live document, or `bun open-pencil export` to render the current canvas. - -Tested with Playwright using mock transport for CI (chat), bun:test for tool execution (MCP). - -## Code Panel - -The Code tab in the properties panel shows the JSX representation of the current selection. Uses `sceneNodeToJsx()` from `@open-pencil/core` to convert the SceneNode subtree into JSX with Tailwind-like shorthand props. Prism.js syntax highlighting with line numbers and a copy-to-clipboard button. Multi-selection shows each node's JSX. The exported JSX is compatible with `renderJsx()` for round-trip creation. - - - -## Code Quality - -Copy-paste detection via jscpd — reduced project-wide duplication from 15.6% to 0.62%. Kiwi serialization consolidated into `kiwi-serialize.ts` (shared by clipboard, fig-export, and the CLI). The .fig import pipeline was optimized from O(n²) to O(n) by building a children index upfront — material3.fig (87K nodes) went from 37s to 535ms. ByteBuffer optimized with inline readVarUint and TextDecoder for strings. +When a font isn't available locally, OpenPencil fetches it from Google Fonts automatically. No manual installation needed when opening .fig files with unfamiliar fonts. diff --git a/packages/docs/index.md b/packages/docs/index.md index cba2b5b9e..b4e55b800 100644 --- a/packages/docs/index.md +++ b/packages/docs/index.md @@ -1,12 +1,12 @@ --- layout: home -title: OpenPencil — AI-Native Design Editor -description: Open-source Figma alternative. Fully local, AI-native, programmable. +title: OpenPencil — Open-Source Design Editor +description: Open-source Figma alternative. Opens .fig files, built-in AI, fully programmable. hero: name: OpenPencil - text: AI-Native Design Editor - tagline: Open-source Figma alternative. Fully local, AI-native, programmable. + text: Open-Source Design Editor + tagline: Opens Figma files. Built-in AI. Fully programmable. Free forever. actions: - theme: brand text: Try Online @@ -19,19 +19,22 @@ hero: link: https://github.com/open-pencil/open-pencil features: - - icon: 📖 - title: Open Source - details: MIT license. Read and modify everything — the editor, the engine, the file codec. - icon: 📂 title: Figma-Compatible - details: Opens .fig files natively. Copy/paste between apps. Kiwi codec with round-trip fidelity. - - icon: 🤖 - title: AI-Native - details: Built-in chat with tool use. Bring your own API key — no subscription, no vendor lock-in. - - icon: 🖥️ - title: No Subscription - details: No account, no server, no internet required. Free forever. ~5 MB desktop app. + details: Opens .fig files natively. Copy & paste between Figma and OpenPencil. Kiwi binary codec with round-trip fidelity. - icon: ⚡ title: Programmable - details: Headless CLI for .fig inspection and export. Every operation is scriptable. JSX renderer. + details: Headless CLI to inspect, export, and analyze .fig files. Figma Plugin API via eval. Tailwind CSS export. JSON output for CI. + - icon: 🤖 + title: AI-Native + details: Built-in chat with 90 tools — create shapes, set styles, manage layout, analyze tokens. MCP server for Claude Code, Cursor, Windsurf. + - icon: 📖 + title: Open Source + details: MIT license. Read and modify everything — the editor, the engine, the file codec, the CLI. + - icon: 🖥️ + title: Free & Local + details: No account, no server, no internet required. ~7 MB desktop app via Homebrew, or use the web app. + - icon: 👥 + title: Real-Time Collaboration + details: P2P via WebRTC — no server. Share a link, edit together with live cursors and follow mode. --- diff --git a/packages/docs/it/guide/architecture.md b/packages/docs/it/guide/architecture.md index 770d1282e..ec0399519 100644 --- a/packages/docs/it/guide/architecture.md +++ b/packages/docs/it/guide/architecture.md @@ -1,68 +1,55 @@ # Architettura -## Panoramica del sistema +## Panoramica del Sistema -``` -┌──────────────────────────────────────────────────────────────────┐ -│ Tauri v2 Shell │ -│ │ -│ ┌────────────────────────────────────────────────────────────┐ │ -│ │ Editor (Web) │ │ -│ │ │ │ -│ │ Vue 3 UI Skia CanvasKit (WASM, 7MB) │ │ -│ │ - Barra strumenti - Rendering vettoriale │ │ -│ │ - Pannelli - Composizione testo │ │ -│ │ - Proprietà - Elaborazione immagini │ │ -│ │ - Livelli - Effetti (sfocatura, ombra) │ │ -│ │ - Selettore colore - Esportazione (PNG, SVG, PDF)│ │ -│ │ │ │ -│ │ ┌──────────────────────────────────────────────────────┐ │ │ -│ │ │ Core Engine (TS) │ │ │ -│ │ │ SceneGraph ─── Layout (Yoga) ─── Selection │ │ │ -│ │ │ │ │ │ │ │ -│ │ │ Undo/Redo ─── Constraints ─── Hit Testing │ │ │ -│ │ └──────────────────────────────────────────────────────┘ │ │ -│ │ │ │ -│ │ ┌──────────────────────────────────────────────────────┐ │ │ -│ │ │ Livello formato file │ │ │ -│ │ │ .fig import/export ── Kiwi codec ── .svg (previsto) │ │ │ -│ │ └──────────────────────────────────────────────────────┘ │ │ -│ └────────────────────────────────────────────────────────────┘ │ -│ │ -│ MCP Server (75+ tools, stdio+HTTP) P2P Collab (Trystero + Yjs) │ -└──────────────────────────────────────────────────────────────────┘ +```mermaid +graph TB + subgraph Tauri["Tauri v2 Shell"] + subgraph Editor["Editor (Web)"] + UI["Vue 3 UI
Toolbar · Panels · Properties
Layers · Color Picker"] + Skia["Skia CanvasKit (WASM, 7MB)
Vector rendering · Text shaping
Effects · Export"] + subgraph Core["Core Engine (TS)"] + SG[SceneGraph] --- Layout[Layout - Yoga] + SG --- Selection + Undo[Undo/Redo] --- Constraints + Constraints --- HitTest[Hit Testing] + end + subgraph FileFormat["File Format Layer"] + FigIO[".fig import/export"] --- Kiwi[Kiwi codec] + Kiwi --- SVG[SVG export] + end + end + MCP["MCP Server (90 tools, stdio+HTTP)"] + Collab["P2P Collab (Trystero + Yjs)"] + end ``` -## Layout dell'editor +## Layout dell'Editor -L'interfaccia segue il layout UI3 di Figma — barra strumenti in basso, navigazione a sinistra, proprietà a destra: +L'interfaccia segue il layout UI3 di Figma — barra degli strumenti in basso, navigazione a sinistra, proprietà a destra: -- **Pannello di navigazione (sinistra)** — Albero dei livelli, pannello pagine, libreria asset (previsto) +- **Pannello navigazione (sinistra)** — Albero dei livelli, pannello pagine - **Canvas (centro)** — Canvas infinito con rendering CanvasKit, zoom/pan -- **Pannello proprietà (destra)** — Sezioni contestuali: Aspetto, Riempimento, Contorno, Tipografia, Layout, Posizione -- **Barra strumenti (basso)** — Selezione strumento: Seleziona, Frame, Sezione, Rettangolo, Ellisse, Linea, Testo, Penna, Mano +- **Pannello proprietà (destra)** — Sezioni sensibili al contesto: Aspetto, Riempimento, Bordo, Tipografia, Layout, Posizione +- **Barra degli strumenti (basso)** — Selezione strumenti: Seleziona, Frame, Sezione, Rettangolo, Ellisse, Linea, Testo, Penna, Mano ## Componenti ### Rendering (CanvasKit WASM) -Lo stesso motore di rendering di Figma. CanvasKit fornisce disegno 2D accelerato via GPU con: -- Forme vettoriali (rettangolo, ellisse, percorso, linea, stella, poligono) -- Composizione testo via Paragraph API -- Effetti (ombre, sfocature, modalità di fusione) -- Esportazione (PNG, SVG, PDF) +Lo stesso motore di rendering di Figma. CanvasKit fornisce disegno 2D accelerato dalla GPU con forme vettoriali, formattazione del testo tramite Paragraph API, effetti (ombre, sfocature, modalità di fusione) ed esportazione (PNG, SVG). Il binario WASM da 7MB viene caricato all'avvio e crea una superficie GPU sul canvas HTML. -Il binario WASM da 7 MB viene caricato all'avvio e crea una superficie GPU sul canvas HTML. +Il renderer è suddiviso in moduli specializzati in `packages/core/src/renderer/`: attraversamento della scena, overlay, riempimenti, bordi, forme, effetti, righelli, etichette e cursori remoti. -### Grafo della scena +### Scene Graph -`Map` piatto indicizzato per stringhe GUID. Struttura ad albero tramite riferimenti `parentIndex`. Fornisce ricerca O(1), attraversamento efficiente, hit testing e query per area rettangolare per la selezione a marquee. +`Map` piatto indicizzato da stringhe GUID. Struttura ad albero tramite riferimenti `parentIndex`. Fornisce lookup O(1), attraversamento efficiente, hit testing e query per area rettangolare per la selezione con marquee. -Vedi [Riferimento del grafo della scena](/reference/scene-graph) per i dettagli interni. +Consulta il [riferimento Scene Graph](/it/reference/scene-graph) per i dettagli interni. -### Motore di layout (Yoga WASM) +### Motore di Layout (Yoga WASM) -Yoga di Meta fornisce il calcolo del layout CSS flexbox. Un sottile adattatore mappa i nomi delle proprietà Figma agli equivalenti Yoga: +Yoga di Meta fornisce il calcolo del layout CSS flexbox. Un adattatore sottile mappa i nomi delle proprietà Figma agli equivalenti Yoga: | Proprietà Figma | Equivalente Yoga | |---|---| @@ -73,24 +60,56 @@ Yoga di Meta fornisce il calcolo del layout CSS flexbox. Un sottile adattatore m | `stackJustify` | `justifyContent` | | `stackChildPrimaryGrow` | `flexGrow` | -### Formato file (Kiwi binario) +### Formato File (Kiwi Binary) -Riutilizza il collaudato codec binario Kiwi di Figma con 194 definizioni di messaggio/enum/struct. Pipeline di importazione `.fig`: analizzare header → decomprimere Zstd → decodificare Kiwi → NodeChange[] → grafo della scena. Il pipeline di esportazione inverte il processo: grafo della scena → NodeChange[] → codificare Kiwi → comprimere Zstd → ZIP con miniatura. +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. -Vedi [Riferimento del formato file](/reference/file-format) per maggiori dettagli. +Consulta il [riferimento Formato File](/it/reference/file-format) per i dettagli. + +### AI e Strumenti + +Gli strumenti sono definiti una sola volta in `packages/core/src/tools/`, suddivisi per dominio: read, create, modify, structure, variables, vector, analyze. Ogni strumento ha parametri tipizzati e una funzione `execute(figma, args)`. Gli adattatori li convertono per: + +- **Chat AI** — schema valibot, collegati a OpenRouter +- **Server MCP** — schema zod, trasporti stdio + HTTP +- **CLI** — disponibili tramite il comando `eval` + +87 strumenti core + 3 strumenti di gestione file MCP = 90 totali. ### Annulla/Ripristina -Pattern di comando inverso. Prima di applicare qualsiasi modifica, i campi interessati vengono catturati in uno snapshot. Lo snapshot diventa l'operazione inversa. Il batching raggruppa le modifiche rapide (come il trascinamento) in singole voci di annullamento. +Pattern a comandi inversi. Prima di applicare qualsiasi modifica, i campi interessati vengono salvati in uno snapshot. Lo snapshot diventa l'operazione inversa. Il batching raggruppa le modifiche rapide (come il trascinamento) in singole voci di annullamento. ### Appunti -Appunti bidirezionali compatibili con Figma. Codifica/decodifica binario Kiwi (stesso formato dei file .fig) usando gli eventi nativi copia/incolla del browser (sincroni, non l'API asincrona degli Appunti). L'incolla gestisce il ridimensionamento dei percorsi vettoriali, la popolazione dei figli delle istanze, il rilevamento dei set di componenti e l'applicazione degli override. - -### Server MCP - -`@open-pencil/mcp` espone 87 strumenti core + 3 strumenti di gestione file per strumenti di codifica IA. Due trasporti: stdio per Claude Code/Cursor/Windsurf, HTTP con Hono + Streamable HTTP per script e CI. Gli strumenti sono definiti una volta in `packages/core/src/tools/` e adattati per chat IA (valibot), MCP (zod) e CLI (comando eval). +Appunti bidirezionali compatibili con Figma. Codifica/decodifica binario Kiwi (stesso formato dei file .fig) tramite eventi nativi di copia/incolla del browser. Gestisce il ridimensionamento dei tracciati vettoriali, i figli delle istanze, il rilevamento dei set di componenti e l'applicazione degli override. ### Collaborazione P2P -Collaborazione peer-to-peer in tempo reale via Trystero (WebRTC) + Yjs CRDT. Senza server relay — segnalazione tramite broker MQTT pubblici, STUN/TURN per il traversal NAT. Il protocollo awareness fornisce cursori in tempo reale, selezioni e presenza. Persistenza locale tramite y-indexeddb. +Collaborazione peer-to-peer in tempo reale tramite Trystero (WebRTC) + Yjs CRDT. Nessun relay server — segnalazione tramite broker MQTT pubblici, STUN/TURN per l'attraversamento NAT. Il protocollo Awareness fornisce cursori live, selezioni e presenza. Persistenza locale tramite y-indexeddb. + +### Bridge RPC CLI-App + +Quando l'app desktop è in esecuzione, i comandi CLI si connettono tramite WebSocket invece di richiedere un file .fig. Il server di automazione è in esecuzione su `127.0.0.1:7600` (HTTP) e `127.0.0.1:7601` (WebSocket). I comandi vengono eseguiti sullo stato dell'editor live, consentendo a script di automazione e agenti AI di interagire con l'app in esecuzione. + +## Prossimi Passi + +### Set Completo di Strumenti figma-use + +Il server MCP attualmente espone 90 strumenti. L'implementazione di riferimento in [figma-use](https://github.com/dannote/figma-use) ne ha 118. Gli strumenti rimanenti coprono vincoli di layout avanzati, connessioni per prototipi, modifica avanzata delle proprietà dei componenti e operazioni in blocco sui documenti. + +### Strumenti di Design per CI + +La CLI headless supporta già `analyze colors/typography/spacing/clusters`. Prossimamente: integrazione con GitHub Actions per linting automatico del design e regressione visiva nelle PR. + +### Prototipazione + +Transizioni frame-to-frame, trigger di interazione (clic, hover, trascinamento), gestione degli overlay e modalità anteprima a schermo intero. + +### 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. + +### Firma del Codice per Windows + +I binari macOS sono firmati e autenticati dalla v0.6.0. La firma Windows Authenticode tramite Azure Code Signing è pianificata per rimuovere l'avviso SmartScreen. diff --git a/packages/docs/it/guide/features.md b/packages/docs/it/guide/features.md index c026d9a96..40c4ab6ca 100644 --- a/packages/docs/it/guide/features.md +++ b/packages/docs/it/guide/features.md @@ -1,201 +1,138 @@ # Funzionalità -## Perché OpenPencil +## File .fig di Figma -Gli strumenti di design sono un problema di catena di fornitura. Quando il tuo strumento è proprietario, il fornitore controlla ciò che è possibile. OpenPencil è un'alternativa open-source: licenza MIT, compatibile con Figma, completamente locale e programmabile. +Apri e salva file nativi di Figma direttamente. La pipeline di importazione/esportazione utilizza lo stesso codec binario Kiwi di Figma — 194 definizioni di schema, ~390 campi per nodo. Salva con S, Salva con nome con S. -## Import & export file .fig di Figma +**Copia e incolla con Figma** — seleziona i nodi in Figma, C, passa a OpenPencil, V. Riempimenti, bordi, auto-layout, testo, effetti, raggi degli angoli e reti vettoriali vengono preservati. Funziona in entrambe le direzioni. -Apri e salva file nativi Figma direttamente. L'import decodifica lo schema Kiwi completo a 194 definizioni inclusi i messaggi NodeChange con ~390 campi. L'export codifica il grafo della scena in binario Kiwi con compressione Zstd e generazione thumbnail. Salva (S) e Salva con nome (S) usano dialoghi nativi dell'OS. +## Disegno e Modifica -## Copia e incolla con Figma +- **Forme** — Rettangolo (R), Ellisse (O), Linea (L), Poligono, Stella +- **Strumento penna** — reti vettoriali (non semplici tracciati), curve di Bézier con maniglie tangenti +- **Testo** — modifica nativa sul canvas con supporto IME, doppio clic per entrare in modalità di modifica +- **Testo ricco** — grassetto per carattere (B), corsivo (I), sottolineato (U), barrato +- **Auto-layout** — flexbox tramite Yoga WASM: direzione, gap, padding, giustificazione, allineamento, dimensionamento figli. A per attivare/disattivare +- **Componenti** — crea (K), set di componenti (K), istanze con supporto override, sincronizzazione live +- **Variabili** — token di design con collezioni, modalità (Light/Dark), tipi colore/float/stringa/booleano, binding di variabili +- **Sezioni** — contenitori organizzativi con adozione automatica dei figli e etichette titolo -Seleziona nodi in Figma, C, passa a OpenPencil, V — appaiono con riempimenti, contorni, auto-layout, testo, raggi degli angoli, effetti e reti vettoriali preservati. Funziona anche al contrario. +## Pannello Proprietà -L'incolla gestisce scenari complessi: i percorsi vettoriali vengono ridimensionati dalla `normalizedSize` di Figma, i figli delle istanze vengono popolati dal `symbolData` del componente, i set di componenti vengono rilevati e i `symbolOverrides` vengono applicati. I font vengono caricati automaticamente. +Schede Design | Code | AI sensibili al contesto: -## Reti vettoriali +- **Aspetto** — opacità, raggio degli angoli (uniforme o per angolo), visibilità +- **Riempimento** — solido, gradiente (lineare/radiale/angolare/diamante), immagine +- **Bordo** — colore, spessore, allineamento (interno/centro/esterno), spessori per lato, terminazione, giunzione, tratteggio +- **Effetti** — ombra esterna, ombra interna, sfocatura livello, sfocatura sfondo, sfocatura primo piano +- **Tipografia** — selettore font con scroll virtuale e ricerca, peso, dimensione, allineamento, pulsanti stile +- **Layout** — controlli auto-layout quando attivo +- **Esportazione** — scala, formato (PNG/JPG/WEBP/SVG), anteprima live -Lo strumento penna usa il modello di rete vettoriale di Figma — non percorsi semplici. Click per punti angolari, click+trascinamento per curve di Bézier. Percorsi aperti e chiusi supportati. +## Rendering -## Strumenti forma +Skia (CanvasKit WASM) — lo stesso motore di rendering di Figma: -La barra strumenti fornisce tutti gli strumenti forma base di Figma: Rettangolo (R), Ellisse (O), Linea (L), Poligono e Stella. Tutti supportano riempimento, contorno, evidenziazione al passaggio e contorno di selezione. - -## Auto-Layout - -Yoga WASM fornisce il layout CSS flexbox. I frame supportano: direzione, gap, padding, justify, align e dimensionamento figli. Shift+A attiva/disattiva l'auto-layout. - -## Modifica testo inline - -Modifica testo nativa nel canvas. Doppio click su un nodo testo per entrare in modalità modifica. **Selettore font** con scroll virtuale, filtro di ricerca e anteprima CSS. In Tauri, i font di sistema sono enumerati via il crate Rust `font-kit`. - -## Formattazione testo ricco - -Formattazione per carattere: B grassetto, I corsivo, U sottolineato, o pulsanti B/I/U/S. Implementato via modello StyleRun. Preservato nell'import/export .fig. +- Riempimenti gradiente (lineare, radiale, angolare, diamante) +- Riempimenti immagine con modalità di scala +- Effetti con cache per nodo +- Dati arco (ellissi parziali, ciambelle) +- Culling del viewport e riutilizzo paint +- Guide di snap con allineamento sensibile alla rotazione +- Righelli sul canvas con badge di selezione +- Evidenziazione hover che segue la geometria reale ## Annulla/Ripristina -Ogni operazione è annullabile. Pattern di comando inverso. Z annulla, Z ripristina. +Ogni operazione è annullabile — creazione, eliminazione, spostamenti, ridimensionamenti, modifiche proprietà, riparentamento, modifiche layout, operazioni su variabili. Usa un pattern a comandi inversi. Z / Z. -## Guide di snap +## Documenti Multi-Pagina -Snap ai bordi e al centro con linee guida rosse. Consapevole della rotazione. +Aggiungi, elimina, rinomina pagine. Ogni pagina ha uno stato viewport indipendente. Doppio clic per rinominare inline. -## Righelli canvas +## Schede Multi-File -Righelli in alto e a sinistra mostrano scale di coordinate con badge di coordinate alla selezione. +Apri più documenti in schede. T nuova scheda, W chiudi, O apri file. -## Selettore colore e tipi di riempimento +## Esportazione -Selezione HSV con slider di tonalità, slider alfa, input hex e controllo opacità. Tipi: Solido, Gradiente (Lineare, Radiale, Angolare, Diamante) e Immagine. +- **Immagine** — PNG, JPG, WEBP a scala configurabile (0.5×–4×). Tramite pannello, menu contestuale o E +- **SVG** — forme, testo con stili per segmento, gradienti, effetti, modalità di fusione +- **Tailwind JSX** — HTML con classi utility Tailwind v4, pronto per React o Vue +- **Copia come** — testo, SVG, PNG (C), o JSX tramite menu contestuale -## Pannello livelli +CLI: `open-pencil export design.fig -f jsx --style tailwind` -Vista ad albero della gerarchia del documento. Pannelli ridimensionabili. +## Chat AI -## Pannello proprietà +Premi J per aprire l'assistente AI. 87 strumenti che possono creare forme, impostare stili, gestire layout, lavorare con componenti e variabili, eseguire operazioni booleane, analizzare token di design ed esportare risorse. Porta la tua chiave API OpenRouter. -Interfaccia a tab **Design** | **Codice** | **IA**. Il tab Design mostra sezioni contestuali: Aspetto, Riempimento, Contorno, Effetti, Tipografia, Layout, Posizione, Esportazione e Pagina. +Le chiamate agli strumenti vengono mostrate come voci di timeline comprimibili. Selettore modello con Claude, Gemini, GPT, DeepSeek e altri. -## Raggruppa/Separa +## Server MCP -⌘G raggruppa. ⇧⌘G separa. I nodi vengono ordinati per posizione visiva. +Connetti Claude Code, Cursor, Windsurf o qualsiasi client MCP per leggere e scrivere file `.fig` in modalità headless. 90 strumenti (87 core + 3 gestione file). Due trasporti: stdio e HTTP. -## Sezioni +```sh +bun add -g @open-pencil/mcp +``` -Le sezioni (S) sono contenitori organizzativi di livello superiore sul canvas con pillole di titolo e inversione automatica del colore del testo. +```json +{ + "mcpServers": { + "open-pencil": { + "command": "openpencil-mcp" + } + } +} +``` -## Documenti multi-pagina +Consulta il [riferimento strumenti MCP](/it/reference/mcp-tools) per l'elenco completo degli strumenti. -I documenti supportano più pagine. Ogni pagina mantiene uno stato viewport indipendente. +## CLI -## Evidenziazione al passaggio +Ispeziona, esporta e analizza file `.fig` dal terminale: -I nodi si evidenziano con un contorno che segue la geometria reale. +```sh +open-pencil tree design.fig # Albero dei nodi +open-pencil find design.fig --type TEXT # Ricerca +open-pencil export design.fig -f png # Render +open-pencil analyze colors design.fig # Audit colori +open-pencil analyze clusters design.fig # Pattern ripetuti +open-pencil eval design.fig -c "..." # Figma Plugin API +``` -## Rendering avanzato (Tier 1) +Quando l'app desktop è in esecuzione, ometti il file per controllare l'editor live tramite RPC: -Il renderer CanvasKit supporta le caratteristiche visive Tier 1 complete: riempimenti gradiente, riempimenti immagine, effetti, proprietà contorno, dati arco, culling viewport, riuso Paint e coalescenza RAF. +```sh +open-pencil tree # Documento live +open-pencil export -f png # Screenshot del canvas +``` -## Componenti e istanze +Tutti i comandi supportano `--json`. Installazione: `bun add -g @open-pencil/cli` -Componenti riutilizzabili (K), set (K), istanze via menu contestuale, stacca (B). **Sync in tempo reale** e **supporto override**. Etichette viola con icona diamante. +## Collaborazione in Tempo Reale -## Variabili +P2P tramite WebRTC — nessun server necessario. Condividi un link e modifica insieme. -Token di design con collezioni e modalità. Dialogo TanStack Table. Supporta COLOR con UI completa, FLOAT/STRING/BOOLEAN definiti. Tutte le operazioni sono annullabili. +- Cursori live con frecce colorate e etichette nome +- Avatar di presenza +- Modalità segui — clicca su un partecipante per seguire il suo viewport +- Persistenza locale tramite IndexedDB +- ID stanza sicuri tramite `crypto.getRandomValues()` -## Esportazione immagini +## Desktop e Web -PNG, JPG, WEBP con scala 0,5×–4×, anteprima live e E. +**Desktop** — Tauri v2, ~7 MB. macOS (firmato e autenticato), Windows, Linux. Menu nativi, offline, salvataggio automatico. -## Menu contestuale +**Web** — disponibile su [app.openpencil.dev](https://app.openpencil.dev), installabile come PWA su mobile con interfaccia ottimizzata per il touch. -Click destro per: Appunti, Ordine Z, Raggruppamento, Componenti (voci viola), Visibilità, Sposta a pagina. +**Homebrew:** -## Ordine Z, visibilità e blocco +```sh +brew install open-pencil/tap/open-pencil +``` -] porta in primo piano, [ invia in fondo. H visibilità. L blocco. +## Fallback Google Fonts -## App web e desktop - -OpenPencil funziona nel browser su [app.openpencil.dev](https://app.openpencil.dev). L'app desktop usa Tauri v2 (~5 MB). Funziona completamente offline. - -## Menu app (browser) - -Barra dei menu con reka-ui: **File**, **Modifica**, **Visualizza**, **Oggetto**, **Testo**, **Disponi**. Scorciatoie adattate alla piattaforma. Nascosto in Tauri. - -## Salvataggio automatico - -File salvati 3 secondi dopo l'ultima modifica. Debounce su `sceneVersion`. Disabilitato per documenti nuovi senza titolo. - -## Collaborazione P2P - -Collaborazione peer-to-peer in tempo reale — nessun server richiesto. Basato su Trystero (WebRTC) + Yjs (CRDT). - -- **Zero costi di hosting** — segnalazione via broker MQTT pubblici -- **Traversal NAT** — server Google STUN, Cloudflare STUN e Open Relay TURN -- **Cursori in tempo reale** — frecce colorate stile Figma con pillole di nome -- **Presenza** — avatar colorati -- **Modalità segui** — clicca sull'avatar di un peer per seguire il suo viewport -- **Persistenza locale** — y-indexeddb mantiene la stanza tra i ricaricamenti -- **Stanze sicure** — ID via `crypto.getRandomValues()` - -## Schede multi-file - -Apri più documenti in schede. N/T nuova scheda, W chiudi, O apri in nuova scheda. Ogni scheda mantiene il proprio stato documento. - -## Rendering effetti - -Rendering completo degli effetti Figma: **Ombra portata**, **Ombra interna**, **Sfocatura livello** (Gaussiana), **Sfocatura sfondo** (effetto vetro/satinato), **Sfocatura primo piano**. Cache SkPicture per nodo per le prestazioni. - -## Proprietà multi-selezione - -Seleziona più nodi e modifica le proprietà condivise. Valori comuni visualizzati normalmente, valori diversi mostrano "Mixed". Capovolgi H/V si applica a tutti i nodi. - -## ScrubInput - -Tutte le entrate numeriche usano interazione trascina-per-regolare. Supporta suffissi (°, px, %). - -## Build CI/CD - -GitHub Actions costruisce app Tauri sui tag di versione. macOS firmato e notarizzato. Note di release auto-popolate dal CHANGELOG.md. - -## @open-pencil/core e CLI - -Il motore è estratto in `packages/core/`. Il CLI fornisce: info, tree, find, export, analyze, node, pages, variables, eval. Tutti supportano `--json`. Il comando `eval` esegue JavaScript con API Plugin Figma. Vedi [Comando Eval](/eval-command). - -## Renderer JSX - -Creazione programmabile via TreeNode builder. Props shorthand stile Tailwind. - -## Chat IA - -Assistente IA integrato via J. **87 strumenti** in `packages/core/src/tools/` che coprono lettura, creazione, modifica, manipolazione nodi, CRUD variabili, strumenti vettoriali, controllo viewport e `eval`. **Server MCP** espone 90 strumenti totali (87 core + 3 gestione file) per strumenti di codifica IA esterni. - -**AI agent skill** — `npx skills add open-pencil/skills@open-pencil` — teaches AI coding agents to use the CLI, MCP tools, and automation bridge. Source: [open-pencil/skills](https://github.com/open-pencil/skills). - -## Export SVG - -Esporta i nodi selezionati come PNG, JPG, WEBP o SVG. CLI: `bun open-pencil export --format svg file.fig`. - -## Copia come - -Il sottomenu **Copia come** del menu contestuale offre: Copia come testo, SVG, PNG (C), JSX. - -## Allineamento contorno e spessori per lato - -Allineamento: **Interno**, **Centro** o **Esterno**. Spessori individuali per lato (Alto/Destra/Basso/Sinistra). - -## Layout mobile & PWA - -Installabile come PWA. Su mobile, i pannelli laterali sono sostituiti da un cassetto inferiore scorrevole con schede. - -## Export Tailwind CSS v4 - -La scheda Codice offre un selettore tra **OpenPencil JSX** e **Tailwind CSS v4** (HTML con classi utility). - -## Google Fonts Fallback - -Se un font non è disponibile localmente, OpenPencil lo carica automaticamente da Google Fonts API. - -## Homebrew Tap - -Su macOS: `brew install open-pencil/tap/open-pencil` - -## Rinomina inline livelli - -Doppio click sul nome di un livello per rinominarlo. Invio o clic altrove conferma, Esc annulla. - -## Profiler di rendering - -Overlay HUD con metriche di timing. Accessibile dal menu Visualizza. - -## Pannello codice - -Il tab Codice mostra il JSX della selezione con evidenziazione sintassi Prism.js e copia. - -## Qualità del codice - -Rilevamento copia-incolla via jscpd — duplicazione ridotta dal 15,6% allo 0,62%. Pipeline di importazione ottimizzato da O(n²) a O(n). +Quando un font non è disponibile localmente, OpenPencil lo scarica automaticamente da Google Fonts. Nessuna installazione manuale necessaria quando si aprono file .fig con font non familiari. diff --git a/packages/docs/it/index.md b/packages/docs/it/index.md index b4ddec76a..d4ab90880 100644 --- a/packages/docs/it/index.md +++ b/packages/docs/it/index.md @@ -1,16 +1,16 @@ --- layout: home -title: OpenPencil — Editor di Design IA-Nativo -description: Alternativa open-source a Figma. Completamente locale, IA-nativa, programmabile. +title: OpenPencil — Editor di Design Open Source +description: Alternativa open source a Figma. Apre file .fig, AI integrata, completamente programmabile. hero: name: OpenPencil - text: Editor di design IA-nativo - tagline: Alternativa open-source a Figma. Completamente locale, IA-nativa, programmabile. + text: Editor di Design Open Source + tagline: Apre file Figma. AI integrata. Completamente programmabile. Gratis per sempre. actions: - theme: brand - text: Prova online - link: https://app.openpencil.dev + text: Prova Online + link: https://app.openpencil.dev/demo - theme: alt text: Scarica link: https://github.com/open-pencil/open-pencil/releases/latest @@ -19,19 +19,22 @@ hero: link: https://github.com/open-pencil/open-pencil features: - - icon: 📖 - title: Open Source - details: Licenza MIT. Leggi e modifica tutto — l'editor, il motore, il codec dei file. - icon: 📂 title: Compatibile con Figma - details: Apre file .fig nativamente. Copia/incolla tra le app. Codec Kiwi con fedeltà round-trip. - - icon: 🤖 - title: IA-nativo - details: Chat integrata con uso degli strumenti. Porta la tua chiave API — nessun abbonamento, nessun vendor lock-in. - - icon: 🖥️ - title: Nessun abbonamento - details: Nessun account, nessun server, nessun internet necessario. Gratuito per sempre. App desktop ~5 MB. + details: Apre file .fig nativamente. Copia e incolla tra Figma e OpenPencil. Codec binario Kiwi con fedeltà round-trip. - icon: ⚡ title: Programmabile - details: CLI headless per ispezione ed esportazione .fig. Ogni operazione è scriptabile. Renderer JSX. + details: CLI headless per ispezionare, esportare e analizzare file .fig. Figma Plugin API tramite eval. Esportazione Tailwind CSS. Output JSON per CI. + - icon: 🤖 + title: AI Nativa + details: Chat integrata con 90 strumenti — crea forme, imposta stili, gestisci layout, analizza token. Server MCP per Claude Code, Cursor, Windsurf. + - icon: 📖 + title: Open Source + details: Licenza MIT. Leggi e modifica tutto — l'editor, il motore, il codec dei file, la CLI. + - icon: 🖥️ + title: Gratuito e Locale + details: Nessun account, nessun server, nessuna connessione richiesta. App desktop da ~7 MB tramite Homebrew, oppure usa l'app web. + - icon: 👥 + title: Collaborazione in Tempo Reale + details: P2P tramite WebRTC — nessun server. Condividi un link, modifica insieme con cursori live e modalità segui. --- diff --git a/packages/docs/pl/guide/architecture.md b/packages/docs/pl/guide/architecture.md index 6f5f6396c..6960e88e8 100644 --- a/packages/docs/pl/guide/architecture.md +++ b/packages/docs/pl/guide/architecture.md @@ -2,42 +2,33 @@ ## Przegląd systemu -``` -┌──────────────────────────────────────────────────────────────────┐ -│ Tauri v2 Shell │ -│ │ -│ ┌────────────────────────────────────────────────────────────┐ │ -│ │ Edytor (Web) │ │ -│ │ │ │ -│ │ Vue 3 UI Skia CanvasKit (WASM, 7MB) │ │ -│ │ - Pasek narzędzi - Renderowanie wektorowe │ │ -│ │ - Panele - Kształtowanie tekstu │ │ -│ │ - Właściwości - Przetwarzanie obrazów │ │ -│ │ - Warstwy - Efekty (rozmycie, cień) │ │ -│ │ - Selektor kolorów - Eksport (PNG, SVG, PDF) │ │ -│ │ │ │ -│ │ ┌──────────────────────────────────────────────────────┐ │ │ -│ │ │ Core Engine (TS) │ │ │ -│ │ │ SceneGraph ─── Layout (Yoga) ─── Selection │ │ │ -│ │ │ │ │ │ │ │ -│ │ │ Undo/Redo ─── Constraints ─── Hit Testing │ │ │ -│ │ └──────────────────────────────────────────────────────┘ │ │ -│ │ │ │ -│ │ ┌──────────────────────────────────────────────────────┐ │ │ -│ │ │ Warstwa formatu pliku │ │ │ -│ │ │ .fig import/export ── Kiwi codec ── .svg (planowane)│ │ │ -│ │ └──────────────────────────────────────────────────────┘ │ │ -│ └────────────────────────────────────────────────────────────┘ │ -│ │ -│ MCP Server (75+ tools, stdio+HTTP) P2P Collab (Trystero + Yjs) │ -└──────────────────────────────────────────────────────────────────┘ +```mermaid +graph TB + subgraph Tauri["Tauri v2 Shell"] + subgraph Editor["Editor (Web)"] + UI["Vue 3 UI
Toolbar · Panels · Properties
Layers · Color Picker"] + Skia["Skia CanvasKit (WASM, 7MB)
Vector rendering · Text shaping
Effects · Export"] + subgraph Core["Core Engine (TS)"] + SG[SceneGraph] --- Layout[Layout - Yoga] + SG --- Selection + Undo[Undo/Redo] --- Constraints + Constraints --- HitTest[Hit Testing] + end + subgraph FileFormat["File Format Layer"] + FigIO[".fig import/export"] --- Kiwi[Kiwi codec] + Kiwi --- SVG[SVG export] + end + end + MCP["MCP Server (90 tools, stdio+HTTP)"] + Collab["P2P Collab (Trystero + Yjs)"] + end ``` ## Układ edytora Interfejs podąża za layoutem UI3 Figmy — pasek narzędzi na dole, nawigacja po lewej, właściwości po prawej: -- **Panel nawigacji (lewy)** — Drzewo warstw, panel stron, biblioteka zasobów (planowane) +- **Panel nawigacji (lewy)** — Drzewo warstw, panel stron - **Canvas (środek)** — Nieskończony canvas z renderowaniem CanvasKit, zoom/pan - **Panel właściwości (prawy)** — Kontekstowe sekcje: Wygląd, Wypełnienie, Obrys, Typografia, Layout, Pozycja - **Pasek narzędzi (dół)** — Wybór narzędzia: Zaznacz, Frame, Sekcja, Prostokąt, Elipsa, Linia, Tekst, Pióro, Ręka @@ -46,13 +37,9 @@ Interfejs podąża za layoutem UI3 Figmy — pasek narzędzi na dole, nawigacja ### Renderowanie (CanvasKit WASM) -Ten sam silnik renderowania co Figma. CanvasKit zapewnia rysowanie 2D z akceleracją GPU: -- Kształty wektorowe (prostokąt, elipsa, ścieżka, linia, gwiazda, wielokąt) -- Kształtowanie tekstu przez Paragraph API -- Efekty (cienie, rozmycia, tryby mieszania) -- Eksport (PNG, SVG, PDF) +Ten sam silnik renderowania co Figma. CanvasKit zapewnia rysowanie 2D z akceleracją GPU z kształtami wektorowymi, kształtowaniem tekstu przez Paragraph API, efektami (cienie, rozmycia, tryby mieszania) i eksportem (PNG, SVG). Binarny plik WASM o wielkości 7 MB ładuje się przy starcie i tworzy powierzchnię GPU na canvasie HTML. -Binarny plik WASM o wielkości 7 MB ładuje się przy starcie i tworzy powierzchnię GPU na canvasie HTML. +Renderer jest podzielony na wyspecjalizowane moduły w `packages/core/src/renderer/`: przechodzenie sceny, nakładki, wypełnienia, obrysy, kształty, efekty, linijki, etykiety i zdalne kursory. ### Graf sceny @@ -75,22 +62,54 @@ Yoga od Mety zapewnia obliczanie layoutu CSS flexbox. Cienki adapter mapuje nazw ### Format pliku (Kiwi binarny) -Wykorzystuje sprawdzony binarny kodek Kiwi Figmy z 194 definicjami wiadomości/enum/struct. Pipeline importu `.fig`: parsowanie nagłówka → dekompresja Zstd → dekodowanie Kiwi → NodeChange[] → graf sceny. Pipeline eksportu odwraca proces: graf sceny → NodeChange[] → kodowanie Kiwi → kompresja Zstd → ZIP z 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. +### AI i narzędzia + +Narzędzia są definiowane raz w `packages/core/src/tools/`, podzielone wg domeny: read, create, modify, structure, variables, vector, analyze. Każde narzędzie ma typowane parametry i funkcję `execute(figma, args)`. Adaptery konwertują je dla: + +- **Chat AI** — schematy valibot, podłączone do OpenRouter +- **Serwer MCP** — schematy zod, transporty stdio + HTTP +- **CLI** — dostępne przez komendę `eval` + +87 narzędzi core + 3 narzędzia zarządzania plikami MCP = 90 łącznie. + ### Cofnij/Ponów Wzorzec komendy odwrotnej. Przed zastosowaniem jakiejkolwiek zmiany, dotknięte pola są zrzucane do snapshotu. Snapshot staje się operacją odwrotną. Batching grupuje szybkie zmiany (jak przeciąganie) w pojedyncze wpisy cofania. ### Schowek -Dwukierunkowy schowek kompatybilny z Figmą. Koduje/dekoduje binarne Kiwi (ten sam format co pliki .fig) używając natywnych zdarzeń kopiuj/wklej przeglądarki (synchronicznych, nie asynchronicznego API Schowka). Wklejanie obsługuje skalowanie ścieżek wektorowych, wypełnianie dzieci instancji, wykrywanie zestawów komponentów i stosowanie nadpisań. - -### Serwer MCP - -`@open-pencil/mcp` udostępnia 87 narzędzi core + 3 narzędzia zarządzania plikami dla narzędzi kodowania AI. Dwa transporty: stdio dla Claude Code/Cursor/Windsurf, HTTP z Hono + Streamable HTTP dla skryptów i CI. Narzędzia są definiowane raz w `packages/core/src/tools/` i adaptowane dla chatu AI (valibot), MCP (zod) i CLI (polecenie eval). +Dwukierunkowy schowek kompatybilny z Figmą. Koduje/dekoduje binarne Kiwi (ten sam format co pliki .fig) przez natywne zdarzenia kopiuj/wklej przeglądarki. Obsługuje skalowanie ścieżek wektorowych, dzieci instancji, wykrywanie zestawów komponentów i stosowanie nadpisań. ### Współpraca P2P Współpraca peer-to-peer w czasie rzeczywistym przez Trystero (WebRTC) + Yjs CRDT. Bez serwera relay — sygnalizacja przez publiczne brokery MQTT, STUN/TURN dla traversalu NAT. Protokół awareness zapewnia kursory na żywo, selekcje i obecność. Lokalna persystencja przez y-indexeddb. + +### Most RPC CLI-do-Aplikacji + +Gdy aplikacja desktopowa jest uruchomiona, komendy CLI łączą się z nią przez WebSocket zamiast wymagać pliku .fig. Serwer automatyzacji działa na `127.0.0.1:7600` (HTTP) i `127.0.0.1:7601` (WebSocket). Komendy wykonują się na stanie edytora na żywo, umożliwiając skryptom automatyzacji i agentom AI interakcję z uruchomioną aplikacją. + +## Co dalej + +### Pełny zestaw narzędzi figma-use + +Serwer MCP obecnie udostępnia 90 narzędzi. Referencyjna implementacja w [figma-use](https://github.com/dannote/figma-use) ma 118. Pozostałe narzędzia obejmują zaawansowane ograniczenia layoutu, połączenia prototypów, zaawansowaną edycję właściwości komponentów i masowe operacje na dokumentach. + +### Narzędzia CI do designu + +Headless CLI już obsługuje `analyze colors/typography/spacing/clusters`. Następnie: integracja z GitHub Actions dla automatycznego lintingu designu i regresji wizualnej w PR-ach. + +### Prototypowanie + +Przejścia między ramkami, wyzwalacze interakcji (kliknięcie, najechanie, przeciągnięcie), zarządzanie nakładkami i tryb podglądu pełnoekranowego. + +### 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. + +### Podpisywanie kodu Windows + +Binaria macOS są podpisane i notaryzowane od v0.6.0. Podpisywanie Windows Authenticode przez Azure Code Signing jest planowane aby usunąć ostrzeżenie SmartScreen. diff --git a/packages/docs/pl/guide/features.md b/packages/docs/pl/guide/features.md index d85f94fdb..5bff3abaf 100644 --- a/packages/docs/pl/guide/features.md +++ b/packages/docs/pl/guide/features.md @@ -1,201 +1,138 @@ # Funkcje -## Dlaczego OpenPencil +## Pliki .fig Figmy -Narzędzia projektowe to problem łańcucha dostaw. Gdy narzędzie jest zamknięte, dostawca kontroluje co jest możliwe — może zepsuć automatyzację z dnia na dzień. OpenPencil to alternatywa open-source: licencja MIT, kompatybilny z Figmą, w pełni lokalny i programowalny. +Otwieraj i zapisuj natywne pliki Figmy bezpośrednio. Pipeline importu/eksportu używa tego samego binarnego kodeka Kiwi co Figma — 194 definicje schematu, ~390 pól na węzeł. Zapisz: S, Zapisz jako: S. -## Import i eksport plików .fig Figmy +**Kopiuj i wklej z Figmą** — zaznacz węzły w Figmie, C, przełącz się na OpenPencil, V. Wypełnienia, obrysy, auto-layout, tekst, efekty, promienie narożników i sieci wektorowe są zachowane. Działa w obie strony. -Otwieraj i zapisuj natywne pliki Figmy bezpośrednio. Import dekoduje pełny schemat Kiwi z 194 definicjami w tym wiadomości NodeChange z ~390 polami. Eksport koduje graf sceny z powrotem do binarnego Kiwi z kompresją Zstd i generowaniem miniatur. Zapisz (S) i Zapisz jako (S) używają natywnych okien dialogowych OS. +## Rysowanie i edycja -## Kopiuj i wklej z Figmą - -Zaznacz węzły w Figmie, C, przełącz się na OpenPencil, V — pojawiają się z wypełnieniami, obrysami, auto-layoutem, tekstem, promieniami narożników, efektami i sieciami wektorowymi. Działa też w drugą stronę. - -Wklejanie obsługuje złożone scenariusze: ścieżki wektorowe są skalowane z `normalizedSize` Figmy, dzieci instancji są wypełniane z `symbolData` komponentu, zestawy komponentów są wykrywane, a `symbolOverrides` są stosowane. Czcionki są ładowane automatycznie. - -## Sieci wektorowe - -Narzędzie pióro używa modelu sieci wektorowej Figmy — nie prostych ścieżek. Kliknij dla punktów narożnych, kliknij+przeciągnij dla krzywych Béziera. Obsługa ścieżek otwartych i zamkniętych. - -## Narzędzia kształtów - -Pasek narzędzi udostępnia wszystkie podstawowe narzędzia kształtów Figmy: Prostokąt (R), Elipsa (O), Linia (L), Wielokąt i Gwiazda. Wszystkie obsługują wypełnienie, obrys, podświetlenie przy najechaniu i kontur zaznaczenia. - -## Auto-Layout - -Yoga WASM zapewnia layout CSS flexbox. Ramki obsługują: kierunek, gap, padding, justify, align i wymiarowanie dzieci. Shift+A przełącza auto-layout. - -## Edycja tekstu inline - -Natywna edycja tekstu na canvasie. Podwójne kliknięcie na węźle tekstowym wchodzi w tryb edycji. **Wybieracz czcionek** z wirtualnym przewijaniem, filtrem wyszukiwania i podglądem CSS. W Tauri czcionki systemowe są enumerowane przez crate Rust `font-kit`. - -## Formatowanie tekstu bogatego - -Formatowanie per-znak: B pogrubienie, I kursywa, U podkreślenie, lub przyciski B/I/U/S. Zaimplementowane przez model StyleRun. Zachowane przy imporcie/eksporcie .fig. - -## Cofnij/Ponów - -Każda operacja jest cofalna. Wzorzec komendy odwrotnej. Z cofa, Z ponawia. - -## Prowadnice snap - -Przyciąganie do krawędzi i centrów z czerwonymi liniami prowadzącymi. Uwzględnia rotację. - -## Linijki canvasu - -Linijki na górze i po lewej pokazują skale współrzędnych z badge'ami współrzędnych przy zaznaczeniu. - -## Wybieracz kolorów i typy wypełnień - -Wybór koloru HSV ze sliderem odcienia, sliderem alfa, wejściem hex i kontrolą przezroczystości. Typy: Jednolity, Gradient (Liniowy, Radialny, Kątowy, Diamentowy) i Obraz. - -## Panel warstw - -Widok drzewa hierarchii dokumentu. Panele są zmiennych rozmiarów. +- **Kształty** — Prostokąt (R), Elipsa (O), Linia (L), Wielokąt, Gwiazda +- **Narzędzie pióro** — sieci wektorowe (nie proste ścieżki), krzywe Béziera z uchwytami stycznych +- **Tekst** — natywna edycja na canvasie z obsługą IME, podwójne kliknięcie aby wejść w tryb edycji +- **Tekst bogaty** — formatowanie per-znak: pogrubienie (B), kursywa (I), podkreślenie (U), przekreślenie +- **Auto-layout** — flexbox przez Yoga WASM: kierunek, gap, padding, justify, align, wymiarowanie dzieci. A aby przełączyć +- **Komponenty** — tworzenie (K), zestawy komponentów (K), instancje z obsługą nadpisań, synchronizacja na żywo +- **Zmienne** — tokeny projektowe z kolekcjami, trybami (Light/Dark), typami color/float/string/boolean, wiązaniem zmiennych +- **Sekcje** — kontenery organizacyjne z automatyczną adopcją dzieci i pigułkami tytułu ## Panel właściwości -Interfejs z kartami **Design** | **Kod** | **AI**. Karta Design pokazuje sekcje kontekstowe: Wygląd, Wypełnienie, Obrys, Efekty, Typografia, Layout, Pozycja, Eksport i Strona. +Kontekstowe karty Design | Kod | AI: -## Grupuj/Rozgrupuj +- **Wygląd** — przezroczystość, promień narożnika (jednolity lub per-narożnik), widoczność +- **Wypełnienie** — jednolite, gradient (liniowy/radialny/kątowy/diamentowy), obraz +- **Obrys** — kolor, grubość, wyrównanie (wewnątrz/środek/na zewnątrz), grubości per-strona, zakończenie, łączenie, kreska +- **Efekty** — cień rzutowany, cień wewnętrzny, rozmycie warstwy, rozmycie tła, rozmycie pierwszego planu +- **Typografia** — wybieracz czcionek z wirtualnym przewijaniem i wyszukiwaniem, grubość, rozmiar, wyrównanie, przyciski stylu +- **Layout** — kontrolki auto-layoutu gdy włączony +- **Eksport** — skala, format (PNG/JPG/WEBP/SVG), podgląd na żywo -⌘G grupuje. ⇧⌘G rozgrupowuje. Węzły są sortowane wg pozycji wizualnej. +## Renderowanie -## Sekcje +Skia (CanvasKit WASM) — ten sam silnik renderowania co Figma: -Sekcje (S) to kontenery organizacyjne najwyższego poziomu na canvasie z pigułkami tytułu i automatyczną inwersją koloru tekstu. +- Wypełnienia gradientowe (liniowe, radialne, kątowe, diamentowe) +- Wypełnienia obrazem z trybami skalowania +- Efekty z cache'owaniem per-węzeł +- Dane łuku (częściowe elipsy, donuty) +- Culling viewportu i ponowne użycie paint +- Prowadnice snap z wyrównywaniem uwzględniającym rotację +- Linijki canvasu z badge'ami zaznaczenia +- Podświetlenie przy najechaniu podążające za rzeczywistą geometrią + +## Cofnij/Ponów + +Każda operacja jest cofalna — tworzenie, usuwanie, przesuwanie, zmiana rozmiaru, zmiana właściwości, zmiana rodzica, zmiany layoutu, operacje na zmiennych. Wzorzec komendy odwrotnej. Z / Z. ## Dokumenty wielostronicowe -Dokumenty obsługują wiele stron. Każda strona utrzymuje niezależny stan viewportu. - -## Podświetlenie przy najechaniu - -Węzły podświetlają się konturem podążającym za rzeczywistą geometrią. - -## Zaawansowane renderowanie (Tier 1) - -Renderer CanvasKit obsługuje pełne cechy wizualne Tier 1: wypełnienia gradientowe, wypełnienia obrazem, efekty, właściwości obrysu, dane łuku, culling viewportu, ponowne użycie Paint i koalescencja RAF. - -## Komponenty i instancje - -Komponenty wielokrotnego użytku (K), zestawy (K), instancje przez menu kontekstowe, odłącz (B). **Synchronizacja na żywo** i **obsługa nadpisań**. Fioletowe etykiety z ikoną diamentu. - -## Zmienne - -Tokeny projektowe z kolekcjami i trybami. Dialog TanStack Table. Obsługuje COLOR z pełnym UI, FLOAT/STRING/BOOLEAN zdefiniowane. Wszystkie operacje są cofalne. - -## Eksport obrazów - -PNG, JPG, WEBP ze skalą 0,5×–4×, podgląd na żywo i E. - -## Menu kontekstowe - -Kliknij prawym dla: Schowek, Kolejność Z, Grupowanie, Komponenty (fioletowe pozycje), Widoczność, Przenieś na stronę. - -## Kolejność Z, widoczność i blokada - -] przenosi na wierzch, [ wysyła na spód. H widoczność. L blokada. - -## Aplikacja webowa i desktopowa - -OpenPencil działa w przeglądarce na [app.openpencil.dev](https://app.openpencil.dev). Aplikacja desktopowa używa Tauri v2 (~5 MB). Działa w pełni offline. - -## Menu aplikacji (przeglądarka) - -Pasek menu z reka-ui: **Plik**, **Edycja**, **Widok**, **Obiekt**, **Tekst**, **Rozmieszczenie**. Skróty klawiszowe dostosowane do platformy. Ukryte w Tauri. - -## Automatyczny zapis - -Pliki zapisywane 3 sekundy po ostatniej zmianie. Debounce na `sceneVersion`. Wyłączone dla nowych dokumentów bez tytułu. - -## Współpraca P2P - -Współpraca peer-to-peer w czasie rzeczywistym — bez serwera. Oparta na Trystero (WebRTC) + Yjs (CRDT). - -- **Zero kosztów hostingu** — sygnalizacja przez publiczne brokery MQTT -- **Traversal NAT** — serwery Google STUN, Cloudflare STUN i Open Relay TURN -- **Kursory na żywo** — kolorowe strzałki w stylu Figmy z pigułkami imion -- **Obecność** — kolorowe awatary -- **Tryb śledzenia** — kliknij awatar peera aby śledzić jego viewport -- **Lokalna persystencja** — y-indexeddb utrzymuje pokój między przeładowaniami -- **Bezpieczne pokoje** — ID przez `crypto.getRandomValues()` +Dodawaj, usuwaj, zmieniaj nazwy stron. Każda strona ma niezależny stan viewportu. Podwójne kliknięcie aby zmienić nazwę inline. ## Karty wieloplikowe -Otwieraj wiele dokumentów w kartach. N/T nowa karta, W zamknij, O otwórz w nowej karcie. Każda karta utrzymuje własny stan dokumentu. +Otwieraj wiele dokumentów w kartach. T nowa karta, W zamknij, O otwórz plik. -## Renderowanie efektów +## Eksport -Pełne renderowanie efektów Figmy: **Cień rzutowany**, **Cień wewnętrzny**, **Rozmycie warstwy** (Gaussowskie), **Rozmycie tła** (efekt szkła/matowania), **Rozmycie pierwszego planu**. Cache SkPicture per węzeł dla wydajności. +- **Obraz** — PNG, JPG, WEBP w konfigurowalnej skali (0,5×–4×). Przez panel, menu kontekstowe lub E +- **SVG** — kształty, tekst z przebiegami stylów, gradienty, efekty, tryby mieszania +- **Tailwind JSX** — HTML z klasami utility Tailwind v4, gotowy dla React lub Vue +- **Kopiuj jako** — tekst, SVG, PNG (C) lub JSX przez menu kontekstowe -## Właściwości wielokrotnego zaznaczenia - -Zaznacz wiele węzłów i edytuj wspólne właściwości. Wspólne wartości wyświetlane normalnie, różne pokazują "Mixed". Odwróć H/V dotyczy wszystkich węzłów. - -## ScrubInput - -Wszystkie wejścia numeryczne używają interakcji przeciągnij-aby-zmienić. Obsługuje sufiksy (°, px, %). - -## Budowanie CI/CD - -GitHub Actions buduje aplikacje Tauri na tagach wersji. macOS podpisany i notaryzowany. Noty wydania auto-wypełniane z CHANGELOG.md. - -## @open-pencil/core i CLI - -Silnik wyodrębniony do `packages/core/`. CLI udostępnia: info, tree, find, export, analyze, node, pages, variables, eval. Wszystko obsługuje `--json`. Komenda `eval` wykonuje JavaScript z API Plugin Figma. Zobacz [Komenda Eval](/eval-command). - -## Renderer JSX - -Programistyczne tworzenie designu przez buildery TreeNode. Propsy shorthand w stylu Tailwind. +CLI: `open-pencil export design.fig -f jsx --style tailwind` ## Chat AI -Wbudowany asystent AI przez J. **87 narzędzi** w `packages/core/src/tools/` obejmujących: odczyt, tworzenie, modyfikację, manipulację węzłów, CRUD zmiennych, narzędzia wektorowe, kontrolę viewportu i `eval`. **Serwer MCP** udostępnia 90 narzędzi łącznie (87 core + 3 zarządzanie plikami) dla zewnętrznych narzędzi kodowania AI. +Naciśnij J aby otworzyć asystenta AI. 87 narzędzi do tworzenia kształtów, ustawiania stylów, zarządzania layoutem, pracy z komponentami i zmiennymi, operacji boolowskich, analizy tokenów projektowych i eksportu zasobów. Użyj własnego klucza API OpenRouter. -**AI agent skill** — `npx skills add open-pencil/skills@open-pencil` — teaches AI coding agents to use the CLI, MCP tools, and automation bridge. Source: [open-pencil/skills](https://github.com/open-pencil/skills). +Wywołania narzędzi wyświetlane jako zwijane wpisy na osi czasu. Selektor modeli z Claude, Gemini, GPT, DeepSeek i innymi. -## Eksport SVG +## Serwer MCP -Eksportuje wybrane węzły jako PNG, JPG, WEBP lub SVG. CLI: `bun open-pencil export --format svg file.fig`. +Podłącz Claude Code, Cursor, Windsurf lub dowolnego klienta MCP do odczytu i zapisu plików `.fig` headlessly. 90 narzędzi (87 core + 3 zarządzanie plikami). Dwa transporty: stdio i HTTP. -## Kopiuj jako +```sh +bun add -g @open-pencil/mcp +``` -Podmenu **Kopiuj jako** w menu kontekstowym oferuje: Kopiuj jako tekst, SVG, PNG (C), JSX. +```json +{ + "mcpServers": { + "open-pencil": { + "command": "openpencil-mcp" + } + } +} +``` -## Wyrównanie obrysu i grubości per-strona +Zobacz [Referencja narzędzi MCP](/reference/mcp-tools) dla pełnej listy narzędzi. -Wyrównanie: **Wewnątrz**, **Środek** lub **Na zewnątrz**. Indywidualne grubości per-strona (Góra/Prawo/Dół/Lewo). +## CLI -## Układ mobilny & PWA +Inspekcja, eksport i analiza plików `.fig` z terminala: -Instalowalne jako PWA. Na urządzeniach mobilnych panele boczne zastąpione przez wysuwaną szufladę dolną z zakładkami. +```sh +open-pencil tree design.fig # Drzewo węzłów +open-pencil find design.fig --type TEXT # Wyszukiwanie +open-pencil export design.fig -f png # Renderowanie +open-pencil analyze colors design.fig # Audyt kolorów +open-pencil analyze clusters design.fig # Powtarzające się wzorce +open-pencil eval design.fig -c "..." # Figma Plugin API +``` -## Eksport Tailwind CSS v4 +Gdy aplikacja desktopowa jest uruchomiona, pomiń plik aby sterować edytorem na żywo przez RPC: -Zakładka Kod oferuje przełącznik między **OpenPencil JSX** a **Tailwind CSS v4** (HTML z klasami utility). +```sh +open-pencil tree # Aktywny dokument +open-pencil export -f png # Zrzut ekranu canvasu +``` + +Wszystkie komendy obsługują `--json`. Instalacja: `bun add -g @open-pencil/cli` + +## Współpraca w czasie rzeczywistym + +P2P przez WebRTC — bez serwera. Udostępnij link i edytujcie razem. + +- Kursory na żywo z kolorowymi strzałkami i pigułkami imion +- Awatary obecności +- Tryb śledzenia — kliknij peera aby śledzić jego viewport +- Lokalna persystencja przez IndexedDB +- Bezpieczne ID pokojów przez `crypto.getRandomValues()` + +## Desktop i Web + +**Desktop** — Tauri v2, ~7 MB. macOS (podpisany i notaryzowany), Windows, Linux. Natywne menu, tryb offline, automatyczny zapis. + +**Web** — działa na [app.openpencil.dev](https://app.openpencil.dev), instalowalny jako PWA na urządzeniach mobilnych z UI zoptymalizowanym pod dotyk. + +**Homebrew:** + +```sh +brew install open-pencil/tap/open-pencil +``` ## Google Fonts Fallback -Gdy czcionka nie jest dostępna lokalnie, OpenPencil ładuje ją automatycznie z Google Fonts API. - -## Homebrew Tap - -Na macOS: `brew install open-pencil/tap/open-pencil` - -## Inline zmiana nazwy warstw - -Dwuklik na nazwie warstwy aby ją zmienić. Enter lub klik poza polem zatwierdza, Escape anuluje. - -## Profiler renderowania - -Nakładka HUD z metrykami czasu renderowania. Dostępna z menu Widok. - -## Panel kodu - -Karta Kod pokazuje JSX zaznaczenia z podświetlaniem składni Prism.js i kopiowaniem. - -## Jakość kodu - -Wykrywanie kopiuj-wklej przez jscpd — duplikacja zredukowana z 15,6% do 0,62%. Pipeline importu zoptymalizowany z O(n²) do O(n). +Gdy czcionka nie jest dostępna lokalnie, OpenPencil pobiera ją automatycznie z Google Fonts. Nie trzeba ręcznie instalować czcionek przy otwieraniu plików .fig z nieznanymi fontami. diff --git a/packages/docs/pl/index.md b/packages/docs/pl/index.md index f37d2049b..b33115ef6 100644 --- a/packages/docs/pl/index.md +++ b/packages/docs/pl/index.md @@ -1,16 +1,16 @@ --- layout: home -title: OpenPencil — Edytor Graficzny z Natywnym AI -description: Open-source'owa alternatywa dla Figma. W pełni lokalna, natywnie AI, programowalna. +title: OpenPencil — Open-Source'owy Edytor Graficzny +description: Open-source'owa alternatywa dla Figma. Otwiera pliki .fig, wbudowane AI, w pełni programowalny. hero: name: OpenPencil - text: Edytor graficzny z natywnym AI - tagline: Open-source'owa alternatywa dla Figma. W pełni lokalna, natywnie AI, programowalna. + text: Open-Source'owy Edytor Graficzny + tagline: Otwiera pliki Figmy. Wbudowane AI. W pełni programowalny. Za darmo na zawsze. actions: - theme: brand text: Wypróbuj online - link: https://app.openpencil.dev + link: https://app.openpencil.dev/demo - theme: alt text: Pobierz link: https://github.com/open-pencil/open-pencil/releases/latest @@ -19,19 +19,22 @@ hero: link: https://github.com/open-pencil/open-pencil features: - - icon: 📖 - title: Open Source - details: Licencja MIT. Czytaj i modyfikuj wszystko — edytor, silnik, kodek plików. - icon: 📂 title: Kompatybilny z Figmą - details: Otwiera pliki .fig natywnie. Kopiuj/wklej między aplikacjami. Kodek Kiwi z wiernością round-trip. - - icon: 🤖 - title: Natywne AI - details: Wbudowany chat z obsługą narzędzi. Użyj własnego klucza API — bez subskrypcji, bez uzależnienia od dostawcy. - - icon: 🖥️ - title: Bez subskrypcji - details: Bez konta, bez serwera, bez internetu. Za darmo na zawsze. Aplikacja desktopowa ~5 MB. + details: Otwiera pliki .fig natywnie. Kopiuj i wklej między Figmą a OpenPencil. Kodek binarny Kiwi z wiernością round-trip. - icon: ⚡ title: Programowalny - details: Headless CLI do inspekcji i eksportu .fig. Każda operacja jest skryptowalna. Renderer JSX. + details: Headless CLI do inspekcji, eksportu i analizy plików .fig. Figma Plugin API przez eval. Eksport Tailwind CSS. Wyjście JSON dla CI. + - icon: 🤖 + title: Natywne AI + details: Wbudowany chat z 90 narzędziami — tworzenie kształtów, ustawianie stylów, zarządzanie layoutem, analiza tokenów. Serwer MCP dla Claude Code, Cursor, Windsurf. + - icon: 📖 + title: Open Source + details: Licencja MIT. Czytaj i modyfikuj wszystko — edytor, silnik, kodek plików, CLI. + - icon: 🖥️ + title: Darmowy i lokalny + details: Bez konta, bez serwera, bez internetu. Aplikacja desktopowa ~7 MB przez Homebrew, lub korzystaj z aplikacji webowej. + - icon: 👥 + title: Współpraca w czasie rzeczywistym + details: P2P przez WebRTC — bez serwera. Udostępnij link, edytujcie razem z kursorami na żywo i trybem śledzenia. ---