All files / owid-grapher/grapher/mapCharts MapChart.tsx

88.93% Statements 755/849
80.16% Branches 101/126
85.9% Functions 67/78
88.93% Lines 755/849

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 9981x 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 202x 202x 202x 202x 330x 330x 330x 330x 330x 330x 330x 330x 330x 202x 202x 202x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 1x 1x 202x 202x 202x 202x 202x 202x 202x 202x 202x 202x 201x 201x 201x 201x 201x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 4x 4x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 4x 4x 5x 5x 5x 5x 5x 5x 5x 5x   5x 5x 5x 5x 4x 4x 5x 5x 4x 4x 5x 5x 5x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 1x 1x 1x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 5x 5x 5x 1x 1x 1x 5x 5x 4x 4x 5x 5x                       5x 5x 1x 1x 1x 5x 5x     5x 5x 1x 1x 5x 5x 5x 5x 5x 5x     5x 5x 4x 4x 4x 11x 11x           11x 11x 4x 5x 5x 4x 4x 4x 4x 2x 2x 2x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 2x 2x 5x 5x 4x 4x 11x 11x 4x 4x 5x 5x 4x 4x 4x 4x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 808x 808x 5x 5x 5x 5x 5x 808x 808x 5x 808x 808x 5x 5x 5x 5x 4x 4x 4x 4x 4x 4x 4x 4x 5x 5x 4x 4x 5x 5x 4x 4x 5x 5x 4x 4x 5x 5x 4x 4x 5x 5x 4x 4x 4x 4x 22x 4x 4x 4x 4x 4x 4x 4x 4x 22x 22x 4x 4x 4x 5x 5x     5x 5x 4x 4x 22x 4x 4x 5x 5x 4x 4x 5x 5x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 5x 5x                     5x 5x     5x 5x 4x 4x 5x 5x 4x 4x 5x 5x 4x 4x 5x 5x 4x 4x 5x 5x 4x 4x 4x 4x 4x 4x 5x 5x 4x 4x   4x 5x 5x 4x 4x 5x 5x           5x 5x 4x 4x 5x 5x 4x 4x 4x 4x 4x 4x 4x 4x 4x         5x 5x 4x 4x 4x 4x 4x 4x 4x 4x   4x 4x 4x 4x 5x 5x 5x 5x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 808x 808x 808x     808x 808x 808x 4x 4x     4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x                   4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x                                                         4x 4x 1x 1x 1x 1x 1x 1x 4x 4x       4x 4x 4x 4x 4x 4x       4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x                                                                                                                                                                                                                                                                                                          
import * as React from "react"
import { Bounds, DEFAULT_BOUNDS } from "../../clientUtils/Bounds"
import { observable, computed, action } from "mobx"
import { observer } from "mobx-react"
import {
    HorizontalCategoricalColorLegend,
    HorizontalColorLegendManager,
    HorizontalNumericColorLegend,
} from "../horizontalColorLegend/HorizontalColorLegends"
import {
    flatten,
    getRelativeMouse,
    isString,
    identity,
    sortBy,
    guid,
    minBy,
    difference,
    exposeInstanceOnWindow,
} from "../../clientUtils/Util"
import { isPresent } from "../../clientUtils/isPresent"
import { MapProjectionName, MapProjectionGeos } from "./MapProjections"
import { select } from "d3-selection"
import { easeCubic } from "d3-ease"
import { MapTooltip } from "./MapTooltip"
import { ProjectionChooser } from "./ProjectionChooser"
import { isOnTheMap } from "./EntitiesOnTheMap"
import { EntityName } from "../../coreTable/OwidTableConstants"
import {
    GeoFeature,
    MapBracket,
    MapChartManager,
    MapEntity,
    ChoroplethMapProps,
    RenderFeature,
    ChoroplethSeries,
} from "./MapChartConstants"
import { MapConfig } from "./MapConfig"
import { ColorScale, ColorScaleManager } from "../color/ColorScale"
import {
    BASE_FONT_SIZE,
    GrapherTabOption,
    SeriesName,
} from "../core/GrapherConstants"
import { ChartInterface } from "../chart/ChartInterface"
import {
    CategoricalBin,
    ColorScaleBin,
    NumericBin,
} from "../color/ColorScaleBin"
import * as topojson from "topojson-client"
import { MapTopology } from "./MapTopology"
import { PointVector } from "../../clientUtils/PointVector"
import {
    WorldRegionName,
    WorldRegionToProjection,
} from "./WorldRegionsToProjection"
import { OwidTable } from "../../coreTable/OwidTable"
import { ColorSchemeName } from "../color/ColorConstants"
import {
    autoDetectYColumnSlugs,
    makeClipPath,
    makeSelectionArray,
} from "../chart/ChartUtils"
import { NoDataModal } from "../noDataModal/NoDataModal"
import { ColorScaleConfig } from "../color/ColorScaleConfig"
import { CoreColumn } from "../../coreTable/CoreTableColumns"
import { SelectionArray } from "../selection/SelectionArray"
import { Color, HorizontalAlign } from "../../clientUtils/owidTypes"
 
