-
-
Notifications
You must be signed in to change notification settings - Fork 107
/
Copy pathscheduler.ts
54 lines (44 loc) · 1.09 KB
/
scheduler.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
import { ReactiveEffect } from '@vue/reactivity'
const p = Promise.resolve()
type Queued = { value?: any[] }
let preQueued: Queued = {}
let renderQueued: Queued = {}
let postQueued: Queued = {}
function queue(fn: any, queued: Queued) {
if (!queued.value) {
queued.value = [fn]
p.then(flush)
} else {
queued.value.push(fn)
}
}
function flush() {
flushAQueued(preQueued)
flushAQueued(renderQueued)
flushAQueued(postQueued)
}
function flushAQueued(queued: Queued) {
if (queued.value) {
for (let i = 0; i < queued.value.length; i++) {
queued.value[i]()
}
}
queued.value = undefined
}
export const nextTick = (fn?: any) => (fn ? p.then(fn) : p)
export type EffectOptions = {
flush?: 'pre' | 'post' | 'render'
}
export function effect(fn: any, options?: EffectOptions) {
let run: () => void
const flushMode = options?.flush
const queued =
flushMode === 'pre'
? preQueued
: flushMode === 'post'
? postQueued
: renderQueued // default
const e = new ReactiveEffect(fn, () => queue(run, queued))
run = e.run.bind(e)
run()
}