UNPKG

@wordpress/components

Version:
1 lines • 2.67 kB
{"version":3,"file":"index.cjs","names":["createHigherOrderComponent","useState","useRef","fastDeepEqual"],"sources":["../../../src/higher-order/with-fallback-styles/index.tsx"],"sourcesContent":["import fastDeepEqual from 'fast-deep-equal/es6/index.js';\nimport { useState, useRef } from '@wordpress/element';\nimport {\n\tcreateHigherOrderComponent,\n\tuseIsomorphicLayoutEffect,\n} from '@wordpress/compose';\n\ntype Props = {\n\tnode?: HTMLElement;\n\t[ key: string ]: any;\n};\n\nexport default (\n\tmapNodeToProps: (\n\t\tnode: HTMLElement,\n\t\tprops: Props\n\t) => { [ key: string ]: any }\n) =>\n\tcreateHigherOrderComponent( ( WrappedComponent ) => {\n\t\treturn function WithFallbackStyles( props: Props ) {\n\t\t\tconst [ fallbackStyles, setFallbackStyles ] = useState<\n\t\t\t\t{ [ key: string ]: any } | undefined\n\t\t\t>( undefined );\n\n\t\t\tconst nodeRef = useRef< HTMLDivElement >( null );\n\n\t\t\t// Runs before paint, so the fallback styles apply without a flash.\n\t\t\tuseIsomorphicLayoutEffect( () => {\n\t\t\t\tconst node = props.node ?? nodeRef.current;\n\t\t\t\t// Derived from fallbackStyles: the grab is complete once every\n\t\t\t\t// mapped value has resolved to a truthy style.\n\t\t\t\tconst grabStylesCompleted =\n\t\t\t\t\t!! fallbackStyles &&\n\t\t\t\t\tObject.values( fallbackStyles ).every( Boolean );\n\n\t\t\t\tif ( node && ! grabStylesCompleted ) {\n\t\t\t\t\tconst newFallbackStyles = mapNodeToProps( node, props );\n\n\t\t\t\t\tif (\n\t\t\t\t\t\t! fastDeepEqual( newFallbackStyles, fallbackStyles )\n\t\t\t\t\t) {\n\t\t\t\t\t\tsetFallbackStyles( newFallbackStyles );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} );\n\n\t\t\tconst wrappedComponent = (\n\t\t\t\t<WrappedComponent { ...props } { ...fallbackStyles } />\n\t\t\t);\n\n\t\t\treturn props.node ? (\n\t\t\t\twrappedComponent\n\t\t\t) : (\n\t\t\t\t<div ref={ nodeRef }> { wrappedComponent } </div>\n\t\t\t);\n\t\t};\n\t}, 'withFallbackStyles' );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYA,IAAA,gCACC,oBAAA,GAKAA,mBAAAA,2BAAAA,EAA8B,qBAAsB;CACnD,OAAO,SAAS,mBAAoB,OAAe;EAClD,MAAM,CAAE,gBAAgB,sBAAA,GAAsBC,mBAAAA,SAAAA,CAE3C,KAAA,CAAU;EAEb,MAAM,WAAA,GAAUC,mBAAAA,OAAAA,CAA0B,IAAK;EAG/C,CAAA,GAAA,mBAAA,0BAAA,OAAiC;GAChC,MAAM,OAAO,MAAM,QAAQ,QAAQ;GAGnC,MAAM,sBACL,CAAC,CAAE,kBACH,OAAO,OAAQ,cAAe,CAAC,CAAC,MAAO,OAAQ;GAEhD,IAAK,QAAQ,CAAE,qBAAsB;IACpC,MAAM,oBAAoB,eAAgB,MAAM,KAAM;IAEtD,IACC,EAAA,GAAEC,6BAAAA,QAAAA,CAAe,mBAAmB,cAAe,GAEnD,kBAAmB,iBAAkB;GAEvC;EACD,CAAE;EAEF,MAAM,mBACL,iBAAA,GAAA,kBAAA,IAAA,CAAC,kBAAD;GAAkB,GAAK;GAAQ,GAAK;EAAkB,CAAA;EAGvD,OAAO,MAAM,OACZ,mBAEA,iBAAA,GAAA,kBAAA,KAAA,CAAC,OAAD;GAAK,KAAM;GAAX,UAAA;IAAqB;IAAG;IAAkB;GAAM;;CAElD;AACD,GAAG,oBAAqB"}