All files / owid-grapher/grapher/horizontalColorLegend HorizontalColorLegends.tsx

86.54% Statements 611/706
68.93% Branches 71/103
89.8% Functions 44/49
86.54% Lines 611/706

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 8201x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 4x 4x 1x 1x     1x 1x     1x 1x 8x 8x 8x 1x 1x 8x 8x 1x 1x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 1x 1x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 1x 1x 4x 4x 4x 4x 4x 1x 1x 1x 1x 3x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x   2x 2x 2x 2x 4x 4x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x         1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 2x   2x 2x 2x 2x 2x 2x 2x 1x 1x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 2x 2x 2x 2x 2x 2x 3x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x     3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 2x 2x 2x       2x 1x 1x                     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x                                                             1x 1x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 23x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 22x 22x 22x   22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 4x 4x 22x 22x 22x 4x 4x 22x 22x 22x 22x 4x 4x 4x 23x 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 22x 22x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 22x                       20x 20x 20x 22x 1x 1x 1x 1x 8x 8x 1x 1x 8x 8x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 10x 10x 10x 10x 10x           10x 10x 10x 10x 10x 10x 10x 10x                                                                                                                                                                                                                                    
import * as React from "react"
import { action, computed } from "mobx"
import { observer } from "mobx-react"
import {
    getRelativeMouse,
    sortBy,
    min,
    max,
    last,
    flatten,
    sum,
    dyFromAlign,
    removeAllWhitespace,
} from "../../clientUtils/Util"
import { Bounds } from "../../clientUtils/Bounds"
import {
    ColorScaleBin,
    NumericBin,
    CategoricalBin,
} from "../color/ColorScaleBin"
import { BASE_FONT_SIZE } from "../core/GrapherConstants"
import {
    Color,
    HorizontalAlign,
    VerticalAlign,
} from "../../clientUtils/owidTypes"
import { TextWrap } from "../text/TextWrap"
import { darkenColorForLine } from "../color/ColorUtils"
 
export interface PositionedBin {
    x: number
    width: number
    bin: ColorScaleBin
}
 
interface NumericLabel {
    text: string
    fontSize: number
    bounds: Bounds
    priority?: boolean
    hidden: boolean
    raised: boolean
}
 
interface CategoricalMark {
    x: number
    y: number
    rectSize: number
    label: {
        text: string
        bounds: Bounds
        fontSize: number
    }
    bin: CategoricalBin
}
 
interface MarkLine {
    totalWidth: number
    marks: CategoricalMark[]
}
 
// TODO unify properties across categorical & numeric legend.
// This would make multiple legends per chart less convenient (only used in Map), but we shouldn't
// be using multiple anyway – instead the numeric should also handle categorical bins too.
export interface HorizontalColorLegendManager {
    fontSize?: number
    legendX?: number
    legendAlign?: HorizontalAlign
    legendTitle?: string
    categoryLegendY?: number
    numericLegendY?: number
    legendWidth?: number
    legendMaxWidth?: number
    legendHeight?: number
    legendOpacity?: number
    legendTextColor?: Color
    legendTickSize?: number
    categoricalLegendData?: CategoricalBin[]
    categoricalFocusBracket?: CategoricalBin
    categoricalBinStroke?: Color
    numericLegendData?: ColorScaleBin[]
    numericFocusBracket?: ColorScaleBin
    numericBinSize?: number
    numericBinStroke?: Color
    numericBinStrokeWidth?: number
    equalSizeBins?: boolean
    onLegendMouseLeave?: () => void
    onLegendMouseOver?: (d: ColorScaleBin) => void
}
 
const DEFAULT_NUMERIC_BIN_SIZE = 10
const DEFAULT_NUMERIC_BIN_STROKE = "#333"
const DEFAULT_NUMERIC_BIN_STROKE_WIDTH = 0.3
const DEFAULT_TEXT_COLOR = "#111"
const DEFAULT_TICK_SIZE = 3
 
const CATEGORICAL_BIN_MIN_WIDTH = 20
const FOCUS_BORDER_COLOR = "#111"
const SPACE_BETWEEN_CATEGORICAL_BINS = 7
const MINIMUM_LABEL_DISTANCE = 5
 
