refactor: rename reactivity package name and APIs
This commit is contained in:
138
packages/reactivity/src/baseHandlers.ts
Normal file
138
packages/reactivity/src/baseHandlers.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
import { state, immutableState, toRaw } from './index'
|
||||
import { OperationTypes } from './operations'
|
||||
import { track, trigger } from './effect'
|
||||
import { LOCKED } from './lock'
|
||||
import { isObject } from '@vue/shared'
|
||||
import { isValue } from './value'
|
||||
|
||||
const hasOwnProperty = Object.prototype.hasOwnProperty
|
||||
|
||||
const builtInSymbols = new Set(
|
||||
Object.getOwnPropertyNames(Symbol)
|
||||
.map(key => (Symbol as any)[key])
|
||||
.filter(value => typeof value === 'symbol')
|
||||
)
|
||||
|
||||
function createGetter(isImmutable: boolean) {
|
||||
return function get(target: any, key: string | symbol, receiver: any) {
|
||||
const res = Reflect.get(target, key, receiver)
|
||||
if (typeof key === 'symbol' && builtInSymbols.has(key)) {
|
||||
return res
|
||||
}
|
||||
if (isValue(res)) {
|
||||
return res.value
|
||||
}
|
||||
track(target, OperationTypes.GET, key)
|
||||
return isObject(res)
|
||||
? isImmutable
|
||||
? // need to lazy access immutable and observable here to avoid
|
||||
// circular dependency
|
||||
immutableState(res)
|
||||
: state(res)
|
||||
: res
|
||||
}
|
||||
}
|
||||
|
||||
function set(
|
||||
target: any,
|
||||
key: string | symbol,
|
||||
value: any,
|
||||
receiver: any
|
||||
): boolean {
|
||||
value = toRaw(value)
|
||||
const hadKey = hasOwnProperty.call(target, key)
|
||||
const oldValue = target[key]
|
||||
if (isValue(oldValue)) {
|
||||
oldValue.value = value
|
||||
return true
|
||||
}
|
||||
const result = Reflect.set(target, key, value, receiver)
|
||||
// don't trigger if target is something up in the prototype chain of original
|
||||
if (target === toRaw(receiver)) {
|
||||
/* istanbul ignore else */
|
||||
if (__DEV__) {
|
||||
const extraInfo = { oldValue, newValue: value }
|
||||
if (!hadKey) {
|
||||
trigger(target, OperationTypes.ADD, key, extraInfo)
|
||||
} else if (value !== oldValue) {
|
||||
trigger(target, OperationTypes.SET, key, extraInfo)
|
||||
}
|
||||
} else {
|
||||
if (!hadKey) {
|
||||
trigger(target, OperationTypes.ADD, key)
|
||||
} else if (value !== oldValue) {
|
||||
trigger(target, OperationTypes.SET, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function deleteProperty(target: any, key: string | symbol): boolean {
|
||||
const hadKey = hasOwnProperty.call(target, key)
|
||||
const oldValue = target[key]
|
||||
const result = Reflect.deleteProperty(target, key)
|
||||
if (hadKey) {
|
||||
/* istanbul ignore else */
|
||||
if (__DEV__) {
|
||||
trigger(target, OperationTypes.DELETE, key, { oldValue })
|
||||
} else {
|
||||
trigger(target, OperationTypes.DELETE, key)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function has(target: any, key: string | symbol): boolean {
|
||||
const result = Reflect.has(target, key)
|
||||
track(target, OperationTypes.HAS, key)
|
||||
return result
|
||||
}
|
||||
|
||||
function ownKeys(target: any): (string | number | symbol)[] {
|
||||
track(target, OperationTypes.ITERATE)
|
||||
return Reflect.ownKeys(target)
|
||||
}
|
||||
|
||||
export const mutableHandlers: ProxyHandler<any> = {
|
||||
get: createGetter(false),
|
||||
set,
|
||||
deleteProperty,
|
||||
has,
|
||||
ownKeys
|
||||
}
|
||||
|
||||
export const immutableHandlers: ProxyHandler<any> = {
|
||||
get: createGetter(true),
|
||||
|
||||
set(target: any, key: string | symbol, value: any, receiver: any): boolean {
|
||||
if (LOCKED) {
|
||||
if (__DEV__) {
|
||||
console.warn(
|
||||
`Set operation on key "${key as any}" failed: target is immutable.`,
|
||||
target
|
||||
)
|
||||
}
|
||||
return true
|
||||
} else {
|
||||
return set(target, key, value, receiver)
|
||||
}
|
||||
},
|
||||
|
||||
deleteProperty(target: any, key: string | symbol): boolean {
|
||||
if (LOCKED) {
|
||||
if (__DEV__) {
|
||||
console.warn(
|
||||
`Delete operation on key "${key as any}" failed: target is immutable.`,
|
||||
target
|
||||
)
|
||||
}
|
||||
return true
|
||||
} else {
|
||||
return deleteProperty(target, key)
|
||||
}
|
||||
},
|
||||
|
||||
has,
|
||||
ownKeys
|
||||
}
|
||||
239
packages/reactivity/src/collectionHandlers.ts
Normal file
239
packages/reactivity/src/collectionHandlers.ts
Normal file
@@ -0,0 +1,239 @@
|
||||
import { toRaw, state, immutableState } from './index'
|
||||
import { track, trigger } from './effect'
|
||||
import { OperationTypes } from './operations'
|
||||
import { LOCKED } from './lock'
|
||||
import { isObject } from '@vue/shared'
|
||||
|
||||
const toObservable = (value: any) => (isObject(value) ? state(value) : value)
|
||||
const toImmutable = (value: any) =>
|
||||
isObject(value) ? immutableState(value) : value
|
||||
|
||||
function get(target: any, key: any, wrap: (t: any) => any): any {
|
||||
target = toRaw(target)
|
||||
key = toRaw(key)
|
||||
const proto: any = Reflect.getPrototypeOf(target)
|
||||
track(target, OperationTypes.GET, key)
|
||||
const res = proto.get.call(target, key)
|
||||
return wrap(res)
|
||||
}
|
||||
|
||||
function has(key: any): boolean {
|
||||
const target = toRaw(this)
|
||||
key = toRaw(key)
|
||||
const proto: any = Reflect.getPrototypeOf(target)
|
||||
track(target, OperationTypes.HAS, key)
|
||||
return proto.has.call(target, key)
|
||||
}
|
||||
|
||||
function size(target: any) {
|
||||
target = toRaw(target)
|
||||
const proto = Reflect.getPrototypeOf(target)
|
||||
track(target, OperationTypes.ITERATE)
|
||||
return Reflect.get(proto, 'size', target)
|
||||
}
|
||||
|
||||
function add(value: any) {
|
||||
value = toRaw(value)
|
||||
const target = toRaw(this)
|
||||
const proto: any = Reflect.getPrototypeOf(this)
|
||||
const hadKey = proto.has.call(target, value)
|
||||
const result = proto.add.call(target, value)
|
||||
if (!hadKey) {
|
||||
/* istanbul ignore else */
|
||||
if (__DEV__) {
|
||||
trigger(target, OperationTypes.ADD, value, { value })
|
||||
} else {
|
||||
trigger(target, OperationTypes.ADD, value)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function set(key: any, value: any) {
|
||||
value = toRaw(value)
|
||||
const target = toRaw(this)
|
||||
const proto: any = Reflect.getPrototypeOf(this)
|
||||
const hadKey = proto.has.call(target, key)
|
||||
const oldValue = proto.get.call(target, key)
|
||||
const result = proto.set.call(target, key, value)
|
||||
if (value !== oldValue) {
|
||||
/* istanbul ignore else */
|
||||
if (__DEV__) {
|
||||
const extraInfo = { oldValue, newValue: value }
|
||||
if (!hadKey) {
|
||||
trigger(target, OperationTypes.ADD, key, extraInfo)
|
||||
} else {
|
||||
trigger(target, OperationTypes.SET, key, extraInfo)
|
||||
}
|
||||
} else {
|
||||
if (!hadKey) {
|
||||
trigger(target, OperationTypes.ADD, key)
|
||||
} else {
|
||||
trigger(target, OperationTypes.SET, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function deleteEntry(key: any) {
|
||||
const target = toRaw(this)
|
||||
const proto: any = Reflect.getPrototypeOf(this)
|
||||
const hadKey = proto.has.call(target, key)
|
||||
const oldValue = proto.get ? proto.get.call(target, key) : undefined
|
||||
// forward the operation before queueing reactions
|
||||
const result = proto.delete.call(target, key)
|
||||
if (hadKey) {
|
||||
/* istanbul ignore else */
|
||||
if (__DEV__) {
|
||||
trigger(target, OperationTypes.DELETE, key, { oldValue })
|
||||
} else {
|
||||
trigger(target, OperationTypes.DELETE, key)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function clear() {
|
||||
const target = toRaw(this)
|
||||
const proto: any = Reflect.getPrototypeOf(this)
|
||||
const hadItems = target.size !== 0
|
||||
const oldTarget = target instanceof Map ? new Map(target) : new Set(target)
|
||||
// forward the operation before queueing reactions
|
||||
const result = proto.clear.call(target)
|
||||
if (hadItems) {
|
||||
/* istanbul ignore else */
|
||||
if (__DEV__) {
|
||||
trigger(target, OperationTypes.CLEAR, void 0, { oldTarget })
|
||||
} else {
|
||||
trigger(target, OperationTypes.CLEAR)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function createForEach(isImmutable: boolean) {
|
||||
return function forEach(callback: Function, thisArg?: any) {
|
||||
const observed = this
|
||||
const target = toRaw(observed)
|
||||
const proto: any = Reflect.getPrototypeOf(target)
|
||||
const wrap = isImmutable ? toImmutable : toObservable
|
||||
track(target, OperationTypes.ITERATE)
|
||||
// important: create sure the callback is
|
||||
// 1. invoked with the observable map as `this` and 3rd arg
|
||||
// 2. the value received should be a corresponding observable/immutable.
|
||||
function wrappedCallback(value: any, key: any) {
|
||||
return callback.call(observed, wrap(value), wrap(key), observed)
|
||||
}
|
||||
return proto.forEach.call(target, wrappedCallback, thisArg)
|
||||
}
|
||||
}
|
||||
|
||||
function createIterableMethod(method: string | symbol, isImmutable: boolean) {
|
||||
return function(...args: any[]) {
|
||||
const target = toRaw(this)
|
||||
const proto: any = Reflect.getPrototypeOf(target)
|
||||
const isPair =
|
||||
method === 'entries' ||
|
||||
(method === Symbol.iterator && target instanceof Map)
|
||||
const innerIterator = proto[method].apply(target, args)
|
||||
const wrap = isImmutable ? toImmutable : toObservable
|
||||
track(target, OperationTypes.ITERATE)
|
||||
// return a wrapped iterator which returns observed versions of the
|
||||
// values emitted from the real iterator
|
||||
return {
|
||||
// iterator protocol
|
||||
next() {
|
||||
const { value, done } = innerIterator.next()
|
||||
return done
|
||||
? { value, done }
|
||||
: {
|
||||
value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
|
||||
done
|
||||
}
|
||||
},
|
||||
// iterable protocol
|
||||
[Symbol.iterator]() {
|
||||
return this
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function createImmutableMethod(
|
||||
method: Function,
|
||||
type: OperationTypes
|
||||
): Function {
|
||||
return function(...args: any[]) {
|
||||
if (LOCKED) {
|
||||
if (__DEV__) {
|
||||
const key = args[0] ? `on key "${args[0]}"` : ``
|
||||
console.warn(
|
||||
`${type} operation ${key}failed: target is immutable.`,
|
||||
toRaw(this)
|
||||
)
|
||||
}
|
||||
return type === OperationTypes.DELETE ? false : this
|
||||
} else {
|
||||
return method.apply(this, args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const mutableInstrumentations: any = {
|
||||
get(key: any) {
|
||||
return get(this, key, toObservable)
|
||||
},
|
||||
get size() {
|
||||
return size(this)
|
||||
},
|
||||
has,
|
||||
add,
|
||||
set,
|
||||
delete: deleteEntry,
|
||||
clear,
|
||||
forEach: createForEach(false)
|
||||
}
|
||||
|
||||
const immutableInstrumentations: any = {
|
||||
get(key: any) {
|
||||
return get(this, key, toImmutable)
|
||||
},
|
||||
get size() {
|
||||
return size(this)
|
||||
},
|
||||
has,
|
||||
add: createImmutableMethod(add, OperationTypes.ADD),
|
||||
set: createImmutableMethod(set, OperationTypes.SET),
|
||||
delete: createImmutableMethod(deleteEntry, OperationTypes.DELETE),
|
||||
clear: createImmutableMethod(clear, OperationTypes.CLEAR),
|
||||
forEach: createForEach(true)
|
||||
}
|
||||
|
||||
const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator]
|
||||
iteratorMethods.forEach(method => {
|
||||
mutableInstrumentations[method] = createIterableMethod(method, false)
|
||||
immutableInstrumentations[method] = createIterableMethod(method, true)
|
||||
})
|
||||
|
||||
function createInstrumentationGetter(instrumentations: any) {
|
||||
return function getInstrumented(
|
||||
target: any,
|
||||
key: string | symbol,
|
||||
receiver: any
|
||||
) {
|
||||
target =
|
||||
instrumentations.hasOwnProperty(key) && key in target
|
||||
? instrumentations
|
||||
: target
|
||||
return Reflect.get(target, key, receiver)
|
||||
}
|
||||
}
|
||||
|
||||
export const mutableCollectionHandlers: ProxyHandler<any> = {
|
||||
get: createInstrumentationGetter(mutableInstrumentations)
|
||||
}
|
||||
|
||||
export const immutableCollectionHandlers: ProxyHandler<any> = {
|
||||
get: createInstrumentationGetter(immutableInstrumentations)
|
||||
}
|
||||
62
packages/reactivity/src/computed.ts
Normal file
62
packages/reactivity/src/computed.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import { effect } from './index'
|
||||
import { ReactiveEffect, activeReactiveEffectStack } from './effect'
|
||||
import { knownValues } from './value'
|
||||
|
||||
export interface ComputedValue<T> {
|
||||
readonly value: T
|
||||
readonly effect: ReactiveEffect
|
||||
}
|
||||
|
||||
export function computed<T>(
|
||||
getter: () => T,
|
||||
setter?: (v: T) => void
|
||||
): ComputedValue<T> {
|
||||
let dirty: boolean = true
|
||||
let value: any = undefined
|
||||
const runner = effect(getter, {
|
||||
lazy: true,
|
||||
// mark effect as computed so that it gets priority during trigger
|
||||
computed: true,
|
||||
scheduler: () => {
|
||||
dirty = true
|
||||
}
|
||||
})
|
||||
const computedValue = {
|
||||
// expose effect so computed can be stopped
|
||||
effect: runner,
|
||||
get value() {
|
||||
if (dirty) {
|
||||
value = runner()
|
||||
dirty = false
|
||||
}
|
||||
// When computed effects are accessed in a parent effect, the parent
|
||||
// should track all the dependencies the computed property has tracked.
|
||||
// This should also apply for chained computed properties.
|
||||
trackChildRun(runner)
|
||||
return value
|
||||
},
|
||||
set value(newValue) {
|
||||
if (setter) {
|
||||
setter(newValue)
|
||||
} else {
|
||||
// TODO warn attempting to mutate readonly computed value
|
||||
}
|
||||
}
|
||||
}
|
||||
knownValues.add(computedValue)
|
||||
return computedValue
|
||||
}
|
||||
|
||||
function trackChildRun(childRunner: ReactiveEffect) {
|
||||
const parentRunner =
|
||||
activeReactiveEffectStack[activeReactiveEffectStack.length - 1]
|
||||
if (parentRunner) {
|
||||
for (let i = 0; i < childRunner.deps.length; i++) {
|
||||
const dep = childRunner.deps[i]
|
||||
if (!dep.has(parentRunner)) {
|
||||
dep.add(parentRunner)
|
||||
parentRunner.deps.push(dep)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
197
packages/reactivity/src/effect.ts
Normal file
197
packages/reactivity/src/effect.ts
Normal file
@@ -0,0 +1,197 @@
|
||||
import { OperationTypes } from './operations'
|
||||
import { Dep, targetMap } from './state'
|
||||
|
||||
export interface ReactiveEffect {
|
||||
(): any
|
||||
isEffect: true
|
||||
active: boolean
|
||||
raw: Function
|
||||
deps: Array<Dep>
|
||||
computed?: boolean
|
||||
scheduler?: Scheduler
|
||||
onTrack?: Debugger
|
||||
onTrigger?: Debugger
|
||||
onStop?: () => void
|
||||
}
|
||||
|
||||
export interface ReactiveEffectOptions {
|
||||
lazy?: boolean
|
||||
computed?: boolean
|
||||
scheduler?: Scheduler
|
||||
onTrack?: Debugger
|
||||
onTrigger?: Debugger
|
||||
onStop?: () => void
|
||||
}
|
||||
|
||||
export type Scheduler = (run: () => any) => void
|
||||
|
||||
export interface DebuggerEvent {
|
||||
effect: ReactiveEffect
|
||||
target: any
|
||||
type: OperationTypes
|
||||
key: string | symbol | undefined
|
||||
}
|
||||
|
||||
export type Debugger = (event: DebuggerEvent) => void
|
||||
|
||||
export const activeReactiveEffectStack: ReactiveEffect[] = []
|
||||
|
||||
export const ITERATE_KEY = Symbol('iterate')
|
||||
|
||||
export function createReactiveEffect(
|
||||
fn: Function,
|
||||
options: ReactiveEffectOptions
|
||||
): ReactiveEffect {
|
||||
const effect = function effect(...args): any {
|
||||
return run(effect as ReactiveEffect, fn, args)
|
||||
} as ReactiveEffect
|
||||
effect.isEffect = true
|
||||
effect.active = true
|
||||
effect.raw = fn
|
||||
effect.scheduler = options.scheduler
|
||||
effect.onTrack = options.onTrack
|
||||
effect.onTrigger = options.onTrigger
|
||||
effect.onStop = options.onStop
|
||||
effect.computed = options.computed
|
||||
effect.deps = []
|
||||
return effect
|
||||
}
|
||||
|
||||
function run(effect: ReactiveEffect, fn: Function, args: any[]): any {
|
||||
if (!effect.active) {
|
||||
return fn(...args)
|
||||
}
|
||||
if (activeReactiveEffectStack.indexOf(effect) === -1) {
|
||||
cleanup(effect)
|
||||
try {
|
||||
activeReactiveEffectStack.push(effect)
|
||||
return fn(...args)
|
||||
} finally {
|
||||
activeReactiveEffectStack.pop()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function cleanup(effect: ReactiveEffect) {
|
||||
const { deps } = effect
|
||||
if (deps.length) {
|
||||
for (let i = 0; i < deps.length; i++) {
|
||||
deps[i].delete(effect)
|
||||
}
|
||||
deps.length = 0
|
||||
}
|
||||
}
|
||||
|
||||
export function track(
|
||||
target: any,
|
||||
type: OperationTypes,
|
||||
key?: string | symbol
|
||||
) {
|
||||
const effect = activeReactiveEffectStack[activeReactiveEffectStack.length - 1]
|
||||
if (effect) {
|
||||
if (type === OperationTypes.ITERATE) {
|
||||
key = ITERATE_KEY
|
||||
}
|
||||
let depsMap = targetMap.get(target)
|
||||
if (depsMap === void 0) {
|
||||
targetMap.set(target, (depsMap = new Map()))
|
||||
}
|
||||
let dep = depsMap.get(key as string | symbol)
|
||||
if (!dep) {
|
||||
depsMap.set(key as string | symbol, (dep = new Set()))
|
||||
}
|
||||
if (!dep.has(effect)) {
|
||||
dep.add(effect)
|
||||
effect.deps.push(dep)
|
||||
if (__DEV__ && effect.onTrack) {
|
||||
effect.onTrack({
|
||||
effect,
|
||||
target,
|
||||
type,
|
||||
key
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function trigger(
|
||||
target: any,
|
||||
type: OperationTypes,
|
||||
key?: string | symbol,
|
||||
extraInfo?: any
|
||||
) {
|
||||
const depsMap = targetMap.get(target)
|
||||
if (depsMap === void 0) {
|
||||
// never been tracked
|
||||
return
|
||||
}
|
||||
const effects: Set<ReactiveEffect> = new Set()
|
||||
const computedRunners: Set<ReactiveEffect> = new Set()
|
||||
if (type === OperationTypes.CLEAR) {
|
||||
// collection being cleared, trigger all effects for target
|
||||
depsMap.forEach(dep => {
|
||||
addRunners(effects, computedRunners, dep)
|
||||
})
|
||||
} else {
|
||||
// schedule runs for SET | ADD | DELETE
|
||||
if (key !== void 0) {
|
||||
addRunners(effects, computedRunners, depsMap.get(key as string | symbol))
|
||||
}
|
||||
// also run for iteration key on ADD | DELETE
|
||||
if (type === OperationTypes.ADD || type === OperationTypes.DELETE) {
|
||||
const iterationKey = Array.isArray(target) ? 'length' : ITERATE_KEY
|
||||
addRunners(effects, computedRunners, depsMap.get(iterationKey))
|
||||
}
|
||||
}
|
||||
const run = (effect: ReactiveEffect) => {
|
||||
scheduleRun(effect, target, type, key, extraInfo)
|
||||
}
|
||||
// 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)
|
||||
}
|
||||
|
||||
function addRunners(
|
||||
effects: Set<ReactiveEffect>,
|
||||
computedRunners: Set<ReactiveEffect>,
|
||||
effectsToAdd: Set<ReactiveEffect> | undefined
|
||||
) {
|
||||
if (effectsToAdd !== void 0) {
|
||||
effectsToAdd.forEach(effect => {
|
||||
if (effect.computed) {
|
||||
computedRunners.add(effect)
|
||||
} else {
|
||||
effects.add(effect)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleRun(
|
||||
effect: ReactiveEffect,
|
||||
target: any,
|
||||
type: OperationTypes,
|
||||
key: string | symbol | undefined,
|
||||
extraInfo: any
|
||||
) {
|
||||
if (__DEV__ && effect.onTrigger) {
|
||||
effect.onTrigger(
|
||||
Object.assign(
|
||||
{
|
||||
effect,
|
||||
target,
|
||||
key,
|
||||
type
|
||||
},
|
||||
extraInfo
|
||||
)
|
||||
)
|
||||
}
|
||||
if (effect.scheduler !== void 0) {
|
||||
effect.scheduler(effect)
|
||||
} else {
|
||||
effect()
|
||||
}
|
||||
}
|
||||
164
packages/reactivity/src/index.ts
Normal file
164
packages/reactivity/src/index.ts
Normal file
@@ -0,0 +1,164 @@
|
||||
import { isObject, EMPTY_OBJ } from '@vue/shared'
|
||||
import { mutableHandlers, immutableHandlers } from './baseHandlers'
|
||||
|
||||
import {
|
||||
mutableCollectionHandlers,
|
||||
immutableCollectionHandlers
|
||||
} from './collectionHandlers'
|
||||
|
||||
import {
|
||||
targetMap,
|
||||
observedToRaw,
|
||||
rawToObserved,
|
||||
immutableToRaw,
|
||||
rawToImmutable,
|
||||
immutableValues,
|
||||
nonReactiveValues
|
||||
} from './state'
|
||||
|
||||
import {
|
||||
createReactiveEffect,
|
||||
cleanup,
|
||||
ReactiveEffect,
|
||||
ReactiveEffectOptions,
|
||||
DebuggerEvent
|
||||
} from './effect'
|
||||
|
||||
import { UnwrapValue } from './value'
|
||||
|
||||
export { ReactiveEffect, ReactiveEffectOptions, DebuggerEvent }
|
||||
export { OperationTypes } from './operations'
|
||||
export { computed, ComputedValue } from './computed'
|
||||
export { lock, unlock } from './lock'
|
||||
export { value, isValue, Value, UnwrapValue } from './value'
|
||||
|
||||
const collectionTypes: Set<any> = new Set([Set, Map, WeakMap, WeakSet])
|
||||
const observableValueRE = /^\[object (?:Object|Array|Map|Set|WeakMap|WeakSet)\]$/
|
||||
|
||||
const canObserve = (value: any): boolean => {
|
||||
return (
|
||||
!value._isVue &&
|
||||
!value._isVNode &&
|
||||
observableValueRE.test(Object.prototype.toString.call(value)) &&
|
||||
!nonReactiveValues.has(value)
|
||||
)
|
||||
}
|
||||
|
||||
type ObservableFactory = <T>(target?: T) => UnwrapValue<T>
|
||||
|
||||
export const state = ((target: any = {}): any => {
|
||||
// if trying to observe an immutable proxy, return the immutable version.
|
||||
if (immutableToRaw.has(target)) {
|
||||
return target
|
||||
}
|
||||
// target is explicitly marked as immutable by user
|
||||
if (immutableValues.has(target)) {
|
||||
return immutableState(target)
|
||||
}
|
||||
return createObservable(
|
||||
target,
|
||||
rawToObserved,
|
||||
observedToRaw,
|
||||
mutableHandlers,
|
||||
mutableCollectionHandlers
|
||||
)
|
||||
}) as ObservableFactory
|
||||
|
||||
export const immutableState = ((target: any = {}): any => {
|
||||
// value is a mutable observable, retrive its original and return
|
||||
// a readonly version.
|
||||
if (observedToRaw.has(target)) {
|
||||
target = observedToRaw.get(target)
|
||||
}
|
||||
return createObservable(
|
||||
target,
|
||||
rawToImmutable,
|
||||
immutableToRaw,
|
||||
immutableHandlers,
|
||||
immutableCollectionHandlers
|
||||
)
|
||||
}) as ObservableFactory
|
||||
|
||||
function createObservable(
|
||||
target: any,
|
||||
toProxy: WeakMap<any, any>,
|
||||
toRaw: WeakMap<any, any>,
|
||||
baseHandlers: ProxyHandler<any>,
|
||||
collectionHandlers: ProxyHandler<any>
|
||||
) {
|
||||
if (!isObject(target)) {
|
||||
if (__DEV__) {
|
||||
console.warn(`value is not observable: ${String(target)}`)
|
||||
}
|
||||
return target
|
||||
}
|
||||
// target already has corresponding Proxy
|
||||
let observed = toProxy.get(target)
|
||||
if (observed !== void 0) {
|
||||
return observed
|
||||
}
|
||||
// target is already a Proxy
|
||||
if (toRaw.has(target)) {
|
||||
return target
|
||||
}
|
||||
// only a whitelist of value types can be observed.
|
||||
if (!canObserve(target)) {
|
||||
return target
|
||||
}
|
||||
const handlers = collectionTypes.has(target.constructor)
|
||||
? collectionHandlers
|
||||
: baseHandlers
|
||||
observed = new Proxy(target, handlers)
|
||||
toProxy.set(target, observed)
|
||||
toRaw.set(observed, target)
|
||||
if (!targetMap.has(target)) {
|
||||
targetMap.set(target, new Map())
|
||||
}
|
||||
return observed
|
||||
}
|
||||
|
||||
export function effect(
|
||||
fn: Function,
|
||||
options: ReactiveEffectOptions = EMPTY_OBJ
|
||||
): ReactiveEffect {
|
||||
if ((fn as ReactiveEffect).isEffect) {
|
||||
fn = (fn as ReactiveEffect).raw
|
||||
}
|
||||
const effect = createReactiveEffect(fn, options)
|
||||
if (!options.lazy) {
|
||||
effect()
|
||||
}
|
||||
return effect
|
||||
}
|
||||
|
||||
export function stop(effect: ReactiveEffect) {
|
||||
if (effect.active) {
|
||||
cleanup(effect)
|
||||
if (effect.onStop) {
|
||||
effect.onStop()
|
||||
}
|
||||
effect.active = false
|
||||
}
|
||||
}
|
||||
|
||||
export function isState(value: any): boolean {
|
||||
return observedToRaw.has(value) || immutableToRaw.has(value)
|
||||
}
|
||||
|
||||
export function isImmutableState(value: any): boolean {
|
||||
return immutableToRaw.has(value)
|
||||
}
|
||||
|
||||
export function toRaw<T>(observed: T): T {
|
||||
return observedToRaw.get(observed) || immutableToRaw.get(observed) || observed
|
||||
}
|
||||
|
||||
export function markImmutable<T>(value: T): T {
|
||||
immutableValues.add(value)
|
||||
return value
|
||||
}
|
||||
|
||||
export function markNonReactive<T>(value: T): T {
|
||||
nonReactiveValues.add(value)
|
||||
return value
|
||||
}
|
||||
10
packages/reactivity/src/lock.ts
Normal file
10
packages/reactivity/src/lock.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
// global immutability lock
|
||||
export let LOCKED = true
|
||||
|
||||
export function lock() {
|
||||
LOCKED = true
|
||||
}
|
||||
|
||||
export function unlock() {
|
||||
LOCKED = false
|
||||
}
|
||||
11
packages/reactivity/src/operations.ts
Normal file
11
packages/reactivity/src/operations.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
export const enum OperationTypes {
|
||||
// using literal strings instead of numbers so that it's easier to inspect
|
||||
// debugger events
|
||||
SET = 'set',
|
||||
ADD = 'add',
|
||||
DELETE = 'delete',
|
||||
CLEAR = 'clear',
|
||||
GET = 'get',
|
||||
HAS = 'has',
|
||||
ITERATE = 'iterate'
|
||||
}
|
||||
20
packages/reactivity/src/state.ts
Normal file
20
packages/reactivity/src/state.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { ReactiveEffect } from './effect'
|
||||
|
||||
// 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.
|
||||
export type Dep = Set<ReactiveEffect>
|
||||
export type KeyToDepMap = Map<string | symbol, Dep>
|
||||
export const targetMap: WeakMap<any, KeyToDepMap> = new WeakMap()
|
||||
|
||||
// WeakMaps that store {raw <-> observed} pairs.
|
||||
export const rawToObserved: WeakMap<any, any> = new WeakMap()
|
||||
export const observedToRaw: WeakMap<any, any> = new WeakMap()
|
||||
export const rawToImmutable: WeakMap<any, any> = new WeakMap()
|
||||
export const immutableToRaw: WeakMap<any, any> = new WeakMap()
|
||||
|
||||
// WeakSets for values that are marked immutable or non-reactive during
|
||||
// observable creation.
|
||||
export const immutableValues: WeakSet<any> = new WeakSet()
|
||||
export const nonReactiveValues: WeakSet<any> = new WeakSet()
|
||||
118
packages/reactivity/src/value.ts
Normal file
118
packages/reactivity/src/value.ts
Normal file
@@ -0,0 +1,118 @@
|
||||
import { track, trigger } from './effect'
|
||||
import { OperationTypes } from './operations'
|
||||
import { isObject } from '@vue/shared'
|
||||
import { state } from './index'
|
||||
|
||||
export const knownValues = new WeakSet()
|
||||
|
||||
export interface Value<T> {
|
||||
value: T
|
||||
}
|
||||
|
||||
const convert = (val: any): any => (isObject(val) ? state(val) : val)
|
||||
|
||||
export function value<T>(raw: T): Value<T> {
|
||||
raw = convert(raw)
|
||||
const v = {
|
||||
get value() {
|
||||
track(v, OperationTypes.GET, '')
|
||||
return raw
|
||||
},
|
||||
set value(newVal) {
|
||||
raw = convert(newVal)
|
||||
trigger(v, OperationTypes.SET, '')
|
||||
}
|
||||
}
|
||||
knownValues.add(v)
|
||||
return v
|
||||
}
|
||||
|
||||
export function isValue(v: any): v is Value<any> {
|
||||
return knownValues.has(v)
|
||||
}
|
||||
|
||||
type BailTypes =
|
||||
| Function
|
||||
| Map<any, any>
|
||||
| Set<any>
|
||||
| WeakMap<any, any>
|
||||
| WeakSet<any>
|
||||
|
||||
// Recursively unwraps nested value bindings.
|
||||
// Unfortunately TS cannot do recursive types, but this should be enough for
|
||||
// practical use cases...
|
||||
export type UnwrapValue<T> = T extends Value<infer V>
|
||||
? UnwrapValue2<V>
|
||||
: T extends Array<infer V>
|
||||
? Array<UnwrapValue2<V>>
|
||||
: T extends BailTypes
|
||||
? T // bail out on types that shouldn't be unwrapped
|
||||
: T extends object ? { [K in keyof T]: UnwrapValue2<T[K]> } : T
|
||||
|
||||
type UnwrapValue2<T> = T extends Value<infer V>
|
||||
? UnwrapValue3<V>
|
||||
: T extends Array<infer V>
|
||||
? Array<UnwrapValue3<V>>
|
||||
: T extends BailTypes
|
||||
? T
|
||||
: T extends object ? { [K in keyof T]: UnwrapValue3<T[K]> } : T
|
||||
|
||||
type UnwrapValue3<T> = T extends Value<infer V>
|
||||
? UnwrapValue4<V>
|
||||
: T extends Array<infer V>
|
||||
? Array<UnwrapValue4<V>>
|
||||
: T extends BailTypes
|
||||
? T
|
||||
: T extends object ? { [K in keyof T]: UnwrapValue4<T[K]> } : T
|
||||
|
||||
type UnwrapValue4<T> = T extends Value<infer V>
|
||||
? UnwrapValue5<V>
|
||||
: T extends Array<infer V>
|
||||
? Array<UnwrapValue5<V>>
|
||||
: T extends BailTypes
|
||||
? T
|
||||
: T extends object ? { [K in keyof T]: UnwrapValue5<T[K]> } : T
|
||||
|
||||
type UnwrapValue5<T> = T extends Value<infer V>
|
||||
? UnwrapValue6<V>
|
||||
: T extends Array<infer V>
|
||||
? Array<UnwrapValue6<V>>
|
||||
: T extends BailTypes
|
||||
? T
|
||||
: T extends object ? { [K in keyof T]: UnwrapValue6<T[K]> } : T
|
||||
|
||||
type UnwrapValue6<T> = T extends Value<infer V>
|
||||
? UnwrapValue7<V>
|
||||
: T extends Array<infer V>
|
||||
? Array<UnwrapValue7<V>>
|
||||
: T extends BailTypes
|
||||
? T
|
||||
: T extends object ? { [K in keyof T]: UnwrapValue7<T[K]> } : T
|
||||
|
||||
type UnwrapValue7<T> = T extends Value<infer V>
|
||||
? UnwrapValue8<V>
|
||||
: T extends Array<infer V>
|
||||
? Array<UnwrapValue8<V>>
|
||||
: T extends BailTypes
|
||||
? T
|
||||
: T extends object ? { [K in keyof T]: UnwrapValue8<T[K]> } : T
|
||||
|
||||
type UnwrapValue8<T> = T extends Value<infer V>
|
||||
? UnwrapValue9<V>
|
||||
: T extends Array<infer V>
|
||||
? Array<UnwrapValue9<V>>
|
||||
: T extends BailTypes
|
||||
? T
|
||||
: T extends object ? { [K in keyof T]: UnwrapValue9<T[K]> } : T
|
||||
|
||||
type UnwrapValue9<T> = T extends Value<infer V>
|
||||
? UnwrapValue10<V>
|
||||
: T extends Array<infer V>
|
||||
? Array<UnwrapValue10<V>>
|
||||
: T extends BailTypes
|
||||
? T
|
||||
: T extends object ? { [K in keyof T]: UnwrapValue10<T[K]> } : T
|
||||
|
||||
type UnwrapValue10<T> = T extends Value<infer V>
|
||||
? V // stop recursion
|
||||
: T
|
||||
Reference in New Issue
Block a user