All files / owid-grapher/grapher/facetChart FacetChart.tsx

91.96% Statements 629/684
80.41% Branches 78/97
80.7% Functions 46/57
91.96% Lines 629/684

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 7781x 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 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 108x 108x 84x 84x 108x 54x 54x 1x 1x 108x 108x 108x 108x 108x 108x 108x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 14x 14x 6x 6x 15x 15x 6x 6x 15x 15x 15x 15x 15x 6x 6x 16x 16x 6x 6x 12x 12x 6x 6x     6x 6x 12x 12x 6x 6x 9x 9x 9x 6x 6x 9x 9x 9x     9x 9x 6x 6x 12x 12x 6x 6x 12x 12x 6x 6x 12x 12x 12x 12x 6x 6x 12x 12x 12x 12x 12x 6x 6x 9x 9x 9x 6x 6x 12x 12x 6x 6x 12x 12x 12x 12x 12x 12x 12x 12x 6x 6x 12x 12x 12x 12x 12x 12x 6x 6x 12x 12x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 12x 6x 6x 12x 60x 60x   60x 60x 12x 6x 6x 6x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 8x 9x 9x 9x 18x 18x 18x 18x 18x 18x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 18x 1x 1x 18x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 54x 54x 54x 54x 54x 54x 90x 90x 90x 90x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 9x 6x 6x 16x 16x 6x 6x 12x 12x 12x 12x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 12x 6x 6x 4x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 4x 6x 6x 4x 4x 6x 6x 4x 4x 6x 6x 16x 16x 6x 6x 16x 12x 12x 16x 6x 6x 6x 6x 10x 10x 10x 10x 10x 10x 6x 6x 10x 56x 10x 10x 6x 6x 9x 9x 9x   9x 9x 6x 6x 9x 9x 9x 9x 9x 9x 9x 9x                 9x 9x 9x     6x 6x 4x 4x 4x 14x     14x 4x 4x 6x 6x 10x 301x 301x 301x 301x 301x 301x 301x     10x 6x 6x 6x 6x 2x 2x 6x 6x     6x 6x 2x 2x 6x 6x 9x 9x 6x 6x 9x 9x 6x 6x     6x 6x     6x 6x 2x 2x 6x 6x     6x 6x     6x 6x 2x 2x 6x 6x     6x 6x     6x 6x     6x 6x     6x 6x 9x                           6x 6x 10x 10x 10x 56x 56x 56x 10x 10x 10x 10x 10x 29x 29x 10x 10x 10x 10x 10x 6x 6x 6x 6x 6x     6x                                                                                                                                                                                            
import React from "react"
import { observer } from "mobx-react"
import { Bounds, DEFAULT_BOUNDS } from "../../clientUtils/Bounds"
import { action, computed, observable } from "mobx"
import {
    BASE_FONT_SIZE,
    ChartTypeName,
    FacetAxisDomain,
    FacetStrategy,
    SeriesColorMap,
    SeriesStrategy,
} from "../core/GrapherConstants"
import {
    ChartComponentClassMap,
    DefaultChartClass,
} from "../chart/ChartTypeMap"
import { ChartManager } from "../chart/ChartManager"
import { ChartInterface } from "../chart/ChartInterface"
import { getChartPadding, getFontSize } from "./FacetChartUtils"
import {
    FacetSeries,
    FacetChartProps,
    PlacedFacetSeries,
} from "./FacetChartConstants"
import { OwidTable } from "../../coreTable/OwidTable"
import { autoDetectYColumnSlugs, makeSelectionArray } from "../chart/ChartUtils"
import { SelectionArray } from "../selection/SelectionArray"
import { CoreColumn } from "../../coreTable/CoreTableColumns"
import {
    excludeUndefined,
    flatten,
    getIdealGridParams,
    max,
    maxBy,
    min,
    sortBy,
    uniqWith,
    values,
} from "../../clientUtils/Util"
import { AxisConfigInterface } from "../axis/AxisConfigInterface"
import {
    IDEAL_PLOT_ASPECT_RATIO,
    GridParameters,
    Position,
    PositionMap,
    HorizontalAlign,
    Color,
} from "../../clientUtils/owidTypes"
import { AxisConfig } from "../axis/AxisConfig"
import { HorizontalAxis, VerticalAxis } from "../axis/Axis"
import {
    HorizontalCategoricalColorLegend,
    HorizontalColorLegend,
    HorizontalColorLegendManager,
    HorizontalNumericColorLegend,
} from "../horizontalColorLegend/HorizontalColorLegends"
import {
    CategoricalBin,
    ColorScaleBin,
    NumericBin,
} from "../color/ColorScaleBin"
import { shortenForTargetWidth } from "../text/TextWrap"
 
