Plany: wyluskano stan edytora do hooka + naprawiono inicjalizacje edycji (czystszy PlanEditor, skeleton przy ladowaniu)
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import {
|
||||
createPlan,
|
||||
@@ -13,20 +13,55 @@ import {
|
||||
type PlanWeekInput,
|
||||
} from '../../api/queries';
|
||||
import type { Exercise, LatestExerciseResult } from '../../api/types';
|
||||
import { BackButton, Button, ErrorText, isPastWeek, type BadgeColor } from '../../components/ui';
|
||||
import {
|
||||
BackButton,
|
||||
Button,
|
||||
ErrorText,
|
||||
isPastWeek,
|
||||
Skeleton,
|
||||
type BadgeColor,
|
||||
} from '../../components/ui';
|
||||
import { useTopbar } from '../../topbar';
|
||||
import { DEFAULT_SET, displayedDaysOf, emptyWeek, weekFromApi, type EditorDay, type EditorSet, type EditorWeek } from './plan-editor/types';
|
||||
import { displayedDaysOf, type EditorDay, type EditorWeek } from './plan-editor/types';
|
||||
import { usePlanEditorState } from './plan-editor/usePlanEditorState';
|
||||
import { PlanMetaForm } from './plan-editor/PlanMetaForm';
|
||||
import { WeekAccordion } from './plan-editor/WeekAccordion';
|
||||
import { DayPicker } from './plan-editor/DayPicker';
|
||||
import { DayEditor } from './plan-editor/DayEditor';
|
||||
|
||||
/** Stan ładowania trybu edycji: skeleton w miejscu formularza i tygodni. */
|
||||
function EditorSkeleton() {
|
||||
return (
|
||||
<div className="space-y-4" aria-busy="true">
|
||||
<Skeleton className="h-36 w-full" />
|
||||
<Skeleton className="h-16 w-full" />
|
||||
<Skeleton className="h-40 w-full" />
|
||||
<Skeleton className="h-40 w-full" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function PlanEditor() {
|
||||
const { id, userId, planId } = useParams();
|
||||
const traineeUserId = userId ?? '';
|
||||
const isTraineeMode = !!traineeUserId;
|
||||
const planIdParam = id ?? planId ?? '';
|
||||
const isEdit = !!planIdParam;
|
||||
const navigate = useNavigate();
|
||||
const editor = usePlanEditorState();
|
||||
const ownerPlan = usePlan(isTraineeMode ? '' : planIdParam);
|
||||
const traineePlan = useTraineePlan(traineeUserId, isTraineeMode ? planIdParam : '');
|
||||
const planData = isTraineeMode ? traineePlan.data : ownerPlan.data;
|
||||
const { data: exData } = useExercises();
|
||||
const { data: latestData } = useTraineeLatestResults(traineeUserId);
|
||||
const { data: progressData } = useTraineeExerciseProgress(traineeUserId);
|
||||
|
||||
const backPath = isTraineeMode
|
||||
? `/trainees/${traineeUserId}?tab=plans`
|
||||
: isEdit
|
||||
? `/plans/${planIdParam}`
|
||||
: '/plans';
|
||||
|
||||
useTopbar({
|
||||
title: isTraineeMode
|
||||
? isEdit
|
||||
@@ -41,34 +76,21 @@ export default function PlanEditor() {
|
||||
? `/plans/${planIdParam}`
|
||||
: '/plans',
|
||||
});
|
||||
const navigate = useNavigate();
|
||||
const ownerPlan = usePlan(isTraineeMode ? '' : planIdParam);
|
||||
const traineePlan = useTraineePlan(traineeUserId, isTraineeMode ? planIdParam : '');
|
||||
const planData = isTraineeMode ? traineePlan.data : ownerPlan.data;
|
||||
const { data: exData } = useExercises();
|
||||
const { data: latestData } = useTraineeLatestResults(traineeUserId);
|
||||
const { data: progressData } = useTraineeExerciseProgress(traineeUserId);
|
||||
|
||||
const [title, setTitle] = useState('');
|
||||
const [startDate, setStartDate] = useState('');
|
||||
const [weeksCount, setWeeksCount] = useState(4);
|
||||
const [weeks, setWeeks] = useState<EditorWeek[]>(Array.from({ length: 4 }, () => emptyWeek()));
|
||||
const [expandedWeek, setExpandedWeek] = useState(0);
|
||||
// Inicjalizacja trybu edycji po załadowaniu danych (useEffect, nie setState during render)
|
||||
useEffect(() => {
|
||||
if (isEdit && planData && !editor.initialized) {
|
||||
editor.initFromPlan(planData.plan);
|
||||
}
|
||||
}, [isEdit, planData, editor]);
|
||||
|
||||
const [error, setError] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [initialized, setInitialized] = useState(!isEdit);
|
||||
const [expandedWeek, setExpandedWeek] = useState(0);
|
||||
const [resultsOpenKey, setResultsOpenKey] = useState<string | null>(null);
|
||||
|
||||
const backPath = isTraineeMode ? `/trainees/${traineeUserId}?tab=plans` : '/plans';
|
||||
const exercises = exData?.exercises ?? [];
|
||||
|
||||
// Initialize from API when editing
|
||||
if (isEdit && planData && !initialized) {
|
||||
setTitle(planData.plan.title);
|
||||
setWeeksCount(planData.plan.weeksCount);
|
||||
setWeeks(planData.plan.weeks.map((w) => weekFromApi(w)));
|
||||
setInitialized(true);
|
||||
}
|
||||
const loading = isEdit && !editor.initialized;
|
||||
|
||||
const grouped = useMemo(() => {
|
||||
const g = new Map<string, Exercise[]>();
|
||||
@@ -89,168 +111,63 @@ export default function PlanEditor() {
|
||||
[progressData],
|
||||
);
|
||||
|
||||
const editWeek = (wi: number, updater: (w: EditorWeek) => Partial<EditorWeek>) =>
|
||||
setWeeks((ws) => {
|
||||
const next = ws.map((w, i) => {
|
||||
if (i !== wi) return w;
|
||||
const base = i > 0 && !w.detached ? { ...w, days: JSON.parse(JSON.stringify(ws[0].days)) } : w;
|
||||
return { ...base, ...updater(base), detached: true };
|
||||
});
|
||||
return next;
|
||||
});
|
||||
|
||||
const addDay = (wi: number, dayOfWeek: number) =>
|
||||
editWeek(wi, (w) => ({
|
||||
days: [...w.days, { dayOfWeek, exercises: [] }].sort((a, b) => a.dayOfWeek - b.dayOfWeek),
|
||||
}));
|
||||
|
||||
const removeDay = (wi: number, dayOfWeek: number) =>
|
||||
editWeek(wi, (w) => ({ days: w.days.filter((d) => d.dayOfWeek !== dayOfWeek) }));
|
||||
|
||||
const addExercise = (wi: number, di: number, exerciseId: string) =>
|
||||
editWeek(wi, (w) => ({
|
||||
days: w.days.map((d, idx) =>
|
||||
idx === di ? { ...d, exercises: [...d.exercises, { exerciseId, sets: [{ ...DEFAULT_SET }] }] } : d,
|
||||
),
|
||||
}));
|
||||
|
||||
const removeExercise = (wi: number, di: number, ei: number) =>
|
||||
editWeek(wi, (w) => ({
|
||||
days: w.days.map((d, idx) =>
|
||||
idx === di ? { ...d, exercises: d.exercises.filter((_, x) => x !== ei) } : d,
|
||||
),
|
||||
}));
|
||||
|
||||
const setSetField = (wi: number, di: number, ei: number, si: number, field: keyof EditorSet, value: string) =>
|
||||
editWeek(wi, (w) => ({
|
||||
days: w.days.map((d, idx) =>
|
||||
idx === di
|
||||
? {
|
||||
...d,
|
||||
exercises: d.exercises.map((ex, x) =>
|
||||
x === ei
|
||||
? { ...ex, sets: ex.sets.map((s, y) => (y === si ? { ...s, [field]: value } : s)) }
|
||||
: ex,
|
||||
),
|
||||
}
|
||||
: d,
|
||||
),
|
||||
}));
|
||||
|
||||
const addSet = (wi: number, di: number, ei: number) =>
|
||||
editWeek(wi, (w) => ({
|
||||
days: w.days.map((d, idx) =>
|
||||
idx === di
|
||||
? {
|
||||
...d,
|
||||
exercises: d.exercises.map((ex, x) =>
|
||||
x === ei ? { ...ex, sets: [...ex.sets, { ...DEFAULT_SET }] } : ex,
|
||||
),
|
||||
}
|
||||
: d,
|
||||
),
|
||||
}));
|
||||
|
||||
const removeSet = (wi: number, di: number, ei: number, si: number) =>
|
||||
editWeek(wi, (w) => ({
|
||||
days: w.days.map((d, idx) => {
|
||||
if (idx !== di) return d;
|
||||
const updated = d.exercises.map((ex, x) =>
|
||||
x === ei ? { ...ex, sets: ex.sets.filter((_, y) => y !== si) } : ex,
|
||||
);
|
||||
// An exercise without sets is meaningless — drop it.
|
||||
if (updated[ei].sets.length === 0) {
|
||||
return { ...d, exercises: updated.filter((_, x) => x !== ei) };
|
||||
}
|
||||
return { ...d, exercises: updated };
|
||||
}),
|
||||
}));
|
||||
|
||||
/** Prefill serii z ostatniej sesji podopiecznego (reps/loadKg; brak danych → domyślne). */
|
||||
const prefillExercise = (wi: number, di: number, ei: number, latest: LatestExerciseResult) =>
|
||||
editWeek(wi, (w) => ({
|
||||
days: w.days.map((d, idx) =>
|
||||
idx === di
|
||||
? {
|
||||
...d,
|
||||
exercises: d.exercises.map((ex, x) =>
|
||||
x === ei
|
||||
? {
|
||||
...ex,
|
||||
sets: latest.sets.map((ls) => ({
|
||||
...DEFAULT_SET,
|
||||
reps: ls.reps != null ? String(ls.reps) : DEFAULT_SET.reps,
|
||||
loadKg: ls.loadKg != null ? String(ls.loadKg) : DEFAULT_SET.loadKg,
|
||||
})),
|
||||
}
|
||||
: ex,
|
||||
),
|
||||
}
|
||||
: d,
|
||||
),
|
||||
}));
|
||||
|
||||
const copyPrevWeek = (wi: number) => {
|
||||
if (wi === 0) return;
|
||||
setWeeks((ws) => {
|
||||
const prevDays = displayedDaysOf(ws, wi - 1);
|
||||
return ws.map((w, i) => (i === wi ? { days: JSON.parse(JSON.stringify(prevDays)), detached: true } : w));
|
||||
});
|
||||
};
|
||||
|
||||
const clearWeek = (wi: number) =>
|
||||
setWeeks((ws) => ws.map((w, i) => (i === wi ? { ...w, days: [], detached: true } : w)));
|
||||
|
||||
const dayLabel = (n: number) => (n === 1 ? '1 dzień' : `${n} dni`);
|
||||
|
||||
const weekSummary = (wi: number, w: EditorWeek, days: EditorDay[]): { text: string; color: BadgeColor } => {
|
||||
const weekSummary = (
|
||||
wi: number,
|
||||
w: EditorWeek,
|
||||
days: EditorDay[],
|
||||
): { text: string; color: BadgeColor } => {
|
||||
if (days.length === 0) {
|
||||
if (wi === 0) return { text: 'pusty', color: 'gray' };
|
||||
return w.detached ? { text: 'przerwa', color: 'blue' } : { text: 'odzwierciedla tyg. 1', color: 'yellow' };
|
||||
return w.detached
|
||||
? { text: 'przerwa', color: 'blue' }
|
||||
: { text: 'odzwierciedla tyg. 1', color: 'yellow' };
|
||||
}
|
||||
return { text: dayLabel(days.length), color: 'green' };
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
setError('');
|
||||
if (!title.trim()) {
|
||||
if (!editor.title.trim()) {
|
||||
setError('Podaj tytuł planu');
|
||||
return;
|
||||
}
|
||||
if (weeks.length !== weeksCount) {
|
||||
setError(`Plan ma ${weeksCount} tygodni — zdefiniuj je wszystkie`);
|
||||
if (editor.weeks.length !== editor.weeksCount) {
|
||||
setError(`Plan ma ${editor.weeksCount} tygodni — zdefiniuj je wszystkie`);
|
||||
return;
|
||||
}
|
||||
const body: { title: string; weeksCount: number; weeks: PlanWeekInput[]; startDate?: string } = {
|
||||
title: title.trim(),
|
||||
weeksCount,
|
||||
weeks: weeks.map((_, i) => ({
|
||||
index: i,
|
||||
days: displayedDaysOf(weeks, i).map((d) => ({
|
||||
dayOfWeek: d.dayOfWeek,
|
||||
exercises: d.exercises.map((e, oi) => ({
|
||||
exerciseId: e.exerciseId,
|
||||
order: oi,
|
||||
sets: e.sets.map((s, si) => ({
|
||||
index: si,
|
||||
reps: s.reps ? parseInt(s.reps) : null,
|
||||
loadKg: s.loadKg ? parseFloat(s.loadKg) : null,
|
||||
restSec: s.restSec ? parseInt(s.restSec) : null,
|
||||
rir: s.rir !== '' ? parseInt(s.rir) : null,
|
||||
difficulty: s.difficulty ? parseInt(s.difficulty) : null,
|
||||
const body: { title: string; weeksCount: number; weeks: PlanWeekInput[]; startDate?: string } =
|
||||
{
|
||||
title: editor.title.trim(),
|
||||
weeksCount: editor.weeksCount,
|
||||
weeks: editor.weeks.map((_, i) => ({
|
||||
index: i,
|
||||
days: displayedDaysOf(editor.weeks, i).map((d) => ({
|
||||
dayOfWeek: d.dayOfWeek,
|
||||
exercises: d.exercises.map((e, oi) => ({
|
||||
exerciseId: e.exerciseId,
|
||||
order: oi,
|
||||
sets: e.sets.map((s, si) => ({
|
||||
index: si,
|
||||
reps: s.reps ? parseInt(s.reps) : null,
|
||||
loadKg: s.loadKg ? parseFloat(s.loadKg) : null,
|
||||
restSec: s.restSec ? parseInt(s.restSec) : null,
|
||||
rir: s.rir !== '' ? parseInt(s.rir) : null,
|
||||
difficulty: s.difficulty ? parseInt(s.difficulty) : null,
|
||||
})),
|
||||
})),
|
||||
})),
|
||||
})),
|
||||
})),
|
||||
};
|
||||
};
|
||||
// Data startu tylko przy tworzeniu — plan tworzony i aktywowany w jednym kroku.
|
||||
// Tydzień startu: bieżący lub przyszły (WeekPicker blokuje minione; guard zapasowy).
|
||||
if (!isEdit && startDate) {
|
||||
if (isPastWeek(startDate)) {
|
||||
if (!isEdit && editor.startDate) {
|
||||
if (isPastWeek(editor.startDate)) {
|
||||
setError('Tydzień startu nie może być w przeszłości');
|
||||
return;
|
||||
}
|
||||
body.startDate = startDate;
|
||||
body.startDate = editor.startDate;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
@@ -277,6 +194,10 @@ export default function PlanEditor() {
|
||||
|
||||
const exerciseName = (eid: string) => exercises.find((p) => p.id === eid)?.name ?? eid;
|
||||
|
||||
if (loading) {
|
||||
return <EditorSkeleton />;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex justify-end mb-4">
|
||||
@@ -284,27 +205,17 @@ export default function PlanEditor() {
|
||||
</div>
|
||||
|
||||
<PlanMetaForm
|
||||
title={title}
|
||||
onTitleChange={setTitle}
|
||||
weeksCount={weeksCount}
|
||||
onWeeksCountChange={(n) => {
|
||||
setWeeksCount(n);
|
||||
setWeeks((ws) => {
|
||||
const next = [...ws];
|
||||
while (next.length < n) {
|
||||
const prev = next[next.length - 1] ?? emptyWeek();
|
||||
next.push({ days: JSON.parse(JSON.stringify(prev.days)), detached: true });
|
||||
}
|
||||
return next.slice(0, n);
|
||||
});
|
||||
}}
|
||||
startDate={startDate}
|
||||
onStartDateChange={setStartDate}
|
||||
title={editor.title}
|
||||
onTitleChange={editor.setTitle}
|
||||
weeksCount={editor.weeksCount}
|
||||
onWeeksCountChange={editor.setWeeksCount}
|
||||
startDate={editor.startDate}
|
||||
onStartDateChange={editor.setStartDate}
|
||||
showStartWeek={!isEdit}
|
||||
/>
|
||||
|
||||
{weeks.map((w, wi) => {
|
||||
const days = displayedDaysOf(weeks, wi);
|
||||
{editor.weeks.map((w, wi) => {
|
||||
const days = displayedDaysOf(editor.weeks, wi);
|
||||
const summary = weekSummary(wi, w, days);
|
||||
const expanded = expandedWeek === wi;
|
||||
return (
|
||||
@@ -315,14 +226,16 @@ export default function PlanEditor() {
|
||||
expanded={expanded}
|
||||
onToggle={() => setExpandedWeek(expanded ? -1 : wi)}
|
||||
canCopy={wi > 0}
|
||||
onCopyPrev={() => copyPrevWeek(wi)}
|
||||
onCopyPrev={() => editor.copyPrevWeek(wi)}
|
||||
canClear={days.length > 0 || !w.detached}
|
||||
onClear={() => clearWeek(wi)}
|
||||
onClear={() => editor.clearWeek(wi)}
|
||||
>
|
||||
<DayPicker
|
||||
days={days}
|
||||
onToggleDay={(dow) =>
|
||||
days.some((d) => d.dayOfWeek === dow) ? removeDay(wi, dow) : addDay(wi, dow)
|
||||
days.some((d) => d.dayOfWeek === dow)
|
||||
? editor.removeDay(wi, dow)
|
||||
: editor.addDay(wi, dow)
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -352,16 +265,18 @@ export default function PlanEditor() {
|
||||
const key = `${wi}:${di}:${ei}`;
|
||||
setResultsOpenKey(resultsOpenKey === key ? null : key);
|
||||
}}
|
||||
onAddExercise={(exerciseId) => addExercise(wi, di, exerciseId)}
|
||||
onRemoveExercise={(ei) => removeExercise(wi, di, ei)}
|
||||
onSetField={(ei, si, field, value) => setSetField(wi, di, ei, si, field, value)}
|
||||
onAddSet={(ei) => addSet(wi, di, ei)}
|
||||
onRemoveSet={(ei, si) => removeSet(wi, di, ei, si)}
|
||||
onAddExercise={(exerciseId) => editor.addExercise(wi, di, exerciseId)}
|
||||
onRemoveExercise={(ei) => editor.removeExercise(wi, di, ei)}
|
||||
onSetField={(ei, si, field, value) =>
|
||||
editor.setSetField(wi, di, ei, si, field, value)
|
||||
}
|
||||
onAddSet={(ei) => editor.addSet(wi, di, ei)}
|
||||
onRemoveSet={(ei, si) => editor.removeSet(wi, di, ei, si)}
|
||||
latestByExercise={latestByExercise}
|
||||
progressByExercise={progressByExercise}
|
||||
onPrefill={(ei) => {
|
||||
const latest = latestByExercise.get(d.exercises[ei].exerciseId);
|
||||
if (latest) prefillExercise(wi, di, ei, latest);
|
||||
if (latest) editor.prefillExercise(wi, di, ei, latest);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
@@ -377,7 +292,11 @@ export default function PlanEditor() {
|
||||
<Button onClick={save} disabled={saving} className="w-full sm:w-auto">
|
||||
{saving ? 'Zapisywanie…' : isEdit ? 'Zapisz zmiany' : 'Utwórz plan'}
|
||||
</Button>
|
||||
<Button variant="secondary" onClick={() => navigate(backPath)} className="w-full sm:w-auto">
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => navigate(backPath)}
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
Anuluj
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
281
app/src/pages/plans/plan-editor/usePlanEditorState.ts
Normal file
281
app/src/pages/plans/plan-editor/usePlanEditorState.ts
Normal file
@@ -0,0 +1,281 @@
|
||||
import { useCallback, useMemo, useRef, useState } from 'react';
|
||||
import type { LatestExerciseResult } from '../../../api/types';
|
||||
import { DEFAULT_SET, emptyWeek, weekFromApi, type EditorSet, type EditorWeek } from './types';
|
||||
|
||||
/** Shape of `plan` from the API (only the fields the editor needs). */
|
||||
export interface PlanLike {
|
||||
title: string;
|
||||
weeksCount: number;
|
||||
weeks: Parameters<typeof weekFromApi>[0][];
|
||||
}
|
||||
|
||||
/**
|
||||
* Cały stan edytora planu + akcje mutacji. PlanEditor zostaje cienki:
|
||||
* dane query + layout + save. Flaga `dirty` (porównanie z snapshotem
|
||||
* startowym) jest bazą dla guarda niezapisanych zmian i podsumowania stopki.
|
||||
*/
|
||||
export function usePlanEditorState() {
|
||||
const [title, setTitleState] = useState('');
|
||||
const [startDate, setStartDateState] = useState('');
|
||||
const [weeksCount, setWeeksCountState] = useState(4);
|
||||
const [weeks, setWeeks] = useState<EditorWeek[]>(() =>
|
||||
Array.from({ length: 4 }, () => emptyWeek()),
|
||||
);
|
||||
const [initialized, setInitialized] = useState(false);
|
||||
|
||||
// snapshot startowy: tryb nowy = stan początkowy; tryb edycji = po initFromPlan
|
||||
const snapshotRef = useRef<string | null>(null);
|
||||
if (snapshotRef.current === null) {
|
||||
snapshotRef.current = JSON.stringify({ title, startDate, weeksCount, weeks });
|
||||
}
|
||||
|
||||
const dirty = useMemo(
|
||||
() => JSON.stringify({ title, startDate, weeksCount, weeks }) !== snapshotRef.current,
|
||||
[title, startDate, weeksCount, weeks],
|
||||
);
|
||||
|
||||
/** Inicjalizacja trybu edycji po załadowaniu danych (zamiast setState during render). */
|
||||
const initFromPlan = useCallback((plan: PlanLike) => {
|
||||
const loaded = plan.weeks.map((w) => weekFromApi(w));
|
||||
setTitleState(plan.title);
|
||||
setWeeksCountState(plan.weeksCount);
|
||||
setWeeks(loaded);
|
||||
snapshotRef.current = JSON.stringify({
|
||||
title: plan.title,
|
||||
startDate: '',
|
||||
weeksCount: plan.weeksCount,
|
||||
weeks: loaded,
|
||||
});
|
||||
setInitialized(true);
|
||||
}, []);
|
||||
|
||||
const setTitle = useCallback((v: string) => setTitleState(v), []);
|
||||
const setStartDate = useCallback((v: string) => setStartDateState(v), []);
|
||||
|
||||
const setWeeksCount = useCallback((n: number) => {
|
||||
setWeeksCountState(n);
|
||||
setWeeks((ws) => {
|
||||
const next = [...ws];
|
||||
while (next.length < n) {
|
||||
const prev = next[next.length - 1] ?? emptyWeek();
|
||||
next.push({ days: structuredClone(prev.days), detached: true });
|
||||
}
|
||||
return next.slice(0, n);
|
||||
});
|
||||
}, []);
|
||||
|
||||
/** Mutacja tygodnia: niedetached tygodnie ≥2 odzwierciedlają tyg. 1 — pierwsza edycja odłącza. */
|
||||
const editWeek = useCallback((wi: number, updater: (w: EditorWeek) => Partial<EditorWeek>) => {
|
||||
setWeeks((ws) =>
|
||||
ws.map((w, i) => {
|
||||
if (i !== wi) return w;
|
||||
const base = i > 0 && !w.detached ? { ...w, days: structuredClone(ws[0].days) } : w;
|
||||
return { ...base, ...updater(base), detached: true };
|
||||
}),
|
||||
);
|
||||
}, []);
|
||||
|
||||
const addDay = useCallback(
|
||||
(wi: number, dayOfWeek: number) =>
|
||||
editWeek(wi, (w) => ({
|
||||
days: [...w.days, { dayOfWeek, exercises: [] }].sort((a, b) => a.dayOfWeek - b.dayOfWeek),
|
||||
})),
|
||||
[editWeek],
|
||||
);
|
||||
|
||||
const removeDay = useCallback(
|
||||
(wi: number, dayOfWeek: number) =>
|
||||
editWeek(wi, (w) => ({ days: w.days.filter((d) => d.dayOfWeek !== dayOfWeek) })),
|
||||
[editWeek],
|
||||
);
|
||||
|
||||
const addExercise = useCallback(
|
||||
(wi: number, di: number, exerciseId: string) =>
|
||||
editWeek(wi, (w) => ({
|
||||
days: w.days.map((d, idx) =>
|
||||
idx === di
|
||||
? { ...d, exercises: [...d.exercises, { exerciseId, sets: [{ ...DEFAULT_SET }] }] }
|
||||
: d,
|
||||
),
|
||||
})),
|
||||
[editWeek],
|
||||
);
|
||||
|
||||
const removeExercise = useCallback(
|
||||
(wi: number, di: number, ei: number) =>
|
||||
editWeek(wi, (w) => ({
|
||||
days: w.days.map((d, idx) =>
|
||||
idx === di ? { ...d, exercises: d.exercises.filter((_, x) => x !== ei) } : d,
|
||||
),
|
||||
})),
|
||||
[editWeek],
|
||||
);
|
||||
|
||||
/** Zmiana kolejności ćwiczenia w dniu (dir: -1 = wyżej, +1 = niżej). */
|
||||
const moveExercise = useCallback(
|
||||
(wi: number, di: number, ei: number, dir: -1 | 1) =>
|
||||
editWeek(wi, (w) => ({
|
||||
days: w.days.map((d, idx) => {
|
||||
if (idx !== di) return d;
|
||||
const target = ei + dir;
|
||||
if (target < 0 || target >= d.exercises.length) return d;
|
||||
const exercises = [...d.exercises];
|
||||
[exercises[ei], exercises[target]] = [exercises[target], exercises[ei]];
|
||||
return { ...d, exercises };
|
||||
}),
|
||||
})),
|
||||
[editWeek],
|
||||
);
|
||||
|
||||
const setSetField = useCallback(
|
||||
(wi: number, di: number, ei: number, si: number, field: keyof EditorSet, value: string) =>
|
||||
editWeek(wi, (w) => ({
|
||||
days: w.days.map((d, idx) =>
|
||||
idx === di
|
||||
? {
|
||||
...d,
|
||||
exercises: d.exercises.map((ex, x) =>
|
||||
x === ei
|
||||
? {
|
||||
...ex,
|
||||
sets: ex.sets.map((s, y) => (y === si ? { ...s, [field]: value } : s)),
|
||||
}
|
||||
: ex,
|
||||
),
|
||||
}
|
||||
: d,
|
||||
),
|
||||
})),
|
||||
[editWeek],
|
||||
);
|
||||
|
||||
const addSet = useCallback(
|
||||
(wi: number, di: number, ei: number) =>
|
||||
editWeek(wi, (w) => ({
|
||||
days: w.days.map((d, idx) =>
|
||||
idx === di
|
||||
? {
|
||||
...d,
|
||||
exercises: d.exercises.map((ex, x) =>
|
||||
x === ei ? { ...ex, sets: [...ex.sets, { ...DEFAULT_SET }] } : ex,
|
||||
),
|
||||
}
|
||||
: d,
|
||||
),
|
||||
})),
|
||||
[editWeek],
|
||||
);
|
||||
|
||||
/** Kopiowanie serii (tapering): nowa seria = kopia serii `si`, wstawiona za nią. */
|
||||
const duplicateSet = useCallback(
|
||||
(wi: number, di: number, ei: number, si: number) =>
|
||||
editWeek(wi, (w) => ({
|
||||
days: w.days.map((d, idx) =>
|
||||
idx === di
|
||||
? {
|
||||
...d,
|
||||
exercises: d.exercises.map((ex, x) =>
|
||||
x === ei
|
||||
? {
|
||||
...ex,
|
||||
sets: [
|
||||
...ex.sets.slice(0, si + 1),
|
||||
structuredClone(ex.sets[si]),
|
||||
...ex.sets.slice(si + 1),
|
||||
],
|
||||
}
|
||||
: ex,
|
||||
),
|
||||
}
|
||||
: d,
|
||||
),
|
||||
})),
|
||||
[editWeek],
|
||||
);
|
||||
|
||||
const removeSet = useCallback(
|
||||
(wi: number, di: number, ei: number, si: number) =>
|
||||
editWeek(wi, (w) => ({
|
||||
days: w.days.map((d, idx) => {
|
||||
if (idx !== di) return d;
|
||||
const updated = d.exercises.map((ex, x) =>
|
||||
x === ei ? { ...ex, sets: ex.sets.filter((_, y) => y !== si) } : ex,
|
||||
);
|
||||
// Ćwiczenie bez serii jest bez sensu — usuwamy je.
|
||||
if (updated[ei].sets.length === 0) {
|
||||
return { ...d, exercises: updated.filter((_, x) => x !== ei) };
|
||||
}
|
||||
return { ...d, exercises: updated };
|
||||
}),
|
||||
})),
|
||||
[editWeek],
|
||||
);
|
||||
|
||||
/** Prefill serii z ostatniej sesji podopiecznego (reps/loadKg; brak danych → domyślne). */
|
||||
const prefillExercise = useCallback(
|
||||
(wi: number, di: number, ei: number, latest: LatestExerciseResult) =>
|
||||
editWeek(wi, (w) => ({
|
||||
days: w.days.map((d, idx) =>
|
||||
idx === di
|
||||
? {
|
||||
...d,
|
||||
exercises: d.exercises.map((ex, x) =>
|
||||
x === ei
|
||||
? {
|
||||
...ex,
|
||||
sets: latest.sets.map((ls) => ({
|
||||
...DEFAULT_SET,
|
||||
reps: ls.reps != null ? String(ls.reps) : DEFAULT_SET.reps,
|
||||
loadKg: ls.loadKg != null ? String(ls.loadKg) : DEFAULT_SET.loadKg,
|
||||
})),
|
||||
}
|
||||
: ex,
|
||||
),
|
||||
}
|
||||
: d,
|
||||
),
|
||||
})),
|
||||
[editWeek],
|
||||
);
|
||||
|
||||
const copyPrevWeek = useCallback((wi: number) => {
|
||||
if (wi === 0) return;
|
||||
setWeeks((ws) => {
|
||||
const prevDays = ws[wi - 1].detached ? ws[wi - 1].days : ws[0].days;
|
||||
return ws.map((w, i) => (i === wi ? { days: structuredClone(prevDays), detached: true } : w));
|
||||
});
|
||||
}, []);
|
||||
|
||||
const clearWeek = useCallback(
|
||||
(wi: number) =>
|
||||
setWeeks((ws) => ws.map((w, i) => (i === wi ? { ...w, days: [], detached: true } : w))),
|
||||
[],
|
||||
);
|
||||
|
||||
return {
|
||||
title,
|
||||
startDate,
|
||||
weeksCount,
|
||||
weeks,
|
||||
initialized,
|
||||
dirty,
|
||||
setTitle,
|
||||
setStartDate,
|
||||
setWeeksCount,
|
||||
initFromPlan,
|
||||
addDay,
|
||||
removeDay,
|
||||
addExercise,
|
||||
removeExercise,
|
||||
moveExercise,
|
||||
setSetField,
|
||||
addSet,
|
||||
duplicateSet,
|
||||
removeSet,
|
||||
prefillExercise,
|
||||
copyPrevWeek,
|
||||
clearWeek,
|
||||
};
|
||||
}
|
||||
|
||||
export type PlanEditorState = ReturnType<typeof usePlanEditorState>;
|
||||
@@ -316,6 +316,16 @@ describe('Zakładka „Plany" w panelu podopiecznego', () => {
|
||||
});
|
||||
|
||||
describe('PlanEditor — tryb podopiecznego', () => {
|
||||
it('edycja: formularz inicjalizuje się z danych planu po załadowaniu', async () => {
|
||||
mockApi();
|
||||
renderAt(`/trainees/${TRAINEE_ID}/plans/plan-1/edit`);
|
||||
|
||||
expect(await screen.findByRole('heading', { name: 'Edycja planu podopiecznego' })).toBeInTheDocument();
|
||||
// tytuł i serie wczytane z API (DRAFT_DETAIL: Przysiady 1 seria 10 @ 60)
|
||||
expect(await screen.findByDisplayValue('Plan masowy')).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue('60')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('„Wstaw wyniki" prefylluje serie z ostatniej sesji', async () => {
|
||||
mockApi();
|
||||
const user = userEvent.setup();
|
||||
|
||||
Reference in New Issue
Block a user