collectionHandlers.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. import { toRaw, ReactiveFlags, toReactive, toReadonly } from './reactive'
  2. import { track, trigger, ITERATE_KEY, MAP_KEY_ITERATE_KEY } from './effect'
  3. import { TrackOpTypes, TriggerOpTypes } from './operations'
  4. import { capitalize, hasOwn, hasChanged, toRawType, isMap } from '@vue/shared'
  5. export type CollectionTypes = IterableCollections | WeakCollections
  6. type IterableCollections = Map<any, any> | Set<any>
  7. type WeakCollections = WeakMap<any, any> | WeakSet<any>
  8. type MapTypes = Map<any, any> | WeakMap<any, any>
  9. type SetTypes = Set<any> | WeakSet<any>
  10. const toShallow = <T extends unknown>(value: T): T => value
  11. const getProto = <T extends CollectionTypes>(v: T): any =>
  12. Reflect.getPrototypeOf(v)
  13. function get(
  14. target: MapTypes,
  15. key: unknown,
  16. isReadonly = false,
  17. isShallow = false
  18. ) {
  19. // #1772: readonly(reactive(Map)) should return readonly + reactive version
  20. // of the value
  21. target = (target as any)[ReactiveFlags.RAW]
  22. const rawTarget = toRaw(target)
  23. const rawKey = toRaw(key)
  24. if (key !== rawKey) {
  25. !isReadonly && track(rawTarget, TrackOpTypes.GET, key)
  26. }
  27. !isReadonly && track(rawTarget, TrackOpTypes.GET, rawKey)
  28. const { has } = getProto(rawTarget)
  29. const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive
  30. if (has.call(rawTarget, key)) {
  31. return wrap(target.get(key))
  32. } else if (has.call(rawTarget, rawKey)) {
  33. return wrap(target.get(rawKey))
  34. } else if (target !== rawTarget) {
  35. // #3602 readonly(reactive(Map))
  36. // ensure that the nested reactive `Map` can do tracking for itself
  37. target.get(key)
  38. }
  39. }
  40. function has(this: CollectionTypes, key: unknown, isReadonly = false): boolean {
  41. const target = (this as any)[ReactiveFlags.RAW]
  42. const rawTarget = toRaw(target)
  43. const rawKey = toRaw(key)
  44. if (key !== rawKey) {
  45. !isReadonly && track(rawTarget, TrackOpTypes.HAS, key)
  46. }
  47. !isReadonly && track(rawTarget, TrackOpTypes.HAS, rawKey)
  48. return key === rawKey
  49. ? target.has(key)
  50. : target.has(key) || target.has(rawKey)
  51. }
  52. function size(target: IterableCollections, isReadonly = false) {
  53. target = (target as any)[ReactiveFlags.RAW]
  54. !isReadonly && track(toRaw(target), TrackOpTypes.ITERATE, ITERATE_KEY)
  55. return Reflect.get(target, 'size', target)
  56. }
  57. function add(this: SetTypes, value: unknown) {
  58. value = toRaw(value)
  59. const target = toRaw(this)
  60. const proto = getProto(target)
  61. const hadKey = proto.has.call(target, value)
  62. if (!hadKey) {
  63. target.add(value)
  64. trigger(target, TriggerOpTypes.ADD, value, value)
  65. }
  66. return this
  67. }
  68. function set(this: MapTypes, key: unknown, value: unknown) {
  69. value = toRaw(value)
  70. const target = toRaw(this)
  71. const { has, get } = getProto(target)
  72. let hadKey = has.call(target, key)
  73. if (!hadKey) {
  74. key = toRaw(key)
  75. hadKey = has.call(target, key)
  76. } else if (__DEV__) {
  77. checkIdentityKeys(target, has, key)
  78. }
  79. const oldValue = get.call(target, key)
  80. target.set(key, value)
  81. if (!hadKey) {
  82. trigger(target, TriggerOpTypes.ADD, key, value)
  83. } else if (hasChanged(value, oldValue)) {
  84. trigger(target, TriggerOpTypes.SET, key, value, oldValue)
  85. }
  86. return this
  87. }
  88. function deleteEntry(this: CollectionTypes, key: unknown) {
  89. const target = toRaw(this)
  90. const { has, get } = getProto(target)
  91. let hadKey = has.call(target, key)
  92. if (!hadKey) {
  93. key = toRaw(key)
  94. hadKey = has.call(target, key)
  95. } else if (__DEV__) {
  96. checkIdentityKeys(target, has, key)
  97. }
  98. const oldValue = get ? get.call(target, key) : undefined
  99. // forward the operation before queueing reactions
  100. const result = target.delete(key)
  101. if (hadKey) {
  102. trigger(target, TriggerOpTypes.DELETE, key, undefined, oldValue)
  103. }
  104. return result
  105. }
  106. function clear(this: IterableCollections) {
  107. const target = toRaw(this)
  108. const hadItems = target.size !== 0
  109. const oldTarget = __DEV__
  110. ? isMap(target)
  111. ? new Map(target)
  112. : new Set(target)
  113. : undefined
  114. // forward the operation before queueing reactions
  115. const result = target.clear()
  116. if (hadItems) {
  117. trigger(target, TriggerOpTypes.CLEAR, undefined, undefined, oldTarget)
  118. }
  119. return result
  120. }
  121. function createForEach(isReadonly: boolean, isShallow: boolean) {
  122. return function forEach(
  123. this: IterableCollections,
  124. callback: Function,
  125. thisArg?: unknown
  126. ) {
  127. const observed = this as any
  128. const target = observed[ReactiveFlags.RAW]
  129. const rawTarget = toRaw(target)
  130. const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive
  131. !isReadonly && track(rawTarget, TrackOpTypes.ITERATE, ITERATE_KEY)
  132. return target.forEach((value: unknown, key: unknown) => {
  133. // important: make sure the callback is
  134. // 1. invoked with the reactive map as `this` and 3rd arg
  135. // 2. the value received should be a corresponding reactive/readonly.
  136. return callback.call(thisArg, wrap(value), wrap(key), observed)
  137. })
  138. }
  139. }
  140. interface Iterable {
  141. [Symbol.iterator](): Iterator
  142. }
  143. interface Iterator {
  144. next(value?: any): IterationResult
  145. }
  146. interface IterationResult {
  147. value: any
  148. done: boolean
  149. }
  150. function createIterableMethod(
  151. method: string | symbol,
  152. isReadonly: boolean,
  153. isShallow: boolean
  154. ) {
  155. return function (
  156. this: IterableCollections,
  157. ...args: unknown[]
  158. ): Iterable & Iterator {
  159. const target = (this as any)[ReactiveFlags.RAW]
  160. const rawTarget = toRaw(target)
  161. const targetIsMap = isMap(rawTarget)
  162. const isPair =
  163. method === 'entries' || (method === Symbol.iterator && targetIsMap)
  164. const isKeyOnly = method === 'keys' && targetIsMap
  165. const innerIterator = target[method](...args)
  166. const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive
  167. !isReadonly &&
  168. track(
  169. rawTarget,
  170. TrackOpTypes.ITERATE,
  171. isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY
  172. )
  173. // return a wrapped iterator which returns observed versions of the
  174. // values emitted from the real iterator
  175. return {
  176. // iterator protocol
  177. next() {
  178. const { value, done } = innerIterator.next()
  179. return done
  180. ? { value, done }
  181. : {
  182. value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
  183. done
  184. }
  185. },
  186. // iterable protocol
  187. [Symbol.iterator]() {
  188. return this
  189. }
  190. }
  191. }
  192. }
  193. function createReadonlyMethod(type: TriggerOpTypes): Function {
  194. return function (this: CollectionTypes, ...args: unknown[]) {
  195. if (__DEV__) {
  196. const key = args[0] ? `on key "${args[0]}" ` : ``
  197. console.warn(
  198. `${capitalize(type)} operation ${key}failed: target is readonly.`,
  199. toRaw(this)
  200. )
  201. }
  202. return type === TriggerOpTypes.DELETE ? false : this
  203. }
  204. }
  205. function createInstrumentations() {
  206. const mutableInstrumentations: Record<string, Function> = {
  207. get(this: MapTypes, key: unknown) {
  208. return get(this, key)
  209. },
  210. get size() {
  211. return size(this as unknown as IterableCollections)
  212. },
  213. has,
  214. add,
  215. set,
  216. delete: deleteEntry,
  217. clear,
  218. forEach: createForEach(false, false)
  219. }
  220. const shallowInstrumentations: Record<string, Function> = {
  221. get(this: MapTypes, key: unknown) {
  222. return get(this, key, false, true)
  223. },
  224. get size() {
  225. return size(this as unknown as IterableCollections)
  226. },
  227. has,
  228. add,
  229. set,
  230. delete: deleteEntry,
  231. clear,
  232. forEach: createForEach(false, true)
  233. }
  234. const readonlyInstrumentations: Record<string, Function> = {
  235. get(this: MapTypes, key: unknown) {
  236. return get(this, key, true)
  237. },
  238. get size() {
  239. return size(this as unknown as IterableCollections, true)
  240. },
  241. has(this: MapTypes, key: unknown) {
  242. return has.call(this, key, true)
  243. },
  244. add: createReadonlyMethod(TriggerOpTypes.ADD),
  245. set: createReadonlyMethod(TriggerOpTypes.SET),
  246. delete: createReadonlyMethod(TriggerOpTypes.DELETE),
  247. clear: createReadonlyMethod(TriggerOpTypes.CLEAR),
  248. forEach: createForEach(true, false)
  249. }
  250. const shallowReadonlyInstrumentations: Record<string, Function> = {
  251. get(this: MapTypes, key: unknown) {
  252. return get(this, key, true, true)
  253. },
  254. get size() {
  255. return size(this as unknown as IterableCollections, true)
  256. },
  257. has(this: MapTypes, key: unknown) {
  258. return has.call(this, key, true)
  259. },
  260. add: createReadonlyMethod(TriggerOpTypes.ADD),
  261. set: createReadonlyMethod(TriggerOpTypes.SET),
  262. delete: createReadonlyMethod(TriggerOpTypes.DELETE),
  263. clear: createReadonlyMethod(TriggerOpTypes.CLEAR),
  264. forEach: createForEach(true, true)
  265. }
  266. const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator]
  267. iteratorMethods.forEach(method => {
  268. mutableInstrumentations[method as string] = createIterableMethod(
  269. method,
  270. false,
  271. false
  272. )
  273. readonlyInstrumentations[method as string] = createIterableMethod(
  274. method,
  275. true,
  276. false
  277. )
  278. shallowInstrumentations[method as string] = createIterableMethod(
  279. method,
  280. false,
  281. true
  282. )
  283. shallowReadonlyInstrumentations[method as string] = createIterableMethod(
  284. method,
  285. true,
  286. true
  287. )
  288. })
  289. return [
  290. mutableInstrumentations,
  291. readonlyInstrumentations,
  292. shallowInstrumentations,
  293. shallowReadonlyInstrumentations
  294. ]
  295. }
  296. const [
  297. mutableInstrumentations,
  298. readonlyInstrumentations,
  299. shallowInstrumentations,
  300. shallowReadonlyInstrumentations
  301. ] = /* #__PURE__*/ createInstrumentations()
  302. function createInstrumentationGetter(isReadonly: boolean, shallow: boolean) {
  303. const instrumentations = shallow
  304. ? isReadonly
  305. ? shallowReadonlyInstrumentations
  306. : shallowInstrumentations
  307. : isReadonly
  308. ? readonlyInstrumentations
  309. : mutableInstrumentations
  310. return (
  311. target: CollectionTypes,
  312. key: string | symbol,
  313. receiver: CollectionTypes
  314. ) => {
  315. if (key === ReactiveFlags.IS_REACTIVE) {
  316. return !isReadonly
  317. } else if (key === ReactiveFlags.IS_READONLY) {
  318. return isReadonly
  319. } else if (key === ReactiveFlags.RAW) {
  320. return target
  321. }
  322. return Reflect.get(
  323. hasOwn(instrumentations, key) && key in target
  324. ? instrumentations
  325. : target,
  326. key,
  327. receiver
  328. )
  329. }
  330. }
  331. export const mutableCollectionHandlers: ProxyHandler<CollectionTypes> = {
  332. get: /*#__PURE__*/ createInstrumentationGetter(false, false)
  333. }
  334. export const shallowCollectionHandlers: ProxyHandler<CollectionTypes> = {
  335. get: /*#__PURE__*/ createInstrumentationGetter(false, true)
  336. }
  337. export const readonlyCollectionHandlers: ProxyHandler<CollectionTypes> = {
  338. get: /*#__PURE__*/ createInstrumentationGetter(true, false)
  339. }
  340. export const shallowReadonlyCollectionHandlers: ProxyHandler<CollectionTypes> =
  341. {
  342. get: /*#__PURE__*/ createInstrumentationGetter(true, true)
  343. }
  344. function checkIdentityKeys(
  345. target: CollectionTypes,
  346. has: (key: unknown) => boolean,
  347. key: unknown
  348. ) {
  349. const rawKey = toRaw(key)
  350. if (rawKey !== key && has.call(target, rawKey)) {
  351. const type = toRawType(target)
  352. console.warn(
  353. `Reactive ${type} contains both the raw and reactive ` +
  354. `versions of the same object${type === `Map` ? ` as keys` : ``}, ` +
  355. `which can lead to inconsistencies. ` +
  356. `Avoid differentiating between the raw and reactive versions ` +
  357. `of an object and only use the reactive version if possible.`
  358. )
  359. }
  360. }