All files / owid-grapher/grapher/scatterCharts ScatterPointsWithLabels.tsx

88.86% Statements 351/395
92.96% Branches 66/71
88.46% Functions 23/26
88.86% Lines 351/395

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 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 5781x 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 1x 1x 1x 1x 1x 1x 1x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 1x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 432x 4000x 4000x 4000x 3980x 3980x 4000x 4000x 4000x 4000x 4000x 4000x 4000x 4000x 4000x 4000x 4000x 4000x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 432x 432x 432x 432x 432x 15x 15x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 432x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 14x 14x 14x 14x 15x 15x 15x 15x 15x 459x 459x 179x 459x 2776x 2776x 1563x 1563x 1563x 1317x 1317x 1317x 1317x 1317x 1317x 2776x 2776x 2776x 1317x 1317x 1317x 246x 246x 246x 246x 246x 246x 246x 246x 2776x 2776x 2776x 52x 52x 2776x 179x 15x 15x 15x 15x 15x 15x 15x 15x 459x 459x 454x 454x 454x 459x 459x 459x 459x 459x 459x 448x 459x 459x 459x 459x 15x 15x 15x 15x         15x 15x                                                                           15x 15x     15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x   15x 230x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 230x 230x 230x 2x 2x 2x 230x 230x 230x 230x 230x 230x 230x 230x 230x 230x 230x 230x 230x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 202x 202x 202x                                                                                                                                                                                                                                                                                                                                                                              
import { scaleLinear } from "d3-scale"
import { select } from "d3-selection"
import { NoDataModal } from "../noDataModal/NoDataModal"
import { SortOrder } from "../../coreTable/CoreTableConstants"
import { Bounds } from "../../clientUtils/Bounds"
import { PointVector } from "../../clientUtils/PointVector"
import {
    sortNumeric,
    makeSafeForCSS,
    getRelativeMouse,
    intersection,
    last,
    flatten,
    minBy,
    min,
    first,
    isEmpty,
    guid,
} from "../../clientUtils/Util"
import { computed, action } from "mobx"
import { observer } from "mobx-react"
import React from "react"
import { getElementWithHalo } from "./Halos"
import { MultiColorPolyline } from "./MultiColorPolyline"
import {
    ScatterPointsWithLabelsProps,
    ScatterRenderSeries,
    ScatterLabel,
    ScatterRenderPoint,
    ScatterLabelFontFamily,
    ScatterSeries,
} from "./ScatterPlotChartConstants"
import { ScatterLine, ScatterPoint } from "./ScatterPoints"
import {
    makeStartLabel,
    makeMidLabels,
    makeEndLabel,
    labelPriority,
} from "./ScatterUtils"
import { Triangle } from "./Triangle"
import { ColorScale } from "../color/ColorScale"
import { ScaleLinear } from "d3-scale"
 
// This is the component that actually renders the points. The higher level ScatterPlot class renders points, legends, comparison lines, etc.
@observer
export class ScatterPointsWithLabels extends React.Component<ScatterPointsWithLabelsProps> {
    base: React.RefObject<SVGGElement> = React.createRef()
    @computed private get seriesArray(): ScatterSeries[] {
        return this.props.seriesArray
    }
 
    @computed private get isConnected(): boolean {
        return this.seriesArray.some((g) => g.points.length > 1)
    }
 
    @computed private get focusedSeriesNames(): string[] {
        return intersection(
            this.props.focusedSeriesNames || [],
            this.seriesArray.map((g) => g.seriesName)
        )
    }
 
    @computed private get hoveredSeriesNames(): string[] {
        return this.props.hoveredSeriesNames
    }
 
    // Layered mode occurs when any entity on the chart is hovered or focused
    // Then, a special "foreground" set of entities is rendered over the background
    @computed private get isLayerMode(): boolean {
        return (
            this.focusedSeriesNames.length > 0 ||
            this.hoveredSeriesNames.length > 0
        )
    }
 
    @computed private get bounds(): Bounds {
        return this.props.dualAxis.innerBounds
    }
 
    // When focusing multiple entities, we hide some information to declutter
    @computed private get isSubtleForeground(): boolean {
        return (
            this.focusedSeriesNames.length > 1 &&
            this.props.seriesArray.some((series) => series.points.length > 2)
        )
    }
 
    @computed private get colorScale(): ColorScale | undefined {
        return this.props.colorScale
    }
 
    @computed private get sizeScale(): ScaleLinear<number, number> {
        const sizeScale = scaleLinear()
            .range([10, 1000])
            .domain(this.props.sizeDomain)
        return sizeScale
    }
 
    @computed private get fontScale(): (d: number) => number {
        return scaleLinear().range([10, 13]).domain(this.sizeScale.domain())
    }
 
    @computed private get hideConnectedScatterLines(): boolean {
        return this.props.hideConnectedScatterLines
    }
 
