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
@@ -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,
|
||||
})}
|
||||
|
||||
Reference in new issue
Block a user