Skip to content

Commit b5f1a59

Browse files
authored
Merge pull request #1025 from primer/portal
Add a Portal component for rendering content outside of the current DOM element
2 parents 09cb174 + a0b8474 commit b5f1a59

File tree

10 files changed

+427
-2
lines changed

10 files changed

+427
-2
lines changed

.vscode/launch.json

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
{
2+
// Use IntelliSense to learn about possible attributes.
3+
// Hover to view descriptions of existing attributes.
4+
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5+
"version": "0.2.0",
6+
"configurations": [
7+
{
8+
"type": "node",
9+
"request": "launch",
10+
"name": "Jest Current File",
11+
"program": "${workspaceFolder}/node_modules/.bin/jest",
12+
"args": ["${fileBasenameNoExtension}", "--config", "jest.config.js"],
13+
"console": "integratedTerminal",
14+
"internalConsoleOptions": "neverOpen",
15+
"disableOptimisticBPs": true,
16+
"windows": {
17+
"program": "${workspaceFolder}/node_modules/jest/bin/jest"
18+
}
19+
}
20+
]
21+
}

docs/content/Portal.mdx

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
---
2+
title: Portal
3+
---
4+
5+
6+
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.
7+
8+
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.
9+
10+
## Customizing the portal root
11+
12+
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:
13+
14+
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.
15+
2. Call the `registerPortalRoot` function, passing in the element you would like to use as your default portal root.
16+
17+
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.
18+
19+
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.
20+
21+
## Multiple portal roots
22+
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.
23+
24+
## Default example
25+
26+
```jsx
27+
<Portal>
28+
Regardless of where this appears in the React component
29+
tree, this text will be rendered in the DOM within the
30+
portal root at document.body.
31+
</Portal>
32+
```
33+
34+
## Example: custom portal root
35+
36+
```html
37+
<!-- Wherever in your DOM tree you would like to have the default portal root -->
38+
<div id="__primerPortalRoot__"></div>
39+
```
40+
or
41+
```js
42+
import { registerPortalRoot } from "@primer/components"
43+
registerPortalRoot(document.querySelector(".my-portal-root")!)
44+
```
45+
46+
## Example: multiple portal roots
47+
```jsx
48+
import { Portal, registerPortalRoot } from "@primer/components"
49+
registerPortalRoot(document.querySelector(".scrolling-canvas-root")!, "scrolling-canvas")
50+
// ...
51+
<Portal containerName="scrolling-canvas">
52+
<div>This div will be rendered into the element registered above.</div>
53+
<Portal>
54+
<div>
55+
This div will be rendered into the default
56+
portal root created at document.body
57+
</div>
58+
</Portal>
59+
</Portal>
60+
```
61+
62+
## System props
63+
64+
Since Portals do not render UI on their own, they do not accept any system props.
65+
66+
## Component props
67+
68+
| Name | Type | Default | Description |
69+
| :- | :- | :-: | :- |
70+
| onMount | () => void | | Called when this portal is added to the DOM |
71+
| containerName | string | | Renders the portal children into the container registered with the given name. If omitted, children are rendered into the default portal root. |

docs/src/@primer/gatsby-theme-doctocat/nav.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,8 @@
8080
url: /PointerBox
8181
- title: Popover
8282
url: /Popover
83+
# - title: Portal
84+
# url: /Portal
8385
- title: Position
8486
url: /Position
8587
- title: ProgressBar

