From 0d908c677a3dca2b7c19f0c03f6e043043ca3420 Mon Sep 17 00:00:00 2001 From: tisachi Date: Sat, 17 Oct 2026 06:32:51 +0200 Subject: [PATCH] Profil: parametry ciala w formie paska kafelow z panelem jednej czesci (pelna historia, bez filtra miesiaca) --- app/src/components/calendar/CalendarView.tsx | 2 +- app/src/components/ui/week-picker.tsx | 2 +- app/src/lib/format.ts | 37 + .../pages/profile/ProfileBodyParameters.tsx | 701 +++++++++--------- app/src/store/body-params.ts | 64 -- app/src/topbar/MonthPicker.tsx | 10 +- app/src/topbar/index.ts | 2 +- app/test/Calendar.test.tsx | 2 +- app/test/ProfileBodyParameters.test.tsx | 126 ++-- app/test/e2e/profile-mobile.spec.ts | 11 +- 10 files changed, 434 insertions(+), 523 deletions(-) delete mode 100644 app/src/store/body-params.ts diff --git a/app/src/components/calendar/CalendarView.tsx b/app/src/components/calendar/CalendarView.tsx index c3100e1..bb1667c 100644 --- a/app/src/components/calendar/CalendarView.tsx +++ b/app/src/components/calendar/CalendarView.tsx @@ -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'; diff --git a/app/src/components/ui/week-picker.tsx b/app/src/components/ui/week-picker.tsx index 3754a58..43dbf1f 100644 --- a/app/src/components/ui/week-picker.tsx +++ b/app/src/components/ui/week-picker.tsx @@ -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'; diff --git a/app/src/lib/format.ts b/app/src/lib/format.ts index ed590b3..048f605 100644 --- a/app/src/lib/format.ts +++ b/app/src/lib/format.ts @@ -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}`; +} diff --git a/app/src/pages/profile/ProfileBodyParameters.tsx b/app/src/pages/profile/ProfileBodyParameters.tsx index 507b2c6..05604f4 100644 --- a/app/src/pages/profile/ProfileBodyParameters.tsx +++ b/app/src/pages/profile/ProfileBodyParameters.tsx @@ -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(); - 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>(); + 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 = { 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 ( + + ); +} + +/* 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 (
@@ -126,73 +227,125 @@ function MeasurementCard({ -

{title}

-
-
- {latest} - {actions} +

{group.part}

+ + + + {latest.value} {group.unit} + + + {latest.side ? `${SIDE_LABELS[latest.side]} · ` : ''} + {fmtDate(latest.date)} + + + - {children} -
- ); -} -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 ( -
- {/* 3 najnowsze; duże ekrany: wiersz z poziomym scrollem, małe: kolumna */} -
    - {points.slice(0, visible).map((p) => ( -
  • -
    -
    - {p.label} -
    {p.meta}
    -
    - -
    -
  • - ))} -
- {points.length > visible && ( - + {chartReady ? ( + + {sided ? ( + + + + + + {group.sidesPresent.map((side) => ( + + ))} + + ) : ( + + + + + + + + )} + + ) : ( +

Za mało danych na wykres (min. 2 pomiary).

)} -
+ {sided && ( +
+ {group.sidesPresent.map((side) => ( + + + {SIDE_LABELS[side]} + + ))} +
+ )} + + {/* lista: najnowsze 3 + „Pokaż więcej" (kolejne 3); pełna historia w wykresie */} +
+
    + {[...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 ( +
  • +
    +
    + + {p.value} {group.unit} + +
    + {fmtDate(p.date)} + {sideLabel} +
    +
    + +
    +
  • + ); + })} +
+ {group.points.length > visible && ( + + )} +
+ ); } @@ -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>({}); + const [selected, setSelected] = useState(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: , - 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(() => { + 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 (
@@ -480,222 +633,42 @@ export default function ProfileBodyParameters() { return ( <> - navigate('/profile')} />} - /> - - - - - {latestWeight.value} kg - - · {fmtDate(latestWeight.date)} - - {weightDelta != null && weightDelta !== 0 && ( - - {weightDelta < 0 ? '−' : '+'} - {Math.abs(weightDelta).toLocaleString('pl-PL')} kg w tym miesiącu - - )} - - ) - } - > - {weightPoints.length === 0 ? ( - { - setAddTab('weight'); - setAddOpen(true); - }} - > - - Dodaj wagę - - } - /> - ) : ( - <> - {weightData.length >= 2 ? ( - - - - - - - - - - ) : ( -

Za mało danych na wykres (min. 2 pomiary).

- )} - ({ - 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} - /> - - )} -
- - {circGroups.length === 0 && ( - -

Brak pomiarów w wybranym miesiącu.

-
- )} - {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 ( - - - {latest.value} cm - - - {latest.side ? `${SIDE_LABELS[latest.side]} · ` : '· '} - {fmtDate(latest.date)} - - - ) - } + {active == null ? ( + + ) : ( + <> + {/* pasek kaflów: najnowsze wartości wszystkich części; klik = panel poniżej */} +
- {chartReady ? ( - <> - - {sided ? ( - - - - - - - - - ) : ( - ({ - date: new Date(p.date).toLocaleDateString('pl-PL', { - day: '2-digit', - month: '2-digit', - }), - value: p.value, - }))} - > - - - - - - - )} - - {sided && ( -
- {sidesPresent.includes('left') && ( - - - Lewy - - )} - {sidesPresent.includes('right') && ( - - - Prawy - - )} -
- )} - - ) : ( -

Za mało danych na wykres.

- )} - 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) => ( + setSelected(g.part)} + /> + ))} +
+ +
+ showMore(active.part)} onDelete={setRemoveTarget} /> - - ); - })} +
+ + )} 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((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}`; -} diff --git a/app/src/topbar/MonthPicker.tsx b/app/src/topbar/MonthPicker.tsx index fac9fec..2f8110a 100644 --- a/app/src/topbar/MonthPicker.tsx +++ b/app/src/topbar/MonthPicker.tsx @@ -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({
); } - -/** Selektor miesiąca dla strony parametrów ciała (stan w `useBodyParams`). */ -export function MonthPicker() { - const { month, setMonth, availableMonths } = useBodyParams(); - return ; -} diff --git a/app/src/topbar/index.ts b/app/src/topbar/index.ts index 722bd38..8c4ef17 100644 --- a/app/src/topbar/index.ts +++ b/app/src/topbar/index.ts @@ -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'; diff --git a/app/test/Calendar.test.tsx b/app/test/Calendar.test.tsx index af2ca0b..eb22df1 100644 --- a/app/test/Calendar.test.tsx +++ b/app/test/Calendar.test.tsx @@ -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 = { diff --git a/app/test/ProfileBodyParameters.test.tsx b/app/test/ProfileBodyParameters.test.tsx index f236002..aa8c68a 100644 --- a/app/test/ProfileBodyParameters.test.tsx +++ b/app/test/ProfileBodyParameters.test.tsx @@ -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(); }); }); diff --git a/app/test/e2e/profile-mobile.spec.ts b/app/test/e2e/profile-mobile.spec.ts index 43d272d..0463cbc 100644 --- a/app/test/e2e/profile-mobile.spec.ts +++ b/app/test/e2e/profile-mobile.spec.ts @@ -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();