diff --git a/messages/de.json b/messages/de.json index b4de1c4bb..bed6128bc 100644 --- a/messages/de.json +++ b/messages/de.json @@ -4999,6 +4999,9 @@ "noActiveCycle": "Noch kein aktiver Zyklus", "viewDetails": "Zyklus-Erkenntnisse ansehen" }, + "wellnessRing": { + "label": "Zyklus" + }, "disclaimer": "Diese Vorhersagen sind beschreibende Schätzungen aus deinen erfassten Daten, keine Verhütungsmethode und keine medizinische Beratung. Sie zeigen nie an, dass ungeschützter Geschlechtsverkehr sicher ist. Wende dich für Verhütung oder medizinische Entscheidungen an eine medizinische Fachperson.", "title": "Dein Zyklus", "subtitle": "Erfasse deine Periode und Symptome und sieh, was als Nächstes kommt.", diff --git a/messages/en.json b/messages/en.json index 65956ba5c..d9d9a08ba 100644 --- a/messages/en.json +++ b/messages/en.json @@ -4999,6 +4999,9 @@ "noActiveCycle": "No active cycle yet", "viewDetails": "View cycle insights" }, + "wellnessRing": { + "label": "Cycle" + }, "disclaimer": "These predictions are descriptive estimates from your logged data, not a contraceptive method and not medical advice. They never indicate that it is safe to have unprotected sex. For contraception or any medical decision, consult a healthcare professional.", "title": "Your cycle", "subtitle": "Log your period and symptoms, see what comes next.", diff --git a/messages/es.json b/messages/es.json index 55eeb130d..2629b9c90 100644 --- a/messages/es.json +++ b/messages/es.json @@ -4999,6 +4999,9 @@ "noActiveCycle": "Aún no hay un ciclo activo", "viewDetails": "Ver análisis del ciclo" }, + "wellnessRing": { + "label": "Ciclo" + }, "disclaimer": "Estas predicciones son estimaciones descriptivas a partir de tus datos registrados, no un método anticonceptivo ni un consejo médico. Nunca indican que sea seguro tener relaciones sin protección. Para anticoncepción o cualquier decisión médica, consulta a un profesional sanitario.", "title": "Tu ciclo", "subtitle": "Registra tu periodo y síntomas, y mira qué viene después.", diff --git a/messages/fr.json b/messages/fr.json index ee4f7309b..f352bd636 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -4999,6 +4999,9 @@ "noActiveCycle": "Aucun cycle actif pour l'instant", "viewDetails": "Voir les analyses du cycle" }, + "wellnessRing": { + "label": "Cycle" + }, "disclaimer": "Ces prévisions sont des estimations descriptives issues de vos données enregistrées, ni une méthode de contraception ni un avis médical. Elles n'indiquent jamais qu'il est sûr d'avoir des rapports non protégés. Pour la contraception ou toute décision médicale, consultez un professionnel de santé.", "title": "Ton cycle", "subtitle": "Enregistre tes règles et symptômes, et vois ce qui arrive ensuite.", diff --git a/messages/it.json b/messages/it.json index 367a129d5..a9325f736 100644 --- a/messages/it.json +++ b/messages/it.json @@ -4999,6 +4999,9 @@ "noActiveCycle": "Nessun ciclo attivo ancora", "viewDetails": "Vedi le analisi del ciclo" }, + "wellnessRing": { + "label": "Ciclo" + }, "disclaimer": "Queste previsioni sono stime descrittive basate sui tuoi dati registrati, non un metodo contraccettivo né un parere medico. Non indicano mai che sia sicuro avere rapporti non protetti. Per la contraccezione o qualsiasi decisione medica, consulta un professionista sanitario.", "title": "Il tuo ciclo", "subtitle": "Registra il ciclo e i sintomi e scopri cosa arriva dopo.", diff --git a/messages/pl.json b/messages/pl.json index 6e5754dce..1e6fe6c4a 100644 --- a/messages/pl.json +++ b/messages/pl.json @@ -4999,6 +4999,9 @@ "noActiveCycle": "Brak aktywnego cyklu", "viewDetails": "Zobacz analizy cyklu" }, + "wellnessRing": { + "label": "Cykl" + }, "disclaimer": "Te prognozy to opisowe szacunki na podstawie zapisanych danych, a nie metoda antykoncepcji ani porada medyczna. Nigdy nie oznaczają, że współżycie bez zabezpieczenia jest bezpieczne. W sprawach antykoncepcji lub decyzji medycznych skonsultuj się z pracownikiem ochrony zdrowia.", "title": "Twój cykl", "subtitle": "Zapisuj miesiączkę i objawy oraz sprawdzaj, co dalej.", diff --git a/src/app/insights/page.tsx b/src/app/insights/page.tsx index db3a1a1ad..5018a9035 100644 --- a/src/app/insights/page.tsx +++ b/src/app/insights/page.tsx @@ -167,6 +167,19 @@ const CycleInsightSummaryCard = dynamic( { ssr: false }, ); +// v1.15.3 — the compact cycle RING, dropped into the wellness-score strip as a +// gated sibling tile (NOT the summary teaser — that stays further down). Mounted +// only for a cycle-tracking account, so its calendar read never fires otherwise. +// Deferred behind `next/dynamic`; it renders nothing while resolving / on error / +// when there is no active cycle, so it carries no loading placeholder. +const CycleRingTile = dynamic( + () => + import("@/components/cycle/cycle-ring-tile").then((mod) => ({ + default: mod.CycleRingTile, + })), + { ssr: false }, +); + /** * v1.4.25 W4d — Insights mother page. * @@ -376,6 +389,12 @@ export default function InsightsPage() { isLoading={dashboardDerived.isLoading} isError={dashboardDerived.isError} refetch={dashboardDerived.refetch} + // v1.15.3 — the cycle ring rides the scores strip as a gated sibling + // tile, only for a cycle-tracking account, so its calendar read never + // fires otherwise (the same `/api/auth/me` gate the sidebar nav uses). + extraTile={ + user?.cycleTrackingEnabled ? : undefined + } /> {flags.briefing && ( diff --git a/src/components/charts/compliance-heatmap.tsx b/src/components/charts/compliance-heatmap.tsx index 2cf347f37..c6a23e071 100644 --- a/src/components/charts/compliance-heatmap.tsx +++ b/src/components/charts/compliance-heatmap.tsx @@ -24,6 +24,14 @@ const GAP = 3; // below the touch-friendly 14 px square on narrow viewports. The // stretch branch computes an adaptive size; both branches clamp here. const CELL_FLOOR_PX = 14; +// v1.15.3 — cell-ceiling for the stretch branch. With a short window (a +// single medication / few covered weeks → only ~5 columns) the adaptive +// `containerWidth / weeks` cell ballooned to fill a wide card, and since the +// grid is square the SVG height (`7 * cellSize + 6 * GAP`) blew up to ~3× the +// neighbouring tiles. Capping the cell keeps the grid dense + left-aligned +// (extra width is whitespace) so the heatmap holds the tile-height rhythm: +// height ≈ 18 + 7·22 + 6·3 = 190 px, in line with the surrounding tiles. +const CELL_CEIL_PX = 22; function getColor(data: DailyData): string { if (data.expected === 0) return "var(--secondary)"; @@ -229,10 +237,13 @@ export function ComplianceHeatmap({ // narrows. Static (non-stretch) instances use the canonical 18 px. const cellSize = stretch && containerWidth > 0 - ? Math.max( - CELL_FLOOR_PX, - (containerWidth - labelWidth - Math.max(0, weeks - 1) * GAP) / - Math.max(weeks, 1), + ? Math.min( + CELL_CEIL_PX, + Math.max( + CELL_FLOOR_PX, + (containerWidth - labelWidth - Math.max(0, weeks - 1) * GAP) / + Math.max(weeks, 1), + ), ) : CELL_SIZE; const step = cellSize + GAP; @@ -253,7 +264,11 @@ export function ComplianceHeatmap({ setTooltip((prev) => (prev?.pinned ? prev : null))} > {/* Month labels */} diff --git a/src/components/charts/mood-heatmap.tsx b/src/components/charts/mood-heatmap.tsx index 35bf3fc28..c5fd04019 100644 --- a/src/components/charts/mood-heatmap.tsx +++ b/src/components/charts/mood-heatmap.tsx @@ -35,6 +35,12 @@ interface MoodHeatmapProps { const CELL_SIZE = 18; const GAP = 3; const CELL_FLOOR_PX = 14; +// v1.15.3 — cell-ceiling for the stretch branch. A short window (few covered +// weeks → only ~5 columns) drove the adaptive `containerWidth / weeks` cell to +// fill a wide card; since the grid is square the SVG height blew up to ~3× the +// neighbouring tiles. Capping the cell keeps the grid dense + left-aligned so +// the calendar holds the tile-height rhythm. Mirrors `compliance-heatmap.tsx`. +const CELL_CEIL_PX = 22; /** * Mood score band → Dracula colour. Mirrors `mood-chart.tsx` VALUE_BANDS @@ -183,10 +189,13 @@ export function MoodHeatmap({ const headerHeight = 18; const cellSize = stretch && containerWidth > 0 - ? Math.max( - CELL_FLOOR_PX, - (containerWidth - labelWidth - Math.max(0, weeks - 1) * GAP) / - Math.max(weeks, 1), + ? Math.min( + CELL_CEIL_PX, + Math.max( + CELL_FLOOR_PX, + (containerWidth - labelWidth - Math.max(0, weeks - 1) * GAP) / + Math.max(weeks, 1), + ), ) : CELL_SIZE; const step = cellSize + GAP; @@ -205,7 +214,10 @@ export function MoodHeatmap({ setTooltip((prev) => (prev?.pinned ? prev : null))} > {monthMarkers.map((m, i) => ( diff --git a/src/components/cycle/__tests__/cycle-ring-tile.test.tsx b/src/components/cycle/__tests__/cycle-ring-tile.test.tsx new file mode 100644 index 000000000..42d7d1d12 --- /dev/null +++ b/src/components/cycle/__tests__/cycle-ring-tile.test.tsx @@ -0,0 +1,134 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { renderToStaticMarkup } from "react-dom/server"; + +import { I18nProvider } from "@/lib/i18n/context"; +import type { CalendarResponse } from "../types"; + +/** + * v1.15.3 — the compact cycle ring as a wellness-strip tile. + * + * The tile is mounted ONLY when `user.cycleTrackingEnabled` is true (a + * page-level gate the Insights page owns, mirroring the summary card); these + * tests cover the tile's own behaviour given that gate: it sources the phase + + * cycle day from the SAME calendar read + `deriveWheelState` the wheel uses, + * renders the cycle ring labelled, deep-links to the cycle page, and stays + * silent while resolving / on a hard error / when there is no active cycle so + * the wellness strip never shows a half-painted dial (no gap, no placeholder). + * + * The calendar read is mocked at the hook boundary so the SSR snapshot is + * deterministic without a TanStack-Query client / network round-trip. + */ + +// `next/link` → a plain anchor in the static snapshot. +vi.mock("next/link", () => ({ + default: ({ + href, + children, + ...rest + }: { + href: string; + children: React.ReactNode; + }) => ( + + {children} + + ), +})); + +const calendarState = vi.hoisted(() => ({ + current: { + data: undefined as CalendarResponse | undefined, + isLoading: false, + isError: false, + }, +})); + +vi.mock("../use-cycle", async () => { + const actual = + await vi.importActual("../use-cycle"); + return { + ...actual, + useCycleCalendar: () => calendarState.current, + }; +}); + +import { CycleRingTile } from "../cycle-ring-tile"; + +function render(node: React.ReactNode) { + return renderToStaticMarkup( + {node}, + ); +} + +/** A calendar read where `today` sits on a LUTEAL day at day-of-cycle 3. */ +function lutealCalendar(today: string): CalendarResponse { + const days = [ + { date: shift(today, -2), phase: "MENSTRUAL" as const }, + { date: shift(today, -1), phase: "FOLLICULAR" as const }, + { date: today, phase: "LUTEAL" as const }, + ]; + return { + days: days as unknown as CalendarResponse["days"], + profile: {} as CalendarResponse["profile"], + prediction: null, + } as CalendarResponse; +} + +function shift(ymd: string, delta: number): string { + const [y, m, d] = ymd.split("-").map(Number); + const dt = new Date(y, m - 1, d); + dt.setDate(dt.getDate() + delta); + return `${dt.getFullYear()}-${String(dt.getMonth() + 1).padStart(2, "0")}-${String(dt.getDate()).padStart(2, "0")}`; +} + +function todayYmd(): string { + const d = new Date(); + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; +} + +beforeEach(() => { + calendarState.current = { data: undefined, isLoading: false, isError: false }; +}); + +describe("", () => { + it("renders the cycle ring, phase label, and deep-link for an active cycle", () => { + calendarState.current = { + data: lutealCalendar(todayYmd()), + isLoading: false, + isError: false, + }; + + const html = render(); + + // The wellness-strip tile chrome + the compact cycle ring. + expect(html).toContain('data-slot="wellness-cycle-tile"'); + expect(html).toContain('data-slot="cycle-ring"'); + expect(html).toContain('data-phase="LUTEAL"'); + // The phase band word + the strip-tile label. + expect(html).toContain("Luteal"); + expect(html).toContain("Cycle"); + // Deep-link into the cycle page. + expect(html).toContain('href="/cycle"'); + }); + + it("renders nothing while the calendar read is still resolving", () => { + calendarState.current = { data: undefined, isLoading: true, isError: false }; + expect(render()).toBe(""); + }); + + it("renders nothing on a hard calendar read error", () => { + calendarState.current = { data: undefined, isLoading: false, isError: true }; + expect(render()).toBe(""); + }); + + it("renders nothing when there is no active cycle today", () => { + // A resolved calendar with no phase on today → no active cycle. + const empty: CalendarResponse = { + days: [] as unknown as CalendarResponse["days"], + profile: {} as CalendarResponse["profile"], + prediction: null, + } as CalendarResponse; + calendarState.current = { data: empty, isLoading: false, isError: false }; + expect(render()).toBe(""); + }); +}); diff --git a/src/components/cycle/cycle-ring-tile.tsx b/src/components/cycle/cycle-ring-tile.tsx new file mode 100644 index 000000000..0285f192f --- /dev/null +++ b/src/components/cycle/cycle-ring-tile.tsx @@ -0,0 +1,127 @@ +"use client"; + +import { useMemo, useState } from "react"; +import Link from "next/link"; +import { Droplets } from "lucide-react"; + +import { cn } from "@/lib/utils"; +import { useTranslations } from "@/lib/i18n/context"; +import { CycleRing } from "./cycle-ring"; +import { PHASE_HUE } from "./phase-tokens"; +import { deriveWheelState } from "./wheel-state"; +import { localYmd, useCycleCalendar } from "./use-cycle"; + +/** + * v1.15.3 — the compact cycle ring as a WELLNESS-STRIP element. + * + * A same-size sibling tile that drops into the main Insights "Your health + * scores" grid (``), so the cycle phase reads as part of the + * premium scores strip rather than bolted-on below it. It reuses the SAME + * `` SVG the cycle page wheel uses, sized down to match a + * `ScoreRing size="sm"` (≈120 px) so the dial sits in the strip's tile + * rhythm; the tile chrome (hue-tinted `wellness-tile`, icon header, once-per- + * session reveal) mirrors the score `RingTile` exactly. + * + * It is NOT a second `` — that teaser (phase finding + + * deep-link) already lives further down the overview. This is the RING only, + * as a wellness dial. Both surfaces derive day-of-cycle + phase from the SAME + * `useCycleCalendar` read + `deriveWheelState`, so they can never disagree. + * + * GATING IS THE CALLER'S JOB. The page mounts this only when + * `user.cycleTrackingEnabled` is true (the same `/api/auth/me` signal the + * sidebar-nav entry + the summary card gate on), so the cycle read never fires + * for an account without the feature. The tile additionally renders nothing + * while the calendar read resolves, on a hard error, and when there is no + * active cycle phase today — never an empty-framed or half-painted dial in the + * strip (no gap, no placeholder). + */ + +/** YYYY-MM-DD for `n` days from now in the local tz (shares `localYmd`). */ +function shiftToday(days: number): string { + const d = new Date(); + d.setDate(d.getDate() + days); + return localYmd(d); +} + +export function CycleRingTile({ className }: { className?: string }) { + const { t } = useTranslations(); + + // Mirror the cycle-view + summary-card window so the cache key is shared — + // no extra request when the user opens the cycle page in the same session. + const today = useMemo(() => shiftToday(0), []); + const from = useMemo(() => shiftToday(-90), []); + const to = useMemo(() => shiftToday(180), []); + + const calendar = useCycleCalendar(from, to); + + const wheel = useMemo( + () => deriveWheelState(calendar.data?.days ?? [], today), + [calendar.data, today], + ); + + // The signature reveal plays ONCE per browser session, gated on its own key + // so a background calendar refetch never re-triggers the moment. The + // reduced-motion zeroing lives inside ``. + const [play] = useState(() => { + if (typeof window === "undefined") return false; + try { + if (sessionStorage.getItem("cycle-strip-ring-revealed")) return false; + sessionStorage.setItem("cycle-strip-ring-revealed", "1"); + return true; + } catch { + return true; + } + }); + + // Stay silent until the read resolves, on a hard error, and when today has + // no phase (no active cycle) — the strip must never show a half-painted or + // empty-framed cycle dial. The full cycle page owns the empty-state CTA. + if (calendar.isLoading && !calendar.data) return null; + if (calendar.isError && !calendar.data) return null; + if (wheel.phase == null || wheel.dayOfCycle == null) return null; + + const hue = PHASE_HUE[wheel.phase]; + + return ( + +
+
+
+ + + {t(`cycle.phase.${wheel.phase}`)} + +
+ + ); +} diff --git a/src/components/insights/derived/wellness-scores.tsx b/src/components/insights/derived/wellness-scores.tsx index d7e147803..2a04a4623 100644 --- a/src/components/insights/derived/wellness-scores.tsx +++ b/src/components/insights/derived/wellness-scores.tsx @@ -47,6 +47,16 @@ interface ScoreStripProps { isError?: boolean; /** Refetch the one shared batch query. Recovers both strips at once. */ refetch?: () => void; + /** + * An optional extra tile rendered as the LAST sibling inside the same scores + * grid (e.g. the gated cycle ring). It participates in the column-count math + * so it never leaves a dangling empty cell, and it keeps the strip mounted + * even when no wellness score has data (a cycle-only account still sees its + * dial). The caller owns the gating — the strip just slots whatever it gets. + * The element is expected to render `null` on its own when it has nothing to + * show, so the strip subtracts it from the count in that case. + */ + extraTile?: React.ReactNode; className?: string; } @@ -149,6 +159,7 @@ export function WellnessScores({ isLoading, isError = false, refetch, + extraTile, className, }: ScoreStripProps) { const { t } = useTranslations(); @@ -310,7 +321,23 @@ export function WellnessScores({ ); } - // Whole strip un-mounts when no score has data — never an empty section. + // The optional caller-supplied tile (e.g. the gated cycle ring) slots in as + // the last sibling. It is counted toward the grid column math so it never + // leaves a dangling cell, and its presence keeps the strip mounted even when + // no wellness score has data (a cycle-only account still sees its dial). The + // tile renders `null` on its own when it has nothing to show; the grid has + // no background, so a transient empty trailing cell shows nothing — never a + // "missing tile" frame. + if (extraTile != null) { + tiles.push( +
+ {extraTile} +
, + ); + } + + // Whole strip un-mounts when no score has data AND no extra tile — never an + // empty section. if (tiles.length === 0) return null; // v1.12.4 — the strip used a fixed `lg:grid-cols-5`, so the common case of