All files / owid-grapher/grapher/dataTable DataTable.tsx

82.15% Statements 474/577
83.54% Branches 66/79
75.76% Functions 25/33
82.15% Lines 474/577

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 820 821 822 823 824 825 826 827 8281x 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 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 4x 4x 4x 4x 4x 4x 4x                               4x 4x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 4x 4x 5x 5x 5x 5x 5x 5x 5x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x         5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 4x 4x 1x 1x 1x 4x 2x 2x 4x 4x 4x 4x 4x 4x   4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 4x 4x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 4x 4x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 8x 16x 16x 16x 16x 16x 16x 11x 11x 11x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 1x 16x 16x 16x 16x 16x 16x 16x 4x 4x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 16x 16x 16x 16x 16x 16x   16x 16x 16x 10x 10x 10x 10x 4x 4x 5x 5x 5x 5x 4x 4x     4x 4x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 4x 4x     4x 4x 4x 4x 4x 4x 4x 4x                                                                           4x 4x 4x 4x 4x           4x 4x 4x 4x 4x 24x 24x 24x 4x 4x 4x 4x 1x 1x 4x 4x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 4x 4x 4x 4x 4x 4x 15x 15x 15x 15x 15x 14x 15x 15x 15x 15x 15x 15x 4x 4x 4x 4x 4x 4x 3x 3x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 4x 4x 4x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 3x 3x 3x 3x 4x 4x 4x 4x 4x 4x 4x 9x 9x 9x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      
import * as React from "react"
import { computed, observable, action } from "mobx"
import { observer } from "mobx-react"
import classnames from "classnames"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faInfoCircle } from "@fortawesome/free-solid-svg-icons/faInfoCircle"
import { SortOrder, Time } from "../../coreTable/CoreTableConstants"
import { EntityName, OwidTableSlugs } from "../../coreTable/OwidTableConstants"
import { TickFormattingOptions } from "../../clientUtils/formatValue"
import {
    capitalize,
    orderBy,
    upperFirst,
    valuesByEntityAtTimes,
    es6mapValues,
    valuesByEntityWithinTimes,
    getStartEndValues,
    sortBy,
    countBy,
    union,
    exposeInstanceOnWindow,
} from "../../clientUtils/Util"
import { SortIcon } from "../controls/SortIcon"
import { Tippy } from "../chart/Tippy"
import { BlankOwidTable, OwidTable } from "../../coreTable/OwidTable"
import { CoreColumn } from "../../coreTable/CoreTableColumns"
import { Bounds, DEFAULT_BOUNDS } from "../../clientUtils/Bounds"
import { makeSelectionArray } from "../chart/ChartUtils"
import { SelectionArray } from "../selection/SelectionArray"
import { ColumnSlug } from "../../clientUtils/owidTypes"
 
interface DataTableState {
    sort: DataTableSortState
}
 
const ENTITY_DIM_INDEX = -1
 
type DimensionIndex = number
 
interface DataTableSortState {
    dimIndex: DimensionIndex
    columnKey: ColumnKey | undefined
    order: SortOrder
}
 
const DEFAULT_SORT_STATE: DataTableSortState = {
    dimIndex: ENTITY_DIM_INDEX,
    columnKey: undefined,
    order: SortOrder.asc,
}
 
const columnNameByType: Record<ColumnKey, string> = {
    single: "Value",
    start: "Start",
    end: "End",
    delta: "Absolute Change",
    deltaRatio: "Relative Change",
}
 
const inverseSortOrder = (order: SortOrder): SortOrder =>
    order === SortOrder.asc ? SortOrder.desc : SortOrder.asc
 
export interface DataTableManager {
    table: OwidTable
    entityType: string
    endTime?: Time
    startTime?: Time
    minPopulationFilter?: number
    dataTableSlugs?: ColumnSlug[]
}
 
