medkit/src/kit/notify.tsx

121 lines
4.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {
ArrowRightIcon,
CircleCheckIcon,
InfoIcon,
OctagonXIcon,
TriangleAlertIcon,
XIcon,
type LucideIcon,
} from "lucide-react"
import * as React from "react"
import { toast, Toaster } from "sonner"
import { cn } from "../lib/utils"
export type NotifyType = "success" | "info" | "warning" | "error"
const TOASTER_ID = "notify"
/** Переход по href из карточки; без роутера — обычная навигация браузера. */
const NavigateContext = React.createContext<(href: string) => void>((href) => window.location.assign(href))
const typeMeta: Record<NotifyType, { icon: LucideIcon; tile: string; bar: string; duration: number }> = {
success: { icon: CircleCheckIcon, tile: "bg-success-soft text-success", bar: "bg-success", duration: 5000 },
info: { icon: InfoIcon, tile: "bg-info-soft text-info", bar: "bg-info", duration: 6000 },
warning: { icon: TriangleAlertIcon, tile: "bg-warning-soft text-warning", bar: "bg-warning", duration: 8000 },
error: { icon: OctagonXIcon, tile: "bg-coral-soft text-coral", bar: "bg-coral", duration: 10000 },
}
export interface NotifyOptions {
type?: NotifyType
title: string
description?: React.ReactNode
/** Маршрут для кнопки «Перейти». */
href?: string
/** Текст кнопки перехода, по умолчанию «Перейти». */
actionLabel?: string
/** Мс до автозакрытия; Infinity — висит до закрытия руками. */
duration?: number
}
/** Всплывающее уведомление справа сверху. Возвращает id для notify.dismiss(id). */
export function notify({ type = "info", duration, ...rest }: NotifyOptions) {
return toast.custom((id) => <NotifyCard id={id} type={type} {...rest} />, {
toasterId: TOASTER_ID,
duration: duration ?? typeMeta[type].duration,
})
}
notify.success = (o: Omit<NotifyOptions, "type">) => notify({ ...o, type: "success" })
notify.info = (o: Omit<NotifyOptions, "type">) => notify({ ...o, type: "info" })
notify.warning = (o: Omit<NotifyOptions, "type">) => notify({ ...o, type: "warning" })
notify.error = (o: Omit<NotifyOptions, "type">) => notify({ ...o, type: "error" })
notify.dismiss = (id?: string | number) => toast.dismiss(id)
/**
* Контейнер уведомлений, монтируется один раз. `navigate` — переход для кнопки «Перейти»
* (с react-router: `useNavigate()`), по умолчанию `window.location.assign`.
*/
export function NotifyToaster({ navigate }: { navigate?: (href: string) => void }) {
const toaster = (
<Toaster
id={TOASTER_ID}
position="top-right"
visibleToasts={5}
gap={10}
offset={{ top: 64, right: 16 }}
toastOptions={{ unstyled: true, className: "w-full" }}
/>
)
return navigate ? <NavigateContext.Provider value={navigate}>{toaster}</NavigateContext.Provider> : toaster
}
function NotifyCard({
id,
type,
title,
description,
href,
actionLabel = "Перейти",
}: Omit<NotifyOptions, "duration"> & { id: string | number; type: NotifyType }) {
const navigate = React.useContext(NavigateContext)
const { icon: Icon, tile, bar } = typeMeta[type]
return (
<div
role={type === "error" ? "alert" : "status"}
className="relative flex w-[356px] max-w-[calc(100vw-2rem)] gap-3 overflow-hidden rounded-xl border bg-popover p-3 pl-4 text-popover-foreground shadow-lg"
>
<span className={cn("absolute inset-y-0 left-0 w-1", bar)} />
<div className={cn("grid size-8 shrink-0 place-items-center rounded-lg", tile)}>
<Icon className="size-4" />
</div>
<div className="min-w-0 flex-1 pt-0.5">
<div className="text-sm font-semibold leading-snug">{title}</div>
{description && <div className="mt-0.5 text-sm text-muted-foreground">{description}</div>}
{href && (
<button
type="button"
onClick={() => {
navigate(href)
toast.dismiss(id)
}}
className="mt-2 inline-flex items-center gap-1 text-sm font-medium text-primary hover:underline"
>
{actionLabel}
<ArrowRightIcon className="size-3.5" />
</button>
)}
</div>
<button
type="button"
aria-label="Закрыть"
onClick={() => toast.dismiss(id)}
className="-mt-0.5 -mr-0.5 grid size-6 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground"
>
<XIcon className="size-4" />
</button>
</div>
)
}