headplane/app/components/Toaster.tsx

92 lines
2 KiB
TypeScript
Raw Normal View History

2024-12-31 10:30:14 +05:30
import { XIcon } from '@primer/octicons-react';
import {
AriaToastProps,
useToast,
useToastRegion,
} from '@react-aria/toast';
import {
ToastQueue,
ToastState,
useToastQueue,
} from '@react-stately/toast';
import { ReactNode, useRef } from 'react';
2024-12-31 10:30:14 +05:30
import { Button } from 'react-aria-components';
import { createPortal } from 'react-dom';
import { ClientOnly } from 'remix-utils/client-only';
import { cn } from '~/utils/cn';
2024-03-25 18:47:15 -04:00
2024-12-31 10:30:14 +05:30
type ToastProps = AriaToastProps<ReactNode> & {
readonly state: ToastState<ReactNode>;
2024-12-31 10:30:14 +05:30
};
2024-12-31 10:30:14 +05:30
function Toast({ state, ...properties }: ToastProps) {
const reference = useRef(null);
2024-12-31 10:30:14 +05:30
const { toastProps, titleProps, closeButtonProps } = useToast(
properties,
state,
reference,
);
2024-03-25 18:47:15 -04:00
return (
<div
{...toastProps}
ref={reference}
className={cn(
'bg-main-700 dark:bg-main-800 rounded-lg',
'text-main-100 dark:text-main-200 z-50',
'border border-main-600 dark:border-main-700',
2024-12-31 10:30:14 +05:30
'flex items-center justify-between p-3 pl-4 w-80',
)}
2024-03-25 18:47:15 -04:00
>
<div {...titleProps}>{properties.toast.content}</div>
<Button
{...closeButtonProps}
className={cn(
'outline-none rounded-full p-1',
2024-12-31 10:30:14 +05:30
'hover:bg-main-600 dark:hover:bg-main-700',
)}
>
2024-12-31 10:30:14 +05:30
<XIcon className="w-4 h-4" />
</Button>
</div>
2024-12-31 10:30:14 +05:30
);
}
const toasts = new ToastQueue<ReactNode>({
2024-12-31 10:30:14 +05:30
maxVisibleToasts: 5,
});
export function toast(text: string) {
2024-12-31 10:30:14 +05:30
return toasts.add(text, { timeout: 5000 });
}
export function Toaster() {
2024-12-31 10:30:14 +05:30
const reference = useRef(null);
const state = useToastQueue(toasts);
2024-12-31 10:30:14 +05:30
const { regionProps } = useToastRegion({}, state, reference);
return (
<ClientOnly>
{
2024-12-31 10:30:14 +05:30
() =>
createPortal(
state.visibleToasts.length >= 0 ? (
<div
2025-01-06 08:35:25 +05:30
className={cn('fixed bottom-20 right-4', 'flex flex-col gap-4')}
2024-12-31 10:30:14 +05:30
{...regionProps}
ref={reference}
>
{state.visibleToasts.map((toast) => (
<Toast key={toast.key} toast={toast} state={state} />
))}
</div>
) : undefined,
document.body,
)
}
</ClientOnly>
2024-12-31 10:30:14 +05:30
);
2024-03-25 18:47:15 -04:00
}