@observer
export class DataTable extends React.Component<{
    manager?: DataTableManager
    bounds?: Bounds
}> {
    @observable private storedState: DataTableState = {
        sort: DEFAULT_SORT_STATE,
    }
 
    @computed private get tableState(): DataTableState {
        return {
            sort: this.sortState,
        }
    }
 
    @computed private get sortState(): DataTableSortState {
        let { dimIndex, columnKey, order } = {
            ...DEFAULT_SORT_STATE,
            ...this.storedState.sort,
        }
 
        // If not sorted by entity, then make sure the index of the chosen column exists
        dimIndex = Math.min(dimIndex, this.table.numColumns - 1)
        if (dimIndex !== ENTITY_DIM_INDEX) {
            const availableColumns = this.columnsWithValues[
                dimIndex
            ].columns.map((sub) => sub.key)
            if (
                columnKey === undefined ||
                !availableColumns.includes(columnKey)
            )
                columnKey = availableColumns[0]
        }
 
        return {
            dimIndex,
            columnKey,
            order,
        }
    }
 
    @computed get table(): OwidTable {
        return this.inputTable
    }
 
    @computed get inputTable(): OwidTable {
        return this.manager.table
    }
 
    @computed get manager(): DataTableManager {
        return (
            this.props.manager ?? {
                table: BlankOwidTable(),
                entityType: "country",
            }
        )
    }
 
    @computed private get entityType(): string {
        return this.manager.entityType
    }
 
    @computed private get sortValueMapper(): (
        row: DataTableRow
    ) => number | string {
        const { dimIndex, columnKey, order } = this.tableState.sort
        if (dimIndex === ENTITY_DIM_INDEX)
            return (row): string => row.entityName

        return (row): string | number => {
            const dv = row.dimensionValues[dimIndex] as DimensionValue

            let value: number | string | undefined
            if (dv) {
                if (isSingleValue(dv)) value = dv.single?.value
                else if (
                    isRangeValue(dv) &&
                    columnKey !== undefined &&
                    columnKey in RangeValueKey
                )
                    value = dv[columnKey as RangeValueKey]?.value
            }

            // We always want undefined values to be last
            if (
                value === undefined ||
                (typeof value === "number" &&
                    (!isFinite(value) || isNaN(value)))
            )
                return order === SortOrder.asc ? Infinity : -Infinity

            return value
        }
    }
 
    @computed private get hasSubheaders(): boolean {
        return this.displayDimensions.some(
            (header) => header.columns.length > 1
        )
    }
 
    @action.bound private updateSort(
        dimIndex: DimensionIndex,
        columnKey?: ColumnKey
    ): void {
        const { sort } = this.tableState
        const order =
            sort.dimIndex === dimIndex && sort.columnKey === columnKey
                ? inverseSortOrder(sort.order)
                : dimIndex === ENTITY_DIM_INDEX
                ? SortOrder.asc
                : SortOrder.desc

        this.storedState.sort.dimIndex = dimIndex
        this.storedState.sort.columnKey = columnKey
        this.storedState.sort.order = order
    }
 
    private get entityHeader(): JSX.Element {
        const { sort } = this.tableState
        return (
            <ColumnHeader
                key="entity"
                sortable={true}
                sortedCol={sort.dimIndex === ENTITY_DIM_INDEX}
                sortOrder={sort.order}
                onClick={(): void => this.updateSort(ENTITY_DIM_INDEX)}
                rowSpan={this.hasSubheaders ? 2 : 1}
                headerText={capitalize(this.entityType)}
                colType="entity"
                dataType="text"
            />
        )
    }
 
    private get dimensionHeaders(): JSX.Element[] {
        const { sort } = this.tableState
        return this.displayDimensions.map((dim, dimIndex) => {
            const actualColumn = dim.coreTableColumn
            const unit =
                actualColumn.unit === "%" ? "percent" : dim.coreTableColumn.unit
            const columnName =
                actualColumn.displayName !== ""
                    ? actualColumn.displayName
                    : actualColumn.name
 
            const dimensionHeaderText = (
                <React.Fragment>
                    <span className="name">{upperFirst(columnName)}</span>
                    <span className="unit">{unit}</span>
                </React.Fragment>
            )
 
            const props = {
                sortable: dim.sortable,
                sortedCol: dim.sortable && sort.dimIndex === dimIndex,
                sortOrder: sort.order,
                onClick: (): void => {
                    if (dim.sortable) {
                        this.updateSort(dimIndex, SingleValueKey.single)
                    }
                },
                rowSpan: this.hasSubheaders && dim.columns.length < 2 ? 2 : 1,
                colSpan: dim.columns.length,
                headerText: dimensionHeaderText,
                colType: "dimension" as const,
                dataType: "numeric" as const,
            }
 
            return <ColumnHeader key={actualColumn.slug} {...props} />
        })
    }
 
    private get dimensionSubheaders(): JSX.Element[][] {
        const { sort } = this.tableState
        return this.displayDimensions.map((dim, dimIndex) =>
            dim.columns.map((column, i) => {
                const headerText = isDeltaColumn(column.key)
                    ? columnNameByType[column.key]
                    : dim.coreTableColumn.table.formatTime(column.targetTime!)
                return (
                    <ColumnHeader
                        key={column.key}
                        sortable={column.sortable}
                        sortedCol={
                            sort.dimIndex === dimIndex &&
                            sort.columnKey === column.key
                        }
                        sortOrder={sort.order}
                        onClick={(): void =>
                            this.updateSort(dimIndex, column.key)
                        }
                        headerText={headerText}
                        colType="subdimension"
                        dataType="numeric"
                        subdimensionType={column.key}
                        lastSubdimension={i === dim.columns.length - 1}
                    />
                )
            })
        )
    }
 
    private get headerRow(): JSX.Element {
        return (
            <React.Fragment>
                <tr>
                    {this.entityHeader}
                    {this.dimensionHeaders}
                </tr>
                {this.hasSubheaders && <tr>{this.dimensionSubheaders}</tr>}
            </React.Fragment>
        )
    }
 
    private renderValueCell(
        key: string,
        column: DataTableColumn,
        dv: DimensionValue | undefined,
        sorted: boolean,
        actualColumn: CoreColumn
    ): JSX.Element {
        if (dv === undefined || !(column.key in dv))
            return <td key={key} className="dimension" />
 
        let value: Value | undefined
 
        if (isSingleValue(dv)) value = dv[column.key as SingleValueKey] as Value
        else if (isRangeValue(dv))
            value = dv[column.key as RangeValueKey] as Value
 
        if (value === undefined) return <td key={key} className="dimension" />
 
        const shouldShowClosestTimeNotice =
            value.time !== undefined &&
            !isDeltaColumn(column.key) &&
            column.targetTime !== undefined &&
            column.targetTime !== value.time
 
        return (
            <td
                key={key}
                className={classnames([
                    "dimension",
                    `dimension-${column.key}`,
                    {
                        sorted,
                    },
                ])}
            >
                {shouldShowClosestTimeNotice &&
                    makeClosestTimeNotice(
                        actualColumn.table.formatTime(column.targetTime!),
                        actualColumn.table.formatTime(value.time!) // todo: add back format: "MMM D",
                    )}
                {value.displayValue}
            </td>
        )
    }
 
    private renderEntityRow(
        row: DataTableRow,
        dimensions: DataTableDimension[]
    ): JSX.Element {
        const { sort } = this.tableState
        return (
            <tr key={row.entityName}>
                <td
                    key="entity"
                    className={classnames({
                        entity: true,
                        sorted: sort.dimIndex === ENTITY_DIM_INDEX,
                    })}
                >
                    {row.entityName}
                </td>
                {row.dimensionValues.map((dv, dimIndex) => {
                    const dimension = dimensions[dimIndex]
                    return dimension.columns.map((column, colIndex) => {
                        const key = `${dimIndex}-${colIndex}`
                        return this.renderValueCell(
                            key,
                            column,
                            dv,
                            sort.dimIndex === dimIndex &&
                                sort.columnKey === column.key,
                            dimension.coreTableColumn
                        )
                    })
                })}
            </tr>
        )
    }
 
    private get valueRows(): JSX.Element[] {
        return this.sortedRows.map((row) =>
            this.renderEntityRow(row, this.displayDimensions)
        )
    }
 
    @computed get bounds(): Bounds {
        return this.props.bounds ?? DEFAULT_BOUNDS
    }
 
    render(): JSX.Element {
        return (
            <div
                style={{
                    width: "100%",
                    height: "100%",
                    overflow: "auto",
                }}
            >
                <table className="data-table">
                    <thead>{this.headerRow}</thead>
                    <tbody>{this.valueRows}</tbody>
                </table>
            </div>
        )
    }
 
    @computed private get loadedWithData(): boolean {
        return this.columnsToShow.length > 0
    }
 
    private readonly AUTO_SELECTION_THRESHOLD_PERCENTAGE = 0.5
 
    /**
     * If the user or the editor hasn't specified a start, auto-select a start time
     *  where AUTO_SELECTION_THRESHOLD_PERCENTAGE of the entities have values.
     */
    @computed get autoSelectedStartTime(): number | undefined {
        let autoSelectedStartTime: number | undefined = undefined

        if (
            // this.grapher.userHasSetTimeline ||
            //this.initialTimelineStartTimeSpecified ||
            !this.loadedWithData
        )
            return undefined

        const numEntitiesInTable = this.entityNames.length

        this.columnsToShow.forEach((column): boolean => {
            const numberOfEntitiesWithDataSortedByTime = sortBy(
                Object.entries(countBy(column.uniqTimesAsc)),
                (value) => parseInt(value[0])
            )

            const firstTimeWithSufficientData =
                numberOfEntitiesWithDataSortedByTime.find((time) => {
                    const numEntitiesWithData = time[1]
                    const percentEntitiesWithData =
                        numEntitiesWithData / numEntitiesInTable
                    return (
                        percentEntitiesWithData >=
                        this.AUTO_SELECTION_THRESHOLD_PERCENTAGE
                    )
                })?.[0]

            if (firstTimeWithSufficientData) {
                autoSelectedStartTime = parseInt(firstTimeWithSufficientData)
                return false
            }
            return true
        })

        return autoSelectedStartTime
    }
 
    @computed private get columnsToShow(): CoreColumn[] {
        const slugs = this.manager.dataTableSlugs ?? []
        if (slugs.length)
            return slugs
                .map((slug: string) => {
                    const col = this.table.get(slug)
                    if (!col) console.log(`Warning: column '${slug}' not found`)
                    return col
                })
                .filter((col) => col)
 
        const skips = new Set(Object.keys(OwidTableSlugs))
        return this.table.columnsAsArray.filter(
            (column) =>
                !skips.has(column.slug) &&
                //  dim.property !== "color" &&
                (column.display?.includeInTable ?? true)
        )
    }
 
    @computed private get selectionArray(): SelectionArray {
        return makeSelectionArray(this.manager)
    }
 
    @computed private get entityNames(): string[] {
        let tableForEntities = this.table
        if (this.manager.minPopulationFilter)
            tableForEntities = tableForEntities.filterByPopulationExcept(
                this.manager.minPopulationFilter,
                this.selectionArray.selectedEntityNames
            )
        return union(
            ...this.columnsToShow.map(
                (col) => tableForEntities.get(col.slug).uniqEntityNames
            )
        )
    }
 
    componentDidMount(): void {
        exposeInstanceOnWindow(this, "dataTable")
    }
 
    formatValue(
        column: CoreColumn,
        value: number | string | undefined,
        formattingOverrides?: TickFormattingOptions
    ): string | undefined {
        return value === undefined
            ? value
            : column.formatValueShort(value, {
                  numberPrefixes: false,
                  noTrailingZeroes: false,
                  ...formattingOverrides,
              })
    }
 
    @computed get targetTimes(): number[] | undefined {
        const { startTime, endTime } = this.manager
        if (startTime === undefined || endTime === undefined) return undefined
 
        if (startTime !== endTime) return [startTime, endTime]
        return [endTime]
    }
 
    // todo: this function should be refactored. It's about 5x-10x too long. I'm currently getting an undefined value but it's very hard to figure out where.
    @computed get columnsWithValues(): Dimension[] {
        return this.columnsToShow.map((sourceColumn) => {
            const targetTimes = this.targetTimes ?? [sourceColumn.maxTime]
 
            const targetTimeMode =
                targetTimes.length < 2
                    ? TargetTimeMode.point
                    : TargetTimeMode.range
 
            const prelimValuesByEntity =
                targetTimeMode === TargetTimeMode.range
                    ? // In the "range" mode, we receive all data values within the range. But we
                      // only want to plot the start & end values in the table.
                      // getStartEndValues() extracts these two values.
                      es6mapValues(
                          valuesByEntityWithinTimes(
                              sourceColumn.valueByEntityNameAndOriginalTime,
                              targetTimes
                          ),
                          getStartEndValues
                      )
                    : valuesByEntityAtTimes(
                          sourceColumn.valueByEntityNameAndOriginalTime,
                          targetTimes,
                          sourceColumn.tolerance
                      )
 
            const isRange = targetTimes.length === 2
 
            // Inject delta columns if we have start & end values to compare in the table.
            // One column for absolute difference, another for % difference.
            const deltaColumns: DimensionColumn[] = []
            if (isRange) {
                const tableDisplay = {} as any
                if (!tableDisplay?.hideAbsoluteChange)
                    deltaColumns.push({ key: RangeValueKey.delta })
                if (!tableDisplay?.hideRelativeChange)
                    deltaColumns.push({ key: RangeValueKey.deltaRatio })
            }
 
            const columns: DimensionColumn[] = [
                ...targetTimes.map((targetTime, index) => ({
                    key: isRange
                        ? index === 0
                            ? RangeValueKey.start
                            : RangeValueKey.end
                        : SingleValueKey.single,
                    targetTime,
                    targetTimeMode,
                })),
                ...deltaColumns,
            ]
 
            const valueByEntity = es6mapValues(prelimValuesByEntity, (dvs) => {
                // There is always a column, but not always a data value (in the delta column the
                // value needs to be calculated)
                if (isRange) {
                    const [start, end]: (Value | undefined)[] = dvs
                    const result: RangeValue = {
                        start: {
                            ...start,
                            displayValue: this.formatValue(
                                sourceColumn,
                                start?.value
                            ),
                        },
                        end: {
                            ...end,
                            displayValue: this.formatValue(
                                sourceColumn,
                                end?.value
                            ),
                        },
                        delta: undefined,
                        deltaRatio: undefined,
                    }
 
                    if (
                        start !== undefined &&
                        end !== undefined &&
                        typeof start.value === "number" &&
                        typeof end.value === "number"
                    ) {
                        const deltaValue = end.value - start.value
                        const deltaRatioValue =
                            deltaValue / Math.abs(start.value)
 
                        result.delta = {
                            value: deltaValue,
                            displayValue: this.formatValue(
                                sourceColumn,
                                deltaValue,
                                {
                                    showPlus: true,
                                    unit:
                                        sourceColumn.shortUnit === "%"
                                            ? "pp"
                                            : sourceColumn.shortUnit,
                                }
                            ),
                        }
 
                        result.deltaRatio = {
                            value: deltaRatioValue,
                            displayValue:
                                isFinite(deltaRatioValue) &&
                                !isNaN(deltaRatioValue)
                                    ? this.formatValue(
                                          sourceColumn,
                                          deltaRatioValue * 100,
                                          {
                                              unit: "%",
                                              numDecimalPlaces: 0,
                                              showPlus: true,
                                          }
                                      )
                                    : undefined,
                        }
                    }
                    return result
                } else {
                    // if single time
                    const dv = dvs[0]
                    const result: SingleValue = {
                        single: { ...dv },
                    }
                    if (dv !== undefined)
                        result.single!.displayValue = this.formatValue(
                            sourceColumn,
                            dv.value
                        )
                    return result
                }
            })
 
            return {
                columns,
                valueByEntity,
                sourceColumn,
            }
        })
    }
 
    @computed get displayDimensions(): DataTableDimension[] {
        // Todo: for sorting etc, use CoreTable?
        return this.columnsWithValues.map((d) => ({
            // A top-level header is only sortable if it has a single nested column, because
            // in that case the nested column is not rendered.
            sortable: d.columns.length === 1,
            columns: d.columns.map((column) => ({
                ...column,
                // All columns are sortable for now, but in the future we will have a sparkline that
                // is not sortable.
                sortable: true,
            })),
            coreTableColumn: d.sourceColumn,
        }))
    }
 
    @computed private get sortedRows(): DataTableRow[] {
        const { order } = this.tableState.sort
        return orderBy(this.displayRows, this.sortValueMapper, [order])
    }
 
    @computed private get displayRows(): DataTableRow[] {
        return this.entityNames.map((entityName) => {
            return {
                entityName,
                dimensionValues: this.columnsWithValues.map((d) =>
                    d.valueByEntity.get(entityName)
                ),
            }
        })
    }
}
 