src/BaseStyles.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ function BaseStyles(props: BaseStylesProps) {
3838
const {children, ...rest} = props
3939
useMouseIntent()
4040
return (
41-
<Base {...rest}>
41+
<Base {...rest} data-portal-root>
4242
<GlobalStyle />
4343
{children}
4444
</Base>

src/Portal/Portal.tsx

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import React from 'react'
2+
import {createPortal} from 'react-dom'
3+
4+
const PRIMER_PORTAL_ROOT_ID = '__primerPortalRoot__'
5+
const DEFAULT_PORTAL_CONTAINER_NAME = '__default__'
6+
7+
const portalRootRegistry: {[key: string]: Element} = {}
8+
9+
/**
10+
* Register a container to serve as a portal root.
11+
* @param root The element that will be the root for portals created in this container
12+
* @param name The name of the container, to be used with the `containerName` prop on the Portal Component.
13+
* If name is not specified, registers the default portal root.
14+
*/
15+
export function registerPortalRoot(root: Element | undefined, name?: string): void {
16+
if (root instanceof Element) {
17+
portalRootRegistry[name ?? DEFAULT_PORTAL_CONTAINER_NAME] = root
18+
} else {
19+
delete portalRootRegistry[name ?? DEFAULT_PORTAL_CONTAINER_NAME]
20+
}
21+
}
22+
23+
// Ensures that a default portal root exists and is registered. If a DOM element exists
24+
// with id __primerPortalRoot__, allow that element to serve as the default portl root.
25+
// Otherwise, create that element and attach it to the end of document.body.
26+
function ensureDefaultPortal() {
27+
if (!(DEFAULT_PORTAL_CONTAINER_NAME in portalRootRegistry)) {
28+
let defaultPortalContainer = document.getElementById(PRIMER_PORTAL_ROOT_ID)
29+
if (!(defaultPortalContainer instanceof Element)) {
30+
defaultPortalContainer = document.createElement('div')
31+
defaultPortalContainer.setAttribute('id', PRIMER_PORTAL_ROOT_ID)
32+
const suitablePortalRoot = document.querySelector('[data-portal-root]')
33+
if (suitablePortalRoot) {
34+
suitablePortalRoot.appendChild(defaultPortalContainer)
35+
} else {
36+
document.body.appendChild(defaultPortalContainer)
37+
}
38+
}
39+
portalRootRegistry[DEFAULT_PORTAL_CONTAINER_NAME] = defaultPortalContainer
40+
}
41+
}
42+
43+
export interface PortalProps {
44+
/**
45+
* Called when this portal is added to the DOM
46+
*/
47+
onMount?: () => void
48+
49+
/**
50+
* Optional. Mount this portal at the container specified
51+
* by this name. The container must be previously registered
52+
* with `registerPortal`.
53+
*/
54+
containerName?: string
55+
}
56+
57+
/**
58+
* Creates a React Portal, placing all children in a separate physical DOM root node.
59+
* @see https://reactjs.org/docs/portals.html
60+
*/
61+
export const Portal: React.FC<PortalProps> = ({children, onMount, containerName: _containerName}) => {
62+
const elementRef = React.useRef(document.createElement('div'))
63+
64+
React.useLayoutEffect(() => {
65+
let containerName = _containerName
66+
if (containerName == undefined) {
67+
containerName = DEFAULT_PORTAL_CONTAINER_NAME
68+
ensureDefaultPortal()
69+
}
70+
const parentElement = portalRootRegistry[containerName]
71+
72+
if (!parentElement) {
73+
throw new Error(
74+
`Portal container '${_containerName}' is not yet registered. Container must be registered with registerPortal before use.`
75+
)
76+
}
77+
const element = elementRef.current
78+
parentElement.appendChild(element)
79+
onMount?.()
80+
81+
return () => {
82+
parentElement.removeChild(element)
83+
}
84+
// eslint-disable-next-line react-hooks/exhaustive-deps
85+
}, [elementRef])
86+
87+
return createPortal(children, elementRef.current)
88+
}

src/Portal/index.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
import {Portal, PortalProps, registerPortalRoot} from "./Portal"
2+
3+
export default Portal
4+
export {registerPortalRoot, PortalProps}

src/__tests__/Portal.tsx

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
import Portal, {registerPortalRoot} from '../Portal/index'
2+
3+
import {render} from '@testing-library/react'
4+
import React from 'react'
5+
import BaseStyles from '../BaseStyles'
6+
7+
describe('Portal', () => {
8+
afterEach(() => {
9+
// since the registry is global, reset after each test
10+
registerPortalRoot(undefined)
11+
})
12+
it('renders a default portal into document.body (no BaseStyles present)', () => {
13+
const {baseElement} = render(<Portal>123test123</Portal>)
14+
const generatedRoot = baseElement.querySelector('#__primerPortalRoot__')
15+
expect(generatedRoot).toBeInstanceOf(HTMLElement)
16+
expect(generatedRoot?.textContent?.trim()).toEqual('123test123')
17+
baseElement.innerHTML = ''
18+
})
19+
20+
it('renders a default portal into nearest BaseStyles element', () => {
21+
const toRender = (
22+
<div id="renderedRoot">
23+
<BaseStyles>
24+
<div id="baseStylesRoot">
25+
<Portal>123test123</Portal>
26+
</div>
27+
</BaseStyles>
28+
</div>
29+
)
30+
31+
const {baseElement} = render(toRender)
32+
const baseStylesRoot = baseElement.querySelector('#baseStylesRoot')
33+
const baseStylesElement = baseStylesRoot?.parentElement
34+
const generatedRoot = baseStylesElement?.querySelector('#__primerPortalRoot__')
35+
36+
expect(baseStylesRoot).toBeInstanceOf(HTMLElement)
37+
expect(baseStylesElement).toBeInstanceOf(HTMLElement)
38+
expect(generatedRoot).toBeInstanceOf(HTMLElement)
39+
expect(generatedRoot?.textContent?.trim()).toEqual('123test123')
40+
41+
baseElement.innerHTML = ''
42+
})
43+
44+
it('renders into the custom portal root (default root name - declarative)', () => {
45+
const toRender = (
46+
<div id="renderedRoot">
47+
<div id="__primerPortalRoot__"></div>
48+
<Portal>123test123</Portal>
49+
</div>
50+
)
51+
const {baseElement} = render(toRender)
52+
const renderedRoot = baseElement.querySelector('#renderedRoot')
53+
const portalRoot = renderedRoot?.querySelector('#__primerPortalRoot__')
54+
55+
expect(portalRoot).toBeInstanceOf(HTMLElement)
56+
expect(portalRoot?.textContent?.trim()).toEqual('123test123')
57+
58+
baseElement.innerHTML = ''
59+
})
60+
61+
it('renders into the custom portal root (default root name - imperative)', () => {
62+
const portalRootJSX = <div id="myPortalRoot"></div>
63+
let {baseElement} = render(portalRootJSX)
64+
const portalRoot = baseElement.querySelector('#myPortalRoot')
65+
expect(portalRoot).toBeInstanceOf(HTMLElement)
66+
67+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
68+
registerPortalRoot(baseElement.querySelector('#myPortalRoot')!)
69+
70+
const toRender = <Portal>123test123</Portal>
71+
;({baseElement} = render(toRender))
72+
expect(portalRoot?.textContent?.trim()).toEqual('123test123')
73+
74+
baseElement.innerHTML = ''
75+
})
76+
77+
it('renders into multiple custom portal roots (named)', () => {
78+
const portalRootJSX = (
79+
<main>
80+
<div id="myPortalRoot1"></div>
81+
<div id="myPortalRoot2"></div>
82+
</main>
83+
)
84+
let {baseElement} = render(portalRootJSX)
85+
const fancyPortalRoot1 = baseElement.querySelector('#myPortalRoot1')
86+
const fancyPortalRoot2 = baseElement.querySelector('#myPortalRoot2')
87+
expect(fancyPortalRoot1).toBeInstanceOf(HTMLElement)
88+
expect(fancyPortalRoot2).toBeInstanceOf(HTMLElement)
89+
90+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
91+
registerPortalRoot(baseElement.querySelector('#myPortalRoot1')!, 'fancyPortal1')
92+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
93+
registerPortalRoot(baseElement.querySelector('#myPortalRoot2')!, 'fancyPortal2')
94+
95+
const toRender = (
96+
<>
97+
<Portal>123test123</Portal>
98+
<Portal containerName="fancyPortal1">456test456</Portal>
99+
<Portal containerName="fancyPortal2">789test789</Portal>
100+
</>
101+
)
102+
;({baseElement} = render(toRender))
103+
const generatedRoot = baseElement.querySelector('#__primerPortalRoot__')
104+
expect(generatedRoot?.textContent?.trim()).toEqual('123test123')
105+
expect(fancyPortalRoot1?.textContent?.trim()).toEqual('456test456')
106+
expect(fancyPortalRoot2?.textContent?.trim()).toEqual('789test789')
107+
108+
console.log(baseElement.outerHTML)
109+
110+
baseElement.innerHTML = ''
111+
})
112+
})

src/index.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ export {
2828
ButtonInvisible,
2929
ButtonTableList,
3030
ButtonClose,
31-
ButtonGroup,
31+
ButtonGroup
3232
} from './Button'
3333
export {default as Caret} from './Caret'
3434
export {default as CircleBadge} from './CircleBadge'
@@ -50,6 +50,7 @@ export {default as Pagehead} from './Pagehead'
5050
export {default as Pagination} from './Pagination'
5151
export {default as PointerBox} from './PointerBox'
5252
export {default as Popover} from './Popover'
53+
// export {default as Portal, PortalProps, registerPortalRoot} from './Portal'
5354
export {default as ProgressBar} from './ProgressBar'
5455
export {default as SelectMenu} from './SelectMenu'
5556
export {default as SideNav} from './SideNav'

src/stories/Button.stories.tsx

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,21 @@ export default {
3030
}
3131
],
3232
argTypes: {
33+
as: {
34+
table: {
35+
disable: true
36+
}
37+
},
38+
theme: {
39+
table: {
40+
disable: true
41+
}
42+
},
43+
sx: {
44+
table: {
45+
disable: true
46+
}
47+
},
3348
variant: {
3449
control: {
3550
type: 'radio',

0 commit comments

Comments
 (0)