| 1 | |
| 2 | |
| 3 | export class TranscriptTestClock { |
| 4 | time = 0; |
| 5 | private sequence = 0; |
| 6 | frames = new Map<number, FrameRequestCallback>(); |
| 7 | timers = new Map<number, { at: number; callback: () => void }>(); |
| 8 | now = () => this.time; |
| 9 | requestAnimationFrame = (callback: FrameRequestCallback) => { |
| 10 | const id = ++this.sequence; |
| 11 | this.frames.set(id, callback); |
| 12 | return id; |
| 13 | }; |
| 14 | cancelAnimationFrame = (id: number) => { this.frames.delete(id); }; |
| 15 | setTimeout = (callback: () => void, delay: number) => { |
| 16 | const id = ++this.sequence; |
| 17 | this.timers.set(id, { at: this.time + delay, callback }); |
| 18 | return id as unknown as ReturnType<typeof setTimeout>; |
| 19 | }; |
| 20 | clearTimeout = (id: ReturnType<typeof setTimeout>) => { this.timers.delete(id as unknown as number); }; |
| 21 | flushFrames() { |
| 22 | const frames = [...this.frames.values()]; |
| 23 | this.frames.clear(); |
| 24 | frames.forEach((callback) => callback(this.time)); |
| 25 | } |
| 26 | advance(ms: number) { |
| 27 | this.time += ms; |
| 28 | const ready = [...this.timers].filter(([, timer]) => timer.at <= this.time); |
| 29 | ready.forEach(([id, timer]) => { this.timers.delete(id); timer.callback(); }); |
| 30 | this.flushFrames(); |
| 31 | } |
| 32 | } |
| 33 |