Skip to content

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

perf(properties): retain inactive panels safely

Danila Poyarkov453b27f15f36
diff --git a/AGENTS.md b/AGENTS.md
index 006a634ec..6d1d235a7 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -38,6 +38,10 @@ CanvasKit runtime loading is centralized in `@open-pencil/core/canvaskit`. Headl
`Editor` type = `ReturnType<typeof createEditor>`. Core modules should share state through `EditorContext` rather than importing app code or Vue.
+#### Retained property panels
+
+`DesignPanel` retains at most one selection-property subtree through `RetainedPanel`. The app installs `createRetainedScopePlugin()` from the Vue SDK; opted-in descendants receive `provideRetainedActivity()`. Vue component scopes are detached, so pausing only a parent or using bare `KeepAlive` does not suspend descendant work. Cancel drafts synchronously before DOM detachment can fire blur, close transient state and gate portals with `useRetainedPopup()`, and invalidate pending async results on deactivation/disposal. The plugin lets cleanup flush before pausing each component scope and resumes it on activation; it requires Vue's Options API. Unmounting the owning editor releases the retained subtree.
+
#### Editor event bus
The editor exposes a typed nanoevents emitter. Event names/payloads live in `EditorEvents` in `packages/core/src/editor/types.ts`; graph events are bridged from SceneGraph by `graph-events.ts`. Subscribe with `editor.onEditorEvent(event, handler)`, or in Vue use `useEditorEvent(event, handler)` from `packages/vue/src/editor/events/use.ts`.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 423b2305d..f7ff9eab1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -126,6 +126,7 @@
- Prevent unbounded instance duplication when editing Figma-imported or pasted components with serialized or renamed children, keep extra instance children stable instead of yanking them to the front, and avoid pasted instances re-linking pre-existing instances during clipboard import.
### Performance
+- Reduce pauses after repeated frame creation without leaving hidden property edits or popups active.
- Reduce repeated text shaping and scene invalidation while moving and resizing objects.
- Scope automation and Figma API layout reconciliation to graph nodes and parent containers actually changed by each mutation.
- Keep rapid trackpad zoom reversals and effect-heavy document navigation responsive by cancelling obsolete reconstruction and reusing safe raster snapshots.
diff --git a/packages/vue/src/controls/node-preview/use.ts b/packages/vue/src/controls/node-preview/use.ts
index 959db51f4..98c41337d 100644
--- a/packages/vue/src/controls/node-preview/use.ts
+++ b/packages/vue/src/controls/node-preview/use.ts
@@ -1,4 +1,5 @@
import { tryOnScopeDispose } from '@vueuse/core'
+import { getCurrentInstance, onDeactivated } from 'vue'
import type { Editor, NodePreview } from '@open-pencil/core/editor'
import type { SceneNode } from '@open-pencil/scene-graph'
@@ -30,5 +31,6 @@ export function useNodePreview(editor: Editor) {
}
tryOnScopeDispose(cancel)
+ if (getCurrentInstance()) onDeactivated(cancel)
return { update, commit, cancel }
}
diff --git a/packages/vue/src/controls/undo-batch/use.ts b/packages/vue/src/controls/undo-batch/use.ts
index e9cfb965f..6f4c243e6 100644
--- a/packages/vue/src/controls/undo-batch/use.ts
+++ b/packages/vue/src/controls/undo-batch/use.ts
@@ -1,4 +1,5 @@
import { tryOnScopeDispose, useTimeoutFn } from '@vueuse/core'
+import { getCurrentInstance, onDeactivated } from 'vue'
import type { UndoManager } from '@open-pencil/scene-graph'
@@ -43,6 +44,9 @@ export function useUndoBatch(undo: UndoManager, beginInteractiveEdit?: () => ()
}
tryOnScopeDispose(flush)
+ // These are applied property-list edits, not owned previews. Preserve the
+ // normal unmount behavior; preview owners cancel unfinished interactions.
+ if (getCurrentInstance()) onDeactivated(flush)
return { ensure, flush }
}
diff --git a/packages/vue/src/editor/selection-state/nodes.ts b/packages/vue/src/editor/selection-state/nodes.ts
index 4718b8eb9..c625b7b35 100644
--- a/packages/vue/src/editor/selection-state/nodes.ts
+++ b/packages/vue/src/editor/selection-state/nodes.ts
@@ -1,10 +1,12 @@
-import { computed, onScopeDispose, shallowReactive } from 'vue'
-import type { ComputedRef } from 'vue'
+import { tryOnScopeDispose, watchImmediate } from '@vueuse/core'
+import { computed, shallowReactive } from 'vue'
+import type { ComputedRef, Ref } from 'vue'
import type { Editor } from '@open-pencil/core/editor'
import type { SceneNode } from '@open-pencil/scene-graph'
import { useEditor } from '#vue/editor/context'
+import { useRetainedActivity } from '#vue/lifecycle/retention/context'
export interface SelectedNodeState {
nodes: ComputedRef<SceneNode[]>
@@ -13,24 +15,38 @@ export interface SelectedNodeState {
}
/** Selected-node copies with property-level preview tracking; never proxies the graph. */
-export function createSelectedNodeState(editor: Editor): SelectedNodeState {
- const nodes = computed(() => {
+export function createSelectedNodeState(
+ editor: Editor,
+ active?: Readonly<Ref<boolean>>
+): SelectedNodeState {
+ const nodes = computed<SceneNode[]>((previous) => {
+ if (active?.value === false && previous) return previous
void editor.state.sceneVersion
void editor.state.currentPageId
return editor.getSelectedNodes().map((node) => shallowReactive(node))
})
const byId = computed(() => new Map(nodes.value.map((node) => [node.id, node])))
const node = computed(() => (nodes.value.length === 1 ? nodes.value[0] : null))
- const dispose = editor.onEditorEvent('node:previewUpdated', (id, changes) => {
+
+ function updatePreview(id: string, changes: Partial<SceneNode>) {
if (!editor.state.selectedIds.has(id)) return
const selected = byId.value.get(id)
if (selected) Object.assign(selected, changes)
- })
+ }
+
+ const dispose = watchImmediate(
+ () => active?.value ?? true,
+ (enabled, _previous, onCleanup) => {
+ if (!enabled) return
+ onCleanup(editor.onEditorEvent('node:previewUpdated', updatePreview))
+ },
+ { flush: 'sync' }
+ )
return { nodes, node, dispose }
}
export function useSelectedNodeState(editor = useEditor()): SelectedNodeState {
- const state = createSelectedNodeState(editor)
- onScopeDispose(state.dispose)
+ const state = createSelectedNodeState(editor, useRetainedActivity())
+ tryOnScopeDispose(state.dispose)
return state
}
diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts
index 68f126954..baa1da451 100644
--- a/packages/vue/src/index.ts
+++ b/packages/vue/src/index.ts
@@ -32,6 +32,9 @@ export type { MixedValue } from '#vue/controls/node-props/use'
export { useSceneComputed } from '#vue/internal/scene-computed/use'
export { useSelectionState } from '#vue/editor/selection-state/use'
export { createSelectedNodeState } from '#vue/editor/selection-state/nodes'
+export { provideRetainedActivity, useRetainedActivity } from '#vue/lifecycle/retention/context'
+export { createRetainedScopePlugin } from '#vue/lifecycle/retention/plugin'
+export { useRetainedPopup } from '#vue/lifecycle/retention/popup'
export type { SelectedNodeState } from '#vue/editor/selection-state/nodes'
export { useEditorEvent } from '#vue/editor/events/use'
export { useSelectionCapabilities } from '#vue/editor/selection-capabilities/use'
diff --git a/packages/vue/src/lifecycle/retention/context.ts b/packages/vue/src/lifecycle/retention/context.ts
new file mode 100644
index 000000000..ff042efb8
--- /dev/null
+++ b/packages/vue/src/lifecycle/retention/context.ts
@@ -0,0 +1,21 @@
+import { hasInjectionContext, inject, provide } from 'vue'
+import type { App, InjectionKey, Ref } from 'vue'
+
+const RETAINED_ACTIVITY: InjectionKey<Readonly<Ref<boolean>>> = Symbol('retained-activity')
+const RETAINED_SCOPES_INSTALLED: InjectionKey<boolean> = Symbol('retained-scopes-installed')
+
+export function installRetainedScopes(app: App): void {
+ app.provide(RETAINED_SCOPES_INSTALLED, true)
+}
+
+/** Opt a bounded KeepAlive subtree into suspended work while it is inactive. */
+export function provideRetainedActivity(active: Readonly<Ref<boolean>>): void {
+ if (!inject(RETAINED_SCOPES_INSTALLED, false)) {
+ throw new Error('Retained activity requires createRetainedScopePlugin')
+ }
+ provide(RETAINED_ACTIVITY, active)
+}
+
+export function useRetainedActivity(): Readonly<Ref<boolean>> | undefined {
+ return hasInjectionContext() ? inject(RETAINED_ACTIVITY, undefined) : undefined
+}
diff --git a/packages/vue/src/lifecycle/retention/plugin.ts b/packages/vue/src/lifecycle/retention/plugin.ts
new file mode 100644
index 000000000..be065a3f3
--- /dev/null
+++ b/packages/vue/src/lifecycle/retention/plugin.ts
@@ -0,0 +1,39 @@
+import { getCurrentScope, nextTick, onActivated, onBeforeUnmount, onDeactivated } from 'vue'
+import type { Plugin } from 'vue'
+
+import { installRetainedScopes, useRetainedActivity } from './context'
+
+/**
+ * Installs per-component suspension inside explicitly opted-in KeepAlive trees.
+ * Vue component scopes are detached: pausing only the root leaves children running.
+ * Requires Vue's Options API (enabled by default) for the beforeCreate mixin hook.
+ */
+export function createRetainedScopePlugin(): Plugin {
+ return {
+ install(app) {
+ installRetainedScopes(app)
+ app.mixin({
+ beforeCreate() {
+ const active = useRetainedActivity()
+ const scope = getCurrentScope()
+ if (!active || !scope) return
+ let generation = 0
+ onDeactivated(() => {
+ const ticket = ++generation
+ // Let cancellation and popup cleanup render once before suspending.
+ void nextTick(() => {
+ if (ticket === generation && !active.value && scope.active) scope.pause()
+ })
+ })
+ onActivated(() => {
+ generation++
+ scope.resume()
+ })
+ onBeforeUnmount(() => {
+ generation++
+ })
+ }
+ })
+ }
+ }
+}
diff --git a/packages/vue/src/lifecycle/retention/popup.ts b/packages/vue/src/lifecycle/retention/popup.ts
new file mode 100644
index 000000000..ca45c5e36
--- /dev/null
+++ b/packages/vue/src/lifecycle/retention/popup.ts
@@ -0,0 +1,27 @@
+import { watchImmediate } from '@vueuse/core'
+import { computed, getCurrentInstance, onDeactivated, ref } from 'vue'
+import type { Ref } from 'vue'
+
+import { useRetainedActivity } from './context'
+
+/** Close transient state and remove portals before their owning panel is suspended. */
+export function useRetainedPopup(open: Ref<boolean> = ref(false), cancel?: () => void) {
+ const activity = useRetainedActivity()
+ const portalActive = computed(() => activity?.value ?? true)
+
+ function close() {
+ if (open.value) cancel?.()
+ open.value = false
+ }
+
+ watchImmediate(
+ portalActive,
+ (active) => {
+ if (!active) close()
+ },
+ { flush: 'sync' }
+ )
+ if (getCurrentInstance()) onDeactivated(close)
+
+ return { open, portalActive }
+}
diff --git a/packages/vue/src/primitives/BindableValue/BindableValueRoot.vue b/packages/vue/src/primitives/BindableValue/BindableValueRoot.vue
index b1d1b5659..0ef102344 100644
--- a/packages/vue/src/primitives/BindableValue/BindableValueRoot.vue
+++ b/packages/vue/src/primitives/BindableValue/BindableValueRoot.vue
@@ -1,5 +1,6 @@
<script setup lang="ts" generic="V">
-import { computed, onBeforeUnmount, ref } from 'vue'
+import { watchImmediate } from '@vueuse/core'
+import { computed, onBeforeUnmount, onDeactivated, ref } from 'vue'
import { useBindingProvider } from '#vue/controls/binding-provider/context'
import { prepareBindingEdits } from '#vue/controls/binding-provider/prepare-edits'
@@ -9,6 +10,7 @@ import type {
BindingProvider,
BindingTarget
} from '#vue/controls/binding-provider/types'
+import { useRetainedActivity } from '#vue/lifecycle/retention/context'
import { provideBindableValue } from '#vue/primitives/BindableValue/context'
import type {
BindableValueActions,
@@ -29,6 +31,7 @@ const {
defineSlots<BindableValueRootSlots<V>>()
+const retainedActivity = useRetainedActivity()
const injectedProvider = useBindingProvider<V>()
const resolvedProvider = providerProp ?? injectedProvider
if (!resolvedProvider) {
@@ -133,18 +136,15 @@ function snapshotBindings() {
}
function beginMutation(source: BindingMutationSource): boolean {
+ if (retainedActivity?.value === false) return false
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
- if (
- !startedUnbound &&
- !startedMixed &&
- policy.value === 'edit-variable' &&
- !provider.prepareEdit
- ) {
- return false
+ const startedBound = !startedUnbound && !startedMixed
+ if (startedBound) {
+ if (policy.value === 'readonly-when-bound') return false
+ if (policy.value === 'edit-variable' && !provider.prepareEdit) return false
}
interactionPolicy = policy.value
@@ -248,7 +248,20 @@ const context: BindableValueContext<V> = {
}
provideBindableValue(context)
+function deactivate() {
+ cancelMutation()
+ closePicker()
+}
+
+watchImmediate(
+ () => retainedActivity?.value ?? true,
+ (active) => {
+ if (!active) deactivate()
+ },
+ { flush: 'sync' }
+)
onBeforeUnmount(cancelMutation)
+onDeactivated(deactivate)
</script>
<template>
diff --git a/packages/vue/src/primitives/ColorPicker/ColorPickerRoot.vue b/packages/vue/src/primitives/ColorPicker/ColorPickerRoot.vue
index 86e55ec94..1f6b97e9d 100644
--- a/packages/vue/src/primitives/ColorPicker/ColorPickerRoot.vue
+++ b/packages/vue/src/primitives/ColorPicker/ColorPickerRoot.vue
@@ -5,6 +5,8 @@ import { computed } from 'vue'
import { colorToCSS } from '@open-pencil/core/color'
import type { Color } from '@open-pencil/scene-graph/primitives'
+import { useRetainedPopup } from '#vue/lifecycle/retention/popup'
+
export interface ColorPickerUI {
content?: string
swatch?: string
@@ -27,6 +29,10 @@ const emit = defineEmits<{
}>()
const swatchBg = computed(() => colorToCSS(color))
+const { open: popupOpen, portalActive } = useRetainedPopup(undefined, () => {
+ emit('cancel')
+ emit('openChange', false)
+})
function cancelFromEscape(event: KeyboardEvent) {
event.stopPropagation()
@@ -35,7 +41,7 @@ function cancelFromEscape(event: KeyboardEvent) {
</script>
<template>
- <PopoverRoot @update:open="emit('openChange', $event)">
+ <PopoverRoot v-model:open="popupOpen" @update:open="emit('openChange', $event)">
<PopoverTrigger as-child>
<slot name="trigger" :style="{ background: swatchBg }">
<button
@@ -47,7 +53,7 @@ function cancelFromEscape(event: KeyboardEvent) {
</slot>
</PopoverTrigger>
- <PopoverPortal>
+ <PopoverPortal v-if="portalActive">
<PopoverContent
:class="ui?.content"
:side-offset="4"
diff --git a/packages/vue/src/primitives/FontPicker/FontPickerRoot.vue b/packages/vue/src/primitives/FontPicker/FontPickerRoot.vue
index 38740dc81..e82b8f79b 100644
--- a/packages/vue/src/primitives/FontPicker/FontPickerRoot.vue
+++ b/packages/vue/src/primitives/FontPicker/FontPickerRoot.vue
@@ -15,6 +15,7 @@ import {
} from 'reka-ui'
import { nextTick } from 'vue'
+import { useRetainedPopup } from '#vue/lifecycle/retention/popup'
import type { FontPickerUI } from '#vue/primitives/FontPicker/types'
import {
useFontPicker,
@@ -51,6 +52,7 @@ const { searchTerm, open, filtered, loading, accessState, requestAccess, select
localFontAccess,
onSelect: (family) => emit('select', family)
})
+const { portalActive } = useRetainedPopup(open)
</script>
<template>
@@ -74,7 +76,7 @@ const { searchTerm, open, filtered, loading, accessState, requestAccess, select
</ComboboxTrigger>
</ComboboxAnchor>
- <ComboboxPortal>
+ <ComboboxPortal v-if="portalActive">
<ComboboxContent
:side-offset="2"
align="start"
diff --git a/packages/vue/src/primitives/FontPicker/useFontPicker.ts b/packages/vue/src/primitives/FontPicker/useFontPicker.ts
index e03d7f152..35f855459 100644
--- a/packages/vue/src/primitives/FontPicker/useFontPicker.ts
+++ b/packages/vue/src/primitives/FontPicker/useFontPicker.ts
@@ -1,8 +1,11 @@
+import { tryOnScopeDispose, watchImmediate } from '@vueuse/core'
import { useFilter } from 'reka-ui'
import { computed, ref, watch } from 'vue'
import type { FontFamilyOption } from '@open-pencil/core/text'
+import { useRetainedActivity } from '#vue/lifecycle/retention/context'
+
export type FontAccessState = 'unsupported' | 'prompt' | 'granted' | 'denied'
export type { FontFamilyOption, FontFamilySource } from '@open-pencil/core/text'
@@ -38,6 +41,22 @@ export function useFontPicker(options: UseFontPickerOptions) {
const open = ref(false)
const loading = ref(false)
const accessState = ref<FontAccessState>(options.localFontAccess?.state() ?? 'granted')
+ const active = useRetainedActivity()
+ let requestVersion = 0
+
+ function cancelLoad() {
+ requestVersion++
+ loading.value = false
+ }
+
+ watchImmediate(
+ () => active?.value ?? true,
+ (enabled) => {
+ if (!enabled) cancelLoad()
+ },
+ { flush: 'sync' }
+ )
+ tryOnScopeDispose(cancelLoad)
const { contains } = useFilter({ sensitivity: 'base' })
const filtered = computed(() => {
@@ -48,11 +67,14 @@ export function useFontPicker(options: UseFontPickerOptions) {
async function loadFamilies() {
if (families.value.length > 0 || loading.value) return
loading.value = true
+ const version = ++requestVersion
try {
- families.value = normalizeOptions(await options.listFamilies())
+ const items = await options.listFamilies()
+ if (version !== requestVersion) return
+ families.value = normalizeOptions(items)
accessState.value = options.localFontAccess?.state() ?? accessState.value
} finally {
- loading.value = false
+ if (version === requestVersion) loading.value = false
}
}
@@ -70,11 +92,14 @@ export function useFontPicker(options: UseFontPickerOptions) {
async function requestAccess() {
if (!options.localFontAccess || loading.value) return
loading.value = true
+ const version = ++requestVersion
try {
- families.value = normalizeOptions(await options.localFontAccess.load())
+ const items = await options.localFontAccess.load()
+ if (version !== requestVersion) return
+ families.value = normalizeOptions(items)
accessState.value = options.localFontAccess.state()
} finally {
- loading.value = false
+ if (version === requestVersion) loading.value = false
}
}
diff --git a/packages/vue/src/primitives/NumberField/NumberFieldRoot.vue b/packages/vue/src/primitives/NumberField/NumberFieldRoot.vue
index 0e7485c28..8b37ce889 100644
--- a/packages/vue/src/primitives/NumberField/NumberFieldRoot.vue
+++ b/packages/vue/src/primitives/NumberField/NumberFieldRoot.vue
@@ -1,6 +1,6 @@
<script setup lang="ts">
-import { useEventListener } from '@vueuse/core'
-import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'
+import { useEventListener, watchImmediate } from '@vueuse/core'
+import { computed, nextTick, onBeforeUnmount, onDeactivated, ref, watch } from 'vue'
import {
clampNumberValue,
@@ -9,6 +9,7 @@ import {
stepNumberValue
} from '#vue/controls/number-expression'
import type { NumberExpressionError } from '#vue/controls/number-expression'
+import { useRetainedActivity } from '#vue/lifecycle/retention/context'
import { useOptionalBindableValue } from '#vue/primitives/BindableValue/context'
import { provideNumberField } from '#vue/primitives/NumberField/context'
import type {
@@ -41,6 +42,7 @@ const {
const emit = defineEmits<NumberFieldRootEmits>()
defineSlots<NumberFieldRootSlots>()
+const retainedActivity = useRetainedActivity()
const enclosingBinding = useOptionalBindableValue<number>()
const binding = inheritBinding ? enclosingBinding : undefined
const editing = ref(false)
@@ -394,13 +396,28 @@ watch(
{ immediate: true }
)
-onBeforeUnmount(() => {
+function cancelDetachedInteraction() {
stopScrubListeners()
if (editing.value || scrubbing.value) {
+ restoreInteractionValue()
+ editing.value = false
+ scrubbing.value = false
binding?.actions.cancelMutation()
emit('cancel')
}
-})
+}
+
+// Cancel before KeepAlive moves a focused input: detachment can synchronously
+// fire blur, which must not commit the draft before onDeactivated runs.
+watchImmediate(
+ () => retainedActivity?.value ?? true,
+ (active) => {
+ if (!active) cancelDetachedInteraction()
+ },
+ { flush: 'sync' }
+)
+onBeforeUnmount(cancelDetachedInteraction)
+onDeactivated(cancelDetachedInteraction)
</script>
<template>
diff --git a/playwright.config.ts b/playwright.config.ts
index 3af85fec8..a89169ec3 100644
--- a/playwright.config.ts
+++ b/playwright.config.ts
@@ -51,6 +51,7 @@ export default defineConfig({
testMatch: [
'**/*.webkit.spec.ts',
'**/design/panel.spec.ts',
+ '**/design/retained-panel.spec.ts',
'**/export/basic.spec.ts',
'**/fonts/settings.spec.ts'
],
diff --git a/src/app/shell/keyboard/use.ts b/src/app/shell/keyboard/use.ts
index 92a568d57..cee60121d 100644
--- a/src/app/shell/keyboard/use.ts
+++ b/src/app/shell/keyboard/use.ts
@@ -18,7 +18,7 @@ export function useKeyboard() {
const store = useEditorStore()
const { isMobile } = useViewportKind()
const { runCommand, setOpacityTarget } = useEditorCommands()
- const activeElement = useActiveElement()
+ const activeElement = useActiveElement({ triggerOnRemoval: true })
const inputFocused = computed(() => isInputElement(activeElement.value))
const actions = createKeyboardActions({
diff --git a/src/components/DesignPanel.vue b/src/components/DesignPanel.vue
index db2f9a956..3cb8e89e8 100644
--- a/src/components/DesignPanel.vue
+++ b/src/components/DesignPanel.vue
@@ -23,6 +23,7 @@ import LayoutGridSection from './properties/layout/guides/LayoutGridSection.vue'
import LayoutSection from './properties/layout/LayoutSection.vue'
import MaskSection from './properties/MaskSection.vue'
import PageSection from './properties/PageSection.vue'
+import RetainedPanel from './properties/panel/RetainedPanel.vue'
import PositionSection from './properties/PositionSection.vue'
import SelectionActionsControl from './properties/SelectionActionsControl.vue'
import StrokeSection from './properties/stroke/StrokeSection.vue'
@@ -100,82 +101,84 @@ const { panels } = useI18n()
<ExportSection />
</div>
- <!-- Single selection -->
- <div
- v-else-if="node"
- data-test-id="design-panel-single"
- class="scrollbar-thin flex-1 overflow-x-hidden overflow-y-auto pb-4"
- >
- <PanelHeader :component="isComponentType">
- <template #icon>
- <Tip :label="node.type">
- <span role="img" :aria-label="node.type" class="contents">
- <component :is="selectedIcon" class="size-3.5" />
- </span>
- </Tip>
- </template>
- <span role="heading" aria-level="2">{{ node.name }}</span>
- <template #actions>
- <InstanceUpdateAction
- v-if="node.type === 'INSTANCE'"
- :node="node"
- :editor="store"
- :service="libraryService"
- @review="openSelectedInstanceReview"
- />
- <SelectionActionsControl />
- </template>
- </PanelHeader>
-
- <!-- Component actions -->
+ <!-- Single selection: retain one paused subtree while frame presets are shown. -->
+ <RetainedPanel :active="activeTool !== 'FRAME' && multiCount === 1 && !!node">
<div
- v-if="node.type === 'INSTANCE'"
- class="flex flex-col gap-1 border-b border-border px-3 py-2"
+ v-if="node"
+ data-test-id="design-panel-single"
+ class="scrollbar-thin flex-1 overflow-x-hidden overflow-y-auto pb-4"
>
- <button
- type="button"
- class="rounded bg-component/10 px-2 py-1 text-left text-[11px] text-component hover:bg-component/20"
- @click="goToMainComponent.run()"
- >
- {{ panels.goToMainComponent }}
- </button>
- <button
- type="button"
- class="rounded px-2 py-1 text-left text-[11px] text-muted hover:bg-hover"
- @click="detachInstance.run()"
+ <PanelHeader :component="isComponentType">
+ <template #icon>
+ <Tip :label="node.type">
+ <span role="img" :aria-label="node.type" class="contents">
+ <component :is="selectedIcon" class="size-3.5" />
+ </span>
+ </Tip>
+ </template>
+ <span role="heading" aria-level="2">{{ node.name }}</span>
+ <template #actions>
+ <InstanceUpdateAction
+ v-if="node.type === 'INSTANCE'"
+ :node="node"
+ :editor="store"
+ :service="libraryService"
+ @review="openSelectedInstanceReview"
+ />
+ <SelectionActionsControl />
+ </template>
+ </PanelHeader>
+
+ <!-- Component actions -->
+ <div
+ v-if="node.type === 'INSTANCE'"
+ class="flex flex-col gap-1 border-b border-border px-3 py-2"
>
- {{ panels.detachInstance }}
- </button>
- </div>
+ <button
+ type="button"
+ class="rounded bg-component/10 px-2 py-1 text-left text-[11px] text-component hover:bg-component/20"
+ @click="goToMainComponent.run()"
+ >
+ {{ panels.goToMainComponent }}
+ </button>
+ <button
+ type="button"
+ class="rounded px-2 py-1 text-left text-[11px] text-muted hover:bg-hover"
+ @click="detachInstance.run()"
+ >
+ {{ panels.detachInstance }}
+ </button>
+ </div>
- <ComponentPropertiesSection v-if="node.type === 'INSTANCE'" />
- <VariantAuthoringSection
- v-if="
- node.type === 'COMPONENT_SET' ||
- (node.type === 'COMPONENT' &&
- node.parentId &&
- store.graph.getNode(node.parentId)?.type === 'COMPONENT_SET')
- "
- />
+ <ComponentPropertiesSection v-if="node.type === 'INSTANCE'" />
+ <VariantAuthoringSection
+ v-if="
+ node.type === 'COMPONENT_SET' ||
+ (node.type === 'COMPONENT' &&
+ node.parentId &&
+ store.graph.getNode(node.parentId)?.type === 'COMPONENT_SET')
+ "
+ />
- <FramePresetSelect v-if="node.type === 'FRAME'" />
+ <FramePresetSelect v-if="node.type === 'FRAME'" />
- <PositionSection />
- <ConstraintsSection />
- <LayoutSection />
- <AppearanceSection />
- <MaskSection />
- <TypographySection v-if="node.type === 'TEXT'" />
- <FillSection />
- <StrokeSection />
- <LayoutGridSection v-if="supportsLayoutGuides" />
- <EffectsSection />
+ <PositionSection />
+ <ConstraintsSection />
+ <LayoutSection />
+ <AppearanceSection />
+ <MaskSection />
+ <TypographySection v-if="node.type === 'TEXT'" />
+ <FillSection />
+ <StrokeSection />
+ <LayoutGridSection v-if="supportsLayoutGuides" />
+ <EffectsSection />
- <ExportSection />
- </div>
+ <ExportSection />
+ </div>
+ </RetainedPanel>
<div
- v-else
+ v-if="activeTool !== 'FRAME' && multiCount <= 1 && !node"
data-test-id="design-panel-empty"
class="scrollbar-thin flex-1 overflow-x-hidden overflow-y-auto pb-4"
>
diff --git a/src/components/fill-picker/FillPicker.vue b/src/components/fill-picker/FillPicker.vue
index 62c90a1aa..a2d77583b 100644
--- a/src/components/fill-picker/FillPicker.vue
+++ b/src/components/fill-picker/FillPicker.vue
@@ -3,7 +3,7 @@ import { PopoverContent, PopoverPortal, PopoverRoot, PopoverTrigger } from 'reka
import { tv } from 'tailwind-variants'
import type { Fill } from '@open-pencil/scene-graph'
-import { applySolidFillColor, FillRoot, useI18n } from '@open-pencil/vue'
+import { applySolidFillColor, FillRoot, useI18n, useRetainedPopup } from '@open-pencil/vue'
import type { OkHCLControls } from '@open-pencil/vue'
import ColorPickerPanel from '@/components/color-picker-panel/ColorPickerPanel.vue'
@@ -34,6 +34,10 @@ const emit = defineEmits<{
openChange: [open: boolean]
cancel: []
}>()
+const { open: popupOpen, portalActive } = useRetainedPopup(undefined, () => {
+ emit('cancel')
+ emit('openChange', false)
+})
const cls = usePopoverUI({ content: 'w-60 p-2' })
const { panels } = useI18n()
@@ -45,7 +49,7 @@ function cancelFromEscape(event: KeyboardEvent) {
<template>
<FillRoot :fill="fill" @update="emit('update', $event)" v-slot="root">
- <PopoverRoot @update:open="emit('openChange', $event)">
+ <PopoverRoot v-model:open="popupOpen" @update:open="emit('openChange', $event)">
<PopoverTrigger as-child>
<button
type="button"
@@ -62,7 +66,7 @@ function cancelFromEscape(event: KeyboardEvent) {
</button>
</PopoverTrigger>
- <PopoverPortal>
+ <PopoverPortal v-if="portalActive">
<PopoverContent
:class="cls.content"
:side-offset="4"
diff --git a/src/components/FontSettings/FontSettingsPopover.vue b/src/components/font-settings/FontSettingsPopover.vue
similarity index 97%
rename from src/components/FontSettings/FontSettingsPopover.vue
rename to src/components/font-settings/FontSettingsPopover.vue
index 4e602b6b2..065c9ddff 100644
--- a/src/components/FontSettings/FontSettingsPopover.vue
+++ b/src/components/font-settings/FontSettingsPopover.vue
@@ -1,17 +1,18 @@
<script setup lang="ts">
import { PopoverContent, PopoverPortal, PopoverRoot, PopoverTrigger } from 'reka-ui'
-import { onMounted, ref } from 'vue'
+import { onMounted } from 'vue'
import { WEB_FONT_PROVIDER_IDS, WEB_FONT_PROVIDER_LABELS } from '@open-pencil/core/text'
import type { WebFontProviderId } from '@open-pencil/core/text'
-import { useI18n } from '@open-pencil/vue'
+import { useI18n, useRetainedPopup } from '@open-pencil/vue'
import { isTauri } from '@/app/tauri/env'
-import { useFontSettings } from '@/components/FontSettings/use'
import AppButton from '@/components/ui/button/AppButton.vue'
import { usePopoverUI } from '@/components/ui/overlay/popover'
import Tip from '@/components/ui/overlay/Tip.vue'
+import { useFontSettings } from './use'
+
const { fonts, common } = useI18n()
const cls = usePopoverUI({ content: 'isolate z-[51] w-80 p-3' })
const trigger = 'shrink-0'
@@ -27,7 +28,7 @@ const primaryButton = {
}
const showDownloadedFonts = isTauri()
const webFontProviderIds = WEB_FONT_PROVIDER_IDS
-const popoverOpen = ref(false)
+const { open: popoverOpen, portalActive } = useRetainedPopup()
const {
accessState,
@@ -80,7 +81,7 @@ onMounted(() => {
</PopoverTrigger>
</Tip>
- <PopoverPortal>
+ <PopoverPortal v-if="portalActive">
<PopoverContent
data-test-id="font-settings-panel"
side="left"
diff --git a/src/components/FontSettings/use.ts b/src/components/font-settings/use.ts
similarity index 100%
rename from src/components/FontSettings/use.ts
rename to src/components/font-settings/use.ts
diff --git a/src/components/properties/BooleanOperationsControl.vue b/src/components/properties/BooleanOperationsControl.vue
index b71a9dc0e..11239185c 100644
--- a/src/components/properties/BooleanOperationsControl.vue
+++ b/src/components/properties/BooleanOperationsControl.vue
@@ -13,7 +13,13 @@ import IconCopyX from '~icons/lucide/copy-x'
import IconListCollapse from '~icons/lucide/list-collapse'
import IconSquaresIntersect from '~icons/lucide/squares-intersect'
-import { editorCommandMetadata, formatShortcut, useEditorCommands, useI18n } from '@open-pencil/vue'
+import {
+ editorCommandMetadata,
+ formatShortcut,
+ useEditorCommands,
+ useI18n,
+ useRetainedPopup
+} from '@open-pencil/vue'
import type { EditorCommandId } from '@open-pencil/vue'
import { menuItem, useMenuUI } from '@/components/ui/menu/menu'
@@ -21,6 +27,7 @@ import Tip from '@/components/ui/overlay/Tip.vue'
const { getCommand, runCommand } = useEditorCommands()
const { commands } = useI18n()
+const { open: popupOpen, portalActive } = useRetainedPopup()
const operations = [
{ id: 'selection.booleanUnion', icon: IconCombine },
@@ -35,7 +42,7 @@ const itemCls = menuItem({ justify: 'between' })
</script>
<template>
- <DropdownMenuRoot>
+ <DropdownMenuRoot v-model:open="popupOpen">
<Tip :label="commands.booleanOperations">
<DropdownMenuTrigger as-child>
<button
@@ -47,7 +54,7 @@ const itemCls = menuItem({ justify: 'between' })
</button>
</DropdownMenuTrigger>
</Tip>
- <DropdownMenuPortal>
+ <DropdownMenuPortal v-if="portalActive">
<DropdownMenuContent align="end" side="bottom" :side-offset="4" :class="menuCls.content">
<DropdownMenuItem
v-for="operation in operations"
diff --git a/src/components/properties/ExportScaleInput.vue b/src/components/properties/ExportScaleInput.vue
index d5ca6c459..ccbd90d3e 100644
--- a/src/components/properties/ExportScaleInput.vue
+++ b/src/components/properties/ExportScaleInput.vue
@@ -6,7 +6,9 @@ import {
DropdownMenuRoot,
DropdownMenuTrigger
} from 'reka-ui'
-import { ref, watch } from 'vue'
+import { onDeactivated, ref, watch } from 'vue'
+
+import { useRetainedPopup } from '@open-pencil/vue'
import { useInputUI } from '@/components/ui/input/input'
import { menuItem, useMenuUI } from '@/components/ui/menu/menu'
@@ -24,9 +26,12 @@ const { presets, clamp, label } = defineProps<ExportScaleInputProps>()
const modelValue = defineModel<number>({ required: true })
-const open = ref(false)
+const { open, portalActive } = useRetainedPopup()
const inputRef = ref<HTMLInputElement | null>(null)
const text = ref('')
+onDeactivated(() => {
+ text.value = `${modelValue.value}x`
+})
// Keep the editable text in sync with the committed scale (e.g. 1.5 -> "1.5x").
watch(modelValue, (value) => (text.value = `${value}x`), { immediate: true })
@@ -40,7 +45,7 @@ const itemCls = menuItem({ justify: 'between' })
function commit() {
const parsed = Number.parseFloat(text.value.replace(/[^0-9.]/g, ''))
- if (Number.isFinite(parsed) && parsed > 0) modelValue.value = clamp(parsed)
+ if (portalActive.value && Number.isFinite(parsed) && parsed > 0) modelValue.value = clamp(parsed)
// Reformat from the resulting value: normalizes "9" -> "9x", reverts invalid
// input, and reflects clamping (e.g. "9999999" -> "1024x").
text.value = `${modelValue.value}x`
@@ -87,7 +92,7 @@ function isActive(scale: number) {
<icon-lucide-chevron-down class="size-3 text-muted" />
</button>
</DropdownMenuTrigger>
- <DropdownMenuPortal>
+ <DropdownMenuPortal v-if="portalActive">
<DropdownMenuContent side="bottom" align="end" :side-offset="4" :class="menuCls.content">
<DropdownMenuItem
v-for="scale in presets"
diff --git a/src/components/properties/ExportSection.vue b/src/components/properties/ExportSection.vue
index ec59dcac9..f96fca71a 100644
--- a/src/components/properties/ExportSection.vue
+++ b/src/components/properties/ExportSection.vue
@@ -1,8 +1,8 @@
<script setup lang="ts">
-import { useObjectUrl } from '@vueuse/core'
-import { computed, ref, shallowRef, watch } from 'vue'
+import { tryOnScopeDispose, useObjectUrl } from '@vueuse/core'
+import { computed, onActivated, onDeactivated, ref, shallowRef, watch } from 'vue'
-import { useExport, useI18n } from '@open-pencil/vue'
+import { useExport, useI18n, useRetainedActivity } from '@open-pencil/vue'
import type { ExportFormatId } from '@open-pencil/vue'
import { useEditorStore } from '@/app/editor/active-store'
@@ -44,6 +44,19 @@ const previewBlob = shallowRef<Blob | null>(null)
const previewURL = useObjectUrl(previewBlob)
const showPreview = ref(false)
const exporting = ref(false)
+const retainedActivity = useRetainedActivity()
+let previewVersion = 0
+
+function clearPreview() {
+ previewVersion++
+ previewBlob.value = null
+}
+
+onDeactivated(clearPreview)
+tryOnScopeDispose(clearPreview)
+onActivated(() => {
+ void updatePreview()
+})
const PREVIEW_WIDTH = 480
@@ -73,7 +86,11 @@ async function doExport() {
}
async function updatePreview() {
- if (!showPreview.value) return
+ const version = ++previewVersion
+ if (retainedActivity?.value === false || !showPreview.value) {
+ previewBlob.value = null
+ return
+ }
const ids =
activeTarget.value === 'selection'
@@ -92,6 +109,7 @@ async function updatePreview() {
}
const scale = maxW > 0 ? Math.min(PREVIEW_WIDTH / maxW, 2) : 1
const data = await editorStore.renderExportImage(ids, scale, 'PNG')
+ if (version !== previewVersion) return
previewBlob.value = data ? new Blob([data], { type: 'image/png' }) : null
}
diff --git a/src/components/properties/TypographySection.vue b/src/components/properties/TypographySection.vue
index 386c8497d..37158e193 100644
--- a/src/components/properties/TypographySection.vue
+++ b/src/components/properties/TypographySection.vue
@@ -6,7 +6,7 @@ import { TypographyControlsRoot, useI18n } from '@open-pencil/vue'
import { loadFont } from '@/app/editor/fonts'
import { appMenuShortcutLabel } from '@/app/shell/menu/shortcut'
import FontPicker from '@/components/font-picker/FontPicker.vue'
-import FontSettingsPopover from '@/components/FontSettings/FontSettingsPopover.vue'
+import FontSettingsPopover from '@/components/font-settings/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'
diff --git a/src/components/properties/binding/VariableBindingPicker.vue b/src/components/properties/binding/VariableBindingPicker.vue
index 3473541f4..84d59afc2 100644
--- a/src/components/properties/binding/VariableBindingPicker.vue
+++ b/src/components/properties/binding/VariableBindingPicker.vue
@@ -29,7 +29,7 @@ import {
} from 'reka-ui'
import { computed, nextTick, ref, watch } from 'vue'
-import { BindableValuePicker, useBindableValue } from '@open-pencil/vue'
+import { BindableValuePicker, useBindableValue, useRetainedPopup } from '@open-pencil/vue'
import { BindingTrigger, useBindingFieldUI } from '@/components/ui/binding'
import AppButton from '@/components/ui/button/AppButton.vue'
@@ -50,6 +50,7 @@ const {
} = defineProps<VariableBindingPickerProps>()
const binding = useBindableValue<unknown>()
+const { portalActive } = useRetainedPopup(binding.open)
const creating = ref(false)
const createName = ref('')
const createInput = ref<HTMLInputElement | null>(null)
@@ -115,7 +116,7 @@ defineOptions({ inheritAttrs: false })
</Tip>
</ComboboxAnchor>
- <ComboboxPortal>
+ <ComboboxPortal v-if="portalActive">
<ComboboxContent
v-if="picker.open"
position="popper"
diff --git a/src/components/properties/component-properties/instance-update/InstanceUpdateAction.vue b/src/components/properties/component-properties/instance-update/InstanceUpdateAction.vue
index e66e6abef..b40cc7a8d 100644
--- a/src/components/properties/component-properties/instance-update/InstanceUpdateAction.vue
+++ b/src/components/properties/component-properties/instance-update/InstanceUpdateAction.vue
@@ -9,7 +9,7 @@ import {
import { toRef } from 'vue'
import type { SceneNode } from '@open-pencil/scene-graph'
-import { useI18n } from '@open-pencil/vue'
+import { useI18n, useRetainedPopup } from '@open-pencil/vue'
import type { EditorStore } from '@/app/editor/session'
import type { LibraryService } from '@/app/libraries'
@@ -24,6 +24,7 @@ const { node, editor, service } = defineProps<{
}>()
const emit = defineEmits<{ review: [] }>()
const { panels } = useI18n()
+const { open: popupOpen, portalActive } = useRetainedPopup()
const menu = useMenuUI({ content: 'min-w-48' })
const { available, updating, updateSelectedInstance } = useInstanceUpdate(
toRef(() => node),
@@ -33,7 +34,7 @@ const { available, updating, updateSelectedInstance } = useInstanceUpdate(
</script>
<template>
- <DropdownMenuRoot v-if="available">
+ <DropdownMenuRoot v-if="available" v-model:open="popupOpen">
<Tip :label="panels.updateSelectedInstance">
<DropdownMenuTrigger as-child>
<button
@@ -50,7 +51,7 @@ const { available, updating, updateSelectedInstance } = useInstanceUpdate(
</button>
</DropdownMenuTrigger>
</Tip>
- <DropdownMenuPortal>
+ <DropdownMenuPortal v-if="portalActive">
<DropdownMenuContent align="end" side="bottom" :side-offset="4" :class="menu.content">
<DropdownMenuItem
data-test-id="instance-update-selected"
diff --git a/src/components/properties/layout/flex/FlexGapField.vue b/src/components/properties/layout/flex/FlexGapField.vue
index d2f05ed9c..f8f168bcf 100644
--- a/src/components/properties/layout/flex/FlexGapField.vue
+++ b/src/components/properties/layout/flex/FlexGapField.vue
@@ -11,13 +11,14 @@ import {
} from 'reka-ui'
import { computed, ref } from 'vue'
-import { useI18n, useLayoutControlsContext } from '@open-pencil/vue'
+import { useI18n, useLayoutControlsContext, useRetainedPopup } from '@open-pencil/vue'
import VariableNumberField from '@/components/properties/VariableNumberField.vue'
import { useSelectUI } from '@/components/ui/select/select'
const { axis = 'primary' } = defineProps<{ axis?: 'primary' | 'counter' }>()
const ctx = useLayoutControlsContext()
+const { open: popupOpen, portalActive } = useRetainedPopup()
const { panels } = useI18n()
const anchor = ref<HTMLElement | null>(null)
const prop = computed(() => (axis === 'primary' ? 'itemSpacing' : 'counterAxisSpacing'))
@@ -34,7 +35,11 @@ function setMode(value: string) {
</script>
<template>
- <SelectRoot :model-value="auto ? 'AUTO' : 'FIXED'" @update:model-value="setMode">
+ <SelectRoot
+ v-model:open="popupOpen"
+ :model-value="auto ? 'AUTO' : 'FIXED'"
+ @update:model-value="setMode"
+ >
<div ref="anchor" class="min-w-0">
<div
v-if="auto"
@@ -85,7 +90,7 @@ function setMode(value: string) {
</template>
</VariableNumberField>
</div>
- <SelectPortal v-if="allowAuto">
+ <SelectPortal v-if="allowAuto && portalActive">
<SelectContent position="popper" align="start" :side-offset="4" :class="menu.content">
<SelectViewport class="p-0.5">
<SelectItem
diff --git a/src/components/properties/layout/size/SizeAxisField.vue b/src/components/properties/layout/size/SizeAxisField.vue
index c69014707..0fe1c339e 100644
--- a/src/components/properties/layout/size/SizeAxisField.vue
+++ b/src/components/properties/layout/size/SizeAxisField.vue
@@ -11,7 +11,7 @@ import {
} from 'reka-ui'
import type { LayoutSizing } from '@open-pencil/scene-graph'
-import { useI18n, useLayoutControlsContext } from '@open-pencil/vue'
+import { useI18n, useLayoutControlsContext, useRetainedPopup } from '@open-pencil/vue'
import type { SizeLimitProp } from '@open-pencil/vue'
import type { SizeAxisFieldProps } from '@/components/properties/layout/size/types'
@@ -24,6 +24,7 @@ type SizeSelectValue = LayoutSizing | `add-${SizeLimitProp}` | `remove-${SizeLim
const { axis, icon, label } = defineProps<SizeAxisFieldProps>()
const ctx = useLayoutControlsContext()
+const { open: popupOpen, portalActive } = useRetainedPopup()
const { panels } = useI18n()
const selectUI = useSelectUI({ item: 'rounded py-1.5 pr-2 pl-6 text-xs' })
@@ -88,6 +89,7 @@ function handleSelect(value: SizeSelectValue) {
>
<template #after-variable>
<SelectRoot
+ v-model:open="popupOpen"
:model-value="sizing()"
@update:model-value="handleSelect($event as SizeSelectValue)"
>
@@ -100,7 +102,7 @@ function handleSelect(value: SizeSelectValue) {
<span v-if="sizingLabel()">{{ sizingLabel() }}</span>
<icon-lucide-chevron-down class="size-3" />
</SelectTrigger>
- <SelectPortal>
+ <SelectPortal v-if="portalActive">
<SelectContent
position="popper"
align="start"
diff --git a/src/components/properties/layout/size/SizeLimitField.vue b/src/components/properties/layout/size/SizeLimitField.vue
index ae6f727f3..d23feec51 100644
--- a/src/components/properties/layout/size/SizeLimitField.vue
+++ b/src/components/properties/layout/size/SizeLimitField.vue
@@ -9,7 +9,7 @@ import {
SelectViewport
} from 'reka-ui'
-import { useLayoutControlsContext } from '@open-pencil/vue'
+import { useLayoutControlsContext, useRetainedPopup } from '@open-pencil/vue'
import type { SizeLimitFieldProps } from '@/components/properties/layout/size/types'
import VariableNumberField from '@/components/properties/VariableNumberField.vue'
@@ -19,6 +19,7 @@ import { useSelectUI } from '@/components/ui/select/select'
const { item } = defineProps<SizeLimitFieldProps>()
const ctx = useLayoutControlsContext()
+const { open: popupOpen, portalActive } = useRetainedPopup()
const selectUI = useSelectUI({ item: 'rounded py-1.5 px-2 text-xs' })
function handleSelect(value: string) {
@@ -41,7 +42,11 @@ function handleSelect(value: string) {
@cancel="ctx.cancelPreview"
>
<template #after-variable>
- <SelectRoot :model-value="'VALUE'" @update:model-value="handleSelect($event as string)">
+ <SelectRoot
+ v-model:open="popupOpen"
+ :model-value="'VALUE'"
+ @update:model-value="handleSelect($event as string)"
+ >
<SelectTrigger
data-slot="limit-trigger"
:aria-label="item.label"
@@ -50,7 +55,7 @@ function handleSelect(value: string) {
>
<icon-lucide-chevron-down class="size-3" />
</SelectTrigger>
- <SelectPortal>
+ <SelectPortal v-if="portalActive">
<SelectContent
position="popper"
align="start"
diff --git a/src/components/properties/panel/RetainedPanel.vue b/src/components/properties/panel/RetainedPanel.vue
new file mode 100644
index 000000000..cb2705ec6
--- /dev/null
+++ b/src/components/properties/panel/RetainedPanel.vue
@@ -0,0 +1,24 @@
+<script setup lang="ts">
+import { defineComponent, KeepAlive, toRef } from 'vue'
+
+import { provideRetainedActivity } from '@open-pencil/vue'
+
+const { active } = defineProps<{ active: boolean }>()
+provideRetainedActivity(toRef(() => active))
+
+// One retained subtree per panel, released when its owning editor view unmounts.
+const PanelBody = defineComponent({
+ name: 'RetainedPanelBody',
+ setup(_, { slots }) {
+ return () => slots.default?.()
+ }
+})
+</script>
+
+<template>
+ <KeepAlive :max="1">
+ <PanelBody v-if="active">
+ <slot />
+ </PanelBody>
+ </KeepAlive>
+</template>
diff --git a/src/components/properties/stroke/StrokeSettingsPopover.vue b/src/components/properties/stroke/StrokeSettingsPopover.vue
index 4426b4743..9529c61ca 100644
--- a/src/components/properties/stroke/StrokeSettingsPopover.vue
+++ b/src/components/properties/stroke/StrokeSettingsPopover.vue
@@ -2,7 +2,7 @@
import { PopoverRoot, PopoverTrigger, PopoverPortal, PopoverContent, PopoverClose } from 'reka-ui'
import type { Stroke } from '@open-pencil/scene-graph'
-import { useI18n } from '@open-pencil/vue'
+import { useI18n, useRetainedPopup } from '@open-pencil/vue'
import AppButton from '@/components/ui/button/AppButton.vue'
import { usePopoverUI } from '@/components/ui/overlay/popover'
@@ -13,6 +13,7 @@ import StrokeGeometryControls from './StrokeGeometryControls.vue'
const { stroke } = defineProps<{ stroke?: Stroke }>()
const emit = defineEmits<{ patch: [changes: Partial<Stroke>] }>()
const { panels, common } = useI18n()
+const { open: popupOpen, portalActive } = useRetainedPopup()
const styles = usePopoverUI({
content: 'w-64 max-w-[calc(100vw-1rem)]',
header: 'flex items-center justify-between border-b border-border px-3 py-2',
@@ -21,13 +22,13 @@ const styles = usePopoverUI({
</script>
<template>
- <PopoverRoot>
+ <PopoverRoot v-model:open="popupOpen">
<PopoverTrigger as-child>
<AppButton :aria-label="panels.strokeSettings" data-property="stroke-settings">
<icon-lucide-sliders-horizontal class="size-3.5" />
</AppButton>
</PopoverTrigger>
- <PopoverPortal>
+ <PopoverPortal v-if="portalActive">
<PopoverContent
side="left"
align="start"
diff --git a/src/components/properties/typography/LineHeightField.vue b/src/components/properties/typography/LineHeightField.vue
index c52adba39..e9f3a0573 100644
--- a/src/components/properties/typography/LineHeightField.vue
+++ b/src/components/properties/typography/LineHeightField.vue
@@ -11,7 +11,7 @@ import {
import { computed } from 'vue'
import type { SceneNode } from '@open-pencil/scene-graph'
-import { useEditor, useI18n } from '@open-pencil/vue'
+import { useEditor, useI18n, useRetainedPopup } from '@open-pencil/vue'
import VariableNumberField from '@/components/properties/VariableNumberField.vue'
import { useSelectUI } from '@/components/ui/select/select'
@@ -19,6 +19,7 @@ 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 { open: popupOpen, portalActive } = useRetainedPopup()
const { panels } = useI18n()
const automatic = computed(() => node.lineHeight == null && !node.boundVariables.lineHeight)
const value = computed(() => node.lineHeight ?? Math.round((node.fontSize || 14) * 1.2))
@@ -51,14 +52,18 @@ function setMode(mode: string) {
><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">
+ <SelectRoot
+ v-model:open="popupOpen"
+ :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>
+ <SelectPortal v-if="portalActive">
<SelectContent position="popper" :side-offset="4" :class="menu.content">
<SelectViewport>
<SelectItem value="AUTO" :class="menu.item"
diff --git a/src/components/ui/overlay/Tip.vue b/src/components/ui/overlay/Tip.vue
index d1f4cd896..d9c1151b5 100644
--- a/src/components/ui/overlay/Tip.vue
+++ b/src/components/ui/overlay/Tip.vue
@@ -1,8 +1,16 @@
<script setup lang="ts">
-import { unrefElement, useEventListener, useTimeoutFn } from '@vueuse/core'
+import {
+ defaultDocument,
+ defaultWindow,
+ unrefElement,
+ useEventListener,
+ useTimeoutFn
+} from '@vueuse/core'
import { Primitive } from 'reka-ui'
import type { ComponentPublicInstance } from 'vue'
-import { computed, nextTick, ref, watch } from 'vue'
+import { computed, nextTick, onDeactivated, ref, watch } from 'vue'
+
+import { useRetainedPopup } from '@open-pencil/vue'
import { useTooltipUI } from '@/components/ui/overlay/tooltip'
import { motionStyles } from '@/theme/motion/styles'
@@ -35,6 +43,9 @@ function setTrigger(value: Element | ComponentPublicInstance | null) {
}
const contentRef = ref<HTMLElement>()
const open = ref(false)
+const { portalActive } = useRetainedPopup(open)
+const activeWindow = computed(() => (portalActive.value ? defaultWindow : undefined))
+const activeDocument = computed(() => (portalActive.value ? defaultDocument : undefined))
const position = ref({ x: 0, y: 0 })
const canOpen = computed(() => Boolean(label) && !disabled)
@@ -165,11 +176,12 @@ function onTooltipClaim(event: Event) {
hide()
}
-useEventListener(window, 'resize', refreshPosition)
-useEventListener(window, 'scroll', refreshPosition, { capture: true, passive: true })
-useEventListener(document, 'pointerdown', hide, { capture: true })
-useEventListener(document, 'click', hide, { capture: true })
-useEventListener(document, TOOLTIP_CLAIM_EVENT, onTooltipClaim)
+useEventListener(activeWindow, 'resize', refreshPosition)
+useEventListener(activeWindow, 'scroll', refreshPosition, { capture: true, passive: true })
+useEventListener(activeDocument, 'pointerdown', hide, { capture: true })
+useEventListener(activeDocument, 'click', hide, { capture: true })
+useEventListener(activeDocument, TOOLTIP_CLAIM_EVENT, onTooltipClaim)
+onDeactivated(hide)
watch(canOpen, (value) => {
if (!value) hide()
@@ -193,7 +205,7 @@ watch(canOpen, (value) => {
>
<slot />
</Primitive>
- <Teleport to="body">
+ <Teleport v-if="portalActive" to="body">
<div
v-if="open && label"
ref="contentRef"
diff --git a/src/components/ui/select/AppCombobox.vue b/src/components/ui/select/AppCombobox.vue
index 65429e007..59d0854ef 100644
--- a/src/components/ui/select/AppCombobox.vue
+++ b/src/components/ui/select/AppCombobox.vue
@@ -18,6 +18,8 @@ import {
import { tv } from 'tailwind-variants'
import { computed, ref } from 'vue'
+import { useRetainedPopup } from '@open-pencil/vue'
+
import type { ComponentUI } from '@/components/ui/types'
import theme from '@/theme/select/combobox'
import type { AppComboboxTheme } from '@/theme/select/combobox'
@@ -58,6 +60,7 @@ const {
const modelValue = defineModel<string>({ required: true })
const open = ref(false)
const searchTerm = ref('')
+const { portalActive } = useRetainedPopup(open, () => updateOpen(false))
const styles = tv(theme)()
const selectedOption = computed(() => options.find((option) => option.value === modelValue.value))
@@ -123,7 +126,7 @@ function updateOpen(value: boolean): void {
</ComboboxTrigger>
</ComboboxAnchor>
- <ComboboxPortal>
+ <ComboboxPortal v-if="portalActive">
<ComboboxContent
position="popper"
:side-offset="2"
diff --git a/src/components/ui/select/AppGroupedSelect.vue b/src/components/ui/select/AppGroupedSelect.vue
index 0ec3c8430..ff99513ba 100644
--- a/src/components/ui/select/AppGroupedSelect.vue
+++ b/src/components/ui/select/AppGroupedSelect.vue
@@ -13,6 +13,8 @@ import {
} from 'reka-ui'
import { tv } from 'tailwind-variants'
+import { useRetainedPopup } from '@open-pencil/vue'
+
import type { ComponentUI } from '@/components/ui/types'
import theme from '@/theme/select/grouped'
import type { AppGroupedSelectTheme } from '@/theme/select/grouped'
@@ -40,15 +42,16 @@ const { groups, displayValue, ui } = defineProps<AppGroupedSelectProps<T>>()
const modelValue = defineModel<T>({ required: true })
const styles = tv(theme)()
+const { open: popupOpen, portalActive } = useRetainedPopup()
</script>
<template>
- <SelectRoot v-model="modelValue">
+ <SelectRoot v-model="modelValue" v-model:open="popupOpen">
<SelectTrigger v-bind="$attrs" :class="styles.trigger({ class: ui?.trigger })">
<slot name="value">{{ displayValue }}</slot>
<icon-lucide-chevron-down class="size-2.5 shrink-0 text-muted" />
</SelectTrigger>
- <SelectPortal>
+ <SelectPortal v-if="portalActive">
<SelectContent
position="popper"
:side-offset="4"
diff --git a/src/components/ui/select/AppSelect.vue b/src/components/ui/select/AppSelect.vue
index b6b49f972..5286b70d5 100644
--- a/src/components/ui/select/AppSelect.vue
+++ b/src/components/ui/select/AppSelect.vue
@@ -14,6 +14,8 @@ import {
} from 'reka-ui'
import { tv } from 'tailwind-variants'
+import { useRetainedPopup } from '@open-pencil/vue'
+
import type { ComponentUI } from '@/components/ui/types'
import theme from '@/theme/select/app'
import type { AppSelectTheme } from '@/theme/select/app'
@@ -30,10 +32,11 @@ defineOptions({ inheritAttrs: false })
const { options, label, placeholder, ui } = defineProps<AppSelectProps<T>>()
const modelValue = defineModel<T>({ required: true })
const styles = tv(theme)()
+const { open: popupOpen, portalActive } = useRetainedPopup()
</script>
<template>
- <SelectRoot v-model="modelValue">
+ <SelectRoot v-model="modelValue" v-model:open="popupOpen">
<SelectTrigger v-if="$slots.trigger" as-child v-bind="$attrs" :aria-label="label">
<slot name="trigger" />
</SelectTrigger>
@@ -46,7 +49,7 @@ const styles = tv(theme)()
<SelectValue :placeholder="placeholder" :class="styles.value({ class: ui?.value })" />
<icon-lucide-chevron-down class="ml-1 size-3 shrink-0 text-muted" />
</SelectTrigger>
- <SelectPortal>
+ <SelectPortal v-if="portalActive">
<SelectContent
position="popper"
:side-offset="2"
diff --git a/src/main.ts b/src/main.ts
index 78feee8d2..59a11fb3d 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -1,6 +1,8 @@
import { createHead } from '@unhead/vue/client'
import { createApp } from 'vue'
+import { createRetainedScopePlugin } from '@open-pencil/vue'
+
import './app.css'
import { preloadFonts } from '@/app/editor/fonts'
import { IS_TAURI } from '@/constants'
@@ -10,7 +12,7 @@ import router from './router'
preloadFonts()
const head = createHead()
-createApp(App).use(router).use(head).mount('#app')
+createApp(App).use(router).use(head).use(createRetainedScopePlugin()).mount('#app')
if (!IS_TAURI) {
void import('virtual:pwa-register').then(({ registerSW }) => {
diff --git a/tests/e2e/design/retained-panel.spec.ts b/tests/e2e/design/retained-panel.spec.ts
new file mode 100644
index 000000000..3c54c7e49
--- /dev/null
+++ b/tests/e2e/design/retained-panel.spec.ts
@@ -0,0 +1,183 @@
+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
+import { expectDefined } from '#tests/helpers/assert'
+
+const editor = useEditorSetupWithClear('/?test')
+
+const width = () => editor.page.getByRole('spinbutton', { name: 'Width', exact: true })
+
+async function setTool(tool: 'FRAME' | 'SELECT') {
+ await editor.page.evaluate((tool) => window.openPencil?.getStore?.().setTool(tool), tool)
+}
+
+test.beforeEach(async () => {
+ await editor.page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('Editor unavailable')
+ const id = store.createShape('FRAME', 100, 100, 320, 120)
+ store.select([id])
+ })
+ await expect(width()).toHaveAttribute('aria-valuenow', '320')
+})
+
+test('reuses one panel without updating its detached fields', async () => {
+ const probe = await width().evaluateHandle((element) => {
+ let mutations = 0
+ const observer = new MutationObserver((records) => {
+ mutations += records.length
+ })
+ observer.observe(element, { attributes: true, childList: true, subtree: true })
+ return {
+ element,
+ mutations: () => mutations,
+ reset: () => {
+ observer.takeRecords()
+ mutations = 0
+ },
+ stop: () => observer.disconnect()
+ }
+ })
+ try {
+ await setTool('FRAME')
+ await expect(width()).toHaveCount(0)
+ await editor.page.evaluate(
+ () =>
+ new Promise<void>((resolve) => {
+ requestAnimationFrame(() => resolve())
+ })
+ )
+ await probe.evaluate((probe) => probe.reset())
+ await editor.page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ const node = store?.selectedNode.value
+ if (!store || !node) throw new Error('Selected frame unavailable')
+ for (let width = 321; width <= 380; width++) store.graph.updateNodePreview(node.id, { width })
+ })
+ expect(
+ await probe.evaluate((probe) => ({
+ connected: probe.element.isConnected,
+ value: probe.element.getAttribute('aria-valuenow'),
+ mutations: probe.mutations()
+ }))
+ ).toEqual({ connected: false, value: '320', mutations: 0 })
+
+ for (let repeat = 0; repeat < 3; repeat++) {
+ await setTool('SELECT')
+ await expect(width()).toHaveAttribute('aria-valuenow', '380')
+ expect(await width().evaluate((element, probe) => element === probe.element, probe)).toBe(
+ true
+ )
+ if (repeat < 2) await setTool('FRAME')
+ }
+ } finally {
+ await probe.evaluate((probe) => probe.stop())
+ await probe.dispose()
+ }
+})
+
+test('reuses the panel for a newly drawn frame', async () => {
+ const original = await width().evaluateHandle((element) => element)
+ try {
+ const box = expectDefined(await editor.canvas.canvas.boundingBox(), 'canvas')
+ await setTool('FRAME')
+ await editor.page.mouse.move(box.x + 500, box.y + 350)
+ await editor.page.mouse.down()
+ await editor.page.mouse.move(box.x + 620, box.y + 430, { steps: 6 })
+ await editor.page.mouse.up()
+ await expect(width()).toHaveAttribute('aria-valuenow', '120')
+ expect(await width().evaluate((element, original) => element === original, original)).toBe(true)
+ } finally {
+ await editor.page.mouse.up()
+ await original.dispose()
+ }
+})
+
+test('discards an unfinished text edit and restores normal editing on activation', async () => {
+ await width().dblclick()
+ await editor.page.keyboard.press('ControlOrMeta+A')
+ await editor.page.keyboard.type('999')
+ await setTool('FRAME')
+ await expect(width()).toHaveCount(0)
+ await setTool('SELECT')
+ await expect(width()).toHaveAttribute('aria-valuenow', '320')
+ await width().dblclick()
+ await editor.page.keyboard.press('ControlOrMeta+A')
+ await editor.page.keyboard.type('400')
+ await editor.page.keyboard.press('Enter')
+ await expect(width()).toHaveAttribute('aria-valuenow', '400')
+ const url = editor.page.url()
+ await editor.page.keyboard.press('Backspace')
+ await expect(editor.page).toHaveURL(url)
+ await expect(width()).toHaveCount(0)
+})
+
+test('restores a bound width when a live text edit is deactivated', async () => {
+ const variableId = await editor.page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ const node = store?.selectedNode.value
+ if (!store || !node) throw new Error('Selected frame unavailable')
+ const collection = store.graph.createCollection('Retention')
+ const variable = store.graph.createVariable('Width/shared', 'FLOAT', collection.id, 320)
+ store.bindVariable(node.id, 'width', variable.id)
+ return variable.id
+ })
+ await width().dblclick()
+ await editor.page.keyboard.press('ControlOrMeta+A')
+ await editor.page.keyboard.type('999')
+ await setTool('FRAME')
+ await expect(width()).toHaveCount(0)
+ await setTool('SELECT')
+ await expect(width()).toHaveAttribute('aria-valuenow', '320')
+ expect(
+ await editor.page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ return {
+ binding: store?.selectedNode.value?.boundVariables.width,
+ interactive: store?.isInteractiveEditing()
+ }
+ })
+ ).toEqual({ binding: variableId, interactive: false })
+})
+
+test('removes open paint portals and does not reopen them on activation', async () => {
+ const swatch = editor.page.getByTestId('fill-picker-swatch').first()
+ await swatch.click()
+ await expect(editor.page.getByRole('dialog')).toBeVisible()
+ await setTool('FRAME')
+ await expect(editor.page.getByRole('dialog')).toHaveCount(0)
+ await setTool('SELECT')
+ await expect(width()).toBeVisible()
+ await expect(editor.page.getByRole('dialog')).toHaveCount(0)
+ await swatch.click()
+ await expect(editor.page.getByRole('dialog')).toBeVisible()
+ await editor.page.keyboard.press('Escape')
+ await expect(editor.page.getByRole('dialog')).toHaveCount(0)
+})
+
+test('cancels a held scrub before retaining the panel', async () => {
+ const box = expectDefined(await width().boundingBox(), 'width field')
+ await editor.page.mouse.move(box.x + box.width / 2, box.y + box.height / 2)
+ await editor.page.mouse.down()
+ try {
+ await editor.page.mouse.move(box.x + box.width / 2 + 40, box.y + box.height / 2, { steps: 4 })
+ await expect(width()).toHaveAttribute('aria-valuenow', '360')
+ await setTool('FRAME')
+ await expect(width()).toHaveCount(0)
+ expect(
+ await editor.page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ return { width: store?.selectedNode.value?.width, preview: store?.isInteractiveEditing() }
+ })
+ ).toEqual({ width: 320, preview: false })
+ } finally {
+ await editor.page.mouse.up()
+ }
+ await setTool('SELECT')
+ await expect(width()).toHaveAttribute('aria-valuenow', '320')
+ await width().dblclick()
+ await editor.page.keyboard.press('ControlOrMeta+A')
+ await editor.page.keyboard.type('400')
+ await editor.page.keyboard.press('Enter')
+ await expect(width()).toHaveAttribute('aria-valuenow', '400')
+ await editor.page.evaluate(() => window.openPencil?.getStore?.().undoAction())
+ await expect(width()).toHaveAttribute('aria-valuenow', '320')
+})
diff --git a/tests/e2e/properties/frame-presets.spec.ts b/tests/e2e/properties/frame-presets.spec.ts
index 92fe9057f..954b815c7 100644
--- a/tests/e2e/properties/frame-presets.spec.ts
+++ b/tests/e2e/properties/frame-presets.spec.ts
@@ -26,7 +26,7 @@ test('creates and resizes a frame with presets', async () => {
let frame = await getSelectedNode(editor.page)
expect(frame).toMatchObject({ type: 'FRAME', name: 'iPhone Air', width: 420, height: 912 })
await expect(editor.page.getByTestId(toolbarToolTestId('SELECT'))).toHaveAttribute(
- 'data-active',
+ 'aria-pressed',
'true'
)
diff --git a/tests/engine/app/settings/font.test.ts b/tests/engine/app/settings/font.test.ts
index e7c89b7b4..f038175be 100644
--- a/tests/engine/app/settings/font.test.ts
+++ b/tests/engine/app/settings/font.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { useFontSettings, type FontSettingsActions } from '@/components/FontSettings/use'
+import { useFontSettings, type FontSettingsActions } from '@/components/font-settings/use'
function actions(overrides: Partial<FontSettingsActions> = {}): FontSettingsActions {
let accessState: ReturnType<FontSettingsActions['localFontAccessState']> = 'prompt'
diff --git a/tests/engine/vue/document-workspace.test.ts b/tests/engine/vue/document-workspace.test.ts
index 6ff36a83c..093b8d1b2 100644
--- a/tests/engine/vue/document-workspace.test.ts
+++ b/tests/engine/vue/document-workspace.test.ts
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, test, vi } from 'bun:test'
-import { createRenderer, defineComponent, h, type ComponentPublicInstance } from 'vue'
+import { defineComponent, h, type ComponentPublicInstance } from 'vue'
import {
useDocumentWorkspace,
@@ -8,11 +8,7 @@ import {
type DocumentWorkspaceSource
} from '@open-pencil/vue'
-type HostNode = {
- children: HostNode[]
- parent: HostNode | null
- text: string
-}
+import { createTestRenderer, hostNode } from '#tests/helpers/vue/renderer'
type Deferred<Value> = {
promise: Promise<Value>
@@ -32,58 +28,7 @@ function deferred<Value>(): Deferred<Value> {
}
}
-function hostNode(text = ''): HostNode {
- return { children: [], parent: null, text }
-}
-
-const renderer = createRenderer<HostNode, HostNode>({
- patchProp() {
- return undefined
- },
- insert(child, parent, anchor) {
- child.parent = parent
- const index = anchor ? parent.children.indexOf(anchor) : -1
- if (index < 0) parent.children.push(child)
- else parent.children.splice(index, 0, child)
- },
- remove(child) {
- const parent = child.parent
- if (!parent) return
- const index = parent.children.indexOf(child)
- if (index !== -1) parent.children.splice(index, 1)
- child.parent = null
- },
- createElement() {
- return hostNode()
- },
- createText: hostNode,
- createComment: hostNode,
- setText(node, text) {
- node.text = text
- },
- setElementText(node, text) {
- node.text = text
- },
- parentNode(node) {
- return node.parent
- },
- nextSibling(node) {
- const parent = node.parent
- if (!parent) return null
- return parent.children[parent.children.indexOf(node) + 1] ?? null
- },
- querySelector() {
- return null
- },
- setScopeId() {
- return undefined
- },
- insertStaticContent(content, parent, anchor) {
- const node = hostNode(content)
- this.insert(node, parent, anchor)
- return [node, node]
- }
-})
+const renderer = createTestRenderer()
type Workspace = ReturnType<typeof useDocumentWorkspace<DocumentWorkspaceItem>>
diff --git a/tests/engine/vue/editor/selected-nodes.test.ts b/tests/engine/vue/editor/selected-nodes.test.ts
index cbd45fc05..1a3ebeab5 100644
--- a/tests/engine/vue/editor/selected-nodes.test.ts
+++ b/tests/engine/vue/editor/selected-nodes.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { computed, createApp, effectScope, shallowReactive } from 'vue'
+import { computed, createApp, effectScope, ref, shallowReactive } from 'vue'
import { createDefaultEditorState, createEditor } from '@open-pencil/core/editor'
import { getSharedStyles, SceneGraph } from '@open-pencil/scene-graph'
@@ -31,6 +31,40 @@ function setup() {
}
describe('selected-node preview projections', () => {
+ test('freezes inactive projections, refreshes on activation and disposes subscriptions', () => {
+ const fixture = setup()
+ const { editor, first, second } = fixture
+ const active = ref(true)
+ const selection = createSelectedNodeState(editor, active)
+ try {
+ const initial = selection.nodes.value
+ expect(selection.node.value?.x).toBe(10)
+
+ active.value = false
+ editor.graph.updateNodePreview(first.id, { x: 80 })
+ editor.select([second.id])
+ editor.graph.updateNodePreview(second.id, { x: 130 })
+ expect(selection.nodes.value).toBe(initial)
+ expect(selection.node.value?.x).toBe(10)
+
+ active.value = true
+ expect(selection.node.value?.id).toBe(second.id)
+ expect(selection.node.value?.x).toBe(130)
+ editor.graph.updateNodePreview(second.id, { x: 160 })
+ expect(selection.node.value?.x).toBe(160)
+
+ const last = selection.node.value
+ selection.dispose()
+ active.value = false
+ active.value = true
+ editor.graph.updateNodePreview(second.id, { x: 200 })
+ expect(last?.x).toBe(160)
+ } finally {
+ selection.dispose()
+ fixture.dispose()
+ }
+ })
+
test('updates only consumers of changed properties, not scene catalogs or the graph object', () => {
const fixture = setup()
const { editor, first, second, selection } = fixture
diff --git a/tests/engine/vue/lifecycle/retention.test.ts b/tests/engine/vue/lifecycle/retention.test.ts
new file mode 100644
index 000000000..eb846c808
--- /dev/null
+++ b/tests/engine/vue/lifecycle/retention.test.ts
@@ -0,0 +1,212 @@
+import { expect, test } from 'bun:test'
+
+import { defineComponent, h, KeepAlive, nextTick, ref, watchEffect } from 'vue'
+
+import { createEditor } from '@open-pencil/core/editor'
+
+import { usePropScrub } from '#vue/controls/prop-scrub/use'
+import { useUndoBatch } from '#vue/controls/undo-batch/use'
+import { provideRetainedActivity } from '#vue/lifecycle/retention/context'
+import { createRetainedScopePlugin } from '#vue/lifecycle/retention/plugin'
+import { useRetainedPopup } from '#vue/lifecycle/retention/popup'
+import { useFontPicker } from '#vue/primitives/FontPicker/useFontPicker'
+
+import { expectDefined } from '#tests/helpers/assert'
+import { createTestRenderer, hostNode } from '#tests/helpers/vue/renderer'
+
+async function flushRetention() {
+ await nextTick()
+ await nextTick()
+}
+
+test('suspends descendant scopes, cancels previews, closes popups and refreshes on activation', async () => {
+ const editor = createEditor()
+ const shape = editor.graph.createNode('RECTANGLE', editor.state.currentPageId, { x: 10 })
+ editor.select([shape.id])
+ const active = ref(true),
+ value = ref(0)
+ let mounts = 0,
+ renders = 0,
+ effects = 0
+ const popup = ref(false)
+ const Field = defineComponent({
+ setup() {
+ mounts++
+ useRetainedPopup(popup)
+ const scrub = usePropScrub(editor)
+ scrub.updateProp([shape], 'x', 50)
+ watchEffect(() => {
+ void value.value
+ effects++
+ })
+ return () => {
+ renders++
+ return h('span', `${value.value}:${popup.value}`)
+ }
+ }
+ })
+ const Panel = defineComponent({ setup: () => () => h(Field) })
+ const root = hostNode()
+ const app = createTestRenderer()
+ .createApp({
+ setup() {
+ provideRetainedActivity(active)
+ return () => h(KeepAlive, { max: 1 }, { default: () => (active.value ? h(Panel) : null) })
+ }
+ })
+ .use(createRetainedScopePlugin())
+ try {
+ app.mount(root)
+ popup.value = true
+ await flushRetention()
+ active.value = false
+ await flushRetention()
+ expect(editor.isInteractiveEditing()).toBe(false)
+ expect(shape.x).toBe(10)
+ expect(popup.value).toBe(false)
+ const before = { renders, effects }
+ value.value = 42
+ await flushRetention()
+ expect({ renders, effects }).toEqual(before)
+ active.value = true
+ await flushRetention()
+ expect(mounts).toBe(1)
+ expect(renders).toBeGreaterThan(before.renders)
+ expect(effects).toBe(before.effects + 1)
+ expect(root.children[0]?.text).toBe('42:false')
+ expect(popup.value).toBe(false)
+ } finally {
+ app.unmount()
+ editor.dispose()
+ }
+})
+
+test('finishes applied property-list batches and releases their interaction lease', async () => {
+ const editor = createEditor()
+ const shape = editor.graph.createNode('RECTANGLE', editor.state.currentPageId, { x: 10 })
+ const active = ref(true)
+ const Field = defineComponent({
+ setup() {
+ const batch = useUndoBatch(editor.undo, editor.beginInteractiveEdit)
+ batch.ensure('property', 'Change property')
+ editor.updateNodeWithUndo(shape.id, { x: 50 })
+ return () => h('span')
+ }
+ })
+ const app = createTestRenderer()
+ .createApp({
+ setup() {
+ provideRetainedActivity(active)
+ return () => h(KeepAlive, { max: 1 }, { default: () => (active.value ? h(Field) : null) })
+ }
+ })
+ .use(createRetainedScopePlugin())
+ try {
+ app.mount(hostNode())
+ expect(editor.undo.isBatching).toBe(true)
+ active.value = false
+ await flushRetention()
+ expect(editor.undo.isBatching).toBe(false)
+ expect(editor.isInteractiveEditing()).toBe(false)
+ expect(shape.x).toBe(50)
+ editor.undoAction()
+ expect(shape.x).toBe(10)
+ expect(editor.undo.canUndo).toBe(false)
+ } finally {
+ app.unmount()
+ editor.dispose()
+ }
+})
+
+test('discards pending font results on deactivation and disposal, and permits a fresh request', async () => {
+ const first = Promise.withResolvers<string[]>()
+ const second = Promise.withResolvers<string[]>()
+ const active = ref(true)
+ const state: { picker?: ReturnType<typeof useFontPicker> } = {}
+ let requests = 0
+ const Field = defineComponent({
+ setup() {
+ const picker = useFontPicker({
+ modelValue: ref('Inter'),
+ listFamilies: () => (++requests === 1 ? first.promise : second.promise)
+ })
+ useRetainedPopup(picker.open)
+ state.picker = picker
+ picker.open.value = true
+ return () => h('span')
+ }
+ })
+ const app = createTestRenderer()
+ .createApp({
+ setup() {
+ provideRetainedActivity(active)
+ return () => h(KeepAlive, { max: 1 }, { default: () => (active.value ? h(Field) : null) })
+ }
+ })
+ .use(createRetainedScopePlugin())
+ try {
+ app.mount(hostNode())
+ await flushRetention()
+ const picker = expectDefined(state.picker, 'font picker')
+ expect(picker.loading.value).toBe(true)
+ active.value = false
+ await flushRetention()
+ first.resolve(['Stale font'])
+ await flushRetention()
+ expect(picker.families.value).toEqual([])
+ expect(picker.loading.value).toBe(false)
+ expect(picker.open.value).toBe(false)
+ active.value = true
+ await flushRetention()
+ picker.open.value = true
+ await flushRetention()
+ expect(requests).toBe(2)
+ expect(picker.loading.value).toBe(true)
+ } finally {
+ app.unmount()
+ second.resolve(['Disposed font'])
+ }
+ await flushRetention()
+ expect(state.picker?.families.value).toEqual([])
+ expect(state.picker?.loading.value).toBe(false)
+})
+
+test('an interrupted deactivation does not pause a reactivated or unmounted scope', async () => {
+ const active = ref(true),
+ value = ref(0)
+ let renders = 0
+ const Field = defineComponent({
+ setup: () => () => {
+ renders++
+ return h('span', String(value.value))
+ }
+ })
+ const app = createTestRenderer()
+ .createApp({
+ setup() {
+ provideRetainedActivity(active)
+ return () => h(KeepAlive, { max: 1 }, { default: () => (active.value ? h(Field) : null) })
+ }
+ })
+ .use(createRetainedScopePlugin())
+ try {
+ app.mount(hostNode())
+ active.value = false
+ await nextTick()
+ active.value = true
+ await flushRetention()
+ const before = renders
+ value.value++
+ await flushRetention()
+ expect(renders).toBe(before + 1)
+ active.value = false
+ await nextTick()
+ } finally {
+ app.unmount()
+ }
+ await flushRetention()
+ const before = renders
+ value.value++
+ await flushRetention()
+ expect(renders).toBe(before)
+})
diff --git a/tests/helpers/vue/renderer.ts b/tests/helpers/vue/renderer.ts
new file mode 100644
index 000000000..23614cf11
--- /dev/null
+++ b/tests/helpers/vue/renderer.ts
@@ -0,0 +1,54 @@
+import { createRenderer } from 'vue'
+
+export type HostNode = {
+ children: HostNode[]
+ parent: HostNode | null
+ text: string
+}
+
+export function hostNode(text = ''): HostNode {
+ return { children: [], parent: null, text }
+}
+
+function remove(child: HostNode): void {
+ const parent = child.parent
+ if (!parent) return
+ const index = parent.children.indexOf(child)
+ if (index !== -1) parent.children.splice(index, 1)
+ child.parent = null
+}
+
+export function createTestRenderer() {
+ return createRenderer<HostNode, HostNode>({
+ patchProp: () => undefined,
+ insert(child, parent, anchor) {
+ remove(child)
+ child.parent = parent
+ const index = anchor ? parent.children.indexOf(anchor) : -1
+ if (index < 0) parent.children.push(child)
+ else parent.children.splice(index, 0, child)
+ },
+ remove,
+ createElement: () => hostNode(),
+ createText: hostNode,
+ createComment: hostNode,
+ setText(node, text) {
+ node.text = text
+ },
+ setElementText(node, text) {
+ node.text = text
+ },
+ parentNode: (node) => node.parent,
+ nextSibling(node) {
+ const parent = node.parent
+ return parent?.children[parent.children.indexOf(node) + 1] ?? null
+ },
+ querySelector: () => null,
+ setScopeId: () => undefined,
+ insertStaticContent(content, parent, anchor) {
+ const node = hostNode(content)
+ this.insert(node, parent, anchor)
+ return [node, node]
+ }
+ })
+}