feat(webui): polish tabbed previews and image presentation
This commit is contained in:
1 parent
fccf415283
commit
b555164a17
41 files changed
+1459
-621
No files matched your search
@@ -8,6 +8,7 @@
|
||||
"@radix-ui/react-alert-dialog": "^1.1.4",
|
||||
"@radix-ui/react-dialog": "^1.1.4",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.4",
|
||||
"@radix-ui/react-menu": "2.1.16",
|
||||
"@radix-ui/react-popover": "1.1.15",
|
||||
"@radix-ui/react-select": "2.2.6",
|
||||
"@radix-ui/react-slot": "^1.1.1",
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
"@radix-ui/react-alert-dialog": "^1.1.4",
|
||||
"@radix-ui/react-dialog": "^1.1.4",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.4",
|
||||
"@radix-ui/react-menu": "2.1.16",
|
||||
"@radix-ui/react-popover": "1.1.15",
|
||||
"@radix-ui/react-select": "2.2.6",
|
||||
"@radix-ui/react-slot": "^1.1.1",
|
||||
|
||||
@@ -4,6 +4,9 @@ import { useTranslation } from "react-i18next";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { UIMediaAttachment } from "@/lib/types";
|
||||
import { ImageThumbnail } from "@/components/ImageGallery";
|
||||
import { ImageLightbox } from "@/components/ImageLightbox";
|
||||
import { useRegisterInlineImage } from "@/components/InlineImageContext";
|
||||
|
||||
interface AttachmentTileProps {
|
||||
attachment: UIMediaAttachment;
|
||||
@@ -14,41 +17,22 @@ interface AttachmentTileProps {
|
||||
|
||||
export function AttachmentTile({ attachment, className, inline = false, variant = "default" }: AttachmentTileProps) {
|
||||
const { t } = useTranslation();
|
||||
const [failed, setFailed] = useState(false);
|
||||
const [failedUrl, setFailedUrl] = useState<string | undefined>(undefined);
|
||||
const failed = !!attachment.url && failedUrl === attachment.url;
|
||||
const [imageOpen, setImageOpen] = useState(false);
|
||||
const hasUrl = typeof attachment.url === "string" && attachment.url.length > 0;
|
||||
const label = attachmentLabel(attachment, t);
|
||||
useRegisterInlineImage(inline && attachment.kind === "image" && hasUrl && !failed ? attachment.url : undefined);
|
||||
|
||||
if (attachment.kind === "image" && hasUrl && !failed) {
|
||||
return (
|
||||
<AttachmentFrame
|
||||
attachment={attachment}
|
||||
className={className}
|
||||
inline={inline}
|
||||
variant={variant}
|
||||
>
|
||||
<a
|
||||
href={attachment.url}
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
className="block bg-muted/20"
|
||||
aria-label={attachment.name
|
||||
? t("message.openAttachment", { name: attachment.name })
|
||||
: t("lightbox.open", { defaultValue: "Open image" })}
|
||||
>
|
||||
<img
|
||||
src={attachment.url}
|
||||
alt={attachment.name ?? ""}
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
draggable={false}
|
||||
onError={() => setFailed(true)}
|
||||
className={cn(
|
||||
"block h-auto max-w-full bg-background object-contain",
|
||||
variant === "compact" ? "max-h-40" : "max-h-[34rem]",
|
||||
)}
|
||||
/>
|
||||
</a>
|
||||
</AttachmentFrame>
|
||||
<span className={cn("not-prose my-3 block max-w-full", className)}>
|
||||
<ImageThumbnail key={attachment.url} image={attachment}
|
||||
size={variant === "compact" ? "compact" : "large"}
|
||||
onOpen={() => setImageOpen(true)} onError={() => setFailedUrl(attachment.url)} />
|
||||
<ImageLightbox images={[attachment]} index={imageOpen ? 0 : null}
|
||||
onIndexChange={() => {}} onOpenChange={setImageOpen} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,31 +1,36 @@
|
||||
import { createContext, useContext, useEffect, useState, type ReactNode } from "react";
|
||||
import { Copy, Ellipsis, PanelRight } from "lucide-react";
|
||||
import { createContext, useContext, useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import * as Menu from "@radix-ui/react-menu";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import {
|
||||
DropdownMenu, DropdownMenuContent, DropdownMenuItem,
|
||||
DropdownMenuSeparator, DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { floatingItemClassName, floatingItemFocusClassName, floatingSurfaceClassName, floatingSurfaceMotionClassName } from "@/components/ui/floating-surface";
|
||||
import { useFloatingPortal } from "@/components/ui/floating-portal";
|
||||
import { copyTextToClipboard } from "@/lib/clipboard";
|
||||
import type { FileReferenceMetadata } from "@/lib/types";
|
||||
import type { FileReferenceMetadata, FilePreviewPayload } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface FileActionsContextValue {
|
||||
resolveMetadata: (path: string) => Promise<FileReferenceMetadata>;
|
||||
openPreview: (path: string) => void;
|
||||
loadPreview?: (path: string) => Promise<FilePreviewPayload>;
|
||||
}
|
||||
|
||||
const FileActionsContext = createContext<FileActionsContextValue | undefined>(undefined);
|
||||
|
||||
export const FileActionsProvider = FileActionsContext.Provider;
|
||||
|
||||
/** Shared by reply references, activity rows, and the preview header. */
|
||||
export function useFilePreviewLoader() {
|
||||
return useContext(FileActionsContext)?.loadPreview;
|
||||
}
|
||||
|
||||
const itemClassName = `${floatingItemClassName} ${floatingItemFocusClassName} cursor-default data-[disabled]:pointer-events-none data-[disabled]:opacity-50`;
|
||||
|
||||
/** Copy-only context menu, shared by file references and preview tabs. */
|
||||
export function FileActions({
|
||||
path, children, onPreview, metadata,
|
||||
path, children, metadata, className,
|
||||
}: {
|
||||
path: string;
|
||||
children?: ReactNode;
|
||||
onPreview?: (path: string) => void;
|
||||
children: ReactNode;
|
||||
metadata?: FileReferenceMetadata;
|
||||
className?: string;
|
||||
}) {
|
||||
const context = useContext(FileActionsContext);
|
||||
const { t } = useTranslation();
|
||||
@@ -34,6 +39,11 @@ export function FileActions({
|
||||
const [loadFailed, setLoadFailed] = useState(false);
|
||||
const [copyStatus, setCopyStatus] = useState<"copied" | "failed" | null>(null);
|
||||
const resolveMetadata = context?.resolveMetadata;
|
||||
const portal = useFloatingPortal();
|
||||
const point = useRef({ x: 0, y: 0 });
|
||||
const anchor = useRef({ getBoundingClientRect: () => new DOMRect(point.current.x, point.current.y, 0, 0) });
|
||||
const opener = useRef<HTMLElement | null>(null);
|
||||
const interactedOutside = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
@@ -51,79 +61,72 @@ export function FileActions({
|
||||
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");
|
||||
if (success) setOpen(false);
|
||||
};
|
||||
const preview = onPreview ? context?.openPreview ?? onPreview : undefined;
|
||||
const openMenu = (target: EventTarget, x: number, y: number) => {
|
||||
point.current = { x, y };
|
||||
opener.current = target instanceof Element ? target.closest<HTMLElement>("button, a, [tabindex]") : null;
|
||||
interactedOutside.current = false;
|
||||
setOpen(true);
|
||||
};
|
||||
const status = copyStatus ?? (loadFailed ? "unavailable" : !resolved && resolveMetadata ? "loading" : null);
|
||||
|
||||
return (
|
||||
<DropdownMenu open={open} onOpenChange={setOpen}>
|
||||
<Menu.Root open={open} onOpenChange={setOpen}>
|
||||
<Menu.Anchor virtualRef={anchor} />
|
||||
<span
|
||||
className="not-prose inline-flex max-w-full items-baseline gap-0.5 align-baseline"
|
||||
className={cn("not-prose inline-flex max-w-full items-baseline align-baseline", className)}
|
||||
onContextMenu={(event) => {
|
||||
if (!enabled) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
setOpen(true);
|
||||
openMenu(event.target, event.clientX, event.clientY);
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (!enabled) return;
|
||||
if (event.key === "ContextMenu" || (event.key === "F10" && event.shiftKey)) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
setOpen(true);
|
||||
const bounds = event.currentTarget.getBoundingClientRect();
|
||||
openMenu(event.target, bounds.left, bounds.bottom);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{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) => {
|
||||
</span>
|
||||
<Menu.Portal container={portal ?? undefined}>
|
||||
<Menu.Content aria-label={t("fileActions.menu", { name: path.split(/[\\/]/).pop() || path })}
|
||||
align="start" sideOffset={4} collisionPadding={12}
|
||||
className={cn(floatingSurfaceClassName, floatingSurfaceMotionClassName, "min-w-40 rounded-control p-1 [&_[role=menuitem]]:py-1.5")}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
onContextMenu={(event) => { event.preventDefault(); event.stopPropagation(); }}
|
||||
onInteractOutside={() => { interactedOutside.current = true; }}
|
||||
onCloseAutoFocus={(event) => {
|
||||
event.preventDefault();
|
||||
if (!interactedOutside.current) opener.current?.focus();
|
||||
}}>
|
||||
<Menu.Item className={itemClassName} 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) => {
|
||||
</Menu.Item>
|
||||
<Menu.Item className={itemClassName} 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) => {
|
||||
</Menu.Item>
|
||||
{!resolved ? <Menu.Item className={itemClassName} 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>
|
||||
}}>{t("fileActions.copyReference")}</Menu.Item> : null}
|
||||
{status ? <div role="status" className="max-w-64 px-2.5 py-1.5 text-xs text-muted-foreground">
|
||||
{t(`fileActions.${status}`)}
|
||||
</div> : null}
|
||||
</Menu.Content>
|
||||
</Menu.Portal>
|
||||
</Menu.Root>
|
||||
);
|
||||
}
|
||||
@@ -1,24 +1,19 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import type { CSSProperties, PointerEvent as ReactPointerEvent } from "react";
|
||||
import { AlertCircle, ChevronRight, Loader2, X } from "lucide-react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { AlertCircle } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { CodeBlock } from "@/components/CodeBlock";
|
||||
import { FileActions } from "@/components/FileActions";
|
||||
import { splitFilePath } from "@/components/FileReferenceChip";
|
||||
import { ImageLightbox } from "@/components/ImageLightbox";
|
||||
import { fileKindForPath, splitFilePath } from "@/components/FileReferenceChip";
|
||||
import { ApiError, fetchFilePreview } from "@/lib/api";
|
||||
import type { FilePreviewPayload, FileReferenceMetadata } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { FilePreviewPayload } from "@/lib/types";
|
||||
|
||||
interface FilePreviewPanelProps {
|
||||
sessionKey: string;
|
||||
path: string;
|
||||
token: string;
|
||||
loadPreview?: (path: string) => Promise<FilePreviewPayload>;
|
||||
desktopWidth?: number;
|
||||
isClosing?: boolean;
|
||||
onResizeStart?: (event: ReactPointerEvent<HTMLButtonElement>) => void;
|
||||
onClose: () => void;
|
||||
initialPreview?: FilePreviewPayload;
|
||||
}
|
||||
|
||||
type PreviewState =
|
||||
@@ -31,28 +26,22 @@ export function FilePreviewPanel({
|
||||
path,
|
||||
token,
|
||||
loadPreview,
|
||||
desktopWidth = 544,
|
||||
isClosing = false,
|
||||
onResizeStart,
|
||||
onClose,
|
||||
initialPreview,
|
||||
}: FilePreviewPanelProps) {
|
||||
const { t } = useTranslation();
|
||||
const [state, setState] = useState<PreviewState>({ status: "loading" });
|
||||
const [entered, setEntered] = useState(false);
|
||||
const tokenRef = useRef(token);
|
||||
tokenRef.current = token;
|
||||
const loadPreviewRef = useRef(loadPreview);
|
||||
loadPreviewRef.current = loadPreview;
|
||||
|
||||
useEffect(() => {
|
||||
const frame = window.requestAnimationFrame(() => setEntered(true));
|
||||
return () => window.cancelAnimationFrame(frame);
|
||||
}, []);
|
||||
const [state, setState] = useState<PreviewState>(() => initialPreview
|
||||
? { status: "ready", payload: initialPreview } : { status: "loading" });
|
||||
const [imageOpen, setImageOpen] = useState(false);
|
||||
// Cache aging must not restart an already open preview on unrelated rerenders.
|
||||
const initialPreviewRef = useRef(initialPreview);
|
||||
initialPreviewRef.current = initialPreview;
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
setState({ status: "loading" });
|
||||
(loadPreviewRef.current?.(path) ?? fetchFilePreview(tokenRef.current, sessionKey, path))
|
||||
setImageOpen(false);
|
||||
const cached = initialPreviewRef.current;
|
||||
setState(cached ? { status: "ready", payload: cached } : { status: "loading" });
|
||||
(loadPreview?.(path) ?? fetchFilePreview(token, sessionKey, path))
|
||||
.then((payload) => {
|
||||
if (!cancelled) setState({ status: "ready", payload });
|
||||
})
|
||||
@@ -62,45 +51,11 @@ export function FilePreviewPanel({
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [path, sessionKey]);
|
||||
}, [path, sessionKey, token, loadPreview]);
|
||||
|
||||
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("/");
|
||||
const { name } = splitFilePath(displayPath);
|
||||
const fileName = name || displayPath;
|
||||
const pathParts = useMemo(
|
||||
() => normalizedPreviewPath.split("/").filter(Boolean),
|
||||
[normalizedPreviewPath],
|
||||
);
|
||||
const directoryParts = useMemo(
|
||||
() => (pathParts.length > 1 ? pathParts.slice(0, -1) : []),
|
||||
[pathParts],
|
||||
);
|
||||
const breadcrumbParts = useMemo(
|
||||
() => (directoryParts.length > 0 ? [...directoryParts, fileName] : [fileName]),
|
||||
[directoryParts, fileName],
|
||||
);
|
||||
const compactBreadcrumbParts = useMemo(
|
||||
() => (breadcrumbParts.length > 3 ? breadcrumbParts.slice(-3) : breadcrumbParts),
|
||||
[breadcrumbParts],
|
||||
);
|
||||
const hasCompactPrefix = breadcrumbParts.length > compactBreadcrumbParts.length;
|
||||
const breadcrumbTitle = `${hasRootPrefix ? "/" : ""}${[
|
||||
...directoryParts,
|
||||
fileName,
|
||||
].join("/")}`;
|
||||
const errorMessage = state.status === "error"
|
||||
? (state.error instanceof ApiError
|
||||
? (state.error.status === 404 && /API route not found/i.test(state.error.message)
|
||||
@@ -112,128 +67,17 @@ export function FilePreviewPanel({
|
||||
: null;
|
||||
|
||||
return (
|
||||
<aside
|
||||
aria-label={t("filePreview.aria", { defaultValue: "File preview" })}
|
||||
style={{
|
||||
"--file-preview-width": `${desktopWidth}px`,
|
||||
"--file-preview-slot-width": !entered || isClosing ? "0px" : `${desktopWidth}px`,
|
||||
"--file-preview-mobile-width": !entered || isClosing ? "0px" : "100%",
|
||||
} as CSSProperties}
|
||||
className={cn(
|
||||
"absolute inset-y-0 right-0 z-30 w-[var(--file-preview-mobile-width)] overflow-hidden",
|
||||
"transition-[width] duration-300 ease-out will-change-[width]",
|
||||
"md:relative md:z-auto md:w-[var(--file-preview-slot-width)] md:min-w-0 md:shrink-0",
|
||||
isClosing && "pointer-events-none",
|
||||
)}
|
||||
data-testid="file-preview-panel"
|
||||
data-file-preview-panel
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"absolute inset-y-0 right-0 flex w-screen flex-col overflow-hidden pb-[env(safe-area-inset-bottom)] md:w-[var(--file-preview-width)] md:pb-0",
|
||||
"border-l border-border/70 bg-background shadow-2xl md:shadow-none",
|
||||
"transition-[opacity,transform] duration-300 ease-out will-change-transform",
|
||||
!entered || isClosing ? "translate-x-full opacity-0" : "translate-x-0 opacity-100",
|
||||
"motion-reduce:translate-x-0",
|
||||
)}
|
||||
>
|
||||
{onResizeStart ? (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("filePreview.resize", { defaultValue: "Resize file preview" })}
|
||||
className={cn(
|
||||
"group absolute inset-y-0 left-0 z-20 hidden w-3 -translate-x-1/2 cursor-col-resize touch-none md:flex",
|
||||
"items-stretch justify-center focus-visible:outline-none",
|
||||
)}
|
||||
onPointerDown={onResizeStart}
|
||||
>
|
||||
<span
|
||||
aria-hidden
|
||||
className={cn(
|
||||
"h-full w-px bg-foreground/25 opacity-0 transition-opacity",
|
||||
"group-hover:opacity-100 group-focus-visible:bg-ring group-focus-visible:opacity-100",
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
) : null}
|
||||
<div className="flex min-h-0 flex-1 flex-col">
|
||||
<div
|
||||
className="flex h-11 shrink-0 items-center gap-2 border-b border-border/60 px-3"
|
||||
title={previewPath}
|
||||
>
|
||||
<nav
|
||||
aria-label={t("filePreview.breadcrumb", { defaultValue: "File path" })}
|
||||
className="flex min-w-0 flex-1 items-center overflow-hidden text-sm leading-5"
|
||||
title={breadcrumbTitle}
|
||||
data-testid="file-preview-breadcrumb"
|
||||
>
|
||||
{hasCompactPrefix ? (
|
||||
<>
|
||||
<span className="shrink-0 text-muted-foreground/55">...</span>
|
||||
<ChevronRight
|
||||
className="mx-1 h-3.5 w-3.5 shrink-0 text-muted-foreground/35"
|
||||
aria-hidden
|
||||
/>
|
||||
</>
|
||||
) : hasRootPrefix ? (
|
||||
<>
|
||||
<span className="shrink-0 text-muted-foreground/55">/</span>
|
||||
<ChevronRight
|
||||
className="mx-1 h-3.5 w-3.5 shrink-0 text-muted-foreground/35"
|
||||
aria-hidden
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
{compactBreadcrumbParts.map((part, index) => {
|
||||
const isLast = index === compactBreadcrumbParts.length - 1;
|
||||
return (
|
||||
<span
|
||||
key={`${part}-${index}`}
|
||||
className="flex min-w-0 items-center overflow-hidden"
|
||||
>
|
||||
{index > 0 ? (
|
||||
<ChevronRight
|
||||
className="mx-1 h-3.5 w-3.5 shrink-0 text-muted-foreground/35"
|
||||
aria-hidden
|
||||
/>
|
||||
) : null}
|
||||
<span
|
||||
className={cn(
|
||||
"min-w-0 truncate rounded-mark px-1 py-0.5",
|
||||
isLast
|
||||
? "font-medium text-foreground"
|
||||
: "max-w-[26vw] shrink text-muted-foreground/78",
|
||||
)}
|
||||
data-testid={isLast ? "file-preview-title" : undefined}
|
||||
>
|
||||
{part}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
{metadata ? <FileActions path={previewPath} metadata={metadata} /> : null}
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className={cn(
|
||||
"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md",
|
||||
"text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",
|
||||
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
|
||||
)}
|
||||
title={t("filePreview.close", { defaultValue: "Close file preview" })}
|
||||
aria-label={t("filePreview.close", { defaultValue: "Close file preview" })}
|
||||
data-testid="file-preview-close"
|
||||
>
|
||||
<X className="h-4 w-4" aria-hidden />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<section aria-label={t("filePreview.aria")} data-testid="file-preview-panel" className="flex min-h-0 flex-1 flex-col">
|
||||
<div className="min-h-0 flex-1 overflow-auto">
|
||||
{state.status === "loading" ? (
|
||||
<div className="flex h-full items-center justify-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" aria-hidden />
|
||||
{t("filePreview.loading", { defaultValue: "Loading preview..." })}
|
||||
<div role="status" aria-label={t("filePreview.loading", { defaultValue: "Loading preview..." })}
|
||||
className="flex h-full flex-col justify-center gap-3 p-6" aria-busy="true">
|
||||
<span className="sr-only">{t("filePreview.loading", { defaultValue: "Loading preview..." })}</span>
|
||||
<div aria-hidden className="mx-auto w-full max-w-sm space-y-3 animate-pulse [animation-duration:900ms] motion-reduce:animate-none">
|
||||
{fileKindForPath(path) === "image" ? <div className="aspect-[8/5] rounded-compact bg-muted/40" />
|
||||
: <>{["w-2/3", "w-full", "w-5/6", "w-3/4"].map((width) =>
|
||||
<div key={width} className={`h-1.5 rounded-full bg-muted/40 ${width}`} />)}</>}
|
||||
</div>
|
||||
</div>
|
||||
) : state.status === "error" ? (
|
||||
<div className="flex h-full items-center justify-center px-8 text-center text-sm text-muted-foreground">
|
||||
@@ -247,12 +91,17 @@ export function FilePreviewPanel({
|
||||
</div>
|
||||
) : state.payload.kind === "image" ? (
|
||||
<div className="flex min-h-full items-center justify-center p-4">
|
||||
<img
|
||||
<button type="button" aria-label={`${t("lightbox.open")}: ${fileName}`} onClick={() => setImageOpen(true)}
|
||||
className="flex max-h-full max-w-full cursor-zoom-in items-center justify-center rounded-compact focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
|
||||
<img
|
||||
src={state.payload.data_url}
|
||||
alt={fileName}
|
||||
className="max-h-full max-w-full object-contain"
|
||||
onError={() => setState({ status: "error", error: new Error("Invalid image") })}
|
||||
/>
|
||||
/>
|
||||
</button>
|
||||
<ImageLightbox images={[{ url: state.payload.data_url, name: fileName }]} index={imageOpen ? 0 : null}
|
||||
onIndexChange={() => {}} onOpenChange={setImageOpen} />
|
||||
</div>
|
||||
) : (
|
||||
<div className="min-h-full">
|
||||
@@ -275,8 +124,6 @@ export function FilePreviewPanel({
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
import type { KeyboardEvent, MouseEvent } from "react";
|
||||
import { FileActions } from "@/components/FileActions";
|
||||
import { useEffect, useState, type KeyboardEvent, type MouseEvent } from "react";
|
||||
import { ImageIcon } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FileActions, useFilePreviewLoader } from "@/components/FileActions";
|
||||
import { inferMediaKind } from "@/lib/media";
|
||||
|
||||
import {
|
||||
Tooltip,
|
||||
@@ -13,6 +16,7 @@ export type FileReferenceKind =
|
||||
| "default"
|
||||
| "css"
|
||||
| "html"
|
||||
| "image"
|
||||
| "javascript"
|
||||
| "json"
|
||||
| "markdown"
|
||||
@@ -44,16 +48,20 @@ export function FileReferenceChip({
|
||||
onOpen,
|
||||
testId = "inline-file-path",
|
||||
}: FileReferenceChipProps) {
|
||||
const { t } = useTranslation();
|
||||
const [tooltipOpen, setTooltipOpen] = useState(false);
|
||||
const { directory, name } = splitFilePath(path);
|
||||
const kind = fileKindForPath(path);
|
||||
const displayText = display === "path" ? path.replace(/\\/g, "/") : name;
|
||||
const fullPath = tooltipPath || path;
|
||||
const targetPath = previewPath || tooltipPath || path;
|
||||
const kind = fileKindForPath(targetPath);
|
||||
const interactive = Boolean(onOpen);
|
||||
const imageQuickLook = kind === "image" && interactive;
|
||||
const openPreview = (event: MouseEvent | KeyboardEvent) => {
|
||||
if (!onOpen) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
setTooltipOpen(false);
|
||||
onOpen(targetPath);
|
||||
};
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
@@ -61,11 +69,12 @@ export function FileReferenceChip({
|
||||
openPreview(event);
|
||||
};
|
||||
return (
|
||||
<FileActions path={targetPath} onPreview={onOpen}>
|
||||
<FileActions path={targetPath}>
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<Tooltip open={tooltipOpen} onOpenChange={setTooltipOpen}>
|
||||
<TooltipTrigger asChild>
|
||||
<span
|
||||
onContextMenuCapture={() => setTooltipOpen(false)}
|
||||
className={cn("not-prose inline-flex max-w-full align-baseline leading-[inherit]", className)}
|
||||
>
|
||||
<span
|
||||
@@ -108,17 +117,21 @@ export function FileReferenceChip({
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent
|
||||
aria-label={imageQuickLook ? t("filePreview.aria") : undefined}
|
||||
side="top"
|
||||
align="center"
|
||||
sideOffset={8}
|
||||
collisionPadding={12}
|
||||
className={cn(
|
||||
"max-w-[min(38rem,calc(100vw-2rem))] rounded-control",
|
||||
"px-2.5 py-1.5",
|
||||
"break-all font-mono text-[11px] leading-snug text-popover-foreground",
|
||||
"rounded-control text-popover-foreground",
|
||||
imageQuickLook
|
||||
? "w-max max-w-[calc(100vw-2rem)] p-2"
|
||||
: "max-w-[min(38rem,calc(100vw-2rem))] break-all px-2.5 py-1.5 font-mono text-[11px] leading-snug",
|
||||
)}
|
||||
>
|
||||
{fullPath}
|
||||
{imageQuickLook
|
||||
? tooltipOpen ? <FileImageQuickLook key={targetPath} path={targetPath} /> : null
|
||||
: fullPath}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
@@ -126,6 +139,29 @@ export function FileReferenceChip({
|
||||
);
|
||||
}
|
||||
|
||||
/** Only loads after the normal hover/focus delay, through the session's guarded preview API. */
|
||||
function FileImageQuickLook({ path }: { path: string }) {
|
||||
const { t } = useTranslation();
|
||||
const load = useFilePreviewLoader();
|
||||
const [result, setResult] = useState<{ load: typeof load; source: string | null }>();
|
||||
const source = result?.load === load ? result?.source : undefined;
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
void load?.(path).then((payload) => {
|
||||
if (!cancelled) setResult({ load, source: payload.kind === "image" ? payload.data_url : null });
|
||||
}).catch(() => { if (!cancelled) setResult({ load, source: null }); });
|
||||
return () => { cancelled = true; };
|
||||
}, [path, load]);
|
||||
if (!load || source === null) return <span className="block px-1 py-1 text-xs text-muted-foreground">
|
||||
{t("filePreview.failed", { defaultValue: "Could not preview this file." })}
|
||||
</span>;
|
||||
return <span data-testid="file-image-quick-look" className="block w-max max-w-full overflow-hidden rounded-mark" aria-hidden>
|
||||
{source ? <img src={source} alt="" decoding="async" draggable={false}
|
||||
className="block h-auto max-h-36 w-auto max-w-[min(14rem,calc(100vw-3rem))] rounded-mark object-contain" onError={() => setResult({ load, source: null })} />
|
||||
: <span className="block h-36 w-56 max-w-[calc(100vw-3rem)] animate-pulse bg-muted/40 motion-reduce:animate-none" />}
|
||||
</span>;
|
||||
}
|
||||
|
||||
export function isLikelyFilePath(value: string): boolean {
|
||||
const raw = value.trim();
|
||||
if (!raw || raw.includes("\n")) return false;
|
||||
@@ -155,7 +191,8 @@ export function splitFilePath(path: string): { directory: string; name: string }
|
||||
};
|
||||
}
|
||||
|
||||
function fileKindForPath(path: string): FileReferenceKind {
|
||||
export function fileKindForPath(path: string): FileReferenceKind {
|
||||
if (inferMediaKind({ url: path }) === "image") return "image";
|
||||
const normalized = path.toLowerCase();
|
||||
const name = normalized.split(/[\\/]/).pop() ?? normalized;
|
||||
const ext = name.includes(".") ? name.split(".").pop() ?? "" : "";
|
||||
@@ -197,7 +234,8 @@ function fileKindForPath(path: string): FileReferenceKind {
|
||||
}
|
||||
}
|
||||
|
||||
function FileReferenceIcon({ kind, interactive }: { kind: FileReferenceKind; interactive: boolean }) {
|
||||
export function FileReferenceIcon({ kind, interactive }: { kind: FileReferenceKind; interactive: boolean }) {
|
||||
if (kind === "image") return <ImageIcon aria-hidden className="h-[1em] w-[1em] shrink-0 translate-y-[0.12em]" />;
|
||||
if (kind === "python") {
|
||||
return (
|
||||
<svg
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { useState } from "react";
|
||||
import { ImageIcon } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { ImageLightbox } from "@/components/ImageLightbox";
|
||||
import type { UIImage } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/** A bounded, quiet preview; the viewer still contains every delivered image. */
|
||||
export function ImageGallery({ images, align = "left", size = "large" }: {
|
||||
images: UIImage[];
|
||||
align?: "left" | "right";
|
||||
size?: "compact" | "large";
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [index, setIndex] = useState<number | null>(null);
|
||||
const viewable = images.filter((image) => image.url);
|
||||
const multiple = images.length > 1;
|
||||
const visible = images.slice(0, 4);
|
||||
return <>
|
||||
<span className={cn(
|
||||
"max-w-full gap-2",
|
||||
multiple && size === "large" ? "grid w-[28rem] grid-cols-2" : "flex flex-wrap items-end",
|
||||
align === "right" ? "ml-auto justify-end" : "mr-auto justify-start",
|
||||
)}>
|
||||
{visible.map((image, position) => {
|
||||
const remaining = images.length - visible.length;
|
||||
const overflow = position === visible.length - 1 && remaining > 0;
|
||||
return <ImageThumbnail key={`${image.url ?? image.name}-${position}`}
|
||||
image={image} size={multiple && size === "large" ? "grid" : size}
|
||||
label={overflow ? t("lightbox.viewAll", { count: images.length }) : undefined}
|
||||
onOpen={image.url || (overflow && viewable.length) ? () => setIndex(Math.max(0, viewable.indexOf(image))) : undefined}
|
||||
overlay={overflow ? `+${remaining}` : undefined} />;
|
||||
})}
|
||||
</span>
|
||||
<ImageLightbox images={viewable} index={index} onIndexChange={setIndex}
|
||||
onOpenChange={(open) => { if (!open) setIndex(null); }} />
|
||||
</>;
|
||||
}
|
||||
|
||||
export function ImageThumbnail({ image, size = "large", onOpen, label, overlay, onError }: {
|
||||
image: UIImage;
|
||||
size?: "compact" | "large" | "grid";
|
||||
onOpen?: () => void;
|
||||
label?: string;
|
||||
overlay?: string;
|
||||
onError?: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [failed, setFailed] = useState(false);
|
||||
const classes = cn(
|
||||
"relative block max-w-full overflow-hidden rounded-control border border-border/60 bg-muted/25",
|
||||
size === "large" ? "w-[min(100%,28rem)]" : size === "grid" ? "aspect-[8/5] w-full" : "h-24 w-24",
|
||||
);
|
||||
const content = image.url && !failed ? <img src={image.url} alt={image.name ?? ""}
|
||||
loading="lazy" decoding="async" draggable={false}
|
||||
onError={() => { setFailed(true); onError?.(); }}
|
||||
className={cn("block w-full object-contain", size === "large" ? "h-auto max-h-[22rem]" : "h-full")} />
|
||||
: <span className={cn("flex min-h-24 items-center justify-center gap-2 px-3 py-5 text-xs text-muted-foreground", size === "grid" && "h-full")}
|
||||
aria-label={t("message.attachmentUnavailable")}>
|
||||
<ImageIcon className="h-4 w-4 shrink-0" aria-hidden />
|
||||
<span className="min-w-0 truncate">{image.name || t("message.imageAttachment")}</span>
|
||||
</span>;
|
||||
if (!onOpen || ((!image.url || failed) && !overlay)) return <span className={classes}>{content}</span>;
|
||||
return <button type="button" onClick={onOpen}
|
||||
aria-label={label ?? (image.name ? `${t("lightbox.open")}: ${image.name}` : t("lightbox.open"))}
|
||||
className={cn(classes, "cursor-zoom-in p-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background")}>
|
||||
{content}
|
||||
{overlay ? <span className="absolute inset-0 flex items-center justify-center bg-black/45 text-xl font-medium text-white" aria-hidden>{overlay}</span> : null}
|
||||
</button>;
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef } from "react";
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog";
|
||||
import { ChevronLeft, ChevronRight, X } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { UIImage } from "@/lib/types";
|
||||
import { ZoomableImage } from "@/components/ZoomableImage";
|
||||
|
||||
interface ImageLightboxProps {
|
||||
images: UIImage[];
|
||||
@@ -19,8 +20,7 @@ interface ImageLightboxProps {
|
||||
* which is much too small for a photo preview).
|
||||
*
|
||||
* Implementation notes:
|
||||
* - `translate3d` + `will-change: transform` promote the image to a GPU
|
||||
* compositing layer so open/swap stays at 60 FPS on long threads.
|
||||
* - Image-local pinch/pan uses transforms; switching images resets the view.
|
||||
* - Adjacent images are rendered in hidden `<img>` tags so the browser
|
||||
* decodes them eagerly; pressing left/right feels instant.
|
||||
* - Radix handles `Escape` + focus trapping; we only wire up ←/→ + Home/End.
|
||||
@@ -37,6 +37,7 @@ export function ImageLightbox({
|
||||
const open = index !== null;
|
||||
const total = images.length;
|
||||
const current = index !== null ? images[index] : null;
|
||||
const opener = useRef<HTMLElement | null>(null);
|
||||
|
||||
const go = useCallback(
|
||||
(delta: number) => {
|
||||
@@ -94,8 +95,13 @@ export function ImageLightbox({
|
||||
/>
|
||||
<DialogPrimitive.Content
|
||||
aria-label={current.name ?? t("lightbox.title")}
|
||||
aria-describedby={undefined}
|
||||
onOpenAutoFocus={() => { opener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null; }}
|
||||
onCloseAutoFocus={(event) => {
|
||||
if (opener.current?.isConnected) { event.preventDefault(); opener.current.focus(); }
|
||||
}}
|
||||
className={cn(
|
||||
"fixed inset-0 z-50 flex items-center justify-center",
|
||||
"fixed inset-0 z-50 flex items-center justify-center overflow-hidden",
|
||||
"focus:outline-none",
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out",
|
||||
"data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
|
||||
@@ -107,22 +113,7 @@ export function ImageLightbox({
|
||||
{current.name ?? t("lightbox.title")}
|
||||
</DialogPrimitive.Title>
|
||||
|
||||
<div
|
||||
className="relative flex max-h-[92vh] max-w-[94vw] items-center justify-center"
|
||||
style={{
|
||||
transform: "translate3d(0,0,0)",
|
||||
willChange: "transform",
|
||||
}}
|
||||
>
|
||||
<img
|
||||
key={current.url}
|
||||
src={current.url}
|
||||
alt={current.name ?? ""}
|
||||
decoding="async"
|
||||
draggable={false}
|
||||
className="max-h-[92vh] max-w-[94vw] select-none rounded-compact object-contain shadow-2xl"
|
||||
/>
|
||||
</div>
|
||||
<ZoomableImage key={`${index}:${current.url}`} src={current.url} alt={current.name ?? ""} />
|
||||
|
||||
{hasMany ? (
|
||||
<>
|
||||
@@ -142,7 +133,7 @@ export function ImageLightbox({
|
||||
go(1);
|
||||
}}
|
||||
/>
|
||||
<div className="pointer-events-none absolute bottom-5 left-1/2 -translate-x-1/2 rounded-full bg-black/55 px-3 py-1 text-xs font-medium text-white/90 tabular-nums">
|
||||
<div className="pointer-events-none absolute left-4 top-5 rounded-full bg-black/55 px-3 py-1 text-xs font-medium text-white/90 tabular-nums">
|
||||
{counter}
|
||||
</div>
|
||||
</>
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { createContext, useCallback, useContext, useLayoutEffect, useState, type ReactNode } from "react";
|
||||
|
||||
const InlineImages = createContext<ReadonlyMap<string, number>>(new Map());
|
||||
const RegisterImage = createContext<((url: string) => () => void) | undefined>(undefined);
|
||||
|
||||
/** Deduplicate only images actually rendered in this answer, not links or code examples. */
|
||||
export function InlineImageProvider({ children }: { children: ReactNode }) {
|
||||
const [urls, setUrls] = useState<ReadonlyMap<string, number>>(new Map());
|
||||
const register = useCallback((url: string) => {
|
||||
const update = (delta: number) => setUrls((previous) => {
|
||||
const next = new Map(previous);
|
||||
const count = (next.get(url) ?? 0) + delta;
|
||||
if (count > 0) next.set(url, count);
|
||||
else next.delete(url);
|
||||
return next;
|
||||
});
|
||||
update(1);
|
||||
return () => update(-1);
|
||||
}, []);
|
||||
return <RegisterImage.Provider value={register}>
|
||||
<InlineImages.Provider value={urls}>{children}</InlineImages.Provider>
|
||||
</RegisterImage.Provider>;
|
||||
}
|
||||
|
||||
export function useRegisterInlineImage(url?: string) {
|
||||
const register = useContext(RegisterImage);
|
||||
useLayoutEffect(() => url ? register?.(url) : undefined, [register, url]);
|
||||
}
|
||||
|
||||
export function useInlineImages() {
|
||||
return useContext(InlineImages);
|
||||
}
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
CircleAlert,
|
||||
Clock3,
|
||||
Copy,
|
||||
ImageIcon,
|
||||
Quote,
|
||||
Wrench,
|
||||
} from "lucide-react";
|
||||
@@ -24,7 +23,8 @@ import { DisclosureContent } from "@/components/ui/disclosure";
|
||||
import { AttachmentTile } from "@/components/AttachmentTile";
|
||||
import { SessionHandleLabel } from "@/components/SessionHandleLabel";
|
||||
import { FallbackResponseSources } from "@/components/ResponseSourceBadge";
|
||||
import { ImageLightbox } from "@/components/ImageLightbox";
|
||||
import { ImageGallery } from "@/components/ImageGallery";
|
||||
import { InlineImageProvider, useInlineImages } from "@/components/InlineImageContext";
|
||||
import { MarkdownText } from "@/components/MarkdownText";
|
||||
import { SlashCommandText } from "@/components/SlashCommandText";
|
||||
import { ReasoningRow } from "@/components/thread/activity/ReasoningRow";
|
||||
@@ -511,7 +511,7 @@ export function MessageBubble({
|
||||
className="group relative ml-auto flex w-fit max-w-[min(85%,36rem)] flex-col items-end gap-1.5"
|
||||
>
|
||||
{contextMenu}
|
||||
{hasImages ? <UserImages images={images} align="right" /> : null}
|
||||
{hasImages ? <ImageGallery images={images} align="right" size="compact" /> : null}
|
||||
{!hasImages && hasMedia ? (
|
||||
<MessageMedia media={media} align="right" />
|
||||
) : null}
|
||||
@@ -576,7 +576,7 @@ export function MessageBubble({
|
||||
{empty && message.isStreaming && !hasReasoning ? (
|
||||
<ThinkingState />
|
||||
) : empty && message.isStreaming ? null : (
|
||||
<>
|
||||
<InlineImageProvider>
|
||||
<div data-assistant-selectable={message.isStreaming ? undefined : "true"}>
|
||||
{/* A mode switch rebuilds Streamdown's subtree and moves the scroll anchor. */}
|
||||
<MarkdownText
|
||||
@@ -588,7 +588,7 @@ export function MessageBubble({
|
||||
</MarkdownText>
|
||||
</div>
|
||||
{media.length > 0 ? <MessageMedia media={media} align="left" /> : null}
|
||||
</>
|
||||
</InlineImageProvider>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
@@ -681,17 +681,22 @@ function MessageMedia({
|
||||
media: UIMediaAttachment[];
|
||||
align: "left" | "right";
|
||||
}) {
|
||||
const inlineImages = useInlineImages();
|
||||
if (media.length === 0) return null;
|
||||
const images: UIImage[] = [];
|
||||
const seen = new Set<string>();
|
||||
const nonImages: UIMediaAttachment[] = [];
|
||||
for (const item of media) {
|
||||
const normalized = toMediaAttachment(item);
|
||||
if (normalized.kind === "image") {
|
||||
if (normalized.url && (inlineImages.has(normalized.url) || seen.has(normalized.url))) continue;
|
||||
if (normalized.url) seen.add(normalized.url);
|
||||
images.push({ url: normalized.url, name: normalized.name });
|
||||
} else {
|
||||
nonImages.push(normalized);
|
||||
}
|
||||
}
|
||||
if (images.length === 0 && nonImages.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -701,7 +706,7 @@ function MessageMedia({
|
||||
)}
|
||||
>
|
||||
{images.length > 0 ? (
|
||||
<UserImages images={images} align={align} size={align === "left" ? "large" : "compact"} />
|
||||
<ImageGallery images={images} align={align} size={align === "left" ? "large" : "compact"} />
|
||||
) : null}
|
||||
{nonImages.map((item, i) => (
|
||||
<AttachmentTile key={`${item.url ?? item.name ?? item.kind}-${i}`} attachment={item} />
|
||||
@@ -710,141 +715,6 @@ function MessageMedia({
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Right-aligned preview row for images attached to a user turn.
|
||||
*
|
||||
* The URL is expected to be a self-contained ``data:`` URL (the Composer
|
||||
* hands the normalized base64 payload to the optimistic bubble so that the
|
||||
* preview survives React StrictMode double-mount — blob URLs would be
|
||||
* revoked by the Composer's cleanup before remount). Historical replays
|
||||
* have no URL (the backend strips data URLs before persisting), so we
|
||||
* render a labelled placeholder tile instead of a broken ``<img>``.
|
||||
*/
|
||||
function UserImages({
|
||||
images,
|
||||
align = "right",
|
||||
size = "compact",
|
||||
}: {
|
||||
images: UIImage[];
|
||||
align?: "left" | "right";
|
||||
size?: "compact" | "large";
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
// Only real-URL images can open in the lightbox; historical-replay
|
||||
// placeholders (no URL) have nothing to zoom into.
|
||||
const viewableImages: UIImage[] = [];
|
||||
const originalToViewable = new Map<number, number>();
|
||||
for (let i = 0; i < images.length; i += 1) {
|
||||
const img = images[i];
|
||||
if (typeof img.url !== "string" || img.url.length === 0) continue;
|
||||
originalToViewable.set(i, viewableImages.length);
|
||||
viewableImages.push(img);
|
||||
}
|
||||
|
||||
const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-wrap items-end gap-2",
|
||||
size === "large" && "gap-3",
|
||||
align === "right" ? "ml-auto justify-end" : "mr-auto justify-start",
|
||||
)}
|
||||
>
|
||||
{images.map((img, i) => (
|
||||
<UserImageCell
|
||||
key={`${img.url ?? "placeholder"}-${i}`}
|
||||
image={img}
|
||||
size={size}
|
||||
placeholderLabel={t("message.imageAttachment")}
|
||||
openLabel={t("lightbox.open")}
|
||||
onOpen={
|
||||
originalToViewable.has(i)
|
||||
? () => setLightboxIndex(originalToViewable.get(i)!)
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<ImageLightbox
|
||||
images={viewableImages}
|
||||
index={lightboxIndex}
|
||||
onIndexChange={setLightboxIndex}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setLightboxIndex(null);
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function UserImageCell({
|
||||
image,
|
||||
size,
|
||||
placeholderLabel,
|
||||
openLabel,
|
||||
onOpen,
|
||||
}: {
|
||||
image: UIImage;
|
||||
size: "compact" | "large";
|
||||
placeholderLabel: string;
|
||||
openLabel: string;
|
||||
onOpen?: () => void;
|
||||
}) {
|
||||
const hasUrl = typeof image.url === "string" && image.url.length > 0;
|
||||
const tileClasses = cn(
|
||||
"relative overflow-hidden border border-border/60 bg-muted/40",
|
||||
size === "large"
|
||||
? "w-[min(100%,34rem)] rounded-panel bg-transparent"
|
||||
: "h-24 w-24 rounded-control",
|
||||
"shadow-[0_6px_18px_-14px_rgba(0,0,0,0.45)]",
|
||||
);
|
||||
|
||||
if (hasUrl && onOpen) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpen}
|
||||
aria-label={image.name ? `${openLabel}: ${image.name}` : openLabel}
|
||||
className={cn(
|
||||
tileClasses,
|
||||
"block cursor-zoom-in p-0",
|
||||
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",
|
||||
)}
|
||||
>
|
||||
<img
|
||||
src={image.url}
|
||||
alt={image.name ?? ""}
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
draggable={false}
|
||||
className={cn(
|
||||
"block",
|
||||
size === "large"
|
||||
? "h-auto max-h-[36rem] w-full rounded-[inherit] object-contain"
|
||||
: "h-full w-full object-cover",
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={tileClasses} title={image.name ?? undefined}>
|
||||
<div
|
||||
className="flex h-full w-full flex-col items-center justify-center gap-1 px-2 text-[11px] text-muted-foreground"
|
||||
aria-label={placeholderLabel}
|
||||
>
|
||||
<ImageIcon className="h-4 w-4 flex-none" aria-hidden />
|
||||
<span className="line-clamp-2 text-center leading-tight">
|
||||
{image.name ?? placeholderLabel}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Quiet pre-token state that occupies a stable line in the answer column. */
|
||||
function ThinkingState() {
|
||||
const { t } = useTranslation();
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { useEffect, useId, useRef, useState, type CSSProperties, type PointerEvent, type ReactNode } from "react";
|
||||
import { Globe2, Image, PanelRightClose, X } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FileReferenceIcon, fileKindForPath, splitFilePath } from "@/components/FileReferenceChip";
|
||||
import { FileActions } from "@/components/FileActions";
|
||||
import { SidebarSelectionHighlight, SIDEBAR_SELECTION_ITEM_CLASS } from "@/components/SidebarSelectionHighlight";
|
||||
import type { PreviewTab } from "@/hooks/useFilePreviewState";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
function tabName(tab: PreviewTab) {
|
||||
return tab.kind === "web" ? new URL(tab.value).host : splitFilePath(tab.value).name;
|
||||
}
|
||||
|
||||
/** One stable sidebar shell: switching targets never replays its opening animation. */
|
||||
export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onCloseTab, onClose, onResizeStart, children }: {
|
||||
tabs: PreviewTab[];
|
||||
activeId: string;
|
||||
width: number;
|
||||
isClosing: boolean;
|
||||
onSelect: (id: string) => void;
|
||||
onCloseTab: (id: string) => void;
|
||||
onClose: () => void;
|
||||
onResizeStart: (event: PointerEvent<HTMLButtonElement>) => void;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const id = useId();
|
||||
const [entered, setEntered] = useState(false);
|
||||
const buttons = useRef(new Map<string, HTMLButtonElement>());
|
||||
const tabList = useRef<HTMLDivElement>(null);
|
||||
const pendingFocus = useRef<string | null>(null);
|
||||
useEffect(() => {
|
||||
const frame = requestAnimationFrame(() => setEntered(true));
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
const revealActiveTab = () => buttons.current.get(activeId)?.parentElement?.scrollIntoView?.({ block: "nearest", inline: "nearest" });
|
||||
revealActiveTab();
|
||||
if (pendingFocus.current) {
|
||||
buttons.current.get(pendingFocus.current)?.focus();
|
||||
pendingFocus.current = null;
|
||||
}
|
||||
if (!tabList.current || typeof ResizeObserver === "undefined") return;
|
||||
const observer = new ResizeObserver(revealActiveTab);
|
||||
observer.observe(tabList.current);
|
||||
return () => observer.disconnect();
|
||||
}, [activeId, tabs]);
|
||||
const closeTab = (tab: PreviewTab, index: number) => {
|
||||
const remaining = tabs.filter((item) => item.id !== tab.id);
|
||||
pendingFocus.current = tab.id === activeId
|
||||
? remaining[Math.min(index, remaining.length - 1)]?.id ?? null : activeId;
|
||||
onCloseTab(tab.id);
|
||||
};
|
||||
const iconButton = "inline-flex size-8 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
|
||||
return <aside aria-label={t("previewTabs.title")} data-testid="preview-pane" data-file-preview-panel
|
||||
style={{
|
||||
"--file-preview-width": `${width}px`,
|
||||
"--file-preview-slot-width": !entered || isClosing ? "0px" : `${width}px`,
|
||||
"--file-preview-mobile-width": !entered || isClosing ? "0px" : "100%",
|
||||
} as CSSProperties}
|
||||
className={cn("file-preview-pane absolute inset-y-0 right-0 z-30 w-[var(--file-preview-mobile-width)] overflow-hidden transition-[width] duration-300 ease-out motion-reduce:transition-none", isClosing && "pointer-events-none")}
|
||||
>
|
||||
<div className={cn("file-preview-content absolute inset-y-0 right-0 flex w-[100cqw] flex-col border-l border-border/60 bg-background pb-[env(safe-area-inset-bottom)] transition-opacity duration-200 motion-reduce:transition-none", !entered || isClosing ? "opacity-0" : "opacity-100")}>
|
||||
<button type="button" aria-label={t("filePreview.resize")} onPointerDown={onResizeStart}
|
||||
className="file-preview-resize group absolute inset-y-0 left-0 z-20 hidden w-2 cursor-col-resize touch-none justify-start focus-visible:outline-none">
|
||||
<span aria-hidden className="h-full w-px bg-foreground/25 opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100" />
|
||||
</button>
|
||||
<div className="flex h-10 shrink-0 items-center gap-1 border-b border-border/40 px-2">
|
||||
<div ref={tabList} role="tablist" aria-label={t("previewTabs.title")} className="min-w-0 flex-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
|
||||
<SidebarSelectionHighlight activeId={activeId} scope="preview-tabs" targetSelector="[data-preview-tab-active]"
|
||||
className="relative isolate flex w-max min-w-full items-center gap-1"
|
||||
highlightClassName="rounded-compact">
|
||||
{tabs.map((tab, index) => {
|
||||
const selected = tab.id === activeId;
|
||||
const name = tabName(tab);
|
||||
const item = <div key={tab.id} role="presentation" data-preview-tab-active={selected ? "" : undefined}
|
||||
className={cn(SIDEBAR_SELECTION_ITEM_CLASS, "group flex h-8 max-w-56 shrink-0 items-center rounded-compact", selected ? "text-foreground" : "text-muted-foreground hover:bg-muted/50 hover:text-foreground")}>
|
||||
<button type="button" role="tab" id={`${id}-tab-${index}`} aria-selected={selected} aria-controls={`${id}-panel`}
|
||||
tabIndex={selected ? 0 : -1} title={tab.value}
|
||||
ref={(node) => { if (node) buttons.current.set(tab.id, node); else buttons.current.delete(tab.id); }}
|
||||
onClick={() => onSelect(tab.id)}
|
||||
onKeyDown={(event) => {
|
||||
let next: number;
|
||||
if (event.key === "ArrowRight") next = (index + 1) % tabs.length;
|
||||
else if (event.key === "ArrowLeft") next = (index - 1 + tabs.length) % tabs.length;
|
||||
else if (event.key === "Home") next = 0;
|
||||
else if (event.key === "End") next = tabs.length - 1;
|
||||
else if (event.key === "Delete") { event.preventDefault(); closeTab(tab, index); return; }
|
||||
else return;
|
||||
event.preventDefault();
|
||||
onSelect(tabs[next].id);
|
||||
buttons.current.get(tabs[next].id)?.focus();
|
||||
}}
|
||||
className="flex h-8 min-w-0 items-center gap-1.5 rounded-compact pl-2.5 pr-1.5 text-[12.5px] font-medium leading-5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring">
|
||||
<span aria-hidden className="flex size-3.5 shrink-0 items-center justify-center text-muted-foreground">
|
||||
{tab.kind === "web" ? <Globe2 className="size-3.5" /> : /\.(png|jpe?g|gif|webp|avif|bmp)$/i.test(tab.value)
|
||||
? <Image className="size-3.5" /> : <FileReferenceIcon kind={fileKindForPath(tab.value)} interactive={false} />}
|
||||
</span>
|
||||
<span className="truncate">{name}</span>
|
||||
</button>
|
||||
<button type="button" tabIndex={selected ? 0 : -1} aria-label={t("previewTabs.closeTab", { name })} title={t("previewTabs.closeTab", { name })}
|
||||
onClick={() => closeTab(tab, index)}
|
||||
className={cn("mr-1 inline-flex size-6 shrink-0 items-center justify-center rounded-compact text-muted-foreground transition-colors hover:bg-foreground/10 hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", !selected && "sm:opacity-0 sm:group-hover:opacity-100 sm:group-focus-within:opacity-100")}>
|
||||
<X className="size-3" aria-hidden />
|
||||
</button>
|
||||
</div>;
|
||||
return tab.kind === "file" ? <FileActions key={tab.id} path={tab.value} className="shrink-0">{item}</FileActions> : item;
|
||||
})}
|
||||
</SidebarSelectionHighlight>
|
||||
</div>
|
||||
{tabs.length > 1 ? <button type="button" className={iconButton} onClick={onClose} aria-label={t("previewTabs.closeAll")} title={t("previewTabs.closeAll")}>
|
||||
<PanelRightClose className="size-4" aria-hidden />
|
||||
</button> : null}
|
||||
</div>
|
||||
<div role="tabpanel" id={`${id}-panel`} aria-labelledby={`${id}-tab-${tabs.findIndex((tab) => tab.id === activeId)}`} tabIndex={0}
|
||||
className="flex min-h-0 flex-1 flex-col focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring">
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</aside>;
|
||||
}
|
||||
@@ -4,12 +4,14 @@ import {
|
||||
useLayoutEffect,
|
||||
useRef,
|
||||
} from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface SidebarSelectionHighlightProps extends HTMLAttributes<HTMLDivElement> {
|
||||
targetRef?: RefObject<HTMLElement>;
|
||||
targetSelector?: string;
|
||||
activeId: string | null;
|
||||
scope: string;
|
||||
highlightClassName?: string;
|
||||
}
|
||||
|
||||
export const SIDEBAR_SELECTION_ITEM_CLASS =
|
||||
@@ -24,6 +26,7 @@ export function SidebarSelectionHighlight({
|
||||
targetSelector,
|
||||
activeId,
|
||||
scope,
|
||||
highlightClassName,
|
||||
children,
|
||||
...containerProps
|
||||
}: SidebarSelectionHighlightProps) {
|
||||
@@ -114,7 +117,7 @@ export function SidebarSelectionHighlight({
|
||||
data-testid={`${scope}-selection-highlight`}
|
||||
data-active-id={activeId ?? undefined}
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none absolute left-0 top-0 z-0 !mt-0 rounded-xl bg-sidebar-foreground/[0.055] opacity-0 transition-[transform,width,height] duration-300 ease-out will-change-transform motion-reduce:transition-none dark:bg-white/[0.07]"
|
||||
className={cn("pointer-events-none absolute left-0 top-0 z-0 !mt-0 rounded-xl bg-sidebar-foreground/[0.055] opacity-0 transition-[transform,width,height] duration-300 ease-out will-change-transform motion-reduce:transition-none dark:bg-white/[0.07]", highlightClassName)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,19 +1,17 @@
|
||||
import { useState, type CSSProperties, type PointerEvent } from "react";
|
||||
import { ExternalLink, RotateCw, X } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { ExternalLink, Info, RotateCw } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
import { isLoopbackHost } from "@/lib/network";
|
||||
import { isNativeRuntime } from "@/lib/runtime";
|
||||
import { parseWebLink, webPreviewRestriction } from "@/lib/web-preview";
|
||||
|
||||
interface WebPreviewPanelProps {
|
||||
url: string;
|
||||
desktopWidth?: number;
|
||||
onResizeStart?: (event: PointerEvent<HTMLButtonElement>) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function WebPreviewPanel({ url: value, desktopWidth = 544, onResizeStart, onClose }: WebPreviewPanelProps) {
|
||||
export function WebPreviewPanel({ url: value }: WebPreviewPanelProps) {
|
||||
const { t } = useTranslation();
|
||||
const [revision, setRevision] = useState(0);
|
||||
const url = parseWebLink(value);
|
||||
@@ -21,29 +19,23 @@ export function WebPreviewPanel({ url: value, desktopWidth = 544, onResizeStart,
|
||||
"credentialless" in HTMLIFrameElement.prototype) : "invalid";
|
||||
const buttonClass = "inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
|
||||
return (
|
||||
<aside aria-label={t("webPreview.title")} data-testid="web-preview-panel" data-file-preview-panel
|
||||
style={{ "--file-preview-width": `${desktopWidth}px`, "--file-preview-slot-width": `${desktopWidth}px` } as CSSProperties}
|
||||
className="absolute inset-y-0 right-0 z-30 flex w-full flex-col border-l border-border/70 bg-background pb-[env(safe-area-inset-bottom)] shadow-2xl md:relative md:z-auto md:w-[var(--file-preview-slot-width)] md:min-w-0 md:shrink-0 md:pb-0 md:shadow-none">
|
||||
{onResizeStart ? <button type="button" aria-label={t("webPreview.resize")}
|
||||
className="absolute inset-y-0 left-0 z-20 hidden w-2 cursor-col-resize touch-none hover:bg-border/50 md:block"
|
||||
onPointerDown={onResizeStart} /> : null}
|
||||
<div className="flex shrink-0 items-center gap-1 border-b border-border/60 px-3 py-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-sm font-medium" title={url?.origin}>{t("webPreview.original")}</p>
|
||||
<p className="truncate text-xs text-muted-foreground" title={url?.href}>{url?.href}</p>
|
||||
</div>
|
||||
<section aria-label={t("webPreview.title")} data-testid="web-preview-panel" className="flex min-h-0 flex-1 flex-col">
|
||||
<div className="flex h-9 shrink-0 items-center gap-1 border-b border-border/40 px-2">
|
||||
<p className="min-w-0 flex-1 truncate px-1 text-xs text-muted-foreground" title={url?.href}>{url?.href}</p>
|
||||
<Popover>
|
||||
<PopoverTrigger asChild><button type="button" className={buttonClass} aria-label={t("previewTabs.websiteInfo")} title={t("previewTabs.websiteInfo")}><Info className="size-3.5" aria-hidden /></button></PopoverTrigger>
|
||||
<PopoverContent align="end" className="w-72 space-y-2 rounded-control p-3 text-xs leading-relaxed text-muted-foreground">
|
||||
<p>{t("webPreview.isolated")}</p>
|
||||
<p>{t("webPreview.blockedHint")}</p>
|
||||
{url && isLoopbackHost(url.hostname) ? <p>{t("webPreview.loopback")}</p> : null}
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
{!restriction ? <button type="button" className={buttonClass} onClick={() => setRevision((n) => n + 1)} title={t("webPreview.refresh")} aria-label={t("webPreview.refresh")}>
|
||||
<RotateCw className="h-4 w-4" aria-hidden />
|
||||
</button> : null}
|
||||
{url ? <a className={buttonClass} href={url.href} target="_blank" rel="noreferrer noopener" title={t("webPreview.external")} aria-label={t("webPreview.external")}>
|
||||
<ExternalLink className="h-4 w-4" aria-hidden />
|
||||
</a> : null}
|
||||
<button type="button" className={buttonClass} onClick={onClose} title={t("webPreview.close")} aria-label={t("webPreview.close")}><X className="h-4 w-4" aria-hidden /></button>
|
||||
</div>
|
||||
<div className="shrink-0 space-y-1 border-b border-border/60 px-4 py-3 text-xs leading-relaxed text-muted-foreground">
|
||||
<p>{t("webPreview.isolated")}</p>
|
||||
<p>{t("webPreview.blockedHint")}</p>
|
||||
{url && isLoopbackHost(url.hostname) ? <p>{t("webPreview.loopback")}</p> : null}
|
||||
</div>
|
||||
{restriction ? <div role="status" className="flex min-h-0 flex-1 items-center justify-center overflow-auto p-6 text-center text-sm text-muted-foreground">
|
||||
{t(`webPreview.${restriction}`)}
|
||||
@@ -51,6 +43,6 @@ export function WebPreviewPanel({ url: value, desktopWidth = 544, onResizeStart,
|
||||
{...{ credentialless: "" }} sandbox="allow-scripts" referrerPolicy="no-referrer"
|
||||
allow="camera 'none'; microphone 'none'; geolocation 'none'; clipboard-read 'none'; clipboard-write 'none'; payment 'none'; fullscreen 'none'; display-capture 'none'; usb 'none'; serial 'none'; hid 'none'"
|
||||
src={url!.href} className="min-h-0 w-full flex-1 border-0 bg-white" />}
|
||||
</aside>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import { useCallback, useEffect, useRef, useState, type PointerEvent } from "react";
|
||||
import { Minus, Plus } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type Point = { x: number; y: number };
|
||||
type View = Point & { scale: number };
|
||||
const FIT: View = { x: 0, y: 0, scale: 1 };
|
||||
const MAX_SCALE = 8;
|
||||
const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));
|
||||
const midpoint = (a: Point, b: Point): Point => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 });
|
||||
const distance = (a: Point, b: Point) => Math.hypot(a.x - b.x, a.y - b.y);
|
||||
|
||||
/** Image-local gestures; the surrounding page retains normal browser zoom. Remount per image. */
|
||||
export function ZoomableImage({ src, alt }: { src: string; alt: string }) {
|
||||
const { t } = useTranslation();
|
||||
const viewport = useRef<HTMLDivElement>(null);
|
||||
const image = useRef<HTMLImageElement>(null);
|
||||
const pointers = useRef(new Map<number, Point>());
|
||||
const viewRef = useRef(FIT);
|
||||
const [view, setView] = useState(FIT);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
|
||||
const apply = useCallback((next: View) => {
|
||||
const scale = clamp(next.scale, 1, MAX_SCALE);
|
||||
const maxX = Math.max(0, ((image.current?.offsetWidth ?? 0) * scale - (viewport.current?.clientWidth ?? 0)) / 2);
|
||||
const maxY = Math.max(0, ((image.current?.offsetHeight ?? 0) * scale - (viewport.current?.clientHeight ?? 0)) / 2);
|
||||
const bounded = { scale, x: clamp(next.x, -maxX, maxX), y: clamp(next.y, -maxY, maxY) };
|
||||
viewRef.current = bounded;
|
||||
setView(bounded);
|
||||
}, []);
|
||||
|
||||
const zoom = useCallback((scale: number, from?: Point, to = from) => {
|
||||
const rect = viewport.current?.getBoundingClientRect();
|
||||
const current = viewRef.current;
|
||||
const next = clamp(scale, 1, MAX_SCALE);
|
||||
const center = rect ? { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 } : { x: 0, y: 0 };
|
||||
const origin = from ?? center;
|
||||
const target = to ?? origin;
|
||||
apply({
|
||||
scale: next,
|
||||
x: target.x - center.x - (origin.x - center.x - current.x) * next / current.scale,
|
||||
y: target.y - center.y - (origin.y - center.y - current.y) * next / current.scale,
|
||||
});
|
||||
}, [apply]);
|
||||
|
||||
useEffect(() => {
|
||||
const element = viewport.current;
|
||||
if (!element) return;
|
||||
// React's wheel listener is passive; cancel browser zoom only over this image viewport.
|
||||
const onWheel = (event: WheelEvent) => {
|
||||
if (event.ctrlKey) {
|
||||
event.preventDefault();
|
||||
zoom(viewRef.current.scale * Math.exp(-clamp(event.deltaY, -50, 50) * 0.01), { x: event.clientX, y: event.clientY });
|
||||
} else if (viewRef.current.scale > 1) {
|
||||
event.preventDefault();
|
||||
const unit = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? element.clientHeight : 1;
|
||||
apply({ ...viewRef.current, x: viewRef.current.x - event.deltaX * unit, y: viewRef.current.y - event.deltaY * unit });
|
||||
}
|
||||
};
|
||||
element.addEventListener("wheel", onWheel, { passive: false });
|
||||
const resize = new ResizeObserver(() => apply(viewRef.current));
|
||||
resize.observe(element);
|
||||
return () => { element.removeEventListener("wheel", onWheel); resize.disconnect(); };
|
||||
}, [apply, zoom]);
|
||||
|
||||
const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {
|
||||
if (event.button !== 0 || pointers.current.size >= 2) return;
|
||||
pointers.current.set(event.pointerId, { x: event.clientX, y: event.clientY });
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
setDragging(true);
|
||||
};
|
||||
const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {
|
||||
if (!pointers.current.has(event.pointerId)) return;
|
||||
const before = [...pointers.current.values()];
|
||||
pointers.current.set(event.pointerId, { x: event.clientX, y: event.clientY });
|
||||
const after = [...pointers.current.values()];
|
||||
if (before.length === 2) {
|
||||
const previousDistance = distance(before[0], before[1]);
|
||||
if (previousDistance > 0) zoom(viewRef.current.scale * distance(after[0], after[1]) / previousDistance,
|
||||
midpoint(before[0], before[1]), midpoint(after[0], after[1]));
|
||||
} else if (viewRef.current.scale > 1) {
|
||||
apply({ ...viewRef.current, x: viewRef.current.x + after[0].x - before[0].x, y: viewRef.current.y + after[0].y - before[0].y });
|
||||
}
|
||||
};
|
||||
const endPointer = (event: PointerEvent<HTMLDivElement>) => {
|
||||
pointers.current.delete(event.pointerId);
|
||||
if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
|
||||
setDragging(pointers.current.size > 0);
|
||||
};
|
||||
const buttonClass = "grid size-9 shrink-0 place-items-center rounded-full text-white/90 transition-colors hover:bg-white/10 hover:text-white disabled:opacity-30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/70";
|
||||
|
||||
return <>
|
||||
<div ref={viewport} data-testid="image-zoom-viewport" tabIndex={0} role="group" aria-label={t("lightbox.gestures")}
|
||||
className={cn("absolute inset-x-3 bottom-[calc(4rem+env(safe-area-inset-bottom))] top-14 flex touch-none select-none items-center justify-center overflow-hidden focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-white/40 sm:inset-x-8", view.scale > 1 ? dragging ? "cursor-grabbing" : "cursor-grab" : "cursor-zoom-in")}
|
||||
onPointerDown={onPointerDown} onPointerMove={onPointerMove} onPointerUp={endPointer} onPointerCancel={endPointer} onLostPointerCapture={endPointer}
|
||||
onDoubleClick={(event) => zoom(view.scale > 1 ? 1 : 2, { x: event.clientX, y: event.clientY })}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "+" || event.key === "=") zoom(view.scale * 1.5);
|
||||
else if (event.key === "-") zoom(view.scale / 1.5);
|
||||
else if (event.key === "0") apply(FIT);
|
||||
else return;
|
||||
event.preventDefault();
|
||||
}}>
|
||||
<img ref={image} src={src} alt={alt} decoding="async" draggable={false} onLoad={() => apply(viewRef.current)}
|
||||
className="max-h-full max-w-full select-none rounded-compact object-contain shadow-2xl will-change-transform"
|
||||
style={{ transform: `translate3d(${view.x}px, ${view.y}px, 0) scale(${view.scale})` }} />
|
||||
</div>
|
||||
<div className="absolute bottom-[calc(1rem+env(safe-area-inset-bottom))] left-1/2 flex -translate-x-1/2 items-center gap-1 rounded-full bg-black/55 p-1 backdrop-blur-sm">
|
||||
<button type="button" aria-label={t("lightbox.zoomOut")} title={t("lightbox.zoomOut")} disabled={view.scale <= 1} className={buttonClass} onClick={() => zoom(view.scale / 1.5)}><Minus className="size-4" aria-hidden /></button>
|
||||
<button type="button" aria-label={t("lightbox.resetZoom")} title={t("lightbox.resetZoom")}
|
||||
className="h-9 min-w-14 rounded-full px-2 text-xs font-medium tabular-nums text-white/90 hover:bg-white/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/70" onClick={() => apply(FIT)}>
|
||||
{Math.round(view.scale * 100)}%
|
||||
</button>
|
||||
<button type="button" aria-label={t("lightbox.zoomIn")} title={t("lightbox.zoomIn")} disabled={view.scale >= MAX_SCALE} className={buttonClass} onClick={() => zoom(view.scale * 1.5)}><Plus className="size-4" aria-hidden /></button>
|
||||
</div>
|
||||
</>;
|
||||
}
|
||||
@@ -20,6 +20,7 @@ const controlsClassName = cn(
|
||||
);
|
||||
|
||||
interface ThreadHeaderProps {
|
||||
className?: string;
|
||||
title: string;
|
||||
handle?: SessionHandle | null;
|
||||
onToggleSidebar: () => void;
|
||||
@@ -39,6 +40,7 @@ interface ThreadHeaderProps {
|
||||
}
|
||||
|
||||
export function ThreadHeader({
|
||||
className,
|
||||
title,
|
||||
handle = null,
|
||||
onToggleSidebar,
|
||||
@@ -65,6 +67,7 @@ export function ThreadHeader({
|
||||
"pointer-events-none inset-x-0 top-0 z-30 flex shrink-0 items-center justify-between gap-3 px-3 py-1",
|
||||
"[position:var(--thread-header-position,absolute)]",
|
||||
minimal && "h-11",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div
|
||||
|
||||
@@ -5,10 +5,12 @@ import { useTranslation } from "react-i18next";
|
||||
|
||||
import { FilePreviewAvailabilityProvider } from "@/components/FilePreviewAvailabilityContext";
|
||||
import { FilePreviewPanel } from "@/components/FilePreviewPanel";
|
||||
import { PreviewPane } from "@/components/PreviewPane";
|
||||
import { FileActionsProvider } from "@/components/FileActions";
|
||||
import { WebPreviewContext } from "@/components/WebLink";
|
||||
import { WebPreviewPanel } from "@/components/WebPreviewPanel";
|
||||
import { parseWebLink } from "@/lib/web-preview";
|
||||
import { createFilePreviewResource } from "@/lib/file-preview-resource";
|
||||
import { SessionHandleLabel } from "@/components/SessionHandleLabel";
|
||||
import { PromptNavigator } from "@/components/thread/PromptNavigator";
|
||||
import { ModelFallbackNotice } from "@/components/thread/ModelFallbackNotice";
|
||||
@@ -28,10 +30,11 @@ import { StreamErrorNotice } from "@/components/thread/StreamErrorNotice";
|
||||
import { ThreadViewport, type ThreadViewportHandle } from "@/components/thread/ThreadViewport";
|
||||
import { useNanobotStream, type SendAttachment, type SendOptions } from "@/hooks/useNanobotStream";
|
||||
import { useSessionHistory } from "@/hooks/useSessions";
|
||||
import { useFilePreviewState, type FilePreviewStore } from "@/hooks/useFilePreviewState";
|
||||
import { useFilePreviewState, type FilePreviewState, type FilePreviewStore } from "@/hooks/useFilePreviewState";
|
||||
import {
|
||||
ApiError,
|
||||
fetchFilePreviewAvailability,
|
||||
fetchFilePreview,
|
||||
fetchFileReferenceMetadata,
|
||||
fetchInstalledCliApps,
|
||||
fetchMcpPresets,
|
||||
@@ -716,12 +719,13 @@ export function ThreadShell({
|
||||
} | null>(null);
|
||||
const [heroGreetingKey, setHeroGreetingKey] = useState(randomHeroGreetingKey);
|
||||
const [submittedViewportTurnId, setSubmittedViewportTurnId] = useState<string | null>(null);
|
||||
const { state: previewState, setPath: setFilePreviewPath, setWidth: setFilePreviewWidth, setWebUrl } =
|
||||
const { state: previewState, openFile, openWeb, selectTab, closeTab, close: closePreview, setWidth: setFilePreviewWidth } =
|
||||
useFilePreviewState(previewSessionKey, filePreviewStore);
|
||||
const [closingPreview, setClosingPreview] = useState<{ key: string; path: string } | null>(null);
|
||||
const [closingPreview, setClosingPreview] = useState<{ key: string; state: FilePreviewState } | null>(null);
|
||||
const filePreviewClosing = closingPreview?.key === previewSessionKey;
|
||||
const filePreviewPath = previewState.path
|
||||
?? (filePreviewClosing ? closingPreview?.path ?? null : null);
|
||||
const visiblePreview = filePreviewClosing ? closingPreview.state : previewState;
|
||||
const activePreview = visiblePreview.tabs.find((tab) => tab.id === visiblePreview.activeId);
|
||||
const previewOpen = Boolean(activePreview);
|
||||
const [filePreviewMaxWidth, setFilePreviewMaxWidth] = useState(FILE_PREVIEW_MAX_WIDTH);
|
||||
const filePreviewWidth = clampFilePreviewWidth(previewState.width, filePreviewMaxWidth);
|
||||
const [quotedContext, setQuotedContext] = useState<string | null>(null);
|
||||
@@ -1502,29 +1506,38 @@ export function ThreadShell({
|
||||
}), [client, chatId]);
|
||||
|
||||
const handleCloseFilePreview = useCallback(() => {
|
||||
if (!previewSessionKey || !filePreviewPath || filePreviewClosing) return;
|
||||
if (!previewSessionKey || !previewState.activeId || filePreviewClosing) return;
|
||||
filePreviewResizeCleanupRef.current?.();
|
||||
setClosingPreview({ key: previewSessionKey, path: filePreviewPath });
|
||||
setClosingPreview({ key: previewSessionKey, state: previewState });
|
||||
// Record the closed state immediately, even if navigation interrupts the animation.
|
||||
setFilePreviewPath(null);
|
||||
closePreview();
|
||||
filePreviewCloseTimerRef.current = window.setTimeout(() => {
|
||||
filePreviewCloseTimerRef.current = null;
|
||||
setClosingPreview(null);
|
||||
}, FILE_PREVIEW_CLOSE_ANIMATION_MS);
|
||||
}, [previewSessionKey, filePreviewClosing, filePreviewPath, setFilePreviewPath]);
|
||||
}, [previewSessionKey, filePreviewClosing, previewState, closePreview]);
|
||||
|
||||
const handleOpenFilePreview = useCallback((path: string) => {
|
||||
if (path === filePreviewPath && !filePreviewClosing) {
|
||||
handleCloseFilePreview();
|
||||
return;
|
||||
}
|
||||
const cancelPreviewClose = useCallback(() => {
|
||||
filePreviewResizeCleanupRef.current?.();
|
||||
if (filePreviewCloseTimerRef.current !== null) {
|
||||
window.clearTimeout(filePreviewCloseTimerRef.current);
|
||||
filePreviewCloseTimerRef.current = null;
|
||||
}
|
||||
setClosingPreview(null);
|
||||
setFilePreviewPath(path);
|
||||
}, [filePreviewPath, filePreviewClosing, handleCloseFilePreview, setFilePreviewPath]);
|
||||
}, []);
|
||||
|
||||
const handleOpenFilePreview = useCallback((path: string) => {
|
||||
cancelPreviewClose();
|
||||
openFile(path);
|
||||
}, [cancelPreviewClose, openFile]);
|
||||
|
||||
const handleClosePreviewTab = useCallback((id: string) => {
|
||||
if (previewState.tabs.length === 1) handleCloseFilePreview();
|
||||
else {
|
||||
filePreviewResizeCleanupRef.current?.();
|
||||
closeTab(id);
|
||||
}
|
||||
}, [previewState.tabs.length, handleCloseFilePreview, closeTab]);
|
||||
|
||||
// Markdown blocks can retain rendered links while their text is unchanged.
|
||||
// Keep their callback stable, but always act on the current pane/session state.
|
||||
@@ -1539,44 +1552,35 @@ export function ThreadShell({
|
||||
})
|
||||
: fetchFileReferenceMetadata(getToken(), previewSessionKey, path);
|
||||
}, [chatId, client, getToken, previewSessionKey, temporary]);
|
||||
const loadFilePreview = useCallback((path: string) => {
|
||||
if (!previewSessionKey) return Promise.reject(new Error("No active session"));
|
||||
return temporary ? loadTemporaryFilePreview(path) : fetchFilePreview(getToken(), previewSessionKey, path);
|
||||
}, [previewSessionKey, temporary, loadTemporaryFilePreview, getToken]);
|
||||
const filePreviews = useMemo(() => createFilePreviewResource(loadFilePreview), [loadFilePreview, token]);
|
||||
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]);
|
||||
loadPreview: filePreviews.load,
|
||||
}), [resolveFileMetadata, filePreviews]);
|
||||
|
||||
const openWebPreview = useCallback((url: string) => {
|
||||
const parsed = parseWebLink(url);
|
||||
if (!parsed) return;
|
||||
filePreviewResizeCleanupRef.current?.();
|
||||
if (filePreviewCloseTimerRef.current !== null) {
|
||||
window.clearTimeout(filePreviewCloseTimerRef.current);
|
||||
filePreviewCloseTimerRef.current = null;
|
||||
}
|
||||
setClosingPreview(null);
|
||||
setWebUrl(parsed.href);
|
||||
}, [setWebUrl]);
|
||||
|
||||
const closeWebPreview = useCallback(() => {
|
||||
filePreviewResizeCleanupRef.current?.();
|
||||
setWebUrl(null);
|
||||
}, [setWebUrl]);
|
||||
cancelPreviewClose();
|
||||
openWeb(parsed.href);
|
||||
}, [cancelPreviewClose, openWeb]);
|
||||
|
||||
useEffect(() => {
|
||||
if ((!filePreviewPath && !previewState.webUrl) || !headerActive) return;
|
||||
if (!previewOpen || !headerActive) return;
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key !== "Escape" || event.defaultPrevented || event.isComposing) return;
|
||||
// Let a dialog/menu above the pane consume Escape without closing this preview.
|
||||
if (document.querySelector('[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"], [data-radix-popper-content-wrapper]')) return;
|
||||
event.preventDefault();
|
||||
if (previewState.webUrl) closeWebPreview();
|
||||
else handleCloseFilePreview();
|
||||
handleCloseFilePreview();
|
||||
};
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
}, [filePreviewPath, previewState.webUrl, headerActive, handleCloseFilePreview, closeWebPreview]);
|
||||
}, [previewOpen, headerActive, handleCloseFilePreview]);
|
||||
|
||||
const handleFilePreviewResizeStart = useCallback((event: ReactPointerEvent<HTMLButtonElement>) => {
|
||||
filePreviewResizeCleanupRef.current?.();
|
||||
@@ -1640,7 +1644,7 @@ export function ThreadShell({
|
||||
}, [setFilePreviewWidth]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!filePreviewPath && !previewState.webUrl) return;
|
||||
if (!previewOpen) return;
|
||||
const clampToShell = () => {
|
||||
const shellWidth = shellRef.current?.getBoundingClientRect().width ?? window.innerWidth;
|
||||
const maxWidth = maxFilePreviewWidth(shellWidth);
|
||||
@@ -1654,7 +1658,7 @@ export function ThreadShell({
|
||||
observer?.disconnect();
|
||||
window.removeEventListener("resize", clampToShell);
|
||||
};
|
||||
}, [filePreviewPath, previewState.webUrl]);
|
||||
}, [previewOpen]);
|
||||
|
||||
const handleForkFromMessage = useCallback(
|
||||
async (beforeUserIndex: number) => {
|
||||
@@ -1813,6 +1817,7 @@ export function ThreadShell({
|
||||
|
||||
const threadHeader = !hideHeader ? (
|
||||
<ThreadHeader
|
||||
className={previewOpen ? "h-10" : undefined}
|
||||
title={title}
|
||||
onToggleSidebar={onToggleSidebar}
|
||||
theme={theme}
|
||||
@@ -1834,9 +1839,9 @@ export function ThreadShell({
|
||||
) : null;
|
||||
|
||||
return (
|
||||
<section ref={shellRef} className="relative flex min-h-0 flex-1 overflow-hidden">
|
||||
<section ref={shellRef} data-preview-open={previewOpen || undefined} className="thread-preview-layout relative flex min-h-0 flex-1 overflow-hidden">
|
||||
<div className={cn(
|
||||
"relative flex min-w-0 flex-1 flex-col overflow-hidden",
|
||||
"thread-conversation relative flex min-w-0 flex-1 flex-col overflow-hidden",
|
||||
headerPortalTarget === undefined && !hideHeader && "thread-workspace",
|
||||
)}>
|
||||
{hideHeaderTitle && inlineHandle && !temporary && session?.handle ? (
|
||||
@@ -1904,27 +1909,31 @@ export function ThreadShell({
|
||||
</div>,
|
||||
composerPortalTarget,
|
||||
) : null}
|
||||
{filePreviewPath && previewSessionKey ? (
|
||||
<FilePreviewPanel
|
||||
key={`${previewSessionKey}:${filePreviewPath}`}
|
||||
sessionKey={previewSessionKey}
|
||||
path={filePreviewPath}
|
||||
token={token}
|
||||
loadPreview={temporary ? loadTemporaryFilePreview : undefined}
|
||||
desktopWidth={filePreviewWidth}
|
||||
{activePreview && previewSessionKey ? (
|
||||
<FileActionsProvider key={previewSessionKey} value={fileActions}>
|
||||
<PreviewPane
|
||||
key={previewSessionKey}
|
||||
tabs={visiblePreview.tabs}
|
||||
activeId={activePreview.id}
|
||||
width={filePreviewWidth}
|
||||
isClosing={filePreviewClosing}
|
||||
onResizeStart={handleFilePreviewResizeStart}
|
||||
onSelect={selectTab}
|
||||
onCloseTab={handleClosePreviewTab}
|
||||
onClose={handleCloseFilePreview}
|
||||
/>
|
||||
) : null}
|
||||
{previewState.webUrl && previewSessionKey ? (
|
||||
<WebPreviewPanel
|
||||
key={`${previewSessionKey}:${previewState.webUrl}`}
|
||||
url={previewState.webUrl}
|
||||
desktopWidth={filePreviewWidth}
|
||||
onResizeStart={handleFilePreviewResizeStart}
|
||||
onClose={closeWebPreview}
|
||||
/>
|
||||
>
|
||||
{activePreview.kind === "file" ? (
|
||||
<FilePreviewPanel
|
||||
key={activePreview.id}
|
||||
sessionKey={previewSessionKey}
|
||||
path={activePreview.value}
|
||||
token={token}
|
||||
loadPreview={filePreviews.load}
|
||||
initialPreview={filePreviews.peek(activePreview.value)}
|
||||
/>
|
||||
) : <WebPreviewPanel key={activePreview.id} url={activePreview.value} />}
|
||||
</PreviewPane>
|
||||
</FileActionsProvider>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -732,7 +732,9 @@ export function PaneWorkbench({
|
||||
>
|
||||
{renderPane(pane, {
|
||||
active,
|
||||
headerPortalTarget: chrome ? headerPortalTarget : undefined,
|
||||
// A single conversation owns its header, alongside its preview tabs.
|
||||
// Multiple conversation panes still share the workbench toolbar.
|
||||
headerPortalTarget: chrome && displayedPanes.length > 1 ? headerPortalTarget : undefined,
|
||||
composerPortalTarget: chrome ? composerPortalTarget : undefined,
|
||||
headerActions,
|
||||
})}
|
||||
|
||||
+28
-1
@@ -607,7 +607,34 @@
|
||||
.thread-workspace {
|
||||
container: thread-workspace / inline-size;
|
||||
}
|
||||
/* The full-width toolbar must not cover the preview breadcrumb or close button. */
|
||||
.thread-preview-layout {
|
||||
container: thread-preview-layout / inline-size;
|
||||
}
|
||||
/* A split needs 420px for the conversation plus 360px for the preview.
|
||||
Narrow workbench panes use the same contained overlay as a phone. */
|
||||
@container thread-preview-layout (min-width: 780px) {
|
||||
.file-preview-pane {
|
||||
position: relative;
|
||||
z-index: auto;
|
||||
width: var(--file-preview-slot-width);
|
||||
min-width: 0;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.file-preview-content {
|
||||
width: var(--file-preview-width);
|
||||
padding-bottom: 0;
|
||||
}
|
||||
.file-preview-resize {
|
||||
display: flex;
|
||||
}
|
||||
}
|
||||
@container thread-preview-layout (width < 780px) {
|
||||
/* Covered conversation controls must not remain in the keyboard/AT order. */
|
||||
.thread-preview-layout[data-preview-open] > .thread-conversation {
|
||||
visibility: hidden;
|
||||
}
|
||||
}
|
||||
/* Split content leaves no margin for floating conversation controls. */
|
||||
.thread-workspace:has([data-file-preview-panel]) > * {
|
||||
--thread-header-position: relative;
|
||||
--thread-prompt-inset: 1rem;
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
import { useCallback, useState, useSyncExternalStore } from "react";
|
||||
|
||||
interface FilePreviewState {
|
||||
path: string | null;
|
||||
webUrl?: string | null;
|
||||
export interface PreviewTab {
|
||||
id: string;
|
||||
kind: "file" | "web";
|
||||
value: string;
|
||||
}
|
||||
|
||||
export interface FilePreviewState {
|
||||
tabs: PreviewTab[];
|
||||
activeId: string | null;
|
||||
width: number;
|
||||
}
|
||||
|
||||
const EMPTY_PREVIEW: FilePreviewState = { path: null, width: 544 };
|
||||
const EMPTY_PREVIEW: FilePreviewState = { tabs: [], activeId: null, width: 544 };
|
||||
|
||||
/** App-lifetime view state only. Never stores file contents or writes to browser storage. */
|
||||
export class FilePreviewStore {
|
||||
@@ -25,13 +31,37 @@ export class FilePreviewStore {
|
||||
update(key: string, patch: Partial<FilePreviewState>) {
|
||||
const previous = this.get(key);
|
||||
const next = { ...previous, ...patch };
|
||||
if (patch.path) next.webUrl = null;
|
||||
if (patch.webUrl) next.path = null;
|
||||
if (previous.path === next.path && previous.width === next.width && previous.webUrl === next.webUrl) return;
|
||||
if (previous.tabs === next.tabs && previous.width === next.width && previous.activeId === next.activeId) return;
|
||||
this.states.set(key, next);
|
||||
this.listeners.forEach((listener) => listener());
|
||||
}
|
||||
|
||||
open(key: string, kind: PreviewTab["kind"], value: string) {
|
||||
const previous = this.get(key);
|
||||
const id = `${kind}:${value}`;
|
||||
const tabs = previous.tabs.some((tab) => tab.id === id)
|
||||
? previous.tabs : [...previous.tabs, { id, kind, value }];
|
||||
this.update(key, { tabs, activeId: id });
|
||||
}
|
||||
|
||||
select(key: string, id: string) {
|
||||
if (this.get(key).tabs.some((tab) => tab.id === id)) this.update(key, { activeId: id });
|
||||
}
|
||||
|
||||
closeTab(key: string, id: string) {
|
||||
const previous = this.get(key);
|
||||
const index = previous.tabs.findIndex((tab) => tab.id === id);
|
||||
if (index < 0) return;
|
||||
const tabs = previous.tabs.filter((tab) => tab.id !== id);
|
||||
const activeId = previous.activeId === id
|
||||
? (tabs[Math.min(index, tabs.length - 1)]?.id ?? null) : previous.activeId;
|
||||
this.update(key, { tabs, activeId });
|
||||
}
|
||||
|
||||
close(key: string) {
|
||||
this.update(key, { tabs: [], activeId: null });
|
||||
}
|
||||
|
||||
delete(key: string) {
|
||||
if (this.states.delete(key)) this.listeners.forEach((listener) => listener());
|
||||
}
|
||||
@@ -47,14 +77,23 @@ export function useFilePreviewState(key: string | null, sharedStore?: FilePrevie
|
||||
const store = sharedStore ?? localStore;
|
||||
const snapshot = useCallback(() => store.get(key), [key, store]);
|
||||
const state = useSyncExternalStore(store.subscribe, snapshot, snapshot);
|
||||
const setPath = useCallback((path: string | null) => {
|
||||
if (key) store.update(key, { path });
|
||||
const openFile = useCallback((path: string) => {
|
||||
if (key) store.open(key, "file", path);
|
||||
}, [key, store]);
|
||||
const setWidth = useCallback((width: number) => {
|
||||
if (key) store.update(key, { width });
|
||||
}, [key, store]);
|
||||
const setWebUrl = useCallback((webUrl: string | null) => {
|
||||
if (key) store.update(key, { webUrl });
|
||||
const openWeb = useCallback((url: string) => {
|
||||
if (key) store.open(key, "web", url);
|
||||
}, [key, store]);
|
||||
return { state, setPath, setWidth, setWebUrl };
|
||||
const selectTab = useCallback((id: string) => {
|
||||
if (key) store.select(key, id);
|
||||
}, [key, store]);
|
||||
const closeTab = useCallback((id: string) => {
|
||||
if (key) store.closeTab(key, id);
|
||||
}, [key, store]);
|
||||
const close = useCallback(() => {
|
||||
if (key) store.close(key);
|
||||
}, [key, store]);
|
||||
return { state, openFile, openWeb, selectTab, closeTab, close, setWidth };
|
||||
}
|
||||
@@ -1,4 +1,10 @@
|
||||
{
|
||||
"previewTabs": {
|
||||
"title": "Preview",
|
||||
"closeTab": "Close {{name}}",
|
||||
"closeAll": "Close preview pane",
|
||||
"websiteInfo": "About website previews"
|
||||
},
|
||||
"webPreview": {
|
||||
"original": "Original link",
|
||||
"actions": "Link actions",
|
||||
@@ -1897,6 +1903,11 @@
|
||||
"continue": "Continue"
|
||||
},
|
||||
"lightbox": {
|
||||
"viewAll": "View all {{count}} images",
|
||||
"zoomIn": "Zoom in",
|
||||
"zoomOut": "Zoom out",
|
||||
"resetZoom": "Fit image",
|
||||
"gestures": "Pinch or double-click to zoom. Drag to move when zoomed. Use +, − or 0 to zoom or reset.",
|
||||
"title": "Image preview",
|
||||
"open": "View image",
|
||||
"prev": "Previous image",
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
{
|
||||
"previewTabs": {
|
||||
"title": "Vista previa",
|
||||
"closeTab": "Cerrar {{name}}",
|
||||
"closeAll": "Cerrar panel de vista previa",
|
||||
"websiteInfo": "Acerca de las vistas previas web"
|
||||
},
|
||||
"webPreview": {
|
||||
"original": "Enlace original",
|
||||
"actions": "Acciones del enlace",
|
||||
@@ -1698,6 +1704,11 @@
|
||||
"continue": "Continuar"
|
||||
},
|
||||
"lightbox": {
|
||||
"viewAll": "Ver las {{count}} imágenes",
|
||||
"zoomIn": "Acercar",
|
||||
"zoomOut": "Alejar",
|
||||
"resetZoom": "Ajustar imagen",
|
||||
"gestures": "Pellizca o haz doble clic para ampliar. Arrastra para mover. Usa +, − o 0 para ampliar o restablecer.",
|
||||
"title": "Vista previa de imagen",
|
||||
"open": "Ver imagen",
|
||||
"prev": "Imagen anterior",
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
{
|
||||
"previewTabs": {
|
||||
"title": "Aperçu",
|
||||
"closeTab": "Fermer {{name}}",
|
||||
"closeAll": "Fermer le panneau d’aperçu",
|
||||
"websiteInfo": "À propos des aperçus web"
|
||||
},
|
||||
"webPreview": {
|
||||
"original": "Lien d’origine",
|
||||
"actions": "Actions du lien",
|
||||
@@ -1697,6 +1703,11 @@
|
||||
"continue": "Continuer"
|
||||
},
|
||||
"lightbox": {
|
||||
"viewAll": "Voir les {{count}} images",
|
||||
"zoomIn": "Agrandir",
|
||||
"zoomOut": "Réduire",
|
||||
"resetZoom": "Ajuster l’image",
|
||||
"gestures": "Pincez ou double-cliquez pour zoomer. Faites glisser pour déplacer. Utilisez +, − ou 0 pour zoomer ou réinitialiser.",
|
||||
"title": "Aperçu de l’image",
|
||||
"open": "Voir l’image",
|
||||
"prev": "Image précédente",
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
{
|
||||
"previewTabs": {
|
||||
"title": "Pratinjau",
|
||||
"closeTab": "Tutup {{name}}",
|
||||
"closeAll": "Tutup panel pratinjau",
|
||||
"websiteInfo": "Tentang pratinjau situs"
|
||||
},
|
||||
"webPreview": {
|
||||
"original": "Tautan asli",
|
||||
"actions": "Tindakan tautan",
|
||||
@@ -1697,6 +1703,11 @@
|
||||
"continue": "Lanjutkan"
|
||||
},
|
||||
"lightbox": {
|
||||
"viewAll": "Lihat semua {{count}} gambar",
|
||||
"zoomIn": "Perbesar",
|
||||
"zoomOut": "Perkecil",
|
||||
"resetZoom": "Sesuaikan gambar",
|
||||
"gestures": "Cubit atau klik dua kali untuk memperbesar. Seret untuk menggeser. Gunakan +, − atau 0 untuk memperbesar atau mereset.",
|
||||
"title": "Pratinjau gambar",
|
||||
"open": "Lihat gambar",
|
||||
"prev": "Gambar sebelumnya",
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
{
|
||||
"previewTabs": {
|
||||
"title": "プレビュー",
|
||||
"closeTab": "{{name}} を閉じる",
|
||||
"closeAll": "プレビューパネルを閉じる",
|
||||
"websiteInfo": "ウェブプレビューについて"
|
||||
},
|
||||
"webPreview": {
|
||||
"original": "元のリンク",
|
||||
"actions": "リンク操作",
|
||||
@@ -1697,6 +1703,11 @@
|
||||
"continue": "続行"
|
||||
},
|
||||
"lightbox": {
|
||||
"viewAll": "すべての画像({{count}} 枚)を表示",
|
||||
"zoomIn": "拡大",
|
||||
"zoomOut": "縮小",
|
||||
"resetZoom": "画面に合わせる",
|
||||
"gestures": "ピンチまたはダブルクリックで拡大し、ドラッグで移動できます。+、−、0 キーで拡大・縮小・リセットできます。",
|
||||
"title": "画像プレビュー",
|
||||
"open": "画像を表示",
|
||||
"prev": "前の画像",
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
{
|
||||
"previewTabs": {
|
||||
"title": "미리보기",
|
||||
"closeTab": "{{name}} 닫기",
|
||||
"closeAll": "미리보기 패널 닫기",
|
||||
"websiteInfo": "웹 미리보기 정보"
|
||||
},
|
||||
"webPreview": {
|
||||
"original": "원래 링크",
|
||||
"actions": "링크 작업",
|
||||
@@ -1697,6 +1703,11 @@
|
||||
"continue": "계속"
|
||||
},
|
||||
"lightbox": {
|
||||
"viewAll": "이미지 {{count}}개 모두 보기",
|
||||
"zoomIn": "확대",
|
||||
"zoomOut": "축소",
|
||||
"resetZoom": "화면에 맞추기",
|
||||
"gestures": "두 손가락이나 두 번 클릭으로 확대하고 드래그로 이동하세요. +, −, 0 키로 확대, 축소 또는 초기화할 수 있습니다.",
|
||||
"title": "이미지 미리보기",
|
||||
"open": "이미지 보기",
|
||||
"prev": "이전 이미지",
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
{
|
||||
"previewTabs": {
|
||||
"title": "Prévia",
|
||||
"closeTab": "Fechar {{name}}",
|
||||
"closeAll": "Fechar painel de prévia",
|
||||
"websiteInfo": "Sobre as prévias de sites"
|
||||
},
|
||||
"webPreview": {
|
||||
"original": "Link original",
|
||||
"actions": "Ações do link",
|
||||
@@ -1711,6 +1717,11 @@
|
||||
"continue": "Continuar"
|
||||
},
|
||||
"lightbox": {
|
||||
"viewAll": "Ver todas as {{count}} imagens",
|
||||
"zoomIn": "Ampliar",
|
||||
"zoomOut": "Reduzir",
|
||||
"resetZoom": "Ajustar imagem",
|
||||
"gestures": "Faça o gesto de pinça ou clique duas vezes para ampliar. Arraste para mover. Use +, − ou 0 para ampliar ou redefinir.",
|
||||
"title": "Pré-visualização de imagem",
|
||||
"open": "Ver imagem",
|
||||
"prev": "Imagem anterior",
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
{
|
||||
"previewTabs": {
|
||||
"title": "Xem trước",
|
||||
"closeTab": "Đóng {{name}}",
|
||||
"closeAll": "Đóng khung xem trước",
|
||||
"websiteInfo": "Giới thiệu về xem trước trang web"
|
||||
},
|
||||
"webPreview": {
|
||||
"original": "Liên kết gốc",
|
||||
"actions": "Thao tác liên kết",
|
||||
@@ -1697,6 +1703,11 @@
|
||||
"continue": "Tiếp tục"
|
||||
},
|
||||
"lightbox": {
|
||||
"viewAll": "Xem tất cả {{count}} ảnh",
|
||||
"zoomIn": "Phóng to",
|
||||
"zoomOut": "Thu nhỏ",
|
||||
"resetZoom": "Vừa khung hình",
|
||||
"gestures": "Chụm ngón tay hoặc nhấp đúp để thu phóng. Kéo để di chuyển. Dùng +, − hoặc 0 để thu phóng hoặc đặt lại.",
|
||||
"title": "Xem trước ảnh",
|
||||
"open": "Xem ảnh",
|
||||
"prev": "Ảnh trước",
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
{
|
||||
"previewTabs": {
|
||||
"title": "预览",
|
||||
"closeTab": "关闭 {{name}}",
|
||||
"closeAll": "关闭预览栏",
|
||||
"websiteInfo": "关于网页预览"
|
||||
},
|
||||
"webPreview": {
|
||||
"original": "原始链接",
|
||||
"actions": "链接操作",
|
||||
@@ -1897,6 +1903,11 @@
|
||||
"continue": "继续"
|
||||
},
|
||||
"lightbox": {
|
||||
"viewAll": "查看全部 {{count}} 张图片",
|
||||
"zoomIn": "放大",
|
||||
"zoomOut": "缩小",
|
||||
"resetZoom": "适应窗口",
|
||||
"gestures": "双指捏合或双击缩放,放大后拖动查看。也可按 +、− 或 0 缩放或复位。",
|
||||
"title": "图片预览",
|
||||
"open": "查看图片",
|
||||
"prev": "上一张",
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
{
|
||||
"previewTabs": {
|
||||
"title": "預覽",
|
||||
"closeTab": "關閉 {{name}}",
|
||||
"closeAll": "關閉預覽欄",
|
||||
"websiteInfo": "關於網頁預覽"
|
||||
},
|
||||
"webPreview": {
|
||||
"original": "原始連結",
|
||||
"actions": "連結操作",
|
||||
@@ -1697,6 +1703,11 @@
|
||||
"continue": "繼續"
|
||||
},
|
||||
"lightbox": {
|
||||
"viewAll": "查看全部 {{count}} 張圖片",
|
||||
"zoomIn": "放大",
|
||||
"zoomOut": "縮小",
|
||||
"resetZoom": "符合視窗",
|
||||
"gestures": "雙指捏合或按兩下縮放,放大後拖曳查看。也可按 +、− 或 0 縮放或重設。",
|
||||
"title": "圖片預覽",
|
||||
"open": "檢視圖片",
|
||||
"prev": "上一張",
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { FilePreviewPayload } from "@/lib/types";
|
||||
|
||||
const FRESH_MS = 5_000;
|
||||
const RETAIN_MS = 60_000;
|
||||
const MAX_ENTRIES = 4;
|
||||
const MAX_BYTES = 8 * 1024 * 1024;
|
||||
|
||||
/** Short-lived, in-memory only. The caller owns one resource per session/loader. */
|
||||
export function createFilePreviewResource(fetchPreview: (path: string) => Promise<FilePreviewPayload>) {
|
||||
const entries = new Map<string, {
|
||||
payload?: FilePreviewPayload;
|
||||
pending?: Promise<FilePreviewPayload>;
|
||||
loadedAt: number;
|
||||
bytes: number;
|
||||
}>();
|
||||
const peek = (path: string) => {
|
||||
const entry = entries.get(path);
|
||||
return entry?.payload && Date.now() - entry.loadedAt < RETAIN_MS ? entry.payload : undefined;
|
||||
};
|
||||
const load = (path: string): Promise<FilePreviewPayload> => {
|
||||
const existing = entries.get(path);
|
||||
if (existing?.pending) return existing.pending;
|
||||
if (existing?.payload && Date.now() - existing.loadedAt < FRESH_MS) {
|
||||
return Promise.resolve(existing.payload);
|
||||
}
|
||||
const entry = { payload: peek(path), loadedAt: existing?.loadedAt ?? 0, bytes: existing?.bytes ?? 0,
|
||||
pending: undefined as Promise<FilePreviewPayload> | undefined };
|
||||
entries.delete(path);
|
||||
entries.set(path, entry);
|
||||
while (entries.size > MAX_ENTRIES) entries.delete(entries.keys().next().value!);
|
||||
entry.pending = Promise.resolve().then(() => fetchPreview(path)).then((payload) => {
|
||||
// An evicted request may finish, but must not put its data back into the cache.
|
||||
if (entries.get(path) === entry) {
|
||||
entry.payload = payload;
|
||||
entry.pending = undefined;
|
||||
entry.loadedAt = Date.now();
|
||||
entry.bytes = 2 * (payload.kind === "image" ? payload.data_url.length : payload.content.length);
|
||||
let total = [...entries.values()].reduce((sum, item) => sum + item.bytes, 0);
|
||||
for (const [key, item] of entries) {
|
||||
if (total <= MAX_BYTES) break;
|
||||
total -= item.bytes;
|
||||
entries.delete(key);
|
||||
}
|
||||
}
|
||||
return payload;
|
||||
}, (error: unknown) => {
|
||||
if (entries.get(path) === entry) entries.delete(path);
|
||||
throw error;
|
||||
});
|
||||
return entry.pending;
|
||||
};
|
||||
return { peek, load };
|
||||
}
|
||||
@@ -16,22 +16,28 @@ describe("File actions", () => {
|
||||
it("resolves paths only when opened and uses the same menu for both copies", async () => {
|
||||
const user = userEvent.setup();
|
||||
const resolveMetadata = vi.fn().mockResolvedValue(details);
|
||||
const openPreview = vi.fn();
|
||||
render(<FileActionsProvider value={{ resolveMetadata, openPreview }}>
|
||||
render(<FileActionsProvider value={{ resolveMetadata }}>
|
||||
<FileReferenceChip path="notes.md:12" onOpen={vi.fn()} />
|
||||
</FileActionsProvider>);
|
||||
expect(resolveMetadata).not.toHaveBeenCalled();
|
||||
await user.click(screen.getByRole("button", { name: "File actions for notes.md:12" }));
|
||||
expect(screen.queryByRole("button", { name: /File actions/ })).not.toBeInTheDocument();
|
||||
fireEvent.contextMenu(screen.getByRole("button", { name: "notes.md:12" }), { clientX: 100, clientY: 200 });
|
||||
await waitFor(() => expect(screen.getByRole("menuitem", { name: "Copy absolute path" })).not.toHaveAttribute("data-disabled"));
|
||||
expect(resolveMetadata).toHaveBeenCalledWith("notes.md:12");
|
||||
expect(screen.queryByRole("menuitem", { name: "Preview" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("Paths refer to the gateway machine.")).not.toBeInTheDocument();
|
||||
expect(screen.getAllByRole("menuitem")).toHaveLength(2);
|
||||
await user.click(screen.getByRole("menuitem", { name: "Copy absolute path" }));
|
||||
expect(copyTextToClipboard).toHaveBeenLastCalledWith(details.path);
|
||||
expect(await screen.findByText("Copied")).toBeVisible();
|
||||
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
|
||||
expect(screen.getByRole("button", { name: "notes.md:12" })).toHaveFocus();
|
||||
fireEvent.contextMenu(screen.getByRole("button", { name: "notes.md:12" }));
|
||||
await waitFor(() => expect(screen.getByRole("menuitem", { name: "Copy relative path" })).not.toHaveAttribute("data-disabled"));
|
||||
await user.click(screen.getByRole("menuitem", { name: "Copy relative path" }));
|
||||
expect(copyTextToClipboard).toHaveBeenLastCalledWith("notes.md");
|
||||
await user.click(screen.getByRole("menuitem", { name: "Preview" }));
|
||||
expect(openPreview).toHaveBeenCalledWith("notes.md:12");
|
||||
expect(screen.queryByRole("menu")).not.toBeInTheDocument();
|
||||
await user.keyboard("{Escape}");
|
||||
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
|
||||
expect(screen.getByRole("button", { name: "notes.md:12" })).toHaveFocus();
|
||||
});
|
||||
|
||||
it("keeps primary click working and supports context menu and Shift+F10", async () => {
|
||||
@@ -43,17 +49,21 @@ describe("File actions", () => {
|
||||
expect(onOpen).toHaveBeenCalledTimes(1);
|
||||
expect(onOpen).toHaveBeenCalledWith("src/app.ts");
|
||||
fireEvent.contextMenu(reference);
|
||||
expect(await screen.findByRole("menuitem", { name: "Preview" })).toBeVisible();
|
||||
expect(await screen.findByRole("menuitem", { name: "Copy reference" })).toBeVisible();
|
||||
await user.keyboard("{Escape}");
|
||||
fireEvent.keyDown(reference, { key: "F10", shiftKey: true });
|
||||
expect(await screen.findByRole("menuitem", { name: "Copy reference" })).toBeVisible();
|
||||
expect(onOpen).toHaveBeenCalledTimes(1);
|
||||
await user.keyboard("{Escape}");
|
||||
fireEvent.keyDown(reference, { key: "ContextMenu" });
|
||||
expect(await screen.findByRole("menuitem", { name: "Copy reference" })).toBeVisible();
|
||||
expect(onOpen).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("does not invent a relative path for files outside the project", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<FileActions path="/media/image.png" metadata={{ path: "/media/image.png", relative_path: null }} />);
|
||||
await user.click(screen.getByRole("button", { name: "File actions for image.png" }));
|
||||
render(<FileActions path="/media/image.png" metadata={{ path: "/media/image.png", relative_path: null }}><button>image.png</button></FileActions>);
|
||||
fireEvent.contextMenu(screen.getByRole("button", { name: "image.png" }));
|
||||
expect(screen.getByRole("menuitem", { name: "Copy relative path" })).toHaveAttribute("data-disabled");
|
||||
expect(screen.queryByRole("menuitem", { name: "Preview" })).not.toBeInTheDocument();
|
||||
await user.click(screen.getByRole("menuitem", { name: "Copy absolute path" }));
|
||||
@@ -63,10 +73,10 @@ describe("File actions", () => {
|
||||
it("retains the original reference if resolution fails and reports clipboard errors", async () => {
|
||||
const user = userEvent.setup();
|
||||
vi.mocked(copyTextToClipboard).mockResolvedValue(false);
|
||||
render(<FileActionsProvider value={{ resolveMetadata: vi.fn().mockRejectedValue(new Error("404")), openPreview: vi.fn() }}>
|
||||
render(<FileActionsProvider value={{ resolveMetadata: vi.fn().mockRejectedValue(new Error("404")) }}>
|
||||
<FileReferenceChip path="missing.txt" onOpen={vi.fn()} />
|
||||
</FileActionsProvider>);
|
||||
await user.click(screen.getByRole("button", { name: "File actions for missing.txt" }));
|
||||
fireEvent.contextMenu(screen.getByRole("button", { name: "missing.txt" }));
|
||||
expect(await screen.findByText(/Could not resolve this file/)).toBeVisible();
|
||||
expect(screen.getByRole("menuitem", { name: "Copy absolute path" })).toHaveAttribute("data-disabled");
|
||||
await user.click(screen.getByRole("menuitem", { name: "Copy reference" }));
|
||||
@@ -77,11 +87,11 @@ describe("File actions", () => {
|
||||
it("ignores late metadata from a previous session", async () => {
|
||||
const user = userEvent.setup();
|
||||
let resolveOld!: (value: FileReferenceMetadata) => void;
|
||||
const previous = { resolveMetadata: () => new Promise<FileReferenceMetadata>((resolve) => { resolveOld = resolve; }), openPreview: vi.fn() };
|
||||
const current = { resolveMetadata: vi.fn().mockResolvedValue({ path: "/new/notes.md", relative_path: "notes.md" }), openPreview: vi.fn() };
|
||||
const previous = { resolveMetadata: () => new Promise<FileReferenceMetadata>((resolve) => { resolveOld = resolve; }) };
|
||||
const current = { resolveMetadata: vi.fn().mockResolvedValue({ path: "/new/notes.md", relative_path: "notes.md" }) };
|
||||
const view = (value: typeof current | typeof previous) => <FileActionsProvider value={value}><FileReferenceChip path="notes.md" onOpen={vi.fn()} /></FileActionsProvider>;
|
||||
const { rerender } = render(view(previous));
|
||||
await user.click(screen.getByRole("button", { name: "File actions for notes.md" }));
|
||||
fireEvent.contextMenu(screen.getByRole("button", { name: "notes.md" }));
|
||||
rerender(view(current));
|
||||
await waitFor(() => expect(current.resolveMetadata).toHaveBeenCalled());
|
||||
await act(async () => resolveOld(details));
|
||||
@@ -91,10 +101,10 @@ describe("File actions", () => {
|
||||
|
||||
it("degrades to the original reference on an older gateway response", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<FileActionsProvider value={{ resolveMetadata: vi.fn().mockResolvedValue({ path: "/workspace/notes.md", content: "old preview response" }), openPreview: vi.fn() }}>
|
||||
render(<FileActionsProvider value={{ resolveMetadata: vi.fn().mockResolvedValue({ path: "/workspace/notes.md", content: "old preview response" }) }}>
|
||||
<FileReferenceChip path="notes.md" onOpen={vi.fn()} />
|
||||
</FileActionsProvider>);
|
||||
await user.click(screen.getByRole("button", { name: "File actions for notes.md" }));
|
||||
fireEvent.contextMenu(screen.getByRole("button", { name: "notes.md" }));
|
||||
expect(await screen.findByText(/Could not resolve this file/)).toBeVisible();
|
||||
expect(screen.getByRole("menuitem", { name: "Copy absolute path" })).toHaveAttribute("data-disabled");
|
||||
await user.click(screen.getByRole("menuitem", { name: "Copy reference" }));
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { FilePreviewPanel } from "@/components/FilePreviewPanel";
|
||||
@@ -46,7 +45,7 @@ describe("FilePreviewPanel", () => {
|
||||
kind: "image", path: "/workspace/chart.png", display_path: "chart.png",
|
||||
project_path: "/workspace", size: 42, mime_type: "image/png", data_url: dataUrl,
|
||||
});
|
||||
render(<FilePreviewPanel sessionKey="websocket:a" path="chart.png" token="test" onClose={() => {}} />);
|
||||
render(<FilePreviewPanel sessionKey="websocket:a" path="chart.png" token="test" />);
|
||||
const img = await screen.findByRole("img", { name: "chart.png" });
|
||||
expect(img).toHaveAttribute("src", dataUrl);
|
||||
expect(screen.queryByTestId("mock-code-block")).not.toBeInTheDocument();
|
||||
@@ -62,7 +61,7 @@ describe("FilePreviewPanel", () => {
|
||||
language: "text", content: "session B", truncated: false, size: 9,
|
||||
};
|
||||
vi.mocked(fetchFilePreview).mockResolvedValueOnce(payload);
|
||||
const view = (key: string) => <FilePreviewPanel key={key} sessionKey={key} path="notes.txt" token="test" onClose={() => {}} />;
|
||||
const view = (key: string) => <FilePreviewPanel key={key} sessionKey={key} path="notes.txt" token="test" />;
|
||||
const { rerender } = render(view("a"));
|
||||
rerender(view("b"));
|
||||
await screen.findByText("session B");
|
||||
@@ -70,9 +69,27 @@ describe("FilePreviewPanel", () => {
|
||||
expect(screen.queryByText("session A")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows a compact breadcrumb with one file name and a visible close action", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onClose = vi.fn();
|
||||
it("opens the sidebar image in the shared zoomable viewer and returns to the preview", async () => {
|
||||
vi.mocked(fetchFilePreview).mockResolvedValue({
|
||||
kind: "image", path: "/workspace/chart.png", display_path: "chart.png",
|
||||
size: 42, mime_type: "image/png", data_url: "data:image/png;base64,example",
|
||||
});
|
||||
render(<FilePreviewPanel sessionKey="websocket:a" path="chart.png" token="test" />);
|
||||
const trigger = await screen.findByRole("button", { name: "View image: chart.png" });
|
||||
trigger.focus();
|
||||
fireEvent.click(trigger);
|
||||
const dialog = screen.getByRole("dialog");
|
||||
expect(within(dialog).getByRole("img", { name: "chart.png" })).toBeInTheDocument();
|
||||
fireEvent.click(within(dialog).getByRole("button", { name: "Zoom in" }));
|
||||
expect(within(dialog).getByRole("button", { name: "Fit image" })).toHaveTextContent("150%");
|
||||
fireEvent.keyDown(dialog, { key: "Escape" });
|
||||
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
|
||||
await waitFor(() => expect(trigger).toHaveFocus());
|
||||
expect(screen.getByTestId("file-preview-panel")).toBeInTheDocument();
|
||||
expect(fetchFilePreview).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("renders file content without a second filename or breadcrumb below the tabs", async () => {
|
||||
vi.mocked(fetchFilePreview).mockResolvedValue({
|
||||
path: "/Users/hr/workspace/quicksort.py",
|
||||
display_path: "quicksort.py",
|
||||
@@ -86,7 +103,6 @@ describe("FilePreviewPanel", () => {
|
||||
sessionKey="websocket:chat-1"
|
||||
path="quicksort.py"
|
||||
token="tok"
|
||||
onClose={onClose}
|
||||
/>,
|
||||
);
|
||||
|
||||
@@ -94,16 +110,33 @@ describe("FilePreviewPanel", () => {
|
||||
expect(codeBlock).toHaveTextContent("print('ok')");
|
||||
expect(codeBlock).toHaveAttribute("data-language", "python");
|
||||
expect(codeBlock).toHaveAttribute("data-highlight", "true");
|
||||
expect(screen.getByTestId("file-preview-breadcrumb")).toHaveTextContent("...");
|
||||
expect(screen.getByTestId("file-preview-breadcrumb")).toHaveTextContent("workspace");
|
||||
expect(screen.getByTestId("file-preview-title")).toHaveTextContent("quicksort.py");
|
||||
expect(screen.getAllByText("quicksort.py")).toHaveLength(1);
|
||||
expect(screen.queryByTestId("file-preview-breadcrumb")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("quicksort.py")).not.toBeInTheDocument();
|
||||
|
||||
const closeButton = screen.getByRole("button", { name: "Close file preview" });
|
||||
expect(closeButton).toBeVisible();
|
||||
});
|
||||
|
||||
await user.click(closeButton);
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
it("paints cached content immediately, revalidates it, and does not restart when the cache ages", async () => {
|
||||
const cached = { path: "notes.txt", display_path: "notes.txt", language: "text", content: "Cached", truncated: false };
|
||||
let resolve!: (payload: typeof cached) => void;
|
||||
const loadPreview = vi.fn(() => new Promise<typeof cached>(r => { resolve = r; }));
|
||||
const view = (initialPreview?: typeof cached) => <FilePreviewPanel sessionKey="a" path="notes.txt"
|
||||
token="test" loadPreview={loadPreview} initialPreview={initialPreview} />;
|
||||
const { rerender } = render(view(cached));
|
||||
expect(screen.getByTestId("mock-code-block")).toHaveTextContent("Cached");
|
||||
expect(screen.queryByRole("status")).not.toBeInTheDocument();
|
||||
await act(async () => resolve({ ...cached, content: "Updated" }));
|
||||
expect(screen.getByTestId("mock-code-block")).toHaveTextContent("Updated");
|
||||
rerender(view());
|
||||
expect(screen.getByTestId("mock-code-block")).toHaveTextContent("Updated");
|
||||
expect(loadPreview).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("reports a failed revalidation rather than leaving stale cached content looking current", async () => {
|
||||
const cached = { path: "notes.txt", display_path: "notes.txt", language: "text", content: "Cached", truncated: false };
|
||||
render(<FilePreviewPanel sessionKey="a" path="notes.txt" token="test" initialPreview={cached}
|
||||
loadPreview={vi.fn().mockRejectedValue(new Error("Forbidden"))} />);
|
||||
await screen.findByText("Could not preview this file.");
|
||||
expect(screen.queryByText("Cached")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("updates translated chrome without refetching the open file", async () => {
|
||||
@@ -120,7 +153,6 @@ describe("FilePreviewPanel", () => {
|
||||
sessionKey="websocket:chat-1"
|
||||
path="notes.md"
|
||||
token="tok"
|
||||
onClose={() => {}}
|
||||
/>,
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { createFilePreviewResource } from "@/lib/file-preview-resource";
|
||||
import type { FilePreviewPayload } from "@/lib/types";
|
||||
|
||||
const payload: FilePreviewPayload = { path: "notes.txt", display_path: "notes.txt", content: "One", language: "text", truncated: false };
|
||||
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
describe("session-scoped file previews", () => {
|
||||
it("shares hover and click requests, then immediately reuses a recently viewed file", async () => {
|
||||
const fetchPreview = vi.fn().mockResolvedValue(payload);
|
||||
const resource = createFilePreviewResource(fetchPreview);
|
||||
const hover = resource.load("notes.txt");
|
||||
expect(resource.load("notes.txt")).toBe(hover);
|
||||
await hover;
|
||||
expect(resource.peek("notes.txt")).toBe(payload);
|
||||
expect(await resource.load("notes.txt")).toBe(payload);
|
||||
expect(fetchPreview).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("revalidates older content without losing the snapshot, but does not retain it forever", async () => {
|
||||
vi.useFakeTimers();
|
||||
const updated = { ...payload, content: "Two" };
|
||||
const fetchPreview = vi.fn().mockResolvedValueOnce(payload).mockResolvedValueOnce(updated);
|
||||
const resource = createFilePreviewResource(fetchPreview);
|
||||
await resource.load("notes.txt");
|
||||
vi.advanceTimersByTime(5_001);
|
||||
expect(resource.peek("notes.txt")).toBe(payload);
|
||||
expect(await resource.load("notes.txt")).toBe(updated);
|
||||
expect(fetchPreview).toHaveBeenCalledTimes(2);
|
||||
vi.advanceTimersByTime(60_001);
|
||||
expect(resource.peek("notes.txt")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("does not hide authorization failures behind cached data and allows a retry", async () => {
|
||||
vi.useFakeTimers();
|
||||
const fetchPreview = vi.fn().mockResolvedValueOnce(payload).mockRejectedValueOnce(new Error("401")).mockResolvedValueOnce(payload);
|
||||
const resource = createFilePreviewResource(fetchPreview);
|
||||
await resource.load("notes.txt");
|
||||
vi.advanceTimersByTime(5_001);
|
||||
await expect(resource.load("notes.txt")).rejects.toThrow("401");
|
||||
expect(resource.peek("notes.txt")).toBeUndefined();
|
||||
expect(await resource.load("notes.txt")).toBe(payload);
|
||||
});
|
||||
|
||||
it("bounds entries and payload bytes; late evicted requests cannot refill the cache", async () => {
|
||||
let resolve!: (value: FilePreviewPayload) => void;
|
||||
const fetchPreview = vi.fn().mockImplementationOnce(() => new Promise<FilePreviewPayload>(r => { resolve = r; })).mockResolvedValue(payload);
|
||||
const resource = createFilePreviewResource(fetchPreview);
|
||||
const late = resource.load("old.txt");
|
||||
for (let index = 0; index < 4; index++) await resource.load(`${index}.txt`);
|
||||
resolve(payload);
|
||||
await late;
|
||||
expect(resource.peek("old.txt")).toBeUndefined();
|
||||
fetchPreview.mockResolvedValueOnce({ ...payload, content: "x".repeat(4 * 1024 * 1024 + 1) });
|
||||
await resource.load("huge.txt");
|
||||
expect(resource.peek("huge.txt")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("never shares data between session resources or writes browser storage", async () => {
|
||||
const writes = vi.spyOn(Storage.prototype, "setItem");
|
||||
const first = createFilePreviewResource(vi.fn().mockResolvedValue(payload));
|
||||
const second = createFilePreviewResource(vi.fn().mockResolvedValue({ ...payload, content: "Second session" }));
|
||||
await first.load("notes.txt");
|
||||
expect(second.peek("notes.txt")).toBeUndefined();
|
||||
expect((await second.load("notes.txt"))).toMatchObject({ content: "Second session" });
|
||||
expect(first.peek("notes.txt")).toBe(payload);
|
||||
expect(writes).not.toHaveBeenCalled();
|
||||
writes.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,165 @@
|
||||
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ImageGallery } from "@/components/ImageGallery";
|
||||
import { MessageBubble } from "@/components/MessageBubble";
|
||||
import { FileActionsProvider } from "@/components/FileActions";
|
||||
import { FileReferenceChip } from "@/components/FileReferenceChip";
|
||||
import type { FilePreviewPayload, UIMessage } from "@/lib/types";
|
||||
|
||||
const images = Array.from({ length: 8 }, (_, index) => ({ url: `/api/media/sign/image-${index}`, name: `${index}.png` }));
|
||||
const message: UIMessage = { id: "images", role: "assistant", content: "", createdAt: 1,
|
||||
media: [{ kind: "image", url: "/api/media/sign/chart", name: "chart.png" }] };
|
||||
|
||||
describe("image presentation", () => {
|
||||
it("bounds a large collection to four thumbnails and keeps every image in the viewer", async () => {
|
||||
const user = userEvent.setup();
|
||||
const { container } = render(<ImageGallery images={images} />);
|
||||
expect(container.querySelectorAll("img")).toHaveLength(4);
|
||||
expect(screen.getByText("+4")).toBeVisible();
|
||||
await user.click(screen.getByRole("button", { name: "View all 8 images" }));
|
||||
expect(screen.getByText("4 / 8")).toBeVisible();
|
||||
await user.keyboard("{End}");
|
||||
expect(screen.getByText("8 / 8")).toBeVisible();
|
||||
expect(within(screen.getByRole("dialog")).getByRole("img", { name: "7.png" })).toBeVisible();
|
||||
await user.keyboard("{Escape}");
|
||||
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "View all 8 images" })).toHaveFocus();
|
||||
});
|
||||
|
||||
it("preserves an inline image's position, deduplicates its attachment, and opens the shared viewer", async () => {
|
||||
const user = userEvent.setup();
|
||||
const { container, rerender } = render(<MessageBubble message={{ ...message,
|
||||
content: "Before\n\n\n\nAfter", media: [...message.media!, ...message.media!] }} />);
|
||||
await screen.findByRole("img", { name: "Trend" });
|
||||
await waitFor(() => expect(container.querySelectorAll("img")).toHaveLength(1));
|
||||
expect(container.textContent).toMatch(/Before.*After/s);
|
||||
await user.click(screen.getByRole("button", { name: "View image: Trend" }));
|
||||
expect(await screen.findByRole("button", { name: "Zoom in" })).toBeVisible();
|
||||
await user.keyboard("{Escape}");
|
||||
// Removing inline content must restore the attachment; no global remembered suppression.
|
||||
rerender(<MessageBubble message={{ ...message, content: "File ready" }} />);
|
||||
expect(await screen.findByRole("button", { name: "View image: chart.png" })).toBeVisible();
|
||||
});
|
||||
|
||||
it("does not suppress files referenced in code or links, or different images sharing a name", async () => {
|
||||
const { container } = render(<MessageBubble message={{ ...message,
|
||||
content: "```md\n\n```\n\n[chart.png](/api/media/sign/chart)",
|
||||
media: [...message.media!, { kind: "image", url: "/api/media/other/chart", name: "chart.png" }] }} />);
|
||||
await waitFor(() => expect(container.querySelector("pre")).toBeInTheDocument());
|
||||
expect(container.querySelectorAll("img")).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("keeps the attachment if an image reference is not actually rendered by the streaming renderer", async () => {
|
||||
const { container } = render(<MessageBubble message={{ ...message,
|
||||
content: "![Trend][chart]\n\n[chart]: /api/media/sign/chart" }} />);
|
||||
await screen.findByText("![Trend][chart]");
|
||||
expect(screen.getByRole("button", { name: "View image: chart.png" })).toBeVisible();
|
||||
await waitFor(() => expect(container.querySelectorAll("img")).toHaveLength(1));
|
||||
});
|
||||
|
||||
it("keeps unavailable images readable, and never hides a valid image behind missing placeholders", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<ImageGallery images={[...Array.from({ length: 4 }, () => ({ name: "old.png" })), images[0]]} />);
|
||||
await user.click(screen.getByRole("button", { name: "View all 5 images" }));
|
||||
expect(within(screen.getByRole("dialog")).getByRole("img", { name: "0.png" })).toBeVisible();
|
||||
});
|
||||
|
||||
it("replaces a broken thumbnail with a quiet named placeholder", () => {
|
||||
render(<ImageGallery images={[images[0]]} />);
|
||||
fireEvent.error(screen.getByRole("img"));
|
||||
expect(screen.queryByRole("img")).not.toBeInTheDocument();
|
||||
expect(screen.getByText("0.png")).toBeVisible();
|
||||
expect(screen.queryByRole("button")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe("file quick look", () => {
|
||||
const preview: FilePreviewPayload = { kind: "image", path: "chart.png", display_path: "chart.png",
|
||||
project_path: "/workspace", size: 100, mime_type: "image/png", data_url: "data:image/png;base64,dGVzdA==" };
|
||||
it("loads only on deliberate hover/focus, keeps click as preview, and releases content on dismissal", async () => {
|
||||
const user = userEvent.setup();
|
||||
const loadPreview = vi.fn().mockResolvedValue(preview);
|
||||
const onOpen = vi.fn();
|
||||
const { container } = render(<FileActionsProvider value={{ resolveMetadata: vi.fn(), loadPreview }}>
|
||||
<FileReferenceChip path="chart.png" onOpen={onOpen} />
|
||||
</FileActionsProvider>);
|
||||
expect(loadPreview).not.toHaveBeenCalled();
|
||||
await user.hover(screen.getByRole("button", { name: "chart.png" }));
|
||||
expect(loadPreview).not.toHaveBeenCalled();
|
||||
await screen.findByRole("tooltip");
|
||||
await waitFor(() => expect(loadPreview).toHaveBeenCalledWith("chart.png"));
|
||||
const quickLook = screen.getByTestId("file-image-quick-look");
|
||||
expect(quickLook.textContent).toBe("");
|
||||
expect(quickLook).toHaveClass("w-max");
|
||||
expect(quickLook).not.toHaveClass("h-36", "w-full");
|
||||
expect(quickLook.querySelector("img")).toHaveClass("rounded-mark", "object-contain");
|
||||
expect(quickLook.querySelector("img")).toHaveClass("h-auto", "w-auto", "max-h-36");
|
||||
expect(screen.getByRole("tooltip")).toHaveTextContent("File preview");
|
||||
await user.click(screen.getByRole("button", { name: "chart.png" }));
|
||||
expect(onOpen).toHaveBeenCalledWith("chart.png");
|
||||
await waitFor(() => expect(screen.queryByRole("tooltip")).not.toBeInTheDocument());
|
||||
expect(container.querySelector("img")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does not show a late image from a previous session, and shows a quiet failure instead of an empty popup", async () => {
|
||||
let resolveOld!: (payload: FilePreviewPayload) => void;
|
||||
const oldLoader = vi.fn(() => new Promise<FilePreviewPayload>((resolve) => { resolveOld = resolve; }));
|
||||
const newLoader = vi.fn().mockRejectedValue(new Error("404"));
|
||||
const view = (loadPreview: typeof oldLoader) => <FileActionsProvider value={{ resolveMetadata: vi.fn(), loadPreview }}>
|
||||
<FileReferenceChip path="chart.png" onOpen={vi.fn()} />
|
||||
</FileActionsProvider>;
|
||||
const { rerender } = render(view(oldLoader));
|
||||
fireEvent.focus(screen.getByRole("button", { name: "chart.png" }));
|
||||
await waitFor(() => expect(oldLoader).toHaveBeenCalled());
|
||||
rerender(view(newLoader));
|
||||
await act(async () => resolveOld(preview));
|
||||
expect(document.querySelector('img[src^="data:image"]')).not.toBeInTheDocument();
|
||||
expect(screen.getByText("Could not preview this file.")).toBeVisible();
|
||||
expect(screen.getByRole("button", { name: "chart.png" })).toBeVisible();
|
||||
});
|
||||
|
||||
it("keeps long image paths out of the quick look while preserving the real preview target", async () => {
|
||||
const user = userEvent.setup();
|
||||
const filename = "a-long-descriptive-filename-for-a-generated-project-overview.png";
|
||||
const path = `/workspace/projects/weekly-reports/exported-charts/${filename}`;
|
||||
const loadPreview = vi.fn().mockResolvedValue(preview);
|
||||
const onOpen = vi.fn();
|
||||
render(<FileActionsProvider value={{ resolveMetadata: vi.fn(), loadPreview }}>
|
||||
<FileReferenceChip path="Project overview" tooltipPath={path} previewPath={path} onOpen={onOpen} />
|
||||
</FileActionsProvider>);
|
||||
fireEvent.focus(screen.getByRole("button", { name: path }));
|
||||
const tooltip = await screen.findByRole("tooltip");
|
||||
expect(tooltip).not.toHaveTextContent(filename);
|
||||
expect(tooltip).not.toHaveTextContent("/workspace/");
|
||||
await waitFor(() => expect(loadPreview).toHaveBeenCalledWith(path));
|
||||
expect(screen.getByTestId("file-image-quick-look").textContent).toBe("");
|
||||
await user.click(screen.getByRole("button", { name: path }));
|
||||
expect(onOpen).toHaveBeenCalledWith(path);
|
||||
});
|
||||
|
||||
it("replaces a broken preview image with a readable failure without repeating the filename", async () => {
|
||||
const loadPreview = vi.fn().mockResolvedValue(preview);
|
||||
render(<FileActionsProvider value={{ resolveMetadata: vi.fn(), loadPreview }}>
|
||||
<FileReferenceChip path="chart.png" onOpen={vi.fn()} />
|
||||
</FileActionsProvider>);
|
||||
fireEvent.focus(screen.getByRole("button", { name: "chart.png" }));
|
||||
await waitFor(() => expect(document.querySelector('img[src^="data:image"]')).toBeInTheDocument());
|
||||
fireEvent.error(screen.getByTestId("file-image-quick-look").querySelector("img")!);
|
||||
expect(screen.queryByTestId("file-image-quick-look")).not.toBeInTheDocument();
|
||||
expect(screen.getByText("Could not preview this file.")).toBeVisible();
|
||||
expect(screen.getAllByText("chart.png")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("retains the full path tooltip for non-image file references without fetching an image", async () => {
|
||||
const path = "/workspace/projects/reports/data.json";
|
||||
const loadPreview = vi.fn();
|
||||
render(<FileActionsProvider value={{ resolveMetadata: vi.fn(), loadPreview }}>
|
||||
<FileReferenceChip path="data.json" tooltipPath={path} onOpen={vi.fn()} />
|
||||
</FileActionsProvider>);
|
||||
fireEvent.focus(screen.getByRole("button", { name: path }));
|
||||
expect(await screen.findByRole("tooltip")).toHaveTextContent(path);
|
||||
expect(loadPreview).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
import { fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ImageLightbox } from "@/components/ImageLightbox";
|
||||
import { ZoomableImage } from "@/components/ZoomableImage";
|
||||
|
||||
function renderImage() {
|
||||
const result = render(<ZoomableImage src="data:image/png;base64,test" alt="Test chart" />);
|
||||
const viewport = screen.getByTestId("image-zoom-viewport");
|
||||
const image = screen.getByRole("img", { name: "Test chart" });
|
||||
Object.defineProperties(viewport, { clientWidth: { value: 800 }, clientHeight: { value: 600 } });
|
||||
Object.defineProperties(image, { offsetWidth: { value: 800 }, offsetHeight: { value: 600 } });
|
||||
viewport.getBoundingClientRect = () => new DOMRect(0, 0, 800, 600);
|
||||
return { ...result, viewport, image };
|
||||
}
|
||||
|
||||
function wheel(target: Element, deltaY: number, ctrlKey = true) {
|
||||
const event = new WheelEvent("wheel", { deltaY, bubbles: true, cancelable: true });
|
||||
// happy-dom 16's WheelEvent extends UIEvent instead of MouseEvent and drops these fields.
|
||||
Object.defineProperties(event, { ctrlKey: { value: ctrlKey }, clientX: { value: 400 }, clientY: { value: 300 } });
|
||||
return fireEvent(target, event);
|
||||
}
|
||||
|
||||
describe("image zoom", () => {
|
||||
it("pinches around the two-finger midpoint, then drags with the remaining finger", () => {
|
||||
const { viewport, image } = renderImage();
|
||||
fireEvent.pointerDown(viewport, { pointerId: 1, pointerType: "touch", button: 0, clientX: 300, clientY: 300 });
|
||||
fireEvent.pointerDown(viewport, { pointerId: 2, pointerType: "touch", button: 0, clientX: 500, clientY: 300 });
|
||||
fireEvent.pointerMove(viewport, { pointerId: 2, pointerType: "touch", clientX: 700, clientY: 300 });
|
||||
expect(image.style.transform).toBe("translate3d(100px, 0px, 0) scale(2)");
|
||||
fireEvent.pointerUp(viewport, { pointerId: 2, pointerType: "touch" });
|
||||
fireEvent.pointerMove(viewport, { pointerId: 1, pointerType: "touch", clientX: 400, clientY: 300 });
|
||||
expect(image.style.transform).toBe("translate3d(200px, 0px, 0) scale(2)");
|
||||
fireEvent.pointerMove(viewport, { pointerId: 1, pointerType: "touch", clientX: 9000, clientY: 9000 });
|
||||
expect(image.style.transform).toBe("translate3d(400px, 300px, 0) scale(2)");
|
||||
fireEvent.pointerCancel(viewport, { pointerId: 1 });
|
||||
fireEvent.pointerMove(viewport, { pointerId: 1, clientX: 300, clientY: 300 });
|
||||
expect(image.style.transform).toBe("translate3d(400px, 300px, 0) scale(2)");
|
||||
expect(viewport.className).not.toContain("cursor-grabbing");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Fit image" }));
|
||||
expect(image.style.transform).toBe("translate3d(0px, 0px, 0) scale(1)");
|
||||
});
|
||||
|
||||
it("supports trackpad pinch without hijacking browser zoom outside the image", () => {
|
||||
const { viewport, image } = renderImage();
|
||||
expect(wheel(viewport, 20, false)).toBe(true);
|
||||
expect(wheel(viewport, -50)).toBe(false);
|
||||
expect(image.style.transform).toContain(`scale(${Math.exp(0.5)})`);
|
||||
expect(wheel(document.body, -50)).toBe(true);
|
||||
expect(wheel(viewport, 20, false)).toBe(false);
|
||||
expect(image.style.transform).toContain("-20px");
|
||||
for (let i = 0; i < 10; i++) wheel(viewport, -50);
|
||||
expect(image.style.transform).toContain("scale(8)");
|
||||
expect(screen.getByRole("button", { name: "Zoom in" })).toBeDisabled();
|
||||
for (let i = 0; i < 10; i++) wheel(viewport, 50);
|
||||
expect(image.style.transform).toBe("translate3d(0px, 0px, 0) scale(1)");
|
||||
expect(screen.getByRole("button", { name: "Zoom out" })).toBeDisabled();
|
||||
});
|
||||
|
||||
it("supports double-click, keyboard and visible controls", () => {
|
||||
const { viewport, image } = renderImage();
|
||||
fireEvent.doubleClick(viewport, { clientX: 400, clientY: 300 });
|
||||
expect(image.style.transform).toContain("scale(2)");
|
||||
fireEvent.doubleClick(viewport, { clientX: 400, clientY: 300 });
|
||||
expect(image.style.transform).toContain("scale(1)");
|
||||
fireEvent.keyDown(viewport, { key: "+" });
|
||||
expect(screen.getByRole("button", { name: "Fit image" })).toHaveTextContent("150%");
|
||||
fireEvent.keyDown(viewport, { key: "0" });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Zoom in" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Zoom out" }));
|
||||
expect(image.style.transform).toContain("scale(1)");
|
||||
});
|
||||
|
||||
it("resets zoom when switching images and reopening the lightbox", () => {
|
||||
const images = [{ url: "data:image/png;base64,a", name: "A" }, { url: "data:image/png;base64,b", name: "B" }];
|
||||
const view = (index: number | null) => <ImageLightbox images={images} index={index} onIndexChange={() => {}} onOpenChange={() => {}} />;
|
||||
const { rerender } = render(view(0));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Zoom in" }));
|
||||
expect(screen.getByRole("button", { name: "Fit image" })).toHaveTextContent("150%");
|
||||
rerender(view(1));
|
||||
expect(within(screen.getByRole("dialog")).getByRole("img", { name: "B" }).style.transform).toContain("scale(1)");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Zoom in" }));
|
||||
rerender(view(null));
|
||||
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
||||
rerender(view(1));
|
||||
expect(screen.getByRole("button", { name: "Fit image" })).toHaveTextContent("100%");
|
||||
});
|
||||
});
|
||||
@@ -265,10 +265,7 @@ describe("MarkdownTextRenderer", () => {
|
||||
|
||||
const image = screen.getByRole("img", { name: "Diagram" });
|
||||
expect(image).toHaveAttribute("src", "/api/media/sig/payload");
|
||||
expect(screen.getByRole("link", { name: "Open Diagram" })).toHaveAttribute(
|
||||
"href",
|
||||
"/api/media/sig/payload",
|
||||
);
|
||||
expect(screen.getByRole("button", { name: "View image: Diagram" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders markdown videos as inline players", () => {
|
||||
@@ -378,10 +375,7 @@ describe("MarkdownTextRenderer", () => {
|
||||
"src",
|
||||
"/api/media/sig/payload",
|
||||
);
|
||||
expect(screen.getByRole("link", { name: "Open Diagram" })).toHaveAttribute(
|
||||
"href",
|
||||
"/api/media/sig/payload",
|
||||
);
|
||||
expect(screen.getByRole("button", { name: "View image: Diagram" })).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Code" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
|
||||
@@ -1158,7 +1158,7 @@ describe("MessageBubble", () => {
|
||||
const { container } = render(<MessageBubble message={message} />);
|
||||
|
||||
const imageButton = screen.getByRole("button", { name: /view image/i });
|
||||
expect(imageButton).toHaveClass("w-[min(100%,34rem)]", "rounded-panel");
|
||||
expect(imageButton).toHaveClass("w-[min(100%,28rem)]", "rounded-control");
|
||||
expect(imageButton).toHaveClass(
|
||||
"border",
|
||||
"border-border/60",
|
||||
|
||||
@@ -108,6 +108,18 @@ function BspWorkbenchHarness() {
|
||||
}
|
||||
|
||||
describe("PaneWorkbench", () => {
|
||||
it("keeps a single conversation's header inside that pane instead of above its previews", () => {
|
||||
render(<PaneWorkbench panes={[{ key: "alpha", title: "Alpha" }]} activePaneKey="alpha"
|
||||
layout="columns" chrome showLayoutControl={false} onActivatePane={vi.fn()} onAddPane={vi.fn()}
|
||||
onLayoutChange={vi.fn()} onPaneOrderChange={vi.fn()}
|
||||
renderPane={(_pane, context) => {
|
||||
expect(context.headerPortalTarget).toBeUndefined();
|
||||
return <div data-testid="local-toolbar">{context.headerActions}</div>;
|
||||
}} />);
|
||||
expect(screen.getByTestId("workbench-header-host")).toBeEmptyDOMElement();
|
||||
expect(within(screen.getByTestId("local-toolbar")).getByRole("button", { name: "Add pane" })).toBeVisible();
|
||||
});
|
||||
|
||||
const originalGetBoundingClientRect = HTMLElement.prototype.getBoundingClientRect;
|
||||
const originalAnimate = HTMLElement.prototype.animate;
|
||||
const animate = vi.fn(() => ({
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { PreviewPane } from "@/components/PreviewPane";
|
||||
import { FilePreviewStore, useFilePreviewState } from "@/hooks/useFilePreviewState";
|
||||
|
||||
describe("preview tabs", () => {
|
||||
it("deduplicates targets, keeps selection and width per session, and closes neighboring tabs", () => {
|
||||
const store = new FilePreviewStore();
|
||||
const storage = vi.spyOn(Storage.prototype, "setItem");
|
||||
store.open("a", "file", "chart.png");
|
||||
store.open("a", "file", "index.html");
|
||||
store.open("a", "file", "data.json");
|
||||
store.update("a", { width: 620 });
|
||||
store.open("a", "file", "index.html");
|
||||
expect(store.get("a").tabs).toHaveLength(3);
|
||||
expect(store.get("a").activeId).toBe("file:index.html");
|
||||
store.closeTab("a", "file:chart.png");
|
||||
expect(store.get("a").activeId).toBe("file:index.html");
|
||||
store.closeTab("a", "file:index.html");
|
||||
expect(store.get("a").activeId).toBe("file:data.json");
|
||||
store.select("a", "missing");
|
||||
store.closeTab("a", "missing");
|
||||
expect(store.get("a").activeId).toBe("file:data.json");
|
||||
store.open("b", "web", "https://example.com");
|
||||
expect(store.get("a").width).toBe(620);
|
||||
store.closeTab("a", "file:data.json");
|
||||
expect(store.get("a")).toMatchObject({ tabs: [], activeId: null, width: 620 });
|
||||
expect(store.get("b").tabs).toHaveLength(1);
|
||||
store.open("a", "file", "chart.png");
|
||||
store.close("a");
|
||||
expect(store.get("a")).toMatchObject({ tabs: [], activeId: null, width: 620 });
|
||||
store.delete("b");
|
||||
store.clear();
|
||||
expect(store.get("a").tabs).toEqual([]);
|
||||
expect(store.get("b").tabs).toEqual([]);
|
||||
expect(storage).not.toHaveBeenCalled();
|
||||
storage.mockRestore();
|
||||
});
|
||||
|
||||
it("keeps one shell, supports keyboard tabs and close buttons, and never reloads the same tab", async () => {
|
||||
const store = new FilePreviewStore();
|
||||
store.open("a", "file", "chart.png");
|
||||
store.open("a", "file", "index.html");
|
||||
store.open("a", "file", "data.json");
|
||||
function View() {
|
||||
const { state, selectTab, closeTab, close } = useFilePreviewState("a", store);
|
||||
return state.activeId ? <PreviewPane tabs={state.tabs} activeId={state.activeId} width={544}
|
||||
isClosing={false} onSelect={selectTab} onCloseTab={closeTab} onClose={close} onResizeStart={() => {}}>
|
||||
<p>{state.activeId}</p>
|
||||
</PreviewPane> : null;
|
||||
}
|
||||
render(<View />);
|
||||
const shell = screen.getByTestId("preview-pane");
|
||||
const highlight = screen.getByTestId("preview-tabs-selection-highlight");
|
||||
expect(highlight).toHaveAttribute("data-active-id", "file:data.json");
|
||||
expect(highlight.className).toContain("bg-sidebar-foreground/[0.055]");
|
||||
expect(highlight.className).toContain("motion-reduce:transition-none");
|
||||
await waitFor(() => expect(shell.style.getPropertyValue("--file-preview-slot-width")).toBe("544px"));
|
||||
fireEvent.click(screen.getByRole("tab", { name: "chart.png" }));
|
||||
expect(screen.getByTestId("preview-pane")).toBe(shell);
|
||||
expect(screen.getByTestId("preview-tabs-selection-highlight")).toBe(highlight);
|
||||
expect(highlight).toHaveAttribute("data-active-id", "file:chart.png");
|
||||
expect(shell.style.getPropertyValue("--file-preview-slot-width")).toBe("544px");
|
||||
expect(screen.getByRole("tabpanel")).toHaveTextContent("file:chart.png");
|
||||
fireEvent.keyDown(screen.getByRole("tab", { name: "chart.png" }), { key: "ArrowRight" });
|
||||
expect(screen.getByRole("tab", { name: "index.html" })).toHaveFocus();
|
||||
expect(screen.getByRole("tab", { name: "index.html" })).toHaveAttribute("aria-selected", "true");
|
||||
act(() => store.open("a", "file", "index.html"));
|
||||
expect(screen.getAllByRole("tab")).toHaveLength(3);
|
||||
fireEvent.keyDown(screen.getByRole("tab", { name: "index.html" }), { key: "Delete" });
|
||||
expect(screen.queryByRole("tab", { name: "index.html" })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("tab", { name: "data.json" })).toHaveFocus();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Close chart.png" }));
|
||||
expect(screen.getByRole("tab", { name: "data.json" })).toHaveAttribute("aria-selected", "true");
|
||||
expect(screen.queryByRole("button", { name: "Close preview pane" })).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Close data.json" }));
|
||||
expect(screen.queryByTestId("preview-pane")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("reveals the whole active tab including its close button after the tab strip resizes", () => {
|
||||
let resize: (() => void) | undefined;
|
||||
const observe = vi.fn();
|
||||
const disconnect = vi.fn();
|
||||
vi.stubGlobal("ResizeObserver", class {
|
||||
constructor(callback: () => void) { resize = callback; }
|
||||
observe = observe;
|
||||
disconnect = disconnect;
|
||||
});
|
||||
try {
|
||||
const tab = { id: "file:chart.png", kind: "file" as const, value: "chart.png" };
|
||||
const view = render(<PreviewPane tabs={[tab]} activeId={tab.id} width={544} isClosing={false}
|
||||
onSelect={() => {}} onCloseTab={() => {}} onClose={() => {}} onResizeStart={() => {}}>
|
||||
<p>Preview</p>
|
||||
</PreviewPane>);
|
||||
const wholeTab = screen.getByRole("tab", { name: "chart.png" }).parentElement!;
|
||||
const reveal = vi.fn();
|
||||
wholeTab.scrollIntoView = reveal;
|
||||
expect(wholeTab).toContainElement(screen.getByRole("button", { name: "Close chart.png" }));
|
||||
expect(observe).toHaveBeenCalledWith(screen.getByRole("tablist"));
|
||||
act(() => resize?.());
|
||||
expect(reveal).toHaveBeenCalledWith({ block: "nearest", inline: "nearest" });
|
||||
view.unmount();
|
||||
expect(disconnect).toHaveBeenCalled();
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -174,18 +174,50 @@ describe("temporary chat navigation", () => {
|
||||
} else {
|
||||
expect(vi.mocked(fetch).mock.calls.some(([url]) => String(url).includes("path=notes.txt&metadata=1"))).toBe(true);
|
||||
}
|
||||
fireEvent.click(screen.getByRole("menuitem", { name: "Preview" }));
|
||||
fireEvent.keyDown(screen.getByRole("menu"), { key: "Escape" });
|
||||
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
|
||||
fireEvent.click(screen.getByRole("button", { name: "notes.txt" }));
|
||||
await screen.findByText("Preview of notes.txt");
|
||||
fireEvent.click(screen.getByRole("button", { name: "second.txt" }));
|
||||
await screen.findByText("Preview of second.txt");
|
||||
const pane = screen.getByTestId("preview-pane");
|
||||
expect(within(pane).getAllByText("second.txt")).toHaveLength(1);
|
||||
expect(within(pane).queryByRole("navigation", { name: "File path" })).not.toBeInTheDocument();
|
||||
expect(within(pane).queryByRole("button", { name: /File actions/ })).not.toBeInTheDocument();
|
||||
fireEvent.contextMenu(within(pane).getByRole("tab", { name: "second.txt" }));
|
||||
await waitFor(() => expect(screen.getByRole("menuitem", { name: "Copy absolute path" })).not.toHaveAttribute("data-disabled"));
|
||||
if (temporary) {
|
||||
expect(TestSocket.current.sent).toContainEqual(expect.objectContaining({
|
||||
type: "webui_request", action: "temporary_chat.file_preview",
|
||||
payload: expect.objectContaining({ path: "second.txt", metadata: true }),
|
||||
}));
|
||||
} else {
|
||||
expect(vi.mocked(fetch).mock.calls.some(([url]) => String(url).includes("path=second.txt&metadata=1"))).toBe(true);
|
||||
}
|
||||
fireEvent.keyDown(screen.getByRole("menu"), { key: "Escape" });
|
||||
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
|
||||
expect(screen.getByTestId("preview-pane")).toBe(pane);
|
||||
const previewRequestCount = () => temporary
|
||||
? TestSocket.current.sent.filter((frame) => frame.type === "webui_request" && frame.action === "temporary_chat.file_preview"
|
||||
&& frame.payload?.path === "notes.txt" && !frame.payload?.metadata && !frame.payload?.probe).length
|
||||
: vi.mocked(fetch).mock.calls.filter(([url]) => String(url).includes("/file-preview?path=notes.txt")
|
||||
&& !String(url).includes("metadata=") && !String(url).includes("probe=")).length;
|
||||
const beforeReturn = previewRequestCount();
|
||||
fireEvent.click(screen.getByRole("tab", { name: "notes.txt" }));
|
||||
expect(screen.getByText("Preview of notes.txt")).toBeInTheDocument();
|
||||
expect(previewRequestCount()).toBe(beforeReturn);
|
||||
await selectTopic("Second pane");
|
||||
expect(screen.queryByTestId("file-preview-panel")).not.toBeInTheDocument();
|
||||
fireEvent.click(await screen.findByRole("button", { name: "second.txt" }));
|
||||
await screen.findByText("Preview of second.txt");
|
||||
await selectTopic(temporary ? "Show example files" : "Regular topic");
|
||||
await screen.findByText("Preview of notes.txt");
|
||||
expect(screen.getAllByRole("tab")).toHaveLength(2);
|
||||
expect(screen.getByRole("tab", { name: "notes.txt" })).toHaveAttribute("aria-selected", "true");
|
||||
expect(screen.queryByText("Preview of second.txt")).not.toBeInTheDocument();
|
||||
|
||||
// Explicit close must stick even if switching interrupts the close animation.
|
||||
fireEvent.click(screen.getByRole("button", { name: "Close file preview" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Close preview pane" }));
|
||||
await selectTopic("Second pane");
|
||||
await selectTopic(temporary ? "Show example files" : "Regular topic");
|
||||
expect(screen.queryByTestId("file-preview-panel")).not.toBeInTheDocument();
|
||||
@@ -212,7 +244,7 @@ describe("temporary chat navigation", () => {
|
||||
fireEvent.click(await screen.findByRole("menuitem", { name: "Preview website" }));
|
||||
await screen.findByTestId("web-preview-panel");
|
||||
await selectTopic("Synthetic separate session");
|
||||
expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument();
|
||||
await waitFor(() => expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument());
|
||||
await selectTopic("Regular topic");
|
||||
await screen.findByTestId("web-preview-panel");
|
||||
fireEvent.contextMenu(screen.getByRole("link", { name: "Website" }));
|
||||
@@ -221,24 +253,24 @@ describe("temporary chat navigation", () => {
|
||||
expect(screen.getByTestId("web-preview-panel")).toBeInTheDocument();
|
||||
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
|
||||
fireEvent.keyDown(window, { key: "Escape" });
|
||||
expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument();
|
||||
await waitFor(() => expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument());
|
||||
fireEvent.contextMenu(screen.getByRole("link", { name: "Website" }));
|
||||
fireEvent.click(await screen.findByRole("menuitem", { name: "Preview website" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "notes.txt" }));
|
||||
expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument();
|
||||
await waitFor(() => expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument());
|
||||
await screen.findByText("Preview of notes.txt");
|
||||
fireEvent.contextMenu(screen.getByRole("link", { name: "Website" }));
|
||||
fireEvent.click(await screen.findByRole("menuitem", { name: "Preview website" }));
|
||||
expect(screen.queryByTestId("file-preview-panel")).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Close website preview" }));
|
||||
expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Close preview pane" }));
|
||||
await waitFor(() => expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument());
|
||||
for (const storage of [localStorage, sessionStorage]) {
|
||||
const values = Array.from({ length: storage.length }, (_, i) => storage.getItem(storage.key(i)!));
|
||||
expect(JSON.stringify(values)).not.toContain("https://example.com/demo");
|
||||
}
|
||||
});
|
||||
|
||||
it("toggles the current file, switches files, and only handles Escape below dialogs", async () => {
|
||||
it("keeps the sidebar mounted across tabs, deduplicates repeated opens, and handles Escape below dialogs", async () => {
|
||||
withFiles = true;
|
||||
render(<App />);
|
||||
await screen.findByRole("button", { name: "Temporary chat" });
|
||||
@@ -248,8 +280,15 @@ describe("temporary chat navigation", () => {
|
||||
await screen.findByText("Preview of notes.txt");
|
||||
fireEvent.click(screen.getByRole("button", { name: "second.txt" }));
|
||||
await screen.findByText("Preview of second.txt");
|
||||
const pane = screen.getByTestId("preview-pane");
|
||||
fireEvent.click(screen.getByRole("button", { name: "second.txt" }));
|
||||
await waitFor(() => expect(screen.queryByTestId("file-preview-panel")).not.toBeInTheDocument());
|
||||
expect(screen.getByTestId("preview-pane")).toBe(pane);
|
||||
expect(screen.getAllByRole("tab")).toHaveLength(2);
|
||||
expect(screen.getByRole("tab", { name: "second.txt" })).toHaveAttribute("aria-selected", "true");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Close second.txt" }));
|
||||
await screen.findByText("Preview of notes.txt");
|
||||
expect(screen.getByTestId("preview-pane")).toBe(pane);
|
||||
expect(screen.getAllByRole("tab")).toHaveLength(1);
|
||||
fireEvent.click(screen.getByRole("button", { name: "notes.txt" }));
|
||||
await screen.findByText("Preview of notes.txt");
|
||||
const dialog = document.createElement("div");
|
||||
@@ -263,7 +302,7 @@ describe("temporary chat navigation", () => {
|
||||
});
|
||||
|
||||
it("forgets preview paths on temporary close and disconnect", async () => {
|
||||
const update = vi.spyOn(FilePreviewStore.prototype, "update");
|
||||
const update = vi.spyOn(FilePreviewStore.prototype, "open");
|
||||
render(<App />);
|
||||
await screen.findByRole("button", { name: "Temporary chat" });
|
||||
act(() => TestSocket.current.open());
|
||||
@@ -273,14 +312,14 @@ describe("temporary chat navigation", () => {
|
||||
}));
|
||||
fireEvent.click(await screen.findByRole("button", { name: "notes.txt" }));
|
||||
await screen.findByText("Preview of notes.txt");
|
||||
const store = update.mock.contexts.find((value) => value.get(`websocket:${chatId}`).path)!;
|
||||
expect(store.get(`websocket:${chatId}`).path).toBe("notes.txt");
|
||||
const store = update.mock.contexts.find((value) => value.get(`websocket:${chatId}`).tabs.length)!;
|
||||
expect(store.get(`websocket:${chatId}`).activeId).toBe("file:notes.txt");
|
||||
await selectTopic("Close temporary chat: Show example files");
|
||||
expect(store.get(`websocket:${chatId}`).path).toBeNull();
|
||||
act(() => store.update("websocket:regular", { path: "notes.txt" }));
|
||||
expect(store.get(`websocket:${chatId}`).tabs).toEqual([]);
|
||||
act(() => store.open("websocket:regular", "file", "notes.txt"));
|
||||
vi.useFakeTimers();
|
||||
act(() => TestSocket.current.close());
|
||||
expect(store.get("websocket:regular").path).toBeNull();
|
||||
expect(store.get("websocket:regular").tabs).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps messages when navigating to a regular workbench and back", async () => {
|
||||
|
||||
@@ -40,8 +40,7 @@ describe("web preview boundaries", () => {
|
||||
expect(webPreviewRestriction(external, page, false, true)).toBeNull();
|
||||
});
|
||||
it("embeds only on mount, without credentials/referrer/host permissions, and refreshes with a new frame", async () => {
|
||||
const close = vi.fn();
|
||||
const { container } = render(<WebPreviewPanel url="https://example.com/demo" onClose={close} />);
|
||||
const { container } = render(<WebPreviewPanel url="https://example.com/demo" />);
|
||||
const frame = container.querySelector("iframe")!;
|
||||
expect(frame).toHaveAttribute("src", "https://example.com/demo");
|
||||
expect(frame).toHaveAttribute("sandbox", "allow-scripts");
|
||||
@@ -50,27 +49,29 @@ describe("web preview boundaries", () => {
|
||||
expect(frame.getAttribute("allow")).toContain("clipboard-read 'none'");
|
||||
// A frame load event is not evidence that CSP/X-Frame-Options allowed embedding.
|
||||
fireEvent.load(frame);
|
||||
expect(screen.getByText(/Some sites block embedding/)).toBeInTheDocument();
|
||||
expect(screen.queryByText(/Some sites block embedding/)).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "About website previews" }));
|
||||
expect(await screen.findByText(/Some sites block embedding/)).toBeInTheDocument();
|
||||
await userEvent.setup().keyboard("{Escape}");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Refresh website" }));
|
||||
expect(container.querySelector("iframe")).not.toBe(frame);
|
||||
expect(screen.getByRole("link", { name: "Open in browser" })).toHaveAttribute("rel", "noreferrer noopener");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Close website preview" }));
|
||||
expect(close).toHaveBeenCalledOnce();
|
||||
});
|
||||
it("does not load an iframe in native or unsupported browsers", () => {
|
||||
vi.mocked(isNativeRuntime).mockReturnValue(true);
|
||||
const { container, rerender } = render(<WebPreviewPanel url="https://example.com" onClose={() => {}} />);
|
||||
const { container, rerender } = render(<WebPreviewPanel url="https://example.com" />);
|
||||
expect(container.querySelector("iframe")).toBeNull();
|
||||
expect(screen.getByRole("status")).toHaveTextContent(/native host/);
|
||||
vi.mocked(isNativeRuntime).mockReturnValue(false);
|
||||
Reflect.deleteProperty(HTMLIFrameElement.prototype, "credentialless");
|
||||
rerender(<WebPreviewPanel url="https://example.com" onClose={() => {}} />);
|
||||
rerender(<WebPreviewPanel url="https://example.com" />);
|
||||
expect(container.querySelector("iframe")).toBeNull();
|
||||
expect(screen.getByRole("status")).toHaveTextContent(/does not support/);
|
||||
});
|
||||
it("explains that loopback belongs to the browsing device", () => {
|
||||
render(<WebPreviewPanel url="http://127.0.0.1:4173" onClose={() => {}} />);
|
||||
expect(screen.getByText(/not a remote gateway/)).toBeInTheDocument();
|
||||
it("explains that loopback belongs to the browsing device on request", async () => {
|
||||
render(<WebPreviewPanel url="http://127.0.0.1:4173" />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "About website previews" }));
|
||||
expect(await screen.findByText(/not a remote gateway/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -105,12 +106,12 @@ describe("web link actions", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps mutually exclusive preview targets per session, clears them on deletion, and never persists URLs", () => {
|
||||
it("keeps file and website tabs per session, clears them on deletion, and never persists URLs", () => {
|
||||
const store = new FilePreviewStore();
|
||||
const local = vi.spyOn(Storage.prototype, "setItem");
|
||||
function View({ session }: { session: string }) {
|
||||
const { state, setWebUrl, setPath } = useFilePreviewState(session, store);
|
||||
return <><output>{state.webUrl ?? state.path ?? "closed"}</output><button onClick={() => setWebUrl("https://example.com/preview")}>Web</button><button onClick={() => setPath("notes.txt")}>File</button></>;
|
||||
const { state, openWeb, openFile } = useFilePreviewState(session, store);
|
||||
return <><output>{state.tabs.find((tab) => tab.id === state.activeId)?.value ?? "closed"}</output><button onClick={() => openWeb("https://example.com/preview")}>Web</button><button onClick={() => openFile("notes.txt")}>File</button></>;
|
||||
}
|
||||
const { rerender } = render(<View session="a" />);
|
||||
fireEvent.click(screen.getByText("Web"));
|
||||
@@ -120,12 +121,14 @@ it("keeps mutually exclusive preview targets per session, clears them on deletio
|
||||
rerender(<View session="a" />);
|
||||
expect(screen.getByRole("status")).toHaveTextContent("https://example.com/preview");
|
||||
fireEvent.click(screen.getByText("File"));
|
||||
expect(store.get("a")).toMatchObject({ path: "notes.txt", webUrl: null });
|
||||
expect(store.get("a").activeId).toBe("file:notes.txt");
|
||||
expect(store.get("a").tabs).toHaveLength(2);
|
||||
fireEvent.click(screen.getByText("Web"));
|
||||
expect(store.get("a").path).toBeNull();
|
||||
expect(store.get("a").activeId).toBe("web:https://example.com/preview");
|
||||
expect(store.get("a").tabs).toHaveLength(2);
|
||||
act(() => store.delete("a"));
|
||||
expect(screen.getByRole("status")).toHaveTextContent("closed");
|
||||
act(() => store.clear());
|
||||
expect(store.get("b").path).toBeNull();
|
||||
expect(store.get("b").tabs).toEqual([]);
|
||||
expect(local).not.toHaveBeenCalled();
|
||||
});
|
||||
Reference in new issue
Block a user