|
| 1 | +import React, {useState, useRef, useEffect} from 'react' |
| 2 | +import ReactDOM from 'react-dom' |
| 3 | + |
| 4 | +/** |
| 5 | + * Utility to render a component with a shadow root. |
| 6 | + * |
| 7 | + * Based on React Shadow: https://github.com/apearce/react-shadow-root/blob/master/src/lib/ReactShadowRoot.js |
| 8 | + */ |
| 9 | + |
| 10 | +const constructableStylesheetsSupported = |
| 11 | + typeof window !== 'undefined' && |
| 12 | + window.ShadowRoot && |
| 13 | + window.ShadowRoot.prototype.hasOwnProperty('adoptedStyleSheets') && |
| 14 | + window.CSSStyleSheet && |
| 15 | + window.CSSStyleSheet.prototype.hasOwnProperty('replace') |
| 16 | + |
| 17 | +const shadowRootSupported = |
| 18 | + typeof window !== 'undefined' && |
| 19 | + window.Element && |
| 20 | + window.Element.prototype.hasOwnProperty('attachShadow') |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {object} props Properties passed to the component |
| 24 | + * @param {boolean} props.declarative When true, uses a declarative shadow root |
| 25 | + * @param {boolean} props.delegatesFocus Expands the focus behavior of elements within the shadow DOM. |
| 26 | + * @param {string} props.mode Sets the mode of the shadow root. (open or closed) |
| 27 | + * @param {CSSStyleSheet[]} props.stylesheets Takes an array of CSSStyleSheet objects for constructable stylesheets. |
| 28 | + */ |
| 29 | +const ReactShadowRoot = ({ |
| 30 | + declarative = false, |
| 31 | + delegatesFocus = false, |
| 32 | + mode = 'open', |
| 33 | + stylesheets, |
| 34 | + children, |
| 35 | +}) => { |
| 36 | + const [initialized, setInitialized] = useState(false) |
| 37 | + const placeholder = useRef(null) |
| 38 | + const shadowRootRef = useRef(null) |
| 39 | + |
| 40 | + useEffect(() => { |
| 41 | + if (placeholder.current) { |
| 42 | + shadowRootRef.current = placeholder.current.parentNode.attachShadow({ |
| 43 | + delegatesFocus, |
| 44 | + mode, |
| 45 | + }) |
| 46 | + |
| 47 | + if (stylesheets) { |
| 48 | + shadowRootRef.current.adoptedStyleSheets = stylesheets |
| 49 | + } |
| 50 | + |
| 51 | + setInitialized(true) |
| 52 | + } |
| 53 | + }, [delegatesFocus, mode, stylesheets]) |
| 54 | + |
| 55 | + if (!initialized) { |
| 56 | + if (declarative) { |
| 57 | + // @ts-ignore |
| 58 | + return ( |
| 59 | + <template ref={placeholder} shadowroot={mode}> |
| 60 | + {children} |
| 61 | + </template> |
| 62 | + ) |
| 63 | + } |
| 64 | + |
| 65 | + return <span ref={placeholder}></span> |
| 66 | + } |
| 67 | + |
| 68 | + return ReactDOM.createPortal(children, shadowRootRef.current) |
| 69 | +} |
| 70 | + |
| 71 | +ReactShadowRoot.displayName = 'ReactShadowRoot' |
| 72 | + |
| 73 | +export {ReactShadowRoot, constructableStylesheetsSupported, shadowRootSupported} |
0 commit comments