Skip to content

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

fix(bindings): resolve modes and preserve edit transactions (#671)

Danila Poyarkov77739c42a405
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d5de20bab..671289a54 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,10 @@
## Unreleased
+### Breaking changes
+
+- Update custom Vue SDK binding providers to implement `getBindingId()` and handle `unresolved`. Replace `setValue()` with `prepareEdit()`, returning a stable edit key, captured value, setter, and restoration callback.
+
### Added
- Save AI conversations and attachment previews locally, switch between chats, rename or delete them, and browse saved transcripts across documents. Choose whether reasoning stays collapsed, expands while thinking, or stays expanded, with animated disclosure controls that respect reduced motion.
@@ -46,6 +50,8 @@
- Route browser Command/Ctrl plus and minus shortcuts to canvas zoom instead of page zoom.
- Resolve `$name` references in imported `.pen` fills, stroke fills, font families, dimensions, and spacing without requiring a `--` prefix. (#563)
+- Resolve bound fields in each layer’s mode, keep variable edits scoped and undoable, and make broken bindings visible and recoverable.
+- Display letter spacing in pixels and support explicit automatic line height.
- Prevent the stock photo tool from replacing text, lines, structural layers, or containers with content while supporting closed shape geometry.
- Preserve explicit text alignment metadata on imported Figma vectors across save and reload.
diff --git a/packages/vue/src/controls/binding-provider/color.ts b/packages/vue/src/controls/binding-provider/color.ts
index 4255084d6..9ca36c419 100644
--- a/packages/vue/src/controls/binding-provider/color.ts
+++ b/packages/vue/src/controls/binding-provider/color.ts
@@ -6,6 +6,9 @@ import type { Color } from '@open-pencil/scene-graph/primitives'
import { useOpenPencilBindingProvider } from '#vue/controls/binding-provider/open-pencil'
import type { BindingTarget } from '#vue/controls/binding-provider/types'
+import { prepareModeEdit } from './mode-edit'
+import { resolveEffectiveBindingValue } from './resolution'
+
const FALLBACK_COLOR_VARIABLE_NAME = 'New color'
function colorCollection(editor: Editor): VariableCollection {
@@ -49,20 +52,19 @@ export function createAndBindColorVariable(
editor.bindVariable(target.nodeId, target.path, id)
}
-export function setColorVariableValue(editor: Editor, variableId: string, value: Color) {
- const variable = editor.getVariable(variableId)
- if (!variable) return
- const collection = editor.getCollection(variable.collectionId)
- if (!collection) return
- for (const mode of collection.modes)
- editor.updateVariableValue(variableId, mode.modeId, structuredClone(value))
+function resolveColor(editor: Editor, id: string, target?: BindingTarget) {
+ const value = target
+ ? resolveEffectiveBindingValue(editor, id, target)
+ : editor.resolveColorVariable(id)
+ return value && typeof value === 'object' && 'r' in value ? value : undefined
}
export function useColorBindingProvider() {
return useOpenPencilBindingProvider<Color>({
type: 'COLOR',
- resolve: (editor, variableId) => editor.resolveColorVariable(variableId),
- create: createAndBindColorVariable,
- setValue: setColorVariableValue
+ resolve: resolveColor,
+ prepareEdit: (editor, id, target) =>
+ prepareModeEdit(editor, id, target, () => resolveColor(editor, id, target)),
+ create: createAndBindColorVariable
})
}
diff --git a/packages/vue/src/controls/binding-provider/mode-edit.ts b/packages/vue/src/controls/binding-provider/mode-edit.ts
new file mode 100644
index 000000000..5f0c00a0c
--- /dev/null
+++ b/packages/vue/src/controls/binding-provider/mode-edit.ts
@@ -0,0 +1,31 @@
+import type { Editor } from '@open-pencil/core/editor'
+import type { Color } from '@open-pencil/scene-graph'
+
+import type { BindingTarget, BindingValueEdit } from './types'
+
+/** Edit the directly bound variable's mode, not a shared alias source.
+ * Capturing the raw value lets cancel and Undo restore an alias exactly.
+ */
+export function prepareModeEdit<V extends number | Color>(
+ editor: Editor,
+ variableId: string,
+ target: BindingTarget,
+ resolve: () => V | undefined
+): BindingValueEdit<V> | undefined {
+ const variable = editor.getVariable(variableId)
+ const value = resolve()
+ if (!variable || value === undefined) return undefined
+ const modeId = editor.graph.getNodeVariableModeId(target.nodeId, variable.collectionId)
+ if (!Object.hasOwn(variable.valuesByMode, modeId)) return undefined
+ const original = structuredClone(variable.valuesByMode[modeId])
+ return {
+ restore() {
+ editor.updateVariableValue(variableId, modeId, structuredClone(original))
+ },
+ key: JSON.stringify([variableId, modeId]),
+ value: structuredClone(value),
+ set(next) {
+ editor.updateVariableValue(variableId, modeId, structuredClone(next))
+ }
+ }
+}
diff --git a/packages/vue/src/controls/binding-provider/number.ts b/packages/vue/src/controls/binding-provider/number.ts
index 7fc8e4f5d..427aad2e2 100644
--- a/packages/vue/src/controls/binding-provider/number.ts
+++ b/packages/vue/src/controls/binding-provider/number.ts
@@ -5,6 +5,9 @@ import type { VariableCollection } from '@open-pencil/scene-graph'
import { useOpenPencilBindingProvider } from '#vue/controls/binding-provider/open-pencil'
import type { BindingTarget } from '#vue/controls/binding-provider/types'
+import { prepareModeEdit } from './mode-edit'
+import { resolveEffectiveBindingValue } from './resolution'
+
const FALLBACK_NUMBER_VARIABLE_NAME = 'New number'
function numberCollection(editor: Editor): VariableCollection {
@@ -46,19 +49,19 @@ export function createAndBindNumberVariable(
editor.bindVariable(target.nodeId, target.path, id)
}
-function setNumberVariableValue(editor: Editor, variableId: string, value: number) {
- const variable = editor.getVariable(variableId)
- if (!variable) return
- const collection = editor.getCollection(variable.collectionId)
- if (!collection) return
- for (const mode of collection.modes) editor.updateVariableValue(variableId, mode.modeId, value)
+function resolveNumber(editor: Editor, id: string, target?: BindingTarget) {
+ const value = target
+ ? resolveEffectiveBindingValue(editor, id, target)
+ : editor.resolveNumberVariable(id)
+ return typeof value === 'number' ? value : undefined
}
export function useNumberBindingProvider() {
return useOpenPencilBindingProvider<number>({
type: 'FLOAT',
- resolve: (editor, variableId) => editor.resolveNumberVariable(variableId),
- create: createAndBindNumberVariable,
- setValue: setNumberVariableValue
+ resolve: resolveNumber,
+ prepareEdit: (editor, id, target) =>
+ prepareModeEdit(editor, id, target, () => resolveNumber(editor, id, target)),
+ create: createAndBindNumberVariable
})
}
diff --git a/packages/vue/src/controls/binding-provider/open-pencil.ts b/packages/vue/src/controls/binding-provider/open-pencil.ts
index 0644074a8..4412d35a9 100644
--- a/packages/vue/src/controls/binding-provider/open-pencil.ts
+++ b/packages/vue/src/controls/binding-provider/open-pencil.ts
@@ -1,9 +1,11 @@
+import { isEqual } from 'es-toolkit'
import { useFilter } from 'reka-ui'
import type { Editor } from '@open-pencil/core/editor'
import type { Variable, VariableType } from '@open-pencil/scene-graph'
import type {
+ BindingValueEdit,
BindingProvider,
BindingState,
BindingTarget
@@ -11,32 +13,34 @@ import type {
import { useEditor } from '#vue/editor/context'
import { useSceneComputed } from '#vue/internal/scene-computed/use'
+import { resolveEffectiveBindingValue } from './resolution'
+
export interface OpenPencilBindingProviderOptions<V> {
type: VariableType
- resolve(editor: Editor, variableId: string): V | undefined
+ resolve(editor: Editor, variableId: string, target?: BindingTarget): V | undefined
create?(editor: Editor, target: BindingTarget, value: V, name: string): void
- setValue?(editor: Editor, variableId: string, value: V): void
+ prepareEdit?(
+ editor: Editor,
+ variableId: string,
+ target: BindingTarget
+ ): BindingValueEdit<V> | undefined
}
-export function useOpenPencilBindingProvider<V>(
- options: OpenPencilBindingProviderOptions<V>
+export function createOpenPencilBindingProvider<V>(
+ editor: Editor,
+ options: OpenPencilBindingProviderOptions<V>,
+ revision?: BindingProvider<V>['revision']
): BindingProvider<V> {
- const editor = useEditor()
- const revision = useSceneComputed(() => editor.state.sceneVersion)
- const variables = useSceneComputed(() => editor.getVariablesByType(options.type))
const { contains } = useFilter({ sensitivity: 'base' })
-
- function listVariables(): Variable[] {
- return variables.value
- }
+ const variables = () => editor.getVariablesByType(options.type)
function filterVariables(term: string): Variable[] {
- if (!term) return variables.value
- return variables.value.filter((variable) => contains(variable.name, term))
+ if (!term) return variables()
+ return variables().filter((variable) => contains(variable.name, term))
}
function getBound(target: BindingTarget): Variable | undefined {
- void revision.value
+ void revision?.value
const variableId = editor.getNode(target.nodeId)?.boundVariables[target.path]
return variableId ? editor.getVariable(variableId) : undefined
}
@@ -48,24 +52,42 @@ export function useOpenPencilBindingProvider<V>(
(target) => editor.getNode(target.nodeId)?.boundVariables[target.path] ?? undefined
)
)
+ // Identity takes precedence: an explicit mixed edit can detach the selection.
+ // edit-variable still requires every bound destination to prepare successfully.
if (variableIds.size > 1) return 'mixed'
- return variableIds.has(undefined) ? 'unbound' : 'bound'
+ const unresolved = targets.some((target) => {
+ const id = editor.getNode(target.nodeId)?.boundVariables[target.path]
+ return (
+ id !== undefined &&
+ (resolveEffectiveBindingValue(editor, id, target) === undefined ||
+ options.resolve(editor, id, target) === undefined)
+ )
+ })
+ if (unresolved) return 'unresolved'
+ if (variableIds.has(undefined)) return 'unbound'
+ const values = targets.map((target) => {
+ const id = editor.getNode(target.nodeId)?.boundVariables[target.path]
+ return id ? options.resolve(editor, id, target) : undefined
+ })
+ if (values.some((value) => value === undefined)) return 'unresolved'
+ return values.every((value) => isEqual(value, values[0])) ? 'bound' : 'mixed'
}
return {
revision,
- listVariables,
+ listVariables: variables,
filterVariables,
+ getBindingId: (target) => editor.getNode(target.nodeId)?.boundVariables[target.path],
getBound,
getState,
- resolve: (variableId) => options.resolve(editor, variableId),
+ resolve: (variableId, target) => options.resolve(editor, variableId, target),
bind: (target, variableId) => editor.bindVariable(target.nodeId, target.path, variableId),
unbind: (target) => editor.unbindVariable(target.nodeId, target.path),
create: options.create
? (target, value, name) => options.create?.(editor, target, value, name)
: undefined,
- setValue: options.setValue
- ? (variableId, value) => options.setValue?.(editor, variableId, value)
+ prepareEdit: options.prepareEdit
+ ? (variableId, target) => options.prepareEdit?.(editor, variableId, target)
: undefined,
runBatch: (label, action) => editor.undo.runBatch(label, action),
beginBatch: (label) => editor.undo.beginBatch(label),
@@ -73,3 +95,11 @@ export function useOpenPencilBindingProvider<V>(
rollbackBatch: () => editor.undo.rollbackBatch()
}
}
+
+export function useOpenPencilBindingProvider<V>(
+ options: OpenPencilBindingProviderOptions<V>
+): BindingProvider<V> {
+ const editor = useEditor()
+ const revision = useSceneComputed(() => editor.state.sceneVersion)
+ return createOpenPencilBindingProvider(editor, options, revision)
+}
diff --git a/packages/vue/src/controls/binding-provider/prepare-edits.ts b/packages/vue/src/controls/binding-provider/prepare-edits.ts
new file mode 100644
index 000000000..e86a2553b
--- /dev/null
+++ b/packages/vue/src/controls/binding-provider/prepare-edits.ts
@@ -0,0 +1,18 @@
+import type { BindingProvider, BindingTarget, BindingValueEdit } from './types'
+
+/** Capture and deduplicate edit destinations before an interaction starts. */
+export function prepareBindingEdits<V>(
+ provider: BindingProvider<V>,
+ targets: readonly BindingTarget[]
+): BindingValueEdit<V>[] | undefined {
+ const edits = new Map<string, BindingValueEdit<V>>()
+ for (const target of targets) {
+ const captured = { ...target }
+ const variable = provider.getBound(captured)
+ if (!variable) return undefined
+ const edit = provider.prepareEdit?.(variable.id, captured)
+ if (!edit) return undefined
+ edits.set(edit.key, edit)
+ }
+ return [...edits.values()]
+}
diff --git a/packages/vue/src/controls/binding-provider/resolution.ts b/packages/vue/src/controls/binding-provider/resolution.ts
new file mode 100644
index 000000000..bbf4b12e5
--- /dev/null
+++ b/packages/vue/src/controls/binding-provider/resolution.ts
@@ -0,0 +1,24 @@
+import type { Editor } from '@open-pencil/core/editor'
+import type { VariableValue } from '@open-pencil/scene-graph'
+
+import type { BindingTarget } from './types'
+
+/** Validate the effective value without substituting values from other modes. */
+export function resolveEffectiveBindingValue(
+ editor: Editor,
+ variableId: string,
+ target: BindingTarget,
+ visited = new Set<string>()
+): VariableValue | undefined {
+ if (visited.has(variableId)) return undefined
+ visited.add(variableId)
+ const variable = editor.getVariable(variableId)
+ if (!variable || !editor.getCollection(variable.collectionId)) return undefined
+ const mode = editor.graph.getNodeVariableModeId(target.nodeId, variable.collectionId)
+ if (!Object.hasOwn(variable.valuesByMode, mode)) return undefined
+ const value = variable.valuesByMode[mode]
+ if (value && typeof value === 'object' && 'aliasId' in value) {
+ return resolveEffectiveBindingValue(editor, value.aliasId, target, visited)
+ }
+ return value
+}
diff --git a/packages/vue/src/controls/binding-provider/types.ts b/packages/vue/src/controls/binding-provider/types.ts
index 66fa26bda..50ef0f523 100644
--- a/packages/vue/src/controls/binding-provider/types.ts
+++ b/packages/vue/src/controls/binding-provider/types.ts
@@ -2,7 +2,7 @@ import type { Ref } from 'vue'
import type { Variable } from '@open-pencil/scene-graph'
-export type BindingState = 'unbound' | 'bound' | 'mixed'
+export type BindingState = 'unbound' | 'bound' | 'mixed' | 'unresolved'
export type BoundEditPolicy = 'detach-on-edit' | 'readonly-when-bound' | 'edit-variable'
export type BindingMutationSource = 'edit' | 'scrub' | 'step'
@@ -11,18 +11,27 @@ export interface BindingTarget {
path: string
}
+export interface BindingValueEdit<V> {
+ /** Stable identity of the variable and storage location being edited. */
+ key: string
+ value: V
+ restore(): void
+ set(value: V): void
+}
+
export interface BindingProvider<V = unknown> {
/** Optional reactive revision consumed by BindableValueRoot. */
revision?: Readonly<Ref<unknown>>
listVariables(): Variable[]
filterVariables(term: string): Variable[]
+ getBindingId(target: BindingTarget): string | undefined
getBound(target: BindingTarget): Variable | undefined
getState(targets: BindingTarget[]): BindingState
- resolve(variableId: string): V | undefined
+ resolve(variableId: string, target?: BindingTarget): V | undefined
bind(target: BindingTarget, variableId: string): void
unbind(target: BindingTarget): void
create?(target: BindingTarget, value: V, name: string): void
- setValue?(variableId: string, value: V): void
+ prepareEdit?(variableId: string, target: BindingTarget): BindingValueEdit<V> | undefined
runBatch?<T>(label: string, action: () => T): T
beginBatch?(label: string): void
commitBatch?(): void
diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.json
index 808fdcf4f..a9dfce2ad 100644
--- a/packages/vue/src/i18n/locales/de/panels.json
+++ b/packages/vue/src/i18n/locales/de/panels.json
@@ -350,5 +350,7 @@
"individualPadding": "Individueller Innenabstand",
"strokeSettings": "Kontureinstellungen",
"strokeDashLength": "Strich",
- "strokeDashGap": "Lücke"
+ "strokeDashGap": "Lücke",
+ "lineHeightMode": "Zeilenhöhenmodus",
+ "unresolvedVariable": "Variablenwert nicht verfügbar"
}
diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.json
index a7cc396f6..5a4feadc5 100644
--- a/packages/vue/src/i18n/locales/es/panels.json
+++ b/packages/vue/src/i18n/locales/es/panels.json
@@ -350,5 +350,7 @@
"individualPadding": "Relleno individual",
"strokeSettings": "Ajustes de trazo",
"strokeDashLength": "Guion",
- "strokeDashGap": "Espacio"
+ "strokeDashGap": "Espacio",
+ "lineHeightMode": "Modo de altura de línea",
+ "unresolvedVariable": "Valor de variable no disponible"
}
diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.json
index 99d53d648..07a6593fb 100644
--- a/packages/vue/src/i18n/locales/fr/panels.json
+++ b/packages/vue/src/i18n/locales/fr/panels.json
@@ -350,5 +350,7 @@
"individualPadding": "Marges intérieures individuelles",
"strokeSettings": "Paramètres du contour",
"strokeDashLength": "Tiret",
- "strokeDashGap": "Espacement"
+ "strokeDashGap": "Espacement",
+ "lineHeightMode": "Mode de hauteur de ligne",
+ "unresolvedVariable": "Valeur de variable indisponible"
}
diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.json
index 045c5f9fb..c1bd89022 100644
--- a/packages/vue/src/i18n/locales/it/panels.json
+++ b/packages/vue/src/i18n/locales/it/panels.json
@@ -350,5 +350,7 @@
"individualPadding": "Spaziatura interna individuale",
"strokeSettings": "Impostazioni del tratto",
"strokeDashLength": "Trattino",
- "strokeDashGap": "Spazio"
+ "strokeDashGap": "Spazio",
+ "lineHeightMode": "Modalità altezza riga",
+ "unresolvedVariable": "Valore della variabile non disponibile"
}
diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.json
index 7fae44d00..81ff8bfd0 100644
--- a/packages/vue/src/i18n/locales/ja/panels.json
+++ b/packages/vue/src/i18n/locales/ja/panels.json
@@ -350,5 +350,7 @@
"individualPadding": "個別のパディング",
"strokeSettings": "線の設定",
"strokeDashLength": "破線の長さ",
- "strokeDashGap": "間隔"
+ "strokeDashGap": "間隔",
+ "lineHeightMode": "行の高さモード",
+ "unresolvedVariable": "変数の値を取得できません"
}
diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.json
index 8ada91085..bff88ba2a 100644
--- a/packages/vue/src/i18n/locales/pl/panels.json
+++ b/packages/vue/src/i18n/locales/pl/panels.json
@@ -350,5 +350,7 @@
"individualPadding": "Indywidualne dopełnienie",
"strokeSettings": "Ustawienia obrysu",
"strokeDashLength": "Kreska",
- "strokeDashGap": "Odstęp"
+ "strokeDashGap": "Odstęp",
+ "lineHeightMode": "Tryb wysokości wiersza",
+ "unresolvedVariable": "Wartość zmiennej jest niedostępna"
}
diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.json
index 23639d163..541bfc9cf 100644
--- a/packages/vue/src/i18n/locales/ru/panels.json
+++ b/packages/vue/src/i18n/locales/ru/panels.json
@@ -350,5 +350,7 @@
"individualPadding": "Отступы по сторонам",
"strokeSettings": "Настройки обводки",
"strokeDashLength": "Штрих",
- "strokeDashGap": "Промежуток"
+ "strokeDashGap": "Промежуток",
+ "lineHeightMode": "Режим межстрочного интервала",
+ "unresolvedVariable": "Значение переменной недоступно"
}
diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.json
index 3040fc9d7..c1106aab0 100644
--- a/packages/vue/src/i18n/locales/zh-cn/panels.json
+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json
@@ -350,5 +350,7 @@
"individualPadding": "独立内边距",
"strokeSettings": "描边设置",
"strokeDashLength": "虚线",
- "strokeDashGap": "间距"
+ "strokeDashGap": "间距",
+ "lineHeightMode": "行高模式",
+ "unresolvedVariable": "变量值不可用"
}
diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.ts
index 6b768310a..9e229f373 100644
--- a/packages/vue/src/i18n/messages/panels.ts
+++ b/packages/vue/src/i18n/messages/panels.ts
@@ -137,6 +137,8 @@ export const panelMessageDefaults = {
fontFamily: 'Font family',
fontWeight: 'Font weight',
fontSize: 'Font size',
+ lineHeightMode: 'Line height mode',
+ unresolvedVariable: 'Variable value unavailable',
lineHeight: 'Line height',
letterSpacing: 'Letter spacing',
textAlignment: 'Text alignment',
diff --git a/packages/vue/src/primitives/BindableValue/BindableValue.stories.ts b/packages/vue/src/primitives/BindableValue/BindableValue.stories.ts
index 1ef200215..94c8d4970 100644
--- a/packages/vue/src/primitives/BindableValue/BindableValue.stories.ts
+++ b/packages/vue/src/primitives/BindableValue/BindableValue.stories.ts
@@ -2,6 +2,7 @@ import type { Meta, StoryObj } from '@storybook/vue3-vite'
import { expect, userEvent, within } from 'storybook/test'
import BindableValueDemo from './demo/BindableValueDemo.vue'
+import ModeEditDemo from './demo/ModeEditDemo.vue'
const meta = {
title: 'Vue SDK/Primitives/BindableValue',
@@ -20,6 +21,10 @@ const meta = {
export default meta
type Story = StoryObj<typeof meta>
+export const ModeEditing: Story = {
+ render: () => ({ components: { ModeEditDemo }, template: '<ModeEditDemo />' })
+}
+
export const StateMatrix: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement)
diff --git a/packages/vue/src/primitives/BindableValue/BindableValueRoot.vue b/packages/vue/src/primitives/BindableValue/BindableValueRoot.vue
index 8c7d2593e..b1d1b5659 100644
--- a/packages/vue/src/primitives/BindableValue/BindableValueRoot.vue
+++ b/packages/vue/src/primitives/BindableValue/BindableValueRoot.vue
@@ -2,7 +2,9 @@
import { computed, onBeforeUnmount, ref } from 'vue'
import { useBindingProvider } from '#vue/controls/binding-provider/context'
+import { prepareBindingEdits } from '#vue/controls/binding-provider/prepare-edits'
import type {
+ BindingValueEdit,
BindingMutationSource,
BindingProvider,
BindingTarget
@@ -54,18 +56,20 @@ const state = computed(() => {
})
const variable = computed(() => {
const target = targets.value[0]
- return state.value === 'bound' && target ? provider.getBound(target) : undefined
+ return state.value !== 'mixed' && target ? provider.getBound(target) : undefined
})
const resolvedValue = computed(() => {
void provider.revision?.value
+ if (state.value === 'unresolved') return undefined
const current = variable.value
- return current ? provider.resolve(current.id) : undefined
+ return current ? provider.resolve(current.id, targets.value[0]) : undefined
})
const variables = computed(() => {
void provider.revision?.value
return provider.filterVariables(searchTerm.value)
})
const stateAttrs = computed<BindableValueStateAttrs>(() => ({
+ 'data-unresolved': state.value === 'unresolved' ? '' : undefined,
'data-unbound': state.value === 'unbound' ? '' : undefined,
'data-bound': state.value === 'bound' ? '' : undefined,
'data-mixed': state.value === 'mixed' ? '' : undefined,
@@ -76,7 +80,8 @@ const stateAttrs = computed<BindableValueStateAttrs>(() => ({
let interactionActive = false
let detachedForInteraction = false
let bindingSnapshot = new Map<BindingTarget, string>()
-let resolvedSnapshot: V | undefined
+let valueEdits: BindingValueEdit<V>[] = []
+let interactionPolicy = policy.value
function runImmediate(label: string, action: () => void) {
if (provider.runBatch) provider.runBatch(label, action)
@@ -122,13 +127,14 @@ function setSearchTerm(term: string) {
function snapshotBindings() {
bindingSnapshot = new Map()
for (const target of targets.value) {
- const current = provider.getBound(target)
- if (current) bindingSnapshot.set(target, current.id)
+ const id = provider.getBindingId(target)
+ if (id) bindingSnapshot.set({ ...target }, id)
}
}
function beginMutation(source: BindingMutationSource): boolean {
if (interactionActive) return true
+ if (state.value === 'unresolved') return false
const startedUnbound = state.value === 'unbound'
const startedMixed = state.value === 'mixed'
if (!startedUnbound && !startedMixed && policy.value === 'readonly-when-bound') return false
@@ -136,18 +142,27 @@ function beginMutation(source: BindingMutationSource): boolean {
!startedUnbound &&
!startedMixed &&
policy.value === 'edit-variable' &&
- (!variable.value || !provider.setValue)
+ !provider.prepareEdit
) {
return false
}
+ interactionPolicy = policy.value
+ valueEdits = []
+ if (interactionPolicy === 'edit-variable' && !startedUnbound) {
+ const edits = prepareBindingEdits(provider, targets.value)
+ if (!edits) return false
+ valueEdits = edits
+ }
interactionActive = true
void source
if (!startedUnbound) snapshotBindings()
- resolvedSnapshot = resolvedValue.value
if (supportsInteractionBatch) beginProviderBatch(batchLabel)
- if (startedMixed || (!startedUnbound && policy.value === 'detach-on-edit')) {
+ if (
+ interactionPolicy !== 'edit-variable' &&
+ (startedMixed || (!startedUnbound && interactionPolicy === 'detach-on-edit'))
+ ) {
detachedForInteraction = true
for (const target of targets.value) provider.unbind(target)
}
@@ -155,10 +170,9 @@ function beginMutation(source: BindingMutationSource): boolean {
}
function applyValue(nextValue: V): boolean {
- if (policy.value !== 'edit-variable' || !interactionActive) return false
- const current = variable.value
- if (!current || !provider.setValue) return false
- provider.setValue(current.id, nextValue)
+ if (interactionPolicy !== 'edit-variable' || !interactionActive || !valueEdits.length)
+ return false
+ for (const edit of valueEdits) edit.set(nextValue)
return true
}
@@ -166,7 +180,7 @@ function resetInteraction() {
interactionActive = false
detachedForInteraction = false
bindingSnapshot.clear()
- resolvedSnapshot = undefined
+ valueEdits = []
}
function commitMutation() {
@@ -178,13 +192,8 @@ function commitMutation() {
function restoreWithoutRollback() {
if (detachedForInteraction) {
for (const [target, variableId] of bindingSnapshot) provider.bind(target, variableId)
- } else if (
- policy.value === 'edit-variable' &&
- variable.value &&
- resolvedSnapshot !== undefined &&
- provider.setValue
- ) {
- provider.setValue(variable.value.id, resolvedSnapshot)
+ } else if (interactionPolicy === 'edit-variable') {
+ for (const edit of valueEdits) edit.restore()
}
}
@@ -211,6 +220,7 @@ const actions: BindableValueActions<V> = {
const slotProps = computed<BindableValueSlotProps<V>>(() => ({
state: state.value,
+ bindingId: targets.value[0] ? provider.getBindingId(targets.value[0]) : undefined,
variable: variable.value,
resolvedValue: resolvedValue.value,
policy: policy.value,
diff --git a/packages/vue/src/primitives/BindableValue/demo/BindableValueDemo.vue b/packages/vue/src/primitives/BindableValue/demo/BindableValueDemo.vue
index f920ffb00..c094b9e58 100644
--- a/packages/vue/src/primitives/BindableValue/demo/BindableValueDemo.vue
+++ b/packages/vue/src/primitives/BindableValue/demo/BindableValueDemo.vue
@@ -58,6 +58,7 @@ const provider: BindingProvider<number> = {
listVariables: () => variables,
filterVariables: (term) =>
variables.filter((variable) => variable.name.toLowerCase().includes(term.toLowerCase())),
+ getBindingId: (target) => bindings.value[key(target)],
getBound: (target) => variables.find((variable) => variable.id === bindings.value[key(target)]),
getState(targets): BindingState {
const ids = new Set(targets.map((target) => bindings.value[key(target)]))
@@ -76,10 +77,22 @@ const provider: BindingProvider<number> = {
bindings.value[key(target)] = undefined
revision.value++
},
- setValue(variableId, value) {
+ prepareEdit(variableId) {
const variable = variables.find((item) => item.id === variableId)
- if (variable) variable.valuesByMode.default = value
- revision.value++
+ const value = variable?.valuesByMode.default
+ if (!variable || typeof value !== 'number') return undefined
+ return {
+ key: variableId,
+ value,
+ set(next: number) {
+ variable.valuesByMode.default = next
+ revision.value++
+ },
+ restore() {
+ variable.valuesByMode.default = value
+ revision.value++
+ }
+ }
},
create(target, value, name) {
const id = `created:${name}`
diff --git a/packages/vue/src/primitives/BindableValue/demo/ModeEditDemo.vue b/packages/vue/src/primitives/BindableValue/demo/ModeEditDemo.vue
new file mode 100644
index 000000000..d4e5e8e7e
--- /dev/null
+++ b/packages/vue/src/primitives/BindableValue/demo/ModeEditDemo.vue
@@ -0,0 +1,88 @@
+<script setup lang="ts">
+import { ref } from 'vue'
+
+import { createEditor } from '@open-pencil/core/editor'
+
+import { prepareModeEdit } from '#vue/controls/binding-provider/mode-edit'
+import { createOpenPencilBindingProvider } from '#vue/controls/binding-provider/open-pencil'
+import BindableValueRoot from '#vue/primitives/BindableValue/BindableValueRoot.vue'
+
+const editor = createEditor()
+const page = editor.graph.getPages()[0]
+if (!page) throw new Error('Missing demo page')
+const collection = editor.graph.createCollection('Spacing')
+editor.graph.addMode(collection.id, 'large', 'Large')
+editor.graph.addMode(collection.id, 'untouched', 'Untouched')
+const variable = editor.graph.createVariable('Space', 'FLOAT', collection.id, 8)
+editor.updateVariableValue(variable.id, 'large', 8)
+editor.updateVariableValue(variable.id, 'untouched', 40)
+const first = editor.graph.createNode('FRAME', page.id, {})
+const second = editor.graph.createNode('FRAME', page.id, {
+ variableModes: { [collection.id]: 'large' }
+})
+const other = editor.graph.createNode('FRAME', page.id, {
+ variableModes: { [collection.id]: 'untouched' }
+})
+for (const node of [first, second, other]) editor.bindVariable(node.id, 'width', variable.id)
+const revision = ref(0)
+const targets = ref([first, first, second].map((node) => ({ nodeId: node.id, path: 'width' })))
+const provider = createOpenPencilBindingProvider(
+ editor,
+ {
+ type: 'FLOAT',
+ resolve: (e, id, target) =>
+ target
+ ? e.graph.resolveNumberVariableForNode(target.nodeId, id)
+ : e.resolveNumberVariable(id),
+ prepareEdit: (e, id, target) =>
+ prepareModeEdit(e, id, target, () => e.graph.resolveNumberVariableForNode(target.nodeId, id))
+ },
+ revision
+)
+function changeTargets() {
+ editor.graph.updateNode(second.id, { variableModes: {} })
+ targets.value = [{ nodeId: other.id, path: 'width' }]
+ revision.value++
+}
+function values() {
+ void revision.value
+ return JSON.stringify(editor.getVariable(variable.id)?.valuesByMode ?? null)
+}
+function undo() {
+ editor.undo.undo()
+ revision.value++
+}
+function removeVariable() {
+ editor.graph.variables.delete(variable.id)
+ revision.value++
+}
+function refresh(action: () => unknown) {
+ action()
+ revision.value++
+}
+</script>
+
+<template>
+ <BindableValueRoot
+ v-slot="{ actions, state, bindingId }"
+ :provider="provider"
+ :targets="targets"
+ :value="8"
+ policy="edit-variable"
+ >
+ <div class="flex flex-wrap gap-2 bg-panel p-4 text-surface">
+ <button @click="actions.beginMutation('edit')">Begin edit</button>
+ <button @click="refresh(() => actions.applyValue(12))">Set 12</button>
+ <button @click="changeTargets">Change selection and mode</button>
+ <button @click="refresh(() => actions.applyValue(20))">Set 20</button>
+ <button @click="refresh(actions.cancelMutation)">Cancel</button>
+ <button @click="actions.commitMutation()">Commit</button>
+ <button @click="undo">Undo</button>
+ <button @click="removeVariable">Remove variable definition</button>
+ <button @click="refresh(actions.unbind)">Detach</button>
+ <output aria-label="Binding state">{{ state }}</output>
+ <output aria-label="Binding identity">{{ bindingId }}</output>
+ <output aria-label="Mode values">{{ values() }}</output>
+ </div>
+ </BindableValueRoot>
+</template>
diff --git a/packages/vue/src/primitives/BindableValue/types.ts b/packages/vue/src/primitives/BindableValue/types.ts
index e87f70ba4..0c8d5f5ca 100644
--- a/packages/vue/src/primitives/BindableValue/types.ts
+++ b/packages/vue/src/primitives/BindableValue/types.ts
@@ -27,6 +27,7 @@ export interface BindableValueRootProps<V = unknown> {
}
export interface BindableValueStateAttrs {
+ 'data-unresolved'?: ''
'data-unbound'?: ''
'data-bound'?: ''
'data-mixed'?: ''
@@ -50,6 +51,8 @@ export interface BindableValueActions<V = unknown> {
export interface BindableValueSlotProps<V = unknown> {
state: BindingState
+ /** Stored identity remains available when the variable has been deleted. */
+ bindingId: string | undefined
variable: Variable | undefined
resolvedValue: V | undefined
policy: BoundEditPolicy
diff --git a/packages/vue/src/primitives/Fill/demo/ColorFillDemo.vue b/packages/vue/src/primitives/Fill/demo/ColorFillDemo.vue
index b71db26aa..e1e33d832 100644
--- a/packages/vue/src/primitives/Fill/demo/ColorFillDemo.vue
+++ b/packages/vue/src/primitives/Fill/demo/ColorFillDemo.vue
@@ -46,6 +46,7 @@ const boundColor: Color = { r: 0.65, g: 0.3, b: 0.95, a: 1 }
const provider: BindingProvider<Color> = {
listVariables: () => [variable],
filterVariables: () => [variable],
+ getBindingId: () => variable.id,
getBound: () => variable,
getState: () => 'bound',
resolve: (variableId) => (variableId === variable.id ? boundColor : undefined),
diff --git a/packages/vue/src/primitives/NumberField/NumberFieldRoot.vue b/packages/vue/src/primitives/NumberField/NumberFieldRoot.vue
index eae37a3d6..e44a9c387 100644
--- a/packages/vue/src/primitives/NumberField/NumberFieldRoot.vue
+++ b/packages/vue/src/primitives/NumberField/NumberFieldRoot.vue
@@ -31,6 +31,7 @@ const {
max = Infinity,
step = 1,
sensitivity = 1,
+ inheritBinding = true,
placeholder = 'Mixed',
ariaLabel,
disabled: disabledProp = false,
@@ -40,7 +41,8 @@ const {
const emit = defineEmits<NumberFieldRootEmits>()
defineSlots<NumberFieldRootSlots>()
-const binding = useOptionalBindableValue<number>()
+const enclosingBinding = useOptionalBindableValue<number>()
+const binding = inheritBinding ? enclosingBinding : undefined
const editing = ref(false)
const scrubbing = ref(false)
const draftValue = ref('')
@@ -54,11 +56,14 @@ const numericValue = computed(() => {
if (binding?.state.value === 'bound' && typeof resolved === 'number') return resolved
return typeof modelValue === 'number' ? modelValue : 0
})
-const displayValue = computed(() =>
- isMixed.value ? '' : String(normalizeNumberValue(numericValue.value))
-)
+const displayValue = computed(() => {
+ if (binding?.state.value === 'unresolved') return '—'
+ return isMixed.value ? '' : String(normalizeNumberValue(numericValue.value))
+})
const disabled = computed(() => disabledProp)
-const bound = computed(() => (binding ? binding.state.value === 'bound' : boundProp))
+const bound = computed(() =>
+ binding ? binding.state.value === 'bound' || binding.state.value === 'unresolved' : boundProp
+)
const effectiveEditPolicy = computed<NumberFieldEditPolicy>(() => {
if (!binding) return editPolicy
if (binding.policy.value === 'readonly-when-bound') return 'readonly'
@@ -80,6 +85,7 @@ let scrubTarget: Element | undefined
let scrubPointerId: number | undefined
function canMutate(): boolean {
+ if (binding?.state.value === 'unresolved') return false
return !disabled.value && !(bound.value && effectiveEditPolicy.value === 'readonly')
}
@@ -315,7 +321,11 @@ const rootAttrs = computed<NumberFieldRootAttrs>(() => ({
...stateAttrs.value,
role: editing.value ? undefined : 'spinbutton',
tabindex: rootTabindex.value,
- 'aria-valuenow': editing.value || isMixed.value ? undefined : numericValue.value,
+ 'aria-valuenow':
+ editing.value || isMixed.value || binding?.state.value === 'unresolved'
+ ? undefined
+ : numericValue.value,
+ 'aria-readonly': binding?.state.value === 'unresolved' ? true : undefined,
'aria-valuemin': !editing.value && Number.isFinite(min) ? min : undefined,
'aria-valuemax': !editing.value && Number.isFinite(max) ? max : undefined,
'aria-disabled': !editing.value && disabled.value ? 'true' : undefined,
diff --git a/packages/vue/src/primitives/NumberField/types.ts b/packages/vue/src/primitives/NumberField/types.ts
index e42a46cf1..1a800ae54 100644
--- a/packages/vue/src/primitives/NumberField/types.ts
+++ b/packages/vue/src/primitives/NumberField/types.ts
@@ -23,6 +23,8 @@ export interface NumberFieldRootProps {
/** Prevents editing, scrubbing, and keyboard stepping. */
disabled?: boolean
/** Marks the value as controlled by an external binding. */
+ /** Consume the enclosing BindableValue context. Disable for independent sibling values. */
+ inheritBinding?: boolean
bound?: boolean
/** Mutation policy used when the value is bound. */
editPolicy?: NumberFieldEditPolicy
diff --git a/src/components/inputs/NumberField.vue b/src/components/inputs/NumberField.vue
index af8a12721..4d07b9a51 100644
--- a/src/components/inputs/NumberField.vue
+++ b/src/components/inputs/NumberField.vue
@@ -23,6 +23,7 @@ export interface NumberFieldProps {
sensitivity?: number
placeholder?: string
disabled?: boolean
+ inheritBinding?: boolean
bound?: boolean
editPolicy?: NumberFieldEditPolicy
ui?: NumberFieldUI
@@ -61,6 +62,7 @@ const {
sensitivity,
placeholder,
disabled,
+ inheritBinding = true,
bound,
editPolicy,
ui
@@ -93,6 +95,7 @@ defineOptions({ inheritAttrs: false })
:placeholder="placeholder ?? panels.mixed"
:aria-label="accessibleLabel"
:disabled="disabled"
+ :inherit-binding="inheritBinding"
:bound="bound"
:edit-policy="editPolicy"
@update:model-value="emit('update:modelValue', $event)"
@@ -118,14 +121,16 @@ defineOptions({ inheritAttrs: false })
actions.startScrub($event)
"
>
- <span :class="styles.leading({ class: ui?.leading })">
+ <span
+ v-if="editing || !slots.bound || rootAttrs['data-bound'] === undefined"
+ :class="styles.leading({ class: ui?.leading })"
+ >
<slot name="icon">
<span v-if="icon" class="text-[11px] leading-none">{{ icon }}</span>
</slot>
<span v-if="label" class="text-[11px] leading-none">{{ label }}</span>
</span>
<NumberFieldInput :class="styles.field({ class: ui?.field })" />
- <slot v-if="editing" name="suffix" />
<NumberFieldValue :class="styles.display({ class: ui?.display })">
<template #default="display">
<slot name="display" v-bind="display">
@@ -141,9 +146,18 @@ defineOptions({ inheritAttrs: false })
<span v-if="suffix" :class="styles.suffix({ class: ui?.suffix })">{{ suffix }}</span>
</template>
</slot>
- <slot name="suffix" />
</template>
</NumberFieldValue>
+ <span v-if="editing && suffix" :class="styles.suffix({ class: ui?.suffix })">{{
+ suffix
+ }}</span>
+ <span
+ v-if="slots.suffix"
+ data-slot="trailing"
+ :class="styles.trailing({ class: ui?.trailing })"
+ >
+ <slot name="suffix" />
+ </span>
</div>
</NumberFieldRoot>
</template>
diff --git a/src/components/properties/FillSection.vue b/src/components/properties/FillSection.vue
index ff0566abe..b6351cbcc 100644
--- a/src/components/properties/FillSection.vue
+++ b/src/components/properties/FillSection.vue
@@ -124,7 +124,10 @@ function updateSolidColor(
v-if="fill.type === 'SOLID'"
:color="fill.color"
:resolved-color="binding.resolvedValue"
- :variable-name="binding.variable?.name"
+ :variable-name="binding.variable?.name ?? binding.bindingId"
+ :unavailable-label="
+ binding.state === 'unresolved' ? panels.unresolvedVariable : undefined
+ "
:label="panels.fill"
@update="
updateSolidColor(binding.actions, flush, fill, $event, (next) =>
diff --git a/src/components/properties/TypographySection.vue b/src/components/properties/TypographySection.vue
index 6f7d7bc00..386c8497d 100644
--- a/src/components/properties/TypographySection.vue
+++ b/src/components/properties/TypographySection.vue
@@ -9,6 +9,7 @@ import FontPicker from '@/components/font-picker/FontPicker.vue'
import FontSettingsPopover from '@/components/FontSettings/FontSettingsPopover.vue'
import NumberField from '@/components/inputs/NumberField.vue'
import SharedStyleField from '@/components/properties/shared-style/SharedStyleField.vue'
+import LineHeightField from '@/components/properties/typography/LineHeightField.vue'
import VariableNumberField from '@/components/properties/VariableNumberField.vue'
import IconButton from '@/components/ui/button/IconButton.vue'
import Tip from '@/components/ui/overlay/Tip.vue'
@@ -113,25 +114,15 @@ function featureEnabled(features: Array<{ tag: string; enabled: boolean }>, tag:
<PanelGrid :columns="2" class="mb-3">
<PanelFieldGroup :label="panels.lineHeight">
- <VariableNumberField
- :model-value="
- ctx.node.value.lineHeight ?? Math.round((ctx.node.value.fontSize || 14) * 1.2)
- "
- :aria-label="panels.lineHeight"
- :min="0"
- :node-id="ctx.node.value.id"
- binding-path="lineHeight"
- @update:model-value="ctx.actions.updateProp('lineHeight', $event)"
- @commit="(v: number, p: number) => ctx.actions.commitProp('lineHeight', v, p)"
- >
- <template #icon>
- <icon-lucide-baseline class="size-3" />
- </template>
- </VariableNumberField>
+ <LineHeightField
+ :node="ctx.node.value"
+ @update="ctx.actions.updateProp('lineHeight', $event)"
+ @commit="(v, p) => ctx.actions.commitProp('lineHeight', v, p)"
+ />
</PanelFieldGroup>
<PanelFieldGroup :label="panels.letterSpacing">
<VariableNumberField
- suffix="%"
+ suffix="px"
:model-value="ctx.node.value.letterSpacing"
:aria-label="panels.letterSpacing"
:node-id="ctx.node.value.id"
@@ -146,145 +137,152 @@ function featureEnabled(features: Array<{ tag: string; enabled: boolean }>, tag:
</PanelFieldGroup>
</PanelGrid>
- <PanelFieldGroup :label="panels.direction" class="mb-3">
- <AppSelect
- :label="panels.direction"
- :model-value="ctx.node.value.textDirection"
- :options="[
- { value: 'AUTO', label: panels.auto },
- { value: 'LTR', label: 'LTR' },
- { value: 'RTL', label: 'RTL' }
- ]"
- @update:model-value="ctx.actions.setDirection($event as 'AUTO' | 'LTR' | 'RTL')"
- />
- </PanelFieldGroup>
+ <div class="border-t border-border pt-3">
+ <PanelFieldGroup :label="panels.direction" class="mb-3">
+ <AppSelect
+ :label="panels.direction"
+ :model-value="ctx.node.value.textDirection"
+ :options="[
+ { value: 'AUTO', label: panels.auto },
+ { value: 'LTR', label: 'LTR' },
+ { value: 'RTL', label: 'RTL' }
+ ]"
+ @update:model-value="ctx.actions.setDirection($event as 'AUTO' | 'LTR' | 'RTL')"
+ />
+ </PanelFieldGroup>
- <PanelFieldGroup :label="panels.textAlignment" class="mb-3">
- <SegmentedControl
- :model-value="ctx.node.value.textAlignHorizontal"
- :options="alignmentOptions"
- :label="panels.textAlignment"
- @change="ctx.actions.align($event as 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED')"
- >
- <template #option="{ option }">
- <icon-lucide-align-left v-if="option.value === 'LEFT'" class="size-3.5" />
- <icon-lucide-align-center v-else-if="option.value === 'CENTER'" class="size-3.5" />
- <icon-lucide-align-right v-else-if="option.value === 'RIGHT'" class="size-3.5" />
- <icon-lucide-align-justify v-else class="size-3.5" />
- </template>
- </SegmentedControl>
- </PanelFieldGroup>
+ <PanelFieldGroup :label="panels.textAlignment" class="mb-3">
+ <SegmentedControl
+ :model-value="ctx.node.value.textAlignHorizontal"
+ :options="alignmentOptions"
+ :label="panels.textAlignment"
+ @change="ctx.actions.align($event as 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED')"
+ >
+ <template #option="{ option }">
+ <icon-lucide-align-left v-if="option.value === 'LEFT'" class="size-3.5" />
+ <icon-lucide-align-center v-else-if="option.value === 'CENTER'" class="size-3.5" />
+ <icon-lucide-align-right v-else-if="option.value === 'RIGHT'" class="size-3.5" />
+ <icon-lucide-align-justify v-else class="size-3.5" />
+ </template>
+ </SegmentedControl>
+ </PanelFieldGroup>
+
+ <PanelFieldGroup :label="panels.verticalTextAlignment" class="mb-3">
+ <SegmentedControl
+ :model-value="ctx.node.value.textAlignVertical"
+ :options="verticalAlignmentOptions"
+ :label="panels.verticalTextAlignment"
+ @change="ctx.actions.setVerticalAlign($event as 'TOP' | 'CENTER' | 'BOTTOM')"
+ >
+ <template #option="{ option }">
+ <icon-lucide-align-vertical-justify-start
+ v-if="option.value === 'TOP'"
+ class="size-3.5"
+ />
+ <icon-lucide-align-vertical-justify-center
+ v-else-if="option.value === 'CENTER'"
+ class="size-3.5"
+ />
+ <icon-lucide-align-vertical-justify-end v-else class="size-3.5" />
+ </template>
+ </SegmentedControl>
+ </PanelFieldGroup>
+ </div>
- <PanelFieldGroup :label="panels.verticalTextAlignment" class="mb-3">
- <SegmentedControl
- :model-value="ctx.node.value.textAlignVertical"
- :options="verticalAlignmentOptions"
- :label="panels.verticalTextAlignment"
- @change="ctx.actions.setVerticalAlign($event as 'TOP' | 'CENTER' | 'BOTTOM')"
+ <div class="border-t border-border pt-3">
+ <PanelFieldGroup
+ :label="panels.textFormatting"
+ class="mb-3"
+ :ui="{ container: 'flex-row gap-1.5' }"
>
- <template #option="{ option }">
- <icon-lucide-align-vertical-justify-start
- v-if="option.value === 'TOP'"
- class="size-3.5"
+ <div
+ class="inline-flex items-center gap-0.5 rounded bg-panel-field p-0.5 hover:bg-panel-field-hover"
+ role="toolbar"
+ :aria-label="panels.textFormatting"
+ >
+ <IconButton
+ :label="`${menu.bold} (${appMenuShortcutLabel('text.bold')})`"
+ size="xs"
+ :active="ctx.activeFormatting.value.includes('bold')"
+ @click="ctx.actions.toggleBold"
+ >
+ <icon-lucide-bold class="size-3.5" />
+ </IconButton>
+ <IconButton
+ :label="`${menu.italic} (${appMenuShortcutLabel('text.italic')})`"
+ size="xs"
+ :active="ctx.activeFormatting.value.includes('italic')"
+ @click="ctx.actions.toggleItalic"
+ >
+ <icon-lucide-italic class="size-3.5" />
+ </IconButton>
+ <IconButton
+ :label="`${menu.underline} (${appMenuShortcutLabel('text.underline')})`"
+ size="xs"
+ :active="ctx.activeFormatting.value.includes('underline')"
+ @click="ctx.actions.toggleDecoration('UNDERLINE')"
+ >
+ <icon-lucide-underline class="size-3.5" />
+ </IconButton>
+ <IconButton
+ :label="menu.strikethrough"
+ size="xs"
+ :active="ctx.activeFormatting.value.includes('strikethrough')"
+ @click="ctx.actions.toggleDecoration('STRIKETHROUGH')"
+ >
+ <icon-lucide-strikethrough class="size-3.5" />
+ </IconButton>
+ </div>
+ </PanelFieldGroup>
+
+ <PanelGrid :columns="2" class="mb-3">
+ <PanelFieldGroup :label="panels.textCase">
+ <AppSelect
+ :label="panels.textCase"
+ :model-value="ctx.node.value.textCase"
+ :options="textCaseOptions"
+ @update:model-value="
+ ctx.actions.setTextCase($event as 'ORIGINAL' | 'UPPER' | 'LOWER' | 'TITLE')
+ "
/>
- <icon-lucide-align-vertical-justify-center
- v-else-if="option.value === 'CENTER'"
- class="size-3.5"
+ </PanelFieldGroup>
+ <PanelFieldGroup :label="panels.truncation">
+ <AppSelect
+ :label="panels.truncation"
+ :model-value="ctx.node.value.textTruncation"
+ :options="truncationOptions"
+ @update:model-value="ctx.actions.setTruncation($event as 'DISABLED' | 'ENDING')"
/>
- <icon-lucide-align-vertical-justify-end v-else class="size-3.5" />
- </template>
- </SegmentedControl>
- </PanelFieldGroup>
+ </PanelFieldGroup>
+ </PanelGrid>
- <PanelFieldGroup
- :label="panels.textFormatting"
- class="mb-3"
- :ui="{ container: 'flex-row gap-1.5' }"
- >
- <div
- class="inline-flex items-center gap-0.5 rounded bg-panel-field p-0.5 hover:bg-panel-field-hover"
- role="toolbar"
- :aria-label="panels.textFormatting"
+ <PanelFieldGroup
+ v-if="ctx.node.value.textTruncation === 'ENDING'"
+ :label="panels.maxLines"
+ class="mb-3"
>
- <IconButton
- :label="`${menu.bold} (${appMenuShortcutLabel('text.bold')})`"
- size="xs"
- :active="ctx.activeFormatting.value.includes('bold')"
- @click="ctx.actions.toggleBold"
- >
- <icon-lucide-bold class="size-3.5" />
- </IconButton>
- <IconButton
- :label="`${menu.italic} (${appMenuShortcutLabel('text.italic')})`"
- size="xs"
- :active="ctx.activeFormatting.value.includes('italic')"
- @click="ctx.actions.toggleItalic"
- >
- <icon-lucide-italic class="size-3.5" />
- </IconButton>
- <IconButton
- :label="`${menu.underline} (${appMenuShortcutLabel('text.underline')})`"
- size="xs"
- :active="ctx.activeFormatting.value.includes('underline')"
- @click="ctx.actions.toggleDecoration('UNDERLINE')"
- >
- <icon-lucide-underline class="size-3.5" />
- </IconButton>
- <IconButton
- :label="menu.strikethrough"
- size="xs"
- :active="ctx.activeFormatting.value.includes('strikethrough')"
- @click="ctx.actions.toggleDecoration('STRIKETHROUGH')"
- >
- <icon-lucide-strikethrough class="size-3.5" />
- </IconButton>
- </div>
- </PanelFieldGroup>
-
- <PanelGrid :columns="2" class="mb-3">
- <PanelFieldGroup :label="panels.textCase">
- <AppSelect
- :label="panels.textCase"
- :model-value="ctx.node.value.textCase"
- :options="textCaseOptions"
+ <NumberField
+ :model-value="ctx.node.value.maxLines ?? 1"
+ :aria-label="panels.maxLines"
+ :min="1"
+ :step="1"
+ data-property="max-lines"
@update:model-value="
- ctx.actions.setTextCase($event as 'ORIGINAL' | 'UPPER' | 'LOWER' | 'TITLE')
+ ctx.actions.updateProp('maxLines', Math.max(1, Math.round($event)))
+ "
+ @commit="
+ (value: number, previous: number) =>
+ ctx.actions.commitProp('maxLines', value, previous)
"
/>
</PanelFieldGroup>
- <PanelFieldGroup :label="panels.truncation">
- <AppSelect
- :label="panels.truncation"
- :model-value="ctx.node.value.textTruncation"
- :options="truncationOptions"
- @update:model-value="ctx.actions.setTruncation($event as 'DISABLED' | 'ENDING')"
- />
- </PanelFieldGroup>
- </PanelGrid>
-
- <PanelFieldGroup
- v-if="ctx.node.value.textTruncation === 'ENDING'"
- :label="panels.maxLines"
- class="mb-3"
- >
- <NumberField
- :model-value="ctx.node.value.maxLines ?? 1"
- :aria-label="panels.maxLines"
- :min="1"
- :step="1"
- data-property="max-lines"
- @update:model-value="ctx.actions.updateProp('maxLines', Math.max(1, Math.round($event)))"
- @commit="
- (value: number, previous: number) => ctx.actions.commitProp('maxLines', value, previous)
- "
- />
- </PanelFieldGroup>
+ </div>
- <div class="mb-3 grid gap-2.5">
+ <div class="grid gap-2.5 border-t border-border pt-3">
<label
v-for="feature in commonFeatures"
:key="feature.tag"
- class="flex items-center justify-between gap-1.5 text-[11px] text-muted/70"
+ class="flex items-center justify-between gap-1.5 text-[11px] text-muted"
>
<span>{{ feature.label }}</span>
<AppSwitch
diff --git a/src/components/properties/VariableNumberField.vue b/src/components/properties/VariableNumberField.vue
index 0b13c5bb3..fa6ac15c7 100644
--- a/src/components/properties/VariableNumberField.vue
+++ b/src/components/properties/VariableNumberField.vue
@@ -84,10 +84,18 @@ defineOptions({ inheritAttrs: false })
<template v-if="$slots.icon" #icon>
<slot name="icon" />
</template>
- <template v-if="binding.variable" #bound>
+ <template v-if="$slots.display" #display="display">
+ <slot name="display" v-bind="display" />
+ </template>
+ <template v-if="binding.variable || binding.state === 'unresolved'" #bound>
<BindingPill
- :label="binding.variable.name"
- :tooltip="bindingTooltip(binding.variable.name, binding.resolvedValue)"
+ :unresolved="binding.state === 'unresolved'"
+ :label="binding.variable?.name ?? binding.bindingId ?? panels.unresolvedVariable"
+ :tooltip="
+ binding.state === 'unresolved'
+ ? panels.unresolvedVariable
+ : bindingTooltip(binding.variable?.name ?? '', binding.resolvedValue)
+ "
/>
</template>
<template #suffix>
diff --git a/src/components/properties/binding/BindingField.stories.ts b/src/components/properties/binding/BindingField.stories.ts
index 57c36e06f..3d688e857 100644
--- a/src/components/properties/binding/BindingField.stories.ts
+++ b/src/components/properties/binding/BindingField.stories.ts
@@ -4,7 +4,7 @@ import { expect, userEvent, within } from 'storybook/test'
import BindingFieldDemo from './demo/BindingFieldDemo.vue'
const meta = {
- title: 'Design System/Properties/Binding Field',
+ title: 'Editor/Properties/Binding Field',
component: BindingFieldDemo,
tags: ['autodocs'],
parameters: {
@@ -20,6 +20,8 @@ const meta = {
export default meta
type Story = StoryObj<typeof meta>
+export const PickerActions: Story = {}
+
export const StateMatrix: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement)
diff --git a/src/components/properties/binding/VariableBindingPicker.vue b/src/components/properties/binding/VariableBindingPicker.vue
index f70898d02..b6cb8b7d2 100644
--- a/src/components/properties/binding/VariableBindingPicker.vue
+++ b/src/components/properties/binding/VariableBindingPicker.vue
@@ -32,6 +32,7 @@ import { computed, nextTick, ref, watch } from 'vue'
import { BindableValuePicker, useBindableValue } from '@open-pencil/vue'
import { BindingTrigger, useBindingFieldUI } from '@/components/ui/binding'
+import AppButton from '@/components/ui/button/AppButton.vue'
import Tip from '@/components/ui/overlay/Tip.vue'
const {
@@ -157,16 +158,16 @@ defineOptions({ inheritAttrs: false })
</ComboboxViewport>
<div :class="styles.pickerFooter" data-slot="footer">
- <button
- v-if="picker.state === 'bound'"
- type="button"
- :class="styles.pickerAction"
+ <AppButton
+ v-if="picker.state !== 'unbound'"
+ size="xs"
+ class="w-full justify-start"
data-slot="action"
@click="detach"
>
- <icon-lucide-unlink class="size-3" />
- <span>{{ detachLabel }}</span>
- </button>
+ <template #leading><icon-lucide-unlink class="size-3" /></template>
+ {{ detachLabel }}
+ </AppButton>
<form
v-if="creating"
@@ -182,25 +183,26 @@ defineOptions({ inheritAttrs: false })
:class="styles.createInput"
data-slot="createInput"
/>
- <button
+ <AppButton
+ size="xs"
+ variant="soft"
:disabled="!canCreate"
- :class="styles.createSubmit"
data-slot="createSubmit"
type="submit"
>
{{ createSubmitLabel }}
- </button>
+ </AppButton>
</form>
- <button
+ <AppButton
v-else-if="createLabel"
- type="button"
- :class="styles.pickerAction"
+ size="xs"
+ class="w-full justify-start"
data-slot="action"
@click="startCreate"
>
- <icon-lucide-plus class="size-3" />
+ <template #leading><icon-lucide-plus class="size-3" /></template>
<span class="min-w-0 flex-1 truncate">{{ createLabel }}</span>
- </button>
+ </AppButton>
</div>
</ComboboxContent>
</ComboboxPortal>
diff --git a/src/components/properties/binding/demo/BindingFieldDemo.vue b/src/components/properties/binding/demo/BindingFieldDemo.vue
index 31ca5300f..057d3aae6 100644
--- a/src/components/properties/binding/demo/BindingFieldDemo.vue
+++ b/src/components/properties/binding/demo/BindingFieldDemo.vue
@@ -65,6 +65,7 @@ const provider: BindingProvider<number> = {
listVariables: () => variables,
filterVariables: (term) =>
variables.filter((variable) => variable.name.toLowerCase().includes(term.toLowerCase())),
+ getBindingId: (target) => bindings.value[key(target)],
getBound: (target) => variables.find((variable) => variable.id === bindings.value[key(target)]),
getState(targets): BindingState {
const ids = new Set(targets.map((target) => bindings.value[key(target)]))
@@ -83,10 +84,22 @@ const provider: BindingProvider<number> = {
bindings.value[key(target)] = undefined
revision.value++
},
- setValue(variableId, value) {
+ prepareEdit(variableId) {
const variable = variables.find((item) => item.id === variableId)
- if (variable) variable.valuesByMode.default = value
- revision.value++
+ const value = variable?.valuesByMode.default
+ if (!variable || typeof value !== 'number') return undefined
+ return {
+ key: variableId,
+ value,
+ set(next: number) {
+ variable.valuesByMode.default = next
+ revision.value++
+ },
+ restore() {
+ variable.valuesByMode.default = value
+ revision.value++
+ }
+ }
},
create(target, value, name) {
const id = `created:${name}`
diff --git a/src/components/properties/paint/PaintField.vue b/src/components/properties/paint/PaintField.vue
index a0699ac31..25e1fb9cb 100644
--- a/src/components/properties/paint/PaintField.vue
+++ b/src/components/properties/paint/PaintField.vue
@@ -48,6 +48,7 @@ const styles = computed(() => tv(paintFieldTheme)())
</div>
<div :class="styles.divider({ class: ui?.divider })" data-slot="divider" />
<NumberField
+ :inherit-binding="false"
:class="styles.opacity({ class: ui?.opacity })"
:aria-label="opacityLabel"
suffix="%"
diff --git a/src/components/properties/paint/PaintValue.vue b/src/components/properties/paint/PaintValue.vue
index 307d297ef..230cef036 100644
--- a/src/components/properties/paint/PaintValue.vue
+++ b/src/components/properties/paint/PaintValue.vue
@@ -6,9 +6,10 @@ import { inputValue, useColorModel } from '@open-pencil/vue'
import { BindingPill } from '@/components/ui/binding'
-const { color, resolvedColor, variableName, label } = defineProps<{
+const { color, resolvedColor, variableName, unavailableLabel, label } = defineProps<{
color: Color
resolvedColor?: Color
+ unavailableLabel?: string
variableName?: string
label: string
}>()
@@ -24,10 +25,11 @@ const tooltip = computed(() => (variableName ? `${variableName} · #${model.hex.
<template>
<BindingPill
- v-if="variableName"
+ v-if="variableName || unavailableLabel"
class="min-w-0 flex-1"
- :label="variableName"
- :tooltip="tooltip"
+ :label="variableName ?? unavailableLabel ?? label"
+ :unresolved="!!unavailableLabel"
+ :tooltip="unavailableLabel ?? tooltip"
/>
<input
v-else
diff --git a/src/components/properties/stroke/StrokeSection.vue b/src/components/properties/stroke/StrokeSection.vue
index 1c88a0ab2..ff87bd81b 100644
--- a/src/components/properties/stroke/StrokeSection.vue
+++ b/src/components/properties/stroke/StrokeSection.vue
@@ -148,7 +148,10 @@ function onToggleSides(activeNode: SceneNode | null) {
<PaintValue
:color="stroke.color"
:resolved-color="binding.resolvedValue"
- :variable-name="binding.variable?.name"
+ :variable-name="binding.variable?.name ?? binding.bindingId"
+ :unavailable-label="
+ binding.state === 'unresolved' ? panels.unresolvedVariable : undefined
+ "
:label="panels.stroke"
@update="
updateStrokeColor(
diff --git a/src/components/properties/typography/LineHeightField.vue b/src/components/properties/typography/LineHeightField.vue
new file mode 100644
index 000000000..c52adba39
--- /dev/null
+++ b/src/components/properties/typography/LineHeightField.vue
@@ -0,0 +1,76 @@
+<script setup lang="ts">
+import {
+ SelectRoot,
+ SelectTrigger,
+ SelectPortal,
+ SelectContent,
+ SelectViewport,
+ SelectItem,
+ SelectItemText
+} from 'reka-ui'
+import { computed } from 'vue'
+
+import type { SceneNode } from '@open-pencil/scene-graph'
+import { useEditor, useI18n } from '@open-pencil/vue'
+
+import VariableNumberField from '@/components/properties/VariableNumberField.vue'
+import { useSelectUI } from '@/components/ui/select/select'
+
+const { node } = defineProps<{ node: SceneNode }>()
+const emit = defineEmits<{ update: [value: number]; commit: [value: number, previous: number] }>()
+const editor = useEditor()
+const { panels } = useI18n()
+const automatic = computed(() => node.lineHeight == null && !node.boundVariables.lineHeight)
+const value = computed(() => node.lineHeight ?? Math.round((node.fontSize || 14) * 1.2))
+const menu = useSelectUI()
+function setMode(mode: string) {
+ if (mode === 'AUTO') {
+ editor.undo.runBatch('Use automatic line height', () => {
+ if (node.boundVariables.lineHeight) editor.unbindVariable(node.id, 'lineHeight')
+ editor.updateNodeWithUndo(node.id, { lineHeight: null }, 'Use automatic line height')
+ })
+ } else if (mode === 'FIXED' && automatic.value) {
+ editor.updateNodeWithUndo(node.id, { lineHeight: value.value }, 'Set line height')
+ }
+}
+</script>
+
+<template>
+ <VariableNumberField
+ :model-value="value"
+ :aria-label="panels.lineHeight"
+ suffix="px"
+ :min="0"
+ :node-id="node.id"
+ binding-path="lineHeight"
+ @update:model-value="emit('update', $event)"
+ @commit="(current, previous) => emit('commit', current, previous)"
+ >
+ <template #icon><icon-lucide-baseline class="size-3" /></template>
+ <template v-if="automatic" #display
+ ><span class="min-w-0 flex-1 truncate text-surface">{{ panels.auto }}</span></template
+ >
+ <template #after-variable>
+ <SelectRoot :model-value="automatic ? 'AUTO' : 'FIXED'" @update:model-value="setMode">
+ <SelectTrigger
+ :aria-label="panels.lineHeightMode"
+ class="flex shrink-0 items-center self-stretch px-1 text-muted"
+ @pointerdown.stop
+ ><icon-lucide-chevron-down class="size-3"
+ /></SelectTrigger>
+ <SelectPortal>
+ <SelectContent position="popper" :side-offset="4" :class="menu.content">
+ <SelectViewport>
+ <SelectItem value="AUTO" :class="menu.item"
+ ><SelectItemText>{{ panels.auto }}</SelectItemText></SelectItem
+ >
+ <SelectItem value="FIXED" :class="menu.item"
+ ><SelectItemText>{{ panels.sizingFixed }}</SelectItemText></SelectItem
+ >
+ </SelectViewport>
+ </SelectContent>
+ </SelectPortal>
+ </SelectRoot>
+ </template>
+ </VariableNumberField>
+</template>
diff --git a/src/components/ui/binding/BindingPill.vue b/src/components/ui/binding/BindingPill.vue
index bd7437f2d..968b966fa 100644
--- a/src/components/ui/binding/BindingPill.vue
+++ b/src/components/ui/binding/BindingPill.vue
@@ -6,6 +6,7 @@ import type { BindingFieldUI } from './ui'
export interface BindingPillProps {
label: string
tooltip?: string
+ unresolved?: boolean
disabled?: boolean
derived?: boolean
class?: HTMLAttributes['class']
@@ -22,6 +23,7 @@ import Tip from '@/components/ui/overlay/Tip.vue'
const {
label,
tooltip,
+ unresolved = false,
disabled = false,
derived = false,
class: className,
@@ -30,7 +32,7 @@ const {
const styles = computed(() =>
useBindingFieldUI(
- { state: 'bound', disabled, derived },
+ { state: unresolved ? 'unresolved' : 'bound', disabled, derived },
{ ...ui, pill: [ui?.pill, normalizeClass(className)].filter(Boolean).join(' ') }
)
)
@@ -43,6 +45,8 @@ defineOptions({ inheritAttrs: false })
<span
v-bind="$attrs"
:class="styles.pill"
+ :data-unresolved="unresolved ? '' : undefined"
+ :aria-label="unresolved ? (tooltip ? `${label}: ${tooltip}` : label) : undefined"
:data-disabled="disabled ? '' : undefined"
:data-derived="derived ? '' : undefined"
data-slot="pill"
diff --git a/src/components/ui/binding/ui.ts b/src/components/ui/binding/ui.ts
index 9aa263108..21bf94767 100644
--- a/src/components/ui/binding/ui.ts
+++ b/src/components/ui/binding/ui.ts
@@ -31,9 +31,7 @@ export function useBindingFieldUI(options: BindingFieldUIOptions = {}, ui?: Bind
pickerItemIndicator: styles.pickerItemIndicator({ class: ui?.pickerItemIndicator }),
pickerEmpty: styles.pickerEmpty({ class: ui?.pickerEmpty }),
pickerFooter: styles.pickerFooter({ class: ui?.pickerFooter }),
- pickerAction: styles.pickerAction({ class: ui?.pickerAction }),
createForm: styles.createForm({ class: ui?.createForm }),
- createInput: styles.createInput({ class: ui?.createInput }),
- createSubmit: styles.createSubmit({ class: ui?.createSubmit })
+ createInput: styles.createInput({ class: ui?.createInput })
}
}
diff --git a/src/theme/binding/field.ts b/src/theme/binding/field.ts
index 075070d7f..11c4c3ae2 100644
--- a/src/theme/binding/field.ts
+++ b/src/theme/binding/field.ts
@@ -17,13 +17,9 @@ const bindingFieldTheme = {
pickerItemIndicator: 'flex size-3 shrink-0 items-center justify-center text-component',
pickerEmpty: 'px-2 py-3 text-center text-[11px] text-muted',
pickerFooter: 'border-t border-border p-1',
- pickerAction:
- 'flex h-6 w-full cursor-pointer items-center gap-2 rounded border-0 bg-transparent px-2 text-left text-[11px] text-muted outline-none hover:bg-hover hover:text-surface focus-visible:border-panel-focus',
createForm: 'flex items-center gap-1.5 p-1',
createInput:
- 'h-6 min-w-0 flex-1 rounded border border-transparent bg-panel-field px-2 text-[11px] text-surface outline-none placeholder:text-muted focus:border-panel-focus',
- createSubmit:
- 'h-6 shrink-0 rounded border border-transparent bg-panel-field px-2 text-[11px] text-surface outline-none hover:bg-panel-field-hover focus-visible:border-panel-focus disabled:cursor-not-allowed disabled:opacity-50'
+ 'h-6 min-w-0 flex-1 rounded border border-transparent bg-panel-field px-2 text-[11px] text-surface outline-none placeholder:text-muted focus:border-panel-focus'
},
variants: {
state: {
@@ -31,6 +27,7 @@ const bindingFieldTheme = {
bound: {
trigger: 'text-component opacity-100'
},
+ unresolved: { trigger: 'text-error opacity-100', pill: 'text-error' },
mixed: {}
},
open: {
diff --git a/src/theme/input/number-field.ts b/src/theme/input/number-field.ts
index a8e72b84a..bd74f1dab 100644
--- a/src/theme/input/number-field.ts
+++ b/src/theme/input/number-field.ts
@@ -10,9 +10,10 @@ const numberFieldTheme = {
'flex shrink-0 items-center justify-center self-stretch px-[5px] text-muted select-none [&>*]:pointer-events-none',
field:
'min-w-0 flex-1 cursor-text border-none bg-transparent pr-1.5 font-[inherit] text-[11px] text-surface outline-none',
- display: 'flex flex-1 items-center truncate overflow-hidden text-[11px] select-none',
+ display: 'flex min-w-0 flex-1 items-center overflow-hidden text-[11px] select-none',
mixed: 'flex-1 text-muted',
- value: 'flex-1 text-surface',
+ value: 'min-w-0 flex-1 truncate text-surface',
+ trailing: 'flex shrink-0 items-center self-stretch',
suffix: 'shrink-0 pr-1.5 text-muted'
},
variants: {
diff --git a/src/theme/paint/field.ts b/src/theme/paint/field.ts
index 29aaaa112..f040f80fe 100644
--- a/src/theme/paint/field.ts
+++ b/src/theme/paint/field.ts
@@ -4,7 +4,7 @@ export default {
preview: 'flex shrink-0 items-center pl-1',
value: 'flex min-w-0 flex-1 items-center pl-1.5 pr-1',
divider: 'h-4 w-px shrink-0 bg-muted/40',
- opacity: 'h-full w-12 flex-none shrink-0',
+ opacity: 'h-full w-14 flex-none shrink-0',
binding: 'flex shrink-0 items-center pr-0.5'
}
} as const
diff --git a/tests/e2e/properties/dimensions.spec.ts b/tests/e2e/properties/dimensions.spec.ts
new file mode 100644
index 000000000..5d6d325a8
--- /dev/null
+++ b/tests/e2e/properties/dimensions.spec.ts
@@ -0,0 +1,59 @@
+import { expect, test } from '@playwright/test'
+
+import { CanvasHelper } from '#tests/helpers/canvas'
+
+for (const theme of ['light', 'dark']) {
+ test.describe(`dimension fields in ${theme}`, () => {
+ test.use({
+ storageState: async ({ baseURL }, use) => {
+ if (!baseURL) throw new Error('Dimensions tests require a baseURL')
+ await use({
+ cookies: [],
+ origins: [
+ {
+ origin: new URL(baseURL).origin,
+ localStorage: [{ name: 'open-pencil:theme', value: theme }]
+ }
+ ]
+ })
+ }
+ })
+ test('values and long variable bindings share space with sizing controls', async ({ page }) => {
+ await page.goto('/?test')
+ await new CanvasHelper(page).waitForInit()
+ await page.evaluate(() => {
+ const editor = window.openPencil?.getStore?.()
+ if (!editor) throw new Error('Editor unavailable')
+ const id = editor.createShape('FRAME', 0, 0, 12345, 6789)
+ editor.select([id])
+ })
+ const section = page.getByRole('region', { name: 'Layout', exact: true })
+ const width = section.locator('[data-property="width"]')
+ await expect(width).toContainText('12345')
+ await expect(section.locator('[data-property="height"]')).toContainText('6789')
+ for (const axis of ['width', 'height']) {
+ const value = section
+ .locator(`[data-property="${axis}"] [data-slot="value"] > span`)
+ .first()
+ await expect(value).toBeVisible()
+ await expect
+ .poll(() => value.evaluate((element) => element.scrollWidth <= element.clientWidth))
+ .toBe(true)
+ }
+ await width.getByRole('button', { name: 'Apply variable' }).click()
+ await page
+ .getByRole('button', { name: 'Create number variable from 12345', exact: true })
+ .click()
+ await page
+ .getByPlaceholder('Variable name')
+ .fill('Dimensions/Content/Maximum comfortable width')
+ await page.getByRole('button', { name: 'Create', exact: true }).click()
+ await expect(width).toHaveAttribute('data-bound')
+ if (theme === 'light') await expect(section).toHaveScreenshot('dimensions-bound-light.png')
+ await width.getByRole('combobox', { name: 'Width', exact: true }).click()
+ await expect(page.getByRole('option', { name: 'Fixed', exact: true })).toBeVisible()
+ await page.keyboard.press('Escape')
+ await expect(width).toHaveAttribute('data-bound')
+ })
+ })
+}
diff --git a/tests/e2e/properties/dimensions.spec.ts-snapshots/dimensions-bound-light-openpencil-darwin.png b/tests/e2e/properties/dimensions.spec.ts-snapshots/dimensions-bound-light-openpencil-darwin.png
new file mode 100644
index 000000000..82e4bd1a6
Binary files /dev/null and b/tests/e2e/properties/dimensions.spec.ts-snapshots/dimensions-bound-light-openpencil-darwin.png differ
diff --git a/tests/e2e/properties/line-height.spec.ts b/tests/e2e/properties/line-height.spec.ts
new file mode 100644
index 000000000..bca251042
--- /dev/null
+++ b/tests/e2e/properties/line-height.spec.ts
@@ -0,0 +1,61 @@
+import { expect, test } from '@playwright/test'
+
+import { CanvasHelper } from '#tests/helpers/canvas'
+
+test('automatic line height survives focus and can be restored with undo', async ({ page }) => {
+ await page.setViewportSize({ width: 1280, height: 1200 })
+ await page.goto('/?test')
+ await new CanvasHelper(page).waitForInit()
+ const id = await page.evaluate(() => {
+ const e = window.openPencil?.getStore?.()
+ if (!e) throw new Error('No editor')
+ const id = e.createShape('TEXT', 100, 100, 240, 80)
+ e.updateNode(id, { text: 'Line height', fontSize: 24, lineHeight: null })
+ e.select([id])
+ return id
+ })
+ const field = page.locator('[data-property="lineHeight"]')
+ await expect(field).toContainText('Auto')
+
+ await page.evaluate((id) => window.openPencil?.getStore?.().updateNode(id, { fontSize: 30 }), id)
+ const input = page.getByRole('spinbutton', { name: 'Line height', exact: true })
+ await input.focus()
+ await expect(input).toHaveValue('36')
+ await input.press('Escape')
+ await expect
+ .poll(() =>
+ page.evaluate((id) => window.openPencil?.getStore?.().graph.getNode(id)?.lineHeight, id)
+ )
+ .toBeNull()
+ await input.focus()
+ await input.fill('32')
+ await input.press('Enter')
+ await expect
+ .poll(() =>
+ page.evaluate((id) => window.openPencil?.getStore?.().graph.getNode(id)?.lineHeight, id)
+ )
+ .toBe(32)
+ await page.getByRole('combobox', { name: 'Line height mode' }).click()
+ await page.getByRole('option', { name: 'Auto', exact: true }).click()
+ await expect(field).toContainText('Auto')
+ await page.getByRole('heading', { name: 'Typography', exact: true }).click()
+ await page.keyboard.press(process.platform === 'darwin' ? 'Meta+z' : 'Control+z')
+ await expect
+ .poll(() =>
+ page.evaluate((id) => window.openPencil?.getStore?.().graph.getNode(id)?.lineHeight, id)
+ )
+ .toBe(32)
+ await field.getByRole('button', { name: 'Apply variable' }).click()
+ await page.getByRole('button', { name: 'Create number variable from 32', exact: true }).click()
+ await page.getByPlaceholder('Variable name').fill('Typography/Line height/Body')
+ await page.getByRole('button', { name: 'Create', exact: true }).click()
+ await expect(field).toHaveAttribute('data-bound')
+
+ await page.getByRole('combobox', { name: 'Line height mode' }).click()
+ await page.getByRole('option', { name: 'Auto', exact: true }).click()
+ await expect(field).not.toHaveAttribute('data-bound')
+ await expect(field).toContainText('Auto')
+ await page.getByRole('heading', { name: 'Typography', exact: true }).click()
+ await page.keyboard.press(process.platform === 'darwin' ? 'Meta+z' : 'Control+z')
+ await expect(field).toHaveAttribute('data-bound')
+})
diff --git a/tests/e2e/properties/tracking-binding.spec.ts b/tests/e2e/properties/tracking-binding.spec.ts
new file mode 100644
index 000000000..cd0948321
--- /dev/null
+++ b/tests/e2e/properties/tracking-binding.spec.ts
@@ -0,0 +1,49 @@
+import { expect, test } from '@playwright/test'
+
+import { CanvasHelper } from '#tests/helpers/canvas'
+
+for (const theme of ['light', 'dark']) {
+ test(`letter spacing variable lifecycle in ${theme}`, async ({ page }) => {
+ await page.setViewportSize({ width: 1280, height: 1200 })
+ await page.goto('/?test')
+ await new CanvasHelper(page).waitForInit()
+ const id = await page.evaluate(async (mode) => {
+ const path = '/src/app/shell/theme.ts'
+ const module = await import(path)
+ module.useAppTheme().setTheme(mode)
+ const editor = window.openPencil?.getStore?.()
+ if (!editor) throw new Error('Editor unavailable')
+ const id = editor.createShape('TEXT', 100, 100, 240, 80)
+ editor.updateNode(id, { text: 'Tracking review', fontSize: 24, letterSpacing: 2 })
+ editor.select([id])
+ return id
+ }, theme)
+ const section = page.getByRole('region', { name: 'Typography', exact: true })
+ const field = section.locator('[data-property="letterSpacing"]')
+ await expect(field).toContainText('px')
+ await field.getByRole('button', { name: 'Apply variable' }).click()
+ await page.getByRole('button', { name: 'Create number variable from 2', exact: true }).click()
+ await page.getByPlaceholder('Variable name').fill('Typography/Tracking/Comfortable')
+ await page.getByRole('button', { name: 'Create', exact: true }).click()
+ await expect(field).toHaveAttribute('data-bound')
+
+ const input = section.getByRole('spinbutton', { name: 'Letter spacing', exact: true })
+ await input.focus()
+ await expect(field).toHaveAttribute('data-bound')
+
+ await input.fill('3')
+ await input.press('Enter')
+ await expect
+ .poll(() =>
+ page.evaluate((id) => window.openPencil?.getStore?.().graph.getNode(id)?.letterSpacing, id)
+ )
+ .toBe(3)
+ await expect(field).not.toHaveAttribute('data-bound')
+ await section.getByRole('heading', { name: 'Typography', exact: true }).click()
+ await page.keyboard.press(process.platform === 'darwin' ? 'Meta+z' : 'Control+z')
+ await expect(field).toHaveAttribute('data-bound')
+ await field.getByRole('button', { name: 'Apply variable' }).click()
+ await page.getByRole('button', { name: 'Detach variable', exact: true }).click()
+ await expect(field).not.toHaveAttribute('data-bound')
+ })
+}
diff --git a/tests/e2e/properties/typography-panel.spec.ts b/tests/e2e/properties/typography-panel.spec.ts
new file mode 100644
index 000000000..4ca97132c
--- /dev/null
+++ b/tests/e2e/properties/typography-panel.spec.ts
@@ -0,0 +1,46 @@
+import { expect, test } from '@playwright/test'
+
+import { CanvasHelper } from '#tests/helpers/canvas'
+
+for (const theme of ['light', 'dark']) {
+ test(`typography groups remain directly editable in ${theme}`, async ({ page }) => {
+ await page.setViewportSize({ width: 1280, height: 1200 })
+ await page.goto('/?test')
+ await new CanvasHelper(page).waitForInit()
+ const id = await page.evaluate(async (mode) => {
+ const path = '/src/app/shell/theme.ts'
+ const module = await import(path)
+ module.useAppTheme().setTheme(mode)
+ const editor = window.openPencil?.getStore?.()
+ if (!editor) throw new Error('Editor unavailable')
+ const id = editor.createShape('TEXT', 100, 100, 240, 80)
+ editor.updateNode(id, { text: 'Typography review', fontSize: 24 })
+ editor.select([id])
+ return id
+ }, theme)
+ const section = page.getByRole('region', { name: 'Typography', exact: true })
+ await expect(section).toHaveScreenshot(`typography-groups-${theme}.png`)
+ await section.getByRole('button', { name: 'Align center horizontally', exact: true }).click()
+ await expect
+ .poll(() =>
+ page.evaluate(
+ (id) => window.openPencil?.getStore?.().graph.getNode(id)?.textAlignHorizontal,
+ id
+ )
+ )
+ .toBe('CENTER')
+ await section.getByRole('switch', { name: 'Standard ligatures', exact: true }).click()
+ await expect
+ .poll(() =>
+ page.evaluate(
+ (id) =>
+ window.openPencil
+ ?.getStore?.()
+ .graph.getNode(id)
+ ?.fontFeatures.find((feature) => feature.tag === 'LIGA')?.enabled,
+ id
+ )
+ )
+ .toBe(false)
+ })
+}
diff --git a/tests/e2e/properties/typography-panel.spec.ts-snapshots/typography-groups-dark-openpencil-darwin.png b/tests/e2e/properties/typography-panel.spec.ts-snapshots/typography-groups-dark-openpencil-darwin.png
new file mode 100644
index 000000000..943fa8510
Binary files /dev/null and b/tests/e2e/properties/typography-panel.spec.ts-snapshots/typography-groups-dark-openpencil-darwin.png differ
diff --git a/tests/e2e/properties/typography-panel.spec.ts-snapshots/typography-groups-light-openpencil-darwin.png b/tests/e2e/properties/typography-panel.spec.ts-snapshots/typography-groups-light-openpencil-darwin.png
new file mode 100644
index 000000000..d59040786
Binary files /dev/null and b/tests/e2e/properties/typography-panel.spec.ts-snapshots/typography-groups-light-openpencil-darwin.png differ
diff --git a/tests/e2e/properties/unresolved-binding.spec.ts b/tests/e2e/properties/unresolved-binding.spec.ts
new file mode 100644
index 000000000..790b74385
--- /dev/null
+++ b/tests/e2e/properties/unresolved-binding.spec.ts
@@ -0,0 +1,101 @@
+import { expect, test } from '@playwright/test'
+
+import { CanvasHelper } from '#tests/helpers/canvas'
+
+for (const theme of ['light', 'dark']) {
+ test.describe(`unresolved bindings in ${theme}`, () => {
+ test.use({
+ storageState: async ({ baseURL }, use) => {
+ if (!baseURL) throw new Error('Binding tests require a baseURL')
+ await use({
+ cookies: [],
+ origins: [
+ {
+ origin: new URL(baseURL).origin,
+ localStorage: [{ name: 'open-pencil:theme', value: theme }]
+ }
+ ]
+ })
+ }
+ })
+ test(`unresolved number binding remains recoverable in ${theme}`, async ({ page }) => {
+ await page.setViewportSize({ width: 1280, height: 1200 })
+ await page.goto('/?test')
+ await new CanvasHelper(page).waitForInit()
+ await page.evaluate(() => {
+ const editor = window.openPencil?.getStore?.()
+ if (!editor) throw new Error('Editor unavailable')
+ const id = editor.createShape('TEXT', 100, 100, 240, 80)
+ editor.updateNode(id, { text: 'Unavailable variable', fontSize: 24, letterSpacing: 2 })
+ const collection = editor.graph.createCollection('Typography')
+ const variable = editor.graph.createVariable(
+ 'Tracking/Missing alias',
+ 'FLOAT',
+ collection.id,
+ 2
+ )
+ editor.graph.createVariable('Tracking/Replacement', 'FLOAT', collection.id, 6)
+ editor.bindVariable(id, 'letterSpacing', variable.id)
+ editor.updateVariableValue(variable.id, collection.defaultModeId, { aliasId: 'missing' })
+ const color = editor.graph.createVariable('Paint/Unavailable', 'COLOR', collection.id, {
+ r: 1,
+ g: 0,
+ b: 0,
+ a: 1
+ })
+ editor.graph.createVariable('Paint/Replacement', 'COLOR', collection.id, {
+ r: 0,
+ g: 1,
+ b: 0,
+ a: 1
+ })
+ editor.updateNode(id, {
+ strokes: [
+ {
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ weight: 1,
+ opacity: 1,
+ visible: true,
+ align: 'CENTER'
+ }
+ ]
+ })
+ editor.bindVariable(id, 'fills/0/color', color.id)
+ editor.bindVariable(id, 'strokes/0/color', color.id)
+ editor.updateVariableValue(color.id, collection.defaultModeId, { aliasId: 'missing-color' })
+ editor.select([id])
+ })
+ const section = page.getByRole('region', { name: 'Typography', exact: true })
+ const field = section.locator('[data-property="letterSpacing"]')
+ await expect(field.locator('[data-slot="pill"]')).toHaveAttribute('data-unresolved')
+ await expect(field).toContainText('Tracking/Missing alias')
+ for (const name of ['Fill', 'Stroke']) {
+ const paint = page.getByRole('region', { name, exact: true })
+ await expect(paint.locator('[data-slot="pill"][data-unresolved]')).toBeVisible()
+ await expect(paint.locator('[data-property="opacity"]')).toContainText('100')
+ if (theme === 'dark' && name === 'Fill')
+ await expect(paint).toHaveScreenshot('unresolved-fill-dark.png')
+ await paint.getByRole('button', { name: 'Apply variable' }).click()
+ await page.getByRole('button', { name: 'Detach variable', exact: true }).click()
+ await expect(paint.locator('[data-slot="pill"]')).toHaveCount(0)
+ await paint.getByRole('heading', { name, exact: true }).click()
+ await page.keyboard.press(process.platform === 'darwin' ? 'Meta+z' : 'Control+z')
+ await expect(paint.locator('[data-slot="pill"]')).toHaveAttribute('data-unresolved')
+ await paint.getByRole('button', { name: 'Apply variable' }).click()
+ await page.getByRole('option', { name: 'Paint/Replacement' }).click()
+ await expect(paint).toContainText('Paint/Replacement')
+ await expect(paint.locator('[data-slot="pill"]')).not.toHaveAttribute('data-unresolved')
+ }
+ await field.getByRole('button', { name: 'Apply variable' }).click()
+ await page.getByRole('button', { name: 'Detach variable', exact: true }).click()
+ await expect(field.locator('[data-slot="pill"]')).toHaveCount(0)
+ await section.getByRole('heading', { name: 'Typography', exact: true }).click()
+ await page.keyboard.press(process.platform === 'darwin' ? 'Meta+z' : 'Control+z')
+ await expect(field.locator('[data-slot="pill"]')).toHaveAttribute('data-unresolved')
+ await field.getByRole('button', { name: 'Apply variable' }).click()
+ await page.getByRole('option', { name: 'Tracking/Replacement' }).click()
+ await expect(field).toContainText('Tracking/Replacement')
+ await expect(field.locator('[data-slot="pill"]')).not.toHaveAttribute('data-unresolved')
+ })
+ })
+}
diff --git a/tests/e2e/properties/unresolved-binding.spec.ts-snapshots/unresolved-fill-dark-openpencil-darwin.png b/tests/e2e/properties/unresolved-binding.spec.ts-snapshots/unresolved-fill-dark-openpencil-darwin.png
new file mode 100644
index 000000000..7d6681b1a
Binary files /dev/null and b/tests/e2e/properties/unresolved-binding.spec.ts-snapshots/unresolved-fill-dark-openpencil-darwin.png differ
diff --git a/tests/e2e/storybook/binding-actions.spec.ts b/tests/e2e/storybook/binding-actions.spec.ts
new file mode 100644
index 000000000..33f6f7189
--- /dev/null
+++ b/tests/e2e/storybook/binding-actions.spec.ts
@@ -0,0 +1,18 @@
+import { expect, test } from '@playwright/test'
+
+test('binding picker creates a variable through submit and detaches it', async ({ page }) => {
+ await page.goto('/iframe.html?id=editor-properties-binding-field--picker-actions&viewMode=story')
+ const field = page.getByLabel('Unbound field', { exact: true })
+ await field.getByRole('button', { name: 'Apply variable' }).click()
+ await page.getByRole('button', { name: 'Create number variable' }).click()
+ const input = page.getByPlaceholder('Variable name')
+ await expect(input).toBeFocused()
+ const create = page.getByRole('button', { name: 'Create', exact: true })
+ await expect(create).toBeDisabled()
+ await input.fill('New spacing')
+ await create.click()
+ await expect(field).toHaveAttribute('data-bound')
+ await field.getByRole('button', { name: 'Apply variable' }).click()
+ await page.getByRole('button', { name: 'Detach variable' }).click()
+ await expect(field).toHaveAttribute('data-unbound')
+})
diff --git a/tests/e2e/storybook/binding-modes.spec.ts b/tests/e2e/storybook/binding-modes.spec.ts
new file mode 100644
index 000000000..1ab68c48f
--- /dev/null
+++ b/tests/e2e/storybook/binding-modes.spec.ts
@@ -0,0 +1,34 @@
+import { expect, test } from '@playwright/test'
+
+test('missing definitions retain identity and remain explicitly detachable', async ({ page }) => {
+ await page.goto('/iframe.html?id=vue-sdk-primitives-bindablevalue--mode-editing&viewMode=story')
+ const identity = await page.getByLabel('Binding identity').innerText()
+ expect(identity).not.toBe('')
+ await page.getByRole('button', { name: 'Remove variable definition' }).click()
+ await expect(page.getByLabel('Binding state')).toHaveText('unresolved')
+ await expect(page.getByLabel('Binding identity')).toHaveText(identity)
+ await page.getByRole('button', { name: 'Begin edit', exact: true }).click()
+ await page.getByRole('button', { name: 'Set 12', exact: true }).click()
+ await expect(page.getByLabel('Binding state')).toHaveText('unresolved')
+ await expect(page.getByLabel('Mode values')).toHaveText('null')
+ await page.getByRole('button', { name: 'Detach', exact: true }).click()
+ await expect(page.getByLabel('Binding state')).toHaveText('unbound')
+})
+
+for (const outcome of ['Cancel', 'Commit']) {
+ test(`captured variable modes survive target changes: ${outcome}`, async ({ page }) => {
+ await page.goto('/iframe.html?id=vue-sdk-primitives-bindablevalue--mode-editing&viewMode=story')
+ const values = async () =>
+ JSON.parse(await page.getByLabel('Mode values').innerText()) as Record<string, number>
+ const before = await values()
+ await page.getByRole('button', { name: 'Begin edit', exact: true }).click()
+ await page.getByRole('button', { name: 'Set 12', exact: true }).click()
+ expect(Object.values(await values()).sort((a, b) => a - b)).toEqual([12, 12, 40])
+ await page.getByRole('button', { name: 'Change selection and mode' }).click()
+ await page.getByRole('button', { name: 'Set 20', exact: true }).click()
+ expect(Object.values(await values()).sort((a, b) => a - b)).toEqual([20, 20, 40])
+ await page.getByRole('button', { name: outcome, exact: true }).click()
+ if (outcome === 'Commit') await page.getByRole('button', { name: 'Undo', exact: true }).click()
+ expect(await values()).toEqual(before)
+ })
+}
diff --git a/tests/engine/vue/controls/binding-mode-edit.test.ts b/tests/engine/vue/controls/binding-mode-edit.test.ts
new file mode 100644
index 000000000..610998e1d
--- /dev/null
+++ b/tests/engine/vue/controls/binding-mode-edit.test.ts
@@ -0,0 +1,84 @@
+import { expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+
+import { prepareModeEdit } from '#vue/controls/binding-provider/mode-edit'
+import { createOpenPencilBindingProvider } from '#vue/controls/binding-provider/open-pencil'
+import { prepareBindingEdits } from '#vue/controls/binding-provider/prepare-edits'
+import { resolveEffectiveBindingValue } from '#vue/controls/binding-provider/resolution'
+
+test('editing an alias captures the bound mode without mutating its shared source', () => {
+ const editor = createEditor()
+ const page = editor.graph.getPages()[0]
+ if (!page) throw new Error('No page')
+ const collection = editor.graph.createCollection('Tokens')
+ const source = editor.graph.createVariable('Shared', 'FLOAT', collection.id, 8)
+ const alias = editor.graph.createVariable('Local', 'FLOAT', collection.id, 0)
+ const original = { aliasId: source.id }
+ editor.updateVariableValue(alias.id, collection.defaultModeId, original)
+ const node = editor.graph.createNode('RECTANGLE', page.id, {})
+ const target = { nodeId: node.id, path: 'width' }
+ const edit = prepareModeEdit<number>(editor, alias.id, target, () => {
+ const value = resolveEffectiveBindingValue(editor, alias.id, target)
+ return typeof value === 'number' ? value : undefined
+ })
+ if (!edit) throw new Error('No edit')
+ expect(edit.value).toBe(8)
+ editor.undo.runBatch('Edit local token', () => edit.set(16))
+ expect(editor.getVariable(alias.id)?.valuesByMode[collection.defaultModeId]).toBe(16)
+ expect(editor.getVariable(source.id)?.valuesByMode[collection.defaultModeId]).toBe(8)
+ editor.undo.undo()
+ expect(editor.getVariable(alias.id)?.valuesByMode[collection.defaultModeId]).toEqual(original)
+ edit.set(24)
+ edit.restore()
+ expect(editor.getVariable(alias.id)?.valuesByMode[collection.defaultModeId]).toEqual(original)
+ expect(editor.getVariable(source.id)?.valuesByMode[collection.defaultModeId]).toBe(8)
+})
+
+test('prepared edits retain modes after targets change and undo atomically', () => {
+ const editor = createEditor()
+ const page = editor.graph.getPages()[0]
+ if (!page) throw new Error('No page')
+ const collection = editor.graph.createCollection('Spacing')
+ editor.graph.addMode(collection.id, 'alternate', 'Alternate')
+ const variable = editor.graph.createVariable('Gap', 'FLOAT', collection.id, 8)
+ editor.updateVariableValue(variable.id, 'alternate', 8)
+ const a = editor.graph.createNode('FRAME', page.id, {})
+ const b = editor.graph.createNode('FRAME', page.id, {
+ variableModes: { [collection.id]: 'alternate' }
+ })
+ const provider = createOpenPencilBindingProvider(editor, {
+ type: 'FLOAT',
+ resolve: (e, id, target) =>
+ target
+ ? e.graph.resolveNumberVariableForNode(target.nodeId, id)
+ : e.resolveNumberVariable(id),
+ prepareEdit: (e, id, target) =>
+ prepareModeEdit(e, id, target, () => e.graph.resolveNumberVariableForNode(target.nodeId, id))
+ })
+ const targets = [a, a, b].map((node) => ({ nodeId: node.id, path: 'width' }))
+ for (const target of targets) provider.bind(target, variable.id)
+ const edits = prepareBindingEdits(provider, targets)
+ expect(edits).toHaveLength(2)
+ if (!edits) throw new Error('No edits')
+ const [first, second] = edits
+ if (!first || !second) throw new Error('No edit')
+ expect(first.key).not.toBe(second.key)
+ editor.graph.updateNode(b.id, { variableModes: {} })
+ editor.undo.runBatch('Edit variable', () => {
+ first.set(12)
+ second.set(12)
+ })
+ expect(editor.getVariable(variable.id)?.valuesByMode).toEqual({
+ [collection.defaultModeId]: 12,
+ alternate: 12
+ })
+ editor.undo.undo()
+ expect(editor.getVariable(variable.id)?.valuesByMode).toEqual({
+ [collection.defaultModeId]: 8,
+ alternate: 8
+ })
+ second.set(20)
+ second.restore?.()
+ expect(editor.getVariable(variable.id)?.valuesByMode.alternate).toBe(8)
+})
diff --git a/tests/engine/vue/controls/binding-modes.test.ts b/tests/engine/vue/controls/binding-modes.test.ts
new file mode 100644
index 000000000..e16b2b03e
--- /dev/null
+++ b/tests/engine/vue/controls/binding-modes.test.ts
@@ -0,0 +1,73 @@
+import { expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+
+import { prepareModeEdit } from '#vue/controls/binding-provider/mode-edit'
+import { createOpenPencilBindingProvider } from '#vue/controls/binding-provider/open-pencil'
+import { prepareBindingEdits } from '#vue/controls/binding-provider/prepare-edits'
+import { resolveEffectiveBindingValue } from '#vue/controls/binding-provider/resolution'
+
+test('binding resolution uses node modes and reports mixed resolved values', () => {
+ const editor = createEditor()
+ const page = editor.graph.getPages()[0]
+ if (!page) throw new Error('No page')
+ const collection = editor.graph.createCollection('Spacing')
+ editor.graph.addMode(collection.id, 'large', 'Large')
+ const variable = editor.graph.createVariable('Space', 'FLOAT', collection.id, 8)
+ editor.updateVariableValue(variable.id, 'large', 24)
+ const a = editor.graph.createNode('RECTANGLE', page.id, {})
+ const b = editor.graph.createNode('RECTANGLE', page.id, {
+ variableModes: { [collection.id]: 'large' }
+ })
+ const targets = [a, b].map((node) => ({ nodeId: node.id, path: 'width' }))
+ const provider = createOpenPencilBindingProvider(editor, {
+ type: 'FLOAT',
+ prepareEdit: (e, id, target) =>
+ prepareModeEdit(e, id, target, () => e.graph.resolveNumberVariableForNode(target.nodeId, id)),
+ resolve: (e, id, target) =>
+ target ? e.graph.resolveNumberVariableForNode(target.nodeId, id) : e.resolveNumberVariable(id)
+ })
+ for (const target of targets) provider.bind(target, variable.id)
+ expect(provider.resolve(variable.id, targets[0])).toBe(8)
+ expect(provider.resolve(variable.id, targets[1])).toBe(24)
+ expect(provider.getState(targets)).toBe('mixed')
+ expect(provider.getState(targets.slice(0, 1))).toBe('bound')
+ const target = targets[1]
+ if (!target) throw new Error('No target')
+ const edit = provider.prepareEdit?.(variable.id, target)
+ if (!edit) throw new Error('No edit')
+ edit.set(32)
+ expect(provider.resolve(variable.id, targets[0])).toBe(8)
+ expect(provider.resolve(variable.id, targets[1])).toBe(32)
+
+ const aliasCollection = editor.graph.createCollection('Alias values')
+ editor.graph.addMode(aliasCollection.id, 'alternate', 'Alternate')
+ const alias = editor.graph.createVariable('Alias', 'FLOAT', aliasCollection.id, 4)
+ editor.updateVariableValue(alias.id, 'alternate', 64)
+ editor.graph.updateNode(b.id, {
+ variableModes: { [collection.id]: 'large', [aliasCollection.id]: 'alternate' }
+ })
+ editor.updateVariableValue(variable.id, 'large', { aliasId: alias.id })
+ expect(resolveEffectiveBindingValue(editor, variable.id, target)).toBe(64)
+ editor.updateVariableValue(alias.id, 'alternate', { aliasId: variable.id })
+ expect(resolveEffectiveBindingValue(editor, variable.id, target)).toBeUndefined()
+
+ delete variable.valuesByMode.large
+ expect(provider.getState(targets.slice(1))).toBe('unresolved')
+ editor.updateVariableValue(variable.id, 'large', { aliasId: 'missing-alias' })
+ expect(provider.getState(targets.slice(1))).toBe('unresolved')
+ editor.graph.variables.delete(variable.id)
+ expect(provider.getBindingId(target)).toBe(variable.id)
+ expect(provider.getBound(target)).toBeUndefined()
+ expect(provider.getState(targets)).toBe('unresolved')
+ provider.unbind(target)
+ expect(provider.getState(targets)).toBe('mixed')
+ expect(prepareBindingEdits(provider, targets)).toBeUndefined()
+ const other = editor.graph.createVariable('Other', 'FLOAT', collection.id, 12)
+ provider.bind(target, other.id)
+ editor.graph.variables.delete(other.id)
+ expect(provider.getState(targets)).toBe('mixed')
+ expect(prepareBindingEdits(provider, targets)).toBeUndefined()
+ expect(provider.getBindingId(targets[0] ?? target)).toBe(variable.id)
+ expect(provider.getBindingId(target)).toBe(other.id)
+})
diff --git a/tests/engine/vue/controls/color-binding-provider.test.ts b/tests/engine/vue/controls/color-binding-provider.test.ts
index a71f38269..d357d8015 100644
--- a/tests/engine/vue/controls/color-binding-provider.test.ts
+++ b/tests/engine/vue/controls/color-binding-provider.test.ts
@@ -3,10 +3,8 @@ import { describe, expect, test } from 'bun:test'
import { createEditor } from '@open-pencil/core/editor'
import type { Color, Fill } from '@open-pencil/scene-graph'
-import {
- createAndBindColorVariable,
- setColorVariableValue
-} from '#vue/controls/binding-provider/color'
+import { createAndBindColorVariable } from '#vue/controls/binding-provider/color'
+import { prepareModeEdit } from '#vue/controls/binding-provider/mode-edit'
const fill: Fill = {
type: 'SOLID',
@@ -47,7 +45,7 @@ describe('color binding provider helpers', () => {
expect(variableId ? editor.resolveColorVariable(variableId) : undefined).toEqual(fill.color)
})
- test('reuses a color collection and updates every mode with structured colors', () => {
+ test('reuses a color collection and edits only the captured mode', () => {
const { editor, node } = setup()
const collection = editor.graph.createCollection('Product colors')
editor.graph.addMode(collection.id, 'dark', 'Dark')
@@ -64,10 +62,18 @@ describe('color binding provider helpers', () => {
const variableId = editor.getNode(node.id)?.boundVariables['fills/0/color']
if (!variableId) throw new Error('Expected color binding')
const next: Color = { r: 0.9, g: 0.1, b: 0.3, a: 0.75 }
- setColorVariableValue(editor, variableId, next)
+ const edit = prepareModeEdit(
+ editor,
+ variableId,
+ { nodeId: node.id, path: 'fills/0/color' },
+ () => editor.graph.resolveColorVariableForNode(node.id, variableId)
+ )
+ if (!edit) throw new Error('No edit')
+ edit.set(next)
const variable = editor.getVariable(variableId)
expect(variable).toBeDefined()
- for (const mode of collection.modes) expect(variable?.valuesByMode[mode.modeId]).toEqual(next)
+ expect(variable?.valuesByMode[collection.defaultModeId]).toEqual(next)
+ expect(variable?.valuesByMode.dark).toEqual(fill.color)
})
})
diff --git a/tools/lint/src/rules/runtime.ts b/tools/lint/src/rules/runtime.ts
index e347ea29e..c3f882f4a 100644
--- a/tools/lint/src/rules/runtime.ts
+++ b/tools/lint/src/rules/runtime.ts
@@ -39,6 +39,8 @@ const noDirectStorageAccess = {
return {
Identifier(node) {
if (node.name !== 'localStorage' && node.name !== 'sessionStorage') return
+ const parent = node.parent
+ if (parent.type === 'Property' && parent.key === node && !parent.computed) return
reportStorage(node, node.name)
}
}
diff --git a/tools/lint/tests/plugin.test.ts b/tools/lint/tests/plugin.test.ts
index 38dbd3d10..828ff3e01 100644
--- a/tools/lint/tests/plugin.test.ts
+++ b/tools/lint/tests/plugin.test.ts
@@ -86,6 +86,19 @@ test('domain naming uses ownership prefixes, not control-kind suffixes', async (
).toBe(1)
})
+test('storage rule permits data keys but rejects storage access', async () => {
+ const rule = 'no-direct-storage-access'
+ for (const [source, count] of [
+ ['const state = {localStorage: []}', 0],
+ ['localStorage.clear()', 1],
+ ['window.sessionStorage.clear()', 1],
+ ['const value = {localStorage}', 1]
+ ] as const) {
+ const diagnostics = await lint(source, { [`open-pencil/${rule}`]: 'error' })
+ expect(ruleDiagnostics(diagnostics, rule)).toHaveLength(count)
+ }
+})
+
function ruleDiagnostics(diagnostics: Diagnostic[], rule: string): Diagnostic[] {
return diagnostics.filter((diagnostic) => diagnostic.code === `open-pencil(${rule})`)
}