douyinWEB/frontend/src/components/Toast.tsx
eric 60ea916a4d feat: 全站 H5 响应式导航与可选 PWA 安装
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-14 22:19:06 -05:00

105 lines
3.0 KiB
TypeScript

"use client";
import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from "react";
type ToastTone = "ok" | "warn" | "err";
type ToastItem = {
id: string;
text: string;
tone?: ToastTone;
href?: string;
actionLabel?: string;
onClick?: () => void;
};
type PushOpts = {
href?: string;
actionLabel?: string;
onClick?: () => void;
durationMs?: number;
};
const ToastCtx = createContext<{
push: (text: string, tone?: ToastTone, opts?: PushOpts) => void;
} | null>(null);
export function ToastProvider({ children }: { children: ReactNode }) {
const [items, setItems] = useState<ToastItem[]>([]);
const push = useCallback((text: string, tone: ToastTone = "ok", opts?: PushOpts) => {
const id = `${Date.now()}-${Math.random()}`;
setItems((prev) => [
...prev.slice(-4),
{
id,
text,
tone,
href: opts?.href,
actionLabel: opts?.actionLabel,
onClick: opts?.onClick,
},
]);
window.setTimeout(() => {
setItems((prev) => prev.filter((x) => x.id !== id));
}, opts?.durationMs ?? (opts?.onClick || opts?.href ? 6000 : 3200));
}, []);
const value = useMemo(() => ({ push }), [push]);
return (
<ToastCtx.Provider value={value}>
{children}
<div className="pointer-events-none fixed inset-x-3 bottom-[calc(4.75rem+env(safe-area-inset-bottom))] z-[80] flex flex-col gap-2 md:inset-x-auto md:bottom-4 md:right-4 md:w-[min(92vw,22rem)]">
{items.map((t) => {
const clickable = Boolean(t.onClick || t.href);
const body = (
<>
<div>{t.text}</div>
{clickable ? (
<div className="mt-1 text-[11px] opacity-80">{t.actionLabel || "点击查看 →"}</div>
) : null}
</>
);
const cls = `pointer-events-auto animate-fade-up rounded-xl border px-3 py-2 text-left text-sm shadow-lg backdrop-blur ${
t.tone === "err"
? "border-rose-500/40 bg-rose-500/20 text-rose-50"
: t.tone === "warn"
? "border-amber-500/40 bg-amber-500/20 text-amber-50"
: "border-teal-500/40 bg-teal-500/20 text-teal-50"
} ${clickable ? "cursor-pointer hover:brightness-110" : ""}`;
if (t.href) {
return (
<a key={t.id} href={t.href} className={cls}>
{body}
</a>
);
}
if (t.onClick) {
return (
<button key={t.id} type="button" onClick={t.onClick} className={cls}>
{body}
</button>
);
}
return (
<div key={t.id} className={cls}>
{body}
</div>
);
})}
</div>
</ToastCtx.Provider>
);
}
export function useToast() {
const ctx = useContext(ToastCtx);
if (!ctx) {
return {
push: (_t: string, _tone?: ToastTone, _opts?: PushOpts) => undefined,
};
}
return ctx;
}