All files / owid-grapher/grapher/lineCharts LineChart.tsx

74.66% Statements 772/1034
70.15% Branches 94/134
87.5% Functions 70/80
74.66% Lines 772/1034

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 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 12041x 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 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 27x 27x 27x 27x     27x 27x                                   27x 27x     27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x         27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 16x 16x 16x 16x 16x 27x 27x 11x 11x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 106x 106x 106x 106x 36x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 36x 36x 1955x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 27x 27x 27x 27x 106x 106x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 1x 1x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x             38x 38x 38x 39x 39x 1x 1x 39x 39x 1x 1x 1x 1x 1x 39x 39x 1x 1x 1x 1x 1x           1x 1x 39x 39x 39x 39x     39x 39x 27x 27x 39x 39x 39x 39x 39x 39x 6x 6x 39x 39x 6x 6x 6x 6x 39x 39x 6x 6x 39x 39x 27x   27x 27x 39x 39x 27x   27x 27x 39x 39x 27x   27x 27x 39x 39x 38x 38x 39x 39x           39x 39x 27x 27x 27x 27x                                                                   27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x                                                                                                                                                                                                                                   27x 27x 27x 27x 27x 39x 39x 39x 39x 39x       39x 39x     39x 39x     39x 39x 27x 27x 27x 27x 27x 27x             27x 27x 39x 39x     39x 39x 39x 39x 39x 39x 39x 39x 27x 27x 27x 39x 39x 2x 2x 39x 39x 27x 27x 39x 39x 6x 6x 39x 39x 6x 6x 39x 39x 16x 16x 39x 39x 27x 27x 27x 27x 27x 39x 39x 27x 27x 39x 39x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 39x 39x 6x   6x 6x 39x 39x 27x 27x   27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x   27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x                                                   27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 39x 39x 2x 2x 2x 1x 1x 39x 39x 1x 1x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 1x 1x 39x 39x 6x 6x 39x 39x 1x 1x 39x 39x 39x 39x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 39x 39x 8x 8x 8x 8x 8x 39x 39x 4x 4x 4x 4x 4x 39x 39x 39x 39x 39x 39x 39x 13x 13x 39x 39x 39x 39x 39x 39x 6x 6x 39x 39x 1x 1x 39x 39x 1x 1x 39x 39x 1x 1x 39x 39x 39x 1x 1x 1x 1x 1x 1x 39x 39x 39x 2x 2x 39x 39x 39x 39x 39x 39x 39x 39x 1x 1x   1x 39x 39x     39x 39x 2x 1x 1x 2x 39x 39x 1x 1x 39x 39x 39x 39x 39x 6x 6x 6x 6x   6x 6x 39x 39x 11x 11x 11x   11x 11x 11x 11x 39x 39x 1x 1x     1x 1x 39x 39x 1x 1x 39x 39x 38x 38x 39x 39x 1x 1x 1x 1x 1x     1x 1x 1x 39x 39x 5x 5x 5x 5x 5x 5x 5x           5x 39x 39x 5x 5x 5x 5x 5x 5x 5x                 5x 39x 39x 39x 1x 1x 1x 1x 39x 39x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 350x 350x 350x 350x 350x           350x 350x 5x 5x 5x 5x 5x 5x 5x 5x                                                                                                                                                                                                                                                                                                                                                    
import * as React from "react"
import {
    sortBy,
    sum,
    guid,
    getRelativeMouse,
    pointsToPath,
    minBy,
    flatten,
    last,
    exposeInstanceOnWindow,
    round,
    excludeUndefined,
    isNumber,
    sortedUniqBy,
} from "../../clientUtils/Util"
import { computed, action, observable } from "mobx"
import { observer } from "mobx-react"
import { select } from "d3-selection"
import { easeLinear } from "d3-ease"
import { Bounds, DEFAULT_BOUNDS } from "../../clientUtils/Bounds"
import { DualAxisComponent } from "../axis/AxisViews"
import { DualAxis, HorizontalAxis, VerticalAxis } from "../axis/Axis"
import { PointVector } from "../../clientUtils/PointVector"
import {
    LineLegend,
    LineLabelSeries,
    LineLegendManager,
} from "../lineLegend/LineLegend"
import { ComparisonLine } from "../scatterCharts/ComparisonLine"
import { Tooltip } from "../tooltip/Tooltip"
import { NoDataModal } from "../noDataModal/NoDataModal"
import { extent } from "d3-array"
import {
    BASE_FONT_SIZE,
    SeriesName,
    ScaleType,
    SeriesStrategy,
} from "../core/GrapherConstants"
import { ColorSchemes } from "../color/ColorSchemes"
import { AxisConfig, FontSizeManager } from "../axis/AxisConfig"
import { ChartInterface } from "../chart/ChartInterface"
import {
    LinesProps,
    LineChartSeries,
    LineChartManager,
    LinePoint,
    PlacedLineChartSeries,
    PlacedPoint,
} from "./LineChartConstants"
import { OwidTable } from "../../coreTable/OwidTable"
import {
    autoDetectSeriesStrategy,
    autoDetectYColumnSlugs,
    getDefaultFailMessage,
    getSeriesKey,
    makeClipPath,
    makeSelectionArray,
} from "../chart/ChartUtils"
import { ColorScheme } from "../color/ColorScheme"
import { SelectionArray } from "../selection/SelectionArray"
import { CoreColumn } from "../../coreTable/CoreTableColumns"
import {
    CoreValueType,
    PrimitiveType,
} from "../../coreTable/CoreTableConstants"
import { CategoricalBin, ColorScaleBin } from "../color/ColorScaleBin"
import { ColorScale, ColorScaleManager } from "../color/ColorScale"
import {
    ColorScaleConfig,
    ColorScaleConfigInterface,
} from "../color/ColorScaleConfig"
import { isNotErrorValue } from "../../coreTable/ErrorValues"
import { ColorSchemeName } from "../color/ColorConstants"
import { MultiColorPolyline } from "../scatterCharts/MultiColorPolyline"
import { CategoricalColorAssigner } from "../color/CategoricalColorAssigner"
import { EntityName } from "../../coreTable/OwidTableConstants"
import { Color, HorizontalAlign } from "../../clientUtils/owidTypes"
import {
    darkenColorForHighContrastText,
    darkenColorForLine,
} from "../color/ColorUtils"
import {
    HorizontalColorLegendManager,
    HorizontalNumericColorLegend,
} from "../horizontalColorLegend/HorizontalColorLegends"
 
