fix(webui): confirm linked automation deletion in untimed toast (#6731)
* fix(webui): confirm linked automation deletion in untimed toast * feat(webui): add linked automation dropdown and session exclude in delete toast * style(webui): align toast automation dropdown and refine visual polish
This commit is contained in:
1 parent
7935176eb7
commit
cb95277098
31 files changed
+652
-668
No files matched your search
@@ -0,0 +1,139 @@
|
||||
import type { TFunction } from "i18next";
|
||||
import { MessageSquare } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { currentLocale } from "@/i18n";
|
||||
import { fmtDateTime } from "@/lib/format-time";
|
||||
import type { SessionAutomationJob } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { SidebarDeleteItem } from "@/components/ChatList";
|
||||
|
||||
export interface AutomationDeleteSessionGroup {
|
||||
item: SidebarDeleteItem;
|
||||
jobs: SessionAutomationJob[];
|
||||
}
|
||||
|
||||
export function AutomationDeleteToastDetails({
|
||||
groups,
|
||||
onExcludeSession,
|
||||
}: {
|
||||
groups: AutomationDeleteSessionGroup[];
|
||||
onExcludeSession: (key: string) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const locale = currentLocale();
|
||||
|
||||
return (
|
||||
<div className="max-h-64 divide-y divide-border/60 overflow-y-auto overscroll-contain">
|
||||
{groups.map(({ item, jobs }) => (
|
||||
<section key={item.key} className="px-3.5 py-2.5">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<MessageSquare
|
||||
aria-hidden="true"
|
||||
className="h-3.5 w-3.5 shrink-0 text-muted-foreground/80"
|
||||
strokeWidth={1.8}
|
||||
/>
|
||||
<span className="min-w-0 truncate text-[13px] font-medium leading-5 text-foreground">
|
||||
{item.label}
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
aria-label={t("toast.excludeSessionAria", { title: item.label })}
|
||||
onClick={() => onExcludeSession(item.key)}
|
||||
className="h-6 shrink-0 rounded-full border border-border/70 bg-background/70 px-2.5 text-[11.5px] font-medium leading-4 text-muted-foreground transition-colors hover:border-border hover:bg-muted/75 hover:text-foreground"
|
||||
>
|
||||
{t("toast.excludeSession")}
|
||||
</Button>
|
||||
</div>
|
||||
<ul className="mt-1.5 space-y-0.5 pl-[1.375rem]">
|
||||
{jobs.map((job) => {
|
||||
const needsAttention = job.state.last_status === "error" || Boolean(job.state.last_error);
|
||||
const statusDotClass = job.enabled
|
||||
? needsAttention
|
||||
? "bg-destructive"
|
||||
: "bg-emerald-500"
|
||||
: "bg-muted-foreground/35";
|
||||
return (
|
||||
<li
|
||||
key={job.id}
|
||||
className="flex items-center justify-between gap-3 rounded-lg px-2 py-1 text-[12.5px] leading-5 transition-colors hover:bg-muted/45"
|
||||
>
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={cn("h-1.5 w-1.5 shrink-0 rounded-full", statusDotClass)}
|
||||
/>
|
||||
<span className="min-w-0 truncate text-foreground/90">
|
||||
{job.name || job.id}
|
||||
</span>
|
||||
</div>
|
||||
{!job.enabled ? (
|
||||
<span className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-[11px] font-medium leading-4 text-muted-foreground">
|
||||
{t("settings.automations.status.paused")}
|
||||
</span>
|
||||
) : (
|
||||
<span className="shrink-0 text-[11.5px] leading-4 tabular-nums text-muted-foreground">
|
||||
{formatCompactSchedule(job, locale, t)}
|
||||
</span>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function formatCompactSchedule(
|
||||
job: SessionAutomationJob,
|
||||
locale: string,
|
||||
t: TFunction,
|
||||
): string {
|
||||
if (job.schedule.kind === "at" && job.schedule.at_ms) {
|
||||
return t("settings.automations.schedule.at", { time: fmtDateTime(job.schedule.at_ms, locale) });
|
||||
}
|
||||
if (job.schedule.kind === "every" && job.schedule.every_ms) {
|
||||
return t("settings.automations.schedule.every", {
|
||||
duration: formatDuration(job.schedule.every_ms, locale),
|
||||
});
|
||||
}
|
||||
if (job.schedule.kind === "cron" && job.schedule.expr) {
|
||||
return job.schedule.expr;
|
||||
}
|
||||
if (job.kind === "local_trigger" || job.schedule.kind === "local" || job.payload.kind === "local_trigger") {
|
||||
return t("settings.automations.commandCondition");
|
||||
}
|
||||
return t("settings.automations.schedule.custom");
|
||||
}
|
||||
|
||||
function formatDuration(ms: number, locale: string): string {
|
||||
const units: Array<[Intl.NumberFormatOptions["unit"], number]> = [
|
||||
["day", 86_400_000],
|
||||
["hour", 3_600_000],
|
||||
["minute", 60_000],
|
||||
["second", 1000],
|
||||
];
|
||||
for (const [unit, size] of units) {
|
||||
if (ms >= size && ms % size === 0) {
|
||||
return new Intl.NumberFormat(locale, {
|
||||
style: "unit",
|
||||
unit,
|
||||
unitDisplay: "long",
|
||||
maximumFractionDigits: 0,
|
||||
}).format(ms / size);
|
||||
}
|
||||
}
|
||||
return new Intl.NumberFormat(locale, {
|
||||
style: "unit",
|
||||
unit: "minute",
|
||||
unitDisplay: "long",
|
||||
maximumFractionDigits: 1,
|
||||
}).format(ms / 60_000);
|
||||
}
|
||||
@@ -1,173 +0,0 @@
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import type { TFunction } from "i18next";
|
||||
import { Trash2 } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { currentLocale } from "@/i18n";
|
||||
import { fmtDateTime } from "@/lib/format-time";
|
||||
import type { SessionAutomationJob } from "@/lib/types";
|
||||
|
||||
interface DeleteConfirmProps {
|
||||
open: boolean;
|
||||
title: string;
|
||||
count?: number;
|
||||
automations: SessionAutomationJob[];
|
||||
onCancel: () => void;
|
||||
onConfirm: () => void;
|
||||
}
|
||||
|
||||
export function DeleteConfirm({
|
||||
open,
|
||||
title,
|
||||
count = 1,
|
||||
automations,
|
||||
onCancel,
|
||||
onConfirm,
|
||||
}: DeleteConfirmProps) {
|
||||
const { t } = useTranslation();
|
||||
const locale = currentLocale();
|
||||
const multiple = count > 1;
|
||||
const visibleAutomations = automations.slice(0, 4);
|
||||
const hiddenCount = Math.max(0, automations.length - visibleAutomations.length);
|
||||
return (
|
||||
<AlertDialog open={open} onOpenChange={(o) => (!o ? onCancel() : undefined)}>
|
||||
<AlertDialogContent
|
||||
className="w-[min(calc(100vw-2rem),24rem)] gap-0 p-5 text-center"
|
||||
onEscapeKeyDown={(event) => event.stopPropagation()}
|
||||
>
|
||||
<AlertDialogHeader className="items-center space-y-0 text-center">
|
||||
<Trash2
|
||||
className="mb-4 h-6 w-6 text-destructive"
|
||||
strokeWidth={1.8}
|
||||
aria-hidden
|
||||
/>
|
||||
<AlertDialogTitle className="text-center text-[20px] font-semibold leading-tight tracking-[-0.02em] text-foreground">
|
||||
{multiple
|
||||
? t("deleteConfirm.titleMany", {
|
||||
defaultValue: "Delete {{count}} conversations?",
|
||||
count,
|
||||
})
|
||||
: t("deleteConfirm.title", { title })}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription className="mt-3 max-w-[17rem] text-center text-[14px] leading-6 text-muted-foreground">
|
||||
{multiple
|
||||
? t("deleteConfirm.automationsDescriptionMany", {
|
||||
defaultValue: "Linked automations will also be deleted.",
|
||||
})
|
||||
: t("deleteConfirm.automationsDescription")}
|
||||
</AlertDialogDescription>
|
||||
<div className="mt-4 max-h-40 w-full overflow-y-auto rounded-2xl bg-muted/55 px-3 py-2 text-left">
|
||||
{visibleAutomations.map((job) => (
|
||||
<div key={job.id} className="min-w-0 py-1.5">
|
||||
<div className="truncate text-[13px] font-medium leading-5 text-foreground">
|
||||
{job.name || job.id}
|
||||
</div>
|
||||
<div className="mt-0.5 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5 text-[11.5px] leading-5 text-muted-foreground">
|
||||
<span className="truncate">
|
||||
{formatAutomationSchedule(job, t, locale)}
|
||||
</span>
|
||||
<span className="truncate">{formatAutomationNextRun(job, t, locale)}</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{hiddenCount > 0 ? (
|
||||
<div className="text-[13px] leading-6 text-muted-foreground">
|
||||
{t("deleteConfirm.moreAutomations", {
|
||||
count: hiddenCount,
|
||||
})}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter className="mt-6 !grid grid-cols-1 gap-2 sm:grid-cols-2">
|
||||
<AlertDialogCancel
|
||||
onClick={onCancel}
|
||||
className="mt-0 w-full min-w-0"
|
||||
>
|
||||
{t("deleteConfirm.cancel")}
|
||||
</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={onConfirm}
|
||||
className="w-full min-w-0 !whitespace-normal bg-destructive text-center text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{t("deleteConfirm.confirm")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
|
||||
function formatAutomationSchedule(
|
||||
job: SessionAutomationJob,
|
||||
t: TFunction,
|
||||
locale: string,
|
||||
): string {
|
||||
if (job.schedule.kind === "at" && job.schedule.at_ms) {
|
||||
return t("deleteConfirm.schedule.at", { time: fmtDateTime(job.schedule.at_ms, locale) });
|
||||
}
|
||||
if (job.schedule.kind === "every" && job.schedule.every_ms) {
|
||||
return t("deleteConfirm.schedule.every", {
|
||||
duration: formatDuration(job.schedule.every_ms, locale),
|
||||
});
|
||||
}
|
||||
if (job.schedule.kind === "cron" && job.schedule.expr) {
|
||||
return job.schedule.tz
|
||||
? t("deleteConfirm.schedule.cronWithTz", {
|
||||
expr: job.schedule.expr,
|
||||
tz: job.schedule.tz,
|
||||
})
|
||||
: t("deleteConfirm.schedule.cron", { expr: job.schedule.expr });
|
||||
}
|
||||
if (job.schedule.kind === "local" || job.payload.kind === "local_trigger") {
|
||||
return t("deleteConfirm.schedule.local", { defaultValue: "Local trigger" });
|
||||
}
|
||||
return t("deleteConfirm.schedule.unknown");
|
||||
}
|
||||
|
||||
function formatAutomationNextRun(
|
||||
job: SessionAutomationJob,
|
||||
t: TFunction,
|
||||
locale: string,
|
||||
): string {
|
||||
if (!job.enabled) return t("deleteConfirm.next.disabled");
|
||||
if (job.schedule.kind === "local" || job.payload.kind === "local_trigger") {
|
||||
return t("deleteConfirm.next.local", { defaultValue: "Waiting for trigger" });
|
||||
}
|
||||
const next = job.state.next_run_at_ms;
|
||||
if (!next) return t("deleteConfirm.next.none");
|
||||
return t("deleteConfirm.next.label", { time: fmtDateTime(next, locale) });
|
||||
}
|
||||
|
||||
function formatDuration(ms: number, locale: string): string {
|
||||
const units: Array<[Intl.NumberFormatOptions["unit"], number]> = [
|
||||
["day", 86_400_000],
|
||||
["hour", 3_600_000],
|
||||
["minute", 60_000],
|
||||
["second", 1000],
|
||||
];
|
||||
for (const [unit, size] of units) {
|
||||
if (ms >= size && ms % size === 0) {
|
||||
return new Intl.NumberFormat(locale, {
|
||||
style: "unit",
|
||||
unit,
|
||||
unitDisplay: "long",
|
||||
maximumFractionDigits: 0,
|
||||
}).format(ms / size);
|
||||
}
|
||||
}
|
||||
return new Intl.NumberFormat(locale, {
|
||||
style: "unit",
|
||||
unit: "minute",
|
||||
unitDisplay: "long",
|
||||
maximumFractionDigits: 1,
|
||||
}).format(ms / 60_000);
|
||||
}
|
||||
@@ -71,7 +71,7 @@ export function RenameDialog({
|
||||
variant="outline"
|
||||
onClick={onCancel}
|
||||
>
|
||||
{t("deleteConfirm.cancel")}
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button className="min-w-20" type="submit" disabled={!trimmed}>
|
||||
{t("chat.renameSave")}
|
||||
|
||||
@@ -97,7 +97,7 @@ export function SidebarTopicRename({ title, onSave, onClose }: SidebarTopicRenam
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("deleteConfirm.cancel")}
|
||||
aria-label={t("common.cancel")}
|
||||
disabled={saving}
|
||||
onClick={onClose}
|
||||
className="touch-target inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-sidebar-muted-foreground disabled:opacity-40"
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
box-shadow: 0 1px 2px rgb(0 0 0 / 0.18), 0 8px 24px -8px rgb(0 0 0 / 0.45);
|
||||
}
|
||||
|
||||
.toast-card::before {
|
||||
.toast-card[data-toast-timed="true"]::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
z-index: -1;
|
||||
@@ -26,7 +26,7 @@
|
||||
animation-play-state: var(--toast-play-state);
|
||||
}
|
||||
|
||||
.toast-card:dir(rtl)::before {
|
||||
.toast-card[data-toast-timed="true"]:dir(rtl)::before {
|
||||
--toast-sweep-direction: to left;
|
||||
animation-direction: reverse;
|
||||
}
|
||||
|
||||
@@ -1,18 +1,36 @@
|
||||
import { Check, Trash2, TriangleAlert } from "lucide-react";
|
||||
import { createContext, useCallback, useContext, useLayoutEffect, useRef, useState, type CSSProperties, type ReactNode, type Ref } from "react";
|
||||
import { Check, ChevronDown, Trash2, TriangleAlert } from "lucide-react";
|
||||
import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode, type Ref } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
import "./toast.css";
|
||||
|
||||
const TOAST_NOTICE_MS = 3_000;
|
||||
export const TOAST_ACTION_MS = 8_000;
|
||||
|
||||
type ToastNotice = {
|
||||
export type ToastController = {
|
||||
update: (next: ToastNotice) => void;
|
||||
dismiss: () => void;
|
||||
};
|
||||
|
||||
type ToastAction = {
|
||||
label: string;
|
||||
run: () => void | ToastNotice;
|
||||
tone?: "default" | "destructive";
|
||||
};
|
||||
|
||||
export type ToastNotice = {
|
||||
message: string;
|
||||
detail?: string;
|
||||
tone: "success" | "error" | "pending";
|
||||
dedupeKey?: string;
|
||||
action?: { label: string; run: () => void };
|
||||
persistent?: boolean;
|
||||
details?: {
|
||||
label: string;
|
||||
render: (controller: ToastController) => ReactNode;
|
||||
};
|
||||
action?: ToastAction;
|
||||
secondaryAction?: { label: string; run?: () => void };
|
||||
onExpire?: () => void;
|
||||
};
|
||||
|
||||
@@ -20,63 +38,145 @@ function toastDurationMs(notice: ToastNotice) {
|
||||
return notice.action ? TOAST_ACTION_MS : TOAST_NOTICE_MS;
|
||||
}
|
||||
|
||||
type ToastEntry = ToastNotice & { id: number };
|
||||
type ToastEntry = ToastNotice & { id: number; step: number };
|
||||
const ToastContext = createContext<((notice: ToastNotice) => void) | null>(null);
|
||||
export const useToast = () => useContext(ToastContext);
|
||||
|
||||
function ToastViewport({ children, viewportRef, hidden }: { children: ReactNode; viewportRef: Ref<HTMLDivElement>; hidden: boolean }) {
|
||||
return <div ref={viewportRef} className="pointer-events-none fixed inset-x-3 top-[calc(0.75rem+env(safe-area-inset-top))] z-50 mx-auto flex max-w-[22rem] flex-col items-center gap-2 [.native-host_&]:top-12" style={hidden ? { visibility: "hidden" } : undefined}>
|
||||
return <div ref={viewportRef} className="pointer-events-none fixed inset-x-3 top-[calc(0.75rem+env(safe-area-inset-top))] z-50 mx-auto flex max-w-[min(calc(100vw-1.5rem),36rem)] flex-col items-center gap-2 [.native-host_&]:top-12" style={hidden ? { visibility: "hidden" } : undefined}>
|
||||
{children}
|
||||
</div>;
|
||||
}
|
||||
|
||||
function ToastCard({ notice, paused, onAction, onHoverChange, onFocusChange }: {
|
||||
function ToastCard({ notice, step, paused, unavailable, controller, onAction, onSecondaryAction, onHoverChange, onFocusChange }: {
|
||||
notice: ToastNotice;
|
||||
step: number;
|
||||
paused: boolean;
|
||||
unavailable: boolean;
|
||||
controller: ToastController;
|
||||
onAction: () => void;
|
||||
onSecondaryAction: () => void;
|
||||
onHoverChange?: (hovered: boolean) => void;
|
||||
onFocusChange?: (focused: boolean) => void;
|
||||
}) {
|
||||
const { message, detail, tone, action } = notice;
|
||||
const { message, detail, tone, persistent, details, action, secondaryAction } = notice;
|
||||
const [detailsOpen, setDetailsOpen] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!details || unavailable) setDetailsOpen(false);
|
||||
}, [details, unavailable]);
|
||||
const Icon = tone === "error" ? TriangleAlert : tone === "pending" ? Trash2 : Check;
|
||||
return <div
|
||||
className={`toast-card isolate relative flex min-h-10 max-w-full items-center gap-2 px-3 py-0.5${action ? " pointer-events-auto" : ""}`}
|
||||
style={{
|
||||
"--toast-duration": `${toastDurationMs(notice)}ms`,
|
||||
"--toast-play-state": paused ? "paused" : "running",
|
||||
} as CSSProperties}
|
||||
onPointerEnter={(event) => { if (event.pointerType !== "touch") onHoverChange?.(true); }}
|
||||
onPointerLeave={() => onHoverChange?.(false)}
|
||||
onFocus={() => onFocusChange?.(true)}
|
||||
onBlur={(event) => { if (!event.currentTarget.contains(event.relatedTarget)) onFocusChange?.(false); }}
|
||||
data-toast-tone={tone}
|
||||
>
|
||||
<Icon aria-hidden="true" size={15} strokeWidth={2} className="shrink-0" />
|
||||
<div role={tone === "error" ? "alert" : "status"} className="min-w-0 truncate text-sm leading-5"
|
||||
title={detail ? `${message} ${detail}` : message}>
|
||||
<span className={detail ? "text-muted-foreground" : "font-medium"}>{message}</span>
|
||||
{detail && <> <span className="font-medium">{detail}</span></>}
|
||||
</div>
|
||||
{action && <Button type="button" variant="ghost" size="sm" onClick={onAction} className="h-8 shrink-0 px-2">{action.label}</Button>}
|
||||
</div>;
|
||||
const hasActions = Boolean(action || secondaryAction);
|
||||
const interactive = Boolean(hasActions || details);
|
||||
return (
|
||||
<Popover open={Boolean(details) && detailsOpen} onOpenChange={setDetailsOpen}>
|
||||
<PopoverAnchor asChild>
|
||||
<div
|
||||
className={`toast-card isolate relative flex min-h-10 max-w-full items-center gap-2 ${interactive ? "py-1 pl-3.5 pr-1.5" : "px-3.5 py-1"}${interactive ? " pointer-events-auto" : ""}`}
|
||||
style={{
|
||||
"--toast-duration": `${toastDurationMs(notice)}ms`,
|
||||
"--toast-play-state": paused ? "paused" : "running",
|
||||
} as CSSProperties}
|
||||
onPointerEnter={(event) => { if (event.pointerType !== "touch") onHoverChange?.(true); }}
|
||||
onPointerLeave={() => onHoverChange?.(false)}
|
||||
onFocus={() => onFocusChange?.(true)}
|
||||
onBlur={(event) => { if (!event.currentTarget.contains(event.relatedTarget)) onFocusChange?.(false); }}
|
||||
data-toast-tone={tone}
|
||||
data-toast-timed={persistent ? "false" : "true"}
|
||||
>
|
||||
<Icon aria-hidden="true" size={15} strokeWidth={2} className="shrink-0" />
|
||||
<div role={tone === "error" ? "alert" : "status"} className="min-w-0 truncate text-sm leading-5">
|
||||
<span className={detail ? "text-muted-foreground" : "font-medium"}>{message}</span>
|
||||
{detail && <> <span className="font-medium">{detail}</span></>}
|
||||
</div>
|
||||
{details && (
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 shrink-0 gap-1 rounded-full bg-muted/65 px-2.5 text-sm font-medium leading-5 tabular-nums text-foreground/85 hover:bg-muted hover:text-foreground data-[state=open]:bg-muted data-[state=open]:text-foreground"
|
||||
>
|
||||
<span>{details.label}</span>
|
||||
<ChevronDown
|
||||
className={`h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform duration-150 ${detailsOpen ? "rotate-180" : ""}`}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
)}
|
||||
{details && hasActions && (
|
||||
<span aria-hidden="true" className="mx-0.5 h-4 w-px shrink-0 bg-border/80" />
|
||||
)}
|
||||
{hasActions && (
|
||||
<div className="flex shrink-0 items-center gap-0.5">
|
||||
{secondaryAction && (
|
||||
<Button
|
||||
key={`secondary-${step}`}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onSecondaryAction}
|
||||
className="h-7 shrink-0 rounded-full px-2.5 text-sm leading-5 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{secondaryAction.label}
|
||||
</Button>
|
||||
)}
|
||||
{action && (
|
||||
<Button
|
||||
key={`action-${step}`}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onAction}
|
||||
className={action.tone === "destructive"
|
||||
? "h-7 shrink-0 rounded-full px-2.5 text-sm font-medium leading-5 text-destructive hover:bg-destructive/10 hover:text-destructive"
|
||||
: "h-7 shrink-0 rounded-full px-2.5 text-sm font-medium leading-5"}
|
||||
>
|
||||
{action.label}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</PopoverAnchor>
|
||||
{details && (
|
||||
<PopoverContent
|
||||
align="center"
|
||||
side="bottom"
|
||||
sideOffset={8}
|
||||
className="w-[var(--radix-popover-trigger-width)] min-w-[min(calc(100vw-1.5rem),21rem)] max-w-[calc(100vw-1.5rem)] rounded-panel border border-border bg-popover p-0 shadow-[0_1px_2px_rgb(0_0_0/0.04),0_12px_32px_-10px_rgb(0_0_0/0.18)] dark:shadow-[0_1px_2px_rgb(0_0_0/0.2),0_14px_34px_-8px_rgb(0_0_0/0.48)]"
|
||||
>
|
||||
{details.render(controller)}
|
||||
</PopoverContent>
|
||||
)}
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
type ToastFinishReason = "action" | "expired";
|
||||
type ToastFinishReason = "action" | "secondary" | "expired";
|
||||
|
||||
function TimedToast({ entry, finish, unavailable }: {
|
||||
function TimedToast({ entry, finish, update, dismiss, unavailable }: {
|
||||
entry: ToastEntry;
|
||||
finish: (entry: ToastEntry, reason: ToastFinishReason) => void;
|
||||
update: (entry: ToastEntry, next: ToastNotice) => void;
|
||||
dismiss: (entry: ToastEntry) => void;
|
||||
unavailable: boolean;
|
||||
}) {
|
||||
const [hovered, setHovered] = useState(false);
|
||||
const [focused, setFocused] = useState(false);
|
||||
const paused = unavailable || hovered || focused;
|
||||
const persistent = Boolean(entry.persistent);
|
||||
const paused = persistent || unavailable || hovered || focused;
|
||||
const remaining = useRef(toastDurationMs(entry));
|
||||
useLayoutEffect(() => {
|
||||
setHovered(false);
|
||||
setFocused(false);
|
||||
remaining.current = toastDurationMs(entry);
|
||||
}, [entry.step]);
|
||||
useLayoutEffect(() => {
|
||||
if (!unavailable) return;
|
||||
setHovered(false);
|
||||
setFocused(false);
|
||||
}, [unavailable]);
|
||||
const remaining = useRef(toastDurationMs(entry));
|
||||
useLayoutEffect(() => {
|
||||
if (paused) return;
|
||||
const start = performance.now();
|
||||
@@ -86,9 +186,17 @@ function TimedToast({ entry, finish, unavailable }: {
|
||||
remaining.current = Math.max(0, remaining.current - (performance.now() - start));
|
||||
};
|
||||
}, [entry, finish, paused]);
|
||||
const controller = useMemo<ToastController>(() => ({
|
||||
update: (next) => update(entry, next),
|
||||
dismiss: () => dismiss(entry),
|
||||
}), [dismiss, entry, update]);
|
||||
|
||||
return <ToastCard notice={entry} paused={paused} onAction={() => finish(entry, "action")}
|
||||
onHoverChange={entry.action ? setHovered : undefined} onFocusChange={entry.action ? setFocused : undefined} />;
|
||||
return <ToastCard notice={entry} step={entry.step} paused={paused} unavailable={unavailable}
|
||||
controller={controller}
|
||||
onAction={() => finish(entry, "action")}
|
||||
onSecondaryAction={() => finish(entry, "secondary")}
|
||||
onHoverChange={!persistent && entry.action ? setHovered : undefined}
|
||||
onFocusChange={!persistent && entry.action ? setFocused : undefined} />;
|
||||
}
|
||||
|
||||
export function ToastProvider({ children }: { children: ReactNode }) {
|
||||
@@ -115,25 +223,58 @@ export function ToastProvider({ children }: { children: ReactNode }) {
|
||||
const live = useRef(new Map<number, ToastEntry>());
|
||||
const publish = useCallback(() => setEntries([...live.current.values()]), []);
|
||||
const show = useCallback((notice: ToastNotice) => {
|
||||
if (notice.dedupeKey && !notice.action && !notice.onExpire) {
|
||||
if (notice.dedupeKey && !notice.onExpire && (!notice.action || notice.persistent)) {
|
||||
for (const [id, entry] of live.current) {
|
||||
if (entry.dedupeKey === notice.dedupeKey && !entry.action && !entry.onExpire) live.current.delete(id);
|
||||
if (entry.dedupeKey === notice.dedupeKey && !entry.onExpire && (!entry.action || entry.persistent)) {
|
||||
live.current.delete(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
const entry = { ...notice, id: ++nextId.current };
|
||||
const entry = { ...notice, id: ++nextId.current, step: 0 };
|
||||
live.current.set(entry.id, entry);
|
||||
publish();
|
||||
}, [publish]);
|
||||
const finish = useCallback((entry: ToastEntry, reason: ToastFinishReason) => {
|
||||
if (!live.current.delete(entry.id)) return;
|
||||
const update = useCallback((entry: ToastEntry, next: ToastNotice) => {
|
||||
const current = live.current.get(entry.id);
|
||||
if (!current || current.step !== entry.step) return;
|
||||
live.current.set(entry.id, { ...next, id: entry.id, step: current.step + 1 });
|
||||
publish();
|
||||
if (reason === "action") entry.action?.run();
|
||||
else entry.onExpire?.();
|
||||
}, [publish]);
|
||||
const dismiss = useCallback((entry: ToastEntry) => {
|
||||
const current = live.current.get(entry.id);
|
||||
if (!current || current.step !== entry.step) return;
|
||||
live.current.delete(entry.id);
|
||||
publish();
|
||||
}, [publish]);
|
||||
const finish = useCallback((entry: ToastEntry, reason: ToastFinishReason) => {
|
||||
const current = live.current.get(entry.id);
|
||||
if (!current || current.step !== entry.step) return;
|
||||
if (reason === "action") {
|
||||
const next = current.action?.run();
|
||||
if (next) {
|
||||
live.current.set(entry.id, { ...next, id: entry.id, step: current.step + 1 });
|
||||
publish();
|
||||
return;
|
||||
}
|
||||
}
|
||||
live.current.delete(entry.id);
|
||||
publish();
|
||||
if (reason === "secondary") current.secondaryAction?.run?.();
|
||||
else if (reason === "expired") current.onExpire?.();
|
||||
}, [publish]);
|
||||
return <ToastContext.Provider value={show}>
|
||||
{children}
|
||||
<ToastViewport viewportRef={viewportRef} hidden={unavailable}>
|
||||
{entries.map((entry) => <TimedToast key={entry.id} entry={entry} finish={finish} unavailable={unavailable} />)}
|
||||
{entries.map((entry) => (
|
||||
<TimedToast
|
||||
key={entry.id}
|
||||
entry={entry}
|
||||
finish={finish}
|
||||
update={update}
|
||||
dismiss={dismiss}
|
||||
unavailable={unavailable}
|
||||
/>
|
||||
))}
|
||||
</ToastViewport>
|
||||
</ToastContext.Provider>;
|
||||
}
|
||||
Reference in new issue
Block a user