fix(ui): notification UX — outside-click close, toast countdown, hide entry actions

- NotificationCenter closes on outside click (document listener, not an overlay
  that the blurred header trapped) and no longer needs a second bell click.
- Toasts show a level-colored countdown bar and auto-dismiss faster (6s default).
- Hidden-video notifications carry structured meta so the center offers an in-app
  'Find in feed' (jump to that channel's hidden videos) and a one-click 'Unhide',
  working even after a reload when the live Undo callback is gone.
This commit is contained in:
npeter83 2026-06-11 19:46:58 +02:00
parent 42150edb92
commit a86f829a2d
6 changed files with 173 additions and 71 deletions

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/notifications"; import { notify } from "../lib/notifications";
import VideoCard from "./VideoCard"; import VideoCard from "./VideoCard";
const PAGE = 60; const PAGE = 60;
@ -73,7 +73,18 @@ export default function Feed({
.then(() => qc.invalidateQueries({ queryKey: ["feed"] })) .then(() => qc.invalidateQueries({ queryKey: ["feed"] }))
.catch(() => {}); .catch(() => {});
if (status === "hidden") { if (status === "hidden") {
toast("Video hidden", { label: "Undo", onClick: () => onState(id, "new") }); const v = (query.data?.pages ?? []).flatMap((p) => p.items).find((x) => x.id === id);
notify({
message: v?.title ? `Hidden “${v.title}` : "Video hidden",
action: { label: "Undo", onClick: () => onState(id, "new") },
meta: {
kind: "video-hidden",
videoId: id,
title: v?.title ?? "this video",
channelId: v?.channel_id ?? "",
channelName: v?.channel_title ?? "",
},
});
} }
} }

View file

@ -131,7 +131,7 @@ export default function Header({
)} )}
</div> </div>
<NotificationCenter /> <NotificationCenter filters={filters} setFilters={setFilters} />
<div className="pl-1"> <div className="pl-1">
<AccountMenu me={me} logout={logout} /> <AccountMenu me={me} logout={logout} />

View file