// background
const BACKGROUND_COLOR = "#fff"
// line color
const BLUR_LINE_COLOR = "#eee"
const DEFAULT_LINE_COLOR = "#000"
// stroke width
const DEFAULT_STROKE_WIDTH = 1.5
const VARIABLE_COLOR_STROKE_WIDTH = 2.5
// marker radius
const DEFAULT_MARKER_RADIUS = 1.8
const VARIABLE_COLOR_MARKER_RADIUS = 2.2
// line outline
const DEFAULT_LINE_OUTLINE_WIDTH = 0.5
const VARIABLE_COLOR_LINE_OUTLINE_WIDTH = 1.0
// legend
const LEGEND_PADDING = 25
 
@observer
class Lines extends React.Component<LinesProps> {
    base: React.RefObject<SVGGElement> = React.createRef()
 
    @computed private get allValues(): LinePoint[] {
        return flatten(this.props.placedSeries.map((series) => series.points))
    }
 
    @action.bound private onCursorMove(ev: MouseEvent | TouchEvent): void {
        const { dualAxis } = this.props
        const { horizontalAxis } = dualAxis

        if (!this.base.current) return

        const mouse = getRelativeMouse(this.base.current, ev)

        let hoverX
        if (dualAxis.innerBounds.contains(mouse)) {
            const closestValue = minBy(this.allValues, (point) =>
                Math.abs(horizontalAxis.place(point.x) - mouse.x)
            )
            hoverX = closestValue?.x
        }

        this.props.onHover(hoverX)
    }
 
    @action.bound private onCursorLeave(): void {
        this.props.onHover(undefined)
    }
 
    @computed get bounds(): Bounds {
        const { horizontalAxis, verticalAxis } = this.props.dualAxis
        return Bounds.fromCorners(
            new PointVector(horizontalAxis.range[0], verticalAxis.range[0]),
            new PointVector(horizontalAxis.range[1], verticalAxis.range[1])
        )
    }
 
    @computed private get focusedLines(): PlacedLineChartSeries[] {
        const { focusedSeriesNames } = this.props
        // If nothing is focused, everything is
        if (!focusedSeriesNames.length) return this.props.placedSeries
        return this.props.placedSeries.filter((series) =>
            focusedSeriesNames.includes(series.seriesName)
        )
    }
 
    @computed private get backgroundLines(): PlacedLineChartSeries[] {
        const { focusedSeriesNames } = this.props
        return this.props.placedSeries.filter(
            (series) => !focusedSeriesNames.includes(series.seriesName)
        )
    }
 
    // Don't display point markers if there are very many of them for performance reasons
    // Note that we're using circle elements instead of marker-mid because marker performance in Safari 10 is very poor for some reason
    @computed private get hasMarkers(): boolean {
        if (this.props.hidePoints) return false
        return (
            sum(this.focusedLines.map((series) => series.placedPoints.length)) <
            500
        )
    }
 
    @computed private get markerRadius(): number {
        return this.props.markerRadius ?? DEFAULT_MARKER_RADIUS
    }
 
    @computed private get strokeWidth(): number {
        return this.props.lineStrokeWidth ?? DEFAULT_STROKE_WIDTH
    }
 
    @computed private get lineOutlineWidth(): number {
        return this.props.lineOutlineWidth ?? DEFAULT_LINE_OUTLINE_WIDTH
    }
 
