Skip to content

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

AI chat rendering, undo, visual verification, and provider compatibility

Danila Poyarkove3ab8dab38d6
diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.ts
index cf63416c5..a66e65cb8 100644
--- a/packages/core/src/constants.ts
+++ b/packages/core/src/constants.ts
@@ -93,6 +93,7 @@ export type AIProviderID =
| 'openai'
| 'google'
| 'openai-compatible'
+ | 'anthropic-compatible'
export interface ModelOption {
id: string
@@ -179,6 +180,16 @@ export const AI_PROVIDERS: AIProviderDef[] = [
models: [],
supportsCustomBaseURL: true,
supportsCustomModel: true
+ },
+ {
+ id: 'anthropic-compatible',
+ name: 'Anthropic-compatible',
+ keyPlaceholder: 'API key',
+ keyURL: '',
+ defaultModel: '',
+ models: [],
+ supportsCustomBaseURL: true,
+ supportsCustomModel: true
}
]
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 1efa040f8..14758ea05 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -114,7 +114,7 @@ export {
computeVectorBounds
} from './vector'
export { computeSelectionBounds, computeSnap, type SnapGuide } from './snap'
-export { UndoManager } from './undo'
+export { UndoManager, type UndoEntry } from './undo'
export { TextEditor, type TextCaret, type TextEditorState } from './text-editor'
export {
getStyleAt,
diff --git a/packages/core/src/layout.ts b/packages/core/src/layout.ts
index db7603b03..bd3740b3c 100644
--- a/packages/core/src/layout.ts
+++ b/packages/core/src/layout.ts
@@ -7,6 +7,7 @@ import Yoga, {
Gutter,
Justify,
Edge,
+ Overflow,
Wrap,
type Node as YogaNode
} from 'yoga-layout'
@@ -140,6 +141,7 @@ function buildYogaTree(graph: SceneGraph, frame: SceneNode): YogaNode {
root.setFlexWrap(frame.layoutWrap === 'WRAP' ? Wrap.Wrap : Wrap.NoWrap)
root.setJustifyContent(mapJustify(frame.primaryAxisAlign))
root.setAlignItems(mapAlign(frame.counterAxisAlign))
+ if (frame.clipsContent) root.setOverflow(Overflow.Hidden)
root.setPadding(Edge.Top, frame.paddingTop)
root.setPadding(Edge.Right, frame.paddingRight)
@@ -230,6 +232,7 @@ function configureChildAsAutoLayout(
yogaChild.setFlexWrap(child.layoutWrap === 'WRAP' ? Wrap.Wrap : Wrap.NoWrap)
yogaChild.setJustifyContent(mapJustify(child.primaryAxisAlign))
yogaChild.setAlignItems(mapAlign(child.counterAxisAlign))
+ if (child.clipsContent) yogaChild.setOverflow(Overflow.Hidden)
yogaChild.setPadding(Edge.Top, child.paddingTop)
yogaChild.setPadding(Edge.Right, child.paddingRight)
@@ -264,12 +267,13 @@ function configureChildAsLeaf(yogaChild: YogaNode, child: SceneNode, parent: Sce
const isRow = parent.layoutMode === 'HORIZONTAL'
const stretchCross = child.layoutAlignSelf === 'STRETCH' || parent.counterAxisAlign === 'STRETCH'
- const measured =
- child.type === 'TEXT' && child.textAutoResize === 'WIDTH_AND_HEIGHT'
- ? measureTextSize(child)
- : null
- const w = measured ? measured.width : child.width
- const h = child.height
+ const isText = child.type === 'TEXT'
+ const autoW = isText && child.textAutoResize === 'WIDTH_AND_HEIGHT'
+ const autoH = isText && (child.textAutoResize === 'HEIGHT' || child.textAutoResize === 'WIDTH_AND_HEIGHT')
+
+ const measured = (autoW || autoH) ? measureTextSize(child) : null
+ const w = autoW && measured ? measured.width : child.width
+ const h = autoH && measured ? measured.height : child.height
if (child.layoutGrow > 0) {
yogaChild.setFlexGrow(child.layoutGrow)
diff --git a/packages/core/src/render/export-jsx.ts b/packages/core/src/render/export-jsx.ts
index 8335b664e..d2060b645 100644
--- a/packages/core/src/render/export-jsx.ts
+++ b/packages/core/src/render/export-jsx.ts
@@ -303,6 +303,49 @@ function collectAppearanceProps(node: SceneNode, props: [string, unknown][]): vo
}
}
+function collectPositionProps(
+ node: SceneNode,
+ ctx: ReturnType<typeof getNodeContext>,
+ props: [string, unknown][]
+): void {
+ if (ctx.parentIsAutoLayout || ctx.parentIsGrid) return
+ if (node.x !== 0) props.push(['x', node.x])
+ if (node.y !== 0) props.push(['y', node.y])
+}
+
+function collectSizingProps(
+ node: SceneNode,
+ ctx: ReturnType<typeof getNodeContext>,
+ graph: SceneGraph,
+ props: [string, unknown][]
+): void {
+ if (ctx.isGrid) collectGridSizingProps(node, props)
+ else if (ctx.isFlex) collectFlexSizingProps(node, props)
+ else if (node.type === 'TEXT') collectTextSizingProps(node, props)
+ else {
+ if (node.width > 0) props.push(['w', node.width])
+ if (node.height > 0) props.push(['h', node.height])
+ }
+
+ if (!ctx.parentIsAutoLayout) return
+ if (node.layoutGrow > 0) props.push(['grow', node.layoutGrow])
+ if (node.layoutAlignSelf === 'STRETCH') {
+ const parent = node.parentId ? graph.getNode(node.parentId) : null
+ if (parent && (parent.layoutMode === 'HORIZONTAL' || parent.layoutMode === 'VERTICAL')) {
+ const crossDim = parent.layoutMode === 'HORIZONTAL' ? 'h' : 'w'
+ if (!props.some(([k]) => k === crossDim)) props.push([crossDim, 'fill'])
+ }
+ }
+}
+
+function collectTextSizingProps(node: SceneNode, props: [string, unknown][]): void {
+ const autoResize = node.textAutoResize
+ const emitW = autoResize !== 'WIDTH_AND_HEIGHT'
+ const emitH = autoResize === 'NONE' || autoResize === 'TRUNCATE'
+ if (emitW && node.width > 0) props.push(['w', node.width])
+ if (emitH && node.height > 0) props.push(['h', node.height])
+}
+
function collectTextNodeProps(node: SceneNode, props: [string, unknown][]): void {
if (node.fontSize !== 14) props.push(['size', node.fontSize])
if (node.fontFamily && node.fontFamily !== DEFAULT_FONT_FAMILY)
@@ -339,14 +382,8 @@ function collectProps(node: SceneNode, graph: SceneGraph): [string, unknown][] {
if (node.name && node.name !== node.type) props.push(['name', node.name])
- if (ctx.isGrid) collectGridSizingProps(node, props)
- else if (ctx.isFlex) collectFlexSizingProps(node, props)
- else {
- if (node.width > 0) props.push(['w', node.width])
- if (node.height > 0) props.push(['h', node.height])
- }
-
- if (ctx.parentIsAutoLayout && node.layoutGrow > 0) props.push(['grow', node.layoutGrow])
+ collectPositionProps(node, ctx, props)
+ collectSizingProps(node, ctx, graph, props)
if (ctx.parentIsGrid) collectGridPositionProps(node, props)
if (ctx.isFlex) collectFlexAlignmentProps(node, props)
if (ctx.isAutoLayout) collectAutoLayoutPaddingProps(node, props)
diff --git a/packages/core/src/render/renderer.ts b/packages/core/src/render/renderer.ts
index f7cbdf767..561546555 100644
--- a/packages/core/src/render/renderer.ts
+++ b/packages/core/src/render/renderer.ts
@@ -34,11 +34,11 @@ const ALIGN_MAP: Record<string, 'MIN' | 'MAX' | 'CENTER' | 'SPACE_BETWEEN'> = {
between: 'SPACE_BETWEEN'
}
-const COUNTER_ALIGN_MAP: Record<string, 'MIN' | 'MAX' | 'CENTER'> = {
+const COUNTER_ALIGN_MAP: Record<string, 'MIN' | 'MAX' | 'CENTER' | 'STRETCH'> = {
start: 'MIN',
end: 'MAX',
center: 'CENTER',
- stretch: 'MIN'
+ stretch: 'STRETCH'
}
const TEXT_ALIGN_MAP: Record<string, SceneNode['textAlignHorizontal']> = {
@@ -102,8 +102,11 @@ function renderNode(graph: SceneGraph, tree: TreeNode, parentId: string): SceneN
const nodeType = TYPE_MAP[tree.type]
if (!nodeType) throw new Error(`Unknown element: <${tree.type}>`)
+ const parent = graph.getNode(parentId)
+ const parentLayout = parent?.layoutMode ?? 'NONE'
+
const isText = nodeType === 'TEXT'
- const overrides = propsToOverrides(tree.props, isText)
+ const overrides = propsToOverrides(tree.props, isText, parentLayout)
if (isText) {
const textContent = tree.children.filter((c): c is string => typeof c === 'string').join('')
@@ -124,19 +127,26 @@ function renderNode(graph: SceneGraph, tree: TreeNode, parentId: string): SceneN
function applySizeOverrides(
props: Record<string, unknown>,
- o: Partial<SceneNode>
+ o: Partial<SceneNode>,
+ parentLayout: SceneNode['layoutMode']
): { w: unknown; h: unknown } {
const w = props.w ?? props.width
const h = props.h ?? props.height
if (typeof w === 'number') o.width = w
if (typeof h === 'number') o.height = h
+ const isParentRow = parentLayout === 'HORIZONTAL'
+ const isParentCol = parentLayout === 'VERTICAL'
+
if (w === 'fill') {
- o.layoutGrow = 1
- o.layoutAlignSelf = 'STRETCH'
+ if (isParentRow) o.layoutGrow = 1
+ else if (isParentCol) o.layoutAlignSelf = 'STRETCH'
+ else { o.layoutGrow = 1; o.layoutAlignSelf = 'STRETCH' }
}
if (h === 'fill') {
- o.layoutAlignSelf = 'STRETCH'
+ if (isParentCol) o.layoutGrow = 1
+ else if (isParentRow) o.layoutAlignSelf = 'STRETCH'
+ else o.layoutAlignSelf = 'STRETCH'
}
if (props.x !== undefined) o.x = props.x as number
@@ -206,23 +216,45 @@ function applyPaddingOverrides(props: Record<string, unknown>, o: Partial<SceneN
if (props.pl !== undefined) o.paddingLeft = props.pl as number
}
-function applyLayoutOverrides(
- props: Record<string, unknown>,
+const PADDING_KEYS = ['p', 'padding', 'px', 'py', 'pt', 'pr', 'pb', 'pl'] as const
+
+function hasPaddingProps(props: Record<string, unknown>): boolean {
+ return PADDING_KEYS.some((k) => props[k] !== undefined)
+}
+
+function applyAutoLayoutSizing(
o: Partial<SceneNode>,
+ props: Record<string, unknown>,
w: unknown,
h: unknown
): void {
- if (props.flex !== undefined) {
- const dir = props.flex as string
- o.layoutMode = (dir === 'col' || dir === 'column' ? 'VERTICAL' : 'HORIZONTAL') as LayoutMode
+ const dir = (props.flex as string | undefined) ?? 'col'
+ const isVertical = dir === 'col' || dir === 'column'
+ o.layoutMode = (isVertical ? 'VERTICAL' : 'HORIZONTAL') as LayoutMode
+
+ o.primaryAxisSizing = 'HUG'
+ o.counterAxisSizing = 'HUG'
- o.primaryAxisSizing = 'HUG'
- o.counterAxisSizing = 'HUG'
+ const primaryDim = isVertical ? h : w
+ const counterDim = isVertical ? w : h
- if (typeof w === 'number') o.primaryAxisSizing = 'FIXED'
- if (typeof h === 'number') o.counterAxisSizing = 'FIXED'
- if (w === 'hug') o.primaryAxisSizing = 'HUG'
- if (h === 'hug') o.counterAxisSizing = 'HUG'
+ if (typeof primaryDim === 'number') o.primaryAxisSizing = 'FIXED'
+ if (typeof counterDim === 'number') o.counterAxisSizing = 'FIXED'
+ if (primaryDim === 'hug') o.primaryAxisSizing = 'HUG'
+ if (counterDim === 'hug') o.counterAxisSizing = 'HUG'
+}
+
+function applyLayoutOverrides(
+ props: Record<string, unknown>,
+ o: Partial<SceneNode>,
+ w: unknown,
+ h: unknown,
+ isText: boolean
+): void {
+ const needsAutoLayout = props.flex !== undefined || (!isText && hasPaddingProps(props))
+
+ if (needsAutoLayout) {
+ applyAutoLayoutSizing(o, props, w, h)
}
if (props.gap !== undefined) o.itemSpacing = props.gap as number
@@ -269,9 +301,12 @@ function applyTextOverrides(props: Record<string, unknown>, o: Partial<SceneNode
o.textAlignHorizontal = TEXT_ALIGN_MAP[props.textAlign as string] ?? 'LEFT'
}
- o.textAutoResize = props.textAutoResize
- ? (TEXT_AUTO_RESIZE_MAP[props.textAutoResize as string] ?? 'NONE')
- : 'HEIGHT'
+ const hasExplicitWidth = (props.w ?? props.width) !== undefined
+ if (props.textAutoResize) {
+ o.textAutoResize = TEXT_AUTO_RESIZE_MAP[props.textAutoResize as string] ?? 'NONE'
+ } else {
+ o.textAutoResize = hasExplicitWidth ? 'HEIGHT' : 'WIDTH_AND_HEIGHT'
+ }
}
function applyShapeAndEffectOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {
@@ -312,14 +347,18 @@ function applyShapeAndEffectOverrides(props: Record<string, unknown>, o: Partial
}
}
-function propsToOverrides(props: Record<string, unknown>, isText: boolean): Partial<SceneNode> {
+function propsToOverrides(
+ props: Record<string, unknown>,
+ isText: boolean,
+ parentLayout: SceneNode['layoutMode']
+): Partial<SceneNode> {
const o: Partial<SceneNode> = {}
if (props.name) o.name = props.name as string
- const { w, h } = applySizeOverrides(props, o)
+ const { w, h } = applySizeOverrides(props, o, parentLayout)
applyVisualOverrides(props, o)
- applyLayoutOverrides(props, o, w, h)
+ applyLayoutOverrides(props, o, w, h, isText)
if (isText) applyTextOverrides(props, o)
applyShapeAndEffectOverrides(props, o)
diff --git a/packages/core/src/tools/ai-adapter.ts b/packages/core/src/tools/ai-adapter.ts
index a53156cc7..c8f7c322c 100644
--- a/packages/core/src/tools/ai-adapter.ts
+++ b/packages/core/src/tools/ai-adapter.ts
@@ -11,8 +11,8 @@ import type * as valibot from 'valibot'
export interface AIAdapterOptions {
getFigma: () => FigmaAPI
- onBeforeExecute?: () => void
- onAfterExecute?: () => void
+ onBeforeExecute?: (def: ToolDef) => void
+ onAfterExecute?: (def: ToolDef) => void
onFlashNodes?: (nodeIds: string[]) => void
}
@@ -54,11 +54,11 @@ export function toolsToAI(
shape[key] = paramToValibot(v, param)
}
- result[def.name] = tool({
+ const toolOpts: Record<string, unknown> = {
description: def.description,
inputSchema: valibotSchema(v.object(shape as any)),
execute: async (args: Record<string, unknown>) => {
- options.onBeforeExecute?.()
+ options.onBeforeExecute?.(def)
try {
const execResult = await def.execute(options.getFigma(), args as any)
if (def.mutates && options.onFlashNodes) {
@@ -69,10 +69,25 @@ export function toolsToAI(
} catch (err) {
return { error: err instanceof Error ? err.message : String(err) }
} finally {
- options.onAfterExecute?.()
+ options.onAfterExecute?.(def)
}
}
- })
+ }
+
+ if (def.name === 'export_image') {
+ toolOpts.toModelOutput = ({ output }: { output: unknown }) => {
+ if (output && typeof output === 'object' && 'base64' in output && 'mimeType' in output) {
+ const r = output as { base64: string; mimeType: string }
+ return {
+ type: 'content' as const,
+ value: [{ type: 'media' as const, mediaType: r.mimeType, data: r.base64 }]
+ }
+ }
+ return { type: 'json' as const, value: output as Record<string, unknown> }
+ }
+ }
+
+ result[def.name] = tool(toolOpts)
}
return result
diff --git a/packages/core/src/tools/describe.ts b/packages/core/src/tools/describe.ts
new file mode 100644
index 000000000..296ea048b
--- /dev/null
+++ b/packages/core/src/tools/describe.ts
@@ -0,0 +1,263 @@
+import { colorDistance, colorToHex } from '../color'
+
+import { defineTool } from './schema'
+
+import type { Color } from '../types'
+import type { SceneGraph, SceneNode } from '../scene-graph'
+
+const NAME_ROLE_PATTERNS: { pattern: RegExp; role: string }[] = [
+ { pattern: /^button$/i, role: 'button' },
+ { pattern: /^btn[-_\s]/i, role: 'button' },
+ { pattern: /[-_\s]btn$/i, role: 'button' },
+ { pattern: /^cta$/i, role: 'button' },
+ { pattern: /^icon[-_]?button$/i, role: 'button' },
+ { pattern: /^link$/i, role: 'link' },
+ { pattern: /^text[-_]?link$/i, role: 'link' },
+ { pattern: /^input$/i, role: 'textbox' },
+ { pattern: /^text[-_]?field$/i, role: 'textbox' },
+ { pattern: /^search$/i, role: 'searchbox' },
+ { pattern: /^checkbox$/i, role: 'checkbox' },
+ { pattern: /^toggle$/i, role: 'switch' },
+ { pattern: /^switch$/i, role: 'switch' },
+ { pattern: /^radio$/i, role: 'radio' },
+ { pattern: /^select$/i, role: 'combobox' },
+ { pattern: /^dropdown$/i, role: 'combobox' },
+ { pattern: /^slider$/i, role: 'slider' },
+ { pattern: /^tab$/i, role: 'tab' },
+ { pattern: /^tabs$/i, role: 'tablist' },
+ { pattern: /^nav(bar|igation)?$/i, role: 'navigation' },
+ { pattern: /^header$/i, role: 'banner' },
+ { pattern: /^footer$/i, role: 'contentinfo' },
+ { pattern: /^sidebar$/i, role: 'complementary' },
+ { pattern: /^modal$/i, role: 'dialog' },
+ { pattern: /^dialog$/i, role: 'dialog' },
+ { pattern: /^tooltip$/i, role: 'tooltip' },
+ { pattern: /^card$/i, role: 'article' },
+ { pattern: /^avatar$/i, role: 'img' },
+ { pattern: /^badge$/i, role: 'status' },
+ { pattern: /^toast$/i, role: 'alert' },
+ { pattern: /^alert$/i, role: 'alert' },
+ { pattern: /^list$/i, role: 'list' },
+ { pattern: /^menu$/i, role: 'menu' },
+ { pattern: /^breadcrumb/i, role: 'navigation' },
+ { pattern: /^progress$/i, role: 'progressbar' },
+ { pattern: /^spinner$/i, role: 'progressbar' },
+ { pattern: /^divider$/i, role: 'separator' },
+ { pattern: /^separator$/i, role: 'separator' },
+]
+
+function detectRoleFromName(name: string): string | null {
+ const base = (name.split(/[/,=]/)[0] ?? name).trim()
+ for (const { pattern, role } of NAME_ROLE_PATTERNS) {
+ if (pattern.test(base)) return role
+ }
+ return null
+}
+
+function headingLevel(fontSize: number): number | null {
+ if (fontSize >= 32) return 1
+ if (fontSize >= 24) return 2
+ if (fontSize >= 20) return 3
+ if (fontSize >= 18) return 4
+ return null
+}
+
+function looksLikeSeparator(node: SceneNode): boolean {
+ if (node.width <= 2 && node.height > 10) return true
+ if (node.height <= 2 && node.width > 10) return true
+ const ratio = Math.max(node.width, node.height) / Math.max(1, Math.min(node.width, node.height))
+ return ratio > 10 && Math.min(node.width, node.height) <= 4
+}
+
+const BUTTON_MAX_WIDTH = 200
+const BUTTON_MAX_HEIGHT = 50
+const BUTTON_MIN_HEIGHT = 28
+const BUTTON_MIN_RADIUS = 2
+
+function looksLikeButton(node: SceneNode): boolean {
+ if (node.type !== 'FRAME' && node.type !== 'COMPONENT' && node.type !== 'INSTANCE') return false
+ if (node.width > BUTTON_MAX_WIDTH || node.height > BUTTON_MAX_HEIGHT || node.height < BUTTON_MIN_HEIGHT) return false
+ if (node.fills.length === 0 && node.strokes.length === 0) return false
+ if (node.cornerRadius < BUTTON_MIN_RADIUS) return false
+ return node.childIds.length > 0
+}
+
+function describeVisual(node: SceneNode): string {
+ const parts: string[] = []
+ const fill = node.fills.find((f) => f.type === 'SOLID' && f.visible)
+ if (fill) parts.push(`${colorToHex(fill.color)} fill`)
+ if (node.strokes.length > 0 && node.strokes[0]?.visible) parts.push('bordered')
+ if (node.cornerRadius > 0) parts.push('rounded')
+ if (node.clipsContent) parts.push('clipped')
+ for (const e of node.effects) {
+ if (!e.visible) continue
+ if (e.type === 'DROP_SHADOW') parts.push('drop shadow')
+ else if (e.type === 'INNER_SHADOW') parts.push('inner shadow')
+ else if (e.type === 'LAYER_BLUR' || e.type === 'FOREGROUND_BLUR') parts.push('blurred')
+ else parts.push('backdrop blur')
+ }
+ return parts.join(', ') || 'no visual styles'
+}
+
+function describeLayout(node: SceneNode): string | null {
+ if (node.layoutMode === 'NONE') return null
+ const dir = node.layoutMode === 'HORIZONTAL' ? 'horizontal' : 'vertical'
+ const parts = [dir]
+ if (node.itemSpacing > 0) parts.push(`${node.itemSpacing}px gap`)
+ const pad = [node.paddingTop, node.paddingRight, node.paddingBottom, node.paddingLeft]
+ const allSame = pad.every((p) => p === pad[0])
+ const first = pad[0]
+ if (allSame && first > 0) parts.push(`${first}px padding`)
+ else if (pad.some((p) => p > 0)) parts.push(`padding ${pad.join('/')}`)
+ if (node.layoutWrap === 'WRAP') parts.push('wrap')
+ return parts.join(', ')
+}
+
+const MIN_FILL_OPACITY = 0.15
+const MIN_STROKE_OPACITY = 0.20
+const LOW_CONTRAST_THRESHOLD = 15
+
+interface DescribeIssue {
+ message: string
+ suggestion?: string
+}
+
+function findAncestorBackground(node: SceneNode, graph: SceneGraph): Color | null {
+ let current = node.parentId ? graph.getNode(node.parentId) : null
+ while (current) {
+ const solidFill = current.fills.find((f) => f.visible && f.type === 'SOLID' && f.opacity > 0.5)
+ if (solidFill) return solidFill.color
+ current = current.parentId ? graph.getNode(current.parentId) : null
+ }
+ return null
+}
+
+function detectStructuralIssues(node: SceneNode, gridSize: number, issues: DescribeIssue[]): void {
+ if (node.x % 1 !== 0 || node.y % 1 !== 0) {
+ issues.push({
+ message: `Subpixel position (${node.x}, ${node.y})`,
+ suggestion: `(${Math.round(node.x)}, ${Math.round(node.y)})`
+ })
+ }
+ const isContainer = node.type === 'FRAME' || node.type === 'COMPONENT' || node.type === 'INSTANCE'
+ if (isContainer && node.fills.length === 0 && node.childIds.length === 0) {
+ issues.push({ message: 'Empty frame with no fill' })
+ }
+ if (looksLikeButton(node) && node.width < 44) {
+ issues.push({ message: `Touch target too small (${node.width}×${node.height})`, suggestion: 'Min 44×44' })
+ }
+ if (node.itemSpacing > 0 && node.itemSpacing % gridSize !== 0) {
+ const nearest = Math.round(node.itemSpacing / gridSize) * gridSize
+ issues.push({ message: `Gap ${node.itemSpacing} not on ${gridSize}px grid`, suggestion: `${nearest}` })
+ }
+}
+
+function detectVisibilityIssues(node: SceneNode, graph: SceneGraph, issues: DescribeIssue[]): void {
+ for (const fill of node.fills) {
+ if (!fill.visible || fill.type !== 'SOLID') continue
+ if (fill.opacity < MIN_FILL_OPACITY) {
+ issues.push({
+ message: `Near-invisible fill ${colorToHex(fill.color)} at ${Math.round(fill.opacity * 100)}% opacity`,
+ suggestion: `Increase to at least ${Math.round(MIN_FILL_OPACITY * 100)}%`
+ })
+ }
+ }
+ for (const stroke of node.strokes) {
+ if (!stroke.visible || stroke.opacity >= MIN_STROKE_OPACITY) continue
+ issues.push({
+ message: `Near-invisible stroke at ${Math.round(stroke.opacity * 100)}% opacity`,
+ suggestion: `Increase to at least ${Math.round(MIN_STROKE_OPACITY * 100)}%`
+ })
+ }
+ if (node.type !== 'TEXT' || !node.parentId) return
+ const textFill = node.fills.find((f) => f.visible && f.type === 'SOLID')
+ if (!textFill) return
+ const parentBg = findAncestorBackground(node, graph)
+ if (!parentBg) return
+ const dist = colorDistance(textFill.color, parentBg)
+ if (dist < LOW_CONTRAST_THRESHOLD) {
+ issues.push({
+ message: `Low contrast: text ${colorToHex(textFill.color)} on ${colorToHex(parentBg)} (distance ${Math.round(dist)})`,
+ suggestion: 'Increase color difference between text and background'
+ })
+ }
+}
+
+function detectIssues(node: SceneNode, gridSize: number, graph: SceneGraph): DescribeIssue[] {
+ const issues: DescribeIssue[] = []
+ detectStructuralIssues(node, gridSize, issues)
+ detectVisibilityIssues(node, graph, issues)
+ return issues
+}
+
+function detectRole(node: SceneNode): string {
+ const nameDetected = detectRoleFromName(node.name)
+ if (nameDetected) return nameDetected
+ if (node.type === 'TEXT') {
+ const level = headingLevel(node.fontSize)
+ return level ? `heading(${level})` : 'StaticText'
+ }
+ if (looksLikeSeparator(node)) return 'separator'
+ if (looksLikeButton(node)) return 'button'
+ return 'generic'
+}
+
+function describeChild(node: SceneNode): { role: string; name: string; summary: string; id: string } {
+ const role = detectRole(node)
+ let summary = ''
+ if (node.type === 'TEXT') {
+ const text = node.text.slice(0, 60)
+ summary = `"${text}" ${node.fontSize}px ${node.fontFamily}`
+ if (node.fontWeight >= 700) summary += ' bold'
+ else if (node.fontWeight >= 500) summary += ' medium'
+ const textColor = node.fills.find((f) => f.type === 'SOLID' && f.visible)
+ if (textColor) summary += `, ${colorToHex(textColor.color)}`
+ } else {
+ summary = `${node.width}×${node.height}`
+ const fill = node.fills.find((f) => f.type === 'SOLID' && f.visible)
+ if (fill) summary += `, ${colorToHex(fill.color)}`
+ if (node.cornerRadius > 0) summary += ', rounded'
+ }
+ return { role, name: node.name, summary, id: node.id }
+}
+
+export const describe = defineTool({
+ name: 'describe',
+ description:
+ 'Semantic description of a node: role, visual style, layout, children summary, and design issues.',
+ params: {
+ id: { type: 'string', description: 'Node ID', required: true },
+ grid: { type: 'number', description: 'Grid size for alignment checks (default: 8)' }
+ },
+ execute: (figma, args) => {
+ const gridSize = args.grid ?? 8
+ const raw = figma.graph.getNode(args.id)
+ if (!raw) return { error: `Node "${args.id}" not found` }
+
+ const role = detectRole(raw)
+ const visual = describeVisual(raw)
+ const layout = describeLayout(raw)
+ const issues = detectIssues(raw, gridSize, figma.graph)
+
+ const children: { role: string; name: string; summary: string; id: string }[] = []
+ for (const childId of raw.childIds) {
+ const child = figma.graph.getNode(childId)
+ if (!child || !child.visible) continue
+ children.push(describeChild(child))
+ }
+
+ const result: Record<string, unknown> = {
+ id: raw.id,
+ name: raw.name,
+ type: raw.type,
+ role,
+ size: `${raw.width}×${raw.height}`,
+ visual,
+ }
+ if (layout) result.layout = layout
+ if (children.length > 0) result.children = children
+ if (issues.length > 0) result.issues = issues
+
+ return result
+ }
+})
diff --git a/packages/core/src/tools/read.ts b/packages/core/src/tools/read.ts
index a48dec580..7e38527a4 100644
--- a/packages/core/src/tools/read.ts
+++ b/packages/core/src/tools/read.ts
@@ -1,3 +1,6 @@
+import { createTwoFilesPatch } from 'diff'
+
+import { sceneNodeToJSX } from '../render/export-jsx'
import { defineTool, nodeSummary, nodeToResult } from './schema'
import { queryByXPath } from '../xpath'
@@ -240,3 +243,61 @@ Examples:
}
}
})
+
+const MAX_JSX_LENGTH = 12_000
+
+export const getJsx = defineTool({
+ name: 'get_jsx',
+ description:
+ 'Get JSX representation of a node and its children. Compact round-trip format — same syntax as the render tool.',
+ params: {
+ id: { type: 'string', description: 'Node ID', required: true }
+ },
+ execute: (figma, { id }) => {
+ const node = figma.getNodeById(id)
+ if (!node) return { error: `Node "${id}" not found` }
+ const jsx = sceneNodeToJSX(id, figma.graph)
+ if (jsx.length > MAX_JSX_LENGTH) {
+ return {
+ id,
+ name: node.name,
+ jsx: jsx.slice(0, MAX_JSX_LENGTH),
+ truncated: true,
+ totalLength: jsx.length
+ }
+ }
+ return { id, name: node.name, jsx }
+ }
+})
+
+export const diffJsx = defineTool({
+ name: 'diff_jsx',
+ description:
+ 'Structural diff between two nodes in JSX format. Shows added/removed children, changed props.',
+ params: {
+ from: { type: 'string', description: 'Source node ID', required: true },
+ to: { type: 'string', description: 'Target node ID', required: true }
+ },
+ execute: (figma, { from, to }) => {
+ const fromNode = figma.getNodeById(from)
+ if (!fromNode) return { error: `Node "${from}" not found` }
+ const toNode = figma.getNodeById(to)
+ if (!toNode) return { error: `Node "${to}" not found` }
+
+ const fromJsx = sceneNodeToJSX(from, figma.graph)
+ const toJsx = sceneNodeToJSX(to, figma.graph)
+
+ if (fromJsx === toJsx) return { diff: null, message: 'No differences' }
+
+ const patch = createTwoFilesPatch(
+ fromNode.name,
+ toNode.name,
+ fromJsx,
+ toJsx,
+ 'source',
+ 'target',
+ { context: 3 }
+ )
+ return { diff: patch }
+ }
+})
diff --git a/packages/core/src/tools/registry.ts b/packages/core/src/tools/registry.ts
index 8179431c9..6623ae401 100644
--- a/packages/core/src/tools/registry.ts
+++ b/packages/core/src/tools/registry.ts
@@ -2,7 +2,8 @@ import type { ToolDef } from './schema'
import {
getSelection, getPageTree, getNode, findNodes, queryNodes, getComponents,
- listPages, switchPage, getCurrentPage, pageBounds, selectNodes, listFonts
+ listPages, switchPage, getCurrentPage, pageBounds, selectNodes, listFonts,
+ getJsx, diffJsx
} from './read'
import {
createShape, render, createComponent, createInstance,
@@ -34,6 +35,7 @@ import {
analyzeColors, analyzeTypography, analyzeSpacing, analyzeClusters,
diffCreate, diffShow, evalCode
} from './analyze'
+import { describe } from './describe'
export const ALL_TOOLS: ToolDef[] = [
// Read
@@ -49,6 +51,8 @@ export const ALL_TOOLS: ToolDef[] = [
pageBounds,
selectNodes,
listFonts,
+ getJsx,
+ diffJsx,
// Create
createShape,
render,
@@ -130,6 +134,7 @@ export const ALL_TOOLS: ToolDef[] = [
analyzeClusters,
diffCreate,
diffShow,
+ describe,
// Eval
evalCode
]
diff --git a/packages/core/src/tools/vector.ts b/packages/core/src/tools/vector.ts
index 3da662662..ec5d9fda9 100644
--- a/packages/core/src/tools/vector.ts
+++ b/packages/core/src/tools/vector.ts
@@ -1,5 +1,19 @@
import { defineTool, nodeSummary } from './schema'
+const CHUNK_SIZE = 0x8000
+
+function uint8ArrayToBase64(bytes: Uint8Array): string {
+ if (typeof Buffer !== 'undefined') {
+ return Buffer.from(bytes).toString('base64')
+ }
+ let binary = ''
+ for (let i = 0; i < bytes.length; i += CHUNK_SIZE) {
+ const chunk = bytes.subarray(i, i + CHUNK_SIZE)
+ binary += String.fromCharCode.apply(null, chunk as unknown as number[])
+ }
+ return btoa(binary)
+}
+
export const booleanUnion = defineTool({
name: 'boolean_union',
mutates: true,
@@ -286,10 +300,7 @@ export const exportImage = defineTool({
format
})
if (!data || data.length === 0) return { error: 'No visible nodes to export' }
- const base64 =
- typeof Buffer !== 'undefined'
- ? Buffer.from(data).toString('base64')
- : btoa(String.fromCharCode(...data))
+ const base64 = uint8ArrayToBase64(data)
const mimeMap = { PNG: 'image/png', JPG: 'image/jpeg', WEBP: 'image/webp' } as const
return {
mimeType: mimeMap[format],
diff --git a/src/ai/chat-debug.ts b/src/ai/chat-debug.ts
new file mode 100644
index 000000000..de089a3d0
--- /dev/null
+++ b/src/ai/chat-debug.ts
@@ -0,0 +1,54 @@
+import type { UIMessage } from 'ai'
+
+function formatToolPart(part: Record<string, unknown>): string {
+ const inv = part.toolInvocation as Record<string, unknown> | undefined
+ if (inv) {
+ const lines = [` [tool] ${String(inv.toolName)} (${String(inv.state)})`]
+ if (inv.args) lines.push(` args: ${JSON.stringify(inv.args)}`)
+ if (inv.result !== undefined) lines.push(` result: ${JSON.stringify(inv.result)}`)
+ return lines.join('\n')
+ }
+
+ const name = String(part.type ?? 'unknown').replace(/^tool-/, '')
+ const state = String(part.state ?? '?')
+ const lines = [` [tool] ${name} (${state})`]
+ if (part.input) lines.push(` input: ${JSON.stringify(part.input)}`)
+ if (part.output !== undefined) lines.push(` output: ${JSON.stringify(part.output)}`)
+ if (part.errorText) lines.push(` error: ${String(part.errorText)}`)
+ return lines.join('\n')
+}
+
+export function serializeChatLog(messages: UIMessage[]): string {
+ const sections: string[] = []
+
+ for (const msg of messages) {
+ const header = `=== ${msg.role.toUpperCase()} (${msg.id}) ===`
+ const parts: string[] = []
+
+ for (const part of msg.parts) {
+ const p = part as Record<string, unknown>
+ if (p.type === 'text') {
+ parts.push(` ${p.text}`)
+ } else if (p.type === 'reasoning') {
+ parts.push(` [reasoning] ${String(p.text ?? p.content ?? '')}`)
+ } else if (
+ p.type === 'tool-invocation' ||
+ p.toolInvocation ||
+ (typeof p.type === 'string' && p.type.startsWith('tool-'))
+ ) {
+ parts.push(formatToolPart(p))
+ } else {
+ parts.push(` [${String(p.type ?? 'unknown')}] ${JSON.stringify(p)}`)
+ }
+ }
+
+ sections.push(`${header}\n${parts.join('\n')}`)
+ }
+
+ return sections.join('\n\n')
+}
+
+export function copyChatLog(messages: UIMessage[]): Promise<void> {
+ const text = serializeChatLog(messages)
+ return navigator.clipboard.writeText(text)
+}
diff --git a/src/ai/tools.ts b/src/ai/tools.ts
index 996391e5d..90d974f77 100644
--- a/src/ai/tools.ts
+++ b/src/ai/tools.ts
@@ -3,17 +3,36 @@ import { tool } from 'ai'
import * as v from 'valibot'
import { makeFigmaFromStore } from '@/automation/figma-factory'
-import { ALL_TOOLS, toolsToAI } from '@open-pencil/core'
+import { ALL_TOOLS, computeAllLayouts, toolsToAI } from '@open-pencil/core'
import type { EditorStore } from '@/stores/editor'
+import type { SceneNode } from '@open-pencil/core'
export function createAITools(store: EditorStore) {
+ let beforeSnapshot: Map<string, SceneNode> | null = null
+
return toolsToAI(
ALL_TOOLS,
{
getFigma: () => makeFigmaFromStore(store),
- onAfterExecute: () => {
+ onBeforeExecute: (def) => {
+ if (def.mutates) {
+ beforeSnapshot = store.snapshotPage()
+ }
+ },
+ onAfterExecute: (def) => {
+ computeAllLayouts(store.graph, store.state.currentPageId)
store.requestRender()
+ if (def.mutates && beforeSnapshot) {
+ const before = beforeSnapshot
+ const after = store.snapshotPage()
+ store.pushUndoEntry({
+ label: `AI: ${def.name}`,
+ forward: () => store.restorePageFromSnapshot(after),
+ inverse: () => store.restorePageFromSnapshot(before)
+ })
+ beforeSnapshot = null
+ }
},
onFlashNodes: (nodeIds) => {
store.flashNodes(nodeIds)
diff --git a/src/components/ChatPanel.vue b/src/components/ChatPanel.vue
index 6b120f998..3491fa1af 100644
--- a/src/components/ChatPanel.vue
+++ b/src/components/ChatPanel.vue
@@ -2,18 +2,23 @@
import { ScrollAreaRoot, ScrollAreaScrollbar, ScrollAreaThumb, ScrollAreaViewport } from 'reka-ui'
import { computed, markRaw, nextTick, ref, watch } from 'vue'
-import ProviderSetup from '@/components/chat/ProviderSetup.vue'
+import { copyChatLog } from '@/ai/chat-debug'
import ChatInput from '@/components/chat/ChatInput.vue'
import ChatMessage from '@/components/chat/ChatMessage.vue'
+import ProviderSetup from '@/components/chat/ProviderSetup.vue'
import { useAIChat } from '@/composables/use-chat'
import type { Chat } from '@ai-sdk/vue'
import type { UIMessage } from 'ai'
-const { isConfigured, ensureChat } = useAIChat()
+const IS_DEV = import.meta.env.DEV
-const chat = ref<Chat<UIMessage> | null>(null)
+const { isConfigured, ensureChat, resetChat } = useAIChat()
+
+const existing = ensureChat()
+const chat = ref<Chat<UIMessage> | null>(existing ? markRaw(existing) : null)
const messagesEnd = ref<HTMLDivElement>()
+const debugCopied = ref(false)
const messages = computed(() => chat.value?.messages ?? [])
const status = computed(() => chat.value?.status ?? 'ready')
@@ -39,6 +44,19 @@ function handleSubmit(text: string) {
function handleStop() {
chat.value?.stop()
}
+
+async function handleCopyDebug() {
+ await copyChatLog(messages.value)
+ debugCopied.value = true
+ setTimeout(() => {
+ debugCopied.value = false
+ }, 1500)
+}
+
+function handleClearChat() {
+ chat.value = null
+ resetChat()
+}
</script>
<template>
@@ -97,6 +115,28 @@ function handleStop() {
</ScrollAreaScrollbar>
</ScrollAreaRoot>
+ <!-- Debug toolbar (dev only) -->
+ <div
+ v-if="IS_DEV && messages.length > 0"
+ class="flex shrink-0 items-center gap-1 border-t border-border px-3 py-1"
+ >
+ <button
+ class="flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] text-muted hover:bg-hover hover:text-surface"
+ @click="handleCopyDebug"
+ >
+ <icon-lucide-clipboard-copy v-if="!debugCopied" class="size-3" />
+ <icon-lucide-check v-else class="size-3 text-green-400" />
+ {{ debugCopied ? 'Copied' : 'Copy log' }}
+ </button>
+ <button
+ class="flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] text-muted hover:bg-hover hover:text-surface"
+ @click="handleClearChat"
+ >
+ <icon-lucide-trash-2 class="size-3" />
+ Clear
+ </button>
+ </div>
+
<ChatInput :status="status" @submit="handleSubmit" @stop="handleStop" />
</template>
</div>
diff --git a/src/components/LayerTree.vue b/src/components/LayerTree.vue
index efed15c77..88c6cf30f 100644
--- a/src/components/LayerTree.vue
+++ b/src/components/LayerTree.vue
@@ -176,8 +176,7 @@ function onPointerDown(e: PointerEvent, nodeId: string) {
if (didMove && dropTarget.value && dragNodeId.value) {
const { parentId, index } = dropTarget.value
if (parentId !== dragNodeId.value && !store.graph.isDescendant(parentId, dragNodeId.value)) {
- store.graph.reorderChild(dragNodeId.value, parentId, index)
- store.requestRender()
+ store.reorderChildWithUndo(dragNodeId.value, parentId, index)
}
} else if (!didMove && dragNodeId.value) {
store.select([dragNodeId.value])
diff --git a/src/components/chat/ProviderSettings.vue b/src/components/chat/ProviderSettings.vue
index 9eeea9bca..085cfb781 100644
--- a/src/components/chat/ProviderSettings.vue
+++ b/src/components/chat/ProviderSettings.vue
@@ -5,6 +5,10 @@ import {
PopoverPortal,
PopoverRoot,
PopoverTrigger,
+ TabsContent,
+ TabsList,
+ TabsRoot,
+ TabsTrigger,
TooltipContent,
TooltipPortal,
TooltipRoot,
@@ -16,7 +20,8 @@ import ProviderSelect from '@/components/chat/ProviderSelect.vue'
import { uiInput } from '@/components/ui/input'
import { useAIChat } from '@/composables/use-chat'
-const { providerID, providerDef, apiKey, setAPIKey, customBaseURL, customModelID } = useAIChat()
+const { providerID, providerDef, apiKey, setAPIKey, customBaseURL, customModelID, customAPIType } =
+ useAIChat()
const keyInput = ref('')
const baseURLInput = ref(customBaseURL.value)
@@ -112,6 +117,39 @@ function clearKey() {
/>
</div>
+ <!-- API type (OpenAI-compatible only) -->
+ <div v-if="providerID === 'openai-compatible'" class="flex flex-col gap-1">
+ <label class="text-[10px] text-muted">API Type</label>
+ <TabsRoot
+ :model-value="customAPIType"
+ data-test-id="provider-settings-api-type"
+ class="flex flex-col"
+ @update:model-value="
+ (v: string) => {
+ customAPIType = v as 'completions' | 'responses'
+ save()
+ }
+ "
+ >
+ <TabsList class="flex rounded bg-canvas">
+ <TabsTrigger
+ value="completions"
+ class="flex-1 rounded px-2 py-1 text-[10px] text-muted data-[state=active]:bg-hover data-[state=active]:text-surface"
+ >
+ Completions
+ </TabsTrigger>
+ <TabsTrigger
+ value="responses"
+ class="flex-1 rounded px-2 py-1 text-[10px] text-muted data-[state=active]:bg-hover data-[state=active]:text-surface"
+ >
+ Responses
+ </TabsTrigger>
+ </TabsList>
+ <TabsContent value="completions" />
+ <TabsContent value="responses" />
+ </TabsRoot>
+ </div>
+
<!-- API key -->
<div class="flex flex-col gap-1">
<div class="flex items-center justify-between">
diff --git a/src/composables/use-canvas-input.ts b/src/composables/use-canvas-input.ts
index b564698ff..7c4b2cd63 100644
--- a/src/composables/use-canvas-input.ts
+++ b/src/composables/use-canvas-input.ts
@@ -29,7 +29,7 @@ interface DragMove {
type: 'move'
startX: number
startY: number
- originals: Map<string, Vector>
+ originals: Map<string, { x: number; y: number; parentId: string }>
duplicated?: boolean
autoLayoutParentId?: string
brokeFromAutoLayout?: boolean
@@ -353,9 +353,12 @@ export function useCanvasInput(
return false
}
- function duplicateAndDrag(cx: number, cy: number): Map<string, Vector> {
+ function duplicateAndDrag(
+ cx: number,
+ cy: number
+ ): Map<string, { x: number; y: number; parentId: string }> {
const newIds: string[] = []
- const newOriginals = new Map<string, Vector>()
+ const newOriginals = new Map<string, { x: number; y: number; parentId: string }>()
for (const id of store.state.selectedIds) {
const src = store.graph.getNode(id)
if (!src) continue
@@ -370,7 +373,12 @@ export function useCanvasInput(
rotation: src.rotation
})
newIds.push(newId)
- newOriginals.set(newId, { x: src.x, y: src.y })
+ const newNode = store.graph.getNode(newId)
+ newOriginals.set(newId, {
+ x: src.x,
+ y: src.y,
+ parentId: newNode?.parentId ?? store.state.currentPageId
+ })
}
store.select(newIds)
drag.value = {
@@ -422,10 +430,11 @@ export function useCanvasInput(
store.select([hit.id], true)
}
- const originals = new Map<string, Vector>()
+ const originals = new Map<string, { x: number; y: number; parentId: string }>()
for (const id of store.state.selectedIds) {
const n = store.graph.getNode(id)
- if (n) originals.set(id, { x: n.x, y: n.y })
+ if (n)
+ originals.set(id, { x: n.x, y: n.y, parentId: n.parentId ?? store.state.currentPageId })
}
if (e.altKey && store.state.selectedIds.size > 0) {
@@ -896,14 +905,13 @@ export function useCanvasInput(
})
if (moved) {
- store.commitMove(d.originals)
-
const dropId = store.state.dropTargetId
if (dropId) {
store.reparentNodes([...store.state.selectedIds], dropId)
} else {
reparentOutsideNodes()
}
+ store.commitMoveWithReparent(d.originals)
}
store.setDropTarget(null)
}
@@ -1268,8 +1276,12 @@ export function useCanvasInput(
useEventListener(canvasRef, 'mousemove', onMouseMove)
useEventListener(canvasRef, 'mouseup', onMouseUp)
useEventListener(canvasRef, 'mouseleave', () => {
- onMouseUp()
- store.setHoveredNode(null)
+ if (!drag.value) {
+ store.setHoveredNode(null)
+ }
+ })
+ useEventListener(window, 'mouseup', () => {
+ if (drag.value) onMouseUp()
})
useEventListener(canvasRef, 'wheel', onWheel, { passive: false })
useEventListener(canvasRef, 'touchstart', onTouchStart, { passive: false })
diff --git a/src/composables/use-chat.ts b/src/composables/use-chat.ts
index e19e899c9..85ce3e790 100644
--- a/src/composables/use-chat.ts
+++ b/src/composables/use-chat.ts
@@ -35,22 +35,96 @@ function migrateLegacyStorage() {
if (typeof window !== 'undefined') migrateLegacyStorage()
+// eslint-disable-next-line open-pencil/no-hand-rolled-color -- hex examples in AI prompt, not runtime color values
const SYSTEM_PROMPT = dedent`
You are a design assistant inside OpenPencil, a Figma-like design editor.
- Help users create and modify designs. Be concise and direct.
- When describing changes, use specific design terminology.
-
- Use the render tool with JSX as the primary way to create designs.
- JSX supports full JavaScript expressions (map, ternaries, Array.from, etc.).
- Available tags: Frame, Text, Rectangle, Ellipse, Line, Star, Polygon, Group, Section.
- Common props: name, w, h, x, y, bg (hex color), stroke, rounded, opacity, rotate.
- Layout: flex="row"|"col", gap, justify, items, p, px, py, pt/pr/pb/pl, wrap.
- Text: size, weight, color, font, textAlign.
- Sizing: w/h accept numbers (px) or "hug"/"fill".
-
- Colors are hex strings (#ff0000). Coordinates use canvas space — (0, 0) is top-left.
- Always use tools to make changes. After creating nodes, briefly describe what you did.
- Use create_shape + set_layout only for simple single nodes; prefer render for layouts.
+ Be concise and direct. Use specific design terminology.
+ Always use tools to make changes. Briefly describe what you did after.
+
+ # Creating designs
+
+ Use the \`render\` tool with JSX. Full JavaScript expressions work (map, ternaries, Array.from).
+
+ ## Tags
+ Frame, Text, Rectangle, Ellipse, Line, Star, Polygon, Group, Section, Component
+
+ ## Props reference (ONLY these exist — no style, no className, no CSS properties)
+
+ ### Identity & position
+ - name="string" — node name in layers panel
+ - x={number}, y={number} — absolute position in px. Only works WITHOUT auto-layout parent.
+
+ ### Size
+ - w={number}, h={number} — fixed size in px
+ - w="hug", h="hug" — shrink to fit content (default for flex containers)
+ - w="fill", h="fill" — stretch to fill available space (only inside a flex parent)
+ - grow={number} — flex-grow factor (only inside a flex parent)
+
+ ### Text
+ **Tags:** \`<Text>content here</Text>\`
+ **Props:** size={number}, weight={number|"bold"|"medium"}, color="#hex", font="Family Name", textAlign="left"|"center"|"right"|"justified"
+ ⚠ Default color is BLACK — always set color="#FFFFFF" on dark backgrounds!
+ ⚠ Do NOT set w or h on Text. Text auto-sizes. If you need wider text, set ONLY w.
+
+ ### Fill & stroke
+ - bg="#hex" — background fill (6 or 8 digit hex only)
+ - stroke="#hex", strokeWidth={number}
+
+ ### Corners & visual
+ - rounded={number}, roundedTL/TR/BL/BR={number}, cornerSmoothing={0-1}
+ - opacity={0-1}, rotate={degrees}, blendMode="multiply"|"screen"|etc.
+ - overflow="hidden" — clip children to bounds
+ - shadow="offsetX offsetY blurRadius #color", blur={number}
+
+ ### Flex layout
+ - flex="row"|"col" — enables auto-layout. Without this, children use absolute x/y.
+ - gap={number}, wrap, rowGap={number}
+ - justify="start"|"end"|"center"|"between" (⚠ "between", NOT "space-between")
+ - items="start"|"end"|"center"|"stretch"
+ - p, px, py, pt, pr, pb, pl={number} — padding (auto-enables flex="col" if no flex set)
+
+ ### Grid layout
+ - grid, columns="1fr 1fr 1fr", rows="1fr 1fr"
+ - columnGap={number}, rowGap={number}
+ - Children: colStart, rowStart, colSpan, rowSpan
+
+ ## How sizing works
+
+ 1. **No flex → absolute layout.** Children positioned by x/y.
+ 2. **flex="row"** → w is primary axis, h is cross axis
+ 3. **flex="col"** → h is primary axis, w is cross axis
+ 4. **Default = hug.** Flex container without w/h shrinks to fit.
+ 5. **grow={1}** fills remaining space. ⚠ Parent MUST have fixed size on that axis!
+ 6. **Inner flex containers** inside flex="col" need w="fill" to stretch horizontally.
+
+ ## Common patterns
+
+ **Card:** \`<Frame flex="col" w={380} gap={16} p={24} bg="#FFFFFF" rounded={16}>\`
+ **Row with spacer:** \`<Frame flex="row" w={380} items="center"><Text>Title</Text><Frame grow={1} /><Text>Action</Text></Frame>\`
+ **Grow children:** Inner flex="row" MUST have w="fill" so grow children can divide space.
+
+ ## Forbidden patterns
+ - ❌ style={{...}}, className, CSS properties
+ - ❌ w/h on Text, justify="space-between", "red"/"rgb(...)" colors, percentage values
+ - ❌ grow={1} inside hug-width parent, nested flex without w="fill"
+
+ ## Color contrast rules
+ - Subtle backgrounds on dark bg: at least #FFFFFF30 alpha (~19%)
+ - Borders on dark bg: at least #FFFFFF40 (~25%)
+ - Dividers: at least #FFFFFF25 (~15%)
+ - Better: use opaque tinted colors like #1E1E32, #252540
+
+ ## Workflow: always verify after render
+
+ After every \`render\` call, call \`export_image\` to visually verify.
+ ⚠ Export ONE node at a time. Be extremely critical: check text clipping, spacing, alignment, contrast, overflow.
+ Fix any issues immediately, then re-export.
+
+ # Reading designs
+ - \`export_image\`: renders to PNG for visual inspection
+ - \`get_jsx\`: JSX representation (same format as render)
+ - \`describe\`: semantic description with role, style, layout, and design issues
+ - \`diff_jsx\`: unified diff between two nodes
`
const providerID = useLocalStorage<AIProviderID>(
@@ -62,6 +136,10 @@ const apiKey = useLocalStorage(apiKeyStorageKey, '')
const modelID = useLocalStorage(`${STORAGE_PREFIX}ai-model`, DEFAULT_AI_MODEL)
const customBaseURL = useLocalStorage(`${STORAGE_PREFIX}ai-base-url`, '')
const customModelID = useLocalStorage(`${STORAGE_PREFIX}ai-custom-model`, '')
+const customAPIType = useLocalStorage<'completions' | 'responses'>(
+ `${STORAGE_PREFIX}ai-api-type`,
+ 'completions'
+)
const activeTab = ref<'design' | 'ai'>('design')
const providerDef = computed(
@@ -70,7 +148,9 @@ const providerDef = computed(
const isConfigured = computed(() => {
if (!apiKey.value) return false
- if (providerID.value === 'openai-compatible' && !customBaseURL.value) return false
+ const needsBaseURL =
+ providerID.value === 'openai-compatible' || providerID.value === 'anthropic-compatible'
+ if (needsBaseURL && !customBaseURL.value) return false
return true
})
@@ -84,6 +164,7 @@ watch(providerID, (id) => {
watch(modelID, () => resetChat())
watch(customModelID, () => resetChat())
+watch(customAPIType, () => resetChat())
function setAPIKey(key: string) {
apiKey.value = key
@@ -91,8 +172,9 @@ function setAPIKey(key: string) {
function createModel(): LanguageModel {
const key = apiKey.value
- const effectiveModelID =
- providerID.value === 'openai-compatible' ? customModelID.value : modelID.value
+ const needsCustomModel =
+ providerID.value === 'openai-compatible' || providerID.value === 'anthropic-compatible'
+ const effectiveModelID = needsCustomModel ? customModelID.value : modelID.value
switch (providerID.value) {
case 'openrouter': {
@@ -122,6 +204,15 @@ function createModel(): LanguageModel {
apiKey: key,
baseURL: customBaseURL.value
})
+ return customAPIType.value === 'responses'
+ ? custom.responses(effectiveModelID)
+ : custom.chat(effectiveModelID)
+ }
+ case 'anthropic-compatible': {
+ const custom = createAnthropic({
+ apiKey: key,
+ baseURL: customBaseURL.value
+ })
return custom(effectiveModelID)
}
default: {
@@ -179,6 +270,7 @@ export function useAIChat() {
modelID,
customBaseURL,
customModelID,
+ customAPIType,
activeTab,
isConfigured,
ensureChat,
diff --git a/src/stores/editor.ts b/src/stores/editor.ts
index 2e1f33080..0b85d5818 100644
--- a/src/stores/editor.ts
+++ b/src/stores/editor.ts
@@ -44,6 +44,7 @@ import type {
SceneNode,
SkiaRenderer,
SnapGuide,
+ UndoEntry,
VectorNetwork,
VectorRegion,
VectorSegment,
@@ -388,14 +389,10 @@ export function createEditorStore() {
requestRepaint()
}
- function reorderInAutoLayout(nodeId: string, parentId: string, insertIndex: number) {
- const parent = graph.getNode(parentId)
- if (!parent || parent.layoutMode === 'NONE') return
-
+ function doReorderChild(nodeId: string, parentId: string, insertIndex: number) {
const node = graph.getNode(nodeId)
if (!node) return
- // Convert position if coming from different parent
if (node.parentId !== parentId) {
const absPos = graph.getAbsolutePosition(nodeId)
const parentAbs = graph.getAbsolutePosition(parentId)
@@ -405,6 +402,72 @@ export function createEditorStore() {
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)
+ requestRender()
+ },
+ 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)
+ }
+ requestRender()
+ }
+ })
+
+ requestRender()
+ }
+
+ 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)
+ requestRender()
+ },
+ inverse: () => {
+ graph.reorderChild(nodeId, origParentId, origIndex)
+ graph.updateNode(nodeId, { x: origX, y: origY })
+ runLayoutForNode(origParentId)
+ if (origParentId !== newParentId) runLayoutForNode(newParentId)
+ requestRender()
+ }
+ })
+
requestRender()
}
@@ -1984,6 +2047,77 @@ export function createEditorStore() {
})
}
+ 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 })
+ }
+ for (const [id] of finals) syncIfInsideComponent(id)
+ 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)
+ }
+ for (const [id] of finals) syncIfInsideComponent(id)
+ requestRender()
+ },
+ inverse: () => {
+ for (const [id, pos] of originals) {
+ graph.reparentNode(id, pos.parentId)
+ graph.updateNode(id, { x: pos.x, y: pos.y })
+ runLayoutForNode(id)
+ }
+ for (const [id] of originals) syncIfInsideComponent(id)
+ requestRender()
+ }
+ })
+ }
+
+ 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)
+ }
+
+ 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
@@ -2175,6 +2309,7 @@ export function createEditorStore() {
setLayoutInsertIndicator,
reorderInAutoLayout,
reparentNodes,
+ reorderChildWithUndo,
penAddVertex,
penSetDragTangent,
penSetClosingToFirst,
@@ -2215,12 +2350,16 @@ export function createEditorStore() {
mobilePaste,
deleteSelected,
commitMove,
+ commitMoveWithReparent,
commitResize,
commitRotation,
commitNodeUpdate,
updateNodeWithUndo,
undoAction,
redoAction,
+ snapshotPage,
+ restorePageFromSnapshot,
+ pushUndoEntry,
screenToCanvas,
applyZoom,
pan,