const PROJECTION_CHOOSER_WIDTH = 110
const PROJECTION_CHOOSER_HEIGHT = 22
 
const DEFAULT_STROKE_COLOR = "#333"
const CHOROPLETH_MAP_CLASSNAME = "ChoroplethMap"
 
// TODO refactor to use transform pattern, bit too much info for a pure component
 
interface MapChartProps {
    bounds?: Bounds
    manager: MapChartManager
    containerElement?: HTMLDivElement
}
 
// Get the underlying geographical topology elements we're going to display
const GeoFeatures: GeoFeature[] = (
    topojson.feature(
        MapTopology as any,
        MapTopology.objects.world as any
    ) as any
).features
 
// Get the svg path specification string for every feature
const geoPathCache = new Map<MapProjectionName, string[]>()
const geoPathsFor = (projectionName: MapProjectionName): string[] => {
    if (geoPathCache.has(projectionName))
        return geoPathCache.get(projectionName)!
    const projectionGeo = MapProjectionGeos[projectionName]
    const strs = GeoFeatures.map((feature) => {
        const s = projectionGeo(feature) as string
        const paths = s.split(/Z/).filter(identity)
 
        const newPaths = paths.map((path) => {
            const points = path.split(/[MLZ]/).filter((f: any) => f)
            const rounded = points.map((point) =>
                point
                    .split(/,/)
                    .map((v) => parseFloat(v).toFixed(1))
                    .join(",")
            )
            return "M" + rounded.join("L")
        })
 
        return newPaths.join("Z") + "Z"
    })
 
    geoPathCache.set(projectionName, strs)
    return geoPathCache.get(projectionName)!
}
 
// Get the bounding box for every geographical feature
const geoBoundsCache = new Map<MapProjectionName, Bounds[]>()
const geoBoundsFor = (projectionName: MapProjectionName): Bounds[] => {
    if (geoBoundsCache.has(projectionName))
        return geoBoundsCache.get(projectionName)!
    const projectionGeo = MapProjectionGeos[projectionName]
    const bounds = GeoFeatures.map((feature) => {
        const corners = projectionGeo.bounds(feature)
 
        const bounds = Bounds.fromCorners(
            new PointVector(...corners[0]),
            new PointVector(...corners[1])
        )
 
        // HACK (Mispy): The path generator calculates weird bounds for Fiji (probably it wraps around the map)
        if (feature.id === "Fiji")
            return bounds.set({
                x: bounds.right - bounds.height,
                width: bounds.height,
            })
        return bounds
    })
 
    geoBoundsCache.set(projectionName, bounds)
    return geoBoundsCache.get(projectionName)!
}
 
// Bundle GeoFeatures with the calculated info needed to render them
const renderFeaturesCache = new Map<MapProjectionName, RenderFeature[]>()
const renderFeaturesFor = (
    projectionName: MapProjectionName
): RenderFeature[] => {
    if (renderFeaturesCache.has(projectionName))
        return renderFeaturesCache.get(projectionName)!
    const geoBounds = geoBoundsFor(projectionName)
    const geoPaths = geoPathsFor(projectionName)
    const feats = GeoFeatures.map((geo, index) => ({
        id: geo.id as string,
        geo: geo,
        path: geoPaths[index],
        bounds: geoBounds[index],
        center: geoBounds[index].centerPos,
    }))
 
    renderFeaturesCache.set(projectionName, feats)
    return renderFeaturesCache.get(projectionName)!
}
 
