跳至正文
获取 Pro
基础原语U.34

全局通知

FreeRegistry
components/linyi/toast.tsx
@base-ui/reactclass-variance-authoritylucide-react
"use client";
 
import * as React from "react";
import { Toast as BaseToast } from "@base-ui/react/toast";
import { cva, type VariantProps } from "class-variance-authority";
import {
AlertCircle,
AlertTriangle,
CheckCircle2,
Info,
Loader2,
X,
} from "lucide-react";
import { cn } from "@/lib/cn";
import { playSound } from "@/lib/sound";
 
export type ToastTone =
| "default"
| "success"
| "error"
| "warning"
| "info"
| "loading";
 
export type ToastPosition =
| "bottom-right"
| "bottom-center"
| "top-right"
| "top-center";
 
export interface ToastCustomData {
sound?: boolean;
}
 
export interface ToastOptions {
id?: string;
title?: React.ReactNode;
description?: React.ReactNode;
type?: ToastTone;
timeout?: number;
priority?: "low" | "high";
sound?: boolean;
action?: {
label: string;
onClick: () => void;
};
onClose?: () => void;
onRemove?: () => void;
}
 
export interface ToastPromiseMessages<Value> {
loading: React.ReactNode | ToastOptions;
success:
| React.ReactNode
| ToastOptions
| ((value: Value) => React.ReactNode | ToastOptions);
error:
| React.ReactNode
| ToastOptions
| ((err: unknown) => React.ReactNode | ToastOptions);
}
 
export const toastItemVariants = cva(
[
"group pointer-events-auto relative w-full select-none rounded-[14px] border bg-surface/96 px-3.5 py-3 text-fg shadow-popover backdrop-blur-md outline-none",
"focus-visible:ring-2 focus-visible:ring-accent/35",
].join(" "),
{
variants: {
tone: {
default: "border-line-strong",
success: "border-success-border",
error: "border-danger-border",
warning: "border-warning-border",
info: "border-info-border",
loading: "border-line-strong",
},
},
defaultVariants: {
tone: "default",
},
}
);
 
export const toasterViewportVariants = cva(
"fixed z-[var(--z-toast)] pointer-events-none flex w-[min(calc(100vw-24px),360px)] outline-none",
{
variants: {
position: {
"bottom-right":
"right-4 bottom-[max(1rem,env(safe-area-inset-bottom))] flex-col",
"bottom-center":
"left-1/2 -translate-x-1/2 bottom-[max(1rem,env(safe-area-inset-bottom))] flex-col",
"top-right":
"right-4 top-[max(1rem,env(safe-area-inset-top))] flex-col",
"top-center":
"left-1/2 -translate-x-1/2 top-[max(1rem,env(safe-area-inset-top))] flex-col",
},
},
defaultVariants: {
position: "bottom-right",
},
}
);
 
function normalizeToastInput(
input: React.ReactNode | ToastOptions,
extra?: Partial<ToastOptions>
): ToastOptions {
if (
input !== null &&
typeof input === "object" &&
!React.isValidElement(input) &&
("title" in input || "description" in input || "type" in input)
) {
return { ...(input as ToastOptions), ...extra };
}
return { title: input as React.ReactNode, ...extra };
}
 
function triggerToneSound(tone: ToastTone | undefined, enabled?: boolean) {
if (enabled === false) return;
if (tone === "success") {
playSound("success", { volume: 0.4 });
} else if (tone === "error" || tone === "warning") {
playSound("tap", { pitch: 0.85, volume: 0.45 });
} else if (tone !== "loading") {
playSound("bubble", { volume: 0.35 });
}
}
 
