openpencil/tests/engine/render.test.ts

815 lines
26 KiB
TypeScript
Raw Normal View History

import { describe, expect, it } from 'bun:test'
import {
renderTree,
renderJSX,
renderTreeNode,
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
computeLayout,
computeAllLayouts,
sceneNodeToJSX,
Frame,
Text,
Rectangle,
Ellipse,
Line,
Star,
Group,
Section,
isTreeNode,
node
} from '@open-pencil/core'
2026-05-03 18:03:40 +00:00
import { makeSceneGraph } from '../helpers/scene'
describe('TreeNode builders', () => {
it('creates Frame tree node', () => {
const tree = Frame({ name: 'Card', w: 320, h: 200, bg: '#FFF' })
expect(isTreeNode(tree)).toBe(true)
expect(tree.type).toBe('frame')
expect(tree.props.name).toBe('Card')
expect(tree.props.w).toBe(320)
expect(tree.children).toEqual([])
})
it('creates Text tree node with string child', () => {
const tree = Text({ name: 'Title', size: 18, children: 'Hello World' })
expect(tree.type).toBe('text')
expect(tree.children).toEqual(['Hello World'])
})
it('creates nested tree', () => {
const tree = Frame({
name: 'Card',
children: [
Rectangle({ name: 'Bg', w: 100, h: 100, bg: '#E5E7EB' }),
Text({ name: 'Label', size: 14, children: 'Click me' })
]
})
expect(tree.children.length).toBe(2)
expect(isTreeNode(tree.children[0]!)).toBe(true)
const bg = tree.children[0] as ReturnType<typeof Rectangle>
expect(bg.type).toBe('rectangle')
expect(bg.props.name).toBe('Bg')
})
it('node() flattens nested arrays', () => {
const tree = node('frame', {
children: [[Text({ children: 'A' }), Text({ children: 'B' })], Text({ children: 'C' })]
})
expect(tree.children.length).toBe(3)
})
it('node() filters null/undefined children', () => {
const tree = node('frame', {
children: [null, Text({ children: 'A' }), undefined]
})
expect(tree.children.length).toBe(1)
})
})
describe('renderTree', () => {
it('renders a simple frame', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const tree = Frame({ name: 'MyFrame', w: 200, h: 100, bg: '#FF0000' })
const result = await renderTree(g, tree)
expect(result.name).toBe('MyFrame')
expect(result.type).toBe('FRAME')
const node = g.nodes.get(result.id)!
expect(node.width).toBe(200)
expect(node.height).toBe(100)
expect(node.fills.length).toBe(1)
expect(node.fills[0]!.type).toBe('SOLID')
})
it('renders text node with content', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
2026-05-03 18:03:40 +00:00
const tree = Text({
name: 'Heading',
size: 24,
weight: 'bold',
color: '#111',
children: 'Hello'
})
const result = await renderTree(g, tree)
const node = g.nodes.get(result.id)!
expect(node.type).toBe('TEXT')
expect(node.text).toBe('Hello')
expect(node.fontSize).toBe(24)
expect(node.fontWeight).toBe(700)
expect(node.fills.length).toBe(1)
})
it('renders nested structure', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const tree = Frame({
name: 'Card',
w: 320,
flex: 'col',
gap: 16,
p: 24,
bg: '#FFF',
children: [
Rectangle({ name: 'Image', w: 272, h: 200, bg: '#E5E7EB' }),
Text({ name: 'Title', size: 18, weight: 'bold', color: '#111', children: 'Card Title' }),
Text({ name: 'Description', size: 14, color: '#6B7280', children: 'Lorem ipsum' })
]
})
const result = await renderTree(g, tree)
const card = g.nodes.get(result.id)!
expect(card.layoutMode).toBe('VERTICAL')
expect(card.itemSpacing).toBe(16)
expect(card.paddingTop).toBe(24)
expect(card.paddingRight).toBe(24)
expect(card.childIds.length).toBe(3)
const title = g.nodes.get(card.childIds[1]!)!
expect(title.text).toBe('Card Title')
expect(title.fontWeight).toBe(700)
})
it('renders with position override', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const tree = Frame({ name: 'Positioned', w: 100, h: 100 })
const result = await renderTree(g, tree, { x: 50, y: 75 })
const node = g.nodes.get(result.id)!
expect(node.x).toBe(50)
expect(node.y).toBe(75)
})
it('renders into a specific parent', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const page = g.getPages()[0]!
const container = g.createNode('FRAME', page.id, { name: 'Container' })
const tree = Frame({ name: 'Child', w: 50, h: 50 })
await renderTree(g, tree, { parentId: container.id })
expect(container.childIds.length).toBe(1)
})
it('handles auto-layout properties', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const tree = Frame({
name: 'Flex',
flex: 'row',
gap: 8,
justify: 'between',
items: 'center',
wrap: true
})
const result = await renderTree(g, tree)
const node = g.nodes.get(result.id)!
expect(node.layoutMode).toBe('HORIZONTAL')
expect(node.itemSpacing).toBe(8)
expect(node.primaryAxisAlign).toBe('SPACE_BETWEEN')
expect(node.counterAxisAlign).toBe('CENTER')
expect(node.layoutWrap).toBe('WRAP')
})
it('justify/items without flex auto-enables auto-layout', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
const tree = Frame(
{ name: 'IconBtn', w: 36, h: 36, justify: 'center', items: 'center' },
Text({ size: 16, color: '#FFFFFF', children: '★' })
)
const result = await renderTree(g, tree)
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
const n = g.nodes.get(result.id)!
expect(n.layoutMode).toBe('VERTICAL')
expect(n.primaryAxisAlign).toBe('CENTER')
expect(n.counterAxisAlign).toBe('CENTER')
})
it('handles padding shorthands', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const tree = Frame({ name: 'Padded', px: 16, py: 8, pt: 4 })
const result = await renderTree(g, tree)
const node = g.nodes.get(result.id)!
expect(node.paddingLeft).toBe(16)
expect(node.paddingRight).toBe(16)
expect(node.paddingBottom).toBe(8)
expect(node.paddingTop).toBe(4) // pt overrides py
})
it('handles corner radius', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const tree = Frame({ name: 'Rounded', rounded: 12 })
const result = await renderTree(g, tree)
expect(g.nodes.get(result.id)!.cornerRadius).toBe(12)
})
it('handles independent corners', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const tree = Frame({ name: 'Corners', roundedTL: 8, roundedBR: 16 })
const result = await renderTree(g, tree)
const node = g.nodes.get(result.id)!
expect(node.independentCorners).toBe(true)
expect(node.topLeftRadius).toBe(8)
expect(node.bottomRightRadius).toBe(16)
})
it('handles stroke', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const tree = Rectangle({ name: 'Bordered', stroke: '#000', strokeWidth: 2 })
const result = await renderTree(g, tree)
const node = g.nodes.get(result.id)!
expect(node.strokes.length).toBe(1)
expect(node.strokes[0]!.weight).toBe(2)
})
it('handles opacity and rotation', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const tree = Frame({ name: 'Transformed', opacity: 0.5, rotate: 45 })
const result = await renderTree(g, tree)
const node = g.nodes.get(result.id)!
expect(node.opacity).toBe(0.5)
expect(node.rotation).toBe(45)
})
it('handles overflow hidden (clip)', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const tree = Frame({ name: 'Clipped', overflow: 'hidden' })
const result = await renderTree(g, tree)
expect(g.nodes.get(result.id)!.clipsContent).toBe(true)
})
it('handles hug sizing', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const tree = Frame({ name: 'Hug', w: 'hug', h: 'hug', flex: 'col' })
const result = await renderTree(g, tree)
const node = g.nodes.get(result.id)!
expect(node.primaryAxisSizing).toBe('HUG')
expect(node.counterAxisSizing).toBe('HUG')
})
it('handles fill sizing', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const tree = Frame({ name: 'Fill', w: 'fill' })
const result = await renderTree(g, tree)
const node = g.nodes.get(result.id)!
expect(node.layoutGrow).toBe(1)
})
it('handles shadow effect', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const tree = Frame({ name: 'Shadow', shadow: '0 4 12 rgba(0,0,0,0.1)' })
const result = await renderTree(g, tree)
const node = g.nodes.get(result.id)!
expect(node.effects.length).toBe(1)
expect(node.effects[0]!.type).toBe('DROP_SHADOW')
expect(node.effects[0]!.radius).toBe(12)
})
it('handles blur effect', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const tree = Frame({ name: 'Blurred', blur: 8 })
const result = await renderTree(g, tree)
const node = g.nodes.get(result.id)!
expect(node.effects.length).toBe(1)
expect(node.effects[0]!.type).toBe('LAYER_BLUR')
expect(node.effects[0]!.radius).toBe(8)
})
it('renders all primitive types', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const types = [
{ fn: Rectangle, expected: 'RECTANGLE' },
{ fn: Ellipse, expected: 'ELLIPSE' },
{ fn: Line, expected: 'LINE' },
{ fn: Star, expected: 'STAR' },
{ fn: Group, expected: 'GROUP' },
{ fn: Section, expected: 'SECTION' }
] as const
for (const { fn, expected } of types) {
const tree = fn({ name: expected })
const result = await renderTree(g, tree)
expect(g.nodes.get(result.id)!.type).toBe(expected)
}
})
it('throws on unknown element type', () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const tree = { type: 'foobar', props: {}, children: [] }
expect(() => renderTree(g, tree)).toThrow('Unknown element: <foobar>')
})
})
describe('renderTreeNode', () => {
it('renders pre-built tree (browser path)', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const tree = Frame({
name: 'FromAI',
w: 200,
h: 100,
bg: '#3B82F6',
children: [Text({ name: 'Label', size: 16, color: '#FFF', children: 'Button' })]
})
const result = await renderTreeNode(g, tree)
expect(result.name).toBe('FromAI')
const node = g.nodes.get(result.id)!
expect(node.childIds.length).toBe(1)
const label = g.nodes.get(node.childIds[0]!)!
expect(label.text).toBe('Button')
})
})
describe('renderJSX (string → scene graph)', () => {
it('renders JSX string', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const jsx = `
<Frame name="Test" w={200} h={100} bg="#FF0000">
<Text name="Hello" size={16} color="#000">World</Text>
</Frame>
`
const [result] = await renderJSX(g, jsx)
expect(result.name).toBe('Test')
const node = g.nodes.get(result.id)!
expect(node.type).toBe('FRAME')
expect(node.childIds.length).toBe(1)
const text = g.nodes.get(node.childIds[0]!)!
expect(text.text).toBe('World')
})
it('renders nested JSX', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const jsx = `
<Frame name="Card" w={320} flex="col" gap={16} p={24} bg="#FFF" rounded={16}>
<Rectangle name="Image" w={272} h={200} bg="#E5E7EB" rounded={12} />
<Text name="Title" size={18} weight="bold" color="#111">Card Title</Text>
<Text name="Description" size={14} color="#6B7280">Lorem ipsum</Text>
</Frame>
`
const [result] = await renderJSX(g, jsx)
const card = g.nodes.get(result.id)!
expect(card.layoutMode).toBe('VERTICAL')
expect(card.childIds.length).toBe(3)
})
it('renders with position', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const [result] = await renderJSX(g, '<Frame name="At" w={50} h={50} />', { x: 100, y: 200 })
const node = g.nodes.get(result.id)!
expect(node.x).toBe(100)
expect(node.y).toBe(200)
})
})
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
describe('grid layout rendering', () => {
it('creates grid frame with template columns', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
2026-05-03 18:03:40 +00:00
const tree = Frame(
{ name: 'Grid', w: 300, h: 200, grid: true, columns: '1fr 1fr 1fr' },
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
Rectangle({ name: 'A', w: 50, h: 50 }),
Rectangle({ name: 'B', w: 50, h: 50 }),
Rectangle({ name: 'C', w: 50, h: 50 })
)
const result = await renderTree(g, tree)
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
const frame = g.nodes.get(result.id)!
expect(frame.layoutMode).toBe('GRID')
expect(frame.gridTemplateColumns).toEqual([
{ sizing: 'FR', value: 1 },
{ sizing: 'FR', value: 1 },
{ sizing: 'FR', value: 1 }
])
})
it('creates grid frame with mixed track sizes', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
const tree = Frame({ name: 'Grid', w: 400, h: 200, grid: true, columns: '100 1fr 2fr' })
const result = await renderTree(g, tree)
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
const frame = g.nodes.get(result.id)!
expect(frame.gridTemplateColumns).toEqual([
{ sizing: 'FIXED', value: 100 },
{ sizing: 'FR', value: 1 },
{ sizing: 'FR', value: 2 }
])
})
it('creates grid with numeric columns shorthand', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
const tree = Frame({ name: 'Grid', w: 300, h: 200, grid: true, columns: 3 })
const result = await renderTree(g, tree)
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
const frame = g.nodes.get(result.id)!
expect(frame.gridTemplateColumns).toEqual([
{ sizing: 'FR', value: 1 },
{ sizing: 'FR', value: 1 },
{ sizing: 'FR', value: 1 }
])
})
it('sets grid gaps', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
2026-05-03 18:03:40 +00:00
const tree = Frame({
name: 'Grid',
w: 300,
h: 200,
grid: true,
columns: '1fr 1fr',
columnGap: 10,
rowGap: 20
})
const result = await renderTree(g, tree)
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
const frame = g.nodes.get(result.id)!
expect(frame.gridColumnGap).toBe(10)
expect(frame.gridRowGap).toBe(20)
})
it('sets grid gap shorthand', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
const tree = Frame({ name: 'Grid', w: 300, h: 200, grid: true, columns: '1fr 1fr', gap: 16 })
const result = await renderTree(g, tree)
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
const frame = g.nodes.get(result.id)!
expect(frame.gridColumnGap).toBe(16)
expect(frame.gridRowGap).toBe(16)
})
it('applies grid padding', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
const tree = Frame({ name: 'Grid', w: 300, h: 200, grid: true, columns: '1fr 1fr', p: 10 })
const result = await renderTree(g, tree)
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
const frame = g.nodes.get(result.id)!
expect(frame.paddingTop).toBe(10)
expect(frame.paddingRight).toBe(10)
expect(frame.paddingBottom).toBe(10)
expect(frame.paddingLeft).toBe(10)
})
it('sets grid rows', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
2026-05-03 18:03:40 +00:00
const tree = Frame({
name: 'Grid',
w: 300,
h: 200,
grid: true,
columns: '1fr',
rows: '100 1fr'
})
const result = await renderTree(g, tree)
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
const frame = g.nodes.get(result.id)!
expect(frame.gridTemplateRows).toEqual([
{ sizing: 'FIXED', value: 100 },
{ sizing: 'FR', value: 1 }
])
})
it('sets grid child position', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
2026-05-03 18:03:40 +00:00
const tree = Frame(
{ name: 'Grid', w: 300, h: 200, grid: true, columns: '1fr 1fr 1fr', rows: '1fr 1fr' },
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
Rectangle({ name: 'A', w: 50, h: 50, colStart: 2, rowStart: 1 })
)
const result = await renderTree(g, tree)
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
const children = g.getChildren(result.id)
expect(children[0].gridPosition).toEqual({ column: 2, row: 1, columnSpan: 1, rowSpan: 1 })
})
it('sets grid child span', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
2026-05-03 18:03:40 +00:00
const tree = Frame(
{ name: 'Grid', w: 300, h: 200, grid: true, columns: '1fr 1fr 1fr', rows: '1fr 1fr' },
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
Rectangle({ name: 'A', w: 50, h: 50, colStart: 1, colSpan: 2, rowStart: 1, rowSpan: 2 })
)
const result = await renderTree(g, tree)
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
const children = g.getChildren(result.id)
expect(children[0].gridPosition).toEqual({ column: 1, row: 1, columnSpan: 2, rowSpan: 2 })
})
it('grid + computeLayout positions children in cells', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
2026-05-03 18:03:40 +00:00
const tree = Frame(
{ name: 'Grid', w: 300, h: 200, grid: true, columns: '1fr 1fr 1fr', rows: '1fr' },
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
Rectangle({ name: 'A', w: 50, h: 50 }),
Rectangle({ name: 'B', w: 50, h: 50 }),
Rectangle({ name: 'C', w: 50, h: 50 })
)
const result = await renderTree(g, tree)
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
computeLayout(g, result.id)
const children = g.getChildren(result.id)
expect(children[0].x).toBe(0)
expect(children[1].x).toBe(100)
expect(children[2].x).toBe(200)
})
it('grid 2x2 with gap positions correctly', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
2026-05-03 18:03:40 +00:00
const tree = Frame(
{ name: 'Grid', w: 210, h: 210, grid: true, columns: '1fr 1fr', rows: '1fr 1fr', gap: 10 },
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
Rectangle({ name: 'A', w: 30, h: 30 }),
Rectangle({ name: 'B', w: 30, h: 30 }),
Rectangle({ name: 'C', w: 30, h: 30 }),
Rectangle({ name: 'D', w: 30, h: 30 })
)
const result = await renderTree(g, tree)
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
computeLayout(g, result.id)
const children = g.getChildren(result.id)
expect(children[0].x).toBe(0)
expect(children[0].y).toBe(0)
expect(children[1].x).toBe(110)
expect(children[1].y).toBe(0)
expect(children[2].x).toBe(0)
expect(children[2].y).toBe(110)
expect(children[3].x).toBe(110)
expect(children[3].y).toBe(110)
})
it('renders grid from JSX string', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
const jsx = `
<Frame name="Grid" w={300} h={100} grid columns="1fr 1fr" gap={10}>
<Rectangle name="A" w={50} h={50} />
<Rectangle name="B" w={50} h={50} />
</Frame>
`
const [result] = await renderJSX(g, jsx)
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
const frame = g.nodes.get(result.id)!
expect(frame.layoutMode).toBe('GRID')
expect(frame.gridTemplateColumns).toEqual([
{ sizing: 'FR', value: 1 },
{ sizing: 'FR', value: 1 }
])
expect(frame.gridColumnGap).toBe(10)
expect(frame.gridRowGap).toBe(10)
computeLayout(g, result.id)
const children = g.getChildren(result.id)
expect(children[0].x).toBe(0)
expect(children[1].x).toBe(155)
})
it('grid auto-height (no rows) grows to fit content', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
2026-05-03 18:03:40 +00:00
const tree = Frame(
{ name: 'Grid', w: 300, grid: true, columns: '1fr 1fr', gap: 10 },
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
Rectangle({ name: 'A', w: 50, h: 80 }),
Rectangle({ name: 'B', w: 50, h: 80 }),
Rectangle({ name: 'C', w: 50, h: 60 }),
Rectangle({ name: 'D', w: 50, h: 60 })
)
const result = await renderTree(g, tree)
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
const frame = g.nodes.get(result.id)!
expect(frame.gridTemplateRows).toEqual([])
computeLayout(g, result.id)
const updated = g.nodes.get(result.id)!
expect(updated.height).toBe(150)
})
it('grid children with flex stretch to cell width', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
2026-05-03 18:03:40 +00:00
const tree = Frame(
{ name: 'Grid', w: 200, grid: true, columns: '1fr 1fr', gap: 0 },
Frame({
name: 'A',
flex: 'col',
gap: 4,
p: 8,
children: [Rectangle({ name: 'R1', w: 10, h: 20 })]
}),
Frame({
name: 'B',
flex: 'col',
gap: 4,
p: 8,
children: [Rectangle({ name: 'R2', w: 10, h: 20 })]
})
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
)
const result = await renderTree(g, tree)
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
computeAllLayouts(g)
const children = g.getChildren(result.id)
expect(children[0].width).toBe(100)
expect(children[1].width).toBe(100)
expect(children[0].x).toBe(0)
expect(children[1].x).toBe(100)
})
it('grid prop takes precedence over padding-triggered auto-layout', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
2026-05-03 18:03:40 +00:00
const tree = Frame(
{ name: 'Grid', w: 300, grid: true, columns: '1fr 1fr', p: 20 },
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
Rectangle({ name: 'A', w: 50, h: 50 }),
Rectangle({ name: 'B', w: 50, h: 50 })
)
const result = await renderTree(g, tree)
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
const frame = g.nodes.get(result.id)!
expect(frame.layoutMode).toBe('GRID')
})
it('grid w=fill stretches in flex-col parent', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
const jsx = `
<Frame name="P" flex="col" w={400} p={20}>
<Frame name="G" grid columns="1fr 1fr" gap={10} w="fill">
<Rectangle w={10} h={30} />
<Rectangle w={10} h={30} />
</Frame>
</Frame>
`
const [result] = await renderJSX(g, jsx)
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
computeAllLayouts(g)
2026-05-03 18:03:40 +00:00
const grid = g.getChildren(result.id).find((c) => c.name === 'G')!
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
expect(grid.width).toBe(360)
expect(grid.layoutMode).toBe('GRID')
})
it('grid grow=1 fills remaining space in flex-row', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
const jsx = `
<Frame name="P" flex="row" w={500} p={20} gap={10}>
<Rectangle w={100} h={50} />
<Frame name="G" grid columns="1fr 1fr" gap={10} grow={1}>
<Rectangle w={10} h={30} />
<Rectangle w={10} h={30} />
</Frame>
</Frame>
`
const [result] = await renderJSX(g, jsx)
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
computeAllLayouts(g)
2026-05-03 18:03:40 +00:00
const grid = g.getChildren(result.id).find((c) => c.name === 'G')!
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
expect(grid.width).toBe(350)
})
it('nested flex > flex > grid: grid stretches to correct width', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
const jsx = `
<Frame name="Card" flex="col" w={780}>
<Frame name="Content" flex="col" w="fill" p={28}>
<Frame name="G" grid columns="1fr 1fr 1fr" w="fill" columnGap={16}>
<Rectangle w={10} h={30} />
<Rectangle w={10} h={30} />
<Rectangle w={10} h={30} />
</Frame>
</Frame>
</Frame>
`
const [result] = await renderJSX(g, jsx)
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
computeAllLayouts(g)
2026-05-03 18:03:40 +00:00
const content = g.getChildren(result.id).find((c) => c.name === 'Content')!
const grid = g.getChildren(content.id).find((c) => c.name === 'G')!
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
expect(content.width).toBe(780)
expect(grid.width).toBe(724)
})
it('grid h=fill grows in flex-col parent', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
const jsx = `
<Frame name="P" flex="col" w={400} h={600} p={20}>
<Rectangle w={360} h={100} />
<Frame name="G" grid columns="1fr 1fr" gap={10} h="fill">
<Rectangle w={10} h={30} />
<Rectangle w={10} h={30} />
</Frame>
</Frame>
`
const [result] = await renderJSX(g, jsx)
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
computeAllLayouts(g)
2026-05-03 18:03:40 +00:00
const grid = g.getChildren(result.id).find((c) => c.name === 'G')!
Fix auto-layout overflow, grid layout, AI chat UX (#86) * Fix auto-layout overflow: MeasureFunc, min/max, absolute positioning, text wrap Layout engine (layout.ts): - Use Yoga MeasureFunc for text nodes instead of static pre-measurement, so text wraps correctly when width is determined by flex layout - Add min/max width/height constraint support (minWidth, maxWidth, etc.) - Translate counterAxisAlignContent to Yoga setAlignContent for wrap layouts - Extract configureFlexContainer to share between root and nested frames JSX renderer (render/renderer.ts): - Auto-set layoutPositioning ABSOLUTE for elements with x/y inside auto-layout - Fix text auto-resize: set HEIGHT when text fills parent in auto-layout Text measurer (renderer/renderer.ts): - Accept optional maxWidth parameter for constraint-based measurement * AI prompt: prefer describe over export_image for post-render verification * Strip TS casts from AI-generated JSX before sucrase parse AI models sometimes emit `as any`, `as const` etc. in JSX props. Sucrase with jsx-only transform can't handle these, causing parse errors. - Strip TypeScript cast expressions before passing to sucrase - Add forbidden patterns to AI prompt: as any, template literals for sizes, Math.random() * Cache text MeasureFunc results to avoid repeated buildParagraph calls Yoga calls MeasureFunc multiple times per node during calculateLayout. Each call was creating a full CanvasKit Paragraph — expensive for layouts with many text nodes. Cache by rounded constraint width. * AI chat: fix provider settings popover, add max output tokens, fix paste in chat input - Fix ProviderSettings popover not visible (remove tooltip/popover trigger conflict, add collision-padding, isolate z-[51]) - Add configurable max output tokens (default 16384) in provider settings - Pass maxOutputTokens to ToolLoopAgent to prevent truncated tool calls - Add system prompt size limits: split render calls at ~40 elements - Fix paste/copy/cut in chat input (stop event propagation to canvas handler) * Fix 6 layout engine bugs: hidden size, FILL basis, SPACE_EVENLY, alignSelf range, grid stretch, absolute children Layout engine (layout.ts): - Guard applyYogaLayout to preserve hidden children dimensions - Add setFlexBasis(0) for FILL sizing so children share space from zero - Add SPACE_EVENLY to mapJustify via Justify.SpaceEvenly - Replace hardcoded STRETCH checks with mapAlignSelf for full range - Use setWidthStretch/setHeightStretch for grid children instead of flexGrow - Insert absolute children in Yoga tree via configureAbsoluteChild with PositionType.Absolute, keeping manual x/y (no write-back) Types (scene-graph.ts): - Add SPACE_EVENLY to LayoutAlign union - New LayoutAlignSelf type: AUTO | MIN | CENTER | MAX | STRETCH | BASELINE Import (kiwi-convert.ts): - Map SPACE_EVENLY correctly instead of collapsing to SPACE_BETWEEN - New mapAlignSelf function for full StackCounterAlign range Tools (modify.ts): - Expand set_layout align enum with SPACE_EVENLY - Expand set_layout_child align_self enum with MIN/CENTER/MAX/BASELINE Tests: 86 pass (+13 new covering all 6 fixes) * Grid layout support in JSX renderer, auto-height grids, flex children stretch in cells Renderer: - Parse grid/columns/rows/columnGap/rowGap/gap props - Parse grid child positioning: colStart/col/rowStart/row/colSpan/rowSpan - Grid prop takes precedence over padding-triggered auto-layout - SPACE_EVENLY added to ALIGN_MAP - Numeric columns shorthand (columns={3} → 3×1fr) - Auto-height: grid without rows sets height=0 for Yoga auto-sizing - fill sizing in grid children → layoutAlignSelf: STRETCH - Component builders accept variadic children: Frame(props, ...children) Layout: - Grid auto-height: skip setHeight when no gridTemplateRows - Write back computed height for auto-height grids - Grid children with layoutMode stretch width to fill cell - recomputeGridChild: re-run flex layout after grid assigns cell size (temporarily sets sizing to FIXED so HUG doesn't override grid width) Export: - Skip height export for auto-height grids (no rows template) Tests: 18 new grid render tests covering all paths * Auto-enable flex for justify/items props, discourage export_image in AI prompt * Address review: use sucrase typescript transform, don't reset chat on maxOutputTokens change * Fix lint errors: extract applyFrameSize, wrap nested ternary, remove unnecessary cast * Remove SPACE_EVENLY — not a valid Figma layout value * CI: debug LFS pull from R2 * Apply maxOutputTokens dynamically via prepareCall instead of at agent creation * Fix heavy .fig parse: restore GUID/defID guards, fix optional types Commit f3eac5a removed null guards from fig-import and instance-overrides as 'unnecessary conditions', but Kiwi-decoded data can have NodeChanges without GUIDs and ComponentPropAssignments/Refs without defIDs. Made the types optional to match reality. Also fix CI LFS: add git lfs install --force before pull (R2 endpoint needs the filter registered first). * Fix Google AI model IDs: gemini-3.1-pro → gemini-3.1-pro-preview Closes #91 --------- Co-authored-by: Danila Poyarkov <dev@dannote.net>
2026-03-10 12:43:04 +00:00
expect(grid.height).toBe(460)
})
})
describe('text props round-trip', () => {
it('lineHeight renders and exports', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const [result] = await renderJSX(g, '<Text color="#000" lineHeight={24}>Hello</Text>')
const n = g.getNode(result.id)!
expect(n.lineHeight).toBe(24)
const jsx = sceneNodeToJSX(n.id, g)
expect(jsx).toContain('lineHeight={24}')
})
it('letterSpacing renders and exports', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const [result] = await renderJSX(g, '<Text color="#000" letterSpacing={2}>Spaced</Text>')
const n = g.getNode(result.id)!
expect(n.letterSpacing).toBe(2)
const jsx = sceneNodeToJSX(n.id, g)
expect(jsx).toContain('letterSpacing={2}')
})
it('textDecoration renders and exports', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const [result] = await renderJSX(g, '<Text color="#000" textDecoration="underline">Link</Text>')
const n = g.getNode(result.id)!
expect(n.textDecoration).toBe('UNDERLINE')
const jsx = sceneNodeToJSX(n.id, g)
expect(jsx).toContain('textDecoration="underline"')
})
it('textCase renders and exports', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const [result] = await renderJSX(g, '<Text color="#000" textCase="upper">label</Text>')
const n = g.getNode(result.id)!
expect(n.textCase).toBe('UPPER')
const jsx = sceneNodeToJSX(n.id, g)
expect(jsx).toContain('textCase="upper"')
})
it('maxLines renders with truncation', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const [result] = await renderJSX(g, '<Text color="#000" maxLines={2}>Long text here</Text>')
const n = g.getNode(result.id)!
expect(n.maxLines).toBe(2)
expect(n.textTruncation).toBe('ENDING')
const jsx = sceneNodeToJSX(n.id, g)
expect(jsx).toContain('maxLines={2}')
})
it('truncate without maxLines', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const [result] = await renderJSX(g, '<Text color="#000" truncate>Overflow</Text>')
const n = g.getNode(result.id)!
expect(n.textTruncation).toBe('ENDING')
const jsx = sceneNodeToJSX(n.id, g)
expect(jsx).toContain('truncate')
})
it('defaults omit text props', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
const [result] = await renderJSX(g, '<Text color="#000">Plain</Text>')
const n = g.getNode(result.id)!
expect(n.lineHeight).toBeNull()
expect(n.letterSpacing).toBe(0)
expect(n.textDecoration).toBe('NONE')
expect(n.textCase).toBe('ORIGINAL')
expect(n.maxLines).toBeNull()
const jsx = sceneNodeToJSX(n.id, g)
expect(jsx).not.toContain('lineHeight')
expect(jsx).not.toContain('letterSpacing')
expect(jsx).not.toContain('textDecoration')
expect(jsx).not.toContain('textCase')
expect(jsx).not.toContain('maxLines')
expect(jsx).not.toContain('truncate')
})
it('text w="fill" in flex="col" exports as w="fill" not w={computed}', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
2026-05-03 18:03:40 +00:00
const [result] = await renderJSX(
g,
`
<Frame name="Card" flex="col" w={300} p={20}>
<Text name="Title" size={22} weight="bold" color="#111" w="fill">Hello World</Text>
</Frame>
2026-05-03 18:03:40 +00:00
`
)
const card = g.getNode(result.id)!
const title = g.getNode(card.childIds[0]!)!
expect(title.layoutAlignSelf).toBe('STRETCH')
expect(title.textAutoResize).toBe('HEIGHT')
const jsx = sceneNodeToJSX(title.id, g)
expect(jsx).toContain('w="fill"')
expect(jsx).not.toMatch(/w=\{/)
})
it('text grow={1} in flex="row" exports as grow not w={computed}', async () => {
Refactor architecture boundaries across core, app, and packages (#234) * refactor(core): decompose editor factory and action modules Split the monolithic editor factory and large action modules into focused domain helpers: - create.ts assembles context through bridge modules (clipboard, components, structure, undo) and delegates to graph-reads, graph-events, layout-runner, component-sync, and state factory - structure.ts delegates to group, container-wrap, auto-layout-wrap, reorder, and state-toggle helpers - selection.ts delegates to hit-test, overlays, container navigation, and read helpers - clipboard.ts delegates to subtree-history, images, export, copy, fonts, and placement helpers - shapes.ts delegates to pen actions and section-adopt - components.ts delegates to focus and instances helpers - alignment.ts delegates to flip-rotate helper - text.ts uses explicit TextEditSession for snapshot comparison New focused modules: nudge, variable-bindings, layout-mode, page-viewports, tool-registry, color-space Undo: history/position and history/snapshot helpers, hardened batch/rollback with nested batch support and configurable limit * refactor(core): split tool definitions by domain Split the monolithic tool registry into domain-specific modules: - read/ — selection, find, pages, fonts, components, nodes, query, jsx - create/ — basic shapes, components, vector, JSX render - modify/ — paint, effects, geometry, layout, state, text, update - structure/ — basic, arrange, batch, hierarchy, replace, tree - variables/ — bindings, collections, read, values - vector/ — boolean, path, export, viewport - analyze/ — colors, typography, spacing, clusters, diff, eval - describe/ — summaries, tree, roles, layout-issues - stock-photo/ — providers, requests, apply - codegen/ — component-map, tokens Split registry into core/extended tiers; refine schema and AI adapter * refactor(core): restructure kiwi codec and instance overrides Reorganize the Kiwi .fig codec into domain subdirectories: - binary/ — codec, schema, protocol - fig/ — file, import, parse (core, worker, transfer) - node-change/ — convert, export-node, serialize, plugin-data - instance-overrides/ — constraints, dsd, populate, props, resolve, symbol-overrides, symbol-props, sync, types Vendored kiwi-schema/ left isolated * refactor(core): split profiler, icons, IO, and add subpath exports Profiler: speedscope-export, capture-session, hud-controller Icons: api, svg, types, render, create-icons tool IO: format registry and subpath exports Canvas/color/text/vector: targeted cleanup Add deliberate subpath exports: random, xpath, vector, color, canvas, scene-graph, kiwi, design-jsx, io, tools, editor, layout, canvaskit, profiler, text, lint, rpc, figma-api, constants * refactor(vue): decompose canvas input, surface lifecycle, and controls Canvas surface: gl-surface, kit-loader, render-loop, resize-observer Canvas input handlers: - move: drop-target, move-snap, duplicate-drag - select: select-move, select-hover, select-hit - resize: resize-rect, resize-vector, resize-start - transform: rotation, marquee, pan, text-selection - text-edit: navigation, clipboard, textarea lifecycle - Shared: click-count, space-key, pan, pan-zoom, draw, raf-scheduler Editor composition: - commands split: actions, context, metadata, edit, selection, view - menu-model split: command-groups, builders, types - Gradient stop composable reuse in primitive root Controls: fill, layout, typography, appearance, effects, stroke, okhcl, prop-scrub, node-props, undo-batch, color-variable-binding Variables/i18n/document/export helpers Organize canvas, primitives, controls, editor, and variables into cohesive module directories with package-local import aliases Expose MenuActionNode/MenuSeparatorNode from public API * refactor(app): split document IO, editor session, and automation bridge Document IO: source-state, naming, writer, reload-source, reload-state, imported-document, watch-targets, save-targets Editor session: create, modules, types, accessors, computed, refs Editor canvas: loader-overlay, collaboration-awareness, context-selection, menu-actions, menu-model Automation bridge: eval, tools, exports, files, selection, RPC fallback AI/ACP: transport, map-update, permission, debug, chat effects/storage Collab: awareness, graph-bindings, yjs-sync, follow, session, types Shell keyboard: actions, bindings, clipboard, focus, nudging, raw-events, registry, reserved, shortcuts, space-tool Shell menu: app-menu, document-name, entry, files Demo: colors, effects, helpers, section builders (components, app-preview, effects, standalone, variables) — document.ts reduced from 981 to 32 lines as pure orchestrator Move app modules under src/app/ with organized domain structure: editor, document, ai, collab, shell, automation, demo, tabs * refactor(app): decompose UI components with provide/inject context Split monolithic components using Reka UI-inspired namespace folders with scoped provide/inject context — no prop drilling: - CollabPanel/ — context, avatars, share, connected, join - ColorPickerPanel/ — context, area, format, field groups, sliders - MobileHud/ — context, action toast, tool badge, file menu, presence - ProviderSettings/ — context, API key/type, endpoint, tokens, photos - Toolbar/ — actions, types, desktop, mobile, tool button, flyout - LayoutSection/ — types, auto-layout, flex, grid, padding, size, clip Properties helpers: fill-okhcl adapter, fill-label, color-style-row Menu: entry helpers, document-name rename, stale type removal * refactor(mcp): split server into focused modules - browser-rpc — WebSocket client management - mcp-sessions — session lifecycle - tool-output — response formatting - tool-schema — Zod schema generation from ToolDefs - jsx-preprocess — JSX source transformation - result — result helpers - tool-registration — MCP tool wiring - auth — API key validation - http-options — CORS/request handling - stdio-bridge — stdio transport adapter * refactor(cli): split analyze subcommands and shared helpers - Analyze subcommands: clusters, colors, spacing, typography - RPC data loading helper - Migrate imports to targeted core subpath exports * refactor(docs): split VitePress config and shared table component Config helpers: sdk-sidebar, seo, labels, sidebars, locale-theme, root-theme, locales Shared SdkDataTable component replaces duplicated table markup in SdkPropsTable, SdkEventsTable, and SdkSlotsTable Update contributing and testing docs * refactor(tauri): decompose desktop entrypoint Split lib.rs into focused service modules: - fig_container.rs — .fig archive/compression commands - fonts.rs — font cache and system font enumeration - menu.rs — native menu construction - menu_events.rs — menu event dispatch and devtools toggle - window.rs — main window show/focus lifecycle * test: share domain test factories and migrate fixtures New shared helpers: - tests/helpers/scene.ts — makeSceneGraph factory - tests/helpers/vector-network.ts — vertex/segment/network builders - tests/helpers/fig-traversal.ts — all-node collection, type counts - tests/helpers/undo.ts — undo test utilities - tests/helpers/editor-history.ts — editor history test helpers Migrate render, vector, fig-roundtrip, and undo tests to use shared factories instead of inline fixture construction * build: add structural lint rules, split vite config, update docs Structural lint (oxlint.structure.json + lint/plugin.js): - 20+ custom rules enforcing package boundaries, lifecycle patterns, naming conventions, and import discipline Vite config split: raw-markdown, canvaskit-assets, pwa, server, aliases, automation plugins Remove legacy shims and utils superseded by SDK/core modules Update AGENTS.md, CONTRIBUTING.md, eval-command docs, tsconfig * fix(vue): normalize canvas directory casing and remove duplicate export - Rename Canvas/ to canvas/ in git index to match #vue/canvas/* imports (PascalCase was correct for component primitives but canvas/ is a non-component domain directory) - Remove duplicate ./random subpath export in core package.json * fix: add #vue and #core Vite resolve aliases for dev server * refactor(core): reduce remaining large modules Split the remaining large core hotspots into cohesive domain modules while preserving public facades and behavior. - Extract scene graph types, variables, node defaults, and vector-network helpers - Decompose canvas renderer orchestration, state, paints, colors, lifecycle, labels, and delegated domain methods into renderer/ and labels/ subfolders - Split Kiwi node-change, binary variable binding, layout, RPC, vector, JSX export, clipboard, design JSX, and Figma proxy helpers - Replace collision-driven *Fn import aliases with namespace imports and enforce the pattern in lint Validation: - bun run check - bun --filter @open-pencil/vue build - bun run test:dupes * fix(app): forward color input attrs * fix(app): cover section drawing errors * fix(editor): undo option-drag duplicates * docs: document domain subfolder convention * fix(app): handle undo redo on keydown * refactor(app): dispatch shortcuts from keydown * refactor: group prefixed domain modules * refactor(app): use tinykeys for shortcuts * refactor(core): group symbol override modules * refactor(core): group fig kiwi container helper * refactor(canvas): split overlay rendering modules * refactor(vue): remove unused internal barrels * fix(app): lay out demo components before instancing * fix(app): restore demo badge spacing * perf(canvas): split scene and overlay rendering * refactor(vue): wrap wheel gesture lifecycle * fix(canvas): wait for fonts before hiding loader * docs: update unreleased changelog
2026-04-30 12:14:19 +00:00
const g = makeSceneGraph()
2026-05-03 18:03:40 +00:00
const [result] = await renderJSX(
g,
`
<Frame name="Row" flex="row" w={300}>
<Text name="Label" color="#999" w={60}>Label</Text>
<Text name="Value" color="#111" w="fill">Some value text</Text>
</Frame>
2026-05-03 18:03:40 +00:00
`
)
const row = g.getNode(result.id)!
const value = g.getNode(row.childIds[1]!)!
expect(value.layoutGrow).toBe(1)
const jsx = sceneNodeToJSX(value.id, g)
expect(jsx).toContain('grow={1}')
expect(jsx).not.toMatch(/\bw=\{\d+\}/)
})
})