watch.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. import {
  2. EMPTY_OBJ,
  3. NOOP,
  4. hasChanged,
  5. isArray,
  6. isFunction,
  7. isMap,
  8. isObject,
  9. isPlainObject,
  10. isSet,
  11. remove,
  12. } from '@vue/shared'
  13. import { warn } from './warning'
  14. import type { ComputedRef } from './computed'
  15. import { ReactiveFlags } from './constants'
  16. import {
  17. type DebuggerOptions,
  18. EffectFlags,
  19. type EffectScheduler,
  20. ReactiveEffect,
  21. pauseTracking,
  22. resetTracking,
  23. } from './effect'
  24. import { isReactive, isShallow } from './reactive'
  25. import { type Ref, isRef } from './ref'
  26. import { getCurrentScope } from './effectScope'
  27. // These errors were transferred from `packages/runtime-core/src/errorHandling.ts`
  28. // to @vue/reactivity to allow co-location with the moved base watch logic, hence
  29. // it is essential to keep these values unchanged.
  30. export enum WatchErrorCodes {
  31. WATCH_GETTER = 2,
  32. WATCH_CALLBACK,
  33. WATCH_CLEANUP,
  34. }
  35. export type WatchEffect = (onCleanup: OnCleanup) => void
  36. export type WatchSource<T = any> = Ref<T, any> | ComputedRef<T> | (() => T)
  37. export type WatchCallback<V = any, OV = any> = (
  38. value: V,
  39. oldValue: OV,
  40. onCleanup: OnCleanup,
  41. ) => any
  42. export type OnCleanup = (cleanupFn: () => void) => void
  43. export interface WatchOptions<Immediate = boolean> extends DebuggerOptions {
  44. immediate?: Immediate
  45. deep?: boolean | number
  46. once?: boolean
  47. scheduler?: WatchScheduler
  48. onWarn?: (msg: string, ...args: any[]) => void
  49. /**
  50. * @internal
  51. */
  52. augmentJob?: (job: (...args: any[]) => void) => void
  53. /**
  54. * @internal
  55. */
  56. call?: (
  57. fn: Function | Function[],
  58. type: WatchErrorCodes,
  59. args?: unknown[],
  60. ) => void
  61. }
  62. export type WatchStopHandle = () => void
  63. export interface WatchHandle extends WatchStopHandle {
  64. pause: () => void
  65. resume: () => void
  66. stop: () => void
  67. }
  68. // initial value for watchers to trigger on undefined initial values
  69. const INITIAL_WATCHER_VALUE = {}
  70. export type WatchScheduler = (job: () => void, isFirstRun: boolean) => void
  71. const cleanupMap: WeakMap<ReactiveEffect, (() => void)[]> = new WeakMap()
  72. let activeWatcher: ReactiveEffect | undefined = undefined
  73. /**
  74. * Returns the current active effect if there is one.
  75. */
  76. export function getCurrentWatcher(): ReactiveEffect<any> | undefined {
  77. return activeWatcher
  78. }
  79. /**
  80. * Registers a cleanup callback on the current active effect. This
  81. * registered cleanup callback will be invoked right before the
  82. * associated effect re-runs.
  83. *
  84. * @param cleanupFn - The callback function to attach to the effect's cleanup.
  85. * @param failSilently - if `true`, will not throw warning when called without
  86. * an active effect.
  87. * @param owner - The effect that this cleanup function should be attached to.
  88. * By default, the current active effect.
  89. */
  90. export function onWatcherCleanup(
  91. cleanupFn: () => void,
  92. failSilently = false,
  93. owner: ReactiveEffect | undefined = activeWatcher,
  94. ): void {
  95. if (owner) {
  96. let cleanups = cleanupMap.get(owner)
  97. if (!cleanups) cleanupMap.set(owner, (cleanups = []))
  98. cleanups.push(cleanupFn)
  99. } else if (__DEV__ && !failSilently) {
  100. warn(
  101. `onWatcherCleanup() was called when there was no active watcher` +
  102. ` to associate with.`,
  103. )
  104. }
  105. }
  106. export function watch(
  107. source: WatchSource | WatchSource[] | WatchEffect | object,
  108. cb?: WatchCallback | null,
  109. options: WatchOptions = EMPTY_OBJ,
  110. ): WatchHandle {
  111. const { immediate, deep, once, scheduler, augmentJob, call } = options
  112. const warnInvalidSource = (s: unknown) => {
  113. ;(options.onWarn || warn)(
  114. `Invalid watch source: `,
  115. s,
  116. `A watch source can only be a getter/effect function, a ref, ` +
  117. `a reactive object, or an array of these types.`,
  118. )
  119. }
  120. const reactiveGetter = (source: object) => {
  121. // traverse will happen in wrapped getter below
  122. if (deep) return source
  123. // for `deep: false | 0` or shallow reactive, only traverse root-level properties
  124. if (isShallow(source) || deep === false || deep === 0)
  125. return traverse(source, 1)
  126. // for `deep: undefined` on a reactive object, deeply traverse all properties
  127. return traverse(source)
  128. }
  129. let effect: ReactiveEffect
  130. let getter: () => any
  131. let cleanup: (() => void) | undefined
  132. let boundCleanup: typeof onWatcherCleanup
  133. let forceTrigger = false
  134. let isMultiSource = false
  135. if (isRef(source)) {
  136. getter = () => source.value
  137. forceTrigger = isShallow(source)
  138. } else if (isReactive(source)) {
  139. getter = () => reactiveGetter(source)
  140. forceTrigger = true
  141. } else if (isArray(source)) {
  142. isMultiSource = true
  143. forceTrigger = source.some(s => isReactive(s) || isShallow(s))
  144. getter = () =>
  145. source.map(s => {
  146. if (isRef(s)) {
  147. return s.value
  148. } else if (isReactive(s)) {
  149. return reactiveGetter(s)
  150. } else if (isFunction(s)) {
  151. return call ? call(s, WatchErrorCodes.WATCH_GETTER) : s()
  152. } else {
  153. __DEV__ && warnInvalidSource(s)
  154. }
  155. })
  156. } else if (isFunction(source)) {
  157. if (cb) {
  158. // getter with cb
  159. getter = call
  160. ? () => call(source, WatchErrorCodes.WATCH_GETTER)
  161. : (source as () => any)
  162. } else {
  163. // no cb -> simple effect
  164. getter = () => {
  165. if (cleanup) {
  166. pauseTracking()
  167. try {
  168. cleanup()
  169. } finally {
  170. resetTracking()
  171. }
  172. }
  173. const currentEffect = activeWatcher
  174. activeWatcher = effect
  175. try {
  176. return call
  177. ? call(source, WatchErrorCodes.WATCH_CALLBACK, [boundCleanup])
  178. : source(boundCleanup)
  179. } finally {
  180. activeWatcher = currentEffect
  181. }
  182. }
  183. }
  184. } else {
  185. getter = NOOP
  186. __DEV__ && warnInvalidSource(source)
  187. }
  188. if (cb && deep) {
  189. const baseGetter = getter
  190. const depth = deep === true ? Infinity : deep
  191. getter = () => traverse(baseGetter(), depth)
  192. }
  193. const scope = getCurrentScope()
  194. const watchHandle: WatchHandle = () => {
  195. effect.stop()
  196. if (scope && scope.active) {
  197. remove(scope.effects, effect)
  198. }
  199. }
  200. if (once && cb) {
  201. const _cb = cb
  202. cb = (...args) => {
  203. _cb(...args)
  204. watchHandle()
  205. }
  206. }
  207. let oldValue: any = isMultiSource
  208. ? new Array((source as []).length).fill(INITIAL_WATCHER_VALUE)
  209. : INITIAL_WATCHER_VALUE
  210. const job = (immediateFirstRun?: boolean) => {
  211. if (
  212. !(effect.flags & EffectFlags.ACTIVE) ||
  213. (!effect.dirty && !immediateFirstRun)
  214. ) {
  215. return
  216. }
  217. if (cb) {
  218. // watch(source, cb)
  219. const newValue = effect.run()
  220. if (
  221. deep ||
  222. forceTrigger ||
  223. (isMultiSource
  224. ? (newValue as any[]).some((v, i) => hasChanged(v, oldValue[i]))
  225. : hasChanged(newValue, oldValue))
  226. ) {
  227. // cleanup before running cb again
  228. if (cleanup) {
  229. cleanup()
  230. }
  231. const currentWatcher = activeWatcher
  232. activeWatcher = effect
  233. try {
  234. const args = [
  235. newValue,
  236. // pass undefined as the old value when it's changed for the first time
  237. oldValue === INITIAL_WATCHER_VALUE
  238. ? undefined
  239. : isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE
  240. ? []
  241. : oldValue,
  242. boundCleanup,
  243. ]
  244. oldValue = newValue
  245. call
  246. ? call(cb!, WatchErrorCodes.WATCH_CALLBACK, args)
  247. : // @ts-expect-error
  248. cb!(...args)
  249. } finally {
  250. activeWatcher = currentWatcher
  251. }
  252. }
  253. } else {
  254. // watchEffect
  255. effect.run()
  256. }
  257. }
  258. if (augmentJob) {
  259. augmentJob(job)
  260. }
  261. effect = new ReactiveEffect(getter)
  262. effect.scheduler = scheduler
  263. ? () => scheduler(job, false)
  264. : (job as EffectScheduler)
  265. boundCleanup = fn => onWatcherCleanup(fn, false, effect)
  266. cleanup = effect.onStop = () => {
  267. const cleanups = cleanupMap.get(effect)
  268. if (cleanups) {
  269. if (call) {
  270. call(cleanups, WatchErrorCodes.WATCH_CLEANUP)
  271. } else {
  272. for (const cleanup of cleanups) cleanup()
  273. }
  274. cleanupMap.delete(effect)
  275. }
  276. }
  277. if (__DEV__) {
  278. effect.onTrack = options.onTrack
  279. effect.onTrigger = options.onTrigger
  280. }
  281. // initial run
  282. if (cb) {
  283. if (immediate) {
  284. job(true)
  285. } else {
  286. oldValue = effect.run()
  287. }
  288. } else if (scheduler) {
  289. scheduler(job.bind(null, true), true)
  290. } else {
  291. effect.run()
  292. }
  293. watchHandle.pause = effect.pause.bind(effect)
  294. watchHandle.resume = effect.resume.bind(effect)
  295. watchHandle.stop = watchHandle
  296. return watchHandle
  297. }
  298. export function traverse(
  299. value: unknown,
  300. depth: number = Infinity,
  301. seen?: Map<unknown, number>,
  302. ): unknown {
  303. if (depth <= 0 || !isObject(value) || (value as any)[ReactiveFlags.SKIP]) {
  304. return value
  305. }
  306. seen = seen || new Map()
  307. if ((seen.get(value) || 0) >= depth) {
  308. return value
  309. }
  310. seen.set(value, depth)
  311. depth--
  312. if (isRef(value)) {
  313. traverse(value.value, depth, seen)
  314. } else if (isArray(value)) {
  315. for (let i = 0; i < value.length; i++) {
  316. traverse(value[i], depth, seen)
  317. }
  318. } else if (isSet(value) || isMap(value)) {
  319. value.forEach((v: any) => {
  320. traverse(v, depth, seen)
  321. })
  322. } else if (isPlainObject(value)) {
  323. for (const key in value) {
  324. traverse(value[key], depth, seen)
  325. }
  326. for (const key of Object.getOwnPropertySymbols(value)) {
  327. if (Object.prototype.propertyIsEnumerable.call(value, key)) {
  328. traverse(value[key as any], depth, seen)
  329. }
  330. }
  331. }
  332. return value
  333. }