Skip to content

feat(DocumentContext): document provider and hook #3516

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
wants to merge 15 commits into
base: main
Choose a base branch
from
Open
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
11 changes: 11 additions & 0 deletions apps/ssr-testing/app/document-context/child.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
'use client';
import * as React from 'react';
import { DocumentContext } from 'radix-ui/internal';

export function Child() {
const document = DocumentContext.useDocument();
React.useEffect(() => {
console.log(document);
}, [document]);
return <p>Open the console to see the document context.</p>;
}
13 changes: 13 additions & 0 deletions apps/ssr-testing/app/document-context/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import * as React from 'react';

import { Parent } from './parent';
import { Child } from './child';

export default function Page() {
return (
<Parent>
<h1>Document Context</h1>
<Child />
</Parent>
);
}
29 changes: 29 additions & 0 deletions apps/ssr-testing/app/document-context/parent.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
'use client';
import * as React from 'react';
import { DocumentContext } from 'radix-ui/internal';

export function Parent({ children }: { children: React.ReactNode }) {
const [document, setDocument] = React.useState<Document | null>(null);
React.useEffect(() => {
console.log(document);
}, [document]);
return (
<DocumentContext.DocumentProvider document={document}>
{children}
<div>
<iframe
onLoad={(event) => {
const iframeDocument = event.currentTarget.contentDocument;
setDocument(iframeDocument);
}}
title="Radix UI webiste"
src="https://www.radix-ui.com"
style={{
width: '100%',
height: '1000px',
}}
/>
</div>
</DocumentContext.DocumentProvider>
);
}
1 change: 1 addition & 0 deletions apps/ssr-testing/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export default function Layout({ children }: { children: React.ReactNode }) {
<Link href="/toolbar">Toolbar</Link>
<Link href="/tooltip">Tooltip</Link>
<Link href="/visually-hidden">VisuallyHidden</Link>
<Link href="/document-context">DocumentContext</Link>
</div>

<div>{children}</div>
Expand Down
2 changes: 1 addition & 1 deletion apps/storybook/stories/accordion.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ export const Animated = () => {
});
}, 3000);
return () => {
clearTimeout(timerRef.current);
window.clearTimeout(timerRef.current);
};
}
}, [count, hasDynamicContent]);
Expand Down
64 changes: 64 additions & 0 deletions apps/storybook/stories/document-context.stories.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
.trigger {
border: 1px solid black;
border-radius: 6px;
background-color: transparent;
padding: 5px 10px;
font-family: apple-system, BlinkMacSystemFont, helvetica, arial, sans-serif;
font-size: 13px;

&:focus {
outline: none;
box-shadow: 0 0 0 2px rgb(0 0 0 / 0.5);
}
}

.content {
display: inline-block;
box-sizing: border-box;
min-width: 130px;
background-color: var(--color-white);
border: 1px solid var(--color-gray100);
border-radius: 6px;
padding: 5px;
box-shadow: 0 5px 10px 0 rgba(0, 0, 0, 0.1);
font-family: apple-system, BlinkMacSystemFont, helvetica, arial, sans-serif;
font-size: 13px;
&:focus-within {
border-color: var(--color-black);
}
}

.item {
display: flex;
align-items: center;
justify-content: space-between;
line-height: 1;
cursor: default;
user-select: none;
white-space: nowrap;
height: 25px;
padding: 0 10px;
color: var(--color-black);
border-radius: 3px;

outline: none;

&[data-highlighted] {
background-color: var(--color-black);
color: var(--color-white);
}

&[data-disabled] {
color: var(--color-gray100);
}
}

.dialog {
position: fixed;
background: white;
border: 1px solid black;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 30px;
}
146 changes: 146 additions & 0 deletions apps/storybook/stories/document-context.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import * as React from 'react';
import { createPortal } from 'react-dom';
import { DocumentContext } from 'radix-ui/internal';
import { Dialog, DropdownMenu, Tooltip } from 'radix-ui';
import styles from './document-context.stories.module.css';

export default { title: 'Utilities/DocumentContext' };

