Cialo: tlumaczone etykiety pomiarow w panelu admina (namespace body PL/EN, hook useMeasurementLabels, strona pomiarow czyta typeId+side, grupa legacy po name)

This commit is contained in:
tisachi
2026-10-17 11:17:03 +02:00
parent bde01ef105
commit 25b9a2f8bf
8 changed files with 176 additions and 166 deletions

View File

@@ -272,7 +272,12 @@ export interface WeightPoint {
}
export interface CircumferenceSeries {
name: string;
/** Identyfikator typu (chest/waist/...) lub null dla starszego pomiaru swobodnego. */
typeId: string | null;
/** Strona (left/right) dla pomiarów w parach lub null. */
side: 'left' | 'right' | null;
/** Zachowana swobodna nazwa — tylko gdy typeId jest null. */
name: string | null;
points: WeightPoint[];
}

View File

@@ -9,16 +9,18 @@ import {
import plCommon from './locales/pl/common.json';
import plAuth from './locales/pl/auth.json';
import plErrors from './locales/pl/errors.json';
import plBody from './locales/pl/body.json';
import enCommon from './locales/en/common.json';
import enAuth from './locales/en/auth.json';
import enErrors from './locales/en/errors.json';
import enBody from './locales/en/body.json';
export const NAMESPACES = ['common', 'auth', 'errors'] as const;
export const NAMESPACES = ['common', 'auth', 'errors', 'body'] as const;
export type Namespace = (typeof NAMESPACES)[number];
const resources = {
pl: { common: plCommon, auth: plAuth, errors: plErrors },
en: { common: enCommon, auth: enAuth, errors: enErrors },
pl: { common: plCommon, auth: plAuth, errors: plErrors, body: plBody },
en: { common: enCommon, auth: enAuth, errors: enErrors, body: enBody },
} as const;
const initial = detectInitialLanguage();

View File

@@ -0,0 +1,19 @@
{
"weight": "Weight",
"chest": "Chest",
"waist": "Waist",
"hips": "Hips",
"neck": "Neck",
"biceps": "Biceps",
"forearm": "Forearm",
"thigh": "Thigh",
"calf": "Calf",
"side": {
"left_m": "Left",
"right_m": "Right",
"left_f": "Left",
"right_f": "Right",
"left_n": "Left",
"right_n": "Right"
}
}

View File

@@ -0,0 +1,19 @@
{
"weight": "Waga",
"chest": "Klatka piersiowa",
"waist": "Talia",
"hips": "Biodra",
"neck": "Kark",
"biceps": "Biceps",
"forearm": "Przedramię",
"thigh": "Udo",
"calf": "Łydka",
"side": {
"left_m": "Lewy",
"right_m": "Prawy",
"left_f": "Lewa",
"right_f": "Prawa",
"left_n": "Lewe",
"right_n": "Prawe"
}
}

View File

@@ -1,117 +1,28 @@
export type Side = 'left' | 'right';
/** Rodzaj gramatyczny części ciała → poprawna fleksja przymiotnika strony (PL). */
export type Gender = 'm' | 'f' | 'n' | 'p';
export interface MeasurementType {
id: string;
label: string;
/** pomiar w parach lewy/prawy (biceps, udo, ...) */
sided: boolean;
gender: Gender;
}
export const MEASUREMENT_TYPES: MeasurementType[] = [
{ id: 'chest', label: 'Klatka piersiowa', sided: false },
{ id: 'waist', label: 'Talia', sided: false },
{ id: 'hips', label: 'Biodra', sided: false },
{ id: 'neck', label: 'Kark', sided: false },
{ id: 'biceps', label: 'Biceps', sided: true },
{ id: 'forearm', label: 'Przedramię', sided: true },
{ id: 'thigh', label: 'Udo', sided: true },
{ id: 'calf', label: 'Łydka', sided: true },
{ id: 'chest', sided: false, gender: 'f' },
{ id: 'waist', sided: false, gender: 'f' },
{ id: 'hips', sided: false, gender: 'p' },
{ id: 'neck', sided: false, gender: 'm' },
{ id: 'biceps', sided: true, gender: 'm' },
{ id: 'forearm', sided: true, gender: 'n' },
{ id: 'thigh', sided: true, gender: 'n' },
{ id: 'calf', sided: true, gender: 'f' },
];
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 const MEASUREMENT_TYPE_IDS: string[] = MEASUREMENT_TYPES.map((t) => t.id);
export function measurementType(typeId: string): MeasurementType | undefined {
return MEASUREMENT_TYPES.find((t) => t.id === typeId);
}
/** Nazwa serii wysyłana do API: `Biceps lewy`, `Biceps prawy`, `Talia`. */
export function measurementName(typeId: string, side: Side): string {
const type = measurementType(typeId);
if (!type) return '';
return type.sided ? `${type.label} ${side === 'left' ? 'lewy' : 'prawy'}` : type.label;
}
/** Część ciała bazowa: `Biceps lewy` → `Biceps`, `Talia` → `Talia`. */
export function bodyPartOf(name: string): string {
return name.replace(/\s+(lewy|prawy)$/i, '');
}
/** Strona pomiaru: `Biceps lewy` → `left`, `Biceps prawy` → `right`, `Talia` → `null`. */
export function sideOf(name: string): Side | null {
const m = name.match(/\s+(lewy|prawy)$/i);
if (!m) return null;
return m[1].toLowerCase() === 'lewy' ? 'left' : 'right';
}
function normalize(s: string): string {
return s
.toLowerCase()
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '');
}
function levenshtein(a: string, b: string): number {
const m = a.length;
const n = b.length;
if (m === 0) return n;
if (n === 0) return m;
const row: number[] = Array.from({ length: n + 1 }, (_, i) => i);
for (let i = 1; i <= m; i++) {
let prev = row[0];
row[0] = i;
for (let j = 1; j <= n; j++) {
const tmp = row[j];
row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
prev = tmp;
}
}
return row[n];
}
/**
* Mapuje nazwę pomiaru (również starsze, swobodne, np. `Bicepcs`, `Klatka`, `Przedramie`)
* na znaną część ciała z listy. Dokładnie, prefiksowo lub z lekkim literówkowym
* odchyleniem (edycja ≤ 2). Brak dopasowania → `null` (nazwa zostaje jako własna grupa).
*/
export function detectBodyPart(name: string): string | null {
const base = normalize(bodyPartOf(name));
if (base.length === 0) return null;
for (const t of MEASUREMENT_TYPES) {
if (normalize(t.label) === base) return t.label;
}
for (const t of MEASUREMENT_TYPES) {
const label = normalize(t.label);
if (base.length >= 5 && (label.startsWith(base) || base.startsWith(label))) return t.label;
}
let best: { label: string; d: number } | null = null;
for (const t of MEASUREMENT_TYPES) {
const d = levenshtein(base, normalize(t.label));
if (best == null || d < best.d) best = { label: t.label, d };
}
return best && best.d <= 2 ? best.label : null;
}

