|
|
import { raf } from '@react-spring/rafz' |
|
|
import * as G from './globals' |
|
|
|
|
|
export interface OpaqueAnimation { |
|
|
idle: boolean |
|
|
priority: number |
|
|
advance(dt: number): void |
|
|
} |
|
|
|
|
|
|
|
|
const startQueue = new Set<OpaqueAnimation>() |
|
|
|
|
|
|
|
|
|
|
|
let currentFrame: OpaqueAnimation[] = [] |
|
|
let prevFrame: OpaqueAnimation[] = [] |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
let priority = 0 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export const frameLoop = { |
|
|
get idle() { |
|
|
return !startQueue.size && !currentFrame.length |
|
|
}, |
|
|
|
|
|
|
|
|
start(animation: OpaqueAnimation) { |
|
|
|
|
|
|
|
|
if (priority > animation.priority) { |
|
|
startQueue.add(animation) |
|
|
raf.onStart(flushStartQueue) |
|
|
} else { |
|
|
startSafely(animation) |
|
|
raf(advance) |
|
|
} |
|
|
}, |
|
|
|
|
|
|
|
|
advance, |
|
|
|
|
|
|
|
|
sort(animation: OpaqueAnimation) { |
|
|
if (priority) { |
|
|
raf.onFrame(() => frameLoop.sort(animation)) |
|
|
} else { |
|
|
const prevIndex = currentFrame.indexOf(animation) |
|
|
if (~prevIndex) { |
|
|
currentFrame.splice(prevIndex, 1) |
|
|
startUnsafely(animation) |
|
|
} |
|
|
} |
|
|
}, |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
clear() { |
|
|
currentFrame = [] |
|
|
startQueue.clear() |
|
|
}, |
|
|
} |
|
|
|
|
|
function flushStartQueue() { |
|
|
startQueue.forEach(startSafely) |
|
|
startQueue.clear() |
|
|
raf(advance) |
|
|
} |
|
|
|
|
|
function startSafely(animation: OpaqueAnimation) { |
|
|
if (!currentFrame.includes(animation)) startUnsafely(animation) |
|
|
} |
|
|
|
|
|
function startUnsafely(animation: OpaqueAnimation) { |
|
|
currentFrame.splice( |
|
|
findIndex(currentFrame, other => other.priority > animation.priority), |
|
|
0, |
|
|
animation |
|
|
) |
|
|
} |
|
|
|
|
|
function advance(dt: number) { |
|
|
const nextFrame = prevFrame |
|
|
|
|
|
for (let i = 0; i < currentFrame.length; i++) { |
|
|
const animation = currentFrame[i] |
|
|
priority = animation.priority |
|
|
|
|
|
|
|
|
if (!animation.idle) { |
|
|
G.willAdvance(animation) |
|
|
animation.advance(dt) |
|
|
if (!animation.idle) { |
|
|
nextFrame.push(animation) |
|
|
} |
|
|
} |
|
|
} |
|
|
priority = 0 |
|
|
|
|
|
|
|
|
prevFrame = currentFrame |
|
|
prevFrame.length = 0 |
|
|
|
|
|
|
|
|
|
|
|
currentFrame = nextFrame |
|
|
|
|
|
return currentFrame.length > 0 |
|
|
} |
|
|
|
|
|
|
|
|
function findIndex<T>(arr: T[], test: (value: T) => boolean) { |
|
|
const index = arr.findIndex(test) |
|
|
return index < 0 ? arr.length : index |
|
|
} |
|
|
|