export abstract class HorizontalColorLegend extends React.Component<{
    manager: HorizontalColorLegendManager
}> {
    @computed protected get manager(): HorizontalColorLegendManager {
        return this.props.manager
    }
 
    @computed protected get legendX(): number {
        return this.manager.legendX ?? 0
    }
 
    @computed protected get categoryLegendY(): number {
        return this.manager.categoryLegendY ?? 0
    }
 
    @computed protected get numericLegendY(): number {
        return this.manager.numericLegendY ?? 0
    }
 
    @computed protected get legendMaxWidth(): number | undefined {
        return this.manager.legendMaxWidth
    }
 
    @computed protected get legendHeight(): number {
        return this.manager.legendHeight ?? 200
    }
 
    @computed protected get legendAlign(): HorizontalAlign {
        // Assume center alignment if none specified, for backwards-compatibility
        return this.manager.legendAlign ?? HorizontalAlign.center
    }
 
    @computed protected get fontSize(): number {
        return this.manager.fontSize ?? BASE_FONT_SIZE
    }
 
    @computed protected get legendTextColor(): Color {
        return this.manager.legendTextColor ?? DEFAULT_TEXT_COLOR
    }
 
    @computed protected get legendTickSize(): number {
        return this.manager.legendTickSize ?? DEFAULT_TICK_SIZE
    }
 
    abstract get height(): number
    abstract get width(): number
}
 
@observer
export class HorizontalNumericColorLegend extends HorizontalColorLegend {
    base: React.RefObject<SVGGElement> = React.createRef()
 
    @computed private get numericLegendData(): ColorScaleBin[] {
        return this.manager.numericLegendData ?? []
    }
 
    @computed private get visibleBins(): ColorScaleBin[] {
        return this.numericLegendData.filter((bin) => !bin.isHidden)
    }
 
    @computed private get numericBins(): NumericBin[] {
        return this.visibleBins.filter(
            (bin): bin is NumericBin => bin instanceof NumericBin
        )
    }
 
    @computed private get numericBinSize(): number {
        return this.props.manager.numericBinSize ?? DEFAULT_NUMERIC_BIN_SIZE
    }
 
    @computed private get numericBinStroke(): Color {
        return this.props.manager.numericBinStroke ?? DEFAULT_NUMERIC_BIN_STROKE
    }
 
    @computed private get numericBinStrokeWidth(): number {
        return (
            this.props.manager.numericBinStrokeWidth ??
            DEFAULT_NUMERIC_BIN_STROKE_WIDTH
        )
    }
 
    @computed private get tickFontSize(): number {
        return 0.75 * this.fontSize
    }
 
    @computed private get itemMargin(): number {
        return Math.round(this.fontSize * 1.125)
    }
 
    // NumericColorLegend wants to map a range to a width. However, sometimes we are given
    // data without a clear min/max. So we must fit these scurrilous bins into the width somehow.
    @computed private get minValue(): number {
        return min(this.numericBins.map((bin) => bin.min)) as number
    }
    @computed private get maxValue(): number {
        return max(this.numericBins.map((bin) => bin.max)) as number
    }
    @computed private get rangeSize(): number {
        return this.maxValue - this.minValue
    }
 
    @computed private get maxWidth(): number {
        return this.manager.legendMaxWidth ?? this.manager.legendWidth ?? 200
    }
 
    private getTickLabelWidth(label: string): number {
        return Bounds.forText(label, {
            fontSize: this.tickFontSize,
        }).width
    }
 
    private getCategoricalBinWidth(bin: ColorScaleBin): number {
        return Math.max(
            this.getTickLabelWidth(bin.text),
            CATEGORICAL_BIN_MIN_WIDTH
        )
    }
 
    @computed private get totalCategoricalWidth(): number {
        const { visibleBins, itemMargin } = this
        const widths = visibleBins.map((bin) =>
            bin instanceof CategoricalBin && !bin.isHidden
                ? this.getCategoricalBinWidth(bin) + itemMargin
                : 0
        )
        return sum(widths)
    }
 
    @computed private get isAutoWidth(): boolean {
        return (
            this.manager.legendWidth === undefined &&
            this.manager.legendMaxWidth !== undefined
        )
    }
 
    private getNumericLabelMinWidth(bin: NumericBin): number {
        if (bin.text) {
            return this.getTickLabelWidth(bin.text)
        } else {
            const combinedLabelWidths = sum(
                [bin.minText, bin.maxText].map(
                    (text) =>
                        // because labels are center-aligned, only half the label space is required
                        this.getTickLabelWidth(text) / 2
                )
            )
            return combinedLabelWidths + MINIMUM_LABEL_DISTANCE * 2
        }
    }
 
