Plany: wyszukiwarka cwiczen z filtrami grup i hintem ostatnich wyników (zamiast selecta)

This commit is contained in:
tisachi
2026-09-11 18:40:58 +02:00
parent 4e34245779
commit e1ebc56fdc
5 changed files with 241 additions and 48 deletions

View File

@@ -113,16 +113,6 @@ export default function PlanEditor() {
return () => window.removeEventListener('beforeunload', handler);
}, [editor.dirty]);
const grouped = useMemo(() => {
const g = new Map<string, Exercise[]>();
for (const p of exercises) {
const list = g.get(p.primaryMuscle) ?? [];
list.push(p);
g.set(p.primaryMuscle, list);
}
return g;
}, [exercises]);
const latestByExercise = useMemo(
() => new Map((latestData?.results ?? []).map((r) => [r.exerciseId, r])),
[latestData],
@@ -280,7 +270,8 @@ export default function PlanEditor() {
dayIndex={di}
exerciseName={exerciseName}
isTraineeMode={isTraineeMode}
grouped={grouped}
exercises={exercises}
exercisesLoading={exData === undefined}
resultsOpenKey={resultsOpenKey}
onToggleResults={(ei) => {
const key = `${wi}:${di}:${ei}`;

View File

@@ -1,17 +1,19 @@
import { Badge, H3, Select } from '../../../components/ui';
import { DAY_NAMES, MUSCLE_NAMES } from '../../../lib/labels';
import { Badge, H3 } from '../../../components/ui';
import { DAY_NAMES } from '../../../lib/labels';
import type { Exercise, ExerciseProgress, LatestExerciseResult } from '../../../api/types';
import type { EditorDay, EditorSet } from './types';
import { ExerciseEditor } from './ExerciseEditor';
import { ExercisePicker } from './ExercisePicker';
/* Dzień tygodnia: H3 + badge ćwiczeń + lista ćwiczeń + select „+ dodaj ćwiczenie…”. */
/* Dzień tygodnia: H3 + badge ćwiczeń + lista ćwiczeń + wyszukiwarka „+ dodaj ćwiczenie…”. */
export function DayEditor({
day,
weekIndex,
dayIndex,
exerciseName,
isTraineeMode,
grouped,
exercises,
exercisesLoading,
resultsOpenKey,
onToggleResults,
onAddExercise,
@@ -28,7 +30,8 @@ export function DayEditor({
dayIndex: number;
exerciseName: (eid: string) => string;
isTraineeMode: boolean;
grouped: Map<string, Exercise[]>;
exercises: Exercise[];
exercisesLoading: boolean;
resultsOpenKey: string | null;
onToggleResults: (ei: number) => void;
onAddExercise: (exerciseId: string) => void;
@@ -69,27 +72,14 @@ export function DayEditor({
/>
))}
</div>
<Select
defaultValue=""
className="mt-3 sm:max-w-xs"
onChange={(e) => {
if (e.target.value) {
onAddExercise(e.target.value);
e.target.value = '';
}
}}
>
<option value="">+ dodaj ćwiczenie…</option>
{[...grouped.entries()].map(([muscle, list]) => (
<optgroup key={muscle} label={MUSCLE_NAMES[muscle] || muscle}>
{list.map((p) => (
<option key={p.id} value={p.id}>
{p.name}
</option>
))}
</optgroup>
))}
</Select>
<div className="mt-3">
<ExercisePicker
exercises={exercises}
latestByExercise={isTraineeMode ? latestByExercise : undefined}
onSelect={onAddExercise}
loading={exercisesLoading}
/>
</div>
</div>
);
}

View File

@@ -0,0 +1,208 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import type { KeyboardEvent } from 'react';
import { Plus, Search } from 'lucide-react';
import { Button, Input, Modal } from '../../../components/ui';
import { MUSCLE_NAMES } from '../../../lib/labels';
import { cn } from '../../../lib/utils';
import type { Exercise, LatestExerciseResult } from '../../../api/types';
/** Hint ostatniej sesji podopiecznego (pierwsza seria): „ost. 12 @ 70 kg”. */
function latestHint(latest: LatestExerciseResult | undefined): string | null {
if (!latest || latest.sets.length === 0) return null;
const s = latest.sets[0];
if (s.reps == null && s.loadKg == null) return null;
const reps = s.reps != null ? String(s.reps) : '?';
const load = s.loadKg != null ? ` @ ${s.loadKg} kg` : '';
return `ost. ${reps}${load}`;
}
const chipCls = (selected: boolean) =>
cn(
'rounded-full border px-3 py-1 text-[0.8125rem] font-semibold cursor-pointer transition-colors',
selected
? 'bg-accent text-accent-ink border-accent'
: 'bg-input border-line text-dim hover:border-accent hover:text-accent-text',
);
/**
* Wyszukiwarka ćwiczeń (zamiast natywnego <select>): pole wyszukiwania,
* quick-chipy grup mięśniowych, lista grupowana wg mięśni, klawiatura
* (strzałki + Enter, Esc zamyka). Mobile: bottom sheet (Radix Dialog),
* tap = dodaj + zamknij. W trybie podopiecznego hint ostatniej sesji.
*/
export function ExercisePicker({
exercises,
latestByExercise,
onSelect,
loading,
}: {
exercises: Exercise[];
latestByExercise?: Map<string, LatestExerciseResult>;
onSelect: (exerciseId: string) => void;
loading?: boolean;
}) {
const [open, setOpen] = useState(false);
const [query, setQuery] = useState('');
const [muscle, setMuscle] = useState<string | null>(null);
const [active, setActive] = useState(0);
const listRef = useRef<HTMLDivElement>(null);
const muscles = useMemo(() => {
const present = new Set(exercises.map((e) => e.primaryMuscle));
return Object.keys(MUSCLE_NAMES).filter((m) => present.has(m));
}, [exercises]);
const filtered = useMemo(() => {
const q = query.trim().toLowerCase();
return exercises.filter(
(e) =>
(muscle === null || e.primaryMuscle === muscle) &&
(q === '' || e.name.toLowerCase().includes(q)),
);
}, [exercises, query, muscle]);
const groups = useMemo(() => {
const g = new Map<string, Exercise[]>();
for (const e of filtered) {
const list = g.get(e.primaryMuscle) ?? [];
list.push(e);
g.set(e.primaryMuscle, list);
}
return [...g.entries()];
}, [filtered]);
const flat = useMemo(() => groups.flatMap(([, list]) => list), [groups]);
useEffect(() => {
if (open) {
setQuery('');
setMuscle(null);
setActive(0);
}
}, [open]);
useEffect(() => setActive(0), [query, muscle]);
// aktywna opcja zawsze w polu widzenia listy
useEffect(() => {
const id = flat[active]?.id;
if (!id) return;
listRef.current
?.querySelector<HTMLElement>(`[data-ex-id="${CSS.escape(id)}"]`)
?.scrollIntoView({ block: 'nearest' });
}, [active, flat]);
const select = (id: string) => {
onSelect(id);
setOpen(false);
};
const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'ArrowDown') {
e.preventDefault();
setActive((a) => Math.min(a + 1, flat.length - 1));
} else if (e.key === 'ArrowUp') {
e.preventDefault();
setActive((a) => Math.max(a - 1, 0));
} else if (e.key === 'Enter') {
e.preventDefault();
const ex = flat[active];
if (ex) select(ex.id);
}
};
return (
<>
<Button
variant="secondary"
className="w-full sm:max-w-xs"
disabled={loading}
onClick={() => setOpen(true)}
>
<Plus className="w-4 h-4" />+ dodaj ćwiczenie…
</Button>
<Modal open={open} onClose={() => setOpen(false)} title="Wybierz ćwiczenie">
<div className="relative mb-3">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-dim" />
<Input
autoFocus
value={query}
onChange={(e) => setQuery(e.target.value)}
onKeyDown={onKeyDown}
placeholder="Szukaj ćwiczenia…"
aria-label="Szukaj ćwiczenia"
className="pl-9"
/>
</div>
{muscles.length > 0 && (
<div className="flex flex-wrap gap-1.5 mb-3">
<button
type="button"
onClick={() => setMuscle(null)}
className={chipCls(muscle === null)}
>
Wszystkie
</button>
{muscles.map((m) => (
<button
key={m}
type="button"
onClick={() => setMuscle(m)}
className={chipCls(muscle === m)}
>
{MUSCLE_NAMES[m] ?? m}
</button>
))}
</div>
)}
<div
ref={listRef}
role="listbox"
aria-label="Ćwiczenia"
aria-activedescendant={flat[active] ? `ex-opt-${flat[active].id}` : undefined}
className="max-h-72 overflow-y-auto -mx-1 px-1"
>
{flat.length === 0 && (
<p className="text-dim text-center py-6 text-[0.9rem]">
{exercises.length === 0
? 'Brak ćwiczeń w katalogu.'
: 'Brak ćwiczeń pasujących do wyszukiwania.'}
</p>
)}
{groups.map(([m, list]) => (
<div key={m}>
<div className="px-2 pt-2 pb-1 text-[10.5px] font-bold uppercase tracking-[0.11em] text-dim">
{MUSCLE_NAMES[m] ?? m}
</div>
{list.map((e) => {
const idx = flat.indexOf(e);
const hint = latestByExercise ? latestHint(latestByExercise.get(e.id)) : null;
return (
<button
key={e.id}
type="button"
role="option"
id={`ex-opt-${e.id}`}
data-ex-id={e.id}
aria-selected={idx === active}
onClick={() => select(e.id)}
onMouseEnter={() => setActive(idx)}
className={cn(
'w-full flex items-center justify-between gap-3 rounded-[10px] px-3 py-2.5 text-left cursor-pointer transition-colors',
idx === active ? 'bg-accent/12 text-accent-text' : 'hover:bg-line/30',
)}
>
<span className="min-w-0 truncate text-[0.95rem] font-semibold">{e.name}</span>
{hint && (
<span className="shrink-0 text-dim text-[0.8rem] tabular-nums">{hint}</span>
)}
</button>
);
})}
</div>
))}
</div>
</Modal>
</>
);
}

View File

@@ -23,7 +23,9 @@ async function openTraineePlansTab(page: import('@playwright/test').Page) {
await expect(page.getByRole('heading', { name: 'Plany podopiecznego' })).toBeVisible();
}
test('zakładka Plany: lista planów podopiecznego z badge statusu i etykietą twórcy', async ({ page }) => {
test('zakładka Plany: lista planów podopiecznego z badge statusu i etykietą twórcy', async ({
page,
}) => {
await openTraineePlansTab(page);
await expect(page.getByRole('button', { name: 'Utwórz plan' })).toBeVisible();
@@ -57,7 +59,9 @@ test('zakładka Plany: aktywny — akcje „Oznacz jako ukończony" i „Porzuć
await expect(page.getByRole('button', { name: 'Oznacz jako ukończony' })).toBeVisible();
});
test('zakładka Plany: blokada aktywacji szkicu, gdy podopieczny ma już aktywny plan', async ({ page }) => {
test('zakładka Plany: blokada aktywacji szkicu, gdy podopieczny ma już aktywny plan', async ({
page,
}) => {
await openTraineePlansTab(page);
await page.getByRole('button', { name: 'Plan masowy' }).click();
@@ -73,16 +77,18 @@ test('zakładka Plany: blokada aktywacji szkicu, gdy podopieczny ma już aktywny
await expect(page.getByRole('button', { name: 'Aktywuj' })).toBeDisabled();
});
test('edytor planu podopiecznego: „Wstaw wyniki" prefylluje serie z ostatniej sesji', async ({ page }) => {
test('edytor planu podopiecznego: „Wstaw wyniki" prefylluje serie z ostatniej sesji', async ({
page,
}) => {
await openTraineePlansTab(page);
await page.getByRole('button', { name: 'Utwórz plan' }).click();
await expect(page.getByRole('heading', { name: 'Plan dla podopiecznego' })).toBeVisible();
// dodaj dzień (Poniedziałek)
await page.getByRole('button', { name: 'Pon' }).click();
// dodaj ćwiczenie Przysiady (select z opcją ex-1)
const exerciseSelect = page.locator('select').filter({ has: page.locator('option[value="ex-1"]') });
await exerciseSelect.selectOption('ex-1');
// dodaj ćwiczenie Przysiady (wyszukiwarka ćwiczeń zamiast selecta)
await page.getByRole('button', { name: '+ dodaj ćwiczenie…' }).click();
await page.getByRole('option', { name: /Przysiady/ }).click();
// otwórz panel wyników i wstaw
await page.getByRole('button', { name: 'Wyniki' }).click();
await expect(page.getByText('Wstaw wyniki')).toBeVisible();

View File

@@ -367,11 +367,9 @@ describe('PlanEditor — tryb podopiecznego', () => {
// dodaj dzień (Poniedziałek)
await user.click(screen.getByRole('button', { name: 'Pon' }));
// dodaj ćwiczenie Przysiady
const exerciseSelect = screen
.getAllByRole('combobox')
.find((s) => s.querySelector('option[value="ex-1"]'));
await user.selectOptions(exerciseSelect, 'ex-1');
// dodaj ćwiczenie Przysiady (wyszukiwarka ćwiczeń)
await user.click(screen.getByRole('button', { name: '+ dodaj ćwiczenie…' }));
await user.click(await screen.findByRole('option', { name: /Przysiady/ }));
// otwórz panel wyników i wstaw
await user.click(screen.getByRole('button', { name: 'Wyniki' }));