All files / owid-grapher/grapher/barCharts DiscreteBarChart.tsx

87.74% Statements 601/685
67.62% Branches 71/105
85% Functions 51/60
87.74% Lines 601/685

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 7471x 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 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 30x 11x 11x 11x 11x 11x 11x 11x 11x 30x 30x 11x 11x 11x 11x 11x 11x 11x 11x             11x 11x 11x 32x 32x 1x 1x 32x 32x 2x 2x 2x 2x 2x 32x 32x 32x 32x 32x 32x 2x 2x 32x 32x 11x 11x 32x 32x 4x 4x 32x 32x 4x 4x 4x 4x 32x 32x 4x 4x 32x 32x 4x 4x 4x 4x 4x 4x 4x 4x 32x 32x 4x 4x 4x 4x 4x 4x 4x 4x 32x 32x 32x 4x 4x 4x 4x 32x 32x 4x 4x 32x 32x 4x 4x 32x 32x 32x 4x 4x 4x 4x 4x 4x 4x 4x 32x 32x 32x 32x 32x 4x                     32x 32x 4x     4x 4x 32x 32x 32x 4x 4x 4x 4x 4x 4x 32x 32x 4x 4x 4x 4x 4x 4x 4x 32x 32x 11x 11x 32x 32x 4x 4x 4x 4x 4x 4x 4x 4x 4x 32x 32x 4x 4x 4x 4x 4x 32x 32x 12x 12x 32x 32x 32x 4x 4x 32x 32x 4x 4x 32x 32x 4x 4x 32x 32x 27x 27x 229x 229x   229x 229x   229x 229x 229x 229x 27x 32x 32x 27x 27x 32x 32x 8x 8x 32x 32x 4x 4x 4x 4x 32x 32x 4x 4x 4x 4x 32x 32x           32x 32x 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 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 27x 27x 27x 27x 27x 27x 27x 27x 27x 4x 4x 4x 32x 32x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 32x 32x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 2x 2x 32x 32x 32x 32x 32x 32x 12x 12x 32x 32x 1x 1x 32x 32x 1x 1x 1x 1x 1x   1x     1x 1x 32x 32x 2x 2x 32x 32x 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 1x 32x 32x 3x 3x 6x 3x 3x 3x 32x 32x 1x 1x 1x 32x 32x 1x 1x 32x 32x 1x 1x     1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 32x 32x 1x 1x 1x     1x 1x 1x   1x 1x 1x 32x 32x 1x 1x 1x 1x 1x 1x 1x 32x 32x 32x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 32x 32x 1x 1x 32x 32x 32x 32x                     32x 32x           32x 32x           32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 4x 4x 32x 32x     32x 32x     32x 32x     32x 32x 32x             32x 32x 32x                                                                                                                                
import * as React from "react"
import { select } from "d3-selection"
import {
    min,
    max,
    maxBy,
    sortBy,
    exposeInstanceOnWindow,
    uniq,
    flatten,
} from "../../clientUtils/Util"
import { computed } from "mobx"
import { observer } from "mobx-react"
import { Bounds, DEFAULT_BOUNDS } from "../../clientUtils/Bounds"
import {
    ScaleType,
    BASE_FONT_SIZE,
    SeriesStrategy,
} from "../core/GrapherConstants"
import {
    HorizontalAxisComponent,
    HorizontalAxisGridLines,
} from "../axis/AxisViews"
import { NoDataModal } from "../noDataModal/NoDataModal"
import { AxisConfig, FontSizeManager } from "../axis/AxisConfig"
import { ColorSchemes } from "../color/ColorSchemes"
import { ChartInterface } from "../chart/ChartInterface"
import {
    BACKGROUND_COLOR,
    DEFAULT_BAR_COLOR,
    DiscreteBarChartManager,
    DiscreteBarSeries,
} from "./DiscreteBarChartConstants"
import { OwidTable } from "../../coreTable/OwidTable"
import {
    autoDetectSeriesStrategy,
    autoDetectYColumnSlugs,
    makeSelectionArray,
} from "../chart/ChartUtils"
import { HorizontalAxis } from "../axis/Axis"
import { SelectionArray } from "../selection/SelectionArray"
import { CoreColumn } from "../../coreTable/CoreTableColumns"
import { ColorScheme } from "../color/ColorScheme"
import {
    Time,
    SortOrder,
    SortBy,
    SortConfig,
    Color,
    HorizontalAlign,
} from "../../clientUtils/owidTypes"
import { CategoricalColorAssigner } from "../color/CategoricalColorAssigner"
import { ColorScale, ColorScaleManager } from "../color/ColorScale"
import {
    ColorScaleConfig,
    ColorScaleConfigInterface,
} from "../color/ColorScaleConfig"
import { ColorSchemeName } from "../color/ColorConstants"
import { darkenColorForLine } from "../color/ColorUtils"
import { CoreValueType } from "../../coreTable/CoreTableConstants"
import { isNotErrorValue } from "../../coreTable/ErrorValues"
import {
    CategoricalBin,
    ColorScaleBin,
    NumericBin,
} from "../color/ColorScaleBin"
import { HorizontalNumericColorLegend } from "../horizontalColorLegend/HorizontalColorLegends"
 
