Skip to content

Commit 9a9381d

Browse files
committed
fix(dismissable): register escape handler as soon as the node commits
trackDismissableElement deferred its entire body by one animation frame when defer: true, so a dialog was painted and focus-trapped before the layer reached layerStack and before trackEscapeKeydown was attached. An Escape sent in that window did nothing, and under CPU load the window stretched well past a frame. Resolving the node eagerly does not help on its own: machine effects run before the framework commits its DOM, so the node is always null at call time and the deferred pass is always taken. The node does commit on the following microtask, which lands far sooner than the next frame. whenNode (new, in dom-query) escalates sync -> microtask -> rAF and is now used by both trackDismissableElement and trackDismissableBranch. trackDismissableElementImpl takes a non-null node, dropping its internal null checks and the node! assertions. Measured on /dialog/basic: registration gap 33ms -> 0ms, and a real Escape keypress at 6x and 20x CPU throttle went from 4/5 to 5/5. Fixes #3248
1 parent c15e7ec commit 9a9381d

6 files changed

Lines changed: 340 additions & 49 deletions

File tree

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
"@zag-js/dom-query": patch
3+
"@zag-js/dismissable": patch
4+
---
5+
6+
Fix `Escape` being ignored for a frame after a dismissable layer opens. `trackDismissableElement` deferred handler
7+
registration to the next animation frame, so a dialog, popover or menu was painted and focus-trapped while its layer was
8+
not yet on the stack. Under CPU load the gap grew well past one frame and swallowed the keypress.

‎packages/utilities/dismissable/src/dismissable-layer.ts‎

Lines changed: 24 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
import { contains, getEventTarget, isHTMLElement, raf } from "@zag-js/dom-query"
1+
import { contains, getEventTarget, isHTMLElement, whenNode } from "@zag-js/dom-query"
22
import {
33
trackInteractOutside,
44
type FocusOutsideEvent,
55
type InteractOutsideHandlers,
66
type PointerDownOutsideEvent,
77
} from "@zag-js/interact-outside"
8-
import { isFunction, warn, type MaybeFunction } from "@zag-js/utils"
8+
import { warn, type MaybeFunction } from "@zag-js/utils"
99
import { trackEscapeKeydown } from "./escape-keydown"
1010
import { layerStack, type Layer, type LayerDismissEvent, type LayerStyleTarget, type LayerType } from "./layer-stack"
1111
import { assignPointerEventToLayers, clearPointerEvent, disablePointerEventsOutside } from "./pointer-event-outside"
@@ -71,18 +71,7 @@ export interface DismissableElementOptions extends DismissableElementHandlers, P
7171
type?: LayerType | undefined
7272
}
7373

