dep.ts 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. import { extend, isArray, isIntegerKey, isMap, isSymbol } from '@vue/shared'
  2. import type { ComputedRefImpl } from './computed'
  3. import { type TrackOpTypes, TriggerOpTypes } from './constants'
  4. import {
  5. type DebuggerEventExtraInfo,
  6. EffectFlags,
  7. type Subscriber,
  8. activeSub,
  9. endBatch,
  10. shouldTrack,
  11. startBatch,
  12. } from './effect'
  13. /**
  14. * Incremented every time a reactive change happens
  15. * This is used to give computed a fast path to avoid re-compute when nothing
  16. * has changed.
  17. */
  18. export let globalVersion = 0
  19. /**
  20. * Represents a link between a source (Dep) and a subscriber (Effect or Computed).
  21. * Deps and subs have a many-to-many relationship - each link between a
  22. * dep and a sub is represented by a Link instance.
  23. *
  24. * A Link is also a node in two doubly-linked lists - one for the associated
  25. * sub to track all its deps, and one for the associated dep to track all its
  26. * subs.
  27. *
  28. * @internal
  29. */
  30. export class Link {
  31. /**
  32. * - Before each effect run, all previous dep links' version are reset to -1
  33. * - During the run, a link's version is synced with the source dep on access
  34. * - After the run, links with version -1 (that were never used) are cleaned
  35. * up
  36. */
  37. version: number
  38. /**
  39. * Pointers for doubly-linked lists
  40. */
  41. nextDep?: Link
  42. prevDep?: Link
  43. nextSub?: Link
  44. prevSub?: Link
  45. prevActiveLink?: Link
  46. constructor(
  47. public sub: Subscriber,
  48. public dep: Dep,
  49. ) {
  50. this.version = dep.version
  51. this.nextDep =
  52. this.prevDep =
  53. this.nextSub =
  54. this.prevSub =
  55. this.prevActiveLink =
  56. undefined
  57. }
  58. }
  59. /**
  60. * @internal
  61. */
  62. export class Dep {
  63. version = 0
  64. /**
  65. * Link between this dep and the current active effect
  66. */
  67. activeLink?: Link = undefined
  68. /**
  69. * Doubly linked list representing the subscribing effects (tail)
  70. */
  71. subs?: Link = undefined
  72. /**
  73. * Doubly linked list representing the subscribing effects (head)
  74. * DEV only, for invoking onTrigger hooks in correct order
  75. */
  76. subsHead?: Link
  77. /**
  78. * For object property deps cleanup
  79. */
  80. map?: KeyToDepMap = undefined
  81. key?: unknown = undefined
  82. /**
  83. * Subscriber counter
  84. */
  85. sc: number = 0
  86. constructor(public computed?: ComputedRefImpl | undefined) {
  87. if (__DEV__) {
  88. this.subsHead = undefined
  89. }
  90. }
  91. track(debugInfo?: DebuggerEventExtraInfo): Link | undefined {
  92. if (!activeSub || !shouldTrack || activeSub === this.computed) {
  93. return
  94. }
  95. let link = this.activeLink
  96. if (link === undefined || link.sub !== activeSub) {
  97. link = this.activeLink = new Link(activeSub, this)
  98. // add the link to the activeEffect as a dep (as tail)
  99. if (!activeSub.deps) {
  100. activeSub.deps = activeSub.depsTail = link
  101. } else {
  102. link.prevDep = activeSub.depsTail
  103. activeSub.depsTail!.nextDep = link
  104. activeSub.depsTail = link
  105. }
  106. addSub(link)
  107. } else if (link.version === -1) {
  108. // reused from last run - already a sub, just sync version
  109. link.version = this.version
  110. // If this dep has a next, it means it's not at the tail - move it to the
  111. // tail. This ensures the effect's dep list is in the order they are
  112. // accessed during evaluation.
  113. if (link.nextDep) {
  114. const next = link.nextDep
  115. next.prevDep = link.prevDep
  116. if (link.prevDep) {
  117. link.prevDep.nextDep = next
  118. }
  119. link.prevDep = activeSub.depsTail
  120. link.nextDep = undefined
  121. activeSub.depsTail!.nextDep = link
  122. activeSub.depsTail = link
  123. // this was the head - point to the new head
  124. if (activeSub.deps === link) {
  125. activeSub.deps = next
  126. }
  127. }
  128. }
  129. if (__DEV__ && activeSub.onTrack) {
  130. activeSub.onTrack(
  131. extend(
  132. {
  133. effect: activeSub,
  134. },
  135. debugInfo,
  136. ),
  137. )
  138. }
  139. return link
  140. }
  141. trigger(debugInfo?: DebuggerEventExtraInfo): void {
  142. this.version++
  143. globalVersion++
  144. this.notify(debugInfo)
  145. }
  146. notify(debugInfo?: DebuggerEventExtraInfo): void {
  147. startBatch()
  148. try {
  149. if (__DEV__) {
  150. // subs are notified and batched in reverse-order and then invoked in
  151. // original order at the end of the batch, but onTrigger hooks should
  152. // be invoked in original order here.
  153. for (let head = this.subsHead; head; head = head.nextSub) {
  154. if (head.sub.onTrigger && !(head.sub.flags & EffectFlags.NOTIFIED)) {
  155. head.sub.onTrigger(
  156. extend(
  157. {
  158. effect: head.sub,
  159. },
  160. debugInfo,
  161. ),
  162. )
  163. }
  164. }
  165. }
  166. for (let link = this.subs; link; link = link.prevSub) {
  167. if (link.sub.notify()) {
  168. // if notify() returns `true`, this is a computed. Also call notify
  169. // on its dep - it's called here instead of inside computed's notify
  170. // in order to reduce call stack depth.
  171. ;(link.sub as ComputedRefImpl).dep.notify()
  172. }
  173. }
  174. } finally {
  175. endBatch()
  176. }
  177. }
  178. }
  179. function addSub(link: Link) {
  180. link.dep.sc++
  181. if (link.sub.flags & EffectFlags.TRACKING) {
  182. const computed = link.dep.computed
  183. // computed getting its first subscriber
  184. // enable tracking + lazily subscribe to all its deps
  185. if (computed && !link.dep.subs) {
  186. computed.flags |= EffectFlags.TRACKING | EffectFlags.DIRTY
  187. for (let l = computed.deps; l; l = l.nextDep) {
  188. addSub(l)
  189. }
  190. }
  191. const currentTail = link.dep.subs
  192. if (currentTail !== link) {
  193. link.prevSub = currentTail
  194. if (currentTail) currentTail.nextSub = link
  195. }
  196. if (__DEV__ && link.dep.subsHead === undefined) {
  197. link.dep.subsHead = link
  198. }
  199. link.dep.subs = link
  200. }
  201. }
  202. // The main WeakMap that stores {target -> key -> dep} connections.
  203. // Conceptually, it's easier to think of a dependency as a Dep class
  204. // which maintains a Set of subscribers, but we simply store them as
  205. // raw Maps to reduce memory overhead.
  206. type KeyToDepMap = Map<any, Dep>
  207. export const targetMap: WeakMap<object, KeyToDepMap> = new WeakMap()
  208. export const ITERATE_KEY: unique symbol = Symbol(
  209. __DEV__ ? 'Object iterate' : '',
  210. )
  211. export const MAP_KEY_ITERATE_KEY: unique symbol = Symbol(
  212. __DEV__ ? 'Map keys iterate' : '',
  213. )
  214. export const ARRAY_ITERATE_KEY: unique symbol = Symbol(
  215. __DEV__ ? 'Array iterate' : '',
  216. )
  217. /**
  218. * Tracks access to a reactive property.
  219. *
  220. * This will check which effect is running at the moment and record it as dep
  221. * which records all effects that depend on the reactive property.
  222. *
  223. * @param target - Object holding the reactive property.
  224. * @param type - Defines the type of access to the reactive property.
  225. * @param key - Identifier of the reactive property to track.
  226. */
  227. export function track(target: object, type: TrackOpTypes, key: unknown): void {
  228. if (shouldTrack && activeSub) {
  229. let depsMap = targetMap.get(target)
  230. if (!depsMap) {
  231. targetMap.set(target, (depsMap = new Map()))
  232. }
  233. let dep = depsMap.get(key)
  234. if (!dep) {
  235. depsMap.set(key, (dep = new Dep()))
  236. dep.map = depsMap
  237. dep.key = key
  238. }
  239. if (__DEV__) {
  240. dep.track({
  241. target,
  242. type,
  243. key,
  244. })
  245. } else {
  246. dep.track()
  247. }
  248. }
  249. }
  250. /**
  251. * Finds all deps associated with the target (or a specific property) and
  252. * triggers the effects stored within.
  253. *
  254. * @param target - The reactive object.
  255. * @param type - Defines the type of the operation that needs to trigger effects.
  256. * @param key - Can be used to target a specific reactive property in the target object.
  257. */
  258. export function trigger(
  259. target: object,
  260. type: TriggerOpTypes,
  261. key?: unknown,
  262. newValue?: unknown,
  263. oldValue?: unknown,
  264. oldTarget?: Map<unknown, unknown> | Set<unknown>,
  265. ): void {
  266. const depsMap = targetMap.get(target)
  267. if (!depsMap) {
  268. // never been tracked
  269. globalVersion++
  270. return
  271. }
  272. const run = (dep: Dep | undefined) => {
  273. if (dep) {
  274. if (__DEV__) {
  275. dep.trigger({
  276. target,
  277. type,
  278. key,
  279. newValue,
  280. oldValue,
  281. oldTarget,
  282. })
  283. } else {
  284. dep.trigger()
  285. }
  286. }
  287. }
  288. startBatch()
  289. if (type === TriggerOpTypes.CLEAR) {
  290. // collection being cleared
  291. // trigger all effects for target
  292. depsMap.forEach(run)
  293. } else {
  294. const targetIsArray = isArray(target)
  295. const isArrayIndex = targetIsArray && isIntegerKey(key)
  296. if (targetIsArray && key === 'length') {
  297. const newLength = Number(newValue)
  298. depsMap.forEach((dep, key) => {
  299. if (
  300. key === 'length' ||
  301. key === ARRAY_ITERATE_KEY ||
  302. (!isSymbol(key) && key >= newLength)
  303. ) {
  304. run(dep)
  305. }
  306. })
  307. } else {
  308. // schedule runs for SET | ADD | DELETE
  309. if (key !== void 0 || depsMap.has(void 0)) {
  310. run(depsMap.get(key))
  311. }
  312. // schedule ARRAY_ITERATE for any numeric key change (length is handled above)
  313. if (isArrayIndex) {
  314. run(depsMap.get(ARRAY_ITERATE_KEY))
  315. }
  316. // also run for iteration key on ADD | DELETE | Map.SET
  317. switch (type) {
  318. case TriggerOpTypes.ADD:
  319. if (!targetIsArray) {
  320. run(depsMap.get(ITERATE_KEY))
  321. if (isMap(target)) {
  322. run(depsMap.get(MAP_KEY_ITERATE_KEY))
  323. }
  324. } else if (isArrayIndex) {
  325. // new index added to array -> length changes
  326. run(depsMap.get('length'))
  327. }
  328. break
  329. case TriggerOpTypes.DELETE:
  330. if (!targetIsArray) {
  331. run(depsMap.get(ITERATE_KEY))
  332. if (isMap(target)) {
  333. run(depsMap.get(MAP_KEY_ITERATE_KEY))
  334. }
  335. }
  336. break
  337. case TriggerOpTypes.SET:
  338. if (isMap(target)) {
  339. run(depsMap.get(ITERATE_KEY))
  340. }
  341. break
  342. }
  343. }
  344. }
  345. endBatch()
  346. }
  347. export function getDepFromReactive(
  348. object: any,
  349. key: string | number | symbol,
  350. ): Dep | undefined {
  351. const depMap = targetMap.get(object)
  352. return depMap && depMap.get(key)
  353. }