@observer
export class MapChart
    extends React.Component<MapChartProps>
    implements ChartInterface, HorizontalColorLegendManager, ColorScaleManager
{
    @observable.ref tooltip: React.ReactNode | null = null
    @observable tooltipTarget?: { x: number; y: number; featureId: string }
 
    @observable focusEntity?: MapEntity
    @observable focusBracket?: MapBracket
 
    transformTable(table: OwidTable): OwidTable {
        if (!table.has(this.mapColumnSlug)) return table
        return this.dropNonMapEntities(table)
            .dropRowsWithErrorValuesForColumn(this.mapColumnSlug)
            .interpolateColumnWithTolerance(
                this.mapColumnSlug,
                this.mapConfig.timeTolerance
            )
    }
 
    private dropNonMapEntities(table: OwidTable): OwidTable {
        const entityNamesToSelect =
            table.availableEntityNames.filter(isOnTheMap)
        return table.filterByEntityNames(entityNamesToSelect)
    }
 
    @computed get inputTable(): OwidTable {
        return this.manager.table
    }
 
    @computed get transformedTable(): OwidTable {
        return (
            this.manager.transformedTable ??
            this.transformTable(this.inputTable)
        )
    }
 
    @computed get failMessage(): string {
        if (this.mapColumn.isMissing) return "Missing map column"
        return ""
    }
 
    @computed get mapColumn(): CoreColumn {
        return this.transformedTable.get(this.mapColumnSlug)
    }
 
    @computed get mapColumnSlug(): string {
        return (
            this.manager.mapColumnSlug ??
            autoDetectYColumnSlugs(this.manager)[0]!
        )
    }
 
    @computed private get targetTime(): number | undefined {
        return this.manager.endTime
    }
 
    @computed get bounds(): Bounds {
        return this.props.bounds ?? DEFAULT_BOUNDS
    }
 
    base: React.RefObject<SVGGElement> = React.createRef()
    @action.bound onMapMouseOver(
        feature: GeoFeature,
        ev: React.MouseEvent
    ): void {
        const series =
            feature.id === undefined
                ? undefined
                : this.seriesMap.get(feature.id as string)
        this.focusEntity = {
            id: feature.id,
            series: series || { value: "No data" },
        }
 
        const { containerElement } = this.props
        if (!containerElement) return
 
        const mouse = getRelativeMouse(containerElement, ev)
        if (feature.id !== undefined)
            this.tooltipTarget = {
                x: mouse.x,
                y: mouse.y,
                featureId: feature.id as string,
            }
    }
 
    @action.bound onMapMouseLeave(): void {
        this.focusEntity = undefined
        this.tooltipTarget = undefined
    }
 
    @computed get manager(): MapChartManager {
        return this.props.manager
    }
 
    @computed private get entityNamesWithData(): Set<EntityName> {
        // We intentionally use `inputTable` here instead of `transformedTable`, because of countries where there is no data
        // available in the map view for the current year, but data might still be available for other chart types
        return this.inputTable.entitiesWith([this.mapColumnSlug])
    }
 
    // Determine if we can go to line chart by clicking on a given map entity
    private isEntityClickable(entityName?: EntityName): boolean {
        if (!this.manager.mapIsClickable || !entityName) return false
        return this.entityNamesWithData.has(entityName)
    }
 
    @computed private get selectionArray(): SelectionArray {
        return makeSelectionArray(this.manager)
    }
 
    @action.bound onClick(
        d: GeoFeature,
        ev: React.MouseEvent<SVGElement>
    ): void {
        const entityName = d.id as EntityName
        if (!this.isEntityClickable(entityName)) return

        if (!ev.shiftKey) {
            this.selectionArray.setSelectedEntities([entityName])
            this.manager.currentTab = GrapherTabOption.chart
        } else this.selectionArray.toggleSelection(entityName)
    }
 
    componentWillUnmount(): void {
        this.onMapMouseLeave()
        this.onLegendMouseLeave()
    }
 
    @action.bound onLegendMouseOver(bracket: MapBracket): void {
        this.focusBracket = bracket
    }
 
    @action.bound onLegendMouseLeave(): void {
        this.focusBracket = undefined
    }
 
    @computed get mapConfig(): MapConfig {
        return this.manager.mapConfig || new MapConfig()
    }
 
    @action.bound onProjectionChange(value: MapProjectionName): void {
        this.mapConfig.projection = value
    }
 
    @computed get formatTooltipValue(): (d: number | string) => string {
        const { mapConfig, mapColumn, colorScale } = this
 
        return (d: number | string): string => {
            if (isString(d)) return d
            else if (mapConfig.tooltipUseCustomLabels) {
                // Find the bin (and its label) that this value belongs to
                const bin = colorScale.getBinForValue(d)
                const label = bin?.label
                if (label !== undefined && label !== "") return label
            }
            return mapColumn?.formatValueLong(d) ?? ""
        }
    }
 
    @computed get series(): ChoroplethSeries[] {
        const { mapColumn, selectionArray, targetTime, formatTooltipValue } =
            this
        if (mapColumn.isMissing) return []
        if (targetTime === undefined) return []
 
        return mapColumn.owidRows
            .map((row) => {
                const { entityName, value, time } = row
                const color = this.colorScale.getColor(value) || "red" // todo: color fix
                if (!color) return undefined
                return {
                    seriesName: entityName,
                    displayValue: formatTooltipValue(value),
                    time,
                    value,
                    isSelected: selectionArray.selectedSet.has(entityName),
                    color,
                    highlightFillColor: color,
                }
            })
            .filter(isPresent)
    }
 
    @computed private get seriesMap(): Map<SeriesName, ChoroplethSeries> {
        const map = new Map<SeriesName, ChoroplethSeries>()
        this.series.forEach((series) => {
            map.set(series.seriesName, series)
        })
        return map
    }
 
    @computed get colorScaleColumn(): CoreColumn {
        // Use the table before transform to build the legend.
        // Otherwise the legend jumps around as you slide the timeline handle.
        return this.dropNonMapEntities(this.inputTable).get(this.mapColumnSlug)
    }
 
    colorScale = new ColorScale(this)
 
    @computed get colorScaleConfig(): ColorScaleConfig {
        return (
            ColorScaleConfig.fromDSL(this.mapColumn.def) ??
            this.mapConfig.colorScale
        )
    }
 
    defaultBaseColorScheme = ColorSchemeName.BuGn
    hasNoDataBin = true
 
    componentDidMount(): void {
        select(this.base.current)
            .selectAll(`.${CHOROPLETH_MAP_CLASSNAME} path`)
            .attr("data-fill", function () {
                return (this as SVGPathElement).getAttribute("fill")
            })
            .attr("fill", this.colorScale.noDataColor)
            .transition()
            .duration(500)
            .ease(easeCubic)
            .attr("fill", function () {
                return (this as SVGPathElement).getAttribute("data-fill")
            })
            .attr("data-fill", function () {
                return (this as SVGPathElement).getAttribute("fill")
            })
        exposeInstanceOnWindow(this)
    }
 
    @computed get projectionChooserBounds(): Bounds {
        const { bounds } = this
        return new Bounds(
            bounds.width - PROJECTION_CHOOSER_WIDTH + 15 - 3,
            5,
            PROJECTION_CHOOSER_WIDTH,
            PROJECTION_CHOOSER_HEIGHT
        )
    }
 
    @computed get legendData(): ColorScaleBin[] {
        return this.colorScale.legendBins
    }
 
    @computed get equalSizeBins(): boolean | undefined {
        return this.colorScale.config.equalSizeBins
    }
 
    @computed get focusValue(): string | number | undefined {
        return this.focusEntity?.series?.value
    }
 
    @computed get fontSize(): number {
        return this.manager.baseFontSize ?? BASE_FONT_SIZE
    }
 
    @computed get numericLegendData(): ColorScaleBin[] {
        if (
            this.hasCategorical ||
            !this.legendData.some(
                (bin) =>
                    (bin as CategoricalBin).value === "No data" && !bin.isHidden
            )
        )
            return this.legendData.filter(
                (bin) => bin instanceof NumericBin && !bin.isHidden
            )
 
        const bin = this.legendData.filter(
            (bin) =>
                (bin instanceof NumericBin || bin.value === "No data") &&
                !bin.isHidden
        )
        return flatten([bin[bin.length - 1], bin.slice(0, -1)])
    }
 
    @computed get hasNumeric(): boolean {
        return this.numericLegendData.length > 1
    }
 
    @computed get categoricalLegendData(): CategoricalBin[] {
        return this.legendData.filter(
            (bin): bin is CategoricalBin =>
                bin instanceof CategoricalBin && !bin.isHidden
        )
    }
 
    @computed get hasCategorical(): boolean {
        return this.categoricalLegendData.length > 1
    }
 
    @computed get numericFocusBracket(): ColorScaleBin | undefined {
        const { focusBracket, focusValue } = this
        const { numericLegendData } = this
 
        if (focusBracket) return focusBracket
 
        if (focusValue !== undefined)
            return numericLegendData.find((bin) => bin.contains(focusValue))
 
        return undefined
    }
 
    @computed get categoricalFocusBracket(): CategoricalBin | undefined {
        const { focusBracket, focusValue } = this
        const { categoricalLegendData } = this
        if (focusBracket && focusBracket instanceof CategoricalBin)
            return focusBracket

        if (focusValue !== undefined)
            return categoricalLegendData.find((bin) => bin.contains(focusValue))

        return undefined
    }
 
    @computed get categoricalBinStroke(): Color {
        return DEFAULT_STROKE_COLOR
    }
 
    @computed get legendWidth(): number {
        return this.bounds.width * 0.8
    }
 
    @computed get legendHeight(): number {
        return this.categoryLegendHeight + this.numericLegendHeight + 10
    }
 
    @computed get numericLegendHeight(): number {
        return this.numericLegend ? this.numericLegend.height : 0
    }
 
    @computed get categoryLegendHeight(): number {
        return this.categoryLegend ? this.categoryLegend.height + 5 : 0
    }
 
    @computed get categoryLegend():
        | HorizontalCategoricalColorLegend
        | undefined {
        return this.categoricalLegendData.length > 1
            ? new HorizontalCategoricalColorLegend({ manager: this })
            : undefined
    }
 
    @computed get numericLegend(): HorizontalNumericColorLegend | undefined {
        return this.numericLegendData.length > 1
            ? new HorizontalNumericColorLegend({ manager: this })
            : undefined
    }
 
    @computed get legendX(): number {
        return this.bounds.centerX - this.legendWidth / 2
    }
 
    @computed get categoryLegendY(): number {
        const { categoryLegend, bounds, categoryLegendHeight } = this

        if (categoryLegend) return bounds.bottom - categoryLegendHeight
        return 0
    }
 
    @computed get legendAlign(): HorizontalAlign {
        return HorizontalAlign.center
    }
 
    @computed get numericLegendY(): number {
        const {
            numericLegend,
            numericLegendHeight,
            bounds,
            categoryLegendHeight,
        } = this
 
        if (numericLegend)
            return (
                bounds.bottom - categoryLegendHeight - numericLegendHeight - 4
            )
        return 0
    }
 
    renderMapLegend(): JSX.Element {
        const { numericLegend, categoryLegend } = this
 
        return (
            <g>
                {numericLegend && (
                    <HorizontalNumericColorLegend manager={this} />
                )}
                {categoryLegend && (
                    <HorizontalCategoricalColorLegend manager={this} />
                )}
            </g>
        )
    }
 
    render(): JSX.Element {
        if (this.failMessage)
            return (
                <NoDataModal
                    manager={this.manager}
                    bounds={this.props.bounds}
                    message={this.failMessage}
                />
            )
 
        const {
            focusBracket,
            focusEntity,
            tooltipTarget,
            projectionChooserBounds,
            seriesMap,
            colorScale,
            mapConfig,
        } = this
 
        const { projection } = mapConfig
 
        const tooltipDatum = tooltipTarget
            ? seriesMap.get(tooltipTarget.featureId)
            : undefined
 
        return (
            <g ref={this.base} className="mapTab">
                <ChoroplethMap
                    bounds={this.bounds.padBottom(this.legendHeight + 15)}
                    choroplethData={seriesMap}
                    projection={projection}
                    defaultFill={colorScale.noDataColor}
                    onHover={this.onMapMouseOver}
                    onHoverStop={this.onMapMouseLeave}
                    onClick={this.onClick}
                    focusBracket={focusBracket}
                    focusEntity={focusEntity}
                />
                {this.renderMapLegend()}
                <foreignObject
                    id="projection-chooser"
                    x={projectionChooserBounds.left}
                    y={projectionChooserBounds.top}
                    width={projectionChooserBounds.width}
                    height={projectionChooserBounds.height}
                    style={{
                        overflow: "visible",
                        height: "100%",
                        pointerEvents: "none",
                    }}
                >
                    <ProjectionChooser
                        value={projection}
                        onChange={this.onProjectionChange}
                    />
                </foreignObject>
                {tooltipTarget && (
                    <MapTooltip
                        tooltipDatum={tooltipDatum}
                        isEntityClickable={this.isEntityClickable(
                            tooltipTarget?.featureId
                        )}
                        tooltipTarget={tooltipTarget}
                        manager={this.manager}
                        colorScale={this.colorScale}
                        targetTime={this.targetTime}
                    />
                )}
            </g>
        )
    }
}
 
