chatbot-template/components/toast.tsx

74 lines
2 KiB
TypeScript
Raw Normal View History

'use client';
2025-03-04 17:25:46 -08:00
import React, { useEffect, useRef, useState, type ReactNode } from 'react';
import { toast as sonnerToast } from 'sonner';
import { CheckCircleFillIcon, WarningIcon } from './icons';
import { cn } from '@/lib/utils';
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 id={id} type={props.type} description={props.description} />
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();
}, [description]);
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
data-testid="toast"
key={id}
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',
)}
2025-03-04 17:25:46 -08:00
>
<div
data-type={type}
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
)}
2025-03-04 17:25:46 -08:00
>
{iconsByType[type]}
</div>
<div ref={descriptionRef} className="text-sm text-zinc-950">
2025-04-25 23:40:15 -07:00
{description}
</div>
2025-03-04 17:25:46 -08:00
</div>
</div>
);
}
interface 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;
}