74-
function trackDismissableElementImpl(node: MaybeElement, options: DismissableElementOptions) {
75-
const { warnOnMissingNode = true } = options
76-
77-
if (warnOnMissingNode && !node) {
78-
warn("[@zag-js/dismissable] node is `null` or `undefined`")
79-
return
80-
}
81-
82-
if (!node) {
83-
return
84-
}
85-
74+
function trackDismissableElementImpl(node: HTMLElement, options: DismissableElementOptions) {
8675
const {
8776
onDismiss,
8877
onRequestDismiss,
@@ -107,7 +96,7 @@ function trackDismissableElementImpl(node: MaybeElement, options: DismissableEle
10796

10897
function onPointerDownOutside(event: PointerDownOutsideEvent) {
10998
const target = getEventTarget(event.detail.originalEvent)
110-
if (layerStack.isBelowPointerBlockingLayer(node!) || layerStack.isInBranch(target)) return
99+
if (layerStack.isBelowPointerBlockingLayer(node) || layerStack.isInBranch(target)) return
111100
options.onPointerDownOutside?.(event)
112101
options.onInteractOutside?.(event)
113102
if (event.defaultPrevented) return
@@ -130,7 +119,7 @@ function trackDismissableElementImpl(node: MaybeElement, options: DismissableEle
130119
}
131120

132121
function onEscapeKeyDown(event: KeyboardEvent) {
133-
if (!layerStack.isTopMost(node!)) return
122+
if (!layerStack.isTopMost(node)) return
134123
options.onEscapeKeyDown?.(event)
135124
if (!event.defaultPrevented && onDismiss) {
136125
event.preventDefault()
@@ -139,7 +128,6 @@ function trackDismissableElementImpl(node: MaybeElement, options: DismissableEle
139128
}
140129

141130
function exclude(target: Element) {
142-
if (!node) return false
143131
const containers = typeof excludeContainers === "function" ? excludeContainers() : excludeContainers
144132
const _containers = Array.isArray(containers) ? containers : [containers]
145133
const persistentElements = options.persistentElements?.map((fn) => fn()).filter(isHTMLElement)
@@ -154,50 +142,37 @@ function trackDismissableElementImpl(node: MaybeElement, options: DismissableEle
154142
]
155143

156144
return () => {
157-
layerStack.remove(node!)
145+
layerStack.remove(node)
158146
// re-assign pointer event to remaining layers
159147
assignPointerEventToLayers()
160148
// remove pointer event from removed layer
161-
clearPointerEvent(node!)
149+
clearPointerEvent(node)
162150
cleanups.forEach((fn) => fn?.())
163151
}
164152
}
165153

166154
export function trackDismissableElement(nodeOrFn: NodeOrFn, options: DismissableElementOptions) {
167-
const { defer } = options
168-
const func = defer ? raf : (v: any) => v()
169-
const cleanups: (VoidFunction | undefined)[] = []
170-
cleanups.push(
171-
func(() => {
172-
const node = isFunction(nodeOrFn) ? nodeOrFn() : nodeOrFn
173-
cleanups.push(trackDismissableElementImpl(node, options))
174-
}),
175-
)
176-
return () => {
177-
cleanups.forEach((fn) => fn?.())
178-
}
155+
const { warnOnMissingNode = true } = options
156+
// `defer` gates node resolution only — escape dismissal is dead until the layer is on
157+
// the stack, so registration must not wait a frame longer than the node does.
158+
return whenNode(nodeOrFn, (node) => trackDismissableElementImpl(node, options), {
159+
defer: options.defer,
160+
onMissing: warnOnMissingNode ? () => warn("[@zag-js/dismissable] node is `null` or `undefined`") : undefined,
161+
})
179162
}
180163

181164
export function trackDismissableBranch(nodeOrFn: NodeOrFn, options: { defer?: boolean | undefined } = {}) {
182-
const { defer } = options
183-
const func = defer ? raf : (v: any) => v()
184-
const cleanups: (VoidFunction | undefined)[] = []
185-
186-
cleanups.push(
187-
func(() => {
188-
const node = isFunction(nodeOrFn) ? nodeOrFn() : nodeOrFn
189-
if (!node) {
190-
warn("[@zag-js/dismissable] branch node is `null` or `undefined`")
191-
return
192-
}
165+
return whenNode(
166+
nodeOrFn,
167+
(node) => {
193168
layerStack.addBranch(node)
194-
cleanups.push(() => {
169+
return () => {
195170
layerStack.removeBranch(node)
196-
})
197-
}),
171+
}
172+
},
173+
{
174+
defer: options.defer,
175+
onMissing: () => warn("[@zag-js/dismissable] branch node is `null` or `undefined`"),
176+
},
198177
)
199-
200-
return () => {
201-
cleanups.forEach((fn) => fn?.())
202-
}
203178
}
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
// @vitest-environment jsdom
2+
3+
import { noop } from "@zag-js/utils"
4+
import { afterEach, describe, expect, test, vi } from "vitest"
5+
import { trackDismissableElement } from "../src/dismissable-layer"
6+
import { layerStack } from "../src/layer-stack"
7+
8+
function raf() {
9+
return new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))
10+
}
11+
12+
function pressEscape() {
13+
document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }))
14+
}
15+
16+
function mountNode() {
17+
const node = document.createElement("div")
18+
document.body.appendChild(node)
19+
return node
20+
}
21+
22+
function resetStack() {
23+
while (layerStack.count() > 0) {
24+
const first = layerStack.layers[0]
25+
if (first) layerStack.remove(first.node)
26+
}
27+
}
28+
29+
describe("trackDismissableElement", () => {
30+
afterEach(() => {
31+
resetStack()
32+
document.body.innerHTML = ""
33+
})
34+
35+
test("registers escape handler synchronously when the node is already available", () => {
36+
const node = mountNode()
37+
const onDismiss = vi.fn()
38+
39+
// `defer: true` is what every machine passes (dialog, popover, menu, ...)
40+
const cleanup = trackDismissableElement(node, { defer: true, onDismiss })
41+
42+
// no frame has passed — the dialog is painted and interactive at this point
43+
pressEscape()
44+
expect(onDismiss).toHaveBeenCalledTimes(1)
45+
46+
cleanup()
47+
})
48+
49+
test("adds the layer to the stack synchronously when the node is already available", () => {
50+
const node = mountNode()
51+
52+
const cleanup = trackDismissableElement(node, { defer: true, onDismiss: noop })
53+
54+
expect(layerStack.isTopMost(node)).toBe(true)
55+
56+
cleanup()
57+
})
58+
59+
// the real-world path: machine effects run before the framework commits the content,
60+
// so the node is always null at call time and only appears in the following render
61+
test("registers on the microtask tick, without waiting a frame, once the node commits", async () => {
62+
let node: HTMLElement | null = null
63+
const onDismiss = vi.fn()
64+
65+
const cleanup = trackDismissableElement(() => node, {
66+
defer: true,
67+
onDismiss,
68+
warnOnMissingNode: false,
69+
})
70+
71+
node = mountNode()
72+
await Promise.resolve()
73+
74+
pressEscape()
75+
expect(onDismiss).toHaveBeenCalledTimes(1)
76+
77+
cleanup()
78+
})
79+
80+
test("falls back to a frame when the node has still not committed by the microtask", async () => {
81+
let node: HTMLElement | null = null
82+
const onDismiss = vi.fn()
83+
84+
const cleanup = trackDismissableElement(() => node, {
85+
defer: true,
86+
onDismiss,
87+
warnOnMissingNode: false,
88+
})
89+
90+
await Promise.resolve()
91+
node = mountNode()
92+
await raf()
93+
94+
pressEscape()
95+
expect(onDismiss).toHaveBeenCalledTimes(1)
96+
97+
cleanup()
98+
})
99+
100+
test("does not register when cleanup runs before the node commits", async () => {
101+
let node: HTMLElement | null = null
102+
const onDismiss = vi.fn()
103+
104+
const cleanup = trackDismissableElement(() => node, {
105+
defer: true,
106+
onDismiss,
107+
warnOnMissingNode: false,
108+
})
109+
cleanup()
110+
111+
node = mountNode()
112+
await Promise.resolve()
113+
await raf()
114+
115+
pressEscape()
116+
expect(onDismiss).not.toHaveBeenCalled()
117+
expect(layerStack.isTopMost(node)).toBe(false)
118+
})
119+
120+
test("cleanup removes the layer and unregisters escape", async () => {
121+
const node = mountNode()
122+
const onDismiss = vi.fn()
123+
124+
const cleanup = trackDismissableElement(node, { defer: true, onDismiss })
125+
cleanup()
126+
await raf()
127+
128+
pressEscape()
129+
expect(onDismiss).not.toHaveBeenCalled()
130+
expect(layerStack.isTopMost(node)).toBe(false)
131+
})
132+
})

‎packages/utilities/dom-query/src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,4 @@ export type { Booleanish } from "./types"
3131
export * from "./visual-viewport"
3232
export * from "./visually-hidden"
3333
export * from "./wait-for"
34+
export * from "./when-node"
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import type { MaybeFn } from "@zag-js/types"
2+
import { raf } from "./raf"
3+
4+
export interface WhenNodeOptions {
5+
/**
6+
* Whether the node may not be committed to the DOM yet.
7+
* When `false`, the node is resolved once and never awaited.
8+
*/
9+
defer?: boolean | undefined
10+
/**
11+
* Called when the node never became available.
12+
*/
13+
onMissing?: VoidFunction | undefined
14+
}
15+
16+
/**
17+
* Invokes `fn` with the node as soon as it is available:
18+
* synchronously if it is already committed, otherwise on the microtask that follows the
19+
* framework's render pass, falling back to the next frame.
20+
*
21+
* Machine effects run before the framework commits its DOM, so a lazily-rendered node is
22+
* usually `null` at call time but present a microtask later — waiting a whole frame leaves
23+
* handlers unregistered while the element is already painted and interactive.
24+
*
25+
* `fn` is never called without a node; use `onMissing` to handle that case.
26+
* Returns a cleanup that cancels any pending work and runs the cleanup `fn` returned.
27+
*/
28+
export function whenNode<T extends Element = HTMLElement>(
29+
nodeOrFn: MaybeFn<T | null>,
30+
fn: (node: T) => VoidFunction | void,
31+
options: WhenNodeOptions = {},
32+
): VoidFunction {
33+
const { defer, onMissing } = options
34+
35+
const getNode = () => (typeof nodeOrFn === "function" ? nodeOrFn() : nodeOrFn)
36+
const cleanups: (VoidFunction | undefined | void)[] = []
37+
38+
const setup = (node: T | null) => {
39+
if (!node) return onMissing?.()
40+
cleanups.push(fn(node))
41+
}
42+
43+
const node = getNode()
44+
45+
if (!defer || node) {
46+
setup(node)
47+
} else {
48+
let cancelled = false
49+
cleanups.push(() => {
50+
cancelled = true
51+
})
52+
53+
queueMicrotask(() => {
54+
if (cancelled) return
55+
56+
const committed = getNode()
57+
if (committed) {
58+
setup(committed)
59+
return
60+
}
61+
62+
cleanups.push(
63+
raf(() => {
64+
if (cancelled) return
65+
setup(getNode())
66+
}),
67+
)
68+
})
69+
}
70+
71+
return () => {
72+
cleanups.forEach((fn) => fn?.())
73+
}
74+
}

0 commit comments

Comments
 (0)