All files / owid-grapher/grapher/lineLegend LineLegend.tsx

98.3% Statements 346/352
81.82% Branches 27/33
81.25% Functions 13/16
98.3% Lines 346/352

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 4651x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 434x 434x 434x 434x 434x 434x 434x 1x 61x 61x 61x 61x 61x 61x 324x 324x 324x 324x 61x 61x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 82x 82x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 9x 9x 9x 9x 143x 143x 143x 143x 143x 143x 143x 143x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 6x 6x 6x 6x 6x 6x 6x 6x     6x     6x     6x 6x 29x 29x 29x 29x 6x 6x 29x 29x 6x 6x 6x 29x 29x 29x 29x 29x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 29x 29x 29x 6x 6x 29x 29x 29x 29x 29x 29x 29x 29x 29x 84x 84x 217x 217x 217x 217x 217x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 217x 84x 29x 29x 82x 82x 82x 143x 143x 143x 143x 109x 109x 143x 143x 143x 82x 82x 82x 143x 143x 143x 82x 29x 29x 29x 6x                                                                                                                                                                                                                                  
// This implements the line labels that appear to the right of the lines/polygons in LineCharts/StackedAreas.
import * as React from "react"
import {
    noop,
    cloneDeep,
    max,
    min,
    sortBy,
    sumBy,
    flatten,
} from "../../clientUtils/Util"
import { computed } from "mobx"
import { observer } from "mobx-react"
import { TextWrap } from "../text/TextWrap"
import { VerticalAxis } from "../axis/Axis"
import { Bounds } from "../../clientUtils/Bounds"
import { EntityName } from "../../coreTable/OwidTableConstants"
import { BASE_FONT_SIZE } from "../core/GrapherConstants"
import { ChartSeries } from "../chart/ChartInterface"
import { darkenColorForText } from "../color/ColorUtils"
 
// Minimum vertical space between two legend items
const LEGEND_ITEM_MIN_SPACING = 2
// Horizontal distance from the end of the chart to the start of the marker
const MARKER_MARGIN = 4
// Need a constant button height which we can use in positioning calculations
const ADD_BUTTON_HEIGHT = 30
 
const DEFAULT_FONT_WEIGHT = 400
 
export interface LineLabelSeries extends ChartSeries {
    label: string
    yValue: number
    annotation?: string
    yRange?: [number, number]
}
 
interface SizedSeries extends LineLabelSeries {
    textWrap: TextWrap
    annotationTextWrap?: TextWrap
    width: number
    height: number
}
 
interface PlacedSeries extends SizedSeries {
    origBounds: Bounds
    bounds: Bounds
    isOverlap: boolean
    repositions: number
    level: number
    totalLevels: number
}
 
function groupBounds(group: PlacedSeries[]): Bounds {
    const first = group[0]
    const last = group[group.length - 1]
    const height = last.bounds.bottom - first.bounds.top
    const width = Math.max(first.bounds.width, last.bounds.width)
    return new Bounds(first.bounds.x, first.bounds.y, width, height)
}
 
function stackGroupVertically(
    group: PlacedSeries[],
    y: number
): PlacedSeries[] {
    let currentY = y
    group.forEach((mark) => {
        mark.bounds = mark.bounds.set({ y: currentY })
        mark.repositions += 1
        currentY += mark.bounds.height + LEGEND_ITEM_MIN_SPACING
    })
    return group
}
 
@observer
class Label extends React.Component<{
    series: PlacedSeries
    manager: LineLegend
    isFocus?: boolean
    needsLines?: boolean
    onMouseOver: () => void
    onClick: () => void
    onMouseLeave?: () => void
}> {
    render(): JSX.Element {
        const {
            series,
            manager,
            isFocus,
            needsLines,
            onMouseOver,
            onMouseLeave,
            onClick,
        } = this.props
        const x = series.origBounds.x
        const markerX1 = x + MARKER_MARGIN
        const markerX2 = x + manager.leftPadding - MARKER_MARGIN
        const step = (markerX2 - markerX1) / (series.totalLevels + 1)
        const markerXMid = markerX1 + step + series.level * step
        const lineColor = isFocus ? "#999" : "#eee"
        const textColor = isFocus ? darkenColorForText(series.color) : "#ddd"
        const annotationColor = isFocus ? "#333" : "#ddd"
        return (
            <g
                className="legendMark"
                onMouseOver={onMouseOver}
                onMouseLeave={onMouseLeave}
                onClick={onClick}
            >
                {needsLines && (
                    <g className="indicator">
                        <path
                            d={`M${markerX1},${series.origBounds.centerY} H${markerXMid} V${series.bounds.centerY} H${markerX2}`}
                            stroke={lineColor}
                            strokeWidth={0.5}
                            fill="none"
                        />
                    </g>
                )}
                <rect
                    x={x}
                    y={series.bounds.y}
                    width={series.bounds.width}
                    height={series.bounds.height}
                    fill="#fff"
                    opacity={0}
                />
                {series.textWrap.render(
                    needsLines ? markerX2 + MARKER_MARGIN : markerX1,
                    series.bounds.y,
                    { fill: textColor }
                )}
                {series.annotationTextWrap &&
                    series.annotationTextWrap.render(
                        needsLines ? markerX2 + MARKER_MARGIN : markerX1,
                        series.bounds.y + series.textWrap.height,
                        {
                            fill: annotationColor,
                            className: "textAnnotation",
                            style: { fontWeight: "lighter" },
                        }
                    )}
            </g>
        )
    }
}
 
