fix(dialog): keep stacked dialogs dismissible

This commit is contained in:
二丫讲梵 authored and GitHub committed 2026-10-02 09:21:47 +08:00
1 parent 80bd37ebaa
commit b1d068cd97
18 files changed
+286 -68

No files matched your search

@@ -1,7 +1,7 @@
<script setup lang="ts">
import type { DialogContentEmits, DialogContentProps } from "reka-ui";
import { ref, type HTMLAttributes } from "vue";
import { type HTMLAttributes } from "vue";
import { reactiveOmit } from "@vueuse/core";
import { XIcon } from "@lucide/vue";
import { DialogClose, DialogContent, DialogDescription, DialogPortal, VisuallyHidden, useForwardPropsEmits } from "reka-ui";
@@ -33,14 +33,13 @@ const delegatedProps = reactiveOmit(props, "class", "overlayClass", "portalClass
const forwarded = useForwardPropsEmits(delegatedProps, emits);
const positioner = ref<HTMLElement | null>(null);
useDialogLayerOrder(positioner);
const { layerStyle } = useDialogLayerOrder();
</script>
<template>
<DialogPortal>
<DialogOverlay :class="props.overlayClass" />
<div ref="positioner" data-slot="dialog-positioner" :class="cn('fixed inset-0 z-50 grid place-items-center p-4 pointer-events-none', props.portalClass)">
<DialogOverlay :class="props.overlayClass" :style="layerStyle" />
<div data-slot="dialog-positioner" :style="layerStyle" :class="cn('fixed inset-0 z-50 grid place-items-center p-4 pointer-events-none', props.portalClass)">
<DialogContent
data-slot="dialog-content"
v-bind="{ ...$attrs, ...forwarded }"
@@ -1,7 +1,7 @@
<script setup lang="ts">
import type { DialogContentEmits, DialogContentProps } from "reka-ui";
import { ref, type HTMLAttributes } from "vue";
import { type HTMLAttributes } from "vue";
import { reactiveOmit } from "@vueuse/core";
import { XIcon } from "@lucide/vue";
import { DialogClose, DialogContent, DialogDescription, DialogPortal, VisuallyHidden, useForwardPropsEmits } from "reka-ui";
@@ -23,14 +23,13 @@ const delegatedProps = reactiveOmit(props, "class", "showOverlay", "showCloseBut
const forwarded = useForwardPropsEmits(delegatedProps, emits);
const positioner = ref<HTMLElement | null>(null);
useDialogLayerOrder(positioner);
const { layerStyle } = useDialogLayerOrder();
</script>
<template>
<DialogPortal>
<DialogOverlay v-if="props.showOverlay" />
<div ref="positioner" data-slot="dialog-positioner" class="fixed inset-0 z-50 grid place-items-center p-4 pointer-events-none">
<DialogOverlay v-if="props.showOverlay" :style="layerStyle" />
<div data-slot="dialog-positioner" :style="layerStyle" class="fixed inset-0 z-50 grid place-items-center p-4 pointer-events-none">
<DialogContent
data-slot="dialog-content"
:class="cn('relative z-50 grid max-h-[calc(var(--dbx-viewport-height)-6rem)] w-full max-w-lg my-8 gap-4 rounded-lg border border-border bg-popover text-popover-foreground p-4 shadow-lg duration-200 md:w-full pointer-events-auto', props.class)"
@@ -1,20 +1,40 @@
// @vitest-environment happy-dom
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { createApp, defineComponent, h, nextTick, reactive, type Component } from "vue";
import { createI18n } from "vue-i18n";
import { afterEach, describe, expect, it } from "vitest";
import { Dialog, DialogContent, DialogScrollContent, DialogTitle } from "@/components/ui/dialog";
import { useFloatingLayerOrder } from "@/components/ui/dialog/useDialogLayerOrder";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
const mountedApps: Array<{ unmount: () => void; host: HTMLElement }> = [];
const mountedStyles: HTMLStyleElement[] = [];
const floatingLayerRule = readFileSync(resolve(process.cwd(), "apps/desktop/src/styles/globals.css"), "utf8").match(/\[data-dbx-floating-layer\]\s*\{[^}]+\}/)?.[0];
if (!floatingLayerRule) {
throw new Error("globals.css is missing the floating layer z-index rule");
}
afterEach(() => {
for (const { unmount, host } of mountedApps.splice(0)) {
unmount();
host.remove();
}
for (const style of mountedStyles.splice(0)) {
style.remove();
}
document.body.innerHTML = "";
});
function installFloatingLayerStyles() {
const style = document.createElement("style");
style.textContent = floatingLayerRule;
document.head.append(style);
mountedStyles.push(style);
}
async function flush() {
for (let turn = 0; turn < 5; turn += 1) {
await nextTick();
@@ -23,15 +43,16 @@ async function flush() {
}
}
type Layer = { index: number; slot: string; label: string; element: Element };
type Layer = { index: number; slot: string; label: string; zIndex: number; element: Element };
/** Dialog layers teleport into `body`, so paint order is their order among the body children. */
/** Dialog layers teleport into `body`; their visual order is controlled by z-index. */
function dialogLayers(): Layer[] {
return Array.from(document.body.children)
.map((element, index) => ({
index,
element,
slot: element.getAttribute("data-slot") || "",
zIndex: Number.parseInt((element as HTMLElement).style.zIndex || "0", 10),
label: (element.textContent || "")
.replace(/\s+/g, " ")
.trim()
@@ -46,8 +67,8 @@ function layer(slot: string, label?: string): Layer {
return match!;
}
function overlayBefore(target: Layer): Layer | undefined {
return dialogLayers().find((candidate) => candidate.slot === "dialog-overlay" && candidate.index === target.index - 1);
function layers(slot: string): Layer[] {
return dialogLayers().filter((candidate) => candidate.slot === slot);
}
function labeledDialog(options: { open: () => boolean; setOpen: (open: boolean) => void; label: string; content: Component }) {
@@ -115,19 +136,21 @@ describe("dialog layer order", () => {
state.confirmOpen = true;
await flush();
// The transfer form and its confirmation paint in open order to begin with.
// The transfer form and its confirmation receive layers in open order to begin with.
const transfer = layer("dialog-positioner", "transfer form");
const confirm = layer("dialog-positioner", "confirm transfer");
expect(confirm.index).toBeGreaterThan(transfer.index);
expect(overlayBefore(confirm)).toBeDefined();
expect(confirm.zIndex).toBeGreaterThan(transfer.zIndex);
expect(
layers("dialog-overlay")
.map(({ zIndex }) => zIndex)
.sort(),
).toEqual([transfer.zIndex, confirm.zIndex].sort());
// A dialog that gets remounted (leaving the tracked-transfer dialog and returning to the form)
// ends up after the dialog it is supposed to sit below; Reka UI then keeps handing pointer
// events to the confirmation dialog while the form's backdrop covers it.
// Reparenting a portal node must not change which dialog is visually on top.
const transferOverlay = transfer.element.previousElementSibling!;
document.body.append(transferOverlay, transfer.element);
await flush();
expect(layer("dialog-positioner", "transfer form").index).toBeGreaterThan(layer("dialog-positioner", "confirm transfer").index);
expect(layer("dialog-positioner", "confirm transfer").zIndex).toBeGreaterThan(layer("dialog-positioner", "transfer form").zIndex);
// Reopening the confirmation must bring its layer back above the form.
state.confirmOpen = false;
@@ -136,9 +159,7 @@ describe("dialog layer order", () => {
await flush();
const reopened = layer("dialog-positioner", "confirm transfer");
expect(reopened.index).toBeGreaterThan(layer("dialog-positioner", "transfer form").index);
expect(document.body.lastElementChild).toBe(reopened.element);
expect(overlayBefore(reopened)).toBeDefined();
expect(reopened.zIndex).toBeGreaterThan(layer("dialog-positioner", "transfer form").zIndex);
});
it("paints a nested dialog above the dialog that opened it", async () => {
@@ -185,6 +206,114 @@ describe("dialog layer order", () => {
state.confirmOpen = true;
await flush();
expect(layer("dialog-positioner", "confirm transfer").index).toBeGreaterThan(layer("dialog-positioner", "transfer form").index);
const transfer = layer("dialog-positioner", "transfer form");
const confirm = layer("dialog-positioner", "confirm transfer");
expect(transfer.zIndex).toBeGreaterThan(50);
expect(confirm.zIndex).toBeGreaterThan(transfer.zIndex);
});
it("resets the layer sequence after all dialogs close", async () => {
const state = mountSiblingDialogs();
state.transferOpen = true;
await flush();
expect(layer("dialog-positioner", "transfer form").zIndex).toBe(51);
state.transferOpen = false;
await flush();
expect(document.documentElement.style.getPropertyValue("--dbx-dialog-top-z-index")).toBe("50");
expect(document.documentElement.style.getPropertyValue("--dbx-floating-layer-z-index")).toBe("51");
state.transferOpen = true;
await flush();
expect(layer("dialog-positioner", "transfer form").zIndex).toBe(51);
});
it("exposes a floating layer above the open dialog", async () => {
installFloatingLayerStyles();
const host = document.createElement("div");
document.body.append(host);
const state = reactive({ dialogOpen: true, selectOpen: false });
const app = createApp(
defineComponent({
setup() {
return () =>
h("div", [
h(
Dialog,
{ open: state.dialogOpen, "onUpdate:open": (open: boolean) => (state.dialogOpen = open) },
{
default: () =>
h(DialogContent, null, {
default: () => [
h(DialogTitle, null, { default: () => "settings" }),
h(
Select,
{ open: state.selectOpen, "onUpdate:open": (open: boolean) => (state.selectOpen = open) },
{
default: () => [h(SelectTrigger, null, { default: () => h(SelectValue, { placeholder: "Choose" }) }), h(SelectContent, null, { default: () => h(SelectItem, { value: "one" }, { default: () => "One" }) })],
},
),
],
}),
},
),
]);
},
}),
);
app.use(createI18n({ legacy: false, locale: "en", messages: { en: {} }, missingWarn: false, fallbackWarn: false }));
app.mount(host);
mountedApps.push({ unmount: () => app.unmount(), host });
await flush();
const dialog = layer("dialog-positioner", "settings");
state.selectOpen = true;
await flush();
const selectContent = document.body.querySelector<HTMLElement>('[data-slot="select-content"]');
const popperWrapper = document.body.querySelector<HTMLElement>("[data-reka-popper-content-wrapper]");
expect(selectContent).not.toBeNull();
expect(popperWrapper?.hasAttribute("data-dbx-floating-layer")).toBe(true);
expect(selectContent?.className).toContain("z-(--dbx-floating-layer-z-index)");
expect(Number(document.documentElement.style.getPropertyValue("--dbx-floating-layer-z-index"))).toBe(dialog.zIndex + 1);
expect(getComputedStyle(popperWrapper!).zIndex).toContain(String(dialog.zIndex + 1));
});
it("preserves an explicit floating layer z-index", async () => {
installFloatingLayerStyles();
const host = document.createElement("div");
document.body.append(host);
const FloatingProbe = defineComponent({
setup() {
const { forwardRef } = useFloatingLayerOrder();
return () => h("div", { ref: forwardRef, "data-reka-popper-content-wrapper": "", style: { zIndex: "80" } }, h("div", { style: { zIndex: "80" } }));
},
});
const app = createApp(
defineComponent({
setup() {
return () =>
h(
Dialog,
{ open: true },
{
default: () =>
h(DialogContent, null, {
default: () => [h(DialogTitle, null, { default: () => "settings" }), h(FloatingProbe)],
}),
},
);
},
}),
);
app.use(createI18n({ legacy: false, locale: "en", messages: { en: {} }, missingWarn: false, fallbackWarn: false }));
app.mount(host);
mountedApps.push({ unmount: () => app.unmount(), host });
await flush();
const popperWrapper = document.body.querySelector<HTMLElement>("[data-reka-popper-content-wrapper]");
expect(popperWrapper?.style.getPropertyValue("--dbx-floating-content-z-index")).toBe("80");
expect(getComputedStyle(popperWrapper!).zIndex).toContain("80");
});
});
@@ -1,39 +1,100 @@
import { injectDialogRootContext } from "reka-ui";
import { watch, type Ref } from "vue";
import { injectDialogRootContext, useForwardExpose } from "reka-ui";
import { computed, onBeforeUnmount, onUpdated, ref, watch, watchPostEffect, type Ref } from "vue";
const BASE_DIALOG_Z_INDEX = 50;
const DIALOG_TOP_Z_INDEX_VAR = "--dbx-dialog-top-z-index";
const FLOATING_LAYER_Z_INDEX_VAR = "--dbx-floating-layer-z-index";
const activeDialogLayers = new Map<symbol, Ref<number>>();
const topDialogZIndex = ref(BASE_DIALOG_Z_INDEX);
function syncLayerVariables() {
if (typeof document === "undefined") return;
const root = document.documentElement;
root.style.setProperty(DIALOG_TOP_Z_INDEX_VAR, String(topDialogZIndex.value));
root.style.setProperty(FLOATING_LAYER_Z_INDEX_VAR, String(topDialogZIndex.value + 1));
}
function refreshTopDialogZIndex() {
let zIndex = BASE_DIALOG_Z_INDEX;
// Compact in insertion order even while a parent dialog remains open.
for (const layer of activeDialogLayers.values()) layer.value = ++zIndex;
topDialogZIndex.value = zIndex;
syncLayerVariables();
}
function registerDialogLayer(id: symbol, zIndex: Ref<number>) {
if (activeDialogLayers.has(id)) return;
activeDialogLayers.set(id, zIndex);
refreshTopDialogZIndex();
}
function unregisterDialogLayer(id: symbol) {
if (!activeDialogLayers.delete(id)) return;
refreshTopDialogZIndex();
}
/** Keep Reka's positioning wrapper in sync with the floating content's layer. */
export function useFloatingLayerOrder() {
const { forwardRef, currentElement } = useForwardExpose();
function syncWrapper() {
const element = currentElement.value;
const wrapper = element?.hasAttribute("data-reka-popper-content-wrapper") ? element : element?.parentElement;
if (!wrapper || (!wrapper.hasAttribute("data-reka-popper-content-wrapper") && element.dataset.alignTrigger !== "true")) return;
// Reka copies the content's computed z-index to the positioning wrapper.
// Read that value before enabling the important override below, otherwise
// an existing z-[60]/z-[80] value would be replaced by the live default.
const contentElement = wrapper === element ? (element.firstElementChild ?? element) : element;
const contentZIndex = Number.parseInt(getComputedStyle(contentElement).zIndex, 10);
const wrapperZIndex = Number.parseInt(wrapper.style.zIndex, 10);
const preservedZIndex = Math.max(Number.isFinite(contentZIndex) ? contentZIndex : 0, Number.isFinite(wrapperZIndex) ? wrapperZIndex : 0);
wrapper.style.setProperty("--dbx-floating-content-z-index", String(preservedZIndex));
wrapper.dataset.dbxFloatingLayer = "";
}
watchPostEffect(() => {
void topDialogZIndex.value;
syncWrapper();
});
onUpdated(syncWrapper);
return { forwardRef };
}
/**
* Keeps a dialog layer painted above every dialog that was opened before it.
* Keep the visual order of dialogs aligned with Reka UI's logical layer stack.
*
* `DialogPortal` only teleports its children, it does not gate them on the open state,
* so the `fixed inset-0 z-50` wrapper lands in the target as soon as the dialog
* *component* mounts. Because all dialog layers share the same z-index, the browser
* paints them in mount order. A dialog mounted earlier therefore covered one that opens
* later: Reka UI's dismissable-layer stack still handed pointer events to the later
* dialog, so that dialog stayed invisible while the earlier one became unclickable.
*
* Re-appending the wrapper when its dialog opens makes paint order follow open order
* instead of mount order. The element stays mounted on close, so enter/leave animations
* are unchanged.
* Reparenting portal nodes changes only their DOM order. Reka UI keeps a
* separate insertion ordered layer set for pointer-events and outside-click
* handling, so reparenting can leave the visible top dialog unreachable. A
* z-index gives each open dialog a new visual layer while its logical layer
* remains where Reka UI registered it.
*/
export function useDialogLayerOrder(positioner: Ref<HTMLElement | null>) {
export function useDialogLayerOrder() {
const rootContext = injectDialogRootContext();
function raiseLayer() {
const element = positioner.value;
const parent = element?.parentNode;
if (!element || !parent || parent.lastElementChild === element) return;
// The overlay is the sibling right in front of the wrapper; move both so a later
// dialog's backdrop still covers the earlier dialog instead of slipping under it.
const overlay = element.previousElementSibling;
if (overlay?.getAttribute("data-slot") === "dialog-overlay") parent.appendChild(overlay);
parent.appendChild(element);
}
const layerId = Symbol("dialog-layer");
const zIndex = ref(BASE_DIALOG_Z_INDEX);
watch(
() => rootContext?.open.value ?? false,
(isOpen) => {
if (isOpen) raiseLayer();
if (isOpen) {
registerDialogLayer(layerId, zIndex);
} else {
unregisterDialogLayer(layerId);
}
},
{ flush: "post" },
{ flush: "post", immediate: true },
);
onBeforeUnmount(() => unregisterDialogLayer(layerId));
return {
layerStyle: computed(() => ({ zIndex: String(zIndex.value) })),
};
}