Profil: parametry ciala w formie paska kafelow z panelem jednej czesci (pelna historia, bez filtra miesiaca)

This commit is contained in:
tisachi
2026-10-17 06:32:51 +02:00
parent 0d6b804463
commit 0d908c677a
10 changed files with 434 additions and 523 deletions

View File

@@ -2,7 +2,7 @@ import { useState } from 'react';
import { CalendarDays, ChevronLeft, ChevronRight } from 'lucide-react';
import { monthStr } from '../../lib/format';
import { DAY_STATUS } from '../../lib/labels';
import { MONTH_SHORT, formatMonth } from '../../store/body-params';
import { MONTH_SHORT, formatMonth } from '../../lib/format';
import type { CalendarDay } from '../../api/types';
import { Badge, Button, EmptyState } from '../ui';

View File

@@ -1,7 +1,7 @@
import { useState } from 'react';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { Button } from './button';
import { formatMonth } from '../../store/body-params';
import { formatMonth } from '../../lib/format';
import { fmtDate } from '../../lib/format';
import { cn } from '../../lib/utils';

View File

@@ -112,3 +112,40 @@ export function todayStr(): string {
export function monthStr(d: Date): string {
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
}
const MONTH_NAMES = [
'Styczeń',
'Luty',
'Marzec',
'Kwiecień',
'Maj',
'Czerwiec',
'Lipiec',
'Sierpień',
'Wrzesień',
'Październik',
'Listopad',
'Grudzień',
];
/** Krótkie nazwy do siatki miesięcy w panelu selektora. */
export const MONTH_SHORT = [
'Sty',
'Lut',
'Mar',
'Kwi',
'Maj',
'Cze',
'Lip',
'Sie',
'Wrz',
'Paź',
'Lis',
'Gru',
];
/** `2026-08` → `Sierpień 2026`. */
export function formatMonth(month: string): string {
const [y, m] = month.split('-').map(Number);
return `${MONTH_NAMES[m - 1]} ${y}`;
}

View File

@@ -1,6 +1,5 @@
import { useEffect, useRef, useState, type ReactNode } from 'react';
import { useNavigate } from 'react-router-dom';
import { ChevronDown, Plus, Ruler, Scale, Trash2, type LucideIcon } from 'lucide-react';
import { useMemo, useRef, useState } from 'react';
import { Plus, Ruler, Scale, Trash2, type LucideIcon } from 'lucide-react';
import {
addCircumference,
addWeight,
@@ -19,7 +18,6 @@ import {
} from 'recharts';
import { fmtDate } from '../../lib/format';
import {
BackButton,
Button,
Card,
ConfirmDialog,
@@ -28,7 +26,6 @@ import {
H3,
Input,
Modal,
PageHeader,
Select,
Skeleton,
Tabs,
@@ -43,8 +40,7 @@ import {
sideOf,
type Side,
} from '../../lib/body-measurements';
import { MonthPicker, useTopbar } from '../../topbar';
import { useBodyParams } from '../../store/body-params';
import { useTopbar } from '../../topbar';
import { useToast } from '../../components/toast';
import type { CircumferenceSeries } from '../../api/types';
@@ -84,41 +80,146 @@ function groupCircumferences(series: CircumferenceSeries[]): CircGroup[] {
}));
}
/** Wspólna oś dat dla obu stron: `[{ date, lewy, prawy }]` (brak pomiaru = null). */
function mergedSideData(series: CircumferenceSeries[]) {
const byDate = new Map<string, { date: string; lewy: number | null; prawy: number | null }>();
for (const s of series) {
const side = sideOf(s.name);
if (side == null) continue;
for (const p of s.points) {
const entry = byDate.get(p.date) ?? { date: p.date, lewy: null, prawy: null };
entry[side === 'left' ? 'lewy' : 'prawy'] = p.value;
byDate.set(p.date, entry);
}
/* Grupa pomiaru w ujednoliconej postaci: waga i obwody jako jeden model (kafel + panel). */
interface GroupPoint {
id: string;
value: number;
date: string;
side: Side | null;
name: string;
}
interface PartGroup {
part: string;
unit: 'kg' | 'cm';
/** Wszystkie pomiary (pełna historia), rosnąco po dacie. */
points: GroupPoint[];
sided: boolean;
sidesPresent: Side[];
}
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';
if (g.sided && g.sidesPresent.length > 1) {
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' };
}
return [...byDate.values()]
.sort((a, b) => a.date.localeCompare(b.date))
.map((e) => ({
date: new Date(e.date).toLocaleDateString('pl-PL', { day: '2-digit', month: '2-digit' }),
lewy: e.lewy,
prawy: e.prawy,
if (g.points.length < 2) return null;
const d = g.points[g.points.length - 1].value - g.points[g.points.length - 2].value;
if (d === 0) return null;
return { text: `${signed(d)} vs poprzedni`, className: deltaClass(d) };
}
/**
* Wspólna oś dat dla serii: `[{ date, lewy, prawy }]` (brak pomiaru = null).
* Jednostronna grupa → kolumna wg bieżącej strony (osie nazywane po stronie).
*/
function sideSeriesData(points: GroupPoint[], sides: Side[]) {
const col = (side: Side) => (side === 'left' ? 'lewy' : 'prawy');
const byDate = new Map<string, Record<string, number | null>>();
for (const p of points) {
if (p.side == null) continue;
const entry = byDate.get(p.date) ?? {};
for (const s of sides) entry[col(s)] = null;
entry[col(p.side)] = p.value;
byDate.set(p.date, entry);
}
return [...byDate.entries()]
.sort((a, b) => a[0].localeCompare(b[0]))
.map(([date, row]) => ({
date: new Date(date).toLocaleDateString('pl-PL', { day: '2-digit', month: '2-digit' }),
...row,
}));
}
/* Karta pomiaru: nagłówek (ikona + H3 + najnowszy pomiar + akcje) + treść (wykres + lista). */
function MeasurementCard({
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,
title,
latest,
actions,
children,
active,
onSelect,
}: {
group: PartGroup;
icon: LucideIcon;
title: string;
latest?: ReactNode;
actions?: ReactNode;
children: ReactNode;
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,
icon: Icon,
visible,
onShowMore,
onDelete,
}: {
group: PartGroup;
icon: LucideIcon;
visible: number;
onShowMore: () => void;
onDelete: (target: { kind: 'weight' | 'circumference'; id: string; label: string }) => void;
}) {
const latest = group.points[group.points.length - 1];
const sided = group.sided && group.sidesPresent.length > 0;
const singleData = group.points.map((p) => ({
date: new Date(p.date).toLocaleDateString('pl-PL', { day: '2-digit', month: '2-digit' }),
value: p.value,
}));
const sidedData = sided ? sideSeriesData(group.points, group.sidesPresent) : [];
const chartReady = sided ? sidedData.length >= 2 : group.points.length >= 2;
return (
<Card>
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
@@ -126,73 +227,125 @@ function MeasurementCard({
<span className="grid h-8 w-8 place-items-center rounded-[10px] bg-accent/10 text-accent-text">
<Icon className="h-4 w-4" />
</span>
<H3 className="mb-0">{title}</H3>
</div>
<div className="flex flex-wrap items-center gap-2">
{latest}
{actions}
<H3 className="mb-0">{group.part}</H3>
</div>
<span className="flex flex-col items-end">
<span className="flex items-baseline gap-2">
<span className="font-display text-[1.35rem] font-bold leading-none tabular-nums">
{latest.value} {group.unit}
</span>
<span className="text-[0.75rem] text-dim">
{latest.side ? `${SIDE_LABELS[latest.side]} · ` : ''}
{fmtDate(latest.date)}
</span>
</span>
</span>
</div>
{children}
</Card>
);
}
export interface MeasurementPoint {
id: string;
kind: 'weight' | 'circumference';
label: string;
meta: string;
deleteLabel: string;
removeLabel: string;
}
/* Lista pomiarów: najnowsze N + „Pokaż więcej"; wiersz = wartość + data (+ strona) + usuń. */
function MeasurementList({
points,
visible,
onShowMore,
onDelete,
}: {
points: MeasurementPoint[];
visible: number;
onShowMore: () => void;
onDelete: (target: { kind: 'weight' | 'circumference'; id: string; label: string }) => void;
}) {
if (points.length === 0) return null;
return (
<div>
{/* 3 najnowsze; duże ekrany: wiersz z poziomym scrollem, małe: kolumna */}
<ul className="mt-3 flex flex-col gap-1.5 sm:flex-row sm:overflow-x-auto sm:pb-1">
{points.slice(0, visible).map((p) => (
<li
key={p.id}
className="border border-line bg-input rounded-xl px-3.5 py-2.5 text-[0.95rem] sm:w-44 sm:shrink-0"
>
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
<strong className="text-ink">{p.label}</strong>
<div className="mt-0.5 text-[0.875rem] text-dim">{p.meta}</div>
</div>
<button
type="button"
aria-label={p.deleteLabel}
onClick={() => onDelete({ kind: p.kind, id: p.id, label: p.removeLabel })}
className="p-1.5 -m-1.5 text-dim hover:text-danger cursor-pointer shrink-0"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
</li>
))}
</ul>
{points.length > visible && (
<Button variant="ghost" size="sm" className="mt-2" onClick={onShowMore}>
<ChevronDown className="w-4 h-4" />
Pokaż więcej
</Button>
{chartReady ? (
<ResponsiveContainer width="100%" height={220}>
{sided ? (
<LineChart data={sidedData}>
<CartesianGrid stroke="var(--border)" />
<XAxis dataKey="date" stroke="var(--text-dim)" />
<YAxis stroke="var(--text-dim)" domain={['auto', 'auto']} />
<Tooltip contentStyle={TOOLTIP_STYLE} />
{group.sidesPresent.map((side) => (
<Line
key={side}
type="monotone"
dataKey={side === 'left' ? 'lewy' : 'prawy'}
name={SIDE_LABELS[side]}
stroke={SIDE_STROKE[side]}
strokeWidth={2}
dot={false}
connectNulls
/>
))}
</LineChart>
) : (
<LineChart data={singleData}>
<CartesianGrid stroke="var(--border)" />
<XAxis dataKey="date" stroke="var(--text-dim)" />
<YAxis stroke="var(--text-dim)" domain={['auto', 'auto']} />
<Tooltip contentStyle={TOOLTIP_STYLE} />
<Line
type="monotone"
dataKey="value"
stroke={group.unit === 'kg' ? 'var(--accent)' : 'var(--info)'}
strokeWidth={2}
dot={false}
/>
</LineChart>
)}
</ResponsiveContainer>
) : (
<p className="text-dim">Za mało danych na wykres (min. 2 pomiary).</p>
)}
</div>
{sided && (
<div className="mt-2 flex flex-wrap gap-4 text-[0.875rem] text-dim">
{group.sidesPresent.map((side) => (
<span key={side} className="flex items-center gap-1.5">
<span
className="inline-block h-0.5 w-3 rounded-md"
style={{ background: SIDE_STROKE[side] }}
/>
{SIDE_LABELS[side]}
</span>
))}
</div>
)}
{/* lista: najnowsze 3 + „Pokaż więcej" (kolejne 3); pełna historia w wykresie */}
<div>
<ul className="mt-3 flex flex-col gap-1.5 sm:flex-row sm:overflow-x-auto sm:pb-1">
{[...group.points]
.reverse()
.slice(0, visible)
.map((p) => {
const kind = group.unit === 'kg' ? ('weight' as const) : ('circumference' as const);
const sideLabel = p.side ? ` · ${SIDE_LABELS[p.side]}` : '';
return (
<li
key={p.id}
className="border border-line bg-input rounded-xl px-3.5 py-2.5 text-[0.95rem] sm:w-44 sm:shrink-0"
>
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
<strong className="text-ink">
{p.value} {group.unit}
</strong>
<div className="mt-0.5 text-[0.875rem] text-dim">
{fmtDate(p.date)}
{sideLabel}
</div>
</div>
<button
type="button"
aria-label={`Usuń pomiar ${p.name} z ${fmtDate(p.date)}`}
onClick={() =>
onDelete({
kind,
id: p.id,
label: `${p.name} ${p.value} ${group.unit} (${fmtDate(p.date)})`,
})
}
className="p-1.5 -m-1.5 text-dim hover:text-danger cursor-pointer shrink-0"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
</li>
);
})}
</ul>
{group.points.length > visible && (
<Button variant="ghost" size="sm" className="mt-2" onClick={onShowMore}>
Pokaż więcej
</Button>
)}
</div>
</Card>
);
}
@@ -330,10 +483,8 @@ function AddMeasurementModal({
}
export default function ProfileBodyParameters() {
const navigate = useNavigate();
const { data: bp, isLoading: bpLoading, refetch: refetchBp } = useBodyParameters();
const { push } = useToast();
const { month, setMonth, setAvailableMonths } = useBodyParams();
const today = () => new Date().toISOString().slice(0, 10);
const [weight, setWeight] = useState('');
@@ -351,35 +502,65 @@ export default function ProfileBodyParameters() {
const [addOpen, setAddOpen] = useState(false);
const [addTab, setAddTab] = useState<'weight' | 'circ'>('weight');
const [visible, setVisible] = useState<Record<string, number>>({});
const [selected, setSelected] = useState<string | null>(null);
// menu top: selektor miesiąca (filtr po dacie) + akcja otwierająca modal w treści strony
// menu top: jedyna akcja strony (tworzenie pomiaru) — treść = dane i wybór części
useTopbar({
title: 'Parametry ciała',
back: '/profile',
dateFilter: <MonthPicker />,
filterActive: month !== '',
actions: [{ label: 'Dodaj pomiar', onClick: () => setAddOpen(true), icon: Plus }],
});
// lista: 3 najnowsze + „Pokaż więcej" (kolejne 3); zmiana miesiąca resetuje
// lista panelu: 3 najnowsze + „Pokaż więcej" (kolejne 3)
const countFor = (key: string) => visible[key] ?? 3;
const showMore = (key: string) => setVisible((v) => ({ ...v, [key]: (v[key] ?? 3) + 3 }));
useEffect(() => setVisible({}), [month]);
// miesiące z danymi (nowe → stare) — do selektora w topmenu
const monthKeys = [
...(bp?.weight ?? []).map((w) => w.date.slice(0, 7)),
...(bp?.circumferences ?? []).flatMap((s) => s.points.map((p) => p.date.slice(0, 7))),
];
const monthsKey = [...new Set(monthKeys)].sort().reverse().join(',');
useEffect(() => {
setAvailableMonths(monthsKey ? monthsKey.split(',') : []);
}, [monthsKey, setAvailableMonths]);
// wybrany miesiąc bez danych → najnowszy miesiąc z danymi
useEffect(() => {
const available = monthsKey ? monthsKey.split(',') : [];
if (available.length > 0 && !available.includes(month)) setMonth(available[0]);
}, [monthsKey, month, setMonth]);
// pełna historia: waga + obwody jako jednolite grupy (bez filtra miesiąca)
const groups = useMemo<PartGroup[]>(() => {
const list: PartGroup[] = [];
const weightPoints = [...(bp?.weight ?? [])].sort((a, b) => a.date.localeCompare(b.date));
if (weightPoints.length > 0) {
list.push({
part: WEIGHT_PART,
unit: 'kg',
points: weightPoints.map((w) => ({
id: w.id,
value: w.value,
date: w.date,
side: null,
name: 'wagi',
})),
sided: false,
sidesPresent: [],
});
}
for (const g of groupCircumferences(bp?.circumferences ?? [])) {
const points = g.series
.flatMap((s) =>
s.points.map((p) => ({
id: p.id,
value: p.value,
date: p.date,
side: sideOf(s.name),
name: s.name,
})),
)
.sort((a, b) => a.date.localeCompare(b.date));
list.push({
part: g.part,
unit: 'cm',
points,
sided: g.series.some((s) => sideOf(s.name) != null),
sidesPresent: [
...new Set(g.series.map((s) => sideOf(s.name)).filter((s): s is Side => s != null)),
],
});
}
return list;
}, [bp]);
// wybrana część odpada (brak danych) → pierwsza dostępna
const active = groups.find((g) => g.part === selected) ?? groups[0];
// ref (nie stan): drugi klik w tym samym ticku musi zobaczyć flagę natychmiast
const savingRef = useRef(false);
@@ -393,6 +574,7 @@ export default function ProfileBodyParameters() {
setWeight('');
setWeightDate(today());
setAddOpen(false);
setSelected(WEIGHT_PART);
await refetchBp();
push('Waga dodana', 'success');
} catch (err) {
@@ -406,15 +588,14 @@ export default function ProfileBodyParameters() {
e.preventDefault();
if (!circValue || savingRef.current) return;
savingRef.current = true;
const seriesName = measurementName(circType, circSide);
try {
await addCircumference(
measurementName(circType, circSide),
parseFloat(circValue),
circDate || undefined,
);
await addCircumference(seriesName, parseFloat(circValue), circDate || undefined);
setCircValue('');
setCircDate(today());
setAddOpen(false);
// dodany pomiar od razu widoczny w panelu jego części
setSelected(detectBodyPart(seriesName) ?? bodyPartOf(seriesName));
await refetchBp();
push('Obwód dodany', 'success');
} catch (err) {
@@ -441,34 +622,6 @@ export default function ProfileBodyParameters() {
}
};
// zakres: wybrany w topmenu miesiąc (YYYY-MM)
const inMonth = (date: string) => date.startsWith(month);
const weightPoints = [...(bp?.weight ?? [])]
.filter((w) => inMonth(w.date))
.sort((a, b) => a.date.localeCompare(b.date));
const weightData = weightPoints.map((w) => ({
date: new Date(w.date).toLocaleDateString('pl-PL', { day: '2-digit', month: '2-digit' }),
value: w.value,
}));
const latestWeight = weightPoints[weightPoints.length - 1];
// delta wagi w wybranym miesiącu: ostatni pomiar − pierwszy (spadek = accent, wzrost = warn)
const weightDelta =
weightPoints.length >= 2
? weightPoints[weightPoints.length - 1].value - weightPoints[0].value
: null;
const circGroups = groupCircumferences(
(bp?.circumferences ?? [])
.map((s) => ({
...s,
points: s.points
.filter((p) => inMonth(p.date))
.sort((a, b) => a.date.localeCompare(b.date)),
}))
.filter((s) => s.points.length > 0),
);
if (bpLoading) {
return (
<div className="space-y-4">
@@ -480,222 +633,42 @@ export default function ProfileBodyParameters() {
return (
<>
<PageHeader
title="Parametry ciała"
actions={<BackButton onClick={() => navigate('/profile')} />}
/>
<MeasurementCard
icon={Scale}
title="Waga"
latest={
latestWeight && (
<span className="flex flex-col items-end">
<span className="flex items-baseline gap-2">
<span className="font-display text-[1.35rem] font-bold leading-none tabular-nums">
{latestWeight.value} kg
</span>
<span className="text-[0.75rem] text-dim">· {fmtDate(latestWeight.date)}</span>
</span>
{weightDelta != null && weightDelta !== 0 && (
<span
className={`text-[0.75rem] font-semibold ${
weightDelta < 0 ? 'text-accent-text' : 'text-warn'
}`}
>
{weightDelta < 0 ? '−' : '+'}
{Math.abs(weightDelta).toLocaleString('pl-PL')} kg w tym miesiącu
</span>
)}
</span>
)
}
>
{weightPoints.length === 0 ? (
<EmptyState
icon={Scale}
title="Brak pomiarów wagi"
description="Dodaj pierwszy pomiar wagi, aby śledzić postęp."
action={
<Button
size="sm"
onClick={() => {
setAddTab('weight');
setAddOpen(true);
}}
>
<Plus className="w-4 h-4" />
Dodaj wagę
</Button>
}
/>
) : (
<>
{weightData.length >= 2 ? (
<ResponsiveContainer width="100%" height={220}>
<LineChart data={weightData}>
<CartesianGrid stroke="var(--border)" />
<XAxis dataKey="date" stroke="var(--text-dim)" />
<YAxis stroke="var(--text-dim)" domain={['auto', 'auto']} />
<Tooltip contentStyle={TOOLTIP_STYLE} />
<Line
type="monotone"
dataKey="value"
stroke="var(--accent)"
strokeWidth={2}
dot={false}
/>
</LineChart>
</ResponsiveContainer>
) : (
<p className="text-dim">Za mało danych na wykres (min. 2 pomiary).</p>
)}
<MeasurementList
points={[...weightPoints].reverse().map((p) => ({
id: p.id,
kind: 'weight' as const,
label: `${p.value} kg`,
meta: fmtDate(p.date),
deleteLabel: `Usuń pomiar wagi z ${fmtDate(p.date)}`,
removeLabel: `waga ${p.value} kg (${fmtDate(p.date)})`,
}))}
visible={countFor('weight')}
onShowMore={() => showMore('weight')}
onDelete={setRemoveTarget}
/>
</>
)}
</MeasurementCard>
{circGroups.length === 0 && (
<MeasurementCard icon={Ruler} title="Obwody">
<p className="text-dim">Brak pomiarów w wybranym miesiącu.</p>
</MeasurementCard>
)}
{circGroups.map((g) => {
const allPoints = g.series.flatMap((s) =>
s.points.map((p) => ({ ...p, name: s.name, side: sideOf(s.name) })),
);
const latest = allPoints.reduce<(typeof allPoints)[number] | null>(
(max, p) => (max == null || p.date > max.date ? p : max),
null,
);
const sided = g.series.some((s) => sideOf(s.name) != null);
const sidesPresent = [
...new Set(g.series.map((s) => sideOf(s.name)).filter((s): s is Side => s != null)),
];
const sideData = mergedSideData(g.series);
const chartReady = sided ? sideData.length >= 2 : g.series[0].points.length >= 2;
return (
<MeasurementCard
key={g.part}
icon={Ruler}
title={g.part}
latest={
latest && (
<span className="flex items-baseline gap-2">
<span className="font-display text-[1.35rem] font-bold leading-none tabular-nums">
{latest.value} cm
</span>
<span className="text-[0.75rem] text-dim">
{latest.side ? `${SIDE_LABELS[latest.side]} · ` : '· '}
{fmtDate(latest.date)}
</span>
</span>
)
}
{active == null ? (
<EmptyState
icon={Scale}
title="Brak pomiarów"
description="Dodaj pierwszy pomiar, aby śledzić postęp."
/>
) : (
<>
{/* 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"
>
{chartReady ? (
<>
<ResponsiveContainer width="100%" height={180}>
{sided ? (
<LineChart data={sideData}>
<CartesianGrid stroke="var(--border)" />
<XAxis dataKey="date" stroke="var(--text-dim)" />
<YAxis stroke="var(--text-dim)" domain={['auto', 'auto']} />
<Tooltip contentStyle={TOOLTIP_STYLE} />
<Line
type="monotone"
dataKey="lewy"
name="Lewy"
stroke="var(--info)"
strokeWidth={2}
dot={false}
connectNulls
/>
<Line
type="monotone"
dataKey="prawy"
name="Prawy"
stroke="var(--accent)"
strokeWidth={2}
dot={false}
connectNulls
/>
</LineChart>
) : (
<LineChart
data={g.series[0].points.map((p) => ({
date: new Date(p.date).toLocaleDateString('pl-PL', {
day: '2-digit',
month: '2-digit',
}),
value: p.value,
}))}
>
<CartesianGrid stroke="var(--border)" />
<XAxis dataKey="date" stroke="var(--text-dim)" />
<YAxis stroke="var(--text-dim)" domain={['auto', 'auto']} />
<Tooltip contentStyle={TOOLTIP_STYLE} />
<Line
type="monotone"
dataKey="value"
stroke="var(--info)"
strokeWidth={2}
dot={false}
/>
</LineChart>
)}
</ResponsiveContainer>
{sided && (
<div className="mt-2 flex flex-wrap gap-4 text-[0.875rem] text-dim">
{sidesPresent.includes('left') && (
<span className="flex items-center gap-1.5">
<span className="w-3 h-0.5 bg-info inline-block rounded-md" />
Lewy
</span>
)}
{sidesPresent.includes('right') && (
<span className="flex items-center gap-1.5">
<span className="w-3 h-0.5 bg-accent inline-block rounded-md" />
Prawy
</span>
)}
</div>
)}
</>
) : (
<p className="text-dim">Za mało danych na wykres.</p>
)}
<MeasurementList
points={[...allPoints]
.sort((a, b) => b.date.localeCompare(a.date))
.map((p) => ({
id: p.id,
kind: 'circumference' as const,
label: `${p.value} cm`,
meta: `${fmtDate(p.date)}${p.side ? ` · ${SIDE_LABELS[p.side]}` : ''}`,
deleteLabel: `Usuń pomiar ${p.name} z ${fmtDate(p.date)}`,
removeLabel: `${p.name} ${p.value} cm (${fmtDate(p.date)})`,
}))}
visible={countFor(g.part)}
onShowMore={() => showMore(g.part)}
{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>
<div className="mt-4">
<MeasurementPanel
group={active}
icon={active.part === WEIGHT_PART ? Scale : Ruler}
visible={countFor(active.part)}
onShowMore={() => showMore(active.part)}
onDelete={setRemoveTarget}
/>
</MeasurementCard>
);
})}
</div>
</>
)}
<AddMeasurementModal
open={addOpen}

View File

@@ -1,64 +0,0 @@
import { create } from 'zustand';
function currentMonth(): string {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
}
interface BodyParamsState {
/** Wybrany miesiąc (YYYY-MM) — zakres danych na /profile/body-parameters. */
month: string;
setMonth: (month: string) => void;
/** Miesiące z danymi (YYYY-MM, najnowsze pierwsze) — zasilane przez stronę. */
availableMonths: string[];
setAvailableMonths: (months: string[]) => void;
}
/**
* Zakres dat na podstronie „Parametry ciała": selektor miesiąca w topmenu (Layout)
* filtruje wykresy i listy; domyślnie bieżący miesiąc. Lista miesięcy do wyboru
* zawiera tylko te, które mają dane (strona podaje je przez `setAvailableMonths`).
*/
export const useBodyParams = create<BodyParamsState>((set) => ({
month: currentMonth(),
setMonth: (month) => set({ month }),
availableMonths: [],
setAvailableMonths: (availableMonths) => set({ availableMonths }),
}));
const MONTH_NAMES = [
'Styczeń',
'Luty',
'Marzec',
'Kwiecień',
'Maj',
'Czerwiec',
'Lipiec',
'Sierpień',
'Wrzesień',
'Październik',
'Listopad',
'Grudzień',
];
/** Krótkie nazwy do siatki miesięcy w panelu selektora. */
export const MONTH_SHORT = [
'Sty',
'Lut',
'Mar',
'Kwi',
'Maj',
'Cze',
'Lip',
'Sie',
'Wrz',
'Paź',
'Lis',
'Gru',
];
/** `2026-08` → `Sierpień 2026`. */
export function formatMonth(month: string): string {
const [y, m] = month.split('-').map(Number);
return `${MONTH_NAMES[m - 1]} ${y}`;
}

View File

@@ -1,7 +1,7 @@
import { useState } from 'react';
import { Calendar, ChevronLeft, ChevronRight } from 'lucide-react';
import { Button } from '../components/ui';
import { useBodyParams, formatMonth, MONTH_SHORT } from '../store/body-params';
import { formatMonth, MONTH_SHORT } from '../lib/format';
function currentMonthStr(): string {
const d = new Date();
@@ -30,8 +30,8 @@ export interface MonthPickerCoreProps {
/**
* Selektor miesiąca (YYYY-MM) — widget top menu.
* Wariant domyślny (parametry ciała): tylko miesiące z danymi.
* Wariant `allowAll` (historia): „Wszystkie” + pełna siatka kalendarzowa.
* Domyślny: strzałki skaczą między miesiącami z danymi (`availableMonths`).
*/
export function MonthPickerCore({
month,
@@ -219,9 +219,3 @@ export function MonthPickerCore({
</div>
);
}
/** Selektor miesiąca dla strony parametrów ciała (stan w `useBodyParams`). */
export function MonthPicker() {
const { month, setMonth, availableMonths } = useBodyParams();
return <MonthPickerCore month={month} setMonth={setMonth} availableMonths={availableMonths} />;
}

View File

@@ -1,5 +1,5 @@
export { Topbar } from './Topbar';
export { MonthPicker, MonthPickerCore } from './MonthPicker';
export { MonthPickerCore } from './MonthPicker';
export { useTopbar } from './useTopbar';
export { useTopbarStore } from './store';
export type { TopbarAction, TopbarConfig, TopbarCustomGroup, TopbarGroup } from './types';

View File

@@ -7,7 +7,7 @@ import App from '../src/App';
import { useAuth } from '../src/store/auth';
import { setAccessToken } from '../src/api/client';
import { monthStr } from '../src/lib/format';
import { formatMonth } from '../src/store/body-params';
import { formatMonth } from '../src/lib/format';
import type { User } from '../src/api/types';
const USER: User = {

View File

@@ -6,7 +6,6 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import App from '../src/App';
import { useAuth } from '../src/store/auth';
import { setAccessToken } from '../src/api/client';
import { useBodyParams } from '../src/store/body-params';
import type { User } from '../src/api/types';
const USER: User = {
@@ -125,6 +124,11 @@ async function loginToProfile(user: userEvent.User) {
).toBeInTheDocument();
}
/** Klik w kafel części ciała z paska (kafel to jedyny przycisk z datą najnowszego pomiaru). */
function selectPart(part: string) {
return screen.getByRole('button', { name: new RegExp(`^${part}.*\\d{2}\\.\\d{2}\\.\\d{4}`) });
}
function renderApp() {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } },
@@ -143,8 +147,6 @@ beforeEach(async () => {
setAccessToken(null);
localStorage.clear();
useAuth.setState({ user: null, ready: false });
// deterministyczny miesiąc — dane w mockach są z 07/08.2026
useBodyParams.setState({ month: '2026-08', availableMonths: [] });
});
afterEach(() => {
@@ -158,13 +160,16 @@ describe('Profile — body parameter removal', () => {
renderApp();
await loginToProfile(user);
// lista wag (najnowsze pierwsze) i obwodów z przyciskami usuwania
// domyślnie wybrana „Waga": pełna historia pomiarów z przyciskami usuwania
expect(await screen.findByText('82.5 kg')).toBeInTheDocument();
// 81.8 kg: nagłówek (ostatni pomiar) + wiersz listy
// 81.8 kg: nagłówek panelu (ostatni pomiar) + wiersz listy
expect(screen.getAllByText('81.8 kg').length).toBe(2);
// 38 cm: nagłówek serii (ostatni pomiar) + wiersz listy
expect(screen.getAllByText('38 cm').length).toBe(2);
expect(screen.getAllByRole('button', { name: /Usuń pomiar wagi/ }).length).toBe(2);
// obwody żyją w panelu swojej części — otwieranym z paska kaflów
await user.click(selectPart('Biceps'));
// 38 cm: nagłówek panelu (ostatni pomiar) + wiersz listy
expect(screen.getAllByText('38 cm').length).toBe(2);
expect(screen.getByRole('button', { name: /Usuń pomiar Biceps lewy/ })).toBeInTheDocument();
});
@@ -202,21 +207,20 @@ describe('Profile — body parameter removal', () => {
renderApp();
await loginToProfile(user);
// `Bicepcs` scalony z grupą Biceps — nie ma osobnego nagłówka
expect(await screen.findByText('Biceps')).toBeInTheDocument(); // nagłówek grupy
// pasek kaflów: `Bicepcs` scalony z grupą Biceps — nie ma osobnego kafla
await user.click(selectPart('Biceps'));
expect(screen.queryByText('Bicepcs')).not.toBeInTheDocument();
// nagłówek grupy: najnowszy pomiar (40 cm, 20.08) + wiersz listy
expect(screen.getAllByText('40 cm').length).toBe(2);
// legenda obu stron
// nagłówek panelu: najnowszy pomiar grupy (40 cm, 20.08)
expect(screen.getAllByText('40 cm').length).toBe(2); // nagłówek + wiersz listy
// legenda obu stron przy wykresie
expect(screen.getByText('Lewy')).toBeInTheDocument();
expect(screen.getByText('Prawy')).toBeInTheDocument();
// wiersze listy z oznaczeniem strony
expect(screen.getByText('15.08.2026 · Lewy')).toBeInTheDocument();
expect(screen.getByText('15.08.2026 · Prawy')).toBeInTheDocument();
// wiersz pomiaru bez strony (Bicepcs) — sama data
expect(screen.getByText('20.08.2026')).toBeInTheDocument();
// talia to osobna grupa
expect(screen.getByText('Talia')).toBeInTheDocument();
// talia to osobna grupa — własny kafel i panel
await user.click(selectPart('Talia'));
expect(screen.getAllByText('80 cm').length).toBe(2); // nagłówek panelu + wiersz
});
it('opens the add-measurement modal from the context menu', async () => {
@@ -240,7 +244,25 @@ describe('Profile — body parameter removal', () => {
expect(screen.getByPlaceholderText('wartość (cm)')).toBeInTheDocument();
});
it('filters data by the month selected in the top menu', async () => {
it('shows the weight delta vs previous measurement; adding lives only in the top menu', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await loginToProfile(user);
// delta: 81.8 (15.08) − 82.5 (01.08) = −0,7 kg (spadek) — liczona z pełnej historii
expect(await screen.findByText('82.5 kg')).toBeInTheDocument();
expect(screen.getByText('−0,7 kg vs poprzedni')).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();
await user.click(screen.getByRole('button', { name: 'Dodaj pomiar' }));
expect(await screen.findByRole('dialog')).toBeInTheDocument();
expect(screen.getByPlaceholderText('waga (kg)')).toBeInTheDocument();
});
it('shows all measurements from every month (chart covers the full history)', async () => {
mockApi([
{ id: 'c-1', name: 'Talia', value: 80, date: '2026-07-10T08:00:00.000Z' },
{ id: 'c-2', name: 'Talia', value: 82, date: '2026-08-10T08:00:00.000Z' },
@@ -249,69 +271,13 @@ describe('Profile — body parameter removal', () => {
renderApp();
await loginToProfile(user);
// domyślnie 08.2026 (ustawione w beforeEach): waga + talia z sierpnia
// pomiary spoza bieżącego miesiąca są widoczne bez żadnego filtra
expect(await screen.findByText('82.5 kg')).toBeInTheDocument();
expect(screen.getAllByText('82 cm').length).toBe(2); // nagłówek grupy + wiersz
expect(screen.queryByText('10.07.2026')).not.toBeInTheDocument();
// selektor miesiąca jest w grupie lejka (ikona „Filtry” w nagłówku)
await user.click(screen.getByRole('button', { name: 'Filtry' }));
// strzałki: z sierpnia — poprzedni z danymi (lipiec) jest, kolejnego nie ma
await waitFor(() =>
expect(screen.getByRole('button', { name: 'Poprzedni miesiąc z danymi' })).toBeEnabled(),
);
expect(screen.getByRole('button', { name: 'Następny miesiąc z danymi' })).toBeDisabled();
// panel: filtr po roku + siatka 12 miesięcy; bez danych = nieaktywne
await user.click(screen.getByRole('button', { name: 'Sierpień 2026' }));
expect(screen.getByRole('button', { name: '2026', exact: true })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Lip', exact: true })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Cze', exact: true })).toBeDisabled();
// zmiana miesiąca — dane z lipca, sierpień znika
await user.click(screen.getByRole('button', { name: 'Lip', exact: true }));
await waitFor(() => expect(screen.queryByText('82.5 kg')).not.toBeInTheDocument());
expect(screen.getAllByText('80 cm').length).toBe(2);
expect(screen.queryByText('82 cm')).not.toBeInTheDocument();
// z lipca: poprzedniego z danymi nie ma, kolejny (sierpień) jest
await waitFor(() =>
expect(screen.getByRole('button', { name: 'Następny miesiąc z danymi' })).toBeEnabled(),
);
expect(screen.getByRole('button', { name: 'Poprzedni miesiąc z danymi' })).toBeDisabled();
});
it('pokaże deltę wagi w wybranym miesiącu, a dodanie wagi jest tylko w topmenu', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await loginToProfile(user);
// delta: 81.8 (15.08) − 82.5 (01.08) = −0,7 kg (spadek)
expect(await screen.findByText('82.5 kg')).toBeInTheDocument();
expect(screen.getByText('−0,7 kg w tym miesiącu')).toBeInTheDocument();
// 1 kontrolka = 1 miejsce: w nagłówku karty brak przycisku „+ Waga”
expect(screen.queryByRole('button', { name: '+ Waga' })).not.toBeInTheDocument();
// dodanie wagi wyłącznie z topmenu (modal otwiera się na zakładce Waga)
await user.click(screen.getByRole('button', { name: 'Dodaj pomiar' }));
expect(await screen.findByRole('dialog')).toBeInTheDocument();
expect(screen.getByPlaceholderText('waga (kg)')).toBeInTheDocument();
});
it('auto-selects the latest month with data when the selected month is empty', async () => {
mockApi();
const user = userEvent.setup();
// wrzesień 2026 nie ma danych w mockach
useBodyParams.setState({ month: '2026-09', availableMonths: [] });
renderApp();
await loginToProfile(user);
// po załadowaniu danych: najnowszy miesiąc z danymi (sierpień) — selektor w grupie „Filtry”
await user.click(screen.getByRole('button', { name: 'Filtry' }));
expect(await screen.findByRole('button', { name: 'Sierpień 2026' })).toBeInTheDocument();
expect(screen.getByText('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();
});
});

View File

@@ -82,7 +82,9 @@ test('mobile: dane osobowe — bottom sheet mięśni z zakładkami i wyszukiwark
await expectNoHorizontalScroll(page, 'dane osobowe');
});
test('mobile: parametry ciała — delta wagi i dodanie pomiaru z topmenu', async ({ page }) => {
test('mobile: parametry ciała — pasek kaflów, delta wagi i dodanie pomiaru z topmenu', async ({
page,
}) => {
const now = new Date();
const ym = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
mockApi(page, {
@@ -99,9 +101,12 @@ test('mobile: parametry ciała — delta wagi i dodanie pomiaru z topmenu', asyn
await page.getByRole('link', { name: /Parametry ciała/ }).click();
await expect(page.getByRole('heading', { name: 'Parametry ciała', level: 1 })).toBeVisible();
// najnowsza waga + delta w bieżącym miesiącu (spadek); wartość też w liście → first()
// 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();
await expect(page.getByText('81.8 kg').first()).toBeVisible();
await expect(page.getByText('−0,7 kg w tym miesiącu')).toBeVisible();
// brak przycisków dodawania w treści — 1 kontrolka = 1 miejsce (tylko topmenu)
await expect(page.getByRole('button', { name: 'Dodaj wagę' })).toHaveCount(0);
// dodanie wagi wyłącznie z topmenu (telefon): „➕” → „Dodaj pomiar”
await page.getByRole('button', { name: 'Dodawanie' }).click();