declare type SVGMouseEvent = React.MouseEvent<SVGElement>
 
@observer
class ChoroplethMap extends React.Component<ChoroplethMapProps> {
    base: React.RefObject<SVGGElement> = React.createRef()
 
    @computed private get uid(): number {
        return guid()
    }
 
    @computed.struct private get bounds(): Bounds {
        return this.props.bounds
    }
 
    @computed.struct private get choroplethData(): Map<
        string,
        ChoroplethSeries
    > {
        return this.props.choroplethData
    }
 
    @computed.struct private get defaultFill(): string {
        return this.props.defaultFill
    }
 
    // Combine bounding boxes to get the extents of the entire map
    @computed private get mapBounds(): Bounds {
        return Bounds.merge(geoBoundsFor(this.props.projection))
    }
 
    @computed private get focusBracket(): ColorScaleBin | undefined {
        return this.props.focusBracket
    }
 
    @computed private get focusEntity(): MapEntity | undefined {
        return this.props.focusEntity
    }
 
    // Check if a geo entity is currently focused, either directly or via the bracket
    private hasFocus(id: string): boolean {
        const { choroplethData, focusBracket, focusEntity } = this
        if (focusEntity && focusEntity.id === id) return true
        else if (!focusBracket) return false

        const datum = choroplethData.get(id) || null
        if (focusBracket.contains(datum?.value)) return true
        else return false
    }
 
