@wordpress/interactivity
Version:
Package that provides a standard and simple way to handle the frontend interactivity of Gutenberg blocks.
83 lines (75 loc) • 2.4 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.proxifyStore = void 0;
var _registry = require("./registry");
var _namespaces = require("../namespaces");
var _utils = require("../utils");
/**
* Internal dependencies
*/
/**
* External dependencies
*/
/**
* Identifies the store proxies handling the root objects of each store.
*/
const storeRoots = new WeakSet();
/**
* Handlers for store proxies.
*/
const storeHandlers = {
get: (target, key, receiver) => {
const result = Reflect.get(target, key);
const ns = (0, _registry.getNamespaceFromProxy)(receiver);
/*
* Check if the proxy is the store root and no key with that name exist. In
* that case, return an empty object for the requested key.
*/
if (typeof result === 'undefined' && storeRoots.has(receiver)) {
const obj = {};
Reflect.set(target, key, obj);
return proxifyStore(ns, obj, false);
}
/*
* Check if the property is a function. If it is, add the store
* namespace to the stack and wrap the function with the current scope.
* The `withScope` util handles both synchronous functions and generator
* functions.
*/
if (typeof result === 'function') {
(0, _namespaces.setNamespace)(ns);
const scoped = (0, _utils.withScope)(result);
(0, _namespaces.resetNamespace)();
return scoped;
}
// Check if the property is an object. If it is, proxyify it.
if ((0, _utils.isPlainObject)(result) && (0, _registry.shouldProxy)(result)) {
return proxifyStore(ns, result, false);
}
return result;
}
};
/**
* Returns the proxy associated with the given store object, creating it if it
* does not exist.
*
* @param namespace The namespace that will be associated to this proxy.
* @param obj The object to proxify.
*
* @param isRoot Whether the passed object is the store root object.
* @throws Error if the object cannot be proxified. Use {@link shouldProxy} to
* check if a proxy can be created for a specific object.
*
* @return The associated proxy.
*/
const proxifyStore = (namespace, obj, isRoot = true) => {
const proxy = (0, _registry.createProxy)(namespace, obj, storeHandlers);
if (proxy && isRoot) {
storeRoots.add(proxy);
}
return proxy;
};
exports.proxifyStore = proxifyStore;
//# sourceMappingURL=store.js.map