Profil: naprawa wykresu obwodow przy asymetrii stron i pomiarach z jednego dnia + zgodna gramatycznie strona w formularzu

This commit is contained in:
tisachi
2026-10-17 06:47:35 +02:00
parent 0cf2bf370d
commit bb9a0120b2
4 changed files with 140 additions and 53 deletions

View File

@@ -20,6 +20,31 @@ export const MEASUREMENT_TYPES: MeasurementType[] = [
export const SIDE_LABELS: Record<Side, string> = { left: 'Lewy', right: 'Prawy' };
/* Rodzaj gramatyczny części ciała → poprawna fleksja przymiotnika strony. */
const PART_GENDERS: Record<string, 'm' | 'f' | 'n' | 'p'> = {
'Klatka piersiowa': 'f',
Talia: 'f',
Biodra: 'p',
Kark: 'm',
Biceps: 'm',
Przedramię: 'n',
Udo: 'n',
Łydka: 'f',
};
/** Etykiety strony zgodne z rodzajem części: `Udo` → `Lewe`/`Prawe`, `Talia` → `Lewa`/`Prawa`. */
export function sideLabelsFor(part: string): Record<Side, string> {
switch (PART_GENDERS[part]) {
case 'f':
return { left: 'Lewa', right: 'Prawa' };
case 'n':
case 'p':
return { left: 'Lewe', right: 'Prawe' };
default:
return SIDE_LABELS;
}
}
export function measurementType(typeId: string): MeasurementType | undefined {
return MEASUREMENT_TYPES.find((t) => t.id === typeId);
}

View File

@@ -39,6 +39,7 @@ import {
detectBodyPart,
measurementType,
measurementName,
sideLabelsFor,
sideOf,
type Side,
} from '../../lib/body-measurements';
@@ -116,8 +117,9 @@ interface PartGroup {
unit: 'kg' | 'cm';
/** Wszystkie pomiary (pełna historia), rosnąco po dacie. */
points: GroupPoint[];
sided: boolean;
sidesPresent: Side[];
/** Wykres dwuliniowy tylko gdy każda obecna strona ma ≥2 pomiary. */
chartSided: boolean;
}
const WEIGHT_PART = 'Waga';
@@ -132,7 +134,7 @@ function groupDelta(g: PartGroup): { text: string; className: string } | null {
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) {
if (g.chartSided) {
const parts = g.sidesPresent
.map((side) => {
const pts = g.points.filter((p) => p.side === side);
@@ -163,24 +165,32 @@ function axisDateLabel(iso: string, withYear: boolean): string {
/**
* Wspólna oś dat dla serii: `[{ date, lewy, prawy }]` (brak pomiaru = null).
* Jednostronna grupa → kolumna wg bieżącej strony (osie nazywane po stronie).
* 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.
*/
function sideSeriesData(points: GroupPoint[], sides: Side[], withYear: boolean) {
const col = (side: Side) => (side === 'left' ? 'lewy' : 'prawy');
const byDate = new Map<string, Record<string, number | null>>();
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 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);
const row = byDate.get(p.date) ?? {};
row[p.side] = p.value;
byDate.set(p.date, row);
}
return [...byDate.entries()]
.sort((a, b) => a[0].localeCompare(b[0]))
.map(([date, row]) => ({
date: axisDateLabel(date, withYear),
...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;
}
const SIDE_STROKE: Record<Side, string> = { left: 'var(--info)', right: 'var(--accent)' };
@@ -243,18 +253,33 @@ function MeasurementPanel({
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;
// dwuliniowo tylko gdy każda strona ma min. 2 pomiary (patrz chartSided)
const sided = group.chartSided;
// 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;
const singleData = group.points.map((p) => ({
date: axisDateLabel(p.date, withYear),
value: p.value,
}));
const sidedData = sided ? sideSeriesData(group.points, group.sidesPresent, withYear) : [];
const chartReady = sided ? sidedData.length >= 2 : group.points.length >= 2;
// 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;
return (
<Card>
@@ -316,7 +341,7 @@ function MeasurementPanel({
</LineChart>
) : (
(() => {
const stroke = unitStroke(group.unit);
const stroke = chartSide ? SIDE_STROKE[chartSide] : unitStroke(group.unit);
const areaId = `bp-area-${encodeURIComponent(group.part)}`;
return (
<AreaChart data={singleData} margin={CHART_MARGIN}>
@@ -347,7 +372,11 @@ function MeasurementPanel({
<Area
type="monotone"
dataKey="value"
name={group.part}
name={
chartSide
? `${group.part} (${sideLabelsFor(group.part)[chartSide].toLowerCase()})`
: group.part
}
stroke={stroke}
strokeWidth={2}
fill={`url(#${areaId})`}
@@ -515,27 +544,29 @@ function AddMeasurementModal({
))}
</Select>
{measurementType(circType)?.sided && (
<div
className="inline-flex self-start overflow-hidden rounded-xl border border-line bg-input"
role="group"
aria-label="Strona"
>
{(['left', 'right'] as Side[]).map((s) => (
<button
key={s}
type="button"
aria-pressed={circSide === s}
onClick={() => onCircSideChange(s)}
className={`px-3 py-2.5 text-[0.95rem] cursor-pointer transition-colors ${
circSide === s
? 'bg-accent/15 font-semibold text-accent-text'
: 'text-dim hover:text-ink'
}`}
>
{SIDE_LABELS[s]}
</button>
))}
</div>
<Field label="Strona">
<div
className="inline-flex overflow-hidden rounded-xl border border-line bg-input"
role="group"
aria-label="Strona"
>
{(['left', 'right'] as Side[]).map((s) => (
<button
key={s}
type="button"
aria-pressed={circSide === s}
onClick={() => onCircSideChange(s)}
className={`px-3 py-2.5 text-[0.95rem] cursor-pointer transition-colors ${
circSide === s
? 'bg-accent/15 font-semibold text-accent-text'
: 'text-dim hover:text-ink'
}`}
>
{sideLabelsFor(measurementType(circType)!.label)[s]}
</button>
))}
</div>
</Field>
)}
<Input
type="number"
@@ -610,7 +641,7 @@ export default function ProfileBodyParameters() {
side: null,
name: 'wagi',
})),
sided: false,
chartSided: false,
sidesPresent: [],
});
}
@@ -626,14 +657,19 @@ export default function ProfileBodyParameters() {
})),
)
.sort((a, b) => a.date.localeCompare(b.date));
const sidesPresent = [
...new Set(g.series.map((s) => sideOf(s.name)).filter((s): s is Side => s != null)),
];
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)),
],
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;

View File

@@ -223,6 +223,24 @@ describe('Profile — body parameter removal', () => {
expect(screen.getAllByText('80 cm').length).toBe(2); // nagłówek panelu + wiersz
});
it('rysuje wykres przy pomiarach z jednego dnia i asymetrii stron', async () => {
mockApi([
// dwa prawe i jedno lewe z TEJ SAMEJ daty — dawniej oś X scalała się
// w jedną kategorię i wykres w ogóle się nie rysował
{ id: 'c-1', name: 'Udo prawy', value: 55, date: '2026-08-10T08:00:00.000Z' },
{ id: 'c-2', name: 'Udo prawy', value: 56, date: '2026-08-10T19:00:00.000Z' },
{ id: 'c-3', name: 'Udo lewy', value: 54, date: '2026-08-10T12:00:00.000Z' },
]);
const user = userEvent.setup();
renderApp();
await loginToProfile(user);
await user.click(selectPart('Udo'));
// nagłówek panelu (ostatni 56) + wiersz listy
expect((await screen.findAllByText('56 cm')).length).toBeGreaterThanOrEqual(2);
expect(screen.queryByText(/Za mało danych na wykres/)).not.toBeInTheDocument();
});
it('opens the add-measurement modal from the context menu', async () => {
mockApi();
const user = userEvent.setup();

View File

@@ -144,14 +144,22 @@ describe('Profile — circumference form (predefined list)', () => {
// domyślny typ (klatka) nie ma strony lewy/prawy
expect(screen.queryByRole('button', { name: 'Lewy' })).not.toBeInTheDocument();
// biceps ma przełącznik lewy/prawy
// biceps ma przełącznik strony z etykietą „Strona”
await user.selectOptions(select, 'biceps');
expect(await screen.findByRole('button', { name: 'Lewy' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Prawy' })).toBeInTheDocument();
expect(screen.getByText('Strona')).toBeInTheDocument();
// talia znów ukrywa przełącznik
// udo (rodzaj nijaki) → zgadza się fleksja: Lewe/Prawe, nie „Lewy Udo”
await user.selectOptions(select, 'thigh');
expect(await screen.findByRole('button', { name: 'Lewe' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Prawe' })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Lewy' })).not.toBeInTheDocument();
// biodra i talia nie mają strony → brak przełącznika
await user.selectOptions(select, 'waist');
expect(screen.queryByRole('button', { name: 'Lewy' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Lewe' })).not.toBeInTheDocument();
});
it('sends the composed name (type + side) to the API', async () => {