From f4368dd2c00a0d78585e0377f0a65d1701dfa5b4 Mon Sep 17 00:00:00 2001 From: molvqingtai Date: Mon, 17 Feb 2025 02:21:28 +0800 Subject: [PATCH] fix: TitleWarning & DescriptionWarning not working correctly in shadow dom --- packages/react/alert-dialog/src/alert-dialog.tsx | 5 ++--- packages/react/dialog/src/dialog.tsx | 13 ++++++++----- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/packages/react/alert-dialog/src/alert-dialog.tsx b/packages/react/alert-dialog/src/alert-dialog.tsx index be6969978..07630519b 100644 --- a/packages/react/alert-dialog/src/alert-dialog.tsx +++ b/packages/react/alert-dialog/src/alert-dialog.tsx @@ -251,9 +251,8 @@ Alternatively, you can use your own component as a description by assigning it a For more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`; React.useEffect(() => { - const hasDescription = document.getElementById( - contentRef.current?.getAttribute('aria-describedby')! - ); + const describedById = contentRef.current?.getAttribute('aria-describedby'); + const hasDescription = contentRef.current?.querySelector(`[id="${describedById}"]`); if (!hasDescription) console.warn(MESSAGE); }, [MESSAGE, contentRef]); diff --git a/packages/react/dialog/src/dialog.tsx b/packages/react/dialog/src/dialog.tsx index db1d22ad1..7cf03903b 100644 --- a/packages/react/dialog/src/dialog.tsx +++ b/packages/react/dialog/src/dialog.tsx @@ -411,7 +411,7 @@ const DialogContentImpl = React.forwardRef {process.env.NODE_ENV !== 'production' && ( <> - + )} @@ -500,9 +500,12 @@ const [WarningProvider, useWarningContext] = createContext(TITLE_WARNING_NAME, { docsSlug: 'dialog', }); -type TitleWarningProps = { titleId?: string }; +type TitleWarningProps = { + contentRef: React.RefObject; + titleId?: string; +}; -const TitleWarning: React.FC = ({ titleId }) => { +const TitleWarning: React.FC = ({ 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. @@ -513,7 +516,7 @@ For more information, see https://radix-ui.com/primitives/docs/components/${titl React.useEffect(() => { if (titleId) { - const hasTitle = document.getElementById(titleId); + const hasTitle = contentRef.current?.querySelector(`[id="${titleId}"]`); if (!hasTitle) console.error(MESSAGE); } }, [MESSAGE, titleId]); @@ -536,7 +539,7 @@ const DescriptionWarning: React.FC = ({ 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); + const hasDescription = contentRef.current?.querySelector(`[id="${descriptionId}"]`); if (!hasDescription) console.warn(MESSAGE); } }, [MESSAGE, contentRef, descriptionId]);