Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions packages/emcn/src/components/modal/modal.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -153,9 +153,15 @@ describe('native-surface modal preparation', () => {
expect(readyLayers.contentLayer.className).toContain('pointer-events-none')
expect(readyLayers.dialog).not.toBeNull()
expect(readyLayers.dialog?.style.visibility).not.toBe('hidden')
expect(document.activeElement).toBe(
document.querySelector<HTMLInputElement>('[aria-label="Modal field"]')
)
const modalField = document.querySelector<HTMLInputElement>('[aria-label="Modal field"]')
expect(document.activeElement).toBe(modalField)
// The control that now holds focus takes the very next key; no frame has to pass first.
const modalKeyDown = vi.fn()
modalField?.addEventListener('keydown', modalKeyDown)
const firstKey = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, key: 'x' })
modalField?.dispatchEvent(firstKey)
expect(firstKey.defaultPrevented).toBe(false)
expect(modalKeyDown).toHaveBeenCalledOnce()
})

it('fails closed when a registered preparation rejects', async () => {
Expand Down
37 changes: 30 additions & 7 deletions packages/emcn/src/components/modal/modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import * as React from 'react'
import * as DialogPrimitive from '@radix-ui/react-dialog'
import { usePathname } from 'next/navigation'
import { flushSync } from 'react-dom'
import { cn } from '../../lib/cn'
import { focusFirstTextInput, focusFirstTextInputIn } from './auto-focus'

Expand Down Expand Up @@ -79,9 +80,21 @@ export interface NativeSurfaceOcclusionPrepareDetail {

interface NativeSurfaceOcclusionPreparation {
completion: Promise<void>
/** Re-enables keyboard input. Idempotent; `cancel` also releases it. */
releaseInteraction: () => void
cancel: () => void
}

interface NativeSurfaceOcclusionPreparationOptions {
/**
* Keeps keyboard input blocked after preparation settles until the caller
* calls `releaseInteraction`, instead of releasing it on the next frame. A
* surface that moves focus into itself on readiness releases right after
* that focus lands, so a focused control never drops its first key.
*/
holdInteraction?: boolean
}

const PENDING_NATIVE_INTERACTION_EVENTS = [
'beforeinput',
'compositionstart',
Expand Down Expand Up @@ -162,7 +175,8 @@ function acquirePendingNativeInteractionLock(): () => void {
* than exposing an unoccluded native surface underneath it.
*/
function requestNativeSurfaceOcclusionPreparation(
kind: NativeSurfaceOcclusionPrepareDetail['kind']
kind: NativeSurfaceOcclusionPrepareDetail['kind'],
{ holdInteraction = false }: NativeSurfaceOcclusionPreparationOptions = {}
): NativeSurfaceOcclusionPreparation | null {
const preparations: Promise<unknown>[] = []
const detail: NativeSurfaceOcclusionPrepareDetail = {
Expand All @@ -178,12 +192,13 @@ function requestNativeSurfaceOcclusionPreparation(
const releaseInteractionLock = acquirePendingNativeInteractionLock()
let releaseFrame: number | null = null
const completion = Promise.all(preparations).then(() => undefined)
// Keep keyboard input blocked through the first ready paint. The modal's
// layout effect can move focus into its real content before interaction is
// re-enabled; rejected preparation deliberately remains fail-closed until
// the owning surface unmounts and calls `cancel`.
// Keep keyboard input blocked through the first ready paint, or with
// `holdInteraction` until the caller has moved focus and releases it.
// Rejected preparation deliberately remains fail-closed until the owning
// surface unmounts and calls `cancel`.
void completion.then(
() => {
if (holdInteraction) return
releaseFrame = requestAnimationFrame(() => {
releaseFrame = null
releaseInteractionLock()
Expand All @@ -193,6 +208,7 @@ function requestNativeSurfaceOcclusionPreparation(
)
return {
completion,
releaseInteraction: releaseInteractionLock,
cancel: () => {
if (releaseFrame !== null) cancelAnimationFrame(releaseFrame)
releaseFrame = null
Expand Down Expand Up @@ -340,14 +356,21 @@ function NativeSurfaceModalGate({ barrierClaimedRef, onReadyChange }: NativeSurf
let active = true

onReadyChange(false)
const preparation = requestNativeSurfaceOcclusionPreparation('modal')
const preparation = requestNativeSurfaceOcclusionPreparation('modal', {
holdInteraction: true,
})
barrierClaimedRef.current = preparation !== null
if (!preparation) {
onReadyChange(true)
} else {
void preparation.completion.then(
() => {
if (active) onReadyChange(true)
if (!active) return
// Commit readiness now so ModalContent's layout effect moves focus into
// the dialog, then accept keys: a focused control must take the very
// next key (Escape on a Leave prompt), never drop it to the barrier.
flushSync(() => onReadyChange(true))
preparation.releaseInteraction()
},
() => {
// A failed native-surface transition is unsafe to reveal through.
Expand Down
Loading