UNPKG

@atlaskit/portal

Version:

A wrapper for rendering components in React portals.

61 lines (60 loc) 2.35 kB
import React, { Suspense, useState } from 'react'; import { createPortal } from 'react-dom'; import { ThemeProvider, useColorMode } from '@atlaskit/app-provider'; import { fg } from '@atlaskit/platform-feature-flags'; import { useIsomorphicLayoutEffect } from '../hooks/use-isomorphic-layout-effect'; import { createAtlaskitPortal, createPortalParent, removePortalParent } from '../utils/portal-dom-utils'; export default function InternalPortalNew(props) { const { zIndex, children, isClosed } = props; const [atlaskitPortal, setAtlaskitPortal] = useState(null); const colorMode = useColorMode(); useIsomorphicLayoutEffect(() => { if (fg('import_into_jsm_in_template_gallery_killswitch')) { if (!isClosed) { let tempPortalContainer = createAtlaskitPortal(zIndex); setAtlaskitPortal(tempPortalContainer); const portalParent = createPortalParent(); if (!tempPortalContainer || !portalParent) { return; } portalParent.appendChild(tempPortalContainer); return () => { if (portalParent) { portalParent.removeChild(tempPortalContainer); !portalParent.hasChildNodes() && removePortalParent(portalParent); } setAtlaskitPortal(null); }; } } else { const tempPortalContainer = createAtlaskitPortal(zIndex); setAtlaskitPortal(tempPortalContainer); const portalParent = createPortalParent(); if (!tempPortalContainer || !portalParent) { return; } portalParent.appendChild(tempPortalContainer); return () => { if (tempPortalContainer) { portalParent.removeChild(tempPortalContainer); } setAtlaskitPortal(null); }; } }, [zIndex, isClosed, fg]); /** * We wrap portal children with a Suspense boundary because in React 18 concurrent, * if you suspend from _within_ a portal to a Suspense boundary _outside_ the portal, * our portal gets in an infinite loop of rendering. */ const suspendedChildren = /*#__PURE__*/React.createElement(Suspense, { fallback: null }, colorMode ? /*#__PURE__*/React.createElement(ThemeProvider, { defaultColorMode: colorMode }, children) : children); return atlaskitPortal ? /*#__PURE__*/createPortal(suspendedChildren, atlaskitPortal) : null; }