All files / src/components/overview OverviewDetail.tsx

97.61% Statements 41/42
66.19% Branches 47/71
100% Functions 11/11
100% Lines 38/38

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 2841x                             1x           1x               1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 12x 16x 1x 1x 1x     6x     1x                                                                                   6x 6x                                                                         1x   1x           1x                                                                                                                                                                         6x 6x                                         3x                                 1x                          
"use client";
 
/**
 * The detail panel of a persona overview (issue #271): one node at a time,
 * with its latest value against the expected band, the trend, a chart, the
 * description, the facts, the series table and the links to the page that
 * owns the record. Plain HTML and inline SVG, so it reads without the scene.
 */
import Link from "next/link";
import { X } from "lucide-react";
import { isOutOfRange, trendOf } from "@/lib/overview/derive";
import type { OverviewNode } from "@/lib/overview/types";
import { useT } from "@/lib/i18n/translate";
 
/** A trend's direction in words, before "from {first} over {months} months". */
const TREND_WORDS: Record<string, string> = {
  rising: "rising",
  falling: "falling",
  stable: "stable",
};
 
const DIR_CLASS: Record<string, string> = {
  bad: "border-red-500 text-red-600 dark:text-red-400",
  warn: "border-amber-500 text-amber-600 dark:text-amber-400",
  ok: "border-emerald-500 text-emerald-600 dark:text-emerald-400",
  info: "border-sky-500 text-sky-600 dark:text-sky-400",
};
 
function SeriesChart({ node }: { node: OverviewNode }) {
  const t = useT("explore");
  const pts = node.series ?? [];
  Iif (pts.length < 2) return null;
  const W = 340;
  const H = 170;
  const L = 38;
  const R = 14;
  const T = 14;
  const B = 26;
  const xs = pts.map((p) => new Date(p.date).getTime());
  const vs = pts.map((p) => p.value);
  const lo = node.range?.low ?? null;
  const hi = node.range?.high ?? null;
  let ymin = Math.min(...vs, lo ?? Infinity);
  let ymax = Math.max(...vs, hi ?? -Infinity);
  const pad = (ymax - ymin || 1) * 0.15;
  ymin -= pad;
  ymax += pad;
  const x = (t: number) =>
    L + ((t - xs[0]) / (xs[xs.length - 1] - xs[0] || 1)) * (W - L - R);
  const y = (v: number) => T + (1 - (v - ymin) / (ymax - ymin)) * (H - T - B);
  const bandTop = y(hi ?? ymax);
  const bandBot = y(lo ?? ymin);
  const line = pts
    .map(
      (p) =>
        `${x(new Date(p.date).getTime()).toFixed(1)},${y(p.value).toFixed(1)}`,
    )
    .join(" ");
  return (
    <svg
      className="w-full h-[170px] block my-1"
      viewBox={`0 0 ${W} ${H}`}
      role="img"
      aria-label={t("{measure} over time", {
        measure: node.measure ?? node.label,
      })}
      data-testid="overview-chart"
    >
      <rect
        x={L}
        y={Math.min(bandTop, bandBot).toFixed(1)}
        width={W - L - R}
        height={Math.abs(bandBot - bandTop).toFixed(1)}
        fill="#22c55e"
        opacity="0.12"
      />
      {hi != null && (
        <text
          x={L - 4}
          y={(y(hi) + 4).toFixed(1)}
          textAnchor="end"
          fontSize="10"
          fill="#9ca3af"
        >
          {hi}
        </text>
      )}
      {lo != null && (
        <text
          x={L - 4}
          y={(y(lo) + 4).toFixed(1)}
          textAnchor="end"
          fontSize="10"
          fill="#9ca3af"
        >
          {lo}
        </text>
      )}
      <polyline points={line} fill="none" stroke="#93c5fd" strokeWidth="2" />
      {pts.map((p) => {
        const out = isOutOfRange(p.value, node.range);
        return (
          <circle
            key={p.date}
            cx={x(new Date(p.date).getTime()).toFixed(1)}
            cy={y(p.value).toFixed(1)}
            r="4"
            fill={out ? "#f59e0b" : "#22c55e"}
            stroke="#0b1220"
            strokeWidth="1.5"
          >
            <title>{`${p.date}: ${p.value} ${node.unit ?? ""}`}</title>
          </circle>
        );
      })}
      <text x={L} y={H - 8} fontSize="10" fill="#9ca3af">
        {pts[0].date.slice(0, 7)}
      </text>
      <text x={W - R} y={H - 8} fontSize="10" fill="#9ca3af" textAnchor="end">
        {pts[pts.length - 1].date.slice(0, 7)}
      </text>
    </svg>
  );
}
 
