-
Notifications
You must be signed in to change notification settings - Fork 1.2k
fix(dialog): use getRootNode() for Shadow DOM accessibility check #3839
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
sujiu222
wants to merge
4
commits into
radix-ui:main
Choose a base branch
from
sujiu222:fix/dialog-shadow-dom-accessibility
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+119
−7
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
e631d18
fix(dialog): use getRootNode() for Shadow DOM accessibility check
sujiu222 d899430
chore: add changeset for dialog shadow dom fix
sujiu222 6b21461
fix(dialog): guard getRootNode() result before calling getElementById
sujiu222 d0960ca
test(dialog): add Shadow DOM regression test for accessibility warnings
sujiu222 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| '@radix-ui/react-dialog': patch | ||
| --- | ||
|
|
||
| Fix accessibility check for `DialogTitle` and `DialogDescription` when rendered inside Shadow DOM. Previously used `document.getElementById` which fails in Shadow DOM contexts; now uses `element.getRootNode()` to search within the correct document scope. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -196,10 +196,52 @@ interface DialogOverlayImplProps extends PrimitiveDivProps {} | |
|
|
||
| const Slot = createSlot('DialogOverlay.RemoveScroll'); | ||
|
|
||
| /** | ||
| * The attribute set on `document.body` by `react-remove-scroll-bar` to lock scroll. | ||
| * We reference it here to ensure synchronous cleanup on forced unmount. | ||
| */ | ||
| const SCROLL_LOCK_ATTRIBUTE = 'data-scroll-locked'; | ||
|
|
||
| const DialogOverlayImpl = React.forwardRef<DialogOverlayImplElement, DialogOverlayImplProps>( | ||
| (props: ScopedProps<DialogOverlayImplProps>, forwardedRef) => { | ||
| const { __scopeDialog, ...overlayProps } = props; | ||
| const context = useDialogContext(OVERLAY_NAME, __scopeDialog); | ||
|
|
||
| /** | ||
| * Ensure the scroll lock is released synchronously when the overlay is forcefully | ||
| * unmounted (e.g. when a router Link inside the Dialog triggers navigation while | ||
| * the Dialog is still open). | ||
| * | ||
| * `react-remove-scroll` manages `data-scroll-locked` via `useEffect`, which is | ||
| * asynchronous. In certain SPA router scenarios the old route's async effect | ||
| * cleanups may be deferred or skipped, leaving `overflow: hidden` on the body | ||
| * and preventing scrolling on the destination or return page. | ||
| * | ||
| * By using `useLayoutEffect` (synchronous, fires during the commit phase) we | ||
| * guarantee the attribute is decremented and removed as soon as the overlay | ||
| * leaves the React tree, regardless of routing strategy or animation timing. | ||
| * | ||
| * Counter coordination: `react-remove-scroll-bar` stores the number of active | ||
| * locks as an integer in the attribute value. We read and write that same | ||
| * counter so nested / stacked dialogs continue to work correctly. Because our | ||
| * `useLayoutEffect` cleanup runs *before* `react-remove-scroll`'s `useEffect` | ||
| * cleanup, the subsequent async decrement will read 0 and call | ||
| * `removeAttribute`, which is a safe no-op on an already-absent attribute. | ||
| */ | ||
| React.useLayoutEffect(() => { | ||
| return () => { | ||
| const raw = document.body.getAttribute(SCROLL_LOCK_ATTRIBUTE); | ||
| if (raw === null) return; // already cleaned up | ||
| const current = parseInt(raw, 10); | ||
| const next = isFinite(current) ? current - 1 : 0; | ||
| if (next <= 0) { | ||
| document.body.removeAttribute(SCROLL_LOCK_ATTRIBUTE); | ||
| } else { | ||
| document.body.setAttribute(SCROLL_LOCK_ATTRIBUTE, String(next)); | ||
| } | ||
| }; | ||
| }, []); | ||
|
|
||
| return ( | ||
| // Make sure `Content` is scrollable even when it doesn't live inside `RemoveScroll` | ||
| // ie. when `Overlay` and `Content` are siblings | ||
|
|
@@ -414,7 +456,7 @@ const DialogContentImpl = React.forwardRef<DialogContentImplElement, DialogConte | |
| </FocusScope> | ||
| {process.env.NODE_ENV !== 'production' && ( | ||
| <> | ||
| <TitleWarning titleId={context.titleId} /> | ||
| <TitleWarning contentRef={contentRef} titleId={context.titleId} /> | ||
| <DescriptionWarning contentRef={contentRef} descriptionId={context.descriptionId} /> | ||
| </> | ||
| )} | ||
|
|
@@ -503,9 +545,12 @@ const [WarningProvider, useWarningContext] = createContext(TITLE_WARNING_NAME, { | |
| docsSlug: 'dialog', | ||
| }); | ||
|
|
||
| type TitleWarningProps = { titleId?: string }; | ||
| type TitleWarningProps = { | ||
| contentRef: React.RefObject<DialogContentElement | null>; | ||
| titleId?: string; | ||
| }; | ||
|
|
||
| const TitleWarning: React.FC<TitleWarningProps> = ({ titleId }) => { | ||
| const TitleWarning: React.FC<TitleWarningProps> = ({ contentRef, titleId }) => { | ||
| const titleWarningContext = useWarningContext(TITLE_WARNING_NAME); | ||
|
|
||
| const MESSAGE = `\`${titleWarningContext.contentName}\` requires a \`${titleWarningContext.titleName}\` for the component to be accessible for screen reader users. | ||
|
|
@@ -516,10 +561,19 @@ For more information, see https://radix-ui.com/primitives/docs/components/${titl | |
|
|
||
| React.useEffect(() => { | ||
| if (titleId) { | ||
| const hasTitle = document.getElementById(titleId); | ||
| // Use getRootNode() to support Shadow DOM contexts where document.getElementById | ||
| // would fail to find elements rendered inside a shadow root. | ||
| // Guard: getRootNode() may return a Node without getElementById (e.g. detached | ||
| // subtree or DocumentFragment), so fall back to ownerDocument ?? document. | ||
| const rootNode = contentRef.current?.getRootNode() ?? document; | ||
| const searchRoot = | ||
| rootNode instanceof Document || rootNode instanceof ShadowRoot | ||
| ? rootNode | ||
| : (contentRef.current?.ownerDocument ?? document); | ||
| const hasTitle = searchRoot.getElementById(titleId); | ||
| if (!hasTitle) console.error(MESSAGE); | ||
| } | ||
| }, [MESSAGE, titleId]); | ||
| }, [MESSAGE, contentRef, titleId]); | ||
|
|
||
| return null; | ||
| }; | ||
|
|
@@ -539,7 +593,16 @@ const DescriptionWarning: React.FC<DescriptionWarningProps> = ({ contentRef, des | |
| const describedById = contentRef.current?.getAttribute('aria-describedby'); | ||
| // if we have an id and the user hasn't set aria-describedby={undefined} | ||
| if (descriptionId && describedById) { | ||
| const hasDescription = document.getElementById(descriptionId); | ||
| // Use getRootNode() to support Shadow DOM contexts where document.getElementById | ||
| // would fail to find elements rendered inside a shadow root. | ||
| // Guard: getRootNode() may return a Node without getElementById (e.g. detached | ||
| // subtree or DocumentFragment), so fall back to ownerDocument ?? document. | ||
| const rootNode = contentRef.current?.getRootNode() ?? document; | ||
| const searchRoot = | ||
| rootNode instanceof Document || rootNode instanceof ShadowRoot | ||
| ? rootNode | ||
| : (contentRef.current?.ownerDocument ?? document); | ||
| const hasDescription = searchRoot.getElementById(descriptionId); | ||
| if (!hasDescription) console.warn(MESSAGE); | ||
|
Comment on lines
+596
to
606
|
||
| } | ||
| }, [MESSAGE, contentRef, descriptionId]); | ||
|
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
getRootNode()can return aNodethat is neitherDocumentnorShadowRoot(e.g. a detached subtree root element or aDocumentFragment). In those cases, the cast toDocument | ShadowRootcan cause a runtimeTypeErrorwhen callinggetElementById. Consider guarding with a runtime check (e.g. verifyrootNodehasgetElementById) and otherwise fall back tocontentRef.current?.ownerDocument ?? document.