    private isSelected(id: string): boolean | undefined {
        return this.choroplethData.get(id)!.isSelected
    }
 
    // Viewport for each projection, defined by center and width+height in fractional coordinates
    @computed private get viewport(): {
        x: number
        y: number
        width: number
        height: number
    } {
        const viewports = {
            World: { x: 0.565, y: 0.5, width: 1, height: 1 },
            Europe: { x: 0.5, y: 0.22, width: 0.2, height: 0.2 },
            Africa: { x: 0.49, y: 0.7, width: 0.21, height: 0.38 },
            NorthAmerica: { x: 0.49, y: 0.4, width: 0.19, height: 0.32 },
            SouthAmerica: { x: 0.52, y: 0.815, width: 0.1, height: 0.26 },
            Asia: { x: 0.75, y: 0.45, width: 0.3, height: 0.5 },
            Oceania: { x: 0.51, y: 0.75, width: 0.1, height: 0.2 },
        }
 
        return viewports[this.props.projection]
    }
 
    // Calculate what scaling should be applied to the untransformed map to match the current viewport to the container
    @computed private get viewportScale(): number {
        const { bounds, viewport, mapBounds } = this
        const viewportWidth = viewport.width * mapBounds.width
        const viewportHeight = viewport.height * mapBounds.height
        return Math.min(
            bounds.width / viewportWidth,
            bounds.height / viewportHeight
        )
    }
 
