AI-native design editor. Open-source Figma alternative.
Add variables support: collections, modes, bindings, UI panel
Danila Poyarkovd30ab4c5d503
diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 7669b9ce4..d75f46187 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -38,7 +38,12 @@ export {type VectorSegment,type VectorRegion,type HandleMirroring,- type WindingRule+ type WindingRule,+ type VariableType,+ type VariableValue,+ type Variable,+ type VariableCollection,+ type VariableCollectionMode} from './scene-graph'export { SkiaRenderer, type RenderOverlays } from './renderer'diff --git a/packages/core/src/kiwi/fig-import.ts b/packages/core/src/kiwi/fig-import.tsindex 5d4ceda3c..6abbfd44e 100644--- a/packages/core/src/kiwi/fig-import.ts+++ b/packages/core/src/kiwi/fig-import.ts@@ -137,10 +137,12 @@ function convertEffects(effects?: KiwiEffect[]): Effect[] {}))}-function mapNodeType(type?: string): NodeType | 'DOCUMENT' {+function mapNodeType(type?: string): NodeType | 'DOCUMENT' | 'VARIABLE' {switch (type) {case 'DOCUMENT':return 'DOCUMENT'+ case 'VARIABLE':+ return 'VARIABLE'case 'CANVAS':return 'CANVAS'case 'FRAME':@@ -357,7 +359,7 @@ export function importNodeChanges(if (!nc) returnconst nodeType = mapNodeType(nc.type)- if (nodeType === 'DOCUMENT') return+ if (nodeType === 'DOCUMENT' || nodeType === 'VARIABLE') returnconst x = nc.transform?.m02 ?? 0const y = nc.transform?.m12 ?? 0@@ -437,7 +439,8 @@ export function importNodeChanges(borderRightWeight: (ext(nc).borderRightWeight as number) ?? 0,borderBottomWeight: (ext(nc).borderBottomWeight as number) ?? 0,borderLeftWeight: (ext(nc).borderLeftWeight as number) ?? 0,- independentStrokeWeights: (ext(nc).borderStrokeWeightsIndependent as boolean) ?? false+ independentStrokeWeights: (ext(nc).borderStrokeWeightsIndependent as boolean) ?? false,+ boundVariables: extractBoundVariables(nc)})for (const childId of getChildren(ncId)) {@@ -445,6 +448,70 @@ export function importNodeChanges(}}+ function extractBoundVariables(nc: NodeChange): Record<string, string> {+ const bindings: Record<string, string> = {}+ nc.fillPaints?.forEach((paint, i) => {+ if (paint.colorVariableBinding) {+ bindings[`fills/${i}/color`] = guidToString(paint.colorVariableBinding.variableID)+ }+ })+ nc.strokePaints?.forEach((paint, i) => {+ if (paint.colorVariableBinding) {+ bindings[`strokes/${i}/color`] = guidToString(paint.colorVariableBinding.variableID)+ }+ })+ return bindings+ }++ function importVariables() {+ for (const [id, nc] of changeMap) {+ if (nc.type !== 'VARIABLE') continue+ const varData = (ext(nc) as { variableData?: { value?: { boolValue?: boolean; textValue?: string; floatValue?: number }; dataType?: string } }).variableData+ if (!varData) continue++ const parentId = parentMap.get(id) ?? ''+ const parentNc = changeMap.get(parentId)+ const collectionName = parentNc?.name ?? 'Variables'+ const collectionId = parentId++ if (!graph.variableCollections.has(collectionId)) {+ graph.addCollection({+ id: collectionId,+ name: collectionName,+ modes: [{ modeId: 'default', name: 'Default' }],+ defaultModeId: 'default',+ variableIds: []+ })+ }++ let type: import('../scene-graph').VariableType = 'FLOAT'+ let value: import('../scene-graph').VariableValue = 0+ const dt = varData.dataType+ const v = varData.value++ if (dt === 'BOOLEAN' || dt === '0') {+ type = 'BOOLEAN'+ value = v?.boolValue ?? false+ } else if (dt === 'STRING' || dt === '2') {+ type = 'STRING'+ value = v?.textValue ?? ''+ } else {+ type = 'FLOAT'+ value = v?.floatValue ?? 0+ }++ graph.addVariable({+ id,+ name: nc.name ?? 'Variable',+ type,+ collectionId,+ valuesByMode: { default: value },+ description: '',+ hiddenFromPublishing: false+ })+ }+ }+// Find the document node (type=DOCUMENT or guid 0:0)let docId: string | null = nullfor (const [id, nc] of changeMap) {@@ -482,6 +549,8 @@ export function importNodeChanges(}}+ importVariables()+// Ensure at least one page existsif (graph.getPages().length === 0) {graph.addPage('Page 1')diff --git a/packages/core/src/renderer.ts b/packages/core/src/renderer.tsindex 75a9caa7f..25e4301b2 100644--- a/packages/core/src/renderer.ts+++ b/packages/core/src/renderer.ts@@ -57,7 +57,8 @@ import {import { vectorNetworkToPath } from './vector'-import type { SceneNode, SceneGraph, Fill } from './scene-graph'+import type { SceneNode, SceneGraph, Fill, Stroke } from './scene-graph'+import type { Color } from './types'import type { SnapGuide } from './snap'import type { Rect } from './types'import type { EmbindEnumEntity, Image as CKImage, Path } from 'canvaskit-wasm'@@ -945,20 +946,21 @@ export class SkiaRenderer {const rrect = this.ck.RRectXY(rect, SECTION_CORNER_RADIUS, SECTION_CORNER_RADIUS)// Fill- for (const fill of node.fills) {+ for (let fi = 0; fi < node.fills.length; fi++) {+ const fill = node.fills[fi]!if (!fill.visible) continue- this.applyFill(fill, node, graph)+ this.applyFill(fill, node, graph, fi)this.fillPaint.setAlphaf(fill.opacity)canvas.drawRRect(rrect, this.fillPaint)this.fillPaint.setShader(null)}// Stroke- for (const stroke of node.strokes) {+ for (let si = 0; si < node.strokes.length; si++) {+ const stroke = node.strokes[si]!if (!stroke.visible) continue- this.strokePaint.setColor(- this.ck.Color4f(stroke.color.r, stroke.color.g, stroke.color.b, stroke.color.a)- )+ const sc = this.resolveStrokeColor(stroke, si, node, graph)+ this.strokePaint.setColor(this.ck.Color4f(sc.r, sc.g, sc.b, sc.a))this.strokePaint.setStrokeWidth(stroke.weight)this.strokePaint.setAlphaf(stroke.opacity)canvas.drawRRect(rrect, this.strokePaint)@@ -1171,9 +1173,10 @@ export class SkiaRenderer {const rect = this.ck.LTRBRect(0, 0, node.width, node.height)const rrect = this.ck.RRectXY(rect, 5, 5)- for (const fill of node.fills) {+ for (let fi = 0; fi < node.fills.length; fi++) {+ const fill = node.fills[fi]!if (!fill.visible) continue- this.applyFill(fill, node, graph)+ this.applyFill(fill, node, graph, fi)this.fillPaint.setAlphaf(fill.opacity)canvas.drawRRect(rrect, this.fillPaint)this.fillPaint.setShader(null)@@ -1203,9 +1206,10 @@ export class SkiaRenderer {node.bottomLeftRadius > 0))// Fills- for (const fill of node.fills) {+ for (let fi = 0; fi < node.fills.length; fi++) {+ const fill = node.fills[fi]!if (!fill.visible) continue- this.applyFill(fill, node, graph)+ this.applyFill(fill, node, graph, fi)this.fillPaint.setAlphaf(fill.opacity)this.drawNodeFill(canvas, node, rect, hasRadius)@@ -1216,11 +1220,11 @@ export class SkiaRenderer {this.renderEffects(canvas, node, rect, hasRadius, 'behind')// Strokes- for (const stroke of node.strokes) {+ for (let si = 0; si < node.strokes.length; si++) {+ const stroke = node.strokes[si]!if (!stroke.visible) continue- this.strokePaint.setColor(- this.ck.Color4f(stroke.color.r, stroke.color.g, stroke.color.b, stroke.color.a)- )+ const sc = this.resolveStrokeColor(stroke, si, node, graph)+ this.strokePaint.setColor(this.ck.Color4f(sc.r, sc.g, sc.b, sc.a))this.strokePaint.setStrokeWidth(stroke.weight)this.strokePaint.setAlphaf(stroke.opacity)@@ -1563,13 +1567,30 @@ export class SkiaRenderer {}}- private applyFill(fill: Fill, node: SceneNode, graph: SceneGraph): void {+ resolveFillColor(fill: Fill, fillIndex: number, node: SceneNode, graph: SceneGraph): Color {+ const varId = node.boundVariables[`fills/${fillIndex}/color`]+ if (varId) {+ const resolved = graph.resolveColorVariable(varId)+ if (resolved) return resolved+ }+ return fill.color+ }++ resolveStrokeColor(stroke: Stroke, strokeIndex: number, node: SceneNode, graph: SceneGraph): Color {+ const varId = node.boundVariables[`strokes/${strokeIndex}/color`]+ if (varId) {+ const resolved = graph.resolveColorVariable(varId)+ if (resolved) return resolved+ }+ return stroke.color+ }++ private applyFill(fill: Fill, node: SceneNode, graph: SceneGraph, fillIndex = 0): void {this.fillPaint.setShader(null)if (fill.type === 'SOLID') {- this.fillPaint.setColor(- this.ck.Color4f(fill.color.r, fill.color.g, fill.color.b, fill.color.a)- )+ const c = this.resolveFillColor(fill, fillIndex, node, graph)+ this.fillPaint.setColor(this.ck.Color4f(c.r, c.g, c.b, c.a))return}diff --git a/packages/core/src/scene-graph.ts b/packages/core/src/scene-graph.tsindex 026895d1e..cc018e4ba 100644--- a/packages/core/src/scene-graph.ts+++ b/packages/core/src/scene-graph.ts@@ -224,6 +224,34 @@ export interface SceneNode {componentId: string | nulloverrides: Record<string, unknown>++ boundVariables: Record<string, string>+}++export type VariableType = 'COLOR' | 'FLOAT' | 'STRING' | 'BOOLEAN'+export type VariableValue = Color | number | string | boolean | { aliasId: string }++export interface Variable {+ id: string+ name: string+ type: VariableType+ collectionId: string+ valuesByMode: Record<string, VariableValue>+ description: string+ hiddenFromPublishing: boolean+}++export interface VariableCollectionMode {+ modeId: string+ name: string+}++export interface VariableCollection {+ id: string+ name: string+ modes: VariableCollectionMode[]+ defaultModeId: string+ variableIds: string[]}let nextLocalID = 1@@ -302,6 +330,7 @@ function createDefaultNode(type: NodeType, overrides: Partial<SceneNode> = {}):starInnerRadius: 0.38,componentId: null,overrides: {},+ boundVariables: {},...overrides}}@@ -319,6 +348,9 @@ const CONTAINER_TYPES = new Set<NodeType>([export class SceneGraph {nodes = new Map<string, SceneNode>()images = new Map<string, Uint8Array>()+ variables = new Map<string, Variable>()+ variableCollections = new Map<string, VariableCollection>()+ activeMode = new Map<string, string>()rootId: stringconstructor() {@@ -349,6 +381,108 @@ export class SceneGraph {return this.nodes.get(id)}+ // --- Variables ---++ addVariable(variable: Variable): void {+ this.variables.set(variable.id, variable)+ const collection = this.variableCollections.get(variable.collectionId)+ if (collection && !collection.variableIds.includes(variable.id)) {+ collection.variableIds.push(variable.id)+ }+ }++ removeVariable(id: string): void {+ const variable = this.variables.get(id)+ if (!variable) return+ this.variables.delete(id)+ const collection = this.variableCollections.get(variable.collectionId)+ if (collection) {+ collection.variableIds = collection.variableIds.filter((vid) => vid !== id)+ }+ for (const node of this.nodes.values()) {+ for (const [field, varId] of Object.entries(node.boundVariables)) {+ if (varId === id) delete node.boundVariables[field]+ }+ }+ }++ addCollection(collection: VariableCollection): void {+ this.variableCollections.set(collection.id, collection)+ if (!this.activeMode.has(collection.id)) {+ this.activeMode.set(collection.id, collection.defaultModeId)+ }+ }++ removeCollection(id: string): void {+ const collection = this.variableCollections.get(id)+ if (collection) {+ for (const varId of [...collection.variableIds]) {+ this.removeVariable(varId)+ }+ }+ this.variableCollections.delete(id)+ this.activeMode.delete(id)+ }++ getActiveModeId(collectionId: string): string {+ const mode = this.activeMode.get(collectionId)+ if (mode) return mode+ const collection = this.variableCollections.get(collectionId)+ return collection?.defaultModeId ?? ''+ }++ setActiveMode(collectionId: string, modeId: string): void {+ this.activeMode.set(collectionId, modeId)+ }++ resolveVariable(variableId: string, modeId?: string, visited?: Set<string>): VariableValue | undefined {+ if (visited?.has(variableId)) return undefined+ const variable = this.variables.get(variableId)+ if (!variable) return undefined+ const resolvedModeId = modeId ?? this.getActiveModeId(variable.collectionId)+ const value = variable.valuesByMode[resolvedModeId]+ if (value === undefined) return undefined+ if (typeof value === 'object' && value !== null && 'aliasId' in value) {+ const seen = visited ?? new Set<string>()+ seen.add(variableId)+ return this.resolveVariable(value.aliasId, undefined, seen)+ }+ return value+ }++ resolveColorVariable(variableId: string): Color | undefined {+ const value = this.resolveVariable(variableId)+ if (value && typeof value === 'object' && 'r' in value) return value as Color+ return undefined+ }++ resolveNumberVariable(variableId: string): number | undefined {+ const value = this.resolveVariable(variableId)+ return typeof value === 'number' ? value : undefined+ }++ getVariablesForCollection(collectionId: string): Variable[] {+ const collection = this.variableCollections.get(collectionId)+ if (!collection) return []+ return collection.variableIds+ .map((id) => this.variables.get(id))+ .filter((v): v is Variable => v !== undefined)+ }++ getVariablesByType(type: VariableType): Variable[] {+ return [...this.variables.values()].filter((v) => v.type === type)+ }++ bindVariable(nodeId: string, field: string, variableId: string): void {+ const node = this.nodes.get(nodeId)+ if (node) node.boundVariables[field] = variableId+ }++ unbindVariable(nodeId: string, field: string): void {+ const node = this.nodes.get(nodeId)+ if (node) delete node.boundVariables[field]+ }+getChildren(id: string): SceneNode[] {const node = this.nodes.get(id)if (!node) return []diff --git a/src/App.vue b/src/App.vueindex 5abf627c3..2a0f3dc82 100644--- a/src/App.vue+++ b/src/App.vue@@ -1,5 +1,6 @@<script setup lang="ts">import { useEventListener, useUrlSearchParams } from '@vueuse/core'+import { ref } from 'vue'import { SplitterGroup, SplitterPanel, SplitterResizeHandle } from 'reka-ui'import { useKeyboard } from './composables/use-keyboard'@@ -9,6 +10,7 @@ import { provideEditorStore } from './stores/editor'import EditorCanvas from './components/EditorCanvas.vue'import LayersPanel from './components/LayersPanel.vue'+import VariablesPanel from './components/VariablesPanel.vue'import PropertiesPanel from './components/PropertiesPanel.vue'import Toolbar from './components/Toolbar.vue'@@ -26,6 +28,7 @@ useEventListener({ passive: false })+const showVariables = ref(false)const params = useUrlSearchParams('history')const showChrome = !('no-chrome' in params)if (!('test' in params)) {@@ -41,8 +44,28 @@ if (!('test' in params)) {class="flex-1 overflow-hidden"auto-save-id="editor-layout">- <SplitterPanel :default-size="15" :min-size="10" :max-size="30" class="flex">- <LayersPanel />+ <SplitterPanel :default-size="15" :min-size="10" :max-size="30" class="flex flex-col">+ <SplitterGroup v-if="showVariables" direction="vertical" class="flex-1 overflow-hidden">+ <SplitterPanel :default-size="60" :min-size="20" class="flex">+ <LayersPanel />+ </SplitterPanel>+ <SplitterResizeHandle class="group relative z-10 -my-1 h-2 cursor-row-resize">+ <div class="pointer-events-none absolute inset-x-0 top-1/2 h-px -translate-y-1/2" />+ </SplitterResizeHandle>+ <SplitterPanel :default-size="40" :min-size="20" class="flex">+ <VariablesPanel />+ </SplitterPanel>+ </SplitterGroup>+ <template v-else>+ <LayersPanel />+ </template>+ <button+ class="flex w-full cursor-pointer items-center justify-center gap-1 border-t border-border bg-transparent px-2 py-1 text-[11px] text-muted hover:text-surface"+ @click="showVariables = !showVariables"+ >+ <icon-lucide-braces class="size-3" />+ {{ showVariables ? 'Hide variables' : 'Variables' }}+ </button></SplitterPanel><SplitterResizeHandle class="group relative z-10 -mx-1 w-2 cursor-col-resize"><div class="pointer-events-none absolute inset-y-0 left-1/2 w-px -translate-x-1/2" />diff --git a/src/components/LayersPanel.vue b/src/components/LayersPanel.vueindex 8af373f0e..66a418be1 100644--- a/src/components/LayersPanel.vue+++ b/src/components/LayersPanel.vue@@ -221,7 +221,10 @@ function updateDropTarget(ev: PointerEvent) {</script><template>- <aside class="flex min-w-0 flex-1 flex-col overflow-y-auto border-r border-border bg-panel" style="contain: paint layout style">+ <aside+ class="flex min-w-0 flex-1 flex-col overflow-y-auto border-r border-border bg-panel"+ style="contain: paint layout style"+ ><PagesPanel /><header class="shrink-0 px-3 py-2 text-[11px] uppercase tracking-wider text-muted">Layersdiff --git a/src/components/PropertiesPanel.vue b/src/components/PropertiesPanel.vueindex bdb3e9c9b..ed07848fc 100644--- a/src/components/PropertiesPanel.vue+++ b/src/components/PropertiesPanel.vue@@ -24,7 +24,10 @@ const isComponentType = computed(() => {</script><template>- <aside class="flex min-w-0 flex-1 flex-col overflow-hidden border-l border-border bg-panel" style="contain: paint layout style">+ <aside+ class="flex min-w-0 flex-1 flex-col overflow-hidden border-l border-border bg-panel"+ style="contain: paint layout style"+ ><!-- Tabs --><div class="flex h-10 shrink-0 items-center gap-1 border-b border-border px-2"><button class="rounded px-2.5 py-1 text-xs font-semibold text-surface">Design</button>diff --git a/src/components/VariablesPanel.vue b/src/components/VariablesPanel.vuenew file mode 100644index 000000000..aac3f01d2--- /dev/null+++ b/src/components/VariablesPanel.vue@@ -0,0 +1,279 @@+<script setup lang="ts">+import { ref, computed } from 'vue'+import {+ TabsRoot,+ TabsList,+ TabsTrigger,+ TabsContent,+ EditableRoot,+ EditableArea,+ EditableInput,+ EditablePreview+} from 'reka-ui'++import { colorToHexRaw } from '@/engine/color'+import { useEditorStore } from '@/stores/editor'+import type { Variable, VariableType, Color } from '@/engine/scene-graph'++const store = useEditorStore()++const collections = computed(() => {+ void store.state.sceneVersion+ return [...store.graph.variableCollections.values()]+})++const activeTab = ref(collections.value[0]?.id ?? '')++const variables = computed(() => {+ if (!activeTab.value) return []+ return store.graph.getVariablesForCollection(activeTab.value)+})++const groupedVariables = computed(() => {+ const groups = new Map<string, Variable[]>()+ for (const v of variables.value) {+ const parts = v.name.split('/')+ const group = parts.length > 1 ? parts.slice(0, -1).join('/') : ''+ const arr = groups.get(group) ?? []+ if (!groups.has(group)) groups.set(group, arr)+ arr.push(v)+ }+ return groups+})++function formatValue(variable: Variable): string {+ const modeId = store.graph.getActiveModeId(variable.collectionId)+ const value = variable.valuesByMode[modeId]+ if (value === undefined) return '—'+ if (typeof value === 'object' && 'r' in value) return colorToHexRaw(value as Color)+ if (typeof value === 'object' && 'aliasId' in value) {+ const aliased = store.graph.variables.get(value.aliasId)+ return aliased ? `→ ${aliased.name}` : '→ ?'+ }+ return String(value)+}++function getSwatchColor(variable: Variable): string | null {+ if (variable.type !== 'COLOR') return null+ const resolved = store.graph.resolveColorVariable(variable.id)+ if (!resolved) return null+ return `rgb(${Math.round(resolved.r * 255)}, ${Math.round(resolved.g * 255)}, ${Math.round(resolved.b * 255)})`+}++function shortName(variable: Variable): string {+ const parts = variable.name.split('/')+ return parts[parts.length - 1] ?? variable.name+}++function commitNameEdit(variable: Variable, newName: string) {+ if (newName && newName !== variable.name) {+ store.graph.variables.set(variable.id, { ...variable, name: newName })+ store.requestRender()+ }+}++function commitValueEdit(variable: Variable, newValue: string) {+ const modeId = store.graph.getActiveModeId(variable.collectionId)++ if (variable.type === 'COLOR') {+ const hex = newValue.replace('#', '')+ if (/^[0-9a-fA-F]{6}$/.test(hex)) {+ const r = parseInt(hex.slice(0, 2), 16) / 255+ const g = parseInt(hex.slice(2, 4), 16) / 255+ const b = parseInt(hex.slice(4, 6), 16) / 255+ variable.valuesByMode[modeId] = { r, g, b, a: 1 }+ }+ } else if (variable.type === 'FLOAT') {+ const num = parseFloat(newValue)+ if (!isNaN(num)) variable.valuesByMode[modeId] = num+ } else if (variable.type === 'BOOLEAN') {+ variable.valuesByMode[modeId] = newValue === 'true'+ } else {+ variable.valuesByMode[modeId] = newValue+ }+ store.requestRender()+}++function addVariable(type: VariableType) {+ const collection = store.graph.variableCollections.get(activeTab.value)+ if (!collection) return++ const defaults: Record<VariableType, import('@open-pencil/core').VariableValue> = {+ COLOR: { r: 0, g: 0, b: 0, a: 1 },+ FLOAT: 0,+ STRING: '',+ BOOLEAN: false+ }++ const id = `var:${Date.now()}`+ store.graph.addVariable({+ id,+ name: `New ${type.toLowerCase()}`,+ type,+ collectionId: collection.id,+ valuesByMode: { [collection.defaultModeId]: defaults[type] },+ description: '',+ hiddenFromPublishing: false+ })+ store.requestRender()+}++function addCollection() {+ const id = `col:${Date.now()}`+ store.graph.addCollection({+ id,+ name: 'New collection',+ modes: [{ modeId: 'default', name: 'Default' }],+ defaultModeId: 'default',+ variableIds: []+ })+ activeTab.value = id+}++function removeVariable(id: string) {+ store.graph.removeVariable(id)+ store.requestRender()+}+</script>++<template>+ <div class="flex h-full flex-col">+ <div class="flex items-center justify-between border-b border-border px-3 py-1.5">+ <span class="text-[11px] font-medium text-muted">Variables</span>+ <button+ class="flex size-5 cursor-pointer items-center justify-center rounded border-none bg-transparent text-xs text-muted hover:bg-hover hover:text-surface"+ title="Add collection"+ @click="addCollection"+ >+ <icon-lucide-folder-plus class="size-3.5" />+ </button>+ </div>++ <div v-if="collections.length === 0" class="px-3 py-4 text-center text-[11px] text-muted">+ No variables yet+ </div>++ <template v-else>+ <TabsRoot v-model="activeTab" class="flex flex-1 flex-col overflow-hidden">+ <TabsList class="flex gap-0.5 overflow-x-auto border-b border-border px-2 py-1">+ <TabsTrigger+ v-for="col in collections"+ :key="col.id"+ :value="col.id"+ class="cursor-pointer whitespace-nowrap rounded border-none px-2 py-0.5 text-[11px] text-muted data-[state=active]:bg-hover data-[state=active]:text-surface"+ >+ {{ col.name }}+ <span class="ml-1 text-[10px] opacity-50">{{ col.variableIds.length }}</span>+ </TabsTrigger>+ </TabsList>++ <TabsContent+ v-for="col in collections"+ :key="col.id"+ :value="col.id"+ class="flex-1 overflow-y-auto outline-none"+ >+ <template v-for="[group, vars] in groupedVariables" :key="group">+ <div+ v-if="group"+ class="px-3 pt-2 pb-0.5 text-[10px] font-medium uppercase tracking-wide text-muted"+ >+ {{ group }}+ </div>+ <div+ v-for="v in vars"+ :key="v.id"+ class="group flex items-center gap-2 px-3 py-1 hover:bg-hover"+ >+ <!-- Type indicator -->+ <div+ v-if="v.type === 'COLOR'"+ class="size-4 shrink-0 rounded border border-border"+ :style="{ background: getSwatchColor(v) ?? '#000' }"+ />+ <icon-lucide-hash+ v-else-if="v.type === 'FLOAT'"+ class="size-3.5 shrink-0 text-muted"+ />+ <icon-lucide-type+ v-else-if="v.type === 'STRING'"+ class="size-3.5 shrink-0 text-muted"+ />+ <icon-lucide-toggle-left v-else class="size-3.5 shrink-0 text-muted" />++ <!-- Editable name -->+ <EditableRoot+ :default-value="shortName(v)"+ class="min-w-0 flex-1"+ @submit="commitNameEdit(v, $event)"+ >+ <EditableArea class="flex">+ <EditablePreview class="min-w-0 flex-1 truncate text-[11px] text-surface" />+ <EditableInput+ class="min-w-0 flex-1 rounded border border-border bg-panel px-1 text-[11px] text-surface outline-none"+ />+ </EditableArea>+ </EditableRoot>++ <!-- Editable value -->+ <EditableRoot+ :default-value="formatValue(v)"+ class="w-20 shrink-0"+ @submit="commitValueEdit(v, $event)"+ >+ <EditableArea class="flex">+ <EditablePreview+ class="w-full truncate text-right font-mono text-[11px] text-muted"+ />+ <EditableInput+ class="w-full rounded border border-border bg-panel px-1 text-right font-mono text-[11px] text-surface outline-none"+ />+ </EditableArea>+ </EditableRoot>++ <!-- Delete -->+ <button+ class="cursor-pointer border-none bg-transparent p-0 text-muted opacity-0 transition-opacity group-hover:opacity-100 hover:text-surface"+ @click.stop="removeVariable(v.id)"+ >+ <icon-lucide-x class="size-3" />+ </button>+ </div>+ </template>+ </TabsContent>+ </TabsRoot>++ <!-- Add variable buttons -->+ <div class="flex gap-1 border-t border-border px-2 py-1.5">+ <button+ class="flex cursor-pointer items-center gap-1 rounded border-none bg-transparent px-2 py-0.5 text-[11px] text-muted hover:bg-hover hover:text-surface"+ @click="addVariable('COLOR')"+ >+ <div class="size-2.5 rounded-sm bg-current" />+ Color+ </button>+ <button+ class="flex cursor-pointer items-center gap-1 rounded border-none bg-transparent px-2 py-0.5 text-[11px] text-muted hover:bg-hover hover:text-surface"+ @click="addVariable('FLOAT')"+ >+ <icon-lucide-hash class="size-2.5" />+ Number+ </button>+ <button+ class="flex cursor-pointer items-center gap-1 rounded border-none bg-transparent px-2 py-0.5 text-[11px] text-muted hover:bg-hover hover:text-surface"+ @click="addVariable('STRING')"+ >+ <icon-lucide-type class="size-2.5" />+ String+ </button>+ <button+ class="flex cursor-pointer items-center gap-1 rounded border-none bg-transparent px-2 py-0.5 text-[11px] text-muted hover:bg-hover hover:text-surface"+ @click="addVariable('BOOLEAN')"+ >+ <icon-lucide-toggle-left class="size-2.5" />+ Bool+ </button>+ </div>+ </template>+ </div>+</template>diff --git a/src/components/properties/ExportSection.vue b/src/components/properties/ExportSection.vueindex 145b8840a..dda91462f 100644--- a/src/components/properties/ExportSection.vue+++ b/src/components/properties/ExportSection.vue@@ -163,10 +163,12 @@ function formatScale(scale: number): string {image-rendering: auto;background: repeating-conic-gradient(#808080 0% 25%, transparent 0% 50%) 50% / 16px 16px;"-/></div>- <div v-else-if="showPreview" class="mt-1 rounded border border-border px-3 py-2 text-[11px] text-muted">+ <div+ v-else-if="showPreview"+ class="mt-1 rounded border border-border px-3 py-2 text-[11px] text-muted"+ >Rendering preview…</div></div>diff --git a/src/components/properties/FillSection.vue b/src/components/properties/FillSection.vueindex 37130ec8c..452205d76 100644--- a/src/components/properties/FillSection.vue+++ b/src/components/properties/FillSection.vue@@ -1,14 +1,50 @@<script setup lang="ts">+import { computed, ref } from 'vue'+import {+ PopoverRoot,+ PopoverTrigger,+ PopoverPortal,+ PopoverContent,+ ComboboxRoot,+ ComboboxInput,+ ComboboxContent,+ ComboboxItem,+ ComboboxEmpty,+ useFilter+} from 'reka-ui'+import FillPicker from '@/components/FillPicker.vue'import ScrubInput from '@/components/ScrubInput.vue'import { useNodeProps } from '@/composables/use-node-props'import { DEFAULT_SHAPE_FILL } from '@/constants'import { colorToHexRaw } from '@/engine/color'--import type { Fill } from '@/engine/scene-graph'+import type { Fill, Variable, Color } from '@/engine/scene-graph'const { store, node } = useNodeProps()+const colorVariables = computed(() => store.graph.getVariablesByType('COLOR'))++function getBoundVariable(index: number): Variable | undefined {+ const varId = node.value.boundVariables[`fills/${index}/color`]+ return varId ? store.graph.variables.get(varId) : undefined+}++function bindVariable(index: number, variableId: string) {+ store.graph.bindVariable(node.value.id, `fills/${index}/color`, variableId)+ store.requestRender()+}++function unbindVariable(index: number) {+ store.graph.unbindVariable(node.value.id, `fills/${index}/color`)+ store.requestRender()+}++function resolvedSwatchStyle(variable: Variable): string {+ const color = store.graph.resolveColorVariable(variable.id)+ if (!color) return 'background: #000'+ return `background: rgb(${Math.round(color.r * 255)}, ${Math.round(color.g * 255)}, ${Math.round(color.b * 255)})`+}+function updateFill(index: number, fill: Fill) {const fills = [...node.value.fills]fills[index] = fill@@ -42,6 +78,13 @@ function remove(index: number) {'Remove fill')}++const searchTerm = ref('')+const { contains } = useFilter({ sensitivity: 'base' })+const filteredVariables = computed(() => {+ if (!searchTerm.value) return colorVariables.value+ return colorVariables.value.filter((v) => contains(v.name, searchTerm.value))+})</script><template>@@ -57,13 +100,32 @@ function remove(index: number) {</div><div v-for="(fill, i) in node.fills" :key="i" class="group flex items-center gap-1.5 py-0.5"><FillPicker :fill="fill" @update="updateFill(i, $event)" />- <span class="min-w-0 flex-1 font-mono text-xs text-surface">- <template v-if="fill.type === 'SOLID'">{{ colorToHexRaw(fill.color) }}</template>- <template v-else-if="fill.type.startsWith('GRADIENT')">{{- fill.type.replace('GRADIENT_', '')- }}</template>- <template v-else>{{ fill.type }}</template>- </span>++ <!-- Bound variable indicator or hex value -->+ <template v-if="getBoundVariable(i)">+ <span+ class="min-w-0 flex-1 truncate rounded bg-violet-500/10 px-1 font-mono text-xs text-violet-400"+ >+ {{ getBoundVariable(i)!.name }}+ </span>+ <button+ class="cursor-pointer border-none bg-transparent p-0 text-violet-400 hover:text-surface"+ title="Detach variable"+ @click="unbindVariable(i)"+ >+ <icon-lucide-unlink class="size-3" />+ </button>+ </template>+ <template v-else>+ <span class="min-w-0 flex-1 font-mono text-xs text-surface">+ <template v-if="fill.type === 'SOLID'">{{ colorToHexRaw(fill.color) }}</template>+ <template v-else-if="fill.type.startsWith('GRADIENT')">{{+ fill.type.replace('GRADIENT_', '')+ }}</template>+ <template v-else>{{ fill.type }}</template>+ </span>+ </template>+<ScrubInputclass="w-12"suffix="%"@@ -72,6 +134,51 @@ function remove(index: number) {:max="100"@update:model-value="updateOpacity(i, $event)"/>++ <!-- Variable picker -->+ <PopoverRoot+ v-if="colorVariables.length > 0 && fill.type === 'SOLID' && !getBoundVariable(i)"+ >+ <PopoverTrigger+ class="cursor-pointer border-none bg-transparent p-0 text-muted opacity-0 transition-opacity group-hover:opacity-100 hover:text-surface"+ title="Apply variable"+ >+ <icon-lucide-link class="size-3.5" />+ </PopoverTrigger>+ <PopoverPortal>+ <PopoverContent+ side="left"+ :side-offset="8"+ class="z-50 w-56 rounded-lg border border-border bg-panel shadow-lg"+ >+ <ComboboxRoot @update:model-value="bindVariable(i, ($event as Variable).id)">+ <ComboboxInput+ v-model="searchTerm"+ placeholder="Search variables…"+ class="w-full border-b border-border bg-transparent px-2 py-1.5 text-[11px] text-surface outline-none placeholder:text-muted"+ />+ <ComboboxContent class="max-h-48 overflow-y-auto p-1">+ <ComboboxEmpty class="px-2 py-3 text-center text-[11px] text-muted">+ No variables found+ </ComboboxEmpty>+ <ComboboxItem+ v-for="v in filteredVariables"+ :key="v.id"+ :value="v"+ class="flex cursor-pointer items-center gap-2 rounded px-2 py-1 text-[11px] text-surface data-[highlighted]:bg-hover"+ >+ <div+ class="size-3 shrink-0 rounded-sm border border-border"+ :style="resolvedSwatchStyle(v)"+ />+ <span class="min-w-0 flex-1 truncate">{{ v.name }}</span>+ </ComboboxItem>+ </ComboboxContent>+ </ComboboxRoot>+ </PopoverContent>+ </PopoverPortal>+ </PopoverRoot>+<buttonclass="cursor-pointer border-none bg-transparent p-0 text-muted opacity-0 transition-opacity group-hover:opacity-100 hover:text-surface"@click="toggleVisibility(i)"diff --git a/src/engine/scene-graph.ts b/src/engine/scene-graph.tsindex 5095d8ed2..d9f1574a2 100644--- a/src/engine/scene-graph.ts+++ b/src/engine/scene-graph.ts@@ -30,5 +30,10 @@ export type {VectorSegment,VectorRegion,HandleMirroring,- WindingRule+ WindingRule,+ VariableType,+ VariableValue,+ Variable,+ VariableCollection,+ VariableCollectionMode} from '@open-pencil/core'diff --git a/src/engine/vector.ts b/src/engine/vector.tsindex 38e483a6a..9b4d74151 100644--- a/src/engine/vector.ts+++ b/src/engine/vector.ts@@ -1 +1,6 @@-export { vectorNetworkToPath, decodeVectorNetworkBlob, encodeVectorNetworkBlob, computeVectorBounds } from '@open-pencil/core'+export {+ vectorNetworkToPath,+ decodeVectorNetworkBlob,+ encodeVectorNetworkBlob,+ computeVectorBounds+} from '@open-pencil/core'diff --git a/tests/engine/scene-graph.test.ts b/tests/engine/scene-graph.test.tsindex 20165bdc4..3ab8c8d49 100644--- a/tests/engine/scene-graph.test.ts+++ b/tests/engine/scene-graph.test.ts@@ -144,3 +144,185 @@ describe('SceneGraph', () => {expect(graph.getInstances(comp.id)).toHaveLength(0)})})++describe('Variables', () => {+ function pageId(graph: SceneGraph): string {+ return graph.getPages()[0]!.id+ }++ test('add and resolve color variable', () => {+ const graph = new SceneGraph()+ graph.addCollection({+ id: 'col1',+ name: 'Colors',+ modes: [{ modeId: 'm1', name: 'Light' }],+ defaultModeId: 'm1',+ variableIds: []+ })+ graph.addVariable({+ id: 'v1',+ name: 'Primary',+ type: 'COLOR',+ collectionId: 'col1',+ valuesByMode: { m1: { r: 0, g: 0.5, b: 1, a: 1 } },+ description: '',+ hiddenFromPublishing: false+ })++ const color = graph.resolveColorVariable('v1')+ expect(color).toEqual({ r: 0, g: 0.5, b: 1, a: 1 })+ })++ test('resolve number variable', () => {+ const graph = new SceneGraph()+ graph.addCollection({+ id: 'col1',+ name: 'Spacing',+ modes: [{ modeId: 'm1', name: 'Default' }],+ defaultModeId: 'm1',+ variableIds: []+ })+ graph.addVariable({+ id: 'v1',+ name: 'spacing/md',+ type: 'FLOAT',+ collectionId: 'col1',+ valuesByMode: { m1: 16 },+ description: '',+ hiddenFromPublishing: false+ })++ expect(graph.resolveNumberVariable('v1')).toBe(16)+ })++ test('resolve alias variable', () => {+ const graph = new SceneGraph()+ graph.addCollection({+ id: 'col1',+ name: 'Tokens',+ modes: [{ modeId: 'm1', name: 'Light' }],+ defaultModeId: 'm1',+ variableIds: []+ })+ graph.addVariable({+ id: 'v1',+ name: 'Blue/500',+ type: 'COLOR',+ collectionId: 'col1',+ valuesByMode: { m1: { r: 0, g: 0, b: 1, a: 1 } },+ description: '',+ hiddenFromPublishing: false+ })+ graph.addVariable({+ id: 'v2',+ name: 'Primary',+ type: 'COLOR',+ collectionId: 'col1',+ valuesByMode: { m1: { aliasId: 'v1' } },+ description: '',+ hiddenFromPublishing: false+ })++ expect(graph.resolveColorVariable('v2')).toEqual({ r: 0, g: 0, b: 1, a: 1 })+ })++ test('mode switching changes resolved value', () => {+ const graph = new SceneGraph()+ graph.addCollection({+ id: 'col1',+ name: 'Theme',+ modes: [+ { modeId: 'light', name: 'Light' },+ { modeId: 'dark', name: 'Dark' }+ ],+ defaultModeId: 'light',+ variableIds: []+ })+ graph.addVariable({+ id: 'v1',+ name: 'bg',+ type: 'COLOR',+ collectionId: 'col1',+ valuesByMode: {+ light: { r: 1, g: 1, b: 1, a: 1 },+ dark: { r: 0, g: 0, b: 0, a: 1 }+ },+ description: '',+ hiddenFromPublishing: false+ })++ expect(graph.resolveColorVariable('v1')).toEqual({ r: 1, g: 1, b: 1, a: 1 })+ graph.setActiveMode('col1', 'dark')+ expect(graph.resolveColorVariable('v1')).toEqual({ r: 0, g: 0, b: 0, a: 1 })+ })++ test('bind and unbind variable to node', () => {+ const graph = new SceneGraph()+ const node = graph.createNode('RECTANGLE', pageId(graph), { name: 'Rect' })++ graph.bindVariable(node.id, 'fills/0/color', 'v1')+ expect(node.boundVariables['fills/0/color']).toBe('v1')++ graph.unbindVariable(node.id, 'fills/0/color')+ expect(node.boundVariables['fills/0/color']).toBeUndefined()+ })++ test('removing variable cleans up bindings', () => {+ const graph = new SceneGraph()+ graph.addCollection({+ id: 'col1',+ name: 'Colors',+ modes: [{ modeId: 'm1', name: 'Default' }],+ defaultModeId: 'm1',+ variableIds: []+ })+ graph.addVariable({+ id: 'v1',+ name: 'Red',+ type: 'COLOR',+ collectionId: 'col1',+ valuesByMode: { m1: { r: 1, g: 0, b: 0, a: 1 } },+ description: '',+ hiddenFromPublishing: false+ })++ const node = graph.createNode('RECTANGLE', pageId(graph), { name: 'Rect' })+ graph.bindVariable(node.id, 'fills/0/color', 'v1')+ expect(node.boundVariables['fills/0/color']).toBe('v1')++ graph.removeVariable('v1')+ expect(node.boundVariables['fills/0/color']).toBeUndefined()+ expect(graph.variables.size).toBe(0)+ })++ test('circular alias does not infinite loop', () => {+ const graph = new SceneGraph()+ graph.addCollection({+ id: 'col1',+ name: 'Test',+ modes: [{ modeId: 'm1', name: 'Default' }],+ defaultModeId: 'm1',+ variableIds: []+ })+ graph.addVariable({+ id: 'v1',+ name: 'A',+ type: 'COLOR',+ collectionId: 'col1',+ valuesByMode: { m1: { aliasId: 'v2' } },+ description: '',+ hiddenFromPublishing: false+ })+ graph.addVariable({+ id: 'v2',+ name: 'B',+ type: 'COLOR',+ collectionId: 'col1',+ valuesByMode: { m1: { aliasId: 'v1' } },+ description: '',+ hiddenFromPublishing: false+ })++ expect(graph.resolveColorVariable('v1')).toBeUndefined()+ })+})