@muban/muban
Version:
Writing components for server-rendered HTML
69 lines (68 loc) • 3.08 kB
JavaScript
/* eslint-disable @typescript-eslint/naming-convention,@typescript-eslint/ban-types,@typescript-eslint/no-explicit-any,no-underscore-dangle */
import { pauseTracking, resetTracking } from '@vue/reactivity';
import { getCurrentComponentInstance, setCurrentComponentInstance } from '../Component';
// eslint-disable-next-line no-shadow
export var LifecycleHooks;
(function (LifecycleHooks) {
LifecycleHooks["Mounted"] = "m";
LifecycleHooks["Unmounted"] = "um";
})(LifecycleHooks || (LifecycleHooks = {}));
const ErrorTypeStrings = {
[LifecycleHooks.Mounted]: 'mounted hook',
[LifecycleHooks.Unmounted]: 'unmounted hook',
};
export function injectHook(type, hook, target = getCurrentComponentInstance(), prepend = false) {
if (target) {
// eslint-disable-next-line no-param-reassign
const hooks = target[type] || (target[type] = []);
// cache the error handling wrapper for injected hooks so the same hook
// can be properly deduped by the scheduler. "__weh" stands for "with error
// handling".
const wrappedHook = hook.__weh ||
// eslint-disable-next-line no-param-reassign
(hook.__weh = () => {
if (target.isUnmounted) {
return;
}
// disable tracking inside all lifecycle hooks
// since they can potentially be called inside effects.
pauseTracking();
// Set currentInstance during hook invocation.
// This assumes the hook does not synchronously trigger other hooks, which
// can only be false when the user does something really funky.
setCurrentComponentInstance(target);
hook();
setCurrentComponentInstance(null);
resetTracking();
});
if (prepend) {
hooks.unshift(wrappedHook);
}
else {
hooks.push(wrappedHook);
}
return wrappedHook;
}
const apiName = ErrorTypeStrings[type];
// eslint-disable-next-line no-console
console.warn(`${apiName} is called when there is no active component instance to be ` +
`associated with. ` +
`Lifecycle injection APIs can only be used during execution of setup().`);
}
export const createHook = (lifecycle) => (hook, target = getCurrentComponentInstance()) => injectHook(lifecycle, hook, target);
// export const onBeforeMount = createHook(LifecycleHooks.BEFORE_MOUNT);
export const onMounted = createHook(LifecycleHooks.Mounted);
// export const onBeforeUnmount = createHook(LifecycleHooks.BEFORE_UNMOUNT);
export const onUnmounted = createHook(LifecycleHooks.Unmounted);
// export type ErrorCapturedHook = (
// err: unknown,
// instance: ComponentPublicInstance | null,
// info: string,
// ) => boolean | void;
//
// export const onErrorCaptured = (
// hook: ErrorCapturedHook,
// target: ComponentInternalInstance | null = currentInstance,
// ) => {
// injectHook(LifecycleHooks.ERROR_CAPTURED, hook, target);
// };