Files
FitOS/app/src/pages/messages/MessageThread.tsx

358 lines
11 KiB
TypeScript

import { Fragment, useEffect, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useQueryClient } from '@tanstack/react-query';
import { Paperclip, Send, UserRound, X } from 'lucide-react';
import {
sendMessage,
useHistory,
useMe,
useMessages,
useTraineeHistory,
} from '../../api/queries';
import type { HistorySession, Message } from '../../api/types';
import MessageAttachmentCard from '../../components/MessageAttachmentCard';
import { displayName, fmtDate, fmtDateTime } from '../../lib/format';
import {
BackButton,
Button,
Card,
ErrorText,
Field,
Modal,
PageHeader,
Select,
Skeleton,
Textarea,
} from '../../components/ui';
import { useToast } from '../../components/toast';
import { useTopbar } from '../../topbar';
import { Avatar } from '../../components/Avatar';
import { ThreadContextCard } from './ThreadContextCard';
/* Bąbelek wiadomości: treść + załącznik + czas (mine = prawo, other = lewo). */
function MessageBubble({
message,
mine,
onOpenSession,
}: {
message: Message;
mine: boolean;
onOpenSession: (sessionId: string) => void;
}) {
return (
<div className={`flex ${mine ? 'justify-end' : 'justify-start'}`}>
<div
className={`max-w-[85%] rounded-2xl px-3 py-2 ${
mine ? 'bg-accent/15 border border-accent/30' : 'bg-input border border-line'
}`}
>
<div className="whitespace-pre-wrap break-words text-[0.95rem]">{message.body}</div>
{message.attachment && (
<MessageAttachmentCard attachment={message.attachment} onOpenSession={onOpenSession} />
)}
<div className="mt-1 text-right text-[0.75rem] text-dim">
{fmtDateTime(message.createdAt)}
</div>
</div>
</div>
);
}
/* Pisanie wiadomości: załącznik (opcjonalny) + textarea + „Załącz wynik” / „Wyślij”. */
function ComposerCard({
body,
onBodyChange,
staged,
onRemoveAttachment,
hasSessions,
onAttach,
onSend,
busy,
}: {
body: string;
onBodyChange: (v: string) => void;
staged: { label: string } | null;
onRemoveAttachment: () => void;
hasSessions: boolean;
onAttach: () => void;
onSend: () => void;
busy: boolean;
}) {
return (
<Card>
{staged && (
<div className="mb-2 flex items-center gap-2 rounded-[10px] border border-accent/40 bg-accent/10 px-3 py-2">
<Paperclip className="w-4 h-4 shrink-0 text-accent-text" />
<span className="min-w-0 flex-1 truncate text-[0.875rem] font-semibold">{staged.label}</span>
<button
type="button"
aria-label="Usuń załącznik"
onClick={onRemoveAttachment}
className="shrink-0 cursor-pointer rounded-md p-1 text-dim transition-colors hover:text-danger"
>
<X className="w-4 h-4" />
</button>
</div>
)}
<Textarea
rows={2}
placeholder="Napisz wiadomość…"
value={body}
onChange={(e) => onBodyChange(e.target.value)}
aria-label="Treść wiadomości"
/>
<div className="flex items-center justify-between gap-2 mt-2">
<Button variant="secondary" size="sm" onClick={onAttach} disabled={!hasSessions}>
<Paperclip className="w-4 h-4" />
Załącz wynik
</Button>
<Button size="sm" onClick={onSend} disabled={busy || !body.trim()}>
<Send className="w-4 h-4" />
Wyślij
</Button>
</div>
</Card>
);
}
/* Wybór sesji/ćwiczenia do załączenia w wiadomości (załącznik trafia do composera). */
function AttachmentPickerModal({
open,
onClose,
sessions,
sessionId,
onSessionChange,
exerciseId,
onExerciseChange,
onAttach,
busy,
}: {
open: boolean;
onClose: () => void;
sessions: HistorySession[];
sessionId: string;
onSessionChange: (id: string) => void;
exerciseId: string;
onExerciseChange: (id: string) => void;
onAttach: () => void;
busy: boolean;
}) {
const selectedSession = sessions.find((s) => s.id === sessionId);
return (
<Modal open={open} onClose={onClose} title="Załącz wynik">
{sessions.length === 0 && (
<p className="text-dim mb-3">Brak ukończonych sesji do załączenia.</p>
)}
<Field label="Sesja">
<Select
value={sessionId}
onChange={(e) => onSessionChange(e.target.value)}
aria-label="Sesja"
>
<option value="">— wybierz —</option>
{sessions.map((s) => (
<option key={s.id} value={s.id}>
{s.date ? fmtDate(s.date) : '—'} · {s.plan}
</option>
))}
</Select>
</Field>
{selectedSession && selectedSession.exercises.length > 0 && (
<Field label="Ćwiczenie (opcjonalnie)">
<Select
value={exerciseId}
onChange={(e) => onExerciseChange(e.target.value)}
aria-label="Ćwiczenie"
>
<option value="">Cała sesja</option>
{selectedSession.exercises.map((ex) => (
<option key={ex.id} value={ex.id}>
{ex.name}
</option>
))}
</Select>
</Field>
)}
<Button className="w-full" onClick={onAttach} disabled={busy || !sessionId}>
<Paperclip className="w-4 h-4" />
Dodaj załącznik
</Button>
<p className="mt-2 text-dim text-[0.8125rem]">
Załącznik pojawi się nad polem wiadomości — treść możesz dopisać później.
</p>
</Modal>
);
}
export default function MessageThread() {
const { coachingId = '' } = useParams();
const navigate = useNavigate();
const queryClient = useQueryClient();
const { push } = useToast();
const { data: meData } = useMe();
const myId = meData?.user.id;
const { data: thread, isLoading, error } = useMessages(coachingId);
/* Trener: mostek do kokpitu treningowego (panel podopiecznego); podopieczny
nie ma panelu trenera — akcja tylko dla roli trainer. */
useTopbar({
title: 'Komunikator',
back: '/messages',
actions:
thread?.role === 'trainer' && thread.other.id
? [{ label: 'Otwórz panel podopiecznego', icon: UserRound, to: `/trainees/${thread.other.id}` }]
: [],
});
const [body, setBody] = useState('');
const [pickerOpen, setPickerOpen] = useState(false);
const [attachSessionId, setAttachSessionId] = useState('');
const [attachExerciseId, setAttachExerciseId] = useState('');
const [staged, setStaged] = useState<{ sessionId: string; exerciseId: string; label: string } | null>(null);
const [busy, setBusy] = useState(false);
const bottomRef = useRef<HTMLDivElement>(null);
const role = thread?.role;
// Trener załącza sesje podopiecznego, podopieczny — własne.
const { data: traineeHist } = useTraineeHistory(role === 'trainer' ? (thread?.other.id ?? '') : '');
const { data: myHist } = useHistory();
const sessions = (role === 'trainer' ? (traineeHist?.sessions ?? []) : (myHist?.sessions ?? [])).filter(
(s) => s.status === 'COMPLETED',
);
useEffect(() => {
bottomRef.current?.scrollIntoView?.({ block: 'end' });
}, [thread?.messages.length]);
const openSession = (sessionId: string) => {
if (role === 'trainer') navigate(`/trainees/${thread?.other.id}?session=${sessionId}`);
else navigate(`/profile/history?session=${sessionId}`);
};
const doSend = async () => {
const text = body.trim();
if (!text) return;
setBusy(true);
try {
await sendMessage(
coachingId,
text,
staged
? {
sessionId: staged.sessionId,
...(staged.exerciseId ? { sessionExerciseId: staged.exerciseId } : {}),
}
: undefined,
);
setBody('');
setStaged(null);
setAttachSessionId('');
setAttachExerciseId('');
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['conversations'] }),
queryClient.invalidateQueries({ queryKey: ['messages', coachingId] }),
]);
} catch (e) {
push((e as Error).message, 'error');
} finally {
setBusy(false);
}
};
/* Załącznik można dodać przed napisaniem treści — trafia do composera jako etap. */
const stageAttachment = () => {
const session = sessions.find((s) => s.id === attachSessionId);
if (!session) return;
const exerciseName = attachExerciseId
? session.exercises.find((e) => e.id === attachExerciseId)?.name
: null;
setStaged({
sessionId: attachSessionId,
exerciseId: attachExerciseId,
label: `${session.date ? fmtDate(session.date) : '—'} · ${session.plan}${exerciseName ? ` · ${exerciseName}` : ''}`,
});
setPickerOpen(false);
};
if (isLoading) {
return (
<div className="space-y-4">
<Skeleton className="h-9 w-48" />
<Skeleton className="h-64" />
</div>
);
}
const otherName = thread ? displayName(thread.other) : '—';
return (
<>
<PageHeader
title={otherName}
leading={thread ? <Avatar name={otherName} size={28} /> : undefined}
actions={<BackButton onClick={() => navigate('/messages')} />}
/>
{!error && thread && <ThreadContextCard thread={thread} />}
<Card>
{error && <ErrorText>Błąd: {(error as Error).message}</ErrorText>}
{!error && (thread?.messages.length ?? 0) === 0 && (
<p className="text-dim">Brak wiadomości — napisz pierwszą.</p>
)}
{!error && (
<div className="space-y-2.5">
{thread?.messages.map((m, i, arr) => {
const prev = i > 0 ? arr[i - 1] : null;
const newDay = !prev || fmtDate(prev.createdAt) !== fmtDate(m.createdAt);
return (
<Fragment key={m.id}>
{newDay && (
<div className="flex justify-center py-1">
<span className="rounded-full bg-dim/13 px-3 py-0.5 text-[0.7rem] font-bold text-dim">
{fmtDate(m.createdAt)}
</span>
</div>
)}
<MessageBubble message={m} mine={m.senderId === myId} onOpenSession={openSession} />
</Fragment>
);
})}
<div ref={bottomRef} />
</div>
)}
</Card>
<ComposerCard
body={body}
onBodyChange={setBody}
staged={staged}
onRemoveAttachment={() => setStaged(null)}
hasSessions={sessions.length > 0}
onAttach={() => {
setAttachSessionId(staged?.sessionId ?? '');
setAttachExerciseId(staged?.exerciseId ?? '');
setPickerOpen(true);
}}
onSend={() => void doSend()}
busy={busy}
/>
<AttachmentPickerModal
open={pickerOpen}
onClose={() => setPickerOpen(false)}
sessions={sessions}
sessionId={attachSessionId}
onSessionChange={(id) => {
setAttachSessionId(id);
setAttachExerciseId('');
}}
exerciseId={attachExerciseId}
onExerciseChange={setAttachExerciseId}
onAttach={stageAttachment}
busy={busy}
/>
</>
);
}