const facetBackgroundColor = "transparent" // we don't use color yet but may use it for background later
 
const getContentBounds = (
    containerBounds: Bounds,
    manager: ChartManager,
    chartInstance: ChartInterface
): Bounds => {
    let bounds = containerBounds
    const axes = [
        { config: manager.xAxisConfig, axis: chartInstance.xAxis },
        { config: manager.yAxisConfig, axis: chartInstance.yAxis },
    ]
    for (const { config, axis } of axes) {
        if (!config || !axis) continue
        if (!config.hideAxis && config.minSize !== undefined) {
            bounds = bounds.pad({ [axis.orient]: config.minSize })
        }
    }
    return bounds
}
 
const shouldHideFacetAxis = (
    axis: HorizontalAxis | VerticalAxis | undefined,
    edges: Set<Position>,
    sharedAxesSizes: PositionMap<number>
): boolean => {
    if (axis) {
        return axis.orient in sharedAxesSizes && !edges.has(axis.orient)
    }
    return false
}
 
interface AxisInfo {
    config: AxisConfigInterface
    axisAccessor: (
        instance: ChartInterface
    ) => HorizontalAxis | VerticalAxis | undefined
    uniform: boolean
    /** only considered when `uniform` is `true`, otherwise ignored */
    shared: boolean
}
 
interface AxesInfo {
    x: AxisInfo
    y: AxisInfo
}
 
