Komunikator: sortowanie wg nieprzeczytanych/nazwy i grupowanie wg roli z zakładkami w topmenu (role w API rozmów)

This commit is contained in:
tisachi
2026-09-11 17:39:12 +02:00
parent 0ac6224a82
commit d211b092f2
10 changed files with 363 additions and 81 deletions

View File

@@ -400,6 +400,8 @@ export interface CircumferenceSeries {
// ---------- komunikator (messages) ----------
export interface Conversation {
coachingId: string;
/** Moja rola w relacji (odwrotna dla rozmówcy: podopieczny/trener). */
role: 'trainer' | 'trainee';
other: { id: string; firstName: string | null; lastName: string | null; nickname: string | null };
lastMessage: { body: string; createdAt: string; senderId: string } | null;
unreadCount: number;

View File

@@ -1,15 +1,38 @@
import { useEffect } from 'react';
import { useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { MessageSquare } from 'lucide-react';
import { ArrowUpDown, ChevronDown, MessageSquare, Users } from 'lucide-react';
import { useConversations, useMe } from '../../api/queries';
import { displayName, timeAgo } from '../../lib/format';
import { Card, EmptyState, ErrorText, Skeleton } from '../../components/ui';
import { cn } from '../../lib/utils';
import {
Badge,
Button,
Card,
EmptyState,
ErrorText,
H3,
Skeleton,
Tabs,
} from '../../components/ui';
import { Avatar } from '../../components/Avatar';
import { useListSearch } from '../../store/list-search';
import { useTopbar } from '../../topbar';
/* Opcje sortowania rozmów — komunikacyjne (inne niż metryki treningowe w /trainees) */
const SORT_OPTIONS = [
{ id: 'none', label: 'Brak' },
{ id: 'unread', label: 'Nieprzeczytane' },
{ id: 'name', label: 'Nazwa' },
] as const;
type SortKey = (typeof SORT_OPTIONS)[number]['id'];
/* Grupy rozmów wg roli rozmówcy: ja=trener → podopieczni; ja=podopieczny → trenerzy */
const ROLE_GROUPS = [
{ id: 'trainees', label: 'Podopieczni', myRole: 'trainer' as const },
{ id: 'trainers', label: 'Trenerzy', myRole: 'trainee' as const },
];
export default function Messages() {
useTopbar({ title: 'Komunikator', search: 'messages' });
const navigate = useNavigate();
const { data, isLoading, error } = useConversations();
const { data: meData } = useMe();
@@ -18,6 +41,108 @@ export default function Messages() {
const setQuery = useListSearch((s) => s.setQuery);
useEffect(() => () => setQuery('messages', ''), [setQuery]);
const [sortKey, setSortKey] = useState<SortKey>('none');
const [sortOpen, setSortOpen] = useState(false);
const [groupByRole, setGroupByRole] = useState(false);
const [activeRoleTab, setActiveRoleTab] = useState<string | null>(null);
useTopbar({
title: 'Komunikator',
search: 'messages',
filters: [
/* sortowanie: przycisk „Sortuj: <wartość>” + rozwijany select (kompaktowo w grupie filtrów) */
<div key="sort" className="relative">
<Button
size="sm"
variant="secondary"
onClick={() => setSortOpen((o) => !o)}
aria-haspopup="true"
aria-expanded={sortOpen}
/* pomarańcz (accent) tylko gdy wybrano nie-domyślne sortowanie; telefon: pełna szerokość */
className={cn(
'max-md:w-full',
sortKey !== 'none' && 'border-accent/55 bg-accent/11 text-accent-text',
)}
>
<ArrowUpDown className="w-4 h-4" />
Sortuj: {SORT_OPTIONS.find((s) => s.id === sortKey)?.label}
<ChevronDown className={`w-4 h-4 transition-transform ${sortOpen ? 'rotate-180' : ''}`} />
</Button>
{sortOpen && (
<>
<div className="fixed inset-0 z-40" onClick={() => setSortOpen(false)} />
{/* telefon: panel filtrów otwiera się w górę od dolnego paska — dropdown też w górę */}
<div className="absolute right-0 top-full z-50 mt-2 min-w-full rounded-xl border border-line bg-card p-1.5 shadow-lg max-md:top-auto max-md:bottom-full max-md:mb-2 max-md:mt-0">
{SORT_OPTIONS.map((s) => (
<button
key={s.id}
type="button"
onClick={() => {
setSortKey(s.id);
setSortOpen(false);
}}
className={`flex w-full cursor-pointer items-center justify-between gap-3 rounded-lg px-2.5 py-2 text-left text-[0.9rem] font-semibold transition-colors ${
sortKey === s.id ? 'bg-accent/12 text-accent-text' : 'text-ink hover:bg-line/30'
}`}
>
{s.label}
</button>
))}
</div>
</>
)}
</div>,
/* grupowanie wg roli rozmówcy — opcja (domyślnie lista płaska) */
<Button
key="group"
size="sm"
variant="secondary"
aria-pressed={groupByRole}
onClick={() => setGroupByRole((v) => !v)}
className={cn('max-md:w-full', groupByRole && 'border-accent/55 bg-accent/11 text-accent-text')}
>
<Users className="w-4 h-4" />
Grupuj wg roli
</Button>,
],
filterActive: sortKey !== 'none' || groupByRole,
});
const conversations = data?.conversations ?? [];
const q = query.toLowerCase();
const filtered = useMemo(() => {
const list = conversations.filter((c) => !q || displayName(c.other).toLowerCase().includes(q));
const byName = (a: (typeof list)[number], b: (typeof list)[number]) =>
displayName(a.other).localeCompare(displayName(b.other), 'pl');
const byLastMessage = (a: (typeof list)[number], b: (typeof list)[number]) =>
(b.lastMessage?.createdAt ?? '').localeCompare(a.lastMessage?.createdAt ?? '');
switch (sortKey) {
case 'unread':
list.sort(
(a, b) => b.unreadCount - a.unreadCount || byLastMessage(a, b) || byName(a, b),
);
break;
case 'name':
list.sort(byName);
break;
default:
break; // bez sortowania — kolejność z API (najnowsze rozmowy najpierw)
}
return list;
}, [conversations, q, sortKey]);
// grupy wg roli rozmówcy (tylko niepuste; stała kolejność: Podopieczni, Trenerzy)
const roleGroups = useMemo(
() =>
ROLE_GROUPS.map((g) => ({
...g,
items: filtered.filter((c) => c.role === g.myRole),
})).filter((g) => g.items.length > 0),
[filtered],
);
// aktywna zakładka roli (domyślnie pierwsza; fallback gdy grupa zniknie np. po wyszukiwarce)
const activeGroup = roleGroups.find((g) => g.id === activeRoleTab) ?? roleGroups[0];
if (isLoading) {
return (
<div className="space-y-4">
@@ -27,89 +152,109 @@ export default function Messages() {
);
}
const conversations = data?.conversations ?? [];
const q = query.toLowerCase();
const filtered = conversations
.filter((c) => !q || displayName(c.other).toLowerCase().includes(q))
.sort((a, b) => {
const ta = a.lastMessage?.createdAt ?? '';
const tb = b.lastMessage?.createdAt ?? '';
return tb.localeCompare(ta);
});
const renderRows = (items: typeof filtered) => (
<div className="divide-y divide-line">
{items.map((c) => {
const name = displayName(c.other);
const unread = c.unreadCount > 0;
const mine = c.lastMessage?.senderId === myId;
return (
<button
key={c.coachingId}
type="button"
onClick={() => navigate(`/messages/${c.coachingId}`)}
className="group flex w-full cursor-pointer items-center gap-3 rounded-[10px] px-2 py-3.5 text-left transition-colors hover:bg-line/20"
>
<div className="relative shrink-0">
<Avatar name={name} size={44} />
{unread && (
<span
aria-hidden="true"
className="absolute -right-0.5 -top-0.5 h-3 w-3 rounded-full border-2 border-card bg-accent"
/>
)}
</div>
<div className="min-w-0 flex-1">
<div className="flex items-baseline justify-between gap-2">
<span
className={`min-w-0 truncate text-[0.95rem] ${unread ? 'font-bold text-ink' : 'font-semibold'}`}
>
{name}
</span>
{c.lastMessage && (
<span
className={`shrink-0 text-[0.7rem] tabular-nums ${unread ? 'font-bold text-accent-text' : 'text-dim'}`}
>
{timeAgo(c.lastMessage.createdAt)}
</span>
)}
</div>
<div className="mt-0.5 flex items-center justify-between gap-2">
{c.lastMessage ? (
<span
className={`min-w-0 truncate text-[0.8125rem] ${unread ? 'font-semibold text-ink' : 'text-dim'}`}
>
{mine ? 'Ty: ' : ''}
{c.lastMessage.body}
</span>
) : (
<span className="min-w-0 truncate text-[0.8125rem] italic text-dim/70">
Brak wiadomości
</span>
)}
{unread && (
<span className="grid h-[18px] min-w-[18px] shrink-0 place-items-center rounded-full bg-accent px-1 text-[0.65rem] font-extrabold text-accent-ink">
{c.unreadCount}
</span>
)}
</div>
</div>
</button>
);
})}
</div>
);
return (
<Card>
<>
{error && <ErrorText>Błąd: {(error as Error).message}</ErrorText>}
{!error && conversations.length === 0 && (
<EmptyState
icon={MessageSquare}
title="Brak rozmów"
description="Rozmowa pojawi się po nawiązaniu aktywnej relacji z trenerem."
/>
<Card>
<EmptyState
icon={MessageSquare}
title="Brak rozmów"
description="Rozmowa pojawi się po nawiązaniu aktywnej relacji z trenerem."
/>
</Card>
)}
{!error && conversations.length > 0 && filtered.length === 0 && (
<p className="text-dim">Brak wyników dla podanego zapytania.</p>
<Card>
<p className="text-dim">Brak wyników dla podanego zapytania.</p>
</Card>
)}
{!error && filtered.length > 0 && (
<div className="divide-y divide-line">
{filtered.map((c) => {
const name = displayName(c.other);
const unread = c.unreadCount > 0;
const mine = c.lastMessage?.senderId === myId;
return (
<button
key={c.coachingId}
type="button"
onClick={() => navigate(`/messages/${c.coachingId}`)}
className="group flex w-full cursor-pointer items-center gap-3 rounded-[10px] px-2 py-3.5 text-left transition-colors hover:bg-line/20"
>
<div className="relative shrink-0">
<Avatar name={name} size={44} />
{unread && (
<span
aria-hidden="true"
className="absolute -right-0.5 -top-0.5 h-3 w-3 rounded-full border-2 border-card bg-accent"
/>
)}
</div>
<div className="min-w-0 flex-1">
<div className="flex items-baseline justify-between gap-2">
<span
className={`min-w-0 truncate text-[0.95rem] ${unread ? 'font-bold text-ink' : 'font-semibold'}`}
>
{name}
</span>
{c.lastMessage && (
<span
className={`shrink-0 text-[0.7rem] tabular-nums ${unread ? 'font-bold text-accent-text' : 'text-dim'}`}
>
{timeAgo(c.lastMessage.createdAt)}
</span>
)}
</div>
<div className="mt-0.5 flex items-center justify-between gap-2">
{c.lastMessage ? (
<span
className={`min-w-0 truncate text-[0.8125rem] ${unread ? 'font-semibold text-ink' : 'text-dim'}`}
>
{mine ? 'Ty: ' : ''}
{c.lastMessage.body}
</span>
) : (
<span className="min-w-0 truncate text-[0.8125rem] italic text-dim/70">Brak wiadomości</span>
)}
{unread && (
<span className="grid h-[18px] min-w-[18px] shrink-0 place-items-center rounded-full bg-accent px-1 text-[0.65rem] font-extrabold text-accent-ink">
{c.unreadCount}
</span>
)}
</div>
</div>
</button>
);
})}
</div>
groupByRole && activeGroup ? (
<>
{/* lista ról rozmówców jako zakładki — łatwiej się odnaleźć */}
<div className="mb-4">
<Tabs
tabs={roleGroups.map((g) => ({ id: g.id, label: g.label }))}
active={activeGroup.id}
onChange={setActiveRoleTab}
/>
</div>
<section>
<div className="mb-3 flex items-center gap-2.5">
<H3 className="mb-0">{activeGroup.label}</H3>
<Badge color="gray">{activeGroup.items.length}</Badge>
</div>
<Card>{renderRows(activeGroup.items)}</Card>
</section>
</>
) : (
<Card>{renderRows(filtered)}</Card>
)
)}
</Card>
</>
);
}