All files / owid-grapher/grapher/stackedCharts StackedBarChart.tsx

86.24% Statements 351/407
81.82% Branches 36/44
77.42% Functions 24/31
86.24% Lines 351/407

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 4971x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1190x 1190x 1190x 1190x 1190x 1190x 1190x 1190x 1190x 1190x 1190x 1190x 1190x 1190x 1190x 1190x 1190x 1190x 1190x 1190x       1190x 1190x       1190x 1190x 1190x 1190x 1190x 1190x 1190x 1190x 1190x 1190x 1190x 1190x 1190x 1190x 1190x 1190x 1190x 1190x 1190x 1190x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 1x 1x 4x 4x 1x 1x 4x 4x 4x 4x 1x 1x 4x 4x 4x 4x 4x 1x 1x     1x 1x 4x 4x 1x 1x 1x 4x 4x 4x 4x     4x 4x 4x 4x 4x 4x 4x 1x 1x 4x 4x 4x 4x 4x 4x               1x 1x 4x 4x 17x 17x 17x 17x 17x 4x 4x 1x 1x 4x 4x 1x 1x 4x 4x 1x 4x 4x 1x 4x 4x 4x 4x 4x 4x 4x 1x 1x 4x 4x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x                                                     4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 4x 4x 4x 4x 4x 4x 280x 280x 280x 4x 4x 1x 1x 1x 4x 4x 4x 4x 4x 280x 280x 280x 280x 280x 280x 280x 280x 280x 280x 280x 280x 280x 4x 1x 1x 4x 4x 4x 280x 19320x 19320x 19320x 19320x 1832x 19320x 236x 214x 236x 236x 19320x 280x 4x 4x 4x 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 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 44x 44x                                                                                                                                                                                    
import * as React from "react"
import { computed, action, observable } from "mobx"
import { observer } from "mobx-react"
import { uniq, makeSafeForCSS } from "../../clientUtils/Util"
import { Bounds } from "../../clientUtils/Bounds"
import {
    VerticalAxisComponent,
    AxisTickMarks,
    VerticalAxisGridLines,
} from "../axis/AxisViews"
import { NoDataModal } from "../noDataModal/NoDataModal"
import { Text } from "../text/Text"
import {
    VerticalColorLegend,
    VerticalColorLegendManager,
    LegendItem,
} from "../verticalColorLegend/VerticalColorLegend"
import { Tooltip } from "../tooltip/Tooltip"
import { BASE_FONT_SIZE } from "../core/GrapherConstants"
import { ColorScaleManager } from "../color/ColorScale"
import {
    AbstactStackedChart,
    AbstactStackedChartProps,
} from "./AbstractStackedChart"
import { StackedPoint, StackedSeries } from "./StackedConstants"
import { VerticalAxis } from "../axis/Axis"
import { ColorSchemeName } from "../color/ColorConstants"
import { stackSeries, withMissingValuesAsZeroes } from "./StackedUtils"
import { makeClipPath } from "../chart/ChartUtils"
import { Time } from "../../clientUtils/owidTypes"
import { ColorScaleConfigDefaults } from "../color/ColorScaleConfig"
 
interface StackedBarSegmentProps extends React.SVGAttributes<SVGGElement> {
    bar: StackedPoint<Time>
    series: StackedSeries<Time>
    color: string
    opacity: number
    yAxis: VerticalAxis
    xOffset: number
    barWidth: number
    onBarMouseOver: (
        bar: StackedPoint<Time>,
        series: StackedSeries<Time>
    ) => void
    onBarMouseLeave: () => void
}
 
@observer
class StackedBarSegment extends React.Component<StackedBarSegmentProps> {
    base: React.RefObject<SVGRectElement> = React.createRef()
 
    @observable mouseOver: boolean = false
 
    @computed get yPos(): number {
        const { bar, yAxis } = this.props
        return yAxis.place(bar.value + bar.valueOffset)
    }
 