    private renderFocusGroups(): JSX.Element[] {
        return this.focusedLines.map((series, index) => {
            // If the series only contains one point, then we will always want to show a marker/circle
            // because we can't draw a line.
            const showMarkers =
                (this.hasMarkers || series.placedPoints.length === 1) &&
                !series.isProjection
            const strokeDasharray = series.isProjection ? "2,3" : undefined
 
            return (
                <g key={index}>
                    {/*
                        Create a white outline around the lines so they're
                        easier to follow when they overlap.
                    */}
                    <path
                        fill="none"
                        strokeLinecap="butt"
                        strokeLinejoin="round"
                        stroke={BACKGROUND_COLOR}
                        strokeWidth={
                            this.strokeWidth + this.lineOutlineWidth * 2
                        }
                        strokeDasharray={strokeDasharray}
                        d={pointsToPath(
                            series.placedPoints.map((value) => [
                                value.x,
                                value.y,
                            ]) as [number, number][]
                        )}
                    />
                    <MultiColorPolyline
                        points={series.placedPoints}
                        strokeLinejoin="round"
                        strokeWidth={this.strokeWidth}
                        strokeDasharray={strokeDasharray}
                    />
                    {showMarkers && (
                        <g>
                            {series.placedPoints.map((value, index) => (
                                <circle
                                    key={index}
                                    cx={value.x}
                                    cy={value.y}
                                    r={this.markerRadius}
                                    fill={value.color}
                                />
                            ))}
                        </g>
                    )}
                </g>
            )
        })
    }
 
    private renderBackgroundGroups(): JSX.Element[] {
        return this.backgroundLines.map((series, index) => (
            <g key={index}>
                <path
                    key={getSeriesKey(series, "line")}
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    stroke="#ddd"
                    d={pointsToPath(
                        series.placedPoints.map((value) => [
                            value.x,
                            value.y,
                        ]) as [number, number][]
                    )}
                    fill="none"
                    strokeWidth={1}
                />
            </g>
        ))
    }
 
    private container?: SVGElement
    componentDidMount(): void {
        const base = this.base.current as SVGGElement
        const container = base.closest("svg") as SVGElement
        container.addEventListener("mousemove", this.onCursorMove)
        container.addEventListener("mouseleave", this.onCursorLeave)
        container.addEventListener("touchstart", this.onCursorMove)
        container.addEventListener("touchmove", this.onCursorMove)
        container.addEventListener("touchend", this.onCursorLeave)
        container.addEventListener("touchcancel", this.onCursorLeave)
        this.container = container
    }
 
    componentWillUnmount(): void {
        const { container } = this
        if (!container) return
 
        container.removeEventListener("mousemove", this.onCursorMove)
        container.removeEventListener("mouseleave", this.onCursorLeave)
        container.removeEventListener("touchstart", this.onCursorMove)
        container.removeEventListener("touchmove", this.onCursorMove)
        container.removeEventListener("touchend", this.onCursorLeave)
        container.removeEventListener("touchcancel", this.onCursorLeave)
    }
 
    render(): JSX.Element {
        const { bounds } = this
 
        return (
            <g ref={this.base} className="Lines">
                <rect
                    x={Math.round(bounds.x)}
                    y={Math.round(bounds.y)}
                    width={Math.round(bounds.width)}
                    height={Math.round(bounds.height)}
                    fill="rgba(255,255,255,0)"
                    opacity={0}
                />
                {this.renderBackgroundGroups()}
                {this.renderFocusGroups()}
            </g>
        )
    }
}
 