    @computed private get matrixTransform(): string {
        const { bounds, mapBounds, viewport, viewportScale } = this
 
        // Calculate our reference dimensions. These values are independent of the current
        // map translation and scaling.
        const mapX = mapBounds.x + 1
        const mapY = mapBounds.y + 1
 
        // Work out how to center the map, accounting for the new scaling we've worked out
        const newWidth = mapBounds.width * viewportScale
        const newHeight = mapBounds.height * viewportScale
        const boundsCenterX = bounds.left + bounds.width / 2
        const boundsCenterY = bounds.top + bounds.height / 2
        const newCenterX =
            mapX + (viewportScale - 1) * mapBounds.x + viewport.x * newWidth
        const newCenterY =
            mapY + (viewportScale - 1) * mapBounds.y + viewport.y * newHeight
        const newOffsetX = boundsCenterX - newCenterX
        const newOffsetY = boundsCenterY - newCenterY
 
        const matrixStr = `matrix(${viewportScale},0,0,${viewportScale},${newOffsetX},${newOffsetY})`
        return matrixStr
    }
 
    // Features that aren't part of the current projection (e.g. India if we're showing Africa)
    @computed private get featuresOutsideProjection(): RenderFeature[] {
        return difference(
            renderFeaturesFor(this.props.projection),
            this.featuresInProjection
        )
    }
 
