Уведомления: persistent + live (push-to-invalidate → pull)

Новая система уведомлений поверх готовой SSE-шины: события пишутся в БД,
живут 72 часа и чистятся (при чтении списка + фоновой задачей), всплывают
сверху экрана в момент прихода, доступны через колокольчик в правом верхнем
углу (бейдж непрочитанных + панель).

Типы: приглашение в группу (→ /group), старт/финиш партии участникам кроме
инициатора (→ /match/{id}). Титулы — готовый хелпер-задел (не подключён, т.к.
выдача титулов игрокам ещё не реализована).

Бэкенд: модель Notification + миграция 0008 (идемпотентная), notification_service,
notify.notifications_changed, роутер /api/notifications (GET + /read), триггеры
в groups/matches, фоновая чистка в lifespan, защита hub.publish от закрытого loop.
Фронт: useNotifications/useMarkNotificationsRead, NotificationBell/Panel/Toaster,
перекомпоновка top-bar, стили; useServerEvents знает тип notifications.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-26 15:16:40 +03:00
co-authored by Claude Opus 4.8
parent ef5c242e16
commit f4286ffa6c
20 changed files with 939 additions and 13 deletions
+17 -8
View File
@@ -3,6 +3,8 @@ import { Outlet, useLocation, useNavigate } from "react-router-dom";
import { useMe } from "../hooks/auth";
import { useServerEvents } from "../hooks/useServerEvents";
import { BottomBar } from "./BottomBar";
import { NotificationBell } from "./NotificationBell";
import { NotificationToaster } from "./NotificationToaster";
const TITLES: Record<string, string> = {
"/": "Forbidden Stars",
@@ -26,16 +28,23 @@ export function AppShell() {
return (
<div className="app-shell">
<header className="top-bar">
{isHome ? (
<span className="title">{title}</span>
) : (
<button className="btn btn-ghost" onClick={() => navigate(-1)}>
← Назад
</button>
)}
<span className="title small muted">{!isHome ? title : ""}</span>
<div className="top-bar-left">
{isHome ? (
<span className="title">{title}</span>
) : (
<button className="btn btn-ghost" onClick={() => navigate(-1)}>
← Назад
</button>
)}
</div>
<span className="title small muted top-bar-center">{!isHome ? title : ""}</span>
<div className="top-bar-right">
<NotificationBell enabled={!!me} />
</div>
</header>
<NotificationToaster enabled={!!me} />
<main className="app-main">
<Outlet />
</main>
@@ -0,0 +1,42 @@
import { Bell } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useMarkNotificationsRead, useNotifications } from "../hooks/notifications";
import { NotificationPanel } from "./NotificationPanel";
/** Колокольчик в правом верхнем углу: бейдж непрочитанных + выпадающая панель. */
export function NotificationBell({ enabled }: { enabled: boolean }) {
const { data } = useNotifications(enabled);
const markRead = useMarkNotificationsRead();
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);
const unread = data?.unread_count ?? 0;
// Закрытие панели по клику вне неё.
useEffect(() => {
if (!open) return;
const onDoc = (e: MouseEvent) => {
if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
};
document.addEventListener("mousedown", onDoc);
return () => document.removeEventListener("mousedown", onDoc);
}, [open]);
if (!enabled) return null;
const toggle = () => {
const next = !open;
setOpen(next);
if (next && unread > 0) markRead.mutate(undefined); // открыли — гасим бейдж
};
return (
<div className="notif-bell-wrap" ref={ref}>
<button className="notif-bell" aria-label="Уведомления" onClick={toggle}>
<Bell size={20} />
{unread > 0 && <span className="notif-badge">{unread > 99 ? "99+" : unread}</span>}
</button>
{open && <NotificationPanel items={data?.items ?? []} onClose={() => setOpen(false)} />}
</div>
);
}
@@ -0,0 +1,43 @@
import { useNavigate } from "react-router-dom";
import { formatTime } from "../domain/format";
import type { Notification } from "../hooks/notifications";
/** Выпадающий список уведомлений под колокольчиком. Клик по строке ведёт по ссылке. */
export function NotificationPanel({
items,
onClose,
}: {
items: Notification[];
onClose: () => void;
}) {
const navigate = useNavigate();
const go = (n: Notification) => {
onClose();
if (n.link) navigate(n.link);
};
return (
<div className="notif-panel">
<div className="notif-panel-head">Уведомления</div>
{items.length === 0 ? (
<div className="notif-empty muted small">Уведомлений нет</div>
) : (
<div className="notif-list">
{items.map((n) => (
<button
key={n.id}
className={`notif-item${n.read_at ? "" : " unread"}`}
onClick={() => go(n)}
>
<div className="notif-item-title">{n.title}</div>
{n.body && <div className="notif-item-body muted small">{n.body}</div>}
<div className="notif-item-time muted small">{formatTime(n.created_at)}</div>
</button>
))}
</div>
)}
</div>
);
}
@@ -0,0 +1,50 @@
import { useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useNotifications, type Notification } from "../hooks/notifications";
const TOAST_TTL_MS = 5000;
const MAX_VISIBLE = 4;
/** Всплывашки сверху экрана в момент прихода новых уведомлений (push-to-invalidate → pull).
* Первый снимок списка не всплывает (чтобы не спамить при загрузке) — только новые id. */
export function NotificationToaster({ enabled }: { enabled: boolean }) {
const { data } = useNotifications(enabled);
const navigate = useNavigate();
const seen = useRef<Set<number> | null>(null);
const [toasts, setToasts] = useState<Notification[]>([]);
useEffect(() => {
if (!data) return;
const items = data.items;
if (seen.current === null) {
seen.current = new Set(items.map((n) => n.id)); // первая загрузка — запомнить, не всплывать
return;
}
const fresh = items.filter((n) => !seen.current!.has(n.id));
if (fresh.length === 0) return;
fresh.forEach((n) => seen.current!.add(n.id));
setToasts((prev) => [...fresh, ...prev].slice(0, MAX_VISIBLE));
fresh.forEach((n) => {
setTimeout(() => setToasts((prev) => prev.filter((t) => t.id !== n.id)), TOAST_TTL_MS);
});
}, [data]);
if (!enabled || toasts.length === 0) return null;
const click = (n: Notification) => {
setToasts((prev) => prev.filter((t) => t.id !== n.id));
if (n.link) navigate(n.link);
};
return (
<div className="toast-top-wrap">
{toasts.map((n) => (
<button key={n.id} className="toast-top" onClick={() => click(n)}>
<div className="toast-top-title">{n.title}</div>
{n.body && <div className="toast-top-body">{n.body}</div>}
</button>
))}
</div>
);
}