export interface LineLegendManager {
    startSelectingWhenLineClicked?: boolean
    canAddData?: boolean
    isSelectingData?: boolean
    entityType?: string
    labelSeries: LineLabelSeries[]
    maxLineLegendWidth?: number
    fontSize?: number
    fontWeight?: number
    onLineLegendMouseOver?: (key: EntityName) => void
    onLineLegendClick?: (key: EntityName) => void
    onLineLegendMouseLeave?: () => void
    focusedSeriesNames: EntityName[]
    yAxis: VerticalAxis
    lineLegendX?: number
}
 
@observer
export class LineLegend extends React.Component<{
    manager: LineLegendManager
}> {
    leftPadding = 35
 
    @computed private get fontSize(): number {
        return 0.75 * (this.manager.fontSize ?? BASE_FONT_SIZE)
    }
 
    @computed private get fontWeight(): number {
        return this.manager.fontWeight ?? DEFAULT_FONT_WEIGHT
    }
 
    @computed private get maxWidth(): number {
        return this.manager.maxLineLegendWidth ?? 300
    }
 
    @computed.struct get sizedLabels(): SizedSeries[] {
        const { fontSize, fontWeight, leftPadding, maxWidth } = this
        const maxTextWidth = maxWidth - leftPadding
        const maxAnnotationWidth = Math.min(maxTextWidth, 150)
 
        return this.manager.labelSeries.map((label) => {
            const annotationTextWrap = label.annotation
                ? new TextWrap({
                      text: label.annotation,
                      maxWidth: maxAnnotationWidth,
                      fontSize: fontSize * 0.9,
                  })
                : undefined
            const textWrap = new TextWrap({
                text: label.label,
                maxWidth: maxTextWidth,
                fontSize,
                fontWeight,
            })
            return {
                ...label,
                textWrap,
                annotationTextWrap,
                width:
                    leftPadding +
                    Math.max(
                        textWrap.width,
                        annotationTextWrap ? annotationTextWrap.width : 0
                    ),
                height:
                    textWrap.height +
                    (annotationTextWrap ? annotationTextWrap.height : 0),
            }
        })
    }
 
    @computed get width(): number {
        if (this.sizedLabels.length === 0) return 0
        return max(this.sizedLabels.map((d) => d.width)) ?? 0
    }
 
    @computed get onMouseOver(): any {
        return this.manager.onLineLegendMouseOver ?? noop
    }
    @computed get onMouseLeave(): any {
        return this.manager.onLineLegendMouseLeave ?? noop
    }
    @computed get onClick(): any {
        return this.manager.onLineLegendClick ?? noop
    }
 
    @computed get isFocusMode(): boolean {
        return this.sizedLabels.some((label) =>
            this.manager.focusedSeriesNames.includes(label.seriesName)
        )
    }
 
    @computed get legendX(): number {
        return this.manager.lineLegendX ?? 0
    }
 
    // Naive initial placement of each mark at the target height, before collision detection
    @computed private get initialSeries(): PlacedSeries[] {
        const { yAxis } = this.manager
        const { legendX } = this
 
        return sortBy(
            this.sizedLabels.map((label) => {
                // place vertically centered at Y value
                const initialY = yAxis.place(label.yValue) - label.height / 2
                const origBounds = new Bounds(
                    legendX,
                    initialY,
                    label.width,
                    label.height
                )
 
                // ensure label doesn't go beyond the top or bottom of the chart
                const y = Math.min(
                    Math.max(initialY, yAxis.rangeMin),
                    yAxis.rangeMax - label.height
                )
                const bounds = new Bounds(legendX, y, label.width, label.height)
 
                return {
                    ...label,
                    y,
                    origBounds,
                    bounds,
                    isOverlap: false,
                    repositions: 0,
                    level: 0,
                    totalLevels: 0,
                }
 
                // Ensure list is sorted by the visual position in ascending order
            }),
            (label) => yAxis.place(label.yValue)
        )
    }
 
    @computed get standardPlacement(): PlacedSeries[] {
        const { yAxis } = this.manager
 
        const groups: PlacedSeries[][] = cloneDeep(this.initialSeries).map(
            (mark) => [mark]
        )
 
        let hasOverlap
 
        do {
            hasOverlap = false
            for (let i = 0; i < groups.length - 1; i++) {
                const topGroup = groups[i]
                const bottomGroup = groups[i + 1]
                const topBounds = groupBounds(topGroup)
                const bottomBounds = groupBounds(bottomGroup)
                if (topBounds.intersects(bottomBounds)) {
                    const overlapHeight =
                        topBounds.bottom -
                        bottomBounds.top +
                        LEGEND_ITEM_MIN_SPACING
                    const newHeight =
                        topBounds.height +
                        LEGEND_ITEM_MIN_SPACING +
                        bottomBounds.height
                    const targetY =
                        topBounds.top -
                        overlapHeight *
                            (bottomGroup.length /
                                (topGroup.length + bottomGroup.length))
                    const overflowTop = Math.max(yAxis.rangeMin - targetY, 0)
                    const overflowBottom = Math.max(
                        targetY + newHeight - yAxis.rangeMax,
                        0
                    )
                    const newY = targetY + overflowTop - overflowBottom
                    const newGroup = [...topGroup, ...bottomGroup]
                    stackGroupVertically(newGroup, newY)
                    groups.splice(i, 2, newGroup)
                    hasOverlap = true
                    break
                }
            }
        } while (hasOverlap && groups.length > 1)
 
        for (const group of groups) {
            let currentLevel = 0
            let prevSign = 0
            for (const series of group) {
                const currentSign = Math.sign(
                    series.bounds.y - series.origBounds.y
                )
                if (prevSign === currentSign) {
                    currentLevel -= currentSign
                }
                series.level = currentLevel
                prevSign = currentSign
            }
            const minLevel = min(group.map((mark) => mark.level)) as number
            const maxLevel = max(group.map((mark) => mark.level)) as number
            for (const mark of group) {
                mark.level -= minLevel
                mark.totalLevels = maxLevel - minLevel + 1
            }
        }
 
        return flatten(groups)
    }
 
    // Overlapping placement, for when we really can't find a solution without overlaps.
    @computed get overlappingPlacement(): PlacedSeries[] {
        const series = cloneDeep(this.initialSeries)
        for (let i = 0; i < series.length; i++) {
            const m1 = series[i]
 
            for (let j = i + 1; j < series.length; j++) {
                const m2 = series[j]
                const isOverlap =
                    !m1.isOverlap && m1.bounds.intersects(m2.bounds)
                if (isOverlap) m2.isOverlap = true
            }
        }
        return series
    }
 
    @computed get placedSeries(): PlacedSeries[] {
        const nonOverlappingMinHeight =
            sumBy(this.initialSeries, (series) => series.bounds.height) +
            this.initialSeries.length * LEGEND_ITEM_MIN_SPACING
        const availableHeight = this.manager.canAddData
            ? this.manager.yAxis.rangeSize - ADD_BUTTON_HEIGHT
            : this.manager.yAxis.rangeSize
 
        // Need to be careful here – the controls overlay will automatically add padding if
        // needed to fit the floating 'Add country' button, therefore decreasing the space
        // available to render the legend.
        // At a certain height, this ends up infinitely toggling between the two placement
        // modes. The overlapping placement allows the button to float without additional
        // padding, which then frees up space, causing the legend to render with
        // standardPlacement.
        // This is why we need to take into account the height of the 'Add country' button.
        if (nonOverlappingMinHeight > availableHeight)
            return this.overlappingPlacement
 
        return this.standardPlacement
    }
 
    @computed private get backgroundSeries(): PlacedSeries[] {
        const { focusedSeriesNames } = this.manager
        const { isFocusMode } = this
        return this.placedSeries.filter((mark) =>
            isFocusMode
                ? !focusedSeriesNames.includes(mark.seriesName)
                : mark.isOverlap
        )
    }
 
    @computed private get focusedSeries(): PlacedSeries[] {
        const { focusedSeriesNames } = this.manager
        const { isFocusMode } = this
        return this.placedSeries.filter((mark) =>
            isFocusMode
                ? focusedSeriesNames.includes(mark.seriesName)
                : !mark.isOverlap
        )
    }
 
    // Does this placement need line markers or is the position of the labels already clear?
    @computed private get needsLines(): boolean {
        return this.placedSeries.some((series) => series.totalLevels > 1)
    }
 
    private renderBackground(): JSX.Element[] {
        return this.backgroundSeries.map((series, index) => (
            <Label
                key={`background-${index}-` + series.seriesName}
                series={series}
                manager={this}
                needsLines={this.needsLines}
                onMouseOver={(): void => this.onMouseOver(series.seriesName)}
                onClick={(): void => this.onClick(series.seriesName)}
            />
        ))
    }
 
    // All labels are focused by default, moved to background when mouseover of other label
    private renderFocus(): JSX.Element[] {
        return this.focusedSeries.map((series, index) => (
            <Label
                key={`focus-${index}-` + series.seriesName}
                series={series}
                manager={this}
                isFocus={true}
                needsLines={this.needsLines}
                onMouseOver={(): void => this.onMouseOver(series.seriesName)}
                onClick={(): void => this.onClick(series.seriesName)}
                onMouseLeave={(): void => this.onMouseLeave(series.seriesName)}
            />
        ))
    }
 
    @computed get manager(): LineLegendManager {
        return this.props.manager
    }
 
    render(): JSX.Element {
        return (
            <g
                className="LineLabels"
                style={{
                    cursor: this.manager.startSelectingWhenLineClicked
                        ? "pointer"
                        : "default",
                }}
            >
                {this.renderBackground()}
                {this.renderFocus()}
            </g>
        )
    }
}