    @computed private get featuresInProjection(): RenderFeature[] {
        const { projection } = this.props
        const features = renderFeaturesFor(this.props.projection)
        if (projection === MapProjectionName.World) return features

        return features.filter(
            (feature) =>
                projection ===
                (WorldRegionToProjection[
                    feature.id as WorldRegionName
                ] as any as MapProjectionName)
        )
    }
 
    @computed private get featuresWithNoData(): RenderFeature[] {
        return difference(this.featuresInProjection, this.featuresWithData)
    }
 
    @computed private get featuresWithData(): RenderFeature[] {
        return this.featuresInProjection.filter((feature) =>
            this.choroplethData.has(feature.id)
        )
    }
 
    // Map uses a hybrid approach to mouseover
    // If mouse is inside an element, that is prioritized
    // Otherwise we look for the closest center point of a feature bounds, so that we can hover
    // very small countries without trouble
 
    @observable private hoverEnterFeature?: RenderFeature
    @observable private hoverNearbyFeature?: RenderFeature
    @action.bound private onMouseMove(ev: React.MouseEvent<SVGGElement>): void {
        if (ev.shiftKey) this.showSelectedStyle = true // Turn on highlight selection. To turn off, user can switch tabs.
        if (this.hoverEnterFeature) return

        const { featuresInProjection } = this
        const subunits = this.base.current?.querySelector(".subunits")
        if (subunits) {
            const mouse = getRelativeMouse(subunits, ev)

            const featuresWithDistance = featuresInProjection.map((feature) => {
                return {
                    feature,
                    distance: PointVector.distance(feature.center, mouse),
                }
            })

            const feature = minBy(featuresWithDistance, (d) => d.distance)

            if (feature && feature.distance < 20) {
                if (feature.feature !== this.hoverNearbyFeature) {
                    this.hoverNearbyFeature = feature.feature
                    this.props.onHover(feature.feature.geo, ev)
                }
            } else {
                this.hoverNearbyFeature = undefined
                this.props.onHoverStop()
            }
        } else console.error("subunits was falsy")
    }
 
    @action.bound private onMouseEnter(
        feature: RenderFeature,
        ev: SVGMouseEvent
    ): void {
        this.hoverEnterFeature = feature
        this.props.onHover(feature.geo, ev)
    }
 
    @action.bound private onMouseLeave(): void {
        this.hoverEnterFeature = undefined
        this.props.onHoverStop()
    }
 
    @computed private get hoverFeature(): RenderFeature | undefined {
        return this.hoverEnterFeature || this.hoverNearbyFeature
    }
 
    @action.bound private onClick(ev: React.MouseEvent<SVGGElement>): void {
        if (this.hoverFeature !== undefined)
            this.props.onClick(this.hoverFeature.geo, ev)
    }
 
    // If true selected countries will have an outline
    @observable private showSelectedStyle = false
 