    // Overstretched legends don't look good.
    // If the manager provides `legendMaxWidth`, then we calculate an _ideal_ width for the legend.
    @computed private get idealNumericWidth(): number {
        const binCount = this.numericBins.length
        const spaceRequirements = this.numericBins.map((bin) => ({
            labelSpace: this.getNumericLabelMinWidth(bin),
            shareOfTotal: (bin.max - bin.min) / this.rangeSize,
        }))
        // Make sure the legend is big enough to avoid overlapping labels (including `raisedMode`)
        if (this.manager.equalSizeBins) {
            const minBinWidth = this.fontSize * 3.5
            const maxBinWidth =
                max(
                    spaceRequirements.map(({ labelSpace }) =>
                        Math.max(labelSpace, minBinWidth)
                    )
                ) ?? 0
            return Math.round(maxBinWidth * binCount)
        } else {
            const minBinWidth = this.fontSize * 2
            const maxTotalWidth =
                max(
                    spaceRequirements.map(({ labelSpace, shareOfTotal }) =>
                        Math.max(labelSpace / shareOfTotal, minBinWidth)
                    )
                ) ?? 0
            return Math.round(maxTotalWidth)
        }
    }
 
    @computed get width(): number {
        if (this.isAutoWidth) {
            return Math.min(
                this.maxWidth,
                this.legendTitleWidth +
                    this.totalCategoricalWidth +
                    this.idealNumericWidth
            )
        } else {
            return this.maxWidth
        }
    }
 
    @computed private get availableNumericWidth(): number {
        return this.width - this.totalCategoricalWidth - this.legendTitleWidth
    }
 
    // Since we calculate the width automatically in some cases (when `isAutoWidth` is true),
    // we need to shift X to align the legend horizontally (`legendAlign`).
    @computed private get x(): number {
        const { width, maxWidth, legendAlign, legendX } = this
        const widthDiff = maxWidth - width
        if (legendAlign === HorizontalAlign.center) {
            return legendX + widthDiff / 2
        } else if (legendAlign === HorizontalAlign.right) {
            return legendX + widthDiff
        } else {
            return legendX // left align
        }
    }
 
    @computed private get positionedBins(): PositionedBin[] {
        const {
            manager,
            rangeSize,
            availableNumericWidth,
            visibleBins,
            numericBins,
            legendTitleWidth,
            x,
        } = this
 
        let xOffset = x + legendTitleWidth
        let prevBin: ColorScaleBin | undefined
 
        return visibleBins.map((bin, index) => {
            const isFirst = index === 0
            let width: number = this.getCategoricalBinWidth(bin)
            let marginLeft: number = isFirst ? 0 : this.itemMargin
 
            if (bin instanceof NumericBin) {
                if (manager.equalSizeBins) {
                    width = availableNumericWidth / numericBins.length
                } else {
                    width =
                        ((bin.max - bin.min) / rangeSize) *
                        availableNumericWidth
                }
                // Don't add any margin between numeric bins
                if (prevBin instanceof NumericBin) {
                    marginLeft = 0
                }
            }
 
            const x = xOffset + marginLeft
            xOffset = x + width
            prevBin = bin
 
            return {
                x,
                width,
                bin,
            }
        })
    }
 
    @computed private get legendTitleFontSize(): number {
        return this.fontSize * 0.85
    }
 
    @computed private get legendTitle(): TextWrap | undefined {
        const { legendTitle } = this.manager
        return legendTitle
            ? new TextWrap({
                  text: legendTitle,
                  fontSize: this.legendTitleFontSize,
                  fontWeight: 700,
                  maxWidth: this.maxWidth / 3,
              })
            : undefined
    }
 
    @computed private get legendTitleWidth(): number {
        return this.legendTitle ? this.legendTitle.width + this.itemMargin : 0
    }
 