export interface OverviewDetailProps {
  node: OverviewNode;
  expanded: boolean;
  onClose: () => void;
  onToggleExpand?: () => void;
}
 
export default function OverviewDetail({
  node,
  expanded,
  onClose,
  onToggleExpand,
}: OverviewDetailProps) {
  const t = useT("explore");
  const trend =
    node.series && node.series.length > 1
      ? trendOf(node.series, {
          range: node.range,
          higherIsWorse: node.higherIsWorse !== false,
        })
      : null;
  return (
    <aside
      className="rounded-lg border border-(--border) bg-(--surface-2) p-4 text-sm overflow-auto lg:max-h-[calc(100vh-120px)]"
      data-testid="overview-detail"
      aria-label={t("Details: {name}", { name: node.title ?? node.label })}
    >
      <div className="flex items-start justify-between gap-2">
        <div>
          <div className="text-xs uppercase tracking-wide text-(--text-secondary)">
            {node.kind}
          </div>
          <h3 className="text-base font-semibold">
            {node.title ?? node.label}
          </h3>
          {node.sub && (
            <div className="text-xs text-(--text-secondary)">{node.sub}</div>
          )}
        </div>
        <button
          type="button"
          onClick={onClose}
          className="p-1 rounded-sm hover:bg-(--bg)"
          aria-label={t("Close details")}
        >
          <X size={16} />
        </button>
      </div>
 
      {node.description && (
        <p className="my-3 leading-relaxed" data-testid="overview-description">
          {node.description}
        </p>
      )}
 
      {trend && node.series && (
        <div className="my-2">
          <div
            className="flex items-baseline gap-3"
            data-testid="overview-trend"
          >
            <span className="text-2xl font-bold">
              {trend.last} {node.unit ?? ""}
            </span>
            <span
              className={`text-xs px-2 py-0.5 rounded-full border ${
                DIR_CLASS[trend.severity] ?? ""
              }`}
              data-severity={trend.severity}
            >
              {trend.dir === "stable"
                ? t(TREND_WORDS.stable)
                : t("{dir} from {first} over {months} months", {
                    dir: t(TREND_WORDS[trend.dir] ?? trend.dir),
                    first: trend.first,
                    months: trend.months,
                  })}
            </span>
          </div>
          <SeriesChart node={node} />
          <div className="text-xs text-(--text-secondary)">
            {t("Reference {range}. Green band: the expected range.", {
              range: node.range?.text ?? t("n/a"),
            })}{" "}
            {node.expand && (
              <button
                type="button"
                className="underline"
                onClick={onToggleExpand}
                data-testid="overview-toggle-expand"
              >
                {expanded
                  ? t("Fold the single values back into the node.")
                  : t("Unfold the single values as nodes.")}
              </button>
            )}
          </div>
          <table className="mt-2 w-full text-xs" data-testid="overview-series">
            <thead>
              <tr className="text-left text-(--text-secondary)">
                <th className="pr-3 font-medium">{t("Date")}</th>
                <th className="font-medium">{t("Value")}</th>
              </tr>
            </thead>
            <tbody>
              {[...node.series].reverse().map((p) => {
                const out = isOutOfRange(p.value, node.range);
                return (
                  <tr key={p.date} data-testid="overview-series-row">
                    <td className="pr-3">{p.date}</td>
                    <td
                      className={
                        out ? "text-amber-600 dark:text-amber-400" : ""
                      }
                    >
                      {p.value} {node.unit ?? ""}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
 
      {node.facts && node.facts.length > 0 && (
        <dl className="mt-3 grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs">
          {node.facts.map(([k, v], i) => (
            <div key={`${k}-${i}`} className="contents">
              <dt className="text-(--text-secondary)">{k}</dt>
              <dd>{v}</dd>
            </div>
          ))}
        </dl>
      )}
 
      {node.article && (
        <div className="mt-3 text-xs text-(--text-secondary)">
          {node.article}
        </div>
      )}
 
      {node.links && node.links.length > 0 && (
        <div className="mt-3 flex flex-wrap gap-3 text-xs">
          {node.links.map((l) => (
            <Link
              key={l.href}
              href={l.href}
              className="underline text-(--accent)"
            >
              {t(l.text)}
            </Link>
          ))}
        </div>
      )}
    </aside>
  );
}