    // SVG layering is based on order of appearance in the element tree (later elements rendered on top)
    // The ordering here is quite careful
    render(): JSX.Element {
        const {
            uid,
            bounds,
            choroplethData,
            defaultFill,
            matrixTransform,
            viewportScale,
            featuresOutsideProjection,
            featuresWithNoData,
            featuresWithData,
        } = this
        const focusStrokeColor = "#111"
        const focusStrokeWidth = 1.5
        const selectedStrokeWidth = 1
        const blurFillOpacity = 0.2
        const blurStrokeOpacity = 0.5
 
        const clipPath = makeClipPath(uid, bounds)
 
        return (
            <g
                ref={this.base}
                className={CHOROPLETH_MAP_CLASSNAME}
                clipPath={clipPath.id}
                onMouseDown={
                    (ev: SVGMouseEvent): void =>
                        ev.preventDefault() /* Without this, title may get selected while shift clicking */
                }
                onMouseMove={this.onMouseMove}
                onMouseLeave={this.onMouseLeave}
                style={this.hoverFeature ? { cursor: "pointer" } : {}}
            >
                <rect
                    x={bounds.x}
                    y={bounds.y}
                    width={bounds.width}
                    height={bounds.height}
                    fill="rgba(255,255,255,0)"
                    opacity={0}
                />
                {clipPath.element}
                <g className="subunits" transform={matrixTransform}>
                    {featuresOutsideProjection.length && (
                        <g className="nonProjectionFeatures">
                            {featuresOutsideProjection.map((feature) => {
                                return (
                                    <path
                                        key={feature.id}
                                        d={feature.path}
                                        strokeWidth={0.3 / viewportScale}
                                        stroke={"#aaa"}
                                        fill={"#fff"}
                                    />
                                )
                            })}
                        </g>
                    )}
 
                    {featuresWithNoData.length && (
                        <g className="noDataFeatures">
                            {featuresWithNoData.map((feature) => {
                                const isFocus = this.hasFocus(feature.id)
                                const outOfFocusBracket =
                                    !!this.focusBracket && !isFocus
                                const stroke = isFocus
                                    ? focusStrokeColor
                                    : "#aaa"
                                const fillOpacity = outOfFocusBracket
                                    ? blurFillOpacity
                                    : 1
                                const strokeOpacity = outOfFocusBracket
                                    ? blurStrokeOpacity
                                    : 1
                                return (
                                    <path
                                        key={feature.id}
                                        d={feature.path}
                                        strokeWidth={
                                            (isFocus ? focusStrokeWidth : 0.3) /
                                            viewportScale
                                        }
                                        stroke={stroke}
                                        strokeOpacity={strokeOpacity}
                                        cursor="pointer"
                                        fill={defaultFill}
                                        fillOpacity={fillOpacity}
                                        onClick={(ev: SVGMouseEvent): void =>
                                            this.props.onClick(feature.geo, ev)
                                        }
                                        onMouseEnter={(ev): void =>
                                            this.onMouseEnter(feature, ev)
                                        }
                                        onMouseLeave={this.onMouseLeave}
                                    />
                                )
                            })}
                        </g>
                    )}
 
                    {sortBy(
                        featuresWithData.map((feature) => {
                            const isFocus = this.hasFocus(feature.id)
                            const showSelectedStyle =
                                this.showSelectedStyle &&
                                this.isSelected(feature.id)
                            const outOfFocusBracket =
                                !!this.focusBracket && !isFocus
                            const series = choroplethData.get(
                                feature.id as string
                            )
                            const stroke =
                                isFocus || showSelectedStyle
                                    ? focusStrokeColor
                                    : DEFAULT_STROKE_COLOR
                            const fill = series ? series.color : defaultFill
                            const fillOpacity = outOfFocusBracket
                                ? blurFillOpacity
                                : 1
                            const strokeOpacity = outOfFocusBracket
                                ? blurStrokeOpacity
                                : 1
 
                            return (
                                <path
                                    key={feature.id}
                                    d={feature.path}
                                    strokeWidth={
                                        (isFocus
                                            ? focusStrokeWidth
                                            : showSelectedStyle
                                            ? selectedStrokeWidth
                                            : 0.3) / viewportScale
                                    }
                                    stroke={stroke}
                                    strokeOpacity={strokeOpacity}
                                    cursor="pointer"
                                    fill={fill}
                                    fillOpacity={fillOpacity}
                                    onClick={(ev: SVGMouseEvent): void =>
                                        this.props.onClick(feature.geo, ev)
                                    }
                                    onMouseEnter={(ev): void =>
                                        this.onMouseEnter(feature, ev)
                                    }
                                    onMouseLeave={this.onMouseLeave}
                                />
                            )
                        }),
                        (p) => p.props["strokeWidth"]
                    )}
                </g>
            </g>
        )
    }
}