All files / src/pages/flowsheet-page/economics/results-panel/charts/comparison StudyComparisonOverlayCharts.tsx

88.52% Statements 108/122
40.35% Branches 23/57
68.75% Functions 11/16
95.18% Lines 79/83

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                                                            103x 103x   5x         10x 10x 10x       5x   10x 5x   15x 5x     5x       5x             10x 5x                     5x 5x                       10x 5x 5x 12x                     15x 20x 20x 10x 25x       5x         10x 10x       5x   10x 5x     5x         5x         5x     5x 5x                   5x 5x                 5x 5x 5x 12x           10x 15x 20x 10x 20x       29x 29x 29x             29x 29x     29x 29x 29x 29x 29x 29x   29x 58x             261x 203x         10x 24x                   10x 2x   8x 8x 22x                   16x 16x                 35x   35x   35x           5x   12x 5x             70x    
import {
  Bar,
  BarChart,
  CartesianGrid,
  Line,
  LineChart,
  XAxis,
  YAxis,
} from "recharts";
import type { ChartConfig } from "@/ahuora-design-system/ui/chart";
import { ChartContainer, ChartTooltip } from "@/ahuora-design-system/ui/chart";
import type { ChartSeries, ParsedChartDataset } from "../../model/types";
import { stringField } from "../../model/valueParsing";
import { formatCompactAxisTick, formatYearAxisTick } from "../chartFormatters";
import {
  COMPARISON_CHART_CASH_FLOW,
  operatingTimelineColors,
  RESULT_CHART_BOTTOM_MARGIN,
  RESULT_CHART_X_AXIS_LABEL_OFFSET,
  RESULT_CHART_Y_AXIS_LABEL_DY,
  RESULT_CHART_Y_AXIS_LABEL_OFFSET,
  RESULT_CHART_Y_AXIS_WIDTH,
} from "../constants";
import { EconomicsChartTooltip } from "../EconomicsChartTooltip";
import {
  cashFlowOverlayRows,
  costBreakdownRows,
  costBreakdownTickLines,
} from "./studyComparisonOverlayData";
 
const COST_BREAKDOWN_AXIS_WIDTH = 270;
const COST_BREAKDOWN_TICK_LINE_HEIGHT = 20;
 
export function LineOverlayComparisonChart({
  dataset,
}: {
  dataset: ParsedChartDataset;
}) {
  const rows = cashFlowOverlayRows(dataset);
  const config = datasetChartConfig(dataset);
  const yAxisLabel = `Cash flow (${chartUnit(dataset)})`;
 
  return (
    <div className="flex h-full flex-col">
      <div className="sr-only" aria-label={`${dataset.title} x-axis label`}>
        Year
      </div>
      <div className="sr-only" aria-label={`${dataset.title} y-axis label`}>
        {yAxisLabel}
      </div>
      <ChartContainer
        config={config}
        className="min-h-0 w-full flex-1"
        aria-label={`Graph ${dataset.title}`}
      >
        <LineChart
          data={rows}
          margin={{
            left: 0,
            right: 28,
            top: 16,
            bottom: RESULT_CHART_BOTTOM_MARGIN,
          }}
        >
          <CartesianGrid vertical={false} strokeOpacity={0.35} />
          <XAxis
            dataKey="label"
            type="number"
            tickFormatter={formatYearAxisTick}
            tickLine={false}
            axisLine={false}
            label={{
              value: "Year",
              position: "insideBottom",
              offset: RESULT_CHART_X_AXIS_LABEL_OFFSET,
            }}
          />
          <YAxis
            width={RESULT_CHART_Y_AXIS_WIDTH}
            tickFormatter={formatCompactAxisTick}
            tickLine={false}
            axisLine={false}
            label={{
              value: yAxisLabel,
              angle: -90,
              position: "insideLeft",
              offset: RESULT_CHART_Y_AXIS_LABEL_OFFSET,
              dy: RESULT_CHART_Y_AXIS_LABEL_DY,
            }}
          />
          <ChartTooltip content={<EconomicsChartTooltip />} />
          {dataset.series.map((series, index) => (
            <Line
              key={series.key}
              type="monotone"
              dataKey={series.key}
              name={seriesDisplayLabel(dataset, series)}
              stroke={seriesColor(index)}
              strokeWidth={2}
              dot={rows.length <= 40 ? { r: 2.5 } : false}
              activeDot={{ r: 4 }}
              connectNulls
            />
          ))}
        </LineChart>
      </ChartContainer>
      <ComparisonLegend dataset={dataset} />
    </div>
  );
}
 
