chatbot-template/components/toast.tsx

76 lines
1.9 KiB
TypeScript
Raw Normal View History

"use client";
2025-03-04 17:25:46 -08:00
import { type ReactNode, useEffect, useRef, useState } from "react";
import { toast as sonnerToast } from "sonner";
import { cn } from "@/lib/utils";
import { CheckCircleFillIcon, WarningIcon } from "./icons";
2025-03-04 17:25:46 -08:00
const iconsByType: Record<"success" | "error", ReactNode> = {
2025-03-04 17:25:46 -08:00
success: <CheckCircleFillIcon />,
error: <WarningIcon />,
};
export function toast(props: Omit<ToastProps, "id">) {
2025-03-04 17:25:46 -08:00
return sonnerToast.custom((id) => (
<Toast description={props.description} id={id} type={props.type} />
2025-03-04 17:25:46 -08:00
));
}
function Toast(props: ToastProps) {
const { id, type, description } = props;
2025-04-25 23:40:15 -07:00
const descriptionRef = useRef<HTMLDivElement>(null);
const [multiLine, setMultiLine] = useState(false);
useEffect(() => {
const el = descriptionRef.current;
if (!el) {
return;
}
2025-04-25 23:40:15 -07:00
const update = () => {
const lineHeight = Number.parseFloat(getComputedStyle(el).lineHeight);
const lines = Math.round(el.scrollHeight / lineHeight);
setMultiLine(lines > 1);
};
update(); // initial check
const ro = new ResizeObserver(update); // re-check on width changes
ro.observe(el);
return () => ro.disconnect();
}, []);
2025-04-25 23:40:15 -07:00
2025-03-04 17:25:46 -08:00
return (
2025-09-09 15:44:07 -04:00
<div className="flex toast-mobile:w-[356px] w-full justify-center">
2025-03-04 17:25:46 -08:00
<div
className={cn(
"flex toast-mobile:w-fit w-full flex-row gap-3 rounded-lg bg-zinc-100 p-3",
multiLine ? "items-start" : "items-center"
)}
data-testid="toast"
key={id}
2025-03-04 17:25:46 -08:00
>
<div
2025-04-25 23:40:15 -07:00
className={cn(
"data-[type=error]:text-red-600 data-[type=success]:text-green-600",
{ "pt-1": multiLine }
2025-04-25 23:40:15 -07:00
)}
data-type={type}
2025-03-04 17:25:46 -08:00
>
{iconsByType[type]}
</div>
<div className="text-sm text-zinc-950" ref={descriptionRef}>
2025-04-25 23:40:15 -07:00
{description}
</div>
2025-03-04 17:25:46 -08:00
</div>
</div>
);
}
type ToastProps = {
2025-03-04 17:25:46 -08:00
id: string | number;
type: "success" | "error";
2025-03-04 17:25:46 -08:00
description: string;
};