@observer
export class LineChart
    extends React.Component<{
        bounds?: Bounds
        manager: LineChartManager
    }>
    implements
        ChartInterface,
        LineLegendManager,
        FontSizeManager,
        ColorScaleManager,
        HorizontalColorLegendManager
{
    base: React.RefObject<SVGGElement> = React.createRef()
 
    transformTable(table: OwidTable): OwidTable {
        table = table.filterByEntityNames(
            this.selectionArray.selectedEntityNames
        )
 
        // TODO: remove this filter once we don't have mixed type columns in datasets
        // Currently we set skipParsing=true on these columns to be backwards-compatible
        table = table.replaceNonNumericCellsWithErrorValues(this.yColumnSlugs)
 
        if (this.isLogScale)
            table = table.replaceNonPositiveCellsForLogScale(this.yColumnSlugs)
 
        if (this.colorColumnSlug) {
            table = table
                // TODO: remove this filter once we don't have mixed type columns in datasets
                // Currently we set skipParsing=true on these columns to be backwards-compatible
                .replaceNonNumericCellsWithErrorValues([this.colorColumnSlug])
                .interpolateColumnWithTolerance(this.colorColumnSlug)
        }
 
        return table
    }
 
    @computed get inputTable(): OwidTable {
        return this.manager.table
    }
 
    @computed private get transformedTableFromGrapher(): OwidTable {
        return (
            this.manager.transformedTable ??
            this.transformTable(this.inputTable)
        )
    }
 
    @computed get transformedTable(): OwidTable {
        let table = this.transformedTableFromGrapher
        // The % growth transform cannot be applied in transformTable() because it will filter out
        // any rows before startHandleTimeBound and change the timeline bounds.
        const { isRelativeMode, startHandleTimeBound } = this.manager
        if (isRelativeMode && startHandleTimeBound !== undefined) {
            table = table.toTotalGrowthForEachColumnComparedToStartTime(
                startHandleTimeBound,
                this.manager.yColumnSlugs ?? []
            )
        }
        return table
    }
 
    // todo: rename mouseHoverX -> hoverX and hoverX -> activeX
    @observable mouseHoverX?: number = undefined
    @action.bound onHover(hoverX: number | undefined): void {
        this.mouseHoverX = hoverX
    }
 
    @computed get hoverX(): number | undefined {
        return this.mouseHoverX ?? this.props.manager.annotation?.year
    }
 
    @computed private get manager(): LineChartManager {
        return this.props.manager
    }
 
    @computed get bounds(): Bounds {
        return this.props.bounds ?? DEFAULT_BOUNDS
    }
 
    @computed private get boundsWithoutColorLegend(): Bounds {
        return this.bounds.padTop(
            this.hasColorLegend ? this.legendHeight + LEGEND_PADDING : 0
        )
    }
 
    @computed get maxLineLegendWidth(): number {
        return this.bounds.width / 3
    }
 
    @computed private get lineStrokeWidth(): number {
        return this.manager.lineStrokeWidth ?? this.hasColorScale
            ? VARIABLE_COLOR_STROKE_WIDTH
            : DEFAULT_STROKE_WIDTH
    }
 
    @computed private get lineOutlineWidth(): number {
        return this.hasColorScale
            ? VARIABLE_COLOR_LINE_OUTLINE_WIDTH
            : DEFAULT_LINE_OUTLINE_WIDTH
    }
 
    @computed private get markerRadius(): number {
        return this.hasColorScale
            ? VARIABLE_COLOR_MARKER_RADIUS
            : DEFAULT_MARKER_RADIUS
    }
 
    @computed get selectionArray(): SelectionArray {
        return makeSelectionArray(this.manager)
    }
 
    seriesIsBlurred(series: LineChartSeries): boolean {
        return (
            this.isFocusMode &&
            !this.focusedSeriesNames.includes(series.seriesName)
        )
    }
 
    @computed private get tooltip(): JSX.Element | undefined {
        const { hoverX, dualAxis, inputTable, formatColumn, hasColorScale } =
            this
 
        if (hoverX === undefined) return undefined

        const sortedData = sortBy(this.series, (series) => {
            const value = series.points.find((point) => point.x === hoverX)
            return value !== undefined ? -value.y : Infinity
        })

        const formatted = inputTable.timeColumnFormatFunction(hoverX)

        return (
            <Tooltip
                tooltipManager={this.manager}
                x={dualAxis.horizontalAxis.place(hoverX)}
                y={
                    dualAxis.verticalAxis.rangeMin +
                    dualAxis.verticalAxis.rangeSize / 2
                }
                style={{ padding: "0.3em" }}
                offsetX={5}
            >
                <table
                    style={{
                        fontSize: "0.9em",
                        lineHeight: "1.4em",
                        whiteSpace: "normal",
                    }}
                >
                    <thead>
                        <tr>
                            <td colSpan={3}>
                                <strong>{formatted}</strong>
                            </td>
                            {hasColorScale && (
                                <td
                                    style={{
                                        paddingLeft: "0.5em",
                                        fontSize: "0.9em",
                                        color: "#999",
                                        whiteSpace: "normal",
                                        maxWidth: "5em",
                                        textAlign: "right",
                                        lineHeight: "1.1em",
                                    }}
                                >
                                    {this.colorScale.legendDescription}
                                </td>
                            )}
                        </tr>
                    </thead>
                    <tbody>
                        {sortedData.map((series) => {
                            const value = series.points.find(
                                (point) => point.x === hoverX
                            )

                            const annotation = this.getAnnotationsForSeries(
                                series.seriesName
                            )

                            // It sometimes happens that data is missing for some years for a particular
                            // entity. If the user hovers over these years, we want to show a "No data"
                            // notice. However, we only want to show this notice when we are in the middle
                            // of a time series – when data points exist before and after the current year.
                            // Otherwise we want to entirely exclude the entity from the tooltip.
                            if (!value) {
                                const [startX, endX] = extent(
                                    series.points,
                                    (point) => point.x
                                )
                                if (
                                    startX === undefined ||
                                    endX === undefined ||
                                    startX > hoverX ||
                                    endX < hoverX
                                )
                                    return undefined
                            }

                            const isBlur =
                                this.seriesIsBlurred(series) ||
                                value === undefined
                            const circleColor = isBlur
                                ? BLUR_LINE_COLOR
                                : this.hasColorScale
                                ? this.getColorScaleColor(value.colorValue)
                                : series.color
                            const textColor = isBlur
                                ? "#ddd"
                                : darkenColorForHighContrastText(circleColor)
                            const annotationColor = isBlur ? "#ddd" : "#999"
                            return (
                                <tr
                                    key={getSeriesKey(series)}
                                    style={{ color: textColor }}
                                >
                                    <td>
                                        <div
                                            style={{
                                                width: "10px",
                                                height: "10px",
                                                borderRadius: "5px",
                                                backgroundColor: circleColor,
                                                display: "inline-block",
                                                marginRight: "2px",
                                            }}
                                        />
                                    </td>
                                    <td
                                        style={{
                                            paddingRight: "0.8em",
                                            fontWeight: 700,
                                        }}
                                    >
                                        {series.seriesName}
                                        {annotation && (
                                            <span
                                                className="tooltipAnnotation"
                                                style={{
                                                    color: annotationColor,
                                                    fontSize: "90%",
                                                }}
                                            >
                                                {" "}
                                                {annotation}
                                            </span>
                                        )}
                                    </td>
                                    <td
                                        style={{
                                            textAlign: "right",
                                            whiteSpace: "nowrap",
                                            fontWeight: 700,
                                        }}
                                    >
                                        {value === undefined
                                            ? "No data"
                                            : formatColumn.formatValueShort(
                                                  value.y,
                                                  { noTrailingZeroes: false }
                                              )}
                                    </td>
                                    {hasColorScale && (
                                        <td
                                            style={{
                                                textAlign: "right",
                                                whiteSpace: "nowrap",
                                                fontSize: "0.95em",
                                                paddingLeft: "0.5em",
                                            }}
                                        >
                                            {value?.colorValue !== undefined
                                                ? this.colorColumn.formatValueShort(
                                                      value.colorValue,
                                                      {
                                                          noTrailingZeroes:
                                                              false,
                                                      }
                                                  )
                                                : undefined}
                                        </td>
                                    )}
                                </tr>
                            )
                        })}
                    </tbody>
                </table>
            </Tooltip>
        )
    }
 
    defaultRightPadding = 1
 
    @observable hoveredSeriesName?: SeriesName
    @action.bound onLineLegendClick(): void {
        if (this.manager.startSelectingWhenLineClicked)
            this.manager.isSelectingData = true
    }
 
    @action.bound onLineLegendMouseOver(seriesName: SeriesName): void {
        this.hoveredSeriesName = seriesName
    }
 
    @action.bound onLineLegendMouseLeave(): void {
        this.hoveredSeriesName = undefined
    }
 
    @computed get focusedSeriesNames(): string[] {
        const { externalLegendFocusBin } = this.manager
        const focusedSeriesNames = excludeUndefined([
            this.props.manager.annotation?.entityName,
            this.hoveredSeriesName,
        ])
        if (externalLegendFocusBin) {
            focusedSeriesNames.push(
                ...this.series
                    .map((s) => s.seriesName)
                    .filter((name) => externalLegendFocusBin.contains(name))
            )
        }
        return focusedSeriesNames
    }
 
    @computed get isFocusMode(): boolean {
        return this.focusedSeriesNames.length > 0
    }
 
    animSelection?: d3.Selection<
        d3.BaseType,
        unknown,
        SVGGElement | null,
        unknown
    >
    componentDidMount(): void {
        if (!this.manager.isExportingtoSvgOrPng) this.runFancyIntroAnimation()
        exposeInstanceOnWindow(this)
    }
 
    componentWillUnmount(): void {
        if (this.animSelection) this.animSelection.interrupt()
    }
 
    @computed get renderUid(): number {
        return guid()
    }
 
    @computed get fontSize(): number {
        return this.manager.baseFontSize ?? BASE_FONT_SIZE
    }
 
    @computed get fontWeight(): number {
        return this.hasColorScale ? 700 : 400
    }
 
    @computed get lineLegendX(): number {
        return this.bounds.right - (this.lineLegendDimensions?.width || 0)
    }
 
    @computed get clipPathBounds(): Bounds {
        const { dualAxis, boundsWithoutColorLegend } = this
        return boundsWithoutColorLegend
            .set({ x: dualAxis.innerBounds.x })
            .expand(10)
    }
 
    @computed get clipPath(): { id: string; element: JSX.Element } {
        return makeClipPath(this.renderUid, this.clipPathBounds)
    }
 
    private runFancyIntroAnimation(): void {
        this.animSelection = select(this.base.current)
            .selectAll("clipPath > rect")
            .attr("width", 0)
        this.animSelection
            .transition()
            .duration(800)
            .ease(easeLinear)
            .attr("width", this.clipPathBounds.width)
            .on("end", () => this.forceUpdate()) // Important in case bounds changes during transition
    }
 
    @computed private get lineLegendDimensions(): LineLegend | undefined {
        return this.manager.hideLegend
            ? undefined
            : new LineLegend({ manager: this })
    }
 
    render(): JSX.Element {
        if (this.failMessage)
            return (
                <NoDataModal
                    manager={this.manager}
                    bounds={this.bounds}
                    message={this.failMessage}
                />
            )
 
        const { manager, tooltip, dualAxis, hoverX, clipPath } = this
        const { horizontalAxis, verticalAxis } = dualAxis
 
        const comparisonLines = manager.comparisonLines || []
 
        const showLegend = !manager.hideLegend
 
        // The tiny bit of extra space in the clippath is to ensure circles centered on the very edge are still fully visible
        return (
            <g ref={this.base} className="LineChart">
                {clipPath.element}
                {this.hasColorLegend && (
                    <HorizontalNumericColorLegend manager={this} />
                )}
                <DualAxisComponent dualAxis={dualAxis} showTickMarks={true} />
                <g clipPath={clipPath.id}>
                    {comparisonLines.map((line, index) => (
                        <ComparisonLine
                            key={index}
                            dualAxis={dualAxis}
                            comparisonLine={line}
                        />
                    ))}
                    {showLegend && <LineLegend manager={this} />}
                    <Lines
                        dualAxis={dualAxis}
                        placedSeries={this.placedSeries}
                        hidePoints={manager.hidePoints}
                        onHover={this.onHover}
                        focusedSeriesNames={this.focusedSeriesNames}
                        lineStrokeWidth={this.lineStrokeWidth}
                        lineOutlineWidth={this.lineOutlineWidth}
                        markerRadius={this.markerRadius}
                    />
                </g>
                {hoverX !== undefined && (
                    <g className="hoverIndicator">
                        {this.series.map((series) => {
                            const value = series.points.find(
                                (point) => point.x === hoverX
                            )
                            if (!value || this.seriesIsBlurred(series))
                                return null

                            return (
                                <circle
                                    key={getSeriesKey(series)}
                                    cx={horizontalAxis.place(value.x)}
                                    cy={verticalAxis.place(value.y)}
                                    r={4}
                                    fill={
                                        this.hasColorScale
                                            ? this.getColorScaleColor(
                                                  value.colorValue
                                              )
                                            : series.color
                                    }
                                />
                            )
                        })}
                        <line
                            x1={horizontalAxis.place(hoverX)}
                            y1={verticalAxis.range[0]}
                            x2={horizontalAxis.place(hoverX)}
                            y2={verticalAxis.range[1]}
                            stroke="rgba(180,180,180,.4)"
                        />
                    </g>
                )}
 
                {tooltip}
            </g>
        )
    }
 
    @computed get failMessage(): string {
        const message = getDefaultFailMessage(this.manager)
        if (message) return message
        if (!this.series.length) return "No matching data"
        return ""
    }
 
    @computed private get yColumns(): CoreColumn[] {
        return this.yColumnSlugs.map((slug) => this.transformedTable.get(slug))
    }
 
    @computed protected get yColumnSlugs(): string[] {
        return autoDetectYColumnSlugs(this.manager)
    }
 
    @computed private get colorColumnSlug(): string | undefined {
        return this.manager.colorColumnSlug
    }
 
    @computed private get colorColumn(): CoreColumn {
        return this.transformedTable.get(this.colorColumnSlug)
    }
 
    @computed private get formatColumn(): CoreColumn {
        return this.yColumns[0]
    }
 
    @computed private get hasColorScale(): boolean {
        return !this.colorColumn.isMissing
    }
 
    // Color scale props
 
    @computed get colorScaleColumn(): CoreColumn {
        return (
            // For faceted charts, we have to get the values of inputTable before it's filtered by
            // the faceting logic.
            this.manager.colorScaleColumnOverride ??
            // We need to use inputTable in order to get consistent coloring for a variable across
            // charts, e.g. each continent being assigned to the same color.
            // inputTable is unfiltered, so it contains every value that exists in the variable.
            this.inputTable.get(this.colorColumnSlug)
        )
    }
 
    @computed get colorScaleConfig(): ColorScaleConfigInterface | undefined {
        return (
            ColorScaleConfig.fromDSL(this.colorColumn.def) ??
            this.manager.colorScale
        )
    }
 
    @computed get hasNoDataBin(): boolean {
        if (!this.hasColorScale) return false
        return this.colorColumn.valuesIncludingErrorValues.some(
            (value) => !isNotErrorValue(value)
        )
    }
 
    defaultBaseColorScheme = ColorSchemeName.YlGnBu
    defaultNoDataColor = "#959595"
    transformColor = darkenColorForLine
    colorScale = new ColorScale(this)
 
    private getColorScaleColor(value: CoreValueType | undefined): Color {
        return this.colorScale.getColor(value) ?? DEFAULT_LINE_COLOR
    }
 
    // End of color scale props
 
    // Color legend props
 
    @computed private get hasColorLegend(): boolean {
        return this.hasColorScale && !this.manager.hideLegend
    }
 
    @computed get legendX(): number {
        return this.bounds.x
    }
 
    @computed get legendMaxWidth(): number {
        return this.bounds.width
    }
 
    @computed get legendAlign(): HorizontalAlign {
        return HorizontalAlign.center
    }
 
    // TODO just pass colorScale to legend and let it figure it out?
    @computed get numericLegendData(): ColorScaleBin[] {
        // Move CategoricalBins to end
        return sortBy(
            this.colorScale.legendBins,
            (bin) => bin instanceof CategoricalBin
        )
    }
 
    // TODO just pass colorScale to legend and let it figure it out?
    @computed get equalSizeBins(): boolean | undefined {
        return this.colorScale.config.equalSizeBins
    }
 
    numericBinSize = 6
    numericBinStroke = BACKGROUND_COLOR
    numericBinStrokeWidth = 1
    legendTextColor = "#555"
    legendTickSize = 1
 
    @computed get numericLegend(): HorizontalNumericColorLegend | undefined {
        return this.hasColorScale && !this.manager.hideLegend
            ? new HorizontalNumericColorLegend({ manager: this })
            : undefined
    }
 
    @computed get numericLegendY(): number {
        return this.bounds.top
    }
 
    @computed get legendTitle(): string | undefined {
        return this.hasColorScale
            ? this.colorScale.legendDescription
            : undefined
    }
 
    @computed get legendHeight(): number {
        return this.numericLegend?.height ?? 0
    }
 
    // End of color legend props
 
    // todo: for now just works with 1 y column
    @computed private get annotationsMap(): Map<
        PrimitiveType,
        Set<PrimitiveType>
    > {
        return this.inputTable
            .getAnnotationColumnForColumn(this.yColumnSlugs[0])
            ?.getUniqueValuesGroupedBy(this.inputTable.entityNameSlug)
    }
 
    getAnnotationsForSeries(seriesName: SeriesName): string | undefined {
        const annotationsMap = this.annotationsMap
        const annos = annotationsMap?.get(seriesName)
        return annos
            ? Array.from(annos.values())
                  .filter((anno) => anno)
                  .join(" & ")
            : undefined
    }
 
    @computed private get colorScheme(): ColorScheme {
        return (
            (this.manager.baseColorScheme
                ? ColorSchemes[this.manager.baseColorScheme]
                : null) ?? ColorSchemes["owid-distinct"]
        )
    }
 
    @computed get seriesStrategy(): SeriesStrategy {
        return autoDetectSeriesStrategy(this.manager, true)
    }
 
    @computed get isLogScale(): boolean {
        return this.yAxisConfig.scaleType === ScaleType.log
    }
 
    @computed private get categoricalColorAssigner(): CategoricalColorAssigner {
        return new CategoricalColorAssigner({
            colorScheme: this.colorScheme,
            invertColorScheme: this.manager.invertColorScheme,
            colorMap:
                this.seriesStrategy === SeriesStrategy.entity
                    ? this.inputTable.entityNameColorIndex
                    : this.inputTable.columnDisplayNameToColorMap,
            autoColorMapCache: this.manager.seriesColorMap,
        })
    }
 
    private getSeriesName(
        entityName: EntityName,
        columnName: string,
        entityCount: number
    ): SeriesName {
        if (this.seriesStrategy === SeriesStrategy.entity) {
            return entityName
        }
        if (entityCount > 1 || this.manager.canSelectMultipleEntities) {
            return `${entityName} - ${columnName}`
        } else {
            return columnName
        }
    }
 
    private getColorKey(
        entityName: EntityName,
        columnName: string,
        entityCount: number
    ): SeriesName {
        if (this.seriesStrategy === SeriesStrategy.entity) {
            return entityName
        }
        // If only one entity is plotted, we want to use the column colors.
        // Unlike in `getSeriesName`, we don't care whether the user can select
        // multiple entities, only whether more than one is plotted.
        if (entityCount > 1) {
            return `${entityName} - ${columnName}`
        } else {
            return columnName
        }
    }
 
    // cache value for performance
    @computed private get rowIndicesByEntityName(): Map<string, number[]> {
        return this.transformedTable.rowIndex([
            this.transformedTable.entityNameSlug,
        ])
    }
 
    private constructSingleSeries(
        entityName: string,
        col: CoreColumn
    ): LineChartSeries {
        const { hasColorScale, transformedTable, colorColumn } = this
 
        // Construct the points
        const timeValues = col.originalTimeColumn.valuesIncludingErrorValues
        const values = col.valuesIncludingErrorValues
        const colorValues = colorColumn.valuesIncludingErrorValues
        // If Y and Color are the same column, we need to get rid of any duplicate rows.
        // Duplicates occur because Y doesn't have tolerance applied, but Color does.
        const rowIndexes = sortedUniqBy(
            this.rowIndicesByEntityName
                .get(entityName)!
                .filter((index) => isNumber(values[index])),
            (index) => timeValues[index]
        )
        const points = rowIndexes.map((index) => {
            const point: LinePoint = {
                x: timeValues[index] as number,
                y: values[index] as number,
            }
            if (hasColorScale) {
                const colorValue = colorValues[index]
                point.colorValue = isNotErrorValue(colorValue)
                    ? colorValue
                    : undefined
            }
            return point
        })
 
        // Construct series properties
        const totalEntityCount = transformedTable.availableEntityNames.length
        const seriesName = this.getSeriesName(
            entityName,
            col.displayName,
            totalEntityCount
        )
        let seriesColor: Color
        if (hasColorScale) {
            const colorValue = last(points)?.colorValue
            seriesColor = this.getColorScaleColor(colorValue)
        } else {
            seriesColor = this.categoricalColorAssigner.assign(
                this.getColorKey(entityName, col.displayName, totalEntityCount)
            )
        }
 
        return {
            points,
            seriesName,
            isProjection: col.isProjection,
            color: seriesColor,
        }
    }
 
    @computed get series(): readonly LineChartSeries[] {
        return flatten(
            this.yColumns.map((col) =>
                col.uniqEntityNames.map(
                    (entityName): LineChartSeries =>
                        this.constructSingleSeries(entityName, col)
                )
            )
        )
    }
 
    // TODO: remove, seems unused
    @computed get allPoints(): LinePoint[] {
        return flatten(this.series.map((series) => series.points))
    }
 
    @computed get placedSeries(): PlacedLineChartSeries[] {
        const { dualAxis } = this
        const { horizontalAxis, verticalAxis } = dualAxis
 
        return this.series
            .slice()
            .reverse()
            .map((series) => {
                return {
                    ...series,
                    placedPoints: series.points.map(
                        (point): PlacedPoint => ({
                            x: round(horizontalAxis.place(point.x), 1),
                            y: round(verticalAxis.place(point.y), 1),
                            color: this.hasColorScale
                                ? this.getColorScaleColor(point.colorValue)
                                : series.color,
                        })
                    ),
                }
            })
    }
 
    // Order of the legend items on a line chart should visually correspond
    // to the order of the lines as the approach the legend
    @computed get labelSeries(): LineLabelSeries[] {
        // If there are any projections, ignore non-projection legends
        // Bit of a hack
        let seriesToShow = this.series
        if (seriesToShow.some((series) => !!series.isProjection))
            seriesToShow = seriesToShow.filter((series) => series.isProjection)
 
        return seriesToShow.map((series) => {
            const { seriesName, color } = series
            const lastValue = last(series.points)!.y
            return {
                color,
                seriesName,
                // E.g. https://ourworldindata.org/grapher/size-poverty-gap-world
                label: this.manager.hideLegend ? "" : `${seriesName}`,
                annotation: this.getAnnotationsForSeries(seriesName),
                yValue: lastValue,
            }
        })
    }
 
    @computed private get xAxisConfig(): AxisConfig {
        return new AxisConfig(this.manager.xAxisConfig, this)
    }
 
    @computed private get horizontalAxisPart(): HorizontalAxis {
        const axis = this.xAxisConfig.toHorizontalAxis()
        axis.updateDomainPreservingUserSettings(
            this.transformedTable.timeDomainFor(this.yColumnSlugs)
        )
        axis.scaleType = ScaleType.linear
        axis.formatColumn = this.inputTable.timeColumn
        axis.hideFractionalTicks = true
        axis.hideGridlines = true
        return axis
    }
 
    @computed private get yAxisConfig(): AxisConfig {
        // TODO: enable nice axis ticks for linear scales
        return new AxisConfig(this.manager.yAxisConfig, this)
    }
 
    @computed private get verticalAxisPart(): VerticalAxis {
        const axisConfig = this.yAxisConfig
        const yDomain = this.transformedTable.domainFor(this.yColumnSlugs)
        const domain = axisConfig.domain
        const axis = axisConfig.toVerticalAxis()
        axis.updateDomainPreservingUserSettings([
            Math.min(domain[0], yDomain[0]),
            Math.max(domain[1], yDomain[1]),
        ])
        axis.hideFractionalTicks = this.yColumns.every(
            (yColumn) => yColumn.isAllIntegers
        ) // all y axis points are integral, don't show fractional ticks in that case
        axis.label = ""
        axis.formatColumn = this.formatColumn
        return axis
    }
 
    @computed private get dualAxis(): DualAxis {
        return new DualAxis({
            bounds: this.boundsWithoutColorLegend.padRight(
                this.lineLegendDimensions
                    ? this.lineLegendDimensions.width
                    : this.defaultRightPadding
            ),
            verticalAxis: this.verticalAxisPart,
            horizontalAxis: this.horizontalAxisPart,
        })
    }
 
    @computed get yAxis(): VerticalAxis {
        return this.dualAxis.verticalAxis
    }
 
    @computed get xAxis(): HorizontalAxis {
        return this.dualAxis.horizontalAxis
    }
 
    @computed get externalLegend(): HorizontalColorLegendManager | undefined {
        if (this.manager.hideLegend) {
            const numericLegendData = this.hasColorScale
                ? this.numericLegendData
                : []
            const categoricalLegendData = this.hasColorScale
                ? []
                : this.series.map(
                      (series, index) =>
                          new CategoricalBin({
                              index,
                              value: series.seriesName,
                              label: series.seriesName,
                              color: series.color,
                          })
                  )
            return {
                legendTitle: this.legendTitle,
                legendTextColor: this.legendTextColor,
                legendTickSize: this.legendTickSize,
                equalSizeBins: this.equalSizeBins,
                numericBinSize: this.numericBinSize,
                numericBinStroke: this.numericBinStroke,
                numericBinStrokeWidth: this.numericBinStrokeWidth,
                numericLegendData,
                categoricalLegendData,
            }
        }
        return undefined
    }
}