@observer
export class FacetChart
    extends React.Component<FacetChartProps>
    implements ChartInterface, HorizontalColorLegendManager
{
    transformTable(table: OwidTable): OwidTable {
        return table
    }
 
    @computed get inputTable(): OwidTable {
        return this.manager.table
    }
 
    @computed get transformedTable(): OwidTable {
        return (
            this.manager.transformedTable ??
            this.transformTable(this.inputTable)
        )
    }
 
    @computed private get manager(): ChartManager {
        return this.props.manager
    }
 
    @computed private get chartTypeName(): ChartTypeName {
        return this.props.chartTypeName ?? ChartTypeName.LineChart
    }
 
    @computed get failMessage(): string {
        return ""
    }
 
    @computed private get bounds(): Bounds {
        return this.props.bounds ?? DEFAULT_BOUNDS
    }
 
    @computed private get legendPadding(): number {
        const { isNumericLegend, fontSize } = this
        return isNumericLegend ? 1.5 * fontSize : 0.875 * fontSize
    }
 
    @computed private get facetsContainerBounds(): Bounds {
        const fontSize = this.facetFontSize
        const legendHeightWithPadding =
            this.showLegend && this.legend.height > 0
                ? this.legend.height + this.legendPadding
                : 0
        return this.bounds.padTop(legendHeightWithPadding + 1.8 * fontSize)
    }
 
    @computed get fontSize(): number {
        return this.manager.baseFontSize ?? BASE_FONT_SIZE
    }
 
    @computed private get facetFontSize(): number {
        return getFontSize(this.series.length, this.fontSize)
    }
 
    @computed private get yAxisConfig(): AxisConfig {
        return new AxisConfig(this.manager.yAxisConfig, {
            fontSize: this.facetFontSize,
        })
    }
 
    @computed private get uniformYAxis(): boolean {
        // default to shared
        const facetDomain =
            this.yAxisConfig.facetDomain || FacetAxisDomain.shared
        return facetDomain === FacetAxisDomain.shared
    }
 
    @computed private get uniformXAxis(): boolean {
        // TODO: maybe should not be the default for ScatterPlot?
        return true
    }
 
    @computed private get facetCount(): number {
        return this.series.length
    }
 
    @computed private get gridParams(): GridParameters {
        const count = this.facetCount
        const { width, height } = this.bounds
        return getIdealGridParams({
            count,
            containerAspectRatio: width / height,
            idealAspectRatio: IDEAL_PLOT_ASPECT_RATIO,
        })
    }
 
    @computed private get facetGridPadding(): {
        rowPadding: number
        columnPadding: number
        outerPadding: number
    } {
        return getChartPadding(this.facetCount, this.facetFontSize)
    }
 
    @computed private get hideFacetLegends(): boolean {
        return true
    }
 
    // Passing this color map is important to ensure that all facets use the same entity colors
    seriesColorMap: SeriesColorMap = new Map()
 
    /**
     * Holds the intermediate render properties for chart views, before axes are synchronized,
     * collapsed, aligned, etc.
     *
     * An example: a StackedArea has a Y axis domain that is the largest sum of all columns.
     * In order to avoid replicating that logic here (stacking values), we initialize StackedArea
     * instances, without rendering them. In a later method, we use those intermediate chart views to
     * determine the final axes for facets, e.g. for a uniform axis, we would iterate through all
     * instances to find the full extent of the domain.
     *
     * @danielgavrilov, 2021-07-13
     */
    @computed private get intermediatePlacedSeries(): PlacedFacetSeries[] {
        const { manager, series, facetCount, seriesColorMap } = this
 
        // Copy properties from manager to facets
        const baseFontSize = this.facetFontSize
        // We are using `bounds` instead of `facetsContainerBounds` because the legend
        // is not yet created, and it is derived from the intermediate chart series.
        const gridBoundsArr = this.bounds.grid(
            this.gridParams,
            this.facetGridPadding
        )
 
        const {
            yColumnSlug,
            xColumnSlug,
            yColumnSlugs,
            colorColumnSlug,
            sizeColumnSlug,
            isRelativeMode,
            colorScale,
            sortConfig,
        } = manager
 
        // Use compact labels, e.g. 50k instead of 50,000.
        const compactLabels = facetCount > 2
        const globalXAxisConfig: AxisConfigInterface = {
            compactLabels,
        }
        const globalYAxisConfig: AxisConfigInterface = {
            compactLabels,
        }
 
        // We infer that the user cares about the trend if the axis is not uniform
        // and the metrics on all facets are the same
        const careAboutTrend =
            !this.uniformYAxis && this.facetStrategy === FacetStrategy.entity
        if (careAboutTrend) {
            // Force disable nice axes if we care about the trend,
            // because nice axes misrepresent trends.
            globalYAxisConfig.nice = false
        }
 
        const table = this.transformedTable
 
        // In order to produce consistent color scales across facets, we need to pass
        // all possible color values from `inputTable`.
        const colorScaleColumnOverride = this.inputTable.get(colorColumnSlug)
 
        return series.map((series, index) => {
            const { bounds } = gridBoundsArr[index]
            const hideLegend = this.hideFacetLegends
            const hidePoints = true
 
            // NOTE: The order of overrides is important!
            // We need to preserve most config coming in.
            const manager: ChartManager = {
                table,
                baseFontSize,
                hideLegend,
                hidePoints,
                yColumnSlug,
                xColumnSlug,
                yColumnSlugs,
                colorColumnSlug,
                sizeColumnSlug,
                isRelativeMode,
                seriesColorMap,
                colorScale,
                colorScaleColumnOverride,
                sortConfig,
                ...series.manager,
                xAxisConfig: {
                    ...globalXAxisConfig,
                    ...this.manager.xAxisConfig,
                    ...series.manager.xAxisConfig,
                },
                yAxisConfig: {
                    ...globalYAxisConfig,
                    ...this.manager.yAxisConfig,
                    ...series.manager.yAxisConfig,
                },
            }
            return {
                bounds,
                contentBounds: bounds,
                manager,
                seriesName: series.seriesName,
                color: series.color,
            }
        })
    }
 
    @computed private get intermediateChartInstances(): ChartInterface[] {
        return this.intermediatePlacedSeries.map(({ bounds, manager }) => {
            const ChartClass =
                ChartComponentClassMap.get(this.chartTypeName) ??
                DefaultChartClass
            return new ChartClass({ bounds, manager })
        })
    }
 
    // Only made public for testing
    @computed get placedSeries(): PlacedFacetSeries[] {
        const { intermediateChartInstances } = this
        // Define the global axis config, shared between all facets
        const sharedAxesSizes: PositionMap<number> = {}
        const axes: AxesInfo = {
            x: {
                config: {},
                axisAccessor: (instance) => instance.xAxis,
                uniform: this.uniformXAxis,
                // For now, X axes are never shared for any chart.
                // If we ever allow them to be shared, we need to be careful with how we determine
                // the `minSize` – in the intermediate series (at this time) all axes are shown in
                // order to find the one with maximum size, but in the placed series, some axes are
                // hidden. This expands the available area for the chart, which can in turn increase
                // the number of ticks shown, which can make the size of the axis in the placed
                // series greater than the one in the intermediate series.
                shared: false,
            },
            y: {
                config: {},
                axisAccessor: (instance) => instance.yAxis,
                uniform: this.uniformYAxis,
                shared:
                    this.uniformYAxis &&
                    this.chartTypeName !== ChartTypeName.StackedDiscreteBar,
            },
        }
        values(axes).forEach(({ config, axisAccessor, uniform, shared }) => {
            // max size is the width (if vertical axis) or height (if horizontal axis)
            const axisWithMaxSize = maxBy(
                intermediateChartInstances.map(axisAccessor),
                (axis) => axis?.size
            )
            if (uniform) {
                // If the axes are uniform, we want to find the full domain extent across all facets
                const domains = excludeUndefined(
                    intermediateChartInstances
                        .map(axisAccessor)
                        .map((axis) => axis?.domain)
                )
                config.min = min(domains.map((d) => d[0]))
                config.max = max(domains.map((d) => d[1]))
                // If there was at least one chart with a non-undefined axis,
                // this variable will be populated
                if (axisWithMaxSize) {
                    // Create a new axis object with the full domain extent
                    const axis = axisWithMaxSize.clone()
                    const { size } = axis.updateDomainPreservingUserSettings([
                        config.min,
                        config.max,
                    ])
                    config.minSize = size
                    if (shared) sharedAxesSizes[axis.orient] = size
                }
            } else if (axisWithMaxSize) {
                config.minSize = axisWithMaxSize.size
            }
        })
 
        // Allocate space for shared axes, so that the content areas of charts are all equal.
        // If the axes are "shared", then an axis will only plotted on the facets that are on the
        // same side as the axis.
        // For example, a vertical Y axis would be plotted on the left-most charts only.
        // An exception is the bottom axis, which gets plotted on the top row of charts, instead of
        // the bottom row of charts.
        const fullBounds = this.facetsContainerBounds.pad(sharedAxesSizes)
        const gridBoundsArr = fullBounds.grid(
            this.gridParams,
            this.facetGridPadding
        )
        return this.intermediatePlacedSeries.map((series, i) => {
            const chartInstance = intermediateChartInstances[i]
            const { xAxis, yAxis } = chartInstance
            const { bounds: initialGridBounds, edges } = gridBoundsArr[i]
            let bounds = initialGridBounds
            // Only expand bounds if the facet is on the same edge as the shared axes
            for (const edge of edges) {
                bounds = bounds.expand({
                    [edge]: sharedAxesSizes[edge],
                })
            }
            // NOTE: The order of overrides is important!
            // We need to preserve most config coming in.
            const manager = {
                ...series.manager,
                externalLegendFocusBin: this.legendFocusBin,
                xAxisConfig: {
                    hideAxis: shouldHideFacetAxis(
                        xAxis,
                        edges,
                        sharedAxesSizes
                    ),
                    ...series.manager.xAxisConfig,
                    ...axes.x.config,
                },
                yAxisConfig: {
                    hideAxis: shouldHideFacetAxis(
                        yAxis,
                        edges,
                        sharedAxesSizes
                    ),
                    ...series.manager.yAxisConfig,
                    ...axes.y.config,
                },
            }
            const contentBounds = getContentBounds(
                bounds,
                manager,
                chartInstance
            )
            return {
                ...series,
                bounds,
                contentBounds,
                manager,
            }
        })
    }
 
    @computed private get selectionArray(): SelectionArray {
        return makeSelectionArray(this.manager)
    }
 
    @computed private get entityFacets(): FacetSeries[] {
        const table = this.transformedTable.filterByEntityNames(
            this.selectionArray.selectedEntityNames
        )
        return this.selectionArray.selectedEntityNames.map((seriesName) => {
            const seriesTable = table.filterByEntityNames([seriesName])
            // Only set overrides for this facet strategy.
            // Default properties are set elsewhere.
            const manager: ChartManager = {
                table: seriesTable,
                selection: [seriesName],
                seriesStrategy: SeriesStrategy.column,
            }
            return {
                seriesName,
                color: facetBackgroundColor,
                manager,
            }
        })
    }
 
    @computed private get columnFacets(): FacetSeries[] {
        return this.yColumns.map((col) => {
            // Only set overrides for this facet strategy.
            // Default properties are set elsewhere.
            return {
                seriesName: col.displayName,
                color: facetBackgroundColor,
                manager: {
                    selection: this.selectionArray,
                    yColumnSlug: col.slug,
                    yColumnSlugs: [col.slug],
                    seriesStrategy: SeriesStrategy.entity,
                },
            }
        })
    }
 
    @computed private get yColumns(): CoreColumn[] {
        return this.yColumnSlugs.map((slug) => this.inputTable.get(slug))
    }
 
    @computed private get yColumnSlugs(): string[] {
        return autoDetectYColumnSlugs(this.manager)
    }
 
    @computed private get facetStrategy(): FacetStrategy {
        return this.manager.facetStrategy ?? FacetStrategy.none
    }
 
    @computed get series(): FacetSeries[] {
        return this.facetStrategy === FacetStrategy.metric
            ? this.columnFacets
            : this.entityFacets
    }
 
    // legend utils
 
    @computed private get externalLegends(): HorizontalColorLegendManager[] {
        return excludeUndefined(
            this.intermediateChartInstances.map(
                (instance) => instance.externalLegend
            )
        )
    }
 
    @computed private get isNumericLegend(): boolean {
        return this.externalLegends.some((legend) =>
            legend.numericLegendData?.some((bin) => bin instanceof NumericBin)
        )
    }
 
    @computed private get LegendClass():
        | typeof HorizontalNumericColorLegend
        | typeof HorizontalCategoricalColorLegend {
        return this.isNumericLegend
            ? HorizontalNumericColorLegend
            : HorizontalCategoricalColorLegend
    }
 
    @computed private get showLegend(): boolean {
        const { isNumericLegend, categoricalLegendData, numericLegendData } =
            this
        const hasBins =
            categoricalLegendData.length > 0 || numericLegendData.length > 0
        if (!hasBins) return false
        if (isNumericLegend) return true
        if (
            categoricalLegendData.length > 1 ||
            // If the facetStrategy is metric, then the legend (probably?) shows entity items.
            // If the user happens to select only a single entity, we don't want to collapse the
            // legend, because it's (probably?) the only information about what is selected.
            // This is fragile and ideally we shouldn't be making assumptions about what type of
            // items are shown on the legend, but it works for now...
            // -@danielgavrilov, 2021-09-28
            (this.facetStrategy === FacetStrategy.metric &&
                this.props.manager.canSelectMultipleEntities)
        ) {
            return true
        }
        return false
    }
 
    private getExternalLegendProp<
        Prop extends keyof HorizontalColorLegendManager
    >(prop: Prop): HorizontalColorLegendManager[Prop] | undefined {
        for (const externalLegend of this.externalLegends) {
            if (externalLegend[prop] !== undefined) {
                return externalLegend[prop]
            }
        }
        return undefined
    }
 
    private getUniqBins<Bin extends ColorScaleBin>(bins: Bin[]): Bin[] {
        return uniqWith(bins, (binA, binB): boolean => {
            // For categorical bins, the `.equals()` method isn't good enough,
            // because it only compares `.index`, which in this case can be
            // identical even when the bins are not, because they are coming
            // from different charts (facets).
            if (binA instanceof CategoricalBin) {
                return binA.text === binB.text
            }
            return binA.equals(binB)
        })
    }
 
    // legend props
 
    @computed get legendX(): number {
        return this.bounds.x
    }
 
    @computed get numericLegendY(): number {
        return this.bounds.top
    }
 
    @computed get categoryLegendY(): number {
        return this.bounds.top
    }
 
    @computed get legendMaxWidth(): number {
        return this.bounds.width
    }
 
    @computed get legendAlign(): HorizontalAlign {
        return HorizontalAlign.center
    }
 
    @computed get legendTitle(): string | undefined {
        return this.getExternalLegendProp("legendTitle")
    }
 
    @computed get legendHeight(): number | undefined {
        return this.getExternalLegendProp("legendHeight")
    }
 
    @computed get legendOpacity(): number | undefined {
        return this.getExternalLegendProp("legendOpacity")
    }
 
    @computed get legendTextColor(): Color | undefined {
        return this.getExternalLegendProp("legendTextColor")
    }
 
    @computed get legendTickSize(): number | undefined {
        return this.getExternalLegendProp("legendTickSize")
    }
 
    @computed get categoricalBinStroke(): Color | undefined {
        return this.getExternalLegendProp("categoricalBinStroke")
    }
 
    @computed get numericBinSize(): number | undefined {
        return this.getExternalLegendProp("numericBinSize")
    }
 
    @computed get numericBinStroke(): Color | undefined {
        return this.getExternalLegendProp("numericBinStroke")
    }
 
    @computed get numericBinStrokeWidth(): number | undefined {
        return this.getExternalLegendProp("numericBinStrokeWidth")
    }
 
    @computed get equalSizeBins(): boolean | undefined {
        return this.getExternalLegendProp("equalSizeBins")
    }
 
    @computed get numericLegendData(): ColorScaleBin[] {
        if (!this.isNumericLegend || !this.hideFacetLegends) return []
        const allBins: ColorScaleBin[] = flatten(
            this.externalLegends.map((legend) => [
                ...(legend.numericLegendData ?? []),
                ...(legend.categoricalLegendData ?? []),
            ])
        )
        const uniqBins = this.getUniqBins(allBins)
        const sortedBins = sortBy(
            uniqBins,
            (bin) => bin instanceof CategoricalBin
        )
        return sortedBins
    }
 
    @computed get categoricalLegendData(): CategoricalBin[] {
        if (this.isNumericLegend || !this.hideFacetLegends) return []
        const allBins: CategoricalBin[] = flatten(
            this.externalLegends.map((legend) => [
                ...(legend.numericLegendData ?? []),
                ...(legend.categoricalLegendData ?? []),
            ])
        ).filter((bin) => bin instanceof CategoricalBin) as CategoricalBin[]
        const uniqBins = this.getUniqBins(allBins)
        const newBins = uniqBins.map(
            // remap index to ensure it's unique (the above procedure can lead to duplicates)
            (bin, index) =>
                new CategoricalBin({
                    ...bin.props,
                    index,
                })
        )
        return newBins
    }
 
    @observable.ref private legendFocusBin: ColorScaleBin | undefined =
        undefined
 
    @action.bound onLegendMouseOver(bin: ColorScaleBin): void {
        this.legendFocusBin = bin
    }
 
    @action.bound onLegendMouseLeave(): void {
        this.legendFocusBin = undefined
    }
 
    // end of legend props
 
    @computed private get legend(): HorizontalColorLegend {
        return new this.LegendClass({ manager: this })
    }
 
    /**
     * In order to display a potentially long facet label in the potentially tight space, we
     * shrink and shorten the label as follows to prevent overlap between neighbouring labels:
     * - If the label already fits, we're happy :)
     * - Otherwise, we calculate the ideal font size where it would fit perfectly.
     *   However, in order to not make the label tiny, we cap the font size at 0.7 * baseFontSize
     * - If the label still doesn't fit, we shorten it to the number of characters that fit and append an ellispsis (…)
     * -@MarcelGerber, 2021-10-28
     */
    private shrinkAndShortenFacetLabel(
        label: string,
        availableWidth: number,
        baseFontSize: number // font size to use when we're not shrinking
    ): { fontSize: number; shortenedLabel: string } {
        // How much width would we need if we were to render the text at font size 1?
        // We calculate this to compute the ideal font size from the available width.
        const textBounds = Bounds.forText(label, {
            fontSize: 1,
        })
        const idealFontSize = availableWidth / textBounds.width
 
        // Clamp the ideal font size: 0.7 * baseFontSize <= fontSize <= baseFontSize
        const fontSize = Math.min(
            baseFontSize,
            Math.max(0.7 * baseFontSize, idealFontSize)
        )
 
        if (fontSize > idealFontSize) {
            const ellipsisWidth = Bounds.forText("…", {
                fontSize,
            }).width
 
            label = `${shortenForTargetWidth(
                label,
                availableWidth - ellipsisWidth,
                { fontSize }
            )}…`
        }
        return { fontSize, shortenedLabel: label }
    }
 
    render(): JSX.Element {
        const { facetFontSize, LegendClass, showLegend } = this
        return (
            <React.Fragment>
                {showLegend && <LegendClass manager={this} />}
                {this.placedSeries.map((facetChart, index: number) => {
                    const ChartClass =
                        ChartComponentClassMap.get(this.chartTypeName) ??
                        DefaultChartClass
                    const { bounds, contentBounds, seriesName } = facetChart
                    const shiftTop = facetFontSize * 0.9
 
                    const { fontSize, shortenedLabel } =
                        this.shrinkAndShortenFacetLabel(
                            seriesName,
                            contentBounds.width,
                            facetFontSize
                        )
 
                    return (
                        <React.Fragment key={index}>
                            <text
                                x={contentBounds.x}
                                y={contentBounds.top - shiftTop}
                                fill={"#1d3d63"}
                                fontSize={fontSize}
                                style={{ fontWeight: 700 }}
                            >
                                {shortenedLabel}
                                <title>{seriesName}</title>
                            </text>
                            <ChartClass
                                bounds={bounds}
                                manager={facetChart.manager}
                            />
                        </React.Fragment>
                    )
                })}
            </React.Fragment>
        )
    }
}