export function CostBreakdownComparisonChart({
  dataset,
}: {
  dataset: ParsedChartDataset;
}) {
  const rows = costBreakdownRows(dataset);
  const config = datasetChartConfig(dataset);
 
  return (
    <div className="flex h-full flex-col">
      <div className="sr-only" aria-label={`${dataset.title} x-axis label`}>
        Amount
      </div>
      <ChartContainer
        config={config}
        className="min-h-0 w-full flex-1"
        aria-label={`Graph ${dataset.title}`}
      >
        <BarChart
          data={rows}
          layout="vertical"
          margin={{
            left: 8,
            right: 16,
            top: 8,
            bottom: RESULT_CHART_BOTTOM_MARGIN,
          }}
          barCategoryGap={16}
        >
          <CartesianGrid horizontal={false} />
          <XAxis
            type="number"
            tickLine={false}
            axisLine={false}
            tickFormatter={formatCompactAxisTick}
            label={{
              value: "Amount",
              position: "insideBottom",
              offset: RESULT_CHART_X_AXIS_LABEL_OFFSET,
            }}
          />
          <YAxis
            type="category"
            dataKey="label"
            width={COST_BREAKDOWN_AXIS_WIDTH}
            interval={0}
            tickMargin={8}
            tickLine={false}
            axisLine={false}
            tick={<CostBreakdownYAxisTick />}
          />
          <ChartTooltip content={<EconomicsChartTooltip />} />
          {dataset.series.map((series, index) => (
            <Bar
              key={series.key}
              dataKey={series.key}
              name={seriesDisplayLabel(dataset, series)}
              fill={seriesColor(index)}
            />
          ))}
        </BarChart>
      </ChartContainer>
      <ComparisonLegend dataset={dataset} />
    </div>
  );
}
 
function CostBreakdownYAxisTick({
  x = 0,
  y = 0,
  payload,
}: {
  x?: number;
  y?: number;
  payload?: { value?: unknown };
}) {
  const lines = costBreakdownTickLines(payload?.value);
  const initialDy = -((lines.length - 1) * COST_BREAKDOWN_TICK_LINE_HEIGHT) / 2;
 
  return (
    <text
      x={x}
      y={y}
      textAnchor="end"
      className="fill-muted-foreground"
      fontSize={12}
    >
      {lines.map((line, index) => (
        <tspan
          key={`${line}-${index}`}
          x={x}
          dy={index === 0 ? initialDy : COST_BREAKDOWN_TICK_LINE_HEIGHT}
        >
          {line}
        </tspan>
      ))}
    </text>
  );
}
 
function datasetChartConfig(dataset: ParsedChartDataset): ChartConfig {
  return Object.fromEntries(
    dataset.series.map((series, index) => [
      series.key,
      {
        label: seriesDisplayLabel(dataset, series),
        color: seriesColor(index),
      },
    ]),
  ) as ChartConfig;
}
 
function ComparisonLegend({ dataset }: { dataset: ParsedChartDataset }) {
  Iif (dataset.series.length < 2) return null;
  return (
    <div className="mt-3 flex flex-wrap items-center justify-start gap-x-4 gap-y-1.5 pl-[84px] pr-2 text-xs leading-5 text-muted-foreground">
      {dataset.series.map((series, index) => (
        <div key={series.key} className="flex min-w-0 items-center gap-1.5">
          <span
            className="size-3 rounded-full"
            style={{ backgroundColor: seriesColor(index) }}
            aria-hidden="true"
          />
          <span className="truncate">
            {seriesDisplayLabel(dataset, series)}
          </span>
        </div>
      ))}
    </div>
  );
}
 
function seriesDisplayLabel(
  dataset: ParsedChartDataset,
  series: ChartSeries,
): string {
  if (dataset.chart_key !== COMPARISON_CHART_CASH_FLOW) {
    return series.label;
  }
  const metricLabel = stringField(series.points[0]?.metadata.metric_label);
  if (!metricLabel || series.label.includes(metricLabel)) {
    return series.label;
  }
  return `${series.label} - ${metricLabel}`;
}
 
function chartUnit(dataset: ParsedChartDataset) {
  return (
    dataset.series
      .flatMap((series) => series.points)
      .find((point) => point.unit)?.unit ||
    dataset.series.find((series) => series.unit)?.unit ||
    "amount"
  );
}
 
function seriesColor(index: number) {
  return operatingTimelineColors[index % operatingTimelineColors.length];
}