Skip to content

Instantly share code, notes, and snippets.

@dougwollison
Created January 25, 2022 00:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dougwollison/e8e01b1c756160be2bcbfb42f2c5b72f to your computer and use it in GitHub Desktop.
Save dougwollison/e8e01b1c756160be2bcbfb42f2c5b72f to your computer and use it in GitHub Desktop.
/**
* 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