function ColumnHeader(props: {
    sortable: boolean
    sortedCol: boolean
    sortOrder: SortOrder
    onClick: () => void
    rowSpan?: number
    colSpan?: number
    headerText: React.ReactFragment
    colType: "entity" | "dimension" | "subdimension"
    dataType: "text" | "numeric"
    subdimensionType?: ColumnKey
    lastSubdimension?: boolean
}): JSX.Element {
    const { sortable, sortedCol, colType, subdimensionType, lastSubdimension } =
        props
    return (
        <th
            className={classnames(colType, {
                sortable,
                sorted: sortedCol,
                firstSubdimension: subdimensionType === "start",
                endSubdimension: subdimensionType === "end",
                lastSubdimension,
            })}
            rowSpan={props.rowSpan ?? 1}
            colSpan={props.colSpan ?? 1}
            onClick={props.onClick}
        >
            <div
                className={classnames({
                    deltaColumn: isDeltaColumn(subdimensionType),
                })}
            >
                {props.headerText}
                {sortable && (
                    <SortIcon
                        type={props.dataType}
                        isActiveIcon={sortedCol}
                        order={
                            sortedCol
                                ? props.sortOrder
                                : colType === "entity"
                                ? SortOrder.asc
                                : SortOrder.desc
                        }
                    />
                )}
            </div>
        </th>
    )
}
 