export const Default = () => {
const [portalElement, setPortalElement] = React.useState<HTMLElement | null>(null);
const [count, setCount] = React.useState(0);

const openContentInPopup = async () => {
const popup = window.open(
'',
'Popup Test',
'height=600,width=600,left=300,top=300,resizable=yes,scrollbars=yes,toolbar=no,menubar=no,location=no,directories=no,status=no'
);
if (!popup) return;

// Copy all parent window styles and fonts
// https://developer.chrome.com/docs/web-platform/document-picture-in-picture/#copy-style-sheets-to-the-picture-in-picture-window
[...document.styleSheets].forEach((styleSheet) => {
try {
const cssRules = [...styleSheet.cssRules].map((rule) => rule.cssText).join('');
const style = document.createElement('style');

style.textContent = cssRules;
popup.document.head.appendChild(style);
} catch (e) {
console.error(e);
const link = document.createElement('link');
if (styleSheet.href === null) {
return;
}

link.rel = 'stylesheet';
link.type = styleSheet.type;
link.media = styleSheet.media.toString();
link.href = styleSheet.href;
popup.document.head.appendChild(link);
}
});

setPortalElement(popup.document.body);

// Detect when window is closed by user
popup.addEventListener('pagehide', () => {
setPortalElement(null);
});
};

const content = (
<div style={{ display: 'flex', flexDirection: 'column', gap: 40 }}>
<div
style={{
display: 'flex',
flexDirection: 'column',
gap: 32,
padding: 32,
background: 'yellow',
}}
>
<h1>This section will be portalled to another document/window</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
<DropdownMenu.Root>
<DropdownMenu.Trigger className={styles.trigger}>
Dropdown with dialog test
</DropdownMenu.Trigger>
<DropdownMenu.Portal>
<DropdownMenu.Content className={styles.content} sideOffset={5}>
<Dialog.Root>
<Dialog.Trigger className={styles.item} asChild>
<DropdownMenu.Item onSelect={(event) => event.preventDefault()}>
Open dialog
</DropdownMenu.Item>
</Dialog.Trigger>

<Dialog.Portal>
<Dialog.Content className={styles.dialog}>
<Dialog.Title>Nested dropdown</Dialog.Title>
<DropdownMenu.Root>
<DropdownMenu.Trigger
className={styles.trigger}
style={{ width: '100%', marginBottom: 20 }}
>
Open
</DropdownMenu.Trigger>
<DropdownMenu.Portal>
<DropdownMenu.Content className={styles.content} sideOffset={5}>
<DropdownMenu.Item
className={styles.item}
onSelect={() => console.log('undo')}
>
Undo
</DropdownMenu.Item>
<DropdownMenu.Item
className={styles.item}
onSelect={() => console.log('redo')}
>
Redo
</DropdownMenu.Item>
<DropdownMenu.Arrow />
</DropdownMenu.Content>
</DropdownMenu.Portal>
</DropdownMenu.Root>
<Dialog.Close>Close</Dialog.Close>
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
<DropdownMenu.Item className={styles.item}>Test</DropdownMenu.Item>
<DropdownMenu.Arrow />
</DropdownMenu.Content>
</DropdownMenu.Portal>
</DropdownMenu.Root>

<Tooltip.Provider>
<Tooltip.Root>
<Tooltip.Trigger asChild>
<button>Tooltip test</button>
</Tooltip.Trigger>
<Tooltip.Content>Tooltip content</Tooltip.Content>
</Tooltip.Root>
</Tooltip.Provider>
</div>
</div>
);

return (
<div>
<button onClick={openContentInPopup} type="button">
Open in Popup
</button>
<mark>{count}</mark>

{portalElement
? createPortal(
<DocumentContext.DocumentProvider document={portalElement.ownerDocument}>
{content}
</DocumentContext.DocumentProvider>,
portalElement
)
: content}
</div>
);
};
2 changes: 1 addition & 1 deletion apps/storybook/stories/dropdown-menu.stories.module.css
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
.trigger {
border: 1px solid $black;
border: 1px solid black;
border-radius: 6px;
background-color: transparent;
padding: 5px 10px;
Expand Down
2 changes: 1 addition & 1 deletion apps/storybook/stories/hover-card.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ export const AsyncUpdate = () => {

React.useEffect(() => {
return () => {
clearTimeout(timerRef.current);
window.clearTimeout(timerRef.current);
};
}, []);

Expand Down
1 change: 1 addition & 0 deletions packages/react/alert-dialog/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"@radix-ui/react-compose-refs": "workspace:*",
"@radix-ui/react-context": "workspace:*",
"@radix-ui/react-dialog": "workspace:*",
"@radix-ui/react-document-context": "workspace:*",
"@radix-ui/react-primitive": "workspace:*",
"@radix-ui/react-slot": "workspace:*"
},
Expand Down
7 changes: 5 additions & 2 deletions packages/react/alert-dialog/src/alert-dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { composeEventHandlers } from '@radix-ui/primitive';
import { createSlottable } from '@radix-ui/react-slot';

import type { Scope } from '@radix-ui/react-context';
import { useDocument } from '@radix-ui/react-document-context';

/* -------------------------------------------------------------------------------------------------
* AlertDialog
Expand Down Expand Up @@ -244,6 +245,7 @@ type DescriptionWarningProps = {
};

const DescriptionWarning: React.FC<DescriptionWarningProps> = ({ contentRef }) => {
const providedDocument = useDocument();
const MESSAGE = `\`${CONTENT_NAME}\` requires a description for the component to be accessible for screen reader users.

You can add a description to the \`${CONTENT_NAME}\` by passing a \`${DESCRIPTION_NAME}\` component as a child, which also benefits sighted users by adding visible context to the dialog.
Expand All @@ -253,11 +255,12 @@ 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(
if (!providedDocument) return;
const hasDescription = providedDocument.getElementById(
contentRef.current?.getAttribute('aria-describedby')!
);
if (!hasDescription) console.warn(MESSAGE);
}, [MESSAGE, contentRef]);
}, [MESSAGE, contentRef, providedDocument]);

return null;
};
Expand Down
1 change: 1 addition & 0 deletions packages/react/avatar/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
},
"dependencies": {
"@radix-ui/react-context": "workspace:*",
"@radix-ui/react-document-context": "workspace:*",
"@radix-ui/react-primitive": "workspace:*",
"@radix-ui/react-use-callback-ref": "workspace:*",
"@radix-ui/react-use-is-hydrated": "workspace:*",
Expand Down
10 changes: 6 additions & 4 deletions packages/react/avatar/src/avatar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Primitive } from '@radix-ui/react-primitive';
import { useIsHydrated } from '@radix-ui/react-use-is-hydrated';

import type { Scope } from '@radix-ui/react-context';
import { useDocument } from '@radix-ui/react-document-context';

/* -------------------------------------------------------------------------------------------------
* Avatar
Expand Down Expand Up @@ -99,11 +100,10 @@ const AvatarFallback = React.forwardRef<AvatarFallbackElement, AvatarFallbackPro
const { __scopeAvatar, delayMs, ...fallbackProps } = props;
const context = useAvatarContext(FALLBACK_NAME, __scopeAvatar);
const [canRender, setCanRender] = React.useState(delayMs === undefined);

React.useEffect(() => {
if (delayMs !== undefined) {
const timerId = window.setTimeout(() => setCanRender(true), delayMs);
return () => window.clearTimeout(timerId);
const timerId = globalThis.window.setTimeout(() => setCanRender(true), delayMs);
return () => globalThis.window.clearTimeout(timerId);
Comment on lines +105 to +106

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@chaance afaik browsers throttle setTimeout and setInterval by 1000ms when browser tab is inactive or hidden. So if the timeout is set on the parent window, and user opens Document PIP from it with an avatar in it, then navigates to a different tab or app, these timeouts might get delayed or paused. that's why I've attached all timeouts to the provided document window

}
}, [delayMs]);

Expand Down Expand Up @@ -136,10 +136,12 @@ function useImageLoadingStatus(
) {
const isHydrated = useIsHydrated();
const imageRef = React.useRef<HTMLImageElement | null>(null);
const providedDocument = useDocument();
const documentWindow = providedDocument?.defaultView;
const image = (() => {
if (!isHydrated) return null;
if (!imageRef.current) {
imageRef.current = new window.Image();
imageRef.current = new (documentWindow ?? globalThis.window).Image();
}
return imageRef.current;
})();
Expand Down
Loading