Profil: parametry ciala jako zakladki + osobny div postepu i przywrocony Wstecz

This commit is contained in:
tisachi
2026-10-17 07:00:23 +02:00
parent bb9a0120b2
commit b74fc7913e
4 changed files with 169 additions and 164 deletions

View File

@@ -20,6 +20,13 @@ export const MEASUREMENT_TYPES: MeasurementType[] = [
export const SIDE_LABELS: Record<Side, string> = { left: 'Lewy', right: 'Prawy' };
/* Skrót do listów zwartych (zakładki): pełna nazwa jest w nagłówku panelu. */
export const PART_SHORT: Record<string, string> = {
'Klatka piersiowa': 'Klatka',
Przedramię: 'Przedr.',
Waga: 'Waga',
};
/* Rodzaj gramatyczny części ciała → poprawna fleksja przymiotnika strony. */
const PART_GENDERS: Record<string, 'm' | 'f' | 'n' | 'p'> = {
'Klatka piersiowa': 'f',

View File

@@ -1,5 +1,13 @@
import { useMemo, useRef, useState, type ReactNode } from 'react';
import { Plus, Ruler, Scale, Trash2, type LucideIcon } from 'lucide-react';
import {
Plus,
Ruler,
Scale,
Trash2,
TrendingDown,
TrendingUp,
type LucideIcon,
} from 'lucide-react';
import {
addCircumference,
addWeight,
@@ -20,6 +28,7 @@ import {
} from 'recharts';
import { fmtDate } from '../../lib/format';
import {
BackButton,
Button,
Card,
ConfirmDialog,
@@ -34,6 +43,7 @@ import {
} from '../../components/ui';
import {
MEASUREMENT_TYPES,
PART_SHORT,
SIDE_LABELS,
bodyPartOf,
detectBodyPart,
@@ -118,40 +128,74 @@ interface PartGroup {
/** Wszystkie pomiary (pełna historia), rosnąco po dacie. */
points: GroupPoint[];
sidesPresent: Side[];
/** Wykres dwuliniowy tylko gdy każda obecna strona ma ≥2 pomiary. */
chartSided: boolean;
}
/* Polski pluralis dla „pomiar”. */
function pomN(n: number): string {
if (n === 1) return '1 pomiar';
if (n % 10 >= 2 && n % 10 <= 4 && !(n % 100 >= 12 && n % 100 <= 14)) return `${n} pomiary`;
return `${n} pomiarów`;
}
const WEIGHT_PART = 'Waga';
/** Delta najnowszego pomiaru vs poprzedni; przy ≥2 stronach liczona osobno per strona. */
function groupDelta(g: PartGroup): { text: string; className: string } | null {
const signed = (d: number) =>
`${d < 0 ? '−' : '+'}${Math.abs(d).toLocaleString('pl-PL', {
maximumFractionDigits: 1,
})} ${g.unit}`;
// waga: spadek = accent, wzrost = warn; obwody: bez oceny kierunku (neutralny)
const deltaClass: (d: number) => string =
g.unit === 'kg' ? (d) => (d < 0 ? 'text-accent-text' : 'text-warn') : () => 'text-ink';
const fmtVal = (n: number) => n.toLocaleString('pl-PL', { maximumFractionDigits: 1 });
const signed = (d: number) => `${d < 0 ? '−' : '+'}${fmtVal(Math.abs(d))}`;
if (g.chartSided) {
const parts = g.sidesPresent
.map((side) => {
const pts = g.points.filter((p) => p.side === side);
if (pts.length < 2) return null;
const d = pts[pts.length - 1].value - pts[pts.length - 2].value;
if (d === 0) return null;
return `${SIDE_LABELS[side]} ${signed(d)}`;
})
.filter((t): t is string => t != null);
if (parts.length === 0) return null;
// strony: kierunki mogą się różnić → bez oceny koloru
return { text: `${parts.join(' · ')} vs poprzedni`, className: 'text-ink' };
}
/** Skrót do zakładek: najkrótsza jednoznaczna nazwa (pełna jest w nagłówku panelu). */
function shortPartName(part: string): string {
const known = MEASUREMENT_TYPES.some((t) => t.label === part);
return known ? (PART_SHORT[part] ?? part) : part.split(/\s+/)[0];
}
/* Postęp części: zmiana najnowszego pomiaru od pierwszego; spadek wagi = dobry kierunek. */
function progressOf(g: PartGroup): { text: string; className: string } | null {
if (g.points.length < 2) return null;
const d = g.points[g.points.length - 1].value - g.points[g.points.length - 2].value;
const d = g.points[g.points.length - 1].value - g.points[0].value;
if (d === 0) return null;
return { text: `${signed(d)} vs poprzedni`, className: deltaClass(d) };
const className = g.unit === 'kg' ? (d < 0 ? 'text-accent-text' : 'text-warn') : 'text-ink';
return { text: `${signed(d)} ${g.unit} od pierwszego`, className };
}
/* Zmiana ostatniego pomiaru każdej strony vs poprzednik jej strony; 0 = bez zmian. */
function sideDeltas(g: PartGroup): { side: Side; text: string; zero: boolean }[] {
return g.sidesPresent
.map((side) => {
const pts = g.points.filter((p) => p.side === side);
if (pts.length < 2) return null;
const d = pts[pts.length - 1].value - pts[pts.length - 2].value;
return { side, text: `${signed(d)} ${g.unit}`, zero: d === 0 };
})
.filter((x): x is { side: Side; text: string; zero: boolean } => x != null);
}
/* Osobny div postępu wybranej części: kierunek zmiany + wynik (strony osobno, gdy łączone). */
function ProgressCard({
down,
primary,
primaryClass,
sub,
}: {
down: boolean;
primary: string;
primaryClass: string;
sub: string;
}) {
const Icon = down ? TrendingDown : TrendingUp;
return (
<Card className="mb-4">
<div className="flex items-center gap-3">
<span className="grid h-9 w-9 flex-none place-items-center rounded-[10px] bg-input text-dim">
<Icon className="h-4 w-4" />
</span>
<div className="min-w-0">
<H3 className="mb-0.5">Postęp</H3>
<p className={`text-[0.95rem] font-semibold tabular-nums ${primaryClass}`}>{primary}</p>
<p className="text-[0.8125rem] text-dim">{sub}</p>
</div>
</div>
</Card>
);
}
/** Etykieta osi X: `17.10`; gdy historia przekracza rok — `17.10.26`. */
@@ -164,80 +208,21 @@ function axisDateLabel(iso: string, withYear: boolean): string {
}
/**
* Wspólna oś dat dla serii: `[{ date, lewy, prawy }]` (brak pomiaru = null).
* Dwie strony w tym samym momencie → dwa wiersze z rozróżnialną etykietą
* (`17.10 ·L` / `17.10 ·P`) — inaczej starszy pomiar nadpisywałby młodszy.
* Dane wykresu: kategorie osi = numery porządkowe pomiarów (unikalne i równe
* odległości), więc dwa pomiary z tego samego dnia nie scalają się w jeden
* punkt — wykres rysuje się zawsze, etykiety osi pokazują daty (tickFormatter).
*/
function sideSeriesData(points: GroupPoint[], withYear: boolean) {
const byDate = new Map<string, Partial<Record<Side, number>>>();
for (const p of points) {
if (p.side == null) continue;
const row = byDate.get(p.date) ?? {};
row[p.side] = p.value;
byDate.set(p.date, row);
}
const rows: { date: string; lewy: number | null; prawy: number | null }[] = [];
for (const [date, row] of [...byDate.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {
const label = axisDateLabel(date, withYear);
if (row.left != null && row.right != null) {
// dwie strony w tym samym momencie → dwie kategorie osi, inaczej recharts
// scalyłby duplikat etykiety w jeden punkt i linia „gubiłaby” pomiary
rows.push({ date: `${label} ·L`, lewy: row.left, prawy: null });
rows.push({ date: `${label} ·P`, lewy: null, prawy: row.right });
} else if (row.left != null) {
rows.push({ date: label, lewy: row.left, prawy: null });
} else if (row.right != null) {
rows.push({ date: label, lewy: null, prawy: row.right });
}
}
return rows;
function chartData(points: GroupPoint[]) {
return points.map((p, idx) => ({
idx: String(idx),
value: p.value,
lewy: p.side === 'left' ? p.value : null,
prawy: p.side === 'right' ? p.value : null,
}));
}
const SIDE_STROKE: Record<Side, string> = { left: 'var(--info)', right: 'var(--accent)' };
/* Kafel podsumowania części ciała: nazwa + najnowsza wartość + delta; klik = panel poniżej. */
function PartTile({
group,
icon: Icon,
active,
onSelect,
}: {
group: PartGroup;
icon: LucideIcon;
active: boolean;
onSelect: () => void;
}) {
const latest = group.points[group.points.length - 1];
const delta = groupDelta(group);
return (
<button
type="button"
aria-pressed={active}
onClick={onSelect}
className={`min-w-36 shrink-0 rounded-2xl border px-3.5 py-3 text-left transition-colors cursor-pointer ${
active ? 'border-accent bg-accent/10' : 'border-line bg-input hover:border-accent/50'
}`}
>
<span className="flex items-center gap-1.5 text-[0.75rem] text-dim">
<Icon className="h-3.5 w-3.5" />
{group.part}
</span>
<span className="mt-1 flex items-baseline gap-1.5">
<span className="font-display text-[1.25rem] font-bold leading-none tabular-nums">
{latest.value}
</span>
<span className="text-[0.75rem] text-dim">{group.unit}</span>
</span>
{delta && (
<span className={`mt-1 block text-[0.75rem] font-semibold ${delta.className}`}>
{delta.text}
</span>
)}
<span className="mt-0.5 block text-[0.6875rem] text-dim">{fmtDate(latest.date)}</span>
</button>
);
}
/* Panel wybranej części: nagłówek (nazwa + ostatni pomiar) + wykres pełnej historii + lista pomiarów. */
function MeasurementPanel({
group,
@@ -253,33 +238,32 @@ function MeasurementPanel({
onDelete: (target: { kind: 'weight' | 'circumference'; id: string; label: string }) => void;
}) {
const latest = group.points[group.points.length - 1];
// dwuliniowo tylko gdy każda strona ma min. 2 pomiary (patrz chartSided)
const sided = group.chartSided;
const sided = group.sidesPresent.length > 1;
// historia przekracza rok → oś X z rokiem (również przy przerwie >12 mies. w jednym roku)
const withYear =
new Date(group.points[group.points.length - 1].date).getTime() -
new Date(group.points[0].date).getTime() >
300 * 86_400_000;
// jedna strona ma ≥2 pomiary, a druga mniej → wykres tylko dla tej strony,
// żeby pojedynczy pomiar drugiej strony nie „skakał” po linii
const chartSide: Side | null = sided
? null
: (group.sidesPresent.find((s) => group.points.filter((p) => p.side === s).length >= 2) ??
null);
const singlePoints = chartSide ? group.points.filter((p) => p.side === chartSide) : group.points;
// ten sam dzień mierzony dwa razy → unikalne kategorie osi (`17.10`, `17.10 ·2`),
// inaczej recharts scala duplikaty i wykres rysuje się dla jednego punktu
const singleData = (() => {
const seen = new Map<string, number>();
return singlePoints.map((p) => {
const base = axisDateLabel(p.date, withYear);
const n = (seen.get(base) ?? 0) + 1;
seen.set(base, n);
return { date: n > 1 ? `${base} ·${n}` : base, value: p.value };
});
})();
const sidedData = sided ? sideSeriesData(group.points, withYear) : [];
const chartReady = sided ? sidedData.length >= 2 : singlePoints.length >= 2;
const data = chartData(group.points);
// kategorie osi = numery porządkowe → etykiety i tooltip tłumaczone na daty
const labelAt = (v: string | number) => {
const p = group.points[Number(v)];
return p ? axisDateLabel(p.date, withYear) : '';
};
const chartReady = group.points.length >= 2;
// osobna strona: przy >1 strony wynik per strona, poza tym zmiana od pierwszego pomiaru
const deltas = sideDeltas(group);
const prog = progressOf(group);
const parts =
sided && deltas.length > 0
? deltas.map((d) => `${SIDE_LABELS[d.side]} ${d.zero ? 'bez zmian' : d.text}`).join(' · ')
: (prog?.text ?? '');
const primary = parts || 'bez zmian';
const primaryClass = prog?.className ?? 'text-dim';
const sub =
group.points.length < 2
? 'drugi pomiar pokaże zmianę'
: `${pomN(group.points.length)} · pierwszy → ostatni`;
return (
<Card>
@@ -303,13 +287,21 @@ function MeasurementPanel({
</span>
</div>
<ProgressCard
down={prog != null && prog.text.startsWith('−')}
primary={primary}
primaryClass={primaryClass}
sub={sub}
/>
{chartReady ? (
<ResponsiveContainer width="100%" height={220}>
{sided ? (
<LineChart data={sidedData} margin={CHART_MARGIN}>
<LineChart data={data} margin={CHART_MARGIN}>
<CartesianGrid stroke="var(--border)" vertical={false} />
<XAxis
dataKey="date"
dataKey="idx"
tickFormatter={labelAt}
tickLine={false}
axisLine={false}
tickMargin={10}
@@ -324,7 +316,11 @@ function MeasurementPanel({
domain={['auto', 'auto']}
tick={AXIS_TICK}
/>
<Tooltip contentStyle={TOOLTIP_STYLE} formatter={tooltipUnit(group.unit)} />
<Tooltip
contentStyle={TOOLTIP_STYLE}
formatter={tooltipUnit(group.unit)}
labelFormatter={labelAt}
/>
{group.sidesPresent.map((side) => (
<Line
key={side}
@@ -341,10 +337,10 @@ function MeasurementPanel({
</LineChart>
) : (
(() => {
const stroke = chartSide ? SIDE_STROKE[chartSide] : unitStroke(group.unit);
const stroke = unitStroke(group.unit);
const areaId = `bp-area-${encodeURIComponent(group.part)}`;
return (
<AreaChart data={singleData} margin={CHART_MARGIN}>
<AreaChart data={data} margin={CHART_MARGIN}>
<defs>
<linearGradient id={areaId} x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor={stroke} stopOpacity={0.25} />
@@ -353,7 +349,8 @@ function MeasurementPanel({
</defs>
<CartesianGrid stroke="var(--border)" vertical={false} />
<XAxis
dataKey="date"
dataKey="idx"
tickFormatter={labelAt}
tickLine={false}
axisLine={false}
tickMargin={10}
@@ -368,15 +365,15 @@ function MeasurementPanel({
domain={['auto', 'auto']}
tick={AXIS_TICK}
/>
<Tooltip contentStyle={TOOLTIP_STYLE} formatter={tooltipUnit(group.unit)} />
<Tooltip
contentStyle={TOOLTIP_STYLE}
formatter={tooltipUnit(group.unit)}
labelFormatter={labelAt}
/>
<Area
type="monotone"
dataKey="value"
name={
chartSide
? `${group.part} (${sideLabelsFor(group.part)[chartSide].toLowerCase()})`
: group.part
}
name={group.part}
stroke={stroke}
strokeWidth={2}
fill={`url(#${areaId})`}
@@ -641,7 +638,6 @@ export default function ProfileBodyParameters() {
side: null,
name: 'wagi',
})),
chartSided: false,
sidesPresent: [],
});
}
@@ -665,11 +661,6 @@ export default function ProfileBodyParameters() {
unit: 'cm',
points,
sidesPresent,
// dwuliniowy wykres tylko gdy każda strona ma ≥2 pomiary — przy jednym
// pomiarze na stronie linia byłaby niewidoczna (linia potrzebuje min. 2 punktów)
chartSided:
sidesPresent.length > 1 &&
sidesPresent.every((side) => points.filter((p) => p.side === side).length >= 2),
});
}
return list;
@@ -749,6 +740,11 @@ export default function ProfileBodyParameters() {
return (
<>
{/* podstrona: „Wstecz” do przeglądu profilu (na telefonie = „<” w topmenu) */}
<div className="mb-4">
<BackButton to="/profile" />
</div>
{active == null ? (
<EmptyState
icon={Scale}
@@ -757,22 +753,23 @@ export default function ProfileBodyParameters() {
/>
) : (
<>
{/* pasek kaflów: najnowsze wartości wszystkich części; klik = panel poniżej */}
<div
role="group"
aria-label="Części ciała"
className="flex flex-wrap gap-2 sm:flex-nowrap sm:overflow-x-auto sm:pb-1"
>
{groups.map((g) => (
<PartTile
key={g.part}
group={g}
icon={g.part === WEIGHT_PART ? Scale : Ruler}
active={active.part === g.part}
onSelect={() => setSelected(g.part)}
/>
))}
</div>
{/* zakładki części: skrót + najnowsza wartość; strzałki, gdy się nie mieszczą */}
<Tabs
tabs={groups.map((g) => {
const latest = g.points[g.points.length - 1];
return {
id: g.part,
label: (
<span className="flex items-baseline gap-1.5">
{shortPartName(g.part)}
<span className="tabular-nums opacity-70">{fmtVal(latest.value)}</span>
</span>
),
};
})}
active={active.part}
onChange={(id) => setSelected(id)}
/>
<div className="mt-4">
<MeasurementPanel

View File

@@ -124,9 +124,9 @@ async function loginToProfile(user: userEvent.User) {
).toBeInTheDocument();
}
/** Klik w kafel części ciała z paska (kafel to jedyny przycisk z datą najnowszego pomiaru). */
/** Klik w zakładkę części ciała (skrót nazwy + najnowsza wartość). */
function selectPart(part: string) {
return screen.getByRole('button', { name: new RegExp(`^${part}.*\\d{2}\\.\\d{2}\\.\\d{4}`) });
return screen.getByRole('button', { name: new RegExp(`^${part} `) });
}
function renderApp() {
@@ -268,9 +268,9 @@ describe('Profile — body parameter removal', () => {
renderApp();
await loginToProfile(user);
// delta: 81.8 (15.08) − 82.5 (01.08) = −0,7 kg (spadek) — liczona z pełnej historii
// postęp: 81.8 (15.08) − 82.5 (01.08) = −0,7 kg (spadek) — liczony z pełnej historii
expect(await screen.findByText('82.5 kg')).toBeInTheDocument();
expect(screen.getByText('−0,7 kg vs poprzedni')).toBeInTheDocument();
expect(screen.getByText('−0,7 kg od pierwszego')).toBeInTheDocument();
// 1 kontrolka = 1 miejsce: w treści brak przycisków dodawania — dodaje się z topmenu
expect(screen.queryByRole('button', { name: /Dodaj wagę/ })).not.toBeInTheDocument();
@@ -293,9 +293,9 @@ describe('Profile — body parameter removal', () => {
expect(await screen.findByText('82.5 kg')).toBeInTheDocument();
await user.click(selectPart('Talia'));
expect(screen.getByText('10.07.2026')).toBeInTheDocument();
// 10.08 w kafelu, nagłówku panelu i w wierszu listy
expect(screen.getAllByText('10.08.2026').length).toBe(3);
// delta Talii: 82 (10.08) − 80 (10.07) = +2 cm
expect(screen.getByText('+2 cm vs poprzedni')).toBeInTheDocument();
// 10.08 w nagłówku panelu i w wierszu listy (zakładka pokazuje samą wartość)
expect(screen.getAllByText('10.08.2026').length).toBe(2);
// postęp Talii: 82 (10.08) − 80 (10.07) = +2 cm
expect(screen.getByText('+2 cm od pierwszego')).toBeInTheDocument();
});
});

View File

@@ -82,7 +82,7 @@ test('mobile: dane osobowe — bottom sheet mięśni z zakładkami i wyszukiwark
await expectNoHorizontalScroll(page, 'dane osobowe');
});
test('mobile: parametry ciała — pasek kaflów, delta wagi i dodanie pomiaru z topmenu', async ({
test('mobile: parametry ciała — zakładki części, postęp wagi i dodanie pomiaru z topmenu', async ({
page,
}) => {
const now = new Date();
@@ -101,8 +101,9 @@ test('mobile: parametry ciała — pasek kaflów, delta wagi i dodanie pomiaru z
await page.getByRole('link', { name: /Parametry ciała/ }).click();
await expect(page.getByRole('heading', { name: 'Parametry ciała', level: 1 })).toBeVisible();
// kafel „Waga” wybrany domyślnie: panel z ostatnim pomiarem + delta vs poprzedni (spadek)
await expect(page.getByRole('button', { name: /Waga.*−0,7 kg vs poprzedni/ })).toBeVisible();
// zakładka „Waga” wybrana domyślnie: panel z ostatnim pomiarem + postęp (spadek)
await expect(page.getByRole('button', { name: /^Waga 81,8/ })).toBeVisible();
await expect(page.getByText('−0,7 kg od pierwszego')).toBeVisible();
await expect(page.getByText('81.8 kg').first()).toBeVisible();
// brak przycisków dodawania w treści — 1 kontrolka = 1 miejsce (tylko topmenu)