vue3-yuanma/packages/reactivity/src/effect.ts

249 lines
6.2 KiB
TypeScript
Raw Normal View History

import { TrackOpTypes, TriggerOpTypes } from './operations'
import { EMPTY_OBJ, isArray } from '@vue/shared'
2018-11-14 00:03:35 +08:00
// The main WeakMap that stores {target -> key -> dep} connections.
// Conceptually, it's easier to think of a dependency as a Dep class
// which maintains a Set of subscribers, but we simply store them as
// raw Sets to reduce memory overhead.
type Dep = Set<ReactiveEffect>
type KeyToDepMap = Map<any, Dep>
const targetMap = new WeakMap<any, KeyToDepMap>()
export interface ReactiveEffect<T = any> {
(...args: any[]): T
2019-10-22 23:26:48 +08:00
_isEffect: true
2018-11-14 00:03:35 +08:00
active: boolean
raw: () => T
2018-11-14 00:03:35 +08:00
deps: Array<Dep>
options: ReactiveEffectOptions
2018-11-14 00:03:35 +08:00
}
export interface ReactiveEffectOptions {
lazy?: boolean
2019-05-29 23:44:59 +08:00
computed?: boolean
scheduler?: (job: () => void) => void
2019-09-07 00:58:31 +08:00
onTrack?: (event: DebuggerEvent) => void
onTrigger?: (event: DebuggerEvent) => void
2019-06-06 13:25:05 +08:00
onStop?: () => void
2018-11-14 00:03:35 +08:00
}
2019-10-22 23:53:17 +08:00
export type DebuggerEvent = {
2018-11-14 00:03:35 +08:00
effect: ReactiveEffect
2019-10-22 23:26:48 +08:00
target: object
type: TrackOpTypes | TriggerOpTypes
2019-10-22 23:26:48 +08:00
key: any
} & DebuggerEventExtraInfo
export interface DebuggerEventExtraInfo {
newValue?: any
oldValue?: any
oldTarget?: Map<any, any> | Set<any>
2018-11-14 00:03:35 +08:00
}
const effectStack: ReactiveEffect[] = []
export let activeEffect: ReactiveEffect | undefined
2018-11-14 00:03:35 +08:00
export const ITERATE_KEY = Symbol(__DEV__ ? 'iterate' : '')
export const MAP_KEY_ITERATE_KEY = Symbol(__DEV__ ? 'Map key iterate' : '')
2018-11-14 00:03:35 +08:00
export function isEffect(fn: any): fn is ReactiveEffect {
2020-03-19 06:14:51 +08:00
return fn && fn._isEffect === true
}
export function effect<T = any>(
fn: () => T,
2019-06-12 00:03:50 +08:00
options: ReactiveEffectOptions = EMPTY_OBJ
): ReactiveEffect<T> {
if (isEffect(fn)) {
fn = fn.raw
2019-06-12 00:03:50 +08:00
}
const effect = createReactiveEffect(fn, options)
if (!options.lazy) {
effect()
}
return effect
}
export function stop(effect: ReactiveEffect) {
if (effect.active) {
cleanup(effect)
if (effect.options.onStop) {
effect.options.onStop()
2019-06-12 00:03:50 +08:00
}
effect.active = false
}
}
function createReactiveEffect<T = any>(
fn: (...args: any[]) => T,
2018-11-14 00:03:35 +08:00
options: ReactiveEffectOptions
): ReactiveEffect<T> {
2019-10-22 23:26:48 +08:00
const effect = function reactiveEffect(...args: unknown[]): unknown {
if (!effect.active) {
return options.scheduler ? undefined : fn(...args)
}
if (!effectStack.includes(effect)) {
cleanup(effect)
try {
enableTracking()
effectStack.push(effect)
activeEffect = effect
return fn(...args)
} finally {
effectStack.pop()
resetTracking()
activeEffect = effectStack[effectStack.length - 1]
}
}
} as ReactiveEffect
2019-10-22 23:26:48 +08:00
effect._isEffect = true
2018-11-14 00:03:35 +08:00
effect.active = true
effect.raw = fn
effect.deps = []
effect.options = options
2018-11-14 00:03:35 +08:00
return effect
}
2019-06-12 00:03:50 +08:00
function cleanup(effect: ReactiveEffect) {
2019-06-02 16:35:19 +08:00
const { deps } = effect
if (deps.length) {
for (let i = 0; i < deps.length; i++) {
deps[i].delete(effect)
}
deps.length = 0
2018-11-14 00:03:35 +08:00
}
}
2019-09-05 06:20:47 +08:00
let shouldTrack = true
const trackStack: boolean[] = []
2019-09-05 06:20:47 +08:00
export function pauseTracking() {
trackStack.push(shouldTrack)
2019-09-05 06:20:47 +08:00
shouldTrack = false
}
export function enableTracking() {
trackStack.push(shouldTrack)
2019-09-05 06:20:47 +08:00
shouldTrack = true
}
export function resetTracking() {
const last = trackStack.pop()
shouldTrack = last === undefined ? true : last
}
export function track(target: object, type: TrackOpTypes, key: unknown) {
if (!shouldTrack || activeEffect === undefined) {
return
}
let depsMap = targetMap.get(target)
if (depsMap === void 0) {
targetMap.set(target, (depsMap = new Map()))
}
let dep = depsMap.get(key)
if (dep === void 0) {
depsMap.set(key, (dep = new Set()))
}
if (!dep.has(activeEffect)) {
dep.add(activeEffect)
activeEffect.deps.push(dep)
if (__DEV__ && activeEffect.options.onTrack) {
activeEffect.options.onTrack({
effect: activeEffect,
target,
type,
key
})
2018-11-14 00:03:35 +08:00
}
}
}
export function trigger(
2019-10-22 23:26:48 +08:00
target: object,
type: TriggerOpTypes,
2019-10-22 23:26:48 +08:00
key?: unknown,
newValue?: unknown,
oldValue?: unknown,
oldTarget?: Map<unknown, unknown> | Set<unknown>
2018-11-14 00:03:35 +08:00
) {
2019-05-29 17:36:53 +08:00
const depsMap = targetMap.get(target)
if (depsMap === void 0) {
// never been tracked
return
}
const effects = new Set<ReactiveEffect>()
const computedRunners = new Set<ReactiveEffect>()
const add = (effectsToAdd: Set<ReactiveEffect> | undefined) => {
if (effectsToAdd !== void 0) {
effectsToAdd.forEach(effect => {
if (effect !== activeEffect || !shouldTrack) {
if (effect.options.computed) {
computedRunners.add(effect)
} else {
effects.add(effect)
}
} else {
// the effect mutated its own dependency during its execution.
// this can be caused by operations like foo.value++
// do not trigger or we end in an infinite loop
}
})
}
}
if (type === TriggerOpTypes.CLEAR) {
// collection being cleared
// trigger all effects for target
depsMap.forEach(add)
} else if (key === 'length' && isArray(target)) {
depsMap.forEach((dep, key) => {
if (key === 'length' || key >= (newValue as number)) {
add(dep)
}
})
2018-11-14 00:03:35 +08:00
} else {
// schedule runs for SET | ADD | DELETE
if (key !== void 0) {
add(depsMap.get(key))
2018-11-14 00:03:35 +08:00
}
// also run for iteration key on ADD | DELETE | Map.SET
const isAddOrDelete =
type === TriggerOpTypes.ADD ||
(type === TriggerOpTypes.DELETE && !isArray(target))
if (
isAddOrDelete ||
(type === TriggerOpTypes.SET && target instanceof Map)
) {
add(depsMap.get(isArray(target) ? 'length' : ITERATE_KEY))
}
if (isAddOrDelete && target instanceof Map) {
add(depsMap.get(MAP_KEY_ITERATE_KEY))
2018-11-14 00:03:35 +08:00
}
}
2018-11-14 00:03:35 +08:00
const run = (effect: ReactiveEffect) => {
if (__DEV__ && effect.options.onTrigger) {
effect.options.onTrigger({
effect,
target,
key,
type,
newValue,
oldValue,
oldTarget
})
}
if (effect.options.scheduler !== void 0) {
effect.options.scheduler(effect)
} else {
effect()
}
2018-11-14 00:03:35 +08:00
}
2018-11-14 00:03:35 +08:00
// Important: computed effects must be run first so that computed getters
// can be invalidated before any normal effects that depend on them are run.
computedRunners.forEach(run)
effects.forEach(run)
}