579 lines
18 KiB
TypeScript
579 lines
18 KiB
TypeScript
import { useEffect, useState } from 'react';
|
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
|
import { Pencil, Plus, Trash2, Dumbbell } from 'lucide-react';
|
|
import { api } from '../../api/client';
|
|
import type { Equipment, Exercise, FocusArea } from '../../api/types';
|
|
import { useTopbar } from '../../topbar';
|
|
import { useListSearch } from '../../store/list-search';
|
|
import {
|
|
Badge,
|
|
Button,
|
|
Card,
|
|
ConfirmDialog,
|
|
EmptyState,
|
|
ErrorText,
|
|
Field,
|
|
Input,
|
|
Loading,
|
|
Modal,
|
|
Muted,
|
|
Select,
|
|
Textarea,
|
|
} from '../../components/ui';
|
|
|
|
const FLAG_KEYS = [
|
|
'hasReps',
|
|
'hasLoad',
|
|
'hasRest',
|
|
'hasSets',
|
|
'hasRir',
|
|
'hasDifficulty',
|
|
'hasCardio',
|
|
'hasTime',
|
|
'hasSpeed',
|
|
] as const;
|
|
type FlagKey = (typeof FLAG_KEYS)[number];
|
|
type Flags = Record<FlagKey, boolean>;
|
|
|
|
const FLAG_LABELS: Record<FlagKey, string> = {
|
|
hasReps: 'Powtórzenia',
|
|
hasLoad: 'Obciążenie',
|
|
hasRest: 'Przerwa',
|
|
hasSets: 'Serie',
|
|
hasRir: 'RIR',
|
|
hasDifficulty: 'Trudność',
|
|
hasCardio: 'Cardio',
|
|
hasTime: 'Czas',
|
|
hasSpeed: 'Prędkość',
|
|
};
|
|
|
|
/** Chipy na karcie — tylko najbardziej wyróżniające flagi. */
|
|
const CARD_FLAG_CHIPS: Partial<Record<FlagKey, string>> = {
|
|
hasCardio: 'cardio',
|
|
hasTime: 'czas',
|
|
hasSpeed: 'prędkość',
|
|
hasReps: 'powt.',
|
|
hasLoad: 'obciążenie',
|
|
hasRir: 'RIR',
|
|
};
|
|
|
|
const PRESET_STRENGTH: Flags = {
|
|
hasReps: true,
|
|
hasLoad: true,
|
|
hasRest: true,
|
|
hasSets: true,
|
|
hasRir: true,
|
|
hasDifficulty: true,
|
|
hasCardio: false,
|
|
hasTime: false,
|
|
hasSpeed: false,
|
|
};
|
|
|
|
const PRESET_CARDIO: Flags = {
|
|
hasReps: false,
|
|
hasLoad: false,
|
|
hasRest: true,
|
|
hasSets: true,
|
|
hasRir: false,
|
|
hasDifficulty: true,
|
|
hasCardio: true,
|
|
hasTime: true,
|
|
hasSpeed: false,
|
|
};
|
|
|
|
const PRESETS: Record<'strength' | 'cardio', Flags> = {
|
|
strength: PRESET_STRENGTH,
|
|
cardio: PRESET_CARDIO,
|
|
};
|
|
|
|
type ExerciseType = 'strength' | 'cardio' | 'custom';
|
|
|
|
const EXERCISE_TYPE_LABELS: Record<ExerciseType, string> = {
|
|
strength: 'Siłowe',
|
|
cardio: 'Cardio',
|
|
custom: 'Własne',
|
|
};
|
|
|
|
const SOURCE_LABELS: Record<string, string> = {
|
|
BUILTIN: 'wbudowane',
|
|
GYM_CUSTOM: 'siłowni',
|
|
TRAINER_CUSTOM: 'trenera',
|
|
};
|
|
|
|
function flagsOf(ex: Exercise): Flags {
|
|
return Object.fromEntries(FLAG_KEYS.map((k) => [k, ex[k]])) as Flags;
|
|
}
|
|
|
|
function sameFlags(a: Flags, b: Flags): boolean {
|
|
return FLAG_KEYS.every((k) => a[k] === b[k]);
|
|
}
|
|
|
|
function detectType(ex: Exercise): ExerciseType {
|
|
const flags = flagsOf(ex);
|
|
if (sameFlags(flags, PRESET_STRENGTH)) return 'strength';
|
|
if (sameFlags(flags, PRESET_CARDIO)) return 'cardio';
|
|
return 'custom';
|
|
}
|
|
|
|
interface FormState {
|
|
name: string;
|
|
primaryMuscle: string;
|
|
secondaryMuscles: string[];
|
|
description: string;
|
|
howTo: string;
|
|
commonMistakes: string;
|
|
exerciseType: ExerciseType;
|
|
flags: Flags;
|
|
equipmentIds: string[];
|
|
}
|
|
|
|
const EMPTY: FormState = {
|
|
name: '',
|
|
primaryMuscle: '',
|
|
secondaryMuscles: [],
|
|
description: '',
|
|
howTo: '',
|
|
commonMistakes: '',
|
|
exerciseType: 'strength',
|
|
flags: PRESET_STRENGTH,
|
|
equipmentIds: [],
|
|
};
|
|
|
|
/** Opcje mięśni z katalogu obszarów + wartości spoza katalogu zachowane z edytowanego ćwiczenia. */
|
|
function muscleOptions(
|
|
areas: FocusArea[],
|
|
extraValues: string[],
|
|
): { value: string; label: string }[] {
|
|
const options = areas.map((a) => ({ value: a.muscle, label: `${a.name} (${a.muscle})` }));
|
|
const known = new Set(options.map((o) => o.value));
|
|
for (const v of extraValues) {
|
|
if (v && !known.has(v)) {
|
|
options.push({ value: v, label: `${v} (brak w katalogu obszarów)` });
|
|
known.add(v);
|
|
}
|
|
}
|
|
return options;
|
|
}
|
|
|
|
export default function Exercises() {
|
|
const qc = useQueryClient();
|
|
const { data, isLoading, error } = useQuery({
|
|
queryKey: ['exercises'],
|
|
queryFn: () => api<{ exercises: Exercise[] }>('/admin/exercises'),
|
|
});
|
|
const { data: eqData } = useQuery({
|
|
queryKey: ['equipment'],
|
|
queryFn: () => api<{ equipment: Equipment[] }>('/admin/equipment'),
|
|
});
|
|
const { data: areaData } = useQuery({
|
|
queryKey: ['focus-areas'],
|
|
queryFn: () => api<{ focusAreas: FocusArea[] }>('/admin/focus-areas'),
|
|
});
|
|
|
|
const exercises = data?.exercises ?? [];
|
|
const equipment = eqData?.equipment ?? [];
|
|
const areas = areaData?.focusAreas ?? [];
|
|
const query = useListSearch((s) => s.queries.exercises);
|
|
const setQuery = useListSearch((s) => s.setQuery);
|
|
|
|
const filtered = query
|
|
? exercises.filter((ex) =>
|
|
[ex.name, ex.primaryMuscle, ex.description, ...ex.secondaryMuscles]
|
|
.filter(Boolean)
|
|
.some((s) => s!.toLowerCase().includes(query.toLowerCase())),
|
|
)
|
|
: exercises;
|
|
|
|
// wyszukiwarka jest w menu kontekstowym (Layout) — czyścimy ją przy opuszczeniu strony
|
|
useEffect(() => () => setQuery('exercises', ''), [setQuery]);
|
|
|
|
const [formOpen, setFormOpen] = useState(false);
|
|
const [editing, setEditing] = useState<Exercise | null>(null);
|
|
const [form, setForm] = useState<FormState>(EMPTY);
|
|
const [formError, setFormError] = useState<string | null>(null);
|
|
const [deleting, setDeleting] = useState<Exercise | null>(null);
|
|
const [confirmFlagChange, setConfirmFlagChange] = useState(false);
|
|
|
|
const invalidate = () => {
|
|
qc.invalidateQueries({ queryKey: ['exercises'] });
|
|
};
|
|
|
|
function currentFlags(): Flags {
|
|
return form.exerciseType === 'custom' ? form.flags : PRESETS[form.exerciseType];
|
|
}
|
|
|
|
function flagsChanged(): boolean {
|
|
if (!editing) return false;
|
|
return !sameFlags(currentFlags(), flagsOf(editing));
|
|
}
|
|
|
|
function buildBody() {
|
|
const flags = currentFlags();
|
|
return {
|
|
name: form.name,
|
|
primaryMuscle: form.primaryMuscle,
|
|
secondaryMuscles: form.secondaryMuscles,
|
|
description: form.description || null,
|
|
howTo: form.howTo || null,
|
|
commonMistakes: form.commonMistakes || null,
|
|
equipmentIds: form.equipmentIds,
|
|
...flags,
|
|
};
|
|
}
|
|
|
|
const save = useMutation({
|
|
mutationFn: async () => {
|
|
const body = buildBody();
|
|
if (editing) {
|
|
await api(`/admin/exercises/${editing.id}`, { method: 'PATCH', body });
|
|
} else {
|
|
await api('/admin/exercises', { method: 'POST', body });
|
|
}
|
|
},
|
|
onSuccess: () => {
|
|
invalidate();
|
|
setFormOpen(false);
|
|
setConfirmFlagChange(false);
|
|
setEditing(null);
|
|
setForm(EMPTY);
|
|
setFormError(null);
|
|
},
|
|
onError: (e) => setFormError((e as Error).message),
|
|
});
|
|
|
|
function submit() {
|
|
// zmiana flag u ćwiczenia używanego w planach zmienia formularz zapisu w aplikacji
|
|
if (flagsChanged() && (editing?.planExercisesCount ?? 0) > 0) {
|
|
setConfirmFlagChange(true);
|
|
return;
|
|
}
|
|
save.mutate();
|
|
}
|
|
|
|
const remove = useMutation({
|
|
mutationFn: (id: string) => api(`/admin/exercises/${id}`, { method: 'DELETE' }),
|
|
onSuccess: () => {
|
|
invalidate();
|
|
setDeleting(null);
|
|
},
|
|
onError: (e) => alert((e as Error).message),
|
|
});
|
|
|
|
function openCreate() {
|
|
setEditing(null);
|
|
setForm(EMPTY);
|
|
setFormError(null);
|
|
setFormOpen(true);
|
|
}
|
|
|
|
// menu top: akcja „Nowe ćwiczenie” otwiera modal w treści strony
|
|
useTopbar({
|
|
title: 'Rodzaje ćwiczeń',
|
|
search: 'exercises',
|
|
actions: [{ label: 'Nowe ćwiczenie', onClick: openCreate, icon: Plus }],
|
|
});
|
|
|
|
function openEdit(ex: Exercise) {
|
|
setEditing(ex);
|
|
setForm({
|
|
name: ex.name,
|
|
primaryMuscle: ex.primaryMuscle,
|
|
secondaryMuscles: ex.secondaryMuscles,
|
|
description: ex.description ?? '',
|
|
howTo: ex.howTo ?? '',
|
|
commonMistakes: ex.commonMistakes ?? '',
|
|
exerciseType: detectType(ex),
|
|
flags: flagsOf(ex),
|
|
equipmentIds: ex.equipment.map((e) => e.id),
|
|
});
|
|
setFormError(null);
|
|
setFormOpen(true);
|
|
}
|
|
|
|
function toggleEquipment(id: string) {
|
|
setForm((f) => ({
|
|
...f,
|
|
equipmentIds: f.equipmentIds.includes(id)
|
|
? f.equipmentIds.filter((x) => x !== id)
|
|
: [...f.equipmentIds, id],
|
|
}));
|
|
}
|
|
|
|
function toggleSecondary(muscle: string) {
|
|
setForm((f) => ({
|
|
...f,
|
|
secondaryMuscles: f.secondaryMuscles.includes(muscle)
|
|
? f.secondaryMuscles.filter((x) => x !== muscle)
|
|
: [...f.secondaryMuscles, muscle],
|
|
}));
|
|
}
|
|
|
|
const primaryOptions = muscleOptions(areas, editing ? [editing.primaryMuscle] : []);
|
|
const secondaryOptions = muscleOptions(areas, form.secondaryMuscles);
|
|
|
|
return (
|
|
<>
|
|
<Muted className="mb-4 block">Rodzaje ćwiczeń i przypisane do nich maszyny/urządzenia.</Muted>
|
|
|
|
{isLoading && <Loading />}
|
|
{error && <ErrorText>Błąd: {(error as Error).message}</ErrorText>}
|
|
|
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
|
{filtered.map((ex) => (
|
|
<Card key={ex.id} className="mb-0">
|
|
<div className="flex items-start justify-between gap-3">
|
|
<div className="min-w-0">
|
|
<div className="text-[1.05rem] font-semibold">
|
|
{ex.name}
|
|
{SOURCE_LABELS[ex.source] && (
|
|
<span className="ml-2 text-[0.875rem] text-dim font-normal">
|
|
{SOURCE_LABELS[ex.source]}
|
|
</span>
|
|
)}
|
|
</div>
|
|
<div className="mt-1 flex flex-wrap items-center gap-1.5">
|
|
<Badge color="blue">{ex.primaryMuscle}</Badge>
|
|
{ex.secondaryMuscles.map((m) => (
|
|
<Badge key={m} color="blue">
|
|
{m}
|
|
</Badge>
|
|
))}
|
|
{FLAG_KEYS.filter((k) => CARD_FLAG_CHIPS[k] && ex[k]).map((k) => (
|
|
<Badge key={k} color="green">
|
|
{CARD_FLAG_CHIPS[k]}
|
|
</Badge>
|
|
))}
|
|
{ex.planExercisesCount > 0 && (
|
|
<Badge color="yellow">
|
|
{ex.planExercisesCount === 1 ? '1 plan' : `${ex.planExercisesCount} planów`}
|
|
</Badge>
|
|
)}
|
|
</div>
|
|
<div className="mt-1 flex flex-wrap items-center gap-1.5">
|
|
{ex.equipment.length === 0 ? (
|
|
<span className="text-dim text-[0.875rem]">brak maszyn</span>
|
|
) : (
|
|
ex.equipment.map((e) => (
|
|
<Badge key={e.id} color="gray">
|
|
{e.name}
|
|
</Badge>
|
|
))
|
|
)}
|
|
</div>
|
|
</div>
|
|
<div className="flex items-center gap-1">
|
|
<Button
|
|
variant="ghost"
|
|
size="sm"
|
|
onClick={() => openEdit(ex)}
|
|
aria-label={`Edytuj ${ex.name}`}
|
|
>
|
|
<Pencil className="w-4 h-4" />
|
|
</Button>
|
|
<Button
|
|
variant="ghost"
|
|
size="sm"
|
|
className="text-danger hover:text-danger"
|
|
onClick={() => setDeleting(ex)}
|
|
aria-label={`Usuń ${ex.name}`}
|
|
>
|
|
<Trash2 className="w-4 h-4" />
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
</Card>
|
|
))}
|
|
</div>
|
|
|
|
{!isLoading && !error && filtered.length === 0 && (
|
|
<Card>
|
|
<EmptyState
|
|
icon={Dumbbell}
|
|
title="Brak ćwiczeń"
|
|
description={
|
|
query
|
|
? 'Brak wyników dla podanego zapytania.'
|
|
: 'Brak ćwiczeń. Dodaj pierwsze przyciskiem „Nowe ćwiczenie” w menu kontekstowym.'
|
|
}
|
|
/>
|
|
</Card>
|
|
)}
|
|
|
|
<Modal
|
|
open={formOpen}
|
|
onClose={() => setFormOpen(false)}
|
|
title={editing ? 'Edytuj ćwiczenie' : 'Nowe ćwiczenie'}
|
|
className="sm:max-w-2xl"
|
|
>
|
|
<div className="flex flex-col gap-3.5">
|
|
<Field label="Nazwa">
|
|
<Input
|
|
value={form.name}
|
|
onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
|
|
placeholder="np. Wyciskanie sztangi leżąc"
|
|
/>
|
|
</Field>
|
|
<Field label="Główny mięsień">
|
|
<Select
|
|
value={form.primaryMuscle}
|
|
onChange={(e) => setForm((f) => ({ ...f, primaryMuscle: e.target.value }))}
|
|
>
|
|
<option value="">— wybierz —</option>
|
|
{primaryOptions.map((o) => (
|
|
<option key={o.value} value={o.value}>
|
|
{o.label}
|
|
</option>
|
|
))}
|
|
</Select>
|
|
</Field>
|
|
<Field label="Mięśnie pomocnicze">
|
|
{secondaryOptions.length === 0 ? (
|
|
<p className="text-dim text-[0.875rem]">
|
|
Brak obszarów w katalogu. Dodaj je w sekcji „Obszary treningowe”.
|
|
</p>
|
|
) : (
|
|
<div className="max-h-40 overflow-y-auto rounded-xl border border-line bg-input p-2">
|
|
{secondaryOptions.map((o) => (
|
|
<label
|
|
key={o.value}
|
|
className="flex items-center gap-2 rounded-[10px] px-2 py-1.5 hover:bg-card cursor-pointer"
|
|
>
|
|
<input
|
|
type="checkbox"
|
|
checked={form.secondaryMuscles.includes(o.value)}
|
|
onChange={() => toggleSecondary(o.value)}
|
|
className="accent-[var(--accent)]"
|
|
/>
|
|
<span className="text-[0.875rem]">{o.label}</span>
|
|
</label>
|
|
))}
|
|
</div>
|
|
)}
|
|
</Field>
|
|
<Field label="Typ ćwiczenia">
|
|
<Select
|
|
value={form.exerciseType}
|
|
onChange={(e) => {
|
|
const t = e.target.value as ExerciseType;
|
|
setForm((f) => ({
|
|
...f,
|
|
exerciseType: t,
|
|
// „własne” startuje od aktualnie zaznaczonego zestawu flag
|
|
flags: t === 'custom' ? currentFlags() : PRESETS[t as 'strength' | 'cardio'],
|
|
}));
|
|
}}
|
|
>
|
|
{(Object.keys(EXERCISE_TYPE_LABELS) as ExerciseType[]).map((t) => (
|
|
<option key={t} value={t}>
|
|
{EXERCISE_TYPE_LABELS[t]}
|
|
</option>
|
|
))}
|
|
</Select>
|
|
</Field>
|
|
{form.exerciseType === 'custom' && (
|
|
<Field label="Zapisywane wartości">
|
|
<div className="grid grid-cols-2 gap-1 rounded-xl border border-line bg-input p-2">
|
|
{FLAG_KEYS.map((k) => (
|
|
<label
|
|
key={k}
|
|
className="flex items-center gap-2 rounded-[10px] px-2 py-1.5 hover:bg-card cursor-pointer"
|
|
>
|
|
<input
|
|
type="checkbox"
|
|
checked={form.flags[k]}
|
|
onChange={() =>
|
|
setForm((f) => ({ ...f, flags: { ...f.flags, [k]: !f.flags[k] } }))
|
|
}
|
|
className="accent-[var(--accent)]"
|
|
/>
|
|
<span className="text-[0.875rem]">{FLAG_LABELS[k]}</span>
|
|
</label>
|
|
))}
|
|
</div>
|
|
</Field>
|
|
)}
|
|
<Field label="Maszyny / urządzenia">
|
|
{equipment.length === 0 ? (
|
|
<p className="text-dim text-[0.875rem]">
|
|
Brak urządzeń w katalogu. Dodaj je w sekcji „Urządzenia”.
|
|
</p>
|
|
) : (
|
|
<div className="max-h-56 overflow-y-auto rounded-xl border border-line bg-input p-2">
|
|
{equipment.map((e) => (
|
|
<label
|
|
key={e.id}
|
|
className="flex items-center gap-2 rounded-[10px] px-2 py-1.5 hover:bg-card cursor-pointer"
|
|
>
|
|
<input
|
|
type="checkbox"
|
|
checked={form.equipmentIds.includes(e.id)}
|
|
onChange={() => toggleEquipment(e.id)}
|
|
className="accent-[var(--accent)]"
|
|
/>
|
|
<span className="text-[0.875rem]">{e.name}</span>
|
|
</label>
|
|
))}
|
|
</div>
|
|
)}
|
|
</Field>
|
|
<Field label="Opis (opcjonalnie)">
|
|
<Textarea
|
|
value={form.description}
|
|
onChange={(e) => setForm((f) => ({ ...f, description: e.target.value }))}
|
|
placeholder="Krótki opis ćwiczenia widoczny w aplikacji."
|
|
rows={3}
|
|
/>
|
|
</Field>
|
|
<Field label="Jak wykonać (opcjonalnie)">
|
|
<Textarea
|
|
value={form.howTo}
|
|
onChange={(e) => setForm((f) => ({ ...f, howTo: e.target.value }))}
|
|
placeholder="Instrukcja wykonania."
|
|
rows={3}
|
|
/>
|
|
</Field>
|
|
<Field label="Najczęstsze błędy (opcjonalnie)">
|
|
<Textarea
|
|
value={form.commonMistakes}
|
|
onChange={(e) => setForm((f) => ({ ...f, commonMistakes: e.target.value }))}
|
|
placeholder="Czego unikać przy wykonaniu."
|
|
rows={3}
|
|
/>
|
|
</Field>
|
|
{formError && <ErrorText>{formError}</ErrorText>}
|
|
<div className="flex justify-end gap-2">
|
|
<Button variant="secondary" onClick={() => setFormOpen(false)}>
|
|
Anuluj
|
|
</Button>
|
|
<Button onClick={submit} disabled={save.isPending || !form.name || !form.primaryMuscle}>
|
|
{editing ? 'Zapisz' : 'Dodaj'}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
</Modal>
|
|
|
|
<ConfirmDialog
|
|
open={confirmFlagChange}
|
|
onClose={() => setConfirmFlagChange(false)}
|
|
onConfirm={() => save.mutate()}
|
|
title="Zmieniasz typ ćwiczenia"
|
|
description={`„${editing?.name}” jest używane w ${editing?.planExercisesCount} planie/planach. Zmiana zapisywanych wartości (serie/obciążenie/czas...) wpłynie na trwające plany. Kontynuować?`}
|
|
confirmLabel="Zapisz"
|
|
danger
|
|
busy={save.isPending}
|
|
/>
|
|
|
|
<ConfirmDialog
|
|
open={deleting != null}
|
|
onClose={() => setDeleting(null)}
|
|
onConfirm={() => deleting && remove.mutate(deleting.id)}
|
|
title="Usuń ćwiczenie"
|
|
description={`Na pewno usunąć „${deleting?.name}”? Nie można usunąć ćwiczenia używanego w planach.`}
|
|
confirmLabel="Usuń"
|
|
danger
|
|
busy={remove.isPending}
|
|
/>
|
|
</>
|
|
);
|
|
}
|