    @computed get barHeight(): number {
        const { bar, yAxis } = this.props
        return yAxis.place(bar.valueOffset) - this.yPos
    }
 
    @computed get trueOpacity(): number {
        return this.mouseOver ? 1 : this.props.opacity
    }
 
    @action.bound onBarMouseOver(): void {
        this.mouseOver = true
        this.props.onBarMouseOver(this.props.bar, this.props.series)
    }
 
    @action.bound onBarMouseLeave(): void {
        this.mouseOver = false
        this.props.onBarMouseLeave()
    }
 
    render(): JSX.Element {
        const { color, xOffset, barWidth } = this.props
        const { yPos, barHeight, trueOpacity } = this
 
        return (
            <rect
                ref={this.base}
                x={xOffset}
                y={yPos}
                width={barWidth}
                height={barHeight}
                fill={color}
                opacity={trueOpacity}
                onMouseOver={this.onBarMouseOver}
                onMouseLeave={this.onBarMouseLeave}
            />
        )
    }
}
 
@observer
export class StackedBarChart
    extends AbstactStackedChart
    implements VerticalColorLegendManager, ColorScaleManager
{
    readonly minBarSpacing = 4
 
    constructor(props: AbstactStackedChartProps) {
        super(props)
    }
 
    // currently hovered legend color
    @observable hoverColor?: string
    // current hovered individual bar
    @observable hoverBar?: StackedPoint<Time>
    @observable hoverSeries?: StackedSeries<Time>
 
    @computed private get baseFontSize(): number {
        return this.manager.baseFontSize ?? BASE_FONT_SIZE
    }
 
    @computed get tickFontSize(): number {
        return 0.9 * this.baseFontSize
    }
 
    @computed get barWidth(): number {
        const { dualAxis } = this
 
        return (0.8 * dualAxis.innerBounds.width) / this.xValues.length
    }
 
    @computed get barSpacing(): number {
        return (
            this.dualAxis.innerBounds.width / this.xValues.length -
            this.barWidth
        )
    }
 
    @computed get barFontSize(): number {
        return 0.75 * this.baseFontSize
    }
 
    @computed protected get paddingForLegend(): number {
        return this.sidebarWidth + 20
    }
 
    // All currently hovered group keys, combining the legend and the main UI
    @computed get hoverKeys(): string[] {
        const { hoverColor } = this
 
        const hoverKeys =
            hoverColor === undefined
                ? []
                : uniq(
                      this.series
                          .filter((g) => g.color === hoverColor)
                          .map((g) => g.seriesName)
                  )
 
        return hoverKeys
    }
 
    @computed get activeColors(): string[] {
        const { hoverKeys } = this
        const activeKeys = hoverKeys.length > 0 ? hoverKeys : []
 
        if (!activeKeys.length)
            // No hover means they're all active by default
            return uniq(this.series.map((g) => g.color))

        return uniq(
            this.series
                .filter((g) => activeKeys.indexOf(g.seriesName) !== -1)
                .map((g) => g.color)
        )
    }
 
    @computed get legendItems(): LegendItem[] {
        return this.series
            .map((series) => {
                return {
                    label: series.seriesName,
                    color: series.color,
                }
            })
            .reverse() // Vertical legend orders things in the opposite direction we want
    }
 
    @computed get maxLegendWidth(): number {
        return this.sidebarMaxWidth
    }
 
    @computed get sidebarMaxWidth(): number {
        return this.bounds.width / 5
    }
    @computed get sidebarMinWidth(): number {
        return 100
    }
    @computed get sidebarWidth(): number {
        if (this.manager.hideLegend) return 0
        const { sidebarMinWidth, sidebarMaxWidth, legendDimensions } = this
        return Math.max(
            Math.min(legendDimensions.width, sidebarMaxWidth),
            sidebarMinWidth
        )
    }
 
    @computed private get legendDimensions(): VerticalColorLegend {
        return new VerticalColorLegend({ manager: this })
    }
 
    @computed get tooltip(): JSX.Element | undefined {
        const {
            hoverBar,
            mapXValueToOffset,
            barWidth,
            dualAxis,
            yColumns,
            inputTable,
            hoverSeries,
        } = this
        if (hoverBar === undefined) return

        const xPos = mapXValueToOffset.get(hoverBar.position)
        if (xPos === undefined) return

        const yPos = dualAxis.verticalAxis.place(
            hoverBar.valueOffset + hoverBar.value
        )

        const yColumn = yColumns[0] // we can just use the first column for formatting, b/c we assume all columns have same type
        return (
            <Tooltip
                tooltipManager={this.props.manager}
                x={xPos + barWidth}
                y={yPos}
                style={{ textAlign: "center" }}
            >
                <h3
                    style={{
                        padding: "0.3em 0.9em",
                        margin: 0,
                        backgroundColor: "#fcfcfc",
                        borderBottom: "1px solid #ebebeb",
                        fontWeight: "normal",
                        fontSize: "1em",
                    }}
                >
                    {hoverSeries?.seriesName}
                </h3>
                <p
                    style={{
                        margin: 0,
                        padding: "0.3em 0.9em",
                        fontSize: "0.8em",
                    }}
                >
                    <span>{yColumn.formatValueLong(hoverBar.value)}</span>
                    <br />
                    in
                    <br />
                    <span>
                        {inputTable.timeColumnFormatFunction(hoverBar.position)}
                    </span>
                </p>
            </Tooltip>
        )
    }
 
    @computed get mapXValueToOffset(): Map<number, number> {
        const { dualAxis, barWidth, barSpacing } = this
 
        const xValueToOffset = new Map<number, number>()
        let xOffset = dualAxis.innerBounds.left + barSpacing
 
        for (let i = 0; i < this.xValues.length; i++) {
            xValueToOffset.set(this.xValues[i], xOffset)
            xOffset += barWidth + barSpacing
        }
        return xValueToOffset
    }
 
    // Place ticks centered beneath the bars, before doing overlap detection
    @computed private get tickPlacements() {
        const { mapXValueToOffset, barWidth, dualAxis } = this
        const { xValues } = this
        const { horizontalAxis } = dualAxis
 
        return xValues.map((x) => {
            const text = horizontalAxis.formatTick(x)
            const xPos = mapXValueToOffset.get(x) as number
 
            const bounds = Bounds.forText(text, { fontSize: this.tickFontSize })
            return {
                text,
                bounds: bounds.set({
                    x: xPos + barWidth / 2 - bounds.width / 2,
                    y: dualAxis.innerBounds.bottom + 5,
                }),
                isHidden: false,
            }
        })
    }
 
    @computed get ticks() {
        const { tickPlacements } = this
 
        for (let i = 0; i < tickPlacements.length; i++) {
            for (let j = 1; j < tickPlacements.length; j++) {
                const t1 = tickPlacements[i],
                    t2 = tickPlacements[j]
 
                if (t1 === t2 || t1.isHidden || t2.isHidden) continue
 
                if (t1.bounds.intersects(t2.bounds.padWidth(-5))) {
                    if (i === 0) t2.isHidden = true
                    else if (j === tickPlacements.length - 1) t1.isHidden = true
                    else t2.isHidden = true
                }
            }
        }
 
        return tickPlacements.filter((t) => !t.isHidden)
    }
 
    @action.bound onLegendMouseOver(color: string): void {
        this.hoverColor = color
    }
 
    @action.bound onLegendMouseLeave(): void {
        this.hoverColor = undefined
    }
 
    @action.bound onLegendClick(): void {}
 
    @action.bound onBarMouseOver(
        bar: StackedPoint<Time>,
        series: StackedSeries<Time>
    ): void {
        this.hoverBar = bar
        this.hoverSeries = series
    }
 
    @action.bound onBarMouseLeave(): void {
        this.hoverBar = undefined
    }
 
    render(): JSX.Element {
        if (this.failMessage)
            return (
                <NoDataModal
                    manager={this.manager}
                    bounds={this.bounds}
                    message={this.failMessage}
                />
            )
 
        const {
            dualAxis,
            renderUid,
            bounds,
            tooltip,
            barWidth,
            mapXValueToOffset,
            ticks,
        } = this
        const { series } = this
        const { innerBounds, verticalAxis } = dualAxis
 
        const textColor = "#666"
 
        const clipPath = makeClipPath(renderUid, innerBounds)
 
        return (
            <g
                className="StackedBarChart"
                width={bounds.width}
                height={bounds.height}
            >
                {clipPath.element}
 
                <rect
                    x={bounds.left}
                    y={bounds.top}
                    width={bounds.width}
                    height={bounds.height}
                    opacity={0}
                    fill="rgba(255,255,255,0)"
                />
                <VerticalAxisComponent
                    bounds={bounds}
                    verticalAxis={verticalAxis}
                />
                <VerticalAxisGridLines
                    verticalAxis={verticalAxis}
                    bounds={innerBounds}
                />
 
                <AxisTickMarks
                    tickMarkTopPosition={innerBounds.bottom}
                    tickMarkXPositions={ticks.map(
                        (tick) => tick.bounds.centerX
                    )}
                    color={textColor}
                />
 
                <g>
                    {ticks.map((tick, i) => {
                        return (
                            <Text
                                key={i}
                                x={tick.bounds.x}
                                y={tick.bounds.y}
                                fill={textColor}
                                fontSize={this.tickFontSize}
                            >
                                {tick.text}
                            </Text>
                        )
                    })}
                </g>
 
                <g clipPath={clipPath.id}>
                    {series.map((series, index) => {
                        const isLegendHovered = this.hoverKeys.includes(
                            series.seriesName
                        )
                        const opacity =
                            isLegendHovered || this.hoverKeys.length === 0
                                ? 0.8
                                : 0.2
 
                        return (
                            <g
                                key={index}
                                className={
                                    makeSafeForCSS(series.seriesName) +
                                    "-segments"
                                }
                            >
                                {series.points.map((bar, index) => {
                                    const xPos = mapXValueToOffset.get(
                                        bar.position
                                    ) as number
                                    const barOpacity =
                                        bar === this.hoverBar ? 1 : opacity
 
                                    return (
                                        <StackedBarSegment
                                            key={index}
                                            bar={bar}
                                            color={series.color}
                                            xOffset={xPos}
                                            opacity={barOpacity}
                                            yAxis={verticalAxis}
                                            series={series}
                                            onBarMouseOver={this.onBarMouseOver}
                                            onBarMouseLeave={
                                                this.onBarMouseLeave
                                            }
                                            barWidth={barWidth}
                                        />
                                    )
                                })}
                            </g>
                        )
                    })}
                </g>
 
                {!this.manager.hideLegend && (
                    <VerticalColorLegend manager={this} />
                )}
                {tooltip}
            </g>
        )
    }
 
    @computed get legendY(): number {
        return this.bounds.top
    }
 
    @computed get legendX(): number {
        return this.bounds.right - this.sidebarWidth
    }
 
    @computed private get xValues(): number[] {
        return uniq(this.allStackedPoints.map((bar) => bar.position))
    }
 
    @computed get colorScaleConfig(): ColorScaleConfigDefaults | undefined {
        return this.manager.colorScale
    }
 
    defaultBaseColorScheme = ColorSchemeName.stackedAreaDefault
 
    @computed get series(): readonly StackedSeries<number>[] {
        return stackSeries(withMissingValuesAsZeroes(this.unstackedSeries))
    }
}