AI-native design editor. Open-source Figma alternative.
feat: bind layer visibility to boolean and text variables (#1334)
Danila Poyarkov45604d34f57f
diff --git a/changes/1334/added.md b/changes/1334/added.mdnew file mode 100644index 000000000..cddeee8b9--- /dev/null+++ b/changes/1334/added.md@@ -0,0 +1 @@+- A layer's visibility binds to a boolean or text variable from the Appearance panel, as in Figma: right-click the eye, or use the variable/property button on a layer inside a component. Text shows the layer unless it is empty or reads "false", "no" or "off".diff --git a/changes/1334/breaking.md b/changes/1334/breaking.mdnew file mode 100644index 000000000..faaf15a5d--- /dev/null+++ b/changes/1334/breaking.md@@ -0,0 +1 @@+- `OpenPencilBindingProviderOptions` in `@open-pencil/vue` takes `types`, a list of variable types, instead of `type`.diff --git a/packages/scene-graph/src/variables.ts b/packages/scene-graph/src/variables.tsindex 730752353..f95ff6d74 100644--- a/packages/scene-graph/src/variables.ts+++ b/packages/scene-graph/src/variables.ts@@ -17,7 +17,11 @@ import {variableBindingOwner,assignVariableBindingUnits} from './variables/bindings'-import { BOOLEAN_BINDING_FIELDS, STRING_BINDING_FIELDS } from './variables/fields'+import {+ BOOLEAN_BINDING_FIELDS,+ STRING_BINDING_FIELDS,+ VISIBILITY_VARIABLE_TYPES+} from './variables/fields'export * from './variables/resolution'@@ -265,7 +269,10 @@ export function bindVariable(throw new Error(`Cannot bind ${variable.type} variable to string field "${field}"`)}- if (BOOLEAN_BINDING_FIELDS.has(field) && variable.type !== 'BOOLEAN') {+ if (+ BOOLEAN_BINDING_FIELDS.has(field) &&+ !VISIBILITY_VARIABLE_TYPES.some((type) => type === variable.type)+ ) {throw new Error(`Cannot bind ${variable.type} variable to boolean field "${field}"`)}diff --git a/packages/scene-graph/src/variables/bindings.ts b/packages/scene-graph/src/variables/bindings.tsindex 71fbe92ce..7eedea714 100644--- a/packages/scene-graph/src/variables/bindings.ts+++ b/packages/scene-graph/src/variables/bindings.ts@@ -7,7 +7,7 @@ import type { VariableModeFallback } from '../variables'import { NUMERIC_FIELDS, isNumericVariableBindingField } from './fields'import { variableText, variableTruthy } from './text'import { variableValueReferences } from './value'-export { isNumericVariableBindingField } from './fields'+export { isNumericVariableBindingField, VISIBILITY_VARIABLE_TYPES } from './fields'/** New declarations belong to the outermost occurrence, bounded by a component definition. */export function variableBindingOwner(graph: SceneGraph, node: SceneNode): SceneNode {diff --git a/packages/scene-graph/src/variables/fields.ts b/packages/scene-graph/src/variables/fields.tsindex 57ade651b..b2d37d089 100644--- a/packages/scene-graph/src/variables/fields.ts+++ b/packages/scene-graph/src/variables/fields.ts@@ -1,3 +1,5 @@+import type { VariableType } from '../types'+export const NUMERIC_FIELDS = new Set(['opacity','width',@@ -41,3 +43,12 @@ export const STRING_BINDING_FIELDS: ReadonlySet<string> = new Set(['text', 'font/** Visibility is the only boolean-valued binding a node accepts. */export const BOOLEAN_BINDING_FIELDS: ReadonlySet<string> = new Set(['visible'])++/**+ * The variable types visibility binds to: a boolean, or text that shows the layer unless it reads+ * as false, as Figma's layer panel offers. Figma's plugin API takes booleans alone.+ */+export const VISIBILITY_VARIABLE_TYPES = [+ 'BOOLEAN',+ 'STRING'+] as const satisfies readonly VariableType[]diff --git a/packages/scene-graph/tests/basic/variables.test.ts b/packages/scene-graph/tests/basic/variables.test.tsindex 5987192da..e5d0cc88c 100644--- a/packages/scene-graph/tests/basic/variables.test.ts+++ b/packages/scene-graph/tests/basic/variables.test.ts@@ -1,6 +1,6 @@import { describe, expect, test } from 'bun:test'-import { SceneGraph } from '@open-pencil/scene-graph'+import { resolvedValueBindings, SceneGraph } from '@open-pencil/scene-graph'describe('Variables', () => {function pageId(graph: SceneGraph): string {@@ -256,6 +256,26 @@ describe('Variables', () => {expect(node.boundVariables['fills/0/color']).toBeUndefined()})+ test('visibility binds a boolean or text variable and follows its truth', () => {+ const graph = new SceneGraph()+ const collection = graph.createCollection('Visibility')+ const mode = collection.defaultModeId+ const flag = graph.createVariable('flag', 'BOOLEAN', collection.id, true)+ const state = graph.createVariable('state', 'STRING', collection.id, 'off')+ const size = graph.createVariable('size', 'FLOAT', collection.id, 1)+ const node = graph.createNode('RECTANGLE', graph.getPages()[0].id)++ graph.bindVariable(node.id, 'visible', state.id)+ expect(resolvedValueBindings(graph, node)).toEqual({ visible: false })+ state.valuesByMode[mode] = 'yes'+ expect(resolvedValueBindings(graph, node)).toEqual({})+ graph.bindVariable(node.id, 'visible', flag.id)+ expect(node.boundVariables.visible).toBe(flag.id)+ expect(() => graph.bindVariable(node.id, 'visible', size.id)).toThrow(+ 'Cannot bind FLOAT variable to boolean field "visible"'+ )+ })+test('removing variable cleans up bindings', () => {const graph = new SceneGraph()graph.addCollection({diff --git a/packages/vue/src/controls/binding-provider/color.ts b/packages/vue/src/controls/binding-provider/color.tsindex 47541a7b2..ad1550d57 100644--- a/packages/vue/src/controls/binding-provider/color.ts+++ b/packages/vue/src/controls/binding-provider/color.ts@@ -61,7 +61,7 @@ function resolveColor(editor: Editor, id: string, target?: BindingTarget) {export function useColorBindingProvider() {return useOpenPencilBindingProvider<Color>({- type: 'COLOR',+ types: ['COLOR'],resolve: resolveColor,prepareEdit: (editor, id, target) =>prepareModeEdit(editor, id, target, () => resolveColor(editor, id, target)),diff --git a/packages/vue/src/controls/binding-provider/index.ts b/packages/vue/src/controls/binding-provider/index.tsindex 2915dde65..0bd0a39af 100644--- a/packages/vue/src/controls/binding-provider/index.ts+++ b/packages/vue/src/controls/binding-provider/index.ts@@ -22,3 +22,4 @@ export type {BindingTarget,BoundEditPolicy} from '#vue/controls/binding-provider/types'+export { useVisibilityBindingProvider } from '#vue/controls/binding-provider/visibility'diff --git a/packages/vue/src/controls/binding-provider/number.ts b/packages/vue/src/controls/binding-provider/number.tsindex 548958922..3913db2f4 100644--- a/packages/vue/src/controls/binding-provider/number.ts+++ b/packages/vue/src/controls/binding-provider/number.ts@@ -58,7 +58,7 @@ function resolveNumber(editor: Editor, id: string, target?: BindingTarget) {export function useNumberBindingProvider() {return useOpenPencilBindingProvider<number>({- type: 'FLOAT',+ types: ['FLOAT'],resolve: resolveNumber,prepareEdit: (editor, id, target) =>prepareModeEdit(editor, id, target, () => resolveNumber(editor, id, target)),diff --git a/packages/vue/src/controls/binding-provider/open-pencil.ts b/packages/vue/src/controls/binding-provider/open-pencil.tsindex 263f3a080..7e0b424f5 100644--- a/packages/vue/src/controls/binding-provider/open-pencil.ts+++ b/packages/vue/src/controls/binding-provider/open-pencil.ts@@ -16,7 +16,8 @@ import { useSceneComputed } from '#vue/internal/scene-computed/use'import { resolveEffectiveBindingValue } from './resolution'export interface OpenPencilBindingProviderOptions<V> {- type: VariableType+ /** The variable types the field binds to, which the picker lists. */+ types: readonly VariableType[]resolve(editor: Editor, variableId: string, target?: BindingTarget): V | undefinedcreate?(editor: Editor, target: BindingTarget, value: V, name: string): voidprepareEdit?(@@ -32,7 +33,8 @@ export function createOpenPencilBindingProvider<V>(revision?: BindingProvider<V>['revision']): BindingProvider<V> {const { contains } = useFilter({ sensitivity: 'base' })- const variables = () => editor.getVariablesByType(options.type)+ const variables = () =>+ [...editor.graph.variables.values()].filter((variable) => options.types.includes(variable.type))const interactiveEdits: Array<{ end: () => void; stopSettling: () => void }> = []/**diff --git a/packages/vue/src/controls/binding-provider/visibility.ts b/packages/vue/src/controls/binding-provider/visibility.tsnew file mode 100644index 000000000..353d0a69a--- /dev/null+++ b/packages/vue/src/controls/binding-provider/visibility.ts@@ -0,0 +1,22 @@+import type { Editor } from '@open-pencil/core/editor'+import { VISIBILITY_VARIABLE_TYPES, variableTruthy } from '@open-pencil/scene-graph'++import { useOpenPencilBindingProvider } from '#vue/controls/binding-provider/open-pencil'+import type { BindingTarget } from '#vue/controls/binding-provider/types'++/** Whether a variable shows the layer: a boolean as it is, text unless it reads as false. */+function resolveVisibility(editor: Editor, id: string, target?: BindingTarget) {+ return variableTruthy(+ target+ ? editor.graph.resolveVariableForNode(target.nodeId, id)+ : editor.graph.resolveVariable(id)+ )+}++/** Binds a layer's visibility to a boolean or text variable, as Figma's layer panel does. */+export function useVisibilityBindingProvider() {+ return useOpenPencilBindingProvider<boolean>({+ types: VISIBILITY_VARIABLE_TYPES,+ resolve: resolveVisibility+ })+}diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.jsonindex 021bcb692..d4160c30c 100644--- a/packages/vue/src/i18n/locales/de/panels.json+++ b/packages/vue/src/i18n/locales/de/panels.json@@ -401,6 +401,8 @@"componentPropertySwap": "Instanz austauschen","createComponentProperty": "Eigenschaft erstellen…","applyComponentProperty": "Komponenteneigenschaft auf {field} anwenden",+ "applyVariableOrProperty": "Variable/Eigenschaft anwenden",+ "propertiesInComponent": "Eigenschaften in {name}","goToComponentProperty": "Zur Eigenschaft","detachComponentProperty": "Eigenschaft trennen","deleteComponentProperty": "Eigenschaft löschen",diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.jsonindex a028a7216..f90adf18a 100644--- a/packages/vue/src/i18n/locales/es/panels.json+++ b/packages/vue/src/i18n/locales/es/panels.json@@ -419,6 +419,8 @@"componentPropertySwap": "Intercambio de instancia","createComponentProperty": "Crear propiedad…","applyComponentProperty": "Aplicar propiedad de componente a {field}",+ "applyVariableOrProperty": "Aplicar variable/propiedad",+ "propertiesInComponent": "Propiedades de {name}","goToComponentProperty": "Ir a la propiedad","detachComponentProperty": "Separar propiedad","deleteComponentProperty": "Eliminar propiedad",diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.jsonindex f9f205463..91a418bef 100644--- a/packages/vue/src/i18n/locales/fr/panels.json+++ b/packages/vue/src/i18n/locales/fr/panels.json@@ -401,6 +401,8 @@"componentPropertySwap": "Permutation d’instance","createComponentProperty": "Créer une propriété…","applyComponentProperty": "Appliquer une propriété de composant à {field}",+ "applyVariableOrProperty": "Appliquer une variable/propriété",+ "propertiesInComponent": "Propriétés de {name}","goToComponentProperty": "Aller à la propriété","detachComponentProperty": "Dissocier la propriété","deleteComponentProperty": "Supprimer la propriété",diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.jsonindex cbf693101..1f8790f8b 100644--- a/packages/vue/src/i18n/locales/it/panels.json+++ b/packages/vue/src/i18n/locales/it/panels.json@@ -401,6 +401,8 @@"componentPropertySwap": "Scambio di istanza","createComponentProperty": "Crea proprietà…","applyComponentProperty": "Applica proprietà del componente a {field}",+ "applyVariableOrProperty": "Applica variabile/proprietà",+ "propertiesInComponent": "Proprietà di {name}","goToComponentProperty": "Vai alla proprietà","detachComponentProperty": "Scollega proprietà","deleteComponentProperty": "Elimina proprietà",diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.jsonindex e21cf8b93..d7545b018 100644--- a/packages/vue/src/i18n/locales/ja/panels.json+++ b/packages/vue/src/i18n/locales/ja/panels.json@@ -413,6 +413,8 @@"componentPropertySwap": "インスタンスの入れ替え","createComponentProperty": "プロパティを作成…","applyComponentProperty": "{field}にコンポーネントプロパティを適用",+ "applyVariableOrProperty": "変数/プロパティを適用",+ "propertiesInComponent": "{name}のプロパティ","goToComponentProperty": "プロパティに移動","detachComponentProperty": "プロパティを解除","deleteComponentProperty": "プロパティを削除",diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.jsonindex 8d2dfb0f5..d32e9c96b 100644--- a/packages/vue/src/i18n/locales/pl/panels.json+++ b/packages/vue/src/i18n/locales/pl/panels.json@@ -407,6 +407,8 @@"componentPropertySwap": "Zamiana instancji","createComponentProperty": "Utwórz właściwość…","applyComponentProperty": "Zastosuj właściwość komponentu do: {field}",+ "applyVariableOrProperty": "Zastosuj zmienną/właściwość",+ "propertiesInComponent": "Właściwości w: {name}","goToComponentProperty": "Przejdź do właściwości","detachComponentProperty": "Odłącz właściwość","deleteComponentProperty": "Usuń właściwość",diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.jsonindex 59761637f..28f5db991 100644--- a/packages/vue/src/i18n/locales/ru/panels.json+++ b/packages/vue/src/i18n/locales/ru/panels.json@@ -407,6 +407,8 @@"componentPropertySwap": "Замена экземпляра","createComponentProperty": "Создать свойство…","applyComponentProperty": "Применить свойство компонента к полю «{field}»",+ "applyVariableOrProperty": "Применить переменную или свойство",+ "propertiesInComponent": "Свойства компонента «{name}»","goToComponentProperty": "Перейти к свойству","detachComponentProperty": "Отвязать свойство","deleteComponentProperty": "Удалить свойство",diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.jsonindex 8e75646f6..07e06378f 100644--- a/packages/vue/src/i18n/locales/zh-cn/panels.json+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json@@ -395,6 +395,8 @@"componentPropertySwap": "实例切换","createComponentProperty": "创建属性…","applyComponentProperty": "将组件属性应用到{field}",+ "applyVariableOrProperty": "应用变量/属性",+ "propertiesInComponent": "{name}中的属性","goToComponentProperty": "转到属性","detachComponentProperty": "分离属性","deleteComponentProperty": "删除属性",diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.tsindex 0cd4d0b5e..604cbf1a5 100644--- a/packages/vue/src/i18n/messages/panels.ts+++ b/packages/vue/src/i18n/messages/panels.ts@@ -101,6 +101,8 @@ export const panelMessageDefaults = {componentPropertySwap: 'Instance swap',createComponentProperty: 'Create property…',applyComponentProperty: params('Apply component property to {field}'),+ applyVariableOrProperty: 'Apply variable/property',+ propertiesInComponent: params('Properties in {name}'),goToComponentProperty: 'Go to property',detachComponentProperty: 'Detach property',deleteComponentProperty: 'Delete property',diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.tsindex afa0e18ad..d5f927154 100644--- a/packages/vue/src/index.ts+++ b/packages/vue/src/index.ts@@ -407,7 +407,8 @@ export {useBindingProvider,useOpenPencilBindingProvider,useNumberBindingProvider,- useColorBindingProvider+ useColorBindingProvider,+ useVisibilityBindingProvider} from '#vue/controls/binding-provider'export type {BindingMutationSource,diff --git a/packages/vue/src/primitives/BindableValue/examples/ModeEdit.vue b/packages/vue/src/primitives/BindableValue/examples/ModeEdit.vueindex 38c9a3a55..40bad4dd8 100644--- a/packages/vue/src/primitives/BindableValue/examples/ModeEdit.vue+++ b/packages/vue/src/primitives/BindableValue/examples/ModeEdit.vue@@ -29,7 +29,7 @@ const targets = ref([first, first, second].map((node) => ({ nodeId: node.id, patconst provider = createOpenPencilBindingProvider(editor,{- type: 'FLOAT',+ types: ['FLOAT'],resolve: (e, id, target) =>target? e.graph.resolveNumberVariableForNode(target.nodeId, id)diff --git a/src/components/properties/AppearanceSection.vue b/src/components/properties/AppearanceSection.vueindex 22394aa55..5b7d68c9a 100644--- a/src/components/properties/AppearanceSection.vue+++ b/src/components/properties/AppearanceSection.vue@@ -12,10 +12,11 @@ import PanelGrid from '@/components/ui/panel/PanelGrid.vue'import PanelSection from '@/components/ui/panel/PanelSection.vue'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'+import VisibilityBindingRow from './visibility/VisibilityBindingRow.vue'+import VisibilityControl from './visibility/VisibilityControl.vue'const { panels } = useI18n()const variableModes = useVariableModes()@@ -59,18 +60,14 @@ 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"- :active="visibilityState === 'hidden'"- @click="actions.toggleVisibility"- >- <icon-lucide-eye v-if="visibilityState === 'visible'" class="size-3.5" />- <icon-lucide-eye-off v-else-if="visibilityState === 'hidden'" class="size-3.5" />- <icon-lucide-eye v-else class="size-3.5 opacity-50" />- </IconButton>+ <VisibilityControl+ :node-id="node && !isMulti ? node.id : undefined"+ :visibility="visibilityState"+ @toggle="actions.toggleVisibility"+ /></template><PropertyBoundField field="VISIBLE" />+ <VisibilityBindingRow v-if="node && !isMulti" :node-id="node.id" /><PanelGrid :columns="2" distribution="wide-first"><PanelFieldGroup :label="panels.blendMode">diff --git a/src/components/properties/binding/BoundFieldRow.vue b/src/components/properties/binding/BoundFieldRow.vuenew file mode 100644index 000000000..11443ef2c--- /dev/null+++ b/src/components/properties/binding/BoundFieldRow.vue@@ -0,0 +1,46 @@+<script setup lang="ts">+import PanelFieldGroup from '@/components/ui/panel/PanelFieldGroup.vue'++/**+ * A field whose value something else decides, shown in place of the value: the field's label,+ * a chip naming what decides it with its value here, and the actions on that link. A component+ * property and a variable share it, told apart by tone.+ */+const {+ label,+ name,+ value,+ tone = 'variable'+} = defineProps<{+ /** The field, which also names the row for assistive tech. */+ label: string+ /** The property or variable the field follows. */+ name: string+ /** What it holds for this layer, when that helps read the field. */+ value?: string+ tone?: 'component' | 'variable' | 'unresolved'+}>()+defineSlots<{ icon(): unknown; actions(): unknown }>()+</script>++<template>+ <PanelFieldGroup class="mb-1.5" :label="label">+ <div class="flex min-w-0 flex-1 items-center gap-1" role="group" :aria-label="label">+ <span+ class="flex h-7 min-w-0 flex-1 items-center gap-1.5 rounded px-2 text-xs"+ :class="{+ 'bg-component/15 text-component': tone === 'component',+ 'bg-input text-surface': tone === 'variable',+ 'bg-error-bg text-error': tone === 'unresolved'+ }"+ >+ <slot name="icon" />+ <span class="truncate">{{ name }}</span>+ <span v-if="value !== undefined" class="ml-auto max-w-1/2 min-w-0 truncate text-muted">+ {{ value }}+ </span>+ </span>+ <slot name="actions" />+ </div>+ </PanelFieldGroup>+</template>diff --git a/src/components/properties/component-properties/PropertyBoundField.vue b/src/components/properties/component-properties/PropertyBoundField.vueindex 00cc33fec..935123f8d 100644--- a/src/components/properties/component-properties/PropertyBoundField.vue+++ b/src/components/properties/component-properties/PropertyBoundField.vue@@ -9,10 +9,10 @@ import {import { usePanelMessages } from '@open-pencil/vue'+import BoundFieldRow from '@/components/properties/binding/BoundFieldRow.vue'import IconButton from '@/components/ui/button/IconButton.vue'import { menuItem, useMenuUI } from '@/components/ui/menu/menu'import MenuScrollArea from '@/components/ui/menu/MenuScrollArea.vue'-import PanelFieldGroup from '@/components/ui/panel/PanelFieldGroup.vue'import PropertyTypeIcon from './PropertyTypeIcon.vue'import { usePropertyBinding, type BindableField } from './usePropertyBinding'@@ -32,7 +32,7 @@ const panels = usePanelMessages()const menu = useMenuUI({ content: 'min-w-40' })const item = menuItem({ justify: 'start' })const chip =- 'flex h-7 min-w-0 items-center gap-1.5 rounded bg-component/15 px-2 text-xs text-component'+ 'flex h-7 max-w-40 min-w-0 items-center gap-1.5 rounded bg-component/15 px-2 text-xs text-component'</script><template>@@ -40,7 +40,7 @@ const chip =<DropdownMenuTrigger as-child><buttontype="button"- :class="[chip, 'max-w-40']"+ :class="chip":aria-label="`${binding.fieldLabel.value}: ${binding.definition.value.name}`":data-property-bound="field">@@ -67,16 +67,17 @@ const chip =</DropdownMenuContent></DropdownMenuPortal></DropdownMenuRoot>- <PanelFieldGroup+ <BoundFieldRowv-else-if="binding.available.value && binding.definition.value"- class="mb-1.5":label="label ?? binding.fieldLabel.value"+ :name="binding.definition.value.name"+ tone="component"+ :data-property-bound="field">- <div class="flex min-w-0 flex-1 items-center gap-1" :data-property-bound="field">- <span :class="[chip, 'flex-1']">- <PropertyTypeIcon :kind="binding.definition.value.type" class="!text-component" />- <span class="truncate">{{ binding.definition.value.name }}</span>- </span>+ <template #icon>+ <PropertyTypeIcon :kind="binding.definition.value.type" class="!text-component" />+ </template>+ <template #actions><IconButton :label="panels.goToComponentProperty" @click="binding.goToProperty()"><icon-lucide-crosshair class="size-3.5" /></IconButton>@@ -87,6 +88,6 @@ const chip =><icon-lucide-unlink class="size-3.5" /></IconButton>- </div>- </PanelFieldGroup>+ </template>+ </BoundFieldRow></template>diff --git a/src/components/properties/component-properties/usePropertyBinding.ts b/src/components/properties/component-properties/usePropertyBinding.tsindex 1a4d2978c..0e2d7c5ed 100644--- a/src/components/properties/component-properties/usePropertyBinding.ts+++ b/src/components/properties/component-properties/usePropertyBinding.ts@@ -44,6 +44,8 @@ export function usePropertyBinding(field: BindableField) {authoring.definitions.value.filter((item) => item.type === FIELD_TYPES[field])),fieldLabel: computed(() => fieldLabels.value[field]),+ /** The component whose properties the layer can link to. */+ ownerName: computed(() => context.value?.owner.name),create: () => {const node = context.value?.nodeif (node) authoring.expose(node.id, field, suggestedName())diff --git a/src/components/properties/visibility/VisibilityBindingRow.vue b/src/components/properties/visibility/VisibilityBindingRow.vuenew file mode 100644index 000000000..9885665b2--- /dev/null+++ b/src/components/properties/visibility/VisibilityBindingRow.vue@@ -0,0 +1,54 @@+<script setup lang="ts">+import { computed } from 'vue'++import { variableText } from '@open-pencil/scene-graph'+import {+ BindableValueRoot,+ useEditor,+ useI18n,+ useVisibilityBindingProvider+} from '@open-pencil/vue'++import BoundFieldRow from '@/components/properties/binding/BoundFieldRow.vue'+import IconButton from '@/components/ui/button/IconButton.vue'+import { VARIABLE_TYPE_ICONS } from '@/components/variables/type-icons'++/**+ * The variable a layer's visibility follows, with its value here and a way to let go of it.+ */+const { nodeId } = defineProps<{ nodeId: string }>()++const editor = useEditor()+const { panels } = useI18n()+const provider = useVisibilityBindingProvider()+const targets = computed(() => [{ nodeId, path: 'visible' }])++function valueText(variableId: string) {+ return variableText(editor.graph.resolveVariableForNode(nodeId, variableId))+}+</script>++<template>+ <BindableValueRoot v-slot="binding" :provider="provider" :targets="targets" :value="true">+ <BoundFieldRow+ v-if="binding.state !== 'unbound'"+ :label="panels.layerVisibility"+ :name="binding.variable?.name ?? binding.bindingId ?? panels.unresolvedVariable"+ :value="binding.variable ? valueText(binding.variable.id) : undefined"+ :tone="binding.state === 'unresolved' ? 'unresolved' : 'variable'"+ >+ <template #icon>+ <component+ :is="VARIABLE_TYPE_ICONS[binding.variable?.type ?? 'BOOLEAN']"+ class="size-3.5 shrink-0 text-muted"+ aria-hidden="true"+ />+ </template>+ <template #actions>+ <IconButton :label="panels.detachVariable" @click="binding.actions.unbind()">+ <icon-lucide-unlink class="size-3.5" />+ </IconButton>+ </template>+ </BoundFieldRow>+ </BindableValueRoot>+</template>diff --git a/src/components/properties/visibility/VisibilityControl.vue b/src/components/properties/visibility/VisibilityControl.vuenew file mode 100644index 000000000..8495aad65--- /dev/null+++ b/src/components/properties/visibility/VisibilityControl.vue@@ -0,0 +1,62 @@+<script setup lang="ts">+import { computed } from 'vue'++import { BindableValueRoot, useI18n, useVisibilityBindingProvider } from '@open-pencil/vue'++import IconButton from '@/components/ui/button/IconButton.vue'++import VisibilityPicker from './VisibilityPicker.vue'++/**+ * The Appearance eye with what binds visibility. While a variable decides it, the eye is+ * disabled, as in Figma: detaching the variable is what hands visibility back to the eye.+ */+const { nodeId, visibility } = defineProps<{+ /** The selected layer; several selected layers get the eye alone. */+ nodeId?: string+ visibility: 'visible' | 'hidden' | 'mixed'+}>()+const emit = defineEmits<{ toggle: [] }>()++const { panels } = useI18n()+const provider = useVisibilityBindingProvider()+const targets = computed(() => (nodeId ? [{ nodeId, path: 'visible' }] : []))+</script>++<template>+ <BindableValueRoot+ v-if="nodeId"+ v-slot="binding"+ :provider="provider"+ :targets="targets"+ :value="visibility === 'visible'"+ >+ <VisibilityPicker :node-id="nodeId">+ <template #eye="{ open }">+ <!-- A disabled button gets no events, so the right-click that opens the list lands here. -->+ <span class="inline-flex" @contextmenu.prevent="open">+ <IconButton+ :label="panels.toggleVisibility"+ :active="visibility === 'hidden'"+ :disabled="binding.state !== 'unbound'"+ class="disabled:pointer-events-none"+ @click="emit('toggle')"+ >+ <icon-lucide-eye v-if="visibility === 'visible'" class="size-3.5" />+ <icon-lucide-eye-off v-else class="size-3.5" />+ </IconButton>+ </span>+ </template>+ </VisibilityPicker>+ </BindableValueRoot>+ <IconButton+ v-else+ :label="panels.toggleVisibility"+ :active="visibility === 'hidden'"+ @click="emit('toggle')"+ >+ <icon-lucide-eye v-if="visibility === 'visible'" class="size-3.5" />+ <icon-lucide-eye-off v-else-if="visibility === 'hidden'" class="size-3.5" />+ <icon-lucide-eye v-else class="size-3.5 opacity-50" />+ </IconButton>+</template>diff --git a/src/components/properties/visibility/VisibilityPicker.vue b/src/components/properties/visibility/VisibilityPicker.vuenew file mode 100644index 000000000..e783de155--- /dev/null+++ b/src/components/properties/visibility/VisibilityPicker.vue@@ -0,0 +1,168 @@+<script setup lang="ts">+import { computed } from 'vue'++import { variableText } from '@open-pencil/scene-graph'+import { useBindableValue, useEditor, useI18n } from '@open-pencil/vue'++import PropertyTypeIcon from '@/components/properties/component-properties/PropertyTypeIcon.vue'+import { usePropertyBinding } from '@/components/properties/component-properties/usePropertyBinding'+import AppButton from '@/components/ui/button/AppButton.vue'+import IconButton from '@/components/ui/button/IconButton.vue'+import AppPicker, { type AppPickerItem } from '@/components/ui/select/AppPicker.vue'+import { VARIABLE_TYPE_ICONS } from '@/components/variables/type-icons'++/**+ * The list a layer's visibility binds from, as Figma's: a component layer's boolean properties,+ * then boolean and text variables. A component layer opens it from its own button; any layer+ * opens it by right-clicking the eye, which the `eye` slot renders.+ */+const { nodeId } = defineProps<{ nodeId: string }>()+defineSlots<{ eye(props: { open: () => void }): unknown }>()++const PROPERTY = 'property:'++const editor = useEditor()+const binding = useBindableValue<boolean>()+const property = usePropertyBinding('VISIBLE')+const { panels, common } = useI18n()++const open = computed({+ get: () => binding.open.value,+ set: (value: boolean) => (value ? binding.actions.openPicker() : binding.actions.closePicker())+})++const properties = computed(() => (property.available.value ? property.compatible.value : []))++/** A property the layer follows can only be let go of where properties are editable. */+const lockedToProperty = computed(() => !!property.definition.value && !property.editable.value)++const items = computed<AppPickerItem[]>(() => {+ const group = panels.value.propertiesInComponent({ name: property.ownerName.value ?? '' })+ return [+ ...properties.value.map((definition) => ({+ value: `${PROPERTY}${definition.id}`,+ label: definition.name,+ group,+ disabled: !property.editable.value+ })),+ ...binding.variables.value.map((variable) => ({+ value: variable.id,+ label: variable.name,+ group: binding.provider.collectionName?.(variable),+ disabled: lockedToProperty.value+ }))+ ]+})++const selected = computed(() => {+ const definition = property.definition.value+ return definition ? `${PROPERTY}${definition.id}` : binding.variable.value?.id+})++/** What an item holds now: a property's default, or a variable's value for this layer. */+function valueText(value: string) {+ if (value.startsWith(PROPERTY))+ return properties.value.find((definition) => `${PROPERTY}${definition.id}` === value)+ ?.defaultValue+ return variableText(editor.graph.resolveVariableForNode(nodeId, value))+}++function variableType(value: string) {+ return editor.getVariable(value)?.type+}++/** A layer follows one source at a time, so choosing one lets go of the other in the same step. */+function select(value: string) {+ if (value.startsWith(PROPERTY) ? !property.editable.value : lockedToProperty.value) return+ editor.undo.runBatch('Bind visibility', () => {+ if (value.startsWith(PROPERTY)) {+ if (binding.state.value !== 'unbound') binding.actions.unbind()+ property.bind(value.slice(PROPERTY.length))+ } else {+ if (property.definition.value) property.bind(null)+ binding.actions.bind(value)+ }+ })+}++function createProperty() {+ open.value = false+ editor.undo.runBatch('Bind visibility', () => {+ if (binding.state.value !== 'unbound') binding.actions.unbind()+ property.create()+ })+}++function detach() {+ open.value = false+ binding.actions.unbind()+}++function openPicker() {+ open.value = true+}+</script>++<template>+ <slot v-if="property.available.value" name="eye" :open="openPicker" />+ <AppPicker+ v-model:open="open"+ :heading="property.available.value ? panels.applyVariableOrProperty : panels.applyVariable"+ :items="items"+ :selected="selected"+ density="compact"+ side="bottom"+ align="end"+ :search-placeholder="common.search"+ :empty-label="panels.noVariablesFound"+ :close-label="common.close"+ :tooltip="panels.applyVariableOrProperty"+ @select="select"+ >+ <template v-if="property.available.value" #trigger>+ <IconButton+ :label="panels.applyVariableOrProperty"+ :disabled="!property.editable.value"+ :active="open"+ >+ <icon-lucide-diamond-plus class="size-3.5" />+ </IconButton>+ </template>+ <template v-else #anchor>+ <slot name="eye" :open="openPicker" />+ </template>+ <template #leading="{ item }">+ <PropertyTypeIcon v-if="item.value.startsWith(PROPERTY)" kind="BOOLEAN" />+ <component+ :is="VARIABLE_TYPE_ICONS[variableType(item.value) ?? 'BOOLEAN']"+ v-else+ class="size-3.5 shrink-0 text-muted"+ aria-hidden="true"+ />+ </template>+ <template #trailing="{ item }">+ <span class="max-w-20 shrink-0 truncate text-muted">{{ valueText(item.value) }}</span>+ </template>+ <template v-if="binding.state.value !== 'unbound' || property.available.value" #footer>+ <AppButton+ v-if="binding.state.value !== 'unbound'"+ size="xs"+ class="w-full justify-start"+ @click="detach"+ >+ <template #leading><icon-lucide-unlink class="size-3" /></template>+ {{ panels.detachVariable }}+ </AppButton>+ <AppButton+ v-if="property.available.value"+ size="xs"+ class="w-full justify-start"+ :disabled="!property.editable.value"+ @click="createProperty"+ >+ <template #leading><icon-lucide-plus class="size-3" /></template>+ {{ panels.createComponentProperty }}+ </AppButton>+ </template>+ </AppPicker>+</template>diff --git a/src/components/ui/select/AppPicker.vue b/src/components/ui/select/AppPicker.vueindex 0d2915f27..569c708bf 100644--- a/src/components/ui/select/AppPicker.vue+++ b/src/components/ui/select/AppPicker.vue@@ -47,7 +47,12 @@ export interface AppPickerProps {export interface AppPickerSlots {/** The control that opens the picker; rendered as the popover trigger. */- trigger(): VNode[]+ trigger?(): VNode[]+ /**+ * What the list opens beside when the owner opens it through `v-model:open` instead of a+ * trigger, such as from a context menu; used when there is no `trigger`.+ */+ anchor?(): VNode[]/** Thumbnail or icon before an item's label. */leading?(props: { item: AppPickerItem }): VNode[]/** A control at the end of the search field that narrows the list, such as a category. */@@ -67,6 +72,7 @@ import {ListboxGroupLabel,ListboxItem,ListboxRoot,+ PopoverAnchor,PopoverClose,PopoverContent,PopoverPortal,@@ -184,11 +190,14 @@ function select(value: AcceptableValue) {<template><PopoverRoot v-model:open="open">- <Tip as-child :label="tooltip" :disabled="!tooltip">+ <Tip v-if="slots.trigger" as-child :label="tooltip" :disabled="!tooltip"><PopoverTrigger as-child><slot name="trigger" /></PopoverTrigger></Tip>+ <PopoverAnchor v-else as-child>+ <slot name="anchor" />+ </PopoverAnchor><PopoverPortal v-if="portalActive"><PopoverContent:side="side"diff --git a/tests/e2e/properties/bound-visibility.spec.ts b/tests/e2e/properties/bound-visibility.spec.tsnew file mode 100644index 000000000..d2e7db9c3--- /dev/null+++ b/tests/e2e/properties/bound-visibility.spec.ts@@ -0,0 +1,74 @@+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'+import { visibilityDriver } from '#tests/helpers/properties/visibility-driver'++// Figma desktop 126: right-clicking the Appearance eye binds visibility to a boolean or text+// variable; a component layer's own button also lists its boolean properties. While a variable+// decides visibility the eye is disabled, and detaching keeps the visibility it last gave.++const editor = useEditorSetupWithClear('/?test')+const visibility = visibilityDriver(() => editor.page)++function appearance() {+ return editor.page.getByRole('region', { name: 'Appearance', exact: true })+}++test('right-clicking the eye binds visibility to a text variable that decides it', async () => {+ const scene = await visibility.build()+ const eye = appearance().getByRole('button', { name: 'Toggle visibility' })+ await expect(appearance().getByRole('button', { name: 'Apply variable/property' })).toHaveCount(0)++ await eye.dispatchEvent('contextmenu')+ const picker = editor.page.getByRole('dialog', { name: 'Apply variable' })+ await expect(picker.getByRole('option')).toHaveText([/show-icon\s*true/, /state\s*yes/])+ await picker.getByRole('option', { name: /state/ }).click()++ const bound = appearance().getByRole('group', { name: 'Visibility' })+ await expect(eye).toBeDisabled()+ await expect(bound).toContainText(/state\s*yes/)+ for (const [text, visible] of [+ ['no', false],+ ['On', true],+ ['', false]+ ] as const) {+ await visibility.setText(text)+ expect(await visibility.layer(scene.plain)).toMatchObject({ visible, variable: scene.state })+ }++ await bound.getByRole('button', { name: 'Detach variable' }).click()+ expect(await visibility.layer(scene.plain)).toEqual({+ visible: false,+ variable: undefined,+ property: undefined+ })+ await expect(eye).toBeEnabled()+})++test('a component layer picks a property or a variable, one at a time', async () => {+ const scene = await visibility.build()+ await visibility.selectComponentLayer()+ const apply = appearance().getByRole('button', { name: 'Apply variable/property' })+ const picker = editor.page.getByRole('dialog', { name: 'Apply variable/property' })++ await apply.click()+ await picker.getByRole('option', { name: /show-icon/ }).click()+ expect((await visibility.layer(scene.componentLayer)).variable).toBe(scene.flag)++ await apply.click()+ await picker.getByRole('button', { name: 'Create property…' }).click()+ const { property, variable } = await visibility.layer(scene.componentLayer)+ expect(property).toBeDefined()+ expect(variable).toBeUndefined()++ await apply.click()+ await expect(picker.getByRole('group', { name: 'Properties in Button' })).toBeVisible()+ await picker.getByRole('option', { name: /show-icon/ }).click()+ expect(await visibility.layer(scene.componentLayer)).toMatchObject({+ variable: scene.flag,+ property: undefined+ })++ await editor.page.keyboard.press('ControlOrMeta+z')+ await expect+ .poll(() => visibility.layer(scene.componentLayer))+ .toMatchObject({ variable: undefined, property })+})diff --git a/tests/engine/vue/controls/binding-mode-edit.test.ts b/tests/engine/vue/controls/binding-mode-edit.test.tsindex 610998e1d..0f29842d5 100644--- a/tests/engine/vue/controls/binding-mode-edit.test.ts+++ b/tests/engine/vue/controls/binding-mode-edit.test.ts@@ -48,7 +48,7 @@ test('prepared edits retain modes after targets change and undo atomically', ()variableModes: { [collection.id]: 'alternate' }})const provider = createOpenPencilBindingProvider(editor, {- type: 'FLOAT',+ types: ['FLOAT'],resolve: (e, id, target) =>target? e.graph.resolveNumberVariableForNode(target.nodeId, id)diff --git a/tests/engine/vue/controls/binding-modes.test.ts b/tests/engine/vue/controls/binding-modes.test.tsindex e16b2b03e..641ef7461 100644--- a/tests/engine/vue/controls/binding-modes.test.ts+++ b/tests/engine/vue/controls/binding-modes.test.ts@@ -21,7 +21,7 @@ test('binding resolution uses node modes and reports mixed resolved values', ()})const targets = [a, b].map((node) => ({ nodeId: node.id, path: 'width' }))const provider = createOpenPencilBindingProvider(editor, {- type: 'FLOAT',+ types: ['FLOAT'],prepareEdit: (e, id, target) =>prepareModeEdit(e, id, target, () => e.graph.resolveNumberVariableForNode(target.nodeId, id)),resolve: (e, id, target) =>diff --git a/tests/helpers/properties/visibility-driver.ts b/tests/helpers/properties/visibility-driver.tsnew file mode 100644index 000000000..4b3273231--- /dev/null+++ b/tests/helpers/properties/visibility-driver.ts@@ -0,0 +1,94 @@+import type { Page } from '@playwright/test'++interface VisibilityScene {+ componentLayer: string+ plain: string+ flag: string+ state: string+ mode: string+}++/**+ * Builds variables of each type, a component with a layer and a plain layer, and reads back+ * what decides a layer's visibility. Selection and variable values are fixture setup; binding+ * goes through the panel.+ */+export function visibilityDriver(page: () => Page) {+ let scene: VisibilityScene | undefined++ function built() {+ if (!scene) throw new Error('Build the scene first')+ return scene+ }++ return {+ async build() {+ scene = await page().evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const graph = store.graph+ const pageId = store.state.currentPageId+ // The page is cleared between tests; the variables an earlier test made are not.+ for (const id of graph.variableCollections.keys()) graph.removeCollection(id)+ const collection = graph.createCollection('Flags')+ const flag = graph.createVariable('show-icon', 'BOOLEAN', collection.id, true)+ const state = graph.createVariable('state', 'STRING', collection.id, 'yes')+ graph.createVariable('size', 'FLOAT', collection.id, 4)+ const button = graph.createNode('COMPONENT', pageId, {+ name: 'Button',+ width: 160,+ height: 48+ })+ const badge = graph.createNode('RECTANGLE', button.id, {+ name: 'Badge',+ width: 24,+ height: 24+ })+ const plain = graph.createNode('RECTANGLE', pageId, {+ name: 'Plain',+ x: 300,+ width: 48,+ height: 48+ })+ store.select([plain.id])+ return {+ componentLayer: badge.id,+ plain: plain.id,+ flag: flag.id,+ state: state.id,+ mode: collection.defaultModeId+ }+ })+ return scene+ },++ selectComponentLayer() {+ return page().evaluate(+ (id) => window.openPencil?.getStore?.().select([id]),+ built().componentLayer+ )+ },++ setText(text: string) {+ const { state, mode } = built()+ return page().evaluate(+ (args) =>+ window.openPencil?.getStore?.().updateVariableValue(args.state, args.mode, args.text),+ { state, mode, text }+ )+ },++ /** What decides a layer's visibility: its value, its variable, and its component property. */+ layer(id: string) {+ return page().evaluate((nodeId) => {+ const node = window.openPencil?.getStore?.().graph.getNode(nodeId)+ return {+ visible: node?.visible,+ variable: node?.boundVariables.visible,+ property: node?.componentPropertyReferences.find((item) => item.field === 'VISIBLE')+ ?.propertyId+ }+ }, id)+ }+ }+}