Skip to content

AI-native design editor. Open-source Figma alternative.

Extract createEditor() to packages/core/src/editor/ folder

Danila Poyarkov99d27035831f
diff --git a/packages/core/package.json b/packages/core/package.json
index f2557c639..4f74a0dbc 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -69,6 +69,11 @@
"types": "./src/profiler/index.ts",
"bun": "./src/profiler/index.ts",
"default": "./src/profiler/index.ts"
+ },
+ "./editor": {
+ "types": "./src/editor/index.ts",
+ "bun": "./src/editor/index.ts",
+ "default": "./src/editor/index.ts"
}
},
"main": "./src/index.ts",
@@ -151,6 +156,11 @@
"types": "./dist/profiler/index.d.ts",
"import": "./dist/profiler/index.js",
"default": "./dist/profiler/index.js"
+ },
+ "./editor": {
+ "types": "./dist/editor/index.d.ts",
+ "import": "./dist/editor/index.js",
+ "default": "./dist/editor/index.js"
}
},
"main": "./dist/index.js",
diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.ts
index 7497cdd37..37bdd4eeb 100644
--- a/packages/core/src/constants.ts
+++ b/packages/core/src/constants.ts
@@ -1,4 +1,5 @@
import type { Color } from './types'
+import type { Fill, Stroke } from './scene-graph'
export const IS_BROWSER = typeof window !== 'undefined'
export const IS_TAURI = IS_BROWSER && '__TAURI_INTERNALS__' in window
@@ -282,3 +283,36 @@ export const CJK_FALLBACK_FAMILIES_LINUX = [
export const CJK_GOOGLE_FONT = 'Noto Sans SC'
+
+export const DEFAULT_SHAPE_FILL: Fill = {
+ type: 'SOLID',
+ color: { r: 0.83, g: 0.83, b: 0.83, a: 1 },
+ opacity: 1,
+ visible: true
+}
+
+export const DEFAULT_FRAME_FILL: Fill = {
+ type: 'SOLID',
+ color: { r: 1, g: 1, b: 1, a: 1 },
+ opacity: 1,
+ visible: true
+}
+
+export const SECTION_DEFAULT_FILL: Fill = {
+ type: 'SOLID',
+ color: { r: 0.37, g: 0.37, b: 0.37, a: 1 },
+ opacity: 1,
+ visible: true
+}
+
+export const SECTION_DEFAULT_STROKE: Stroke = {
+ color: { r: 0.55, g: 0.55, b: 0.55, a: 1 },
+ weight: 1,
+ opacity: 1,
+ visible: true,
+ align: 'INSIDE'
+}
+
+export const ZOOM_DIVISOR = 50
+export const ZOOM_SCALE_MIN = 0.75
+export const ZOOM_SCALE_MAX = 1.25
diff --git a/packages/core/src/editor/clipboard.ts b/packages/core/src/editor/clipboard.ts
new file mode 100644
index 000000000..68c195a1f
--- /dev/null
+++ b/packages/core/src/editor/clipboard.ts
@@ -0,0 +1,209 @@
+import { computeAllLayouts } from '../layout'
+import {
+ buildFigmaClipboardHTML,
+ importClipboardNodes,
+ parseFigmaClipboard
+} from '../clipboard'
+import { collectFontKeys } from '../fonts'
+import { computeImageHash } from '../figma-api'
+
+import type { SceneGraph, SceneNode } from '../scene-graph'
+import type { Vector } from '../types'
+import type { EditorContext } from './types'
+
+export function createClipboardActions(ctx: EditorContext) {
+ function collectSubtrees(g: SceneGraph, rootIds: string[]): SceneNode[] {
+ const result: SceneNode[] = []
+ function walk(id: string) {
+ const node = g.getNode(id)
+ if (!node) return
+ result.push({ ...node })
+ for (const childId of node.childIds) walk(childId)
+ }
+ for (const id of rootIds) walk(id)
+ return result
+ }
+
+ function centerNodesAt(nodeIds: string[], cx: number, cy: number) {
+ let minX = Infinity
+ let minY = Infinity
+ let maxX = -Infinity
+ let maxY = -Infinity
+ for (const id of nodeIds) {
+ const n = ctx.graph.getNode(id)
+ if (!n) continue
+ minX = Math.min(minX, n.x)
+ minY = Math.min(minY, n.y)
+ maxX = Math.max(maxX, n.x + n.width)
+ maxY = Math.max(maxY, n.y + n.height)
+ }
+ if (minX === Infinity) return
+ const dx = cx - (minX + maxX) / 2
+ const dy = cy - (minY + maxY) / 2
+ for (const id of nodeIds) {
+ const n = ctx.graph.getNode(id)
+ if (n) ctx.graph.updateNode(id, { x: n.x + dx, y: n.y + dy })
+ }
+ }
+
+ async function loadFontsForNodes(nodeIds: string[]) {
+ const toLoad = collectFontKeys(ctx.graph, nodeIds)
+ if (toLoad.length === 0) return []
+
+ const results = await Promise.all(toLoad.map(([family, style]) => ctx.loadFont(family, style)))
+ const failed = toLoad.filter((_, i) => results[i] === null)
+ computeAllLayouts(ctx.graph, ctx.state.currentPageId)
+ return failed
+ }
+
+ function duplicateSelected(selectedNodes: SceneNode[]) {
+ const prevSelection = new Set(ctx.state.selectedIds)
+ const newIds: string[] = []
+ const snapshots: Array<{ id: string; parentId: string; snapshot: SceneNode }> = []
+
+ for (const node of selectedNodes) {
+ const parentId = node.parentId ?? ctx.state.currentPageId
+ const { id: _srcId, parentId: _srcParent, childIds: _srcChildren, ...srcRest } = node
+ const created = ctx.graph.createNode(node.type, parentId, {
+ ...srcRest,
+ name: node.name + ' copy',
+ x: node.x + 20,
+ y: node.y + 20
+ })
+ newIds.push(created.id)
+ snapshots.push({ id: created.id, parentId, snapshot: { ...created } })
+ }
+
+ if (newIds.length > 0) {
+ ctx.state.selectedIds = new Set(newIds)
+ ctx.undo.push({
+ label: 'Duplicate',
+ forward: () => {
+ for (const { snapshot, parentId } of snapshots) {
+ ctx.graph.createNode(snapshot.type, parentId, snapshot)
+ }
+ ctx.state.selectedIds = new Set(newIds)
+ },
+ inverse: () => {
+ for (const { id } of snapshots) ctx.graph.deleteNode(id)
+ ctx.state.selectedIds = prevSelection
+ }
+ })
+ }
+ }
+
+ function writeCopyData(clipboardData: DataTransfer, selectedNodes: SceneNode[]) {
+ if (selectedNodes.length === 0) return
+
+ const names = selectedNodes.map((n) => n.name).join('\n')
+ const html = buildFigmaClipboardHTML(selectedNodes, ctx.graph)
+ if (html) clipboardData.setData('text/html', html)
+ clipboardData.setData('text/plain', names)
+ }
+
+ function pasteFromHTML(html: string, cursorPos?: Vector) {
+ void parseFigmaClipboard(html).then((figma) => {
+ if (figma) {
+ const prevSelection = new Set(ctx.state.selectedIds)
+ const created = importClipboardNodes(
+ figma.nodes,
+ ctx.graph,
+ ctx.state.currentPageId,
+ 0,
+ 0,
+ figma.blobs
+ )
+ if (created.length > 0) {
+ const { width: viewW, height: viewH } = ctx.getViewportSize()
+ const cx = cursorPos?.x ?? (-ctx.state.panX + viewW / 2) / ctx.state.zoom
+ const cy = cursorPos?.y ?? (-ctx.state.panY + viewH / 2) / ctx.state.zoom
+ centerNodesAt(created, cx, cy)
+ computeAllLayouts(ctx.graph, ctx.state.currentPageId)
+ ctx.state.selectedIds = new Set(created)
+
+ const allNodes = collectSubtrees(ctx.graph, created)
+ const pageId = ctx.state.currentPageId
+ ctx.undo.push({
+ label: 'Paste',
+ forward: () => {
+ for (const snapshot of allNodes) {
+ ctx.graph.createNode(snapshot.type, snapshot.parentId ?? pageId, {
+ ...snapshot,
+ childIds: []
+ })
+ }
+ computeAllLayouts(ctx.graph, pageId)
+ ctx.state.selectedIds = new Set(created)
+ },
+ inverse: () => {
+ for (const id of [...created].reverse()) ctx.graph.deleteNode(id)
+ computeAllLayouts(ctx.graph, pageId)
+ ctx.state.selectedIds = prevSelection
+ }
+ })
+ void loadFontsForNodes(created)
+ warnMissingImages(created)
+ }
+ }
+ })
+ }
+
+ function warnMissingImages(nodeIds: string[]) {
+ const allNodes = collectSubtrees(ctx.graph, nodeIds)
+ return allNodes.some((n) =>
+ n.fills.some((f) => f.type === 'IMAGE' && f.imageHash && !ctx.graph.images.has(f.imageHash))
+ )
+ }
+
+ function deleteSelected() {
+ const entries: Array<{ id: string; parentId: string; snapshot: SceneNode; index: number }> = []
+ for (const id of ctx.state.selectedIds) {
+ const node = ctx.graph.getNode(id)
+ if (!node || node.locked) continue
+ const parentId = node.parentId ?? ctx.state.currentPageId
+ const parent = ctx.graph.getNode(parentId)
+ const index = parent?.childIds.indexOf(id) ?? -1
+ entries.push({ id, parentId, snapshot: { ...node }, index })
+ }
+ if (entries.length === 0) return
+
+ const prevSelection = new Set(ctx.state.selectedIds)
+ for (const { id } of entries) ctx.graph.deleteNode(id)
+
+ ctx.undo.push({
+ label: 'Delete',
+ forward: () => {
+ for (const { id } of entries) ctx.graph.deleteNode(id)
+ ctx.state.selectedIds = new Set()
+ },
+ inverse: () => {
+ for (const { snapshot, parentId, index } of [...entries].reverse()) {
+ ctx.graph.createNode(snapshot.type, parentId, snapshot)
+ if (index >= 0) {
+ ctx.graph.reorderChild(snapshot.id, parentId, index)
+ }
+ }
+ ctx.state.selectedIds = prevSelection
+ }
+ })
+ ctx.state.selectedIds = new Set()
+ }
+
+ function storeImage(bytes: Uint8Array): string {
+ const hash = computeImageHash(bytes)
+ ctx.graph.images.set(hash, bytes)
+ return hash
+ }
+
+ return {
+ collectSubtrees,
+ centerNodesAt,
+ loadFontsForNodes,
+ duplicateSelected,
+ writeCopyData,
+ pasteFromHTML,
+ warnMissingImages,
+ deleteSelected,
+ storeImage
+ }
+}
diff --git a/packages/core/src/editor/components.ts b/packages/core/src/editor/components.ts
new file mode 100644
index 000000000..296f863b3
--- /dev/null
+++ b/packages/core/src/editor/components.ts
@@ -0,0 +1,141 @@
+import type { SceneNode } from '../scene-graph'
+import type { EditorContext } from './types'
+
+export function createComponentActions(ctx: EditorContext) {
+ function createComponentFromSelection(
+ selectedNodes: SceneNode[],
+ wrapSelectionInContainer: (
+ type: 'GROUP' | 'FRAME' | 'COMPONENT' | 'COMPONENT_SET',
+ nodes: SceneNode[],
+ extra?: Partial<SceneNode>
+ ) => string | null
+ ) {
+ if (selectedNodes.length === 0) return
+
+ const prevSelection = new Set(ctx.state.selectedIds)
+
+ if (selectedNodes.length === 1) {
+ const node = selectedNodes[0]
+ const prevType = node.type
+
+ if (node.type === 'COMPONENT') return
+
+ if (node.type === 'FRAME' || node.type === 'GROUP') {
+ ctx.graph.updateNode(node.id, { type: 'COMPONENT' })
+ ctx.state.selectedIds = new Set([node.id])
+ ctx.undo.push({
+ label: 'Create component',
+ forward: () => {
+ ctx.graph.updateNode(node.id, { type: 'COMPONENT' })
+ ctx.state.selectedIds = new Set([node.id])
+ },
+ inverse: () => {
+ ctx.graph.updateNode(node.id, { type: prevType })
+ ctx.state.selectedIds = prevSelection
+ }
+ })
+ return
+ }
+ }
+
+ wrapSelectionInContainer('COMPONENT', selectedNodes)
+ }
+
+ function createComponentSetFromComponents(
+ selectedNodes: SceneNode[],
+ wrapSelectionInContainer: (
+ type: 'GROUP' | 'FRAME' | 'COMPONENT' | 'COMPONENT_SET',
+ nodes: SceneNode[],
+ extra?: Partial<SceneNode>
+ ) => string | null
+ ) {
+ if (selectedNodes.length < 2) return
+ if (!selectedNodes.every((n) => n.type === 'COMPONENT')) return
+ wrapSelectionInContainer('COMPONENT_SET', selectedNodes)
+ }
+
+ function createInstanceFromComponent(componentId: string, x?: number, y?: number) {
+ const component = ctx.graph.getNode(componentId)
+ if (component?.type !== 'COMPONENT') return null
+
+ const parentId = component.parentId ?? ctx.state.currentPageId
+ const instance = ctx.graph.createInstance(componentId, parentId, {
+ x: x ?? component.x + component.width + 40,
+ y: y ?? component.y
+ })
+ if (!instance) return null
+
+ const instanceId = instance.id
+ ctx.state.selectedIds = new Set([instanceId])
+
+ ctx.undo.push({
+ label: 'Create instance',
+ forward: () => {
+ ctx.graph.createInstance(componentId, parentId, { ...instance })
+ ctx.state.selectedIds = new Set([instanceId])
+ },
+ inverse: () => {
+ ctx.graph.deleteNode(instanceId)
+ ctx.state.selectedIds = new Set([componentId])
+ }
+ })
+ return instanceId
+ }
+
+ function detachInstance(selectedNode: SceneNode | undefined) {
+ if (selectedNode?.type !== 'INSTANCE') return
+
+ const prevComponentId = selectedNode.componentId
+
+ ctx.graph.detachInstance(selectedNode.id)
+ ctx.state.selectedIds = new Set([selectedNode.id])
+
+ ctx.undo.push({
+ label: 'Detach instance',
+ forward: () => {
+ ctx.graph.detachInstance(selectedNode.id)
+ ctx.requestRender()
+ },
+ inverse: () => {
+ ctx.graph.updateNode(selectedNode.id, {
+ type: 'INSTANCE',
+ componentId: prevComponentId,
+ overrides: {}
+ })
+ }
+ })
+ }
+
+ function goToMainComponent(
+ selectedNode: SceneNode | undefined,
+ switchPage: (pageId: string) => Promise<void>
+ ) {
+ if (!selectedNode?.componentId) return
+ const main = ctx.graph.getMainComponent(selectedNode.id)
+ if (!main) return
+
+ let current: SceneNode | undefined = main
+ while (current && current.type !== 'CANVAS') {
+ current = current.parentId ? ctx.graph.getNode(current.parentId) : undefined
+ }
+ if (current && current.id !== ctx.state.currentPageId) {
+ void switchPage(current.id)
+ }
+
+ ctx.state.selectedIds = new Set([main.id])
+
+ const abs = ctx.graph.getAbsolutePosition(main.id)
+ const { width: viewW, height: viewH } = ctx.getViewportSize()
+ ctx.state.panX = viewW / 2 - (abs.x + main.width / 2) * ctx.state.zoom
+ ctx.state.panY = viewH / 2 - (abs.y + main.height / 2) * ctx.state.zoom
+ ctx.requestRender()
+ }
+
+ return {
+ createComponentFromSelection,
+ createComponentSetFromComponents,
+ createInstanceFromComponent,
+ detachInstance,
+ goToMainComponent
+ }
+}
diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.ts
new file mode 100644
index 000000000..56ce97173
--- /dev/null
+++ b/packages/core/src/editor/create.ts
@@ -0,0 +1,270 @@
+import { CANVAS_BG_COLOR, IS_BROWSER } from '../constants'
+import { computeLayout, setTextMeasurer } from '../layout'
+import { loadFont as defaultLoadFont } from '../fonts'
+import { prefetchFigmaSchema } from '../clipboard'
+import { SceneGraph } from '../scene-graph'
+import { TextEditor } from '../text-editor'
+import { UndoManager } from '../undo'
+
+import { createClipboardActions } from './clipboard'
+import { createComponentActions } from './components'
+import { createNodeActions } from './nodes'
+import { createPageActions } from './pages'
+import { createSelectionActions } from './selection'
+import { createShapeActions } from './shapes'
+import { createStructureActions } from './structure'
+import { createTextActions } from './text'
+import { createUndoActions } from './undo'
+import { createViewportActions } from './viewport'
+
+import type { SceneNode } from '../scene-graph'
+import type { SkiaRenderer } from '../renderer/renderer'
+import type { CanvasKit } from 'canvaskit-wasm'
+import type { EditorContext, EditorOptions, EditorState } from './types'
+
+export function createEditor(options?: EditorOptions) {
+ let _graph = options?.graph ?? new SceneGraph()
+ const undo = new UndoManager()
+ const _loadFont = options?.loadFont ?? defaultLoadFont
+ const _getViewportSize = options?.getViewportSize ?? (() => {
+ if (IS_BROWSER) return { width: window.innerWidth, height: window.innerHeight }
+ return { width: 800, height: 600 }
+ })
+ let _ck: CanvasKit | null = null
+ let _renderer: SkiaRenderer | null = null
+ let _textEditor: TextEditor | null = null
+
+ void prefetchFigmaSchema()
+
+ const state: EditorState = options?.state ?? {
+ activeTool: 'SELECT',
+ currentPageId: _graph.getPages()[0].id,
+ selectedIds: new Set<string>(),
+ marquee: null,
+ snapGuides: [],
+ rotationPreview: null,
+ dropTargetId: null,
+ layoutInsertIndicator: null,
+ hoveredNodeId: null,
+ editingTextId: null,
+ penState: null,
+ penCursorX: null,
+ penCursorY: null,
+ remoteCursors: [],
+ documentName: 'Untitled',
+ panX: 0,
+ pageColor: { ...CANVAS_BG_COLOR },
+ panY: 0,
+ zoom: 1,
+ renderVersion: 0,
+ sceneVersion: 0,
+ loading: false,
+ enteredContainerId: null
+ }
+
+ function requestRender() {
+ state.renderVersion++
+ state.sceneVersion++
+ }
+
+ function requestRepaint() {
+ state.renderVersion++
+ }
+
+ function runLayoutForNode(id: string) {
+ const node = _graph.getNode(id)
+ if (!node) return
+
+ if (node.layoutMode !== 'NONE') {
+ computeLayout(_graph, id)
+ }
+
+ let parent = node.parentId ? _graph.getNode(node.parentId) : undefined
+ while (parent) {
+ if (parent.layoutMode !== 'NONE') {
+ computeLayout(_graph, parent.id)
+ }
+ parent = parent.parentId ? _graph.getNode(parent.parentId) : undefined
+ }
+ }
+
+ // Microtask-batched component sync
+ let pendingComponentSync: Set<string> | null = null
+
+ function flushComponentSync() {
+ const ids = pendingComponentSync
+ if (!ids) return
+ pendingComponentSync = null
+ const componentIds = new Set<string>()
+ for (const id of ids) {
+ let current = _graph.getNode(id)
+ while (current) {
+ if (current.type === 'COMPONENT') {
+ componentIds.add(current.id)
+ break
+ }
+ current = current.parentId ? _graph.getNode(current.parentId) : undefined
+ }
+ }
+ for (const compId of componentIds) {
+ _graph.syncInstances(compId)
+ }
+ if (componentIds.size > 0) requestRender()
+ }
+
+ function scheduleComponentSync(nodeId: string) {
+ if (!pendingComponentSync) {
+ pendingComponentSync = new Set()
+ queueMicrotask(flushComponentSync)
+ }
+ pendingComponentSync.add(nodeId)
+ }
+
+ function onNodeUpdated(id: string, changes: Partial<SceneNode>) {
+ if ('vectorNetwork' in changes) {
+ _renderer?.invalidateVectorPath(id)
+ }
+ _renderer?.invalidateNodePicture(id)
+ scheduleComponentSync(id)
+ requestRender()
+ }
+
+ function onNodeStructureChanged(nodeId: string) {
+ scheduleComponentSync(nodeId)
+ requestRender()
+ }
+
+ function subscribeToGraph() {
+ _graph.emitter.on('node:updated', onNodeUpdated)
+ _graph.emitter.on('node:created', (node) => onNodeStructureChanged(node.id))
+ _graph.emitter.on('node:deleted', onNodeStructureChanged)
+ _graph.emitter.on('node:reparented', onNodeStructureChanged)
+ _graph.emitter.on('node:reordered', onNodeStructureChanged)
+ }
+
+ subscribeToGraph()
+
+ // Build the shared context
+ const ctx: EditorContext = {
+ get graph() { return _graph },
+ set graph(g) { _graph = g },
+ undo,
+ state,
+ loadFont: _loadFont,
+ getViewportSize: _getViewportSize,
+ getCk: () => _ck,
+ getRenderer: () => _renderer,
+ getTextEditor: () => _textEditor,
+ requestRender,
+ requestRepaint,
+ runLayoutForNode,
+ subscribeToGraph
+ }
+
+ // Assemble domain modules
+ const viewport = createViewportActions(ctx)
+ const selection = createSelectionActions(ctx)
+ const pages = createPageActions(ctx)
+ const shapes = createShapeActions(ctx)
+ const structure = createStructureActions(ctx)
+ const components = createComponentActions(ctx)
+ const clipboard = createClipboardActions(ctx)
+ const undoActions = createUndoActions(ctx)
+ const text = createTextActions(ctx)
+ const nodes = createNodeActions(ctx)
+
+ function setCanvasKit(ck: CanvasKit, renderer: SkiaRenderer) {
+ _ck = ck
+ _renderer = renderer
+ _textEditor = new TextEditor(ck)
+ setTextMeasurer((node, maxWidth) => renderer.measureTextNode(node, maxWidth))
+ }
+
+ function replaceGraph(newGraph: SceneGraph) {
+ _graph = newGraph
+ subscribeToGraph()
+ state.currentPageId = _graph.getPages()[0]?.id ?? _graph.rootId
+ state.selectedIds = new Set()
+ state.hoveredNodeId = null
+ pages.clearPageViewports()
+ requestRender()
+ }
+
+ return {
+ get graph() { return _graph },
+ get renderer() { return _renderer },
+ get textEditor() { return _textEditor },
+ undo,
+ state,
+
+ // Lifecycle
+ requestRender,
+ requestRepaint,
+ setCanvasKit,
+ replaceGraph,
+
+ // Selection
+ ...selection,
+
+ // Pages
+ ...pages,
+
+ // Shapes & tools
+ ...shapes,
+
+ // Structure (group, reorder, reparent, z-order)
+ ...structure,
+
+ // Nodes (update, layout)
+ ...nodes,
+
+ // Text editing
+ ...text,
+
+ // Viewport
+ ...viewport,
+
+ // Undo — bridge functions that need cross-module refs
+ commitMove: undoActions.commitMove,
+ commitMoveWithReparent: undoActions.commitMoveWithReparent,
+ commitResize: undoActions.commitResize,
+ commitRotation: undoActions.commitRotation,
+ commitNodeUpdate: undoActions.commitNodeUpdate,
+ undoAction: () => undoActions.undoAction(selection.validateEnteredContainer),
+ redoAction: () => undoActions.redoAction(selection.validateEnteredContainer),
+ snapshotPage: undoActions.snapshotPage,
+ restorePageFromSnapshot: undoActions.restorePageFromSnapshot,
+ pushUndoEntry: undoActions.pushUndoEntry,
+
+ // Clipboard — bridge functions that need selectedNodes
+ duplicateSelected: () => clipboard.duplicateSelected(selection.getSelectedNodes()),
+ writeCopyData: (data: DataTransfer) => clipboard.writeCopyData(data, selection.getSelectedNodes()),
+ pasteFromHTML: clipboard.pasteFromHTML,
+ deleteSelected: clipboard.deleteSelected,
+ storeImage: clipboard.storeImage,
+ loadFontsForNodes: clipboard.loadFontsForNodes,
+
+ // Components — bridge functions
+ createComponentFromSelection: () =>
+ components.createComponentFromSelection(
+ selection.getSelectedNodes(),
+ structure.wrapSelectionInContainer
+ ),
+ createComponentSetFromComponents: () =>
+ components.createComponentSetFromComponents(
+ selection.getSelectedNodes(),
+ structure.wrapSelectionInContainer
+ ),
+ createInstanceFromComponent: components.createInstanceFromComponent,
+ detachInstance: () => components.detachInstance(selection.getSelectedNode()),
+ goToMainComponent: () =>
+ components.goToMainComponent(selection.getSelectedNode(), pages.switchPage),
+
+ // Structure — bridge functions that need selectedNodes
+ wrapInAutoLayout: () => structure.wrapInAutoLayout(selection.getSelectedNodes()),
+ groupSelected: () => structure.groupSelected(selection.getSelectedNodes()),
+ ungroupSelected: () => structure.ungroupSelected(selection.getSelectedNode())
+ }
+}
+
+export type Editor = ReturnType<typeof createEditor>
diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.ts
new file mode 100644
index 000000000..7f1e60048
--- /dev/null
+++ b/packages/core/src/editor/index.ts
@@ -0,0 +1,13 @@
+export { createEditor } from './create'
+export type { Editor } from './create'
+export {
+ EDITOR_TOOLS,
+ TOOL_SHORTCUTS
+} from './types'
+export type {
+ EditorContext,
+ EditorOptions,
+ EditorState,
+ EditorToolDef,
+ Tool
+} from './types'
diff --git a/packages/core/src/editor/nodes.ts b/packages/core/src/editor/nodes.ts
new file mode 100644
index 000000000..b3ed00777
--- /dev/null
+++ b/packages/core/src/editor/nodes.ts
@@ -0,0 +1,120 @@
+import { computeLayout } from '../layout'
+
+import type { LayoutMode, SceneNode } from '../scene-graph'
+import type { EditorContext } from './types'
+
+export function createNodeActions(ctx: EditorContext) {
+ function updateNode(id: string, changes: Partial<SceneNode>) {
+ ctx.graph.updateNode(id, changes)
+ ctx.runLayoutForNode(id)
+ }
+
+ function updateNodeWithUndo(id: string, changes: Partial<SceneNode>, label = 'Update') {
+ const node = ctx.graph.getNode(id)
+ if (!node) return
+ const previous = Object.fromEntries(
+ (Object.keys(changes) as (keyof SceneNode)[]).map((key) => [key, node[key]])
+ ) as Partial<SceneNode>
+ ctx.graph.updateNode(id, changes)
+ ctx.runLayoutForNode(id)
+ ctx.undo.push({
+ label,
+ forward: () => {
+ ctx.graph.updateNode(id, changes)
+ ctx.runLayoutForNode(id)
+ },
+ inverse: () => {
+ ctx.graph.updateNode(id, previous)
+ ctx.runLayoutForNode(id)
+ }
+ })
+ }
+
+ function setLayoutMode(id: string, mode: LayoutMode) {
+ const node = ctx.graph.getNode(id)
+ if (!node) return
+
+ const previous: Partial<SceneNode> = {
+ layoutMode: node.layoutMode,
+ itemSpacing: node.itemSpacing,
+ paddingTop: node.paddingTop,
+ paddingRight: node.paddingRight,
+ paddingBottom: node.paddingBottom,
+ paddingLeft: node.paddingLeft,
+ primaryAxisSizing: node.primaryAxisSizing,
+ counterAxisSizing: node.counterAxisSizing,
+ primaryAxisAlign: node.primaryAxisAlign,
+ counterAxisAlign: node.counterAxisAlign,
+ gridTemplateColumns: node.gridTemplateColumns,
+ gridTemplateRows: node.gridTemplateRows,
+ gridColumnGap: node.gridColumnGap,
+ gridRowGap: node.gridRowGap,
+ width: node.width,
+ height: node.height
+ }
+
+ const updates: Partial<SceneNode> = { layoutMode: mode }
+ if (mode === 'GRID' && node.layoutMode !== 'GRID') {
+ const children = ctx.graph.getChildren(id)
+ const cols = Math.max(2, Math.ceil(Math.sqrt(children.length)))
+ const rows = Math.max(1, Math.ceil(children.length / cols))
+ updates.gridTemplateColumns = Array.from({ length: cols }, () => ({
+ sizing: 'FR' as const,
+ value: 1
+ }))
+ updates.gridTemplateRows = Array.from({ length: rows }, () => ({
+ sizing: 'FR' as const,
+ value: 1
+ }))
+ updates.gridColumnGap = 0
+ updates.gridRowGap = 0
+ updates.primaryAxisSizing = 'FIXED'
+ updates.counterAxisSizing = 'FIXED'
+ if (node.primaryAxisSizing === 'HUG' || node.counterAxisSizing === 'HUG') {
+ const maxChildW = Math.max(...children.map((c) => c.width), 100)
+ const maxChildH = Math.max(...children.map((c) => c.height), 100)
+ updates.width = maxChildW * cols
+ updates.height = maxChildH * rows
+ }
+ updates.paddingTop = 0
+ updates.paddingRight = 0
+ updates.paddingBottom = 0
+ updates.paddingLeft = 0
+ } else if (mode !== 'NONE' && node.layoutMode === 'NONE') {
+ updates.itemSpacing = 0
+ updates.paddingTop = 0
+ updates.paddingRight = 0
+ updates.paddingBottom = 0
+ updates.paddingLeft = 0
+ updates.primaryAxisSizing = 'HUG'
+ updates.counterAxisSizing = 'HUG'
+ updates.primaryAxisAlign = 'MIN'
+ updates.counterAxisAlign = 'MIN'
+ }
+
+ ctx.graph.updateNode(id, updates)
+ if (mode !== 'NONE') computeLayout(ctx.graph, id)
+ ctx.runLayoutForNode(id)
+
+ const updated = ctx.graph.getNode(id)
+ if (!updated) return
+ const finalState = Object.fromEntries(
+ (Object.keys(previous) as (keyof SceneNode)[]).map((key) => [key, updated[key]])
+ ) as Partial<SceneNode>
+
+ ctx.undo.push({
+ label: mode === 'NONE' ? 'Remove auto layout' : 'Add auto layout',
+ forward: () => {
+ ctx.graph.updateNode(id, finalState)
+ if (mode !== 'NONE') computeLayout(ctx.graph, id)
+ ctx.runLayoutForNode(id)
+ },
+ inverse: () => {
+ ctx.graph.updateNode(id, previous)
+ ctx.runLayoutForNode(id)
+ }
+ })
+ }
+
+ return { updateNode, updateNodeWithUndo, setLayoutMode }
+}
diff --git a/packages/core/src/editor/pages.ts b/packages/core/src/editor/pages.ts
new file mode 100644
index 000000000..c295b4e0f
--- /dev/null
+++ b/packages/core/src/editor/pages.ts
@@ -0,0 +1,82 @@
+import { CANVAS_BG_COLOR } from '../constants'
+import { collectFontKeys } from '../fonts'
+
+import type { Color } from '../types'
+import type { EditorContext } from './types'
+
+interface PageViewport {
+ panX: number
+ panY: number
+ zoom: number
+ pageColor: Color
+}
+
+export function createPageActions(ctx: EditorContext) {
+ const pageViewports = new Map<string, PageViewport>()
+
+ async function switchPage(pageId: string) {
+ const page = ctx.graph.getNode(pageId)
+ if (page?.type !== 'CANVAS') return
+
+ pageViewports.set(ctx.state.currentPageId, {
+ panX: ctx.state.panX,
+ panY: ctx.state.panY,
+ zoom: ctx.state.zoom,
+ pageColor: { ...ctx.state.pageColor }
+ })
+
+ ctx.state.currentPageId = pageId
+ ctx.state.enteredContainerId = null
+ ctx.state.selectedIds = new Set()
+
+ const vp = pageViewports.get(pageId)
+ if (vp) {
+ ctx.state.panX = vp.panX
+ ctx.state.panY = vp.panY
+ ctx.state.zoom = vp.zoom
+ ctx.state.pageColor = { ...vp.pageColor }
+ } else {
+ ctx.state.panX = 0
+ ctx.state.panY = 0
+ ctx.state.zoom = 1
+ ctx.state.pageColor = { ...CANVAS_BG_COLOR }
+ }
+
+ const toLoad = collectFontKeys(ctx.graph, ctx.graph.getChildren(pageId).map((n) => n.id))
+ if (toLoad.length > 0) {
+ await Promise.all(toLoad.map(([family, style]) => ctx.loadFont(family, style)))
+ }
+ ctx.requestRender()
+ }
+
+ function addPage(name?: string) {
+ const pages = ctx.graph.getPages()
+ const pageName = name ?? `Page ${pages.length + 1}`
+ const page = ctx.graph.addPage(pageName)
+ void switchPage(page.id)
+ return page.id
+ }
+
+ function deletePage(pageId: string) {
+ const pages = ctx.graph.getPages()
+ if (pages.length <= 1) return
+ const idx = pages.findIndex((p) => p.id === pageId)
+ ctx.graph.deleteNode(pageId)
+ pageViewports.delete(pageId)
+ if (ctx.state.currentPageId === pageId) {
+ const newIdx = Math.min(idx, pages.length - 2)
+ const remaining = ctx.graph.getPages()
+ void switchPage(remaining[newIdx].id)
+ }
+ }
+
+ function renamePage(pageId: string, name: string) {
+ ctx.graph.updateNode(pageId, { name })
+ }
+
+ function clearPageViewports() {
+ pageViewports.clear()
+ }
+
+ return { switchPage, addPage, deletePage, renamePage, clearPageViewports }
+}
diff --git a/packages/core/src/editor/selection.ts b/packages/core/src/editor/selection.ts
new file mode 100644
index 000000000..1c64ca616
--- /dev/null
+++ b/packages/core/src/editor/selection.ts
@@ -0,0 +1,119 @@
+import type { Rect } from '../types'
+import type { SnapGuide } from '../snap'
+import type { EditorContext } from './types'
+
+export function createSelectionActions(ctx: EditorContext) {
+ function select(ids: string[], additive = false) {
+ if (additive) {
+ const next = new Set(ctx.state.selectedIds)
+ for (const id of ids) {
+ if (next.has(id)) next.delete(id)
+ else next.add(id)
+ }
+ ctx.state.selectedIds = next
+ } else {
+ ctx.state.selectedIds = new Set(ids)
+ }
+ }
+
+ function clearSelection() {
+ ctx.state.selectedIds = new Set()
+ }
+
+ function selectAll() {
+ const children = ctx.graph.getChildren(ctx.state.currentPageId)
+ ctx.state.selectedIds = new Set(children.map((n) => n.id))
+ }
+
+ function setMarquee(rect: Rect | null) {
+ ctx.state.marquee = rect
+ ctx.requestRepaint()
+ }
+
+ function setSnapGuides(guides: SnapGuide[]) {
+ ctx.state.snapGuides = guides
+ ctx.requestRepaint()
+ }
+
+ function setRotationPreview(preview: { nodeId: string; angle: number } | null) {
+ ctx.state.rotationPreview = preview
+ ctx.requestRepaint()
+ }
+
+ function setHoveredNode(id: string | null) {
+ if (ctx.state.hoveredNodeId === id) return
+ ctx.state.hoveredNodeId = id
+ ctx.requestRepaint()
+ }
+
+ function setDropTarget(id: string | null) {
+ ctx.state.dropTargetId = id
+ ctx.requestRepaint()
+ }
+
+ function setLayoutInsertIndicator(indicator: typeof ctx.state.layoutInsertIndicator) {
+ ctx.state.layoutInsertIndicator = indicator
+ ctx.requestRepaint()
+ }
+
+ function validateEnteredContainer() {
+ if (ctx.state.enteredContainerId && !ctx.graph.getNode(ctx.state.enteredContainerId)) {
+ ctx.state.enteredContainerId = null
+ }
+ }
+
+ function enterContainer(id: string) {
+ ctx.state.enteredContainerId = id
+ }
+
+ function exitContainer() {
+ const entered = ctx.state.enteredContainerId
+ if (!entered) return
+ const node = ctx.graph.getNode(entered)
+ const parentId = node?.parentId
+ if (parentId && parentId !== ctx.state.currentPageId) {
+ ctx.state.enteredContainerId = parentId
+ } else {
+ ctx.state.enteredContainerId = null
+ }
+ ctx.state.selectedIds = new Set(entered ? [entered] : [])
+ }
+
+ function getSelectedNodes() {
+ const nodes = []
+ for (const id of ctx.state.selectedIds) {
+ const n = ctx.graph.getNode(id)
+ if (n) nodes.push({ ...n })
+ }
+ return nodes
+ }
+
+ function getSelectedNode() {
+ if (ctx.state.selectedIds.size !== 1) return undefined
+ const id = ctx.state.selectedIds.values().next().value as string
+ const n = ctx.graph.getNode(id)
+ return n ? { ...n } : undefined
+ }
+
+ function getLayerTree() {
+ return ctx.graph.flattenTree(ctx.state.currentPageId)
+ }
+
+ return {
+ select,
+ clearSelection,
+ selectAll,
+ setMarquee,
+ setSnapGuides,
+ setRotationPreview,
+ setHoveredNode,
+ setDropTarget,
+ setLayoutInsertIndicator,
+ validateEnteredContainer,
+ enterContainer,
+ exitContainer,
+ getSelectedNodes,
+ getSelectedNode,
+ getLayerTree
+ }
+}
diff --git a/packages/core/src/editor/shapes.ts b/packages/core/src/editor/shapes.ts
new file mode 100644
index 000000000..bbb85e121
--- /dev/null
+++ b/packages/core/src/editor/shapes.ts
@@ -0,0 +1,277 @@
+import {
+ DEFAULT_FRAME_FILL,
+ DEFAULT_SHAPE_FILL,
+ SECTION_DEFAULT_FILL,
+ SECTION_DEFAULT_STROKE
+} from '../constants'
+import { computeVectorBounds } from '../vector'
+
+import type { Fill, NodeType, SceneNode, VectorNetwork, VectorRegion } from '../scene-graph'
+import type { EditorContext } from './types'
+
+const BLACK_FILL: Fill = {
+ type: 'SOLID',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ opacity: 1,
+ visible: true
+}
+
+const DEFAULT_FILLS: Record<string, Fill> = {
+ FRAME: DEFAULT_FRAME_FILL,
+ SECTION: SECTION_DEFAULT_FILL,
+ RECTANGLE: DEFAULT_SHAPE_FILL,
+ ELLIPSE: DEFAULT_SHAPE_FILL,
+ POLYGON: DEFAULT_SHAPE_FILL,
+ STAR: DEFAULT_SHAPE_FILL,
+ LINE: BLACK_FILL,
+ TEXT: BLACK_FILL
+}
+
+export function createShapeActions(ctx: EditorContext) {
+ function createShape(
+ type: NodeType,
+ x: number,
+ y: number,
+ w: number,
+ h: number,
+ parentId?: string
+ ): string {
+ const fill = DEFAULT_FILLS[type] ?? DEFAULT_FILLS.RECTANGLE
+ const pid = parentId ?? ctx.state.currentPageId
+ const overrides: Partial<SceneNode> = {
+ x,
+ y,
+ width: w,
+ height: h,
+ fills: [{ ...fill }]
+ }
+ if (type === 'SECTION') {
+ overrides.strokes = [{ ...SECTION_DEFAULT_STROKE }]
+ overrides.cornerRadius = 5
+ }
+ if (type === 'POLYGON') {
+ overrides.pointCount = 3
+ }
+ if (type === 'STAR') {
+ overrides.pointCount = 5
+ overrides.starInnerRadius = 0.38
+ }
+ const node = ctx.graph.createNode(type, pid, overrides)
+ const id = node.id
+ const snapshot = { ...node }
+ ctx.undo.push({
+ label: `Create ${type.toLowerCase()}`,
+ forward: () => {
+ ctx.graph.createNode(snapshot.type, pid, snapshot)
+ },
+ inverse: () => {
+ ctx.graph.deleteNode(id)
+ const next = new Set(ctx.state.selectedIds)
+ next.delete(id)
+ ctx.state.selectedIds = next
+ }
+ })
+ return id
+ }
+
+ function penAddVertex(x: number, y: number) {
+ if (!ctx.state.penState) {
+ ctx.state.penState = {
+ vertices: [{ x, y }],
+ segments: [],
+ dragTangent: null,
+ closingToFirst: false
+ }
+ ctx.requestRender()
+ return
+ }
+
+ const ps = ctx.state.penState
+ const prevIdx = ps.vertices.length - 1
+
+ const first = ps.vertices[0]
+ const dist = Math.hypot(x - first.x, y - first.y)
+ if (ps.vertices.length > 2 && dist < 8) {
+ ps.segments.push({
+ start: prevIdx,
+ end: 0,
+ tangentStart: ps.dragTangent ?? { x: 0, y: 0 },
+ tangentEnd: { x: 0, y: 0 }
+ })
+ penCommit(true)
+ return
+ }
+
+ ps.vertices.push({ x, y })
+ const newIdx = ps.vertices.length - 1
+ ps.segments.push({
+ start: prevIdx,
+ end: newIdx,
+ tangentStart: ps.dragTangent ?? { x: 0, y: 0 },
+ tangentEnd: { x: 0, y: 0 }
+ })
+ ps.dragTangent = null
+ ctx.requestRender()
+ }
+
+ function penSetDragTangent(tx: number, ty: number) {
+ if (!ctx.state.penState) return
+ ctx.state.penState.dragTangent = { x: tx, y: ty }
+
+ const ps = ctx.state.penState
+ if (ps.segments.length > 0) {
+ const lastSeg = ps.segments[ps.segments.length - 1]
+ lastSeg.tangentEnd = { x: -tx, y: -ty }
+ }
+ ctx.requestRender()
+ }
+
+ function penSetClosingToFirst(closing: boolean) {
+ if (!ctx.state.penState) return
+ ctx.state.penState.closingToFirst = closing
+ ctx.requestRender()
+ }
+
+ function penCommit(closed: boolean) {
+ const ps = ctx.state.penState
+ if (!ps || ps.vertices.length < 2) {
+ ctx.state.penState = null
+ ctx.state.penCursorX = null
+ ctx.state.penCursorY = null
+ return
+ }
+
+ const regions: VectorRegion[] = closed
+ ? [{ windingRule: 'NONZERO', loops: [ps.segments.map((_, i) => i)] }]
+ : []
+
+ const network: VectorNetwork = {
+ vertices: ps.vertices,
+ segments: ps.segments,
+ regions
+ }
+
+ const bounds = computeVectorBounds(network)
+
+ const normalizedVertices = network.vertices.map((v) => ({
+ ...v,
+ x: v.x - bounds.x,
+ y: v.y - bounds.y
+ }))
+
+ const normalizedNetwork: VectorNetwork = {
+ vertices: normalizedVertices,
+ segments: network.segments,
+ regions: network.regions
+ }
+
+ const nodeId = createShape('VECTOR', bounds.x, bounds.y, bounds.width, bounds.height)
+ ctx.graph.updateNode(nodeId, {
+ vectorNetwork: normalizedNetwork,
+ name: 'Vector',
+ fills: closed ? [{ ...DEFAULT_SHAPE_FILL }] : [],
+ strokes: closed
+ ? []
+ : [
+ {
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ weight: 2,
+ opacity: 1,
+ visible: true,
+ align: 'CENTER' as const
+ }
+ ]
+ })
+ ctx.state.selectedIds = new Set([nodeId])
+
+ ctx.state.penState = null
+ ctx.state.penCursorX = null
+ ctx.state.penCursorY = null
+ ctx.state.activeTool = 'SELECT'
+ ctx.requestRender()
+ }
+
+ function penCancel() {
+ ctx.state.penState = null
+ ctx.state.penCursorX = null
+ ctx.state.penCursorY = null
+ ctx.state.activeTool = 'SELECT'
+ ctx.requestRender()
+ }
+
+ function adoptNodesIntoSection(sectionId: string) {
+ const section = ctx.graph.getNode(sectionId)
+ if (section?.type !== 'SECTION') return
+
+ const parentId = section.parentId ?? ctx.state.currentPageId
+ const siblings = ctx.graph.getChildren(parentId)
+
+ const sx = section.x
+ const sy = section.y
+ const sx2 = sx + section.width
+ const sy2 = sy + section.height
+
+ const toAdopt: string[] = []
+ for (const sibling of siblings) {
+ if (sibling.id === sectionId) continue
+ const nx = sibling.x
+ const ny = sibling.y
+ const nx2 = nx + sibling.width
+ const ny2 = ny + sibling.height
+ if (nx >= sx && ny >= sy && nx2 <= sx2 && ny2 <= sy2) {
+ toAdopt.push(sibling.id)
+ }
+ }
+
+ if (toAdopt.length === 0) return
+
+ const undoOps: Array<{
+ id: string
+ oldParent: string
+ oldX: number
+ oldY: number
+ newX: number
+ newY: number
+ }> = []
+ for (const id of toAdopt) {
+ const node = ctx.graph.getNode(id)
+ if (!node) continue
+ const newX = node.x - sx
+ const newY = node.y - sy
+ undoOps.push({ id, oldParent: parentId, oldX: node.x, oldY: node.y, newX, newY })
+ ctx.graph.reparentNode(id, sectionId)
+ ctx.graph.updateNode(id, { x: newX, y: newY })
+ }
+
+ ctx.undo.push({
+ label: 'Adopt into section',
+ forward: () => {
+ for (const op of undoOps) {
+ ctx.graph.reparentNode(op.id, sectionId)
+ ctx.graph.updateNode(op.id, { x: op.newX, y: op.newY })
+ }
+ },
+ inverse: () => {
+ for (const op of undoOps) {
+ ctx.graph.reparentNode(op.id, op.oldParent)
+ ctx.graph.updateNode(op.id, { x: op.oldX, y: op.oldY })
+ }
+ }
+ })
+ }
+
+ function setTool(tool: typeof ctx.state.activeTool) {
+ ctx.state.activeTool = tool
+ }
+
+ return {
+ createShape,
+ penAddVertex,
+ penSetDragTangent,
+ penSetClosingToFirst,
+ penCommit,
+ penCancel,
+ adoptNodesIntoSection,
+ setTool
+ }
+}
diff --git a/packages/core/src/editor/structure.ts b/packages/core/src/editor/structure.ts
new file mode 100644
index 000000000..cddb523b4
--- /dev/null
+++ b/packages/core/src/editor/structure.ts
@@ -0,0 +1,394 @@
+import { computeLayout } from '../layout'
+
+import type { LayoutMode, SceneNode } from '../scene-graph'
+import type { EditorContext } from './types'
+
+export function createStructureActions(ctx: EditorContext) {
+ function isTopLevel(parentId: string | null): boolean {
+ return !parentId || parentId === ctx.graph.rootId || parentId === ctx.state.currentPageId
+ }
+
+ function doReorderChild(nodeId: string, parentId: string, insertIndex: number) {
+ const node = ctx.graph.getNode(nodeId)
+ if (!node) return
+
+ if (node.parentId !== parentId) {
+ const absPos = ctx.graph.getAbsolutePosition(nodeId)
+ const parentAbs = ctx.graph.getAbsolutePosition(parentId)
+ ctx.graph.updateNode(nodeId, { x: absPos.x - parentAbs.x, y: absPos.y - parentAbs.y })
+ }
+
+ ctx.graph.reorderChild(nodeId, parentId, insertIndex)
+ computeLayout(ctx.graph, parentId)
+ ctx.runLayoutForNode(parentId)
+ }
+
+ function reorderInAutoLayout(nodeId: string, parentId: string, insertIndex: number) {
+ const parent = ctx.graph.getNode(parentId)
+ if (!parent || parent.layoutMode === 'NONE') return
+
+ const node = ctx.graph.getNode(nodeId)
+ if (!node) return
+ const origParentId = node.parentId ?? ctx.state.currentPageId
+ const origX = node.x
+ const origY = node.y
+ const origIndex = ctx.graph.getNode(origParentId)?.childIds.indexOf(nodeId) ?? -1
+
+ doReorderChild(nodeId, parentId, insertIndex)
+
+ ctx.undo.push({
+ label: 'Reorder',
+ forward: () => {
+ doReorderChild(nodeId, parentId, insertIndex)
+ },
+ inverse: () => {
+ ctx.graph.reorderChild(nodeId, origParentId, origIndex >= 0 ? origIndex : 0)
+ ctx.graph.updateNode(nodeId, { x: origX, y: origY })
+ computeLayout(ctx.graph, origParentId)
+ ctx.runLayoutForNode(origParentId)
+ if (origParentId !== parentId) {
+ computeLayout(ctx.graph, parentId)
+ ctx.runLayoutForNode(parentId)
+ }
+ }
+ })
+ }
+
+ function reorderChildWithUndo(nodeId: string, newParentId: string, insertIndex: number) {
+ const node = ctx.graph.getNode(nodeId)
+ if (!node) return
+ const origParentId = node.parentId ?? ctx.state.currentPageId
+ const origIndex = ctx.graph.getNode(origParentId)?.childIds.indexOf(nodeId) ?? 0
+ const origX = node.x
+ const origY = node.y
+
+ ctx.graph.reorderChild(nodeId, newParentId, insertIndex)
+ ctx.runLayoutForNode(newParentId)
+ if (origParentId !== newParentId) ctx.runLayoutForNode(origParentId)
+
+ ctx.undo.push({
+ label: 'Reorder',
+ forward: () => {
+ ctx.graph.reorderChild(nodeId, newParentId, insertIndex)
+ ctx.runLayoutForNode(newParentId)
+ if (origParentId !== newParentId) ctx.runLayoutForNode(origParentId)
+ },
+ inverse: () => {
+ ctx.graph.reorderChild(nodeId, origParentId, origIndex)
+ ctx.graph.updateNode(nodeId, { x: origX, y: origY })
+ ctx.runLayoutForNode(origParentId)
+ if (origParentId !== newParentId) ctx.runLayoutForNode(newParentId)
+ }
+ })
+ }
+
+ function reparentNodes(nodeIds: string[], newParentId: string) {
+ const parent = ctx.graph.getNode(newParentId)
+ for (const id of nodeIds) {
+ const node = ctx.graph.getNode(id)
+ if (
+ node?.type === 'SECTION' &&
+ parent &&
+ parent.type !== 'CANVAS' &&
+ parent.type !== 'SECTION'
+ )
+ continue
+ ctx.graph.reparentNode(id, newParentId)
+ }
+ }
+
+ function wrapSelectionInContainer(
+ containerType: 'GROUP' | 'FRAME' | 'COMPONENT' | 'COMPONENT_SET',
+ selectedNodes: SceneNode[],
+ extraProps?: Partial<SceneNode>
+ ) {
+ if (selectedNodes.length === 0) return null
+
+ const parentId = selectedNodes[0].parentId ?? ctx.state.currentPageId
+ const sameParent = selectedNodes.every(
+ (n) => (n.parentId ?? ctx.state.currentPageId) === parentId
+ )
+ if (!sameParent) return null
+
+ const parent = ctx.graph.getNode(parentId)
+ if (!parent) return null
+
+ const prevSelection = new Set(ctx.state.selectedIds)
+ const nodeIds = selectedNodes.map((n) => n.id)
+ const origPositions = selectedNodes.map((n) => ({ id: n.id, x: n.x, y: n.y }))
+
+ let minX = Infinity
+ let minY = Infinity
+ let maxX = -Infinity
+ let maxY = -Infinity
+ for (const n of selectedNodes) {
+ const abs = ctx.graph.getAbsolutePosition(n.id)
+ minX = Math.min(minX, abs.x)
+ minY = Math.min(minY, abs.y)
+ maxX = Math.max(maxX, abs.x + n.width)
+ maxY = Math.max(maxY, abs.y + n.height)
+ }
+
+ const parentAbs = isTopLevel(parentId) ? { x: 0, y: 0 } : ctx.graph.getAbsolutePosition(parentId)
+ const firstIndex = Math.min(...nodeIds.map((id) => parent.childIds.indexOf(id)))
+
+ const padding = containerType === 'COMPONENT_SET' ? 40 : 0
+ const containerNames: Record<string, string> = {
+ COMPONENT_SET: selectedNodes[0].name.split('/')[0]?.trim() || 'Component Set',
+ COMPONENT: 'Component',
+ GROUP: 'Group',
+ FRAME: 'Frame'
+ }
+ const containerNode = ctx.graph.createNode(containerType, parentId, {
+ name: containerNames[containerType] ?? containerType,
+ x: minX - parentAbs.x - padding,
+ y: minY - parentAbs.y - padding,
+ width: maxX - minX + padding * 2,
+ height: maxY - minY + padding * 2,
+ fills: containerType === 'COMPONENT_SET'
+ ? [{ type: 'SOLID', color: { r: 0.96, g: 0.96, b: 0.96, a: 1 }, opacity: 1, visible: true }]
+ : [],
+ ...extraProps
+ })
+ const containerId = containerNode.id
+
+ parent.childIds = parent.childIds.filter((id) => id !== containerId)
+ parent.childIds.splice(firstIndex, 0, containerId)
+
+ for (const n of selectedNodes) {
+ ctx.graph.reparentNode(n.id, containerId)
+ }
+
+ ctx.state.selectedIds = new Set([containerId])
+
+ ctx.undo.push({
+ label: `Create ${containerType.toLowerCase().replace('_', ' ')}`,
+ forward: () => {
+ const c = ctx.graph.createNode(containerType, parentId, { ...containerNode, ...extraProps })
+ parent.childIds = parent.childIds.filter((id) => id !== c.id)
+ parent.childIds.splice(firstIndex, 0, c.id)
+ for (const n of origPositions) ctx.graph.reparentNode(n.id, c.id)
+ ctx.state.selectedIds = new Set([c.id])
+ },
+ inverse: () => {
+ for (const orig of origPositions) {
+ ctx.graph.reparentNode(orig.id, parentId)
+ ctx.graph.updateNode(orig.id, { x: orig.x, y: orig.y })
+ }
+ ctx.graph.deleteNode(containerId)
+ ctx.state.selectedIds = prevSelection
+ }
+ })
+
+ return containerId
+ }
+
+ function wrapInAutoLayout(selectedNodes: SceneNode[]) {
+ if (selectedNodes.length === 0) return
+
+ const parentId = selectedNodes[0].parentId ?? ctx.state.currentPageId
+ const sameParent = selectedNodes.every(
+ (n) => (n.parentId ?? ctx.state.currentPageId) === parentId
+ )
+ if (!sameParent) return
+
+ const prevSelection = new Set(ctx.state.selectedIds)
+ const origPositions = selectedNodes.map((n) => ({ id: n.id, x: n.x, y: n.y, parentId }))
+
+ let minX = Infinity
+ let minY = Infinity
+ let maxX = -Infinity
+ let maxY = -Infinity
+ for (const n of selectedNodes) {
+ const abs = ctx.graph.getAbsolutePosition(n.id)
+ minX = Math.min(minX, abs.x)
+ minY = Math.min(minY, abs.y)
+ maxX = Math.max(maxX, abs.x + n.width)
+ maxY = Math.max(maxY, abs.y + n.height)
+ }
+
+ const parentAbs = isTopLevel(parentId)
+ ? { x: 0, y: 0 }
+ : ctx.graph.getAbsolutePosition(parentId)
+
+ const direction: LayoutMode =
+ selectedNodes.length <= 1 || maxY - minY > maxX - minX ? 'VERTICAL' : 'HORIZONTAL'
+
+ const frame = ctx.graph.createNode('FRAME', parentId, {
+ name: 'Frame',
+ x: minX - parentAbs.x,
+ y: minY - parentAbs.y,
+ width: maxX - minX,
+ height: maxY - minY,
+ layoutMode: direction,
+ primaryAxisSizing: 'HUG',
+ counterAxisSizing: 'HUG',
+ primaryAxisAlign: 'MIN',
+ counterAxisAlign: 'MIN',
+ fills: []
+ })
+ const frameId = frame.id
+
+ const sortedIds = selectedNodes
+ .map((n) => ({ id: n.id, pos: ctx.graph.getAbsolutePosition(n.id) }))
+ .sort((a, b) => a.pos.y - b.pos.y || a.pos.x - b.pos.x)
+ .map((n) => n.id)
+
+ for (const id of sortedIds) {
+ ctx.graph.reparentNode(id, frameId)
+ }
+
+ computeLayout(ctx.graph, frameId)
+ ctx.runLayoutForNode(frameId)
+ ctx.state.selectedIds = new Set([frameId])
+
+ ctx.undo.push({
+ label: 'Wrap in auto layout',
+ forward: () => {
+ const f = ctx.graph.createNode('FRAME', parentId, { ...frame })
+ for (const n of origPositions) ctx.graph.reparentNode(n.id, f.id)
+ computeLayout(ctx.graph, f.id)
+ ctx.runLayoutForNode(f.id)
+ ctx.state.selectedIds = new Set([f.id])
+ },
+ inverse: () => {
+ for (const orig of origPositions) {
+ ctx.graph.reparentNode(orig.id, orig.parentId)
+ ctx.graph.updateNode(orig.id, { x: orig.x, y: orig.y })
+ }
+ ctx.graph.deleteNode(frameId)
+ ctx.state.selectedIds = prevSelection
+ }
+ })
+ }
+
+ function groupSelected(selectedNodes: SceneNode[]) {
+ return wrapSelectionInContainer('GROUP', selectedNodes)
+ }
+
+ function ungroupSelected(selectedNode: SceneNode | undefined) {
+ if (selectedNode?.type !== 'GROUP') return
+
+ const node = selectedNode
+ const parentId = node.parentId ?? ctx.state.currentPageId
+ const parent = ctx.graph.getNode(parentId)
+ if (!parent) return
+
+ const groupIndex = parent.childIds.indexOf(node.id)
+ const childIds = [...node.childIds]
+ const prevSelection = new Set(ctx.state.selectedIds)
+ const origPositions = childIds.map((id) => {
+ const child = ctx.graph.getNode(id)
+ if (!child) return { id, x: 0, y: 0 }
+ return { id, x: child.x, y: child.y }
+ })
+ const groupSnapshot = { ...node, childIds: [...node.childIds] }
+
+ for (let i = 0; i < childIds.length; i++) {
+ ctx.graph.reparentNode(childIds[i], parentId)
+ parent.childIds = parent.childIds.filter((id) => id !== childIds[i])
+ parent.childIds.splice(groupIndex + i, 0, childIds[i])
+ }
+
+ ctx.graph.deleteNode(node.id)
+ ctx.state.selectedIds = new Set(childIds)
+
+ ctx.undo.push({
+ label: 'Ungroup',
+ forward: () => {
+ for (let i = 0; i < childIds.length; i++) {
+ ctx.graph.reparentNode(childIds[i], parentId)
+ parent.childIds = parent.childIds.filter((id) => id !== childIds[i])
+ parent.childIds.splice(groupIndex + i, 0, childIds[i])
+ }
+ ctx.graph.deleteNode(node.id)
+ ctx.state.selectedIds = new Set(childIds)
+ },
+ inverse: () => {
+ const g = ctx.graph.createNode('GROUP', parentId, { ...groupSnapshot, childIds: [] })
+ parent.childIds = parent.childIds.filter((id) => id !== g.id)
+ parent.childIds.splice(groupIndex, 0, g.id)
+ for (const orig of origPositions) {
+ ctx.graph.reparentNode(orig.id, g.id)
+ ctx.graph.updateNode(orig.id, { x: orig.x, y: orig.y })
+ }
+ ctx.state.selectedIds = prevSelection
+ }
+ })
+ }
+
+ function bringToFront() {
+ for (const id of ctx.state.selectedIds) {
+ const node = ctx.graph.getNode(id)
+ if (!node?.parentId) continue
+ const parent = ctx.graph.getNode(node.parentId)
+ if (!parent) continue
+ const idx = parent.childIds.indexOf(id)
+ if (idx === parent.childIds.length - 1) continue
+ parent.childIds = parent.childIds.filter((cid) => cid !== id)
+ parent.childIds.push(id)
+ }
+ ctx.requestRender()
+ }
+
+ function sendToBack() {
+ for (const id of ctx.state.selectedIds) {
+ const node = ctx.graph.getNode(id)
+ if (!node?.parentId) continue
+ const parent = ctx.graph.getNode(node.parentId)
+ if (!parent) continue
+ const idx = parent.childIds.indexOf(id)
+ if (idx === 0) continue
+ parent.childIds = parent.childIds.filter((cid) => cid !== id)
+ parent.childIds.unshift(id)
+ }
+ ctx.requestRender()
+ }
+
+ function toggleVisibility() {
+ for (const id of ctx.state.selectedIds) {
+ const node = ctx.graph.getNode(id)
+ if (!node) continue
+ ctx.graph.updateNode(id, { visible: !node.visible })
+ }
+ }
+
+ function toggleLock() {
+ for (const id of ctx.state.selectedIds) {
+ const node = ctx.graph.getNode(id)
+ if (!node) continue
+ ctx.graph.updateNode(id, { locked: !node.locked })
+ }
+ }
+
+ function moveToPage(pageId: string) {
+ const targetPage = ctx.graph.getNode(pageId)
+ if (targetPage?.type !== 'CANVAS') return
+ const ids = [...ctx.state.selectedIds]
+ for (const id of ids) {
+ ctx.graph.reparentNode(id, pageId)
+ }
+ ctx.state.selectedIds = new Set()
+ }
+
+ function renameNode(id: string, name: string) {
+ ctx.graph.updateNode(id, { name })
+ }
+
+ return {
+ isTopLevel,
+ reorderInAutoLayout,
+ reorderChildWithUndo,
+ reparentNodes,
+ wrapSelectionInContainer,
+ wrapInAutoLayout,
+ groupSelected,
+ ungroupSelected,
+ bringToFront,
+ sendToBack,
+ toggleVisibility,
+ toggleLock,
+ moveToPage,
+ renameNode
+ }
+}
diff --git a/packages/core/src/editor/text.ts b/packages/core/src/editor/text.ts
new file mode 100644
index 000000000..0d9f776c6
--- /dev/null
+++ b/packages/core/src/editor/text.ts
@@ -0,0 +1,48 @@
+import type { EditorContext } from './types'
+
+export function createTextActions(ctx: EditorContext) {
+ function startTextEditing(nodeId: string) {
+ const te = ctx.getTextEditor()
+ if (ctx.state.editingTextId) commitTextEdit()
+ const node = ctx.graph.getNode(nodeId)
+ if (!node) return
+ ctx.state.editingTextId = nodeId
+ if (te) {
+ te.setRenderer(ctx.getRenderer())
+ te.start(node)
+ }
+ ctx.requestRender()
+ }
+
+ function commitTextEdit() {
+ const te = ctx.getTextEditor()
+ if (!te?.isActive) {
+ ctx.state.editingTextId = null
+ return
+ }
+ const result = te.stop()
+ if (!result) {
+ ctx.state.editingTextId = null
+ ctx.requestRender()
+ return
+ }
+ const node = ctx.graph.getNode(result.nodeId)
+ const prevText = node?.text ?? ''
+ const newText = result.text
+ ctx.graph.updateNode(result.nodeId, { text: newText })
+ ctx.state.editingTextId = null
+ if (prevText !== newText) {
+ ctx.undo.push({
+ label: 'Edit text',
+ forward: () => {
+ ctx.graph.updateNode(result.nodeId, { text: newText })
+ },
+ inverse: () => {
+ ctx.graph.updateNode(result.nodeId, { text: prevText })
+ }
+ })
+ }
+ }
+
+ return { startTextEditing, commitTextEdit }
+}
diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.ts
new file mode 100644
index 000000000..06a82b44b
--- /dev/null
+++ b/packages/core/src/editor/types.ts
@@ -0,0 +1,120 @@
+import type { Color, Rect, Vector } from '../types'
+import type { SceneGraph, VectorSegment, VectorVertex } from '../scene-graph'
+import type { SnapGuide } from '../snap'
+import type { SkiaRenderer } from '../renderer/renderer'
+import type { UndoManager } from '../undo'
+import type { TextEditor } from '../text-editor'
+import type { CanvasKit } from 'canvaskit-wasm'
+
+export type Tool =
+ | 'SELECT'
+ | 'FRAME'
+ | 'SECTION'
+ | 'RECTANGLE'
+ | 'ELLIPSE'
+ | 'LINE'
+ | 'POLYGON'
+ | 'STAR'
+ | 'TEXT'
+ | 'PEN'
+ | 'HAND'
+
+export interface EditorToolDef {
+ key: Tool
+ label: string
+ shortcut: string
+ flyout?: Tool[]
+}
+
+export const EDITOR_TOOLS: EditorToolDef[] = [
+ { key: 'SELECT', label: 'Move', shortcut: 'V' },
+ { key: 'FRAME', label: 'Frame', shortcut: 'F', flyout: ['FRAME', 'SECTION'] },
+ {
+ key: 'RECTANGLE',
+ label: 'Rectangle',
+ shortcut: 'R',
+ flyout: ['RECTANGLE', 'LINE', 'ELLIPSE', 'POLYGON', 'STAR']
+ },
+ { key: 'PEN', label: 'Pen', shortcut: 'P' },
+ { key: 'TEXT', label: 'Text', shortcut: 'T' },
+ { key: 'HAND', label: 'Hand', shortcut: 'H' }
+]
+
+export const TOOL_SHORTCUTS: Partial<Record<string, Tool>> = {
+ v: 'SELECT',
+ f: 'FRAME',
+ s: 'SECTION',
+ r: 'RECTANGLE',
+ o: 'ELLIPSE',
+ l: 'LINE',
+ t: 'TEXT',
+ p: 'PEN',
+ h: 'HAND'
+}
+
+export interface EditorState {
+ activeTool: Tool
+ currentPageId: string
+ selectedIds: Set<string>
+ marquee: Rect | null
+ snapGuides: SnapGuide[]
+ rotationPreview: { nodeId: string; angle: number } | null
+ dropTargetId: string | null
+ layoutInsertIndicator: {
+ parentId: string
+ index: number
+ x: number
+ y: number
+ length: number
+ direction: 'HORIZONTAL' | 'VERTICAL'
+ } | null
+ hoveredNodeId: string | null
+ editingTextId: string | null
+ penState: {
+ vertices: VectorVertex[]
+ segments: VectorSegment[]
+ dragTangent: Vector | null
+ closingToFirst: boolean
+ } | null
+ penCursorX: number | null
+ penCursorY: number | null
+ remoteCursors: Array<{
+ name: string
+ color: Color
+ x: number
+ y: number
+ selection?: string[]
+ }>
+ documentName: string
+ panX: number
+ pageColor: Color
+ panY: number
+ zoom: number
+ renderVersion: number
+ sceneVersion: number
+ loading: boolean
+ enteredContainerId: string | null
+}
+
+export interface EditorOptions {
+ graph?: SceneGraph
+ state?: EditorState
+ loadFont?: (family: string, style: string) => Promise<ArrayBuffer | null>
+ getViewportSize?: () => { width: number; height: number }
+}
+
+export interface EditorContext {
+ get graph(): SceneGraph
+ set graph(g: SceneGraph)
+ undo: UndoManager
+ state: EditorState
+ loadFont: (family: string, style: string) => Promise<ArrayBuffer | null>
+ getViewportSize: () => { width: number; height: number }
+ getCk: () => CanvasKit | null
+ getRenderer: () => SkiaRenderer | null
+ getTextEditor: () => TextEditor | null
+ requestRender: () => void
+ requestRepaint: () => void
+ runLayoutForNode: (id: string) => void
+ subscribeToGraph: () => void
+}
diff --git a/packages/core/src/editor/undo.ts b/packages/core/src/editor/undo.ts
new file mode 100644
index 000000000..ba3729b46
--- /dev/null
+++ b/packages/core/src/editor/undo.ts
@@ -0,0 +1,172 @@
+import { computeAllLayouts } from '../layout'
+
+import type { Rect, Vector } from '../types'
+import type { SceneNode } from '../scene-graph'
+import type { UndoEntry } from '../undo'
+import type { EditorContext } from './types'
+
+export function createUndoActions(ctx: EditorContext) {
+ function commitMove(originals: Map<string, Vector>) {
+ const finals = new Map<string, Vector>()
+ for (const [id] of originals) {
+ const n = ctx.graph.getNode(id)
+ if (n) finals.set(id, { x: n.x, y: n.y })
+ }
+ ctx.undo.push({
+ label: 'Move',
+ forward: () => {
+ for (const [id, pos] of finals) {
+ ctx.graph.updateNode(id, pos)
+ ctx.runLayoutForNode(id)
+ }
+ },
+ inverse: () => {
+ for (const [id, pos] of originals) {
+ ctx.graph.updateNode(id, pos)
+ ctx.runLayoutForNode(id)
+ }
+ }
+ })
+ }
+
+ function commitMoveWithReparent(
+ originals: Map<string, { x: number; y: number; parentId: string }>
+ ) {
+ const finals = new Map<string, { x: number; y: number; parentId: string }>()
+ for (const [id] of originals) {
+ const n = ctx.graph.getNode(id)
+ if (n) finals.set(id, { x: n.x, y: n.y, parentId: n.parentId ?? ctx.state.currentPageId })
+ }
+ ctx.undo.push({
+ label: 'Move',
+ forward: () => {
+ for (const [id, pos] of finals) {
+ ctx.graph.reparentNode(id, pos.parentId)
+ ctx.graph.updateNode(id, { x: pos.x, y: pos.y })
+ ctx.runLayoutForNode(id)
+ }
+ },
+ inverse: () => {
+ for (const [id, pos] of originals) {
+ ctx.graph.reparentNode(id, pos.parentId)
+ ctx.graph.updateNode(id, { x: pos.x, y: pos.y })
+ ctx.runLayoutForNode(id)
+ }
+ }
+ })
+ }
+
+ function commitResize(nodeId: string, origRect: Rect) {
+ const node = ctx.graph.getNode(nodeId)
+ if (!node) return
+ const finalRect = { x: node.x, y: node.y, width: node.width, height: node.height }
+ ctx.undo.push({
+ label: 'Resize',
+ forward: () => {
+ ctx.graph.updateNode(nodeId, finalRect)
+ ctx.runLayoutForNode(nodeId)
+ },
+ inverse: () => {
+ ctx.graph.updateNode(nodeId, origRect)
+ ctx.runLayoutForNode(nodeId)
+ }
+ })
+ }
+
+ function commitRotation(nodeId: string, origRotation: number) {
+ const node = ctx.graph.getNode(nodeId)
+ if (!node) return
+ const finalRotation = node.rotation
+ ctx.undo.push({
+ label: 'Rotate',
+ forward: () => {
+ ctx.graph.updateNode(nodeId, { rotation: finalRotation })
+ },
+ inverse: () => {
+ ctx.graph.updateNode(nodeId, { rotation: origRotation })
+ }
+ })
+ }
+
+ function commitNodeUpdate(nodeId: string, previous: Partial<SceneNode>, label = 'Update') {
+ const node = ctx.graph.getNode(nodeId)
+ if (!node) return
+ const current = Object.fromEntries(
+ (Object.keys(previous) as (keyof SceneNode)[]).map((key) => [key, node[key]])
+ ) as Partial<SceneNode>
+ ctx.undo.push({
+ label,
+ forward: () => {
+ ctx.graph.updateNode(nodeId, current)
+ ctx.runLayoutForNode(nodeId)
+ },
+ inverse: () => {
+ ctx.graph.updateNode(nodeId, previous)
+ ctx.runLayoutForNode(nodeId)
+ }
+ })
+ }
+
+ function undoAction(validateEnteredContainer: () => void) {
+ ctx.undo.undo()
+ validateEnteredContainer()
+ }
+
+ function redoAction(validateEnteredContainer: () => void) {
+ ctx.undo.redo()
+ validateEnteredContainer()
+ ctx.requestRender()
+ }
+
+ function snapshotPage(): Map<string, SceneNode> {
+ const snapshot = new Map<string, SceneNode>()
+ const walk = (id: string) => {
+ const node = ctx.graph.getNode(id)
+ if (!node) return
+ snapshot.set(id, structuredClone(node))
+ for (const childId of node.childIds) walk(childId)
+ }
+ walk(ctx.state.currentPageId)
+ return snapshot
+ }
+
+ function restorePageFromSnapshot(snapshot: Map<string, SceneNode>) {
+ const page = ctx.graph.getNode(ctx.state.currentPageId)
+ if (!page) return
+
+ for (const childId of page.childIds.slice()) {
+ ctx.graph.deleteNode(childId)
+ }
+
+ const pageSnap = snapshot.get(ctx.state.currentPageId)
+ if (pageSnap) page.childIds = [...pageSnap.childIds]
+
+ for (const [id, snap] of snapshot) {
+ if (id === ctx.state.currentPageId) continue
+ ctx.graph.nodes.set(id, structuredClone(snap))
+ }
+
+ ctx.graph.clearAbsPosCache()
+ computeAllLayouts(ctx.graph, ctx.state.currentPageId)
+ ctx.state.selectedIds = new Set()
+ ctx.state.hoveredNodeId = null
+ ctx.requestRender()
+ }
+
+ function pushUndoEntry(entry: UndoEntry) {
+ ctx.undo.push(entry)
+ }
+
+ return {
+ commitMove,
+ commitMoveWithReparent,
+ commitResize,
+ commitRotation,
+ commitNodeUpdate,
+ undoAction,
+ redoAction,
+ snapshotPage,
+ restorePageFromSnapshot,
+ pushUndoEntry
+ }
+}
diff --git a/packages/core/src/editor/viewport.ts b/packages/core/src/editor/viewport.ts
new file mode 100644
index 000000000..cda054257
--- /dev/null
+++ b/packages/core/src/editor/viewport.ts
@@ -0,0 +1,96 @@
+import { ZOOM_DIVISOR, ZOOM_SCALE_MAX, ZOOM_SCALE_MIN } from '../constants'
+
+import type { EditorContext } from './types'
+
+export function createViewportActions(ctx: EditorContext) {
+ function screenToCanvas(sx: number, sy: number) {
+ return {
+ x: (sx - ctx.state.panX) / ctx.state.zoom,
+ y: (sy - ctx.state.panY) / ctx.state.zoom
+ }
+ }
+
+ function applyZoom(delta: number, centerX: number, centerY: number) {
+ const factor = Math.min(
+ ZOOM_SCALE_MAX,
+ Math.max(ZOOM_SCALE_MIN, Math.exp(-delta / ZOOM_DIVISOR))
+ )
+ const newZoom = Math.max(0.02, Math.min(256, ctx.state.zoom * factor))
+ ctx.state.panX = centerX - (centerX - ctx.state.panX) * (newZoom / ctx.state.zoom)
+ ctx.state.panY = centerY - (centerY - ctx.state.panY) * (newZoom / ctx.state.zoom)
+ ctx.state.zoom = newZoom
+ ctx.requestRepaint()
+ }
+
+ function pan(dx: number, dy: number) {
+ ctx.state.panX += dx
+ ctx.state.panY += dy
+ ctx.requestRepaint()
+ }
+
+ function zoomToBounds(minX: number, minY: number, maxX: number, maxY: number) {
+ const padding = 80
+ const w = maxX - minX + padding * 2
+ const h = maxY - minY + padding * 2
+
+ const { width: viewW, height: viewH } = ctx.getViewportSize()
+ const zoom = Math.min(viewW / w, viewH / h, 1)
+
+ ctx.state.zoom = zoom
+ ctx.state.panX = (viewW - w * zoom) / 2 - minX * zoom + padding * zoom
+ ctx.state.panY = (viewH - h * zoom) / 2 - minY * zoom + padding * zoom
+ ctx.requestRepaint()
+ }
+
+ function zoomToFit() {
+ const nodes = ctx.graph.getChildren(ctx.state.currentPageId)
+ if (nodes.length === 0) return
+
+ let minX = Infinity
+ let minY = Infinity
+ let maxX = -Infinity
+ let maxY = -Infinity
+ for (const n of nodes) {
+ minX = Math.min(minX, n.x)
+ minY = Math.min(minY, n.y)
+ maxX = Math.max(maxX, n.x + n.width)
+ maxY = Math.max(maxY, n.y + n.height)
+ }
+
+ zoomToBounds(minX, minY, maxX, maxY)
+ }
+
+ function zoomTo100() {
+ const { width: viewW, height: viewH } = ctx.getViewportSize()
+ const centerX = (-ctx.state.panX + viewW / 2) / ctx.state.zoom
+ const centerY = (-ctx.state.panY + viewH / 2) / ctx.state.zoom
+
+ ctx.state.zoom = 1
+ ctx.state.panX = viewW / 2 - centerX
+ ctx.state.panY = viewH / 2 - centerY
+ ctx.requestRepaint()
+ }
+
+ function zoomToSelection() {
+ if (ctx.state.selectedIds.size === 0) return
+
+ let minX = Infinity
+ let minY = Infinity
+ let maxX = -Infinity
+ let maxY = -Infinity
+ for (const id of ctx.state.selectedIds) {
+ const n = ctx.graph.getNode(id)
+ if (!n) continue
+ const abs = ctx.graph.getAbsolutePosition(id)
+ minX = Math.min(minX, abs.x)
+ minY = Math.min(minY, abs.y)
+ maxX = Math.max(maxX, abs.x + n.width)
+ maxY = Math.max(maxY, abs.y + n.height)
+ }
+ if (minX === Infinity) return
+
+ zoomToBounds(minX, minY, maxX, maxY)
+ }
+
+ return { screenToCanvas, applyZoom, pan, zoomToBounds, zoomToFit, zoomTo100, zoomToSelection }
+}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index bcdd810d2..a418baddb 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -4,6 +4,20 @@ export { randomHex, randomInt, randomIndex } from './random'
export * from './constants'
+export {
+ createEditor,
+ EDITOR_TOOLS,
+ TOOL_SHORTCUTS
+} from './editor'
+export type {
+ Editor,
+ EditorContext,
+ EditorOptions,
+ EditorState,
+ EditorToolDef,
+ Tool
+} from './editor'
+
export {
SceneGraph,
generateId,
diff --git a/src/components/LayerTree.vue b/src/components/LayerTree.vue
index 76467341d..4a2ebb587 100644
--- a/src/components/LayerTree.vue
+++ b/src/components/LayerTree.vue
@@ -67,12 +67,22 @@ const COMPONENT_TYPES = new Set(['COMPONENT', 'COMPONENT_SET', 'INSTANCE'])
function toggleNodeVisibility(id: string) {
const node = store.graph.getNode(id)
- if (node) store.updateNodeWithUndo(id, { visible: !node.visible }, node.visible ? 'Hide layer' : 'Show layer')
+ if (node)
+ store.updateNodeWithUndo(
+ id,
+ { visible: !node.visible },
+ node.visible ? 'Hide layer' : 'Show layer'
+ )
}
function toggleNodeLock(id: string) {
const node = store.graph.getNode(id)
- if (node) store.updateNodeWithUndo(id, { locked: !node.locked }, node.locked ? 'Unlock layer' : 'Lock layer')
+ if (node)
+ store.updateNodeWithUndo(
+ id,
+ { locked: !node.locked },
+ node.locked ? 'Unlock layer' : 'Lock layer'
+ )
}
function buildTree(parentId: string): LayerNode[] {
@@ -443,9 +453,7 @@ function updateDropTarget(ev: PointerEvent) {
v-if="item.value.locked"
class="size-3"
:class="
- store.state.selectedIds.has(item.value.id)
- ? 'text-white'
- : 'text-surface'
+ store.state.selectedIds.has(item.value.id) ? 'text-white' : 'text-surface'
"
/>
<icon-lucide-unlock
@@ -468,9 +476,7 @@ function updateDropTarget(ev: PointerEvent) {
v-if="!item.value.visible"
class="size-3"
:class="
- store.state.selectedIds.has(item.value.id)
- ? 'text-white'
- : 'text-surface'
+ store.state.selectedIds.has(item.value.id) ? 'text-white' : 'text-surface'
"
/>
<icon-lucide-eye
diff --git a/src/components/properties/FillSection.vue b/src/components/properties/FillSection.vue
index a5fb3bb18..ce80226e8 100644
--- a/src/components/properties/FillSection.vue
+++ b/src/components/properties/FillSection.vue
@@ -22,7 +22,17 @@ import { colorToCSS, colorToHexRaw } from '@open-pencil/core'
import type { Fill, Variable, Color } from '@open-pencil/core'
const { store } = useNodeProps()
-const { nodes, isMulti, active, activeNode, targetNodes, isArrayMixed, updateArrayItem, removeArrayItem, toggleArrayVisibility } = useMultiProps()
+const {
+ nodes,
+ isMulti,
+ active,
+ activeNode,
+ targetNodes,
+ isArrayMixed,
+ updateArrayItem,
+ removeArrayItem,
+ toggleArrayVisibility
+} = useMultiProps()
const fillsAreMixed = computed(() => isArrayMixed('fills'))
@@ -60,7 +70,12 @@ function updateFill(index: number, fill: Fill) {
}
function updateOpacity(index: number, opacity: number) {
- updateArrayItem('fills', index, { opacity: Math.max(0, Math.min(1, opacity / 100)) }, 'Change fill')
+ updateArrayItem(
+ 'fills',
+ index,
+ { opacity: Math.max(0, Math.min(1, opacity / 100)) },
+ 'Change fill'
+ )
}
function toggleVisibility(index: number) {
@@ -69,7 +84,9 @@ function toggleVisibility(index: number) {
function add() {
for (const n of targetNodes()) {
- const fills = isMulti.value ? [{ ...DEFAULT_SHAPE_FILL }] : [...n.fills, { ...DEFAULT_SHAPE_FILL }]
+ const fills = isMulti.value
+ ? [{ ...DEFAULT_SHAPE_FILL }]
+ : [...n.fills, { ...DEFAULT_SHAPE_FILL }]
store.updateNodeWithUndo(n.id, { fills }, isMulti.value ? 'Set fill' : 'Add fill')
}
}
diff --git a/src/components/properties/StrokeSection.vue b/src/components/properties/StrokeSection.vue
index e84d4f3cc..d0456f160 100644
--- a/src/components/properties/StrokeSection.vue
+++ b/src/components/properties/StrokeSection.vue
@@ -20,7 +20,17 @@ import type { Color, SceneNode, Stroke } from '@open-pencil/core'
type StrokeSides = 'ALL' | 'TOP' | 'BOTTOM' | 'LEFT' | 'RIGHT' | 'CUSTOM'
const { store } = useNodeProps()
-const { nodes, isMulti, active, activeNode, targetNodes, isArrayMixed, updateArrayItem, removeArrayItem, toggleArrayVisibility } = useMultiProps()
+const {
+ nodes,
+ isMulti,
+ active,
+ activeNode,
+ targetNodes,
+ isArrayMixed,
+ updateArrayItem,
+ removeArrayItem,
+ toggleArrayVisibility
+} = useMultiProps()
const strokesAreMixed = computed(() => isArrayMixed('strokes'))
@@ -67,7 +77,12 @@ function updateWeight(index: number, weight: number) {
}
function updateOpacity(index: number, opacity: number) {
- updateArrayItem('strokes', index, { opacity: Math.max(0, Math.min(1, opacity / 100)) }, 'Change stroke')
+ updateArrayItem(
+ 'strokes',
+ index,
+ { opacity: Math.max(0, Math.min(1, opacity / 100)) },
+ 'Change stroke'
+ )
}
function updateAlign(align: Stroke['align']) {
diff --git a/src/composables/use-canvas-input.ts b/src/composables/use-canvas-input.ts
index 8f9afb5eb..a548607f7 100644
--- a/src/composables/use-canvas-input.ts
+++ b/src/composables/use-canvas-input.ts
@@ -497,9 +497,7 @@ export function useCanvasInput(
function resolveHit(cx: number, cy: number): SceneNode | null {
const titleHit =
- hitTestFrameTitle(cx, cy) ??
- hitTestSectionTitle(cx, cy) ??
- hitTestComponentLabel(cx, cy)
+ hitTestFrameTitle(cx, cy) ?? hitTestSectionTitle(cx, cy) ?? hitTestComponentLabel(cx, cy)
if (titleHit) return titleHit
const hit = hitTestInScope(cx, cy, false)
@@ -681,9 +679,7 @@ export function useCanvasInput(
cursorOverride.value = cursor
const hit =
- hitTestSectionTitle(cx, cy) ??
- hitTestComponentLabel(cx, cy) ??
- hitTestInScope(cx, cy, false)
+ hitTestSectionTitle(cx, cy) ?? hitTestComponentLabel(cx, cy) ?? hitTestInScope(cx, cy, false)
store.setHoveredNode(hit && !store.state.selectedIds.has(hit.id) ? hit.id : null)
}
@@ -1161,12 +1157,11 @@ export function useCanvasInput(
const { cx, cy } = getCoords(e)
- const selectedId = store.state.selectedIds.size === 1
- ? [...store.state.selectedIds][0]
- : undefined
+ const selectedId =
+ store.state.selectedIds.size === 1 ? [...store.state.selectedIds][0] : undefined
const selectedNode = selectedId ? store.graph.getNode(selectedId) : undefined
- const canEnter = selectedNode && selectedId
- && store.graph.isContainer(selectedId) && !selectedNode.locked
+ const canEnter =
+ selectedNode && selectedId && store.graph.isContainer(selectedId) && !selectedNode.locked
if (canEnter) {
store.enterContainer(selectedId)
@@ -1180,9 +1175,8 @@ export function useCanvasInput(
return
}
- const hit = hitTestSectionTitle(cx, cy) ??
- hitTestComponentLabel(cx, cy) ??
- hitTestInScope(cx, cy, true)
+ const hit =
+ hitTestSectionTitle(cx, cy) ?? hitTestComponentLabel(cx, cy) ?? hitTestInScope(cx, cy, true)
if (!hit) return
if (hit.type === 'TEXT') {
diff --git a/src/composables/use-collab.ts b/src/composables/use-collab.ts
index 26bafd582..c6b2534b5 100644
--- a/src/composables/use-collab.ts
+++ b/src/composables/use-collab.ts
@@ -12,9 +12,9 @@ import {
ROOM_ID_CHARS,
YJS_JSON_FIELDS
} from '@/constants'
+import { randomIndex } from '@open-pencil/core'
import type { EditorStore } from '@/stores/editor'
-import { randomIndex } from '@open-pencil/core'
import type { Color, SceneNode } from '@open-pencil/core'
import type { Room } from 'trystero'
diff --git a/src/composables/use-multi-props.ts b/src/composables/use-multi-props.ts
index 209985bfe..3bfe0988f 100644
--- a/src/composables/use-multi-props.ts
+++ b/src/composables/use-multi-props.ts
@@ -79,7 +79,11 @@ export function useMultiProps() {
if (!items[index]) continue
const arr = [...n[key]]
arr[index] = { ...arr[index], visible: !items[index].visible }
- store.updateNodeWithUndo(n.id, { [key]: arr } as Partial<SceneNode>, `Toggle ${key} visibility`)
+ store.updateNodeWithUndo(
+ n.id,
+ { [key]: arr } as Partial<SceneNode>,
+ `Toggle ${key} visibility`
+ )
}
}
diff --git a/src/constants.ts b/src/constants.ts
index 53164e9a9..4d7aecb29 100644
--- a/src/constants.ts
+++ b/src/constants.ts
@@ -57,7 +57,7 @@ export {
RULER_MAJOR_TOLERANCE
} from '@open-pencil/core'
-import type { Color, Fill, Stroke } from '@open-pencil/core'
+import type { Color } from '@open-pencil/core'
export const TRYSTERO_APP_ID = 'openpencil'
export const ROOM_ID_LENGTH = 8
@@ -84,19 +84,15 @@ export const YJS_JSON_FIELDS = new Set([
'styleRuns'
])
-export const DEFAULT_SHAPE_FILL: Fill = {
- type: 'SOLID',
- color: { r: 0.83, g: 0.83, b: 0.83, a: 1 },
- opacity: 1,
- visible: true
-}
-
-export const DEFAULT_FRAME_FILL: Fill = {
- type: 'SOLID',
- color: { r: 1, g: 1, b: 1, a: 1 },
- opacity: 1,
- visible: true
-}
+export {
+ DEFAULT_SHAPE_FILL,
+ DEFAULT_FRAME_FILL,
+ SECTION_DEFAULT_FILL,
+ SECTION_DEFAULT_STROKE,
+ ZOOM_DIVISOR,
+ ZOOM_SCALE_MIN,
+ ZOOM_SCALE_MAX
+} from '@open-pencil/core'
export const HANDLE_SIZE = 6
@@ -118,28 +114,6 @@ export const DEFAULT_TEXT_HEIGHT = 24
export const AUTO_LAYOUT_BREAK_THRESHOLD = 8
export const HANDLE_HIT_RADIUS = 6
-// Pixels of deltaY for one e-fold of zoom (Math.exp(-deltaY / ZOOM_DIVISOR))
-// Trackpad pinch sends small deltas (~2-5px), mouse wheel sends large (~100px).
-// Lower = more responsive. 50 matches Figma's trackpad feel.
-export const ZOOM_DIVISOR = 50
-// Clamp scale factor per wheel flush to prevent jarring jumps from mouse wheels
-export const ZOOM_SCALE_MIN = 0.75
-export const ZOOM_SCALE_MAX = 1.25
-
-export const SECTION_DEFAULT_FILL: Fill = {
- type: 'SOLID',
- color: { r: 0.37, g: 0.37, b: 0.37, a: 1 },
- opacity: 1,
- visible: true
-}
-export const SECTION_DEFAULT_STROKE: Stroke = {
- color: { r: 0.55, g: 0.55, b: 0.55, a: 1 },
- weight: 1,
- opacity: 1,
- visible: true,
- align: 'INSIDE'
-}
-
export const ACP_PERMISSION_TIMEOUT_MS = 60_000
export const ACP_DESIGN_CONTEXT = `You are inside OpenPencil, an open-source design editor (like Figma). \
diff --git a/src/stores/editor.ts b/src/stores/editor.ts
index f97a441a7..256fb1c2a 100644
--- a/src/stores/editor.ts
+++ b/src/stores/editor.ts
@@ -1,213 +1,102 @@
import { shallowReactive, shallowRef, computed, watch } from 'vue'
import { toast } from '@/composables/use-toast'
-import {
- IS_TAURI,
- DEFAULT_SHAPE_FILL,
- DEFAULT_FRAME_FILL,
- SECTION_DEFAULT_FILL,
- SECTION_DEFAULT_STROKE,
- CANVAS_BG_COLOR,
- ZOOM_DIVISOR,
- ZOOM_SCALE_MIN,
- ZOOM_SCALE_MAX
-} from '@/constants'
+import { IS_TAURI, CANVAS_BG_COLOR } from '@/constants'
import { loadFont } from '@/engine/fonts'
import {
- collectFontKeys,
- computeLayout,
computeAllLayouts,
- computeVectorBounds,
+ createEditor,
exportFigFile,
- importClipboardNodes,
- parseFigmaClipboard,
- buildFigmaClipboardHTML,
- prefetchFigmaSchema,
readFigFile,
- computeImageHash,
renderNodesToImage,
renderNodesToSVG,
- SceneGraph,
- setTextMeasurer,
- TextEditor,
- UndoManager
-} from '@open-pencil/core'
-
-import type {
- Color,
- ExportFormat,
- Fill,
- LayoutMode,
- NodeType,
- Rect,
- SceneNode,
- SkiaRenderer,
- SnapGuide,
- UndoEntry,
- VectorNetwork,
- VectorRegion,
- VectorSegment,
- Vector,
- VectorVertex
+ SceneGraph
} from '@open-pencil/core'
-import type { CanvasKit } from 'canvaskit-wasm'
-
-export type Tool =
- | 'SELECT'
- | 'FRAME'
- | 'SECTION'
- | 'RECTANGLE'
- | 'ELLIPSE'
- | 'LINE'
- | 'POLYGON'
- | 'STAR'
- | 'TEXT'
- | 'PEN'
- | 'HAND'
-
-export interface ToolDef {
- key: Tool
- label: string
- shortcut: string
- flyout?: Tool[]
-}
-
-export const TOOLS: ToolDef[] = [
- { key: 'SELECT', label: 'Move', shortcut: 'V' },
- { key: 'FRAME', label: 'Frame', shortcut: 'F', flyout: ['FRAME', 'SECTION'] },
- {
- key: 'RECTANGLE',
- label: 'Rectangle',
- shortcut: 'R',
- flyout: ['RECTANGLE', 'LINE', 'ELLIPSE', 'POLYGON', 'STAR']
- },
- { key: 'PEN', label: 'Pen', shortcut: 'P' },
- { key: 'TEXT', label: 'Text', shortcut: 'T' },
- { key: 'HAND', label: 'Hand', shortcut: 'H' }
-]
-
-export const TOOL_SHORTCUTS: Partial<Record<string, Tool>> = {
- v: 'SELECT',
- f: 'FRAME',
- s: 'SECTION',
- r: 'RECTANGLE',
- o: 'ELLIPSE',
- l: 'LINE',
- t: 'TEXT',
- p: 'PEN',
- h: 'HAND'
-}
-
-const BLACK_FILL: Fill = {
- type: 'SOLID',
- color: { r: 0, g: 0, b: 0, a: 1 },
- opacity: 1,
- visible: true
-}
-const DEFAULT_FILLS: Record<string, Fill> = {
- FRAME: DEFAULT_FRAME_FILL,
- SECTION: SECTION_DEFAULT_FILL,
- RECTANGLE: DEFAULT_SHAPE_FILL,
- ELLIPSE: DEFAULT_SHAPE_FILL,
- POLYGON: DEFAULT_SHAPE_FILL,
- STAR: DEFAULT_SHAPE_FILL,
- LINE: BLACK_FILL,
- TEXT: BLACK_FILL
-}
+import type { EditorState, ExportFormat, SceneNode } from '@open-pencil/core'
-interface PageViewport {
- panX: number
- panY: number
- zoom: number
- pageColor: Color
-}
+export type { Tool } from '@open-pencil/core'
+export type { EditorToolDef as ToolDef } from '@open-pencil/core'
+export { EDITOR_TOOLS as TOOLS, TOOL_SHORTCUTS } from '@open-pencil/core'
export function createEditorStore() {
- let graph = new SceneGraph()
- const undo = new UndoManager()
- const pageViewports = new Map<string, PageViewport>()
- let fileHandle: FileSystemFileHandle | null = null
- let filePath: string | null = null
- let downloadName: string | null = null
- let savedVersion = 0
- let autosaveTimer: ReturnType<typeof setTimeout> | undefined
- let lastWriteTime = 0
- let unwatchFile: (() => void) | null = null
- let _ck: CanvasKit | null = null
- let _renderer: SkiaRenderer | null = null
- let _textEditor: TextEditor | null = null
-
- void prefetchFigmaSchema()
-
- function downloadBlob(data: Uint8Array, filename: string, mime: string) {
- const blob = new Blob([data.buffer as ArrayBuffer], { type: mime })
- const url = URL.createObjectURL(blob)
- const a = document.createElement('a')
- a.href = url
- a.download = filename
- a.style.display = 'none'
- document.body.appendChild(a)
- a.click()
- setTimeout(() => {
- document.body.removeChild(a)
- URL.revokeObjectURL(url)
- }, 100)
- }
-
- const state = shallowReactive({
- activeTool: 'SELECT' as Tool,
+ const graph = new SceneGraph()
+
+ const state = shallowReactive<
+ EditorState & {
+ showUI: boolean
+ activeRibbonTab: 'panels' | 'code' | 'ai'
+ panelMode: 'layers' | 'design'
+ actionToast: string | null
+ mobileDrawerSnap: 'closed' | 'half' | 'full'
+ clipboardHtml: string
+ autosaveEnabled: boolean
+ cursorCanvasX: number | null
+ cursorCanvasY: number | null
+ }
+ >({
+ activeTool: 'SELECT',
currentPageId: graph.getPages()[0].id,
selectedIds: new Set<string>(),
- marquee: null as Rect | null,
- snapGuides: [] as SnapGuide[],
- rotationPreview: null as { nodeId: string; angle: number } | null,
- dropTargetId: null as string | null,
- layoutInsertIndicator: null as {
- parentId: string
- index: number
- x: number
- y: number
- length: number
- direction: 'HORIZONTAL' | 'VERTICAL'
- } | null,
- hoveredNodeId: null as string | null,
- editingTextId: null as string | null,
- penState: null as {
- vertices: VectorVertex[]
- segments: VectorSegment[]
- dragTangent: Vector | null
- closingToFirst: boolean
- } | null,
- penCursorX: null as number | null,
- penCursorY: null as number | null,
- cursorCanvasX: null as number | null,
- cursorCanvasY: null as number | null,
- remoteCursors: [] as Array<{
- name: string
- color: Color
- x: number
- y: number
- selection?: string[]
- }>,
- showUI: true,
- documentName: 'Untitled' as string,
+ marquee: null,
+ snapGuides: [],
+ rotationPreview: null,
+ dropTargetId: null,
+ layoutInsertIndicator: null,
+ hoveredNodeId: null,
+ editingTextId: null,
+ penState: null,
+ penCursorX: null,
+ penCursorY: null,
+ remoteCursors: [],
+ documentName: 'Untitled',
panX: 0,
- pageColor: { ...CANVAS_BG_COLOR } as Color,
+ pageColor: { ...CANVAS_BG_COLOR },
panY: 0,
zoom: 1,
renderVersion: 0,
sceneVersion: 0,
loading: false,
- activeRibbonTab: 'panels' as 'panels' | 'code' | 'ai',
- panelMode: 'design' as 'layers' | 'design',
- actionToast: null as string | null,
- mobileDrawerSnap: 'closed' as 'closed' | 'half' | 'full',
+ enteredContainerId: null,
+ showUI: true,
+ activeRibbonTab: 'panels',
+ panelMode: 'design',
+ actionToast: null,
+ mobileDrawerSnap: 'closed',
clipboardHtml: '',
autosaveEnabled: false,
- enteredContainerId: null as string | null
+ cursorCanvasX: null,
+ cursorCanvasY: null
+ })
+
+ const editor = createEditor({ graph, state, loadFont })
+
+ // ─── Vue computed refs ────────────────────────────────────────
+
+ const selectedNodes = computed(() => {
+ void state.sceneVersion
+ return editor.getSelectedNodes()
+ })
+
+ const selectedNode = computed(() =>
+ selectedNodes.value.length === 1 ? selectedNodes.value[0] : undefined
+ )
+
+ const layerTree = computed(() => {
+ void state.sceneVersion
+ return editor.getLayerTree()
})
+ // ─── File I/O state ───────────────────────────────────────────
+
+ let fileHandle: FileSystemFileHandle | null = null
+ let filePath: string | null = null
+ let downloadName: string | null = null
+ let savedVersion = 0
+ let autosaveTimer: ReturnType<typeof setTimeout> | undefined
+ let lastWriteTime = 0
+ let unwatchFile: (() => void) | null = null
+
const AUTOSAVE_DELAY = 3000
watch(
@@ -230,66 +119,40 @@ export function createEditorStore() {
}
)
- const selectedNodes = computed(() => {
- void state.sceneVersion
- const nodes: SceneNode[] = []
- for (const id of state.selectedIds) {
- const n = graph.getNode(id)
- if (n) nodes.push({ ...n })
- }
- return nodes
- })
-
- const selectedNode = computed(() =>
- selectedNodes.value.length === 1 ? selectedNodes.value[0] : undefined
- )
-
- const layerTree = computed(() => {
- void state.sceneVersion
- return graph.flattenTree(state.currentPageId)
- })
-
- function requestRender() {
- state.renderVersion++
- state.sceneVersion++
- }
-
- function requestRepaint() {
- state.renderVersion++
- }
+ // ─── Flash nodes (renderer-specific) ─────────────────────────
let flashRafId = 0
function flashNodes(nodeIds: string[]) {
- if (!_renderer) return
- for (const id of nodeIds) _renderer.flashNode(id)
+ const renderer = editor.renderer
+ if (!renderer) return
+ for (const id of nodeIds) renderer.flashNode(id)
if (!flashRafId) pumpFlashes()
}
function aiMarkActive(nodeIds: string[]) {
- if (!_renderer) return
- _renderer.aiMarkActive(nodeIds)
+ if (!editor.renderer) return
+ editor.renderer.aiMarkActive(nodeIds)
if (!flashRafId) pumpFlashes()
}
function aiMarkDone(nodeIds: string[]) {
- if (!_renderer) return
- _renderer.aiMarkDone(nodeIds)
+ if (!editor.renderer) return
+ editor.renderer.aiMarkDone(nodeIds)
if (!flashRafId) pumpFlashes()
}
function aiFlashDone(nodeIds: string[]) {
- if (!_renderer) return
- _renderer.aiFlashDone(nodeIds)
+ if (!editor.renderer) return
+ editor.renderer.aiFlashDone(nodeIds)
if (!flashRafId) pumpFlashes()
}
function aiClearAll() {
- if (!_renderer) return
- _renderer.aiClearAll()
+ editor.renderer?.aiClearAll()
}
function pumpFlashes() {
- if (!_renderer?.hasActiveFlashes) {
+ if (!editor.renderer?.hasActiveFlashes) {
flashRafId = 0
return
}
@@ -297,404 +160,21 @@ export function createEditorStore() {
flashRafId = requestAnimationFrame(pumpFlashes)
}
- function isTopLevel(parentId: string | null): boolean {
- return !parentId || parentId === graph.rootId || parentId === state.currentPageId
- }
-
- async function switchPage(pageId: string) {
- const page = graph.getNode(pageId)
- if (page?.type !== 'CANVAS') return
-
- // Save current viewport
- pageViewports.set(state.currentPageId, {
- panX: state.panX,
- panY: state.panY,
- zoom: state.zoom,
- pageColor: { ...state.pageColor }
- })
-
- // Switch
- state.currentPageId = pageId
- state.enteredContainerId = null
- clearSelection()
-
- // Restore viewport
- const vp = pageViewports.get(pageId)
- if (vp) {
- state.panX = vp.panX
- state.panY = vp.panY
- state.zoom = vp.zoom
- state.pageColor = { ...vp.pageColor }
- } else {
- state.panX = 0
- state.panY = 0
- state.zoom = 1
- state.pageColor = { ...CANVAS_BG_COLOR }
- }
-
- await loadFontsForNodes(graph.getChildren(pageId).map((n) => n.id))
- requestRender()
- }
-
- function addPage(name?: string) {
- const pages = graph.getPages()
- const pageName = name ?? `Page ${pages.length + 1}`
- const page = graph.addPage(pageName)
- void switchPage(page.id)
- return page.id
- }
-
- function deletePage(pageId: string) {
- const pages = graph.getPages()
- if (pages.length <= 1) return
- const idx = pages.findIndex((p) => p.id === pageId)
- graph.deleteNode(pageId)
- pageViewports.delete(pageId)
- if (state.currentPageId === pageId) {
- const newIdx = Math.min(idx, pages.length - 2)
- const remaining = graph.getPages()
- void switchPage(remaining[newIdx].id)
- }
- }
-
- function renamePage(pageId: string, name: string) {
- graph.updateNode(pageId, { name })
- }
-
- function setTool(tool: Tool) {
- state.activeTool = tool
- }
-
- function select(ids: string[], additive = false) {
- if (additive) {
- const next = new Set(state.selectedIds)
- for (const id of ids) {
- if (next.has(id)) next.delete(id)
- else next.add(id)
- }
- state.selectedIds = next
- } else {
- state.selectedIds = new Set(ids)
- }
- }
-
- function clearSelection() {
- state.selectedIds = new Set()
- }
-
- function validateEnteredContainer() {
- if (state.enteredContainerId && !graph.getNode(state.enteredContainerId)) {
- state.enteredContainerId = null
- }
- }
-
- function enterContainer(id: string) {
- state.enteredContainerId = id
- }
-
- function exitContainer() {
- const entered = state.enteredContainerId
- if (!entered) return
- const node = graph.getNode(entered)
- const parentId = node?.parentId
- if (parentId && parentId !== state.currentPageId) {
- state.enteredContainerId = parentId
- } else {
- state.enteredContainerId = null
- }
- state.selectedIds = new Set(entered ? [entered] : [])
- }
-
- function setMarquee(rect: Rect | null) {
- state.marquee = rect
- requestRepaint()
- }
-
- function setSnapGuides(guides: SnapGuide[]) {
- state.snapGuides = guides
- requestRepaint()
- }
-
- function setRotationPreview(preview: { nodeId: string; angle: number } | null) {
- state.rotationPreview = preview
- requestRepaint()
- }
-
- function setHoveredNode(id: string | null) {
- if (state.hoveredNodeId === id) return
- state.hoveredNodeId = id
- requestRepaint()
- }
-
- function setDropTarget(id: string | null) {
- state.dropTargetId = id
- requestRepaint()
- }
-
- function setLayoutInsertIndicator(indicator: typeof state.layoutInsertIndicator) {
- state.layoutInsertIndicator = indicator
- requestRepaint()
- }
-
- function doReorderChild(nodeId: string, parentId: string, insertIndex: number) {
- const node = graph.getNode(nodeId)
- if (!node) return
-
- if (node.parentId !== parentId) {
- const absPos = graph.getAbsolutePosition(nodeId)
- const parentAbs = graph.getAbsolutePosition(parentId)
- graph.updateNode(nodeId, { x: absPos.x - parentAbs.x, y: absPos.y - parentAbs.y })
- }
-
- graph.reorderChild(nodeId, parentId, insertIndex)
- computeLayout(graph, parentId)
- runLayoutForNode(parentId)
- }
-
- function reorderInAutoLayout(nodeId: string, parentId: string, insertIndex: number) {
- const parent = graph.getNode(parentId)
- if (!parent || parent.layoutMode === 'NONE') return
-
- const node = graph.getNode(nodeId)
- if (!node) return
- const origParentId = node.parentId ?? state.currentPageId
- const origX = node.x
- const origY = node.y
- const origIndex = graph.getNode(origParentId)?.childIds.indexOf(nodeId) ?? -1
-
- doReorderChild(nodeId, parentId, insertIndex)
-
- undo.push({
- label: 'Reorder',
- forward: () => {
- doReorderChild(nodeId, parentId, insertIndex)
- },
- inverse: () => {
- graph.reorderChild(nodeId, origParentId, origIndex >= 0 ? origIndex : 0)
- graph.updateNode(nodeId, { x: origX, y: origY })
- computeLayout(graph, origParentId)
- runLayoutForNode(origParentId)
- if (origParentId !== parentId) {
- computeLayout(graph, parentId)
- runLayoutForNode(parentId)
- }
- }
- })
- }
-
- function reorderChildWithUndo(nodeId: string, newParentId: string, insertIndex: number) {
- const node = graph.getNode(nodeId)
- if (!node) return
- const origParentId = node.parentId ?? state.currentPageId
- const origIndex = graph.getNode(origParentId)?.childIds.indexOf(nodeId) ?? 0
- const origX = node.x
- const origY = node.y
-
- graph.reorderChild(nodeId, newParentId, insertIndex)
- runLayoutForNode(newParentId)
- if (origParentId !== newParentId) runLayoutForNode(origParentId)
-
- undo.push({
- label: 'Reorder',
- forward: () => {
- graph.reorderChild(nodeId, newParentId, insertIndex)
- runLayoutForNode(newParentId)
- if (origParentId !== newParentId) runLayoutForNode(origParentId)
- },
- inverse: () => {
- graph.reorderChild(nodeId, origParentId, origIndex)
- graph.updateNode(nodeId, { x: origX, y: origY })
- runLayoutForNode(origParentId)
- if (origParentId !== newParentId) runLayoutForNode(newParentId)
- }
- })
- }
-
- function reparentNodes(nodeIds: string[], newParentId: string) {
- const parent = graph.getNode(newParentId)
- for (const id of nodeIds) {
- const node = graph.getNode(id)
- // Sections can only live in pages (CANVAS) or other sections
- if (
- node?.type === 'SECTION' &&
- parent &&
- parent.type !== 'CANVAS' &&
- parent.type !== 'SECTION'
- )
- continue
- graph.reparentNode(id, newParentId)
- }
- }
-
- function penAddVertex(x: number, y: number) {
- if (!state.penState) {
- state.penState = {
- vertices: [{ x, y }],
- segments: [],
- dragTangent: null,
- closingToFirst: false
- }
- requestRender()
- return
- }
-
- const ps = state.penState
- const prevIdx = ps.vertices.length - 1
-
- // Check if clicking near first vertex to close
- const first = ps.vertices[0]
- const dist = Math.hypot(x - first.x, y - first.y)
- if (ps.vertices.length > 2 && dist < 8) {
- // Close the path
- ps.segments.push({
- start: prevIdx,
- end: 0,
- tangentStart: ps.dragTangent ?? { x: 0, y: 0 },
- tangentEnd: { x: 0, y: 0 }
- })
- penCommit(true)
- return
- }
-
- // Add new vertex and segment from previous
- ps.vertices.push({ x, y })
- const newIdx = ps.vertices.length - 1
- ps.segments.push({
- start: prevIdx,
- end: newIdx,
- tangentStart: ps.dragTangent ?? { x: 0, y: 0 },
- tangentEnd: { x: 0, y: 0 }
- })
- ps.dragTangent = null
- requestRender()
- }
-
- function penSetDragTangent(tx: number, ty: number) {
- if (!state.penState) return
- state.penState.dragTangent = { x: tx, y: ty }
-
- // Also set the tangentStart on the last segment (the one being dragged)
- const ps = state.penState
- if (ps.segments.length > 0) {
- const lastSeg = ps.segments[ps.segments.length - 1]
- lastSeg.tangentEnd = { x: -tx, y: -ty }
- }
- requestRender()
- }
-
- function penSetClosingToFirst(closing: boolean) {
- if (!state.penState) return
- state.penState.closingToFirst = closing
- requestRender()
- }
-
- function penCommit(closed: boolean) {
- const ps = state.penState
- if (!ps || ps.vertices.length < 2) {
- state.penState = null
- state.penCursorX = null
- state.penCursorY = null
- return
- }
-
- const regions: VectorRegion[] = closed
- ? [{ windingRule: 'NONZERO', loops: [ps.segments.map((_, i) => i)] }]
- : []
-
- const network: VectorNetwork = {
- vertices: ps.vertices,
- segments: ps.segments,
- regions
- }
-
- const bounds = computeVectorBounds(network)
-
- // Normalize vertices relative to bounds origin
- const normalizedVertices = network.vertices.map((v) => ({
- ...v,
- x: v.x - bounds.x,
- y: v.y - bounds.y
- }))
-
- const normalizedNetwork: VectorNetwork = {
- vertices: normalizedVertices,
- segments: network.segments,
- regions: network.regions
- }
-
- const nodeId = createShape('VECTOR', bounds.x, bounds.y, bounds.width, bounds.height)
- updateNode(nodeId, {
- vectorNetwork: normalizedNetwork,
- name: 'Vector',
- fills: closed ? [{ ...DEFAULT_SHAPE_FILL }] : [],
- strokes: closed
- ? []
- : [
- {
- color: { r: 0, g: 0, b: 0, a: 1 },
- weight: 2,
- opacity: 1,
- visible: true,
- align: 'CENTER' as const
- }
- ]
- })
- select([nodeId])
-
- state.penState = null
- state.penCursorX = null
- state.penCursorY = null
- state.activeTool = 'SELECT'
- requestRender()
- }
-
- function penCancel() {
- state.penState = null
- state.penCursorX = null
- state.penCursorY = null
- state.activeTool = 'SELECT'
- requestRender()
- }
-
- function startTextEditing(nodeId: string) {
- if (state.editingTextId) commitTextEdit()
- const node = graph.getNode(nodeId)
- if (!node) return
- state.editingTextId = nodeId
- if (_textEditor) {
- _textEditor.setRenderer(_renderer)
- _textEditor.start(node)
- }
- requestRender()
- }
+ // ─── File I/O ─────────────────────────────────────────────────
- function commitTextEdit() {
- if (!_textEditor?.isActive) {
- state.editingTextId = null
- return
- }
- const result = _textEditor.stop()
- if (!result) {
- state.editingTextId = null
- requestRender()
- return
- }
- const node = graph.getNode(result.nodeId)
- const prevText = node?.text ?? ''
- const newText = result.text
- graph.updateNode(result.nodeId, { text: newText })
- state.editingTextId = null
- if (prevText !== newText) {
- undo.push({
- label: 'Edit text',
- forward: () => {
- graph.updateNode(result.nodeId, { text: newText })
- },
- inverse: () => {
- graph.updateNode(result.nodeId, { text: prevText })
- }
- })
- }
+ function downloadBlob(data: Uint8Array, filename: string, mime: string) {
+ const blob = new Blob([data.buffer as ArrayBuffer], { type: mime })
+ const url = URL.createObjectURL(blob)
+ const a = document.createElement('a')
+ a.href = url
+ a.download = filename
+ a.style.display = 'none'
+ document.body.appendChild(a)
+ a.click()
+ setTimeout(() => {
+ document.body.removeChild(a)
+ URL.revokeObjectURL(url)
+ }, 100)
}
function yieldToUI(): Promise<void> {
@@ -707,25 +187,23 @@ export function createEditorStore() {
await yieldToUI()
const imported = await readFigFile(file)
await yieldToUI()
- graph = imported
- computeAllLayouts(graph)
- subscribeToGraph()
- undo.clear()
- pageViewports.clear()
+ editor.replaceGraph(imported)
+ computeAllLayouts(editor.graph)
+ editor.undo.clear()
fileHandle = handle ?? null
filePath = path ?? null
state.documentName = file.name.replace(/\.fig$/i, '')
downloadName = file.name
state.selectedIds = new Set()
- const firstPage = graph.getPages()[0] as SceneNode | undefined
- const pageId = firstPage?.id ?? graph.rootId
+ const firstPage = editor.graph.getPages()[0] as SceneNode | undefined
+ const pageId = firstPage?.id ?? editor.graph.rootId
state.currentPageId = pageId
state.panX = 0
state.panY = 0
state.zoom = 1
state.pageColor = { ...CANVAS_BG_COLOR }
- await loadFontsForNodes(graph.getChildren(pageId).map((n) => n.id))
- requestRender()
+ await editor.loadFontsForNodes(editor.graph.getChildren(pageId).map((n) => n.id))
+ editor.requestRender()
void startWatchingFile()
} catch (e) {
console.error('Failed to open .fig file:', e)
@@ -735,15 +213,8 @@ export function createEditorStore() {
}
}
- function setCanvasKit(ck: CanvasKit, renderer: SkiaRenderer) {
- _ck = ck
- _renderer = renderer
- _textEditor = new TextEditor(ck)
- setTextMeasurer((node, maxWidth) => renderer.measureTextNode(node, maxWidth))
- }
-
function buildFigFile() {
- return exportFigFile(graph, _ck ?? undefined, _renderer ?? undefined, state.currentPageId)
+ return exportFigFile(editor.graph, undefined, editor.renderer ?? undefined, state.currentPageId)
}
async function saveFigFile() {
@@ -835,31 +306,29 @@ export function createEditorStore() {
const blob = new Blob([bytes])
const file = new File([blob], state.documentName + '.fig')
const imported = await readFigFile(file)
- graph = imported
- computeAllLayouts(graph)
- subscribeToGraph()
+ editor.replaceGraph(imported)
+ computeAllLayouts(editor.graph)
} else if (fileHandle) {
const file = await fileHandle.getFile()
const imported = await readFigFile(file)
- graph = imported
- computeAllLayouts(graph)
- subscribeToGraph()
+ editor.replaceGraph(imported)
+ computeAllLayouts(editor.graph)
} else {
return
}
- undo.clear()
+ editor.undo.clear()
savedVersion = state.sceneVersion
state.selectedIds = new Set()
- if (graph.getNode(pageId)) {
+ if (editor.graph.getNode(pageId)) {
state.currentPageId = pageId
} else {
- state.currentPageId = graph.getPages()[0]?.id ?? graph.rootId
+ state.currentPageId = editor.graph.getPages()[0]?.id ?? editor.graph.rootId
}
state.panX = viewport.panX
state.panY = viewport.panY
state.zoom = viewport.zoom
- requestRender()
+ editor.requestRender()
}
function stopWatchingFile() {
@@ -908,16 +377,22 @@ export function createEditorStore() {
}
}
+ // ─── Export ───────────────────────────────────────────────────
+
async function renderExportImage(
nodeIds: string[],
scale: number,
format: ExportFormat
): Promise<Uint8Array | null> {
- if (!_ck || !_renderer) return null
+ const renderer = editor.renderer
+ if (!renderer) return null
const ids =
- nodeIds.length > 0 ? nodeIds : graph.getChildren(state.currentPageId).map((n) => n.id)
+ nodeIds.length > 0 ? nodeIds : editor.graph.getChildren(state.currentPageId).map((n) => n.id)
if (ids.length === 0) return null
- return renderNodesToImage(_ck, _renderer, graph, state.currentPageId, ids, { scale, format })
+ return renderNodesToImage(renderer.ck, renderer, editor.graph, state.currentPageId, ids, {
+ scale,
+ format
+ })
}
function exportImageExtension(format: ExportFormat): string {
@@ -946,14 +421,15 @@ export function createEditorStore() {
const ids = [...state.selectedIds]
if (format === 'SVG') {
- const nodeIds = ids.length > 0 ? ids : graph.getChildren(state.currentPageId).map((n) => n.id)
- const svgStr = renderNodesToSVG(graph, state.currentPageId, nodeIds)
+ const nodeIds =
+ ids.length > 0 ? ids : editor.graph.getChildren(state.currentPageId).map((n) => n.id)
+ const svgStr = renderNodesToSVG(editor.graph, state.currentPageId, nodeIds)
if (!svgStr) {
console.error('Export failed: renderNodesToSVG returned null')
return
}
const svgData = new TextEncoder().encode(svgStr)
- const node = ids.length === 1 ? graph.getNode(ids[0]) : undefined
+ const node = ids.length === 1 ? editor.graph.getNode(ids[0]) : undefined
const fileName = `${node?.name ?? 'Export'}.svg`
await saveExportedFile(svgData, fileName, 'SVG', '.svg', 'image/svg+xml')
return
@@ -967,7 +443,7 @@ export function createEditorStore() {
return
}
- const node = ids.length === 1 ? graph.getNode(ids[0]) : undefined
+ const node = ids.length === 1 ? editor.graph.getNode(ids[0]) : undefined
const baseName = node?.name ?? 'Export'
const ext = exportImageExtension(format)
const fileName = `${baseName}@${scale}x${ext}`
@@ -1016,823 +492,75 @@ export function createEditorStore() {
downloadBlob(data, fileName, mime)
}
- function runLayoutForNode(id: string) {
- const node = graph.getNode(id)
- if (!node) return
-
- if (node.layoutMode !== 'NONE') {
- computeLayout(graph, id)
- }
+ // ─── Images ───────────────────────────────────────────────────
- let parent = node.parentId ? graph.getNode(node.parentId) : undefined
- while (parent) {
- if (parent.layoutMode !== 'NONE') {
- computeLayout(graph, parent.id)
- }
- parent = parent.parentId ? graph.getNode(parent.parentId) : undefined
- }
- }
+ const IMAGE_MAX_DIMENSION = 4096
+ const IMAGE_GAP = 20
- // ─── Graph event subscriptions ────────────────────────────────
- // Microtask-batched component sync: collects mutated node IDs during a
- // synchronous block, deduplicates to unique ancestor components, then
- // calls syncInstances once per component in one microtask.
- let pendingComponentSync: Set<string> | null = null
-
- function flushComponentSync() {
- const ids = pendingComponentSync
- if (!ids) return
- pendingComponentSync = null
- const componentIds = new Set<string>()
- for (const id of ids) {
- let current = graph.getNode(id)
- while (current) {
- if (current.type === 'COMPONENT') {
- componentIds.add(current.id)
- break
- }
- current = current.parentId ? graph.getNode(current.parentId) : undefined
- }
- }
- for (const compId of componentIds) {
- graph.syncInstances(compId)
+ function decodeImageDimensions(bytes: Uint8Array): { w: number; h: number } | null {
+ const renderer = editor.renderer
+ if (!renderer) return null
+ const skImg = renderer.ck.MakeImageFromEncoded(bytes)
+ if (!skImg) return null
+ let w = skImg.width()
+ let h = skImg.height()
+ skImg.delete()
+ if (w > IMAGE_MAX_DIMENSION || h > IMAGE_MAX_DIMENSION) {
+ const ratio = Math.min(IMAGE_MAX_DIMENSION / w, IMAGE_MAX_DIMENSION / h)
+ w = Math.round(w * ratio)
+ h = Math.round(h * ratio)
}
- if (componentIds.size > 0) requestRender()
+ return { w, h }
}
- function scheduleComponentSync(nodeId: string) {
- if (!pendingComponentSync) {
- pendingComponentSync = new Set()
- queueMicrotask(flushComponentSync)
+ async function placeImageFiles(files: File[], cx: number, cy: number) {
+ const prepared: Array<{ bytes: Uint8Array; name: string; w: number; h: number }> = []
+ for (const file of files) {
+ const bytes = new Uint8Array(await file.arrayBuffer())
+ const dims = decodeImageDimensions(bytes)
+ if (dims) prepared.push({ bytes, name: file.name, ...dims })
}
- pendingComponentSync.add(nodeId)
- }
+ if (!prepared.length) return
- function onNodeUpdated(id: string, changes: Partial<SceneNode>) {
- if ('vectorNetwork' in changes) {
- _renderer?.invalidateVectorPath(id)
- }
- _renderer?.invalidateNodePicture(id)
- scheduleComponentSync(id)
- requestRender()
- }
-
- function onNodeStructureChanged(nodeId: string) {
- scheduleComponentSync(nodeId)
- requestRender()
- }
-
- function subscribeToGraph() {
- graph.emitter.on('node:updated', onNodeUpdated)
- graph.emitter.on('node:created', (node) => onNodeStructureChanged(node.id))
- graph.emitter.on('node:deleted', onNodeStructureChanged)
- graph.emitter.on('node:reparented', onNodeStructureChanged)
- graph.emitter.on('node:reordered', onNodeStructureChanged)
- }
-
- subscribeToGraph()
-
- function updateNode(id: string, changes: Partial<SceneNode>) {
- graph.updateNode(id, changes)
- runLayoutForNode(id)
- }
-
- function updateNodeWithUndo(id: string, changes: Partial<SceneNode>, label = 'Update') {
- const node = graph.getNode(id)
- if (!node) return
- const previous = Object.fromEntries(
- (Object.keys(changes) as (keyof SceneNode)[]).map((key) => [key, node[key]])
- ) as Partial<SceneNode>
- graph.updateNode(id, changes)
- runLayoutForNode(id)
- undo.push({
- label,
- forward: () => {
- graph.updateNode(id, changes)
- runLayoutForNode(id)
- },
- inverse: () => {
- graph.updateNode(id, previous)
- runLayoutForNode(id)
- }
- })
- }
-
- function setLayoutMode(id: string, mode: LayoutMode) {
- const node = graph.getNode(id)
- if (!node) return
-
- const previous: Partial<SceneNode> = {
- layoutMode: node.layoutMode,
- itemSpacing: node.itemSpacing,
- paddingTop: node.paddingTop,
- paddingRight: node.paddingRight,
- paddingBottom: node.paddingBottom,
- paddingLeft: node.paddingLeft,
- primaryAxisSizing: node.primaryAxisSizing,
- counterAxisSizing: node.counterAxisSizing,
- primaryAxisAlign: node.primaryAxisAlign,
- counterAxisAlign: node.counterAxisAlign,
- gridTemplateColumns: node.gridTemplateColumns,
- gridTemplateRows: node.gridTemplateRows,
- gridColumnGap: node.gridColumnGap,
- gridRowGap: node.gridRowGap,
- width: node.width,
- height: node.height
- }
-
- const updates: Partial<SceneNode> = { layoutMode: mode }
- if (mode === 'GRID' && node.layoutMode !== 'GRID') {
- const children = graph.getChildren(id)
- const cols = Math.max(2, Math.ceil(Math.sqrt(children.length)))
- const rows = Math.max(1, Math.ceil(children.length / cols))
- updates.gridTemplateColumns = Array.from({ length: cols }, () => ({
- sizing: 'FR' as const,
- value: 1
- }))
- updates.gridTemplateRows = Array.from({ length: rows }, () => ({
- sizing: 'FR' as const,
- value: 1
- }))
- updates.gridColumnGap = 0
- updates.gridRowGap = 0
- updates.primaryAxisSizing = 'FIXED'
- updates.counterAxisSizing = 'FIXED'
- if (node.primaryAxisSizing === 'HUG' || node.counterAxisSizing === 'HUG') {
- const maxChildW = Math.max(...children.map((c) => c.width), 100)
- const maxChildH = Math.max(...children.map((c) => c.height), 100)
- updates.width = maxChildW * cols
- updates.height = maxChildH * rows
- }
- updates.paddingTop = 0
- updates.paddingRight = 0
- updates.paddingBottom = 0
- updates.paddingLeft = 0
- } else if (mode !== 'NONE' && node.layoutMode === 'NONE') {
- updates.itemSpacing = 0
- updates.paddingTop = 0
- updates.paddingRight = 0
- updates.paddingBottom = 0
- updates.paddingLeft = 0
- updates.primaryAxisSizing = 'HUG'
- updates.counterAxisSizing = 'HUG'
- updates.primaryAxisAlign = 'MIN'
- updates.counterAxisAlign = 'MIN'
- }
-
- graph.updateNode(id, updates)
- if (mode !== 'NONE') computeLayout(graph, id)
- runLayoutForNode(id)
-
- const updated = graph.getNode(id)
- if (!updated) return
- const finalState = Object.fromEntries(
- (Object.keys(previous) as (keyof SceneNode)[]).map((key) => [key, updated[key]])
- ) as Partial<SceneNode>
-
- undo.push({
- label: mode === 'NONE' ? 'Remove auto layout' : 'Add auto layout',
- forward: () => {
- graph.updateNode(id, finalState)
- if (mode !== 'NONE') computeLayout(graph, id)
- runLayoutForNode(id)
- },
- inverse: () => {
- graph.updateNode(id, previous)
- runLayoutForNode(id)
- }
- })
- }
-
- function wrapInAutoLayout() {
- const nodes = selectedNodes.value
- if (nodes.length === 0) return
-
- const parentId = nodes[0].parentId ?? state.currentPageId
- const sameParent = nodes.every((n) => (n.parentId ?? state.currentPageId) === parentId)
- if (!sameParent) return
-
- const prevSelection = new Set(state.selectedIds)
- const origPositions = nodes.map((n) => ({ id: n.id, x: n.x, y: n.y, parentId }))
-
- let minX = Infinity
- let minY = Infinity
- let maxX = -Infinity
- let maxY = -Infinity
- for (const n of nodes) {
- const abs = graph.getAbsolutePosition(n.id)
- minX = Math.min(minX, abs.x)
- minY = Math.min(minY, abs.y)
- maxX = Math.max(maxX, abs.x + n.width)
- maxY = Math.max(maxY, abs.y + n.height)
- }
-
- const parentAbs = isTopLevel(parentId) ? { x: 0, y: 0 } : graph.getAbsolutePosition(parentId)
-
- const direction: LayoutMode =
- nodes.length <= 1 || maxY - minY > maxX - minX ? 'VERTICAL' : 'HORIZONTAL'
-
- const frame = graph.createNode('FRAME', parentId, {
- name: 'Frame',
- x: minX - parentAbs.x,
- y: minY - parentAbs.y,
- width: maxX - minX,
- height: maxY - minY,
- layoutMode: direction,
- primaryAxisSizing: 'HUG',
- counterAxisSizing: 'HUG',
- primaryAxisAlign: 'MIN',
- counterAxisAlign: 'MIN',
- fills: []
- })
- const frameId = frame.id
-
- const sortedIds = nodes
- .map((n) => ({ id: n.id, pos: graph.getAbsolutePosition(n.id) }))
- .sort((a, b) => a.pos.y - b.pos.y || a.pos.x - b.pos.x)
- .map((n) => n.id)
-
- for (const id of sortedIds) {
- graph.reparentNode(id, frameId)
- }
-
- computeLayout(graph, frameId)
- runLayoutForNode(frameId)
- state.selectedIds = new Set([frameId])
-
- undo.push({
- label: 'Wrap in auto layout',
- forward: () => {
- // Re-create frame and reparent
- const f = graph.createNode('FRAME', parentId, { ...frame })
- for (const n of origPositions) graph.reparentNode(n.id, f.id)
- computeLayout(graph, f.id)
- runLayoutForNode(f.id)
- state.selectedIds = new Set([f.id])
- },
- inverse: () => {
- // Move children back to original parent and delete frame
- for (const orig of origPositions) {
- graph.reparentNode(orig.id, orig.parentId)
- graph.updateNode(orig.id, { x: orig.x, y: orig.y })
- }
- graph.deleteNode(frameId)
- state.selectedIds = prevSelection
- }
- })
- }
-
- function groupSelected() {
- const nodes = selectedNodes.value
- if (nodes.length === 0) return
-
- const parentId = nodes[0].parentId ?? state.currentPageId
- const sameParent = nodes.every((n) => (n.parentId ?? state.currentPageId) === parentId)
- if (!sameParent) return
-
- const parent = graph.getNode(parentId)
- if (!parent) return
-
- const prevSelection = new Set(state.selectedIds)
- const nodeIds = nodes.map((n) => n.id)
- const origPositions = nodes.map((n) => ({ id: n.id, x: n.x, y: n.y }))
-
- // Bounding box from absolute positions
- let minX = Infinity
- let minY = Infinity
- let maxX = -Infinity
- let maxY = -Infinity
- for (const n of nodes) {
- const abs = graph.getAbsolutePosition(n.id)
- minX = Math.min(minX, abs.x)
- minY = Math.min(minY, abs.y)
- maxX = Math.max(maxX, abs.x + n.width)
- maxY = Math.max(maxY, abs.y + n.height)
- }
-
- const parentAbs = isTopLevel(parentId) ? { x: 0, y: 0 } : graph.getAbsolutePosition(parentId)
-
- // Insert group at the position of the topmost selected node
- const firstIndex = Math.min(...nodeIds.map((id) => parent.childIds.indexOf(id)))
-
- const group = graph.createNode('GROUP', parentId, {
- name: 'Group',
- x: minX - parentAbs.x,
- y: minY - parentAbs.y,
- width: maxX - minX,
- height: maxY - minY,
- fills: []
- })
- const groupId = group.id
-
- // Move group to the correct z-order position
- parent.childIds = parent.childIds.filter((id) => id !== groupId)
- parent.childIds.splice(firstIndex, 0, groupId)
-
- for (const n of nodes) {
- graph.reparentNode(n.id, groupId)
- }
-
- state.selectedIds = new Set([groupId])
-
- undo.push({
- label: 'Group',
- forward: () => {
- const g = graph.createNode('GROUP', parentId, { ...group })
- parent.childIds = parent.childIds.filter((id) => id !== g.id)
- parent.childIds.splice(firstIndex, 0, g.id)
- for (const n of origPositions) graph.reparentNode(n.id, g.id)
- state.selectedIds = new Set([g.id])
- },
- inverse: () => {
- for (const orig of origPositions) {
- graph.reparentNode(orig.id, parentId)
- graph.updateNode(orig.id, { x: orig.x, y: orig.y })
- }
- graph.deleteNode(groupId)
- state.selectedIds = prevSelection
- }
- })
- }
-
- function createComponentFromSelection() {
- const nodes = selectedNodes.value
- if (nodes.length === 0) return
-
- const prevSelection = new Set(state.selectedIds)
-
- if (nodes.length === 1) {
- const node = nodes[0]
- const prevType = node.type
-
- if (node.type === 'COMPONENT') return
-
- if (node.type === 'FRAME' || node.type === 'GROUP') {
- graph.updateNode(node.id, { type: 'COMPONENT' })
- state.selectedIds = new Set([node.id])
- undo.push({
- label: 'Create component',
- forward: () => {
- graph.updateNode(node.id, { type: 'COMPONENT' })
- state.selectedIds = new Set([node.id])
- },
- inverse: () => {
- graph.updateNode(node.id, { type: prevType })
- state.selectedIds = prevSelection
- }
- })
- return
- }
- }
-
- const parentId = nodes[0].parentId ?? state.currentPageId
- const sameParent = nodes.every((n) => (n.parentId ?? state.currentPageId) === parentId)
- if (!sameParent) return
-
- const parent = graph.getNode(parentId)
- if (!parent) return
-
- const nodeIds = nodes.map((n) => n.id)
- const origPositions = nodes.map((n) => ({ id: n.id, x: n.x, y: n.y }))
-
- let minX = Infinity
- let minY = Infinity
- let maxX = -Infinity
- let maxY = -Infinity
- for (const n of nodes) {
- const abs = graph.getAbsolutePosition(n.id)
- minX = Math.min(minX, abs.x)
- minY = Math.min(minY, abs.y)
- maxX = Math.max(maxX, abs.x + n.width)
- maxY = Math.max(maxY, abs.y + n.height)
- }
-
- const parentAbs = isTopLevel(parentId) ? { x: 0, y: 0 } : graph.getAbsolutePosition(parentId)
- const firstIndex = Math.min(...nodeIds.map((id) => parent.childIds.indexOf(id)))
-
- const component = graph.createNode('COMPONENT', parentId, {
- name: 'Component',
- x: minX - parentAbs.x,
- y: minY - parentAbs.y,
- width: maxX - minX,
- height: maxY - minY,
- fills: []
- })
- const componentId = component.id
-
- parent.childIds = parent.childIds.filter((id) => id !== componentId)
- parent.childIds.splice(firstIndex, 0, componentId)
-
- for (const n of nodes) {
- graph.reparentNode(n.id, componentId)
- }
-
- state.selectedIds = new Set([componentId])
-
- undo.push({
- label: 'Create component',
- forward: () => {
- const c = graph.createNode('COMPONENT', parentId, { ...component })
- parent.childIds = parent.childIds.filter((id) => id !== c.id)
- parent.childIds.splice(firstIndex, 0, c.id)
- for (const n of origPositions) graph.reparentNode(n.id, c.id)
- state.selectedIds = new Set([c.id])
- },
- inverse: () => {
- for (const orig of origPositions) {
- graph.reparentNode(orig.id, parentId)
- graph.updateNode(orig.id, { x: orig.x, y: orig.y })
- }
- graph.deleteNode(componentId)
- state.selectedIds = prevSelection
- }
- })
- }
-
- function createComponentSetFromComponents() {
- const nodes = selectedNodes.value
- if (nodes.length < 2) return
- if (!nodes.every((n) => n.type === 'COMPONENT')) return
-
- const parentId = nodes[0].parentId ?? state.currentPageId
- const sameParent = nodes.every((n) => (n.parentId ?? state.currentPageId) === parentId)
- if (!sameParent) return
-
- const parent = graph.getNode(parentId)
- if (!parent) return
-
- const prevSelection = new Set(state.selectedIds)
- const nodeIds = nodes.map((n) => n.id)
- const origPositions = nodes.map((n) => ({ id: n.id, x: n.x, y: n.y }))
-
- let minX = Infinity
- let minY = Infinity
- let maxX = -Infinity
- let maxY = -Infinity
- for (const n of nodes) {
- const abs = graph.getAbsolutePosition(n.id)
- minX = Math.min(minX, abs.x)
- minY = Math.min(minY, abs.y)
- maxX = Math.max(maxX, abs.x + n.width)
- maxY = Math.max(maxY, abs.y + n.height)
- }
-
- const padding = 40
- const parentAbs = isTopLevel(parentId) ? { x: 0, y: 0 } : graph.getAbsolutePosition(parentId)
- const firstIndex = Math.min(...nodeIds.map((id) => parent.childIds.indexOf(id)))
-
- const componentSet = graph.createNode('COMPONENT_SET', parentId, {
- name: nodes[0].name.split('/')[0]?.trim() || 'Component Set',
- x: minX - parentAbs.x - padding,
- y: minY - parentAbs.y - padding,
- width: maxX - minX + padding * 2,
- height: maxY - minY + padding * 2,
- fills: [
- { type: 'SOLID', color: { r: 0.96, g: 0.96, b: 0.96, a: 1 }, opacity: 1, visible: true }
- ]
- })
- const setId = componentSet.id
-
- parent.childIds = parent.childIds.filter((id) => id !== setId)
- parent.childIds.splice(firstIndex, 0, setId)
-
- for (const n of nodes) {
- graph.reparentNode(n.id, setId)
- }
-
- state.selectedIds = new Set([setId])
-
- undo.push({
- label: 'Create component set',
- forward: () => {
- const cs = graph.createNode('COMPONENT_SET', parentId, { ...componentSet })
- parent.childIds = parent.childIds.filter((id) => id !== cs.id)
- parent.childIds.splice(firstIndex, 0, cs.id)
- for (const n of origPositions) graph.reparentNode(n.id, cs.id)
- state.selectedIds = new Set([cs.id])
- },
- inverse: () => {
- for (const orig of origPositions) {
- graph.reparentNode(orig.id, parentId)
- graph.updateNode(orig.id, { x: orig.x, y: orig.y })
- }
- graph.deleteNode(setId)
- state.selectedIds = prevSelection
- }
- })
- }
-
- function createInstanceFromComponent(componentId: string, x?: number, y?: number) {
- const component = graph.getNode(componentId)
- if (component?.type !== 'COMPONENT') return null
-
- const parentId = component.parentId ?? state.currentPageId
- const instance = graph.createInstance(componentId, parentId, {
- x: x ?? component.x + component.width + 40,
- y: y ?? component.y
- })
- if (!instance) return null
-
- const instanceId = instance.id
- state.selectedIds = new Set([instanceId])
-
- undo.push({
- label: 'Create instance',
- forward: () => {
- graph.createInstance(componentId, parentId, { ...instance })
- state.selectedIds = new Set([instanceId])
- },
- inverse: () => {
- graph.deleteNode(instanceId)
- state.selectedIds = new Set([componentId])
- }
- })
- return instanceId
- }
-
- function detachInstance() {
- const node = selectedNode.value
- if (node?.type !== 'INSTANCE') return
-
- const prevComponentId = node.componentId
-
- graph.detachInstance(node.id)
- state.selectedIds = new Set([node.id])
-
- undo.push({
- label: 'Detach instance',
- forward: () => {
- graph.detachInstance(node.id)
- requestRender()
- },
- inverse: () => {
- graph.updateNode(node.id, { type: 'INSTANCE', componentId: prevComponentId, overrides: {} })
- }
- })
- }
-
- function goToMainComponent() {
- const node = selectedNode.value
- if (!node?.componentId) return
- const main = graph.getMainComponent(node.id)
- if (!main) return
-
- // Find which page the main component is on
- let current: SceneNode | undefined = main
- while (current && current.type !== 'CANVAS') {
- current = current.parentId ? graph.getNode(current.parentId) : undefined
- }
- if (current && current.id !== state.currentPageId) {
- void switchPage(current.id)
- }
-
- state.selectedIds = new Set([main.id])
-
- const abs = graph.getAbsolutePosition(main.id)
- const viewW = 800
- const viewH = 600
- state.panX = viewW / 2 - (abs.x + main.width / 2) * state.zoom
- state.panY = viewH / 2 - (abs.y + main.height / 2) * state.zoom
- requestRender()
- }
-
- function ungroupSelected() {
- const node = selectedNode.value
- if (node?.type !== 'GROUP') return
-
- const parentId = node.parentId ?? state.currentPageId
- const parent = graph.getNode(parentId)
- if (!parent) return
-
- const groupIndex = parent.childIds.indexOf(node.id)
- const childIds = [...node.childIds]
- const prevSelection = new Set(state.selectedIds)
- const origPositions = childIds.map((id) => {
- const child = graph.getNode(id)
- if (!child) return { id, x: 0, y: 0 }
- return { id, x: child.x, y: child.y }
- })
- const groupSnapshot = { ...node, childIds: [...node.childIds] }
-
- // Reparent children to the group's parent, preserving visual position
- for (let i = 0; i < childIds.length; i++) {
- graph.reparentNode(childIds[i], parentId)
- // Move to correct z-order (where the group was)
- parent.childIds = parent.childIds.filter((id) => id !== childIds[i])
- parent.childIds.splice(groupIndex + i, 0, childIds[i])
- }
-
- graph.deleteNode(node.id)
- state.selectedIds = new Set(childIds)
-
- undo.push({
- label: 'Ungroup',
- forward: () => {
- for (let i = 0; i < childIds.length; i++) {
- graph.reparentNode(childIds[i], parentId)
- parent.childIds = parent.childIds.filter((id) => id !== childIds[i])
- parent.childIds.splice(groupIndex + i, 0, childIds[i])
- }
- graph.deleteNode(node.id)
- state.selectedIds = new Set(childIds)
- },
- inverse: () => {
- const g = graph.createNode('GROUP', parentId, { ...groupSnapshot, childIds: [] })
- parent.childIds = parent.childIds.filter((id) => id !== g.id)
- parent.childIds.splice(groupIndex, 0, g.id)
- for (const orig of origPositions) {
- graph.reparentNode(orig.id, g.id)
- graph.updateNode(orig.id, { x: orig.x, y: orig.y })
- }
- state.selectedIds = prevSelection
- }
- })
- }
-
- function bringToFront() {
- for (const id of state.selectedIds) {
- const node = graph.getNode(id)
- if (!node?.parentId) continue
- const parent = graph.getNode(node.parentId)
- if (!parent) continue
- const idx = parent.childIds.indexOf(id)
- if (idx === parent.childIds.length - 1) continue
- parent.childIds = parent.childIds.filter((cid) => cid !== id)
- parent.childIds.push(id)
- }
- requestRender()
- }
-
- function sendToBack() {
- for (const id of state.selectedIds) {
- const node = graph.getNode(id)
- if (!node?.parentId) continue
- const parent = graph.getNode(node.parentId)
- if (!parent) continue
- const idx = parent.childIds.indexOf(id)
- if (idx === 0) continue
- parent.childIds = parent.childIds.filter((cid) => cid !== id)
- parent.childIds.unshift(id)
- }
- requestRender()
- }
-
- function toggleProfiler() {
- _renderer?.profiler.toggle()
- requestRepaint()
- }
-
- function toggleVisibility() {
- for (const id of state.selectedIds) {
- const node = graph.getNode(id)
- if (!node) continue
- graph.updateNode(id, { visible: !node.visible })
- }
- }
-
- function toggleLock() {
- for (const id of state.selectedIds) {
- const node = graph.getNode(id)
- if (!node) continue
- graph.updateNode(id, { locked: !node.locked })
- }
- }
-
- function moveToPage(pageId: string) {
- const targetPage = graph.getNode(pageId)
- if (targetPage?.type !== 'CANVAS') return
- const ids = [...state.selectedIds]
- for (const id of ids) {
- graph.reparentNode(id, pageId)
- }
- clearSelection()
- }
-
- function renameNode(id: string, name: string) {
- graph.updateNode(id, { name })
- }
-
- function createShape(
- type: NodeType,
- x: number,
- y: number,
- w: number,
- h: number,
- parentId?: string
- ): string {
- const fill = DEFAULT_FILLS[type] ?? DEFAULT_FILLS.RECTANGLE
- const pid = parentId ?? state.currentPageId
- const overrides: Partial<SceneNode> = {
- x,
- y,
- width: w,
- height: h,
- fills: [{ ...fill }]
- }
- if (type === 'SECTION') {
- overrides.strokes = [{ ...SECTION_DEFAULT_STROKE }]
- overrides.cornerRadius = 5
- }
- if (type === 'POLYGON') {
- overrides.pointCount = 3
- }
- if (type === 'STAR') {
- overrides.pointCount = 5
- overrides.starInnerRadius = 0.38
- }
- const node = graph.createNode(type, pid, overrides)
- const id = node.id
- const snapshot = { ...node }
- undo.push({
- label: `Create ${type.toLowerCase()}`,
- forward: () => {
- graph.createNode(snapshot.type, pid, snapshot)
- },
- inverse: () => {
- graph.deleteNode(id)
- const next = new Set(state.selectedIds)
- next.delete(id)
- state.selectedIds = next
- }
- })
- return id
- }
-
- const IMAGE_MAX_DIMENSION = 4096
- const IMAGE_GAP = 20
-
- async function placeImageFiles(files: File[], cx: number, cy: number) {
- if (!_ck) return
-
- const prepared: Array<{ bytes: Uint8Array; name: string; w: number; h: number }> = []
- for (const file of files) {
- const bytes = new Uint8Array(await file.arrayBuffer())
- const dims = decodeImageDimensions(bytes)
- if (dims) prepared.push({ bytes, name: file.name, ...dims })
- }
- if (!prepared.length) return
-
- let totalW = 0
- for (const p of prepared) totalW += p.w
- totalW += IMAGE_GAP * (prepared.length - 1)
- const maxH = Math.max(...prepared.map((p) => p.h))
+ let totalW = 0
+ for (const p of prepared) totalW += p.w
+ totalW += IMAGE_GAP * (prepared.length - 1)
+ const maxH = Math.max(...prepared.map((p) => p.h))
let curX = cx - totalW / 2
const topY = cy - maxH / 2
const ids: string[] = []
for (const p of prepared) {
- const id = await placeImageNode(p.bytes, curX, topY, p.w, p.h, p.name)
+ const id = placeImageNode(p.bytes, curX, topY, p.w, p.h, p.name)
if (id) ids.push(id)
curX += p.w + IMAGE_GAP
}
if (ids.length) {
- select(ids)
- requestRender()
+ editor.select(ids)
+ editor.requestRender()
}
}
- function decodeImageDimensions(bytes: Uint8Array): { w: number; h: number } | null {
- if (!_ck) return null
- const skImg = _ck.MakeImageFromEncoded(bytes)
- if (!skImg) return null
- let w = skImg.width()
- let h = skImg.height()
- skImg.delete()
- if (w > IMAGE_MAX_DIMENSION || h > IMAGE_MAX_DIMENSION) {
- const ratio = Math.min(IMAGE_MAX_DIMENSION / w, IMAGE_MAX_DIMENSION / h)
- w = Math.round(w * ratio)
- h = Math.round(h * ratio)
- }
- return { w, h }
- }
-
- function storeImage(bytes: Uint8Array): string {
- const hash = computeImageHash(bytes)
- graph.images.set(hash, bytes)
- return hash
- }
-
- async function placeImageNode(
+ function placeImageNode(
bytes: Uint8Array,
x: number,
y: number,
w: number,
h: number,
name = 'Image'
- ): Promise<string | null> {
- const hash = storeImage(bytes)
-
+ ): string | null {
+ const hash = editor.storeImage(bytes)
const displayName = name.replace(/\.[^.]+$/, '')
const pid = state.currentPageId
- const fill: Fill = {
- type: 'IMAGE',
+ const fill = {
+ type: 'IMAGE' as const,
imageHash: hash,
- imageScaleMode: 'FILL',
+ imageScaleMode: 'FILL' as const,
color: { r: 0, g: 0, b: 0, a: 0 },
opacity: 1,
visible: true
}
- const node = graph.createNode('RECTANGLE', pid, {
+ const node = editor.graph.createNode('RECTANGLE', pid, {
name: displayName,
x,
y,
@@ -1842,15 +570,15 @@ export function createEditorStore() {
})
const id = node.id
const snapshot = { ...node }
- undo.push({
+ editor.undo.push({
label: 'Place image',
forward: () => {
- graph.images.set(hash, bytes)
- graph.createNode(snapshot.type, pid, snapshot)
+ editor.graph.images.set(hash, bytes)
+ editor.graph.createNode(snapshot.type, pid, snapshot)
},
inverse: () => {
- graph.deleteNode(id)
- graph.images.delete(hash)
+ editor.graph.deleteNode(id)
+ editor.graph.images.delete(hash)
const next = new Set(state.selectedIds)
next.delete(id)
state.selectedIds = next
@@ -1859,625 +587,139 @@ export function createEditorStore() {
return id
}
- function adoptNodesIntoSection(sectionId: string) {
- const section = graph.getNode(sectionId)
- if (section?.type !== 'SECTION') return
-
- const parentId = section.parentId ?? state.currentPageId
- const siblings = graph.getChildren(parentId)
-
- const sx = section.x
- const sy = section.y
- const sx2 = sx + section.width
- const sy2 = sy + section.height
-
- const toAdopt: string[] = []
- for (const sibling of siblings) {
- if (sibling.id === sectionId) continue
- const nx = sibling.x
- const ny = sibling.y
- const nx2 = nx + sibling.width
- const ny2 = ny + sibling.height
- if (nx >= sx && ny >= sy && nx2 <= sx2 && ny2 <= sy2) {
- toAdopt.push(sibling.id)
- }
- }
-
- if (toAdopt.length === 0) return
-
- const undoOps: Array<{
- id: string
- oldParent: string
- oldX: number
- oldY: number
- newX: number
- newY: number
- }> = []
- for (const id of toAdopt) {
- const node = graph.getNode(id)
- if (!node) continue
- const newX = node.x - sx
- const newY = node.y - sy
- undoOps.push({ id, oldParent: parentId, oldX: node.x, oldY: node.y, newX, newY })
- graph.reparentNode(id, sectionId)
- graph.updateNode(id, { x: newX, y: newY })
- }
-
- undo.push({
- label: 'Adopt into section',
- forward: () => {
- for (const op of undoOps) {
- graph.reparentNode(op.id, sectionId)
- graph.updateNode(op.id, { x: op.newX, y: op.newY })
- }
- },
- inverse: () => {
- for (const op of undoOps) {
- graph.reparentNode(op.id, op.oldParent)
- graph.updateNode(op.id, { x: op.oldX, y: op.oldY })
- }
- }
- })
- }
-
- function selectAll() {
- const children = graph.getChildren(state.currentPageId)
- state.selectedIds = new Set(children.map((n) => n.id))
- }
-
- function duplicateSelected() {
- const prevSelection = new Set(state.selectedIds)
- const newIds: string[] = []
- const snapshots: Array<{ id: string; parentId: string; snapshot: SceneNode }> = []
-
- for (const id of state.selectedIds) {
- const src = graph.getNode(id)
- if (!src) continue
- const parentId = src.parentId ?? state.currentPageId
- const { id: _srcId, parentId: _srcParent, childIds: _srcChildren, ...srcRest } = src
- const node = graph.createNode(src.type, parentId, {
- ...srcRest,
- name: src.name + ' copy',
- x: src.x + 20,
- y: src.y + 20
- })
- newIds.push(node.id)
- snapshots.push({ id: node.id, parentId, snapshot: { ...node } })
- }
-
- if (newIds.length > 0) {
- state.selectedIds = new Set(newIds)
- undo.push({
- label: 'Duplicate',
- forward: () => {
- for (const { snapshot, parentId } of snapshots) {
- graph.createNode(snapshot.type, parentId, snapshot)
- }
- state.selectedIds = new Set(newIds)
- },
- inverse: () => {
- for (const { id } of snapshots) graph.deleteNode(id)
- state.selectedIds = prevSelection
- }
- })
- }
- }
-
- function writeCopyData(clipboardData: DataTransfer) {
- const nodes = selectedNodes.value
- if (nodes.length === 0) return
-
- const names = nodes.map((n) => n.name).join('\n')
- const html = buildFigmaClipboardHTML(nodes, graph)
- if (html) clipboardData.setData('text/html', html)
- clipboardData.setData('text/plain', names)
- }
-
- function centerNodesAt(nodeIds: string[], cx: number, cy: number) {
- let minX = Infinity
- let minY = Infinity
- let maxX = -Infinity
- let maxY = -Infinity
- for (const id of nodeIds) {
- const n = graph.getNode(id)
- if (!n) continue
- minX = Math.min(minX, n.x)
- minY = Math.min(minY, n.y)
- maxX = Math.max(maxX, n.x + n.width)
- maxY = Math.max(maxY, n.y + n.height)
- }
- if (minX === Infinity) return
- const dx = cx - (minX + maxX) / 2
- const dy = cy - (minY + maxY) / 2
- for (const id of nodeIds) {
- const n = graph.getNode(id)
- if (n) graph.updateNode(id, { x: n.x + dx, y: n.y + dy })
- }
- }
-
- function collectSubtrees(g: SceneGraph, rootIds: string[]): SceneNode[] {
- const result: SceneNode[] = []
- function walk(id: string) {
- const node = g.getNode(id)
- if (!node) return
- result.push({ ...node })
- for (const childId of node.childIds) walk(childId)
- }
- for (const id of rootIds) walk(id)
- return result
- }
-
- async function loadFontsForNodes(nodeIds: string[]) {
- const toLoad = collectFontKeys(graph, nodeIds)
- if (toLoad.length === 0) return
-
- const results = await Promise.all(toLoad.map(([family, style]) => loadFont(family, style)))
- const failed = toLoad.filter((_, i) => results[i] === null)
- if (failed.length > 0) {
- const families = [...new Set(failed.map(([family]) => family))]
- toast.show(
- families.length === 1
- ? `Font "${families[0]}" could not be loaded`
- : `${families.length} fonts could not be loaded: ${families.join(', ')}`,
- 'warning'
- )
- }
- computeAllLayouts(graph, state.currentPageId)
- }
-
- function pasteFromHTML(html: string, cursorPos?: Vector) {
- void parseFigmaClipboard(html).then((figma) => {
- if (figma) {
- const prevSelection = new Set(state.selectedIds)
- const created = importClipboardNodes(
- figma.nodes,
- graph,
- state.currentPageId,
- 0,
- 0,
- figma.blobs
- )
- if (created.length > 0) {
- const cx = cursorPos?.x ?? (-state.panX + window.innerWidth / 2) / state.zoom
- const cy = cursorPos?.y ?? (-state.panY + window.innerHeight / 2) / state.zoom
- centerNodesAt(created, cx, cy)
- computeAllLayouts(graph, state.currentPageId)
- state.selectedIds = new Set(created)
-
- const allNodes = collectSubtrees(graph, created)
- const pageId = state.currentPageId
- undo.push({
- label: 'Paste',
- forward: () => {
- for (const snapshot of allNodes) {
- graph.createNode(snapshot.type, snapshot.parentId ?? pageId, {
- ...snapshot,
- childIds: []
- })
- }
- computeAllLayouts(graph, pageId)
- state.selectedIds = new Set(created)
- },
- inverse: () => {
- for (const id of [...created].reverse()) graph.deleteNode(id)
- computeAllLayouts(graph, pageId)
- state.selectedIds = prevSelection
- }
- })
- void loadFontsForNodes(created)
- warnMissingImages(created)
- }
- }
- })
- }
-
- function warnMissingImages(nodeIds: string[]) {
- const allNodes = collectSubtrees(graph, nodeIds)
- const hasMissing = allNodes.some((n) =>
- n.fills.some((f) => f.type === 'IMAGE' && f.imageHash && !graph.images.has(f.imageHash))
- )
- if (hasMissing) {
- toast.show(
- "Some images couldn't be pasted — Figma doesn't include image data in clipboard",
- 'warning'
- )
- }
- }
-
- function deleteSelected() {
- const entries: Array<{ id: string; parentId: string; snapshot: SceneNode; index: number }> = []
- for (const id of state.selectedIds) {
- const node = graph.getNode(id)
- if (!node || node.locked) continue
- const parentId = node.parentId ?? state.currentPageId
- const parent = graph.getNode(parentId)
- const index = parent?.childIds.indexOf(id) ?? -1
- entries.push({ id, parentId, snapshot: { ...node }, index })
- }
- if (entries.length === 0) return
-
- const prevSelection = new Set(state.selectedIds)
- for (const { id } of entries) graph.deleteNode(id)
-
- undo.push({
- label: 'Delete',
- forward: () => {
- for (const { id } of entries) graph.deleteNode(id)
- clearSelection()
- },
- inverse: () => {
- for (const { snapshot, parentId, index } of [...entries].reverse()) {
- graph.createNode(snapshot.type, parentId, snapshot)
- if (index >= 0) {
- graph.reorderChild(snapshot.id, parentId, index)
- }
- }
- state.selectedIds = prevSelection
- }
- })
- clearSelection()
- }
+ // ─── Mobile clipboard ─────────────────────────────────────────
function mobileCopy() {
const transfer = new DataTransfer()
- writeCopyData(transfer)
+ editor.writeCopyData(transfer)
state.clipboardHtml = transfer.getData('text/html')
}
function mobileCut() {
mobileCopy()
- deleteSelected()
+ editor.deleteSelected()
}
function mobilePaste() {
if (state.clipboardHtml) {
- pasteFromHTML(state.clipboardHtml)
- }
- }
-
- function commitMove(originals: Map<string, Vector>) {
- const finals = new Map<string, Vector>()
- for (const [id] of originals) {
- const n = graph.getNode(id)
- if (n) finals.set(id, { x: n.x, y: n.y })
- }
- undo.push({
- label: 'Move',
- forward: () => {
- for (const [id, pos] of finals) {
- graph.updateNode(id, pos)
- runLayoutForNode(id)
- }
- },
- inverse: () => {
- for (const [id, pos] of originals) {
- graph.updateNode(id, pos)
- runLayoutForNode(id)
- }
- }
- })
- }
-
- function commitMoveWithReparent(
- originals: Map<string, { x: number; y: number; parentId: string }>
- ) {
- const finals = new Map<string, { x: number; y: number; parentId: string }>()
- for (const [id] of originals) {
- const n = graph.getNode(id)
- if (n) finals.set(id, { x: n.x, y: n.y, parentId: n.parentId ?? state.currentPageId })
+ editor.pasteFromHTML(state.clipboardHtml)
}
- undo.push({
- label: 'Move',
- forward: () => {
- for (const [id, pos] of finals) {
- graph.reparentNode(id, pos.parentId)
- graph.updateNode(id, { x: pos.x, y: pos.y })
- runLayoutForNode(id)
- }
- },
- inverse: () => {
- for (const [id, pos] of originals) {
- graph.reparentNode(id, pos.parentId)
- graph.updateNode(id, { x: pos.x, y: pos.y })
- runLayoutForNode(id)
- }
- }
- })
- }
-
- function snapshotPage(): Map<string, SceneNode> {
- const snapshot = new Map<string, SceneNode>()
- const walk = (id: string) => {
- const node = graph.getNode(id)
- if (!node) return
- snapshot.set(id, structuredClone(node))
- for (const childId of node.childIds) walk(childId)
- }
- walk(state.currentPageId)
- return snapshot
}
- function restorePageFromSnapshot(snapshot: Map<string, SceneNode>) {
- const page = graph.getNode(state.currentPageId)
- if (!page) return
-
- for (const childId of page.childIds.slice()) {
- graph.deleteNode(childId)
- }
+ // ─── Profiler toggle ─────────────────────────────────────────
- const pageSnap = snapshot.get(state.currentPageId)
- if (pageSnap) page.childIds = [...pageSnap.childIds]
-
- for (const [id, snap] of snapshot) {
- if (id === state.currentPageId) continue
- graph.nodes.set(id, structuredClone(snap))
- }
-
- graph.clearAbsPosCache()
- computeAllLayouts(graph, state.currentPageId)
- state.selectedIds = new Set()
- state.hoveredNodeId = null
- requestRender()
- }
-
- function pushUndoEntry(entry: UndoEntry) {
- undo.push(entry)
- }
-
- function commitResize(nodeId: string, origRect: Rect) {
- const node = graph.getNode(nodeId)
- if (!node) return
- const finalRect = { x: node.x, y: node.y, width: node.width, height: node.height }
- undo.push({
- label: 'Resize',
- forward: () => {
- graph.updateNode(nodeId, finalRect)
- runLayoutForNode(nodeId)
- },
- inverse: () => {
- graph.updateNode(nodeId, origRect)
- runLayoutForNode(nodeId)
- }
- })
- }
-
- function commitRotation(nodeId: string, origRotation: number) {
- const node = graph.getNode(nodeId)
- if (!node) return
- const finalRotation = node.rotation
- undo.push({
- label: 'Rotate',
- forward: () => {
- graph.updateNode(nodeId, { rotation: finalRotation })
- },
- inverse: () => {
- graph.updateNode(nodeId, { rotation: origRotation })
- }
- })
- }
-
- function commitNodeUpdate(nodeId: string, previous: Partial<SceneNode>, label = 'Update') {
- const node = graph.getNode(nodeId)
- if (!node) return
- const current = Object.fromEntries(
- (Object.keys(previous) as (keyof SceneNode)[]).map((key) => [key, node[key]])
- ) as Partial<SceneNode>
- undo.push({
- label,
- forward: () => {
- graph.updateNode(nodeId, current)
- runLayoutForNode(nodeId)
- },
- inverse: () => {
- graph.updateNode(nodeId, previous)
- runLayoutForNode(nodeId)
- }
- })
- }
-
- function undoAction() {
- undo.undo()
- validateEnteredContainer()
- }
-
- function redoAction() {
- undo.redo()
- validateEnteredContainer()
- requestRender()
- }
-
- function screenToCanvas(sx: number, sy: number) {
- return {
- x: (sx - state.panX) / state.zoom,
- y: (sy - state.panY) / state.zoom
- }
- }
-
- function applyZoom(delta: number, centerX: number, centerY: number) {
- const factor = Math.min(
- ZOOM_SCALE_MAX,
- Math.max(ZOOM_SCALE_MIN, Math.exp(-delta / ZOOM_DIVISOR))
- )
- const newZoom = Math.max(0.02, Math.min(256, state.zoom * factor))
- state.panX = centerX - (centerX - state.panX) * (newZoom / state.zoom)
- state.panY = centerY - (centerY - state.panY) * (newZoom / state.zoom)
- state.zoom = newZoom
- requestRepaint()
- }
-
- function pan(dx: number, dy: number) {
- state.panX += dx
- state.panY += dy
- requestRepaint()
- }
-
- function zoomToBounds(minX: number, minY: number, maxX: number, maxY: number) {
- const padding = 80
- const w = maxX - minX + padding * 2
- const h = maxY - minY + padding * 2
-
- const viewW = window.innerWidth
- const viewH = window.innerHeight
- const zoom = Math.min(viewW / w, viewH / h, 1)
-
- state.zoom = zoom
- state.panX = (viewW - w * zoom) / 2 - minX * zoom + padding * zoom
- state.panY = (viewH - h * zoom) / 2 - minY * zoom + padding * zoom
- requestRepaint()
- }
-
- function zoomToFit() {
- const nodes = graph.getChildren(state.currentPageId)
- if (nodes.length === 0) return
-
- let minX = Infinity
- let minY = Infinity
- let maxX = -Infinity
- let maxY = -Infinity
- for (const n of nodes) {
- minX = Math.min(minX, n.x)
- minY = Math.min(minY, n.y)
- maxX = Math.max(maxX, n.x + n.width)
- maxY = Math.max(maxY, n.y + n.height)
- }
-
- zoomToBounds(minX, minY, maxX, maxY)
- }
-
- function zoomTo100() {
- const viewW = window.innerWidth
- const viewH = window.innerHeight
- const centerX = (-state.panX + viewW / 2) / state.zoom
- const centerY = (-state.panY + viewH / 2) / state.zoom
-
- state.zoom = 1
- state.panX = viewW / 2 - centerX
- state.panY = viewH / 2 - centerY
- requestRepaint()
+ function toggleProfiler() {
+ editor.renderer?.profiler.toggle()
+ editor.requestRepaint()
}
- function zoomToSelection() {
- if (state.selectedIds.size === 0) return
-
- let minX = Infinity
- let minY = Infinity
- let maxX = -Infinity
- let maxY = -Infinity
- for (const id of state.selectedIds) {
- const n = graph.getNode(id)
- if (!n) continue
- const abs = graph.getAbsolutePosition(id)
- minX = Math.min(minX, abs.x)
- minY = Math.min(minY, abs.y)
- maxX = Math.max(maxX, abs.x + n.width)
- maxY = Math.max(maxY, abs.y + n.height)
- }
- if (minX === Infinity) return
-
- zoomToBounds(minX, minY, maxX, maxY)
- }
+ // ─── Public API ───────────────────────────────────────────────
return {
get graph() {
- return graph
+ return editor.graph
},
get renderer() {
- return _renderer
+ return editor.renderer
},
get textEditor() {
- return _textEditor
+ return editor.textEditor
},
- undo,
+ undo: editor.undo,
state,
selectedNodes,
selectedNode,
layerTree,
- requestRender,
- requestRepaint,
+
+ // Core editor methods
+ requestRender: editor.requestRender,
+ requestRepaint: editor.requestRepaint,
+ setCanvasKit: editor.setCanvasKit,
+ isTopLevel: editor.isTopLevel,
+ switchPage: editor.switchPage,
+ addPage: editor.addPage,
+ deletePage: editor.deletePage,
+ renamePage: editor.renamePage,
+ setTool: editor.setTool,
+ select: editor.select,
+ clearSelection: editor.clearSelection,
+ enterContainer: editor.enterContainer,
+ exitContainer: editor.exitContainer,
+ validateEnteredContainer: editor.validateEnteredContainer,
+ selectAll: editor.selectAll,
+ setMarquee: editor.setMarquee,
+ setSnapGuides: editor.setSnapGuides,
+ setRotationPreview: editor.setRotationPreview,
+ setHoveredNode: editor.setHoveredNode,
+ setDropTarget: editor.setDropTarget,
+ setLayoutInsertIndicator: editor.setLayoutInsertIndicator,
+ reorderInAutoLayout: editor.reorderInAutoLayout,
+ reorderChildWithUndo: editor.reorderChildWithUndo,
+ reparentNodes: editor.reparentNodes,
+ penAddVertex: editor.penAddVertex,
+ penSetDragTangent: editor.penSetDragTangent,
+ penSetClosingToFirst: editor.penSetClosingToFirst,
+ penCommit: editor.penCommit,
+ penCancel: editor.penCancel,
+ startTextEditing: editor.startTextEditing,
+ commitTextEdit: editor.commitTextEdit,
+ updateNode: editor.updateNode,
+ updateNodeWithUndo: editor.updateNodeWithUndo,
+ setLayoutMode: editor.setLayoutMode,
+ wrapInAutoLayout: editor.wrapInAutoLayout,
+ groupSelected: editor.groupSelected,
+ ungroupSelected: editor.ungroupSelected,
+ createComponentFromSelection: editor.createComponentFromSelection,
+ createComponentSetFromComponents: editor.createComponentSetFromComponents,
+ createInstanceFromComponent: editor.createInstanceFromComponent,
+ detachInstance: editor.detachInstance,
+ goToMainComponent: editor.goToMainComponent,
+ bringToFront: editor.bringToFront,
+ sendToBack: editor.sendToBack,
+ toggleVisibility: editor.toggleVisibility,
+ toggleLock: editor.toggleLock,
+ moveToPage: editor.moveToPage,
+ renameNode: editor.renameNode,
+ createShape: editor.createShape,
+ adoptNodesIntoSection: editor.adoptNodesIntoSection,
+ duplicateSelected: editor.duplicateSelected,
+ writeCopyData: editor.writeCopyData,
+ pasteFromHTML: editor.pasteFromHTML,
+ deleteSelected: editor.deleteSelected,
+ commitMove: editor.commitMove,
+ commitMoveWithReparent: editor.commitMoveWithReparent,
+ commitResize: editor.commitResize,
+ commitRotation: editor.commitRotation,
+ commitNodeUpdate: editor.commitNodeUpdate,
+ undoAction: editor.undoAction,
+ redoAction: editor.redoAction,
+ snapshotPage: editor.snapshotPage,
+ restorePageFromSnapshot: editor.restorePageFromSnapshot,
+ pushUndoEntry: editor.pushUndoEntry,
+ screenToCanvas: editor.screenToCanvas,
+ applyZoom: editor.applyZoom,
+ pan: editor.pan,
+ zoomToFit: editor.zoomToFit,
+ zoomTo100: editor.zoomTo100,
+ zoomToSelection: editor.zoomToSelection,
+ storeImage: editor.storeImage,
+
+ // App-specific methods
flashNodes,
aiMarkActive,
aiMarkDone,
aiFlashDone,
aiClearAll,
- setTool,
- select,
- clearSelection,
- enterContainer,
- exitContainer,
- validateEnteredContainer,
- selectAll,
- setMarquee,
- setSnapGuides,
- setRotationPreview,
- setHoveredNode,
- setDropTarget,
- setLayoutInsertIndicator,
- reorderInAutoLayout,
- reparentNodes,
- reorderChildWithUndo,
- penAddVertex,
- penSetDragTangent,
- penSetClosingToFirst,
- penCommit,
- penCancel,
- startTextEditing,
- commitTextEdit,
+ toggleProfiler,
openFigFile,
saveFigFile,
- setCanvasKit,
saveFigFileAs,
renderExportImage,
exportSelection,
- updateNode,
- setLayoutMode,
- wrapInAutoLayout,
- groupSelected,
- ungroupSelected,
- createComponentFromSelection,
- createComponentSetFromComponents,
- createInstanceFromComponent,
- detachInstance,
- goToMainComponent,
- bringToFront,
- sendToBack,
- toggleProfiler,
- toggleVisibility,
- toggleLock,
- moveToPage,
- renameNode,
- createShape,
- storeImage,
placeImageFiles,
- adoptNodesIntoSection,
- duplicateSelected,
- writeCopyData,
- pasteFromHTML,
mobileCopy,
mobileCut,
- mobilePaste,
- deleteSelected,
- commitMove,
- commitMoveWithReparent,
- commitResize,
- commitRotation,
- commitNodeUpdate,
- updateNodeWithUndo,
- undoAction,
- redoAction,
- snapshotPage,
- restorePageFromSnapshot,
- pushUndoEntry,
- screenToCanvas,
- applyZoom,
- pan,
- zoomToFit,
- zoomTo100,
- zoomToSelection,
- isTopLevel,
- switchPage,
- addPage,
- deletePage,
- renamePage
+ mobilePaste
}
}