All files / src/pages/flowsheet-page/dynamics/results-panel/views GraphResultView.tsx

58.73% Statements 74/126
49.61% Branches 64/129
30.76% Functions 4/13
64.44% Lines 58/90

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                                                                                  103x             103x                               69x                               1600x           1600x                   69x 2389x     2389x             69x 69x               30x 30x 30x     69x     69x                         69x 69x   69x                                               87x                     74x 74x 18x   110x   74x         74x 18x   110x   73x   73x       105x 102x   73x 73x         73x 73x                     88x 37x 52x         36x   1213x     1x 2x 3x           8x 27x 35x         9x 9x 69x 69x 69x 69x 69x 69x 69x                                                                                                                                                                                                                                                                           81x 27x                 109x        
import { skipToken } from "@reduxjs/toolkit/query";
import { useState } from "react";
import {
  CartesianGrid,
  Label,
  Line,
  LineChart,
  Scatter,
  ScatterChart,
  XAxis,
  YAxis,
  ZAxis,
} from "recharts";
import {
  ChartConfig,
  ChartContainer,
  ChartTooltip,
} from "@/ahuora-design-system/ui/chart";
import {
  MssTimeSeriesUnitEnum,
  ResultGraphPoint,
  ResultSummary,
  ScenarioRead,
  StateNameEnum,
  useCoreDataRowOutputGraphListQuery,
  useCoreDataRowOutputSummaryRetrieveQuery,
} from "@/api/apiStore.gen";
import { ResultMetricStrip } from "../components/ResultMetricStrip";
import {
  ResultEmptyMessage,
  ResultLoadingMessage,
  ResultSummaryStatusMessage,
} from "../components/ResultStatusMessage";
import { ResultCard, ResultViewGrid } from "../components/ResultViewLayout";
import type { ResultMetricNavigationTarget } from "../utils/resultMetricNavigation";
import {
  getResultSummaryStatus,
  isResultSummaryPending,
  isResultSummaryUnavailable,
} from "../utils/resultSummaryStatus";
 
const chartConfig = {
  desktop: {
    label: "Desktop",
    color: "hsl(var(--chart-1))",
  },
} satisfies ChartConfig;
 
const GRAPH_Y_AXIS_WIDTH = 78;
 
type GraphTooltipPoint = {
  index?: number | string | null;
  key?: string | null;
  label?: string | null;
  unit?: string | null;
  value?: number | string | null;
};
 
type GraphTooltipPayload = {
  payload?: GraphTooltipPoint;
  value?: number | string | null;
};
 
function getXAxisTickInterval(pointCount: number): number {
  return Math.max(0, Math.ceil(pointCount / 12) - 1);
}
 
function formatGraphTooltipValue(value: number | string | null | undefined) {
  if (typeof value === "number") {
    return Number.isFinite(value)
      ? Intl.NumberFormat(undefined, {
          maximumFractionDigits: 4,
        }).format(value)
      : "Unavailable";
  }
 
  return value ?? "Unavailable";
}
 
function formatGraphAxisValue(value: number | string): string {
  const numericValue = typeof value === "number" ? value : Number(value);
 
  if (!Number.isFinite(numericValue)) {
    return String(value);
  }
 
  return Intl.NumberFormat(undefined, {
    maximumFractionDigits: 1,
    notation: Math.abs(numericValue) >= 1000 ? "compact" : "standard",
  }).format(numericValue);
}
 
function getYAxisDomain(
  solution: Array<{ value?: number | null }>,
  includeZeroBaseline: boolean,
): [number, number] {
  const values = solution
    .map((point) => point.value)
    .filter(
      (value): value is number =>
        typeof value === "number" && Number.isFinite(value),
    );
 
  if (values.length === 0) {
    return [0, 1];
  }
 
  let minValue = Math.min(...values);
  let maxValue = Math.max(...values);
 
  if (includeZeroBaseline) {
    minValue = Math.min(minValue, 0);
    maxValue = Math.max(maxValue, 0);
  }
 
  if (minValue === maxValue) {
    const padding = Math.max(Math.abs(minValue) * 0.05, 1);
    minValue -= padding;
    maxValue += padding;
  }
 
  return [Math.floor(minValue), Math.ceil(maxValue)];
}
 
