All files / owid-grapher/grapher/timeline TimelineController.ts

79.89% Statements 143/179
86.67% Branches 26/30
80.95% Functions 17/21
79.89% Lines 143/179

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 2121x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 218x 218x 1x 1x 6x 6x 6x 1x 1x 12x 12x 12x 12x 12x 1x 1x 2x 2x 1x 1x 72x 72x 1x 1x 2x 2x 1x 1x 12x 12x 1x 1x 12x 12x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 1x 1x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x       1x 1x 1x 1x               1x 1x 7x 7x 5x 5x 7x 7x 1x 1x                                           1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x   3x 2x 2x 3x                                                                  
import { Time } from "../../coreTable/CoreTableConstants"
import { TimeBound, TimeBoundValue } from "../../clientUtils/TimeBounds"
import { findClosestTime, last } from "../../clientUtils/Util"
 
export interface TimelineManager {
    disablePlay?: boolean
    formatTimeFn?: (time: Time) => string
    isPlaying?: boolean
    userHasSetTimeline?: boolean
    times: Time[]
    startHandleTimeBound: TimeBound
    endHandleTimeBound: TimeBound
    msPerTick?: number
    onPlay?: () => void
}
 
const delay = (ms: number): Promise<void> =>
    new Promise((resolve) => setTimeout(resolve, ms))
 
export class TimelineController {
    manager: TimelineManager
 
    constructor(manager: TimelineManager) {
        this.manager = manager
    }
 
    private get timesAsc(): number[] {
        // Note: assumes times is sorted in asc
        return this.manager.times
    }
 
    private get startTime(): number {
        return findClosestTime(
            this.timesAsc,
            this.manager.startHandleTimeBound
        )!
    }
 
    private get endTime(): number {
        return findClosestTime(this.timesAsc, this.manager.endHandleTimeBound)!
    }
 
    get minTime(): number {
        return this.timesAsc[0]
    }
 
    get maxTime(): number {
        return last(this.timesAsc)!
    }
 
    get startTimeProgress(): number {
        return (this.startTime - this.minTime) / (this.maxTime - this.minTime)
    }
 
    get endTimeProgress(): number {
        return (this.endTime - this.minTime) / (this.maxTime - this.minTime)
    }
 
    getNextTime(time: number): number {
        // Todo: speed up?
        return this.timesAsc[this.timesAsc.indexOf(time) + 1] ?? this.maxTime
    }
 
    // By default, play means extend the endTime to the right. Toggle this to play one time unit at a time.
    private rangeMode = true
    toggleRangeMode(): this {
        this.rangeMode = !this.rangeMode
        return this
    }
 
    private isAtEnd(): boolean {
        return this.endTime === this.maxTime
    }
 
    private resetToBeginning(): void {
        const { manager } = this
        const beginning =
            manager.endHandleTimeBound !== manager.startHandleTimeBound
                ? manager.startHandleTimeBound
                : this.minTime
        manager.endHandleTimeBound = beginning
        manager.startHandleTimeBound = beginning
    }
 
    async play(numberOfTicks?: number): Promise<number> {
        const { manager } = this
        manager.isPlaying = true
 
        if (this.isAtEnd()) this.resetToBeginning()
 
        if (manager.onPlay) manager.onPlay()
 
        // Keep and return a tickCount for easier testability
        let tickCount = 0
        while (manager.isPlaying) {
            const nextTime = this.getNextTime(this.endTime)
            if (!this.rangeMode) this.updateStartTime(nextTime)
            this.updateEndTime(nextTime)
            tickCount++
            if (nextTime >= this.maxTime || numberOfTicks === tickCount) {
                this.stop()
                break
            }
            await delay(manager.msPerTick ?? 0)
        }
 
        return tickCount
    }
 
    private stop(): void {
        this.manager.isPlaying = false
    }
 
    private pause(): void {
        this.manager.isPlaying = false
    }
 
    async togglePlay(): Promise<void> {
        if (this.manager.isPlaying) this.pause()
        else await this.play()
    }
 
    private dragOffsets: [number, number] = [0, 0]
 
    setDragOffsets(inputTime: number): void {
        const closestTime =
            findClosestTime(this.timesAsc, inputTime) ?? inputTime
        this.dragOffsets = [
            this.startTime - closestTime,
            this.endTime - closestTime,
        ]
    }
 
    getTimeBoundFromDrag(inputTime: Time): TimeBound {
        if (inputTime < this.minTime) return TimeBoundValue.negativeInfinity
        if (inputTime > this.maxTime) return TimeBoundValue.positiveInfinity
        const closestTime =
            findClosestTime(this.timesAsc, inputTime) ?? inputTime
        return Math.min(this.maxTime, Math.max(this.minTime, closestTime))
    }
 
    private dragRangeToTime(time: Time): void {
        const { minTime, maxTime } = this
        const closestTime = findClosestTime(this.timesAsc, time) ?? time

        let startTime = this.dragOffsets[0] + closestTime
        let endTime = this.dragOffsets[1] + closestTime

        if (startTime < minTime) {
            startTime = minTime
            endTime = this.getTimeBoundFromDrag(
                minTime + (this.dragOffsets[1] - this.dragOffsets[0])
            )
        } else if (endTime > maxTime) {
            startTime = this.getTimeBoundFromDrag(
                maxTime + (this.dragOffsets[0] - this.dragOffsets[1])
            )
            endTime = maxTime
        }

        this.updateStartTime(startTime)
        this.updateEndTime(endTime)
    }
 
    dragHandleToTime(
        handle: "start" | "end" | "both",
        inputTime: number
    ): "start" | "end" | "both" {
        const { manager } = this
 
        const time = this.getTimeBoundFromDrag(inputTime)
 
        const constrainedHandle =
            handle === "start" && time > this.endTime
                ? "end"
                : handle === "end" && time < this.startTime
                ? "start"
                : handle
 
        if (constrainedHandle !== handle) {
            if (handle === "start")
                this.updateStartTime(manager.endHandleTimeBound)
            else this.updateEndTime(manager.startHandleTimeBound)
        }
 
        if (manager.isPlaying && !this.rangeMode) {
            this.updateStartTime(time)
            this.updateEndTime(time)
        } else if (handle === "both") this.dragRangeToTime(inputTime)
        else if (constrainedHandle === "start") this.updateStartTime(time)
        else if (constrainedHandle === "end") this.updateEndTime(time)
 
        return constrainedHandle
    }
 
    private updateStartTime(timeBound: TimeBound): void {
        this.manager.startHandleTimeBound = timeBound
    }
 
    private updateEndTime(timeBound: TimeBound): void {
        this.manager.endHandleTimeBound = timeBound
    }
 
    resetStartToMin(): void {
        this.updateStartTime(TimeBoundValue.negativeInfinity)
    }
 
    resetEndToMax(): void {
        this.updateEndTime(TimeBoundValue.positiveInfinity)
    }
}