View File

@@ -0,0 +1,20 @@
import { useTranslation } from 'react-i18next';
import { measurementType, type Gender, type Side } from './body-measurements';
/**
* Etykiety pomiarów ciała z namespace `body`. Etykieta strony zależy od rodzaju
* gramatycznego części (PL: Lewy/Lewa/Lewe), więc klucz to `side.<strona>_<rodzaj>`.
*/
export function useMeasurementLabels() {
const { t } = useTranslation('body');
const measurementLabel = (typeId: string): string => t(typeId);
const genderOf = (typeId: string | null): Gender =>
(typeId ? measurementType(typeId)?.gender : undefined) ?? 'm';
const sideLabel = (side: Side, gender: Gender): string =>
t(`side.${side}_${gender === 'p' ? 'n' : gender}`);
return { measurementLabel, genderOf, sideLabel };
}

View File

@@ -22,15 +22,8 @@ import {
Skeleton,
Tabs,
} from '../../components/ui';
import {
MEASUREMENT_TYPES,
SIDE_LABELS,
bodyPartOf,
detectBodyPart,
sideLabelsFor,
sideOf,
type Side,
} from '../../lib/body-measurements';
import { MEASUREMENT_TYPES, type Gender, type Side } from '../../lib/body-measurements';
import { useMeasurementLabels } from '../../lib/useMeasurementLabels';
import { fmtDate } from '../../lib/format';
import type { CircumferenceSeries } from '../../api/types';
import { useAdminUser, useUserBodyParameters } from './user-queries';
@@ -64,31 +57,44 @@ const lineActiveDot = (stroke: string) => ({
});
interface CircGroup {
part: string;
key: string;
typeId: string | null;
/** Swobodna nazwa starszego pomiaru — tylko gdy typeId jest null. */
legacyName: string | null;
series: CircumferenceSeries[];
}
/**
* Grupuje serie obwodów po części ciała: `Biceps lewy` + `Biceps prawy` → jedna grupa `Biceps`.
* Nazwy wykrywane na bazie listy znanych części (`Bicepcs` → `Biceps`); nieznane zostają osobno.
* Grupuje serie obwodów po części ciała (typie): `biceps/left` + `biceps/right` → jedna grupa.
* Serie z `typeId` układają się w kolejności listy; starsze (typeId = null) zostają osobno.
*/
function groupCircumferences(series: CircumferenceSeries[]): CircGroup[] {
const byPart = new Map<string, CircumferenceSeries[]>();
const byKey = new Map<string, CircGroup>();
for (const s of series) {
const part = detectBodyPart(s.name) ?? bodyPartOf(s.name);
const list = byPart.get(part) ?? [];
list.push(s);
byPart.set(part, list);
const key = s.typeId ? `t:${s.typeId}` : `n:${s.name ?? ''}`;
const g = byKey.get(key) ?? {
key,
typeId: s.typeId,
legacyName: s.typeId ? null : (s.name ?? ''),
series: [],
};
g.series.push(s);
byKey.set(key, g);
}
const knownOrder = (part: string) => {
const idx = MEASUREMENT_TYPES.findIndex((t) => t.label === part);
const knownOrder = (g: CircGroup) => {
const idx = MEASUREMENT_TYPES.findIndex((t) => t.id === g.typeId);
return idx >= 0 ? idx : MEASUREMENT_TYPES.length;
};
return [...byPart.entries()]
.sort((a, b) => knownOrder(a[0]) - knownOrder(b[0]) || a[0].localeCompare(b[0], 'pl'))
.map(([part, list]) => ({
part,
series: list.sort((a, b) => a.name.localeCompare(b.name, 'pl')),
const sideOrder = (s: Side | null) => (s === 'left' ? 0 : s === 'right' ? 1 : 2);
return [...byKey.values()]
.sort(
(a, b) =>
knownOrder(a) - knownOrder(b) ||
(a.typeId ?? a.legacyName ?? '').localeCompare(b.typeId ?? b.legacyName ?? '', 'pl'),
)
.map((g) => ({
...g,
series: [...g.series].sort((x, y) => sideOrder(x.side) - sideOrder(y.side)),
}));
}
@@ -102,7 +108,10 @@ interface GroupPoint {
}
interface PartGroup {
part: string;
key: string;
label: string;
/** Rodzaj gramatyczny → fleksja strony w nagłówkach/etykietach. */
gender: Gender;
unit: 'kg' | 'cm';
/** Wszystkie pomiary (pełna historia), rosnąco po dacie. */
points: GroupPoint[];
@@ -116,13 +125,16 @@ function pomN(n: number): string {
return `${n} pomiarów`;
}
const WEIGHT_PART = 'Waga';
const WEIGHT_KEY = 'weight';
const fmtVal = (n: number) => n.toLocaleString('pl-PL', { maximumFractionDigits: 1 });
const signed = (d: number) => `${d < 0 ? '−' : '+'}${fmtVal(Math.abs(d))}`;
/* Postęp części: zmiana najnowszego pomiaru od pierwszego; spadek wagi = dobry kierunek. */
function progressOf(g: PartGroup): { text: string; className: string } | null {
function progressOf(g: { unit: 'kg' | 'cm'; points: GroupPoint[] }): {
text: string;
className: string;
} | null {
if (g.points.length < 2) return null;
const d = g.points[g.points.length - 1].value - g.points[0].value;
if (d === 0) return null;
@@ -268,30 +280,33 @@ function MeasurementPanel({
icon: Icon,
visible,
onShowMore,
sideLabel,
}: {
group: PartGroup;
icon: LucideIcon;
visible: number;
onShowMore: () => void;
sideLabel: (side: Side, gender: Gender) => string;
}) {
const sideName = (s: Side) => sideLabel(s, group.gender);
const sided = group.sidesPresent.length > 1;
if (!sided) {
return (
<Card>
<PartSection
title={group.part}
title={group.label}
icon={Icon}
unit={group.unit}
points={group.points}
stroke={unitStroke(group.unit)}
chartName={group.part}
chartName={group.label}
visible={visible}
onShowMore={onShowMore}
sideName={sideName}
/>
</Card>
);
}
const labels = sideLabelsFor(group.part);
const unsidePoints = group.points.filter((p) => p.side == null);
return (
<div className="flex flex-col gap-4">
@@ -300,28 +315,30 @@ function MeasurementPanel({
.map((s) => (
<Card key={s}>
<PartSection
title={`${group.part} — ${labels[s].toLowerCase()}`}
title={`${group.label} — ${sideName(s).toLowerCase()}`}
icon={Icon}
unit={group.unit}
points={group.points.filter((p) => p.side === s)}
stroke={SIDE_STROKE[s]}
chartName={labels[s].toLowerCase()}
chartName={sideName(s).toLowerCase()}
visible={visible}
onShowMore={onShowMore}
sideName={sideName}
/>
</Card>
))}
{unsidePoints.length > 0 && (
<Card>
<PartSection
title={group.part}
title={group.label}
icon={Icon}
unit={group.unit}
points={unsidePoints}
stroke={unitStroke(group.unit)}
chartName={group.part}
chartName={group.label}
visible={visible}
onShowMore={onShowMore}
sideName={sideName}
/>
</Card>
)}
@@ -340,6 +357,7 @@ function PartSection({
chartName,
visible,
onShowMore,
sideName,
}: {
title: string;
icon: LucideIcon;
@@ -349,6 +367,7 @@ function PartSection({
chartName: string;
visible: number;
onShowMore: () => void;
sideName: (side: Side) => string;
}) {
const latest = points[points.length - 1];
// historia przekracza rok → oś X z rokiem (również przy przerwie >12 mies. w jednym roku)
@@ -356,7 +375,7 @@ function PartSection({
new Date(points[points.length - 1].date).getTime() - new Date(points[0].date).getTime() >
300 * 86_400_000;
// postęp sekcji (dla strony: osobna, przy łączonej: per strona): zmiana od pierwszego pomiaru
const prog = progressOf({ part: title, unit, points, sidesPresent: [] });
const prog = progressOf({ unit, points });
const primary = prog?.text ?? 'bez zmian';
const primaryClass = prog?.className ?? 'text-dim';
const sub =
@@ -413,7 +432,7 @@ function PartSection({
.reverse()
.slice(0, visible)
.map((p) => {
const sideLabel = p.side ? ` · ${SIDE_LABELS[p.side]}` : '';
const sideSuffix = p.side ? ` · ${sideName(p.side)}` : '';
return (
<li
key={p.id}
@@ -424,7 +443,7 @@ function PartSection({
</strong>
<div className="mt-0.5 text-[0.875rem] text-dim">
{fmtDate(p.date)}
{sideLabel}
{sideSuffix}
</div>
</li>
);
@@ -449,6 +468,7 @@ export default function UserBodyParameters() {
const { id } = useParams();
const { user } = useAdminUser(id);
const { data: bp, isLoading: bpLoading, error: bpError } = useUserBodyParameters(id);
const { measurementLabel, genderOf, sideLabel } = useMeasurementLabels();
const [visible, setVisible] = useState<Record<string, number>>({});
const [selected, setSelected] = useState<string | null>(null);
@@ -468,8 +488,11 @@ export default function UserBodyParameters() {
const list: PartGroup[] = [];
const weightPoints = [...(bp?.weight ?? [])].sort((a, b) => a.date.localeCompare(b.date));
if (weightPoints.length > 0) {
const label = measurementLabel(WEIGHT_KEY);
list.push({
part: WEIGHT_PART,
key: WEIGHT_KEY,
label,
gender: 'f',
unit: 'kg',
points: weightPoints.map((w) => ({
id: w.id,
@@ -482,32 +505,36 @@ export default function UserBodyParameters() {
});
}
for (const g of groupCircumferences(bp?.circumferences ?? [])) {
const gender = genderOf(g.typeId);
const label = g.typeId ? measurementLabel(g.typeId) : (g.legacyName ?? '');
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,
side: s.side,
name: s.side ? `${label} · ${sideLabel(s.side, gender)}` : label,
})),
)
.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)),
...new Set(g.series.map((s) => s.side).filter((s): s is Side => s != null)),
];
list.push({
part: g.part,
key: g.key,
label,
gender,
unit: 'cm',
points,
sidesPresent,
});
}
return list;
}, [bp]);
}, [bp, measurementLabel, genderOf, sideLabel]);
// wybrana część odpada (brak danych) → pierwsza dostępna
const active = groups.find((g) => g.part === selected) ?? groups[0];
const active = groups.find((g) => g.key === selected) ?? groups[0];
if (bpLoading) {
return (
@@ -537,17 +564,18 @@ export default function UserBodyParameters() {
<>
{/* zakładki części: pełna nazwa (pasek jest przewijalny); szczegóły w panelu poniżej */}
<Tabs
tabs={groups.map((g) => ({ id: g.part, label: g.part }))}
active={active.part}
tabs={groups.map((g) => ({ id: g.key, label: g.label }))}
active={active.key}
onChange={(id) => setSelected(id)}
/>
<div className="mt-4">
<MeasurementPanel
group={active}
icon={active.part === WEIGHT_PART ? Scale : Ruler}
visible={countFor(active.part)}
onShowMore={() => showMore(active.part)}
icon={active.key === WEIGHT_KEY ? Scale : Ruler}
visible={countFor(active.key)}
onShowMore={() => showMore(active.key)}
sideLabel={sideLabel}
/>
</div>
</>

View File

@@ -12,18 +12,24 @@ const BP = {
],
circumferences: [
{
name: 'Biceps lewy',
typeId: 'biceps',
side: 'left',
name: null,
points: [
{ id: 'c1', value: 35, date: '2026-09-01T10:00:00.000Z' },
{ id: 'c3', value: 36, date: '2026-09-20T10:00:00.000Z' },
],
},
{
name: 'Biceps prawy',
typeId: 'biceps',
side: 'right',
name: null,
points: [{ id: 'c2', value: 35.5, date: '2026-09-09T10:00:00.000Z' }],
},
{
name: 'Klatka piersiowa',
typeId: 'chest',
side: null,
name: null,
points: [{ id: 'c4', value: 100, date: '2026-09-05T10:00:00.000Z' }],
},
],
@@ -91,8 +97,8 @@ describe('admin UserBodyParameters page', () => {
// lista z pełnej historii (oba pomiary, nawet sprzed „bieżącego miesiąca”);
// wartość i jednostka to osobne węzły tekstowe w kafelku listy
const tiles = () =>
Array.from(document.querySelectorAll('li')).map(
(li) => (li.textContent ?? '').replace(/\s+/g, ' ').trim(),
Array.from(document.querySelectorAll('li')).map((li) =>
(li.textContent ?? '').replace(/\s+/g, ' ').trim(),
);
expect(tiles().some((t) => t.startsWith('82 kg'))).toBe(true);
});
@@ -126,8 +132,8 @@ describe('admin UserBodyParameters page', () => {
// domyślnie 3 najnowsze, gwóźdź programu: 4. pomiar ukryty do kliknięcia
const tiles = () =>
Array.from(document.querySelectorAll('li')).map(
(li) => (li.textContent ?? '').replace(/\s+/g, ' ').trim(),
Array.from(document.querySelectorAll('li')).map((li) =>
(li.textContent ?? '').replace(/\s+/g, ' ').trim(),
);
expect(tiles().some((t) => /^80[.,]1 kg/.test(t))).toBe(false);
fireEvent.click(screen.getByRole('button', { name: 'Pokaż więcej' }));
@@ -135,14 +141,14 @@ describe('admin UserBodyParameters page', () => {
});
it('pokazuje stan pusty, gdy użytkownik nie ma pomiarów', async () => {
mockFetchRoutes([
['/body-parameters', () => ({ weight: [], circumferences: [] })],
]);
mockFetchRoutes([['/body-parameters', () => ({ weight: [], circumferences: [] })]]);
renderPage();
expect(await screen.findByText('Brak pomiarów')).toBeInTheDocument();
expect(
screen.getByText('Pomiary pojawią się tutaj, gdy użytkownik doda wagę lub obwód w aplikacji.'),
screen.getByText(
'Pomiary pojawią się tutaj, gdy użytkownik doda wagę lub obwód w aplikacji.',
),
).toBeInTheDocument();
});