All files / owid-grapher/grapher/timeline TimelineComponent.tsx

60.97% Statements 189/310
76.19% Branches 16/21
33.33% Functions 8/24
60.97% Lines 189/310

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 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 3631x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x     12x 12x 12x 12x 12x 12x 12x 12x 12x 12x         12x 12x 12x 12x 12x                   12x 12x               12x 12x                           12x 12x                                 12x 12x                                     12x 12x 12x                   12x 12x                         12x 12x 12x                 12x 12x             12x 12x   12x 12x   12x 12x 12x         12x 12x     12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 48x 16x 16x 48x 12x 12x 24x 24x 24x 24x 24x 24x 24x     24x 24x 24x 24x 24x 24x 24x 12x 12x 12x 12x 12x 12x     12x 12x         12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 10x 10x 10x 10x 10x 10x   10x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x                                                                                                          
import * as React from "react"
import { select } from "d3-selection"
import { getRelativeMouse, isMobile, debounce } from "../../clientUtils/Util"
import { Bounds } from "../../clientUtils/Bounds"
import { observable, computed, action } from "mobx"
import { observer } from "mobx-react"
import { faPlay } from "@fortawesome/free-solid-svg-icons/faPlay"
import { faPause } from "@fortawesome/free-solid-svg-icons/faPause"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import Tippy from "@tippyjs/react"
import classNames from "classnames"
import { TimelineController, TimelineManager } from "./TimelineController"
import { timeFromTimebounds } from "../../clientUtils/TimeBounds"
 
const HANDLE_TOOLTIP_FADE_TIME_MS = 2000
 