    @computed private get numericLabels(): NumericLabel[] {
        const { numericBinSize, positionedBins, tickFontSize } = this
 
        const makeBoundaryLabel = (
            bin: PositionedBin,
            minOrMax: "min" | "max",
            text: string
        ): NumericLabel => {
            const labelBounds = Bounds.forText(text, { fontSize: tickFontSize })
            const x =
                bin.x +
                (minOrMax === "min" ? 0 : bin.width) -
                labelBounds.width / 2
            const y = -numericBinSize - labelBounds.height - this.legendTickSize
 
            return {
                text: text,
                fontSize: tickFontSize,
                bounds: labelBounds.set({ x: x, y: y }),
                hidden: false,
                raised: false,
            }
        }
 
        const makeRangeLabel = (bin: PositionedBin): NumericLabel => {
            const labelBounds = Bounds.forText(bin.bin.text, {
                fontSize: tickFontSize,
            })
            const x = bin.x + bin.width / 2 - labelBounds.width / 2
            const y = -numericBinSize - labelBounds.height - this.legendTickSize
 
            return {
                text: bin.bin.text,
                fontSize: tickFontSize,
                bounds: labelBounds.set({ x: x, y: y }),
                priority: true,
                hidden: false,
                raised: false,
            }
        }
 
        let labels: NumericLabel[] = []
        for (const bin of positionedBins) {
            if (bin.bin.text) labels.push(makeRangeLabel(bin))
            else if (bin.bin instanceof NumericBin) {
                if (bin.bin.minText)
                    labels.push(makeBoundaryLabel(bin, "min", bin.bin.minText))
                if (bin === last(positionedBins) && bin.bin.maxText)
                    labels.push(makeBoundaryLabel(bin, "max", bin.bin.maxText))
            }
        }
 
        for (let index = 0; index < labels.length; index++) {
            const l1 = labels[index]
            if (l1.hidden) continue
 
            for (let j = index + 1; j < labels.length; j++) {
                const l2 = labels[j]
                if (
                    l1.bounds.right + MINIMUM_LABEL_DISTANCE >=
                        l2.bounds.centerX ||
                    (l2.bounds.left - MINIMUM_LABEL_DISTANCE <=
                        l1.bounds.centerX &&
                        !l2.priority)
                )
                    l2.hidden = true
            }
        }
 
        labels = labels.filter((label) => !label.hidden)
 
        // If labels overlap, first we try alternating raised labels
        let raisedMode = false
        for (let index = 1; index < labels.length; index++) {
            const l1 = labels[index - 1],
                l2 = labels[index]
            if (l1.bounds.right + MINIMUM_LABEL_DISTANCE >= l2.bounds.left) {
                raisedMode = true
                break
            }
        }
 
        if (raisedMode) {
            for (let index = 1; index < labels.length; index++) {
                const label = labels[index]
                if (index % 2 !== 0) {
                    label.bounds = label.bounds.set({
                        y: label.bounds.y - label.bounds.height - 1,
                    })
                    label.raised = true
                }
            }
        }
 
        return labels
    }
 
    @computed get height(): number {
        return Math.abs(
            min(this.numericLabels.map((label) => label.bounds.y)) ?? 0
        )
    }
 
    @computed private get bounds(): Bounds {
        return new Bounds(this.x, this.numericLegendY, this.width, this.height)
    }
 
    @action.bound private onMouseMove(ev: MouseEvent | TouchEvent): void {
        const { manager, base, positionedBins } = this
        const { numericFocusBracket } = manager
        if (base.current) {
            const mouse = getRelativeMouse(base.current, ev)

            // We implement onMouseMove and onMouseLeave in a custom way, without attaching them to
            // specific SVG elements, in order to allow continuous transition between bins as the user
            // moves their cursor across (even if their cursor is in the empty area above the
            // legend, where the labels are).
            // We could achieve the same by rendering invisible rectangles over the areas and attaching
            // event handlers to those.

            // If outside legend bounds, trigger onMouseLeave if there is an existing bin in focus.
            if (!this.bounds.contains(mouse)) {
                if (numericFocusBracket && manager.onLegendMouseLeave)
                    return manager.onLegendMouseLeave()
                return
            }

            // If inside legend bounds, trigger onMouseOver with the bin closest to the cursor.
            let newFocusBracket: ColorScaleBin | undefined
            positionedBins.forEach((bin) => {
                if (mouse.x >= bin.x && mouse.x <= bin.x + bin.width)
                    newFocusBracket = bin.bin
            })

            if (newFocusBracket && manager.onLegendMouseOver)
                manager.onLegendMouseOver(newFocusBracket)
        }
    }
 
    componentDidMount(): void {
        document.documentElement.addEventListener("mousemove", this.onMouseMove)
        document.documentElement.addEventListener("touchmove", this.onMouseMove)
    }
 