    // Pre-transform data for rendering
    @computed private get initialRenderSeries(): ScatterRenderSeries[] {
        const { seriesArray, sizeScale, fontScale, colorScale, bounds } = this
        const xAxis = this.props.dualAxis.horizontalAxis.clone()
        xAxis.range = bounds.xRange()
        const yAxis = this.props.dualAxis.verticalAxis.clone()
        yAxis.range = this.bounds.yRange()
 
        return sortNumeric(
            seriesArray.map((series) => {
                const points = series.points.map((point) => {
                    const area = sizeScale(point.size || 4)
                    const scaleColor =
                        colorScale !== undefined
                            ? colorScale.getColor(point.color)
                            : undefined
                    return {
                        position: new PointVector(
                            Math.floor(xAxis.place(point.x)),
                            Math.floor(yAxis.place(point.y))
                        ),
                        color: scaleColor ?? series.color,
                        size: Math.sqrt(area / Math.PI),
                        fontSize: fontScale(series.size || 1),
                        time: point.time,
                        label: point.label,
                    }
                })
 
                return {
                    seriesName: series.seriesName,
                    displayKey: "key-" + makeSafeForCSS(series.seriesName),
                    color: series.color,
                    size: (last(points) as any).size,
                    points,
                    text: series.label,
                    midLabels: [],
                    allLabels: [],
                    offsetVector: PointVector.zero,
                }
            }),
            (d) => d.size,
            SortOrder.desc
        )
    }
 
    @computed private get renderSeries(): ScatterRenderSeries[] {
        // Draw the largest points first so that smaller ones can sit on top of them
        const renderData = this.initialRenderSeries
 
        for (const series of renderData) {
            series.isHover = this.hoveredSeriesNames.includes(series.seriesName)
            series.isFocus = this.focusedSeriesNames.includes(series.seriesName)
            series.isForeground = series.isHover || series.isFocus
            if (series.isHover) series.size += 1
        }
 
        for (const series of renderData) {
            series.startLabel = makeStartLabel(
                series,
                this.isSubtleForeground,
                this.hideConnectedScatterLines
            )
            series.midLabels = makeMidLabels(
                series,
                this.isSubtleForeground,
                this.hideConnectedScatterLines
            )
            series.endLabel = makeEndLabel(
                series,
                this.isSubtleForeground,
                this.hideConnectedScatterLines
            )
            series.allLabels = [series.startLabel]
                .concat(series.midLabels)
                .concat([series.endLabel])
                .filter((x) => x) as ScatterLabel[]
        }
 
        const labels = flatten(renderData.map((series) => series.allLabels))
 
        // Ensure labels fit inside bounds
        // Must do before collision detection since it'll change the positions
        this.moveLabelsInsideChartBounds(labels, this.bounds)
 
        const labelsByPriority = sortNumeric(
            labels,
            (l) => labelPriority(l),
            SortOrder.desc
        )
        if (this.focusedSeriesNames.length > 0)
            this.hideUnselectedLabels(labelsByPriority)
 
        this.hideCollidingLabelsByPriority(labelsByPriority)
 
        return renderData
    }
 
    private hideUnselectedLabels(labelsByPriority: ScatterLabel[]): void {
        labelsByPriority
            .filter((label) => !label.series.isFocus && !label.series.isHover)
            .forEach((label) => (label.isHidden = true))
    }
 
    private hideCollidingLabelsByPriority(
        labelsByPriority: ScatterLabel[]
    ): void {
        for (let i = 0; i < labelsByPriority.length; i++) {
            const higherPriorityLabel = labelsByPriority[i]
            if (higherPriorityLabel.isHidden) continue
 
            for (let j = i + 1; j < labelsByPriority.length; j++) {
                const lowerPriorityLabel = labelsByPriority[j]
                if (lowerPriorityLabel.isHidden) continue
 
                const isHighlightedEndLabelOfEqualPriority =
                    lowerPriorityLabel.isEnd &&
                    (lowerPriorityLabel.series.isHover ||
                        lowerPriorityLabel.series.isFocus) &&
                    higherPriorityLabel.series.isHover ===
                        lowerPriorityLabel.series.isHover &&
                    higherPriorityLabel.series.isFocus ===
                        lowerPriorityLabel.series.isFocus
 
                if (
                    isHighlightedEndLabelOfEqualPriority
                        ? // For highlighted end labels of equal priority, we want to allow some
                          // overlap – labels are still readable even if they overlap
                          higherPriorityLabel.bounds
                              .pad(6) // allow up to 6px of overlap
                              .intersects(lowerPriorityLabel.bounds)
                        : // For non-highlighted labels we want to leave more space between labels,
                          // partly to have a less noisy chart, and partly to prevent readers from
                          // thinking that "everything is labelled". In the past this has made
                          // readers think that if a label doesn't exist, it isn't plotted on the
                          // chart.
                          higherPriorityLabel.bounds
                              .pad(-6)
                              .intersects(lowerPriorityLabel.bounds)
                ) {
                    lowerPriorityLabel.isHidden = true
                }
            }
        }
    }
 
