forked from vuejs/composition-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatch.ts
463 lines (414 loc) · 11.2 KB
/
watch.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
import { ComponentInstance } from '../component'
import { Ref, isRef, isReactive } from '../reactivity'
import {
assert,
logError,
noopFn,
warn,
isFunction,
isObject,
isArray,
isPlainObject,
isSet,
isMap,
} from '../utils'
import { defineComponentInstance } from '../utils/helper'
import { getCurrentInstance, getVueConstructor } from '../runtimeContext'
import {
WatcherPreFlushQueueKey,
WatcherPostFlushQueueKey,
} from '../utils/symbols'
import { ComputedRef } from './computed'
export type WatchEffect = (onInvalidate: InvalidateCbRegistrator) => void
export type WatchSource<T = any> = Ref<T> | ComputedRef<T> | (() => T)
export type WatchCallback<V = any, OV = any> = (
value: V,
oldValue: OV,
onInvalidate: InvalidateCbRegistrator
) => any
type MapSources<T> = {
[K in keyof T]: T[K] extends WatchSource<infer V> ? V : never
}
type MapOldSources<T, Immediate> = {
[K in keyof T]: T[K] extends WatchSource<infer V>
? Immediate extends true
? V | undefined
: V
: never
}
export interface WatchOptionsBase {
flush?: FlushMode
// onTrack?: ReactiveEffectOptions['onTrack'];
// onTrigger?: ReactiveEffectOptions['onTrigger'];
}
type InvalidateCbRegistrator = (cb: () => void) => void
export type FlushMode = 'pre' | 'post' | 'sync'
export interface WatchOptions<Immediate = boolean> extends WatchOptionsBase {
immediate?: Immediate
deep?: boolean
}
export interface VueWatcher {
lazy: boolean
get(): any
teardown(): void
run(): void
value: any
}
export type WatchStopHandle = () => void
let fallbackVM: ComponentInstance
function flushPreQueue(this: any) {
flushQueue(this, WatcherPreFlushQueueKey)
}
function flushPostQueue(this: any) {
flushQueue(this, WatcherPostFlushQueueKey)
}
function hasWatchEnv(vm: any) {
return vm[WatcherPreFlushQueueKey] !== undefined
}
function installWatchEnv(vm: any) {
vm[WatcherPreFlushQueueKey] = []
vm[WatcherPostFlushQueueKey] = []
vm.$on('hook:beforeUpdate', flushPreQueue)
vm.$on('hook:updated', flushPostQueue)
}
function getWatcherOption(options?: Partial<WatchOptions>): WatchOptions {
return {
...{
immediate: false,
deep: false,
flush: 'pre',
},
...options,
}
}
function getWatchEffectOption(options?: Partial<WatchOptions>): WatchOptions {
return {
...{
immediate: true,
deep: false,
flush: 'pre',
},
...options,
}
}
function getWatcherVM() {
let vm = getCurrentInstance()?.proxy
if (!vm) {
if (!fallbackVM) {
fallbackVM = defineComponentInstance(getVueConstructor())
}
vm = fallbackVM
} else if (!hasWatchEnv(vm)) {
installWatchEnv(vm)
}
return vm
}
function flushQueue(vm: any, key: any) {
const queue = vm[key]
for (let index = 0; index < queue.length; index++) {
queue[index]()
}
queue.length = 0
}
function queueFlushJob(
vm: any,
fn: () => void,
mode: Exclude<FlushMode, 'sync'>
) {
// flush all when beforeUpdate and updated are not fired
const fallbackFlush = () => {
vm.$nextTick(() => {
if (vm[WatcherPreFlushQueueKey].length) {
flushQueue(vm, WatcherPreFlushQueueKey)
}
if (vm[WatcherPostFlushQueueKey].length) {
flushQueue(vm, WatcherPostFlushQueueKey)
}
})
}
switch (mode) {
case 'pre':
fallbackFlush()
vm[WatcherPreFlushQueueKey].push(fn)
break
case 'post':
fallbackFlush()
vm[WatcherPostFlushQueueKey].push(fn)
break
default:
assert(
false,
`flush must be one of ["post", "pre", "sync"], but got ${mode}`
)
break
}
}
function createVueWatcher(
vm: ComponentInstance,
getter: () => any,
callback: (n: any, o: any) => any,
options: {
deep: boolean
sync: boolean
immediateInvokeCallback?: boolean
noRun?: boolean
before?: () => void
}
): VueWatcher {
const index = vm._watchers.length
// @ts-ignore: use undocumented options
vm.$watch(getter, callback, {
immediate: options.immediateInvokeCallback,
deep: options.deep,
lazy: options.noRun,
sync: options.sync,
before: options.before,
})
return vm._watchers[index]
}
// We have to monkeypatch the teardown function so Vue will run
// runCleanup() when it tears down the watcher on unmounted.
function patchWatcherTeardown(watcher: VueWatcher, runCleanup: () => void) {
const _teardown = watcher.teardown
watcher.teardown = function (...args) {
_teardown.apply(watcher, args)
runCleanup()
}
}
function createWatcher(
vm: ComponentInstance,
source: WatchSource<unknown> | WatchSource<unknown>[] | WatchEffect,
cb: WatchCallback<any> | null,
options: WatchOptions
): () => void {
const flushMode = options.flush
const isSync = flushMode === 'sync'
let cleanup: (() => void) | null
const registerCleanup: InvalidateCbRegistrator = (fn: () => void) => {
cleanup = () => {
try {
fn()
} catch (error) {
logError(error, vm, 'onCleanup()')
}
}
}
// cleanup before running getter again
const runCleanup = () => {
if (cleanup) {
cleanup()
cleanup = null
}
}
const createScheduler = <T extends Function>(fn: T): T => {
if (
isSync ||
/* without a current active instance, ignore pre|post mode */ vm ===
fallbackVM
) {
return fn
}
return ((...args: any[]) =>
queueFlushJob(
vm,
() => {
fn(...args)
},
flushMode as 'pre' | 'post'
)) as any as T
}
// effect watch
if (cb === null) {
let running = false
const getter = () => {
// preventing the watch callback being call in the same execution
if (running) {
return
}
try {
running = true
;(source as WatchEffect)(registerCleanup)
} finally {
running = false
}
}
const watcher = createVueWatcher(vm, getter, noopFn, {
deep: options.deep || false,
sync: isSync,
before: runCleanup,
})
patchWatcherTeardown(watcher, runCleanup)
// enable the watcher update
watcher.lazy = false
const originGet = watcher.get.bind(watcher)
// always run watchEffect
watcher.get = createScheduler(originGet)
return () => {
watcher.teardown()
}
}
let deep = options.deep
let getter: () => any
if (isRef(source)) {
getter = () => source.value
} else if (isReactive(source)) {
getter = () => source
deep = true
} else if (isArray(source)) {
getter = () =>
source.map((s) => {
if (isRef(s)) {
return s.value
} else if (isReactive(s)) {
return traverse(s)
} else if (isFunction(s)) {
return s()
} else {
warn(
`Invalid watch source: ${JSON.stringify(s)}.
A watch source can only be a getter/effect function, a ref, a reactive object, or an array of these types.`,
vm
)
return noopFn
}
})
} else if (isFunction(source)) {
getter = source as () => any
} else {
getter = noopFn
warn(
`Invalid watch source: ${JSON.stringify(source)}.
A watch source can only be a getter/effect function, a ref, a reactive object, or an array of these types.`,
vm
)
}
if (deep) {
const baseGetter = getter
getter = () => traverse(baseGetter())
}
const applyCb = (n: any, o: any) => {
// cleanup before running cb again
runCleanup()
return cb(n, o, registerCleanup)
}
let callback = createScheduler(applyCb)
if (options.immediate) {
const originalCallback = callback
// `shiftCallback` is used to handle the first sync effect run.
// The subsequent callbacks will redirect to `callback`.
let shiftCallback = (n: any, o: any) => {
shiftCallback = originalCallback
// o is undefined on the first call
return applyCb(n, isArray(n) ? [] : o)
}
callback = (n: any, o: any) => {
return shiftCallback(n, o)
}
}
// @ts-ignore: use undocumented option "sync"
const stop = vm.$watch(getter, callback, {
immediate: options.immediate,
deep: deep,
sync: isSync,
})
// Once again, we have to hack the watcher for proper teardown
const watcher = vm._watchers[vm._watchers.length - 1]
// if the return value is reactive and deep:true
// watch for changes, this might happen when new key is added
if (isReactive(watcher.value) && watcher.value.__ob__?.dep && deep) {
watcher.value.__ob__.dep.addSub({
update() {
// this will force the source to be revaluated and the callback
// executed if needed
watcher.run()
},
})
}
patchWatcherTeardown(watcher, runCleanup)
return () => {
stop()
}
}
export function watchEffect(
effect: WatchEffect,
options?: WatchOptionsBase
): WatchStopHandle {
const opts = getWatchEffectOption(options)
const vm = getWatcherVM()
return createWatcher(vm, effect, null, opts)
}
// overload #1: array of multiple sources + cb
// Readonly constraint helps the callback to correctly infer value types based
// on position in the source array. Otherwise the values will get a union type
// of all possible value types.
export function watch<
T extends Readonly<WatchSource<unknown>[]>,
Immediate extends Readonly<boolean> = false
>(
sources: T,
cb: WatchCallback<MapSources<T>, MapOldSources<T, Immediate>>,
options?: WatchOptions<Immediate>
): WatchStopHandle
// overload #2: single source + cb
export function watch<T, Immediate extends Readonly<boolean> = false>(
source: WatchSource<T>,
cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
options?: WatchOptions<Immediate>
): WatchStopHandle
// overload #3: watching reactive object w/ cb
export function watch<
T extends object,
Immediate extends Readonly<boolean> = false
>(
source: T,
cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
options?: WatchOptions<Immediate>
): WatchStopHandle
// implementation
export function watch<T = any>(
source: WatchSource<T> | WatchSource<T>[],
cb: WatchCallback<T>,
options?: WatchOptions
): WatchStopHandle {
let callback: WatchCallback<unknown> | null = null
if (typeof cb === 'function') {
// source watch
callback = cb as WatchCallback<unknown>
} else {
// effect watch
if (__DEV__) {
warn(
`\`watch(fn, options?)\` signature has been moved to a separate API. ` +
`Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` +
`supports \`watch(source, cb, options?) signature.`
)
}
options = cb as Partial<WatchOptions>
callback = null
}
const opts = getWatcherOption(options)
const vm = getWatcherVM()
return createWatcher(vm, source, callback, opts)
}
function traverse(value: unknown, seen: Set<unknown> = new Set()) {
if (!isObject(value) || seen.has(value)) {
return value
}
seen.add(value)
if (isRef(value)) {
traverse(value.value, seen)
} else if (isArray(value)) {
for (let i = 0; i < value.length; i++) {
traverse(value[i], seen)
}
} else if (isSet(value) || isMap(value)) {
value.forEach((v: any) => {
traverse(v, seen)
})
} else if (isPlainObject(value)) {
for (const key in value) {
traverse((value as any)[key], seen)
}
}
return value
}