feat(ui): notification center with leveled toasts and error capture

- Replace the toast store with a notification store: levels (info/success/
  warning/error/fatal), requiresInteraction, and a persisted history.
- Move toasts to the top-right, styled per level, with manual dismiss.
- Add a bell in the header opening a Notification Center (history, unread badge,
  'needs attention' vs info, clear all).
- Capture network failures and 5xx responses (api layer) and render crashes
  (ErrorBoundary) as notifications.
- Sound + server-sourced events + per-account settings remain for 6b.
This commit is contained in:
npeter83 2026-06-11 19:26:34 +02:00
parent ae0cd89e20
commit a105e5c184
9 changed files with 403 additions and 68 deletions

View file

@ -0,0 +1,48 @@
import { Component, type ReactNode } from "react";
import { notify } from "../lib/notifications";
interface Props {
children: ReactNode;
}
interface State {
crashed: boolean;
}
// Catches render-time crashes anywhere in the tree, logs a fatal notification (kept
// in the center across the reload) and offers a recovery action.
export default class ErrorBoundary extends Component<Props, State> {
state: State = { crashed: false };
static getDerivedStateFromError(): State {
return { crashed: true };
}
componentDidCatch(error: Error) {
notify({
level: "fatal",
title: "Something broke",
message: error.message || "Unexpected error",
requiresInteraction: true,
});
}
render() {
if (this.state.crashed) {
return (
<div className="min-h-screen grid place-items-center text-muted p-6 text-center">
<div>
<div className="text-lg font-semibold text-fg mb-1">Something went wrong.</div>
<div className="text-sm mb-3">The app hit an unexpected error.</div>
<button
onClick={() => location.reload()}
className="text-accent hover:underline text-sm font-semibold"
>
Reload
</button>
</div>
</div>
);
}
return this.props.children;
}
}

View file

@ -1,7 +1,7 @@
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query"; import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";
import { api, type FeedFilters, type Video } from "../lib/api"; import { api, type FeedFilters, type Video } from "../lib/api";
import { toast } from "../lib/toast"; import { toast } from "../lib/notifications";
import VideoCard from "./VideoCard"; import VideoCard from "./VideoCard";
const PAGE = 60; const PAGE = 60;

View file

