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

264 lines
7.5 KiB
TypeScript

import { toRaw, reactive, readonly } from './reactive'
import { track, trigger } from './effect'
import { OperationTypes } from './operations'
import { LOCKED } from './lock'
import { isObject, capitalize, hasOwn, hasChanged } from '@vue/shared'
export type CollectionTypes = IterableCollections | WeakCollections
type IterableCollections = Map<any, any> | Set<any>
type WeakCollections = WeakMap<any, any> | WeakSet<any>
type MapTypes = Map<any, any> | WeakMap<any, any>
type SetTypes = Set<any> | WeakSet<any>
const toReactive = <T extends unknown>(value: T): T =>
isObject(value) ? reactive(value) : value
const toReadonly = <T extends unknown>(value: T): T =>
isObject(value) ? readonly(value) : value
const getProto = <T extends CollectionTypes>(v: T): any =>
Reflect.getPrototypeOf(v)
function get(
target: MapTypes,
key: unknown,
wrap: typeof toReactive | typeof toReadonly
) {
target = toRaw(target)
key = toRaw(key)
track(target, OperationTypes.GET, key)
return wrap(getProto(target).get.call(target, key))
}
function has(this: CollectionTypes, key: unknown): boolean {
const target = toRaw(this)
key = toRaw(key)
track(target, OperationTypes.HAS, key)
return getProto(target).has.call(target, key)
}
function size(target: IterableCollections) {
target = toRaw(target)
track(target, OperationTypes.ITERATE)
return Reflect.get(getProto(target), 'size', target)
}
function add(this: SetTypes, value: unknown) {
value = toRaw(value)
const target = toRaw(this)
const proto = getProto(target)
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, { newValue: value })
} else {
trigger(target, OperationTypes.ADD, value)
}
}
return result
}
function set(this: MapTypes, key: unknown, value: unknown) {
value = toRaw(value)
const target = toRaw(this)
const proto = getProto(target)
const hadKey = proto.has.call(target, key)
const oldValue = proto.get.call(target, key)
const result = proto.set.call(target, key, value)
/* istanbul ignore else */
if (__DEV__) {
const extraInfo = { oldValue, newValue: value }
if (!hadKey) {
trigger(target, OperationTypes.ADD, key, extraInfo)
} else if (hasChanged(value, oldValue)) {
trigger(target, OperationTypes.SET, key, extraInfo)
}
} else {
if (!hadKey) {
trigger(target, OperationTypes.ADD, key)
} else if (hasChanged(value, oldValue)) {
trigger(target, OperationTypes.SET, key)
}
}
return result
}
function deleteEntry(this: CollectionTypes, key: unknown) {
const target = toRaw(this)
const proto = getProto(target)
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(this: IterableCollections) {
const target = toRaw(this)
const hadItems = target.size !== 0
const oldTarget = __DEV__
? target instanceof Map
? new Map(target)
: new Set(target)
: undefined
// forward the operation before queueing reactions
const result = getProto(target).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(isReadonly: boolean) {
return function forEach(
this: IterableCollections,
callback: Function,
thisArg?: unknown
) {
const observed = this
const target = toRaw(observed)
const wrap = isReadonly ? toReadonly : toReactive
track(target, OperationTypes.ITERATE)
// important: create sure the callback is
// 1. invoked with the reactive map as `this` and 3rd arg
// 2. the value received should be a corresponding reactive/readonly.
function wrappedCallback(value: unknown, key: unknown) {
return callback.call(observed, wrap(value), wrap(key), observed)
}
return getProto(target).forEach.call(target, wrappedCallback, thisArg)
}
}
function createIterableMethod(method: string | symbol, isReadonly: boolean) {
return function(this: IterableCollections, ...args: unknown[]) {
const target = toRaw(this)
const isPair =
method === 'entries' ||
(method === Symbol.iterator && target instanceof Map)
const innerIterator = getProto(target)[method].apply(target, args)
const wrap = isReadonly ? toReadonly : toReactive
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 createReadonlyMethod(
method: Function,
type: OperationTypes
): Function {
return function(this: CollectionTypes, ...args: unknown[]) {
if (LOCKED) {
if (__DEV__) {
const key = args[0] ? `on key "${args[0]}" ` : ``
console.warn(
`${capitalize(type)} operation ${key}failed: target is readonly.`,
toRaw(this)
)
}
return type === OperationTypes.DELETE ? false : this
} else {
return method.apply(this, args)
}
}
}
const mutableInstrumentations: Record<string, Function> = {
get(this: MapTypes, key: unknown) {
return get(this, key, toReactive)
},
get size(this: IterableCollections) {
return size(this)
},
has,
add,
set,
delete: deleteEntry,
clear,
forEach: createForEach(false)
}
const readonlyInstrumentations: Record<string, Function> = {
get(this: MapTypes, key: unknown) {
return get(this, key, toReadonly)
},
get size(this: IterableCollections) {
return size(this)
},
has,
add: createReadonlyMethod(add, OperationTypes.ADD),
set: createReadonlyMethod(set, OperationTypes.SET),
delete: createReadonlyMethod(deleteEntry, OperationTypes.DELETE),
clear: createReadonlyMethod(clear, OperationTypes.CLEAR),
forEach: createForEach(true)
}
const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator]
iteratorMethods.forEach(method => {
mutableInstrumentations[method as string] = createIterableMethod(
method,
false
)
readonlyInstrumentations[method as string] = createIterableMethod(
method,
true
)
})
function createInstrumentationGetter(
instrumentations: Record<string, Function>
) {
return (
target: CollectionTypes,
key: string | symbol,
receiver: CollectionTypes
) =>
Reflect.get(
hasOwn(instrumentations, key) && key in target
? instrumentations
: target,
key,
receiver
)
}
export const mutableCollectionHandlers: ProxyHandler<CollectionTypes> = {
get: createInstrumentationGetter(mutableInstrumentations)
}
export const readonlyCollectionHandlers: ProxyHandler<CollectionTypes> = {
get: createInstrumentationGetter(readonlyInstrumentations)
}