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

94.02% Statements 330/351
81.97% Branches 50/61
85.71% Functions 30/35
94.02% Lines 330/351

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 3461x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 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 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x                 3x 3x 3x 3x 14x 14x 3x 3x 14x 14x 14x 14x 14x 3x 3x 3x 3x 3x 2x 2x 3x 3x 2x 2x 3x 3x     3x 3x 16x 16x 3x 3x 14x 14x 3x 3x 3x 3x   3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 3x 3x     3x 3x 14x 14x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 3x 2x 2x 3x 3x     3x 3x 2x 2x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 3x 2x 2x 2x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 3x 3x 5x 5x 10x 10x 10x 10x 10x 10x 5x 5x 3x 3x 3x 9x 9x 9x 12x 12x 12x 12x 12x 12x 9x 9x 3x 3x 3x 14x 5x 5x 14x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 3x 3x 8x 8x     8x 2x 2x 8x 8x 8x 8x 3x 3x 18x 18x 6x 18x 18x 18x 3x 3x 3x 3x 3x 3x 14x 14x 3x 3x     3x 3x 3x 17x 17x 3x 3x 14x 14x 14x 22x 14x 14x 14x 14x 18x 18x 18x 18x 18x 836x 836x 836x 836x 836x 836x 836x 18x 18x 18x 14x 3x 3x     3x 3x 2x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 1x
import { DualAxis, HorizontalAxis, VerticalAxis } from "../axis/Axis"
import { AxisConfig, FontSizeManager } from "../axis/AxisConfig"
import { ChartInterface } from "../chart/ChartInterface"
import { ChartManager } from "../chart/ChartManager"
import {
    BASE_FONT_SIZE,
    SeriesName,
    SeriesStrategy,
} from "../core/GrapherConstants"
import { Bounds, DEFAULT_BOUNDS } from "../../clientUtils/Bounds"
import {
    exposeInstanceOnWindow,
    flatten,
    guid,
    max,
} from "../../clientUtils/Util"
import { computed } from "mobx"
import { observer } from "mobx-react"
import React from "react"
import {
    StackedPoint,
    StackedRawSeries,
    StackedSeries,
} from "./StackedConstants"
import { OwidTable } from "../../coreTable/OwidTable"
import {
    autoDetectSeriesStrategy,
    autoDetectYColumnSlugs,
    makeSelectionArray,
} from "../chart/ChartUtils"
import { ScaleOrdinal, scaleOrdinal } from "d3-scale"
import { easeLinear } from "d3-ease"
import { select } from "d3-selection"
import { ColorSchemes } from "../color/ColorSchemes"
import { CoreColumn } from "../../coreTable/CoreTableColumns"
import { SelectionArray } from "../selection/SelectionArray"
import { CategoricalBin } from "../color/ColorScaleBin"
import { HorizontalColorLegendManager } from "../horizontalColorLegend/HorizontalColorLegends"
 
export interface AbstactStackedChartProps {
    bounds?: Bounds
    manager: ChartManager
    disableLinearInterpolation?: boolean // just for testing
}
 
