Created
January 25, 2022 00:47
-
-
Save dougwollison/e8e01b1c756160be2bcbfb42f2c5b72f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Proxy for the `wp` object, with fallback | |
* to experimental names and error throwing | |
* when accessing a non-existent item (intended | |
* for debugging purposes). | |
*/ | |
export default new Proxy( {}, { | |
get( cache, moduleName, reciever ) { | |
if ( typeof cache[ moduleName ] === 'undefined' ) { | |
if ( typeof wp[ moduleName ] === 'undefined' ) { | |
throw `WordPress module not found: wp.${ moduleName }`; | |
} | |
const moduleProxy = new Proxy( {}, { | |
get( moduleCache, componentName ) { | |
if ( typeof moduleCache[ componentName ] === 'undefined' ) { | |
// ensure component name starts with upppercase when | |
// prefixing __experimental, for stuff like hooks | |
const experimentalName = '__experimental' + | |
componentName.charAt( 0 ).toUpperCase() + | |
componentName.slice( 1 ); | |
const componentMatch = wp[ moduleName ][ componentName ] || wp[ moduleName ][ experimentalName ]; | |
if ( ! componentMatch ) { | |
throw `Component not found: wp.${ moduleName }.${ componentName }`; | |
} | |
moduleCache[ componentName ] = componentMatch; | |
} | |
return moduleCache[ componentName ]; | |
}, | |
} ); | |
cache[ moduleName ] = moduleProxy; | |
} | |
return cache[ moduleName ]; | |
}, | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment