AI-native design editor. Open-source Figma alternative.
feat(properties): apply a variable mode to layers and pages, as in Figma (#1156)
Danila Poyarkov8d07929ba851
diff --git a/changes/1156/added.md b/changes/1156/added.mdnew file mode 100644index 000000000..bcb26a412--- /dev/null+++ b/changes/1156/added.md@@ -0,0 +1 @@+- Apply a variable mode to layers and pages from Appearance, or the Page section with nothing selected, as in Figma: choose Auto or a mode for each collection the layers use. Layers set to a mode show it after their name in Layers.diff --git a/packages/docs/.vitepress/sdk-sidebar.ts b/packages/docs/.vitepress/sdk-sidebar.tsindex 15ae50e15..d4c65fb94 100644--- a/packages/docs/.vitepress/sdk-sidebar.ts+++ b/packages/docs/.vitepress/sdk-sidebar.ts@@ -56,6 +56,7 @@ const SDK_COMPOSABLE_PAGES = [{ text: 'useSelectionLayout', slug: 'use-selection-layout', canonical: true },{ text: 'useSelectionColors', slug: 'use-selection-colors', canonical: true },{ text: 'useMask', slug: 'use-mask', canonical: true },+ { text: 'useVariableModes', slug: 'use-variable-modes', canonical: true },{ text: 'useDocumentWorkspace', slug: 'use-document-workspace', canonical: true },{ text: 'usePageList', slug: 'use-page-list' },{ text: 'useI18n', slug: 'use-i18n' },diff --git a/packages/docs/programmable/sdk/api/composables/index.md b/packages/docs/programmable/sdk/api/composables/index.mdindex 1b2ebdfa5..a04fe064d 100644--- a/packages/docs/programmable/sdk/api/composables/index.md+++ b/packages/docs/programmable/sdk/api/composables/index.md@@ -32,6 +32,7 @@ These are the main composables most `@open-pencil/vue` consumers will use.- [useSharedStyleBinding](./use-shared-style-binding)- [useColorModel](./use-color-model)- [useMask](./use-mask)+- [useVariableModes](./use-variable-modes)- [useTypography](./use-typography)- [useExport](./use-export)- [useFillControls](./use-fill-controls)diff --git a/packages/docs/programmable/sdk/api/composables/use-variable-modes.md b/packages/docs/programmable/sdk/api/composables/use-variable-modes.mdnew file mode 100644index 000000000..d0b03deb7--- /dev/null+++ b/packages/docs/programmable/sdk/api/composables/use-variable-modes.md@@ -0,0 +1,27 @@+---+title: useVariableModes+description: Read and set the variable modes the selection or the current page shows.+---++# useVariableModes++`useVariableModes()` provides headless state and actions for Figma's Apply variable mode control: the collections a mode can be set for on the selection, or on the current page when nothing is selected, and the mode each one shows.++## Usage++```ts+import { useVariableModes } from '@open-pencil/vue'++const { choices, applied, setMode } = useVariableModes()+```++- `choices` lists the collections with more than one mode that the selected layers use, through their own bindings or variables those alias; for a page, every such collection. Each has its `modes`, its `value` (the mode set on every target, `MIXED` when they differ, or `null` for Auto), and the `inherited` mode the targets show without one of their own.+- `applied` is the part of `choices` with a mode set on at least one target, which a panel shows as rows.+- `setMode(collectionId, modeId)` sets the mode on every target in one undo step; `null` clears it, so the targets inherit their parent's mode again.++`variableModeChoices(editor, nodes)` and `setVariableMode(editor, nodes, collectionId, modeId)` do the same for any layers, outside a component.++## Related APIs++- [useAppearance](./use-appearance)+- [SDK API Overview](../)diff --git a/packages/scene-graph/src/variables/bindings.ts b/packages/scene-graph/src/variables/bindings.tsindex ea3bc3a06..9f0c1e123 100644--- a/packages/scene-graph/src/variables/bindings.ts+++ b/packages/scene-graph/src/variables/bindings.ts@@ -229,6 +229,27 @@ function subtreeNodes(graph: SceneGraph, roots: Iterable<string>): SceneNode[] {return nodes}+/**+ * The collections whose variables the layers in these subtrees resolve: those they bind, and+ * those the bound variables alias, so a mode set on the subtrees can change what they show.+ */+export function collectionsBoundIn(graph: SceneGraph, roots: Iterable<string>): Set<string> {+ const pending = subtreeNodes(graph, roots).flatMap(boundVariableIds)+ const seen = new Set<string>()+ const collections = new Set<string>()+ for (let id = pending.pop(); id !== undefined; id = pending.pop()) {+ if (seen.has(id)) continue+ seen.add(id)+ const variable = graph.variables.get(id)+ if (!variable) continue+ collections.add(variable.collectionId)+ for (const value of Object.values(variable.valuesByMode)) {+ if (typeof value === 'object' && 'aliasId' in value) pending.push(value.aliasId)+ }+ }+ return collections+}+/*** The layers a change to these variables reaches: those binding one of them, or a variable that* aliases one, on the layer itself or on its characters.diff --git a/packages/vue/src/controls/variable-modes/helpers.ts b/packages/vue/src/controls/variable-modes/helpers.tsnew file mode 100644index 000000000..896dea5f0--- /dev/null+++ b/packages/vue/src/controls/variable-modes/helpers.ts@@ -0,0 +1,99 @@+import { omit } from 'es-toolkit'++import type { Editor } from '@open-pencil/core/editor'+import {+ collectionsBoundIn,+ isLibraryCollection,+ type SceneNode,+ type VariableCollection,+ type VariableCollectionMode+} from '@open-pencil/scene-graph'++import { MIXED, type MixedValue } from '#vue/controls/node-props/use'++/** A mode as the control lists it. */+export type VariableModeOption = Pick<VariableCollectionMode, 'modeId' | 'name'>++/** One collection a variable mode can be set for, as Figma's Apply variable mode menu lists it. */+export interface VariableModeChoice {+ collectionId: string+ name: string+ /** Whether the collection is a library's copy rather than the file's own. */+ library: boolean+ modes: VariableModeOption[]+ /** The mode every target sets, MIXED when they differ, or null when none sets one (Auto). */+ value: MixedValue<string | null>+ /** The mode the targets show without one of their own, null when they would show different ones. */+ inherited: VariableModeOption | null+}++function modeOption(collection: VariableCollection, modeId: string): VariableModeOption | null {+ const mode = collection.modes.find((candidate) => candidate.modeId === modeId)+ return mode ? { modeId: mode.modeId, name: mode.name } : null+}++function shared<T>(values: readonly T[]): MixedValue<T> {+ const [first] = values+ return values.every((value) => value === first) ? first : MIXED+}++/**+ * The collections a mode can be set for on `targets`, as Figma offers them: those with more than+ * one mode whose variables the targets' layers use, or every such collection for a page.+ */+export function variableModeChoices(editor: Editor, targets: SceneNode[]): VariableModeChoice[] {+ if (targets.length === 0) return []+ const { graph } = editor+ const page = targets.every((target) => target.type === 'CANVAS')+ const used = page+ ? null+ : collectionsBoundIn(+ graph,+ targets.map((target) => target.id)+ )+ const choices: VariableModeChoice[] = []+ for (const collection of graph.variableCollections.values()) {+ if (collection.modes.length < 2) continue+ if (used && !used.has(collection.id)) continue+ const inherited = shared(+ targets.map((target) =>+ target.parentId+ ? graph.getNodeVariableModeId(target.parentId, collection.id)+ : collection.defaultModeId+ )+ )+ choices.push({+ collectionId: collection.id,+ name: collection.name,+ library: isLibraryCollection(collection),+ modes: collection.modes.map((mode) => ({ modeId: mode.modeId, name: mode.name })),+ value: shared(targets.map((target) => target.variableModes[collection.id] ?? null)),+ inherited: inherited === MIXED ? null : modeOption(collection, inherited)+ })+ }+ return choices+}++/**+ * Sets the mode `targets` show for a collection, or clears it with null so they inherit their+ * parent's again, in one undo step.+ */+export function setVariableMode(+ editor: Editor,+ targets: SceneNode[],+ collectionId: string,+ modeId: string | null+): void {+ const changed = targets.filter(+ (target) => (target.variableModes[collectionId] ?? null) !== modeId+ )+ if (changed.length === 0) return+ const label = modeId ? 'Apply variable mode' : 'Remove variable mode'+ editor.undo.runBatch(label, () => {+ for (const target of changed) {+ const others = omit(target.variableModes, [collectionId])+ const variableModes = modeId ? { ...others, [collectionId]: modeId } : others+ editor.updateNodeWithUndo(target.id, { variableModes }, label)+ }+ })+}diff --git a/packages/vue/src/controls/variable-modes/use.ts b/packages/vue/src/controls/variable-modes/use.tsnew file mode 100644index 000000000..a43bd5229--- /dev/null+++ b/packages/vue/src/controls/variable-modes/use.ts@@ -0,0 +1,34 @@+import type { SceneNode } from '@open-pencil/scene-graph'++import { setVariableMode, variableModeChoices } from '#vue/controls/variable-modes/helpers'+import { useEditor } from '#vue/editor/context'+import { useSceneComputed } from '#vue/internal/scene-computed/use'++/**+ * Returns the variable modes the selection can show, or the current page's when nothing is+ * selected, and the action that sets or clears one.+ *+ * Use this composable for Figma's Apply variable mode control: `choices` lists the collections a+ * mode can be set for, and `applied` those a mode is set for on at least one target, which the+ * panel shows as rows.+ */+export function useVariableModes() {+ const editor = useEditor()++ const targets = useSceneComputed((): SceneNode[] => {+ const selected = [...editor.state.selectedIds]+ .map((id) => editor.getNode(id))+ .filter((node): node is SceneNode => node !== undefined)+ if (selected.length > 0) return selected+ const page = editor.getNode(editor.state.currentPageId)+ return page ? [page] : []+ })+ const choices = useSceneComputed(() => variableModeChoices(editor, targets.value))+ const applied = useSceneComputed(() => choices.value.filter((choice) => choice.value !== null))++ function setMode(collectionId: string, modeId: string | null) {+ setVariableMode(editor, targets.value, collectionId, modeId)+ }++ return { targets, choices, applied, setMode }+}diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.jsonindex 95be7dba6..0e7acac58 100644--- a/packages/vue/src/i18n/locales/de/panels.json+++ b/packages/vue/src/i18n/locales/de/panels.json@@ -580,5 +580,12 @@"behaviourStateUnset": "Keine","behaviourStateField": "Zustand {state}","searchComponentProperties": "Eigenschaften suchen",- "noComponentProperties": "Keine Eigenschaften gefunden"+ "noComponentProperties": "Keine Eigenschaften gefunden",+ "applyVariableMode": "Variablenmodus anwenden",+ "removeVariableMode": "Modus von {collection} entfernen",+ "variableModesInFile": "In dieser Datei erstellt",+ "variableModesFromLibraries": "Aus Bibliotheken",+ "variableModeAuto": "Automatisch ({mode})",+ "variableModeAutoMixed": "Automatisch",+ "variableModeHeading": "Modus"}diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.jsonindex 66713653f..b4d5b0c6a 100644--- a/packages/vue/src/i18n/locales/es/panels.json+++ b/packages/vue/src/i18n/locales/es/panels.json@@ -580,5 +580,12 @@"behaviourStateUnset": "Ninguno","behaviourStateField": "Estado {state}","searchComponentProperties": "Buscar propiedades",- "noComponentProperties": "No se encontraron propiedades"+ "noComponentProperties": "No se encontraron propiedades",+ "applyVariableMode": "Aplicar modo de variable",+ "removeVariableMode": "Quitar el modo de {collection}",+ "variableModesInFile": "Creadas en este archivo",+ "variableModesFromLibraries": "De bibliotecas",+ "variableModeAuto": "Automático ({mode})",+ "variableModeAutoMixed": "Automático",+ "variableModeHeading": "Modo"}diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.jsonindex 464045989..20b49df1c 100644--- a/packages/vue/src/i18n/locales/fr/panels.json+++ b/packages/vue/src/i18n/locales/fr/panels.json@@ -580,5 +580,12 @@"behaviourStateUnset": "Aucun","behaviourStateField": "État {state}","searchComponentProperties": "Rechercher des propriétés",- "noComponentProperties": "Aucune propriété trouvée"+ "noComponentProperties": "Aucune propriété trouvée",+ "applyVariableMode": "Appliquer un mode de variable",+ "removeVariableMode": "Retirer le mode de {collection}",+ "variableModesInFile": "Créées dans ce fichier",+ "variableModesFromLibraries": "Des bibliothèques",+ "variableModeAuto": "Auto ({mode})",+ "variableModeAutoMixed": "Auto",+ "variableModeHeading": "Mode"}diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.jsonindex 3e7377809..80f8c3a74 100644--- a/packages/vue/src/i18n/locales/it/panels.json+++ b/packages/vue/src/i18n/locales/it/panels.json@@ -580,5 +580,12 @@"behaviourStateUnset": "Nessuno","behaviourStateField": "Stato {state}","searchComponentProperties": "Cerca proprietà",- "noComponentProperties": "Nessuna proprietà trovata"+ "noComponentProperties": "Nessuna proprietà trovata",+ "applyVariableMode": "Applica modalità variabile",+ "removeVariableMode": "Rimuovi la modalità di {collection}",+ "variableModesInFile": "Create in questo file",+ "variableModesFromLibraries": "Dalle librerie",+ "variableModeAuto": "Auto ({mode})",+ "variableModeAutoMixed": "Auto",+ "variableModeHeading": "Modalità"}diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.jsonindex 6c5fbafde..85f529d79 100644--- a/packages/vue/src/i18n/locales/ja/panels.json+++ b/packages/vue/src/i18n/locales/ja/panels.json@@ -573,5 +573,12 @@"behaviourStateUnset": "なし","behaviourStateField": "{state} 状態","searchComponentProperties": "プロパティを検索",- "noComponentProperties": "プロパティが見つかりません"+ "noComponentProperties": "プロパティが見つかりません",+ "applyVariableMode": "変数モードを適用",+ "removeVariableMode": "{collection} のモードを解除",+ "variableModesInFile": "このファイルで作成",+ "variableModesFromLibraries": "ライブラリから",+ "variableModeAuto": "自動({mode})",+ "variableModeAutoMixed": "自動",+ "variableModeHeading": "モード"}diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.jsonindex 93fd4c606..f2e277006 100644--- a/packages/vue/src/i18n/locales/pl/panels.json+++ b/packages/vue/src/i18n/locales/pl/panels.json@@ -587,5 +587,12 @@"behaviourStateUnset": "Brak","behaviourStateField": "Stan {state}","searchComponentProperties": "Szukaj właściwości",- "noComponentProperties": "Nie znaleziono właściwości"+ "noComponentProperties": "Nie znaleziono właściwości",+ "applyVariableMode": "Zastosuj tryb zmiennych",+ "removeVariableMode": "Usuń tryb kolekcji {collection}",+ "variableModesInFile": "Utworzone w tym pliku",+ "variableModesFromLibraries": "Z bibliotek",+ "variableModeAuto": "Automatycznie ({mode})",+ "variableModeAutoMixed": "Automatycznie",+ "variableModeHeading": "Tryb"}diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.jsonindex 2c561759b..2a0ddcac6 100644--- a/packages/vue/src/i18n/locales/ru/panels.json+++ b/packages/vue/src/i18n/locales/ru/panels.json@@ -587,5 +587,12 @@"behaviourStateUnset": "Нет","behaviourStateField": "Состояние «{state}»","searchComponentProperties": "Поиск свойств",- "noComponentProperties": "Свойства не найдены"+ "noComponentProperties": "Свойства не найдены",+ "applyVariableMode": "Применить режим переменных",+ "removeVariableMode": "Убрать режим коллекции «{collection}»",+ "variableModesInFile": "Созданы в этом файле",+ "variableModesFromLibraries": "Из библиотек",+ "variableModeAuto": "Авто ({mode})",+ "variableModeAutoMixed": "Авто",+ "variableModeHeading": "Режим"}diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.jsonindex 0d697ff93..8c60be969 100644--- a/packages/vue/src/i18n/locales/zh-cn/panels.json+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json@@ -573,5 +573,12 @@"behaviourStateUnset": "无","behaviourStateField": "{state}状态","searchComponentProperties": "搜索属性",- "noComponentProperties": "未找到属性"+ "noComponentProperties": "未找到属性",+ "applyVariableMode": "应用变量模式",+ "removeVariableMode": "移除 {collection} 的模式",+ "variableModesInFile": "在此文件中创建",+ "variableModesFromLibraries": "来自库",+ "variableModeAuto": "自动({mode})",+ "variableModeAutoMixed": "自动",+ "variableModeHeading": "模式"}diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.tsindex a6e2788d6..ca8180078 100644--- a/packages/vue/src/i18n/messages/panels.ts+++ b/packages/vue/src/i18n/messages/panels.ts@@ -126,6 +126,13 @@ export const panelMessageDefaults = {height: 'Height',opacity: 'Opacity',blendMode: 'Blend mode',+ applyVariableMode: 'Apply variable mode',+ removeVariableMode: params('Remove {collection} mode'),+ variableModesInFile: 'Created in this file',+ variableModesFromLibraries: 'From libraries',+ variableModeAuto: params('Auto ({mode})'),+ variableModeAutoMixed: 'Auto',+ variableModeHeading: 'Mode',radius: 'Radius',cornerSmoothing: 'Corner smoothing',/** A polygon's sides or a star's points. */diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.tsindex b46c5799f..9b81b568f 100644--- a/packages/vue/src/index.ts+++ b/packages/vue/src/index.ts@@ -116,6 +116,13 @@ export {export type { TextResizeMode } from '#vue/controls/selection-layout/use'export type { LayoutAxis, SizeLimitProp } from '#vue/controls/layout/helpers'export { useAppearance } from '#vue/controls/appearance/use'+export { useVariableModes } from '#vue/controls/variable-modes/use'+export {+ setVariableMode,+ variableModeChoices,+ type VariableModeChoice,+ type VariableModeOption+} from '#vue/controls/variable-modes/helpers'export { useMask } from '#vue/controls/mask/use'export { useIcon } from '#vue/controls/icon/use'export { useIconSearch } from '#vue/controls/icon/search'diff --git a/packages/vue/src/primitives/LayerTree/LayerTreeRoot.vue b/packages/vue/src/primitives/LayerTree/LayerTreeRoot.vueindex 07f579c84..5ca402c67 100644--- a/packages/vue/src/primitives/LayerTree/LayerTreeRoot.vue+++ b/packages/vue/src/primitives/LayerTree/LayerTreeRoot.vue@@ -1,6 +1,6 @@<script setup lang="ts">import { TreeRoot } from 'reka-ui'-import { computed, nextTick, onScopeDispose, ref } from 'vue'+import { computed, nextTick, onScopeDispose, reactive, ref } from 'vue'import type { SceneNode } from '@open-pencil/scene-graph'@@ -83,7 +83,8 @@ const PATCHABLE_NODE_KEYS = new Set<keyof SceneNode>(['type','layoutMode','visible',- 'locked'+ 'locked',+ 'variableModes'])function patchTreeNode(id: string, changes: Partial<SceneNode>) {@@ -96,7 +97,9 @@ function patchTreeNode(id: string, changes: Partial<SceneNode>) {}const target = nodesById.get(id)const source = editor.graph.getNode(id)- if (target && source) patchLayerNode(target, source)+ // The index holds the plain rows; writing through their reactive proxy updates every view of+ // them, including values a row derives and caches, such as its variable mode tags.+ if (target && source) patchLayerNode(reactive(target), source)}const rowRefs = new Map<string, HTMLElement>()diff --git a/packages/vue/src/primitives/LayerTree/context.ts b/packages/vue/src/primitives/LayerTree/context.tsindex b621d58c1..43fe17b37 100644--- a/packages/vue/src/primitives/LayerTree/context.ts+++ b/packages/vue/src/primitives/LayerTree/context.ts@@ -13,6 +13,8 @@ export interface LayerNode {icon?: booleanvisible: booleanlocked: boolean+ /** The variable modes set on the layer itself, which Figma tags its row with. */+ modeIds?: string[]children?: LayerNode[]}diff --git a/packages/vue/src/primitives/LayerTree/model.ts b/packages/vue/src/primitives/LayerTree/model.tsindex dd708eb22..f8fffe496 100644--- a/packages/vue/src/primitives/LayerTree/model.ts+++ b/packages/vue/src/primitives/LayerTree/model.ts@@ -1,8 +1,15 @@+import { isEqual } from 'es-toolkit'+import { readIcon, slotPropertyId } from '@open-pencil/scene-graph'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import type { LayerNode, LayerRow, LayerSelectionMode } from '#vue/primitives/LayerTree/context'+function explicitModeIds(node: SceneNode): string[] | undefined {+ const ids = Object.values(node.variableModes)+ return ids.length > 0 ? ids : undefined+}+function nodeToLayerNode(node: SceneNode): LayerNode {return {id: node.id,@@ -12,7 +19,8 @@ function nodeToLayerNode(node: SceneNode): LayerNode {slot: !!slotPropertyId(node),icon: !!readIcon(node),visible: node.visible,- locked: node.locked+ locked: node.locked,+ modeIds: explicitModeIds(node)}}@@ -62,7 +70,8 @@ export function patchLayerNode(target: LayerNode, source: SceneNode): boolean {target.slot !== !!slotPropertyId(source) ||target.icon !== !!readIcon(source) ||target.visible !== source.visible ||- target.locked !== source.locked+ target.locked !== source.locked ||+ !isEqual(target.modeIds, explicitModeIds(source))if (!changed) return falsetarget.name = source.nametarget.type = source.type@@ -71,6 +80,7 @@ export function patchLayerNode(target: LayerNode, source: SceneNode): boolean {target.icon = !!readIcon(source)target.visible = source.visibletarget.locked = source.locked+ target.modeIds = explicitModeIds(source)return true}diff --git a/packages/vue/tests/controls/variable-modes.test.ts b/packages/vue/tests/controls/variable-modes.test.tsnew file mode 100644index 000000000..78d1a36a3--- /dev/null+++ b/packages/vue/tests/controls/variable-modes.test.ts@@ -0,0 +1,96 @@+import { describe, expect, test } from 'bun:test'++import { createEditor } from '@open-pencil/core/editor'+import { collectionsBoundIn, SceneGraph, type SceneNode } from '@open-pencil/scene-graph'+import { MIXED, setVariableMode, variableModeChoices } from '@open-pencil/vue'++const RED = { r: 1, g: 0, b: 0, a: 1 }++function expectDefined<T>(value: T | null | undefined, label: string): T {+ if (value === null || value === undefined) throw new Error(`Expected ${label}`)+ return value+}++/**+ * A Theme collection with Light and Dark modes, a single-mode Density collection, a frame whose+ * fill is bound to Theme with a bound child inside it, and a plain frame.+ */+function setup() {+ const graph = new SceneGraph()+ const editor = createEditor({ graph })+ const page = expectDefined(graph.getPages()[0], 'first page').id+ const theme = graph.createCollection('Theme')+ const light = theme.defaultModeId+ theme.modes[0].name = 'Light'+ const dark = expectDefined(graph.createMode(theme.id, 'Dark'), 'Dark')+ const surface = graph.createVariable('Surface', 'COLOR', theme.id, RED)+ const density = graph.createCollection('Density')+ graph.createVariable('Gap', 'FLOAT', density.id, 8)+ const bound = { boundVariables: { 'fills/0/color': surface.id } }+ const outer = graph.createNode('FRAME', page, { name: 'Outer', ...bound })+ const inner = graph.createNode('FRAME', outer.id, { name: 'Inner', ...bound })+ const plain = graph.createNode('FRAME', page, { name: 'Plain' })+ const node = (id: string): SceneNode => expectDefined(graph.getNode(id), id)+ return { editor, graph, page, theme, light, dark, density, outer, inner, plain, node }+}++describe('variable mode choices', () => {+ test('offer the collections with more than one mode that the layers use', () => {+ const { editor, theme, outer, plain, node } = setup()+ expect(variableModeChoices(editor, [node(outer.id)]).map((c) => c.collectionId)).toEqual([+ theme.id+ ])+ expect(variableModeChoices(editor, [node(plain.id)])).toEqual([])+ })++ test('offer every collection with more than one mode for a page', () => {+ const { editor, theme, page, node } = setup()+ expect(variableModeChoices(editor, [node(page)]).map((c) => c.collectionId)).toEqual([theme.id])+ })++ test('show Auto with the inherited mode, the set mode, or MIXED', () => {+ const { editor, theme, light, dark, outer, inner, node } = setup()+ const [auto] = variableModeChoices(editor, [node(inner.id)])+ expect(auto?.value).toBeNull()+ expect(auto?.inherited).toEqual({ modeId: light, name: 'Light' })++ setVariableMode(editor, [node(outer.id)], theme.id, dark)+ const [inherited] = variableModeChoices(editor, [node(inner.id)])+ expect(inherited?.inherited).toEqual({ modeId: dark, name: 'Dark' })+ expect(variableModeChoices(editor, [node(outer.id)])[0]?.value).toBe(dark)+ expect(variableModeChoices(editor, [node(outer.id), node(inner.id)])[0]?.value).toBe(MIXED)+ })+})++describe('setting a variable mode', () => {+ test('sets it on every target in one undo step, and the layers inside resolve it', () => {+ const { editor, graph, theme, dark, outer, inner, node } = setup()+ setVariableMode(editor, [node(outer.id)], theme.id, dark)+ expect(node(outer.id).variableModes).toEqual({ [theme.id]: dark })+ expect(graph.getNodeVariableModeId(inner.id, theme.id)).toBe(dark)++ editor.undoAction()+ expect(node(outer.id).variableModes).toEqual({})+ })++ test('clearing it restores the inherited mode and keeps other collections', () => {+ const { editor, graph, theme, density, light, dark, outer, node } = setup()+ const densityMode = density.defaultModeId+ graph.updateNode(outer.id, { variableModes: { [density.id]: densityMode } })+ setVariableMode(editor, [node(outer.id)], theme.id, dark)+ setVariableMode(editor, [node(outer.id)], theme.id, null)+ expect(node(outer.id).variableModes).toEqual({ [density.id]: densityMode })+ expect(graph.getNodeVariableModeId(outer.id, theme.id)).toBe(light)+ })+})++describe('collectionsBoundIn', () => {+ test('includes the collections that bound variables alias', () => {+ const { graph, theme, outer } = setup()+ const brand = graph.createCollection('Brand')+ const accent = graph.createVariable('Accent', 'COLOR', brand.id, RED)+ const surface = expectDefined(graph.variables.get(theme.variableIds[0] ?? ''), 'Surface')+ surface.valuesByMode[theme.defaultModeId] = { aliasId: accent.id }+ expect(collectionsBoundIn(graph, [outer.id])).toEqual(new Set([theme.id, brand.id]))+ })+})diff --git a/packages/vue/tests/primitives/LayerTree/model.test.ts b/packages/vue/tests/primitives/LayerTree/model.test.tsindex f8eb52c2f..c80c81d9a 100644--- a/packages/vue/tests/primitives/LayerTree/model.test.ts+++ b/packages/vue/tests/primitives/LayerTree/model.test.ts@@ -21,4 +21,21 @@ describe('layer tree model', () => {expect(patchLayerNode(row, frame)).toBe(true)expect(row.icon).toBe(true)})++ test('carries the variable modes set on a layer itself, so rows can tag them', () => {+ const graph = new SceneGraph()+ const pageId = graph.getPages()[0].id+ const theme = graph.createCollection('Theme')+ const dark = graph.createMode(theme.id, 'Dark') ?? ''+ const frame = graph.createNode('FRAME', pageId, { name: 'Frame' })++ const model = buildLayerTreeModel(graph, pageId)+ const row = model.byId.get(frame.id)+ if (!row) throw new Error('Expected the frame in the model')+ expect(row.modeIds).toBeUndefined()++ graph.updateNode(frame.id, { variableModes: { [theme.id]: dark } })+ expect(patchLayerNode(row, frame)).toBe(true)+ expect(row.modeIds).toEqual([dark])+ })})diff --git a/src/components/LayerTree/LayerTreeNodeRow.vue b/src/components/LayerTree/LayerTreeNodeRow.vueindex aff09cd77..1a206b500 100644--- a/src/components/LayerTree/LayerTreeNodeRow.vue+++ b/src/components/LayerTree/LayerTreeNodeRow.vue@@ -4,6 +4,7 @@ import { computed } from 'vue'import type { LayerNode } from '@open-pencil/vue'+import { useEditorStore } from '@/app/editor/active-store'import type { LayerIssueMark as LayerIssueMarkData } from '@/app/editor/design-check/layers'import { COMPONENT_TYPES, nodeIcon } from '@/app/editor/icons'import LayerIssueMark from '@/components/design-check/LayerIssueMark.vue'@@ -35,6 +36,17 @@ const emit = defineEmits<{}>()const ui = useLayerTreeUI()+const store = useEditorStore()+/** The names of the variable modes set on the layer itself, tagged after its name as in Figma. */+const modeNames = computed(() =>+ (node.modeIds ?? []).flatMap((modeId) => {+ for (const collection of store.graph.variableCollections.values()) {+ const mode = collection.modes.find((candidate) => candidate.modeId === modeId)+ if (mode) return [mode.name]+ }+ return []+ })+)const layerTree = tv(layerTreeTheme)const styles = computed(() =>layerTree({@@ -81,7 +93,17 @@ const styles = computed(() =>/><component :is="nodeIcon(node)" data-slot="icon" :class="styles.icon({ class: ui?.icon })" />- <span data-slot="label" :class="styles.label({ class: ui?.label })">{{ node.name }}</span>+ <span data-slot="label" :class="styles.label({ class: ui?.label })">+ <span class="min-w-0 truncate">{{ node.name }}</span>+ <span+ v-for="name in modeNames"+ :key="name"+ data-slot="variable-mode"+ class="shrink-0 rounded-full border border-current/40 px-1.5 text-[10px] leading-3.5"+ >+ {{ name }}+ </span>+ </span><LayerIssueMark v-if="issue && (issue.own || !expanded)" :mark="issue" /><LayerTreeActionsdiff --git a/src/components/properties/AppearanceSection.vue b/src/components/properties/AppearanceSection.vueindex 045d75d3d..22394aa55 100644--- a/src/components/properties/AppearanceSection.vue+++ b/src/components/properties/AppearanceSection.vue@@ -1,7 +1,7 @@<script setup lang="ts">import type { BlendMode } from '@open-pencil/scene-graph'import { POINT_COUNT_RANGE } from '@open-pencil/scene-graph/polygon'-import { AppearanceControlsRoot, MIXED, useI18n } from '@open-pencil/vue'+import { AppearanceControlsRoot, MIXED, useI18n, useVariableModes } from '@open-pencil/vue'import NumberField from '@/components/inputs/NumberField.vue'import { useBlendModeGroups } from '@/components/properties/blend-mode/use'@@ -14,8 +14,11 @@ import AppSelect from '@/components/ui/select/AppSelect.vue'import PropertyBindButton from './component-properties/PropertyBindButton.vue'import PropertyBoundField from './component-properties/PropertyBoundField.vue'+import VariableModeMenu from './variable-modes/VariableModeMenu.vue'+import VariableModeRows from './variable-modes/VariableModeRows.vue'const { panels } = useI18n()+const variableModes = useVariableModes()type BlendModeSelectValue = BlendMode | 'MIXED'const baseBlendModeGroups = useBlendModeGroups(true)@@ -55,6 +58,7 @@ function blendModeGroups(value: BlendMode | typeof MIXED) {><PanelSection v-if="active" :label="panels.appearance"><template #actions>+ <VariableModeMenu :choices="variableModes.choices.value" @set="variableModes.setMode" /><PropertyBindButton field="VISIBLE" /><IconButton:label="panels.toggleVisibility"@@ -273,6 +277,8 @@ function blendModeGroups(value: BlendMode | typeof MIXED) {</NumberField></PanelFieldGroup></PanelGrid>++ <VariableModeRows :choices="variableModes.applied.value" @set="variableModes.setMode" /></PanelSection></AppearanceControlsRoot></template>diff --git a/src/components/properties/PageSection.vue b/src/components/properties/PageSection.vueindex ea1b8fe62..1fca0fc84 100644--- a/src/components/properties/PageSection.vue+++ b/src/components/properties/PageSection.vue@@ -2,7 +2,7 @@import { computed } from 'vue'import type { Color, Fill } from '@open-pencil/scene-graph'-import { useI18n } from '@open-pencil/vue'+import { useI18n, useVariableModes } from '@open-pencil/vue'import { useEditorStore } from '@/app/editor/active-store'import ColorPicker from '@/components/ColorPicker/ColorPicker.vue'@@ -11,6 +11,9 @@ import PaintValue from '@/components/properties/paint/PaintValue.vue'import FillSwatch from '@/components/ui/paint/FillSwatch.vue'import PanelSection from '@/components/ui/panel/PanelSection.vue'+import VariableModeMenu from './variable-modes/VariableModeMenu.vue'+import VariableModeRows from './variable-modes/VariableModeRows.vue'+const editor = useEditorStore()const pageColor = computed(() => editor.state.pageColor)const pageFill = computed<Fill>(() => ({@@ -20,6 +23,7 @@ const pageFill = computed<Fill>(() => ({visible: true}))const { panels } = useI18n()+const variableModes = useVariableModes()function updatePageAlpha(alpha: number) {editor.setPageColor({ ...pageColor.value, a: alpha })@@ -32,6 +36,9 @@ function updatePageColor(color: Color) {<template><PanelSection :label="panels.page">+ <template #actions>+ <VariableModeMenu :choices="variableModes.choices.value" @set="variableModes.setMode" />+ </template><PaintField:opacity="pageColor.a":opacity-label="panels.opacity"@@ -54,5 +61,6 @@ function updatePageColor(color: Color) {<PaintValue :color="pageColor" :label="panels.pageBackground" @update="updatePageColor" /></template></PaintField>+ <VariableModeRows :choices="variableModes.applied.value" @set="variableModes.setMode" /></PanelSection></template>diff --git a/src/components/properties/variable-modes/VariableModeMenu.vue b/src/components/properties/variable-modes/VariableModeMenu.vuenew file mode 100644index 000000000..2fa3b7dd0--- /dev/null+++ b/src/components/properties/variable-modes/VariableModeMenu.vue@@ -0,0 +1,106 @@+<script setup lang="ts">+import {+ DropdownMenuContent,+ DropdownMenuItemIndicator,+ DropdownMenuLabel,+ DropdownMenuPortal,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuRoot,+ DropdownMenuSeparator,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+ DropdownMenuTrigger+} from 'reka-ui'+import { computed } from 'vue'++import { MIXED, usePanelMessages, type VariableModeChoice } from '@open-pencil/vue'++import IconButton from '@/components/ui/button/IconButton.vue'+import { menuItem, useMenuUI } from '@/components/ui/menu/menu'++import { AUTO_MODE, autoModeLabel } from './labels'++/** Figma's Apply variable mode button: a collection, then Auto or one of its modes. */+const { choices } = defineProps<{ choices: VariableModeChoice[] }>()+const emit = defineEmits<{ set: [collectionId: string, modeId: string | null] }>()++const panels = usePanelMessages()+const menu = useMenuUI({ content: 'min-w-44' })+const item = menuItem({ justify: 'start', class: 'pl-6 relative' })+const groups = computed(() =>+ [+ { label: panels.value.variableModesInFile, choices: choices.filter((c) => !c.library) },+ { label: panels.value.variableModesFromLibraries, choices: choices.filter((c) => c.library) }+ ].filter((group) => group.choices.length > 0)+)++/** The radio value a choice shows: its mode, Auto, or none checked when the targets differ. */+function current(choice: VariableModeChoice): string {+ if (choice.value === MIXED) return ''+ return choice.value ?? AUTO_MODE+}++function select(choice: VariableModeChoice, value: string) {+ emit('set', choice.collectionId, value === AUTO_MODE ? null : value)+}+</script>++<template>+ <DropdownMenuRoot v-if="choices.length > 0">+ <DropdownMenuTrigger as-child>+ <IconButton :label="panels.applyVariableMode" data-variable-mode-menu>+ <icon-lucide-swatch-book class="size-3.5" />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuPortal>+ <DropdownMenuContent side="bottom" align="end" :side-offset="4" :class="menu.content">+ <template v-for="(group, index) in groups" :key="group.label">+ <DropdownMenuSeparator v-if="index > 0" :class="menu.separator" />+ <DropdownMenuLabel :class="menu.label">{{ group.label }}</DropdownMenuLabel>+ <DropdownMenuSub v-for="choice in group.choices" :key="choice.collectionId">+ <DropdownMenuSubTrigger+ :class="[menu.subTrigger, 'justify-between data-[highlighted]:bg-hover']"+ >+ {{ choice.name }}+ <icon-lucide-chevron-right :class="menu.icon" />+ </DropdownMenuSubTrigger>+ <DropdownMenuPortal>+ <DropdownMenuSubContent :side-offset="4" :class="menu.content">+ <DropdownMenuRadioGroup+ :model-value="current(choice)"+ @update:model-value="+ (value) => typeof value === 'string' && select(choice, value)+ "+ >+ <DropdownMenuRadioItem :value="AUTO_MODE" :class="item">+ <DropdownMenuItemIndicator class="absolute left-1.5">+ <icon-lucide-check :class="menu.icon" />+ </DropdownMenuItemIndicator>+ {{ autoModeLabel(panels, choice) }}+ </DropdownMenuRadioItem>+ <DropdownMenuSeparator :class="menu.separator" />+ <DropdownMenuLabel :class="menu.label">+ {{ panels.variableModeHeading }}+ </DropdownMenuLabel>+ <DropdownMenuRadioItem+ v-for="mode in choice.modes"+ :key="mode.modeId"+ :value="mode.modeId"+ :class="item"+ >+ <DropdownMenuItemIndicator class="absolute left-1.5">+ <icon-lucide-check :class="menu.icon" />+ </DropdownMenuItemIndicator>+ {{ mode.name }}+ </DropdownMenuRadioItem>+ </DropdownMenuRadioGroup>+ </DropdownMenuSubContent>+ </DropdownMenuPortal>+ </DropdownMenuSub>+ </template>+ </DropdownMenuContent>+ </DropdownMenuPortal>+ </DropdownMenuRoot>+</template>diff --git a/src/components/properties/variable-modes/VariableModeRows.vue b/src/components/properties/variable-modes/VariableModeRows.vuenew file mode 100644index 000000000..191c5d307--- /dev/null+++ b/src/components/properties/variable-modes/VariableModeRows.vue@@ -0,0 +1,63 @@+<script setup lang="ts">+import { MIXED, usePanelMessages, type VariableModeChoice } from '@open-pencil/vue'++import IconButton from '@/components/ui/button/IconButton.vue'+import AppSelect from '@/components/ui/select/AppSelect.vue'+import type { AppSelectGroup } from '@/components/ui/select/select'++import { AUTO_MODE, autoModeLabel } from './labels'++/** A row for each collection a mode is set for: its name, Auto or a mode, and a remove button. */+const { choices } = defineProps<{ choices: VariableModeChoice[] }>()+const emit = defineEmits<{ set: [collectionId: string, modeId: string | null] }>()++const panels = usePanelMessages()+const MIXED_MODE = ':mixed'++function groups(choice: VariableModeChoice): AppSelectGroup<string>[] {+ const mixed =+ choice.value === MIXED ? [{ options: [{ value: MIXED_MODE, label: panels.value.mixed }] }] : []+ return [+ ...mixed,+ { options: [{ value: AUTO_MODE, label: autoModeLabel(panels.value, choice) }] },+ {+ label: panels.value.variableModeHeading,+ options: choice.modes.map((mode) => ({ value: mode.modeId, label: mode.name }))+ }+ ]+}++function current(choice: VariableModeChoice): string {+ if (choice.value === MIXED) return MIXED_MODE+ return choice.value ?? AUTO_MODE+}++function select(choice: VariableModeChoice, value: string) {+ if (value === MIXED_MODE) return+ emit('set', choice.collectionId, value === AUTO_MODE ? null : value)+}+</script>++<template>+ <div+ v-for="choice in choices"+ :key="choice.collectionId"+ class="mt-1.5 grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto] items-center gap-2"+ data-variable-mode-row+ >+ <span class="truncate text-[11px] text-muted">{{ choice.name }}</span>+ <AppSelect+ :model-value="current(choice)"+ class="w-full"+ :label="choice.name"+ :groups="groups(choice)"+ @update:model-value="(value: string) => select(choice, value)"+ />+ <IconButton+ :label="panels.removeVariableMode({ collection: choice.name })"+ @click="emit('set', choice.collectionId, null)"+ >+ <icon-lucide-minus class="size-3.5" />+ </IconButton>+ </div>+</template>diff --git a/src/components/properties/variable-modes/labels.ts b/src/components/properties/variable-modes/labels.tsnew file mode 100644index 000000000..3a8f84d6b--- /dev/null+++ b/src/components/properties/variable-modes/labels.ts@@ -0,0 +1,13 @@+import type { usePanelMessages, VariableModeChoice } from '@open-pencil/vue'++type PanelMessages = ReturnType<typeof usePanelMessages>['value']++/** The value Auto stands for in the menu and the row select; mode ids never take this form. */+export const AUTO_MODE = ':auto'++/** "Auto (Light)", naming the mode the targets inherit, or "Auto" when they inherit different ones. */+export function autoModeLabel(panels: PanelMessages, choice: VariableModeChoice): string {+ return choice.inherited+ ? panels.variableModeAuto({ mode: choice.inherited.name })+ : panels.variableModeAutoMixed+}diff --git a/src/theme/layer-tree.ts b/src/theme/layer-tree.tsindex 3c9de1c7f..ef4166433 100644--- a/src/theme/layer-tree.ts+++ b/src/theme/layer-tree.ts@@ -6,7 +6,7 @@ const layerTreeTheme = {'flex w-4 shrink-0 cursor-pointer items-center justify-center text-current transition-transform',disclosurePlaceholder: 'w-4 shrink-0',icon: 'size-3 shrink-0',- label: 'min-w-0 flex-1 truncate',+ label: 'flex min-w-0 flex-1 items-center gap-1.5',actions: 'flex shrink-0 items-center gap-0.5',action:'flex size-4 items-center justify-center rounded text-current outline-none hover:bg-white/15 focus-visible:ring-1 focus-visible:ring-panel-focus',diff --git a/tools/checks/i18n/translation-baseline.txt b/tools/checks/i18n/translation-baseline.txtindex aa8aa4d35..bcb66f319 100644--- a/tools/checks/i18n/translation-baseline.txt+++ b/tools/checks/i18n/translation-baseline.txt@@ -175,6 +175,9 @@ fr:panels.behaviourMinfr:panels.behaviourMaxfr:panels.behaviourStateFocusfr:panels.shader+fr:panels.variableModeAuto+fr:panels.variableModeAutoMixed+fr:panels.variableModeHeadingfr:settings.animationsfr:settings.diagnosticsfr:settings.mcp@@ -222,6 +225,8 @@ it:panels.behaviourMaxit:panels.behaviourStateHoverit:panels.behaviourStateFocusit:panels.shader+it:panels.variableModeAuto+it:panels.variableModeAutoMixedit:rendering.settingsTitleit:settings.mcpit:settings.media