Skip to content

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

refactor: resolve canvas behaviour from view profiles (#1591)

Danila Poyarkov10f0c0d78c9c
diff --git a/changes/1591/breaking.md b/changes/1591/breaking.md
new file mode 100644
index 000000000..ee6ca235e
--- /dev/null
+++ b/changes/1591/breaking.md
@@ -0,0 +1 @@
+- `@open-pencil/core` replaces `state.play` and the `PlayState` type with `state.canvasView` (`CanvasView`, `{ id: 'edit' }` or `{ id: 'play', revision }`); read how a canvas behaves with `resolveEditorProfile(state)` rather than checking the view.
diff --git a/oxlint.json b/oxlint.json
index 508b85831..35b855568 100644
--- a/oxlint.json
+++ b/oxlint.json
@@ -231,6 +231,7 @@
"open-pencil/no-flat-kiwi-modules": "error",
"open-pencil/no-bun-globals-in-cli": "error",
"open-pencil/no-top-level-prefixed-test-files": "error",
+ "open-pencil/no-canvas-view-checks": "error",
"open-pencil/no-conditional-object-spreads": "error",
"open-pencil/no-sibling-domain-prefixed-files": "error",
"array-callback-return": "error",
diff --git a/packages/core/AGENTS.md b/packages/core/AGENTS.md
index 633e57dbe..6c4a4f1b4 100644
--- a/packages/core/AGENTS.md
+++ b/packages/core/AGENTS.md
@@ -52,6 +52,7 @@ Renderer, layout, editor, Figma API, tools, clipboard, vector conversion, and do
- Numeric geometry edits own a `beginNodePreview()` handle with `update`, `commit`, and `cancel`. It captures all affected fields and layout children, publishes the complete delta once, and restores exact originals on cancellation. Selection, page, and graph changes and disposal cancel the old edit; trailing input must not target the new selection. Controls must close previews even when a gesture returns to its starting value.
- Rotation previews change through `setRotationPreview()` and `rotation:preview-changed`; cancellation must close the owning gesture without deselecting or committing it.
- A read-only document (`setReadOnly`) refuses every editor action not listed in `READ_ONLY_ACTIONS`, so a new action that only reads, selects, or navigates is added there; front ends ignore the refusal and change only what behaves differently, such as the toolbar (`packages/core/tests/editor/read-only.test.ts`).
+- A canvas pane behaves by the profile its view resolves to (`resolveEditorProfile` in `packages/core/src/editor/views/`): pointer, shortcuts, editing chrome, live islands, panels, and where leaving goes. A new view is a new profile, and code outside the views and state modules reads profile values, never the view, which `open-pencil/no-canvas-view-checks` enforces (`packages/core/tests/editor/views/profile.test.ts`).
- Renderer interaction policy uses explicit `beginInteractiveEdit()` leases and `isInteractiveEditing()`, not undo batching. Release leases on every terminal path. Keep live queries callable across app facades that spread editor actions.
- `packages/core/src/editor/history/atomic-tool.ts` owns synchronous property/variable transactions for AI, MCP, and WebMCP tools; see Tools above.
diff --git a/packages/core/src/canvas/renderer/pipeline.ts b/packages/core/src/canvas/renderer/pipeline.ts
index 68d799cfc..30fef19b3 100644
--- a/packages/core/src/canvas/renderer/pipeline.ts
+++ b/packages/core/src/canvas/renderer/pipeline.ts
@@ -7,6 +7,7 @@ import { needsImagePreviews } from '#core/canvas/images/previews'
import type { RenderOverlays, SkiaRenderer } from '#core/canvas/renderer'
import { playIslandRoots } from '#core/editor/play/islands'
import type { EditorState } from '#core/editor/types'
+import { resolveEditorProfile } from '#core/editor/views/profile'
import { emitNavigationTrace } from '#core/profiler'
import { drawChromePass, drawLabelPass, drawOverlayPass } from './overlay-pass'
@@ -78,17 +79,16 @@ export function renderFromEditorState(
r.navigationPhase = state.navigation.phase
r.navigationGeneration = state.navigation.generation
r.readOnly = state.readOnly
- // A previewing canvas shows the design as it runs: no selection, hover, or edit chrome.
- const previewing = state.play !== null
+ const { editChrome, live } = resolveEditorProfile(state)
render(
r,
graph,
- previewing ? new Set<string>() : state.selectedIds,
+ editChrome ? state.selectedIds : new Set<string>(),
{
- playing: previewing,
- playIslands: previewing ? new Set(playIslandRoots(graph, state.currentPageId)) : undefined,
- hoveredNodeId: previewing ? null : state.hoveredNodeId,
- showPixelGrid: !previewing && state.showPixelGrid !== false,
+ playing: !editChrome,
+ playIslands: live ? new Set(playIslandRoots(graph, state.currentPageId)) : undefined,
+ hoveredNodeId: editChrome ? state.hoveredNodeId : null,
+ showPixelGrid: editChrome && state.showPixelGrid !== false,
gradientEdit: state.gradientEdit,
transforming: state.transforming,
measurementMode: state.measurementMode,
diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.ts
index 26822e51b..e4baba6b2 100644
--- a/packages/core/src/editor/create.ts
+++ b/packages/core/src/editor/create.ts
@@ -50,7 +50,6 @@ import { createDesignIssueActions } from './issues'
import { createLineEndActions } from './line-ends'
import { createNodeActions } from './nodes'
import { createPageActions } from './pages'
-import { createPlayActions } from './play/actions'
import { createReadOnlyActions, guardReadOnly, guardUndo, READ_ONLY_TOOLS } from './read-only'
import { createSelectionActions } from './selection'
import { createShaderActions } from './shaders/actions'
@@ -76,6 +75,7 @@ import { createUndoActions } from './undo'
import { createVariableActions } from './variables'
import { createVectorizeActions } from './vectorize'
import { createViewportActions } from './viewport'
+import { createCanvasViewActions } from './views'
export { createDefaultEditorState } from './state'
@@ -323,7 +323,7 @@ export function createEditor(options?: EditorOptions) {
const lineEnds = createLineEndActions(ctx, nodes.beginNodePreview)
const shaders = createShaderActions(ctx, nodes)
const alignment = createAlignmentActions(ctx)
- const preview = createPlayActions(ctx)
+ const canvasViews = createCanvasViewActions(ctx)
const clipboardBridge = createClipboardBridge(clipboard, selection)
const componentBridge = createComponentBridge(components, selection, structure, pages)
const structureBridge = createStructureBridge(structure, selection)
@@ -482,8 +482,8 @@ export function createEditor(options?: EditorOptions) {
// Alignment (align, flip, rotate)
...alignment,
- // Preview: instances with a behaviour respond to the pointer on this canvas
- ...preview,
+ // Canvas views: editing, or a preview where instances with a behaviour respond to the pointer
+ ...canvasViews,
// Bitmap-to-vector replacement
...vectorize,
diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.ts
index 553f99cfe..e4ea16abb 100644
--- a/packages/core/src/editor/index.ts
+++ b/packages/core/src/editor/index.ts
@@ -34,7 +34,8 @@ export { pastedPropertyChanges } from './clipboard/paste/properties'
export { resolvePasteTarget } from './clipboard/paste/target'
export { playIslandRoots } from './play/islands'
export { resolvePlayState, type InstanceState } from './play/states'
-export type { PlayState } from './play/actions'
+export { EDIT_VIEW, resolveEditorProfile } from './views'
+export type { CanvasView, EditorProfile } from './views'
export type { ShaderRasterizer } from './shaders/types'
export type { ShaderPaintList } from './shaders/actions'
export type { Editor } from './create'
diff --git a/packages/core/src/editor/play/actions.ts b/packages/core/src/editor/play/actions.ts
deleted file mode 100644
index 594099b60..000000000
--- a/packages/core/src/editor/play/actions.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import type { EditorContext } from '#core/editor/types'
-
-/** A previewing canvas: its islands remount whenever the revision changes. */
-export interface PlayState {
- revision: number
-}
-
-export function createPlayActions(ctx: EditorContext) {
- /** Preview this canvas: layers holding controls run as live components. */
- function startPlay(): void {
- if (ctx.state.play) return
- ctx.state.play = { revision: 0 }
- ctx.state.hoveredNodeId = null
- ctx.requestRepaint()
- }
-
- /** Go back to editing; the canvas draws every layer again. */
- function stopPlay(): void {
- if (!ctx.state.play) return
- ctx.state.play = null
- ctx.requestRepaint()
- }
-
- function togglePlay(): void {
- if (ctx.state.play) stopPlay()
- else startPlay()
- }
-
- /** Put every control back as designed by running the islands afresh. */
- function resetPlay(): void {
- if (ctx.state.play) ctx.state.play = { revision: ctx.state.play.revision + 1 }
- }
-
- // Another document's layers start from their designed state, not from the old islands'.
- ctx.onEditorEvent('graph:replaced', resetPlay)
-
- return { startPlay, stopPlay, togglePlay, resetPlay }
-}
diff --git a/packages/core/src/editor/read-only/actions.ts b/packages/core/src/editor/read-only/actions.ts
index 2bb6c15bc..0773816da 100644
--- a/packages/core/src/editor/read-only/actions.ts
+++ b/packages/core/src/editor/read-only/actions.ts
@@ -114,6 +114,7 @@ export const READ_ONLY_ACTIONS: ReadonlySet<string> = new Set([
'zoomToSelection',
// Preview
+ 'leaveCanvasView',
'resetPlay',
'startPlay',
'stopPlay',
diff --git a/packages/core/src/editor/state/view.ts b/packages/core/src/editor/state/view.ts
index c3288d4ff..5b81164e4 100644
--- a/packages/core/src/editor/state/view.ts
+++ b/packages/core/src/editor/state/view.ts
@@ -34,7 +34,7 @@ export function createDefaultEditorViewState(pageId: string): EditorViewState {
nodeEditState: null,
cursorCanvasX: null,
cursorCanvasY: null,
- play: null
+ canvasView: { id: 'edit' }
}
}
@@ -54,7 +54,8 @@ export function copyEditorViewState(source: EditorViewState): EditorViewState {
connectorTarget: structuredClone(source.connectorTarget),
pageColor: { ...source.pageColor },
navigation: { ...source.navigation },
- nodeEditState: structuredClone(source.nodeEditState)
+ nodeEditState: structuredClone(source.nodeEditState),
+ canvasView: { ...source.canvasView }
}
}
diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.ts
index 56fe8842b..65bdf82de 100644
--- a/packages/core/src/editor/types.ts
+++ b/packages/core/src/editor/types.ts
@@ -26,9 +26,9 @@ import type {
} from '#core/canvas/renderer/types'
import type { InterfaceTheme } from '#core/constants'
import type { ConnectorTarget } from '#core/editor/connectors/attach'
-import type { PlayState } from '#core/editor/play/actions'
import type { SnappingPreferences } from '#core/editor/preferences'
import type { ShaderRasterizer } from '#core/editor/shaders/types'
+import type { CanvasView } from '#core/editor/views/types'
import type { RotationPreview, ShapeHandleKind } from '#core/geometry'
import type { IconProvider } from '#core/icons/provider'
import type { TextEditor } from '#core/text/editor'
@@ -186,8 +186,8 @@ export interface EditorViewState {
nodeEditState?: RenderOverlays['nodeEditState'] | null
cursorCanvasX?: number | null
cursorCanvasY?: number | null
- /** This canvas's preview, or null while it edits. */
- play: PlayState | null
+ /** What this canvas shows: the design being edited, or running as a preview. */
+ canvasView: CanvasView
}
export type NavigationPhase = 'idle' | 'pan' | 'zoom' | 'momentum' | 'settling'
diff --git a/packages/core/src/editor/views/actions.ts b/packages/core/src/editor/views/actions.ts
new file mode 100644
index 000000000..35f029c0a
--- /dev/null
+++ b/packages/core/src/editor/views/actions.ts
@@ -0,0 +1,47 @@
+import type { EditorContext } from '#core/editor/types'
+
+import { EDIT_VIEW, resolveEditorProfile } from './profile'
+import type { CanvasView } from './types'
+
+export function createCanvasViewActions(ctx: EditorContext) {
+ function setCanvasView(view: CanvasView): void {
+ ctx.state.canvasView = view
+ ctx.requestRepaint()
+ }
+
+ /** Leaves the canvas's view for the one it returns to; false when there is none to leave. */
+ function leaveCanvasView(): boolean {
+ const target = resolveEditorProfile(ctx.state).leaveTo
+ if (!target) return false
+ setCanvasView(target)
+ return true
+ }
+
+ /** Preview this canvas: layers holding controls run as live components. */
+ function startPlay(): void {
+ if (ctx.state.canvasView.id === 'play') return
+ ctx.state.hoveredNodeId = null
+ setCanvasView({ id: 'play', revision: 0 })
+ }
+
+ /** Go back to editing; the canvas draws every layer again. */
+ function stopPlay(): void {
+ if (ctx.state.canvasView.id === 'play') setCanvasView(EDIT_VIEW)
+ }
+
+ function togglePlay(): void {
+ if (ctx.state.canvasView.id === 'play') stopPlay()
+ else startPlay()
+ }
+
+ /** Put every control back as designed by running the islands afresh. */
+ function resetPlay(): void {
+ const view = ctx.state.canvasView
+ if (view.id === 'play') ctx.state.canvasView = { id: 'play', revision: view.revision + 1 }
+ }
+
+ // Another document's layers start from their designed state, not from the old islands'.
+ ctx.onEditorEvent('graph:replaced', resetPlay)
+
+ return { leaveCanvasView, startPlay, stopPlay, togglePlay, resetPlay }
+}
diff --git a/packages/core/src/editor/views/index.ts b/packages/core/src/editor/views/index.ts
new file mode 100644
index 000000000..394500870
--- /dev/null
+++ b/packages/core/src/editor/views/index.ts
@@ -0,0 +1,3 @@
+export { createCanvasViewActions } from './actions'
+export { EDIT_VIEW, resolveEditorProfile } from './profile'
+export type { CanvasView, EditorProfile } from './types'
diff --git a/packages/core/src/editor/views/profile.ts b/packages/core/src/editor/views/profile.ts
new file mode 100644
index 000000000..fa8385581
--- /dev/null
+++ b/packages/core/src/editor/views/profile.ts
@@ -0,0 +1,34 @@
+import type { EditorViewState } from '#core/editor/types'
+
+import type { CanvasView, EditorProfile } from './types'
+
+export const EDIT_VIEW: CanvasView = { id: 'edit' }
+
+const EDIT_PROFILE: EditorProfile = {
+ pointer: 'tools',
+ shortcuts: 'all',
+ editChrome: true,
+ live: null,
+ panels: true,
+ leaveTo: null
+}
+
+/** A preview runs the design: the canvas only pans, and its controls take the pointer. */
+function playProfile(revision: number): EditorProfile {
+ return {
+ pointer: 'pan',
+ shortcuts: 'view',
+ editChrome: false,
+ live: { revision },
+ panels: false,
+ leaveTo: EDIT_VIEW
+ }
+}
+
+/**
+ * The profile a canvas behaves by. Pass the pane's own state, since each pane shows its own view.
+ */
+export function resolveEditorProfile(state: Pick<EditorViewState, 'canvasView'>): EditorProfile {
+ const view = state.canvasView
+ return view.id === 'play' ? playProfile(view.revision) : EDIT_PROFILE
+}
diff --git a/packages/core/src/editor/views/types.ts b/packages/core/src/editor/views/types.ts
new file mode 100644
index 000000000..de13712b7
--- /dev/null
+++ b/packages/core/src/editor/views/types.ts
@@ -0,0 +1,28 @@
+/**
+ * What a canvas pane shows: the design being edited, or the design running as a preview whose
+ * controls respond to the pointer. Each pane has its own.
+ */
+export type CanvasView = { id: 'edit' } | { id: 'play'; revision: number }
+
+/**
+ * How the editor behaves for a canvas, resolved from its view. Front ends read these values
+ * rather than asking which view is showing, so a new view is a new profile, not a new branch at
+ * every place that behaves differently.
+ */
+export interface EditorProfile {
+ /** What the pointer does on the canvas: every tool, or only panning and zooming. */
+ pointer: 'tools' | 'pan'
+ /** Which shortcuts run: every one, or only those that switch or leave the view. */
+ shortcuts: 'all' | 'view'
+ /** Whether the canvas draws what editing needs: selection, hover, pixel grid, and rulers. */
+ editChrome: boolean
+ /**
+ * The run of layers that hold controls as live components, and of animated shaders; a new
+ * revision starts them afresh. Null while layers draw as designed.
+ */
+ live: { revision: number } | null
+ /** Whether the editor's panels stay beside a canvas shown on its own. */
+ panels: boolean
+ /** The view leaving this one returns to, as Escape does, or null when there is none. */
+ leaveTo: CanvasView | null
+}
diff --git a/packages/core/tests/editor/play/states.test.ts b/packages/core/tests/editor/play/states.test.ts
index 897e07bc5..b3a0b1c80 100644
--- a/packages/core/tests/editor/play/states.test.ts
+++ b/packages/core/tests/editor/play/states.test.ts
@@ -114,7 +114,7 @@ describe('preview islands', () => {
editor.startPlay()
editor.resetPlay()
editor.replaceGraph(new SceneGraph())
- expect(editor.state.play).toEqual({ revision: 2 })
+ expect(editor.state.canvasView).toEqual({ id: 'play', revision: 2 })
})
test('a copy paints bound colors in the mode the canvas is showing, not as they were saved', () => {
diff --git a/packages/core/tests/editor/views/profile.test.ts b/packages/core/tests/editor/views/profile.test.ts
new file mode 100644
index 000000000..536cbecc0
--- /dev/null
+++ b/packages/core/tests/editor/views/profile.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createEditor, resolveEditorProfile } from '@open-pencil/core'
+
+describe('canvas view profiles', () => {
+ test('an editing canvas takes every tool and shortcut and draws its chrome', () => {
+ const editor = createEditor()
+ expect(resolveEditorProfile(editor.state)).toEqual({
+ pointer: 'tools',
+ shortcuts: 'all',
+ editChrome: true,
+ live: null,
+ panels: true,
+ leaveTo: null
+ })
+ })
+
+ test('a preview only pans, keeps view shortcuts, and runs its controls live', () => {
+ const editor = createEditor()
+ editor.startPlay()
+ expect(resolveEditorProfile(editor.state)).toEqual({
+ pointer: 'pan',
+ shortcuts: 'view',
+ editChrome: false,
+ live: { revision: 0 },
+ panels: false,
+ leaveTo: { id: 'edit' }
+ })
+ })
+
+ test('resetting a preview starts its live run afresh', () => {
+ const editor = createEditor()
+ editor.startPlay()
+ editor.resetPlay()
+ expect(resolveEditorProfile(editor.state).live).toEqual({ revision: 1 })
+ })
+
+ test('leaving a preview returns to editing; an editing canvas has nothing to leave', () => {
+ const editor = createEditor()
+ expect(editor.leaveCanvasView()).toBe(false)
+ editor.startPlay()
+ expect(editor.leaveCanvasView()).toBe(true)
+ expect(editor.state.canvasView).toEqual({ id: 'edit' })
+ })
+
+ test('a read-only document can still preview and leave it', () => {
+ const editor = createEditor()
+ editor.setReadOnly(true)
+ editor.startPlay()
+ expect(editor.leaveCanvasView()).toBe(true)
+ })
+})
diff --git a/packages/docs/.vitepress/theme/landing/stage/StagePreviewControls.vue b/packages/docs/.vitepress/theme/landing/stage/StagePreviewControls.vue
index ab49502d5..265af0b65 100644
--- a/packages/docs/.vitepress/theme/landing/stage/StagePreviewControls.vue
+++ b/packages/docs/.vitepress/theme/landing/stage/StagePreviewControls.vue
@@ -2,6 +2,7 @@
import { tinykeys } from 'tinykeys'
import { onScopeDispose } from 'vue'
+import { resolveEditorProfile } from '@open-pencil/core'
import { useI18n } from '@open-pencil/vue/i18n'
import { getActiveEditorStoreOrNull, useEditorStore } from '@/app/editor/active-store'
@@ -34,7 +35,7 @@ if (keys) {
<template>
<WorkspacePill
- v-if="store.state.play"
+ v-if="resolveEditorProfile(store.state).live"
mode="preview"
:document-name="store.state.documentName"
:shortcut="shortcut"
diff --git a/packages/docs/development/behaviours-and-preview.md b/packages/docs/development/behaviours-and-preview.md
index d54fccbc9..581130f3e 100644
--- a/packages/docs/development/behaviours-and-preview.md
+++ b/packages/docs/development/behaviours-and-preview.md
@@ -30,7 +30,7 @@ All of them write the same model.
## Preview islands
-Preview is a per-pane mode (`EditorViewState.play`). It runs controls as real components; it never simulates them on the canvas.
+Preview is a per-pane canvas view (`EditorViewState.canvasView`, `{ id: 'play', revision }`). It runs controls as real components; it never simulates them on the canvas. How the editor behaves in a view comes from its profile (`resolveEditorProfile` in `packages/core/src/editor/views/`): the pointer only pans, only shortcuts that switch or leave the view run, the canvas draws no editing chrome, a lone previewing pane hides the panels, and Escape returns to editing. Front ends read those values rather than the view's id.
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.
diff --git a/packages/vue/src/canvas/islands/IslandLayer.vue b/packages/vue/src/canvas/islands/IslandLayer.vue
index 733389080..074bb53b8 100644
--- a/packages/vue/src/canvas/islands/IslandLayer.vue
+++ b/packages/vue/src/canvas/islands/IslandLayer.vue
@@ -2,7 +2,7 @@
import { computedAsync } from '@vueuse/core'
import { computed, watch } from 'vue'
-import { playIslandRoots, type PlayState } from '@open-pencil/core'
+import { playIslandRoots, resolveEditorProfile, type CanvasView } from '@open-pencil/core'
import type { ViewportTransform } from '@open-pencil/core/geometry'
import { tokenStylesheet } from '@open-pencil/dom-css/export'
@@ -15,7 +15,7 @@ import Island from './Island.vue'
* canvas leaves these layers to the islands; wheel gestures over them still pan and zoom it.
*/
const { view, canvas, drawn } = defineProps<{
- view: { panX: number; panY: number; zoom: number; currentPageId: string; play: PlayState | null }
+ view: { panX: number; panY: number; zoom: number; currentPageId: string; canvasView: CanvasView }
/** The canvas that wheel gestures over the islands are passed on to. */
canvas: HTMLElement | null
/**
@@ -26,6 +26,8 @@ const { view, canvas, drawn } = defineProps<{
}>()
const placement = computed(() => drawn ?? view)
+/** The run the islands belong to, or null while the canvas edits and draws every layer. */
+const live = computed(() => resolveEditorProfile(view).live)
const editor = useEditor()
/**
@@ -36,7 +38,7 @@ const editor = useEditor()
const tokens = new CSSStyleSheet()
const tokensCSS = computedAsync(async () => {
void editor.state.sceneVersion
- if (!view.play) return ''
+ if (!live.value) return ''
const { css } = await tokenStylesheet(editor.graph, { format: 'css' })
return css.replaceAll(':root', ':host')
}, '')
@@ -44,7 +46,7 @@ watch(tokensCSS, (css) => tokens.replaceSync(css), { immediate: true })
const islands = computed(() => {
void editor.state.sceneVersion
- if (!view.play) return []
+ if (!live.value) return []
return playIslandRoots(editor.graph, view.currentPageId).map((id) => ({
id,
position: editor.graph.getAbsolutePosition(id)
@@ -60,7 +62,7 @@ function forwardWheel(event: WheelEvent) {
<template>
<div
- v-if="view.play"
+ v-if="live"
class="pointer-events-none absolute inset-0 overflow-hidden"
data-test-id="play-islands"
@wheel="forwardWheel"
@@ -75,7 +77,7 @@ function forwardWheel(event: WheelEvent) {
v-for="island in islands"
:key="island.id"
:root-id="island.id"
- :revision="view.play.revision"
+ :revision="live.revision"
:tokens="tokens"
class="pointer-events-auto absolute"
:style="{ left: `${island.position.x}px`, top: `${island.position.y}px` }"
diff --git a/packages/vue/src/canvas/surface/shader/playback.ts b/packages/vue/src/canvas/surface/shader/playback.ts
index 584424935..fe8467732 100644
--- a/packages/vue/src/canvas/surface/shader/playback.ts
+++ b/packages/vue/src/canvas/surface/shader/playback.ts
@@ -2,7 +2,7 @@ import { useRafFn, watchThrottled } from '@vueuse/core'
import type { createRendererFromJSON } from 'shaders/core'
import { onScopeDispose, watch } from 'vue'
-import type { Editor, EditorState } from '@open-pencil/core'
+import { resolveEditorProfile, type Editor, type EditorState } from '@open-pencil/core'
import type { SkiaRenderer } from '@open-pencil/core/canvas'
import type { Rect } from '@open-pencil/scene-graph/primitives'
import {
@@ -85,7 +85,7 @@ export function useShaderPlayback(options: {
editor: Editor
getRenderer: () => SkiaRenderer | null
/** The view this canvas draws: its pan, zoom, page, and whether it previews. */
- getView: () => Pick<EditorState, 'panX' | 'panY' | 'zoom' | 'currentPageId' | 'play'>
+ getView: () => Pick<EditorState, 'panX' | 'panY' | 'zoom' | 'currentPageId' | 'canvasView'>
getViewport: () => { width: number; height: number }
markDirty: () => void
}) {
@@ -259,7 +259,7 @@ export function useShaderPlayback(options: {
function sync() {
const view = getView()
- const playing = view.play !== null && canDrawShaders()
+ const playing = resolveEditorProfile(view).live !== null && canDrawShaders()
const wanted = playing ? shadersOnPage(editor, view.currentPageId) : new Map()
for (const [hash, player] of players) {
const shader = wanted.get(hash)
@@ -361,9 +361,17 @@ export function useShaderPlayback(options: {
}
}
- watch(() => [getView().play !== null, getView().currentPageId, editor.state.sceneVersion], sync, {
- immediate: true
- })
+ watch(
+ () => [
+ resolveEditorProfile(getView()).live !== null,
+ getView().currentPageId,
+ editor.state.sceneVersion
+ ],
+ sync,
+ {
+ immediate: true
+ }
+ )
// The view moving or the canvas resizing, as it does when preview hides the panels, changes
// what is on screen.
watchThrottled(
diff --git a/packages/vue/src/canvas/useCanvasInput.ts b/packages/vue/src/canvas/useCanvasInput.ts
index 60fa63910..9dedc6661 100644
--- a/packages/vue/src/canvas/useCanvasInput.ts
+++ b/packages/vue/src/canvas/useCanvasInput.ts
@@ -1,7 +1,7 @@
import { useEventListener } from '@vueuse/core'
import { onScopeDispose, ref, watch, type Ref } from 'vue'
-import type { Editor } from '@open-pencil/core'
+import { resolveEditorProfile, type Editor } from '@open-pencil/core'
import type { SceneNode } from '@open-pencil/scene-graph'
import { createAutoLayoutValueEdit } from '#vue/canvas/auto-layout/value-edit'
@@ -193,7 +193,7 @@ export function useCanvasInput(
} = createCanvasTransformInput(editor, setDrag)
function onDblClick(e: MouseEvent) {
- if (editor.state.play) return
+ if (resolveEditorProfile(editor.state).pointer === 'pan') return
const { cx, cy } = getCoords(e)
if (!editor.state.readOnly && valueEdit.start(cx, cy)) {
e.preventDefault()
@@ -206,8 +206,9 @@ export function useCanvasInput(
function onMouseDown(e: MouseEvent) {
onActivate?.()
if (!isEnabled()) return
- // Preview: controls live in islands above the canvas; the canvas itself only pans.
- if (editor.state.play && e.button === 0 && editor.state.activeTool !== 'HAND') {
+ // A canvas that only pans, as a preview's does, leaves its controls to the islands above it.
+ const panOnly = resolveEditorProfile(editor.state).pointer === 'pan'
+ if (panOnly && e.button === 0 && editor.state.activeTool !== 'HAND') {
e.preventDefault()
return
}
@@ -261,7 +262,7 @@ export function useCanvasInput(
onCursorMove(coords.cx, coords.cy)
}
- if (editor.state.play && !drag.value) return
+ if (resolveEditorProfile(editor.state).pointer === 'pan' && !drag.value) return
if (!drag.value) {
const { cx, cy } = coords
diff --git a/src/app/shell/keyboard/actions.ts b/src/app/shell/keyboard/actions.ts
index 18e13c637..eccc38dde 100644
--- a/src/app/shell/keyboard/actions.ts
+++ b/src/app/shell/keyboard/actions.ts
@@ -72,10 +72,7 @@ export function createKeyboardActions({
}
function escapeOrDeselect() {
- if (store.state.play) {
- store.stopPlay()
- return
- }
+ if (store.leaveCanvasView()) return
if (store.state.rotationPreview) {
store.setRotationPreview(null)
return
diff --git a/src/app/shell/keyboard/registry.ts b/src/app/shell/keyboard/registry.ts
index 97735b217..dafe749ff 100644
--- a/src/app/shell/keyboard/registry.ts
+++ b/src/app/shell/keyboard/registry.ts
@@ -2,6 +2,7 @@ import { useEventListener } from '@vueuse/core'
import { createKeybindingsHandler } from 'tinykeys'
import type { KeyBindingMap } from 'tinykeys'
+import { resolveEditorProfile } from '@open-pencil/core'
import { isCanvasTextInput } from '@open-pencil/vue/canvas/text-edit'
import { editorCommandMetadata, type EditorCommandId } from '@open-pencil/vue/editor/commands'
@@ -32,8 +33,8 @@ type ShortcutDefinition = {
run: ShortcutAction
shouldPreventDefault?: (event: KeyboardEvent) => boolean
global?: boolean
- /** Whether the shortcut also works while a canvas previews. */
- preview?: boolean
+ /** Whether the shortcut switches or leaves the canvas's view, so it runs in every view. */
+ view?: boolean
}
function commandShortcut(
@@ -217,7 +218,7 @@ export function registerKeyboardShortcuts(options: KeyboardShortcutOptions) {
id: 'toggle-preview',
keys: appMenuTinykeysShortcut('toggle-preview') ?? '$mod+Alt+Enter',
run: ({ actions }) => actions.togglePlay(),
- preview: true
+ view: true
},
{
id: 'toggle-rulers',
@@ -361,7 +362,7 @@ export function registerKeyboardShortcuts(options: KeyboardShortcutOptions) {
id: 'escape',
keys: 'Escape',
run: ({ actions }) => actions.escapeOrDeselect(),
- preview: true
+ view: true
},
siblingShortcut('selection.selectNextSibling'),
siblingShortcut('selection.selectPreviousSibling'),
@@ -370,9 +371,9 @@ export function registerKeyboardShortcuts(options: KeyboardShortcutOptions) {
const bindings: KeyBindingMap = {}
const globalBindings: KeyBindingMap = {}
- /** Keys that keep working while a canvas previews; everything else would edit the design. */
- const previewKeys = new Set(
- shortcuts.filter((shortcut) => shortcut.preview).flatMap((shortcut) => [shortcut.keys].flat())
+ /** Keys that switch or leave the canvas's view, which every view keeps. */
+ const viewKeys = new Set(
+ shortcuts.filter((shortcut) => shortcut.view).flatMap((shortcut) => [shortcut.keys].flat())
)
const historyKeys = new Set(
shortcuts
@@ -394,7 +395,8 @@ export function registerKeyboardShortcuts(options: KeyboardShortcutOptions) {
keys,
(event: KeyboardEvent) => {
if (shouldIgnoreShortcut(event, options, historyKeys.has(keys))) return
- if (options.store.state.play && !previewKeys.has(keys)) return
+ const { shortcuts: allowed } = resolveEditorProfile(options.store.state)
+ if (allowed === 'view' && !viewKeys.has(keys)) return
handler(event)
}
])
diff --git a/src/components/EditorCanvas.vue b/src/components/EditorCanvas.vue
index bacabf699..67449ff38 100644
--- a/src/components/EditorCanvas.vue
+++ b/src/components/EditorCanvas.vue
@@ -15,6 +15,7 @@ import IconLucidePanelLeft from '~icons/lucide/panel-left'
import IconLucidePanelRight from '~icons/lucide/panel-right'
import IconLucidePanelTop from '~icons/lucide/panel-top'
+import { resolveEditorProfile } from '@open-pencil/core'
import type { PlacedStatusLabel } from '@open-pencil/core/canvas'
import {
AUTO_LAYOUT_PADDING_EDITOR_OFFSET_X,
@@ -79,6 +80,7 @@ function updatePaneCursor(cx: number, cy: number) {
const getRenderState = paneId ? () => store.getPaneRenderState(paneId) : undefined
/** This pane's view: its pan, zoom, page, and whether it previews. */
const paneView = computed(() => (paneId ? store.getPaneRenderState(paneId) : store.state))
+const paneProfile = computed(() => resolveEditorProfile(paneView.value))
const onViewportResize = (width: number, height: number) => {
if (paneId) store.resizePane(paneId, width, height)
if (isActivePane.value) store.setViewportSize(width, height)
@@ -136,7 +138,7 @@ const {
// The scene canvas reports a canvas that cannot start.
onFailed: () => undefined,
get showRulers() {
- return appRuntimeConfig.showRulers && store.state.showRulers && paneView.value.play === null
+ return appRuntimeConfig.showRulers && store.state.showRulers && paneProfile.value.editChrome
},
getOverlayObstacles: () => canvasOverlayObstacles(canvasRef.value),
shouldSuspendRender,
diff --git a/src/components/editor/EditorWorkspace.vue b/src/components/editor/EditorWorkspace.vue
index 5d31eb90f..4d379a574 100644
--- a/src/components/editor/EditorWorkspace.vue
+++ b/src/components/editor/EditorWorkspace.vue
@@ -3,6 +3,7 @@ import { SplitterGroup, SplitterPanel, SplitterResizeHandle } from 'reka-ui'
import { tv } from 'tailwind-variants'
import { computed } from 'vue'
+import { resolveEditorProfile } from '@open-pencil/core'
import { formatShortcut } from '@open-pencil/vue/editor/commands'
import { useViewportKind } from '@open-pencil/vue/editor/viewport-kind'
import { useI18n } from '@open-pencil/vue/i18n'
@@ -58,8 +59,13 @@ function saveResizedLayout(layout: number[]) {
saveEditorLayout(layout)
}
const horizontalSplitterStyles = tv(splitterTheme)({ direction: 'horizontal' })
-/** One canvas previewing takes the whole window, in the canvas-only layout; split view keeps panels. */
-const playingAlone = computed(() => store.state.play !== null && store.visiblePaneCount.value <= 1)
+/**
+ * A canvas whose view hides the panels takes the whole window when it is the only one shown, in the
+ * canvas-only layout; split view keeps the panels for the other panes.
+ */
+const canvasAlone = computed(
+ () => !resolveEditorProfile(store.state).panels && store.visiblePaneCount.value <= 1
+)
const { editor } = useI18n()
// Until a room's document arrives there is nothing to edit, so its screen replaces the editor.
const { pending: roomPending } = useRoomActions()
@@ -71,7 +77,7 @@ const { pending: roomPending } = useRoomActions()
</div>
<SplitterGroup
- v-else-if="!isMobile && showChrome && store.state.showUI && !playingAlone"
+ v-else-if="!isMobile && showChrome && store.state.showUI && !canvasAlone"
:key="tab.id"
direction="horizontal"
class="flex-1 overflow-hidden"
@@ -149,7 +155,7 @@ const { pending: roomPending } = useRoomActions()
<EditorCanvas />
<ActiveRoomOverlay />
<WorkspacePill
- v-if="!isMobile && playingAlone"
+ v-if="!isMobile && canvasAlone"
mode="preview"
:document-name="store.state.documentName"
:shortcut="formatShortcut(appMenuShortcut('toggle-preview')) ?? ''"
diff --git a/tools/checks/lint/src/plugin.ts b/tools/checks/lint/src/plugin.ts
index 37ef28af3..abd049005 100644
--- a/tools/checks/lint/src/plugin.ts
+++ b/tools/checks/lint/src/plugin.ts
@@ -4,6 +4,7 @@ import {
noCloudSecretLoggingRule
} from '#lint/rules/cloud.ts'
import {
+ noCanvasViewChecks,
noConditionalObjectSpreads,
noFlatKiwiModules,
noMixedCaseAcronymIdentifiers
@@ -501,6 +502,7 @@ const plugin = {
'no-flat-kiwi-modules': noFlatKiwiModules,
'no-bun-globals-in-cli': noBunGlobalsInCli,
'no-top-level-prefixed-test-files': noTopLevelPrefixedTestFiles,
+ 'no-canvas-view-checks': noCanvasViewChecks,
'no-conditional-object-spreads': noConditionalObjectSpreads,
'no-hand-rolled-base64': noHandRolledBase64Rule,
'no-raw-sql': noRawSQLRule,
diff --git a/tools/checks/lint/src/rules/policy.ts b/tools/checks/lint/src/rules/policy.ts
index e62b876a3..15cedd7ff 100644
--- a/tools/checks/lint/src/rules/policy.ts
+++ b/tools/checks/lint/src/rules/policy.ts
@@ -1,6 +1,14 @@
-import { normalizedFilename } from '#lint/support/context.ts'
+import { normalizedFilename, staticPropertyName } from '#lint/support/context.ts'
import { createProgramFilenameRule } from '#lint/support/factories.ts'
import type { RuleDefinition } from '#lint/support/types.ts'
+import {
+ VUE_SIMPLE_EXPRESSION_NODE,
+ type ExpressionAstNode,
+ type VueTemplateNode,
+ vueTemplateAst,
+ walkExpressionAst,
+ walkVueTemplateAst
+} from '#lint/support/vue.ts'
import type { TSESTree } from '@typescript-eslint/utils'
function isObjectKeyIdentifier(node: TSESTree.Identifier): boolean {
@@ -132,4 +140,87 @@ const noConditionalObjectSpreads = {
}
} satisfies RuleDefinition
-export { noMixedCaseAcronymIdentifiers, noFlatKiwiModules, noConditionalObjectSpreads }
+/** The key a member expression reads when it is fixed (`a.key`, `a['key']`, ``a[`key`]``), not `a[key]`. */
+function memberName(node: TSESTree.MemberExpression): string | null {
+ const key = node.property
+ if (!node.computed || key.type === 'Literal') return staticPropertyName(key)
+ if (key.type === 'TemplateLiteral' && key.expressions.length === 0) {
+ return key.quasis[0]?.value.cooked ?? null
+ }
+ return null
+}
+
+/** The fixed key a template member expression reads (`a.key`, `a['key']`), or null. */
+function templateMemberKey(node: ExpressionAstNode): string | null {
+ if (node.type !== 'MemberExpression' && node.type !== 'OptionalMemberExpression') return null
+ const key = node.property as ExpressionAstNode | undefined
+ if (node.computed !== true && key?.type === 'Identifier') return key.name ?? null
+ if (key?.type === 'StringLiteral' && typeof key.value === 'string') return key.value
+ return null
+}
+
+/** Whether a Vue template expression reads `canvasView` from anything. */
+function templateReadsCanvasView(expression: VueTemplateNode): boolean {
+ if (expression.type !== VUE_SIMPLE_EXPRESSION_NODE || !expression.ast) return false
+ let found = false
+ walkExpressionAst(expression.ast as ExpressionAstNode, (node) => {
+ if (templateMemberKey(node) === 'canvasView') found = true
+ })
+ return found
+}
+
+const CANVAS_VIEW_MESSAGE =
+ "Read the canvas's behaviour from resolveEditorProfile instead of reading which view it shows."
+
+/**
+ * A canvas behaves by the profile its view resolves to, so code outside Core's editor views and
+ * state reads the profile's values, never the view: checks of the view's id are how preview came to
+ * branch at every place it behaves differently.
+ */
+const noCanvasViewChecks: RuleDefinition = {
+ meta: {
+ type: 'problem',
+ docs: {
+ description:
+ 'Disallow reading the canvas view outside core editor views and state — read resolveEditorProfile instead'
+ },
+ schema: []
+ },
+ create(context) {
+ const file = normalizedFilename(context)
+ const checked = file.includes('/src/') || file.includes('/packages/docs/.vitepress/theme/')
+ const owner =
+ file.includes('/packages/core/src/editor/views/') ||
+ file.includes('/packages/core/src/editor/state/')
+ if (!checked || owner) return {}
+ return {
+ Program(node) {
+ if (!file.endsWith('.vue')) return
+ const template = vueTemplateAst(context.sourceCode.getText(), file)
+ if (!template) return
+ let reads = false
+ walkVueTemplateAst(template, (templateNode) => {
+ reads ||= templateReadsCanvasView(templateNode)
+ })
+ if (reads) context.report({ node, message: CANVAS_VIEW_MESSAGE })
+ },
+ MemberExpression(node) {
+ if (memberName(node) === 'canvasView')
+ context.report({ node, message: CANVAS_VIEW_MESSAGE })
+ },
+ Property(node) {
+ if (node.parent.type !== 'ObjectPattern' || node.computed) return
+ if (staticPropertyName(node.key) === 'canvasView') {
+ context.report({ node, message: CANVAS_VIEW_MESSAGE })
+ }
+ }
+ }
+ }
+}
+
+export {
+ noCanvasViewChecks,
+ noMixedCaseAcronymIdentifiers,
+ noFlatKiwiModules,
+ noConditionalObjectSpreads
+}
diff --git a/tools/checks/lint/src/support/vue.ts b/tools/checks/lint/src/support/vue.ts
index e821da31a..b27d0ce9e 100644
--- a/tools/checks/lint/src/support/vue.ts
+++ b/tools/checks/lint/src/support/vue.ts
@@ -77,7 +77,7 @@ function walkVueTemplateAst(node: VueTemplateNode, visitor: (node: VueTemplateNo
}
}
-interface ExpressionAstNode {
+export interface ExpressionAstNode {
type?: string
callee?: ExpressionAstNode
name?: string
@@ -170,5 +170,6 @@ export {
vueComponentSource,
vueSfcDescriptor,
vueTemplateAst,
+ walkExpressionAst,
walkVueTemplateAst
}
diff --git a/tools/checks/lint/tests/canvas-view-checks.test.ts b/tools/checks/lint/tests/canvas-view-checks.test.ts
new file mode 100644
index 000000000..094a22999
--- /dev/null
+++ b/tools/checks/lint/tests/canvas-view-checks.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, test } from 'bun:test'
+
+import dedent from 'dedent'
+
+import { lint, ruleDiagnostics } from './helpers/lint.ts'
+
+const rule = 'no-canvas-view-checks'
+const rules = { [`open-pencil/${rule}`]: 'error' }
+const check = "export const previewing = editor.state.canvasView.id === 'play'"
+const path = 'packages/vue/src/canvas/useCanvasInput.ts'
+
+describe('no-canvas-view-checks', () => {
+ test.each([
+ 'packages/vue/src/canvas/useCanvasInput.ts',
+ 'packages/core/src/canvas/renderer/pipeline.ts',
+ 'src/app/shell/keyboard/registry.ts',
+ 'packages/docs/.vitepress/theme/landing/stage/controls.ts'
+ ])('rejects a view check in %s', async (path) => {
+ expect(ruleDiagnostics(await lint(check, rules, path), rule)).toHaveLength(1)
+ })
+
+ test.each([
+ 'packages/core/src/editor/views/actions.ts',
+ 'packages/core/src/editor/state/view.ts',
+ 'packages/core/tests/editor/play/states.test.ts'
+ ])('accepts a view check in %s', async (path) => {
+ expect(ruleDiagnostics(await lint(check, rules, path), rule)).toHaveLength(0)
+ })
+
+ test.each([
+ "export const previewing = editor.state['canvasView'].id === 'play'",
+ 'export const previewing = editor.state[`canvasView`].id',
+ 'export const view = editor.state.canvasView',
+ 'export const { id } = editor.state.canvasView',
+ 'export const { canvasView } = editor.state'
+ ])('rejects reading the view: %s', async (source) => {
+ expect(ruleDiagnostics(await lint(source, rules, path), rule)).toHaveLength(1)
+ })
+
+ test('accepts a key read from a variable', async () => {
+ const source = 'export const read = (key: string) => editor.state[key]'
+ expect(ruleDiagnostics(await lint(source, rules, path), rule)).toHaveLength(0)
+ })
+
+ test('rejects reading the view in a Vue template', async () => {
+ const source = dedent`
+ <script setup lang="ts">
+ defineProps<{ state: { canvasView: { id: string } } }>()
+ </script>
+ <template><div v-if="state.canvasView.id === 'play'" /></template>
+ `
+ const component = 'src/components/Fixture.vue'
+ expect(ruleDiagnostics(await lint(source, rules, component), rule)).toHaveLength(1)
+ })
+
+ test('accepts the view in a type', async () => {
+ const source = "export type View = Pick<EditorState, 'canvasView'> & { canvasView: CanvasView }"
+ expect(ruleDiagnostics(await lint(source, rules, path), rule)).toHaveLength(0)
+ })
+
+ test('accepts reading the profile anywhere', async () => {
+ const source = "export const panOnly = resolveEditorProfile(state).pointer === 'pan'"
+ expect(ruleDiagnostics(await lint(source, rules, path), rule)).toHaveLength(0)
+ })
+})