Plany: edytor - akcje inline od md+ i pojedyncze Wstecz (smartBack), tydzien startu w edycji (zapis = aktualizacja + aktywacja), kalendarz pelna szerokosc

This commit is contained in:
tisachi
2026-09-13 02:28:11 +02:00
parent 3a40afe743
commit 8049c4bc47
9 changed files with 128 additions and 61 deletions

View File

@@ -368,6 +368,43 @@ export function usePlan(id: string) {
});
}
/** Plany jawnie udostępnione zalogowanemu (read-only). */
export function useSharedWithMe() {
return useQuery({
queryKey: ['plans', 'shared-with-me'],
queryFn: () => api<{ plans: Plan[] }>('/plans/shared-with-me'),
});
}
/** Moi trenerzy (ACTIVE coachings, gdzie ja jestem podopiecznym). */
export function useMyTrainers() {
return useQuery({
queryKey: ['me', 'trainers'],
queryFn: () =>
api<{
trainers: {
id: string;
firstName: string | null;
lastName: string | null;
nickname: string | null;
}[];
}>('/me/trainers'),
});
}
/** Udostępnienie planu użytkownikowi z AKTYWNYM coachingiem (właściciel). */
export function sharePlan(planId: string, userId: string) {
return api<{ share: { id: string } }>(`/plans/${planId}/share`, {
method: 'POST',
body: { userId },
});
}
/** Cofnięcie udostępnienia (właściciel). */
export function unsharePlan(planId: string, userId: string) {
return api(`/plans/${planId}/share/${userId}`, { method: 'DELETE' });
}
export interface PlanSetInput {
index: number;
reps?: number | null;
@@ -412,7 +449,7 @@ export function createPlan(body: PlanBody) {
return api<{ plan: { id: string } }>('/plans', { method: 'POST', body });
}
export function updatePlan(id: string, body: Omit<PlanBody, 'startDate'>) {
export function updatePlan(id: string, body: PlanBody) {
return api(`/plans/${id}`, { method: 'PATCH', body });
}
@@ -726,11 +763,7 @@ export function createTraineePlan(userId: string, body: PlanBody) {
});
}
export function updateTraineePlan(
userId: string,
planId: string,
body: Omit<PlanBody, 'startDate'>,
) {
export function updateTraineePlan(userId: string, planId: string, body: PlanBody) {
return api(`/trainer/trainees/${userId}/plans/${planId}`, { method: 'PATCH', body });
}

View File

@@ -85,7 +85,7 @@ export function WeekPicker({
const selMondayKey = value ? localDayKey(mondayOf(parseIsoLocal(value))) : null;
return (
<div className={cn('w-full max-w-xs', className)}>
<div className={cn('w-full', className)}>
<div className="flex items-center justify-between gap-2 mb-2">
<Button
size="sm"

View File

@@ -14,7 +14,7 @@ import {
useExercises,
type PlanBody,
} from '../../api/queries';
import { CalendarX, Check, ChevronLeft, ChevronRight } from 'lucide-react';
import { CalendarX, Check, ChevronRight } from 'lucide-react';
import {
BackButton,
Card,
@@ -146,8 +146,9 @@ export default function PlanEditor() {
// Walidacja kroku 1 (potrzebna w akcji topbar — przed useTopbar):
// pusty tytuł lub tydzień startu w przeszłości blokują „Dalej”. Krok 2 → 3 zawsze.
// Tydzień startu walidowany w obu trybach (edycja = aktualizacja + aktywacja).
const startWeekError =
!isEdit && editor.startDate && isPastWeek(editor.startDate)
editor.startDate && isPastWeek(editor.startDate)
? 'Tydzień startu nie może być w przeszłości'
: '';
const step1Valid = editor.title.trim() !== '' && !startWeekError;
@@ -175,16 +176,15 @@ export default function PlanEditor() {
: isEdit
? 'Edycja planu'
: 'Nowy plan',
// telefon: akcje płasko w dolnym pasku (bez zwijania za „⋯”) — to główna nawigacja
// „Wstecz”: telefon = ikona „<” (smartBack: krok > 1 → poprzedni etap, krok 1 → wyjście
// z guardem), tablet/PC = BackButton w treści — jedno sterowanie na viewport
back: backPath,
onBack: smartBack,
// akcje (Dalej/Zapisz) płasko w dolnym pasku na telefonie i inline od md+
// (bez akordeonu „⋯”) — to główna nawigacja wizarda
flatActionsMobile: true,
// nawigacja wizarda + zapis w menu kontekstowym (grupa ⋯; na lg+ inline w nagłówku)
alwaysInlineActions: true,
actions: [
{
label: 'Wstecz',
icon: ChevronLeft,
variant: 'secondary' as const,
onClick: smartBack,
},
...(step < 3
? [
{
@@ -326,9 +326,10 @@ export default function PlanEditor() {
})),
})),
};
// Data startu tylko przy tworzeniu — plan tworzony i aktywowany w jednym kroku.
// Data startu w obu trybach — przy tworzeniu: plan tworzony i aktywowany w jednym
// kroku; przy edycji (DRAFT): zapis = aktualizacja struktury + aktywacja.
// Tydzień startu: bieżący lub przyszły (WeekPicker blokuje minione; guard zapasowy).
if (!isEdit && editor.startDate) {
if (editor.startDate) {
if (isPastWeek(editor.startDate)) {
setError('Tydzień startu nie może być w przeszłości');
return;
@@ -407,7 +408,6 @@ export default function PlanEditor() {
startDate={editor.startDate}
onStartDateChange={editor.setStartDate}
startWeekError={startWeekError}
showStartWeek={!isEdit}
/>
)}
@@ -557,14 +557,14 @@ export default function PlanEditor() {
<PlanSummary
title={editor.title}
gymName={gymName}
startDate={isEdit ? '' : editor.startDate}
startDate={editor.startDate}
weeks={editor.weeks}
/>
)}
{/* sticky stopka: tylko belka podsumowania (akcje Wstecz/Dalej/Zapisz są w menu kontekstowym topbar);
na mobile pod stałym dolnym paskiem topmenu (+ safe-area) */}
<div className="sticky bottom-0 -mx-4 px-4 py-3 bg-bg/95 backdrop-blur border-t border-line mt-2 md:-mx-8 md:px-8 max-md:bottom-[calc(43px+max(0.5rem,env(safe-area-inset-bottom)))]">
{/* sticky stopka: tylko belka podsumowania (akcje Dalej/Zapisz + „<” są w menu kontekstowym topbar);
na mobile pod stałym dolnym paskiem topmenu (50px = pt-2 + wiersz 34px + pb) + safe-area */}
<div className="sticky bottom-0 -mx-4 px-4 py-3 bg-bg/95 backdrop-blur border-t border-line mt-2 md:-mx-8 md:px-8 max-md:bottom-[calc(50px+max(0.5rem,env(safe-area-inset-bottom)))]">
{error && <ErrorText>{error}</ErrorText>}
<div className="text-dim text-[0.8125rem]">
{dayCountLabel(totals.days)} · {exerciseCountLabel(totals.exercises)} ·{' '}

View File

@@ -1,6 +1,7 @@
import { Card, ErrorText, Field, Input, Select, WeekPicker } from '../../../components/ui';
/* Meta planu: tytuł, długość, tydzień startu (+ hint) — siatka pól, błędy inline. */
/* Meta planu: tytuł, długość, tydzień startu (+ hint) — inputy w rzędzie,
kalendarz na pełną szerokość karty, błędy inline. */
export function PlanMetaForm({
title,
onTitleChange,
@@ -11,7 +12,6 @@ export function PlanMetaForm({
startDate,
onStartDateChange,
startWeekError,
showStartWeek,
}: {
title: string;
onTitleChange: (v: string) => void;
@@ -22,7 +22,6 @@ export function PlanMetaForm({
startDate: string;
onStartDateChange: (v: string) => void;
startWeekError?: string;
showStartWeek: boolean;
}) {
const titleField = (
<Field label="Tytuł">
@@ -50,34 +49,21 @@ export function PlanMetaForm({
return (
<Card>
{/* desktop: równe kolumny — po lewej kalendarz startu (wypełnia kolumnę), po prawej
inputy pod siebie; mobile: inputy nad kalendarzem; tryb edycji bez startu: 2 kolumny */}
{showStartWeek ? (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4 items-start">
<div className="grid gap-4">
{titleField}
{weeksField}
</div>
<div className="lg:order-first">
<Field label="Tydzień startu">
<WeekPicker value={startDate} onChange={onStartDateChange} className="max-w-none" />
{startWeekError && <ErrorText>{startWeekError}</ErrorText>}
</Field>
</div>
</div>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
{titleField}
{weeksField}
</div>
)}
{showStartWeek && (
<p className="mt-3 text-dim text-[0.875rem]">
Opcjonalnie zaznacz tydzień startu — plan zostanie od razu aktywowany (start =
poniedziałek zaznaczonego tygodnia), a daty dni treningowych wyliczone automatycznie. Bez
tygodnia plan pozostanie szkicem.
</p>
)}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
{titleField}
{weeksField}
</div>
<div className="mt-4">
<Field label="Tydzień startu">
<WeekPicker value={startDate} onChange={onStartDateChange} />
{startWeekError && <ErrorText>{startWeekError}</ErrorText>}
</Field>
</div>
<p className="mt-3 text-dim text-[0.875rem]">
Opcjonalnie zaznacz tydzień startu — plan zostanie od razu aktywowany (start = poniedziałek
zaznaczonego tygodnia), a daty dni treningowych wyliczone automatycznie. Bez tygodnia plan
pozostanie szkicem.
</p>
</Card>
);
}

View File

@@ -6,6 +6,8 @@ import { DEFAULT_SET, emptyWeek, weekFromApi, type EditorSet, type EditorWeek }
export interface PlanLike {
title: string;
weeksCount: number;
/** Data startu (poniedziałek); null = szkic bez tygodnia startu. */
startDate?: string | null;
/** Informacyjna — siłownia planu; null = bez siłowni. */
gym?: { id: string; name: string } | null;
weeks: Parameters<typeof weekFromApi>[0][];
@@ -41,13 +43,15 @@ export function usePlanEditorState() {
/** Inicjalizacja trybu edycji po załadowaniu danych (zamiast setState during render). */
const initFromPlan = useCallback((plan: PlanLike) => {
const loaded = plan.weeks.map((w) => weekFromApi(w));
const loadedStart = plan.startDate ?? '';
setTitleState(plan.title);
setStartDateState(loadedStart);
setWeeksCountState(plan.weeksCount);
setWeeks(loaded);
setGymIdState(plan.gym?.id ?? null);
snapshotRef.current = JSON.stringify({
title: plan.title,
startDate: '',
startDate: loadedStart,
weeksCount: plan.weeksCount,
weeks: loaded,
gymId: plan.gym?.id ?? null,

View File

@@ -35,6 +35,11 @@ interface GroupButtonProps {
* Tablet (md–lg) i PC (lg+) bez zmian.
*/
flatOnMobile?: boolean;
/**
* md+: panel grupy zawsze inline (bez akordeonu od ikonki) — dla stron,
* gdzie akcje to główna nawigacja (np. wizard). Telefon bez zmian.
*/
alwaysInlineFromMd?: boolean;
children: ReactNode;
}
@@ -52,6 +57,7 @@ export function GroupButton({
open,
onToggle,
flatOnMobile,
alwaysInlineFromMd,
children,
}: GroupButtonProps) {
const ref = useRef<HTMLDivElement>(null);
@@ -77,14 +83,15 @@ export function GroupButton({
return (
<div ref={ref} className="md:relative flex items-center gap-2">
{/* lg+ treść grupy zawsze inline; md–lg akordeon od ikonki;
{/* lg+ (lub md+ przy alwaysInlineFromMd) treść grupy zawsze inline;
md–lg akordeon od ikonki;
telefon: domyślnie panel nad dolnym paskiem (w górę),
flatOnMobile: płaski rząd bezpośrednio w pasku */}
<div
className={cn(
'topbar-expand items-center gap-2',
flat || open ? 'flex' : 'hidden',
'lg:flex',
alwaysInlineFromMd ? 'md:flex' : 'lg:flex',
flat
? 'max-md:static max-md:flex-row max-md:items-center max-md:gap-2'
: 'max-md:absolute max-md:inset-x-0 max-md:bottom-full max-md:z-50 max-md:flex-col max-md:items-stretch max-md:gap-1.5 max-md:rounded-t-xl max-md:border-t max-md:border-line max-md:bg-card max-md:p-2.5 max-md:shadow-card max-md:animate-none',
@@ -100,7 +107,16 @@ export function GroupButton({
aria-expanded={open}
className={cn(
'relative grid h-[34px] w-[34px] flex-none cursor-pointer place-items-center rounded-[10px] border shadow-card transition-all duration-150',
flatOnMobile ? 'md:hidden' : 'lg:hidden',
// tryb płaski: ikona niepotrzebna na telefonie (akcje płasko w pasku)
// i na lg+ (panel inline); md–lg zostaje akordeon od ikonki;
// alwaysInlineFromMd: ikona niepotrzebna od md+ (panel inline)
alwaysInlineFromMd
? flatOnMobile
? 'hidden'
: 'md:hidden'
: flatOnMobile
? 'max-md:hidden lg:hidden'
: 'lg:hidden',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/60',
open
? 'border-accent/55 bg-accent/10 text-accent-text'

View File

@@ -168,6 +168,7 @@ export function Topbar({ onMenuOpen }: { onMenuOpen?: () => void }) {
open={openGroup === 'actions'}
onToggle={() => toggle('actions')}
flatOnMobile={config?.flatActionsMobile}
alwaysInlineFromMd={config?.alwaysInlineActions}
>
{otherActions.map((action) => (
<ActionButton key={action.label} action={action} onNavigate={navigate} />

View File

@@ -63,6 +63,12 @@ export interface TopbarConfig {
* Tablet (md–lg) i PC (lg+) bez zmian.
*/
flatActionsMobile?: boolean;
/**
* Tablet/PC (md+): akcje (grupa ⋯) zawsze rozwinięte inline w nagłówku
* (bez akordeonu od ikonki) — dla stron, gdzie akcje to główna nawigacja
* (np. wizard). Telefon bez zmian (flatActionsMobile lub akordeon).
*/
alwaysInlineActions?: boolean;
/** Własne grupy tematyczne (ikona + akcje), np. Edycja/Galeria/Urządzenia. */
groups?: TopbarCustomGroup[];
/** Wyjątek od domyślnie-zwiniętego akordeonu: grupa otwarta na starcie strony. */

View File

@@ -285,9 +285,30 @@ describe('PlanEditor — data startu i menu kontekstowe', () => {
const user = userEvent.setup();
renderApp();
await loginAndOpenNewPlan(user);
// „Wstecz” jest też w topmenu (wariant mobilny) — sprawdzamy ten w treści strony
const content = document.querySelector('.max-w-5xl');
// „Wstecz” w treści strony (BackButton, md+); topbar ma osobną ikonę „<” (mobile)
const content = document.querySelector('main .max-w-5xl');
expect(content).not.toBeNull();
expect(within(content!).getByRole('button', { name: 'Wstecz' })).toBeInTheDocument();
});
it('topmenu edytora: akcje inline od md+ (bez akordeonu „⋯”), pojedyncze „Wstecz”', async () => {
mockApi({});
const user = userEvent.setup();
renderApp();
await loginAndOpenNewPlan(user);
const header = document.querySelector('header')!;
// ikona grupy ⋯ zawsze ukryta: telefon = płaski rząd w pasku, md+ = inline w nagłówku
const actionsIcon = header.querySelector('button[aria-label="Akcje"]') as HTMLElement;
expect(actionsIcon.className).toContain('hidden');
// panel akcji inline od md+
const panel = actionsIcon.previousElementSibling as HTMLElement;
expect(panel.className).toContain('md:flex');
// akcje widoczne w nagłówku bez otwierania menu
expect(within(header).getByRole('button', { name: 'Dalej' })).toBeInTheDocument();
expect(within(header).getByRole('button', { name: 'Zapisz' })).toBeInTheDocument();
// „Wstecz” w topbarze = ikona „<” (mobile); na md+ BackButton w treści
const backIcon = header.querySelector('button[aria-label="Wstecz"]') as HTMLElement;
expect(backIcon.className).toContain('md:hidden');
});
});