Skip to content

Commit 511e6d6

Browse files
qudsiamehmoodQudsia Mehmood
andauthored
fix(focus-scope): trap focus inside a shadow root (#2780)
* fix(focus-scope): trap focus inside a shadow root FocusScope attaches its focusin/focusout listeners to `document`. When the scope is teleported into a shadow root, those events are retargeted to the host, so `container.contains(target)` never matches and focus is not trapped — Tab escapes to the background. Resolve the scope's root node via `getRootNode()` (the shadow root when teleported, otherwise the document) and attach the listeners there. Related: #1667 * fix(focus-scope): add document focusin fallback for shadow-root escapes Listening only on the scope's root node misses focus escaping to a light-DOM element outside the shadow tree: that focusin fires on the owner document, not the shadow root, so the trap never recalls it. Keep the root listeners for intra-shadow moves and, when the root is a shadow root, also listen for focusin on the owner document. That handler resolves the real target via composedPath() and checks containment with a new containsComposed() helper that walks up through shadow hosts, since the event target is retargeted to the host at the document level. Rewrite the shadow-root test to assert behaviour (focus escaping to a light-DOM element is recalled into the scope) instead of spying on addEventListener, and clean up the host/listener leaks it left behind. Resolve the root via an explicit ternary and fall back to container.ownerDocument for iframe consistency. * test(focus-scope): keep shadow-root suite clear of the #2886 test region Both this PR and #2888 appended a describe block to the end of FocusScope.test.ts and extended adjacent import lines, so the two changes collided on merge. Move the shadow-root suite ahead of the #2550 block (keeping issue numbers ascending) and scope its DOM cleanup to the test body, so it no longer touches the same lines. --------- Co-authored-by: Qudsia Mehmood <qudsia.mehmood@open-xchange.com>
1 parent 2fbeade commit 511e6d6

3 files changed

Lines changed: 99 additions & 4 deletions

File tree

‎packages/core/src/FocusScope/FocusScope.test.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,64 @@ describe('focusScope', () => {
149149
})
150150

151151
// https://github.com/unovue/reka-ui/issues/2550
152+
// https://github.com/unovue/reka-ui/issues/1667
153+
// A trapped FocusScope teleported into a shadow root must keep focus inside
154+
// even when focus escapes to a light-DOM element outside the shadow tree.
155+
// Listening only on `document` misses intra-shadow moves (retargeted to the
156+
// host); listening only on the shadow root misses the light-DOM escape (which
157+
// never propagates into the root). We assert the behaviour, not the wiring.
158+
describe('given a trapped FocusScope rendered inside a shadow root (#1667)', () => {
159+
const ShadowScope = defineComponent({
160+
components: { FocusScope },
161+
template: `<FocusScope asChild loop trapped>
162+
<form>
163+
<input data-testid="inner-first" />
164+
<input data-testid="inner-second" />
165+
</form>
166+
</FocusScope>`,
167+
})
168+
169+
// document.activeElement stops at the shadow host; drill down to the real one.
170+
function deepActiveElement(): Element | null {
171+
let active = document.activeElement
172+
while (active?.shadowRoot?.activeElement)
173+
active = active.shadowRoot.activeElement
174+
return active
175+
}
176+
177+
it('recalls focus into the scope when it escapes to a light-DOM element', async () => {
178+
const host = document.createElement('div')
179+
const outsideButton = document.createElement('button')
180+
outsideButton.textContent = 'outside'
181+
document.body.append(host, outsideButton)
182+
183+
try {
184+
const shadowRoot = host.attachShadow({ mode: 'open' })
185+
const container = document.createElement('div')
186+
shadowRoot.appendChild(container)
187+
188+
render(ShadowScope, { container })
189+
await nextTick()
190+
191+
const innerFirst = shadowRoot.querySelector<HTMLInputElement>('[data-testid="inner-first"]')!
192+
innerFirst.focus()
193+
await nextTick()
194+
expect(container.contains(deepActiveElement())).toBe(true)
195+
196+
// Focus escapes to a light-DOM button outside the shadow tree.
197+
outsideButton.focus()
198+
await nextTick()
199+
200+
// The trap must pull focus back inside the scope.
201+
expect(container.contains(deepActiveElement())).toBe(true)
202+
}
203+
finally {
204+
host.remove()
205+
outsideButton.remove()
206+
}
207+
})
208+
})
209+
152210
describe('given a FocusScope with SelectTrigger inside Dialog (#2550)', () => {
153211
const DialogWithSelect = defineComponent({
154212
components: { DialogRoot, DialogTrigger, DialogContent, DialogTitle, SelectRoot, SelectTrigger, SelectValue, SelectContent, SelectItem },

‎packages/core/src/FocusScope/FocusScope.vue‎

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ import { createFocusScopesStack } from './stack'
5151
import {
5252
AUTOFOCUS_ON_MOUNT,
5353
AUTOFOCUS_ON_UNMOUNT,
54+
containsComposed,
5455
EVENT_OPTIONS,
5556
focus,
5657
focusFirst,
@@ -92,6 +93,14 @@ watchEffect((cleanupFn) => {
9293
if (!props.trapped)
9394
return
9495
96+
// Attach focus listeners to the scope's root node (a shadow root when
97+
// teleported into one, otherwise the document). On `document`, focus events
98+
// originating inside a shadow root are retargeted to the host, so
99+
// `container.contains(target)` never matches and focus escapes the trap.
100+
// -- related: https://github.com/unovue/reka-ui/issues/1667
101+
const ownerDocument = container?.ownerDocument ?? document
102+
const root = container ? (container.getRootNode() as Document | ShadowRoot) : ownerDocument
103+
95104
function handleFocusIn(event: FocusEvent) {
96105
if (focusScope.paused || !container)
97106
return
@@ -164,15 +173,32 @@ watchEffect((cleanupFn) => {
164173
focus(container)
165174
}
166175
167-
document.addEventListener('focusin', handleFocusIn)
168-
document.addEventListener('focusout', handleFocusOut)
176+
// A shadow root never sees a light-DOM `focusin`: when focus escapes to an
177+
// element outside the shadow tree, the event fires on the owner document, not
178+
// the root. So when the scope lives in a shadow root we also listen on the
179+
// document and use a composed (deep) containment check, since `event.target`
180+
// is retargeted to the shadow host at the document level.
181+
function handleDocumentFocusIn(event: FocusEvent) {
182+
if (focusScope.paused || !container)
183+
return
184+
const target = event.composedPath()[0] as HTMLElement | null
185+
if (!containsComposed(container, target))
186+
focus(lastFocusedElementRef.value, { select: true })
187+
}
188+
189+
root.addEventListener('focusin', handleFocusIn as EventListener)
190+
root.addEventListener('focusout', handleFocusOut as EventListener)
191+
if (root !== ownerDocument)
192+
ownerDocument.addEventListener('focusin', handleDocumentFocusIn as EventListener)
169193
const mutationObserver = new MutationObserver(handleMutations)
170194
if (container)
171195
mutationObserver.observe(container, { childList: true, subtree: true })
172196
173197
cleanupFn(() => {
174-
document.removeEventListener('focusin', handleFocusIn)
175-
document.removeEventListener('focusout', handleFocusOut)
198+
root.removeEventListener('focusin', handleFocusIn as EventListener)
199+
root.removeEventListener('focusout', handleFocusOut as EventListener)
200+
if (root !== ownerDocument)
201+
ownerDocument.removeEventListener('focusin', handleDocumentFocusIn as EventListener)
176202
mutationObserver.disconnect()
177203
})
178204
})

‎packages/core/src/FocusScope/utils.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,17 @@ export const EVENT_OPTIONS = { bubbles: false, cancelable: true }
66

77
type FocusableTarget = HTMLElement | { focus: () => void }
88

9+
/** Like `Node.contains`, but crosses shadow boundaries by walking up through host elements. */
10+
export function containsComposed(container: Node, node: Node | null): boolean {
11+
let current: Node | null = node
12+
while (current) {
13+
if (container.contains(current))
14+
return true
15+
current = (current.getRootNode() as ShadowRoot).host ?? null
16+
}
17+
return false
18+
}
19+
920
/**
1021
* Attempts focusing the first element in a list of candidates.
1122
* Stops when focus has actually moved.

0 commit comments

Comments
 (0)