diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 00000000000..08483c0c807 --- /dev/null +++ b/.vscode/launch.json @@ -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" + } + } + ] +} diff --git a/docs/content/Portal.mdx b/docs/content/Portal.mdx new file mode 100644 index 00000000000..d71897ff7f1 --- /dev/null +++ b/docs/content/Portal.mdx @@ -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 `` 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 `` 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 `` element will not apply to the portaled content unless the portal root is a descendent of a `` element. + +Also, as `` affects the _React_ context, which applies to the logical React component hierarchy, the portal root is not required to be a child of a `` 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 `` with a `name` prop matching the one you registered. + +## Default example + +```jsx + + 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. + +``` + +## Example: custom portal root + +```html + +
+``` +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") +// ... + +
This div will be rendered into the element registered above.
+ +
+ This div will be rendered into the default + portal root created at document.body +
+
+
+``` + +## 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. | diff --git a/docs/src/@primer/gatsby-theme-doctocat/nav.yml b/docs/src/@primer/gatsby-theme-doctocat/nav.yml index 9a5ab38a2b6..7fcc9bc040c 100644 --- a/docs/src/@primer/gatsby-theme-doctocat/nav.yml +++ b/docs/src/@primer/gatsby-theme-doctocat/nav.yml @@ -80,6 +80,8 @@ url: /PointerBox - title: Popover url: /Popover + # - title: Portal + # url: /Portal - title: Position url: /Position - title: ProgressBar diff --git a/src/BaseStyles.tsx b/src/BaseStyles.tsx index 9e0fb178a1c..c520b1d9654 100644 --- a/src/BaseStyles.tsx +++ b/src/BaseStyles.tsx @@ -38,7 +38,7 @@ function BaseStyles(props: BaseStylesProps) { const {children, ...rest} = props useMouseIntent() return ( - + {children} diff --git a/src/Portal/Portal.tsx b/src/Portal/Portal.tsx new file mode 100644 index 00000000000..6ea3c405395 --- /dev/null +++ b/src/Portal/Portal.tsx @@ -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 = ({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) +} diff --git a/src/Portal/index.ts b/src/Portal/index.ts new file mode 100644 index 00000000000..b644e02340a --- /dev/null +++ b/src/Portal/index.ts @@ -0,0 +1,4 @@ +import {Portal, PortalProps, registerPortalRoot} from "./Portal" + +export default Portal +export {registerPortalRoot, PortalProps} \ No newline at end of file diff --git a/src/__tests__/Portal.tsx b/src/__tests__/Portal.tsx new file mode 100644 index 00000000000..6055c19e4ad --- /dev/null +++ b/src/__tests__/Portal.tsx @@ -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(123test123) + 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 = ( +
+ +
+ 123test123 +
+
+
+ ) + + 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 = ( +
+
+ 123test123 +
+ ) + 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 =
+ 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 = 123test123 + ;({baseElement} = render(toRender)) + expect(portalRoot?.textContent?.trim()).toEqual('123test123') + + baseElement.innerHTML = '' + }) + + it('renders into multiple custom portal roots (named)', () => { + const portalRootJSX = ( +
+
+
+
+ ) + 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 = ( + <> + 123test123 + 456test456 + 789test789 + + ) + ;({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 = '' + }) +}) diff --git a/src/index.ts b/src/index.ts index 721ecefbb3c..3a1b82eaf21 100644 --- a/src/index.ts +++ b/src/index.ts @@ -28,7 +28,7 @@ export { ButtonInvisible, ButtonTableList, ButtonClose, - ButtonGroup, + ButtonGroup } from './Button' export {default as Caret} from './Caret' export {default as CircleBadge} from './CircleBadge' @@ -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' diff --git a/src/stories/Button.stories.tsx b/src/stories/Button.stories.tsx index 3acdd5c23d4..1805d8c0715 100644 --- a/src/stories/Button.stories.tsx +++ b/src/stories/Button.stories.tsx @@ -30,6 +30,21 @@ export default { } ], argTypes: { + as: { + table: { + disable: true + } + }, + theme: { + table: { + disable: true + } + }, + sx: { + table: { + disable: true + } + }, variant: { control: { type: 'radio', diff --git a/src/stories/Portal.stories.tsx b/src/stories/Portal.stories.tsx new file mode 100644 index 00000000000..a84646adf58 --- /dev/null +++ b/src/stories/Portal.stories.tsx @@ -0,0 +1,111 @@ +/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ +import React from 'react' +import {Meta} from '@storybook/react' + +import {BaseStyles, Box} from '..' +import Portal, {registerPortalRoot} from '../Portal' + +export default { + title: 'Generic behaviors/Portal', + component: Portal, + decorators: [ + Story => { + // Since portal roots are registered globally, we need this line so that each storybook + // story works in isolation. + registerPortalRoot(undefined) + return ( + + + + ) + } + ] +} as Meta + +export const defaultPortal = () => ( + <> + Root position + + Outer container + + Inner container + + Portaled content rendered at <BaseStyles> root. + + + + +) + +export const customPortalRootById = () => ( + <> + Root position + + Outer container + + Inner container + Portaled content rendered at the outer container. + + + +) + +export const CustomPortalRootByRegistration: React.FC> = () => { + const outerContainerRef = React.useRef(null) + const [mounted, setMounted] = React.useState(false) + React.useEffect(() => { + if (outerContainerRef.current instanceof HTMLElement) { + registerPortalRoot(outerContainerRef.current) + setMounted(true) + } + }, [outerContainerRef]) + return ( + <> + Root position + + {mounted && ( + <> + Outer container + + Inner container + Portaled content rendered at the outer container. + + + )} + + + ) +} + +export const MultiplePortalRoots: React.FC> = () => { + const outerContainerRef = React.useRef(null) + const innerContainerRef = React.useRef(null) + const [mounted, setMounted] = React.useState(false) + React.useEffect(() => { + if (outerContainerRef.current instanceof HTMLElement && innerContainerRef.current instanceof HTMLElement) { + registerPortalRoot(outerContainerRef.current, 'outer') + registerPortalRoot(innerContainerRef.current, 'inner') + setMounted(true) + } + }, [outerContainerRef]) + return ( + <> + Root position + + Outer container + + {mounted && ( + <> + Portaled content rendered at the outer container. + Portaled content rendered at the end of the inner container. + + Portaled content rendered at <BaseStyles> root. + + + )} + Inner container + + + + ) +}