@wordpress/hooks
Version:
WordPress hooks library.
67 lines (66 loc) • 2.05 kB
JavaScript
// packages/hooks/src/createRunHook.ts
function createRunHook(hooks, storeKey, returnFirstArg, async) {
return function runHook(hookName, ...args) {
const hooksStore = hooks[storeKey];
if (!hooksStore[hookName]) {
hooksStore[hookName] = {
handlers: [],
runs: 0
};
}
hooksStore[hookName].runs++;
const handlers = hooksStore[hookName].handlers;
if ("production" !== process.env.NODE_ENV) {
if ("hookAdded" !== hookName && hooksStore.all) {
handlers.push(...hooksStore.all.handlers);
}
}
if (!handlers || !handlers.length) {
return returnFirstArg ? args[0] : void 0;
}
const hookInfo = {
name: hookName,
currentIndex: 0
};
async function asyncRunner() {
try {
hooksStore.__current.add(hookInfo);
let result = returnFirstArg ? args[0] : void 0;
while (hookInfo.currentIndex < handlers.length) {
const handler = handlers[hookInfo.currentIndex];
result = await handler.callback.apply(null, args);
if (returnFirstArg) {
args[0] = result;
}
hookInfo.currentIndex++;
}
return returnFirstArg ? result : void 0;
} finally {
hooksStore.__current.delete(hookInfo);
}
}
function syncRunner() {
try {
hooksStore.__current.add(hookInfo);
let result = returnFirstArg ? args[0] : void 0;
while (hookInfo.currentIndex < handlers.length) {
const handler = handlers[hookInfo.currentIndex];
result = handler.callback.apply(null, args);
if (returnFirstArg) {
args[0] = result;
}
hookInfo.currentIndex++;
}
return returnFirstArg ? result : void 0;
} finally {
hooksStore.__current.delete(hookInfo);
}
}
return (async ? asyncRunner : syncRunner)();
};
}
var createRunHook_default = createRunHook;
export {
createRunHook_default as default
};
//# sourceMappingURL=createRunHook.js.map