Skip to content

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

fix: keep dialogs still while they open and close (#1457)

Danila Poyarkov84c4dd03c68e
diff --git a/changes/1457/fixed.md b/changes/1457/fixed.md
new file mode 100644
index 000000000..d212e3d4e
--- /dev/null
+++ b/changes/1457/fixed.md
@@ -0,0 +1 @@
+- Dialogs keep their content still while they open and close, instead of redrawing a cleared name, the other choice's labels, or emptied fields as they fade out, and open on their loaded content rather than filling in after.
diff --git a/oxlint.json b/oxlint.json
index 0cec97a2a..7149829ce 100644
--- a/oxlint.json
+++ b/oxlint.json
@@ -155,6 +155,7 @@
"open-pencil/no-structuredclone-scene-arrays": "error",
"open-pencil/no-vue-style-blocks": "error",
"open-pencil/no-native-title-attributes-in-vue": "error",
+ "open-pencil/no-overlay-content-from-open-state": "error",
"open-pencil/no-hardcoded-tip-labels-in-vue": "error",
"open-pencil/no-raw-svg-in-app-vue-templates": "error",
"open-pencil/no-ui-helper-calls-in-vue-templates": "error",
diff --git a/src/AGENTS.md b/src/AGENTS.md
index e46e28302..ca4776cb0 100644
--- a/src/AGENTS.md
+++ b/src/AGENTS.md
@@ -98,10 +98,13 @@ The supported browser baseline lives in `src/app/shell/support/baseline.ts` and
- Store-free presets live in `src/theme/motion/` and compose into owning themes; keep what moves, geometry, and feature-specific spring values local. Share repeated duration and easing values. Policy resolution: Shell above.
- Collapsibles use Reka state attributes and measured CSS variables with `animate-collapsible-down` / `animate-collapsible-up`; keep padding and borders inside the animated height wrapper.
- Respect `prefers-reduced-motion` in CSS and Motion; simplify nonessential motion while preserving state changes and feedback. Verify opening, closing, interrupted transitions, reduced motion, and scroll behavior. Expanding historical chat content must not force the transcript to the bottom.
+- A dialog keeps drawing what it showed while it animates closed: derive `open` from the live state, draw the content through `useHeldContent`, and reset fields as it opens, never as it closes. Close it through `open`, never by unmounting it with `v-if`; popovers, menus, and tooltips close at once (`motionStyles.floating`) (`open-pencil/no-overlay-content-from-open-state`, `src/components/ui/overlay/held.ts`).
+- An overlay opens on its loaded content: read its data before opening, or keep the last known value, rather than drawing a default that then changes. A neutral loading state is fine; a definite wrong one such as "Needs key" or "0 members" is not (`src/components/cloud/share/CloudShareHost.vue`, `src/components/libraries/useLibraryManager.ts`).
### Storybook
- Colocate `ComponentName.stories.ts` with `ComponentName.vue`; multipart compositions may use a descriptive family name. Preserve explicit titles and exported story names during moves. Default playgrounds stay static; interaction flows get named stories. Prefer inline story fixtures for small app-local states; use colocated `examples/<Variant>.vue` SFCs for substantial templates or fixtures that need SFC template/slot typing, including app-only fixtures (shared SDK examples follow `packages/vue/AGENTS.md`, Documentation). Story templates compile at runtime, so they must be plain JavaScript with no TypeScript syntax, and `icon-lucide-*` tags do not resolve there; import icons from `~icons/...` and register them.
- Titles mirror ownership in Title Case: `Design System/<Family>/<Component>` for `src/components/ui/<family>`, `App/<Area>/…` for app components, `Vue SDK/…` for SDK primitives. Two files share a title only to keep a heavy example out of the docs page (`packages/vue/src/primitives/BindableValue/BindableValueModeEdit.stories.ts`); the sidebar order lives in `.storybook/preview.ts`.
- Every story must render, pass its play function, and pass axe in the dark and light themes: `tests/e2e/storybook/stories.spec.ts` runs them all in `bun run test:storybook`, so a play function asserts behavior that stays true, not copy or obsolete markup. Exempt an axe rule only for third-party markup or a deliberate demo state, scoped as narrowly as axe allows and explained where it is set (`.storybook/preview.ts`, `src/components/chat/ChatMarkdown.stories.ts`).
+- Storybook runs with reduced motion, which turns overlay animations off; a spec checking what an overlay draws while it animates opts back in and records each frame with `recordOverlayFrames` (`tests/e2e/storybook/overlay-states.spec.ts`).
- Isolated visual states of feedback components belong in stories, not Playwright application screenshots. Do not add automated tests or snapshot baselines for CSS-only changes (spacing, sizing, colors, breakpoints); verify those visually. Settings E2E covers integration behavior: feedback appearance, validation and focus, retained drafts, successful retries.
diff --git a/src/app/ai/models/settings/status.ts b/src/app/ai/models/settings/status.ts
index 668703d5c..4ff778ce3 100644
--- a/src/app/ai/models/settings/status.ts
+++ b/src/app/ai/models/settings/status.ts
@@ -70,6 +70,8 @@ export function modelConnectionState({
}
}
if (credential === 'locked' || credential === 'unavailable') return 'unavailable'
+ // Not read yet: saying the key is missing before knowing would flash a wrong state.
+ if (credential === undefined) return 'checking'
return 'needs-credential'
}
diff --git a/src/app/ai/models/settings/use.ts b/src/app/ai/models/settings/use.ts
index 98d61ae9b..1812ed1d0 100644
--- a/src/app/ai/models/settings/use.ts
+++ b/src/app/ai/models/settings/use.ts
@@ -12,6 +12,12 @@ import {
import { modelProviderName } from '@/app/ai/models/provider-name'
import type { CredentialStatus } from '@/app/settings/credentials/types'
+/**
+ * Credential statuses as last read, shared by every view of the model list, so reopening
+ * Settings draws them at once instead of starting from nothing.
+ */
+const knownStatuses = ref<Record<string, CredentialStatus>>({})
+
export function useModelSettings() {
let version = 0
let disposed = false
@@ -20,7 +26,7 @@ export function useModelSettings() {
disposed = true
})
- const statusByConnection = ref<Record<string, CredentialStatus>>({})
+ const statusByConnection = knownStatuses
const profiles = computed(() =>
aiModelSettings.value.models.map((profile) => {
diff --git a/src/app/settings/navigation/use.ts b/src/app/settings/navigation/use.ts
index 36a85fa4c..71289c7be 100644
--- a/src/app/settings/navigation/use.ts
+++ b/src/app/settings/navigation/use.ts
@@ -25,19 +25,30 @@ interface SettingsFormGuard {
/** One navigation policy for every editor in the Settings window. */
export function createSettingsNavigation() {
const active = shallowRef<SettingsFormGuard | null>(null)
- const pending = shallowRef<{ form: SettingsFormGuard; action: () => void } | null>(null)
+ const pending = shallowRef<{
+ form: SettingsFormGuard
+ action: () => void
+ closesWindow: boolean
+ } | null>(null)
- function leave(form: SettingsFormGuard | null, action: () => void) {
- active.value = null
- form?.cancel()
+ /**
+ * Leaves the open editor. Closing the window instead keeps it, and the window as it was, until
+ * the window has animated out and the editor unmounts and unregisters; cancelling it first
+ * would slide it back to its list in front of the person.
+ */
+ function leave(form: SettingsFormGuard | null, action: () => void, closesWindow: boolean) {
+ if (!closesWindow) {
+ active.value = null
+ form?.cancel()
+ }
action()
}
- function request(action: () => void) {
+ function request(action: () => void, { closesWindow = false } = {}) {
const form = active.value
if (form?.busy.value) return
- if (form?.dirty.value) pending.value = { form, action }
- else leave(form, action)
+ if (form?.dirty.value) pending.value = { form, action, closesWindow }
+ else leave(form, action, closesWindow)
}
return {
@@ -67,7 +78,7 @@ export function createSettingsNavigation() {
const request = pending.value
if (!request || request.form !== active.value || request.form.busy.value) return
pending.value = null
- leave(request.form, request.action)
+ leave(request.form, request.action, request.closesWindow)
}
}
}
diff --git a/src/components/assets-panel/AssetsPanel.vue b/src/components/assets-panel/AssetsPanel.vue
index d54c8ef4b..3a053c649 100644
--- a/src/components/assets-panel/AssetsPanel.vue
+++ b/src/components/assets-panel/AssetsPanel.vue
@@ -30,6 +30,7 @@ import AppPlaceholder from '@/components/ui/feedback/AppPlaceholder.vue'
import AppInput from '@/components/ui/input/AppInput.vue'
import { useMenuUI } from '@/components/ui/menu/menu'
import MenuScrollArea from '@/components/ui/menu/MenuScrollArea.vue'
+import { useHeldContent } from '@/components/ui/overlay/held'
import Tip from '@/components/ui/overlay/Tip.vue'
import SegmentedControl from '@/components/ui/select/SegmentedControl.vue'
import { ASSET_GRID_THUMBNAIL_SIZE, ASSET_LIST_THUMBNAIL_SIZE } from '@/constants'
@@ -206,6 +207,11 @@ const selectedAsset = computed(
() => assets.value.find((asset) => asset.id === selectedAssetId.value) ?? null
)
const selectedPreviewNodeId = computed(() => selectedAsset.value?.componentId ?? null)
+// An asset deleted while its details are open closes them; they keep showing it as they fade.
+const shownAsset = useHeldContent(selectedAsset)
+watch(selectedAsset, (asset) => {
+ if (!asset) detailsOpen.value = false
+})
onMounted(() => {
void libraryService.refresh(editor)
@@ -215,10 +221,12 @@ function clearPreview() {
previewBlob.value = null
}
-async function updatePreview() {
+async function updatePreview(opening = false) {
+ // Closing keeps the preview the dialog showed while it animates out.
+ if (!detailsOpen.value && !opening) return
const requestId = ++previewRequestId
const nodeId = selectedPreviewNodeId.value
- if (!detailsOpen.value || !nodeId) {
+ if (!nodeId) {
clearPreview()
return
}
@@ -243,12 +251,19 @@ async function updatePreview() {
}
}
-watch([detailsOpen, selectedPreviewNodeId, () => editor.state.sceneVersion], updatePreview, {
- flush: 'post'
-})
+watch(
+ [detailsOpen, selectedPreviewNodeId, () => editor.state.sceneVersion],
+ () => updatePreview(),
+ {
+ flush: 'post'
+ }
+)
-function openDetails(asset: LocalAsset) {
+/** Renders the preview before opening, so the dialog never shows another asset's or none. */
+async function openDetails(asset: LocalAsset) {
+ if (asset.id !== selectedAssetId.value) clearPreview()
selectedAssetId.value = asset.id
+ await updatePreview(true)
detailsOpen.value = true
}
@@ -311,7 +326,7 @@ function focusAsset(asset: LocalAsset) {
function onAssetKeydown(event: KeyboardEvent, asset: LocalAsset) {
if ((event.metaKey || event.ctrlKey) && event.code === 'Enter') {
event.preventDefault()
- openDetails(asset)
+ void openDetails(asset)
return
}
if (event.code === 'Enter' || event.code === 'Space') {
@@ -387,7 +402,7 @@ async function insertSelectedAsset() {
? 'flex min-w-0 flex-col items-center gap-1 p-1.5'
: 'flex w-full items-center gap-2 px-1.5 py-1'
]"
- @click="openDetails(asset)"
+ @click="void openDetails(asset)"
@keydown="onAssetKeydown($event, asset)"
@dragstart="onDragStart($event, asset)"
>
@@ -482,7 +497,7 @@ async function insertSelectedAsset() {
<ContextMenuItem
data-test-id="asset-context-view-details"
:class="contextMenu.item"
- @select="openDetails(asset)"
+ @select="void openDetails(asset)"
>
{{ panels.viewDetails }}
</ContextMenuItem>
@@ -508,24 +523,22 @@ async function insertSelectedAsset() {
<LibraryManagerDialog v-model="librariesOpen" :initial-section="libraryInitialSection" />
<AppDialogRoot
- v-if="selectedAsset"
+ v-if="shownAsset"
v-model:open="detailsOpen"
size="lg"
data-test-id="asset-details-dialog"
>
<div class="flex items-center justify-between border-b border-border px-4 py-3">
<div class="flex min-w-0 items-center gap-2">
- <component :is="nodeIcon(selectedAsset.node)" class="size-4 shrink-0 text-component" />
+ <component :is="nodeIcon(shownAsset.node)" class="size-4 shrink-0 text-component" />
<div class="min-w-0">
- <DialogTitle :class="dialog.title" class="truncate">{{
- selectedAsset.name
- }}</DialogTitle>
+ <DialogTitle :class="dialog.title" class="truncate">{{ shownAsset.name }}</DialogTitle>
<p class="mt-0.5 text-[11px] text-muted">
{{
- selectedAsset.node.type === 'COMPONENT_SET' ? panels.componentSet : panels.component
+ shownAsset.node.type === 'COMPONENT_SET' ? panels.componentSet : panels.component
}}
- <span v-if="selectedAsset.variantCount > 0">
- · {{ selectedAsset.variantCount }} variants</span
+ <span v-if="shownAsset.variantCount > 0">
+ · {{ shownAsset.variantCount }} variants</span
>
</p>
</div>
@@ -548,7 +561,7 @@ async function insertSelectedAsset() {
v-if="previewURL"
data-test-id="asset-details-preview-image"
:src="previewURL"
- :alt="`${selectedAsset.name} preview`"
+ :alt="`${shownAsset.name} preview`"
class="max-h-[120px] max-w-[210px] object-contain"
/>
<div v-else class="text-center">
@@ -558,11 +571,11 @@ async function insertSelectedAsset() {
/>
<component
v-else
- :is="nodeIcon(selectedAsset.node)"
+ :is="nodeIcon(shownAsset.node)"
class="mx-auto size-8 text-component"
/>
<p class="mt-2 max-w-44 truncate text-xs font-medium text-surface">
- {{ selectedAsset.name }}
+ {{ shownAsset.name }}
</p>
</div>
</div>
@@ -577,25 +590,25 @@ async function insertSelectedAsset() {
</div>
<div class="min-w-0 p-4">
- <section v-if="selectedAsset.description" class="mb-4">
+ <section v-if="shownAsset.description" class="mb-4">
<h3 class="text-[11px] font-medium tracking-wider text-muted uppercase">
{{ panels.description }}
</h3>
<p data-test-id="asset-details-description" class="mt-1 text-xs leading-5 text-surface">
- {{ selectedAsset.description }}
+ {{ shownAsset.description }}
</p>
</section>
- <section v-if="selectedAsset.sourceLibraryKey" class="mb-4">
+ <section v-if="shownAsset.sourceLibraryKey" class="mb-4">
<h3 class="text-[11px] font-medium tracking-wider text-muted uppercase">
{{ panels.assetLibraryBadge }}
</h3>
<p data-test-id="asset-details-library" class="mt-1 break-all text-xs text-muted">
- {{ selectedAsset.sourceLibraryKey }}
+ {{ shownAsset.sourceLibraryKey }}
</p>
</section>
- <section v-if="selectedAsset.docsURL" class="mb-4">
+ <section v-if="shownAsset.docsURL" class="mb-4">
<h3 class="text-[11px] font-medium tracking-wider text-muted uppercase">
{{ panels.documentation }}
</h3>
@@ -605,20 +618,20 @@ async function insertSelectedAsset() {
size="xs"
data-test-id="asset-details-docs"
class="mt-1"
- @click="selectedAsset.docsURL ? openExternalLink(selectedAsset.docsURL) : undefined"
+ @click="shownAsset.docsURL ? openExternalLink(shownAsset.docsURL) : undefined"
>
<icon-lucide-book-open class="size-3" />
{{ panels.openDocs }}
</AppButton>
</section>
- <section v-if="selectedAsset.variants.length > 0">
+ <section v-if="shownAsset.variants.length > 0">
<h3 class="text-[11px] font-medium tracking-wider text-muted uppercase">
{{ panels.properties }}
</h3>
<div class="mt-2 flex flex-col gap-2">
<div
- v-for="variant in selectedAsset.variants"
+ v-for="variant in shownAsset.variants"
:key="variant.name"
data-test-id="asset-details-property"
class="rounded border border-border bg-input/40 px-2 py-1.5"
diff --git a/src/components/chat/ACPPermissionDialog.vue b/src/components/chat/ACPPermissionDialog.vue
index e95c26274..131f90c90 100644
--- a/src/components/chat/ACPPermissionDialog.vue
+++ b/src/components/chat/ACPPermissionDialog.vue
@@ -16,8 +16,11 @@ import {
respondToPermission
} from '@/app/ai/agents/acp/permission'
import { AppAlertDialogRoot } from '@/components/ui/dialog'
+import { useHeldContent } from '@/components/ui/overlay/held'
const open = computed(() => currentPermission.value !== null)
+// Answering clears the request; the dialog keeps showing it while it animates closed.
+const permission = useHeldContent(currentPermission)
const { ai } = useI18n()
interface ToolCallInfo {
title?: string
@@ -25,7 +28,7 @@ interface ToolCallInfo {
}
const toolCall = computed(
- (): ToolCallInfo => (currentPermission.value?.request.toolCall as ToolCallInfo) ?? {}
+ (): ToolCallInfo => (permission.value?.request.toolCall as ToolCallInfo) ?? {}
)
const toolName = computed(() => toolCall.value.title ?? ai.value.unknownTool)
@@ -41,11 +44,11 @@ const toolInput = computed(() => {
})
const allowOptions = computed(
- () => currentPermission.value?.request.options.filter((o) => o.kind.startsWith('allow')) ?? []
+ () => permission.value?.request.options.filter((o) => o.kind.startsWith('allow')) ?? []
)
const rejectOptions = computed(
- () => currentPermission.value?.request.options.filter((o) => o.kind.startsWith('reject')) ?? []
+ () => permission.value?.request.options.filter((o) => o.kind.startsWith('reject')) ?? []
)
function handleDismiss() {
diff --git a/src/components/cloud-portal/account/PortalAccountSecurity.vue b/src/components/cloud-portal/account/PortalAccountSecurity.vue
index 3b204573b..b869dde53 100644
--- a/src/components/cloud-portal/account/PortalAccountSecurity.vue
+++ b/src/components/cloud-portal/account/PortalAccountSecurity.vue
@@ -10,6 +10,7 @@ import AppButton from '@/components/ui/button/AppButton.vue'
import AppConfirmationDialog from '@/components/ui/dialog/AppConfirmationDialog.vue'
import AppAlert from '@/components/ui/feedback/AppAlert.vue'
import AppBadge from '@/components/ui/feedback/AppBadge.vue'
+import { useHeldContent } from '@/components/ui/overlay/held'
import type { PortalLinkedMethod, PortalSignInMethod } from '../types'
@@ -63,8 +64,9 @@ const confirming = ref<
| { kind: 'passkey'; id: string; name: string }
| null
>(null)
+const confirmingShown = useHeldContent(confirming)
const confirmation = computed(() => {
- const pending = confirming.value
+ const pending = confirmingShown.value
if (!pending) return null
const words = messages.value
return pending.kind === 'unlink'
@@ -211,7 +213,7 @@ function confirm() {
</SettingsSection>
<AppConfirmationDialog
- :open="confirmation !== null"
+ :open="confirming !== null"
tone="danger"
:heading="confirmation?.heading ?? ''"
:description="confirmation?.description"
diff --git a/src/components/cloud-portal/account/PortalAuthenticatorSetup.vue b/src/components/cloud-portal/account/PortalAuthenticatorSetup.vue
index 63307f30e..3fc1190a8 100644
--- a/src/components/cloud-portal/account/PortalAuthenticatorSetup.vue
+++ b/src/components/cloud-portal/account/PortalAuthenticatorSetup.vue
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { computedAsync } from '@vueuse/core'
import { toDataURL } from 'qrcode'
-import { computed, ref } from 'vue'
+import { computed, ref, watch } from 'vue'
import { useCloudPortalMessages } from '@open-pencil/vue/i18n'
@@ -26,11 +26,22 @@ const emit = defineEmits<{ verify: [code: string] }>()
const ui = portalForm()
const messages = useCloudPortalMessages()
const code = ref('')
+watch(open, (value) => {
+ if (value) code.value = ''
+})
const secret = computed(() =>
URL.canParse(uri) ? (new URL(uri).searchParams.get('secret') ?? '') : ''
)
// A newer key replaces a QR code still rendering for an older one; a failed render leaves the key.
-const image = computedAsync(() => toDataURL(uri, { margin: 1, width: 176 }).catch(() => null), null)
+const rendered = computedAsync(
+ () =>
+ toDataURL(uri, { margin: 1, width: 176 })
+ .then((data) => ({ uri, data }))
+ .catch(() => null),
+ null
+)
+/** Only the current key's code, so a reopened dialog never shows the previous one. */
+const image = computed(() => (rendered.value?.uri === uri ? rendered.value.data : null))
</script>
<template>
@@ -41,7 +52,10 @@ const image = computedAsync(() => toDataURL(uri, { margin: 1, width: 176 }).catc
:close-label="messages.cancel"
/>
<AppDialogBody :ui="{ body: 'flex flex-col items-center gap-4' }">
- <img v-if="image" :src="image" alt="" class="size-44 rounded-lg bg-white p-2" />
+ <!-- The box keeps its size while the code renders, so the dialog does not jump. -->
+ <div class="size-44 rounded-lg bg-white p-2">
+ <img v-if="image" :src="image" alt="" class="size-full" />
+ </div>
<div class="flex w-full flex-col gap-1.5">
<span :class="ui.label()">{{ messages.authenticatorSetupKey }}</span>
<AppCopyField
diff --git a/src/components/cloud-portal/account/PortalPasswordDialog.vue b/src/components/cloud-portal/account/PortalPasswordDialog.vue
index c604aeaeb..27fd85844 100644
--- a/src/components/cloud-portal/account/PortalPasswordDialog.vue
+++ b/src/components/cloud-portal/account/PortalPasswordDialog.vue
@@ -37,8 +37,9 @@ const current = ref('')
const next = ref('')
const repeat = ref('')
const errors = ref<{ current?: string; next?: string; repeat?: string }>({})
+// Cleared as it opens: clearing as it closes would empty the fields during its exit animation.
watch(open, (value) => {
- if (!value) {
+ if (value) {
current.value = ''
next.value = ''
repeat.value = ''
diff --git a/src/components/cloud-portal/account/PortalSessions.vue b/src/components/cloud-portal/account/PortalSessions.vue
index af8f420f4..2baabeff3 100644
--- a/src/components/cloud-portal/account/PortalSessions.vue
+++ b/src/components/cloud-portal/account/PortalSessions.vue
@@ -9,6 +9,7 @@ import SettingsSection from '@/components/settings/layout/SettingsSection.vue'
import AppButton from '@/components/ui/button/AppButton.vue'
import AppConfirmationDialog from '@/components/ui/dialog/AppConfirmationDialog.vue'
import AppBadge from '@/components/ui/feedback/AppBadge.vue'
+import { useHeldContent } from '@/components/ui/overlay/held'
import { portalList } from '@/theme/cloud-portal/list'
import type { PortalDevice, PortalSession, PortalSignIn } from '../types'
@@ -37,8 +38,9 @@ const messages = useCloudPortalMessages()
const labels = usePortalDeviceLabels()
const others = computed(() => sessions.filter((session) => !session.current))
const confirming = ref<{ kind: 'one'; session: PortalSession } | { kind: 'others' } | null>(null)
+const confirmingShown = useHeldContent(confirming)
const confirmation = computed(() => {
- const pending = confirming.value
+ const pending = confirmingShown.value
if (!pending) return null
const words = messages.value
return pending.kind === 'others'
@@ -139,7 +141,7 @@ function confirm() {
</SettingsSection>
<AppConfirmationDialog
- :open="confirmation !== null"
+ :open="confirming !== null"
tone="danger"
:heading="confirmation?.heading ?? ''"
:description="confirmation?.description"
diff --git a/src/components/cloud-portal/console/PortalAccessRequests.vue b/src/components/cloud-portal/console/PortalAccessRequests.vue
index 52b562766..ac66c4319 100644
--- a/src/components/cloud-portal/console/PortalAccessRequests.vue
+++ b/src/components/cloud-portal/console/PortalAccessRequests.vue
@@ -8,6 +8,7 @@ import AppButton from '@/components/ui/button/AppButton.vue'
import AppConfirmationDialog from '@/components/ui/dialog/AppConfirmationDialog.vue'
import AppPlaceholder from '@/components/ui/feedback/AppPlaceholder.vue'
import AppTextarea from '@/components/ui/input/AppTextarea.vue'
+import { useHeldContent } from '@/components/ui/overlay/held'
import SegmentedControl from '@/components/ui/select/SegmentedControl.vue'
import { portalForm } from '@/theme/cloud-portal/form'
import { portalList } from '@/theme/cloud-portal/list'
@@ -55,8 +56,9 @@ function detail(request: AccessRequest) {
/** Declining or taking access away is asked once more, with a note for the other administrators. */
const confirming = ref<{ kind: 'reject' | 'revoke'; request: AccessRequest } | null>(null)
const note = ref('')
+const confirmingShown = useHeldContent(confirming)
const confirmation = computed(() => {
- const pending = confirming.value
+ const pending = confirmingShown.value
if (!pending) return null
const words = messages.value
const name = pending.request.name ?? pending.request.email
@@ -161,7 +163,7 @@ function confirm() {
<template #icon><icon-lucide-inbox class="size-5" /></template>
</AppPlaceholder>
<AppConfirmationDialog
- :open="confirmation !== null"
+ :open="confirming !== null"
tone="danger"
:heading="confirmation?.heading ?? ''"
:description="confirmation?.description"
diff --git a/src/components/cloud-portal/console/PortalPersonActions.vue b/src/components/cloud-portal/console/PortalPersonActions.vue
index e681ade42..5fb723316 100644
--- a/src/components/cloud-portal/console/PortalPersonActions.vue
+++ b/src/components/cloud-portal/console/PortalPersonActions.vue
@@ -16,6 +16,7 @@ import IconButton from '@/components/ui/button/IconButton.vue'
import AppConfirmationDialog from '@/components/ui/dialog/AppConfirmationDialog.vue'
import AppTextarea from '@/components/ui/input/AppTextarea.vue'
import { menu } from '@/components/ui/menu/menu'
+import { useHeldContent } from '@/components/ui/overlay/held'
import { portalForm } from '@/theme/cloud-portal/form'
import type { PortalPerson, PortalPersonAction } from '../types'
@@ -42,8 +43,9 @@ const form = portalForm()
const confirming = ref<PortalPersonAction | null>(null)
const reason = ref('')
+const confirmingShown = useHeldContent(confirming)
const confirmation = computed(() => {
- const action = confirming.value
+ const action = confirmingShown.value
if (!action) return null
const words = messages.value
const name = person.name
@@ -159,7 +161,7 @@ function confirm() {
</DropdownMenuPortal>
</DropdownMenuRoot>
<AppConfirmationDialog
- :open="confirmation !== null"
+ :open="confirming !== null"
:tone="confirmation?.tone"
:heading="confirmation?.heading ?? ''"
:description="confirmation?.description"
@@ -168,7 +170,7 @@ function confirm() {
@update:open="(open) => !open && (confirming = null)"
@confirm="confirm"
>
- <div v-if="confirming === 'suspend'" :class="[form.field(), 'mt-3']">
+ <div v-if="confirmingShown === 'suspend'" :class="[form.field(), 'mt-3']">
<label for="portal-suspend-reason" :class="form.label()">{{ messages.suspendReason }}</label>
<AppTextarea id="portal-suspend-reason" v-model="reason" :rows="2" maxlength="500" />
</div>
diff --git a/src/components/cloud-portal/sections/SecuritySection.vue b/src/components/cloud-portal/sections/SecuritySection.vue
index 27546e3ee..aeaf130a6 100644
--- a/src/components/cloud-portal/sections/SecuritySection.vue
+++ b/src/components/cloud-portal/sections/SecuritySection.vue
@@ -9,6 +9,7 @@ import { portalURL } from '@/app/cloud-portal/navigation'
import { usePortalAction, usePortalLoad } from '@/app/cloud-portal/state'
import { formatDate } from '@/app/i18n/date'
import AppAlert from '@/components/ui/feedback/AppAlert.vue'
+import { useHeldContent } from '@/components/ui/overlay/held'
import PortalAccountSecurity from '../account/PortalAccountSecurity.vue'
import PortalAuthenticatorSetup from '../account/PortalAuthenticatorSetup.vue'
@@ -135,6 +136,10 @@ const busy = computed(
verifyAction.busy.value
)
const passwordError = computed(() => (passwordStep.value ? passwordAction.error.value : null))
+const passwordShown = useHeldContent(passwordStep)
+const passwordErrorShown = useHeldContent(passwordError, () => passwordStep.value !== null)
+const setupShown = useHeldContent(setupURI)
+const codesShown = useHeldContent(recoveryCodes)
const error = computed(
() =>
change.error.value ??
@@ -227,9 +232,9 @@ function addPasskey() {
<PortalPasswordDialog
:open="passwordStep !== null"
- :purpose="passwordStep === 'change' ? 'change' : 'confirm'"
+ :purpose="passwordShown === 'change' ? 'change' : 'confirm'"
:minimum-password-length="minimum"
- :error="passwordError"
+ :error="passwordErrorShown"
:saving="busy"
@update:open="(open) => !open && closePasswordStep()"
@submit="
@@ -237,18 +242,16 @@ function addPasskey() {
"
/>
<PortalAuthenticatorSetup
- v-if="setupURI"
- :open="true"
- :uri="setupURI"
+ :open="setupURI !== null"
+ :uri="setupShown ?? ''"
:error="verifyAction.error.value"
:verifying="busy"
@update:open="(open) => !open && closeAuthenticatorSetup()"
@verify="verifyAction.run"
/>
<PortalRecoveryCodes
- v-if="recoveryCodes"
- :open="true"
- :codes="recoveryCodes"
+ :open="recoveryCodes !== null"
+ :codes="codesShown ?? []"
@update:open="(open) => !open && (recoveryCodes = null)"
/>
</div>
diff --git a/src/components/cloud/connect/CloudConnectHost.vue b/src/components/cloud/connect/CloudConnectHost.vue
index a56d04f2e..2b4ae0f69 100644
--- a/src/components/cloud/connect/CloudConnectHost.vue
+++ b/src/components/cloud/connect/CloudConnectHost.vue
@@ -35,6 +35,7 @@ import { cloudServerHost } from '@/app/cloud/servers/address'
import { findCloudServer } from '@/app/cloud/servers/store'
import { cloudConnection } from '@/app/cloud/sessions/connection'
import { openExternalLink, toast } from '@/app/shell/ui'
+import { useHeldContent } from '@/components/ui/overlay/held'
import { OFFICIAL_CLOUD_URL } from '@/constants'
import CloudConnectDialog from './CloudConnectDialog.vue'
@@ -70,6 +71,23 @@ watch(cloudSignedIn, (signedIn) => {
}
})
+// Cancelling resets the attempt as the dialog closes; it keeps drawing the step it was on.
+const shown = useHeldContent(
+ () => ({
+ step: cloudConnectStep.value,
+ choosing: cloudConnectChoosing.value,
+ server: cloudConnectServer.value,
+ error: cloudConnectError.value,
+ failure: cloudConnectFailure.value,
+ busy: cloudConnectBusy.value,
+ email: cloudConnectEmail.value,
+ resent: cloudConnectResent.value,
+ device: device.value,
+ canGoBack: cloudConnectCanGoBack.value
+ }),
+ cloudConnectOpen
+)
+
function onOpenChange(open: boolean) {
if (!open) cancelCloudConnect()
}
@@ -93,18 +111,18 @@ function forgotPassword() {
:open="cloudConnectOpen"
v-model:kind="cloudConnectKind"
v-model:address="cloudConnectAddress"
- :step="cloudConnectStep"
+ :step="shown.step"
:official="official"
- :choosing="cloudConnectChoosing"
- :server="cloudConnectServer"
- :error="cloudConnectError"
- :failure="cloudConnectFailure"
- :busy="cloudConnectBusy"
- :email="cloudConnectEmail"
- :resent="cloudConnectResent"
- :device="device"
- :desktop="cloudConnectServer?.route === 'device'"
- :can-go-back="cloudConnectCanGoBack"
+ :choosing="shown.choosing"
+ :server="shown.server"
+ :error="shown.error"
+ :failure="shown.failure"
+ :busy="shown.busy"
+ :email="shown.email"
+ :resent="shown.resent"
+ :device="shown.device"
+ :desktop="shown.server?.route === 'device'"
+ :can-go-back="shown.canGoBack"
@update:open="onOpenChange"
@continue="continueCloudConnect"
@back="backCloudConnect"
diff --git a/src/components/cloud/invitation/CloudInvitationHost.vue b/src/components/cloud/invitation/CloudInvitationHost.vue
index e289ff393..b5dd9c1c7 100644
--- a/src/components/cloud/invitation/CloudInvitationHost.vue
+++ b/src/components/cloud/invitation/CloudInvitationHost.vue
@@ -18,6 +18,7 @@ import {
switchCloudInvitationAccount
} from '@/app/cloud/invitations/flow'
import { canOfferDesktopApp } from '@/app/cloud/links'
+import { useHeldContent } from '@/components/ui/overlay/held'
import CloudInvitationDialog from './CloudInvitationDialog.vue'
@@ -39,6 +40,11 @@ const summary = computed(() => {
return { ...invitation, expiresIn }
})
+// Dismissing clears the invitation; the dialog keeps drawing it while it animates closed.
+const shownInvitation = useHeldContent(summary, cloudInvitationOpen)
+const shownState = useHeldContent(cloudInvitationState, cloudInvitationOpen)
+const shownAccount = useHeldContent(cloudInvitationAccount, cloudInvitationOpen)
+
// Signing in for the invitation comes back here; check it again with the new account.
watch(cloudSignedIn, () => {
if (cloudInvitationOpen.value) void checkCloudInvitation()
@@ -48,9 +54,9 @@ watch(cloudSignedIn, () => {
<template>
<CloudInvitationDialog
:open="cloudInvitationOpen"
- :state="cloudInvitationState"
- :invitation="summary"
- :account="cloudInvitationAccount"
+ :state="shownState"
+ :invitation="shownInvitation"
+ :account="shownAccount"
:offer-desktop="canOfferDesktopApp()"
@update:open="(open) => !open && dismissCloudInvitation()"
@accept="acceptCloudInvitation"
diff --git a/src/components/cloud/share/CloudShareHost.vue b/src/components/cloud/share/CloudShareHost.vue
index 952ba7a61..dee8c5e36 100644
--- a/src/components/cloud/share/CloudShareHost.vue
+++ b/src/components/cloud/share/CloudShareHost.vue
@@ -12,6 +12,7 @@ import { useActiveEditorStoreRef } from '@/app/editor/active-store'
import { useDateFormat } from '@/app/i18n/date'
import { useSendLink } from '@/app/shell/share/link'
import { toast } from '@/app/shell/ui'
+import { useHeldContent } from '@/components/ui/overlay/held'
import CloudShareDialog from './CloudShareDialog.vue'
@@ -28,6 +29,20 @@ const target = computed(() => {
})
const cloudSharing = useCloudSharing(target)
const { sharing, linkURL, inviting } = cloudSharing
+
+/**
+ * The dialog appears once the document's sharing has loaded, so it never opens on a restricted
+ * document with no members and then fills in.
+ */
+const dialogOpen = computed({
+ get: () => cloudShareOpen.value && sharing.value !== null,
+ set: (open) => {
+ cloudShareOpen.value = open
+ }
+})
+// Losing the document, as after signing out, closes the dialog; it keeps drawing it as it fades.
+const shownTarget = useHeldContent(target)
+const shown = useHeldContent(sharing, dialogOpen)
const { sendsLink, copied, send } = useSendLink()
const workspace = computed(() => {
@@ -40,14 +55,17 @@ const workspace = computed(() => {
})
const dates = useDateFormat()
const members = computed(() =>
- (sharing.value?.members ?? []).map((member) => ({
+ (shown.value?.members ?? []).map((member) => ({
...member,
pendingUntil: member.pendingUntil ? dates.format(member.pendingUntil, 'day') : undefined
}))
)
async function refresh() {
- if (!(await cloudSharing.refresh())) toast.error(t.value.shareLoadFailed)
+ if (await cloudSharing.refresh()) return
+ toast.error(t.value.shareLoadFailed)
+ // Nothing loaded to show, so the dialog that was waiting for it does not open.
+ if (sharing.value === null) cloudShareOpen.value = false
}
/** Says when a change did not take; the dialog shows what the server kept either way. */
@@ -85,14 +103,14 @@ watch(
<template>
<CloudShareDialog
- v-if="target"
- v-model:open="cloudShareOpen"
+ v-if="shownTarget"
+ v-model:open="dialogOpen"
:document-name="storeRef?.state.documentName ?? ''"
:workspace="workspace"
:members="members"
- :link="sharing?.link ?? { access: 'restricted' }"
- :can-manage="sharing?.canManage ?? false"
- :links="sharing?.links"
+ :link="shown?.link ?? { access: 'restricted' }"
+ :can-manage="shown?.canManage ?? false"
+ :links="shown?.links"
:inviting="inviting"
:copied="copied"
:sends-link="sendsLink"
diff --git a/src/components/cloud/status/CloudDocumentStatusHost.vue b/src/components/cloud/status/CloudDocumentStatusHost.vue
index 084d98fe6..00d483e3d 100644
--- a/src/components/cloud/status/CloudDocumentStatusHost.vue
+++ b/src/components/cloud/status/CloudDocumentStatusHost.vue
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { useObjectUrl } from '@vueuse/core'
+import { isEqual } from 'es-toolkit'
import { computed, ref, shallowRef } from 'vue'
import { useRouter } from 'vue-router'
@@ -54,18 +55,26 @@ const choice = ref<CloudConflictChoice>('keep-both')
const localPreview = shallowRef<Blob | null>(null)
const localPreviewURL = useObjectUrl(localPreview)
const cloudSavedAt = ref<string | null>(null)
+let conflictRequest = 0
async function openConflict() {
const binding = store.getStorageBinding()
if (!binding) return
+ const request = ++conflictRequest
choice.value = 'keep-both'
- resolving.value = true
- const thumb = await getLocalCanvasStore().readThumb(binding.documentId)
- localPreview.value = thumb ? new Blob([Uint8Array.from(thumb)], { type: 'image/png' }) : null
+ const thumb = await getLocalCanvasStore()
+ .readThumb(binding.documentId)
+ .catch(() => null)
const stored = await createStorageAdapter(binding)
.getDocumentMetadata?.(binding.documentId)
.catch(() => null)
+ // A later request supersedes this one, and its own reads fill and open the dialog; Save to
+ // can also move the document elsewhere meanwhile, and these reads describe the old place.
+ if (request !== conflictRequest || !isEqual(store.getStorageBinding(), binding)) return
+ localPreview.value = thumb ? new Blob([Uint8Array.from(thumb)], { type: 'image/png' }) : null
cloudSavedAt.value = stored?.updatedAt ?? null
+ // Opened once both copies are read, so it never shows the last conflict's preview or time.
+ resolving.value = true
}
async function confirm(picked: CloudConflictChoice) {
diff --git a/src/components/cloud/versions/CloudVersionDialog.vue b/src/components/cloud/versions/CloudVersionDialog.vue
index 057a4af69..3e07174e0 100644
--- a/src/components/cloud/versions/CloudVersionDialog.vue
+++ b/src/components/cloud/versions/CloudVersionDialog.vue
@@ -17,6 +17,7 @@ import AppDialogRoot from '@/components/ui/dialog/AppDialogRoot.vue'
import AppAlert from '@/components/ui/feedback/AppAlert.vue'
import AppInput from '@/components/ui/input/AppInput.vue'
import AppTextarea from '@/components/ui/input/AppTextarea.vue'
+import { useHeldContent } from '@/components/ui/overlay/held'
import { cloudVersions } from '@/theme/cloud/versions'
/**
@@ -37,12 +38,15 @@ const open = computed({
if (!value) versionDialog.value = null
}
})
-const editing = computed(() => versionDialog.value?.version ?? null)
+const shown = useHeldContent(versionDialog)
+const editing = computed(() => shown.value?.version ?? null)
const trimmed = computed(() => name.value.trim())
+// Filled as it opens: clearing as it closes would empty the fields during its exit animation.
watch(versionDialog, (dialog) => {
- name.value = dialog?.version?.name ?? ''
- description.value = dialog?.version?.description ?? ''
+ if (!dialog) return
+ name.value = dialog.version?.name ?? ''
+ description.value = dialog.version?.description ?? ''
failed.value = false
})
diff --git a/src/components/cloud/workspace/CloudWorkspaceMembersDialog.vue b/src/components/cloud/workspace/CloudWorkspaceMembersDialog.vue
index 7d1d752b5..75385d6fb 100644
--- a/src/components/cloud/workspace/CloudWorkspaceMembersDialog.vue
+++ b/src/components/cloud/workspace/CloudWorkspaceMembersDialog.vue
@@ -18,6 +18,7 @@ import AppAlert from '@/components/ui/feedback/AppAlert.vue'
import AppBadge from '@/components/ui/feedback/AppBadge.vue'
import AppPlaceholder from '@/components/ui/feedback/AppPlaceholder.vue'
import AppInput from '@/components/ui/input/AppInput.vue'
+import { useHeldContent } from '@/components/ui/overlay/held'
import AppSelect from '@/components/ui/select/AppSelect.vue'
import AppTabsContent from '@/components/ui/tabs/AppTabsContent.vue'
import AppTabsList from '@/components/ui/tabs/AppTabsList.vue'
@@ -153,8 +154,9 @@ function invitationDetail(invitation: WorkspaceMembers['invitations'][number]):
const confirming = ref<
{ kind: 'leave' } | { kind: 'delete' } | { kind: 'remove'; userId: string; name: string } | null
>(null)
+const confirmingShown = useHeldContent(confirming)
const confirmation = computed(() => {
- const pending = confirming.value
+ const pending = confirmingShown.value
if (!pending) return null
if (pending.kind === 'delete') {
return {
@@ -177,11 +179,14 @@ const confirmation = computed(() => {
})
/** Deleting can't be undone, so it waits for the workspace's name. */
const typedName = ref('')
-watch(confirming, () => {
- typedName.value = ''
-})
+watch(
+ () => confirming.value !== null,
+ (isOpen) => {
+ if (isOpen) typedName.value = ''
+ }
+)
const confirmBlocked = computed(
- () => confirming.value?.kind === 'delete' && typedName.value.trim() !== workspaceName.trim()
+ () => confirmingShown.value?.kind === 'delete' && typedName.value.trim() !== workspaceName.trim()
)
function confirm() {
const pending = confirming.value
@@ -214,7 +219,8 @@ function invite() {
<AppTabsList :label="t.membersSections">
<AppTabsTrigger value="members">
{{ t.membersTab }}
- <template #trailing>
+ <!-- Counted once known; "0" while loading would be a wrong first frame. -->
+ <template v-if="members" #trailing>
<span class="text-muted tabular-nums">{{ allMembers.length }}</span>
</template>
</AppTabsTrigger>
@@ -434,7 +440,7 @@ function invite() {
</AppDialogFooter>
</AppDialogRoot>
<AppConfirmationDialog
- :open="confirmation !== null"
+ :open="confirming !== null"
tone="danger"
:heading="confirmation?.heading ?? ''"
:description="confirmation?.description"
@@ -444,7 +450,7 @@ function invite() {
@update:open="(isOpen) => !isOpen && (confirming = null)"
@confirm="confirm"
>
- <div v-if="confirming?.kind === 'delete'" :class="ui.confirmName()">
+ <div v-if="confirmingShown?.kind === 'delete'" :class="ui.confirmName()">
<label for="cloud-workspace-delete-name" :class="ui.label()">
{{ t.deleteWorkspaceTypeName({ workspace: workspaceName }) }}
</label>
diff --git a/src/components/cloud/workspace/CloudWorkspaceMembersHost.vue b/src/components/cloud/workspace/CloudWorkspaceMembersHost.vue
index d7c9b3fd9..db81582be 100644
--- a/src/components/cloud/workspace/CloudWorkspaceMembersHost.vue
+++ b/src/components/cloud/workspace/CloudWorkspaceMembersHost.vue
@@ -1,5 +1,5 @@
<script setup lang="ts">
-import { computed } from 'vue'
+import { computed, watch } from 'vue'
import { useCloudMessages } from '@open-pencil/vue/i18n'
@@ -23,11 +23,17 @@ import {
workspaceMembers,
type WorkspaceFailure
} from '@/app/cloud/workspaces/manage'
+import { useHeldContent } from '@/components/ui/overlay/held'
import CloudWorkspaceMembersDialog from './CloudWorkspaceMembersDialog.vue'
/** The one Members dialog, for whichever workspace Home opened it from. */
const t = useCloudMessages()
+// Leaving or deleting the workspace drops it; the dialog closes and keeps drawing it as it fades.
+const workspace = useHeldContent(membersWorkspace)
+watch(membersWorkspace, (current) => {
+ if (!current) membersOpen.value = false
+})
const failure = computed(() => {
const kind = membersFailure.value
if (!kind) return null
@@ -46,10 +52,10 @@ const failure = computed(() => {
<template>
<CloudWorkspaceMembersDialog
- v-if="membersWorkspace"
+ v-if="workspace"
v-model:open="membersOpen"
- :workspace-name="membersWorkspace.name"
- :can-manage="membersWorkspace.role === 'admin'"
+ :workspace-name="workspace.name"
+ :can-manage="workspace.role === 'admin'"
:self="membersSelf"
:members="workspaceMembers"
:loading="membersLoading"
diff --git a/src/components/document/UnsavedChangesDialog.vue b/src/components/document/UnsavedChangesDialog.vue
index 7847ed9c3..b6e5c5df0 100644
--- a/src/components/document/UnsavedChangesDialog.vue
+++ b/src/components/document/UnsavedChangesDialog.vue
@@ -10,11 +10,13 @@ import AppButton from '@/components/ui/button/AppButton.vue'
import AppAlertDialogRoot from '@/components/ui/dialog/AppAlertDialogRoot.vue'
import AppDialogFooter from '@/components/ui/dialog/AppDialogFooter.vue'
import AppDialogHeader from '@/components/ui/dialog/AppDialogHeader.vue'
+import { useHeldContent } from '@/components/ui/overlay/held'
import { documentCloseUI, documentCloseButtonUI } from '@/theme/document/close'
const files = useStore(filesMessages)
const common = useStore(commonMessages)
const saveButton = useTemplateRef('saveButton')
+const prompt = useHeldContent(closePrompt)
// The dialog mounts on open, so focusing the primary action when the target appears keeps
// Return on Save while Escape still cancels.
@@ -28,7 +30,7 @@ function updateOpen(open: boolean) {
<template>
<AppAlertDialogRoot :open="closePrompt !== null" @update:open="updateOpen">
<AppDialogHeader
- :heading="files.saveBeforeClosing({ name: closePrompt?.documentName ?? '' })"
+ :heading="files.saveBeforeClosing({ name: prompt?.documentName ?? '' })"
:description="files.saveBeforeClosingDescription"
:show-close="false"
:ui="documentCloseUI"
diff --git a/src/components/libraries/LibraryManagerDialog.vue b/src/components/libraries/LibraryManagerDialog.vue
index eff13bd34..b0c03aed4 100644
--- a/src/components/libraries/LibraryManagerDialog.vue
+++ b/src/components/libraries/LibraryManagerDialog.vue
@@ -40,6 +40,7 @@ async function openPublish() {
const {
section,
loading,
+ ready,
showAllPages,
applying,
visibleUpdateGroups,
@@ -69,7 +70,13 @@ function reviewUpdate(group: (typeof visibleUpdateGroups.value)[number]) {
</script>
<template>
- <AppDialogRoot v-model:open="open" size="lg" height="tall" data-test-id="asset-libraries-dialog">
+ <AppDialogRoot
+ :open="open && ready"
+ size="lg"
+ height="tall"
+ data-test-id="asset-libraries-dialog"
+ @update:open="open = $event"
+ >
<AppDialogHeader
:heading="panels.manageLibraries"
:description="panels.manageLibrariesDescription"
diff --git a/src/components/libraries/review/LibraryUpdateReviewDialog.vue b/src/components/libraries/review/LibraryUpdateReviewDialog.vue
index 40e212287..b0deeb9c8 100644
--- a/src/components/libraries/review/LibraryUpdateReviewDialog.vue
+++ b/src/components/libraries/review/LibraryUpdateReviewDialog.vue
@@ -13,6 +13,7 @@ import LibraryComparisonPreview from '@/components/libraries/review/LibraryCompa
import AppButton from '@/components/ui/button/AppButton.vue'
import IconButton from '@/components/ui/button/IconButton.vue'
import { AppDialogFooter, AppDialogHeader, AppDialogRoot } from '@/components/ui/dialog'
+import { useHeldContent } from '@/components/ui/overlay/held'
import SegmentedControl from '@/components/ui/select/SegmentedControl.vue'
const editor = useEditorStore()
@@ -34,6 +35,8 @@ interface ReviewOrigin {
let origin: ReviewOrigin | null = null
let accepted = false
let requestId = 0
+/** The canvas move toward the reviewed instance, which restoring the origin waits for. */
+let focusing: Promise<void> | null = null
const operationFailed = (cause: unknown) =>
notificationMessages.get().operationFailed({
error: cause instanceof Error ? cause.message : String(cause)
@@ -48,7 +51,8 @@ const modeOptions = computed(() => [
{ value: 'side-by-side', label: panels.value.sideBySide },
{ value: 'overlay', label: panels.value.overlay }
])
-const request = computed(() => libraryReviewRequest.value)
+// Closing clears the request; the dialog keeps reviewing it while it animates closed.
+const request = useHeldContent(libraryReviewRequest)
const currentInstanceId = computed(() => request.value?.instanceIds[instanceIndex.value] ?? null)
function pageIdForNode(nodeId: string): string | null {
@@ -61,11 +65,12 @@ function pageIdForNode(nodeId: string): string | null {
return null
}
-async function focusCurrentInstance() {
+async function focusCurrentInstance(currentRequest: number) {
const instanceId = currentInstanceId.value
if (!instanceId) return
const pageId = pageIdForNode(instanceId)
if (pageId && pageId !== editor.state.currentPageId) await editor.switchPage(pageId)
+ if (currentRequest !== requestId) return
editor.select([instanceId])
editor.zoomToSelection()
}
@@ -81,10 +86,11 @@ async function loadPreview() {
const next = createLibraryUpdatePreview(editor.graph, instanceId, revision)
if (currentRequest === requestId) {
preview.value = next
- await focusCurrentInstance()
+ focusing = focusCurrentInstance(currentRequest)
+ await focusing
}
} catch (cause) {
- toast.error(operationFailed(cause))
+ if (currentRequest === requestId) toast.error(operationFailed(cause))
} finally {
if (currentRequest === requestId) loading.value = false
}
@@ -94,7 +100,12 @@ async function restoreOrigin() {
const value = origin
origin = null
if (!value || accepted) return
+ // A page switch already under way lands first, then the origin replaces it.
+ await focusing?.catch(() => undefined)
+ // A review opened meanwhile owns the canvas now.
+ if (libraryReviewRequest.value) return
if (editor.state.currentPageId !== value.pageId) await editor.switchPage(value.pageId)
+ if (libraryReviewRequest.value) return
editor.select(value.selectedIds)
editor.state.panX = value.panX
editor.state.panY = value.panY
@@ -137,8 +148,12 @@ async function updateAll() {
}
}
-watch(request, (value, previous) => {
+// The live request, not the held one, which stays set while the dialog animates closed.
+watch(libraryReviewRequest, (value, previous) => {
if (!value) {
+ // A preview still loading must not move the canvas away from where it is restored to. Its
+ // loading message stays while the dialog animates closed; the next review loads afresh.
+ requestId++
if (previous) void restoreOrigin()
return
}
diff --git a/src/components/libraries/useLibraryManager.ts b/src/components/libraries/useLibraryManager.ts
index 98edb000c..2a810ff62 100644
--- a/src/components/libraries/useLibraryManager.ts
+++ b/src/components/libraries/useLibraryManager.ts
@@ -28,7 +28,22 @@ export function useLibraryManager(
const showAllPages = ref(false)
const applying = ref<string | null>(null)
const updateGroups = ref<LibraryAssetUpdateGroup[]>([])
+ /**
+ * Whether this opening's first read has finished. The dialog shows once it has, so it never
+ * opens on the previous opening's updates, or on none, and then fills in.
+ */
+ const ready = ref(false)
let requestId = 0
+ watch(
+ open,
+ (isOpen) => {
+ if (!isOpen) return
+ ready.value = false
+ // A read still running from before this opening must not mark it ready.
+ requestId++
+ },
+ { flush: 'sync' }
+ )
const visibleUpdateGroups = computed(() =>
scopeLibraryUpdateGroups(editor, updateGroups.value, showAllPages.value)
)
@@ -36,16 +51,23 @@ export function useLibraryManager(
async function refresh() {
const request = ++requestId
loading.value = true
+ let read = false
try {
await service.refresh(editor)
const groups = await service.getUpdateGroups(editor)
if (request === requestId) updateGroups.value = groups
+ read = true
} catch (cause) {
if (request === requestId) {
toast.error(notificationMessages.get().operationFailed({ error: errorDetail(cause) }))
}
} finally {
- if (request === requestId) loading.value = false
+ if (request === requestId) {
+ loading.value = false
+ // A first read that failed has nothing current to show, so the dialog does not open.
+ if (read || ready.value) ready.value = true
+ else open.value = false
+ }
}
}
@@ -142,6 +164,7 @@ export function useLibraryManager(
return {
section,
loading,
+ ready,
showAllPages,
applying,
visibleUpdateGroups,
diff --git a/src/components/properties/IconSection.vue b/src/components/properties/IconSection.vue
index ca34af699..5e98ba07d 100644
--- a/src/components/properties/IconSection.vue
+++ b/src/components/properties/IconSection.vue
@@ -11,6 +11,7 @@ import IconPicker from '@/components/icon-picker/IconPicker.vue'
import IconPreview from '@/components/icon-picker/IconPreview.vue'
import IconButton from '@/components/ui/button/IconButton.vue'
import { AppConfirmationDialog } from '@/components/ui/dialog'
+import { useHeldContent } from '@/components/ui/overlay/held'
import PanelFieldGroup from '@/components/ui/panel/PanelFieldGroup.vue'
import PanelSection from '@/components/ui/panel/PanelSection.vue'
import theme from '@/theme/select/app'
@@ -34,6 +35,7 @@ const styles = tv(theme)()
/** An icon picked to replace an edited one, waiting for the edits to be given up. */
const pendingSwap = ref<string | null>(null)
+const swapShown = useHeldContent(pendingSwap)
// The question is about the icon selected when it was asked; another selection drops it, so a
// confirmation never swaps an icon it did not describe.
watch(frameId, () => {
@@ -102,7 +104,7 @@ function confirmSwap() {
<AppConfirmationDialog
:open="pendingSwap !== null"
:heading="panels.swapEditedIconHeading"
- :description="panels.swapEditedIconDescription({ name: iconLayerName(pendingSwap ?? '') })"
+ :description="panels.swapEditedIconDescription({ name: iconLayerName(swapShown ?? '') })"
:cancel-label="common.cancel"
:confirm-label="panels.swapIcon"
tone="warning"
diff --git a/src/components/recovery/RecoveryDialog.vue b/src/components/recovery/RecoveryDialog.vue
index 6e72d77e1..dbac9a6ec 100644
--- a/src/components/recovery/RecoveryDialog.vue
+++ b/src/components/recovery/RecoveryDialog.vue
@@ -25,12 +25,18 @@ const dates = useDateFormat()
const updatedLabel = (snapshot: RecoverySnapshotMeta) =>
dates.format(snapshot.updatedAt, 'dateTime')
+/** Drops a handled snapshot; the last one stays listed while the dialog animates closed. */
+function settle(snapshot: RecoverySnapshotMeta): void {
+ const remaining = snapshots.value.filter((candidate) => candidate.id !== snapshot.id)
+ if (remaining.length === 0) open.value = false
+ else snapshots.value = remaining
+}
+
async function restore(snapshot: RecoverySnapshotMeta): Promise<void> {
busyId.value = snapshot.id
try {
await restoreRecoverySnapshot(snapshot.id)
- snapshots.value = snapshots.value.filter((candidate) => candidate.id !== snapshot.id)
- if (snapshots.value.length === 0) open.value = false
+ settle(snapshot)
} catch (error) {
toast.error(
notifications.value.operationFailed({
@@ -46,8 +52,7 @@ async function discard(snapshot: RecoverySnapshotMeta): Promise<void> {
busyId.value = snapshot.id
try {
await discardRecoverySnapshot(snapshot.id)
- snapshots.value = snapshots.value.filter((candidate) => candidate.id !== snapshot.id)
- if (snapshots.value.length === 0) open.value = false
+ settle(snapshot)
} finally {
busyId.value = null
}
diff --git a/src/components/save-to/SaveToHost.vue b/src/components/save-to/SaveToHost.vue
index 095144ee2..b85cedf9e 100644
--- a/src/components/save-to/SaveToHost.vue
+++ b/src/components/save-to/SaveToHost.vue
@@ -1,9 +1,17 @@
<script setup lang="ts">
import { closeSaveTo, confirmSaveTo, saveToSession } from '@/app/storage/save-to/session'
+import { useHeldContent } from '@/components/ui/overlay/held'
import SaveToDialog from './SaveToDialog.vue'
-/** The Save to dialog, driven by the app's save flow for whichever tab opened it. */
+/**
+ * The Save to dialog, driven by the app's save flow for whichever tab opened it. A finished save
+ * resets the state as it closes; the dialog keeps its progress while it fades.
+ */
+const state = useHeldContent(
+ () => saveToSession.value?.state,
+ () => saveToSession.value?.open ?? false
+)
</script>
<template>
@@ -13,7 +21,7 @@ import SaveToDialog from './SaveToDialog.vue'
v-model:destination="saveToSession.chosen"
:open="saveToSession.open"
:destinations="saveToSession.destinations"
- :state="saveToSession.state"
+ :state="state ?? saveToSession.state"
@update:open="(open) => !open && closeSaveTo()"
@save="confirmSaveTo"
@cancel="closeSaveTo"
diff --git a/src/components/settings/SettingsDialog.vue b/src/components/settings/SettingsDialog.vue
index 310562acd..e9231a615 100644
--- a/src/components/settings/SettingsDialog.vue
+++ b/src/components/settings/SettingsDialog.vue
@@ -71,9 +71,12 @@ function onSectionChange(section: string | number): void {
function onOpenChange(open: boolean): void {
if (open) settingsDialogOpen.value = true
else
- navigation.request(() => {
- settingsDialogOpen.value = false
- })
+ navigation.request(
+ () => {
+ settingsDialogOpen.value = false
+ },
+ { closesWindow: true }
+ )
}
</script>
diff --git a/src/components/settings/cloud/CloudSettingsSection.vue b/src/components/settings/cloud/CloudSettingsSection.vue
index 76edc17be..e27096354 100644
--- a/src/components/settings/cloud/CloudSettingsSection.vue
+++ b/src/components/settings/cloud/CloudSettingsSection.vue
@@ -19,6 +19,7 @@ import { signOutOfCloud } from '@/app/cloud/sessions/sign-out'
import { clearCloudSessionToken } from '@/app/cloud/sessions/token'
import { openExternalLink, toast } from '@/app/shell/ui'
import AppConfirmationDialog from '@/components/ui/dialog/AppConfirmationDialog.vue'
+import { useHeldContent } from '@/components/ui/overlay/held'
import CloudSettingsPanel from './CloudSettingsPanel.vue'
import CloudWaitlist from './CloudWaitlist.vue'
@@ -53,6 +54,7 @@ const entries = computed<CloudServerEntry[]>(() =>
/** The server being removed, and how many documents would lose changes the server hasn't got. */
const removing = ref<{ entry: CloudServerEntry; unsaved: number } | null>(null)
+const removingShown = useHeldContent(removing)
async function askToRemove(id: string) {
const entry = entries.value.find((candidate) => candidate.id === id)
@@ -106,14 +108,16 @@ async function remove() {
<AppConfirmationDialog
:open="removing !== null"
tone="danger"
- :heading="t.settingsDisconnectHeading({ host: removing?.entry.host ?? '' })"
+ :heading="t.settingsDisconnectHeading({ host: removingShown?.entry.host ?? '' })"
:description="
- removing?.unsaved
- ? t.settingsDisconnectUnsavedDescription(removing.unsaved)
+ removingShown?.unsaved
+ ? t.settingsDisconnectUnsavedDescription(removingShown.unsaved)
: t.settingsDisconnectDescription
"
:cancel-label="common.cancel"
- :confirm-label="removing?.unsaved ? t.settingsDisconnectAndDiscard : t.settingsDisconnect"
+ :confirm-label="
+ removingShown?.unsaved ? t.settingsDisconnectAndDiscard : t.settingsDisconnect
+ "
@update:open="(open) => !open && (removing = null)"
@confirm="remove"
/>
diff --git a/src/components/statuses/StatusesDialog.vue b/src/components/statuses/StatusesDialog.vue
index fd3c18de4..8eb59b0e8 100644
--- a/src/components/statuses/StatusesDialog.vue
+++ b/src/components/statuses/StatusesDialog.vue
@@ -45,9 +45,14 @@ const open = computed({
}
})
+/** Discarded edits are dropped as the dialog next opens, so its closing animation keeps them. */
+let discarded = false
+
// A draft opens on the document's statuses as they are now, unless it holds edits not applied.
watch(open, (value) => {
- if (value && !dirty.value) editor.reset()
+ if (!value || (dirty.value && !discarded)) return
+ discarded = false
+ editor.reset()
})
/** The preset menu's value while the statuses match no preset. */
@@ -117,7 +122,7 @@ function choosePreset(value: string) {
}
function discard() {
- editor.reset()
+ discarded = true
store.state.statusesOpen = false
}
</script>
diff --git a/src/components/ui/dialog/Dialog.stories.ts b/src/components/ui/dialog/Dialog.stories.ts
index ae5f73068..3713c3304 100644
--- a/src/components/ui/dialog/Dialog.stories.ts
+++ b/src/components/ui/dialog/Dialog.stories.ts
@@ -3,6 +3,7 @@ import { expect, userEvent, within } from 'storybook/test'
import { ref } from 'vue'
import AppButton from '@/components/ui/button/AppButton.vue'
+import { useHeldContent } from '@/components/ui/overlay/held'
import AppConfirmationDialog from './AppConfirmationDialog.vue'
import AppDialog from './AppDialog.vue'
@@ -87,3 +88,33 @@ export const SemanticWrapper: Story = {
`
})
}
+
+/**
+ * A confirmation whose `open` follows a target that closing clears, as a list's remove action
+ * does. The dialog keeps naming the target while it animates closed.
+ */
+export const TargetedConfirmation: Story = {
+ render: () => ({
+ components: { AppButton, AppConfirmationDialog },
+ setup() {
+ const removing = ref<{ name: string; unsaved: boolean } | null>(null)
+ const shown = useHeldContent(removing)
+ return { removing, shown }
+ },
+ template: `
+ <div class="flex gap-2">
+ <AppButton @click="removing = { name: 'Alpha', unsaved: true }">Remove Alpha</AppButton>
+ <AppButton @click="removing = { name: 'Beta', unsaved: false }">Remove Beta</AppButton>
+ </div>
+ <AppConfirmationDialog
+ :open="removing !== null"
+ tone="danger"
+ :heading="'Remove ' + (shown?.name ?? '')"
+ :description="shown?.unsaved ? 'Unsaved changes will be lost.' : 'This cannot be undone.'"
+ cancel-label="Cancel"
+ :confirm-label="shown?.unsaved ? 'Discard and remove' : 'Remove'"
+ @update:open="(open) => !open && (removing = null)"
+ />
+ `
+ })
+}
diff --git a/src/components/ui/overlay/held.ts b/src/components/ui/overlay/held.ts
new file mode 100644
index 000000000..a15b8fd84
--- /dev/null
+++ b/src/components/ui/overlay/held.ts
@@ -0,0 +1,31 @@
+import { computed, shallowRef, toValue, watch, type ComputedRef, type MaybeRefOrGetter } from 'vue'
+
+/**
+ * What an overlay shows: the source while the overlay is open, and the value it had when it
+ * closed while the overlay animates out.
+ *
+ * An overlay closes by clearing the state it draws, and its exit animation would otherwise draw
+ * the cleared content: an empty name, the other variant's labels, a vanished error. Once closed
+ * the overlay unmounts, so the held value is never seen. `open` defaults to the source being
+ * present, for an overlay whose `open` is that test.
+ *
+ * The value is taken once per tick, before rendering: a flow that clears its state and then
+ * closes in the same tick keeps what the overlay showed before either change.
+ */
+export function useHeldContent<T>(
+ source: MaybeRefOrGetter<T>,
+ open: MaybeRefOrGetter<boolean> = () => {
+ const value = toValue(source)
+ return value !== null && value !== undefined
+ }
+): ComputedRef<T> {
+ const held = shallowRef(toValue(source))
+ watch(
+ [() => toValue(source), () => toValue(open)],
+ ([value, isOpen]) => {
+ if (isOpen) held.value = value
+ },
+ { immediate: true }
+ )
+ return computed(() => (toValue(open) ? toValue(source) : held.value))
+}
diff --git a/src/components/variables/TokenImportDialog.vue b/src/components/variables/TokenImportDialog.vue
index ad57efe6d..9ac6891d7 100644
--- a/src/components/variables/TokenImportDialog.vue
+++ b/src/components/variables/TokenImportDialog.vue
@@ -22,6 +22,7 @@ import AppButton from '@/components/ui/button/AppButton.vue'
import AppCollapsible from '@/components/ui/collapsible/AppCollapsible.vue'
import { AppDialog } from '@/components/ui/dialog'
import AppAlert from '@/components/ui/feedback/AppAlert.vue'
+import { useHeldContent } from '@/components/ui/overlay/held'
import AppSelect from '@/components/ui/select/AppSelect.vue'
import AppCheckbox from '@/components/ui/toggle/AppCheckbox.vue'
@@ -56,11 +57,12 @@ function isStale(choices: TokenImportOptions): boolean {
}
// The plan reads the document, so it follows every change to it, and choices that went stale
-// start over from the defaults.
+// start over from the defaults. The import itself changes the document as the dialog closes,
+// so a closed dialog keeps its choices and the plan it showed.
watch(
() => store.state.sceneVersion,
() => {
- if (bundle && options.value && isStale(options.value))
+ if (open.value && bundle && options.value && isStale(options.value))
options.value = defaultTokenImportOptions(store.graph, bundle)
}
)
@@ -69,16 +71,18 @@ function currentPlan() {
return bundle && options.value ? planTokenImport(store.graph, bundle, options.value) : null
}
-const plan = computed(() => {
+const livePlan = computed(() => {
void store.state.sceneVersion
return currentPlan()
})
-const existingCollections = computed(() => {
+const plan = useHeldContent(livePlan, open)
+const liveCollections = computed(() => {
void store.state.sceneVersion
return [...store.graph.variableCollections.values()].filter(
(collection) => !isLibraryCollection(collection)
)
})
+const existingCollections = useHeldContent(liveCollections, open)
const styleCount = computed(
() =>
bundle?.composites.filter((token) => token.type === 'typography' || token.type === 'shadow')
diff --git a/tests/app/ai/models/settings/status.test.ts b/tests/app/ai/models/settings/status.test.ts
index 8860f3de7..e402325f3 100644
--- a/tests/app/ai/models/settings/status.test.ts
+++ b/tests/app/ai/models/settings/status.test.ts
@@ -21,6 +21,7 @@ describe('model connection state', () => {
expect(state({ credential: 'configured' })).toBe('connected')
expect(state({ credential: 'missing' })).toBe('needs-credential')
expect(state({ credential: 'locked' })).toBe('unavailable')
+ expect(state({ credential: undefined })).toBe('checking')
expect(state({ providerID: 'chatgpt', credential: 'configured' })).toBe('connected')
})
diff --git a/tests/e2e/storybook/overlay-states.spec.ts b/tests/e2e/storybook/overlay-states.spec.ts
new file mode 100644
index 000000000..c7a664ca2
--- /dev/null
+++ b/tests/e2e/storybook/overlay-states.spec.ts
@@ -0,0 +1,27 @@
+import { expect, test, type Page } from '@playwright/test'
+
+import { overlayContents, recordOverlayFrames } from '#tests/helpers/overlay/states'
+
+// Overlays flicker only while they animate, which reduced motion turns off.
+test.use({ contextOptions: { reducedMotion: 'no-preference' } })
+
+async function openStory(page: Page, id: string) {
+ await page.goto(`/iframe.html?id=${id}&viewMode=story`)
+ await expect(page.locator('#storybook-root')).not.toBeEmpty()
+}
+
+test('a targeted confirmation keeps its content while it animates closed', async ({ page }) => {
+ await openStory(page, 'design-system-overlays-dialog--targeted-confirmation')
+ const opening = await recordOverlayFrames(page, () =>
+ page.getByRole('button', { name: 'Remove Alpha' }).click()
+ )
+ expect(overlayContents(opening)).toHaveLength(1)
+
+ const dialog = page.getByRole('alertdialog')
+ const shown = await dialog.innerText()
+ const closing = await recordOverlayFrames(page, () =>
+ dialog.getByRole('button', { name: 'Cancel' }).click()
+ )
+ expect(new Set(overlayContents(closing))).toEqual(new Set([shown.replace(/\s+/g, ' ').trim()]))
+ expect(closing.at(-1)).toBeNull()
+})
diff --git a/tests/engine/app/settings/navigation.test.ts b/tests/engine/app/settings/navigation.test.ts
index 595a6372f..d4c963bab 100644
--- a/tests/engine/app/settings/navigation.test.ts
+++ b/tests/engine/app/settings/navigation.test.ts
@@ -73,3 +73,33 @@ test('busy and replaced editors cannot be discarded by stale requests', () => {
expect(navigated).toBe(false)
expect(navigation.editing.value).toBe(true)
})
+
+test('closing the window leaves an editor without cancelling it back to its list', () => {
+ const navigation = createSettingsNavigation()
+ const dirty = ref(false)
+ let cancelled = 0
+ let closed = 0
+ const form = {
+ dirty,
+ busy: ref(false),
+ cancel: () => {
+ cancelled++
+ }
+ }
+ const close = () => {
+ closed++
+ }
+ const unregister = navigation.register(form)
+ navigation.request(close, { closesWindow: true })
+ expect([cancelled, closed]).toEqual([0, 1])
+ // The window keeps showing the editor until it unmounts with the closed window.
+ expect(navigation.editing.value).toBe(true)
+ unregister()
+ expect(navigation.editing.value).toBe(false)
+
+ dirty.value = true
+ navigation.register(form)
+ navigation.request(close, { closesWindow: true })
+ navigation.discard()
+ expect([cancelled, closed]).toEqual([0, 2])
+})
diff --git a/tests/helpers/overlay/states.ts b/tests/helpers/overlay/states.ts
new file mode 100644
index 000000000..95e92608b
--- /dev/null
+++ b/tests/helpers/overlay/states.ts
@@ -0,0 +1,79 @@
+import type { Page } from '@playwright/test'
+
+/** Dialogs, alert dialogs, and popovers as Reka renders their content. */
+export const OVERLAY_SELECTOR =
+ '[role="dialog"], [role="alertdialog"], [data-slot="popover-content"]'
+
+/** What the overlay showed on one animation frame: its text, or null when none was in the page. */
+export type OverlayFrame = string | null
+
+/**
+ * Records the overlay's text on every animation frame while `action` runs and until the page
+ * settles, keeping only frames that differ from the one before. An overlay that animates open
+ * or closed without flicker records its content once; one that redraws mid-animation records
+ * each version it drew.
+ */
+export async function recordOverlayFrames(
+ page: Page,
+ action: () => Promise<void>,
+ { selector = OVERLAY_SELECTOR, settleFrames = 30 } = {}
+): Promise<OverlayFrame[]> {
+ const recorder = await page.evaluateHandle(
+ ({ selector, settleFrames }) => {
+ const frames: (string | null)[] = []
+ let unchanged = 0
+ // Settling counts only after the action ran, however long it takes.
+ let counting = false
+ let done = false
+ let resolveSettled: () => void = () => undefined
+ const settled = new Promise<void>((resolve) => {
+ resolveSettled = resolve
+ })
+ const read = (): string | null => {
+ const overlays = [...document.querySelectorAll<HTMLElement>(selector)]
+ if (overlays.length === 0) return null
+ return overlays.map((overlay) => overlay.innerText.replace(/\s+/g, ' ').trim()).join(' | ')
+ }
+ const tick = () => {
+ if (done) return
+ const frame = read()
+ if (frames.length === 0 || frames[frames.length - 1] !== frame) {
+ frames.push(frame)
+ unchanged = 0
+ } else if (counting && ++unchanged >= settleFrames) {
+ resolveSettled()
+ }
+ requestAnimationFrame(tick)
+ }
+ tick()
+ return {
+ frames,
+ settled,
+ armed: () => {
+ unchanged = 0
+ counting = true
+ },
+ stop: () => {
+ done = true
+ return frames
+ }
+ }
+ },
+ { selector, settleFrames }
+ )
+ try {
+ await action()
+ await recorder.evaluate((state) => state.armed())
+ await recorder.evaluate((state) => state.settled)
+ return await recorder.evaluate((state) => state.stop())
+ } finally {
+ // Stops the frame loop even when a step threw, so it does not run for the rest of the test.
+ await recorder.evaluate((state) => state.stop()).catch(() => undefined)
+ await recorder.dispose()
+ }
+}
+
+/** The distinct contents an overlay showed, leaving out the frames with no overlay. */
+export function overlayContents(frames: OverlayFrame[]): string[] {
+ return frames.filter((frame): frame is string => frame !== null)
+}
diff --git a/tools/checks/lint/src/plugin.ts b/tools/checks/lint/src/plugin.ts
index 29e4292e5..cd1bb6db5 100644
--- a/tools/checks/lint/src/plugin.ts
+++ b/tools/checks/lint/src/plugin.ts
@@ -17,6 +17,7 @@ import { noUnknownTailwindClassesRule } from '#lint/rules/quality/tailwind-class
import { valibotSchemaConventionsRule } from '#lint/rules/quality/valibot-schemas.ts'
import { noWidenThenAssertRule } from '#lint/rules/quality/widen-then-assert.ts'
import { noRawSQLRule } from '#lint/rules/sql.ts'
+import { noOverlayContentFromOpenState } from '#lint/rules/vue/overlays.ts'
import { normalizedFilename } from '#lint/support/context.ts'
import type { PluginRule, RuleDefinition } from '#lint/support/types.ts'
import type { TSESTree } from '@typescript-eslint/utils'
@@ -436,6 +437,7 @@ const plugin = {
'no-structuredclone-scene-arrays': noStructuredCloneSceneArrays,
'no-vue-style-blocks': noVueStyleBlocks,
'no-native-title-attributes-in-vue': noNativeTitleAttributesInVue,
+ 'no-overlay-content-from-open-state': noOverlayContentFromOpenState,
'no-hardcoded-tip-labels-in-vue': noHardcodedTipLabelsInVue,
'no-raw-svg-in-app-vue-templates': noRawSvgInAppVueTemplates,
'no-ui-helper-calls-in-vue-templates': noUiHelperCallsInVueTemplates,
diff --git a/tools/checks/lint/src/rules/vue/overlays.ts b/tools/checks/lint/src/rules/vue/overlays.ts
new file mode 100644
index 000000000..3c466e466
--- /dev/null
+++ b/tools/checks/lint/src/rules/vue/overlays.ts
@@ -0,0 +1,208 @@
+import { normalizedFilename } from '#lint/support/context.ts'
+import type { RuleDefinition } from '#lint/support/types.ts'
+import {
+ VUE_DIRECTIVE_NODE,
+ VUE_ELEMENT_NODE,
+ VUE_INTERPOLATION_NODE,
+ VUE_SIMPLE_EXPRESSION_NODE,
+ isVueBindDirective,
+ isVueSourceFile,
+ vueTemplateAst,
+ walkVueTemplateAst,
+ type VueTemplateNode
+} from '#lint/support/vue.ts'
+
+interface ExpressionNode {
+ type?: string
+ name?: string
+ computed?: boolean
+ object?: ExpressionNode
+ property?: ExpressionNode
+ [key: string]: unknown
+}
+
+/** The names an expression reads, leaving out property names after a dot. */
+function readNames(
+ node: ExpressionNode | null | undefined,
+ names = new Set<string>()
+): Set<string> {
+ if (!node || typeof node !== 'object') return names
+ if (node.type === 'Identifier' && node.name) {
+ names.add(node.name)
+ return names
+ }
+ if (node.type === 'MemberExpression' || node.type === 'OptionalMemberExpression') {
+ readNames(node.object, names)
+ if (node.computed) readNames(node.property, names)
+ return names
+ }
+ for (const [key, value] of Object.entries(node)) {
+ if (key === 'loc' || key === 'start' || key === 'end' || !value) continue
+ if (Array.isArray(value)) {
+ for (const item of value) readNames(item as ExpressionNode, names)
+ } else if (typeof value === 'object') {
+ readNames(value as ExpressionNode, names)
+ }
+ }
+ return names
+}
+
+function isAbsent(node: ExpressionNode | undefined): boolean {
+ if (!node) return false
+ if (node.type === 'NullLiteral' || (node.type === 'Literal' && node.value === null)) return true
+ return node.type === 'Identifier' && node.name === 'undefined'
+}
+
+/**
+ * The state an `open` expression tests for presence: `x`, `!!x`, `Boolean(x)`, `x !== null`,
+ * `x != undefined`, and their `&&` combinations. Such an overlay closes by clearing that state.
+ */
+/** The operands a presence test reads, by expression type. */
+const PRESENCE_OPERANDS: Record<string, (node: ExpressionNode) => (ExpressionNode | undefined)[]> =
+ {
+ // `!!x`
+ UnaryExpression: (node) => {
+ const inner = node.argument as ExpressionNode | undefined
+ const doubled =
+ node.operator === '!' && inner?.type === 'UnaryExpression' && inner.operator === '!'
+ return doubled ? [inner.argument as ExpressionNode] : []
+ },
+ // `x !== null`, `undefined != x`
+ BinaryExpression: (node) => {
+ if (node.operator !== '!==' && node.operator !== '!=') return []
+ const left = node.left as ExpressionNode | undefined
+ const right = node.right as ExpressionNode | undefined
+ if (isAbsent(right)) return [left]
+ return isAbsent(left) ? [right] : []
+ },
+ // `a && b`
+ LogicalExpression: (node) =>
+ node.operator === '&&' ? [node.left as ExpressionNode, node.right as ExpressionNode] : [],
+ // `Boolean(x)`
+ CallExpression: (node) => {
+ const callee = node.callee as ExpressionNode | undefined
+ const [argument] = (node.arguments as ExpressionNode[] | undefined) ?? []
+ return callee?.type === 'Identifier' && callee.name === 'Boolean' ? [argument] : []
+ }
+ }
+
+function presenceNames(node: ExpressionNode | undefined, names = new Set<string>()): Set<string> {
+ if (!node?.type) return names
+ if (node.type === 'Identifier') {
+ if (node.name && node.name !== 'undefined') names.add(node.name)
+ return names
+ }
+ for (const operand of PRESENCE_OPERANDS[node.type]?.(node) ?? []) presenceNames(operand, names)
+ return names
+}
+
+function openStateNames(expression: VueTemplateNode | null | undefined): Set<string> {
+ if (expression?.type !== VUE_SIMPLE_EXPRESSION_NODE) return new Set()
+ if (expression.ast) return presenceNames(expression.ast as ExpressionNode)
+ return expressionNames(expression)
+}
+
+function expressionNames(expression: VueTemplateNode | null | undefined): Set<string> {
+ if (expression?.type !== VUE_SIMPLE_EXPRESSION_NODE) return new Set()
+ if (expression.ast) return readNames(expression.ast as ExpressionNode)
+ // A bare identifier has no AST.
+ return /^[A-Za-z_$][\w$]*$/.test(expression.content) ? new Set([expression.content]) : new Set()
+}
+
+function isDirective(node: VueTemplateNode, name: string): boolean {
+ return node.type === VUE_DIRECTIVE_NODE && node.name === name
+}
+
+/** Bindings that decide whether the overlay is open, or run on events rather than when drawn. */
+function drawsContent(prop: VueTemplateNode): boolean {
+ if (isVueBindDirective(prop, 'open')) return false
+ if (isDirective(prop, 'on')) return false
+ if (isDirective(prop, 'model')) return false
+ return true
+}
+
+/** The names the overlay's drawn content reads: its own bindings and everything inside it. */
+function contentNames(element: VueTemplateNode): Set<string> {
+ const names = new Set<string>()
+ if (!('props' in element) || !('children' in element)) return names
+ const visit = (node: VueTemplateNode) => {
+ if (node.type === VUE_DIRECTIVE_NODE && isDirective(node, 'on')) return
+ walkVueTemplateAst(node, (inner) => {
+ if (inner.type === VUE_DIRECTIVE_NODE && !isDirective(inner, 'on')) {
+ for (const name of expressionNames(inner.exp)) names.add(name)
+ }
+ if (inner.type === VUE_INTERPOLATION_NODE) {
+ for (const name of expressionNames(inner.content)) names.add(name)
+ }
+ })
+ }
+ for (const prop of element.props) if (drawsContent(prop)) visit(prop)
+ for (const child of element.children) {
+ if (typeof child !== 'string' && typeof child !== 'symbol') visit(child)
+ }
+ return names
+}
+
+const HELD_CONTENT = '`useHeldContent` from `@/components/ui/overlay/held`'
+
+/**
+ * Overlays that close at once rather than animating out (`motionStyles.floating` in
+ * `src/theme/motion/styles.ts`), so nothing is drawn after their state clears.
+ */
+const INSTANT_CLOSE_ROOTS = new Set([
+ 'PopoverRoot',
+ 'TooltipRoot',
+ 'HoverCardRoot',
+ 'DropdownMenuRoot',
+ 'ContextMenuRoot',
+ 'MenubarRoot',
+ 'SelectRoot',
+ 'ComboboxRoot',
+ 'AppPicker',
+ 'AppSelect',
+ 'AppCombobox'
+])
+
+const noOverlayContentFromOpenState = {
+ meta: {
+ docs: {
+ description:
+ 'Disallow overlays that draw the state deciding their `open` — closing would redraw cleared content'
+ }
+ },
+ create(context) {
+ const file = normalizedFilename(context)
+ if (!isVueSourceFile(file)) return {}
+
+ return {
+ Program(node) {
+ const template = vueTemplateAst(context.sourceCode.getText(), file)
+ if (!template) return
+ walkVueTemplateAst(template, (element) => {
+ if (element.type !== VUE_ELEMENT_NODE || INSTANT_CLOSE_ROOTS.has(element.tag)) return
+ const open = element.props.find((prop) => isVueBindDirective(prop, 'open'))
+ if (!open || open.type !== VUE_DIRECTIVE_NODE) return
+ if (open.exp?.type === VUE_SIMPLE_EXPRESSION_NODE && open.exp.content.trim() === 'true') {
+ if (element.props.some((prop) => isDirective(prop, 'if'))) {
+ context.report({
+ node,
+ message: `<${element.tag}> opens through v-if, so clearing it removes the overlay without its closing animation. Bind :open to the state and draw the content from ${HELD_CONTENT}.`
+ })
+ }
+ return
+ }
+ const deciding = openStateNames(open.exp)
+ const drawn = contentNames(element)
+ const shared = [...deciding].filter((name) => drawn.has(name))
+ if (shared.length === 0) return
+ context.report({
+ node,
+ message: `<${element.tag}> draws ${shared.map((name) => `\`${name}\``).join(', ')}, which also decides :open; clearing it to close redraws the overlay while it animates out. Draw the content from ${HELD_CONTENT}.`
+ })
+ })
+ }
+ }
+ }
+} satisfies RuleDefinition
+
+export { noOverlayContentFromOpenState }
diff --git a/tools/checks/lint/src/support/vue.ts b/tools/checks/lint/src/support/vue.ts
index 55d6a7be4..e821da31a 100644
--- a/tools/checks/lint/src/support/vue.ts
+++ b/tools/checks/lint/src/support/vue.ts
@@ -158,6 +158,8 @@ function isBoundStringLiteral(node: VueTemplateNode, name: string): boolean {
export {
VUE_DIRECTIVE_NODE,
VUE_ELEMENT_NODE,
+ VUE_INTERPOLATION_NODE,
+ VUE_SIMPLE_EXPRESSION_NODE,
hasExpressionCall,
hasUIHelperCall,
isBoundStringLiteral,
diff --git a/tools/checks/lint/tests/overlay-content.test.ts b/tools/checks/lint/tests/overlay-content.test.ts
new file mode 100644
index 000000000..bf13f3b7e
--- /dev/null
+++ b/tools/checks/lint/tests/overlay-content.test.ts
@@ -0,0 +1,42 @@
+import { expect, test } from 'bun:test'
+
+import { lintFiles, ruleDiagnostics } from './helpers/lint.ts'
+
+const RULE = 'no-overlay-content-from-open-state'
+const SCRIPT = '<script setup lang="ts">\nconst removing = null\nconst shown = null\n</script>\n'
+
+async function flagged(files: Record<string, string>): Promise<string[]> {
+ const diagnostics = await lintFiles(files, { [`open-pencil/${RULE}`]: 'error' })
+ return ruleDiagnostics(diagnostics, RULE)
+ .map((item) => item.filename?.split('/').pop() ?? '')
+ .sort()
+}
+
+test('flags an overlay that draws the state its open tests for presence', async () => {
+ expect(
+ await flagged({
+ 'src/components/Cleared.vue': `${SCRIPT}<template><AppConfirmationDialog :open="removing !== null" :heading="removing?.name" @update:open="removing = null" /></template>\n`,
+ 'src/components/Slot.vue': `${SCRIPT}<template><AppDialogRoot :open="!!removing"><p>{{ removing.name }}</p></AppDialogRoot></template>\n`,
+ 'src/components/Held.vue': `${SCRIPT}<template><AppConfirmationDialog :open="removing !== null" :heading="shown?.name" @confirm="remove(removing)" @update:open="removing = null" /></template>\n`
+ })
+ ).toEqual(['Cleared.vue', 'Slot.vue'])
+})
+
+test('leaves overlays whose open is not a presence test', async () => {
+ expect(
+ await flagged({
+ 'src/components/List.vue': `${SCRIPT}<template><Disclosure v-for="group in groups" :open="expanded.includes(group.id)">{{ group.name }}</Disclosure></template>\n`,
+ 'src/components/Context.vue': `${SCRIPT}<template><ComboboxRoot :open="ctx.open">{{ ctx.label }}</ComboboxRoot></template>\n`,
+ // Popovers close at once, so nothing draws after their state clears.
+ 'src/components/Popover.vue': `${SCRIPT}<template><PopoverRoot :open="!!removing">{{ removing.name }}</PopoverRoot></template>\n`
+ })
+ ).toEqual([])
+})
+
+test('flags an overlay opened by v-if instead of :open', async () => {
+ expect(
+ await flagged({
+ 'src/components/Mounted.vue': `${SCRIPT}<template><RecoveryCodes v-if="removing" :open="true" :codes="shown" /></template>\n`
+ })
+ ).toEqual(['Mounted.vue'])
+})