AI-native design editor. Open-source Figma alternative.
fix(components): respect default variants in assets
Danila Poyarkov24d3ea748f0b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 85d9587ea..ab4e506a2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,7 +9,7 @@- Bind variables to line height, letter spacing, font weight, paragraph spacing, and paragraph indent in the typography inspector.- Add editor event bus with typed lifecycle events — subscribe via `editor.onEditorEvent()` in core or `useEditorEvent()` composable in the Vue SDK.- Register desktop file associations for `.fig` and `.pen` so supported design files can be opened from OS file browsers with OpenPencil.-- Add a local Assets panel for document components and component sets, with grouped variant assets and instance insertion.+- Add a local Assets panel for document components and component sets, with grouped variant assets, default variant insertion, and duplicate variant warnings.### Changeddiff --git a/packages/core/src/editor/bridges/components.ts b/packages/core/src/editor/bridges/components.tsindex 30a9b0bb1..988c34fa0 100644--- a/packages/core/src/editor/bridges/components.ts+++ b/packages/core/src/editor/bridges/components.ts@@ -35,6 +35,8 @@ export function createComponentBridge(renamePropertyDefinition: components.renamePropertyDefinition,collectVariantOptions: components.collectVariantOptions,findVariantByValues: components.findVariantByValues,+ getDefaultVariantForComponentSet: components.getDefaultVariantForComponentSet,+ getComponentSetVariantConflicts: components.getComponentSetVariantConflicts,switchInstanceVariant: components.switchInstanceVariant}}diff --git a/packages/core/src/editor/components/variants.ts b/packages/core/src/editor/components/variants.tsindex 637cf9e5a..39da7f208 100644--- a/packages/core/src/editor/components/variants.ts+++ b/packages/core/src/editor/components/variants.ts@@ -6,6 +6,15 @@ import type {SceneNode} from '#core/scene-graph'+export type VariantConflict = {+ values: Record<string, string>+ componentIds: string[]+}++function sortByCanvasPosition(a: SceneNode, b: SceneNode) {+ return a.y - b.y || a.x - b.x || a.name.localeCompare(b.name)+}+export function createVariantActions(ctx: EditorContext) {function getComponentSetPropertyDefs(componentSetId: string): ComponentPropertyDefinition[] {const node = ctx.graph.getNode(componentSetId)@@ -181,15 +190,19 @@ export function createVariantActions(ctx: EditorContext) {return options}+ function getComponentSetVariants(componentSetId: string): SceneNode[] {+ const node = ctx.graph.getNode(componentSetId)+ if (node?.type !== 'COMPONENT_SET') return []+ return node.childIds+ .map((id) => ctx.graph.getNode(id))+ .filter((child): child is SceneNode => child?.type === 'COMPONENT')+ }+function findVariantByValues(componentSetId: string,values: Record<string, string>): SceneNode | undefined {- const node = ctx.graph.getNode(componentSetId)- if (node?.type !== 'COMPONENT_SET') return undefined- for (const childId of node.childIds) {- const child = ctx.graph.getNode(childId)- if (child?.type !== 'COMPONENT') continue+ for (const child of getComponentSetVariants(componentSetId).sort(sortByCanvasPosition)) {const childValues = child.componentPropertyValuesconst matches = Object.entries(values).every(([k, v]) => childValues[k] === v)if (matches) return child@@ -197,6 +210,45 @@ export function createVariantActions(ctx: EditorContext) {return undefined}+ function getDefaultVariantForComponentSet(componentSetId: string): SceneNode | undefined {+ const node = ctx.graph.getNode(componentSetId)+ if (node?.type !== 'COMPONENT_SET') return undefined++ const defaultValues = Object.fromEntries(+ node.componentPropertyDefinitions+ .filter((def) => def.type === 'VARIANT' && def.defaultValue)+ .map((def) => [def.name, def.defaultValue])+ )+ if (Object.keys(defaultValues).length > 0) {+ const explicitDefault = findVariantByValues(componentSetId, defaultValues)+ if (explicitDefault) return explicitDefault+ }++ return getComponentSetVariants(componentSetId).sort(sortByCanvasPosition)[0]+ }++ function getComponentSetVariantConflicts(componentSetId: string): VariantConflict[] {+ const node = ctx.graph.getNode(componentSetId)+ if (node?.type !== 'COMPONENT_SET') return []++ const propNames = node.componentPropertyDefinitions+ .filter((def) => def.type === 'VARIANT')+ .map((def) => def.name)+ const byKey = new Map<string, { values: Record<string, string>; componentIds: string[] }>()++ for (const variant of getComponentSetVariants(componentSetId)) {+ const values = Object.fromEntries(+ propNames.map((name) => [name, variant.componentPropertyValues[name] ?? ''])+ )+ const key = propNames.map((name) => `${name}=${values[name]}`).join('\u0000')+ const entry = byKey.get(key) ?? { values, componentIds: [] }+ entry.componentIds.push(variant.id)+ byKey.set(key, entry)+ }++ return [...byKey.values()].filter((entry) => entry.componentIds.length > 1)+ }+function switchInstanceVariant(instanceId: string, propertyName: string, newValue: string) {const instance = ctx.graph.getNode(instanceId)if (instance?.type !== 'INSTANCE' || !instance.componentId) return@@ -238,6 +290,8 @@ export function createVariantActions(ctx: EditorContext) {buildVariantName,collectVariantOptions,findVariantByValues,+ getDefaultVariantForComponentSet,+ getComponentSetVariantConflicts,switchInstanceVariant}}diff --git a/src/components/AssetsPanel.vue b/src/components/AssetsPanel.vueindex 7fa84d5ac..c38e2eec1 100644--- a/src/components/AssetsPanel.vue+++ b/src/components/AssetsPanel.vue@@ -17,6 +17,7 @@ type LocalAsset = {componentId: string | nullvariants: Array<{ name: string; values: string[] }>variantCount: number+ hasConflicts: boolean}const editor = useEditorStore()@@ -25,18 +26,6 @@ const query = ref('')const input = useInputUI({ size: 'sm' })const insertButton = useButtonUI({ tone: 'ghost', size: 'iconSm' })-function sortByCanvasPosition(a: SceneNode, b: SceneNode) {- return a.y - b.y || a.x - b.x || a.name.localeCompare(b.name)-}--function componentSetDefaultVariant(componentSet: SceneNode): SceneNode | null {- const variants = componentSet.childIds- .map((id) => editor.graph.getNode(id))- .filter((node): node is SceneNode => node?.type === 'COMPONENT')- .sort(sortByCanvasPosition)- return variants[0] ?? null-}-function componentSetVariantInfo(componentSetId: string) {return [...editor.collectVariantOptions(componentSetId)].map(([name, values]) => ({name,@@ -58,7 +47,10 @@ const assets = computed<LocalAsset[]>(() => {return parent?.type !== 'COMPONENT_SET'}).map((node) => {- const defaultVariant = node.type === 'COMPONENT_SET' ? componentSetDefaultVariant(node) : node+ const defaultVariant =+ node.type === 'COMPONENT_SET' ? editor.getDefaultVariantForComponentSet(node.id) : node+ const conflicts =+ node.type === 'COMPONENT_SET' ? editor.getComponentSetVariantConflicts(node.id) : []const variants = node.type === 'COMPONENT_SET' ? componentSetVariantInfo(node.id) : []return {id: node.id,@@ -66,7 +58,8 @@ const assets = computed<LocalAsset[]>(() => {node,componentId: defaultVariant?.id ?? null,variants,- variantCount: node.type === 'COMPONENT_SET' ? node.childIds.length : 0+ variantCount: node.type === 'COMPONENT_SET' ? node.childIds.length : 0,+ hasConflicts: conflicts.length > 0}}).sort((a, b) => a.name.localeCompare(b.name))@@ -145,6 +138,13 @@ function insertAsset(asset: LocalAsset) {{{ asset.variantCount }} variants ·{{ asset.variants.map((variant) => variant.name).join(', ') }}</span>+ <span+ v-if="asset.hasConflicts"+ data-test-id="asset-variant-conflict"+ class="mt-0.5 block truncate text-[10px] text-[var(--color-warning-text)]"+ >+ Duplicate variant values+ </span></span><Tip :label="commands.createInstance"><spandiff --git a/tests/e2e/components/assets-panel.spec.ts b/tests/e2e/components/assets-panel.spec.tsindex 4e753ed13..62cfc0952 100644--- a/tests/e2e/components/assets-panel.spec.ts+++ b/tests/e2e/components/assets-panel.spec.ts@@ -44,7 +44,7 @@ test('assets panel groups component sets and inserts the default variant', asyncid: 'prop:type',name: 'Type',type: 'VARIANT',- defaultValue: 'Primary',+ defaultValue: 'Secondary',variantOptions: ['Primary', 'Secondary']}]@@ -65,6 +65,14 @@ test('assets panel groups component sets and inserts the default variant', asyncheight: 40,componentPropertyValues: { Type: 'Secondary' }})+ const duplicateSecondary = store.graph.createNode('COMPONENT', set.id, {+ name: 'Type=Secondary duplicate',+ x: 240,+ y: 0,+ width: 96,+ height: 40,+ componentPropertyValues: { Type: 'Secondary' }+ })const card = store.graph.createNode('COMPONENT', pageNode.id, {name: 'Card',x: 80,@@ -73,7 +81,13 @@ test('assets panel groups component sets and inserts the default variant', asyncheight: 100})store.requestRender()- return { setId: set.id, primaryId: primary.id, secondaryId: secondary.id, cardId: card.id }+ return {+ setId: set.id,+ primaryId: primary.id,+ secondaryId: secondary.id,+ duplicateSecondaryId: duplicateSecondary.id,+ cardId: card.id+ }})await canvas.waitForRender()@@ -89,6 +103,9 @@ test('assets panel groups component sets and inserts the default variant', asyncawait expect(page.locator(`[data-asset-id="${ids.setId}"] [data-test-id="asset-variant-summary"]`)).toContainText('Type')+ await expect(+ page.locator(`[data-asset-id="${ids.setId}"] [data-test-id="asset-variant-conflict"]`)+ ).toContainText('Duplicate variant values')await page.locator('[data-test-id="assets-search"]').fill('card')await expect(assetItems).toHaveCount(1)@@ -112,13 +129,13 @@ test('assets panel groups component sets and inserts the default variant', asyncconst inserted = await selectedNodeSnapshot(page)expect(inserted?.type).toBe('INSTANCE')- expect(inserted?.componentId).toBe(ids.primaryId)+ expect(inserted?.componentId).toBe(ids.secondaryId)expect(inserted?.parentId).toBe(inserted?.pageId)await expect(page.locator('[data-test-id="variant-section"]')).toBeVisible()await page.locator('[data-test-id="variant-section"] [data-test-id="app-select-trigger"]').click()- await page.getByRole('option', { name: 'Secondary' }).click()+ await page.getByRole('option', { name: 'Primary' }).click()const switchedComponentId = await page.evaluate((instanceId) => {@@ -128,7 +145,7 @@ test('assets panel groups component sets and inserts the default variant', async},expectDefined(inserted?.id, 'inserted instance id'))- expect(switchedComponentId).toBe(ids.secondaryId)+ expect(switchedComponentId).toBe(ids.primaryId)canvas.assertNoErrors()})