export function createToastController() {
const manager = BaseToast.createToastManager<ToastCustomData>();
 
const dispatch = (
input: React.ReactNode | ToastOptions,
extra?: Partial<ToastOptions>
) => {
const opts = normalizeToastInput(input, extra);
const tone: ToastTone = opts.type ?? "default";
triggerToneSound(tone, opts.sound);
return manager.add({
id: opts.id,
title: opts.title,
description: opts.description,
type: tone,
timeout: opts.timeout,
priority: opts.priority ?? (tone === "error" ? "high" : "low"),
onClose: opts.onClose,
onRemove: opts.onRemove,
data: { sound: opts.sound },
actionProps: opts.action
? {
children: opts.action.label,
onClick: opts.action.onClick,
}
: undefined,
});
};
 
const api = Object.assign(dispatch, {
manager,
success: (title: React.ReactNode, opts?: Omit<ToastOptions, "title" | "type">) =>
dispatch(title, { ...opts, type: "success" }),
error: (title: React.ReactNode, opts?: Omit<ToastOptions, "title" | "type">) =>
dispatch(title, { ...opts, type: "error", priority: opts?.priority ?? "high" }),
warning: (title: React.ReactNode, opts?: Omit<ToastOptions, "title" | "type">) =>
dispatch(title, { ...opts, type: "warning" }),
info: (title: React.ReactNode, opts?: Omit<ToastOptions, "title" | "type">) =>
dispatch(title, { ...opts, type: "info" }),
loading: (title: React.ReactNode, opts?: Omit<ToastOptions, "title" | "type">) =>
dispatch(title, { ...opts, type: "loading", timeout: opts?.timeout ?? 0 }),
dismiss: (id?: string) => manager.close(id),
update: (id: string, opts: ToastOptions) =>
manager.update(id, {
title: opts.title,
description: opts.description,
type: opts.type,
timeout: opts.timeout,
priority: opts.priority,
actionProps: opts.action
? {
children: opts.action.label,
onClick: opts.action.onClick,
}
: undefined,
}),
promise: <Value,>(
promiseValue: Promise<Value>,
messages: ToastPromiseMessages<Value>
): Promise<Value> => {
const loadingOpts = normalizeToastInput(messages.loading, {
type: "loading",
timeout: 0,
});
 
return manager.promise<Value, ToastCustomData>(promiseValue, {
loading: {
title: loadingOpts.title,
description: loadingOpts.description,
type: "loading",
timeout: 0,
},
success: (result) => {
const raw =
typeof messages.success === "function"
? messages.success(result)
: messages.success;
const opts = normalizeToastInput(raw, { type: "success" });
triggerToneSound("success", opts.sound);
return {
title: opts.title,
description: opts.description,
type: "success",
timeout: opts.timeout ?? 4200,
};
},
error: (err) => {
const raw =
typeof messages.error === "function"
? messages.error(err)
: messages.error;
const opts = normalizeToastInput(raw, { type: "error" });
triggerToneSound("error", opts.sound);
return {
title: opts.title,
description: opts.description,
type: "error",
priority: "high",
timeout: opts.timeout ?? 5200,
};
},
});
},
});
 
return api;
}
 
export const toast = createToastController();
export const globalToastManager = toast.manager;
 
function ToastToneIcon({ tone }: { tone: ToastTone }) {
switch (tone) {
case "success":
return (
<CheckCircle2
className="mt-0.5 h-4 w-4 flex-shrink-0 text-success"
aria-hidden="true"
/>
);
case "error":
return (
<AlertCircle
className="mt-0.5 h-4 w-4 flex-shrink-0 text-danger"
aria-hidden="true"
/>
);
case "warning":
return (
<AlertTriangle
className="mt-0.5 h-4 w-4 flex-shrink-0 text-warning"
aria-hidden="true"
/>
);
case "info":
return (
<Info
className="mt-0.5 h-4 w-4 flex-shrink-0 text-info"
aria-hidden="true"
/>
);
case "loading":
return (
<Loader2
className="mt-0.5 h-4 w-4 flex-shrink-0 animate-spin text-accent"
aria-hidden="true"
/>
);
default:
return (
<span
className="mt-1.5 h-2 w-2 flex-shrink-0 rounded-full bg-accent"
aria-hidden="true"
/>
);
}
}
 
