UNPKG

@wordpress/interactivity

Version:

Package that provides a standard and simple way to handle the frontend interactivity of Gutenberg blocks.

66 lines (65 loc) 1.93 kB
// packages/interactivity/src/scopes.ts import { signal } from "@preact/signals"; import { getNamespace } from "./namespaces"; import { deepReadOnly, deepClone } from "./utils"; var scopeStack = []; var getScope = () => scopeStack.slice(-1)[0]; var setScope = (scope) => { scopeStack.push(scope); }; var resetScope = () => { scopeStack.pop(); }; var throwNotInScope = (method) => { throw Error( `Cannot call \`${method}()\` when there is no scope. If you are using an async function, please consider using a generator instead. If you are using some sort of async callbacks, like \`setTimeout\`, please wrap the callback with \`withScope(callback)\`.` ); }; var getContext = (namespace) => { const scope = getScope(); if (globalThis.SCRIPT_DEBUG) { if (!scope) { throwNotInScope("getContext"); } } return scope.context[namespace || getNamespace()]; }; var getElement = () => { const scope = getScope(); let deepReadOnlyOptions = {}; if (globalThis.SCRIPT_DEBUG) { if (!scope) { throwNotInScope("getElement"); } deepReadOnlyOptions = { errorMessage: "Don't mutate the attributes from `getElement`, use `data-wp-bind` to modify the attributes of an element instead." }; } const { ref, attributes } = scope; return Object.freeze({ ref: ref.current, attributes: deepReadOnly(attributes, deepReadOnlyOptions) }); }; var navigationContextSignal = signal(0); function getServerContext(namespace) { const scope = getScope(); if (globalThis.SCRIPT_DEBUG) { if (!scope) { throwNotInScope("getServerContext"); } } getServerContext.subscribe = navigationContextSignal.value; return deepClone(scope.serverContext[namespace || getNamespace()]); } getServerContext.subscribe = 0; export { getContext, getElement, getScope, getServerContext, navigationContextSignal, resetScope, setScope }; //# sourceMappingURL=scopes.js.map