UNPKG

@dark-engine/core

Version:

The lightweight and powerful UI rendering engine without dependencies and written in TypeScript (Browser, Node.js, Android, iOS, Windows, Linux, macOS)

54 lines (53 loc) 1.73 kB
import { __useCursor as useCursor } from '../internal'; import { EFFECT_HOST_MASK } from '../constants'; import { detectIsFiberAlive } from '../walk'; import { detectIsFunction } from '../utils'; import { useMemo } from '../use-memo'; import { $$scope } from '../scope'; const $$effect = Symbol('effect'); function createEffect(type) { return (effect, deps = [{}]) => { const $scope = $$scope(); const cursor = useCursor(); const scope = useMemo(() => ({ token: $$effect, cleanup: undefined }), []); cursor.markHost(EFFECT_HOST_MASK); useMemo(() => { const run = () => { scope.cleanup = effect(); if (type === EffectType.ASYNC && detectIsFunction(scope.cleanup) && !detectIsFiberAlive(cursor)) { scope.cleanup(); } }; switch (type) { case EffectType.INSERTION: $scope.addInsertionEffect(run); break; case EffectType.LAYOUT: $scope.addLayoutEffect(run); break; case EffectType.ASYNC: $scope.addAsyncEffect(run); break; default: break; } detectIsFunction(scope.cleanup) && scope.cleanup(); return null; }, deps); }; } function dropEffects(hook) { const { values } = hook; for (const { value } of values) { value?.token === $$effect && detectIsFunction(value.cleanup) && value.cleanup(); } } export var EffectType; (function (EffectType) { EffectType['ASYNC'] = 'ASYNC'; EffectType['LAYOUT'] = 'LAYOUT'; EffectType['INSERTION'] = 'INSERTION'; })(EffectType || (EffectType = {})); const useEffect = createEffect(EffectType.ASYNC); export { useEffect, dropEffects, createEffect }; //# sourceMappingURL=use-effect.js.map