function ScenarioGraphTooltip({
  active,
  enabled,
  payload,
  unit,
  xAxisLabel,
}: {
  active?: boolean;
  enabled: boolean;
  payload?: GraphTooltipPayload[];
  unit?: string | null;
  xAxisLabel: string;
}) {
  const point = payload?.[0]?.payload;
  const value = payload?.[0]?.value ?? point?.value;
 
  if (!enabled || !active || !point) {
    return null;
  }
 
  return (
    <div className="grid min-w-[10rem] gap-1.5 rounded-lg border border-border bg-background px-2.5 py-2 text-xs shadow-xl">
      <div className="flex items-center justify-between gap-4">
        <span className="text-muted-foreground">{xAxisLabel}</span>
        <span className="font-mono font-medium tabular-nums">
          {formatGraphTooltipValue(point.index)}
        </span>
      </div>
      <div className="flex items-center justify-between gap-4">
        <span className="text-muted-foreground">
          {unit ? `Value (${unit})` : "Value"}
        </span>
        <span className="font-mono font-medium tabular-nums">
          {formatGraphTooltipValue(value)}
        </span>
      </div>
    </div>
  );
}
 
export default function GraphResultView({
  includeZeroBaseline,
  onMetricTargetSelect,
  scenario,
  selectedObjectId,
}: {
  includeZeroBaseline: boolean;
  onMetricTargetSelect?: (target: ResultMetricNavigationTarget) => void;
  scenario: ScenarioRead;
  selectedObjectId: number | undefined;
}) {
  const [activeTooltipKey, setActiveTooltipKey] = useState<string | null>(null);
  const graphQuery = useCoreDataRowOutputGraphListQuery(
    selectedObjectId
      ? { scenario: scenario.id, simulationObject: selectedObjectId }
      : skipToken,
  );
  const { data: list } = graphQuery;
  const {
    data: summaryData,
    error: summaryError,
    ...summaryQuery
  } = useCoreDataRowOutputSummaryRetrieveQuery(
    selectedObjectId
      ? { scenario: scenario.id, simulationObject: selectedObjectId }
      : skipToken,
  );
  const summaryStatus =
    getResultSummaryStatus(summaryData) ?? getResultSummaryStatus(summaryError);
  const summaryByKey = new Map(
    (Array.isArray(summaryData) ? summaryData : []).map(
      (summary: ResultSummary) => [summary.key, summary],
    ),
  );
  const graphSeries: ResultGraphPoint[][] = Array.isArray(list) ? list : [];
 
  const isDynamics = scenario.enable_dynamics;
  const isMssTimeSeries =
    !isDynamics &&
    scenario.state_name === StateNameEnum.Mss &&
    Boolean(scenario.mss_time_series_enabled);
  const timeSeriesUnit =
    scenario.mss_time_series_unit ?? MssTimeSeriesUnitEnum.Seconds;
  const xAxisLabel = isDynamics
    ? "Time step"
    : isMssTimeSeries
      ? `Time (${timeSeriesUnit})`
      : "Row";
 
  if (
    selectedObjectId &&
    (isQueryLoading(graphQuery) || isQueryLoading(summaryQuery))
  ) {
    return (
      <ResultViewGrid selectedObjectId={selectedObjectId}>
        <ResultLoadingMessage />
      </ResultViewGrid>
    );
  }
 
  if (
    summaryStatus &&
    (isResultSummaryPending(summaryStatus) ||
      isResultSummaryUnavailable(summaryStatus))
  ) {
    return (
      <ResultViewGrid selectedObjectId={selectedObjectId}>
        <ResultSummaryStatusMessage status={summaryStatus} />
      </ResultViewGrid>
    );
  }
 
  if (selectedObjectId && graphSeries.length === 0) {
    return (
      <ResultViewGrid selectedObjectId={selectedObjectId}>
        <ResultEmptyMessage />
      </ResultViewGrid>
    );
  }
 
  return (
    <ResultViewGrid selectedObjectId={selectedObjectId}>
      {graphSeries.map((solution) => {
        const firstPoint = solution[0];
        const resultKey = firstPoint?.key ?? firstPoint?.label ?? "Result";
        const propertyLabel = firstPoint?.label ?? resultKey;
        const showLineChart = isDynamics || isMssTimeSeries;
        const summary = summaryByKey.get(resultKey);
        const xAxisTickInterval = getXAxisTickInterval(solution.length);
        const yAxisDomain = getYAxisDomain(solution, includeZeroBaseline);
 
        return (
          <ResultCard
            key={resultKey}
            title={propertyLabel}
            unit={summary?.unit}
          >
            <ResultMetricStrip
              metricTargets={summary?.metric_targets}
              onMetricTargetSelect={onMetricTargetSelect}
              resultKey={resultKey}
              resultLabel={propertyLabel}
              stats={summary?.stats}
              unit={summary?.unit}
            />
            <ChartContainer
              config={chartConfig}
              className="w-full h-[220px]"
              onMouseEnter={() => setActiveTooltipKey(resultKey)}
              onMouseMove={() => setActiveTooltipKey(resultKey)}
              onMouseLeave={() =>
                setActiveTooltipKey((currentKey) =>
                  currentKey === resultKey ? null : currentKey,
                )
              }
            >
              {showLineChart ? (
                <LineChart
                  data={solution}
                  margin={{ bottom: 8, left: 6, right: 8, top: 4 }}
                >
                  <CartesianGrid vertical={false} />
                  <XAxis
                    dataKey="index"
                    height={56}
                    interval={xAxisTickInterval}
                    minTickGap={8}
                    tick={{ fontSize: 11 }}
                    tickMargin={8}
                  >
                    <Label
                      value={xAxisLabel}
                      offset={-2}
                      position="insideBottom"
                    />
                  </XAxis>
                  <YAxis
                    type="number"
                    domain={yAxisDomain}
                    tick={{ fontSize: 11 }}
                    tickFormatter={formatGraphAxisValue}
                    tickMargin={8}
                    width={GRAPH_Y_AXIS_WIDTH}
                    hide={false}
                  >
                    <Label
                      value="Value"
                      angle={-90}
                      offset={8}
                      position="insideLeft"
                    />
                  </YAxis>
                  <Line
                    dataKey="value"
                    type="linear"
                    stroke="var(--color-desktop)"
                    strokeWidth={2}
                    dot={false}
                    activeDot={{ r: 3 }}
                  />
                  <ChartTooltip
                    cursor={false}
                    content={
                      <ScenarioGraphTooltip
                        enabled={activeTooltipKey === resultKey}
                        unit={summary?.unit}
                        xAxisLabel={xAxisLabel}
                      />
                    }
                  />
                </LineChart>
              ) : (
                <ScatterChart
                  data={solution}
                  margin={{ bottom: 8, left: 6, right: 8, top: 4 }}
                >
                  <CartesianGrid vertical={false} />
                  <XAxis
                    dataKey="index"
                    height={56}
                    interval={xAxisTickInterval}
                    minTickGap={8}
                    tick={{ fontSize: 11 }}
                    tickMargin={8}
                  >
                    <Label
                      value={xAxisLabel}
                      offset={-2}
                      position="insideBottom"
                    />
                  </XAxis>
                  <YAxis
                    type="number"
                    domain={yAxisDomain}
                    tick={{ fontSize: 11 }}
                    tickFormatter={formatGraphAxisValue}
                    tickMargin={8}
                    width={GRAPH_Y_AXIS_WIDTH}
                  >
                    <Label
                      value="Value"
                      angle={-90}
                      offset={8}
                      position="insideLeft"
                    />
                  </YAxis>
                  <ZAxis range={[30, 31]} />
                  <Scatter dataKey="value" fill="var(--color-desktop)" />
                  <ChartTooltip
                    cursor={false}
                    content={
                      <ScenarioGraphTooltip
                        enabled={activeTooltipKey === resultKey}
                        unit={summary?.unit}
                        xAxisLabel={xAxisLabel}
                      />
                    }
                  />
                </ScatterChart>
              )}
            </ChartContainer>
          </ResultCard>
        );
      })}
    </ResultViewGrid>
  );
}
 
function isQueryLoading(query: {
  currentData?: unknown;
  isFetching?: boolean;
  isLoading?: boolean;
}): boolean {
  return Boolean(
    query.isLoading || (query.isFetching && query.currentData == null),
  );
}