| 1 |
import { Subscription } from '../Subscription'; |
| 2 |
|
| 3 |
interface AnimationFrameProvider { |
| 4 |
schedule(callback: FrameRequestCallback): Subscription; |
| 5 |
requestAnimationFrame: typeof requestAnimationFrame; |
| 6 |
cancelAnimationFrame: typeof cancelAnimationFrame; |
| 7 |
delegate: |
| 8 |
| { |
| 9 |
requestAnimationFrame: typeof requestAnimationFrame; |
| 10 |
cancelAnimationFrame: typeof cancelAnimationFrame; |
| 11 |
} |
| 12 |
| undefined; |
| 13 |
} |
| 14 |
|
| 15 |
export const animationFrameProvider: AnimationFrameProvider = { |
| 16 |
// When accessing the delegate, use the variable rather than `this` so that |
| 17 |
// the functions can be called without being bound to the provider. |
| 18 |
schedule(callback) { |
| 19 |
let request = requestAnimationFrame; |
| 20 |
let cancel: typeof cancelAnimationFrame | undefined = cancelAnimationFrame; |
| 21 |
const { delegate } = animationFrameProvider; |
| 22 |
if (delegate) { |
| 23 |
request = delegate.requestAnimationFrame; |
| 24 |
cancel = delegate.cancelAnimationFrame; |
| 25 |
} |
| 26 |
const handle = request((timestamp) => { |
| 27 |
// Clear the cancel function. The request has been fulfilled, so |
| 28 |
// attempting to cancel the request upon unsubscription would be |
| 29 |
// pointless. |
| 30 |
cancel = undefined; |
| 31 |
callback(timestamp); |
| 32 |
}); |
| 33 |
return new Subscription(() => cancel?.(handle)); |
| 34 |
}, |
| 35 |
requestAnimationFrame(...args) { |
| 36 |
const { delegate } = animationFrameProvider; |
| 37 |
return (delegate?.requestAnimationFrame || requestAnimationFrame)(...args); |
| 38 |
}, |
| 39 |
cancelAnimationFrame(...args) { |
| 40 |
const { delegate } = animationFrameProvider; |
| 41 |
return (delegate?.cancelAnimationFrame || cancelAnimationFrame)(...args); |
| 42 |
}, |
| 43 |
delegate: undefined, |
| 44 |
}; |