    componentWillUnmount(): void {
        document.documentElement.removeEventListener(
            "mousemove",
            this.onMouseMove
        )
        document.documentElement.removeEventListener(
            "touchmove",
            this.onMouseMove
        )
    }
 
    render(): JSX.Element {
        const {
            manager,
            numericLabels,
            numericBinSize,
            positionedBins,
            height,
        } = this
        const { numericFocusBracket } = manager
 
        const stroke = this.numericBinStroke
        const strokeWidth = this.numericBinStrokeWidth
        const bottomY = this.numericLegendY + height
 
        return (
            <g ref={this.base} className="numericColorLegend">
                {numericLabels.map((label, index) => (
                    <line
                        key={index}
                        x1={label.bounds.x + label.bounds.width / 2}
                        y1={bottomY - numericBinSize}
                        x2={label.bounds.x + label.bounds.width / 2}
                        y2={bottomY + label.bounds.y + label.bounds.height}
                        // if we use a light color for stroke (e.g. white), we want it to stay
                        // "invisible", except for raised labels, where we want *some* contrast.
                        stroke={
                            label.raised ? darkenColorForLine(stroke) : stroke
                        }
                        strokeWidth={strokeWidth}
                    />
                ))}
                {sortBy(
                    positionedBins.map((positionedBin, index) => {
                        const bin = positionedBin.bin
                        const isFocus =
                            numericFocusBracket &&
                            bin.equals(numericFocusBracket)
                        return (
                            <NumericBinRect
                                key={index}
                                x={positionedBin.x}
                                y={bottomY - numericBinSize}
                                width={positionedBin.width}
                                height={numericBinSize}
                                fill={bin.color}
                                opacity={manager.legendOpacity} // defaults to undefined which removes the prop
                                stroke={isFocus ? FOCUS_BORDER_COLOR : stroke}
                                strokeWidth={isFocus ? 2 : strokeWidth}
                                isOpenLeft={
                                    bin instanceof NumericBin
                                        ? bin.props.isOpenLeft
                                        : false
                                }
                                isOpenRight={
                                    bin instanceof NumericBin
                                        ? bin.props.isOpenRight
                                        : false
                                }
                            />
                        )
                    }),
                    (rect) => rect.props["strokeWidth"]
                )}
                {numericLabels.map((label, index) => (
                    <text
                        key={index}
                        x={label.bounds.x}
                        y={bottomY + label.bounds.y}
                        // we can't use dominant-baseline to do proper alignment since our svg-to-png library Sharp
                        // doesn't support that (https://github.com/lovell/sharp/issues/1996), so we'll have to make
                        // do with some rough positioning.
                        dy={dyFromAlign(VerticalAlign.bottom)}
                        fontSize={label.fontSize}
                        fill={this.legendTextColor}
                    >
                        {label.text}
                    </text>
                ))}
                {this.legendTitle?.render(
                    this.x,
                    // Align legend title baseline with bottom of color bins
                    this.numericLegendY +
                        height -
                        this.legendTitle.height +
                        this.legendTitleFontSize * 0.2,
                    { fill: this.legendTextColor }
                )}
            </g>
        )
    }
}
 
interface NumericBinRectProps extends React.SVGProps<SVGRectElement> {
    x: number
    y: number
    width: number
    height: number
    isOpenLeft?: boolean
    isOpenRight?: boolean
}
 
/** The width of the arrowhead for open-ended bins (left or right) */
const ARROW_SIZE = 5
 
const NumericBinRect = (props: NumericBinRectProps) => {
    const { isOpenLeft, isOpenRight, x, y, width, height, ...restProps } = props
    if (isOpenRight) {
        const a = ARROW_SIZE
        const w = width - a
        const d = removeAllWhitespace(`
            M ${x}, ${y}
            l ${w}, 0
            l ${a}, ${height / 2}
            l ${-a}, ${height / 2}
            l ${-w}, 0
            z
        `)
        return <path d={d} {...restProps} />
    } else if (isOpenLeft) {
        const a = ARROW_SIZE
        const w = width - a
        const d = removeAllWhitespace(`
            M ${x + a}, ${y}
            l ${w}, 0
            l 0, ${height}
            l ${-w}, 0
            l ${-a}, ${-height / 2}
            z
        `)
        return <path d={d} {...restProps} />
    } else {
        return <rect x={x} y={y} width={width} height={height} {...restProps} />
    }
}
 
