"use client"; import { useRecordCapabilities } from "@/hooks/use-record-capabilities"; import { useMemo } from "react"; import Link from "next/link"; import { useQuery } from "@tanstack/react-query"; import { ChevronRight, FlaskConical } from "lucide-react"; import { MedicationCardHeader } from "@/components/medications/medication-card-header"; import { Button } from "@/components/ui/button"; import { Card, CardContent } from "@/components/ui/card"; import { EmptyState } from "@/components/ui/empty-state"; import { QueryErrorCard } from "@/components/ui/query-error-card"; import { Skeleton } from "@/components/ui/skeleton"; import { apiGet } from "@/lib/api/api-fetch"; import { formatDate } from "@/lib/format"; import { formatReferenceRange } from "@/lib/labs/reference-range"; import { formatLabReading, formatLabValue } from "@/lib/labs/format-value"; import { useTranslations } from "@/lib/i18n/context"; import { cn } from "@/lib/utils"; import { queryKeys } from "@/lib/query-keys"; import { applyOrder, useModuleListPrefs } from "@/lib/module-list-prefs"; import { LabTrendSparkline } from "./lab-trend-sparkline"; import { LabReferenceRangeBar } from "./lab-reference-range-bar"; import { ReferenceRangeBadge } from "./reference-range-badge"; import { SourceRangeNote } from "./source-range-note"; import type { LabResultDto, LabResultListResponse } from "./types"; interface MarkerGroup { /** Stable group key: the biomarker id, or `analyte:` for legacy rows. */ key: string; /** Link target when the group is catalog-linked; null for legacy rows. */ biomarkerId: string | null; analyte: string; panel: string | null; unit: string; readings: LabResultDto[]; latest: LabResultDto; } /** * Group readings by their linked biomarker (or, for legacy un-linked rows, * case-insensitively by analyte). A catalog-linked group deep-links to its * detail chart; legacy groups render inert until the backfill links them. */ function groupReadings(results: LabResultDto[]): MarkerGroup[] { const byKey = new Map(); for (const r of results) { const key = r.biomarkerId ? `bm:${r.biomarkerId}` : `analyte:${r.analyte.toLowerCase()}`; const bucket = byKey.get(key); if (bucket) bucket.push(r); else byKey.set(key, [r]); } const groups: MarkerGroup[] = []; for (const [key, readings] of byKey.entries()) { const ordered = [...readings].sort( (a, b) => new Date(a.takenAt).getTime() - new Date(b.takenAt).getTime(), ); const latest = ordered[ordered.length - 1]; groups.push({ key, biomarkerId: latest.biomarkerId, analyte: latest.analyte, panel: latest.panel, unit: latest.unit, readings: ordered, latest, }); } return groups.sort( (a, b) => new Date(b.latest.takenAt).getTime() - new Date(a.latest.takenAt).getTime(), ); } function LabRangeBarSlot({ reading }: { reading: LabResultDto }) { return (
); } /** * The compact list is a five-column table from `lg` up: name and reading, range * badge, range bar, trend, chevron. Below that the same five cells fold into * two lines per row, because the fixed columns alone (badge + 12rem bar + 72px * trend + gaps) are wider than a phone, and the only flexible column — the * name — was the one that gave way: it collapsed to nothing and the row * panned sideways off the card. * * Phone layout, per row: * * name / reading · date badge › * range bar trend * * The placement classes are all `max-lg:` so the desktop table keeps exactly * the subgrid it had. */ const ROW_CLASS = "grid min-w-0 grid-cols-[minmax(0,1fr)_auto_auto] items-center gap-x-3 gap-y-2 px-4 py-2.5 lg:col-span-full lg:grid-cols-subgrid lg:gap-y-0"; const MOBILE_CELL = { reading: "max-lg:col-start-1 max-lg:row-start-1", badge: "max-lg:col-start-2 max-lg:row-start-1 max-lg:justify-self-end", rangeBar: "max-lg:col-start-1 max-lg:row-start-2 max-lg:empty:hidden", trend: "max-lg:col-start-2 max-lg:row-start-2 max-lg:justify-self-end max-lg:empty:hidden", end: "max-lg:col-start-3 max-lg:row-start-1", notLinked: "max-lg:col-span-full max-lg:row-start-3", } as const; export function LabList({ onAddFirst }: { onAddFirst?: () => void } = {}) { const { t } = useTranslations(); const { canWriteDomain } = useRecordCapabilities(); const canAddLab = canWriteDomain("labs"); const { prefs } = useModuleListPrefs("labs"); // v1.22 — a short, factual line under each marker heading describing what the // biomarker measures, sourced from the catalog via i18n. Free-text markers // (no catalog match) carry no subtitle rather than a fabricated one. // v1.24 — the per-marker description moved to the biomarker detail page // (beneath the heading); the overview rows no longer carry it. const listKey = queryKeys.labResultsList({ biomarkerId: undefined, analyte: undefined, panel: undefined, from: undefined, to: undefined, page: 0, sortDir: "desc", }); const { data, isLoading, isError, refetch } = useQuery({ queryKey: listKey, queryFn: () => apiGet("/api/labs?limit=500&sortDir=desc"), }); const groups = useMemo(() => { const base = groupReadings(data?.results ?? []); // v1.18.6 (MOD-04) — honour the user's Labs sort choice. `groupReadings` // already returns most-recent-first; `recentAsc` reverses, the alpha // options sort by analyte name (#43), and `manual` applies the persisted // biomarker order (legacy un-linked groups, which carry no biomarkerId, // sort after the ordered block). if (prefs.sortDir === "recentAsc") return [...base].reverse(); if (prefs.sortDir === "alphaAsc" || prefs.sortDir === "alphaDesc") { const dir = prefs.sortDir === "alphaAsc" ? 1 : -1; return [...base].sort( (a, b) => dir * a.analyte.localeCompare(b.analyte, undefined, { sensitivity: "base", }), ); } if (prefs.sortDir === "manual") { return applyOrder(base, prefs.order, (g) => g.biomarkerId ?? g.key); } return base; }, [data?.results, prefs.sortDir, prefs.order]); // The list caps at 500 rows server-side (the `limit` ceiling). Surface a // calm "showing latest N of M" hint when the cap truncates so the count is // never silently wrong — proper cursor paging is a later iteration. const total = data?.meta?.total ?? 0; const shown = data?.results?.length ?? 0; const truncated = total > shown; if (isLoading) { return (
{Array.from({ length: 3 }, (_, i) => ( ))}
); } if (isError) { // A read failure is NOT an empty list — surface the error + Retry so an // outage never reads as "you have no lab results". return ( void refetch()} /> ); } if (groups.length === 0) { return ( } title={t("labs.emptyTitle")} description={t("labs.emptyDescription")} action={ onAddFirst && canAddLab ? ( ) : undefined } /> ); } // v1.18.10 (#3) — delete lives ONLY on the value detail view (next to Edit), // not on these overview rows. The list/tile rows navigate; the trash icon was // removed here so a stray tap can't delete a biomarker from the overview. // v1.18.6 (MOD-03) — compact list view: one bordered card holding tight // divided rows instead of a card per biomarker. This is the default view // (#40); the card/tile view is the alternative the settings toggle selects. if (prefs.view === "list") { return ( // `lab-list` marks the read results in both view shapes. The loading // branch above carries `lab-list-loading` instead, so the marker // cannot stand for a silhouette.
{truncated ? (

{t("labs.showingLatestOf", { shown, total })}

) : null} {groups.map((group) => { const inner = (
{group.analyte}
{formatLabReading(group.latest)} {formatDate(group.latest.takenAt)}
); // The whole row navigates into the detail (where delete lives). return group.biomarkerId ? ( {inner}
reading.value)} referenceLow={group.latest.referenceLow} referenceHigh={group.latest.referenceHigh} />
) : ( // Un-linked group (not backfilled to a catalog biomarker): // render inert but say so, so it doesn't read as a broken // link next to its clickable neighbours.
{inner}
reading.value)} referenceLow={group.latest.referenceLow} referenceHigh={group.latest.referenceHigh} />
{t("labs.notLinkedYet")}
); })}
); } // v1.18.9 (#40) — card/tile view. The tile reuses the medication module's // `MedicationCardHeader` so a lab tile reads identically to a medication or // Vorsorge tile side-by-side: name on line 1, the reference-range badge as // the line-1 chip, the panel as the category badge. v1.18.10 (#3) — no delete // control on the tile; the trash icon lives only on the value detail view. return (
    1 && "sm:grid-cols-2", )} > {truncated ? (
  • {t("labs.showingLatestOf", { shown, total })}

  • ) : null} {groups.map((group) => { return (
  • } href={ group.biomarkerId ? `/labs/${group.biomarkerId}` : undefined } linkLabel={group.analyte} />
    {formatLabReading(group.latest)} {group.latest.value !== null && (group.latest.referenceLow !== null || group.latest.referenceHigh !== null) ? ( {t("labs.referenceLabel")}{" "} {formatReferenceRange( group.latest.referenceLow, group.latest.referenceHigh, formatLabValue, )} ) : null} {formatDate(group.latest.takenAt)} {group.readings.length > 1 ? ( {t("labs.readingsCount", { count: group.readings.length, })} ) : null}
    reading.value)} referenceLow={group.latest.referenceLow} referenceHigh={group.latest.referenceHigh} />
    {/* Un-linked group: the header renders no link, so name the reason rather than leaving a card that silently does nothing on tap. */} {!group.biomarkerId ? (

    {t("labs.notLinkedYet")}

    ) : null}
  • ); })}
); }