const makeClosestTimeNotice = (
    targetTime: string,
    closestTime: string
): JSX.Element => (
    <Tippy
        content={
            <div className="closest-time-notice-tippy">
                <strong>Data not available for {targetTime}</strong>
                <br />
                Showing closest available data point ({closestTime})
            </div>
        }
        arrow={false}
    >
        <span className="closest-time-notice-icon">
            {closestTime}{" "}
            <span className="icon">
                <FontAwesomeIcon icon={faInfoCircle} />
            </span>
        </span>
    </Tippy>
)
 
enum TargetTimeMode {
    point = "point",
    range = "range",
}
 
interface Dimension {
    columns: DimensionColumn[]
    valueByEntity: Map<string, DimensionValue>
    sourceColumn: CoreColumn
}
 
interface DimensionColumn {
    key: SingleValueKey | RangeValueKey
    targetTime?: Time
    targetTimeMode?: TargetTimeMode
}
 
interface DataTableColumn extends DimensionColumn {
    sortable: boolean
}
 
interface Value {
    value?: string | number
    displayValue?: string
    time?: Time
}
 
// range (two point values)
enum RangeValueKey {
    start = "start",
    end = "end",
    delta = "delta",
    deltaRatio = "deltaRatio",
}
 
type RangeValue = Record<RangeValueKey, Value | undefined>
 
function isRangeValue(value: DimensionValue): value is RangeValue {
    return "start" in value
}
 
// single point values
enum SingleValueKey {
    single = "single",
}
 
type SingleValue = Record<SingleValueKey, Value | undefined>
 
function isSingleValue(value: DimensionValue): value is SingleValue {
    return "single" in value
}
 
// combined types
type DimensionValue = SingleValue | RangeValue
type ColumnKey = SingleValueKey | RangeValueKey
 
interface DataTableDimension {
    columns: DataTableColumn[]
    coreTableColumn: CoreColumn
    sortable: boolean
}
 
interface DataTableRow {
    entityName: EntityName
    dimensionValues: (DimensionValue | undefined)[] // TODO make it not undefined
}
 
function isDeltaColumn(columnKey?: ColumnKey): boolean {
    return columnKey === "delta" || columnKey === "deltaRatio"
}