    // todo: move this to bounds class with a test
    private moveLabelsInsideChartBounds(
        labels: ScatterLabel[],
        bounds: Bounds
    ): void {
        for (const label of labels) {
            if (label.bounds.left < bounds.left - 1)
                label.bounds = label.bounds.set({
                    x: label.bounds.x + label.bounds.width,
                })
            else if (label.bounds.right > bounds.right + 1)
                label.bounds = label.bounds.set({
                    x: label.bounds.x - label.bounds.width,
                })
 
            if (label.bounds.top < bounds.top - 1)
                label.bounds = label.bounds.set({ y: bounds.top })
            else if (label.bounds.bottom > bounds.bottom + 1)
                label.bounds = label.bounds.set({
                    y: bounds.bottom - label.bounds.height,
                })
        }
    }
 
    mouseFrame?: number
    @action.bound onMouseLeave(): void {
        if (this.mouseFrame !== undefined) cancelAnimationFrame(this.mouseFrame)

        if (this.props.onMouseLeave) this.props.onMouseLeave()
    }
 
    @action.bound onMouseMove(ev: React.MouseEvent<SVGGElement>): void {
        if (this.mouseFrame !== undefined) cancelAnimationFrame(this.mouseFrame)

        const nativeEvent = ev.nativeEvent

        this.mouseFrame = requestAnimationFrame(() => {
            if (this.base.current) {
                const mouse = getRelativeMouse(this.base.current, nativeEvent)

                const closestSeries = minBy(this.renderSeries, (series) => {
                    if (series.points.length > 1)
                        return min(
                            series.points.slice(0, -1).map((d, i) => {
                                return PointVector.distanceFromPointToLineSq(
                                    mouse,
                                    d.position,
                                    series.points[i + 1].position
                                )
                            })
                        )

                    return min(
                        series.points.map((v) =>
                            PointVector.distanceSq(v.position, mouse)
                        )
                    )
                })

                if (closestSeries && this.props.onMouseOver) {
                    const series = this.seriesArray.find(
                        (series) =>
                            series.seriesName === closestSeries.seriesName
                    )
                    if (series) this.props.onMouseOver(series)
                }
            }
        })
    }
 
    @action.bound onClick(): void {
        if (this.props.onClick) this.props.onClick()
    }
 
    @computed get backgroundSeries(): ScatterRenderSeries[] {
        return this.renderSeries.filter((series) => !series.isForeground)
    }
 
    @computed get foregroundSeries(): ScatterRenderSeries[] {
        return this.renderSeries.filter((series) => !!series.isForeground)
    }
 
    private renderBackgroundSeries(): JSX.Element[] {
        const {
            backgroundSeries,
            isLayerMode,
            isConnected,
            hideConnectedScatterLines,
        } = this
 
        return hideConnectedScatterLines
            ? []
            : backgroundSeries.map((series) => (
                  <ScatterLine
                      key={series.seriesName}
                      series={series}
                      isLayerMode={isLayerMode}
                      isConnected={isConnected}
                  />
              ))
    }
 
    private renderBackgroundLabels(): JSX.Element {
        const { isLayerMode } = this
        return (
            <g
                className="backgroundLabels"
                fill={!isLayerMode ? "#333" : "#aaa"}
            >
                {this.backgroundSeries.map((series) => {
                    return series.allLabels
                        .filter((label) => !label.isHidden)
                        .map((label) =>
                            getElementWithHalo(
                                series.displayKey + "-endLabel",
                                <text
                                    x={label.bounds.x.toFixed(2)}
                                    y={(
                                        label.bounds.y + label.bounds.height
                                    ).toFixed(2)}
                                    fontSize={label.fontSize.toFixed(2)}
                                    fontWeight={label.fontWeight}
                                    fill={isLayerMode ? "#aaa" : label.color}
                                >
                                    {label.text}
                                </text>
                            )
                        )
                })}
            </g>
        )
    }
 
    @computed get renderUid(): number {
        return guid()
    }
 