@observer
export class HorizontalCategoricalColorLegend extends HorizontalColorLegend {
    @computed get width(): number {
        return this.manager.legendWidth ?? this.manager.legendMaxWidth ?? 200
    }
 
    @computed private get categoricalLegendData(): CategoricalBin[] {
        return this.manager.categoricalLegendData ?? []
    }
 
    @computed private get markLines(): MarkLine[] {
        const fontSize = this.fontSize * 0.8
        const rectSize = this.fontSize * 0.75
        const rectPadding = 5
        const markPadding = 5
 
        const lines: MarkLine[] = []
        let marks: CategoricalMark[] = []
        let xOffset = 0
        let yOffset = 0
        this.categoricalLegendData.forEach((bin) => {
            const labelBounds = Bounds.forText(bin.text, { fontSize })
            const markWidth =
                rectSize + rectPadding + labelBounds.width + markPadding
 
            if (xOffset + markWidth > this.width && marks.length > 0) {
                lines.push({ totalWidth: xOffset - markPadding, marks: marks })
                marks = []
                xOffset = 0
                yOffset += rectSize + rectPadding
            }
 
            const markX = xOffset
            const markY = yOffset
 
            const label = {
                text: bin.text,
                bounds: labelBounds.set({
                    x: markX + rectSize + rectPadding,
                    y: markY + rectSize / 2,
                }),
                fontSize,
            }
 
            marks.push({
                x: markX,
                y: markY,
                rectSize,
                label,
                bin,
            })
 
            xOffset += markWidth + SPACE_BETWEEN_CATEGORICAL_BINS
        })
 
        if (marks.length > 0)
            lines.push({ totalWidth: xOffset - markPadding, marks: marks })
 
        return lines
    }
 
    @computed private get contentWidth(): number {
        return max(this.markLines.map((l) => l.totalWidth)) as number
    }
 
    @computed private get containerWidth(): number {
        return this.width ?? this.contentWidth
    }
 
    @computed private get marks(): CategoricalMark[] {
        const lines = this.markLines
        const align = this.legendAlign
        const width = this.containerWidth
 
        // Center each line
        lines.forEach((line) => {
            // TODO abstract this
            const xShift =
                align === HorizontalAlign.center
                    ? (width - line.totalWidth) / 2
                    : align === HorizontalAlign.right
                    ? width - line.totalWidth
                    : 0
            line.marks.forEach((mark) => {
                mark.x += xShift
                mark.label.bounds = mark.label.bounds.set({
                    x: mark.label.bounds.x + xShift,
                })
            })
        })
 
        return flatten(lines.map((l) => l.marks))
    }
 
    @computed get height(): number {
        return max(this.marks.map((mark) => mark.y + mark.rectSize)) ?? 0
    }
 
    render(): JSX.Element {
        const { manager, marks } = this
 
        return (
            <g>
                <g className="categoricalColorLegend">
                    {marks.map((mark, index) => {
                        return (
                            <g
                                key={index}
                                onMouseOver={(): void =>
                                    manager.onLegendMouseOver
                                        ? manager.onLegendMouseOver(mark.bin)
                                        : undefined
                                }
                                onMouseLeave={(): void =>
                                    manager.onLegendMouseLeave
                                        ? manager.onLegendMouseLeave()
                                        : undefined
                                }
                            >
                                <rect
                                    x={this.legendX + mark.x}
                                    y={this.categoryLegendY + mark.y}
                                    width={mark.rectSize}
                                    height={mark.rectSize}
                                    fill={mark.bin.color}
                                    stroke={manager.categoricalBinStroke}
                                    strokeWidth={0.4}
                                    opacity={manager.legendOpacity} // defaults to undefined which removes the prop
                                />
                                ,
                                <text
                                    x={this.legendX + mark.label.bounds.x}
                                    y={
                                        this.categoryLegendY +
                                        mark.label.bounds.y
                                    }
                                    // we can't use dominant-baseline to do proper alignment since our svg-to-png library Sharp
                                    // doesn't support that (https://github.com/lovell/sharp/issues/1996), so we'll have to make
                                    // do with some rough positioning.
                                    dy={dyFromAlign(VerticalAlign.middle)}
                                    fontSize={mark.label.fontSize}
                                >
                                    {mark.label.text}
                                </text>
                            </g>
                        )
                    })}
                </g>
            </g>
        )
    }
}