Calio/src/Trends.tsx
Elijah 6fc0a01c56
All checks were successful
Verify and publish Calio container / build-and-push (push) Successful in 1m4s
first commit
2026-10-20 19:04:12 -07:00

370 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useState } from "react";
import {
ArrowDownRight,
ArrowUpRight,
ChevronLeft,
ChevronRight,
Plus,
Scale,
Trash2,
Pencil,
Activity,
} from "lucide-react";
import type { Entry, JournalRecord, Settings, Weight, Metric } from "./types";
import { metrics } from "./types";
import {
displayDate,
number,
offsetDay,
recordsOf,
today,
weightValue,
} from "./utils";
import { totalNutrients } from "../shared/domain.js";
import { Empty } from "./components";
export function Trends({
records,
settings,
logWeight,
editWeight,
remove,
}: {
records: JournalRecord[];
settings: Settings;
logWeight: () => void;
editWeight: (r: JournalRecord<Weight>) => void;
remove: (r: JournalRecord) => void;
}) {
const [period, setPeriod] = useState(7);
const [end, setEnd] = useState(today());
const [metric, setMetric] = useState<Metric>("calories");
const start = offsetDay(end, 1 - period);
const entries = recordsOf<Entry>(records, "entry");
const allWeights = recordsOf<Weight>(records, "weight").sort(
(a, b) =>
a.data.date.localeCompare(b.data.date) ||
a.updatedAt.localeCompare(b.updatedAt),
);
const weights = allWeights.filter(
(r) => r.data.date >= start && r.data.date <= end,
);
// One latest weigh-in per day for the trend; the journal retains every measurement.
const dailyWeights = [
...new Map(weights.map((r) => [r.data.date, r])).values(),
];
const days = Array.from({ length: period }, (_, i) => {
const date = offsetDay(start, i);
const logs = entries.filter((r) => r.data.date === date);
return {
date,
logged: logs.length > 0,
total: totalNutrients(logs.map((r) => r.data))[metric],
};
});
const loggedDays = days.filter((d) => d.logged);
const avg = loggedDays.length
? loggedDays.reduce((sum, d) => sum + d.total, 0) / loggedDays.length
: 0;
const goal = settings.goals[metric];
const maximum =
Math.max(...days.map((d) => d.total), goal.enabled ? goal.target : 1, 1) *
1.12;
const chosen = metrics.find((m) => m.key === metric)!;
const values = dailyWeights.map((r) =>
weightValue(r.data.valueKg, settings.unit),
);
const minWeight = Math.min(...values) - 1;
const maxWeight = Math.max(...values) + 1;
const points = dailyWeights.map((r, i) => ({
x:
28 +
((new Date(r.data.date).getTime() - new Date(start).getTime()) /
((period - 1) * 86400000)) *
544,
y: 170 - ((values[i] - minWeight) / (maxWeight - minWeight)) * 140,
}));
const delta = values.length > 1 ? values.at(-1)! - values[0] : null;
return (
<>
<div className="page-heading">
<div>
<span className="eyebrow">THE BIGGER PICTURE</span>
<h1>
Your rhythms<span>.</span>
</h1>
<p>Small moments. A little perspective.</p>
</div>
<button className="primary" onClick={logWeight}>
<Plus size={18} />
Log weight
</button>
</div>
<div className="trend-controls">
<div className="segmented">
{[7, 30, 90, 365].map((n) => (
<button
key={n}
className={period === n ? "active" : ""}
onClick={() => setPeriod(n)}
>
{n === 7
? "Week"
: n === 30
? "Month"
: n === 90
? "3 months"
: "Year"}
</button>
))}
</div>
<div className="date-controls">
<button
className="icon-button"
aria-label="Previous period"
onClick={() => setEnd(offsetDay(end, -period))}
>
<ChevronLeft size={18} />
</button>
<span>
{displayDate(start, { month: "short", day: "numeric" })} –{" "}
{displayDate(end, {
month: "short",
day: "numeric",
year: "numeric",
})}
</span>
<button
className="icon-button"
aria-label="Next period"
disabled={end >= today()}
onClick={() =>
setEnd(
offsetDay(end, period) > today()
? today()
: offsetDay(end, period),
)
}
>
<ChevronRight size={18} />
</button>
</div>
</div>
<div className="trends-grid">
<section className="card chart-card">
<div className="card-title">
<div>
<span className="eyebrow">DAILY INTAKE</span>
<h2>{chosen.label}</h2>
</div>
<select
aria-label="Trend nutrient"
value={metric}
onChange={(e) => setMetric(e.target.value as Metric)}
>
{metrics.map((m) => (
<option value={m.key} key={m.key}>
{m.label}
</option>
))}
</select>
</div>
<div className="stat-large">
{number(avg)} <span>{chosen.unit} / logged day</span>
</div>
<div
className="bar-chart"
role="img"
aria-label={`${chosen.label}: ${number(avg)} ${chosen.unit} average over ${loggedDays.length} logged days`}
>
<div className="chart-grid-lines">
<span>{number(maximum)}</span>
<span>{number(maximum / 2)}</span>
<span>0</span>
</div>
<div className="bars">
{goal.enabled && (
<div
className="goal-line"
style={{ bottom: `${(goal.target / maximum) * 100}%` }}
>
<span>Goal {number(goal.target)}</span>
</div>
)}
{days.map((d) => (
<div
className={"bar-slot " + (!d.logged ? "unlogged" : "")}
key={d.date}
title={`${displayDate(d.date)}: ${d.logged ? number(d.total) + " " + chosen.unit : "Not logged"}`}
>
<div
className="bar"
style={{
height: `${d.logged ? Math.max(1, (d.total / maximum) * 100) : 2}%`,
background: d.logged ? chosen.color : undefined,
}}
/>
{period === 7 && (
<span>
{displayDate(d.date, { weekday: "short" }).slice(0, 1)}
</span>
)}
</div>
))}
</div>
</div>
<p className="chart-note">
{loggedDays.length} of {period} days logged · Empty days are
excluded from the average.
</p>
</section>
<section className="card chart-card">
<div className="card-title">
<div>
<span className="eyebrow">YOUR JOURNEY</span>
<h2>Weight</h2>
</div>
<Scale size={22} className="muted" />
</div>
{dailyWeights.length ? (
<>
<div className="stat-large">
{number(values.at(-1)!, 1)} <span>{settings.unit}</span>
</div>
<div className="weight-chart">
<svg
viewBox="0 0 600 210"
role="img"
aria-label={`${dailyWeights.length} weigh-ins, latest ${number(values.at(-1)!, 1)} ${settings.unit}`}
>
<line
x1="28"
x2="572"
y1="30"
y2="30"
className="grid-line"
/>
<line
x1="28"
x2="572"
y1="100"
y2="100"
className="grid-line"
/>
<line
x1="28"
x2="572"
y1="170"
y2="170"
className="grid-line"
/>
<polyline
points={points.map((p) => `${p.x},${p.y}`).join(" ")}
fill="none"
stroke="var(--accent)"
strokeWidth="3"
strokeLinejoin="round"
/>
{points.map((p, i) => (
<circle
key={i}
cx={p.x}
cy={p.y}
r="4"
fill="var(--accent)"
>
<title>
{dailyWeights[i].data.date}: {number(values[i], 1)}{" "}
{settings.unit}
</title>
</circle>
))}
<text x="28" y="202">
{displayDate(start, { month: "short", day: "numeric" })}
</text>
<text x="572" y="202" textAnchor="end">
{displayDate(end, { month: "short", day: "numeric" })}
</text>
</svg>
<div className="weight-axis">
<span>{number(maxWeight, 1)}</span>
<span>{number(minWeight, 1)}</span>
</div>
</div>
<p className="chart-note">
{delta === null ? (
"Log another day to see a change over time."
) : (
<>
{delta < 0 ? (
<ArrowDownRight size={15} />
) : (
<ArrowUpRight size={15} />
)}{" "}
{number(Math.abs(delta), 1)} {settings.unit}{" "}
{delta < 0 ? "down" : "up"} in this period
</>
)}
</p>
</>
) : (
<Empty
icon={<Activity size={28} />}
title="A starting point, whenever you’re ready"
text="Your weigh-ins will become a simple picture of your progress."
action={
<button className="text-button" onClick={logWeight}>
Log your first weight <ArrowUpRight size={16} />
</button>
}
/>
)}
</section>
</div>
<section className="card weight-journal">
<div className="card-title">
<div>
<span className="eyebrow">ONE CHECK-IN AT A TIME</span>
<h2>Weight journal</h2>
</div>
<span className="pill">{weights.length} in this period</span>
</div>
{weights.length === 0 ? (
<p className="muted">No weigh-ins in this date range.</p>
) : (
[...weights].reverse().map((r) => (
<div className="journal-row" key={r.id}>
<div className="food-avatar weight-avatar">
<Scale size={19} />
</div>
<div className="row-copy">
<strong>
{number(weightValue(r.data.valueKg, settings.unit), 1)}{" "}
{settings.unit}
</strong>
<small>
{displayDate(r.data.date)}
{r.data.notes ? " · " + r.data.notes : ""}
</small>
</div>
<button
className="icon-button"
aria-label={`Edit weight ${r.data.date}`}
onClick={() => editWeight(r)}
>
<Pencil size={16} />
</button>
<button
className="icon-button danger-hover"
aria-label={`Delete weight ${r.data.date}`}
onClick={() => remove(r)}
>
<Trash2 size={16} />
</button>
</div>
))
)}
</section>
</>
);
}