feat(webui): unify file preview actions

This commit is contained in:
Xubin Ren committed 2026-09-24 15:17:05 +08:00
1 parent af5acabb33
commit 05bee21b10
24 files changed
+542 -10

No files matched your search

+129
View File
@@ -0,0 +1,129 @@
import { createContext, useContext, useEffect, useState, type ReactNode } from "react";
import { Copy, Ellipsis, PanelRight } from "lucide-react";
import { useTranslation } from "react-i18next";
import {
DropdownMenu, DropdownMenuContent, DropdownMenuItem,
DropdownMenuSeparator, DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { copyTextToClipboard } from "@/lib/clipboard";
import type { FileReferenceMetadata } from "@/lib/types";
interface FileActionsContextValue {
resolveMetadata: (path: string) => Promise<FileReferenceMetadata>;
openPreview: (path: string) => void;
}
const FileActionsContext = createContext<FileActionsContextValue | undefined>(undefined);
export const FileActionsProvider = FileActionsContext.Provider;
/** Shared by reply references, activity rows, and the preview header. */
export function FileActions({
path, children, onPreview, metadata,
}: {
path: string;
children?: ReactNode;
onPreview?: (path: string) => void;
metadata?: FileReferenceMetadata;
}) {
const context = useContext(FileActionsContext);
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const [resolved, setResolved] = useState<FileReferenceMetadata | null>(null);
const [loadFailed, setLoadFailed] = useState(false);
const [copyStatus, setCopyStatus] = useState<"copied" | "failed" | null>(null);
const resolveMetadata = context?.resolveMetadata;
useEffect(() => {
let cancelled = false;
setResolved(metadata ?? null);
setLoadFailed(false);
setCopyStatus(null);
if (open && !metadata && resolveMetadata) {
void resolveMetadata(path).then((value) => {
if (typeof value.path !== "string" || !(value.relative_path === null || typeof value.relative_path === "string")) {
throw new Error("File metadata is unavailable on this gateway");
}
if (!cancelled) setResolved(value);
}).catch(() => { if (!cancelled) setLoadFailed(true); });
}
return () => { cancelled = true; };
}, [open, path, metadata, resolveMetadata]);
const enabled = Boolean(context || onPreview || metadata);
const copy = async (value: string) => {
const success = await copyTextToClipboard(value);
setCopyStatus(success ? "copied" : "failed");
};
const preview = onPreview ? context?.openPreview ?? onPreview : undefined;
return (
<DropdownMenu open={open} onOpenChange={setOpen}>
<span
className="not-prose inline-flex max-w-full items-baseline gap-0.5 align-baseline"
onContextMenu={(event) => {
if (!enabled) return;
event.preventDefault();
event.stopPropagation();
setOpen(true);
}}
onKeyDown={(event) => {
if (!enabled) return;
if (event.key === "ContextMenu" || (event.key === "F10" && event.shiftKey)) {
event.preventDefault();
event.stopPropagation();
setOpen(true);
}
}}
>
{children}
{enabled ? <DropdownMenuTrigger asChild>
<button
type="button"
aria-label={t("fileActions.menu", { name: path.split(/[\\/]/).pop() || path })}
title={t("fileActions.title")}
onClick={(event) => event.stopPropagation()}
className="inline-flex h-6 w-6 shrink-0 items-center justify-center self-center rounded-md text-muted-foreground/65 transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<Ellipsis className="h-3.5 w-3.5" aria-hidden />
</button>
</DropdownMenuTrigger> : null}
{enabled ? <DropdownMenuContent align="end" collisionPadding={12} onClick={(event) => event.stopPropagation()}>
{preview ? <>
<DropdownMenuItem onSelect={() => preview(path)}>
<PanelRight className="mr-2 h-4 w-4" aria-hidden />
{t("fileActions.preview")}
</DropdownMenuItem>
<DropdownMenuSeparator />
</> : null}
<DropdownMenuItem disabled={!resolved} onSelect={(event) => {
event.preventDefault();
if (resolved) void copy(resolved.path);
}}>
<Copy className="mr-2 h-4 w-4" aria-hidden />
{t("fileActions.copyAbsolute")}
</DropdownMenuItem>
<DropdownMenuItem disabled={!resolved?.relative_path} onSelect={(event) => {
event.preventDefault();
if (resolved?.relative_path) void copy(resolved.relative_path);
}}>
<Copy className="mr-2 h-4 w-4" aria-hidden />
{t("fileActions.copyRelative")}
</DropdownMenuItem>
{!resolved ? <DropdownMenuItem onSelect={(event) => {
event.preventDefault();
void copy(path);
}}>{t("fileActions.copyReference")}</DropdownMenuItem> : null}
<div role="status" className="max-w-64 px-2.5 py-1.5 text-xs text-muted-foreground">
{copyStatus ? t(`fileActions.${copyStatus}`)
: loadFailed ? t("fileActions.unavailable")
: !resolved && resolveMetadata ? t("fileActions.loading")
: t("fileActions.gatewayPath")}
</div>
</DropdownMenuContent> : null}
</span>
</DropdownMenu>
);
}
+13 -1
View File
@@ -4,9 +4,10 @@ import { AlertCircle, ChevronRight, Loader2, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { CodeBlock } from "@/components/CodeBlock";
import { FileActions } from "@/components/FileActions";
import { splitFilePath } from "@/components/FileReferenceChip";
import { ApiError, fetchFilePreview } from "@/lib/api";
import type { FilePreviewPayload } from "@/lib/types";
import type { FilePreviewPayload, FileReferenceMetadata } from "@/lib/types";
import { cn } from "@/lib/utils";
interface FilePreviewPanelProps {
@@ -64,6 +65,16 @@ export function FilePreviewPanel({
}, [path, sessionKey]);
const displayPath = state.status === "ready" ? state.payload.display_path : path;
const metadata = useMemo<FileReferenceMetadata | undefined>(() => {
if (state.status !== "ready") return undefined;
const { path: absolute, project_path: root, display_path: relative } = state.payload;
// display_path is absolute for files outside the session project (e.g. media).
const normalizedRoot = root?.replace(/\\/g, "/").replace(/\/+$/, "");
return {
path: absolute,
relative_path: normalizedRoot != null && absolute.replace(/\\/g, "/").startsWith(`${normalizedRoot}/`) ? relative : null,
};
}, [state]);
const previewPath = state.status === "ready" ? state.payload.path : displayPath;
const normalizedPreviewPath = previewPath.replace(/\\/g, "/");
const hasRootPrefix = normalizedPreviewPath.startsWith("/");
@@ -201,6 +212,7 @@ export function FilePreviewPanel({
);
})}
</nav>
{metadata ? <FileActions path={previewPath} metadata={metadata} /> : null}
<button
type="button"
onClick={onClose}
@@ -1,4 +1,5 @@
import type { KeyboardEvent, MouseEvent } from "react";
import { FileActions } from "@/components/FileActions";
import {
Tooltip,
@@ -60,6 +61,7 @@ export function FileReferenceChip({
openPreview(event);
};
return (
<FileActions path={targetPath} onPreview={onOpen}>
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
@@ -120,6 +122,7 @@ export function FileReferenceChip({
</TooltipContent>
</Tooltip>
</TooltipProvider>
</FileActions>
);
}
@@ -5,6 +5,7 @@ import { useTranslation } from "react-i18next";
import { FilePreviewAvailabilityProvider } from "@/components/FilePreviewAvailabilityContext";
import { FilePreviewPanel } from "@/components/FilePreviewPanel";
import { FileActionsProvider } from "@/components/FileActions";
import { SessionHandleLabel } from "@/components/SessionHandleLabel";
import { PromptNavigator } from "@/components/thread/PromptNavigator";
import { ModelFallbackNotice } from "@/components/thread/ModelFallbackNotice";
@@ -28,6 +29,7 @@ import { useFilePreviewState, type FilePreviewStore } from "@/hooks/useFilePrevi
import {
ApiError,
fetchFilePreviewAvailability,
fetchFileReferenceMetadata,
fetchInstalledCliApps,
fetchMcpPresets,
fetchSettings,
@@ -48,6 +50,7 @@ import type { CanonicalRunSnapshot, StreamError } from "@/lib/nanobot-client";
import type {
ChatSummary,
FilePreviewPayload,
FileReferenceMetadata,
RoundUsage,
SettingsPayload,
SlashCommand,
@@ -1525,6 +1528,21 @@ export function ThreadShell({
const openFilePreviewRef = useRef(handleOpenFilePreview);
openFilePreviewRef.current = handleOpenFilePreview;
const openFilePreview = useCallback((path: string) => openFilePreviewRef.current(path), []);
const resolveFileMetadata = useCallback((path: string) => {
if (!previewSessionKey) return Promise.reject(new Error("No active session"));
return temporary
? client.requestMutation<FileReferenceMetadata>("temporary_chat.file_preview", {
chat_id: chatId, path, metadata: true,
})
: fetchFileReferenceMetadata(getToken(), previewSessionKey, path);
}, [chatId, client, getToken, previewSessionKey, temporary]);
const fileActions = useMemo(() => ({
resolveMetadata: resolveFileMetadata,
// A menu's explicit Preview action should not toggle an already-open file closed.
openPreview: (path: string) => {
if (path !== filePreviewPath || filePreviewClosing) openFilePreview(path);
},
}), [filePreviewClosing, filePreviewPath, openFilePreview, resolveFileMetadata]);
useEffect(() => {
if (!filePreviewPath || !headerActive) return;
@@ -1814,6 +1832,7 @@ export function ThreadShell({
<FilePreviewAvailabilityProvider
resolve={previewSessionKey ? resolveFilePreviewAvailability : undefined}
>
<FileActionsProvider value={previewSessionKey ? fileActions : undefined}>
<ThreadViewport
ref={viewportRef}
messages={displayMessages}
@@ -1842,6 +1861,7 @@ export function ThreadShell({
onForkFromMessage={onForkChat ? handleForkFromMessage : undefined}
onQuoteSelection={session ? handleQuoteSelection : undefined}
/>
</FileActionsProvider>
</FilePreviewAvailabilityProvider>
</div>
{headerPortalTarget && headerActive