From 89d51c5380ddd5fa22ae3aa8f4ae8f87ed8bbd92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Fri, 5 Jun 2026 10:37:25 +0200 Subject: [PATCH 1/4] =?UTF-8?q?refactor(insights):=20tighten=20the=20mood?= =?UTF-8?q?=20page=20=E2=80=94=20consolidate=20subtexts,=20icon-ify=20expl?= =?UTF-8?q?ainers,=20unify=20palette?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Lay the narrative takeaways two-up instead of a single full-width column so short one-liners (best daypart, logging streak, weekday peak) stop stacking into a long ladder of half-empty rows. Fold the low-density footnotes behind a focusable ring/info explainer icon with a tooltip: the per-pair paired-day/r/q stat under each discovered relation, the per-card paired-day/r line under each mood-correlation scatter, and the false-discovery footer + observational disclaimer that sat as two full-width rows under the discovered-relations list. The trigger is a real button carrying an aria-label so the explanation is keyboard- and screen-reader-reachable, not hover-only. Charts stay Recharts and visually identical — the mood distribution and mood-by-time-of-day charts already share one Dracula band palette (red/orange/yellow/green over the same thresholds, --dracula-fg ticks, --dracula-comment axes, --card/--border tooltips), so the surface palette is already consistent and left untouched. New explainer keys land in all six locales. (cherry picked from commit afc38491ebfae3beed6476a79439d2b87f33f823) --- messages/de.json | 7 ++- messages/en.json | 5 +- messages/es.json | 7 ++- messages/fr.json | 7 ++- messages/it.json | 7 ++- messages/pl.json | 7 ++- .../mood-discovered-relations.test.tsx | 24 +++++--- .../insights/mood/mood-correlation-cards.tsx | 25 ++++++--- .../mood/mood-discovered-relations.tsx | 50 ++++++++++------- .../insights/mood/mood-explainer-icon.tsx | 55 +++++++++++++++++++ .../insights/mood/mood-narrative-feed.tsx | 8 ++- 11 files changed, 153 insertions(+), 49 deletions(-) create mode 100644 src/components/insights/mood/mood-explainer-icon.tsx diff --git a/messages/de.json b/messages/de.json index 86fcb9031..f63ed1c59 100644 --- a/messages/de.json +++ b/messages/de.json @@ -2558,7 +2558,8 @@ "weightTitle": "Stimmung vs. Gewicht", "bloodPressureTitle": "Stimmung vs. Blutdruck", "weightAxis": "Gewicht", - "bloodPressureAxis": "Systolisch (mmHg)" + "bloodPressureAxis": "Systolisch (mmHg)", + "sourceLabel": "Wie das berechnet wurde" }, "structuredTagsTitle": "Tag-Auswertung", "inTargetValue": "{pct} %", @@ -2629,7 +2630,9 @@ "moodDown": "Höheres {factor} geht in deinen Daten tendenziell mit schlechterer Stimmung am Folgetag einher.", "outcomeUp": "Bessere Stimmung geht in deinen Daten tendenziell mit höherem {factor} am Folgetag einher.", "outcomeDown": "Bessere Stimmung geht in deinen Daten tendenziell mit niedrigerem {factor} am Folgetag einher.", - "stat": "{n} gepaarte Tage · r = {r} · q = {q}" + "stat": "{n} gepaarte Tage · r = {r} · q = {q}", + "statLabel": "Wie das berechnet wurde", + "explainerLabel": "Wie das berechnet wurde" } }, "derived": { diff --git a/messages/en.json b/messages/en.json index 5d4da4ca3..9b74a7ae0 100644 --- a/messages/en.json +++ b/messages/en.json @@ -2553,6 +2553,7 @@ "strengthWeak": "Weak", "strengthNone": "None", "source": "{n} paired days · r = {r}", + "sourceLabel": "How this was computed", "emptyTitle": "Not enough paired data yet", "emptyDescription": "Log mood and this metric on the same days to see a correlation.", "weightTitle": "Mood vs. weight", @@ -2629,7 +2630,9 @@ "moodDown": "Higher {factor} tends to go with lower next-day mood in your data.", "outcomeUp": "Higher mood tends to go with higher next-day {factor} in your data.", "outcomeDown": "Higher mood tends to go with lower next-day {factor} in your data.", - "stat": "{n} paired days · r = {r} · q = {q}" + "stat": "{n} paired days · r = {r} · q = {q}", + "statLabel": "How this was computed", + "explainerLabel": "How this was computed" } }, "derived": { diff --git a/messages/es.json b/messages/es.json index 81c68c037..b71f2d98d 100644 --- a/messages/es.json +++ b/messages/es.json @@ -2558,7 +2558,8 @@ "weightTitle": "Ánimo vs. peso", "bloodPressureTitle": "Ánimo vs. presión arterial", "weightAxis": "Peso", - "bloodPressureAxis": "Sistólica (mmHg)" + "bloodPressureAxis": "Sistólica (mmHg)", + "sourceLabel": "Cómo se calculó esto" }, "structuredTagsTitle": "Desglose de etiquetas", "inTargetValue": "{pct} %", @@ -2629,7 +2630,9 @@ "moodDown": "Un mayor {factor} suele coincidir con peor ánimo al día siguiente en tus datos.", "outcomeUp": "Mejor ánimo suele coincidir con un {factor} más alto al día siguiente en tus datos.", "outcomeDown": "Mejor ánimo suele coincidir con un {factor} más bajo al día siguiente en tus datos.", - "stat": "{n} días emparejados · r = {r} · q = {q}" + "stat": "{n} días emparejados · r = {r} · q = {q}", + "statLabel": "Cómo se calculó esto", + "explainerLabel": "Cómo se calculó esto" } }, "derived": { diff --git a/messages/fr.json b/messages/fr.json index db919b66c..ae2827a11 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -2558,7 +2558,8 @@ "weightTitle": "Humeur vs. poids", "bloodPressureTitle": "Humeur vs. tension artérielle", "weightAxis": "Poids", - "bloodPressureAxis": "Systolique (mmHg)" + "bloodPressureAxis": "Systolique (mmHg)", + "sourceLabel": "Comment ceci est calculé" }, "structuredTagsTitle": "Répartition des étiquettes", "inTargetValue": "{pct} %", @@ -2629,7 +2630,9 @@ "moodDown": "Un {factor} plus élevé tend à coïncider avec une moins bonne humeur le lendemain dans vos données.", "outcomeUp": "Une meilleure humeur tend à coïncider avec un {factor} plus élevé le lendemain dans vos données.", "outcomeDown": "Une meilleure humeur tend à coïncider avec un {factor} plus bas le lendemain dans vos données.", - "stat": "{n} jours appariés · r = {r} · q = {q}" + "stat": "{n} jours appariés · r = {r} · q = {q}", + "statLabel": "Comment ceci est calculé", + "explainerLabel": "Comment ceci est calculé" } }, "derived": { diff --git a/messages/it.json b/messages/it.json index e50b0f5f8..6ede77c17 100644 --- a/messages/it.json +++ b/messages/it.json @@ -2558,7 +2558,8 @@ "weightTitle": "Umore vs. peso", "bloodPressureTitle": "Umore vs. pressione sanguigna", "weightAxis": "Peso", - "bloodPressureAxis": "Sistolica (mmHg)" + "bloodPressureAxis": "Sistolica (mmHg)", + "sourceLabel": "Come è stato calcolato" }, "structuredTagsTitle": "Analisi etichette", "inTargetValue": "{pct} %", @@ -2629,7 +2630,9 @@ "moodDown": "Un {factor} più alto tende a coincidere con un umore peggiore il giorno dopo nei tuoi dati.", "outcomeUp": "Un umore migliore tende a coincidere con un {factor} più alto il giorno dopo nei tuoi dati.", "outcomeDown": "Un umore migliore tende a coincidere con un {factor} più basso il giorno dopo nei tuoi dati.", - "stat": "{n} giorni appaiati · r = {r} · q = {q}" + "stat": "{n} giorni appaiati · r = {r} · q = {q}", + "statLabel": "Come è stato calcolato", + "explainerLabel": "Come è stato calcolato" } }, "derived": { diff --git a/messages/pl.json b/messages/pl.json index 647ee2e35..5153f4a78 100644 --- a/messages/pl.json +++ b/messages/pl.json @@ -2558,7 +2558,8 @@ "weightTitle": "Nastrój vs. waga", "bloodPressureTitle": "Nastrój vs. ciśnienie krwi", "weightAxis": "Waga", - "bloodPressureAxis": "Skurczowe (mmHg)" + "bloodPressureAxis": "Skurczowe (mmHg)", + "sourceLabel": "Jak to obliczono" }, "structuredTagsTitle": "Podział tagów", "inTargetValue": "{pct}%", @@ -2629,7 +2630,9 @@ "moodDown": "Wyższy {factor} zwykle wiąże się z gorszym nastrojem następnego dnia w Twoich danych.", "outcomeUp": "Lepszy nastrój zwykle wiąże się z wyższym {factor} następnego dnia w Twoich danych.", "outcomeDown": "Lepszy nastrój zwykle wiąże się z niższym {factor} następnego dnia w Twoich danych.", - "stat": "{n} sparowanych dni · r = {r} · q = {q}" + "stat": "{n} sparowanych dni · r = {r} · q = {q}", + "statLabel": "Jak to obliczono", + "explainerLabel": "Jak to obliczono" } }, "derived": { diff --git a/src/components/insights/mood/__tests__/mood-discovered-relations.test.tsx b/src/components/insights/mood/__tests__/mood-discovered-relations.test.tsx index 05ea3957e..204510baa 100644 --- a/src/components/insights/mood/__tests__/mood-discovered-relations.test.tsx +++ b/src/components/insights/mood/__tests__/mood-discovered-relations.test.tsx @@ -96,9 +96,11 @@ describe("", () => { // factor label resolves to the localized measurement name expect(html).toContain("Time in Daylight"); expect(html).toContain("higher next-day mood"); - // stat line carries n, r, q - expect(html).toContain("r = 0.50"); - expect(html).toContain("q = 0.020"); + // v1.12.4 (C4) — the n/r/q detail moved off the visible sub-row into a + // focusable explainer icon (its tooltip content is portalled on open, so + // it is absent from the static markup). Assert the icon is wired per pair + // instead of the inline stat string. + expect(html).toContain('aria-label="How this was computed"'); }); it("phrases a mood → next-day outcome pair", () => { @@ -111,7 +113,7 @@ describe("", () => { expect(html).toContain("lower next-day"); }); - it("filters to mood pairs and shows the honest full-family footer", () => { + it("filters to mood pairs and folds the full-family footer into the header explainer", () => { const html = renderWith( [ pair({ behaviour: "TIME_IN_DAYLIGHT", outcome: "MOOD" }), @@ -122,8 +124,16 @@ describe("", () => { expect((html.match(/data-slot="mood-discovered-pair"/g) ?? []).length).toBe( 1, ); - // Footer's denominator is the full behaviour×outcome family the engine - // tested, not the mood-only subset — so it must report 12, not 1 of 1. - expect(html).toContain("from 12 day-to-day pairs"); + // v1.12.4 (C3) — the false-discovery footer (denominator = the full + // behaviour×outcome family the engine tested, i.e. 12, not the mood-only + // subset) + the observational disclaimer were two full-width footnote + // rows; both fold into a single header explainer icon now. Its tooltip + // content is portalled on open, so assert the trigger exists rather than + // the (now hidden) footer string. + expect( + (html.match(/aria-label="How this was computed"/g) ?? []).length, + ).toBeGreaterThanOrEqual(1); + // The two old inline footnote rows are gone from the static markup. + expect(html).not.toContain("day-to-day pairs tested"); }); }); diff --git a/src/components/insights/mood/mood-correlation-cards.tsx b/src/components/insights/mood/mood-correlation-cards.tsx index 1f5983161..f0366ff3a 100644 --- a/src/components/insights/mood/mood-correlation-cards.tsx +++ b/src/components/insights/mood/mood-correlation-cards.tsx @@ -8,6 +8,7 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { EmptyState } from "@/components/ui/empty-state"; import { useTranslations } from "@/lib/i18n/context"; import type { CorrelationResult } from "@/lib/analytics/correlations"; +import { MoodExplainerIcon } from "./mood-explainer-icon"; /** * v1.8.5 — mood × metric correlation cards (Apple "Life Factors" parity). @@ -96,9 +97,21 @@ function MoodCorrelationCard({ {t(TITLE_KEY[kind])} {hasResult && data.result && ( - - {t(STRENGTH_KEY[data.result.strength])} - +
+ + {t(STRENGTH_KEY[data.result.strength])} + + {/* v1.12.4 (C4) — the "{n} paired days · r" line sat under the + scatter as a half-empty row. Move it into an explainer icon + in the header so the card footprint stays tight. */} + +
)} @@ -117,12 +130,6 @@ function MoodCorrelationCard({ yAxis={{ dataKey: "y", name: t(Y_LABEL_KEY[kind]) }} height={180} /> -

- {t("insights.mood.correlation.source", { - n: data.n, - r: data.result.r.toFixed(2), - })} -

) : ( -

- {t("insights.mood.discovery.title")} -

+
+

+ {t("insights.mood.discovery.title")} +

+ {/* v1.12.4 (C3) — the false-discovery footer + observational + disclaimer were two full-width footnote rows. Fold both into a + single explainer icon so the explanation is one hover/focus away + instead of a low-density block under the list. */} + +

{t("insights.mood.discovery.description")}

@@ -108,28 +121,25 @@ export function MoodDiscoveredRelations() { data-mood-role={moodIsOutcome ? "outcome" : "behaviour"} data-direction={up ? "up" : "down"} > - - {t(sentenceKey, { factor: factorLabel })} - - - {t("insights.mood.discovery.stat", { - n: pair.n, - r: pair.r.toFixed(2), - q: pair.qValue.toFixed(3), - })} + {/* v1.12.4 (C4) — the {n} paired days · r · q line was a + low-density sub-row under each sentence. Move the numeric + detail behind an explainer icon on the same line as the + finding so the list stays one row per pair. */} + + {t(sentenceKey, { factor: factorLabel })} + ); })} -