@ -12,6 +12,7 @@ import {
import { SCHEMES, type Scheme, type ThemePrefs } from "../lib/theme"; import { SCHEMES, type Scheme, type ThemePrefs } from "../lib/theme";
import type { FeedFilters, Me } from "../lib/api"; import type { FeedFilters, Me } from "../lib/api";
import SyncStatus from "./SyncStatus"; import SyncStatus from "./SyncStatus";
import NotificationCenter from "./NotificationCenter";
function IconBtn(props: React.ButtonHTMLAttributes<HTMLButtonElement>) { function IconBtn(props: React.ButtonHTMLAttributes<HTMLButtonElement>) {
const { className = "", ...rest } = props; const { className = "", ...rest } = props;
@ -130,6 +131,8 @@ export default function Header({
)} )}
</div> </div>
<NotificationCenter />
<div className="pl-1"> <div className="pl-1">
<AccountMenu me={me} logout={logout} /> <AccountMenu me={me} logout={logout} />
</div> </div>

View file

@ -0,0 +1,119 @@
import { useEffect, useRef, useState } from "react";
import { useSyncExternalStore } from "react";
import { Bell, Trash2 } from "lucide-react";
import {
clearAll,
dismiss,
getNotifications,
getUnreadCount,
markAllRead,
subscribe,
} from "../lib/notifications";
import { LEVEL_STYLE } from "./Toaster";
function relTime(ts: number): string {
const s = Math.round((Date.now() - ts) / 1000);
if (s < 60) return "just now";
const m = Math.round(s / 60);
if (m < 60) return `${m}m ago`;
const h = Math.round(m / 60);
if (h < 24) return `${h}h ago`;
const d = Math.round(h / 24);
return `${d}d ago`;
}
export default function NotificationCenter() {
const notifications = useSyncExternalStore(subscribe, getNotifications, getNotifications);
const unread = useSyncExternalStore(subscribe, getUnreadCount, getUnreadCount);
const [open, setOpen] = useState(false);
const wrap = useRef<HTMLDivElement>(null);
// Opening the center marks everything read.
useEffect(() => {
if (open) markAllRead();
}, [open, notifications.length]);
return (
<div className="relative" ref={wrap}>
<button
onClick={() => setOpen((o) => !o)}
title="Notifications"
className="relative p-2 rounded-lg text-muted hover:text-fg hover:bg-card transition"
>
<Bell className="w-5 h-5" />
{unread > 0 && (
<span className="absolute -top-0.5 -right-0.5 min-w-[16px] h-4 px-1 rounded-full bg-accent text-accent-fg text-[10px] font-bold grid place-items-center">
{unread > 9 ? "9+" : unread}
</span>
)}
</button>
{open && (
<>
<div className="fixed inset-0 z-20" onClick={() => setOpen(false)} />
<div className="absolute right-0 mt-2 w-80 max-w-[calc(100vw-2rem)] rounded-xl border border-border bg-surface shadow-2xl z-30 flex flex-col max-h-[70vh]">
<div className="flex items-center justify-between px-3 py-2 border-b border-border">
<div className="text-sm font-semibold">Notifications</div>
{notifications.length > 0 && (
<button
onClick={clearAll}
className="flex items-center gap-1 text-xs text-muted hover:text-accent transition"
title="Clear all"
>
<Trash2 className="w-3.5 h-3.5" />
Clear
</button>
)}
</div>
<div className="overflow-y-auto">
{notifications.length === 0 ? (
<div className="px-3 py-8 text-center text-sm text-muted">
No notifications yet.
</div>
) : (
notifications.map((n) => {
const { icon: Icon, color } = LEVEL_STYLE[n.level];
const needsAction = n.requiresInteraction && !n.dismissed;
return (
<div
key={n.id}
className={`flex items-start gap-2.5 px-3 py-2.5 border-b border-border/60 ${
needsAction ? "bg-accent/5" : ""
}`}
>
<Icon className={`w-4 h-4 shrink-0 mt-0.5 ${color}`} />
<div className="min-w-0 flex-1">
{n.title && <div className="text-sm font-semibold">{n.title}</div>}
<div className="text-sm break-words">{n.message}</div>
<div className="flex items-center gap-2 mt-0.5">
<span className="text-[11px] text-muted">{relTime(n.ts)}</span>
{needsAction && (
<span className="text-[10px] uppercase tracking-wide font-semibold text-accent">
Action needed
</span>
)}
</div>
{n.action && !n.dismissed && (
<button
onClick={() => {
n.action!.onClick();
dismiss(n.id);
}}
className="mt-1 text-accent text-sm font-semibold hover:underline"
>
{n.action.label}
</button>
)}
</div>
</div>
);
})
)}
</div>
</div>
</>
)}
</div>
);
}

View file

@ -1,29 +1,68 @@
import { useSyncExternalStore } from "react"; import { useSyncExternalStore } from "react";
import { dismiss, getToasts, subscribe } from "../lib/toast"; import {
AlertCircle,
AlertTriangle,
CheckCircle2,
Info,
X,
XCircle,
} from "lucide-react";
import {
dismiss,
getActiveToasts,
subscribe,
type NotifLevel,
} from "../lib/notifications";
export const LEVEL_STYLE: Record<
NotifLevel,
{ icon: typeof Info; color: string }
> = {
info: { icon: Info, color: "text-accent" },
success: { icon: CheckCircle2, color: "text-emerald-400" },
warning: { icon: AlertTriangle, color: "text-amber-400" },
error: { icon: AlertCircle, color: "text-red-400" },
fatal: { icon: XCircle, color: "text-red-500" },
};
export default function Toaster() { export default function Toaster() {
const toasts = useSyncExternalStore(subscribe, getToasts, getToasts); const toasts = useSyncExternalStore(subscribe, getActiveToasts, getActiveToasts);
return ( return (
<div className="fixed bottom-4 right-4 z-50 flex flex-col gap-2"> <div className="fixed top-4 right-4 z-50 flex flex-col gap-2 w-80 max-w-[calc(100vw-2rem)]">
{toasts.map((t) => ( {toasts.map((t) => {
<div const { icon: Icon, color } = LEVEL_STYLE[t.level];
key={t.id} return (
className="bg-surface border border-border rounded-xl shadow-2xl px-4 py-3 flex items-center gap-4 animate-[fadeIn_0.15s_ease]" <div
> key={t.id}
<span className="text-sm">{t.message}</span> className="bg-surface border border-border rounded-xl shadow-2xl px-3 py-3 flex items-start gap-3 animate-[fadeIn_0.15s_ease]"
{t.action && ( >
<Icon className={`w-5 h-5 shrink-0 mt-0.5 ${color}`} />
<div className="min-w-0 flex-1">
{t.title && <div className="text-sm font-semibold">{t.title}</div>}
<div className="text-sm break-words">{t.message}</div>
{t.action && (
<button
onClick={() => {
t.action!.onClick();
dismiss(t.id);
}}
className="mt-1 text-accent text-sm font-semibold hover:underline"
>
{t.action.label}
</button>
)}
</div>
<button <button
onClick={() => { onClick={() => dismiss(t.id)}
t.action!.onClick(); className="shrink-0 text-muted hover:text-fg"
dismiss(t.id); title="Dismiss"
}}
className="text-accent text-sm font-semibold hover:underline"
> >
{t.action.label} <X className="w-4 h-4" />
</button> </button>
)} </div>
</div> );
))} })}
</div> </div>
); );
} }

View file

@ -1,3 +1,5 @@
import { notify } from "./notifications";
export interface Me { export interface Me {
id: number; id: number;
email: string; email: string;
@ -67,12 +69,34 @@ class HttpError extends Error {
} }
async function req(url: string, opts: RequestInit = {}): Promise<any> { async function req(url: string, opts: RequestInit = {}): Promise<any> {
const r = await fetch(url, { const method = opts.method ?? "GET";
credentials: "include", let r: Response;
headers: { "Content-Type": "application/json" }, try {
...opts, r = await fetch(url, {
}); credentials: "include",
if (!r.ok) throw new HttpError(r.status); headers: { "Content-Type": "application/json" },
...opts,
});
} catch (e) {
// Network/connection failure — surface it in the notification center.
notify({
level: "error",
title: "Network error",
message: `Couldn't reach the server (${method} ${url}).`,
});
throw e;
}
if (!r.ok) {
// Server faults are worth logging; 401/403/404 etc. are handled by callers.
if (r.status >= 500) {
notify({
level: "error",
title: `Server error ${r.status}`,
message: `${method} ${url}`,
});
}
throw new HttpError(r.status);
}
return r.status === 204 ? null : r.json(); return r.status === 204 ? null : r.json();
} }

View file

@ -0,0 +1,140 @@
// Client-side notification store. Surfaces transient toasts AND keeps a history that
// the Notification Center shows (info events, actions awaiting interaction, and app
// errors). History is persisted to localStorage so it survives reloads; action
// callbacks are live-only and dropped on reload.
export type NotifLevel = "info" | "success" | "warning" | "error" | "fatal";
export interface NotifAction {
label: string;
onClick: () => void;
}
export interface Notification {
id: number;
level: NotifLevel;
title?: string;
message: string;
action?: NotifAction;
requiresInteraction: boolean;
ts: number;
read: boolean;
dismissed: boolean; // transient toast surface closed (still kept in history)
}
export interface NotifyInput {
message: string;
level?: NotifLevel;
title?: string;
action?: NotifAction;
requiresInteraction?: boolean;
}
const HISTORY_KEY = "subfeed.notifications";
const MAX_HISTORY = 100;
const DEFAULT_TTL = 9000;
const ERROR_TTL = 15000;
let items: Notification[] = load();
let listeners: Array<() => void> = [];
let counter = items.reduce((m, n) => Math.max(m, n.id), 0) + 1;
// Cached derived snapshots — useSyncExternalStore needs stable references between
// emits, so we recompute these only when `items` changes.
let cachedActive: Notification[] = [];
let cachedReversed: Notification[] = [];
let cachedUnread = 0;
function load(): Notification[] {
try {
const raw = JSON.parse(localStorage.getItem(HISTORY_KEY) || "[]");
if (!Array.isArray(raw)) return [];
return raw.map((n) => ({ ...n, action: undefined }) as Notification);
} catch {
return [];
}
}
function persist() {
try {
const slim = items.map(({ action: _action, ...n }) => n);
localStorage.setItem(HISTORY_KEY, JSON.stringify(slim));
} catch {
/* ignore quota / serialization errors */
}
}
function recompute() {
cachedActive = items.filter((n) => !n.dismissed);
cachedReversed = [...items].reverse();
cachedUnread = items.reduce((c, n) => c + (n.read ? 0 : 1), 0);
}
function emit() {
items = items.slice(-MAX_HISTORY);
recompute();
persist();
listeners.forEach((l) => l());
}
recompute();
export function subscribe(listener: () => void): () => void {
listeners.push(listener);
return () => {
listeners = listeners.filter((l) => l !== listener);
};
}
export function notify(input: NotifyInput): number {
const id = counter++;
const requiresInteraction = input.requiresInteraction ?? false;
const level = input.level ?? "info";
items = [
...items,
{
id,
level,
title: input.title,
message: input.message,
action: input.action,
requiresInteraction,
ts: Date.now(),
read: false,
dismissed: false,
},
];
emit();
if (!requiresInteraction) {
const ttl = level === "error" || level === "fatal" ? ERROR_TTL : DEFAULT_TTL;
setTimeout(() => dismiss(id), ttl);
}
return id;
}
/** Back-compat: a simple info toast with an optional inline action (e.g. Undo). */
export function toast(message: string, action?: NotifAction): number {
return notify({ message, action });
}
/** Close the transient toast surface; the entry stays in the center's history. */
export function dismiss(id: number): void {
items = items.map((n) => (n.id === id ? { ...n, dismissed: true } : n));
emit();
}
export function markAllRead(): void {
if (items.every((n) => n.read)) return;
items = items.map((n) => (n.read ? n : { ...n, read: true }));
emit();
}
export function clearAll(): void {
if (items.length === 0) return;
items = [];
emit();
}
export const getActiveToasts = (): Notification[] => cachedActive;
export const getNotifications = (): Notification[] => cachedReversed;
export const getUnreadCount = (): number => cachedUnread;

View file

@ -1,41 +0,0 @@
export interface ToastAction {
label: string;
onClick: () => void;
}
export interface ToastItem {
id: number;
message: string;
action?: ToastAction;
}
let items: ToastItem[] = [];
let listeners: Array<() => void> = [];
let counter = 1;
function emit() {
listeners.forEach((l) => l());
}
export function toast(message: string, action?: ToastAction): number {
const id = counter++;
items = [...items, { id, message, action }];
emit();
setTimeout(() => dismiss(id), 9000);
return id;
}
export function dismiss(id: number) {
items = items.filter((i) => i.id !== id);
emit();
}
export function getToasts(): ToastItem[] {
return items;
}
export function subscribe(listener: () => void): () => void {
listeners.push(listener);
return () => {
listeners = listeners.filter((l) => l !== listener);
};
}

View file

@ -2,6 +2,7 @@ import React from "react";
import { createRoot } from "react-dom/client"; import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import App from "./App"; import App from "./App";
import ErrorBoundary from "./components/ErrorBoundary";
import "./index.css"; import "./index.css";
const queryClient = new QueryClient({ const queryClient = new QueryClient({
@ -11,7 +12,9 @@ const queryClient = new QueryClient({
createRoot(document.getElementById("root")!).render( createRoot(document.getElementById("root")!).render(
<React.StrictMode> <React.StrictMode>
<QueryClientProvider client={queryClient}> <QueryClientProvider client={queryClient}>
<App /> <ErrorBoundary>
<App />
</ErrorBoundary>
</QueryClientProvider> </QueryClientProvider>
</React.StrictMode> </React.StrictMode>
); );