@observer
export class AbstactStackedChart
    extends React.Component<AbstactStackedChartProps>
    implements ChartInterface, FontSizeManager
{
    transformTable(table: OwidTable): OwidTable {
        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)
            .dropRowsWithErrorValuesForAllColumns(this.yColumnSlugs)
 
        if (!this.props.disableLinearInterpolation) {
            this.yColumnSlugs.forEach((slug) => {
                table = table.interpolateColumnLinearly(slug)
            })
        }
 
        // Drop rows for which no valid data points exist for any display column
        // after interpolation, which most likely means they lie at the start/end
        // of the time range and were not extrapolated
        table = table.dropRowsWithErrorValuesForAnyColumn(this.yColumnSlugs)
 
        if (this.manager.isRelativeMode) {
            table = this.isEntitySeries
                ? table.toPercentageFromEachEntityForEachTime(
                      this.yColumnSlugs[0]
                  )
                : table.toPercentageFromEachColumnForEachEntityAndTime(
                      this.yColumnSlugs
                  )
        }
        return table
    }
 
    @computed get inputTable(): OwidTable {
        return this.manager.table
    }
 
    @computed get transformedTable(): OwidTable {
        return (
            this.manager.transformedTable ??
            this.transformTable(this.inputTable)
        )
    }
 
    @computed get manager(): ChartManager {
        return this.props.manager
    }
    @computed get bounds(): Bounds {
        return this.props.bounds ?? DEFAULT_BOUNDS
    }
 
    @computed get fontSize(): number {
        return this.manager.baseFontSize ?? BASE_FONT_SIZE
    }
 
    protected get paddingForLegend(): number {
        return 0
    }
 
    @computed get renderUid(): number {
        return guid()
    }
 
    @computed protected get yColumns(): CoreColumn[] {
        return this.transformedTable.getColumns(this.yColumnSlugs)
    }
 
    @computed protected get yColumnSlugs(): string[] {
        return (
            this.manager.yColumnSlugsInSelectionOrder ??
            autoDetectYColumnSlugs(this.manager)
        )
    }
 
    private animSelection?: d3.Selection<
        d3.BaseType,
        unknown,
        SVGGElement | null,
        unknown
    >
 
    base: React.RefObject<SVGGElement> = React.createRef()
    componentDidMount(): void {
        // Fancy intro animation
        this.animSelection = select(this.base.current)
            .selectAll("clipPath > rect")
            .attr("width", 0)
 
        this.animSelection
            .transition()
            .duration(800)
            .ease(easeLinear)
            .attr("width", this.bounds.width)
            .on("end", () => this.forceUpdate()) // Important in case bounds changes during transition
 
        exposeInstanceOnWindow(this)
    }
 
    componentWillUnmount(): void {
        if (this.animSelection) this.animSelection.interrupt()
    }
 
    @computed get seriesStrategy(): SeriesStrategy {
        return autoDetectSeriesStrategy(this.manager)
    }
 
    @computed protected get dualAxis(): DualAxis {
        const {
            bounds,
            horizontalAxisPart,
            verticalAxisPart,
            paddingForLegend,
        } = this
        return new DualAxis({
            bounds: bounds.padRight(paddingForLegend),
            horizontalAxis: horizontalAxisPart,
            verticalAxis: verticalAxisPart,
        })
    }
 
    @computed get yAxis(): VerticalAxis {
        return this.dualAxis.verticalAxis
    }
 
    @computed get xAxis(): HorizontalAxis {
        return this.dualAxis.horizontalAxis
    }
 
    @computed private get xAxisConfig(): AxisConfig {
        return new AxisConfig(this.manager.xAxisConfig, this)
    }
 
    @computed private get horizontalAxisPart(): HorizontalAxis {
        const axis = this.xAxisConfig.toHorizontalAxis()
        axis.updateDomainPreservingUserSettings(
            this.transformedTable.timeDomainFor(this.yColumnSlugs)
        )
        axis.formatColumn = this.inputTable.timeColumn
        axis.hideFractionalTicks = true
        axis.hideGridlines = true
        return axis
    }
 
    @computed private get yAxisConfig(): AxisConfig {
        // TODO: enable nice axis ticks for linear scales
        return new AxisConfig(this.manager.yAxisConfig, this)
    }
 
    @computed private get verticalAxisPart(): VerticalAxis {
        // const lastSeries = this.series[this.series.length - 1]
        // const yValues = lastSeries.points.map((d) => d.yOffset + d.y)
        const yValues = this.allStackedPoints.map(
            (point) => point.value + point.valueOffset
        )
        const axis = this.yAxisConfig.toVerticalAxis()
        // Use user settings for axis, unless relative mode
        if (this.manager.isRelativeMode) axis.domain = [0, 100]
        else axis.updateDomainPreservingUserSettings([0, max(yValues) ?? 100]) // Stacked area chart must have its own y domain)
        axis.formatColumn = this.yColumns[0]
        return axis
    }
 
    @computed
    private get columnsAsSeries(): readonly StackedRawSeries<number>[] {
        return this.yColumns
            .map((col) => {
                return {
                    isProjection: col.isProjection,
                    seriesName: col.displayName,
                    rows: col.owidRows,
                }
            })
            .reverse() // For stacked charts, we want the first selected series to be on top, so we reverse the order of the stacks.
    }
 
    @computed
    private get entitiesAsSeries(): readonly StackedRawSeries<number>[] {
        const { isProjection, owidRowsByEntityName } = this.yColumns[0]
        return this.selectionArray.selectedEntityNames
            .map((seriesName) => {
                return {
                    isProjection,
                    seriesName,
                    rows: owidRowsByEntityName.get(seriesName) || [],
                }
            })
            .reverse() // For stacked charts, we want the first selected series to be on top, so we reverse the order of the stacks.
    }
 
    @computed
    protected get rawSeries(): readonly StackedRawSeries<number>[] {
        return this.isEntitySeries
            ? this.entitiesAsSeries
            : this.columnsAsSeries
    }
 
    @computed
    protected get allStackedPoints(): readonly StackedPoint<number>[] {
        return flatten(this.series.map((series) => series.points))
    }
 
    @computed get failMessage(): string {
        const { yColumnSlugs } = this
        if (!yColumnSlugs.length) return "Missing variable"
        if (!this.series.length) return "No matching data"
        if (!this.allStackedPoints.length) return "No matching points"
        return ""
    }
 
    @computed private get colorScheme(): ScaleOrdinal<string, string> {
        const scheme =
            (this.manager.baseColorScheme
                ? ColorSchemes[this.manager.baseColorScheme]
                : null) ?? ColorSchemes.stackedAreaDefault
        const seriesCount = this.isEntitySeries
            ? this.selectionArray.numSelectedEntities
            : this.yColumns.length
        const baseColors = scheme.getColors(seriesCount)
        if (this.manager.invertColorScheme) baseColors.reverse()
        return scaleOrdinal(baseColors)
    }
 
    getColorForSeries(seriesName: SeriesName): string {
        const table = this.transformedTable
        const color = this.isEntitySeries
            ? table.getColorForEntityName(seriesName)
            : table.getColorForColumnByDisplayName(seriesName)
        return color ?? this.colorScheme(seriesName) ?? "#ddd"
    }
 
    @computed protected get selectionArray(): SelectionArray {
        return makeSelectionArray(this.manager)
    }
 
    @computed get isEntitySeries(): boolean {
        return this.seriesStrategy === SeriesStrategy.entity
    }
 
    @computed get seriesColors(): string[] {
        return this.series.map((series) => series.color)
    }
 
    /** Whether we want to display series with only zeroes. Defaults to true but e.g. StackedArea charts want to set this to false */
    get showAllZeroSeries(): boolean {
        return true
    }
 
    @computed get unstackedSeries(): readonly StackedSeries<number>[] {
        return this.rawSeries
            .filter(
                (series) =>
                    series.rows.length &&
                    (this.showAllZeroSeries ||
                        series.rows.some((row) => row.value !== 0))
            )
            .map((series) => {
                const { isProjection, seriesName, rows } = series
                return {
                    seriesName,
                    isProjection,
                    points: rows.map((row) => {
                        return {
                            position: row.time,
                            time: row.time,
                            value: row.value,
                            valueOffset: 0,
                        }
                    }),
                    color: this.getColorForSeries(seriesName),
                }
            }) as StackedSeries<number>[]
    }
 
    @computed get series(): readonly StackedSeries<number>[] {
        return this.unstackedSeries
    }
 
    @computed get externalLegend(): HorizontalColorLegendManager | undefined {
        if (this.manager.hideLegend) {
            const categoricalLegendData = this.series
                .map(
                    (series, index) =>
                        new CategoricalBin({
                            index,
                            value: series.seriesName,
                            label: series.seriesName,
                            color: series.color,
                        })
                )
                .reverse()
            return { categoricalLegendData }
        }
        return undefined
    }
}