Skip to content

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

fix(preview): toggle controls both ways and keep islands in step with the canvas (#982)

Danila Poyarkov9081c4b1d6eb
diff --git a/packages/core/AGENTS.md b/packages/core/AGENTS.md
index ab5249dc5..199cb09ed 100644
--- a/packages/core/AGENTS.md
+++ b/packages/core/AGENTS.md
@@ -5,6 +5,7 @@ Renderer, layout, editor, Figma API, tools, clipboard, vector conversion, and do
- Public surface is the compatibility barrel plus the subpaths listed in `packages/core/package.json` `exports`; add a subpath there rather than deep-importing.
- CanvasKit runtime loading is centralized in `@open-pencil/core/canvaskit`. Headless raster export may dynamically load `canvaskit-wasm/full`; elsewhere `import type` and pass CanvasKit in.
- Drawing and input share preview-aware geometry through `@open-pencil/core/geometry`, built on Scene Graph matrices. Use it for world/screen transforms, inverses, bounds, and handle placement.
+- Copies of part of a document, such as previews, history snapshots, and exports, come from `extractPageContext` or `extractExportGraph` in `packages/core/src/io/subgraph.ts`, not another copier. Pass `componentSets` when instances must switch variant and `shareTables` for a read-only view rebuilt often (`packages/core/tests/io/subgraph.test.ts`).
## Layout
diff --git a/packages/core/src/editor/play/states.ts b/packages/core/src/editor/play/states.ts
index 95ff7ff35..2e1a73c16 100644
--- a/packages/core/src/editor/play/states.ts
+++ b/packages/core/src/editor/play/states.ts
@@ -2,10 +2,11 @@ import {
applyComponentPropertyValue,
componentPropertyDefinitions,
findLayerByPath,
- SceneGraph,
+ type SceneGraph,
type SceneNode
} from '@open-pencil/scene-graph'
+import { extractPageContext, findPageId } from '#core/io/subgraph'
import { computeAllLayouts } from '#core/layout'
/** How one instance of an island is shown: the variant, properties, and layers it displays. */
@@ -23,47 +24,6 @@ export interface InstanceState {
reveal?: string[]
}
-/** The root's layers and every component they show, so instances can switch variant. */
-function closure(source: SceneGraph, rootId: string): Set<string> {
- const ids = new Set<string>()
- const visit = (id: string) => {
- if (ids.has(id)) return
- const node = source.getNode(id)
- if (!node) return
- ids.add(id)
- for (const child of node.childIds) visit(child)
- if (node.componentId) {
- const component = source.getNode(node.componentId)
- const set = component?.parentId ? source.getNode(component.parentId) : undefined
- visit(set?.type === 'COMPONENT_SET' ? set.id : node.componentId)
- }
- }
- visit(rootId)
- return ids
-}
-
-function copyGraph(source: SceneGraph, ids: Set<string>): SceneGraph {
- const graph = new SceneGraph()
- // Fills, images, and bindings resolve against the document's own tables.
- graph.variables = source.variables
- graph.variableCollections = source.variableCollections
- graph.activeMode = source.activeMode
- graph.images = source.images
- graph.documentColorSpace = source.documentColorSpace
- for (const id of ids) {
- const node = source.getNode(id)
- if (!node) continue
- const copy = structuredClone(node)
- graph.nodes.set(id, copy)
- if (copy.type === 'INSTANCE' && copy.componentId) {
- const instances = graph.instanceIndex.get(copy.componentId) ?? new Set<string>()
- instances.add(id)
- graph.instanceIndex.set(copy.componentId, instances)
- }
- }
- return graph
-}
-
/**
* The variant of the instance's set that shows `required`, and `prefer` too when one does, and
* otherwise keeps as many of the instance's values as it can.
@@ -115,7 +75,8 @@ function applyState(
if (state.variants || state.prefer) {
const variant = variantFor(graph, instance, state.variants ?? {}, state.prefer ?? {})
if (variant && variant.id !== instance.componentId) {
- graph.swapInstanceComponent(instance.id, variant.id)
+ // Its layer path names the control, so the instance keeps its name in every variant.
+ graph.swapInstanceComponent(instance.id, variant.id, { keepName: true })
reflow(graph, instance.id)
}
}
@@ -146,7 +107,13 @@ export function resolvePlayState(
rootId: string,
states: ReadonlyMap<string, InstanceState>
): SceneGraph {
- const graph = copyGraph(source, closure(source, rootId))
+ // The root's page context with every variant its instances can switch to, reading the
+ // document's own variables and images, since a state never changes them.
+ const pageId = findPageId(source, rootId) ?? source.rootId
+ const graph = extractPageContext(source, pageId, [rootId], {
+ componentSets: true,
+ shareTables: true
+ })
const ordered = [...states].sort(([a], [b]) => a.split('/').length - b.split('/').length)
for (const [path, state] of ordered) {
const instance = findLayerByPath(graph, rootId, path)
diff --git a/packages/core/src/io/subgraph.ts b/packages/core/src/io/subgraph.ts
index 348437ba5..5a9c6b225 100644
--- a/packages/core/src/io/subgraph.ts
+++ b/packages/core/src/io/subgraph.ts
@@ -2,6 +2,16 @@ import { SceneGraph } from '@open-pencil/scene-graph'
import type { ExportTarget } from './types'
+export interface ExtractOptions {
+ /** Every variant of an instance's set, not only its main component, so it can switch variant. */
+ componentSets?: boolean
+ /**
+ * Use the source's variables, collections, and images instead of copies, for a read-only view
+ * rebuilt often, such as preview's. A copy may change its tables without touching the source.
+ */
+ shareTables?: boolean
+}
+
export interface ExtractedGraph {
graph: SceneGraph
pageId: string | null
@@ -30,7 +40,11 @@ function includeReferencedStyles(source: SceneGraph, ids: Set<string>): void {
}
}
-function cloneIntoGraph(source: SceneGraph, ids: Set<string>): SceneGraph {
+function cloneIntoGraph(
+ source: SceneGraph,
+ ids: Set<string>,
+ { shareTables = false }: ExtractOptions = {}
+): SceneGraph {
const graph = new SceneGraph()
graph.rootId = source.rootId
graph.nodes = new Map()
@@ -57,7 +71,14 @@ function cloneIntoGraph(source: SceneGraph, ids: Set<string>): SceneGraph {
for (const id of sortedIds) {
const node = source.getNode(id)
if (!node) continue
- graph.nodes.set(id, structuredClone(node))
+ const copy = structuredClone(node)
+ graph.nodes.set(id, copy)
+ // Syncing and swapping find an instance through its component's index.
+ if (copy.type === 'INSTANCE' && copy.componentId) {
+ const instances = graph.instanceIndex.get(copy.componentId) ?? new Set<string>()
+ instances.add(id)
+ graph.instanceIndex.set(copy.componentId, instances)
+ }
}
const rootClone = graph.getNode(source.rootId)
@@ -76,6 +97,18 @@ function cloneIntoGraph(source: SceneGraph, ids: Set<string>): SceneGraph {
node.childIds = node.childIds.filter((childId) => ids.has(childId))
}
+ if (shareTables) {
+ graph.images = source.images
+ graph.variables = source.variables
+ graph.variableCollections = source.variableCollections
+ } else copyReferencedTables(source, graph)
+
+ graph.clearAbsPosCache()
+ return graph
+}
+
+/** The images and variables the copied layers use, with their collections, copied in. */
+function copyReferencedTables(source: SceneGraph, graph: SceneGraph): void {
const { imageHashes, variableIds } = collectReferencedResources(source, graph)
for (const imageHash of imageHashes) {
@@ -98,9 +131,6 @@ function cloneIntoGraph(source: SceneGraph, ids: Set<string>): SceneGraph {
}
graph.variableCollections.get(collection.id)?.variableIds.push(variableId)
}
-
- graph.clearAbsPosCache()
- return graph
}
function collectReferencedResources(source: SceneGraph, graph: SceneGraph) {
@@ -169,7 +199,11 @@ function resolveInstanceComponentId(source: SceneGraph, componentId: string): st
return componentId
}
-function collectComponentDependencies(source: SceneGraph, ids: Set<string>) {
+function collectComponentDependencies(
+ source: SceneGraph,
+ ids: Set<string>,
+ { componentSets = false }: ExtractOptions = {}
+) {
let changed = true
while (changed) {
changed = false
@@ -177,10 +211,13 @@ function collectComponentDependencies(source: SceneGraph, ids: Set<string>) {
const node = source.getNode(id)
if (node?.type !== 'INSTANCE' || !node.componentId) continue
const componentId = resolveInstanceComponentId(source, node.componentId)
- if (ids.has(componentId)) continue
+ const component = source.getNode(componentId)
+ const set = component?.parentId ? source.getNode(component.parentId) : undefined
+ const dependency = componentSets && set?.type === 'COMPONENT_SET' ? set.id : componentId
+ if (ids.has(dependency)) continue
const before = ids.size
- collectAncestors(source, componentId, ids)
- collectDescendants(source, componentId, ids)
+ collectAncestors(source, dependency, ids)
+ collectDescendants(source, dependency, ids)
changed ||= ids.size !== before
}
}
@@ -218,7 +255,11 @@ function ancestorChain(source: SceneGraph, id: string): string[] {
return chain.reverse()
}
-function collectSelectionIds(source: SceneGraph, nodeIds: string[]): Set<string> {
+function collectSelectionIds(
+ source: SceneGraph,
+ nodeIds: string[],
+ options: ExtractOptions = {}
+): Set<string> {
const ids = new Set<string>([source.rootId])
const pageIds = new Set<string>()
@@ -237,7 +278,7 @@ function collectSelectionIds(source: SceneGraph, nodeIds: string[]): Set<string>
ids.add(pageId)
}
- collectComponentDependencies(source, ids)
+ collectComponentDependencies(source, ids, options)
return ids
}
@@ -260,11 +301,12 @@ function rootNodeIds(source: SceneGraph): Set<string> {
export function extractPageContext(
source: SceneGraph,
pageId: string,
- nodeIds: string[]
+ nodeIds: string[],
+ options: ExtractOptions = {}
): SceneGraph {
- const ids = collectSelectionIds(source, nodeIds)
+ const ids = collectSelectionIds(source, nodeIds, options)
ids.add(pageId)
- return cloneIntoGraph(source, ids)
+ return cloneIntoGraph(source, ids, options)
}
export function extractExportGraph(source: SceneGraph, target: ExportTarget): ExtractedGraph {
diff --git a/packages/core/tests/editor/play/states.test.ts b/packages/core/tests/editor/play/states.test.ts
index 45a670ec1..920e73272 100644
--- a/packages/core/tests/editor/play/states.test.ts
+++ b/packages/core/tests/editor/play/states.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, test } from 'bun:test'
import { createEditor, playIslandRoots, resolvePlayState } from '@open-pencil/core/editor'
import {
emptyBehaviour,
+ findLayerByPath,
instanceMainComponent,
layerPath,
SceneGraph
@@ -69,6 +70,24 @@ describe('preview islands', () => {
expect(instanceMainComponent(graph, instance)?.id).toBe(off.id)
})
+ test('an instance named after its variant keeps its path through a state switch', () => {
+ const { graph, card, off, on } = switchCard()
+ // Left with its default name, which is its variant's, as instances placed from a set are.
+ const instance = graph.createInstance(off.id, card.id)
+ if (!instance) throw new Error('No instance')
+ const path = layerPath(graph, card.id, instance.id)
+ expect(instance.name).toBe(off.name)
+
+ const shown = resolvePlayState(graph, card.id, new Map([[path, { variants: { State: 'On' } }]]))
+ const copy = findLayerByPath(shown, card.id, path)
+ expect(copy && instanceMainComponent(shown, copy)?.id).toBe(on.id)
+ expect(copy?.name).toBe(off.name)
+ // The same path switches it back, so a control toggles both ways.
+ const back = resolvePlayState(graph, card.id, new Map([[path, { variants: { State: 'Off' } }]]))
+ const restored = findLayerByPath(back, card.id, path)
+ expect(restored && instanceMainComponent(back, restored)?.id).toBe(off.id)
+ })
+
test('a preferred state shows only where the set draws it with the required values', () => {
const { graph, card, instance, on, offHover } = switchCard()
const path = layerPath(graph, card.id, instance.id)
diff --git a/packages/core/tests/io/subgraph.test.ts b/packages/core/tests/io/subgraph.test.ts
new file mode 100644
index 000000000..eb36c9872
--- /dev/null
+++ b/packages/core/tests/io/subgraph.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, test } from 'bun:test'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { extractPageContext } from '#core/io/subgraph'
+
+/** A Switch set with two variants, and a card on the same page holding an Off instance. */
+function cardWithSwitch() {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const set = graph.createNode('COMPONENT_SET', pageId, { name: 'Switch' })
+ const off = graph.createNode('COMPONENT', set.id, { name: 'State=Off' })
+ const on = graph.createNode('COMPONENT', set.id, { name: 'State=On' })
+ const card = graph.createNode('FRAME', pageId, { name: 'Card' })
+ const instance = graph.createInstance(off.id, card.id)
+ if (!instance) throw new Error('No instance')
+ return { graph, pageId, card, instance, off, on }
+}
+
+describe('extracting page context', () => {
+ test("brings an instance's main component, or its whole set when asked", () => {
+ const { graph, pageId, card, off, on } = cardWithSwitch()
+ const plain = extractPageContext(graph, pageId, [card.id])
+ expect(plain.getNode(off.id)).toBeDefined()
+ expect(plain.getNode(on.id)).toBeUndefined()
+ const withSets = extractPageContext(graph, pageId, [card.id], { componentSets: true })
+ expect(withSets.getNode(on.id)).toBeDefined()
+ })
+
+ test('indexes instances by component, so the copy can sync and swap them', () => {
+ const { graph, pageId, card, instance, off } = cardWithSwitch()
+ const copy = extractPageContext(graph, pageId, [card.id], { componentSets: true })
+ expect([...(copy.instanceIndex.get(off.id) ?? [])]).toEqual([instance.id])
+ })
+
+ test("copies the source's tables, or shares them for a read-only view", () => {
+ const { graph, pageId, card } = cardWithSwitch()
+ expect(extractPageContext(graph, pageId, [card.id]).variables).not.toBe(graph.variables)
+ const shared = extractPageContext(graph, pageId, [card.id], { shareTables: true })
+ expect(shared.variables).toBe(graph.variables)
+ expect(shared.images).toBe(graph.images)
+ })
+})
diff --git a/packages/docs/development/behaviours-and-preview.md b/packages/docs/development/behaviours-and-preview.md
index 9c07fdaf2..d54fccbc9 100644
--- a/packages/docs/development/behaviours-and-preview.md
+++ b/packages/docs/development/behaviours-and-preview.md
@@ -32,9 +32,9 @@ All of them write the same model.
Preview is a per-pane mode (`EditorViewState.play`). It runs controls as real components; it never simulates them on the canvas.
-1. **Islands.** `playIslandRoots` (Core) picks the top-level layers of the page that hold an instance with a behaviour. The renderer skips them while the pane previews, and `PlayIslands` (`packages/vue/src/canvas/islands/`) mounts one island per root, laid over the canvas at the pane's pan and zoom.
+1. **Islands.** `playIslandRoots` (Core) picks the top-level layers of the page that hold an instance with a behaviour. The renderer skips them while the pane previews, and `PlayIslands` (`packages/vue/src/canvas/islands/`) mounts one island per root, laid over the canvas at the pan and zoom of the canvas's last drawn frame, so the islands never run ahead of a canvas still catching up while panning and zooming.
2. **Shadow DOM.** Each island renders into its own shadow root: app CSS does not reach in, island CSS does not leak out, fonts already loaded by the app apply, and the island moves with the canvas in the same frame. Wheel gestures over an island are passed to the canvas.
-3. **State to design.** An island keeps each control's state (values, choice, number, typed text, hover, pressed, focus). Core's `resolvePlayState` copies the island's layers into a private graph and shows each instance in its state: the matching variant, boolean properties, and layers a control reveals, such as tab panels. The document is never changed.
+3. **State to design.** An island keeps each control's state (values, choice, number, typed text, hover, pressed, focus). Core's `resolvePlayState` copies the island's layers into a private graph and shows each instance in its state: the matching variant, boolean properties, and layers a control reveals, such as tab panels. The copy comes from the page extractor history and export use (`extractPageContext`), with every variant of each instance's set so it can switch, and the document's variables and images shared rather than copied, since a state never changes them. The document is never changed.
4. **Design to DOM.** The private graph is projected to DOM through `@open-pencil/dom-css`, the same projection HTML export uses, so island fidelity and export fidelity improve together.
5. **DOM to Reka.** Each projected layer has a role: a control's root, a part, a group's item, a tab trigger or panel, or a text input. `behaviourControls` and `controlRoles` in `@open-pencil/dom-css` (`packages/dom-css/src/behaviours/`) assign them, so code export reads the same roles. Roles wrap the layer in its Reka UI primitive with `asChild`, so Reka renders through the designed element. Typing, focus, keyboard navigation, and accessibility are the browser's and Reka's.
diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.ts
index f96880b09..fdf894c02 100644
--- a/packages/scene-graph/src/index.ts
+++ b/packages/scene-graph/src/index.ts
@@ -827,8 +827,12 @@ export class SceneGraph {
Instances.populateInstanceChildren(this, instanceId, componentId, mode)
}
- swapInstanceComponent(instanceId: string, componentId: string): void {
- Instances.swapInstanceComponent(this, instanceId, componentId)
+ swapInstanceComponent(
+ instanceId: string,
+ componentId: string,
+ options?: Instances.SwapInstanceOptions
+ ): void {
+ Instances.swapInstanceComponent(this, instanceId, componentId, options)
}
syncInstances(componentId: string): void {
diff --git a/packages/scene-graph/src/instances.ts b/packages/scene-graph/src/instances.ts
index 1d52a6c1a..ce9b954c7 100644
--- a/packages/scene-graph/src/instances.ts
+++ b/packages/scene-graph/src/instances.ts
@@ -94,10 +94,20 @@ function recordNestedSwap(graph: SceneGraph, instance: SceneNode, componentId: s
graph.updateNode(owner.id, { instanceOverrides: owner.instanceOverrides })
}
+export interface SwapInstanceOptions {
+ /**
+ * Keep the instance's name even when it is its old component's. A swap otherwise renames such
+ * an instance after the new component, as Figma does; a view that only shows another variant,
+ * such as preview, keeps names so layer paths stay the same.
+ */
+ keepName?: boolean
+}
+
export function swapInstanceComponent(
graph: SceneGraph,
instanceId: string,
- componentId: string
+ componentId: string,
+ { keepName = false }: SwapInstanceOptions = {}
): void {
const instance = graph.nodes.get(instanceId)
const component = graph.nodes.get(componentId)
@@ -112,7 +122,8 @@ export function swapInstanceComponent(
copyProp(updates, source, key)
}
- if (!previousComponent || instance.name === previousComponent.name) updates.name = component.name
+ if (!keepName && (!previousComponent || instance.name === previousComponent.name))
+ updates.name = component.name
const childIds = Array.from(instance.childIds)
const slotContent = detachOwnedSlotContent(graph, instance)
diff --git a/packages/scene-graph/tests/instances/swap.test.ts b/packages/scene-graph/tests/instances/swap.test.ts
new file mode 100644
index 000000000..e3a8ae3e5
--- /dev/null
+++ b/packages/scene-graph/tests/instances/swap.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, test } from 'bun:test'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+/** A set with two variants and an instance of the first, left with the variant's name. */
+function setWithInstance() {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const set = graph.createNode('COMPONENT_SET', pageId, { name: 'Switch' })
+ const off = graph.createNode('COMPONENT', set.id, { name: 'State=Off' })
+ const on = graph.createNode('COMPONENT', set.id, { name: 'State=On' })
+ const instance = graph.createInstance(off.id, pageId)
+ if (!instance) throw new Error('No instance')
+ return { graph, instance, on }
+}
+
+describe('swapping an instance', () => {
+ test("renames an instance named after its component, as Figma does", () => {
+ const { graph, instance, on } = setWithInstance()
+ graph.swapInstanceComponent(instance.id, on.id)
+ expect(graph.getNode(instance.id)?.name).toBe('State=On')
+ })
+
+ test('keeps the name when asked, so a view showing another variant keeps layer paths', () => {
+ const { graph, instance, on } = setWithInstance()
+ graph.swapInstanceComponent(instance.id, on.id, { keepName: true })
+ expect(graph.getNode(instance.id)?.name).toBe('State=Off')
+ expect(graph.getNode(instance.id)?.componentId).toBe(on.id)
+ })
+})
diff --git a/packages/vue/src/canvas/islands/IslandLayer.vue b/packages/vue/src/canvas/islands/IslandLayer.vue
index 3bbac62cf..939c13c18 100644
--- a/packages/vue/src/canvas/islands/IslandLayer.vue
+++ b/packages/vue/src/canvas/islands/IslandLayer.vue
@@ -2,6 +2,7 @@
import { computed } from 'vue'
import { playIslandRoots, type PlayState } from '@open-pencil/core/editor'
+import type { ViewportTransform } from '@open-pencil/core/geometry'
import { useEditor } from '#vue/editor/context'
@@ -11,11 +12,18 @@ import Island from './Island.vue'
* The live islands of a previewing canvas pane, laid over the canvas at its pan and zoom. The
* canvas leaves these layers to the islands; wheel gestures over them still pan and zoom it.
*/
-const { view, canvas } = defineProps<{
+const { view, canvas, drawn } = defineProps<{
view: { panX: number; panY: number; zoom: number; currentPageId: string; play: PlayState | null }
/** The canvas that wheel gestures over the islands are passed on to. */
canvas: HTMLElement | null
+ /**
+ * The pan and zoom of the canvas's last drawn frame. The islands follow it rather than the
+ * live view, which runs ahead of the drawing while panning and zooming fast.
+ */
+ drawn?: ViewportTransform | null
}>()
+
+const placement = computed(() => drawn ?? view)
const editor = useEditor()
const islands = computed(() => {
@@ -43,7 +51,9 @@ function forwardWheel(event: WheelEvent) {
>
<div
class="absolute top-0 left-0 origin-top-left"
- :style="{ transform: `translate(${view.panX}px, ${view.panY}px) scale(${view.zoom})` }"
+ :style="{
+ transform: `translate(${placement.panX}px, ${placement.panY}px) scale(${placement.zoom})`
+ }"
>
<Island
v-for="island in islands"
diff --git a/packages/vue/src/canvas/surface/lifecycle.ts b/packages/vue/src/canvas/surface/lifecycle.ts
index 526fc2974..4d128f908 100644
--- a/packages/vue/src/canvas/surface/lifecycle.ts
+++ b/packages/vue/src/canvas/surface/lifecycle.ts
@@ -140,8 +140,9 @@ export function createCanvasSurfaceManager({
function renderNow() {
if (!state.renderer || isDestroyed()) return
state.renderer.overlayObstacles = overlayObstacles()
+ const view = options?.getRenderState?.() ?? editor.state
state.renderer.renderFromEditorState(
- options?.getRenderState?.() ?? editor.state,
+ view,
editor.graph,
editor.textEditor,
canvasRef.value?.clientWidth ?? 0,
@@ -151,6 +152,7 @@ export function createCanvasSurfaceManager({
editor.isInteractiveEditing()
)
renderLoop.markRendered()
+ options?.onFrame?.({ panX: view.panX, panY: view.panY, zoom: view.zoom })
acknowledgePresentation()
clearSceneBackingRenderTimer()
if (options?.layer === 'scene' && state.renderer.tiledScenePending) {
diff --git a/packages/vue/src/canvas/surface/types.ts b/packages/vue/src/canvas/surface/types.ts
index be31d3730..0069081a5 100644
--- a/packages/vue/src/canvas/surface/types.ts
+++ b/packages/vue/src/canvas/surface/types.ts
@@ -1,4 +1,5 @@
import type { EditorState } from '@open-pencil/core/editor'
+import type { ViewportTransform } from '@open-pencil/core/geometry'
import type { Rect } from '@open-pencil/scene-graph/primitives'
import type { PresentationColorSpace } from '#vue/canvas/surface/color-space'
@@ -53,6 +54,12 @@ export interface UseCanvasOptions {
* document graph, history, and editor event bus.
*/
getRenderState?: () => EditorState
+ /**
+ * Called after each frame this canvas draws, with the pan and zoom it was drawn at. DOM laid
+ * over the canvas, such as preview islands, follows these to stay in step with the drawing
+ * instead of running ahead of it while the canvas is still catching up.
+ */
+ onFrame?: (view: ViewportTransform) => void
/**
* Receives this canvas surface's CSS viewport size after creation and resize.
*/
diff --git a/src/components/EditorCanvas.vue b/src/components/EditorCanvas.vue
index 501e0c2e1..f5adf0e29 100644
--- a/src/components/EditorCanvas.vue
+++ b/src/components/EditorCanvas.vue
@@ -7,7 +7,7 @@ import {
PopoverPortal,
PopoverRoot
} from 'reka-ui'
-import { computed, onUnmounted, ref, useTemplateRef, watch, type Component } from 'vue'
+import { computed, onUnmounted, ref, shallowRef, useTemplateRef, watch, type Component } from 'vue'
import IconLucidePanelBottom from '~icons/lucide/panel-bottom'
import IconLucidePanelLeft from '~icons/lucide/panel-left'
import IconLucidePanelRight from '~icons/lucide/panel-right'
@@ -17,6 +17,7 @@ import {
AUTO_LAYOUT_PADDING_EDITOR_OFFSET_X,
AUTO_LAYOUT_PADDING_EDITOR_OFFSET_Y
} from '@open-pencil/core/constants'
+import type { ViewportTransform } from '@open-pencil/core/geometry'
import {
PlayIslands,
toolCursor,
@@ -82,8 +83,14 @@ const shouldSuspendRender = () =>
store.state.preparation.kind !== 'font-retry' &&
store.state.preparation.phase !== 'preparing-render'
+/** The pan and zoom of the scene's last drawn frame, which preview islands follow. */
+const drawnView = shallowRef<ViewportTransform | null>(null)
+
useCanvas(sceneCanvasRef, store, {
layer: 'scene',
+ onFrame: (view) => {
+ drawnView.value = view
+ },
sceneRenderer: appRuntimeConfig.sceneRenderer,
onReady: store.markCanvasReady,
shouldSuspendRender,
@@ -230,7 +237,7 @@ const cursor = computed(() =>
:style="{ cursor }"
class="absolute inset-0 block size-full touch-none outline-none"
/>
- <PlayIslands :view="paneView" :canvas="canvasRef" />
+ <PlayIslands :view="paneView" :drawn="drawnView" :canvas="canvasRef" />
<AppDropOverlay :visible="isDraggingOver" />
<IssueMarkerTooltip :marker="hoveredIssueMarker" :canvas="canvasRef" />
<CanvasLabelEditor
diff --git a/tests/e2e/components/behaviours.spec.ts b/tests/e2e/components/behaviours.spec.ts
index 9ec8f58bf..4509157f9 100644
--- a/tests/e2e/components/behaviours.spec.ts
+++ b/tests/e2e/components/behaviours.spec.ts
@@ -15,9 +15,12 @@ async function startPreview() {
await expect(editor.page.getByRole('button', { name: /Leave preview/ })).toBeVisible()
}
-/** A Switch set whose State=On and State=Off variants differ, and an Off instance below it. */
-async function createSwitch() {
- return editor.page.evaluate(() => {
+/**
+ * A Switch set whose State=On and State=Off variants differ, and an Off instance below it,
+ * either on the page or inside a frame, as a settings row holds one.
+ */
+async function createSwitch({ nested = false } = {}) {
+ return editor.page.evaluate((inFrame) => {
const store = window.openPencil?.getStore?.()
if (!store) throw new Error('OpenPencil store not initialized')
const graph = store.graph
@@ -64,23 +67,43 @@ async function createSwitch() {
}
variant('On', 0, true)
const off = variant('Off', 1, false)
- const instance = graph.createInstance(off.id, pageId, { x: 120, y: 260 })
+ const row = inFrame
+ ? graph.createNode('FRAME', pageId, {
+ name: 'Settings',
+ x: 120,
+ y: 260,
+ width: 200,
+ height: 60
+ })
+ : undefined
+ const instance = row
+ ? graph.createInstance(off.id, row.id, { x: 12, y: 12 })
+ : graph.createInstance(off.id, pageId, { x: 120, y: 260 })
if (!instance) throw new Error('Instance not created')
store.select([set.id])
- return { setId: set.id, offId: off.id, instanceId: instance.id }
- })
+ return {
+ setId: set.id,
+ offId: off.id,
+ instanceId: instance.id,
+ islandId: row?.id ?? instance.id
+ }
+ }, nested)
}
-test('a Switch behaviour flips in preview and leaves the document alone', async () => {
- const ids = await createSwitch()
- await editor.canvas.waitForRender()
-
+/** Adds the Switch behaviour to the selected set, binding its value to State. */
+async function addSwitchBehaviour() {
const section = propertySection(editor.page, 'Behaviour')
await section.getByRole('button', { name: 'Add behaviour' }).click()
await editor.page.getByRole('option', { name: /Switch/ }).click()
await section.getByRole('combobox', { name: 'Checked' }).click()
await editor.page.getByRole('option', { name: 'State' }).click()
await expect(section.getByText('Ready', { exact: true })).toBeVisible()
+}
+
+test('a Switch behaviour flips in preview and leaves the document alone', async () => {
+ const ids = await createSwitch()
+ await editor.canvas.waitForRender()
+ await addSwitchBehaviour()
await startPreview()
// The instance runs as Reka UI's Switch, drawn by the set's variants.
@@ -106,6 +129,61 @@ test('a Switch behaviour flips in preview and leaves the document alone', async
await expect(editor.page.getByRole('button', { name: /^Preview/ })).toBeVisible()
})
+test('a switch inside a frame, named after its variant, toggles both ways in preview', async () => {
+ // Its layer path includes its name, which a variant switch used to rename to State=On.
+ const ids = await createSwitch({ nested: true })
+ await editor.canvas.waitForRender()
+ await addSwitchBehaviour()
+
+ await startPreview()
+ const control = island(ids.islandId).getByRole('switch')
+ for (const checked of ['true', 'false', 'true']) {
+ await control.click()
+ await expect(control).toHaveAttribute('aria-checked', checked)
+ }
+ await editor.page.keyboard.press('Escape')
+})
+
+test('preview islands move with the frames the canvas draws, not ahead of them', async () => {
+ const ids = await createSwitch({ nested: true })
+ await editor.canvas.waitForRender()
+ await addSwitchBehaviour()
+ await startPreview()
+ await expect(island(ids.islandId).getByRole('switch')).toBeVisible()
+
+ const layer = editor.page.getByTestId('play-islands').locator(':scope > div')
+ const placed = await layer.evaluate((element) => element.style.transform)
+ // Hold the canvas's drawing, as a slow frame does, and move the view meanwhile.
+ const held = await editor.page.evaluateHandle(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const preparation = store.preparationController.begin({
+ kind: 'document-open',
+ phase: 'materializing'
+ })
+ store.pan(80, 40)
+ return preparation
+ })
+ try {
+ await editor.page.evaluate(
+ () =>
+ new Promise<void>((resolve) => {
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()))
+ })
+ )
+ expect(await layer.evaluate((element) => element.style.transform)).toBe(placed)
+
+ // Drawing resumes: the islands follow the pan, which the canvas has now drawn.
+ await held.evaluate((preparation) => preparation.complete())
+ await expect.poll(() => layer.evaluate((element) => element.style.transform)).not.toBe(placed)
+ } finally {
+ // Never leave the canvas held for later tests; completing again does nothing.
+ await held.evaluate((preparation) => preparation.complete())
+ await held.dispose()
+ }
+ await editor.page.keyboard.press('Escape')
+})
+
test('a Button behaviour maps its states and shows them in preview', async () => {
const ids = await editor.page.evaluate(() => {
const store = window.openPencil?.getStore?.()