@ -1,13 +1,16 @@
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState, useSyncExternalStore } from "react";
import { useSyncExternalStore } from "react"; import { useQueryClient } from "@tanstack/react-query";
import { Bell, Trash2 } from "lucide-react"; import { Bell, Eye, Search, Trash2 } from "lucide-react";
import { api, type FeedFilters } from "../lib/api";
import { import {
clearAll, clearAll,
dismiss, dismiss,
getNotifications, getNotifications,
getUnreadCount, getUnreadCount,
markAllRead, markAllRead,
notify,
subscribe, subscribe,
type NotifMeta,
} from "../lib/notifications"; } from "../lib/notifications";
import { LEVEL_STYLE } from "./Toaster"; import { LEVEL_STYLE } from "./Toaster";
@ -22,17 +25,55 @@ function relTime(ts: number): string {
return `${d}d ago`; return `${d}d ago`;
} }
export default function NotificationCenter() { export default function NotificationCenter({
filters,
setFilters,
}: {
filters: FeedFilters;
setFilters: (f: FeedFilters) => void;
}) {
const notifications = useSyncExternalStore(subscribe, getNotifications, getNotifications); const notifications = useSyncExternalStore(subscribe, getNotifications, getNotifications);
const unread = useSyncExternalStore(subscribe, getUnreadCount, getUnreadCount); const unread = useSyncExternalStore(subscribe, getUnreadCount, getUnreadCount);
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const wrap = useRef<HTMLDivElement>(null); const wrap = useRef<HTMLDivElement>(null);
const qc = useQueryClient();
// Close when clicking anywhere outside the panel.
useEffect(() => {
if (!open) return;
function onDown(e: MouseEvent) {
if (wrap.current && !wrap.current.contains(e.target as Node)) setOpen(false);
}
document.addEventListener("mousedown", onDown);
return () => document.removeEventListener("mousedown", onDown);
}, [open]);
// Opening the center marks everything read. // Opening the center marks everything read.
useEffect(() => { useEffect(() => {
if (open) markAllRead(); if (open) markAllRead();
}, [open, notifications.length]); }, [open, notifications.length]);
function locateHidden(meta: NotifMeta) {
setFilters({
...filters,
show: "hidden",
channelId: meta.channelId || undefined,
channelName: meta.channelName || undefined,
});
setOpen(false);
}
function unhide(meta: NotifMeta) {
api
.setState(meta.videoId, "new")
.then(() => {
qc.invalidateQueries({ queryKey: ["feed"] });
qc.invalidateQueries({ queryKey: ["feed-count"] });
notify({ level: "success", message: `Unhidden “${meta.title}` });
})
.catch(() => {});
}
return ( return (
<div className="relative" ref={wrap}> <div className="relative" ref={wrap}>
<button <button
@ -49,52 +90,69 @@ export default function NotificationCenter() {
</button> </button>
{open && ( {open && (
<> <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="fixed inset-0 z-20" onClick={() => setOpen(false)} /> <div className="flex items-center justify-between px-3 py-2 border-b border-border">
<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="text-sm font-semibold">Notifications</div>
<div className="flex items-center justify-between px-3 py-2 border-b border-border"> {notifications.length > 0 && (
<div className="text-sm font-semibold">Notifications</div> <button
{notifications.length > 0 && ( onClick={clearAll}
<button className="flex items-center gap-1 text-xs text-muted hover:text-accent transition"
onClick={clearAll} title="Clear all"
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
<Trash2 className="w-3.5 h-3.5" /> </button>
Clear )}
</button> </div>
)}
</div>
<div className="overflow-y-auto"> <div className="overflow-y-auto">
{notifications.length === 0 ? ( {notifications.length === 0 ? (
<div className="px-3 py-8 text-center text-sm text-muted"> <div className="px-3 py-8 text-center text-sm text-muted">No notifications yet.</div>
No notifications yet. ) : (
</div> notifications.map((n) => {
) : ( const { icon: Icon, color } = LEVEL_STYLE[n.level];
notifications.map((n) => { const needsAction = n.requiresInteraction && !n.dismissed;
const { icon: Icon, color } = LEVEL_STYLE[n.level]; const hidden = n.meta?.kind === "video-hidden" ? n.meta : null;
const needsAction = n.requiresInteraction && !n.dismissed; return (
return ( <div
<div key={n.id}
key={n.id} className={`flex items-start gap-2.5 px-3 py-2.5 border-b border-border/60 ${
className={`flex items-start gap-2.5 px-3 py-2.5 border-b border-border/60 ${ needsAction ? "bg-accent/5" : ""
needsAction ? "bg-accent/5" : "" }`}
}`} >
> <Icon className={`w-4 h-4 shrink-0 mt-0.5 ${color}`} />
<Icon className={`w-4 h-4 shrink-0 mt-0.5 ${color}`} /> <div className="min-w-0 flex-1">
<div className="min-w-0 flex-1"> {n.title && <div className="text-sm font-semibold">{n.title}</div>}
{n.title && <div className="text-sm font-semibold">{n.title}</div>} <div className="text-sm break-words">{n.message}</div>
<div className="text-sm break-words">{n.message}</div> <div className="flex items-center gap-2 mt-0.5">
<div className="flex items-center gap-2 mt-0.5"> <span className="text-[11px] text-muted">{relTime(n.ts)}</span>
<span className="text-[11px] text-muted">{relTime(n.ts)}</span> {needsAction && (
{needsAction && ( <span className="text-[10px] uppercase tracking-wide font-semibold text-accent">
<span className="text-[10px] uppercase tracking-wide font-semibold text-accent"> Action needed
Action needed </span>
</span> )}
)} </div>
{hidden ? (
<div className="flex items-center gap-3 mt-1">
<button
onClick={() => locateHidden(hidden)}
className="flex items-center gap-1 text-accent text-sm font-semibold hover:underline"
>
<Search className="w-3.5 h-3.5" />
Find in feed
</button>
<button
onClick={() => unhide(hidden)}
className="flex items-center gap-1 text-accent text-sm font-semibold hover:underline"
>
<Eye className="w-3.5 h-3.5" />
Unhide
</button>
</div> </div>
{n.action && !n.dismissed && ( ) : (
n.action &&
!n.dismissed && (
<button <button
onClick={() => { onClick={() => {
n.action!.onClick(); n.action!.onClick();
@ -104,15 +162,15 @@ export default function NotificationCenter() {
> >
{n.action.label} {n.action.label}
</button> </button>
)} )
</div> )}
</div> </div>
); </div>
}) );
)} })
</div> )}
</div> </div>
</> </div>
)} )}
</div> </div>
); );

View file

@ -16,13 +16,13 @@ import {
export const LEVEL_STYLE: Record< export const LEVEL_STYLE: Record<
NotifLevel, NotifLevel,
{ icon: typeof Info; color: string } { icon: typeof Info; color: string; bar: string }
> = { > = {
info: { icon: Info, color: "text-accent" }, info: { icon: Info, color: "text-accent", bar: "bg-accent" },
success: { icon: CheckCircle2, color: "text-emerald-400" }, success: { icon: CheckCircle2, color: "text-emerald-400", bar: "bg-emerald-400" },
warning: { icon: AlertTriangle, color: "text-amber-400" }, warning: { icon: AlertTriangle, color: "text-amber-400", bar: "bg-amber-400" },
error: { icon: AlertCircle, color: "text-red-400" }, error: { icon: AlertCircle, color: "text-red-400", bar: "bg-red-400" },
fatal: { icon: XCircle, color: "text-red-500" }, fatal: { icon: XCircle, color: "text-red-500", bar: "bg-red-500" },
}; };
export default function Toaster() { export default function Toaster() {
@ -31,11 +31,11 @@ export default function Toaster() {
return ( return (
<div className="fixed top-4 right-4 z-50 flex flex-col gap-2 w-80 max-w-[calc(100vw-2rem)]"> <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) => {
const { icon: Icon, color } = LEVEL_STYLE[t.level]; const { icon: Icon, color, bar } = LEVEL_STYLE[t.level];
return ( return (
<div <div
key={t.id} key={t.id}
className="bg-surface border border-border rounded-xl shadow-2xl px-3 py-3 flex items-start gap-3 animate-[fadeIn_0.15s_ease]" className="relative overflow-hidden bg-surface border border-border rounded-xl shadow-2xl px-3 py-3 flex items-start gap-3"
> >
<Icon className={`w-5 h-5 shrink-0 mt-0.5 ${color}`} /> <Icon className={`w-5 h-5 shrink-0 mt-0.5 ${color}`} />
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
@ -60,6 +60,12 @@ export default function Toaster() {
> >
<X className="w-4 h-4" /> <X className="w-4 h-4" />
</button> </button>
{t.duration && (
<div
className={`absolute left-0 bottom-0 h-0.5 w-full origin-left ${bar}`}
style={{ animation: `toastbar ${t.duration}ms linear forwards` }}
/>
)}
</div> </div>
); );
})} })}

View file

@ -115,6 +115,16 @@ html[data-scheme="youtube"][data-theme="light"] {
--accent-fg: #ffffff; --accent-fg: #ffffff;
} }
/* Toast auto-dismiss countdown bar (shrinks left-to-right to zero) */
@keyframes toastbar {
from {
transform: scaleX(1);
}
to {
transform: scaleX(0);
}
}
/* Thin, theme-aware scrollbars */ /* Thin, theme-aware scrollbars */
* { * {
scrollbar-color: var(--border) transparent; scrollbar-color: var(--border) transparent;

View file

@ -10,13 +10,25 @@ export interface NotifAction {
onClick: () => void; onClick: () => void;
} }
// Structured payload that lets the Notification Center offer in-app actions even
// after a reload (when live `action` callbacks are gone).
export type NotifMeta = {
kind: "video-hidden";
videoId: string;
title: string;
channelId: string;
channelName: string;
};
export interface Notification { export interface Notification {
id: number; id: number;
level: NotifLevel; level: NotifLevel;
title?: string; title?: string;
message: string; message: string;
action?: NotifAction; action?: NotifAction;
meta?: NotifMeta;
requiresInteraction: boolean; requiresInteraction: boolean;
duration?: number; // auto-dismiss ms (undefined when it stays until acted on)
ts: number; ts: number;
read: boolean; read: boolean;
dismissed: boolean; // transient toast surface closed (still kept in history) dismissed: boolean; // transient toast surface closed (still kept in history)
@ -27,12 +39,13 @@ export interface NotifyInput {
level?: NotifLevel; level?: NotifLevel;
title?: string; title?: string;
action?: NotifAction; action?: NotifAction;
meta?: NotifMeta;
requiresInteraction?: boolean; requiresInteraction?: boolean;
} }
const HISTORY_KEY = "subfeed.notifications"; const HISTORY_KEY = "subfeed.notifications";
const MAX_HISTORY = 100; const MAX_HISTORY = 100;
const DEFAULT_TTL = 9000; const DEFAULT_TTL = 6000;
const ERROR_TTL = 15000; const ERROR_TTL = 15000;
let items: Notification[] = load(); let items: Notification[] = load();
@ -90,6 +103,11 @@ export function notify(input: NotifyInput): number {
const id = counter++; const id = counter++;
const requiresInteraction = input.requiresInteraction ?? false; const requiresInteraction = input.requiresInteraction ?? false;
const level = input.level ?? "info"; const level = input.level ?? "info";
const duration = requiresInteraction
? undefined
: level === "error" || level === "fatal"
? ERROR_TTL
: DEFAULT_TTL;
items = [ items = [
...items, ...items,
{ {
@ -98,17 +116,16 @@ export function notify(input: NotifyInput): number {
title: input.title, title: input.title,
message: input.message, message: input.message,
action: input.action, action: input.action,
meta: input.meta,
requiresInteraction, requiresInteraction,
duration,
ts: Date.now(), ts: Date.now(),
read: false, read: false,
dismissed: false, dismissed: false,
}, },
]; ];
emit(); emit();
if (!requiresInteraction) { if (duration) setTimeout(() => dismiss(id), duration);
const ttl = level === "error" || level === "fatal" ? ERROR_TTL : DEFAULT_TTL;
setTimeout(() => dismiss(id), ttl);
}
return id; return id;
} }