AI-native design editor. Open-source Figma alternative.
feat: add Figma-style variants and component libraries (#512)
Danila Poyarkovb93ffea073c2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1dc9237ff..3c94d0cdb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,44 +2,7 @@## Unreleased-### Added--- Show Figma-style temporary distance measurements between selected and Option/Alt-hovered layers. (#491)-- Add a reproducible Dev Container for web, package, CLI, and non-browser test development.-- Add local crash recovery for unsaved and pathless documents, including MCP-created documents. (#487)-- Add isolated visual inspection that sends bounded selection renders to the configured Vision model and returns text findings without retaining image data in Design chat history. (#232, #471)-- Add image attachments to AI chat with bounded analysis, immediate transcript thumbnails, hover previews, and click-to-view images. (#232)-- Allow supported AI model profiles to set a provider-specific reasoning effort. (#454)-- Show unavailable or substituted document fonts with affected-layer selection and retry actions, and expose font fidelity through the Figma API and MCP tooling. (#503)--### Performance--- Defer JSX generation and syntax highlighting until the Code panel is active, keeping large canvas selections responsive. (#500)-- Index Figma clipboard children once during import instead of rescanning every pasted node, keeping large flat pastes linear. (#500)-- Reduce peak memory during `.fig` export by sharing immutable binary resources with the isolated export graph.--### Fixed--- Transfer native `.fig` exports over binary Tauri IPC instead of JSON byte arrays, preventing large desktop saves from being truncated or exhausting WebView memory. (#484)-- Keep unsaved source-less documents recoverable after their editor tab is closed, matching Figma's retained offline-change behavior.-- Decode zstd-compressed FIG containers, reject invalid compressed payloads, and preserve exact fixture byte ranges. (#397)-- Compose caller CSS with Tailwind defaults when importing DOM/CSS documents. (#397)-- Preserve desktop HTTP timeout, abort, and empty-response semantics. (#397)-- Escape Vue SDK test selectors when the browser `CSS` global is unavailable. (#397)-- Report whether missing Figma clipboard images were actually fetched. (#397)-- Report exhausted provider credit, request failures, and output-token limits through localized chat toasts and copied diagnostics. (#451, #454)-- Prevent Windows desktop crashes when loading large system fonts for non-Latin text.-- Preserve open vector segments when the same vector network also contains filled regions. (#450)-- Match Figma Plugin API behavior for `rescale()`, page `backgrounds`, and nullable visual `absoluteRenderBounds`. (#442)-- Keep imported Figma instances linked to their remapped source components so later component edits update existing instances. (#385)-- Restore native copy, cut, and paste shortcuts in desktop text inputs while preserving design clipboard handling on the canvas.-- Remove the permanent CORS configuration action from cloud-storage settings and report connection results through standard toasts with clear browser-specific guidance.-- Complete translated app, accessibility, font, color, collaboration, import, connection-test, and browser fallback text across all supported locales, and keep the document language synchronized with the selected locale.-- Preserve effective nested instance text overrides when importing complex Figma component hierarchies. (#102)-- Preserve SVG clip paths, including clip shapes referenced through `<use>`, when importing editable vectors.-- Preserve circles, ellipses, rectangles, lines, polylines, and polygons supplied as JSX children of inline SVG elements. (#452)--## 0.14.0 — 2026-08-10+## 0.14.0 - 2026-08-10### Breaking changes@@ -52,10 +15,30 @@- Export selections, pages, and documents as editable PowerPoint (`.pptx`) files from the File menu, CLI, and SDK. Text, rectangles, ellipses, and lines remain editable; visually complex layers are embedded as images.- Import HTML, CSS, Tailwind, and JSX as editable documents from the app, CLI, and SDK, and export standalone browser-ready HTML with compiled CSS and optional external assets.- Drag image files into the desktop app and paste Figma layers with their remote image fills.-- Import dropped SVG files as editable vector layers, preserving compatible multi-color fills and transparent paints. (#386, #392, #394, #446).-- Convert image layers into editable vectors with Recraft or fal.ai from the canvas context menu. (#322).-- Browse document components as thumbnails or a list in the Assets panel, group them by page, and drag instances directly onto the canvas. (#424).-- Create centered frames from Figma-style device and asset presets, or resize selected frames to a preset while preserving their names. (#418).+- Import dropped SVG files as editable vector layers, preserving compatible multi-color fills and transparent paints. (#386, #392, #394, #446)+- Convert image layers into editable vectors with Recraft or fal.ai from the canvas context menu. (#322)+- Browse document components as thumbnails or a list in the Assets panel, group them by page, and drag instances directly onto the canvas. (#424)+- Author multidimensional component variants in the Design panel, including property/value renaming, sparse-combination diagnostics, variant duplication, and exact instance transitions. (#239)+- Create deterministic, dependency-complete component-library revisions through the provider-neutral Core library catalog, with browser IndexedDB persistence for local catalogs. (#239)+- Enable published component libraries per document, browse their assets alongside local components, and lazily materialize read-only definitions for offline linked instances. (#239)+- Detect newer component-library revisions and explicitly apply stable-key updates to linked instances while preserving assignments and retaining old definitions. (#239)+- Let AI, MCP, and headless tools discover enabled library components, rank preferred libraries before local assets, and insert components by stable library identity. (#239)+- Publish the current document as an immutable local component library from the Assets panel, assigning durable collision-safe asset keys on first publication. (#239)+- Review component-library asset changes before acceptance and undo or redo accepted instance updates as one editor history action. (#239)+- Preserve enabled-library bindings and materialized definition identities through `.fig` save/reopen, and reject Figma API or AI edits to read-only library definitions. (#239)+- Enforce read-only library capabilities across visual/layout Figma API setters, structural edits, editor history actions, variant authoring, and clipboard replacement while keeping instances editable. (#239)+- Publish component-library revisions to storage-provider object namespaces with immutable revision objects, validated manifests, and conflict-checked latest pointers. (#239)+- Switch the library manager between local and configured storage catalogs, caching remote revisions in IndexedDB for offline browsing and insertion. (#239)+- Bind the active library catalog into live automation requests so MCP component discovery and stable-identity insertion use the targeted document’s enabled libraries. (#239)+- Show affected-instance and variant-fallback counts before accepting a component-library update. (#239)+- Persist the selected local/storage catalog and preferred-library priorities, restoring them for Assets browsing and AI component ranking. (#239)+- Validate downloaded library revisions against size, node, image, content-hash, and revision-hash limits before caching or materialization. (#239)+- Manage bounded filesystem component-library catalogs from the CLI with JSON-capable `libraries list` and immutable `libraries publish` commands. (#239)+- Cover the complete local library lifecycle from multidimensional publication and cross-document insertion through `.fig` save/reopen and offline linked-instance editing. (#239)+- Track library update state per linked instance so individual instances or every instance of one asset can accept a revision while older definitions remain usable. (#239)+- Group outdated linked instances by library asset, filter updates by current page or all pages, and apply visible updates in one undoable transaction. (#239)+- Keep library update discovery read-only until acceptance and cover the populated manager’s page scope, atomic update, and graph immutability in Playwright. (#239)+- Create centered frames from Figma-style device and asset presets, or resize selected frames to a preset while preserving their names. (#418)- Manage pages by renaming, deleting, and dragging to reorder them in the Pages panel.- Create text by dragging a fixed-size text box or clicking for auto-width text.- Create and edit layout grids for frames and components, including columns, rows, counts, gutters, margins, visibility, and grid size.@@ -65,12 +48,12 @@- Access more common design actions from the browser and desktop menus, including visibility, locking, masks, flipping, components, z-order, distribution, selection, rulers, multiplayer cursors, and Settings.- Find overlapping layers and overflowing children from the CLI, AI tools, and MCP.- Target a specific open document and page from live CLI and MCP automation, including sessions with multiple documents.-- Connect local MCP clients through automatically discovered private Unix sockets on macOS and Linux, with localhost TCP fallback. (#338).+- Connect local MCP clients through automatically discovered private Unix sockets on macOS and Linux, with localhost TCP fallback. (#338)- Test OpenAI-compatible provider connections from AI settings with clearer setup errors.- Configure separate Design, Review, Fast, and Vision models, providers, endpoints, and credentials from AI settings.- Manage AI, agent, media, and storage credentials from unified Settings, using the system credential store on desktop and encrypted browser storage by default, with a session-only browser option.- Connect an S3-compatible storage workspace with local-first saves, background synchronization, embedded `.fig` previews loaded without downloading full documents, and automatic refresh while the workspace is active.-- Add Japanese localization and improve menu translations across the existing supported languages. (#367).+- Add Japanese localization and improve menu translations across the existing supported languages. (#367)- Author richer Design JSX with components, instances, variables, gradients, structured fills, shadows, blur effects, masks, and inline SVG vectors.- Build custom property panels and document workspaces with new Vue SDK number fields, bindable values, property sections, responsive grids, segmented controls, property lists, color models, fill controls, gradient primitives, and the headless `useDocumentWorkspace()` composable.- Use `useColorModel()` in the Vue SDK for extensible color formats and shared RGB, HSL, HSB, and OkHCL channel behavior.@@ -83,9 +66,9 @@- Choose Freeform, vertical, horizontal, or grid flow directly from the contextual Layout section, with sizing controls grouped alongside it.- Choose Auto width, Auto height, or Fixed size directly from the Layout section for text layers.- Scale the Layers panel to documents with thousands of nodes through virtualized rows, faster incremental updates, stable expansion, range selection, and scroll-to-selection.-- Open and save large `.fig` documents substantially faster while preserving original metadata and user edits, and switch between large pages with fewer Layers panel stalls. (#420).+- Open and save large `.fig` documents substantially faster while preserving original metadata and user edits, and switch between large pages with fewer Layers panel stalls. (#420)- Resolve fonts before text appears, with language-aware CJK and Arabic fallbacks, character-specific remote subsets, and more reliable rendering as fonts load.-- Use MiniMax M3 as the default model for MiniMax AI connections. (#431).+- Use MiniMax M3 as the default model for MiniMax AI connections. (#431)- Center empty and setup states consistently across panels, dialogs, and workspaces.### Fixed@@ -96,18 +79,18 @@- Keep swapped image avatars and thin stepper dividers at their effective imported size and position.- Scale proportion-constrained `.fig` instance geometry through fixed wrapper layers so imported logos and icons retain their intended size.- Match Figma auto-layout spacing, padding, min/max constraints, scalar variable bindings, CanvasKit-shaped generated text, imported text bounds, and nested instance geometry more closely.-- Match Figma Plugin API vector path and network editing, including bounds, transforms, winding rules, region fills, validation, and handle mirroring. (#444).-- Let AI and MCP tools create arbitrary vectors from SVG path data, validating input without leaving blank layers behind. (#440).-- Improve AI design accuracy by exposing every supported shape, including visible stroke colors and weights in visual descriptions, and accepting supported inline SVG attributes without false warnings. (#445, #447, #448).-- Restore Anthropic AI connections in the web app instead of failing with a browser endpoint error. (#438).+- Match Figma Plugin API vector path and network editing, including bounds, transforms, winding rules, region fills, validation, and handle mirroring. (#444)+- Let AI and MCP tools create arbitrary vectors from SVG path data, validating input without leaving blank layers behind. (#440)+- Improve AI design accuracy by exposing every supported shape, including visible stroke colors and weights in visual descriptions, and accepting supported inline SVG attributes without false warnings. (#445, #447, #448)+- Restore Anthropic AI connections in the web app instead of failing with a browser endpoint error. (#438)- Reconnect live CLI and automation sessions automatically after an unexpected bridge disconnection.-- Keep MCP file access inside its configured root when paths contain symlinks, and strengthen local authentication token checks. (#338).-- Start globally installed ACP agents correctly on Windows instead of reporting them as unavailable. (#361).+- Keep MCP file access inside its configured root when paths contain symlinks, and strengthen local authentication token checks. (#338)+- Start globally installed ACP agents correctly on Windows instead of reporting them as unavailable. (#361)- Resume pending cloud saves after restarting the app or temporarily losing credentials, without reviving deleted documents or overwriting newer local changes.- Handle S3 object listings, pagination, and escaped names more reliably, and explain required CORS setup without modifying bucket rules.- Show HTML, CSS, Tailwind, and JSX import errors instead of failing silently.- Preserve inline SVG attributes, nested transforms, and explicit icon dimensions when rendering Design JSX artwork.-- Save auto-layout frames that stretch their children to `.fig` without failing. (#427).+- Save auto-layout frames that stretch their children to `.fig` without failing. (#427)- Preserve nested instance text, visibility, paint, geometry, clipping, variable modes, and component swaps in `.fig` files.- Improve `.fig` import and rendering fidelity for groups, booleans, instances, rotated vectors, complex text fills, auto-sized text, layout grids, page guides, patterns, noise effects, masks, and canvas backgrounds.- Preserve pages, components, prototype and library metadata, export settings, unsupported effects, and other unrelated Figma data when editing and resaving `.fig` files.@@ -116,17 +99,17 @@- Report corrupted compressed `.fig` data as an error instead of opening it as valid content.- Match Figma auto-layout reflow after deleting children, hiding optional instance slots, or syncing component changes.- Make group and boolean-operation children scale with their parent during resize.-- Edit vectors in opened documents at the correct position, with live fill updates and working undo and redo. (#390).+- Edit vectors in opened documents at the correct position, with live fill updates and working undo and redo. (#390)- Keep duplicated layers independent instead of sharing mutable fills, strokes, bindings, overrides, or vector data, and remove stale bindings when paints are deleted.-- Keep desktop text visible across scene and overlay canvases, refresh it after local fonts load, and preserve rendering when an italic face is unavailable. (#395).-- Vertically center text correctly when an explicit line height adds space above and below its glyphs. (#422).+- Keep desktop text visible across scene and overlay canvases, refresh it after local fonts load, and preserve rendering when an italic face is unavailable. (#395)+- Vertically center text correctly when an explicit line height adds space above and below its glyphs. (#422)- Preserve Hangul IME composition while editing text.- Restore desktop copy, cut, and paste when browser clipboard events are unavailable.- Finish pasting Figma layers promptly even when remote images are slow or unavailable, and hydrate their image fills when downloads complete.-- Reuse the existing tab when reopening a file through its desktop path or browser file handle, avoiding duplicate watchers and conflicting saves. (#297).+- Reuse the existing tab when reopening a file through its desktop path or browser file handle, avoiding duplicate watchers and conflicting saves. (#297)- Share public app links from the desktop collaboration panel and send the current document to newly joined collaborators.- Show only the most specific tooltip when property controls contain nested actions.-- Match regional browser languages to supported locales without selecting a lower-priority language. (#417).+- Match regional browser languages to supported locales without selecting a lower-priority language. (#417)- Improve Simplified Chinese translations and correct localized menu terminology.- Resolve published package types correctly for TypeScript consumers and keep file-backed CLI commands working under Node.@@ -140,19 +123,19 @@- Update the Homebrew install command to use the published `openpencil` cask.-### Fixed+### Fixes- Fix the published MCP package so global installs include the `openpencil-mcp` and `openpencil-mcp-http` launchers required by desktop app integrations.## 0.13.1 — 2026-05-29-### Fixed+### Fixes- Fix the npm package contents for the CLI so Bun installs include the built `openpencil` binary and runtime bundle.## 0.13.0 — 2026-05-29-### Fixed+### Fixes- Fix the published CLI package so Bun global installs run the built `openpencil` binary instead of raw TypeScript sources.@@ -191,7 +174,7 @@- Update Claude Code MCP setup documentation and the docs landing screenshot.- Ignore non-source Markdown files in the app dev watcher so documentation edits do not reload the running editor.-### Fixed+### Fixes- Route Claude Code stdio MCP requests through the live OpenPencil app connection, including immediate disconnected errors when no document is connected.- Keep MCP disconnected guidance focused on starting OpenPencil and opening a document.@@ -202,7 +185,7 @@## 0.12.1 — 2026-05-19-### Fixed+### Fixes- Fix `.fig` round-trips for OpenPencil component sets and variable bindings, and recompute imported layouts after opening documents.- Report desktop/MCP package version mismatches explicitly and include package-manager-aware install guidance from the MCP server.@@ -240,7 +223,7 @@- Editor command metadata now drives shortcut display across browser menus, native menus, tooltips, and context menus.- Text-to-vector conversion now uses shared loaded-font outline geometry across Boolean, flatten, and outline commands.-### Fixed+### Fixes- Fix `.fig` export of component variant properties and text stretch alignment so designs round-trip correctly through Figma.- Fix CJK and Arabic text rendering — fallback fonts now load before the first paint instead of showing blank text.@@ -288,446 +271,448 @@## 0.11.8 — 2026-04-23-### Fixed+### Fixes-- Fix MCP server not spawning on Windows — use `cmd /c` to resolve `.cmd` wrappers from npm global installs.-- Fix MCP server and automation WebSocket not connecting on Windows/Linux — inline `__TAURI_INTERNALS__` check at call time instead of using stale module-level `IS_TAURI` constant.-- Fix shell PATH not inherited by GUI app on macOS/Linux — add `fix-path-env-rs` to read shell config.+- Fix MCP server not spawning on Windows — use `cmd /c` to resolve `.cmd` wrappers from npm global installs+- Fix MCP server and automation WebSocket not connecting on Windows/Linux — inline `__TAURI_INTERNALS__` check at call time instead of using stale module-level `IS_TAURI` constant+- Fix shell PATH not inherited by GUI app on macOS/Linux — add `fix-path-env-rs` to read shell config## 0.11.7 — 2026-04-22-### Added+### Features- Add stdio transport for MCP server — `openpencil-mcp` now works as a proper stdio MCP server for Claude Code, Cursor, etc. HTTP server available as `openpencil-mcp-http`.-- Default canvas background to dark when system prefers dark color scheme.-- Add `list_available_fonts` MCP tool for font discovery.-- Copy node ID / XPath from context menu; CLI selection command.-- Arrow key nudge for selected nodes (1px, Shift+arrow for 10px).-- JSX renderer: `position="absolute"`, `top`, `left` props for absolute children inside auto-layout containers.-- MCP server sends `notifications/tools/list_changed` when the desktop app connects or disconnects.-- Headless text measurement via opentype.js per-glyph advance widths — no CanvasKit needed.-- Add `open_file` and `new_document` MCP tools with `OPENPENCIL_MCP_ROOT` path scoping.-- Optional `path` param on `export_image`, `export_svg`, `get_jsx` — write output to disk instead of returning base64/string.-- Multi-root JSX support — multiple top-level elements auto-wrapped in a fragment.-- `Component` and `Instance` tag aliases in JSX renderer.-- JSX prop reference doc — copy to clipboard via book icon in Code panel.-- Prompts (`CODEGEN_PROMPT`, `JSX_REFERENCE`) moved from embedded strings to markdown files.--### Fixed--- Fix Backspace not deleting selected nodes after clicking on canvas — canvas now receives focus on click so keyboard shortcuts aren't blocked by stale input focus.-- Support Cmd/Ctrl+click for additive multi-select in layers panel (previously only Shift+click worked).-- Fix macOS Tauri build — move `NSAllowsLocalNetworking` ATS config from invalid `tauri.conf.json` property to a proper `Info.plist` file.-- Fix tab order and keyboard handling in inspector panel.-- Fix design token variables not resolved before passing to yoga-layout.-- Suppress keyboard shortcuts while editing property panel inputs.-- Fix tooltip competing with popover trigger on Windows.-- Fix hit area for nodes with rotated parents.-- Error toasts auto-dismiss, deduplicate, and cap stack at 5.-- Bump yoga-layout to 3.3.0-grid.3 with `Node.free()` support.-- Bump PWA precache limit for canvaskit-webgpu.-- Fix color picker dragging flooding the undo stack — fill/stroke/effect color and opacity drags now collapse into a single undo entry per interaction via debounced batching in `PropertyListRoot`.-- Fix .fig import crash on alias variables without a GUID.-- Fix `save_file` crash on vectors with missing tangent control points — default to straight segments.-- Validate `create_vector` path JSON upfront with clear error messages for malformed input.-- Fix MCP/AI tools rejecting string-encoded numeric arguments from MCP clients (`"42"` → `42`).-- Fix "Create Instance" context menu item always grayed out — inverted disabled flag.-- Show "Create Instance" instead of "Create Component" in context menu when a component is selected.-- Fix headless layout: use stored .fig dimensions instead of rough text size estimates (26K → 11K mismatches on material3.fig).-- Fix `--help` output with huge vertical gaps between commands — remove inline examples from query description.-- Fix `openpencil-mcp` npm package missing `dist/stdio.js` — explicitly list entry points in tsconfig.-- Show toast when MCP server fails to start instead of silently swallowing the error.-- Fix provider settings popover not appearing — tooltip wrapper broke floating-ui positioning.-- Fix `set_font_range` producing invalid style runs that crash `.fig` export — use `applyStyleToRange`, apply color and fontWeight from style name.-- Fix MCP "app not connected" error — message now instructs the agent to stop and inform the user.-- Fix external links in AI panel blocked by Tauri ACL — use opener plugin instead of shell.+- Default canvas background to dark when system prefers dark color scheme+- Add `list_available_fonts` MCP tool for font discovery+- Copy node ID / XPath from context menu; CLI selection command+- Arrow key nudge for selected nodes (1px, Shift+arrow for 10px)+- JSX renderer: `position="absolute"`, `top`, `left` props for absolute children inside auto-layout containers+- MCP server sends `notifications/tools/list_changed` when the desktop app connects or disconnects+- Headless text measurement via opentype.js per-glyph advance widths — no CanvasKit needed+- Add `open_file` and `new_document` MCP tools with `OPENPENCIL_MCP_ROOT` path scoping+- Optional `path` param on `export_image`, `export_svg`, `get_jsx` — write output to disk instead of returning base64/string+- Multi-root JSX support — multiple top-level elements auto-wrapped in a fragment+- `Component` and `Instance` tag aliases in JSX renderer+- JSX prop reference doc — copy to clipboard via book icon in Code panel+- Prompts (`CODEGEN_PROMPT`, `JSX_REFERENCE`) moved from embedded strings to markdown files++### Fixes++- Fix Backspace not deleting selected nodes after clicking on canvas — canvas now receives focus on click so keyboard shortcuts aren't blocked by stale input focus+- Support Cmd/Ctrl+click for additive multi-select in layers panel (previously only Shift+click worked)+- Fix macOS Tauri build — move `NSAllowsLocalNetworking` ATS config from invalid `tauri.conf.json` property to a proper `Info.plist` file+- Fix tab order and keyboard handling in inspector panel+- Fix design token variables not resolved before passing to yoga-layout+- Suppress keyboard shortcuts while editing property panel inputs+- Fix tooltip competing with popover trigger on Windows+- Fix hit area for nodes with rotated parents+- Error toasts auto-dismiss, deduplicate, and cap stack at 5+- Bump yoga-layout to 3.3.0-grid.3 with `Node.free()` support+- Bump PWA precache limit for canvaskit-webgpu+- Fix color picker dragging flooding the undo stack — fill/stroke/effect color and opacity drags now collapse into a single undo entry per interaction via debounced batching in `PropertyListRoot`+- Fix .fig import crash on alias variables without a GUID+- Fix `save_file` crash on vectors with missing tangent control points — default to straight segments+- Validate `create_vector` path JSON upfront with clear error messages for malformed input+- Fix MCP/AI tools rejecting string-encoded numeric arguments from MCP clients (`"42"` → `42`)+- Fix "Create Instance" context menu item always grayed out — inverted disabled flag+- Show "Create Instance" instead of "Create Component" in context menu when a component is selected+- Fix headless layout: use stored .fig dimensions instead of rough text size estimates (26K → 11K mismatches on material3.fig)+- Fix `--help` output with huge vertical gaps between commands — remove inline examples from query description+- Fix `openpencil-mcp` npm package missing `dist/stdio.js` — explicitly list entry points in tsconfig+- Show toast when MCP server fails to start instead of silently swallowing the error+- Fix provider settings popover not appearing — tooltip wrapper broke floating-ui positioning+- Fix `set_font_range` producing invalid style runs that crash `.fig` export — use `applyStyleToRange`, apply color and fontWeight from style name+- Fix MCP "app not connected" error — message now instructs the agent to stop and inform the user+- Fix external links in AI panel blocked by Tauri ACL — use opener plugin instead of shell## 0.11.6 — 2026-04-08-### Fixed+### Fixes-- Switch `@open-pencil/core` build from `tsgo` + `fix-esm-import-path` to `tsdown` — fixes bare directory imports that broke Node.js and Bun consumers.+- Switch `@open-pencil/core` build from `tsgo` + `fix-esm-import-path` to `tsdown` — fixes bare directory imports that broke Node.js and Bun consumers## 0.11.5 — 2026-04-08-### Fixed+### Fixes-- Fix published npm packages resolving to TypeScript source instead of compiled JavaScript — `publishConfig.exports` overrides are now applied during CI publish.-- Fix Windows CI build failures caused by backslash file paths in custom lint rules.+- Fix published npm packages resolving to TypeScript source instead of compiled JavaScript — `publishConfig.exports` overrides are now applied during CI publish+- Fix Windows CI build failures caused by backslash file paths in custom lint rules## 0.11.4 — 2026-04-08-### Fixed+### Fixes-- Fix `@open-pencil/core` published package containing stale import paths from before the domain module restructuring — CLI and MCP installs from npm now resolve correctly.-- Add `save_file` MCP tool for saving the current document to disk.-- Clipboard text export now writes richer v4 `derivedTextData` payloads with glyph outlines for better paste fidelity.+- Fix `@open-pencil/core` published package containing stale import paths from before the domain module restructuring — CLI and MCP installs from npm now resolve correctly+- Add `save_file` MCP tool for saving the current document to disk+- Clipboard text export now writes richer v4 `derivedTextData` payloads with glyph outlines for better paste fidelity## 0.11.3 — 2026-04-08-### Fixed+### Fixes-- Show actionable install errors in the chat panel when a required local AI CLI is missing.-- Fix inline layer rename so clearing the name restores the default name, and Backspace/Delete inside rename inputs no longer delete the layer.-- Fix rotated frame hit testing, hover highlights, and selection overlays so interactive areas and overlay labels stay aligned during rotation.-- Fix text edit undo so it restores both the original text and `styleRuns`.-- Pressing Enter with a selected text node now starts text editing and selects all text.-- Fix `ScrubInput` Enter handling so committing a value no longer triggers a second blur-based commit that overwrites it.-- Show the auto-layout panel for `COMPONENT`, `COMPONENT_SET`, and `INSTANCE` nodes.-- Fix missing layout direction icons in the auto-layout controls.-- Fix nested text selection inside gradient cards.-- Unify the size control into a single inline sizing input/dropdown with shorter localized labels to prevent overflow.+- Show actionable install errors in the chat panel when a required local AI CLI is missing+- Fix inline layer rename so clearing the name restores the default name, and Backspace/Delete inside rename inputs no longer delete the layer+- Fix rotated frame hit testing, hover highlights, and selection overlays so interactive areas and overlay labels stay aligned during rotation+- Fix text edit undo so it restores both the original text and `styleRuns`+- Pressing Enter with a selected text node now starts text editing and selects all text+- Fix `ScrubInput` Enter handling so committing a value no longer triggers a second blur-based commit that overwrites it+- Show the auto-layout panel for `COMPONENT`, `COMPONENT_SET`, and `INSTANCE` nodes+- Fix missing layout direction icons in the auto-layout controls+- Fix nested text selection inside gradient cards+- Unify the size control into a single inline sizing input/dropdown with shorter localized labels to prevent overflow## 0.11.2 — 2026-03-30-### Fixed+### Fixes-- Stabilize npm publishing with isolated temp publish directories instead of mutating tracked package manifests in CI.-- Strip build-time scripts and dev dependencies from generated publish manifests so tarballs pack from verified artifacts only.-- Fix `@open-pencil/mcp` release packaging so the published npm tarball includes its built `dist/` CLI and server entrypoints deterministically.-- Fix `@open-pencil/core` release build configuration so CI publish jobs include Node and Bun ambient types when compiling package artifacts.+- Stabilize npm publishing with isolated temp publish directories instead of mutating tracked package manifests in CI+- Strip build-time scripts and dev dependencies from generated publish manifests so tarballs pack from verified artifacts only+- Fix `@open-pencil/mcp` release packaging so the published npm tarball includes its built `dist/` CLI and server entrypoints deterministically+- Fix `@open-pencil/core` release build configuration so CI publish jobs include Node and Bun ambient types when compiling package artifacts## 0.11.1 — 2026-03-30-### Fixed+### Fixes-- Fix npm publishing pipeline to publish packed tarballs instead of raw package folders.-- Attempt to fix `@open-pencil/mcp` npm package contents so the published CLI includes its built `dist/` entrypoints.-- Fix `@open-pencil/vue` npm package metadata and build output so the published package resolves from `dist/` while local workspace development keeps using source aliases.+- Fix npm publishing pipeline to publish packed tarballs instead of raw package folders+- Attempt to fix `@open-pencil/mcp` npm package contents so the published CLI includes its built `dist/` entrypoints+- Fix `@open-pencil/vue` npm package metadata and build output so the published package resolves from `dist/` while local workspace development keeps using source aliases## 0.11.0 — 2026-03-30-### Added--- Lock and visibility toggle buttons in layers panel (hover to reveal, always shown when active).-- Figma-style selection scope — double-click to enter groups/frames/components, Escape to exit.-- Nested container navigation — each double-click goes one level deeper.-- Dashed border around entered container for visual feedback.-- Layer panel click syncs canvas scope automatically.-- Vue SDK internationalization primitives — `useI18n()`, locale detection, persisted locale selection, lazy-loaded locale JSON files, and exported locale metadata for custom editor shells.-- Vue SDK docs and public API audit — documented advanced exports (`useOkHCL()`, variables helpers, viewport and locale APIs), aligned docs with the actual `provideEditor()` injection model, and expanded release-ready SDK guidance.-- npm release pipeline now publishes `@open-pencil/core`, `@open-pencil/cli`, `@open-pencil/mcp`, and `@open-pencil/vue` together on version tags.-- App language picker in the menu bar — switch UI locale without reloading.-- Added a vector curve editor and improved drawing experience with the pen tool.-- Resume pen drawing from existing open path endpoints — click an endpoint to continue the curve.-- Close open paths by dragging one endpoint to the other.-- Align selected anchor points relative to each other in vector edit mode — the standard alignment buttons in the position panel now operate on selected vertices when 2 or more are selected.-- Unified core IO format registry — `.fig` is now modeled as the native document format alongside shared export adapters for PNG, JPG, WEBP, SVG, and JSX.-- Export selection or current page as `.fig` from the app export UI and app menu.-- New CLI commands: `open-pencil convert` for document conversion, `open-pencil formats` to inspect readable/writable/exportable formats, and `open-pencil lint` for design consistency, structure, and accessibility checks.-- CLI export now supports `.fig` output and routes PNG/JPG/WEBP/SVG/JSX/`.fig` through the shared IO layer.-- `Open…` now supports `.pen` Pencil documents through the shared document reader pipeline while keeping `.fig` as the native save format.-- Display‑P3 document color space pipeline — documents now default to Display‑P3, `.fig` import/export preserves document color profiles, the live canvas requests P3 surfaces with sRGB fallback, and raster/SVG export paths accept explicit color-space targets.-- Color picker overhaul — unified `RGB` / `HSL` / `HSB` / `OkHCL` field formats, slider-space-aware track/thumb previews, and better neutral-color editing behavior for fills, strokes, gradient stops, and component fills.-- OkHCL metadata now round-trips through `.fig` plugin data and integrates directly into the main fill/stroke color workflow with preview gamut diagnostics.-- Vue SDK now exposes reusable color-picker model helpers and solid fill/stroke commit helpers for custom editor shells.-- Update built-in Z.ai and MiniMax model lists — Z.ai now uses the Anthropic-compatible endpoint for GLM coding models, adds GLM-5.1, and MiniMax adds M2.7 / M2.7-highspeed.-- Arabic and RTL support across text rendering, editing, layout, export, and AI tooling — text nodes support `Auto`/`LTR`/`RTL`, auto-layout frames support `Auto`/`LTR`/`RTL` flow, and JSX/AI prompts/tools can now generate and edit both explicitly.--### Fixed+### Features++- Lock and visibility toggle buttons in layers panel (hover to reveal, always shown when active)+- Figma-style selection scope — double-click to enter groups/frames/components, Escape to exit+- Nested container navigation — each double-click goes one level deeper+- Dashed border around entered container for visual feedback+- Layer panel click syncs canvas scope automatically+- Vue SDK internationalization primitives — `useI18n()`, locale detection, persisted locale selection, lazy-loaded locale JSON files, and exported locale metadata for custom editor shells+- Vue SDK docs and public API audit — documented advanced exports (`useOkHCL()`, variables helpers, viewport and locale APIs), aligned docs with the actual `provideEditor()` injection model, and expanded release-ready SDK guidance+- npm release pipeline now publishes `@open-pencil/core`, `@open-pencil/cli`, `@open-pencil/mcp`, and `@open-pencil/vue` together on version tags+- App language picker in the menu bar — switch UI locale without reloading+- Added a vector curve editor and improved drawing experience with the pen tool+- Resume pen drawing from existing open path endpoints — click an endpoint to continue the curve+- Close open paths by dragging one endpoint to the other+- Align selected anchor points relative to each other in vector edit mode — the standard alignment buttons in the position panel now operate on selected vertices when 2 or more are selected+- Unified core IO format registry — `.fig` is now modeled as the native document format alongside shared export adapters for PNG, JPG, WEBP, SVG, and JSX+- Export selection or current page as `.fig` from the app export UI and app menu+- New CLI commands: `open-pencil convert` for document conversion, `open-pencil formats` to inspect readable/writable/exportable formats, and `open-pencil lint` for design consistency, structure, and accessibility checks+- CLI export now supports `.fig` output and routes PNG/JPG/WEBP/SVG/JSX/`.fig` through the shared IO layer+- `Open…` now supports `.pen` Pencil documents through the shared document reader pipeline while keeping `.fig` as the native save format+- Display‑P3 document color space pipeline — documents now default to Display‑P3, `.fig` import/export preserves document color profiles, the live canvas requests P3 surfaces with sRGB fallback, and raster/SVG export paths accept explicit color-space targets+- Color picker overhaul — unified `RGB` / `HSL` / `HSB` / `OkHCL` field formats, slider-space-aware track/thumb previews, and better neutral-color editing behavior for fills, strokes, gradient stops, and component fills+- OkHCL metadata now round-trips through `.fig` plugin data and integrates directly into the main fill/stroke color workflow with preview gamut diagnostics+- Vue SDK now exposes reusable color-picker model helpers and solid fill/stroke commit helpers for custom editor shells+- Update built-in Z.ai and MiniMax model lists — Z.ai now uses the Anthropic-compatible endpoint for GLM coding models, adds GLM-5.1, and MiniMax adds M2.7 / M2.7-highspeed+- Arabic and RTL support across text rendering, editing, layout, export, and AI tooling — text nodes support `Auto`/`LTR`/`RTL`, auto-layout frames support `Auto`/`LTR`/`RTL` flow, and JSX/AI prompts/tools can now generate and edit both explicitly++### Fixes- Fix shortcuts, now work on non-English keyboard layouts.-- Fix imported `.fig` file open and page-switch regressions — loaded documents now keep graph/store state in sync, remap imported canvas/page children correctly, and recompute imported auto-layout descendants when switching pages.-- Fix first canvas render happening before fonts load — wait for fonts before the initial draw to avoid Safari and text measurement glitches.-- Preserve `fig-kiwi` version on `.fig` roundtrip — imports keep the original header version instead of rewriting everything to a hardcoded value; new files default to version 101.-- Normalize auto-layout text export for Figma — text children inside auto-layout frames now serialize with `NONE` auto-resize to match Figma behavior and avoid overflow on reimport.-- Fix keyboard editing regressions after the refactor — canvas shortcuts no longer fire while editing text, and Delete/Backspace no longer delete nodes during text entry.-- Fix MCP page switching persistence — `switch_page` now survives across tool calls in the same session.-- Improve CJK font fallback coverage — load multiple Google Fonts for broader Han/Japanese/Korean text support.-- Normalize more visible UI strings for localized app chrome — menus, panels, variables dialog, code panel, chat setup, and editor controls now respect the selected locale instead of falling back to English in common flows.-- Fix imported text rendering in browser and headless export — preserve stored bounds until fonts are ready, restore missing font-loaded guards, use natural width for `WIDTH_AND_HEIGHT` text, and clip text to node bounds.-- Fix browser/headless rendering mismatch for imported toolbar/instance content by correcting runtime imported layout recomputation instead of diverging browser rendering behavior.-- Fix `set_layout` tool not defaulting to HUG sizing when enabling auto-layout — frames now shrink/grow to fit children instead of keeping fixed dimensions.-- Normalize font family names on `.fig` export — strip optical size suffixes (e.g. "DM Sans 9pt" → "DM Sans") so Figma recognizes the font.-- TEXT nodes now default to a solid black fill — previously exported with no fill, making text invisible when opened in Figma.-- Fix save crash when COLOR variable is missing alpha channel.-- Fix console error spam on deployed web app from automation WebSocket reconnect loop.-- Fix headless CLI font fallback — bundled Inter font now ships with `@open-pencil/core` and loads without a web server.-- Locked nodes now block move, resize, rotate, and delete on canvas.-- Locked containers block double-click enter.-- Marquee selection skips locked and hidden nodes.-- COMPONENT/INSTANCE containers are now enterable via double-click.-- Replaced the alignment and reflection icons with the correct ones.+- Fix imported `.fig` file open and page-switch regressions — loaded documents now keep graph/store state in sync, remap imported canvas/page children correctly, and recompute imported auto-layout descendants when switching pages+- Fix first canvas render happening before fonts load — wait for fonts before the initial draw to avoid Safari and text measurement glitches+- Preserve `fig-kiwi` version on `.fig` roundtrip — imports keep the original header version instead of rewriting everything to a hardcoded value; new files default to version 101+- Normalize auto-layout text export for Figma — text children inside auto-layout frames now serialize with `NONE` auto-resize to match Figma behavior and avoid overflow on reimport+- Fix keyboard editing regressions after the refactor — canvas shortcuts no longer fire while editing text, and Delete/Backspace no longer delete nodes during text entry+- Fix MCP page switching persistence — `switch_page` now survives across tool calls in the same session+- Improve CJK font fallback coverage — load multiple Google Fonts for broader Han/Japanese/Korean text support+- Normalize more visible UI strings for localized app chrome — menus, panels, variables dialog, code panel, chat setup, and editor controls now respect the selected locale instead of falling back to English in common flows+- Fix imported text rendering in browser and headless export — preserve stored bounds until fonts are ready, restore missing font-loaded guards, use natural width for `WIDTH_AND_HEIGHT` text, and clip text to node bounds+- Fix browser/headless rendering mismatch for imported toolbar/instance content by correcting runtime imported layout recomputation instead of diverging browser rendering behavior+- Fix `set_layout` tool not defaulting to HUG sizing when enabling auto-layout — frames now shrink/grow to fit children instead of keeping fixed dimensions+- Normalize font family names on `.fig` export — strip optical size suffixes (e.g. "DM Sans 9pt" → "DM Sans") so Figma recognizes the font+- TEXT nodes now default to a solid black fill — previously exported with no fill, making text invisible when opened in Figma+- Fix save crash when COLOR variable is missing alpha channel+- Fix console error spam on deployed web app from automation WebSocket reconnect loop+- Fix headless CLI font fallback — bundled Inter font now ships with `@open-pencil/core` and loads without a web server+- Locked nodes now block move, resize, rotate, and delete on canvas+- Locked containers block double-click enter+- Marquee selection skips locked and hidden nodes+- COMPONENT/INSTANCE containers are now enterable via double-click+- Replaced the alignment and reflection icons with the correct ones## 0.10.0 — 2026-03-15-### Added--- ACP agent support — use Claude Code, Codex, or Gemini CLI as AI assistants in the desktop chat panel.-- Permission confirmation dialog — ACP agents request user approval for file/shell operations, MCP design tools auto-approved.-- Unified MCP server — single HTTP + WebSocket proxy replaces Vite SSR bridge.-- Stock photo integration — `stock_photo` tool fetches images from Pexels or Unsplash and applies to design nodes. Provider adapter supports custom providers.-- Skeleton-first AI workflow — 4-phase design process (plan → skeleton → content fill via `replace_id` → polish) for more reliable AI-generated layouts.-- Batched AI tools — `calc` accepts arrays of expressions, `stock_photo` fetches all images in parallel, `batch_update` applies multiple property changes in one call, `describe` accepts `ids` array for multi-node inspection.-- AI visual feedback — blue pulsing border on nodes being modified, green flash on completion.-- Auto-depth `describe` — adapts inspection depth to subtree size (small block → deeper, large page → shallower).-- `set_fill` gradient support — linear gradients with `color_end` and `gradient` direction params.-- `render` tool `replace_id` — atomically swap skeleton placeholders with real content.-- MCP `export_image_file` tool for headless PNG rendering.-- Grid layout in AI chat — JSX renderer supports `grid`, `columns`, `rows`, `gap` props.-- Configurable max output tokens in AI provider settings (default 16384).-- Z.ai AI provider with GLM-5, GLM-4.7, GLM-4.6, GLM-4.5 model families.-- MiniMax AI provider with M2.5, M2.1, M2 models.--### Fixed--- Resolve variable-bound fill colors through alias chains.-- Fix SCALE constraint resizing for auto-layout instances.-- Propagate SCALE constraints through instance clone chains.-- Skip self-referencing symbolOverrides on nodes with explicit kiwi properties.-- Fix DSD resolution for swapped instance children.-- Fix instance swap override propagation through clone chains.-- Fix component property override resolution through clone chains.-- Fix text/property overrides clobbered by second transitive sync.---- Fix text rendering with wrong fonts on file open — all font weights (including default family) are now loaded before the first render.-- Fix `weightToStyle` mapping: weight 400 now correctly maps to "Regular" instead of "Medium".-- Fix detached ArrayBuffer crash when switching pages after saving — export worker now copies image buffers before transferring.-- Show warning toast when fonts fail to load, error toast when file open fails.-- Fix FillPicker crash when selecting image fills (missing `ref` import from #92).-- Fix Google Fonts TLS/network errors not cached — failed families no longer retry on every render.-- Fix CJK text garbled when font is unavailable — fallback now renders through paragraph shaper instead of raw `drawText`, preserving CJK characters via the fallback font chain.-- Fix auto-layout overflow in AI-generated designs — text wrapping, min/max constraints, absolute positioning, and FILL sizing now work correctly.-- Fix `layoutAlignSelf` limited to STRETCH — full range supported (CENTER, MAX, MIN, BASELINE).-- Fix hidden auto-layout children losing their dimensions on layout recompute.-- Fix ProviderSettings popover not visible in AI chat.-- Fix paste/copy/cut intercepted by canvas in AI chat input.-- Strip TypeScript casts from AI-generated JSX (`as any`, `as const`).-- Fix parsing complex .fig files crashing on missing GUIDs in component overrides.-- Fix headless text layout using 100×100 default size instead of estimated dimensions — multi-line wrapping now estimated correctly.-- Fix clipboard roundtrip losing properties — clipsContent, constraints, arcData, strokeCap/Join, layoutAlignSelf, textAutoResize, autoRename now preserved in Figma Kiwi serialization.-- Fix MCP headless export crashing on `window.queryLocalFonts` in non-browser runtimes (Bun/Node).-- Fix MCP `export_image` rendering blank text — fonts now loaded before rasterization.-- Fix text always using paragraph rendering with Inter fallback chain (no more missing-font garbling).-- Clip children to rounded corners when `clipsContent` is true.-- Use child shape for drop shadows on transparent containers.-- Treat `FOREGROUND_BLUR` as layer blur wrapping children.-- Fix radial, angular, and diamond gradient rendering.-- Fix .fig export roundtrip: variable GUIDs colliding with document.-- Fix file open dialog not working on first click in Safari.-- Skip variable fonts from local font access, use Google Fonts instead.-- Disable autosave by default.-### Performance-- Offload .fig parsing (unzip + Kiwi decode) to a Web Worker — main thread stays responsive during file open.-- Offload .fig compression to a Web Worker during save (was blocking 450ms+).-- Add instance index (`componentId → Set<nodeId>`) — `getInstances()` is O(1) instead of scanning all nodes.-- Defer graph event subscription until after layout computation during file open — eliminates redundant `syncInstances` calls.-- Cache label collection (sections/components) per scene mutation instead of walking the full tree every frame.-- Blocking font loading — fonts load before first render to ensure correct glyphs.--## 0.9.0 — 2026-03-09--### Added+- Offload .fig parsing (unzip + Kiwi decode) to a Web Worker — main thread stays responsive during file open+- Offload .fig compression to a Web Worker during save (was blocking 450ms+)+- Add instance index (`componentId → Set<nodeId>`) — `getInstances()` is O(1) instead of scanning all nodes+- Defer graph event subscription until after layout computation during file open — eliminates redundant `syncInstances` calls+- Cache label collection (sections/components) per scene mutation instead of walking the full tree every frame+- Blocking font loading — fonts load before first render to ensure correct glyphs-- XPath query command — `open-pencil query design.fig "//FRAME[@width < 300]"` to find nodes by type, attributes, and tree structure using XPath selectors.-- CSS Grid layout mode — select a frame, click the grid icon in the auto layout toolbar to switch from flex to grid. Configure column/row tracks (fr, fixed px, auto), column and row gaps, and per-side padding. Powered by a [Yoga fork](https://github.com/open-pencil/yoga/tree/grid) with cherry-picked CSS Grid PRs from upstream.-- JSX and Tailwind CSS export for grid layouts — `grid grid-cols-N`, `gap-x-*`/`gap-y-*`, child `col-start-*`/`row-start-*`/`col-span-*`/`row-span-*`.-- Multi-provider AI support — connect to Anthropic, OpenAI, Google AI, or any OpenAI-compatible endpoint directly, in addition to OpenRouter. Per-provider API key storage, provider settings popover, automatic migration from single OpenRouter key.-- Anthropic-compatible provider for custom API endpoints.-- New AI tools: `get_jsx` (JSX roundtrip view), `diff_jsx` (structural diff), `describe` (semantic role, visual style, layout, design issues).-- AI visual verification — `export_image` returns image content to the model for vision-based review.-- API type toggle (Completions/Responses) for OpenAI-compatible providers.-- Figma zoom shortcuts — ⌘0 (100%), ⌘1 (zoom to fit), ⌘2 (zoom to selection), ⇧1/⇧2 alternatives.-- XPath query tool — `query_nodes` for AI/MCP with attribute selectors, tree traversal, and type filtering.+### Features-### Changed--- Padding on a frame auto-enables vertical auto-layout.-- AI tools run `computeAllLayouts` after execution — layout updates immediately.-- Enhanced AI system prompt with full JSX prop reference and verification workflow.-- Chat panel preserves messages when toggling UI visibility.-- SceneGraph event bus (nanoevents) — `node:created`, `node:updated`, `node:deleted`, `node:reparented`, `node:reordered` events replace monkey-patching in collab sync and manual render invalidation.-- Replace esbuild-wasm (14 MB) with sucrase (201 KB) for JSX transform — `buildComponent()` and `renderJSX()` now synchronous and browser-compatible.-- `useMagicKeys` keyboard shortcut system — replaces tinykeys with VueUse built-in, cross-platform Meta/Control handling, modifier exclusion for combo conflicts.-- Dev-only debug toolbar for copying chat logs.-- Auto-layout icons in layer tree — vertical (rows), horizontal (columns), and grid icons for auto-layout frames; components keep their purple diamond.-- Frame titles on canvas are now draggable — clicking a selected top-level frame's name label starts a drag.-- Compact layout controls — icon-based gap (↔/↕) and padding (T/R/B/L) inputs instead of text labels.-- Auto-detect horizontal vs vertical direction when wrapping in auto layout (Shift+A).-- Fix alignment grid for vertical layouts — visual positions now match spatial axes.-- Fix grid switch from HUG-sized frames — frame expands to fit children.-- Remove unwanted white fill when wrapping in auto layout.+- ACP agent support — use Claude Code, Codex, or Gemini CLI as AI assistants in the desktop chat panel+- Permission confirmation dialog — ACP agents request user approval for file/shell operations, MCP design tools auto-approved+- Unified MCP server — single HTTP + WebSocket proxy replaces Vite SSR bridge+- Stock photo integration — `stock_photo` tool fetches images from Pexels or Unsplash and applies to design nodes. Provider adapter supports custom providers.+- Skeleton-first AI workflow — 4-phase design process (plan → skeleton → content fill via `replace_id` → polish) for more reliable AI-generated layouts+- Batched AI tools — `calc` accepts arrays of expressions, `stock_photo` fetches all images in parallel, `batch_update` applies multiple property changes in one call, `describe` accepts `ids` array for multi-node inspection+- AI visual feedback — blue pulsing border on nodes being modified, green flash on completion+- Auto-depth `describe` — adapts inspection depth to subtree size (small block → deeper, large page → shallower)+- `set_fill` gradient support — linear gradients with `color_end` and `gradient` direction params+- `render` tool `replace_id` — atomically swap skeleton placeholders with real content+- MCP `export_image_file` tool for headless PNG rendering+- Grid layout in AI chat — JSX renderer supports `grid`, `columns`, `rows`, `gap` props+- Configurable max output tokens in AI provider settings (default 16384)+- Z.ai AI provider with GLM-5, GLM-4.7, GLM-4.6, GLM-4.5 model families+- MiniMax AI provider with M2.5, M2.1, M2 models++### Improved .fig import fidelity++- Resolve variable-bound fill colors through alias chains+- Fix SCALE constraint resizing for auto-layout instances+- Propagate SCALE constraints through instance clone chains+- Skip self-referencing symbolOverrides on nodes with explicit kiwi properties+- Fix DSD resolution for swapped instance children+- Fix instance swap override propagation through clone chains+- Fix component property override resolution through clone chains+- Fix text/property overrides clobbered by second transitive sync++### Fixes++- Fix text rendering with wrong fonts on file open — all font weights (including default family) are now loaded before the first render+- Fix `weightToStyle` mapping: weight 400 now correctly maps to "Regular" instead of "Medium"+- Fix detached ArrayBuffer crash when switching pages after saving — export worker now copies image buffers before transferring+- Show warning toast when fonts fail to load, error toast when file open fails+- Fix FillPicker crash when selecting image fills (missing `ref` import from #92)+- Fix Google Fonts TLS/network errors not cached — failed families no longer retry on every render+- Fix CJK text garbled when font is unavailable — fallback now renders through paragraph shaper instead of raw `drawText`, preserving CJK characters via the fallback font chain+- Fix auto-layout overflow in AI-generated designs — text wrapping, min/max constraints, absolute positioning, and FILL sizing now work correctly+- Fix `layoutAlignSelf` limited to STRETCH — full range supported (CENTER, MAX, MIN, BASELINE)+- Fix hidden auto-layout children losing their dimensions on layout recompute+- Fix ProviderSettings popover not visible in AI chat+- Fix paste/copy/cut intercepted by canvas in AI chat input+- Strip TypeScript casts from AI-generated JSX (`as any`, `as const`)+- Fix parsing complex .fig files crashing on missing GUIDs in component overrides+- Fix headless text layout using 100×100 default size instead of estimated dimensions — multi-line wrapping now estimated correctly+- Fix clipboard roundtrip losing properties — clipsContent, constraints, arcData, strokeCap/Join, layoutAlignSelf, textAutoResize, autoRename now preserved in Figma Kiwi serialization+- Fix MCP headless export crashing on `window.queryLocalFonts` in non-browser runtimes (Bun/Node)+- Fix MCP `export_image` rendering blank text — fonts now loaded before rasterization+- Fix text always using paragraph rendering with Inter fallback chain (no more missing-font garbling)+- Clip children to rounded corners when `clipsContent` is true+- Use child shape for drop shadows on transparent containers+- Treat `FOREGROUND_BLUR` as layer blur wrapping children+- Fix radial, angular, and diamond gradient rendering+- Fix .fig export roundtrip: variable GUIDs colliding with document+- Fix file open dialog not working on first click in Safari+- Skip variable fonts from local font access, use Google Fonts instead+- Disable autosave by default-### Fixed+## 0.9.0 — 2026-03-09-- Serialize variables, collections, and bindings to `.fig` files — previously lost on save (#65).-- Text nodes created via MCP now render in Figma — emit `derivedTextData` with font metadata and layout size (#64).-- Double-click on layer tree no longer toggles expand/collapse — use the chevron instead.-- Page rename input matches layer rename styling.-- Fix `w="fill"`/`h="fill"` in JSX renderer — now direction-aware based on parent flex axis.-- Fix text auto-resize defaulting to fixed 100×100 — text without explicit width uses `WIDTH_AND_HEIGHT`.-- Fix `clipsContent` not propagated to Yoga — frames with clip enabled now set `Overflow.Hidden`.-- Fix `COUNTER_ALIGN_MAP` mapping stretch to `MIN` instead of `STRETCH`.-- Fix JSX export omitting x/y for absolute-positioned children.-- Fix JSX export ignoring `textAutoResize` for text sizing.-- Fix drag terminating on mouseleave — drags now continue outside the canvas.-- Fix `export_image` stack overflow on large nodes — chunked base64 encoding.-- Undo support for auto-layout reorder, layer tree reorder, and drag reparent.-- Page snapshot undo for AI tool mutations.-- Fix collab sync for same-parent reorder — `node:reordered` events now propagated to Yjs peers.-- Fix orphaned instances on clipboard paste — detach to FRAME when component is missing.-- Fix text typography lost on Figma clipboard import — preserve fontFamily, fontWeight, fontSize, lineHeight.-- Fix `copyFill` missing `gradientTransform` and `imageTransform` — gradient fills now round-trip correctly.+### Features++- XPath query command — `open-pencil query design.fig "//FRAME[@width < 300]"` to find nodes by type, attributes, and tree structure using XPath selectors+- CSS Grid layout mode — select a frame, click the grid icon in the auto layout toolbar to switch from flex to grid. Configure column/row tracks (fr, fixed px, auto), column and row gaps, and per-side padding. Powered by a [Yoga fork](https://github.com/open-pencil/yoga/tree/grid) with cherry-picked CSS Grid PRs from upstream+- JSX and Tailwind CSS export for grid layouts — `grid grid-cols-N`, `gap-x-*`/`gap-y-*`, child `col-start-*`/`row-start-*`/`col-span-*`/`row-span-*`+- Multi-provider AI support — connect to Anthropic, OpenAI, Google AI, or any OpenAI-compatible endpoint directly, in addition to OpenRouter. Per-provider API key storage, provider settings popover, automatic migration from single OpenRouter key+- Anthropic-compatible provider for custom API endpoints+- New AI tools: `get_jsx` (JSX roundtrip view), `diff_jsx` (structural diff), `describe` (semantic role, visual style, layout, design issues)+- AI visual verification — `export_image` returns image content to the model for vision-based review+- API type toggle (Completions/Responses) for OpenAI-compatible providers+- Figma zoom shortcuts — ⌘0 (100%), ⌘1 (zoom to fit), ⌘2 (zoom to selection), ⇧1/⇧2 alternatives+- XPath query tool — `query_nodes` for AI/MCP with attribute selectors, tree traversal, and type filtering++### Fixes++- Serialize variables, collections, and bindings to `.fig` files — previously lost on save (#65)+- Text nodes created via MCP now render in Figma — emit `derivedTextData` with font metadata and layout size (#64)+- Double-click on layer tree no longer toggles expand/collapse — use the chevron instead+- Page rename input matches layer rename styling+- Fix `w="fill"`/`h="fill"` in JSX renderer — now direction-aware based on parent flex axis+- Fix text auto-resize defaulting to fixed 100×100 — text without explicit width uses `WIDTH_AND_HEIGHT`+- Fix `clipsContent` not propagated to Yoga — frames with clip enabled now set `Overflow.Hidden`+- Fix `COUNTER_ALIGN_MAP` mapping stretch to `MIN` instead of `STRETCH`+- Fix JSX export omitting x/y for absolute-positioned children+- Fix JSX export ignoring `textAutoResize` for text sizing+- Fix drag terminating on mouseleave — drags now continue outside the canvas+- Fix `export_image` stack overflow on large nodes — chunked base64 encoding+- Undo support for auto-layout reorder, layer tree reorder, and drag reparent+- Page snapshot undo for AI tool mutations+- Fix collab sync for same-parent reorder — `node:reordered` events now propagated to Yjs peers+- Fix orphaned instances on clipboard paste — detach to FRAME when component is missing+- Fix text typography lost on Figma clipboard import — preserve fontFamily, fontWeight, fontSize, lineHeight+- Fix `copyFill` missing `gradientTransform` and `imageTransform` — gradient fills now round-trip correctly### Performance-- Event-driven rendering and component sync — `SceneGraph` emits typed events on mutations; `requestRender()` calls reduced from 94 to 22, component instance sync uses microtask batching with deduplication.-- Replace `structuredClone` with typed copy helpers for fills, strokes, effects, and style runs (~24× faster in hot paths).-- Filter .fig unzip to only decompress canvas and image entries, skipping metadata cruft.+- Event-driven rendering and component sync — `SceneGraph` emits typed events on mutations; `requestRender()` calls reduced from 94 to 22, component instance sync uses microtask batching with deduplication+- Replace `structuredClone` with typed copy helpers for fills, strokes, effects, and style runs (~24× faster in hot paths)+- Filter .fig unzip to only decompress canvas and image entries, skipping metadata cruft++### Improvements++- Padding on a frame auto-enables vertical auto-layout+- AI tools run `computeAllLayouts` after execution — layout updates immediately+- Enhanced AI system prompt with full JSX prop reference and verification workflow+- Chat panel preserves messages when toggling UI visibility+- SceneGraph event bus (nanoevents) — `node:created`, `node:updated`, `node:deleted`, `node:reparented`, `node:reordered` events replace monkey-patching in collab sync and manual render invalidation+- Replace esbuild-wasm (14 MB) with sucrase (201 KB) for JSX transform — `buildComponent()` and `renderJSX()` now synchronous and browser-compatible+- `useMagicKeys` keyboard shortcut system — replaces tinykeys with VueUse built-in, cross-platform Meta/Control handling, modifier exclusion for combo conflicts+- Dev-only debug toolbar for copying chat logs+- Auto-layout icons in layer tree — vertical (rows), horizontal (columns), and grid icons for auto-layout frames; components keep their purple diamond+- Frame titles on canvas are now draggable — clicking a selected top-level frame's name label starts a drag+- Compact layout controls — icon-based gap (↔/↕) and padding (T/R/B/L) inputs instead of text labels+- Auto-detect horizontal vs vertical direction when wrapping in auto layout (Shift+A)+- Fix alignment grid for vertical layouts — visual positions now match spatial axes+- Fix grid switch from HUG-sized frames — frame expands to fit children+- Remove unwanted white fill when wrapping in auto layout## 0.8.0 — 2026-03-07-### Added+### Features-- Mobile layout & PWA — responsive editor with touch-optimized toolbar, swipeable bottom drawer (layers/properties/design/code), HUD overlay, and installable PWA with icons and service worker.+- Mobile layout & PWA — responsive editor with touch-optimized toolbar, swipeable bottom drawer (layers/properties/design/code), HUD overlay, and installable PWA with icons and service worker- Tailwind CSS v4 JSX export — export selections as HTML with Tailwind utility classes (`<div className="flex gap-4 p-3">`) from the Code panel, CLI (`bun open-pencil export --format jsx --style tailwind`), or programmatically via `sceneNodeToJSX(id, graph, 'tailwind')`. 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.-- Code panel format toggle — switch between OpenPencil (custom components) and Tailwind (HTML + utility classes) output.-- Homebrew tap — `brew install open-pencil/tap/open-pencil` for macOS (arm64 + x64), auto-updated on each release.-- Double-click to rename layers — inline rename in layer panel, shared `useInlineRename` composable.-- New AI/MCP tools: `analyze_colors`, `analyze_typography`, `analyze_spacing`, `analyze_clusters`, `diff_create`, `diff_show`, `get_components`, `get_current_page`, `arrange`, `node_to_component`.-- CLI-to-app RPC bridge — all CLI commands work against the running app when no file is specified. Start the app, then run `bun open-pencil tree` to inspect the live document.-- VitePress docs site — user guide, reference, architecture, and development docs at openpencil.dev with 6 locales (en, de, fr, es, it, pl), SEO (OG tags, hreflang, JSON-LD, sitemap), and dark theme.--### Changed--- Refactor mobile drawer tabs, layout sizing dropdowns, and inline rename to use Reka UI primitives.-- Add shared UI style helpers with tailwind-variants for menus, selects, buttons, and surfaces.-- Unified tool definitions — define once in `packages/core/src/tools/`, automatically available in AI chat, CLI, and MCP.-- Harden FigmaAPI — hide internals via Symbols, freeze arrays, fix `layoutSizing`, 30+ new properties and methods.-- Split tools into domain files (read, create, modify, structure, variables, vector, analyze) — easier to navigate and extend.-- Replace inline type definitions with named types (`Color`, `Vector`, `SceneNode`) across the codebase.-- Split 3200-line `renderer.ts` into `packages/core/src/renderer/` with 10 focused files (scene, overlays, fills, strokes, shapes, effects, rulers, labels).-- Centralize all color utilities in `packages/core/src/color.ts` — `colorToHex8`, `colorToCSSCompact`, `normalizeColor`, `colorDistance`; remove 5 duplicate implementations across the codebase.-- Add `geometry.ts` with shared rotation math (`degToRad`, `radToDeg`, `rotatePoint`, `rotatedCorners`, `rotatedBBox`).-- Extract `isArrayMixed()` helper for multi-selection property panels.---- Add `motion-v` for declarative animations — used in mobile drawer (spring-animated height with pan gestures) and toolbar (layout-animated category switching with directional slide transitions).-- Mobile drawer: replace `useSwipe` + manual rAF animation with `motion.div` `:animate` + `@pan`/`@panEnd`; always-on tab state (no more null `activeRibbonTab`); content stays rendered when closed.-- Mobile toolbar: replace manual `scrollWidth` measuring + inline CSS transitions with `motion.div layout` + `AnimatePresence` directional slide variants.-- Mobile UI cleanup: extract shared `colorToCSS` util to core, `initials` to `src/utils/text`, `toolIcons` to `src/utils/tools`; replace hand-rolled dropdowns with reka-ui Popover/DropdownMenu; narrow `mobileDrawerSnap` type to string union; move magic numbers to constants; disable PWA service worker in dev mode.-- 83 new E2E tests (57 → 140): design panel, code panel, components, copy/paste, multi-page, text editing, keyboard shortcuts, context menu.-- 150 new unit tests (588 → 738): color, undo, snap, vector, style-runs, text-editor.-- 48 new E2E tests (9 spec files) + 26 mutation unit tests + store/canvas test helpers.-- Add `data-test-id` attributes to AppearanceSection, LayoutSection, TypographySection, VariablesDialog, EditorView.--### Fixed--- Fix drawer animation jump on close — single spring transition instead of two-phase.-- Fix `ALL_TOOLS` registry missing newer tools (`analyzeColors`, `diffCreate`, `exportImage`, `arrangeNodes`).-- Fix `renderJSX` typo in tool definitions (`renderJsx` → `renderJSX`).-- Fix all oxlint warnings and tsgo errors — replace `!` non-null assertions in `use-collab.ts` with local const captures.-- Fix broken test imports — stale `../../src/engine/` paths updated to `@open-pencil/core`.-- Fix flaky E2E tests: layers panel navigates to `/demo`, zoom-to-fit test zooms in first, snapshot rendering stabilized with `workers: 1` and `colorScheme: dark`.-- Fix bogus .fig import mappings for `expanded` and `strokeMiterLimit` fields.-- Fix PWA manifest error in dev mode, handle invalid font data gracefully.-- Fix eval response unwrapping and `export_jsx` page selection in RPC bridge.-- Fix automation commands not recomputing layouts after mutations.-- Fix workspace dependency not resolved when installing from npm (switch CI to pnpm publish).+- Code panel format toggle — switch between OpenPencil (custom components) and Tailwind (HTML + utility classes) output+- Homebrew tap — `brew install open-pencil/tap/open-pencil` for macOS (arm64 + x64), auto-updated on each release+- Double-click to rename layers — inline rename in layer panel, shared `useInlineRename` composable+- New AI/MCP tools: `analyze_colors`, `analyze_typography`, `analyze_spacing`, `analyze_clusters`, `diff_create`, `diff_show`, `get_components`, `get_current_page`, `arrange`, `node_to_component`+- CLI-to-app RPC bridge — all CLI commands work against the running app when no file is specified. Start the app, then run `bun open-pencil tree` to inspect the live document+- VitePress docs site — user guide, reference, architecture, and development docs at openpencil.dev with 6 locales (en, de, fr, es, it, pl), SEO (OG tags, hreflang, JSON-LD, sitemap), and dark theme++### Improvements++- Refactor mobile drawer tabs, layout sizing dropdowns, and inline rename to use Reka UI primitives+- Add shared UI style helpers with tailwind-variants for menus, selects, buttons, and surfaces+- Unified tool definitions — define once in `packages/core/src/tools/`, automatically available in AI chat, CLI, and MCP+- Harden FigmaAPI — hide internals via Symbols, freeze arrays, fix `layoutSizing`, 30+ new properties and methods+- Split tools into domain files (read, create, modify, structure, variables, vector, analyze) — easier to navigate and extend+- Replace inline type definitions with named types (`Color`, `Vector`, `SceneNode`) across the codebase+- Split 3200-line `renderer.ts` into `packages/core/src/renderer/` with 10 focused files (scene, overlays, fills, strokes, shapes, effects, rulers, labels)+- Centralize all color utilities in `packages/core/src/color.ts` — `colorToHex8`, `colorToCSSCompact`, `normalizeColor`, `colorDistance`; remove 5 duplicate implementations across the codebase+- Add `geometry.ts` with shared rotation math (`degToRad`, `radToDeg`, `rotatePoint`, `rotatedCorners`, `rotatedBBox`)+- Extract `isArrayMixed()` helper for multi-selection property panels++### Fixes++- Fix drawer animation jump on close — single spring transition instead of two-phase+- Fix `ALL_TOOLS` registry missing newer tools (`analyzeColors`, `diffCreate`, `exportImage`, `arrangeNodes`)+- Fix `renderJSX` typo in tool definitions (`renderJsx` → `renderJSX`)+- Fix all oxlint warnings and tsgo errors — replace `!` non-null assertions in `use-collab.ts` with local const captures+- Fix broken test imports — stale `../../src/engine/` paths updated to `@open-pencil/core`+- Fix flaky E2E tests: layers panel navigates to `/demo`, zoom-to-fit test zooms in first, snapshot rendering stabilized with `workers: 1` and `colorScheme: dark`+- Fix bogus .fig import mappings for `expanded` and `strokeMiterLimit` fields+- Fix PWA manifest error in dev mode, handle invalid font data gracefully+- Fix eval response unwrapping and `export_jsx` page selection in RPC bridge+- Fix automation commands not recomputing layouts after mutations+- Fix workspace dependency not resolved when installing from npm (switch CI to pnpm publish)++### Internal++- Add `motion-v` for declarative animations — used in mobile drawer (spring-animated height with pan gestures) and toolbar (layout-animated category switching with directional slide transitions)+- Mobile drawer: replace `useSwipe` + manual rAF animation with `motion.div` `:animate` + `@pan`/`@panEnd`; always-on tab state (no more null `activeRibbonTab`); content stays rendered when closed+- Mobile toolbar: replace manual `scrollWidth` measuring + inline CSS transitions with `motion.div layout` + `AnimatePresence` directional slide variants+- Mobile UI cleanup: extract shared `colorToCSS` util to core, `initials` to `src/utils/text`, `toolIcons` to `src/utils/tools`; replace hand-rolled dropdowns with reka-ui Popover/DropdownMenu; narrow `mobileDrawerSnap` type to string union; move magic numbers to constants; disable PWA service worker in dev mode+- 83 new E2E tests (57 → 140): design panel, code panel, components, copy/paste, multi-page, text editing, keyboard shortcuts, context menu+- 150 new unit tests (588 → 738): color, undo, snap, vector, style-runs, text-editor+- 48 new E2E tests (9 spec files) + 26 mutation unit tests + store/canvas test helpers+- Add `data-test-id` attributes to AppearanceSection, LayoutSection, TypographySection, VariablesDialog, EditorView## 0.7.0 — 2026-03-05-### Added+### Features-- SVG export — export selections as SVG from the export panel, context menu, CLI (`bun open-pencil export --format svg`), or MCP/AI tools (`export_svg`). Supports rectangles, ellipses, lines, stars, polygons, vectors, text with style runs, gradients, image fills, effects, blend modes, clip paths, and nested groups (#46).-- Copy/Paste as submenu in context menu — Copy as text, Copy as SVG, Copy as PNG (⇧⌘C), Copy as JSX.-- Stroke align (Inside/Center/Outside) with clip-based rendering matching Figma behavior.-- Individual stroke weights per side (Top/Right/Bottom/Left) with side selector dropdown.-- Google Fonts fallback — automatically loads fonts from Google Fonts API when not available locally.-- Auto-save toggle in File menu — disable to prevent automatic writes to the opened .fig file.-- Renderer profiler with in-canvas HUD overlay, GPU timing, and phase instrumentation.+- SVG export — export selections as SVG from the export panel, context menu, CLI (`bun open-pencil export --format svg`), or MCP/AI tools (`export_svg`). Supports rectangles, ellipses, lines, stars, polygons, vectors, text with style runs, gradients, image fills, effects, blend modes, clip paths, and nested groups (#46)+- Copy/Paste as submenu in context menu — Copy as text, Copy as SVG, Copy as PNG (⇧⌘C), Copy as JSX+- Stroke align (Inside/Center/Outside) with clip-based rendering matching Figma behavior+- Individual stroke weights per side (Top/Right/Bottom/Left) with side selector dropdown+- Google Fonts fallback — automatically loads fonts from Google Fonts API when not available locally+- Auto-save toggle in File menu — disable to prevent automatic writes to the opened .fig file+- Renderer profiler with in-canvas HUD overlay, GPU timing, and phase instrumentation-### Changed+### Improvements-- Replace custom color picker with Reka UI Color components (ColorArea, ColorSlider, ColorField) — adds keyboard navigation and accessibility to the color area, hue, and alpha controls.+- Replace custom color picker with Reka UI Color components (ColorArea, ColorSlider, ColorField) — adds keyboard navigation and accessibility to the color area, hue, and alpha controls-### Fixed+### Fixes-- CJK text rendering — load a system CJK font (PingFang SC, Microsoft YaHei, Noto Sans CJK) as fallback; falls back to Noto Sans SC from Google Fonts when no system font is available (#48).-- Font registration errors no longer cache invalid font data — `loadFont` only caches after successful CanvasKit registration.-- Fix `render` tool failing on Windows + Bun with "Cannot find module" error (#43).-- Fix hover highlighting nodes from internal component pages — scope hit-test to current page.-- Fix hit-testing on transparent frames and groups — empty containers without fills or strokes are now click-through, clipping parents reject hits outside their bounds, matching Figma behavior.+- CJK text rendering — load a system CJK font (PingFang SC, Microsoft YaHei, Noto Sans CJK) as fallback; falls back to Noto Sans SC from Google Fonts when no system font is available (#48)+- Font registration errors no longer cache invalid font data — `loadFont` only caches after successful CanvasKit registration+- Fix `render` tool failing on Windows + Bun with "Cannot find module" error (#43)+- Fix hover highlighting nodes from internal component pages — scope hit-test to current page+- Fix hit-testing on transparent frames and groups — empty containers without fills or strokes are now click-through, clipping parents reject hits outside their bounds, matching Figma behavior- Fix instance overrides on .fig import and clipboard paste — resolve guidPaths by overrideKey, handle component swaps (`overriddenSymbolID`), propagate through nested clone chains. Import and paste now share a single override engine.-- Apply Figma component property assignments on import — boolean visibility toggles and instance swaps via `componentPropRefs`/`componentPropAssignments`.-- Apply `derivedSymbolData` sizes on import — containers now shrink correctly when component properties hide children.-- Fix override resolution for nested instance targets — check the current node before searching descendants.-- Fix component property assignments for nested instances — resolve scoped `componentPropAssignments` inside `symbolOverrides` via guidPath, handle `guidValue` for instance swaps, reorder phases so transitive sync doesn't clobber visibility.-- Pixel-perfect vector rendering using pre-computed `fillGeometry`/`strokeGeometry` blobs from .fig files — eliminates white gaps between adjacent stroked shapes.-- Stroke outlines on clipboard paste — convert vectorNetwork paths to filled outlines via CanvasKit when geometry blobs are unavailable.-- Apply `derivedSymbolData` transforms and geometry during import — instance children render at correct scale and position.-- Fix internal pages becoming visible after .fig round-trip — preserve `internalOnly` flag on export.-- Scope layout recomputation to current page for paste/undo/font-load (major speedup on large multi-page files).-- Show loading overlay until all document fonts are loaded (no more partially rendered text).-- Load fonts when switching pages (previously only loaded for the first page).-- Always show visibility toggle on fill, stroke, and effect rows (matches Figma).-- Fix renderer crash on double destroy when closing files quickly.-- Fix .fig page ordering — use deterministic byte comparison for fractional index positions.-- Fix text truncation using `textTruncation` field instead of `textAutoResize`.-- Fix horizontal scrollbar on design and pages panels.-- Style scrollbars for Tauri (thin dark overlay instead of default OS chrome).-- Enable file watcher in Tauri — `watch` feature was missing from `tauri-plugin-fs`.+- Apply Figma component property assignments on import — boolean visibility toggles and instance swaps via `componentPropRefs`/`componentPropAssignments`+- Apply `derivedSymbolData` sizes on import — containers now shrink correctly when component properties hide children+- Fix override resolution for nested instance targets — check the current node before searching descendants+- Fix component property assignments for nested instances — resolve scoped `componentPropAssignments` inside `symbolOverrides` via guidPath, handle `guidValue` for instance swaps, reorder phases so transitive sync doesn't clobber visibility+- Pixel-perfect vector rendering using pre-computed `fillGeometry`/`strokeGeometry` blobs from .fig files — eliminates white gaps between adjacent stroked shapes+- Stroke outlines on clipboard paste — convert vectorNetwork paths to filled outlines via CanvasKit when geometry blobs are unavailable+- Apply `derivedSymbolData` transforms and geometry during import — instance children render at correct scale and position+- Fix internal pages becoming visible after .fig round-trip — preserve `internalOnly` flag on export+- Scope layout recomputation to current page for paste/undo/font-load (major speedup on large multi-page files)+- Show loading overlay until all document fonts are loaded (no more partially rendered text)+- Load fonts when switching pages (previously only loaded for the first page)+- Always show visibility toggle on fill, stroke, and effect rows (matches Figma)+- Fix renderer crash on double destroy when closing files quickly+- Fix .fig page ordering — use deterministic byte comparison for fractional index positions+- Fix text truncation using `textTruncation` field instead of `textAutoResize`+- Fix horizontal scrollbar on design and pages panels+- Style scrollbars for Tauri (thin dark overlay instead of default OS chrome)+- Enable file watcher in Tauri — `watch` feature was missing from `tauri-plugin-fs`## 0.6.0 — 2026-03-04-### Added--- Multi-selection properties panel — edit position, size, appearance, fill, stroke, and effects across multiple selected nodes.-- Shared values display normally, differing values show "Mixed".-- W/H inputs in multi-selection mode.-- Flip horizontal/vertical using scale transform instead of rotation.-- Single-node alignment aligns to parent frame bounds.-- ACP agent package — Agent Communication Protocol server for AI coding tools, reusing core ToolDefs.--### Changed--- Apple code signing and notarization for macOS builds.-- Git LFS storage moved from GitHub to Cloudflare R2.--### Fixed--- Fix Figma clipboard paste: extract shared kiwi→SceneNode conversion, fixing broken auto-layout, missing gradient/image fills, effects, style runs, and text properties.-- Fix vector rendering on paste — scale path coordinates from Figma's normalizedSize to actual node bounds.-- Fix pasted instances having no children — populate from component via symbolData when both are in clipboard.-- Detect component sets on import — promote FRAME nodes with VARIANT componentPropDefs to COMPONENT_SET.-- Skip internal canvas on paste — components on Figma's hidden internal page populate instances but are not pasted as visible nodes.-- Apply instance overrides on paste — text content, fills, visibility, layoutGrow, and textAutoResize from symbolOverrides.-- Fix auto-layout child ordering — sort by geometric position instead of z-order position strings.-- Load fonts on paste and .fig import — collect font families from text nodes and load into CanvasKit.-- Text measurement in auto-layout — use CanvasKit paragraph metrics for WIDTH_AND_HEIGHT text nodes.-- Recompute layouts after font loading completes.-- Fix PERCENT line height conversion — was stored as raw value instead of pixels.-- Fix InvalidCharacterError when copying nodes with non-ASCII text.-- Load all font weight/style variants needed by pasted text nodes.-- Fix font loading not registering in core cache.-- Fix halfLeading applied to text measurement — enable only for rendering.-- Clear hover on zoom/pinch to keep scene picture cache valid.-- Fix flip buttons using rotation math instead of actual mirroring.-- Fix flip transform encoding — scale first matrix column only (was incorrectly producing 180° rotation).-- Decode flip state from .fig transform matrix on import.+### Features++- Multi-selection properties panel — edit position, size, appearance, fill, stroke, and effects across multiple selected nodes+- Shared values display normally, differing values show "Mixed"+- W/H inputs in multi-selection mode+- Flip horizontal/vertical using scale transform instead of rotation+- Single-node alignment aligns to parent frame bounds+- ACP agent package — Agent Communication Protocol server for AI coding tools, reusing core ToolDefs++### Build++- Apple code signing and notarization for macOS builds+- Git LFS storage moved from GitHub to Cloudflare R2++### Fixes++- Fix Figma clipboard paste: extract shared kiwi→SceneNode conversion, fixing broken auto-layout, missing gradient/image fills, effects, style runs, and text properties+- Fix vector rendering on paste — scale path coordinates from Figma's normalizedSize to actual node bounds+- Fix pasted instances having no children — populate from component via symbolData when both are in clipboard+- Detect component sets on import — promote FRAME nodes with VARIANT componentPropDefs to COMPONENT_SET+- Skip internal canvas on paste — components on Figma's hidden internal page populate instances but are not pasted as visible nodes+- Apply instance overrides on paste — text content, fills, visibility, layoutGrow, and textAutoResize from symbolOverrides+- Fix auto-layout child ordering — sort by geometric position instead of z-order position strings+- Load fonts on paste and .fig import — collect font families from text nodes and load into CanvasKit+- Text measurement in auto-layout — use CanvasKit paragraph metrics for WIDTH_AND_HEIGHT text nodes+- Recompute layouts after font loading completes+- Fix PERCENT line height conversion — was stored as raw value instead of pixels+- Fix InvalidCharacterError when copying nodes with non-ASCII text+- Load all font weight/style variants needed by pasted text nodes+- Fix font loading not registering in core cache+- Fix halfLeading applied to text measurement — enable only for rendering+- Clear hover on zoom/pinch to keep scene picture cache valid+- Fix flip buttons using rotation math instead of actual mirroring+- Fix flip transform encoding — scale first matrix column only (was incorrectly producing 180° rotation)+- Decode flip state from .fig transform matrix on import## 0.5.1 — 2026-03-03-### Fixed+### Fixes-- Fix File → Save crash when document has layer blur effects.+- Fix File → Save crash when document has layer blur effects## 0.5.0 — 2026-03-03-### Added--- Effects rendering: drop shadow, inner shadow, shadow spread, layer blur, background blur, foreground blur.-- Text shadows render on glyphs instead of bounding box.-- Multi-file tabs — open multiple documents in tabs within a single window.-- Tab bar with close buttons, middle-click to close, and new tab (+) button.-- Keyboard shortcuts: ⌘N/⌘T new tab, ⌘W close tab, ⌘O opens in new tab.-- Native Tauri menu: File → New and File → Close Tab wired to tab actions.-- Render text from SkPicture cache when fonts are missing — pixel-perfect display without the font installed.-- Missing font indicator (⚠) next to font picker in the sidebar.-- Right-click context menu on layers panel — same actions as the canvas context menu.+### Features++- Effects rendering: drop shadow, inner shadow, shadow spread, layer blur, background blur, foreground blur+- Text shadows render on glyphs instead of bounding box+- Multi-file tabs — open multiple documents in tabs within a single window+- Tab bar with close buttons, middle-click to close, and new tab (+) button+- Keyboard shortcuts: ⌘N/⌘T new tab, ⌘W close tab, ⌘O opens in new tab+- Native Tauri menu: File → New and File → Close Tab wired to tab actions+- Render text from SkPicture cache when fonts are missing — pixel-perfect display without the font installed+- Missing font indicator (⚠) next to font picker in the sidebar+- Right-click context menu on layers panel — same actions as the canvas context menu- 40+ new AI/MCP tools ported from figma-use:- Granular set tools: `set_rotation`, `set_opacity`, `set_radius`, `set_minmax`, `set_text`, `set_font`, `set_font_range`, `set_text_resize`, `set_visible`, `set_blend`, `set_locked`, `set_stroke_align`- Node operations: `node_bounds`, `node_move`, `node_resize`, `node_ancestors`, `node_children`, `node_tree`, `node_bindings`, `node_replace_with`@@ -738,259 +723,271 @@- Create tools: `create_page`, `create_vector`, `create_slice`- Viewport: `viewport_get`, `viewport_set`, `viewport_zoom_to_fit`, `page_bounds`- Misc: `flatten_nodes`, `list_fonts`-- `set_text_properties` tool: alignment, auto-resize, decoration.-- `set_layout_child` tool: sizing, grow, align_self, positioning.-- 13 MCP server integration tests via `InMemoryTransport`.--### Changed--- Resizable pages/layers split in left panel with reka-ui Splitter.-- Layers tree auto-expands and scrolls to reveal selected node.-- Loading overlay on canvas while opening .fig files.-- Hide internal-only pages (e.g. "Internal Only Canvas" in design systems).-- Render page dividers — pages named with only dashes/asterisks/spaces show as horizontal lines.-- Only show component labels for COMPONENT and COMPONENT_SET, not instances.-- Replace all native `<select>` dropdowns with reka-ui `AppSelect` component.-- Smoother trackpad pinch-to-zoom with `Math.exp` curve and deltaMode normalization.-- Fix font picker dropdown truncating long font names.-- Show explanation in font picker when Local Font Access API unavailable (Safari/Firefox).---- Auto-populate GitHub Release notes from CHANGELOG.md via `ffurrer2/extract-release-notes@v2`.-- Skip already-published npm versions on CI re-runs instead of failing.-- Exclude non-app directories from Vite file watcher.+- `set_text_properties` tool: alignment, auto-resize, decoration+- `set_layout_child` tool: sizing, grow, align_self, positioning+- 13 MCP server integration tests via `InMemoryTransport`++### UI++- Resizable pages/layers split in left panel with reka-ui Splitter+- Layers tree auto-expands and scrolls to reveal selected node+- Loading overlay on canvas while opening .fig files+- Hide internal-only pages (e.g. "Internal Only Canvas" in design systems)+- Render page dividers — pages named with only dashes/asterisks/spaces show as horizontal lines+- Only show component labels for COMPONENT and COMPONENT_SET, not instances+- Replace all native `<select>` dropdowns with reka-ui `AppSelect` component+- Smoother trackpad pinch-to-zoom with `Math.exp` curve and deltaMode normalization+- Fix font picker dropdown truncating long font names+- Show explanation in font picker when Local Font Access API unavailable (Safari/Firefox)++### Fixes++- Fix drop shadow rendering on top of fills — shadow now draws behind opaque content+- Fix effect property changes not recorded in undo/redo history+- Fix active tab text invisible against same-color background+- Fix clipboard "Outside int range" error — `pasteID` used unsigned int exceeding Kiwi's signed 32-bit field+- Error toasts are now sticky (don't auto-dismiss), with selectable text, copy button, and close button+- Truncate long node names in export button+### Performance-- Extract shared color constants (`BLACK`, `TRANSPARENT`, `DEFAULT_SHADOW_COLOR`) — replaces 8 inline literals across core.-- Extract shared `NodeContextMenuContent` component to avoid menu duplication.-- Fix `@open-pencil/core` dep in MCP package: `workspace:*` for local dev (pnpm resolves at publish time).-- Replace store thunks with a late-binding proxy.+- Per-node SkPicture cache for effect rendering — unchanged shadow/blur nodes replay from cache on scene redraws+- Drop shadows use `MaskFilter` direct draw instead of `saveLayer` offscreen buffers+- Cached `ImageFilter`, `MaskFilter`, reusable effect paint — zero per-frame WASM allocations for effects+- Reuse GL context on panel resize — swap surface without recreating renderer, preserving all caches+- Per-frame absolute position cache — avoids repeated parent-chain walks during rendering+- Optimize zoom/pan smoothness with `shallowReactive`, `useRafFn`, and input coalescing+### Build-- Clipboard roundtrip tests: encode to Figma Kiwi binary → decode → verify.-- 9 visual regression snapshot tests for effects rendering.-- Zoom/pan E2E tests and pipeline benchmark.-- MCP server edge-case tests for `find_nodes` and Zod validation.-- 6 unit tests for absolute position cache.+- Auto-populate GitHub Release notes from CHANGELOG.md via `ffurrer2/extract-release-notes@v2`+- Skip already-published npm versions on CI re-runs instead of failing+- Exclude non-app directories from Vite file watcher-### Fixed+### Internal-- Fix drop shadow rendering on top of fills — shadow now draws behind opaque content.-- Fix effect property changes not recorded in undo/redo history.-- Fix active tab text invisible against same-color background.-- Fix clipboard "Outside int range" error — `pasteID` used unsigned int exceeding Kiwi's signed 32-bit field.-- Error toasts are now sticky (don't auto-dismiss), with selectable text, copy button, and close button.-- Truncate long node names in export button.+- Extract shared color constants (`BLACK`, `TRANSPARENT`, `DEFAULT_SHADOW_COLOR`) — replaces 8 inline literals across core+- Extract shared `NodeContextMenuContent` component to avoid menu duplication+- Fix `@open-pencil/core` dep in MCP package: `workspace:*` for local dev (pnpm resolves at publish time)+- Replace store thunks with a late-binding proxy-### Performance+### Tests-- Per-node SkPicture cache for effect rendering — unchanged shadow/blur nodes replay from cache on scene redraws.-- Drop shadows use `MaskFilter` direct draw instead of `saveLayer` offscreen buffers.-- Cached `ImageFilter`, `MaskFilter`, reusable effect paint — zero per-frame WASM allocations for effects.-- Reuse GL context on panel resize — swap surface without recreating renderer, preserving all caches.-- Per-frame absolute position cache — avoids repeated parent-chain walks during rendering.-- Optimize zoom/pan smoothness with `shallowReactive`, `useRafFn`, and input coalescing.+- Clipboard roundtrip tests: encode to Figma Kiwi binary → decode → verify+- 9 visual regression snapshot tests for effects rendering+- Zoom/pan E2E tests and pipeline benchmark+- MCP server edge-case tests for `find_nodes` and Zod validation+- 6 unit tests for absolute position cache-## 0.4.2 — 2026-03-02+## [0.4.2] (2026-03-02)-### Changed+### Fixes-- Import additional properties from Figma clipboard: `layoutAlignSelf`, `clipsContent`, `fontWeight`, `italic`, `letterSpacing`, `lineHeight`.-- Convert `letterSpacing` PERCENT units to pixels based on font size.+- Fix Figma clipboard paste: skip non-visual node types (variables, widgets, stickies, connectors)+- Fix text not rendering after paste — `letterSpacing` from Figma is a `{value, units}` object, was passed as-is → `NaN` broke CanvasKit paragraph layout+- Fix undo/redo for Figma paste — no undo entry was recorded; redo duplicated `childIds`+- Center pasted Figma content in viewport instead of using original coordinates+- Compute auto-layouts after clipboard paste (same as .fig import and demo creation)+### Improvements-- 7 new clipboard import unit tests (14 total).+- Import additional properties from Figma clipboard: `layoutAlignSelf`, `clipsContent`, `fontWeight`, `italic`, `letterSpacing`, `lineHeight`+- Convert `letterSpacing` PERCENT units to pixels based on font size-### Fixed+### Tests-- Fix Figma clipboard paste: skip non-visual node types (variables, widgets, stickies, connectors).-- Fix text not rendering after paste — `letterSpacing` from Figma is a `{value, units}` object, was passed as-is → `NaN` broke CanvasKit paragraph layout.-- Fix undo/redo for Figma paste — no undo entry was recorded; redo duplicated `childIds`.-- Center pasted Figma content in viewport instead of using original coordinates.-- Compute auto-layouts after clipboard paste (same as .fig import and demo creation).+- 7 new clipboard import unit tests (14 total)-## 0.4.1 — 2026-03-02+## [0.4.1] (2026-03-02)-### Changed+### Fixes-- Highlight copy & paste with Figma in README and feature docs.-- Replace "fig-kiwi" format name with "Kiwi binary" — the format is shared between .fig files and clipboard.+- Fix text disappearing after hover when SkPicture cache was recorded before fonts loaded+- Invalidate scene picture cache on font load to prevent stale fallback text-### Fixed+### Docs-- Fix text disappearing after hover when SkPicture cache was recorded before fonts loaded.-- Invalidate scene picture cache on font load to prevent stale fallback text.+- Highlight copy & paste with Figma in README and feature docs+- Replace "fig-kiwi" format name with "Kiwi binary" — the format is shared between .fig files and clipboard-## 0.4.0 — 2026-03-02+## [0.4.0] (2026-03-02)-### Added+### Features-- MCP server (`@open-pencil/mcp`) — 29 tools for headless .fig editing via stdio (Claude Code, Cursor, Windsurf) or HTTP (Hono + Streamable HTTP with sessions).-- `openpencil-mcp` and `openpencil-mcp-http` binaries — install globally via `bun add -g @open-pencil/mcp`.+- MCP server (`@open-pencil/mcp`) — 29 tools for headless .fig editing via stdio (Claude Code, Cursor, Windsurf) or HTTP (Hono + Streamable HTTP with sessions)+- `openpencil-mcp` and `openpencil-mcp-http` binaries — install globally via `bun add -g @open-pencil/mcp`-### Changed+### Build-- All packages emit JS via tsgo + fix-esm-import-path — `@open-pencil/core` and `@open-pencil/mcp` work on Node.js without Bun.-- Core package exports: `bun` condition → src (dev), `import` condition → dist (npm consumers).-- `@open-pencil/mcp` added to CI publish workflow.+- All packages emit JS via tsgo + fix-esm-import-path — `@open-pencil/core` and `@open-pencil/mcp` work on Node.js without Bun+- Core package exports: `bun` condition → src (dev), `import` condition → dist (npm consumers)+- `@open-pencil/mcp` added to CI publish workflow-## 0.3.2 — 2026-03-02--### Changed--- Visual regression tests for SkPicture cache: hover on/off cycle, multiple cycles, mouse hover, scene change + hover.-- Type `window.__OPEN_PENCIL_STORE__` globally, remove ad-hoc casts from tests.+## [0.3.2] (2026-03-02)### Performance-- Re-apply SkPicture scene caching for ~7x faster pan/zoom (0.98ms vs 6.8ms per frame at 500 nodes).+- Re-apply SkPicture scene caching for ~7x faster pan/zoom (0.98ms vs 6.8ms per frame at 500 nodes)-## 0.3.1 — 2026-03-02+### Tests-### Fixed+- Visual regression tests for SkPicture cache: hover on/off cycle, multiple cycles, mouse hover, scene change + hover+- Type `window.__OPEN_PENCIL_STORE__` globally, remove ad-hoc casts from tests-- Fix text disappearing after hovering a frame (revert SkPicture scene caching).-- Fix macOS startup hang: async font loading, show window on reopen.+## [0.3.1] (2026-03-02)-## 0.3.0 — 2026-03-01+### Fixes-### Fixed+- Fix text disappearing after hovering a frame (revert SkPicture scene caching)+- Fix macOS startup hang: async font loading, show window on reopen-- Fix npm publish: use pnpm for workspace dependency resolution with provenance.-- CLI version now reads from package.json instead of hardcoded value.-- Update README: accurate app size (~7 MB), streamlined feature list, current project structure.+## [0.3.0] (2026-03-01)### Performance-- SkPicture scene caching — pan/zoom replays cached display list instead of re-rendering all nodes.-- Cache vector network paths — avoid rebuilding WASM paths every frame.-- Cache ruler and pen overlay paints — eliminate 10 WASM Paint allocations per frame.-- Only enable `preserveDrawingBuffer` in test mode.-- Hoist URL param parsing out of render loop.+- SkPicture scene caching — pan/zoom replays cached display list instead of re-rendering all nodes+- Cache vector network paths — avoid rebuilding WASM paths every frame+- Cache ruler and pen overlay paints — eliminate 10 WASM Paint allocations per frame+- Only enable `preserveDrawingBuffer` in test mode+- Hoist URL param parsing out of render loop-## 0.2.1 — 2026-03-01+### Fixes-### Changed+- Fix npm publish: use pnpm for workspace dependency resolution with provenance+- CLI version now reads from package.json instead of hardcoded value+- Update README: accurate app size (~7 MB), streamlined feature list, current project structure++## [0.2.1] (2026-03-01)-- Panel header with app logo, editable document name, and sidebar toggle.-- ⌘\\ to toggle side panels for distraction-free canvas.-- Panels hidden by default on mobile (< 768px).-- Floating bar with logo, filename, and restore button when panels hidden.-- Always show local user avatar in collab header.-- Touch support for pan and pinch-zoom on iOS.+### UI++- Panel header with app logo, editable document name, and sidebar toggle+- ⌘\\ to toggle side panels for distraction-free canvas+- Panels hidden by default on mobile (< 768px)+- Floating bar with logo, filename, and restore button when panels hidden+- Always show local user avatar in collab header+- Touch support for pan and pinch-zoom on iOS### Performance-- Stubbed shiki to remove 9MB of unused language grammars (20MB → 11MB bundle).+- Stubbed shiki to remove 9MB of unused language grammars (20MB → 11MB bundle)-## 0.2.0 — 2026-03-01+## [0.2.0] (2026-03-01)-### Added+### Collaboration-- Real-time P2P collaboration via Trystero (WebRTC) + Yjs CRDT.-- Peer-to-peer sync — no server relay, zero hosting cost.-- WebRTC signaling via MQTT public brokers.-- STUN (Google, Cloudflare) + TURN (Open Relay) for NAT traversal.-- Awareness protocol: live cursors, selections, presence.-- Figma-style colored cursor arrows with name pills.-- Click peer avatar to follow their viewport, click again to stop.-- Stale cursor cleanup on peer disconnect.-- Local persistence via y-indexeddb — room survives page refresh.-- Share link at `/share/<room-id>` with vue-router.-- Secure room IDs via `crypto.getRandomValues()`.-- Removed Cloudflare Durable Object relay server (`packages/collab/`).+- Real-time P2P collaboration via Trystero (WebRTC) + Yjs CRDT+- Peer-to-peer sync — no server relay, zero hosting cost+- WebRTC signaling via MQTT public brokers+- STUN (Google, Cloudflare) + TURN (Open Relay) for NAT traversal+- Awareness protocol: live cursors, selections, presence+- Figma-style colored cursor arrows with name pills+- Click peer avatar to follow their viewport, click again to stop+- Stale cursor cleanup on peer disconnect+- Local persistence via y-indexeddb — room survives page refresh+- Share link at `/share/<room-id>` with vue-router+- Secure room IDs via `crypto.getRandomValues()`+- Removed Cloudflare Durable Object relay server (`packages/collab/`)-### Changed+### UI-- Toast notifications via Reka UI Toast — top-center blue pill for info, red for errors.-- Global error handler (window.error + unhandledrejection) shows errors as toasts.-- Link copied toast on share and copy link actions.-- HsvColorArea extracted as shared component (ColorPicker + FillPicker).-- Scrollable app menu without visible scrollbar.-- Selection broadcasting to remote peers.+- Toast notifications via Reka UI Toast — top-center blue pill for info, red for errors+- Global error handler (window.error + unhandledrejection) shows errors as toasts+- Link copied toast on share and copy link actions+- HsvColorArea extracted as shared component (ColorPicker + FillPicker)+- Scrollable app menu without visible scrollbar+- Selection broadcasting to remote peers-## 0.1.0-alpha — 2026-03-01+## [0.1.0-alpha] (2026-03-01)First public alpha. The editor is functional but not production-ready.-### Added--- Canvas rendering via CanvasKit (Skia WASM) on WebGL surface.-- Rectangle, Ellipse, Line, Polygon, Star drawing tools.-- Pen tool with vector network model (bezier curves, open/closed paths).-- Inline text editing on canvas with phantom textarea for input/IME.-- Rich text formatting: bold, italic, underline per-character via style runs.-- Font picker with system font enumeration (font-kit on desktop, Local Font Access API in browser).-- Auto-layout via Yoga WASM (direction, gap, padding, justify, align, child sizing).-- Components, instances, component sets with live sync and override preservation.-- Variables with collections, modes, color bindings, alias chains.-- Undo/redo for all operations (inverse-command pattern).-- Snap guides with rotation-aware edge/center snapping.-- Canvas rulers with selection range badges.-- Marquee selection, multi-select, resize handles, rotation.-- Group/ungroup, z-order, visibility, lock.-- Sections with title pills and auto-adoption of overlapping nodes.-- Multi-page documents with independent viewport state.-- Hover highlight following node geometry (ellipses, rounded rects, vectors).-- Context menu with clipboard, z-order, grouping, component, and visibility actions.-- Color picker with HSV, gradients (linear, radial, angular, diamond), image fills.-- Properties panel: position, appearance, fill, stroke, effects, typography, layout, export.-- ScrubInput drag-to-change number controls.-- Resizable side panels via reka-ui Splitter.---- .fig file import via Kiwi binary codec (194 definitions, ~390 fields).-- .fig file export with Kiwi encoding, Zstd compression, thumbnail generation.-- Figma clipboard: copy/paste between OpenPencil and Figma.-- Round-trip fidelity for supported node types.---- Built-in AI chat in properties panel (⌘J).-- Direct browser → OpenRouter communication, no backend.-- Model selector: Claude, Gemini, GPT, DeepSeek, Qwen, Kimi, Llama.-- 10 AI tools: create_shape, set_fill, set_stroke, update_node, set_layout, delete_node, select_nodes, get_page_tree, get_selection, rename_node.-- Streaming markdown responses (vue-stream-markdown).-- Tool call timeline with collapsible details.---- JSX export of selected nodes with Tailwind-like shorthand props.-- Syntax highlighting via Prism.js.-- Copy to clipboard.---- `info` — document stats, node types, fonts.-- `tree` — visual node tree.-- `find` — search by name/type.-- `export` — render to PNG/JPG/WEBP at any scale.-- `node` — detailed properties by ID.-- `pages` — list pages with node counts.-- `variables` — list design variables and collections.-- `eval` — run scripts with Figma-compatible plugin API.-- `analyze colors` — color palette usage.-- `analyze typography` — font/size/weight distribution.-- `analyze spacing` — gap/padding values.-- `analyze clusters` — repeated patterns.-- All commands support `--json`.---- Scene graph with flat Map storage and parentIndex tree.-- FigmaAPI with ~65% Figma plugin API compatibility.-- JSX renderer (TreeNode builder functions with shorthand props).-- Kiwi binary codec (encode/decode).-- Vector network blob encoder/decoder.---- Tauri v2 (~5 MB).-- Native menu bar, save/open dialogs.-- System font enumeration via font-kit.-- Zstd compression in Rust.-- macOS and Windows builds via GitHub Actions.---- Runs at [app.openpencil.dev](https://app.openpencil.dev).-- No installation required.-- File System Access API for save/open (Chrome/Edge), download fallback elsewhere.---- [openpencil.dev](https://openpencil.dev) — VitePress site with user guide, reference, and development docs.-- Deployed via Cloudflare Pages.+### Editor++- Canvas rendering via CanvasKit (Skia WASM) on WebGL surface+- Rectangle, Ellipse, Line, Polygon, Star drawing tools+- Pen tool with vector network model (bezier curves, open/closed paths)+- Inline text editing on canvas with phantom textarea for input/IME+- Rich text formatting: bold, italic, underline per-character via style runs+- Font picker with system font enumeration (font-kit on desktop, Local Font Access API in browser)+- Auto-layout via Yoga WASM (direction, gap, padding, justify, align, child sizing)+- Components, instances, component sets with live sync and override preservation+- Variables with collections, modes, color bindings, alias chains+- Undo/redo for all operations (inverse-command pattern)+- Snap guides with rotation-aware edge/center snapping+- Canvas rulers with selection range badges+- Marquee selection, multi-select, resize handles, rotation+- Group/ungroup, z-order, visibility, lock+- Sections with title pills and auto-adoption of overlapping nodes+- Multi-page documents with independent viewport state+- Hover highlight following node geometry (ellipses, rounded rects, vectors)+- Context menu with clipboard, z-order, grouping, component, and visibility actions+- Color picker with HSV, gradients (linear, radial, angular, diamond), image fills+- Properties panel: position, appearance, fill, stroke, effects, typography, layout, export+- ScrubInput drag-to-change number controls+- Resizable side panels via reka-ui Splitter++### File Format++- .fig file import via Kiwi binary codec (194 definitions, ~390 fields)+- .fig file export with Kiwi encoding, Zstd compression, thumbnail generation+- Figma clipboard: copy/paste between OpenPencil and Figma+- Round-trip fidelity for supported node types++### AI Integration++- Built-in AI chat in properties panel (⌘J)+- Direct browser → OpenRouter communication, no backend+- Model selector: Claude, Gemini, GPT, DeepSeek, Qwen, Kimi, Llama+- 10 AI tools: create_shape, set_fill, set_stroke, update_node, set_layout, delete_node, select_nodes, get_page_tree, get_selection, rename_node+- Streaming markdown responses (vue-stream-markdown)+- Tool call timeline with collapsible details++### Code Panel++- JSX export of selected nodes with Tailwind-like shorthand props+- Syntax highlighting via Prism.js+- Copy to clipboard++### CLI (`@open-pencil/cli`)++- `info` — document stats, node types, fonts+- `tree` — visual node tree+- `find` — search by name/type+- `export` — render to PNG/JPG/WEBP at any scale+- `node` — detailed properties by ID+- `pages` — list pages with node counts+- `variables` — list design variables and collections+- `eval` — run scripts with Figma-compatible plugin API+- `analyze colors` — color palette usage+- `analyze typography` — font/size/weight distribution+- `analyze spacing` — gap/padding values+- `analyze clusters` — repeated patterns+- All commands support `--json`++### Core (`@open-pencil/core`)++- Scene graph with flat Map storage and parentIndex tree+- FigmaAPI with ~65% Figma plugin API compatibility+- JSX renderer (TreeNode builder functions with shorthand props)+- Kiwi binary codec (encode/decode)+- Vector network blob encoder/decoder++### Desktop App++- Tauri v2 (~5 MB)+- Native menu bar, save/open dialogs+- System font enumeration via font-kit+- Zstd compression in Rust+- macOS and Windows builds via GitHub Actions++### Web App++- Runs at [app.openpencil.dev](https://app.openpencil.dev)+- No installation required+- File System Access API for save/open (Chrome/Edge), download fallback elsewhere++### Documentation++- [openpencil.dev](https://openpencil.dev) — VitePress site with user guide, reference, and development docs+- Deployed via Cloudflare Pagesdiff --git a/packages/cli/package.json b/packages/cli/package.jsonindex 6ef731530..209da63f3 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -9,6 +9,14 @@"bin": {"openpencil": "./bin/openpencil.js"},+ "exports": {+ "./library": {+ "types": "./dist/library/index.d.mts",+ "bun": "./src/library/index.ts",+ "import": "./dist/library/index.mjs",+ "default": "./dist/library/index.mjs"+ }+ },"files": ["bin","dist"diff --git a/packages/cli/src/commands/libraries.ts b/packages/cli/src/commands/libraries.tsnew file mode 100644index 000000000..abf7fb726--- /dev/null+++ b/packages/cli/src/commands/libraries.ts@@ -0,0 +1,73 @@+import { resolve } from 'node:path'++import { defineCommand } from 'citty'++import { bold, fmtList, ok } from '#cli/format'+import { loadDocument, populateWholeDocument } from '#cli/headless'+import { FileSystemLibraryCatalog } from '#cli/library/catalog'++const list = defineCommand({+ meta: { description: 'List component libraries in a filesystem catalog' },+ args: {+ root: { type: 'string', description: 'Library catalog directory', required: true },+ json: { type: 'boolean', description: 'Output as JSON' }+ },+ async run({ args }) {+ const libraries = await new FileSystemLibraryCatalog(args.root).listLibraries()+ if (args.json) {+ console.log(JSON.stringify(libraries, null, 2))+ return+ }+ console.log('')+ console.log(bold(` ${libraries.length} component libraries`))+ console.log('')+ console.log(+ fmtList(+ libraries.map((library) => ({+ header: `${library.name} (${library.libraryId})`,+ details: {+ revision: library.latestRevisionId,+ assets: library.assetCount,+ published: library.publishedAt+ }+ })),+ { compact: true }+ )+ )+ console.log('')+ }+})++const publish = defineCommand({+ meta: { description: 'Publish a document as a component library revision' },+ args: {+ file: { type: 'positional', description: 'Source .fig file', required: true },+ root: { type: 'string', description: 'Library catalog directory', required: true },+ id: { type: 'string', description: 'Stable library ID', required: true },+ name: { type: 'string', description: 'Library name', required: true },+ description: { type: 'string', description: 'Revision description' },+ previous: { type: 'string', description: 'Expected previous revision ID' },+ json: { type: 'boolean', description: 'Output as JSON' }+ },+ async run({ args }) {+ const graph = await loadDocument(resolve(args.file))+ populateWholeDocument(graph)+ const revision = await new FileSystemLibraryCatalog(args.root).publishRevision({+ libraryId: args.id,+ name: args.name,+ graph,+ description: args.description,+ previousRevisionId: args.previous || null+ })+ if (args.json) {+ console.log(JSON.stringify(revision.manifest, null, 2))+ return+ }+ console.log(ok(`Published ${revision.manifest.name} @ ${revision.manifest.revisionId}`))+ }+})++export default defineCommand({+ meta: { description: 'Manage component library catalogs' },+ subCommands: { list, publish }+})diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex a960f1c8e..15e0d5314 100755--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -10,6 +10,7 @@ import find from './commands/find'import formats from './commands/formats'import importCmd from './commands/import'import info from './commands/info'+import libraries from './commands/libraries'import lint from './commands/lint'import node from './commands/node'import pages from './commands/pages'@@ -37,6 +38,7 @@ const main = defineCommand({formats,info,lint,+ libraries,query,node,pages,diff --git a/packages/cli/src/library/catalog.ts b/packages/cli/src/library/catalog.tsnew file mode 100644index 000000000..a044d8456--- /dev/null+++ b/packages/cli/src/library/catalog.ts@@ -0,0 +1,121 @@+import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'+import { dirname, resolve, sep } from 'node:path'++import type {+ ComponentLibraryRevision,+ LibraryCatalog,+ LibrarySummary,+ PublishLibraryInput,+ SerializedComponentLibraryRevision,+ StoredLibraryLatestManifest+} from '@open-pencil/core/library'+import {+ createLibraryRevision,+ deserializeLibraryRevision,+ serializeLibraryRevision+} from '@open-pencil/core/library'++const catalogPublicationQueues = new Map<string, Promise<void>>()++async function serializePublication<T>(root: string, operation: () => Promise<T>): Promise<T> {+ const previous = catalogPublicationQueues.get(root) ?? Promise.resolve()+ let release: (() => void) | undefined+ const current = new Promise<void>((resolveQueue) => {+ release = resolveQueue+ })+ const tail = previous.then(() => current)+ catalogPublicationQueues.set(root, tail)+ await previous+ try {+ return await operation()+ } finally {+ release?.()+ if (catalogPublicationQueues.get(root) === tail) catalogPublicationQueues.delete(root)+ }+}++export class FileSystemLibraryCatalog implements LibraryCatalog {+ readonly #root: string++ constructor(root: string) {+ this.#root = resolve(root)+ }++ async listLibraries(): Promise<LibrarySummary[]> {+ try {+ return await this.#readJSON<LibrarySummary[]>('libraries.json')+ } catch (error) {+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return []+ throw error+ }+ }++ async getRevision(libraryId: string, revisionId?: string): Promise<ComponentLibraryRevision> {+ const resolvedRevisionId =+ revisionId ??+ (await this.#readJSON<StoredLibraryLatestManifest>(`${libraryId}/manifest.json`)).summary+ .latestRevisionId+ const data = await this.#readJSON<SerializedComponentLibraryRevision>(+ `${libraryId}/revisions/${resolvedRevisionId}.json`+ )+ return deserializeLibraryRevision(data)+ }++ async publishRevision(input: PublishLibraryInput): Promise<ComponentLibraryRevision> {+ return serializePublication(this.#root, async () => {+ const current = (await this.listLibraries()).find(+ (item) => item.libraryId === input.libraryId+ )+ if ((input.previousRevisionId ?? null) !== (current?.latestRevisionId ?? null)) {+ throw new Error('Library revision conflict: latest revision has changed')+ }+ const revision = await createLibraryRevision(input)+ const manifest = revision.manifest+ await this.#writeJSON(+ `${manifest.libraryId}/revisions/${manifest.revisionId}.json`,+ serializeLibraryRevision(revision)+ )+ const summary: LibrarySummary = {+ libraryId: manifest.libraryId,+ name: manifest.name,+ latestRevisionId: manifest.revisionId,+ publishedAt: manifest.publishedAt,+ assetCount: manifest.assets.length+ }+ await this.#writeJSON(`${manifest.libraryId}/manifest.json`, {+ schemaVersion: 1,+ summary+ } satisfies StoredLibraryLatestManifest)+ const summaries = (await this.listLibraries()).filter(+ (item) => item.libraryId !== input.libraryId+ )+ summaries.push(summary)+ await this.#writeJSON(+ 'libraries.json',+ summaries.sort((left, right) => left.name.localeCompare(right.name))+ )+ return revision+ })+ }++ #path(relative: string): string {+ if (relative.split(/[\\/]/).some((segment) => segment === '..'))+ throw new Error('Invalid catalog path')+ const path = resolve(this.#root, relative)+ if (path !== this.#root && !path.startsWith(`${this.#root}${sep}`))+ throw new Error('Invalid catalog path')+ return path+ }++ async #readJSON<T>(relative: string): Promise<T> {+ return JSON.parse(await readFile(this.#path(relative), 'utf8')) as T+ }++ async #writeJSON(relative: string, value: unknown): Promise<void> {+ const path = this.#path(relative)+ const temporaryPath = `${path}.${crypto.randomUUID()}.tmp`+ await mkdir(dirname(path), { recursive: true })+ await writeFile(temporaryPath, JSON.stringify(value, null, 2))+ await rename(temporaryPath, path)+ }+}diff --git a/packages/cli/src/library/index.ts b/packages/cli/src/library/index.tsnew file mode 100644index 000000000..dfcfbb73b--- /dev/null+++ b/packages/cli/src/library/index.ts@@ -0,0 +1 @@+export { FileSystemLibraryCatalog } from './catalog'diff --git a/packages/cli/tests/library-catalog.test.ts b/packages/cli/tests/library-catalog.test.tsnew file mode 100644index 000000000..167a8359a--- /dev/null+++ b/packages/cli/tests/library-catalog.test.ts@@ -0,0 +1,56 @@+import { describe, expect, test } from 'bun:test'+import { mkdtemp, readFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { SceneGraph } from '@open-pencil/scene-graph'++import { FileSystemLibraryCatalog } from '@open-pencil/cli/library'++describe('filesystem library catalog', () => {+ test('publishes and restores revisions under a bounded root', async () => {+ const root = await mkdtemp(join(tmpdir(), 'open-pencil-libraries-'))+ const graph = new SceneGraph()+ graph.createNode('COMPONENT', graph.getPages()[0].id, {+ name: 'Button',+ componentKey: 'button'+ })+ const catalog = new FileSystemLibraryCatalog(root)+ const revision = await catalog.publishRevision({+ libraryId: 'design-system',+ name: 'Design system',+ graph,+ publishedAt: '2026-01-01T00:00:00.000Z'+ })+ expect(await catalog.listLibraries()).toMatchObject([{ libraryId: 'design-system' }])+ expect((await catalog.getRevision('design-system')).manifest).toEqual(revision.manifest)+ expect(JSON.parse(await readFile(join(root, 'libraries.json'), 'utf8'))).toHaveLength(1)+ })++ test('rejects traversal and preserves malformed indexes', async () => {+ const root = await mkdtemp(join(tmpdir(), 'open-pencil-libraries-'))+ const catalog = new FileSystemLibraryCatalog(root)+ await expect(catalog.getRevision('../outside')).rejects.toThrow('Invalid catalog path')+ await Bun.write(join(root, 'libraries.json'), '{invalid')+ await expect(catalog.listLibraries()).rejects.toBeInstanceOf(SyntaxError)+ })++ test('serializes concurrent publishers and keeps a valid index', async () => {+ const root = await mkdtemp(join(tmpdir(), 'open-pencil-libraries-'))+ const graph = new SceneGraph()+ graph.createNode('COMPONENT', graph.getPages()[0].id, {+ name: 'Button',+ componentKey: 'button'+ })+ const first = new FileSystemLibraryCatalog(root)+ const second = new FileSystemLibraryCatalog(root)+ const results = await Promise.allSettled([+ first.publishRevision({ libraryId: 'design-system', name: 'First', graph }),+ second.publishRevision({ libraryId: 'design-system', name: 'Second', graph })+ ])+ expect(results.filter((result) => result.status === 'fulfilled')).toHaveLength(1)+ expect(results.filter((result) => result.status === 'rejected')).toHaveLength(1)+ expect(await first.listLibraries()).toHaveLength(1)+ expect((await first.getRevision('design-system')).manifest.name).toBe('First')+ })+})diff --git a/packages/cli/tsdown.config.ts b/packages/cli/tsdown.config.tsindex 3eec91132..9d7105bf4 100644--- a/packages/cli/tsdown.config.ts+++ b/packages/cli/tsdown.config.ts@@ -2,7 +2,8 @@ import { defineConfig } from 'tsdown'export default defineConfig({entry: {- index: './src/index.ts'+ index: './src/index.ts',+ 'library/index': './src/library/index.ts'},platform: 'node',format: ['esm'],diff --git a/packages/core/package.json b/packages/core/package.jsonindex e5b81f2ca..3093ffc0b 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -85,6 +85,12 @@"import": "./dist/rpc/index.js","default": "./dist/rpc/index.js"},+ "./library": {+ "bun": "./src/library/index.ts",+ "types": "./dist/library/index.d.ts",+ "import": "./dist/library/index.js",+ "default": "./dist/library/index.js"+ },"./lint": {"types": "./dist/lint/index.d.ts","import": "./dist/lint/index.js",diff --git a/packages/core/src/editor/bridges/components.ts b/packages/core/src/editor/bridges/components.tsindex 78ffb0692..329b7d560 100644--- a/packages/core/src/editor/bridges/components.ts+++ b/packages/core/src/editor/bridges/components.ts@@ -35,11 +35,20 @@ export function createComponentBridge(addPropertyDefinition: components.addPropertyDefinition,removePropertyDefinition: components.removePropertyDefinition,renamePropertyDefinition: components.renamePropertyDefinition,+ reorderPropertyDefinitions: components.reorderPropertyDefinitions,+ renameVariantValue: components.renameVariantValue,+ reorderVariantValues: components.reorderVariantValues,+ setVariantPropertyValue: components.setVariantPropertyValue,collectVariantOptions: components.collectVariantOptions,findVariantByValues: components.findVariantByValues,getDefaultVariantForComponentSet: components.getDefaultVariantForComponentSet,getComponentSetVariantConflicts: components.getComponentSetVariantConflicts,+ validateComponentSet: components.validateComponentSet,+ getVariantOptionAvailability: components.getVariantOptionAvailability,switchInstanceVariant: components.switchInstanceVariant,+ addVariant: components.addVariant,+ duplicateVariant: components.duplicateVariant,+ removeVariant: components.removeVariant,getInstanceComponentPropertyDefinitions: components.getInstanceComponentPropertyDefinitions,getInstanceComponentPropertyValue: components.getInstanceComponentPropertyValue,setInstanceComponentProperty: components.setInstanceComponentPropertydiff --git a/packages/core/src/editor/capabilities.ts b/packages/core/src/editor/capabilities.tsnew file mode 100644index 000000000..e5b7f330f--- /dev/null+++ b/packages/core/src/editor/capabilities.ts@@ -0,0 +1,51 @@+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'++export type NodeEditCapability =+ | { editable: true }+ | {+ editable: false+ reason: 'library-definition'+ libraryId: string+ assetKey: string+ }++export class ReadOnlyLibraryDefinitionError extends Error {+ readonly libraryId: string+ readonly assetKey: string++ constructor(libraryId: string, assetKey: string) {+ super(`This component belongs to library ${libraryId}. Edit the source library to change it.`)+ this.name = 'ReadOnlyLibraryDefinitionError'+ this.libraryId = libraryId+ this.assetKey = assetKey+ }+}++function libraryDefinitionOwner(graph: SceneGraph, nodeId: string): SceneNode | undefined {+ let node = graph.getNode(nodeId)+ while (node) {+ if (node.librarySource?.readOnly) return node+ node = node.parentId ? graph.getNode(node.parentId) : undefined+ }+ return undefined+}++export function getNodeEditCapability(graph: SceneGraph, nodeId: string): NodeEditCapability {+ const owner = libraryDefinitionOwner(graph, nodeId)+ const identity = owner?.librarySource?.identity+ return identity+ ? {+ editable: false,+ reason: 'library-definition',+ libraryId: identity.libraryId,+ assetKey: identity.assetKey+ }+ : { editable: true }+}++export function assertNodeEditable(graph: SceneGraph, nodeId: string): void {+ const capability = getNodeEditCapability(graph, nodeId)+ if (!capability.editable) {+ throw new ReadOnlyLibraryDefinitionError(capability.libraryId, capability.assetKey)+ }+}diff --git a/packages/core/src/editor/clipboard/paste-replace.ts b/packages/core/src/editor/clipboard/paste-replace.tsindex ce712085e..a3d033db5 100644--- a/packages/core/src/editor/clipboard/paste-replace.ts+++ b/packages/core/src/editor/clipboard/paste-replace.ts@@ -1,6 +1,7 @@import type { SceneNode } from '@open-pencil/scene-graph'import { computeAbsoluteBounds } from '@open-pencil/scene-graph/geometry'+import { getNodeEditCapability } from '#core/editor/capabilities'import type { EditorContext } from '#core/editor/types'import { computeAllLayouts } from '#core/layout'@@ -12,7 +13,10 @@ type CenterNodesAt = (nodeIds: string[], cx: number, cy: number) => voidexport function selectedReplacementTargets(ctx: EditorContext) {const selected = [...ctx.state.selectedIds].map((id) => ctx.graph.getNode(id))- .filter((node): node is SceneNode => node != null && !node.locked)+ .filter(+ (node): node is SceneNode =>+ node != null && !node.locked && getNodeEditCapability(ctx.graph, node.id).editable+ )const selectedSet = new Set(selected.map((node) => node.id))return selected.filter((node) => !node.parentId || !selectedSet.has(node.parentId))}diff --git a/packages/core/src/editor/components/properties.ts b/packages/core/src/editor/components/properties.tsindex bcc43e04f..af7301ab2 100644--- a/packages/core/src/editor/components/properties.ts+++ b/packages/core/src/editor/components/properties.ts@@ -4,6 +4,7 @@ import type {SceneNode} from '@open-pencil/scene-graph'+import { assertNodeEditable } from '#core/editor/capabilities'import type { EditorContext } from '#core/editor/types'interface PropertyTarget {@@ -12,7 +13,7 @@ interface PropertyTarget {source: SceneNode}-function definitionOwners(ctx: EditorContext, instance: SceneNode): SceneNode[] {+function definitionOwners(ctx: Pick<EditorContext, 'graph'>, instance: SceneNode): SceneNode[] {if (!instance.componentId) return []const component = ctx.graph.getNode(instance.componentId)if (!component) return []@@ -21,7 +22,7 @@ function definitionOwners(ctx: EditorContext, instance: SceneNode): SceneNode[]}function definitionsForInstance(- ctx: EditorContext,+ ctx: Pick<EditorContext, 'graph'>,instance: SceneNode): ComponentPropertyDefinition[] {const byId = new Map<string, ComponentPropertyDefinition>()@@ -34,7 +35,7 @@ function definitionsForInstance(}function findPropertyPath(- ctx: EditorContext,+ ctx: Pick<EditorContext, 'graph'>,sourceParent: SceneNode,propertyId: string,path: number[] = []@@ -50,7 +51,11 @@ function findPropertyPath(return null}-function nodeAtPath(ctx: EditorContext, root: SceneNode, path: number[]): SceneNode | null {+function nodeAtPath(+ ctx: Pick<EditorContext, 'graph'>,+ root: SceneNode,+ path: number[]+): SceneNode | null {let node = rootfor (const index of path) {const childId = node.childIds[index]@@ -62,7 +67,7 @@ function nodeAtPath(ctx: EditorContext, root: SceneNode, path: number[]): SceneN}function propertyTarget(- ctx: EditorContext,+ ctx: Pick<EditorContext, 'graph'>,instance: SceneNode,propertyId: string): PropertyTarget | null {@@ -74,7 +79,7 @@ function propertyTarget(return node ? { node, field: match.field, source: match.source } : null}-function swapTargetId(ctx: EditorContext, value: string): string | null {+function swapTargetId(ctx: Pick<EditorContext, 'graph'>, value: string): string | null {const direct = ctx.graph.getNode(value)if (direct?.type === 'COMPONENT') return direct.idfor (const node of ctx.graph.getAllNodes()) {@@ -98,7 +103,7 @@ function targetValue(target: PropertyTarget | null): string {}function propertyOverrides(- ctx: EditorContext,+ ctx: Pick<EditorContext, 'graph'>,instance: SceneNode,target: PropertyTarget | null,value: string,@@ -117,7 +122,7 @@ function propertyOverrides(}function updatePropertyTarget(- ctx: EditorContext,+ ctx: Pick<EditorContext, 'graph'>,target: PropertyTarget | null,value: string,swapComponentId: string | null@@ -136,7 +141,7 @@ function updatePropertyTarget(}function applyPropertyValue(- ctx: EditorContext,+ ctx: Pick<EditorContext, 'graph'>,instanceId: string,definition: ComponentPropertyDefinition,value: string@@ -155,7 +160,10 @@ function applyPropertyValue(updatePropertyTarget(ctx, target, value, swapComponentId)}-export function reapplyInstanceComponentProperties(ctx: EditorContext, instanceId: string): void {+export function reapplyInstanceComponentProperties(+ ctx: Pick<EditorContext, 'graph'>,+ instanceId: string+): void {const instance = ctx.graph.getNode(instanceId)if (instance?.type !== 'INSTANCE') returnconst definitions = new Map(@@ -195,6 +203,7 @@ export function createComponentPropertyActions(function setInstanceComponentProperty(instanceId: string, propertyId: string, value: string) {const instance = ctx.graph.getNode(instanceId)if (instance?.type !== 'INSTANCE') return+ assertNodeEditable(ctx.graph, instanceId)const definition = definitionsForInstance(ctx, instance).find((item) => item.id === propertyId)if (!definition) returnif (definition.type === 'VARIANT') {diff --git a/packages/core/src/editor/components/variants.ts b/packages/core/src/editor/components/variants.tsdeleted file mode 100644index 889f4c29d..000000000--- a/packages/core/src/editor/components/variants.ts+++ /dev/null@@ -1,277 +0,0 @@-import { omit } from 'es-toolkit/object'--import type {- ComponentPropertyDefinition,- ComponentPropertyType,- SceneNode-} from '@open-pencil/scene-graph'-import { buildVariantName, parseVariantName } from '@open-pencil/scene-graph/variant-name'--import { reapplyInstanceComponentProperties } from '#core/editor/components/properties'-import type { EditorContext } from '#core/editor/types'-import { randomHex } from '#core/random'--export type VariantConflict = {- values: Record<string, string>- componentIds: string[]-}--function sortByCanvasPosition(a: SceneNode, b: SceneNode) {- return a.y - b.y || a.x - b.x || a.name.localeCompare(b.name)-}--export function createVariantActions(ctx: EditorContext) {- function getComponentSetPropertyDefs(componentSetId: string): ComponentPropertyDefinition[] {- const node = ctx.graph.getNode(componentSetId)- if (node?.type !== 'COMPONENT_SET') return []- return node.componentPropertyDefinitions- }-- function addPropertyDefinition(- componentSetId: string,- name: string,- type: ComponentPropertyType = 'VARIANT',- defaultValue = ''- ): string | undefined {- const node = ctx.graph.getNode(componentSetId)- if (node?.type !== 'COMPONENT_SET') return undefined- const id = `prop:${randomHex(8)}`- const def: ComponentPropertyDefinition = {- id,- name,- type,- defaultValue,- variantOptions: type === 'VARIANT' ? [defaultValue] : undefined- }- const prevDefs = [...node.componentPropertyDefinitions]- ctx.graph.updateNode(componentSetId, {- componentPropertyDefinitions: [...prevDefs, def]- })- ctx.undo.push({- label: 'Add property',- forward: () => {- const n = ctx.graph.getNode(componentSetId)- if (n) {- ctx.graph.updateNode(componentSetId, {- componentPropertyDefinitions: [...n.componentPropertyDefinitions, def]- })- }- ctx.requestRender()- },- inverse: () => {- ctx.graph.updateNode(componentSetId, {- componentPropertyDefinitions: prevDefs- })- ctx.requestRender()- }- })- ctx.requestRender()- return id- }-- function removePropertyDefinition(componentSetId: string, propertyId: string) {- const node = ctx.graph.getNode(componentSetId)- if (node?.type !== 'COMPONENT_SET') return- const prevDefs = [...node.componentPropertyDefinitions]- const def = prevDefs.find((d) => d.id === propertyId)- if (!def) return- ctx.graph.updateNode(componentSetId, {- componentPropertyDefinitions: prevDefs.filter((d) => d.id !== propertyId)- })- for (const childId of node.childIds) {- const child = ctx.graph.getNode(childId)- if (!child) continue- const values = omit(child.componentPropertyValues, [def.name])- ctx.graph.updateNode(childId, { componentPropertyValues: values })- }- ctx.undo.push({- label: 'Remove property',- forward: () => {- const n = ctx.graph.getNode(componentSetId)- if (n) {- ctx.graph.updateNode(componentSetId, {- componentPropertyDefinitions: n.componentPropertyDefinitions.filter(- (d) => d.id !== propertyId- )- })- for (const cid of n.childIds) {- const c = ctx.graph.getNode(cid)- if (!c) continue- const v = omit(c.componentPropertyValues, [def.name])- ctx.graph.updateNode(cid, { componentPropertyValues: v })- }- }- ctx.requestRender()- },- inverse: () => {- ctx.graph.updateNode(componentSetId, {- componentPropertyDefinitions: prevDefs- })- ctx.requestRender()- }- })- ctx.requestRender()- }-- function renamePropertyDefinition(componentSetId: string, propertyId: string, newName: string) {- const node = ctx.graph.getNode(componentSetId)- if (node?.type !== 'COMPONENT_SET') return- const def = node.componentPropertyDefinitions.find((d) => d.id === propertyId)- if (!def) return- const prevName = def.name- const newDefs = node.componentPropertyDefinitions.map((d) =>- d.id === propertyId ? { ...d, name: newName } : d- )- ctx.graph.updateNode(componentSetId, { componentPropertyDefinitions: newDefs })- for (const childId of node.childIds) {- const child = ctx.graph.getNode(childId)- if (!child) continue- const values = { ...child.componentPropertyValues }- if (prevName in values) {- const nextValues: Record<string, string> = omit(values, [prevName])- nextValues[newName] = values[prevName]- ctx.graph.updateNode(childId, { componentPropertyValues: nextValues })- }- }- const renamePropertyDef = (name: string) => {- const n = ctx.graph.getNode(componentSetId)- if (!n) return- ctx.graph.updateNode(componentSetId, {- componentPropertyDefinitions: n.componentPropertyDefinitions.map((d) =>- d.id === propertyId ? { ...d, name } : d- )- })- ctx.requestRender()- }- ctx.undo.push({- label: 'Rename property',- forward: () => renamePropertyDef(newName),- inverse: () => renamePropertyDef(prevName)- })- ctx.requestRender()- }-- function collectVariantOptions(componentSetId: string): Map<string, Set<string>> {- const node = ctx.graph.getNode(componentSetId)- if (node?.type !== 'COMPONENT_SET') return new Map()- const options = new Map<string, Set<string>>()- for (const childId of node.childIds) {- const child = ctx.graph.getNode(childId)- if (child?.type !== 'COMPONENT') continue- for (const [key, value] of Object.entries(child.componentPropertyValues)) {- const set = options.get(key) ?? new Set()- set.add(value)- options.set(key, set)- }- }- return options- }-- function getComponentSetVariants(componentSetId: string): SceneNode[] {- const node = ctx.graph.getNode(componentSetId)- if (node?.type !== 'COMPONENT_SET') return []- return node.childIds- .map((id) => ctx.graph.getNode(id))- .filter((child): child is SceneNode => child?.type === 'COMPONENT')- }-- function findVariantByValues(- componentSetId: string,- values: Record<string, string>- ): SceneNode | undefined {- for (const child of getComponentSetVariants(componentSetId).sort(sortByCanvasPosition)) {- const childValues = child.componentPropertyValues- const matches = Object.entries(values).every(([k, v]) => childValues[k] === v)- if (matches) return child- }- return undefined- }-- function getDefaultVariantForComponentSet(componentSetId: string): SceneNode | undefined {- const node = ctx.graph.getNode(componentSetId)- if (node?.type !== 'COMPONENT_SET') return undefined-- const defaultValues = Object.fromEntries(- node.componentPropertyDefinitions- .filter((def) => def.type === 'VARIANT' && def.defaultValue)- .map((def) => [def.name, def.defaultValue])- )- if (Object.keys(defaultValues).length > 0) {- const explicitDefault = findVariantByValues(componentSetId, defaultValues)- if (explicitDefault) return explicitDefault- }-- return getComponentSetVariants(componentSetId).sort(sortByCanvasPosition)[0]- }-- function getComponentSetVariantConflicts(componentSetId: string): VariantConflict[] {- const node = ctx.graph.getNode(componentSetId)- if (node?.type !== 'COMPONENT_SET') return []-- const propNames = node.componentPropertyDefinitions- .filter((def) => def.type === 'VARIANT')- .map((def) => def.name)- const byKey = new Map<string, { values: Record<string, string>; componentIds: string[] }>()-- for (const variant of getComponentSetVariants(componentSetId)) {- const values = Object.fromEntries(- propNames.map((name) => [name, variant.componentPropertyValues[name] ?? ''])- )- const key = propNames.map((name) => `${name}=${values[name]}`).join('\u0000')- const entry = byKey.get(key) ?? { values, componentIds: [] }- entry.componentIds.push(variant.id)- byKey.set(key, entry)- }-- return [...byKey.values()].filter((entry) => entry.componentIds.length > 1)- }-- function switchInstanceVariant(instanceId: string, propertyName: string, newValue: string) {- const instance = ctx.graph.getNode(instanceId)- if (instance?.type !== 'INSTANCE' || !instance.componentId) return-- const component = ctx.graph.getNode(instance.componentId)- if (!component) return- const componentSetId = component.parentId- if (!componentSetId) return- const componentSet = ctx.graph.getNode(componentSetId)- if (componentSet?.type !== 'COMPONENT_SET') return-- const currentValues = { ...component.componentPropertyValues }- currentValues[propertyName] = newValue- const target = findVariantByValues(componentSetId, currentValues)- if (!target || target.id === instance.componentId) return-- const prevComponentId = instance.componentId- ctx.graph.swapInstanceComponent(instanceId, target.id)- reapplyInstanceComponentProperties(ctx, instanceId)- ctx.undo.push({- label: 'Switch variant',- forward: () => {- ctx.graph.swapInstanceComponent(instanceId, target.id)- reapplyInstanceComponentProperties(ctx, instanceId)- ctx.requestRender()- },- inverse: () => {- ctx.graph.swapInstanceComponent(instanceId, prevComponentId)- reapplyInstanceComponentProperties(ctx, instanceId)- ctx.requestRender()- }- })- ctx.requestRender()- }-- return {- getComponentSetPropertyDefs,- addPropertyDefinition,- removePropertyDefinition,- renamePropertyDefinition,- parseVariantName,- buildVariantName,- collectVariantOptions,- findVariantByValues,- getDefaultVariantForComponentSet,- getComponentSetVariantConflicts,- switchInstanceVariant- }-}diff --git a/packages/core/src/editor/components/variants/index.ts b/packages/core/src/editor/components/variants/index.tsnew file mode 100644index 000000000..0023af140--- /dev/null+++ b/packages/core/src/editor/components/variants/index.ts@@ -0,0 +1,704 @@+import { omit } from 'es-toolkit/object'++import type {+ ComponentPropertyDefinition,+ ComponentPropertyType,+ SceneNode+} from '@open-pencil/scene-graph'+import { buildVariantName, parseVariantName } from '@open-pencil/scene-graph/variant-name'++import { assertNodeEditable } from '#core/editor/capabilities'+import { restoreSubtree, snapshotSubtree } from '#core/editor/clipboard/subtree-history'+import { reapplyInstanceComponentProperties } from '#core/editor/components/properties'+import type { EditorContext } from '#core/editor/types'+import { randomHex } from '#core/random'++export type VariantConflict = {+ values: Record<string, string>+ componentIds: string[]+}++export type VariantValidationIssue =+ | ({ kind: 'duplicate-combination' } & VariantConflict)+ | {+ kind: 'missing-value'+ propertyId: string+ propertyName: string+ componentIds: string[]+ }++export type VariantTransitionResult =+ | { kind: 'changed'; componentId: string }+ | { kind: 'unchanged'; componentId: string }+ | { kind: 'unavailable'; requested: Record<string, string> }+ | { kind: 'invalid' }++export type VariantMutationResult =+ | { kind: 'changed' }+ | { kind: 'unchanged' }+ | { kind: 'conflict'; componentIds: string[] }+ | { kind: 'invalid' }++export type VariantOptionAvailability = {+ value: string+ available: boolean+}++type VariantSnapshot = {+ definitions: ComponentPropertyDefinition[]+ variants: Map<string, Pick<SceneNode, 'componentPropertyValues' | 'name'>>+}++function sortByCanvasPosition(a: SceneNode, b: SceneNode) {+ return a.y - b.y || a.x - b.x || a.name.localeCompare(b.name)+}++export function createVariantActions(ctx: EditorContext) {+ function getComponentSet(componentSetId: string): SceneNode | undefined {+ const node = ctx.graph.getNode(componentSetId)+ return node?.type === 'COMPONENT_SET' ? node : undefined+ }++ function getVariantDefinitions(componentSetId: string): ComponentPropertyDefinition[] {+ return (getComponentSet(componentSetId)?.componentPropertyDefinitions ?? []).filter(+ (definition) => definition.type === 'VARIANT'+ )+ }++ function getComponentSetPropertyDefs(componentSetId: string): ComponentPropertyDefinition[] {+ return getComponentSet(componentSetId)?.componentPropertyDefinitions ?? []+ }++ function getComponentSetVariants(componentSetId: string): SceneNode[] {+ const node = getComponentSet(componentSetId)+ if (!node) return []+ return node.childIds+ .map((id) => ctx.graph.getNode(id))+ .filter((child): child is SceneNode => child?.type === 'COMPONENT')+ }++ function assertComponentSetEditable(componentSetId: string): void {+ assertNodeEditable(ctx.graph, componentSetId)+ for (const variant of getComponentSetVariants(componentSetId)) {+ assertNodeEditable(ctx.graph, variant.id)+ }+ }++ function captureVariantSnapshot(componentSetId: string): VariantSnapshot | null {+ const componentSet = getComponentSet(componentSetId)+ if (!componentSet) return null+ return {+ definitions: structuredClone(componentSet.componentPropertyDefinitions),+ variants: new Map(+ getComponentSetVariants(componentSetId).map((variant) => [+ variant.id,+ {+ componentPropertyValues: structuredClone(variant.componentPropertyValues),+ name: variant.name+ }+ ])+ )+ }+ }++ function restoreVariantSnapshot(componentSetId: string, snapshot: VariantSnapshot): void {+ const componentSet = getComponentSet(componentSetId)+ if (!componentSet) return+ ctx.graph.updateNode(componentSetId, {+ componentPropertyDefinitions: structuredClone(snapshot.definitions)+ })+ for (const [variantId, variantSnapshot] of snapshot.variants) {+ if (!ctx.graph.getNode(variantId)) continue+ ctx.graph.updateNode(variantId, {+ componentPropertyValues: structuredClone(variantSnapshot.componentPropertyValues),+ name: variantSnapshot.name+ })+ }+ ctx.requestRender()+ }++ function recordSnapshotChange(+ componentSetId: string,+ label: string,+ before: VariantSnapshot,+ after: VariantSnapshot+ ): void {+ ctx.undo.push({+ label,+ forward: () => restoreVariantSnapshot(componentSetId, after),+ inverse: () => restoreVariantSnapshot(componentSetId, before)+ })+ ctx.requestRender()+ }++ function updateVariantName(componentSetId: string, variant: SceneNode): void {+ const values = Object.fromEntries(+ getVariantDefinitions(componentSetId).map((definition) => [+ definition.name,+ variant.componentPropertyValues[definition.name] ?? ''+ ])+ )+ ctx.graph.updateNode(variant.id, { name: buildVariantName(values) })+ }++ function refreshVariantOptions(componentSetId: string): void {+ const componentSet = getComponentSet(componentSetId)+ if (!componentSet) return+ const collected = collectVariantOptions(componentSetId)+ const definitions = componentSet.componentPropertyDefinitions.map((definition) => {+ if (definition.type !== 'VARIANT') return definition+ const present = collected.get(definition.name) ?? new Set<string>()+ const options = [+ ...(definition.variantOptions ?? []).filter((value) => present.has(value)),+ ...[...present].filter((value) => !definition.variantOptions?.includes(value))+ ]+ return {+ ...definition,+ defaultValue: options.includes(definition.defaultValue)+ ? definition.defaultValue+ : (options[0] ?? ''),+ variantOptions: options+ }+ })+ ctx.graph.updateNode(componentSetId, { componentPropertyDefinitions: definitions })+ }++ function hasDuplicateCombination(+ componentSetId: string,+ valuesForVariant: (variant: SceneNode) => Record<string, string>+ ): boolean {+ const seen = new Set<string>()+ const definitions = getVariantDefinitions(componentSetId)+ for (const variant of getComponentSetVariants(componentSetId)) {+ const values = valuesForVariant(variant)+ const key = definitions.map((definition) => values[definition.name] ?? '').join('\u0000')+ if (seen.has(key)) return true+ seen.add(key)+ }+ return false+ }++ function reorderPropertyDefinitions(componentSetId: string, propertyIds: string[]): boolean {+ assertComponentSetEditable(componentSetId)+ const componentSet = getComponentSet(componentSetId)+ const before = captureVariantSnapshot(componentSetId)+ if (!componentSet || !before) return false+ const definitionsById = new Map(+ componentSet.componentPropertyDefinitions.map((definition) => [definition.id, definition])+ )+ if (+ propertyIds.length !== definitionsById.size ||+ new Set(propertyIds).size !== definitionsById.size ||+ propertyIds.some((id) => !definitionsById.has(id))+ ) {+ return false+ }+ if (+ propertyIds.every((id, index) => componentSet.componentPropertyDefinitions[index]?.id === id)+ )+ return true++ ctx.graph.updateNode(componentSetId, {+ componentPropertyDefinitions: propertyIds.flatMap((id) => {+ const definition = definitionsById.get(id)+ return definition ? [definition] : []+ })+ })+ for (const variant of getComponentSetVariants(componentSetId))+ updateVariantName(componentSetId, variant)+ const after = captureVariantSnapshot(componentSetId)+ if (after) recordSnapshotChange(componentSetId, 'Reorder properties', before, after)+ return true+ }++ function reorderVariantValues(+ componentSetId: string,+ propertyId: string,+ values: string[]+ ): boolean {+ assertComponentSetEditable(componentSetId)+ const componentSet = getComponentSet(componentSetId)+ const definition = getVariantDefinitions(componentSetId).find((item) => item.id === propertyId)+ const currentValues = definition?.variantOptions ?? []+ const before = captureVariantSnapshot(componentSetId)+ if (!componentSet || !definition || !before) return false+ if (+ values.length !== currentValues.length ||+ new Set(values).size !== currentValues.length ||+ values.some((value) => !currentValues.includes(value))+ ) {+ return false+ }+ if (values.every((value, index) => currentValues[index] === value)) return true++ ctx.graph.updateNode(componentSetId, {+ componentPropertyDefinitions: componentSet.componentPropertyDefinitions.map((item) =>+ item.id === propertyId+ ? { ...item, variantOptions: [...values], defaultValue: values[0] ?? '' }+ : item+ )+ })+ const after = captureVariantSnapshot(componentSetId)+ if (after) recordSnapshotChange(componentSetId, 'Reorder variant values', before, after)+ return true+ }++ function addPropertyDefinition(+ componentSetId: string,+ name: string,+ type: ComponentPropertyType = 'VARIANT',+ defaultValue = ''+ ): string | undefined {+ assertComponentSetEditable(componentSetId)+ const node = getComponentSet(componentSetId)+ const normalizedName = name.trim()+ if (!node || !normalizedName) return undefined+ if (+ node.componentPropertyDefinitions.some((definition) => definition.name === normalizedName)+ ) {+ return undefined+ }++ const before = captureVariantSnapshot(componentSetId)+ if (!before) return undefined+ const id = `prop:${randomHex(8)}`+ const definition: ComponentPropertyDefinition = {+ id,+ name: normalizedName,+ type,+ defaultValue,+ variantOptions: type === 'VARIANT' ? [defaultValue] : undefined+ }+ ctx.graph.updateNode(componentSetId, {+ componentPropertyDefinitions: [...node.componentPropertyDefinitions, definition]+ })+ if (type === 'VARIANT') {+ for (const variant of getComponentSetVariants(componentSetId)) {+ ctx.graph.updateNode(variant.id, {+ componentPropertyValues: {+ ...variant.componentPropertyValues,+ [normalizedName]: defaultValue+ }+ })+ const updated = ctx.graph.getNode(variant.id)+ if (updated) updateVariantName(componentSetId, updated)+ }+ refreshVariantOptions(componentSetId)+ }+ const after = captureVariantSnapshot(componentSetId)+ if (after) recordSnapshotChange(componentSetId, 'Add property', before, after)+ return id+ }++ function removePropertyDefinition(componentSetId: string, propertyId: string): boolean {+ assertComponentSetEditable(componentSetId)+ const node = getComponentSet(componentSetId)+ const definition = node?.componentPropertyDefinitions.find((item) => item.id === propertyId)+ const before = captureVariantSnapshot(componentSetId)+ if (!node || !definition || !before) return false++ ctx.graph.updateNode(componentSetId, {+ componentPropertyDefinitions: node.componentPropertyDefinitions.filter(+ (item) => item.id !== propertyId+ )+ })+ if (definition.type === 'VARIANT') {+ for (const variant of getComponentSetVariants(componentSetId)) {+ ctx.graph.updateNode(variant.id, {+ componentPropertyValues: omit(variant.componentPropertyValues, [definition.name])+ })+ const updated = ctx.graph.getNode(variant.id)+ if (updated) updateVariantName(componentSetId, updated)+ }+ refreshVariantOptions(componentSetId)+ }+ const after = captureVariantSnapshot(componentSetId)+ if (after) recordSnapshotChange(componentSetId, 'Remove property', before, after)+ return true+ }++ function renamePropertyDefinition(+ componentSetId: string,+ propertyId: string,+ newName: string+ ): boolean {+ assertComponentSetEditable(componentSetId)+ const node = getComponentSet(componentSetId)+ const normalizedName = newName.trim()+ const definition = node?.componentPropertyDefinitions.find((item) => item.id === propertyId)+ const before = captureVariantSnapshot(componentSetId)+ if (!node || !definition || !before || !normalizedName) return false+ if (+ node.componentPropertyDefinitions.some(+ (item) => item.id !== propertyId && item.name === normalizedName+ )+ ) {+ return false+ }+ if (definition.name === normalizedName) return true++ ctx.graph.updateNode(componentSetId, {+ componentPropertyDefinitions: node.componentPropertyDefinitions.map((item) =>+ item.id === propertyId ? { ...item, name: normalizedName } : item+ )+ })+ if (definition.type === 'VARIANT') {+ for (const variant of getComponentSetVariants(componentSetId)) {+ const value = variant.componentPropertyValues[definition.name] ?? ''+ ctx.graph.updateNode(variant.id, {+ componentPropertyValues: {+ ...omit(variant.componentPropertyValues, [definition.name]),+ [normalizedName]: value+ }+ })+ const updated = ctx.graph.getNode(variant.id)+ if (updated) updateVariantName(componentSetId, updated)+ }+ }+ const after = captureVariantSnapshot(componentSetId)+ if (after) recordSnapshotChange(componentSetId, 'Rename property', before, after)+ return true+ }++ function renameVariantValue(+ componentSetId: string,+ propertyId: string,+ previousValue: string,+ newValue: string+ ): boolean {+ assertComponentSetEditable(componentSetId)+ const definition = getVariantDefinitions(componentSetId).find((item) => item.id === propertyId)+ const normalizedValue = newValue.trim()+ const before = captureVariantSnapshot(componentSetId)+ const componentSet = getComponentSet(componentSetId)+ if (+ !definition ||+ !componentSet ||+ !before ||+ !normalizedValue ||+ previousValue === normalizedValue+ )+ return false+ if (+ hasDuplicateCombination(componentSetId, (variant) => ({+ ...variantValues(componentSetId, variant),+ [definition.name]:+ variant.componentPropertyValues[definition.name] === previousValue+ ? normalizedValue+ : (variant.componentPropertyValues[definition.name] ?? '')+ }))+ ) {+ return false+ }++ ctx.graph.updateNode(componentSetId, {+ componentPropertyDefinitions: componentSet.componentPropertyDefinitions.map((item) =>+ item.id === propertyId+ ? {+ ...item,+ defaultValue:+ item.defaultValue === previousValue ? normalizedValue : item.defaultValue,+ variantOptions: item.variantOptions?.map((option) =>+ option === previousValue ? normalizedValue : option+ )+ }+ : item+ )+ })+ for (const variant of getComponentSetVariants(componentSetId)) {+ if (variant.componentPropertyValues[definition.name] !== previousValue) continue+ ctx.graph.updateNode(variant.id, {+ componentPropertyValues: {+ ...variant.componentPropertyValues,+ [definition.name]: normalizedValue+ }+ })+ const updated = ctx.graph.getNode(variant.id)+ if (updated) updateVariantName(componentSetId, updated)+ }+ refreshVariantOptions(componentSetId)+ const after = captureVariantSnapshot(componentSetId)+ if (after) recordSnapshotChange(componentSetId, 'Rename variant value', before, after)+ return true+ }++ function setVariantPropertyValue(+ variantId: string,+ propertyId: string,+ value: string+ ): VariantMutationResult {+ assertNodeEditable(ctx.graph, variantId)+ const variant = ctx.graph.getNode(variantId)+ const componentSetId = variant?.parentId+ if (variant?.type !== 'COMPONENT' || !componentSetId) return { kind: 'invalid' }+ const definition = getVariantDefinitions(componentSetId).find((item) => item.id === propertyId)+ const normalizedValue = value.trim()+ const before = captureVariantSnapshot(componentSetId)+ if (!definition || !before || !normalizedValue) return { kind: 'invalid' }+ if (variant.componentPropertyValues[definition.name] === normalizedValue) {+ return { kind: 'unchanged' }+ }++ const requested = {+ ...variantValues(componentSetId, variant),+ [definition.name]: normalizedValue+ }+ const conflicting = findExactVariant(componentSetId, requested)+ if (conflicting && conflicting.id !== variantId) {+ return { kind: 'conflict', componentIds: [variantId, conflicting.id] }+ }++ ctx.graph.updateNode(variantId, {+ componentPropertyValues: {+ ...variant.componentPropertyValues,+ [definition.name]: normalizedValue+ }+ })+ const updated = ctx.graph.getNode(variantId)+ if (updated) updateVariantName(componentSetId, updated)+ refreshVariantOptions(componentSetId)+ const after = captureVariantSnapshot(componentSetId)+ if (after) recordSnapshotChange(componentSetId, `Change ${definition.name}`, before, after)+ return { kind: 'changed' }+ }++ function collectVariantOptions(componentSetId: string): Map<string, Set<string>> {+ const options = new Map<string, Set<string>>()+ for (const definition of getVariantDefinitions(componentSetId)) {+ options.set(definition.name, new Set())+ }+ for (const variant of getComponentSetVariants(componentSetId)) {+ for (const definition of getVariantDefinitions(componentSetId)) {+ const value = variant.componentPropertyValues[definition.name]+ if (value) options.get(definition.name)?.add(value)+ }+ }+ return options+ }++ function variantValues(componentSetId: string, variant: SceneNode): Record<string, string> {+ return Object.fromEntries(+ getVariantDefinitions(componentSetId).map((definition) => [+ definition.name,+ variant.componentPropertyValues[definition.name] ?? ''+ ])+ )+ }++ function findVariantByValues(+ componentSetId: string,+ values: Record<string, string>+ ): SceneNode | undefined {+ return getComponentSetVariants(componentSetId)+ .sort(sortByCanvasPosition)+ .find((variant) =>+ Object.entries(values).every(+ ([propertyName, value]) => variant.componentPropertyValues[propertyName] === value+ )+ )+ }++ function findExactVariant(+ componentSetId: string,+ values: Record<string, string>+ ): SceneNode | undefined {+ const definitions = getVariantDefinitions(componentSetId)+ if (definitions.some((definition) => !Object.hasOwn(values, definition.name))) return undefined+ return findVariantByValues(+ componentSetId,+ Object.fromEntries(+ definitions.map((definition) => [definition.name, values[definition.name]])+ )+ )+ }++ function getDefaultVariantForComponentSet(componentSetId: string): SceneNode | undefined {+ return getComponentSetVariants(componentSetId).sort(sortByCanvasPosition)[0]+ }++ function getComponentSetVariantConflicts(componentSetId: string): VariantConflict[] {+ const definitions = getVariantDefinitions(componentSetId)+ const byKey = new Map<string, VariantConflict>()+ for (const variant of getComponentSetVariants(componentSetId)) {+ const values = variantValues(componentSetId, variant)+ const key = definitions+ .map((definition) => `${definition.name}=${values[definition.name]}`)+ .join('\u0000')+ const entry = byKey.get(key) ?? { values, componentIds: [] }+ entry.componentIds.push(variant.id)+ byKey.set(key, entry)+ }+ return [...byKey.values()].filter((entry) => entry.componentIds.length > 1)+ }++ function validateComponentSet(componentSetId: string): VariantValidationIssue[] {+ const missing = getVariantDefinitions(componentSetId).flatMap((definition) => {+ const componentIds = getComponentSetVariants(componentSetId)+ .filter((variant) => !variant.componentPropertyValues[definition.name]?.trim())+ .map((variant) => variant.id)+ return componentIds.length > 0+ ? [+ {+ kind: 'missing-value' as const,+ propertyId: definition.id,+ propertyName: definition.name,+ componentIds+ }+ ]+ : []+ })+ return [+ ...missing,+ ...getComponentSetVariantConflicts(componentSetId).map((conflict) => ({+ kind: 'duplicate-combination' as const,+ ...conflict+ }))+ ]+ }++ function getVariantOptionAvailability(+ instanceId: string,+ propertyName: string+ ): VariantOptionAvailability[] {+ const instance = ctx.graph.getNode(instanceId)+ const component = instance?.componentId ? ctx.graph.getNode(instance.componentId) : undefined+ const componentSetId = component?.parentId+ if (instance?.type !== 'INSTANCE' || component?.type !== 'COMPONENT' || !componentSetId) {+ return []+ }+ const options = collectVariantOptions(componentSetId).get(propertyName) ?? new Set<string>()+ return [...options].map((value) => ({+ value,+ available: Boolean(+ findExactVariant(componentSetId, {+ ...variantValues(componentSetId, component),+ [propertyName]: value+ })+ )+ }))+ }++ function switchInstanceVariant(+ instanceId: string,+ propertyName: string,+ newValue: string+ ): VariantTransitionResult {+ assertNodeEditable(ctx.graph, instanceId)+ const instance = ctx.graph.getNode(instanceId)+ if (instance?.type !== 'INSTANCE' || !instance.componentId) return { kind: 'invalid' }+ const component = ctx.graph.getNode(instance.componentId)+ const componentSetId = component?.parentId+ if (component?.type !== 'COMPONENT' || !componentSetId || !getComponentSet(componentSetId)) {+ return { kind: 'invalid' }+ }++ const requested = {+ ...variantValues(componentSetId, component),+ [propertyName]: newValue+ }+ const target = findExactVariant(componentSetId, requested)+ if (!target) return { kind: 'unavailable', requested }+ if (target.id === instance.componentId) return { kind: 'unchanged', componentId: target.id }++ const previousComponentId = instance.componentId+ const applyComponent = (componentId: string) => {+ ctx.graph.swapInstanceComponent(instanceId, componentId)+ reapplyInstanceComponentProperties(ctx, instanceId)+ ctx.requestRender()+ }+ applyComponent(target.id)+ ctx.undo.push({+ label: 'Switch variant',+ forward: () => applyComponent(target.id),+ inverse: () => applyComponent(previousComponentId)+ })+ return { kind: 'changed', componentId: target.id }+ }++ function duplicateVariant(variantId: string): string | undefined {+ assertNodeEditable(ctx.graph, variantId)+ const variant = ctx.graph.getNode(variantId)+ const componentSetId = variant?.parentId+ if (variant?.type !== 'COMPONENT' || !componentSetId || !getComponentSet(componentSetId)) {+ return undefined+ }+ const clone = ctx.graph.cloneTree(variantId, componentSetId, {+ x: variant.x + variant.width + 40,+ name: variant.name+ })+ if (!clone) return undefined+ const snapshots = snapshotSubtree(ctx.graph, clone.id)+ ctx.setSelectedIds(new Set([clone.id]))+ ctx.undo.push({+ label: 'Add variant',+ forward: () => {+ const root = snapshots.get(clone.id)+ if (root) restoreSubtree(ctx.graph, root, componentSetId, snapshots)+ ctx.setSelectedIds(new Set([clone.id]))+ ctx.requestRender()+ },+ inverse: () => {+ ctx.graph.deleteNode(clone.id)+ ctx.setSelectedIds(new Set([variantId]))+ ctx.requestRender()+ }+ })+ ctx.requestRender()+ return clone.id+ }++ function addVariant(componentSetId: string): string | undefined {+ const source = getDefaultVariantForComponentSet(componentSetId)+ return source ? duplicateVariant(source.id) : undefined+ }++ function removeVariant(variantId: string): boolean {+ assertNodeEditable(ctx.graph, variantId)+ const variant = ctx.graph.getNode(variantId)+ const componentSetId = variant?.parentId+ if (variant?.type !== 'COMPONENT' || !componentSetId) return false+ if (getComponentSetVariants(componentSetId).length <= 1) return false+ const snapshots = snapshotSubtree(ctx.graph, variantId)+ ctx.graph.deleteNode(variantId)+ ctx.setSelectedIds(new Set([componentSetId]))+ ctx.undo.push({+ label: 'Remove variant',+ forward: () => {+ ctx.graph.deleteNode(variantId)+ ctx.setSelectedIds(new Set([componentSetId]))+ ctx.requestRender()+ },+ inverse: () => {+ const root = snapshots.get(variantId)+ if (root) restoreSubtree(ctx.graph, root, componentSetId, snapshots)+ ctx.setSelectedIds(new Set([variantId]))+ ctx.requestRender()+ }+ })+ ctx.requestRender()+ return true+ }++ return {+ getComponentSetPropertyDefs,+ addPropertyDefinition,+ removePropertyDefinition,+ renamePropertyDefinition,+ reorderPropertyDefinitions,+ renameVariantValue,+ reorderVariantValues,+ setVariantPropertyValue,+ parseVariantName,+ buildVariantName,+ collectVariantOptions,+ findVariantByValues,+ getDefaultVariantForComponentSet,+ getComponentSetVariantConflicts,+ validateComponentSet,+ getVariantOptionAvailability,+ switchInstanceVariant,+ addVariant,+ duplicateVariant,+ removeVariant+ }+}diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.tsindex cc7620e95..9bcdae145 100644--- a/packages/core/src/editor/index.ts+++ b/packages/core/src/editor/index.ts@@ -1,10 +1,18 @@+export {+ assertNodeEditable,+ getNodeEditCapability,+ ReadOnlyLibraryDefinitionError+} from './capabilities'+export type { NodeEditCapability } from './capabilities'export { createDefaultEditorState, createEditor } from './create'export type { Editor } from './create'+export { reapplyInstanceComponentProperties } from './components/properties'export { createTextActions } from './text'export { opacityFromBuffer } from './nodes'export { EDITOR_TOOLS, TOOL_SHORTCUTS } from './tool-registry'export type { RenameSelectionOptions, RenameSelectionPreview } from './structure/rename'export type { EditorToolDef } from './tool-registry'+export type { VariantConflict, VariantValidationIssue } from './components/variants'export type {ClipboardImageResolution,EditorContext,diff --git a/packages/core/src/editor/structure/reorder.ts b/packages/core/src/editor/structure/reorder.tsindex d21ed077a..e30549003 100644--- a/packages/core/src/editor/structure/reorder.ts+++ b/packages/core/src/editor/structure/reorder.ts@@ -1,8 +1,11 @@+import { assertNodeEditable } from '#core/editor/capabilities'import type { EditorContext } from '#core/editor/types'import { computeLayout } from '#core/layout'export function createStructureReorderActions(ctx: EditorContext) {function doReorderChild(nodeId: string, parentId: string, insertIndex: number) {+ assertNodeEditable(ctx.graph, nodeId)+ assertNodeEditable(ctx.graph, parentId)const node = ctx.graph.getNode(nodeId)if (!node) return@@ -49,6 +52,8 @@ export function createStructureReorderActions(ctx: EditorContext) {}function reorderChildWithUndo(nodeId: string, newParentId: string, insertIndex: number) {+ assertNodeEditable(ctx.graph, nodeId)+ assertNodeEditable(ctx.graph, newParentId)const node = ctx.graph.getNode(nodeId)if (!node) returnconst origParentId = node.parentId ?? ctx.state.currentPageId@@ -77,6 +82,8 @@ export function createStructureReorderActions(ctx: EditorContext) {}function applyChildOrder(parentId: string, childIds: readonly string[]) {+ assertNodeEditable(ctx.graph, parentId)+ for (const childId of childIds) assertNodeEditable(ctx.graph, childId)const current = ctx.graph.getNode(parentId)?.childIds ?? []for (const [index, childId] of childIds.entries()) {if (current[index] === childId) continue@@ -91,6 +98,7 @@ export function createStructureReorderActions(ctx: EditorContext) {reorder: (childIds: readonly string[], selectedIds: ReadonlySet<string>) => string[]) {const selectedIds = ctx.state.selectedIds+ for (const id of selectedIds) assertNodeEditable(ctx.graph, id)const parentIds = new Set<string>()for (const id of selectedIds) {const parentId = ctx.graph.getNode(id)?.parentIddiff --git a/packages/core/src/editor/structure/state.ts b/packages/core/src/editor/structure/state.tsindex 9912e2293..e62ceda4f 100644--- a/packages/core/src/editor/structure/state.ts+++ b/packages/core/src/editor/structure/state.ts@@ -1,7 +1,9 @@+import { assertNodeEditable } from '#core/editor/capabilities'import type { EditorContext } from '#core/editor/types'export function createStructureStateActions(ctx: EditorContext) {function toggleNodeVisibility(id: string) {+ assertNodeEditable(ctx.graph, id)const node = ctx.graph.getNode(id)if (!node) returnctx.graph.updateNode(id, { visible: !node.visible })@@ -9,16 +11,19 @@ export function createStructureStateActions(ctx: EditorContext) {}function toggleNodeLock(id: string) {+ assertNodeEditable(ctx.graph, id)const node = ctx.graph.getNode(id)if (!node) returnctx.graph.updateNode(id, { locked: !node.locked })}function toggleVisibility() {+ for (const id of ctx.state.selectedIds) assertNodeEditable(ctx.graph, id)for (const id of ctx.state.selectedIds) toggleNodeVisibility(id)}function toggleLock() {+ for (const id of ctx.state.selectedIds) assertNodeEditable(ctx.graph, id)for (const id of ctx.state.selectedIds) toggleNodeLock(id)}diff --git a/packages/core/src/editor/undo.ts b/packages/core/src/editor/undo.tsindex 3729464e8..c8963d839 100644--- a/packages/core/src/editor/undo.ts+++ b/packages/core/src/editor/undo.ts@@ -5,6 +5,7 @@ import { copyGeometryPaths } from '@open-pencil/scene-graph/copy'import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'import type { UndoEntry } from '@open-pencil/scene-graph/undo'+import { assertNodeEditable } from './capabilities'import { restoreSubtree, snapshotSubtree } from './clipboard/subtree-history'import { collectNodePositions, pushPositionUndo } from './history/position'import {@@ -36,12 +37,14 @@ function createResizeSnapshot(node: SceneNode): ResizeSnapshot {export function createUndoActions(ctx: EditorContext) {function commitMove(originals: Map<string, Vector>) {+ for (const id of originals.keys()) assertNodeEditable(ctx.graph, id)pushPositionUndo(ctx, 'Move', originals, collectNodePositions(ctx, originals.keys()))}function commitMoveWithReparent(originals: Map<string, { x: number; y: number; parentId: string }>) {+ for (const id of originals.keys()) assertNodeEditable(ctx.graph, id)const finals = new Map<string, { x: number; y: number; parentId: string }>()for (const [id] of originals) {const n = ctx.graph.getNode(id)@@ -99,6 +102,7 @@ export function createUndoActions(ctx: EditorContext) {}function commitResize(nodeId: string, original: ResizeOriginal) {+ assertNodeEditable(ctx.graph, nodeId)const node = ctx.graph.getNode(nodeId)if (!node) returnconst includesGeometry =@@ -124,6 +128,8 @@ export function createUndoActions(ctx: EditorContext) {origRect: Rect,origChildren: Map<string, ResizeSnapshot>) {+ assertNodeEditable(ctx.graph, nodeId)+ for (const childId of origChildren.keys()) assertNodeEditable(ctx.graph, childId)const node = ctx.graph.getNode(nodeId)if (!node) returnconst finalRect = { x: node.x, y: node.y, width: node.width, height: node.height }@@ -135,11 +141,15 @@ export function createUndoActions(ctx: EditorContext) {ctx.undo.push({label: 'Resize',forward: () => {+ assertNodeEditable(ctx.graph, nodeId)+ for (const childId of finalChildren.keys()) assertNodeEditable(ctx.graph, childId)ctx.graph.updateNode(nodeId, finalRect)for (const [childId, final] of finalChildren) ctx.graph.updateNode(childId, final)ctx.runLayoutForNode(nodeId)},inverse: () => {+ assertNodeEditable(ctx.graph, nodeId)+ for (const childId of origChildren.keys()) assertNodeEditable(ctx.graph, childId)ctx.graph.updateNode(nodeId, origRect)for (const [childId, orig] of origChildren) ctx.graph.updateNode(childId, orig)ctx.runLayoutForNode(nodeId)@@ -148,6 +158,7 @@ export function createUndoActions(ctx: EditorContext) {}function commitRotation(nodeId: string, origRotation: number) {+ assertNodeEditable(ctx.graph, nodeId)const node = ctx.graph.getNode(nodeId)if (!node) returnconst finalRotation = node.rotation@@ -163,6 +174,7 @@ export function createUndoActions(ctx: EditorContext) {}function commitNodeUpdate(nodeId: string, previous: Partial<SceneNode>, label = 'Update') {+ assertNodeEditable(ctx.graph, nodeId)const node = ctx.graph.getNode(nodeId)if (!node) returnconst restoredPrevious = { ...previous, ...textAutoResizeChanges(node, previous) }diff --git a/packages/core/src/figma-api/accessor-utils.ts b/packages/core/src/figma-api/accessor-utils.tsindex 7adb135bb..e07a0264b 100644--- a/packages/core/src/figma-api/accessor-utils.ts+++ b/packages/core/src/figma-api/accessor-utils.ts@@ -1,5 +1,7 @@import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { assertNodeEditable } from '#core/editor/capabilities'+export interface NodeProxyInternals {id: symbolgraph: symbol@@ -23,10 +25,15 @@ export function raw(target: ProxyThis, internals: NodeProxyInternals): SceneNodereturn node}+export function assertProxyEditable(target: ProxyThis, internals: NodeProxyInternals): void {+ assertNodeEditable(graph(target, internals), nodeId(target, internals))+}+export function updateNode(target: ProxyThis,internals: NodeProxyInternals,changes: Partial<SceneNode>): void {+ assertProxyEditable(target, internals)graph(target, internals).updateNode(nodeId(target, internals), changes)}diff --git a/packages/core/src/figma-api/accessors/basic.ts b/packages/core/src/figma-api/accessors/basic.tsindex 6cc3288fb..9f32a207c 100644--- a/packages/core/src/figma-api/accessors/basic.ts+++ b/packages/core/src/figma-api/accessors/basic.ts@@ -1,6 +1,7 @@import { getNodeLocalMatrix, getWorldMatrix, type SceneNode } from '@open-pencil/scene-graph'import type { Rect } from '@open-pencil/scene-graph/primitives'+import { assertNodeEditable } from '#core/editor/capabilities'import {graph,nodeId,@@ -15,6 +16,10 @@ import type { FigmaTransform } from '#core/figma-api/types'const TRANSFORM_FIELDS = new Set(['x', 'y', 'rotation', 'flipX', 'flipY'])+function assertEditable(target: ProxyThis, internals: NodeProxyInternals): void {+ assertNodeEditable(graph(target, internals), nodeId(target, internals))+}+function preservesRawTransform(node: SceneNode): boolean {return !node.source.editedFields.some((field) => TRANSFORM_FIELDS.has(field))}@@ -56,6 +61,7 @@ export function installBasicNodeProxyAccessors(return raw(this, internals).name},set(this: ProxyThis, value: string) {+ assertEditable(this, internals)graph(this, internals).updateNode(nodeId(this, internals), { name: value })}},@@ -69,6 +75,7 @@ export function installBasicNodeProxyAccessors(return raw(this, internals).x},set(this: ProxyThis, value: number) {+ assertEditable(this, internals)graph(this, internals).updateNode(nodeId(this, internals), { x: value })}},@@ -77,6 +84,7 @@ export function installBasicNodeProxyAccessors(return raw(this, internals).y},set(this: ProxyThis, value: number) {+ assertEditable(this, internals)graph(this, internals).updateNode(nodeId(this, internals), { y: value })}},@@ -100,6 +108,7 @@ export function installBasicNodeProxyAccessors(return node.rotation},set(this: ProxyThis, value: number) {+ assertEditable(this, internals)graph(this, internals).updateNode(nodeId(this, internals), { rotation: value })}},@@ -139,12 +148,14 @@ export function installBasicNodeProxyAccessors(Object.assign(prototype, {resize(this: ProxyThis, width: number, height: number): void {+ assertEditable(this, internals)graph(this, internals).updateNode(nodeId(this, internals), { width, height })},resizeWithoutConstraints(this: ProxyThis, width: number, height: number): void {;(this as { resize(width: number, height: number): void }).resize(width, height)},rescale(this: ProxyThis, scale: number): void {+ assertEditable(this, internals)rescaleNodeTree(graph(this, internals), nodeId(this, internals), scale)}})diff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.tsindex 1984a6009..0584a2c28 100644--- a/packages/core/src/figma-api/proxy.ts+++ b/packages/core/src/figma-api/proxy.ts@@ -16,6 +16,7 @@ import {setNodeStrokeOkHCL} from '#core/color/okhcl'import type { OkHCLColor, OkHCLPayload } from '#core/color/okhcl'+import { assertNodeEditable } from '#core/editor/capabilities'import { installBasicNodeProxyAccessors } from './accessors/basic'import { installLayoutNodeProxyAccessors } from './accessors/layout'@@ -133,6 +134,11 @@ export class FigmaNodeProxy {}}+ private _update(changes: Partial<SceneNode>): void {+ assertNodeEditable(this[INTERNAL_GRAPH], this[INTERNAL_ID])+ this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], changes)+ }+private _raw(): SceneNode {const n = this[INTERNAL_GRAPH].getNode(this[INTERNAL_ID])if (!n) throw new Error(`Node ${this[INTERNAL_ID]} has been removed`)@@ -164,7 +170,7 @@ export class FigmaNodeProxy {}set dashPattern(v: readonly number[]) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { dashPattern: [...v] })+ this._update({ dashPattern: [...v] })}get strokeCap(): string {@@ -174,7 +180,7 @@ export class FigmaNodeProxy {set strokeCap(v: string) {const strokeCap = v as SceneNode['strokeCap']const node = this._raw()- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {+ this._update({strokeCap,strokes: node.strokes.map((stroke) => ({ ...stroke, cap: strokeCap }))})@@ -187,7 +193,7 @@ export class FigmaNodeProxy {set strokeJoin(v: string) {const strokeJoin = v as SceneNode['strokeJoin']const node = this._raw()- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {+ this._update({strokeJoin,strokes: node.strokes.map((stroke) => ({ ...stroke, join: strokeJoin }))})@@ -198,7 +204,7 @@ export class FigmaNodeProxy {}set strokeMiterLimit(v: number) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { strokeMiterLimit: v })+ this._update({ strokeMiterLimit: v })}get strokeTopWeight(): number {@@ -240,7 +246,7 @@ export class FigmaNodeProxy {}set characters(v: string) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { text: v })+ this._update({ text: v })}get fontSize(): number {@@ -248,7 +254,7 @@ export class FigmaNodeProxy {}set fontSize(v: number) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { fontSize: v })+ this._update({ fontSize: v })}get fontName(): FigmaFontName {@@ -264,7 +270,7 @@ export class FigmaNodeProxy {}set fontWeight(v: number) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { fontWeight: v })+ this._update({ fontWeight: v })}get textAlignHorizontal(): string {@@ -272,7 +278,7 @@ export class FigmaNodeProxy {}set textAlignHorizontal(v: string) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {+ this._update({textAlignHorizontal: v as SceneNode['textAlignHorizontal']})}@@ -282,7 +288,7 @@ export class FigmaNodeProxy {}set textDirection(v: string) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {+ this._update({textDirection: v as SceneNode['textDirection']})}@@ -292,7 +298,7 @@ export class FigmaNodeProxy {}set textAlignVertical(v: string) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {+ this._update({textAlignVertical: v as SceneNode['textAlignVertical']})}@@ -302,7 +308,7 @@ export class FigmaNodeProxy {}set textAutoResize(v: string) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {+ this._update({textAutoResize: v as SceneNode['textAutoResize']})}@@ -312,7 +318,7 @@ export class FigmaNodeProxy {}set letterSpacing(v: number) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { letterSpacing: v })+ this._update({ letterSpacing: v })}get lineHeight(): number | null {@@ -320,7 +326,7 @@ export class FigmaNodeProxy {}set lineHeight(v: number | null) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { lineHeight: v })+ this._update({ lineHeight: v })}get textCase(): string {@@ -328,7 +334,7 @@ export class FigmaNodeProxy {}set textCase(v: string) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { textCase: v as SceneNode['textCase'] })+ this._update({ textCase: v as SceneNode['textCase'] })}get textDecoration(): string {@@ -336,7 +342,7 @@ export class FigmaNodeProxy {}set textDecoration(v: string) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {+ this._update({textDecoration: v as SceneNode['textDecoration']})}@@ -346,7 +352,7 @@ export class FigmaNodeProxy {}set maxLines(v: number | null) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { maxLines: v })+ this._update({ maxLines: v })}get textTruncation(): string {@@ -354,7 +360,7 @@ export class FigmaNodeProxy {}set textTruncation(v: string) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], {+ this._update({textTruncation: v as SceneNode['textTruncation']})}@@ -364,7 +370,7 @@ export class FigmaNodeProxy {}set autoRename(v: boolean) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { autoRename: v })+ this._update({ autoRename: v })}insertCharacters(start: number, characters: string): void {@@ -380,7 +386,7 @@ export class FigmaNodeProxy {}set isMask(v: boolean) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { isMask: v })+ this._update({ isMask: v })}get maskType(): string {@@ -388,7 +394,7 @@ export class FigmaNodeProxy {}set maskType(v: string) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { maskType: v as SceneNode['maskType'] })+ this._update({ maskType: v as SceneNode['maskType'] })}// --- UI state ---@@ -398,7 +404,7 @@ export class FigmaNodeProxy {}set expanded(v: boolean) {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], { expanded: v })+ this._update({ expanded: v })}// --- Components ---@@ -443,15 +449,20 @@ export class FigmaNodeProxy {}appendChild(child: FigmaNodeProxy): void {+ assertNodeEditable(this[INTERNAL_GRAPH], this[INTERNAL_ID])+ assertNodeEditable(this[INTERNAL_GRAPH], child[INTERNAL_ID])this[INTERNAL_GRAPH].reparentNode(child[INTERNAL_ID], this[INTERNAL_ID])}insertChild(index: number, child: FigmaNodeProxy): void {+ assertNodeEditable(this[INTERNAL_GRAPH], this[INTERNAL_ID])+ assertNodeEditable(this[INTERNAL_GRAPH], child[INTERNAL_ID])this[INTERNAL_GRAPH].reparentNode(child[INTERNAL_ID], this[INTERNAL_ID])this[INTERNAL_GRAPH].reorderChild(child[INTERNAL_ID], this[INTERNAL_ID], index)}clone(): FigmaNodeProxy {+ assertNodeEditable(this[INTERNAL_GRAPH], this[INTERNAL_ID])const n = this._raw()const parentId = n.parentId ?? this[INTERNAL_API].currentPageIdconst cloned = this[INTERNAL_GRAPH].cloneTree(this[INTERNAL_ID], parentId)@@ -460,6 +471,7 @@ export class FigmaNodeProxy {}remove(): void {+ assertNodeEditable(this[INTERNAL_GRAPH], this[INTERNAL_ID])this[INTERNAL_GRAPH].deleteNode(this[INTERNAL_ID])}@@ -505,6 +517,7 @@ export class FigmaNodeProxy {}setPluginData(key: string, value: string): void {+ assertNodeEditable(this[INTERNAL_GRAPH], this[INTERNAL_ID])PluginData.setPluginData(this[INTERNAL_GRAPH], this._raw(), key, value)}@@ -517,6 +530,7 @@ export class FigmaNodeProxy {}setSharedPluginData(namespace: string, key: string, value: string): void {+ assertNodeEditable(this[INTERNAL_GRAPH], this[INTERNAL_ID])PluginData.setSharedPluginData(this[INTERNAL_GRAPH], this._raw(), namespace, key, value)}@@ -529,7 +543,7 @@ export class FigmaNodeProxy {}setFillOkHCL(color: OkHCLColor, index = 0): void {- this[INTERNAL_GRAPH].updateNode(this[INTERNAL_ID], setNodeFillOkHCL(this._raw(), index, color))+ this._update(setNodeFillOkHCL(this._raw(), index, color))}getStrokeOkHCL(index = 0): OkHCLPayload | null {@@ -537,10 +551,7 @@ export class FigmaNodeProxy {}setStrokeOkHCL(color: OkHCLColor, index = 0): void {- this[INTERNAL_GRAPH].updateNode(- this[INTERNAL_ID],- setNodeStrokeOkHCL(this._raw(), index, color)- )+ this._update(setNodeStrokeOkHCL(this._raw(), index, color))}// --- Serialization ---diff --git a/packages/core/src/io/formats/fig/export.ts b/packages/core/src/io/formats/fig/export.tsindex dc3f11aa4..ca5d0b6cd 100644--- a/packages/core/src/io/formats/fig/export.ts+++ b/packages/core/src/io/formats/fig/export.ts@@ -13,6 +13,7 @@ import type { GUID } from '@open-pencil/scene-graph/primitives'import { decodeBase64 } from '#core/bytes'import type { SkiaRenderer } from '#core/canvas'import { CANVAS_BG_COLOR, IS_BROWSER, IS_TAURI } from '#core/constants'+import { applyEnabledLibrariesPluginData } from '#core/io/formats/fig/library-metadata'import { renderThumbnail } from '#core/io/formats/raster'import { populateAllLazyFigImportRoots } from '#core/kiwi/fig/lazy-import'import {@@ -416,6 +417,7 @@ export async function exportFigFile(const documentNc = makeDocumentNodeChange(docGuid, graph.documentColorSpace)const rootNode = graph.getNode(graph.rootId)if (rootNode) Object.assign(documentNc, rootNode.source.fig.rawNodeFields)+ applyEnabledLibrariesPluginData(documentNc, graph)const nodeChanges: KiwiNodeChange[] = [documentNc]const blobs: Uint8Array[] = []diff --git a/packages/core/src/io/formats/fig/library-metadata.ts b/packages/core/src/io/formats/fig/library-metadata.tsnew file mode 100644index 000000000..4cdecb768--- /dev/null+++ b/packages/core/src/io/formats/fig/library-metadata.ts@@ -0,0 +1,34 @@+import {+ ENABLED_LIBRARIES_PLUGIN_KEY,+ mergePluginData,+ OPEN_PENCIL_PLUGIN_ID+} from '@open-pencil/fig/node-change'+import type { KiwiNodeChange } from '@open-pencil/fig/node-change'+import type { SceneGraph } from '@open-pencil/scene-graph'++export function applyEnabledLibrariesPluginData(+ documentNodeChange: KiwiNodeChange,+ graph: SceneGraph+): void {+ const rootPluginData = graph.getNode(graph.rootId)?.pluginData ?? []+ const bindings = [...graph.enabledLibraries.values()]+ const managedBinding = rootPluginData.find(+ (entry) =>+ entry.pluginId === OPEN_PENCIL_PLUGIN_ID && entry.key === ENABLED_LIBRARIES_PLUGIN_KEY+ )+ const bindingEntry =+ bindings.length > 0+ ? {+ pluginId: OPEN_PENCIL_PLUGIN_ID,+ key: ENABLED_LIBRARIES_PLUGIN_KEY,+ value: JSON.stringify(bindings)+ }+ : managedBinding+ documentNodeChange.pluginData = mergePluginData([+ ...rootPluginData.filter(+ (entry) =>+ !(entry.pluginId === OPEN_PENCIL_PLUGIN_ID && entry.key === ENABLED_LIBRARIES_PLUGIN_KEY)+ ),+ ...(bindingEntry ? [bindingEntry] : [])+ ])+}diff --git a/packages/core/src/kiwi/fig/import.ts b/packages/core/src/kiwi/fig/import.tsindex 8e6780def..5ae529b39 100644--- a/packages/core/src/kiwi/fig/import.ts+++ b/packages/core/src/kiwi/fig/import.ts@@ -4,6 +4,8 @@ import { populateAndApplyOverrides } from '@open-pencil/fig/instance-overrides'import type { InstanceNodeChange } from '@open-pencil/fig/instance-overrides'import {applyStyleRefsToFields,+ ENABLED_LIBRARIES_PLUGIN_KEY,+ getOpenPencilPluginValue,guidToString,nodeChangeToProps,shouldImportTextAsAutoSize,@@ -41,8 +43,33 @@ function applyImportedDocumentMetadata(graph: SceneGraph, docNc: NodeChange | unconst rootNode = graph.getNode(graph.rootId)if (!docNc || !rootNode) returnrootNode.source.format = 'fig'+ rootNode.pluginData = docNc.pluginData+ ? docNc.pluginData.map((entry) => ({+ pluginId: entry.pluginID,+ key: entry.key,+ value: entry.value+ }))+ : []rootNode.source.fig.rawNodeFields.strokeJoin = docNc.strokeJoinrootNode.source.fig.rawNodeFields.strokeWeight = docNc.strokeWeight+ const bindings = getOpenPencilPluginValue(docNc, ENABLED_LIBRARIES_PLUGIN_KEY)+ if (!bindings) return+ try {+ const parsed = JSON.parse(bindings) as unknown+ if (!Array.isArray(parsed)) return+ for (const entry of parsed) {+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue+ const value = entry as { libraryId?: unknown; revisionId?: unknown; enabled?: unknown }+ if (typeof value.libraryId !== 'string' || typeof value.revisionId !== 'string') continue+ graph.enabledLibraries.set(value.libraryId, {+ libraryId: value.libraryId,+ revisionId: value.revisionId,+ enabled: value.enabled === true+ })+ }+ } catch (error) {+ console.warn('Ignored malformed OpenPencil library metadata', error)+ }}function assetRefKey(assetRef: AssetRef): string {diff --git a/packages/core/src/kiwi/fig/parse/portable-data.ts b/packages/core/src/kiwi/fig/parse/portable-data.tsnew file mode 100644index 000000000..cbf8a8f17--- /dev/null+++ b/packages/core/src/kiwi/fig/parse/portable-data.ts@@ -0,0 +1,16 @@+import type {+ DocumentColorSpace,+ SceneNode,+ Variable,+ VariableCollection+} from '@open-pencil/scene-graph'++export interface PortableSceneGraphData {+ rootId: string+ nodes: Array<[string, SceneNode]>+ images: Array<[string, Uint8Array]>+ variables: Array<[string, Variable]>+ variableCollections: Array<[string, VariableCollection]>+ activeMode: Array<[string, string]>+ documentColorSpace: DocumentColorSpace+}diff --git a/packages/core/src/kiwi/fig/parse/transfer.ts b/packages/core/src/kiwi/fig/parse/transfer.tsindex 4fe0154b8..ca26b35fb 100644--- a/packages/core/src/kiwi/fig/parse/transfer.ts+++ b/packages/core/src/kiwi/fig/parse/transfer.ts@@ -1,13 +1,9 @@import type { InstanceNodeChange } from '@open-pencil/fig/instance-overrides'import { SceneGraph } from '@open-pencil/scene-graph'-import type {- SceneNode,- Variable,- VariableCollection,- DocumentColorSpace-} from '@open-pencil/scene-graph'+import type { EnabledLibraryBinding } from '@open-pencil/scene-graph'import { getLazyFigImportContext, setLazyFigImportContext } from '#core/kiwi/fig/lazy-import'+import type { PortableSceneGraphData } from '#core/kiwi/fig/parse/portable-data'export interface SerializedLazyFigImportContext {changeMap: Array<[string, InstanceNodeChange]>@@ -16,17 +12,11 @@ export interface SerializedLazyFigImportContext {populatedRootIds: string[]}-export interface SerializedSceneGraph {- rootId: string- nodes: Array<[string, SceneNode]>- images: Array<[string, Uint8Array]>- variables: Array<[string, Variable]>- variableCollections: Array<[string, VariableCollection]>- activeMode: Array<[string, string]>+export interface SerializedSceneGraph extends PortableSceneGraphData {instanceIndex: Array<[string, string[]]>figKiwiVersion: number | nullfigSchemaDeflated: Uint8Array | null- documentColorSpace: DocumentColorSpace+ enabledLibraries?: Array<[string, EnabledLibraryBinding]>lazyFigImport?: SerializedLazyFigImportContext}@@ -43,6 +33,7 @@ export function serializeSceneGraph(graph: SceneGraph): SerializedSceneGraph {figKiwiVersion: graph.figKiwiVersion,figSchemaDeflated: graph.figSchemaDeflated,documentColorSpace: graph.documentColorSpace,+ enabledLibraries: [...graph.enabledLibraries],lazyFigImport: lazyFigImport? {changeMap: [...lazyFigImport.changeMap],@@ -107,6 +98,7 @@ export function cloneSceneGraphForFigExport(graph: SceneGraph): SceneGraph {cloned.figKiwiVersion = graph.figKiwiVersioncloned.figSchemaDeflated = graph.figSchemaDeflatedcloned.documentColorSpace = graph.documentColorSpace+ cloned.enabledLibraries = new Map(graph.enabledLibraries)const lazyFigImport = getLazyFigImportContext(graph)if (lazyFigImport) {@@ -132,6 +124,7 @@ export function deserializeSceneGraph(data: SerializedSceneGraph): SceneGraph {graph.figKiwiVersion = data.figKiwiVersiongraph.figSchemaDeflated = data.figSchemaDeflatedgraph.documentColorSpace = data.documentColorSpace+ graph.enabledLibraries = data.enabledLibraries ? new Map(data.enabledLibraries) : new Map()if (data.lazyFigImport) {setLazyFigImportContext(graph, {changeMap: new Map(data.lazyFigImport.changeMap),diff --git a/packages/core/src/library/asset-keys.ts b/packages/core/src/library/asset-keys.tsnew file mode 100644index 000000000..67c190c5f--- /dev/null+++ b/packages/core/src/library/asset-keys.ts@@ -0,0 +1,73 @@+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'++import { isValidLibraryAssetKey } from './identity'++export interface AssetKeyAssignment {+ nodeId: string+ assetKey: string+ existing: boolean+}++function normalizeAssetKey(name: string): string {+ const normalized = name+ .trim()+ .toLowerCase()+ .replace(/[^a-z0-9._:/-]+/g, '-')+ .replace(/^-+|-+$/g, '')+ return normalized || 'component'+}++export function publishableLibraryRoots(+ graph: SceneGraph+): Array<SceneNode & { type: 'COMPONENT' | 'COMPONENT_SET' }> {+ return [...graph.getAllNodes()].filter(+ (node): node is SceneNode & { type: 'COMPONENT' | 'COMPONENT_SET' } => {+ if (node.type !== 'COMPONENT' && node.type !== 'COMPONENT_SET') return false+ if (node.librarySource?.readOnly) return false+ const parent = node.parentId ? graph.getNode(node.parentId) : undefined+ return parent?.type !== 'COMPONENT_SET'+ }+ )+}++function publishedRoots(graph: SceneGraph, assetNodeIds?: string[]): SceneNode[] {+ if (!assetNodeIds) return publishableLibraryRoots(graph)+ const selected = new Set(assetNodeIds)+ return publishableLibraryRoots(graph).filter((node) => selected.has(node.id))+}++export function ensureLibraryAssetKeys(+ graph: SceneGraph,+ assetNodeIds?: string[]+): AssetKeyAssignment[] {+ const roots = publishedRoots(graph, assetNodeIds)+ const used = new Set(+ [...graph.getAllNodes()].flatMap((node) =>+ node.componentKey && isValidLibraryAssetKey(node.componentKey) ? [node.componentKey] : []+ )+ )+ return roots.map((node) => {+ if (node.componentKey && isValidLibraryAssetKey(node.componentKey)) {+ return { nodeId: node.id, assetKey: node.componentKey, existing: true }+ }+ const base = normalizeAssetKey(node.name)+ let assetKey = base+ let suffix = 2+ while (used.has(assetKey)) assetKey = `${base}-${suffix++}`+ used.add(assetKey)+ graph.updateNode(node.id, { componentKey: assetKey })+ return { nodeId: node.id, assetKey, existing: false }+ })+}++export function duplicateLibraryAssetKeys(graph: SceneGraph): Map<string, string[]> {+ const byKey = new Map<string, string[]>()+ for (const node of graph.getAllNodes()) {+ if (node.type !== 'COMPONENT' && node.type !== 'COMPONENT_SET') continue+ if (!node.componentKey) continue+ const ids = byKey.get(node.componentKey) ?? []+ ids.push(node.id)+ byKey.set(node.componentKey, ids)+ }+ return new Map([...byKey].filter(([, ids]) => ids.length > 1))+}diff --git a/packages/core/src/library/definitions.ts b/packages/core/src/library/definitions.tsnew file mode 100644index 000000000..f66e42aec--- /dev/null+++ b/packages/core/src/library/definitions.ts@@ -0,0 +1,20 @@+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'++export function findLibraryDefinition(+ graph: SceneGraph,+ libraryId: string,+ assetKey: string,+ revisionId: string+): SceneNode | undefined {+ for (const node of graph.getAllNodes()) {+ const identity = node.librarySource?.identity+ if (+ identity?.libraryId === libraryId &&+ identity.assetKey === assetKey &&+ identity.revisionId === revisionId+ ) {+ return node+ }+ }+ return undefined+}diff --git a/packages/core/src/library/diff.ts b/packages/core/src/library/diff.tsnew file mode 100644index 000000000..3c33734c1--- /dev/null+++ b/packages/core/src/library/diff.ts@@ -0,0 +1,28 @@+import type { ComponentLibraryManifest, LibraryAssetChange } from './types'++export function diffLibraryManifests(+ previous: ComponentLibraryManifest,+ next: ComponentLibraryManifest+): LibraryAssetChange[] {+ if (previous.libraryId !== next.libraryId) {+ throw new Error('Cannot diff manifests from different libraries')+ }+ const previousByKey = new Map(previous.assets.map((asset) => [asset.key, asset]))+ const nextByKey = new Map(next.assets.map((asset) => [asset.key, asset]))+ const changes: LibraryAssetChange[] = []++ for (const asset of next.assets) {+ const oldAsset = previousByKey.get(asset.key)+ if (!oldAsset) {+ changes.push({ kind: 'added', asset })+ } else if (oldAsset.contentHash !== asset.contentHash) {+ changes.push({ kind: 'modified', previous: oldAsset, asset })+ } else if (oldAsset.name !== asset.name || oldAsset.description !== asset.description) {+ changes.push({ kind: 'renamed', previous: oldAsset, asset })+ }+ }+ for (const asset of previous.assets) {+ if (!nextByKey.has(asset.key)) changes.push({ kind: 'removed', asset })+ }+ return changes+}diff --git a/packages/core/src/library/hash.ts b/packages/core/src/library/hash.tsnew file mode 100644index 000000000..466a3e701--- /dev/null+++ b/packages/core/src/library/hash.ts@@ -0,0 +1,38 @@+const textEncoder = new TextEncoder()++function canonicalize(value: unknown): unknown {+ if (value instanceof Uint8Array) return { $bytes: [...value] }+ if (Array.isArray(value)) return value.map(canonicalize)+ if (value && typeof value === 'object') {+ return Object.fromEntries(+ Object.entries(value)+ .filter(([, entry]) => entry !== undefined)+ .sort(([left], [right]) => {+ if (left < right) return -1+ if (left > right) return 1+ return 0+ })+ .map(([key, entry]) => [key, canonicalize(entry)])+ )+ }+ return value+}++export function canonicalJSONString(value: unknown): string {+ return JSON.stringify(canonicalize(value))+}++function toHex(bytes: Uint8Array): string {+ return [...bytes].map((byte) => byte.toString(16).padStart(2, '0')).join('')+}++export async function contentHash(value: unknown): Promise<string> {+ if (typeof crypto === 'undefined') {+ throw new TypeError('Web Crypto is required to hash library content')+ }+ const digest = await crypto.subtle.digest(+ 'SHA-256',+ textEncoder.encode(canonicalJSONString(value))+ )+ return toHex(new Uint8Array(digest))+}diff --git a/packages/core/src/library/identity.ts b/packages/core/src/library/identity.tsnew file mode 100644index 000000000..3e6a0d68c--- /dev/null+++ b/packages/core/src/library/identity.ts@@ -0,0 +1,24 @@+const LIBRARY_ID_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/+const ASSET_KEY_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._:/-]{0,255}$/++export function isValidLibraryId(value: string): boolean {+ return LIBRARY_ID_PATTERN.test(value)+}++export function isValidLibraryAssetKey(value: string): boolean {+ return ASSET_KEY_PATTERN.test(value)+}++export function assertLibraryId(value: string): void {+ if (!isValidLibraryId(value)) throw new Error(`Invalid library ID: ${value}`)+}++export function assertLibraryAssetKey(value: string): void {+ if (!isValidLibraryAssetKey(value)) throw new Error(`Invalid library asset key: ${value}`)+}++export function libraryAssetIdentityKey(libraryId: string, assetKey: string): string {+ assertLibraryId(libraryId)+ assertLibraryAssetKey(assetKey)+ return `${libraryId}\u0000${assetKey}`+}diff --git a/packages/core/src/library/index.ts b/packages/core/src/library/index.tsnew file mode 100644index 000000000..a615cc8fd--- /dev/null+++ b/packages/core/src/library/index.ts@@ -0,0 +1,17 @@+export * from './asset-keys'+export * from './definitions'+export * from './diff'+export * from './hash'+export * from './identity'+export * from './instance-updates'+export * from './materialize'+export * from './preview'+export * from './registry'+export * from './revision'+export * from './selective'+export * from './serialization'+export * from './source-publication'+export * from './snapshot'+export type * from './types'+export * from './update'+export * from './validation'diff --git a/packages/core/src/library/instance-updates.ts b/packages/core/src/library/instance-updates.tsnew file mode 100644index 000000000..0471fecb2--- /dev/null+++ b/packages/core/src/library/instance-updates.ts@@ -0,0 +1,78 @@+import type { SceneGraph } from '@open-pencil/scene-graph'++import { findLibraryDefinition } from './definitions'+import type { ComponentLibraryRevision, LibraryAssetDescriptor } from './types'+import type { LibraryInstanceUpdate } from './update'++export function libraryAssetKeyForComponent(graph: SceneGraph, componentId: string): string | null {+ let node = graph.getNode(componentId)+ while (node) {+ const identity = node.librarySource?.identity+ if (identity) return identity.assetKey+ node = node.parentId ? graph.getNode(node.parentId) : undefined+ }+ return null+}++function targetComponentId(+ graph: SceneGraph,+ descriptor: LibraryAssetDescriptor,+ revision: ComponentLibraryRevision,+ previousComponentId: string+): { id: string; fallback: boolean } | null {+ const root = findLibraryDefinition(+ graph,+ revision.manifest.libraryId,+ descriptor.key,+ revision.manifest.revisionId+ )+ if (!root) return null+ const candidates =+ root.type === 'COMPONENT'+ ? [root]+ : graph.getChildren(root.id).filter((node) => node.type === 'COMPONENT')+ const previous = graph.getNode(previousComponentId)+ if (!previous) return null+ const exact = candidates.find((candidate) => {+ const entries = Object.entries(previous.componentPropertyValues)+ return (+ entries.length === Object.keys(candidate.componentPropertyValues).length &&+ entries.every(([name, value]) => candidate.componentPropertyValues[name] === value)+ )+ })+ if (candidates.length === 0) return null+ const fallback = [...candidates].sort((left, right) => left.y - right.y || left.x - right.x)[0]+ const target = exact ?? fallback+ return { id: target.id, fallback: !exact }+}++export function planOutdatedLibraryInstances(+ graph: SceneGraph,+ revision: ComponentLibraryRevision,+ assetKeys?: ReadonlySet<string>,+ instanceIds?: ReadonlySet<string>+): LibraryInstanceUpdate[] {+ const descriptors = new Map(revision.manifest.assets.map((asset) => [asset.key, asset]))+ const updates: LibraryInstanceUpdate[] = []+ for (const instance of graph.getAllNodes()) {+ if (instance.type !== 'INSTANCE' || !instance.componentId) continue+ if (instanceIds && !instanceIds.has(instance.id)) continue+ const component = graph.getNode(instance.componentId)+ const identity = component?.librarySource?.identity+ if (!identity || identity.libraryId !== revision.manifest.libraryId) continue+ const assetKey = libraryAssetKeyForComponent(graph, component.id)+ if (!assetKey || (assetKeys && !assetKeys.has(assetKey))) continue+ if (identity.revisionId === revision.manifest.revisionId) continue+ const descriptor = descriptors.get(assetKey)+ if (!descriptor) continue+ const target = targetComponentId(graph, descriptor, revision, component.id)+ if (!target) continue+ updates.push({+ instanceId: instance.id,+ previousComponentId: component.id,+ componentId: target.id,+ fallback: target.fallback+ })+ }+ return updates+}diff --git a/packages/core/src/library/materialize.ts b/packages/core/src/library/materialize.tsnew file mode 100644index 000000000..507af843c--- /dev/null+++ b/packages/core/src/library/materialize.ts@@ -0,0 +1,178 @@+import { cloneNodeProps, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'++import { findLibraryDefinition } from './definitions'+import { assertLibraryAssetKey, assertLibraryId, libraryAssetIdentityKey } from './identity'+import type { ComponentLibraryRevision, LibraryAssetDescriptor } from './types'++const INTERNAL_LIBRARY_PAGE_NAME = 'OpenPencil library definitions'++export interface MaterializedLibraryAsset {+ componentId: string+ componentSetId: string | null+ pageId: string+ created: boolean+}++function getInternalLibraryPage(graph: SceneGraph): SceneNode {+ const existing = graph+ .getPages(true)+ .find((page) => page.internalOnly && page.name === INTERNAL_LIBRARY_PAGE_NAME)+ if (existing) return existing+ const page = graph.addPage(INTERNAL_LIBRARY_PAGE_NAME)+ graph.updateNode(page.id, { internalOnly: true, visible: false, locked: true })+ return graph.getNode(page.id) ?? page+}++export function libraryDependencyRoots(+ revision: ComponentLibraryRevision,+ descriptor: LibraryAssetDescriptor+): SceneNode[] {+ const root = revision.graph.getNode(descriptor.sourceNodeId)+ if (!root) throw new Error(`Library asset source is missing: ${descriptor.key}`)+ const roots = new Map([[root.id, root]])+ const visited = new Set<string>()+ const pending = [root.id]+ while (pending.length > 0) {+ const id = pending.pop()+ if (!id || visited.has(id)) continue+ visited.add(id)+ const node = revision.graph.getNode(id)+ if (!node) continue+ pending.push(...node.childIds)+ if (!node.componentId) continue+ const component = revision.graph.getNode(node.componentId)+ if (!component) continue+ let definitionRoot = component+ const parent = component.parentId ? revision.graph.getNode(component.parentId) : undefined+ if (parent?.type === 'COMPONENT_SET') definitionRoot = parent+ roots.set(definitionRoot.id, definitionRoot)+ pending.push(definitionRoot.id)+ }+ return [...roots.values()]+}++export function copyLibraryTree(+ source: SceneGraph,+ target: SceneGraph,+ sourceId: string,+ parentId: string,+ mappedIds: Map<string, string>+): void {+ if (mappedIds.has(sourceId)) return+ const node = source.getNode(sourceId)+ if (!node) return+ const created = target.createNode(node.type, parentId, cloneNodeProps(node, node.componentId))+ mappedIds.set(sourceId, created.id)+ for (const childId of node.childIds)+ copyLibraryTree(source, target, childId, created.id, mappedIds)+}++function markDefinitions(+ graph: SceneGraph,+ revision: ComponentLibraryRevision,+ mappedIds: Map<string, string>+): void {+ const descriptorsBySourceId = new Map(+ revision.manifest.assets.map((asset) => [asset.sourceNodeId, asset])+ )+ for (const [sourceId, targetId] of mappedIds) {+ const target = graph.getNode(targetId)+ if (!target) continue+ const componentId = target.componentId ? mappedIds.get(target.componentId) : undefined+ const descriptor = descriptorsBySourceId.get(sourceId)+ const source = revision.graph.getNode(sourceId)+ const sourceAssetKey =+ descriptor?.key ??+ (source?.type === 'COMPONENT' || source?.type === 'COMPONENT_SET'+ ? (source.componentKey ?? source.sourceLibraryKey ?? source.publishId)+ : null)+ graph.updateNode(targetId, {+ componentId: componentId ?? target.componentId,+ locked: true,+ librarySource: sourceAssetKey+ ? {+ identity: {+ libraryId: revision.manifest.libraryId,+ assetKey: sourceAssetKey,+ revisionId: revision.manifest.revisionId+ },+ sourceNodeId: sourceId,+ readOnly: true+ }+ : target.librarySource+ })+ }+}++function copyImages(source: SceneGraph, target: SceneGraph, mappedIds: Map<string, string>): void {+ const hashes = new Set<string>()+ for (const sourceId of mappedIds.keys()) {+ const node = source.getNode(sourceId)+ const fills = [+ ...(node?.fills ?? []),+ ...(node?.fillGeometry.flatMap((geometry) => geometry.fills ?? []) ?? [])+ ]+ for (const fill of fills) {+ if (fill.type === 'IMAGE' && fill.imageHash) hashes.add(fill.imageHash)+ }+ }+ for (const hash of hashes) {+ const image = source.images.get(hash)+ if (image) target.images.set(hash, new Uint8Array(image))+ }+}++function defaultComponent(graph: SceneGraph, root: SceneNode): SceneNode | undefined {+ if (root.type === 'COMPONENT') return root+ return root.childIds+ .flatMap((id) => {+ const child = graph.getNode(id)+ return child?.type === 'COMPONENT' ? [child] : []+ })+ .sort((left, right) => left.y - right.y || left.x - right.x)[0]+}++export function materializeLibraryAsset(+ consumer: SceneGraph,+ revision: ComponentLibraryRevision,+ assetKey: string+): MaterializedLibraryAsset {+ const { libraryId, revisionId } = revision.manifest+ assertLibraryId(libraryId)+ assertLibraryAssetKey(assetKey)+ consumer.enabledLibraries.set(libraryId, { libraryId, revisionId, enabled: true })+ const existing = findLibraryDefinition(consumer, libraryId, assetKey, revisionId)+ if (existing) {+ const component = defaultComponent(consumer, existing)+ if (!component) throw new Error(`Materialized asset has no component: ${assetKey}`)+ return {+ componentId: component.id,+ componentSetId: existing.type === 'COMPONENT_SET' ? existing.id : null,+ pageId: existing.parentId ?? consumer.rootId,+ created: false+ }+ }++ const descriptor = revision.manifest.assets.find((asset) => asset.key === assetKey)+ if (!descriptor)+ throw new Error(`Library asset not found: ${libraryAssetIdentityKey(libraryId, assetKey)}`)+ const page = getInternalLibraryPage(consumer)+ const mappedIds = new Map<string, string>()+ for (const root of libraryDependencyRoots(revision, descriptor)) {+ copyLibraryTree(revision.graph, consumer, root.id, page.id, mappedIds)+ }+ markDefinitions(consumer, revision, mappedIds)+ copyImages(revision.graph, consumer, mappedIds)++ const rootId = mappedIds.get(descriptor.sourceNodeId)+ const root = rootId ? consumer.getNode(rootId) : undefined+ if (!root) throw new Error(`Failed to materialize library asset: ${assetKey}`)+ const component = defaultComponent(consumer, root)+ if (!component) throw new Error(`Library asset has no component: ${assetKey}`)+ return {+ componentId: component.id,+ componentSetId: root.type === 'COMPONENT_SET' ? root.id : null,+ pageId: page.id,+ created: true+ }+}diff --git a/packages/core/src/library/preview.ts b/packages/core/src/library/preview.tsnew file mode 100644index 000000000..509b30e1b--- /dev/null+++ b/packages/core/src/library/preview.ts@@ -0,0 +1,146 @@+import { cloneNodeProps, SceneGraph, type SceneNode } from '@open-pencil/scene-graph'++import { reapplyInstanceComponentProperties } from '#core/editor/components/properties'++import { libraryAssetKeyForComponent } from './instance-updates'+import { libraryDependencyRoots } from './materialize'+import type { ComponentLibraryRevision } from './types'++export interface LibraryUpdatePreview {+ graph: SceneGraph+ currentNodeId: string+ updatedNodeId: string+ fallback: boolean+}++function copyPreviewDefinitions(+ source: SceneGraph,+ target: SceneGraph,+ components: SceneNode[],+ pageId: string+): Map<string, string> {+ const mapped = new Map<string, string>()+ const copy = (node: SceneNode, parentId: string): string => {+ const existing = mapped.get(node.id)+ if (existing) return existing+ const created = target.createNode(node.type, parentId, cloneNodeProps(node, node.componentId))+ mapped.set(node.id, created.id)+ for (const child of source.getChildren(node.id)) copy(child, created.id)+ return created.id+ }+ for (const component of components) copy(component, pageId)+ for (const [sourceId, targetId] of mapped) {+ const componentId = source.getNode(sourceId)?.componentId+ const remapped = componentId ? mapped.get(componentId) : null+ if (remapped) target.updateNode(targetId, { componentId: remapped })+ }+ return mapped+}++function consumerDependencyRoots(graph: SceneGraph, component: SceneNode): SceneNode[] {+ const roots = new Map([[component.id, component]])+ const visited = new Set<string>()+ const pending = [component.id]+ while (pending.length > 0) {+ const id = pending.pop()+ if (!id || visited.has(id)) continue+ visited.add(id)+ const node = graph.getNode(id)+ if (!node) continue+ pending.push(...node.childIds)+ if (!node.componentId) continue+ const dependency = graph.getNode(node.componentId)+ if (!dependency) continue+ const parent = dependency.parentId ? graph.getNode(dependency.parentId) : undefined+ const root = parent?.type === 'COMPONENT_SET' ? parent : dependency+ roots.set(root.id, root)+ pending.push(root.id)+ }+ return [...roots.values()]+}++function revisionComponents(revision: ComponentLibraryRevision, assetKey: string): SceneNode[] {+ const descriptor = revision.manifest.assets.find((asset) => asset.key === assetKey)+ const root = descriptor ? revision.graph.getNode(descriptor.sourceNodeId) : null+ if (!root) return []+ return root.type === 'COMPONENT'+ ? [root]+ : revision.graph.getChildren(root.id).filter((node) => node.type === 'COMPONENT')+}++function sameVariant(left: SceneNode, right: SceneNode): boolean {+ const entries = Object.entries(left.componentPropertyValues)+ return (+ entries.length === Object.keys(right.componentPropertyValues).length &&+ entries.every(([name, value]) => right.componentPropertyValues[name] === value)+ )+}++function propertyDefinitions(graph: SceneGraph, component: SceneNode) {+ const parent = component.parentId ? graph.getNode(component.parentId) : null+ return [+ ...(parent?.type === 'COMPONENT_SET' ? parent.componentPropertyDefinitions : []),+ ...component.componentPropertyDefinitions+ ]+}++function createPreviewInstance(+ graph: SceneGraph,+ pageId: string,+ componentId: string,+ source: SceneNode+): string {+ const instance = graph.createInstance(componentId, pageId, {+ ...cloneNodeProps(source, componentId),+ componentId,+ x: 0,+ y: 0+ })+ if (!instance) throw new Error('Preview instance could not be created')+ return instance.id+}++export function createLibraryUpdatePreview(+ consumer: SceneGraph,+ instanceId: string,+ latest: ComponentLibraryRevision+): LibraryUpdatePreview {+ const instance = consumer.getNode(instanceId)+ if (instance?.type !== 'INSTANCE' || !instance.componentId)+ throw new Error('Linked instance not found')+ const currentComponent = consumer.getNode(instance.componentId)+ if (!currentComponent) throw new Error('Linked component not found')+ const assetKey = libraryAssetKeyForComponent(consumer, currentComponent.id)+ if (!assetKey) throw new Error('Linked library asset not found')+ const candidates = revisionComponents(latest, assetKey)+ const exact = candidates.find((candidate) => sameVariant(currentComponent, candidate))+ if (candidates.length === 0) throw new Error('Updated library component not found')+ const fallback = [...candidates].sort((left, right) => left.y - right.y || left.x - right.x)[0]+ const updatedComponent = exact ?? fallback++ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const latestRoots = latest.manifest.assets.flatMap((descriptor) =>+ libraryDependencyRoots(latest, descriptor)+ )+ const currentRoots = consumerDependencyRoots(consumer, currentComponent)+ const currentMapped = copyPreviewDefinitions(consumer, graph, currentRoots, page.id)+ const currentComponentId = currentMapped.get(currentComponent.id)+ if (!currentComponentId) throw new Error('Current preview definition could not be copied')+ const latestMapped = copyPreviewDefinitions(latest.graph, graph, latestRoots, page.id)+ const updatedComponentId = latestMapped.get(updatedComponent.id)+ if (!updatedComponentId) throw new Error('Updated preview definition could not be copied')+ graph.updateNode(currentComponentId, {+ componentPropertyDefinitions: propertyDefinitions(consumer, currentComponent)+ })+ graph.updateNode(updatedComponentId, {+ componentPropertyDefinitions: propertyDefinitions(latest.graph, updatedComponent)+ })+ const currentNodeId = createPreviewInstance(graph, page.id, currentComponentId, instance)+ const updatedNodeId = createPreviewInstance(graph, page.id, updatedComponentId, instance)+ reapplyInstanceComponentProperties({ graph }, currentNodeId)+ reapplyInstanceComponentProperties({ graph }, updatedNodeId)+ graph.updateNode(currentComponentId, { internalOnly: true })+ graph.updateNode(updatedComponentId, { internalOnly: true })+ return { graph, currentNodeId, updatedNodeId, fallback: !exact }+}diff --git a/packages/core/src/library/registry.ts b/packages/core/src/library/registry.tsnew file mode 100644index 000000000..87ba30471--- /dev/null+++ b/packages/core/src/library/registry.ts@@ -0,0 +1,60 @@+import { createLibraryRevision } from './revision'+import { deserializeLibraryRevision, serializeLibraryRevision } from './serialization'+import type {+ ComponentLibraryRevision,+ LibraryCatalog,+ LibrarySummary,+ PublishLibraryInput+} from './types'++function revisionKey(libraryId: string, revisionId: string): string {+ return `${libraryId}\u0000${revisionId}`+}++export class MemoryLibraryCatalog implements LibraryCatalog {+ readonly #latest = new Map<string, string>()+ readonly #revisions = new Map<string, ComponentLibraryRevision>()++ async listLibraries(): Promise<LibrarySummary[]> {+ return [...this.#latest].flatMap(([libraryId, revisionId]) => {+ const revision = this.#revisions.get(revisionKey(libraryId, revisionId))+ return revision+ ? [+ {+ libraryId,+ name: revision.manifest.name,+ latestRevisionId: revisionId,+ publishedAt: revision.manifest.publishedAt,+ assetCount: revision.manifest.assets.length+ }+ ]+ : []+ })+ }++ async getRevision(libraryId: string, revisionId?: string): Promise<ComponentLibraryRevision> {+ const resolvedRevisionId = revisionId ?? this.#latest.get(libraryId)+ const revision = resolvedRevisionId+ ? this.#revisions.get(revisionKey(libraryId, resolvedRevisionId))+ : undefined+ if (!revision)+ throw new Error(`Library revision not found: ${libraryId}/${revisionId ?? 'latest'}`)+ return deserializeLibraryRevision(serializeLibraryRevision(revision))+ }++ async publishRevision(input: PublishLibraryInput): Promise<ComponentLibraryRevision> {+ const latestRevisionId = this.#latest.get(input.libraryId) ?? null+ if ((input.previousRevisionId ?? null) !== latestRevisionId) {+ throw new Error('Library revision conflict: latest revision has changed')+ }+ const revision = await createLibraryRevision(input)+ const currentLatestRevisionId = this.#latest.get(input.libraryId) ?? null+ if ((input.previousRevisionId ?? null) !== currentLatestRevisionId) {+ throw new Error('Library revision conflict: latest revision has changed')+ }+ const stored = deserializeLibraryRevision(serializeLibraryRevision(revision))+ this.#revisions.set(revisionKey(input.libraryId, revision.manifest.revisionId), stored)+ this.#latest.set(input.libraryId, revision.manifest.revisionId)+ return deserializeLibraryRevision(serializeLibraryRevision(stored))+ }+}diff --git a/packages/core/src/library/revision.ts b/packages/core/src/library/revision.tsnew file mode 100644index 000000000..af2857495--- /dev/null+++ b/packages/core/src/library/revision.ts@@ -0,0 +1,34 @@+import { contentHash } from './hash'+import { assertLibraryId } from './identity'+import { describeSnapshotAssets, extractLibrarySnapshot } from './snapshot'+import { COMPONENT_LIBRARY_SCHEMA_VERSION } from './types'+import type {+ ComponentLibraryManifest,+ ComponentLibraryRevision,+ PublishLibraryInput+} from './types'++export async function createLibraryRevision(+ input: PublishLibraryInput+): Promise<ComponentLibraryRevision> {+ assertLibraryId(input.libraryId)+ const snapshot = extractLibrarySnapshot(input.graph, input.assetNodeIds)+ const assets = await describeSnapshotAssets(snapshot)+ const revisionId = await contentHash({+ schemaVersion: COMPONENT_LIBRARY_SCHEMA_VERSION,+ libraryId: input.libraryId,+ previousRevisionId: input.previousRevisionId ?? null,+ assets: assets.map(({ thumbnail: _, sourceNodeId: __, ...asset }) => asset)+ })+ const manifest: ComponentLibraryManifest = {+ schemaVersion: COMPONENT_LIBRARY_SCHEMA_VERSION,+ libraryId: input.libraryId,+ name: input.name.trim(),+ revisionId,+ previousRevisionId: input.previousRevisionId ?? null,+ publishedAt: input.publishedAt ?? new Date().toISOString(),+ description: input.description?.trim() ?? '',+ assets+ }+ return { manifest, graph: snapshot.graph }+}diff --git a/packages/core/src/library/selective.ts b/packages/core/src/library/selective.tsnew file mode 100644index 000000000..74a6ef600--- /dev/null+++ b/packages/core/src/library/selective.ts@@ -0,0 +1,100 @@+import { SceneGraph } from '@open-pencil/scene-graph'++import { diffLibraryManifests } from './diff'+import { copyLibraryTree, libraryDependencyRoots } from './materialize'+import { createLibraryRevision } from './revision'+import type {+ ComponentLibraryRevision,+ LibraryAssetChange,+ LibraryAssetDescriptor,+ PublishLibraryInput+} from './types'++export interface SelectiveLibraryRevisionInput extends Omit<+ PublishLibraryInput,+ 'graph' | 'assetNodeIds' | 'libraryId' | 'previousRevisionId'+> {+ previous: ComponentLibraryRevision+ sourceGraph: SceneGraph+ selectedAssetKeys: ReadonlySet<string>+}++export async function discoverPublishableLibraryChanges(+ previous: ComponentLibraryRevision,+ sourceGraph: SceneGraph+): Promise<{ current: ComponentLibraryRevision; changes: LibraryAssetChange[] }> {+ const current = await createLibraryRevision({+ libraryId: previous.manifest.libraryId,+ name: previous.manifest.name,+ graph: sourceGraph,+ previousRevisionId: previous.manifest.revisionId,+ publishedAt: previous.manifest.publishedAt+ })+ return { current, changes: diffLibraryManifests(previous.manifest, current.manifest) }+}++function copyAssets(+ target: SceneGraph,+ source: ComponentLibraryRevision,+ assets: LibraryAssetDescriptor[],+ pageId: string,+ mappedIds = new Map<string, string>()+): string[] {+ const roots = new Map(+ assets.flatMap((asset) =>+ libraryDependencyRoots(source, asset).map((root) => [root.id, root] as const)+ )+ )+ for (const root of roots.values())+ copyLibraryTree(source.graph, target, root.id, pageId, mappedIds)+ for (const [sourceId, targetId] of mappedIds) {+ const sourceNode = source.graph.getNode(sourceId)+ const componentId = sourceNode?.componentId ? mappedIds.get(sourceNode.componentId) : null+ if (componentId) target.updateNode(targetId, { componentId })+ }+ for (const [hash, bytes] of source.graph.images) target.images.set(hash, new Uint8Array(bytes))+ return assets.flatMap((asset) => {+ const id = mappedIds.get(asset.sourceNodeId)+ return id ? [id] : []+ })+}++export async function createSelectiveLibraryRevision(+ input: SelectiveLibraryRevisionInput+): Promise<ComponentLibraryRevision> {+ const { current, changes } = await discoverPublishableLibraryChanges(+ input.previous,+ input.sourceGraph+ )+ const selectedChanges = changes.filter((change) => input.selectedAssetKeys.has(change.asset.key))+ if (selectedChanges.length === 0) throw new Error('No library changes selected')++ const selectedKeys = new Set(selectedChanges.map((change) => change.asset.key))+ const removedKeys = new Set(+ selectedChanges.flatMap((change) => (change.kind === 'removed' ? [change.asset.key] : []))+ )+ const currentAssets = current.manifest.assets.filter((asset) => selectedKeys.has(asset.key))+ const retainedAssets = input.previous.manifest.assets.filter(+ (asset) => !selectedKeys.has(asset.key) && !removedKeys.has(asset.key)+ )+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const currentNodeIds = copyAssets(graph, current, currentAssets, page.id)+ const currentKeys = new Set(currentAssets.map((asset) => asset.key))+ const retainedWithoutCurrentDependencies = retainedAssets.filter(+ (asset) => !currentKeys.has(asset.key)+ )+ const assetNodeIds = [+ ...currentNodeIds,+ ...copyAssets(graph, input.previous, retainedWithoutCurrentDependencies, page.id)+ ]+ return createLibraryRevision({+ libraryId: input.previous.manifest.libraryId,+ name: input.name,+ graph,+ assetNodeIds,+ previousRevisionId: input.previous.manifest.revisionId,+ description: input.description,+ publishedAt: input.publishedAt+ })+}diff --git a/packages/core/src/library/serialization.ts b/packages/core/src/library/serialization.tsnew file mode 100644index 000000000..001121284--- /dev/null+++ b/packages/core/src/library/serialization.ts@@ -0,0 +1,58 @@+import { SceneGraph } from '@open-pencil/scene-graph'++import type { PortableSceneGraphData } from '#core/kiwi/fig/parse/portable-data'++import type { ComponentLibraryManifest, ComponentLibraryRevision } from './types'++export type SerializedLibraryGraph = PortableSceneGraphData++export interface SerializedComponentLibraryRevision {+ manifest: ComponentLibraryManifest+ graph: SerializedLibraryGraph+}++export function serializeLibraryRevision(+ revision: ComponentLibraryRevision+): SerializedComponentLibraryRevision {+ return {+ manifest: structuredClone(revision.manifest),+ graph: {+ rootId: revision.graph.rootId,+ nodes: [...revision.graph.nodes].map(([id, node]) => [id, structuredClone(node)]),+ images: [...revision.graph.images].map(([hash, bytes]) => [hash, new Uint8Array(bytes)]),+ variables: [...revision.graph.variables].map(([id, variable]) => [+ id,+ structuredClone(variable)+ ]),+ variableCollections: [...revision.graph.variableCollections].map(([id, collection]) => [+ id,+ structuredClone(collection)+ ]),+ activeMode: [...revision.graph.activeMode],+ documentColorSpace: revision.graph.documentColorSpace+ }+ }+}++export function deserializeLibraryRevision(+ revision: SerializedComponentLibraryRevision+): ComponentLibraryRevision {+ const graph = new SceneGraph()+ graph.rootId = revision.graph.rootId+ graph.nodes = new Map(revision.graph.nodes.map(([id, node]) => [id, structuredClone(node)]))+ graph.images = new Map(+ revision.graph.images.map(([hash, bytes]) => [hash, new Uint8Array(bytes)])+ )+ graph.variables = new Map(revision.graph.variables)+ graph.variableCollections = new Map(revision.graph.variableCollections)+ graph.activeMode = new Map(revision.graph.activeMode)+ graph.documentColorSpace = revision.graph.documentColorSpace+ graph.instanceIndex = new Map()+ for (const node of graph.getAllNodes()) {+ if (!node.componentId) continue+ const instances = graph.instanceIndex.get(node.componentId) ?? new Set<string>()+ instances.add(node.id)+ graph.instanceIndex.set(node.componentId, instances)+ }+ return { manifest: structuredClone(revision.manifest), graph }+}diff --git a/packages/core/src/library/snapshot.ts b/packages/core/src/library/snapshot.tsnew file mode 100644index 000000000..e837299e5--- /dev/null+++ b/packages/core/src/library/snapshot.ts@@ -0,0 +1,210 @@+import { cloneNodeProps, SceneGraph } from '@open-pencil/scene-graph'+import type { SceneNode } from '@open-pencil/scene-graph'++import { contentHash } from './hash'+import { assertLibraryAssetKey } from './identity'+import type { LibraryAssetDescriptor, PortableLibrarySnapshot } from './types'++const VOLATILE_NODE_FIELDS = new Set([+ 'id',+ 'parentId',+ 'childIds',+ 'source',+ 'overrides',+ 'componentPropertyAssignments',+ 'textPicture',+ 'figmaDerivedTextGlyphs',+ 'figmaDerivedLayout',+ 'librarySource',+ 'pluginData'+])++function assetKey(node: SceneNode): string {+ const key = node.componentKey ?? node.sourceLibraryKey ?? node.publishId ?? node.source.id+ if (!key) throw new Error(`Component ${node.name} has no stable library asset key`)+ assertLibraryAssetKey(key)+ return key+}++function collectNodeClosure(graph: SceneGraph, rootIds: string[]): Set<string> {+ const ids = new Set<string>()+ const pending = [...rootIds]+ while (pending.length > 0) {+ const id = pending.pop()+ if (!id || ids.has(id)) continue+ const node = graph.getNode(id)+ if (!node) continue+ ids.add(id)+ pending.push(...node.childIds)+ if (node.componentId) pending.push(node.componentId)+ }+ return ids+}++function addSnapshotNode(+ source: SceneGraph,+ target: SceneGraph,+ sourceId: string,+ targetParentId: string,+ mappedIds: Map<string, string>+): void {+ const node = source.getNode(sourceId)+ if (!node) return+ const created = target.createNode(+ node.type,+ targetParentId,+ cloneNodeProps(node, node.componentId)+ )+ mappedIds.set(sourceId, created.id)+ for (const childId of node.childIds)+ addSnapshotNode(source, target, childId, created.id, mappedIds)+}++function remapSnapshotReferences(graph: SceneGraph, mappedIds: Map<string, string>): void {+ for (const [sourceId, targetId] of mappedIds) {+ const sourceTarget = graph.getNode(targetId)+ if (!sourceTarget) continue+ const componentId = sourceTarget.componentId+ if (componentId && mappedIds.has(componentId)) {+ graph.updateNode(targetId, { componentId: mappedIds.get(componentId) ?? null })+ }+ if (sourceId === targetId) throw new Error('Snapshot IDs must be remapped')+ }+}++export function extractLibrarySnapshot(+ source: SceneGraph,+ assetNodeIds?: string[]+): PortableLibrarySnapshot {+ const roots = (assetNodeIds ?? [...source.getAllNodes()].map((node) => node.id))+ .map((id) => source.getNode(id))+ .filter(+ (node): node is SceneNode => node?.type === 'COMPONENT' || node?.type === 'COMPONENT_SET'+ )+ .filter((node) => node.parentId && source.getNode(node.parentId)?.type !== 'COMPONENT_SET')+ const closure = collectNodeClosure(+ source,+ roots.map((node) => node.id)+ )+ const snapshot = new SceneGraph()+ const page = snapshot.getPages()[0]+ page.name = 'Library definitions'+ page.internalOnly = true+ const mappedIds = new Map<string, string>()+ const sourceComponentIds = new Map<string, string | null>()+ const closureRoots = [...closure]+ .map((id) => source.getNode(id))+ .filter((node): node is SceneNode =>+ Boolean(node && (!node.parentId || !closure.has(node.parentId)))+ )+ for (const root of closureRoots) addSnapshotNode(source, snapshot, root.id, page.id, mappedIds)+ for (const sourceId of mappedIds.keys()) {+ sourceComponentIds.set(sourceId, source.getNode(sourceId)?.componentId ?? null)+ }+ for (const [sourceId, targetId] of mappedIds) {+ const componentId = sourceComponentIds.get(sourceId)+ if (componentId) snapshot.updateNode(targetId, { componentId })+ }+ remapSnapshotReferences(snapshot, mappedIds)++ for (const imageHash of new Set(+ [...closure].flatMap((id) => {+ const node = source.getNode(id)+ return node+ ? node.fills.flatMap((paint) =>+ paint.type === 'IMAGE' && paint.imageHash ? [paint.imageHash] : []+ )+ : []+ })+ )) {+ const image = source.images.get(imageHash)+ if (image) snapshot.images.set(imageHash, new Uint8Array(image))+ }+ return {+ graph: snapshot,+ assetRoots: roots.flatMap((root) => {+ const id = mappedIds.get(root.id)+ const mapped = id ? snapshot.getNode(id) : undefined+ return mapped ? [mapped] : []+ })+ }+}++function normalizedLibraryField(key: string, value: unknown): unknown {+ if (key === 'lineHeight' && (value === null || value === 17)) return null+ if (+ key === 'fontFeatures' &&+ Array.isArray(value) &&+ (value.length === 0 ||+ JSON.stringify(value) ===+ JSON.stringify([+ { tag: 'LIGA', enabled: true },+ { tag: 'CALT', enabled: true }+ ]))+ ) {+ return []+ }+ if (key === 'fills' && Array.isArray(value)) {+ return value.map((paint) => {+ if (!paint || typeof paint !== 'object' || Array.isArray(paint)) return paint+ return Object.fromEntries(+ Object.entries(paint).filter(+ ([field, fieldValue]) => !(field === 'blendMode' && fieldValue === 'NORMAL')+ )+ )+ })+ }+ return value+}++export function canonicalLibraryNode(+ graph: SceneGraph,+ node: SceneNode,+ dependencyStack = new Set<string>()+): unknown {+ const visualFields = Object.fromEntries(+ Object.entries(node)+ .filter(+ ([key]) =>+ !VOLATILE_NODE_FIELDS.has(key) &&+ key !== 'componentId' &&+ key !== 'instanceIndex' &&+ key !== 'name' &&+ key !== 'symbolDescription'+ )+ .map(([key, value]) => [key, normalizedLibraryField(key, value)])+ )+ const component = node.componentId ? graph.getNode(node.componentId) : undefined+ const dependencyKey =+ component?.type === 'COMPONENT' || component?.type === 'COMPONENT_SET'+ ? assetKey(component)+ : null+ const dependency =+ component && dependencyKey && !dependencyStack.has(component.id)+ ? canonicalLibraryNode(graph, component, new Set([...dependencyStack, component.id]))+ : null+ return {+ ...visualFields,+ componentKey: dependencyKey,+ componentDependency: dependency,+ children: node.childIds.flatMap((id) => {+ const child = graph.getNode(id)+ return child ? [canonicalLibraryNode(graph, child, dependencyStack)] : []+ })+ }+}++export async function describeSnapshotAssets(+ snapshot: PortableLibrarySnapshot+): Promise<LibraryAssetDescriptor[]> {+ return Promise.all(+ snapshot.assetRoots.map(async (node) => ({+ key: assetKey(node),+ type: node.type === 'COMPONENT_SET' ? 'COMPONENT_SET' : 'COMPONENT',+ name: node.name,+ description: node.symbolDescription,+ sourceNodeId: node.id,+ contentHash: await contentHash(canonicalLibraryNode(snapshot.graph, node, new Set([node.id])))+ }))+ )+}diff --git a/packages/core/src/library/source-publication.ts b/packages/core/src/library/source-publication.tsnew file mode 100644index 000000000..f93af0178--- /dev/null+++ b/packages/core/src/library/source-publication.ts@@ -0,0 +1,61 @@+import type { SceneGraph } from '@open-pencil/scene-graph'++export const SOURCE_LIBRARY_PUBLICATION_PLUGIN_KEY = 'sourceLibraryPublication'+const OPEN_PENCIL_PLUGIN_ID = 'open-pencil'++export interface SourceLibraryPublication {+ libraryId: string+ revisionId: string+ name: string+ catalogSource?: string+}++function isPublication(value: unknown): value is SourceLibraryPublication {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false+ const publication = value as Partial<SourceLibraryPublication>+ return (+ typeof publication.libraryId === 'string' &&+ typeof publication.revisionId === 'string' &&+ typeof publication.name === 'string' &&+ (publication.catalogSource === undefined || typeof publication.catalogSource === 'string')+ )+}++export function readSourceLibraryPublication(graph: SceneGraph): SourceLibraryPublication | null {+ const root = graph.getNode(graph.rootId)+ const entry = root?.pluginData.find(+ (item) =>+ item.pluginId === OPEN_PENCIL_PLUGIN_ID && item.key === SOURCE_LIBRARY_PUBLICATION_PLUGIN_KEY+ )+ if (!entry) return null+ try {+ const parsed: unknown = JSON.parse(entry.value)+ return isPublication(parsed) ? parsed : null+ } catch {+ return null+ }+}++export function writeSourceLibraryPublication(+ graph: SceneGraph,+ publication: SourceLibraryPublication+): void {+ const root = graph.getNode(graph.rootId)+ if (!root) return+ graph.updateNode(root.id, {+ pluginData: [+ ...root.pluginData.filter(+ (entry) =>+ !(+ entry.pluginId === OPEN_PENCIL_PLUGIN_ID &&+ entry.key === SOURCE_LIBRARY_PUBLICATION_PLUGIN_KEY+ )+ ),+ {+ pluginId: OPEN_PENCIL_PLUGIN_ID,+ key: SOURCE_LIBRARY_PUBLICATION_PLUGIN_KEY,+ value: JSON.stringify(publication)+ }+ ]+ })+}diff --git a/packages/core/src/library/types.ts b/packages/core/src/library/types.tsnew file mode 100644index 000000000..4f4cfa95b--- /dev/null+++ b/packages/core/src/library/types.ts@@ -0,0 +1,74 @@+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'++export const COMPONENT_LIBRARY_SCHEMA_VERSION = 1 as const++export type LibraryAssetType = 'COMPONENT' | 'COMPONENT_SET'++export interface LibraryAssetDescriptor {+ key: string+ type: LibraryAssetType+ name: string+ description: string+ sourceNodeId: string+ contentHash: string+ thumbnail?: Uint8Array+}++export interface ComponentLibraryManifest {+ schemaVersion: typeof COMPONENT_LIBRARY_SCHEMA_VERSION+ libraryId: string+ name: string+ revisionId: string+ previousRevisionId: string | null+ publishedAt: string+ description: string+ assets: LibraryAssetDescriptor[]+}++export interface ComponentLibraryRevision {+ manifest: ComponentLibraryManifest+ graph: SceneGraph+}++export interface PublishLibraryInput {+ libraryId: string+ name: string+ graph: SceneGraph+ description?: string+ previousRevisionId?: string | null+ assetNodeIds?: string[]+ publishedAt?: string+}++export interface LibrarySummary {+ libraryId: string+ name: string+ latestRevisionId: string+ publishedAt: string+ assetCount: number+}++export interface StoredLibraryLatestManifest {+ schemaVersion: typeof COMPONENT_LIBRARY_SCHEMA_VERSION+ summary: LibrarySummary+}++export interface LibraryCatalog {+ listLibraries(): Promise<LibrarySummary[]>+ getRevision(libraryId: string, revisionId?: string): Promise<ComponentLibraryRevision>+ publishRevision(input: PublishLibraryInput): Promise<ComponentLibraryRevision>+}++export type LibraryAssetChange =+ | { kind: 'added'; asset: LibraryAssetDescriptor }+ | { kind: 'removed'; asset: LibraryAssetDescriptor }+ | {+ kind: 'modified' | 'renamed'+ previous: LibraryAssetDescriptor+ asset: LibraryAssetDescriptor+ }++export interface PortableLibrarySnapshot {+ graph: SceneGraph+ assetRoots: SceneNode[]+}diff --git a/packages/core/src/library/update.ts b/packages/core/src/library/update.tsnew file mode 100644index 000000000..208a25c44--- /dev/null+++ b/packages/core/src/library/update.ts@@ -0,0 +1,103 @@+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'++import { findLibraryDefinition } from './definitions'+import { diffLibraryManifests } from './diff'+import type { ComponentLibraryRevision, LibraryAssetChange, LibraryAssetDescriptor } from './types'++export interface LibraryUpdateSummary {+ libraryId: string+ currentRevisionId: string+ latestRevisionId: string+ changes: LibraryAssetChange[]+}++export interface LibraryUpdateImpact {+ affectedInstanceCount: number+ fallbackInstanceCount: number+}++export interface LibraryInstanceUpdate {+ instanceId: string+ previousComponentId: string+ componentId: string+ fallback: boolean+}++function componentsForRoot(graph: SceneGraph, root: SceneNode): SceneNode[] {+ if (root.type === 'COMPONENT') return [root]+ if (root.type !== 'COMPONENT_SET') return []+ return root.childIds.flatMap((id) => {+ const child = graph.getNode(id)+ return child?.type === 'COMPONENT' ? [child] : []+ })+}++function sameVariant(left: SceneNode, right: SceneNode): boolean {+ const leftEntries = Object.entries(left.componentPropertyValues)+ return (+ leftEntries.length === Object.keys(right.componentPropertyValues).length &&+ leftEntries.every(([name, value]) => right.componentPropertyValues[name] === value)+ )+}++function topLeft(components: SceneNode[]): SceneNode | undefined {+ return [...components].sort(+ (left, right) => left.y - right.y || left.x - right.x || left.name.localeCompare(right.name)+ )[0]+}++export function summarizeLibraryUpdate(+ current: ComponentLibraryRevision,+ latest: ComponentLibraryRevision+): LibraryUpdateSummary | null {+ if (current.manifest.libraryId !== latest.manifest.libraryId) {+ throw new Error('Cannot compare revisions from different libraries')+ }+ if (current.manifest.revisionId === latest.manifest.revisionId) return null+ return {+ libraryId: current.manifest.libraryId,+ currentRevisionId: current.manifest.revisionId,+ latestRevisionId: latest.manifest.revisionId,+ changes: diffLibraryManifests(current.manifest, latest.manifest)+ }+}++export function libraryUpdateImpact(updates: LibraryInstanceUpdate[]): LibraryUpdateImpact {+ return {+ affectedInstanceCount: updates.length,+ fallbackInstanceCount: updates.filter((update) => update.fallback).length+ }+}++export function planLibraryInstanceUpdates(+ graph: SceneGraph,+ libraryId: string,+ previousRevisionId: string,+ nextRevisionId: string,+ descriptors: LibraryAssetDescriptor[]+): LibraryInstanceUpdate[] {+ const updates: LibraryInstanceUpdate[] = []+ for (const descriptor of descriptors) {+ const previousRoot = findLibraryDefinition(graph, libraryId, descriptor.key, previousRevisionId)+ const nextRoot = findLibraryDefinition(graph, libraryId, descriptor.key, nextRevisionId)+ if (!previousRoot || !nextRoot) continue+ const previousComponents = componentsForRoot(graph, previousRoot)+ const nextComponents = componentsForRoot(graph, nextRoot)+ const fallback = topLeft(nextComponents)+ if (!fallback) continue++ for (const previousComponent of previousComponents) {+ const target =+ nextComponents.find((component) => sameVariant(previousComponent, component)) ?? fallback+ for (const instance of graph.getInstances(previousComponent.id)) {+ updates.push({+ instanceId: instance.id,+ previousComponentId: previousComponent.id,+ componentId: target.id,+ fallback: !sameVariant(previousComponent, target)+ })+ }+ }+ }+ return updates+}diff --git a/packages/core/src/library/validation.ts b/packages/core/src/library/validation.tsnew file mode 100644index 000000000..da0864a43--- /dev/null+++ b/packages/core/src/library/validation.ts@@ -0,0 +1,77 @@+import { contentHash } from './hash'+import { serializeLibraryRevision } from './serialization'+import { describeSnapshotAssets } from './snapshot'+import type { ComponentLibraryRevision } from './types'++export const MAX_LIBRARY_REVISION_BYTES = 50 * 1024 * 1024+export const MAX_LIBRARY_NODES = 50_000+export const MAX_LIBRARY_IMAGES = 500+export const MAX_LIBRARY_IMAGE_BYTES = MAX_LIBRARY_REVISION_BYTES++export class LibraryRevisionIntegrityError extends Error {+ constructor(message: string, options?: ErrorOptions) {+ super(message, options)+ this.name = 'LibraryRevisionIntegrityError'+ }+}++export function isLibraryRevisionIntegrityError(+ error: unknown+): error is LibraryRevisionIntegrityError {+ return error instanceof LibraryRevisionIntegrityError+}++function integrityError(message: string): never {+ throw new LibraryRevisionIntegrityError(message)+}++function serializedRevisionBytes(revision: ComponentLibraryRevision): number {+ const serialized = serializeLibraryRevision(revision)+ return new TextEncoder().encode(JSON.stringify(serialized)).byteLength+}++export async function validateLibraryRevision(revision: ComponentLibraryRevision): Promise<void> {+ const { manifest, graph } = revision+ if (graph.nodes.size > MAX_LIBRARY_NODES) integrityError('Component library exceeds node limit')+ if (graph.images.size > MAX_LIBRARY_IMAGES)+ integrityError('Component library exceeds image limit')+ const imageBytes = [...graph.images.values()].reduce(+ (total, image) => total + image.byteLength,+ 0+ )+ if (imageBytes > MAX_LIBRARY_IMAGE_BYTES)+ integrityError('Component library exceeds image byte limit')+ if (serializedRevisionBytes(revision) > MAX_LIBRARY_REVISION_BYTES)+ integrityError('Component library exceeds serialized revision byte limit')++ const assetKeys = new Set<string>()+ for (const asset of manifest.assets) {+ if (assetKeys.has(asset.key))+ integrityError(`Duplicate component library asset key: ${asset.key}`)+ assetKeys.add(asset.key)+ const source = graph.getNode(asset.sourceNodeId)+ if (source && source.type !== asset.type)+ integrityError(`Component library asset type mismatch: ${asset.key}`)+ }++ const roots = manifest.assets.flatMap((asset) => {+ const node = graph.getNode(asset.sourceNodeId)+ return node ? [node] : []+ })+ if (roots.length !== manifest.assets.length)+ integrityError('Component library asset source is missing')+ const described = await describeSnapshotAssets({ graph, assetRoots: roots })+ const hashes = new Map(described.map((asset) => [asset.key, asset.contentHash]))+ for (const asset of manifest.assets) {+ if (hashes.get(asset.key) !== asset.contentHash) {+ integrityError(`Component library content hash mismatch: ${asset.key}`)+ }+ }+ const revisionId = await contentHash({+ schemaVersion: manifest.schemaVersion,+ libraryId: manifest.libraryId,+ previousRevisionId: manifest.previousRevisionId,+ assets: manifest.assets.map(({ thumbnail: _, sourceNodeId: __, ...asset }) => asset)+ })+ if (revisionId !== manifest.revisionId) integrityError('Component library revision hash mismatch')+}diff --git a/packages/core/src/tools/component-catalog.ts b/packages/core/src/tools/component-catalog.tsnew file mode 100644index 000000000..bb1e01906--- /dev/null+++ b/packages/core/src/tools/component-catalog.ts@@ -0,0 +1,45 @@+import type { LibraryAssetDescriptor, LibrarySummary } from '#core/library'++export type ComponentCatalogSource = 'document' | 'libraries' | 'all'++export interface ComponentCatalogLibraryAsset {+ libraryId: string+ libraryName: string+ revisionId: string+ enabled: boolean+ priority: number+ asset: LibraryAssetDescriptor+}++export interface ComponentCatalogInsertInput {+ libraryId: string+ revisionId?: string+ assetKey: string+ parentId?: string+ x?: number+ y?: number+ variantValues?: Record<string, string>+}++export interface ComponentCatalog {+ listLibraries(): Promise<LibrarySummary[]>+ listComponents(input: {+ name?: string+ libraryId?: string+ enabledOnly?: boolean+ }): Promise<ComponentCatalogLibraryAsset[]>+ insertComponent(input: ComponentCatalogInsertInput): Promise<{ id: string; componentId: string }>+}++const catalogs = new WeakMap<object, ComponentCatalog>()++export function registerComponentCatalog(owner: object, catalog: ComponentCatalog): () => void {+ catalogs.set(owner, catalog)+ return () => {+ if (catalogs.get(owner) === catalog) catalogs.delete(owner)+ }+}++export function getComponentCatalog(owner: object): ComponentCatalog | undefined {+ return catalogs.get(owner)+}diff --git a/packages/core/src/tools/index.ts b/packages/core/src/tools/index.tsindex 9d3188e1e..326bb40d3 100644--- a/packages/core/src/tools/index.ts+++ b/packages/core/src/tools/index.ts@@ -1,5 +1,11 @@import codegenPrompt from './prompts/codegen.md'+export { getComponentCatalog, registerComponentCatalog } from './component-catalog'+export type {+ ComponentCatalog,+ ComponentCatalogInsertInput,+ ComponentCatalogLibraryAsset+} from './component-catalog'export { ALL_TOOLS, CORE_TOOLS, EXTENDED_TOOLS } from './registry'export const CODEGEN_PROMPT: string = codegenPromptexport { exportImage } from './vector'diff --git a/packages/core/src/tools/modify/update.ts b/packages/core/src/tools/modify/update.tsindex 66b1284eb..c4b0c028d 100644--- a/packages/core/src/tools/modify/update.ts+++ b/packages/core/src/tools/modify/update.ts@@ -1,5 +1,6 @@import type { SceneNode } from '@open-pencil/scene-graph'+import { assertNodeEditable } from '#core/editor/capabilities'import { defineTool, nodeNotFound } from '#core/tools/schema'export const updateNode = defineTool({@@ -34,6 +35,7 @@ export const updateNode = defineTool({execute: (figma, args) => {const node = figma.getNodeById(args.id)if (!node) return nodeNotFound(args.id)+ assertNodeEditable(figma.graph, args.id)const updated: string[] = []if (args.x !== undefined) {node.x = args.xdiff --git a/packages/core/src/tools/read.ts b/packages/core/src/tools/read.tsindex e26465362..892c3300a 100644--- a/packages/core/src/tools/read.ts+++ b/packages/core/src/tools/read.ts@@ -1,4 +1,5 @@export { getComponents } from './read/components'+export { insertLibraryComponent, listLibraries } from './read/libraries'export { getFontStatus, listAvailableFonts, listFonts } from './read/fonts'export { diffJSX, getJSX } from './read/jsx'export { findNodes, getNode, getPageTree } from './read/nodes'diff --git a/packages/core/src/tools/read/components.ts b/packages/core/src/tools/read/components.tsindex 729b9790c..59e5e0254 100644--- a/packages/core/src/tools/read/components.ts+++ b/packages/core/src/tools/read/components.ts@@ -1,28 +1,98 @@+import { getComponentCatalog } from '#core/tools/component-catalog'import { defineTool } from '#core/tools/schema'+interface DocumentComponentResult {+ id: string+ name: string+ type: string+ page: string+ source: 'document'+}++interface LibraryComponentResult {+ libraryId: string+ libraryName: string+ revisionId: string+ assetKey: string+ name: string+ type: string+ description: string+ source: 'library'+ enabled: boolean+ priority: number+}+export const getComponents = defineTool({name: 'get_components',- description: 'List all components in the document, optionally filtered by name.',+ description:+ 'List reusable components from the document and enabled component libraries, optionally filtered by name.',params: {name: { type: 'string', description: 'Filter by name (case-insensitive substring)' },+ source: {+ type: 'string',+ description: 'Component source',+ enum: ['all', 'document', 'libraries'],+ default: 'all'+ },+ library_id: { type: 'string', description: 'Filter library components by library ID' },limit: { type: 'number', description: 'Max results (default: 50)' }},- execute: (figma, args) => {+ execute: async (figma, args) => {const limit = args.limit ?? 50+ const source = args.source ?? 'all'const nameFilter = args.name?.toLowerCase()- const components: { id: string; name: string; type: string; page: string }[] = []+ const documentComponents: DocumentComponentResult[] = []- for (const page of figma.root.children) {- if (components.length >= limit) break- page.findAll((node) => {- if (components.length >= limit) return false- if (node.type !== 'COMPONENT' && node.type !== 'COMPONENT_SET') return false- if (nameFilter && !node.name.toLowerCase().includes(nameFilter)) return false- components.push({ id: node.id, name: node.name, type: node.type, page: page.name })- return false+ if (source !== 'libraries') {+ for (const page of figma.root.children) {+ if (documentComponents.length >= limit) break+ page.findAll((node) => {+ if (documentComponents.length >= limit) return false+ if (node.type !== 'COMPONENT' && node.type !== 'COMPONENT_SET') return false+ if (nameFilter && !node.name.toLowerCase().includes(nameFilter)) return false+ documentComponents.push({+ id: node.id,+ name: node.name,+ type: node.type,+ page: page.name,+ source: 'document'+ })+ return false+ })+ }+ }++ const catalog = getComponentCatalog(figma.graph)+ const libraryComponents: LibraryComponentResult[] = []+ if (source !== 'document' && catalog) {+ const assets = await catalog.listComponents({+ name: args.name,+ libraryId: args.library_id,+ enabledOnly: true})+ libraryComponents.push(+ ...assets.map(({ libraryId, libraryName, revisionId, enabled, priority, asset }) => ({+ libraryId,+ libraryName,+ revisionId,+ assetKey: asset.key,+ name: asset.name,+ type: asset.type,+ description: asset.description,+ source: 'library' as const,+ enabled,+ priority+ }))+ )}+ const components = [...libraryComponents, ...documentComponents]+ .sort((left, right) => {+ const leftPriority = 'priority' in left ? left.priority : -1+ const rightPriority = 'priority' in right ? right.priority : -1+ return rightPriority - leftPriority || left.name.localeCompare(right.name)+ })+ .slice(0, limit)return { count: components.length, components }}})diff --git a/packages/core/src/tools/read/libraries.ts b/packages/core/src/tools/read/libraries.tsnew file mode 100644index 000000000..346622fdb--- /dev/null+++ b/packages/core/src/tools/read/libraries.ts@@ -0,0 +1,57 @@+import { getComponentCatalog } from '#core/tools/component-catalog'+import { defineTool } from '#core/tools/schema'++export const listLibraries = defineTool({+ name: 'list_libraries',+ description: 'List available published component libraries.',+ params: {},+ execute: async (figma) => {+ const catalog = getComponentCatalog(figma.graph)+ const libraries = catalog ? await catalog.listLibraries() : []+ return { count: libraries.length, libraries }+ }+})++export const insertLibraryComponent = defineTool({+ name: 'insert_library_component',+ description:+ 'Insert a reusable component from an enabled library by stable library and asset identity.',+ mutates: true,+ params: {+ library_id: { type: 'string', description: 'Library ID', required: true },+ revision_id: { type: 'string', description: 'Pinned revision ID' },+ asset_key: { type: 'string', description: 'Stable asset key', required: true },+ parent_id: { type: 'string', description: 'Optional parent node ID' },+ x: { type: 'number', description: 'X position' },+ y: { type: 'number', description: 'Y position' },+ variant_values: {+ type: 'string',+ description: 'Optional JSON object of variant property values'+ }+ },+ execute: async (figma, args) => {+ const catalog = getComponentCatalog(figma.graph)+ if (!catalog) throw new Error('No component library catalog is configured')+ let variantValues: Record<string, string> | undefined+ if (args.variant_values) {+ const parsed: unknown = JSON.parse(args.variant_values)+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {+ throw new TypeError('variant_values must be a JSON object')+ }+ const entries = Object.entries(parsed)+ if (entries.some(([, value]) => typeof value !== 'string')) {+ throw new TypeError('variant_values values must be strings')+ }+ variantValues = Object.fromEntries(entries) as Record<string, string>+ }+ return catalog.insertComponent({+ libraryId: args.library_id,+ revisionId: args.revision_id,+ assetKey: args.asset_key,+ parentId: args.parent_id,+ x: args.x,+ y: args.y,+ variantValues+ })+ }+})diff --git a/packages/core/src/tools/registry-extended.ts b/packages/core/src/tools/registry-extended.tsindex 7fdd062e9..d865732b8 100644--- a/packages/core/src/tools/registry-extended.ts+++ b/packages/core/src/tools/registry-extended.ts@@ -41,8 +41,10 @@ import {getCurrentPage,getFontStatus,getPageTree,+ insertLibraryComponent,listAvailableFonts,listFonts,+ listLibraries,listPages,pageBounds,queryNodes,@@ -109,6 +111,8 @@ export const EXTENDED_TOOLS: ToolDef[] = [selectNodes,queryNodes,getComponents,+ listLibraries,+ insertLibraryComponent,switchPage,pageBounds,getFontStatus,diff --git a/packages/fig/src/node-change/convert.ts b/packages/fig/src/node-change/convert.tsindex 3337f9b7d..b2240c90f 100644--- a/packages/fig/src/node-change/convert.ts+++ b/packages/fig/src/node-change/convert.ts@@ -14,6 +14,7 @@ import { convertEffects, convertFills, convertStrokes } from './paint'import {extractBoundVariables,extractExportSettings,+ extractLibrarySource,extractPluginData,extractPluginRelaunchData,getOpenPencilPluginValue,@@ -624,6 +625,7 @@ export function nodeChangeToProps(variableModes: extractVariableModes(nc),exportSettings: extractExportSettings(nc),pluginData: extractPluginData(nc),+ librarySource: extractLibrarySource(nc),pluginRelaunchData: extractPluginRelaunchData(nc),clipsContent: nc.frameMaskDisabled === false && nc.resizeToFit !== true,componentId: extractSymbolId(nc),diff --git a/packages/fig/src/node-change/export-node.ts b/packages/fig/src/node-change/export-node.tsindex 530f01c3a..de9101bdc 100644--- a/packages/fig/src/node-change/export-node.ts+++ b/packages/fig/src/node-change/export-node.ts@@ -14,6 +14,7 @@ import { effectiveFigmaRawNodeFields, effectiveFigmaSourcePayload } from '../souimport { bytesToHex } from './bytes'import {applyExportSettingsPluginData,+ applyLibrarySourcePluginData,mergePluginData,NODE_TYPE_PLUGIN_KEY,serializePluginRelaunchData,@@ -885,6 +886,7 @@ export function sceneNodeToKiwiWithContext(if (variableModeBySetMap) nc.variableModeBySetMap = variableModeBySetMapapplyExportSettingsPluginData(node)+ applyLibrarySourcePluginData(node)const pluginData = mergePluginData(node.pluginData)if (pluginData.length > 0) nc.pluginData = pluginDataif (node.pluginRelaunchData.length > 0) {diff --git a/packages/fig/src/node-change/plugin-data.ts b/packages/fig/src/node-change/plugin-data.tsindex 237ce514c..166557b5c 100644--- a/packages/fig/src/node-change/plugin-data.ts+++ b/packages/fig/src/node-change/plugin-data.ts@@ -18,6 +18,8 @@ export const LAYOUT_DIRECTION_PLUGIN_KEY = 'layoutDirection'export const NODE_TYPE_PLUGIN_KEY = 'nodeType'export const BOUND_VARIABLES_PLUGIN_KEY = 'boundVariables'export const EXPORT_SETTINGS_PLUGIN_KEY = 'exportSettings'+export const LIBRARY_SOURCE_PLUGIN_KEY = 'librarySource'+export const ENABLED_LIBRARIES_PLUGIN_KEY = 'enabledLibraries'const NATIVE_EXPORT_FORMATS: Record<string, ExportFormatId> = {PNG: 'png',@@ -167,6 +169,49 @@ export function extractPluginData(nc: NodeChange): PluginDataEntry[] {}))}+export function extractLibrarySource(nc: NodeChange): SceneNode['librarySource'] {+ const value = getOpenPencilPluginValue(nc, LIBRARY_SOURCE_PLUGIN_KEY)+ if (!value) return null+ try {+ const parsed = JSON.parse(value) as unknown+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null+ const source = parsed as {+ identity?: { libraryId?: unknown; assetKey?: unknown; revisionId?: unknown }+ sourceNodeId?: unknown+ readOnly?: unknown+ }+ if (+ typeof source.identity?.libraryId !== 'string' ||+ typeof source.identity.assetKey !== 'string' ||+ typeof source.identity.revisionId !== 'string'+ ) {+ return null+ }+ return {+ identity: {+ libraryId: source.identity.libraryId,+ assetKey: source.identity.assetKey,+ revisionId: source.identity.revisionId+ },+ sourceNodeId: typeof source.sourceNodeId === 'string' ? source.sourceNodeId : null,+ readOnly: source.readOnly === true+ }+ } catch {+ return null+ }+}++export function applyLibrarySourcePluginData(node: SceneNode): void {+ if (node.librarySource) {+ upsertPluginData(node, LIBRARY_SOURCE_PLUGIN_KEY, JSON.stringify(node.librarySource))+ } else {+ node.pluginData = node.pluginData.filter(+ (entry) =>+ !(entry.pluginId === OPEN_PENCIL_PLUGIN_ID && entry.key === LIBRARY_SOURCE_PLUGIN_KEY)+ )+ }+}+export function getOpenPencilPluginValue(nc: NodeChange, key: string): string | null {return (nc.pluginData?.find((entry) => entry.pluginID === OPEN_PENCIL_PLUGIN_ID && entry.key === key)diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.tsindex 50d8241f2..c25cc7218 100644--- a/packages/scene-graph/src/index.ts+++ b/packages/scene-graph/src/index.ts@@ -37,6 +37,7 @@ import { getAbsolutePosition } from './coordinate'import type { Color, Rect, Vector } from './primitives'import type {DocumentColorSpace,+ EnabledLibraryBinding,NodeType,SceneGraphEventHandlers,SceneGraphEvents,@@ -74,6 +75,7 @@ export class SceneGraph {/** Deflated kiwi schema bytes from the original .fig file, preserved for roundtrip fidelity. */figSchemaDeflated: Uint8Array | null = nulldocumentColorSpace: DocumentColorSpace = 'display-p3'+ enabledLibraries = new Map<string, EnabledLibraryBinding>()readonly emitter: Emitter<SceneGraphEvents> = createNanoEvents()private absPosCache = new Map<string, Vector>()private previewMutationDepth = 0diff --git a/packages/scene-graph/src/node-defaults.ts b/packages/scene-graph/src/node-defaults.tsindex f076213ee..e95049c61 100644--- a/packages/scene-graph/src/node-defaults.ts+++ b/packages/scene-graph/src/node-defaults.ts@@ -150,6 +150,7 @@ export function createDefaultNode(overrideKey: null,sharedSymbolVersion: null,publishedVersion: null,+ librarySource: null,isPublishable: false,isSymbolPublishable: false,symbolDescription: '',diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.tsindex 464c57426..b5e29669a 100644--- a/packages/scene-graph/src/types.ts+++ b/packages/scene-graph/src/types.ts@@ -351,6 +351,24 @@ export type FigmaLayoutMetadata = Partial<Record<'bordersTakeSpace' | 'stackReverseZIndex', boolean>>+export interface LibraryAssetIdentity {+ libraryId: string+ assetKey: string+ revisionId: string+}++export interface LibraryAssetSource {+ identity: LibraryAssetIdentity+ sourceNodeId: string | null+ readOnly: boolean+}++export interface EnabledLibraryBinding {+ libraryId: string+ revisionId: string+ enabled: boolean+}+export interface SceneNode {id: stringtype: NodeType@@ -497,6 +515,7 @@ export interface SceneNode {overrideKey: string | nullsharedSymbolVersion: string | nullpublishedVersion: string | null+ librarySource: LibraryAssetSource | nullisPublishable: booleanisSymbolPublishable: booleansymbolDescription: stringdiff --git a/packages/vue/src/controls/component-props/authoring.ts b/packages/vue/src/controls/component-props/authoring.tsnew file mode 100644index 000000000..14c08bfb9--- /dev/null+++ b/packages/vue/src/controls/component-props/authoring.ts@@ -0,0 +1,127 @@+import { computed } from 'vue'++import type { VariantConflict } from '@open-pencil/core/editor'+import type { ComponentPropertyDefinition, SceneNode } from '@open-pencil/scene-graph'++import { useEditor } from '#vue/editor/context'+import { useSceneComputed } from '#vue/internal/scene-computed/use'++export interface VariantDefinitionControl {+ id: string+ name: string+ values: string[]+}++function variantContext(node: SceneNode | null, graph: ReturnType<typeof useEditor>['graph']) {+ if (node?.type === 'COMPONENT_SET') return { componentSet: node, variant: null }+ if (node?.type !== 'COMPONENT' || !node.parentId) return null+ const parent = graph.getNode(node.parentId)+ return parent?.type === 'COMPONENT_SET' ? { componentSet: parent, variant: node } : null+}++export function useVariantAuthoring() {+ const editor = useEditor()+ const context = useSceneComputed(() => {+ void editor.state.sceneVersion+ const selected = editor.getSelectedNodes()+ return selected.length === 1 ? variantContext(selected[0] ?? null, editor.graph) : null+ })+ const active = computed(() => context.value !== null)+ const componentSet = computed(() => context.value?.componentSet ?? null)+ const variant = computed(() => context.value?.variant ?? null)+ const definitions = useSceneComputed<VariantDefinitionControl[]>(() => {+ void editor.state.sceneVersion+ const componentSetId = componentSet.value?.id+ if (!componentSetId) return []+ const values = editor.collectVariantOptions(componentSetId)+ return editor+ .getComponentSetPropertyDefs(componentSetId)+ .filter(+ (definition): definition is ComponentPropertyDefinition => definition.type === 'VARIANT'+ )+ .map((definition) => ({+ id: definition.id,+ name: definition.name,+ values: [...(values.get(definition.name) ?? [])]+ }))+ })+ const diagnostics = useSceneComputed<VariantConflict[]>(() => {+ void editor.state.sceneVersion+ const componentSetId = componentSet.value?.id+ return componentSetId ? editor.getComponentSetVariantConflicts(componentSetId) : []+ })++ function addProperty(name: string, initialValue: string) {+ const componentSetId = componentSet.value?.id+ if (componentSetId) editor.addPropertyDefinition(componentSetId, name, 'VARIANT', initialValue)+ }++ function renameProperty(propertyId: string, name: string) {+ const componentSetId = componentSet.value?.id+ return componentSetId+ ? editor.renamePropertyDefinition(componentSetId, propertyId, name)+ : false+ }++ function removeProperty(propertyId: string) {+ const componentSetId = componentSet.value?.id+ return componentSetId ? editor.removePropertyDefinition(componentSetId, propertyId) : false+ }++ function reorderProperties(propertyIds: string[]) {+ const componentSetId = componentSet.value?.id+ return componentSetId ? editor.reorderPropertyDefinitions(componentSetId, propertyIds) : false+ }++ function renameValue(propertyId: string, previousValue: string, value: string) {+ const componentSetId = componentSet.value?.id+ return componentSetId+ ? editor.renameVariantValue(componentSetId, propertyId, previousValue, value)+ : false+ }++ function reorderValues(propertyId: string, values: string[]) {+ const componentSetId = componentSet.value?.id+ return componentSetId ? editor.reorderVariantValues(componentSetId, propertyId, values) : false+ }++ function setVariantValue(propertyId: string, value: string) {+ const variantId = variant.value?.id+ return variantId+ ? editor.setVariantPropertyValue(variantId, propertyId, value)+ : { kind: 'invalid' as const }+ }++ function addVariant() {+ const componentSetId = componentSet.value?.id+ return componentSetId ? editor.addVariant(componentSetId) : undefined+ }++ function duplicateVariant() {+ const source =+ variant.value ?? editor.getDefaultVariantForComponentSet(componentSet.value?.id ?? '')+ return source ? editor.duplicateVariant(source.id) : undefined+ }++ function removeVariant() {+ return variant.value ? editor.removeVariant(variant.value.id) : false+ }++ return {+ active,+ componentSet,+ variant,+ definitions,+ diagnostics,+ addProperty,+ renameProperty,+ removeProperty,+ reorderProperties,+ renameValue,+ reorderValues,+ setVariantValue,+ addVariant,+ duplicateVariant,+ removeVariant+ }+}diff --git a/packages/vue/src/controls/component-props/index.ts b/packages/vue/src/controls/component-props/index.tsindex 2551633ff..5b6914aa1 100644--- a/packages/vue/src/controls/component-props/index.ts+++ b/packages/vue/src/controls/component-props/index.ts@@ -1,2 +1,3 @@+export * from './authoring'export * from './model'export * from './use'diff --git a/packages/vue/src/controls/component-props/model.ts b/packages/vue/src/controls/component-props/model.tsindex 1480401dd..22728e9c3 100644--- a/packages/vue/src/controls/component-props/model.ts+++ b/packages/vue/src/controls/component-props/model.ts@@ -10,6 +10,7 @@ export interface ComponentPropertyOption {value: stringlabel: stringmissing?: boolean+ disabled?: boolean}export interface ComponentPropertyControl {diff --git a/packages/vue/src/controls/component-props/use.ts b/packages/vue/src/controls/component-props/use.tsindex 96e2547ac..a2fb8ef6e 100644--- a/packages/vue/src/controls/component-props/use.ts+++ b/packages/vue/src/controls/component-props/use.ts@@ -14,11 +14,11 @@ import { useEditor } from '#vue/editor/context'import { useSceneComputed } from '#vue/internal/scene-computed/use'function variantOptions(editor: ReturnType<typeof useEditor>, instance: SceneNode, name: string) {- const component = instance.componentId ? editor.graph.getNode(instance.componentId) : null- const parent = component?.parentId ? editor.graph.getNode(component.parentId) : null- const values =- parent?.type === 'COMPONENT_SET' ? editor.collectVariantOptions(parent.id).get(name) : null- return [...(values ?? [])].map((value) => ({ value, label: value }))+ return editor.getVariantOptionAvailability(instance.id, name).map(({ value, available }) => ({+ value,+ label: value,+ disabled: !available+ }))}export function useComponentProperties() {diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.jsonindex 6932f295e..d8c583dfa 100644--- a/packages/vue/src/i18n/locales/de/panels.json+++ b/packages/vue/src/i18n/locales/de/panels.json@@ -204,8 +204,76 @@"listView": "Listenansicht","viewDetails": "Details anzeigen","assetLibraryBadge": "Bibliothek",+ "manageLibraries": "Manage libraries",+ "manageLibrariesDescription": "Browse libraries and review updates available in this file.",+ "reviewLibraryUpdates": "Review library updates",+ "enableLibrary": "Enable library",+ "disableLibrary": "Disable library",+ "noLibraries": "No published libraries",+ "libraryAssetCount": "{count} assets",+ "libraryInstanceCount": "Instances: {count}",+ "libraryUpdateAvailable": "Update available",+ "applyLibraryUpdate": "Apply update",+ "browseLibraries": "Browse libraries",+ "libraryUpdates": "Updates",+ "updateLibraryAsset": "Update",+ "updateAll": "Update all",+ "noLibraryUpdates": "No library updates",+ "showUpdatesForAllPages": "Show updates for all pages",+ "updateSelectedInstance": "Update selected instance",+ "currentVersion": "Current",+ "updatedVersion": "Updated",+ "sideBySide": "Side by side",+ "overlay": "Overlay",+ "comparisonMode": "Comparison mode",+ "overlayOpacity": "Overlay opacity",+ "loadingUpdatePreview": "Loading update preview…",+ "updateInstance": "Update instance",+ "libraryInstancePosition": "{current} of {total} instances",+ "previousLibraryInstance": "Previous instance",+ "nextLibraryInstance": "Next instance",+ "libraryVariantFallbackWarning": "The exact variant is unavailable in the updated library. The default variant will be used.",+ "reviewLibraryUpdate": "Review library update",+ "reviewLibraryUpdateDescription": "Compare current and updated instances before accepting changes.",+ "noLibraryAssetChanges": "No asset changes",+ "libraryUpdateImpact": "{affected} affected instances · {fallback} variant fallbacks",+ "publishLibrary": "Publish library",+ "publishingLibrary": "Publishing…",+ "publishLibraryHelp": "Publish this file’s components as an immutable revision.",+ "libraryId": "Library ID",+ "libraryName": "Library name",+ "revisionDescription": "Revision description",+ "libraryPublishFailed": "Failed to publish library",+ "libraryChanges": "Changes",+ "searchLibraryChanges": "Search changes",+ "noLibraryChangesFound": "No matching changes",+ "libraryDestination": "Destination",+ "libraryChangeAdded": "Added",+ "libraryChangeModified": "Modified",+ "libraryChangeRenamed": "Renamed",+ "libraryChangeRemoved": "Removed",+ "loading": "Loading…",+ "cancel": "Cancel",+ "localLibraries": "Local",+ "storageLibraries": "Storage",+ "storageNotConfigured": "Storage is not configured",+ "storageLibrariesUnavailable": "This storage provider does not support libraries",+ "preferLibrary": "Prefer this library","assetVariantSummary": "{count} Varianten · {names}","duplicateVariantValues": "Doppelte Variantenwerte",+ "variantPropertyName": "Property name",+ "variantPropertyValue": "Initial value",+ "addVariantProperty": "Add variant property",+ "addVariant": "Add variant",+ "duplicateVariant": "Duplicate variant",+ "removeVariant": "Remove variant",+ "removeVariantProperty": "Remove variant property",+ "moveVariantPropertyUp": "Move variant property up",+ "moveVariantPropertyDown": "Move variant property down",+ "moveVariantValueUp": "Move variant value up",+ "moveVariantValueDown": "Move variant value down",+ "noVariantProperties": "No variant properties",+ "variantConflictHelp": "Each variant needs a unique combination of property values","openDocumentation": "Dokumentation öffnen","noLocalComponents": "Keine lokalen Komponenten","componentSet": "Komponentensatz",diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.jsonindex 368239e18..51b39d64a 100644--- a/packages/vue/src/i18n/locales/es/panels.json+++ b/packages/vue/src/i18n/locales/es/panels.json@@ -221,8 +221,76 @@"listView": "Vista de lista","viewDetails": "Ver detalles","assetLibraryBadge": "Biblioteca",+ "manageLibraries": "Manage libraries",+ "manageLibrariesDescription": "Browse libraries and review updates available in this file.",+ "reviewLibraryUpdates": "Review library updates",+ "enableLibrary": "Enable library",+ "disableLibrary": "Disable library",+ "noLibraries": "No published libraries",+ "libraryAssetCount": "{count} assets",+ "libraryInstanceCount": "Instances: {count}",+ "libraryUpdateAvailable": "Update available",+ "applyLibraryUpdate": "Apply update",+ "browseLibraries": "Browse libraries",+ "libraryUpdates": "Updates",+ "updateLibraryAsset": "Update",+ "updateAll": "Update all",+ "noLibraryUpdates": "No library updates",+ "showUpdatesForAllPages": "Show updates for all pages",+ "updateSelectedInstance": "Update selected instance",+ "currentVersion": "Current",+ "updatedVersion": "Updated",+ "sideBySide": "Side by side",+ "overlay": "Overlay",+ "comparisonMode": "Comparison mode",+ "overlayOpacity": "Overlay opacity",+ "loadingUpdatePreview": "Loading update preview…",+ "updateInstance": "Update instance",+ "libraryInstancePosition": "{current} of {total} instances",+ "previousLibraryInstance": "Previous instance",+ "nextLibraryInstance": "Next instance",+ "libraryVariantFallbackWarning": "The exact variant is unavailable in the updated library. The default variant will be used.",+ "reviewLibraryUpdate": "Review library update",+ "reviewLibraryUpdateDescription": "Compare current and updated instances before accepting changes.",+ "noLibraryAssetChanges": "No asset changes",+ "libraryUpdateImpact": "{affected} affected instances · {fallback} variant fallbacks",+ "publishLibrary": "Publish library",+ "publishingLibrary": "Publishing…",+ "publishLibraryHelp": "Publish this file’s components as an immutable revision.",+ "libraryId": "Library ID",+ "libraryName": "Library name",+ "revisionDescription": "Revision description",+ "libraryPublishFailed": "Failed to publish library",+ "libraryChanges": "Changes",+ "searchLibraryChanges": "Search changes",+ "noLibraryChangesFound": "No matching changes",+ "libraryDestination": "Destination",+ "libraryChangeAdded": "Added",+ "libraryChangeModified": "Modified",+ "libraryChangeRenamed": "Renamed",+ "libraryChangeRemoved": "Removed",+ "loading": "Loading…",+ "cancel": "Cancel",+ "localLibraries": "Local",+ "storageLibraries": "Storage",+ "storageNotConfigured": "Storage is not configured",+ "storageLibrariesUnavailable": "This storage provider does not support libraries",+ "preferLibrary": "Prefer this library","assetVariantSummary": "{count} variantes · {names}","duplicateVariantValues": "Valores de variante duplicados",+ "variantPropertyName": "Property name",+ "variantPropertyValue": "Initial value",+ "addVariantProperty": "Add variant property",+ "addVariant": "Add variant",+ "duplicateVariant": "Duplicate variant",+ "removeVariant": "Remove variant",+ "removeVariantProperty": "Remove variant property",+ "moveVariantPropertyUp": "Move variant property up",+ "moveVariantPropertyDown": "Move variant property down",+ "moveVariantValueUp": "Move variant value up",+ "moveVariantValueDown": "Move variant value down",+ "noVariantProperties": "No variant properties",+ "variantConflictHelp": "Each variant needs a unique combination of property values","openDocumentation": "Abrir documentación","noLocalComponents": "No hay componentes locales","componentSet": "Conjunto de componentes",diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.jsonindex 0bcf93b6c..7e29548ab 100644--- a/packages/vue/src/i18n/locales/fr/panels.json+++ b/packages/vue/src/i18n/locales/fr/panels.json@@ -204,8 +204,76 @@"listView": "Vue en liste","viewDetails": "Voir les détails","assetLibraryBadge": "Bibliothèque",+ "manageLibraries": "Manage libraries",+ "manageLibrariesDescription": "Browse libraries and review updates available in this file.",+ "reviewLibraryUpdates": "Review library updates",+ "enableLibrary": "Enable library",+ "disableLibrary": "Disable library",+ "noLibraries": "No published libraries",+ "libraryAssetCount": "{count} assets",+ "libraryInstanceCount": "Instances: {count}",+ "libraryUpdateAvailable": "Update available",+ "applyLibraryUpdate": "Apply update",+ "browseLibraries": "Browse libraries",+ "libraryUpdates": "Updates",+ "updateLibraryAsset": "Update",+ "updateAll": "Update all",+ "noLibraryUpdates": "No library updates",+ "showUpdatesForAllPages": "Show updates for all pages",+ "updateSelectedInstance": "Update selected instance",+ "currentVersion": "Current",+ "updatedVersion": "Updated",+ "sideBySide": "Side by side",+ "overlay": "Overlay",+ "comparisonMode": "Comparison mode",+ "overlayOpacity": "Overlay opacity",+ "loadingUpdatePreview": "Loading update preview…",+ "updateInstance": "Update instance",+ "libraryInstancePosition": "{current} of {total} instances",+ "previousLibraryInstance": "Previous instance",+ "nextLibraryInstance": "Next instance",+ "libraryVariantFallbackWarning": "The exact variant is unavailable in the updated library. The default variant will be used.",+ "reviewLibraryUpdate": "Review library update",+ "reviewLibraryUpdateDescription": "Compare current and updated instances before accepting changes.",+ "noLibraryAssetChanges": "No asset changes",+ "libraryUpdateImpact": "{affected} affected instances · {fallback} variant fallbacks",+ "publishLibrary": "Publish library",+ "publishingLibrary": "Publishing…",+ "publishLibraryHelp": "Publish this file’s components as an immutable revision.",+ "libraryId": "Library ID",+ "libraryName": "Library name",+ "revisionDescription": "Revision description",+ "libraryPublishFailed": "Failed to publish library",+ "libraryChanges": "Changes",+ "searchLibraryChanges": "Search changes",+ "noLibraryChangesFound": "No matching changes",+ "libraryDestination": "Destination",+ "libraryChangeAdded": "Added",+ "libraryChangeModified": "Modified",+ "libraryChangeRenamed": "Renamed",+ "libraryChangeRemoved": "Removed",+ "loading": "Loading…",+ "cancel": "Cancel",+ "localLibraries": "Local",+ "storageLibraries": "Storage",+ "storageNotConfigured": "Storage is not configured",+ "storageLibrariesUnavailable": "This storage provider does not support libraries",+ "preferLibrary": "Prefer this library","assetVariantSummary": "{count} variantes · {names}","duplicateVariantValues": "Valeurs de variante en double",+ "variantPropertyName": "Property name",+ "variantPropertyValue": "Initial value",+ "addVariantProperty": "Add variant property",+ "addVariant": "Add variant",+ "duplicateVariant": "Duplicate variant",+ "removeVariant": "Remove variant",+ "removeVariantProperty": "Remove variant property",+ "moveVariantPropertyUp": "Move variant property up",+ "moveVariantPropertyDown": "Move variant property down",+ "moveVariantValueUp": "Move variant value up",+ "moveVariantValueDown": "Move variant value down",+ "noVariantProperties": "No variant properties",+ "variantConflictHelp": "Each variant needs a unique combination of property values","openDocumentation": "Ouvrir la documentation","noLocalComponents": "Aucun composant local","componentSet": "Jeu de composants",diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.jsonindex 8904c89cd..5a77a9e04 100644--- a/packages/vue/src/i18n/locales/it/panels.json+++ b/packages/vue/src/i18n/locales/it/panels.json@@ -204,8 +204,76 @@"listView": "Vista elenco","viewDetails": "Visualizza dettagli","assetLibraryBadge": "Libreria",+ "manageLibraries": "Manage libraries",+ "manageLibrariesDescription": "Browse libraries and review updates available in this file.",+ "reviewLibraryUpdates": "Review library updates",+ "enableLibrary": "Enable library",+ "disableLibrary": "Disable library",+ "noLibraries": "No published libraries",+ "libraryAssetCount": "{count} assets",+ "libraryInstanceCount": "Instances: {count}",+ "libraryUpdateAvailable": "Update available",+ "applyLibraryUpdate": "Apply update",+ "browseLibraries": "Browse libraries",+ "libraryUpdates": "Updates",+ "updateLibraryAsset": "Update",+ "updateAll": "Update all",+ "noLibraryUpdates": "No library updates",+ "showUpdatesForAllPages": "Show updates for all pages",+ "updateSelectedInstance": "Update selected instance",+ "currentVersion": "Current",+ "updatedVersion": "Updated",+ "sideBySide": "Side by side",+ "overlay": "Overlay",+ "comparisonMode": "Comparison mode",+ "overlayOpacity": "Overlay opacity",+ "loadingUpdatePreview": "Loading update preview…",+ "updateInstance": "Update instance",+ "libraryInstancePosition": "{current} of {total} instances",+ "previousLibraryInstance": "Previous instance",+ "nextLibraryInstance": "Next instance",+ "libraryVariantFallbackWarning": "The exact variant is unavailable in the updated library. The default variant will be used.",+ "reviewLibraryUpdate": "Review library update",+ "reviewLibraryUpdateDescription": "Compare current and updated instances before accepting changes.",+ "noLibraryAssetChanges": "No asset changes",+ "libraryUpdateImpact": "{affected} affected instances · {fallback} variant fallbacks",+ "publishLibrary": "Publish library",+ "publishingLibrary": "Publishing…",+ "publishLibraryHelp": "Publish this file’s components as an immutable revision.",+ "libraryId": "Library ID",+ "libraryName": "Library name",+ "revisionDescription": "Revision description",+ "libraryPublishFailed": "Failed to publish library",+ "libraryChanges": "Changes",+ "searchLibraryChanges": "Search changes",+ "noLibraryChangesFound": "No matching changes",+ "libraryDestination": "Destination",+ "libraryChangeAdded": "Added",+ "libraryChangeModified": "Modified",+ "libraryChangeRenamed": "Renamed",+ "libraryChangeRemoved": "Removed",+ "loading": "Loading…",+ "cancel": "Cancel",+ "localLibraries": "Local",+ "storageLibraries": "Storage",+ "storageNotConfigured": "Storage is not configured",+ "storageLibrariesUnavailable": "This storage provider does not support libraries",+ "preferLibrary": "Prefer this library","assetVariantSummary": "{count} varianti · {names}","duplicateVariantValues": "Valori variante duplicati",+ "variantPropertyName": "Property name",+ "variantPropertyValue": "Initial value",+ "addVariantProperty": "Add variant property",+ "addVariant": "Add variant",+ "duplicateVariant": "Duplicate variant",+ "removeVariant": "Remove variant",+ "removeVariantProperty": "Remove variant property",+ "moveVariantPropertyUp": "Move variant property up",+ "moveVariantPropertyDown": "Move variant property down",+ "moveVariantValueUp": "Move variant value up",+ "moveVariantValueDown": "Move variant value down",+ "noVariantProperties": "No variant properties",+ "variantConflictHelp": "Each variant needs a unique combination of property values","openDocumentation": "Apri documentazione","noLocalComponents": "Nessun componente locale","componentSet": "Set di componenti",diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.jsonindex e26d8347e..e968714b7 100644--- a/packages/vue/src/i18n/locales/ja/panels.json+++ b/packages/vue/src/i18n/locales/ja/panels.json@@ -221,8 +221,76 @@"listView": "リスト表示","viewDetails": "詳細を表示","assetLibraryBadge": "ライブラリ",+ "manageLibraries": "Manage libraries",+ "manageLibrariesDescription": "Browse libraries and review updates available in this file.",+ "reviewLibraryUpdates": "Review library updates",+ "enableLibrary": "Enable library",+ "disableLibrary": "Disable library",+ "noLibraries": "No published libraries",+ "libraryAssetCount": "{count} assets",+ "libraryInstanceCount": "Instances: {count}",+ "libraryUpdateAvailable": "Update available",+ "applyLibraryUpdate": "Apply update",+ "browseLibraries": "Browse libraries",+ "libraryUpdates": "Updates",+ "updateLibraryAsset": "Update",+ "updateAll": "Update all",+ "noLibraryUpdates": "No library updates",+ "showUpdatesForAllPages": "Show updates for all pages",+ "updateSelectedInstance": "Update selected instance",+ "currentVersion": "Current",+ "updatedVersion": "Updated",+ "sideBySide": "Side by side",+ "overlay": "Overlay",+ "comparisonMode": "Comparison mode",+ "overlayOpacity": "Overlay opacity",+ "loadingUpdatePreview": "Loading update preview…",+ "updateInstance": "Update instance",+ "libraryInstancePosition": "{current} of {total} instances",+ "previousLibraryInstance": "Previous instance",+ "nextLibraryInstance": "Next instance",+ "libraryVariantFallbackWarning": "The exact variant is unavailable in the updated library. The default variant will be used.",+ "reviewLibraryUpdate": "Review library update",+ "reviewLibraryUpdateDescription": "Compare current and updated instances before accepting changes.",+ "noLibraryAssetChanges": "No asset changes",+ "libraryUpdateImpact": "{affected} affected instances · {fallback} variant fallbacks",+ "publishLibrary": "Publish library",+ "publishingLibrary": "Publishing…",+ "publishLibraryHelp": "Publish this file’s components as an immutable revision.",+ "libraryId": "Library ID",+ "libraryName": "Library name",+ "revisionDescription": "Revision description",+ "libraryPublishFailed": "Failed to publish library",+ "libraryChanges": "Changes",+ "searchLibraryChanges": "Search changes",+ "noLibraryChangesFound": "No matching changes",+ "libraryDestination": "Destination",+ "libraryChangeAdded": "Added",+ "libraryChangeModified": "Modified",+ "libraryChangeRenamed": "Renamed",+ "libraryChangeRemoved": "Removed",+ "loading": "Loading…",+ "cancel": "Cancel",+ "localLibraries": "Local",+ "storageLibraries": "Storage",+ "storageNotConfigured": "Storage is not configured",+ "storageLibrariesUnavailable": "This storage provider does not support libraries",+ "preferLibrary": "Prefer this library","assetVariantSummary": "{count} 個のバリアント · {names}","duplicateVariantValues": "重複したバリアント値",+ "variantPropertyName": "Property name",+ "variantPropertyValue": "Initial value",+ "addVariantProperty": "Add variant property",+ "addVariant": "Add variant",+ "duplicateVariant": "Duplicate variant",+ "removeVariant": "Remove variant",+ "removeVariantProperty": "Remove variant property",+ "moveVariantPropertyUp": "Move variant property up",+ "moveVariantPropertyDown": "Move variant property down",+ "moveVariantValueUp": "Move variant value up",+ "moveVariantValueDown": "Move variant value down",+ "noVariantProperties": "No variant properties",+ "variantConflictHelp": "Each variant needs a unique combination of property values","openDocumentation": "ドキュメントを開く","noLocalComponents": "ローカルコンポーネントはありません","componentSet": "コンポーネントセット",diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.jsonindex a3d004fb6..64f56f16a 100644--- a/packages/vue/src/i18n/locales/pl/panels.json+++ b/packages/vue/src/i18n/locales/pl/panels.json@@ -204,8 +204,76 @@"listView": "Widok listy","viewDetails": "Pokaż szczegóły","assetLibraryBadge": "Biblioteka",+ "manageLibraries": "Manage libraries",+ "manageLibrariesDescription": "Browse libraries and review updates available in this file.",+ "reviewLibraryUpdates": "Review library updates",+ "enableLibrary": "Enable library",+ "disableLibrary": "Disable library",+ "noLibraries": "No published libraries",+ "libraryAssetCount": "{count} assets",+ "libraryInstanceCount": "Instances: {count}",+ "libraryUpdateAvailable": "Update available",+ "applyLibraryUpdate": "Apply update",+ "browseLibraries": "Browse libraries",+ "libraryUpdates": "Updates",+ "updateLibraryAsset": "Update",+ "updateAll": "Update all",+ "noLibraryUpdates": "No library updates",+ "showUpdatesForAllPages": "Show updates for all pages",+ "updateSelectedInstance": "Update selected instance",+ "currentVersion": "Current",+ "updatedVersion": "Updated",+ "sideBySide": "Side by side",+ "overlay": "Overlay",+ "comparisonMode": "Comparison mode",+ "overlayOpacity": "Overlay opacity",+ "loadingUpdatePreview": "Loading update preview…",+ "updateInstance": "Update instance",+ "libraryInstancePosition": "{current} of {total} instances",+ "previousLibraryInstance": "Previous instance",+ "nextLibraryInstance": "Next instance",+ "libraryVariantFallbackWarning": "The exact variant is unavailable in the updated library. The default variant will be used.",+ "reviewLibraryUpdate": "Review library update",+ "reviewLibraryUpdateDescription": "Compare current and updated instances before accepting changes.",+ "noLibraryAssetChanges": "No asset changes",+ "libraryUpdateImpact": "{affected} affected instances · {fallback} variant fallbacks",+ "publishLibrary": "Publish library",+ "publishingLibrary": "Publishing…",+ "publishLibraryHelp": "Publish this file’s components as an immutable revision.",+ "libraryId": "Library ID",+ "libraryName": "Library name",+ "revisionDescription": "Revision description",+ "libraryPublishFailed": "Failed to publish library",+ "libraryChanges": "Changes",+ "searchLibraryChanges": "Search changes",+ "noLibraryChangesFound": "No matching changes",+ "libraryDestination": "Destination",+ "libraryChangeAdded": "Added",+ "libraryChangeModified": "Modified",+ "libraryChangeRenamed": "Renamed",+ "libraryChangeRemoved": "Removed",+ "loading": "Loading…",+ "cancel": "Cancel",+ "localLibraries": "Local",+ "storageLibraries": "Storage",+ "storageNotConfigured": "Storage is not configured",+ "storageLibrariesUnavailable": "This storage provider does not support libraries",+ "preferLibrary": "Prefer this library","assetVariantSummary": "{count} wariantów · {names}","duplicateVariantValues": "Zduplikowane wartości wariantu",+ "variantPropertyName": "Property name",+ "variantPropertyValue": "Initial value",+ "addVariantProperty": "Add variant property",+ "addVariant": "Add variant",+ "duplicateVariant": "Duplicate variant",+ "removeVariant": "Remove variant",+ "removeVariantProperty": "Remove variant property",+ "moveVariantPropertyUp": "Move variant property up",+ "moveVariantPropertyDown": "Move variant property down",+ "moveVariantValueUp": "Move variant value up",+ "moveVariantValueDown": "Move variant value down",+ "noVariantProperties": "No variant properties",+ "variantConflictHelp": "Each variant needs a unique combination of property values","openDocumentation": "Otwórz dokumentację","noLocalComponents": "Brak lokalnych komponentów","componentSet": "Zestaw komponentów",diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.jsonindex 16d987b7f..6d43ff533 100644--- a/packages/vue/src/i18n/locales/ru/panels.json+++ b/packages/vue/src/i18n/locales/ru/panels.json@@ -204,8 +204,76 @@"listView": "Список","viewDetails": "Показать детали","assetLibraryBadge": "Библиотека",+ "manageLibraries": "Manage libraries",+ "manageLibrariesDescription": "Browse libraries and review updates available in this file.",+ "reviewLibraryUpdates": "Review library updates",+ "enableLibrary": "Enable library",+ "disableLibrary": "Disable library",+ "noLibraries": "No published libraries",+ "libraryAssetCount": "{count} assets",+ "libraryInstanceCount": "Instances: {count}",+ "libraryUpdateAvailable": "Update available",+ "applyLibraryUpdate": "Apply update",+ "browseLibraries": "Browse libraries",+ "libraryUpdates": "Updates",+ "updateLibraryAsset": "Update",+ "updateAll": "Update all",+ "noLibraryUpdates": "No library updates",+ "showUpdatesForAllPages": "Show updates for all pages",+ "updateSelectedInstance": "Update selected instance",+ "currentVersion": "Current",+ "updatedVersion": "Updated",+ "sideBySide": "Side by side",+ "overlay": "Overlay",+ "comparisonMode": "Comparison mode",+ "overlayOpacity": "Overlay opacity",+ "loadingUpdatePreview": "Loading update preview…",+ "updateInstance": "Update instance",+ "libraryInstancePosition": "{current} of {total} instances",+ "previousLibraryInstance": "Previous instance",+ "nextLibraryInstance": "Next instance",+ "libraryVariantFallbackWarning": "The exact variant is unavailable in the updated library. The default variant will be used.",+ "reviewLibraryUpdate": "Review library update",+ "reviewLibraryUpdateDescription": "Compare current and updated instances before accepting changes.",+ "noLibraryAssetChanges": "No asset changes",+ "libraryUpdateImpact": "{affected} affected instances · {fallback} variant fallbacks",+ "publishLibrary": "Publish library",+ "publishingLibrary": "Publishing…",+ "publishLibraryHelp": "Publish this file’s components as an immutable revision.",+ "libraryId": "Library ID",+ "libraryName": "Library name",+ "revisionDescription": "Revision description",+ "libraryPublishFailed": "Failed to publish library",+ "libraryChanges": "Changes",+ "searchLibraryChanges": "Search changes",+ "noLibraryChangesFound": "No matching changes",+ "libraryDestination": "Destination",+ "libraryChangeAdded": "Added",+ "libraryChangeModified": "Modified",+ "libraryChangeRenamed": "Renamed",+ "libraryChangeRemoved": "Removed",+ "loading": "Loading…",+ "cancel": "Cancel",+ "localLibraries": "Local",+ "storageLibraries": "Storage",+ "storageNotConfigured": "Storage is not configured",+ "storageLibrariesUnavailable": "This storage provider does not support libraries",+ "preferLibrary": "Prefer this library","assetVariantSummary": "{count} вариантов · {names}","duplicateVariantValues": "Повторяющиеся значения вариантов",+ "variantPropertyName": "Property name",+ "variantPropertyValue": "Initial value",+ "addVariantProperty": "Add variant property",+ "addVariant": "Add variant",+ "duplicateVariant": "Duplicate variant",+ "removeVariant": "Remove variant",+ "removeVariantProperty": "Remove variant property",+ "moveVariantPropertyUp": "Move variant property up",+ "moveVariantPropertyDown": "Move variant property down",+ "moveVariantValueUp": "Move variant value up",+ "moveVariantValueDown": "Move variant value down",+ "noVariantProperties": "No variant properties",+ "variantConflictHelp": "Each variant needs a unique combination of property values","openDocumentation": "Открыть документацию","noLocalComponents": "Нет локальных компонентов","componentSet": "Набор компонентов",diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.jsonindex 546b8e04e..0becebfe0 100644--- a/packages/vue/src/i18n/locales/zh-cn/panels.json+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json@@ -204,8 +204,76 @@"listView": "列表视图","viewDetails": "查看详情","assetLibraryBadge": "库",+ "manageLibraries": "Manage libraries",+ "manageLibrariesDescription": "Browse libraries and review updates available in this file.",+ "reviewLibraryUpdates": "Review library updates",+ "enableLibrary": "Enable library",+ "disableLibrary": "Disable library",+ "noLibraries": "No published libraries",+ "libraryAssetCount": "{count} assets",+ "libraryInstanceCount": "Instances: {count}",+ "libraryUpdateAvailable": "Update available",+ "applyLibraryUpdate": "Apply update",+ "browseLibraries": "Browse libraries",+ "libraryUpdates": "Updates",+ "updateLibraryAsset": "Update",+ "updateAll": "Update all",+ "noLibraryUpdates": "No library updates",+ "showUpdatesForAllPages": "Show updates for all pages",+ "updateSelectedInstance": "Update selected instance",+ "currentVersion": "Current",+ "updatedVersion": "Updated",+ "sideBySide": "Side by side",+ "overlay": "Overlay",+ "comparisonMode": "Comparison mode",+ "overlayOpacity": "Overlay opacity",+ "loadingUpdatePreview": "Loading update preview…",+ "updateInstance": "Update instance",+ "libraryInstancePosition": "{current} of {total} instances",+ "previousLibraryInstance": "Previous instance",+ "nextLibraryInstance": "Next instance",+ "libraryVariantFallbackWarning": "The exact variant is unavailable in the updated library. The default variant will be used.",+ "reviewLibraryUpdate": "Review library update",+ "reviewLibraryUpdateDescription": "Compare current and updated instances before accepting changes.",+ "noLibraryAssetChanges": "No asset changes",+ "libraryUpdateImpact": "{affected} affected instances · {fallback} variant fallbacks",+ "publishLibrary": "Publish library",+ "publishingLibrary": "Publishing…",+ "publishLibraryHelp": "Publish this file’s components as an immutable revision.",+ "libraryId": "Library ID",+ "libraryName": "Library name",+ "revisionDescription": "Revision description",+ "libraryPublishFailed": "Failed to publish library",+ "libraryChanges": "Changes",+ "searchLibraryChanges": "Search changes",+ "noLibraryChangesFound": "No matching changes",+ "libraryDestination": "Destination",+ "libraryChangeAdded": "Added",+ "libraryChangeModified": "Modified",+ "libraryChangeRenamed": "Renamed",+ "libraryChangeRemoved": "Removed",+ "loading": "Loading…",+ "cancel": "Cancel",+ "localLibraries": "Local",+ "storageLibraries": "Storage",+ "storageNotConfigured": "Storage is not configured",+ "storageLibrariesUnavailable": "This storage provider does not support libraries",+ "preferLibrary": "Prefer this library","assetVariantSummary": "{count} 个变体 · {names}","duplicateVariantValues": "重复的变体值",+ "variantPropertyName": "Property name",+ "variantPropertyValue": "Initial value",+ "addVariantProperty": "Add variant property",+ "addVariant": "Add variant",+ "duplicateVariant": "Duplicate variant",+ "removeVariant": "Remove variant",+ "removeVariantProperty": "Remove variant property",+ "moveVariantPropertyUp": "Move variant property up",+ "moveVariantPropertyDown": "Move variant property down",+ "moveVariantValueUp": "Move variant value up",+ "moveVariantValueDown": "Move variant value down",+ "noVariantProperties": "No variant properties",+ "variantConflictHelp": "Each variant needs a unique combination of property values","openDocumentation": "打开文档","noLocalComponents": "没有本地组件","componentSet": "组件集",diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.tsindex 8fd5c2ff9..89230a3e5 100644--- a/packages/vue/src/i18n/messages/panels.ts+++ b/packages/vue/src/i18n/messages/panels.ts@@ -17,8 +17,77 @@ export const panelMessageDefaults = {listView: 'List view',viewDetails: 'View details',assetLibraryBadge: 'Library',+ manageLibraries: 'Manage libraries',+ manageLibrariesDescription: 'Browse libraries and review updates available in this file.',+ reviewLibraryUpdates: 'Review library updates',+ enableLibrary: 'Enable library',+ disableLibrary: 'Disable library',+ noLibraries: 'No published libraries',+ libraryAssetCount: params('{count} assets'),+ libraryInstanceCount: params('Instances: {count}'),+ libraryUpdateAvailable: 'Update available',+ applyLibraryUpdate: 'Apply update',+ browseLibraries: 'Browse libraries',+ libraryUpdates: 'Updates',+ updateLibraryAsset: 'Update',+ updateAll: 'Update all',+ noLibraryUpdates: 'No library updates',+ showUpdatesForAllPages: 'Show updates for all pages',+ updateSelectedInstance: 'Update selected instance',+ currentVersion: 'Current',+ updatedVersion: 'Updated',+ sideBySide: 'Side by side',+ overlay: 'Overlay',+ comparisonMode: 'Comparison mode',+ overlayOpacity: 'Overlay opacity',+ loadingUpdatePreview: 'Loading update preview…',+ updateInstance: 'Update instance',+ libraryInstancePosition: params('{current} of {total} instances'),+ previousLibraryInstance: 'Previous instance',+ nextLibraryInstance: 'Next instance',+ libraryVariantFallbackWarning:+ 'The exact variant is unavailable in the updated library. The default variant will be used.',+ reviewLibraryUpdate: 'Review library update',+ reviewLibraryUpdateDescription: 'Compare current and updated instances before accepting changes.',+ noLibraryAssetChanges: 'No asset changes',+ libraryUpdateImpact: params('{affected} affected instances · {fallback} variant fallbacks'),+ publishLibrary: 'Publish library',+ publishingLibrary: 'Publishing…',+ publishLibraryHelp: 'Publish this file’s components as an immutable revision.',+ libraryId: 'Library ID',+ libraryName: 'Library name',+ revisionDescription: 'Revision description',+ libraryPublishFailed: 'Failed to publish library',+ libraryChanges: 'Changes',+ searchLibraryChanges: 'Search changes',+ noLibraryChangesFound: 'No matching changes',+ libraryDestination: 'Destination',+ libraryChangeAdded: 'Added',+ libraryChangeModified: 'Modified',+ libraryChangeRenamed: 'Renamed',+ libraryChangeRemoved: 'Removed',+ loading: 'Loading…',+ cancel: 'Cancel',+ localLibraries: 'Local',+ storageLibraries: 'Storage',+ storageNotConfigured: 'Storage is not configured',+ storageLibrariesUnavailable: 'This storage provider does not support libraries',+ preferLibrary: 'Prefer this library',assetVariantSummary: params('{count} variants · {names}'),duplicateVariantValues: 'Duplicate variant values',+ variantPropertyName: 'Property name',+ variantPropertyValue: 'Initial value',+ addVariantProperty: 'Add variant property',+ addVariant: 'Add variant',+ duplicateVariant: 'Duplicate variant',+ removeVariant: 'Remove variant',+ removeVariantProperty: 'Remove variant property',+ moveVariantPropertyUp: 'Move variant property up',+ moveVariantPropertyDown: 'Move variant property down',+ moveVariantValueUp: 'Move variant value up',+ moveVariantValueDown: 'Move variant value down',+ noVariantProperties: 'No variant properties',+ variantConflictHelp: 'Each variant needs a unique combination of property values',openDocumentation: 'Open documentation',noLocalComponents: 'No local components',componentSet: 'Component set',diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.tsindex 9f2d4056b..92deb3630 100644--- a/packages/vue/src/index.ts+++ b/packages/vue/src/index.ts@@ -219,11 +219,13 @@ export {compatibleComponentPropertyDefinitions,instanceSwapOptions,mergedComponentPropertyValue,- useComponentProperties+ useComponentProperties,+ useVariantAuthoring} from '#vue/controls/component-props'export type {ComponentPropertyControl,- ComponentPropertyOption+ ComponentPropertyOption,+ VariantDefinitionControl} from '#vue/controls/component-props'export type { CornerGeometryKey, CornerRadiusKey } from '#vue/controls/appearance/types'export { PageListRoot } from '#vue/primitives/PageList'diff --git a/src/App.vue b/src/App.vueindex 8c95a60bf..358137754 100644--- a/src/App.vue+++ b/src/App.vue@@ -7,6 +7,8 @@ import { TooltipProvider } from 'reka-ui'import { provideEditor, useI18n } from '@open-pencil/vue'import AppShell from '@/components/Shell/AppShell.vue'import AppToast from '@/components/Shell/AppToast.vue'+import PublishLibraryDialog from '@/components/libraries/PublishLibraryDialog.vue'+import LibraryUpdateReviewDialog from '@/components/libraries/review/LibraryUpdateReviewDialog.vue'import RecoveryDialog from '@/components/recovery/RecoveryDialog.vue'import SettingsDialog from '@/components/settings/SettingsDialog.vue'import { useEditorStore } from '@/app/editor/active-store'@@ -44,6 +46,8 @@ onMounted(() => {</AppShell><SettingsDialog /><RecoveryDialog />+ <PublishLibraryDialog />+ <LibraryUpdateReviewDialog /><AppToast /></TooltipProvider></template>diff --git a/src/app/ai/chat/system-prompt.md b/src/app/ai/chat/system-prompt.mdindex c897044fd..12adb3fda 100644--- a/src/app/ai/chat/system-prompt.md+++ b/src/app/ai/chat/system-prompt.md@@ -172,6 +172,10 @@ Never skip step 2. Never defer describes to the end. Never batch multiple renderAfter every 3 content renders, also `describe` root at depth=1 to catch cross-section layout drift.+## Reusable components and libraries++Before constructing a common UI element from primitive shapes, call `get_components` with a semantic name. Prefer enabled library matches first, then local document components. Use `insert_library_component` with the returned stable `libraryId` and `assetKey`; only construct an ad hoc replacement when no suitable reusable component exists.+## Phase 4 — Polish1. `stock_photo` — batch ALL named image placeholders in one calldiff --git a/src/app/ai/tools/index.ts b/src/app/ai/tools/index.tsindex 47d56dd5d..3c13e81fd 100644--- a/src/app/ai/tools/index.ts+++ b/src/app/ai/tools/index.ts@@ -3,7 +3,12 @@ import { tool } from 'ai'import * as v from 'valibot'import { computeAllLayouts } from '@open-pencil/core/layout'-import { CORE_TOOLS, EXTENDED_TOOLS, toolsToAI } from '@open-pencil/core/tools'+import {+ CORE_TOOLS,+ EXTENDED_TOOLS,+ registerComponentCatalog,+ toolsToAI+} from '@open-pencil/core/tools'import type { StepBudget, ToolLogEntry } from '@open-pencil/core/tools'import type { SceneNode } from '@open-pencil/scene-graph'@@ -11,17 +16,10 @@ import { makeFigmaFromStore } from '@/app/automation/bridge/figma-factory'import { getActiveEditorStore } from '@/app/editor/active-store'import type { EditorStore } from '@/app/editor/active-store'import { ensureGraphFonts } from '@/app/editor/fonts'--import { createVisualInspectionTool } from './vision'+import { useLibraryService } from '@/app/libraries'export const MAX_AGENT_STEPS = 50-const VISUAL_INSPECTION_TOOL_NAMES = new Set(['export_image'])-const AI_CHAT_TOOLS = [- ...CORE_TOOLS,- ...EXTENDED_TOOLS.filter((definition) => VISUAL_INSPECTION_TOOL_NAMES.has(definition.name))-]-export interface StepUsage {inputTokens: numberoutputTokens: number@@ -93,54 +91,59 @@ export function clearToolLogEntries(store?: EditorStore): void {export function createAITools(store: EditorStore) {let beforeSnapshot: Map<string, SceneNode> | null = nullconst runState = getRunState(store)-- return {- ...toolsToAI(- AI_CHAT_TOOLS,- {- getFigma: () => makeFigmaFromStore(store),- onBeforeExecute: (def) => {- if (def.mutates) {- beforeSnapshot = store.snapshotPage()- }- },- onAfterExecute: async (def) => {- if (def.mutates) {- const pageId = store.state.currentPageId- const pageNode = store.graph.getNode(pageId)- if (pageNode) await ensureGraphFonts(store.graph, pageNode.childIds, store.renderer)- computeAllLayouts(store.graph, pageId)- store.requestRender()- if (beforeSnapshot) {- const before = beforeSnapshot- const after = store.snapshotPage()- store.pushUndoEntry({- label: `AI: ${def.name}`,- forward: () => store.restorePageFromSnapshot(after),- inverse: () => store.restorePageFromSnapshot(before)- })- beforeSnapshot = null- }- }- },- onFlashNodes: (nodeIds) => {- store.renderer?.aiClearActive()- if (nodeIds.length > 0) {- store.aiFlashDone(nodeIds)+ const libraryService = useLibraryService()+ libraryService.bindEditor(store)+ registerComponentCatalog(store.graph, libraryService)++ return toolsToAI(+ [+ ...CORE_TOOLS,+ ...EXTENDED_TOOLS.filter((def) =>+ ['get_components', 'list_libraries', 'insert_library_component'].includes(def.name)+ )+ ],+ {+ getFigma: () => makeFigmaFromStore(store),+ onBeforeExecute: (def) => {+ if (def.mutates) {+ beforeSnapshot = store.snapshotPage()+ }+ },+ onAfterExecute: async (def) => {+ if (def.mutates) {+ const pageId = store.state.currentPageId+ const pageNode = store.graph.getNode(pageId)+ if (pageNode) await ensureGraphFonts(store.graph, pageNode.childIds, store.renderer)+ computeAllLayouts(store.graph, pageId)+ store.requestRender()+ if (beforeSnapshot) {+ const before = beforeSnapshot+ const after = store.snapshotPage()+ store.pushUndoEntry({+ label: `AI: ${def.name}`,+ forward: () => store.restorePageFromSnapshot(after),+ inverse: () => store.restorePageFromSnapshot(before)+ })+ beforeSnapshot = null}- },- onToolLog: (entry) => {- runState.toolLog.push(entry)- },- getStepBudget: (): StepBudget => ({- current: runState.currentSteps,- max: MAX_AGENT_STEPS- })+ }},- { v, valibotSchema, tool }- ),- inspect_visual: createVisualInspectionTool(store)- }+ onFlashNodes: (nodeIds) => {+ store.renderer?.aiClearActive()+ if (nodeIds.length > 0) {+ store.aiFlashDone(nodeIds)+ }+ },+ onToolLog: (entry) => {+ runState.toolLog.push(entry)+ },+ getStepBudget: (): StepBudget => ({+ current: runState.currentSteps,+ max: MAX_AGENT_STEPS+ })+ },+ { v, valibotSchema, tool }+ )}export type AITools = ReturnType<typeof createAITools>diff --git a/src/app/automation/bridge/server.ts b/src/app/automation/bridge/server.tsindex 7df94646a..37def406d 100644--- a/src/app/automation/bridge/server.ts+++ b/src/app/automation/bridge/server.ts@@ -54,8 +54,10 @@ export function connectAutomation(getStore: () => EditorStore, authToken: stringif (msg.type !== 'request' || !msg.id) returntry {const result = await handleRequest(msg.id, msg.command, msg.args)+ if (socket.readyState !== WebSocket.OPEN) returnsocket.send(JSON.stringify({ type: 'response', id: msg.id, ...(result as object) }))} catch (e) {+ if (socket.readyState !== WebSocket.OPEN) returnsocket.send(JSON.stringify({type: 'response',diff --git a/src/app/automation/bridge/tool-handlers.ts b/src/app/automation/bridge/tool-handlers.tsindex 6cf0fa17f..8043f170d 100644--- a/src/app/automation/bridge/tool-handlers.ts+++ b/src/app/automation/bridge/tool-handlers.ts@@ -1,11 +1,12 @@import { renderTreeNode } from '@open-pencil/core/design-jsx'import type { FigmaAPI } from '@open-pencil/core/figma-api'import { computeAllLayouts } from '@open-pencil/core/layout'-import { ALL_TOOLS } from '@open-pencil/core/tools'+import { ALL_TOOLS, registerComponentCatalog } from '@open-pencil/core/tools'import type { JSONObject } from '@open-pencil/scene-graph/primitives'import type { AutomationTarget } from '@/app/automation/bridge/target'import { ensureGraphFonts } from '@/app/editor/fonts'+import { useLibraryService } from '@/app/libraries'type FigmaFactory = (store: AutomationTarget['store'], pageId?: string) => FigmaAPI@@ -43,6 +44,9 @@ export function createAutomationToolHandler(makeFigma: FigmaFactory) {const def = ALL_TOOLS.find((t) => t.name === toolName)if (!def) throw new Error(`Unknown tool: ${toolName}`)const store = target.store+ const libraryService = useLibraryService()+ libraryService.bindEditor(store)+ registerComponentCatalog(store.graph, libraryService)const figma = makeFigma(store, target.pageId)const result = await def.execute(figma, toolArgs)diff --git a/src/app/integrations/storage/index.ts b/src/app/integrations/storage/index.tsindex 1ff6e759e..681e475f6 100644--- a/src/app/integrations/storage/index.ts+++ b/src/app/integrations/storage/index.ts@@ -24,6 +24,10 @@ export type {StorageDocumentBinding,StorageDocumentMetadata,StorageFieldID,+ LibraryObjectStore,+ LibraryObjectSummary,+ LibraryObjectValue,+ LibraryObjectWriteOptions,StoragePreferenceField,StorageProviderID,StorageProviderRegistration,diff --git a/src/app/integrations/storage/s3/adapter.ts b/src/app/integrations/storage/s3/adapter.tsindex 1694f3d9b..25b5b0bc1 100644--- a/src/app/integrations/storage/s3/adapter.ts+++ b/src/app/integrations/storage/s3/adapter.ts@@ -22,6 +22,7 @@ import {S3HttpError,deleteObject,getObject,+ getObjectValue,getObjectRange,headObject,headObjectSize,@@ -264,6 +265,32 @@ export function createS3StorageAdapter(runtime: StorageProviderRuntime): S3Storareturn (await getObjectRange(config, figKey, start, endExclusive)) ?? new Uint8Array()}})+ },++ libraryObjects: {+ async getObject(key) {+ return getObject(await resolveConfig(runtime), key)+ },+ async getObjectValue(key) {+ return getObjectValue(await resolveConfig(runtime), key)+ },+ async putObject(key, bytes, contentType, options) {+ try {+ await putObject(await resolveConfig(runtime), key, bytes, contentType, undefined, options)+ } catch (error) {+ if (error instanceof S3HttpError && (error.status === 409 || error.status === 412)) {+ throw new Error('Library revision conflict: latest revision has changed')+ }+ throw error+ }+ },+ async listObjects(prefix) {+ return (await listObjects(await resolveConfig(runtime), prefix)).map((object) => ({+ key: object.key,+ size: object.size,+ etag: null+ }))+ }}}}diff --git a/src/app/integrations/storage/s3/client.ts b/src/app/integrations/storage/s3/client.tsindex 9b8e9f7f3..cf426d7ce 100644--- a/src/app/integrations/storage/s3/client.ts+++ b/src/app/integrations/storage/s3/client.ts@@ -8,6 +8,7 @@ import {parseS3ErrorXML,type ListedObject} from '@/app/integrations/storage/s3/xml'+import type { LibraryObjectWriteOptions } from '@/app/integrations/storage/types'export function resolveS3Region(config: S3CompatibleConfig): string {const explicit = config.region?.trim()@@ -204,7 +205,8 @@ export async function putObject(key: string,body: Uint8Array | string,contentType: string,- onUploadProgress?: (progress: UploadProgress) => void+ onUploadProgress?: (progress: UploadProgress) => void,+ options?: LibraryObjectWriteOptions): Promise<void> {const bytes = typeof body === 'string' ? new TextEncoder().encode(body) : body// Exact ArrayBuffer so fetch/UA can set Content-Length (required by B2 for large PUTs).@@ -218,7 +220,9 @@ export async function putObject({method: 'PUT',headers: {- 'Content-Type': contentType+ 'Content-Type': contentType,+ ...(options?.ifMatch ? { 'If-Match': options.ifMatch } : {}),+ ...(options?.ifNoneMatch ? { 'If-None-Match': options.ifNoneMatch } : {})},body: payload},@@ -229,6 +233,18 @@ export async function putObject(}}+export async function getObjectValue(+ config: S3CompatibleConfig,+ key: string+): Promise<{ bytes: Uint8Array | null; etag: string | null }> {+ const res = await s3Request(config, objectURL(config, key), { method: 'GET' })+ if (res.status === 404) return { bytes: null, etag: null }+ return {+ bytes: new Uint8Array(await res.arrayBuffer()),+ etag: res.headers.get('etag')+ }+}+export type DownloadProgress = { receivedBytes: number; totalBytes: number | null }export async function getObject(diff --git a/src/app/integrations/storage/types.ts b/src/app/integrations/storage/types.tsindex 24874b328..9e1584510 100644--- a/src/app/integrations/storage/types.ts+++ b/src/app/integrations/storage/types.ts@@ -35,6 +35,34 @@ export type StorageConnectionResult = {message: string}+export interface LibraryObjectSummary {+ key: string+ size: number | null+ etag: string | null+}++export interface LibraryObjectValue {+ bytes: Uint8Array | null+ etag: string | null+}++export interface LibraryObjectWriteOptions {+ ifMatch?: string+ ifNoneMatch?: '*'+}++export interface LibraryObjectStore {+ getObject(key: string): Promise<Uint8Array | null>+ getObjectValue?(key: string): Promise<LibraryObjectValue>+ putObject(+ key: string,+ bytes: Uint8Array,+ contentType: string,+ options?: LibraryObjectWriteOptions+ ): Promise<void>+ listObjects(prefix: string): Promise<LibraryObjectSummary[]>+}+export interface StorageAdapter {testConnection(): Promise<StorageConnectionResult>listDocuments(): Promise<StorageDocument[]>@@ -53,6 +81,7 @@ export interface StorageAdapter {getUsage(): Promise<StorageUsage>getThumbnail?(id: string): Promise<Uint8Array | null>putThumbnail?(id: string, bytes: Uint8Array): Promise<void>+ libraryObjects?: LibraryObjectStore}export type StoragePreferenceField = {diff --git a/src/app/libraries/catalog/local.ts b/src/app/libraries/catalog/local.tsnew file mode 100644index 000000000..31abcf914--- /dev/null+++ b/src/app/libraries/catalog/local.ts@@ -0,0 +1,125 @@+import { openDB, type DBSchema, type IDBPDatabase } from 'idb'++import type {+ ComponentLibraryRevision,+ LibraryCatalog,+ LibrarySummary,+ PublishLibraryInput,+ SerializedComponentLibraryRevision+} from '@open-pencil/core/library'+import {+ createLibraryRevision,+ deserializeLibraryRevision,+ serializeLibraryRevision+} from '@open-pencil/core/library'++const DATABASE_NAME = 'open-pencil-libraries'+const DATABASE_VERSION = 1++interface StoredLibraryRevision {+ libraryId: string+ revisionId: string+ revision: SerializedComponentLibraryRevision+}++interface LocalLibraryDatabase extends DBSchema {+ revisions: {+ key: [string, string]+ value: StoredLibraryRevision+ indexes: { 'by-library': string }+ }+ latest: {+ key: string+ value: LibrarySummary+ }+}++export class LocalLibraryCatalog implements LibraryCatalog {+ readonly #database: Promise<IDBPDatabase<LocalLibraryDatabase>>++ constructor(databaseName = DATABASE_NAME) {+ this.#database = openDB<LocalLibraryDatabase>(databaseName, DATABASE_VERSION, {+ upgrade(database) {+ if (!database.objectStoreNames.contains('revisions')) {+ const revisions = database.createObjectStore('revisions', {+ keyPath: ['libraryId', 'revisionId']+ })+ revisions.createIndex('by-library', 'libraryId')+ }+ if (!database.objectStoreNames.contains('latest')) {+ database.createObjectStore('latest')+ }+ }+ })+ }++ async listLibraries(): Promise<LibrarySummary[]> {+ return (await this.#database).getAll('latest')+ }++ async getRevision(libraryId: string, revisionId?: string): Promise<ComponentLibraryRevision> {+ const database = await this.#database+ const resolvedRevisionId =+ revisionId ?? (await database.get('latest', libraryId))?.latestRevisionId+ const stored = resolvedRevisionId+ ? await database.get('revisions', [libraryId, resolvedRevisionId])+ : undefined+ if (!stored)+ throw new Error(`Library revision not found: ${libraryId}/${revisionId ?? 'latest'}`)+ return deserializeLibraryRevision(stored.revision)+ }++ async cacheRevision(revision: ComponentLibraryRevision, updateLatest = true): Promise<void> {+ const database = await this.#database+ const transaction = database.transaction(['latest', 'revisions'], 'readwrite')+ const manifest = revision.manifest+ await transaction.objectStore('revisions').put({+ libraryId: manifest.libraryId,+ revisionId: manifest.revisionId,+ revision: serializeLibraryRevision(revision)+ })+ if (updateLatest) {+ await transaction.objectStore('latest').put(+ {+ libraryId: manifest.libraryId,+ name: manifest.name,+ latestRevisionId: manifest.revisionId,+ publishedAt: manifest.publishedAt,+ assetCount: manifest.assets.length+ },+ manifest.libraryId+ )+ }+ await transaction.done+ }++ async publishRevision(input: PublishLibraryInput): Promise<ComponentLibraryRevision> {+ const revision = await createLibraryRevision(input)+ const serializedRevision = serializeLibraryRevision(revision)+ const database = await this.#database+ const transaction = database.transaction(['latest', 'revisions'], 'readwrite')+ const latest = await transaction.objectStore('latest').get(input.libraryId)+ if ((input.previousRevisionId ?? null) !== (latest?.latestRevisionId ?? null)) {+ transaction.abort()+ throw new Error('Library revision conflict: latest revision has changed')+ }+ const manifest = revision.manifest+ await transaction.objectStore('revisions').put({+ libraryId: manifest.libraryId,+ revisionId: manifest.revisionId,+ revision: serializedRevision+ })+ await transaction.objectStore('latest').put(+ {+ libraryId: manifest.libraryId,+ name: manifest.name,+ latestRevisionId: manifest.revisionId,+ publishedAt: manifest.publishedAt,+ assetCount: manifest.assets.length+ },+ manifest.libraryId+ )+ await transaction.done+ return revision+ }+}diff --git a/src/app/libraries/catalog/routed.ts b/src/app/libraries/catalog/routed.tsnew file mode 100644index 000000000..12b1a9b9e--- /dev/null+++ b/src/app/libraries/catalog/routed.ts@@ -0,0 +1,66 @@+import {+ isLibraryRevisionIntegrityError,+ type ComponentLibraryRevision,+ type LibraryCatalog,+ type LibrarySummary,+ type PublishLibraryInput+} from '@open-pencil/core/library'++import type { LocalLibraryCatalog } from './local'++export type LibraryCatalogSource = 'local' | 'storage'++export class RoutedLibraryCatalog implements LibraryCatalog {+ readonly #local: LocalLibraryCatalog+ #remote: LibraryCatalog | null = null+ #source: LibraryCatalogSource = 'local'++ constructor(local: LocalLibraryCatalog) {+ this.#local = local+ }++ get source(): LibraryCatalogSource {+ return this.#source+ }++ useLocal(): void {+ this.#source = 'local'+ }++ useStorage(remote: LibraryCatalog): void {+ this.#remote = remote+ this.#source = 'storage'+ }++ async listLibraries(): Promise<LibrarySummary[]> {+ if (this.#source === 'local' || !this.#remote) return this.#local.listLibraries()+ try {+ return await this.#remote.listLibraries()+ } catch (error) {+ console.warn('[Libraries] Remote catalog unavailable, using cached libraries', error)+ return this.#local.listLibraries()+ }+ }++ async getRevision(libraryId: string, revisionId?: string): Promise<ComponentLibraryRevision> {+ if (this.#source === 'local' || !this.#remote) {+ return this.#local.getRevision(libraryId, revisionId)+ }+ try {+ const revision = await this.#remote.getRevision(libraryId, revisionId)+ await this.#local.cacheRevision(revision, revisionId === undefined)+ return revision+ } catch (error) {+ if (isLibraryRevisionIntegrityError(error)) throw error+ console.warn('[Libraries] Remote revision unavailable, using cached revision', error)+ return this.#local.getRevision(libraryId, revisionId)+ }+ }++ async publishRevision(input: PublishLibraryInput): Promise<ComponentLibraryRevision> {+ if (this.#source === 'local' || !this.#remote) return this.#local.publishRevision(input)+ const revision = await this.#remote.publishRevision(input)+ await this.#local.cacheRevision(revision)+ return revision+ }+}diff --git a/src/app/libraries/catalog/storage.ts b/src/app/libraries/catalog/storage.tsnew file mode 100644index 000000000..d4255287d--- /dev/null+++ b/src/app/libraries/catalog/storage.ts@@ -0,0 +1,173 @@+import { decodeBase64, encodeBase64 } from '@open-pencil/core/bytes'+import {+ createLibraryRevision,+ deserializeLibraryRevision,+ MAX_LIBRARY_REVISION_BYTES,+ serializeLibraryRevision,+ validateLibraryRevision+} from '@open-pencil/core/library'+import type {+ ComponentLibraryRevision,+ LibraryCatalog,+ LibrarySummary,+ PublishLibraryInput,+ SerializedComponentLibraryRevision,+ StoredLibraryLatestManifest+} from '@open-pencil/core/library'++import type { LibraryObjectStore } from '@/app/integrations/storage'++const PREFIX = 'open-pencil/libraries'+const textDecoder = new TextDecoder()+const textEncoder = new TextEncoder()++function latestKey(libraryId: string): string {+ return `${PREFIX}/${libraryId}/manifest.json`+}++function revisionKey(libraryId: string, revisionId: string): string {+ return `${PREFIX}/${libraryId}/revisions/${revisionId}.json`+}++function encodeValue(value: unknown): unknown {+ if (value instanceof Uint8Array) return { $bytes: encodeBase64(value) }+ if (Array.isArray(value)) return value.map(encodeValue)+ if (value && typeof value === 'object') {+ return Object.fromEntries(+ Object.entries(value).map(([key, entry]) => [key, encodeValue(entry)])+ )+ }+ return value+}++function decodeValue(value: unknown): unknown {+ if (Array.isArray(value)) return value.map(decodeValue)+ if (value && typeof value === 'object') {+ if ('$bytes' in value && typeof (value as { $bytes?: unknown }).$bytes === 'string') {+ return decodeBase64((value as { $bytes: string }).$bytes)+ }+ return Object.fromEntries(+ Object.entries(value).map(([key, entry]) => [key, decodeValue(entry)])+ )+ }+ return value+}++function encodeRevision(revision: ComponentLibraryRevision): Uint8Array {+ return textEncoder.encode(JSON.stringify(encodeValue(serializeLibraryRevision(revision))))+}++function decodeRevision(bytes: Uint8Array): ComponentLibraryRevision {+ const parsed = decodeValue(+ JSON.parse(textDecoder.decode(bytes))+ ) as SerializedComponentLibraryRevision+ return deserializeLibraryRevision(parsed)+}++function decodeLatest(bytes: Uint8Array): StoredLibraryLatestManifest {+ const parsed = JSON.parse(textDecoder.decode(bytes)) as unknown+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {+ throw new Error('Invalid component library manifest')+ }+ const candidate = parsed as { schemaVersion?: unknown; summary?: unknown }+ if (+ candidate.schemaVersion !== 1 ||+ !candidate.summary ||+ typeof candidate.summary !== 'object' ||+ Array.isArray(candidate.summary)+ ) {+ throw new Error('Invalid component library manifest')+ }+ const summary = candidate.summary as Partial<LibrarySummary>+ if (+ typeof summary.libraryId !== 'string' ||+ typeof summary.name !== 'string' ||+ typeof summary.latestRevisionId !== 'string' ||+ typeof summary.publishedAt !== 'string' ||+ typeof summary.assetCount !== 'number' ||+ !Number.isSafeInteger(summary.assetCount) ||+ summary.assetCount < 0+ ) {+ throw new Error('Invalid component library manifest')+ }+ return candidate as StoredLibraryLatestManifest+}++export class StorageLibraryCatalog implements LibraryCatalog {+ readonly #objects: LibraryObjectStore++ constructor(objects: LibraryObjectStore) {+ this.#objects = objects+ }++ async listLibraries(): Promise<LibrarySummary[]> {+ const objects = await this.#objects.listObjects(`${PREFIX}/`)+ const keys = objects.map((object) => object.key).filter((key) => key.endsWith('/manifest.json'))+ const summaries: LibrarySummary[] = []+ for (const key of keys) {+ const bytes = await this.#objects.getObject(key)+ if (bytes) summaries.push(decodeLatest(bytes).summary)+ }+ return summaries.sort((left, right) => left.name.localeCompare(right.name))+ }++ async getRevision(libraryId: string, revisionId?: string): Promise<ComponentLibraryRevision> {+ const resolvedRevisionId = revisionId ?? (await this.#latest(libraryId))?.latestRevisionId+ if (!resolvedRevisionId) throw new Error(`Library not found: ${libraryId}`)+ const bytes = await this.#objects.getObject(revisionKey(libraryId, resolvedRevisionId))+ if (!bytes) throw new Error(`Library revision not found: ${libraryId}/${resolvedRevisionId}`)+ if (bytes.byteLength > MAX_LIBRARY_REVISION_BYTES)+ throw new Error('Component library revision exceeds size limit')+ const revision = decodeRevision(bytes)+ if (+ revision.manifest.libraryId !== libraryId ||+ revision.manifest.revisionId !== resolvedRevisionId+ ) {+ throw new Error('Library revision identity mismatch')+ }+ await validateLibraryRevision(revision)+ return revision+ }++ async publishRevision(input: PublishLibraryInput): Promise<ComponentLibraryRevision> {+ const manifestKey = latestKey(input.libraryId)+ const latestValue = this.#objects.getObjectValue+ ? await this.#objects.getObjectValue(manifestKey)+ : { bytes: await this.#objects.getObject(manifestKey), etag: null }+ const latest = latestValue.bytes ? decodeLatest(latestValue.bytes).summary : null+ if ((input.previousRevisionId ?? null) !== (latest?.latestRevisionId ?? null)) {+ throw new Error('Library revision conflict: latest revision has changed')+ }+ if (latest && !latestValue.etag) {+ throw new Error('Storage provider does not support conditional library publication')+ }+ const revision = await createLibraryRevision(input)+ const manifest = revision.manifest+ await this.#objects.putObject(+ revisionKey(manifest.libraryId, manifest.revisionId),+ encodeRevision(revision),+ 'application/json'+ )+ const summary: LibrarySummary = {+ libraryId: manifest.libraryId,+ name: manifest.name,+ latestRevisionId: manifest.revisionId,+ publishedAt: manifest.publishedAt,+ assetCount: manifest.assets.length+ }+ await this.#objects.putObject(+ manifestKey,+ textEncoder.encode(+ JSON.stringify({ schemaVersion: 1, summary } satisfies StoredLibraryLatestManifest)+ ),+ 'application/json',+ latest ? (latestValue.etag ? { ifMatch: latestValue.etag } : undefined) : { ifNoneMatch: '*' }+ )+ return revision+ }++ async #latest(libraryId: string): Promise<LibrarySummary | null> {+ const bytes = await this.#objects.getObject(latestKey(libraryId))+ return bytes ? decodeLatest(bytes).summary : null+ }+}diff --git a/src/app/libraries/index.ts b/src/app/libraries/index.tsnew file mode 100644index 000000000..73d727ee0--- /dev/null+++ b/src/app/libraries/index.ts@@ -0,0 +1,15 @@+export { LocalLibraryCatalog } from './catalog/local'+export { RoutedLibraryCatalog } from './catalog/routed'+export type { LibraryCatalogSource } from './catalog/routed'+export { StorageLibraryCatalog } from './catalog/storage'+export { openPublishLibraryDialog, publishLibraryDialogOpen } from './publish/dialog'+export {+ readLibraryCatalogSource,+ readLibraryPriority,+ writeLibraryCatalogSource,+ writeLibraryPriority+} from './preferences'+export { closeLibraryReview, libraryReviewRequest, openLibraryReview } from './review'+export type { LibraryReviewRequest } from './review'+export { LibraryService, useLibraryService } from './service'+export type { EnabledLibraryAsset } from './service'diff --git a/src/app/libraries/preferences.ts b/src/app/libraries/preferences.tsnew file mode 100644index 000000000..d76033744--- /dev/null+++ b/src/app/libraries/preferences.ts@@ -0,0 +1,34 @@+import { useLocalStorage } from '@vueuse/core'++import type { LibraryCatalogSource } from './catalog/routed'++interface LibraryPreferences {+ catalogSource: LibraryCatalogSource+ priorities: Record<string, number>+}++const preferences = useLocalStorage<LibraryPreferences>('open-pencil:library-preferences', {+ catalogSource: 'local',+ priorities: {}+})++export function readLibraryCatalogSource(): LibraryCatalogSource {+ return preferences.value.catalogSource+}++export function writeLibraryCatalogSource(source: LibraryCatalogSource): void {+ preferences.value = { ...preferences.value, catalogSource: source }+}++export function readLibraryPriority(libraryId: string): number {+ const value = preferences.value.priorities[libraryId]+ return typeof value === 'number' && Number.isFinite(value) ? value : 0+}++export function writeLibraryPriority(libraryId: string, priority: number): void {+ if (!Number.isFinite(priority)) throw new TypeError('Library priority must be finite')+ preferences.value = {+ ...preferences.value,+ priorities: { ...preferences.value.priorities, [libraryId]: priority }+ }+}diff --git a/src/app/libraries/publish/dialog.ts b/src/app/libraries/publish/dialog.tsnew file mode 100644index 000000000..013dd7976--- /dev/null+++ b/src/app/libraries/publish/dialog.ts@@ -0,0 +1,7 @@+import { ref } from 'vue'++export const publishLibraryDialogOpen = ref(false)++export function openPublishLibraryDialog(): void {+ publishLibraryDialogOpen.value = true+}diff --git a/src/app/libraries/review.ts b/src/app/libraries/review.tsnew file mode 100644index 000000000..de798d1fb--- /dev/null+++ b/src/app/libraries/review.ts@@ -0,0 +1,18 @@+import { shallowRef } from 'vue'++export interface LibraryReviewRequest {+ libraryId: string+ assetKey: string+ instanceIds: string[]+ initialInstanceId: string+}++export const libraryReviewRequest = shallowRef<LibraryReviewRequest | null>(null)++export function openLibraryReview(request: LibraryReviewRequest): void {+ libraryReviewRequest.value = request+}++export function closeLibraryReview(): void {+ libraryReviewRequest.value = null+}diff --git a/src/app/libraries/service.ts b/src/app/libraries/service.tsnew file mode 100644index 000000000..924f0a642--- /dev/null+++ b/src/app/libraries/service.ts@@ -0,0 +1,564 @@+import { markRaw, shallowRef } from 'vue'++import { reapplyInstanceComponentProperties } from '@open-pencil/core/editor'+import {+ materializeLibraryAsset,+ ensureLibraryAssetKeys,+ libraryUpdateImpact,+ libraryAssetKeyForComponent,+ planOutdatedLibraryInstances,+ planLibraryInstanceUpdates,+ summarizeLibraryUpdate,+ createSelectiveLibraryRevision,+ discoverPublishableLibraryChanges,+ readSourceLibraryPublication,+ writeSourceLibraryPublication+} from '@open-pencil/core/library'+import type {+ ComponentLibraryRevision,+ LibraryCatalog,+ LibrarySummary,+ LibraryUpdateImpact,+ LibraryUpdateSummary,+ PublishLibraryInput,+ LibraryAssetChange+} from '@open-pencil/core/library'+import type {+ ComponentCatalog,+ ComponentCatalogInsertInput,+ ComponentCatalogLibraryAsset+} from '@open-pencil/core/tools'++import type { EditorStore } from '@/app/editor/session'+import { LocalLibraryCatalog } from '@/app/libraries/catalog/local'+import { RoutedLibraryCatalog, type LibraryCatalogSource } from '@/app/libraries/catalog/routed'+import {+ readLibraryPriority,+ writeLibraryCatalogSource,+ writeLibraryPriority+} from '@/app/libraries/preferences'+import type { LibraryAssetUpdateGroup } from '@/app/libraries/update-groups'++export type EnabledLibraryAsset = ComponentCatalogLibraryAsset++export class LibraryService implements ComponentCatalog {+ readonly #catalog: LibraryCatalog+ readonly #routedCatalog: RoutedLibraryCatalog | null+ readonly #summaries = shallowRef<LibrarySummary[]>([])+ readonly #enabledAssets = shallowRef<EnabledLibraryAsset[]>([])+ readonly #updates = shallowRef<LibraryUpdateSummary[]>([])+ readonly #updateImpacts = shallowRef(new Map<string, LibraryUpdateImpact>())+ readonly #revisionCache = new Map<string, ComponentLibraryRevision>()+ #activeEditor: EditorStore | null = null++ constructor(catalog?: LibraryCatalog) {+ if (catalog) {+ this.#catalog = markRaw(catalog)+ this.#routedCatalog = catalog instanceof RoutedLibraryCatalog ? catalog : null+ } else {+ const routed = new RoutedLibraryCatalog(new LocalLibraryCatalog())+ this.#catalog = markRaw(routed)+ this.#routedCatalog = routed+ }+ }++ get catalogSource(): LibraryCatalogSource {+ return this.#routedCatalog?.source ?? 'local'+ }++ useLocalCatalog(): void {+ this.#routedCatalog?.useLocal()+ writeLibraryCatalogSource('local')+ }++ useStorageCatalog(catalog: LibraryCatalog): void {+ this.#routedCatalog?.useStorage(catalog)+ writeLibraryCatalogSource('storage')+ }++ get summaries() {+ return this.#summaries+ }++ get enabledAssets() {+ return this.#enabledAssets+ }++ get updates() {+ return this.#updates+ }++ get updateImpacts() {+ return this.#updateImpacts+ }++ async listLibraries(): Promise<LibrarySummary[]> {+ this.#summaries.value = await this.#catalog.listLibraries()+ return this.#summaries.value+ }++ async listComponents(input: {+ name?: string+ libraryId?: string+ enabledOnly?: boolean+ }): Promise<EnabledLibraryAsset[]> {+ const normalizedName = input.name?.trim().toLowerCase()+ const libraries = await this.#catalog.listLibraries()+ const assets: EnabledLibraryAsset[] = []+ for (const summary of libraries) {+ if (input.libraryId && input.libraryId !== summary.libraryId) continue+ const revision = await this.#getRevision(summary.libraryId, summary.latestRevisionId)+ const binding = this.#activeEditor?.graph.enabledLibraries.get(summary.libraryId)+ if (input.enabledOnly && !binding?.enabled) continue+ assets.push(+ ...revision.manifest.assets+ .filter((asset) => !normalizedName || asset.name.toLowerCase().includes(normalizedName))+ .map((asset) => ({+ libraryId: summary.libraryId,+ libraryName: summary.name,+ revisionId: revision.manifest.revisionId,+ asset,+ enabled: binding?.enabled ?? false,+ priority: readLibraryPriority(summary.libraryId)+ }))+ )+ }+ return assets.sort((left, right) => right.priority - left.priority)+ }++ setPriority(libraryId: string, priority: number): void {+ writeLibraryPriority(libraryId, priority)+ }++ bindEditor(editor: EditorStore): void {+ this.#activeEditor = editor+ }++ async insertComponent(+ input: ComponentCatalogInsertInput+ ): Promise<{ id: string; componentId: string }> {+ const editor = this.#activeEditor+ if (!editor) throw new Error('No active editor is bound to the library catalog')+ const revisionId =+ input.revisionId ?? editor.graph.enabledLibraries.get(input.libraryId)?.revisionId+ if (!revisionId) throw new Error(`Library is not enabled: ${input.libraryId}`)+ const materialized = await this.materialize(editor, input.libraryId, revisionId, input.assetKey)+ let componentId = materialized.componentId+ if (input.variantValues && materialized.componentSetId) {+ const match = editor.findVariantByValues(materialized.componentSetId, input.variantValues)+ if (match) componentId = match.id+ }+ const parentId = input.parentId ?? editor.state.currentPageId+ const id = editor.createInstanceFromComponent(componentId, input.x, input.y, parentId)+ if (!id) throw new Error(`Failed to insert library component: ${input.assetKey}`)+ editor.requestRender()+ return { id, componentId }+ }++ async refresh(editor: EditorStore): Promise<void> {+ this.#activeEditor = editor+ this.#summaries.value = await this.#catalog.listLibraries()+ const assets: EnabledLibraryAsset[] = []+ for (const binding of editor.graph.enabledLibraries.values()) {+ if (!binding.enabled) continue+ const revision = await this.#getRevision(binding.libraryId, binding.revisionId)+ assets.push(+ ...revision.manifest.assets.map((asset) => ({+ libraryId: binding.libraryId,+ libraryName: revision.manifest.name,+ revisionId: binding.revisionId,+ asset,+ enabled: true,+ priority: readLibraryPriority(binding.libraryId)+ }))+ )+ }+ this.#enabledAssets.value = assets+ await this.refreshUpdates(editor)+ }++ async refreshUpdates(editor: EditorStore): Promise<void> {+ const summariesById = new Map(+ this.#summaries.value.map((summary) => [summary.libraryId, summary])+ )+ const updates: LibraryUpdateSummary[] = []+ const impacts = new Map<string, LibraryUpdateImpact>()+ for (const binding of editor.graph.enabledLibraries.values()) {+ if (!binding.enabled) continue+ const latestId = summariesById.get(binding.libraryId)?.latestRevisionId+ if (!latestId || latestId === binding.revisionId) continue+ const current = await this.#getRevision(binding.libraryId, binding.revisionId)+ const latest = await this.#getRevision(binding.libraryId, latestId)+ const summary = summarizeLibraryUpdate(current, latest)+ if (summary) {+ updates.push(summary)+ const commonAssets = latest.manifest.assets.filter((asset) =>+ current.manifest.assets.some((previous) => previous.key === asset.key)+ )+ const plans = planLibraryInstanceUpdates(+ editor.graph,+ binding.libraryId,+ binding.revisionId,+ latestId,+ commonAssets+ )+ impacts.set(binding.libraryId, libraryUpdateImpact(plans))+ }+ }+ this.#updates.value = updates+ this.#updateImpacts.value = impacts+ }++ async applyUpdate(editor: EditorStore, libraryId: string): Promise<void> {+ const update = this.#updates.value.find((item) => item.libraryId === libraryId)+ if (!update) return+ const current = await this.#getRevision(libraryId, update.currentRevisionId)+ const latest = await this.#getRevision(libraryId, update.latestRevisionId)+ const previousAssetKeys = new Set(current.manifest.assets.map((asset) => asset.key))+ const updatable = latest.manifest.assets.filter((asset) => previousAssetKeys.has(asset.key))+ const previousBinding = editor.graph.enabledLibraries.get(libraryId)++ let appliedPlans: ReturnType<typeof planLibraryInstanceUpdates> = []+ let createdRootIds: string[] = []+ const applyRevision = () => {+ const existingNodeIds = new Set(editor.graph.nodes.keys())+ for (const asset of updatable) materializeLibraryAsset(editor.graph, latest, asset.key)+ createdRootIds = [...editor.graph.getAllNodes()]+ .filter((node) => {+ if (existingNodeIds.has(node.id)) return false+ const parent = node.parentId ? editor.graph.getNode(node.parentId) : undefined+ return !parent || existingNodeIds.has(parent.id)+ })+ .map((node) => node.id)+ appliedPlans = planLibraryInstanceUpdates(+ editor.graph,+ libraryId,+ update.currentRevisionId,+ update.latestRevisionId,+ updatable+ )+ for (const plan of appliedPlans) {+ editor.graph.swapInstanceComponent(plan.instanceId, plan.componentId)+ reapplyInstanceComponentProperties(editor, plan.instanceId)+ }+ editor.graph.enabledLibraries.set(libraryId, {+ libraryId,+ revisionId: update.latestRevisionId,+ enabled: true+ })+ editor.requestRender()+ }+ const restorePrevious = () => {+ for (const plan of appliedPlans) {+ editor.graph.swapInstanceComponent(plan.instanceId, plan.previousComponentId)+ reapplyInstanceComponentProperties(editor, plan.instanceId)+ }+ for (const rootId of createdRootIds) {+ if (editor.graph.getNode(rootId)) editor.graph.deleteNode(rootId)+ }+ if (previousBinding) editor.graph.enabledLibraries.set(libraryId, previousBinding)+ else editor.graph.enabledLibraries.delete(libraryId)+ editor.requestRender()+ }++ applyRevision()+ editor.pushUndoEntry({+ label: 'Update library',+ forward: applyRevision,+ inverse: restorePrevious+ })+ await this.refresh(editor)+ }++ async applyInstanceUpdate(editor: EditorStore, instanceId: string): Promise<void> {+ const instance = editor.graph.getNode(instanceId)+ const component =+ instance?.type === 'INSTANCE' && instance.componentId+ ? editor.graph.getNode(instance.componentId)+ : null+ const identity = component?.librarySource?.identity+ if (!identity) return+ const summary = this.#summaries.value.find((item) => item.libraryId === identity.libraryId)+ if (!summary || summary.latestRevisionId === identity.revisionId) return+ const latest = await this.#getRevision(identity.libraryId, summary.latestRevisionId)+ materializeLibraryAsset(editor.graph, latest, identity.assetKey)+ const plans = planOutdatedLibraryInstances(+ editor.graph,+ latest,+ new Set([identity.assetKey]),+ new Set([instanceId])+ )+ if (plans.length === 0) return+ this.#applyPlans(editor, plans, `Update ${component.name}`)+ await this.refresh(editor)+ }++ async getRevision(libraryId: string, revisionId?: string): Promise<ComponentLibraryRevision> {+ return this.#getRevision(libraryId, revisionId)+ }++ async getUpdateGroups(editor: EditorStore): Promise<LibraryAssetUpdateGroup[]> {+ const groups: LibraryAssetUpdateGroup[] = []+ for (const summary of this.#summaries.value) {+ const latest = await this.#getRevision(summary.libraryId, summary.latestRevisionId)+ const assets = new Map(latest.manifest.assets.map((asset) => [asset.key, asset]))+ const previousAssetsByRevision = new Map<string, Map<string, string>>()+ const instancesByAsset = new Map<string, string[]>()+ for (const node of editor.graph.getAllNodes()) {+ if (node.type !== 'INSTANCE' || !node.componentId) continue+ const component = editor.graph.getNode(node.componentId)+ const identity = component?.librarySource?.identity+ if (!component || identity?.libraryId !== summary.libraryId) continue+ if (identity.revisionId === summary.latestRevisionId) continue+ const assetKey = libraryAssetKeyForComponent(editor.graph, component.id)+ const latestAsset = assetKey ? assets.get(assetKey) : undefined+ if (!assetKey || !latestAsset) continue+ let previousAssets = previousAssetsByRevision.get(identity.revisionId)+ if (!previousAssets) {+ const previous = await this.#getRevision(summary.libraryId, identity.revisionId)+ previousAssets = new Map(+ previous.manifest.assets.map((asset) => [asset.key, asset.contentHash])+ )+ previousAssetsByRevision.set(identity.revisionId, previousAssets)+ }+ if (previousAssets.get(assetKey) === latestAsset.contentHash) continue+ const ids = instancesByAsset.get(assetKey) ?? []+ ids.push(node.id)+ instancesByAsset.set(assetKey, ids)+ }+ for (const [assetKey, instanceIds] of instancesByAsset) {+ const asset = assets.get(assetKey)+ if (!asset) continue+ groups.push({+ libraryId: summary.libraryId,+ assetKey,+ name: asset.name,+ instanceIds,+ currentPageCount: instanceIds.length,+ allPagesCount: instanceIds.length+ })+ }+ }+ return groups+ }++ async #plansForGroups(+ editor: EditorStore,+ groups: LibraryAssetUpdateGroup[]+ ): Promise<ReturnType<typeof planOutdatedLibraryInstances>> {+ const plans: ReturnType<typeof planOutdatedLibraryInstances> = []+ for (const group of groups) {+ const latest = await this.#getRevision(group.libraryId)+ materializeLibraryAsset(editor.graph, latest, group.assetKey)+ plans.push(+ ...planOutdatedLibraryInstances(+ editor.graph,+ latest,+ new Set([group.assetKey]),+ new Set(group.instanceIds)+ )+ )+ }+ return plans+ }++ async applyAllUpdates(editor: EditorStore): Promise<void> {+ const groups = await this.getUpdateGroups(editor)+ const plans = await this.#plansForGroups(editor, groups)+ if (plans.length === 0) return+ this.#applyPlans(editor, plans, 'Update all library assets')+ await this.refresh(editor)+ }++ async applyUpdateGroups(+ editor: EditorStore,+ groups: LibraryAssetUpdateGroup[],+ label = 'Update library assets'+ ): Promise<void> {+ const plans = await this.#plansForGroups(editor, groups)+ if (plans.length === 0) return+ this.#applyPlans(editor, plans, label)+ await this.refresh(editor)+ }++ async applyInstanceIdsUpdate(+ editor: EditorStore,+ libraryId: string,+ assetKey: string,+ instanceIds: string[],+ label = 'Update library instances'+ ): Promise<void> {+ const latest = await this.#getRevision(libraryId)+ materializeLibraryAsset(editor.graph, latest, assetKey)+ const plans = planOutdatedLibraryInstances(+ editor.graph,+ latest,+ new Set([assetKey]),+ new Set(instanceIds)+ )+ if (plans.length === 0) return+ this.#applyPlans(editor, plans, label)+ await this.refresh(editor)+ }++ async applyAssetUpdate(editor: EditorStore, libraryId: string, assetKey: string): Promise<void> {+ const summary = this.#summaries.value.find((item) => item.libraryId === libraryId)+ if (!summary) return+ const latest = await this.#getRevision(libraryId, summary.latestRevisionId)+ materializeLibraryAsset(editor.graph, latest, assetKey)+ const plans = planOutdatedLibraryInstances(editor.graph, latest, new Set([assetKey]))+ if (plans.length === 0) return+ this.#applyPlans(editor, plans, 'Update library asset')+ await this.refresh(editor)+ }++ #applyPlans(+ editor: EditorStore,+ plans: ReturnType<typeof planOutdatedLibraryInstances>,+ label: string+ ): void {+ const apply = () => {+ for (const plan of plans) {+ editor.graph.swapInstanceComponent(plan.instanceId, plan.componentId)+ reapplyInstanceComponentProperties(editor, plan.instanceId)+ }+ editor.requestRender()+ }+ const restore = () => {+ for (const plan of plans) {+ editor.graph.swapInstanceComponent(plan.instanceId, plan.previousComponentId)+ reapplyInstanceComponentProperties(editor, plan.instanceId)+ }+ editor.requestRender()+ }+ apply()+ editor.pushUndoEntry({ label, forward: apply, inverse: restore })+ }++ async discoverPublicationChanges(editor: EditorStore): Promise<{+ publication: ReturnType<typeof readSourceLibraryPublication>+ changes: LibraryAssetChange[]+ }> {+ const publication = readSourceLibraryPublication(editor.graph)+ if (!publication) return { publication: null, changes: [] }+ const previous = await this.#getRevision(publication.libraryId, publication.revisionId)+ const { changes } = await discoverPublishableLibraryChanges(previous, editor.graph)+ return { publication, changes }+ }++ async publishSelected(+ editor: EditorStore,+ input: {+ libraryId: string+ name: string+ description?: string+ selectedAssetKeys: ReadonlySet<string>+ }+ ): Promise<ComponentLibraryRevision> {+ const publication = readSourceLibraryPublication(editor.graph)+ let revision: ComponentLibraryRevision+ if (publication) {+ const previous = await this.#getRevision(publication.libraryId, publication.revisionId)+ revision = await createSelectiveLibraryRevision({+ previous,+ sourceGraph: editor.graph,+ selectedAssetKeys: input.selectedAssetKeys,+ name: input.name,+ description: input.description+ })+ revision = await this.#catalog.publishRevision({+ libraryId: revision.manifest.libraryId,+ name: revision.manifest.name,+ graph: revision.graph,+ assetNodeIds: revision.manifest.assets.map((asset) => asset.sourceNodeId),+ previousRevisionId: revision.manifest.previousRevisionId,+ description: revision.manifest.description,+ publishedAt: revision.manifest.publishedAt+ })+ } else {+ revision = await this.publish({+ libraryId: input.libraryId,+ name: input.name,+ graph: editor.graph,+ description: input.description,+ assetNodeIds: [...editor.graph.getAllNodes()]+ .filter(+ (node) =>+ input.selectedAssetKeys.has(node.id) ||+ input.selectedAssetKeys.has(node.componentKey ?? '')+ )+ .map((node) => node.id)+ })+ }+ writeSourceLibraryPublication(editor.graph, {+ libraryId: revision.manifest.libraryId,+ revisionId: revision.manifest.revisionId,+ name: revision.manifest.name,+ catalogSource: this.catalogSource+ })+ this.#revisionCache.set(+ this.#revisionCacheKey(revision.manifest.libraryId, revision.manifest.revisionId),+ revision+ )+ this.#summaries.value = await this.#catalog.listLibraries()+ return revision+ }++ async publish(input: PublishLibraryInput): Promise<ComponentLibraryRevision> {+ ensureLibraryAssetKeys(input.graph, input.assetNodeIds)+ const revision = await this.#catalog.publishRevision(input)+ this.#revisionCache.set(+ this.#revisionCacheKey(input.libraryId, revision.manifest.revisionId),+ revision+ )+ this.#summaries.value = await this.#catalog.listLibraries()+ return revision+ }++ async enable(editor: EditorStore, libraryId: string, revisionId?: string): Promise<void> {+ const revision = await this.#getRevision(libraryId, revisionId)+ editor.graph.enabledLibraries.set(libraryId, {+ libraryId,+ revisionId: revision.manifest.revisionId,+ enabled: true+ })+ await this.refresh(editor)+ }++ async disable(editor: EditorStore, libraryId: string): Promise<void> {+ const binding = editor.graph.enabledLibraries.get(libraryId)+ if (binding) editor.graph.enabledLibraries.set(libraryId, { ...binding, enabled: false })+ await this.refresh(editor)+ }++ async materialize(editor: EditorStore, libraryId: string, revisionId: string, assetKey: string) {+ const revision = await this.#getRevision(libraryId, revisionId)+ const result = materializeLibraryAsset(editor.graph, revision, assetKey)+ editor.requestRender()+ return result+ }++ #revisionCacheKey(libraryId: string, revisionId: string): string {+ return `${libraryId}\u0000${revisionId}`+ }++ async #getRevision(libraryId: string, revisionId?: string): Promise<ComponentLibraryRevision> {+ if (revisionId) {+ const cached = this.#revisionCache.get(this.#revisionCacheKey(libraryId, revisionId))+ if (cached) return cached+ }+ const revision = await this.#catalog.getRevision(libraryId, revisionId)+ this.#revisionCache.set(+ this.#revisionCacheKey(libraryId, revision.manifest.revisionId),+ revision+ )+ return revision+ }+}++let service: LibraryService | undefined++export function useLibraryService(): LibraryService {+ service ??= new LibraryService()+ return service+}diff --git a/src/app/libraries/update-groups.ts b/src/app/libraries/update-groups.tsnew file mode 100644index 000000000..b1d6c62f3--- /dev/null+++ b/src/app/libraries/update-groups.ts@@ -0,0 +1,36 @@+import type { EditorStore } from '@/app/editor/session'++export interface LibraryAssetUpdateGroup {+ libraryId: string+ assetKey: string+ name: string+ instanceIds: string[]+ currentPageCount: number+ allPagesCount: number+}++function pageIdForNode(editor: EditorStore, nodeId: string): string | null {+ let node = editor.graph.getNode(nodeId)+ while (node?.parentId) {+ const parent = editor.graph.getNode(node.parentId)+ if (parent?.type === 'CANVAS') return parent.id+ node = parent+ }+ return null+}++export function scopeLibraryUpdateGroups(+ editor: EditorStore,+ groups: LibraryAssetUpdateGroup[],+ allPages: boolean+): LibraryAssetUpdateGroup[] {+ if (allPages) return groups+ return groups.flatMap((group) => {+ const instanceIds = group.instanceIds.filter(+ (instanceId) => pageIdForNode(editor, instanceId) === editor.state.currentPageId+ )+ return instanceIds.length > 0+ ? [{ ...group, instanceIds, currentPageCount: instanceIds.length }]+ : []+ })+}diff --git a/src/components/DesignPanel.vue b/src/components/DesignPanel.vueindex 083d53e53..f197f55d0 100644--- a/src/components/DesignPanel.vue+++ b/src/components/DesignPanel.vue@@ -4,6 +4,7 @@ import { computed, ref } from 'vue'import { useI18n, useSelectionState, useEditorCommands } from '@open-pencil/vue'import { useEditorStore } from '@/app/editor/active-store'+import { openLibraryReview, useLibraryService } from '@/app/libraries'import { COMPONENT_TYPES, nodeIcon } from '@/app/editor/icons'import PanelHeader from '@/components/ui/panel/PanelHeader.vue'import Tip from '@/components/ui/Tip.vue'@@ -24,11 +25,14 @@ import StrokeSection from './properties/StrokeSection.vue'import TypographySection from './properties/TypographySection.vue'import VariablesSection from './properties/VariablesSection.vue'import ComponentPropertiesSection from './properties/component-properties/ComponentPropertiesSection.vue'+import VariantAuthoringSection from './properties/component-properties/VariantAuthoringSection.vue'+import InstanceUpdateAction from './properties/component-properties/instance-update/InstanceUpdateAction.vue'import FramePresetsSection from './properties/frame-presets/FramePresetsSection.vue'import FramePresetSelect from './properties/frame-presets/FramePresetSelect.vue'const variablesOpen = ref(false)const store = useEditorStore()+const libraryService = useLibraryService()const activeTool = computed(() => store.state.activeTool)const { selectedNode: node, selectedCount: multiCount } = useSelectionState()const showBooleanOperations = computed(() => multiCount.value >= 2)@@ -40,6 +44,19 @@ const isComponentType = computed(() => {return type ? COMPONENT_TYPES.has(type) : false})const selectedIcon = computed(() => (node.value ? nodeIcon(node.value) : undefined))+function openSelectedInstanceReview() {+ const instance = node.value+ if (instance?.type !== 'INSTANCE' || !instance.componentId) return+ const component = store.graph.getNode(instance.componentId)+ const identity = component?.librarySource?.identity+ if (!identity) return+ openLibraryReview({+ libraryId: identity.libraryId,+ assetKey: identity.assetKey,+ instanceIds: [instance.id],+ initialInstanceId: instance.id+ })+}const supportsLayoutGuides = computed(() => {const type = node.value?.typereturn type === 'FRAME' || type === 'COMPONENT' || type === 'COMPONENT_SET' || type === 'INSTANCE'@@ -99,6 +116,13 @@ const { panels } = useI18n()</template><span role="heading" aria-level="2">{{ node.name }}</span><template #actions>+ <InstanceUpdateAction+ v-if="node.type === 'INSTANCE'"+ :node="node"+ :editor="store"+ :service="libraryService"+ @review="openSelectedInstanceReview"+ /><SelectionActionsControl /></template></PanelHeader>@@ -125,6 +149,14 @@ const { panels } = useI18n()</div><ComponentPropertiesSection v-if="node.type === 'INSTANCE'" />+ <VariantAuthoringSection+ v-if="+ node.type === 'COMPONENT_SET' ||+ (node.type === 'COMPONENT' &&+ node.parentId &&+ store.graph.getNode(node.parentId)?.type === 'COMPONENT_SET')+ "+ /><FramePresetSelect v-if="node.type === 'FRAME'" />diff --git a/src/components/assets-panel/AssetsPanel.vue b/src/components/assets-panel/AssetsPanel.vueindex 7f57bb7e3..e26ffaf62 100644--- a/src/components/assets-panel/AssetsPanel.vue+++ b/src/components/assets-panel/AssetsPanel.vue@@ -1,6 +1,6 @@<script setup lang="ts">import { useObjectUrl } from '@vueuse/core'-import { computed, ref, shallowRef, watch } from 'vue'+import { computed, onMounted, ref, shallowRef, watch } from 'vue'import {ContextMenuContent,ContextMenuItem,@@ -12,11 +12,15 @@ import {} from 'reka-ui'import type { SceneNode } from '@open-pencil/scene-graph'+import { createDefaultNode } from '@open-pencil/scene-graph/node-defaults'import { useI18n } from '@open-pencil/vue'import { nodeIcon } from '@/app/editor/icons'import { useEditorStore } from '@/app/editor/active-store'+import { useLibraryService } from '@/app/libraries'import { openExternalLink } from '@/app/shell/ui'+import LibraryManagerDialog from '@/components/libraries/LibraryManagerDialog.vue'+import { useLibraryEntry } from '@/components/libraries/useLibraryEntry'import AssetThumbnail from '@/components/assets-panel/AssetThumbnail.vue'import { findAssetPage } from '@/components/assets-panel/page'import AppInput from '@/components/ui/AppInput.vue'@@ -41,6 +45,10 @@ type LocalAsset = {sourceLibraryKey: string | nulldescription: stringdocsURL: string | null+ libraryId: string | null+ revisionId: string | null+ assetKey: string | null+ libraryName: string | nullpageId: stringpageName: string}@@ -52,14 +60,23 @@ type AssetGroup = {}const editor = useEditorStore()+const libraryService = useLibraryService()+const remoteAssets = libraryService.enabledAssetsconst { panels, commands } = useI18n()const query = ref('')const assetView = ref<AssetView>('grid')const detailsOpen = ref(false)+const {+ open: librariesOpen,+ initialSection: libraryInitialSection,+ updateCount: libraryUpdateCount,+ openManager: openLibraries+} = useLibraryEntry(editor, libraryService)const selectedAssetId = ref<string | null>(null)const previewBlob = shallowRef<Blob | null>(null)const previewURL = useObjectUrl(previewBlob)const previewLoading = ref(false)+const insertingAssetId = ref<string | null>(null)let previewRequestId = 0const insertButton = useButtonUI({ tone: 'ghost', size: 'iconSm' })const primaryButton = useButtonUI({ tone: 'accent', size: 'md' })@@ -99,7 +116,8 @@ const pageByNodeId = computed(() => {})const assets = computed<LocalAsset[]>(() => {- return assetNodes.value+ const local = assetNodes.value+ .filter((node) => !node.librarySource?.readOnly).filter((node) => {if (node.type === 'COMPONENT_SET') return trueconst parent = node.parentId ? editor.graph.getNode(node.parentId) : null@@ -123,11 +141,38 @@ const assets = computed<LocalAsset[]>(() => {sourceLibraryKey: node.sourceLibraryKey,description: node.symbolDescription,docsURL: node.symbolLinks[0]?.uri ?? null,+ libraryId: null,+ revisionId: null,+ assetKey: null,+ libraryName: null,pageId: page?.id ?? editor.state.currentPageId,pageName: page?.name ?? panels.value.page}}).sort((a, b) => a.name.localeCompare(b.name))+ const remote = remoteAssets.value.map(({ libraryId, libraryName, revisionId, asset }) => ({+ id: `${libraryId}:${asset.key}`,+ name: asset.name,+ node: createDefaultNode(() => asset.sourceNodeId, asset.type, {+ name: asset.name,+ symbolDescription: asset.description,+ sourceLibraryKey: asset.key+ }),+ componentId: null,+ variants: [],+ variantCount: 0,+ hasConflicts: false,+ sourceLibraryKey: asset.key,+ description: asset.description,+ docsURL: null,+ libraryId,+ revisionId,+ assetKey: asset.key,+ libraryName,+ pageId: `library:${libraryId}`,+ pageName: libraryName+ }))+ return [...local, ...remote]})const filteredAssets = computed(() => {@@ -155,6 +200,10 @@ const selectedAsset = computed()const selectedPreviewNodeId = computed(() => selectedAsset.value?.componentId ?? null)+onMounted(() => {+ void libraryService.refresh(editor)+})+function clearPreview() {previewBlob.value = null}@@ -209,13 +258,31 @@ function insertionPoint(component: SceneNode, parentId: string) {}}-function insertAsset(asset: LocalAsset) {- if (!asset.componentId) return- const component = editor.graph.getNode(asset.componentId)+async function resolveAssetComponent(asset: LocalAsset): Promise<string | null> {+ if (asset.componentId) return asset.componentId+ if (!asset.libraryId || !asset.revisionId || !asset.assetKey) return null+ insertingAssetId.value = asset.id+ try {+ const result = await libraryService.materialize(+ editor,+ asset.libraryId,+ asset.revisionId,+ asset.assetKey+ )+ return result.componentId+ } finally {+ insertingAssetId.value = null+ }+}++async function insertAsset(asset: LocalAsset) {+ const componentId = await resolveAssetComponent(asset)+ if (!componentId) return+ const component = editor.graph.getNode(componentId)if (!component) returnconst parentId = editor.state.enteredContainerId ?? editor.state.currentPageIdconst point = insertionPoint(component, parentId)- editor.createInstanceFromComponent(asset.componentId, point.x, point.y, parentId)+ editor.createInstanceFromComponent(componentId, point.x, point.y, parentId)editor.requestRender()}@@ -226,6 +293,7 @@ function onDragStart(event: DragEvent, asset: LocalAsset) {}function focusAsset(asset: LocalAsset) {+ if (asset.libraryId) returnvoid editor.focusComponent(asset.id)}@@ -237,13 +305,13 @@ function onAssetKeydown(event: KeyboardEvent, asset: LocalAsset) {}if (event.code === 'Enter' || event.code === 'Space') {event.preventDefault()- insertAsset(asset)+ void insertAsset(asset)}}-function insertSelectedAsset() {+async function insertSelectedAsset() {if (!selectedAsset.value) return- insertAsset(selectedAsset.value)+ await insertAsset(selectedAsset.value)detailsOpen.value = false}</script>@@ -259,6 +327,21 @@ function insertSelectedAsset() {class="min-w-0 flex-1":placeholder="panels.searchLocalComponents"/>+ <button+ type="button"+ :class="insertButton.base"+ class="relative"+ :aria-label="libraryUpdateCount > 0 ? panels.reviewLibraryUpdates : panels.manageLibraries"+ @click="openLibraries"+ >+ <icon-lucide-library class="size-3.5" />+ <span+ v-if="libraryUpdateCount > 0"+ class="absolute top-0.5 right-0.5 min-w-2.5 rounded-full bg-accent px-0.5 text-center text-[8px] leading-2.5 text-white"+ >+ {{ libraryUpdateCount }}+ </span>+ </button><SegmentedControlv-model="assetView"data-test-id="assets-view-toggle"@@ -287,6 +370,7 @@ function insertSelectedAsset() {data-test-id="asset-item":data-asset-id="asset.id":draggable="!!asset.componentId"+ :aria-busy="insertingAssetId === asset.id":class="['group/asset rounded text-left text-xs text-surface outline-none hover:bg-hover focus-visible:ring-1 focus-visible:ring-accent',assetView === 'grid'@@ -366,6 +450,7 @@ function insertSelectedAsset() {type="button":class="insertButton.base"data-test-id="asset-insert"+ :disabled="insertingAssetId === asset.id"@pointerdown.stop@click.stop="insertAsset(asset)">@@ -378,6 +463,7 @@ function insertSelectedAsset() {<ContextMenuPortal><ContextMenuContent :class="contextMenu.content"><ContextMenuItem+ v-if="!asset.libraryId"data-test-id="asset-context-go-to-main":class="contextMenu.item"@select="focusAsset(asset)"@@ -409,6 +495,8 @@ function insertSelectedAsset() {</AppPlaceholder></div>+ <LibraryManagerDialog v-model="librariesOpen" :initial-section="libraryInitialSection" />+<AppDialogRootv-if="selectedAsset"v-model:open="detailsOpen"diff --git a/src/components/libraries/LibraryManagerDialog.vue b/src/components/libraries/LibraryManagerDialog.vuenew file mode 100644index 000000000..f9ac6883d--- /dev/null+++ b/src/components/libraries/LibraryManagerDialog.vue@@ -0,0 +1,201 @@+<script setup lang="ts">+import { nextTick, watch } from 'vue'++import { useI18n } from '@open-pencil/vue'++import { useEditorStore } from '@/app/editor/active-store'+import { openLibraryReview, openPublishLibraryDialog, useLibraryService } from '@/app/libraries'+import { useLibraryManager } from '@/components/libraries/useLibraryManager'+import AppPlaceholder from '@/components/ui/AppPlaceholder.vue'+import AppSwitch from '@/components/ui/AppSwitch.vue'+import { AppDialogFooter, AppDialogHeader, AppDialogRoot } from '@/components/ui/dialog'++const { initialSection = 'browse' } = defineProps<{+ initialSection?: 'browse' | 'updates'+}>()+const open = defineModel<boolean>({ required: true })+const editor = useEditorStore()+const service = useLibraryService()+const { panels, dialogs } = useI18n()++async function openPublish() {+ open.value = false+ await nextTick()+ openPublishLibraryDialog()+}+const {+ section,+ loading,+ showAllPages,+ applying,+ visibleUpdateGroups,+ setSource,+ toggleLibrary,+ preferLibrary,+ updateAsset,+ updateAll+} = useLibraryManager(open, editor, service)+watch(open, (isOpen) => {+ if (isOpen) section.value = initialSection+})+function reviewUpdate(group: (typeof visibleUpdateGroups.value)[number]) {+ const initialInstanceId = group.instanceIds[0]+ if (!initialInstanceId) return+ openLibraryReview({+ libraryId: group.libraryId,+ assetKey: group.assetKey,+ instanceIds: group.instanceIds,+ initialInstanceId+ })+}++const navigationClass =+ 'flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs text-muted transition-colors hover:bg-hover hover:text-surface data-[state=active]:bg-hover data-[state=active]:text-surface'+</script>++<template>+ <AppDialogRoot v-model:open="open" size="lg" height="tall" data-test-id="asset-libraries-dialog">+ <AppDialogHeader+ :heading="panels.manageLibraries"+ :description="panels.manageLibrariesDescription"+ :close-label="dialogs.close"+ >+ <template #actions>+ <button+ type="button"+ class="ml-auto text-xs text-component hover:underline"+ @click="openPublish"+ >+ {{ panels.publishLibrary }}+ </button>+ </template>+ </AppDialogHeader>+ <div class="flex min-h-0 flex-1">+ <nav class="w-40 shrink-0 border-r border-border p-2" :aria-label="panels.manageLibraries">+ <button+ type="button"+ :class="navigationClass"+ :data-state="section === 'browse' ? 'active' : 'inactive'"+ @click="section = 'browse'"+ >+ <icon-lucide-library class="size-3.5" /> {{ panels.browseLibraries }}+ </button>+ <button+ type="button"+ :class="navigationClass"+ :data-state="section === 'updates' ? 'active' : 'inactive'"+ @click="section = 'updates'"+ >+ <icon-lucide-refresh-cw class="size-3.5" /> {{ panels.libraryUpdates }}+ <span+ v-if="visibleUpdateGroups.length"+ class="ml-auto rounded-full bg-accent px-1.5 text-[10px] text-white"+ >{{ visibleUpdateGroups.length }}</span+ >+ </button>+ </nav>+ <section v-if="section === 'browse'" class="min-h-0 flex-1 overflow-y-auto p-4">+ <div class="mb-4 flex gap-1">+ <button+ type="button"+ class="rounded px-2 py-1 text-xs data-[active=true]:bg-hover"+ :data-active="service.catalogSource === 'local'"+ @click="setSource('local')"+ >+ {{ panels.localLibraries }}+ </button>+ <button+ type="button"+ class="rounded px-2 py-1 text-xs data-[active=true]:bg-hover"+ :data-active="service.catalogSource === 'storage'"+ @click="setSource('storage')"+ >+ {{ panels.storageLibraries }}+ </button>+ </div>+ <div+ v-for="library in service.summaries.value"+ :key="library.libraryId"+ class="flex items-center gap-3 border-b border-border py-3"+ >+ <icon-lucide-library class="size-4 text-component" />+ <div class="min-w-0 flex-1">+ <p class="truncate text-xs text-surface">{{ library.name }}</p>+ <p class="text-[10px] text-muted">+ {{ panels.libraryAssetCount({ count: library.assetCount }) }}+ </p>+ </div>+ <button+ v-if="editor.graph.enabledLibraries.get(library.libraryId)?.enabled"+ type="button"+ class="text-muted hover:text-component"+ :aria-label="panels.preferLibrary"+ @click="preferLibrary(library.libraryId)"+ >+ <icon-lucide-star class="size-4" />+ </button>+ <button+ type="button"+ class="rounded border border-border px-2 py-1 text-xs"+ @click="toggleLibrary(library.libraryId)"+ >+ {{+ editor.graph.enabledLibraries.get(library.libraryId)?.enabled+ ? panels.disableLibrary+ : panels.enableLibrary+ }}+ </button>+ </div>+ <AppPlaceholder+ v-if="!loading && service.summaries.value.length === 0"+ :label="panels.noLibraries"+ size="compact"+ />+ </section>+ <section v-else class="flex min-h-0 flex-1 flex-col">+ <div class="min-h-0 flex-1 overflow-y-auto p-4">+ <h3 class="mb-3 text-sm font-semibold text-surface">{{ panels.libraryUpdates }}</h3>+ <div+ v-for="asset in visibleUpdateGroups"+ :key="`${asset.libraryId}:${asset.assetKey}`"+ class="flex items-center gap-3 border-b border-border py-3"+ >+ <icon-lucide-component class="size-4 text-component" />+ <div class="min-w-0 flex-1">+ <button type="button" class="block w-full text-left" @click="reviewUpdate(asset)">+ <p class="truncate text-xs text-surface">{{ asset.name }}</p>+ <p data-test-id="library-update-instance-count" class="text-[10px] text-muted">+ {{ panels.libraryInstanceCount({ count: asset.instanceIds.length }) }}+ </p>+ </button>+ </div>+ <button+ type="button"+ class="rounded border border-border px-3 py-1 text-xs"+ :disabled="applying !== null"+ @click="updateAsset(asset)"+ >+ {{ panels.updateLibraryAsset }}+ </button>+ </div>+ <AppPlaceholder+ v-if="visibleUpdateGroups.length === 0"+ :label="panels.noLibraryUpdates"+ size="compact"+ />+ </div>+ <AppDialogFooter :ui="{ footer: 'justify-between' }">+ <AppSwitch v-model="showAllPages" :label="panels.showUpdatesForAllPages" />+ <button+ type="button"+ class="rounded bg-accent px-3 py-1.5 text-xs text-white disabled:opacity-50"+ :disabled="visibleUpdateGroups.length === 0 || applying !== null"+ @click="updateAll"+ >+ {{ panels.updateAll }}+ </button>+ </AppDialogFooter>+ </section>+ </div>+ </AppDialogRoot>+</template>diff --git a/src/components/libraries/PublishLibraryDialog.vue b/src/components/libraries/PublishLibraryDialog.vuenew file mode 100644index 000000000..9a47b5130--- /dev/null+++ b/src/components/libraries/PublishLibraryDialog.vue@@ -0,0 +1,239 @@+<script setup lang="ts">+import { computed, ref, watch } from 'vue'++import type { LibraryAssetChange } from '@open-pencil/core/library'+import {+ ensureLibraryAssetKeys,+ publishableLibraryRoots,+ readSourceLibraryPublication+} from '@open-pencil/core/library'+import { useI18n } from '@open-pencil/vue'++import { useEditorStore } from '@/app/editor/active-store'+import { publishLibraryDialogOpen, useLibraryService } from '@/app/libraries'+import AppCheckbox from '@/components/ui/AppCheckbox.vue'+import AppInput from '@/components/ui/AppInput.vue'+import AppPlaceholder from '@/components/ui/AppPlaceholder.vue'+import AppTextarea from '@/components/ui/AppTextarea.vue'+import { AppDialogFooter, AppDialogHeader, AppDialogRoot } from '@/components/ui/dialog'++const editor = useEditorStore()+const service = useLibraryService()+const { panels } = useI18n()+const libraryId = ref('')+const libraryName = ref('')+const description = ref('')+const query = ref('')+const publishing = ref(false)+const loading = ref(false)+const error = ref('')+const changes = ref<LibraryAssetChange[]>([])+const selectedKeys = ref(new Set<string>())+const changeLabels = computed(() => ({+ added: panels.value.libraryChangeAdded,+ modified: panels.value.libraryChangeModified,+ renamed: panels.value.libraryChangeRenamed,+ removed: panels.value.libraryChangeRemoved+}))+const publication = computed(() => readSourceLibraryPublication(editor.graph))+const visibleChanges = computed(() => {+ const normalized = query.value.trim().toLowerCase()+ return normalized+ ? changes.value.filter((change) => change.asset.name.toLowerCase().includes(normalized))+ : changes.value+})+const selectionState = computed<boolean | 'indeterminate'>(() => {+ const visibleKeys = visibleChanges.value.map((change) => change.asset.key)+ const selectedVisible = visibleKeys.filter((key) => selectedKeys.value.has(key)).length+ if (selectedVisible === 0) return false+ return selectedVisible === visibleKeys.length ? true : 'indeterminate'+})++watch(publishLibraryDialogOpen, async (open) => {+ if (!open) return+ error.value = ''+ query.value = ''+ loading.value = true+ const existing = publication.value+ libraryId.value = existing?.libraryId ?? libraryId.value+ libraryName.value = existing?.name ?? editor.graph.getNode(editor.graph.rootId)?.name ?? ''+ try {+ if (existing) {+ const discovered = await service.discoverPublicationChanges(editor)+ changes.value = discovered.changes+ } else {+ const roots = publishableLibraryRoots(editor.graph)+ ensureLibraryAssetKeys(+ editor.graph,+ roots.map((node) => node.id)+ )+ changes.value = roots.map((node) => ({+ kind: 'added' as const,+ asset: {+ key: node.componentKey ?? node.id,+ name: node.name,+ description: '',+ type: node.type,+ sourceNodeId: node.id,+ contentHash: ''+ }+ }))+ }+ selectedKeys.value = new Set(changes.value.map((change) => change.asset.key))+ } catch (cause) {+ error.value = cause instanceof Error ? cause.message : panels.value.libraryPublishFailed+ } finally {+ loading.value = false+ }+})++function toggleAll(value: boolean) {+ const visibleKeys = visibleChanges.value.map((change) => change.asset.key)+ const next = new Set(selectedKeys.value)+ for (const key of visibleKeys) {+ if (value) next.add(key)+ else next.delete(key)+ }+ selectedKeys.value = next+}++function toggleAsset(key: string, value: boolean) {+ const next = new Set(selectedKeys.value)+ if (value) next.add(key)+ else next.delete(key)+ selectedKeys.value = next+}++async function publish() {+ const id = libraryId.value.trim()+ const name = libraryName.value.trim()+ if (!id || !name || selectedKeys.value.size === 0 || publishing.value) return+ publishing.value = true+ error.value = ''+ try {+ await service.publishSelected(editor, {+ libraryId: id,+ name,+ description: description.value,+ selectedAssetKeys: selectedKeys.value+ })+ publishLibraryDialogOpen.value = false+ } catch (cause) {+ error.value = cause instanceof Error ? cause.message : panels.value.libraryPublishFailed+ } finally {+ publishing.value = false+ }+}+</script>++<template>+ <AppDialogRoot v-model:open="publishLibraryDialogOpen" size="md" height="tall">+ <AppDialogHeader :heading="panels.publishLibrary" :description="panels.publishLibraryHelp" />+ <form class="flex min-h-0 flex-1 flex-col gap-3 px-4 py-4" @submit.prevent="publish">+ <div class="grid grid-cols-2 gap-3">+ <label class="flex flex-col gap-1.5 text-xs text-muted">+ {{ panels.libraryId }}+ <AppInput v-model="libraryId" required size="md" :disabled="!!publication" />+ </label>+ <label class="flex flex-col gap-1.5 text-xs text-muted">+ {{ panels.libraryName }}+ <AppInput v-model="libraryName" required size="md" />+ </label>+ </div>+ <AppInput+ v-model="query"+ type="search"+ size="md"+ :placeholder="panels.searchLibraryChanges"+ />+ <label class="flex flex-col gap-1.5 text-xs text-muted">+ {{ panels.revisionDescription }}+ <AppTextarea v-model="description" :rows="2" />+ </label>+ <div+ class="flex items-center justify-between rounded-lg border border-border bg-input px-3 py-2 text-xs"+ >+ <span class="text-muted">{{ panels.libraryDestination }}</span>+ <span>{{+ service.catalogSource === 'storage' ? panels.storageLibraries : panels.localLibraries+ }}</span>+ </div>+ <div class="flex min-h-0 flex-1 flex-col overflow-hidden rounded-lg border border-border">+ <div class="flex items-center gap-2 border-b border-border px-3 py-2 text-xs font-medium">+ <AppCheckbox+ :model-value="selectionState"+ :ariaLabel="panels.libraryChanges"+ @update:model-value="toggleAll"+ />+ <span>{{ panels.libraryChanges }}</span>+ <span class="ml-auto text-muted">{{ selectedKeys.size }}/{{ changes.length }}</span>+ </div>+ <div v-if="loading" class="px-3 py-6 text-center text-xs text-muted">+ {{ panels.loading }}+ </div>+ <AppPlaceholder+ v-else-if="changes.length === 0"+ :label="panels.noLibraryAssetChanges"+ size="compact"+ >+ <template #icon><icon-lucide-package-check /></template>+ </AppPlaceholder>+ <AppPlaceholder+ v-else-if="visibleChanges.length === 0"+ :label="panels.noLibraryChangesFound"+ size="compact"+ >+ <template #icon><icon-lucide-search-x /></template>+ </AppPlaceholder>+ <div v-else class="min-h-0 overflow-y-auto">+ <label+ v-for="change in visibleChanges"+ :key="change.asset.key"+ class="flex items-center gap-3 border-b border-border px-3 py-2.5 last:border-b-0"+ >+ <AppCheckbox+ :model-value="selectedKeys.has(change.asset.key)"+ :ariaLabel="change.asset.name"+ @update:model-value="(value) => toggleAsset(change.asset.key, value)"+ />+ <div+ class="flex size-10 shrink-0 items-center justify-center rounded-md border border-border bg-canvas text-muted"+ >+ <icon-lucide-layout-template+ v-if="change.asset.type === 'COMPONENT_SET'"+ class="size-4"+ />+ <icon-lucide-component v-else class="size-4" />+ </div>+ <span class="min-w-0 flex-1 truncate text-xs">{{ change.asset.name }}</span>+ <span class="text-[10px] text-muted">{{ changeLabels[change.kind] }}</span>+ </label>+ </div>+ </div>+ <p v-if="error" role="alert" class="text-xs text-danger">{{ error }}</p>+ </form>+ <AppDialogFooter>+ <button+ type="button"+ class="h-8 rounded-md px-3 text-xs text-muted hover:bg-hover"+ @click="publishLibraryDialogOpen = false"+ >+ {{ panels.cancel }}+ </button>+ <button+ type="button"+ class="h-8 rounded-md bg-accent px-4 text-xs font-medium text-white hover:bg-accent/90 disabled:opacity-50"+ :disabled="+ publishing ||+ loading ||+ selectedKeys.size === 0 ||+ !libraryId.trim() ||+ !libraryName.trim()+ "+ @click="publish"+ >+ {{ publishing ? panels.publishingLibrary : panels.publishLibrary }}+ </button>+ </AppDialogFooter>+ </AppDialogRoot>+</template>diff --git a/src/components/libraries/review/LibraryComparisonPreview.vue b/src/components/libraries/review/LibraryComparisonPreview.vuenew file mode 100644index 000000000..956866159--- /dev/null+++ b/src/components/libraries/review/LibraryComparisonPreview.vue@@ -0,0 +1,38 @@+<script setup lang="ts">+import { useObjectUrl } from '@vueuse/core'+import { shallowRef, watch } from 'vue'++import { renderNodesToImage } from '@open-pencil/core/io'+import type { SceneGraph } from '@open-pencil/scene-graph'++import { useEditorStore } from '@/app/editor/active-store'++const { graph, nodeId, alt } = defineProps<{ graph: SceneGraph; nodeId: string; alt: string }>()+const editor = useEditorStore()+const blob = shallowRef<Blob | null>(null)+const url = useObjectUrl(blob)+let requestId = 0++watch(+ () => [graph, nodeId] as const,+ async () => {+ const request = ++requestId+ const renderer = editor.renderer+ const node = graph.getNode(nodeId)+ const page = graph.getPages()[0]+ if (!renderer || !node || !page) return+ const maxDimension = Math.max(node.width, node.height, 1)+ const data = await renderNodesToImage(renderer.ck, renderer, graph, page.id, [nodeId], {+ scale: 320 / maxDimension,+ format: 'PNG'+ })+ if (request === requestId) blob.value = data ? new Blob([data], { type: 'image/png' }) : null+ },+ { immediate: true }+)+</script>++<template>+ <img v-if="url" :src="url" :alt="alt" class="max-h-[60vh] max-w-[80%] object-contain" />+ <icon-lucide-loader-2 v-else class="size-5 animate-spin text-muted" />+</template>diff --git a/src/components/libraries/review/LibraryUpdateReviewDialog.vue b/src/components/libraries/review/LibraryUpdateReviewDialog.vuenew file mode 100644index 000000000..d5212aa54--- /dev/null+++ b/src/components/libraries/review/LibraryUpdateReviewDialog.vue@@ -0,0 +1,280 @@+<script setup lang="ts">+import { SliderRange, SliderRoot, SliderThumb, SliderTrack } from 'reka-ui'+import { computed, ref, shallowRef, watch } from 'vue'++import { createLibraryUpdatePreview, type LibraryUpdatePreview } from '@open-pencil/core/library'+import { useI18n } from '@open-pencil/vue'++import { useEditorStore } from '@/app/editor/active-store'+import { closeLibraryReview, libraryReviewRequest, useLibraryService } from '@/app/libraries'+import { toast } from '@/app/shell/ui'+import LibraryComparisonPreview from '@/components/libraries/review/LibraryComparisonPreview.vue'+import SegmentedControl from '@/components/ui/SegmentedControl.vue'+import { AppDialogFooter, AppDialogHeader, AppDialogRoot } from '@/components/ui/dialog'++const editor = useEditorStore()+const service = useLibraryService()+const { panels, dialogs } = useI18n()+const preview = shallowRef<LibraryUpdatePreview | null>(null)+const instanceIndex = ref(0)+const mode = ref<'side-by-side' | 'overlay'>('side-by-side')+const opacity = ref([50])+const loading = ref(false)+const applying = ref(false)+interface ReviewOrigin {+ pageId: string+ selectedIds: string[]+ panX: number+ panY: number+ zoom: number+}+let origin: ReviewOrigin | null = null+let accepted = false+let requestId = 0+const open = computed({+ get: () => libraryReviewRequest.value !== null,+ set: (value) => {+ if (!value) closeLibraryReview()+ }+})+const modeOptions = computed(() => [+ { value: 'side-by-side', label: panels.value.sideBySide },+ { value: 'overlay', label: panels.value.overlay }+])+const request = computed(() => libraryReviewRequest.value)+const currentInstanceId = computed(() => request.value?.instanceIds[instanceIndex.value] ?? null)++function pageIdForNode(nodeId: string): string | null {+ let node = editor.graph.getNode(nodeId)+ while (node?.parentId) {+ const parent = editor.graph.getNode(node.parentId)+ if (parent?.type === 'CANVAS') return parent.id+ node = parent+ }+ return null+}++async function focusCurrentInstance() {+ const instanceId = currentInstanceId.value+ if (!instanceId) return+ const pageId = pageIdForNode(instanceId)+ if (pageId && pageId !== editor.state.currentPageId) await editor.switchPage(pageId)+ editor.select([instanceId])+ editor.zoomToSelection()+}++async function loadPreview() {+ const value = request.value+ const instanceId = currentInstanceId.value+ if (!value || !instanceId) return+ const currentRequest = ++requestId+ loading.value = true+ try {+ const revision = await service.getRevision(value.libraryId)+ const next = createLibraryUpdatePreview(editor.graph, instanceId, revision)+ if (currentRequest === requestId) {+ preview.value = next+ await focusCurrentInstance()+ }+ } catch (cause) {+ toast.error(cause instanceof Error ? cause.message : String(cause))+ } finally {+ if (currentRequest === requestId) loading.value = false+ }+}++async function restoreOrigin() {+ const value = origin+ origin = null+ if (!value || accepted) return+ if (editor.state.currentPageId !== value.pageId) await editor.switchPage(value.pageId)+ editor.select(value.selectedIds)+ editor.state.panX = value.panX+ editor.state.panY = value.panY+ editor.state.zoom = value.zoom+ editor.requestRepaint()+}++async function updateInstance() {+ const id = currentInstanceId.value+ if (!id || applying.value) return+ applying.value = true+ try {+ await service.applyInstanceUpdate(editor, id)+ accepted = true+ closeLibraryReview()+ } catch (cause) {+ toast.error(cause instanceof Error ? cause.message : String(cause))+ } finally {+ applying.value = false+ }+}++async function updateAll() {+ const value = request.value+ if (!value || applying.value) return+ applying.value = true+ try {+ await service.applyInstanceIdsUpdate(+ editor,+ value.libraryId,+ value.assetKey,+ value.instanceIds,+ `Update all ${preview.value?.graph.getNode(preview.value.updatedNodeId)?.name ?? value.assetKey} instances`+ )+ accepted = true+ closeLibraryReview()+ } catch (cause) {+ toast.error(cause instanceof Error ? cause.message : String(cause))+ applying.value = false+ }+}++watch(request, (value, previous) => {+ if (!value) {+ if (previous) void restoreOrigin()+ return+ }+ origin = {+ pageId: editor.state.currentPageId,+ selectedIds: [...editor.state.selectedIds],+ panX: editor.state.panX,+ panY: editor.state.panY,+ zoom: editor.state.zoom+ }+ accepted = false+ applying.value = false+ instanceIndex.value = Math.max(0, value.instanceIds.indexOf(value.initialInstanceId))+ mode.value = 'side-by-side'+ opacity.value = [50]+ preview.value = null+})+watch([request, currentInstanceId], () => void loadPreview(), { immediate: true })+</script>++<template>+ <AppDialogRoot v-model:open="open" size="xl" height="full" data-test-id="library-update-review">+ <AppDialogHeader+ :heading="panels.reviewLibraryUpdate"+ :description="panels.reviewLibraryUpdateDescription"+ :close-label="dialogs.close"+ />+ <div+ v-if="request"+ class="border-b border-border px-4 py-3 text-center text-sm font-medium text-surface"+ >+ {{ preview?.graph.getNode(preview.updatedNodeId)?.name ?? panels.reviewLibraryUpdate }}+ </div>+ <div+ v-if="preview?.fallback"+ role="status"+ class="border-b border-warning/40 bg-warning/10 px-4 py-2 text-xs text-warning"+ >+ {{ panels.libraryVariantFallbackWarning }}+ </div>+ <div+ v-if="preview"+ class="relative grid min-h-0 flex-1 bg-canvas"+ :class="mode === 'side-by-side' ? 'grid-cols-2' : 'grid-cols-1'"+ >+ <section class="flex min-h-0 flex-col border-r border-border p-4">+ <h3 class="text-xs font-semibold text-surface">{{ panels.currentVersion }}</h3>+ <div class="flex flex-1 items-center justify-center">+ <LibraryComparisonPreview+ :graph="preview.graph"+ :node-id="preview.currentNodeId"+ :alt="panels.currentVersion"+ />+ </div>+ </section>+ <section+ class="flex min-h-0 flex-col p-4"+ :class="mode === 'overlay' ? 'absolute inset-0' : ''"+ :style="mode === 'overlay' ? { opacity: opacity[0] / 100 } : undefined"+ >+ <h3 class="text-xs font-semibold text-surface">{{ panels.updatedVersion }}</h3>+ <div class="flex flex-1 items-center justify-center">+ <LibraryComparisonPreview+ :graph="preview.graph"+ :node-id="preview.updatedNodeId"+ :alt="panels.updatedVersion"+ />+ </div>+ </section>+ <div class="absolute bottom-3 left-3 flex items-center gap-3 rounded bg-panel p-1 shadow">+ <SegmentedControl+ v-model="mode"+ :options="modeOptions"+ :label="panels.comparisonMode"+ :ui="{ root: 'w-52' }"+ />+ <SliderRoot+ v-if="mode === 'overlay'"+ v-model="opacity"+ :min="0"+ :max="100"+ :step="1"+ :aria-label="panels.overlayOpacity"+ class="relative flex w-32 touch-none items-center"+ >+ <SliderTrack class="relative h-1.5 grow overflow-hidden rounded-full bg-hover">+ <SliderRange class="absolute h-full bg-accent" />+ </SliderTrack>+ <SliderThumb+ class="block size-3.5 rounded-full border border-accent bg-panel shadow outline-none focus-visible:ring-2 focus-visible:ring-accent"+ />+ </SliderRoot>+ <span v-if="mode === 'overlay'" class="w-8 text-right text-[10px] text-muted">+ {{ opacity[0] }}%+ </span>+ </div>+ </div>+ <div v-else class="flex min-h-0 flex-1 items-center justify-center text-xs text-muted">+ {{ loading ? panels.loadingUpdatePreview : panels.noLibraryUpdates }}+ </div>+ <AppDialogFooter :ui="{ footer: 'justify-between' }">+ <div class="flex items-center gap-2 text-xs text-muted">+ <button+ type="button"+ :aria-label="panels.previousLibraryInstance"+ :disabled="applying || instanceIndex === 0"+ @click="instanceIndex--"+ >+ <icon-lucide-chevron-left class="size-4" />+ </button>+ <button+ type="button"+ :aria-label="panels.nextLibraryInstance"+ :disabled="applying || !request || instanceIndex >= request.instanceIds.length - 1"+ @click="instanceIndex++"+ >+ <icon-lucide-chevron-right class="size-4" />+ </button>+ {{+ panels.libraryInstancePosition({+ current: instanceIndex + 1,+ total: request?.instanceIds.length ?? 0+ })+ }}+ </div>+ <div class="flex gap-2">+ <button+ type="button"+ class="rounded border border-border px-3 py-1.5 text-xs"+ :disabled="applying"+ @click="updateInstance"+ >+ {{ panels.updateInstance }}+ </button>+ <button+ type="button"+ class="rounded bg-accent px-3 py-1.5 text-xs text-white"+ :disabled="applying"+ @click="updateAll"+ >+ {{ panels.updateAll }}+ </button>+ </div>+ </AppDialogFooter>+ </AppDialogRoot>+</template>diff --git a/src/components/libraries/useLibraryEntry.ts b/src/components/libraries/useLibraryEntry.tsnew file mode 100644index 000000000..4abebb434--- /dev/null+++ b/src/components/libraries/useLibraryEntry.ts@@ -0,0 +1,23 @@+import { computed, ref } from 'vue'++import type { EditorStore } from '@/app/editor/session'+import type { LibraryService } from '@/app/libraries'++export function useLibraryEntry(editor: EditorStore, service: LibraryService) {+ const open = ref(false)+ const initialSection = ref<'browse' | 'updates'>('browse')+ const updateCount = computed(() => {+ const outdatedBindings = service.summaries.value.filter((summary) => {+ const binding = editor.graph.enabledLibraries.get(summary.libraryId)+ return binding?.enabled && binding.revisionId !== summary.latestRevisionId+ }).length+ return Math.max(outdatedBindings, service.updates.value.length)+ })++ function openManager() {+ initialSection.value = updateCount.value > 0 ? 'updates' : 'browse'+ open.value = true+ }++ return { open, initialSection, updateCount, openManager }+}diff --git a/src/components/libraries/useLibraryManager.ts b/src/components/libraries/useLibraryManager.tsnew file mode 100644index 000000000..d9306bbc9--- /dev/null+++ b/src/components/libraries/useLibraryManager.ts@@ -0,0 +1,143 @@+import { computed, ref, watch, type Ref } from 'vue'++import type { EditorStore } from '@/app/editor/session'+import { createActiveStorageAdapter, storagePreferencesComplete } from '@/app/integrations/storage'+import { activeStorageProviderID } from '@/app/integrations/storage/preferences'+import {+ readLibraryCatalogSource,+ readLibraryPriority,+ StorageLibraryCatalog,+ type LibraryService+} from '@/app/libraries'+import type { LibraryAssetUpdateGroup } from '@/app/libraries/update-groups'+import { scopeLibraryUpdateGroups } from '@/app/libraries/update-groups'+import { toast } from '@/app/shell/ui'++export function useLibraryManager(+ open: Ref<boolean>,+ editor: EditorStore,+ service: LibraryService+) {+ const section = ref<'browse' | 'updates'>('browse')+ const loading = ref(false)+ const showAllPages = ref(false)+ const applying = ref<string | null>(null)+ const updateGroups = ref<LibraryAssetUpdateGroup[]>([])+ let requestId = 0+ const visibleUpdateGroups = computed(() =>+ scopeLibraryUpdateGroups(editor, updateGroups.value, showAllPages.value)+ )++ async function refresh() {+ const request = ++requestId+ loading.value = true+ try {+ await service.refresh(editor)+ const groups = await service.getUpdateGroups(editor)+ if (request === requestId) updateGroups.value = groups+ } catch (cause) {+ if (request === requestId) {+ toast.error(cause instanceof Error ? cause.message : String(cause))+ }+ } finally {+ if (request === requestId) loading.value = false+ }+ }++ async function runOperation(operation: () => Promise<void>): Promise<void> {+ try {+ await operation()+ } catch (cause) {+ toast.error(cause instanceof Error ? cause.message : String(cause))+ }+ }++ async function setSource(source: 'local' | 'storage') {+ await runOperation(async () => {+ if (source === 'local') service.useLocalCatalog()+ else {+ const providerId = activeStorageProviderID.value+ if (!storagePreferencesComplete(providerId)) throw new Error('Storage is not configured')+ const objects = createActiveStorageAdapter(providerId).libraryObjects+ if (!objects) throw new Error('Storage libraries are unavailable')+ service.useStorageCatalog(new StorageLibraryCatalog(objects))+ }+ await refresh()+ })+ }++ async function toggleLibrary(libraryId: string) {+ loading.value = true+ try {+ await runOperation(async () => {+ if (editor.graph.enabledLibraries.get(libraryId)?.enabled)+ await service.disable(editor, libraryId)+ else await service.enable(editor, libraryId)+ await refresh()+ })+ } finally {+ loading.value = false+ }+ }++ function preferLibrary(libraryId: string) {+ const priority = Math.max(+ 0,+ ...service.summaries.value.map((item) => readLibraryPriority(item.libraryId))+ )+ service.setPriority(libraryId, priority + 1)+ }++ async function updateAsset(group: LibraryAssetUpdateGroup) {+ applying.value = `${group.libraryId}:${group.assetKey}`+ try {+ await runOperation(async () => {+ await service.applyUpdateGroups(editor, [group], `Update ${group.name}`)+ await refresh()+ })+ } finally {+ applying.value = null+ }+ }++ async function updateAll() {+ applying.value = 'all'+ try {+ await runOperation(async () => {+ await service.applyUpdateGroups(+ editor,+ visibleUpdateGroups.value,+ 'Update all library assets'+ )+ await refresh()+ })+ } finally {+ applying.value = null+ }+ }++ watch(+ () => [open.value, editor.state.currentPageId] as const,+ ([isOpen]) => {+ if (isOpen) void refresh()+ },+ { immediate: true }+ )++ const source = readLibraryCatalogSource()+ if (source === 'storage' && !open.value) void setSource('storage')++ return {+ section,+ loading,+ showAllPages,+ applying,+ visibleUpdateGroups,+ refresh,+ setSource,+ toggleLibrary,+ preferLibrary,+ updateAsset,+ updateAll+ }+}diff --git a/src/components/properties/component-properties/VariantAuthoringSection.vue b/src/components/properties/component-properties/VariantAuthoringSection.vuenew file mode 100644index 000000000..637117f7d--- /dev/null+++ b/src/components/properties/component-properties/VariantAuthoringSection.vue@@ -0,0 +1,276 @@+<script setup lang="ts">+import { computed, reactive, ref, watch } from 'vue'++import { useI18n, useVariantAuthoring } from '@open-pencil/vue'++import AppInput from '@/components/ui/AppInput.vue'+import IconButton from '@/components/ui/IconButton.vue'+import PanelFieldGroup from '@/components/ui/panel/PanelFieldGroup.vue'+import PanelSection from '@/components/ui/panel/PanelSection.vue'++const {+ active,+ variant,+ definitions,+ diagnostics,+ addProperty,+ renameProperty,+ removeProperty,+ reorderProperties,+ renameValue,+ reorderValues,+ setVariantValue,+ addVariant,+ duplicateVariant,+ removeVariant+} = useVariantAuthoring()+const { panels } = useI18n()+const propertyNames = reactive<Record<string, string>>({})+const propertyValues = reactive<Record<string, string>>({})+const selectedValues = reactive<Record<string, string>>({})+const newPropertyName = ref('')+const newPropertyValue = ref('')+const mutationConflictIds = ref<string[]>([])+const conflictIds = computed(+ () =>+ new Set([+ ...diagnostics.value.flatMap((diagnostic) => diagnostic.componentIds),+ ...mutationConflictIds.value+ ])+)+const selectedHasConflict = computed(() => {+ const variantId = variant.value?.id+ return variantId ? conflictIds.value.has(variantId) : false+})++watch(+ definitions,+ (items) => {+ for (const definition of items) {+ propertyNames[definition.id] = definition.name+ for (const value of definition.values) propertyValues[`${definition.id}:${value}`] = value+ selectedValues[definition.id] =+ variant.value?.componentPropertyValues[definition.name] ?? definition.values[0] ?? ''+ }+ },+ { immediate: true }+)+watch(+ variant,+ (selected) => {+ if (!selected) return+ for (const definition of definitions.value) {+ selectedValues[definition.id] =+ selected.componentPropertyValues[definition.name] ?? definition.values[0] ?? ''+ }+ },+ { immediate: true }+)++function blurInput(event: KeyboardEvent) {+ const target = event.currentTarget+ if (target instanceof HTMLInputElement) target.blur()+}++function commitPropertyName(propertyId: string) {+ const name = propertyNames[propertyId]?.trim()+ const definition = definitions.value.find((item) => item.id === propertyId)+ if (!name || !definition || !renameProperty(propertyId, name)) {+ if (definition) propertyNames[propertyId] = definition.name+ }+}++function moveProperty(propertyId: string, offset: -1 | 1) {+ const ids = definitions.value.map((definition) => definition.id)+ const index = ids.indexOf(propertyId)+ const destination = index + offset+ if (index === -1 || destination < 0 || destination >= ids.length) return+ const [moved] = ids.splice(index, 1)+ if (!moved) return+ ids.splice(destination, 0, moved)+ reorderProperties(ids)+}++function moveValue(propertyId: string, value: string, offset: -1 | 1) {+ const definition = definitions.value.find((item) => item.id === propertyId)+ if (!definition) return+ const values = [...definition.values]+ const index = values.indexOf(value)+ const destination = index + offset+ if (index === -1 || destination < 0 || destination >= values.length) return+ const [moved] = values.splice(index, 1)+ if (!moved) return+ values.splice(destination, 0, moved)+ reorderValues(propertyId, values)+}++function commitPropertyValue(propertyId: string, previousValue: string) {+ const key = `${propertyId}:${previousValue}`+ const value = propertyValues[key]?.trim()+ if (!value || !renameValue(propertyId, previousValue, value)) {+ propertyValues[key] = previousValue+ }+}++function commitSelectedValue(propertyId: string) {+ const value = selectedValues[propertyId]?.trim()+ const definition = definitions.value.find((item) => item.id === propertyId)+ if (!value || !definition) return+ const result = setVariantValue(propertyId, value)+ mutationConflictIds.value = result.kind === 'conflict' ? result.componentIds : []+ if (result.kind === 'invalid' || result.kind === 'conflict') {+ selectedValues[propertyId] = variant.value?.componentPropertyValues[definition.name] ?? ''+ }+}++function createProperty() {+ const name = newPropertyName.value.trim()+ const value = newPropertyValue.value.trim()+ if (!name || !value) return+ addProperty(name, value)+ newPropertyName.value = ''+ newPropertyValue.value = ''+}+</script>++<template>+ <PanelSection v-if="active" :label="panels.variants" :empty="definitions.length === 0">+ <template #actions>+ <IconButton+ :label="variant ? panels.duplicateVariant : panels.addVariant"+ @click="variant ? duplicateVariant() : addVariant()"+ >+ <icon-lucide-plus class="size-3.5" />+ </IconButton>+ <IconButton v-if="variant" :label="panels.removeVariant" @click="removeVariant">+ <icon-lucide-trash-2 class="size-3.5" />+ </IconButton>+ </template>++ <div v-if="variant" class="flex flex-col gap-1.5">+ <PanelFieldGroup+ v-for="definition in definitions"+ :key="definition.id"+ :label="definition.name"+ >+ <AppInput+ v-model="selectedValues[definition.id]"+ size="sm"+ tone="panel"+ :state="selectedHasConflict ? 'invalid' : 'idle'"+ :aria-label="definition.name"+ :data-property="definition.id"+ @change="commitSelectedValue(definition.id)"+ @enter="blurInput"+ />+ </PanelFieldGroup>+ <p+ v-if="selectedHasConflict"+ role="alert"+ class="rounded bg-danger/10 px-2 py-1.5 text-[10px] leading-4 text-danger"+ >+ {{ panels.duplicateVariantValues }}. {{ panels.variantConflictHelp }}.+ </p>+ </div>++ <div v-else-if="definitions.length" class="flex flex-col gap-2">+ <div+ v-for="definition in definitions"+ :key="definition.id"+ class="flex flex-col gap-1.5 rounded border border-border p-1.5"+ :data-property="definition.id"+ >+ <div class="flex items-center gap-1">+ <AppInput+ v-model="propertyNames[definition.id]"+ size="sm"+ tone="panel"+ :aria-label="panels.variantPropertyName"+ @change="commitPropertyName(definition.id)"+ @enter="blurInput"+ />+ <IconButton+ :label="panels.moveVariantPropertyUp"+ :disabled="definitions[0]?.id === definition.id"+ @click="moveProperty(definition.id, -1)"+ >+ <icon-lucide-chevron-up class="size-3.5" />+ </IconButton>+ <IconButton+ :label="panels.moveVariantPropertyDown"+ :disabled="definitions.at(-1)?.id === definition.id"+ @click="moveProperty(definition.id, 1)"+ >+ <icon-lucide-chevron-down class="size-3.5" />+ </IconButton>+ <IconButton :label="panels.removeVariantProperty" @click="removeProperty(definition.id)">+ <icon-lucide-trash-2 class="size-3.5" />+ </IconButton>+ </div>+ <div+ v-for="(value, valueIndex) in definition.values"+ :key="value"+ class="flex items-center gap-1"+ >+ <AppInput+ v-model="propertyValues[`${definition.id}:${value}`]"+ size="sm"+ tone="panel"+ :aria-label="`${definition.name}: ${value}`"+ @change="commitPropertyValue(definition.id, value)"+ @enter="blurInput"+ />+ <IconButton+ :label="panels.moveVariantValueUp"+ :disabled="valueIndex === 0"+ @click="moveValue(definition.id, value, -1)"+ >+ <icon-lucide-chevron-up class="size-3.5" />+ </IconButton>+ <IconButton+ :label="panels.moveVariantValueDown"+ :disabled="valueIndex === definition.values.length - 1"+ @click="moveValue(definition.id, value, 1)"+ >+ <icon-lucide-chevron-down class="size-3.5" />+ </IconButton>+ </div>+ </div>+ <p+ v-if="diagnostics.length"+ role="alert"+ class="rounded bg-danger/10 px-2 py-1.5 text-[10px] leading-4 text-danger"+ >+ {{ panels.duplicateVariantValues }}. {{ panels.variantConflictHelp }}.+ </p>+ </div>++ <p v-else class="py-1 text-[10px] text-muted">{{ panels.noVariantProperties }}</p>++ <form class="mt-2 flex flex-col gap-1.5" @submit.prevent="createProperty">+ <div class="grid grid-cols-2 gap-1">+ <AppInput+ v-model="newPropertyName"+ size="sm"+ tone="panel"+ :placeholder="panels.variantPropertyName"+ :aria-label="panels.variantPropertyName"+ />+ <AppInput+ v-model="newPropertyValue"+ size="sm"+ tone="panel"+ :placeholder="panels.variantPropertyValue"+ :aria-label="panels.variantPropertyValue"+ />+ </div>+ <button+ type="submit"+ class="h-6 rounded bg-hover px-2 text-[10px] text-surface hover:bg-active disabled:opacity-50"+ :disabled="!newPropertyName.trim() || !newPropertyValue.trim()"+ >+ {{ panels.addVariantProperty }}+ </button>+ </form>+ </PanelSection>+</template>diff --git a/src/components/properties/component-properties/instance-update/InstanceUpdateAction.vue b/src/components/properties/component-properties/instance-update/InstanceUpdateAction.vuenew file mode 100644index 000000000..e26b378d5--- /dev/null+++ b/src/components/properties/component-properties/instance-update/InstanceUpdateAction.vue@@ -0,0 +1,70 @@+<script setup lang="ts">+import {+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuPortal,+ DropdownMenuRoot,+ DropdownMenuTrigger+} from 'reka-ui'+import { toRef } from 'vue'++import type { SceneNode } from '@open-pencil/scene-graph'+import { useI18n } from '@open-pencil/vue'++import type { EditorStore } from '@/app/editor/session'+import type { LibraryService } from '@/app/libraries'+import { useInstanceUpdate } from '@/components/properties/component-properties/instance-update/use'+import Tip from '@/components/ui/Tip.vue'+import { useMenuUI } from '@/components/ui/menu'++const { node, editor, service } = defineProps<{+ node: SceneNode | null | undefined+ editor: EditorStore+ service: LibraryService+}>()+const emit = defineEmits<{ review: [] }>()+const { panels } = useI18n()+const menu = useMenuUI({ content: 'min-w-48' })+const { available, updating, updateSelectedInstance } = useInstanceUpdate(+ toRef(() => node),+ editor,+ service+)+</script>++<template>+ <DropdownMenuRoot v-if="available">+ <Tip :label="panels.updateSelectedInstance">+ <DropdownMenuTrigger as-child>+ <button+ type="button"+ data-test-id="instance-update-action"+ class="flex size-7 items-center justify-center rounded bg-accent/10 text-accent hover:bg-accent/20 data-[state=open]:bg-accent/20 disabled:opacity-50"+ :disabled="updating"+ :aria-label="panels.updateSelectedInstance"+ >+ <icon-lucide-refresh-cw class="size-3.5" :class="updating ? 'animate-spin' : ''" />+ </button>+ </DropdownMenuTrigger>+ </Tip>+ <DropdownMenuPortal>+ <DropdownMenuContent align="end" side="bottom" :side-offset="4" :class="menu.content">+ <DropdownMenuItem+ data-test-id="instance-update-selected"+ :class="menu.item"+ :disabled="updating"+ @select="updateSelectedInstance"+ >+ {{ panels.updateSelectedInstance }}+ </DropdownMenuItem>+ <DropdownMenuItem+ data-test-id="instance-review-update"+ :class="menu.item"+ @select="emit('review')"+ >+ {{ panels.reviewLibraryUpdate }}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenuPortal>+ </DropdownMenuRoot>+</template>diff --git a/src/components/properties/component-properties/instance-update/use.ts b/src/components/properties/component-properties/instance-update/use.tsnew file mode 100644index 000000000..40a622b47--- /dev/null+++ b/src/components/properties/component-properties/instance-update/use.ts@@ -0,0 +1,58 @@+import { ref, watch, type Ref } from 'vue'++import { libraryAssetKeyForComponent } from '@open-pencil/core/library'+import type { SceneNode } from '@open-pencil/scene-graph'++import type { EditorStore } from '@/app/editor/session'+import type { LibraryService } from '@/app/libraries'+import { toast } from '@/app/shell/ui'++export function useInstanceUpdate(+ node: Ref<SceneNode | null | undefined>,+ editor: EditorStore,+ service: LibraryService+) {+ const available = ref(false)+ const updating = ref(false)+ let requestId = 0++ async function checkAvailability() {+ const request = ++requestId+ const instance = node.value+ if (instance?.type !== 'INSTANCE' || !instance.componentId) {+ available.value = false+ return+ }+ const component = editor.graph.getNode(instance.componentId)+ const identity = component?.librarySource?.identity+ const assetKey = component ? libraryAssetKeyForComponent(editor.graph, component.id) : null+ const summary = identity+ ? service.summaries.value.find((item) => item.libraryId === identity.libraryId)+ : null+ if (request === requestId) {+ available.value = !!assetKey && !!summary && summary.latestRevisionId !== identity?.revisionId+ }+ }++ async function updateSelectedInstance() {+ const instance = node.value+ if (instance?.type !== 'INSTANCE') return+ updating.value = true+ try {+ await service.applyInstanceUpdate(editor, instance.id)+ available.value = false+ } catch (cause) {+ toast.error(cause instanceof Error ? cause.message : String(cause))+ } finally {+ updating.value = false+ }+ }++ watch(+ () => [node.value?.id, editor.state.sceneVersion, service.summaries.value] as const,+ () => void checkAvailability(),+ { immediate: true }+ )++ return { available, updating, updateSelectedInstance }+}diff --git a/src/components/ui/AppCheckbox.vue b/src/components/ui/AppCheckbox.vuenew file mode 100644index 000000000..618ffeabd--- /dev/null+++ b/src/components/ui/AppCheckbox.vue@@ -0,0 +1,30 @@+<script setup lang="ts">+import { CheckboxIndicator, CheckboxRoot } from 'reka-ui'++const {+ modelValue = false,+ ariaLabel,+ disabled = false+} = defineProps<{+ modelValue?: boolean | 'indeterminate'+ ariaLabel: string+ disabled?: boolean+}>()++const emit = defineEmits<{ 'update:modelValue': [value: boolean] }>()+</script>++<template>+ <CheckboxRoot+ :model-value="modelValue"+ :aria-label="ariaLabel"+ :disabled="disabled"+ class="flex size-4 shrink-0 items-center justify-center rounded border border-border bg-surface text-white outline-none data-[state=checked]:border-accent data-[state=checked]:bg-accent data-[state=indeterminate]:border-accent data-[state=indeterminate]:bg-accent focus-visible:ring-2 focus-visible:ring-accent/40 disabled:opacity-50"+ @update:model-value="(value) => emit('update:modelValue', value === true)"+ >+ <CheckboxIndicator class="flex items-center justify-center">+ <icon-lucide-minus v-if="modelValue === 'indeterminate'" class="size-3" />+ <icon-lucide-check v-else class="size-3" />+ </CheckboxIndicator>+ </CheckboxRoot>+</template>diff --git a/src/components/ui/AppSelect.vue b/src/components/ui/AppSelect.vueindex 538f36808..9e96a3542 100644--- a/src/components/ui/AppSelect.vue+++ b/src/components/ui/AppSelect.vue@@ -20,7 +20,7 @@ import type { ComponentUI } from '@/components/ui/types'interface AppSelectProps<TValue extends string | number> {label?: string- options: { value: TValue; label: string }[]+ options: { value: TValue; label: string; disabled?: boolean }[]placeholder?: stringui?: ComponentUI<AppSelectTheme>}@@ -56,6 +56,7 @@ const styles = tv(theme)()v-for="opt in options":key="String(opt.value)":value="opt.value"+ :disabled="opt.disabled":class="styles.item({ class: ui?.item })"><SelectItemIndicator :class="styles.indicator({ class: ui?.indicator })">diff --git a/src/components/ui/AppTextarea.vue b/src/components/ui/AppTextarea.vuenew file mode 100644index 000000000..734e0349d--- /dev/null+++ b/src/components/ui/AppTextarea.vue@@ -0,0 +1,15 @@+<script setup lang="ts">+import { computed } from 'vue'+import { tv } from 'tailwind-variants'++import theme from '@/theme/textarea'++const model = defineModel<string>({ default: '' })++const { rows = 3, disabled = false } = defineProps<{ rows?: number; disabled?: boolean }>()+const textareaClass = computed(() => tv(theme)())+</script>++<template>+ <textarea v-model="model" :rows="rows" :disabled="disabled" :class="textareaClass" />+</template>diff --git a/src/theme/textarea.ts b/src/theme/textarea.tsnew file mode 100644index 000000000..cdbacec86--- /dev/null+++ b/src/theme/textarea.ts@@ -0,0 +1,3 @@+export default {+ base: 'w-full resize-none rounded-md border border-border bg-input px-3 py-2 text-xs leading-relaxed text-surface outline-none placeholder:text-muted hover:border-muted/60 focus:border-panel-focus focus:ring-1 focus:ring-accent/25 disabled:cursor-not-allowed disabled:opacity-60'+}diff --git a/tests/e2e/components/library-lifecycle.spec.ts b/tests/e2e/components/library-lifecycle.spec.tsnew file mode 100644index 000000000..5e18a5a5b--- /dev/null+++ b/tests/e2e/components/library-lifecycle.spec.ts@@ -0,0 +1,273 @@+import { expect, test, type Page } from '@playwright/test'++import { CanvasHelper } from '#tests/helpers/canvas'++async function openAssets(page: Page) {+ await page.getByTestId('left-panel-assets-tab').click()+}++async function openLibraries(page: Page) {+ await page.getByRole('button', { name: 'Manage libraries' }).click()+}++test('preserves source publication identity across FIG save and reopen', async ({ page }) => {+ const canvas = new CanvasHelper(page)+ await page.goto('/?test')+ await canvas.waitForInit()+ const componentId = await page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const pageNode = store.graph.getNode(store.state.currentPageId)+ if (!pageNode) throw new Error('Current page missing')+ return store.graph.createNode('COMPONENT', pageNode.id, {+ name: 'Source button',+ componentKey: 'source-button',+ width: 80,+ height: 32+ }).id+ })++ await openAssets(page)+ await openLibraries(page)+ await page.getByRole('button', { name: 'Publish library' }).click()+ const publish = page.getByRole('dialog').filter({ hasText: 'Publish library' })+ await publish.getByLabel('Library ID').fill('source-lifecycle')+ await publish.getByLabel('Library name').fill('Source lifecycle')+ await publish.getByRole('button', { name: 'Publish library' }).click()+ await expect(publish.getByLabel('Library ID')).toBeHidden()+ await page.keyboard.press('Escape')+ await expect(page.getByTestId('asset-libraries-dialog')).toBeHidden()+ const firstRevision = await page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ const value = store?.graph+ .getNode(store.graph.rootId)+ ?.pluginData.find((entry) => entry.key === 'sourceLibraryPublication')?.value+ return value ? (JSON.parse(value) as { revisionId: string }).revisionId : null+ })+ expect(firstRevision).toBeTruthy()++ const saved = await page.evaluate(async () => {+ const writes: Uint8Array[] = []+ window.showSaveFilePicker = async () =>+ ({+ name: 'source.fig',+ getFile: async () => new File([], 'source.fig'),+ createWritable: async () => ({+ write: async (data: Uint8Array) => writes.push(data),+ close: async () => undefined+ })+ }) as FileSystemFileHandle+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ await store.saveFigFileAs()+ return Array.from(writes[0] ?? [])+ })+ expect(saved.length).toBeGreaterThan(0)++ await page.evaluate((bytes) => {+ const file = new File([new Uint8Array(bytes)], 'source.fig')+ window.showOpenFilePicker = async () => [{ getFile: async () => file } as FileSystemFileHandle]+ }, saved)+ await page.keyboard.press('ControlOrMeta+KeyO')+ await expect+ .poll(() =>+ page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ const root = store?.graph.getNode(store.graph.rootId)+ return root?.pluginData.find((entry) => entry.key === 'sourceLibraryPublication')?.value+ })+ )+ .toContain('source-lifecycle')++ await openAssets(page)+ await openLibraries(page)+ await page.getByRole('button', { name: 'Publish library' }).click()+ await expect(publish.getByLabel('Library ID')).toHaveValue('source-lifecycle')+ await expect(publish.getByLabel('Library ID')).toBeDisabled()+ await expect(publish.getByText('No asset changes')).toBeVisible()+ await page.keyboard.press('Escape')+ await page.keyboard.press('Escape')++ await page.evaluate((sourceId) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const component = [...store.graph.getAllNodes()].find(+ (node) => node.source.id === sourceId || node.componentKey === 'source-button'+ )+ if (!component) throw new Error('Reopened source component missing')+ store.graph.updateNode(component.id, { width: 144, name: 'Source button updated' })+ }, componentId)+ await openAssets(page)+ await openLibraries(page)+ await page.getByRole('button', { name: 'Publish library' }).click()+ await expect(publish.getByLabel('Source button updated')).toBeChecked()+ await expect(publish.getByText('Modified')).toBeVisible()+ await publish.getByRole('button', { name: 'Publish library' }).click()+ await expect(publish.getByLabel('Library ID')).toBeHidden()++ const secondRevision = await page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ const value = store?.graph+ .getNode(store.graph.rootId)+ ?.pluginData.find((entry) => entry.key === 'sourceLibraryPublication')?.value+ return value ? (JSON.parse(value) as { revisionId: string }).revisionId : null+ })+ expect(secondRevision).toBeTruthy()+ expect(secondRevision).not.toBe(firstRevision)+})++test('publishes, consumes, saves, and reopens a multidimensional library instance offline', async ({+ page+}) => {+ const canvas = new CanvasHelper(page)+ await page.goto('/?test')+ await canvas.waitForInit()++ await page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const pageNode = store.graph.getNode(store.state.currentPageId)+ if (!pageNode) throw new Error('Current page not found')+ const set = store.graph.createNode('COMPONENT_SET', pageNode.id, {+ name: 'Button',+ componentPropertyDefinitions: [+ {+ id: 'size',+ name: 'Size',+ type: 'VARIANT',+ defaultValue: 'Small',+ variantOptions: ['Small', 'Large']+ },+ {+ id: 'tone',+ name: 'Tone',+ type: 'VARIANT',+ defaultValue: 'Neutral',+ variantOptions: ['Neutral', 'Brand']+ }+ ]+ })+ for (const [index, [size, tone]] of [+ ['Small', 'Neutral'],+ ['Small', 'Brand'],+ ['Large', 'Neutral'],+ ['Large', 'Brand']+ ].entries()) {+ const component = store.graph.createNode('COMPONENT', set.id, {+ name: `Size=${size}, Tone=${tone}`,+ x: (index % 2) * 160,+ y: Math.floor(index / 2) * 80,+ width: size === 'Large' ? 144 : 96,+ height: size === 'Large' ? 48 : 32,+ componentPropertyValues: { Size: size, Tone: tone }+ })+ store.graph.createNode('TEXT', component.id, {+ name: 'Label',+ text: `${size} ${tone}`,+ width: 90,+ height: 20+ })+ }+ store.requestRender()+ })++ await openAssets(page)+ await openLibraries(page)+ await page.getByRole('button', { name: 'Publish library' }).click()+ const publish = page.getByRole('dialog').filter({ hasText: 'Publish library' })+ await publish.getByLabel('Library ID').fill('e2e-design-system')+ await publish.getByLabel('Library name').fill('E2E design system')+ await publish.getByRole('button', { name: 'Publish library' }).click()+ await expect(publish.getByLabel('Library ID')).toBeHidden()+ await page.keyboard.press('Escape')+ await expect(page.getByTestId('asset-libraries-dialog')).toBeHidden()++ await page.keyboard.press('ControlOrMeta+KeyN')+ await expect+ .poll(() =>+ page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ return store ? [...store.graph.getAllNodes()].length : 0+ })+ )+ .toBeGreaterThan(0)+ await openAssets(page)+ await openLibraries(page)+ const libraryRow = page.getByText('E2E design system').locator('..').locator('..')+ await libraryRow.getByRole('button', { name: 'Enable library' }).click()+ await libraryRow.getByRole('button', { name: 'Prefer this library' }).click()+ await page.keyboard.press('Escape')+ await expect(page.getByTestId('asset-libraries-dialog')).toBeHidden()++ await page.getByRole('button', { name: 'List view' }).click()+ const asset = page.getByTestId('asset-item').filter({ hasText: 'Button' })+ await asset.getByTestId('asset-insert').click()+ await canvas.waitForRender()+ const variants = page.getByRole('region', { name: 'Variants' })+ await variants.getByRole('combobox', { name: 'Size' }).click()+ await page.getByRole('option', { name: 'Large' }).click()+ await variants.getByRole('combobox', { name: 'Tone' }).click()+ await page.getByRole('option', { name: 'Brand' }).click()++ const saved = await page.evaluate(async () => {+ const writes: Uint8Array[] = []+ window.showSaveFilePicker = async () =>+ ({+ name: 'consumer.fig',+ getFile: async () => new File([], 'consumer.fig'),+ createWritable: async () => ({+ write: async (data: Uint8Array) => writes.push(data),+ close: async () => undefined+ })+ }) as FileSystemFileHandle+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ await store.saveFigFileAs()+ return Array.from(writes[0] ?? [])+ })+ expect(saved.length).toBeGreaterThan(0)++ await page.evaluate(async (bytes) => {+ const file = new File([new Uint8Array(bytes)], 'consumer.fig')+ const originalFetch = window.fetch+ window.fetch = async (...args) => {+ const url = String(args[0])+ if (url.includes('library')) throw new Error('offline')+ return originalFetch(...args)+ }+ window.showOpenFilePicker = async () => [{ getFile: async () => file } as FileSystemFileHandle]+ }, saved)+ await page.keyboard.press('ControlOrMeta+KeyO')++ await expect+ .poll(() =>+ page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) return null+ const instance = [...store.graph.getAllNodes()].find((node) => node.type === 'INSTANCE')+ const component = instance?.componentId ? store.graph.getNode(instance.componentId) : null+ const definitions = [...store.graph.getAllNodes()].filter((node) => node.librarySource)+ return instance && component+ ? {+ values: component.componentPropertyValues,+ libraryId: component.librarySource?.identity.libraryId,+ revisionId: component.librarySource?.identity.revisionId,+ readOnly: component.librarySource?.readOnly,+ definitions: definitions.map((node) => ({+ name: node.name,+ libraryId: node.librarySource?.identity.libraryId+ })),+ enabled: store.graph.enabledLibraries.get('e2e-design-system')?.enabled+ }+ : null+ })+ )+ .toMatchObject({+ values: { Size: 'Large', Tone: 'Brand' },+ definitions: expect.arrayContaining([+ expect.objectContaining({ libraryId: 'e2e-design-system' })+ ])+ })++ await expect(page.getByText(/send was called before connect/i)).toHaveCount(0)+})diff --git a/tests/e2e/components/library-manager.spec.ts b/tests/e2e/components/library-manager.spec.tsnew file mode 100644index 000000000..44163d672--- /dev/null+++ b/tests/e2e/components/library-manager.spec.ts@@ -0,0 +1,292 @@+import { expect, test } from '@playwright/test'++import { CanvasHelper } from '#tests/helpers/canvas'++test('library manager scopes populated updates and does not mutate on discovery', async ({+ page+}) => {+ const canvas = new CanvasHelper(page)+ await page.goto('/?test')+ await canvas.waitForInit()++ const source = await page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const pageNode = store.graph.getNode(store.state.currentPageId)+ if (!pageNode) throw new Error('Current page missing')+ const component = store.graph.createNode('COMPONENT', pageNode.id, {+ name: 'Button',+ componentKey: 'button',+ width: 80,+ height: 32,+ cornerRadius: 4,+ fills: [+ {+ type: 'SOLID',+ color: { r: 1, g: 0.8, b: 0.1, a: 1 },+ opacity: 1,+ visible: true,+ blendMode: 'NORMAL'+ }+ ]+ })+ store.graph.createNode('TEXT', component.id, {+ name: 'Label',+ text: 'Old',+ x: 16,+ y: 6,+ width: 48,+ height: 20+ })+ const card = store.graph.createNode('COMPONENT', pageNode.id, {+ name: 'Card',+ componentKey: 'card',+ x: 180,+ width: 160,+ height: 100+ })+ store.requestRender()+ return { buttonId: component.id, cardId: card.id }+ })++ await page.getByTestId('left-panel-assets-tab').click()+ await page.getByRole('button', { name: 'Manage libraries' }).click()+ await page.getByRole('button', { name: 'Publish library' }).click()+ const publish = page.getByRole('dialog').filter({ hasText: 'Publish library' })+ await publish.getByLabel('Library ID').fill('manager-e2e')+ await publish.getByLabel('Library name').fill('Manager E2E')+ await expect(publish.getByText('Changes')).toBeVisible()+ await expect(publish.getByLabel('Button')).toBeChecked()+ await expect(publish.getByLabel('Card')).toBeChecked()+ await publish.getByRole('button', { name: 'Publish library' }).click()+ await expect(publish.getByLabel('Library ID')).toBeHidden()+ await page.keyboard.press('Escape')+ await page.keyboard.press('ControlOrMeta+KeyN')+ await expect.poll(() => page.evaluate(() => !!window.openPencil?.getStore?.())).toBe(true)++ await page.getByTestId('left-panel-assets-tab').click()+ await page.getByRole('button', { name: 'Manage libraries' }).click()+ const manager = page.getByTestId('asset-libraries-dialog')+ const libraryRow = manager.getByText('Manager E2E').locator('..').locator('..')+ await libraryRow.getByRole('button', { name: 'Enable library' }).click()+ await page.keyboard.press('Escape')+ await page.getByRole('button', { name: 'List view' }).click()+ await page+ .getByTestId('asset-item')+ .filter({ hasText: 'Button' })+ .getByTestId('asset-insert')+ .click()+ await page+ .getByTestId('asset-item')+ .filter({ hasText: 'Card' })+ .getByTestId('asset-insert')+ .click()++ await page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const instances = [...store.graph.getAllNodes()].filter((node) => node.type === 'INSTANCE')+ if (instances.some((instance) => !instance.componentId))+ throw new Error('Inserted instance missing')+ const second = store.graph.addPage('Second')+ for (const instance of instances) {+ if (instance.componentId)+ store.graph.createNode('INSTANCE', second.id, { componentId: instance.componentId })+ }+ })++ await page.getByTestId('tabbar-tab').nth(0).click()+ await page.evaluate(({ buttonId, cardId }) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ store.graph.updateNode(buttonId, {+ width: 144,+ height: 48,+ name: 'Button updated',+ cornerRadius: 14,+ fills: [+ {+ type: 'SOLID',+ color: { r: 1, g: 0.25, b: 0.1, a: 1 },+ opacity: 1,+ visible: true,+ blendMode: 'NORMAL'+ }+ ]+ })+ const label = store.graph.getChildren(buttonId).find((node) => node.type === 'TEXT')+ if (label) store.graph.updateNode(label.id, { text: 'New', x: 48, y: 14 })+ store.graph.updateNode(cardId, { name: 'Card updated', width: 240, height: 140 })+ store.requestRender()+ }, source)+ await page.getByTestId('left-panel-assets-tab').click()+ await page.getByRole('button', { name: 'Manage libraries' }).click()+ await page.getByRole('button', { name: 'Publish library' }).click()+ await publish.getByLabel('Revision description').fill('Wider button')+ await expect(publish.getByLabel('Library ID')).toBeDisabled()+ await expect(publish.getByLabel('Button updated')).toBeChecked()+ await expect(publish.getByLabel('Card updated')).toBeChecked()+ await expect(publish).toHaveScreenshot('library-publish-changes.png', {+ animations: 'disabled'+ })+ const searchChanges = publish.getByPlaceholder('Search changes')+ await searchChanges.fill('Button')+ await expect(publish.getByLabel('Card updated')).toHaveCount(0)+ await publish.getByLabel('Changes').click()+ await searchChanges.fill('')+ await expect(publish.getByLabel('Button updated')).not.toBeChecked()+ await expect(publish.getByLabel('Card updated')).toBeChecked()+ await publish.getByLabel('Card updated').click()+ await expect(publish.getByRole('button', { name: 'Publish library' })).toBeDisabled()+ await publish.getByLabel('Button updated').click()+ await publish.getByRole('button', { name: 'Publish library' }).click()+ await expect(publish.getByLabel('Revision description')).toBeHidden()+ await page.getByTestId('left-panel-assets-tab').click()+ await page.getByRole('button', { name: 'Manage libraries' }).click()+ await page.getByRole('button', { name: 'Publish library' }).click()+ await expect(publish.getByLabel('Card updated')).toBeChecked()+ await expect(publish.getByLabel('Button updated')).toHaveCount(0)+ await page.keyboard.press('Escape')+ await expect(publish.getByLabel('Library ID')).toBeHidden()+ await page.keyboard.press('Escape')+ await expect(manager).toBeHidden()+ await page.getByTestId('tabbar-tab').nth(1).click()++ await page.getByTestId('left-panel-assets-tab').click()+ await expect(page.getByRole('button', { name: 'Review library updates' })).toBeVisible()+ await page.getByRole('button', { name: 'Review library updates' }).click()+ await expect(manager.getByRole('button', { name: /Updates/ })).toHaveAttribute(+ 'data-state',+ 'active'+ )+ await expect(manager.getByText('Button updated')).toBeVisible()+ const before = await page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ return [...store.graph.getAllNodes()].map((node) => node.id)+ })+ await expect(manager.getByTestId('library-update-instance-count')).toHaveText('Instances: 1')+ expect(+ await page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ return [...store.graph.getAllNodes()].map((node) => node.id)+ })+ ).toEqual(before)++ await manager.getByRole('switch', { name: 'Show updates for all pages' }).click()+ await expect(manager.getByTestId('library-update-instance-count')).toHaveText('Instances: 2')+ await page.keyboard.press('Escape')++ const instances = await page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const ids = [...store.graph.getAllNodes()]+ .filter((node) => {+ if (node.type !== 'INSTANCE' || !node.componentId) return false+ return store.graph.getNode(node.componentId)?.name.includes('Button')+ })+ .map((node) => node.id)+ store.select([ids[0]])+ return ids+ })+ const instanceUpdate = page.getByRole('button', { name: 'Update selected instance' })+ await expect(instanceUpdate).toBeVisible()+ await instanceUpdate.click()+ const updateMenuItem = page.getByTestId('instance-update-selected')+ await expect(updateMenuItem).toBeVisible()+ await page.keyboard.press('Escape')+ await expect(updateMenuItem).toBeHidden()+ const reviewOrigin = await page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ return {+ pageId: store.state.currentPageId,+ selectedIds: [...store.state.selectedIds],+ panX: store.state.panX,+ panY: store.state.panY,+ zoom: store.state.zoom+ }+ })+ await instanceUpdate.click()+ await page.getByTestId('instance-review-update').click()+ const reviewDialog = page.getByTestId('library-update-review')+ await expect(reviewDialog).toBeVisible()+ await expect(reviewDialog.getByRole('heading', { name: 'Current' })).toBeVisible()+ await expect(reviewDialog.getByRole('heading', { name: 'Updated' })).toBeVisible()+ await expect(reviewDialog.getByRole('img', { name: 'Current' })).toBeVisible()+ await expect(reviewDialog.getByRole('img', { name: 'Updated' })).toBeVisible()+ await expect(reviewDialog.getByRole('button', { name: 'Previous instance' })).toBeDisabled()+ await expect(reviewDialog.getByRole('button', { name: 'Next instance' })).toBeDisabled()+ await expect(reviewDialog).toHaveScreenshot('library-update-side-by-side.png', {+ animations: 'disabled'+ })+ await page.evaluate(async () => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const otherPage = store.graph.getPages().find((page) => page.id !== store.state.currentPageId)+ if (otherPage) await store.switchPage(otherPage.id)+ store.clearSelection()+ store.state.panX += 120+ store.state.panY -= 80+ store.state.zoom = 0.5+ })+ await page.keyboard.press('Escape')+ await expect(reviewDialog).toBeHidden()+ await expect+ .poll(() =>+ page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) return null+ return {+ pageId: store.state.currentPageId,+ selectedIds: [...store.state.selectedIds],+ panX: store.state.panX,+ panY: store.state.panY,+ zoom: store.state.zoom+ }+ })+ )+ .toEqual(reviewOrigin)+ await instanceUpdate.click()+ await updateMenuItem.click()+ await expect(instanceUpdate).toBeHidden()+ const mixedComponents = await page.evaluate((ids) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ return ids.map((id) => store.graph.getNode(id)?.componentId)+ }, instances)+ expect(new Set(mixedComponents).size).toBe(2)++ await page.evaluate((id) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ store.select([id])+ }, instances[1])+ await expect(instanceUpdate).toBeVisible()++ await page.keyboard.press('ControlOrMeta+KeyZ')+ const undoneComponents = await page.evaluate((ids) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ return ids.map((id) => store.graph.getNode(id)?.componentId)+ }, instances)+ expect(new Set(undoneComponents).size).toBe(1)++ await page.keyboard.press('ControlOrMeta+Shift+KeyZ')+ const redoneComponents = await page.evaluate((ids) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ return ids.map((id) => store.graph.getNode(id)?.componentId)+ }, instances)+ expect(new Set(redoneComponents).size).toBe(2)++ await page.getByTestId('left-panel-assets-tab').click()+ await page.getByRole('button', { name: /libraries|updates/i }).click()+ await manager.getByRole('button', { name: /Updates/ }).click()+ await manager.getByRole('button', { name: 'Button updated' }).click()+ await expect(reviewDialog).toBeVisible()+ await page.keyboard.press('Escape')+ await expect(reviewDialog).toBeHidden()+ await expect(manager.getByText('Card updated')).toHaveCount(0)+})diff --git a/tests/e2e/components/library-manager.spec.ts-snapshots/library-publish-changes-openpencil-darwin.png b/tests/e2e/components/library-manager.spec.ts-snapshots/library-publish-changes-openpencil-darwin.pngnew file mode 100644index 000000000..1ce25be14Binary files /dev/null and b/tests/e2e/components/library-manager.spec.ts-snapshots/library-publish-changes-openpencil-darwin.png differdiff --git a/tests/e2e/components/library-manager.spec.ts-snapshots/library-update-side-by-side-openpencil-darwin.png b/tests/e2e/components/library-manager.spec.ts-snapshots/library-update-side-by-side-openpencil-darwin.pngnew file mode 100644index 000000000..7d9f199eeBinary files /dev/null and b/tests/e2e/components/library-manager.spec.ts-snapshots/library-update-side-by-side-openpencil-darwin.png differdiff --git a/tests/e2e/components/variant-authoring.spec.ts b/tests/e2e/components/variant-authoring.spec.tsnew file mode 100644index 000000000..a561cea77--- /dev/null+++ b/tests/e2e/components/variant-authoring.spec.ts@@ -0,0 +1,121 @@+import { expect, test } from '@playwright/test'++import { CanvasHelper } from '#tests/helpers/canvas'+import { propertySection } from '#tests/helpers/properties'++test('authors multiple variant dimensions and reports duplicate combinations', async ({ page }) => {+ const canvas = new CanvasHelper(page)+ await page.goto('/?test')+ await canvas.waitForInit()++ const ids = await page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const pageId = store.state.currentPageId+ const componentSet = store.graph.createNode('COMPONENT_SET', pageId, {+ name: 'Button',+ componentPropertyDefinitions: [+ {+ id: '50:1',+ name: 'Variant',+ type: 'VARIANT',+ defaultValue: 'Primary',+ variantOptions: ['Primary', 'Secondary']+ },+ {+ id: '50:2',+ name: 'Property 2',+ type: 'VARIANT',+ defaultValue: 'Small',+ variantOptions: ['Small', 'Large']+ }+ ]+ })+ const primarySmall = store.graph.createNode('COMPONENT', componentSet.id, {+ name: 'Variant=Primary, Property 2=Small',+ componentPropertyValues: { Variant: 'Primary', 'Property 2': 'Small' }+ })+ const primaryLarge = store.graph.createNode('COMPONENT', componentSet.id, {+ name: 'Variant=Primary, Property 2=Large',+ x: 160,+ componentPropertyValues: { Variant: 'Primary', 'Property 2': 'Large' }+ })+ const secondarySmall = store.graph.createNode('COMPONENT', componentSet.id, {+ name: 'Variant=Secondary, Property 2=Small',+ y: 120,+ componentPropertyValues: { Variant: 'Secondary', 'Property 2': 'Small' }+ })+ store.select([componentSet.id])+ return {+ componentSetId: componentSet.id,+ primarySmallId: primarySmall.id,+ primaryLargeId: primaryLarge.id,+ secondarySmallId: secondarySmall.id+ }+ })+ await canvas.waitForRender()++ const section = propertySection(page, 'Variants')+ await expect(section).toBeVisible()+ const propertyRows = section.locator('[data-property]')+ await expect(propertyRows).toHaveCount(2)+ await propertyRows.nth(0).getByRole('textbox', { name: 'Property name' }).fill('Type')+ await propertyRows.nth(0).getByRole('textbox', { name: 'Property name' }).blur()+ await canvas.waitForRender()+ await propertyRows.nth(1).getByRole('textbox', { name: 'Property name' }).fill('Size')+ await propertyRows.nth(1).getByRole('textbox', { name: 'Property name' }).blur()+ await canvas.waitForRender()++ await section.getByRole('textbox', { name: 'Property name' }).last().fill('State')+ await section.getByRole('textbox', { name: 'Initial value' }).fill('Enabled')+ await section.getByRole('button', { name: 'Add variant property' }).click()+ await canvas.waitForRender()++ const definitions = await page.evaluate((componentSetId) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ return store.graph.getNode(componentSetId)?.componentPropertyDefinitions+ }, ids.componentSetId)+ expect(definitions?.map((definition) => definition.name)).toEqual(['Type', 'Size', 'State'])++ await page.evaluate((variantId) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ store.select([variantId])+ }, ids.primaryLargeId)+ await canvas.waitForRender()++ const variantSection = propertySection(page, 'Variants')+ await expect(variantSection.getByRole('textbox', { name: 'Type' })).toHaveValue('Primary')+ await expect(variantSection.getByRole('textbox', { name: 'Size' })).toHaveValue('Large')+ await expect(variantSection.getByRole('textbox', { name: 'State' })).toHaveValue('Enabled')+ await variantSection.getByRole('textbox', { name: 'Size' }).fill('Small')+ await variantSection.getByRole('textbox', { name: 'Size' }).blur()+ await expect(variantSection.getByRole('alert')).toContainText('Duplicate variant values')+ await expect(variantSection.getByRole('textbox', { name: 'Size' })).toHaveValue('Large')++ const state = await page.evaluate((variantId) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const node = store.graph.getNode(variantId)+ return node+ ? { name: node.name, values: node.componentPropertyValues, undoLabel: store.undo.undoLabel }+ : null+ }, ids.primaryLargeId)+ expect(state).toEqual({+ name: 'Type=Primary, Size=Large, State=Enabled',+ values: { Type: 'Primary', Size: 'Large', State: 'Enabled' },+ undoLabel: 'Add property'+ })++ await variantSection.getByRole('textbox', { name: 'Size' }).fill('Medium')+ await variantSection.getByRole('textbox', { name: 'Size' }).blur()+ await canvas.waitForRender()+ await expect(variantSection.getByRole('alert')).toHaveCount(0)+ await expect(variantSection.getByRole('textbox', { name: 'Size' })).toHaveValue('Medium')++ await canvas.pressKey('Meta+z')+ await canvas.waitForRender()+ await expect(variantSection.getByRole('alert')).toHaveCount(0)+ await expect(variantSection.getByRole('textbox', { name: 'Size' })).toHaveValue('Large')+})diff --git a/tests/engine/editor/components/library-capabilities.test.ts b/tests/engine/editor/components/library-capabilities.test.tsnew file mode 100644index 000000000..395871b66--- /dev/null+++ b/tests/engine/editor/components/library-capabilities.test.ts@@ -0,0 +1,56 @@+import { describe, expect, test } from 'bun:test'++import {+ assertNodeEditable,+ getNodeEditCapability,+ ReadOnlyLibraryDefinitionError+} from '@open-pencil/core/editor'+import { FigmaAPI } from '@open-pencil/core/figma-api'+import { updateNode } from '@open-pencil/core/tools/modify'+import { SceneGraph } from '@open-pencil/scene-graph'++describe('library definition capabilities', () => {+ test('protects materialized definitions and descendants but not their instances', async () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const component = graph.createNode('COMPONENT', page.id, {+ name: 'Remote button',+ librarySource: {+ identity: { libraryId: 'design-system', assetKey: 'button', revisionId: 'r1' },+ sourceNodeId: 'source',+ readOnly: true+ }+ })+ const child = graph.createNode('TEXT', component.id, { name: 'Label', text: 'Button' })+ const instance = graph.createInstance(component.id, page.id)+ if (!instance) throw new Error('Expected instance')++ expect(getNodeEditCapability(graph, child.id)).toEqual({+ editable: false,+ reason: 'library-definition',+ libraryId: 'design-system',+ assetKey: 'button'+ })+ expect(getNodeEditCapability(graph, instance.id)).toEqual({ editable: true })+ expect(() => assertNodeEditable(graph, child.id)).toThrow(ReadOnlyLibraryDefinitionError)++ const figma = new FigmaAPI(graph)+ const proxy = figma.getNodeById(component.id)+ if (!proxy) throw new Error('Expected proxy')+ expect(() => {+ proxy.name = 'Changed'+ }).toThrow(ReadOnlyLibraryDefinitionError)+ expect(() => {+ proxy.opacity = 0.5+ }).toThrow(ReadOnlyLibraryDefinitionError)+ expect(() => proxy.remove()).toThrow(ReadOnlyLibraryDefinitionError)+ expect(graph.getNode(component.id)?.name).toBe('Remote button')+ const instanceProxy = figma.getNodeById(instance.id)+ if (!instanceProxy) throw new Error('Expected instance proxy')+ instanceProxy.opacity = 0.5+ expect(graph.getNode(instance.id)?.opacity).toBe(0.5)+ expect(() => updateNode.execute(figma, { id: component.id, opacity: 0.5 })).toThrow(+ ReadOnlyLibraryDefinitionError+ )+ })+})diff --git a/tests/engine/editor/components/variants.test.ts b/tests/engine/editor/components/variants.test.tsnew file mode 100644index 000000000..77f7943f3--- /dev/null+++ b/tests/engine/editor/components/variants.test.ts@@ -0,0 +1,217 @@+import { describe, expect, test } from 'bun:test'++import { createEditor } from '@open-pencil/core/editor'++function setupVariants() {+ const editor = createEditor()+ const pageId = editor.state.currentPageId+ const componentSet = editor.graph.createNode('COMPONENT_SET', pageId, {+ name: 'Button',+ componentPropertyDefinitions: [+ {+ id: 'variant:type',+ name: 'Type',+ type: 'VARIANT',+ defaultValue: 'Primary',+ variantOptions: ['Primary', 'Secondary']+ },+ {+ id: 'variant:size',+ name: 'Size',+ type: 'VARIANT',+ defaultValue: 'Small',+ variantOptions: ['Small', 'Large']+ }+ ]+ })+ const createVariant = (type: string, size: string, x: number, y: number) =>+ editor.graph.createNode('COMPONENT', componentSet.id, {+ name: `Type=${type}, Size=${size}`,+ x,+ y,+ componentPropertyValues: { Type: type, Size: size }+ })+ const primarySmall = createVariant('Primary', 'Small', 0, 0)+ const primaryLarge = createVariant('Primary', 'Large', 140, 0)+ const secondarySmall = createVariant('Secondary', 'Small', 0, 140)+ return { editor, componentSet, primarySmall, primaryLarge, secondarySmall }+}++describe('variant authoring', () => {+ test('keeps sparse multidimensional transitions exact and reports unavailable combinations', () => {+ const { editor, primarySmall, primaryLarge } = setupVariants()+ const instance = editor.graph.createInstance(primarySmall.id, editor.state.currentPageId)+ if (!instance) throw new Error('Expected instance')++ expect(editor.getVariantOptionAvailability(instance.id, 'Size')).toEqual([+ { value: 'Small', available: true },+ { value: 'Large', available: true }+ ])+ expect(+ editor.setInstanceComponentProperty(instance.id, 'variant:size', 'Large')+ ).toBeUndefined()+ expect(editor.graph.getNode(instance.id)?.componentId).toBe(primaryLarge.id)++ expect(editor.getVariantOptionAvailability(instance.id, 'Type')).toEqual([+ { value: 'Primary', available: true },+ { value: 'Secondary', available: false }+ ])+ expect(editor.switchInstanceVariant(instance.id, 'Type', 'Secondary')).toEqual({+ kind: 'unavailable',+ requested: { Type: 'Secondary', Size: 'Large' }+ })+ expect(editor.graph.getNode(instance.id)?.componentId).toBe(primaryLarge.id)+ })++ test('renames dimensions and values atomically through undo and redo', () => {+ const { editor, componentSet, primarySmall } = setupVariants()++ expect(editor.renamePropertyDefinition(componentSet.id, 'variant:size', 'Density')).toBe(true)+ expect(editor.graph.getNode(primarySmall.id)?.componentPropertyValues).toEqual({+ Type: 'Primary',+ Density: 'Small'+ })+ expect(editor.graph.getNode(primarySmall.id)?.name).toBe('Type=Primary, Density=Small')++ editor.undo.undo()+ expect(editor.graph.getNode(primarySmall.id)?.componentPropertyValues).toEqual({+ Type: 'Primary',+ Size: 'Small'+ })+ expect(editor.graph.getNode(primarySmall.id)?.name).toBe('Type=Primary, Size=Small')++ editor.undo.redo()+ expect(editor.renameVariantValue(componentSet.id, 'variant:size', 'Small', 'Compact')).toBe(+ true+ )+ expect(editor.graph.getNode(primarySmall.id)?.componentPropertyValues.Density).toBe('Compact')+ expect(+ editor.graph+ .getNode(componentSet.id)+ ?.componentPropertyDefinitions.find((definition) => definition.id === 'variant:size')+ ?.variantOptions+ ).toEqual(['Compact', 'Large'])++ editor.undo.undo()+ expect(editor.graph.getNode(primarySmall.id)?.componentPropertyValues.Density).toBe('Small')+ })++ test('adds and removes dimensions with complete undo snapshots', () => {+ const { editor, componentSet, primarySmall } = setupVariants()+ const propertyId = editor.addPropertyDefinition(componentSet.id, 'State', 'VARIANT', 'Enabled')+ expect(propertyId).toStartWith('prop:')+ expect(editor.graph.getNode(primarySmall.id)?.componentPropertyValues.State).toBe('Enabled')++ editor.undo.undo()+ expect(editor.graph.getNode(primarySmall.id)?.componentPropertyValues).not.toHaveProperty(+ 'State'+ )+ editor.undo.redo()+ expect(editor.graph.getNode(primarySmall.id)?.componentPropertyValues.State).toBe('Enabled')++ if (!propertyId) throw new Error('Expected property ID')+ expect(editor.removePropertyDefinition(componentSet.id, propertyId)).toBe(true)+ expect(editor.graph.getNode(primarySmall.id)?.componentPropertyValues).not.toHaveProperty(+ 'State'+ )+ editor.undo.undo()+ expect(editor.graph.getNode(primarySmall.id)?.componentPropertyValues.State).toBe('Enabled')+ })++ test('reorders properties and values atomically', () => {+ const { editor, componentSet, primarySmall } = setupVariants()++ expect(+ editor.reorderPropertyDefinitions(componentSet.id, ['variant:size', 'variant:type'])+ ).toBe(true)+ expect(+ editor.graph+ .getNode(componentSet.id)+ ?.componentPropertyDefinitions.map((definition) => definition.id)+ ).toEqual(['variant:size', 'variant:type'])+ expect(editor.graph.getNode(primarySmall.id)?.name).toBe('Size=Small, Type=Primary')++ expect(editor.reorderVariantValues(componentSet.id, 'variant:size', ['Large', 'Small'])).toBe(+ true+ )+ expect(+ editor.graph+ .getNode(componentSet.id)+ ?.componentPropertyDefinitions.find((definition) => definition.id === 'variant:size')+ ).toMatchObject({ defaultValue: 'Large', variantOptions: ['Large', 'Small'] })++ editor.undo.undo()+ expect(+ editor.graph+ .getNode(componentSet.id)+ ?.componentPropertyDefinitions.find((definition) => definition.id === 'variant:size')+ ).toMatchObject({ defaultValue: 'Small', variantOptions: ['Small', 'Large'] })+ editor.undo.undo()+ expect(editor.graph.getNode(primarySmall.id)?.name).toBe('Type=Primary, Size=Small')+ })++ test('uses top-left defaults and validates missing or duplicate combinations', () => {+ const { editor, componentSet, primarySmall, primaryLarge } = setupVariants()+ const topLeft = editor.graph.getNode(primarySmall.id)+ const topRight = editor.graph.getNode(primaryLarge.id)+ if (!topLeft || !topRight) throw new Error('Expected variants')+ editor.graph.updateNode(topLeft.id, { x: 200, y: 200 })+ editor.graph.updateNode(topRight.id, { x: 0, y: 0 })+ expect(editor.getDefaultVariantForComponentSet(componentSet.id)?.id).toBe(primaryLarge.id)++ editor.graph.updateNode(primaryLarge.id, {+ componentPropertyValues: { Type: 'Primary', Size: '' }+ })+ expect(editor.validateComponentSet(componentSet.id)).toEqual([+ {+ kind: 'missing-value',+ propertyId: 'variant:size',+ propertyName: 'Size',+ componentIds: [primaryLarge.id]+ }+ ])+ editor.graph.updateNode(primaryLarge.id, {+ componentPropertyValues: { Type: 'Primary', Size: 'Small' }+ })+ expect(editor.validateComponentSet(componentSet.id)).toEqual([+ {+ kind: 'duplicate-combination',+ values: { Type: 'Primary', Size: 'Small' },+ componentIds: [primarySmall.id, primaryLarge.id]+ }+ ])+ })+ test('edits combinations, diagnoses conflicts, and duplicates or removes variants', () => {+ const { editor, componentSet, primarySmall, primaryLarge } = setupVariants()++ expect(editor.setVariantPropertyValue(primaryLarge.id, 'variant:size', 'Small')).toEqual({+ kind: 'conflict',+ componentIds: [primaryLarge.id, primarySmall.id]+ })+ expect(editor.getComponentSetVariantConflicts(componentSet.id)).toEqual([])+ expect(editor.graph.getNode(primaryLarge.id)?.componentPropertyValues.Size).toBe('Large')++ expect(editor.setVariantPropertyValue(primaryLarge.id, 'variant:size', 'Medium')).toEqual({+ kind: 'changed'+ })+ expect(editor.graph.getNode(primaryLarge.id)?.componentPropertyValues.Size).toBe('Medium')+ editor.undo.undo()+ expect(editor.graph.getNode(primaryLarge.id)?.componentPropertyValues.Size).toBe('Large')++ const duplicateId = editor.duplicateVariant(primarySmall.id)+ expect(duplicateId).toBeString()+ expect(editor.getComponentSetVariantConflicts(componentSet.id)).toHaveLength(1)+ editor.undo.undo()+ expect(duplicateId ? editor.graph.getNode(duplicateId) : undefined).toBeUndefined()+ editor.undo.redo()+ expect(duplicateId ? editor.graph.getNode(duplicateId)?.parentId : undefined).toBe(+ componentSet.id+ )++ if (!duplicateId) throw new Error('Expected duplicate')+ expect(editor.removeVariant(duplicateId)).toBe(true)+ expect(editor.graph.getNode(duplicateId)).toBeUndefined()+ editor.undo.undo()+ expect(editor.graph.getNode(duplicateId)?.parentId).toBe(componentSet.id)+ })+})diff --git a/tests/engine/io/fig/export/component-properties.test.ts b/tests/engine/io/fig/export/component-properties.test.tsindex b7cc8d3c4..35321f4b8 100644--- a/tests/engine/io/fig/export/component-properties.test.ts+++ b/tests/engine/io/fig/export/component-properties.test.ts@@ -11,6 +11,111 @@ describe('Figma component property roundtrip', () => {await initCodec()})+ test('retains OpenPencil library bindings and materialized identity', async () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ graph.enabledLibraries.set('design-system', {+ libraryId: 'design-system',+ revisionId: 'revision-1',+ enabled: true+ })+ const component = graph.createNode('COMPONENT', page.id, {+ name: 'Remote button',+ componentKey: 'button',+ librarySource: {+ identity: {+ libraryId: 'design-system',+ assetKey: 'button',+ revisionId: 'revision-1'+ },+ sourceNodeId: 'source-button',+ readOnly: true+ }+ })+ component.source.id = '50:1'++ const bytes = await exportFigFile(graph)+ const parsed = parseFigBuffer(+ bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)+ )+ const imported = importNodeChanges(parsed.nodeChanges, parsed.blobs, undefined, {+ populate: 'all'+ })+ expect(imported.enabledLibraries.get('design-system')).toEqual({+ libraryId: 'design-system',+ revisionId: 'revision-1',+ enabled: true+ })+ expect(+ [...imported.getAllNodes()].find((node) => node.name === 'Remote button')?.librarySource+ ).toEqual(component.librarySource)+ })++ test('retains authored multidimensional variant definitions and combinations', async () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const componentSet = graph.createNode('COMPONENT_SET', page.id, {+ name: 'Button',+ componentPropertyDefinitions: [+ {+ id: '40:1',+ name: 'Type',+ type: 'VARIANT',+ defaultValue: 'Primary',+ variantOptions: ['Primary', 'Secondary']+ },+ {+ id: '40:2',+ name: 'Size',+ type: 'VARIANT',+ defaultValue: 'Small',+ variantOptions: ['Small', 'Large']+ },+ {+ id: '40:3',+ name: 'State',+ type: 'VARIANT',+ defaultValue: 'Enabled',+ variantOptions: ['Enabled', 'Disabled']+ }+ ]+ })+ componentSet.source.id = '40:0'+ const combinations = [+ { Type: 'Primary', Size: 'Small', State: 'Enabled' },+ { Type: 'Primary', Size: 'Large', State: 'Enabled' },+ { Type: 'Secondary', Size: 'Small', State: 'Disabled' }+ ]+ for (const [index, values] of combinations.entries()) {+ const variant = graph.createNode('COMPONENT', componentSet.id, {+ name: Object.entries(values)+ .map(([name, value]) => `${name}=${value}`)+ .join(', '),+ componentPropertyValues: values+ })+ variant.source.id = `40:${index + 10}`+ }++ const bytes = await exportFigFile(graph)+ const parsed = parseFigBuffer(+ bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)+ )+ const imported = importNodeChanges(parsed.nodeChanges, parsed.blobs, undefined, {+ populate: 'all'+ })+ const importedSet = [...imported.getAllNodes()].find(+ (node) => node.type === 'COMPONENT_SET' && node.name === 'Button'+ )+ if (!importedSet) throw new Error('Expected imported component set')++ expect(importedSet.componentPropertyDefinitions).toEqual(+ componentSet.componentPropertyDefinitions+ )+ expect(importedSet.childIds.map((id) => imported.getNode(id)?.componentPropertyValues)).toEqual(+ combinations+ )+ })+test('retains typed definitions, refs, and assignments', async () => {const graph = new SceneGraph()const page = graph.getPages()[0]diff --git a/tests/engine/library/discovery.test.ts b/tests/engine/library/discovery.test.tsnew file mode 100644index 000000000..2bf5518be--- /dev/null+++ b/tests/engine/library/discovery.test.ts@@ -0,0 +1,65 @@+import { describe, expect, test } from 'bun:test'++import { createEditor } from '@open-pencil/core/editor'+import {+ createLibraryRevision,+ materializeLibraryAsset,+ MemoryLibraryCatalog+} from '@open-pencil/core/library'+import { SceneGraph } from '@open-pencil/scene-graph'++import { LibraryService } from '@/app/libraries/service'++function source(width: number) {+ const graph = new SceneGraph()+ graph.createNode('COMPONENT', graph.getPages()[0].id, {+ name: 'Button',+ componentKey: 'button',+ width+ })+ return graph+}++describe('library update discovery', () => {+ test('does not materialize latest definitions while discovering updates', async () => {+ const first = await createLibraryRevision({+ libraryId: 'library',+ name: 'Library',+ graph: source(80),+ publishedAt: '2026-01-01T00:00:00Z'+ })+ const catalog = new MemoryLibraryCatalog()+ await catalog.publishRevision({+ libraryId: 'library',+ name: 'Library',+ graph: source(80),+ publishedAt: '2026-01-01T00:00:00Z'+ })+ const consumer = new SceneGraph()+ const definition = materializeLibraryAsset(consumer, first, 'button')+ consumer.createNode('INSTANCE', consumer.getPages()[0].id, {+ componentId: definition.componentId+ })+ const latest = await catalog.publishRevision({+ libraryId: 'library',+ name: 'Library',+ graph: source(120),+ previousRevisionId: first.manifest.revisionId,+ publishedAt: '2026-01-02T00:00:00Z'+ })+ const editor = createEditor({ graph: consumer })+ const service = new LibraryService(catalog)+ await service.listLibraries()+ const before = [...consumer.getAllNodes()].map((node) => node.id)++ const groups = await service.getUpdateGroups(editor)++ expect(groups).toMatchObject([{ libraryId: 'library', assetKey: 'button' }])+ expect([...consumer.getAllNodes()].map((node) => node.id)).toEqual(before)+ expect(+ [...consumer.getAllNodes()].some(+ (node) => node.librarySource?.identity.revisionId === latest.manifest.revisionId+ )+ ).toBe(false)+ })+})diff --git a/tests/engine/library/hash-normalization.test.ts b/tests/engine/library/hash-normalization.test.tsnew file mode 100644index 000000000..97cc3cda4--- /dev/null+++ b/tests/engine/library/hash-normalization.test.ts@@ -0,0 +1,41 @@+import { describe, expect, test } from 'bun:test'++import { exportFigFile, initCodec, parseFigFile } from '@open-pencil/core'+import { createLibraryRevision, discoverPublishableLibraryChanges } from '@open-pencil/core/library'+import { SceneGraph } from '@open-pencil/scene-graph'++function source() {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const component = graph.createNode('COMPONENT', page.id, {+ name: 'Button',+ componentKey: 'button',+ width: 80,+ height: 32+ })+ graph.createNode('TEXT', component.id, { name: 'Label', text: 'Button', width: 60, height: 20 })+ return graph+}++describe('library hash normalization', () => {+ test('ignores representation-only FIG round-trip changes', async () => {+ initCodec()+ const graph = source()+ const previous = await createLibraryRevision({ libraryId: 'library', name: 'Library', graph })+ const restored = await parseFigFile((await exportFigFile(graph)).buffer as ArrayBuffer)+ const discovery = await discoverPublishableLibraryChanges(previous, restored)+ expect(discovery.changes).toEqual([])+ })++ test('still detects semantic changes after a FIG round trip', async () => {+ initCodec()+ const graph = source()+ const previous = await createLibraryRevision({ libraryId: 'library', name: 'Library', graph })+ const restored = await parseFigFile((await exportFigFile(graph)).buffer as ArrayBuffer)+ const component = [...restored.getAllNodes()].find((node) => node.componentKey === 'button')+ if (!component) throw new Error('Component missing')+ restored.updateNode(component.id, { width: 144 })+ const discovery = await discoverPublishableLibraryChanges(previous, restored)+ expect(discovery.changes).toMatchObject([{ kind: 'modified', asset: { key: 'button' } }])+ })+})diff --git a/tests/engine/library/instance-updates.test.ts b/tests/engine/library/instance-updates.test.tsnew file mode 100644index 000000000..20427c66e--- /dev/null+++ b/tests/engine/library/instance-updates.test.ts@@ -0,0 +1,126 @@+import { describe, expect, test } from 'bun:test'++import {+ createLibraryRevision,+ materializeLibraryAsset,+ planOutdatedLibraryInstances+} from '@open-pencil/core/library'+import { SceneGraph } from '@open-pencil/scene-graph'++function source(label: string) {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const component = graph.createNode('COMPONENT', page.id, {+ name: 'Button',+ componentKey: 'button',+ width: label === 'New' ? 120 : 80+ })+ graph.createNode('TEXT', component.id, { name: 'Label', text: label })+ return graph+}++describe('instance-authoritative library updates', () => {+ test('respects explicit instance scope and leaves other assets untouched', async () => {+ const oldSource = source('Old')+ const oldPage = oldSource.getPages()[0]+ oldSource.createNode('COMPONENT', oldPage.id, {+ name: 'Card',+ componentKey: 'card',+ width: 200+ })+ const newSource = source('New')+ const newPage = newSource.getPages()[0]+ newSource.createNode('COMPONENT', newPage.id, {+ name: 'Card',+ componentKey: 'card',+ width: 200+ })+ const first = await createLibraryRevision({+ libraryId: 'design-system',+ name: 'Design system',+ graph: oldSource+ })+ const second = await createLibraryRevision({+ libraryId: 'design-system',+ name: 'Design system',+ graph: newSource,+ previousRevisionId: first.manifest.revisionId+ })+ const consumer = new SceneGraph()+ const button = materializeLibraryAsset(consumer, first, 'button')+ const card = materializeLibraryAsset(consumer, first, 'card')+ const firstPage = consumer.getPages()[0]+ const secondPage = consumer.addPage('Second')+ const reviewed = consumer.createNode('INSTANCE', firstPage.id, {+ componentId: button.componentId+ })+ const samePage = consumer.createNode('INSTANCE', firstPage.id, {+ componentId: button.componentId+ })+ const otherPage = consumer.createNode('INSTANCE', secondPage.id, {+ componentId: button.componentId+ })+ const otherAsset = consumer.createNode('INSTANCE', firstPage.id, {+ componentId: card.componentId+ })+ materializeLibraryAsset(consumer, second, 'button')++ const plans = planOutdatedLibraryInstances(+ consumer,+ second,+ new Set(['button']),+ new Set([reviewed.id])+ )+ expect(plans.map((plan) => plan.instanceId)).toEqual([reviewed.id])+ const plan = plans[0]+ if (!plan) throw new Error('Expected scoped plan')+ consumer.swapInstanceComponent(plan.instanceId, plan.componentId)+ expect(consumer.getNode(reviewed.id)?.componentId).toBe(plan.componentId)+ expect(consumer.getNode(samePage.id)?.componentId).toBe(button.componentId)+ expect(consumer.getNode(otherPage.id)?.componentId).toBe(button.componentId)+ expect(consumer.getNode(otherAsset.id)?.componentId).toBe(card.componentId)+ consumer.swapInstanceComponent(plan.instanceId, plan.previousComponentId)+ expect(consumer.getNode(reviewed.id)?.componentId).toBe(button.componentId)+ })++ test('plans only outdated instances and permits mixed revisions', async () => {+ const first = await createLibraryRevision({+ libraryId: 'design-system',+ name: 'Design system',+ graph: source('Old'),+ publishedAt: '2026-01-01T00:00:00.000Z'+ })+ const second = await createLibraryRevision({+ libraryId: 'design-system',+ name: 'Design system',+ graph: source('New'),+ previousRevisionId: first.manifest.revisionId,+ publishedAt: '2026-01-02T00:00:00.000Z'+ })+ const consumer = new SceneGraph()+ const oldDefinition = materializeLibraryAsset(consumer, first, 'button')+ const firstInstance = consumer.createNode('INSTANCE', consumer.getPages()[0].id, {+ componentId: oldDefinition.componentId+ })+ const secondInstance = consumer.createNode('INSTANCE', consumer.getPages()[0].id, {+ componentId: oldDefinition.componentId+ })+ materializeLibraryAsset(consumer, second, 'button')++ const [firstPlan, secondPlan] = planOutdatedLibraryInstances(consumer, second)+ expect([firstPlan?.instanceId, secondPlan?.instanceId]).toEqual([+ firstInstance.id,+ secondInstance.id+ ])+ expect(firstPlan?.previousComponentId).toBe(oldDefinition.componentId)+ expect(firstPlan?.componentId).not.toBe(oldDefinition.componentId)++ consumer.swapInstanceComponent(firstPlan.instanceId, firstPlan.componentId)+ expect(planOutdatedLibraryInstances(consumer, second).map((plan) => plan.instanceId)).toEqual([+ secondInstance.id+ ])+ expect(consumer.getNode(firstInstance.id)?.componentId).not.toBe(+ consumer.getNode(secondInstance.id)?.componentId+ )+ })+})diff --git a/tests/engine/library/materialize.test.ts b/tests/engine/library/materialize.test.tsnew file mode 100644index 000000000..15f45529d--- /dev/null+++ b/tests/engine/library/materialize.test.ts@@ -0,0 +1,95 @@+import { describe, expect, test } from 'bun:test'++import { createLibraryRevision, materializeLibraryAsset } from '@open-pencil/core/library'+import { SceneGraph } from '@open-pencil/scene-graph'++function sourceLibrary() {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ if (!page) throw new Error('Expected page')+ const icon = graph.createNode('COMPONENT', page.id, { name: 'Icon', componentKey: 'icon' })+ graph.createNode('ELLIPSE', icon.id, { name: 'Glyph' })+ const set = graph.createNode('COMPONENT_SET', page.id, {+ name: 'Button',+ componentKey: 'button-set',+ componentPropertyDefinitions: [+ {+ id: 'variant:size',+ name: 'Size',+ type: 'VARIANT',+ defaultValue: 'Small',+ variantOptions: ['Small', 'Large']+ }+ ]+ })+ const small = graph.createNode('COMPONENT', set.id, {+ name: 'Size=Small',+ componentKey: 'button-small',+ componentPropertyValues: { Size: 'Small' }+ })+ const nested = graph.createInstance(icon.id, small.id)+ if (!nested) throw new Error('Expected nested icon')+ const large = graph.createNode('COMPONENT', set.id, {+ name: 'Size=Large',+ componentKey: 'button-large',+ componentPropertyValues: { Size: 'Large' }+ })+ return { graph, set, small, large, icon }+}++describe('library materialization', () => {+ test('lazily imports a component set and dependencies as read-only definitions', async () => {+ const source = sourceLibrary()+ const revision = await createLibraryRevision({+ libraryId: 'design-system',+ name: 'Design system',+ graph: source.graph,+ publishedAt: '2026-01-01T00:00:00.000Z'+ })+ const consumer = new SceneGraph()++ const result = materializeLibraryAsset(consumer, revision, 'button-set')+ expect(result.created).toBe(true)+ expect(consumer.getPages()).toHaveLength(1)+ expect(consumer.getPages(true)).toHaveLength(2)+ const componentSet = consumer.getNode(result.componentSetId ?? '')+ expect(componentSet?.librarySource).toMatchObject({+ identity: {+ libraryId: 'design-system',+ assetKey: 'button-set',+ revisionId: revision.manifest.revisionId+ },+ readOnly: true+ })+ expect(componentSet?.locked).toBe(true)+ expect(+ componentSet?.childIds.every((id) => consumer.getNode(id)?.librarySource?.readOnly)+ ).toBe(true)+ const instance = consumer.createInstance(result.componentId, consumer.getPages()[0]?.id ?? '')+ expect(instance?.componentId).toBe(result.componentId)+ const nestedIcon = instance+ ? consumer.getChildren(instance.id).find((node) => node.type === 'INSTANCE')+ : undefined+ expect(consumer.getNode(nestedIcon?.componentId ?? '')?.name).toBe('Icon')+ expect(consumer.enabledLibraries.get('design-system')).toEqual({+ libraryId: 'design-system',+ revisionId: revision.manifest.revisionId,+ enabled: true+ })+ })++ test('deduplicates the same stable asset revision', async () => {+ const source = sourceLibrary()+ const revision = await createLibraryRevision({+ libraryId: 'design-system',+ name: 'Design system',+ graph: source.graph+ })+ const consumer = new SceneGraph()+ const first = materializeLibraryAsset(consumer, revision, 'button-set')+ const nodeCount = consumer.nodes.size+ const second = materializeLibraryAsset(consumer, revision, 'button-set')+ expect(second).toEqual({ ...first, created: false })+ expect(consumer.nodes.size).toBe(nodeCount)+ })+})diff --git a/tests/engine/library/metadata.test.ts b/tests/engine/library/metadata.test.tsnew file mode 100644index 000000000..44c8e357f--- /dev/null+++ b/tests/engine/library/metadata.test.ts@@ -0,0 +1,38 @@+import { describe, expect, test } from 'bun:test'++import { SceneGraph } from '@open-pencil/scene-graph'++import { deserializeSceneGraph, serializeSceneGraph } from '#core/kiwi/fig/parse/transfer'++describe('library graph metadata', () => {+ test('serializes enabled library bindings and node source identity', () => {+ const graph = new SceneGraph()+ graph.enabledLibraries.set('design-system', {+ libraryId: 'design-system',+ revisionId: 'revision-1',+ enabled: true+ })+ const page = graph.getPages()[0]+ if (!page) throw new Error('Expected page')+ const component = graph.createNode('COMPONENT', page.id, {+ name: 'Button',+ librarySource: {+ identity: {+ libraryId: 'design-system',+ assetKey: 'button',+ revisionId: 'revision-1'+ },+ sourceNodeId: 'source-button',+ readOnly: true+ }+ })++ const restored = deserializeSceneGraph(serializeSceneGraph(graph))+ expect(restored.enabledLibraries.get('design-system')).toEqual({+ libraryId: 'design-system',+ revisionId: 'revision-1',+ enabled: true+ })+ expect(restored.getNode(component.id)?.librarySource).toEqual(component.librarySource)+ })+})diff --git a/tests/engine/library/preview.test.ts b/tests/engine/library/preview.test.tsnew file mode 100644index 000000000..bf77d6d74--- /dev/null+++ b/tests/engine/library/preview.test.ts@@ -0,0 +1,221 @@+import { describe, expect, test } from 'bun:test'++import {+ createLibraryRevision,+ createLibraryUpdatePreview,+ materializeLibraryAsset+} from '@open-pencil/core/library'+import { SceneGraph } from '@open-pencil/scene-graph'++function source(label: string) {+ const graph = new SceneGraph()+ const set = graph.createNode('COMPONENT_SET', graph.getPages()[0].id, {+ name: 'Button',+ componentKey: 'button'+ })+ const component = graph.createNode('COMPONENT', set.id, {+ name: 'Size=Small',+ componentPropertyValues: { Size: 'Small' }+ })+ graph.createNode('TEXT', component.id, {+ name: 'Label',+ text: label,+ componentPropertyReferences: [{ propertyId: 'label', field: 'TEXT' }]+ })+ graph.updateNode(set.id, {+ componentPropertyDefinitions: [+ { id: 'label', name: 'Label', type: 'TEXT', defaultValue: label }+ ]+ })+ return graph+}++function propertySource(kind: 'VISIBLE' | 'INSTANCE_SWAP', value: string) {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const alternate = graph.createNode('COMPONENT', page.id, {+ name: 'Alternate',+ componentKey: 'alternate',+ width: 40,+ height: 40+ })+ const component = graph.createNode('COMPONENT', page.id, {+ name: 'Card',+ componentKey: 'card',+ componentPropertyDefinitions: [+ {+ id: 'property',+ name: 'Property',+ type: kind === 'VISIBLE' ? 'BOOLEAN' : 'INSTANCE_SWAP',+ defaultValue: value+ }+ ]+ })+ if (kind === 'VISIBLE') {+ graph.createNode('RECTANGLE', component.id, {+ name: 'Optional',+ visible: true,+ componentPropertyReferences: [{ propertyId: 'property', field: 'VISIBLE' }]+ })+ } else {+ graph.createNode('INSTANCE', component.id, {+ name: 'Nested',+ componentId: alternate.id,+ componentPropertyReferences: [{ propertyId: 'property', field: 'INSTANCE_SWAP' }]+ })+ }+ return graph+}++async function revisions(firstGraph: SceneGraph, latestGraph: SceneGraph, assetKey: string) {+ const first = await createLibraryRevision({+ libraryId: 'library',+ name: 'Library',+ graph: firstGraph+ })+ const latest = await createLibraryRevision({+ libraryId: 'library',+ name: 'Library',+ graph: latestGraph,+ previousRevisionId: first.manifest.revisionId+ })+ const consumer = new SceneGraph()+ const definition = materializeLibraryAsset(consumer, first, assetKey)+ return { latest, consumer, definition }+}++describe('library update preview', () => {+ test('builds an isolated exact-variant comparison without mutating the consumer', async () => {+ const first = await createLibraryRevision({+ libraryId: 'library',+ name: 'Library',+ graph: source('Old')+ })+ const latest = await createLibraryRevision({+ libraryId: 'library',+ name: 'Library',+ graph: source('New'),+ previousRevisionId: first.manifest.revisionId+ })+ const consumer = new SceneGraph()+ const definition = materializeLibraryAsset(consumer, first, 'button')+ const instance = consumer.createNode('INSTANCE', consumer.getPages()[0].id, {+ componentId: definition.componentId,+ componentPropertyAssignments: { label: 'Custom' }+ })+ const beforeNodes = [...consumer.nodes]+ const beforeBindings = [...consumer.enabledLibraries]++ const preview = createLibraryUpdatePreview(consumer, instance.id, latest)++ expect(preview.fallback).toBe(false)+ expect(preview.graph.getNode(preview.currentNodeId)?.type).toBe('INSTANCE')+ expect(preview.graph.getNode(preview.updatedNodeId)?.type).toBe('INSTANCE')+ const currentComponentId = preview.graph.getNode(preview.currentNodeId)?.componentId+ const updatedComponentId = preview.graph.getNode(preview.updatedNodeId)?.componentId+ expect(+ currentComponentId ? preview.graph.getNode(currentComponentId)?.componentPropertyValues : null+ ).toEqual({ Size: 'Small' })+ expect(+ updatedComponentId ? preview.graph.getNode(updatedComponentId)?.componentPropertyValues : null+ ).toEqual({ Size: 'Small' })+ expect(+ preview.graph.getChildren(preview.currentNodeId).find((node) => node.type === 'TEXT')?.text+ ).toBe('Custom')+ expect(+ preview.graph.getChildren(preview.updatedNodeId).find((node) => node.type === 'TEXT')?.text+ ).toBe('Custom')+ expect([...consumer.nodes]).toEqual(beforeNodes)+ expect([...consumer.enabledLibraries]).toEqual(beforeBindings)+ })++ test('reapplies boolean visibility properties to both previews', async () => {+ const { latest, consumer, definition } = await revisions(+ propertySource('VISIBLE', 'true'),+ propertySource('VISIBLE', 'true'),+ 'card'+ )+ const instance = consumer.createNode('INSTANCE', consumer.getPages()[0].id, {+ componentId: definition.componentId,+ componentPropertyAssignments: { property: 'false' }+ })+ const preview = createLibraryUpdatePreview(consumer, instance.id, latest)+ for (const id of [preview.currentNodeId, preview.updatedNodeId]) {+ expect(preview.graph.getChildren(id)[0]?.visible).toBe(false)+ }+ })++ test('reapplies nested instance swaps using preview-local definitions', async () => {+ const firstGraph = propertySource('INSTANCE_SWAP', 'alternate')+ const latestGraph = propertySource('INSTANCE_SWAP', 'alternate')+ latestGraph.createNode('COMPONENT', latestGraph.getPages()[0].id, {+ name: 'Replacement',+ componentKey: 'replacement'+ })+ const { latest, consumer, definition } = await revisions(firstGraph, latestGraph, 'card')+ const instance = consumer.createNode('INSTANCE', consumer.getPages()[0].id, {+ componentId: definition.componentId,+ componentPropertyAssignments: { property: 'replacement' }+ })+ const preview = createLibraryUpdatePreview(consumer, instance.id, latest)+ const nested = preview.graph+ .getChildren(preview.updatedNodeId)+ .find((node) => node.type === 'INSTANCE')+ expect(nested?.componentId ? preview.graph.getNode(nested.componentId)?.name : null).toBe(+ 'Replacement'+ )+ })++ test('copies current-side nested definitions and remaps their instances', async () => {+ const firstGraph = propertySource('INSTANCE_SWAP', 'alternate')+ const latestGraph = propertySource('INSTANCE_SWAP', 'alternate')+ const { latest, consumer, definition } = await revisions(firstGraph, latestGraph, 'card')+ const instance = consumer.createNode('INSTANCE', consumer.getPages()[0].id, {+ componentId: definition.componentId+ })++ const preview = createLibraryUpdatePreview(consumer, instance.id, latest)+ const currentNested = preview.graph+ .getChildren(preview.currentNodeId)+ .find((node) => node.type === 'INSTANCE')+ const currentDefinitionNode = currentNested?.componentId+ ? preview.graph.getNode(currentNested.componentId)+ : null+ const currentDependency = currentDefinitionNode?.componentId+ ? preview.graph.getNode(currentDefinitionNode.componentId)+ : null++ expect(currentDefinitionNode?.name).toBe('Nested')+ expect(currentDependency?.name).toBe('Alternate')+ expect(currentDependency?.parentId).toBe(preview.graph.getPages()[0].id)+ expect(consumer.getNode(currentNested?.componentId ?? '')).toBeUndefined()+ })++ test('reports top-left fallback and reapplies compatible assignments', async () => {+ const firstGraph = source('Old')+ const latestGraph = source('Fallback')+ const set = [...latestGraph.getAllNodes()].find((node) => node.type === 'COMPONENT_SET')+ const variant = set ? latestGraph.getChildren(set.id)[0] : null+ if (!variant) throw new Error('Latest variant missing')+ latestGraph.updateNode(variant.id, {+ name: 'Size=Large',+ componentPropertyValues: { Size: 'Large' },+ x: 0,+ y: 0+ })+ const { latest, consumer, definition } = await revisions(firstGraph, latestGraph, 'button')+ const instance = consumer.createNode('INSTANCE', consumer.getPages()[0].id, {+ componentId: definition.componentId,+ componentPropertyAssignments: { label: 'Custom fallback' }+ })+ const preview = createLibraryUpdatePreview(consumer, instance.id, latest)+ expect(preview.fallback).toBe(true)+ const componentId = preview.graph.getNode(preview.updatedNodeId)?.componentId+ expect(+ componentId ? preview.graph.getNode(componentId)?.componentPropertyValues : null+ ).toEqual({ Size: 'Large' })+ expect(+ preview.graph.getChildren(preview.updatedNodeId).find((node) => node.type === 'TEXT')?.text+ ).toBe('Custom fallback')+ })+})diff --git a/tests/engine/library/routed-catalog.test.ts b/tests/engine/library/routed-catalog.test.tsnew file mode 100644index 000000000..ce3014351--- /dev/null+++ b/tests/engine/library/routed-catalog.test.ts@@ -0,0 +1,83 @@+import { describe, expect, test } from 'bun:test'++import 'fake-indexeddb/auto'+import { SceneGraph } from '@open-pencil/scene-graph'++import type { LibraryObjectStore } from '@/app/integrations/storage'+import { LocalLibraryCatalog } from '@/app/libraries/catalog/local'+import { RoutedLibraryCatalog } from '@/app/libraries/catalog/routed'+import { StorageLibraryCatalog } from '@/app/libraries/catalog/storage'++class MemoryObjects implements LibraryObjectStore {+ readonly values = new Map<string, Uint8Array>()+ fail = false+ async getObject(key: string) {+ if (this.fail) throw new Error('offline')+ return this.values.get(key) ?? null+ }+ async putObject(key: string, bytes: Uint8Array) {+ if (this.fail) throw new Error('offline')+ this.values.set(key, new Uint8Array(bytes))+ }+ async listObjects(prefix: string) {+ if (this.fail) throw new Error('offline')+ return [...this.values]+ .filter(([key]) => key.startsWith(prefix))+ .map(([key, value]) => ({ key, size: value.byteLength, etag: null }))+ }+}++function graph() {+ const result = new SceneGraph()+ result.createNode('COMPONENT', result.getPages()[0].id, {+ name: 'Button',+ componentKey: 'button'+ })+ return result+}++describe('routed library catalog', () => {+ test('caches remote revisions for offline retrieval', async () => {+ const objects = new MemoryObjects()+ const remote = new StorageLibraryCatalog(objects)+ const local = new LocalLibraryCatalog(`library-cache-${crypto.randomUUID()}`)+ const routed = new RoutedLibraryCatalog(local)+ routed.useStorage(remote)+ const published = await routed.publishRevision({+ libraryId: 'design-system',+ name: 'Design system',+ graph: graph()+ })+ objects.fail = true+ expect(+ (await routed.getRevision('design-system', published.manifest.revisionId)).manifest+ ).toEqual(published.manifest)+ expect(await routed.listLibraries()).toMatchObject([+ { libraryId: 'design-system', latestRevisionId: published.manifest.revisionId }+ ])+ })++ test('does not replace corrupted remote revisions with cached data', async () => {+ const objects = new MemoryObjects()+ const remote = new StorageLibraryCatalog(objects)+ const local = new LocalLibraryCatalog(`library-cache-${crypto.randomUUID()}`)+ const routed = new RoutedLibraryCatalog(local)+ routed.useStorage(remote)+ const published = await routed.publishRevision({+ libraryId: 'design-system',+ name: 'Design system',+ graph: graph()+ })+ const key = `open-pencil/libraries/design-system/revisions/${published.manifest.revisionId}.json`+ const bytes = objects.values.get(key)+ if (!bytes) throw new Error('Expected remote revision')+ objects.values.set(+ key,+ new TextEncoder().encode(new TextDecoder().decode(bytes).replace('Button', 'Corrupted'))+ )++ await expect(+ routed.getRevision('design-system', published.manifest.revisionId)+ ).rejects.toThrow('hash mismatch')+ })+})diff --git a/tests/engine/library/selective.test.ts b/tests/engine/library/selective.test.tsnew file mode 100644index 000000000..186ef55b7--- /dev/null+++ b/tests/engine/library/selective.test.ts@@ -0,0 +1,156 @@+import { describe, expect, test } from 'bun:test'++import {+ createLibraryRevision,+ createSelectiveLibraryRevision,+ discoverPublishableLibraryChanges+} from '@open-pencil/core/library'+import { SceneGraph } from '@open-pencil/scene-graph'++function source(buttonWidth: number, includeCard = true) {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ graph.createNode('COMPONENT', page.id, {+ name: 'Button',+ componentKey: 'button',+ width: buttonWidth+ })+ if (includeCard)+ graph.createNode('COMPONENT', page.id, { name: 'Card', componentKey: 'card', width: 200 })+ return graph+}++function assetHash(revision: Awaited<ReturnType<typeof createLibraryRevision>>, key: string) {+ return revision.manifest.assets.find((asset) => asset.key === key)?.contentHash+}++async function initialRevision() {+ return createLibraryRevision({ libraryId: 'library', name: 'Library', graph: source(80) })+}++describe('selective library publication', () => {+ test('publishes one modification while retaining another prior asset', async () => {+ const previous = await initialRevision()+ const changed = source(120)+ const card = [...changed.getAllNodes()].find((node) => node.componentKey === 'card')+ if (!card) throw new Error('Card missing')+ changed.updateNode(card.id, { width: 240 })++ const discovery = await discoverPublishableLibraryChanges(previous, changed)+ expect(discovery.changes.map((change) => change.asset.key).sort()).toEqual(['button', 'card'])+ const next = await createSelectiveLibraryRevision({+ previous,+ sourceGraph: changed,+ selectedAssetKeys: new Set(['button']),+ name: 'Library'+ })+ expect(next.manifest.assets.map((asset) => asset.key).sort()).toEqual(['button', 'card'])+ expect(assetHash(next, 'card')).toBe(assetHash(previous, 'card'))+ expect(assetHash(next, 'button')).not.toBe(assetHash(previous, 'button'))+ })++ test('keeps skipped additions and removals pending', async () => {+ const previous = await initialRevision()+ const changed = source(120, false)+ const page = changed.getPages()[0]+ changed.createNode('COMPONENT', page.id, {+ name: 'Tooltip',+ componentKey: 'tooltip',+ width: 160+ })+ const discovery = await discoverPublishableLibraryChanges(previous, changed)+ expect(discovery.changes.map((change) => `${change.kind}:${change.asset.key}`).sort()).toEqual([+ 'added:tooltip',+ 'modified:button',+ 'removed:card'+ ])++ const next = await createSelectiveLibraryRevision({+ previous,+ sourceGraph: changed,+ selectedAssetKeys: new Set(['button']),+ name: 'Library'+ })+ expect(next.manifest.assets.map((asset) => asset.key).sort()).toEqual(['button', 'card'])+ const pending = await discoverPublishableLibraryChanges(next, changed)+ expect(pending.changes.map((change) => `${change.kind}:${change.asset.key}`).sort()).toEqual([+ 'added:tooltip',+ 'removed:card'+ ])+ })++ test('applies selected additions and removals deterministically', async () => {+ const previous = await initialRevision()+ const changed = source(80, false)+ const page = changed.getPages()[0]+ changed.createNode('COMPONENT', page.id, {+ name: 'Tooltip',+ componentKey: 'tooltip',+ width: 160+ })+ const input = {+ previous,+ sourceGraph: changed,+ selectedAssetKeys: new Set(['tooltip', 'card']),+ name: 'Library',+ publishedAt: '2026-01-01T00:00:00.000Z'+ }+ const first = await createSelectiveLibraryRevision(input)+ const second = await createSelectiveLibraryRevision(input)+ expect(first.manifest.assets.map((asset) => asset.key).sort()).toEqual(['button', 'tooltip'])+ expect(first.manifest.revisionId).toBe(second.manifest.revisionId)+ })++ test('does not mutate the source while discovering changes', async () => {+ const previous = await initialRevision()+ const changed = source(120)+ const before = [...changed.nodes].map(([id, node]) => [id, structuredClone(node)] as const)+ await discoverPublishableLibraryChanges(previous, changed)+ expect([...changed.nodes]).toEqual(before)+ })++ test('preserves nested component dependencies in retained assets', async () => {+ const sourceGraph = source(80)+ const button = [...sourceGraph.getAllNodes()].find((node) => node.componentKey === 'button')+ const card = [...sourceGraph.getAllNodes()].find((node) => node.componentKey === 'card')+ if (!button || !card) throw new Error('Components missing')+ sourceGraph.createNode('INSTANCE', card.id, { componentId: button.id })+ const previous = await createLibraryRevision({+ libraryId: 'library',+ name: 'Library',+ graph: sourceGraph+ })+ const changed = source(120)+ const changedPage = changed.getPages()[0]+ changed.createNode('COMPONENT', changedPage.id, {+ name: 'Tooltip',+ componentKey: 'tooltip'+ })+ const next = await createSelectiveLibraryRevision({+ previous,+ sourceGraph: changed,+ selectedAssetKeys: new Set(['button']),+ name: 'Library'+ })+ const retainedCard = next.manifest.assets.find((asset) => asset.key === 'card')+ const retainedRoot = retainedCard ? next.graph.getNode(retainedCard.sourceNodeId) : null+ const nested = retainedRoot+ ? next.graph.getChildren(retainedRoot.id).find((node) => node.type === 'INSTANCE')+ : null+ expect(nested?.componentId ? next.graph.getNode(nested.componentId)?.componentKey : null).toBe(+ 'button'+ )+ })++ test('rejects publication when no pending change is selected', async () => {+ const previous = await initialRevision()+ expect(+ createSelectiveLibraryRevision({+ previous,+ sourceGraph: source(120),+ selectedAssetKeys: new Set(['missing']),+ name: 'Library'+ })+ ).rejects.toThrow('No library changes selected')+ })+})diff --git a/tests/engine/library/snapshot.test.ts b/tests/engine/library/snapshot.test.tsnew file mode 100644index 000000000..31f9ba37a--- /dev/null+++ b/tests/engine/library/snapshot.test.ts@@ -0,0 +1,152 @@+import { describe, expect, test } from 'bun:test'++import {+ createLibraryRevision,+ deserializeLibraryRevision,+ diffLibraryManifests,+ ensureLibraryAssetKeys,+ extractLibrarySnapshot,+ MemoryLibraryCatalog,+ serializeLibraryRevision+} from '@open-pencil/core/library'+import { SceneGraph } from '@open-pencil/scene-graph'++function setupLibraryGraph() {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ if (!page) throw new Error('Expected page')+ const icon = graph.createNode('COMPONENT', page.id, {+ name: 'Icon',+ componentKey: 'icon'+ })+ graph.createNode('ELLIPSE', icon.id, { name: 'Glyph' })+ const button = graph.createNode('COMPONENT', page.id, {+ name: 'Button',+ componentKey: 'button'+ })+ const nestedIcon = graph.createInstance(icon.id, button.id)+ if (!nestedIcon) throw new Error('Expected nested instance')+ return { graph, icon, button }+}++describe('component library snapshots', () => {+ test('extracts selected assets with nested component dependencies and remapped IDs', () => {+ const { graph, icon, button } = setupLibraryGraph()+ const snapshot = extractLibrarySnapshot(graph, [button.id])+ expect(snapshot.assetRoots.map((node) => node.name)).toEqual(['Button'])+ const components = [...snapshot.graph.getAllNodes()].filter((node) => node.type === 'COMPONENT')+ expect(components.map((node) => node.name).sort()).toEqual(['Button', 'Icon'])+ const importedButton = snapshot.assetRoots[0]+ const importedNested = importedButton+ ? snapshot.graph.getChildren(importedButton.id).find((node) => node.type === 'INSTANCE')+ : undefined+ expect(importedNested?.componentId).not.toBe(icon.id)+ expect(snapshot.graph.getNode(importedNested?.componentId ?? '')?.name).toBe('Icon')+ })++ test('creates deterministic content revisions independent of local node IDs', async () => {+ const first = setupLibraryGraph()+ const second = setupLibraryGraph()+ const inputs = {+ libraryId: 'design-system',+ name: 'Design system',+ publishedAt: '2026-01-01T00:00:00.000Z'+ }+ const firstRevision = await createLibraryRevision({ ...inputs, graph: first.graph })+ const secondRevision = await createLibraryRevision({ ...inputs, graph: second.graph })+ expect(firstRevision.manifest.revisionId).toBe(secondRevision.manifest.revisionId)+ expect(firstRevision.manifest.assets.map((asset) => asset.key).sort()).toEqual([+ 'button',+ 'icon'+ ])++ first.graph.updateNode(first.button.id, { opacity: 0.5 })+ const changedRevision = await createLibraryRevision({ ...inputs, graph: first.graph })+ expect(changedRevision.manifest.revisionId).not.toBe(firstRevision.manifest.revisionId)+ })++ test('diffs revisions by stable asset key', async () => {+ const { graph, button, icon } = setupLibraryGraph()+ const base = await createLibraryRevision({+ libraryId: 'design-system',+ name: 'Design system',+ graph,+ publishedAt: '2026-01-01T00:00:00.000Z'+ })+ graph.updateNode(button.id, { opacity: 0.5 })+ graph.updateNode(icon.id, { name: 'System icon' })+ const next = await createLibraryRevision({+ libraryId: 'design-system',+ name: 'Design system',+ graph,+ previousRevisionId: base.manifest.revisionId,+ publishedAt: '2026-01-02T00:00:00.000Z'+ })+ expect(diffLibraryManifests(base.manifest, next.manifest).map((change) => change.kind)).toEqual(+ ['renamed', 'modified']+ )+ })++ test('assigns durable unique keys once and preserves them across rename', () => {+ const { graph, button, icon } = setupLibraryGraph()+ graph.updateNode(button.id, { componentKey: null })+ graph.updateNode(icon.id, { componentKey: null })+ expect(+ ensureLibraryAssetKeys(graph)+ .map((assignment) => assignment.assetKey)+ .sort()+ ).toEqual(['button', 'icon'])+ graph.updateNode(button.id, { name: 'Primary action' })+ expect(+ ensureLibraryAssetKeys(graph).find((assignment) => assignment.nodeId === button.id)+ ).toEqual({+ nodeId: button.id,+ assetKey: 'button',+ existing: true+ })+ })++ test('serializes portable revisions without losing component links', async () => {+ const { graph } = setupLibraryGraph()+ const revision = await createLibraryRevision({+ libraryId: 'design-system',+ name: 'Design system',+ graph+ })+ const restored = deserializeLibraryRevision(structuredClone(serializeLibraryRevision(revision)))+ expect(restored.manifest).toEqual(revision.manifest)+ const button = [...restored.graph.getAllNodes()].find((node) => node.componentKey === 'button')+ const nested = button+ ? restored.graph.getChildren(button.id).find((node) => node.type === 'INSTANCE')+ : undefined+ expect(restored.graph.getNode(nested?.componentId ?? '')?.componentKey).toBe('icon')+ })++ test('publishes immutable revisions with optimistic conflict detection', async () => {+ const { graph } = setupLibraryGraph()+ const catalog = new MemoryLibraryCatalog()+ const first = await catalog.publishRevision({+ libraryId: 'design-system',+ name: 'Design system',+ graph,+ publishedAt: '2026-01-01T00:00:00.000Z'+ })+ expect(await catalog.listLibraries()).toEqual([+ {+ libraryId: 'design-system',+ name: 'Design system',+ latestRevisionId: first.manifest.revisionId,+ publishedAt: '2026-01-01T00:00:00.000Z',+ assetCount: 2+ }+ ])+ await expect(+ catalog.publishRevision({+ libraryId: 'design-system',+ name: 'Design system',+ graph,+ previousRevisionId: 'stale'+ })+ ).rejects.toThrow('latest revision has changed')+ })+})diff --git a/tests/engine/library/source-publication.test.ts b/tests/engine/library/source-publication.test.tsnew file mode 100644index 000000000..28b6808a8--- /dev/null+++ b/tests/engine/library/source-publication.test.ts@@ -0,0 +1,55 @@+import { describe, expect, test } from 'bun:test'++import { exportFigFile, initCodec, parseFigFile } from '@open-pencil/core'+import {+ readSourceLibraryPublication,+ writeSourceLibraryPublication+} from '@open-pencil/core/library'+import { SceneGraph } from '@open-pencil/scene-graph'++describe('source library publication identity', () => {+ test('survives a FIG export and reimport', async () => {+ initCodec()+ const graph = new SceneGraph()+ writeSourceLibraryPublication(graph, {+ libraryId: 'design-system',+ revisionId: 'revision-1',+ name: 'Design system',+ catalogSource: 'local'+ })+ const restored = await parseFigFile((await exportFigFile(graph)).buffer as ArrayBuffer)+ expect(readSourceLibraryPublication(restored)).toEqual({+ libraryId: 'design-system',+ revisionId: 'revision-1',+ name: 'Design system',+ catalogSource: 'local'+ })+ })++ test('round-trips through root plugin data', () => {+ const graph = new SceneGraph()+ expect(readSourceLibraryPublication(graph)).toBeNull()+ writeSourceLibraryPublication(graph, {+ libraryId: 'design-system',+ revisionId: 'revision-1',+ name: 'Design system',+ catalogSource: 'local'+ })+ expect(readSourceLibraryPublication(graph)).toEqual({+ libraryId: 'design-system',+ revisionId: 'revision-1',+ name: 'Design system',+ catalogSource: 'local'+ })+ })++ test('ignores malformed metadata', () => {+ const graph = new SceneGraph()+ const root = graph.getNode(graph.rootId)+ if (!root) throw new Error('Root missing')+ graph.updateNode(root.id, {+ pluginData: [{ pluginId: 'open-pencil', key: 'sourceLibraryPublication', value: '{}' }]+ })+ expect(readSourceLibraryPublication(graph)).toBeNull()+ })+})diff --git a/tests/engine/library/storage-catalog.test.ts b/tests/engine/library/storage-catalog.test.tsnew file mode 100644index 000000000..0b335b462--- /dev/null+++ b/tests/engine/library/storage-catalog.test.ts@@ -0,0 +1,162 @@+import { describe, expect, test } from 'bun:test'++import { SceneGraph } from '@open-pencil/scene-graph'++import type { LibraryObjectStore } from '@/app/integrations/storage'+import { StorageLibraryCatalog } from '@/app/libraries/catalog/storage'++class MemoryObjects implements LibraryObjectStore {+ readonly values = new Map<string, Uint8Array>()+ readonly etags = new Map<string, string>()+ #version = 0++ async getObject(key: string) {+ return this.values.get(key) ?? null+ }++ async getObjectValue(key: string) {+ return { bytes: await this.getObject(key), etag: this.etags.get(key) ?? null }+ }++ async putObject(+ key: string,+ bytes: Uint8Array,+ _contentType?: string,+ options?: { ifMatch?: string; ifNoneMatch?: '*' }+ ) {+ const current = this.etags.get(key)+ if (options?.ifNoneMatch === '*' && current) throw new Error('revision conflict')+ if (options?.ifMatch && options.ifMatch !== current) throw new Error('revision conflict')+ this.values.set(key, new Uint8Array(bytes))+ this.#version += 1+ this.etags.set(key, `etag-${this.#version}`)+ }++ async listObjects(prefix: string) {+ return [...this.values]+ .filter(([key]) => key.startsWith(prefix))+ .map(([key, value]) => ({ key, size: value.byteLength, etag: null }))+ }+}++function sourceGraph() {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ graph.createNode('COMPONENT', page.id, { name: 'Button', componentKey: 'button' })+ return graph+}++describe('storage library catalog', () => {+ test('publishes immutable revision objects before the latest manifest', async () => {+ const objects = new MemoryObjects()+ const catalog = new StorageLibraryCatalog(objects)+ const revision = await catalog.publishRevision({+ libraryId: 'design-system',+ name: 'Design system',+ graph: sourceGraph(),+ publishedAt: '2026-01-01T00:00:00.000Z'+ })++ expect([...objects.values.keys()]).toEqual([+ `open-pencil/libraries/design-system/revisions/${revision.manifest.revisionId}.json`,+ 'open-pencil/libraries/design-system/manifest.json'+ ])+ expect(await catalog.listLibraries()).toMatchObject([+ { libraryId: 'design-system', latestRevisionId: revision.manifest.revisionId }+ ])+ const restored = await catalog.getRevision('design-system')+ expect(restored.manifest).toEqual(revision.manifest)+ expect([...restored.graph.getAllNodes()].some((node) => node.componentKey === 'button')).toBe(+ true+ )+ })++ test('rejects corrupted revision content', async () => {+ const objects = new MemoryObjects()+ const catalog = new StorageLibraryCatalog(objects)+ const revision = await catalog.publishRevision({+ libraryId: 'design-system',+ name: 'Design system',+ graph: sourceGraph()+ })+ const key = `open-pencil/libraries/design-system/revisions/${revision.manifest.revisionId}.json`+ const bytes = objects.values.get(key)+ if (!bytes) throw new Error('Expected revision object')+ const source = new TextDecoder().decode(bytes).replace('Button', 'Corrupted')+ objects.values.set(key, new TextEncoder().encode(source))+ await expect(+ catalog.getRevision('design-system', revision.manifest.revisionId)+ ).rejects.toThrow('hash mismatch')+ })++ test('rejects updates when the provider cannot return latest-manifest ETags', async () => {+ const objects = new MemoryObjects()+ const catalog = new StorageLibraryCatalog(objects)+ const initial = await catalog.publishRevision({+ libraryId: 'design-system',+ name: 'Design system',+ graph: sourceGraph()+ })+ objects.getObjectValue = async (key) => ({ bytes: await objects.getObject(key), etag: null })+ await expect(+ catalog.publishRevision({+ libraryId: 'design-system',+ name: 'Design system',+ graph: sourceGraph(),+ previousRevisionId: initial.manifest.revisionId+ })+ ).rejects.toThrow('does not support conditional library publication')+ })++ test('allows only one concurrent latest-pointer update', async () => {+ const objects = new MemoryObjects()+ const first = new StorageLibraryCatalog(objects)+ const second = new StorageLibraryCatalog(objects)+ const initial = await first.publishRevision({+ libraryId: 'design-system',+ name: 'Design system',+ graph: sourceGraph()+ })+ const delayedWrites: Array<() => void> = []+ const originalPut = objects.putObject.bind(objects)+ objects.putObject = async (key, bytes, contentType, options) => {+ if (key.endsWith('/manifest.json')) {+ await new Promise<void>((resolve) => {+ delayedWrites.push(resolve)+ })+ }+ return originalPut(key, bytes, contentType, options)+ }+ const publications = [first, second].map((catalog, index) =>+ catalog.publishRevision({+ libraryId: 'design-system',+ name: 'Design system',+ graph: sourceGraph(),+ previousRevisionId: initial.manifest.revisionId,+ description: `publisher-${index}`+ })+ )+ while (delayedWrites.length < 2) await Bun.sleep(1)+ for (const release of delayedWrites) release()+ const results = await Promise.allSettled(publications)+ expect(results.filter((result) => result.status === 'fulfilled')).toHaveLength(1)+ expect(results.filter((result) => result.status === 'rejected')).toHaveLength(1)+ })++ test('rejects stale publication pointers', async () => {+ const catalog = new StorageLibraryCatalog(new MemoryObjects())+ await catalog.publishRevision({+ libraryId: 'design-system',+ name: 'Design system',+ graph: sourceGraph()+ })+ await expect(+ catalog.publishRevision({+ libraryId: 'design-system',+ name: 'Design system',+ graph: sourceGraph(),+ previousRevisionId: 'stale'+ })+ ).rejects.toThrow('latest revision has changed')+ })+})diff --git a/tests/engine/library/update-groups.test.ts b/tests/engine/library/update-groups.test.tsnew file mode 100644index 000000000..436b228f2--- /dev/null+++ b/tests/engine/library/update-groups.test.ts@@ -0,0 +1,31 @@+import { describe, expect, test } from 'bun:test'++import { createEditor } from '@open-pencil/core/editor'+import { SceneGraph } from '@open-pencil/scene-graph'++import { scopeLibraryUpdateGroups } from '@/app/libraries/update-groups'++describe('library update page scopes', () => {+ test('filters grouped updates to the current page', () => {+ const graph = new SceneGraph()+ const firstPage = graph.getPages()[0]+ const secondPage = graph.addPage('Second')+ const first = graph.createNode('INSTANCE', firstPage.id)+ const second = graph.createNode('INSTANCE', secondPage.id)+ const editor = createEditor({ graph })+ editor.state.currentPageId = firstPage.id+ const groups = [+ {+ libraryId: 'library',+ assetKey: 'button',+ name: 'Button',+ instanceIds: [first.id, second.id],+ currentPageCount: 2,+ allPagesCount: 2+ }+ ]++ expect(scopeLibraryUpdateGroups(editor, groups, false)[0]?.instanceIds).toEqual([first.id])+ expect(scopeLibraryUpdateGroups(editor, groups, true)[0]?.instanceIds).toHaveLength(2)+ })+})diff --git a/tests/engine/library/update.test.ts b/tests/engine/library/update.test.tsnew file mode 100644index 000000000..0882f29de--- /dev/null+++ b/tests/engine/library/update.test.ts@@ -0,0 +1,135 @@+import { describe, expect, test } from 'bun:test'++import {+ createLibraryRevision,+ libraryUpdateImpact,+ materializeLibraryAsset,+ planLibraryInstanceUpdates,+ summarizeLibraryUpdate+} from '@open-pencil/core/library'+import { SceneGraph } from '@open-pencil/scene-graph'++function revisionGraph(label: string, includeLarge = true) {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ if (!page) throw new Error('Expected page')+ const set = graph.createNode('COMPONENT_SET', page.id, {+ name: 'Button',+ componentKey: 'button-set',+ componentPropertyDefinitions: [+ {+ id: 'size',+ name: 'Size',+ type: 'VARIANT',+ defaultValue: 'Small',+ variantOptions: includeLarge ? ['Small', 'Large'] : ['Small']+ }+ ]+ })+ const small = graph.createNode('COMPONENT', set.id, {+ name: 'Size=Small',+ componentKey: 'button-small',+ componentPropertyValues: { Size: 'Small' }+ })+ graph.createNode('TEXT', small.id, { name: 'Label', text: label })+ if (includeLarge) {+ const large = graph.createNode('COMPONENT', set.id, {+ name: 'Size=Large',+ componentKey: 'button-large',+ componentPropertyValues: { Size: 'Large' }+ })+ graph.createNode('TEXT', large.id, { name: 'Label', text: label })+ }+ return graph+}++describe('library updates', () => {+ test('summarizes newer revisions and plans exact variant updates', async () => {+ const first = await createLibraryRevision({+ libraryId: 'design-system',+ name: 'Design system',+ graph: revisionGraph('Old'),+ publishedAt: '2026-01-01T00:00:00.000Z'+ })+ const next = await createLibraryRevision({+ libraryId: 'design-system',+ name: 'Design system',+ graph: revisionGraph('New'),+ previousRevisionId: first.manifest.revisionId,+ publishedAt: '2026-01-02T00:00:00.000Z'+ })+ expect(summarizeLibraryUpdate(first, next)).toMatchObject({+ currentRevisionId: first.manifest.revisionId,+ latestRevisionId: next.manifest.revisionId,+ changes: [{ kind: 'modified' }]+ })++ const consumer = new SceneGraph()+ const oldAsset = materializeLibraryAsset(consumer, first, 'button-set')+ const oldSet = consumer.getNode(oldAsset.componentSetId ?? '')+ const oldLarge = oldSet?.childIds+ .map((id) => consumer.getNode(id))+ .find((node) => node?.componentPropertyValues.Size === 'Large')+ if (!oldLarge) throw new Error('Expected old large variant')+ const instance = consumer.createInstance(oldLarge.id, consumer.getPages()[0]?.id ?? '')+ if (!instance) throw new Error('Expected instance')+ materializeLibraryAsset(consumer, next, 'button-set')++ const plans = planLibraryInstanceUpdates(+ consumer,+ 'design-system',+ first.manifest.revisionId,+ next.manifest.revisionId,+ next.manifest.assets+ )+ expect(plans).toHaveLength(1)+ expect(consumer.getNode(plans[0]?.componentId ?? '')?.componentPropertyValues).toEqual({+ Size: 'Large'+ })+ expect(plans[0]?.fallback).toBe(false)+ expect(libraryUpdateImpact(plans)).toEqual({+ affectedInstanceCount: 1,+ fallbackInstanceCount: 0+ })+ })++ test('falls back to the new top-left variant when a combination was removed', async () => {+ const first = await createLibraryRevision({+ libraryId: 'design-system',+ name: 'Design system',+ graph: revisionGraph('Old')+ })+ const next = await createLibraryRevision({+ libraryId: 'design-system',+ name: 'Design system',+ graph: revisionGraph('New', false),+ previousRevisionId: first.manifest.revisionId+ })+ const consumer = new SceneGraph()+ const oldAsset = materializeLibraryAsset(consumer, first, 'button-set')+ const oldSet = consumer.getNode(oldAsset.componentSetId ?? '')+ const oldLarge = oldSet?.childIds+ .map((id) => consumer.getNode(id))+ .find((node) => node?.componentPropertyValues.Size === 'Large')+ if (!oldLarge) throw new Error('Expected old large variant')+ consumer.createInstance(oldLarge.id, consumer.getPages()[0]?.id ?? '')+ materializeLibraryAsset(consumer, next, 'button-set')++ const plans = planLibraryInstanceUpdates(+ consumer,+ 'design-system',+ first.manifest.revisionId,+ next.manifest.revisionId,+ next.manifest.assets+ )+ expect(plans).toHaveLength(1)+ expect(plans[0]?.fallback).toBe(true)+ expect(libraryUpdateImpact(plans)).toEqual({+ affectedInstanceCount: 1,+ fallbackInstanceCount: 1+ })+ expect(consumer.getNode(plans[0]?.componentId ?? '')?.componentPropertyValues).toEqual({+ Size: 'Small'+ })+ })+})diff --git a/tests/engine/tools/library-components.test.ts b/tests/engine/tools/library-components.test.tsnew file mode 100644index 000000000..1c1e9e958--- /dev/null+++ b/tests/engine/tools/library-components.test.ts@@ -0,0 +1,79 @@+import { describe, expect, test } from 'bun:test'++import { FigmaAPI } from '@open-pencil/core/figma-api'+import { registerComponentCatalog } from '@open-pencil/core/tools'+import { getComponents, insertLibraryComponent, listLibraries } from '@open-pencil/core/tools/read'+import { SceneGraph } from '@open-pencil/scene-graph'++function catalog() {+ return {+ async listLibraries() {+ return [+ {+ libraryId: 'preferred',+ name: 'Preferred design system',+ latestRevisionId: 'r1',+ publishedAt: '2026-01-01T00:00:00.000Z',+ assetCount: 1+ }+ ]+ },+ async listComponents() {+ return [+ {+ libraryId: 'preferred',+ libraryName: 'Preferred design system',+ revisionId: 'r1',+ enabled: true,+ priority: 10,+ asset: {+ key: 'button',+ type: 'COMPONENT' as const,+ name: 'Button',+ description: 'Reusable action',+ sourceNodeId: 'source',+ contentHash: 'hash'+ }+ }+ ]+ },+ async insertComponent() {+ return { id: '0:instance', componentId: '0:component' }+ }+ }+}++describe('library component tools', () => {+ test('lists libraries and ranks enabled library components before local components', async () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ if (!page) throw new Error('Expected page')+ graph.createNode('COMPONENT', page.id, { name: 'Button local' })+ const figma = new FigmaAPI(graph)+ figma.currentPage = figma.wrapNode(page.id)+ registerComponentCatalog(graph, catalog())++ expect(await listLibraries.execute(figma, {})).toMatchObject({ count: 1 })+ const result = await getComponents.execute(figma, { name: 'button', source: 'all' })+ expect(result).toMatchObject({+ count: 2,+ components: [+ { source: 'library', libraryId: 'preferred', assetKey: 'button' },+ { source: 'document', name: 'Button local' }+ ]+ })+ })++ test('inserts by stable identity through the configured catalog', async () => {+ const graph = new SceneGraph()+ const figma = new FigmaAPI(graph)+ registerComponentCatalog(graph, catalog())+ expect(+ await insertLibraryComponent.execute(figma, {+ library_id: 'preferred',+ asset_key: 'button',+ variant_values: '{"Size":"Large"}'+ })+ ).toEqual({ id: '0:instance', componentId: '0:component' })+ })+})diff --git a/tsconfig.json b/tsconfig.jsonindex b99713584..67e922c58 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -49,6 +49,9 @@"tinykeys": ["./node_modules/tinykeys/dist/tinykeys.d.ts"],+ "@open-pencil/cli/library": [+ "./packages/cli/src/library/index.ts"+ ],"@open-pencil/vue": ["./packages/vue/src/index.ts"],