UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

65 lines (64 loc) 2.77 kB
"use client"; import _extends from "@babel/runtime/helpers/esm/extends"; import _defineProperty from "@babel/runtime/helpers/esm/defineProperty"; import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; const _excluded = ["innerRef", "className", "style", "children"]; function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } import React, { useContext, useEffect, useMemo, useRef } from 'react'; import { createPortal } from 'react-dom'; import classnames from 'classnames'; import IsolatedStyleScope, { IsolatedStyleScopeContext } from '../../shared/IsolatedStyleScope'; function PortalRoot(_ref) { let { innerRef, className, style, children } = _ref, rest = _objectWithoutProperties(_ref, _excluded); const { style: scopeStyle } = useContext(IsolatedStyleScopeContext) || {}; const id = 'eufemia-portal-root'; const initialElement = useMemo(() => getOrCreatePortalElement(id), []); const localRef = useRef(initialElement); useEffect(() => { const elem = getOrCreatePortalElement(id); localRef.current = elem; if (innerRef) { if (typeof innerRef === 'function') { innerRef(elem); } else { const ref = innerRef; ref.current = elem; } } }, [id, innerRef]); if (!localRef.current) { return null; } return createPortal(React.createElement(IsolatedStyleScope, { scopeHash: "auto", disableCoreStyleWrapper: true, uniqueKey: false }, React.createElement("div", _extends({ className: classnames('dnb-core-style', className), style: _objectSpread(_objectSpread({}, scopeStyle), style) }, rest), children)), localRef.current); } export function getOrCreatePortalElement(id) { if (typeof window === 'undefined') { return null; } let elem = document.getElementById(id); if (!elem) { elem = document.createElement('div'); elem.setAttribute('id', id); elem.setAttribute('role', 'presentation'); document.body.insertBefore(elem, document.body.firstChild); } return elem; } export default PortalRoot; //# sourceMappingURL=PortalRoot.js.map