function ToastList({ position }: { position: ToastPosition }) {
const { toasts } = BaseToast.useToastManager<ToastCustomData>();
const isTop = position.startsWith("top");
const swipeDirections: ("up" | "down" | "right")[] = isTop
? ["up", "right"]
: ["down", "right"];
 
return (
<>
{toasts.map((item) => {
const tone = (item.type as ToastTone) ?? "default";
return (
<BaseToast.Root
key={item.id}
toast={item}
swipeDirection={swipeDirections}
style={
{
"--gap": "10px",
"--peek": "10px",
"--scale": "calc(max(0, 1 - (var(--toast-index) * 0.05)))",
"--shrink": "calc(1 - var(--scale))",
"--height": "var(--toast-frontmost-height, var(--toast-height))",
"--offset-y": isTop
? "calc(var(--toast-offset-y) + (var(--toast-index) * var(--gap)) + var(--toast-swipe-movement-y))"
: "calc(var(--toast-offset-y) * -1 + (var(--toast-index) * var(--gap) * -1) + var(--toast-swipe-movement-y))",
} as React.CSSProperties
}
className={cn(
toastItemVariants({ tone }),
"absolute left-0 right-0 z-[calc(1000-var(--toast-index))]",
isTop ? "top-0 origin-top" : "bottom-0 origin-bottom",
"transition-[transform,opacity,height] duration-300 ease-[cubic-bezier(0.16,1,0.3,1)] motion-reduce:transition-none",
// Collapsed stack transforms
isTop
? "[transform:translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)+(var(--toast-index)*var(--peek))+(var(--shrink)*var(--height))))_scale(var(--scale))]"
: "[transform:translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)-(var(--toast-index)*var(--peek))-(var(--shrink)*var(--height))))_scale(var(--scale))]",
// Expanded transforms on hover/focus
"data-[expanded]:[transform:translateX(var(--toast-swipe-movement-x))_translateY(var(--offset-y))]",
// Starting / ending / limited transitions
isTop
? "data-[starting-style]:opacity-0 data-[starting-style]:[transform:translateY(-120%)]"
: "data-[starting-style]:opacity-0 data-[starting-style]:[transform:translateY(120%)]",
"data-[ending-style]:opacity-0 data-[ending-style]:[transform:translateX(calc(var(--toast-swipe-movement-x)+48px))_translateY(var(--offset-y))]",
"data-[limited]:opacity-0 data-[limited]:pointer-events-none",
"data-[swiping]:transition-none"
)}
>
<BaseToast.Content className="flex items-start gap-2.5 transition-opacity duration-200 data-[behind]:opacity-0 data-[expanded]:opacity-100">
<ToastToneIcon tone={tone} />
<div className="min-w-0 flex-1">
{item.title && (
<BaseToast.Title className="text-xs font-medium leading-snug text-fg">
{item.title}
</BaseToast.Title>
)}
{item.description && (
<BaseToast.Description className="mt-0.5 text-[11px] leading-relaxed text-fg-secondary">
{item.description}
</BaseToast.Description>
)}
{item.actionProps && (
<BaseToast.Action className="mt-2 inline-flex h-6 items-center rounded-[7px] border border-line-strong bg-surface-2 px-2 text-[11px] font-medium text-fg transition-colors cursor-pointer hover:bg-surface-hover" />
)}
</div>
<BaseToast.Close
aria-label="关闭通知"
className="inline-flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-[6px] text-fg-muted transition-colors cursor-pointer hover:bg-well hover:text-fg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/30"
>
<X className="h-3.5 w-3.5" aria-hidden="true" />
</BaseToast.Close>
</BaseToast.Content>
</BaseToast.Root>
);
})}
</>
);
}
 
export interface ToasterProps
extends VariantProps<typeof toasterViewportVariants> {
position?: ToastPosition;
timeout?: number;
limit?: number;
toastManager?: ReturnType<typeof BaseToast.createToastManager<ToastCustomData>>;
className?: string;
}
 
export function Toaster({
position = "bottom-right",
timeout = 4500,
limit = 4,
toastManager = globalToastManager,
className,
}: ToasterProps) {
return (
<BaseToast.Provider
toastManager={toastManager}
timeout={timeout}
limit={limit}
>
<BaseToast.Portal>
<BaseToast.Viewport
aria-label="全局通知列表"
className={cn(toasterViewportVariants({ position }), className)}
>
<ToastList position={position} />
</BaseToast.Viewport>
</BaseToast.Portal>
</BaseToast.Provider>
);
}