Skip to content

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
merged 16 commits into from
Feb 23, 2021
Merged
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
21 changes: 21 additions & 0 deletions .vscode/launch.json
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"
}
}
]
}
71 changes: 71 additions & 0 deletions docs/content/Portal.mdx
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.

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. |
2 changes: 2 additions & 0 deletions docs/src/@primer/gatsby-theme-doctocat/nav.yml
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@
url: /PointerBox
- title: Popover
url: /Popover
# - title: Portal
# url: /Portal
- title: Position
url: /Position
- title: ProgressBar
Expand Down
2 changes: 1 addition & 1 deletion src/BaseStyles.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ function BaseStyles(props: BaseStylesProps) {
const {children, ...rest} = props
useMouseIntent()
return (
<Base {...rest}>
<Base {...rest} data-portal-root>
<GlobalStyle />
{children}
</Base>
Expand Down
88 changes: 88 additions & 0 deletions src/Portal/Portal.tsx
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)
}
4 changes: 4 additions & 0 deletions src/Portal/index.ts
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}
112 changes: 112 additions & 0 deletions src/__tests__/Portal.tsx
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 = ''
})
})
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export {
ButtonInvisible,
ButtonTableList,
ButtonClose,
ButtonGroup,
ButtonGroup
} from './Button'
export {default as Caret} from './Caret'
export {default as CircleBadge} from './CircleBadge'
Expand All @@ -50,6 +50,7 @@ export {default as Pagehead} from './Pagehead'
export {default as Pagination} from './Pagination'
export {default as PointerBox} from './PointerBox'
export {default as Popover} from './Popover'
// export {default as Portal, PortalProps, registerPortalRoot} from './Portal'
export {default as ProgressBar} from './ProgressBar'
export {default as SelectMenu} from './SelectMenu'
export {default as SideNav} from './SideNav'
Expand Down
15 changes: 15 additions & 0 deletions src/stories/Button.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,21 @@ export default {
}
],
argTypes: {
as: {
table: {
disable: true
}
},
theme: {
table: {
disable: true
}
},
sx: {
table: {
disable: true
}
},
variant: {
control: {
type: 'radio',
Expand Down
Loading