2019-08-30 19:15:23 +00:00
|
|
|
import { handleError, ErrorTypes } from './errorHandling'
|
|
|
|
|
2019-05-28 11:36:15 +00:00
|
|
|
const queue: Function[] = []
|
|
|
|
const postFlushCbs: Function[] = []
|
2019-05-28 09:19:47 +00:00
|
|
|
const p = Promise.resolve()
|
|
|
|
|
|
|
|
let isFlushing = false
|
|
|
|
|
|
|
|
export function nextTick(fn?: () => void): Promise<void> {
|
|
|
|
return fn ? p.then(fn) : p
|
|
|
|
}
|
|
|
|
|
2019-08-30 19:15:23 +00:00
|
|
|
export function queueJob(job: () => void) {
|
2019-05-28 09:19:47 +00:00
|
|
|
if (queue.indexOf(job) === -1) {
|
|
|
|
queue.push(job)
|
2019-08-30 19:15:23 +00:00
|
|
|
if (!isFlushing) {
|
|
|
|
nextTick(flushJobs)
|
|
|
|
}
|
2019-05-28 09:19:47 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-08-30 19:15:23 +00:00
|
|
|
export function queuePostFlushCb(cb: Function | Function[]) {
|
2019-05-28 11:36:15 +00:00
|
|
|
if (Array.isArray(cb)) {
|
2019-05-28 11:59:54 +00:00
|
|
|
postFlushCbs.push.apply(postFlushCbs, cb)
|
2019-05-28 11:36:15 +00:00
|
|
|
} else {
|
2019-05-28 11:59:54 +00:00
|
|
|
postFlushCbs.push(cb)
|
2019-05-28 09:19:47 +00:00
|
|
|
}
|
2019-08-19 18:44:52 +00:00
|
|
|
if (!isFlushing) {
|
2019-08-30 19:15:23 +00:00
|
|
|
nextTick(flushJobs)
|
2019-08-19 18:44:52 +00:00
|
|
|
}
|
2019-05-28 09:19:47 +00:00
|
|
|
}
|
|
|
|
|
2019-05-28 11:36:15 +00:00
|
|
|
const dedupe = (cbs: Function[]): Function[] => Array.from(new Set(cbs))
|
|
|
|
|
2019-05-28 09:19:47 +00:00
|
|
|
export function flushPostFlushCbs() {
|
2019-05-28 11:36:15 +00:00
|
|
|
if (postFlushCbs.length) {
|
|
|
|
const cbs = dedupe(postFlushCbs)
|
|
|
|
postFlushCbs.length = 0
|
|
|
|
for (let i = 0; i < cbs.length; i++) {
|
|
|
|
cbs[i]()
|
|
|
|
}
|
2019-05-28 09:19:47 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const RECURSION_LIMIT = 100
|
|
|
|
type JobCountMap = Map<Function, number>
|
|
|
|
|
|
|
|
function flushJobs(seenJobs?: JobCountMap) {
|
|
|
|
isFlushing = true
|
|
|
|
let job
|
|
|
|
if (__DEV__) {
|
|
|
|
seenJobs = seenJobs || new Map()
|
|
|
|
}
|
|
|
|
while ((job = queue.shift())) {
|
|
|
|
if (__DEV__) {
|
|
|
|
const seen = seenJobs as JobCountMap
|
|
|
|
if (!seen.has(job)) {
|
|
|
|
seen.set(job, 1)
|
|
|
|
} else {
|
|
|
|
const count = seen.get(job) as number
|
|
|
|
if (count > RECURSION_LIMIT) {
|
|
|
|
throw new Error(
|
|
|
|
'Maximum recursive updates exceeded. ' +
|
|
|
|
"You may have code that is mutating state in your component's " +
|
|
|
|
'render function or updated hook.'
|
|
|
|
)
|
|
|
|
} else {
|
|
|
|
seen.set(job, count + 1)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2019-08-30 19:15:23 +00:00
|
|
|
try {
|
|
|
|
job()
|
|
|
|
} catch (err) {
|
|
|
|
handleError(err, null, ErrorTypes.SCHEDULER)
|
|
|
|
}
|
2019-05-28 09:19:47 +00:00
|
|
|
}
|
|
|
|
flushPostFlushCbs()
|
|
|
|
isFlushing = false
|
|
|
|
// some postFlushCb queued jobs!
|
|
|
|
// keep flushing until it drains.
|
|
|
|
if (queue.length) {
|
|
|
|
flushJobs(seenJobs)
|
|
|
|
}
|
|
|
|
}
|