-
Notifications
You must be signed in to change notification settings - Fork 615
Add a Portal component for rendering content outside of the current DOM element #1025
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
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
f3a8868
Add a Portal component for rendering content outside of the current D…
T-Hugs af57416
Allow portals to be de-registered (undocumented feature?)
T-Hugs 2ab2e85
Default portal root to a BaseStyles element if available.
T-Hugs f4ecfaf
Remove Portal from docs and index.ts until it is ready to be shipped …
T-Hugs 54e9123
Fix imports
T-Hugs 149e924
Add a Portal component for rendering content outside of the current D…
T-Hugs 3d67971
Allow portals to be de-registered (undocumented feature?)
T-Hugs e556c0b
Default portal root to a BaseStyles element if available.
T-Hugs bf114b0
Remove Portal from docs and index.ts until it is ready to be shipped …
T-Hugs 0ab9ea3
Fix imports
T-Hugs d8a1827
Update portal documentation with info about BaseStyles and ThemeProvi…
T-Hugs 5e51d78
Add Portal tests.
T-Hugs 2fffaf3
Merge remote-tracking branch 'origin/main' into portal
T-Hugs abb99b4
Formatting
T-Hugs 7862c7b
Merge remote-tracking branch 'origin/portal' into portal
T-Hugs a0b8474
Apply suggestions from code review (typos, formatting)
T-Hugs 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,21 @@ | ||
{ | ||
// Use IntelliSense to learn about possible attributes. | ||
// Hover to view descriptions of existing attributes. | ||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 | ||
"version": "0.2.0", | ||
"configurations": [ | ||
{ | ||
"type": "node", | ||
"request": "launch", | ||
"name": "Jest Current File", | ||
"program": "${workspaceFolder}/node_modules/.bin/jest", | ||
"args": ["${fileBasenameNoExtension}", "--config", "jest.config.js"], | ||
"console": "integratedTerminal", | ||
"internalConsoleOptions": "neverOpen", | ||
"disableOptimisticBPs": true, | ||
"windows": { | ||
"program": "${workspaceFolder}/node_modules/jest/bin/jest" | ||
} | ||
} | ||
] | ||
} |
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,71 @@ | ||
--- | ||
title: Portal | ||
--- | ||
|
||
|
||
Portals allow you to create a separation between the logical React component hierarchy and the physical DOM. See the [React documentation on portals](https://reactjs.org/docs/portals.html) for an in-depth explanation. | ||
|
||
This Portal component will render all children into the portal root DOM node instead of as children of this Portal's parent DOM element. This is useful for breaking out of the current stacking context. For example, popup menus and tooltips may need to render on top of (read: covering up) other UI. The best way to guarantee this is to add these elements to top-level DOM, such as directly on `document.body`. These elements can then be moved to the correct location using absolute positioning. | ||
|
||
## Customizing the portal root | ||
|
||
By default, Primer will create a portal root for you as a child of the closest `<BaseStyles>` element, or `document.body` if none is found. If you would like to specify your own portal root, there are two options: | ||
|
||
1. Before rendering a `<Portal>` for the first time, ensure that an element exists with id `__primerPortalRoot__`. If that exists, it will be used as the default portal root. | ||
2. Call the `registerPortalRoot` function, passing in the element you would like to use as your default portal root. | ||
|
||
Keep in mind that any inherited styles applied to portaled elements are based on its physical DOM parent. Practically this means that styles added by a `<BaseStyles>` element will not apply to the portaled content unless the portal root is a descendent of a `<BaseStyles>` element. | ||
T-Hugs marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
Also, as `<ThemeProvider>` affects the _React_ context, which applies to the logical React component hierarchy, the portal root is not required to be a child of a `<ThemeProvider>` for its children to receive that context. | ||
|
||
## Multiple portal roots | ||
There may be situations where you want to have multiple portal roots. Advanced scenarios may necessitate multiple stacking contexts for overlays. You can set up multiple roots using the `registerPortalRoot` function. Calling this function with an element and a string `name` will register the root, which can then be used by creating a `<Portal>` with a `name` prop matching the one you registered. | ||
|
||
## Default example | ||
|
||
```jsx | ||
<Portal> | ||
Regardless of where this appears in the React component | ||
tree, this text will be rendered in the DOM within the | ||
portal root at document.body. | ||
</Portal> | ||
``` | ||
|
||
## Example: custom portal root | ||
|
||
```html | ||
<!-- Wherever in your DOM tree you would like to have the default portal root --> | ||
<div id="__primerPortalRoot__"></div> | ||
``` | ||
or | ||
```js | ||
import { registerPortalRoot } from "@primer/components" | ||
registerPortalRoot(document.querySelector(".my-portal-root")!) | ||
``` | ||
|
||
## Example: multiple portal roots | ||
```jsx | ||
import { Portal, registerPortalRoot } from "@primer/components" | ||
registerPortalRoot(document.querySelector(".scrolling-canvas-root")!, "scrolling-canvas") | ||
// ... | ||
<Portal containerName="scrolling-canvas"> | ||
<div>This div will be rendered into the element registered above.</div> | ||
<Portal> | ||
<div> | ||
This div will be rendered into the default | ||
portal root created at document.body | ||
</div> | ||
</Portal> | ||
</Portal> | ||
``` | ||
|
||
## System props | ||
|
||
Since Portals do not render UI on their own, they do not accept any system props. | ||
|
||
## Component props | ||
|
||
| Name | Type | Default | Description | | ||
| :- | :- | :-: | :- | | ||
| onMount | () => void | | Called when this portal is added to the DOM | | ||
| containerName | string | | Renders the portal children into the container registered with the given name. If omitted, children are rendered into the default portal root. | |
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
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,88 @@ | ||
import React from 'react' | ||
import {createPortal} from 'react-dom' | ||
|
||
const PRIMER_PORTAL_ROOT_ID = '__primerPortalRoot__' | ||
const DEFAULT_PORTAL_CONTAINER_NAME = '__default__' | ||
|
||
const portalRootRegistry: {[key: string]: Element} = {} | ||
|
||
/** | ||
* Register a container to serve as a portal root. | ||
* @param root The element that will be the root for portals created in this container | ||
* @param name The name of the container, to be used with the `containerName` prop on the Portal Component. | ||
* If name is not specified, registers the default portal root. | ||
*/ | ||
export function registerPortalRoot(root: Element | undefined, name?: string): void { | ||
if (root instanceof Element) { | ||
portalRootRegistry[name ?? DEFAULT_PORTAL_CONTAINER_NAME] = root | ||
} else { | ||
delete portalRootRegistry[name ?? DEFAULT_PORTAL_CONTAINER_NAME] | ||
} | ||
} | ||
|
||
// Ensures that a default portal root exists and is registered. If a DOM element exists | ||
// with id __primerPortalRoot__, allow that element to serve as the default portl root. | ||
// Otherwise, create that element and attach it to the end of document.body. | ||
function ensureDefaultPortal() { | ||
if (!(DEFAULT_PORTAL_CONTAINER_NAME in portalRootRegistry)) { | ||
let defaultPortalContainer = document.getElementById(PRIMER_PORTAL_ROOT_ID) | ||
if (!(defaultPortalContainer instanceof Element)) { | ||
defaultPortalContainer = document.createElement('div') | ||
defaultPortalContainer.setAttribute('id', PRIMER_PORTAL_ROOT_ID) | ||
const suitablePortalRoot = document.querySelector('[data-portal-root]') | ||
if (suitablePortalRoot) { | ||
suitablePortalRoot.appendChild(defaultPortalContainer) | ||
} else { | ||
document.body.appendChild(defaultPortalContainer) | ||
} | ||
} | ||
portalRootRegistry[DEFAULT_PORTAL_CONTAINER_NAME] = defaultPortalContainer | ||
} | ||
} | ||
|
||
export interface PortalProps { | ||
/** | ||
* Called when this portal is added to the DOM | ||
*/ | ||
onMount?: () => void | ||
|
||
/** | ||
* Optional. Mount this portal at the container specified | ||
* by this name. The container must be previously registered | ||
* with `registerPortal`. | ||
*/ | ||
containerName?: string | ||
} | ||
|
||
/** | ||
* Creates a React Portal, placing all children in a separate physical DOM root node. | ||
* @see https://reactjs.org/docs/portals.html | ||
*/ | ||
export const Portal: React.FC<PortalProps> = ({children, onMount, containerName: _containerName}) => { | ||
const elementRef = React.useRef(document.createElement('div')) | ||
|
||
React.useLayoutEffect(() => { | ||
let containerName = _containerName | ||
if (containerName == undefined) { | ||
containerName = DEFAULT_PORTAL_CONTAINER_NAME | ||
ensureDefaultPortal() | ||
} | ||
const parentElement = portalRootRegistry[containerName] | ||
|
||
if (!parentElement) { | ||
throw new Error( | ||
`Portal container '${_containerName}' is not yet registered. Container must be registered with registerPortal before use.` | ||
) | ||
} | ||
const element = elementRef.current | ||
parentElement.appendChild(element) | ||
onMount?.() | ||
|
||
return () => { | ||
parentElement.removeChild(element) | ||
} | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
}, [elementRef]) | ||
|
||
return createPortal(children, elementRef.current) | ||
} |
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,4 @@ | ||
import {Portal, PortalProps, registerPortalRoot} from "./Portal" | ||
|
||
export default Portal | ||
export {registerPortalRoot, PortalProps} |
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,112 @@ | ||
import Portal, {registerPortalRoot} from '../Portal/index' | ||
|
||
import {render} from '@testing-library/react' | ||
import React from 'react' | ||
import BaseStyles from '../BaseStyles' | ||
|
||
describe('Portal', () => { | ||
afterEach(() => { | ||
// since the registry is global, reset after each test | ||
registerPortalRoot(undefined) | ||
}) | ||
it('renders a default portal into document.body (no BaseStyles present)', () => { | ||
const {baseElement} = render(<Portal>123test123</Portal>) | ||
const generatedRoot = baseElement.querySelector('#__primerPortalRoot__') | ||
expect(generatedRoot).toBeInstanceOf(HTMLElement) | ||
expect(generatedRoot?.textContent?.trim()).toEqual('123test123') | ||
baseElement.innerHTML = '' | ||
}) | ||
|
||
it('renders a default portal into nearest BaseStyles element', () => { | ||
const toRender = ( | ||
<div id="renderedRoot"> | ||
<BaseStyles> | ||
<div id="baseStylesRoot"> | ||
<Portal>123test123</Portal> | ||
</div> | ||
</BaseStyles> | ||
</div> | ||
) | ||
|
||
const {baseElement} = render(toRender) | ||
const baseStylesRoot = baseElement.querySelector('#baseStylesRoot') | ||
const baseStylesElement = baseStylesRoot?.parentElement | ||
const generatedRoot = baseStylesElement?.querySelector('#__primerPortalRoot__') | ||
|
||
expect(baseStylesRoot).toBeInstanceOf(HTMLElement) | ||
expect(baseStylesElement).toBeInstanceOf(HTMLElement) | ||
expect(generatedRoot).toBeInstanceOf(HTMLElement) | ||
expect(generatedRoot?.textContent?.trim()).toEqual('123test123') | ||
|
||
baseElement.innerHTML = '' | ||
}) | ||
|
||
it('renders into the custom portal root (default root name - declarative)', () => { | ||
const toRender = ( | ||
<div id="renderedRoot"> | ||
<div id="__primerPortalRoot__"></div> | ||
<Portal>123test123</Portal> | ||
</div> | ||
) | ||
const {baseElement} = render(toRender) | ||
const renderedRoot = baseElement.querySelector('#renderedRoot') | ||
const portalRoot = renderedRoot?.querySelector('#__primerPortalRoot__') | ||
|
||
expect(portalRoot).toBeInstanceOf(HTMLElement) | ||
expect(portalRoot?.textContent?.trim()).toEqual('123test123') | ||
|
||
baseElement.innerHTML = '' | ||
}) | ||
|
||
it('renders into the custom portal root (default root name - imperative)', () => { | ||
const portalRootJSX = <div id="myPortalRoot"></div> | ||
let {baseElement} = render(portalRootJSX) | ||
const portalRoot = baseElement.querySelector('#myPortalRoot') | ||
expect(portalRoot).toBeInstanceOf(HTMLElement) | ||
|
||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion | ||
registerPortalRoot(baseElement.querySelector('#myPortalRoot')!) | ||
|
||
const toRender = <Portal>123test123</Portal> | ||
;({baseElement} = render(toRender)) | ||
expect(portalRoot?.textContent?.trim()).toEqual('123test123') | ||
|
||
baseElement.innerHTML = '' | ||
}) | ||
|
||
it('renders into multiple custom portal roots (named)', () => { | ||
const portalRootJSX = ( | ||
<main> | ||
<div id="myPortalRoot1"></div> | ||
<div id="myPortalRoot2"></div> | ||
</main> | ||
) | ||
let {baseElement} = render(portalRootJSX) | ||
const fancyPortalRoot1 = baseElement.querySelector('#myPortalRoot1') | ||
const fancyPortalRoot2 = baseElement.querySelector('#myPortalRoot2') | ||
expect(fancyPortalRoot1).toBeInstanceOf(HTMLElement) | ||
expect(fancyPortalRoot2).toBeInstanceOf(HTMLElement) | ||
|
||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion | ||
registerPortalRoot(baseElement.querySelector('#myPortalRoot1')!, 'fancyPortal1') | ||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion | ||
registerPortalRoot(baseElement.querySelector('#myPortalRoot2')!, 'fancyPortal2') | ||
|
||
const toRender = ( | ||
<> | ||
<Portal>123test123</Portal> | ||
<Portal containerName="fancyPortal1">456test456</Portal> | ||
<Portal containerName="fancyPortal2">789test789</Portal> | ||
</> | ||
) | ||
;({baseElement} = render(toRender)) | ||
const generatedRoot = baseElement.querySelector('#__primerPortalRoot__') | ||
expect(generatedRoot?.textContent?.trim()).toEqual('123test123') | ||
expect(fancyPortalRoot1?.textContent?.trim()).toEqual('456test456') | ||
expect(fancyPortalRoot2?.textContent?.trim()).toEqual('789test789') | ||
|
||
console.log(baseElement.outerHTML) | ||
|
||
baseElement.innerHTML = '' | ||
}) | ||
}) |
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
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.