@observer
export class TimelineComponent extends React.Component<{
    timelineController: TimelineController
}> {
    base: React.RefObject<HTMLDivElement> = React.createRef()
 
    @observable private dragTarget?: "start" | "end" | "both"
 
    @computed private get isDragging(): boolean {
        return !!this.dragTarget
    }
 
    @computed private get manager(): TimelineManager {
        return this.props.timelineController.manager
    }
 
    @computed private get controller(): TimelineController {
        return this.props.timelineController
    }
 
    private get sliderBounds(): Bounds {
        return this.slider
            ? Bounds.fromRect(this.slider.getBoundingClientRect())
            : new Bounds(0, 0, 100, 100)
    }
 
    private slider?: Element | HTMLElement | null
    private playButton?: Element | HTMLElement | null
 
    private getInputTimeFromMouse(
        event: MouseEvent | TouchEvent
    ): number | undefined {
        const { minTime, maxTime } = this.controller
        if (!this.slider) return
        const mouseX = getRelativeMouse(this.slider, event).x

        const fracWidth = mouseX / this.sliderBounds.width
        return minTime + fracWidth * (maxTime - minTime)
    }
 
    @action.bound private onDrag(inputTime: number): void {
        if (!this.manager.isPlaying) this.manager.userHasSetTimeline = true
        this.dragTarget = this.controller.dragHandleToTime(
            this.dragTarget!,
            inputTime
        )
        this.showTooltips()
    }
 
    @action.bound private showTooltips(): void {
        this.hideStartTooltip.cancel()
        this.hideEndTooltip.cancel()
        this.startTooltipVisible = true
        this.endTooltipVisible = true

        if (this.dragTarget === "start") this.lastUpdatedTooltip = "startMarker"
        if (this.dragTarget === "end") this.lastUpdatedTooltip = "endMarker"
        if (this.manager.startHandleTimeBound > this.manager.endHandleTimeBound)
            this.lastUpdatedTooltip =
                this.lastUpdatedTooltip === "startMarker"
                    ? "endMarker"
                    : "startMarker"
    }
 
    private getDragTarget(
        inputTime: number,
        isStartMarker: boolean,
        isEndMarker: boolean
    ): "both" | "start" | "end" {
        const { startHandleTimeBound, endHandleTimeBound } = this.manager

        if (
            startHandleTimeBound === endHandleTimeBound &&
            (isStartMarker || isEndMarker)
        )
            return "both"
        else if (isStartMarker || inputTime <= startHandleTimeBound)
            return "start"
        else if (isEndMarker || inputTime >= endHandleTimeBound) return "end"
        return "both"
    }
 
    @action.bound private onMouseDown(event: any): void {
        const logic = this.controller
        const targetEl = select(event.target)

        const inputTime = this.getInputTimeFromMouse(event)

        if (!inputTime) return

        this.dragTarget = this.getDragTarget(
            inputTime,
            targetEl.classed("startMarker"),
            targetEl.classed("endMarker")
        )

        if (this.dragTarget === "both") logic.setDragOffsets(inputTime)

        this.onDrag(inputTime)
        event.preventDefault()
    }
 
    private queuedDrag?: boolean
    @action.bound private onMouseMove(event: MouseEvent | TouchEvent): void {
        const { dragTarget } = this
        if (!dragTarget) return
        if (this.queuedDrag) return

        this.queuedDrag = true
        const inputTime = this.getInputTimeFromMouse(event)
        if (inputTime) this.onDrag(inputTime)
        this.queuedDrag = false
    }
 
    @action.bound private onMouseUp(): void {
        this.dragTarget = undefined

        if (this.manager.isPlaying) return

        if (isMobile()) {
            if (this.startTooltipVisible) this.hideStartTooltip()
            if (this.endTooltipVisible) this.hideEndTooltip()
        } else if (!this.mouseHoveringOverTimeline) {
            this.startTooltipVisible = false
            this.endTooltipVisible = false
        }
    }
 
    private mouseHoveringOverTimeline: boolean = false
    @action.bound private onMouseOver(): void {
        this.mouseHoveringOverTimeline = true

        this.hideStartTooltip.cancel()
        this.startTooltipVisible = true

        this.hideEndTooltip.cancel()
        this.endTooltipVisible = true
    }
 
    @action.bound private onMouseLeave(): void {
        if (!this.manager.isPlaying && !this.isDragging) {
            this.startTooltipVisible = false
            this.endTooltipVisible = false
        }
        this.mouseHoveringOverTimeline = false
    }
 
    private hideStartTooltip = debounce(() => {
        this.startTooltipVisible = false
    }, HANDLE_TOOLTIP_FADE_TIME_MS)
    private hideEndTooltip = debounce(() => {
        this.endTooltipVisible = false
    }, HANDLE_TOOLTIP_FADE_TIME_MS)
 
    @action.bound onPlayTouchEnd(evt: Event): void {
        evt.preventDefault()
        evt.stopPropagation()
        this.controller.togglePlay()
    }
 
    @computed private get isPlayingOrDragging(): boolean {
        return this.manager.isPlaying || this.isDragging
    }
 
    componentDidMount(): void {
        const current = this.base.current
 
        if (current) {
            this.slider = current.querySelector(".slider")
            this.playButton = current.querySelector(".play")
        }
 
        document.documentElement.addEventListener("mouseup", this.onMouseUp)
        document.documentElement.addEventListener("mouseleave", this.onMouseUp)
        document.documentElement.addEventListener("mousemove", this.onMouseMove)
        document.documentElement.addEventListener("touchend", this.onMouseUp)
        document.documentElement.addEventListener("touchmove", this.onMouseMove)
        this.slider?.addEventListener("touchstart", this.onMouseDown, {
            passive: false,
        })
        this.playButton?.addEventListener("touchend", this.onPlayTouchEnd, {
            passive: false,
        })
    }
 
    componentWillUnmount(): void {
        document.documentElement.removeEventListener("mouseup", this.onMouseUp)
        document.documentElement.removeEventListener(
            "mouseleave",
            this.onMouseUp
        )
        document.documentElement.removeEventListener(
            "mousemove",
            this.onMouseMove
        )
        document.documentElement.removeEventListener("touchend", this.onMouseUp)
        document.documentElement.removeEventListener(
            "touchmove",
            this.onMouseMove
        )
        this.slider?.removeEventListener("touchstart", this.onMouseDown, {
            passive: false,
        } as EventListenerOptions)
        this.playButton?.removeEventListener("touchend", this.onPlayTouchEnd, {
            passive: false,
        } as EventListenerOptions)
    }
 
    private formatTime(time: number): string {
        return this.manager.formatTimeFn
            ? this.manager.formatTimeFn(time)
            : time.toString()
    }
 
    private timelineEdgeMarker(markerType: "start" | "end"): JSX.Element {
        const { controller } = this
        const time =
            markerType === "start" ? controller.minTime : controller.maxTime
        return (
            <div
                className="date clickable"
                onClick={(): void =>
                    markerType === "start"
                        ? controller.resetStartToMin()
                        : controller.resetEndToMax()
                }
            >
                {this.formatTime(time)}
            </div>
        )
    }
 
    @observable private startTooltipVisible: boolean = false
    @observable private endTooltipVisible: boolean = false
    @observable private lastUpdatedTooltip?: "startMarker" | "endMarker"
 
    @action.bound private togglePlay(): void {
        this.controller.togglePlay()
    }
 
    convertToTime(time: number): number {
        if (time === -Infinity) return this.controller.minTime
        if (time === +Infinity) return this.controller.maxTime
        return time
    }
 
    render(): JSX.Element {
        const { manager, controller } = this
        const { startTimeProgress, endTimeProgress, minTime, maxTime } =
            controller
        const { startHandleTimeBound, endHandleTimeBound } = manager
 
        const formattedStartTime = this.formatTime(
            timeFromTimebounds(startHandleTimeBound, minTime)
        )
        const formattedEndTime = this.formatTime(
            timeFromTimebounds(endHandleTimeBound, maxTime)
        )
 
        return (
            <div
                ref={this.base}
                className="TimelineComponent"
                onMouseOver={this.onMouseOver}
                onMouseLeave={this.onMouseLeave}
            >
                {!this.manager.disablePlay && (
                    <div
                        onMouseDown={(e) => e.stopPropagation()}
                        onClick={this.togglePlay}
                        className="play"
                    >
                        {manager.isPlaying ? (
                            <FontAwesomeIcon icon={faPause} />
                        ) : (
                            <FontAwesomeIcon icon={faPlay} />
                        )}
                    </div>
                )}
                {this.timelineEdgeMarker("start")}
                <div
                    className="slider clickable"
                    onMouseDown={this.onMouseDown}
                >
                    <TimelineHandle
                        type="startMarker"
                        offsetPercent={startTimeProgress * 100}
                        tooltipContent={formattedStartTime}
                        tooltipVisible={this.startTooltipVisible}
                        tooltipZIndex={
                            this.lastUpdatedTooltip === "startMarker" ? 2 : 1
                        }
                    />
                    <div
                        className="interval"
                        style={{
                            left: `${startTimeProgress * 100}%`,
                            right: `${100 - endTimeProgress * 100}%`,
                        }}
                    />
                    <TimelineHandle
                        type="endMarker"
                        offsetPercent={endTimeProgress * 100}
                        tooltipContent={formattedEndTime}
                        tooltipVisible={this.endTooltipVisible}
                        tooltipZIndex={
                            this.lastUpdatedTooltip === "endMarker" ? 2 : 1
                        }
                    />
                </div>
                {this.timelineEdgeMarker("end")}
            </div>
        )
    }
}
 
const TimelineHandle = ({
    type,
    offsetPercent,
    tooltipContent,
    tooltipVisible,
    tooltipZIndex,
}: {
    type: "startMarker" | "endMarker"
    offsetPercent: number
    tooltipContent: string
    tooltipVisible: boolean
    tooltipZIndex: number
}) => {
    return (
        <div
            className={classNames("handle", type)}
            style={{
                left: `${offsetPercent}%`,
            }}
        >
            <Tippy
                content={<span>{tooltipContent}</span>}
                visible={tooltipVisible}
                zIndex={tooltipZIndex}
            >
                <div className="icon" />
            </Tippy>
        </div>
    )
}