    private renderForegroundSeries(): JSX.Element[] {
        const { isSubtleForeground, hideConnectedScatterLines } = this
        return this.foregroundSeries.map((series) => {
            const lastValue = last(series.points) as ScatterRenderPoint
            const strokeWidth =
                (hideConnectedScatterLines
                    ? 3
                    : series.isHover
                    ? 3
                    : isSubtleForeground
                    ? 1.5
                    : 2) +
                lastValue.size * 0.05
 
            if (series.points.length === 1)
                return <ScatterPoint key={series.displayKey} series={series} />
 
            const firstValue = first(series.points)
            const opacity = isSubtleForeground ? 0.9 : 1
            const radius = hideConnectedScatterLines
                ? strokeWidth
                : strokeWidth / 2 + 1
            let rotation = PointVector.angle(
                series.offsetVector,
                PointVector.up
            )
            if (series.offsetVector.x < 0) rotation = -rotation
            return (
                <g key={series.displayKey} className={series.displayKey}>
                    {!hideConnectedScatterLines && (
                        <MultiColorPolyline
                            points={series.points.map((point) => ({
                                x: point.position.x,
                                y: point.position.y,
                                color: point.color,
                            }))}
                            strokeWidth={strokeWidth}
                            opacity={opacity}
                        />
                    )}
                    {(series.isFocus || hideConnectedScatterLines) &&
                        firstValue && (
                            <circle
                                cx={firstValue.position.x.toFixed(2)}
                                cy={firstValue.position.y.toFixed(2)}
                                r={radius}
                                fill={firstValue.color}
                                opacity={opacity}
                                stroke={firstValue.color}
                                strokeOpacity={0.6}
                            />
                        )}
                    {(series.isHover || hideConnectedScatterLines) &&
                        series.points
                            .slice(
                                1,
                                hideConnectedScatterLines ? undefined : -1
                            )
                            .map((v, index) => (
                                <circle
                                    key={index}
                                    cx={v.position.x}
                                    cy={v.position.y}
                                    r={radius}
                                    fill={v.color}
                                    stroke="none"
                                />
                            ))}
                    {!hideConnectedScatterLines && (
                        <Triangle
                            transform={`rotate(${rotation}, ${lastValue.position.x.toFixed(
                                2
                            )}, ${lastValue.position.y.toFixed(2)})`}
                            cx={lastValue.position.x}
                            cy={lastValue.position.y}
                            r={strokeWidth * 2}
                            fill={lastValue.color}
                            opacity={opacity}
                        />
                    )}
                </g>
            )
        })
    }
 
    private renderForegroundLabels(): JSX.Element[][] {
        return this.foregroundSeries.map((series) => {
            return series.allLabels
                .filter((label) => !label.isHidden)
                .map((label, index) =>
                    getElementWithHalo(
                        `${series.displayKey}-label-${index}`,
                        <text
                            x={label.bounds.x.toFixed(2)}
                            y={(label.bounds.y + label.bounds.height).toFixed(
                                2
                            )}
                            fontSize={label.fontSize}
                            fontFamily={ScatterLabelFontFamily}
                            fontWeight={label.fontWeight}
                            fill={label.color}
                        >
                            {label.text}
                        </text>
                    )
                )
        })
    }
 
    animSelection?: d3.Selection<
        d3.BaseType,
        unknown,
        SVGGElement | null,
        unknown
    >
 
    private runAnimation(): void {
        const radiuses: string[] = []
        this.animSelection = select(this.base.current).selectAll("circle")
 
        this.animSelection
            .each(function () {
                const circle = this as SVGCircleElement
                radiuses.push(circle.getAttribute("r") as string)
                circle.setAttribute("r", "0")
            })
            .transition()
            .duration(500)
            .attr("r", (_, i) => radiuses[i])
            .on("end", () => this.forceUpdate())
    }
 
    componentDidMount(): void {
        this.runAnimation()
    }
 
    componentWillUnmount(): void {
        if (this.animSelection) this.animSelection.interrupt()
    }
 
    render(): JSX.Element {
        const { bounds, renderSeries, renderUid } = this
        const clipBounds = bounds.pad(-10)
 
        if (isEmpty(renderSeries))
            return (
                <NoDataModal
                    manager={this.props.noDataModalManager}
                    bounds={bounds}
                />
            )
 
        return (
            <g
                ref={this.base}
                className="PointsWithLabels clickable"
                clipPath={`url(#scatterBounds-${renderUid})`}
                onMouseMove={this.onMouseMove}
                onMouseLeave={this.onMouseLeave}
                onClick={this.onClick}
                fontFamily={ScatterLabelFontFamily}
            >
                <rect
                    key="background"
                    x={bounds.x}
                    y={bounds.y}
                    width={bounds.width}
                    height={bounds.height}
                    fill="rgba(255,255,255,0)"
                />
                <defs>
                    <clipPath id={`scatterBounds-${renderUid}`}>
                        <rect
                            x={clipBounds.x}
                            y={clipBounds.y}
                            width={clipBounds.width}
                            height={clipBounds.height}
                        />
                    </clipPath>
                </defs>
                {this.renderBackgroundSeries()}
                {this.renderBackgroundLabels()}
                {this.renderForegroundSeries()}
                {this.renderForegroundLabels()}
            </g>
        )
    }
}