fix(webui): make action feedback easier to notice (#6702)
* fix(webui): make action feedback easier to notice * fix(webui): preserve undo and report confirmed action results * refactor(webui): trim toast preview and redundant coverage * test(webui): advance the undo window for the last topic deletion
This commit is contained in:
1 parent
0f45d74fec
commit
9ccf3b6214
59 files changed
+1621
-508
No files matched your search
@@ -2,6 +2,7 @@ import { Component, Suspense, lazy, memo, startTransition, useCallback, useEffec
|
||||
import { Check, Copy } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { useToast } from "@/components/ui/toast";
|
||||
import { useThemeValue } from "@/hooks/useTheme";
|
||||
import { hasAnsi, parseAnsiSegments, stripAnsi } from "@/lib/ansi";
|
||||
import { copyTextToClipboard } from "@/lib/clipboard";
|
||||
@@ -139,6 +140,7 @@ export const CodeBlock = memo(function CodeBlock({
|
||||
viewportHighlight = false,
|
||||
}: CodeBlockProps) {
|
||||
const { t } = useTranslation();
|
||||
const showToast = useToast();
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [highlightedSource, setHighlightedSource] = useState<string | null>(null);
|
||||
@@ -191,11 +193,14 @@ export const CodeBlock = memo(function CodeBlock({
|
||||
|
||||
const onCopy = useCallback(() => {
|
||||
void copyTextToClipboard(plainCode).then((ok) => {
|
||||
if (!ok) return;
|
||||
if (!ok) {
|
||||
showToast?.({ message: t("fileActions.failed"), tone: "error", dedupeKey: "copy-failed" });
|
||||
return;
|
||||
}
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 1_500);
|
||||
});
|
||||
}, [plainCode]);
|
||||
}, [plainCode, showToast, t]);
|
||||
|
||||
return (
|
||||
<div
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { TOAST_ACTION_MS } from "@/components/ui/toast";
|
||||
import type { TFunction } from "i18next";
|
||||
import { Trash2 } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -65,11 +66,7 @@ export function DeleteConfirm({
|
||||
defaultValue: "Linked automations will also be deleted.",
|
||||
})
|
||||
: t("deleteConfirm.automationsDescription")
|
||||
: multiple
|
||||
? t("deleteConfirm.descriptionMany", {
|
||||
defaultValue: "This action cannot be undone.",
|
||||
})
|
||||
: t("deleteConfirm.description")}
|
||||
: t("toast.deleteWindow", { seconds: TOAST_ACTION_MS / 1_000 })}
|
||||
</AlertDialogDescription>
|
||||
{hasAutomations ? (
|
||||
<div className="mt-4 max-h-40 w-full overflow-y-auto rounded-2xl bg-muted/55 px-3 py-2 text-left">
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next";
|
||||
|
||||
import { floatingItemClassName, floatingItemFocusClassName, floatingSurfaceClassName, floatingSurfaceMotionClassName } from "@/components/ui/floating-surface";
|
||||
import { useFloatingPortal } from "@/components/ui/floating-portal";
|
||||
import { useToast } from "@/components/ui/toast";
|
||||
import { copyTextToClipboard } from "@/lib/clipboard";
|
||||
import type { FileReferenceMetadata, FilePreviewPayload } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
@@ -33,6 +34,7 @@ export function FileActions({
|
||||
}) {
|
||||
const context = useContext(FileActionsContext);
|
||||
const { t } = useTranslation();
|
||||
const showToast = useToast();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [resolved, setResolved] = useState<FileReferenceMetadata | null>(null);
|
||||
const [loadFailed, setLoadFailed] = useState(false);
|
||||
@@ -71,8 +73,14 @@ export function FileActions({
|
||||
const success = await copyTextToClipboard(value);
|
||||
// A dismissed/reopened menu or another reference owns its own feedback.
|
||||
if (generation !== copyGeneration.current) return;
|
||||
setCopyStatus(success ? "copied" : "failed");
|
||||
if (success) changeOpen(false);
|
||||
if (showToast) {
|
||||
showToast({ message: t(success ? "fileActions.copied" : "fileActions.failed"), tone: success ? "success" : "error",
|
||||
dedupeKey: success ? "copied" : "copy-failed" });
|
||||
} else {
|
||||
setCopyStatus(success ? "copied" : "failed");
|
||||
}
|
||||
// A modal menu hides the rest of the app, including the toast, from assistive technology.
|
||||
if (success || showToast) changeOpen(false);
|
||||
};
|
||||
const openMenu = (target: EventTarget, x: number, y: number) => {
|
||||
point.current = { x, y };
|
||||
|
||||
@@ -25,6 +25,7 @@ import { StreamingLabelSheen } from "@/components/ui/streaming-label-sheen";
|
||||
import { ContextCompactionNotice } from "@/components/thread/ContextCompactionNotice";
|
||||
import { UserMessageText } from "@/components/UserMessageText";
|
||||
import { HoverHint } from "@/components/ui/tooltip";
|
||||
import { useToast } from "@/components/ui/toast";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { copyTextToClipboard } from "@/lib/clipboard";
|
||||
import { formatMessageEndTime } from "@/lib/format-time";
|
||||
@@ -76,6 +77,7 @@ function ForkArrowIcon({ className }: { className?: string }) {
|
||||
|
||||
function useMessageCopy(content: string) {
|
||||
const { t } = useTranslation();
|
||||
const showToast = useToast();
|
||||
const [copied, setCopied] = useState(false);
|
||||
const copyResetRef = useRef<number | null>(null);
|
||||
|
||||
@@ -89,7 +91,10 @@ function useMessageCopy(content: string) {
|
||||
|
||||
const onCopy = useCallback(() => {
|
||||
void copyTextToClipboard(content).then((ok) => {
|
||||
if (!ok) return;
|
||||
if (!ok) {
|
||||
showToast?.({ message: t("fileActions.failed"), tone: "error", dedupeKey: "copy-failed" });
|
||||
return;
|
||||
}
|
||||
setCopied(true);
|
||||
if (copyResetRef.current !== null) {
|
||||
window.clearTimeout(copyResetRef.current);
|
||||
@@ -99,7 +104,7 @@ function useMessageCopy(content: string) {
|
||||
copyResetRef.current = null;
|
||||
}, 1_500);
|
||||
});
|
||||
}, [content]);
|
||||
}, [content, showToast, t]);
|
||||
|
||||
const label = copied ? t("message.copiedReply") : t("message.copyReply");
|
||||
return { copied, label, onCopy };
|
||||
|
||||
@@ -6,6 +6,7 @@ import { CodeBlock } from "@/components/CodeBlock";
|
||||
import { Dialog, DialogContent, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
|
||||
import { HoverHint } from "@/components/ui/hover-hint";
|
||||
import { ImageViewport } from "@/components/ui/image-viewport";
|
||||
import { useToast } from "@/components/ui/toast";
|
||||
import { copyTextToClipboard } from "@/lib/clipboard";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useDiagramScope } from "./context";
|
||||
@@ -26,6 +27,7 @@ function readPalette(element: HTMLElement): DiagramPalette {
|
||||
|
||||
export default function MermaidBlock({ source }: { source: string }) {
|
||||
const { t } = useTranslation();
|
||||
const showToast = useToast();
|
||||
const scope = useDiagramScope();
|
||||
const container = useRef<HTMLDivElement>(null);
|
||||
const mono = useRef<HTMLSpanElement>(null);
|
||||
@@ -104,7 +106,10 @@ export default function MermaidBlock({ source }: { source: string }) {
|
||||
useEffect(() => () => clearTimeout(copyTimer.current), []);
|
||||
|
||||
const copy = async () => {
|
||||
if (!await copyTextToClipboard(source)) return;
|
||||
if (!await copyTextToClipboard(source)) {
|
||||
showToast?.({ message: t("fileActions.failed"), tone: "error", dedupeKey: "copy-failed" });
|
||||
return;
|
||||
}
|
||||
setCopied(true);
|
||||
clearTimeout(copyTimer.current);
|
||||
copyTimer.current = setTimeout(() => setCopied(false), 2000);
|
||||
|
||||
@@ -8,6 +8,7 @@ import { Input } from "@/components/ui/input";
|
||||
import { DisclosureContent } from "@/components/ui/disclosure";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
||||
import { useToast } from "@/components/ui/toast";
|
||||
import { useClient } from "@/providers/ClientProvider";
|
||||
import { groupRemoteProfiles, isCompatibilityError, remoteAction, type RemoteInspection, type RemoteProfile } from "@/lib/remote-instances";
|
||||
import { cn } from "@/lib/utils";
|
||||
@@ -34,6 +35,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
|
||||
const { t } = useTranslation();
|
||||
const { client } = useClient();
|
||||
const connections = useRemoteConnections();
|
||||
const showToast = useToast();
|
||||
const [form, setForm] = useState(emptyProfile);
|
||||
const [editorOpen, setEditorOpen] = useState(false);
|
||||
const returnedPair = useSyncExternalStore(subscribePairReturn, readPairReturn);
|
||||
@@ -190,6 +192,15 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
|
||||
if (wanted(attempt)) setFingerprint({ id, ...result, inspect });
|
||||
} catch (scanError) { if (wanted(attempt)) showError(scanError); }
|
||||
} else {
|
||||
// Opening an alias of the local gateway needs no recovery. A dialog
|
||||
// (including the pairing popup) can hide the shell's toast viewport.
|
||||
if (reason instanceof Error && reason.message === "same_instance" && showToast
|
||||
&& !editorOpen && !fingerprint && !detailsOpen && page.current
|
||||
&& !page.current.closest("[hidden], [inert], [aria-hidden='true']")
|
||||
&& !document.querySelector(":is([role='dialog'], [role='alertdialog']):not([data-state='closed'])")) {
|
||||
showToast({ message: t("remote.errors.same_instance"), tone: "error", dedupeKey: "remote-same-instance" });
|
||||
return;
|
||||
}
|
||||
if (!editorOpen) {
|
||||
const profile = directory?.profiles.find((item) => item.id === id);
|
||||
if (profile && !profile.paired) {
|
||||
|
||||
@@ -332,6 +332,7 @@ export function SettingsPage({
|
||||
}}
|
||||
onDeleteConfiguration={(preset, onDeleted) => {
|
||||
presetDeletedCallback.current = onDeleted;
|
||||
modelState.setModelPresetDeleteError(null);
|
||||
modelState.setModelPresetPendingDelete(preset);
|
||||
}}
|
||||
/>
|
||||
@@ -604,9 +605,13 @@ export function SettingsPage({
|
||||
onAction={systemActions.handleAutomationAction}
|
||||
onRequestEdit={(job) => {
|
||||
setAutomationDetailReturn(null);
|
||||
systemState.setAutomationDialogError(null);
|
||||
systemState.setAutomationPendingEdit(job);
|
||||
}}
|
||||
onRequestDelete={systemState.setAutomationPendingDelete}
|
||||
onRequestDelete={(job) => {
|
||||
systemState.setAutomationDialogError(null);
|
||||
systemState.setAutomationPendingDelete(job);
|
||||
}}
|
||||
onChangeChat={systemActions.handleAutomationChat}
|
||||
onManageModels={() => selectSection("models")}
|
||||
returnToDetailJob={automationDetailReturn}
|
||||
@@ -669,6 +674,7 @@ export function SettingsPage({
|
||||
<ModelPresetDeleteDialog
|
||||
preset={modelState.modelPresetPendingDelete}
|
||||
deleting={modelState.saving}
|
||||
error={modelState.modelPresetPendingDelete ? modelState.modelPresetDeleteError : null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
modelState.setModelPresetPendingDelete(null);
|
||||
@@ -728,6 +734,7 @@ export function SettingsPage({
|
||||
<AutomationDeleteDialog
|
||||
job={systemState.automationPendingDelete}
|
||||
deleting={systemState.automationAction === `delete:${systemState.automationPendingDelete?.id ?? ""}`}
|
||||
error={systemState.automationPendingDelete ? systemState.automationDialogError : null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) systemState.setAutomationPendingDelete(null);
|
||||
}}
|
||||
@@ -737,6 +744,7 @@ export function SettingsPage({
|
||||
<AutomationEditDialog
|
||||
job={systemState.automationPendingEdit}
|
||||
saving={systemState.automationAction === `update:${systemState.automationPendingEdit?.id ?? ""}`}
|
||||
error={systemState.automationPendingEdit ? systemState.automationDialogError : null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) systemState.setAutomationPendingEdit(null);
|
||||
}}
|
||||
|
||||
@@ -149,11 +149,13 @@ export function agentDraftFromPayload(
|
||||
export function ModelPresetDeleteDialog({
|
||||
preset,
|
||||
deleting,
|
||||
error,
|
||||
onOpenChange,
|
||||
onConfirm,
|
||||
}: {
|
||||
preset: SettingsPayload["model_presets"][number] | null;
|
||||
deleting: boolean;
|
||||
error?: string | null;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onConfirm: () => void;
|
||||
}) {
|
||||
@@ -161,8 +163,8 @@ export function ModelPresetDeleteDialog({
|
||||
const tx = (key: string, fallback: string, values?: Record<string, unknown>) =>
|
||||
t(key, { defaultValue: fallback, ...(values ?? {}) });
|
||||
return (
|
||||
<Dialog open={preset !== null} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-[440px]">
|
||||
<Dialog open={preset !== null} onOpenChange={(open) => { if (open || !deleting) onOpenChange(open); }}>
|
||||
<DialogContent showCloseButton={!deleting} className="max-w-[440px]">
|
||||
<DialogHeader className="text-left">
|
||||
<DialogTitle>
|
||||
{tx("settings.models.deletePresetTitle", "Delete model preset?")}
|
||||
@@ -175,6 +177,7 @@ export function ModelPresetDeleteDialog({
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{error ? <p role="alert" className="break-words text-sm text-destructive">{error}</p> : null}
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
} from "@/components/settings/models/providerForm";
|
||||
import type { ModelSettingsState } from "@/components/settings/models/useModelSettingsState";
|
||||
import { normalizeContextWindowTokens } from "@/components/settings/shared/ModelControls";
|
||||
import { useToast } from "@/components/ui/toast";
|
||||
import {
|
||||
ApiError,
|
||||
cancelProviderOAuth,
|
||||
@@ -86,6 +87,7 @@ export function useModelSettingsActions({
|
||||
installCapabilities,
|
||||
configuredModelProviderOptions,
|
||||
}: ModelSettingsActionsOptions) {
|
||||
const showToast = useToast();
|
||||
const oauthMounted = useRef(true);
|
||||
useEffect(() => {
|
||||
oauthMounted.current = true;
|
||||
@@ -117,6 +119,7 @@ export function useModelSettingsActions({
|
||||
setModelPresetEditingName,
|
||||
setModelPresetNameError,
|
||||
setModelPresetPendingDelete,
|
||||
setModelPresetDeleteError,
|
||||
setProviderForms,
|
||||
setProviderOAuthCompleting,
|
||||
setProviderOAuthDialogError,
|
||||
@@ -392,7 +395,15 @@ export function useModelSettingsActions({
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
setModelCallOrder(previousOrder);
|
||||
setError((err as Error).message);
|
||||
if (showToast && err instanceof ApiError && (err.status === 503 || err.status === 504)) {
|
||||
showToast({
|
||||
tone: "error",
|
||||
message: t("message.agentActivity.updateAgentSettingsFailed"),
|
||||
dedupeKey: "settings:models:call-order",
|
||||
});
|
||||
} else {
|
||||
setError((err as Error).message);
|
||||
}
|
||||
} finally {
|
||||
setModelCallOrderSaving(false);
|
||||
}
|
||||
@@ -423,14 +434,14 @@ export function useModelSettingsActions({
|
||||
return false;
|
||||
}
|
||||
setSaving(true);
|
||||
setModelPresetDeleteError(null);
|
||||
try {
|
||||
const payload = await deleteModelConfiguration(client, modelPresetPendingDelete.name);
|
||||
applyPayload(payload, { preserveCapabilityForms: true });
|
||||
setModelPresetPendingDelete(null);
|
||||
setError(null);
|
||||
return true;
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
setModelPresetDeleteError(err instanceof Error ? err.message : String(err));
|
||||
return false;
|
||||
} finally {
|
||||
setSaving(false);
|
||||
|
||||
@@ -25,6 +25,7 @@ export function useModelSettingsState(initialSettings: SettingsPayload | null) {
|
||||
const [modelMigrationSaving, setModelMigrationSaving] = useState(false);
|
||||
const [modelPresetPendingDelete, setModelPresetPendingDelete] =
|
||||
useState<SettingsPayload["model_presets"][number] | null>(null);
|
||||
const [modelPresetDeleteError, setModelPresetDeleteError] = useState<string | null>(null);
|
||||
const modelPresetBeforeCreateRef = useRef<string | null>(null);
|
||||
const [providerOperation, setProviderOperation] = useState<ProviderOperation | null>(null);
|
||||
const providerSaving = providerOperation?.provider ?? null;
|
||||
@@ -76,6 +77,8 @@ export function useModelSettingsState(initialSettings: SettingsPayload | null) {
|
||||
setModelPresetEditingName,
|
||||
setModelPresetNameError,
|
||||
setModelPresetPendingDelete,
|
||||
modelPresetDeleteError,
|
||||
setModelPresetDeleteError,
|
||||
setProviderForms,
|
||||
setProviderOAuthCompleting,
|
||||
setProviderOAuthDialogError,
|
||||
|
||||
@@ -55,8 +55,10 @@ import {
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { SegmentedControl } from "@/components/ui/segmented-control";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { useToast } from "@/components/ui/toast";
|
||||
import { SettingsTextEditor } from "@/components/settings/shared/SettingsTextEditor";
|
||||
import { useLogoFallback } from "@/hooks/useLogoFallback";
|
||||
import { copyTextToClipboard } from "@/lib/clipboard";
|
||||
import { isGenericRepositoryLogoUrl, logoFallbackUrls } from "@/lib/provider-brand";
|
||||
import type {
|
||||
CliAppInfo,
|
||||
@@ -1463,17 +1465,20 @@ function CliAppReadyPanel({
|
||||
onBackToChat: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const showToast = useToast();
|
||||
const [copied, setCopied] = useState(false);
|
||||
const prompt = t("settings.cliApps.readyPrompt", {
|
||||
name: app.name,
|
||||
defaultValue: "Use @{{name}} to inspect what this CLI can do.",
|
||||
});
|
||||
const copyPrompt = () => {
|
||||
if (!navigator.clipboard) return;
|
||||
void navigator.clipboard.writeText(prompt).then(() => {
|
||||
setCopied(true);
|
||||
const copyPrompt = async () => {
|
||||
const copied = await copyTextToClipboard(prompt);
|
||||
setCopied(copied);
|
||||
if (copied) {
|
||||
window.setTimeout(() => setCopied(false), 1400);
|
||||
});
|
||||
} else {
|
||||
showToast?.({ tone: "error", message: t("fileActions.failed"), dedupeKey: "settings:apps:copy-prompt" });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -690,12 +690,14 @@ const AUTOMATION_EVERY_UNITS: Array<{ value: AutomationEveryUnit; ms: number }>
|
||||
export function AutomationEditDialog({
|
||||
job,
|
||||
saving,
|
||||
error,
|
||||
onOpenChange,
|
||||
onCancel,
|
||||
onSave,
|
||||
}: {
|
||||
job: SessionAutomationJob | null;
|
||||
saving: boolean;
|
||||
error?: string | null;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onCancel?: (job: SessionAutomationJob) => void;
|
||||
onSave: (job: SessionAutomationJob, values: AutomationUpdatePayload) => void | Promise<void>;
|
||||
@@ -727,11 +729,13 @@ export function AutomationEditDialog({
|
||||
|
||||
const submit = (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
if (saving) return;
|
||||
const payload = automationUpdatePayloadFromDraft(draft, job);
|
||||
if (!job || typeof payload === "string") return;
|
||||
void onSave(job, payload);
|
||||
};
|
||||
const changeOpen = (open: boolean) => {
|
||||
if (!open && saving) return;
|
||||
onOpenChange(open);
|
||||
if (!open && job) onCancel?.(job);
|
||||
};
|
||||
@@ -745,6 +749,7 @@ export function AutomationEditDialog({
|
||||
<DialogContent
|
||||
{...dialogFocus}
|
||||
aria-describedby={undefined}
|
||||
showCloseButton={!saving}
|
||||
className="w-[min(calc(100vw-2rem),34rem)]"
|
||||
onEscapeKeyDown={(event) => {
|
||||
// Escape in the nested date calendar must not cancel the editor.
|
||||
@@ -879,6 +884,7 @@ export function AutomationEditDialog({
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{error ? <AutomationError message={error} /> : null}
|
||||
{validation ? (
|
||||
<div id={validationId} className="rounded-control bg-destructive/8 px-3 py-2 text-[12px] text-destructive">
|
||||
{validation}
|
||||
@@ -910,11 +916,13 @@ export function AutomationEditDialog({
|
||||
export function AutomationDeleteDialog({
|
||||
job,
|
||||
deleting,
|
||||
error,
|
||||
onOpenChange,
|
||||
onConfirm,
|
||||
}: {
|
||||
job: SessionAutomationJob | null;
|
||||
deleting: boolean;
|
||||
error?: string | null;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onConfirm: (job: SessionAutomationJob) => void | Promise<void>;
|
||||
}) {
|
||||
@@ -923,8 +931,8 @@ export function AutomationDeleteDialog({
|
||||
const tx = (key: string, fallback: string, values?: Record<string, unknown>) =>
|
||||
t(key, { defaultValue: fallback, ...(values ?? {}) });
|
||||
return (
|
||||
<Dialog open={Boolean(job)} onOpenChange={onOpenChange}>
|
||||
<DialogContent {...dialogFocus} className="w-[min(calc(100vw-2rem),26rem)]">
|
||||
<Dialog open={Boolean(job)} onOpenChange={(open) => { if (open || !deleting) onOpenChange(open); }}>
|
||||
<DialogContent {...dialogFocus} showCloseButton={!deleting} className="w-[min(calc(100vw-2rem),26rem)]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{tx("settings.automations.deleteTitle", "Delete automation")}</DialogTitle>
|
||||
<DialogDescription>
|
||||
@@ -935,6 +943,7 @@ export function AutomationDeleteDialog({
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{error ? <AutomationError message={error} /> : null}
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
StatusPill,
|
||||
} from "@/components/settings/shared/SettingsControls";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useToast } from "@/components/ui/toast";
|
||||
import { getRuntimeHost, isNativeRuntime } from "@/lib/runtime";
|
||||
import type { NanobotFeatureInfo, SettingsPayload } from "@/lib/types";
|
||||
|
||||
@@ -38,6 +39,7 @@ export function RuntimeSettings({
|
||||
onInstallCapability: (name: string) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const showToast = useToast();
|
||||
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
|
||||
const runtimeSurface = settings.surface ?? settings.runtime_surface;
|
||||
const runtimeHost = getRuntimeHost(runtimeSurface, settings.runtime_capabilities);
|
||||
@@ -84,7 +86,11 @@ export function RuntimeSettings({
|
||||
const result = await action();
|
||||
setHostActionMessage({ target, message: successMessage(result) });
|
||||
} catch {
|
||||
setHostActionMessage({ target, message: failureMessage });
|
||||
if (showToast) {
|
||||
showToast({ tone: "error", message: failureMessage, dedupeKey: `settings:runtime:${target}` });
|
||||
} else {
|
||||
setHostActionMessage({ target, message: failureMessage });
|
||||
}
|
||||
} finally {
|
||||
setHostActionBusy(null);
|
||||
}
|
||||
|
||||
@@ -93,6 +93,7 @@ export function createSystemSettingsActions({
|
||||
nanobotFeatureActionRef,
|
||||
nanobotFeatures,
|
||||
setAutomationAction,
|
||||
setAutomationDialogError,
|
||||
setAutomationPendingDelete,
|
||||
setAutomationPendingEdit,
|
||||
setAutomations,
|
||||
@@ -230,8 +231,9 @@ export function createSystemSettingsActions({
|
||||
job: SessionAutomationJob,
|
||||
) => {
|
||||
const key = `${action}:${job.id}`;
|
||||
const reportError = action === "delete" ? setAutomationDialogError : setAutomationsError;
|
||||
setAutomationAction(key);
|
||||
setAutomationsError(null);
|
||||
reportError(null);
|
||||
try {
|
||||
const payload = await runAutomationAction(client, action, job.id);
|
||||
setAutomations(payload);
|
||||
@@ -241,7 +243,7 @@ export function createSystemSettingsActions({
|
||||
window.setTimeout(() => void refreshAutomations(false), 4000);
|
||||
}
|
||||
} catch (err) {
|
||||
setAutomationsError((err as Error).message);
|
||||
reportError(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
setAutomationAction(null);
|
||||
}
|
||||
@@ -253,13 +255,13 @@ export function createSystemSettingsActions({
|
||||
) => {
|
||||
const key = `update:${job.id}`;
|
||||
setAutomationAction(key);
|
||||
setAutomationsError(null);
|
||||
setAutomationDialogError(null);
|
||||
try {
|
||||
const payload = await updateAutomation(client, job.id, values);
|
||||
setAutomations(payload);
|
||||
setAutomationPendingEdit(null);
|
||||
} catch (err) {
|
||||
setAutomationsError((err as Error).message);
|
||||
setAutomationDialogError(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
setAutomationAction(null);
|
||||
}
|
||||
|
||||
@@ -52,6 +52,7 @@ export function useSystemSettingsState(toolsCatalog: ToolsCatalog) {
|
||||
const [mcpMessage, setMcpMessage] = useState<string | null>(null);
|
||||
const [mcpError, setMcpError] = useState<string | null>(null);
|
||||
const [automationsError, setAutomationsError] = useState<string | null>(null);
|
||||
const [automationDialogError, setAutomationDialogError] = useState<string | null>(null);
|
||||
const [automationAction, setAutomationAction] = useState<string | null>(null);
|
||||
const [automationPendingDelete, setAutomationPendingDelete] =
|
||||
useState<SessionAutomationJob | null>(null);
|
||||
@@ -106,6 +107,8 @@ export function useSystemSettingsState(toolsCatalog: ToolsCatalog) {
|
||||
setAutomationPendingEdit,
|
||||
setAutomations,
|
||||
setAutomationsError,
|
||||
automationDialogError,
|
||||
setAutomationDialogError,
|
||||
setAutomationsFilter,
|
||||
setAutomationsLoading,
|
||||
setCliApps,
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useTranslation } from "react-i18next";
|
||||
import { MarkdownText, preloadMarkdownText } from "@/components/MarkdownText";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
import { useToast } from "@/components/ui/toast";
|
||||
import { useOverlayEscapeFocus } from "@/hooks/useOverlayEscapeFocus";
|
||||
import type { GoalStateWsPayload } from "@/lib/types";
|
||||
|
||||
@@ -18,7 +19,7 @@ export function GoalIsland({ goal, cancelDisabled, onCancel }: {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [cancelling, setCancelling] = useState(false);
|
||||
const [cancelFailed, setCancelFailed] = useState(false);
|
||||
const showToast = useToast();
|
||||
const [scrollBody, setScrollBody] = useState<HTMLDivElement | null>(null);
|
||||
const panelRef = useRef<HTMLDivElement>(null);
|
||||
const escapeFocus = useOverlayEscapeFocus();
|
||||
@@ -53,11 +54,10 @@ export function GoalIsland({ goal, cancelDisabled, onCancel }: {
|
||||
title={cancelDisabled ? t("thread.composer.cancelGoalOffline") : undefined}
|
||||
onClick={async () => {
|
||||
setCancelling(true);
|
||||
setCancelFailed(false);
|
||||
try {
|
||||
await onCancel();
|
||||
} catch {
|
||||
setCancelFailed(true);
|
||||
showToast?.({ message: t("thread.composer.cancelGoalFailed"), tone: "error", dedupeKey: "cancel-goal" });
|
||||
} finally {
|
||||
setCancelling(false);
|
||||
}
|
||||
@@ -66,7 +66,7 @@ export function GoalIsland({ goal, cancelDisabled, onCancel }: {
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!scrollBody) return;
|
||||
if (status === "blocked" || cancelFailed) scrollBody.scrollTop = 0;
|
||||
if (status === "blocked") scrollBody.scrollTop = 0;
|
||||
const measure = () => {
|
||||
scrollBody.toggleAttribute("data-overflow-top", scrollBody.scrollTop > 1);
|
||||
scrollBody.toggleAttribute("data-overflow-bottom", scrollBody.scrollHeight - scrollBody.clientHeight - scrollBody.scrollTop > 1);
|
||||
@@ -80,7 +80,7 @@ export function GoalIsland({ goal, cancelDisabled, onCancel }: {
|
||||
observer.disconnect();
|
||||
scrollBody.removeEventListener("scroll", measure);
|
||||
};
|
||||
}, [scrollBody, status, cancelFailed]);
|
||||
}, [scrollBody, status]);
|
||||
|
||||
return (
|
||||
<div className="goal-island-position">
|
||||
@@ -120,7 +120,6 @@ export function GoalIsland({ goal, cancelDisabled, onCancel }: {
|
||||
</div> : null}
|
||||
<div ref={setScrollBody} className="goal-island-body">
|
||||
<div className="goal-island-document">
|
||||
{cancelFailed ? <p role="alert" className="mb-2 text-caption text-destructive">{t("thread.composer.cancelGoalFailed")}</p> : null}
|
||||
{status === "blocked" ? <div className="goal-island-blocked">
|
||||
<CircleAlert className="goal-island-status-icon" strokeWidth={2.5} aria-hidden="true" />
|
||||
<span className="sr-only">{t("thread.composer.goalBlocked")}</span>
|
||||
|
||||
@@ -87,6 +87,7 @@ export function SessionInfoPopoverView({ jobs, loading, loadFailed, now, onActio
|
||||
setDetailOpen(true);
|
||||
};
|
||||
const handOffDetail = (next: () => void) => {
|
||||
setActionError(null);
|
||||
afterDetailClose.current = next;
|
||||
setDetailOpen(false);
|
||||
};
|
||||
@@ -249,8 +250,12 @@ export function SessionInfoPopoverView({ jobs, loading, loadFailed, now, onActio
|
||||
<AutomationEditDialog
|
||||
job={pendingEdit}
|
||||
saving={actionKey === `update:${pendingEdit?.id ?? ""}`}
|
||||
error={pendingEdit ? actionError : null}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (!nextOpen) setPendingEdit(null);
|
||||
if (!nextOpen) {
|
||||
setPendingEdit(null);
|
||||
setActionError(null);
|
||||
}
|
||||
}}
|
||||
onCancel={(job) => {
|
||||
setInspectedJob(job);
|
||||
@@ -261,8 +266,12 @@ export function SessionInfoPopoverView({ jobs, loading, loadFailed, now, onActio
|
||||
<AutomationDeleteDialog
|
||||
job={pendingDelete}
|
||||
deleting={actionKey === `delete:${pendingDelete?.id ?? ""}`}
|
||||
error={pendingDelete ? actionError : null}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (!nextOpen) setPendingDelete(null);
|
||||
if (!nextOpen) {
|
||||
setPendingDelete(null);
|
||||
setActionError(null);
|
||||
}
|
||||
}}
|
||||
onConfirm={(job) => handleAction("delete", job)}
|
||||
/>
|
||||
|
||||
@@ -66,6 +66,7 @@ import {
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useToast } from "@/components/ui/toast";
|
||||
import { AttachmentCard, AttachmentTypeFace, attachmentCardActionClassName } from "@/components/AttachmentCard";
|
||||
import { ComposerActionIcon, type ComposerActionState } from "@/components/thread/ComposerActionIcon";
|
||||
import {
|
||||
@@ -153,8 +154,6 @@ import {
|
||||
|
||||
const VOICE_SHORTCUT_CODE = "KeyD";
|
||||
const VOICE_SHORTCUT_ARIA = "Control+Shift+D";
|
||||
const VOICE_ERROR_VISIBLE_MS = 3_500;
|
||||
const VOICE_ERROR_FADE_MS = 500;
|
||||
type VoiceShortcutPlatform = "apple" | "chromeos" | "linux" | "other" | "windows";
|
||||
|
||||
function formatBytes(n: number): string {
|
||||
@@ -621,6 +620,8 @@ export function ThreadComposer({
|
||||
end: number;
|
||||
} | null>(null);
|
||||
const [inlineError, setInlineError] = useState<string | null>(null);
|
||||
const [voiceSetupError, setVoiceSetupError] = useState<VoiceRecorderErrorKey | null>(null);
|
||||
const showToast = useToast();
|
||||
const [sendPending, setSendPending] = useState(false);
|
||||
const [pathInspection, setPathInspection] = useState<{
|
||||
generation: number; scope: string; range: PastedPathRange; attachment?: LocalAttachment;
|
||||
@@ -713,7 +714,6 @@ export function ThreadComposer({
|
||||
useEffect(() => {
|
||||
if (queueSnapshot.error) setInlineError(queueSnapshot.error);
|
||||
}, [queueSnapshot.error]);
|
||||
const [voiceErrorFading, setVoiceErrorFading] = useState(false);
|
||||
const [slashMenuDismissed, setSlashMenuDismissed] = useState(false);
|
||||
const [selectedCommandIndex, setSelectedCommandIndex] = useState(0);
|
||||
const [cliAppMenuDismissed, setCliAppMenuDismissed] = useState(false);
|
||||
@@ -756,7 +756,6 @@ export function ThreadComposer({
|
||||
const chipRefs = useRef(new Map<string, HTMLButtonElement>());
|
||||
const previousPendingQueueKeyRef = useRef(pendingQueueKey);
|
||||
const voiceShortcutDownRef = useRef(false);
|
||||
const voiceErrorFadeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const isHero = variant === "hero";
|
||||
const voiceShortcutLabel = useMemo(getVoiceShortcutLabel, []);
|
||||
const projectPickerAvailable =
|
||||
@@ -818,6 +817,10 @@ export function ThreadComposer({
|
||||
const { rejected } = enqueue(files);
|
||||
if (rejected.length > 0) {
|
||||
const { reason, file } = rejected[0];
|
||||
if (reason === "empty_file" || reason === "unsupported_type") {
|
||||
showToast?.({ message: formatRejection(reason), tone: "error", dedupeKey: `attachment:${reason}` });
|
||||
return;
|
||||
}
|
||||
setInlineError(reason === "too_large"
|
||||
? formatUploadTooLarge(file.size, acceptedAttachmentKind(file) === "video" ? MAX_VIDEO_BYTES : maxFileBytes)
|
||||
: formatRejection(reason));
|
||||
@@ -825,7 +828,7 @@ export function ThreadComposer({
|
||||
setInlineError(null);
|
||||
}
|
||||
},
|
||||
[enqueue, formatRejection, formatUploadTooLarge, interactionDisabled, maxFileBytes],
|
||||
[enqueue, formatRejection, formatUploadTooLarge, interactionDisabled, maxFileBytes, showToast],
|
||||
);
|
||||
|
||||
const {
|
||||
@@ -1391,6 +1394,7 @@ export function ThreadComposer({
|
||||
previousPendingQueueKeyRef.current = pendingQueueKey;
|
||||
setValue("");
|
||||
setInlineError(null);
|
||||
setVoiceSetupError(null);
|
||||
setSlashMenuDismissed(false);
|
||||
setCliAppMenuDismissed(false);
|
||||
setCursorPosition(0);
|
||||
@@ -1407,43 +1411,27 @@ export function ThreadComposer({
|
||||
});
|
||||
setSlashMenuDismissed(false);
|
||||
setCliAppMenuDismissed(false);
|
||||
setInlineError(null);
|
||||
focusTextarea();
|
||||
}, [focusTextarea]);
|
||||
|
||||
const clearVoiceErrorTimers = useCallback(() => {
|
||||
if (voiceErrorFadeTimerRef.current !== null) clearTimeout(voiceErrorFadeTimerRef.current);
|
||||
voiceErrorFadeTimerRef.current = null;
|
||||
}, []);
|
||||
const clearInlineError = useCallback(() => {
|
||||
clearVoiceErrorTimers();
|
||||
setVoiceErrorFading(false);
|
||||
setInlineError(null);
|
||||
}, [clearVoiceErrorTimers]);
|
||||
const clearVoiceSetupError = useCallback(() => setVoiceSetupError(null), []);
|
||||
const setVoiceError = useCallback((key: VoiceRecorderErrorKey) => {
|
||||
clearVoiceErrorTimers();
|
||||
setVoiceErrorFading(false);
|
||||
setInlineError(t(`thread.composer.voiceErrors.${key}`));
|
||||
voiceErrorFadeTimerRef.current = setTimeout(() => {
|
||||
setVoiceErrorFading(true);
|
||||
voiceErrorFadeTimerRef.current = setTimeout(() => {
|
||||
setInlineError(null);
|
||||
setVoiceErrorFading(false);
|
||||
voiceErrorFadeTimerRef.current = null;
|
||||
}, VOICE_ERROR_FADE_MS);
|
||||
}, VOICE_ERROR_VISIBLE_MS);
|
||||
}, [clearVoiceErrorTimers, t]);
|
||||
// Setup blockers carry instructions users may need to keep in view while fixing them.
|
||||
if (key === "insecureContext" || key === "permission" || key === "notConfigured") {
|
||||
setVoiceSetupError(key);
|
||||
return;
|
||||
}
|
||||
showToast?.({ message: t(`thread.composer.voiceErrors.${key}`), tone: "error", dedupeKey: "voice-input" });
|
||||
}, [showToast, t]);
|
||||
const voiceRecorder = useVoiceRecorder({
|
||||
disabled: interactionDisabled,
|
||||
onClearError: clearInlineError,
|
||||
onClearError: clearVoiceSetupError,
|
||||
onError: setVoiceError,
|
||||
onTranscript: appendTranscription,
|
||||
onTranscribeAudio,
|
||||
wantsWav: transcriptionProvider === "xiaomi_mimo",
|
||||
});
|
||||
|
||||
useEffect(() => () => clearVoiceErrorTimers(), [clearVoiceErrorTimers]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!onTranscribeAudio) return;
|
||||
|
||||
@@ -1940,7 +1928,7 @@ export function ThreadComposer({
|
||||
: showStopButton ? "stop" : requiresModelSetup ? "setup" : canSend || !isStreaming ? "send" : "busy";
|
||||
const relaxedHeroInput = isHero && images.length === 0 && !isStreaming;
|
||||
const compactIdle = compactWhenIdle && !compactControls && !isHero && !composerFocused
|
||||
&& value.length === 0 && images.length === 0 && !inlineError
|
||||
&& value.length === 0 && images.length === 0 && !inlineError && !(onTranscribeAudio && voiceSetupError)
|
||||
&& !normalizedQuotedContext && !queuedPrompt
|
||||
&& !isDragging && !sessionDragPreview && !voiceRecorder.isRecording && !showProjectPicker;
|
||||
useLayoutEffect(() => {
|
||||
@@ -2229,16 +2217,9 @@ export function ThreadComposer({
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
{inlineError ? (
|
||||
<div
|
||||
role="alert"
|
||||
className={cn(
|
||||
"mx-3 mb-1 max-h-24 overflow-hidden rounded-md border border-destructive/40 bg-destructive/8 px-2.5 py-1",
|
||||
"text-[11.5px] font-medium text-destructive transition-[max-height,margin,padding,opacity] [transition-duration:220ms] ease-out motion-reduce:transition-none",
|
||||
voiceErrorFading && "mb-0 max-h-0 border-transparent py-0 opacity-0",
|
||||
)}
|
||||
>
|
||||
{inlineError}
|
||||
{inlineError || (onTranscribeAudio && voiceSetupError) ? (
|
||||
<div role="alert" className="mx-3 mb-1 break-words rounded-md border border-destructive/40 bg-destructive/8 px-2.5 py-1 text-[11.5px] font-medium text-destructive">
|
||||
{inlineError ?? t(`thread.composer.voiceErrors.${voiceSetupError}`)}
|
||||
</div>
|
||||
) : null}
|
||||
<div
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
.toast-card {
|
||||
border: 1px solid hsl(var(--border));
|
||||
border-radius: var(--radius-pill);
|
||||
background: hsl(var(--popover));
|
||||
color: hsl(var(--popover-foreground));
|
||||
box-shadow: 0 1px 2px rgb(0 0 0 / 0.04), 0 8px 24px -10px rgb(0 0 0 / 0.16);
|
||||
animation: toast-enter 180ms cubic-bezier(0.2, 0.8, 0.2, 1) both;
|
||||
}
|
||||
|
||||
.dark .toast-card {
|
||||
box-shadow: 0 1px 2px rgb(0 0 0 / 0.18), 0 8px 24px -8px rgb(0 0 0 / 0.45);
|
||||
}
|
||||
|
||||
.toast-card::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
z-index: -1;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
border-radius: inherit;
|
||||
--toast-sweep-width: 2.75rem;
|
||||
background-image: linear-gradient(var(--toast-sweep-direction, to right), transparent, hsl(var(--popover-foreground) / 0.055));
|
||||
background-repeat: no-repeat;
|
||||
background-size: var(--toast-sweep-width) 100%;
|
||||
animation: toast-shadow-sweep var(--toast-duration) linear both;
|
||||
animation-play-state: var(--toast-play-state);
|
||||
}
|
||||
|
||||
.toast-card:dir(rtl)::before {
|
||||
--toast-sweep-direction: to left;
|
||||
animation-direction: reverse;
|
||||
}
|
||||
|
||||
@keyframes toast-shadow-sweep {
|
||||
from { background-position: calc(0% - var(--toast-sweep-width)) 0; }
|
||||
to { background-position: calc(100% + var(--toast-sweep-width)) 0; }
|
||||
}
|
||||
|
||||
@keyframes toast-enter {
|
||||
from { opacity: 0; transform: translateY(-0.25rem); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.toast-card { animation: none; }
|
||||
.toast-card::before { content: none; }
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import { Check, Trash2, TriangleAlert } from "lucide-react";
|
||||
import { createContext, useCallback, useContext, useLayoutEffect, useRef, useState, type CSSProperties, type ReactNode, type Ref } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import "./toast.css";
|
||||
|
||||
const TOAST_NOTICE_MS = 3_000;
|
||||
export const TOAST_ACTION_MS = 8_000;
|
||||
|
||||
type ToastNotice = {
|
||||
message: string;
|
||||
detail?: string;
|
||||
tone: "success" | "error" | "pending";
|
||||
dedupeKey?: string;
|
||||
action?: { label: string; run: () => void };
|
||||
onExpire?: () => void;
|
||||
};
|
||||
|
||||
function toastDurationMs(notice: ToastNotice) {
|
||||
return notice.action ? TOAST_ACTION_MS : TOAST_NOTICE_MS;
|
||||
}
|
||||
|
||||
type ToastEntry = ToastNotice & { id: 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}>
|
||||
{children}
|
||||
</div>;
|
||||
}
|
||||
|
||||
function ToastCard({ notice, paused, onAction, onHoverChange, onFocusChange }: {
|
||||
notice: ToastNotice;
|
||||
paused: boolean;
|
||||
onAction: () => void;
|
||||
onHoverChange?: (hovered: boolean) => void;
|
||||
onFocusChange?: (focused: boolean) => void;
|
||||
}) {
|
||||
const { message, detail, tone, action } = notice;
|
||||
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>;
|
||||
}
|
||||
|
||||
type ToastFinishReason = "action" | "expired";
|
||||
|
||||
function TimedToast({ entry, finish, unavailable }: {
|
||||
entry: ToastEntry;
|
||||
finish: (entry: ToastEntry, reason: ToastFinishReason) => void;
|
||||
unavailable: boolean;
|
||||
}) {
|
||||
const [hovered, setHovered] = useState(false);
|
||||
const [focused, setFocused] = useState(false);
|
||||
const paused = unavailable || hovered || focused;
|
||||
useLayoutEffect(() => {
|
||||
if (!unavailable) return;
|
||||
setHovered(false);
|
||||
setFocused(false);
|
||||
}, [unavailable]);
|
||||
const remaining = useRef(toastDurationMs(entry));
|
||||
useLayoutEffect(() => {
|
||||
if (paused) return;
|
||||
const start = performance.now();
|
||||
const timer = window.setTimeout(() => finish(entry, "expired"), remaining.current);
|
||||
return () => {
|
||||
window.clearTimeout(timer);
|
||||
remaining.current = Math.max(0, remaining.current - (performance.now() - start));
|
||||
};
|
||||
}, [entry, finish, paused]);
|
||||
|
||||
return <ToastCard notice={entry} paused={paused} onAction={() => finish(entry, "action")}
|
||||
onHoverChange={entry.action ? setHovered : undefined} onFocusChange={entry.action ? setFocused : undefined} />;
|
||||
}
|
||||
|
||||
export function ToastProvider({ children }: { children: ReactNode }) {
|
||||
const [entries, setEntries] = useState<ToastEntry[]>([]);
|
||||
const [unavailable, setUnavailable] = useState(false);
|
||||
const viewportRef = useRef<HTMLDivElement>(null);
|
||||
useLayoutEffect(() => {
|
||||
const visibilityTree: HTMLElement[] = [];
|
||||
for (let node: HTMLElement | null = viewportRef.current; node; node = node.parentElement) visibilityTree.push(node);
|
||||
// Radix dialogs/sheets hide the surrounding tree; inactive remote hosts are inert.
|
||||
const update = () => setUnavailable(document.visibilityState === "hidden" || visibilityTree.some((node) => (
|
||||
node.getAttribute("aria-hidden") === "true" || node.hasAttribute("inert")
|
||||
)));
|
||||
const observer = new MutationObserver(update);
|
||||
for (const node of visibilityTree) observer.observe(node, { attributeFilter: ["aria-hidden", "inert"] });
|
||||
document.addEventListener("visibilitychange", update);
|
||||
update();
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
document.removeEventListener("visibilitychange", update);
|
||||
};
|
||||
}, []);
|
||||
const nextId = useRef(0);
|
||||
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) {
|
||||
for (const [id, entry] of live.current) {
|
||||
if (entry.dedupeKey === notice.dedupeKey && !entry.action && !entry.onExpire) live.current.delete(id);
|
||||
}
|
||||
}
|
||||
const entry = { ...notice, id: ++nextId.current };
|
||||
live.current.set(entry.id, entry);
|
||||
publish();
|
||||
}, [publish]);
|
||||
const finish = useCallback((entry: ToastEntry, reason: ToastFinishReason) => {
|
||||
if (!live.current.delete(entry.id)) return;
|
||||
publish();
|
||||
if (reason === "action") entry.action?.run();
|
||||
else entry.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} />)}
|
||||
</ToastViewport>
|
||||
</ToastContext.Provider>;
|
||||
}
|
||||
Reference in new issue
Block a user