const labelToTextPadding = 10
const labelToBarPadding = 5
 
const LEGEND_PADDING = 25
 
interface DiscreteBarItem {
    seriesName: string
    value: number
    time: number
    colorValue?: CoreValueType
    color?: Color
}
 
@observer
export class DiscreteBarChart
    extends React.Component<{
        bounds?: Bounds
        manager: DiscreteBarChartManager
    }>
    implements ChartInterface, FontSizeManager, ColorScaleManager
{
    base: React.RefObject<SVGGElement> = React.createRef()
 
    transformTable(table: OwidTable): OwidTable {
        if (!this.yColumnSlugs.length) return table
 
        table = table.filterByEntityNames(
            this.selectionArray.selectedEntityNames
        )
 
        // TODO: remove this filter once we don't have mixed type columns in datasets
        table = table.replaceNonNumericCellsWithErrorValues(this.yColumnSlugs)
 
        if (this.isLogScale)
            table = table.replaceNonPositiveCellsForLogScale(this.yColumnSlugs)
 
        table = table.dropRowsWithErrorValuesForAllColumns(this.yColumnSlugs)
 
        this.yColumnSlugs.forEach((slug) => {
            table = table.interpolateColumnWithTolerance(slug)
        })
 
        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 get transformedTable(): OwidTable {
        return (
            this.manager.transformedTable ??
            this.transformTable(this.inputTable)
        )
    }
 
    @computed private get manager(): DiscreteBarChartManager {
        return this.props.manager
    }
 
    @computed private get targetTime(): Time | undefined {
        return this.manager.endTime
    }
 
    @computed private get isLogScale(): boolean {
        return this.yAxisConfig.scaleType === ScaleType.log
    }
 
    @computed private get bounds(): Bounds {
        return (this.props.bounds ?? DEFAULT_BOUNDS).padRight(10)
    }
 
    @computed private get boundsWithoutColorLegend(): Bounds {
        return this.bounds.padTop(
            this.hasColorLegend ? this.legendHeight + LEGEND_PADDING : 0
        )
    }
 
    @computed get fontSize(): number {
        return this.manager.baseFontSize ?? BASE_FONT_SIZE
    }
 
    @computed private get legendLabelStyle(): {
        fontSize: number
        fontWeight: number
    } {
        return {
            fontSize: 0.75 * this.fontSize,
            fontWeight: 700,
        }
    }
 
    @computed private get valueLabelStyle(): {
        fontSize: number
        fontWeight: number
    } {
        return {
            fontSize: 0.75 * this.fontSize,
            fontWeight: 400,
        }
    }
 
    // Account for the width of the legend
    @computed private get seriesLegendWidth(): number {
        const labels = this.series.map((series) => series.seriesName)
        const longestLabel = maxBy(labels, (d) => d.length)
        return Bounds.forText(longestLabel, this.legendLabelStyle).width
    }
 
    @computed private get hasPositive(): boolean {
        return this.series.some((d) => d.value >= 0)
    }
 
    @computed private get hasNegative(): boolean {
        return this.series.some((d) => d.value < 0)
    }
 
    // The amount of space we need to allocate for bar end labels on the right
    @computed private get rightValueLabelWidth(): number {
        if (!this.hasPositive) return 0
 
        const positiveLabels = this.series
            .filter((d) => d.value >= 0)
            .map((d) => this.formatValue(d))
        const longestPositiveLabel = maxBy(positiveLabels, (l) => l.length)
        return Bounds.forText(longestPositiveLabel, this.valueLabelStyle).width
    }
 
    // The amount of space we need to allocate for bar end labels on the left
    // These are only present if there are negative values
    // We pad this a little so it doesn't run directly up against the bar labels themselves
    @computed private get leftValueLabelWidth(): number {
        if (!this.hasNegative) return 0

        const negativeLabels = this.series
            .filter((d) => d.value < 0)
            .map((d) => this.formatValue(d))
        const longestNegativeLabel = maxBy(negativeLabels, (l) => l.length)
        return (
            Bounds.forText(longestNegativeLabel, this.valueLabelStyle).width +
            labelToTextPadding
        )
    }
 
    @computed private get x0(): number {
        if (!this.isLogScale) return 0

        const minValue = min(this.series.map((d) => d.value))
        return minValue !== undefined ? Math.min(1, minValue) : 1
    }
 
    // Now we can work out the main x axis scale
    @computed private get xDomainDefault(): [number, number] {
        const allValues = this.series.map((d) => d.value)
        return [
            Math.min(this.x0, min(allValues) as number),
            Math.max(this.x0, max(allValues) as number),
        ]
    }
 
    @computed private get xRange(): [number, number] {
        return [
            this.boundsWithoutColorLegend.left +
                this.seriesLegendWidth +
                this.leftValueLabelWidth,
            this.boundsWithoutColorLegend.right - this.rightValueLabelWidth,
        ]
    }
 
    @computed private get yAxisConfig(): AxisConfig {
        return new AxisConfig(this.manager.yAxisConfig, this)
    }
 
    @computed get yAxis(): HorizontalAxis {
        // NB: We use the user's YAxis options here to make the XAxis
        const axis = this.yAxisConfig.toHorizontalAxis()
        axis.updateDomainPreservingUserSettings(this.xDomainDefault)
 
        axis.formatColumn = this.yColumns[0] // todo: does this work for columns as series?
        axis.range = this.xRange
        axis.label = ""
        return axis
    }
 
    @computed private get innerBounds(): Bounds {
        return this.boundsWithoutColorLegend
            .padLeft(this.seriesLegendWidth + this.leftValueLabelWidth)
            .padBottom(this.yAxis.height)
            .padRight(this.rightValueLabelWidth)
    }
 
    @computed private get selectionArray(): SelectionArray {
        return makeSelectionArray(this.manager)
    }
 
    // Leave space for extra bar at bottom to show "Add country" button
    @computed private get barCount(): number {
        return this.series.length
    }
 
    @computed private get barHeight(): number {
        return (0.8 * this.innerBounds.height) / this.barCount
    }
 
    @computed private get barSpacing(): number {
        return this.innerBounds.height / this.barCount - this.barHeight
    }
 
    @computed private get barPlacements(): { x: number; width: number }[] {
        const { series, yAxis } = this
        return series.map((d) => {
            const isNegative = d.value < 0
            const barX = isNegative
                ? yAxis.place(d.value)
                : yAxis.place(this.x0)
            const barWidth = isNegative
                ? yAxis.place(this.x0) - barX
                : yAxis.place(d.value) - barX
 
            return { x: barX, width: barWidth }
        })
    }
 
    @computed private get barWidths(): number[] {
        return this.barPlacements.map((b) => b.width)
    }
 
    private d3Bars() {
        return select(this.base.current).selectAll("g.bar > rect")
    }
 
    private animateBarWidth(): void {
        this.d3Bars()
            .transition()
            .attr("width", (_, i) => this.barWidths[i])
    }
 
    componentDidMount(): void {
        this.d3Bars().attr("width", 0)
        this.animateBarWidth()
        exposeInstanceOnWindow(this)
    }
 
    componentDidUpdate(): void {
        // Animating the bar width after a render ensures there's no race condition, where the
        // initial animation (in componentDidMount) did override the now-changed bar width in
        // some cases. Updating the animation with the updated bar widths fixes that.
        this.animateBarWidth()
    }
 
    render(): JSX.Element {
        if (this.failMessage)
            return (
                <NoDataModal
                    manager={this.manager}
                    bounds={this.bounds}
                    message={this.failMessage}
                />
            )
 
        const {
            series,
            boundsWithoutColorLegend,
            yAxis,
            innerBounds,
            barHeight,
            barSpacing,
        } = this
 
        let yOffset = innerBounds.top + barHeight / 2
 
        return (
            <g ref={this.base} className="DiscreteBarChart">
                <rect
                    x={boundsWithoutColorLegend.left}
                    y={boundsWithoutColorLegend.top}
                    width={boundsWithoutColorLegend.width}
                    height={boundsWithoutColorLegend.height}
                    opacity={0}
                    fill="rgba(255,255,255,0)"
                />
                {this.hasColorLegend && (
                    <HorizontalNumericColorLegend manager={this} />
                )}
                <HorizontalAxisComponent
                    bounds={boundsWithoutColorLegend}
                    axis={yAxis}
                    preferredAxisPosition={innerBounds.bottom}
                />
                <HorizontalAxisGridLines
                    horizontalAxis={yAxis}
                    bounds={innerBounds}
                />
                {series.map((series) => {
                    // Todo: add a "placedSeries" getter to get the transformed series, then just loop over the placedSeries and render a bar for each
                    const isNegative = series.value < 0
                    const barX = isNegative
                        ? yAxis.place(series.value)
                        : yAxis.place(this.x0)
                    const barWidth = isNegative
                        ? yAxis.place(this.x0) - barX
                        : yAxis.place(series.value) - barX
                    const barColor = series.color
                    const valueLabel = this.formatValue(series)
                    const labelX = isNegative
                        ? barX -
                          Bounds.forText(valueLabel, this.valueLabelStyle)
                              .width -
                          labelToTextPadding
                        : barX - labelToBarPadding
 
                    // Using transforms for positioning to enable better (subpixel) transitions
                    // Width transitions don't work well on iOS Safari – they get interrupted and
                    // it appears very slow. Also be careful with negative bar charts.
                    const result = (
                        <g
                            key={series.seriesName}
                            className="bar"
                            transform={`translate(0, ${yOffset})`}
                        >
                            <text
                                x={0}
                                y={0}
                                transform={`translate(${labelX}, 0)`}
                                fill="#555"
                                dominantBaseline="middle"
                                textAnchor="end"
                                {...this.legendLabelStyle}
                            >
                                {series.seriesName}
                            </text>
                            <rect
                                x={0}
                                y={0}
                                transform={`translate(${barX}, ${
                                    -barHeight / 2
                                })`}
                                width={barWidth}
                                height={barHeight}
                                fill={barColor}
                                opacity={0.85}
                                style={{ transition: "height 200ms ease" }}
                            />
                            <text
                                x={0}
                                y={0}
                                transform={`translate(${
                                    yAxis.place(series.value) +
                                    (isNegative
                                        ? -labelToBarPadding
                                        : labelToBarPadding)
                                }, 0)`}
                                fill="#666"
                                dominantBaseline="middle"
                                textAnchor={isNegative ? "end" : "start"}
                                {...this.valueLabelStyle}
                            >
                                {valueLabel}
                            </text>
                        </g>
                    )
 
                    yOffset += barHeight + barSpacing
 
                    return result
                })}
            </g>
        )
    }
 
    @computed get failMessage(): string {
        const column = this.yColumns[0]
 
        if (!column) return "No column to chart"
 
        if (!this.selectionArray.hasSelection) return `No data selected`
 
        // TODO is it better to use .series for this check?
        return this.yColumns.every((col) => col.isEmpty)
            ? `No matching data in columns ${this.yColumnSlugs.join(", ")}`
            : ""
    }
 
    formatValue(series: DiscreteBarSeries): string {
        const column = this.yColumns[0] // todo: do we need to use the right column here?
        const { transformedTable } = this
 
        const showYearLabels =
            this.manager.showYearLabels || series.time !== this.targetTime
        const displayValue = column.formatValueShort(series.value)
        return (
            displayValue +
            (showYearLabels
                ? ` (${transformedTable.timeColumnFormatFunction(series.time)})`
                : "")
        )
    }
 
    @computed private 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 seriesStrategy(): SeriesStrategy {
        const autoStrategy = autoDetectSeriesStrategy(this.manager, true)
        // TODO this is an inconsistency between LineChart and DiscreteBar.
        // We should probably make it consistent at some point.
        if (
            autoStrategy === SeriesStrategy.column &&
            this.selectionArray.numSelectedEntities > 1
        ) {
            return SeriesStrategy.entity
        }
        return autoStrategy
    }
 
    @computed protected get yColumns(): CoreColumn[] {
        return this.transformedTable.getColumns(this.yColumnSlugs)
    }
 
    constructSeries(col: CoreColumn, indexes: number[]): DiscreteBarItem[] {
        const { transformedTable, colorColumn, hasColorScale } = this
        const values = col.valuesIncludingErrorValues
        const originalTimes = col.originalTimeColumn.valuesIncludingErrorValues
        const entityNames =
            transformedTable.entityNameColumn.valuesIncludingErrorValues
        const colorValues = colorColumn.valuesIncludingErrorValues
        return indexes.map((index): DiscreteBarItem => {
            const isColumnStrategy =
                this.seriesStrategy === SeriesStrategy.column
            const seriesName = isColumnStrategy
                ? col.displayName
                : (entityNames[index] as string)
            const colorValue = isNotErrorValue(colorValues[index])
                ? colorValues[index]
                : undefined
            const color = hasColorScale
                ? this.colorScale.getColor(colorValue)
                : isColumnStrategy
                ? col.def.color
                : transformedTable.getColorForEntityName(
                      entityNames[index] as string
                  )
            return {
                seriesName,
                value: values[index] as number,
                time: originalTimes[index] as number,
                colorValue,
                color,
            }
        })
    }
 
    @computed private get columnsAsSeries(): DiscreteBarItem[] {
        return flatten(
            this.yColumns.map((col) =>
                this.constructSeries(col, col.validRowIndices.slice(0, 1))
            )
        )
    }
 
    @computed private get entitiesAsSeries(): DiscreteBarItem[] {
        const col = this.yColumns[0]
        return this.constructSeries(col, col.validRowIndices)
    }
 
    @computed get sortConfig(): SortConfig {
        return this.manager.sortConfig ?? {}
    }
 
    @computed private get sortedRawSeries(): DiscreteBarItem[] {
        const raw =
            this.seriesStrategy === SeriesStrategy.entity
                ? this.entitiesAsSeries
                : this.columnsAsSeries
 
        let sortByFunc: (item: DiscreteBarItem) => number | string
        switch (this.sortConfig.sortBy) {
            case SortBy.entityName:
                sortByFunc = (item: DiscreteBarItem) => item.seriesName
                break
            default:
            case SortBy.total:
            case SortBy.column: // we only have one yColumn, so total and column are the same
                sortByFunc = (item: DiscreteBarItem) => item.value
                break
        }
        const sortedSeries = sortBy(raw, sortByFunc)
        const sortOrder = this.sortConfig.sortOrder ?? SortOrder.desc
        if (sortOrder === SortOrder.desc) sortedSeries.reverse()
        return sortedSeries
    }
 
    @computed private get colorScheme(): ColorScheme | undefined {
        // If this DiscreteBarChart stems from a LineChart, we want to match its (default) color
        // scheme OWID Distinct. Otherwise, use an all-blue color scheme (`undefined`) as default.
        const defaultColorScheme = this.manager.isLineChart
            ? ColorSchemes["owid-distinct"]
            : undefined
 
        return (
            (this.manager.baseColorScheme
                ? ColorSchemes[this.manager.baseColorScheme]
                : undefined) ?? defaultColorScheme
        )
    }
 
    @computed private get valuesToColorsMap(): Map<number, string> | undefined {
        const { manager, colorScheme, sortedRawSeries } = this
 
        return colorScheme?.getUniqValueColorMap(
            uniq(sortedRawSeries.map((series) => series.value)),
            !manager.invertColorScheme // negate here to be consistent with how things worked before
        )
    }
 
    // Only used if it's a LineChart turned into DiscreteBar due to single-point timeline
    @computed private get categoricalColorAssigner():
        | CategoricalColorAssigner
        | undefined {
        if (!this.colorScheme) return undefined
        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,
        })
    }
 
    @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)
 
    // End of color scale props
 
    // Color legend props
 
    @computed 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 = 10
    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
 
    @computed get series(): DiscreteBarSeries[] {
        const { manager } = this
 
        const series = this.sortedRawSeries.map((rawSeries) => {
            const { value, time, colorValue, seriesName, color } = rawSeries
            const series: DiscreteBarSeries = {
                value,
                time,
                colorValue,
                seriesName,
                color:
                    color ??
                    this.valuesToColorsMap?.get(value) ??
                    DEFAULT_BAR_COLOR,
            }
            return series
        })
 
        if (
            manager.isLineChart &&
            !this.hasColorScale &&
            this.categoricalColorAssigner
        ) {
            // For LineChart-based bar charts, we want to assign colors from the color scheme.
            // This way we get consistent between the DiscreteBarChart and the LineChart (by using the same logic).
            series.forEach((s) => {
                s.color = this.categoricalColorAssigner!.assign(s.seriesName)
            })
        }
        return series
    }
}