mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-18 16:12:11 +00:00
1200 lines
38 KiB
TypeScript
1200 lines
38 KiB
TypeScript
"use client";
|
||
|
||
import { useState } from "react";
|
||
import {
|
||
Activity,
|
||
BatteryLow,
|
||
Brain,
|
||
CircleDot,
|
||
Cookie,
|
||
Drama,
|
||
Droplet,
|
||
Droplets,
|
||
Flame,
|
||
Frown,
|
||
Heart,
|
||
HeartPulse,
|
||
Loader2,
|
||
MoonStar,
|
||
PersonStanding,
|
||
Pill,
|
||
Plus,
|
||
Snowflake,
|
||
Soup,
|
||
Stethoscope,
|
||
Tag,
|
||
Thermometer,
|
||
Trash2,
|
||
X,
|
||
Zap,
|
||
type LucideIcon,
|
||
} from "lucide-react";
|
||
|
||
import { cn } from "@/lib/utils";
|
||
import { Button } from "@/components/ui/button";
|
||
import { Input } from "@/components/ui/input";
|
||
import { Label } from "@/components/ui/label";
|
||
import { Switch } from "@/components/ui/switch";
|
||
import { Textarea } from "@/components/ui/textarea";
|
||
import {
|
||
Popover,
|
||
PopoverContent,
|
||
PopoverTrigger,
|
||
} from "@/components/ui/popover";
|
||
import { ResponsiveSheet } from "@/components/ui/responsive-sheet";
|
||
import {
|
||
SheetSection,
|
||
SheetSectionCount,
|
||
} from "@/components/ui/sheet-section";
|
||
import { useTranslations } from "@/lib/i18n/context";
|
||
import { CUSTOM_SYMPTOM_ICON_ALLOWLIST } from "@/lib/cycle/custom-symptoms-shared";
|
||
import { CYCLE_SYMPTOM_CATALOG } from "./symptom-catalog";
|
||
import { FLOW_HUE } from "./phase-tokens";
|
||
import {
|
||
useCreateCustomSymptom,
|
||
useCustomSymptoms,
|
||
useCycleDayLog,
|
||
useCycleProfile,
|
||
useDeleteCustomSymptom,
|
||
useDeleteDayLog,
|
||
useEndPeriod,
|
||
useLogDay,
|
||
usePatchDayLog,
|
||
useStartPeriod,
|
||
CustomSymptomError,
|
||
CUSTOM_SYMPTOM_LIMIT_ERROR_CODE,
|
||
type CustomSymptomDTO,
|
||
type CycleDayLogPatch,
|
||
} from "./use-cycle";
|
||
import type {
|
||
CervicalMucus,
|
||
CervixFirmness,
|
||
CervixOpening,
|
||
CervixPosition,
|
||
ContraceptiveKind,
|
||
CycleDayLogInput,
|
||
CycleSymptomSelection,
|
||
FlowLevel,
|
||
HomeTestResult,
|
||
OvulationTest,
|
||
} from "./types";
|
||
|
||
/**
|
||
* v1.15.0 — the fast-entry log-day sheet.
|
||
*
|
||
* One-tap "started my period today" posts the period-boundary shortcut; the
|
||
* detailed form posts a single day-log (flow, symptoms, BBT, OPK, mucus,
|
||
* intercourse + protection, free-text note). The write is optimistic-ish
|
||
* (the mutation invalidates the cycle keys on success so the calendar +
|
||
* wheel repaint); the symptom chips reuse the mood-tag chip styling.
|
||
*
|
||
* a11y: every chip is a real `<button>` with `aria-pressed`; the sheet
|
||
* footer sticky-pins Save/Cancel.
|
||
*/
|
||
|
||
const FLOW_LEVELS: FlowLevel[] = ["SPOTTING", "LIGHT", "MEDIUM", "HEAVY"];
|
||
const OPK_VALUES: OvulationTest[] = [
|
||
"NEGATIVE",
|
||
"POSITIVE_LH_SURGE",
|
||
"ESTROGEN_SURGE",
|
||
"INDETERMINATE",
|
||
];
|
||
const MUCUS_VALUES: CervicalMucus[] = [
|
||
"DRY",
|
||
"STICKY",
|
||
"CREAMY",
|
||
"WATERY",
|
||
"EGG_WHITE",
|
||
];
|
||
const CERVIX_POSITION_VALUES: CervixPosition[] = ["LOW", "HIGH"];
|
||
const CERVIX_FIRMNESS_VALUES: CervixFirmness[] = ["FIRM", "SOFT"];
|
||
const CERVIX_OPENING_VALUES: CervixOpening[] = ["CLOSED", "OPEN"];
|
||
const TEST_RESULTS: HomeTestResult[] = [
|
||
"POSITIVE",
|
||
"NEGATIVE",
|
||
"INDETERMINATE",
|
||
];
|
||
const CONTRACEPTIVE_KINDS: ContraceptiveKind[] = [
|
||
"ORAL",
|
||
"IUD",
|
||
"IMPLANT",
|
||
"INJECTION",
|
||
"INTRAVAGINAL_RING",
|
||
"PATCH",
|
||
"EMERGENCY",
|
||
"NONE",
|
||
];
|
||
const SEVERITY_LEVELS = [1, 2, 3, 4] as const;
|
||
|
||
/**
|
||
* Resolve a custom symptom's stored Lucide icon NAME to its component. Scoped
|
||
* to the `CUSTOM_SYMPTOM_ICON_ALLOWLIST` (server-validated on create) so the
|
||
* import set stays tight; an unknown / null name falls back to `Tag`.
|
||
*/
|
||
const CUSTOM_ICON_BY_NAME: Record<string, LucideIcon> = {
|
||
Tag,
|
||
Activity,
|
||
Heart,
|
||
HeartPulse,
|
||
Brain,
|
||
Zap,
|
||
Flame,
|
||
Snowflake,
|
||
Droplet,
|
||
CircleDot,
|
||
BatteryLow,
|
||
MoonStar,
|
||
PersonStanding,
|
||
Drama,
|
||
Frown,
|
||
Cookie,
|
||
Soup,
|
||
Pill,
|
||
Thermometer,
|
||
Stethoscope,
|
||
};
|
||
|
||
function customIcon(name: string | null): LucideIcon {
|
||
return (name && CUSTOM_ICON_BY_NAME[name]) || Tag;
|
||
}
|
||
|
||
/** The sheet's editable form state, lifted out so the two save-payload builders
|
||
* are pure + unit-testable (the clear-on-edit semantics are the QA W-2 fix). */
|
||
export interface DayLogFormState {
|
||
flow: FlowLevel | null;
|
||
intermenstrual: boolean;
|
||
/** Raw text from the BBT input; "" / non-finite resolves to null. */
|
||
bbt: string;
|
||
/** Whether the BBT reading is marked disturbed (fever/late) — engine skips it. */
|
||
bbtDisturbed: boolean;
|
||
opk: OvulationTest | null;
|
||
mucus: CervicalMucus | null;
|
||
cervixPosition: CervixPosition | null;
|
||
cervixFirmness: CervixFirmness | null;
|
||
cervixOpening: CervixOpening | null;
|
||
intercourse: boolean;
|
||
protectedSex: boolean;
|
||
pregnancyTest: HomeTestResult | null;
|
||
progesteroneTest: HomeTestResult | null;
|
||
contraceptive: ContraceptiveKind | null;
|
||
note: string;
|
||
symptoms: Map<string, number | null>;
|
||
}
|
||
|
||
function resolveBbt(bbt: string): number | null {
|
||
const n = bbt.trim() === "" ? null : Number(bbt);
|
||
return n != null && Number.isFinite(n) ? n : null;
|
||
}
|
||
|
||
function symptomList(
|
||
symptoms: Map<string, number | null>,
|
||
): CycleSymptomSelection[] {
|
||
return Array.from(symptoms.entries()).map(([key, severity]) => ({
|
||
key,
|
||
severity,
|
||
}));
|
||
}
|
||
|
||
/**
|
||
* The PATCH payload for an EDIT: every enum carries an explicit `null` when
|
||
* deselected so the server clears it (the POST merge can only add/keep — QA
|
||
* W-2). Pure + exported for the unit test.
|
||
*/
|
||
export function buildDayLogPatch(s: DayLogFormState): CycleDayLogPatch {
|
||
return {
|
||
flow: s.flow ?? null,
|
||
intermenstrualBleeding: s.intermenstrual,
|
||
basalBodyTempC: resolveBbt(s.bbt),
|
||
// Only meaningful with a BBT present; a cleared reading resets the flag.
|
||
temperatureExcluded: resolveBbt(s.bbt) != null ? s.bbtDisturbed : false,
|
||
ovulationTest: s.opk ?? null,
|
||
cervicalMucus: s.mucus ?? null,
|
||
cervixPosition: s.cervixPosition ?? null,
|
||
cervixFirmness: s.cervixFirmness ?? null,
|
||
cervixOpening: s.cervixOpening ?? null,
|
||
sexualActivity: s.intercourse,
|
||
protectedSex: s.intercourse ? s.protectedSex : null,
|
||
pregnancyTest: s.pregnancyTest ?? null,
|
||
progesteroneTest: s.progesteroneTest ?? null,
|
||
contraceptive: s.contraceptive ?? null,
|
||
symptoms: symptomList(s.symptoms),
|
||
note: s.note.trim() ? s.note.trim() : null,
|
||
};
|
||
}
|
||
|
||
/** The POST payload for a NEW row: omit empty enums (a fresh row has nothing to
|
||
* clear); `note` posts an explicit "" so an emptied note never persists. */
|
||
export function buildDayLogInput(
|
||
s: DayLogFormState,
|
||
date: string,
|
||
): CycleDayLogInput {
|
||
const bbtVal = resolveBbt(s.bbt);
|
||
return {
|
||
date,
|
||
loggedAt: new Date().toISOString(),
|
||
source: "MANUAL",
|
||
...(s.flow ? { flow: s.flow } : {}),
|
||
intermenstrualBleeding: s.intermenstrual,
|
||
...(bbtVal != null
|
||
? { basalBodyTempC: bbtVal, temperatureExcluded: s.bbtDisturbed }
|
||
: {}),
|
||
...(s.opk ? { ovulationTest: s.opk } : {}),
|
||
...(s.mucus ? { cervicalMucus: s.mucus } : {}),
|
||
...(s.cervixPosition ? { cervixPosition: s.cervixPosition } : {}),
|
||
...(s.cervixFirmness ? { cervixFirmness: s.cervixFirmness } : {}),
|
||
...(s.cervixOpening ? { cervixOpening: s.cervixOpening } : {}),
|
||
sexualActivity: s.intercourse,
|
||
protectedSex: s.intercourse ? s.protectedSex : null,
|
||
...(s.pregnancyTest ? { pregnancyTest: s.pregnancyTest } : {}),
|
||
...(s.progesteroneTest ? { progesteroneTest: s.progesteroneTest } : {}),
|
||
...(s.contraceptive ? { contraceptive: s.contraceptive } : {}),
|
||
symptoms: symptomList(s.symptoms),
|
||
...(s.note.trim() ? { note: s.note.trim() } : { note: "" }),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* v1.17.0 — section summary-badge counts for the sectioned log-day sheet.
|
||
*
|
||
* Each helper reports how many fields a collapsed section holds, so the
|
||
* badge communicates its contents without expanding it. Pure + exported
|
||
* for the unit tests.
|
||
*/
|
||
export function symptomsCount(s: DayLogFormState): number {
|
||
return s.symptoms.size;
|
||
}
|
||
|
||
/**
|
||
* Temperature & ovulation: BBT reading, OPK, and the symptothermal secondary
|
||
* sign. Only the sign the section actually renders is counted — mucus when
|
||
* `showCervix` is false, the three cervix observations when true — so the
|
||
* badge never reports a stale value from the surface that isn't shown (e.g.
|
||
* after the user flips the advanced-settings secondary-symptom choice).
|
||
*/
|
||
export function temperatureCount(
|
||
s: DayLogFormState,
|
||
showCervix: boolean,
|
||
): number {
|
||
let n = 0;
|
||
if (resolveBbt(s.bbt) != null) n += 1;
|
||
if (s.opk) n += 1;
|
||
if (showCervix) {
|
||
if (s.cervixPosition) n += 1;
|
||
if (s.cervixFirmness) n += 1;
|
||
if (s.cervixOpening) n += 1;
|
||
} else if (s.mucus) {
|
||
n += 1;
|
||
}
|
||
return n;
|
||
}
|
||
|
||
/** Intimacy & contraception: intercourse logged, and any contraceptive. */
|
||
export function intimacyCount(s: DayLogFormState): number {
|
||
let n = 0;
|
||
if (s.intercourse) n += 1;
|
||
if (s.contraceptive) n += 1;
|
||
return n;
|
||
}
|
||
|
||
/** Tests: pregnancy + progesterone home-test results. */
|
||
export function testsCount(s: DayLogFormState): number {
|
||
let n = 0;
|
||
if (s.pregnancyTest) n += 1;
|
||
if (s.progesteroneTest) n += 1;
|
||
return n;
|
||
}
|
||
|
||
/** Note: 1 when the free-text note carries content. */
|
||
export function noteCount(s: DayLogFormState): number {
|
||
return s.note.trim() ? 1 : 0;
|
||
}
|
||
|
||
export interface LogDaySheetProps {
|
||
open: boolean;
|
||
onOpenChange: (open: boolean) => void;
|
||
/** The date being logged (YYYY-MM-DD). */
|
||
date: string;
|
||
/** Today (YYYY-MM-DD). */
|
||
today: string;
|
||
/**
|
||
* Whether a period is currently open (today is in the MENSTRUAL phase) — gates
|
||
* the one-tap "end period" affordance so it never shows when no period is in
|
||
* progress (QA M2).
|
||
*/
|
||
activePeriod?: boolean;
|
||
}
|
||
|
||
function Chip({
|
||
active,
|
||
onClick,
|
||
children,
|
||
}: {
|
||
active: boolean;
|
||
onClick: () => void;
|
||
children: React.ReactNode;
|
||
}) {
|
||
return (
|
||
<button
|
||
type="button"
|
||
aria-pressed={active}
|
||
onClick={onClick}
|
||
className={cn(
|
||
"focus-visible:ring-ring/50 rounded-full border px-3 py-1.5 text-sm transition-colors focus-visible:ring-2 focus-visible:outline-none",
|
||
active
|
||
? "border-primary bg-primary/10 text-primary"
|
||
: "border-border text-foreground hover:bg-accent",
|
||
)}
|
||
>
|
||
{children}
|
||
</button>
|
||
);
|
||
}
|
||
|
||
/** One labelled row of cervix-sign chips (position / firmness / opening). */
|
||
function CervixRow<T extends string>({
|
||
label,
|
||
values,
|
||
current,
|
||
labelFor,
|
||
onToggle,
|
||
}: {
|
||
label: string;
|
||
values: readonly T[];
|
||
current: T | null;
|
||
labelFor: (v: T) => string;
|
||
onToggle: (v: T) => void;
|
||
}) {
|
||
return (
|
||
<div className="space-y-1.5">
|
||
<p className="text-muted-foreground text-xs font-medium">{label}</p>
|
||
<div className="flex flex-wrap gap-2">
|
||
{values.map((v) => (
|
||
<Chip key={v} active={current === v} onClick={() => onToggle(v)}>
|
||
{labelFor(v)}
|
||
</Chip>
|
||
))}
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
export function LogDaySheet({
|
||
open,
|
||
onOpenChange,
|
||
date,
|
||
activePeriod = false,
|
||
}: LogDaySheetProps) {
|
||
const { t } = useTranslations();
|
||
const logDay = useLogDay();
|
||
const patchDay = usePatchDayLog();
|
||
const startPeriod = useStartPeriod();
|
||
const endPeriod = useEndPeriod();
|
||
const deleteDay = useDeleteDayLog();
|
||
// Pre-fill from the persisted day-log so a re-log never nulls untouched
|
||
// (or HealthKit-sourced) fields — the v1.15 web data-loss fix.
|
||
const dayLog = useCycleDayLog(open ? date : null);
|
||
// The caller's custom symptoms, merged into the seeded chip grid.
|
||
const customSymptoms = useCustomSymptoms();
|
||
// Drives which symptothermal secondary sign the sheet offers — mucus (default)
|
||
// or the cervix pickers (progressive disclosure: cervix entry only appears
|
||
// when the user chose CERVIX in the advanced cycle settings).
|
||
const cycleProfile = useCycleProfile();
|
||
const showCervix = cycleProfile.data?.secondarySymptom === "CERVIX";
|
||
|
||
const [flow, setFlow] = useState<FlowLevel | null>(null);
|
||
const [intermenstrual, setIntermenstrual] = useState(false);
|
||
const [symptoms, setSymptoms] = useState<Map<string, number | null>>(
|
||
new Map(),
|
||
);
|
||
const [bbt, setBbt] = useState<string>("");
|
||
const [bbtDisturbed, setBbtDisturbed] = useState(false);
|
||
const [opk, setOpk] = useState<OvulationTest | null>(null);
|
||
const [mucus, setMucus] = useState<CervicalMucus | null>(null);
|
||
const [cervixPosition, setCervixPosition] = useState<CervixPosition | null>(
|
||
null,
|
||
);
|
||
const [cervixFirmness, setCervixFirmness] = useState<CervixFirmness | null>(
|
||
null,
|
||
);
|
||
const [cervixOpening, setCervixOpening] = useState<CervixOpening | null>(null);
|
||
const [intercourse, setIntercourse] = useState(false);
|
||
const [protectedSex, setProtectedSex] = useState(false);
|
||
const [pregnancyTest, setPregnancyTest] = useState<HomeTestResult | null>(
|
||
null,
|
||
);
|
||
const [progesteroneTest, setProgesteroneTest] =
|
||
useState<HomeTestResult | null>(null);
|
||
const [contraceptive, setContraceptive] = useState<ContraceptiveKind | null>(
|
||
null,
|
||
);
|
||
const [note, setNote] = useState("");
|
||
const [rowId, setRowId] = useState<string | null>(null);
|
||
|
||
// Hydrate the form from the fetched DTO once per (open, date, fetched-row)
|
||
// tuple. Tracked as an "adjust state when a prop changes" during render
|
||
// (React's recommended alternative to a setState-in-effect) keyed on the
|
||
// open+date+row-identity, so a re-open or a late-arriving fetch repaints the
|
||
// controls exactly once. `dto === null` (nothing logged) resets to blank.
|
||
const dto = open ? (dayLog.data ?? null) : undefined;
|
||
const formKey = open
|
||
? `${date}:${dayLog.isSuccess ? "loaded" : "loading"}`
|
||
: null;
|
||
const [lastFormKey, setLastFormKey] = useState<string | null>(null);
|
||
if (open && formKey !== lastFormKey && !dayLog.isLoading) {
|
||
setLastFormKey(formKey);
|
||
setRowId(dto?.id ?? null);
|
||
setFlow((dto?.flow ?? null) as FlowLevel | null);
|
||
setIntermenstrual(dto?.intermenstrualBleeding ?? false);
|
||
setSymptoms(new Map((dto?.symptoms ?? []).map((s) => [s.key, s.severity])));
|
||
setBbt(dto?.basalBodyTempC != null ? String(dto.basalBodyTempC) : "");
|
||
setBbtDisturbed(dto?.temperatureExcluded ?? false);
|
||
setOpk((dto?.ovulationTest ?? null) as OvulationTest | null);
|
||
setMucus((dto?.cervicalMucus ?? null) as CervicalMucus | null);
|
||
setCervixPosition((dto?.cervixPosition ?? null) as CervixPosition | null);
|
||
setCervixFirmness((dto?.cervixFirmness ?? null) as CervixFirmness | null);
|
||
setCervixOpening((dto?.cervixOpening ?? null) as CervixOpening | null);
|
||
setIntercourse(dto?.sexualActivity ?? false);
|
||
setProtectedSex(dto?.protectedSex ?? false);
|
||
setPregnancyTest(dto?.pregnancyTest ?? null);
|
||
setProgesteroneTest(dto?.progesteroneTest ?? null);
|
||
setContraceptive(dto?.contraceptive ?? null);
|
||
setNote(dto?.note ?? "");
|
||
} else if (!open && lastFormKey !== null) {
|
||
setLastFormKey(null);
|
||
}
|
||
|
||
function toggleSymptom(key: string) {
|
||
setSymptoms((prev) => {
|
||
const next = new Map(prev);
|
||
if (next.has(key)) next.delete(key);
|
||
else next.set(key, null);
|
||
return next;
|
||
});
|
||
}
|
||
|
||
function setSymptomSeverity(key: string, severity: number) {
|
||
setSymptoms((prev) => {
|
||
const next = new Map(prev);
|
||
// Tapping the active level clears it back to a plain presence link.
|
||
next.set(key, next.get(key) === severity ? null : severity);
|
||
return next;
|
||
});
|
||
}
|
||
|
||
// The live form state, shared by the save-payload builders and the section
|
||
// summary badges (so a collapsed section reports what it holds).
|
||
const formState: DayLogFormState = {
|
||
flow,
|
||
intermenstrual,
|
||
bbt,
|
||
bbtDisturbed,
|
||
opk,
|
||
mucus,
|
||
cervixPosition,
|
||
cervixFirmness,
|
||
cervixOpening,
|
||
intercourse,
|
||
protectedSex,
|
||
pregnancyTest,
|
||
progesteroneTest,
|
||
contraceptive,
|
||
note,
|
||
symptoms,
|
||
};
|
||
|
||
async function handleSave() {
|
||
// v1.16.4 — catch so a rejected save doesn't escape as an unhandled
|
||
// rejection; the inline `logDay.isError || patchDay.isError` strip in the
|
||
// footer carries the visible failure signal and the sheet stays open.
|
||
try {
|
||
if (rowId) {
|
||
// Editing an existing row → PATCH with explicit nulls so a deselected
|
||
// chip actually CLEARS (the POST merge can only add/keep — QA W-2).
|
||
await patchDay.mutateAsync({
|
||
id: rowId,
|
||
patch: buildDayLogPatch(formState),
|
||
});
|
||
} else {
|
||
await logDay.mutateAsync(buildDayLogInput(formState, date));
|
||
}
|
||
onOpenChange(false);
|
||
} catch {
|
||
/* surfaced via the inline isError strip */
|
||
}
|
||
}
|
||
|
||
// Period boundaries operate on the SELECTED date, so a forgotten day-1 can be
|
||
// corrected from the calendar retroactively (QA M3) — not today-only.
|
||
// v1.16.4 — the rejection is surfaced as a toast by the hook's onError;
|
||
// catching here keeps the sheet open without an unhandled rejection.
|
||
async function handleStartPeriod() {
|
||
try {
|
||
await startPeriod.mutateAsync(date);
|
||
onOpenChange(false);
|
||
} catch {
|
||
/* toast shown by useStartPeriod onError */
|
||
}
|
||
}
|
||
|
||
async function handleEndPeriod() {
|
||
try {
|
||
await endPeriod.mutateAsync(date);
|
||
onOpenChange(false);
|
||
} catch {
|
||
/* toast shown by useEndPeriod onError */
|
||
}
|
||
}
|
||
|
||
async function handleDelete() {
|
||
if (!rowId) return;
|
||
try {
|
||
await deleteDay.mutateAsync(rowId);
|
||
onOpenChange(false);
|
||
} catch {
|
||
/* toast shown by useDeleteDayLog onError */
|
||
}
|
||
}
|
||
|
||
const busy =
|
||
logDay.isPending ||
|
||
patchDay.isPending ||
|
||
startPeriod.isPending ||
|
||
endPeriod.isPending ||
|
||
deleteDay.isPending;
|
||
const saving = logDay.isPending || patchDay.isPending;
|
||
|
||
return (
|
||
<ResponsiveSheet
|
||
open={open}
|
||
onOpenChange={onOpenChange}
|
||
title={t("cycle.sheet.title")}
|
||
description={t("cycle.sheet.description")}
|
||
footer={
|
||
<>
|
||
{rowId ? (
|
||
<Button
|
||
variant="outline"
|
||
onClick={handleDelete}
|
||
disabled={busy}
|
||
className="text-destructive hover:text-destructive mr-auto"
|
||
aria-label={t("cycle.sheet.delete")}
|
||
>
|
||
{deleteDay.isPending ? (
|
||
<Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" />
|
||
) : (
|
||
<Trash2 className="h-4 w-4" />
|
||
)}
|
||
{t("cycle.sheet.delete")}
|
||
</Button>
|
||
) : null}
|
||
<Button
|
||
variant="outline"
|
||
onClick={() => onOpenChange(false)}
|
||
disabled={busy}
|
||
>
|
||
{t("cycle.sheet.cancel")}
|
||
</Button>
|
||
<Button onClick={handleSave} disabled={busy}>
|
||
{saving ? (
|
||
<Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" />
|
||
) : null}
|
||
{saving ? t("cycle.sheet.saving") : t("cycle.sheet.save")}
|
||
</Button>
|
||
</>
|
||
}
|
||
>
|
||
{/* One-tap period boundaries — available on any selected date so a
|
||
forgotten day-1 can be corrected retroactively (M3). "End period"
|
||
shows only while a period is actually open (M2). */}
|
||
<div className="flex flex-wrap gap-2">
|
||
<Button
|
||
variant="outline"
|
||
className="flex-1 justify-start gap-2"
|
||
onClick={handleStartPeriod}
|
||
disabled={busy}
|
||
style={{ borderColor: FLOW_HUE }}
|
||
>
|
||
{startPeriod.isPending ? (
|
||
<Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" />
|
||
) : (
|
||
<Droplets className="h-4 w-4" style={{ color: FLOW_HUE }} />
|
||
)}
|
||
{t("cycle.startedPeriod")}
|
||
</Button>
|
||
{activePeriod ? (
|
||
<Button
|
||
variant="outline"
|
||
className="flex-1 justify-start gap-2"
|
||
onClick={handleEndPeriod}
|
||
disabled={busy}
|
||
>
|
||
{endPeriod.isPending ? (
|
||
<Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" />
|
||
) : null}
|
||
{t("cycle.endedPeriod")}
|
||
</Button>
|
||
) : null}
|
||
</div>
|
||
|
||
{/* Quick row — Flow is the single most common period sign, so it
|
||
stays always-open at the top alongside the intermenstrual toggle.
|
||
Everything else lives in collapsible sections below. */}
|
||
<Field label={t("cycle.sheet.flow")}>
|
||
<div className="flex flex-wrap gap-2">
|
||
{FLOW_LEVELS.map((f) => (
|
||
<Chip
|
||
key={f}
|
||
active={flow === f}
|
||
onClick={() => setFlow((cur) => (cur === f ? null : f))}
|
||
>
|
||
{t(`cycle.flow.${f}`)}
|
||
</Chip>
|
||
))}
|
||
</div>
|
||
<div className="mt-2 flex items-center justify-between">
|
||
<Label htmlFor="cycle-intermenstrual" className="text-sm font-normal">
|
||
{t("cycle.sheet.intermenstrualBleeding")}
|
||
</Label>
|
||
<Switch
|
||
id="cycle-intermenstrual"
|
||
checked={intermenstrual}
|
||
onCheckedChange={setIntermenstrual}
|
||
/>
|
||
</div>
|
||
</Field>
|
||
|
||
{/* Symptoms */}
|
||
<SheetSection
|
||
title={t("cycle.sheet.symptoms")}
|
||
summary={<SheetSectionCount count={symptomsCount(formState)} />}
|
||
>
|
||
<div className="space-y-3">
|
||
{CYCLE_SYMPTOM_CATALOG.map((cat) => (
|
||
<div key={cat.key} className="space-y-1.5">
|
||
<div className="text-muted-foreground flex items-center gap-1.5 text-xs font-medium">
|
||
<cat.icon className="h-3.5 w-3.5" aria-hidden="true" />
|
||
{t(cat.labelKey)}
|
||
</div>
|
||
<div className="flex flex-wrap gap-2">
|
||
{cat.symptoms.map((s) => (
|
||
<SymptomChip
|
||
key={s.key}
|
||
symptomKey={s.key}
|
||
icon={s.icon}
|
||
label={t(s.labelKey)}
|
||
active={symptoms.has(s.key)}
|
||
severity={symptoms.get(s.key) ?? null}
|
||
onToggle={toggleSymptom}
|
||
onSeverity={setSymptomSeverity}
|
||
/>
|
||
))}
|
||
</div>
|
||
</div>
|
||
))}
|
||
|
||
{/* Custom symptoms — the user's own, under a `custom` category,
|
||
plus the dashed ghost-chip that mints a new one. */}
|
||
<div className="space-y-1.5">
|
||
<div className="text-muted-foreground flex items-center gap-1.5 text-xs font-medium">
|
||
<Tag className="h-3.5 w-3.5" aria-hidden="true" />
|
||
{t("cycle.symptomCategory.custom")}
|
||
</div>
|
||
<div className="flex flex-wrap gap-2">
|
||
{(customSymptoms.data?.symptoms ?? []).map((s) => (
|
||
<SymptomChip
|
||
key={s.key}
|
||
symptomKey={s.key}
|
||
icon={customIcon(s.icon)}
|
||
label={s.label ?? t("cycle.symptom.custom.fallbackLabel")}
|
||
active={symptoms.has(s.key)}
|
||
severity={symptoms.get(s.key) ?? null}
|
||
custom={s}
|
||
onToggle={toggleSymptom}
|
||
onSeverity={setSymptomSeverity}
|
||
onClear={(key) => {
|
||
setSymptoms((prev) => {
|
||
const next = new Map(prev);
|
||
next.delete(key);
|
||
return next;
|
||
});
|
||
}}
|
||
/>
|
||
))}
|
||
<AddSymptomChip onCreated={toggleSymptom} />
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</SheetSection>
|
||
|
||
{/* Temperature & ovulation — BBT, OPK, and the symptothermal secondary
|
||
sign (mucus or cervix) grouped under one disclosure. */}
|
||
<SheetSection
|
||
title={t("cycle.sheet.temperatureSection")}
|
||
summary={
|
||
<SheetSectionCount count={temperatureCount(formState, showCervix)} />
|
||
}
|
||
>
|
||
{/* BBT */}
|
||
<Field label={t("cycle.sheet.temperature")}>
|
||
<input
|
||
type="number"
|
||
inputMode="decimal"
|
||
step="0.01"
|
||
min={30}
|
||
max={45}
|
||
value={bbt}
|
||
onChange={(e) => setBbt(e.target.value)}
|
||
placeholder={t("cycle.sheet.temperaturePlaceholder")}
|
||
className="border-input bg-background focus-visible:ring-ring/50 w-32 rounded-md border px-3 py-2 text-sm focus-visible:ring-2 focus-visible:outline-none"
|
||
aria-label={t("cycle.sheet.temperature")}
|
||
/>
|
||
{resolveBbt(bbt) != null && (
|
||
<div className="mt-3 flex items-start justify-between gap-3">
|
||
<div className="flex flex-col">
|
||
<span className="text-sm">
|
||
{t("cycle.sheet.temperatureDisturbed")}
|
||
</span>
|
||
<span className="text-muted-foreground text-xs">
|
||
{t("cycle.sheet.temperatureDisturbedHint")}
|
||
</span>
|
||
</div>
|
||
<Switch
|
||
checked={bbtDisturbed}
|
||
onCheckedChange={setBbtDisturbed}
|
||
aria-label={t("cycle.sheet.temperatureDisturbed")}
|
||
/>
|
||
</div>
|
||
)}
|
||
</Field>
|
||
|
||
{/* Ovulation test */}
|
||
<Field label={t("cycle.sheet.ovulationTest")}>
|
||
<div className="flex flex-wrap gap-2">
|
||
{OPK_VALUES.map((v) => (
|
||
<Chip
|
||
key={v}
|
||
active={opk === v}
|
||
onClick={() => setOpk((cur) => (cur === v ? null : v))}
|
||
>
|
||
{t(`cycle.ovulationTest.${v}`)}
|
||
</Chip>
|
||
))}
|
||
</div>
|
||
</Field>
|
||
|
||
{/* Symptothermal secondary symptom: cervical mucus (default) OR the
|
||
cervix observation, per the user's advanced-settings choice. Only one
|
||
of the two is offered so the log sheet never overwhelms. */}
|
||
{showCervix ? (
|
||
<Field label={t("cycle.sheet.cervix")}>
|
||
<div className="space-y-3">
|
||
<CervixRow
|
||
label={t("cycle.sheet.cervixPosition")}
|
||
values={CERVIX_POSITION_VALUES}
|
||
current={cervixPosition}
|
||
labelFor={(v) => t(`cycle.cervixPosition.${v}`)}
|
||
onToggle={(v) =>
|
||
setCervixPosition((cur) => (cur === v ? null : v))
|
||
}
|
||
/>
|
||
<CervixRow
|
||
label={t("cycle.sheet.cervixFirmness")}
|
||
values={CERVIX_FIRMNESS_VALUES}
|
||
current={cervixFirmness}
|
||
labelFor={(v) => t(`cycle.cervixFirmness.${v}`)}
|
||
onToggle={(v) =>
|
||
setCervixFirmness((cur) => (cur === v ? null : v))
|
||
}
|
||
/>
|
||
<CervixRow
|
||
label={t("cycle.sheet.cervixOpening")}
|
||
values={CERVIX_OPENING_VALUES}
|
||
current={cervixOpening}
|
||
labelFor={(v) => t(`cycle.cervixOpening.${v}`)}
|
||
onToggle={(v) =>
|
||
setCervixOpening((cur) => (cur === v ? null : v))
|
||
}
|
||
/>
|
||
</div>
|
||
</Field>
|
||
) : (
|
||
<Field label={t("cycle.sheet.mucus")}>
|
||
<div className="flex flex-wrap gap-2">
|
||
{MUCUS_VALUES.map((v) => (
|
||
<Chip
|
||
key={v}
|
||
active={mucus === v}
|
||
onClick={() => setMucus((cur) => (cur === v ? null : v))}
|
||
>
|
||
{t(`cycle.mucus.${v}`)}
|
||
</Chip>
|
||
))}
|
||
</div>
|
||
</Field>
|
||
)}
|
||
</SheetSection>
|
||
|
||
{/* Intimacy & contraception */}
|
||
<SheetSection
|
||
title={t("cycle.sheet.intimacySection")}
|
||
summary={<SheetSectionCount count={intimacyCount(formState)} />}
|
||
>
|
||
{/* Intercourse + protection */}
|
||
<Field label={t("cycle.sheet.intercourse")}>
|
||
<div className="space-y-2">
|
||
<div className="flex items-center justify-between">
|
||
<Label htmlFor="cycle-intercourse" className="text-sm font-normal">
|
||
{t("cycle.sheet.intercourse")}
|
||
</Label>
|
||
<Switch
|
||
id="cycle-intercourse"
|
||
checked={intercourse}
|
||
onCheckedChange={setIntercourse}
|
||
/>
|
||
</div>
|
||
{intercourse ? (
|
||
<div className="flex items-center justify-between">
|
||
<Label
|
||
htmlFor="cycle-protected"
|
||
className="text-muted-foreground text-sm font-normal"
|
||
>
|
||
{t("cycle.sheet.protected")}
|
||
</Label>
|
||
<Switch
|
||
id="cycle-protected"
|
||
checked={protectedSex}
|
||
onCheckedChange={setProtectedSex}
|
||
/>
|
||
</div>
|
||
) : null}
|
||
</div>
|
||
</Field>
|
||
|
||
{/* Contraceptive */}
|
||
<Field label={t("cycle.sheet.contraceptive")}>
|
||
<div className="flex flex-wrap gap-2">
|
||
{CONTRACEPTIVE_KINDS.map((v) => (
|
||
<Chip
|
||
key={v}
|
||
active={contraceptive === v}
|
||
onClick={() =>
|
||
setContraceptive((cur) => (cur === v ? null : v))
|
||
}
|
||
>
|
||
{t(`cycle.contraceptive.${v}`)}
|
||
</Chip>
|
||
))}
|
||
</div>
|
||
</Field>
|
||
</SheetSection>
|
||
|
||
{/* Tests */}
|
||
<SheetSection
|
||
title={t("cycle.sheet.testsSection")}
|
||
summary={<SheetSectionCount count={testsCount(formState)} />}
|
||
>
|
||
{/* Pregnancy test */}
|
||
<Field label={t("cycle.sheet.pregnancyTest")}>
|
||
<div className="flex flex-wrap gap-2">
|
||
{TEST_RESULTS.map((v) => (
|
||
<Chip
|
||
key={v}
|
||
active={pregnancyTest === v}
|
||
onClick={() =>
|
||
setPregnancyTest((cur) => (cur === v ? null : v))
|
||
}
|
||
>
|
||
{t(`cycle.testResult.${v}`)}
|
||
</Chip>
|
||
))}
|
||
</div>
|
||
</Field>
|
||
|
||
{/* Progesterone test */}
|
||
<Field label={t("cycle.sheet.progesteroneTest")}>
|
||
<div className="flex flex-wrap gap-2">
|
||
{TEST_RESULTS.map((v) => (
|
||
<Chip
|
||
key={v}
|
||
active={progesteroneTest === v}
|
||
onClick={() =>
|
||
setProgesteroneTest((cur) => (cur === v ? null : v))
|
||
}
|
||
>
|
||
{t(`cycle.testResult.${v}`)}
|
||
</Chip>
|
||
))}
|
||
</div>
|
||
</Field>
|
||
</SheetSection>
|
||
|
||
{/* Note */}
|
||
<SheetSection
|
||
title={t("cycle.sheet.note")}
|
||
summary={<SheetSectionCount count={noteCount(formState)} />}
|
||
>
|
||
<Textarea
|
||
value={note}
|
||
onChange={(e) => setNote(e.target.value)}
|
||
maxLength={500}
|
||
rows={3}
|
||
placeholder={t("cycle.sheet.notePlaceholder")}
|
||
aria-label={t("cycle.sheet.note")}
|
||
/>
|
||
</SheetSection>
|
||
|
||
{logDay.isError || patchDay.isError ? (
|
||
<p className="text-destructive text-sm" role="alert">
|
||
{t("cycle.sheet.saveError")}
|
||
</p>
|
||
) : null}
|
||
</ResponsiveSheet>
|
||
);
|
||
}
|
||
|
||
function Field({
|
||
label,
|
||
children,
|
||
}: {
|
||
label: string;
|
||
children: React.ReactNode;
|
||
}) {
|
||
return (
|
||
<div className="space-y-2">
|
||
<p className="text-sm font-medium">{label}</p>
|
||
{children}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/**
|
||
* One symptom chip + its inline 1-4 severity selector (shared by the seeded
|
||
* catalogue chips and the custom chips so both render identically). A custom
|
||
* chip additionally carries a tiny remove (×) affordance that soft-hides the
|
||
* symptom from the catalogue.
|
||
*/
|
||
function SymptomChip({
|
||
symptomKey,
|
||
icon: Icon,
|
||
label,
|
||
active,
|
||
severity,
|
||
custom,
|
||
onToggle,
|
||
onSeverity,
|
||
onClear,
|
||
}: {
|
||
symptomKey: string;
|
||
icon: LucideIcon;
|
||
label: string;
|
||
active: boolean;
|
||
severity: number | null;
|
||
custom?: CustomSymptomDTO;
|
||
onToggle: (key: string) => void;
|
||
onSeverity: (key: string, severity: number) => void;
|
||
onClear?: (key: string) => void;
|
||
}) {
|
||
const { t } = useTranslations();
|
||
const deleteCustom = useDeleteCustomSymptom();
|
||
|
||
async function handleRemove() {
|
||
if (!custom) return;
|
||
onClear?.(custom.key);
|
||
try {
|
||
await deleteCustom.mutateAsync(custom.key);
|
||
} catch {
|
||
/* toast shown by useDeleteCustomSymptom onError */
|
||
}
|
||
}
|
||
|
||
return (
|
||
<div className="flex items-center gap-1">
|
||
<span className="relative inline-flex items-center">
|
||
<Chip active={active} onClick={() => onToggle(symptomKey)}>
|
||
<span className="flex items-center gap-1.5">
|
||
<Icon className="h-3.5 w-3.5" aria-hidden="true" />
|
||
{label}
|
||
</span>
|
||
</Chip>
|
||
{custom ? (
|
||
<button
|
||
type="button"
|
||
onClick={handleRemove}
|
||
disabled={deleteCustom.isPending}
|
||
aria-label={t("cycle.symptom.custom.remove", { label })}
|
||
className="border-border bg-background text-muted-foreground hover:text-destructive hover:border-destructive focus-visible:ring-ring/50 -ml-1.5 grid size-4 shrink-0 place-items-center rounded-full border transition-colors focus-visible:ring-2 focus-visible:outline-none"
|
||
>
|
||
<X className="size-2.5" aria-hidden="true" />
|
||
</button>
|
||
) : null}
|
||
</span>
|
||
{active ? (
|
||
<div
|
||
className="flex gap-0.5"
|
||
role="group"
|
||
aria-label={t("cycle.sheet.severity")}
|
||
>
|
||
{SEVERITY_LEVELS.map((lvl) => (
|
||
<button
|
||
key={lvl}
|
||
type="button"
|
||
aria-pressed={severity === lvl}
|
||
aria-label={t("cycle.sheet.severityLevel", { level: lvl })}
|
||
onClick={() => onSeverity(symptomKey, lvl)}
|
||
className={cn(
|
||
"focus-visible:ring-ring/50 size-6 rounded-full border text-xs tabular-nums transition-colors focus-visible:ring-2 focus-visible:outline-none",
|
||
severity === lvl
|
||
? "border-primary bg-primary/15 text-primary font-semibold"
|
||
: "border-border text-muted-foreground hover:bg-accent",
|
||
)}
|
||
>
|
||
{lvl}
|
||
</button>
|
||
))}
|
||
</div>
|
||
) : null}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/**
|
||
* The dashed ghost-chip in the symptom grid that opens a compact label + icon
|
||
* popover to mint a new custom symptom. Matches the chip grid (same rounded-
|
||
* full pill, same size) so it reads as part of the grid, not a foreign button.
|
||
*/
|
||
function AddSymptomChip({ onCreated }: { onCreated: (key: string) => void }) {
|
||
const { t } = useTranslations();
|
||
const create = useCreateCustomSymptom();
|
||
const [openForm, setOpenForm] = useState(false);
|
||
const [label, setLabel] = useState("");
|
||
const [icon, setIcon] = useState<string>("Tag");
|
||
|
||
function reset() {
|
||
setLabel("");
|
||
setIcon("Tag");
|
||
}
|
||
|
||
async function handleCreate() {
|
||
const trimmed = label.trim();
|
||
if (!trimmed) return;
|
||
try {
|
||
const created = await create.mutateAsync({ label: trimmed, icon });
|
||
// Auto-select the freshly-minted symptom so the user doesn't have to tap
|
||
// the new chip after adding it.
|
||
onCreated(created.key);
|
||
reset();
|
||
setOpenForm(false);
|
||
} catch {
|
||
// Keep the popover open; `create.error` drives the inline message
|
||
// (cap copy on the limit errorCode, generic otherwise).
|
||
}
|
||
}
|
||
|
||
// Only the per-user cap surfaces the "limit reached" copy — a transient or
|
||
// validation error must not masquerade as the cap being hit.
|
||
const limitReached =
|
||
create.error instanceof CustomSymptomError &&
|
||
create.error.errorCode === CUSTOM_SYMPTOM_LIMIT_ERROR_CODE;
|
||
|
||
return (
|
||
<Popover
|
||
open={openForm}
|
||
onOpenChange={(o) => {
|
||
setOpenForm(o);
|
||
if (!o) reset();
|
||
}}
|
||
>
|
||
<PopoverTrigger asChild>
|
||
<button
|
||
type="button"
|
||
className="border-border text-muted-foreground hover:border-primary hover:text-primary focus-visible:ring-ring/50 inline-flex items-center gap-1.5 rounded-full border border-dashed px-3 py-1.5 text-sm transition-colors focus-visible:ring-2 focus-visible:outline-none"
|
||
>
|
||
<Plus className="h-3.5 w-3.5" aria-hidden="true" />
|
||
{t("cycle.symptom.custom.add")}
|
||
</button>
|
||
</PopoverTrigger>
|
||
<PopoverContent align="start" className="w-64 space-y-3">
|
||
<div className="space-y-1.5">
|
||
<Label htmlFor="custom-symptom-label" className="text-xs font-medium">
|
||
{t("cycle.symptom.custom.label")}
|
||
</Label>
|
||
<Input
|
||
id="custom-symptom-label"
|
||
value={label}
|
||
maxLength={40}
|
||
autoFocus
|
||
placeholder={t("cycle.symptom.custom.labelPlaceholder")}
|
||
onChange={(e) => setLabel(e.target.value)}
|
||
onKeyDown={(e) => {
|
||
if (e.key === "Enter") {
|
||
e.preventDefault();
|
||
void handleCreate();
|
||
}
|
||
}}
|
||
/>
|
||
</div>
|
||
<div className="space-y-1.5">
|
||
<p className="text-xs font-medium">
|
||
{t("cycle.symptom.custom.icon")}
|
||
</p>
|
||
<div
|
||
className="flex flex-wrap gap-1.5"
|
||
role="radiogroup"
|
||
aria-label={t("cycle.symptom.custom.icon")}
|
||
>
|
||
{CUSTOM_SYMPTOM_ICON_ALLOWLIST.map((name) => {
|
||
const IconC = customIcon(name);
|
||
const selected = icon === name;
|
||
return (
|
||
<button
|
||
key={name}
|
||
type="button"
|
||
role="radio"
|
||
aria-checked={selected}
|
||
aria-label={name}
|
||
onClick={() => setIcon(name)}
|
||
className={cn(
|
||
"focus-visible:ring-ring/50 grid size-7 place-items-center rounded-md border transition-colors focus-visible:ring-2 focus-visible:outline-none",
|
||
selected
|
||
? "border-primary bg-primary/10 text-primary"
|
||
: "border-border text-muted-foreground hover:bg-accent",
|
||
)}
|
||
>
|
||
<IconC className="size-4" aria-hidden="true" />
|
||
</button>
|
||
);
|
||
})}
|
||
</div>
|
||
</div>
|
||
{limitReached ? (
|
||
<p className="text-destructive text-sm" role="alert">
|
||
{t("cycle.symptom.custom.limitReached")}
|
||
</p>
|
||
) : null}
|
||
<div className="flex justify-end gap-2">
|
||
<Button
|
||
variant="ghost"
|
||
size="sm"
|
||
onClick={() => {
|
||
reset();
|
||
setOpenForm(false);
|
||
}}
|
||
>
|
||
{t("cycle.sheet.cancel")}
|
||
</Button>
|
||
<Button
|
||
size="sm"
|
||
onClick={handleCreate}
|
||
disabled={!label.trim() || create.isPending}
|
||
>
|
||
{create.isPending ? (
|
||
<Loader2 className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" />
|
||
) : null}
|
||
{t("cycle.symptom.custom.add")}
|
||
</Button>
|
||
</div>
|
||
</PopoverContent>
|
||
</Popover>
|
||
);
|
||
}
|