- {t("insights.mood.discovery.footer", { - tested: data.pairsTested, - })} -

-

- {t("insights.mood.discovery.disclaimer")} -

); } diff --git a/src/components/insights/mood/mood-explainer-icon.tsx b/src/components/insights/mood/mood-explainer-icon.tsx new file mode 100644 index 000000000..8ccc0a35d --- /dev/null +++ b/src/components/insights/mood/mood-explainer-icon.tsx @@ -0,0 +1,55 @@ +"use client"; + +import { Info } from "lucide-react"; + +import { + Tooltip, + TooltipContent, + TooltipProvider, + TooltipTrigger, +} from "@/components/ui/tooltip"; +import { cn } from "@/lib/utils"; + +/** + * v1.12.4 (C3/C4) — compact explainer affordance for the mood surface. + * + * Replaces the low-density inline "how this was computed" text rows + * (paired-day counts, the false-discovery footer, the observational + * disclaimer) with a single ring/info icon. The detail moves into a + * hover/focus tooltip so the surface stops spending a full-width row on a + * footnote. The trigger is a real focusable `button` carrying an + * `aria-label`, so the explanation is reachable by keyboard and screen + * readers — not hover-only. Self-contained `TooltipProvider` so callers + * don't need an ambient one. + */ +export function MoodExplainerIcon({ + label, + detail, + className, +}: { + /** Accessible name for the trigger (what the icon explains). */ + label: string; + /** The explanation shown in the tooltip. */ + detail: string; + className?: string; +}) { + return ( + + + + + + {detail} + + + + ); +} diff --git a/src/components/insights/mood/mood-narrative-feed.tsx b/src/components/insights/mood/mood-narrative-feed.tsx index ce2f2444c..2e53c899d 100644 --- a/src/components/insights/mood/mood-narrative-feed.tsx +++ b/src/components/insights/mood/mood-narrative-feed.tsx @@ -64,8 +64,12 @@ export function MoodNarrativeFeed({ items }: { items: MoodNarrativeItem[] }) { if (items.length === 0) return null; return ( + // v1.12.4 (C2) — the takeaways are short one-liners, so a single + // full-width column wasted horizontal space and stacked into a long + // ladder. Lay them two-up on anything wider than a phone; a lone + // takeaway still spans the row rather than orphaning half of it.
    @@ -82,7 +86,7 @@ export function MoodNarrativeFeed({ items }: { items: MoodNarrativeItem[] }) { return (
  • From 9cf2b3086a4f3487b5a25bad9951afe486c7b237 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Fri, 5 Jun 2026 10:40:44 +0200 Subject: [PATCH 2/4] feat(insights): reorder the overview, fix briefing legibility and steps link, trim the coach prompts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reorder the Insights overview top → bottom to Hero + Coach, Wellnesswerte, Vitalwerte, Trends, period retrospective, then today's signals — the wellness-score strip and vitals grid already render in that sequence inside the vitals dashboard, so the change is the surrounding section order plus moving the signal cards below the retrospective. Make the steps reference value in the daily briefing tappable: it was the one key finding with no destination, so it now routes to the generic readings view for its measurement type like every other metric drills in. Paint the health-score headline number through the semantic success / warning / destructive tokens instead of the raw dracula primitives, which carry no light-mode override and read illegibly on the Alucard light theme. Widen the wellness-score strip so the tiles always fill the row: the fixed five-column desktop track left an empty cell on the common four-score case and read as a missing tile. Drop the duplicate footer "prepare assessments" control — the tab-strip regenerate button is the single affordance — and remove the now-dead warm hook and its strings. Trim the coach suggested prompts to the two that read as a clear next step (ask the doctor, is the medication working) and remove the three speculative data-specific openers, across all six locales. (cherry picked from commit e819c9c12777f76b66b5b466b8d159b26f169868) --- messages/de.json | 5 -- messages/en.json | 5 -- messages/es.json | 5 -- messages/fr.json | 5 -- messages/it.json | 5 -- messages/pl.json | 5 -- src/app/insights/page.tsx | 61 ++++++----------- .../__tests__/health-score-card.test.tsx | 9 +-- .../insights/__tests__/hero-strip.test.tsx | 2 +- .../__tests__/suggested-prompts.test.tsx | 23 ++++--- src/components/insights/daily-briefing.tsx | 7 +- .../insights/derived/wellness-scores.tsx | 16 ++++- src/components/insights/health-score-card.tsx | 12 +++- src/components/insights/suggested-prompts.tsx | 16 ++--- src/components/insights/use-insights-warm.ts | 67 ------------------- 15 files changed, 75 insertions(+), 168 deletions(-) delete mode 100644 src/components/insights/use-insights-warm.ts diff --git a/messages/de.json b/messages/de.json index f63ed1c59..73279398e 100644 --- a/messages/de.json +++ b/messages/de.json @@ -1592,8 +1592,6 @@ "heroRegenerating": "Wird generiert", "regenerateAnalysis": "Einschätzung neu erstellen", "regenerateSuccess": "Einschätzung wurde neu erstellt", - "warmAssessments": "Einschätzungen vorbereiten", - "warmAssessmentsHint": "Einschätzungen werden über Nacht automatisch aktualisiert. Bereite sie jetzt vor, um den neuesten Stand zu sehen.", "warmStarted": "Einschätzungen werden im Hintergrund erstellt", "narrativeTitle": "Dein Zeitraum im Rückblick", "narrativeWeek": "Diese Woche", @@ -1647,9 +1645,6 @@ }, "suggestedPrompts": { "label": "Frag mich", - "whyMonday": "Warum war der Blutdruck am Montag höher?", - "weightVsPulse": "Wie hat sich die Gewichtsabnahme auf meinen Puls ausgewirkt?", - "weekVsMonth": "Vergleich diese Woche mit letztem Monat", "tellMyDoctor": "Was sollte ich meinem Arzt sagen?", "medicationWorking": "Wirkt mein Medikament?" }, diff --git a/messages/en.json b/messages/en.json index 9b74a7ae0..ff734fe34 100644 --- a/messages/en.json +++ b/messages/en.json @@ -1592,8 +1592,6 @@ "heroRegenerating": "Regenerating", "regenerateAnalysis": "Re-run assessment", "regenerateSuccess": "Assessment refreshed", - "warmAssessments": "Prepare assessments", - "warmAssessmentsHint": "Assessments refresh overnight automatically. Prepare them now to read the latest.", "warmStarted": "Assessments are being prepared in the background", "narrativeTitle": "Your period in review", "narrativeWeek": "This week", @@ -1647,9 +1645,6 @@ }, "suggestedPrompts": { "label": "Try asking", - "whyMonday": "Why was BP higher on Monday?", - "weightVsPulse": "How did weight loss affect my pulse?", - "weekVsMonth": "Compare this week to last month", "tellMyDoctor": "What should I tell my doctor?", "medicationWorking": "Is my medication working?" }, diff --git a/messages/es.json b/messages/es.json index b71f2d98d..4d6f06a78 100644 --- a/messages/es.json +++ b/messages/es.json @@ -1592,8 +1592,6 @@ "heroRegenerating": "Generando", "regenerateAnalysis": "Volver a generar la valoración", "regenerateSuccess": "Valoración regenerada", - "warmAssessments": "Preparar valoraciones", - "warmAssessmentsHint": "Las valoraciones se actualizan automáticamente durante la noche. Prepáralas ahora para ver lo más reciente.", "warmStarted": "Las valoraciones se están preparando en segundo plano", "narrativeTitle": "Tu período en resumen", "narrativeWeek": "Esta semana", @@ -1647,9 +1645,6 @@ }, "suggestedPrompts": { "label": "Pregúntame", - "whyMonday": "¿Por qué fue más alta mi tensión el lunes?", - "weightVsPulse": "¿Cómo ha afectado la pérdida de peso a mi pulso?", - "weekVsMonth": "Compara esta semana con el mes pasado", "tellMyDoctor": "¿Qué debería contarle a mi médico?", "medicationWorking": "¿Está funcionando mi medicamento?" }, diff --git a/messages/fr.json b/messages/fr.json index ae2827a11..13c542728 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -1592,8 +1592,6 @@ "heroRegenerating": "Génération en cours", "regenerateAnalysis": "Relancer l’évaluation", "regenerateSuccess": "Évaluation regénérée", - "warmAssessments": "Préparer les évaluations", - "warmAssessmentsHint": "Les évaluations sont actualisées automatiquement pendant la nuit. Préparez-les maintenant pour voir les dernières données.", "warmStarted": "Les évaluations sont en cours de préparation en arrière-plan", "narrativeTitle": "Votre période en revue", "narrativeWeek": "Cette semaine", @@ -1647,9 +1645,6 @@ }, "suggestedPrompts": { "label": "Demande-moi", - "whyMonday": "Pourquoi ma tension était-elle plus haute lundi ?", - "weightVsPulse": "Comment la perte de poids a-t-elle influé sur mon pouls ?", - "weekVsMonth": "Compare cette semaine avec le mois dernier", "tellMyDoctor": "Que devrais-je dire à mon médecin ?", "medicationWorking": "Mon médicament fonctionne-t-il ?" }, diff --git a/messages/it.json b/messages/it.json index 6ede77c17..5245295ef 100644 --- a/messages/it.json +++ b/messages/it.json @@ -1592,8 +1592,6 @@ "heroRegenerating": "Generazione in corso", "regenerateAnalysis": "Rigenera la valutazione", "regenerateSuccess": "Valutazione rigenerata", - "warmAssessments": "Prepara le valutazioni", - "warmAssessmentsHint": "Le valutazioni si aggiornano automaticamente durante la notte. Preparale ora per vedere i dati più recenti.", "warmStarted": "Le valutazioni vengono preparate in background", "narrativeTitle": "Il tuo periodo in sintesi", "narrativeWeek": "Questa settimana", @@ -1647,9 +1645,6 @@ }, "suggestedPrompts": { "label": "Chiedimi", - "whyMonday": "Perché la mia pressione era più alta lunedì?", - "weightVsPulse": "Come ha inciso il calo di peso sulle mie pulsazioni?", - "weekVsMonth": "Confronta questa settimana con il mese scorso", "tellMyDoctor": "Cosa dovrei dire al mio medico?", "medicationWorking": "Il mio farmaco sta funzionando?" }, diff --git a/messages/pl.json b/messages/pl.json index 5153f4a78..d4b5efcff 100644 --- a/messages/pl.json +++ b/messages/pl.json @@ -1592,8 +1592,6 @@ "heroRegenerating": "Generowanie", "regenerateAnalysis": "Uruchom ocenę ponownie", "regenerateSuccess": "Ocena wygenerowana ponownie", - "warmAssessments": "Przygotuj oceny", - "warmAssessmentsHint": "Oceny odświeżają się automatycznie w nocy. Przygotuj je teraz, aby zobaczyć najnowsze dane.", "warmStarted": "Oceny są przygotowywane w tle", "narrativeTitle": "Twój okres w skrócie", "narrativeWeek": "Ten tydzień", @@ -1647,9 +1645,6 @@ }, "suggestedPrompts": { "label": "Zapytaj mnie", - "whyMonday": "Dlaczego moje ciśnienie było wyższe w poniedziałek?", - "weightVsPulse": "Jak spadek wagi wpłynął na moje tętno?", - "weekVsMonth": "Porównaj ten tydzień z poprzednim miesiącem", "tellMyDoctor": "Co powinienem powiedzieć lekarzowi?", "medicationWorking": "Czy mój lek działa?" }, diff --git a/src/app/insights/page.tsx b/src/app/insights/page.tsx index 435c053a2..a98cfe275 100644 --- a/src/app/insights/page.tsx +++ b/src/app/insights/page.tsx @@ -3,7 +3,7 @@ import { useQuery } from "@tanstack/react-query"; import dynamic from "next/dynamic"; import Link from "next/link"; -import { TrendingUp, Sparkles } from "lucide-react"; +import { TrendingUp } from "lucide-react"; import { useAuth } from "@/hooks/use-auth"; import { queryKeys } from "@/lib/query-keys"; @@ -16,7 +16,6 @@ import { Skeleton } from "@/components/ui/skeleton"; import { cn } from "@/lib/utils"; import { HeroStrip } from "@/components/insights/hero-strip"; import { useInsightsAdvisorQuery } from "@/components/insights/use-insights-advisor"; -import { useInsightsWarm } from "@/components/insights/use-insights-warm"; import { useCoachLaunch } from "@/lib/insights/coach-launch-context"; import { useAnalyticsQuery } from "@/lib/queries/use-analytics-query"; // v1.4.41 W-ORG — shared shape lives in `src/types/analytics.ts` as @@ -225,13 +224,6 @@ export default function InsightsPage() { const analyticsQuery = useAnalyticsQuery(); const analytics = analyticsQuery.data as AnalyticsData | undefined; - // The "prepare assessments" button below re-warms every assessment on - // demand. There is no warm-on-mount: the nightly cron (04:30) keeps the - // caches warm and the per-metric status GETs revalidate gently on their - // own (stale-while-revalidate), so opening the overview only reads cached - // text — it never fans out a full provider warm on a page visit. - const { warm, isWarming } = useInsightsWarm(); - // Empty-state shortcut — only paint once the comprehensive query has // resolved AND reported zero measurements. While it's in-flight we // fall through to the streamed shell so the user gets the hero + @@ -273,15 +265,22 @@ export default function InsightsPage() { // server children would require a Server-Component refactor; that's // a v1.5.x track. - // v1.12.0 — section order mirrors the iOS Insights overview - // (`v0.14` app-structure handover §2c): Coach hero + briefing + chips - // (the HeroStrip bundles all three) → detailed "Heute auf einen Blick" - // briefing → dynamics / alerts zone (today's signal + rhythm events, - // out of the AI gate so a health alert is never hidden) → vitals - // dashboard → trends row → "Zeitraum im Rückblick" retrospective → - // footer (the warm-assessments utility control, no iOS equivalent — - // iOS auto-warms). The per-metric correlation cards moved onto the - // metric pages, so the overview renders no correlation row. + // v1.12.4 — overview section order, top → bottom: + // 1. "Guten Morgen" Hero + Coach questions (HeroStrip) + the detailed + // "Heute auf einen Blick" briefing right below it (same briefing + // cluster, stays at the top). + // 2. Wellnesswerte ┐ both live inside , which renders + // 3. Vitalwerte ┘ the wellness-score strip first, then the vitals + // grid — so a single mount already gives the 2 → 3 sequence. + // 4. Trends (TrendsRow). + // 5. "Dein Zeitraum im Rückblick" retrospective (PeriodNarrativeCard). + // 6. "Signale des Tages" — today's signal (CoincidentDeviationCard) plus + // the rhythm-events alert timeline, kept out of the AI gate so a + // health alert is never hidden. + // The per-metric correlation cards moved onto the metric pages, so the + // overview renders no correlation row. The duplicate footer "prepare + // assessments" control was removed in v1.12.4 — the tab-strip regenerate + // button is the single affordance. return (

    )} - - - - } - {/* v1.11.3 — anchor the warm-assessments control. It used to float - right-aligned with no label, reading as an orphan affordance. The - left-aligned caption explains the nightly-refresh model and gives the - button context. */} -
    -

    - {t("insights.warmAssessmentsHint")} -

    - -
    + + +
    ); } diff --git a/src/components/insights/__tests__/health-score-card.test.tsx b/src/components/insights/__tests__/health-score-card.test.tsx index 25209ebe4..c6f3b7158 100644 --- a/src/components/insights/__tests__/health-score-card.test.tsx +++ b/src/components/insights/__tests__/health-score-card.test.tsx @@ -55,8 +55,9 @@ describe("", () => { expect(html).toMatch(/data-slot="health-score-card-number"/); expect(html).toContain(">86<"); expect(html).toContain("/ 100"); - // Green band uses the dracula-green token. - expect(html).toContain("text-dracula-green"); + // v1.12.4 — the headline number paints through the semantic `--success` + // token (AA-safe on both themes) rather than the raw dracula primitive. + expect(html).toContain("text-success"); }); it("paints the yellow band correctly", () => { @@ -69,7 +70,7 @@ describe("", () => { />, ); expect(html).toMatch(/data-band="yellow"/); - expect(html).toContain("text-dracula-orange"); + expect(html).toContain("text-warning"); }); it("paints the red band correctly", () => { @@ -82,7 +83,7 @@ describe("", () => { />, ); expect(html).toMatch(/data-band="red"/); - expect(html).toContain("text-dracula-red"); + expect(html).toContain("text-destructive"); }); it("renders the unavailable-delta caption when delta is null", () => { diff --git a/src/components/insights/__tests__/hero-strip.test.tsx b/src/components/insights/__tests__/hero-strip.test.tsx index 5e4261850..b0d4009d1 100644 --- a/src/components/insights/__tests__/hero-strip.test.tsx +++ b/src/components/insights/__tests__/hero-strip.test.tsx @@ -157,7 +157,7 @@ describe("", () => { expect(html).toMatch(/data-slot="insights-hero-strip-prompts"/); expect(html).toMatch(/data-slot="insights-suggested-prompts"/); expect(html).toContain("Try asking"); - expect(html).toContain("Why was BP higher on Monday?"); + expect(html).toContain("What should I tell my doctor?"); }); it("forwards onPickPrompt down to the prompt strip without throwing", () => { diff --git a/src/components/insights/__tests__/suggested-prompts.test.tsx b/src/components/insights/__tests__/suggested-prompts.test.tsx index 47951a3e8..6ada6debc 100644 --- a/src/components/insights/__tests__/suggested-prompts.test.tsx +++ b/src/components/insights/__tests__/suggested-prompts.test.tsx @@ -7,7 +7,7 @@ import { SuggestedPrompts } from "../suggested-prompts"; * v1.4.20 phase B1 — "Try asking" prompt-chip strip. * * Renders a horizontal row of clickable prompts below the hero action - * band. Tests cover: default 5-chip rendering, custom prompt list, + * band. Tests cover: default two-chip rendering, custom prompt list, * onPick wiring, locale-aware label. */ @@ -18,20 +18,21 @@ function render(node: React.ReactNode, locale: "en" | "de" = "en") { } describe("", () => { - it("renders the 5 default prompt chips in English", () => { + it("renders the two default prompt chips in English", () => { const html = render( {}} />); - expect(html).toContain("Why was BP higher on Monday?"); - expect(html).toContain("How did weight loss affect my pulse?"); - expect(html).toContain("Compare this week to last month"); expect(html).toContain("What should I tell my doctor?"); expect(html).toContain("Is my medication working?"); + // The speculative data-specific openers were dropped in v1.12.4. + expect(html).not.toContain("Why was BP higher on Monday?"); + expect(html).not.toContain("How did weight loss affect my pulse?"); + expect(html).not.toContain("Compare this week to last month"); }); - it("renders the 5 default prompt chips in German", () => { + it("renders the two default prompt chips in German", () => { const html = render( {}} />, "de"); - expect(html).toContain("Warum war der Blutdruck am Montag höher?"); expect(html).toContain("Wirkt mein Medikament?"); expect(html).toContain("Was sollte ich meinem Arzt sagen?"); + expect(html).not.toContain("Warum war der Blutdruck am Montag höher?"); }); it("renders the 'Try asking' label in English", () => { @@ -49,7 +50,7 @@ describe("", () => { const html = render( {}} />); const matches = html.match(/data-slot="insights-suggested-prompts-chip"/g) ?? []; - expect(matches.length).toBe(5); + expect(matches.length).toBe(2); }); it("accepts a custom prompts array and renders only those", () => { @@ -80,10 +81,10 @@ describe("", () => { // Render to ensure no throw + capture the prompt strings the // component would forward. const html = render(); - expect(html).toContain("Why was BP higher on Monday?"); + expect(html).toContain("What should I tell my doctor?"); // Direct call — SSR can't drive a click; smoke-check the contract. - handler("Why was BP higher on Monday?"); - expect(handler).toHaveBeenCalledWith("Why was BP higher on Monday?"); + handler("What should I tell my doctor?"); + expect(handler).toHaveBeenCalledWith("What should I tell my doctor?"); }); it("forwards a custom className for layout overrides", () => { diff --git a/src/components/insights/daily-briefing.tsx b/src/components/insights/daily-briefing.tsx index a8d391d0d..67eef59ea 100644 --- a/src/components/insights/daily-briefing.tsx +++ b/src/components/insights/daily-briefing.tsx @@ -49,7 +49,12 @@ const METRIC_HREF: Record = { + 1: "lg:grid-cols-1", + 2: "lg:grid-cols-2", + 3: "lg:grid-cols-3", + 4: "lg:grid-cols-4", + 5: "lg:grid-cols-5", + }; + const lgCols = LG_COLS[Math.min(tiles.length, 5)] ?? "lg:grid-cols-5"; + return (
    {tiles}
    diff --git a/src/components/insights/health-score-card.tsx b/src/components/insights/health-score-card.tsx index 54a2e410c..87f5f0985 100644 --- a/src/components/insights/health-score-card.tsx +++ b/src/components/insights/health-score-card.tsx @@ -106,10 +106,16 @@ const SOURCE_PILL_CLASS: Record = { none: "border-muted-foreground/30 text-muted-foreground", }; +// v1.12.4 — the headline score number used the raw `--dracula-*` primitives, +// which carry no light-mode override and render illegibly on the Alucard +// light theme (the band-tokens helper documents the same trap). Route through +// the semantic `--success` / `--warning` / `--destructive` tokens, which both +// themes override to an AA-safe tone — same mapping the wellness-score rings +// already use. const BAND_NUMBER_CLASS: Record = { - green: "text-dracula-green", - yellow: "text-dracula-orange", - red: "text-dracula-red", + green: "text-success", + yellow: "text-warning", + red: "text-destructive", }; const BAND_BORDER_CLASS: Record = { diff --git a/src/components/insights/suggested-prompts.tsx b/src/components/insights/suggested-prompts.tsx index dce24bdb2..5fe2abe2f 100644 --- a/src/components/insights/suggested-prompts.tsx +++ b/src/components/insights/suggested-prompts.tsx @@ -25,7 +25,7 @@ import { cn } from "@/lib/utils"; export interface SuggestedPromptsProps { /** * Override the default prompt list. When omitted, the component - * resolves the 5 defaults from `insights.suggestedPrompts.*`. + * resolves the two defaults from `insights.suggestedPrompts.*`. * Useful for tests + future per-user prompt sets. */ prompts?: string[]; @@ -35,13 +35,11 @@ export interface SuggestedPromptsProps { className?: string; } -const DEFAULT_PROMPT_KEYS = [ - "whyMonday", - "weightVsPulse", - "weekVsMonth", - "tellMyDoctor", - "medicationWorking", -] as const; +// v1.12.4 — trimmed from five speculative prompts to the two that read as a +// clear next step: ask what to tell the doctor, and whether the medication is +// working. The data-specific openers ("why was Monday higher", weight × pulse, +// week vs month) were guesses that did not always match the user's own log. +const DEFAULT_PROMPT_KEYS = ["tellMyDoctor", "medicationWorking"] as const; export function SuggestedPrompts({ prompts, @@ -89,7 +87,7 @@ export function SuggestedPrompts({ data-slot="insights-suggested-prompts-chip" // v1.8.5 W4a — denser chips. The tap target stays comfortable // (`min-h-9` ≈ 36 px, the WCAG/iOS floor) but the horizontal - // padding + type size drop a notch so five prompts pack into + // padding + type size drop a notch so the two prompts pack into // fewer rows and the left column stops towering over the // Health-Score card. className={cn( diff --git a/src/components/insights/use-insights-warm.ts b/src/components/insights/use-insights-warm.ts deleted file mode 100644 index 5120d5052..000000000 --- a/src/components/insights/use-insights-warm.ts +++ /dev/null @@ -1,67 +0,0 @@ -"use client"; - -import { useCallback } from "react"; -import { useMutation } from "@tanstack/react-query"; -import { toast } from "sonner"; - -import { queryKeys } from "@/lib/query-keys"; -import { useTranslations } from "@/lib/i18n/context"; - -/** - * On-demand full assessment warm. - * - * POSTs `/api/insights/pregenerate`, which enqueues a forced warm of every - * AI assessment (comprehensive insight + the seven specialised status cards - * + every data-bearing generic metric assessment) for the calling user on - * the worker and returns immediately. The cards then fill via their existing - * stale-while-revalidate GETs — there is nothing to invalidate here. - * - * This is the explicit "prepare assessments" button only. There is no - * warm-on-mount: the nightly cron (04:30 Europe/Berlin) keeps every user's - * caches warm, and the per-metric status GETs revalidate gently on their - * own — so a page visit reads cached text instead of fanning out a full - * provider warm that would contend with foreground requests. - */ - -async function postWarm(): Promise { - // Same-origin relative-path fetch — exempt from the safe-fetch rule by - // construction. A 429 (warm already in progress) is an expected, - // harmless outcome, not an error. - const res = await fetch("/api/insights/pregenerate", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: "{}", - }); - if (!res.ok && res.status !== 429) { - throw new Error(`HTTP ${res.status}`); - } -} - -export interface UseInsightsWarmResult { - /** Manual trigger — POSTs the warm and shows a toast. */ - warm: () => void; - /** True while the warm POST is in flight. */ - isWarming: boolean; -} - -export function useInsightsWarm(): UseInsightsWarmResult { - const { t } = useTranslations(); - - const mutation = useMutation({ - mutationKey: queryKeys.insightsPregenerate(), - mutationFn: postWarm, - }); - - const { mutate } = mutation; - - const warm = useCallback(() => { - mutate(undefined, { - onSuccess: () => toast.success(t("insights.warmStarted")), - }); - }, [mutate, t]); - - return { - warm, - isWarming: mutation.isPending, - }; -} From 4ace1b7706d2a83721b4604d53c0bea04308277c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Fri, 5 Jun 2026 10:41:58 +0200 Subject: [PATCH 3/4] =?UTF-8?q?refactor(insights):=20unify=20the=20metric?= =?UTF-8?q?=20subpage=20template=20=E2=80=94=20target=20tile,=20order,=20s?= =?UTF-8?q?tat=20strip,=20drop=20the=20range=20row?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Make every metric subpage identical by construction in the shared scaffold rather than per-page bespoke. - Target tile matches the other cards: dark `bg-card` background and the `rounded-xl border p-4` spacing the assessment and stat-strip cards use, instead of the old translucent `bg-card/20` panel. - Drop the 7T/30T/90T/1J range row and its "+X% vs previous" delta from every subpage. The chart owns its own window via its in-card range tabs, so the chart query is unaffected. Retire the now-dead `MetricRangeControls`, `MetricRangeDelta`, `TimeRangePills`, `useAnalyticsRange`, the `useInsightsRangePref` persisted-range hook, and `sentimentFromMetricDirection` along with their tests. - Fix the spine order to intro -> chart -> target card -> assessment -> Min/Max/Median/Mittelwert stat strip. The stat strip moves to the foot of the spine, below the assessment. Remove the "Letzte Messung" card and the headline primary tile from subpages; retire `MetricLastMeasurementCard` and `MetricPrimaryTile`. - Blood pressure gains the stat strip it was missing: two stacked systolic / diastolic strips, since a single-series strip would drop the diastolic half. `MetricStatStrip` takes an optional series caption. Update the spine guard to assert the target card precedes the assessment and that the retired range row and last-measurement card appear on no subpage. Co-Authored-By: Claude Opus 4.8 (1M context) (cherry picked from commit 80b2a810314b4c0951c0d68c04bffc89003005d6) --- .../__tests__/assessment-spine-order.test.ts | 60 ++++-- src/app/insights/blood-pressure/page.tsx | 50 ++--- src/app/insights/bmi/page.tsx | 7 +- src/app/insights/pulse/page.tsx | 12 -- src/app/insights/sleep/page.tsx | 11 +- src/app/insights/weight/page.tsx | 13 -- .../healthkit-metric-page-status.test.tsx | 7 - .../__tests__/metric-range-controls.test.tsx | 52 ----- .../__tests__/metric-range-delta.test.tsx | 57 ------ .../__tests__/time-range-pills.test.tsx | 51 ----- .../insights/healthkit-metric-page.tsx | 23 --- .../insights/metric-last-measurement-card.tsx | 65 ------- .../insights/metric-primary-tile.tsx | 184 ------------------ .../insights/metric-range-controls.tsx | 73 ------- .../insights/metric-range-delta.tsx | 106 ---------- src/components/insights/metric-stat-strip.tsx | 30 ++- .../insights/metric-target-summary.tsx | 2 +- src/components/insights/sub-page-shell.tsx | 42 ++-- src/components/insights/time-range-pills.tsx | 109 ----------- src/hooks/use-analytics-range.ts | 56 ------ src/hooks/use-insights-layout-prefs.ts | 55 ------ src/lib/insights/trend-sentiment.ts | 15 -- 22 files changed, 120 insertions(+), 960 deletions(-) delete mode 100644 src/components/insights/__tests__/metric-range-controls.test.tsx delete mode 100644 src/components/insights/__tests__/metric-range-delta.test.tsx delete mode 100644 src/components/insights/__tests__/time-range-pills.test.tsx delete mode 100644 src/components/insights/metric-last-measurement-card.tsx delete mode 100644 src/components/insights/metric-primary-tile.tsx delete mode 100644 src/components/insights/metric-range-controls.tsx delete mode 100644 src/components/insights/metric-range-delta.tsx delete mode 100644 src/components/insights/time-range-pills.tsx delete mode 100644 src/hooks/use-analytics-range.ts diff --git a/src/app/insights/__tests__/assessment-spine-order.test.ts b/src/app/insights/__tests__/assessment-spine-order.test.ts index 49e85c895..d73973512 100644 --- a/src/app/insights/__tests__/assessment-spine-order.test.ts +++ b/src/app/insights/__tests__/assessment-spine-order.test.ts @@ -3,21 +3,25 @@ import { readFileSync } from "node:fs"; import { join } from "node:path"; /** - * v1.12.2 — canonical metric-detail spine guard. + * v1.12.4 — canonical metric-detail spine guard. * - * v1.12.0 made the AI assessment the LAST content block on every metric - * sub-page (primary → stat strip → chart → range → target → forecast → - * assessment). The generic `HealthKitMetricPage` scaffold enforces this for - * the ~29 HealthKit pages structurally; the six bespoke pages each hand-write - * their body, so a future edit can silently slot a card after the assessment - * (as `mood` and `medications` did before this release). + * The unified subpage spine is: intro → chart → target card → assessment → + * stat strip. The assessment is the LAST content block the page hands to + * `` as `children`; the shell appends the Min/Max/Median/Mean + * stat strip below it. The generic `HealthKitMetricPage` scaffold enforces + * this for the ~29 HealthKit pages structurally; the bespoke pages each + * hand-write their body, so a future edit can silently slot a card after the + * assessment (as `mood` and `medications` did before). * - * This is a source-level structural guard: the assessment card element must be - * the last JSX child of the page's ``. Asserting on the source - * (rather than rendered markup) keeps the test deterministic — the preceding - * blocks (`MetricTargetSummary`, `MoodInsightsSections`, `TherapyTimeline`) - * all self-suppress on a data miss, so a render-order assertion would depend - * on mocking the whole data layer. + * This is a source-level structural guard: + * 1. the assessment card element is the last JSX child of ``; + * 2. the target card (`MetricTargetSummary`) precedes the assessment; + * 3. the retired range row (`MetricRangeControls`) and the retired + * "Letzte Messung" card (`MetricLastMeasurementCard`) appear nowhere. + * + * Asserting on the source (rather than rendered markup) keeps the test + * deterministic — the preceding blocks all self-suppress on a data miss, so a + * render-order assertion would depend on mocking the whole data layer. */ const PAGES_DIR = join(process.cwd(), "src", "app", "insights"); @@ -80,6 +84,36 @@ describe("bespoke metric-detail spine — assessment is the last block", () => { `${slug}: "${trailing.slice(0, 40)}" renders AFTER the assessment card — ` + `the assessment must be the last block on the canonical spine`, ).toBe(""); + + // v1.12.4 — the target card precedes the assessment when present. + const targetIndex = body.indexOf(" -1) { + expect( + targetIndex, + `${slug}: target card must render before the assessment`, + ).toBeLessThan(assessmentIndex); + } + }); + } +}); + +describe("metric subpages — retired range row + Letzte-Messung are gone", () => { + // The whole insights subpage tree (bespoke + the values/scores detail pages). + for (const { slug } of BESPOKE_PAGES) { + it(`/insights/${slug} carries no range row and no last-measurement card`, () => { + const source = readFileSync(join(PAGES_DIR, slug, "page.tsx"), "utf8"); + // Match a real JSX element start (``), + // not the back-ticked references inside explanatory comments + // (``) that mood / medications keep to document + // why the row is intentionally absent. + expect( + / - {/* Blood pressure's primary tile IS its richer target panel - (ESH classification + sys/dia band + 30-day S/D average), - promoted above the chart per the canonical spine. */} - - - + statStrip={ +
    + + +
    } diversityNudge={ } showAllValuesType="BLOOD_PRESSURE_SYS" - /* No `statStrip`: `` is single-series, but blood - pressure is two series (systolic + diastolic). A single min / max / - median / mean strip would silently drop the diastolic half, so the - page omits it rather than mislead. */ > - {/* The period-over-period delta keys on the systolic series — the - canonical BP figure the targets + status surfaces lead with. */} - {/* v1.12.0 — range pills + period-over-period delta below the chart. */} - - {/* v1.12.0 — Einschätzung is the last block on the canonical - metric-detail spine. */} + {/* v1.12.4 — target card sits between the chart and the assessment on + the canonical spine (ESH classification + sys/dia band + 30-day S/D + average). */} + + + {/* v1.12.4 — Einschätzung is the last content block; the stat strip + (rendered by the shell) closes the spine below it. */} } diff --git a/src/app/insights/bmi/page.tsx b/src/app/insights/bmi/page.tsx index 7d3788a3d..7bd339b4f 100644 --- a/src/app/insights/bmi/page.tsx +++ b/src/app/insights/bmi/page.tsx @@ -13,7 +13,6 @@ import { HealthChartDynamic } from "@/components/charts/health-chart-dynamic"; import { CoachLaunchButton } from "@/components/insights/coach-launch-button"; import { SlugInsightStatusCard } from "@/components/insights/slug-insight-status-card"; import { MetricEmptyState } from "@/components/insights/metric-empty-state"; -import { MetricRangeControls } from "@/components/insights/metric-range-controls"; import { MetricTargetSummary } from "@/components/insights/metric-target-summary"; import { SubPageShell } from "@/components/insights/sub-page-shell"; @@ -115,9 +114,7 @@ export default function InsightsBmiPage() { so it has no first-class summary or raw-reading rows of its own. A stat strip would have nothing to read, and a diversity nudge / "show all values" entry would point at WEIGHT and duplicate the weight - page's controls. - BMI is derived from WEIGHT, so the period-over-period delta keys on - the underlying weight series the chart reuses. */} + page's controls. */} - {/* v1.12.0 — range pills + period-over-period delta below the chart. */} - diff --git a/src/app/insights/pulse/page.tsx b/src/app/insights/pulse/page.tsx index 50834520c..5ee3b6531 100644 --- a/src/app/insights/pulse/page.tsx +++ b/src/app/insights/pulse/page.tsx @@ -12,11 +12,8 @@ import { HealthChartDynamic } from "@/components/charts/health-chart-dynamic"; import { SlugInsightStatusCard } from "@/components/insights/slug-insight-status-card"; import { MetricEmptyState } from "@/components/insights/metric-empty-state"; import { MetricStatStrip } from "@/components/insights/metric-stat-strip"; -import { MetricPrimaryTile } from "@/components/insights/metric-primary-tile"; -import { MetricLastMeasurementCard } from "@/components/insights/metric-last-measurement-card"; import { MetricCorrelationCard } from "@/components/insights/metric-correlation-card"; import { MeasurementDiversityNudge } from "@/components/insights/measurement-diversity-nudge"; -import { MetricRangeControls } from "@/components/insights/metric-range-controls"; import { MetricTargetSummary } from "@/components/insights/metric-target-summary"; import { SubPageShell } from "@/components/insights/sub-page-shell"; import { Vo2MaxChartRow } from "@/components/insights/vo2-max-chart-row"; @@ -52,7 +49,6 @@ export default function InsightsPulsPage() { const { data: analytics, isEmpty } = useInsightsAnalytics("PULSE"); const vo2Summary = analytics?.summaries?.VO2_MAX ?? null; const pulseSummary = analytics?.summaries?.PULSE ?? null; - const pulseLastSeenAt = analytics?.lastSeenByType?.PULSE?.lastSeenAt ?? null; // v1.4.27 F17 — gate the sub-page on at least one pulse observation. // Brand-new accounts (no manual logs, no Apple-Health upload yet) @@ -117,12 +113,6 @@ export default function InsightsPulsPage() { title={t("insights.pulseSectionTitle")} description={t("insights.subPage.pulsDescription")} explainerMetric="pulse" - primary={ - <> - - - - } statStrip={} diversityNudge={ - {/* v1.12.0 — range pills + period-over-period delta below the chart. */} - diff --git a/src/app/insights/sleep/page.tsx b/src/app/insights/sleep/page.tsx index 116422bc8..9266068e7 100644 --- a/src/app/insights/sleep/page.tsx +++ b/src/app/insights/sleep/page.tsx @@ -10,8 +10,6 @@ import { Button } from "@/components/ui/button"; import { MeasurementDiversityNudge } from "@/components/insights/measurement-diversity-nudge"; import { MetricStatusCard } from "@/components/insights/metric-status-card"; import { MetricEmptyState } from "@/components/insights/metric-empty-state"; -import { MetricLastMeasurementCard } from "@/components/insights/metric-last-measurement-card"; -import { MetricRangeControls } from "@/components/insights/metric-range-controls"; import { MetricTargetSummary } from "@/components/insights/metric-target-summary"; import { SleepOverview } from "@/components/insights/sleep-overview"; import { SubPageShell } from "@/components/insights/sub-page-shell"; @@ -36,10 +34,7 @@ export default function InsightsSchlafPage() { const { t } = useTranslations(); const { user } = useAuth(); - const { data: analytics, isEmpty } = - useInsightsAnalytics("SLEEP_DURATION"); - const sleepLastSeenAt = - analytics?.lastSeenByType?.SLEEP_DURATION?.lastSeenAt ?? null; + const { isEmpty } = useInsightsAnalytics("SLEEP_DURATION"); if (isEmpty) { return ( @@ -71,7 +66,6 @@ export default function InsightsSchlafPage() { description={t("insights.sleep.description")} explainerMetric="sleep" coachLaunch - primary={} diversityNudge={ - {/* v1.12.0 — range pills + period-over-period delta below the chart. */} - - {/* diff --git a/src/app/insights/weight/page.tsx b/src/app/insights/weight/page.tsx index 391c8de98..afac21922 100644 --- a/src/app/insights/weight/page.tsx +++ b/src/app/insights/weight/page.tsx @@ -12,11 +12,8 @@ import { HealthChartDynamic } from "@/components/charts/health-chart-dynamic"; import { SlugInsightStatusCard } from "@/components/insights/slug-insight-status-card"; import { MetricEmptyState } from "@/components/insights/metric-empty-state"; import { MetricStatStrip } from "@/components/insights/metric-stat-strip"; -import { MetricPrimaryTile } from "@/components/insights/metric-primary-tile"; -import { MetricLastMeasurementCard } from "@/components/insights/metric-last-measurement-card"; import { MetricCorrelationCard } from "@/components/insights/metric-correlation-card"; import { MeasurementDiversityNudge } from "@/components/insights/measurement-diversity-nudge"; -import { MetricRangeControls } from "@/components/insights/metric-range-controls"; import { MetricTargetSummary } from "@/components/insights/metric-target-summary"; import { SubPageShell } from "@/components/insights/sub-page-shell"; import { TrajectoryForecastCard } from "@/components/insights/derived/trajectory-forecast-card"; @@ -41,8 +38,6 @@ export default function InsightsGewichtPage() { const { data: analytics, isEmpty } = useInsightsAnalytics("WEIGHT"); const weightSummary = analytics?.summaries?.WEIGHT ?? null; - const weightLastSeenAt = - analytics?.lastSeenByType?.WEIGHT?.lastSeenAt ?? null; if (isEmpty) { return ( @@ -80,12 +75,6 @@ export default function InsightsGewichtPage() { title={t("insights.weightSectionTitle")} description={t("insights.subPage.gewichtDescription")} explainerMetric="weight" - primary={ - <> - - - - } statStrip={} diversityNudge={ - {/* v1.12.0 — range pills + period-over-period delta below the chart. */} - diff --git a/src/components/insights/__tests__/healthkit-metric-page-status.test.tsx b/src/components/insights/__tests__/healthkit-metric-page-status.test.tsx index 5a398339f..d03212622 100644 --- a/src/components/insights/__tests__/healthkit-metric-page-status.test.tsx +++ b/src/components/insights/__tests__/healthkit-metric-page-status.test.tsx @@ -33,13 +33,6 @@ vi.mock("@/hooks/use-auth", () => ({ vi.mock("@/hooks/use-insights-layout-prefs", () => ({ useInsightsLayoutPrefs: () => ({ layout: null, compareBaseline: false }), - useInsightsRangePref: () => ({ range: "30d", setRange: () => {} }), -})); - -// v1.9.0 — the page reads the period-over-period range delta; mock the hook -// so the test stays deterministic and never touches `fetch`. -vi.mock("@/hooks/use-analytics-range", () => ({ - useAnalyticsRange: () => ({ data: undefined, isLoading: false }), })); const analyticsMock = vi.fn(); diff --git a/src/components/insights/__tests__/metric-range-controls.test.tsx b/src/components/insights/__tests__/metric-range-controls.test.tsx deleted file mode 100644 index dfd58a797..000000000 --- a/src/components/insights/__tests__/metric-range-controls.test.tsx +++ /dev/null @@ -1,52 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { renderToStaticMarkup } from "react-dom/server"; - -import { I18nProvider } from "@/lib/i18n/context"; - -/** - * v1.10.2 — `` is the shared range-controls block lifted - * out of `` so the bespoke metric sub-pages render the - * identical time-range pills + period-over-period delta. The component owns - * the range pref + range read + direction-sentiment lookup; the test mocks - * those hooks so the render stays deterministic and never touches `fetch`. - */ - -const rangeMock = vi.fn(); -vi.mock("@/hooks/use-insights-layout-prefs", () => ({ - useInsightsRangePref: () => ({ range: "30d", setRange: () => {} }), -})); - -vi.mock("@/hooks/use-analytics-range", () => ({ - useAnalyticsRange: (...args: unknown[]) => rangeMock(...args), -})); - -import { MetricRangeControls } from "../metric-range-controls"; - -function render(node: React.ReactNode) { - return renderToStaticMarkup( - {node}, - ); -} - -beforeEach(() => { - rangeMock.mockReset(); - rangeMock.mockReturnValue({ data: undefined, isLoading: false }); -}); - -describe("", () => { - it("renders the time-range pills and the delta slot", () => { - const html = render(); - expect(html).toContain('data-slot="metric-range-controls"'); - expect(html).toContain('data-slot="time-range-pills"'); - }); - - it("passes the measurement type and enabled flag through to the range read", () => { - render(); - expect(rangeMock).toHaveBeenCalledWith("PULSE", "30d", false); - }); - - it("defaults the range read to enabled", () => { - render(); - expect(rangeMock).toHaveBeenCalledWith("SLEEP_DURATION", "30d", true); - }); -}); diff --git a/src/components/insights/__tests__/metric-range-delta.test.tsx b/src/components/insights/__tests__/metric-range-delta.test.tsx deleted file mode 100644 index dd5006a09..000000000 --- a/src/components/insights/__tests__/metric-range-delta.test.tsx +++ /dev/null @@ -1,57 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { renderToStaticMarkup } from "react-dom/server"; - -import { I18nProvider } from "@/lib/i18n/context"; -import { MetricRangeDelta } from "../metric-range-delta"; -import type { AnalyticsRangeData } from "@/hooks/use-analytics-range"; - -/** - * v1.9.0 QA (Design M1 / Correctness L-1) — a perfectly stable metric - * (delta === 0 / rounded 0 %) must read neutral: a flat dash and "no - * change", never a down-arrow with "−0%". - */ -function render(data: AnalyticsRangeData | undefined) { - return renderToStaticMarkup( - - - , - ); -} - -const base: AnalyticsRangeData = { - range: "30d", - windowDays: 30, - granularity: "DAY", - current: { count: 1, min: 1, max: 1, mean: 1, sum: 1 }, - previous: { count: 1, min: 1, max: 1, mean: 1, sum: 1 }, - delta: 0, - deltaPct: 0, -}; - -describe("MetricRangeDelta — zero-delta neutral", () => { - it("renders neutral copy + no directional arrow for a zero delta", () => { - const html = render(base); - expect(html).toContain('data-direction="neutral"'); - expect(html).toContain("no change"); - // No misleading "−0%". - expect(html).not.toContain("0%"); - expect(html).not.toContain("−"); - }); - - it("still renders a directional +pct for a real increase", () => { - const html = render({ ...base, delta: 2, deltaPct: 0.1 }); - expect(html).toContain('data-direction='); - expect(html).not.toContain('data-direction="neutral"'); - expect(html).toContain("+10%"); - }); - - it("shows the no-prior-data line when the comparison is null", () => { - const html = render({ ...base, delta: null, deltaPct: null }); - expect(html).toContain("metric-range-delta-empty"); - }); -}); diff --git a/src/components/insights/__tests__/time-range-pills.test.tsx b/src/components/insights/__tests__/time-range-pills.test.tsx deleted file mode 100644 index 0138a7f8e..000000000 --- a/src/components/insights/__tests__/time-range-pills.test.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { renderToStaticMarkup } from "react-dom/server"; - -import { I18nProvider } from "@/lib/i18n/context"; -import { TimeRangePills } from "../time-range-pills"; -import { ANALYTICS_RANGES } from "@/lib/analytics/range-delta"; - -/** - * v1.9.0 QA (Design H1) — the range pills are a WAI-ARIA APG radiogroup, so - * the group must be a SINGLE tab stop: only the checked radio carries - * `tabIndex={0}`, every other radio is `-1` (roving tabindex). Before the - * fix all four were native buttons (four tab stops) with no arrow-key - * handler. Project convention is SSR-only tests, so we assert the rendered - * roving-tabindex contract + radio semantics rather than driving live key - * events. - */ -function render(value: (typeof ANALYTICS_RANGES)[number]) { - return renderToStaticMarkup( - - {}} /> - , - ); -} - -describe("TimeRangePills — roving tabindex (single tab stop)", () => { - it("renders a radiogroup with one radio per range", () => { - const html = render("30d"); - expect(html).toContain('role="radiogroup"'); - const radios = html.match(/role="radio"/g) ?? []; - expect(radios).toHaveLength(ANALYTICS_RANGES.length); - }); - - it("makes only the checked radio tabbable (tabindex 0); the rest are -1", () => { - const html = render("30d"); - // Exactly one tabindex=0 (the checked radio is the single tab stop). - const tabbable = html.match(/tabindex="0"/g) ?? []; - expect(tabbable).toHaveLength(1); - // The remaining three are removed from the tab order. - const untabbable = html.match(/tabindex="-1"/g) ?? []; - expect(untabbable).toHaveLength(ANALYTICS_RANGES.length - 1); - }); - - it("marks the chosen value selected (aria-checked + data-selected)", () => { - const html = render("90d"); - // Exactly one radio is checked / selected. - expect(html.match(/aria-checked="true"/g) ?? []).toHaveLength(1); - expect(html.match(/data-selected="true"/g) ?? []).toHaveLength(1); - // The chosen pill is present and selected. - expect(html).toMatch(/data-range="90d"/); - }); -}); diff --git a/src/components/insights/healthkit-metric-page.tsx b/src/components/insights/healthkit-metric-page.tsx index 9e3547344..aa86c5c5c 100644 --- a/src/components/insights/healthkit-metric-page.tsx +++ b/src/components/insights/healthkit-metric-page.tsx @@ -19,11 +19,8 @@ import { TrajectoryForecastCard } from "@/components/insights/derived/trajectory import { isTrajectoryType } from "@/lib/insights/derived/registry"; import { MetricEmptyState } from "@/components/insights/metric-empty-state"; import { MetricStatStrip } from "@/components/insights/metric-stat-strip"; -import { MetricPrimaryTile } from "@/components/insights/metric-primary-tile"; -import { MetricLastMeasurementCard } from "@/components/insights/metric-last-measurement-card"; import { MeasurementDiversityNudge } from "@/components/insights/measurement-diversity-nudge"; import { MetricTargetSummary } from "@/components/insights/metric-target-summary"; -import { MetricRangeControls } from "@/components/insights/metric-range-controls"; import { SubPageShell } from "@/components/insights/sub-page-shell"; /** @@ -179,9 +176,6 @@ export function HealthKitMetricPage({ } : rawSummary; - const lastSeenAt = - analytics?.lastSeenByType?.[measurementType]?.lastSeenAt ?? null; - const title = t(`${i18nPrefix}.title`); const description = t(`${i18nPrefix}.description`); @@ -216,16 +210,6 @@ export function HealthKitMetricPage({ title={title} description={description} explainerMetric={explainerMetric} - primary={ - <> - - - - } statStrip={} diversityNudge={ - {/* v1.12.0 — time-range pills + period-over-period delta, relocated - BELOW the chart (iOS-parity). The pills drive the period-over-period - delta read and persist across metrics via `useInsightsRangePref`; - the chart owns its own window via its in-card range tabs, so this - block sits as a clean bottom-of-card row rather than between the - stat strip and the chart. */} - {targetSummarySlug ? ( ) : null} diff --git a/src/components/insights/metric-last-measurement-card.tsx b/src/components/insights/metric-last-measurement-card.tsx deleted file mode 100644 index 997383cf5..000000000 --- a/src/components/insights/metric-last-measurement-card.tsx +++ /dev/null @@ -1,65 +0,0 @@ -"use client"; - -import { Clock } from "lucide-react"; - -import { useFormatters, useTranslations } from "@/lib/i18n/context"; -import { formatRelativeTime } from "@/lib/i18n/relative-time"; - -/** - * v1.12.0 — canonical "Letzte Messung" card. - * - * The third block on the per-metric detail page (after the primary - * tile), mirroring the iOS `InsightsLastMeasurementCard`. It captions - * WHEN the most recent reading landed — the date plus a "vor X Tagen" - * recency line. - * - * It deliberately does NOT repeat the latest value: the headline value - * lives in `` only (the no-duplicate-info rule). This - * card owns the timing dimension; the primary tile owns the value. - * - * Self-suppressing: renders nothing when no `lastSeenAt` is available - * (a brand-new metric, or a metric whose freshness map has no entry), - * so a sparse page never carries an empty timing card. - */ - -interface MetricLastMeasurementCardProps { - /** - * ISO timestamp of the latest reading for this metric, read from the - * analytics `lastSeenByType[type]?.lastSeenAt` slot. Null / undefined - * suppresses the card. - */ - lastSeenAt: string | null | undefined; -} - -export function MetricLastMeasurementCard({ - lastSeenAt, -}: MetricLastMeasurementCardProps) { - const { t } = useTranslations(); - const fmt = useFormatters(); - - if (!lastSeenAt) return null; - const parsed = new Date(lastSeenAt); - if (Number.isNaN(parsed.getTime())) return null; - - return ( -
    -
    -
    -
    -

    - {t("insights.subPage.lastMeasurement.label")} -

    -

    - {fmt.dateWithWeekday(parsed)} - - {formatRelativeTime(lastSeenAt, t)} - -

    -
    -
    - ); -} diff --git a/src/components/insights/metric-primary-tile.tsx b/src/components/insights/metric-primary-tile.tsx deleted file mode 100644 index 7594ef0dc..000000000 --- a/src/components/insights/metric-primary-tile.tsx +++ /dev/null @@ -1,184 +0,0 @@ -"use client"; - -import { useQuery } from "@tanstack/react-query"; - -import { useAuth } from "@/hooks/use-auth"; -import { queryKeys } from "@/lib/query-keys"; -import { useFormatters, useTranslations } from "@/lib/i18n/context"; -import type { DataSummary } from "@/lib/analytics/trends"; -import { cn } from "@/lib/utils"; - -/** - * v1.12.0 — canonical metric primary tile. - * - * The first data block on every per-metric detail page, mirroring the - * iOS `InsightsPrimaryTile`: - * - * • the headline value — the latest reading (the single place on the - * page the headline number appears; the stat strip below carries - * min / max / median / mean, not the latest), - * • the 30-Tage-Durchschnitt (`summary.avg30`) as a secondary line, - * • an "Im Zielbereich" bar — the share of logged days in target over - * the last 30, shown ONLY when the metric carries a per-metric pct - * (a registered target band feeds `/api/insights/targets`). - * - * Self-suppressing: renders nothing without a summary or with a - * zero-count series (the page empty-state owns that surface). The - * in-target bar omits itself when the slug has no numeric target or the - * route flagged insufficient data, so a target-less metric (HRV, SpO₂, - * temperature, …) reads as a clean headline + 30-day average. - * - * Blood pressure does NOT use this tile — its richer BP target panel is - * its primary tile (the page omits this component and leads with - * ``). - */ - -interface TargetRange { - min: number; - max: number; -} - -interface TargetItem { - type: string; - daysInRange30d: number; - daysLogged30d: number; - insufficientData: boolean; - range: TargetRange | null; -} - -interface TargetsResponse { - targets: TargetItem[]; -} - -/** - * Insights slug → target `type`. Mirrors `metric-target-summary.tsx`'s - * map for the single-target metrics. Slugs absent from the map (HRV, - * SpO₂, temperature, …) carry no in-target pct, so the bar suppresses. - */ -const SLUG_TO_TARGET_TYPE: Record = { - weight: "WEIGHT", - bmi: "BMI", - pulse: "PULSE", - sleep: "SLEEP_DURATION", -}; - -interface MetricPrimaryTileProps { - /** - * Analytics summary for the page's `MeasurementType`. Null is allowed - * so the parent doesn't gate on the network read finishing. - */ - summary: DataSummary | null; - /** Unit suffix rendered next to the value (e.g. `bpm`, `kg`). */ - unit: string; - /** - * Insights category slug (e.g. `"weight"`). When the slug maps to a - * registered target, the tile reads the in-target pct from - * `/api/insights/targets` and paints the "Im Zielbereich" bar. Omit - * for metrics with no numeric target — the tile then shows headline + - * 30-day average only. - */ - slug?: string; - /** Decimal precision for the formatted values. Defaults to 1. */ - fractionDigits?: number; -} - -export function MetricPrimaryTile({ - summary, - unit, - slug, - fractionDigits = 1, -}: MetricPrimaryTileProps) { - const { t } = useTranslations(); - const fmt = useFormatters(); - const { isAuthenticated } = useAuth(); - - const targetType = slug ? SLUG_TO_TARGET_TYPE[slug] : undefined; - - const { data: targets } = useQuery({ - queryKey: queryKeys.insightsTargets(), - queryFn: async () => { - const res = await fetch("/api/insights/targets"); - if (!res.ok) throw new Error("Failed"); - const json = await res.json(); - return json.data as TargetsResponse; - }, - enabled: isAuthenticated && targetType != null, - }); - - // Nothing to show until the summary lands or for a metric with no - // readings — the page's empty-state covers the zero-data case. - if (!summary || summary.count <= 0) return null; - - const headline = - summary.latest === null - ? "—" - : `${fmt.number(summary.latest, fractionDigits)} ${unit}`; - const avg30 = - summary.avg30 === null - ? null - : `${fmt.number(summary.avg30, fractionDigits)} ${unit}`; - - // In-target share: fraction of logged days in the green band over the - // last 30, read verbatim from the targets route (never recomputed). - const target = targetType - ? targets?.targets.find((entry) => entry.type === targetType) - : undefined; - const showShare = - target != null && - target.range != null && - !target.insufficientData && - target.daysLogged30d > 0; - const sharePct = showShare - ? Math.round((target.daysInRange30d / target.daysLogged30d) * 100) - : null; - - return ( -
    -
    -

    - {headline} -

    - {avg30 ? ( -

    - {t("insights.subPage.primary.avg30Label")}: {avg30} -

    - ) : null} -
    - - {/* "Im Zielbereich" bar — share of the last 30 logged days inside - the target band. Self-suppresses for target-less metrics and on - insufficient data. */} - {sharePct != null ? ( -
    -
    -

    - {t("insights.subPage.primary.inRangeLabel")} -

    -

    {sharePct}%

    -
    -
    -
    = 70 ? "bg-dracula-green" : "bg-dracula-orange", - )} - style={{ width: `${Math.min(100, Math.max(0, sharePct))}%` }} - /> -
    -
    - ) : null} -
    - ); -} diff --git a/src/components/insights/metric-range-controls.tsx b/src/components/insights/metric-range-controls.tsx deleted file mode 100644 index 7f1a0ee79..000000000 --- a/src/components/insights/metric-range-controls.tsx +++ /dev/null @@ -1,73 +0,0 @@ -"use client"; - -import { useInsightsRangePref } from "@/hooks/use-insights-layout-prefs"; -import { useAnalyticsRange } from "@/hooks/use-analytics-range"; -import { - getMetricStatusMeta, - metricIdForMeasurementType, -} from "@/lib/insights/metric-status-registry"; -import { sentimentFromMetricDirection } from "@/lib/insights/trend-sentiment"; -import type { MeasurementType } from "@/generated/prisma/client"; -import { TimeRangePills } from "@/components/insights/time-range-pills"; -import { MetricRangeDelta } from "@/components/insights/metric-range-delta"; - -/** - * v1.10.2 — shared range-controls block (time-range pills + - * period-over-period delta) lifted out of `` so the - * bespoke metric sub-pages (`weight`, `blood-pressure`, `pulse`, `mood`, - * `sleep`, `bmi`, …) render the identical control. - * - * Before this, the 37 HealthKit pages carried the selector and the 8 - * hand-rolled pages carried nothing, so navigating from an HK metric to - * `weight` made the control vanish. This component is the single source the - * HK scaffold and the bespoke pages both consume, wired to the same - * persisted range pref (`useInsightsRangePref`) so the choice sticks across - * every metric. - * - * The delta's sentiment colour follows the metric's "good direction" from - * the metric-status registry (higher-better → up-good, lower-better → - * up-bad, target-band → neutral); a metric absent from the registry falls - * back to neutral. - */ -export function MetricRangeControls({ - measurementType, - enabled = true, -}: { - /** The MeasurementType the period-over-period read is keyed on. */ - measurementType: string; - /** - * Gate the range read. Pages pass `!isEmpty` so a brand-new metric with - * no observations never fires the round-trip. Defaults to `true`. - */ - enabled?: boolean; -}) { - const { range, setRange } = useInsightsRangePref(); - const { data: rangeData, isLoading: isRangeLoading } = useAnalyticsRange( - measurementType, - range, - enabled, - ); - - const registryMeta = (() => { - const id = metricIdForMeasurementType(measurementType as MeasurementType); - return id ? getMetricStatusMeta(id) : null; - })(); - const directionSentiment = registryMeta - ? sentimentFromMetricDirection(registryMeta.direction) - : "neutral"; - - return ( -
    - - -
    - ); -} diff --git a/src/components/insights/metric-range-delta.tsx b/src/components/insights/metric-range-delta.tsx deleted file mode 100644 index 477ce1aea..000000000 --- a/src/components/insights/metric-range-delta.tsx +++ /dev/null @@ -1,106 +0,0 @@ -"use client"; - -import { ArrowDown, ArrowUp, Minus } from "lucide-react"; - -import { useTranslations } from "@/lib/i18n/context"; -import { cn } from "@/lib/utils"; -import { - getTrendSentiment, - sentimentColorClass, - type TrendDirectionSentiment, -} from "@/lib/insights/trend-sentiment"; -import type { AnalyticsRangeData } from "@/hooks/use-analytics-range"; -import type { AnalyticsRange } from "@/lib/analytics/range-shared"; - -/** - * v1.9.0 — period-over-period delta caption beside the time-range pills. - * - * Renders "+3 % vs prior 30d" with the metric-aware sentiment colour the - * dashboard tiles use (up-good vs up-bad). When the prior window has no data - * it shows a neutral "no prior-period data" line instead of a misleading 0 % - * (the `deltaPct` is null in that case). For `target-band` metrics the - * sentiment is neutral, so the delta still shows magnitude + direction but - * carries no good/bad colour — matching Oura's deviation framing for metrics - * with no single good direction. - */ -export function MetricRangeDelta({ - data, - range, - directionSentiment, - isLoading, -}: { - data: AnalyticsRangeData | undefined; - range: AnalyticsRange; - directionSentiment: TrendDirectionSentiment; - isLoading: boolean; -}) { - const { t } = useTranslations(); - - if (isLoading) { - return ( -