Plany: ochrona przed utrata niezapisanych zmian (beforeunload + potwierdzenie przy Anuluj/Wstecz/topmenu)
This commit is contained in:
@@ -16,6 +16,7 @@ import type { Exercise, LatestExerciseResult } from '../../api/types';
|
||||
import {
|
||||
BackButton,
|
||||
Button,
|
||||
ConfirmDialog,
|
||||
ErrorText,
|
||||
isPastWeek,
|
||||
Skeleton,
|
||||
@@ -62,6 +63,11 @@ export default function PlanEditor() {
|
||||
? `/plans/${planIdParam}`
|
||||
: '/plans';
|
||||
|
||||
const requestExit = () => {
|
||||
if (editor.dirty) setConfirmExit(true);
|
||||
else navigate(backPath);
|
||||
};
|
||||
|
||||
useTopbar({
|
||||
title: isTraineeMode
|
||||
? isEdit
|
||||
@@ -75,6 +81,8 @@ export default function PlanEditor() {
|
||||
: isEdit
|
||||
? `/plans/${planIdParam}`
|
||||
: '/plans',
|
||||
// mobile „<” w dolnym pasku topmenu: potwierdzenie przy niezapisanych zmianach
|
||||
onBack: editor.dirty ? requestExit : undefined,
|
||||
});
|
||||
|
||||
// Inicjalizacja trybu edycji po załadowaniu danych (useEffect, nie setState during render)
|
||||
@@ -88,10 +96,23 @@ export default function PlanEditor() {
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [expandedWeek, setExpandedWeek] = useState(0);
|
||||
const [resultsOpenKey, setResultsOpenKey] = useState<string | null>(null);
|
||||
const [confirmExit, setConfirmExit] = useState(false);
|
||||
const [clearWeekIdx, setClearWeekIdx] = useState<number | null>(null);
|
||||
|
||||
const exercises = exData?.exercises ?? [];
|
||||
const loading = isEdit && !editor.initialized;
|
||||
|
||||
// Guard niezapisanych zmian: F5/odświeżenie + wyjście (Anuluj/Wstecz/mobile „<”)
|
||||
useEffect(() => {
|
||||
if (!editor.dirty) return;
|
||||
const handler = (e: BeforeUnloadEvent) => {
|
||||
e.preventDefault();
|
||||
e.returnValue = '';
|
||||
};
|
||||
window.addEventListener('beforeunload', handler);
|
||||
return () => window.removeEventListener('beforeunload', handler);
|
||||
}, [editor.dirty]);
|
||||
|
||||
const grouped = useMemo(() => {
|
||||
const g = new Map<string, Exercise[]>();
|
||||
for (const p of exercises) {
|
||||
@@ -201,7 +222,7 @@ export default function PlanEditor() {
|
||||
return (
|
||||
<>
|
||||
<div className="flex justify-end mb-4">
|
||||
<BackButton onClick={() => navigate(backPath)} />
|
||||
<BackButton onClick={requestExit} />
|
||||
</div>
|
||||
|
||||
<PlanMetaForm
|
||||
@@ -228,7 +249,7 @@ export default function PlanEditor() {
|
||||
canCopy={wi > 0}
|
||||
onCopyPrev={() => editor.copyPrevWeek(wi)}
|
||||
canClear={days.length > 0 || !w.detached}
|
||||
onClear={() => editor.clearWeek(wi)}
|
||||
onClear={() => setClearWeekIdx(wi)}
|
||||
>
|
||||
<DayPicker
|
||||
days={days}
|
||||
@@ -292,15 +313,36 @@ 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={requestExit} className="w-full sm:w-auto">
|
||||
Anuluj
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ConfirmDialog
|
||||
open={confirmExit}
|
||||
onClose={() => setConfirmExit(false)}
|
||||
onConfirm={() => {
|
||||
setConfirmExit(false);
|
||||
navigate(backPath);
|
||||
}}
|
||||
title="Niezapisane zmiany"
|
||||
description="Masz niezapisane zmiany. Opuścić stronę i utracić je?"
|
||||
confirmLabel="Opuść"
|
||||
danger
|
||||
/>
|
||||
<ConfirmDialog
|
||||
open={clearWeekIdx !== null}
|
||||
onClose={() => setClearWeekIdx(null)}
|
||||
onConfirm={() => {
|
||||
if (clearWeekIdx !== null) editor.clearWeek(clearWeekIdx);
|
||||
setClearWeekIdx(null);
|
||||
}}
|
||||
title={`Wyczyść tydzień ${(clearWeekIdx ?? 0) + 1}`}
|
||||
description="Usunąć wszystkie dni i ćwiczenia tego tygodnia?"
|
||||
confirmLabel="Wyczyść"
|
||||
danger
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -30,7 +30,13 @@ function SectionSearchInput({ section }: { section: SearchableSection }) {
|
||||
);
|
||||
}
|
||||
|
||||
function ActionButton({ action, onNavigate }: { action: TopbarAction; onNavigate: (to: string) => void }) {
|
||||
function ActionButton({
|
||||
action,
|
||||
onNavigate,
|
||||
}: {
|
||||
action: TopbarAction;
|
||||
onNavigate: (to: string) => void;
|
||||
}) {
|
||||
const Icon = action.icon;
|
||||
return (
|
||||
<Button
|
||||
@@ -109,7 +115,7 @@ export function Topbar({ onMenuOpen }: { onMenuOpen?: () => void }) {
|
||||
{config?.back && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => navigate(config.back!)}
|
||||
onClick={() => (config.onBack ? config.onBack() : navigate(config.back!))}
|
||||
aria-label="Wstecz"
|
||||
className="grid h-[34px] w-[34px] flex-none cursor-pointer place-items-center rounded-[10px] border border-line bg-card text-dim shadow-card transition-colors hover:text-ink md:hidden"
|
||||
>
|
||||
@@ -145,7 +151,12 @@ export function Topbar({ onMenuOpen }: { onMenuOpen?: () => void }) {
|
||||
</GroupButton>
|
||||
))}
|
||||
{plusActions.length > 0 && (
|
||||
<GroupButton icon={Plus} label="Dodawanie" open={openGroup === 'add'} onToggle={() => toggle('add')}>
|
||||
<GroupButton
|
||||
icon={Plus}
|
||||
label="Dodawanie"
|
||||
open={openGroup === 'add'}
|
||||
onToggle={() => toggle('add')}
|
||||
>
|
||||
{plusActions.map((action) => (
|
||||
<ActionButton key={action.label} action={action} onNavigate={navigate} />
|
||||
))}
|
||||
|
||||
@@ -40,6 +40,11 @@ export interface TopbarConfig {
|
||||
* Tablet/PC bez zmian (przycisk „Wstecz” w treści strony).
|
||||
*/
|
||||
back?: string;
|
||||
/**
|
||||
* Opcjonalny handler „Wstecz” (mobile „<”): strona może przechwycić powrót
|
||||
* (np. potwierdzenie niezapisanych zmian). Brak handlera = nawigacja do `back`.
|
||||
*/
|
||||
onBack?: () => void;
|
||||
/** Wyszukiwarka listy (store list-search) → grupa 🔍. */
|
||||
search?: SearchableSection;
|
||||
/** Filtr po dacie (np. selektor miesiąca) → grupa lejka. */
|
||||
|
||||
@@ -164,7 +164,14 @@ const ACTIVE_DETAIL = {
|
||||
};
|
||||
|
||||
const LATEST_RESULTS = [
|
||||
{ exerciseId: 'ex-1', name: 'Przysiady', muscle: 'legs', date: '2026-08-20', sets: [{ reps: 12, loadKg: 70 }], oneRm: 80.6 },
|
||||
{
|
||||
exerciseId: 'ex-1',
|
||||
name: 'Przysiady',
|
||||
muscle: 'legs',
|
||||
date: '2026-08-20',
|
||||
sets: [{ reps: 12, loadKg: 70 }],
|
||||
oneRm: 80.6,
|
||||
},
|
||||
];
|
||||
|
||||
const PROGRESS = [
|
||||
@@ -193,10 +200,14 @@ function mockApi(opts: { plans?: unknown[] } = {}) {
|
||||
vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = String(input);
|
||||
const method = init?.method || 'GET';
|
||||
if (url.includes('/auth/refresh')) return jsonResponse(200, { user: USER, accessToken: 'tok-1' });
|
||||
if (url.includes('/auth/refresh'))
|
||||
return jsonResponse(200, { user: USER, accessToken: 'tok-1' });
|
||||
if (url.includes('/me/active-session')) return jsonResponse(200, { session: null });
|
||||
if (url.endsWith('/me'))
|
||||
return jsonResponse(200, { user: USER, memberships: [{ gymId: 'gym-1', roles: ['TRAINER'] }] });
|
||||
return jsonResponse(200, {
|
||||
user: USER,
|
||||
memberships: [{ gymId: 'gym-1', roles: ['TRAINER'] }],
|
||||
});
|
||||
if (url.includes('/dashboard'))
|
||||
return jsonResponse(200, {
|
||||
killstreak: 0,
|
||||
@@ -224,10 +235,12 @@ function mockApi(opts: { plans?: unknown[] } = {}) {
|
||||
return jsonResponse(200, { results: LATEST_RESULTS });
|
||||
if (url.includes(`/trainer/trainees/${TRAINEE_ID}/exercise-progress`))
|
||||
return jsonResponse(200, { exercises: PROGRESS });
|
||||
if (url.includes(`/trainer/trainees/${TRAINEE_ID}/history`)) return jsonResponse(200, { sessions: [] });
|
||||
if (url.includes(`/trainer/trainees/${TRAINEE_ID}/history`))
|
||||
return jsonResponse(200, { sessions: [] });
|
||||
if (url.includes(`/trainer/trainees/${TRAINEE_ID}/report`))
|
||||
return jsonResponse(200, { plan: null, muscles: [], days: [] });
|
||||
if (url.includes(`/trainer/trainees/${TRAINEE_ID}/moves`)) return jsonResponse(200, { moves: [] });
|
||||
if (url.includes(`/trainer/trainees/${TRAINEE_ID}/moves`))
|
||||
return jsonResponse(200, { moves: [] });
|
||||
if (url.includes(`/trainer/trainees/${TRAINEE_ID}`)) return jsonResponse(200, TRAINEE_DETAIL);
|
||||
return jsonResponse(200, {});
|
||||
}),
|
||||
@@ -320,18 +333,37 @@ describe('PlanEditor — tryb podopiecznego', () => {
|
||||
mockApi();
|
||||
renderAt(`/trainees/${TRAINEE_ID}/plans/plan-1/edit`);
|
||||
|
||||
expect(await screen.findByRole('heading', { name: 'Edycja planu podopiecznego' })).toBeInTheDocument();
|
||||
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('„Anuluj" przy niezapisanych zmianach pyta o potwierdzenie', async () => {
|
||||
mockApi();
|
||||
const user = userEvent.setup();
|
||||
renderAt(`/trainees/${TRAINEE_ID}/plans/new`);
|
||||
|
||||
await screen.findByRole('heading', { name: 'Plan dla podopiecznego' });
|
||||
// zmiana tytułu → stan dirty
|
||||
await user.type(screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy'), 'X');
|
||||
await user.click(screen.getByRole('button', { name: 'Anuluj' }));
|
||||
expect(await screen.findByRole('heading', { name: 'Niezapisane zmiany' })).toBeInTheDocument();
|
||||
// potwierdzenie → powrót do zakładki planów podopiecznego
|
||||
await user.click(screen.getByRole('button', { name: 'Opuść' }));
|
||||
expect(await screen.findByRole('heading', { name: 'Plany podopiecznego' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('„Wstaw wyniki" prefylluje serie z ostatniej sesji', async () => {
|
||||
mockApi();
|
||||
const user = userEvent.setup();
|
||||
renderAt(`/trainees/${TRAINEE_ID}/plans/new`);
|
||||
|
||||
expect(await screen.findByRole('heading', { name: 'Plan dla podopiecznego' })).toBeInTheDocument();
|
||||
expect(
|
||||
await screen.findByRole('heading', { name: 'Plan dla podopiecznego' }),
|
||||
).toBeInTheDocument();
|
||||
|
||||
// dodaj dzień (Poniedziałek)
|
||||
await user.click(screen.getByRole('button', { name: 'Pon' }));
|
||||
|
||||
Reference in New Issue
Block a user